@tencent-ai/codebuddy-code 2.66.2-next.fd006f5.20260328 → 2.67.0-next.60e78dc.20260329
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +24 -0
- package/dist/codebuddy-headless.js +73 -71
- package/dist/codebuddy.js +90 -59
- package/dist/web-ui/assets/{index-BPT-qRRx.js → index-CgzucIuo.js} +6 -6
- package/dist/web-ui/index.html +1 -1
- package/package.json +1 -1
- package/product.cloudhosted.json +2 -2
- package/product.internal.json +2 -2
- package/product.ioa.json +2 -2
- package/product.json +2 -2
- package/product.selfhosted.json +2 -2
|
@@ -5,7 +5,7 @@ var fd=Object.defineProperty;var md=(e,t,r)=>t in e?fd(e,t,{enumerable:!0,config
|
|
|
5
5
|
`);let y="";for(const c of w)c.startsWith("data: ")&&(y+=c.substring(6));if(y)try{const c=JSON.parse(y);this.handleMessage(c)}catch{}}const _=this.pendingRequests.get(i);_&&(this.pendingRequests.delete(i),this.cancelling&&t==="session/prompt"?(this.cancelling=!1,_.resolve({stopReason:"cancelled"})):_.reject(new Error(`No response received for request: ${t}`)))},o.onerror=()=>{const _=this.pendingRequests.get(i);_&&(this.pendingRequests.delete(i),_.reject(new Error(`Network error during ACP request: ${t}`)))},o.ontimeout=()=>{const _=this.pendingRequests.get(i);_&&(this.pendingRequests.delete(i),_.reject(new Error(`Request timeout: ${t}`)))},o.timeout=600*1e3,o.send(JSON.stringify(a))})}async notify(t,r){const i={jsonrpc:"2.0",method:t,params:r};await fetch(`${this.baseUrl}/acp`,{method:"POST",headers:this.buildAcpHeaders(),body:JSON.stringify(i)})}async readSseStream(t){var g;const r=(g=t.body)==null?void 0:g.getReader();if(!r)return;const i=new TextDecoder;let a="";try{for(;;){const{done:b,value:n}=await r.read();if(b)break;a+=i.decode(n,{stream:!0});const o=a.split(`
|
|
6
6
|
|
|
7
7
|
`);a=o.pop()||"";for(const d of o){const f=d.split(`
|
|
8
|
-
`);let h="";for(const _ of f)_.startsWith("data: ")&&(h+=_.substring(6));if(h)try{const _=JSON.parse(h);this.handleMessage(_)}catch{}}}}finally{r.releaseLock()}}handleMessage(t){if("method"in t&&"id"in t&&t.id!==void 0&&t.id!==null){if(t.method==="session/request_permission"){this.handlePermissionRequest(t.id,t.params);return}if(t.method==="_codebuddy.ai/question"){this.handleExtMethodQuestion(t.id,t.params);return}if(t.method==="_codebuddy.ai/delegateTool"){this.handleExtMethodDelegateTool(t.id,t.params);return}return}if("id"in t&&t.id!==void 0&&t.id!==null&&!("method"in t)){const r=this.pendingRequests.get(t.id);r&&(this.pendingRequests.delete(t.id),"error"in t&&t.error?r.reject(new Error(t.error.message)):r.resolve(t.result))}if("method"in t&&t.method==="session/update"){const r=t.params;if(r!=null&&r.update){const i=r.update.sessionUpdate;this.emit(i,r.update)}}}mapPermissionDecisionToOptionId(t){return t==="allowAll"?"allow_always":t==="allow"?"allow":t==="rejectAndExitPlan"?"reject_and_exit_plan":"reject"}async sendJsonRpcResult(t,r){var g;const i={jsonrpc:"2.0",id:t,result:r},a=await fetch(`${this.baseUrl}/acp`,{method:"POST",headers:this.buildAcpHeaders(),body:JSON.stringify(i)});if(!a.ok){let b="";try{const n=await a.json();(g=n==null?void 0:n.error)!=null&&g.message&&(b=n.error.message)}catch{}throw new Error(b||`ACP response failed: ${a.status} ${a.statusText}`)}}buildAcpHeaders(){const t={"Content-Type":"application/json",Accept:"application/json, text/event-stream"};return this.connectionId&&(t["acp-connection-id"]=this.connectionId),this.sessionToken&&(t["acp-session-token"]=this.sessionToken),this.token&&(t.Authorization=`Bearer ${this.token}`),t}handlePermissionRequest(t,r){var d;const i=r==null?void 0:r.toolCall,a=`perm-${t}`,g=((d=i==null?void 0:i._meta)==null?void 0:d["codebuddy.ai/toolName"])||(i==null?void 0:i.toolName)||"tool",b=(i==null?void 0:i.title)||g,n=i==null?void 0:i.rawInput,o=i==null?void 0:i.toolCallId;this.permissionRequestIds.set(a,t),this.emit("interruption_request",{sessionUpdate:"interruption_request",interruptionId:a,reason:"Tool requires approval",options:((r==null?void 0:r.options)||[]).map(f=>f.optionId||f.name),toolName:g,toolTitle:b,toolInput:n,toolCallId:o})}handleExtMethodQuestion(t,r){const{sessionId:i,toolCallId:a,schema:g}=r||{},b=((g==null?void 0:g.questions)||[]).map(n=>({id:n.id,question:n.question,header:n.header||"",options:(n.options||[]).map(o=>({label:o.label||"",description:o.description||""})),multiSelect:!!n.multiSelect}));this.extMethodRequestIds.set(a,t),this.emit("question_request",{toolCallId:a,sessionId:i,questions:b})}async handleExtMethodDelegateTool(t,r){const{toolId:i,input:a}=r||{};try{if(i==="ui-control"){const{uiController:g}=await kr(async()=>{const{uiController:n}=await import("./index-DixJ0kqk.js");return{uiController:n}},[]),b=await g.execute({sessionId:r.sessionId,action:a.action,target:a.target,value:a.value});await this.sendJsonRpcResult(t,{status:"success",output:b})}else if(i==="ui-query"){const{uiController:g}=await kr(async()=>{const{uiController:n}=await import("./index-DixJ0kqk.js");return{uiController:n}},[]),b=await g.queryElements({selector:a==null?void 0:a.selector,role:a==null?void 0:a.role,includeHidden:a==null?void 0:a.includeHidden,limit:a==null?void 0:a.limit});await this.sendJsonRpcResult(t,{status:"success",output:b})}else await this.sendJsonRpcResult(t,{status:"error",error:{message:`Unknown delegate tool: ${i}`}})}catch(g){await this.sendJsonRpcResult(t,{status:"error",error:{message:g instanceof Error?g.message:String(g)}})}}emit(t,r){const i=this.listeners.get(t);if(i)for(const a of i)try{a(r)}catch(g){console.error(`Event handler error for ${t}:`,g)}}setStatus(t){this._status=t,this.emit("status_change",t)}}const Ad=Object.freeze(Object.defineProperty({__proto__:null,AcpClient:qr,fetchWithRetry:Oe},Symbol.toStringTag,{value:"Module"}));let ot=null;function xe(){return ot||(ot=new qr),ot}function Rd(){const e=O.useRef(xe()),[t,r]=O.useState(0),{setStatus:i,setSessionId:a,setModels:g,setCurrentModel:b,setModes:n,setCurrentMode:o,setCommands:d,setTopic:f,setThinkingEnabled:h,setPromptSuggestion:_}=Xe(),{addChunk:S,addThinkingChunk:w,addToolCall:y,updateToolCall:c,addInterruption:p,addQuestion:l,setSessionEnd:u,resolveInterruptionByToolCallId:m,setHistoryLoading:x,addHistoryUserMessage:v,finalizeAssistantMessage:k,clearChat:E}=Le();O.useEffect(()=>{const R=e.current,B=[];return B.push(R.on("user_message_chunk",A=>{const F=A.content,M=A._meta||{},H=!!M["codebuddy.ai/isCompactInternal"];let z;const G=M["codebuddy.ai/images"];Array.isArray(G)&&G.length>0&&(z=G.filter(P=>P.blobPath&&P.mimeType).map(P=>({url:`/api/files?path=${encodeURIComponent(P.blobPath)}`,mimeType:P.mimeType})),z.length===0&&(z=void 0));let T;const D=M["codebuddy.ai/channelSource"];D&&(T={source:D,sender:M["codebuddy.ai/channelSender"]||"",senderName:M["codebuddy.ai/channelSenderName"],chatId:M["codebuddy.ai/channelChatId"],chatType:M["codebuddy.ai/channelChatType"]}),F&&typeof F.text=="string"&&v(F.text,z,H,T)})),B.push(R.on("agent_message_chunk",A=>{const F=A.content,M=A._meta||{},H=M["codebuddy.ai/parentToolCallId"],z=!!M["codebuddy.ai/isCompactInternal"];typeof F=="string"?S(F,H,z):F&&F.type==="thinking"&&typeof F.text=="string"?w(F.text,H):F&&typeof F.text=="string"&&S(F.text,H,z)})),B.push(R.on("tool_call",A=>{const F=A._meta||{},M=F["codebuddy.ai/parentToolCallId"],H=!!F["codebuddy.ai/isSubagent"],z=A.toolName||F["codebuddy.ai/toolName"]||"",G=F["codebuddy.ai/planContent"];y({id:A.toolCallId,name:A.title||z||A.kind||"tool",kind:A.kind||"other",toolName:z,input:A.rawInput||A.input,status:"running",locations:A.locations,content:A.content,parentToolCallId:M,subagent:H?{type:F["codebuddy.ai/subagentType"]||"general-purpose",description:F["codebuddy.ai/description"]||"",isBackground:!!F["codebuddy.ai/isBackground"],memberName:F["codebuddy.ai/memberName"]||void 0}:void 0,planContent:G})})),B.push(R.on("tool_call_update",A=>{const M={status:A.status==="completed"?"completed":A.status==="failed"?"failed":A.toolStatus==="completed"?"completed":A.toolStatus==="failed"?"failed":"running",result:A.rawOutput||A.toolResult};A.content!==void 0&&(M.content=A.content),c(A.toolCallId,M)})),B.push(R.on("interruption_request",A=>{p({id:A.interruptionId,reason:A.reason,options:A.options,toolName:A.toolName,toolTitle:A.toolTitle,toolInput:A.toolInput,toolCallId:A.toolCallId})})),B.push(R.on("question_request",A=>{l({id:A.toolCallId,toolCallId:A.toolCallId,sessionId:A.sessionId,questions:A.questions||[]})})),B.push(R.on("session_end",A=>{u(A.stopReason,A.errorMessage)})),B.push(R.on("session_info_update",A=>{A.title&&f(A.title);const F=A._meta||{};if(F["codebuddy.ai/historyReplay"]==="start"?x(!0):F["codebuddy.ai/historyReplay"]==="end"&&(x(!1),k()),F["codebuddy.ai/sessionReset"]){const M=F["codebuddy.ai/newSessionId"];if(M){if(E(),f(null),_(null),a(M),typeof sessionStorage<"u"&&sessionStorage.setItem("acp-session-id",M),typeof window<"u"&&window.history&&window.location){const H=new URL(window.location.href);H.searchParams.get("sessionId")!==M&&(H.searchParams.set("sessionId",M),window.history.replaceState({},"",H.toString()))}R.loadSession(M).then(C).catch(H=>console.error("Failed to load new session after reset:",H))}}if(F["codebuddy.ai/permissionResolved"]){const M=F["codebuddy.ai/toolCallId"],H=F["codebuddy.ai/decision"];M&&H&&m(M,H)}if("codebuddy.ai/promptSuggestion"in F){const M=F["codebuddy.ai/promptSuggestion"];_(M||null)}})),B.push(R.on("model_update",A=>{g(A.availableModels||[]),b(A.currentModelId||"")})),B.push(R.on("mode_update",A=>{A.availableModes&&n(A.availableModes),A.currentModeId&&o(A.currentModeId)})),B.push(R.on("current_mode_update",A=>{A.currentModeId&&o(A.currentModeId)})),B.push(R.on("config_option_update",A=>{const F=A.configOptions||[];for(const M of F)M.id==="thought_level"?h(M.currentValue==="enabled"):M.id==="mode"&&M.currentValue?o(M.currentValue):M.id==="model"&&M.currentValue&&(b(M.currentValue),M.options&&g(M.options.map(H=>({id:H.value,name:H.name||H.value}))))})),B.push(R.on("status_change",A=>{i(A)})),B.push(R.on("available_commands_update",A=>{A.availableCommands&&d(A.availableCommands.map(F=>{var M;return{name:F.name,description:F.description||"",...((M=F._meta)==null?void 0:M.type)==="skill"?{type:"skill"}:{}}}))})),()=>{B.forEach(A=>A())}},[t,S,w,y,c,p,l,u,m,g,b,n,o,d,f,h,i,x,v,k,E,a,_]);const C=O.useCallback(R=>{if(R.models&&(g(R.models.availableModels.map(B=>({id:B.modelId,name:B.name}))),b(R.models.currentModelId)),R.modes&&(n(R.modes.availableModes),o(R.modes.currentModeId)),R.configOptions)for(const B of R.configOptions)B.id==="thought_level"&&h(B.currentValue==="enabled")},[g,b,n,o,h]),N=O.useCallback(async R=>{const B=typeof R=="string"?R:R==null?void 0:R.token,A=typeof R=="object"?R==null?void 0:R.continue:!1;if(B){if(ot)try{await ot.disconnect()}catch{}ot=new qr(void 0,B),e.current=ot,r(F=>F+1)}try{i("connecting"),_(null);const F=await e.current.initializeSession({continue:A});a(F.sessionId),C(F),i("connected")}catch(F){console.error("Connection failed:",F),i("error")}},[i,a,C,_]);return{client:e.current,connect:N}}const Jl="/assets/dark-claw-cat-D_ew_BKV.png",ec="/assets/light-claw-cat-BgBWmnmi.png",tc="/assets/red-claw-cat--t2EuBIB.png",rc={small:{container:"w-20 h-20",text:"text-[12px]"},medium:{container:"w-32 h-32",text:"text-[14px]"},large:{container:"w-40 h-40",text:"text-[16px]"}};function nc({size:e="medium",className:t=""}){const i=Ot(g=>g.resolved)==="dark"?Jl:ec,a=rc[e];return s.jsxs("div",{className:`relative ${a.container} ${t}`,children:[s.jsx("img",{src:i,alt:"",className:"cat-loading-layer cat-loading-layer-base absolute inset-0 w-full h-full object-contain",decoding:"async",loading:"eager"}),s.jsx("img",{src:tc,alt:"",className:"cat-loading-layer cat-loading-layer-color absolute inset-0 w-full h-full object-contain",decoding:"async",loading:"eager"})]})}function lt({size:e="medium",text:t="Loading...",className:r=""}){const i=rc[e];return s.jsxs("div",{className:`flex flex-col items-center justify-center gap-4 ${r}`,children:[s.jsx(nc,{size:e}),t&&s.jsx("div",{className:`text-text-secondary ${i.text} font-medium animate-pulse`,children:t})]})}function Nd({size:e="medium",className:t=""}){return s.jsx(nc,{size:e,className:t})}/**
|
|
8
|
+
`);let h="";for(const _ of f)_.startsWith("data: ")&&(h+=_.substring(6));if(h)try{const _=JSON.parse(h);this.handleMessage(_)}catch{}}}}finally{r.releaseLock()}}handleMessage(t){if("method"in t&&"id"in t&&t.id!==void 0&&t.id!==null){if(t.method==="session/request_permission"){this.handlePermissionRequest(t.id,t.params);return}if(t.method==="_codebuddy.ai/question"){this.handleExtMethodQuestion(t.id,t.params);return}if(t.method==="_codebuddy.ai/delegateTool"){this.handleExtMethodDelegateTool(t.id,t.params);return}return}if("id"in t&&t.id!==void 0&&t.id!==null&&!("method"in t)){const r=this.pendingRequests.get(t.id);r&&(this.pendingRequests.delete(t.id),"error"in t&&t.error?r.reject(new Error(t.error.message)):r.resolve(t.result))}if("method"in t&&t.method==="session/update"){const r=t.params;if(r!=null&&r.update){const i=r.update.sessionUpdate;this.emit(i,r.update)}}}mapPermissionDecisionToOptionId(t){return t==="allowAll"?"allow_always":t==="allow"?"allow":t==="rejectAndExitPlan"?"reject_and_exit_plan":"reject"}async sendJsonRpcResult(t,r){var g;const i={jsonrpc:"2.0",id:t,result:r},a=await fetch(`${this.baseUrl}/acp`,{method:"POST",headers:this.buildAcpHeaders(),body:JSON.stringify(i)});if(!a.ok){let b="";try{const n=await a.json();(g=n==null?void 0:n.error)!=null&&g.message&&(b=n.error.message)}catch{}throw new Error(b||`ACP response failed: ${a.status} ${a.statusText}`)}}buildAcpHeaders(){const t={"Content-Type":"application/json",Accept:"application/json, text/event-stream"};return this.connectionId&&(t["acp-connection-id"]=this.connectionId),this.sessionToken&&(t["acp-session-token"]=this.sessionToken),this.token&&(t.Authorization=`Bearer ${this.token}`),t}handlePermissionRequest(t,r){var d;const i=r==null?void 0:r.toolCall,a=`perm-${t}`,g=((d=i==null?void 0:i._meta)==null?void 0:d["codebuddy.ai/toolName"])||(i==null?void 0:i.toolName)||"tool",b=(i==null?void 0:i.title)||g,n=i==null?void 0:i.rawInput,o=i==null?void 0:i.toolCallId;this.permissionRequestIds.set(a,t),this.emit("interruption_request",{sessionUpdate:"interruption_request",interruptionId:a,reason:"Tool requires approval",options:((r==null?void 0:r.options)||[]).map(f=>f.optionId||f.name),toolName:g,toolTitle:b,toolInput:n,toolCallId:o})}handleExtMethodQuestion(t,r){const{sessionId:i,toolCallId:a,schema:g}=r||{},b=((g==null?void 0:g.questions)||[]).map(n=>({id:n.id,question:n.question,header:n.header||"",options:(n.options||[]).map(o=>({label:o.label||"",description:o.description||""})),multiSelect:!!n.multiSelect}));this.extMethodRequestIds.set(a,t),this.emit("question_request",{toolCallId:a,sessionId:i,questions:b})}async handleExtMethodDelegateTool(t,r){const{toolId:i,input:a}=r||{};try{if(i==="ui-control"){const{uiController:g}=await kr(async()=>{const{uiController:n}=await import("./index-DixJ0kqk.js");return{uiController:n}},[]),b=await g.execute({sessionId:r.sessionId,action:a.action,target:a.target,value:a.value});await this.sendJsonRpcResult(t,{status:"success",output:b})}else if(i==="ui-query"){const{uiController:g}=await kr(async()=>{const{uiController:n}=await import("./index-DixJ0kqk.js");return{uiController:n}},[]),b=await g.queryElements({selector:a==null?void 0:a.selector,role:a==null?void 0:a.role,includeHidden:a==null?void 0:a.includeHidden,limit:a==null?void 0:a.limit});await this.sendJsonRpcResult(t,{status:"success",output:b})}else await this.sendJsonRpcResult(t,{status:"error",error:{message:`Unknown delegate tool: ${i}`}})}catch(g){await this.sendJsonRpcResult(t,{status:"error",error:{message:g instanceof Error?g.message:String(g)}})}}emit(t,r){const i=this.listeners.get(t);if(i)for(const a of i)try{a(r)}catch(g){console.error(`Event handler error for ${t}:`,g)}}setStatus(t){this._status=t,this.emit("status_change",t)}}const Ad=Object.freeze(Object.defineProperty({__proto__:null,AcpClient:qr,fetchWithRetry:Oe},Symbol.toStringTag,{value:"Module"}));let ot=null;function xe(){return ot||(ot=new qr),ot}function Rd(){const e=O.useRef(xe()),[t,r]=O.useState(0),{setStatus:i,setSessionId:a,setModels:g,setCurrentModel:b,setModes:n,setCurrentMode:o,setCommands:d,setTopic:f,setThinkingEnabled:h,setPromptSuggestion:_}=Xe(),{addChunk:S,addThinkingChunk:w,addToolCall:y,updateToolCall:c,addInterruption:p,addQuestion:l,setSessionEnd:u,resolveInterruptionByToolCallId:m,setHistoryLoading:x,addHistoryUserMessage:v,finalizeAssistantMessage:k,clearChat:E}=Le();O.useEffect(()=>{const R=e.current,B=[];return B.push(R.on("user_message_chunk",A=>{const F=A.content,M=A._meta||{},H=!!M["codebuddy.ai/isCompactInternal"];let z;const G=M["codebuddy.ai/images"];Array.isArray(G)&&G.length>0&&(z=G.filter(P=>P.blobPath&&P.mimeType).map(P=>({url:`/api/v1/files?path=${encodeURIComponent(P.blobPath)}`,mimeType:P.mimeType})),z.length===0&&(z=void 0));let T;const D=M["codebuddy.ai/channelSource"];D&&(T={source:D,sender:M["codebuddy.ai/channelSender"]||"",senderName:M["codebuddy.ai/channelSenderName"],chatId:M["codebuddy.ai/channelChatId"],chatType:M["codebuddy.ai/channelChatType"]}),F&&typeof F.text=="string"&&v(F.text,z,H,T)})),B.push(R.on("agent_message_chunk",A=>{const F=A.content,M=A._meta||{},H=M["codebuddy.ai/parentToolCallId"],z=!!M["codebuddy.ai/isCompactInternal"];typeof F=="string"?S(F,H,z):F&&F.type==="thinking"&&typeof F.text=="string"?w(F.text,H):F&&typeof F.text=="string"&&S(F.text,H,z)})),B.push(R.on("tool_call",A=>{const F=A._meta||{},M=F["codebuddy.ai/parentToolCallId"],H=!!F["codebuddy.ai/isSubagent"],z=A.toolName||F["codebuddy.ai/toolName"]||"",G=F["codebuddy.ai/planContent"];y({id:A.toolCallId,name:A.title||z||A.kind||"tool",kind:A.kind||"other",toolName:z,input:A.rawInput||A.input,status:"running",locations:A.locations,content:A.content,parentToolCallId:M,subagent:H?{type:F["codebuddy.ai/subagentType"]||"general-purpose",description:F["codebuddy.ai/description"]||"",isBackground:!!F["codebuddy.ai/isBackground"],memberName:F["codebuddy.ai/memberName"]||void 0}:void 0,planContent:G})})),B.push(R.on("tool_call_update",A=>{const M={status:A.status==="completed"?"completed":A.status==="failed"?"failed":A.toolStatus==="completed"?"completed":A.toolStatus==="failed"?"failed":"running",result:A.rawOutput||A.toolResult};A.content!==void 0&&(M.content=A.content),c(A.toolCallId,M)})),B.push(R.on("interruption_request",A=>{p({id:A.interruptionId,reason:A.reason,options:A.options,toolName:A.toolName,toolTitle:A.toolTitle,toolInput:A.toolInput,toolCallId:A.toolCallId})})),B.push(R.on("question_request",A=>{l({id:A.toolCallId,toolCallId:A.toolCallId,sessionId:A.sessionId,questions:A.questions||[]})})),B.push(R.on("session_end",A=>{u(A.stopReason,A.errorMessage)})),B.push(R.on("session_info_update",A=>{A.title&&f(A.title);const F=A._meta||{};if(F["codebuddy.ai/historyReplay"]==="start"?x(!0):F["codebuddy.ai/historyReplay"]==="end"&&(x(!1),k()),F["codebuddy.ai/sessionReset"]){const M=F["codebuddy.ai/newSessionId"];if(M){if(E(),f(null),_(null),a(M),typeof sessionStorage<"u"&&sessionStorage.setItem("acp-session-id",M),typeof window<"u"&&window.history&&window.location){const H=new URL(window.location.href);H.searchParams.get("sessionId")!==M&&(H.searchParams.set("sessionId",M),window.history.replaceState({},"",H.toString()))}R.loadSession(M).then(C).catch(H=>console.error("Failed to load new session after reset:",H))}}if(F["codebuddy.ai/permissionResolved"]){const M=F["codebuddy.ai/toolCallId"],H=F["codebuddy.ai/decision"];M&&H&&m(M,H)}if("codebuddy.ai/promptSuggestion"in F){const M=F["codebuddy.ai/promptSuggestion"];_(M||null)}})),B.push(R.on("model_update",A=>{g(A.availableModels||[]),b(A.currentModelId||"")})),B.push(R.on("mode_update",A=>{A.availableModes&&n(A.availableModes),A.currentModeId&&o(A.currentModeId)})),B.push(R.on("current_mode_update",A=>{A.currentModeId&&o(A.currentModeId)})),B.push(R.on("config_option_update",A=>{const F=A.configOptions||[];for(const M of F)M.id==="thought_level"?h(M.currentValue==="enabled"):M.id==="mode"&&M.currentValue?o(M.currentValue):M.id==="model"&&M.currentValue&&(b(M.currentValue),M.options&&g(M.options.map(H=>({id:H.value,name:H.name||H.value}))))})),B.push(R.on("status_change",A=>{i(A)})),B.push(R.on("available_commands_update",A=>{A.availableCommands&&d(A.availableCommands.map(F=>{var M;return{name:F.name,description:F.description||"",...((M=F._meta)==null?void 0:M.type)==="skill"?{type:"skill"}:{}}}))})),()=>{B.forEach(A=>A())}},[t,S,w,y,c,p,l,u,m,g,b,n,o,d,f,h,i,x,v,k,E,a,_]);const C=O.useCallback(R=>{if(R.models&&(g(R.models.availableModels.map(B=>({id:B.modelId,name:B.name}))),b(R.models.currentModelId)),R.modes&&(n(R.modes.availableModes),o(R.modes.currentModeId)),R.configOptions)for(const B of R.configOptions)B.id==="thought_level"&&h(B.currentValue==="enabled")},[g,b,n,o,h]),N=O.useCallback(async R=>{const B=typeof R=="string"?R:R==null?void 0:R.token,A=typeof R=="object"?R==null?void 0:R.continue:!1;if(B){if(ot)try{await ot.disconnect()}catch{}ot=new qr(void 0,B),e.current=ot,r(F=>F+1)}try{i("connecting"),_(null);const F=await e.current.initializeSession({continue:A});a(F.sessionId),C(F),i("connected")}catch(F){console.error("Connection failed:",F),i("error")}},[i,a,C,_]);return{client:e.current,connect:N}}const Jl="/assets/dark-claw-cat-D_ew_BKV.png",ec="/assets/light-claw-cat-BgBWmnmi.png",tc="/assets/red-claw-cat--t2EuBIB.png",rc={small:{container:"w-20 h-20",text:"text-[12px]"},medium:{container:"w-32 h-32",text:"text-[14px]"},large:{container:"w-40 h-40",text:"text-[16px]"}};function nc({size:e="medium",className:t=""}){const i=Ot(g=>g.resolved)==="dark"?Jl:ec,a=rc[e];return s.jsxs("div",{className:`relative ${a.container} ${t}`,children:[s.jsx("img",{src:i,alt:"",className:"cat-loading-layer cat-loading-layer-base absolute inset-0 w-full h-full object-contain",decoding:"async",loading:"eager"}),s.jsx("img",{src:tc,alt:"",className:"cat-loading-layer cat-loading-layer-color absolute inset-0 w-full h-full object-contain",decoding:"async",loading:"eager"})]})}function lt({size:e="medium",text:t="Loading...",className:r=""}){const i=rc[e];return s.jsxs("div",{className:`flex flex-col items-center justify-center gap-4 ${r}`,children:[s.jsx(nc,{size:e}),t&&s.jsx("div",{className:`text-text-secondary ${i.text} font-medium animate-pulse`,children:t})]})}function Nd({size:e="medium",className:t=""}){return s.jsx(nc,{size:e,className:t})}/**
|
|
9
9
|
* @license lucide-react v0.468.0 - ISC
|
|
10
10
|
*
|
|
11
11
|
* This source code is licensed under the ISC license.
|
|
@@ -388,13 +388,13 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
388
388
|
`)}}catch{}return e}function qt(e){return e.replace(/\\r\\n/g,`
|
|
389
389
|
`).replace(/\\n/g,`
|
|
390
390
|
`)}function je(e){if(typeof e=="string"){const t=Nl(e);return qt(t)}if(!e)return"";try{if(typeof e=="object"&&e!==null){const t=e,r=Object.keys(t);if(r.length===1&&typeof t[r[0]]=="string"){const i=t[r[0]],a=Nl(i);return qt(a)}if(typeof t.text=="string"&&t.type==="text")return qt(t.text)}if(Array.isArray(e)){const t=e.filter(r=>r&&typeof r.text=="string").map(r=>r.text);if(t.length>0)return qt(t.join(`
|
|
391
|
-
`))}return JSON.stringify(e,null,2)}catch{return String(e)}}const Ce={size:14,strokeWidth:1.5},Te="text-text-tertiary flex-shrink-0";function wp(){return s.jsx(tt,{...Ce,className:Te})}function kp(){return s.jsx(Yd,{...Ce,className:Te})}function Cp(){return s.jsx(bc,{...Ce,className:Te})}function Bc(){return s.jsx(wt,{...Ce,className:Te})}function Mr(){return s.jsx(Kr,{...Ce,className:Te})}function Fc(){return s.jsx(ru,{...Ce,className:Te})}function Il(){return s.jsx(_c,{...Ce,className:Te})}function Ll(){return s.jsx(pc,{...Ce,className:Te})}function Tp(){return s.jsx(tu,{...Ce,className:Te})}function Ap(){return s.jsx(Fd,{...Ce,className:Te})}function Rp(){return s.jsx($d,{...Ce,className:Te})}function Np(){return s.jsx(hc,{...Ce,className:Te})}function Ip(){return s.jsx(Md,{...Ce,className:Te})}function Lp(){return s.jsx(Gd,{...Ce,className:Te})}function Op(){return s.jsx(oc,{...Ce,className:Te})}function Ol(){return s.jsx(dc,{...Ce,className:Te})}function Pc({status:e}){return e==="running"?s.jsx("span",{className:"inline-block w-1.5 h-1.5 rounded-full flex-shrink-0 bg-text-tertiary animate-pulse"}):e==="failed"?s.jsx("span",{className:"inline-block w-1.5 h-1.5 rounded-full flex-shrink-0 bg-accent-red"}):e==="completed"?s.jsx("span",{className:"inline-block w-1.5 h-1.5 rounded-full flex-shrink-0 bg-accent-green"}):null}function Dp(e){if(!e||!Array.isArray(e))return null;const t=e.find(r=>r.type==="diff");return!t||!t.path?null:{path:t.path,oldText:t.oldText??null,newText:t.newText??""}}function et(e){return`/api/files?path=${encodeURIComponent(e)}`}function Br(e){const t=[],r=i=>{if(i){if(typeof i=="object"&&i.type==="image_blob_ref"&&i.blob_path){t.push(i);return}if(Array.isArray(i)){for(const a of i)r(a);return}if(typeof i=="string"&&i.includes("image_blob_ref"))try{r(JSON.parse(i))}catch{}}};return r(e),t}function Fr(e){var t,r,i,a,g;if(e.content&&Array.isArray(e.content)){for(const b of e.content){const n=b;if(n.type==="content"&&((t=n.content)==null?void 0:t.type)==="image"&&((r=n.content)!=null&&r.data))return`data:${n.content.mimeType||"image/png"};base64,${n.content.data}`;if(n.type==="image"&&n.data)return`data:${n.mimeType||n.mediaType||"image/png"};base64,${n.data}`;if(n.type==="image_url"&&((i=n.image_url)!=null&&i.url))return n.image_url.url;if(n.type==="image_blob_ref"&&n.blob_path)return et(n.blob_path)}for(const b of e.content){const n=b,o=n.type==="content"&&((a=n.content)==null?void 0:a.type)==="text"?n.content.text:null;if(o){const d=Br(o);if(d.length>0)return et(d[0].blob_path)}}}if(e.result&&typeof e.result=="object"){const b=e.result;if(b.type==="image"&&b.data)return`data:${b.mimeType||b.mediaType||"image/png"};base64,${b.data}`;if(b.type==="image_url"&&((g=b.image_url)!=null&&g.url))return b.image_url.url;if(b.type==="image_blob_ref"&&b.blob_path)return et(b.blob_path)}if(e.result){const b=Br(e.result);if(b.length>0)return et(b[0].blob_path)}return null}function Dl(e){const t=je(e);if(!t)return null;const r=t.match(/Full path:\s*(.+)/);if(r)return r[1].trim();const i=t.match(/file:\/\/([^\s\n]+)/);if(i)return i[1];const a=Br(e);return a.length>0?a[0].blob_path:null}function Mp(e){const t=e.input;if(t!=null&&t.description&&typeof t.description=="string")return t.description}function he(e){return e.input||{}}function Ne(e,t){return e.length<=t?e:e.slice(0,t)+"..."}function Bp(e,t=[]){const r=new Set(["description","activeForm",...t]),i=[];for(const[a,g]of Object.entries(e))r.has(a)||g===void 0||g===null||typeof g=="string"&&g.length>0&&i.push(g);return i.length>0?Ne(i.join(" · "),80):""}function Fp(e){if(e==null)return[];const t=je(e);if(!t)return[];try{const r=JSON.parse(t);if(Array.isArray(r))return r.map(i=>typeof i=="string"?i:JSON.stringify(i)).filter(Boolean)}catch{}return t.split(`
|
|
391
|
+
`))}return JSON.stringify(e,null,2)}catch{return String(e)}}const Ce={size:14,strokeWidth:1.5},Te="text-text-tertiary flex-shrink-0";function wp(){return s.jsx(tt,{...Ce,className:Te})}function kp(){return s.jsx(Yd,{...Ce,className:Te})}function Cp(){return s.jsx(bc,{...Ce,className:Te})}function Bc(){return s.jsx(wt,{...Ce,className:Te})}function Mr(){return s.jsx(Kr,{...Ce,className:Te})}function Fc(){return s.jsx(ru,{...Ce,className:Te})}function Il(){return s.jsx(_c,{...Ce,className:Te})}function Ll(){return s.jsx(pc,{...Ce,className:Te})}function Tp(){return s.jsx(tu,{...Ce,className:Te})}function Ap(){return s.jsx(Fd,{...Ce,className:Te})}function Rp(){return s.jsx($d,{...Ce,className:Te})}function Np(){return s.jsx(hc,{...Ce,className:Te})}function Ip(){return s.jsx(Md,{...Ce,className:Te})}function Lp(){return s.jsx(Gd,{...Ce,className:Te})}function Op(){return s.jsx(oc,{...Ce,className:Te})}function Ol(){return s.jsx(dc,{...Ce,className:Te})}function Pc({status:e}){return e==="running"?s.jsx("span",{className:"inline-block w-1.5 h-1.5 rounded-full flex-shrink-0 bg-text-tertiary animate-pulse"}):e==="failed"?s.jsx("span",{className:"inline-block w-1.5 h-1.5 rounded-full flex-shrink-0 bg-accent-red"}):e==="completed"?s.jsx("span",{className:"inline-block w-1.5 h-1.5 rounded-full flex-shrink-0 bg-accent-green"}):null}function Dp(e){if(!e||!Array.isArray(e))return null;const t=e.find(r=>r.type==="diff");return!t||!t.path?null:{path:t.path,oldText:t.oldText??null,newText:t.newText??""}}function et(e){return`/api/v1/files?path=${encodeURIComponent(e)}`}function Br(e){const t=[],r=i=>{if(i){if(typeof i=="object"&&i.type==="image_blob_ref"&&i.blob_path){t.push(i);return}if(Array.isArray(i)){for(const a of i)r(a);return}if(typeof i=="string"&&i.includes("image_blob_ref"))try{r(JSON.parse(i))}catch{}}};return r(e),t}function Fr(e){var t,r,i,a,g;if(e.content&&Array.isArray(e.content)){for(const b of e.content){const n=b;if(n.type==="content"&&((t=n.content)==null?void 0:t.type)==="image"&&((r=n.content)!=null&&r.data))return`data:${n.content.mimeType||"image/png"};base64,${n.content.data}`;if(n.type==="image"&&n.data)return`data:${n.mimeType||n.mediaType||"image/png"};base64,${n.data}`;if(n.type==="image_url"&&((i=n.image_url)!=null&&i.url))return n.image_url.url;if(n.type==="image_blob_ref"&&n.blob_path)return et(n.blob_path)}for(const b of e.content){const n=b,o=n.type==="content"&&((a=n.content)==null?void 0:a.type)==="text"?n.content.text:null;if(o){const d=Br(o);if(d.length>0)return et(d[0].blob_path)}}}if(e.result&&typeof e.result=="object"){const b=e.result;if(b.type==="image"&&b.data)return`data:${b.mimeType||b.mediaType||"image/png"};base64,${b.data}`;if(b.type==="image_url"&&((g=b.image_url)!=null&&g.url))return b.image_url.url;if(b.type==="image_blob_ref"&&b.blob_path)return et(b.blob_path)}if(e.result){const b=Br(e.result);if(b.length>0)return et(b[0].blob_path)}return null}function Dl(e){const t=je(e);if(!t)return null;const r=t.match(/Full path:\s*(.+)/);if(r)return r[1].trim();const i=t.match(/file:\/\/([^\s\n]+)/);if(i)return i[1];const a=Br(e);return a.length>0?a[0].blob_path:null}function Mp(e){const t=e.input;if(t!=null&&t.description&&typeof t.description=="string")return t.description}function he(e){return e.input||{}}function Ne(e,t){return e.length<=t?e:e.slice(0,t)+"..."}function Bp(e,t=[]){const r=new Set(["description","activeForm",...t]),i=[];for(const[a,g]of Object.entries(e))r.has(a)||g===void 0||g===null||typeof g=="string"&&g.length>0&&i.push(g);return i.length>0?Ne(i.join(" · "),80):""}function Fp(e){if(e==null)return[];const t=je(e);if(!t)return[];try{const r=JSON.parse(t);if(Array.isArray(r))return r.map(i=>typeof i=="string"?i:JSON.stringify(i)).filter(Boolean)}catch{}return t.split(`
|
|
392
392
|
`).filter(Boolean)}function Pp(e){const t=je(e);if(!t)return"";const r=t.split(`
|
|
393
393
|
`),i=[];let a=!1,g="";for(const b of r){if(b.startsWith("Command: ")){a=!1,g="command";continue}if(b.startsWith("Stdout: ")||b==="Stdout:"){a=!0,g="stdout";const n=b.slice(8);n&&n!=="(empty)"&&i.push(n);continue}if(b.startsWith("Stderr: ")||b==="Stderr:"){a=!0,g="stderr";const n=b.slice(8);n&&n!=="(empty)"&&i.push(n);continue}if(b.startsWith("Exit Code: ")||b.startsWith("Signal: ")){a=!1,g="";continue}a&&(g==="stdout"||g==="stderr")&&i.push(b)}return i.length===0&&t.length>0&&!t.startsWith("Command: ")?t:i.join(`
|
|
394
394
|
`).trim()}function jp({result:e}){const{t}=ue(),[r,i]=O.useState(!1),a=Fp(e);if(a.length===0)return null;const g=10,b=r?a:a.slice(0,g),n=a.length>g;return s.jsxs("div",{className:"rounded-md bg-bg-secondary overflow-hidden",children:[s.jsx("div",{className:"px-2.5 py-1 text-[11px] text-text-tertiary border-b border-border-muted/30",children:t("tool.itemsCount").replace("{count}",String(a.length))}),s.jsx("div",{className:"max-h-64 overflow-y-auto",children:b.map((o,d)=>s.jsxs("div",{className:"flex items-center gap-1.5 px-2.5 py-0.5 text-xs font-mono text-text-secondary hover:bg-bg-hover/50",children:[s.jsx(tt,{size:10,className:"text-text-tertiary flex-shrink-0"}),s.jsx("span",{className:"truncate",title:o,children:o})]},d))}),n&&!r&&s.jsx("button",{onClick:()=>i(!0),className:"w-full px-2.5 py-1 text-[11px] text-accent-brand hover:bg-bg-hover/30 border-t border-border-muted/30 cursor-pointer",children:t("tool.showAllItems").replace("{count}",String(a.length))})]})}function ze({result:e,maxLines:t=8}){const{t:r}=ue(),i=je(e);if(!i)return null;const a=i.split(`
|
|
395
395
|
`),g=a.length>t,b=g?a.slice(0,t).join(`
|
|
396
396
|
`):i;return s.jsxs("pre",{className:"text-text-secondary font-mono text-xs px-2.5 py-1.5 whitespace-pre-wrap break-words max-h-60 overflow-y-auto bg-bg-secondary/40 rounded-md",children:[b,g&&s.jsx("span",{className:"text-text-tertiary",children:`
|
|
397
|
-
${r("tool.moreLinesCount").replace("{count}",String(a.length-t))}`})]})}function Ct({src:e,alt:t}){const r=e.startsWith("file://")?et(e.replace("file://","")):e.startsWith("/")&&!e.startsWith("/api/")?et(e):e;return s.jsx("div",{className:"rounded-md overflow-hidden bg-bg-secondary/40 p-2",children:s.jsx("img",{src:r,alt:t||"Image",className:"max-w-full max-h-64 rounded object-contain",loading:"lazy"})})}const Ml={read:{Icon:wp,render:e=>{const t=Fr(e);if(t){const i=he(e),a=i.file_path?String(i.file_path).split("/").pop():void 0;return s.jsx(Ct,{src:t,alt:a})}if(e.result===void 0)return null;const r=je(e.result);return r?s.jsx("pre",{className:"text-text-secondary font-mono text-xs px-2.5 py-1.5 whitespace-pre overflow-x-auto max-h-64 overflow-y-auto bg-bg-secondary/40 rounded-md",children:r}):null}},edit:{Icon:kp,render:e=>{const t=Dp(e.content);if(t){const r=e.status==="failed";return s.jsx("div",{className:r?"opacity-40":"",children:s.jsx(Jt,{path:t.path,oldText:t.oldText,newText:t.newText,maxHeight:"max-h-64"})})}return e.result!==void 0?s.jsx(ze,{result:e.result}):null}},execute:{Icon:Cp,render:e=>{const t=he(e),i=(e.result!==void 0?Pp(e.result):"")||(e.result!==void 0?je(e.result):"");return s.jsxs("div",{className:"rounded-md overflow-hidden bg-bg-secondary/40",children:[!!t.command&&s.jsxs("pre",{className:"px-2.5 py-1.5 font-mono text-xs whitespace-pre overflow-x-auto text-text-primary",children:[s.jsx("span",{className:"text-text-tertiary select-none",children:"$ "}),String(t.command)]}),i&&s.jsx("pre",{className:"text-text-secondary font-mono text-xs px-2.5 py-1.5 whitespace-pre-wrap break-words max-h-60 overflow-y-auto border-t border-border-muted/30",children:i})]})}},search:{Icon:Bc,render:e=>s.jsx(jp,{result:e.result})},fetch:{Icon:Mr,render:e=>{const t=he(e);return!t.url&&!t.query?null:s.jsxs("div",{className:"text-xs font-mono px-1 space-y-0.5",children:[!!t.url&&s.jsx("div",{className:"text-text-secondary truncate",children:String(t.url)}),!!t.prompt&&s.jsx("div",{className:"text-text-tertiary line-clamp-2",children:String(t.prompt)}),!!t.query&&s.jsx("div",{className:"text-text-secondary",children:String(t.query)})]})}}},Bl={ImageGen:{Icon:Ol,getTitle:(e,t)=>t("tool.imageGen"),getSummary:e=>{const t=he(e);return t.prompt?Ne(String(t.prompt),60):void 0},render:(e,t)=>{const r=Fr(e);if(r)return s.jsx(Ct,{src:r,alt:t("tool.generatedImage")});const i=Dl(e.result);return i?s.jsx(Ct,{src:et(i),alt:t("tool.generatedImage")}):e.result!==void 0?s.jsx(ze,{result:e.result,maxLines:6}):null}},ImageEdit:{Icon:Ol,getTitle:(e,t)=>t("tool.imageEdit"),getSummary:e=>{const t=he(e);return t.prompt?Ne(String(t.prompt),60):void 0},render:(e,t)=>{const r=Fr(e);if(r)return s.jsx(Ct,{src:r,alt:t("tool.editedImage")});const i=Dl(e.result);return i?s.jsx(Ct,{src:et(i),alt:t("tool.editedImage")}):e.result!==void 0?s.jsx(ze,{result:e.result,maxLines:6}):null}},ToolSearch:{Icon:Bc,getTitle:(e,t)=>t("tool.toolSearch"),getSummary:e=>{const t=he(e);if(t.query)return String(t.query);if(t.tool_names)return`[${String(t.tool_names)}]`},render:e=>e.result===void 0?null:s.jsx(ze,{result:e.result,maxLines:12})},TeamCreate:{Icon:Il,getTitle:(e,t)=>t("tool.teamCreate"),getSummary:e=>{const t=he(e),r=t.name?String(t.name):void 0,i=t.description?String(t.description):void 0;return r&&i?`${r} · ${i}`:r||i},render:e=>{if(e.result===void 0)return null;const t=je(e.result);return t?s.jsxs("div",{className:"flex items-center gap-1.5 px-2.5 py-1.5 bg-bg-secondary/40 rounded-md text-xs",children:[s.jsx(ac,{size:12,className:"text-accent-green flex-shrink-0"}),s.jsx("span",{className:"text-text-secondary",children:Ne(t,120)})]}):null}},TeamDelete:{Icon:Il,getTitle:(e,t)=>t("tool.teamDelete"),getSummary:e=>{const t=he(e);return t.team_name?String(t.team_name):void 0}},TaskCreate:{Icon:Ll,getTitle:(e,t)=>t("tool.taskCreate"),getSummary:e=>{const t=he(e);return t.subject?Ne(String(t.subject),80):void 0}},TaskUpdate:{Icon:Ap,getTitle:(e,t)=>t("tool.taskUpdate"),getSummary:e=>{const t=he(e),r=[];return t.taskId&&r.push(`#${t.taskId}`),t.status&&r.push(String(t.status)),t.subject&&r.push(Ne(String(t.subject),40)),r.join(" · ")||void 0}},TaskList:{Icon:Ll,getTitle:(e,t)=>t("tool.taskList")},TaskGet:{Icon:Rp,getTitle:(e,t)=>t("tool.taskGet"),getSummary:e=>{const t=he(e);return t.taskId?`#${t.taskId}`:void 0},render:e=>e.result===void 0?null:s.jsx(ze,{result:e.result,maxLines:8})},SendMessage:{Icon:Tp,getTitle:(e,t)=>{const r=he(e),i=String(r.type||"message"),a=r.recipient?String(r.recipient):void 0;switch(i){case"message":return a?`@${a}`:t("tool.sendMessage");case"broadcast":return"@team";case"shutdown_request":return a?`@${a} · shutdown`:t("tool.shutdown");case"shutdown_response":return r.approve!==!1?t("tool.taskCompleted"):t("tool.shutdownRejected");case"plan_approval_response":return a?`@${a} · ${r.approve!==!1?t("tool.approved"):t("tool.rejected")}`:t("tool.planResponse");default:return a?`@${a}`:i}},getSummary:e=>{const t=he(e);return t.summary?Ne(String(t.summary),80):void 0},render:e=>{if(e.result===void 0)return null;const t=je(e.result);return t?s.jsx("div",{className:"text-xs text-text-secondary px-2.5 py-1.5 bg-bg-secondary/40 rounded-md",children:Ne(t,200)}):null}},WebSearch:{Icon:Mr,getTitle:(e,t)=>t("tool.webSearch"),getSummary:e=>{const t=he(e);return t.query?Ne(String(t.query),80):void 0},render:e=>e.result===void 0?null:s.jsx(ze,{result:e.result,maxLines:10})},WebFetch:{Icon:Mr,getTitle:(e,t)=>t("tool.webFetch"),getSummary:e=>{const t=he(e);return t.url?Ne(String(t.url),60):void 0},render:e=>{const t=he(e);return s.jsxs("div",{className:"text-xs font-mono px-1 space-y-0.5",children:[!!t.url&&s.jsx("div",{className:"text-text-secondary truncate",children:String(t.url)}),!!t.prompt&&s.jsx("div",{className:"text-text-tertiary line-clamp-2",children:String(t.prompt)})]})}},SaveMemory:{Icon:Np,getTitle:(e,t)=>t("tool.saveMemory"),getSummary:e=>{const t=he(e);return t.content?Ne(String(t.content),60):void 0}},AskUserQuestion:{Icon:Ip,getTitle:(e,t)=>t("tool.askUserQuestion"),getSummary:e=>{const r=he(e).questions;if(!r||r.length===0)return;if(r.length===1)return r[0].question?Ne(String(r[0].question),80):r[0].header;const i=r.map(a=>a.header||"?").join(", ");return`${r.length} questions: ${i}`},render:(e,t)=>{const i=he(e).questions;return!i||i.length===0?e.result!==void 0?s.jsx(ze,{result:e.result,maxLines:6}):null:s.jsxs("div",{className:"space-y-2",children:[i.map((a,g)=>s.jsxs("div",{className:"rounded-md bg-bg-secondary/40 overflow-hidden",children:[s.jsxs("div",{className:"px-2.5 py-1.5 text-xs",children:[a.header&&s.jsx("span",{className:"inline-block px-1.5 py-0.5 rounded bg-accent-brand/10 text-accent-brand text-[11px] font-medium mr-1.5",children:a.header}),s.jsx("span",{className:"text-text-primary font-medium",children:a.question}),a.multiSelect&&s.jsxs("span",{className:"text-[10px] text-text-tertiary ml-1",children:["(",t("question.multiLabel"),")"]})]}),a.options&&a.options.length>0&&s.jsx("div",{className:"border-t border-border-muted/30 px-2.5 py-1",children:a.options.map((b,n)=>s.jsxs("div",{className:"flex items-baseline gap-1.5 py-0.5 text-xs",children:[s.jsx("span",{className:"text-text-secondary font-medium",children:b.label}),b.description&&s.jsxs("span",{className:"text-text-tertiary",children:["— ",Ne(String(b.description),60)]})]},n))})]},g)),e.result!==void 0&&s.jsx(ze,{result:e.result,maxLines:4})]})}},EnterPlanMode:{Icon:Lp,getTitle:(e,t)=>t("tool.enterPlanMode"),render:e=>{if(e.result===void 0)return null;const t=je(e.result);if(!t)return null;const r=e.result,i=r!=null&&r.planFilePath?String(r.planFilePath):void 0;return s.jsxs("div",{className:"text-xs px-2.5 py-1.5 bg-bg-secondary/40 rounded-md space-y-1",children:[i&&s.jsxs("div",{className:"flex items-center gap-1.5 text-text-tertiary",children:[s.jsx(oc,{size:10,className:"flex-shrink-0"}),s.jsx("span",{className:"font-mono truncate",children:i})]}),!i&&t&&s.jsx("div",{className:"text-text-secondary",children:Ne(t,200)})]})}},ExitPlanMode:{Icon:Op,getTitle:(e,t)=>t("tool.exitPlanMode"),getSummary:(e,t)=>{const i=he(e).allowedPrompts;if(i&&i.length>0)return t("tool.permissionsCount").replace("{count}",String(i.length))},render:(e,t)=>{const i=he(e).allowedPrompts,a=i&&i.length>0,g=e.result!==void 0;return!a&&!g?null:s.jsxs("div",{className:"space-y-1",children:[a&&s.jsxs("div",{className:"rounded-md bg-bg-secondary/40 px-2.5 py-1.5",children:[s.jsx("div",{className:"text-[11px] text-text-tertiary mb-1",children:t("tool.allowedActions")}),i.map((b,n)=>s.jsxs("div",{className:"flex items-center gap-1.5 text-xs py-0.5",children:[s.jsx(bc,{size:10,className:"text-text-tertiary flex-shrink-0"}),s.jsx("span",{className:"text-text-secondary",children:b.prompt})]},n))]}),g&&s.jsx(ze,{result:e.result,maxLines:6})]})}},Skill:{Icon:Fc,getTitle:(e,t)=>t("tool.skill"),getSummary:e=>{const t=he(e);return t.skill?String(t.skill):t.command?String(t.command):void 0}}};function Up(e){return e.toolName&&Bl[e.toolName]?Bl[e.toolName]:e.kind&&Ml[e.kind]?Ml[e.kind]:jc}function $p(e){return!!(e==null||e===""||Array.isArray(e)&&e.length===0||typeof e=="object"&&Object.keys(e).length===0)}const jc={Icon:Fc,getSummary:e=>{const t=he(e),r=Bp(t);return r||void 0},render:e=>{const t=he(e),r=Object.keys(t).length>0,i=e.result,a=i!==void 0&&!$p(i)&&je(i).length>0;return!r&&!a?null:s.jsxs("div",{className:"space-y-1 max-h-64 overflow-y-auto",children:[r&&s.jsx("pre",{className:"text-text-tertiary font-mono text-xs px-2.5 py-1.5 whitespace-pre-wrap break-words bg-bg-secondary/40 rounded-md",children:JSON.stringify(t,null,2)}),a&&s.jsx("pre",{className:"text-text-secondary font-mono text-xs px-2.5 py-1.5 whitespace-pre-wrap break-words bg-bg-secondary/40 rounded-md",children:je(i)})]})}},Uc="subagent-collapse-pref";function Fl(){try{return localStorage.getItem(Uc)==="true"}catch{return!1}}function Hp(e){try{localStorage.setItem(Uc,String(e))}catch{}}function zp(){return s.jsxs("span",{className:"inline-flex items-center gap-0.5 ml-1 align-middle",children:[s.jsx("span",{className:"w-1 h-1 rounded-full bg-accent-purple animate-[dotPulse_1.4s_ease-in-out_0s_infinite]"}),s.jsx("span",{className:"w-1 h-1 rounded-full bg-accent-purple animate-[dotPulse_1.4s_ease-in-out_0.2s_infinite]"}),s.jsx("span",{className:"w-1 h-1 rounded-full bg-accent-purple animate-[dotPulse_1.4s_ease-in-out_0.4s_infinite]"})]})}function Pl({entry:e,isActive:t}){const r=e.streaming&&t,i=e.content&&e.content.trim().length>0;return!i&&!r?s.jsx(s.Fragment,{}):s.jsxs("div",{className:"markdown-body text-chat text-text-primary py-0.5",children:[i&&s.jsx(Gr,{remarkPlugins:[Wr],children:e.content}),r&&s.jsx(zp,{})]})}function Gp(e){return O.useMemo(()=>{const t=e.subagentTimeline||[];let r=0,i=0;for(const a of t)a.type==="tool_call_ref"?r++:a.type==="message"&&i++;return{toolCount:r,messageCount:i}},[e.subagentTimeline])}function Wp({toolCall:e}){var p,l,u,m,x;const{t}=ue(),r=Le(v=>v.childToolCalls),i=e.subagentTimeline||[],a=e.status==="running",g=e.status==="failed",b=!!((p=e.subagent)!=null&&p.memberName),n=Gp(e),[o,d]=O.useState(()=>!a&&Fl());O.useEffect(()=>{d(a?!1:Fl())},[a]);const f=O.useCallback(()=>{a||d(v=>{const k=!v;return Hp(k),k})},[a]),h=(l=e.subagent)!=null&&l.memberName?`@${e.subagent.memberName}`:((u=e.subagent)==null?void 0:u.type)||t("tool.agent"),_=((m=e.subagent)==null?void 0:m.description)||"",S=(x=e.subagent)==null?void 0:x.isBackground,w=i.length>0,y=w&&!o,c=O.useMemo(()=>{if(a)return null;const v=[];return g?v.push(t("tool.failed")):e.status==="completed"&&v.push(t("tool.completed")),n.toolCount>0&&v.push(t("tool.toolsCount").replace("{count}",String(n.toolCount))),v.length>0?v.join(" · "):null},[a,g,e.status,n.toolCount,t]);return b?s.jsxs("div",{className:`mb-1 rounded-lg border transition-colors ${a?"border-accent-purple/30 bg-accent-purple/5":g?"border-accent-red/20 bg-accent-red/5":"border-border-muted/50 bg-bg-secondary/30"}`,children:[s.jsxs("div",{className:`flex items-center gap-1.5 px-3 py-2 ${w?"cursor-pointer":""}`,onClick:w?f:void 0,children:[s.jsx("div",{className:`w-5 h-5 rounded-full bg-accent-purple/20 flex items-center justify-center flex-shrink-0 ${a?"animate-pulse":""}`,children:s.jsx(ct,{size:12,className:"text-accent-purple"})}),s.jsx("span",{className:"text-[13px] font-semibold text-accent-purple",children:h}),_&&s.jsxs("span",{className:"text-xs text-text-tertiary truncate",children:["· ",_]}),s.jsx("span",{className:"flex-1"}),c&&s.jsx("span",{className:"text-[11px] text-text-tertiary",children:c}),a&&s.jsx(De,{size:12,className:"text-accent-purple animate-spin"}),g&&s.jsx(Cr,{size:12,className:"text-accent-red"}),!a&&!g&&e.status==="completed"&&s.jsx(Ye,{size:12,className:"text-accent-green"}),w&&!a&&(o?s.jsx(It,{size:12,strokeWidth:2,className:"text-text-tertiary flex-shrink-0"}):s.jsx(Nt,{size:12,strokeWidth:2,className:"text-text-tertiary flex-shrink-0"}))]}),y&&s.jsx("div",{className:"px-3 pb-2 pt-0 ml-2.5 pl-3 border-l border-accent-purple/20",children:i.map(v=>{if(v.type==="message")return s.jsx(Pl,{entry:v,isActive:a},v.id);const k=r.get(v.toolCallId);return k?k.toolName==="SendMessage"?s.jsx(jl,{toolCall:k},k.id):s.jsx(Pr,{toolCall:k},k.id):null})})]}):s.jsxs("div",{className:"mb-0.5",children:[s.jsxs("div",{className:`flex items-center gap-1.5 py-0.5 ${w?"cursor-pointer hover:bg-bg-hover/30 rounded-md -mx-1 px-1":""}`,onClick:w?f:void 0,children:[s.jsx("div",{className:`w-5 h-5 rounded-full bg-accent-purple/20 flex items-center justify-center flex-shrink-0 ${a?"animate-pulse":""}`,children:s.jsx(ct,{size:12,className:"text-accent-purple"})}),s.jsx("span",{className:"text-[13px] font-semibold text-accent-purple",children:h}),_&&s.jsxs("span",{className:"text-xs text-text-tertiary truncate",children:["· ",_]}),S&&s.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded bg-bg-secondary text-text-tertiary",children:t("tool.background")}),s.jsx("span",{className:"flex-1"}),c&&s.jsx("span",{className:"text-[11px] text-text-tertiary",children:c}),a&&s.jsx(De,{size:12,className:"text-accent-purple animate-spin"}),g&&s.jsx(Cr,{size:12,className:"text-accent-red"}),w&&!a&&(o?s.jsx(It,{size:12,strokeWidth:2,className:"text-text-tertiary flex-shrink-0"}):s.jsx(Nt,{size:12,strokeWidth:2,className:"text-text-tertiary flex-shrink-0"}))]}),y&&s.jsx("div",{className:"ml-2.5 pl-3 border-l border-accent-purple/25",children:i.map(v=>{if(v.type==="message")return s.jsx(Pl,{entry:v,isActive:a},v.id);const k=r.get(v.toolCallId);return k?k.toolName==="SendMessage"?s.jsx(jl,{toolCall:k},k.id):s.jsx(Pr,{toolCall:k},k.id):null})})]})}function jl({toolCall:e}){const{t}=ue(),r=he(e),i=String(r.type||"message"),a=r.recipient?String(r.recipient):void 0,g=r.summary?String(r.summary):void 0;let b="",n=s.jsx(sc,{size:10,className:"text-text-tertiary"});switch(i){case"message":b=a?`@${a}`:"message";break;case"broadcast":b="@team";break;case"shutdown_request":b=a?`@${a} · shutdown`:"shutdown";break;case"shutdown_response":b=r.approve!==!1?t("tool.taskCompleted"):t("tool.shutdownRejected"),n=s.jsx(Ye,{size:10,className:"text-accent-green"});break;case"plan_approval_response":b=a?`@${a} · ${r.approve!==!1?t("tool.approved"):t("tool.rejected")}`:t("tool.planResponse");break;default:b=a?`@${a}`:i}return s.jsxs("div",{className:"flex items-center gap-1.5 py-0.5 text-xs text-text-tertiary",children:[n,s.jsx("span",{className:"font-medium text-accent-purple",children:b}),g&&s.jsx("span",{className:"truncate",children:g}),s.jsx(Pc,{status:e.status})]})}function Pr({toolCall:e}){var S,w;const{t}=ue(),r=Up(e),[i,a]=O.useState(()=>e.status==="failed");if(O.useEffect(()=>{e.status==="failed"&&a(!0)},[e.status]),e.subagent)return s.jsx(Wp,{toolCall:e});const g=r.Icon,b=e.status==="completed"||e.status==="failed",n=!!r.render||e.result!==void 0&&r===jc,o=(S=r.getTitle)==null?void 0:S.call(r,e,t),d=Mp(e),f=o||(e.kind==="execute"&&d?d:void 0)||e.name||e.toolName||t("tool.defaultName"),_=((w=r.getSummary)==null?void 0:w.call(r,e,t))||(e.kind!=="execute"?d:void 0);return s.jsxs("div",{className:"mb-0.5",children:[s.jsxs("button",{onClick:()=>n&&a(!i),className:"flex items-center gap-1.5 py-0.5 text-left w-full rounded-md transition-colors hover:bg-bg-hover/50 cursor-pointer",children:[s.jsx(g,{}),s.jsx("span",{className:"text-[13px] text-text-secondary font-medium truncate",children:f}),_&&s.jsx("span",{className:"text-xs text-text-tertiary truncate flex-1",children:_}),!_&&s.jsx("span",{className:"flex-1"}),s.jsx(Pc,{status:e.status}),n&&s.jsx(It,{size:12,strokeWidth:2,className:`text-text-tertiary flex-shrink-0 transition-transform duration-200 ${i?"rotate-90":""}`})]}),n&&i&&s.jsx(qp,{renderer:r,toolCall:e,t,isFinished:b})]})}function qp({renderer:e,toolCall:t,t:r,isFinished:i}){const a=e.render?e.render(t,r):s.jsx(ze,{result:t.result});return s.jsx("div",{className:"mt-0.5 mb-1",children:s.jsx("div",{className:i?"empty-result-container":"",children:a})})}const Vp=new Set(["TaskCreate","TaskUpdate","TaskList","TaskGet","AskUserQuestion"]);function Kp({entries:e}){const t=e.filter(r=>r.type==="tool_call"?!Vp.has(r.toolName):r.type==="interruption"||r.type==="question");return t.length===0?null:s.jsx("div",{className:"flex flex-col gap-1 mb-2 w-full",children:t.map(r=>r.type==="tool_call"?s.jsx(Pr,{toolCall:r},r.id):r.type==="interruption"?s.jsx(yp,{interruption:r},r.id):r.type==="question"?s.jsx(xp,{question:r},r.id):null)})}function Yp(e){if(!e)return!0;const t=e.trimStart();return!!/^\/clear\b/.test(t)}function Xp(e){const t=[];for(const r of e)if(r.type==="message"){const i=r;if(i.isCompactInternal){const a=t[t.length-1];a&&a.kind==="compact_group"?a.entries.push(i):t.push({kind:"compact_group",entries:[i]})}else if(i.role==="user"&&i.channel)t.push({kind:"channel_incoming",entry:i});else if(i.role==="user"){if(Yp(i.content))continue;t.push({kind:"user",entry:i})}else t.push({kind:"assistant_message",entry:i})}else{const i=t[t.length-1];i&&i.kind==="assistant_tools"?i.entries.push(r):t.push({kind:"assistant_tools",entries:[r]})}return t}function Ul(e){var t;switch(e.kind){case"user":case"assistant_message":case"channel_incoming":return e.entry.timestamp;case"compact_group":return(t=e.entries[0])==null?void 0:t.timestamp;case"assistant_tools":return}}function Zp(e,t=150){return e.scrollHeight-e.scrollTop-e.clientHeight<t}function $l(){const{t:e}=ue(),r=Ot(i=>i.resolved)==="dark"?Jl:ec;return s.jsxs("div",{className:"empty-state",children:[s.jsx("div",{className:"empty-state-logo",children:s.jsx("img",{src:r,alt:"CodeBuddy"})}),s.jsx("h1",{className:"empty-state-slogan",children:e("chat.empty.slogan")})]})}function Qp({onClickCloseBottomSheet:e}={}){const{timeline:t,isAgentRunning:r,stopReason:i,errorMessage:a,historyLoading:g}=Le(),b=O.useRef(null),n=O.useRef(null),{t:o,resolved:d}=ue(),[f,h]=O.useState(null);O.useEffect(()=>{if(!f)return;const N=R=>{R.key==="Escape"&&h(null)};return document.addEventListener("keydown",N),()=>document.removeEventListener("keydown",N)},[f]);const _=O.useRef(!0),S=O.useRef(0),w=O.useRef(!1),y=O.useMemo(()=>Xp(t),[t]),c=y.length===0,[p,l]=O.useState(!0),[u,m]=O.useState(!1),x=O.useRef(!1);O.useEffect(()=>{if(!c&&!x.current){m(!0);const N=setTimeout(()=>{l(!1),x.current=!0},600);return()=>clearTimeout(N)}},[c]);const v=O.useCallback(()=>{if(w.current)return;const N=n.current;N&&(_.current=Zp(N))},[]);O.useEffect(()=>{const N=t.length;if(N>S.current){const R=t[S.current];(R==null?void 0:R.type)==="message"&&R.role==="user"&&(_.current=!0)}S.current=N},[t]),O.useEffect(()=>{if(!_.current)return;const N=n.current;N&&(w.current=!0,N.scrollTop=N.scrollHeight,requestAnimationFrame(()=>{w.current=!1}))},[t,r]);const k=t[t.length-1],E=(k==null?void 0:k.type)==="message"&&k.streaming,C=E&&!!k.thinking&&!k.content;return s.jsxs("div",{ref:n,onScroll:v,onClick:()=>e==null?void 0:e(),className:"absolute inset-0 overflow-y-auto overflow-x-hidden",children:[p&&s.jsx("div",{className:`empty-state-wrapper${u?" empty-state-fadeout":""}`,children:s.jsx($l,{})}),!p&&g&&t.length===0&&s.jsx("div",{className:"flex items-center justify-center min-h-[60vh] h-full pb-20",children:s.jsx(Nd,{size:"large"})}),!p&&c&&!r&&!g&&s.jsx($l,{}),!c&&s.jsx("div",{className:"px-4 sm:px-6 pt-6 pb-4 animate-fadeIn",children:s.jsxs("div",{className:"max-w-3xl mx-auto flex flex-col",children:[s.jsx("div",{className:"text-center mb-8",children:s.jsx("span",{className:"text-[13px] text-text-tertiary",children:o("chat.disclaimer")})}),y.map((N,R)=>{var M,H;const B=Ul(N);let A=!1,F="";if(B!==void 0){const z=tr(B);let G=null;for(let T=R-1;T>=0;T--){const D=Ul(y[T]);if(D!==void 0){G=tr(D);break}}z!==G&&(A=!0,F=Mc(B,d))}if(N.kind==="user")return s.jsxs("div",{children:[A&&s.jsx(kt,{label:F}),s.jsx("div",{className:"flex justify-end mb-6",children:s.jsxs("div",{className:"max-w-[85%] sm:max-w-[75%] px-5 py-3 rounded-2xl rounded-tr-sm bg-bg-user border border-transparent",children:[N.entry.images&&N.entry.images.length>0&&s.jsx("div",{className:"flex flex-wrap gap-2 mb-2",children:N.entry.images.map((z,G)=>{const T="url"in z?z.url:`data:${z.mimeType};base64,${z.data}`;return s.jsx("img",{src:T,alt:"",className:"max-w-full h-auto rounded-lg cursor-pointer hover:opacity-80 transition-opacity",style:{maxHeight:360},onClick:()=>h(T)},G)})}),N.entry.files&&N.entry.files.length>0&&s.jsx("div",{className:"flex flex-wrap gap-2 mb-2",children:N.entry.files.map((z,G)=>s.jsxs("div",{className:"flex items-center gap-1.5 px-2.5 py-1.5 rounded-lg bg-bg-primary/50 border border-border-muted/30 max-w-[180px]",children:[s.jsx(tt,{size:14,className:"shrink-0 text-text-tertiary"}),s.jsx("span",{className:"text-[12px] text-text-primary truncate",title:z.name,children:z.name})]},G))}),N.entry.content&&s.jsx("p",{className:"whitespace-pre-wrap break-words text-text-primary text-chat",children:N.entry.content})]})})]},N.entry.id);if(N.kind==="channel_incoming")return s.jsxs("div",{children:[A&&s.jsx(kt,{label:F}),s.jsx(du,{content:N.entry.content,channel:N.entry.channel})]},N.entry.id);if(N.kind==="assistant_message"){if(!N.entry.content&&!N.entry.thinking)return null;const z=R>0?y[R-1]:void 0,G=(z==null?void 0:z.kind)==="channel_incoming";return s.jsxs("div",{children:[A&&s.jsx(kt,{label:F}),G&&z.kind==="channel_incoming"&&s.jsx(uu,{channel:z.entry.channel}),s.jsx("div",{className:"mb-2 w-full",children:s.jsx("div",{className:"flex-1 min-w-0",children:s.jsx(Dc,{message:N.entry})})})]},N.entry.id)}if(N.kind==="assistant_tools"){const z=((M=N.entries[0])==null?void 0:M.id)||`tools-${R}`;return s.jsx(Kp,{entries:N.entries},z)}if(N.kind==="compact_group"){const z=((H=N.entries[0])==null?void 0:H.id)||`compact-${R}`;return s.jsxs("div",{children:[A&&s.jsx(kt,{label:F}),s.jsx(gp,{entries:N.entries})]},z)}return null}),r&&t.length>0&&!E&&!C&&s.jsx("div",{className:"mb-2",children:s.jsxs("span",{className:"inline-flex items-center gap-1.5 text-text-tertiary text-xs",children:[s.jsx(De,{size:12,className:"text-accent-brand animate-spin"}),s.jsx("span",{children:o("chat.thinking")})]})}),i&&!r&&s.jsx("div",{className:"py-2",children:s.jsx("span",{className:"text-xs text-text-tertiary",children:a?`${o("chat.error")}: ${a}`:o("chat.stopped")})})]})}),s.jsx("div",{ref:b,className:"h-6"}),f&&s.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/70 cursor-zoom-out",onClick:()=>h(null),children:s.jsx("img",{src:f,alt:"",className:"max-w-[90vw] max-h-[90vh] object-contain rounded-lg shadow-2xl",onClick:N=>N.stopPropagation()})})]})}const $c="codebuddy.auth.token";function Ht(){try{return sessionStorage.getItem($c)}catch{return null}}function Hc(e){try{sessionStorage.setItem($c,e)}catch{}}function Fe(e){const t={...e},r=Ht();return r&&(t.Authorization=`Bearer ${r}`),t}const zc=Ge(e=>({viewState:"loading",error:null,isSubmitting:!1,checkAuth:async()=>{try{e({viewState:"loading",error:null});const t=await Oe("/api/auth/status",{headers:Fe()});if(!t.ok){e({viewState:"authenticated"});return}const r=await t.json();!r.authEnabled||r.authenticated?e({viewState:"authenticated"}):e({viewState:"login"})}catch(t){console.warn("[auth] Failed to check auth status, falling back to authenticated:",t),e({viewState:"authenticated"})}},login:async t=>{try{e({isSubmitting:!0,error:null});const i=await(await fetch("/api/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:t})})).json();if(i.success){const a=i.token||t;return Hc(a),e({viewState:"authenticated",isSubmitting:!1,error:null}),!0}return e({error:i.error||"login.error.incorrect",isSubmitting:!1}),!1}catch(r){return console.warn("[auth] Login request failed:",r),e({error:"app.connectFailed",isSubmitting:!1}),!1}},clearError:()=>e({error:null})}));function Jp(e,t){const i=Date.now()-e,a=Math.floor(i/6e4),g=Math.floor(i/36e5),b=Math.floor(i/864e5);return t==="zh"?a<1?"刚刚":a<60?`${a} 分钟前`:g<24?`${g} 小时前`:b<30?`${b} 天前`:new Date(e).toLocaleDateString("zh-CN"):a<1?"Just now":a<60?`${a}m ago`:g<24?`${g}h ago`:b<30?`${b}d ago`:new Date(e).toLocaleDateString("en-US")}function eh({isOpen:e,onClose:t,onSwitchSession:r}){const{t:i,resolved:a}=ue(),[g,b]=O.useState([]),[n,o]=O.useState(!0),[d,f]=O.useState(null),[h,_]=O.useState(null),[S,w]=O.useState(null),[y,c]=O.useState(""),p=O.useRef(null),[l,u]=O.useState(null),m=O.useCallback(async()=>{o(!0),f(null);try{const R=await fetch("/sessions",{headers:Fe()});if(!R.ok)throw new Error(`HTTP ${R.status}`);const B=await R.json();b(B.sessions||[])}catch(R){f(R.message||"Unknown error")}finally{o(!1)}},[]);O.useEffect(()=>{e&&m()},[e,m]);const x=O.useCallback(async R=>{try{const B=await fetch(`/sessions/${encodeURIComponent(R.id)}`,{method:"DELETE",headers:Fe()});if(!B.ok){const A=await B.json().catch(()=>({}));throw new Error(A.error||`HTTP ${B.status}`)}b(A=>A.filter(F=>F.id!==R.id))}catch(B){console.error("[history] Delete failed:",B)}finally{u(null)}},[]),v=O.useCallback(async(R,B)=>{const A=B.trim();if(A)try{const F=await fetch(`/sessions/${encodeURIComponent(R.id)}/rename`,{method:"POST",headers:Fe({"Content-Type":"application/json"}),body:JSON.stringify({name:A})});if(!F.ok){const M=await F.json().catch(()=>({}));throw new Error(M.error||`HTTP ${F.status}`)}b(M=>M.map(H=>H.id===R.id?{...H,name:A}:H))}catch(F){console.error("[history] Rename failed:",F)}finally{w(null),c("")}},[]),k=O.useCallback((R,B)=>{B.stopPropagation(),w(R),c(R.name),setTimeout(()=>{var A;return(A=p.current)==null?void 0:A.focus()},50)},[]),E=O.useCallback((R,B)=>{B.stopPropagation(),!R.isCurrent&&u(R)},[]),C=O.useCallback(async R=>{if(!(R.isCurrent||h)){_(R.id);try{await(r==null?void 0:r(R.id)),t()}finally{_(null)}}},[h,r,t]),N=()=>n?s.jsx("div",{className:"history-loading",children:s.jsx(lt,{size:"small",text:i("history.loading")})}):d?s.jsxs("div",{className:"history-error",children:[s.jsx("p",{className:"history-error-text",children:i("history.loadError")}),s.jsx("button",{className:"history-retry-btn",onClick:m,children:i("history.retry")})]}):g.length===0?s.jsxs("div",{className:"history-empty",children:[s.jsx(gc,{size:48,className:"text-text-tertiary"}),s.jsx("p",{className:"history-empty-title",children:i("history.noData")}),s.jsx("p",{className:"history-empty-hint",children:i("history.noDataHint")})]}):s.jsx("div",{className:"history-list",children:g.map((R,B)=>{const A=tr(R.updatedAt),F=B>0?tr(g[B-1].updatedAt):null,M=A!==F;return s.jsxs("div",{children:[M&&s.jsx(kt,{label:Mc(R.updatedAt,a)}),s.jsxs("div",{className:`history-session-item${R.isCurrent?" current":""}${!R.isCurrent&&!h?" clickable":""}`,onClick:()=>!R.isCurrent&&!h&&C(R),children:[s.jsxs("div",{className:"history-session-info",children:[s.jsx("p",{className:"history-session-name",children:R.name}),s.jsxs("div",{className:"history-session-meta",children:[R.isCurrent&&s.jsx("span",{className:"history-session-badge",children:i("history.current")}),s.jsx("span",{children:i("history.messages").replace("{count}",String(R.messageCount))}),s.jsx("span",{children:Jp(R.updatedAt,a)})]})]}),s.jsxs("div",{className:"history-session-actions",children:[h===R.id&&s.jsx("div",{className:"history-session-switching",children:s.jsx("div",{className:"history-session-spinner"})}),h!==R.id&&s.jsxs(s.Fragment,{children:[s.jsx("button",{className:"history-action-btn",title:i("history.rename"),onClick:H=>k(R,H),children:s.jsx(Kd,{size:14})}),!R.isCurrent&&s.jsx("button",{className:"history-action-btn danger",title:i("history.delete"),onClick:H=>E(R,H),children:s.jsx(Mt,{size:14})})]})]})]})]},R.id)})});return s.jsxs(s.Fragment,{children:[s.jsx("div",{className:`history-drawer-overlay ${e?"open":""}`,onClick:t}),s.jsxs("div",{className:`history-drawer ${e?"open":""}`,children:[s.jsxs("div",{className:"history-drawer-header",children:[s.jsxs("div",{children:[s.jsx("h2",{className:"history-drawer-title",children:i("history.title")}),s.jsx("p",{className:"history-drawer-subtitle",children:i("history.description")})]}),s.jsx("button",{onClick:t,className:"history-drawer-close",children:s.jsx(Ie,{size:16})})]}),s.jsx("div",{className:"history-content",children:N()})]}),S&&s.jsx("div",{className:"history-rename-overlay",onClick:()=>w(null),children:s.jsxs("div",{className:"history-rename-dialog",onClick:R=>R.stopPropagation(),children:[s.jsx("h3",{children:i("history.renameTitle")}),s.jsx("input",{ref:p,className:"history-rename-input",value:y,onChange:R=>c(R.target.value),placeholder:i("history.renamePlaceholder"),onKeyDown:R=>{R.key==="Enter"&&y.trim()&&v(S,y),R.key==="Escape"&&w(null)}}),s.jsxs("div",{className:"history-rename-actions",children:[s.jsx("button",{className:"history-rename-cancel",onClick:()=>w(null),children:i("history.renameCancel")}),s.jsx("button",{className:"history-rename-ok",disabled:!y.trim(),onClick:()=>v(S,y),children:i("history.renameOk")})]})]})}),l&&s.jsx("div",{className:"history-delete-overlay",onClick:()=>u(null),children:s.jsxs("div",{className:"history-delete-dialog",onClick:R=>R.stopPropagation(),children:[s.jsx("p",{children:i("history.deleteConfirm")}),s.jsxs("div",{className:"history-delete-actions",children:[s.jsx("button",{className:"history-delete-cancel",onClick:()=>u(null),children:i("history.deleteCancel")}),s.jsx("button",{className:"history-delete-ok",onClick:()=>x(l),children:i("history.deleteOk")})]})]})})]})}const Zo="codebuddy.instances.passwords";function Qo(){try{const e=localStorage.getItem(Zo);return e?JSON.parse(e):{}}catch{return{}}}function th(e,t){const r=Qo();r[e]=t,localStorage.setItem(Zo,JSON.stringify(r))}function rh(e){const t=Qo();delete t[e],localStorage.setItem(Zo,JSON.stringify(t))}function nh(e){return Qo()[e]}const ih=Ge((e,t)=>({instances:[],loading:!1,error:null,showManagerPanel:!1,fetchInstances:async()=>{e({loading:!0,error:null});try{const r=await Oe("/api/instances",{headers:Fe()});if(!r.ok)throw new Error(`Failed to fetch instances: ${r.status}`);const i=await r.json();e({instances:i.instances||[],loading:!1})}catch(r){e({error:r.message,loading:!1})}},addInstance:async(r,i,a)=>{e({error:null});try{const g=await Oe("/api/instances/add",{method:"POST",headers:Fe({"Content-Type":"application/json"}),body:JSON.stringify({url:r,password:i,name:a})});if(!g.ok){const o=await g.json().catch(()=>({}));throw new Error(o.error||`Failed to add instance: ${g.status}`)}const b=await g.json();i&&b.id&&th(b.id,i),await t().fetchInstances()}catch(g){throw e({error:g.message}),g}},removeInstance:async r=>{e({error:null});try{const i=await Oe(`/api/instances/${r}`,{method:"DELETE",headers:Fe()});if(!i.ok){const g=await i.json().catch(()=>({}));throw new Error(g.error||`Failed to remove instance: ${i.status}`)}rh(r),await t().fetchInstances()}catch(i){throw e({error:i.message}),i}},setShowManagerPanel:r=>e({showManagerPanel:r})}));function Gc(){const{hostname:e,protocol:t}=window.location;return e==="localhost"||e==="127.0.0.1"||e==="[::1]"||/^(10\.|172\.(1[6-9]|2\d|3[01])\.|192\.168\.)/.test(e)?!1:t==="https:"}function sh(e){return Gc()?e.tunnelUrl||e.localUrl||void 0:e.localUrl||e.tunnelUrl||void 0}function ah(){const e=Le(i=>i.clearChat),t=Xe(i=>i.disconnect);return{switchToInstance:O.useCallback(async i=>{if(i.isCurrent)return;try{await xe().disconnect()}catch{}e();const a=sh(i);if(!a){console.error("Instance has no accessible URL");return}const g=nh(i.id),b=new URL(a);g&&b.searchParams.set("password",g),window.location.href=b.toString()},[e,t])}}const Wc=4,qc="codebuddy_interaction_mode",Vc="codebuddy_terminal_layout",Kc="codebuddy_terminal_panes";let oh=0;function lh(){return`pane-${Date.now()}-${++oh}`}function jr(e){return{id:e??lh(),ptySessionId:null,ptyStatus:"disconnected",errorMessage:null}}function ft(e){return e.type==="leaf"?1:ft(e.children[0])+ft(e.children[1])}function rr(e){return e.type==="leaf"?[e.paneId]:[...rr(e.children[0]),...rr(e.children[1])]}function ch(){try{const e=sessionStorage.getItem(qc);if(e==="chat"||e==="terminal")return e}catch{}return"chat"}function Hl(e){try{sessionStorage.setItem(qc,e)}catch{}}function dh(){try{const e=sessionStorage.getItem(Vc);if(e)return JSON.parse(e)}catch{}return null}function Vt(e){try{sessionStorage.setItem(Vc,JSON.stringify(e))}catch{}}function uh(){try{const e=sessionStorage.getItem(Kc);if(e)return JSON.parse(e)}catch{}return null}function Kt(e){try{sessionStorage.setItem(Kc,JSON.stringify(e))}catch{}}function ph(){const e=dh(),t=uh();if(e&&t){const i=rr(e);if(i.every(a=>a in t)){const a={};for(const g of i)a[g]={...t[g],ptyStatus:"disconnected",errorMessage:null};return{panes:a,layout:e,activePaneId:i[0]}}}const r=jr();return{panes:{[r.id]:r},layout:{type:"leaf",paneId:r.id},activePaneId:r.id}}function Ur(e,t,r,i){return e.type==="leaf"?e.paneId===t?{type:"split",direction:r,children:[{type:"leaf",paneId:t},{type:"leaf",paneId:i}],ratio:.5}:e:{...e,children:[Ur(e.children[0],t,r,i),Ur(e.children[1],t,r,i)]}}function $r(e,t){if(e.type==="leaf")return e.paneId===t?null:e;const r=$r(e.children[0],t),i=$r(e.children[1],t);return r===null?i:i===null?r:{...e,children:[r,i]}}function Yc(e,t,r){if(t.length===0)return e.type==="split"?{...e,ratio:r}:e;if(e.type==="split"){const[i,...a]=t,g=[...e.children];return g[i]=Yc(g[i],a,r),{...e,children:g}}return e}function zl(e){const t=Ht(),r={"Content-Type":"application/json"};t&&(r.Authorization=`Bearer ${t}`),fetch(`/pty/${e}`,{method:"DELETE",headers:r}).catch(()=>{})}const yr=ph(),me=Ge((e,t)=>({mode:ch(),mainView:"chat",terminalTitle:null,panes:yr.panes,layout:yr.layout,activePaneId:yr.activePaneId,setMode:r=>{Hl(r),e({mode:r,mainView:r==="terminal"?"terminal":"chat"})},setMainView:r=>{const i=r==="terminal"?"terminal":"chat";i!==t().mode&&Hl(i),e({mainView:r,mode:i})},setTerminalTitle:r=>e({terminalTitle:r}),splitPane:(r,i)=>{const a=t(),g=i??a.activePaneId;if(ft(a.layout)>=Wc)return;const b=jr(),n=Ur(a.layout,g,r,b.id),o={...a.panes,[b.id]:b};Vt(n),Kt(o),e({layout:n,panes:o,activePaneId:b.id})},closePane:r=>{const i=t();if(ft(i.layout)<=1)return;const a=$r(i.layout,r);if(!a)return;const g=i.panes[r];g!=null&&g.ptySessionId&&zl(g.ptySessionId);const b={...i.panes};delete b[r];const n=rr(a),o=n.includes(i.activePaneId)?i.activePaneId:n[0];Vt(a),Kt(b),e({layout:a,panes:b,activePaneId:o})},setActivePaneId:r=>e({activePaneId:r}),setRatio:(r,i)=>{const a=Math.max(.1,Math.min(.9,i)),g=Yc(t().layout,r,a);Vt(g),e({layout:g})},setPaneSession:(r,i)=>{const a={...t().panes};a[r]&&(a[r]={...a[r],ptySessionId:i},Kt(a),e({panes:a}))},setPaneStatus:(r,i)=>{const a={...t().panes};a[r]&&(a[r]={...a[r],ptyStatus:i},e({panes:a}))},setPaneError:(r,i)=>{const a={...t().panes};a[r]&&(a[r]={...a[r],errorMessage:i},e({panes:a}))},reset:()=>{const r=t().panes;for(const b of Object.values(r))b.ptySessionId&&zl(b.ptySessionId);const i=jr(),a={type:"leaf",paneId:i.id},g={[i.id]:i};Vt(a),Kt(g),e({panes:g,layout:a,activePaneId:i.id})}}));function hh(e){if(!e.length)return[];const t={};for(const i of e){const a=i.cwd||"remote";t[a]||(t[a]=[]),t[a].push(i)}const r=Object.entries(t).map(([i,a])=>{const g=i.split("/").filter(Boolean);return{cwd:i,directoryName:g[g.length-1]||i,hasCurrent:a.some(b=>b.isCurrent),instances:a.sort((b,n)=>b.isCurrent!==n.isCurrent?b.isCurrent?-1:1:n.startedAt-b.startedAt),latestStartTime:Math.max(...a.map(b=>b.startedAt))}});return r.sort((i,a)=>i.hasCurrent!==a.hasCurrent?i.hasCurrent?-1:1:a.latestStartTime!==i.latestStartTime?a.latestStartTime-i.latestStartTime:a.instances.length-i.instances.length),r}function gh(e){const t=Date.now()-e,r=Math.floor(t/6e4),i=Math.floor(t/36e5),a=Math.floor(t/864e5);return a>0?`${a}d ago`:i>0?`${i}h ago`:r>0?`${r}m ago`:"just now"}function fh(e){const t=e.match(/^\/(?:Users|home)\/[^/]+/);return t?e.replace(t[0],"~"):e}function mh({instance:e,switching:t,switchingId:r,onSwitch:i,onRemove:a,t:g}){var o;const b=r===e.id,n=e.mode==="tunnel"||!!e.tunnelUrl;return s.jsxs("div",{className:"flex items-center gap-3 px-4 py-2.5 hover:bg-bg-hover transition-colors group",children:[s.jsx("div",{className:"flex-shrink-0",children:n?s.jsx(Kr,{size:15,className:"text-text-tertiary"}):s.jsx(ct,{size:15,className:"text-text-tertiary"})}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-2 text-[13px]",children:[s.jsx("span",{className:"text-text-primary font-medium truncate",children:e.id.slice(0,8)}),s.jsx("span",{className:"px-1.5 py-px text-[10px] rounded font-medium bg-text-primary/[0.06] text-text-tertiary",children:g(n?"workspace.instanceTunnel":"workspace.instanceLocal")}),e.isCurrent&&s.jsx("span",{className:"px-1.5 py-px text-[10px] rounded font-medium bg-accent-green/15 text-accent-green",children:g("workspace.instanceCurrent")})]}),((o=e.meta)==null?void 0:o.currentTopic)&&s.jsx("div",{className:"text-[12px] text-text-secondary mt-0.5 truncate",title:e.meta.currentTopic,children:e.meta.currentTopic}),s.jsx("div",{className:"text-[11px] text-text-tertiary mt-0.5",children:gh(e.startedAt)})]}),s.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[!e.isCurrent&&s.jsx("button",{onClick:()=>i(e),disabled:t,className:"opacity-0 group-hover:opacity-100 px-3 py-1 text-[12px] font-medium text-text-primary hover:bg-bg-tertiary rounded-md transition-all disabled:opacity-50 disabled:cursor-not-allowed",children:b?s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(De,{size:12,className:"animate-spin"}),g("workspace.switchingInstance")]}):g("workspace.switchInstance")}),e.manual&&s.jsx("button",{onClick:()=>a(e.id),className:"opacity-0 group-hover:opacity-100 w-7 h-7 flex items-center justify-center rounded-md text-text-tertiary hover:text-accent-red hover:bg-accent-red/10 transition-colors",title:g("instance.remove"),children:s.jsx(Mt,{size:13})})]})]})}function Xc({isOpen:e,onClose:t}){const{instances:r,loading:i,error:a,fetchInstances:g,addInstance:b,removeInstance:n}=ih(),{switchToInstance:o}=ah(),{t:d}=ue(),f=me(ee=>ee.setMainView),h=e!==void 0,[_,S]=O.useState(!1),[w,y]=O.useState(""),[c,p]=O.useState(""),[l,u]=O.useState(""),[m,x]=O.useState(!1),[v,k]=O.useState(null),[E,C]=O.useState(!1),[N,R]=O.useState(!1),[B,A]=O.useState(!1),[F,M]=O.useState(!1),[H,z]=O.useState(null),[G,T]=O.useState(new Set),[D,P]=O.useState(!1),j=Gc(),q=O.useMemo(()=>(j?r.filter(de=>de.isCurrent||de.mode==="tunnel"||de.tunnelUrl):r).slice().sort((de,ne)=>de.isCurrent===ne.isCurrent?0:de.isCurrent?-1:1),[r,j]),K=O.useMemo(()=>hh(q),[q]);O.useEffect(()=>{!D&&K.length>0&&(T(new Set(K.map(ee=>ee.cwd))),P(!0))},[K,D]);const re=!i&&q.length===0&&!a;O.useEffect(()=>{(!h||e)&&(C(!1),g())},[e,h,g]);const J=O.useCallback(()=>{t?t():f("chat")},[t,f]),U=O.useCallback(async()=>{R(!0),A(!1),C(!1);try{await g(),A(!0),setTimeout(()=>A(!1),2e3)}finally{R(!1)}},[g]),I=O.useCallback(async()=>{const ee=c.trim();if(ee){x(!0),k(null);try{await b(ee,l.trim()||void 0,w.trim()||void 0),y(""),p(""),u(""),S(!1)}catch(de){k(de.message)}finally{x(!1)}}},[w,c,l,b]),V=O.useCallback(async ee=>{try{await n(ee)}catch(de){console.error("Remove instance failed:",de)}},[n]),W=O.useCallback(async ee=>{if(!ee.isCurrent){M(!0),z(ee.id);try{await o(ee)}catch{M(!1),z(null)}}},[o]),Q=O.useCallback(ee=>{T(de=>{const ne=new Set(de);return ne.has(ee)?ne.delete(ee):ne.add(ee),ne})},[]);if(h&&!e)return null;if(h)return s.jsxs("div",{className:"fixed inset-0 z-50 bg-bg-primary text-text-primary flex flex-col",children:[s.jsxs("div",{className:"flex items-center justify-between px-6 h-14 border-b border-border-muted bg-bg-primary shrink-0",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("button",{onClick:J,className:"w-8 h-8 flex items-center justify-center rounded-full hover:bg-bg-secondary transition-colors text-text-secondary",children:s.jsx(Vr,{size:18})}),s.jsx("span",{className:"font-semibold text-[15px] tracking-wide",children:d("instance.managerTitle")})]}),s.jsxs("button",{onClick:()=>S(!0),className:"flex items-center gap-2 px-4 py-2 rounded-full bg-accent-brand text-white text-[13px] font-medium hover:bg-accent-brand/90 transition-colors",children:[s.jsx(Ke,{size:14}),d("instance.addInstance")]})]}),s.jsx("div",{className:"flex-1 overflow-y-auto p-6",children:s.jsxs("div",{className:"max-w-3xl mx-auto space-y-4",children:[Z(),ae(),oe()]})})]});return s.jsxs("div",{className:"flex-1 flex flex-col overflow-hidden bg-bg-primary",children:[s.jsx("div",{className:"flex-none border-b border-border-muted px-6 py-4",children:s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{children:[s.jsx("h1",{className:"text-lg font-semibold text-text-primary",children:d("instance.managerTitle")}),s.jsx("p",{className:"text-sm text-text-tertiary mt-1",children:d("instance.subtitle")})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs("button",{onClick:U,disabled:N,className:`flex items-center gap-2 px-3 py-2 rounded-lg border transition-all ${B?"border-green-500/50 text-green-500":N?"opacity-50 cursor-not-allowed border-border-muted text-text-secondary":"border-border-muted text-text-secondary hover:text-text-primary hover:border-accent-brand/50 hover:bg-bg-secondary"}`,title:d("instance.refresh"),children:[B?s.jsx(Ye,{size:16}):s.jsx(Dt,{size:16,className:N?"animate-spin":""}),s.jsx("span",{className:"text-sm",children:d(B?"instance.refreshed":"instance.refresh")})]}),s.jsxs("button",{onClick:()=>S(!0),className:"flex items-center gap-2 px-3 py-2 rounded-lg border border-accent-brand/30 bg-accent-brand text-white text-sm font-medium hover:bg-accent-brand/90 transition-colors",children:[s.jsx(Ke,{size:16}),s.jsx("span",{children:d("instance.addInstance")})]})]})]})}),s.jsxs("div",{className:"flex-1 overflow-y-auto px-4 sm:px-6 py-4",children:[Z(),ae(),oe()]})]});function Z(){return _?s.jsxs("div",{className:"bg-bg-secondary rounded-xl border border-border-muted p-5 space-y-4 mb-4",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("span",{className:"text-[14px] font-medium",children:d("instance.addInstance")}),s.jsx("button",{onClick:()=>{S(!1),k(null)},className:"w-6 h-6 flex items-center justify-center rounded-full hover:bg-bg-tertiary transition-colors text-text-secondary",children:s.jsx(Ie,{size:14})})]}),s.jsxs("div",{className:"space-y-3",children:[s.jsxs("div",{children:[s.jsx("label",{className:"text-[12px] text-text-secondary mb-1.5 block",children:d("instance.name")}),s.jsx("input",{type:"text",value:w,onChange:ee=>y(ee.target.value),placeholder:d("instance.namePlaceholder"),className:"w-full bg-bg-primary text-text-primary text-[14px] border border-border-muted rounded-lg px-3 py-2 outline-none focus:ring-2 focus:ring-accent-brand/20 focus:border-accent-brand/50 transition-all placeholder:text-text-tertiary",onKeyDown:ee=>{ee.key==="Enter"&&c.trim()&&I()}})]}),s.jsxs("div",{children:[s.jsx("label",{className:"text-[12px] text-text-secondary mb-1.5 block",children:d("instance.url")}),s.jsx("input",{type:"url",value:c,onChange:ee=>p(ee.target.value),placeholder:"https://abc-def-ghi.trycloudflare.com",className:"w-full bg-bg-primary text-text-primary text-[14px] border border-border-muted rounded-lg px-3 py-2 outline-none focus:ring-2 focus:ring-accent-brand/20 focus:border-accent-brand/50 transition-all placeholder:text-text-tertiary",onKeyDown:ee=>{ee.key==="Enter"&&c.trim()&&I()}})]}),s.jsxs("div",{children:[s.jsxs("label",{className:"text-[12px] text-text-secondary mb-1.5 block",children:[d("instance.password"),s.jsxs("span",{className:"text-text-tertiary ml-1",children:["(",d("instance.optional"),")"]})]}),s.jsx("input",{type:"password",value:l,onChange:ee=>u(ee.target.value),placeholder:d("instance.passwordPlaceholder"),className:"w-full bg-bg-primary text-text-primary text-[14px] border border-border-muted rounded-lg px-3 py-2 outline-none focus:ring-2 focus:ring-accent-brand/20 focus:border-accent-brand/50 transition-all placeholder:text-text-tertiary",onKeyDown:ee=>{ee.key==="Enter"&&c.trim()&&I()}})]}),v&&s.jsx("div",{className:"text-accent-red text-[12px]",children:v}),s.jsxs("div",{className:"flex justify-end gap-2 pt-1",children:[s.jsx("button",{onClick:()=>{S(!1),k(null)},className:"px-4 py-2 rounded-lg text-[13px] text-text-secondary hover:bg-bg-tertiary transition-colors",children:d("instance.cancel")}),s.jsxs("button",{onClick:I,disabled:!c.trim()||m,className:"px-4 py-2 rounded-lg text-[13px] font-medium bg-accent-brand text-white hover:bg-accent-brand/90 transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2",children:[m&&s.jsx(De,{size:14,className:"animate-spin"}),d("instance.add")]})]})]})]}):null}function ae(){return!a||E?null:s.jsxs("div",{className:"bg-accent-red/10 border border-accent-red/30 rounded-xl p-4 text-accent-red text-[13px] flex items-center justify-between mb-4",children:[s.jsx("span",{children:a}),s.jsx("button",{onClick:()=>C(!0),className:"w-5 h-5 flex items-center justify-center rounded-full hover:bg-accent-red/20 transition-colors shrink-0 ml-3",children:s.jsx(Ie,{size:12})})]})}function oe(){return i&&q.length===0?s.jsx("div",{className:"flex flex-col items-center justify-center h-full text-text-tertiary",children:s.jsx("div",{className:"thinking-text text-sm",children:d("instance.loading")})}):a&&!i&&q.length===0&&!E?s.jsx("div",{className:"flex flex-col items-center justify-center h-full",children:s.jsxs("div",{className:"text-center",children:[s.jsx("div",{className:"text-text-tertiary text-[48px] mb-4 opacity-30",children:"⚠"}),s.jsx("div",{className:"text-text-secondary text-sm mb-4",children:d("instance.error")}),s.jsx("button",{onClick:U,className:"px-4 py-2 rounded-lg bg-accent-brand text-white text-sm font-medium hover:bg-accent-brand/90 transition-colors",children:d("instance.retry")})]})}):re?s.jsxs("div",{className:"flex flex-col items-center justify-center h-full text-text-tertiary",children:[s.jsx(ct,{size:48,className:"mb-4 opacity-30"}),s.jsx("div",{className:"text-sm font-medium mb-1",children:d("instance.noInstances")}),s.jsx("div",{className:"text-xs",children:d("instance.noInstancesHint")})]}):s.jsx("div",{className:`space-y-3 transition-opacity duration-300 ${N?"opacity-50 pointer-events-none":"opacity-100"}`,children:K.map(ee=>{const de=G.has(ee.cwd);return s.jsxs("div",{className:`rounded-xl overflow-hidden ${ee.hasCurrent?"bg-text-primary/[0.03]":"bg-bg-secondary/30"}`,children:[s.jsxs("button",{onClick:()=>Q(ee.cwd),className:"w-full flex items-center gap-3 px-4 py-3 hover:bg-bg-hover/50 transition-colors text-left",children:[s.jsx(lc,{size:18,className:"text-text-secondary flex-shrink-0"}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsx("div",{className:"text-[14px] font-medium text-text-primary truncate",children:ee.directoryName}),s.jsx("div",{className:"text-[11px] text-text-tertiary truncate",children:fh(ee.cwd)})]}),s.jsx("span",{className:"text-[12px] text-text-tertiary flex-shrink-0 mr-1",children:d("workspace.instanceCount").replace("{count}",String(ee.instances.length))}),s.jsx(Nt,{size:16,className:`text-text-tertiary flex-shrink-0 transition-transform duration-200 ${de?"":"-rotate-90"}`})]}),de&&s.jsx("div",{className:"border-t border-border-muted",children:ee.instances.map(ne=>s.jsx(mh,{instance:ne,switching:F,switchingId:H,onSwitch:W,onRemove:V,t:d},ne.id))})]},ee.cwd)})})}}function Yt(e,t){return`${e}@${t}`}async function He(e,t){return Oe(e,{method:"POST",headers:{"Content-Type":"application/json",...Fe()},body:t?JSON.stringify(t):void 0})}const bh=Ge((e,t)=>({plugins:[],loading:!1,error:null,marketplaces:[],marketplaceLoading:!1,availablePlugins:[],browsingMarketplace:null,browsingLoading:!1,browsingError:null,operatingPlugins:new Set,fetchPlugins:async()=>{e({loading:!0,error:null});try{const r=await He("/plugin/list");if(!r.ok)throw new Error(`HTTP ${r.status}`);const i=await r.json();e({plugins:Array.isArray(i)?i:[],loading:!1})}catch(r){console.warn("[plugin-store] fetchPlugins failed:",r),e({error:r.message,loading:!1})}},fetchMarketplaces:async()=>{e({marketplaceLoading:!0});try{const r=await He("/plugin/marketplace/list");if(!r.ok)throw new Error(`HTTP ${r.status}`);const i=await r.json();e({marketplaces:Array.isArray(i)?i:[],marketplaceLoading:!1})}catch(r){console.warn("[plugin-store] fetchMarketplaces failed:",r),e({marketplaceLoading:!1})}},browseMarketplace:async r=>{e({browsingMarketplace:r,browsingLoading:!0,browsingError:null});try{const i=await He("/plugin/browse",{marketplace:r});if(!i.ok){const n=await i.json().catch(()=>null);throw new Error((n==null?void 0:n.message)||`HTTP ${i.status}`)}const a=await i.json(),b=(Array.isArray(a)?a:[]).map(n=>({name:n.name,version:n.version,description:n.description,marketplace:n.marketplaceName||r,installed:!!n.status,author:n.author,license:n.license,homepage:n.homepage,repository:n.repository,keywords:n.keywords,category:n.category,features:n.features,source:n.source}));e({availablePlugins:b,browsingLoading:!1})}catch(i){console.warn("[plugin-store] browseMarketplace failed:",i),e({browsingError:i.message,browsingLoading:!1})}},browseAllMarketplaces:async()=>{const{marketplaces:r}=t();if(r.length!==0){e({browsingMarketplace:"__all__",browsingLoading:!0,browsingError:null});try{const i=await Promise.allSettled(r.map(async o=>{const d=await He("/plugin/browse",{marketplace:o.name});if(!d.ok){const _=await d.json().catch(()=>null);throw new Error((_==null?void 0:_.message)||`HTTP ${d.status}`)}const f=await d.json();return(Array.isArray(f)?f:[]).map(_=>({name:_.name,version:_.version,description:_.description,marketplace:_.marketplaceName||o.name,installed:!!_.status,author:_.author,license:_.license,homepage:_.homepage,repository:_.repository,keywords:_.keywords,category:_.category,features:_.features,source:_.source}))})),a=[];let g=!1;for(const o of i)o.status==="fulfilled"?a.push(...o.value):g=!0;const b=new Set,n=a.filter(o=>{const d=`${o.name}@${o.marketplace}`;return b.has(d)?!1:(b.add(d),!0)});e({availablePlugins:n,browsingLoading:!1,browsingError:g&&n.length===0?"Some marketplaces failed to load":null})}catch(i){console.warn("[plugin-store] browseAllMarketplaces failed:",i),e({browsingError:i.message,browsingLoading:!1})}}},enablePlugin:async(r,i)=>{const a=Yt(r,i);e(g=>({operatingPlugins:new Set(g.operatingPlugins).add(a)}));try{const g=await He("/plugin/enable",{plugin:a});if(!g.ok){const b=await g.json().catch(()=>null);throw new Error((b==null?void 0:b.message)||`HTTP ${g.status}`)}await t().fetchPlugins()}finally{e(g=>{const b=new Set(g.operatingPlugins);return b.delete(a),{operatingPlugins:b}})}},disablePlugin:async(r,i)=>{const a=Yt(r,i);e(g=>({operatingPlugins:new Set(g.operatingPlugins).add(a)}));try{const g=await He("/plugin/disable",{plugin:a});if(!g.ok){const b=await g.json().catch(()=>null);throw new Error((b==null?void 0:b.message)||`HTTP ${g.status}`)}await t().fetchPlugins()}finally{e(g=>{const b=new Set(g.operatingPlugins);return b.delete(a),{operatingPlugins:b}})}},uninstallPlugin:async(r,i)=>{const a=Yt(r,i);e(g=>({operatingPlugins:new Set(g.operatingPlugins).add(a)}));try{const g=await He("/plugin/uninstall",{plugin:a});if(!g.ok){const b=await g.json().catch(()=>null);throw new Error((b==null?void 0:b.message)||`HTTP ${g.status}`)}await t().fetchPlugins()}finally{e(g=>{const b=new Set(g.operatingPlugins);return b.delete(a),{operatingPlugins:b}})}},installPlugin:async(r,i)=>{const a=Yt(r,i);e(g=>({operatingPlugins:new Set(g.operatingPlugins).add(a)}));try{const g=await He("/plugin/install",{plugin:a});if(!g.ok){const n=await g.json().catch(()=>null);throw new Error((n==null?void 0:n.message)||`HTTP ${g.status}`)}await t().fetchPlugins();const b=t();b.browsingMarketplace&&(b.browsingMarketplace==="__all__"?await t().browseAllMarketplaces():await t().browseMarketplace(b.browsingMarketplace))}finally{e(g=>{const b=new Set(g.operatingPlugins);return b.delete(a),{operatingPlugins:b}})}},addMarketplace:async(r,i)=>{const a=await He("/plugin/marketplace/add",{source:r,name:i});if(!a.ok){const g=await a.json().catch(()=>null);throw new Error((g==null?void 0:g.message)||`HTTP ${a.status}`)}await t().fetchMarketplaces()},removeMarketplace:async r=>{const i=await He("/plugin/marketplace/remove",{name:r});if(!i.ok){const a=await i.json().catch(()=>null);throw new Error((a==null?void 0:a.message)||`HTTP ${i.status}`)}await t().fetchMarketplaces()}}));function Zc(){const{t:e}=ue(),{plugins:t,marketplaces:r,loading:i,marketplaceLoading:a,error:g,operatingPlugins:b,availablePlugins:n,browsingLoading:o,browsingError:d,fetchPlugins:f,fetchMarketplaces:h,browseMarketplace:_,browseAllMarketplaces:S,enablePlugin:w,disablePlugin:y,uninstallPlugin:c,installPlugin:p,addMarketplace:l,removeMarketplace:u}=bh(),[m,x]=O.useState("installed"),[v,k]=O.useState(""),[E,C]=O.useState("all"),[N,R]=O.useState(null),[B,A]=O.useState(!1),[F,M]=O.useState(""),[H,z]=O.useState(""),[G,T]=O.useState(!1),[D,P]=O.useState(null),[j,q]=O.useState(null),[K,re]=O.useState(null),[J,U]=O.useState(""),[I,V]=O.useState(""),[W,Q]=O.useState(null),Z=O.useCallback(Y=>{Q(ie=>ie===Y?null:Y)},[]);O.useEffect(()=>{f(),h()},[f,h]),O.useEffect(()=>{m==="browse"&&!J&&r.length>0&&(U("__all__"),S())},[m,r,J,S]);const ae=O.useCallback(async Y=>{R(null);try{Y.status==="enabled"?await y(Y.name,Y.marketplace):await w(Y.name,Y.marketplace)}catch(ie){R(ie.message)}},[w,y]),oe=O.useCallback(async Y=>{R(null),q(null);try{await c(Y.name,Y.marketplace)}catch(ie){R(ie.message)}},[c]),ee=O.useCallback(async Y=>{R(null);try{await p(Y.name,Y.marketplace)}catch(ie){R(ie.message)}},[p]),de=O.useCallback(async()=>{const Y=F.trim();if(Y){T(!0),P(null);try{await l(Y,H.trim()||void 0),M(""),z(""),A(!1)}catch(ie){P(ie.message)}finally{T(!1)}}},[F,H,l]),ne=O.useCallback(async Y=>{R(null),re(null);try{if(await u(Y),J===Y&&r.length>1){const ie=r.find(_e=>_e.name!==Y);ie&&(U(ie.name),_(ie.name))}}catch(ie){R(ie.message)}},[u,J,r,_]),qe=O.useCallback(()=>{f(),h(),m==="browse"&&J&&(J==="__all__"?S():_(J))},[f,h,m,J,_,S]),rt=O.useCallback(Y=>{U(Y),V(""),Y==="__all__"?S():_(Y)},[_,S]),nt=Y=>`${Y.name}@${Y.marketplace}`,Ze=O.useMemo(()=>{const Y=new Set(t.map(ie=>ie.marketplace));return Array.from(Y).sort()},[t]),Ue=O.useMemo(()=>{let Y=t;E!=="all"&&(Y=Y.filter(_e=>_e.marketplace===E));const ie=v.trim().toLowerCase();return ie&&(Y=Y.filter(_e=>_e.name.toLowerCase().includes(ie)||_e.description&&_e.description.toLowerCase().includes(ie)||_e.marketplace.toLowerCase().includes(ie))),Y},[t,E,v]),be=O.useMemo(()=>{let Y=n;const ie=I.trim().toLowerCase();return ie&&(Y=Y.filter(_e=>_e.name.toLowerCase().includes(ie)||_e.description&&_e.description.toLowerCase().includes(ie))),Y},[n,I]),Ve=t.filter(Y=>Y.status==="enabled").length;return s.jsxs("div",{className:"flex-1 flex flex-col overflow-hidden bg-bg-primary",children:[s.jsx("div",{className:"flex-none border-b border-border-muted px-6 py-4",children:s.jsxs("div",{className:"max-w-3xl mx-auto",children:[s.jsxs("div",{className:"flex items-center justify-between mb-4",children:[s.jsxs("div",{children:[s.jsx("h1",{className:"text-lg font-semibold text-text-primary",children:e("plugins.title")}),m==="installed"&&t.length>0&&s.jsxs("p",{className:"text-sm text-text-tertiary mt-0.5",children:[t.length," ",e("plugins.totalCount")," · ",Ve," ",e("plugins.enabled")]}),m==="browse"&&J&&!o&&n.length>0&&s.jsxs("p",{className:"text-sm text-text-tertiary mt-0.5",children:[n.length," ",e("plugins.totalCount")]}),m==="marketplaces"&&r.length>0&&s.jsxs("p",{className:"text-sm text-text-tertiary mt-0.5",children:[r.length," ",e("plugins.totalCount")]})]}),s.jsx("button",{onClick:qe,disabled:i||o,className:`flex items-center gap-2 px-3 py-2 rounded-lg border transition-all ${i||o?"opacity-50 cursor-not-allowed border-border-muted text-text-secondary":"border-border-muted text-text-secondary hover:text-text-primary hover:border-text-primary/20 hover:bg-bg-secondary"}`,title:e("plugins.refresh"),children:s.jsx(Dt,{size:14,className:i||o?"animate-spin":""})})]}),s.jsxs("div",{className:"flex gap-1 border-b border-border-muted",children:[s.jsx("button",{onClick:()=>{x("installed"),R(null)},className:`px-4 py-2.5 text-[13px] font-medium border-b-2 transition-colors ${m==="installed"?"text-text-primary border-text-primary":"text-text-secondary border-transparent hover:text-text-primary"}`,children:e("plugins.installedPlugins")}),s.jsx("button",{onClick:()=>{x("browse"),R(null)},className:`px-4 py-2.5 text-[13px] font-medium border-b-2 transition-colors ${m==="browse"?"text-text-primary border-text-primary":"text-text-secondary border-transparent hover:text-text-primary"}`,children:e("plugins.browseMarketplace")}),s.jsx("button",{onClick:()=>{x("marketplaces"),R(null)},className:`px-4 py-2.5 text-[13px] font-medium border-b-2 transition-colors ${m==="marketplaces"?"text-text-primary border-text-primary":"text-text-secondary border-transparent hover:text-text-primary"}`,children:e("plugins.marketplaces")})]}),m==="installed"&&t.length>0&&s.jsxs("div",{className:"flex items-center gap-2 mt-4",children:[s.jsxs("div",{className:"flex-1 relative",children:[s.jsx(wt,{size:14,className:"absolute left-3 top-1/2 -translate-y-1/2 text-text-tertiary pointer-events-none"}),s.jsx("input",{type:"text",value:v,onChange:Y=>k(Y.target.value),placeholder:e("plugins.searchPlaceholder"),className:"w-full bg-bg-secondary text-text-primary text-[13px] border border-border-muted rounded-lg pl-9 pr-8 py-2 outline-none focus:ring-2 focus:ring-text-primary/10 focus:border-text-primary/30 transition-all placeholder:text-text-tertiary"}),v&&s.jsx("button",{onClick:()=>k(""),className:"absolute right-2.5 top-1/2 -translate-y-1/2 w-4 h-4 flex items-center justify-center rounded-full text-text-tertiary hover:text-text-secondary transition-colors",children:s.jsx(Ie,{size:12})})]}),Ze.length>1&&s.jsxs("select",{value:E,onChange:Y=>C(Y.target.value),className:"bg-bg-secondary text-text-primary text-[13px] border border-border-muted rounded-lg px-2 py-2 outline-none focus:ring-2 focus:ring-text-primary/10 focus:border-text-primary/30 transition-all cursor-pointer shrink-0 max-w-[120px] sm:max-w-[160px]",children:[s.jsx("option",{value:"all",children:e("plugins.allMarketplaces")}),Ze.map(Y=>s.jsx("option",{value:Y,children:Y},Y))]})]}),m==="browse"&&r.length>0&&s.jsxs("div",{className:"flex items-center gap-2 mt-4",children:[s.jsxs("div",{className:"flex-1 relative",children:[s.jsx(wt,{size:14,className:"absolute left-3 top-1/2 -translate-y-1/2 text-text-tertiary pointer-events-none"}),s.jsx("input",{type:"text",value:I,onChange:Y=>V(Y.target.value),placeholder:e("plugins.searchPlaceholder"),className:"w-full bg-bg-secondary text-text-primary text-[13px] border border-border-muted rounded-lg pl-9 pr-8 py-2 outline-none focus:ring-2 focus:ring-text-primary/10 focus:border-text-primary/30 transition-all placeholder:text-text-tertiary"}),I&&s.jsx("button",{onClick:()=>V(""),className:"absolute right-2.5 top-1/2 -translate-y-1/2 w-4 h-4 flex items-center justify-center rounded-full text-text-tertiary hover:text-text-secondary transition-colors",children:s.jsx(Ie,{size:12})})]}),s.jsxs("select",{value:J,onChange:Y=>rt(Y.target.value),className:"bg-bg-secondary text-text-primary text-[13px] border border-border-muted rounded-lg px-2 py-2 outline-none focus:ring-2 focus:ring-text-primary/10 focus:border-text-primary/30 transition-all cursor-pointer shrink-0 max-w-[120px] sm:max-w-[160px]",children:[s.jsx("option",{value:"__all__",children:e("plugins.allMarketplaces")}),r.map(Y=>s.jsx("option",{value:Y.name,children:Y.name},Y.name))]})]})]})}),s.jsx("div",{className:"flex-1 overflow-y-auto px-6 py-6",children:s.jsxs("div",{className:"max-w-3xl mx-auto space-y-6",children:[N&&s.jsxs("div",{className:"bg-accent-red/10 border border-accent-red/30 rounded-xl p-3.5 text-accent-red text-[13px] flex items-center justify-between",children:[s.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[s.jsx(mr,{size:14,className:"shrink-0"}),s.jsxs("span",{className:"truncate",children:[e("plugins.operationFailed"),": ",N]})]}),s.jsx("button",{onClick:()=>R(null),className:"w-5 h-5 flex items-center justify-center rounded-full hover:bg-accent-red/20 transition-colors shrink-0 ml-3",children:s.jsx(Ie,{size:12})})]}),m==="installed"&&s.jsxs(s.Fragment,{children:[i&&t.length===0&&s.jsx("div",{className:"flex flex-col items-center justify-center py-20",children:s.jsx(lt,{size:"small",text:e("plugins.loading")})}),g&&!i&&t.length===0&&s.jsxs("div",{className:"flex flex-col items-center justify-center py-20",children:[s.jsx(mr,{size:40,className:"text-text-tertiary opacity-40 mb-4"}),s.jsx("div",{className:"text-[14px] text-text-secondary font-medium mb-3",children:e("plugins.error")}),s.jsx("button",{onClick:f,className:"px-4 py-2 rounded-lg text-[13px] font-medium bg-text-primary text-white hover:opacity-80 transition-colors",children:e("plugins.retry")})]}),!i&&!g&&t.length===0&&s.jsxs("div",{className:"flex flex-col items-center justify-center py-20 text-text-tertiary",children:[s.jsx(gt,{size:48,className:"mb-4 opacity-30"}),s.jsx("div",{className:"text-[15px] font-medium mb-1.5 text-text-secondary",children:e("plugins.noPlugins")}),s.jsx("div",{className:"text-[13px]",children:e("plugins.noPluginsHint")})]}),t.length>0&&Ue.length===0&&!i&&s.jsxs("div",{className:"flex flex-col items-center justify-center py-16 text-text-tertiary",children:[s.jsx(wt,{size:36,className:"mb-3 opacity-30"}),s.jsx("div",{className:"text-[13px]",children:e("plugins.noSearchResults")})]}),Ue.length>0&&s.jsx("div",{className:"space-y-3",children:Ue.map(Y=>{const ie=nt(Y);return s.jsx(_h,{plugin:Y,isEnabled:Y.status==="enabled",isOperating:b.has(ie),isExpanded:W===ie,confirmUninstall:j===ie,onToggle:()=>ae(Y),onUninstall:()=>oe(Y),onConfirmUninstall:()=>q(ie),onCancelUninstall:()=>q(null),onExpand:()=>Z(ie),t:e},ie)})})]}),m==="browse"&&s.jsxs(s.Fragment,{children:[!a&&r.length===0&&s.jsxs("div",{className:"flex flex-col items-center justify-center py-20 text-text-tertiary",children:[s.jsx(At,{size:48,className:"mb-4 opacity-30"}),s.jsx("div",{className:"text-[15px] font-medium mb-1.5 text-text-secondary",children:e("plugins.noMarketplaces")}),s.jsx("div",{className:"text-[13px]",children:e("plugins.noMarketplacesHint")})]}),o&&n.length===0&&J&&s.jsx("div",{className:"flex flex-col items-center justify-center py-20",children:s.jsx(lt,{size:"small",text:e("plugins.browsingMarketplace")})}),d&&n.length===0&&J&&s.jsxs("div",{className:"flex flex-col items-center justify-center py-20",children:[s.jsx(mr,{size:40,className:"text-text-tertiary opacity-40 mb-4"}),s.jsx("div",{className:"text-[14px] text-text-secondary font-medium mb-3",children:e("plugins.error")}),s.jsx("button",{onClick:()=>J&&_(J),className:"px-4 py-2 rounded-lg text-[13px] font-medium bg-text-primary text-white hover:opacity-80 transition-colors",children:e("plugins.retry")})]}),J&&n.length===0&&!o&&!d&&s.jsxs("div",{className:"flex flex-col items-center justify-center py-20 text-text-tertiary",children:[s.jsx(gt,{size:48,className:"mb-4 opacity-30"}),s.jsx("div",{className:"text-[15px] font-medium mb-1.5 text-text-secondary",children:e("plugins.noAvailablePlugins")}),s.jsx("div",{className:"text-[13px]",children:e("plugins.noAvailablePluginsHint")})]}),n.length>0&&be.length===0&&!o&&s.jsxs("div",{className:"flex flex-col items-center justify-center py-16 text-text-tertiary",children:[s.jsx(wt,{size:36,className:"mb-3 opacity-30"}),s.jsx("div",{className:"text-[13px]",children:e("plugins.noSearchResults")})]}),be.length>0&&s.jsx("div",{className:"space-y-3",children:be.map(Y=>{const ie=`${Y.name}@${Y.marketplace}`;return s.jsx(yh,{plugin:Y,isInstalled:Y.installed,isOperating:b.has(ie),isExpanded:W===ie,onInstall:()=>ee(Y),onExpand:()=>Z(ie),t:e},ie)})})]}),m==="marketplaces"&&s.jsxs("div",{className:"space-y-3",children:[!B&&s.jsxs("button",{onClick:()=>A(!0),className:"flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-[12px] font-medium text-text-primary border border-border-muted hover:bg-bg-tertiary hover:border-text-primary/30 transition-colors",children:[s.jsx(Ke,{size:12}),e("plugins.addMarketplace")]}),B&&s.jsxs("div",{className:"bg-bg-secondary rounded-xl border border-border-muted p-4 space-y-3",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("span",{className:"text-[13px] font-medium",children:e("plugins.addMarketplace")}),s.jsx("button",{onClick:()=>{A(!1),P(null)},className:"w-6 h-6 flex items-center justify-center rounded-full hover:bg-bg-tertiary transition-colors text-text-secondary",children:s.jsx(Ie,{size:12})})]}),s.jsx("input",{type:"text",value:F,onChange:Y=>M(Y.target.value),placeholder:e("plugins.sourcePlaceholder"),className:"w-full bg-bg-primary text-text-primary text-[13px] border border-border-muted rounded-lg px-3 py-2 outline-none focus:ring-2 focus:ring-text-primary/10 focus:border-text-primary/30 transition-all placeholder:text-text-tertiary"}),s.jsx("input",{type:"text",value:H,onChange:Y=>z(Y.target.value),placeholder:e("plugins.namePlaceholder"),className:"w-full bg-bg-primary text-text-primary text-[13px] border border-border-muted rounded-lg px-3 py-2 outline-none focus:ring-2 focus:ring-text-primary/10 focus:border-text-primary/30 transition-all placeholder:text-text-tertiary"}),D&&s.jsx("div",{className:"text-accent-red text-[12px]",children:D}),s.jsxs("div",{className:"flex justify-end gap-2",children:[s.jsx("button",{onClick:()=>{A(!1),P(null)},className:"px-3 py-1.5 rounded-lg text-[12px] text-text-secondary hover:bg-bg-tertiary transition-colors",children:e("plugins.cancel")}),s.jsxs("button",{onClick:de,disabled:!F.trim()||G,className:"px-3 py-1.5 rounded-lg text-[12px] font-medium bg-text-primary text-white hover:opacity-80 transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-1.5",children:[G&&s.jsx(De,{size:12,className:"animate-spin"}),e("plugins.add")]})]})]}),a&&r.length===0&&s.jsx("div",{className:"flex items-center justify-center py-6",children:s.jsx(De,{size:18,className:"animate-spin text-text-tertiary"})}),!a&&r.length===0&&!B&&s.jsxs("div",{className:"flex flex-col items-center justify-center py-20 text-text-tertiary",children:[s.jsx(At,{size:48,className:"mb-4 opacity-30"}),s.jsx("div",{className:"text-[15px] font-medium mb-1.5 text-text-secondary",children:e("plugins.noMarketplaces")}),s.jsx("div",{className:"text-[13px]",children:e("plugins.noMarketplacesHint")})]}),r.length>0&&s.jsx("div",{className:"bg-bg-secondary rounded-xl border border-border-muted overflow-hidden",children:r.map((Y,ie)=>s.jsxs("div",{className:`flex items-center justify-between px-4 py-3 ${ie>0?"border-t border-border-muted":""}`,children:[s.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[s.jsx(At,{size:14,className:"text-text-tertiary shrink-0"}),s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"text-[13px] font-medium truncate",children:Y.name}),Y.type&&s.jsx("div",{className:"text-[11px] text-text-tertiary",children:Y.type})]})]}),s.jsx("div",{className:"flex items-center gap-2 shrink-0",children:K===Y.name?s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("button",{onClick:()=>ne(Y.name),className:"px-2.5 py-1 rounded-md text-[11px] font-medium text-white bg-accent-red hover:bg-accent-red/90 transition-colors",children:e("plugins.removeMarketplace")}),s.jsx("button",{onClick:()=>re(null),className:"px-2.5 py-1 rounded-md text-[11px] text-text-secondary hover:bg-bg-tertiary transition-colors",children:e("plugins.cancel")})]}):s.jsx("button",{onClick:()=>re(Y.name),className:"w-7 h-7 flex items-center justify-center rounded-md text-text-tertiary hover:text-accent-red hover:bg-accent-red/10 transition-colors",title:e("plugins.removeMarketplace"),children:s.jsx(Mt,{size:13})})})]},Y.name))})]})]})})]})}function _h({plugin:e,isEnabled:t,isOperating:r,isExpanded:i,confirmUninstall:a,onToggle:g,onUninstall:b,onConfirmUninstall:n,onCancelUninstall:o,onExpand:d,t:f}){return s.jsxs("div",{className:`group rounded-xl border transition-all ${t?"bg-bg-secondary border-border-muted":"bg-bg-secondary border-border-muted hover:border-border-muted"}`,children:[s.jsxs("div",{className:"flex items-start gap-4 px-5 py-4 cursor-pointer",onClick:d,children:[s.jsx("div",{className:`flex-shrink-0 w-9 h-9 rounded-lg flex items-center justify-center mt-0.5 ${t?"bg-text-primary/8":"bg-bg-tertiary"}`,children:s.jsx(gt,{size:18,className:t?"text-text-primary":"text-text-tertiary"})}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-0.5",children:[s.jsx("span",{className:"text-[14px] font-semibold text-text-primary truncate",children:e.name}),e.version&&s.jsxs("span",{className:"text-[11px] text-text-tertiary shrink-0 font-mono",children:["v",e.version]}),s.jsx("span",{className:`text-[10px] px-1.5 py-px rounded font-medium shrink-0 ${t?"bg-accent-green/15 text-accent-green":"bg-bg-tertiary text-text-tertiary"}`,children:f(t?"plugins.enabled":"plugins.disabled")})]}),e.description&&s.jsx("div",{className:`text-[12px] text-text-secondary leading-relaxed mb-1.5 ${i?"":"line-clamp-2"}`,children:e.description}),s.jsxs("div",{className:"flex items-center gap-1 text-[11px] text-text-tertiary",children:[s.jsx(At,{size:10,className:"shrink-0"}),s.jsx("span",{children:e.marketplace})]})]}),s.jsx("div",{className:"flex items-center gap-1.5 shrink-0 pt-0.5",onClick:h=>h.stopPropagation(),children:r?s.jsx("div",{className:"w-[72px] flex justify-center",children:s.jsx(De,{size:16,className:"animate-spin text-text-tertiary"})}):a?s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx("button",{onClick:b,className:"px-2.5 py-1 rounded-md text-[11px] font-medium text-white bg-accent-red hover:bg-accent-red/90 transition-colors",children:f("plugins.uninstall")}),s.jsx("button",{onClick:o,className:"px-2.5 py-1 rounded-md text-[11px] text-text-secondary hover:bg-bg-tertiary transition-colors",children:f("plugins.cancel")})]}):s.jsxs(s.Fragment,{children:[s.jsxs("button",{onClick:g,className:`px-2.5 py-1.5 rounded-md text-[11px] font-medium transition-colors flex items-center gap-1 ${t?"text-text-secondary border border-border-muted hover:bg-bg-tertiary":"text-text-primary border border-border-muted hover:bg-bg-tertiary"}`,title:f(t?"plugins.disable":"plugins.enable"),children:[t?s.jsx(Xd,{size:11}):s.jsx(Zd,{size:11}),f(t?"plugins.disable":"plugins.enable")]}),s.jsx("button",{onClick:n,className:"w-7 h-7 flex items-center justify-center rounded-md text-text-tertiary hover:text-accent-red hover:bg-accent-red/10 transition-colors opacity-0 group-hover:opacity-100",title:f("plugins.uninstall"),children:s.jsx(Mt,{size:13})})]})})]}),i&&s.jsx(Qc,{plugin:e,t:f})]})}function yh({plugin:e,isInstalled:t,isOperating:r,isExpanded:i,onInstall:a,onExpand:g,t:b}){return s.jsxs("div",{className:`group rounded-xl border transition-all ${t?"bg-bg-secondary border-border-muted":"bg-bg-secondary border-border-muted hover:border-border-muted"}`,children:[s.jsxs("div",{className:"flex items-start gap-4 px-5 py-4 cursor-pointer",onClick:g,children:[s.jsx("div",{className:`flex-shrink-0 w-9 h-9 rounded-lg flex items-center justify-center mt-0.5 ${t?"bg-text-primary/8":"bg-bg-tertiary"}`,children:s.jsx(gt,{size:18,className:t?"text-text-primary":"text-text-tertiary"})}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-0.5",children:[s.jsx("span",{className:"text-[14px] font-semibold text-text-primary truncate",children:e.name}),e.version&&s.jsxs("span",{className:"text-[11px] text-text-tertiary shrink-0 font-mono",children:["v",e.version]}),t&&s.jsx("span",{className:"text-[10px] px-1.5 py-px rounded font-medium shrink-0 bg-accent-green/15 text-accent-green",children:b("plugins.installedLabel")})]}),e.description&&s.jsx("div",{className:`text-[12px] text-text-secondary leading-relaxed mb-1.5 ${i?"":"line-clamp-2"}`,children:e.description}),s.jsxs("div",{className:"flex items-center gap-1 text-[11px] text-text-tertiary",children:[s.jsx(At,{size:10,className:"shrink-0"}),s.jsx("span",{children:e.marketplace})]})]}),s.jsx("div",{className:"flex items-center gap-1.5 shrink-0 pt-0.5",onClick:n=>n.stopPropagation(),children:t?s.jsx("div",{className:"px-2.5 py-1.5 rounded-md text-[11px] font-medium text-text-tertiary bg-bg-tertiary",children:b("plugins.installed")}):r?s.jsx("div",{className:"w-[72px] flex justify-center",children:s.jsx(De,{size:16,className:"animate-spin text-text-tertiary"})}):s.jsxs("button",{onClick:a,className:"px-2.5 py-1.5 rounded-md text-[11px] font-medium text-text-primary border border-border-muted hover:bg-bg-tertiary transition-colors flex items-center gap-1",title:b("plugins.install"),children:[s.jsx(jd,{size:11}),b("plugins.install")]})})]}),i&&s.jsx(Qc,{plugin:e,t:b})]})}function Qc({plugin:e,t}){const r=e.source,i=typeof r=="object"&&r!==null?r.url:void 0,a=typeof r=="object"&&r!==null?r.source:typeof r=="string"?r:void 0;return s.jsxs("div",{className:"border-t border-border-muted mx-5 px-0 py-3.5 space-y-2.5",children:[e.category&&s.jsx(Qe,{label:t("plugins.category"),children:s.jsx("span",{className:"text-[11px] px-2 py-0.5 rounded bg-[#f5a623]/8 text-[#b8860b] font-medium",children:e.category})}),e.author&&s.jsxs(Qe,{label:t("plugins.author"),children:[s.jsx("span",{className:"text-[12px] text-text-primary font-medium",children:e.author.name}),e.author.email&&s.jsx("a",{href:`mailto:${e.author.email}`,className:"text-[11px] text-text-tertiary hover:text-text-primary hover:underline ml-1",onClick:g=>g.stopPropagation(),children:e.author.email}),e.author.url&&s.jsxs("a",{href:e.author.url,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-0.5 text-[11px] text-text-tertiary hover:text-text-primary hover:underline ml-1",onClick:g=>g.stopPropagation(),children:[e.author.url,s.jsx(Gt,{size:9})]})]}),e.license&&s.jsx(Qe,{label:t("plugins.license"),children:s.jsx("span",{className:"text-[12px] text-text-secondary",children:e.license})}),e.homepage&&s.jsx(Qe,{label:t("plugins.homepage"),children:s.jsxs("a",{href:e.homepage,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1 text-[12px] text-text-secondary hover:text-text-primary hover:underline break-all",onClick:g=>g.stopPropagation(),children:[e.homepage,s.jsx(Gt,{size:10,className:"shrink-0 text-text-tertiary"})]})}),e.repository&&s.jsx(Qe,{label:t("plugins.repository"),children:s.jsxs("a",{href:e.repository,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1 text-[12px] text-text-secondary hover:text-text-primary hover:underline break-all",onClick:g=>g.stopPropagation(),children:[e.repository,s.jsx(Gt,{size:10,className:"shrink-0 text-text-tertiary"})]})}),a&&s.jsx(Qe,{label:t("plugins.source"),children:i?s.jsxs("a",{href:i,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1 text-[12px] text-text-secondary hover:text-text-primary hover:underline break-all",onClick:g=>g.stopPropagation(),children:[a,s.jsx(Gt,{size:10,className:"shrink-0 text-text-tertiary"})]}):s.jsx("span",{className:"text-[12px] text-text-secondary font-mono",children:a})}),e.keywords&&e.keywords.length>0&&s.jsx(Qe,{label:t("plugins.keywords"),children:s.jsx("div",{className:"flex flex-wrap gap-1",children:e.keywords.map(g=>s.jsx("span",{className:"text-[10px] px-1.5 py-px rounded bg-bg-tertiary text-text-tertiary",children:g},g))})}),e.features&&e.features.length>0&&s.jsx(Qe,{label:t("plugins.features"),children:s.jsx("ul",{className:"space-y-0.5",children:e.features.map((g,b)=>s.jsxs("li",{className:"text-[12px] text-text-secondary flex items-start gap-1.5",children:[s.jsx("span",{className:"text-text-tertiary shrink-0",children:"·"}),g]},b))})})]})}function Qe({label:e,children:t}){return s.jsxs("div",{className:"flex items-baseline gap-3",children:[s.jsx("span",{className:"text-[11px] text-text-tertiary w-12 shrink-0 text-right",children:e}),s.jsx("div",{className:"flex-1 min-w-0 flex items-baseline flex-wrap gap-1",children:t})]})}const Hr=Ge(e=>({info:null,loading:!1,fetch:async()=>{e({loading:!0});try{const t=await Oe("/gateway/info",{headers:Fe()});if(t.ok){const r=await t.json();e({info:r,loading:!1})}else e({loading:!1})}catch{e({loading:!1})}}}));function Jc(){const{status:e,sessionId:t,currentModel:r,models:i,modes:a,currentMode:g}=Xe(),{info:b,fetch:n}=Hr(),{mode:o,toggle:d}=Ot(),{t:f,locale:h,toggleLocale:_}=ue(),[S,w]=O.useState(null);O.useEffect(()=>{b||n()},[b,n]);const y=O.useCallback((E,C)=>{navigator.clipboard.writeText(E).then(()=>{w(C),setTimeout(()=>w(null),1500)})},[]),c=async E=>{if(t)try{await xe().setModel(t,E)}catch(C){console.error("Model change failed:",C)}},p=async E=>{if(t)try{await xe().setMode(t,E)}catch(C){console.error("Mode change failed:",C)}},l={disconnected:"bg-gray-400",connecting:"bg-accent-yellow animate-pulse",connected:"bg-accent-green",error:"bg-accent-red"}[e],u={connected:"connection.connected",connecting:"connection.connecting",disconnected:"connection.disconnected",error:"connection.error"},m=o==="light"?su:o==="dark"?Wd:iu,x=f(o==="light"?"theme.light":o==="dark"?"theme.dark":"theme.system"),v=h==="system"?Hd:Kr,k=f(h==="zh"?"locale.zh":h==="en"?"locale.en":"locale.system");return s.jsx("div",{className:"settings-view",children:s.jsx("div",{className:"settings-content",children:s.jsxs("div",{className:"settings-sections",children:[s.jsxs("div",{className:"settings-group",children:[s.jsx("h2",{className:"settings-group-title",children:f("sidebar.connectionStatus")}),s.jsxs("div",{className:"settings-card",children:[s.jsxs("div",{className:"settings-row",children:[s.jsx("span",{className:"settings-label",children:f("sidebar.status")}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:`w-2 h-2 rounded-full ${l}`}),s.jsx("span",{className:"settings-value",children:f(u[e]||"connection.disconnected")})]})]}),s.jsxs("div",{className:"settings-row",children:[s.jsx("span",{className:"settings-label",children:f("sidebar.sessionId")}),s.jsx("span",{className:"settings-value font-mono text-[12px]",children:t?t.substring(0,12):f("sidebar.notConnected")})]})]})]}),s.jsxs("div",{className:"settings-group",children:[s.jsx("h2",{className:"settings-group-title",children:f("settings.appearance")}),s.jsxs("div",{className:"settings-card",children:[s.jsxs("div",{className:"settings-row",children:[s.jsx("span",{className:"settings-label",children:f("sidebar.theme")}),s.jsxs("button",{onClick:d,className:"settings-toggle-btn",children:[s.jsx(m,{size:14,className:"text-accent-brand"}),s.jsx("span",{children:x})]})]}),s.jsxs("div",{className:"settings-row",children:[s.jsx("span",{className:"settings-label",children:f("sidebar.language")}),s.jsxs("button",{onClick:_,className:"settings-toggle-btn",children:[s.jsx(v,{size:14,className:"text-accent-brand"}),s.jsx("span",{children:k})]})]})]})]}),i.length>0&&s.jsxs("div",{className:"settings-group",children:[s.jsx("h2",{className:"settings-group-title",children:f("settings.model")}),s.jsx("div",{className:"settings-card",children:s.jsx("select",{value:r,onChange:E=>c(E.target.value),className:"settings-select",children:i.map(E=>s.jsx("option",{value:E.id,children:E.name||E.id},E.id))})})]}),a.length>0&&s.jsxs("div",{className:"settings-group",children:[s.jsx("h2",{className:"settings-group-title",children:f("settings.mode")}),s.jsx("div",{className:"settings-card",children:s.jsx("select",{value:g,onChange:E=>p(E.target.value),className:"settings-select",children:a.map(E=>s.jsx("option",{value:E.id,title:E.description,children:E.name},E.id))})})]}),b&&s.jsxs("div",{className:"settings-group",children:[s.jsx("h2",{className:"settings-group-title",children:f("settings.systemInfo")}),s.jsxs("div",{className:"settings-card",children:[s.jsxs("div",{className:"settings-row",children:[s.jsx("span",{className:"settings-label",children:f("sidebar.cwd")}),s.jsxs("button",{onClick:()=>y(b.cwd,"cwd"),className:"settings-copy-btn",title:b.cwd,children:[s.jsx("span",{className:"truncate",children:b.cwd}),S==="cwd"?s.jsx(Ye,{size:12,className:"shrink-0 text-accent-green"}):s.jsx(Tr,{size:12,className:"shrink-0 text-text-tertiary"})]})]}),s.jsxs("div",{className:"settings-row",children:[s.jsx("span",{className:"settings-label",children:f("sidebar.os")}),s.jsxs("span",{className:"settings-value",children:[b.os," ",b.arch]})]}),s.jsxs("div",{className:"settings-row",children:[s.jsx("span",{className:"settings-label",children:f("sidebar.nodeVersion")}),s.jsx("span",{className:"settings-value",children:b.nodeVersion})]}),s.jsxs("div",{className:"settings-row",children:[s.jsx("span",{className:"settings-label",children:f("sidebar.gatewayMode")}),s.jsx("span",{className:"settings-value capitalize",children:b.gatewayMode})]}),b.tunnelUrl&&s.jsxs("div",{className:"settings-row",children:[s.jsx("span",{className:"settings-label",children:f("sidebar.tunnelUrl")}),s.jsxs("button",{onClick:()=>y(b.tunnelUrl,"tunnel"),className:"settings-copy-btn",title:b.tunnelUrl,children:[s.jsx("span",{className:"truncate",children:b.tunnelUrl.replace(/^https?:\/\//,"")}),S==="tunnel"?s.jsx(Ye,{size:12,className:"shrink-0 text-accent-green"}):s.jsx(Tr,{size:12,className:"shrink-0 text-text-tertiary"})]})]})]})]})]})})})}const vh=3e3;function ed(){const{t:e}=ue(),{setMainView:t}=me(),{setExternalInput:r,sessionId:i}=Xe(),[a,g]=O.useState([]),[b,n]=O.useState(!0),[o,d]=O.useState(null),[f,h]=O.useState(!1),[_,S]=O.useState(!1),w=O.useRef(i);w.current=i;const y=O.useRef(null),c=O.useCallback(()=>{y.current&&(clearInterval(y.current),y.current=null)},[]),p=O.useCallback(async()=>{const v=new URLSearchParams,k=w.current;k&&v.append("sessionId",k);const E=v.toString(),C=`/tasks/templates${E?"?"+E:""}`,N=await fetch(C,{headers:Fe()});if(!N.ok)throw new Error(`HTTP ${N.status}`);const R=await N.json();return g(R.templates||[]),d(R.error||null),R.status},[]),l=O.useCallback(()=>{c(),y.current=setInterval(async()=>{try{const v=await p();v!=="loading"&&(c(),h(!1),v==="done"&&(S(!0),setTimeout(()=>S(!1),2e3)))}catch(v){console.error("[TasksView] Poll error:",v),c(),h(!1),d(v.message||"Failed to load templates")}},vh)},[p,c]);O.useEffect(()=>{let v=!1;return(async()=>{try{if(!w.current){if(v)return;n(!1);return}const E=await p();if(v)return;E==="loading"&&(h(!0),l())}catch(k){if(v)return;console.error("[TasksView] Initial fetch error:",k),d(k.message||"Failed to load templates")}finally{v||n(!1)}})(),()=>{v=!0,c()}},[p,l,c,i]);const u=O.useCallback(async()=>{h(!0),d(null),S(!1);try{const v=new URLSearchParams,k=w.current;k&&v.append("sessionId",k);const E=v.toString(),C=`/tasks/templates/refresh${E?"?"+E:""}`,N=await fetch(C,{method:"POST",headers:Fe()});if(!N.ok)throw new Error(`HTTP ${N.status}`);l()}catch(v){console.error("[TasksView] Refresh trigger error:",v),d(v.message||"Failed to trigger refresh"),h(!1)}},[l]),m=O.useCallback(v=>{r(v.command),t("chat")},[r,t]),x=!b&&a.length===0&&!o;return s.jsxs("div",{className:"flex-1 flex flex-col overflow-hidden bg-bg-primary",children:[s.jsx("div",{className:"flex-none border-b border-border-default px-6 py-4",children:s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{children:[s.jsx("h1",{className:"text-lg font-semibold text-text-primary",children:e("tasks.title")}),s.jsx("p",{className:"text-sm text-text-tertiary mt-1",children:e("tasks.subtitle")})]}),s.jsxs("button",{onClick:u,disabled:f,className:`flex items-center gap-2 px-3 py-2 rounded-lg border transition-all ${_?"border-green-500/50 text-green-500":f?"opacity-50 cursor-not-allowed border-border-default text-text-secondary":"border-border-default text-text-secondary hover:text-text-primary hover:border-accent-brand/50 hover:bg-bg-secondary"}`,title:e("tasks.refresh"),children:[_?s.jsx(Ye,{size:16}):s.jsx(Dt,{size:16,className:f?"animate-spin":""}),s.jsx("span",{className:"text-sm",children:e(_?"tasks.refreshed":"tasks.refresh")})]})]})}),s.jsxs("div",{className:"flex-1 overflow-y-auto px-6 py-6",children:[b&&!f&&s.jsx("div",{className:"flex flex-col items-center justify-center h-full text-text-tertiary",children:s.jsx(lt,{size:"small",text:e("tasks.loading")})}),o&&!b&&s.jsx("div",{className:"flex flex-col items-center justify-center h-full",children:s.jsxs("div",{className:"text-center",children:[s.jsx("div",{className:"text-text-tertiary text-[48px] mb-4 opacity-30",children:"⚠"}),s.jsx("div",{className:"text-text-secondary text-sm mb-4",children:e("tasks.error")}),s.jsx("button",{onClick:u,className:"px-4 py-2 rounded-lg bg-accent-brand text-white text-sm font-medium hover:bg-accent-brand/90 transition-colors",children:e("tasks.retry")})]})}),x&&s.jsxs("div",{className:"flex flex-col items-center justify-center h-full text-text-tertiary",children:[s.jsx("div",{className:"text-[48px] mb-4 opacity-30",children:"📋"}),s.jsx("div",{className:"text-sm font-medium mb-1",children:e("tasks.empty")})]}),a.length>0&&s.jsx("div",{className:`grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3 max-w-6xl transition-opacity duration-300 ${f?"opacity-50 pointer-events-none":"opacity-100"}`,children:a.map(v=>{const k=Sh(v.icon);return s.jsxs("div",{onClick:()=>m(v),className:"group flex items-center gap-4 px-4 py-3.5 rounded-xl border border-border-default hover:border-accent-brand/40 hover:bg-bg-secondary/60 transition-all cursor-pointer",children:[s.jsx("div",{className:"flex-shrink-0 w-10 h-10 rounded-lg bg-bg-secondary flex items-center justify-center group-hover:bg-accent-brand/10 transition-colors",children:s.jsx(k,{size:20,className:"text-text-tertiary group-hover:text-accent-brand transition-colors"})}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("h3",{className:"text-sm font-semibold text-text-primary truncate",children:v.title}),s.jsx("p",{className:"text-xs text-text-tertiary mt-0.5 truncate",children:v.description})]})]},v.id)})})]})]})}function Sh(e){switch(e){case"Newspaper":return bl;case"MessageSquare":return bl;case"GitBranch":return Ud;case"Package":return qd;case"FileText":return tt;case"Zap":return au;case"Clock":return hl;default:return hl}}function Eh({direction:e,ratio:t,onRatioChange:r,children:i}){const a=O.useRef(null),[g,b]=O.useState(!1),n=O.useCallback(h=>{h.preventDefault(),h.stopPropagation(),b(!0);const _=a.current;if(!_)return;const S=_.getBoundingClientRect(),w=c=>{let p;e==="horizontal"?p=(c.clientX-S.left)/S.width:p=(c.clientY-S.top)/S.height,p=Math.max(.1,Math.min(.9,p)),r(p)},y=()=>{b(!1),document.removeEventListener("mousemove",w),document.removeEventListener("mouseup",y),document.body.style.cursor="",document.body.style.userSelect=""};document.addEventListener("mousemove",w),document.addEventListener("mouseup",y),document.body.style.cursor=e==="horizontal"?"col-resize":"row-resize",document.body.style.userSelect="none"},[e,r]),o=e==="horizontal",d=`${t*100}%`,f=`${(1-t)*100}%`;return s.jsxs("div",{ref:a,className:"flex h-full w-full",style:{flexDirection:o?"row":"column"},children:[s.jsx("div",{style:{[o?"width":"height"]:d,overflow:"hidden",display:"flex"},children:i[0]}),s.jsx("div",{className:`split-sash ${o?"split-sash-horizontal":"split-sash-vertical"} ${g?"dragging":""}`,onMouseDown:n}),s.jsx("div",{style:{[o?"width":"height"]:f,overflow:"hidden",display:"flex"},children:i[1]})]})}var vr={exports:{}},Gl;function xh(){return Gl||(Gl=1,(function(e,t){(function(r,i){e.exports=i()})(self,(()=>(()=>{var r={};return(()=>{var i=r;Object.defineProperty(i,"__esModule",{value:!0}),i.FitAddon=void 0,i.FitAddon=class{activate(a){this._terminal=a}dispose(){}fit(){const a=this.proposeDimensions();if(!a||!this._terminal||isNaN(a.cols)||isNaN(a.rows))return;const g=this._terminal._core;this._terminal.rows===a.rows&&this._terminal.cols===a.cols||(g._renderService.clear(),this._terminal.resize(a.cols,a.rows))}proposeDimensions(){if(!this._terminal||!this._terminal.element||!this._terminal.element.parentElement)return;const a=this._terminal._core,g=a._renderService.dimensions;if(g.css.cell.width===0||g.css.cell.height===0)return;const b=this._terminal.options.scrollback===0?0:a.viewport.scrollBarWidth,n=window.getComputedStyle(this._terminal.element.parentElement),o=parseInt(n.getPropertyValue("height")),d=Math.max(0,parseInt(n.getPropertyValue("width"))),f=window.getComputedStyle(this._terminal.element),h=o-(parseInt(f.getPropertyValue("padding-top"))+parseInt(f.getPropertyValue("padding-bottom"))),_=d-(parseInt(f.getPropertyValue("padding-right"))+parseInt(f.getPropertyValue("padding-left")))-b;return{cols:Math.max(2,Math.floor(_/g.css.cell.width)),rows:Math.max(1,Math.floor(h/g.css.cell.height))}}}})(),r})()))})(vr)),vr.exports}var wh=xh(),Sr={exports:{}},Wl;function kh(){return Wl||(Wl=1,(function(e,t){(function(r,i){e.exports=i()})(globalThis,(()=>(()=>{var r={4567:function(b,n,o){var d=this&&this.__decorate||function(l,u,m,x){var v,k=arguments.length,E=k<3?u:x===null?x=Object.getOwnPropertyDescriptor(u,m):x;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")E=Reflect.decorate(l,u,m,x);else for(var C=l.length-1;C>=0;C--)(v=l[C])&&(E=(k<3?v(E):k>3?v(u,m,E):v(u,m))||E);return k>3&&E&&Object.defineProperty(u,m,E),E},f=this&&this.__param||function(l,u){return function(m,x){u(m,x,l)}};Object.defineProperty(n,"__esModule",{value:!0}),n.AccessibilityManager=void 0;const h=o(9042),_=o(9924),S=o(844),w=o(4725),y=o(2585),c=o(3656);let p=n.AccessibilityManager=class extends S.Disposable{constructor(l,u,m,x){super(),this._terminal=l,this._coreBrowserService=m,this._renderService=x,this._rowColumns=new WeakMap,this._liveRegionLineCount=0,this._charsToConsume=[],this._charsToAnnounce="",this._accessibilityContainer=this._coreBrowserService.mainDocument.createElement("div"),this._accessibilityContainer.classList.add("xterm-accessibility"),this._rowContainer=this._coreBrowserService.mainDocument.createElement("div"),this._rowContainer.setAttribute("role","list"),this._rowContainer.classList.add("xterm-accessibility-tree"),this._rowElements=[];for(let v=0;v<this._terminal.rows;v++)this._rowElements[v]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[v]);if(this._topBoundaryFocusListener=v=>this._handleBoundaryFocus(v,0),this._bottomBoundaryFocusListener=v=>this._handleBoundaryFocus(v,1),this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._refreshRowsDimensions(),this._accessibilityContainer.appendChild(this._rowContainer),this._liveRegion=this._coreBrowserService.mainDocument.createElement("div"),this._liveRegion.classList.add("live-region"),this._liveRegion.setAttribute("aria-live","assertive"),this._accessibilityContainer.appendChild(this._liveRegion),this._liveRegionDebouncer=this.register(new _.TimeBasedDebouncer(this._renderRows.bind(this))),!this._terminal.element)throw new Error("Cannot enable accessibility before Terminal.open");this._terminal.element.insertAdjacentElement("afterbegin",this._accessibilityContainer),this.register(this._terminal.onResize((v=>this._handleResize(v.rows)))),this.register(this._terminal.onRender((v=>this._refreshRows(v.start,v.end)))),this.register(this._terminal.onScroll((()=>this._refreshRows()))),this.register(this._terminal.onA11yChar((v=>this._handleChar(v)))),this.register(this._terminal.onLineFeed((()=>this._handleChar(`
|
|
397
|
+
${r("tool.moreLinesCount").replace("{count}",String(a.length-t))}`})]})}function Ct({src:e,alt:t}){const r=e.startsWith("file://")?et(e.replace("file://","")):e.startsWith("/")&&!e.startsWith("/api/")?et(e):e;return s.jsx("div",{className:"rounded-md overflow-hidden bg-bg-secondary/40 p-2",children:s.jsx("img",{src:r,alt:t||"Image",className:"max-w-full max-h-64 rounded object-contain",loading:"lazy"})})}const Ml={read:{Icon:wp,render:e=>{const t=Fr(e);if(t){const i=he(e),a=i.file_path?String(i.file_path).split("/").pop():void 0;return s.jsx(Ct,{src:t,alt:a})}if(e.result===void 0)return null;const r=je(e.result);return r?s.jsx("pre",{className:"text-text-secondary font-mono text-xs px-2.5 py-1.5 whitespace-pre overflow-x-auto max-h-64 overflow-y-auto bg-bg-secondary/40 rounded-md",children:r}):null}},edit:{Icon:kp,render:e=>{const t=Dp(e.content);if(t){const r=e.status==="failed";return s.jsx("div",{className:r?"opacity-40":"",children:s.jsx(Jt,{path:t.path,oldText:t.oldText,newText:t.newText,maxHeight:"max-h-64"})})}return e.result!==void 0?s.jsx(ze,{result:e.result}):null}},execute:{Icon:Cp,render:e=>{const t=he(e),i=(e.result!==void 0?Pp(e.result):"")||(e.result!==void 0?je(e.result):"");return s.jsxs("div",{className:"rounded-md overflow-hidden bg-bg-secondary/40",children:[!!t.command&&s.jsxs("pre",{className:"px-2.5 py-1.5 font-mono text-xs whitespace-pre overflow-x-auto text-text-primary",children:[s.jsx("span",{className:"text-text-tertiary select-none",children:"$ "}),String(t.command)]}),i&&s.jsx("pre",{className:"text-text-secondary font-mono text-xs px-2.5 py-1.5 whitespace-pre-wrap break-words max-h-60 overflow-y-auto border-t border-border-muted/30",children:i})]})}},search:{Icon:Bc,render:e=>s.jsx(jp,{result:e.result})},fetch:{Icon:Mr,render:e=>{const t=he(e);return!t.url&&!t.query?null:s.jsxs("div",{className:"text-xs font-mono px-1 space-y-0.5",children:[!!t.url&&s.jsx("div",{className:"text-text-secondary truncate",children:String(t.url)}),!!t.prompt&&s.jsx("div",{className:"text-text-tertiary line-clamp-2",children:String(t.prompt)}),!!t.query&&s.jsx("div",{className:"text-text-secondary",children:String(t.query)})]})}}},Bl={ImageGen:{Icon:Ol,getTitle:(e,t)=>t("tool.imageGen"),getSummary:e=>{const t=he(e);return t.prompt?Ne(String(t.prompt),60):void 0},render:(e,t)=>{const r=Fr(e);if(r)return s.jsx(Ct,{src:r,alt:t("tool.generatedImage")});const i=Dl(e.result);return i?s.jsx(Ct,{src:et(i),alt:t("tool.generatedImage")}):e.result!==void 0?s.jsx(ze,{result:e.result,maxLines:6}):null}},ImageEdit:{Icon:Ol,getTitle:(e,t)=>t("tool.imageEdit"),getSummary:e=>{const t=he(e);return t.prompt?Ne(String(t.prompt),60):void 0},render:(e,t)=>{const r=Fr(e);if(r)return s.jsx(Ct,{src:r,alt:t("tool.editedImage")});const i=Dl(e.result);return i?s.jsx(Ct,{src:et(i),alt:t("tool.editedImage")}):e.result!==void 0?s.jsx(ze,{result:e.result,maxLines:6}):null}},ToolSearch:{Icon:Bc,getTitle:(e,t)=>t("tool.toolSearch"),getSummary:e=>{const t=he(e);if(t.query)return String(t.query);if(t.tool_names)return`[${String(t.tool_names)}]`},render:e=>e.result===void 0?null:s.jsx(ze,{result:e.result,maxLines:12})},TeamCreate:{Icon:Il,getTitle:(e,t)=>t("tool.teamCreate"),getSummary:e=>{const t=he(e),r=t.name?String(t.name):void 0,i=t.description?String(t.description):void 0;return r&&i?`${r} · ${i}`:r||i},render:e=>{if(e.result===void 0)return null;const t=je(e.result);return t?s.jsxs("div",{className:"flex items-center gap-1.5 px-2.5 py-1.5 bg-bg-secondary/40 rounded-md text-xs",children:[s.jsx(ac,{size:12,className:"text-accent-green flex-shrink-0"}),s.jsx("span",{className:"text-text-secondary",children:Ne(t,120)})]}):null}},TeamDelete:{Icon:Il,getTitle:(e,t)=>t("tool.teamDelete"),getSummary:e=>{const t=he(e);return t.team_name?String(t.team_name):void 0}},TaskCreate:{Icon:Ll,getTitle:(e,t)=>t("tool.taskCreate"),getSummary:e=>{const t=he(e);return t.subject?Ne(String(t.subject),80):void 0}},TaskUpdate:{Icon:Ap,getTitle:(e,t)=>t("tool.taskUpdate"),getSummary:e=>{const t=he(e),r=[];return t.taskId&&r.push(`#${t.taskId}`),t.status&&r.push(String(t.status)),t.subject&&r.push(Ne(String(t.subject),40)),r.join(" · ")||void 0}},TaskList:{Icon:Ll,getTitle:(e,t)=>t("tool.taskList")},TaskGet:{Icon:Rp,getTitle:(e,t)=>t("tool.taskGet"),getSummary:e=>{const t=he(e);return t.taskId?`#${t.taskId}`:void 0},render:e=>e.result===void 0?null:s.jsx(ze,{result:e.result,maxLines:8})},SendMessage:{Icon:Tp,getTitle:(e,t)=>{const r=he(e),i=String(r.type||"message"),a=r.recipient?String(r.recipient):void 0;switch(i){case"message":return a?`@${a}`:t("tool.sendMessage");case"broadcast":return"@team";case"shutdown_request":return a?`@${a} · shutdown`:t("tool.shutdown");case"shutdown_response":return r.approve!==!1?t("tool.taskCompleted"):t("tool.shutdownRejected");case"plan_approval_response":return a?`@${a} · ${r.approve!==!1?t("tool.approved"):t("tool.rejected")}`:t("tool.planResponse");default:return a?`@${a}`:i}},getSummary:e=>{const t=he(e);return t.summary?Ne(String(t.summary),80):void 0},render:e=>{if(e.result===void 0)return null;const t=je(e.result);return t?s.jsx("div",{className:"text-xs text-text-secondary px-2.5 py-1.5 bg-bg-secondary/40 rounded-md",children:Ne(t,200)}):null}},WebSearch:{Icon:Mr,getTitle:(e,t)=>t("tool.webSearch"),getSummary:e=>{const t=he(e);return t.query?Ne(String(t.query),80):void 0},render:e=>e.result===void 0?null:s.jsx(ze,{result:e.result,maxLines:10})},WebFetch:{Icon:Mr,getTitle:(e,t)=>t("tool.webFetch"),getSummary:e=>{const t=he(e);return t.url?Ne(String(t.url),60):void 0},render:e=>{const t=he(e);return s.jsxs("div",{className:"text-xs font-mono px-1 space-y-0.5",children:[!!t.url&&s.jsx("div",{className:"text-text-secondary truncate",children:String(t.url)}),!!t.prompt&&s.jsx("div",{className:"text-text-tertiary line-clamp-2",children:String(t.prompt)})]})}},SaveMemory:{Icon:Np,getTitle:(e,t)=>t("tool.saveMemory"),getSummary:e=>{const t=he(e);return t.content?Ne(String(t.content),60):void 0}},AskUserQuestion:{Icon:Ip,getTitle:(e,t)=>t("tool.askUserQuestion"),getSummary:e=>{const r=he(e).questions;if(!r||r.length===0)return;if(r.length===1)return r[0].question?Ne(String(r[0].question),80):r[0].header;const i=r.map(a=>a.header||"?").join(", ");return`${r.length} questions: ${i}`},render:(e,t)=>{const i=he(e).questions;return!i||i.length===0?e.result!==void 0?s.jsx(ze,{result:e.result,maxLines:6}):null:s.jsxs("div",{className:"space-y-2",children:[i.map((a,g)=>s.jsxs("div",{className:"rounded-md bg-bg-secondary/40 overflow-hidden",children:[s.jsxs("div",{className:"px-2.5 py-1.5 text-xs",children:[a.header&&s.jsx("span",{className:"inline-block px-1.5 py-0.5 rounded bg-accent-brand/10 text-accent-brand text-[11px] font-medium mr-1.5",children:a.header}),s.jsx("span",{className:"text-text-primary font-medium",children:a.question}),a.multiSelect&&s.jsxs("span",{className:"text-[10px] text-text-tertiary ml-1",children:["(",t("question.multiLabel"),")"]})]}),a.options&&a.options.length>0&&s.jsx("div",{className:"border-t border-border-muted/30 px-2.5 py-1",children:a.options.map((b,n)=>s.jsxs("div",{className:"flex items-baseline gap-1.5 py-0.5 text-xs",children:[s.jsx("span",{className:"text-text-secondary font-medium",children:b.label}),b.description&&s.jsxs("span",{className:"text-text-tertiary",children:["— ",Ne(String(b.description),60)]})]},n))})]},g)),e.result!==void 0&&s.jsx(ze,{result:e.result,maxLines:4})]})}},EnterPlanMode:{Icon:Lp,getTitle:(e,t)=>t("tool.enterPlanMode"),render:e=>{if(e.result===void 0)return null;const t=je(e.result);if(!t)return null;const r=e.result,i=r!=null&&r.planFilePath?String(r.planFilePath):void 0;return s.jsxs("div",{className:"text-xs px-2.5 py-1.5 bg-bg-secondary/40 rounded-md space-y-1",children:[i&&s.jsxs("div",{className:"flex items-center gap-1.5 text-text-tertiary",children:[s.jsx(oc,{size:10,className:"flex-shrink-0"}),s.jsx("span",{className:"font-mono truncate",children:i})]}),!i&&t&&s.jsx("div",{className:"text-text-secondary",children:Ne(t,200)})]})}},ExitPlanMode:{Icon:Op,getTitle:(e,t)=>t("tool.exitPlanMode"),getSummary:(e,t)=>{const i=he(e).allowedPrompts;if(i&&i.length>0)return t("tool.permissionsCount").replace("{count}",String(i.length))},render:(e,t)=>{const i=he(e).allowedPrompts,a=i&&i.length>0,g=e.result!==void 0;return!a&&!g?null:s.jsxs("div",{className:"space-y-1",children:[a&&s.jsxs("div",{className:"rounded-md bg-bg-secondary/40 px-2.5 py-1.5",children:[s.jsx("div",{className:"text-[11px] text-text-tertiary mb-1",children:t("tool.allowedActions")}),i.map((b,n)=>s.jsxs("div",{className:"flex items-center gap-1.5 text-xs py-0.5",children:[s.jsx(bc,{size:10,className:"text-text-tertiary flex-shrink-0"}),s.jsx("span",{className:"text-text-secondary",children:b.prompt})]},n))]}),g&&s.jsx(ze,{result:e.result,maxLines:6})]})}},Skill:{Icon:Fc,getTitle:(e,t)=>t("tool.skill"),getSummary:e=>{const t=he(e);return t.skill?String(t.skill):t.command?String(t.command):void 0}}};function Up(e){return e.toolName&&Bl[e.toolName]?Bl[e.toolName]:e.kind&&Ml[e.kind]?Ml[e.kind]:jc}function $p(e){return!!(e==null||e===""||Array.isArray(e)&&e.length===0||typeof e=="object"&&Object.keys(e).length===0)}const jc={Icon:Fc,getSummary:e=>{const t=he(e),r=Bp(t);return r||void 0},render:e=>{const t=he(e),r=Object.keys(t).length>0,i=e.result,a=i!==void 0&&!$p(i)&&je(i).length>0;return!r&&!a?null:s.jsxs("div",{className:"space-y-1 max-h-64 overflow-y-auto",children:[r&&s.jsx("pre",{className:"text-text-tertiary font-mono text-xs px-2.5 py-1.5 whitespace-pre-wrap break-words bg-bg-secondary/40 rounded-md",children:JSON.stringify(t,null,2)}),a&&s.jsx("pre",{className:"text-text-secondary font-mono text-xs px-2.5 py-1.5 whitespace-pre-wrap break-words bg-bg-secondary/40 rounded-md",children:je(i)})]})}},Uc="subagent-collapse-pref";function Fl(){try{return localStorage.getItem(Uc)==="true"}catch{return!1}}function Hp(e){try{localStorage.setItem(Uc,String(e))}catch{}}function zp(){return s.jsxs("span",{className:"inline-flex items-center gap-0.5 ml-1 align-middle",children:[s.jsx("span",{className:"w-1 h-1 rounded-full bg-accent-purple animate-[dotPulse_1.4s_ease-in-out_0s_infinite]"}),s.jsx("span",{className:"w-1 h-1 rounded-full bg-accent-purple animate-[dotPulse_1.4s_ease-in-out_0.2s_infinite]"}),s.jsx("span",{className:"w-1 h-1 rounded-full bg-accent-purple animate-[dotPulse_1.4s_ease-in-out_0.4s_infinite]"})]})}function Pl({entry:e,isActive:t}){const r=e.streaming&&t,i=e.content&&e.content.trim().length>0;return!i&&!r?s.jsx(s.Fragment,{}):s.jsxs("div",{className:"markdown-body text-chat text-text-primary py-0.5",children:[i&&s.jsx(Gr,{remarkPlugins:[Wr],children:e.content}),r&&s.jsx(zp,{})]})}function Gp(e){return O.useMemo(()=>{const t=e.subagentTimeline||[];let r=0,i=0;for(const a of t)a.type==="tool_call_ref"?r++:a.type==="message"&&i++;return{toolCount:r,messageCount:i}},[e.subagentTimeline])}function Wp({toolCall:e}){var p,l,u,m,x;const{t}=ue(),r=Le(v=>v.childToolCalls),i=e.subagentTimeline||[],a=e.status==="running",g=e.status==="failed",b=!!((p=e.subagent)!=null&&p.memberName),n=Gp(e),[o,d]=O.useState(()=>!a&&Fl());O.useEffect(()=>{d(a?!1:Fl())},[a]);const f=O.useCallback(()=>{a||d(v=>{const k=!v;return Hp(k),k})},[a]),h=(l=e.subagent)!=null&&l.memberName?`@${e.subagent.memberName}`:((u=e.subagent)==null?void 0:u.type)||t("tool.agent"),_=((m=e.subagent)==null?void 0:m.description)||"",S=(x=e.subagent)==null?void 0:x.isBackground,w=i.length>0,y=w&&!o,c=O.useMemo(()=>{if(a)return null;const v=[];return g?v.push(t("tool.failed")):e.status==="completed"&&v.push(t("tool.completed")),n.toolCount>0&&v.push(t("tool.toolsCount").replace("{count}",String(n.toolCount))),v.length>0?v.join(" · "):null},[a,g,e.status,n.toolCount,t]);return b?s.jsxs("div",{className:`mb-1 rounded-lg border transition-colors ${a?"border-accent-purple/30 bg-accent-purple/5":g?"border-accent-red/20 bg-accent-red/5":"border-border-muted/50 bg-bg-secondary/30"}`,children:[s.jsxs("div",{className:`flex items-center gap-1.5 px-3 py-2 ${w?"cursor-pointer":""}`,onClick:w?f:void 0,children:[s.jsx("div",{className:`w-5 h-5 rounded-full bg-accent-purple/20 flex items-center justify-center flex-shrink-0 ${a?"animate-pulse":""}`,children:s.jsx(ct,{size:12,className:"text-accent-purple"})}),s.jsx("span",{className:"text-[13px] font-semibold text-accent-purple",children:h}),_&&s.jsxs("span",{className:"text-xs text-text-tertiary truncate",children:["· ",_]}),s.jsx("span",{className:"flex-1"}),c&&s.jsx("span",{className:"text-[11px] text-text-tertiary",children:c}),a&&s.jsx(De,{size:12,className:"text-accent-purple animate-spin"}),g&&s.jsx(Cr,{size:12,className:"text-accent-red"}),!a&&!g&&e.status==="completed"&&s.jsx(Ye,{size:12,className:"text-accent-green"}),w&&!a&&(o?s.jsx(It,{size:12,strokeWidth:2,className:"text-text-tertiary flex-shrink-0"}):s.jsx(Nt,{size:12,strokeWidth:2,className:"text-text-tertiary flex-shrink-0"}))]}),y&&s.jsx("div",{className:"px-3 pb-2 pt-0 ml-2.5 pl-3 border-l border-accent-purple/20",children:i.map(v=>{if(v.type==="message")return s.jsx(Pl,{entry:v,isActive:a},v.id);const k=r.get(v.toolCallId);return k?k.toolName==="SendMessage"?s.jsx(jl,{toolCall:k},k.id):s.jsx(Pr,{toolCall:k},k.id):null})})]}):s.jsxs("div",{className:"mb-0.5",children:[s.jsxs("div",{className:`flex items-center gap-1.5 py-0.5 ${w?"cursor-pointer hover:bg-bg-hover/30 rounded-md -mx-1 px-1":""}`,onClick:w?f:void 0,children:[s.jsx("div",{className:`w-5 h-5 rounded-full bg-accent-purple/20 flex items-center justify-center flex-shrink-0 ${a?"animate-pulse":""}`,children:s.jsx(ct,{size:12,className:"text-accent-purple"})}),s.jsx("span",{className:"text-[13px] font-semibold text-accent-purple",children:h}),_&&s.jsxs("span",{className:"text-xs text-text-tertiary truncate",children:["· ",_]}),S&&s.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded bg-bg-secondary text-text-tertiary",children:t("tool.background")}),s.jsx("span",{className:"flex-1"}),c&&s.jsx("span",{className:"text-[11px] text-text-tertiary",children:c}),a&&s.jsx(De,{size:12,className:"text-accent-purple animate-spin"}),g&&s.jsx(Cr,{size:12,className:"text-accent-red"}),w&&!a&&(o?s.jsx(It,{size:12,strokeWidth:2,className:"text-text-tertiary flex-shrink-0"}):s.jsx(Nt,{size:12,strokeWidth:2,className:"text-text-tertiary flex-shrink-0"}))]}),y&&s.jsx("div",{className:"ml-2.5 pl-3 border-l border-accent-purple/25",children:i.map(v=>{if(v.type==="message")return s.jsx(Pl,{entry:v,isActive:a},v.id);const k=r.get(v.toolCallId);return k?k.toolName==="SendMessage"?s.jsx(jl,{toolCall:k},k.id):s.jsx(Pr,{toolCall:k},k.id):null})})]})}function jl({toolCall:e}){const{t}=ue(),r=he(e),i=String(r.type||"message"),a=r.recipient?String(r.recipient):void 0,g=r.summary?String(r.summary):void 0;let b="",n=s.jsx(sc,{size:10,className:"text-text-tertiary"});switch(i){case"message":b=a?`@${a}`:"message";break;case"broadcast":b="@team";break;case"shutdown_request":b=a?`@${a} · shutdown`:"shutdown";break;case"shutdown_response":b=r.approve!==!1?t("tool.taskCompleted"):t("tool.shutdownRejected"),n=s.jsx(Ye,{size:10,className:"text-accent-green"});break;case"plan_approval_response":b=a?`@${a} · ${r.approve!==!1?t("tool.approved"):t("tool.rejected")}`:t("tool.planResponse");break;default:b=a?`@${a}`:i}return s.jsxs("div",{className:"flex items-center gap-1.5 py-0.5 text-xs text-text-tertiary",children:[n,s.jsx("span",{className:"font-medium text-accent-purple",children:b}),g&&s.jsx("span",{className:"truncate",children:g}),s.jsx(Pc,{status:e.status})]})}function Pr({toolCall:e}){var S,w;const{t}=ue(),r=Up(e),[i,a]=O.useState(()=>e.status==="failed");if(O.useEffect(()=>{e.status==="failed"&&a(!0)},[e.status]),e.subagent)return s.jsx(Wp,{toolCall:e});const g=r.Icon,b=e.status==="completed"||e.status==="failed",n=!!r.render||e.result!==void 0&&r===jc,o=(S=r.getTitle)==null?void 0:S.call(r,e,t),d=Mp(e),f=o||(e.kind==="execute"&&d?d:void 0)||e.name||e.toolName||t("tool.defaultName"),_=((w=r.getSummary)==null?void 0:w.call(r,e,t))||(e.kind!=="execute"?d:void 0);return s.jsxs("div",{className:"mb-0.5",children:[s.jsxs("button",{onClick:()=>n&&a(!i),className:"flex items-center gap-1.5 py-0.5 text-left w-full rounded-md transition-colors hover:bg-bg-hover/50 cursor-pointer",children:[s.jsx(g,{}),s.jsx("span",{className:"text-[13px] text-text-secondary font-medium truncate",children:f}),_&&s.jsx("span",{className:"text-xs text-text-tertiary truncate flex-1",children:_}),!_&&s.jsx("span",{className:"flex-1"}),s.jsx(Pc,{status:e.status}),n&&s.jsx(It,{size:12,strokeWidth:2,className:`text-text-tertiary flex-shrink-0 transition-transform duration-200 ${i?"rotate-90":""}`})]}),n&&i&&s.jsx(qp,{renderer:r,toolCall:e,t,isFinished:b})]})}function qp({renderer:e,toolCall:t,t:r,isFinished:i}){const a=e.render?e.render(t,r):s.jsx(ze,{result:t.result});return s.jsx("div",{className:"mt-0.5 mb-1",children:s.jsx("div",{className:i?"empty-result-container":"",children:a})})}const Vp=new Set(["TaskCreate","TaskUpdate","TaskList","TaskGet","AskUserQuestion"]);function Kp({entries:e}){const t=e.filter(r=>r.type==="tool_call"?!Vp.has(r.toolName):r.type==="interruption"||r.type==="question");return t.length===0?null:s.jsx("div",{className:"flex flex-col gap-1 mb-2 w-full",children:t.map(r=>r.type==="tool_call"?s.jsx(Pr,{toolCall:r},r.id):r.type==="interruption"?s.jsx(yp,{interruption:r},r.id):r.type==="question"?s.jsx(xp,{question:r},r.id):null)})}function Yp(e){if(!e)return!0;const t=e.trimStart();return!!/^\/clear\b/.test(t)}function Xp(e){const t=[];for(const r of e)if(r.type==="message"){const i=r;if(i.isCompactInternal){const a=t[t.length-1];a&&a.kind==="compact_group"?a.entries.push(i):t.push({kind:"compact_group",entries:[i]})}else if(i.role==="user"&&i.channel)t.push({kind:"channel_incoming",entry:i});else if(i.role==="user"){if(Yp(i.content))continue;t.push({kind:"user",entry:i})}else t.push({kind:"assistant_message",entry:i})}else{const i=t[t.length-1];i&&i.kind==="assistant_tools"?i.entries.push(r):t.push({kind:"assistant_tools",entries:[r]})}return t}function Ul(e){var t;switch(e.kind){case"user":case"assistant_message":case"channel_incoming":return e.entry.timestamp;case"compact_group":return(t=e.entries[0])==null?void 0:t.timestamp;case"assistant_tools":return}}function Zp(e,t=150){return e.scrollHeight-e.scrollTop-e.clientHeight<t}function $l(){const{t:e}=ue(),r=Ot(i=>i.resolved)==="dark"?Jl:ec;return s.jsxs("div",{className:"empty-state",children:[s.jsx("div",{className:"empty-state-logo",children:s.jsx("img",{src:r,alt:"CodeBuddy"})}),s.jsx("h1",{className:"empty-state-slogan",children:e("chat.empty.slogan")})]})}function Qp({onClickCloseBottomSheet:e}={}){const{timeline:t,isAgentRunning:r,stopReason:i,errorMessage:a,historyLoading:g}=Le(),b=O.useRef(null),n=O.useRef(null),{t:o,resolved:d}=ue(),[f,h]=O.useState(null);O.useEffect(()=>{if(!f)return;const N=R=>{R.key==="Escape"&&h(null)};return document.addEventListener("keydown",N),()=>document.removeEventListener("keydown",N)},[f]);const _=O.useRef(!0),S=O.useRef(0),w=O.useRef(!1),y=O.useMemo(()=>Xp(t),[t]),c=y.length===0,[p,l]=O.useState(!0),[u,m]=O.useState(!1),x=O.useRef(!1);O.useEffect(()=>{if(!c&&!x.current){m(!0);const N=setTimeout(()=>{l(!1),x.current=!0},600);return()=>clearTimeout(N)}},[c]);const v=O.useCallback(()=>{if(w.current)return;const N=n.current;N&&(_.current=Zp(N))},[]);O.useEffect(()=>{const N=t.length;if(N>S.current){const R=t[S.current];(R==null?void 0:R.type)==="message"&&R.role==="user"&&(_.current=!0)}S.current=N},[t]),O.useEffect(()=>{if(!_.current)return;const N=n.current;N&&(w.current=!0,N.scrollTop=N.scrollHeight,requestAnimationFrame(()=>{w.current=!1}))},[t,r]);const k=t[t.length-1],E=(k==null?void 0:k.type)==="message"&&k.streaming,C=E&&!!k.thinking&&!k.content;return s.jsxs("div",{ref:n,onScroll:v,onClick:()=>e==null?void 0:e(),className:"absolute inset-0 overflow-y-auto overflow-x-hidden",children:[p&&s.jsx("div",{className:`empty-state-wrapper${u?" empty-state-fadeout":""}`,children:s.jsx($l,{})}),!p&&g&&t.length===0&&s.jsx("div",{className:"flex items-center justify-center min-h-[60vh] h-full pb-20",children:s.jsx(Nd,{size:"large"})}),!p&&c&&!r&&!g&&s.jsx($l,{}),!c&&s.jsx("div",{className:"px-4 sm:px-6 pt-6 pb-4 animate-fadeIn",children:s.jsxs("div",{className:"max-w-3xl mx-auto flex flex-col",children:[s.jsx("div",{className:"text-center mb-8",children:s.jsx("span",{className:"text-[13px] text-text-tertiary",children:o("chat.disclaimer")})}),y.map((N,R)=>{var M,H;const B=Ul(N);let A=!1,F="";if(B!==void 0){const z=tr(B);let G=null;for(let T=R-1;T>=0;T--){const D=Ul(y[T]);if(D!==void 0){G=tr(D);break}}z!==G&&(A=!0,F=Mc(B,d))}if(N.kind==="user")return s.jsxs("div",{children:[A&&s.jsx(kt,{label:F}),s.jsx("div",{className:"flex justify-end mb-6",children:s.jsxs("div",{className:"max-w-[85%] sm:max-w-[75%] px-5 py-3 rounded-2xl rounded-tr-sm bg-bg-user border border-transparent",children:[N.entry.images&&N.entry.images.length>0&&s.jsx("div",{className:"flex flex-wrap gap-2 mb-2",children:N.entry.images.map((z,G)=>{const T="url"in z?z.url:`data:${z.mimeType};base64,${z.data}`;return s.jsx("img",{src:T,alt:"",className:"max-w-full h-auto rounded-lg cursor-pointer hover:opacity-80 transition-opacity",style:{maxHeight:360},onClick:()=>h(T)},G)})}),N.entry.files&&N.entry.files.length>0&&s.jsx("div",{className:"flex flex-wrap gap-2 mb-2",children:N.entry.files.map((z,G)=>s.jsxs("div",{className:"flex items-center gap-1.5 px-2.5 py-1.5 rounded-lg bg-bg-primary/50 border border-border-muted/30 max-w-[180px]",children:[s.jsx(tt,{size:14,className:"shrink-0 text-text-tertiary"}),s.jsx("span",{className:"text-[12px] text-text-primary truncate",title:z.name,children:z.name})]},G))}),N.entry.content&&s.jsx("p",{className:"whitespace-pre-wrap break-words text-text-primary text-chat",children:N.entry.content})]})})]},N.entry.id);if(N.kind==="channel_incoming")return s.jsxs("div",{children:[A&&s.jsx(kt,{label:F}),s.jsx(du,{content:N.entry.content,channel:N.entry.channel})]},N.entry.id);if(N.kind==="assistant_message"){if(!N.entry.content&&!N.entry.thinking)return null;const z=R>0?y[R-1]:void 0,G=(z==null?void 0:z.kind)==="channel_incoming";return s.jsxs("div",{children:[A&&s.jsx(kt,{label:F}),G&&z.kind==="channel_incoming"&&s.jsx(uu,{channel:z.entry.channel}),s.jsx("div",{className:"mb-2 w-full",children:s.jsx("div",{className:"flex-1 min-w-0",children:s.jsx(Dc,{message:N.entry})})})]},N.entry.id)}if(N.kind==="assistant_tools"){const z=((M=N.entries[0])==null?void 0:M.id)||`tools-${R}`;return s.jsx(Kp,{entries:N.entries},z)}if(N.kind==="compact_group"){const z=((H=N.entries[0])==null?void 0:H.id)||`compact-${R}`;return s.jsxs("div",{children:[A&&s.jsx(kt,{label:F}),s.jsx(gp,{entries:N.entries})]},z)}return null}),r&&t.length>0&&!E&&!C&&s.jsx("div",{className:"mb-2",children:s.jsxs("span",{className:"inline-flex items-center gap-1.5 text-text-tertiary text-xs",children:[s.jsx(De,{size:12,className:"text-accent-brand animate-spin"}),s.jsx("span",{children:o("chat.thinking")})]})}),i&&!r&&s.jsx("div",{className:"py-2",children:s.jsx("span",{className:"text-xs text-text-tertiary",children:a?`${o("chat.error")}: ${a}`:o("chat.stopped")})})]})}),s.jsx("div",{ref:b,className:"h-6"}),f&&s.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/70 cursor-zoom-out",onClick:()=>h(null),children:s.jsx("img",{src:f,alt:"",className:"max-w-[90vw] max-h-[90vh] object-contain rounded-lg shadow-2xl",onClick:N=>N.stopPropagation()})})]})}const $c="codebuddy.auth.token";function Ht(){try{return sessionStorage.getItem($c)}catch{return null}}function Hc(e){try{sessionStorage.setItem($c,e)}catch{}}function Fe(e){const t={...e},r=Ht();return r&&(t.Authorization=`Bearer ${r}`),t}const zc=Ge(e=>({viewState:"loading",error:null,isSubmitting:!1,checkAuth:async()=>{try{e({viewState:"loading",error:null});const t=await Oe("/api/v1/auth/status",{headers:Fe()});if(!t.ok){e({viewState:"authenticated"});return}const r=await t.json();!r.authEnabled||r.authenticated?e({viewState:"authenticated"}):e({viewState:"login"})}catch(t){console.warn("[auth] Failed to check auth status, falling back to authenticated:",t),e({viewState:"authenticated"})}},login:async t=>{try{e({isSubmitting:!0,error:null});const i=await(await fetch("/api/v1/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:t})})).json();if(i.success){const a=i.token||t;return Hc(a),e({viewState:"authenticated",isSubmitting:!1,error:null}),!0}return e({error:i.error||"login.error.incorrect",isSubmitting:!1}),!1}catch(r){return console.warn("[auth] Login request failed:",r),e({error:"app.connectFailed",isSubmitting:!1}),!1}},clearError:()=>e({error:null})}));function Jp(e,t){const i=Date.now()-e,a=Math.floor(i/6e4),g=Math.floor(i/36e5),b=Math.floor(i/864e5);return t==="zh"?a<1?"刚刚":a<60?`${a} 分钟前`:g<24?`${g} 小时前`:b<30?`${b} 天前`:new Date(e).toLocaleDateString("zh-CN"):a<1?"Just now":a<60?`${a}m ago`:g<24?`${g}h ago`:b<30?`${b}d ago`:new Date(e).toLocaleDateString("en-US")}function eh({isOpen:e,onClose:t,onSwitchSession:r}){const{t:i,resolved:a}=ue(),[g,b]=O.useState([]),[n,o]=O.useState(!0),[d,f]=O.useState(null),[h,_]=O.useState(null),[S,w]=O.useState(null),[y,c]=O.useState(""),p=O.useRef(null),[l,u]=O.useState(null),m=O.useCallback(async()=>{o(!0),f(null);try{const R=await fetch("/api/v1/sessions",{headers:Fe()});if(!R.ok)throw new Error(`HTTP ${R.status}`);const B=await R.json();b(B.sessions||[])}catch(R){f(R.message||"Unknown error")}finally{o(!1)}},[]);O.useEffect(()=>{e&&m()},[e,m]);const x=O.useCallback(async R=>{try{const B=await fetch(`/api/v1/sessions/${encodeURIComponent(R.id)}`,{method:"DELETE",headers:Fe()});if(!B.ok){const A=await B.json().catch(()=>({}));throw new Error(A.error||`HTTP ${B.status}`)}b(A=>A.filter(F=>F.id!==R.id))}catch(B){console.error("[history] Delete failed:",B)}finally{u(null)}},[]),v=O.useCallback(async(R,B)=>{const A=B.trim();if(A)try{const F=await fetch(`/api/v1/sessions/${encodeURIComponent(R.id)}/rename`,{method:"POST",headers:Fe({"Content-Type":"application/json"}),body:JSON.stringify({name:A})});if(!F.ok){const M=await F.json().catch(()=>({}));throw new Error(M.error||`HTTP ${F.status}`)}b(M=>M.map(H=>H.id===R.id?{...H,name:A}:H))}catch(F){console.error("[history] Rename failed:",F)}finally{w(null),c("")}},[]),k=O.useCallback((R,B)=>{B.stopPropagation(),w(R),c(R.name),setTimeout(()=>{var A;return(A=p.current)==null?void 0:A.focus()},50)},[]),E=O.useCallback((R,B)=>{B.stopPropagation(),!R.isCurrent&&u(R)},[]),C=O.useCallback(async R=>{if(!(R.isCurrent||h)){_(R.id);try{await(r==null?void 0:r(R.id)),t()}finally{_(null)}}},[h,r,t]),N=()=>n?s.jsx("div",{className:"history-loading",children:s.jsx(lt,{size:"small",text:i("history.loading")})}):d?s.jsxs("div",{className:"history-error",children:[s.jsx("p",{className:"history-error-text",children:i("history.loadError")}),s.jsx("button",{className:"history-retry-btn",onClick:m,children:i("history.retry")})]}):g.length===0?s.jsxs("div",{className:"history-empty",children:[s.jsx(gc,{size:48,className:"text-text-tertiary"}),s.jsx("p",{className:"history-empty-title",children:i("history.noData")}),s.jsx("p",{className:"history-empty-hint",children:i("history.noDataHint")})]}):s.jsx("div",{className:"history-list",children:g.map((R,B)=>{const A=tr(R.updatedAt),F=B>0?tr(g[B-1].updatedAt):null,M=A!==F;return s.jsxs("div",{children:[M&&s.jsx(kt,{label:Mc(R.updatedAt,a)}),s.jsxs("div",{className:`history-session-item${R.isCurrent?" current":""}${!R.isCurrent&&!h?" clickable":""}`,onClick:()=>!R.isCurrent&&!h&&C(R),children:[s.jsxs("div",{className:"history-session-info",children:[s.jsx("p",{className:"history-session-name",children:R.name}),s.jsxs("div",{className:"history-session-meta",children:[R.isCurrent&&s.jsx("span",{className:"history-session-badge",children:i("history.current")}),s.jsx("span",{children:i("history.messages").replace("{count}",String(R.messageCount))}),s.jsx("span",{children:Jp(R.updatedAt,a)})]})]}),s.jsxs("div",{className:"history-session-actions",children:[h===R.id&&s.jsx("div",{className:"history-session-switching",children:s.jsx("div",{className:"history-session-spinner"})}),h!==R.id&&s.jsxs(s.Fragment,{children:[s.jsx("button",{className:"history-action-btn",title:i("history.rename"),onClick:H=>k(R,H),children:s.jsx(Kd,{size:14})}),!R.isCurrent&&s.jsx("button",{className:"history-action-btn danger",title:i("history.delete"),onClick:H=>E(R,H),children:s.jsx(Mt,{size:14})})]})]})]})]},R.id)})});return s.jsxs(s.Fragment,{children:[s.jsx("div",{className:`history-drawer-overlay ${e?"open":""}`,onClick:t}),s.jsxs("div",{className:`history-drawer ${e?"open":""}`,children:[s.jsxs("div",{className:"history-drawer-header",children:[s.jsxs("div",{children:[s.jsx("h2",{className:"history-drawer-title",children:i("history.title")}),s.jsx("p",{className:"history-drawer-subtitle",children:i("history.description")})]}),s.jsx("button",{onClick:t,className:"history-drawer-close",children:s.jsx(Ie,{size:16})})]}),s.jsx("div",{className:"history-content",children:N()})]}),S&&s.jsx("div",{className:"history-rename-overlay",onClick:()=>w(null),children:s.jsxs("div",{className:"history-rename-dialog",onClick:R=>R.stopPropagation(),children:[s.jsx("h3",{children:i("history.renameTitle")}),s.jsx("input",{ref:p,className:"history-rename-input",value:y,onChange:R=>c(R.target.value),placeholder:i("history.renamePlaceholder"),onKeyDown:R=>{R.key==="Enter"&&y.trim()&&v(S,y),R.key==="Escape"&&w(null)}}),s.jsxs("div",{className:"history-rename-actions",children:[s.jsx("button",{className:"history-rename-cancel",onClick:()=>w(null),children:i("history.renameCancel")}),s.jsx("button",{className:"history-rename-ok",disabled:!y.trim(),onClick:()=>v(S,y),children:i("history.renameOk")})]})]})}),l&&s.jsx("div",{className:"history-delete-overlay",onClick:()=>u(null),children:s.jsxs("div",{className:"history-delete-dialog",onClick:R=>R.stopPropagation(),children:[s.jsx("p",{children:i("history.deleteConfirm")}),s.jsxs("div",{className:"history-delete-actions",children:[s.jsx("button",{className:"history-delete-cancel",onClick:()=>u(null),children:i("history.deleteCancel")}),s.jsx("button",{className:"history-delete-ok",onClick:()=>x(l),children:i("history.deleteOk")})]})]})})]})}const Zo="codebuddy.instances.passwords";function Qo(){try{const e=localStorage.getItem(Zo);return e?JSON.parse(e):{}}catch{return{}}}function th(e,t){const r=Qo();r[e]=t,localStorage.setItem(Zo,JSON.stringify(r))}function rh(e){const t=Qo();delete t[e],localStorage.setItem(Zo,JSON.stringify(t))}function nh(e){return Qo()[e]}const ih=Ge((e,t)=>({instances:[],loading:!1,error:null,showManagerPanel:!1,fetchInstances:async()=>{e({loading:!0,error:null});try{const r=await Oe("/api/v1/instances",{headers:Fe()});if(!r.ok)throw new Error(`Failed to fetch instances: ${r.status}`);const i=await r.json();e({instances:i.instances||[],loading:!1})}catch(r){e({error:r.message,loading:!1})}},addInstance:async(r,i,a)=>{e({error:null});try{const g=await Oe("/api/v1/instances",{method:"POST",headers:Fe({"Content-Type":"application/json"}),body:JSON.stringify({url:r,password:i,name:a})});if(!g.ok){const o=await g.json().catch(()=>({}));throw new Error(o.error||`Failed to add instance: ${g.status}`)}const b=await g.json();i&&b.id&&th(b.id,i),await t().fetchInstances()}catch(g){throw e({error:g.message}),g}},removeInstance:async r=>{e({error:null});try{const i=await Oe(`/api/v1/instances/${r}`,{method:"DELETE",headers:Fe()});if(!i.ok){const g=await i.json().catch(()=>({}));throw new Error(g.error||`Failed to remove instance: ${i.status}`)}rh(r),await t().fetchInstances()}catch(i){throw e({error:i.message}),i}},setShowManagerPanel:r=>e({showManagerPanel:r})}));function Gc(){const{hostname:e,protocol:t}=window.location;return e==="localhost"||e==="127.0.0.1"||e==="[::1]"||/^(10\.|172\.(1[6-9]|2\d|3[01])\.|192\.168\.)/.test(e)?!1:t==="https:"}function sh(e){return Gc()?e.tunnelUrl||e.localUrl||void 0:e.localUrl||e.tunnelUrl||void 0}function ah(){const e=Le(i=>i.clearChat),t=Xe(i=>i.disconnect);return{switchToInstance:O.useCallback(async i=>{if(i.isCurrent)return;try{await xe().disconnect()}catch{}e();const a=sh(i);if(!a){console.error("Instance has no accessible URL");return}const g=nh(i.id),b=new URL(a);g&&b.searchParams.set("password",g),window.location.href=b.toString()},[e,t])}}const Wc=4,qc="codebuddy_interaction_mode",Vc="codebuddy_terminal_layout",Kc="codebuddy_terminal_panes";let oh=0;function lh(){return`pane-${Date.now()}-${++oh}`}function jr(e){return{id:e??lh(),ptySessionId:null,ptyStatus:"disconnected",errorMessage:null}}function ft(e){return e.type==="leaf"?1:ft(e.children[0])+ft(e.children[1])}function rr(e){return e.type==="leaf"?[e.paneId]:[...rr(e.children[0]),...rr(e.children[1])]}function ch(){try{const e=sessionStorage.getItem(qc);if(e==="chat"||e==="terminal")return e}catch{}return"chat"}function Hl(e){try{sessionStorage.setItem(qc,e)}catch{}}function dh(){try{const e=sessionStorage.getItem(Vc);if(e)return JSON.parse(e)}catch{}return null}function Vt(e){try{sessionStorage.setItem(Vc,JSON.stringify(e))}catch{}}function uh(){try{const e=sessionStorage.getItem(Kc);if(e)return JSON.parse(e)}catch{}return null}function Kt(e){try{sessionStorage.setItem(Kc,JSON.stringify(e))}catch{}}function ph(){const e=dh(),t=uh();if(e&&t){const i=rr(e);if(i.every(a=>a in t)){const a={};for(const g of i)a[g]={...t[g],ptyStatus:"disconnected",errorMessage:null};return{panes:a,layout:e,activePaneId:i[0]}}}const r=jr();return{panes:{[r.id]:r},layout:{type:"leaf",paneId:r.id},activePaneId:r.id}}function Ur(e,t,r,i){return e.type==="leaf"?e.paneId===t?{type:"split",direction:r,children:[{type:"leaf",paneId:t},{type:"leaf",paneId:i}],ratio:.5}:e:{...e,children:[Ur(e.children[0],t,r,i),Ur(e.children[1],t,r,i)]}}function $r(e,t){if(e.type==="leaf")return e.paneId===t?null:e;const r=$r(e.children[0],t),i=$r(e.children[1],t);return r===null?i:i===null?r:{...e,children:[r,i]}}function Yc(e,t,r){if(t.length===0)return e.type==="split"?{...e,ratio:r}:e;if(e.type==="split"){const[i,...a]=t,g=[...e.children];return g[i]=Yc(g[i],a,r),{...e,children:g}}return e}function zl(e){const t=Ht(),r={"Content-Type":"application/json"};t&&(r.Authorization=`Bearer ${t}`),fetch(`/api/v1/pty/${e}`,{method:"DELETE",headers:r}).catch(()=>{})}const yr=ph(),me=Ge((e,t)=>({mode:ch(),mainView:"chat",terminalTitle:null,panes:yr.panes,layout:yr.layout,activePaneId:yr.activePaneId,setMode:r=>{Hl(r),e({mode:r,mainView:r==="terminal"?"terminal":"chat"})},setMainView:r=>{const i=r==="terminal"?"terminal":"chat";i!==t().mode&&Hl(i),e({mainView:r,mode:i})},setTerminalTitle:r=>e({terminalTitle:r}),splitPane:(r,i)=>{const a=t(),g=i??a.activePaneId;if(ft(a.layout)>=Wc)return;const b=jr(),n=Ur(a.layout,g,r,b.id),o={...a.panes,[b.id]:b};Vt(n),Kt(o),e({layout:n,panes:o,activePaneId:b.id})},closePane:r=>{const i=t();if(ft(i.layout)<=1)return;const a=$r(i.layout,r);if(!a)return;const g=i.panes[r];g!=null&&g.ptySessionId&&zl(g.ptySessionId);const b={...i.panes};delete b[r];const n=rr(a),o=n.includes(i.activePaneId)?i.activePaneId:n[0];Vt(a),Kt(b),e({layout:a,panes:b,activePaneId:o})},setActivePaneId:r=>e({activePaneId:r}),setRatio:(r,i)=>{const a=Math.max(.1,Math.min(.9,i)),g=Yc(t().layout,r,a);Vt(g),e({layout:g})},setPaneSession:(r,i)=>{const a={...t().panes};a[r]&&(a[r]={...a[r],ptySessionId:i},Kt(a),e({panes:a}))},setPaneStatus:(r,i)=>{const a={...t().panes};a[r]&&(a[r]={...a[r],ptyStatus:i},e({panes:a}))},setPaneError:(r,i)=>{const a={...t().panes};a[r]&&(a[r]={...a[r],errorMessage:i},e({panes:a}))},reset:()=>{const r=t().panes;for(const b of Object.values(r))b.ptySessionId&&zl(b.ptySessionId);const i=jr(),a={type:"leaf",paneId:i.id},g={[i.id]:i};Vt(a),Kt(g),e({panes:g,layout:a,activePaneId:i.id})}}));function hh(e){if(!e.length)return[];const t={};for(const i of e){const a=i.cwd||"remote";t[a]||(t[a]=[]),t[a].push(i)}const r=Object.entries(t).map(([i,a])=>{const g=i.split("/").filter(Boolean);return{cwd:i,directoryName:g[g.length-1]||i,hasCurrent:a.some(b=>b.isCurrent),instances:a.sort((b,n)=>b.isCurrent!==n.isCurrent?b.isCurrent?-1:1:n.startedAt-b.startedAt),latestStartTime:Math.max(...a.map(b=>b.startedAt))}});return r.sort((i,a)=>i.hasCurrent!==a.hasCurrent?i.hasCurrent?-1:1:a.latestStartTime!==i.latestStartTime?a.latestStartTime-i.latestStartTime:a.instances.length-i.instances.length),r}function gh(e){const t=Date.now()-e,r=Math.floor(t/6e4),i=Math.floor(t/36e5),a=Math.floor(t/864e5);return a>0?`${a}d ago`:i>0?`${i}h ago`:r>0?`${r}m ago`:"just now"}function fh(e){const t=e.match(/^\/(?:Users|home)\/[^/]+/);return t?e.replace(t[0],"~"):e}function mh({instance:e,switching:t,switchingId:r,onSwitch:i,onRemove:a,t:g}){var o;const b=r===e.id,n=e.mode==="tunnel"||!!e.tunnelUrl;return s.jsxs("div",{className:"flex items-center gap-3 px-4 py-2.5 hover:bg-bg-hover transition-colors group",children:[s.jsx("div",{className:"flex-shrink-0",children:n?s.jsx(Kr,{size:15,className:"text-text-tertiary"}):s.jsx(ct,{size:15,className:"text-text-tertiary"})}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-2 text-[13px]",children:[s.jsx("span",{className:"text-text-primary font-medium truncate",children:e.id.slice(0,8)}),s.jsx("span",{className:"px-1.5 py-px text-[10px] rounded font-medium bg-text-primary/[0.06] text-text-tertiary",children:g(n?"workspace.instanceTunnel":"workspace.instanceLocal")}),e.isCurrent&&s.jsx("span",{className:"px-1.5 py-px text-[10px] rounded font-medium bg-accent-green/15 text-accent-green",children:g("workspace.instanceCurrent")})]}),((o=e.meta)==null?void 0:o.currentTopic)&&s.jsx("div",{className:"text-[12px] text-text-secondary mt-0.5 truncate",title:e.meta.currentTopic,children:e.meta.currentTopic}),s.jsx("div",{className:"text-[11px] text-text-tertiary mt-0.5",children:gh(e.startedAt)})]}),s.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[!e.isCurrent&&s.jsx("button",{onClick:()=>i(e),disabled:t,className:"opacity-0 group-hover:opacity-100 px-3 py-1 text-[12px] font-medium text-text-primary hover:bg-bg-tertiary rounded-md transition-all disabled:opacity-50 disabled:cursor-not-allowed",children:b?s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(De,{size:12,className:"animate-spin"}),g("workspace.switchingInstance")]}):g("workspace.switchInstance")}),e.manual&&s.jsx("button",{onClick:()=>a(e.id),className:"opacity-0 group-hover:opacity-100 w-7 h-7 flex items-center justify-center rounded-md text-text-tertiary hover:text-accent-red hover:bg-accent-red/10 transition-colors",title:g("instance.remove"),children:s.jsx(Mt,{size:13})})]})]})}function Xc({isOpen:e,onClose:t}){const{instances:r,loading:i,error:a,fetchInstances:g,addInstance:b,removeInstance:n}=ih(),{switchToInstance:o}=ah(),{t:d}=ue(),f=me(ee=>ee.setMainView),h=e!==void 0,[_,S]=O.useState(!1),[w,y]=O.useState(""),[c,p]=O.useState(""),[l,u]=O.useState(""),[m,x]=O.useState(!1),[v,k]=O.useState(null),[E,C]=O.useState(!1),[N,R]=O.useState(!1),[B,A]=O.useState(!1),[F,M]=O.useState(!1),[H,z]=O.useState(null),[G,T]=O.useState(new Set),[D,P]=O.useState(!1),j=Gc(),q=O.useMemo(()=>(j?r.filter(de=>de.isCurrent||de.mode==="tunnel"||de.tunnelUrl):r).slice().sort((de,ne)=>de.isCurrent===ne.isCurrent?0:de.isCurrent?-1:1),[r,j]),K=O.useMemo(()=>hh(q),[q]);O.useEffect(()=>{!D&&K.length>0&&(T(new Set(K.map(ee=>ee.cwd))),P(!0))},[K,D]);const re=!i&&q.length===0&&!a;O.useEffect(()=>{(!h||e)&&(C(!1),g())},[e,h,g]);const J=O.useCallback(()=>{t?t():f("chat")},[t,f]),U=O.useCallback(async()=>{R(!0),A(!1),C(!1);try{await g(),A(!0),setTimeout(()=>A(!1),2e3)}finally{R(!1)}},[g]),I=O.useCallback(async()=>{const ee=c.trim();if(ee){x(!0),k(null);try{await b(ee,l.trim()||void 0,w.trim()||void 0),y(""),p(""),u(""),S(!1)}catch(de){k(de.message)}finally{x(!1)}}},[w,c,l,b]),V=O.useCallback(async ee=>{try{await n(ee)}catch(de){console.error("Remove instance failed:",de)}},[n]),W=O.useCallback(async ee=>{if(!ee.isCurrent){M(!0),z(ee.id);try{await o(ee)}catch{M(!1),z(null)}}},[o]),Q=O.useCallback(ee=>{T(de=>{const ne=new Set(de);return ne.has(ee)?ne.delete(ee):ne.add(ee),ne})},[]);if(h&&!e)return null;if(h)return s.jsxs("div",{className:"fixed inset-0 z-50 bg-bg-primary text-text-primary flex flex-col",children:[s.jsxs("div",{className:"flex items-center justify-between px-6 h-14 border-b border-border-muted bg-bg-primary shrink-0",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("button",{onClick:J,className:"w-8 h-8 flex items-center justify-center rounded-full hover:bg-bg-secondary transition-colors text-text-secondary",children:s.jsx(Vr,{size:18})}),s.jsx("span",{className:"font-semibold text-[15px] tracking-wide",children:d("instance.managerTitle")})]}),s.jsxs("button",{onClick:()=>S(!0),className:"flex items-center gap-2 px-4 py-2 rounded-full bg-accent-brand text-white text-[13px] font-medium hover:bg-accent-brand/90 transition-colors",children:[s.jsx(Ke,{size:14}),d("instance.addInstance")]})]}),s.jsx("div",{className:"flex-1 overflow-y-auto p-6",children:s.jsxs("div",{className:"max-w-3xl mx-auto space-y-4",children:[Z(),ae(),oe()]})})]});return s.jsxs("div",{className:"flex-1 flex flex-col overflow-hidden bg-bg-primary",children:[s.jsx("div",{className:"flex-none border-b border-border-muted px-6 py-4",children:s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{children:[s.jsx("h1",{className:"text-lg font-semibold text-text-primary",children:d("instance.managerTitle")}),s.jsx("p",{className:"text-sm text-text-tertiary mt-1",children:d("instance.subtitle")})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs("button",{onClick:U,disabled:N,className:`flex items-center gap-2 px-3 py-2 rounded-lg border transition-all ${B?"border-green-500/50 text-green-500":N?"opacity-50 cursor-not-allowed border-border-muted text-text-secondary":"border-border-muted text-text-secondary hover:text-text-primary hover:border-accent-brand/50 hover:bg-bg-secondary"}`,title:d("instance.refresh"),children:[B?s.jsx(Ye,{size:16}):s.jsx(Dt,{size:16,className:N?"animate-spin":""}),s.jsx("span",{className:"text-sm",children:d(B?"instance.refreshed":"instance.refresh")})]}),s.jsxs("button",{onClick:()=>S(!0),className:"flex items-center gap-2 px-3 py-2 rounded-lg border border-accent-brand/30 bg-accent-brand text-white text-sm font-medium hover:bg-accent-brand/90 transition-colors",children:[s.jsx(Ke,{size:16}),s.jsx("span",{children:d("instance.addInstance")})]})]})]})}),s.jsxs("div",{className:"flex-1 overflow-y-auto px-4 sm:px-6 py-4",children:[Z(),ae(),oe()]})]});function Z(){return _?s.jsxs("div",{className:"bg-bg-secondary rounded-xl border border-border-muted p-5 space-y-4 mb-4",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("span",{className:"text-[14px] font-medium",children:d("instance.addInstance")}),s.jsx("button",{onClick:()=>{S(!1),k(null)},className:"w-6 h-6 flex items-center justify-center rounded-full hover:bg-bg-tertiary transition-colors text-text-secondary",children:s.jsx(Ie,{size:14})})]}),s.jsxs("div",{className:"space-y-3",children:[s.jsxs("div",{children:[s.jsx("label",{className:"text-[12px] text-text-secondary mb-1.5 block",children:d("instance.name")}),s.jsx("input",{type:"text",value:w,onChange:ee=>y(ee.target.value),placeholder:d("instance.namePlaceholder"),className:"w-full bg-bg-primary text-text-primary text-[14px] border border-border-muted rounded-lg px-3 py-2 outline-none focus:ring-2 focus:ring-accent-brand/20 focus:border-accent-brand/50 transition-all placeholder:text-text-tertiary",onKeyDown:ee=>{ee.key==="Enter"&&c.trim()&&I()}})]}),s.jsxs("div",{children:[s.jsx("label",{className:"text-[12px] text-text-secondary mb-1.5 block",children:d("instance.url")}),s.jsx("input",{type:"url",value:c,onChange:ee=>p(ee.target.value),placeholder:"https://abc-def-ghi.trycloudflare.com",className:"w-full bg-bg-primary text-text-primary text-[14px] border border-border-muted rounded-lg px-3 py-2 outline-none focus:ring-2 focus:ring-accent-brand/20 focus:border-accent-brand/50 transition-all placeholder:text-text-tertiary",onKeyDown:ee=>{ee.key==="Enter"&&c.trim()&&I()}})]}),s.jsxs("div",{children:[s.jsxs("label",{className:"text-[12px] text-text-secondary mb-1.5 block",children:[d("instance.password"),s.jsxs("span",{className:"text-text-tertiary ml-1",children:["(",d("instance.optional"),")"]})]}),s.jsx("input",{type:"password",value:l,onChange:ee=>u(ee.target.value),placeholder:d("instance.passwordPlaceholder"),className:"w-full bg-bg-primary text-text-primary text-[14px] border border-border-muted rounded-lg px-3 py-2 outline-none focus:ring-2 focus:ring-accent-brand/20 focus:border-accent-brand/50 transition-all placeholder:text-text-tertiary",onKeyDown:ee=>{ee.key==="Enter"&&c.trim()&&I()}})]}),v&&s.jsx("div",{className:"text-accent-red text-[12px]",children:v}),s.jsxs("div",{className:"flex justify-end gap-2 pt-1",children:[s.jsx("button",{onClick:()=>{S(!1),k(null)},className:"px-4 py-2 rounded-lg text-[13px] text-text-secondary hover:bg-bg-tertiary transition-colors",children:d("instance.cancel")}),s.jsxs("button",{onClick:I,disabled:!c.trim()||m,className:"px-4 py-2 rounded-lg text-[13px] font-medium bg-accent-brand text-white hover:bg-accent-brand/90 transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2",children:[m&&s.jsx(De,{size:14,className:"animate-spin"}),d("instance.add")]})]})]})]}):null}function ae(){return!a||E?null:s.jsxs("div",{className:"bg-accent-red/10 border border-accent-red/30 rounded-xl p-4 text-accent-red text-[13px] flex items-center justify-between mb-4",children:[s.jsx("span",{children:a}),s.jsx("button",{onClick:()=>C(!0),className:"w-5 h-5 flex items-center justify-center rounded-full hover:bg-accent-red/20 transition-colors shrink-0 ml-3",children:s.jsx(Ie,{size:12})})]})}function oe(){return i&&q.length===0?s.jsx("div",{className:"flex flex-col items-center justify-center h-full text-text-tertiary",children:s.jsx("div",{className:"thinking-text text-sm",children:d("instance.loading")})}):a&&!i&&q.length===0&&!E?s.jsx("div",{className:"flex flex-col items-center justify-center h-full",children:s.jsxs("div",{className:"text-center",children:[s.jsx("div",{className:"text-text-tertiary text-[48px] mb-4 opacity-30",children:"⚠"}),s.jsx("div",{className:"text-text-secondary text-sm mb-4",children:d("instance.error")}),s.jsx("button",{onClick:U,className:"px-4 py-2 rounded-lg bg-accent-brand text-white text-sm font-medium hover:bg-accent-brand/90 transition-colors",children:d("instance.retry")})]})}):re?s.jsxs("div",{className:"flex flex-col items-center justify-center h-full text-text-tertiary",children:[s.jsx(ct,{size:48,className:"mb-4 opacity-30"}),s.jsx("div",{className:"text-sm font-medium mb-1",children:d("instance.noInstances")}),s.jsx("div",{className:"text-xs",children:d("instance.noInstancesHint")})]}):s.jsx("div",{className:`space-y-3 transition-opacity duration-300 ${N?"opacity-50 pointer-events-none":"opacity-100"}`,children:K.map(ee=>{const de=G.has(ee.cwd);return s.jsxs("div",{className:`rounded-xl overflow-hidden ${ee.hasCurrent?"bg-text-primary/[0.03]":"bg-bg-secondary/30"}`,children:[s.jsxs("button",{onClick:()=>Q(ee.cwd),className:"w-full flex items-center gap-3 px-4 py-3 hover:bg-bg-hover/50 transition-colors text-left",children:[s.jsx(lc,{size:18,className:"text-text-secondary flex-shrink-0"}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsx("div",{className:"text-[14px] font-medium text-text-primary truncate",children:ee.directoryName}),s.jsx("div",{className:"text-[11px] text-text-tertiary truncate",children:fh(ee.cwd)})]}),s.jsx("span",{className:"text-[12px] text-text-tertiary flex-shrink-0 mr-1",children:d("workspace.instanceCount").replace("{count}",String(ee.instances.length))}),s.jsx(Nt,{size:16,className:`text-text-tertiary flex-shrink-0 transition-transform duration-200 ${de?"":"-rotate-90"}`})]}),de&&s.jsx("div",{className:"border-t border-border-muted",children:ee.instances.map(ne=>s.jsx(mh,{instance:ne,switching:F,switchingId:H,onSwitch:W,onRemove:V,t:d},ne.id))})]},ee.cwd)})})}}function Yt(e,t){return`${e}@${t}`}async function He(e,t){return Oe(e,{method:"POST",headers:{"Content-Type":"application/json",...Fe()},body:t?JSON.stringify(t):void 0})}const bh=Ge((e,t)=>({plugins:[],loading:!1,error:null,marketplaces:[],marketplaceLoading:!1,availablePlugins:[],browsingMarketplace:null,browsingLoading:!1,browsingError:null,operatingPlugins:new Set,fetchPlugins:async()=>{e({loading:!0,error:null});try{const r=await He("/internal/plugin/list");if(!r.ok)throw new Error(`HTTP ${r.status}`);const i=await r.json();e({plugins:Array.isArray(i)?i:[],loading:!1})}catch(r){console.warn("[plugin-store] fetchPlugins failed:",r),e({error:r.message,loading:!1})}},fetchMarketplaces:async()=>{e({marketplaceLoading:!0});try{const r=await He("/internal/plugin/marketplace/list");if(!r.ok)throw new Error(`HTTP ${r.status}`);const i=await r.json();e({marketplaces:Array.isArray(i)?i:[],marketplaceLoading:!1})}catch(r){console.warn("[plugin-store] fetchMarketplaces failed:",r),e({marketplaceLoading:!1})}},browseMarketplace:async r=>{e({browsingMarketplace:r,browsingLoading:!0,browsingError:null});try{const i=await He("/internal/plugin/browse",{marketplace:r});if(!i.ok){const n=await i.json().catch(()=>null);throw new Error((n==null?void 0:n.message)||`HTTP ${i.status}`)}const a=await i.json(),b=(Array.isArray(a)?a:[]).map(n=>({name:n.name,version:n.version,description:n.description,marketplace:n.marketplaceName||r,installed:!!n.status,author:n.author,license:n.license,homepage:n.homepage,repository:n.repository,keywords:n.keywords,category:n.category,features:n.features,source:n.source}));e({availablePlugins:b,browsingLoading:!1})}catch(i){console.warn("[plugin-store] browseMarketplace failed:",i),e({browsingError:i.message,browsingLoading:!1})}},browseAllMarketplaces:async()=>{const{marketplaces:r}=t();if(r.length!==0){e({browsingMarketplace:"__all__",browsingLoading:!0,browsingError:null});try{const i=await Promise.allSettled(r.map(async o=>{const d=await He("/internal/plugin/browse",{marketplace:o.name});if(!d.ok){const _=await d.json().catch(()=>null);throw new Error((_==null?void 0:_.message)||`HTTP ${d.status}`)}const f=await d.json();return(Array.isArray(f)?f:[]).map(_=>({name:_.name,version:_.version,description:_.description,marketplace:_.marketplaceName||o.name,installed:!!_.status,author:_.author,license:_.license,homepage:_.homepage,repository:_.repository,keywords:_.keywords,category:_.category,features:_.features,source:_.source}))})),a=[];let g=!1;for(const o of i)o.status==="fulfilled"?a.push(...o.value):g=!0;const b=new Set,n=a.filter(o=>{const d=`${o.name}@${o.marketplace}`;return b.has(d)?!1:(b.add(d),!0)});e({availablePlugins:n,browsingLoading:!1,browsingError:g&&n.length===0?"Some marketplaces failed to load":null})}catch(i){console.warn("[plugin-store] browseAllMarketplaces failed:",i),e({browsingError:i.message,browsingLoading:!1})}}},enablePlugin:async(r,i)=>{const a=Yt(r,i);e(g=>({operatingPlugins:new Set(g.operatingPlugins).add(a)}));try{const g=await He("/internal/plugin/enable",{plugin:a});if(!g.ok){const b=await g.json().catch(()=>null);throw new Error((b==null?void 0:b.message)||`HTTP ${g.status}`)}await t().fetchPlugins()}finally{e(g=>{const b=new Set(g.operatingPlugins);return b.delete(a),{operatingPlugins:b}})}},disablePlugin:async(r,i)=>{const a=Yt(r,i);e(g=>({operatingPlugins:new Set(g.operatingPlugins).add(a)}));try{const g=await He("/internal/plugin/disable",{plugin:a});if(!g.ok){const b=await g.json().catch(()=>null);throw new Error((b==null?void 0:b.message)||`HTTP ${g.status}`)}await t().fetchPlugins()}finally{e(g=>{const b=new Set(g.operatingPlugins);return b.delete(a),{operatingPlugins:b}})}},uninstallPlugin:async(r,i)=>{const a=Yt(r,i);e(g=>({operatingPlugins:new Set(g.operatingPlugins).add(a)}));try{const g=await He("/internal/plugin/uninstall",{plugin:a});if(!g.ok){const b=await g.json().catch(()=>null);throw new Error((b==null?void 0:b.message)||`HTTP ${g.status}`)}await t().fetchPlugins()}finally{e(g=>{const b=new Set(g.operatingPlugins);return b.delete(a),{operatingPlugins:b}})}},installPlugin:async(r,i)=>{const a=Yt(r,i);e(g=>({operatingPlugins:new Set(g.operatingPlugins).add(a)}));try{const g=await He("/internal/plugin/install",{plugin:a});if(!g.ok){const n=await g.json().catch(()=>null);throw new Error((n==null?void 0:n.message)||`HTTP ${g.status}`)}await t().fetchPlugins();const b=t();b.browsingMarketplace&&(b.browsingMarketplace==="__all__"?await t().browseAllMarketplaces():await t().browseMarketplace(b.browsingMarketplace))}finally{e(g=>{const b=new Set(g.operatingPlugins);return b.delete(a),{operatingPlugins:b}})}},addMarketplace:async(r,i)=>{const a=await He("/internal/plugin/marketplace/add",{source:r,name:i});if(!a.ok){const g=await a.json().catch(()=>null);throw new Error((g==null?void 0:g.message)||`HTTP ${a.status}`)}await t().fetchMarketplaces()},removeMarketplace:async r=>{const i=await He("/internal/plugin/marketplace/remove",{name:r});if(!i.ok){const a=await i.json().catch(()=>null);throw new Error((a==null?void 0:a.message)||`HTTP ${i.status}`)}await t().fetchMarketplaces()}}));function Zc(){const{t:e}=ue(),{plugins:t,marketplaces:r,loading:i,marketplaceLoading:a,error:g,operatingPlugins:b,availablePlugins:n,browsingLoading:o,browsingError:d,fetchPlugins:f,fetchMarketplaces:h,browseMarketplace:_,browseAllMarketplaces:S,enablePlugin:w,disablePlugin:y,uninstallPlugin:c,installPlugin:p,addMarketplace:l,removeMarketplace:u}=bh(),[m,x]=O.useState("installed"),[v,k]=O.useState(""),[E,C]=O.useState("all"),[N,R]=O.useState(null),[B,A]=O.useState(!1),[F,M]=O.useState(""),[H,z]=O.useState(""),[G,T]=O.useState(!1),[D,P]=O.useState(null),[j,q]=O.useState(null),[K,re]=O.useState(null),[J,U]=O.useState(""),[I,V]=O.useState(""),[W,Q]=O.useState(null),Z=O.useCallback(Y=>{Q(ie=>ie===Y?null:Y)},[]);O.useEffect(()=>{f(),h()},[f,h]),O.useEffect(()=>{m==="browse"&&!J&&r.length>0&&(U("__all__"),S())},[m,r,J,S]);const ae=O.useCallback(async Y=>{R(null);try{Y.status==="enabled"?await y(Y.name,Y.marketplace):await w(Y.name,Y.marketplace)}catch(ie){R(ie.message)}},[w,y]),oe=O.useCallback(async Y=>{R(null),q(null);try{await c(Y.name,Y.marketplace)}catch(ie){R(ie.message)}},[c]),ee=O.useCallback(async Y=>{R(null);try{await p(Y.name,Y.marketplace)}catch(ie){R(ie.message)}},[p]),de=O.useCallback(async()=>{const Y=F.trim();if(Y){T(!0),P(null);try{await l(Y,H.trim()||void 0),M(""),z(""),A(!1)}catch(ie){P(ie.message)}finally{T(!1)}}},[F,H,l]),ne=O.useCallback(async Y=>{R(null),re(null);try{if(await u(Y),J===Y&&r.length>1){const ie=r.find(_e=>_e.name!==Y);ie&&(U(ie.name),_(ie.name))}}catch(ie){R(ie.message)}},[u,J,r,_]),qe=O.useCallback(()=>{f(),h(),m==="browse"&&J&&(J==="__all__"?S():_(J))},[f,h,m,J,_,S]),rt=O.useCallback(Y=>{U(Y),V(""),Y==="__all__"?S():_(Y)},[_,S]),nt=Y=>`${Y.name}@${Y.marketplace}`,Ze=O.useMemo(()=>{const Y=new Set(t.map(ie=>ie.marketplace));return Array.from(Y).sort()},[t]),Ue=O.useMemo(()=>{let Y=t;E!=="all"&&(Y=Y.filter(_e=>_e.marketplace===E));const ie=v.trim().toLowerCase();return ie&&(Y=Y.filter(_e=>_e.name.toLowerCase().includes(ie)||_e.description&&_e.description.toLowerCase().includes(ie)||_e.marketplace.toLowerCase().includes(ie))),Y},[t,E,v]),be=O.useMemo(()=>{let Y=n;const ie=I.trim().toLowerCase();return ie&&(Y=Y.filter(_e=>_e.name.toLowerCase().includes(ie)||_e.description&&_e.description.toLowerCase().includes(ie))),Y},[n,I]),Ve=t.filter(Y=>Y.status==="enabled").length;return s.jsxs("div",{className:"flex-1 flex flex-col overflow-hidden bg-bg-primary",children:[s.jsx("div",{className:"flex-none border-b border-border-muted px-6 py-4",children:s.jsxs("div",{className:"max-w-3xl mx-auto",children:[s.jsxs("div",{className:"flex items-center justify-between mb-4",children:[s.jsxs("div",{children:[s.jsx("h1",{className:"text-lg font-semibold text-text-primary",children:e("plugins.title")}),m==="installed"&&t.length>0&&s.jsxs("p",{className:"text-sm text-text-tertiary mt-0.5",children:[t.length," ",e("plugins.totalCount")," · ",Ve," ",e("plugins.enabled")]}),m==="browse"&&J&&!o&&n.length>0&&s.jsxs("p",{className:"text-sm text-text-tertiary mt-0.5",children:[n.length," ",e("plugins.totalCount")]}),m==="marketplaces"&&r.length>0&&s.jsxs("p",{className:"text-sm text-text-tertiary mt-0.5",children:[r.length," ",e("plugins.totalCount")]})]}),s.jsx("button",{onClick:qe,disabled:i||o,className:`flex items-center gap-2 px-3 py-2 rounded-lg border transition-all ${i||o?"opacity-50 cursor-not-allowed border-border-muted text-text-secondary":"border-border-muted text-text-secondary hover:text-text-primary hover:border-text-primary/20 hover:bg-bg-secondary"}`,title:e("plugins.refresh"),children:s.jsx(Dt,{size:14,className:i||o?"animate-spin":""})})]}),s.jsxs("div",{className:"flex gap-1 border-b border-border-muted",children:[s.jsx("button",{onClick:()=>{x("installed"),R(null)},className:`px-4 py-2.5 text-[13px] font-medium border-b-2 transition-colors ${m==="installed"?"text-text-primary border-text-primary":"text-text-secondary border-transparent hover:text-text-primary"}`,children:e("plugins.installedPlugins")}),s.jsx("button",{onClick:()=>{x("browse"),R(null)},className:`px-4 py-2.5 text-[13px] font-medium border-b-2 transition-colors ${m==="browse"?"text-text-primary border-text-primary":"text-text-secondary border-transparent hover:text-text-primary"}`,children:e("plugins.browseMarketplace")}),s.jsx("button",{onClick:()=>{x("marketplaces"),R(null)},className:`px-4 py-2.5 text-[13px] font-medium border-b-2 transition-colors ${m==="marketplaces"?"text-text-primary border-text-primary":"text-text-secondary border-transparent hover:text-text-primary"}`,children:e("plugins.marketplaces")})]}),m==="installed"&&t.length>0&&s.jsxs("div",{className:"flex items-center gap-2 mt-4",children:[s.jsxs("div",{className:"flex-1 relative",children:[s.jsx(wt,{size:14,className:"absolute left-3 top-1/2 -translate-y-1/2 text-text-tertiary pointer-events-none"}),s.jsx("input",{type:"text",value:v,onChange:Y=>k(Y.target.value),placeholder:e("plugins.searchPlaceholder"),className:"w-full bg-bg-secondary text-text-primary text-[13px] border border-border-muted rounded-lg pl-9 pr-8 py-2 outline-none focus:ring-2 focus:ring-text-primary/10 focus:border-text-primary/30 transition-all placeholder:text-text-tertiary"}),v&&s.jsx("button",{onClick:()=>k(""),className:"absolute right-2.5 top-1/2 -translate-y-1/2 w-4 h-4 flex items-center justify-center rounded-full text-text-tertiary hover:text-text-secondary transition-colors",children:s.jsx(Ie,{size:12})})]}),Ze.length>1&&s.jsxs("select",{value:E,onChange:Y=>C(Y.target.value),className:"bg-bg-secondary text-text-primary text-[13px] border border-border-muted rounded-lg px-2 py-2 outline-none focus:ring-2 focus:ring-text-primary/10 focus:border-text-primary/30 transition-all cursor-pointer shrink-0 max-w-[120px] sm:max-w-[160px]",children:[s.jsx("option",{value:"all",children:e("plugins.allMarketplaces")}),Ze.map(Y=>s.jsx("option",{value:Y,children:Y},Y))]})]}),m==="browse"&&r.length>0&&s.jsxs("div",{className:"flex items-center gap-2 mt-4",children:[s.jsxs("div",{className:"flex-1 relative",children:[s.jsx(wt,{size:14,className:"absolute left-3 top-1/2 -translate-y-1/2 text-text-tertiary pointer-events-none"}),s.jsx("input",{type:"text",value:I,onChange:Y=>V(Y.target.value),placeholder:e("plugins.searchPlaceholder"),className:"w-full bg-bg-secondary text-text-primary text-[13px] border border-border-muted rounded-lg pl-9 pr-8 py-2 outline-none focus:ring-2 focus:ring-text-primary/10 focus:border-text-primary/30 transition-all placeholder:text-text-tertiary"}),I&&s.jsx("button",{onClick:()=>V(""),className:"absolute right-2.5 top-1/2 -translate-y-1/2 w-4 h-4 flex items-center justify-center rounded-full text-text-tertiary hover:text-text-secondary transition-colors",children:s.jsx(Ie,{size:12})})]}),s.jsxs("select",{value:J,onChange:Y=>rt(Y.target.value),className:"bg-bg-secondary text-text-primary text-[13px] border border-border-muted rounded-lg px-2 py-2 outline-none focus:ring-2 focus:ring-text-primary/10 focus:border-text-primary/30 transition-all cursor-pointer shrink-0 max-w-[120px] sm:max-w-[160px]",children:[s.jsx("option",{value:"__all__",children:e("plugins.allMarketplaces")}),r.map(Y=>s.jsx("option",{value:Y.name,children:Y.name},Y.name))]})]})]})}),s.jsx("div",{className:"flex-1 overflow-y-auto px-6 py-6",children:s.jsxs("div",{className:"max-w-3xl mx-auto space-y-6",children:[N&&s.jsxs("div",{className:"bg-accent-red/10 border border-accent-red/30 rounded-xl p-3.5 text-accent-red text-[13px] flex items-center justify-between",children:[s.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[s.jsx(mr,{size:14,className:"shrink-0"}),s.jsxs("span",{className:"truncate",children:[e("plugins.operationFailed"),": ",N]})]}),s.jsx("button",{onClick:()=>R(null),className:"w-5 h-5 flex items-center justify-center rounded-full hover:bg-accent-red/20 transition-colors shrink-0 ml-3",children:s.jsx(Ie,{size:12})})]}),m==="installed"&&s.jsxs(s.Fragment,{children:[i&&t.length===0&&s.jsx("div",{className:"flex flex-col items-center justify-center py-20",children:s.jsx(lt,{size:"small",text:e("plugins.loading")})}),g&&!i&&t.length===0&&s.jsxs("div",{className:"flex flex-col items-center justify-center py-20",children:[s.jsx(mr,{size:40,className:"text-text-tertiary opacity-40 mb-4"}),s.jsx("div",{className:"text-[14px] text-text-secondary font-medium mb-3",children:e("plugins.error")}),s.jsx("button",{onClick:f,className:"px-4 py-2 rounded-lg text-[13px] font-medium bg-text-primary text-white hover:opacity-80 transition-colors",children:e("plugins.retry")})]}),!i&&!g&&t.length===0&&s.jsxs("div",{className:"flex flex-col items-center justify-center py-20 text-text-tertiary",children:[s.jsx(gt,{size:48,className:"mb-4 opacity-30"}),s.jsx("div",{className:"text-[15px] font-medium mb-1.5 text-text-secondary",children:e("plugins.noPlugins")}),s.jsx("div",{className:"text-[13px]",children:e("plugins.noPluginsHint")})]}),t.length>0&&Ue.length===0&&!i&&s.jsxs("div",{className:"flex flex-col items-center justify-center py-16 text-text-tertiary",children:[s.jsx(wt,{size:36,className:"mb-3 opacity-30"}),s.jsx("div",{className:"text-[13px]",children:e("plugins.noSearchResults")})]}),Ue.length>0&&s.jsx("div",{className:"space-y-3",children:Ue.map(Y=>{const ie=nt(Y);return s.jsx(_h,{plugin:Y,isEnabled:Y.status==="enabled",isOperating:b.has(ie),isExpanded:W===ie,confirmUninstall:j===ie,onToggle:()=>ae(Y),onUninstall:()=>oe(Y),onConfirmUninstall:()=>q(ie),onCancelUninstall:()=>q(null),onExpand:()=>Z(ie),t:e},ie)})})]}),m==="browse"&&s.jsxs(s.Fragment,{children:[!a&&r.length===0&&s.jsxs("div",{className:"flex flex-col items-center justify-center py-20 text-text-tertiary",children:[s.jsx(At,{size:48,className:"mb-4 opacity-30"}),s.jsx("div",{className:"text-[15px] font-medium mb-1.5 text-text-secondary",children:e("plugins.noMarketplaces")}),s.jsx("div",{className:"text-[13px]",children:e("plugins.noMarketplacesHint")})]}),o&&n.length===0&&J&&s.jsx("div",{className:"flex flex-col items-center justify-center py-20",children:s.jsx(lt,{size:"small",text:e("plugins.browsingMarketplace")})}),d&&n.length===0&&J&&s.jsxs("div",{className:"flex flex-col items-center justify-center py-20",children:[s.jsx(mr,{size:40,className:"text-text-tertiary opacity-40 mb-4"}),s.jsx("div",{className:"text-[14px] text-text-secondary font-medium mb-3",children:e("plugins.error")}),s.jsx("button",{onClick:()=>J&&_(J),className:"px-4 py-2 rounded-lg text-[13px] font-medium bg-text-primary text-white hover:opacity-80 transition-colors",children:e("plugins.retry")})]}),J&&n.length===0&&!o&&!d&&s.jsxs("div",{className:"flex flex-col items-center justify-center py-20 text-text-tertiary",children:[s.jsx(gt,{size:48,className:"mb-4 opacity-30"}),s.jsx("div",{className:"text-[15px] font-medium mb-1.5 text-text-secondary",children:e("plugins.noAvailablePlugins")}),s.jsx("div",{className:"text-[13px]",children:e("plugins.noAvailablePluginsHint")})]}),n.length>0&&be.length===0&&!o&&s.jsxs("div",{className:"flex flex-col items-center justify-center py-16 text-text-tertiary",children:[s.jsx(wt,{size:36,className:"mb-3 opacity-30"}),s.jsx("div",{className:"text-[13px]",children:e("plugins.noSearchResults")})]}),be.length>0&&s.jsx("div",{className:"space-y-3",children:be.map(Y=>{const ie=`${Y.name}@${Y.marketplace}`;return s.jsx(yh,{plugin:Y,isInstalled:Y.installed,isOperating:b.has(ie),isExpanded:W===ie,onInstall:()=>ee(Y),onExpand:()=>Z(ie),t:e},ie)})})]}),m==="marketplaces"&&s.jsxs("div",{className:"space-y-3",children:[!B&&s.jsxs("button",{onClick:()=>A(!0),className:"flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-[12px] font-medium text-text-primary border border-border-muted hover:bg-bg-tertiary hover:border-text-primary/30 transition-colors",children:[s.jsx(Ke,{size:12}),e("plugins.addMarketplace")]}),B&&s.jsxs("div",{className:"bg-bg-secondary rounded-xl border border-border-muted p-4 space-y-3",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("span",{className:"text-[13px] font-medium",children:e("plugins.addMarketplace")}),s.jsx("button",{onClick:()=>{A(!1),P(null)},className:"w-6 h-6 flex items-center justify-center rounded-full hover:bg-bg-tertiary transition-colors text-text-secondary",children:s.jsx(Ie,{size:12})})]}),s.jsx("input",{type:"text",value:F,onChange:Y=>M(Y.target.value),placeholder:e("plugins.sourcePlaceholder"),className:"w-full bg-bg-primary text-text-primary text-[13px] border border-border-muted rounded-lg px-3 py-2 outline-none focus:ring-2 focus:ring-text-primary/10 focus:border-text-primary/30 transition-all placeholder:text-text-tertiary"}),s.jsx("input",{type:"text",value:H,onChange:Y=>z(Y.target.value),placeholder:e("plugins.namePlaceholder"),className:"w-full bg-bg-primary text-text-primary text-[13px] border border-border-muted rounded-lg px-3 py-2 outline-none focus:ring-2 focus:ring-text-primary/10 focus:border-text-primary/30 transition-all placeholder:text-text-tertiary"}),D&&s.jsx("div",{className:"text-accent-red text-[12px]",children:D}),s.jsxs("div",{className:"flex justify-end gap-2",children:[s.jsx("button",{onClick:()=>{A(!1),P(null)},className:"px-3 py-1.5 rounded-lg text-[12px] text-text-secondary hover:bg-bg-tertiary transition-colors",children:e("plugins.cancel")}),s.jsxs("button",{onClick:de,disabled:!F.trim()||G,className:"px-3 py-1.5 rounded-lg text-[12px] font-medium bg-text-primary text-white hover:opacity-80 transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-1.5",children:[G&&s.jsx(De,{size:12,className:"animate-spin"}),e("plugins.add")]})]})]}),a&&r.length===0&&s.jsx("div",{className:"flex items-center justify-center py-6",children:s.jsx(De,{size:18,className:"animate-spin text-text-tertiary"})}),!a&&r.length===0&&!B&&s.jsxs("div",{className:"flex flex-col items-center justify-center py-20 text-text-tertiary",children:[s.jsx(At,{size:48,className:"mb-4 opacity-30"}),s.jsx("div",{className:"text-[15px] font-medium mb-1.5 text-text-secondary",children:e("plugins.noMarketplaces")}),s.jsx("div",{className:"text-[13px]",children:e("plugins.noMarketplacesHint")})]}),r.length>0&&s.jsx("div",{className:"bg-bg-secondary rounded-xl border border-border-muted overflow-hidden",children:r.map((Y,ie)=>s.jsxs("div",{className:`flex items-center justify-between px-4 py-3 ${ie>0?"border-t border-border-muted":""}`,children:[s.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[s.jsx(At,{size:14,className:"text-text-tertiary shrink-0"}),s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"text-[13px] font-medium truncate",children:Y.name}),Y.type&&s.jsx("div",{className:"text-[11px] text-text-tertiary",children:Y.type})]})]}),s.jsx("div",{className:"flex items-center gap-2 shrink-0",children:K===Y.name?s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("button",{onClick:()=>ne(Y.name),className:"px-2.5 py-1 rounded-md text-[11px] font-medium text-white bg-accent-red hover:bg-accent-red/90 transition-colors",children:e("plugins.removeMarketplace")}),s.jsx("button",{onClick:()=>re(null),className:"px-2.5 py-1 rounded-md text-[11px] text-text-secondary hover:bg-bg-tertiary transition-colors",children:e("plugins.cancel")})]}):s.jsx("button",{onClick:()=>re(Y.name),className:"w-7 h-7 flex items-center justify-center rounded-md text-text-tertiary hover:text-accent-red hover:bg-accent-red/10 transition-colors",title:e("plugins.removeMarketplace"),children:s.jsx(Mt,{size:13})})})]},Y.name))})]})]})})]})}function _h({plugin:e,isEnabled:t,isOperating:r,isExpanded:i,confirmUninstall:a,onToggle:g,onUninstall:b,onConfirmUninstall:n,onCancelUninstall:o,onExpand:d,t:f}){return s.jsxs("div",{className:`group rounded-xl border transition-all ${t?"bg-bg-secondary border-border-muted":"bg-bg-secondary border-border-muted hover:border-border-muted"}`,children:[s.jsxs("div",{className:"flex items-start gap-4 px-5 py-4 cursor-pointer",onClick:d,children:[s.jsx("div",{className:`flex-shrink-0 w-9 h-9 rounded-lg flex items-center justify-center mt-0.5 ${t?"bg-text-primary/8":"bg-bg-tertiary"}`,children:s.jsx(gt,{size:18,className:t?"text-text-primary":"text-text-tertiary"})}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-0.5",children:[s.jsx("span",{className:"text-[14px] font-semibold text-text-primary truncate",children:e.name}),e.version&&s.jsxs("span",{className:"text-[11px] text-text-tertiary shrink-0 font-mono",children:["v",e.version]}),s.jsx("span",{className:`text-[10px] px-1.5 py-px rounded font-medium shrink-0 ${t?"bg-accent-green/15 text-accent-green":"bg-bg-tertiary text-text-tertiary"}`,children:f(t?"plugins.enabled":"plugins.disabled")})]}),e.description&&s.jsx("div",{className:`text-[12px] text-text-secondary leading-relaxed mb-1.5 ${i?"":"line-clamp-2"}`,children:e.description}),s.jsxs("div",{className:"flex items-center gap-1 text-[11px] text-text-tertiary",children:[s.jsx(At,{size:10,className:"shrink-0"}),s.jsx("span",{children:e.marketplace})]})]}),s.jsx("div",{className:"flex items-center gap-1.5 shrink-0 pt-0.5",onClick:h=>h.stopPropagation(),children:r?s.jsx("div",{className:"w-[72px] flex justify-center",children:s.jsx(De,{size:16,className:"animate-spin text-text-tertiary"})}):a?s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx("button",{onClick:b,className:"px-2.5 py-1 rounded-md text-[11px] font-medium text-white bg-accent-red hover:bg-accent-red/90 transition-colors",children:f("plugins.uninstall")}),s.jsx("button",{onClick:o,className:"px-2.5 py-1 rounded-md text-[11px] text-text-secondary hover:bg-bg-tertiary transition-colors",children:f("plugins.cancel")})]}):s.jsxs(s.Fragment,{children:[s.jsxs("button",{onClick:g,className:`px-2.5 py-1.5 rounded-md text-[11px] font-medium transition-colors flex items-center gap-1 ${t?"text-text-secondary border border-border-muted hover:bg-bg-tertiary":"text-text-primary border border-border-muted hover:bg-bg-tertiary"}`,title:f(t?"plugins.disable":"plugins.enable"),children:[t?s.jsx(Xd,{size:11}):s.jsx(Zd,{size:11}),f(t?"plugins.disable":"plugins.enable")]}),s.jsx("button",{onClick:n,className:"w-7 h-7 flex items-center justify-center rounded-md text-text-tertiary hover:text-accent-red hover:bg-accent-red/10 transition-colors opacity-0 group-hover:opacity-100",title:f("plugins.uninstall"),children:s.jsx(Mt,{size:13})})]})})]}),i&&s.jsx(Qc,{plugin:e,t:f})]})}function yh({plugin:e,isInstalled:t,isOperating:r,isExpanded:i,onInstall:a,onExpand:g,t:b}){return s.jsxs("div",{className:`group rounded-xl border transition-all ${t?"bg-bg-secondary border-border-muted":"bg-bg-secondary border-border-muted hover:border-border-muted"}`,children:[s.jsxs("div",{className:"flex items-start gap-4 px-5 py-4 cursor-pointer",onClick:g,children:[s.jsx("div",{className:`flex-shrink-0 w-9 h-9 rounded-lg flex items-center justify-center mt-0.5 ${t?"bg-text-primary/8":"bg-bg-tertiary"}`,children:s.jsx(gt,{size:18,className:t?"text-text-primary":"text-text-tertiary"})}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-0.5",children:[s.jsx("span",{className:"text-[14px] font-semibold text-text-primary truncate",children:e.name}),e.version&&s.jsxs("span",{className:"text-[11px] text-text-tertiary shrink-0 font-mono",children:["v",e.version]}),t&&s.jsx("span",{className:"text-[10px] px-1.5 py-px rounded font-medium shrink-0 bg-accent-green/15 text-accent-green",children:b("plugins.installedLabel")})]}),e.description&&s.jsx("div",{className:`text-[12px] text-text-secondary leading-relaxed mb-1.5 ${i?"":"line-clamp-2"}`,children:e.description}),s.jsxs("div",{className:"flex items-center gap-1 text-[11px] text-text-tertiary",children:[s.jsx(At,{size:10,className:"shrink-0"}),s.jsx("span",{children:e.marketplace})]})]}),s.jsx("div",{className:"flex items-center gap-1.5 shrink-0 pt-0.5",onClick:n=>n.stopPropagation(),children:t?s.jsx("div",{className:"px-2.5 py-1.5 rounded-md text-[11px] font-medium text-text-tertiary bg-bg-tertiary",children:b("plugins.installed")}):r?s.jsx("div",{className:"w-[72px] flex justify-center",children:s.jsx(De,{size:16,className:"animate-spin text-text-tertiary"})}):s.jsxs("button",{onClick:a,className:"px-2.5 py-1.5 rounded-md text-[11px] font-medium text-text-primary border border-border-muted hover:bg-bg-tertiary transition-colors flex items-center gap-1",title:b("plugins.install"),children:[s.jsx(jd,{size:11}),b("plugins.install")]})})]}),i&&s.jsx(Qc,{plugin:e,t:b})]})}function Qc({plugin:e,t}){const r=e.source,i=typeof r=="object"&&r!==null?r.url:void 0,a=typeof r=="object"&&r!==null?r.source:typeof r=="string"?r:void 0;return s.jsxs("div",{className:"border-t border-border-muted mx-5 px-0 py-3.5 space-y-2.5",children:[e.category&&s.jsx(Qe,{label:t("plugins.category"),children:s.jsx("span",{className:"text-[11px] px-2 py-0.5 rounded bg-[#f5a623]/8 text-[#b8860b] font-medium",children:e.category})}),e.author&&s.jsxs(Qe,{label:t("plugins.author"),children:[s.jsx("span",{className:"text-[12px] text-text-primary font-medium",children:e.author.name}),e.author.email&&s.jsx("a",{href:`mailto:${e.author.email}`,className:"text-[11px] text-text-tertiary hover:text-text-primary hover:underline ml-1",onClick:g=>g.stopPropagation(),children:e.author.email}),e.author.url&&s.jsxs("a",{href:e.author.url,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-0.5 text-[11px] text-text-tertiary hover:text-text-primary hover:underline ml-1",onClick:g=>g.stopPropagation(),children:[e.author.url,s.jsx(Gt,{size:9})]})]}),e.license&&s.jsx(Qe,{label:t("plugins.license"),children:s.jsx("span",{className:"text-[12px] text-text-secondary",children:e.license})}),e.homepage&&s.jsx(Qe,{label:t("plugins.homepage"),children:s.jsxs("a",{href:e.homepage,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1 text-[12px] text-text-secondary hover:text-text-primary hover:underline break-all",onClick:g=>g.stopPropagation(),children:[e.homepage,s.jsx(Gt,{size:10,className:"shrink-0 text-text-tertiary"})]})}),e.repository&&s.jsx(Qe,{label:t("plugins.repository"),children:s.jsxs("a",{href:e.repository,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1 text-[12px] text-text-secondary hover:text-text-primary hover:underline break-all",onClick:g=>g.stopPropagation(),children:[e.repository,s.jsx(Gt,{size:10,className:"shrink-0 text-text-tertiary"})]})}),a&&s.jsx(Qe,{label:t("plugins.source"),children:i?s.jsxs("a",{href:i,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1 text-[12px] text-text-secondary hover:text-text-primary hover:underline break-all",onClick:g=>g.stopPropagation(),children:[a,s.jsx(Gt,{size:10,className:"shrink-0 text-text-tertiary"})]}):s.jsx("span",{className:"text-[12px] text-text-secondary font-mono",children:a})}),e.keywords&&e.keywords.length>0&&s.jsx(Qe,{label:t("plugins.keywords"),children:s.jsx("div",{className:"flex flex-wrap gap-1",children:e.keywords.map(g=>s.jsx("span",{className:"text-[10px] px-1.5 py-px rounded bg-bg-tertiary text-text-tertiary",children:g},g))})}),e.features&&e.features.length>0&&s.jsx(Qe,{label:t("plugins.features"),children:s.jsx("ul",{className:"space-y-0.5",children:e.features.map((g,b)=>s.jsxs("li",{className:"text-[12px] text-text-secondary flex items-start gap-1.5",children:[s.jsx("span",{className:"text-text-tertiary shrink-0",children:"·"}),g]},b))})})]})}function Qe({label:e,children:t}){return s.jsxs("div",{className:"flex items-baseline gap-3",children:[s.jsx("span",{className:"text-[11px] text-text-tertiary w-12 shrink-0 text-right",children:e}),s.jsx("div",{className:"flex-1 min-w-0 flex items-baseline flex-wrap gap-1",children:t})]})}const Hr=Ge(e=>({info:null,loading:!1,fetch:async()=>{e({loading:!0});try{const t=await Oe("/api/v1/info",{headers:Fe()});if(t.ok){const r=await t.json();e({info:r,loading:!1})}else e({loading:!1})}catch{e({loading:!1})}}}));function Jc(){const{status:e,sessionId:t,currentModel:r,models:i,modes:a,currentMode:g}=Xe(),{info:b,fetch:n}=Hr(),{mode:o,toggle:d}=Ot(),{t:f,locale:h,toggleLocale:_}=ue(),[S,w]=O.useState(null);O.useEffect(()=>{b||n()},[b,n]);const y=O.useCallback((E,C)=>{navigator.clipboard.writeText(E).then(()=>{w(C),setTimeout(()=>w(null),1500)})},[]),c=async E=>{if(t)try{await xe().setModel(t,E)}catch(C){console.error("Model change failed:",C)}},p=async E=>{if(t)try{await xe().setMode(t,E)}catch(C){console.error("Mode change failed:",C)}},l={disconnected:"bg-gray-400",connecting:"bg-accent-yellow animate-pulse",connected:"bg-accent-green",error:"bg-accent-red"}[e],u={connected:"connection.connected",connecting:"connection.connecting",disconnected:"connection.disconnected",error:"connection.error"},m=o==="light"?su:o==="dark"?Wd:iu,x=f(o==="light"?"theme.light":o==="dark"?"theme.dark":"theme.system"),v=h==="system"?Hd:Kr,k=f(h==="zh"?"locale.zh":h==="en"?"locale.en":"locale.system");return s.jsx("div",{className:"settings-view",children:s.jsx("div",{className:"settings-content",children:s.jsxs("div",{className:"settings-sections",children:[s.jsxs("div",{className:"settings-group",children:[s.jsx("h2",{className:"settings-group-title",children:f("sidebar.connectionStatus")}),s.jsxs("div",{className:"settings-card",children:[s.jsxs("div",{className:"settings-row",children:[s.jsx("span",{className:"settings-label",children:f("sidebar.status")}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:`w-2 h-2 rounded-full ${l}`}),s.jsx("span",{className:"settings-value",children:f(u[e]||"connection.disconnected")})]})]}),s.jsxs("div",{className:"settings-row",children:[s.jsx("span",{className:"settings-label",children:f("sidebar.sessionId")}),s.jsx("span",{className:"settings-value font-mono text-[12px]",children:t?t.substring(0,12):f("sidebar.notConnected")})]})]})]}),s.jsxs("div",{className:"settings-group",children:[s.jsx("h2",{className:"settings-group-title",children:f("settings.appearance")}),s.jsxs("div",{className:"settings-card",children:[s.jsxs("div",{className:"settings-row",children:[s.jsx("span",{className:"settings-label",children:f("sidebar.theme")}),s.jsxs("button",{onClick:d,className:"settings-toggle-btn",children:[s.jsx(m,{size:14,className:"text-accent-brand"}),s.jsx("span",{children:x})]})]}),s.jsxs("div",{className:"settings-row",children:[s.jsx("span",{className:"settings-label",children:f("sidebar.language")}),s.jsxs("button",{onClick:_,className:"settings-toggle-btn",children:[s.jsx(v,{size:14,className:"text-accent-brand"}),s.jsx("span",{children:k})]})]})]})]}),i.length>0&&s.jsxs("div",{className:"settings-group",children:[s.jsx("h2",{className:"settings-group-title",children:f("settings.model")}),s.jsx("div",{className:"settings-card",children:s.jsx("select",{value:r,onChange:E=>c(E.target.value),className:"settings-select",children:i.map(E=>s.jsx("option",{value:E.id,children:E.name||E.id},E.id))})})]}),a.length>0&&s.jsxs("div",{className:"settings-group",children:[s.jsx("h2",{className:"settings-group-title",children:f("settings.mode")}),s.jsx("div",{className:"settings-card",children:s.jsx("select",{value:g,onChange:E=>p(E.target.value),className:"settings-select",children:a.map(E=>s.jsx("option",{value:E.id,title:E.description,children:E.name},E.id))})})]}),b&&s.jsxs("div",{className:"settings-group",children:[s.jsx("h2",{className:"settings-group-title",children:f("settings.systemInfo")}),s.jsxs("div",{className:"settings-card",children:[s.jsxs("div",{className:"settings-row",children:[s.jsx("span",{className:"settings-label",children:f("sidebar.cwd")}),s.jsxs("button",{onClick:()=>y(b.cwd,"cwd"),className:"settings-copy-btn",title:b.cwd,children:[s.jsx("span",{className:"truncate",children:b.cwd}),S==="cwd"?s.jsx(Ye,{size:12,className:"shrink-0 text-accent-green"}):s.jsx(Tr,{size:12,className:"shrink-0 text-text-tertiary"})]})]}),s.jsxs("div",{className:"settings-row",children:[s.jsx("span",{className:"settings-label",children:f("sidebar.os")}),s.jsxs("span",{className:"settings-value",children:[b.os," ",b.arch]})]}),s.jsxs("div",{className:"settings-row",children:[s.jsx("span",{className:"settings-label",children:f("sidebar.nodeVersion")}),s.jsx("span",{className:"settings-value",children:b.nodeVersion})]}),s.jsxs("div",{className:"settings-row",children:[s.jsx("span",{className:"settings-label",children:f("sidebar.gatewayMode")}),s.jsx("span",{className:"settings-value capitalize",children:b.gatewayMode})]}),b.tunnelUrl&&s.jsxs("div",{className:"settings-row",children:[s.jsx("span",{className:"settings-label",children:f("sidebar.tunnelUrl")}),s.jsxs("button",{onClick:()=>y(b.tunnelUrl,"tunnel"),className:"settings-copy-btn",title:b.tunnelUrl,children:[s.jsx("span",{className:"truncate",children:b.tunnelUrl.replace(/^https?:\/\//,"")}),S==="tunnel"?s.jsx(Ye,{size:12,className:"shrink-0 text-accent-green"}):s.jsx(Tr,{size:12,className:"shrink-0 text-text-tertiary"})]})]})]})]})]})})})}const vh=3e3;function ed(){const{t:e}=ue(),{setMainView:t}=me(),{setExternalInput:r,sessionId:i}=Xe(),[a,g]=O.useState([]),[b,n]=O.useState(!0),[o,d]=O.useState(null),[f,h]=O.useState(!1),[_,S]=O.useState(!1),w=O.useRef(i);w.current=i;const y=O.useRef(null),c=O.useCallback(()=>{y.current&&(clearInterval(y.current),y.current=null)},[]),p=O.useCallback(async()=>{const v=new URLSearchParams,k=w.current;k&&v.append("sessionId",k);const E=v.toString(),C=`/api/v1/tasks/templates${E?"?"+E:""}`,N=await fetch(C,{headers:Fe()});if(!N.ok)throw new Error(`HTTP ${N.status}`);const R=await N.json();return g(R.templates||[]),d(R.error||null),R.status},[]),l=O.useCallback(()=>{c(),y.current=setInterval(async()=>{try{const v=await p();v!=="loading"&&(c(),h(!1),v==="done"&&(S(!0),setTimeout(()=>S(!1),2e3)))}catch(v){console.error("[TasksView] Poll error:",v),c(),h(!1),d(v.message||"Failed to load templates")}},vh)},[p,c]);O.useEffect(()=>{let v=!1;return(async()=>{try{if(!w.current){if(v)return;n(!1);return}const E=await p();if(v)return;E==="loading"&&(h(!0),l())}catch(k){if(v)return;console.error("[TasksView] Initial fetch error:",k),d(k.message||"Failed to load templates")}finally{v||n(!1)}})(),()=>{v=!0,c()}},[p,l,c,i]);const u=O.useCallback(async()=>{h(!0),d(null),S(!1);try{const v=new URLSearchParams,k=w.current;k&&v.append("sessionId",k);const E=v.toString(),C=`/api/v1/tasks/templates/refresh${E?"?"+E:""}`,N=await fetch(C,{method:"POST",headers:Fe()});if(!N.ok)throw new Error(`HTTP ${N.status}`);l()}catch(v){console.error("[TasksView] Refresh trigger error:",v),d(v.message||"Failed to trigger refresh"),h(!1)}},[l]),m=O.useCallback(v=>{r(v.command),t("chat")},[r,t]),x=!b&&a.length===0&&!o;return s.jsxs("div",{className:"flex-1 flex flex-col overflow-hidden bg-bg-primary",children:[s.jsx("div",{className:"flex-none border-b border-border-default px-6 py-4",children:s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{children:[s.jsx("h1",{className:"text-lg font-semibold text-text-primary",children:e("tasks.title")}),s.jsx("p",{className:"text-sm text-text-tertiary mt-1",children:e("tasks.subtitle")})]}),s.jsxs("button",{onClick:u,disabled:f,className:`flex items-center gap-2 px-3 py-2 rounded-lg border transition-all ${_?"border-green-500/50 text-green-500":f?"opacity-50 cursor-not-allowed border-border-default text-text-secondary":"border-border-default text-text-secondary hover:text-text-primary hover:border-accent-brand/50 hover:bg-bg-secondary"}`,title:e("tasks.refresh"),children:[_?s.jsx(Ye,{size:16}):s.jsx(Dt,{size:16,className:f?"animate-spin":""}),s.jsx("span",{className:"text-sm",children:e(_?"tasks.refreshed":"tasks.refresh")})]})]})}),s.jsxs("div",{className:"flex-1 overflow-y-auto px-6 py-6",children:[b&&!f&&s.jsx("div",{className:"flex flex-col items-center justify-center h-full text-text-tertiary",children:s.jsx(lt,{size:"small",text:e("tasks.loading")})}),o&&!b&&s.jsx("div",{className:"flex flex-col items-center justify-center h-full",children:s.jsxs("div",{className:"text-center",children:[s.jsx("div",{className:"text-text-tertiary text-[48px] mb-4 opacity-30",children:"⚠"}),s.jsx("div",{className:"text-text-secondary text-sm mb-4",children:e("tasks.error")}),s.jsx("button",{onClick:u,className:"px-4 py-2 rounded-lg bg-accent-brand text-white text-sm font-medium hover:bg-accent-brand/90 transition-colors",children:e("tasks.retry")})]})}),x&&s.jsxs("div",{className:"flex flex-col items-center justify-center h-full text-text-tertiary",children:[s.jsx("div",{className:"text-[48px] mb-4 opacity-30",children:"📋"}),s.jsx("div",{className:"text-sm font-medium mb-1",children:e("tasks.empty")})]}),a.length>0&&s.jsx("div",{className:`grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3 max-w-6xl transition-opacity duration-300 ${f?"opacity-50 pointer-events-none":"opacity-100"}`,children:a.map(v=>{const k=Sh(v.icon);return s.jsxs("div",{onClick:()=>m(v),className:"group flex items-center gap-4 px-4 py-3.5 rounded-xl border border-border-default hover:border-accent-brand/40 hover:bg-bg-secondary/60 transition-all cursor-pointer",children:[s.jsx("div",{className:"flex-shrink-0 w-10 h-10 rounded-lg bg-bg-secondary flex items-center justify-center group-hover:bg-accent-brand/10 transition-colors",children:s.jsx(k,{size:20,className:"text-text-tertiary group-hover:text-accent-brand transition-colors"})}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("h3",{className:"text-sm font-semibold text-text-primary truncate",children:v.title}),s.jsx("p",{className:"text-xs text-text-tertiary mt-0.5 truncate",children:v.description})]})]},v.id)})})]})]})}function Sh(e){switch(e){case"Newspaper":return bl;case"MessageSquare":return bl;case"GitBranch":return Ud;case"Package":return qd;case"FileText":return tt;case"Zap":return au;case"Clock":return hl;default:return hl}}function Eh({direction:e,ratio:t,onRatioChange:r,children:i}){const a=O.useRef(null),[g,b]=O.useState(!1),n=O.useCallback(h=>{h.preventDefault(),h.stopPropagation(),b(!0);const _=a.current;if(!_)return;const S=_.getBoundingClientRect(),w=c=>{let p;e==="horizontal"?p=(c.clientX-S.left)/S.width:p=(c.clientY-S.top)/S.height,p=Math.max(.1,Math.min(.9,p)),r(p)},y=()=>{b(!1),document.removeEventListener("mousemove",w),document.removeEventListener("mouseup",y),document.body.style.cursor="",document.body.style.userSelect=""};document.addEventListener("mousemove",w),document.addEventListener("mouseup",y),document.body.style.cursor=e==="horizontal"?"col-resize":"row-resize",document.body.style.userSelect="none"},[e,r]),o=e==="horizontal",d=`${t*100}%`,f=`${(1-t)*100}%`;return s.jsxs("div",{ref:a,className:"flex h-full w-full",style:{flexDirection:o?"row":"column"},children:[s.jsx("div",{style:{[o?"width":"height"]:d,overflow:"hidden",display:"flex"},children:i[0]}),s.jsx("div",{className:`split-sash ${o?"split-sash-horizontal":"split-sash-vertical"} ${g?"dragging":""}`,onMouseDown:n}),s.jsx("div",{style:{[o?"width":"height"]:f,overflow:"hidden",display:"flex"},children:i[1]})]})}var vr={exports:{}},Gl;function xh(){return Gl||(Gl=1,(function(e,t){(function(r,i){e.exports=i()})(self,(()=>(()=>{var r={};return(()=>{var i=r;Object.defineProperty(i,"__esModule",{value:!0}),i.FitAddon=void 0,i.FitAddon=class{activate(a){this._terminal=a}dispose(){}fit(){const a=this.proposeDimensions();if(!a||!this._terminal||isNaN(a.cols)||isNaN(a.rows))return;const g=this._terminal._core;this._terminal.rows===a.rows&&this._terminal.cols===a.cols||(g._renderService.clear(),this._terminal.resize(a.cols,a.rows))}proposeDimensions(){if(!this._terminal||!this._terminal.element||!this._terminal.element.parentElement)return;const a=this._terminal._core,g=a._renderService.dimensions;if(g.css.cell.width===0||g.css.cell.height===0)return;const b=this._terminal.options.scrollback===0?0:a.viewport.scrollBarWidth,n=window.getComputedStyle(this._terminal.element.parentElement),o=parseInt(n.getPropertyValue("height")),d=Math.max(0,parseInt(n.getPropertyValue("width"))),f=window.getComputedStyle(this._terminal.element),h=o-(parseInt(f.getPropertyValue("padding-top"))+parseInt(f.getPropertyValue("padding-bottom"))),_=d-(parseInt(f.getPropertyValue("padding-right"))+parseInt(f.getPropertyValue("padding-left")))-b;return{cols:Math.max(2,Math.floor(_/g.css.cell.width)),rows:Math.max(1,Math.floor(h/g.css.cell.height))}}}})(),r})()))})(vr)),vr.exports}var wh=xh(),Sr={exports:{}},Wl;function kh(){return Wl||(Wl=1,(function(e,t){(function(r,i){e.exports=i()})(globalThis,(()=>(()=>{var r={4567:function(b,n,o){var d=this&&this.__decorate||function(l,u,m,x){var v,k=arguments.length,E=k<3?u:x===null?x=Object.getOwnPropertyDescriptor(u,m):x;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")E=Reflect.decorate(l,u,m,x);else for(var C=l.length-1;C>=0;C--)(v=l[C])&&(E=(k<3?v(E):k>3?v(u,m,E):v(u,m))||E);return k>3&&E&&Object.defineProperty(u,m,E),E},f=this&&this.__param||function(l,u){return function(m,x){u(m,x,l)}};Object.defineProperty(n,"__esModule",{value:!0}),n.AccessibilityManager=void 0;const h=o(9042),_=o(9924),S=o(844),w=o(4725),y=o(2585),c=o(3656);let p=n.AccessibilityManager=class extends S.Disposable{constructor(l,u,m,x){super(),this._terminal=l,this._coreBrowserService=m,this._renderService=x,this._rowColumns=new WeakMap,this._liveRegionLineCount=0,this._charsToConsume=[],this._charsToAnnounce="",this._accessibilityContainer=this._coreBrowserService.mainDocument.createElement("div"),this._accessibilityContainer.classList.add("xterm-accessibility"),this._rowContainer=this._coreBrowserService.mainDocument.createElement("div"),this._rowContainer.setAttribute("role","list"),this._rowContainer.classList.add("xterm-accessibility-tree"),this._rowElements=[];for(let v=0;v<this._terminal.rows;v++)this._rowElements[v]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[v]);if(this._topBoundaryFocusListener=v=>this._handleBoundaryFocus(v,0),this._bottomBoundaryFocusListener=v=>this._handleBoundaryFocus(v,1),this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._refreshRowsDimensions(),this._accessibilityContainer.appendChild(this._rowContainer),this._liveRegion=this._coreBrowserService.mainDocument.createElement("div"),this._liveRegion.classList.add("live-region"),this._liveRegion.setAttribute("aria-live","assertive"),this._accessibilityContainer.appendChild(this._liveRegion),this._liveRegionDebouncer=this.register(new _.TimeBasedDebouncer(this._renderRows.bind(this))),!this._terminal.element)throw new Error("Cannot enable accessibility before Terminal.open");this._terminal.element.insertAdjacentElement("afterbegin",this._accessibilityContainer),this.register(this._terminal.onResize((v=>this._handleResize(v.rows)))),this.register(this._terminal.onRender((v=>this._refreshRows(v.start,v.end)))),this.register(this._terminal.onScroll((()=>this._refreshRows()))),this.register(this._terminal.onA11yChar((v=>this._handleChar(v)))),this.register(this._terminal.onLineFeed((()=>this._handleChar(`
|
|
398
398
|
`)))),this.register(this._terminal.onA11yTab((v=>this._handleTab(v)))),this.register(this._terminal.onKey((v=>this._handleKey(v.key)))),this.register(this._terminal.onBlur((()=>this._clearLiveRegion()))),this.register(this._renderService.onDimensionsChange((()=>this._refreshRowsDimensions()))),this.register((0,c.addDisposableDomListener)(document,"selectionchange",(()=>this._handleSelectionChange()))),this.register(this._coreBrowserService.onDprChange((()=>this._refreshRowsDimensions()))),this._refreshRows(),this.register((0,S.toDisposable)((()=>{this._accessibilityContainer.remove(),this._rowElements.length=0})))}_handleTab(l){for(let u=0;u<l;u++)this._handleChar(" ")}_handleChar(l){this._liveRegionLineCount<21&&(this._charsToConsume.length>0?this._charsToConsume.shift()!==l&&(this._charsToAnnounce+=l):this._charsToAnnounce+=l,l===`
|
|
399
399
|
`&&(this._liveRegionLineCount++,this._liveRegionLineCount===21&&(this._liveRegion.textContent+=h.tooMuchOutput)))}_clearLiveRegion(){this._liveRegion.textContent="",this._liveRegionLineCount=0}_handleKey(l){this._clearLiveRegion(),new RegExp("\\p{Control}","u").test(l)||this._charsToConsume.push(l)}_refreshRows(l,u){this._liveRegionDebouncer.refresh(l,u,this._terminal.rows)}_renderRows(l,u){const m=this._terminal.buffer,x=m.lines.length.toString();for(let v=l;v<=u;v++){const k=m.lines.get(m.ydisp+v),E=[],C=(k==null?void 0:k.translateToString(!0,void 0,void 0,E))||"",N=(m.ydisp+v+1).toString(),R=this._rowElements[v];R&&(C.length===0?(R.innerText=" ",this._rowColumns.set(R,[0,1])):(R.textContent=C,this._rowColumns.set(R,E)),R.setAttribute("aria-posinset",N),R.setAttribute("aria-setsize",x))}this._announceCharacters()}_announceCharacters(){this._charsToAnnounce.length!==0&&(this._liveRegion.textContent+=this._charsToAnnounce,this._charsToAnnounce="")}_handleBoundaryFocus(l,u){const m=l.target,x=this._rowElements[u===0?1:this._rowElements.length-2];if(m.getAttribute("aria-posinset")===(u===0?"1":`${this._terminal.buffer.lines.length}`)||l.relatedTarget!==x)return;let v,k;if(u===0?(v=m,k=this._rowElements.pop(),this._rowContainer.removeChild(k)):(v=this._rowElements.shift(),k=m,this._rowContainer.removeChild(v)),v.removeEventListener("focus",this._topBoundaryFocusListener),k.removeEventListener("focus",this._bottomBoundaryFocusListener),u===0){const E=this._createAccessibilityTreeNode();this._rowElements.unshift(E),this._rowContainer.insertAdjacentElement("afterbegin",E)}else{const E=this._createAccessibilityTreeNode();this._rowElements.push(E),this._rowContainer.appendChild(E)}this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._terminal.scrollLines(u===0?-1:1),this._rowElements[u===0?1:this._rowElements.length-2].focus(),l.preventDefault(),l.stopImmediatePropagation()}_handleSelectionChange(){var C;if(this._rowElements.length===0)return;const l=document.getSelection();if(!l)return;if(l.isCollapsed)return void(this._rowContainer.contains(l.anchorNode)&&this._terminal.clearSelection());if(!l.anchorNode||!l.focusNode)return void console.error("anchorNode and/or focusNode are null");let u={node:l.anchorNode,offset:l.anchorOffset},m={node:l.focusNode,offset:l.focusOffset};if((u.node.compareDocumentPosition(m.node)&Node.DOCUMENT_POSITION_PRECEDING||u.node===m.node&&u.offset>m.offset)&&([u,m]=[m,u]),u.node.compareDocumentPosition(this._rowElements[0])&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_FOLLOWING)&&(u={node:this._rowElements[0].childNodes[0],offset:0}),!this._rowContainer.contains(u.node))return;const x=this._rowElements.slice(-1)[0];if(m.node.compareDocumentPosition(x)&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_PRECEDING)&&(m={node:x,offset:((C=x.textContent)==null?void 0:C.length)??0}),!this._rowContainer.contains(m.node))return;const v=({node:N,offset:R})=>{const B=N instanceof Text?N.parentNode:N;let A=parseInt(B==null?void 0:B.getAttribute("aria-posinset"),10)-1;if(isNaN(A))return console.warn("row is invalid. Race condition?"),null;const F=this._rowColumns.get(B);if(!F)return console.warn("columns is null. Race condition?"),null;let M=R<F.length?F[R]:F.slice(-1)[0]+1;return M>=this._terminal.cols&&(++A,M=0),{row:A,column:M}},k=v(u),E=v(m);if(k&&E){if(k.row>E.row||k.row===E.row&&k.column>=E.column)throw new Error("invalid range");this._terminal.select(k.column,k.row,(E.row-k.row)*this._terminal.cols-k.column+E.column)}}_handleResize(l){this._rowElements[this._rowElements.length-1].removeEventListener("focus",this._bottomBoundaryFocusListener);for(let u=this._rowContainer.children.length;u<this._terminal.rows;u++)this._rowElements[u]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[u]);for(;this._rowElements.length>l;)this._rowContainer.removeChild(this._rowElements.pop());this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._refreshRowsDimensions()}_createAccessibilityTreeNode(){const l=this._coreBrowserService.mainDocument.createElement("div");return l.setAttribute("role","listitem"),l.tabIndex=-1,this._refreshRowDimensions(l),l}_refreshRowsDimensions(){if(this._renderService.dimensions.css.cell.height){this._accessibilityContainer.style.width=`${this._renderService.dimensions.css.canvas.width}px`,this._rowElements.length!==this._terminal.rows&&this._handleResize(this._terminal.rows);for(let l=0;l<this._terminal.rows;l++)this._refreshRowDimensions(this._rowElements[l])}}_refreshRowDimensions(l){l.style.height=`${this._renderService.dimensions.css.cell.height}px`}};n.AccessibilityManager=p=d([f(1,y.IInstantiationService),f(2,w.ICoreBrowserService),f(3,w.IRenderService)],p)},3614:(b,n)=>{function o(_){return _.replace(/\r?\n/g,"\r")}function d(_,S){return S?"\x1B[200~"+_+"\x1B[201~":_}function f(_,S,w,y){_=d(_=o(_),w.decPrivateModes.bracketedPasteMode&&y.rawOptions.ignoreBracketedPasteMode!==!0),w.triggerDataEvent(_,!0),S.value=""}function h(_,S,w){const y=w.getBoundingClientRect(),c=_.clientX-y.left-10,p=_.clientY-y.top-10;S.style.width="20px",S.style.height="20px",S.style.left=`${c}px`,S.style.top=`${p}px`,S.style.zIndex="1000",S.focus()}Object.defineProperty(n,"__esModule",{value:!0}),n.rightClickHandler=n.moveTextAreaUnderMouseCursor=n.paste=n.handlePasteEvent=n.copyHandler=n.bracketTextForPaste=n.prepareTextForTerminal=void 0,n.prepareTextForTerminal=o,n.bracketTextForPaste=d,n.copyHandler=function(_,S){_.clipboardData&&_.clipboardData.setData("text/plain",S.selectionText),_.preventDefault()},n.handlePasteEvent=function(_,S,w,y){_.stopPropagation(),_.clipboardData&&f(_.clipboardData.getData("text/plain"),S,w,y)},n.paste=f,n.moveTextAreaUnderMouseCursor=h,n.rightClickHandler=function(_,S,w,y,c){h(_,S,w),c&&y.rightClickSelect(_),S.value=y.selectionText,S.select()}},7239:(b,n,o)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.ColorContrastCache=void 0;const d=o(1505);n.ColorContrastCache=class{constructor(){this._color=new d.TwoKeyMap,this._css=new d.TwoKeyMap}setCss(f,h,_){this._css.set(f,h,_)}getCss(f,h){return this._css.get(f,h)}setColor(f,h,_){this._color.set(f,h,_)}getColor(f,h){return this._color.get(f,h)}clear(){this._color.clear(),this._css.clear()}}},3656:(b,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.addDisposableDomListener=void 0,n.addDisposableDomListener=function(o,d,f,h){o.addEventListener(d,f,h);let _=!1;return{dispose:()=>{_||(_=!0,o.removeEventListener(d,f,h))}}}},3551:function(b,n,o){var d=this&&this.__decorate||function(p,l,u,m){var x,v=arguments.length,k=v<3?l:m===null?m=Object.getOwnPropertyDescriptor(l,u):m;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")k=Reflect.decorate(p,l,u,m);else for(var E=p.length-1;E>=0;E--)(x=p[E])&&(k=(v<3?x(k):v>3?x(l,u,k):x(l,u))||k);return v>3&&k&&Object.defineProperty(l,u,k),k},f=this&&this.__param||function(p,l){return function(u,m){l(u,m,p)}};Object.defineProperty(n,"__esModule",{value:!0}),n.Linkifier=void 0;const h=o(3656),_=o(8460),S=o(844),w=o(2585),y=o(4725);let c=n.Linkifier=class extends S.Disposable{get currentLink(){return this._currentLink}constructor(p,l,u,m,x){super(),this._element=p,this._mouseService=l,this._renderService=u,this._bufferService=m,this._linkProviderService=x,this._linkCacheDisposables=[],this._isMouseOut=!0,this._wasResized=!1,this._activeLine=-1,this._onShowLinkUnderline=this.register(new _.EventEmitter),this.onShowLinkUnderline=this._onShowLinkUnderline.event,this._onHideLinkUnderline=this.register(new _.EventEmitter),this.onHideLinkUnderline=this._onHideLinkUnderline.event,this.register((0,S.getDisposeArrayDisposable)(this._linkCacheDisposables)),this.register((0,S.toDisposable)((()=>{var v;this._lastMouseEvent=void 0,(v=this._activeProviderReplies)==null||v.clear()}))),this.register(this._bufferService.onResize((()=>{this._clearCurrentLink(),this._wasResized=!0}))),this.register((0,h.addDisposableDomListener)(this._element,"mouseleave",(()=>{this._isMouseOut=!0,this._clearCurrentLink()}))),this.register((0,h.addDisposableDomListener)(this._element,"mousemove",this._handleMouseMove.bind(this))),this.register((0,h.addDisposableDomListener)(this._element,"mousedown",this._handleMouseDown.bind(this))),this.register((0,h.addDisposableDomListener)(this._element,"mouseup",this._handleMouseUp.bind(this)))}_handleMouseMove(p){this._lastMouseEvent=p;const l=this._positionFromMouseEvent(p,this._element,this._mouseService);if(!l)return;this._isMouseOut=!1;const u=p.composedPath();for(let m=0;m<u.length;m++){const x=u[m];if(x.classList.contains("xterm"))break;if(x.classList.contains("xterm-hover"))return}this._lastBufferCell&&l.x===this._lastBufferCell.x&&l.y===this._lastBufferCell.y||(this._handleHover(l),this._lastBufferCell=l)}_handleHover(p){if(this._activeLine!==p.y||this._wasResized)return this._clearCurrentLink(),this._askForLink(p,!1),void(this._wasResized=!1);this._currentLink&&this._linkAtPosition(this._currentLink.link,p)||(this._clearCurrentLink(),this._askForLink(p,!0))}_askForLink(p,l){var m,x;this._activeProviderReplies&&l||((m=this._activeProviderReplies)==null||m.forEach((v=>{v==null||v.forEach((k=>{k.link.dispose&&k.link.dispose()}))})),this._activeProviderReplies=new Map,this._activeLine=p.y);let u=!1;for(const[v,k]of this._linkProviderService.linkProviders.entries())l?(x=this._activeProviderReplies)!=null&&x.get(v)&&(u=this._checkLinkProviderResult(v,p,u)):k.provideLinks(p.y,(E=>{var N,R;if(this._isMouseOut)return;const C=E==null?void 0:E.map((B=>({link:B})));(N=this._activeProviderReplies)==null||N.set(v,C),u=this._checkLinkProviderResult(v,p,u),((R=this._activeProviderReplies)==null?void 0:R.size)===this._linkProviderService.linkProviders.length&&this._removeIntersectingLinks(p.y,this._activeProviderReplies)}))}_removeIntersectingLinks(p,l){const u=new Set;for(let m=0;m<l.size;m++){const x=l.get(m);if(x)for(let v=0;v<x.length;v++){const k=x[v],E=k.link.range.start.y<p?0:k.link.range.start.x,C=k.link.range.end.y>p?this._bufferService.cols:k.link.range.end.x;for(let N=E;N<=C;N++){if(u.has(N)){x.splice(v--,1);break}u.add(N)}}}}_checkLinkProviderResult(p,l,u){var v;if(!this._activeProviderReplies)return u;const m=this._activeProviderReplies.get(p);let x=!1;for(let k=0;k<p;k++)this._activeProviderReplies.has(k)&&!this._activeProviderReplies.get(k)||(x=!0);if(!x&&m){const k=m.find((E=>this._linkAtPosition(E.link,l)));k&&(u=!0,this._handleNewLink(k))}if(this._activeProviderReplies.size===this._linkProviderService.linkProviders.length&&!u)for(let k=0;k<this._activeProviderReplies.size;k++){const E=(v=this._activeProviderReplies.get(k))==null?void 0:v.find((C=>this._linkAtPosition(C.link,l)));if(E){u=!0,this._handleNewLink(E);break}}return u}_handleMouseDown(){this._mouseDownLink=this._currentLink}_handleMouseUp(p){if(!this._currentLink)return;const l=this._positionFromMouseEvent(p,this._element,this._mouseService);l&&this._mouseDownLink===this._currentLink&&this._linkAtPosition(this._currentLink.link,l)&&this._currentLink.link.activate(p,this._currentLink.link.text)}_clearCurrentLink(p,l){this._currentLink&&this._lastMouseEvent&&(!p||!l||this._currentLink.link.range.start.y>=p&&this._currentLink.link.range.end.y<=l)&&(this._linkLeave(this._element,this._currentLink.link,this._lastMouseEvent),this._currentLink=void 0,(0,S.disposeArray)(this._linkCacheDisposables))}_handleNewLink(p){if(!this._lastMouseEvent)return;const l=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);l&&this._linkAtPosition(p.link,l)&&(this._currentLink=p,this._currentLink.state={decorations:{underline:p.link.decorations===void 0||p.link.decorations.underline,pointerCursor:p.link.decorations===void 0||p.link.decorations.pointerCursor},isHovered:!0},this._linkHover(this._element,p.link,this._lastMouseEvent),p.link.decorations={},Object.defineProperties(p.link.decorations,{pointerCursor:{get:()=>{var u,m;return(m=(u=this._currentLink)==null?void 0:u.state)==null?void 0:m.decorations.pointerCursor},set:u=>{var m;(m=this._currentLink)!=null&&m.state&&this._currentLink.state.decorations.pointerCursor!==u&&(this._currentLink.state.decorations.pointerCursor=u,this._currentLink.state.isHovered&&this._element.classList.toggle("xterm-cursor-pointer",u))}},underline:{get:()=>{var u,m;return(m=(u=this._currentLink)==null?void 0:u.state)==null?void 0:m.decorations.underline},set:u=>{var m,x,v;(m=this._currentLink)!=null&&m.state&&((v=(x=this._currentLink)==null?void 0:x.state)==null?void 0:v.decorations.underline)!==u&&(this._currentLink.state.decorations.underline=u,this._currentLink.state.isHovered&&this._fireUnderlineEvent(p.link,u))}}}),this._linkCacheDisposables.push(this._renderService.onRenderedViewportChange((u=>{if(!this._currentLink)return;const m=u.start===0?0:u.start+1+this._bufferService.buffer.ydisp,x=this._bufferService.buffer.ydisp+1+u.end;if(this._currentLink.link.range.start.y>=m&&this._currentLink.link.range.end.y<=x&&(this._clearCurrentLink(m,x),this._lastMouseEvent)){const v=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);v&&this._askForLink(v,!1)}}))))}_linkHover(p,l,u){var m;(m=this._currentLink)!=null&&m.state&&(this._currentLink.state.isHovered=!0,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(l,!0),this._currentLink.state.decorations.pointerCursor&&p.classList.add("xterm-cursor-pointer")),l.hover&&l.hover(u,l.text)}_fireUnderlineEvent(p,l){const u=p.range,m=this._bufferService.buffer.ydisp,x=this._createLinkUnderlineEvent(u.start.x-1,u.start.y-m-1,u.end.x,u.end.y-m-1,void 0);(l?this._onShowLinkUnderline:this._onHideLinkUnderline).fire(x)}_linkLeave(p,l,u){var m;(m=this._currentLink)!=null&&m.state&&(this._currentLink.state.isHovered=!1,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(l,!1),this._currentLink.state.decorations.pointerCursor&&p.classList.remove("xterm-cursor-pointer")),l.leave&&l.leave(u,l.text)}_linkAtPosition(p,l){const u=p.range.start.y*this._bufferService.cols+p.range.start.x,m=p.range.end.y*this._bufferService.cols+p.range.end.x,x=l.y*this._bufferService.cols+l.x;return u<=x&&x<=m}_positionFromMouseEvent(p,l,u){const m=u.getCoords(p,l,this._bufferService.cols,this._bufferService.rows);if(m)return{x:m[0],y:m[1]+this._bufferService.buffer.ydisp}}_createLinkUnderlineEvent(p,l,u,m,x){return{x1:p,y1:l,x2:u,y2:m,cols:this._bufferService.cols,fg:x}}};n.Linkifier=c=d([f(1,y.IMouseService),f(2,y.IRenderService),f(3,w.IBufferService),f(4,y.ILinkProviderService)],c)},9042:(b,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.tooMuchOutput=n.promptLabel=void 0,n.promptLabel="Terminal input",n.tooMuchOutput="Too much output to announce, navigate to rows manually to read"},3730:function(b,n,o){var d=this&&this.__decorate||function(y,c,p,l){var u,m=arguments.length,x=m<3?c:l===null?l=Object.getOwnPropertyDescriptor(c,p):l;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")x=Reflect.decorate(y,c,p,l);else for(var v=y.length-1;v>=0;v--)(u=y[v])&&(x=(m<3?u(x):m>3?u(c,p,x):u(c,p))||x);return m>3&&x&&Object.defineProperty(c,p,x),x},f=this&&this.__param||function(y,c){return function(p,l){c(p,l,y)}};Object.defineProperty(n,"__esModule",{value:!0}),n.OscLinkProvider=void 0;const h=o(511),_=o(2585);let S=n.OscLinkProvider=class{constructor(y,c,p){this._bufferService=y,this._optionsService=c,this._oscLinkService=p}provideLinks(y,c){var C;const p=this._bufferService.buffer.lines.get(y-1);if(!p)return void c(void 0);const l=[],u=this._optionsService.rawOptions.linkHandler,m=new h.CellData,x=p.getTrimmedLength();let v=-1,k=-1,E=!1;for(let N=0;N<x;N++)if(k!==-1||p.hasContent(N)){if(p.loadCell(N,m),m.hasExtendedAttrs()&&m.extended.urlId){if(k===-1){k=N,v=m.extended.urlId;continue}E=m.extended.urlId!==v}else k!==-1&&(E=!0);if(E||k!==-1&&N===x-1){const R=(C=this._oscLinkService.getLinkData(v))==null?void 0:C.uri;if(R){const B={start:{x:k+1,y},end:{x:N+(E||N!==x-1?0:1),y}};let A=!1;if(!(u!=null&&u.allowNonHttpProtocols))try{const F=new URL(R);["http:","https:"].includes(F.protocol)||(A=!0)}catch{A=!0}A||l.push({text:R,range:B,activate:(F,M)=>u?u.activate(F,M,B):w(0,M),hover:(F,M)=>{var H;return(H=u==null?void 0:u.hover)==null?void 0:H.call(u,F,M,B)},leave:(F,M)=>{var H;return(H=u==null?void 0:u.leave)==null?void 0:H.call(u,F,M,B)}})}E=!1,m.hasExtendedAttrs()&&m.extended.urlId?(k=N,v=m.extended.urlId):(k=-1,v=-1)}}c(l)}};function w(y,c){if(confirm(`Do you want to navigate to ${c}?
|
|
400
400
|
|
|
@@ -402,10 +402,10 @@ WARNING: This link could potentially be dangerous`)){const p=window.open();if(p)
|
|
|
402
402
|
`:`
|
|
403
403
|
`)}clearSelection(){this._model.clearSelection(),this._removeMouseDownListeners(),this.refresh(),this._onSelectionChange.fire()}refresh(E){this._refreshAnimationFrame||(this._refreshAnimationFrame=this._coreBrowserService.window.requestAnimationFrame((()=>this._refresh()))),p.isLinux&&E&&this.selectionText.length&&this._onLinuxMouseSelection.fire(this.selectionText)}_refresh(){this._refreshAnimationFrame=void 0,this._onRedrawRequest.fire({start:this._model.finalSelectionStart,end:this._model.finalSelectionEnd,columnSelectMode:this._activeSelectionMode===3})}_isClickInSelection(E){const C=this._getMouseBufferCoords(E),N=this._model.finalSelectionStart,R=this._model.finalSelectionEnd;return!!(N&&R&&C)&&this._areCoordsInSelection(C,N,R)}isCellInSelection(E,C){const N=this._model.finalSelectionStart,R=this._model.finalSelectionEnd;return!(!N||!R)&&this._areCoordsInSelection([E,C],N,R)}_areCoordsInSelection(E,C,N){return E[1]>C[1]&&E[1]<N[1]||C[1]===N[1]&&E[1]===C[1]&&E[0]>=C[0]&&E[0]<N[0]||C[1]<N[1]&&E[1]===N[1]&&E[0]<N[0]||C[1]<N[1]&&E[1]===C[1]&&E[0]>=C[0]}_selectWordAtCursor(E,C){var B,A;const N=(A=(B=this._linkifier.currentLink)==null?void 0:B.link)==null?void 0:A.range;if(N)return this._model.selectionStart=[N.start.x-1,N.start.y-1],this._model.selectionStartLength=(0,l.getRangeLength)(N,this._bufferService.cols),this._model.selectionEnd=void 0,!0;const R=this._getMouseBufferCoords(E);return!!R&&(this._selectWordAt(R,C),this._model.selectionEnd=void 0,!0)}selectAll(){this._model.isSelectAllActive=!0,this.refresh(),this._onSelectionChange.fire()}selectLines(E,C){this._model.clearSelection(),E=Math.max(E,0),C=Math.min(C,this._bufferService.buffer.lines.length-1),this._model.selectionStart=[0,E],this._model.selectionEnd=[this._bufferService.cols,C],this.refresh(),this._onSelectionChange.fire()}_handleTrim(E){this._model.handleTrim(E)&&this.refresh()}_getMouseBufferCoords(E){const C=this._mouseService.getCoords(E,this._screenElement,this._bufferService.cols,this._bufferService.rows,!0);if(C)return C[0]--,C[1]--,C[1]+=this._bufferService.buffer.ydisp,C}_getMouseEventScrollAmount(E){let C=(0,h.getCoordsRelativeToElement)(this._coreBrowserService.window,E,this._screenElement)[1];const N=this._renderService.dimensions.css.canvas.height;return C>=0&&C<=N?0:(C>N&&(C-=N),C=Math.min(Math.max(C,-50),50),C/=50,C/Math.abs(C)+Math.round(14*C))}shouldForceSelection(E){return p.isMac?E.altKey&&this._optionsService.rawOptions.macOptionClickForcesSelection:E.shiftKey}handleMouseDown(E){if(this._mouseDownTimeStamp=E.timeStamp,(E.button!==2||!this.hasSelection)&&E.button===0){if(!this._enabled){if(!this.shouldForceSelection(E))return;E.stopPropagation()}E.preventDefault(),this._dragScrollAmount=0,this._enabled&&E.shiftKey?this._handleIncrementalClick(E):E.detail===1?this._handleSingleClick(E):E.detail===2?this._handleDoubleClick(E):E.detail===3&&this._handleTripleClick(E),this._addMouseDownListeners(),this.refresh(!0)}}_addMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.addEventListener("mousemove",this._mouseMoveListener),this._screenElement.ownerDocument.addEventListener("mouseup",this._mouseUpListener)),this._dragScrollIntervalTimer=this._coreBrowserService.window.setInterval((()=>this._dragScroll()),50)}_removeMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.removeEventListener("mousemove",this._mouseMoveListener),this._screenElement.ownerDocument.removeEventListener("mouseup",this._mouseUpListener)),this._coreBrowserService.window.clearInterval(this._dragScrollIntervalTimer),this._dragScrollIntervalTimer=void 0}_handleIncrementalClick(E){this._model.selectionStart&&(this._model.selectionEnd=this._getMouseBufferCoords(E))}_handleSingleClick(E){if(this._model.selectionStartLength=0,this._model.isSelectAllActive=!1,this._activeSelectionMode=this.shouldColumnSelect(E)?3:0,this._model.selectionStart=this._getMouseBufferCoords(E),!this._model.selectionStart)return;this._model.selectionEnd=void 0;const C=this._bufferService.buffer.lines.get(this._model.selectionStart[1]);C&&C.length!==this._model.selectionStart[0]&&C.hasWidth(this._model.selectionStart[0])===0&&this._model.selectionStart[0]++}_handleDoubleClick(E){this._selectWordAtCursor(E,!0)&&(this._activeSelectionMode=1)}_handleTripleClick(E){const C=this._getMouseBufferCoords(E);C&&(this._activeSelectionMode=2,this._selectLineAt(C[1]))}shouldColumnSelect(E){return E.altKey&&!(p.isMac&&this._optionsService.rawOptions.macOptionClickForcesSelection)}_handleMouseMove(E){if(E.stopImmediatePropagation(),!this._model.selectionStart)return;const C=this._model.selectionEnd?[this._model.selectionEnd[0],this._model.selectionEnd[1]]:null;if(this._model.selectionEnd=this._getMouseBufferCoords(E),!this._model.selectionEnd)return void this.refresh(!0);this._activeSelectionMode===2?this._model.selectionEnd[1]<this._model.selectionStart[1]?this._model.selectionEnd[0]=0:this._model.selectionEnd[0]=this._bufferService.cols:this._activeSelectionMode===1&&this._selectToWordAt(this._model.selectionEnd),this._dragScrollAmount=this._getMouseEventScrollAmount(E),this._activeSelectionMode!==3&&(this._dragScrollAmount>0?this._model.selectionEnd[0]=this._bufferService.cols:this._dragScrollAmount<0&&(this._model.selectionEnd[0]=0));const N=this._bufferService.buffer;if(this._model.selectionEnd[1]<N.lines.length){const R=N.lines.get(this._model.selectionEnd[1]);R&&R.hasWidth(this._model.selectionEnd[0])===0&&this._model.selectionEnd[0]<this._bufferService.cols&&this._model.selectionEnd[0]++}C&&C[0]===this._model.selectionEnd[0]&&C[1]===this._model.selectionEnd[1]||this.refresh(!0)}_dragScroll(){if(this._model.selectionEnd&&this._model.selectionStart&&this._dragScrollAmount){this._onRequestScrollLines.fire({amount:this._dragScrollAmount,suppressScrollEvent:!1});const E=this._bufferService.buffer;this._dragScrollAmount>0?(this._activeSelectionMode!==3&&(this._model.selectionEnd[0]=this._bufferService.cols),this._model.selectionEnd[1]=Math.min(E.ydisp+this._bufferService.rows,E.lines.length-1)):(this._activeSelectionMode!==3&&(this._model.selectionEnd[0]=0),this._model.selectionEnd[1]=E.ydisp),this.refresh()}}_handleMouseUp(E){const C=E.timeStamp-this._mouseDownTimeStamp;if(this._removeMouseDownListeners(),this.selectionText.length<=1&&C<500&&E.altKey&&this._optionsService.rawOptions.altClickMovesCursor){if(this._bufferService.buffer.ybase===this._bufferService.buffer.ydisp){const N=this._mouseService.getCoords(E,this._element,this._bufferService.cols,this._bufferService.rows,!1);if(N&&N[0]!==void 0&&N[1]!==void 0){const R=(0,_.moveToCellSequence)(N[0]-1,N[1]-1,this._bufferService,this._coreService.decPrivateModes.applicationCursorKeys);this._coreService.triggerDataEvent(R,!0)}}}else this._fireEventIfSelectionChanged()}_fireEventIfSelectionChanged(){const E=this._model.finalSelectionStart,C=this._model.finalSelectionEnd,N=!(!E||!C||E[0]===C[0]&&E[1]===C[1]);N?E&&C&&(this._oldSelectionStart&&this._oldSelectionEnd&&E[0]===this._oldSelectionStart[0]&&E[1]===this._oldSelectionStart[1]&&C[0]===this._oldSelectionEnd[0]&&C[1]===this._oldSelectionEnd[1]||this._fireOnSelectionChange(E,C,N)):this._oldHasSelection&&this._fireOnSelectionChange(E,C,N)}_fireOnSelectionChange(E,C,N){this._oldSelectionStart=E,this._oldSelectionEnd=C,this._oldHasSelection=N,this._onSelectionChange.fire()}_handleBufferActivate(E){this.clearSelection(),this._trimListener.dispose(),this._trimListener=E.activeBuffer.lines.onTrim((C=>this._handleTrim(C)))}_convertViewportColToCharacterIndex(E,C){let N=C;for(let R=0;C>=R;R++){const B=E.loadCell(R,this._workCell).getChars().length;this._workCell.getWidth()===0?N--:B>1&&C!==R&&(N+=B-1)}return N}setSelection(E,C,N){this._model.clearSelection(),this._removeMouseDownListeners(),this._model.selectionStart=[E,C],this._model.selectionStartLength=N,this.refresh(),this._fireEventIfSelectionChanged()}rightClickSelect(E){this._isClickInSelection(E)||(this._selectWordAtCursor(E,!1)&&this.refresh(!0),this._fireEventIfSelectionChanged())}_getWordAt(E,C,N=!0,R=!0){if(E[0]>=this._bufferService.cols)return;const B=this._bufferService.buffer,A=B.lines.get(E[1]);if(!A)return;const F=B.translateBufferLineToString(E[1],!1);let M=this._convertViewportColToCharacterIndex(A,E[0]),H=M;const z=E[0]-M;let G=0,T=0,D=0,P=0;if(F.charAt(M)===" "){for(;M>0&&F.charAt(M-1)===" ";)M--;for(;H<F.length&&F.charAt(H+1)===" ";)H++}else{let K=E[0],re=E[0];A.getWidth(K)===0&&(G++,K--),A.getWidth(re)===2&&(T++,re++);const J=A.getString(re).length;for(J>1&&(P+=J-1,H+=J-1);K>0&&M>0&&!this._isCharWordSeparator(A.loadCell(K-1,this._workCell));){A.loadCell(K-1,this._workCell);const U=this._workCell.getChars().length;this._workCell.getWidth()===0?(G++,K--):U>1&&(D+=U-1,M-=U-1),M--,K--}for(;re<A.length&&H+1<F.length&&!this._isCharWordSeparator(A.loadCell(re+1,this._workCell));){A.loadCell(re+1,this._workCell);const U=this._workCell.getChars().length;this._workCell.getWidth()===2?(T++,re++):U>1&&(P+=U-1,H+=U-1),H++,re++}}H++;let j=M+z-G+D,q=Math.min(this._bufferService.cols,H-M+G+T-D-P);if(C||F.slice(M,H).trim()!==""){if(N&&j===0&&A.getCodePoint(0)!==32){const K=B.lines.get(E[1]-1);if(K&&A.isWrapped&&K.getCodePoint(this._bufferService.cols-1)!==32){const re=this._getWordAt([this._bufferService.cols-1,E[1]-1],!1,!0,!1);if(re){const J=this._bufferService.cols-re.start;j-=J,q+=J}}}if(R&&j+q===this._bufferService.cols&&A.getCodePoint(this._bufferService.cols-1)!==32){const K=B.lines.get(E[1]+1);if(K!=null&&K.isWrapped&&K.getCodePoint(0)!==32){const re=this._getWordAt([0,E[1]+1],!1,!1,!0);re&&(q+=re.length)}}return{start:j,length:q}}}_selectWordAt(E,C){const N=this._getWordAt(E,C);if(N){for(;N.start<0;)N.start+=this._bufferService.cols,E[1]--;this._model.selectionStart=[N.start,E[1]],this._model.selectionStartLength=N.length}}_selectToWordAt(E){const C=this._getWordAt(E,!0);if(C){let N=E[1];for(;C.start<0;)C.start+=this._bufferService.cols,N--;if(!this._model.areSelectionValuesReversed())for(;C.start+C.length>this._bufferService.cols;)C.length-=this._bufferService.cols,N++;this._model.selectionEnd=[this._model.areSelectionValuesReversed()?C.start:C.start+C.length,N]}}_isCharWordSeparator(E){return E.getWidth()!==0&&this._optionsService.rawOptions.wordSeparator.indexOf(E.getChars())>=0}_selectLineAt(E){const C=this._bufferService.buffer.getWrappedRangeForLine(E),N={start:{x:0,y:C.first},end:{x:this._bufferService.cols-1,y:C.last}};this._model.selectionStart=[0,C.first],this._model.selectionEnd=void 0,this._model.selectionStartLength=(0,l.getRangeLength)(N,this._bufferService.cols)}};n.SelectionService=k=d([f(3,m.IBufferService),f(4,m.ICoreService),f(5,w.IMouseService),f(6,m.IOptionsService),f(7,w.IRenderService),f(8,w.ICoreBrowserService)],k)},4725:(b,n,o)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.ILinkProviderService=n.IThemeService=n.ICharacterJoinerService=n.ISelectionService=n.IRenderService=n.IMouseService=n.ICoreBrowserService=n.ICharSizeService=void 0;const d=o(8343);n.ICharSizeService=(0,d.createDecorator)("CharSizeService"),n.ICoreBrowserService=(0,d.createDecorator)("CoreBrowserService"),n.IMouseService=(0,d.createDecorator)("MouseService"),n.IRenderService=(0,d.createDecorator)("RenderService"),n.ISelectionService=(0,d.createDecorator)("SelectionService"),n.ICharacterJoinerService=(0,d.createDecorator)("CharacterJoinerService"),n.IThemeService=(0,d.createDecorator)("ThemeService"),n.ILinkProviderService=(0,d.createDecorator)("LinkProviderService")},6731:function(b,n,o){var d=this&&this.__decorate||function(k,E,C,N){var R,B=arguments.length,A=B<3?E:N===null?N=Object.getOwnPropertyDescriptor(E,C):N;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")A=Reflect.decorate(k,E,C,N);else for(var F=k.length-1;F>=0;F--)(R=k[F])&&(A=(B<3?R(A):B>3?R(E,C,A):R(E,C))||A);return B>3&&A&&Object.defineProperty(E,C,A),A},f=this&&this.__param||function(k,E){return function(C,N){E(C,N,k)}};Object.defineProperty(n,"__esModule",{value:!0}),n.ThemeService=n.DEFAULT_ANSI_COLORS=void 0;const h=o(7239),_=o(8055),S=o(8460),w=o(844),y=o(2585),c=_.css.toColor("#ffffff"),p=_.css.toColor("#000000"),l=_.css.toColor("#ffffff"),u=_.css.toColor("#000000"),m={css:"rgba(255, 255, 255, 0.3)",rgba:4294967117};n.DEFAULT_ANSI_COLORS=Object.freeze((()=>{const k=[_.css.toColor("#2e3436"),_.css.toColor("#cc0000"),_.css.toColor("#4e9a06"),_.css.toColor("#c4a000"),_.css.toColor("#3465a4"),_.css.toColor("#75507b"),_.css.toColor("#06989a"),_.css.toColor("#d3d7cf"),_.css.toColor("#555753"),_.css.toColor("#ef2929"),_.css.toColor("#8ae234"),_.css.toColor("#fce94f"),_.css.toColor("#729fcf"),_.css.toColor("#ad7fa8"),_.css.toColor("#34e2e2"),_.css.toColor("#eeeeec")],E=[0,95,135,175,215,255];for(let C=0;C<216;C++){const N=E[C/36%6|0],R=E[C/6%6|0],B=E[C%6];k.push({css:_.channels.toCss(N,R,B),rgba:_.channels.toRgba(N,R,B)})}for(let C=0;C<24;C++){const N=8+10*C;k.push({css:_.channels.toCss(N,N,N),rgba:_.channels.toRgba(N,N,N)})}return k})());let x=n.ThemeService=class extends w.Disposable{get colors(){return this._colors}constructor(k){super(),this._optionsService=k,this._contrastCache=new h.ColorContrastCache,this._halfContrastCache=new h.ColorContrastCache,this._onChangeColors=this.register(new S.EventEmitter),this.onChangeColors=this._onChangeColors.event,this._colors={foreground:c,background:p,cursor:l,cursorAccent:u,selectionForeground:void 0,selectionBackgroundTransparent:m,selectionBackgroundOpaque:_.color.blend(p,m),selectionInactiveBackgroundTransparent:m,selectionInactiveBackgroundOpaque:_.color.blend(p,m),ansi:n.DEFAULT_ANSI_COLORS.slice(),contrastCache:this._contrastCache,halfContrastCache:this._halfContrastCache},this._updateRestoreColors(),this._setTheme(this._optionsService.rawOptions.theme),this.register(this._optionsService.onSpecificOptionChange("minimumContrastRatio",(()=>this._contrastCache.clear()))),this.register(this._optionsService.onSpecificOptionChange("theme",(()=>this._setTheme(this._optionsService.rawOptions.theme))))}_setTheme(k={}){const E=this._colors;if(E.foreground=v(k.foreground,c),E.background=v(k.background,p),E.cursor=v(k.cursor,l),E.cursorAccent=v(k.cursorAccent,u),E.selectionBackgroundTransparent=v(k.selectionBackground,m),E.selectionBackgroundOpaque=_.color.blend(E.background,E.selectionBackgroundTransparent),E.selectionInactiveBackgroundTransparent=v(k.selectionInactiveBackground,E.selectionBackgroundTransparent),E.selectionInactiveBackgroundOpaque=_.color.blend(E.background,E.selectionInactiveBackgroundTransparent),E.selectionForeground=k.selectionForeground?v(k.selectionForeground,_.NULL_COLOR):void 0,E.selectionForeground===_.NULL_COLOR&&(E.selectionForeground=void 0),_.color.isOpaque(E.selectionBackgroundTransparent)&&(E.selectionBackgroundTransparent=_.color.opacity(E.selectionBackgroundTransparent,.3)),_.color.isOpaque(E.selectionInactiveBackgroundTransparent)&&(E.selectionInactiveBackgroundTransparent=_.color.opacity(E.selectionInactiveBackgroundTransparent,.3)),E.ansi=n.DEFAULT_ANSI_COLORS.slice(),E.ansi[0]=v(k.black,n.DEFAULT_ANSI_COLORS[0]),E.ansi[1]=v(k.red,n.DEFAULT_ANSI_COLORS[1]),E.ansi[2]=v(k.green,n.DEFAULT_ANSI_COLORS[2]),E.ansi[3]=v(k.yellow,n.DEFAULT_ANSI_COLORS[3]),E.ansi[4]=v(k.blue,n.DEFAULT_ANSI_COLORS[4]),E.ansi[5]=v(k.magenta,n.DEFAULT_ANSI_COLORS[5]),E.ansi[6]=v(k.cyan,n.DEFAULT_ANSI_COLORS[6]),E.ansi[7]=v(k.white,n.DEFAULT_ANSI_COLORS[7]),E.ansi[8]=v(k.brightBlack,n.DEFAULT_ANSI_COLORS[8]),E.ansi[9]=v(k.brightRed,n.DEFAULT_ANSI_COLORS[9]),E.ansi[10]=v(k.brightGreen,n.DEFAULT_ANSI_COLORS[10]),E.ansi[11]=v(k.brightYellow,n.DEFAULT_ANSI_COLORS[11]),E.ansi[12]=v(k.brightBlue,n.DEFAULT_ANSI_COLORS[12]),E.ansi[13]=v(k.brightMagenta,n.DEFAULT_ANSI_COLORS[13]),E.ansi[14]=v(k.brightCyan,n.DEFAULT_ANSI_COLORS[14]),E.ansi[15]=v(k.brightWhite,n.DEFAULT_ANSI_COLORS[15]),k.extendedAnsi){const C=Math.min(E.ansi.length-16,k.extendedAnsi.length);for(let N=0;N<C;N++)E.ansi[N+16]=v(k.extendedAnsi[N],n.DEFAULT_ANSI_COLORS[N+16])}this._contrastCache.clear(),this._halfContrastCache.clear(),this._updateRestoreColors(),this._onChangeColors.fire(this.colors)}restoreColor(k){this._restoreColor(k),this._onChangeColors.fire(this.colors)}_restoreColor(k){if(k!==void 0)switch(k){case 256:this._colors.foreground=this._restoreColors.foreground;break;case 257:this._colors.background=this._restoreColors.background;break;case 258:this._colors.cursor=this._restoreColors.cursor;break;default:this._colors.ansi[k]=this._restoreColors.ansi[k]}else for(let E=0;E<this._restoreColors.ansi.length;++E)this._colors.ansi[E]=this._restoreColors.ansi[E]}modifyColors(k){k(this._colors),this._onChangeColors.fire(this.colors)}_updateRestoreColors(){this._restoreColors={foreground:this._colors.foreground,background:this._colors.background,cursor:this._colors.cursor,ansi:this._colors.ansi.slice()}}};function v(k,E){if(k!==void 0)try{return _.css.toColor(k)}catch{}return E}n.ThemeService=x=d([f(0,y.IOptionsService)],x)},6349:(b,n,o)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.CircularList=void 0;const d=o(8460),f=o(844);class h extends f.Disposable{constructor(S){super(),this._maxLength=S,this.onDeleteEmitter=this.register(new d.EventEmitter),this.onDelete=this.onDeleteEmitter.event,this.onInsertEmitter=this.register(new d.EventEmitter),this.onInsert=this.onInsertEmitter.event,this.onTrimEmitter=this.register(new d.EventEmitter),this.onTrim=this.onTrimEmitter.event,this._array=new Array(this._maxLength),this._startIndex=0,this._length=0}get maxLength(){return this._maxLength}set maxLength(S){if(this._maxLength===S)return;const w=new Array(S);for(let y=0;y<Math.min(S,this.length);y++)w[y]=this._array[this._getCyclicIndex(y)];this._array=w,this._maxLength=S,this._startIndex=0}get length(){return this._length}set length(S){if(S>this._length)for(let w=this._length;w<S;w++)this._array[w]=void 0;this._length=S}get(S){return this._array[this._getCyclicIndex(S)]}set(S,w){this._array[this._getCyclicIndex(S)]=w}push(S){this._array[this._getCyclicIndex(this._length)]=S,this._length===this._maxLength?(this._startIndex=++this._startIndex%this._maxLength,this.onTrimEmitter.fire(1)):this._length++}recycle(){if(this._length!==this._maxLength)throw new Error("Can only recycle when the buffer is full");return this._startIndex=++this._startIndex%this._maxLength,this.onTrimEmitter.fire(1),this._array[this._getCyclicIndex(this._length-1)]}get isFull(){return this._length===this._maxLength}pop(){return this._array[this._getCyclicIndex(this._length---1)]}splice(S,w,...y){if(w){for(let c=S;c<this._length-w;c++)this._array[this._getCyclicIndex(c)]=this._array[this._getCyclicIndex(c+w)];this._length-=w,this.onDeleteEmitter.fire({index:S,amount:w})}for(let c=this._length-1;c>=S;c--)this._array[this._getCyclicIndex(c+y.length)]=this._array[this._getCyclicIndex(c)];for(let c=0;c<y.length;c++)this._array[this._getCyclicIndex(S+c)]=y[c];if(y.length&&this.onInsertEmitter.fire({index:S,amount:y.length}),this._length+y.length>this._maxLength){const c=this._length+y.length-this._maxLength;this._startIndex+=c,this._length=this._maxLength,this.onTrimEmitter.fire(c)}else this._length+=y.length}trimStart(S){S>this._length&&(S=this._length),this._startIndex+=S,this._length-=S,this.onTrimEmitter.fire(S)}shiftElements(S,w,y){if(!(w<=0)){if(S<0||S>=this._length)throw new Error("start argument out of range");if(S+y<0)throw new Error("Cannot shift elements in list beyond index 0");if(y>0){for(let p=w-1;p>=0;p--)this.set(S+p+y,this.get(S+p));const c=S+w+y-this._length;if(c>0)for(this._length+=c;this._length>this._maxLength;)this._length--,this._startIndex++,this.onTrimEmitter.fire(1)}else for(let c=0;c<w;c++)this.set(S+c+y,this.get(S+c))}}_getCyclicIndex(S){return(this._startIndex+S)%this._maxLength}}n.CircularList=h},1439:(b,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.clone=void 0,n.clone=function o(d,f=5){if(typeof d!="object")return d;const h=Array.isArray(d)?[]:{};for(const _ in d)h[_]=f<=1?d[_]:d[_]&&o(d[_],f-1);return h}},8055:(b,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.contrastRatio=n.toPaddedHex=n.rgba=n.rgb=n.css=n.color=n.channels=n.NULL_COLOR=void 0;let o=0,d=0,f=0,h=0;var _,S,w,y,c;function p(u){const m=u.toString(16);return m.length<2?"0"+m:m}function l(u,m){return u<m?(m+.05)/(u+.05):(u+.05)/(m+.05)}n.NULL_COLOR={css:"#00000000",rgba:0},(function(u){u.toCss=function(m,x,v,k){return k!==void 0?`#${p(m)}${p(x)}${p(v)}${p(k)}`:`#${p(m)}${p(x)}${p(v)}`},u.toRgba=function(m,x,v,k=255){return(m<<24|x<<16|v<<8|k)>>>0},u.toColor=function(m,x,v,k){return{css:u.toCss(m,x,v,k),rgba:u.toRgba(m,x,v,k)}}})(_||(n.channels=_={})),(function(u){function m(x,v){return h=Math.round(255*v),[o,d,f]=c.toChannels(x.rgba),{css:_.toCss(o,d,f,h),rgba:_.toRgba(o,d,f,h)}}u.blend=function(x,v){if(h=(255&v.rgba)/255,h===1)return{css:v.css,rgba:v.rgba};const k=v.rgba>>24&255,E=v.rgba>>16&255,C=v.rgba>>8&255,N=x.rgba>>24&255,R=x.rgba>>16&255,B=x.rgba>>8&255;return o=N+Math.round((k-N)*h),d=R+Math.round((E-R)*h),f=B+Math.round((C-B)*h),{css:_.toCss(o,d,f),rgba:_.toRgba(o,d,f)}},u.isOpaque=function(x){return(255&x.rgba)==255},u.ensureContrastRatio=function(x,v,k){const E=c.ensureContrastRatio(x.rgba,v.rgba,k);if(E)return _.toColor(E>>24&255,E>>16&255,E>>8&255)},u.opaque=function(x){const v=(255|x.rgba)>>>0;return[o,d,f]=c.toChannels(v),{css:_.toCss(o,d,f),rgba:v}},u.opacity=m,u.multiplyOpacity=function(x,v){return h=255&x.rgba,m(x,h*v/255)},u.toColorRGB=function(x){return[x.rgba>>24&255,x.rgba>>16&255,x.rgba>>8&255]}})(S||(n.color=S={})),(function(u){let m,x;try{const v=document.createElement("canvas");v.width=1,v.height=1;const k=v.getContext("2d",{willReadFrequently:!0});k&&(m=k,m.globalCompositeOperation="copy",x=m.createLinearGradient(0,0,1,1))}catch{}u.toColor=function(v){if(v.match(/#[\da-f]{3,8}/i))switch(v.length){case 4:return o=parseInt(v.slice(1,2).repeat(2),16),d=parseInt(v.slice(2,3).repeat(2),16),f=parseInt(v.slice(3,4).repeat(2),16),_.toColor(o,d,f);case 5:return o=parseInt(v.slice(1,2).repeat(2),16),d=parseInt(v.slice(2,3).repeat(2),16),f=parseInt(v.slice(3,4).repeat(2),16),h=parseInt(v.slice(4,5).repeat(2),16),_.toColor(o,d,f,h);case 7:return{css:v,rgba:(parseInt(v.slice(1),16)<<8|255)>>>0};case 9:return{css:v,rgba:parseInt(v.slice(1),16)>>>0}}const k=v.match(/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(,\s*(0|1|\d?\.(\d+))\s*)?\)/);if(k)return o=parseInt(k[1]),d=parseInt(k[2]),f=parseInt(k[3]),h=Math.round(255*(k[5]===void 0?1:parseFloat(k[5]))),_.toColor(o,d,f,h);if(!m||!x)throw new Error("css.toColor: Unsupported css format");if(m.fillStyle=x,m.fillStyle=v,typeof m.fillStyle!="string")throw new Error("css.toColor: Unsupported css format");if(m.fillRect(0,0,1,1),[o,d,f,h]=m.getImageData(0,0,1,1).data,h!==255)throw new Error("css.toColor: Unsupported css format");return{rgba:_.toRgba(o,d,f,h),css:v}}})(w||(n.css=w={})),(function(u){function m(x,v,k){const E=x/255,C=v/255,N=k/255;return .2126*(E<=.03928?E/12.92:Math.pow((E+.055)/1.055,2.4))+.7152*(C<=.03928?C/12.92:Math.pow((C+.055)/1.055,2.4))+.0722*(N<=.03928?N/12.92:Math.pow((N+.055)/1.055,2.4))}u.relativeLuminance=function(x){return m(x>>16&255,x>>8&255,255&x)},u.relativeLuminance2=m})(y||(n.rgb=y={})),(function(u){function m(v,k,E){const C=v>>24&255,N=v>>16&255,R=v>>8&255;let B=k>>24&255,A=k>>16&255,F=k>>8&255,M=l(y.relativeLuminance2(B,A,F),y.relativeLuminance2(C,N,R));for(;M<E&&(B>0||A>0||F>0);)B-=Math.max(0,Math.ceil(.1*B)),A-=Math.max(0,Math.ceil(.1*A)),F-=Math.max(0,Math.ceil(.1*F)),M=l(y.relativeLuminance2(B,A,F),y.relativeLuminance2(C,N,R));return(B<<24|A<<16|F<<8|255)>>>0}function x(v,k,E){const C=v>>24&255,N=v>>16&255,R=v>>8&255;let B=k>>24&255,A=k>>16&255,F=k>>8&255,M=l(y.relativeLuminance2(B,A,F),y.relativeLuminance2(C,N,R));for(;M<E&&(B<255||A<255||F<255);)B=Math.min(255,B+Math.ceil(.1*(255-B))),A=Math.min(255,A+Math.ceil(.1*(255-A))),F=Math.min(255,F+Math.ceil(.1*(255-F))),M=l(y.relativeLuminance2(B,A,F),y.relativeLuminance2(C,N,R));return(B<<24|A<<16|F<<8|255)>>>0}u.blend=function(v,k){if(h=(255&k)/255,h===1)return k;const E=k>>24&255,C=k>>16&255,N=k>>8&255,R=v>>24&255,B=v>>16&255,A=v>>8&255;return o=R+Math.round((E-R)*h),d=B+Math.round((C-B)*h),f=A+Math.round((N-A)*h),_.toRgba(o,d,f)},u.ensureContrastRatio=function(v,k,E){const C=y.relativeLuminance(v>>8),N=y.relativeLuminance(k>>8);if(l(C,N)<E){if(N<C){const A=m(v,k,E),F=l(C,y.relativeLuminance(A>>8));if(F<E){const M=x(v,k,E);return F>l(C,y.relativeLuminance(M>>8))?A:M}return A}const R=x(v,k,E),B=l(C,y.relativeLuminance(R>>8));if(B<E){const A=m(v,k,E);return B>l(C,y.relativeLuminance(A>>8))?R:A}return R}},u.reduceLuminance=m,u.increaseLuminance=x,u.toChannels=function(v){return[v>>24&255,v>>16&255,v>>8&255,255&v]}})(c||(n.rgba=c={})),n.toPaddedHex=p,n.contrastRatio=l},8969:(b,n,o)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.CoreTerminal=void 0;const d=o(844),f=o(2585),h=o(4348),_=o(7866),S=o(744),w=o(7302),y=o(6975),c=o(8460),p=o(1753),l=o(1480),u=o(7994),m=o(9282),x=o(5435),v=o(5981),k=o(2660);let E=!1;class C extends d.Disposable{get onScroll(){return this._onScrollApi||(this._onScrollApi=this.register(new c.EventEmitter),this._onScroll.event((R=>{var B;(B=this._onScrollApi)==null||B.fire(R.position)}))),this._onScrollApi.event}get cols(){return this._bufferService.cols}get rows(){return this._bufferService.rows}get buffers(){return this._bufferService.buffers}get options(){return this.optionsService.options}set options(R){for(const B in R)this.optionsService.options[B]=R[B]}constructor(R){super(),this._windowsWrappingHeuristics=this.register(new d.MutableDisposable),this._onBinary=this.register(new c.EventEmitter),this.onBinary=this._onBinary.event,this._onData=this.register(new c.EventEmitter),this.onData=this._onData.event,this._onLineFeed=this.register(new c.EventEmitter),this.onLineFeed=this._onLineFeed.event,this._onResize=this.register(new c.EventEmitter),this.onResize=this._onResize.event,this._onWriteParsed=this.register(new c.EventEmitter),this.onWriteParsed=this._onWriteParsed.event,this._onScroll=this.register(new c.EventEmitter),this._instantiationService=new h.InstantiationService,this.optionsService=this.register(new w.OptionsService(R)),this._instantiationService.setService(f.IOptionsService,this.optionsService),this._bufferService=this.register(this._instantiationService.createInstance(S.BufferService)),this._instantiationService.setService(f.IBufferService,this._bufferService),this._logService=this.register(this._instantiationService.createInstance(_.LogService)),this._instantiationService.setService(f.ILogService,this._logService),this.coreService=this.register(this._instantiationService.createInstance(y.CoreService)),this._instantiationService.setService(f.ICoreService,this.coreService),this.coreMouseService=this.register(this._instantiationService.createInstance(p.CoreMouseService)),this._instantiationService.setService(f.ICoreMouseService,this.coreMouseService),this.unicodeService=this.register(this._instantiationService.createInstance(l.UnicodeService)),this._instantiationService.setService(f.IUnicodeService,this.unicodeService),this._charsetService=this._instantiationService.createInstance(u.CharsetService),this._instantiationService.setService(f.ICharsetService,this._charsetService),this._oscLinkService=this._instantiationService.createInstance(k.OscLinkService),this._instantiationService.setService(f.IOscLinkService,this._oscLinkService),this._inputHandler=this.register(new x.InputHandler(this._bufferService,this._charsetService,this.coreService,this._logService,this.optionsService,this._oscLinkService,this.coreMouseService,this.unicodeService)),this.register((0,c.forwardEvent)(this._inputHandler.onLineFeed,this._onLineFeed)),this.register(this._inputHandler),this.register((0,c.forwardEvent)(this._bufferService.onResize,this._onResize)),this.register((0,c.forwardEvent)(this.coreService.onData,this._onData)),this.register((0,c.forwardEvent)(this.coreService.onBinary,this._onBinary)),this.register(this.coreService.onRequestScrollToBottom((()=>this.scrollToBottom()))),this.register(this.coreService.onUserInput((()=>this._writeBuffer.handleUserInput()))),this.register(this.optionsService.onMultipleOptionChange(["windowsMode","windowsPty"],(()=>this._handleWindowsPtyOptionChange()))),this.register(this._bufferService.onScroll((B=>{this._onScroll.fire({position:this._bufferService.buffer.ydisp,source:0}),this._inputHandler.markRangeDirty(this._bufferService.buffer.scrollTop,this._bufferService.buffer.scrollBottom)}))),this.register(this._inputHandler.onScroll((B=>{this._onScroll.fire({position:this._bufferService.buffer.ydisp,source:0}),this._inputHandler.markRangeDirty(this._bufferService.buffer.scrollTop,this._bufferService.buffer.scrollBottom)}))),this._writeBuffer=this.register(new v.WriteBuffer(((B,A)=>this._inputHandler.parse(B,A)))),this.register((0,c.forwardEvent)(this._writeBuffer.onWriteParsed,this._onWriteParsed))}write(R,B){this._writeBuffer.write(R,B)}writeSync(R,B){this._logService.logLevel<=f.LogLevelEnum.WARN&&!E&&(this._logService.warn("writeSync is unreliable and will be removed soon."),E=!0),this._writeBuffer.writeSync(R,B)}input(R,B=!0){this.coreService.triggerDataEvent(R,B)}resize(R,B){isNaN(R)||isNaN(B)||(R=Math.max(R,S.MINIMUM_COLS),B=Math.max(B,S.MINIMUM_ROWS),this._bufferService.resize(R,B))}scroll(R,B=!1){this._bufferService.scroll(R,B)}scrollLines(R,B,A){this._bufferService.scrollLines(R,B,A)}scrollPages(R){this.scrollLines(R*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(){this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(R){const B=R-this._bufferService.buffer.ydisp;B!==0&&this.scrollLines(B)}registerEscHandler(R,B){return this._inputHandler.registerEscHandler(R,B)}registerDcsHandler(R,B){return this._inputHandler.registerDcsHandler(R,B)}registerCsiHandler(R,B){return this._inputHandler.registerCsiHandler(R,B)}registerOscHandler(R,B){return this._inputHandler.registerOscHandler(R,B)}_setup(){this._handleWindowsPtyOptionChange()}reset(){this._inputHandler.reset(),this._bufferService.reset(),this._charsetService.reset(),this.coreService.reset(),this.coreMouseService.reset()}_handleWindowsPtyOptionChange(){let R=!1;const B=this.optionsService.rawOptions.windowsPty;B&&B.buildNumber!==void 0&&B.buildNumber!==void 0?R=B.backend==="conpty"&&B.buildNumber<21376:this.optionsService.rawOptions.windowsMode&&(R=!0),R?this._enableWindowsWrappingHeuristics():this._windowsWrappingHeuristics.clear()}_enableWindowsWrappingHeuristics(){if(!this._windowsWrappingHeuristics.value){const R=[];R.push(this.onLineFeed(m.updateWindowsModeWrappedState.bind(null,this._bufferService))),R.push(this.registerCsiHandler({final:"H"},(()=>((0,m.updateWindowsModeWrappedState)(this._bufferService),!1)))),this._windowsWrappingHeuristics.value=(0,d.toDisposable)((()=>{for(const B of R)B.dispose()}))}}}n.CoreTerminal=C},8460:(b,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.runAndSubscribe=n.forwardEvent=n.EventEmitter=void 0,n.EventEmitter=class{constructor(){this._listeners=[],this._disposed=!1}get event(){return this._event||(this._event=o=>(this._listeners.push(o),{dispose:()=>{if(!this._disposed){for(let d=0;d<this._listeners.length;d++)if(this._listeners[d]===o)return void this._listeners.splice(d,1)}}})),this._event}fire(o,d){const f=[];for(let h=0;h<this._listeners.length;h++)f.push(this._listeners[h]);for(let h=0;h<f.length;h++)f[h].call(void 0,o,d)}dispose(){this.clearListeners(),this._disposed=!0}clearListeners(){this._listeners&&(this._listeners.length=0)}},n.forwardEvent=function(o,d){return o((f=>d.fire(f)))},n.runAndSubscribe=function(o,d){return d(void 0),o((f=>d(f)))}},5435:function(b,n,o){var d=this&&this.__decorate||function(G,T,D,P){var j,q=arguments.length,K=q<3?T:P===null?P=Object.getOwnPropertyDescriptor(T,D):P;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")K=Reflect.decorate(G,T,D,P);else for(var re=G.length-1;re>=0;re--)(j=G[re])&&(K=(q<3?j(K):q>3?j(T,D,K):j(T,D))||K);return q>3&&K&&Object.defineProperty(T,D,K),K},f=this&&this.__param||function(G,T){return function(D,P){T(D,P,G)}};Object.defineProperty(n,"__esModule",{value:!0}),n.InputHandler=n.WindowsOptionsReportType=void 0;const h=o(2584),_=o(7116),S=o(2015),w=o(844),y=o(482),c=o(8437),p=o(8460),l=o(643),u=o(511),m=o(3734),x=o(2585),v=o(1480),k=o(6242),E=o(6351),C=o(5941),N={"(":0,")":1,"*":2,"+":3,"-":1,".":2},R=131072;function B(G,T){if(G>24)return T.setWinLines||!1;switch(G){case 1:return!!T.restoreWin;case 2:return!!T.minimizeWin;case 3:return!!T.setWinPosition;case 4:return!!T.setWinSizePixels;case 5:return!!T.raiseWin;case 6:return!!T.lowerWin;case 7:return!!T.refreshWin;case 8:return!!T.setWinSizeChars;case 9:return!!T.maximizeWin;case 10:return!!T.fullscreenWin;case 11:return!!T.getWinState;case 13:return!!T.getWinPosition;case 14:return!!T.getWinSizePixels;case 15:return!!T.getScreenSizePixels;case 16:return!!T.getCellSizePixels;case 18:return!!T.getWinSizeChars;case 19:return!!T.getScreenSizeChars;case 20:return!!T.getIconTitle;case 21:return!!T.getWinTitle;case 22:return!!T.pushTitle;case 23:return!!T.popTitle;case 24:return!!T.setWinLines}return!1}var A;(function(G){G[G.GET_WIN_SIZE_PIXELS=0]="GET_WIN_SIZE_PIXELS",G[G.GET_CELL_SIZE_PIXELS=1]="GET_CELL_SIZE_PIXELS"})(A||(n.WindowsOptionsReportType=A={}));let F=0;class M extends w.Disposable{getAttrData(){return this._curAttrData}constructor(T,D,P,j,q,K,re,J,U=new S.EscapeSequenceParser){super(),this._bufferService=T,this._charsetService=D,this._coreService=P,this._logService=j,this._optionsService=q,this._oscLinkService=K,this._coreMouseService=re,this._unicodeService=J,this._parser=U,this._parseBuffer=new Uint32Array(4096),this._stringDecoder=new y.StringToUtf32,this._utf8Decoder=new y.Utf8ToUtf32,this._workCell=new u.CellData,this._windowTitle="",this._iconName="",this._windowTitleStack=[],this._iconNameStack=[],this._curAttrData=c.DEFAULT_ATTR_DATA.clone(),this._eraseAttrDataInternal=c.DEFAULT_ATTR_DATA.clone(),this._onRequestBell=this.register(new p.EventEmitter),this.onRequestBell=this._onRequestBell.event,this._onRequestRefreshRows=this.register(new p.EventEmitter),this.onRequestRefreshRows=this._onRequestRefreshRows.event,this._onRequestReset=this.register(new p.EventEmitter),this.onRequestReset=this._onRequestReset.event,this._onRequestSendFocus=this.register(new p.EventEmitter),this.onRequestSendFocus=this._onRequestSendFocus.event,this._onRequestSyncScrollBar=this.register(new p.EventEmitter),this.onRequestSyncScrollBar=this._onRequestSyncScrollBar.event,this._onRequestWindowsOptionsReport=this.register(new p.EventEmitter),this.onRequestWindowsOptionsReport=this._onRequestWindowsOptionsReport.event,this._onA11yChar=this.register(new p.EventEmitter),this.onA11yChar=this._onA11yChar.event,this._onA11yTab=this.register(new p.EventEmitter),this.onA11yTab=this._onA11yTab.event,this._onCursorMove=this.register(new p.EventEmitter),this.onCursorMove=this._onCursorMove.event,this._onLineFeed=this.register(new p.EventEmitter),this.onLineFeed=this._onLineFeed.event,this._onScroll=this.register(new p.EventEmitter),this.onScroll=this._onScroll.event,this._onTitleChange=this.register(new p.EventEmitter),this.onTitleChange=this._onTitleChange.event,this._onColor=this.register(new p.EventEmitter),this.onColor=this._onColor.event,this._parseStack={paused:!1,cursorStartX:0,cursorStartY:0,decodedLength:0,position:0},this._specialColors=[256,257,258],this.register(this._parser),this._dirtyRowTracker=new H(this._bufferService),this._activeBuffer=this._bufferService.buffer,this.register(this._bufferService.buffers.onBufferActivate((I=>this._activeBuffer=I.activeBuffer))),this._parser.setCsiHandlerFallback(((I,V)=>{this._logService.debug("Unknown CSI code: ",{identifier:this._parser.identToString(I),params:V.toArray()})})),this._parser.setEscHandlerFallback((I=>{this._logService.debug("Unknown ESC code: ",{identifier:this._parser.identToString(I)})})),this._parser.setExecuteHandlerFallback((I=>{this._logService.debug("Unknown EXECUTE code: ",{code:I})})),this._parser.setOscHandlerFallback(((I,V,W)=>{this._logService.debug("Unknown OSC code: ",{identifier:I,action:V,data:W})})),this._parser.setDcsHandlerFallback(((I,V,W)=>{V==="HOOK"&&(W=W.toArray()),this._logService.debug("Unknown DCS code: ",{identifier:this._parser.identToString(I),action:V,payload:W})})),this._parser.setPrintHandler(((I,V,W)=>this.print(I,V,W))),this._parser.registerCsiHandler({final:"@"},(I=>this.insertChars(I))),this._parser.registerCsiHandler({intermediates:" ",final:"@"},(I=>this.scrollLeft(I))),this._parser.registerCsiHandler({final:"A"},(I=>this.cursorUp(I))),this._parser.registerCsiHandler({intermediates:" ",final:"A"},(I=>this.scrollRight(I))),this._parser.registerCsiHandler({final:"B"},(I=>this.cursorDown(I))),this._parser.registerCsiHandler({final:"C"},(I=>this.cursorForward(I))),this._parser.registerCsiHandler({final:"D"},(I=>this.cursorBackward(I))),this._parser.registerCsiHandler({final:"E"},(I=>this.cursorNextLine(I))),this._parser.registerCsiHandler({final:"F"},(I=>this.cursorPrecedingLine(I))),this._parser.registerCsiHandler({final:"G"},(I=>this.cursorCharAbsolute(I))),this._parser.registerCsiHandler({final:"H"},(I=>this.cursorPosition(I))),this._parser.registerCsiHandler({final:"I"},(I=>this.cursorForwardTab(I))),this._parser.registerCsiHandler({final:"J"},(I=>this.eraseInDisplay(I,!1))),this._parser.registerCsiHandler({prefix:"?",final:"J"},(I=>this.eraseInDisplay(I,!0))),this._parser.registerCsiHandler({final:"K"},(I=>this.eraseInLine(I,!1))),this._parser.registerCsiHandler({prefix:"?",final:"K"},(I=>this.eraseInLine(I,!0))),this._parser.registerCsiHandler({final:"L"},(I=>this.insertLines(I))),this._parser.registerCsiHandler({final:"M"},(I=>this.deleteLines(I))),this._parser.registerCsiHandler({final:"P"},(I=>this.deleteChars(I))),this._parser.registerCsiHandler({final:"S"},(I=>this.scrollUp(I))),this._parser.registerCsiHandler({final:"T"},(I=>this.scrollDown(I))),this._parser.registerCsiHandler({final:"X"},(I=>this.eraseChars(I))),this._parser.registerCsiHandler({final:"Z"},(I=>this.cursorBackwardTab(I))),this._parser.registerCsiHandler({final:"`"},(I=>this.charPosAbsolute(I))),this._parser.registerCsiHandler({final:"a"},(I=>this.hPositionRelative(I))),this._parser.registerCsiHandler({final:"b"},(I=>this.repeatPrecedingCharacter(I))),this._parser.registerCsiHandler({final:"c"},(I=>this.sendDeviceAttributesPrimary(I))),this._parser.registerCsiHandler({prefix:">",final:"c"},(I=>this.sendDeviceAttributesSecondary(I))),this._parser.registerCsiHandler({final:"d"},(I=>this.linePosAbsolute(I))),this._parser.registerCsiHandler({final:"e"},(I=>this.vPositionRelative(I))),this._parser.registerCsiHandler({final:"f"},(I=>this.hVPosition(I))),this._parser.registerCsiHandler({final:"g"},(I=>this.tabClear(I))),this._parser.registerCsiHandler({final:"h"},(I=>this.setMode(I))),this._parser.registerCsiHandler({prefix:"?",final:"h"},(I=>this.setModePrivate(I))),this._parser.registerCsiHandler({final:"l"},(I=>this.resetMode(I))),this._parser.registerCsiHandler({prefix:"?",final:"l"},(I=>this.resetModePrivate(I))),this._parser.registerCsiHandler({final:"m"},(I=>this.charAttributes(I))),this._parser.registerCsiHandler({final:"n"},(I=>this.deviceStatus(I))),this._parser.registerCsiHandler({prefix:"?",final:"n"},(I=>this.deviceStatusPrivate(I))),this._parser.registerCsiHandler({intermediates:"!",final:"p"},(I=>this.softReset(I))),this._parser.registerCsiHandler({intermediates:" ",final:"q"},(I=>this.setCursorStyle(I))),this._parser.registerCsiHandler({final:"r"},(I=>this.setScrollRegion(I))),this._parser.registerCsiHandler({final:"s"},(I=>this.saveCursor(I))),this._parser.registerCsiHandler({final:"t"},(I=>this.windowOptions(I))),this._parser.registerCsiHandler({final:"u"},(I=>this.restoreCursor(I))),this._parser.registerCsiHandler({intermediates:"'",final:"}"},(I=>this.insertColumns(I))),this._parser.registerCsiHandler({intermediates:"'",final:"~"},(I=>this.deleteColumns(I))),this._parser.registerCsiHandler({intermediates:'"',final:"q"},(I=>this.selectProtected(I))),this._parser.registerCsiHandler({intermediates:"$",final:"p"},(I=>this.requestMode(I,!0))),this._parser.registerCsiHandler({prefix:"?",intermediates:"$",final:"p"},(I=>this.requestMode(I,!1))),this._parser.setExecuteHandler(h.C0.BEL,(()=>this.bell())),this._parser.setExecuteHandler(h.C0.LF,(()=>this.lineFeed())),this._parser.setExecuteHandler(h.C0.VT,(()=>this.lineFeed())),this._parser.setExecuteHandler(h.C0.FF,(()=>this.lineFeed())),this._parser.setExecuteHandler(h.C0.CR,(()=>this.carriageReturn())),this._parser.setExecuteHandler(h.C0.BS,(()=>this.backspace())),this._parser.setExecuteHandler(h.C0.HT,(()=>this.tab())),this._parser.setExecuteHandler(h.C0.SO,(()=>this.shiftOut())),this._parser.setExecuteHandler(h.C0.SI,(()=>this.shiftIn())),this._parser.setExecuteHandler(h.C1.IND,(()=>this.index())),this._parser.setExecuteHandler(h.C1.NEL,(()=>this.nextLine())),this._parser.setExecuteHandler(h.C1.HTS,(()=>this.tabSet())),this._parser.registerOscHandler(0,new k.OscHandler((I=>(this.setTitle(I),this.setIconName(I),!0)))),this._parser.registerOscHandler(1,new k.OscHandler((I=>this.setIconName(I)))),this._parser.registerOscHandler(2,new k.OscHandler((I=>this.setTitle(I)))),this._parser.registerOscHandler(4,new k.OscHandler((I=>this.setOrReportIndexedColor(I)))),this._parser.registerOscHandler(8,new k.OscHandler((I=>this.setHyperlink(I)))),this._parser.registerOscHandler(10,new k.OscHandler((I=>this.setOrReportFgColor(I)))),this._parser.registerOscHandler(11,new k.OscHandler((I=>this.setOrReportBgColor(I)))),this._parser.registerOscHandler(12,new k.OscHandler((I=>this.setOrReportCursorColor(I)))),this._parser.registerOscHandler(104,new k.OscHandler((I=>this.restoreIndexedColor(I)))),this._parser.registerOscHandler(110,new k.OscHandler((I=>this.restoreFgColor(I)))),this._parser.registerOscHandler(111,new k.OscHandler((I=>this.restoreBgColor(I)))),this._parser.registerOscHandler(112,new k.OscHandler((I=>this.restoreCursorColor(I)))),this._parser.registerEscHandler({final:"7"},(()=>this.saveCursor())),this._parser.registerEscHandler({final:"8"},(()=>this.restoreCursor())),this._parser.registerEscHandler({final:"D"},(()=>this.index())),this._parser.registerEscHandler({final:"E"},(()=>this.nextLine())),this._parser.registerEscHandler({final:"H"},(()=>this.tabSet())),this._parser.registerEscHandler({final:"M"},(()=>this.reverseIndex())),this._parser.registerEscHandler({final:"="},(()=>this.keypadApplicationMode())),this._parser.registerEscHandler({final:">"},(()=>this.keypadNumericMode())),this._parser.registerEscHandler({final:"c"},(()=>this.fullReset())),this._parser.registerEscHandler({final:"n"},(()=>this.setgLevel(2))),this._parser.registerEscHandler({final:"o"},(()=>this.setgLevel(3))),this._parser.registerEscHandler({final:"|"},(()=>this.setgLevel(3))),this._parser.registerEscHandler({final:"}"},(()=>this.setgLevel(2))),this._parser.registerEscHandler({final:"~"},(()=>this.setgLevel(1))),this._parser.registerEscHandler({intermediates:"%",final:"@"},(()=>this.selectDefaultCharset())),this._parser.registerEscHandler({intermediates:"%",final:"G"},(()=>this.selectDefaultCharset()));for(const I in _.CHARSETS)this._parser.registerEscHandler({intermediates:"(",final:I},(()=>this.selectCharset("("+I))),this._parser.registerEscHandler({intermediates:")",final:I},(()=>this.selectCharset(")"+I))),this._parser.registerEscHandler({intermediates:"*",final:I},(()=>this.selectCharset("*"+I))),this._parser.registerEscHandler({intermediates:"+",final:I},(()=>this.selectCharset("+"+I))),this._parser.registerEscHandler({intermediates:"-",final:I},(()=>this.selectCharset("-"+I))),this._parser.registerEscHandler({intermediates:".",final:I},(()=>this.selectCharset("."+I))),this._parser.registerEscHandler({intermediates:"/",final:I},(()=>this.selectCharset("/"+I)));this._parser.registerEscHandler({intermediates:"#",final:"8"},(()=>this.screenAlignmentPattern())),this._parser.setErrorHandler((I=>(this._logService.error("Parsing error: ",I),I))),this._parser.registerDcsHandler({intermediates:"$",final:"q"},new E.DcsHandler(((I,V)=>this.requestStatusString(I,V))))}_preserveStack(T,D,P,j){this._parseStack.paused=!0,this._parseStack.cursorStartX=T,this._parseStack.cursorStartY=D,this._parseStack.decodedLength=P,this._parseStack.position=j}_logSlowResolvingAsync(T){this._logService.logLevel<=x.LogLevelEnum.WARN&&Promise.race([T,new Promise(((D,P)=>setTimeout((()=>P("#SLOW_TIMEOUT")),5e3)))]).catch((D=>{if(D!=="#SLOW_TIMEOUT")throw D;console.warn("async parser handler taking longer than 5000 ms")}))}_getCurrentLinkId(){return this._curAttrData.extended.urlId}parse(T,D){let P,j=this._activeBuffer.x,q=this._activeBuffer.y,K=0;const re=this._parseStack.paused;if(re){if(P=this._parser.parse(this._parseBuffer,this._parseStack.decodedLength,D))return this._logSlowResolvingAsync(P),P;j=this._parseStack.cursorStartX,q=this._parseStack.cursorStartY,this._parseStack.paused=!1,T.length>R&&(K=this._parseStack.position+R)}if(this._logService.logLevel<=x.LogLevelEnum.DEBUG&&this._logService.debug("parsing data"+(typeof T=="string"?` "${T}"`:` "${Array.prototype.map.call(T,(I=>String.fromCharCode(I))).join("")}"`),typeof T=="string"?T.split("").map((I=>I.charCodeAt(0))):T),this._parseBuffer.length<T.length&&this._parseBuffer.length<R&&(this._parseBuffer=new Uint32Array(Math.min(T.length,R))),re||this._dirtyRowTracker.clearRange(),T.length>R)for(let I=K;I<T.length;I+=R){const V=I+R<T.length?I+R:T.length,W=typeof T=="string"?this._stringDecoder.decode(T.substring(I,V),this._parseBuffer):this._utf8Decoder.decode(T.subarray(I,V),this._parseBuffer);if(P=this._parser.parse(this._parseBuffer,W))return this._preserveStack(j,q,W,I),this._logSlowResolvingAsync(P),P}else if(!re){const I=typeof T=="string"?this._stringDecoder.decode(T,this._parseBuffer):this._utf8Decoder.decode(T,this._parseBuffer);if(P=this._parser.parse(this._parseBuffer,I))return this._preserveStack(j,q,I,0),this._logSlowResolvingAsync(P),P}this._activeBuffer.x===j&&this._activeBuffer.y===q||this._onCursorMove.fire();const J=this._dirtyRowTracker.end+(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp),U=this._dirtyRowTracker.start+(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp);U<this._bufferService.rows&&this._onRequestRefreshRows.fire(Math.min(U,this._bufferService.rows-1),Math.min(J,this._bufferService.rows-1))}print(T,D,P){let j,q;const K=this._charsetService.charset,re=this._optionsService.rawOptions.screenReaderMode,J=this._bufferService.cols,U=this._coreService.decPrivateModes.wraparound,I=this._coreService.modes.insertMode,V=this._curAttrData;let W=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._activeBuffer.x&&P-D>0&&W.getWidth(this._activeBuffer.x-1)===2&&W.setCellFromCodepoint(this._activeBuffer.x-1,0,1,V);let Q=this._parser.precedingJoinState;for(let Z=D;Z<P;++Z){if(j=T[Z],j<127&&K){const de=K[String.fromCharCode(j)];de&&(j=de.charCodeAt(0))}const ae=this._unicodeService.charProperties(j,Q);q=v.UnicodeService.extractWidth(ae);const oe=v.UnicodeService.extractShouldJoin(ae),ee=oe?v.UnicodeService.extractWidth(Q):0;if(Q=ae,re&&this._onA11yChar.fire((0,y.stringFromCodePoint)(j)),this._getCurrentLinkId()&&this._oscLinkService.addLineToLink(this._getCurrentLinkId(),this._activeBuffer.ybase+this._activeBuffer.y),this._activeBuffer.x+q-ee>J){if(U){const de=W;let ne=this._activeBuffer.x-ee;for(this._activeBuffer.x=ee,this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData(),!0)):(this._activeBuffer.y>=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!0),W=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y),ee>0&&W instanceof c.BufferLine&&W.copyCellsFrom(de,ne,0,ee,!1);ne<J;)de.setCellFromCodepoint(ne++,0,1,V)}else if(this._activeBuffer.x=J-1,q===2)continue}if(oe&&this._activeBuffer.x){const de=W.getWidth(this._activeBuffer.x-1)?1:2;W.addCodepointToCell(this._activeBuffer.x-de,j,q);for(let ne=q-ee;--ne>=0;)W.setCellFromCodepoint(this._activeBuffer.x++,0,0,V)}else if(I&&(W.insertCells(this._activeBuffer.x,q-ee,this._activeBuffer.getNullCell(V)),W.getWidth(J-1)===2&&W.setCellFromCodepoint(J-1,l.NULL_CELL_CODE,l.NULL_CELL_WIDTH,V)),W.setCellFromCodepoint(this._activeBuffer.x++,j,q,V),q>0)for(;--q;)W.setCellFromCodepoint(this._activeBuffer.x++,0,0,V)}this._parser.precedingJoinState=Q,this._activeBuffer.x<J&&P-D>0&&W.getWidth(this._activeBuffer.x)===0&&!W.hasContent(this._activeBuffer.x)&&W.setCellFromCodepoint(this._activeBuffer.x,0,1,V),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}registerCsiHandler(T,D){return T.final!=="t"||T.prefix||T.intermediates?this._parser.registerCsiHandler(T,D):this._parser.registerCsiHandler(T,(P=>!B(P.params[0],this._optionsService.rawOptions.windowOptions)||D(P)))}registerDcsHandler(T,D){return this._parser.registerDcsHandler(T,new E.DcsHandler(D))}registerEscHandler(T,D){return this._parser.registerEscHandler(T,D)}registerOscHandler(T,D){return this._parser.registerOscHandler(T,new k.OscHandler(D))}bell(){return this._onRequestBell.fire(),!0}lineFeed(){return this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._optionsService.rawOptions.convertEol&&(this._activeBuffer.x=0),this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData())):this._activeBuffer.y>=this._bufferService.rows?this._activeBuffer.y=this._bufferService.rows-1:this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.x>=this._bufferService.cols&&this._activeBuffer.x--,this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._onLineFeed.fire(),!0}carriageReturn(){return this._activeBuffer.x=0,!0}backspace(){var T;if(!this._coreService.decPrivateModes.reverseWraparound)return this._restrictCursor(),this._activeBuffer.x>0&&this._activeBuffer.x--,!0;if(this._restrictCursor(this._bufferService.cols),this._activeBuffer.x>0)this._activeBuffer.x--;else if(this._activeBuffer.x===0&&this._activeBuffer.y>this._activeBuffer.scrollTop&&this._activeBuffer.y<=this._activeBuffer.scrollBottom&&((T=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y))!=null&&T.isWrapped)){this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.y--,this._activeBuffer.x=this._bufferService.cols-1;const D=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);D.hasWidth(this._activeBuffer.x)&&!D.hasContent(this._activeBuffer.x)&&this._activeBuffer.x--}return this._restrictCursor(),!0}tab(){if(this._activeBuffer.x>=this._bufferService.cols)return!0;const T=this._activeBuffer.x;return this._activeBuffer.x=this._activeBuffer.nextStop(),this._optionsService.rawOptions.screenReaderMode&&this._onA11yTab.fire(this._activeBuffer.x-T),!0}shiftOut(){return this._charsetService.setgLevel(1),!0}shiftIn(){return this._charsetService.setgLevel(0),!0}_restrictCursor(T=this._bufferService.cols-1){this._activeBuffer.x=Math.min(T,Math.max(0,this._activeBuffer.x)),this._activeBuffer.y=this._coreService.decPrivateModes.origin?Math.min(this._activeBuffer.scrollBottom,Math.max(this._activeBuffer.scrollTop,this._activeBuffer.y)):Math.min(this._bufferService.rows-1,Math.max(0,this._activeBuffer.y)),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_setCursor(T,D){this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._coreService.decPrivateModes.origin?(this._activeBuffer.x=T,this._activeBuffer.y=this._activeBuffer.scrollTop+D):(this._activeBuffer.x=T,this._activeBuffer.y=D),this._restrictCursor(),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_moveCursor(T,D){this._restrictCursor(),this._setCursor(this._activeBuffer.x+T,this._activeBuffer.y+D)}cursorUp(T){const D=this._activeBuffer.y-this._activeBuffer.scrollTop;return D>=0?this._moveCursor(0,-Math.min(D,T.params[0]||1)):this._moveCursor(0,-(T.params[0]||1)),!0}cursorDown(T){const D=this._activeBuffer.scrollBottom-this._activeBuffer.y;return D>=0?this._moveCursor(0,Math.min(D,T.params[0]||1)):this._moveCursor(0,T.params[0]||1),!0}cursorForward(T){return this._moveCursor(T.params[0]||1,0),!0}cursorBackward(T){return this._moveCursor(-(T.params[0]||1),0),!0}cursorNextLine(T){return this.cursorDown(T),this._activeBuffer.x=0,!0}cursorPrecedingLine(T){return this.cursorUp(T),this._activeBuffer.x=0,!0}cursorCharAbsolute(T){return this._setCursor((T.params[0]||1)-1,this._activeBuffer.y),!0}cursorPosition(T){return this._setCursor(T.length>=2?(T.params[1]||1)-1:0,(T.params[0]||1)-1),!0}charPosAbsolute(T){return this._setCursor((T.params[0]||1)-1,this._activeBuffer.y),!0}hPositionRelative(T){return this._moveCursor(T.params[0]||1,0),!0}linePosAbsolute(T){return this._setCursor(this._activeBuffer.x,(T.params[0]||1)-1),!0}vPositionRelative(T){return this._moveCursor(0,T.params[0]||1),!0}hVPosition(T){return this.cursorPosition(T),!0}tabClear(T){const D=T.params[0];return D===0?delete this._activeBuffer.tabs[this._activeBuffer.x]:D===3&&(this._activeBuffer.tabs={}),!0}cursorForwardTab(T){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let D=T.params[0]||1;for(;D--;)this._activeBuffer.x=this._activeBuffer.nextStop();return!0}cursorBackwardTab(T){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let D=T.params[0]||1;for(;D--;)this._activeBuffer.x=this._activeBuffer.prevStop();return!0}selectProtected(T){const D=T.params[0];return D===1&&(this._curAttrData.bg|=536870912),D!==2&&D!==0||(this._curAttrData.bg&=-536870913),!0}_eraseInBufferLine(T,D,P,j=!1,q=!1){const K=this._activeBuffer.lines.get(this._activeBuffer.ybase+T);K.replaceCells(D,P,this._activeBuffer.getNullCell(this._eraseAttrData()),q),j&&(K.isWrapped=!1)}_resetBufferLine(T,D=!1){const P=this._activeBuffer.lines.get(this._activeBuffer.ybase+T);P&&(P.fill(this._activeBuffer.getNullCell(this._eraseAttrData()),D),this._bufferService.buffer.clearMarkers(this._activeBuffer.ybase+T),P.isWrapped=!1)}eraseInDisplay(T,D=!1){let P;switch(this._restrictCursor(this._bufferService.cols),T.params[0]){case 0:for(P=this._activeBuffer.y,this._dirtyRowTracker.markDirty(P),this._eraseInBufferLine(P++,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,D);P<this._bufferService.rows;P++)this._resetBufferLine(P,D);this._dirtyRowTracker.markDirty(P);break;case 1:for(P=this._activeBuffer.y,this._dirtyRowTracker.markDirty(P),this._eraseInBufferLine(P,0,this._activeBuffer.x+1,!0,D),this._activeBuffer.x+1>=this._bufferService.cols&&(this._activeBuffer.lines.get(P+1).isWrapped=!1);P--;)this._resetBufferLine(P,D);this._dirtyRowTracker.markDirty(0);break;case 2:for(P=this._bufferService.rows,this._dirtyRowTracker.markDirty(P-1);P--;)this._resetBufferLine(P,D);this._dirtyRowTracker.markDirty(0);break;case 3:const j=this._activeBuffer.lines.length-this._bufferService.rows;j>0&&(this._activeBuffer.lines.trimStart(j),this._activeBuffer.ybase=Math.max(this._activeBuffer.ybase-j,0),this._activeBuffer.ydisp=Math.max(this._activeBuffer.ydisp-j,0),this._onScroll.fire(0))}return!0}eraseInLine(T,D=!1){switch(this._restrictCursor(this._bufferService.cols),T.params[0]){case 0:this._eraseInBufferLine(this._activeBuffer.y,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,D);break;case 1:this._eraseInBufferLine(this._activeBuffer.y,0,this._activeBuffer.x+1,!1,D);break;case 2:this._eraseInBufferLine(this._activeBuffer.y,0,this._bufferService.cols,!0,D)}return this._dirtyRowTracker.markDirty(this._activeBuffer.y),!0}insertLines(T){this._restrictCursor();let D=T.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;const P=this._activeBuffer.ybase+this._activeBuffer.y,j=this._bufferService.rows-1-this._activeBuffer.scrollBottom,q=this._bufferService.rows-1+this._activeBuffer.ybase-j+1;for(;D--;)this._activeBuffer.lines.splice(q-1,1),this._activeBuffer.lines.splice(P,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.y,this._activeBuffer.scrollBottom),this._activeBuffer.x=0,!0}deleteLines(T){this._restrictCursor();let D=T.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;const P=this._activeBuffer.ybase+this._activeBuffer.y;let j;for(j=this._bufferService.rows-1-this._activeBuffer.scrollBottom,j=this._bufferService.rows-1+this._activeBuffer.ybase-j;D--;)this._activeBuffer.lines.splice(P,1),this._activeBuffer.lines.splice(j,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.y,this._activeBuffer.scrollBottom),this._activeBuffer.x=0,!0}insertChars(T){this._restrictCursor();const D=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return D&&(D.insertCells(this._activeBuffer.x,T.params[0]||1,this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}deleteChars(T){this._restrictCursor();const D=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return D&&(D.deleteCells(this._activeBuffer.x,T.params[0]||1,this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}scrollUp(T){let D=T.params[0]||1;for(;D--;)this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollTop,1),this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollBottom,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollDown(T){let D=T.params[0]||1;for(;D--;)this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollBottom,1),this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollTop,0,this._activeBuffer.getBlankLine(c.DEFAULT_ATTR_DATA));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollLeft(T){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;const D=T.params[0]||1;for(let P=this._activeBuffer.scrollTop;P<=this._activeBuffer.scrollBottom;++P){const j=this._activeBuffer.lines.get(this._activeBuffer.ybase+P);j.deleteCells(0,D,this._activeBuffer.getNullCell(this._eraseAttrData())),j.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollRight(T){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;const D=T.params[0]||1;for(let P=this._activeBuffer.scrollTop;P<=this._activeBuffer.scrollBottom;++P){const j=this._activeBuffer.lines.get(this._activeBuffer.ybase+P);j.insertCells(0,D,this._activeBuffer.getNullCell(this._eraseAttrData())),j.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}insertColumns(T){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;const D=T.params[0]||1;for(let P=this._activeBuffer.scrollTop;P<=this._activeBuffer.scrollBottom;++P){const j=this._activeBuffer.lines.get(this._activeBuffer.ybase+P);j.insertCells(this._activeBuffer.x,D,this._activeBuffer.getNullCell(this._eraseAttrData())),j.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}deleteColumns(T){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;const D=T.params[0]||1;for(let P=this._activeBuffer.scrollTop;P<=this._activeBuffer.scrollBottom;++P){const j=this._activeBuffer.lines.get(this._activeBuffer.ybase+P);j.deleteCells(this._activeBuffer.x,D,this._activeBuffer.getNullCell(this._eraseAttrData())),j.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}eraseChars(T){this._restrictCursor();const D=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return D&&(D.replaceCells(this._activeBuffer.x,this._activeBuffer.x+(T.params[0]||1),this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}repeatPrecedingCharacter(T){const D=this._parser.precedingJoinState;if(!D)return!0;const P=T.params[0]||1,j=v.UnicodeService.extractWidth(D),q=this._activeBuffer.x-j,K=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).getString(q),re=new Uint32Array(K.length*P);let J=0;for(let I=0;I<K.length;){const V=K.codePointAt(I)||0;re[J++]=V,I+=V>65535?2:1}let U=J;for(let I=1;I<P;++I)re.copyWithin(U,0,J),U+=J;return this.print(re,0,U),!0}sendDeviceAttributesPrimary(T){return T.params[0]>0||(this._is("xterm")||this._is("rxvt-unicode")||this._is("screen")?this._coreService.triggerDataEvent(h.C0.ESC+"[?1;2c"):this._is("linux")&&this._coreService.triggerDataEvent(h.C0.ESC+"[?6c")),!0}sendDeviceAttributesSecondary(T){return T.params[0]>0||(this._is("xterm")?this._coreService.triggerDataEvent(h.C0.ESC+"[>0;276;0c"):this._is("rxvt-unicode")?this._coreService.triggerDataEvent(h.C0.ESC+"[>85;95;0c"):this._is("linux")?this._coreService.triggerDataEvent(T.params[0]+"c"):this._is("screen")&&this._coreService.triggerDataEvent(h.C0.ESC+"[>83;40003;0c")),!0}_is(T){return(this._optionsService.rawOptions.termName+"").indexOf(T)===0}setMode(T){for(let D=0;D<T.length;D++)switch(T.params[D]){case 4:this._coreService.modes.insertMode=!0;break;case 20:this._optionsService.options.convertEol=!0}return!0}setModePrivate(T){for(let D=0;D<T.length;D++)switch(T.params[D]){case 1:this._coreService.decPrivateModes.applicationCursorKeys=!0;break;case 2:this._charsetService.setgCharset(0,_.DEFAULT_CHARSET),this._charsetService.setgCharset(1,_.DEFAULT_CHARSET),this._charsetService.setgCharset(2,_.DEFAULT_CHARSET),this._charsetService.setgCharset(3,_.DEFAULT_CHARSET);break;case 3:this._optionsService.rawOptions.windowOptions.setWinLines&&(this._bufferService.resize(132,this._bufferService.rows),this._onRequestReset.fire());break;case 6:this._coreService.decPrivateModes.origin=!0,this._setCursor(0,0);break;case 7:this._coreService.decPrivateModes.wraparound=!0;break;case 12:this._optionsService.options.cursorBlink=!0;break;case 45:this._coreService.decPrivateModes.reverseWraparound=!0;break;case 66:this._logService.debug("Serial port requested application keypad."),this._coreService.decPrivateModes.applicationKeypad=!0,this._onRequestSyncScrollBar.fire();break;case 9:this._coreMouseService.activeProtocol="X10";break;case 1e3:this._coreMouseService.activeProtocol="VT200";break;case 1002:this._coreMouseService.activeProtocol="DRAG";break;case 1003:this._coreMouseService.activeProtocol="ANY";break;case 1004:this._coreService.decPrivateModes.sendFocus=!0,this._onRequestSendFocus.fire();break;case 1005:this._logService.debug("DECSET 1005 not supported (see #2507)");break;case 1006:this._coreMouseService.activeEncoding="SGR";break;case 1015:this._logService.debug("DECSET 1015 not supported (see #2507)");break;case 1016:this._coreMouseService.activeEncoding="SGR_PIXELS";break;case 25:this._coreService.isCursorHidden=!1;break;case 1048:this.saveCursor();break;case 1049:this.saveCursor();case 47:case 1047:this._bufferService.buffers.activateAltBuffer(this._eraseAttrData()),this._coreService.isCursorInitialized=!0,this._onRequestRefreshRows.fire(0,this._bufferService.rows-1),this._onRequestSyncScrollBar.fire();break;case 2004:this._coreService.decPrivateModes.bracketedPasteMode=!0}return!0}resetMode(T){for(let D=0;D<T.length;D++)switch(T.params[D]){case 4:this._coreService.modes.insertMode=!1;break;case 20:this._optionsService.options.convertEol=!1}return!0}resetModePrivate(T){for(let D=0;D<T.length;D++)switch(T.params[D]){case 1:this._coreService.decPrivateModes.applicationCursorKeys=!1;break;case 3:this._optionsService.rawOptions.windowOptions.setWinLines&&(this._bufferService.resize(80,this._bufferService.rows),this._onRequestReset.fire());break;case 6:this._coreService.decPrivateModes.origin=!1,this._setCursor(0,0);break;case 7:this._coreService.decPrivateModes.wraparound=!1;break;case 12:this._optionsService.options.cursorBlink=!1;break;case 45:this._coreService.decPrivateModes.reverseWraparound=!1;break;case 66:this._logService.debug("Switching back to normal keypad."),this._coreService.decPrivateModes.applicationKeypad=!1,this._onRequestSyncScrollBar.fire();break;case 9:case 1e3:case 1002:case 1003:this._coreMouseService.activeProtocol="NONE";break;case 1004:this._coreService.decPrivateModes.sendFocus=!1;break;case 1005:this._logService.debug("DECRST 1005 not supported (see #2507)");break;case 1006:case 1016:this._coreMouseService.activeEncoding="DEFAULT";break;case 1015:this._logService.debug("DECRST 1015 not supported (see #2507)");break;case 25:this._coreService.isCursorHidden=!0;break;case 1048:this.restoreCursor();break;case 1049:case 47:case 1047:this._bufferService.buffers.activateNormalBuffer(),T.params[D]===1049&&this.restoreCursor(),this._coreService.isCursorInitialized=!0,this._onRequestRefreshRows.fire(0,this._bufferService.rows-1),this._onRequestSyncScrollBar.fire();break;case 2004:this._coreService.decPrivateModes.bracketedPasteMode=!1}return!0}requestMode(T,D){const P=this._coreService.decPrivateModes,{activeProtocol:j,activeEncoding:q}=this._coreMouseService,K=this._coreService,{buffers:re,cols:J}=this._bufferService,{active:U,alt:I}=re,V=this._optionsService.rawOptions,W=oe=>oe?1:2,Q=T.params[0];return Z=Q,ae=D?Q===2?4:Q===4?W(K.modes.insertMode):Q===12?3:Q===20?W(V.convertEol):0:Q===1?W(P.applicationCursorKeys):Q===3?V.windowOptions.setWinLines?J===80?2:J===132?1:0:0:Q===6?W(P.origin):Q===7?W(P.wraparound):Q===8?3:Q===9?W(j==="X10"):Q===12?W(V.cursorBlink):Q===25?W(!K.isCursorHidden):Q===45?W(P.reverseWraparound):Q===66?W(P.applicationKeypad):Q===67?4:Q===1e3?W(j==="VT200"):Q===1002?W(j==="DRAG"):Q===1003?W(j==="ANY"):Q===1004?W(P.sendFocus):Q===1005?4:Q===1006?W(q==="SGR"):Q===1015?4:Q===1016?W(q==="SGR_PIXELS"):Q===1048?1:Q===47||Q===1047||Q===1049?W(U===I):Q===2004?W(P.bracketedPasteMode):0,K.triggerDataEvent(`${h.C0.ESC}[${D?"":"?"}${Z};${ae}$y`),!0;var Z,ae}_updateAttrColor(T,D,P,j,q){return D===2?(T|=50331648,T&=-16777216,T|=m.AttributeData.fromColorRGB([P,j,q])):D===5&&(T&=-50331904,T|=33554432|255&P),T}_extractColor(T,D,P){const j=[0,0,-1,0,0,0];let q=0,K=0;do{if(j[K+q]=T.params[D+K],T.hasSubParams(D+K)){const re=T.getSubParams(D+K);let J=0;do j[1]===5&&(q=1),j[K+J+1+q]=re[J];while(++J<re.length&&J+K+1+q<j.length);break}if(j[1]===5&&K+q>=2||j[1]===2&&K+q>=5)break;j[1]&&(q=1)}while(++K+D<T.length&&K+q<j.length);for(let re=2;re<j.length;++re)j[re]===-1&&(j[re]=0);switch(j[0]){case 38:P.fg=this._updateAttrColor(P.fg,j[1],j[3],j[4],j[5]);break;case 48:P.bg=this._updateAttrColor(P.bg,j[1],j[3],j[4],j[5]);break;case 58:P.extended=P.extended.clone(),P.extended.underlineColor=this._updateAttrColor(P.extended.underlineColor,j[1],j[3],j[4],j[5])}return K}_processUnderline(T,D){D.extended=D.extended.clone(),(!~T||T>5)&&(T=1),D.extended.underlineStyle=T,D.fg|=268435456,T===0&&(D.fg&=-268435457),D.updateExtended()}_processSGR0(T){T.fg=c.DEFAULT_ATTR_DATA.fg,T.bg=c.DEFAULT_ATTR_DATA.bg,T.extended=T.extended.clone(),T.extended.underlineStyle=0,T.extended.underlineColor&=-67108864,T.updateExtended()}charAttributes(T){if(T.length===1&&T.params[0]===0)return this._processSGR0(this._curAttrData),!0;const D=T.length;let P;const j=this._curAttrData;for(let q=0;q<D;q++)P=T.params[q],P>=30&&P<=37?(j.fg&=-50331904,j.fg|=16777216|P-30):P>=40&&P<=47?(j.bg&=-50331904,j.bg|=16777216|P-40):P>=90&&P<=97?(j.fg&=-50331904,j.fg|=16777224|P-90):P>=100&&P<=107?(j.bg&=-50331904,j.bg|=16777224|P-100):P===0?this._processSGR0(j):P===1?j.fg|=134217728:P===3?j.bg|=67108864:P===4?(j.fg|=268435456,this._processUnderline(T.hasSubParams(q)?T.getSubParams(q)[0]:1,j)):P===5?j.fg|=536870912:P===7?j.fg|=67108864:P===8?j.fg|=1073741824:P===9?j.fg|=2147483648:P===2?j.bg|=134217728:P===21?this._processUnderline(2,j):P===22?(j.fg&=-134217729,j.bg&=-134217729):P===23?j.bg&=-67108865:P===24?(j.fg&=-268435457,this._processUnderline(0,j)):P===25?j.fg&=-536870913:P===27?j.fg&=-67108865:P===28?j.fg&=-1073741825:P===29?j.fg&=2147483647:P===39?(j.fg&=-67108864,j.fg|=16777215&c.DEFAULT_ATTR_DATA.fg):P===49?(j.bg&=-67108864,j.bg|=16777215&c.DEFAULT_ATTR_DATA.bg):P===38||P===48||P===58?q+=this._extractColor(T,q,j):P===53?j.bg|=1073741824:P===55?j.bg&=-1073741825:P===59?(j.extended=j.extended.clone(),j.extended.underlineColor=-1,j.updateExtended()):P===100?(j.fg&=-67108864,j.fg|=16777215&c.DEFAULT_ATTR_DATA.fg,j.bg&=-67108864,j.bg|=16777215&c.DEFAULT_ATTR_DATA.bg):this._logService.debug("Unknown SGR attribute: %d.",P);return!0}deviceStatus(T){switch(T.params[0]){case 5:this._coreService.triggerDataEvent(`${h.C0.ESC}[0n`);break;case 6:const D=this._activeBuffer.y+1,P=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${h.C0.ESC}[${D};${P}R`)}return!0}deviceStatusPrivate(T){if(T.params[0]===6){const D=this._activeBuffer.y+1,P=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${h.C0.ESC}[?${D};${P}R`)}return!0}softReset(T){return this._coreService.isCursorHidden=!1,this._onRequestSyncScrollBar.fire(),this._activeBuffer.scrollTop=0,this._activeBuffer.scrollBottom=this._bufferService.rows-1,this._curAttrData=c.DEFAULT_ATTR_DATA.clone(),this._coreService.reset(),this._charsetService.reset(),this._activeBuffer.savedX=0,this._activeBuffer.savedY=this._activeBuffer.ybase,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,this._coreService.decPrivateModes.origin=!1,!0}setCursorStyle(T){const D=T.params[0]||1;switch(D){case 1:case 2:this._optionsService.options.cursorStyle="block";break;case 3:case 4:this._optionsService.options.cursorStyle="underline";break;case 5:case 6:this._optionsService.options.cursorStyle="bar"}const P=D%2==1;return this._optionsService.options.cursorBlink=P,!0}setScrollRegion(T){const D=T.params[0]||1;let P;return(T.length<2||(P=T.params[1])>this._bufferService.rows||P===0)&&(P=this._bufferService.rows),P>D&&(this._activeBuffer.scrollTop=D-1,this._activeBuffer.scrollBottom=P-1,this._setCursor(0,0)),!0}windowOptions(T){if(!B(T.params[0],this._optionsService.rawOptions.windowOptions))return!0;const D=T.length>1?T.params[1]:0;switch(T.params[0]){case 14:D!==2&&this._onRequestWindowsOptionsReport.fire(A.GET_WIN_SIZE_PIXELS);break;case 16:this._onRequestWindowsOptionsReport.fire(A.GET_CELL_SIZE_PIXELS);break;case 18:this._bufferService&&this._coreService.triggerDataEvent(`${h.C0.ESC}[8;${this._bufferService.rows};${this._bufferService.cols}t`);break;case 22:D!==0&&D!==2||(this._windowTitleStack.push(this._windowTitle),this._windowTitleStack.length>10&&this._windowTitleStack.shift()),D!==0&&D!==1||(this._iconNameStack.push(this._iconName),this._iconNameStack.length>10&&this._iconNameStack.shift());break;case 23:D!==0&&D!==2||this._windowTitleStack.length&&this.setTitle(this._windowTitleStack.pop()),D!==0&&D!==1||this._iconNameStack.length&&this.setIconName(this._iconNameStack.pop())}return!0}saveCursor(T){return this._activeBuffer.savedX=this._activeBuffer.x,this._activeBuffer.savedY=this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,!0}restoreCursor(T){return this._activeBuffer.x=this._activeBuffer.savedX||0,this._activeBuffer.y=Math.max(this._activeBuffer.savedY-this._activeBuffer.ybase,0),this._curAttrData.fg=this._activeBuffer.savedCurAttrData.fg,this._curAttrData.bg=this._activeBuffer.savedCurAttrData.bg,this._charsetService.charset=this._savedCharset,this._activeBuffer.savedCharset&&(this._charsetService.charset=this._activeBuffer.savedCharset),this._restrictCursor(),!0}setTitle(T){return this._windowTitle=T,this._onTitleChange.fire(T),!0}setIconName(T){return this._iconName=T,!0}setOrReportIndexedColor(T){const D=[],P=T.split(";");for(;P.length>1;){const j=P.shift(),q=P.shift();if(/^\d+$/.exec(j)){const K=parseInt(j);if(z(K))if(q==="?")D.push({type:0,index:K});else{const re=(0,C.parseColor)(q);re&&D.push({type:1,index:K,color:re})}}}return D.length&&this._onColor.fire(D),!0}setHyperlink(T){const D=T.split(";");return!(D.length<2)&&(D[1]?this._createHyperlink(D[0],D[1]):!D[0]&&this._finishHyperlink())}_createHyperlink(T,D){this._getCurrentLinkId()&&this._finishHyperlink();const P=T.split(":");let j;const q=P.findIndex((K=>K.startsWith("id=")));return q!==-1&&(j=P[q].slice(3)||void 0),this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=this._oscLinkService.registerLink({id:j,uri:D}),this._curAttrData.updateExtended(),!0}_finishHyperlink(){return this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=0,this._curAttrData.updateExtended(),!0}_setOrReportSpecialColor(T,D){const P=T.split(";");for(let j=0;j<P.length&&!(D>=this._specialColors.length);++j,++D)if(P[j]==="?")this._onColor.fire([{type:0,index:this._specialColors[D]}]);else{const q=(0,C.parseColor)(P[j]);q&&this._onColor.fire([{type:1,index:this._specialColors[D],color:q}])}return!0}setOrReportFgColor(T){return this._setOrReportSpecialColor(T,0)}setOrReportBgColor(T){return this._setOrReportSpecialColor(T,1)}setOrReportCursorColor(T){return this._setOrReportSpecialColor(T,2)}restoreIndexedColor(T){if(!T)return this._onColor.fire([{type:2}]),!0;const D=[],P=T.split(";");for(let j=0;j<P.length;++j)if(/^\d+$/.exec(P[j])){const q=parseInt(P[j]);z(q)&&D.push({type:2,index:q})}return D.length&&this._onColor.fire(D),!0}restoreFgColor(T){return this._onColor.fire([{type:2,index:256}]),!0}restoreBgColor(T){return this._onColor.fire([{type:2,index:257}]),!0}restoreCursorColor(T){return this._onColor.fire([{type:2,index:258}]),!0}nextLine(){return this._activeBuffer.x=0,this.index(),!0}keypadApplicationMode(){return this._logService.debug("Serial port requested application keypad."),this._coreService.decPrivateModes.applicationKeypad=!0,this._onRequestSyncScrollBar.fire(),!0}keypadNumericMode(){return this._logService.debug("Switching back to normal keypad."),this._coreService.decPrivateModes.applicationKeypad=!1,this._onRequestSyncScrollBar.fire(),!0}selectDefaultCharset(){return this._charsetService.setgLevel(0),this._charsetService.setgCharset(0,_.DEFAULT_CHARSET),!0}selectCharset(T){return T.length!==2?(this.selectDefaultCharset(),!0):(T[0]==="/"||this._charsetService.setgCharset(N[T[0]],_.CHARSETS[T[1]]||_.DEFAULT_CHARSET),!0)}index(){return this._restrictCursor(),this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData())):this._activeBuffer.y>=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._restrictCursor(),!0}tabSet(){return this._activeBuffer.tabs[this._activeBuffer.x]=!0,!0}reverseIndex(){if(this._restrictCursor(),this._activeBuffer.y===this._activeBuffer.scrollTop){const T=this._activeBuffer.scrollBottom-this._activeBuffer.scrollTop;this._activeBuffer.lines.shiftElements(this._activeBuffer.ybase+this._activeBuffer.y,T,1),this._activeBuffer.lines.set(this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.getBlankLine(this._eraseAttrData())),this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom)}else this._activeBuffer.y--,this._restrictCursor();return!0}fullReset(){return this._parser.reset(),this._onRequestReset.fire(),!0}reset(){this._curAttrData=c.DEFAULT_ATTR_DATA.clone(),this._eraseAttrDataInternal=c.DEFAULT_ATTR_DATA.clone()}_eraseAttrData(){return this._eraseAttrDataInternal.bg&=-67108864,this._eraseAttrDataInternal.bg|=67108863&this._curAttrData.bg,this._eraseAttrDataInternal}setgLevel(T){return this._charsetService.setgLevel(T),!0}screenAlignmentPattern(){const T=new u.CellData;T.content=4194373,T.fg=this._curAttrData.fg,T.bg=this._curAttrData.bg,this._setCursor(0,0);for(let D=0;D<this._bufferService.rows;++D){const P=this._activeBuffer.ybase+this._activeBuffer.y+D,j=this._activeBuffer.lines.get(P);j&&(j.fill(T),j.isWrapped=!1)}return this._dirtyRowTracker.markAllDirty(),this._setCursor(0,0),!0}requestStatusString(T,D){const P=this._bufferService.buffer,j=this._optionsService.rawOptions;return(q=>(this._coreService.triggerDataEvent(`${h.C0.ESC}${q}${h.C0.ESC}\\`),!0))(T==='"q'?`P1$r${this._curAttrData.isProtected()?1:0}"q`:T==='"p'?'P1$r61;1"p':T==="r"?`P1$r${P.scrollTop+1};${P.scrollBottom+1}r`:T==="m"?"P1$r0m":T===" q"?`P1$r${{block:2,underline:4,bar:6}[j.cursorStyle]-(j.cursorBlink?1:0)} q`:"P0$r")}markRangeDirty(T,D){this._dirtyRowTracker.markRangeDirty(T,D)}}n.InputHandler=M;let H=class{constructor(G){this._bufferService=G,this.clearRange()}clearRange(){this.start=this._bufferService.buffer.y,this.end=this._bufferService.buffer.y}markDirty(G){G<this.start?this.start=G:G>this.end&&(this.end=G)}markRangeDirty(G,T){G>T&&(F=G,G=T,T=F),G<this.start&&(this.start=G),T>this.end&&(this.end=T)}markAllDirty(){this.markRangeDirty(0,this._bufferService.rows-1)}};function z(G){return 0<=G&&G<256}H=d([f(0,x.IBufferService)],H)},844:(b,n)=>{function o(d){for(const f of d)f.dispose();d.length=0}Object.defineProperty(n,"__esModule",{value:!0}),n.getDisposeArrayDisposable=n.disposeArray=n.toDisposable=n.MutableDisposable=n.Disposable=void 0,n.Disposable=class{constructor(){this._disposables=[],this._isDisposed=!1}dispose(){this._isDisposed=!0;for(const d of this._disposables)d.dispose();this._disposables.length=0}register(d){return this._disposables.push(d),d}unregister(d){const f=this._disposables.indexOf(d);f!==-1&&this._disposables.splice(f,1)}},n.MutableDisposable=class{constructor(){this._isDisposed=!1}get value(){return this._isDisposed?void 0:this._value}set value(d){var f;this._isDisposed||d===this._value||((f=this._value)==null||f.dispose(),this._value=d)}clear(){this.value=void 0}dispose(){var d;this._isDisposed=!0,(d=this._value)==null||d.dispose(),this._value=void 0}},n.toDisposable=function(d){return{dispose:d}},n.disposeArray=o,n.getDisposeArrayDisposable=function(d){return{dispose:()=>o(d)}}},1505:(b,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.FourKeyMap=n.TwoKeyMap=void 0;class o{constructor(){this._data={}}set(f,h,_){this._data[f]||(this._data[f]={}),this._data[f][h]=_}get(f,h){return this._data[f]?this._data[f][h]:void 0}clear(){this._data={}}}n.TwoKeyMap=o,n.FourKeyMap=class{constructor(){this._data=new o}set(d,f,h,_,S){this._data.get(d,f)||this._data.set(d,f,new o),this._data.get(d,f).set(h,_,S)}get(d,f,h,_){var S;return(S=this._data.get(d,f))==null?void 0:S.get(h,_)}clear(){this._data.clear()}}},6114:(b,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.isChromeOS=n.isLinux=n.isWindows=n.isIphone=n.isIpad=n.isMac=n.getSafariVersion=n.isSafari=n.isLegacyEdge=n.isFirefox=n.isNode=void 0,n.isNode=typeof process<"u"&&"title"in process;const o=n.isNode?"node":navigator.userAgent,d=n.isNode?"node":navigator.platform;n.isFirefox=o.includes("Firefox"),n.isLegacyEdge=o.includes("Edge"),n.isSafari=/^((?!chrome|android).)*safari/i.test(o),n.getSafariVersion=function(){if(!n.isSafari)return 0;const f=o.match(/Version\/(\d+)/);return f===null||f.length<2?0:parseInt(f[1])},n.isMac=["Macintosh","MacIntel","MacPPC","Mac68K"].includes(d),n.isIpad=d==="iPad",n.isIphone=d==="iPhone",n.isWindows=["Windows","Win16","Win32","WinCE"].includes(d),n.isLinux=d.indexOf("Linux")>=0,n.isChromeOS=/\bCrOS\b/.test(o)},6106:(b,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.SortedList=void 0;let o=0;n.SortedList=class{constructor(d){this._getKey=d,this._array=[]}clear(){this._array.length=0}insert(d){this._array.length!==0?(o=this._search(this._getKey(d)),this._array.splice(o,0,d)):this._array.push(d)}delete(d){if(this._array.length===0)return!1;const f=this._getKey(d);if(f===void 0||(o=this._search(f),o===-1)||this._getKey(this._array[o])!==f)return!1;do if(this._array[o]===d)return this._array.splice(o,1),!0;while(++o<this._array.length&&this._getKey(this._array[o])===f);return!1}*getKeyIterator(d){if(this._array.length!==0&&(o=this._search(d),!(o<0||o>=this._array.length)&&this._getKey(this._array[o])===d))do yield this._array[o];while(++o<this._array.length&&this._getKey(this._array[o])===d)}forEachByKey(d,f){if(this._array.length!==0&&(o=this._search(d),!(o<0||o>=this._array.length)&&this._getKey(this._array[o])===d))do f(this._array[o]);while(++o<this._array.length&&this._getKey(this._array[o])===d)}values(){return[...this._array].values()}_search(d){let f=0,h=this._array.length-1;for(;h>=f;){let _=f+h>>1;const S=this._getKey(this._array[_]);if(S>d)h=_-1;else{if(!(S<d)){for(;_>0&&this._getKey(this._array[_-1])===d;)_--;return _}f=_+1}}return f}}},7226:(b,n,o)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.DebouncedIdleTask=n.IdleTaskQueue=n.PriorityTaskQueue=void 0;const d=o(6114);class f{constructor(){this._tasks=[],this._i=0}enqueue(S){this._tasks.push(S),this._start()}flush(){for(;this._i<this._tasks.length;)this._tasks[this._i]()||this._i++;this.clear()}clear(){this._idleCallback&&(this._cancelCallback(this._idleCallback),this._idleCallback=void 0),this._i=0,this._tasks.length=0}_start(){this._idleCallback||(this._idleCallback=this._requestCallback(this._process.bind(this)))}_process(S){this._idleCallback=void 0;let w=0,y=0,c=S.timeRemaining(),p=0;for(;this._i<this._tasks.length;){if(w=Date.now(),this._tasks[this._i]()||this._i++,w=Math.max(1,Date.now()-w),y=Math.max(w,y),p=S.timeRemaining(),1.5*y>p)return c-w<-20&&console.warn(`task queue exceeded allotted deadline by ${Math.abs(Math.round(c-w))}ms`),void this._start();c=p}this.clear()}}class h extends f{_requestCallback(S){return setTimeout((()=>S(this._createDeadline(16))))}_cancelCallback(S){clearTimeout(S)}_createDeadline(S){const w=Date.now()+S;return{timeRemaining:()=>Math.max(0,w-Date.now())}}}n.PriorityTaskQueue=h,n.IdleTaskQueue=!d.isNode&&"requestIdleCallback"in window?class extends f{_requestCallback(_){return requestIdleCallback(_)}_cancelCallback(_){cancelIdleCallback(_)}}:h,n.DebouncedIdleTask=class{constructor(){this._queue=new n.IdleTaskQueue}set(_){this._queue.clear(),this._queue.enqueue(_)}flush(){this._queue.flush()}}},9282:(b,n,o)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.updateWindowsModeWrappedState=void 0;const d=o(643);n.updateWindowsModeWrappedState=function(f){const h=f.buffer.lines.get(f.buffer.ybase+f.buffer.y-1),_=h==null?void 0:h.get(f.cols-1),S=f.buffer.lines.get(f.buffer.ybase+f.buffer.y);S&&_&&(S.isWrapped=_[d.CHAR_DATA_CODE_INDEX]!==d.NULL_CELL_CODE&&_[d.CHAR_DATA_CODE_INDEX]!==d.WHITESPACE_CELL_CODE)}},3734:(b,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.ExtendedAttrs=n.AttributeData=void 0;class o{constructor(){this.fg=0,this.bg=0,this.extended=new d}static toColorRGB(h){return[h>>>16&255,h>>>8&255,255&h]}static fromColorRGB(h){return(255&h[0])<<16|(255&h[1])<<8|255&h[2]}clone(){const h=new o;return h.fg=this.fg,h.bg=this.bg,h.extended=this.extended.clone(),h}isInverse(){return 67108864&this.fg}isBold(){return 134217728&this.fg}isUnderline(){return this.hasExtendedAttrs()&&this.extended.underlineStyle!==0?1:268435456&this.fg}isBlink(){return 536870912&this.fg}isInvisible(){return 1073741824&this.fg}isItalic(){return 67108864&this.bg}isDim(){return 134217728&this.bg}isStrikethrough(){return 2147483648&this.fg}isProtected(){return 536870912&this.bg}isOverline(){return 1073741824&this.bg}getFgColorMode(){return 50331648&this.fg}getBgColorMode(){return 50331648&this.bg}isFgRGB(){return(50331648&this.fg)==50331648}isBgRGB(){return(50331648&this.bg)==50331648}isFgPalette(){return(50331648&this.fg)==16777216||(50331648&this.fg)==33554432}isBgPalette(){return(50331648&this.bg)==16777216||(50331648&this.bg)==33554432}isFgDefault(){return(50331648&this.fg)==0}isBgDefault(){return(50331648&this.bg)==0}isAttributeDefault(){return this.fg===0&&this.bg===0}getFgColor(){switch(50331648&this.fg){case 16777216:case 33554432:return 255&this.fg;case 50331648:return 16777215&this.fg;default:return-1}}getBgColor(){switch(50331648&this.bg){case 16777216:case 33554432:return 255&this.bg;case 50331648:return 16777215&this.bg;default:return-1}}hasExtendedAttrs(){return 268435456&this.bg}updateExtended(){this.extended.isEmpty()?this.bg&=-268435457:this.bg|=268435456}getUnderlineColor(){if(268435456&this.bg&&~this.extended.underlineColor)switch(50331648&this.extended.underlineColor){case 16777216:case 33554432:return 255&this.extended.underlineColor;case 50331648:return 16777215&this.extended.underlineColor;default:return this.getFgColor()}return this.getFgColor()}getUnderlineColorMode(){return 268435456&this.bg&&~this.extended.underlineColor?50331648&this.extended.underlineColor:this.getFgColorMode()}isUnderlineColorRGB(){return 268435456&this.bg&&~this.extended.underlineColor?(50331648&this.extended.underlineColor)==50331648:this.isFgRGB()}isUnderlineColorPalette(){return 268435456&this.bg&&~this.extended.underlineColor?(50331648&this.extended.underlineColor)==16777216||(50331648&this.extended.underlineColor)==33554432:this.isFgPalette()}isUnderlineColorDefault(){return 268435456&this.bg&&~this.extended.underlineColor?(50331648&this.extended.underlineColor)==0:this.isFgDefault()}getUnderlineStyle(){return 268435456&this.fg?268435456&this.bg?this.extended.underlineStyle:1:0}getUnderlineVariantOffset(){return this.extended.underlineVariantOffset}}n.AttributeData=o;class d{get ext(){return this._urlId?-469762049&this._ext|this.underlineStyle<<26:this._ext}set ext(h){this._ext=h}get underlineStyle(){return this._urlId?5:(469762048&this._ext)>>26}set underlineStyle(h){this._ext&=-469762049,this._ext|=h<<26&469762048}get underlineColor(){return 67108863&this._ext}set underlineColor(h){this._ext&=-67108864,this._ext|=67108863&h}get urlId(){return this._urlId}set urlId(h){this._urlId=h}get underlineVariantOffset(){const h=(3758096384&this._ext)>>29;return h<0?4294967288^h:h}set underlineVariantOffset(h){this._ext&=536870911,this._ext|=h<<29&3758096384}constructor(h=0,_=0){this._ext=0,this._urlId=0,this._ext=h,this._urlId=_}clone(){return new d(this._ext,this._urlId)}isEmpty(){return this.underlineStyle===0&&this._urlId===0}}n.ExtendedAttrs=d},9092:(b,n,o)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.Buffer=n.MAX_BUFFER_SIZE=void 0;const d=o(6349),f=o(7226),h=o(3734),_=o(8437),S=o(4634),w=o(511),y=o(643),c=o(4863),p=o(7116);n.MAX_BUFFER_SIZE=4294967295,n.Buffer=class{constructor(l,u,m){this._hasScrollback=l,this._optionsService=u,this._bufferService=m,this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.tabs={},this.savedY=0,this.savedX=0,this.savedCurAttrData=_.DEFAULT_ATTR_DATA.clone(),this.savedCharset=p.DEFAULT_CHARSET,this.markers=[],this._nullCell=w.CellData.fromCharData([0,y.NULL_CELL_CHAR,y.NULL_CELL_WIDTH,y.NULL_CELL_CODE]),this._whitespaceCell=w.CellData.fromCharData([0,y.WHITESPACE_CELL_CHAR,y.WHITESPACE_CELL_WIDTH,y.WHITESPACE_CELL_CODE]),this._isClearing=!1,this._memoryCleanupQueue=new f.IdleTaskQueue,this._memoryCleanupPosition=0,this._cols=this._bufferService.cols,this._rows=this._bufferService.rows,this.lines=new d.CircularList(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}getNullCell(l){return l?(this._nullCell.fg=l.fg,this._nullCell.bg=l.bg,this._nullCell.extended=l.extended):(this._nullCell.fg=0,this._nullCell.bg=0,this._nullCell.extended=new h.ExtendedAttrs),this._nullCell}getWhitespaceCell(l){return l?(this._whitespaceCell.fg=l.fg,this._whitespaceCell.bg=l.bg,this._whitespaceCell.extended=l.extended):(this._whitespaceCell.fg=0,this._whitespaceCell.bg=0,this._whitespaceCell.extended=new h.ExtendedAttrs),this._whitespaceCell}getBlankLine(l,u){return new _.BufferLine(this._bufferService.cols,this.getNullCell(l),u)}get hasScrollback(){return this._hasScrollback&&this.lines.maxLength>this._rows}get isCursorInViewport(){const l=this.ybase+this.y-this.ydisp;return l>=0&&l<this._rows}_getCorrectBufferLength(l){if(!this._hasScrollback)return l;const u=l+this._optionsService.rawOptions.scrollback;return u>n.MAX_BUFFER_SIZE?n.MAX_BUFFER_SIZE:u}fillViewportRows(l){if(this.lines.length===0){l===void 0&&(l=_.DEFAULT_ATTR_DATA);let u=this._rows;for(;u--;)this.lines.push(this.getBlankLine(l))}}clear(){this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.lines=new d.CircularList(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}resize(l,u){const m=this.getNullCell(_.DEFAULT_ATTR_DATA);let x=0;const v=this._getCorrectBufferLength(u);if(v>this.lines.maxLength&&(this.lines.maxLength=v),this.lines.length>0){if(this._cols<l)for(let E=0;E<this.lines.length;E++)x+=+this.lines.get(E).resize(l,m);let k=0;if(this._rows<u)for(let E=this._rows;E<u;E++)this.lines.length<u+this.ybase&&(this._optionsService.rawOptions.windowsMode||this._optionsService.rawOptions.windowsPty.backend!==void 0||this._optionsService.rawOptions.windowsPty.buildNumber!==void 0?this.lines.push(new _.BufferLine(l,m)):this.ybase>0&&this.lines.length<=this.ybase+this.y+k+1?(this.ybase--,k++,this.ydisp>0&&this.ydisp--):this.lines.push(new _.BufferLine(l,m)));else for(let E=this._rows;E>u;E--)this.lines.length>u+this.ybase&&(this.lines.length>this.ybase+this.y+1?this.lines.pop():(this.ybase++,this.ydisp++));if(v<this.lines.maxLength){const E=this.lines.length-v;E>0&&(this.lines.trimStart(E),this.ybase=Math.max(this.ybase-E,0),this.ydisp=Math.max(this.ydisp-E,0),this.savedY=Math.max(this.savedY-E,0)),this.lines.maxLength=v}this.x=Math.min(this.x,l-1),this.y=Math.min(this.y,u-1),k&&(this.y+=k),this.savedX=Math.min(this.savedX,l-1),this.scrollTop=0}if(this.scrollBottom=u-1,this._isReflowEnabled&&(this._reflow(l,u),this._cols>l))for(let k=0;k<this.lines.length;k++)x+=+this.lines.get(k).resize(l,m);this._cols=l,this._rows=u,this._memoryCleanupQueue.clear(),x>.1*this.lines.length&&(this._memoryCleanupPosition=0,this._memoryCleanupQueue.enqueue((()=>this._batchedMemoryCleanup())))}_batchedMemoryCleanup(){let l=!0;this._memoryCleanupPosition>=this.lines.length&&(this._memoryCleanupPosition=0,l=!1);let u=0;for(;this._memoryCleanupPosition<this.lines.length;)if(u+=this.lines.get(this._memoryCleanupPosition++).cleanupMemory(),u>100)return!0;return l}get _isReflowEnabled(){const l=this._optionsService.rawOptions.windowsPty;return l&&l.buildNumber?this._hasScrollback&&l.backend==="conpty"&&l.buildNumber>=21376:this._hasScrollback&&!this._optionsService.rawOptions.windowsMode}_reflow(l,u){this._cols!==l&&(l>this._cols?this._reflowLarger(l,u):this._reflowSmaller(l,u))}_reflowLarger(l,u){const m=(0,S.reflowLargerGetLinesToRemove)(this.lines,this._cols,l,this.ybase+this.y,this.getNullCell(_.DEFAULT_ATTR_DATA));if(m.length>0){const x=(0,S.reflowLargerCreateNewLayout)(this.lines,m);(0,S.reflowLargerApplyNewLayout)(this.lines,x.layout),this._reflowLargerAdjustViewport(l,u,x.countRemoved)}}_reflowLargerAdjustViewport(l,u,m){const x=this.getNullCell(_.DEFAULT_ATTR_DATA);let v=m;for(;v-- >0;)this.ybase===0?(this.y>0&&this.y--,this.lines.length<u&&this.lines.push(new _.BufferLine(l,x))):(this.ydisp===this.ybase&&this.ydisp--,this.ybase--);this.savedY=Math.max(this.savedY-m,0)}_reflowSmaller(l,u){const m=this.getNullCell(_.DEFAULT_ATTR_DATA),x=[];let v=0;for(let k=this.lines.length-1;k>=0;k--){let E=this.lines.get(k);if(!E||!E.isWrapped&&E.getTrimmedLength()<=l)continue;const C=[E];for(;E.isWrapped&&k>0;)E=this.lines.get(--k),C.unshift(E);const N=this.ybase+this.y;if(N>=k&&N<k+C.length)continue;const R=C[C.length-1].getTrimmedLength(),B=(0,S.reflowSmallerGetNewLineLengths)(C,this._cols,l),A=B.length-C.length;let F;F=this.ybase===0&&this.y!==this.lines.length-1?Math.max(0,this.y-this.lines.maxLength+A):Math.max(0,this.lines.length-this.lines.maxLength+A);const M=[];for(let P=0;P<A;P++){const j=this.getBlankLine(_.DEFAULT_ATTR_DATA,!0);M.push(j)}M.length>0&&(x.push({start:k+C.length+v,newLines:M}),v+=M.length),C.push(...M);let H=B.length-1,z=B[H];z===0&&(H--,z=B[H]);let G=C.length-A-1,T=R;for(;G>=0;){const P=Math.min(T,z);if(C[H]===void 0)break;if(C[H].copyCellsFrom(C[G],T-P,z-P,P,!0),z-=P,z===0&&(H--,z=B[H]),T-=P,T===0){G--;const j=Math.max(G,0);T=(0,S.getWrappedLineTrimmedLength)(C,j,this._cols)}}for(let P=0;P<C.length;P++)B[P]<l&&C[P].setCell(B[P],m);let D=A-F;for(;D-- >0;)this.ybase===0?this.y<u-1?(this.y++,this.lines.pop()):(this.ybase++,this.ydisp++):this.ybase<Math.min(this.lines.maxLength,this.lines.length+v)-u&&(this.ybase===this.ydisp&&this.ydisp++,this.ybase++);this.savedY=Math.min(this.savedY+A,this.ybase+u-1)}if(x.length>0){const k=[],E=[];for(let H=0;H<this.lines.length;H++)E.push(this.lines.get(H));const C=this.lines.length;let N=C-1,R=0,B=x[R];this.lines.length=Math.min(this.lines.maxLength,this.lines.length+v);let A=0;for(let H=Math.min(this.lines.maxLength-1,C+v-1);H>=0;H--)if(B&&B.start>N+A){for(let z=B.newLines.length-1;z>=0;z--)this.lines.set(H--,B.newLines[z]);H++,k.push({index:N+1,amount:B.newLines.length}),A+=B.newLines.length,B=x[++R]}else this.lines.set(H,E[N--]);let F=0;for(let H=k.length-1;H>=0;H--)k[H].index+=F,this.lines.onInsertEmitter.fire(k[H]),F+=k[H].amount;const M=Math.max(0,C+v-this.lines.maxLength);M>0&&this.lines.onTrimEmitter.fire(M)}}translateBufferLineToString(l,u,m=0,x){const v=this.lines.get(l);return v?v.translateToString(u,m,x):""}getWrappedRangeForLine(l){let u=l,m=l;for(;u>0&&this.lines.get(u).isWrapped;)u--;for(;m+1<this.lines.length&&this.lines.get(m+1).isWrapped;)m++;return{first:u,last:m}}setupTabStops(l){for(l!=null?this.tabs[l]||(l=this.prevStop(l)):(this.tabs={},l=0);l<this._cols;l+=this._optionsService.rawOptions.tabStopWidth)this.tabs[l]=!0}prevStop(l){for(l==null&&(l=this.x);!this.tabs[--l]&&l>0;);return l>=this._cols?this._cols-1:l<0?0:l}nextStop(l){for(l==null&&(l=this.x);!this.tabs[++l]&&l<this._cols;);return l>=this._cols?this._cols-1:l<0?0:l}clearMarkers(l){this._isClearing=!0;for(let u=0;u<this.markers.length;u++)this.markers[u].line===l&&(this.markers[u].dispose(),this.markers.splice(u--,1));this._isClearing=!1}clearAllMarkers(){this._isClearing=!0;for(let l=0;l<this.markers.length;l++)this.markers[l].dispose(),this.markers.splice(l--,1);this._isClearing=!1}addMarker(l){const u=new c.Marker(l);return this.markers.push(u),u.register(this.lines.onTrim((m=>{u.line-=m,u.line<0&&u.dispose()}))),u.register(this.lines.onInsert((m=>{u.line>=m.index&&(u.line+=m.amount)}))),u.register(this.lines.onDelete((m=>{u.line>=m.index&&u.line<m.index+m.amount&&u.dispose(),u.line>m.index&&(u.line-=m.amount)}))),u.register(u.onDispose((()=>this._removeMarker(u)))),u}_removeMarker(l){this._isClearing||this.markers.splice(this.markers.indexOf(l),1)}}},8437:(b,n,o)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.BufferLine=n.DEFAULT_ATTR_DATA=void 0;const d=o(3734),f=o(511),h=o(643),_=o(482);n.DEFAULT_ATTR_DATA=Object.freeze(new d.AttributeData);let S=0;class w{constructor(c,p,l=!1){this.isWrapped=l,this._combined={},this._extendedAttrs={},this._data=new Uint32Array(3*c);const u=p||f.CellData.fromCharData([0,h.NULL_CELL_CHAR,h.NULL_CELL_WIDTH,h.NULL_CELL_CODE]);for(let m=0;m<c;++m)this.setCell(m,u);this.length=c}get(c){const p=this._data[3*c+0],l=2097151&p;return[this._data[3*c+1],2097152&p?this._combined[c]:l?(0,_.stringFromCodePoint)(l):"",p>>22,2097152&p?this._combined[c].charCodeAt(this._combined[c].length-1):l]}set(c,p){this._data[3*c+1]=p[h.CHAR_DATA_ATTR_INDEX],p[h.CHAR_DATA_CHAR_INDEX].length>1?(this._combined[c]=p[1],this._data[3*c+0]=2097152|c|p[h.CHAR_DATA_WIDTH_INDEX]<<22):this._data[3*c+0]=p[h.CHAR_DATA_CHAR_INDEX].charCodeAt(0)|p[h.CHAR_DATA_WIDTH_INDEX]<<22}getWidth(c){return this._data[3*c+0]>>22}hasWidth(c){return 12582912&this._data[3*c+0]}getFg(c){return this._data[3*c+1]}getBg(c){return this._data[3*c+2]}hasContent(c){return 4194303&this._data[3*c+0]}getCodePoint(c){const p=this._data[3*c+0];return 2097152&p?this._combined[c].charCodeAt(this._combined[c].length-1):2097151&p}isCombined(c){return 2097152&this._data[3*c+0]}getString(c){const p=this._data[3*c+0];return 2097152&p?this._combined[c]:2097151&p?(0,_.stringFromCodePoint)(2097151&p):""}isProtected(c){return 536870912&this._data[3*c+2]}loadCell(c,p){return S=3*c,p.content=this._data[S+0],p.fg=this._data[S+1],p.bg=this._data[S+2],2097152&p.content&&(p.combinedData=this._combined[c]),268435456&p.bg&&(p.extended=this._extendedAttrs[c]),p}setCell(c,p){2097152&p.content&&(this._combined[c]=p.combinedData),268435456&p.bg&&(this._extendedAttrs[c]=p.extended),this._data[3*c+0]=p.content,this._data[3*c+1]=p.fg,this._data[3*c+2]=p.bg}setCellFromCodepoint(c,p,l,u){268435456&u.bg&&(this._extendedAttrs[c]=u.extended),this._data[3*c+0]=p|l<<22,this._data[3*c+1]=u.fg,this._data[3*c+2]=u.bg}addCodepointToCell(c,p,l){let u=this._data[3*c+0];2097152&u?this._combined[c]+=(0,_.stringFromCodePoint)(p):2097151&u?(this._combined[c]=(0,_.stringFromCodePoint)(2097151&u)+(0,_.stringFromCodePoint)(p),u&=-2097152,u|=2097152):u=p|4194304,l&&(u&=-12582913,u|=l<<22),this._data[3*c+0]=u}insertCells(c,p,l){if((c%=this.length)&&this.getWidth(c-1)===2&&this.setCellFromCodepoint(c-1,0,1,l),p<this.length-c){const u=new f.CellData;for(let m=this.length-c-p-1;m>=0;--m)this.setCell(c+p+m,this.loadCell(c+m,u));for(let m=0;m<p;++m)this.setCell(c+m,l)}else for(let u=c;u<this.length;++u)this.setCell(u,l);this.getWidth(this.length-1)===2&&this.setCellFromCodepoint(this.length-1,0,1,l)}deleteCells(c,p,l){if(c%=this.length,p<this.length-c){const u=new f.CellData;for(let m=0;m<this.length-c-p;++m)this.setCell(c+m,this.loadCell(c+p+m,u));for(let m=this.length-p;m<this.length;++m)this.setCell(m,l)}else for(let u=c;u<this.length;++u)this.setCell(u,l);c&&this.getWidth(c-1)===2&&this.setCellFromCodepoint(c-1,0,1,l),this.getWidth(c)!==0||this.hasContent(c)||this.setCellFromCodepoint(c,0,1,l)}replaceCells(c,p,l,u=!1){if(u)for(c&&this.getWidth(c-1)===2&&!this.isProtected(c-1)&&this.setCellFromCodepoint(c-1,0,1,l),p<this.length&&this.getWidth(p-1)===2&&!this.isProtected(p)&&this.setCellFromCodepoint(p,0,1,l);c<p&&c<this.length;)this.isProtected(c)||this.setCell(c,l),c++;else for(c&&this.getWidth(c-1)===2&&this.setCellFromCodepoint(c-1,0,1,l),p<this.length&&this.getWidth(p-1)===2&&this.setCellFromCodepoint(p,0,1,l);c<p&&c<this.length;)this.setCell(c++,l)}resize(c,p){if(c===this.length)return 4*this._data.length*2<this._data.buffer.byteLength;const l=3*c;if(c>this.length){if(this._data.buffer.byteLength>=4*l)this._data=new Uint32Array(this._data.buffer,0,l);else{const u=new Uint32Array(l);u.set(this._data),this._data=u}for(let u=this.length;u<c;++u)this.setCell(u,p)}else{this._data=this._data.subarray(0,l);const u=Object.keys(this._combined);for(let x=0;x<u.length;x++){const v=parseInt(u[x],10);v>=c&&delete this._combined[v]}const m=Object.keys(this._extendedAttrs);for(let x=0;x<m.length;x++){const v=parseInt(m[x],10);v>=c&&delete this._extendedAttrs[v]}}return this.length=c,4*l*2<this._data.buffer.byteLength}cleanupMemory(){if(4*this._data.length*2<this._data.buffer.byteLength){const c=new Uint32Array(this._data.length);return c.set(this._data),this._data=c,1}return 0}fill(c,p=!1){if(p)for(let l=0;l<this.length;++l)this.isProtected(l)||this.setCell(l,c);else{this._combined={},this._extendedAttrs={};for(let l=0;l<this.length;++l)this.setCell(l,c)}}copyFrom(c){this.length!==c.length?this._data=new Uint32Array(c._data):this._data.set(c._data),this.length=c.length,this._combined={};for(const p in c._combined)this._combined[p]=c._combined[p];this._extendedAttrs={};for(const p in c._extendedAttrs)this._extendedAttrs[p]=c._extendedAttrs[p];this.isWrapped=c.isWrapped}clone(){const c=new w(0);c._data=new Uint32Array(this._data),c.length=this.length;for(const p in this._combined)c._combined[p]=this._combined[p];for(const p in this._extendedAttrs)c._extendedAttrs[p]=this._extendedAttrs[p];return c.isWrapped=this.isWrapped,c}getTrimmedLength(){for(let c=this.length-1;c>=0;--c)if(4194303&this._data[3*c+0])return c+(this._data[3*c+0]>>22);return 0}getNoBgTrimmedLength(){for(let c=this.length-1;c>=0;--c)if(4194303&this._data[3*c+0]||50331648&this._data[3*c+2])return c+(this._data[3*c+0]>>22);return 0}copyCellsFrom(c,p,l,u,m){const x=c._data;if(m)for(let k=u-1;k>=0;k--){for(let E=0;E<3;E++)this._data[3*(l+k)+E]=x[3*(p+k)+E];268435456&x[3*(p+k)+2]&&(this._extendedAttrs[l+k]=c._extendedAttrs[p+k])}else for(let k=0;k<u;k++){for(let E=0;E<3;E++)this._data[3*(l+k)+E]=x[3*(p+k)+E];268435456&x[3*(p+k)+2]&&(this._extendedAttrs[l+k]=c._extendedAttrs[p+k])}const v=Object.keys(c._combined);for(let k=0;k<v.length;k++){const E=parseInt(v[k],10);E>=p&&(this._combined[E-p+l]=c._combined[E])}}translateToString(c,p,l,u){p=p??0,l=l??this.length,c&&(l=Math.min(l,this.getTrimmedLength())),u&&(u.length=0);let m="";for(;p<l;){const x=this._data[3*p+0],v=2097151&x,k=2097152&x?this._combined[p]:v?(0,_.stringFromCodePoint)(v):h.WHITESPACE_CELL_CHAR;if(m+=k,u)for(let E=0;E<k.length;++E)u.push(p);p+=x>>22||1}return u&&u.push(p),m}}n.BufferLine=w},4841:(b,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.getRangeLength=void 0,n.getRangeLength=function(o,d){if(o.start.y>o.end.y)throw new Error(`Buffer range end (${o.end.x}, ${o.end.y}) cannot be before start (${o.start.x}, ${o.start.y})`);return d*(o.end.y-o.start.y)+(o.end.x-o.start.x+1)}},4634:(b,n)=>{function o(d,f,h){if(f===d.length-1)return d[f].getTrimmedLength();const _=!d[f].hasContent(h-1)&&d[f].getWidth(h-1)===1,S=d[f+1].getWidth(0)===2;return _&&S?h-1:h}Object.defineProperty(n,"__esModule",{value:!0}),n.getWrappedLineTrimmedLength=n.reflowSmallerGetNewLineLengths=n.reflowLargerApplyNewLayout=n.reflowLargerCreateNewLayout=n.reflowLargerGetLinesToRemove=void 0,n.reflowLargerGetLinesToRemove=function(d,f,h,_,S){const w=[];for(let y=0;y<d.length-1;y++){let c=y,p=d.get(++c);if(!p.isWrapped)continue;const l=[d.get(y)];for(;c<d.length&&p.isWrapped;)l.push(p),p=d.get(++c);if(_>=y&&_<c){y+=l.length-1;continue}let u=0,m=o(l,u,f),x=1,v=0;for(;x<l.length;){const E=o(l,x,f),C=E-v,N=h-m,R=Math.min(C,N);l[u].copyCellsFrom(l[x],v,m,R,!1),m+=R,m===h&&(u++,m=0),v+=R,v===E&&(x++,v=0),m===0&&u!==0&&l[u-1].getWidth(h-1)===2&&(l[u].copyCellsFrom(l[u-1],h-1,m++,1,!1),l[u-1].setCell(h-1,S))}l[u].replaceCells(m,h,S);let k=0;for(let E=l.length-1;E>0&&(E>u||l[E].getTrimmedLength()===0);E--)k++;k>0&&(w.push(y+l.length-k),w.push(k)),y+=l.length-1}return w},n.reflowLargerCreateNewLayout=function(d,f){const h=[];let _=0,S=f[_],w=0;for(let y=0;y<d.length;y++)if(S===y){const c=f[++_];d.onDeleteEmitter.fire({index:y-w,amount:c}),y+=c-1,w+=c,S=f[++_]}else h.push(y);return{layout:h,countRemoved:w}},n.reflowLargerApplyNewLayout=function(d,f){const h=[];for(let _=0;_<f.length;_++)h.push(d.get(f[_]));for(let _=0;_<h.length;_++)d.set(_,h[_]);d.length=f.length},n.reflowSmallerGetNewLineLengths=function(d,f,h){const _=[],S=d.map(((p,l)=>o(d,l,f))).reduce(((p,l)=>p+l));let w=0,y=0,c=0;for(;c<S;){if(S-c<h){_.push(S-c);break}w+=h;const p=o(d,y,f);w>p&&(w-=p,y++);const l=d[y].getWidth(w-1)===2;l&&w--;const u=l?h-1:h;_.push(u),c+=u}return _},n.getWrappedLineTrimmedLength=o},5295:(b,n,o)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.BufferSet=void 0;const d=o(8460),f=o(844),h=o(9092);class _ extends f.Disposable{constructor(w,y){super(),this._optionsService=w,this._bufferService=y,this._onBufferActivate=this.register(new d.EventEmitter),this.onBufferActivate=this._onBufferActivate.event,this.reset(),this.register(this._optionsService.onSpecificOptionChange("scrollback",(()=>this.resize(this._bufferService.cols,this._bufferService.rows)))),this.register(this._optionsService.onSpecificOptionChange("tabStopWidth",(()=>this.setupTabStops())))}reset(){this._normal=new h.Buffer(!0,this._optionsService,this._bufferService),this._normal.fillViewportRows(),this._alt=new h.Buffer(!1,this._optionsService,this._bufferService),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}),this.setupTabStops()}get alt(){return this._alt}get active(){return this._activeBuffer}get normal(){return this._normal}activateNormalBuffer(){this._activeBuffer!==this._normal&&(this._normal.x=this._alt.x,this._normal.y=this._alt.y,this._alt.clearAllMarkers(),this._alt.clear(),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}))}activateAltBuffer(w){this._activeBuffer!==this._alt&&(this._alt.fillViewportRows(w),this._alt.x=this._normal.x,this._alt.y=this._normal.y,this._activeBuffer=this._alt,this._onBufferActivate.fire({activeBuffer:this._alt,inactiveBuffer:this._normal}))}resize(w,y){this._normal.resize(w,y),this._alt.resize(w,y),this.setupTabStops(w)}setupTabStops(w){this._normal.setupTabStops(w),this._alt.setupTabStops(w)}}n.BufferSet=_},511:(b,n,o)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.CellData=void 0;const d=o(482),f=o(643),h=o(3734);class _ extends h.AttributeData{constructor(){super(...arguments),this.content=0,this.fg=0,this.bg=0,this.extended=new h.ExtendedAttrs,this.combinedData=""}static fromCharData(w){const y=new _;return y.setFromCharData(w),y}isCombined(){return 2097152&this.content}getWidth(){return this.content>>22}getChars(){return 2097152&this.content?this.combinedData:2097151&this.content?(0,d.stringFromCodePoint)(2097151&this.content):""}getCode(){return this.isCombined()?this.combinedData.charCodeAt(this.combinedData.length-1):2097151&this.content}setFromCharData(w){this.fg=w[f.CHAR_DATA_ATTR_INDEX],this.bg=0;let y=!1;if(w[f.CHAR_DATA_CHAR_INDEX].length>2)y=!0;else if(w[f.CHAR_DATA_CHAR_INDEX].length===2){const c=w[f.CHAR_DATA_CHAR_INDEX].charCodeAt(0);if(55296<=c&&c<=56319){const p=w[f.CHAR_DATA_CHAR_INDEX].charCodeAt(1);56320<=p&&p<=57343?this.content=1024*(c-55296)+p-56320+65536|w[f.CHAR_DATA_WIDTH_INDEX]<<22:y=!0}else y=!0}else this.content=w[f.CHAR_DATA_CHAR_INDEX].charCodeAt(0)|w[f.CHAR_DATA_WIDTH_INDEX]<<22;y&&(this.combinedData=w[f.CHAR_DATA_CHAR_INDEX],this.content=2097152|w[f.CHAR_DATA_WIDTH_INDEX]<<22)}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}}n.CellData=_},643:(b,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.WHITESPACE_CELL_CODE=n.WHITESPACE_CELL_WIDTH=n.WHITESPACE_CELL_CHAR=n.NULL_CELL_CODE=n.NULL_CELL_WIDTH=n.NULL_CELL_CHAR=n.CHAR_DATA_CODE_INDEX=n.CHAR_DATA_WIDTH_INDEX=n.CHAR_DATA_CHAR_INDEX=n.CHAR_DATA_ATTR_INDEX=n.DEFAULT_EXT=n.DEFAULT_ATTR=n.DEFAULT_COLOR=void 0,n.DEFAULT_COLOR=0,n.DEFAULT_ATTR=256|n.DEFAULT_COLOR<<9,n.DEFAULT_EXT=0,n.CHAR_DATA_ATTR_INDEX=0,n.CHAR_DATA_CHAR_INDEX=1,n.CHAR_DATA_WIDTH_INDEX=2,n.CHAR_DATA_CODE_INDEX=3,n.NULL_CELL_CHAR="",n.NULL_CELL_WIDTH=1,n.NULL_CELL_CODE=0,n.WHITESPACE_CELL_CHAR=" ",n.WHITESPACE_CELL_WIDTH=1,n.WHITESPACE_CELL_CODE=32},4863:(b,n,o)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.Marker=void 0;const d=o(8460),f=o(844);class h{get id(){return this._id}constructor(S){this.line=S,this.isDisposed=!1,this._disposables=[],this._id=h._nextId++,this._onDispose=this.register(new d.EventEmitter),this.onDispose=this._onDispose.event}dispose(){this.isDisposed||(this.isDisposed=!0,this.line=-1,this._onDispose.fire(),(0,f.disposeArray)(this._disposables),this._disposables.length=0)}register(S){return this._disposables.push(S),S}}n.Marker=h,h._nextId=1},7116:(b,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.DEFAULT_CHARSET=n.CHARSETS=void 0,n.CHARSETS={},n.DEFAULT_CHARSET=n.CHARSETS.B,n.CHARSETS[0]={"`":"◆",a:"▒",b:"␉",c:"␌",d:"␍",e:"␊",f:"°",g:"±",h:"",i:"␋",j:"┘",k:"┐",l:"┌",m:"└",n:"┼",o:"⎺",p:"⎻",q:"─",r:"⎼",s:"⎽",t:"├",u:"┤",v:"┴",w:"┬",x:"│",y:"≤",z:"≥","{":"π","|":"≠","}":"£","~":"·"},n.CHARSETS.A={"#":"£"},n.CHARSETS.B=void 0,n.CHARSETS[4]={"#":"£","@":"¾","[":"ij","\\":"½","]":"|","{":"¨","|":"f","}":"¼","~":"´"},n.CHARSETS.C=n.CHARSETS[5]={"[":"Ä","\\":"Ö","]":"Å","^":"Ü","`":"é","{":"ä","|":"ö","}":"å","~":"ü"},n.CHARSETS.R={"#":"£","@":"à","[":"°","\\":"ç","]":"§","{":"é","|":"ù","}":"è","~":"¨"},n.CHARSETS.Q={"@":"à","[":"â","\\":"ç","]":"ê","^":"î","`":"ô","{":"é","|":"ù","}":"è","~":"û"},n.CHARSETS.K={"@":"§","[":"Ä","\\":"Ö","]":"Ü","{":"ä","|":"ö","}":"ü","~":"ß"},n.CHARSETS.Y={"#":"£","@":"§","[":"°","\\":"ç","]":"é","`":"ù","{":"à","|":"ò","}":"è","~":"ì"},n.CHARSETS.E=n.CHARSETS[6]={"@":"Ä","[":"Æ","\\":"Ø","]":"Å","^":"Ü","`":"ä","{":"æ","|":"ø","}":"å","~":"ü"},n.CHARSETS.Z={"#":"£","@":"§","[":"¡","\\":"Ñ","]":"¿","{":"°","|":"ñ","}":"ç"},n.CHARSETS.H=n.CHARSETS[7]={"@":"É","[":"Ä","\\":"Ö","]":"Å","^":"Ü","`":"é","{":"ä","|":"ö","}":"å","~":"ü"},n.CHARSETS["="]={"#":"ù","@":"à","[":"é","\\":"ç","]":"ê","^":"î",_:"è","`":"ô","{":"ä","|":"ö","}":"ü","~":"û"}},2584:(b,n)=>{var o,d,f;Object.defineProperty(n,"__esModule",{value:!0}),n.C1_ESCAPED=n.C1=n.C0=void 0,(function(h){h.NUL="\0",h.SOH="",h.STX="",h.ETX="",h.EOT="",h.ENQ="",h.ACK="",h.BEL="\x07",h.BS="\b",h.HT=" ",h.LF=`
|
|
404
404
|
`,h.VT="\v",h.FF="\f",h.CR="\r",h.SO="",h.SI="",h.DLE="",h.DC1="",h.DC2="",h.DC3="",h.DC4="",h.NAK="",h.SYN="",h.ETB="",h.CAN="",h.EM="",h.SUB="",h.ESC="\x1B",h.FS="",h.GS="",h.RS="",h.US="",h.SP=" ",h.DEL=""})(o||(n.C0=o={})),(function(h){h.PAD="",h.HOP="",h.BPH="",h.NBH="",h.IND="",h.NEL="
",h.SSA="",h.ESA="",h.HTS="",h.HTJ="",h.VTS="",h.PLD="",h.PLU="",h.RI="",h.SS2="",h.SS3="",h.DCS="",h.PU1="",h.PU2="",h.STS="",h.CCH="",h.MW="",h.SPA="",h.EPA="",h.SOS="",h.SGCI="",h.SCI="",h.CSI="",h.ST="",h.OSC="",h.PM="",h.APC=""})(d||(n.C1=d={})),(function(h){h.ST=`${o.ESC}\\`})(f||(n.C1_ESCAPED=f={}))},7399:(b,n,o)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.evaluateKeyboardEvent=void 0;const d=o(2584),f={48:["0",")"],49:["1","!"],50:["2","@"],51:["3","#"],52:["4","$"],53:["5","%"],54:["6","^"],55:["7","&"],56:["8","*"],57:["9","("],186:[";",":"],187:["=","+"],188:[",","<"],189:["-","_"],190:[".",">"],191:["/","?"],192:["`","~"],219:["[","{"],220:["\\","|"],221:["]","}"],222:["'",'"']};n.evaluateKeyboardEvent=function(h,_,S,w){const y={type:0,cancel:!1,key:void 0},c=(h.shiftKey?1:0)|(h.altKey?2:0)|(h.ctrlKey?4:0)|(h.metaKey?8:0);switch(h.keyCode){case 0:h.key==="UIKeyInputUpArrow"?y.key=_?d.C0.ESC+"OA":d.C0.ESC+"[A":h.key==="UIKeyInputLeftArrow"?y.key=_?d.C0.ESC+"OD":d.C0.ESC+"[D":h.key==="UIKeyInputRightArrow"?y.key=_?d.C0.ESC+"OC":d.C0.ESC+"[C":h.key==="UIKeyInputDownArrow"&&(y.key=_?d.C0.ESC+"OB":d.C0.ESC+"[B");break;case 8:y.key=h.ctrlKey?"\b":d.C0.DEL,h.altKey&&(y.key=d.C0.ESC+y.key);break;case 9:if(h.shiftKey){y.key=d.C0.ESC+"[Z";break}y.key=d.C0.HT,y.cancel=!0;break;case 13:y.key=h.altKey?d.C0.ESC+d.C0.CR:d.C0.CR,y.cancel=!0;break;case 27:y.key=d.C0.ESC,h.altKey&&(y.key=d.C0.ESC+d.C0.ESC),y.cancel=!0;break;case 37:if(h.metaKey)break;c?(y.key=d.C0.ESC+"[1;"+(c+1)+"D",y.key===d.C0.ESC+"[1;3D"&&(y.key=d.C0.ESC+(S?"b":"[1;5D"))):y.key=_?d.C0.ESC+"OD":d.C0.ESC+"[D";break;case 39:if(h.metaKey)break;c?(y.key=d.C0.ESC+"[1;"+(c+1)+"C",y.key===d.C0.ESC+"[1;3C"&&(y.key=d.C0.ESC+(S?"f":"[1;5C"))):y.key=_?d.C0.ESC+"OC":d.C0.ESC+"[C";break;case 38:if(h.metaKey)break;c?(y.key=d.C0.ESC+"[1;"+(c+1)+"A",S||y.key!==d.C0.ESC+"[1;3A"||(y.key=d.C0.ESC+"[1;5A")):y.key=_?d.C0.ESC+"OA":d.C0.ESC+"[A";break;case 40:if(h.metaKey)break;c?(y.key=d.C0.ESC+"[1;"+(c+1)+"B",S||y.key!==d.C0.ESC+"[1;3B"||(y.key=d.C0.ESC+"[1;5B")):y.key=_?d.C0.ESC+"OB":d.C0.ESC+"[B";break;case 45:h.shiftKey||h.ctrlKey||(y.key=d.C0.ESC+"[2~");break;case 46:y.key=c?d.C0.ESC+"[3;"+(c+1)+"~":d.C0.ESC+"[3~";break;case 36:y.key=c?d.C0.ESC+"[1;"+(c+1)+"H":_?d.C0.ESC+"OH":d.C0.ESC+"[H";break;case 35:y.key=c?d.C0.ESC+"[1;"+(c+1)+"F":_?d.C0.ESC+"OF":d.C0.ESC+"[F";break;case 33:h.shiftKey?y.type=2:h.ctrlKey?y.key=d.C0.ESC+"[5;"+(c+1)+"~":y.key=d.C0.ESC+"[5~";break;case 34:h.shiftKey?y.type=3:h.ctrlKey?y.key=d.C0.ESC+"[6;"+(c+1)+"~":y.key=d.C0.ESC+"[6~";break;case 112:y.key=c?d.C0.ESC+"[1;"+(c+1)+"P":d.C0.ESC+"OP";break;case 113:y.key=c?d.C0.ESC+"[1;"+(c+1)+"Q":d.C0.ESC+"OQ";break;case 114:y.key=c?d.C0.ESC+"[1;"+(c+1)+"R":d.C0.ESC+"OR";break;case 115:y.key=c?d.C0.ESC+"[1;"+(c+1)+"S":d.C0.ESC+"OS";break;case 116:y.key=c?d.C0.ESC+"[15;"+(c+1)+"~":d.C0.ESC+"[15~";break;case 117:y.key=c?d.C0.ESC+"[17;"+(c+1)+"~":d.C0.ESC+"[17~";break;case 118:y.key=c?d.C0.ESC+"[18;"+(c+1)+"~":d.C0.ESC+"[18~";break;case 119:y.key=c?d.C0.ESC+"[19;"+(c+1)+"~":d.C0.ESC+"[19~";break;case 120:y.key=c?d.C0.ESC+"[20;"+(c+1)+"~":d.C0.ESC+"[20~";break;case 121:y.key=c?d.C0.ESC+"[21;"+(c+1)+"~":d.C0.ESC+"[21~";break;case 122:y.key=c?d.C0.ESC+"[23;"+(c+1)+"~":d.C0.ESC+"[23~";break;case 123:y.key=c?d.C0.ESC+"[24;"+(c+1)+"~":d.C0.ESC+"[24~";break;default:if(!h.ctrlKey||h.shiftKey||h.altKey||h.metaKey)if(S&&!w||!h.altKey||h.metaKey)!S||h.altKey||h.ctrlKey||h.shiftKey||!h.metaKey?h.key&&!h.ctrlKey&&!h.altKey&&!h.metaKey&&h.keyCode>=48&&h.key.length===1?y.key=h.key:h.key&&h.ctrlKey&&(h.key==="_"&&(y.key=d.C0.US),h.key==="@"&&(y.key=d.C0.NUL)):h.keyCode===65&&(y.type=1);else{const p=f[h.keyCode],l=p==null?void 0:p[h.shiftKey?1:0];if(l)y.key=d.C0.ESC+l;else if(h.keyCode>=65&&h.keyCode<=90){const u=h.ctrlKey?h.keyCode-64:h.keyCode+32;let m=String.fromCharCode(u);h.shiftKey&&(m=m.toUpperCase()),y.key=d.C0.ESC+m}else if(h.keyCode===32)y.key=d.C0.ESC+(h.ctrlKey?d.C0.NUL:" ");else if(h.key==="Dead"&&h.code.startsWith("Key")){let u=h.code.slice(3,4);h.shiftKey||(u=u.toLowerCase()),y.key=d.C0.ESC+u,y.cancel=!0}}else h.keyCode>=65&&h.keyCode<=90?y.key=String.fromCharCode(h.keyCode-64):h.keyCode===32?y.key=d.C0.NUL:h.keyCode>=51&&h.keyCode<=55?y.key=String.fromCharCode(h.keyCode-51+27):h.keyCode===56?y.key=d.C0.DEL:h.keyCode===219?y.key=d.C0.ESC:h.keyCode===220?y.key=d.C0.FS:h.keyCode===221&&(y.key=d.C0.GS)}return y}},482:(b,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.Utf8ToUtf32=n.StringToUtf32=n.utf32ToString=n.stringFromCodePoint=void 0,n.stringFromCodePoint=function(o){return o>65535?(o-=65536,String.fromCharCode(55296+(o>>10))+String.fromCharCode(o%1024+56320)):String.fromCharCode(o)},n.utf32ToString=function(o,d=0,f=o.length){let h="";for(let _=d;_<f;++_){let S=o[_];S>65535?(S-=65536,h+=String.fromCharCode(55296+(S>>10))+String.fromCharCode(S%1024+56320)):h+=String.fromCharCode(S)}return h},n.StringToUtf32=class{constructor(){this._interim=0}clear(){this._interim=0}decode(o,d){const f=o.length;if(!f)return 0;let h=0,_=0;if(this._interim){const S=o.charCodeAt(_++);56320<=S&&S<=57343?d[h++]=1024*(this._interim-55296)+S-56320+65536:(d[h++]=this._interim,d[h++]=S),this._interim=0}for(let S=_;S<f;++S){const w=o.charCodeAt(S);if(55296<=w&&w<=56319){if(++S>=f)return this._interim=w,h;const y=o.charCodeAt(S);56320<=y&&y<=57343?d[h++]=1024*(w-55296)+y-56320+65536:(d[h++]=w,d[h++]=y)}else w!==65279&&(d[h++]=w)}return h}},n.Utf8ToUtf32=class{constructor(){this.interim=new Uint8Array(3)}clear(){this.interim.fill(0)}decode(o,d){const f=o.length;if(!f)return 0;let h,_,S,w,y=0,c=0,p=0;if(this.interim[0]){let m=!1,x=this.interim[0];x&=(224&x)==192?31:(240&x)==224?15:7;let v,k=0;for(;(v=63&this.interim[++k])&&k<4;)x<<=6,x|=v;const E=(224&this.interim[0])==192?2:(240&this.interim[0])==224?3:4,C=E-k;for(;p<C;){if(p>=f)return 0;if(v=o[p++],(192&v)!=128){p--,m=!0;break}this.interim[k++]=v,x<<=6,x|=63&v}m||(E===2?x<128?p--:d[y++]=x:E===3?x<2048||x>=55296&&x<=57343||x===65279||(d[y++]=x):x<65536||x>1114111||(d[y++]=x)),this.interim.fill(0)}const l=f-4;let u=p;for(;u<f;){for(;!(!(u<l)||128&(h=o[u])||128&(_=o[u+1])||128&(S=o[u+2])||128&(w=o[u+3]));)d[y++]=h,d[y++]=_,d[y++]=S,d[y++]=w,u+=4;if(h=o[u++],h<128)d[y++]=h;else if((224&h)==192){if(u>=f)return this.interim[0]=h,y;if(_=o[u++],(192&_)!=128){u--;continue}if(c=(31&h)<<6|63&_,c<128){u--;continue}d[y++]=c}else if((240&h)==224){if(u>=f)return this.interim[0]=h,y;if(_=o[u++],(192&_)!=128){u--;continue}if(u>=f)return this.interim[0]=h,this.interim[1]=_,y;if(S=o[u++],(192&S)!=128){u--;continue}if(c=(15&h)<<12|(63&_)<<6|63&S,c<2048||c>=55296&&c<=57343||c===65279)continue;d[y++]=c}else if((248&h)==240){if(u>=f)return this.interim[0]=h,y;if(_=o[u++],(192&_)!=128){u--;continue}if(u>=f)return this.interim[0]=h,this.interim[1]=_,y;if(S=o[u++],(192&S)!=128){u--;continue}if(u>=f)return this.interim[0]=h,this.interim[1]=_,this.interim[2]=S,y;if(w=o[u++],(192&w)!=128){u--;continue}if(c=(7&h)<<18|(63&_)<<12|(63&S)<<6|63&w,c<65536||c>1114111)continue;d[y++]=c}}return y}}},225:(b,n,o)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.UnicodeV6=void 0;const d=o(1480),f=[[768,879],[1155,1158],[1160,1161],[1425,1469],[1471,1471],[1473,1474],[1476,1477],[1479,1479],[1536,1539],[1552,1557],[1611,1630],[1648,1648],[1750,1764],[1767,1768],[1770,1773],[1807,1807],[1809,1809],[1840,1866],[1958,1968],[2027,2035],[2305,2306],[2364,2364],[2369,2376],[2381,2381],[2385,2388],[2402,2403],[2433,2433],[2492,2492],[2497,2500],[2509,2509],[2530,2531],[2561,2562],[2620,2620],[2625,2626],[2631,2632],[2635,2637],[2672,2673],[2689,2690],[2748,2748],[2753,2757],[2759,2760],[2765,2765],[2786,2787],[2817,2817],[2876,2876],[2879,2879],[2881,2883],[2893,2893],[2902,2902],[2946,2946],[3008,3008],[3021,3021],[3134,3136],[3142,3144],[3146,3149],[3157,3158],[3260,3260],[3263,3263],[3270,3270],[3276,3277],[3298,3299],[3393,3395],[3405,3405],[3530,3530],[3538,3540],[3542,3542],[3633,3633],[3636,3642],[3655,3662],[3761,3761],[3764,3769],[3771,3772],[3784,3789],[3864,3865],[3893,3893],[3895,3895],[3897,3897],[3953,3966],[3968,3972],[3974,3975],[3984,3991],[3993,4028],[4038,4038],[4141,4144],[4146,4146],[4150,4151],[4153,4153],[4184,4185],[4448,4607],[4959,4959],[5906,5908],[5938,5940],[5970,5971],[6002,6003],[6068,6069],[6071,6077],[6086,6086],[6089,6099],[6109,6109],[6155,6157],[6313,6313],[6432,6434],[6439,6440],[6450,6450],[6457,6459],[6679,6680],[6912,6915],[6964,6964],[6966,6970],[6972,6972],[6978,6978],[7019,7027],[7616,7626],[7678,7679],[8203,8207],[8234,8238],[8288,8291],[8298,8303],[8400,8431],[12330,12335],[12441,12442],[43014,43014],[43019,43019],[43045,43046],[64286,64286],[65024,65039],[65056,65059],[65279,65279],[65529,65531]],h=[[68097,68099],[68101,68102],[68108,68111],[68152,68154],[68159,68159],[119143,119145],[119155,119170],[119173,119179],[119210,119213],[119362,119364],[917505,917505],[917536,917631],[917760,917999]];let _;n.UnicodeV6=class{constructor(){if(this.version="6",!_){_=new Uint8Array(65536),_.fill(1),_[0]=0,_.fill(0,1,32),_.fill(0,127,160),_.fill(2,4352,4448),_[9001]=2,_[9002]=2,_.fill(2,11904,42192),_[12351]=1,_.fill(2,44032,55204),_.fill(2,63744,64256),_.fill(2,65040,65050),_.fill(2,65072,65136),_.fill(2,65280,65377),_.fill(2,65504,65511);for(let S=0;S<f.length;++S)_.fill(0,f[S][0],f[S][1]+1)}}wcwidth(S){return S<32?0:S<127?1:S<65536?_[S]:(function(w,y){let c,p=0,l=y.length-1;if(w<y[0][0]||w>y[l][1])return!1;for(;l>=p;)if(c=p+l>>1,w>y[c][1])p=c+1;else{if(!(w<y[c][0]))return!0;l=c-1}return!1})(S,h)?0:S>=131072&&S<=196605||S>=196608&&S<=262141?2:1}charProperties(S,w){let y=this.wcwidth(S),c=y===0&&w!==0;if(c){const p=d.UnicodeService.extractWidth(w);p===0?c=!1:p>y&&(y=p)}return d.UnicodeService.createPropertyValue(0,y,c)}}},5981:(b,n,o)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.WriteBuffer=void 0;const d=o(8460),f=o(844);class h extends f.Disposable{constructor(S){super(),this._action=S,this._writeBuffer=[],this._callbacks=[],this._pendingData=0,this._bufferOffset=0,this._isSyncWriting=!1,this._syncCalls=0,this._didUserInput=!1,this._onWriteParsed=this.register(new d.EventEmitter),this.onWriteParsed=this._onWriteParsed.event}handleUserInput(){this._didUserInput=!0}writeSync(S,w){if(w!==void 0&&this._syncCalls>w)return void(this._syncCalls=0);if(this._pendingData+=S.length,this._writeBuffer.push(S),this._callbacks.push(void 0),this._syncCalls++,this._isSyncWriting)return;let y;for(this._isSyncWriting=!0;y=this._writeBuffer.shift();){this._action(y);const c=this._callbacks.shift();c&&c()}this._pendingData=0,this._bufferOffset=2147483647,this._isSyncWriting=!1,this._syncCalls=0}write(S,w){if(this._pendingData>5e7)throw new Error("write data discarded, use flow control to avoid losing data");if(!this._writeBuffer.length){if(this._bufferOffset=0,this._didUserInput)return this._didUserInput=!1,this._pendingData+=S.length,this._writeBuffer.push(S),this._callbacks.push(w),void this._innerWrite();setTimeout((()=>this._innerWrite()))}this._pendingData+=S.length,this._writeBuffer.push(S),this._callbacks.push(w)}_innerWrite(S=0,w=!0){const y=S||Date.now();for(;this._writeBuffer.length>this._bufferOffset;){const c=this._writeBuffer[this._bufferOffset],p=this._action(c,w);if(p){const u=m=>Date.now()-y>=12?setTimeout((()=>this._innerWrite(0,m))):this._innerWrite(y,m);return void p.catch((m=>(queueMicrotask((()=>{throw m})),Promise.resolve(!1)))).then(u)}const l=this._callbacks[this._bufferOffset];if(l&&l(),this._bufferOffset++,this._pendingData-=c.length,Date.now()-y>=12)break}this._writeBuffer.length>this._bufferOffset?(this._bufferOffset>50&&(this._writeBuffer=this._writeBuffer.slice(this._bufferOffset),this._callbacks=this._callbacks.slice(this._bufferOffset),this._bufferOffset=0),setTimeout((()=>this._innerWrite()))):(this._writeBuffer.length=0,this._callbacks.length=0,this._pendingData=0,this._bufferOffset=0),this._onWriteParsed.fire()}}n.WriteBuffer=h},5941:(b,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.toRgbString=n.parseColor=void 0;const o=/^([\da-f])\/([\da-f])\/([\da-f])$|^([\da-f]{2})\/([\da-f]{2})\/([\da-f]{2})$|^([\da-f]{3})\/([\da-f]{3})\/([\da-f]{3})$|^([\da-f]{4})\/([\da-f]{4})\/([\da-f]{4})$/,d=/^[\da-f]+$/;function f(h,_){const S=h.toString(16),w=S.length<2?"0"+S:S;switch(_){case 4:return S[0];case 8:return w;case 12:return(w+w).slice(0,3);default:return w+w}}n.parseColor=function(h){if(!h)return;let _=h.toLowerCase();if(_.indexOf("rgb:")===0){_=_.slice(4);const S=o.exec(_);if(S){const w=S[1]?15:S[4]?255:S[7]?4095:65535;return[Math.round(parseInt(S[1]||S[4]||S[7]||S[10],16)/w*255),Math.round(parseInt(S[2]||S[5]||S[8]||S[11],16)/w*255),Math.round(parseInt(S[3]||S[6]||S[9]||S[12],16)/w*255)]}}else if(_.indexOf("#")===0&&(_=_.slice(1),d.exec(_)&&[3,6,9,12].includes(_.length))){const S=_.length/3,w=[0,0,0];for(let y=0;y<3;++y){const c=parseInt(_.slice(S*y,S*y+S),16);w[y]=S===1?c<<4:S===2?c:S===3?c>>4:c>>8}return w}},n.toRgbString=function(h,_=16){const[S,w,y]=h;return`rgb:${f(S,_)}/${f(w,_)}/${f(y,_)}`}},5770:(b,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.PAYLOAD_LIMIT=void 0,n.PAYLOAD_LIMIT=1e7},6351:(b,n,o)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.DcsHandler=n.DcsParser=void 0;const d=o(482),f=o(8742),h=o(5770),_=[];n.DcsParser=class{constructor(){this._handlers=Object.create(null),this._active=_,this._ident=0,this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=_}registerHandler(w,y){this._handlers[w]===void 0&&(this._handlers[w]=[]);const c=this._handlers[w];return c.push(y),{dispose:()=>{const p=c.indexOf(y);p!==-1&&c.splice(p,1)}}}clearHandler(w){this._handlers[w]&&delete this._handlers[w]}setHandlerFallback(w){this._handlerFb=w}reset(){if(this._active.length)for(let w=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;w>=0;--w)this._active[w].unhook(!1);this._stack.paused=!1,this._active=_,this._ident=0}hook(w,y){if(this.reset(),this._ident=w,this._active=this._handlers[w]||_,this._active.length)for(let c=this._active.length-1;c>=0;c--)this._active[c].hook(y);else this._handlerFb(this._ident,"HOOK",y)}put(w,y,c){if(this._active.length)for(let p=this._active.length-1;p>=0;p--)this._active[p].put(w,y,c);else this._handlerFb(this._ident,"PUT",(0,d.utf32ToString)(w,y,c))}unhook(w,y=!0){if(this._active.length){let c=!1,p=this._active.length-1,l=!1;if(this._stack.paused&&(p=this._stack.loopPosition-1,c=y,l=this._stack.fallThrough,this._stack.paused=!1),!l&&c===!1){for(;p>=0&&(c=this._active[p].unhook(w),c!==!0);p--)if(c instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=p,this._stack.fallThrough=!1,c;p--}for(;p>=0;p--)if(c=this._active[p].unhook(!1),c instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=p,this._stack.fallThrough=!0,c}else this._handlerFb(this._ident,"UNHOOK",w);this._active=_,this._ident=0}};const S=new f.Params;S.addParam(0),n.DcsHandler=class{constructor(w){this._handler=w,this._data="",this._params=S,this._hitLimit=!1}hook(w){this._params=w.length>1||w.params[0]?w.clone():S,this._data="",this._hitLimit=!1}put(w,y,c){this._hitLimit||(this._data+=(0,d.utf32ToString)(w,y,c),this._data.length>h.PAYLOAD_LIMIT&&(this._data="",this._hitLimit=!0))}unhook(w){let y=!1;if(this._hitLimit)y=!1;else if(w&&(y=this._handler(this._data,this._params),y instanceof Promise))return y.then((c=>(this._params=S,this._data="",this._hitLimit=!1,c)));return this._params=S,this._data="",this._hitLimit=!1,y}}},2015:(b,n,o)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.EscapeSequenceParser=n.VT500_TRANSITION_TABLE=n.TransitionTable=void 0;const d=o(844),f=o(8742),h=o(6242),_=o(6351);class S{constructor(p){this.table=new Uint8Array(p)}setDefault(p,l){this.table.fill(p<<4|l)}add(p,l,u,m){this.table[l<<8|p]=u<<4|m}addMany(p,l,u,m){for(let x=0;x<p.length;x++)this.table[l<<8|p[x]]=u<<4|m}}n.TransitionTable=S;const w=160;n.VT500_TRANSITION_TABLE=(function(){const c=new S(4095),p=Array.apply(null,Array(256)).map(((k,E)=>E)),l=(k,E)=>p.slice(k,E),u=l(32,127),m=l(0,24);m.push(25),m.push.apply(m,l(28,32));const x=l(0,14);let v;for(v in c.setDefault(1,0),c.addMany(u,0,2,0),x)c.addMany([24,26,153,154],v,3,0),c.addMany(l(128,144),v,3,0),c.addMany(l(144,152),v,3,0),c.add(156,v,0,0),c.add(27,v,11,1),c.add(157,v,4,8),c.addMany([152,158,159],v,0,7),c.add(155,v,11,3),c.add(144,v,11,9);return c.addMany(m,0,3,0),c.addMany(m,1,3,1),c.add(127,1,0,1),c.addMany(m,8,0,8),c.addMany(m,3,3,3),c.add(127,3,0,3),c.addMany(m,4,3,4),c.add(127,4,0,4),c.addMany(m,6,3,6),c.addMany(m,5,3,5),c.add(127,5,0,5),c.addMany(m,2,3,2),c.add(127,2,0,2),c.add(93,1,4,8),c.addMany(u,8,5,8),c.add(127,8,5,8),c.addMany([156,27,24,26,7],8,6,0),c.addMany(l(28,32),8,0,8),c.addMany([88,94,95],1,0,7),c.addMany(u,7,0,7),c.addMany(m,7,0,7),c.add(156,7,0,0),c.add(127,7,0,7),c.add(91,1,11,3),c.addMany(l(64,127),3,7,0),c.addMany(l(48,60),3,8,4),c.addMany([60,61,62,63],3,9,4),c.addMany(l(48,60),4,8,4),c.addMany(l(64,127),4,7,0),c.addMany([60,61,62,63],4,0,6),c.addMany(l(32,64),6,0,6),c.add(127,6,0,6),c.addMany(l(64,127),6,0,0),c.addMany(l(32,48),3,9,5),c.addMany(l(32,48),5,9,5),c.addMany(l(48,64),5,0,6),c.addMany(l(64,127),5,7,0),c.addMany(l(32,48),4,9,5),c.addMany(l(32,48),1,9,2),c.addMany(l(32,48),2,9,2),c.addMany(l(48,127),2,10,0),c.addMany(l(48,80),1,10,0),c.addMany(l(81,88),1,10,0),c.addMany([89,90,92],1,10,0),c.addMany(l(96,127),1,10,0),c.add(80,1,11,9),c.addMany(m,9,0,9),c.add(127,9,0,9),c.addMany(l(28,32),9,0,9),c.addMany(l(32,48),9,9,12),c.addMany(l(48,60),9,8,10),c.addMany([60,61,62,63],9,9,10),c.addMany(m,11,0,11),c.addMany(l(32,128),11,0,11),c.addMany(l(28,32),11,0,11),c.addMany(m,10,0,10),c.add(127,10,0,10),c.addMany(l(28,32),10,0,10),c.addMany(l(48,60),10,8,10),c.addMany([60,61,62,63],10,0,11),c.addMany(l(32,48),10,9,12),c.addMany(m,12,0,12),c.add(127,12,0,12),c.addMany(l(28,32),12,0,12),c.addMany(l(32,48),12,9,12),c.addMany(l(48,64),12,0,11),c.addMany(l(64,127),12,12,13),c.addMany(l(64,127),10,12,13),c.addMany(l(64,127),9,12,13),c.addMany(m,13,13,13),c.addMany(u,13,13,13),c.add(127,13,0,13),c.addMany([27,156,24,26],13,14,0),c.add(w,0,2,0),c.add(w,8,5,8),c.add(w,6,0,6),c.add(w,11,0,11),c.add(w,13,13,13),c})();class y extends d.Disposable{constructor(p=n.VT500_TRANSITION_TABLE){super(),this._transitions=p,this._parseStack={state:0,handlers:[],handlerPos:0,transition:0,chunkPos:0},this.initialState=0,this.currentState=this.initialState,this._params=new f.Params,this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._printHandlerFb=(l,u,m)=>{},this._executeHandlerFb=l=>{},this._csiHandlerFb=(l,u)=>{},this._escHandlerFb=l=>{},this._errorHandlerFb=l=>l,this._printHandler=this._printHandlerFb,this._executeHandlers=Object.create(null),this._csiHandlers=Object.create(null),this._escHandlers=Object.create(null),this.register((0,d.toDisposable)((()=>{this._csiHandlers=Object.create(null),this._executeHandlers=Object.create(null),this._escHandlers=Object.create(null)}))),this._oscParser=this.register(new h.OscParser),this._dcsParser=this.register(new _.DcsParser),this._errorHandler=this._errorHandlerFb,this.registerEscHandler({final:"\\"},(()=>!0))}_identifier(p,l=[64,126]){let u=0;if(p.prefix){if(p.prefix.length>1)throw new Error("only one byte as prefix supported");if(u=p.prefix.charCodeAt(0),u&&60>u||u>63)throw new Error("prefix must be in range 0x3c .. 0x3f")}if(p.intermediates){if(p.intermediates.length>2)throw new Error("only two bytes as intermediates are supported");for(let x=0;x<p.intermediates.length;++x){const v=p.intermediates.charCodeAt(x);if(32>v||v>47)throw new Error("intermediate must be in range 0x20 .. 0x2f");u<<=8,u|=v}}if(p.final.length!==1)throw new Error("final must be a single byte");const m=p.final.charCodeAt(0);if(l[0]>m||m>l[1])throw new Error(`final must be in range ${l[0]} .. ${l[1]}`);return u<<=8,u|=m,u}identToString(p){const l=[];for(;p;)l.push(String.fromCharCode(255&p)),p>>=8;return l.reverse().join("")}setPrintHandler(p){this._printHandler=p}clearPrintHandler(){this._printHandler=this._printHandlerFb}registerEscHandler(p,l){const u=this._identifier(p,[48,126]);this._escHandlers[u]===void 0&&(this._escHandlers[u]=[]);const m=this._escHandlers[u];return m.push(l),{dispose:()=>{const x=m.indexOf(l);x!==-1&&m.splice(x,1)}}}clearEscHandler(p){this._escHandlers[this._identifier(p,[48,126])]&&delete this._escHandlers[this._identifier(p,[48,126])]}setEscHandlerFallback(p){this._escHandlerFb=p}setExecuteHandler(p,l){this._executeHandlers[p.charCodeAt(0)]=l}clearExecuteHandler(p){this._executeHandlers[p.charCodeAt(0)]&&delete this._executeHandlers[p.charCodeAt(0)]}setExecuteHandlerFallback(p){this._executeHandlerFb=p}registerCsiHandler(p,l){const u=this._identifier(p);this._csiHandlers[u]===void 0&&(this._csiHandlers[u]=[]);const m=this._csiHandlers[u];return m.push(l),{dispose:()=>{const x=m.indexOf(l);x!==-1&&m.splice(x,1)}}}clearCsiHandler(p){this._csiHandlers[this._identifier(p)]&&delete this._csiHandlers[this._identifier(p)]}setCsiHandlerFallback(p){this._csiHandlerFb=p}registerDcsHandler(p,l){return this._dcsParser.registerHandler(this._identifier(p),l)}clearDcsHandler(p){this._dcsParser.clearHandler(this._identifier(p))}setDcsHandlerFallback(p){this._dcsParser.setHandlerFallback(p)}registerOscHandler(p,l){return this._oscParser.registerHandler(p,l)}clearOscHandler(p){this._oscParser.clearHandler(p)}setOscHandlerFallback(p){this._oscParser.setHandlerFallback(p)}setErrorHandler(p){this._errorHandler=p}clearErrorHandler(){this._errorHandler=this._errorHandlerFb}reset(){this.currentState=this.initialState,this._oscParser.reset(),this._dcsParser.reset(),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._parseStack.state!==0&&(this._parseStack.state=2,this._parseStack.handlers=[])}_preserveStack(p,l,u,m,x){this._parseStack.state=p,this._parseStack.handlers=l,this._parseStack.handlerPos=u,this._parseStack.transition=m,this._parseStack.chunkPos=x}parse(p,l,u){let m,x=0,v=0,k=0;if(this._parseStack.state)if(this._parseStack.state===2)this._parseStack.state=0,k=this._parseStack.chunkPos+1;else{if(u===void 0||this._parseStack.state===1)throw this._parseStack.state=1,new Error("improper continuation due to previous async handler, giving up parsing");const E=this._parseStack.handlers;let C=this._parseStack.handlerPos-1;switch(this._parseStack.state){case 3:if(u===!1&&C>-1){for(;C>=0&&(m=E[C](this._params),m!==!0);C--)if(m instanceof Promise)return this._parseStack.handlerPos=C,m}this._parseStack.handlers=[];break;case 4:if(u===!1&&C>-1){for(;C>=0&&(m=E[C](),m!==!0);C--)if(m instanceof Promise)return this._parseStack.handlerPos=C,m}this._parseStack.handlers=[];break;case 6:if(x=p[this._parseStack.chunkPos],m=this._dcsParser.unhook(x!==24&&x!==26,u),m)return m;x===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0;break;case 5:if(x=p[this._parseStack.chunkPos],m=this._oscParser.end(x!==24&&x!==26,u),m)return m;x===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0}this._parseStack.state=0,k=this._parseStack.chunkPos+1,this.precedingJoinState=0,this.currentState=15&this._parseStack.transition}for(let E=k;E<l;++E){switch(x=p[E],v=this._transitions.table[this.currentState<<8|(x<160?x:w)],v>>4){case 2:for(let A=E+1;;++A){if(A>=l||(x=p[A])<32||x>126&&x<w){this._printHandler(p,E,A),E=A-1;break}if(++A>=l||(x=p[A])<32||x>126&&x<w){this._printHandler(p,E,A),E=A-1;break}if(++A>=l||(x=p[A])<32||x>126&&x<w){this._printHandler(p,E,A),E=A-1;break}if(++A>=l||(x=p[A])<32||x>126&&x<w){this._printHandler(p,E,A),E=A-1;break}}break;case 3:this._executeHandlers[x]?this._executeHandlers[x]():this._executeHandlerFb(x),this.precedingJoinState=0;break;case 0:break;case 1:if(this._errorHandler({position:E,code:x,currentState:this.currentState,collect:this._collect,params:this._params,abort:!1}).abort)return;break;case 7:const C=this._csiHandlers[this._collect<<8|x];let N=C?C.length-1:-1;for(;N>=0&&(m=C[N](this._params),m!==!0);N--)if(m instanceof Promise)return this._preserveStack(3,C,N,v,E),m;N<0&&this._csiHandlerFb(this._collect<<8|x,this._params),this.precedingJoinState=0;break;case 8:do switch(x){case 59:this._params.addParam(0);break;case 58:this._params.addSubParam(-1);break;default:this._params.addDigit(x-48)}while(++E<l&&(x=p[E])>47&&x<60);E--;break;case 9:this._collect<<=8,this._collect|=x;break;case 10:const R=this._escHandlers[this._collect<<8|x];let B=R?R.length-1:-1;for(;B>=0&&(m=R[B](),m!==!0);B--)if(m instanceof Promise)return this._preserveStack(4,R,B,v,E),m;B<0&&this._escHandlerFb(this._collect<<8|x),this.precedingJoinState=0;break;case 11:this._params.reset(),this._params.addParam(0),this._collect=0;break;case 12:this._dcsParser.hook(this._collect<<8|x,this._params);break;case 13:for(let A=E+1;;++A)if(A>=l||(x=p[A])===24||x===26||x===27||x>127&&x<w){this._dcsParser.put(p,E,A),E=A-1;break}break;case 14:if(m=this._dcsParser.unhook(x!==24&&x!==26),m)return this._preserveStack(6,[],0,v,E),m;x===27&&(v|=1),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0;break;case 4:this._oscParser.start();break;case 5:for(let A=E+1;;A++)if(A>=l||(x=p[A])<32||x>127&&x<w){this._oscParser.put(p,E,A),E=A-1;break}break;case 6:if(m=this._oscParser.end(x!==24&&x!==26),m)return this._preserveStack(5,[],0,v,E),m;x===27&&(v|=1),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0}this.currentState=15&v}}}n.EscapeSequenceParser=y},6242:(b,n,o)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.OscHandler=n.OscParser=void 0;const d=o(5770),f=o(482),h=[];n.OscParser=class{constructor(){this._state=0,this._active=h,this._id=-1,this._handlers=Object.create(null),this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}registerHandler(_,S){this._handlers[_]===void 0&&(this._handlers[_]=[]);const w=this._handlers[_];return w.push(S),{dispose:()=>{const y=w.indexOf(S);y!==-1&&w.splice(y,1)}}}clearHandler(_){this._handlers[_]&&delete this._handlers[_]}setHandlerFallback(_){this._handlerFb=_}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=h}reset(){if(this._state===2)for(let _=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;_>=0;--_)this._active[_].end(!1);this._stack.paused=!1,this._active=h,this._id=-1,this._state=0}_start(){if(this._active=this._handlers[this._id]||h,this._active.length)for(let _=this._active.length-1;_>=0;_--)this._active[_].start();else this._handlerFb(this._id,"START")}_put(_,S,w){if(this._active.length)for(let y=this._active.length-1;y>=0;y--)this._active[y].put(_,S,w);else this._handlerFb(this._id,"PUT",(0,f.utf32ToString)(_,S,w))}start(){this.reset(),this._state=1}put(_,S,w){if(this._state!==3){if(this._state===1)for(;S<w;){const y=_[S++];if(y===59){this._state=2,this._start();break}if(y<48||57<y)return void(this._state=3);this._id===-1&&(this._id=0),this._id=10*this._id+y-48}this._state===2&&w-S>0&&this._put(_,S,w)}}end(_,S=!0){if(this._state!==0){if(this._state!==3)if(this._state===1&&this._start(),this._active.length){let w=!1,y=this._active.length-1,c=!1;if(this._stack.paused&&(y=this._stack.loopPosition-1,w=S,c=this._stack.fallThrough,this._stack.paused=!1),!c&&w===!1){for(;y>=0&&(w=this._active[y].end(_),w!==!0);y--)if(w instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=y,this._stack.fallThrough=!1,w;y--}for(;y>=0;y--)if(w=this._active[y].end(!1),w instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=y,this._stack.fallThrough=!0,w}else this._handlerFb(this._id,"END",_);this._active=h,this._id=-1,this._state=0}}},n.OscHandler=class{constructor(_){this._handler=_,this._data="",this._hitLimit=!1}start(){this._data="",this._hitLimit=!1}put(_,S,w){this._hitLimit||(this._data+=(0,f.utf32ToString)(_,S,w),this._data.length>d.PAYLOAD_LIMIT&&(this._data="",this._hitLimit=!0))}end(_){let S=!1;if(this._hitLimit)S=!1;else if(_&&(S=this._handler(this._data),S instanceof Promise))return S.then((w=>(this._data="",this._hitLimit=!1,w)));return this._data="",this._hitLimit=!1,S}}},8742:(b,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.Params=void 0;const o=2147483647;class d{static fromArray(h){const _=new d;if(!h.length)return _;for(let S=Array.isArray(h[0])?1:0;S<h.length;++S){const w=h[S];if(Array.isArray(w))for(let y=0;y<w.length;++y)_.addSubParam(w[y]);else _.addParam(w)}return _}constructor(h=32,_=32){if(this.maxLength=h,this.maxSubParamsLength=_,_>256)throw new Error("maxSubParamsLength must not be greater than 256");this.params=new Int32Array(h),this.length=0,this._subParams=new Int32Array(_),this._subParamsLength=0,this._subParamsIdx=new Uint16Array(h),this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}clone(){const h=new d(this.maxLength,this.maxSubParamsLength);return h.params.set(this.params),h.length=this.length,h._subParams.set(this._subParams),h._subParamsLength=this._subParamsLength,h._subParamsIdx.set(this._subParamsIdx),h._rejectDigits=this._rejectDigits,h._rejectSubDigits=this._rejectSubDigits,h._digitIsSub=this._digitIsSub,h}toArray(){const h=[];for(let _=0;_<this.length;++_){h.push(this.params[_]);const S=this._subParamsIdx[_]>>8,w=255&this._subParamsIdx[_];w-S>0&&h.push(Array.prototype.slice.call(this._subParams,S,w))}return h}reset(){this.length=0,this._subParamsLength=0,this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}addParam(h){if(this._digitIsSub=!1,this.length>=this.maxLength)this._rejectDigits=!0;else{if(h<-1)throw new Error("values lesser than -1 are not allowed");this._subParamsIdx[this.length]=this._subParamsLength<<8|this._subParamsLength,this.params[this.length++]=h>o?o:h}}addSubParam(h){if(this._digitIsSub=!0,this.length)if(this._rejectDigits||this._subParamsLength>=this.maxSubParamsLength)this._rejectSubDigits=!0;else{if(h<-1)throw new Error("values lesser than -1 are not allowed");this._subParams[this._subParamsLength++]=h>o?o:h,this._subParamsIdx[this.length-1]++}}hasSubParams(h){return(255&this._subParamsIdx[h])-(this._subParamsIdx[h]>>8)>0}getSubParams(h){const _=this._subParamsIdx[h]>>8,S=255&this._subParamsIdx[h];return S-_>0?this._subParams.subarray(_,S):null}getSubParamsAll(){const h={};for(let _=0;_<this.length;++_){const S=this._subParamsIdx[_]>>8,w=255&this._subParamsIdx[_];w-S>0&&(h[_]=this._subParams.slice(S,w))}return h}addDigit(h){let _;if(this._rejectDigits||!(_=this._digitIsSub?this._subParamsLength:this.length)||this._digitIsSub&&this._rejectSubDigits)return;const S=this._digitIsSub?this._subParams:this.params,w=S[_-1];S[_-1]=~w?Math.min(10*w+h,o):h}}n.Params=d},5741:(b,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.AddonManager=void 0,n.AddonManager=class{constructor(){this._addons=[]}dispose(){for(let o=this._addons.length-1;o>=0;o--)this._addons[o].instance.dispose()}loadAddon(o,d){const f={instance:d,dispose:d.dispose,isDisposed:!1};this._addons.push(f),d.dispose=()=>this._wrappedAddonDispose(f),d.activate(o)}_wrappedAddonDispose(o){if(o.isDisposed)return;let d=-1;for(let f=0;f<this._addons.length;f++)if(this._addons[f]===o){d=f;break}if(d===-1)throw new Error("Could not dispose an addon that has not been loaded");o.isDisposed=!0,o.dispose.apply(o.instance),this._addons.splice(d,1)}}},8771:(b,n,o)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.BufferApiView=void 0;const d=o(3785),f=o(511);n.BufferApiView=class{constructor(h,_){this._buffer=h,this.type=_}init(h){return this._buffer=h,this}get cursorY(){return this._buffer.y}get cursorX(){return this._buffer.x}get viewportY(){return this._buffer.ydisp}get baseY(){return this._buffer.ybase}get length(){return this._buffer.lines.length}getLine(h){const _=this._buffer.lines.get(h);if(_)return new d.BufferLineApiView(_)}getNullCell(){return new f.CellData}}},3785:(b,n,o)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.BufferLineApiView=void 0;const d=o(511);n.BufferLineApiView=class{constructor(f){this._line=f}get isWrapped(){return this._line.isWrapped}get length(){return this._line.length}getCell(f,h){if(!(f<0||f>=this._line.length))return h?(this._line.loadCell(f,h),h):this._line.loadCell(f,new d.CellData)}translateToString(f,h,_){return this._line.translateToString(f,h,_)}}},8285:(b,n,o)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.BufferNamespaceApi=void 0;const d=o(8771),f=o(8460),h=o(844);class _ extends h.Disposable{constructor(w){super(),this._core=w,this._onBufferChange=this.register(new f.EventEmitter),this.onBufferChange=this._onBufferChange.event,this._normal=new d.BufferApiView(this._core.buffers.normal,"normal"),this._alternate=new d.BufferApiView(this._core.buffers.alt,"alternate"),this._core.buffers.onBufferActivate((()=>this._onBufferChange.fire(this.active)))}get active(){if(this._core.buffers.active===this._core.buffers.normal)return this.normal;if(this._core.buffers.active===this._core.buffers.alt)return this.alternate;throw new Error("Active buffer is neither normal nor alternate")}get normal(){return this._normal.init(this._core.buffers.normal)}get alternate(){return this._alternate.init(this._core.buffers.alt)}}n.BufferNamespaceApi=_},7975:(b,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.ParserApi=void 0,n.ParserApi=class{constructor(o){this._core=o}registerCsiHandler(o,d){return this._core.registerCsiHandler(o,(f=>d(f.toArray())))}addCsiHandler(o,d){return this.registerCsiHandler(o,d)}registerDcsHandler(o,d){return this._core.registerDcsHandler(o,((f,h)=>d(f,h.toArray())))}addDcsHandler(o,d){return this.registerDcsHandler(o,d)}registerEscHandler(o,d){return this._core.registerEscHandler(o,d)}addEscHandler(o,d){return this.registerEscHandler(o,d)}registerOscHandler(o,d){return this._core.registerOscHandler(o,d)}addOscHandler(o,d){return this.registerOscHandler(o,d)}}},7090:(b,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.UnicodeApi=void 0,n.UnicodeApi=class{constructor(o){this._core=o}register(o){this._core.unicodeService.register(o)}get versions(){return this._core.unicodeService.versions}get activeVersion(){return this._core.unicodeService.activeVersion}set activeVersion(o){this._core.unicodeService.activeVersion=o}}},744:function(b,n,o){var d=this&&this.__decorate||function(c,p,l,u){var m,x=arguments.length,v=x<3?p:u===null?u=Object.getOwnPropertyDescriptor(p,l):u;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")v=Reflect.decorate(c,p,l,u);else for(var k=c.length-1;k>=0;k--)(m=c[k])&&(v=(x<3?m(v):x>3?m(p,l,v):m(p,l))||v);return x>3&&v&&Object.defineProperty(p,l,v),v},f=this&&this.__param||function(c,p){return function(l,u){p(l,u,c)}};Object.defineProperty(n,"__esModule",{value:!0}),n.BufferService=n.MINIMUM_ROWS=n.MINIMUM_COLS=void 0;const h=o(8460),_=o(844),S=o(5295),w=o(2585);n.MINIMUM_COLS=2,n.MINIMUM_ROWS=1;let y=n.BufferService=class extends _.Disposable{get buffer(){return this.buffers.active}constructor(c){super(),this.isUserScrolling=!1,this._onResize=this.register(new h.EventEmitter),this.onResize=this._onResize.event,this._onScroll=this.register(new h.EventEmitter),this.onScroll=this._onScroll.event,this.cols=Math.max(c.rawOptions.cols||0,n.MINIMUM_COLS),this.rows=Math.max(c.rawOptions.rows||0,n.MINIMUM_ROWS),this.buffers=this.register(new S.BufferSet(c,this))}resize(c,p){this.cols=c,this.rows=p,this.buffers.resize(c,p),this._onResize.fire({cols:c,rows:p})}reset(){this.buffers.reset(),this.isUserScrolling=!1}scroll(c,p=!1){const l=this.buffer;let u;u=this._cachedBlankLine,u&&u.length===this.cols&&u.getFg(0)===c.fg&&u.getBg(0)===c.bg||(u=l.getBlankLine(c,p),this._cachedBlankLine=u),u.isWrapped=p;const m=l.ybase+l.scrollTop,x=l.ybase+l.scrollBottom;if(l.scrollTop===0){const v=l.lines.isFull;x===l.lines.length-1?v?l.lines.recycle().copyFrom(u):l.lines.push(u.clone()):l.lines.splice(x+1,0,u.clone()),v?this.isUserScrolling&&(l.ydisp=Math.max(l.ydisp-1,0)):(l.ybase++,this.isUserScrolling||l.ydisp++)}else{const v=x-m+1;l.lines.shiftElements(m+1,v-1,-1),l.lines.set(x,u.clone())}this.isUserScrolling||(l.ydisp=l.ybase),this._onScroll.fire(l.ydisp)}scrollLines(c,p,l){const u=this.buffer;if(c<0){if(u.ydisp===0)return;this.isUserScrolling=!0}else c+u.ydisp>=u.ybase&&(this.isUserScrolling=!1);const m=u.ydisp;u.ydisp=Math.max(Math.min(u.ydisp+c,u.ybase),0),m!==u.ydisp&&(p||this._onScroll.fire(u.ydisp))}};n.BufferService=y=d([f(0,w.IOptionsService)],y)},7994:(b,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.CharsetService=void 0,n.CharsetService=class{constructor(){this.glevel=0,this._charsets=[]}reset(){this.charset=void 0,this._charsets=[],this.glevel=0}setgLevel(o){this.glevel=o,this.charset=this._charsets[o]}setgCharset(o,d){this._charsets[o]=d,this.glevel===o&&(this.charset=d)}}},1753:function(b,n,o){var d=this&&this.__decorate||function(u,m,x,v){var k,E=arguments.length,C=E<3?m:v===null?v=Object.getOwnPropertyDescriptor(m,x):v;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")C=Reflect.decorate(u,m,x,v);else for(var N=u.length-1;N>=0;N--)(k=u[N])&&(C=(E<3?k(C):E>3?k(m,x,C):k(m,x))||C);return E>3&&C&&Object.defineProperty(m,x,C),C},f=this&&this.__param||function(u,m){return function(x,v){m(x,v,u)}};Object.defineProperty(n,"__esModule",{value:!0}),n.CoreMouseService=void 0;const h=o(2585),_=o(8460),S=o(844),w={NONE:{events:0,restrict:()=>!1},X10:{events:1,restrict:u=>u.button!==4&&u.action===1&&(u.ctrl=!1,u.alt=!1,u.shift=!1,!0)},VT200:{events:19,restrict:u=>u.action!==32},DRAG:{events:23,restrict:u=>u.action!==32||u.button!==3},ANY:{events:31,restrict:u=>!0}};function y(u,m){let x=(u.ctrl?16:0)|(u.shift?4:0)|(u.alt?8:0);return u.button===4?(x|=64,x|=u.action):(x|=3&u.button,4&u.button&&(x|=64),8&u.button&&(x|=128),u.action===32?x|=32:u.action!==0||m||(x|=3)),x}const c=String.fromCharCode,p={DEFAULT:u=>{const m=[y(u,!1)+32,u.col+32,u.row+32];return m[0]>255||m[1]>255||m[2]>255?"":`\x1B[M${c(m[0])}${c(m[1])}${c(m[2])}`},SGR:u=>{const m=u.action===0&&u.button!==4?"m":"M";return`\x1B[<${y(u,!0)};${u.col};${u.row}${m}`},SGR_PIXELS:u=>{const m=u.action===0&&u.button!==4?"m":"M";return`\x1B[<${y(u,!0)};${u.x};${u.y}${m}`}};let l=n.CoreMouseService=class extends S.Disposable{constructor(u,m){super(),this._bufferService=u,this._coreService=m,this._protocols={},this._encodings={},this._activeProtocol="",this._activeEncoding="",this._lastEvent=null,this._onProtocolChange=this.register(new _.EventEmitter),this.onProtocolChange=this._onProtocolChange.event;for(const x of Object.keys(w))this.addProtocol(x,w[x]);for(const x of Object.keys(p))this.addEncoding(x,p[x]);this.reset()}addProtocol(u,m){this._protocols[u]=m}addEncoding(u,m){this._encodings[u]=m}get activeProtocol(){return this._activeProtocol}get areMouseEventsActive(){return this._protocols[this._activeProtocol].events!==0}set activeProtocol(u){if(!this._protocols[u])throw new Error(`unknown protocol "${u}"`);this._activeProtocol=u,this._onProtocolChange.fire(this._protocols[u].events)}get activeEncoding(){return this._activeEncoding}set activeEncoding(u){if(!this._encodings[u])throw new Error(`unknown encoding "${u}"`);this._activeEncoding=u}reset(){this.activeProtocol="NONE",this.activeEncoding="DEFAULT",this._lastEvent=null}triggerMouseEvent(u){if(u.col<0||u.col>=this._bufferService.cols||u.row<0||u.row>=this._bufferService.rows||u.button===4&&u.action===32||u.button===3&&u.action!==32||u.button!==4&&(u.action===2||u.action===3)||(u.col++,u.row++,u.action===32&&this._lastEvent&&this._equalEvents(this._lastEvent,u,this._activeEncoding==="SGR_PIXELS"))||!this._protocols[this._activeProtocol].restrict(u))return!1;const m=this._encodings[this._activeEncoding](u);return m&&(this._activeEncoding==="DEFAULT"?this._coreService.triggerBinaryEvent(m):this._coreService.triggerDataEvent(m,!0)),this._lastEvent=u,!0}explainEvents(u){return{down:!!(1&u),up:!!(2&u),drag:!!(4&u),move:!!(8&u),wheel:!!(16&u)}}_equalEvents(u,m,x){if(x){if(u.x!==m.x||u.y!==m.y)return!1}else if(u.col!==m.col||u.row!==m.row)return!1;return u.button===m.button&&u.action===m.action&&u.ctrl===m.ctrl&&u.alt===m.alt&&u.shift===m.shift}};n.CoreMouseService=l=d([f(0,h.IBufferService),f(1,h.ICoreService)],l)},6975:function(b,n,o){var d=this&&this.__decorate||function(l,u,m,x){var v,k=arguments.length,E=k<3?u:x===null?x=Object.getOwnPropertyDescriptor(u,m):x;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")E=Reflect.decorate(l,u,m,x);else for(var C=l.length-1;C>=0;C--)(v=l[C])&&(E=(k<3?v(E):k>3?v(u,m,E):v(u,m))||E);return k>3&&E&&Object.defineProperty(u,m,E),E},f=this&&this.__param||function(l,u){return function(m,x){u(m,x,l)}};Object.defineProperty(n,"__esModule",{value:!0}),n.CoreService=void 0;const h=o(1439),_=o(8460),S=o(844),w=o(2585),y=Object.freeze({insertMode:!1}),c=Object.freeze({applicationCursorKeys:!1,applicationKeypad:!1,bracketedPasteMode:!1,origin:!1,reverseWraparound:!1,sendFocus:!1,wraparound:!0});let p=n.CoreService=class extends S.Disposable{constructor(l,u,m){super(),this._bufferService=l,this._logService=u,this._optionsService=m,this.isCursorInitialized=!1,this.isCursorHidden=!1,this._onData=this.register(new _.EventEmitter),this.onData=this._onData.event,this._onUserInput=this.register(new _.EventEmitter),this.onUserInput=this._onUserInput.event,this._onBinary=this.register(new _.EventEmitter),this.onBinary=this._onBinary.event,this._onRequestScrollToBottom=this.register(new _.EventEmitter),this.onRequestScrollToBottom=this._onRequestScrollToBottom.event,this.modes=(0,h.clone)(y),this.decPrivateModes=(0,h.clone)(c)}reset(){this.modes=(0,h.clone)(y),this.decPrivateModes=(0,h.clone)(c)}triggerDataEvent(l,u=!1){if(this._optionsService.rawOptions.disableStdin)return;const m=this._bufferService.buffer;u&&this._optionsService.rawOptions.scrollOnUserInput&&m.ybase!==m.ydisp&&this._onRequestScrollToBottom.fire(),u&&this._onUserInput.fire(),this._logService.debug(`sending data "${l}"`,(()=>l.split("").map((x=>x.charCodeAt(0))))),this._onData.fire(l)}triggerBinaryEvent(l){this._optionsService.rawOptions.disableStdin||(this._logService.debug(`sending binary "${l}"`,(()=>l.split("").map((u=>u.charCodeAt(0))))),this._onBinary.fire(l))}};n.CoreService=p=d([f(0,w.IBufferService),f(1,w.ILogService),f(2,w.IOptionsService)],p)},9074:(b,n,o)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.DecorationService=void 0;const d=o(8055),f=o(8460),h=o(844),_=o(6106);let S=0,w=0;class y extends h.Disposable{get decorations(){return this._decorations.values()}constructor(){super(),this._decorations=new _.SortedList((l=>l==null?void 0:l.marker.line)),this._onDecorationRegistered=this.register(new f.EventEmitter),this.onDecorationRegistered=this._onDecorationRegistered.event,this._onDecorationRemoved=this.register(new f.EventEmitter),this.onDecorationRemoved=this._onDecorationRemoved.event,this.register((0,h.toDisposable)((()=>this.reset())))}registerDecoration(l){if(l.marker.isDisposed)return;const u=new c(l);if(u){const m=u.marker.onDispose((()=>u.dispose()));u.onDispose((()=>{u&&(this._decorations.delete(u)&&this._onDecorationRemoved.fire(u),m.dispose())})),this._decorations.insert(u),this._onDecorationRegistered.fire(u)}return u}reset(){for(const l of this._decorations.values())l.dispose();this._decorations.clear()}*getDecorationsAtCell(l,u,m){let x=0,v=0;for(const k of this._decorations.getKeyIterator(u))x=k.options.x??0,v=x+(k.options.width??1),l>=x&&l<v&&(!m||(k.options.layer??"bottom")===m)&&(yield k)}forEachDecorationAtCell(l,u,m,x){this._decorations.forEachByKey(u,(v=>{S=v.options.x??0,w=S+(v.options.width??1),l>=S&&l<w&&(!m||(v.options.layer??"bottom")===m)&&x(v)}))}}n.DecorationService=y;class c extends h.Disposable{get isDisposed(){return this._isDisposed}get backgroundColorRGB(){return this._cachedBg===null&&(this.options.backgroundColor?this._cachedBg=d.css.toColor(this.options.backgroundColor):this._cachedBg=void 0),this._cachedBg}get foregroundColorRGB(){return this._cachedFg===null&&(this.options.foregroundColor?this._cachedFg=d.css.toColor(this.options.foregroundColor):this._cachedFg=void 0),this._cachedFg}constructor(l){super(),this.options=l,this.onRenderEmitter=this.register(new f.EventEmitter),this.onRender=this.onRenderEmitter.event,this._onDispose=this.register(new f.EventEmitter),this.onDispose=this._onDispose.event,this._cachedBg=null,this._cachedFg=null,this.marker=l.marker,this.options.overviewRulerOptions&&!this.options.overviewRulerOptions.position&&(this.options.overviewRulerOptions.position="full")}dispose(){this._onDispose.fire(),super.dispose()}}},4348:(b,n,o)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.InstantiationService=n.ServiceCollection=void 0;const d=o(2585),f=o(8343);class h{constructor(...S){this._entries=new Map;for(const[w,y]of S)this.set(w,y)}set(S,w){const y=this._entries.get(S);return this._entries.set(S,w),y}forEach(S){for(const[w,y]of this._entries.entries())S(w,y)}has(S){return this._entries.has(S)}get(S){return this._entries.get(S)}}n.ServiceCollection=h,n.InstantiationService=class{constructor(){this._services=new h,this._services.set(d.IInstantiationService,this)}setService(_,S){this._services.set(_,S)}getService(_){return this._services.get(_)}createInstance(_,...S){const w=(0,f.getServiceDependencies)(_).sort(((p,l)=>p.index-l.index)),y=[];for(const p of w){const l=this._services.get(p.id);if(!l)throw new Error(`[createInstance] ${_.name} depends on UNKNOWN service ${p.id}.`);y.push(l)}const c=w.length>0?w[0].index:S.length;if(S.length!==c)throw new Error(`[createInstance] First service dependency of ${_.name} at position ${c+1} conflicts with ${S.length} static arguments`);return new _(...S,...y)}}},7866:function(b,n,o){var d=this&&this.__decorate||function(c,p,l,u){var m,x=arguments.length,v=x<3?p:u===null?u=Object.getOwnPropertyDescriptor(p,l):u;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")v=Reflect.decorate(c,p,l,u);else for(var k=c.length-1;k>=0;k--)(m=c[k])&&(v=(x<3?m(v):x>3?m(p,l,v):m(p,l))||v);return x>3&&v&&Object.defineProperty(p,l,v),v},f=this&&this.__param||function(c,p){return function(l,u){p(l,u,c)}};Object.defineProperty(n,"__esModule",{value:!0}),n.traceCall=n.setTraceLogger=n.LogService=void 0;const h=o(844),_=o(2585),S={trace:_.LogLevelEnum.TRACE,debug:_.LogLevelEnum.DEBUG,info:_.LogLevelEnum.INFO,warn:_.LogLevelEnum.WARN,error:_.LogLevelEnum.ERROR,off:_.LogLevelEnum.OFF};let w,y=n.LogService=class extends h.Disposable{get logLevel(){return this._logLevel}constructor(c){super(),this._optionsService=c,this._logLevel=_.LogLevelEnum.OFF,this._updateLogLevel(),this.register(this._optionsService.onSpecificOptionChange("logLevel",(()=>this._updateLogLevel()))),w=this}_updateLogLevel(){this._logLevel=S[this._optionsService.rawOptions.logLevel]}_evalLazyOptionalParams(c){for(let p=0;p<c.length;p++)typeof c[p]=="function"&&(c[p]=c[p]())}_log(c,p,l){this._evalLazyOptionalParams(l),c.call(console,(this._optionsService.options.logger?"":"xterm.js: ")+p,...l)}trace(c,...p){var l;this._logLevel<=_.LogLevelEnum.TRACE&&this._log(((l=this._optionsService.options.logger)==null?void 0:l.trace.bind(this._optionsService.options.logger))??console.log,c,p)}debug(c,...p){var l;this._logLevel<=_.LogLevelEnum.DEBUG&&this._log(((l=this._optionsService.options.logger)==null?void 0:l.debug.bind(this._optionsService.options.logger))??console.log,c,p)}info(c,...p){var l;this._logLevel<=_.LogLevelEnum.INFO&&this._log(((l=this._optionsService.options.logger)==null?void 0:l.info.bind(this._optionsService.options.logger))??console.info,c,p)}warn(c,...p){var l;this._logLevel<=_.LogLevelEnum.WARN&&this._log(((l=this._optionsService.options.logger)==null?void 0:l.warn.bind(this._optionsService.options.logger))??console.warn,c,p)}error(c,...p){var l;this._logLevel<=_.LogLevelEnum.ERROR&&this._log(((l=this._optionsService.options.logger)==null?void 0:l.error.bind(this._optionsService.options.logger))??console.error,c,p)}};n.LogService=y=d([f(0,_.IOptionsService)],y),n.setTraceLogger=function(c){w=c},n.traceCall=function(c,p,l){if(typeof l.value!="function")throw new Error("not supported");const u=l.value;l.value=function(...m){if(w.logLevel!==_.LogLevelEnum.TRACE)return u.apply(this,m);w.trace(`GlyphRenderer#${u.name}(${m.map((v=>JSON.stringify(v))).join(", ")})`);const x=u.apply(this,m);return w.trace(`GlyphRenderer#${u.name} return`,x),x}}},7302:(b,n,o)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.OptionsService=n.DEFAULT_OPTIONS=void 0;const d=o(8460),f=o(844),h=o(6114);n.DEFAULT_OPTIONS={cols:80,rows:24,cursorBlink:!1,cursorStyle:"block",cursorWidth:1,cursorInactiveStyle:"outline",customGlyphs:!0,drawBoldTextInBrightColors:!0,documentOverride:null,fastScrollModifier:"alt",fastScrollSensitivity:5,fontFamily:"courier-new, courier, monospace",fontSize:15,fontWeight:"normal",fontWeightBold:"bold",ignoreBracketedPasteMode:!1,lineHeight:1,letterSpacing:0,linkHandler:null,logLevel:"info",logger:null,scrollback:1e3,scrollOnUserInput:!0,scrollSensitivity:1,screenReaderMode:!1,smoothScrollDuration:0,macOptionIsMeta:!1,macOptionClickForcesSelection:!1,minimumContrastRatio:1,disableStdin:!1,allowProposedApi:!1,allowTransparency:!1,tabStopWidth:8,theme:{},rescaleOverlappingGlyphs:!1,rightClickSelectsWord:h.isMac,windowOptions:{},windowsMode:!1,windowsPty:{},wordSeparator:" ()[]{}',\"`",altClickMovesCursor:!0,convertEol:!1,termName:"xterm",cancelEvents:!1,overviewRulerWidth:0};const _=["normal","bold","100","200","300","400","500","600","700","800","900"];class S extends f.Disposable{constructor(y){super(),this._onOptionChange=this.register(new d.EventEmitter),this.onOptionChange=this._onOptionChange.event;const c={...n.DEFAULT_OPTIONS};for(const p in y)if(p in c)try{const l=y[p];c[p]=this._sanitizeAndValidateOption(p,l)}catch(l){console.error(l)}this.rawOptions=c,this.options={...c},this._setupOptions(),this.register((0,f.toDisposable)((()=>{this.rawOptions.linkHandler=null,this.rawOptions.documentOverride=null})))}onSpecificOptionChange(y,c){return this.onOptionChange((p=>{p===y&&c(this.rawOptions[y])}))}onMultipleOptionChange(y,c){return this.onOptionChange((p=>{y.indexOf(p)!==-1&&c()}))}_setupOptions(){const y=p=>{if(!(p in n.DEFAULT_OPTIONS))throw new Error(`No option with key "${p}"`);return this.rawOptions[p]},c=(p,l)=>{if(!(p in n.DEFAULT_OPTIONS))throw new Error(`No option with key "${p}"`);l=this._sanitizeAndValidateOption(p,l),this.rawOptions[p]!==l&&(this.rawOptions[p]=l,this._onOptionChange.fire(p))};for(const p in this.rawOptions){const l={get:y.bind(this,p),set:c.bind(this,p)};Object.defineProperty(this.options,p,l)}}_sanitizeAndValidateOption(y,c){switch(y){case"cursorStyle":if(c||(c=n.DEFAULT_OPTIONS[y]),!(function(p){return p==="block"||p==="underline"||p==="bar"})(c))throw new Error(`"${c}" is not a valid value for ${y}`);break;case"wordSeparator":c||(c=n.DEFAULT_OPTIONS[y]);break;case"fontWeight":case"fontWeightBold":if(typeof c=="number"&&1<=c&&c<=1e3)break;c=_.includes(c)?c:n.DEFAULT_OPTIONS[y];break;case"cursorWidth":c=Math.floor(c);case"lineHeight":case"tabStopWidth":if(c<1)throw new Error(`${y} cannot be less than 1, value: ${c}`);break;case"minimumContrastRatio":c=Math.max(1,Math.min(21,Math.round(10*c)/10));break;case"scrollback":if((c=Math.min(c,4294967295))<0)throw new Error(`${y} cannot be less than 0, value: ${c}`);break;case"fastScrollSensitivity":case"scrollSensitivity":if(c<=0)throw new Error(`${y} cannot be less than or equal to 0, value: ${c}`);break;case"rows":case"cols":if(!c&&c!==0)throw new Error(`${y} must be numeric, value: ${c}`);break;case"windowsPty":c=c??{}}return c}}n.OptionsService=S},2660:function(b,n,o){var d=this&&this.__decorate||function(S,w,y,c){var p,l=arguments.length,u=l<3?w:c===null?c=Object.getOwnPropertyDescriptor(w,y):c;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")u=Reflect.decorate(S,w,y,c);else for(var m=S.length-1;m>=0;m--)(p=S[m])&&(u=(l<3?p(u):l>3?p(w,y,u):p(w,y))||u);return l>3&&u&&Object.defineProperty(w,y,u),u},f=this&&this.__param||function(S,w){return function(y,c){w(y,c,S)}};Object.defineProperty(n,"__esModule",{value:!0}),n.OscLinkService=void 0;const h=o(2585);let _=n.OscLinkService=class{constructor(S){this._bufferService=S,this._nextId=1,this._entriesWithId=new Map,this._dataByLinkId=new Map}registerLink(S){const w=this._bufferService.buffer;if(S.id===void 0){const m=w.addMarker(w.ybase+w.y),x={data:S,id:this._nextId++,lines:[m]};return m.onDispose((()=>this._removeMarkerFromLink(x,m))),this._dataByLinkId.set(x.id,x),x.id}const y=S,c=this._getEntryIdKey(y),p=this._entriesWithId.get(c);if(p)return this.addLineToLink(p.id,w.ybase+w.y),p.id;const l=w.addMarker(w.ybase+w.y),u={id:this._nextId++,key:this._getEntryIdKey(y),data:y,lines:[l]};return l.onDispose((()=>this._removeMarkerFromLink(u,l))),this._entriesWithId.set(u.key,u),this._dataByLinkId.set(u.id,u),u.id}addLineToLink(S,w){const y=this._dataByLinkId.get(S);if(y&&y.lines.every((c=>c.line!==w))){const c=this._bufferService.buffer.addMarker(w);y.lines.push(c),c.onDispose((()=>this._removeMarkerFromLink(y,c)))}}getLinkData(S){var w;return(w=this._dataByLinkId.get(S))==null?void 0:w.data}_getEntryIdKey(S){return`${S.id};;${S.uri}`}_removeMarkerFromLink(S,w){const y=S.lines.indexOf(w);y!==-1&&(S.lines.splice(y,1),S.lines.length===0&&(S.data.id!==void 0&&this._entriesWithId.delete(S.key),this._dataByLinkId.delete(S.id)))}};n.OscLinkService=_=d([f(0,h.IBufferService)],_)},8343:(b,n)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.createDecorator=n.getServiceDependencies=n.serviceRegistry=void 0;const o="di$target",d="di$dependencies";n.serviceRegistry=new Map,n.getServiceDependencies=function(f){return f[d]||[]},n.createDecorator=function(f){if(n.serviceRegistry.has(f))return n.serviceRegistry.get(f);const h=function(_,S,w){if(arguments.length!==3)throw new Error("@IServiceName-decorator can only be used to decorate a parameter");(function(y,c,p){c[o]===c?c[d].push({id:y,index:p}):(c[d]=[{id:y,index:p}],c[o]=c)})(h,_,w)};return h.toString=()=>f,n.serviceRegistry.set(f,h),h}},2585:(b,n,o)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.IDecorationService=n.IUnicodeService=n.IOscLinkService=n.IOptionsService=n.ILogService=n.LogLevelEnum=n.IInstantiationService=n.ICharsetService=n.ICoreService=n.ICoreMouseService=n.IBufferService=void 0;const d=o(8343);var f;n.IBufferService=(0,d.createDecorator)("BufferService"),n.ICoreMouseService=(0,d.createDecorator)("CoreMouseService"),n.ICoreService=(0,d.createDecorator)("CoreService"),n.ICharsetService=(0,d.createDecorator)("CharsetService"),n.IInstantiationService=(0,d.createDecorator)("InstantiationService"),(function(h){h[h.TRACE=0]="TRACE",h[h.DEBUG=1]="DEBUG",h[h.INFO=2]="INFO",h[h.WARN=3]="WARN",h[h.ERROR=4]="ERROR",h[h.OFF=5]="OFF"})(f||(n.LogLevelEnum=f={})),n.ILogService=(0,d.createDecorator)("LogService"),n.IOptionsService=(0,d.createDecorator)("OptionsService"),n.IOscLinkService=(0,d.createDecorator)("OscLinkService"),n.IUnicodeService=(0,d.createDecorator)("UnicodeService"),n.IDecorationService=(0,d.createDecorator)("DecorationService")},1480:(b,n,o)=>{Object.defineProperty(n,"__esModule",{value:!0}),n.UnicodeService=void 0;const d=o(8460),f=o(225);class h{static extractShouldJoin(S){return(1&S)!=0}static extractWidth(S){return S>>1&3}static extractCharKind(S){return S>>3}static createPropertyValue(S,w,y=!1){return(16777215&S)<<3|(3&w)<<1|(y?1:0)}constructor(){this._providers=Object.create(null),this._active="",this._onChange=new d.EventEmitter,this.onChange=this._onChange.event;const S=new f.UnicodeV6;this.register(S),this._active=S.version,this._activeProvider=S}dispose(){this._onChange.dispose()}get versions(){return Object.keys(this._providers)}get activeVersion(){return this._active}set activeVersion(S){if(!this._providers[S])throw new Error(`unknown Unicode version "${S}"`);this._active=S,this._activeProvider=this._providers[S],this._onChange.fire(S)}register(S){this._providers[S.version]=S}wcwidth(S){return this._activeProvider.wcwidth(S)}getStringCellWidth(S){let w=0,y=0;const c=S.length;for(let p=0;p<c;++p){let l=S.charCodeAt(p);if(55296<=l&&l<=56319){if(++p>=c)return w+this.wcwidth(l);const x=S.charCodeAt(p);56320<=x&&x<=57343?l=1024*(l-55296)+x-56320+65536:w+=this.wcwidth(x)}const u=this.charProperties(l,y);let m=h.extractWidth(u);h.extractShouldJoin(u)&&(m-=h.extractWidth(y)),w+=m,y=u}return w}charProperties(S,w){return this._activeProvider.charProperties(S,w)}}n.UnicodeService=h}},i={};function a(b){var n=i[b];if(n!==void 0)return n.exports;var o=i[b]={exports:{}};return r[b].call(o.exports,o,o.exports,a),o.exports}var g={};return(()=>{var b=g;Object.defineProperty(b,"__esModule",{value:!0}),b.Terminal=void 0;const n=a(9042),o=a(3236),d=a(844),f=a(5741),h=a(8285),_=a(7975),S=a(7090),w=["cols","rows"];class y extends d.Disposable{constructor(p){super(),this._core=this.register(new o.Terminal(p)),this._addonManager=this.register(new f.AddonManager),this._publicOptions={...this._core.options};const l=m=>this._core.options[m],u=(m,x)=>{this._checkReadonlyOptions(m),this._core.options[m]=x};for(const m in this._core.options){const x={get:l.bind(this,m),set:u.bind(this,m)};Object.defineProperty(this._publicOptions,m,x)}}_checkReadonlyOptions(p){if(w.includes(p))throw new Error(`Option "${p}" can only be set in the constructor`)}_checkProposedApi(){if(!this._core.optionsService.rawOptions.allowProposedApi)throw new Error("You must set the allowProposedApi option to true to use proposed API")}get onBell(){return this._core.onBell}get onBinary(){return this._core.onBinary}get onCursorMove(){return this._core.onCursorMove}get onData(){return this._core.onData}get onKey(){return this._core.onKey}get onLineFeed(){return this._core.onLineFeed}get onRender(){return this._core.onRender}get onResize(){return this._core.onResize}get onScroll(){return this._core.onScroll}get onSelectionChange(){return this._core.onSelectionChange}get onTitleChange(){return this._core.onTitleChange}get onWriteParsed(){return this._core.onWriteParsed}get element(){return this._core.element}get parser(){return this._parser||(this._parser=new _.ParserApi(this._core)),this._parser}get unicode(){return this._checkProposedApi(),new S.UnicodeApi(this._core)}get textarea(){return this._core.textarea}get rows(){return this._core.rows}get cols(){return this._core.cols}get buffer(){return this._buffer||(this._buffer=this.register(new h.BufferNamespaceApi(this._core))),this._buffer}get markers(){return this._checkProposedApi(),this._core.markers}get modes(){const p=this._core.coreService.decPrivateModes;let l="none";switch(this._core.coreMouseService.activeProtocol){case"X10":l="x10";break;case"VT200":l="vt200";break;case"DRAG":l="drag";break;case"ANY":l="any"}return{applicationCursorKeysMode:p.applicationCursorKeys,applicationKeypadMode:p.applicationKeypad,bracketedPasteMode:p.bracketedPasteMode,insertMode:this._core.coreService.modes.insertMode,mouseTrackingMode:l,originMode:p.origin,reverseWraparoundMode:p.reverseWraparound,sendFocusMode:p.sendFocus,wraparoundMode:p.wraparound}}get options(){return this._publicOptions}set options(p){for(const l in p)this._publicOptions[l]=p[l]}blur(){this._core.blur()}focus(){this._core.focus()}input(p,l=!0){this._core.input(p,l)}resize(p,l){this._verifyIntegers(p,l),this._core.resize(p,l)}open(p){this._core.open(p)}attachCustomKeyEventHandler(p){this._core.attachCustomKeyEventHandler(p)}attachCustomWheelEventHandler(p){this._core.attachCustomWheelEventHandler(p)}registerLinkProvider(p){return this._core.registerLinkProvider(p)}registerCharacterJoiner(p){return this._checkProposedApi(),this._core.registerCharacterJoiner(p)}deregisterCharacterJoiner(p){this._checkProposedApi(),this._core.deregisterCharacterJoiner(p)}registerMarker(p=0){return this._verifyIntegers(p),this._core.registerMarker(p)}registerDecoration(p){return this._checkProposedApi(),this._verifyPositiveIntegers(p.x??0,p.width??0,p.height??0),this._core.registerDecoration(p)}hasSelection(){return this._core.hasSelection()}select(p,l,u){this._verifyIntegers(p,l,u),this._core.select(p,l,u)}getSelection(){return this._core.getSelection()}getSelectionPosition(){return this._core.getSelectionPosition()}clearSelection(){this._core.clearSelection()}selectAll(){this._core.selectAll()}selectLines(p,l){this._verifyIntegers(p,l),this._core.selectLines(p,l)}dispose(){super.dispose()}scrollLines(p){this._verifyIntegers(p),this._core.scrollLines(p)}scrollPages(p){this._verifyIntegers(p),this._core.scrollPages(p)}scrollToTop(){this._core.scrollToTop()}scrollToBottom(){this._core.scrollToBottom()}scrollToLine(p){this._verifyIntegers(p),this._core.scrollToLine(p)}clear(){this._core.clear()}write(p,l){this._core.write(p,l)}writeln(p,l){this._core.write(p),this._core.write(`\r
|
|
405
|
-
`,l)}paste(p){this._core.paste(p)}refresh(p,l){this._verifyIntegers(p,l),this._core.refresh(p,l)}reset(){this._core.reset()}clearTextureAtlas(){this._core.clearTextureAtlas()}loadAddon(p){this._addonManager.loadAddon(this,p)}static get strings(){return n}_verifyIntegers(...p){for(const l of p)if(l===1/0||isNaN(l)||l%1!=0)throw new Error("This API only accepts integers")}_verifyPositiveIntegers(...p){for(const l of p)if(l&&(l===1/0||isNaN(l)||l%1!=0||l<0))throw new Error("This API only accepts positive integers")}}b.Terminal=y})(),g})()))})(Sr)),Sr.exports}var Ch=kh();const Er={background:"#ffffff",foreground:"#1e1e1e",cursor:"#1e1e1e",cursorAccent:"#ffffff",selectionBackground:"#add6ff80",black:"#000000",red:"#cd3131",green:"#00bc00",yellow:"#949800",blue:"#0451a5",magenta:"#bc05bc",cyan:"#0598bc",white:"#555555",brightBlack:"#666666",brightRed:"#cd3131",brightGreen:"#14ce14",brightYellow:"#b5ba00",brightBlue:"#0451a5",brightMagenta:"#bc05bc",brightCyan:"#0598bc",brightWhite:"#a5a5a5"},xr={background:"#121212",foreground:"#cccccc",cursor:"#cccccc",cursorAccent:"#121212",selectionBackground:"#264f7880",black:"#000000",red:"#f44747",green:"#6a9955",yellow:"#d7ba7d",blue:"#569cd6",magenta:"#c586c0",cyan:"#4ec9b0",white:"#d4d4d4",brightBlack:"#808080",brightRed:"#f44747",brightGreen:"#6a9955",brightYellow:"#d7ba7d",brightBlue:"#569cd6",brightMagenta:"#c586c0",brightCyan:"#4ec9b0",brightWhite:"#e5e5e5"},Th=25e3,Ah=2e3;function Jo(){const e=Ht(),t={"Content-Type":"application/json"};return e&&(t.Authorization=`Bearer ${e}`),t}function Rh(e){const t=window.location.protocol==="https:"?"wss:":"ws:",r=window.location.host,i=Ht(),a=i?`?password=${encodeURIComponent(i)}`:"";return`${t}//${r}/pty
|
|
405
|
+
`,l)}paste(p){this._core.paste(p)}refresh(p,l){this._verifyIntegers(p,l),this._core.refresh(p,l)}reset(){this._core.reset()}clearTextureAtlas(){this._core.clearTextureAtlas()}loadAddon(p){this._addonManager.loadAddon(this,p)}static get strings(){return n}_verifyIntegers(...p){for(const l of p)if(l===1/0||isNaN(l)||l%1!=0)throw new Error("This API only accepts integers")}_verifyPositiveIntegers(...p){for(const l of p)if(l&&(l===1/0||isNaN(l)||l%1!=0||l<0))throw new Error("This API only accepts positive integers")}}b.Terminal=y})(),g})()))})(Sr)),Sr.exports}var Ch=kh();const Er={background:"#ffffff",foreground:"#1e1e1e",cursor:"#1e1e1e",cursorAccent:"#ffffff",selectionBackground:"#add6ff80",black:"#000000",red:"#cd3131",green:"#00bc00",yellow:"#949800",blue:"#0451a5",magenta:"#bc05bc",cyan:"#0598bc",white:"#555555",brightBlack:"#666666",brightRed:"#cd3131",brightGreen:"#14ce14",brightYellow:"#b5ba00",brightBlue:"#0451a5",brightMagenta:"#bc05bc",brightCyan:"#0598bc",brightWhite:"#a5a5a5"},xr={background:"#121212",foreground:"#cccccc",cursor:"#cccccc",cursorAccent:"#121212",selectionBackground:"#264f7880",black:"#000000",red:"#f44747",green:"#6a9955",yellow:"#d7ba7d",blue:"#569cd6",magenta:"#c586c0",cyan:"#4ec9b0",white:"#d4d4d4",brightBlack:"#808080",brightRed:"#f44747",brightGreen:"#6a9955",brightYellow:"#d7ba7d",brightBlue:"#569cd6",brightMagenta:"#c586c0",brightCyan:"#4ec9b0",brightWhite:"#e5e5e5"},Th=25e3,Ah=2e3;function Jo(){const e=Ht(),t={"Content-Type":"application/json"};return e&&(t.Authorization=`Bearer ${e}`),t}function Rh(e){const t=window.location.protocol==="https:"?"wss:":"ws:",r=window.location.host,i=Ht(),a=i?`?password=${encodeURIComponent(i)}`:"";return`${t}//${r}/api/v1/pty/${e}/ws${a}`}async function ql(e){try{return(await fetch(`/api/v1/pty/${e}`,{headers:Jo()})).ok}catch{return!1}}async function Vl(e,t){const r=await fetch("/api/v1/pty",{method:"POST",headers:Jo(),body:JSON.stringify({cols:e,rows:t})});if(!r.ok){const i=await r.json().catch(()=>({error:"Unknown error"}));throw new Error(i.error||`HTTP ${r.status}`)}return r.json()}async function Nh(){try{const e=await fetch("/api/v1/pty",{headers:Jo()});return e.ok?(await e.json()).sessions||[]:[]}catch{return[]}}function Ih(e){const t=me.getState().panes,r=new Set;for(const[i,a]of Object.entries(t))i!==e&&a.ptySessionId&&r.add(a.ptySessionId);return r}function Lh({paneId:e}){const{t}=ue(),{resolved:r}=Ot(),i=me(M=>M.panes[e]),a=me(M=>M.activePaneId),g=me(M=>M.layout),b=me(M=>M.mainView),n=me(M=>M.setActivePaneId),o=me(M=>M.closePane),d=me(M=>M.setPaneSession),f=me(M=>M.setPaneStatus),h=me(M=>M.setPaneError),_=me(M=>M.setTerminalTitle),S=a===e,w=ft(g),y=O.useRef(null),c=O.useRef(null),p=O.useRef(null),l=O.useRef(null),u=O.useRef(null),m=O.useRef(!0),x=O.useRef(!1),v=O.useRef(!1),k=O.useRef(null),E=O.useCallback(()=>{u.current&&(clearInterval(u.current),u.current=null);const M=l.current;M&&(M.onopen=null,M.onmessage=null,M.onclose=null,M.onerror=null,(M.readyState===WebSocket.OPEN||M.readyState===WebSocket.CONNECTING)&&M.close(1e3,"Cleanup"),l.current=null)},[]),C=O.useCallback((M,H)=>{E(),f(e,"connecting");const z=Rh(H),G=new WebSocket(z);l.current=G,G.onopen=()=>{if(!m.current)return;f(e,"connected"),h(e,null);const j=p.current;if(j)try{j.fit(),G.send(JSON.stringify({type:"resize",cols:M.cols,rows:M.rows}))}catch{}u.current=setInterval(()=>{G.readyState===WebSocket.OPEN&&G.send(JSON.stringify({type:"ping"}))},Th),M.focus()},G.onmessage=j=>{if(m.current)try{const q=JSON.parse(j.data);switch(q.type){case"output":M.write(q.data);break;case"exit":d(e,null),f(e,"disconnected"),v.current=!1,M.write(`\r
|
|
406
406
|
${t("terminal.processExited")}\r
|
|
407
|
-
`);break;case"error":h(e,q.message);break;case"pong":break}}catch{}},G.onclose=j=>{m.current&&(u.current&&(clearInterval(u.current),u.current=null),j.code!==1e3&&j.code!==1001&&(f(e,"error"),h(e,j.reason||t("terminal.connectionLost"))))},G.onerror=()=>{m.current&&(f(e,"error"),h(e,t("terminal.wsConnectionFailed")))};const T=M.onData(j=>{G.readyState===WebSocket.OPEN&&G.send(JSON.stringify({type:"input",data:j}))}),D=M.onResize(({cols:j,rows:q})=>{G.readyState===WebSocket.OPEN&&G.send(JSON.stringify({type:"resize",cols:j,rows:q}))});v.current=!0;const P=()=>{T.dispose(),D.dispose(),E()};return k.current=P,P},[E,e,d,f,h]),N=O.useCallback(()=>{const M=y.current;if(!M||x.current)return;const H=r==="dark"?xr:Er;for(;M.firstChild;)M.removeChild(M.firstChild);const z=new Ch.Terminal({cursorBlink:!0,fontSize:14,fontFamily:'Menlo, Monaco, "Courier New", monospace',theme:H,allowProposedApi:!0,scrollback:1e4}),G=new wh.FitAddon;z.loadAddon(G),z.open(M);const T=M.querySelector(".xterm-helper-textarea");T&&(T.setAttribute("autocomplete","off"),T.setAttribute("autocorrect","off"),T.setAttribute("autocapitalize","off"),T.setAttribute("spellcheck","false"),T.setAttribute("unselectable","on")),c.current=z,p.current=G,x.current=!0;const D=z.onTitleChange(K=>{m.current&&_(K||null)});let P=null;const j=()=>{P&&clearTimeout(P),P=setTimeout(()=>{if(m.current)try{G.fit()}catch{}},50)},q=new ResizeObserver(j);return q.observe(M),window.addEventListener("resize",j),()=>{D.dispose(),q.disconnect(),window.removeEventListener("resize",j),P&&clearTimeout(P)}},[]),R=O.useCallback(async()=>{var q;const M=c.current,H=p.current;if(!M||!H||!m.current||v.current)return;try{H.fit()}catch{}const z=M.cols||80,G=M.rows||24,T=(q=me.getState().panes[e])==null?void 0:q.ptySessionId;if(T&&await ql(T)&&m.current){C(M,T);return}if(!m.current)return;const D=Ih(e),j=(await Nh()).find(K=>!K.hasClient&&!D.has(K.id));if(j&&m.current){d(e,j.id),C(M,j.id);return}if(m.current){f(e,"connecting");try{const{sessionId:K}=await Vl(z,G);if(!m.current)return;d(e,K),C(M,K)}catch(K){if(!m.current)return;f(e,"error"),h(e,K.message||t("terminal.createSessionFailed"))}}},[C,e,d,f,h]),B=O.useRef(null);O.useEffect(()=>{m.current=!0;const M=y.current;if(!M)return;const H=()=>{if(!m.current)return;const{clientWidth:G,clientHeight:T}=M;if(!(G===0||T===0)&&(x.current||(B.current=N()||null),c.current&&p.current)){try{p.current.fit()}catch{}v.current||R()}};if(M.clientWidth>0&&M.clientHeight>0){const G=requestAnimationFrame(H);return()=>cancelAnimationFrame(G)}const z=new ResizeObserver(G=>{for(const T of G){const{width:D,height:P}=T.contentRect;if(D>0&&P>0){z.disconnect(),H();break}}});return z.observe(M),()=>z.disconnect()},[N,R]),O.useEffect(()=>()=>{var M,H,z;m.current=!1,(M=k.current)==null||M.call(k),(H=B.current)==null||H.call(B),(z=c.current)==null||z.dispose(),c.current=null,p.current=null,x.current=!1,v.current=!1},[]),O.useEffect(()=>{const M=c.current;if(M){const H=r==="dark"?xr:Er;M.options.theme=H;try{M.refresh(0,M.rows-1)}catch{}}},[r,b]);const A=O.useCallback(async()=>{var H,z;if(E(),v.current=!1,f(e,"connecting"),h(e,null),await new Promise(G=>setTimeout(G,Ah)),!m.current)return;const M=c.current;if(M)try{M.clear();try{(H=p.current)==null||H.fit()}catch{}const G=M.cols||80,T=M.rows||24,D=(z=me.getState().panes[e])==null?void 0:z.ptySessionId;if(D&&await ql(D)&&m.current){C(M,D);return}if(!m.current)return;const{sessionId:P}=await Vl(G,T);if(!m.current)return;d(e,P),C(M,P)}catch(G){if(!m.current)return;f(e,"error"),h(e,G.message||t("terminal.reconnectFailed"))}},[E,C,e,d,f,h]),F=O.useCallback(()=>{var M;S||n(e),(M=c.current)==null||M.focus()},[S,e,n]);return i?s.jsxs("div",{className:`terminal-pane flex flex-col h-full w-full ${S&&w>1?"active":""}`,style:{backgroundColor:r==="dark"?xr.background:Er.background},onClick:F,children:[w>1&&s.jsx("div",{className:"terminal-pane-toolbar",children:s.jsx("button",{onClick:M=>{M.stopPropagation(),o(e)},className:"w-6 h-6 flex items-center justify-center rounded bg-bg-tertiary/80 text-text-secondary hover:text-text-primary hover:bg-bg-hover transition-colors",title:t("terminal.closePane"),children:s.jsx(Ie,{size:14})})}),s.jsx("div",{ref:y,className:"flex-1 w-full",style:{overflow:"hidden",padding:"4px"}}),i.ptyStatus==="connecting"&&s.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-bg-primary/80 z-10",children:s.jsx(lt,{size:"small",text:t("terminal.connecting")})}),i.ptyStatus==="error"&&s.jsxs("div",{className:"absolute bottom-0 left-0 right-0 flex items-center justify-between px-4 py-2 bg-accent-red/10 border-t border-accent-red/30 z-10",children:[s.jsxs("div",{className:"flex items-center gap-2 text-accent-red text-xs",children:[s.jsx(Dd,{size:14}),s.jsx("span",{children:i.errorMessage||t("terminal.error")})]}),s.jsxs("button",{onClick:A,className:"flex items-center gap-1.5 px-3 py-1 rounded-md bg-bg-secondary border border-border-muted text-text-primary text-xs hover:bg-bg-hover transition-colors",children:[s.jsx(Dt,{size:12}),s.jsx("span",{children:t("terminal.reconnect")})]})]})]}):s.jsx("div",{})}function zr({node:e,path:t}){const r=me(a=>a.setRatio),i=O.useCallback(a=>{r(t,a)},[r,t]);return e.type==="leaf"?s.jsx(Lh,{paneId:e.paneId}):s.jsxs(Eh,{direction:e.direction,ratio:e.ratio,onRatioChange:i,children:[s.jsx(zr,{node:e.children[0],path:[...t,0]}),s.jsx(zr,{node:e.children[1],path:[...t,1]})]})}function rd(){const e=me(t=>t.layout);return s.jsx("div",{className:"flex-1 w-full h-full overflow-hidden",children:s.jsx(zr,{node:e,path:[]})})}function Oh({isOpen:e,onClose:t,onImageSelect:r,onFileSelect:i,onNewChat:a,onHistory:g,mainView:b}){const{t:n}=ue(),o=O.useRef(null),[d,f]=O.useState(null),[h,_]=O.useState(0),S=O.useCallback(()=>{r(),t()},[r,t]),w=O.useCallback(()=>{i(),t()},[i,t]),y=[{type:"attachment",icon:s.jsx(dc,{size:22}),label:n("input.menu.image"),action:S},{type:"attachment",icon:s.jsx(tt,{size:22}),label:n("input.menu.file"),action:w},{type:"action",icon:s.jsx(Ke,{size:20}),label:n("chat.newChat"),action:a},{type:"action",icon:s.jsx(cc,{size:20}),label:n("sidebar.chatHistory"),action:g},{type:"nav",view:"instances",icon:s.jsx(ct,{size:20}),label:n("sidebar.instances")},{type:"nav",view:"tasks",icon:s.jsx(uc,{size:20}),label:n("sidebar.nav.tasks")},{type:"nav",view:"terminal",icon:s.jsx(mc,{size:20}),label:n("sidebar.terminalMode")},{type:"nav",view:"plugins",icon:s.jsx(gt,{size:20}),label:n("sidebar.nav.plugins")},{type:"nav",view:"settings",icon:s.jsx(fc,{size:20}),label:n("sidebar.preferences")}].filter(x=>!(x.type==="action"&&!x.action)),c=8,p=Math.ceil(y.length/c),l=[];for(let x=0;x<p;x++)l.push(y.slice(x*c,(x+1)*c));O.useEffect(()=>{const x=o.current;if(!x)return;const v=()=>{const k=x.clientWidth;if(k>0){const E=Math.round(x.scrollLeft/k);_(E)}};return x.addEventListener("scroll",v,{passive:!0}),()=>x.removeEventListener("scroll",v)},[]);const u=O.useCallback(x=>{const v=o.current;v&&v.scrollTo({left:x*v.clientWidth,behavior:"smooth"})},[]),m=O.useCallback(()=>{f(null)},[]);return e?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"bottom-sheet-inline",children:[s.jsx("div",{ref:o,className:"bottom-sheet-scroll",children:l.map((x,v)=>s.jsx("div",{className:"bottom-sheet-page",children:s.jsx("div",{className:"bottom-sheet-grid",children:x.map((k,E)=>s.jsxs("button",{className:k.type==="nav"&&b===k.view?"active":"",onClick:()=>{var C;k.type==="attachment"||k.type==="action"?(C=k.action)==null||C.call(k):k.type==="nav"&&k.view&&f(k.view)},children:[k.icon,s.jsx("span",{children:k.label})]},E))})},v))}),p>1&&s.jsx("div",{className:"bottom-sheet-pagination",children:Array.from({length:p}).map((x,v)=>s.jsx("button",{className:`pagination-dot ${v===h?"active":""}`,onClick:()=>u(v)},v))})]}),d&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"floating-panel-overlay",onClick:m}),s.jsxs("div",{className:"floating-panel-container",children:[s.jsx("div",{className:"floating-panel-header",children:s.jsx("button",{onClick:m,className:"floating-panel-close-btn",title:"Close",children:s.jsx(Ie,{size:24})})}),s.jsxs("div",{className:"floating-panel-content",children:[d==="instances"&&s.jsx(Xc,{}),d==="tasks"&&s.jsx(ed,{}),d==="terminal"&&s.jsx(rd,{}),d==="plugins"&&s.jsx(Zc,{}),d==="settings"&&s.jsx(Jc,{})]})]})]})]}):null}const Dh=5,nd=10*1024*1024,Tt=["image/jpeg","image/png","image/gif","image/webp"];let Mh=0;function Bh(e){return!Tt.includes(e.type)||e.size>nd?Promise.resolve(null):new Promise(t=>{const r=new FileReader;r.onload=()=>{const i=r.result,a=i.split(",")[1]||"";t({id:`img-${++Mh}`,dataUrl:i,data:a,mimeType:e.type})},r.onerror=()=>t(null),r.readAsDataURL(e)})}const Fh=10,Ph=1*1024*1024,jh=new Set([".txt",".md",".markdown",".json",".jsonl",".yaml",".yml",".toml",".xml",".html",".htm",".css",".scss",".less",".js",".jsx",".ts",".tsx",".mjs",".cjs",".py",".rb",".go",".rs",".java",".kt",".swift",".c",".cpp",".h",".hpp",".sh",".bash",".zsh",".fish",".ps1",".bat",".cmd",".sql",".graphql",".gql",".env",".ini",".cfg",".conf",".properties",".csv",".tsv",".log",".dockerfile",".makefile",".cmake",".gitignore",".gitattributes",".editorconfig",".vue",".svelte",".astro"]);let Uh=0;function id(e){if(e.type.startsWith("text/")||e.type==="application/json"||e.type==="application/xml"||e.type==="application/javascript")return!0;const t=e.name.toLowerCase(),r=t.lastIndexOf(".");if(r!==-1){const a=t.slice(r);if(jh.has(a))return!0}const i=t.split("/").pop()||t;return!!["makefile","dockerfile","cmakelists.txt","gemfile","rakefile","procfile"].includes(i)}function $h(e){return!id(e)||e.size>Ph?Promise.resolve(null):new Promise(t=>{const r=new FileReader;r.onload=()=>{const i=r.result;t({id:`file-${++Uh}`,name:e.name,size:e.size,text:i,mimeType:e.type||"text/plain"})},r.onerror=()=>t(null),r.readAsText(e)})}function Hh(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function zh({onNavigate:e,onNewChat:t,onHistory:r,mainView:i,showBottomSheet:a=!1,setShowBottomSheet:g}){const b=O.useCallback($=>{g&&g(typeof $=="function"?$(a):$)},[g,a]),[n,o]=O.useState(""),[d,f]=O.useState([]),[h,_]=O.useState([]),[S,w]=O.useState(0),[y,c]=O.useState(!1),[p,l]=O.useState(null),[u,m]=O.useState(0),[x,v]=O.useState([]),[k,E]=O.useState(0),[C,N]=O.useState(null),R=O.useRef(null),B=O.useRef(null),A=O.useRef(null),F=O.useRef(null),M=O.useRef(null),H=O.useRef(null),z=O.useRef(0),G=O.useRef(!1),{sessionId:T,commands:D,thinkingEnabled:P,setThinkingEnabled:j,promptSuggestion:q,setPromptSuggestion:K,externalInput:re,setExternalInput:J}=Xe(),{isAgentRunning:U,hasPendingInterruption:I,timeline:V,addUserMessage:W,addQueuedUserMessage:Q,setSessionEnd:Z,resolveInterruption:ae}=Le(),{t:oe}=ue();O.useEffect(()=>{re!==null&&(o(re),J(null),K(null),requestAnimationFrame(()=>{var $;($=R.current)==null||$.focus()}))},[re,J,K]);const ee=O.useCallback(async $=>{const X=Array.from($).filter(ce=>Tt.includes(ce.type)&&ce.size<=nd);if(X.length===0)return;w(ce=>ce+X.length);const ge=(await Promise.all(X.map(Bh))).filter(ce=>ce!==null);w(ce=>Math.max(0,ce-X.length)),ge.length>0&&f(ce=>{const Ee=Dh-ce.length;return[...ce,...ge.slice(0,Ee)]})},[]),de=O.useCallback($=>{f(X=>X.filter(se=>se.id!==$))},[]),ne=O.useCallback(async $=>{const X=Array.from($),ge=(await Promise.all(X.map($h))).filter(ce=>ce!==null);ge.length!==0&&_(ce=>{const Ee=Fh-ce.length;return[...ce,...ge.slice(0,Ee)]})},[]),qe=O.useCallback($=>{_(X=>X.filter(se=>se.id!==$))},[]),rt=O.useCallback($=>{var X;$.preventDefault(),$.stopPropagation(),z.current++,(X=$.dataTransfer)!=null&&X.types.includes("Files")&&c(!0)},[]),nt=O.useCallback($=>{$.preventDefault(),$.stopPropagation(),z.current--,z.current===0&&c(!1)},[]),Ze=O.useCallback($=>{$.preventDefault(),$.stopPropagation()},[]),Ue=O.useCallback($=>{var X;if($.preventDefault(),$.stopPropagation(),z.current=0,c(!1),(X=$.dataTransfer)!=null&&X.files){const se=Array.from($.dataTransfer.files),ge=se.filter(Ee=>Tt.includes(Ee.type)),ce=se.filter(Ee=>!Tt.includes(Ee.type)&&id(Ee));ge.length>0&&ee(ge),ce.length>0&&ne(ce)}},[ee,ne]),be=O.useCallback($=>{var se;const X=(se=$.clipboardData)==null?void 0:se.files;X&&X.length>0&&Array.from(X).some(ce=>Tt.includes(ce.type))&&($.preventDefault(),ee(X))},[ee]),Ve=O.useCallback(()=>{var $;($=B.current)==null||$.click()},[]),Y=O.useCallback(()=>{var $;($=A.current)==null||$.click()},[]),ie=O.useCallback($=>{$.target.files&&ee($.target.files),$.target.value=""},[ee]),_e=O.useCallback($=>{$.target.files&&ne($.target.files),$.target.value=""},[ne]),Se=O.useMemo(()=>{const $=n.trimStart();if(!$.startsWith("/")||$.includes(" "))return[];const X=$.substring(1).toLowerCase();return D.filter(se=>se.name.toLowerCase().includes(X)||se.description.toLowerCase().includes(X)).slice(0,8)},[n,D]),Pe=Se.length>0;O.useEffect(()=>{m(0)},[Se.length]),O.useEffect(()=>{if(Pe&&F.current){const $=F.current.children[u];$==null||$.scrollIntoView({block:"nearest"})}},[u,Pe]);const Re=O.useMemo(()=>{if(C===null)return null;const $=n.substring(C+1),X=$.search(/\s/),se=X===-1?$:$.substring(0,X);return X===0?null:se},[n,C]),Me=Re!==null&&x.length>0,pe=O.useRef(null);O.useEffect(()=>{if(Re===null){v([]);return}return pe.current&&clearTimeout(pe.current),pe.current=setTimeout(async()=>{try{const $=new URLSearchParams;Re&&$.set("query",Re),$.set("limit","15");const X=await fetch(`/api/files/suggest?${$.toString()}`);if(X.ok){const se=await X.json();v(se.items||[]),E(0)}else v([])}catch{v([])}},150),()=>{pe.current&&clearTimeout(pe.current)}},[Re]),O.useEffect(()=>{if(Me&&M.current){const $=M.current.children[k];$==null||$.scrollIntoView({block:"nearest"})}},[k,Me]);const Et=O.useRef(!1),pr=O.useCallback($=>{if(C===null)return;const X=n.substring(0,C),se=n.substring(C+1),ge=se.search(/\s/),ce=ge===-1?"":se.substring(ge),$e=ce.length===0||!/^\s/.test(ce)?" ":"",st=`${X}@${$.path}${$e}${ce}`,xt=X.length+1+$.path.length+$e.length;o(st),v([]),N(null),Et.current=!0,requestAnimationFrame(()=>{const ut=R.current;ut&&(ut.focus(),ut.setSelectionRange(xt,xt))})},[n,C]);O.useEffect(()=>{var X;!(window.innerWidth<=768)&&!U&&((X=R.current)==null||X.focus())},[U]),O.useEffect(()=>{const $=R.current;if($){$.style.height="auto";const X=window.innerHeight*.2,se=Math.min($.scrollHeight,X);$.style.height=`${se}px`,$.style.overflowY=$.scrollHeight>X?"auto":"hidden"}},[n]);const hr=O.useCallback($=>{var X;o(`/${$.name} `),(X=R.current)==null||X.focus()},[]),it=O.useCallback(async $=>{var tl;const X=($??n).trim(),se=d.length>0,ge=h.length>0;if(!X&&!(se||ge)||!T||I)return;o(""),K(null);const Ee=[...d],$e=[...h];f([]),_([]);const st=Ee.length>0?Ee.map(fe=>({data:fe.data,mimeType:fe.mimeType})):void 0,xt=$e.length>0?$e.map(fe=>({name:fe.name,text:fe.text,mimeType:fe.mimeType})):void 0,ut=$e.length>0?$e.map(fe=>({name:fe.name,size:fe.size,mimeType:fe.mimeType})):void 0;if((tl=R.current)==null||tl.blur(),U)Q(X,st,ut),xe().prompt(T,X,st,xt).catch(fe=>{console.error("Queued prompt failed:",fe)});else{W(X,st,ut);try{const fe=await xe().prompt(T,X,st,xt);Z(fe.stopReason,fe.errorMessage)}catch(fe){console.error("Prompt failed:",fe),Z("error",fe instanceof Error?fe.message:oe("input.promptFailed"))}}},[n,d,h,T,U,I,W,Q,Z,K,oe]),ad=O.useCallback(async()=>{if(T)try{const $=xe(),X=V.filter(se=>se.type==="interruption"&&!se.resolved);for(const se of X)if(se.type==="interruption")try{await $.approveInterruption(T,se.id,"deny"),ae(se.id,"deny")}catch{}await $.cancel(T)}catch($){console.error("Cancel failed:",$)}},[T,V,ae]),od=O.useCallback(()=>{G.current=!0},[]),ld=O.useCallback(()=>{G.current=!1},[]),cd=O.useCallback($=>{$.preventDefault(),l({x:$.clientX,y:$.clientY})},[]),dd=O.useCallback(()=>{const $=R.current;if(!$)return;const X=$.selectionStart??n.length,se=$.selectionEnd??X,ge=n.slice(0,X)+`
|
|
407
|
+
`);break;case"error":h(e,q.message);break;case"pong":break}}catch{}},G.onclose=j=>{m.current&&(u.current&&(clearInterval(u.current),u.current=null),j.code!==1e3&&j.code!==1001&&(f(e,"error"),h(e,j.reason||t("terminal.connectionLost"))))},G.onerror=()=>{m.current&&(f(e,"error"),h(e,t("terminal.wsConnectionFailed")))};const T=M.onData(j=>{G.readyState===WebSocket.OPEN&&G.send(JSON.stringify({type:"input",data:j}))}),D=M.onResize(({cols:j,rows:q})=>{G.readyState===WebSocket.OPEN&&G.send(JSON.stringify({type:"resize",cols:j,rows:q}))});v.current=!0;const P=()=>{T.dispose(),D.dispose(),E()};return k.current=P,P},[E,e,d,f,h]),N=O.useCallback(()=>{const M=y.current;if(!M||x.current)return;const H=r==="dark"?xr:Er;for(;M.firstChild;)M.removeChild(M.firstChild);const z=new Ch.Terminal({cursorBlink:!0,fontSize:14,fontFamily:'Menlo, Monaco, "Courier New", monospace',theme:H,allowProposedApi:!0,scrollback:1e4}),G=new wh.FitAddon;z.loadAddon(G),z.open(M);const T=M.querySelector(".xterm-helper-textarea");T&&(T.setAttribute("autocomplete","off"),T.setAttribute("autocorrect","off"),T.setAttribute("autocapitalize","off"),T.setAttribute("spellcheck","false"),T.setAttribute("unselectable","on")),c.current=z,p.current=G,x.current=!0;const D=z.onTitleChange(K=>{m.current&&_(K||null)});let P=null;const j=()=>{P&&clearTimeout(P),P=setTimeout(()=>{if(m.current)try{G.fit()}catch{}},50)},q=new ResizeObserver(j);return q.observe(M),window.addEventListener("resize",j),()=>{D.dispose(),q.disconnect(),window.removeEventListener("resize",j),P&&clearTimeout(P)}},[]),R=O.useCallback(async()=>{var q;const M=c.current,H=p.current;if(!M||!H||!m.current||v.current)return;try{H.fit()}catch{}const z=M.cols||80,G=M.rows||24,T=(q=me.getState().panes[e])==null?void 0:q.ptySessionId;if(T&&await ql(T)&&m.current){C(M,T);return}if(!m.current)return;const D=Ih(e),j=(await Nh()).find(K=>!K.hasClient&&!D.has(K.id));if(j&&m.current){d(e,j.id),C(M,j.id);return}if(m.current){f(e,"connecting");try{const{sessionId:K}=await Vl(z,G);if(!m.current)return;d(e,K),C(M,K)}catch(K){if(!m.current)return;f(e,"error"),h(e,K.message||t("terminal.createSessionFailed"))}}},[C,e,d,f,h]),B=O.useRef(null);O.useEffect(()=>{m.current=!0;const M=y.current;if(!M)return;const H=()=>{if(!m.current)return;const{clientWidth:G,clientHeight:T}=M;if(!(G===0||T===0)&&(x.current||(B.current=N()||null),c.current&&p.current)){try{p.current.fit()}catch{}v.current||R()}};if(M.clientWidth>0&&M.clientHeight>0){const G=requestAnimationFrame(H);return()=>cancelAnimationFrame(G)}const z=new ResizeObserver(G=>{for(const T of G){const{width:D,height:P}=T.contentRect;if(D>0&&P>0){z.disconnect(),H();break}}});return z.observe(M),()=>z.disconnect()},[N,R]),O.useEffect(()=>()=>{var M,H,z;m.current=!1,(M=k.current)==null||M.call(k),(H=B.current)==null||H.call(B),(z=c.current)==null||z.dispose(),c.current=null,p.current=null,x.current=!1,v.current=!1},[]),O.useEffect(()=>{const M=c.current;if(M){const H=r==="dark"?xr:Er;M.options.theme=H;try{M.refresh(0,M.rows-1)}catch{}}},[r,b]);const A=O.useCallback(async()=>{var H,z;if(E(),v.current=!1,f(e,"connecting"),h(e,null),await new Promise(G=>setTimeout(G,Ah)),!m.current)return;const M=c.current;if(M)try{M.clear();try{(H=p.current)==null||H.fit()}catch{}const G=M.cols||80,T=M.rows||24,D=(z=me.getState().panes[e])==null?void 0:z.ptySessionId;if(D&&await ql(D)&&m.current){C(M,D);return}if(!m.current)return;const{sessionId:P}=await Vl(G,T);if(!m.current)return;d(e,P),C(M,P)}catch(G){if(!m.current)return;f(e,"error"),h(e,G.message||t("terminal.reconnectFailed"))}},[E,C,e,d,f,h]),F=O.useCallback(()=>{var M;S||n(e),(M=c.current)==null||M.focus()},[S,e,n]);return i?s.jsxs("div",{className:`terminal-pane flex flex-col h-full w-full ${S&&w>1?"active":""}`,style:{backgroundColor:r==="dark"?xr.background:Er.background},onClick:F,children:[w>1&&s.jsx("div",{className:"terminal-pane-toolbar",children:s.jsx("button",{onClick:M=>{M.stopPropagation(),o(e)},className:"w-6 h-6 flex items-center justify-center rounded bg-bg-tertiary/80 text-text-secondary hover:text-text-primary hover:bg-bg-hover transition-colors",title:t("terminal.closePane"),children:s.jsx(Ie,{size:14})})}),s.jsx("div",{ref:y,className:"flex-1 w-full",style:{overflow:"hidden",padding:"4px"}}),i.ptyStatus==="connecting"&&s.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-bg-primary/80 z-10",children:s.jsx(lt,{size:"small",text:t("terminal.connecting")})}),i.ptyStatus==="error"&&s.jsxs("div",{className:"absolute bottom-0 left-0 right-0 flex items-center justify-between px-4 py-2 bg-accent-red/10 border-t border-accent-red/30 z-10",children:[s.jsxs("div",{className:"flex items-center gap-2 text-accent-red text-xs",children:[s.jsx(Dd,{size:14}),s.jsx("span",{children:i.errorMessage||t("terminal.error")})]}),s.jsxs("button",{onClick:A,className:"flex items-center gap-1.5 px-3 py-1 rounded-md bg-bg-secondary border border-border-muted text-text-primary text-xs hover:bg-bg-hover transition-colors",children:[s.jsx(Dt,{size:12}),s.jsx("span",{children:t("terminal.reconnect")})]})]})]}):s.jsx("div",{})}function zr({node:e,path:t}){const r=me(a=>a.setRatio),i=O.useCallback(a=>{r(t,a)},[r,t]);return e.type==="leaf"?s.jsx(Lh,{paneId:e.paneId}):s.jsxs(Eh,{direction:e.direction,ratio:e.ratio,onRatioChange:i,children:[s.jsx(zr,{node:e.children[0],path:[...t,0]}),s.jsx(zr,{node:e.children[1],path:[...t,1]})]})}function rd(){const e=me(t=>t.layout);return s.jsx("div",{className:"flex-1 w-full h-full overflow-hidden",children:s.jsx(zr,{node:e,path:[]})})}function Oh({isOpen:e,onClose:t,onImageSelect:r,onFileSelect:i,onNewChat:a,onHistory:g,mainView:b}){const{t:n}=ue(),o=O.useRef(null),[d,f]=O.useState(null),[h,_]=O.useState(0),S=O.useCallback(()=>{r(),t()},[r,t]),w=O.useCallback(()=>{i(),t()},[i,t]),y=[{type:"attachment",icon:s.jsx(dc,{size:22}),label:n("input.menu.image"),action:S},{type:"attachment",icon:s.jsx(tt,{size:22}),label:n("input.menu.file"),action:w},{type:"action",icon:s.jsx(Ke,{size:20}),label:n("chat.newChat"),action:a},{type:"action",icon:s.jsx(cc,{size:20}),label:n("sidebar.chatHistory"),action:g},{type:"nav",view:"instances",icon:s.jsx(ct,{size:20}),label:n("sidebar.instances")},{type:"nav",view:"tasks",icon:s.jsx(uc,{size:20}),label:n("sidebar.nav.tasks")},{type:"nav",view:"terminal",icon:s.jsx(mc,{size:20}),label:n("sidebar.terminalMode")},{type:"nav",view:"plugins",icon:s.jsx(gt,{size:20}),label:n("sidebar.nav.plugins")},{type:"nav",view:"settings",icon:s.jsx(fc,{size:20}),label:n("sidebar.preferences")}].filter(x=>!(x.type==="action"&&!x.action)),c=8,p=Math.ceil(y.length/c),l=[];for(let x=0;x<p;x++)l.push(y.slice(x*c,(x+1)*c));O.useEffect(()=>{const x=o.current;if(!x)return;const v=()=>{const k=x.clientWidth;if(k>0){const E=Math.round(x.scrollLeft/k);_(E)}};return x.addEventListener("scroll",v,{passive:!0}),()=>x.removeEventListener("scroll",v)},[]);const u=O.useCallback(x=>{const v=o.current;v&&v.scrollTo({left:x*v.clientWidth,behavior:"smooth"})},[]),m=O.useCallback(()=>{f(null)},[]);return e?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"bottom-sheet-inline",children:[s.jsx("div",{ref:o,className:"bottom-sheet-scroll",children:l.map((x,v)=>s.jsx("div",{className:"bottom-sheet-page",children:s.jsx("div",{className:"bottom-sheet-grid",children:x.map((k,E)=>s.jsxs("button",{className:k.type==="nav"&&b===k.view?"active":"",onClick:()=>{var C;k.type==="attachment"||k.type==="action"?(C=k.action)==null||C.call(k):k.type==="nav"&&k.view&&f(k.view)},children:[k.icon,s.jsx("span",{children:k.label})]},E))})},v))}),p>1&&s.jsx("div",{className:"bottom-sheet-pagination",children:Array.from({length:p}).map((x,v)=>s.jsx("button",{className:`pagination-dot ${v===h?"active":""}`,onClick:()=>u(v)},v))})]}),d&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"floating-panel-overlay",onClick:m}),s.jsxs("div",{className:"floating-panel-container",children:[s.jsx("div",{className:"floating-panel-header",children:s.jsx("button",{onClick:m,className:"floating-panel-close-btn",title:"Close",children:s.jsx(Ie,{size:24})})}),s.jsxs("div",{className:"floating-panel-content",children:[d==="instances"&&s.jsx(Xc,{}),d==="tasks"&&s.jsx(ed,{}),d==="terminal"&&s.jsx(rd,{}),d==="plugins"&&s.jsx(Zc,{}),d==="settings"&&s.jsx(Jc,{})]})]})]})]}):null}const Dh=5,nd=10*1024*1024,Tt=["image/jpeg","image/png","image/gif","image/webp"];let Mh=0;function Bh(e){return!Tt.includes(e.type)||e.size>nd?Promise.resolve(null):new Promise(t=>{const r=new FileReader;r.onload=()=>{const i=r.result,a=i.split(",")[1]||"";t({id:`img-${++Mh}`,dataUrl:i,data:a,mimeType:e.type})},r.onerror=()=>t(null),r.readAsDataURL(e)})}const Fh=10,Ph=1*1024*1024,jh=new Set([".txt",".md",".markdown",".json",".jsonl",".yaml",".yml",".toml",".xml",".html",".htm",".css",".scss",".less",".js",".jsx",".ts",".tsx",".mjs",".cjs",".py",".rb",".go",".rs",".java",".kt",".swift",".c",".cpp",".h",".hpp",".sh",".bash",".zsh",".fish",".ps1",".bat",".cmd",".sql",".graphql",".gql",".env",".ini",".cfg",".conf",".properties",".csv",".tsv",".log",".dockerfile",".makefile",".cmake",".gitignore",".gitattributes",".editorconfig",".vue",".svelte",".astro"]);let Uh=0;function id(e){if(e.type.startsWith("text/")||e.type==="application/json"||e.type==="application/xml"||e.type==="application/javascript")return!0;const t=e.name.toLowerCase(),r=t.lastIndexOf(".");if(r!==-1){const a=t.slice(r);if(jh.has(a))return!0}const i=t.split("/").pop()||t;return!!["makefile","dockerfile","cmakelists.txt","gemfile","rakefile","procfile"].includes(i)}function $h(e){return!id(e)||e.size>Ph?Promise.resolve(null):new Promise(t=>{const r=new FileReader;r.onload=()=>{const i=r.result;t({id:`file-${++Uh}`,name:e.name,size:e.size,text:i,mimeType:e.type||"text/plain"})},r.onerror=()=>t(null),r.readAsText(e)})}function Hh(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function zh({onNavigate:e,onNewChat:t,onHistory:r,mainView:i,showBottomSheet:a=!1,setShowBottomSheet:g}){const b=O.useCallback($=>{g&&g(typeof $=="function"?$(a):$)},[g,a]),[n,o]=O.useState(""),[d,f]=O.useState([]),[h,_]=O.useState([]),[S,w]=O.useState(0),[y,c]=O.useState(!1),[p,l]=O.useState(null),[u,m]=O.useState(0),[x,v]=O.useState([]),[k,E]=O.useState(0),[C,N]=O.useState(null),R=O.useRef(null),B=O.useRef(null),A=O.useRef(null),F=O.useRef(null),M=O.useRef(null),H=O.useRef(null),z=O.useRef(0),G=O.useRef(!1),{sessionId:T,commands:D,thinkingEnabled:P,setThinkingEnabled:j,promptSuggestion:q,setPromptSuggestion:K,externalInput:re,setExternalInput:J}=Xe(),{isAgentRunning:U,hasPendingInterruption:I,timeline:V,addUserMessage:W,addQueuedUserMessage:Q,setSessionEnd:Z,resolveInterruption:ae}=Le(),{t:oe}=ue();O.useEffect(()=>{re!==null&&(o(re),J(null),K(null),requestAnimationFrame(()=>{var $;($=R.current)==null||$.focus()}))},[re,J,K]);const ee=O.useCallback(async $=>{const X=Array.from($).filter(ce=>Tt.includes(ce.type)&&ce.size<=nd);if(X.length===0)return;w(ce=>ce+X.length);const ge=(await Promise.all(X.map(Bh))).filter(ce=>ce!==null);w(ce=>Math.max(0,ce-X.length)),ge.length>0&&f(ce=>{const Ee=Dh-ce.length;return[...ce,...ge.slice(0,Ee)]})},[]),de=O.useCallback($=>{f(X=>X.filter(se=>se.id!==$))},[]),ne=O.useCallback(async $=>{const X=Array.from($),ge=(await Promise.all(X.map($h))).filter(ce=>ce!==null);ge.length!==0&&_(ce=>{const Ee=Fh-ce.length;return[...ce,...ge.slice(0,Ee)]})},[]),qe=O.useCallback($=>{_(X=>X.filter(se=>se.id!==$))},[]),rt=O.useCallback($=>{var X;$.preventDefault(),$.stopPropagation(),z.current++,(X=$.dataTransfer)!=null&&X.types.includes("Files")&&c(!0)},[]),nt=O.useCallback($=>{$.preventDefault(),$.stopPropagation(),z.current--,z.current===0&&c(!1)},[]),Ze=O.useCallback($=>{$.preventDefault(),$.stopPropagation()},[]),Ue=O.useCallback($=>{var X;if($.preventDefault(),$.stopPropagation(),z.current=0,c(!1),(X=$.dataTransfer)!=null&&X.files){const se=Array.from($.dataTransfer.files),ge=se.filter(Ee=>Tt.includes(Ee.type)),ce=se.filter(Ee=>!Tt.includes(Ee.type)&&id(Ee));ge.length>0&&ee(ge),ce.length>0&&ne(ce)}},[ee,ne]),be=O.useCallback($=>{var se;const X=(se=$.clipboardData)==null?void 0:se.files;X&&X.length>0&&Array.from(X).some(ce=>Tt.includes(ce.type))&&($.preventDefault(),ee(X))},[ee]),Ve=O.useCallback(()=>{var $;($=B.current)==null||$.click()},[]),Y=O.useCallback(()=>{var $;($=A.current)==null||$.click()},[]),ie=O.useCallback($=>{$.target.files&&ee($.target.files),$.target.value=""},[ee]),_e=O.useCallback($=>{$.target.files&&ne($.target.files),$.target.value=""},[ne]),Se=O.useMemo(()=>{const $=n.trimStart();if(!$.startsWith("/")||$.includes(" "))return[];const X=$.substring(1).toLowerCase();return D.filter(se=>se.name.toLowerCase().includes(X)||se.description.toLowerCase().includes(X)).slice(0,8)},[n,D]),Pe=Se.length>0;O.useEffect(()=>{m(0)},[Se.length]),O.useEffect(()=>{if(Pe&&F.current){const $=F.current.children[u];$==null||$.scrollIntoView({block:"nearest"})}},[u,Pe]);const Re=O.useMemo(()=>{if(C===null)return null;const $=n.substring(C+1),X=$.search(/\s/),se=X===-1?$:$.substring(0,X);return X===0?null:se},[n,C]),Me=Re!==null&&x.length>0,pe=O.useRef(null);O.useEffect(()=>{if(Re===null){v([]);return}return pe.current&&clearTimeout(pe.current),pe.current=setTimeout(async()=>{try{const $=new URLSearchParams;Re&&$.set("query",Re),$.set("limit","15");const X=await fetch(`/api/v1/files/suggest?${$.toString()}`);if(X.ok){const se=await X.json();v(se.items||[]),E(0)}else v([])}catch{v([])}},150),()=>{pe.current&&clearTimeout(pe.current)}},[Re]),O.useEffect(()=>{if(Me&&M.current){const $=M.current.children[k];$==null||$.scrollIntoView({block:"nearest"})}},[k,Me]);const Et=O.useRef(!1),pr=O.useCallback($=>{if(C===null)return;const X=n.substring(0,C),se=n.substring(C+1),ge=se.search(/\s/),ce=ge===-1?"":se.substring(ge),$e=ce.length===0||!/^\s/.test(ce)?" ":"",st=`${X}@${$.path}${$e}${ce}`,xt=X.length+1+$.path.length+$e.length;o(st),v([]),N(null),Et.current=!0,requestAnimationFrame(()=>{const ut=R.current;ut&&(ut.focus(),ut.setSelectionRange(xt,xt))})},[n,C]);O.useEffect(()=>{var X;!(window.innerWidth<=768)&&!U&&((X=R.current)==null||X.focus())},[U]),O.useEffect(()=>{const $=R.current;if($){$.style.height="auto";const X=window.innerHeight*.2,se=Math.min($.scrollHeight,X);$.style.height=`${se}px`,$.style.overflowY=$.scrollHeight>X?"auto":"hidden"}},[n]);const hr=O.useCallback($=>{var X;o(`/${$.name} `),(X=R.current)==null||X.focus()},[]),it=O.useCallback(async $=>{var tl;const X=($??n).trim(),se=d.length>0,ge=h.length>0;if(!X&&!(se||ge)||!T||I)return;o(""),K(null);const Ee=[...d],$e=[...h];f([]),_([]);const st=Ee.length>0?Ee.map(fe=>({data:fe.data,mimeType:fe.mimeType})):void 0,xt=$e.length>0?$e.map(fe=>({name:fe.name,text:fe.text,mimeType:fe.mimeType})):void 0,ut=$e.length>0?$e.map(fe=>({name:fe.name,size:fe.size,mimeType:fe.mimeType})):void 0;if((tl=R.current)==null||tl.blur(),U)Q(X,st,ut),xe().prompt(T,X,st,xt).catch(fe=>{console.error("Queued prompt failed:",fe)});else{W(X,st,ut);try{const fe=await xe().prompt(T,X,st,xt);Z(fe.stopReason,fe.errorMessage)}catch(fe){console.error("Prompt failed:",fe),Z("error",fe instanceof Error?fe.message:oe("input.promptFailed"))}}},[n,d,h,T,U,I,W,Q,Z,K,oe]),ad=O.useCallback(async()=>{if(T)try{const $=xe(),X=V.filter(se=>se.type==="interruption"&&!se.resolved);for(const se of X)if(se.type==="interruption")try{await $.approveInterruption(T,se.id,"deny"),ae(se.id,"deny")}catch{}await $.cancel(T)}catch($){console.error("Cancel failed:",$)}},[T,V,ae]),od=O.useCallback(()=>{G.current=!0},[]),ld=O.useCallback(()=>{G.current=!1},[]),cd=O.useCallback($=>{$.preventDefault(),l({x:$.clientX,y:$.clientY})},[]),dd=O.useCallback(()=>{const $=R.current;if(!$)return;const X=$.selectionStart??n.length,se=$.selectionEnd??X,ge=n.slice(0,X)+`
|
|
408
408
|
`+n.slice(se);o(ge),l(null),requestAnimationFrame(()=>{$.selectionStart=$.selectionEnd=X+1,$.focus()})},[n]),ud=O.useCallback(()=>{l(null),it()},[it]);O.useEffect(()=>{if(!p)return;const $=()=>l(null),X=()=>l(null);return document.addEventListener("mousedown",$),document.addEventListener("scroll",X,!0),()=>{document.removeEventListener("mousedown",$),document.removeEventListener("scroll",X,!0)}},[p]);const pd=O.useCallback($=>{if(Pe){if($.key==="ArrowUp"){$.preventDefault(),m(X=>X>0?X-1:Se.length-1);return}if($.key==="ArrowDown"){$.preventDefault(),m(X=>X<Se.length-1?X+1:0);return}if($.key==="Tab"||$.key==="Enter"&&!$.shiftKey&&!G.current&&!$.nativeEvent.isComposing){$.preventDefault(),hr(Se[u]);return}if($.key==="Escape"){$.preventDefault(),o("");return}}if(Me){if($.key==="ArrowUp"){$.preventDefault(),E(X=>X>0?X-1:x.length-1);return}if($.key==="ArrowDown"){$.preventDefault(),E(X=>X<x.length-1?X+1:0);return}if($.key==="Tab"||$.key==="Enter"&&!$.shiftKey&&!G.current&&!$.nativeEvent.isComposing){$.preventDefault(),pr(x[k]);return}if($.key==="Escape"){$.preventDefault(),N(null),v([]);return}}if($.key==="Tab"&&!Pe&&!Me&&q&&!n){$.preventDefault(),o(q),K(null);return}if($.key==="Enter"&&!$.shiftKey&&!G.current&&!$.nativeEvent.isComposing){if($.preventDefault(),!n&&q&&!U&&!I){it(q);return}it()}},[it,Pe,Se,u,hr,Me,x,k,pr,q,n,K,U,I]),hd=O.useCallback(async()=>{if(!T)return;const $=!P;j($);try{await xe().setConfigOption(T,"thought_level",$?"enabled":"disabled")}catch(X){j(!$),console.error("Toggle thinking failed:",X)}},[T,P,j]),el=!I&&(n.trim().length>0||d.length>0||h.length>0||!!q&&!n&&!U),gd=d.length>0||h.length>0||S>0;return s.jsx("div",{className:"px-0 pb-0 pt-0 md:px-4 md:pb-6 md:pt-2",children:s.jsxs("div",{className:"max-w-3xl mx-auto",children:[e&&i!==void 0&&s.jsx(Oh,{isOpen:a,onClose:()=>b(!1),onImageSelect:Ve,onFileSelect:Y,onNewChat:t,onHistory:r,mainView:i,onNavigate:e}),s.jsxs("div",{className:`relative bg-bg-secondary rounded-none md:rounded-2xl shadow-sm transition-all focus-within:shadow-md border-t md:border ${y?"border-accent-brand border-dashed bg-accent-brand/5":"border-border-default"}`,onDragEnter:rt,onDragLeave:nt,onDragOver:Ze,onDrop:Ue,children:[y&&s.jsx("div",{className:"absolute inset-0 z-20 rounded-2xl flex items-center justify-center bg-accent-brand/5 pointer-events-none",children:s.jsx("span",{className:"text-accent-brand text-[14px] font-medium",children:oe("input.dropHint")})}),Pe&&s.jsx("div",{ref:F,className:"absolute bottom-full left-3 right-3 mb-2 bg-bg-secondary rounded-xl border border-border-default shadow-lg max-h-[280px] overflow-y-auto z-10",children:Se.map(($,X)=>s.jsxs("button",{className:`w-full text-left px-4 py-2.5 flex items-baseline gap-3 transition-colors ${X===u?"bg-bg-primary text-text-primary":"text-text-primary hover:bg-bg-primary"}`,onMouseEnter:()=>m(X),onMouseDown:se=>{se.preventDefault(),hr($)},children:[s.jsxs("span",{className:"font-mono text-[13px] font-medium shrink-0",children:["/",$.name]}),$.type==="skill"&&s.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded bg-accent-brand/15 text-accent-brand font-medium shrink-0",children:"Skill"}),s.jsx("span",{className:"text-text-tertiary text-[12px] truncate",children:$.description})]},$.name))}),Me&&s.jsx("div",{ref:M,className:"absolute bottom-full left-3 right-3 mb-2 bg-bg-secondary rounded-xl border border-border-default shadow-lg max-h-[280px] overflow-y-auto z-10",children:x.map(($,X)=>s.jsxs("button",{className:`w-full text-left px-4 py-2.5 flex items-center gap-3 transition-colors ${X===k?"bg-bg-primary text-text-primary":"text-text-primary hover:bg-bg-primary"}`,onMouseEnter:()=>E(X),onMouseDown:se=>{se.preventDefault(),pr($)},children:[$.type==="directory"?s.jsx(lc,{size:14,className:"shrink-0 text-accent-brand"}):s.jsx(tt,{size:14,className:"shrink-0 text-text-tertiary"}),s.jsx("span",{className:"font-mono text-[13px] truncate",children:$.name}),s.jsx("span",{className:"text-text-tertiary text-[11px] truncate ml-auto",children:$.path})]},$.path))}),gd&&s.jsxs("div",{className:"px-4 pt-3 pb-1 flex flex-wrap gap-2",children:[d.map($=>s.jsxs("div",{className:"relative group",children:[s.jsx("img",{src:$.dataUrl,alt:"",className:"w-16 h-16 rounded-lg object-cover border border-border-default"}),s.jsx("button",{onClick:()=>de($.id),className:"absolute -top-1.5 -right-1.5 w-5 h-5 rounded-full bg-bg-tertiary border border-border-default flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity hover:bg-accent-red hover:border-accent-red hover:text-white",children:s.jsx(Ie,{size:12})})]},$.id)),Array.from({length:S}).map(($,X)=>s.jsx("div",{className:"w-16 h-16 rounded-lg border border-border-default skeleton-shimmer"},`skeleton-${X}`)),h.map($=>s.jsxs("div",{className:"relative group flex items-center gap-2 px-3 py-2 rounded-lg border border-border-default bg-bg-primary max-w-[200px]",children:[s.jsx(tt,{size:16,className:"shrink-0 text-text-tertiary"}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:"text-[12px] text-text-primary truncate",title:$.name,children:$.name}),s.jsx("div",{className:"text-[11px] text-text-tertiary",children:Hh($.size)})]}),s.jsx("button",{onClick:()=>qe($.id),className:"shrink-0 w-4 h-4 rounded-full flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity text-text-tertiary hover:text-accent-red",children:s.jsx(Ie,{size:12})})]},$.id))]}),s.jsxs("div",{className:"relative",children:[s.jsx("textarea",{ref:R,value:n,onChange:$=>{const X=$.target.value,se=$.target.selectionStart??X.length;if(o(X),Et.current){Et.current=!1;return}let ge=null;for(let ce=se-1;ce>=0;ce--){const Ee=X[ce];if(Ee==="@"){const $e=ce>0?X[ce-1]:" ";($e===" "||$e===`
|
|
409
409
|
`||ce===0)&&(X.substring(ce+1,se).includes(" ")||(ge=ce));break}if(Ee===" "||Ee===`
|
|
410
410
|
`)break}ge!==null?C!==ge&&(N(ge),E(0)):C!==null&&(N(null),v([]))},onCompositionStart:od,onCompositionEnd:ld,onKeyDown:pd,onPaste:be,onContextMenu:cd,onFocus:()=>b(!1),placeholder:I?oe("input.placeholderPending"):U?oe("input.placeholderRunning"):q?"":oe("input.placeholder"),enterKeyHint:"send",rows:1,className:["w-full bg-transparent text-text-primary text-[15px] px-5 pt-4 pb-2","resize-none outline-none placeholder:text-text-tertiary","leading-relaxed"].join(" ")}),q&&!n&&!U&&!I&&s.jsx("div",{className:"absolute inset-0 flex items-start px-5 pt-4 pb-2 pointer-events-none overflow-hidden",children:s.jsx("span",{className:"text-[15px] leading-relaxed text-text-tertiary truncate max-w-full",children:q})})]}),p&&s.jsxs("div",{ref:H,className:"fixed z-50 bg-bg-secondary rounded-xl border border-border-default shadow-lg overflow-hidden min-w-[120px]",style:{left:p.x,top:p.y},onMouseDown:$=>$.stopPropagation(),children:[s.jsxs("button",{className:"w-full text-left px-4 py-2.5 flex items-center gap-2.5 text-text-primary hover:bg-bg-primary transition-colors text-[13px]",onMouseDown:$=>{$.preventDefault(),$.stopPropagation(),dd()},children:[s.jsx(fl,{size:14,className:"text-text-tertiary"}),oe("input.contextMenu.newline")]}),el&&s.jsxs("button",{className:"w-full text-left px-4 py-2.5 flex items-center gap-2.5 text-text-primary hover:bg-bg-primary transition-colors text-[13px]",onMouseDown:$=>{$.preventDefault(),$.stopPropagation(),ud()},children:[s.jsx(pl,{size:14,className:"text-text-tertiary"}),oe("input.contextMenu.send")]})]}),s.jsx("input",{ref:B,type:"file",accept:"image/jpeg,image/png,image/gif,image/webp",multiple:!0,className:"hidden",onChange:ie}),s.jsx("input",{ref:A,type:"file",accept:".txt,.md,.json,.yaml,.yml,.toml,.xml,.html,.css,.scss,.js,.jsx,.ts,.tsx,.py,.rb,.go,.rs,.java,.kt,.swift,.c,.cpp,.h,.hpp,.sh,.bash,.sql,.csv,.tsv,.log,.env,.ini,.cfg,.conf,.vue,.svelte,.astro,.graphql,.gql,.makefile,.dockerfile,.gitignore,.editorconfig",multiple:!0,className:"hidden",onChange:_e}),s.jsxs("div",{className:"flex items-center justify-between px-3 py-2",onClick:$=>{var X;$.target===$.currentTarget&&((X=R.current)==null||X.focus())},children:[s.jsx("div",{className:"flex items-center",children:s.jsxs("button",{onClick:hd,className:`flex items-center gap-1 px-2.5 py-1 rounded-full border transition-colors ${P?"bg-text-primary border-text-primary text-bg-primary":"bg-bg-primary border-border-default text-text-tertiary hover:text-text-primary hover:bg-bg-primary"}`,children:[s.jsx("span",{className:"w-3.5 h-3.5 flex items-center justify-center text-[10px] font-semibold",children:"∞"}),s.jsx("span",{className:"text-[12px] font-medium",children:oe("input.deepThinking")})]})}),s.jsxs("div",{className:"flex items-center gap-1",children:[!U&&s.jsx("button",{onClick:()=>b($=>!$),className:"flex items-center justify-center w-8 h-8 rounded-full text-text-tertiary hover:text-text-primary hover:bg-bg-primary transition-colors",title:oe("input.addFile"),children:s.jsx(Ke,{size:18})}),s.jsx("button",{onClick:()=>{const $=R.current;if(!$)return;const X=$.selectionStart??n.length,se=$.selectionEnd??X,ge=n.slice(0,X)+`
|
|
411
|
-
`+n.slice(se);o(ge),requestAnimationFrame(()=>{$.selectionStart=$.selectionEnd=X+1,$.focus()})},className:"flex items-center justify-center w-8 h-8 rounded-full text-text-tertiary hover:text-text-primary hover:bg-bg-primary transition-colors",title:oe("input.newline"),children:s.jsx(fl,{size:15})}),U&&s.jsx("button",{onClick:ad,className:"flex items-center justify-center w-8 h-8 rounded-full text-text-tertiary hover:text-text-primary hover:bg-bg-primary transition-colors",title:oe("input.stop"),children:s.jsx(nu,{size:14,fill:"currentColor",strokeWidth:0})}),el&&s.jsx("button",{onClick:()=>{!n&&q&&!U?it(q):it()},className:"flex items-center justify-center w-8 h-8 rounded-full bg-text-primary text-bg-primary hover:scale-105 active:scale-95 shadow-sm transition-all",title:oe("input.send"),children:s.jsx(pl,{size:18,strokeWidth:2.5})})]})]})]})]})})}function Gh({children:e}){return s.jsx("code",{className:"bg-bg-tertiary px-1.5 py-0.5 rounded text-xs text-accent-brand",children:e})}function Kl(e){const t=[];let r=e,i=0;for(;r.length>0;){const a=r.indexOf("<code>");if(a===-1){t.push(s.jsx("span",{children:r},i));break}a>0&&(t.push(s.jsx("span",{children:r.substring(0,a)},i)),i++);const g=r.indexOf("</code>",a);if(g===-1){t.push(s.jsx("span",{children:r},i));break}const b=r.substring(a+6,g);t.push(s.jsx(Gh,{children:b},i)),i++,r=r.substring(g+7)}return s.jsx(s.Fragment,{children:t})}function Wh(){const{error:e,isSubmitting:t,login:r,clearError:i}=zc(),{t:a}=ue(),[g,b]=O.useState(""),n=O.useCallback(async d=>{d.preventDefault(),g.trim()&&await r(g)},[g,r]),o=e?a(e)!==e?a(e):e:null;return s.jsxs("div",{className:"login-page",children:[s.jsxs("div",{className:"login-orb login-orb-right",children:[s.jsx("div",{className:"login-orb-layer login-orb-layer-1"}),s.jsx("div",{className:"login-orb-layer login-orb-layer-2"})]}),s.jsx("div",{className:"login-ellipse login-ellipse-outer"}),s.jsx("div",{className:"login-ellipse login-ellipse-outer2"}),s.jsx("div",{className:"login-ellipse login-ellipse-inner"}),s.jsxs("div",{className:"login-orb login-orb-left",children:[s.jsx("div",{className:"login-orb-layer login-orb-layer-1"}),s.jsx("div",{className:"login-orb-layer login-orb-layer-2"})]}),s.jsx("div",{className:"login-ellipse login-ellipse-left"}),s.jsx("div",{className:"login-ellipse login-ellipse-left2"}),s.jsxs("div",{className:"login-content",children:[s.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",gap:"16px"},children:[s.jsx("div",{className:"login-logo",children:s.jsx("img",{src:tc,alt:"CodeBuddy"})}),s.jsx("h1",{className:"login-title",children:a("login.slogan")}),s.jsx("p",{className:"login-tagline",children:a("login.tagline")})]}),s.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",gap:"4px"},children:[o&&s.jsx("div",{className:"login-error",style:{marginBottom:"8px"},children:o}),s.jsxs("form",{onSubmit:n,style:{display:"flex",flexDirection:"column",alignItems:"center",gap:"8px"},children:[s.jsx("input",{type:"password",name:"password",value:g,onChange:d=>{b(d.target.value),e&&i()},placeholder:a("login.placeholder"),autoFocus:!0,autoComplete:"current-password",disabled:t,className:"login-input"}),s.jsx("button",{type:"submit",disabled:t||!g.trim(),className:"login-btn",children:t?s.jsx("span",{className:"thinking-text",children:a("login.submit")}):a("login.submit")})]}),s.jsxs("div",{className:"login-hints",children:[s.jsx("p",{children:a("login.hint.password")}),s.jsx("p",{children:a("login.hint.urlAuth").includes("<code>")?Kl(a("login.hint.urlAuth")):a("login.hint.urlAuth")}),s.jsx("p",{children:a("login.hint.disable").includes("<code>")?Kl(a("login.hint.disable")):a("login.hint.disable")})]})]})]}),s.jsxs("div",{className:"login-footer",children:[s.jsx("a",{href:"#privacy",children:a("login.privacy")}),s.jsx("a",{href:"#terms",children:a("login.terms")})]})]})}const qh="chat",Yl=new Set(["chat","tasks","plugins","terminal","instances","remote-control","settings"]);function sd(){let t=window.location.hash.slice(1);t.startsWith("/")&&(t=t.slice(1));const r=t.split("?")[0]||"";if(Yl.has(r))return r;const i=r.split("/")[0];return Yl.has(i)?i:qh}function Xl(e){const t=new URLSearchParams(window.location.search),r=window.location.hash.slice(1),i=r.indexOf("?");i!==-1&&new URLSearchParams(r.slice(i+1)).forEach((n,o)=>{t.has(o)||t.set(o,n)});const a=t.toString(),g=a?`#/${e}?${a}`:`#/${e}`;window.location.hash=g}function Vh(e){const t=()=>{const r=sd();e(r)};return window.addEventListener("hashchange",t),()=>{window.removeEventListener("hashchange",t)}}function Zl(){const t=window.location.hash.slice(1).replace(/^\//,"").split("?")[0],r=t.indexOf("/");return r>0?t.slice(r+1):void 0}function Xt(e,t){const i=new URLSearchParams(window.location.search).toString(),a=i?`#/${e}/${t}?${i}`:`#/${e}/${t}`;window.location.hash=a}function Kh({onNavigate:e}){const{t}=ue(),[r,i]=O.useState(Zl);return O.useEffect(()=>{const a=()=>i(Zl());return window.addEventListener("hashchange",a),()=>window.removeEventListener("hashchange",a)},[]),r==="add-wechat"?s.jsx(Xh,{onBack:()=>Xl("remote-control"),t}):r==="add-wecom"?s.jsx(Zh,{onBack:()=>Xl("remote-control"),t}):s.jsx(Yh,{onNavigate:e,t})}function Yh({onNavigate:e,t}){const[r,i]=O.useState([]),[a,g]=O.useState(!0),[b,n]=O.useState(null),[o,d]=O.useState(null),f=O.useCallback(async()=>{try{const v=await Oe("/api/remote-control/clients");if(v.ok){const k=await v.json();i((k.clients||[]).filter(E=>!E.hidden&&!E.instanceId.startsWith("_pending")))}}catch{}finally{g(!1)}},[]);O.useEffect(()=>{f();const v=setInterval(f,5e3);return()=>clearInterval(v)},[f]);const h=O.useCallback(async(v,k,E)=>{const C=`${k}:${E}:${v}`;d(C),n(null);try{const N=v==="delete"?"DELETE":"POST",R=v==="delete"?`/api/remote-control/clients/${k}/${E}`:`/api/remote-control/clients/${k}/${E}/${v}`,B=await Oe(R,{method:N});if(!B.ok){const A=await B.json().catch(()=>({}));throw new Error(A.error||`Failed: ${B.status}`)}await f()}catch(N){n((N==null?void 0:N.message)||"Action failed")}finally{d(null)}},[f]),_=v=>v==="connected"?"text-green-500":v==="connecting"?"text-yellow-500":v==="error"?"text-red-500":"text-text-tertiary",S=v=>t(v==="connected"?"remoteControl.connected":v==="connecting"?"remoteControl.connecting":"remoteControl.disconnected"),w=v=>v==="wechat"?s.jsx(hc,{size:18,className:"text-green-500"}):v==="wecom"?s.jsx(Ar,{size:18,className:"text-accent-brand"}):s.jsx(ml,{size:18,className:"text-text-tertiary"}),y=v=>v==="wechat"?t("channel.wechat")+t("remoteControl.bot"):v==="wecom"?t("channel.wecom")+t("remoteControl.bot"):v,c=v=>`${y(v.clientType)} #${v.instanceId.slice(0,4)}`,p=r.filter(v=>v.clientType==="wechat"),l=r.filter(v=>v.clientType==="wecom"),u=r.filter(v=>v.clientType!=="wechat"&&v.clientType!=="wecom"),m=v=>{const k=`${v.clientType}:${v.instanceId}`,E=v.status==="connected",C=o==null?void 0:o.startsWith(k);return s.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-lg bg-bg-secondary hover:bg-bg-hover transition-colors cursor-pointer",onClick:()=>{C||h(E?"stop":"start",v.clientType,v.instanceId)},children:[w(v.clientType),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsx("div",{className:"text-sm font-medium text-text-primary truncate",children:c(v)}),s.jsx("span",{className:`text-xs ${_(v.status)}`,children:S(v.status)})]}),s.jsxs("div",{className:"flex items-center gap-1",onClick:N=>N.stopPropagation(),children:[s.jsx("button",{className:`p-1.5 rounded-md text-text-tertiary transition-colors ${E?"hover:text-orange-500":"hover:text-green-500"} hover:bg-bg-hover`,title:t(E?"remoteControl.disconnect":"remoteControl.connect"),disabled:!!C,onClick:()=>h(E?"stop":"start",v.clientType,v.instanceId),children:E?s.jsx(ml,{size:14}):s.jsx(zd,{size:14})}),E&&s.jsx("button",{className:"p-1.5 rounded-md text-text-tertiary hover:text-orange-500 hover:bg-bg-hover transition-colors",title:t("remoteControl.unbind"),disabled:!!C,onClick:()=>h("unbind",v.clientType,v.instanceId),children:s.jsx(Dt,{size:14})}),s.jsx("button",{className:"p-1.5 rounded-md text-text-tertiary hover:text-red-500 hover:bg-bg-hover transition-colors",title:t("remoteControl.delete"),disabled:!!C,onClick:()=>h("delete",v.clientType,v.instanceId),children:s.jsx(Mt,{size:14})})]})]},k)},x=(v,k,E,C)=>s.jsxs("div",{children:[s.jsx("h2",{className:"text-sm font-medium text-text-secondary mb-2",children:v}),k.length===0?s.jsx("div",{className:"py-4 text-center text-xs text-text-tertiary",children:t("remoteControl.noChannels")}):s.jsx("div",{className:"space-y-2",children:k.map(m)}),E&&s.jsxs("button",{className:"flex items-center gap-1.5 mt-2 px-3 py-1.5 text-xs text-text-tertiary hover:text-text-primary hover:bg-bg-hover rounded-md transition-colors",onClick:E,children:[s.jsx(Ke,{size:12}),C||t("remoteControl.add")]})]});return s.jsxs("div",{className:"flex flex-col h-full overflow-y-auto",children:[s.jsxs("div",{className:"px-6 py-5 border-b border-border-primary",children:[s.jsx("h1",{className:"text-lg font-semibold text-text-primary",children:t("remoteControl.title")}),s.jsx("p",{className:"text-sm text-text-tertiary mt-1",children:t("remoteControl.subtitle")})]}),s.jsxs("div",{className:"px-6 py-4 flex-1 space-y-6",children:[b&&s.jsx("div",{className:"p-3 rounded-lg bg-red-500/10 text-red-500 text-sm",children:b}),a?s.jsx("div",{className:"text-sm text-text-tertiary py-4",children:t("remoteControl.connecting")}):r.length===0?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"py-8 text-center",children:[s.jsx(Ar,{size:32,className:"mx-auto mb-3 text-text-tertiary opacity-50"}),s.jsx("p",{className:"text-sm text-text-tertiary",children:t("remoteControl.noChannels")}),s.jsx("p",{className:"text-xs text-text-tertiary mt-1",children:t("remoteControl.noChannelsHint")})]}),s.jsxs("div",{className:"flex gap-3",children:[s.jsxs("button",{className:"flex items-center gap-2 px-4 py-2 rounded-lg bg-bg-secondary hover:bg-bg-hover text-sm text-text-primary transition-colors border border-border-primary",onClick:()=>Xt("remote-control","add-wechat"),children:[s.jsx(Ke,{size:14}),t("remoteControl.addWeChat")]}),s.jsxs("button",{className:"flex items-center gap-2 px-4 py-2 rounded-lg bg-bg-secondary hover:bg-bg-hover text-sm text-text-primary transition-colors border border-border-primary",onClick:()=>Xt("remote-control","add-wecom"),children:[s.jsx(Ke,{size:14}),t("remoteControl.addWeCom")]})]})]}):s.jsxs(s.Fragment,{children:[x(t("channel.wechat")+t("remoteControl.bot"),p,()=>Xt("remote-control","add-wechat"),t("remoteControl.addWeChat")),x(t("channel.wecom")+t("remoteControl.bot"),l,()=>Xt("remote-control","add-wecom"),t("remoteControl.addWeCom")),u.length>0&&x(t("remoteControl.plugin"),u)]}),s.jsx("hr",{className:"border-border-primary"}),s.jsxs("div",{className:"flex items-center gap-4 p-4 rounded-lg bg-bg-secondary hover:bg-bg-hover cursor-pointer transition-colors border border-border-primary",onClick:()=>{e?e("plugins"):window.location.hash="#/plugins"},children:[s.jsxs("div",{className:"flex-1",children:[s.jsx("h3",{className:"text-sm font-medium text-text-primary",children:t("remoteControl.installMore")}),s.jsx("p",{className:"text-xs text-text-tertiary mt-1",children:t("remoteControl.installMoreHint")})]}),s.jsx(sc,{size:16,className:"text-text-tertiary"})]})]})]})}function Xh({onBack:e,t}){const[r,i]=O.useState(null),[a,g]=O.useState(t("remoteControl.fetchingQr")),[b,n]=O.useState(null),[o,d]=O.useState(null),[f,h]=O.useState(!1);return O.useEffect(()=>{let _=!1;return(async()=>{try{const S=await Oe("/api/remote-control/clients/wechat/add",{method:"POST"});if(!S.ok)throw new Error((await S.json().catch(()=>({}))).error||"Failed");const w=await S.json();if(_)return;n(w.instanceId);for(let y=0;y<180&&!_;y++){await new Promise(c=>setTimeout(c,1e3));try{const c=await fetch(`/api/remote-control/clients/wechat/${w.instanceId}/qr`);if(!c.ok)continue;const p=await c.json();if(_)return;if(p.qrUrl&&i(p.qrUrl),p.message&&g(p.message),p.type==="confirmed"){h(!0),g(t("remoteControl.connected")),setTimeout(()=>{_||e()},1500);return}if(p.type==="error"){d(p.message);return}}catch{}}!_&&!f&&d("Timeout")}catch(S){_||d((S==null?void 0:S.message)||"Failed")}})(),()=>{_=!0}},[]),s.jsxs("div",{className:"flex flex-col h-full overflow-y-auto",children:[s.jsxs("div",{className:"px-6 py-5 border-b border-border-primary flex items-center gap-3",children:[s.jsx("button",{onClick:e,className:"p-1 rounded-md hover:bg-bg-hover transition-colors",children:s.jsx(Vr,{size:18})}),s.jsxs("div",{children:[s.jsx("h1",{className:"text-lg font-semibold text-text-primary",children:t("remoteControl.addWeChat")}),s.jsx("p",{className:"text-sm text-text-tertiary",children:t("remoteControl.scanQr")})]})]}),s.jsx("div",{className:"flex-1 flex flex-col items-center justify-center px-6 py-8",children:o?s.jsxs("div",{className:"text-center space-y-4",children:[s.jsx("p",{className:"text-red-500",children:o}),s.jsx("button",{onClick:e,className:"px-4 py-2 rounded-lg bg-bg-secondary hover:bg-bg-hover text-sm border border-border-primary",children:t("remoteControl.cancel")})]}):r?s.jsxs("div",{className:"text-center space-y-4",children:[s.jsx("div",{className:"inline-block p-4 bg-white rounded-xl",children:s.jsx("img",{src:`https://api.qrserver.com/v1/create-qr-code/?size=240x240&data=${encodeURIComponent(r)}`,alt:"QR Code",className:"w-60 h-60"})}),s.jsx("p",{className:"text-sm text-text-secondary",children:a})]}):s.jsxs("div",{className:"text-center space-y-3",children:[s.jsx("div",{className:"w-8 h-8 mx-auto border-2 border-accent-brand border-t-transparent rounded-full animate-spin"}),s.jsx("p",{className:"text-sm text-text-tertiary",children:a})]})})]})}function Zh({onBack:e,t}){const[r,i]=O.useState(""),[a,g]=O.useState(""),[b,n]=O.useState("botId"),[o,d]=O.useState(!1),[f,h]=O.useState(null),_=O.useCallback(async()=>{if(!(!r.trim()||!a.trim())){d(!0),h(null);try{const S=await Oe("/api/remote-control/clients/wecom/add",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({botId:r.trim(),secret:a.trim()})});if(!S.ok){const w=await S.json().catch(()=>({}));throw new Error(w.error||"Failed")}e()}catch(S){h((S==null?void 0:S.message)||"Failed")}finally{d(!1)}}},[r,a,e]);return s.jsxs("div",{className:"flex flex-col h-full overflow-y-auto",children:[s.jsxs("div",{className:"px-6 py-5 border-b border-border-primary flex items-center gap-3",children:[s.jsx("button",{onClick:e,className:"p-1 rounded-md hover:bg-bg-hover transition-colors",children:s.jsx(Vr,{size:18})}),s.jsxs("div",{children:[s.jsx("h1",{className:"text-lg font-semibold text-text-primary",children:t("remoteControl.addWeCom")}),s.jsx("p",{className:"text-sm text-text-tertiary",children:t("remoteControl.wecomBotIdHint")})]})]}),s.jsxs("div",{className:"px-6 py-8 max-w-md mx-auto w-full space-y-6",children:[f&&s.jsx("div",{className:"p-3 rounded-lg bg-red-500/10 text-red-500 text-sm",children:f}),s.jsxs("div",{className:"space-y-2",children:[s.jsx("label",{className:"text-sm font-medium text-text-primary",children:"Bot ID"}),s.jsx("input",{type:"text",className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-primary text-sm text-text-primary placeholder-text-tertiary focus:outline-none focus:border-accent-brand transition-colors",placeholder:"Enter Bot ID",value:r,onChange:S=>i(S.target.value),autoFocus:!0,disabled:b==="secret",onKeyDown:S=>{S.key==="Enter"&&r.trim()&&n("secret")}})]}),b==="secret"&&s.jsxs("div",{className:"space-y-2",children:[s.jsx("label",{className:"text-sm font-medium text-text-primary",children:"Secret"}),s.jsx("input",{type:"password",className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-primary text-sm text-text-primary placeholder-text-tertiary focus:outline-none focus:border-accent-brand transition-colors",placeholder:"Enter Secret",value:a,onChange:S=>g(S.target.value),autoFocus:!0,onKeyDown:S=>{S.key==="Enter"&&a.trim()&&_()}}),s.jsx("p",{className:"text-xs text-text-tertiary",children:t("remoteControl.wecomSecretHint")})]}),s.jsxs("div",{className:"flex gap-3 pt-2",children:[b==="botId"?s.jsx("button",{className:"px-4 py-2 rounded-lg bg-accent-brand text-white text-sm hover:bg-accent-brand/90 transition-colors disabled:opacity-50",disabled:!r.trim(),onClick:()=>n("secret"),children:t("remoteControl.next")}):s.jsx("button",{className:"px-4 py-2 rounded-lg bg-accent-brand text-white text-sm hover:bg-accent-brand/90 transition-colors disabled:opacity-50",disabled:!a.trim()||o,onClick:_,children:t(o?"remoteControl.connecting":"remoteControl.connect")}),s.jsx("button",{className:"px-4 py-2 rounded-lg bg-bg-secondary border border-border-primary text-sm text-text-secondary hover:bg-bg-hover transition-colors",onClick:e,children:t("remoteControl.cancel")})]})]})]})}const Qh="data:image/svg+xml,%3csvg%20width='24'%20height='24'%20viewBox='0%200%2024%2024'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3cg%20clip-path='url(%23copilot-clip-34e811bed903495093b85bf96a98fb1b_0)'%3e%3crect%20width='24'%20height='24'%20rx='12'%20fill='%234C4F6B'%3e%3c/rect%3e%3cpath%20d='M3.4689%2011.0144C3.32344%2011.2025%203.31607%2011.4567%203.4345%2012.0298C3.65883%2013.0748%204.24029%2014.4426%205.15579%2016.0716L5.747%2017.1172L5.72862%2017.511C5.70544%2017.9326%205.72848%2018.5857%205.77921%2019.0271C5.80994%2019.2967%205.8055%2019.3035%205.66483%2019.4638C5.12042%2020.0864%205.03916%2021.1287%205.44787%2022.2839C5.62456%2022.7775%206.16958%2023.6999%206.50726%2024.0756C7.35392%2025.0154%208.35051%2025.4646%209.11147%2025.246C9.25446%2025.2051%209.28403%2025.213%209.47117%2025.3424C10.182%2025.8233%2011.3834%2026.2377%2012.4447%2026.3663C14.2242%2026.5843%2016.2727%2026.143%2018.8281%2024.9925C19.8948%2024.5099%2022.2541%2023.1352%2023.2513%2022.4096C25.1083%2021.0667%2026.4805%2019.6414%2027.251%2018.2635C27.9337%2017.0364%2028.2735%2015.7781%2028.2495%2014.5174C28.2466%2014.2525%2028.2536%2014.2359%2028.3599%2014.1746C28.8797%2013.8703%2029.1497%2013.198%2029.0927%2012.3562C29.075%2012.1165%2029.0266%2011.7946%2028.9902%2011.6448C28.7404%2010.7144%2028.0885%209.59971%2027.4078%208.94729C26.6515%208.22182%2025.7943%207.9129%2025.1958%208.14598C25.0631%208.19758%2025.0452%208.19542%2024.9177%208.08995C24.6357%207.86124%2023.9604%207.43473%2023.5488%207.22673L23.1224%207.01477L22.8206%206.45595C22.0392%205.01609%2020.7826%203.33003%2019.8801%202.50992C19.4937%202.15818%2019.2668%202.03929%2019.019%202.05739C18.866%202.06657%2018.8535%202.07379%2018.645%202.26084C18.0389%202.79819%2017.1889%204.41355%2016.3588%206.60463L16.1271%207.21325L15.7053%207.34845C14.3909%207.76995%2013.2238%208.30219%2012.1896%208.94928C11.1973%209.56799%2010.6591%209.97037%209.84886%2010.688L9.36087%2011.1197L9.13878%2011.0813C7.00072%2010.7039%205.07892%2010.5639%204.19776%2010.7186C3.84772%2010.7832%203.55743%2010.9008%203.4689%2011.0144Z'%20fill='%23D2D3E0'%3e%3c/path%3e%3crect%20x='6.68555'%20y='16.3788'%20width='17.7918'%20height='11.5605'%20rx='4.61469'%20transform='rotate(-30%206.68555%2016.3788)'%20fill='%23212234'%3e%3c/rect%3e%3cg%3e%3crect%20x='12.2119'%20y='17.2593'%20width='2.13173'%20height='4.42744'%20rx='1.06587'%20transform='rotate(-30%2012.2119%2017.2593)'%20fill='%23D2D3E0'%3e%3canimate%20attributeName='height'%20values='4.42744;2.2;4.42744;4.42744;2.2;4.42744'%20dur='0.6s'%20begin='0s;blink134e811bed903495093b85bf96a98fb1b_0.end+3s'%20id='blink134e811bed903495093b85bf96a98fb1b_0'%3e%3c/animate%3e%3canimate%20attributeName='y'%20values='17.2593;18.2593;17.2593;17.2593;18.2593;17.2593'%20dur='0.6s'%20begin='0s;blink134e811bed903495093b85bf96a98fb1b_0.end+3s'%3e%3c/animate%3e%3canimate%20attributeName='opacity'%20values='1;0.2;1;1;0.2;1'%20dur='0.6s'%20begin='0s;blink134e811bed903495093b85bf96a98fb1b_0.end+3s'%3e%3c/animate%3e%3c/rect%3e%3c/g%3e%3cg%3e%3crect%20x='17.9634'%20y='13.9387'%20width='2.13173'%20height='4.42744'%20rx='1.06587'%20transform='rotate(-30%2017.9634%2013.9387)'%20fill='%23D2D3E0'%3e%3canimate%20attributeName='height'%20values='4.42744;2.2;4.42744;4.42744;2.2;4.42744'%20dur='0.6s'%20begin='0s;blink234e811bed903495093b85bf96a98fb1b_0.end+3s'%20id='blink234e811bed903495093b85bf96a98fb1b_0'%3e%3c/animate%3e%3canimate%20attributeName='y'%20values='13.9387;14.9387;13.9387;13.9387;14.9387;13.9387'%20dur='0.6s'%20begin='0s;blink234e811bed903495093b85bf96a98fb1b_0.end+3s'%3e%3c/animate%3e%3canimate%20attributeName='opacity'%20values='1;0.2;1;1;0.2;1'%20dur='0.6s'%20begin='0s;blink234e811bed903495093b85bf96a98fb1b_0.end+3s'%3e%3c/animate%3e%3c/rect%3e%3c/g%3e%3c/g%3e%3cdefs%3e%3cclipPath%20id='copilot-clip-34e811bed903495093b85bf96a98fb1b_0'%3e%3crect%20width='24'%20height='24'%20rx='12'%20fill='white'%3e%3c/rect%3e%3c/clipPath%3e%3c/defs%3e%3c/svg%3e",Jh="/assets/logo-iZVLr450.svg",eg=Ge(e=>({userInfo:null,loading:!1,error:null,fetchUserInfo:async t=>{e({loading:!0,error:null});try{const r=await t.getUserInfo();r.userInfo?e({userInfo:r.userInfo,loading:!1}):e({loading:!1})}catch(r){console.warn("[user] Failed to fetch user info:",r),e({error:r.message,loading:!1})}},clearUserInfo:()=>{e({userInfo:null,error:null})}}));function tg({isOpen:e,onClose:t,mainView:r,onNavigate:i}){const{t:a}=ue(),{userInfo:g,fetchUserInfo:b}=eg(),n=Hr(_=>_.info),o=Hr(_=>_.fetch);O.useEffect(()=>{n||o();const _=xe();b(_)},[b,o,n]);const d=(g==null?void 0:g.userName)||(n==null?void 0:n.userName)||a("sidebar.user"),f=(n==null?void 0:n.version)||"",h=f&&f!=="dev"?`v${f}`:"CodeBuddy Code";return s.jsxs(s.Fragment,{children:[s.jsx("div",{className:`sidebar-overlay ${e?"":"sidebar-overlay-hidden"}`,onClick:t}),s.jsxs("aside",{className:`sidebar ${e?"":"sidebar-closed"}`,children:[s.jsxs("div",{className:"sidebar-header",children:[s.jsx("img",{src:Jh,alt:"CodeBuddy",className:"sidebar-logo"}),s.jsx("span",{className:"sidebar-brand",children:"CodeBuddy"}),s.jsx("div",{className:"flex-1"}),s.jsx("button",{onClick:t,className:"md:hidden w-7 h-7 flex items-center justify-center rounded-md text-text-tertiary hover:text-text-primary hover:bg-bg-hover transition-colors",children:s.jsx(Ie,{size:16})})]}),s.jsxs("nav",{className:"sidebar-nav",children:[s.jsxs("button",{className:`sidebar-nav-item ${r==="chat"?"active":""}`,onClick:()=>i("chat"),children:[s.jsx(gc,{size:16}),s.jsx("span",{children:a("sidebar.chatMode")})]}),s.jsxs("button",{className:`sidebar-nav-item ${r==="instances"?"active":""}`,onClick:()=>i("instances"),children:[s.jsx(ct,{size:16}),s.jsx("span",{children:a("sidebar.instances")})]}),s.jsxs("button",{className:`sidebar-nav-item ${r==="remote-control"?"active":""}`,onClick:()=>i("remote-control"),children:[s.jsx(Ar,{size:16}),s.jsx("span",{children:a("sidebar.remoteControl")})]})]}),s.jsx("div",{className:"sidebar-content",children:s.jsxs("div",{className:"px-3 py-1",children:[s.jsxs("button",{className:`sidebar-nav-item ${r==="tasks"?"active":""}`,onClick:()=>i("tasks"),children:[s.jsx(uc,{size:16}),s.jsx("span",{children:a("sidebar.nav.tasks")})]}),s.jsxs("button",{className:`sidebar-nav-item ${r==="terminal"?"active":""}`,onClick:()=>i("terminal"),children:[s.jsx(mc,{size:16}),s.jsx("span",{children:a("sidebar.terminalMode")})]}),s.jsxs("button",{className:`sidebar-nav-item ${r==="plugins"?"active":""}`,onClick:()=>i("plugins"),children:[s.jsx(gt,{size:16}),s.jsx("span",{children:a("sidebar.nav.plugins")})]}),s.jsxs("button",{className:`sidebar-nav-item ${r==="settings"?"active":""}`,onClick:()=>i("settings"),children:[s.jsx(fc,{size:16}),s.jsx("span",{children:a("sidebar.preferences")})]})]})}),s.jsx("div",{className:"sidebar-footer",children:s.jsxs("div",{className:"sidebar-user",children:[s.jsx("img",{src:Qh,alt:"User",className:"sidebar-user-avatar"}),s.jsxs("div",{className:"sidebar-user-info",children:[s.jsx("div",{className:"sidebar-user-name",children:d}),s.jsx("div",{className:"sidebar-user-status",children:h})]})]})})]})]})}function rg({onMenuClick:e,onNewChat:t,onSplitTerminal:r,onHistory:i,hasHistory:a,rightActions:g}){const{t:b}=ue(),{topic:n}=Xe(),{mainView:o,layout:d,terminalTitle:f}=me(),[h,_]=O.useState(!1),S=O.useRef(null),w=o==="terminal",c=ft(d)<Wc;O.useEffect(()=>{if(!h)return;const m=x=>{S.current&&!S.current.contains(x.target)&&_(!1)};return document.addEventListener("mousedown",m),()=>document.removeEventListener("mousedown",m)},[h]);const p=O.useCallback(m=>{_(!1),r==null||r(m)},[r]),l=()=>{switch(o){case"chat":return n||b("chat.newChat");case"terminal":return f||b("terminal.title");case"instances":return b("instance.managerTitle");case"settings":return b("settings.title");case"tasks":return b("tasks.title");case"plugins":return b("sidebar.nav.plugins");default:return""}},u=()=>g||(w?s.jsxs("div",{ref:S,className:"relative",children:[s.jsx("button",{onClick:()=>c&&_(!h),className:`text-text-secondary transition-colors flex items-center justify-center w-8 h-8 rounded-full ${c?"hover:text-text-primary hover:bg-bg-secondary":"opacity-40 cursor-not-allowed"}`,title:c?void 0:b("terminal.maxPanes"),children:s.jsx(gl,{size:20})}),h&&s.jsxs("div",{className:"absolute right-0 top-full mt-1 bg-bg-secondary border border-border-muted rounded-lg shadow-lg py-1 z-50 min-w-[140px]",children:[s.jsxs("button",{onClick:()=>p("horizontal"),className:"w-full flex items-center gap-3 px-4 py-2.5 text-[13px] text-text-primary hover:bg-bg-hover transition-colors",children:[s.jsx(gl,{size:16,className:"text-text-secondary"}),s.jsx("span",{children:b("terminal.splitHorizontal")})]}),s.jsxs("button",{onClick:()=>p("vertical"),className:"w-full flex items-center gap-3 px-4 py-2.5 text-[13px] text-text-primary hover:bg-bg-hover transition-colors",children:[s.jsx(Qd,{size:16,className:"text-text-secondary"}),s.jsx("span",{children:b("terminal.splitVertical")})]})]})]}):o==="chat"?s.jsxs("div",{className:"flex items-center gap-1",children:[s.jsx("button",{onClick:t,className:"text-text-secondary hover:text-text-primary transition-colors flex items-center justify-center w-8 h-8 rounded-full hover:bg-bg-secondary",children:s.jsx(Ke,{size:20})}),a&&s.jsx("button",{onClick:i,className:"text-text-secondary hover:text-text-primary transition-colors flex items-center justify-center w-8 h-8 rounded-full hover:bg-bg-secondary",title:b("sidebar.chatHistory"),children:s.jsx(cc,{size:18})})]}):null);return s.jsxs("div",{className:"flex items-center justify-between px-4 sm:px-6 h-14 bg-bg-primary text-xs flex-shrink-0 transition-colors duration-200 sticky top-0 z-10",children:[s.jsx("div",{className:"flex items-center gap-4",children:s.jsx("button",{onClick:e,className:"text-text-secondary hover:text-text-primary transition-colors flex items-center justify-center w-8 h-8 rounded-full hover:bg-bg-secondary",children:s.jsx(Vd,{size:20})})}),s.jsx("div",{className:"flex-1 flex justify-center items-center min-w-0 px-2",children:s.jsx("span",{className:"font-medium text-text-primary text-[15px] tracking-wide truncate max-w-full",children:l()})}),s.jsx("div",{className:"flex items-center",children:u()})]})}function ng(e){var r;const t=new Map;for(const i of e){if(i.type!=="tool_call")continue;const a=i;if(!((r=a.subagent)!=null&&r.memberName))continue;const g=a.subagent.memberName,b=t.get(g),n=a.subagentTimeline||[],o=n.filter(f=>f.type==="tool_call_ref").length;let d;if(a.status==="running"&&a.children&&a.children.length>0)for(let f=n.length-1;f>=0;f--){const h=n[f];if(h.type==="tool_call_ref"){d=h.toolCallId;break}}b?(a.status==="running"&&(b.status="running",b.currentTool=d),b.toolCount=Math.max(b.toolCount,o),a.subagent.description&&(b.description=a.subagent.description)):t.set(g,{name:g,description:a.subagent.description||"",status:a.status,currentTool:d,toolCount:o})}return Array.from(t.values())}function ig(){const{t:e}=ue(),t=Le(n=>n.timeline),r=Le(n=>n.childToolCalls),i=O.useMemo(()=>ng(t),[t]);if(!i.some(n=>n.status==="running")||i.length===0)return null;const g=i.filter(n=>n.status==="running").length,b=i.filter(n=>n.status!=="running").length;return s.jsxs("div",{className:"flex-none border-t border-border-muted/40 bg-bg-secondary/30",children:[s.jsxs("div",{className:"flex items-center gap-2 px-4 py-1.5",children:[s.jsx(_c,{size:13,className:"text-accent-purple"}),s.jsx("span",{className:"text-[12px] font-medium text-text-secondary",children:e("team.title")}),s.jsxs("span",{className:"text-[11px] text-text-tertiary",children:[e("team.activeCount").replace("{count}",String(g)),b>0?` · ${e("team.doneCount").replace("{count}",String(b))}`:""]})]}),s.jsx("div",{className:"flex flex-wrap gap-x-3 gap-y-1 px-4 pb-2",children:i.map(n=>s.jsx(sg,{member:n,childToolCalls:r},n.name))})]})}function sg({member:e,childToolCalls:t}){const r=e.status==="running",i=e.status==="failed";let a;if(e.currentTool){const g=t.get(e.currentTool);g&&(a=g.name||g.toolName)}return s.jsxs("div",{className:`inline-flex items-center gap-1.5 px-2 py-1 rounded-md text-[12px] transition-colors ${r?"bg-accent-purple/10 text-accent-purple":i?"bg-accent-red/10 text-accent-red":"bg-bg-secondary/50 text-text-tertiary"}`,children:[s.jsx("div",{className:`w-3.5 h-3.5 rounded-full flex items-center justify-center flex-shrink-0 ${r?"bg-accent-purple/20":"bg-transparent"}`,children:s.jsx(ct,{size:10})}),s.jsxs("span",{className:"font-medium",children:["@",e.name]}),a&&r&&s.jsx("span",{className:"text-[11px] opacity-70 truncate max-w-[120px]",children:a}),r&&s.jsx(De,{size:10,className:"animate-spin flex-shrink-0"}),i&&s.jsx(Cr,{size:10,className:"flex-shrink-0"}),!r&&!i&&s.jsx(Ye,{size:10,className:"flex-shrink-0"})]})}function ag(e,t){const r=[];for(const i of e)i.type==="tool_call"&&r.push(i);for(const i of t.values())r.push(i);return r}function og(e){const t={};for(const r of e){const i=r.input||{},a=r.toolName;if(a==="TaskCreate"){const g=r.result,b=typeof g=="string"?g:g&&typeof g=="object"?String(g.text??g.output??""):"",n=!b&&Array.isArray(r.content)?r.content.reduce((f,h)=>{var S;const _=((S=h==null?void 0:h.content)==null?void 0:S.text)??(h==null?void 0:h.text)??(typeof h=="string"?h:"");return f||String(_)},""):"",o=(b||n).match(/Task #(\d+)/),d=o?o[1]:`t-${Object.keys(t).length+1}`;t[d]={id:d,subject:i.subject?String(i.subject):"",status:"pending",owner:i.owner?String(i.owner):void 0,activeForm:i.activeForm?String(i.activeForm):void 0}}else if(a==="TaskUpdate"){const g=i.taskId?String(i.taskId):void 0;if(g&&t[g]){const b=t[g];i.status&&i.status!=="deleted"&&(b.status=String(i.status)),i.subject&&(b.subject=String(i.subject)),i.owner!==void 0&&(b.owner=i.owner?String(i.owner):void 0),i.activeForm&&(b.activeForm=String(i.activeForm)),i.status==="deleted"&&delete t[g]}}}return Object.values(t)}function lg(e){let t=0;for(const r of e)(r.toolName==="TaskCreate"||r.toolName==="TaskUpdate")&&t++;return t}function cg({status:e}){switch(e){case"completed":return s.jsx(ac,{size:14,className:"text-accent-green flex-shrink-0"});case"in_progress":return s.jsx(De,{size:14,className:"text-accent-brand flex-shrink-0 animate-spin"});default:return s.jsx(Bd,{size:14,className:"text-text-tertiary flex-shrink-0"})}}function dg(){const e=Le(m=>m.timeline),t=Le(m=>m.childToolCalls),r=Le(m=>m.isAgentRunning),{t:i}=ue(),[a,g]=O.useState(!0),b=O.useRef(0),[n,o]=O.useState(!1),d=O.useRef(r),f=O.useMemo(()=>ag(e,t),[e,t]),h=O.useMemo(()=>og(f),[f]),_=O.useMemo(()=>lg(f),[f]);O.useEffect(()=>{!d.current&&r&&(b.current=_,o(!0)),d.current=r},[r,_]),O.useEffect(()=>{n&&_>b.current&&o(!1)},[n,_]);const S=O.useCallback(()=>g(m=>!m),[]),w=O.useCallback(m=>{m.stopPropagation(),b.current=_,o(!0)},[_]);if(h.length===0||h.length>0&&h.every(m=>m.status==="completed")&&!r||n)return null;const c=h.filter(m=>m.status==="completed").length,p=h.length,l=h.find(m=>m.status==="in_progress"),u=l?l.activeForm||l.subject:`${c}/${p} ${i("todo.title")}`;return s.jsx("div",{className:"flex-none px-4 sm:px-6 pb-1",children:s.jsx("div",{className:"max-w-3xl mx-auto",children:s.jsxs("div",{className:"rounded-lg border border-border-muted/60 bg-bg-secondary/50 shadow-sm overflow-hidden backdrop-blur-sm",children:[s.jsxs("button",{onClick:S,className:"flex items-center gap-2 w-full px-3 py-1.5 hover:bg-bg-hover/30 transition-colors cursor-pointer",children:[s.jsx(pc,{size:13,className:"text-text-tertiary flex-shrink-0"}),s.jsx("span",{className:"text-xs font-medium text-text-primary",children:i("todo.title")}),s.jsxs("span",{className:"text-[11px] text-text-tertiary tabular-nums",children:[c,"/",p]}),!a&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-border-muted/60 select-none",children:"|"}),l&&r&&s.jsx(De,{size:10,className:"text-accent-brand animate-spin flex-shrink-0"}),s.jsx("span",{className:"text-xs text-text-secondary truncate flex-1 text-left",children:u})]}),s.jsx("span",{className:"flex-1"}),!r&&s.jsx("span",{role:"button",tabIndex:0,onClick:w,onKeyDown:m=>{m.key==="Enter"&&w(m)},className:"text-text-tertiary hover:text-text-primary p-0.5 rounded transition-colors flex-shrink-0",children:s.jsx(Ie,{size:12})}),a?s.jsx(Nt,{size:12,className:"text-text-tertiary flex-shrink-0"}):s.jsx(It,{size:12,className:"text-text-tertiary flex-shrink-0"})]}),a&&s.jsx("div",{className:"border-t border-border-muted/40 px-3 py-1.5 space-y-0.5 max-h-52 overflow-y-auto",children:h.map((m,x)=>s.jsxs("div",{className:`flex items-center gap-2 py-0.5 text-xs ${m.status==="in_progress"?"text-text-primary":m.status==="completed"?"text-text-tertiary":"text-text-secondary"}`,children:[s.jsx(cg,{status:m.status}),s.jsxs("span",{className:`truncate ${m.status==="completed"?"line-through":""}`,children:[x+1,". ",m.status==="in_progress"?m.activeForm||m.subject||i("todo.untitled"):m.subject||i("todo.untitled")]})]},m.id))})]})})})}function ug(){const{viewState:e,checkAuth:t}=zc(),{status:r,sessionId:i,topic:a,setPromptSuggestion:g,setTopic:b}=Xe(),{connect:n}=Rd(),{clearChat:o}=Le(),{t:d,resolved:f}=ue(),[h,_]=O.useState(()=>{try{const F=sessionStorage.getItem("codebuddy_sidebar_open");return F!==null?window.innerWidth>=768?F==="true":!1:window.innerWidth>=768}catch{return window.innerWidth>=768}}),S=O.useRef(h),[w,y]=O.useState(!1),[c,p]=O.useState(!1),{splitPane:l,mainView:u,setMainView:m}=me(),x=O.useCallback(F=>{_(M=>{const H=typeof F=="function"?F(M):F;S.current=H;try{sessionStorage.setItem("codebuddy_sidebar_open",String(H))}catch{}return H})},[]);O.useEffect(()=>{const F=window.matchMedia("(min-width: 768px)"),M=H=>{H.matches?_(S.current):_(!1)};return F.addEventListener("change",M),()=>F.removeEventListener("change",M)},[]);const[v,k]=O.useState(!1),E=O.useRef();O.useEffect(()=>r!=="connected"?void 0:((()=>{fetch("/sessions",{headers:Fe()}).then(M=>M.ok?M.json():null).then(M=>{M!=null&&M.sessions&&k(M.sessions.length>1)}).catch(()=>{})})(),()=>{E.current&&clearTimeout(E.current)}),[r,i]);const C=O.useCallback(F=>{l(F)},[l]),N=O.useCallback(async()=>{if(i){try{await xe().prompt(i,"/clear")}catch(F){console.error("New chat (/clear) failed:",F)}o(),b(null),g(null),m("chat"),window.location.hash="/chat"}},[i,o,b,g,m]),R=O.useCallback(async F=>{if(i){try{await xe().prompt(i,`/resume ${F}`)}catch(M){console.error("Switch session failed:",M)}m("chat"),window.location.hash="/chat"}},[i,m]),B=O.useCallback(F=>{m(F),window.location.hash=`/${F}`,window.innerWidth<768&&_(!1)},[m]);if(O.useEffect(()=>{const F=new URLSearchParams(window.location.search),M=F.get("password"),H=F.get("token");if(M||H){Hc(M||H),F.delete("password"),F.delete("token");const z=F.toString()?`${window.location.pathname}?${F.toString()}`:window.location.pathname;window.history.replaceState({},"",z)}t()},[t]),O.useEffect(()=>{if(e==="authenticated"){const F=sd();m(F),(!window.location.hash||window.location.hash==="#")&&(window.location.hash=`/${F}`)}},[e,m]),O.useEffect(()=>Vh(M=>{m(M)}),[m]),O.useEffect(()=>{if(e==="authenticated"){const F=Ht()||void 0;n({token:F,continue:!0})}},[e,n]),O.useEffect(()=>{document.documentElement.lang=f,document.title=a?`${a} - CodeBuddy Code`:d("page.title")},[f,d,a]),e==="loading")return s.jsx("div",{className:"flex h-screen h-[100dvh] bg-bg-primary text-text-primary transition-colors duration-200 font-sans overflow-hidden",children:s.jsx("div",{className:"flex-1 flex items-center justify-center",children:s.jsx(lt,{size:"large",text:d("app.connecting")})})});if(e==="login")return s.jsx(Wh,{});const A=()=>{if(r==="connecting")return s.jsx("div",{className:"flex-1 flex items-center justify-center",children:s.jsx(lt,{size:"large",text:d("app.connecting")})});if(r!=="connected"&&u!=="settings")return s.jsx("div",{className:"flex-1 flex items-center justify-center",children:s.jsxs("div",{className:"text-center",children:[s.jsx("div",{className:"text-text-secondary mb-4 font-medium",children:d("app.connectFailed")}),s.jsx("button",{onClick:()=>n(),className:"px-6 py-2.5 bg-accent-brand text-white rounded-full text-sm font-medium transition-all hover:bg-accent-brand/90 hover:scale-105 active:scale-95 shadow-sm",children:d("app.retry")})]})});switch(u){case"chat":return s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"flex-1 overflow-hidden w-full relative",children:s.jsx(Qp,{onClickCloseBottomSheet:()=>p(!1)})}),s.jsx(ig,{}),s.jsx(dg,{}),s.jsx("div",{className:"flex-none bg-bg-primary",children:s.jsx(zh,{onNavigate:B,onNewChat:N,onHistory:()=>y(!0),mainView:u,showBottomSheet:c,setShowBottomSheet:p})})]});case"tasks":return s.jsx(ed,{});case"plugins":return s.jsx(Zc,{});case"terminal":return null;case"instances":return s.jsx(Xc,{});case"remote-control":return s.jsx(Kh,{onNavigate:B});case"settings":return s.jsx(Jc,{});default:return null}};return s.jsxs("div",{className:"flex h-screen h-[100dvh] bg-bg-primary text-text-primary transition-colors duration-200 font-sans overflow-hidden",children:[s.jsx(tg,{isOpen:h,onClose:()=>x(!1),mainView:u,onNavigate:B}),s.jsxs("div",{className:"flex-1 flex flex-col min-w-0 relative transition-all duration-300 h-full",children:[s.jsx(rg,{onMenuClick:()=>x(F=>!F),onNewChat:N,onSplitTerminal:C,onHistory:()=>y(!0),hasHistory:v}),s.jsxs("div",{className:"flex-1 flex flex-col w-full overflow-hidden relative",children:[s.jsx("div",{className:"flex-1 flex flex-col w-full",style:{display:u==="terminal"?"flex":"none"},children:s.jsx(rd,{})}),u!=="terminal"&&A()]}),s.jsx(eh,{isOpen:w,onClose:()=>y(!1),onSwitchSession:R})]})]})}kd.createRoot(document.getElementById("root")).render(s.jsx(O.StrictMode,{children:s.jsx(ug,{})}));
|
|
411
|
+
`+n.slice(se);o(ge),requestAnimationFrame(()=>{$.selectionStart=$.selectionEnd=X+1,$.focus()})},className:"flex items-center justify-center w-8 h-8 rounded-full text-text-tertiary hover:text-text-primary hover:bg-bg-primary transition-colors",title:oe("input.newline"),children:s.jsx(fl,{size:15})}),U&&s.jsx("button",{onClick:ad,className:"flex items-center justify-center w-8 h-8 rounded-full text-text-tertiary hover:text-text-primary hover:bg-bg-primary transition-colors",title:oe("input.stop"),children:s.jsx(nu,{size:14,fill:"currentColor",strokeWidth:0})}),el&&s.jsx("button",{onClick:()=>{!n&&q&&!U?it(q):it()},className:"flex items-center justify-center w-8 h-8 rounded-full bg-text-primary text-bg-primary hover:scale-105 active:scale-95 shadow-sm transition-all",title:oe("input.send"),children:s.jsx(pl,{size:18,strokeWidth:2.5})})]})]})]})]})})}function Gh({children:e}){return s.jsx("code",{className:"bg-bg-tertiary px-1.5 py-0.5 rounded text-xs text-accent-brand",children:e})}function Kl(e){const t=[];let r=e,i=0;for(;r.length>0;){const a=r.indexOf("<code>");if(a===-1){t.push(s.jsx("span",{children:r},i));break}a>0&&(t.push(s.jsx("span",{children:r.substring(0,a)},i)),i++);const g=r.indexOf("</code>",a);if(g===-1){t.push(s.jsx("span",{children:r},i));break}const b=r.substring(a+6,g);t.push(s.jsx(Gh,{children:b},i)),i++,r=r.substring(g+7)}return s.jsx(s.Fragment,{children:t})}function Wh(){const{error:e,isSubmitting:t,login:r,clearError:i}=zc(),{t:a}=ue(),[g,b]=O.useState(""),n=O.useCallback(async d=>{d.preventDefault(),g.trim()&&await r(g)},[g,r]),o=e?a(e)!==e?a(e):e:null;return s.jsxs("div",{className:"login-page",children:[s.jsxs("div",{className:"login-orb login-orb-right",children:[s.jsx("div",{className:"login-orb-layer login-orb-layer-1"}),s.jsx("div",{className:"login-orb-layer login-orb-layer-2"})]}),s.jsx("div",{className:"login-ellipse login-ellipse-outer"}),s.jsx("div",{className:"login-ellipse login-ellipse-outer2"}),s.jsx("div",{className:"login-ellipse login-ellipse-inner"}),s.jsxs("div",{className:"login-orb login-orb-left",children:[s.jsx("div",{className:"login-orb-layer login-orb-layer-1"}),s.jsx("div",{className:"login-orb-layer login-orb-layer-2"})]}),s.jsx("div",{className:"login-ellipse login-ellipse-left"}),s.jsx("div",{className:"login-ellipse login-ellipse-left2"}),s.jsxs("div",{className:"login-content",children:[s.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",gap:"16px"},children:[s.jsx("div",{className:"login-logo",children:s.jsx("img",{src:tc,alt:"CodeBuddy"})}),s.jsx("h1",{className:"login-title",children:a("login.slogan")}),s.jsx("p",{className:"login-tagline",children:a("login.tagline")})]}),s.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",gap:"4px"},children:[o&&s.jsx("div",{className:"login-error",style:{marginBottom:"8px"},children:o}),s.jsxs("form",{onSubmit:n,style:{display:"flex",flexDirection:"column",alignItems:"center",gap:"8px"},children:[s.jsx("input",{type:"password",name:"password",value:g,onChange:d=>{b(d.target.value),e&&i()},placeholder:a("login.placeholder"),autoFocus:!0,autoComplete:"current-password",disabled:t,className:"login-input"}),s.jsx("button",{type:"submit",disabled:t||!g.trim(),className:"login-btn",children:t?s.jsx("span",{className:"thinking-text",children:a("login.submit")}):a("login.submit")})]}),s.jsxs("div",{className:"login-hints",children:[s.jsx("p",{children:a("login.hint.password")}),s.jsx("p",{children:a("login.hint.urlAuth").includes("<code>")?Kl(a("login.hint.urlAuth")):a("login.hint.urlAuth")}),s.jsx("p",{children:a("login.hint.disable").includes("<code>")?Kl(a("login.hint.disable")):a("login.hint.disable")})]})]})]}),s.jsxs("div",{className:"login-footer",children:[s.jsx("a",{href:"#privacy",children:a("login.privacy")}),s.jsx("a",{href:"#terms",children:a("login.terms")})]})]})}const qh="chat",Yl=new Set(["chat","tasks","plugins","terminal","instances","remote-control","settings"]);function sd(){let t=window.location.hash.slice(1);t.startsWith("/")&&(t=t.slice(1));const r=t.split("?")[0]||"";if(Yl.has(r))return r;const i=r.split("/")[0];return Yl.has(i)?i:qh}function Xl(e){const t=new URLSearchParams(window.location.search),r=window.location.hash.slice(1),i=r.indexOf("?");i!==-1&&new URLSearchParams(r.slice(i+1)).forEach((n,o)=>{t.has(o)||t.set(o,n)});const a=t.toString(),g=a?`#/${e}?${a}`:`#/${e}`;window.location.hash=g}function Vh(e){const t=()=>{const r=sd();e(r)};return window.addEventListener("hashchange",t),()=>{window.removeEventListener("hashchange",t)}}function Zl(){const t=window.location.hash.slice(1).replace(/^\//,"").split("?")[0],r=t.indexOf("/");return r>0?t.slice(r+1):void 0}function Xt(e,t){const i=new URLSearchParams(window.location.search).toString(),a=i?`#/${e}/${t}?${i}`:`#/${e}/${t}`;window.location.hash=a}function Kh({onNavigate:e}){const{t}=ue(),[r,i]=O.useState(Zl);return O.useEffect(()=>{const a=()=>i(Zl());return window.addEventListener("hashchange",a),()=>window.removeEventListener("hashchange",a)},[]),r==="add-wechat"?s.jsx(Xh,{onBack:()=>Xl("remote-control"),t}):r==="add-wecom"?s.jsx(Zh,{onBack:()=>Xl("remote-control"),t}):s.jsx(Yh,{onNavigate:e,t})}function Yh({onNavigate:e,t}){const[r,i]=O.useState([]),[a,g]=O.useState(!0),[b,n]=O.useState(null),[o,d]=O.useState(null),f=O.useCallback(async()=>{try{const v=await Oe("/api/v1/channels");if(v.ok){const k=await v.json();i((k.clients||[]).filter(E=>!E.hidden&&!E.instanceId.startsWith("_pending")))}}catch{}finally{g(!1)}},[]);O.useEffect(()=>{f();const v=setInterval(f,5e3);return()=>clearInterval(v)},[f]);const h=O.useCallback(async(v,k,E)=>{const C=`${k}:${E}:${v}`;d(C),n(null);try{const N=v==="delete"?"DELETE":"POST",R=v==="delete"?`/api/v1/channels/${k}/${E}`:`/api/v1/channels/${k}/${E}/${v}`,B=await Oe(R,{method:N});if(!B.ok){const A=await B.json().catch(()=>({}));throw new Error(A.error||`Failed: ${B.status}`)}await f()}catch(N){n((N==null?void 0:N.message)||"Action failed")}finally{d(null)}},[f]),_=v=>v==="connected"?"text-green-500":v==="connecting"?"text-yellow-500":v==="error"?"text-red-500":"text-text-tertiary",S=v=>t(v==="connected"?"remoteControl.connected":v==="connecting"?"remoteControl.connecting":"remoteControl.disconnected"),w=v=>v==="wechat"?s.jsx(hc,{size:18,className:"text-green-500"}):v==="wecom"?s.jsx(Ar,{size:18,className:"text-accent-brand"}):s.jsx(ml,{size:18,className:"text-text-tertiary"}),y=v=>v==="wechat"?t("channel.wechat")+t("remoteControl.bot"):v==="wecom"?t("channel.wecom")+t("remoteControl.bot"):v,c=v=>`${y(v.clientType)} #${v.instanceId.slice(0,4)}`,p=r.filter(v=>v.clientType==="wechat"),l=r.filter(v=>v.clientType==="wecom"),u=r.filter(v=>v.clientType!=="wechat"&&v.clientType!=="wecom"),m=v=>{const k=`${v.clientType}:${v.instanceId}`,E=v.status==="connected",C=o==null?void 0:o.startsWith(k);return s.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-lg bg-bg-secondary hover:bg-bg-hover transition-colors cursor-pointer",onClick:()=>{C||h(E?"stop":"start",v.clientType,v.instanceId)},children:[w(v.clientType),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsx("div",{className:"text-sm font-medium text-text-primary truncate",children:c(v)}),s.jsx("span",{className:`text-xs ${_(v.status)}`,children:S(v.status)})]}),s.jsxs("div",{className:"flex items-center gap-1",onClick:N=>N.stopPropagation(),children:[s.jsx("button",{className:`p-1.5 rounded-md text-text-tertiary transition-colors ${E?"hover:text-orange-500":"hover:text-green-500"} hover:bg-bg-hover`,title:t(E?"remoteControl.disconnect":"remoteControl.connect"),disabled:!!C,onClick:()=>h(E?"stop":"start",v.clientType,v.instanceId),children:E?s.jsx(ml,{size:14}):s.jsx(zd,{size:14})}),E&&s.jsx("button",{className:"p-1.5 rounded-md text-text-tertiary hover:text-orange-500 hover:bg-bg-hover transition-colors",title:t("remoteControl.unbind"),disabled:!!C,onClick:()=>h("unbind",v.clientType,v.instanceId),children:s.jsx(Dt,{size:14})}),s.jsx("button",{className:"p-1.5 rounded-md text-text-tertiary hover:text-red-500 hover:bg-bg-hover transition-colors",title:t("remoteControl.delete"),disabled:!!C,onClick:()=>h("delete",v.clientType,v.instanceId),children:s.jsx(Mt,{size:14})})]})]},k)},x=(v,k,E,C)=>s.jsxs("div",{children:[s.jsx("h2",{className:"text-sm font-medium text-text-secondary mb-2",children:v}),k.length===0?s.jsx("div",{className:"py-4 text-center text-xs text-text-tertiary",children:t("remoteControl.noChannels")}):s.jsx("div",{className:"space-y-2",children:k.map(m)}),E&&s.jsxs("button",{className:"flex items-center gap-1.5 mt-2 px-3 py-1.5 text-xs text-text-tertiary hover:text-text-primary hover:bg-bg-hover rounded-md transition-colors",onClick:E,children:[s.jsx(Ke,{size:12}),C||t("remoteControl.add")]})]});return s.jsxs("div",{className:"flex flex-col h-full overflow-y-auto",children:[s.jsxs("div",{className:"px-6 py-5 border-b border-border-primary",children:[s.jsx("h1",{className:"text-lg font-semibold text-text-primary",children:t("remoteControl.title")}),s.jsx("p",{className:"text-sm text-text-tertiary mt-1",children:t("remoteControl.subtitle")})]}),s.jsxs("div",{className:"px-6 py-4 flex-1 space-y-6",children:[b&&s.jsx("div",{className:"p-3 rounded-lg bg-red-500/10 text-red-500 text-sm",children:b}),a?s.jsx("div",{className:"text-sm text-text-tertiary py-4",children:t("remoteControl.connecting")}):r.length===0?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"py-8 text-center",children:[s.jsx(Ar,{size:32,className:"mx-auto mb-3 text-text-tertiary opacity-50"}),s.jsx("p",{className:"text-sm text-text-tertiary",children:t("remoteControl.noChannels")}),s.jsx("p",{className:"text-xs text-text-tertiary mt-1",children:t("remoteControl.noChannelsHint")})]}),s.jsxs("div",{className:"flex gap-3",children:[s.jsxs("button",{className:"flex items-center gap-2 px-4 py-2 rounded-lg bg-bg-secondary hover:bg-bg-hover text-sm text-text-primary transition-colors border border-border-primary",onClick:()=>Xt("remote-control","add-wechat"),children:[s.jsx(Ke,{size:14}),t("remoteControl.addWeChat")]}),s.jsxs("button",{className:"flex items-center gap-2 px-4 py-2 rounded-lg bg-bg-secondary hover:bg-bg-hover text-sm text-text-primary transition-colors border border-border-primary",onClick:()=>Xt("remote-control","add-wecom"),children:[s.jsx(Ke,{size:14}),t("remoteControl.addWeCom")]})]})]}):s.jsxs(s.Fragment,{children:[x(t("channel.wechat")+t("remoteControl.bot"),p,()=>Xt("remote-control","add-wechat"),t("remoteControl.addWeChat")),x(t("channel.wecom")+t("remoteControl.bot"),l,()=>Xt("remote-control","add-wecom"),t("remoteControl.addWeCom")),u.length>0&&x(t("remoteControl.plugin"),u)]}),s.jsx("hr",{className:"border-border-primary"}),s.jsxs("div",{className:"flex items-center gap-4 p-4 rounded-lg bg-bg-secondary hover:bg-bg-hover cursor-pointer transition-colors border border-border-primary",onClick:()=>{e?e("plugins"):window.location.hash="#/plugins"},children:[s.jsxs("div",{className:"flex-1",children:[s.jsx("h3",{className:"text-sm font-medium text-text-primary",children:t("remoteControl.installMore")}),s.jsx("p",{className:"text-xs text-text-tertiary mt-1",children:t("remoteControl.installMoreHint")})]}),s.jsx(sc,{size:16,className:"text-text-tertiary"})]})]})]})}function Xh({onBack:e,t}){const[r,i]=O.useState(null),[a,g]=O.useState(t("remoteControl.fetchingQr")),[b,n]=O.useState(null),[o,d]=O.useState(null),[f,h]=O.useState(!1);return O.useEffect(()=>{let _=!1;return(async()=>{try{const S=await Oe("/api/v1/channels/wechat",{method:"POST"});if(!S.ok)throw new Error((await S.json().catch(()=>({}))).error||"Failed");const w=await S.json();if(_)return;n(w.instanceId);for(let y=0;y<180&&!_;y++){await new Promise(c=>setTimeout(c,1e3));try{const c=await fetch(`/api/v1/channels/wechat/${w.instanceId}/qr`);if(!c.ok)continue;const p=await c.json();if(_)return;if(p.qrUrl&&i(p.qrUrl),p.message&&g(p.message),p.type==="confirmed"){h(!0),g(t("remoteControl.connected")),setTimeout(()=>{_||e()},1500);return}if(p.type==="error"){d(p.message);return}}catch{}}!_&&!f&&d("Timeout")}catch(S){_||d((S==null?void 0:S.message)||"Failed")}})(),()=>{_=!0}},[]),s.jsxs("div",{className:"flex flex-col h-full overflow-y-auto",children:[s.jsxs("div",{className:"px-6 py-5 border-b border-border-primary flex items-center gap-3",children:[s.jsx("button",{onClick:e,className:"p-1 rounded-md hover:bg-bg-hover transition-colors",children:s.jsx(Vr,{size:18})}),s.jsxs("div",{children:[s.jsx("h1",{className:"text-lg font-semibold text-text-primary",children:t("remoteControl.addWeChat")}),s.jsx("p",{className:"text-sm text-text-tertiary",children:t("remoteControl.scanQr")})]})]}),s.jsx("div",{className:"flex-1 flex flex-col items-center justify-center px-6 py-8",children:o?s.jsxs("div",{className:"text-center space-y-4",children:[s.jsx("p",{className:"text-red-500",children:o}),s.jsx("button",{onClick:e,className:"px-4 py-2 rounded-lg bg-bg-secondary hover:bg-bg-hover text-sm border border-border-primary",children:t("remoteControl.cancel")})]}):r?s.jsxs("div",{className:"text-center space-y-4",children:[s.jsx("div",{className:"inline-block p-4 bg-white rounded-xl",children:s.jsx("img",{src:`https://api.qrserver.com/v1/create-qr-code/?size=240x240&data=${encodeURIComponent(r)}`,alt:"QR Code",className:"w-60 h-60"})}),s.jsx("p",{className:"text-sm text-text-secondary",children:a})]}):s.jsxs("div",{className:"text-center space-y-3",children:[s.jsx("div",{className:"w-8 h-8 mx-auto border-2 border-accent-brand border-t-transparent rounded-full animate-spin"}),s.jsx("p",{className:"text-sm text-text-tertiary",children:a})]})})]})}function Zh({onBack:e,t}){const[r,i]=O.useState(""),[a,g]=O.useState(""),[b,n]=O.useState("botId"),[o,d]=O.useState(!1),[f,h]=O.useState(null),_=O.useCallback(async()=>{if(!(!r.trim()||!a.trim())){d(!0),h(null);try{const S=await Oe("/api/v1/channels/wecom",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({botId:r.trim(),secret:a.trim()})});if(!S.ok){const w=await S.json().catch(()=>({}));throw new Error(w.error||"Failed")}e()}catch(S){h((S==null?void 0:S.message)||"Failed")}finally{d(!1)}}},[r,a,e]);return s.jsxs("div",{className:"flex flex-col h-full overflow-y-auto",children:[s.jsxs("div",{className:"px-6 py-5 border-b border-border-primary flex items-center gap-3",children:[s.jsx("button",{onClick:e,className:"p-1 rounded-md hover:bg-bg-hover transition-colors",children:s.jsx(Vr,{size:18})}),s.jsxs("div",{children:[s.jsx("h1",{className:"text-lg font-semibold text-text-primary",children:t("remoteControl.addWeCom")}),s.jsx("p",{className:"text-sm text-text-tertiary",children:t("remoteControl.wecomBotIdHint")})]})]}),s.jsxs("div",{className:"px-6 py-8 max-w-md mx-auto w-full space-y-6",children:[f&&s.jsx("div",{className:"p-3 rounded-lg bg-red-500/10 text-red-500 text-sm",children:f}),s.jsxs("div",{className:"space-y-2",children:[s.jsx("label",{className:"text-sm font-medium text-text-primary",children:"Bot ID"}),s.jsx("input",{type:"text",className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-primary text-sm text-text-primary placeholder-text-tertiary focus:outline-none focus:border-accent-brand transition-colors",placeholder:"Enter Bot ID",value:r,onChange:S=>i(S.target.value),autoFocus:!0,disabled:b==="secret",onKeyDown:S=>{S.key==="Enter"&&r.trim()&&n("secret")}})]}),b==="secret"&&s.jsxs("div",{className:"space-y-2",children:[s.jsx("label",{className:"text-sm font-medium text-text-primary",children:"Secret"}),s.jsx("input",{type:"password",className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-primary text-sm text-text-primary placeholder-text-tertiary focus:outline-none focus:border-accent-brand transition-colors",placeholder:"Enter Secret",value:a,onChange:S=>g(S.target.value),autoFocus:!0,onKeyDown:S=>{S.key==="Enter"&&a.trim()&&_()}}),s.jsx("p",{className:"text-xs text-text-tertiary",children:t("remoteControl.wecomSecretHint")})]}),s.jsxs("div",{className:"flex gap-3 pt-2",children:[b==="botId"?s.jsx("button",{className:"px-4 py-2 rounded-lg bg-accent-brand text-white text-sm hover:bg-accent-brand/90 transition-colors disabled:opacity-50",disabled:!r.trim(),onClick:()=>n("secret"),children:t("remoteControl.next")}):s.jsx("button",{className:"px-4 py-2 rounded-lg bg-accent-brand text-white text-sm hover:bg-accent-brand/90 transition-colors disabled:opacity-50",disabled:!a.trim()||o,onClick:_,children:t(o?"remoteControl.connecting":"remoteControl.connect")}),s.jsx("button",{className:"px-4 py-2 rounded-lg bg-bg-secondary border border-border-primary text-sm text-text-secondary hover:bg-bg-hover transition-colors",onClick:e,children:t("remoteControl.cancel")})]})]})]})}const Qh="data:image/svg+xml,%3csvg%20width='24'%20height='24'%20viewBox='0%200%2024%2024'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3cg%20clip-path='url(%23copilot-clip-34e811bed903495093b85bf96a98fb1b_0)'%3e%3crect%20width='24'%20height='24'%20rx='12'%20fill='%234C4F6B'%3e%3c/rect%3e%3cpath%20d='M3.4689%2011.0144C3.32344%2011.2025%203.31607%2011.4567%203.4345%2012.0298C3.65883%2013.0748%204.24029%2014.4426%205.15579%2016.0716L5.747%2017.1172L5.72862%2017.511C5.70544%2017.9326%205.72848%2018.5857%205.77921%2019.0271C5.80994%2019.2967%205.8055%2019.3035%205.66483%2019.4638C5.12042%2020.0864%205.03916%2021.1287%205.44787%2022.2839C5.62456%2022.7775%206.16958%2023.6999%206.50726%2024.0756C7.35392%2025.0154%208.35051%2025.4646%209.11147%2025.246C9.25446%2025.2051%209.28403%2025.213%209.47117%2025.3424C10.182%2025.8233%2011.3834%2026.2377%2012.4447%2026.3663C14.2242%2026.5843%2016.2727%2026.143%2018.8281%2024.9925C19.8948%2024.5099%2022.2541%2023.1352%2023.2513%2022.4096C25.1083%2021.0667%2026.4805%2019.6414%2027.251%2018.2635C27.9337%2017.0364%2028.2735%2015.7781%2028.2495%2014.5174C28.2466%2014.2525%2028.2536%2014.2359%2028.3599%2014.1746C28.8797%2013.8703%2029.1497%2013.198%2029.0927%2012.3562C29.075%2012.1165%2029.0266%2011.7946%2028.9902%2011.6448C28.7404%2010.7144%2028.0885%209.59971%2027.4078%208.94729C26.6515%208.22182%2025.7943%207.9129%2025.1958%208.14598C25.0631%208.19758%2025.0452%208.19542%2024.9177%208.08995C24.6357%207.86124%2023.9604%207.43473%2023.5488%207.22673L23.1224%207.01477L22.8206%206.45595C22.0392%205.01609%2020.7826%203.33003%2019.8801%202.50992C19.4937%202.15818%2019.2668%202.03929%2019.019%202.05739C18.866%202.06657%2018.8535%202.07379%2018.645%202.26084C18.0389%202.79819%2017.1889%204.41355%2016.3588%206.60463L16.1271%207.21325L15.7053%207.34845C14.3909%207.76995%2013.2238%208.30219%2012.1896%208.94928C11.1973%209.56799%2010.6591%209.97037%209.84886%2010.688L9.36087%2011.1197L9.13878%2011.0813C7.00072%2010.7039%205.07892%2010.5639%204.19776%2010.7186C3.84772%2010.7832%203.55743%2010.9008%203.4689%2011.0144Z'%20fill='%23D2D3E0'%3e%3c/path%3e%3crect%20x='6.68555'%20y='16.3788'%20width='17.7918'%20height='11.5605'%20rx='4.61469'%20transform='rotate(-30%206.68555%2016.3788)'%20fill='%23212234'%3e%3c/rect%3e%3cg%3e%3crect%20x='12.2119'%20y='17.2593'%20width='2.13173'%20height='4.42744'%20rx='1.06587'%20transform='rotate(-30%2012.2119%2017.2593)'%20fill='%23D2D3E0'%3e%3canimate%20attributeName='height'%20values='4.42744;2.2;4.42744;4.42744;2.2;4.42744'%20dur='0.6s'%20begin='0s;blink134e811bed903495093b85bf96a98fb1b_0.end+3s'%20id='blink134e811bed903495093b85bf96a98fb1b_0'%3e%3c/animate%3e%3canimate%20attributeName='y'%20values='17.2593;18.2593;17.2593;17.2593;18.2593;17.2593'%20dur='0.6s'%20begin='0s;blink134e811bed903495093b85bf96a98fb1b_0.end+3s'%3e%3c/animate%3e%3canimate%20attributeName='opacity'%20values='1;0.2;1;1;0.2;1'%20dur='0.6s'%20begin='0s;blink134e811bed903495093b85bf96a98fb1b_0.end+3s'%3e%3c/animate%3e%3c/rect%3e%3c/g%3e%3cg%3e%3crect%20x='17.9634'%20y='13.9387'%20width='2.13173'%20height='4.42744'%20rx='1.06587'%20transform='rotate(-30%2017.9634%2013.9387)'%20fill='%23D2D3E0'%3e%3canimate%20attributeName='height'%20values='4.42744;2.2;4.42744;4.42744;2.2;4.42744'%20dur='0.6s'%20begin='0s;blink234e811bed903495093b85bf96a98fb1b_0.end+3s'%20id='blink234e811bed903495093b85bf96a98fb1b_0'%3e%3c/animate%3e%3canimate%20attributeName='y'%20values='13.9387;14.9387;13.9387;13.9387;14.9387;13.9387'%20dur='0.6s'%20begin='0s;blink234e811bed903495093b85bf96a98fb1b_0.end+3s'%3e%3c/animate%3e%3canimate%20attributeName='opacity'%20values='1;0.2;1;1;0.2;1'%20dur='0.6s'%20begin='0s;blink234e811bed903495093b85bf96a98fb1b_0.end+3s'%3e%3c/animate%3e%3c/rect%3e%3c/g%3e%3c/g%3e%3cdefs%3e%3cclipPath%20id='copilot-clip-34e811bed903495093b85bf96a98fb1b_0'%3e%3crect%20width='24'%20height='24'%20rx='12'%20fill='white'%3e%3c/rect%3e%3c/clipPath%3e%3c/defs%3e%3c/svg%3e",Jh="/assets/logo-iZVLr450.svg",eg=Ge(e=>({userInfo:null,loading:!1,error:null,fetchUserInfo:async t=>{e({loading:!0,error:null});try{const r=await t.getUserInfo();r.userInfo?e({userInfo:r.userInfo,loading:!1}):e({loading:!1})}catch(r){console.warn("[user] Failed to fetch user info:",r),e({error:r.message,loading:!1})}},clearUserInfo:()=>{e({userInfo:null,error:null})}}));function tg({isOpen:e,onClose:t,mainView:r,onNavigate:i}){const{t:a}=ue(),{userInfo:g,fetchUserInfo:b}=eg(),n=Hr(_=>_.info),o=Hr(_=>_.fetch);O.useEffect(()=>{n||o();const _=xe();b(_)},[b,o,n]);const d=(g==null?void 0:g.userName)||(n==null?void 0:n.userName)||a("sidebar.user"),f=(n==null?void 0:n.version)||"",h=f&&f!=="dev"?`v${f}`:"CodeBuddy Code";return s.jsxs(s.Fragment,{children:[s.jsx("div",{className:`sidebar-overlay ${e?"":"sidebar-overlay-hidden"}`,onClick:t}),s.jsxs("aside",{className:`sidebar ${e?"":"sidebar-closed"}`,children:[s.jsxs("div",{className:"sidebar-header",children:[s.jsx("img",{src:Jh,alt:"CodeBuddy",className:"sidebar-logo"}),s.jsx("span",{className:"sidebar-brand",children:"CodeBuddy"}),s.jsx("div",{className:"flex-1"}),s.jsx("button",{onClick:t,className:"md:hidden w-7 h-7 flex items-center justify-center rounded-md text-text-tertiary hover:text-text-primary hover:bg-bg-hover transition-colors",children:s.jsx(Ie,{size:16})})]}),s.jsxs("nav",{className:"sidebar-nav",children:[s.jsxs("button",{className:`sidebar-nav-item ${r==="chat"?"active":""}`,onClick:()=>i("chat"),children:[s.jsx(gc,{size:16}),s.jsx("span",{children:a("sidebar.chatMode")})]}),s.jsxs("button",{className:`sidebar-nav-item ${r==="instances"?"active":""}`,onClick:()=>i("instances"),children:[s.jsx(ct,{size:16}),s.jsx("span",{children:a("sidebar.instances")})]}),s.jsxs("button",{className:`sidebar-nav-item ${r==="remote-control"?"active":""}`,onClick:()=>i("remote-control"),children:[s.jsx(Ar,{size:16}),s.jsx("span",{children:a("sidebar.remoteControl")})]})]}),s.jsx("div",{className:"sidebar-content",children:s.jsxs("div",{className:"px-3 py-1",children:[s.jsxs("button",{className:`sidebar-nav-item ${r==="tasks"?"active":""}`,onClick:()=>i("tasks"),children:[s.jsx(uc,{size:16}),s.jsx("span",{children:a("sidebar.nav.tasks")})]}),s.jsxs("button",{className:`sidebar-nav-item ${r==="terminal"?"active":""}`,onClick:()=>i("terminal"),children:[s.jsx(mc,{size:16}),s.jsx("span",{children:a("sidebar.terminalMode")})]}),s.jsxs("button",{className:`sidebar-nav-item ${r==="plugins"?"active":""}`,onClick:()=>i("plugins"),children:[s.jsx(gt,{size:16}),s.jsx("span",{children:a("sidebar.nav.plugins")})]}),s.jsxs("button",{className:`sidebar-nav-item ${r==="settings"?"active":""}`,onClick:()=>i("settings"),children:[s.jsx(fc,{size:16}),s.jsx("span",{children:a("sidebar.preferences")})]})]})}),s.jsx("div",{className:"sidebar-footer",children:s.jsxs("div",{className:"sidebar-user",children:[s.jsx("img",{src:Qh,alt:"User",className:"sidebar-user-avatar"}),s.jsxs("div",{className:"sidebar-user-info",children:[s.jsx("div",{className:"sidebar-user-name",children:d}),s.jsx("div",{className:"sidebar-user-status",children:h})]})]})})]})]})}function rg({onMenuClick:e,onNewChat:t,onSplitTerminal:r,onHistory:i,hasHistory:a,rightActions:g}){const{t:b}=ue(),{topic:n}=Xe(),{mainView:o,layout:d,terminalTitle:f}=me(),[h,_]=O.useState(!1),S=O.useRef(null),w=o==="terminal",c=ft(d)<Wc;O.useEffect(()=>{if(!h)return;const m=x=>{S.current&&!S.current.contains(x.target)&&_(!1)};return document.addEventListener("mousedown",m),()=>document.removeEventListener("mousedown",m)},[h]);const p=O.useCallback(m=>{_(!1),r==null||r(m)},[r]),l=()=>{switch(o){case"chat":return n||b("chat.newChat");case"terminal":return f||b("terminal.title");case"instances":return b("instance.managerTitle");case"settings":return b("settings.title");case"tasks":return b("tasks.title");case"plugins":return b("sidebar.nav.plugins");default:return""}},u=()=>g||(w?s.jsxs("div",{ref:S,className:"relative",children:[s.jsx("button",{onClick:()=>c&&_(!h),className:`text-text-secondary transition-colors flex items-center justify-center w-8 h-8 rounded-full ${c?"hover:text-text-primary hover:bg-bg-secondary":"opacity-40 cursor-not-allowed"}`,title:c?void 0:b("terminal.maxPanes"),children:s.jsx(gl,{size:20})}),h&&s.jsxs("div",{className:"absolute right-0 top-full mt-1 bg-bg-secondary border border-border-muted rounded-lg shadow-lg py-1 z-50 min-w-[140px]",children:[s.jsxs("button",{onClick:()=>p("horizontal"),className:"w-full flex items-center gap-3 px-4 py-2.5 text-[13px] text-text-primary hover:bg-bg-hover transition-colors",children:[s.jsx(gl,{size:16,className:"text-text-secondary"}),s.jsx("span",{children:b("terminal.splitHorizontal")})]}),s.jsxs("button",{onClick:()=>p("vertical"),className:"w-full flex items-center gap-3 px-4 py-2.5 text-[13px] text-text-primary hover:bg-bg-hover transition-colors",children:[s.jsx(Qd,{size:16,className:"text-text-secondary"}),s.jsx("span",{children:b("terminal.splitVertical")})]})]})]}):o==="chat"?s.jsxs("div",{className:"flex items-center gap-1",children:[s.jsx("button",{onClick:t,className:"text-text-secondary hover:text-text-primary transition-colors flex items-center justify-center w-8 h-8 rounded-full hover:bg-bg-secondary",children:s.jsx(Ke,{size:20})}),a&&s.jsx("button",{onClick:i,className:"text-text-secondary hover:text-text-primary transition-colors flex items-center justify-center w-8 h-8 rounded-full hover:bg-bg-secondary",title:b("sidebar.chatHistory"),children:s.jsx(cc,{size:18})})]}):null);return s.jsxs("div",{className:"flex items-center justify-between px-4 sm:px-6 h-14 bg-bg-primary text-xs flex-shrink-0 transition-colors duration-200 sticky top-0 z-10",children:[s.jsx("div",{className:"flex items-center gap-4",children:s.jsx("button",{onClick:e,className:"text-text-secondary hover:text-text-primary transition-colors flex items-center justify-center w-8 h-8 rounded-full hover:bg-bg-secondary",children:s.jsx(Vd,{size:20})})}),s.jsx("div",{className:"flex-1 flex justify-center items-center min-w-0 px-2",children:s.jsx("span",{className:"font-medium text-text-primary text-[15px] tracking-wide truncate max-w-full",children:l()})}),s.jsx("div",{className:"flex items-center",children:u()})]})}function ng(e){var r;const t=new Map;for(const i of e){if(i.type!=="tool_call")continue;const a=i;if(!((r=a.subagent)!=null&&r.memberName))continue;const g=a.subagent.memberName,b=t.get(g),n=a.subagentTimeline||[],o=n.filter(f=>f.type==="tool_call_ref").length;let d;if(a.status==="running"&&a.children&&a.children.length>0)for(let f=n.length-1;f>=0;f--){const h=n[f];if(h.type==="tool_call_ref"){d=h.toolCallId;break}}b?(a.status==="running"&&(b.status="running",b.currentTool=d),b.toolCount=Math.max(b.toolCount,o),a.subagent.description&&(b.description=a.subagent.description)):t.set(g,{name:g,description:a.subagent.description||"",status:a.status,currentTool:d,toolCount:o})}return Array.from(t.values())}function ig(){const{t:e}=ue(),t=Le(n=>n.timeline),r=Le(n=>n.childToolCalls),i=O.useMemo(()=>ng(t),[t]);if(!i.some(n=>n.status==="running")||i.length===0)return null;const g=i.filter(n=>n.status==="running").length,b=i.filter(n=>n.status!=="running").length;return s.jsxs("div",{className:"flex-none border-t border-border-muted/40 bg-bg-secondary/30",children:[s.jsxs("div",{className:"flex items-center gap-2 px-4 py-1.5",children:[s.jsx(_c,{size:13,className:"text-accent-purple"}),s.jsx("span",{className:"text-[12px] font-medium text-text-secondary",children:e("team.title")}),s.jsxs("span",{className:"text-[11px] text-text-tertiary",children:[e("team.activeCount").replace("{count}",String(g)),b>0?` · ${e("team.doneCount").replace("{count}",String(b))}`:""]})]}),s.jsx("div",{className:"flex flex-wrap gap-x-3 gap-y-1 px-4 pb-2",children:i.map(n=>s.jsx(sg,{member:n,childToolCalls:r},n.name))})]})}function sg({member:e,childToolCalls:t}){const r=e.status==="running",i=e.status==="failed";let a;if(e.currentTool){const g=t.get(e.currentTool);g&&(a=g.name||g.toolName)}return s.jsxs("div",{className:`inline-flex items-center gap-1.5 px-2 py-1 rounded-md text-[12px] transition-colors ${r?"bg-accent-purple/10 text-accent-purple":i?"bg-accent-red/10 text-accent-red":"bg-bg-secondary/50 text-text-tertiary"}`,children:[s.jsx("div",{className:`w-3.5 h-3.5 rounded-full flex items-center justify-center flex-shrink-0 ${r?"bg-accent-purple/20":"bg-transparent"}`,children:s.jsx(ct,{size:10})}),s.jsxs("span",{className:"font-medium",children:["@",e.name]}),a&&r&&s.jsx("span",{className:"text-[11px] opacity-70 truncate max-w-[120px]",children:a}),r&&s.jsx(De,{size:10,className:"animate-spin flex-shrink-0"}),i&&s.jsx(Cr,{size:10,className:"flex-shrink-0"}),!r&&!i&&s.jsx(Ye,{size:10,className:"flex-shrink-0"})]})}function ag(e,t){const r=[];for(const i of e)i.type==="tool_call"&&r.push(i);for(const i of t.values())r.push(i);return r}function og(e){const t={};for(const r of e){const i=r.input||{},a=r.toolName;if(a==="TaskCreate"){const g=r.result,b=typeof g=="string"?g:g&&typeof g=="object"?String(g.text??g.output??""):"",n=!b&&Array.isArray(r.content)?r.content.reduce((f,h)=>{var S;const _=((S=h==null?void 0:h.content)==null?void 0:S.text)??(h==null?void 0:h.text)??(typeof h=="string"?h:"");return f||String(_)},""):"",o=(b||n).match(/Task #(\d+)/),d=o?o[1]:`t-${Object.keys(t).length+1}`;t[d]={id:d,subject:i.subject?String(i.subject):"",status:"pending",owner:i.owner?String(i.owner):void 0,activeForm:i.activeForm?String(i.activeForm):void 0}}else if(a==="TaskUpdate"){const g=i.taskId?String(i.taskId):void 0;if(g&&t[g]){const b=t[g];i.status&&i.status!=="deleted"&&(b.status=String(i.status)),i.subject&&(b.subject=String(i.subject)),i.owner!==void 0&&(b.owner=i.owner?String(i.owner):void 0),i.activeForm&&(b.activeForm=String(i.activeForm)),i.status==="deleted"&&delete t[g]}}}return Object.values(t)}function lg(e){let t=0;for(const r of e)(r.toolName==="TaskCreate"||r.toolName==="TaskUpdate")&&t++;return t}function cg({status:e}){switch(e){case"completed":return s.jsx(ac,{size:14,className:"text-accent-green flex-shrink-0"});case"in_progress":return s.jsx(De,{size:14,className:"text-accent-brand flex-shrink-0 animate-spin"});default:return s.jsx(Bd,{size:14,className:"text-text-tertiary flex-shrink-0"})}}function dg(){const e=Le(m=>m.timeline),t=Le(m=>m.childToolCalls),r=Le(m=>m.isAgentRunning),{t:i}=ue(),[a,g]=O.useState(!0),b=O.useRef(0),[n,o]=O.useState(!1),d=O.useRef(r),f=O.useMemo(()=>ag(e,t),[e,t]),h=O.useMemo(()=>og(f),[f]),_=O.useMemo(()=>lg(f),[f]);O.useEffect(()=>{!d.current&&r&&(b.current=_,o(!0)),d.current=r},[r,_]),O.useEffect(()=>{n&&_>b.current&&o(!1)},[n,_]);const S=O.useCallback(()=>g(m=>!m),[]),w=O.useCallback(m=>{m.stopPropagation(),b.current=_,o(!0)},[_]);if(h.length===0||h.length>0&&h.every(m=>m.status==="completed")&&!r||n)return null;const c=h.filter(m=>m.status==="completed").length,p=h.length,l=h.find(m=>m.status==="in_progress"),u=l?l.activeForm||l.subject:`${c}/${p} ${i("todo.title")}`;return s.jsx("div",{className:"flex-none px-4 sm:px-6 pb-1",children:s.jsx("div",{className:"max-w-3xl mx-auto",children:s.jsxs("div",{className:"rounded-lg border border-border-muted/60 bg-bg-secondary/50 shadow-sm overflow-hidden backdrop-blur-sm",children:[s.jsxs("button",{onClick:S,className:"flex items-center gap-2 w-full px-3 py-1.5 hover:bg-bg-hover/30 transition-colors cursor-pointer",children:[s.jsx(pc,{size:13,className:"text-text-tertiary flex-shrink-0"}),s.jsx("span",{className:"text-xs font-medium text-text-primary",children:i("todo.title")}),s.jsxs("span",{className:"text-[11px] text-text-tertiary tabular-nums",children:[c,"/",p]}),!a&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-border-muted/60 select-none",children:"|"}),l&&r&&s.jsx(De,{size:10,className:"text-accent-brand animate-spin flex-shrink-0"}),s.jsx("span",{className:"text-xs text-text-secondary truncate flex-1 text-left",children:u})]}),s.jsx("span",{className:"flex-1"}),!r&&s.jsx("span",{role:"button",tabIndex:0,onClick:w,onKeyDown:m=>{m.key==="Enter"&&w(m)},className:"text-text-tertiary hover:text-text-primary p-0.5 rounded transition-colors flex-shrink-0",children:s.jsx(Ie,{size:12})}),a?s.jsx(Nt,{size:12,className:"text-text-tertiary flex-shrink-0"}):s.jsx(It,{size:12,className:"text-text-tertiary flex-shrink-0"})]}),a&&s.jsx("div",{className:"border-t border-border-muted/40 px-3 py-1.5 space-y-0.5 max-h-52 overflow-y-auto",children:h.map((m,x)=>s.jsxs("div",{className:`flex items-center gap-2 py-0.5 text-xs ${m.status==="in_progress"?"text-text-primary":m.status==="completed"?"text-text-tertiary":"text-text-secondary"}`,children:[s.jsx(cg,{status:m.status}),s.jsxs("span",{className:`truncate ${m.status==="completed"?"line-through":""}`,children:[x+1,". ",m.status==="in_progress"?m.activeForm||m.subject||i("todo.untitled"):m.subject||i("todo.untitled")]})]},m.id))})]})})})}function ug(){const{viewState:e,checkAuth:t}=zc(),{status:r,sessionId:i,topic:a,setPromptSuggestion:g,setTopic:b}=Xe(),{connect:n}=Rd(),{clearChat:o}=Le(),{t:d,resolved:f}=ue(),[h,_]=O.useState(()=>{try{const F=sessionStorage.getItem("codebuddy_sidebar_open");return F!==null?window.innerWidth>=768?F==="true":!1:window.innerWidth>=768}catch{return window.innerWidth>=768}}),S=O.useRef(h),[w,y]=O.useState(!1),[c,p]=O.useState(!1),{splitPane:l,mainView:u,setMainView:m}=me(),x=O.useCallback(F=>{_(M=>{const H=typeof F=="function"?F(M):F;S.current=H;try{sessionStorage.setItem("codebuddy_sidebar_open",String(H))}catch{}return H})},[]);O.useEffect(()=>{const F=window.matchMedia("(min-width: 768px)"),M=H=>{H.matches?_(S.current):_(!1)};return F.addEventListener("change",M),()=>F.removeEventListener("change",M)},[]);const[v,k]=O.useState(!1),E=O.useRef();O.useEffect(()=>r!=="connected"?void 0:((()=>{fetch("/api/v1/sessions",{headers:Fe()}).then(M=>M.ok?M.json():null).then(M=>{M!=null&&M.sessions&&k(M.sessions.length>1)}).catch(()=>{})})(),()=>{E.current&&clearTimeout(E.current)}),[r,i]);const C=O.useCallback(F=>{l(F)},[l]),N=O.useCallback(async()=>{if(i){try{await xe().prompt(i,"/clear")}catch(F){console.error("New chat (/clear) failed:",F)}o(),b(null),g(null),m("chat"),window.location.hash="/chat"}},[i,o,b,g,m]),R=O.useCallback(async F=>{if(i){try{await xe().prompt(i,`/resume ${F}`)}catch(M){console.error("Switch session failed:",M)}m("chat"),window.location.hash="/chat"}},[i,m]),B=O.useCallback(F=>{m(F),window.location.hash=`/${F}`,window.innerWidth<768&&_(!1)},[m]);if(O.useEffect(()=>{const F=new URLSearchParams(window.location.search),M=F.get("password"),H=F.get("token");if(M||H){Hc(M||H),F.delete("password"),F.delete("token");const z=F.toString()?`${window.location.pathname}?${F.toString()}`:window.location.pathname;window.history.replaceState({},"",z)}t()},[t]),O.useEffect(()=>{if(e==="authenticated"){const F=sd();m(F),(!window.location.hash||window.location.hash==="#")&&(window.location.hash=`/${F}`)}},[e,m]),O.useEffect(()=>Vh(M=>{m(M)}),[m]),O.useEffect(()=>{if(e==="authenticated"){const F=Ht()||void 0;n({token:F,continue:!0})}},[e,n]),O.useEffect(()=>{document.documentElement.lang=f,document.title=a?`${a} - CodeBuddy Code`:d("page.title")},[f,d,a]),e==="loading")return s.jsx("div",{className:"flex h-screen h-[100dvh] bg-bg-primary text-text-primary transition-colors duration-200 font-sans overflow-hidden",children:s.jsx("div",{className:"flex-1 flex items-center justify-center",children:s.jsx(lt,{size:"large",text:d("app.connecting")})})});if(e==="login")return s.jsx(Wh,{});const A=()=>{if(r==="connecting")return s.jsx("div",{className:"flex-1 flex items-center justify-center",children:s.jsx(lt,{size:"large",text:d("app.connecting")})});if(r!=="connected"&&u!=="settings")return s.jsx("div",{className:"flex-1 flex items-center justify-center",children:s.jsxs("div",{className:"text-center",children:[s.jsx("div",{className:"text-text-secondary mb-4 font-medium",children:d("app.connectFailed")}),s.jsx("button",{onClick:()=>n(),className:"px-6 py-2.5 bg-accent-brand text-white rounded-full text-sm font-medium transition-all hover:bg-accent-brand/90 hover:scale-105 active:scale-95 shadow-sm",children:d("app.retry")})]})});switch(u){case"chat":return s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"flex-1 overflow-hidden w-full relative",children:s.jsx(Qp,{onClickCloseBottomSheet:()=>p(!1)})}),s.jsx(ig,{}),s.jsx(dg,{}),s.jsx("div",{className:"flex-none bg-bg-primary",children:s.jsx(zh,{onNavigate:B,onNewChat:N,onHistory:()=>y(!0),mainView:u,showBottomSheet:c,setShowBottomSheet:p})})]});case"tasks":return s.jsx(ed,{});case"plugins":return s.jsx(Zc,{});case"terminal":return null;case"instances":return s.jsx(Xc,{});case"remote-control":return s.jsx(Kh,{onNavigate:B});case"settings":return s.jsx(Jc,{});default:return null}};return s.jsxs("div",{className:"flex h-screen h-[100dvh] bg-bg-primary text-text-primary transition-colors duration-200 font-sans overflow-hidden",children:[s.jsx(tg,{isOpen:h,onClose:()=>x(!1),mainView:u,onNavigate:B}),s.jsxs("div",{className:"flex-1 flex flex-col min-w-0 relative transition-all duration-300 h-full",children:[s.jsx(rg,{onMenuClick:()=>x(F=>!F),onNewChat:N,onSplitTerminal:C,onHistory:()=>y(!0),hasHistory:v}),s.jsxs("div",{className:"flex-1 flex flex-col w-full overflow-hidden relative",children:[s.jsx("div",{className:"flex-1 flex flex-col w-full",style:{display:u==="terminal"?"flex":"none"},children:s.jsx(rd,{})}),u!=="terminal"&&A()]}),s.jsx(eh,{isOpen:w,onClose:()=>y(!1),onSwitchSession:R})]})]})}kd.createRoot(document.getElementById("root")).render(s.jsx(O.StrictMode,{children:s.jsx(ug,{})}));
|