@tencent-ai/agent-sdk 0.3.163 → 0.3.164
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/cli/CHANGELOG.md +34 -0
- package/cli/dist/codebuddy-headless.js +145 -143
- package/cli/dist/web-ui/assets/{index-Co5qIufv.js → index-BjwPksUe.js} +4 -4
- package/cli/dist/web-ui/docs/cn/cli/http-api.md +19 -13
- package/cli/dist/web-ui/docs/en/cli/http-api.md +19 -13
- package/cli/dist/web-ui/index.html +1 -1
- package/cli/dist/web-ui/sw.js +1 -1
- package/cli/package.json +1 -1
- package/cli/product.cloudhosted.json +2 -2
- package/cli/product.internal.json +2 -2
- package/cli/product.ioa.json +2 -2
- package/cli/product.json +4 -4
- package/cli/product.selfhosted.json +2 -2
- package/package.json +1 -1
- package/cli/vendor/sandbox/SandboxExt.xcframework/Info.plist +0 -30
- package/cli/vendor/sandbox/SandboxExt.xcframework/macos-arm64_x86_64/SandboxExt.framework/Versions/A/Headers/SandboxExt-Swift.h +0 -900
- package/cli/vendor/sandbox/SandboxExt.xcframework/macos-arm64_x86_64/SandboxExt.framework/Versions/A/Headers/SandboxExt.h +0 -34
- package/cli/vendor/sandbox/SandboxExt.xcframework/macos-arm64_x86_64/SandboxExt.framework/Versions/A/Headers/fileprovider_bridge.h +0 -125
- package/cli/vendor/sandbox/SandboxExt.xcframework/macos-arm64_x86_64/SandboxExt.framework/Versions/A/Headers/projfs_types.h +0 -34
- package/cli/vendor/sandbox/SandboxExt.xcframework/macos-arm64_x86_64/SandboxExt.framework/Versions/A/Headers/xlog_bridge.h +0 -106
- package/cli/vendor/sandbox/SandboxExt.xcframework/macos-arm64_x86_64/SandboxExt.framework/Versions/A/Modules/SandboxExt.swiftmodule/arm64-apple-macos.abi.json +0 -43957
- package/cli/vendor/sandbox/SandboxExt.xcframework/macos-arm64_x86_64/SandboxExt.framework/Versions/A/Modules/SandboxExt.swiftmodule/arm64-apple-macos.package.swiftinterface +0 -1085
- package/cli/vendor/sandbox/SandboxExt.xcframework/macos-arm64_x86_64/SandboxExt.framework/Versions/A/Modules/SandboxExt.swiftmodule/arm64-apple-macos.private.swiftinterface +0 -1084
- package/cli/vendor/sandbox/SandboxExt.xcframework/macos-arm64_x86_64/SandboxExt.framework/Versions/A/Modules/SandboxExt.swiftmodule/arm64-apple-macos.swiftdoc +0 -0
- package/cli/vendor/sandbox/SandboxExt.xcframework/macos-arm64_x86_64/SandboxExt.framework/Versions/A/Modules/SandboxExt.swiftmodule/arm64-apple-macos.swiftinterface +0 -1084
- package/cli/vendor/sandbox/SandboxExt.xcframework/macos-arm64_x86_64/SandboxExt.framework/Versions/A/Modules/SandboxExt.swiftmodule/x86_64-apple-macos.abi.json +0 -43957
- package/cli/vendor/sandbox/SandboxExt.xcframework/macos-arm64_x86_64/SandboxExt.framework/Versions/A/Modules/SandboxExt.swiftmodule/x86_64-apple-macos.package.swiftinterface +0 -1085
- package/cli/vendor/sandbox/SandboxExt.xcframework/macos-arm64_x86_64/SandboxExt.framework/Versions/A/Modules/SandboxExt.swiftmodule/x86_64-apple-macos.private.swiftinterface +0 -1084
- package/cli/vendor/sandbox/SandboxExt.xcframework/macos-arm64_x86_64/SandboxExt.framework/Versions/A/Modules/SandboxExt.swiftmodule/x86_64-apple-macos.swiftdoc +0 -0
- package/cli/vendor/sandbox/SandboxExt.xcframework/macos-arm64_x86_64/SandboxExt.framework/Versions/A/Modules/SandboxExt.swiftmodule/x86_64-apple-macos.swiftinterface +0 -1084
- package/cli/vendor/sandbox/SandboxExt.xcframework/macos-arm64_x86_64/SandboxExt.framework/Versions/A/Modules/module.modulemap +0 -10
- package/cli/vendor/sandbox/SandboxExt.xcframework/macos-arm64_x86_64/SandboxExt.framework/Versions/A/Resources/Info.plist +0 -46
- package/cli/vendor/sandbox/SandboxExt.xcframework/macos-arm64_x86_64/SandboxExt.framework/Versions/A/SandboxExt +0 -0
- package/cli/vendor/sandbox/SandboxExt.xcframework/macos-arm64_x86_64/SandboxExt.framework/Versions/A/_CodeSignature/CodeResources +0 -240
- package/cli/vendor/sandbox/SandboxExt.xcframework/macos-arm64_x86_64/dSYMs/SandboxExt.framework.dSYM/Contents/Info.plist +0 -20
- package/cli/vendor/sandbox/SandboxExt.xcframework/macos-arm64_x86_64/dSYMs/SandboxExt.framework.dSYM/Contents/Resources/DWARF/SandboxExt +0 -0
- package/cli/vendor/sandbox/SandboxExt.xcframework/macos-arm64_x86_64/dSYMs/SandboxExt.framework.dSYM/Contents/Resources/Relocations/aarch64/SandboxExt.yml +0 -3413
- package/cli/vendor/sandbox/SandboxExt.xcframework/macos-arm64_x86_64/dSYMs/SandboxExt.framework.dSYM/Contents/Resources/Relocations/x86_64/SandboxExt.yml +0 -3390
- package/cli/vendor/sandbox/WorkBuddySandboxHelper +0 -0
- package/cli/vendor/sandbox/WorkbuddyFileProvider.appex/Contents/Info.plist +0 -59
- package/cli/vendor/sandbox/WorkbuddyFileProvider.appex/Contents/MacOS/WorkbuddyFileProvider +0 -0
- package/cli/vendor/sandbox/WorkbuddyFileProvider.appex/Contents/_CodeSignature/CodeResources +0 -123
- package/cli/vendor/sandbox/WorkbuddyFileProvider.appex/Contents/embedded.provisionprofile +0 -0
- package/cli/vendor/sandbox/WorkbuddyNetworkExtension.appex/Contents/Info.plist +0 -55
- package/cli/vendor/sandbox/WorkbuddyNetworkExtension.appex/Contents/MacOS/WorkbuddyNetworkExtension +0 -0
- package/cli/vendor/sandbox/WorkbuddyNetworkExtension.appex/Contents/_CodeSignature/CodeResources +0 -123
- package/cli/vendor/sandbox/WorkbuddyNetworkExtension.appex/Contents/embedded.provisionprofile +0 -0
- package/cli/vendor/sandbox/libsandbox_ffi.dylib +0 -0
- package/cli/vendor/sandbox/msvcp140.dll +0 -0
- package/cli/vendor/sandbox/sandbox-cli +0 -0
- package/cli/vendor/sandbox/sandbox-cli.exe +0 -0
- package/cli/vendor/sandbox/sandbox_ffi.dll +0 -0
- package/cli/vendor/sandbox/tsbx.dll +0 -0
- package/cli/vendor/sandbox/tsbx_rules.json +0 -10
- package/cli/vendor/sandbox/tsbx_sdk.dll +0 -0
- package/cli/vendor/sandbox/vcruntime140.dll +0 -0
- package/cli/vendor/sandbox/vcruntime140_1.dll +0 -0
|
@@ -5,7 +5,7 @@ var bm=Object.defineProperty;var ym=(e,t,r)=>t in e?bm(e,t,{enumerable:!0,config
|
|
|
5
5
|
`);let g="";for(const m of v)m.startsWith("data: ")&&(g+=m.substring(6));if(g)try{const m=JSON.parse(g);this.handleMessage(m)}catch{}}const y=this.pendingRequests.get(i);y&&(this.pendingRequests.delete(i),this.cancelling&&t==="session/prompt"?(this.cancelling=!1,y.resolve({stopReason:"cancelled"})):y.reject(new Error(`No response received for request: ${t}`)))},c.onerror=()=>{const y=this.pendingRequests.get(i);if(y){if(this.pendingRequests.delete(i),s<2&&t!=="initialize"){console.warn(`Network error during ACP request: ${t}, reconnecting and retrying (${s+1}/2)...`),this.reconnect().then(()=>this.request(t,r,s+1)).then(k=>y.resolve(k),k=>y.reject(k));return}y.reject(new Error(`Network error during ACP request: ${t}`))}},c.ontimeout=()=>{const y=this.pendingRequests.get(i);if(y){if(this.pendingRequests.delete(i),s<1&&t!=="initialize"){console.warn(`Request timeout: ${t}, reconnecting and retrying...`),this.reconnect().then(()=>this.request(t,r,s+1)).then(k=>y.resolve(k),k=>y.reject(k));return}y.reject(new Error(`Request timeout: ${t}`))}},c.timeout=t==="session/prompt"?0:600*1e3,c.send(JSON.stringify(l))})}async notify(t,r){const s={jsonrpc:"2.0",method:t,params:r};await fetch(`${this.baseUrl}/api/v1/acp`,{method:"POST",headers:this.buildAcpHeaders(),body:JSON.stringify(s)})}async readSseStream(t){var l;const r=(l=t.body)==null?void 0:l.getReader();if(!r)return;const s=new TextDecoder;let i="";try{for(;;){const{done:d,value:a}=await r.read();if(d)break;i+=s.decode(a,{stream:!0});const o=i.split(`
|
|
6
6
|
|
|
7
7
|
`);i=o.pop()||"";for(const c of o){const u=c.split(`
|
|
8
|
-
`);let p="";for(const b of u)b.startsWith("data: ")&&(p+=b.substring(6));if(p)try{const b=JSON.parse(p);this.handleMessage(b)}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 s=r.update,l=((s==null?void 0:s._meta)||{})["codebuddy.ai/interruptionRequest"];l&&this.emit("interruption_request",{sessionUpdate:"interruption_request",sessionId:r.sessionId,interruptionId:l.interruptionId||`ir-${l.toolCallId}`,reason:"Tool requires approval",options:l.options||[],toolName:l.toolName,toolTitle:l.toolTitle,toolInput:l.toolInput,toolCallId:l.toolCallId});const d=r.update.sessionUpdate;this.emit(d,r.update)}}else if("method"in t&&t.method!=="session/update"&&!("id"in t&&t.id!==void 0&&t.id!==null)&&t.method==="_codebuddy.ai/checkpoint"){const s=t.params;(s==null?void 0:s.event)==="created"?this.emit("checkpointCreated",s.checkpoint):(s==null?void 0:s.event)==="updated"?this.emit("checkpointUpdated",s.checkpoint):(s==null?void 0:s.event)==="reverted"&&this.emit("checkpointReverted",s.checkpoint)}}mapPermissionDecisionToOptionId(t){return t==="allowAll"?"allow_always":t==="allow"?"allow":t==="rejectAndExitPlan"?"reject_and_exit_plan":"reject"}async sendJsonRpcResult(t,r){var l;const s={jsonrpc:"2.0",id:t,result:r},i=await fetch(`${this.baseUrl}/api/v1/acp`,{method:"POST",headers:this.buildAcpHeaders(),body:JSON.stringify(s)});if(!i.ok){let d="";try{const a=await i.json();(l=a==null?void 0:a.error)!=null&&l.message&&(d=a.error.message)}catch{}throw new Error(d||`ACP response failed: ${i.status} ${i.statusText}`)}}buildAcpHeaders(){const t={"Content-Type":"application/json",Accept:"application/json, text/event-stream",[bt]:kt};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 c;const s=r==null?void 0:r.toolCall,i=`perm-${t}`,l=((c=s==null?void 0:s._meta)==null?void 0:c["codebuddy.ai/toolName"])||(s==null?void 0:s.toolName)||"tool",d=(s==null?void 0:s.title)||l,a=s==null?void 0:s.rawInput,o=s==null?void 0:s.toolCallId;this.permissionRequestIds.set(i,t),o&&this.permissionRequestToolCallIds.set(o,i),this.emit("interruption_request",{sessionUpdate:"interruption_request",interruptionId:i,reason:"Tool requires approval",options:((r==null?void 0:r.options)||[]).map(u=>u.optionId||u.name),toolName:l,toolTitle:d,toolInput:a,toolCallId:o})}handleExtMethodQuestion(t,r){const{sessionId:s,toolCallId:i,schema:l}=r||{},d=((l==null?void 0:l.questions)||[]).map(a=>({id:a.id,question:a.question,header:a.header||"",options:(a.options||[]).map(o=>({label:o.label||"",description:o.description||""})),multiSelect:!!a.multiSelect}));this.extMethodRequestIds.set(i,t),this.emit("question_request",{toolCallId:i,sessionId:s,questions:d})}async handleExtMethodDelegateTool(t,r){const{toolId:s,input:i}=r||{};try{if(s==="ui-control"){const{uiController:l}=await Or(async()=>{const{uiController:a}=await import("./index-DixJ0kqk.js");return{uiController:a}},[]),d=await l.execute({sessionId:r.sessionId,action:i.action,target:i.target,value:i.value});await this.sendJsonRpcResult(t,{status:"success",output:d})}else if(s==="ui-query"){const{uiController:l}=await Or(async()=>{const{uiController:a}=await import("./index-DixJ0kqk.js");return{uiController:a}},[]),d=await l.queryElements({selector:i==null?void 0:i.selector,role:i==null?void 0:i.role,includeHidden:i==null?void 0:i.includeHidden,limit:i==null?void 0:i.limit});await this.sendJsonRpcResult(t,{status:"success",output:d})}else await this.sendJsonRpcResult(t,{status:"error",error:{message:`Unknown delegate tool: ${s}`}})}catch(l){await this.sendJsonRpcResult(t,{status:"error",error:{message:l instanceof Error?l.message:String(l)}})}}emit(t,r){const s=this.listeners.get(t);if(s)for(const i of s)try{i(r)}catch(l){console.error(`Event handler error for ${t}:`,l)}}setStatus(t){this._status=t,this.emit("status_change",t)}}const Am=Object.freeze(Object.defineProperty({__proto__:null,AcpClient:Xs,CUSTOM_REQUEST_HEADER_NAME:bt,CUSTOM_REQUEST_HEADER_VALUE:kt,fetchWithRetry:ve},Symbol.toStringTag,{value:"Module"})),sp="codebuddy.auth.token";function In(){try{return sessionStorage.getItem(sp)}catch{return null}}function ip(e){try{sessionStorage.setItem(sp,e)}catch{}}function ae(e){const t={[bt]:kt,...e},r=In();return r&&(t.Authorization=`Bearer ${r}`),t}const ap=Ae(e=>({viewState:"loading",error:null,isSubmitting:!1,checkAuth:async()=>{try{e({viewState:"loading",error:null});const t=await ve("/api/v1/auth/status",{headers:ae()});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 s=await(await fetch("/api/v1/auth/login",{method:"POST",headers:ae({"Content-Type":"application/json"}),body:JSON.stringify({password:t})})).json();if(s.success){const i=s.token||t;return ip(i),e({viewState:"authenticated",isSubmitting:!1,error:null}),!0}return e({error:s.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 Er(e){const t=Object.entries(e).filter(([,r])=>r!==void 0);return t.length===0?"":"?"+t.map(([r,s])=>`${r}=${encodeURIComponent(s)}`).join("&")}const Xn={async get(e,t){var l;const r=Er({key:e,scope:t}),s=await fetch(`/api/v1/storage${r}`,{headers:ae()});return s.ok?(l=(await s.json()).data)==null?void 0:l.value:void 0},async getNamespace(e,t){const r=Er({namespace:e,scope:t}),s=await fetch(`/api/v1/storage${r}`,{headers:ae()});return s.ok?(await s.json()).data??{}:{}},async set(e,t,r){const s=Er({scope:r});await fetch(`/api/v1/storage${s}`,{method:"PUT",headers:ae({"Content-Type":"application/json"}),body:JSON.stringify({key:e,value:t})})},async setMany(e,t,r){const s=Er({scope:t});await fetch(`/api/v1/storage${s}`,{method:"PUT",headers:ae({"Content-Type":"application/json"}),body:JSON.stringify({entries:e}),keepalive:(r==null?void 0:r.keepalive)===!0})},async remove(e,t){const r=Er({key:e,scope:t});await fetch(`/api/v1/storage${r}`,{method:"DELETE",headers:ae()})}};function Yr(e){return e instanceof Set?[...e]:e instanceof Map?[...e.entries()]:e}function Pr(e,t){return(r,s,i)=>{const l=e(r,s,i);let d=null;const a=t.debounceMs??500,o=t.scope??"global",c=p=>{if(d===null)return;clearTimeout(d),d=null;const b=s(),y=t.fields.map(k=>({key:`${t.namespace}.${String(k)}`,value:Yr(b[k])}));if(t.localStorageKey)try{const k={};for(const v of t.fields)k[String(v)]=Yr(b[v]);localStorage.setItem(t.localStorageKey,JSON.stringify(k))}catch{}Xn.setMany(y,o,{keepalive:!0}).catch(k=>{console.error(`[persist:${t.namespace}] Save failed (${p}):`,k)})},u=()=>{d&&clearTimeout(d),d=setTimeout(()=>{d=null;const p=s(),b=t.fields.map(y=>({key:`${t.namespace}.${String(y)}`,value:Yr(p[y])}));if(t.localStorageKey)try{const y={};for(const k of t.fields)y[String(k)]=Yr(p[k]);localStorage.setItem(t.localStorageKey,JSON.stringify(y))}catch{}Xn.setMany(b,o).catch(y=>{console.error(`[persist:${t.namespace}] Save failed:`,y)})},a)};if(typeof window<"u"){const p=()=>c("beforeunload");window.addEventListener("beforeunload",p),window.addEventListener("pagehide",p),document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&c("hidden")})}return i.subscribe((p,b)=>{for(const y of t.fields)if(p[y]!==b[y]){u();return}}),Xn.getNamespace(t.namespace,o).then(p=>{if(!p||Object.keys(p).length===0)return;const b={};let y=!1;for(const k of t.fields){const v=String(k);v in p&&p[v]!==void 0&&(b[k]=p[v],y=!0)}y&&(t.onLoad?t.onLoad(b,r):r(b))}).catch(p=>{console.error(`[persist:${t.namespace}] Load failed:`,p)}),l}}const op="codebuddy-theme";function lp(){var e;return typeof window<"u"&&((e=window.matchMedia)!=null&&e.call(window,"(prefers-color-scheme: dark)").matches)?"dark":"light"}function Zn(e){return e==="system"?lp():e}function Xr(e){document.documentElement.setAttribute("data-theme",e)}function Im(){try{const e=localStorage.getItem(op);if(e){const t=JSON.parse(e),r=(t==null?void 0:t.mode)??e;if(["light","dark","system"].includes(r))return r}}catch{}return"system"}const Ke=Ae()(Pr((e,t)=>{const r=Im(),s=Zn(r);return Xr(s),typeof window<"u"&&window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change",()=>{if(t().mode==="system"){const l=lp();Xr(l),e({resolved:l})}}),{mode:r,resolved:s,setMode:i=>{const l=Zn(i);Xr(l),e({mode:i,resolved:l})},toggle:()=>{const i=t().mode,l=i==="light"?"dark":i==="dark"?"system":"light";t().setMode(l)}}},{namespace:"theme",fields:["mode"],scope:"global",debounceMs:300,localStorageKey:op,onLoad:(e,t)=>{if(e.mode){const r=Zn(e.mode);Xr(r),t({mode:e.mode,resolved:r})}}}));var Zr={},Nd;function Rm(){if(Nd)return Zr;Nd=1;var e=Sm();return Zr.createRoot=e.createRoot,Zr.hydrateRoot=e.hydrateRoot,Zr}var Lm=Rm();let Tt=0;function ws(e){const t=e[e.length-1];return t&&t.type==="message"&&t.role==="assistant"&&t.streaming?e.length-1:-1}function xt(e){const t=ws(e);if(t===-1)return e;const r=[...e],s=r[t],i={streaming:!1};return s.thinking&&s.thinkingStartTime&&!s.thinkingDuration&&(i.thinkingDuration=Math.round((Date.now()-s.thinkingStartTime)/1e3)),r[t]={...s,...i},r}const Me=Ae((e,t)=>({timeline:[],childToolCalls:new Map,isAgentRunning:!1,stopReason:null,errorMessage:null,errorCategory:null,agentPhaseLabel:null,progressLabel:null,historyLoading:!1,hasPendingInterruption:!1,compactCancelled:!1,goalRecap:null,addUserMessage:(r,s,i)=>{e(l=>({timeline:[...xt(l.timeline),{type:"message",id:`msg-${++Tt}`,role:"user",content:r,...s&&s.length>0?{images:s}:{},...i&&i.length>0?{files:i}:{},timestamp:Date.now()}],isAgentRunning:!0,stopReason:null,errorMessage:null}))},addQueuedUserMessage:(r,s,i)=>{e(l=>({timeline:[...l.timeline,{type:"message",id:`msg-${++Tt}`,role:"user",content:r,...s&&s.length>0?{images:s}:{},...i&&i.length>0?{files:i}:{},timestamp:Date.now()}]}))},addChunk:(r,s,i)=>{e(l=>{if(s){const o=l.timeline.findIndex(c=>c.type==="tool_call"&&c.id===s);if(o!==-1){const c=l.timeline[o],u=[...c.subagentTimeline||[]],p=u[u.length-1];p&&p.type==="message"&&p.streaming?u[u.length-1]={...p,content:p.content+r}:u.push({type:"message",id:`sub-msg-${++Tt}`,content:r,streaming:!0});const b=[...l.timeline];return b[o]={...c,subagentTimeline:u},{timeline:b}}}const d=[...l.timeline],a=ws(d);if(a!==-1){const o=d[a],c={content:o.content+r};i&&!o.isCompactInternal&&(c.isCompactInternal=!0),o.thinking&&o.thinkingStartTime&&!o.thinkingDuration&&!o.content&&(c.thinkingDuration=Math.round((Date.now()-o.thinkingStartTime)/1e3)),d[a]={...o,...c}}else d.push({type:"message",id:`msg-${++Tt}`,role:"assistant",content:r,timestamp:Date.now(),streaming:!0,...i?{isCompactInternal:i}:{}});return{timeline:d}})},addThinkingChunk:(r,s)=>{e(i=>{if(s){const a=i.timeline.findIndex(o=>o.type==="tool_call"&&o.id===s);if(a!==-1){const o=i.timeline[a],c=[...o.subagentTimeline||[]],u=c[c.length-1];u&&u.type==="message"&&u.streaming?c[c.length-1]={...u,content:u.content+r}:c.push({type:"message",id:`sub-msg-${++Tt}`,content:r,streaming:!0});const p=[...i.timeline];return p[a]={...o,subagentTimeline:c},{timeline:p}}}const l=[...i.timeline],d=ws(l);if(d!==-1){const a=l[d];l[d]={...a,thinking:(a.thinking||"")+r,thinkingStartTime:a.thinkingStartTime||Date.now()}}else l.push({type:"message",id:`msg-${++Tt}`,role:"assistant",content:"",thinking:r,thinkingStartTime:Date.now(),timestamp:Date.now(),streaming:!0});return{timeline:l}})},finalizeAssistantMessage:()=>{e(r=>({timeline:xt(r.timeline)}))},addToolCall:r=>{e(s=>{const i=xt(s.timeline);if(r.parentToolCallId){const l=new Map(s.childToolCalls);return l.set(r.id,{...r,type:"tool_call"}),{timeline:i.map(d=>{if(d.type==="tool_call"&&d.id===r.parentToolCallId){const a=(d.subagentTimeline||[]).map(o=>o.type==="message"&&o.streaming?{...o,streaming:!1}:o);return{...d,children:[...d.children||[],r.id],subagentTimeline:[...a,{type:"tool_call_ref",toolCallId:r.id}]}}return d}),childToolCalls:l}}return{timeline:[...i,{...r,type:"tool_call"}]}})},updateToolCall:(r,s)=>{e(i=>{const l=c=>!c||!Array.isArray(c)?!1:c.some(u=>u.type==="diff"),d=c=>{let u=s;if(l(c.content)&&s.content!==void 0&&!l(s.content)){const{content:p,...b}=s;u=b}return{...c,...u,type:"tool_call"}};if(i.timeline.some(c=>c.type==="tool_call"&&c.id===r))return{timeline:i.timeline.map(c=>c.type==="tool_call"&&c.id===r?d(c):c)};const o=i.childToolCalls.get(r);if(o){const c=new Map(i.childToolCalls);return c.set(r,d(o)),{childToolCalls:c}}return{}})},getChildToolCall:r=>t().childToolCalls.get(r),getToolCall:r=>{const s=t();return s.timeline.find(l=>l.type==="tool_call"&&l.id===r)??s.childToolCalls.get(r)},addQuestion:r=>{e(s=>s.timeline.some(l=>l.type==="question"&&l.toolCallId===r.toolCallId&&l.status==="pending")?s:{timeline:[...xt(s.timeline),{...r,type:"question",status:"pending"}],hasPendingInterruption:!0})},submitQuestion:(r,s)=>{e(i=>{const l=i.timeline.map(a=>a.type==="question"&&a.id===r?{...a,status:"answered",answers:s}:a),d=l.some(a=>a.type==="interruption"&&!a.resolved||a.type==="question"&&a.status==="pending");return{timeline:l,hasPendingInterruption:d}})},cancelQuestion:r=>{e(s=>{const i=s.timeline.map(d=>d.type==="question"&&d.id===r?{...d,status:"cancelled"}:d),l=i.some(d=>d.type==="interruption"&&!d.resolved||d.type==="question"&&d.status==="pending");return{timeline:i,hasPendingInterruption:l}})},resolveQuestionByToolCallId:r=>{e(s=>{const i=s.timeline.map(d=>d.type==="question"&&d.toolCallId===r&&d.status==="pending"&&d.source==="interruption"?{...d,status:"cancelled"}:d),l=i.some(d=>d.type==="interruption"&&!d.resolved||d.type==="question"&&d.status==="pending");return{timeline:i,hasPendingInterruption:l}})},addInterruption:r=>{e(s=>r.toolCallId&&s.timeline.some(l=>l.type==="interruption"&&l.toolCallId===r.toolCallId&&!l.resolved)?s:{timeline:[...xt(s.timeline),{...r,type:"interruption"}],hasPendingInterruption:!0})},resolveInterruption:(r,s)=>{e(i=>{const l=i.timeline.map(a=>a.type==="interruption"&&a.id===r?{...a,resolved:!0,decision:s}:a),d=l.some(a=>a.type==="interruption"&&!a.resolved||a.type==="question"&&a.status==="pending");return{timeline:l,hasPendingInterruption:d}})},resolveInterruptionByToolCallId:(r,s)=>{e(i=>{const l=i.timeline.map(a=>a.type==="interruption"&&a.toolCallId===r&&!a.resolved?{...a,resolved:!0,decision:s}:a),d=l.some(a=>a.type==="interruption"&&!a.resolved||a.type==="question"&&a.status==="pending");return{timeline:l,hasPendingInterruption:d}})},setHistoryLoading:r=>e({historyLoading:r}),addHistoryUserMessage:(r,s,i,l)=>{e(d=>({timeline:[...xt(d.timeline),{type:"message",id:`msg-${++Tt}`,role:"user",content:r,...s&&s.length>0?{images:s}:{},timestamp:Date.now(),...i?{isCompactInternal:i}:{},...l?{channel:l}:{}}]}))},addHistoryUserMessageChunk:(r,s,i,l,d)=>{!s&&!(i&&i.length>0)||e(a=>{const o=xt(a.timeline),c=o[o.length-1];if(c&&c.type==="message"&&c.role==="user"&&r&&c.messageId===r){const u=[...c.images||[],...i||[]];return o[o.length-1]={...c,content:c.content+s,...u.length>0?{images:u}:{},...l?{isCompactInternal:!0}:{},...d?{channel:d}:{}},{timeline:o}}return{timeline:[...o,{type:"message",id:`msg-${++Tt}`,...r?{messageId:r}:{},role:"user",content:s,...i&&i.length>0?{images:i}:{},timestamp:Date.now(),...l?{isCompactInternal:l}:{},...d?{channel:d}:{}}]}})},setAgentRunning:r=>e({isAgentRunning:r,...r?{}:{agentPhaseLabel:null,progressLabel:null}}),setAgentPhaseLabel:r=>e({agentPhaseLabel:r}),setProgressLabel:r=>e({progressLabel:r}),setSessionEnd:(r,s,i)=>{t().finalizeAssistantMessage();const l=r==="end_turn";e(d=>{const a=d.timeline.map(c=>c.type==="tool_call"&&c.status==="running"?{...c,status:"completed"}:c.type==="interruption"&&!c.resolved?{...c,resolved:!0,decision:"deny"}:c.type==="question"&&c.status==="pending"?{...c,status:"cancelled"}:c),o=new Map(d.childToolCalls);for(const[c,u]of o)u.status==="running"&&o.set(c,{...u,status:"completed"});return{isAgentRunning:!1,hasPendingInterruption:!1,agentPhaseLabel:null,progressLabel:null,stopReason:l?null:r,errorMessage:l?null:s||null,errorCategory:l?null:i||null,timeline:a,childToolCalls:o}})},setCompactCancelled:r=>e({compactCancelled:r}),addGoalProgress:r=>{e(s=>{if(s.timeline.some(d=>d.type==="goal-progress"&&d.id===r.id))return s;const i=xt(s.timeline),l={type:"goal-progress",id:r.id,condition:r.condition,reason:r.reason,turnCount:r.turnCount,timestamp:r.timestamp??Date.now()};return{timeline:[...i,l]}})},showGoalRecap:r=>e({goalRecap:r}),dismissGoalRecap:()=>e({goalRecap:null}),addGoalStatus:r=>{e(s=>{if(s.timeline.some(d=>d.type==="goal-status"&&d.id===r.id))return s;const i=xt(s.timeline),l={type:"goal-status",id:r.id,kind:r.kind,condition:r.condition,prev:r.prev,actual:r.actual,max:r.max,timestamp:r.timestamp??Date.now()};return{timeline:[...i,l]}})},clearMessages:()=>e({timeline:[],childToolCalls:new Map,stopReason:null,errorMessage:null,agentPhaseLabel:null,progressLabel:null,historyLoading:!1,hasPendingInterruption:!1,compactCancelled:!1,goalRecap:null}),clearChat:()=>{t().clearMessages()}})),Dm=Object.freeze(Object.defineProperty({__proto__:null,useChatStore:Me},Symbol.toStringTag,{value:"Module"})),rt=Ae((e,t)=>({status:"disconnected",sessionId:null,models:[],currentModel:"",modes:[],currentMode:"default",commands:[],error:null,topic:null,thinkingEnabled:!1,promptSuggestion:null,externalInput:null,setStatus:r=>e({status:r}),setSessionId:r=>e({sessionId:r}),setModels:r=>e({models:r}),setCurrentModel:r=>e({currentModel:r}),setModes:r=>e({modes:r}),setCurrentMode:r=>e({currentMode:r}),setCommands:r=>e({commands:r}),setTopic:r=>e({topic:r}),setThinkingEnabled:r=>e({thinkingEnabled:r}),setPromptSuggestion:r=>e({promptSuggestion:r}),setExternalInput:r=>e({externalInput:r}),connect:async r=>{const s=Re();try{if(e({status:"connecting",error:null}),r){const{AcpClient:i}=await Or(async()=>{const{AcpClient:a}=await Promise.resolve().then(()=>Am);return{AcpClient:a}},void 0),l=new i(void 0,r);l.on("status_change",a=>e({status:a})),l.on("model_update",a=>{e({models:a.availableModels||[],currentModel:a.currentModelId||""})});const{sessionId:d}=await l.initializeSession({continue:!0});e({status:"connected",sessionId:d})}else{const{sessionId:i}=await s.initializeSession({continue:!0});e({status:"connected",sessionId:i})}}catch(i){e({status:"error",error:i.message})}},disconnect:async()=>{await Re().disconnect(),e({status:"disconnected",sessionId:null})}})),Ir=Ae((e,t)=>({fileChanges:[],selectedFile:null,selectedDiff:null,diffLoading:!1,isCollapsed:!0,checkpoints:[],showCheckpoints:!1,reverting:!1,onCheckpoint:r=>{const{fileChanges:s}=t(),i=new Map;for(const l of s)i.set(l.uri,l);for(const l of r.fileChanges.files)i.set(l.uri,l);e({fileChanges:Array.from(i.values())})},selectFile:async r=>{const{selectedFile:s}=t();if(s===r){e({selectedFile:null,selectedDiff:null});return}e({selectedFile:r,selectedDiff:null,diffLoading:!0});try{const i=await ve(`/api/v1/file-changes/diff?path=${encodeURIComponent(r)}`,{headers:ae()});i.ok?e({selectedDiff:await i.json(),diffLoading:!1}):e({diffLoading:!1})}catch{e({diffLoading:!1})}},setCollapsed:r=>e({isCollapsed:r}),setShowCheckpoints:r=>e({showCheckpoints:r}),loadCheckpoints:async()=>{try{const r=await ve("/api/v1/file-changes/checkpoints",{headers:ae()});if(r.ok){const i=((await r.json()).checkpoints||[]).sort((l,d)=>d.createdAt-l.createdAt);e({checkpoints:i})}}catch{}},revertFiles:async r=>{e({reverting:!0});try{const s=await ve("/api/v1/file-changes/revert",{method:"POST",headers:{...ae(),"Content-Type":"application/json"},body:JSON.stringify({paths:r})});if(s.ok){const i=await s.json(),l=new Set(i.revertedFiles||[]);e(d=>({fileChanges:d.fileChanges.filter(a=>!l.has(a.uri)),selectedFile:l.has(d.selectedFile||"")?null:d.selectedFile,selectedDiff:l.has(d.selectedFile||"")?null:d.selectedDiff}))}}finally{e({reverting:!1})}},revertAll:async()=>{e({reverting:!0});try{(await ve("/api/v1/file-changes/revert",{method:"POST",headers:{...ae(),"Content-Type":"application/json"},body:JSON.stringify({})})).ok&&e({fileChanges:[],selectedFile:null,selectedDiff:null})}finally{e({reverting:!1})}},revertToCheckpoint:async(r,s="CodeAndConversation")=>{e({reverting:!0});try{if((await ve("/api/v1/file-changes/revert",{method:"POST",headers:{...ae(),"Content-Type":"application/json"},body:JSON.stringify({checkpointId:r,scope:s})})).ok){if((s==="Code"||s==="CodeAndConversation")&&e({fileChanges:[],selectedFile:null,selectedDiff:null}),s==="Conversation"||s==="CodeAndConversation")try{const{useChatStore:l}=await Or(async()=>{const{useChatStore:o}=await Promise.resolve().then(()=>Dm);return{useChatStore:o}},void 0);l.getState().clearChat();const d=Re(),a=sessionStorage.getItem("acp-session-id");d&&a&&await d.loadSession(a)}catch(l){console.error("Failed to reload session after revert:",l)}t().loadCheckpoints()}}finally{e({reverting:!1})}},reset:()=>e({fileChanges:[],selectedFile:null,selectedDiff:null,diffLoading:!1,isCollapsed:!0,checkpoints:[],showCheckpoints:!1,reverting:!1})})),qe=Ae(e=>({isInTeam:!1,teamName:null,isAutoTeam:!1,members:[],focusedMemberName:null,memberHistories:{},setTeamStatus:t=>e({isInTeam:t.isInTeam,teamName:t.teamName||null,isAutoTeam:t.isAutoTeam||!1,members:t.members}),updateMembers:t=>e({members:t}),setFocusedMember:t=>e({focusedMemberName:t}),setMemberHistory:(t,r)=>e(s=>({memberHistories:{...s.memberHistories,[t]:r}})),clearTeam:()=>e({isInTeam:!1,teamName:null,isAutoTeam:!1,members:[],focusedMemberName:null,memberHistories:{}})})),cp=Ae(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 Ad(e,t){const r=e.options||e.answers;let s=[];return Array.isArray(r)&&(s=r.map(i=>typeof i=="object"&&i!==null&&"label"in i?{label:String(i.label||""),description:String(i.description||"")}:{label:String(i||""),description:""}).filter(i=>i.label.trim().length>0)),{id:e.id||`q_${t}`,question:e.question||"",header:e.header||"",options:s,multiSelect:!!e.multiSelect}}const Om={preparing:"phase.preparing",model_requesting:"phase.modelRequesting",model_streaming:"phase.modelStreaming",model_done:"phase.modelDone",tool_executing:"phase.toolExecuting",waiting_for_permission:"chat.waitingPermission",waiting_for_user:"chat.waitingUser",retrying:"phase.retrying",idle:null};function $m(e){return e.phase==="tool_executing"&&e.toolName?`phase.toolExecutingName:${e.toolName}`:e.phase==="model_streaming"&&e.streamingToolName?`phase.modelStreamingName:${e.streamingToolName}`:Om[e.phase]??null}let Bt=null;function Re(){return Bt||(Bt=new Xs),Bt}function jm(){const e=C.useRef(Re()),[t,r]=C.useState(0),{sessionId:s,setStatus:i,setSessionId:l,setModels:d,setCurrentModel:a,setModes:o,setCurrentMode:c,setCommands:u,setTopic:p,setThinkingEnabled:b,setPromptSuggestion:y}=rt(),{addChunk:k,addThinkingChunk:v,addToolCall:g,updateToolCall:m,addInterruption:h,addQuestion:f,setSessionEnd:x,resolveInterruptionByToolCallId:E,resolveQuestionByToolCallId:_,setHistoryLoading:S,addHistoryUserMessageChunk:w,finalizeAssistantMessage:N,clearChat:L,setAgentPhaseLabel:R,setProgressLabel:j,setAgentRunning:$,setCompactCancelled:G,addGoalProgress:F,showGoalRecap:W,addGoalStatus:V}=Me();C.useEffect(()=>{const T=e.current,D=[],I=(P,M)=>{if(!M)return!1;try{const z=(M._meta||{})["codebuddy.ai/memberEvent"];if(!z)return!1;const U=qe.getState(),O=U.memberHistories[z]||[];return U.setMemberHistory(z,[...O,{sessionUpdate:P,...M}]),!0}catch{return!1}};return D.push(T.on("user_message_chunk",P=>{if(I("user_message_chunk",P))return;const M=P.content,H=P._meta||{},z=!!H["codebuddy.ai/isCompactInternal"],U=typeof P.messageId=="string"?P.messageId:typeof H["codebuddy.ai/messageId"]=="string"?H["codebuddy.ai/messageId"]:void 0;let O;const Y=H["codebuddy.ai/images"];Array.isArray(Y)&&Y.length>0&&(O=Y.filter(J=>J.blobPath&&J.mimeType).map(J=>({url:`/api/v1/files/download?path=${encodeURIComponent(J.blobPath)}`,mimeType:J.mimeType})),O.length===0&&(O=void 0));let X;const Q=H["codebuddy.ai/channelSource"];Q&&(X={source:Q,sender:H["codebuddy.ai/channelSender"]||"",senderName:H["codebuddy.ai/channelSenderName"],chatId:H["codebuddy.ai/channelChatId"],chatType:H["codebuddy.ai/channelChatType"]}),M&&typeof M.text=="string"&&w(U,M.text,O,z,X)})),D.push(T.on("agent_message_chunk",P=>{if(I("agent_message_chunk",P))return;const M=P.content,H=P._meta||{},z=H["codebuddy.ai/parentToolCallId"],U=!!H["codebuddy.ai/isCompactInternal"];typeof M=="string"?k(M,z,U):M&&typeof M.text=="string"&&k(M.text,z,U)})),D.push(T.on("agent_thought_chunk",P=>{if(I("agent_thought_chunk",P))return;const M=P.content,z=(P._meta||{})["codebuddy.ai/parentToolCallId"];M&&typeof M.text=="string"&&v(M.text,z)})),D.push(T.on("tool_call",P=>{if(I("tool_call",P))return;const M=P._meta||{},H=M["codebuddy.ai/parentToolCallId"],z=!!M["codebuddy.ai/isSubagent"],U=P.toolName||M["codebuddy.ai/toolName"]||"",O=M["codebuddy.ai/planContent"],Y={id:P.toolCallId,name:P.title||U||P.kind||"tool",kind:P.kind||"other",toolName:U,input:P.rawInput||P.input,status:"running",locations:P.locations,content:P.content,parentToolCallId:H,subagent:z?{type:M["codebuddy.ai/subagentType"]||"general-purpose",description:M["codebuddy.ai/description"]||"",isBackground:!!M["codebuddy.ai/isBackground"],memberName:M["codebuddy.ai/memberName"]||void 0}:void 0,planContent:O};if(Me.getState().getToolCall(P.toolCallId)){const{id:Q,input:J,...re}=Y,de=J&&typeof J=="object"&&Object.keys(J).length>0?{...re,input:J}:re;m(P.toolCallId,de)}else g(Y)})),D.push(T.on("tool_call_update",P=>{if(I("tool_call_update",P))return;const H={status:P.status==="completed"?"completed":P.status==="failed"?"failed":P.toolStatus==="completed"?"completed":P.toolStatus==="failed"?"failed":"running",result:P.rawOutput||P.toolResult};if(P.content!==void 0){const U=(Array.isArray(P.content)?P.content:[]).filter(O=>{var Y;return!O||typeof O!="object"?!0:!(O.type==="content"&&((Y=O.content)==null?void 0:Y.type)==="text")});U.length>0&&(H.content=U)}P.rawInput&&typeof P.rawInput=="object"&&Object.keys(P.rawInput).length>0&&(H.input=P.rawInput),m(P.toolCallId,H)})),D.push(T.on("interruption_request",P=>{var M;if(P.toolName==="AskUserQuestion"){const H=Array.isArray((M=P.toolInput)==null?void 0:M.questions)?P.toolInput.questions:[];f({id:P.toolCallId,toolCallId:P.toolCallId,sessionId:P.sessionId||s||"",source:"interruption",questions:H.map(Ad)});return}h({id:P.interruptionId,sessionId:P.sessionId,reason:P.reason,options:P.options,toolName:P.toolName,toolTitle:P.toolTitle,toolInput:P.toolInput,toolCallId:P.toolCallId})})),D.push(T.on("question_request",P=>{const M=Array.isArray(P.questions)?P.questions:[];f({id:P.toolCallId,toolCallId:P.toolCallId,sessionId:P.sessionId,source:"extMethod",questions:M.map(Ad)})})),D.push(T.on("session_end",P=>{x(P.stopReason,P.errorMessage)})),D.push(T.on("session_info_update",P=>{P.title&&p(P.title);const M=P._meta||{};if(M["codebuddy.ai/historyReplay"]==="start"?S(!0):M["codebuddy.ai/historyReplay"]==="end"&&(S(!1),N()),M["codebuddy.ai/agentPhase"]){const z=M["codebuddy.ai/agentPhase"];R($m(z))}if("codebuddy.ai/progress"in M){const z=M["codebuddy.ai/progress"];z?(j(`progress.${z.type}`),$(!0),z.type==="compacting"&&G(!1)):j(null)}if("codebuddy.ai/compact-cancelled"in M){const z=M["codebuddy.ai/compact-cancelled"];z&&typeof z=="object"&&G(!0)}if("codebuddy.ai/goalProgress"in M){const z=M["codebuddy.ai/goalProgress"];z&&typeof z=="object"&&z.condition&&F({id:z.id??`goal-progress-${Date.now()}`,condition:z.condition,reason:z.reason,turnCount:z.turnCount??1})}if("codebuddy.ai/goalRecap"in M){const z=M["codebuddy.ai/goalRecap"];z&&typeof z=="object"&&W(z)}if("codebuddy.ai/goalStatus"in M){const z=M["codebuddy.ai/goalStatus"];z&&typeof z=="object"&&z.kind&&V({id:z.id??`goal-status-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,kind:z.kind,condition:z.condition,prev:z.prev,actual:z.actual,max:z.max})}if(M["codebuddy.ai/sessionReset"]){const z=M["codebuddy.ai/newSessionId"];if(z){if(L(),p(null),y(null),l(z),typeof sessionStorage<"u"&&sessionStorage.setItem("acp-session-id",z),typeof window<"u"&&window.history&&window.location){const U=new URL(window.location.href);U.searchParams.get("sessionId")!==z&&(U.searchParams.set("sessionId",z),window.history.replaceState({},"",U.toString()))}T.loadSession(z).then(q).catch(U=>console.error("Failed to load new session after reset:",U))}}if(M["codebuddy.ai/permissionResolved"]){const z=M["codebuddy.ai/toolCallId"],U=M["codebuddy.ai/decision"];z&&U&&(Re().clearPermissionRequestByToolCallId(z),E(z,U),_(z))}if("codebuddy.ai/promptSuggestion"in M){const z=M["codebuddy.ai/promptSuggestion"];y(z||null)}const H=M["codebuddy.ai/teamUpdate"];if(H)switch(H.type){case"member_status_change":H.members&&(H.teamName?qe.getState().setTeamStatus({isInTeam:!0,teamName:H.teamName,isAutoTeam:H.isAutoTeam,members:H.members}):qe.getState().updateMembers(H.members));break;case"team_created":qe.getState().setTeamStatus({isInTeam:!0,teamName:H.teamName,members:[]});break;case"team_deleted":qe.getState().clearTeam();break}})),D.push(T.on("model_update",P=>{d(P.availableModels||[]),a(P.currentModelId||"")})),D.push(T.on("mode_update",P=>{P.availableModes&&o(P.availableModes),P.currentModeId&&c(P.currentModeId)})),D.push(T.on("current_mode_update",P=>{P.currentModeId&&c(P.currentModeId)})),D.push(T.on("config_option_update",P=>{const M=P.configOptions||[];for(const H of M)H.id==="thought_level"?b(H.currentValue==="enabled"):H.id==="mode"&&H.currentValue?c(H.currentValue):H.id==="model"&&H.currentValue&&(a(H.currentValue),H.options&&d(H.options.map(z=>({id:z.value,name:z.name||z.value}))))})),D.push(T.on("status_change",P=>{i(P)})),D.push(T.on("available_commands_update",P=>{P.availableCommands&&u(P.availableCommands.map(M=>{var H;return{name:M.name,description:M.description||"",...((H=M._meta)==null?void 0:H.type)==="skill"?{type:"skill"}:{}}}))})),D.push(T.on("checkpointCreated",P=>{Ir.getState().onCheckpoint(P)})),D.push(T.on("checkpointUpdated",P=>{Ir.getState().onCheckpoint(P)})),D.push(T.on("checkpointReverted",()=>{Ir.getState().reset()})),()=>{D.forEach(P=>P())}},[t,s,k,v,g,m,h,f,x,E,_,d,a,o,c,u,p,b,i,S,w,N,L,l,y,F,W,V]);const q=C.useCallback(T=>{if(T.models&&(d(T.models.availableModels.map(D=>({id:D.modelId,name:D.name}))),a(T.models.currentModelId)),T.modes&&(o(T.modes.availableModes),c(T.modes.currentModeId)),T.configOptions)for(const D of T.configOptions)D.id==="thought_level"&&b(D.currentValue==="enabled")},[d,a,o,c,b]),A=C.useCallback(async T=>{const D=typeof T=="string"?T:T==null?void 0:T.token,I=typeof T=="object"?T==null?void 0:T.continue:!1;if(D){if(Bt)try{await Bt.disconnect()}catch{}Bt=new Xs(void 0,D),e.current=Bt,r(P=>P+1)}try{i("connecting"),y(null);const P=await e.current.initializeSession({continue:I});l(P.sessionId),q(P),i("connected"),cp.getState().fetchUserInfo(e.current)}catch(P){console.error("Connection failed:",P),i("error")}},[i,l,q,y]);return{client:e.current,connect:A}}/**
|
|
8
|
+
`);let p="";for(const b of u)b.startsWith("data: ")&&(p+=b.substring(6));if(p)try{const b=JSON.parse(p);this.handleMessage(b)}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 s=r.update,l=((s==null?void 0:s._meta)||{})["codebuddy.ai/interruptionRequest"];l&&this.emit("interruption_request",{sessionUpdate:"interruption_request",sessionId:r.sessionId,interruptionId:l.interruptionId||`ir-${l.toolCallId}`,reason:"Tool requires approval",options:l.options||[],toolName:l.toolName,toolTitle:l.toolTitle,toolInput:l.toolInput,toolCallId:l.toolCallId});const d=r.update.sessionUpdate;this.emit(d,r.update)}}else if("method"in t&&t.method!=="session/update"&&!("id"in t&&t.id!==void 0&&t.id!==null)&&t.method==="_codebuddy.ai/checkpoint"){const s=t.params;(s==null?void 0:s.event)==="created"?this.emit("checkpointCreated",s.checkpoint):(s==null?void 0:s.event)==="updated"?this.emit("checkpointUpdated",s.checkpoint):(s==null?void 0:s.event)==="reverted"&&this.emit("checkpointReverted",s.checkpoint)}}mapPermissionDecisionToOptionId(t){return t==="allowAll"?"allow_always":t==="allow"?"allow":t==="rejectAndExitPlan"?"reject_and_exit_plan":"reject"}async sendJsonRpcResult(t,r){var l;const s={jsonrpc:"2.0",id:t,result:r},i=await fetch(`${this.baseUrl}/api/v1/acp`,{method:"POST",headers:this.buildAcpHeaders(),body:JSON.stringify(s)});if(!i.ok){let d="";try{const a=await i.json();(l=a==null?void 0:a.error)!=null&&l.message&&(d=a.error.message)}catch{}throw new Error(d||`ACP response failed: ${i.status} ${i.statusText}`)}}buildAcpHeaders(){const t={"Content-Type":"application/json",Accept:"application/json, text/event-stream",[bt]:kt};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 c;const s=r==null?void 0:r.toolCall,i=`perm-${t}`,l=((c=s==null?void 0:s._meta)==null?void 0:c["codebuddy.ai/toolName"])||(s==null?void 0:s.toolName)||"tool",d=(s==null?void 0:s.title)||l,a=s==null?void 0:s.rawInput,o=s==null?void 0:s.toolCallId;this.permissionRequestIds.set(i,t),o&&this.permissionRequestToolCallIds.set(o,i),this.emit("interruption_request",{sessionUpdate:"interruption_request",interruptionId:i,reason:"Tool requires approval",options:((r==null?void 0:r.options)||[]).map(u=>u.optionId||u.name),toolName:l,toolTitle:d,toolInput:a,toolCallId:o})}handleExtMethodQuestion(t,r){const{sessionId:s,toolCallId:i,schema:l}=r||{},d=((l==null?void 0:l.questions)||[]).map(a=>({id:a.id,question:a.question,header:a.header||"",options:(a.options||[]).map(o=>({label:o.label||"",description:o.description||""})),multiSelect:!!a.multiSelect}));this.extMethodRequestIds.set(i,t),this.emit("question_request",{toolCallId:i,sessionId:s,questions:d})}async handleExtMethodDelegateTool(t,r){const{toolId:s,input:i}=r||{};try{if(s==="ui-control"){const{uiController:l}=await Or(async()=>{const{uiController:a}=await import("./index-DixJ0kqk.js");return{uiController:a}},[]),d=await l.execute({sessionId:r.sessionId,action:i.action,target:i.target,value:i.value});await this.sendJsonRpcResult(t,{status:"success",output:d})}else if(s==="ui-query"){const{uiController:l}=await Or(async()=>{const{uiController:a}=await import("./index-DixJ0kqk.js");return{uiController:a}},[]),d=await l.queryElements({selector:i==null?void 0:i.selector,role:i==null?void 0:i.role,includeHidden:i==null?void 0:i.includeHidden,limit:i==null?void 0:i.limit});await this.sendJsonRpcResult(t,{status:"success",output:d})}else await this.sendJsonRpcResult(t,{status:"error",error:{message:`Unknown delegate tool: ${s}`}})}catch(l){await this.sendJsonRpcResult(t,{status:"error",error:{message:l instanceof Error?l.message:String(l)}})}}emit(t,r){const s=this.listeners.get(t);if(s)for(const i of s)try{i(r)}catch(l){console.error(`Event handler error for ${t}:`,l)}}setStatus(t){this._status=t,this.emit("status_change",t)}}const Am=Object.freeze(Object.defineProperty({__proto__:null,AcpClient:Xs,CUSTOM_REQUEST_HEADER_NAME:bt,CUSTOM_REQUEST_HEADER_VALUE:kt,fetchWithRetry:ve},Symbol.toStringTag,{value:"Module"})),sp="codebuddy.auth.token";function In(){try{return sessionStorage.getItem(sp)}catch{return null}}function ip(e){try{sessionStorage.setItem(sp,e)}catch{}}function ae(e){const t={[bt]:kt,...e},r=In();return r&&(t.Authorization=`Bearer ${r}`),t}const ap=Ae(e=>({viewState:"loading",error:null,isSubmitting:!1,checkAuth:async()=>{try{e({viewState:"loading",error:null});const t=await ve("/api/v1/auth/status",{headers:ae()});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 s=await(await fetch("/api/v1/auth/login",{method:"POST",headers:ae({"Content-Type":"application/json"}),body:JSON.stringify({password:t})})).json();if(s.success){const i=s.token||t;return ip(i),e({viewState:"authenticated",isSubmitting:!1,error:null}),!0}return e({error:s.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 Er(e){const t=Object.entries(e).filter(([,r])=>r!==void 0);return t.length===0?"":"?"+t.map(([r,s])=>`${r}=${encodeURIComponent(s)}`).join("&")}const Xn={async get(e,t){var l;const r=Er({key:e,scope:t}),s=await fetch(`/api/v1/storage${r}`,{headers:ae()});return s.ok?(l=(await s.json()).data)==null?void 0:l.value:void 0},async getNamespace(e,t){const r=Er({namespace:e,scope:t}),s=await fetch(`/api/v1/storage${r}`,{headers:ae()});return s.ok?(await s.json()).data??{}:{}},async set(e,t,r){const s=Er({scope:r});await fetch(`/api/v1/storage${s}`,{method:"PUT",headers:ae({"Content-Type":"application/json"}),body:JSON.stringify({key:e,value:t})})},async setMany(e,t,r){const s=Er({scope:t});await fetch(`/api/v1/storage${s}`,{method:"PUT",headers:ae({"Content-Type":"application/json"}),body:JSON.stringify({entries:e}),keepalive:(r==null?void 0:r.keepalive)===!0})},async remove(e,t){const r=Er({key:e,scope:t});await fetch(`/api/v1/storage${r}`,{method:"DELETE",headers:ae()})}};function Yr(e){return e instanceof Set?[...e]:e instanceof Map?[...e.entries()]:e}function Pr(e,t){return(r,s,i)=>{const l=e(r,s,i);let d=null;const a=t.debounceMs??500,o=t.scope??"global",c=p=>{if(d===null)return;clearTimeout(d),d=null;const b=s(),y=t.fields.map(k=>({key:`${t.namespace}.${String(k)}`,value:Yr(b[k])}));if(t.localStorageKey)try{const k={};for(const v of t.fields)k[String(v)]=Yr(b[v]);localStorage.setItem(t.localStorageKey,JSON.stringify(k))}catch{}Xn.setMany(y,o,{keepalive:!0}).catch(k=>{console.error(`[persist:${t.namespace}] Save failed (${p}):`,k)})},u=()=>{d&&clearTimeout(d),d=setTimeout(()=>{d=null;const p=s(),b=t.fields.map(y=>({key:`${t.namespace}.${String(y)}`,value:Yr(p[y])}));if(t.localStorageKey)try{const y={};for(const k of t.fields)y[String(k)]=Yr(p[k]);localStorage.setItem(t.localStorageKey,JSON.stringify(y))}catch{}Xn.setMany(b,o).catch(y=>{console.error(`[persist:${t.namespace}] Save failed:`,y)})},a)};if(typeof window<"u"){const p=()=>c("beforeunload");window.addEventListener("beforeunload",p),window.addEventListener("pagehide",p),document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&c("hidden")})}return i.subscribe((p,b)=>{for(const y of t.fields)if(p[y]!==b[y]){u();return}}),Xn.getNamespace(t.namespace,o).then(p=>{if(!p||Object.keys(p).length===0)return;const b={};let y=!1;for(const k of t.fields){const v=String(k);v in p&&p[v]!==void 0&&(b[k]=p[v],y=!0)}y&&(t.onLoad?t.onLoad(b,r):r(b))}).catch(p=>{console.error(`[persist:${t.namespace}] Load failed:`,p)}),l}}const op="codebuddy-theme";function lp(){var e;return typeof window<"u"&&((e=window.matchMedia)!=null&&e.call(window,"(prefers-color-scheme: dark)").matches)?"dark":"light"}function Zn(e){return e==="system"?lp():e}function Xr(e){document.documentElement.setAttribute("data-theme",e)}function Im(){try{const e=localStorage.getItem(op);if(e){const t=JSON.parse(e),r=(t==null?void 0:t.mode)??e;if(["light","dark","system"].includes(r))return r}}catch{}return"system"}const Ke=Ae()(Pr((e,t)=>{const r=Im(),s=Zn(r);return Xr(s),typeof window<"u"&&window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change",()=>{if(t().mode==="system"){const l=lp();Xr(l),e({resolved:l})}}),{mode:r,resolved:s,setMode:i=>{const l=Zn(i);Xr(l),e({mode:i,resolved:l})},toggle:()=>{const i=t().mode,l=i==="light"?"dark":i==="dark"?"system":"light";t().setMode(l)}}},{namespace:"theme",fields:["mode"],scope:"global",debounceMs:300,localStorageKey:op,onLoad:(e,t)=>{if(e.mode){const r=Zn(e.mode);Xr(r),t({mode:e.mode,resolved:r})}}}));var Zr={},Nd;function Rm(){if(Nd)return Zr;Nd=1;var e=Sm();return Zr.createRoot=e.createRoot,Zr.hydrateRoot=e.hydrateRoot,Zr}var Lm=Rm();let Tt=0;function ws(e){const t=e[e.length-1];return t&&t.type==="message"&&t.role==="assistant"&&t.streaming?e.length-1:-1}function xt(e){const t=ws(e);if(t===-1)return e;const r=[...e],s=r[t],i={streaming:!1};return s.thinking&&s.thinkingStartTime&&!s.thinkingDuration&&(i.thinkingDuration=Math.round((Date.now()-s.thinkingStartTime)/1e3)),r[t]={...s,...i},r}const Me=Ae((e,t)=>({timeline:[],childToolCalls:new Map,isAgentRunning:!1,stopReason:null,errorMessage:null,errorCategory:null,agentPhaseLabel:null,progressLabel:null,historyLoading:!1,hasPendingInterruption:!1,compactCancelled:!1,goalRecap:null,addUserMessage:(r,s,i)=>{e(l=>({timeline:[...xt(l.timeline),{type:"message",id:`msg-${++Tt}`,role:"user",content:r,...s&&s.length>0?{images:s}:{},...i&&i.length>0?{files:i}:{},timestamp:Date.now()}],isAgentRunning:!0,stopReason:null,errorMessage:null}))},addQueuedUserMessage:(r,s,i)=>{e(l=>({timeline:[...l.timeline,{type:"message",id:`msg-${++Tt}`,role:"user",content:r,...s&&s.length>0?{images:s}:{},...i&&i.length>0?{files:i}:{},timestamp:Date.now()}]}))},addChunk:(r,s,i)=>{e(l=>{if(s){const o=l.timeline.findIndex(c=>c.type==="tool_call"&&c.id===s);if(o!==-1){const c=l.timeline[o],u=[...c.subagentTimeline||[]],p=u[u.length-1];p&&p.type==="message"&&p.streaming?u[u.length-1]={...p,content:p.content+r}:u.push({type:"message",id:`sub-msg-${++Tt}`,content:r,streaming:!0});const b=[...l.timeline];return b[o]={...c,subagentTimeline:u},{timeline:b}}}const d=[...l.timeline],a=ws(d);if(a!==-1){const o=d[a],c={content:o.content+r};i&&!o.isCompactInternal&&(c.isCompactInternal=!0),o.thinking&&o.thinkingStartTime&&!o.thinkingDuration&&!o.content&&(c.thinkingDuration=Math.round((Date.now()-o.thinkingStartTime)/1e3)),d[a]={...o,...c}}else d.push({type:"message",id:`msg-${++Tt}`,role:"assistant",content:r,timestamp:Date.now(),streaming:!0,...i?{isCompactInternal:i}:{}});return{timeline:d}})},addThinkingChunk:(r,s)=>{e(i=>{if(s){const a=i.timeline.findIndex(o=>o.type==="tool_call"&&o.id===s);if(a!==-1){const o=i.timeline[a],c=[...o.subagentTimeline||[]],u=c[c.length-1];u&&u.type==="message"&&u.streaming?c[c.length-1]={...u,content:u.content+r}:c.push({type:"message",id:`sub-msg-${++Tt}`,content:r,streaming:!0});const p=[...i.timeline];return p[a]={...o,subagentTimeline:c},{timeline:p}}}const l=[...i.timeline],d=ws(l);if(d!==-1){const a=l[d];l[d]={...a,thinking:(a.thinking||"")+r,thinkingStartTime:a.thinkingStartTime||Date.now()}}else l.push({type:"message",id:`msg-${++Tt}`,role:"assistant",content:"",thinking:r,thinkingStartTime:Date.now(),timestamp:Date.now(),streaming:!0});return{timeline:l}})},finalizeAssistantMessage:()=>{e(r=>({timeline:xt(r.timeline)}))},addToolCall:r=>{e(s=>{const i=xt(s.timeline);if(r.parentToolCallId){const l=new Map(s.childToolCalls);return l.set(r.id,{...r,type:"tool_call"}),{timeline:i.map(d=>{if(d.type==="tool_call"&&d.id===r.parentToolCallId){const a=(d.subagentTimeline||[]).map(o=>o.type==="message"&&o.streaming?{...o,streaming:!1}:o);return{...d,children:[...d.children||[],r.id],subagentTimeline:[...a,{type:"tool_call_ref",toolCallId:r.id}]}}return d}),childToolCalls:l}}return{timeline:[...i,{...r,type:"tool_call"}]}})},updateToolCall:(r,s)=>{e(i=>{const l=c=>!c||!Array.isArray(c)?!1:c.some(u=>u.type==="diff"),d=c=>{let u=s;if(l(c.content)&&s.content!==void 0&&!l(s.content)){const{content:p,...b}=s;u=b}return{...c,...u,type:"tool_call"}};if(i.timeline.some(c=>c.type==="tool_call"&&c.id===r))return{timeline:i.timeline.map(c=>c.type==="tool_call"&&c.id===r?d(c):c)};const o=i.childToolCalls.get(r);if(o){const c=new Map(i.childToolCalls);return c.set(r,d(o)),{childToolCalls:c}}return{}})},getChildToolCall:r=>t().childToolCalls.get(r),getToolCall:r=>{const s=t();return s.timeline.find(l=>l.type==="tool_call"&&l.id===r)??s.childToolCalls.get(r)},addQuestion:r=>{e(s=>s.timeline.some(l=>l.type==="question"&&l.toolCallId===r.toolCallId&&l.status==="pending")?s:{timeline:[...xt(s.timeline),{...r,type:"question",status:"pending"}],hasPendingInterruption:!0})},submitQuestion:(r,s)=>{e(i=>{const l=i.timeline.map(a=>a.type==="question"&&a.id===r?{...a,status:"answered",answers:s}:a),d=l.some(a=>a.type==="interruption"&&!a.resolved||a.type==="question"&&a.status==="pending");return{timeline:l,hasPendingInterruption:d}})},cancelQuestion:r=>{e(s=>{const i=s.timeline.map(d=>d.type==="question"&&d.id===r?{...d,status:"cancelled"}:d),l=i.some(d=>d.type==="interruption"&&!d.resolved||d.type==="question"&&d.status==="pending");return{timeline:i,hasPendingInterruption:l}})},resolveQuestionByToolCallId:r=>{e(s=>{const i=s.timeline.map(d=>d.type==="question"&&d.toolCallId===r&&d.status==="pending"&&d.source==="interruption"?{...d,status:"cancelled"}:d),l=i.some(d=>d.type==="interruption"&&!d.resolved||d.type==="question"&&d.status==="pending");return{timeline:i,hasPendingInterruption:l}})},addInterruption:r=>{e(s=>r.toolCallId&&s.timeline.some(l=>l.type==="interruption"&&l.toolCallId===r.toolCallId&&!l.resolved)?s:{timeline:[...xt(s.timeline),{...r,type:"interruption"}],hasPendingInterruption:!0})},resolveInterruption:(r,s)=>{e(i=>{const l=i.timeline.map(a=>a.type==="interruption"&&a.id===r?{...a,resolved:!0,decision:s}:a),d=l.some(a=>a.type==="interruption"&&!a.resolved||a.type==="question"&&a.status==="pending");return{timeline:l,hasPendingInterruption:d}})},resolveInterruptionByToolCallId:(r,s)=>{e(i=>{const l=i.timeline.map(a=>a.type==="interruption"&&a.toolCallId===r&&!a.resolved?{...a,resolved:!0,decision:s}:a),d=l.some(a=>a.type==="interruption"&&!a.resolved||a.type==="question"&&a.status==="pending");return{timeline:l,hasPendingInterruption:d}})},setHistoryLoading:r=>e({historyLoading:r}),addHistoryUserMessage:(r,s,i,l)=>{e(d=>({timeline:[...xt(d.timeline),{type:"message",id:`msg-${++Tt}`,role:"user",content:r,...s&&s.length>0?{images:s}:{},timestamp:Date.now(),...i?{isCompactInternal:i}:{},...l?{channel:l}:{}}]}))},addHistoryUserMessageChunk:(r,s,i,l,d)=>{!s&&!(i&&i.length>0)||e(a=>{const o=xt(a.timeline),c=o[o.length-1];if(c&&c.type==="message"&&c.role==="user"&&r&&c.messageId===r){const u=[...c.images||[],...i||[]];return o[o.length-1]={...c,content:c.content+s,...u.length>0?{images:u}:{},...l?{isCompactInternal:!0}:{},...d?{channel:d}:{}},{timeline:o}}return{timeline:[...o,{type:"message",id:`msg-${++Tt}`,...r?{messageId:r}:{},role:"user",content:s,...i&&i.length>0?{images:i}:{},timestamp:Date.now(),...l?{isCompactInternal:l}:{},...d?{channel:d}:{}}]}})},setAgentRunning:r=>e({isAgentRunning:r,...r?{}:{agentPhaseLabel:null,progressLabel:null}}),setAgentPhaseLabel:r=>e({agentPhaseLabel:r}),setProgressLabel:r=>e({progressLabel:r}),setSessionEnd:(r,s,i)=>{t().finalizeAssistantMessage();const l=r==="end_turn";e(d=>{const a=d.timeline.map(c=>c.type==="tool_call"&&c.status==="running"?{...c,status:"completed"}:c.type==="interruption"&&!c.resolved?{...c,resolved:!0,decision:"deny"}:c.type==="question"&&c.status==="pending"?{...c,status:"cancelled"}:c),o=new Map(d.childToolCalls);for(const[c,u]of o)u.status==="running"&&o.set(c,{...u,status:"completed"});return{isAgentRunning:!1,hasPendingInterruption:!1,agentPhaseLabel:null,progressLabel:null,stopReason:l?null:r,errorMessage:l?null:s||null,errorCategory:l?null:i||null,timeline:a,childToolCalls:o}})},setCompactCancelled:r=>e({compactCancelled:r}),addGoalProgress:r=>{e(s=>{if(s.timeline.some(d=>d.type==="goal-progress"&&d.id===r.id))return s;const i=xt(s.timeline),l={type:"goal-progress",id:r.id,condition:r.condition,reason:r.reason,turnCount:r.turnCount,timestamp:r.timestamp??Date.now()};return{timeline:[...i,l]}})},showGoalRecap:r=>e({goalRecap:r}),dismissGoalRecap:()=>e({goalRecap:null}),addGoalStatus:r=>{e(s=>{if(s.timeline.some(d=>d.type==="goal-status"&&d.id===r.id))return s;const i=xt(s.timeline),l={type:"goal-status",id:r.id,kind:r.kind,condition:r.condition,prev:r.prev,actual:r.actual,max:r.max,timestamp:r.timestamp??Date.now()};return{timeline:[...i,l]}})},clearMessages:()=>e({timeline:[],childToolCalls:new Map,stopReason:null,errorMessage:null,agentPhaseLabel:null,progressLabel:null,historyLoading:!1,hasPendingInterruption:!1,compactCancelled:!1,goalRecap:null}),clearChat:()=>{t().clearMessages()}})),Dm=Object.freeze(Object.defineProperty({__proto__:null,useChatStore:Me},Symbol.toStringTag,{value:"Module"})),rt=Ae((e,t)=>({status:"disconnected",sessionId:null,models:[],currentModel:"",modes:[],currentMode:"default",commands:[],error:null,topic:null,thinkingEnabled:!1,promptSuggestion:null,externalInput:null,setStatus:r=>e({status:r}),setSessionId:r=>e({sessionId:r}),setModels:r=>e({models:r}),setCurrentModel:r=>e({currentModel:r}),setModes:r=>e({modes:r}),setCurrentMode:r=>e({currentMode:r}),setCommands:r=>e({commands:r}),setTopic:r=>e({topic:r}),setThinkingEnabled:r=>e({thinkingEnabled:r}),setPromptSuggestion:r=>e({promptSuggestion:r}),setExternalInput:r=>e({externalInput:r}),connect:async r=>{const s=Re();try{if(e({status:"connecting",error:null}),r){const{AcpClient:i}=await Or(async()=>{const{AcpClient:a}=await Promise.resolve().then(()=>Am);return{AcpClient:a}},void 0),l=new i(void 0,r);l.on("status_change",a=>e({status:a})),l.on("model_update",a=>{e({models:a.availableModels||[],currentModel:a.currentModelId||""})});const{sessionId:d}=await l.initializeSession({continue:!0});e({status:"connected",sessionId:d})}else{const{sessionId:i}=await s.initializeSession({continue:!0});e({status:"connected",sessionId:i})}}catch(i){e({status:"error",error:i.message})}},disconnect:async()=>{await Re().disconnect(),e({status:"disconnected",sessionId:null})}})),Ir=Ae((e,t)=>({fileChanges:[],selectedFile:null,selectedDiff:null,diffLoading:!1,isCollapsed:!0,checkpoints:[],showCheckpoints:!1,reverting:!1,onCheckpoint:r=>{const{fileChanges:s}=t(),i=new Map;for(const l of s)i.set(l.uri,l);for(const l of r.fileChanges.files)i.set(l.uri,l);e({fileChanges:Array.from(i.values())})},selectFile:async r=>{const{selectedFile:s}=t();if(s===r){e({selectedFile:null,selectedDiff:null});return}e({selectedFile:r,selectedDiff:null,diffLoading:!0});try{const i=await ve("/internal/file-changes/diff",{method:"POST",headers:{...ae(),"Content-Type":"application/json"},body:JSON.stringify({path:r})});if(i.ok){const l=await i.json();e({selectedDiff:l.data??l,diffLoading:!1})}else e({diffLoading:!1})}catch{e({diffLoading:!1})}},setCollapsed:r=>e({isCollapsed:r}),setShowCheckpoints:r=>e({showCheckpoints:r}),loadCheckpoints:async()=>{try{const r=await ve("/internal/file-changes/checkpoints",{method:"POST",headers:{...ae(),"Content-Type":"application/json"},body:JSON.stringify({})});if(r.ok){const s=await r.json(),l=((s.data??s).checkpoints||[]).sort((d,a)=>a.createdAt-d.createdAt);e({checkpoints:l})}}catch{}},revertFiles:async r=>{e({reverting:!0});try{const s=await ve("/internal/file-changes/revert",{method:"POST",headers:{...ae(),"Content-Type":"application/json"},body:JSON.stringify({paths:r})});if(s.ok){const i=await s.json(),l=i.data??i,d=new Set(l.revertedFiles||[]);e(a=>({fileChanges:a.fileChanges.filter(o=>!d.has(o.uri)),selectedFile:d.has(a.selectedFile||"")?null:a.selectedFile,selectedDiff:d.has(a.selectedFile||"")?null:a.selectedDiff}))}}finally{e({reverting:!1})}},revertAll:async()=>{e({reverting:!0});try{(await ve("/internal/file-changes/revert",{method:"POST",headers:{...ae(),"Content-Type":"application/json"},body:JSON.stringify({})})).ok&&e({fileChanges:[],selectedFile:null,selectedDiff:null})}finally{e({reverting:!1})}},revertToCheckpoint:async(r,s="CodeAndConversation")=>{e({reverting:!0});try{if((await ve("/internal/file-changes/revert",{method:"POST",headers:{...ae(),"Content-Type":"application/json"},body:JSON.stringify({checkpointId:r,scope:s})})).ok){if((s==="Code"||s==="CodeAndConversation")&&e({fileChanges:[],selectedFile:null,selectedDiff:null}),s==="Conversation"||s==="CodeAndConversation")try{const{useChatStore:l}=await Or(async()=>{const{useChatStore:o}=await Promise.resolve().then(()=>Dm);return{useChatStore:o}},void 0);l.getState().clearChat();const d=Re(),a=sessionStorage.getItem("acp-session-id");d&&a&&await d.loadSession(a)}catch(l){console.error("Failed to reload session after revert:",l)}t().loadCheckpoints()}}finally{e({reverting:!1})}},reset:()=>e({fileChanges:[],selectedFile:null,selectedDiff:null,diffLoading:!1,isCollapsed:!0,checkpoints:[],showCheckpoints:!1,reverting:!1})})),qe=Ae(e=>({isInTeam:!1,teamName:null,isAutoTeam:!1,members:[],focusedMemberName:null,memberHistories:{},setTeamStatus:t=>e({isInTeam:t.isInTeam,teamName:t.teamName||null,isAutoTeam:t.isAutoTeam||!1,members:t.members}),updateMembers:t=>e({members:t}),setFocusedMember:t=>e({focusedMemberName:t}),setMemberHistory:(t,r)=>e(s=>({memberHistories:{...s.memberHistories,[t]:r}})),clearTeam:()=>e({isInTeam:!1,teamName:null,isAutoTeam:!1,members:[],focusedMemberName:null,memberHistories:{}})})),cp=Ae(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 Ad(e,t){const r=e.options||e.answers;let s=[];return Array.isArray(r)&&(s=r.map(i=>typeof i=="object"&&i!==null&&"label"in i?{label:String(i.label||""),description:String(i.description||"")}:{label:String(i||""),description:""}).filter(i=>i.label.trim().length>0)),{id:e.id||`q_${t}`,question:e.question||"",header:e.header||"",options:s,multiSelect:!!e.multiSelect}}const Om={preparing:"phase.preparing",model_requesting:"phase.modelRequesting",model_streaming:"phase.modelStreaming",model_done:"phase.modelDone",tool_executing:"phase.toolExecuting",waiting_for_permission:"chat.waitingPermission",waiting_for_user:"chat.waitingUser",retrying:"phase.retrying",idle:null};function $m(e){return e.phase==="tool_executing"&&e.toolName?`phase.toolExecutingName:${e.toolName}`:e.phase==="model_streaming"&&e.streamingToolName?`phase.modelStreamingName:${e.streamingToolName}`:Om[e.phase]??null}let Bt=null;function Re(){return Bt||(Bt=new Xs),Bt}function jm(){const e=C.useRef(Re()),[t,r]=C.useState(0),{sessionId:s,setStatus:i,setSessionId:l,setModels:d,setCurrentModel:a,setModes:o,setCurrentMode:c,setCommands:u,setTopic:p,setThinkingEnabled:b,setPromptSuggestion:y}=rt(),{addChunk:k,addThinkingChunk:v,addToolCall:g,updateToolCall:m,addInterruption:h,addQuestion:f,setSessionEnd:x,resolveInterruptionByToolCallId:E,resolveQuestionByToolCallId:_,setHistoryLoading:S,addHistoryUserMessageChunk:w,finalizeAssistantMessage:N,clearChat:L,setAgentPhaseLabel:R,setProgressLabel:j,setAgentRunning:$,setCompactCancelled:G,addGoalProgress:F,showGoalRecap:W,addGoalStatus:V}=Me();C.useEffect(()=>{const T=e.current,D=[],I=(P,M)=>{if(!M)return!1;try{const z=(M._meta||{})["codebuddy.ai/memberEvent"];if(!z)return!1;const U=qe.getState(),O=U.memberHistories[z]||[];return U.setMemberHistory(z,[...O,{sessionUpdate:P,...M}]),!0}catch{return!1}};return D.push(T.on("user_message_chunk",P=>{if(I("user_message_chunk",P))return;const M=P.content,H=P._meta||{},z=!!H["codebuddy.ai/isCompactInternal"],U=typeof P.messageId=="string"?P.messageId:typeof H["codebuddy.ai/messageId"]=="string"?H["codebuddy.ai/messageId"]:void 0;let O;const Y=H["codebuddy.ai/images"];Array.isArray(Y)&&Y.length>0&&(O=Y.filter(J=>J.blobPath&&J.mimeType).map(J=>({url:`/api/v1/files/download?path=${encodeURIComponent(J.blobPath)}`,mimeType:J.mimeType})),O.length===0&&(O=void 0));let X;const Q=H["codebuddy.ai/channelSource"];Q&&(X={source:Q,sender:H["codebuddy.ai/channelSender"]||"",senderName:H["codebuddy.ai/channelSenderName"],chatId:H["codebuddy.ai/channelChatId"],chatType:H["codebuddy.ai/channelChatType"]}),M&&typeof M.text=="string"&&w(U,M.text,O,z,X)})),D.push(T.on("agent_message_chunk",P=>{if(I("agent_message_chunk",P))return;const M=P.content,H=P._meta||{},z=H["codebuddy.ai/parentToolCallId"],U=!!H["codebuddy.ai/isCompactInternal"];typeof M=="string"?k(M,z,U):M&&typeof M.text=="string"&&k(M.text,z,U)})),D.push(T.on("agent_thought_chunk",P=>{if(I("agent_thought_chunk",P))return;const M=P.content,z=(P._meta||{})["codebuddy.ai/parentToolCallId"];M&&typeof M.text=="string"&&v(M.text,z)})),D.push(T.on("tool_call",P=>{if(I("tool_call",P))return;const M=P._meta||{},H=M["codebuddy.ai/parentToolCallId"],z=!!M["codebuddy.ai/isSubagent"],U=P.toolName||M["codebuddy.ai/toolName"]||"",O=M["codebuddy.ai/planContent"],Y={id:P.toolCallId,name:P.title||U||P.kind||"tool",kind:P.kind||"other",toolName:U,input:P.rawInput||P.input,status:"running",locations:P.locations,content:P.content,parentToolCallId:H,subagent:z?{type:M["codebuddy.ai/subagentType"]||"general-purpose",description:M["codebuddy.ai/description"]||"",isBackground:!!M["codebuddy.ai/isBackground"],memberName:M["codebuddy.ai/memberName"]||void 0}:void 0,planContent:O};if(Me.getState().getToolCall(P.toolCallId)){const{id:Q,input:J,...re}=Y,de=J&&typeof J=="object"&&Object.keys(J).length>0?{...re,input:J}:re;m(P.toolCallId,de)}else g(Y)})),D.push(T.on("tool_call_update",P=>{if(I("tool_call_update",P))return;const H={status:P.status==="completed"?"completed":P.status==="failed"?"failed":P.toolStatus==="completed"?"completed":P.toolStatus==="failed"?"failed":"running",result:P.rawOutput||P.toolResult};if(P.content!==void 0){const U=(Array.isArray(P.content)?P.content:[]).filter(O=>{var Y;return!O||typeof O!="object"?!0:!(O.type==="content"&&((Y=O.content)==null?void 0:Y.type)==="text")});U.length>0&&(H.content=U)}P.rawInput&&typeof P.rawInput=="object"&&Object.keys(P.rawInput).length>0&&(H.input=P.rawInput),m(P.toolCallId,H)})),D.push(T.on("interruption_request",P=>{var M;if(P.toolName==="AskUserQuestion"){const H=Array.isArray((M=P.toolInput)==null?void 0:M.questions)?P.toolInput.questions:[];f({id:P.toolCallId,toolCallId:P.toolCallId,sessionId:P.sessionId||s||"",source:"interruption",questions:H.map(Ad)});return}h({id:P.interruptionId,sessionId:P.sessionId,reason:P.reason,options:P.options,toolName:P.toolName,toolTitle:P.toolTitle,toolInput:P.toolInput,toolCallId:P.toolCallId})})),D.push(T.on("question_request",P=>{const M=Array.isArray(P.questions)?P.questions:[];f({id:P.toolCallId,toolCallId:P.toolCallId,sessionId:P.sessionId,source:"extMethod",questions:M.map(Ad)})})),D.push(T.on("session_end",P=>{x(P.stopReason,P.errorMessage)})),D.push(T.on("session_info_update",P=>{P.title&&p(P.title);const M=P._meta||{};if(M["codebuddy.ai/historyReplay"]==="start"?S(!0):M["codebuddy.ai/historyReplay"]==="end"&&(S(!1),N()),M["codebuddy.ai/agentPhase"]){const z=M["codebuddy.ai/agentPhase"];R($m(z))}if("codebuddy.ai/progress"in M){const z=M["codebuddy.ai/progress"];z?(j(`progress.${z.type}`),$(!0),z.type==="compacting"&&G(!1)):j(null)}if("codebuddy.ai/compact-cancelled"in M){const z=M["codebuddy.ai/compact-cancelled"];z&&typeof z=="object"&&G(!0)}if("codebuddy.ai/goalProgress"in M){const z=M["codebuddy.ai/goalProgress"];z&&typeof z=="object"&&z.condition&&F({id:z.id??`goal-progress-${Date.now()}`,condition:z.condition,reason:z.reason,turnCount:z.turnCount??1})}if("codebuddy.ai/goalRecap"in M){const z=M["codebuddy.ai/goalRecap"];z&&typeof z=="object"&&W(z)}if("codebuddy.ai/goalStatus"in M){const z=M["codebuddy.ai/goalStatus"];z&&typeof z=="object"&&z.kind&&V({id:z.id??`goal-status-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,kind:z.kind,condition:z.condition,prev:z.prev,actual:z.actual,max:z.max})}if(M["codebuddy.ai/sessionReset"]){const z=M["codebuddy.ai/newSessionId"];if(z){if(L(),p(null),y(null),l(z),typeof sessionStorage<"u"&&sessionStorage.setItem("acp-session-id",z),typeof window<"u"&&window.history&&window.location){const U=new URL(window.location.href);U.searchParams.get("sessionId")!==z&&(U.searchParams.set("sessionId",z),window.history.replaceState({},"",U.toString()))}T.loadSession(z).then(q).catch(U=>console.error("Failed to load new session after reset:",U))}}if(M["codebuddy.ai/permissionResolved"]){const z=M["codebuddy.ai/toolCallId"],U=M["codebuddy.ai/decision"];z&&U&&(Re().clearPermissionRequestByToolCallId(z),E(z,U),_(z))}if("codebuddy.ai/promptSuggestion"in M){const z=M["codebuddy.ai/promptSuggestion"];y(z||null)}const H=M["codebuddy.ai/teamUpdate"];if(H)switch(H.type){case"member_status_change":H.members&&(H.teamName?qe.getState().setTeamStatus({isInTeam:!0,teamName:H.teamName,isAutoTeam:H.isAutoTeam,members:H.members}):qe.getState().updateMembers(H.members));break;case"team_created":qe.getState().setTeamStatus({isInTeam:!0,teamName:H.teamName,members:[]});break;case"team_deleted":qe.getState().clearTeam();break}})),D.push(T.on("model_update",P=>{d(P.availableModels||[]),a(P.currentModelId||"")})),D.push(T.on("mode_update",P=>{P.availableModes&&o(P.availableModes),P.currentModeId&&c(P.currentModeId)})),D.push(T.on("current_mode_update",P=>{P.currentModeId&&c(P.currentModeId)})),D.push(T.on("config_option_update",P=>{const M=P.configOptions||[];for(const H of M)H.id==="thought_level"?b(H.currentValue==="enabled"):H.id==="mode"&&H.currentValue?c(H.currentValue):H.id==="model"&&H.currentValue&&(a(H.currentValue),H.options&&d(H.options.map(z=>({id:z.value,name:z.name||z.value}))))})),D.push(T.on("status_change",P=>{i(P)})),D.push(T.on("available_commands_update",P=>{P.availableCommands&&u(P.availableCommands.map(M=>{var H;return{name:M.name,description:M.description||"",...((H=M._meta)==null?void 0:H.type)==="skill"?{type:"skill"}:{}}}))})),D.push(T.on("checkpointCreated",P=>{Ir.getState().onCheckpoint(P)})),D.push(T.on("checkpointUpdated",P=>{Ir.getState().onCheckpoint(P)})),D.push(T.on("checkpointReverted",()=>{Ir.getState().reset()})),()=>{D.forEach(P=>P())}},[t,s,k,v,g,m,h,f,x,E,_,d,a,o,c,u,p,b,i,S,w,N,L,l,y,F,W,V]);const q=C.useCallback(T=>{if(T.models&&(d(T.models.availableModels.map(D=>({id:D.modelId,name:D.name}))),a(T.models.currentModelId)),T.modes&&(o(T.modes.availableModes),c(T.modes.currentModeId)),T.configOptions)for(const D of T.configOptions)D.id==="thought_level"&&b(D.currentValue==="enabled")},[d,a,o,c,b]),A=C.useCallback(async T=>{const D=typeof T=="string"?T:T==null?void 0:T.token,I=typeof T=="object"?T==null?void 0:T.continue:!1;if(D){if(Bt)try{await Bt.disconnect()}catch{}Bt=new Xs(void 0,D),e.current=Bt,r(P=>P+1)}try{i("connecting"),y(null);const P=await e.current.initializeSession({continue:I});l(P.sessionId),q(P),i("connected"),cp.getState().fetchUserInfo(e.current)}catch(P){console.error("Connection failed:",P),i("error")}},[i,l,q,y]);return{client:e.current,connect:A}}/**
|
|
9
9
|
* @license lucide-react v1.7.0 - ISC
|
|
10
10
|
*
|
|
11
11
|
* This source code is licensed under the ISC license.
|
|
@@ -633,8 +633,8 @@ WARNING: This link could potentially be dangerous`)){const m=window.open();if(m)
|
|
|
633
633
|
`:`
|
|
634
634
|
`)}clearSelection(){this._model.clearSelection(),this._removeMouseDownListeners(),this.refresh(),this._onSelectionChange.fire()}refresh(w){this._refreshAnimationFrame||(this._refreshAnimationFrame=this._coreBrowserService.window.requestAnimationFrame((()=>this._refresh()))),m.isLinux&&w&&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(w){const N=this._getMouseBufferCoords(w),L=this._model.finalSelectionStart,R=this._model.finalSelectionEnd;return!!(L&&R&&N)&&this._areCoordsInSelection(N,L,R)}isCellInSelection(w,N){const L=this._model.finalSelectionStart,R=this._model.finalSelectionEnd;return!(!L||!R)&&this._areCoordsInSelection([w,N],L,R)}_areCoordsInSelection(w,N,L){return w[1]>N[1]&&w[1]<L[1]||N[1]===L[1]&&w[1]===N[1]&&w[0]>=N[0]&&w[0]<L[0]||N[1]<L[1]&&w[1]===L[1]&&w[0]<L[0]||N[1]<L[1]&&w[1]===N[1]&&w[0]>=N[0]}_selectWordAtCursor(w,N){var j,$;const L=($=(j=this._linkifier.currentLink)==null?void 0:j.link)==null?void 0:$.range;if(L)return this._model.selectionStart=[L.start.x-1,L.start.y-1],this._model.selectionStartLength=(0,h.getRangeLength)(L,this._bufferService.cols),this._model.selectionEnd=void 0,!0;const R=this._getMouseBufferCoords(w);return!!R&&(this._selectWordAt(R,N),this._model.selectionEnd=void 0,!0)}selectAll(){this._model.isSelectAllActive=!0,this.refresh(),this._onSelectionChange.fire()}selectLines(w,N){this._model.clearSelection(),w=Math.max(w,0),N=Math.min(N,this._bufferService.buffer.lines.length-1),this._model.selectionStart=[0,w],this._model.selectionEnd=[this._bufferService.cols,N],this.refresh(),this._onSelectionChange.fire()}_handleTrim(w){this._model.handleTrim(w)&&this.refresh()}_getMouseBufferCoords(w){const N=this._mouseService.getCoords(w,this._screenElement,this._bufferService.cols,this._bufferService.rows,!0);if(N)return N[0]--,N[1]--,N[1]+=this._bufferService.buffer.ydisp,N}_getMouseEventScrollAmount(w){let N=(0,p.getCoordsRelativeToElement)(this._coreBrowserService.window,w,this._screenElement)[1];const L=this._renderService.dimensions.css.canvas.height;return N>=0&&N<=L?0:(N>L&&(N-=L),N=Math.min(Math.max(N,-50),50),N/=50,N/Math.abs(N)+Math.round(14*N))}shouldForceSelection(w){return m.isMac?w.altKey&&this._optionsService.rawOptions.macOptionClickForcesSelection:w.shiftKey}handleMouseDown(w){if(this._mouseDownTimeStamp=w.timeStamp,(w.button!==2||!this.hasSelection)&&w.button===0){if(!this._enabled){if(!this.shouldForceSelection(w))return;w.stopPropagation()}w.preventDefault(),this._dragScrollAmount=0,this._enabled&&w.shiftKey?this._handleIncrementalClick(w):w.detail===1?this._handleSingleClick(w):w.detail===2?this._handleDoubleClick(w):w.detail===3&&this._handleTripleClick(w),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(w){this._model.selectionStart&&(this._model.selectionEnd=this._getMouseBufferCoords(w))}_handleSingleClick(w){if(this._model.selectionStartLength=0,this._model.isSelectAllActive=!1,this._activeSelectionMode=this.shouldColumnSelect(w)?3:0,this._model.selectionStart=this._getMouseBufferCoords(w),!this._model.selectionStart)return;this._model.selectionEnd=void 0;const N=this._bufferService.buffer.lines.get(this._model.selectionStart[1]);N&&N.length!==this._model.selectionStart[0]&&N.hasWidth(this._model.selectionStart[0])===0&&this._model.selectionStart[0]++}_handleDoubleClick(w){this._selectWordAtCursor(w,!0)&&(this._activeSelectionMode=1)}_handleTripleClick(w){const N=this._getMouseBufferCoords(w);N&&(this._activeSelectionMode=2,this._selectLineAt(N[1]))}shouldColumnSelect(w){return w.altKey&&!(m.isMac&&this._optionsService.rawOptions.macOptionClickForcesSelection)}_handleMouseMove(w){if(w.stopImmediatePropagation(),!this._model.selectionStart)return;const N=this._model.selectionEnd?[this._model.selectionEnd[0],this._model.selectionEnd[1]]:null;if(this._model.selectionEnd=this._getMouseBufferCoords(w),!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(w),this._activeSelectionMode!==3&&(this._dragScrollAmount>0?this._model.selectionEnd[0]=this._bufferService.cols:this._dragScrollAmount<0&&(this._model.selectionEnd[0]=0));const L=this._bufferService.buffer;if(this._model.selectionEnd[1]<L.lines.length){const R=L.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]++}N&&N[0]===this._model.selectionEnd[0]&&N[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 w=this._bufferService.buffer;this._dragScrollAmount>0?(this._activeSelectionMode!==3&&(this._model.selectionEnd[0]=this._bufferService.cols),this._model.selectionEnd[1]=Math.min(w.ydisp+this._bufferService.rows,w.lines.length-1)):(this._activeSelectionMode!==3&&(this._model.selectionEnd[0]=0),this._model.selectionEnd[1]=w.ydisp),this.refresh()}}_handleMouseUp(w){const N=w.timeStamp-this._mouseDownTimeStamp;if(this._removeMouseDownListeners(),this.selectionText.length<=1&&N<500&&w.altKey&&this._optionsService.rawOptions.altClickMovesCursor){if(this._bufferService.buffer.ybase===this._bufferService.buffer.ydisp){const L=this._mouseService.getCoords(w,this._element,this._bufferService.cols,this._bufferService.rows,!1);if(L&&L[0]!==void 0&&L[1]!==void 0){const R=(0,b.moveToCellSequence)(L[0]-1,L[1]-1,this._bufferService,this._coreService.decPrivateModes.applicationCursorKeys);this._coreService.triggerDataEvent(R,!0)}}}else this._fireEventIfSelectionChanged()}_fireEventIfSelectionChanged(){const w=this._model.finalSelectionStart,N=this._model.finalSelectionEnd,L=!(!w||!N||w[0]===N[0]&&w[1]===N[1]);L?w&&N&&(this._oldSelectionStart&&this._oldSelectionEnd&&w[0]===this._oldSelectionStart[0]&&w[1]===this._oldSelectionStart[1]&&N[0]===this._oldSelectionEnd[0]&&N[1]===this._oldSelectionEnd[1]||this._fireOnSelectionChange(w,N,L)):this._oldHasSelection&&this._fireOnSelectionChange(w,N,L)}_fireOnSelectionChange(w,N,L){this._oldSelectionStart=w,this._oldSelectionEnd=N,this._oldHasSelection=L,this._onSelectionChange.fire()}_handleBufferActivate(w){this.clearSelection(),this._trimListener.dispose(),this._trimListener=w.activeBuffer.lines.onTrim((N=>this._handleTrim(N)))}_convertViewportColToCharacterIndex(w,N){let L=N;for(let R=0;N>=R;R++){const j=w.loadCell(R,this._workCell).getChars().length;this._workCell.getWidth()===0?L--:j>1&&N!==R&&(L+=j-1)}return L}setSelection(w,N,L){this._model.clearSelection(),this._removeMouseDownListeners(),this._model.selectionStart=[w,N],this._model.selectionStartLength=L,this.refresh(),this._fireEventIfSelectionChanged()}rightClickSelect(w){this._isClickInSelection(w)||(this._selectWordAtCursor(w,!1)&&this.refresh(!0),this._fireEventIfSelectionChanged())}_getWordAt(w,N,L=!0,R=!0){if(w[0]>=this._bufferService.cols)return;const j=this._bufferService.buffer,$=j.lines.get(w[1]);if(!$)return;const G=j.translateBufferLineToString(w[1],!1);let F=this._convertViewportColToCharacterIndex($,w[0]),W=F;const V=w[0]-F;let q=0,A=0,T=0,D=0;if(G.charAt(F)===" "){for(;F>0&&G.charAt(F-1)===" ";)F--;for(;W<G.length&&G.charAt(W+1)===" ";)W++}else{let M=w[0],H=w[0];$.getWidth(M)===0&&(q++,M--),$.getWidth(H)===2&&(A++,H++);const z=$.getString(H).length;for(z>1&&(D+=z-1,W+=z-1);M>0&&F>0&&!this._isCharWordSeparator($.loadCell(M-1,this._workCell));){$.loadCell(M-1,this._workCell);const U=this._workCell.getChars().length;this._workCell.getWidth()===0?(q++,M--):U>1&&(T+=U-1,F-=U-1),F--,M--}for(;H<$.length&&W+1<G.length&&!this._isCharWordSeparator($.loadCell(H+1,this._workCell));){$.loadCell(H+1,this._workCell);const U=this._workCell.getChars().length;this._workCell.getWidth()===2?(A++,H++):U>1&&(D+=U-1,W+=U-1),W++,H++}}W++;let I=F+V-q+T,P=Math.min(this._bufferService.cols,W-F+q+A-T-D);if(N||G.slice(F,W).trim()!==""){if(L&&I===0&&$.getCodePoint(0)!==32){const M=j.lines.get(w[1]-1);if(M&&$.isWrapped&&M.getCodePoint(this._bufferService.cols-1)!==32){const H=this._getWordAt([this._bufferService.cols-1,w[1]-1],!1,!0,!1);if(H){const z=this._bufferService.cols-H.start;I-=z,P+=z}}}if(R&&I+P===this._bufferService.cols&&$.getCodePoint(this._bufferService.cols-1)!==32){const M=j.lines.get(w[1]+1);if(M!=null&&M.isWrapped&&M.getCodePoint(0)!==32){const H=this._getWordAt([0,w[1]+1],!1,!1,!0);H&&(P+=H.length)}}return{start:I,length:P}}}_selectWordAt(w,N){const L=this._getWordAt(w,N);if(L){for(;L.start<0;)L.start+=this._bufferService.cols,w[1]--;this._model.selectionStart=[L.start,w[1]],this._model.selectionStartLength=L.length}}_selectToWordAt(w){const N=this._getWordAt(w,!0);if(N){let L=w[1];for(;N.start<0;)N.start+=this._bufferService.cols,L--;if(!this._model.areSelectionValuesReversed())for(;N.start+N.length>this._bufferService.cols;)N.length-=this._bufferService.cols,L++;this._model.selectionEnd=[this._model.areSelectionValuesReversed()?N.start:N.start+N.length,L]}}_isCharWordSeparator(w){return w.getWidth()!==0&&this._optionsService.rawOptions.wordSeparator.indexOf(w.getChars())>=0}_selectLineAt(w){const N=this._bufferService.buffer.getWrappedRangeForLine(w),L={start:{x:0,y:N.first},end:{x:this._bufferService.cols-1,y:N.last}};this._model.selectionStart=[0,N.first],this._model.selectionEnd=void 0,this._model.selectionStartLength=(0,h.getRangeLength)(L,this._bufferService.cols)}};a.SelectionService=S=c([u(3,x.IBufferService),u(4,x.ICoreService),u(5,k.IMouseService),u(6,x.IOptionsService),u(7,k.IRenderService),u(8,k.ICoreBrowserService)],S)},4725:(d,a,o)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.ILinkProviderService=a.IThemeService=a.ICharacterJoinerService=a.ISelectionService=a.IRenderService=a.IMouseService=a.ICoreBrowserService=a.ICharSizeService=void 0;const c=o(8343);a.ICharSizeService=(0,c.createDecorator)("CharSizeService"),a.ICoreBrowserService=(0,c.createDecorator)("CoreBrowserService"),a.IMouseService=(0,c.createDecorator)("MouseService"),a.IRenderService=(0,c.createDecorator)("RenderService"),a.ISelectionService=(0,c.createDecorator)("SelectionService"),a.ICharacterJoinerService=(0,c.createDecorator)("CharacterJoinerService"),a.IThemeService=(0,c.createDecorator)("ThemeService"),a.ILinkProviderService=(0,c.createDecorator)("LinkProviderService")},6731:function(d,a,o){var c=this&&this.__decorate||function(S,w,N,L){var R,j=arguments.length,$=j<3?w:L===null?L=Object.getOwnPropertyDescriptor(w,N):L;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")$=Reflect.decorate(S,w,N,L);else for(var G=S.length-1;G>=0;G--)(R=S[G])&&($=(j<3?R($):j>3?R(w,N,$):R(w,N))||$);return j>3&&$&&Object.defineProperty(w,N,$),$},u=this&&this.__param||function(S,w){return function(N,L){w(N,L,S)}};Object.defineProperty(a,"__esModule",{value:!0}),a.ThemeService=a.DEFAULT_ANSI_COLORS=void 0;const p=o(7239),b=o(8055),y=o(8460),k=o(844),v=o(2585),g=b.css.toColor("#ffffff"),m=b.css.toColor("#000000"),h=b.css.toColor("#ffffff"),f=b.css.toColor("#000000"),x={css:"rgba(255, 255, 255, 0.3)",rgba:4294967117};a.DEFAULT_ANSI_COLORS=Object.freeze((()=>{const S=[b.css.toColor("#2e3436"),b.css.toColor("#cc0000"),b.css.toColor("#4e9a06"),b.css.toColor("#c4a000"),b.css.toColor("#3465a4"),b.css.toColor("#75507b"),b.css.toColor("#06989a"),b.css.toColor("#d3d7cf"),b.css.toColor("#555753"),b.css.toColor("#ef2929"),b.css.toColor("#8ae234"),b.css.toColor("#fce94f"),b.css.toColor("#729fcf"),b.css.toColor("#ad7fa8"),b.css.toColor("#34e2e2"),b.css.toColor("#eeeeec")],w=[0,95,135,175,215,255];for(let N=0;N<216;N++){const L=w[N/36%6|0],R=w[N/6%6|0],j=w[N%6];S.push({css:b.channels.toCss(L,R,j),rgba:b.channels.toRgba(L,R,j)})}for(let N=0;N<24;N++){const L=8+10*N;S.push({css:b.channels.toCss(L,L,L),rgba:b.channels.toRgba(L,L,L)})}return S})());let E=a.ThemeService=class extends k.Disposable{get colors(){return this._colors}constructor(S){super(),this._optionsService=S,this._contrastCache=new p.ColorContrastCache,this._halfContrastCache=new p.ColorContrastCache,this._onChangeColors=this.register(new y.EventEmitter),this.onChangeColors=this._onChangeColors.event,this._colors={foreground:g,background:m,cursor:h,cursorAccent:f,selectionForeground:void 0,selectionBackgroundTransparent:x,selectionBackgroundOpaque:b.color.blend(m,x),selectionInactiveBackgroundTransparent:x,selectionInactiveBackgroundOpaque:b.color.blend(m,x),ansi:a.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(S={}){const w=this._colors;if(w.foreground=_(S.foreground,g),w.background=_(S.background,m),w.cursor=_(S.cursor,h),w.cursorAccent=_(S.cursorAccent,f),w.selectionBackgroundTransparent=_(S.selectionBackground,x),w.selectionBackgroundOpaque=b.color.blend(w.background,w.selectionBackgroundTransparent),w.selectionInactiveBackgroundTransparent=_(S.selectionInactiveBackground,w.selectionBackgroundTransparent),w.selectionInactiveBackgroundOpaque=b.color.blend(w.background,w.selectionInactiveBackgroundTransparent),w.selectionForeground=S.selectionForeground?_(S.selectionForeground,b.NULL_COLOR):void 0,w.selectionForeground===b.NULL_COLOR&&(w.selectionForeground=void 0),b.color.isOpaque(w.selectionBackgroundTransparent)&&(w.selectionBackgroundTransparent=b.color.opacity(w.selectionBackgroundTransparent,.3)),b.color.isOpaque(w.selectionInactiveBackgroundTransparent)&&(w.selectionInactiveBackgroundTransparent=b.color.opacity(w.selectionInactiveBackgroundTransparent,.3)),w.ansi=a.DEFAULT_ANSI_COLORS.slice(),w.ansi[0]=_(S.black,a.DEFAULT_ANSI_COLORS[0]),w.ansi[1]=_(S.red,a.DEFAULT_ANSI_COLORS[1]),w.ansi[2]=_(S.green,a.DEFAULT_ANSI_COLORS[2]),w.ansi[3]=_(S.yellow,a.DEFAULT_ANSI_COLORS[3]),w.ansi[4]=_(S.blue,a.DEFAULT_ANSI_COLORS[4]),w.ansi[5]=_(S.magenta,a.DEFAULT_ANSI_COLORS[5]),w.ansi[6]=_(S.cyan,a.DEFAULT_ANSI_COLORS[6]),w.ansi[7]=_(S.white,a.DEFAULT_ANSI_COLORS[7]),w.ansi[8]=_(S.brightBlack,a.DEFAULT_ANSI_COLORS[8]),w.ansi[9]=_(S.brightRed,a.DEFAULT_ANSI_COLORS[9]),w.ansi[10]=_(S.brightGreen,a.DEFAULT_ANSI_COLORS[10]),w.ansi[11]=_(S.brightYellow,a.DEFAULT_ANSI_COLORS[11]),w.ansi[12]=_(S.brightBlue,a.DEFAULT_ANSI_COLORS[12]),w.ansi[13]=_(S.brightMagenta,a.DEFAULT_ANSI_COLORS[13]),w.ansi[14]=_(S.brightCyan,a.DEFAULT_ANSI_COLORS[14]),w.ansi[15]=_(S.brightWhite,a.DEFAULT_ANSI_COLORS[15]),S.extendedAnsi){const N=Math.min(w.ansi.length-16,S.extendedAnsi.length);for(let L=0;L<N;L++)w.ansi[L+16]=_(S.extendedAnsi[L],a.DEFAULT_ANSI_COLORS[L+16])}this._contrastCache.clear(),this._halfContrastCache.clear(),this._updateRestoreColors(),this._onChangeColors.fire(this.colors)}restoreColor(S){this._restoreColor(S),this._onChangeColors.fire(this.colors)}_restoreColor(S){if(S!==void 0)switch(S){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[S]=this._restoreColors.ansi[S]}else for(let w=0;w<this._restoreColors.ansi.length;++w)this._colors.ansi[w]=this._restoreColors.ansi[w]}modifyColors(S){S(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 _(S,w){if(S!==void 0)try{return b.css.toColor(S)}catch{}return w}a.ThemeService=E=c([u(0,v.IOptionsService)],E)},6349:(d,a,o)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.CircularList=void 0;const c=o(8460),u=o(844);class p extends u.Disposable{constructor(y){super(),this._maxLength=y,this.onDeleteEmitter=this.register(new c.EventEmitter),this.onDelete=this.onDeleteEmitter.event,this.onInsertEmitter=this.register(new c.EventEmitter),this.onInsert=this.onInsertEmitter.event,this.onTrimEmitter=this.register(new c.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(y){if(this._maxLength===y)return;const k=new Array(y);for(let v=0;v<Math.min(y,this.length);v++)k[v]=this._array[this._getCyclicIndex(v)];this._array=k,this._maxLength=y,this._startIndex=0}get length(){return this._length}set length(y){if(y>this._length)for(let k=this._length;k<y;k++)this._array[k]=void 0;this._length=y}get(y){return this._array[this._getCyclicIndex(y)]}set(y,k){this._array[this._getCyclicIndex(y)]=k}push(y){this._array[this._getCyclicIndex(this._length)]=y,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(y,k,...v){if(k){for(let g=y;g<this._length-k;g++)this._array[this._getCyclicIndex(g)]=this._array[this._getCyclicIndex(g+k)];this._length-=k,this.onDeleteEmitter.fire({index:y,amount:k})}for(let g=this._length-1;g>=y;g--)this._array[this._getCyclicIndex(g+v.length)]=this._array[this._getCyclicIndex(g)];for(let g=0;g<v.length;g++)this._array[this._getCyclicIndex(y+g)]=v[g];if(v.length&&this.onInsertEmitter.fire({index:y,amount:v.length}),this._length+v.length>this._maxLength){const g=this._length+v.length-this._maxLength;this._startIndex+=g,this._length=this._maxLength,this.onTrimEmitter.fire(g)}else this._length+=v.length}trimStart(y){y>this._length&&(y=this._length),this._startIndex+=y,this._length-=y,this.onTrimEmitter.fire(y)}shiftElements(y,k,v){if(!(k<=0)){if(y<0||y>=this._length)throw new Error("start argument out of range");if(y+v<0)throw new Error("Cannot shift elements in list beyond index 0");if(v>0){for(let m=k-1;m>=0;m--)this.set(y+m+v,this.get(y+m));const g=y+k+v-this._length;if(g>0)for(this._length+=g;this._length>this._maxLength;)this._length--,this._startIndex++,this.onTrimEmitter.fire(1)}else for(let g=0;g<k;g++)this.set(y+g+v,this.get(y+g))}}_getCyclicIndex(y){return(this._startIndex+y)%this._maxLength}}a.CircularList=p},1439:(d,a)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.clone=void 0,a.clone=function o(c,u=5){if(typeof c!="object")return c;const p=Array.isArray(c)?[]:{};for(const b in c)p[b]=u<=1?c[b]:c[b]&&o(c[b],u-1);return p}},8055:(d,a)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.contrastRatio=a.toPaddedHex=a.rgba=a.rgb=a.css=a.color=a.channels=a.NULL_COLOR=void 0;let o=0,c=0,u=0,p=0;var b,y,k,v,g;function m(f){const x=f.toString(16);return x.length<2?"0"+x:x}function h(f,x){return f<x?(x+.05)/(f+.05):(f+.05)/(x+.05)}a.NULL_COLOR={css:"#00000000",rgba:0},(function(f){f.toCss=function(x,E,_,S){return S!==void 0?`#${m(x)}${m(E)}${m(_)}${m(S)}`:`#${m(x)}${m(E)}${m(_)}`},f.toRgba=function(x,E,_,S=255){return(x<<24|E<<16|_<<8|S)>>>0},f.toColor=function(x,E,_,S){return{css:f.toCss(x,E,_,S),rgba:f.toRgba(x,E,_,S)}}})(b||(a.channels=b={})),(function(f){function x(E,_){return p=Math.round(255*_),[o,c,u]=g.toChannels(E.rgba),{css:b.toCss(o,c,u,p),rgba:b.toRgba(o,c,u,p)}}f.blend=function(E,_){if(p=(255&_.rgba)/255,p===1)return{css:_.css,rgba:_.rgba};const S=_.rgba>>24&255,w=_.rgba>>16&255,N=_.rgba>>8&255,L=E.rgba>>24&255,R=E.rgba>>16&255,j=E.rgba>>8&255;return o=L+Math.round((S-L)*p),c=R+Math.round((w-R)*p),u=j+Math.round((N-j)*p),{css:b.toCss(o,c,u),rgba:b.toRgba(o,c,u)}},f.isOpaque=function(E){return(255&E.rgba)==255},f.ensureContrastRatio=function(E,_,S){const w=g.ensureContrastRatio(E.rgba,_.rgba,S);if(w)return b.toColor(w>>24&255,w>>16&255,w>>8&255)},f.opaque=function(E){const _=(255|E.rgba)>>>0;return[o,c,u]=g.toChannels(_),{css:b.toCss(o,c,u),rgba:_}},f.opacity=x,f.multiplyOpacity=function(E,_){return p=255&E.rgba,x(E,p*_/255)},f.toColorRGB=function(E){return[E.rgba>>24&255,E.rgba>>16&255,E.rgba>>8&255]}})(y||(a.color=y={})),(function(f){let x,E;try{const _=document.createElement("canvas");_.width=1,_.height=1;const S=_.getContext("2d",{willReadFrequently:!0});S&&(x=S,x.globalCompositeOperation="copy",E=x.createLinearGradient(0,0,1,1))}catch{}f.toColor=function(_){if(_.match(/#[\da-f]{3,8}/i))switch(_.length){case 4:return o=parseInt(_.slice(1,2).repeat(2),16),c=parseInt(_.slice(2,3).repeat(2),16),u=parseInt(_.slice(3,4).repeat(2),16),b.toColor(o,c,u);case 5:return o=parseInt(_.slice(1,2).repeat(2),16),c=parseInt(_.slice(2,3).repeat(2),16),u=parseInt(_.slice(3,4).repeat(2),16),p=parseInt(_.slice(4,5).repeat(2),16),b.toColor(o,c,u,p);case 7:return{css:_,rgba:(parseInt(_.slice(1),16)<<8|255)>>>0};case 9:return{css:_,rgba:parseInt(_.slice(1),16)>>>0}}const S=_.match(/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(,\s*(0|1|\d?\.(\d+))\s*)?\)/);if(S)return o=parseInt(S[1]),c=parseInt(S[2]),u=parseInt(S[3]),p=Math.round(255*(S[5]===void 0?1:parseFloat(S[5]))),b.toColor(o,c,u,p);if(!x||!E)throw new Error("css.toColor: Unsupported css format");if(x.fillStyle=E,x.fillStyle=_,typeof x.fillStyle!="string")throw new Error("css.toColor: Unsupported css format");if(x.fillRect(0,0,1,1),[o,c,u,p]=x.getImageData(0,0,1,1).data,p!==255)throw new Error("css.toColor: Unsupported css format");return{rgba:b.toRgba(o,c,u,p),css:_}}})(k||(a.css=k={})),(function(f){function x(E,_,S){const w=E/255,N=_/255,L=S/255;return .2126*(w<=.03928?w/12.92:Math.pow((w+.055)/1.055,2.4))+.7152*(N<=.03928?N/12.92:Math.pow((N+.055)/1.055,2.4))+.0722*(L<=.03928?L/12.92:Math.pow((L+.055)/1.055,2.4))}f.relativeLuminance=function(E){return x(E>>16&255,E>>8&255,255&E)},f.relativeLuminance2=x})(v||(a.rgb=v={})),(function(f){function x(_,S,w){const N=_>>24&255,L=_>>16&255,R=_>>8&255;let j=S>>24&255,$=S>>16&255,G=S>>8&255,F=h(v.relativeLuminance2(j,$,G),v.relativeLuminance2(N,L,R));for(;F<w&&(j>0||$>0||G>0);)j-=Math.max(0,Math.ceil(.1*j)),$-=Math.max(0,Math.ceil(.1*$)),G-=Math.max(0,Math.ceil(.1*G)),F=h(v.relativeLuminance2(j,$,G),v.relativeLuminance2(N,L,R));return(j<<24|$<<16|G<<8|255)>>>0}function E(_,S,w){const N=_>>24&255,L=_>>16&255,R=_>>8&255;let j=S>>24&255,$=S>>16&255,G=S>>8&255,F=h(v.relativeLuminance2(j,$,G),v.relativeLuminance2(N,L,R));for(;F<w&&(j<255||$<255||G<255);)j=Math.min(255,j+Math.ceil(.1*(255-j))),$=Math.min(255,$+Math.ceil(.1*(255-$))),G=Math.min(255,G+Math.ceil(.1*(255-G))),F=h(v.relativeLuminance2(j,$,G),v.relativeLuminance2(N,L,R));return(j<<24|$<<16|G<<8|255)>>>0}f.blend=function(_,S){if(p=(255&S)/255,p===1)return S;const w=S>>24&255,N=S>>16&255,L=S>>8&255,R=_>>24&255,j=_>>16&255,$=_>>8&255;return o=R+Math.round((w-R)*p),c=j+Math.round((N-j)*p),u=$+Math.round((L-$)*p),b.toRgba(o,c,u)},f.ensureContrastRatio=function(_,S,w){const N=v.relativeLuminance(_>>8),L=v.relativeLuminance(S>>8);if(h(N,L)<w){if(L<N){const $=x(_,S,w),G=h(N,v.relativeLuminance($>>8));if(G<w){const F=E(_,S,w);return G>h(N,v.relativeLuminance(F>>8))?$:F}return $}const R=E(_,S,w),j=h(N,v.relativeLuminance(R>>8));if(j<w){const $=x(_,S,w);return j>h(N,v.relativeLuminance($>>8))?R:$}return R}},f.reduceLuminance=x,f.increaseLuminance=E,f.toChannels=function(_){return[_>>24&255,_>>16&255,_>>8&255,255&_]}})(g||(a.rgba=g={})),a.toPaddedHex=m,a.contrastRatio=h},8969:(d,a,o)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.CoreTerminal=void 0;const c=o(844),u=o(2585),p=o(4348),b=o(7866),y=o(744),k=o(7302),v=o(6975),g=o(8460),m=o(1753),h=o(1480),f=o(7994),x=o(9282),E=o(5435),_=o(5981),S=o(2660);let w=!1;class N extends c.Disposable{get onScroll(){return this._onScrollApi||(this._onScrollApi=this.register(new g.EventEmitter),this._onScroll.event((R=>{var j;(j=this._onScrollApi)==null||j.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 j in R)this.optionsService.options[j]=R[j]}constructor(R){super(),this._windowsWrappingHeuristics=this.register(new c.MutableDisposable),this._onBinary=this.register(new g.EventEmitter),this.onBinary=this._onBinary.event,this._onData=this.register(new g.EventEmitter),this.onData=this._onData.event,this._onLineFeed=this.register(new g.EventEmitter),this.onLineFeed=this._onLineFeed.event,this._onResize=this.register(new g.EventEmitter),this.onResize=this._onResize.event,this._onWriteParsed=this.register(new g.EventEmitter),this.onWriteParsed=this._onWriteParsed.event,this._onScroll=this.register(new g.EventEmitter),this._instantiationService=new p.InstantiationService,this.optionsService=this.register(new k.OptionsService(R)),this._instantiationService.setService(u.IOptionsService,this.optionsService),this._bufferService=this.register(this._instantiationService.createInstance(y.BufferService)),this._instantiationService.setService(u.IBufferService,this._bufferService),this._logService=this.register(this._instantiationService.createInstance(b.LogService)),this._instantiationService.setService(u.ILogService,this._logService),this.coreService=this.register(this._instantiationService.createInstance(v.CoreService)),this._instantiationService.setService(u.ICoreService,this.coreService),this.coreMouseService=this.register(this._instantiationService.createInstance(m.CoreMouseService)),this._instantiationService.setService(u.ICoreMouseService,this.coreMouseService),this.unicodeService=this.register(this._instantiationService.createInstance(h.UnicodeService)),this._instantiationService.setService(u.IUnicodeService,this.unicodeService),this._charsetService=this._instantiationService.createInstance(f.CharsetService),this._instantiationService.setService(u.ICharsetService,this._charsetService),this._oscLinkService=this._instantiationService.createInstance(S.OscLinkService),this._instantiationService.setService(u.IOscLinkService,this._oscLinkService),this._inputHandler=this.register(new E.InputHandler(this._bufferService,this._charsetService,this.coreService,this._logService,this.optionsService,this._oscLinkService,this.coreMouseService,this.unicodeService)),this.register((0,g.forwardEvent)(this._inputHandler.onLineFeed,this._onLineFeed)),this.register(this._inputHandler),this.register((0,g.forwardEvent)(this._bufferService.onResize,this._onResize)),this.register((0,g.forwardEvent)(this.coreService.onData,this._onData)),this.register((0,g.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((j=>{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((j=>{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 _.WriteBuffer(((j,$)=>this._inputHandler.parse(j,$)))),this.register((0,g.forwardEvent)(this._writeBuffer.onWriteParsed,this._onWriteParsed))}write(R,j){this._writeBuffer.write(R,j)}writeSync(R,j){this._logService.logLevel<=u.LogLevelEnum.WARN&&!w&&(this._logService.warn("writeSync is unreliable and will be removed soon."),w=!0),this._writeBuffer.writeSync(R,j)}input(R,j=!0){this.coreService.triggerDataEvent(R,j)}resize(R,j){isNaN(R)||isNaN(j)||(R=Math.max(R,y.MINIMUM_COLS),j=Math.max(j,y.MINIMUM_ROWS),this._bufferService.resize(R,j))}scroll(R,j=!1){this._bufferService.scroll(R,j)}scrollLines(R,j,$){this._bufferService.scrollLines(R,j,$)}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 j=R-this._bufferService.buffer.ydisp;j!==0&&this.scrollLines(j)}registerEscHandler(R,j){return this._inputHandler.registerEscHandler(R,j)}registerDcsHandler(R,j){return this._inputHandler.registerDcsHandler(R,j)}registerCsiHandler(R,j){return this._inputHandler.registerCsiHandler(R,j)}registerOscHandler(R,j){return this._inputHandler.registerOscHandler(R,j)}_setup(){this._handleWindowsPtyOptionChange()}reset(){this._inputHandler.reset(),this._bufferService.reset(),this._charsetService.reset(),this.coreService.reset(),this.coreMouseService.reset()}_handleWindowsPtyOptionChange(){let R=!1;const j=this.optionsService.rawOptions.windowsPty;j&&j.buildNumber!==void 0&&j.buildNumber!==void 0?R=j.backend==="conpty"&&j.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(x.updateWindowsModeWrappedState.bind(null,this._bufferService))),R.push(this.registerCsiHandler({final:"H"},(()=>((0,x.updateWindowsModeWrappedState)(this._bufferService),!1)))),this._windowsWrappingHeuristics.value=(0,c.toDisposable)((()=>{for(const j of R)j.dispose()}))}}}a.CoreTerminal=N},8460:(d,a)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.runAndSubscribe=a.forwardEvent=a.EventEmitter=void 0,a.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 c=0;c<this._listeners.length;c++)if(this._listeners[c]===o)return void this._listeners.splice(c,1)}}})),this._event}fire(o,c){const u=[];for(let p=0;p<this._listeners.length;p++)u.push(this._listeners[p]);for(let p=0;p<u.length;p++)u[p].call(void 0,o,c)}dispose(){this.clearListeners(),this._disposed=!0}clearListeners(){this._listeners&&(this._listeners.length=0)}},a.forwardEvent=function(o,c){return o((u=>c.fire(u)))},a.runAndSubscribe=function(o,c){return c(void 0),o((u=>c(u)))}},5435:function(d,a,o){var c=this&&this.__decorate||function(q,A,T,D){var I,P=arguments.length,M=P<3?A:D===null?D=Object.getOwnPropertyDescriptor(A,T):D;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")M=Reflect.decorate(q,A,T,D);else for(var H=q.length-1;H>=0;H--)(I=q[H])&&(M=(P<3?I(M):P>3?I(A,T,M):I(A,T))||M);return P>3&&M&&Object.defineProperty(A,T,M),M},u=this&&this.__param||function(q,A){return function(T,D){A(T,D,q)}};Object.defineProperty(a,"__esModule",{value:!0}),a.InputHandler=a.WindowsOptionsReportType=void 0;const p=o(2584),b=o(7116),y=o(2015),k=o(844),v=o(482),g=o(8437),m=o(8460),h=o(643),f=o(511),x=o(3734),E=o(2585),_=o(1480),S=o(6242),w=o(6351),N=o(5941),L={"(":0,")":1,"*":2,"+":3,"-":1,".":2},R=131072;function j(q,A){if(q>24)return A.setWinLines||!1;switch(q){case 1:return!!A.restoreWin;case 2:return!!A.minimizeWin;case 3:return!!A.setWinPosition;case 4:return!!A.setWinSizePixels;case 5:return!!A.raiseWin;case 6:return!!A.lowerWin;case 7:return!!A.refreshWin;case 8:return!!A.setWinSizeChars;case 9:return!!A.maximizeWin;case 10:return!!A.fullscreenWin;case 11:return!!A.getWinState;case 13:return!!A.getWinPosition;case 14:return!!A.getWinSizePixels;case 15:return!!A.getScreenSizePixels;case 16:return!!A.getCellSizePixels;case 18:return!!A.getWinSizeChars;case 19:return!!A.getScreenSizeChars;case 20:return!!A.getIconTitle;case 21:return!!A.getWinTitle;case 22:return!!A.pushTitle;case 23:return!!A.popTitle;case 24:return!!A.setWinLines}return!1}var $;(function(q){q[q.GET_WIN_SIZE_PIXELS=0]="GET_WIN_SIZE_PIXELS",q[q.GET_CELL_SIZE_PIXELS=1]="GET_CELL_SIZE_PIXELS"})($||(a.WindowsOptionsReportType=$={}));let G=0;class F extends k.Disposable{getAttrData(){return this._curAttrData}constructor(A,T,D,I,P,M,H,z,U=new y.EscapeSequenceParser){super(),this._bufferService=A,this._charsetService=T,this._coreService=D,this._logService=I,this._optionsService=P,this._oscLinkService=M,this._coreMouseService=H,this._unicodeService=z,this._parser=U,this._parseBuffer=new Uint32Array(4096),this._stringDecoder=new v.StringToUtf32,this._utf8Decoder=new v.Utf8ToUtf32,this._workCell=new f.CellData,this._windowTitle="",this._iconName="",this._windowTitleStack=[],this._iconNameStack=[],this._curAttrData=g.DEFAULT_ATTR_DATA.clone(),this._eraseAttrDataInternal=g.DEFAULT_ATTR_DATA.clone(),this._onRequestBell=this.register(new m.EventEmitter),this.onRequestBell=this._onRequestBell.event,this._onRequestRefreshRows=this.register(new m.EventEmitter),this.onRequestRefreshRows=this._onRequestRefreshRows.event,this._onRequestReset=this.register(new m.EventEmitter),this.onRequestReset=this._onRequestReset.event,this._onRequestSendFocus=this.register(new m.EventEmitter),this.onRequestSendFocus=this._onRequestSendFocus.event,this._onRequestSyncScrollBar=this.register(new m.EventEmitter),this.onRequestSyncScrollBar=this._onRequestSyncScrollBar.event,this._onRequestWindowsOptionsReport=this.register(new m.EventEmitter),this.onRequestWindowsOptionsReport=this._onRequestWindowsOptionsReport.event,this._onA11yChar=this.register(new m.EventEmitter),this.onA11yChar=this._onA11yChar.event,this._onA11yTab=this.register(new m.EventEmitter),this.onA11yTab=this._onA11yTab.event,this._onCursorMove=this.register(new m.EventEmitter),this.onCursorMove=this._onCursorMove.event,this._onLineFeed=this.register(new m.EventEmitter),this.onLineFeed=this._onLineFeed.event,this._onScroll=this.register(new m.EventEmitter),this.onScroll=this._onScroll.event,this._onTitleChange=this.register(new m.EventEmitter),this.onTitleChange=this._onTitleChange.event,this._onColor=this.register(new m.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 W(this._bufferService),this._activeBuffer=this._bufferService.buffer,this.register(this._bufferService.buffers.onBufferActivate((O=>this._activeBuffer=O.activeBuffer))),this._parser.setCsiHandlerFallback(((O,Y)=>{this._logService.debug("Unknown CSI code: ",{identifier:this._parser.identToString(O),params:Y.toArray()})})),this._parser.setEscHandlerFallback((O=>{this._logService.debug("Unknown ESC code: ",{identifier:this._parser.identToString(O)})})),this._parser.setExecuteHandlerFallback((O=>{this._logService.debug("Unknown EXECUTE code: ",{code:O})})),this._parser.setOscHandlerFallback(((O,Y,X)=>{this._logService.debug("Unknown OSC code: ",{identifier:O,action:Y,data:X})})),this._parser.setDcsHandlerFallback(((O,Y,X)=>{Y==="HOOK"&&(X=X.toArray()),this._logService.debug("Unknown DCS code: ",{identifier:this._parser.identToString(O),action:Y,payload:X})})),this._parser.setPrintHandler(((O,Y,X)=>this.print(O,Y,X))),this._parser.registerCsiHandler({final:"@"},(O=>this.insertChars(O))),this._parser.registerCsiHandler({intermediates:" ",final:"@"},(O=>this.scrollLeft(O))),this._parser.registerCsiHandler({final:"A"},(O=>this.cursorUp(O))),this._parser.registerCsiHandler({intermediates:" ",final:"A"},(O=>this.scrollRight(O))),this._parser.registerCsiHandler({final:"B"},(O=>this.cursorDown(O))),this._parser.registerCsiHandler({final:"C"},(O=>this.cursorForward(O))),this._parser.registerCsiHandler({final:"D"},(O=>this.cursorBackward(O))),this._parser.registerCsiHandler({final:"E"},(O=>this.cursorNextLine(O))),this._parser.registerCsiHandler({final:"F"},(O=>this.cursorPrecedingLine(O))),this._parser.registerCsiHandler({final:"G"},(O=>this.cursorCharAbsolute(O))),this._parser.registerCsiHandler({final:"H"},(O=>this.cursorPosition(O))),this._parser.registerCsiHandler({final:"I"},(O=>this.cursorForwardTab(O))),this._parser.registerCsiHandler({final:"J"},(O=>this.eraseInDisplay(O,!1))),this._parser.registerCsiHandler({prefix:"?",final:"J"},(O=>this.eraseInDisplay(O,!0))),this._parser.registerCsiHandler({final:"K"},(O=>this.eraseInLine(O,!1))),this._parser.registerCsiHandler({prefix:"?",final:"K"},(O=>this.eraseInLine(O,!0))),this._parser.registerCsiHandler({final:"L"},(O=>this.insertLines(O))),this._parser.registerCsiHandler({final:"M"},(O=>this.deleteLines(O))),this._parser.registerCsiHandler({final:"P"},(O=>this.deleteChars(O))),this._parser.registerCsiHandler({final:"S"},(O=>this.scrollUp(O))),this._parser.registerCsiHandler({final:"T"},(O=>this.scrollDown(O))),this._parser.registerCsiHandler({final:"X"},(O=>this.eraseChars(O))),this._parser.registerCsiHandler({final:"Z"},(O=>this.cursorBackwardTab(O))),this._parser.registerCsiHandler({final:"`"},(O=>this.charPosAbsolute(O))),this._parser.registerCsiHandler({final:"a"},(O=>this.hPositionRelative(O))),this._parser.registerCsiHandler({final:"b"},(O=>this.repeatPrecedingCharacter(O))),this._parser.registerCsiHandler({final:"c"},(O=>this.sendDeviceAttributesPrimary(O))),this._parser.registerCsiHandler({prefix:">",final:"c"},(O=>this.sendDeviceAttributesSecondary(O))),this._parser.registerCsiHandler({final:"d"},(O=>this.linePosAbsolute(O))),this._parser.registerCsiHandler({final:"e"},(O=>this.vPositionRelative(O))),this._parser.registerCsiHandler({final:"f"},(O=>this.hVPosition(O))),this._parser.registerCsiHandler({final:"g"},(O=>this.tabClear(O))),this._parser.registerCsiHandler({final:"h"},(O=>this.setMode(O))),this._parser.registerCsiHandler({prefix:"?",final:"h"},(O=>this.setModePrivate(O))),this._parser.registerCsiHandler({final:"l"},(O=>this.resetMode(O))),this._parser.registerCsiHandler({prefix:"?",final:"l"},(O=>this.resetModePrivate(O))),this._parser.registerCsiHandler({final:"m"},(O=>this.charAttributes(O))),this._parser.registerCsiHandler({final:"n"},(O=>this.deviceStatus(O))),this._parser.registerCsiHandler({prefix:"?",final:"n"},(O=>this.deviceStatusPrivate(O))),this._parser.registerCsiHandler({intermediates:"!",final:"p"},(O=>this.softReset(O))),this._parser.registerCsiHandler({intermediates:" ",final:"q"},(O=>this.setCursorStyle(O))),this._parser.registerCsiHandler({final:"r"},(O=>this.setScrollRegion(O))),this._parser.registerCsiHandler({final:"s"},(O=>this.saveCursor(O))),this._parser.registerCsiHandler({final:"t"},(O=>this.windowOptions(O))),this._parser.registerCsiHandler({final:"u"},(O=>this.restoreCursor(O))),this._parser.registerCsiHandler({intermediates:"'",final:"}"},(O=>this.insertColumns(O))),this._parser.registerCsiHandler({intermediates:"'",final:"~"},(O=>this.deleteColumns(O))),this._parser.registerCsiHandler({intermediates:'"',final:"q"},(O=>this.selectProtected(O))),this._parser.registerCsiHandler({intermediates:"$",final:"p"},(O=>this.requestMode(O,!0))),this._parser.registerCsiHandler({prefix:"?",intermediates:"$",final:"p"},(O=>this.requestMode(O,!1))),this._parser.setExecuteHandler(p.C0.BEL,(()=>this.bell())),this._parser.setExecuteHandler(p.C0.LF,(()=>this.lineFeed())),this._parser.setExecuteHandler(p.C0.VT,(()=>this.lineFeed())),this._parser.setExecuteHandler(p.C0.FF,(()=>this.lineFeed())),this._parser.setExecuteHandler(p.C0.CR,(()=>this.carriageReturn())),this._parser.setExecuteHandler(p.C0.BS,(()=>this.backspace())),this._parser.setExecuteHandler(p.C0.HT,(()=>this.tab())),this._parser.setExecuteHandler(p.C0.SO,(()=>this.shiftOut())),this._parser.setExecuteHandler(p.C0.SI,(()=>this.shiftIn())),this._parser.setExecuteHandler(p.C1.IND,(()=>this.index())),this._parser.setExecuteHandler(p.C1.NEL,(()=>this.nextLine())),this._parser.setExecuteHandler(p.C1.HTS,(()=>this.tabSet())),this._parser.registerOscHandler(0,new S.OscHandler((O=>(this.setTitle(O),this.setIconName(O),!0)))),this._parser.registerOscHandler(1,new S.OscHandler((O=>this.setIconName(O)))),this._parser.registerOscHandler(2,new S.OscHandler((O=>this.setTitle(O)))),this._parser.registerOscHandler(4,new S.OscHandler((O=>this.setOrReportIndexedColor(O)))),this._parser.registerOscHandler(8,new S.OscHandler((O=>this.setHyperlink(O)))),this._parser.registerOscHandler(10,new S.OscHandler((O=>this.setOrReportFgColor(O)))),this._parser.registerOscHandler(11,new S.OscHandler((O=>this.setOrReportBgColor(O)))),this._parser.registerOscHandler(12,new S.OscHandler((O=>this.setOrReportCursorColor(O)))),this._parser.registerOscHandler(104,new S.OscHandler((O=>this.restoreIndexedColor(O)))),this._parser.registerOscHandler(110,new S.OscHandler((O=>this.restoreFgColor(O)))),this._parser.registerOscHandler(111,new S.OscHandler((O=>this.restoreBgColor(O)))),this._parser.registerOscHandler(112,new S.OscHandler((O=>this.restoreCursorColor(O)))),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 O in b.CHARSETS)this._parser.registerEscHandler({intermediates:"(",final:O},(()=>this.selectCharset("("+O))),this._parser.registerEscHandler({intermediates:")",final:O},(()=>this.selectCharset(")"+O))),this._parser.registerEscHandler({intermediates:"*",final:O},(()=>this.selectCharset("*"+O))),this._parser.registerEscHandler({intermediates:"+",final:O},(()=>this.selectCharset("+"+O))),this._parser.registerEscHandler({intermediates:"-",final:O},(()=>this.selectCharset("-"+O))),this._parser.registerEscHandler({intermediates:".",final:O},(()=>this.selectCharset("."+O))),this._parser.registerEscHandler({intermediates:"/",final:O},(()=>this.selectCharset("/"+O)));this._parser.registerEscHandler({intermediates:"#",final:"8"},(()=>this.screenAlignmentPattern())),this._parser.setErrorHandler((O=>(this._logService.error("Parsing error: ",O),O))),this._parser.registerDcsHandler({intermediates:"$",final:"q"},new w.DcsHandler(((O,Y)=>this.requestStatusString(O,Y))))}_preserveStack(A,T,D,I){this._parseStack.paused=!0,this._parseStack.cursorStartX=A,this._parseStack.cursorStartY=T,this._parseStack.decodedLength=D,this._parseStack.position=I}_logSlowResolvingAsync(A){this._logService.logLevel<=E.LogLevelEnum.WARN&&Promise.race([A,new Promise(((T,D)=>setTimeout((()=>D("#SLOW_TIMEOUT")),5e3)))]).catch((T=>{if(T!=="#SLOW_TIMEOUT")throw T;console.warn("async parser handler taking longer than 5000 ms")}))}_getCurrentLinkId(){return this._curAttrData.extended.urlId}parse(A,T){let D,I=this._activeBuffer.x,P=this._activeBuffer.y,M=0;const H=this._parseStack.paused;if(H){if(D=this._parser.parse(this._parseBuffer,this._parseStack.decodedLength,T))return this._logSlowResolvingAsync(D),D;I=this._parseStack.cursorStartX,P=this._parseStack.cursorStartY,this._parseStack.paused=!1,A.length>R&&(M=this._parseStack.position+R)}if(this._logService.logLevel<=E.LogLevelEnum.DEBUG&&this._logService.debug("parsing data"+(typeof A=="string"?` "${A}"`:` "${Array.prototype.map.call(A,(O=>String.fromCharCode(O))).join("")}"`),typeof A=="string"?A.split("").map((O=>O.charCodeAt(0))):A),this._parseBuffer.length<A.length&&this._parseBuffer.length<R&&(this._parseBuffer=new Uint32Array(Math.min(A.length,R))),H||this._dirtyRowTracker.clearRange(),A.length>R)for(let O=M;O<A.length;O+=R){const Y=O+R<A.length?O+R:A.length,X=typeof A=="string"?this._stringDecoder.decode(A.substring(O,Y),this._parseBuffer):this._utf8Decoder.decode(A.subarray(O,Y),this._parseBuffer);if(D=this._parser.parse(this._parseBuffer,X))return this._preserveStack(I,P,X,O),this._logSlowResolvingAsync(D),D}else if(!H){const O=typeof A=="string"?this._stringDecoder.decode(A,this._parseBuffer):this._utf8Decoder.decode(A,this._parseBuffer);if(D=this._parser.parse(this._parseBuffer,O))return this._preserveStack(I,P,O,0),this._logSlowResolvingAsync(D),D}this._activeBuffer.x===I&&this._activeBuffer.y===P||this._onCursorMove.fire();const z=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(z,this._bufferService.rows-1))}print(A,T,D){let I,P;const M=this._charsetService.charset,H=this._optionsService.rawOptions.screenReaderMode,z=this._bufferService.cols,U=this._coreService.decPrivateModes.wraparound,O=this._coreService.modes.insertMode,Y=this._curAttrData;let X=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._activeBuffer.x&&D-T>0&&X.getWidth(this._activeBuffer.x-1)===2&&X.setCellFromCodepoint(this._activeBuffer.x-1,0,1,Y);let Q=this._parser.precedingJoinState;for(let J=T;J<D;++J){if(I=A[J],I<127&&M){const me=M[String.fromCharCode(I)];me&&(I=me.charCodeAt(0))}const re=this._unicodeService.charProperties(I,Q);P=_.UnicodeService.extractWidth(re);const ue=_.UnicodeService.extractShouldJoin(re),de=ue?_.UnicodeService.extractWidth(Q):0;if(Q=re,H&&this._onA11yChar.fire((0,v.stringFromCodePoint)(I)),this._getCurrentLinkId()&&this._oscLinkService.addLineToLink(this._getCurrentLinkId(),this._activeBuffer.ybase+this._activeBuffer.y),this._activeBuffer.x+P-de>z){if(U){const me=X;let ie=this._activeBuffer.x-de;for(this._activeBuffer.x=de,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),X=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y),de>0&&X instanceof g.BufferLine&&X.copyCellsFrom(me,ie,0,de,!1);ie<z;)me.setCellFromCodepoint(ie++,0,1,Y)}else if(this._activeBuffer.x=z-1,P===2)continue}if(ue&&this._activeBuffer.x){const me=X.getWidth(this._activeBuffer.x-1)?1:2;X.addCodepointToCell(this._activeBuffer.x-me,I,P);for(let ie=P-de;--ie>=0;)X.setCellFromCodepoint(this._activeBuffer.x++,0,0,Y)}else if(O&&(X.insertCells(this._activeBuffer.x,P-de,this._activeBuffer.getNullCell(Y)),X.getWidth(z-1)===2&&X.setCellFromCodepoint(z-1,h.NULL_CELL_CODE,h.NULL_CELL_WIDTH,Y)),X.setCellFromCodepoint(this._activeBuffer.x++,I,P,Y),P>0)for(;--P;)X.setCellFromCodepoint(this._activeBuffer.x++,0,0,Y)}this._parser.precedingJoinState=Q,this._activeBuffer.x<z&&D-T>0&&X.getWidth(this._activeBuffer.x)===0&&!X.hasContent(this._activeBuffer.x)&&X.setCellFromCodepoint(this._activeBuffer.x,0,1,Y),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}registerCsiHandler(A,T){return A.final!=="t"||A.prefix||A.intermediates?this._parser.registerCsiHandler(A,T):this._parser.registerCsiHandler(A,(D=>!j(D.params[0],this._optionsService.rawOptions.windowOptions)||T(D)))}registerDcsHandler(A,T){return this._parser.registerDcsHandler(A,new w.DcsHandler(T))}registerEscHandler(A,T){return this._parser.registerEscHandler(A,T)}registerOscHandler(A,T){return this._parser.registerOscHandler(A,new S.OscHandler(T))}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 A;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&&((A=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y))!=null&&A.isWrapped)){this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.y--,this._activeBuffer.x=this._bufferService.cols-1;const T=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);T.hasWidth(this._activeBuffer.x)&&!T.hasContent(this._activeBuffer.x)&&this._activeBuffer.x--}return this._restrictCursor(),!0}tab(){if(this._activeBuffer.x>=this._bufferService.cols)return!0;const A=this._activeBuffer.x;return this._activeBuffer.x=this._activeBuffer.nextStop(),this._optionsService.rawOptions.screenReaderMode&&this._onA11yTab.fire(this._activeBuffer.x-A),!0}shiftOut(){return this._charsetService.setgLevel(1),!0}shiftIn(){return this._charsetService.setgLevel(0),!0}_restrictCursor(A=this._bufferService.cols-1){this._activeBuffer.x=Math.min(A,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(A,T){this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._coreService.decPrivateModes.origin?(this._activeBuffer.x=A,this._activeBuffer.y=this._activeBuffer.scrollTop+T):(this._activeBuffer.x=A,this._activeBuffer.y=T),this._restrictCursor(),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_moveCursor(A,T){this._restrictCursor(),this._setCursor(this._activeBuffer.x+A,this._activeBuffer.y+T)}cursorUp(A){const T=this._activeBuffer.y-this._activeBuffer.scrollTop;return T>=0?this._moveCursor(0,-Math.min(T,A.params[0]||1)):this._moveCursor(0,-(A.params[0]||1)),!0}cursorDown(A){const T=this._activeBuffer.scrollBottom-this._activeBuffer.y;return T>=0?this._moveCursor(0,Math.min(T,A.params[0]||1)):this._moveCursor(0,A.params[0]||1),!0}cursorForward(A){return this._moveCursor(A.params[0]||1,0),!0}cursorBackward(A){return this._moveCursor(-(A.params[0]||1),0),!0}cursorNextLine(A){return this.cursorDown(A),this._activeBuffer.x=0,!0}cursorPrecedingLine(A){return this.cursorUp(A),this._activeBuffer.x=0,!0}cursorCharAbsolute(A){return this._setCursor((A.params[0]||1)-1,this._activeBuffer.y),!0}cursorPosition(A){return this._setCursor(A.length>=2?(A.params[1]||1)-1:0,(A.params[0]||1)-1),!0}charPosAbsolute(A){return this._setCursor((A.params[0]||1)-1,this._activeBuffer.y),!0}hPositionRelative(A){return this._moveCursor(A.params[0]||1,0),!0}linePosAbsolute(A){return this._setCursor(this._activeBuffer.x,(A.params[0]||1)-1),!0}vPositionRelative(A){return this._moveCursor(0,A.params[0]||1),!0}hVPosition(A){return this.cursorPosition(A),!0}tabClear(A){const T=A.params[0];return T===0?delete this._activeBuffer.tabs[this._activeBuffer.x]:T===3&&(this._activeBuffer.tabs={}),!0}cursorForwardTab(A){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let T=A.params[0]||1;for(;T--;)this._activeBuffer.x=this._activeBuffer.nextStop();return!0}cursorBackwardTab(A){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let T=A.params[0]||1;for(;T--;)this._activeBuffer.x=this._activeBuffer.prevStop();return!0}selectProtected(A){const T=A.params[0];return T===1&&(this._curAttrData.bg|=536870912),T!==2&&T!==0||(this._curAttrData.bg&=-536870913),!0}_eraseInBufferLine(A,T,D,I=!1,P=!1){const M=this._activeBuffer.lines.get(this._activeBuffer.ybase+A);M.replaceCells(T,D,this._activeBuffer.getNullCell(this._eraseAttrData()),P),I&&(M.isWrapped=!1)}_resetBufferLine(A,T=!1){const D=this._activeBuffer.lines.get(this._activeBuffer.ybase+A);D&&(D.fill(this._activeBuffer.getNullCell(this._eraseAttrData()),T),this._bufferService.buffer.clearMarkers(this._activeBuffer.ybase+A),D.isWrapped=!1)}eraseInDisplay(A,T=!1){let D;switch(this._restrictCursor(this._bufferService.cols),A.params[0]){case 0:for(D=this._activeBuffer.y,this._dirtyRowTracker.markDirty(D),this._eraseInBufferLine(D++,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,T);D<this._bufferService.rows;D++)this._resetBufferLine(D,T);this._dirtyRowTracker.markDirty(D);break;case 1:for(D=this._activeBuffer.y,this._dirtyRowTracker.markDirty(D),this._eraseInBufferLine(D,0,this._activeBuffer.x+1,!0,T),this._activeBuffer.x+1>=this._bufferService.cols&&(this._activeBuffer.lines.get(D+1).isWrapped=!1);D--;)this._resetBufferLine(D,T);this._dirtyRowTracker.markDirty(0);break;case 2:for(D=this._bufferService.rows,this._dirtyRowTracker.markDirty(D-1);D--;)this._resetBufferLine(D,T);this._dirtyRowTracker.markDirty(0);break;case 3:const I=this._activeBuffer.lines.length-this._bufferService.rows;I>0&&(this._activeBuffer.lines.trimStart(I),this._activeBuffer.ybase=Math.max(this._activeBuffer.ybase-I,0),this._activeBuffer.ydisp=Math.max(this._activeBuffer.ydisp-I,0),this._onScroll.fire(0))}return!0}eraseInLine(A,T=!1){switch(this._restrictCursor(this._bufferService.cols),A.params[0]){case 0:this._eraseInBufferLine(this._activeBuffer.y,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,T);break;case 1:this._eraseInBufferLine(this._activeBuffer.y,0,this._activeBuffer.x+1,!1,T);break;case 2:this._eraseInBufferLine(this._activeBuffer.y,0,this._bufferService.cols,!0,T)}return this._dirtyRowTracker.markDirty(this._activeBuffer.y),!0}insertLines(A){this._restrictCursor();let T=A.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;const D=this._activeBuffer.ybase+this._activeBuffer.y,I=this._bufferService.rows-1-this._activeBuffer.scrollBottom,P=this._bufferService.rows-1+this._activeBuffer.ybase-I+1;for(;T--;)this._activeBuffer.lines.splice(P-1,1),this._activeBuffer.lines.splice(D,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.y,this._activeBuffer.scrollBottom),this._activeBuffer.x=0,!0}deleteLines(A){this._restrictCursor();let T=A.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;const D=this._activeBuffer.ybase+this._activeBuffer.y;let I;for(I=this._bufferService.rows-1-this._activeBuffer.scrollBottom,I=this._bufferService.rows-1+this._activeBuffer.ybase-I;T--;)this._activeBuffer.lines.splice(D,1),this._activeBuffer.lines.splice(I,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.y,this._activeBuffer.scrollBottom),this._activeBuffer.x=0,!0}insertChars(A){this._restrictCursor();const T=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return T&&(T.insertCells(this._activeBuffer.x,A.params[0]||1,this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}deleteChars(A){this._restrictCursor();const T=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return T&&(T.deleteCells(this._activeBuffer.x,A.params[0]||1,this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}scrollUp(A){let T=A.params[0]||1;for(;T--;)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(A){let T=A.params[0]||1;for(;T--;)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(g.DEFAULT_ATTR_DATA));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollLeft(A){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;const T=A.params[0]||1;for(let D=this._activeBuffer.scrollTop;D<=this._activeBuffer.scrollBottom;++D){const I=this._activeBuffer.lines.get(this._activeBuffer.ybase+D);I.deleteCells(0,T,this._activeBuffer.getNullCell(this._eraseAttrData())),I.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollRight(A){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;const T=A.params[0]||1;for(let D=this._activeBuffer.scrollTop;D<=this._activeBuffer.scrollBottom;++D){const I=this._activeBuffer.lines.get(this._activeBuffer.ybase+D);I.insertCells(0,T,this._activeBuffer.getNullCell(this._eraseAttrData())),I.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}insertColumns(A){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;const T=A.params[0]||1;for(let D=this._activeBuffer.scrollTop;D<=this._activeBuffer.scrollBottom;++D){const I=this._activeBuffer.lines.get(this._activeBuffer.ybase+D);I.insertCells(this._activeBuffer.x,T,this._activeBuffer.getNullCell(this._eraseAttrData())),I.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}deleteColumns(A){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;const T=A.params[0]||1;for(let D=this._activeBuffer.scrollTop;D<=this._activeBuffer.scrollBottom;++D){const I=this._activeBuffer.lines.get(this._activeBuffer.ybase+D);I.deleteCells(this._activeBuffer.x,T,this._activeBuffer.getNullCell(this._eraseAttrData())),I.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}eraseChars(A){this._restrictCursor();const T=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return T&&(T.replaceCells(this._activeBuffer.x,this._activeBuffer.x+(A.params[0]||1),this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}repeatPrecedingCharacter(A){const T=this._parser.precedingJoinState;if(!T)return!0;const D=A.params[0]||1,I=_.UnicodeService.extractWidth(T),P=this._activeBuffer.x-I,M=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).getString(P),H=new Uint32Array(M.length*D);let z=0;for(let O=0;O<M.length;){const Y=M.codePointAt(O)||0;H[z++]=Y,O+=Y>65535?2:1}let U=z;for(let O=1;O<D;++O)H.copyWithin(U,0,z),U+=z;return this.print(H,0,U),!0}sendDeviceAttributesPrimary(A){return A.params[0]>0||(this._is("xterm")||this._is("rxvt-unicode")||this._is("screen")?this._coreService.triggerDataEvent(p.C0.ESC+"[?1;2c"):this._is("linux")&&this._coreService.triggerDataEvent(p.C0.ESC+"[?6c")),!0}sendDeviceAttributesSecondary(A){return A.params[0]>0||(this._is("xterm")?this._coreService.triggerDataEvent(p.C0.ESC+"[>0;276;0c"):this._is("rxvt-unicode")?this._coreService.triggerDataEvent(p.C0.ESC+"[>85;95;0c"):this._is("linux")?this._coreService.triggerDataEvent(A.params[0]+"c"):this._is("screen")&&this._coreService.triggerDataEvent(p.C0.ESC+"[>83;40003;0c")),!0}_is(A){return(this._optionsService.rawOptions.termName+"").indexOf(A)===0}setMode(A){for(let T=0;T<A.length;T++)switch(A.params[T]){case 4:this._coreService.modes.insertMode=!0;break;case 20:this._optionsService.options.convertEol=!0}return!0}setModePrivate(A){for(let T=0;T<A.length;T++)switch(A.params[T]){case 1:this._coreService.decPrivateModes.applicationCursorKeys=!0;break;case 2:this._charsetService.setgCharset(0,b.DEFAULT_CHARSET),this._charsetService.setgCharset(1,b.DEFAULT_CHARSET),this._charsetService.setgCharset(2,b.DEFAULT_CHARSET),this._charsetService.setgCharset(3,b.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(A){for(let T=0;T<A.length;T++)switch(A.params[T]){case 4:this._coreService.modes.insertMode=!1;break;case 20:this._optionsService.options.convertEol=!1}return!0}resetModePrivate(A){for(let T=0;T<A.length;T++)switch(A.params[T]){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(),A.params[T]===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(A,T){const D=this._coreService.decPrivateModes,{activeProtocol:I,activeEncoding:P}=this._coreMouseService,M=this._coreService,{buffers:H,cols:z}=this._bufferService,{active:U,alt:O}=H,Y=this._optionsService.rawOptions,X=ue=>ue?1:2,Q=A.params[0];return J=Q,re=T?Q===2?4:Q===4?X(M.modes.insertMode):Q===12?3:Q===20?X(Y.convertEol):0:Q===1?X(D.applicationCursorKeys):Q===3?Y.windowOptions.setWinLines?z===80?2:z===132?1:0:0:Q===6?X(D.origin):Q===7?X(D.wraparound):Q===8?3:Q===9?X(I==="X10"):Q===12?X(Y.cursorBlink):Q===25?X(!M.isCursorHidden):Q===45?X(D.reverseWraparound):Q===66?X(D.applicationKeypad):Q===67?4:Q===1e3?X(I==="VT200"):Q===1002?X(I==="DRAG"):Q===1003?X(I==="ANY"):Q===1004?X(D.sendFocus):Q===1005?4:Q===1006?X(P==="SGR"):Q===1015?4:Q===1016?X(P==="SGR_PIXELS"):Q===1048?1:Q===47||Q===1047||Q===1049?X(U===O):Q===2004?X(D.bracketedPasteMode):0,M.triggerDataEvent(`${p.C0.ESC}[${T?"":"?"}${J};${re}$y`),!0;var J,re}_updateAttrColor(A,T,D,I,P){return T===2?(A|=50331648,A&=-16777216,A|=x.AttributeData.fromColorRGB([D,I,P])):T===5&&(A&=-50331904,A|=33554432|255&D),A}_extractColor(A,T,D){const I=[0,0,-1,0,0,0];let P=0,M=0;do{if(I[M+P]=A.params[T+M],A.hasSubParams(T+M)){const H=A.getSubParams(T+M);let z=0;do I[1]===5&&(P=1),I[M+z+1+P]=H[z];while(++z<H.length&&z+M+1+P<I.length);break}if(I[1]===5&&M+P>=2||I[1]===2&&M+P>=5)break;I[1]&&(P=1)}while(++M+T<A.length&&M+P<I.length);for(let H=2;H<I.length;++H)I[H]===-1&&(I[H]=0);switch(I[0]){case 38:D.fg=this._updateAttrColor(D.fg,I[1],I[3],I[4],I[5]);break;case 48:D.bg=this._updateAttrColor(D.bg,I[1],I[3],I[4],I[5]);break;case 58:D.extended=D.extended.clone(),D.extended.underlineColor=this._updateAttrColor(D.extended.underlineColor,I[1],I[3],I[4],I[5])}return M}_processUnderline(A,T){T.extended=T.extended.clone(),(!~A||A>5)&&(A=1),T.extended.underlineStyle=A,T.fg|=268435456,A===0&&(T.fg&=-268435457),T.updateExtended()}_processSGR0(A){A.fg=g.DEFAULT_ATTR_DATA.fg,A.bg=g.DEFAULT_ATTR_DATA.bg,A.extended=A.extended.clone(),A.extended.underlineStyle=0,A.extended.underlineColor&=-67108864,A.updateExtended()}charAttributes(A){if(A.length===1&&A.params[0]===0)return this._processSGR0(this._curAttrData),!0;const T=A.length;let D;const I=this._curAttrData;for(let P=0;P<T;P++)D=A.params[P],D>=30&&D<=37?(I.fg&=-50331904,I.fg|=16777216|D-30):D>=40&&D<=47?(I.bg&=-50331904,I.bg|=16777216|D-40):D>=90&&D<=97?(I.fg&=-50331904,I.fg|=16777224|D-90):D>=100&&D<=107?(I.bg&=-50331904,I.bg|=16777224|D-100):D===0?this._processSGR0(I):D===1?I.fg|=134217728:D===3?I.bg|=67108864:D===4?(I.fg|=268435456,this._processUnderline(A.hasSubParams(P)?A.getSubParams(P)[0]:1,I)):D===5?I.fg|=536870912:D===7?I.fg|=67108864:D===8?I.fg|=1073741824:D===9?I.fg|=2147483648:D===2?I.bg|=134217728:D===21?this._processUnderline(2,I):D===22?(I.fg&=-134217729,I.bg&=-134217729):D===23?I.bg&=-67108865:D===24?(I.fg&=-268435457,this._processUnderline(0,I)):D===25?I.fg&=-536870913:D===27?I.fg&=-67108865:D===28?I.fg&=-1073741825:D===29?I.fg&=2147483647:D===39?(I.fg&=-67108864,I.fg|=16777215&g.DEFAULT_ATTR_DATA.fg):D===49?(I.bg&=-67108864,I.bg|=16777215&g.DEFAULT_ATTR_DATA.bg):D===38||D===48||D===58?P+=this._extractColor(A,P,I):D===53?I.bg|=1073741824:D===55?I.bg&=-1073741825:D===59?(I.extended=I.extended.clone(),I.extended.underlineColor=-1,I.updateExtended()):D===100?(I.fg&=-67108864,I.fg|=16777215&g.DEFAULT_ATTR_DATA.fg,I.bg&=-67108864,I.bg|=16777215&g.DEFAULT_ATTR_DATA.bg):this._logService.debug("Unknown SGR attribute: %d.",D);return!0}deviceStatus(A){switch(A.params[0]){case 5:this._coreService.triggerDataEvent(`${p.C0.ESC}[0n`);break;case 6:const T=this._activeBuffer.y+1,D=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${p.C0.ESC}[${T};${D}R`)}return!0}deviceStatusPrivate(A){if(A.params[0]===6){const T=this._activeBuffer.y+1,D=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${p.C0.ESC}[?${T};${D}R`)}return!0}softReset(A){return this._coreService.isCursorHidden=!1,this._onRequestSyncScrollBar.fire(),this._activeBuffer.scrollTop=0,this._activeBuffer.scrollBottom=this._bufferService.rows-1,this._curAttrData=g.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(A){const T=A.params[0]||1;switch(T){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 D=T%2==1;return this._optionsService.options.cursorBlink=D,!0}setScrollRegion(A){const T=A.params[0]||1;let D;return(A.length<2||(D=A.params[1])>this._bufferService.rows||D===0)&&(D=this._bufferService.rows),D>T&&(this._activeBuffer.scrollTop=T-1,this._activeBuffer.scrollBottom=D-1,this._setCursor(0,0)),!0}windowOptions(A){if(!j(A.params[0],this._optionsService.rawOptions.windowOptions))return!0;const T=A.length>1?A.params[1]:0;switch(A.params[0]){case 14:T!==2&&this._onRequestWindowsOptionsReport.fire($.GET_WIN_SIZE_PIXELS);break;case 16:this._onRequestWindowsOptionsReport.fire($.GET_CELL_SIZE_PIXELS);break;case 18:this._bufferService&&this._coreService.triggerDataEvent(`${p.C0.ESC}[8;${this._bufferService.rows};${this._bufferService.cols}t`);break;case 22:T!==0&&T!==2||(this._windowTitleStack.push(this._windowTitle),this._windowTitleStack.length>10&&this._windowTitleStack.shift()),T!==0&&T!==1||(this._iconNameStack.push(this._iconName),this._iconNameStack.length>10&&this._iconNameStack.shift());break;case 23:T!==0&&T!==2||this._windowTitleStack.length&&this.setTitle(this._windowTitleStack.pop()),T!==0&&T!==1||this._iconNameStack.length&&this.setIconName(this._iconNameStack.pop())}return!0}saveCursor(A){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(A){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(A){return this._windowTitle=A,this._onTitleChange.fire(A),!0}setIconName(A){return this._iconName=A,!0}setOrReportIndexedColor(A){const T=[],D=A.split(";");for(;D.length>1;){const I=D.shift(),P=D.shift();if(/^\d+$/.exec(I)){const M=parseInt(I);if(V(M))if(P==="?")T.push({type:0,index:M});else{const H=(0,N.parseColor)(P);H&&T.push({type:1,index:M,color:H})}}}return T.length&&this._onColor.fire(T),!0}setHyperlink(A){const T=A.split(";");return!(T.length<2)&&(T[1]?this._createHyperlink(T[0],T[1]):!T[0]&&this._finishHyperlink())}_createHyperlink(A,T){this._getCurrentLinkId()&&this._finishHyperlink();const D=A.split(":");let I;const P=D.findIndex((M=>M.startsWith("id=")));return P!==-1&&(I=D[P].slice(3)||void 0),this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=this._oscLinkService.registerLink({id:I,uri:T}),this._curAttrData.updateExtended(),!0}_finishHyperlink(){return this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=0,this._curAttrData.updateExtended(),!0}_setOrReportSpecialColor(A,T){const D=A.split(";");for(let I=0;I<D.length&&!(T>=this._specialColors.length);++I,++T)if(D[I]==="?")this._onColor.fire([{type:0,index:this._specialColors[T]}]);else{const P=(0,N.parseColor)(D[I]);P&&this._onColor.fire([{type:1,index:this._specialColors[T],color:P}])}return!0}setOrReportFgColor(A){return this._setOrReportSpecialColor(A,0)}setOrReportBgColor(A){return this._setOrReportSpecialColor(A,1)}setOrReportCursorColor(A){return this._setOrReportSpecialColor(A,2)}restoreIndexedColor(A){if(!A)return this._onColor.fire([{type:2}]),!0;const T=[],D=A.split(";");for(let I=0;I<D.length;++I)if(/^\d+$/.exec(D[I])){const P=parseInt(D[I]);V(P)&&T.push({type:2,index:P})}return T.length&&this._onColor.fire(T),!0}restoreFgColor(A){return this._onColor.fire([{type:2,index:256}]),!0}restoreBgColor(A){return this._onColor.fire([{type:2,index:257}]),!0}restoreCursorColor(A){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,b.DEFAULT_CHARSET),!0}selectCharset(A){return A.length!==2?(this.selectDefaultCharset(),!0):(A[0]==="/"||this._charsetService.setgCharset(L[A[0]],b.CHARSETS[A[1]]||b.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 A=this._activeBuffer.scrollBottom-this._activeBuffer.scrollTop;this._activeBuffer.lines.shiftElements(this._activeBuffer.ybase+this._activeBuffer.y,A,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=g.DEFAULT_ATTR_DATA.clone(),this._eraseAttrDataInternal=g.DEFAULT_ATTR_DATA.clone()}_eraseAttrData(){return this._eraseAttrDataInternal.bg&=-67108864,this._eraseAttrDataInternal.bg|=67108863&this._curAttrData.bg,this._eraseAttrDataInternal}setgLevel(A){return this._charsetService.setgLevel(A),!0}screenAlignmentPattern(){const A=new f.CellData;A.content=4194373,A.fg=this._curAttrData.fg,A.bg=this._curAttrData.bg,this._setCursor(0,0);for(let T=0;T<this._bufferService.rows;++T){const D=this._activeBuffer.ybase+this._activeBuffer.y+T,I=this._activeBuffer.lines.get(D);I&&(I.fill(A),I.isWrapped=!1)}return this._dirtyRowTracker.markAllDirty(),this._setCursor(0,0),!0}requestStatusString(A,T){const D=this._bufferService.buffer,I=this._optionsService.rawOptions;return(P=>(this._coreService.triggerDataEvent(`${p.C0.ESC}${P}${p.C0.ESC}\\`),!0))(A==='"q'?`P1$r${this._curAttrData.isProtected()?1:0}"q`:A==='"p'?'P1$r61;1"p':A==="r"?`P1$r${D.scrollTop+1};${D.scrollBottom+1}r`:A==="m"?"P1$r0m":A===" q"?`P1$r${{block:2,underline:4,bar:6}[I.cursorStyle]-(I.cursorBlink?1:0)} q`:"P0$r")}markRangeDirty(A,T){this._dirtyRowTracker.markRangeDirty(A,T)}}a.InputHandler=F;let W=class{constructor(q){this._bufferService=q,this.clearRange()}clearRange(){this.start=this._bufferService.buffer.y,this.end=this._bufferService.buffer.y}markDirty(q){q<this.start?this.start=q:q>this.end&&(this.end=q)}markRangeDirty(q,A){q>A&&(G=q,q=A,A=G),q<this.start&&(this.start=q),A>this.end&&(this.end=A)}markAllDirty(){this.markRangeDirty(0,this._bufferService.rows-1)}};function V(q){return 0<=q&&q<256}W=c([u(0,E.IBufferService)],W)},844:(d,a)=>{function o(c){for(const u of c)u.dispose();c.length=0}Object.defineProperty(a,"__esModule",{value:!0}),a.getDisposeArrayDisposable=a.disposeArray=a.toDisposable=a.MutableDisposable=a.Disposable=void 0,a.Disposable=class{constructor(){this._disposables=[],this._isDisposed=!1}dispose(){this._isDisposed=!0;for(const c of this._disposables)c.dispose();this._disposables.length=0}register(c){return this._disposables.push(c),c}unregister(c){const u=this._disposables.indexOf(c);u!==-1&&this._disposables.splice(u,1)}},a.MutableDisposable=class{constructor(){this._isDisposed=!1}get value(){return this._isDisposed?void 0:this._value}set value(c){var u;this._isDisposed||c===this._value||((u=this._value)==null||u.dispose(),this._value=c)}clear(){this.value=void 0}dispose(){var c;this._isDisposed=!0,(c=this._value)==null||c.dispose(),this._value=void 0}},a.toDisposable=function(c){return{dispose:c}},a.disposeArray=o,a.getDisposeArrayDisposable=function(c){return{dispose:()=>o(c)}}},1505:(d,a)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.FourKeyMap=a.TwoKeyMap=void 0;class o{constructor(){this._data={}}set(u,p,b){this._data[u]||(this._data[u]={}),this._data[u][p]=b}get(u,p){return this._data[u]?this._data[u][p]:void 0}clear(){this._data={}}}a.TwoKeyMap=o,a.FourKeyMap=class{constructor(){this._data=new o}set(c,u,p,b,y){this._data.get(c,u)||this._data.set(c,u,new o),this._data.get(c,u).set(p,b,y)}get(c,u,p,b){var y;return(y=this._data.get(c,u))==null?void 0:y.get(p,b)}clear(){this._data.clear()}}},6114:(d,a)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.isChromeOS=a.isLinux=a.isWindows=a.isIphone=a.isIpad=a.isMac=a.getSafariVersion=a.isSafari=a.isLegacyEdge=a.isFirefox=a.isNode=void 0,a.isNode=typeof process<"u"&&"title"in process;const o=a.isNode?"node":navigator.userAgent,c=a.isNode?"node":navigator.platform;a.isFirefox=o.includes("Firefox"),a.isLegacyEdge=o.includes("Edge"),a.isSafari=/^((?!chrome|android).)*safari/i.test(o),a.getSafariVersion=function(){if(!a.isSafari)return 0;const u=o.match(/Version\/(\d+)/);return u===null||u.length<2?0:parseInt(u[1])},a.isMac=["Macintosh","MacIntel","MacPPC","Mac68K"].includes(c),a.isIpad=c==="iPad",a.isIphone=c==="iPhone",a.isWindows=["Windows","Win16","Win32","WinCE"].includes(c),a.isLinux=c.indexOf("Linux")>=0,a.isChromeOS=/\bCrOS\b/.test(o)},6106:(d,a)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.SortedList=void 0;let o=0;a.SortedList=class{constructor(c){this._getKey=c,this._array=[]}clear(){this._array.length=0}insert(c){this._array.length!==0?(o=this._search(this._getKey(c)),this._array.splice(o,0,c)):this._array.push(c)}delete(c){if(this._array.length===0)return!1;const u=this._getKey(c);if(u===void 0||(o=this._search(u),o===-1)||this._getKey(this._array[o])!==u)return!1;do if(this._array[o]===c)return this._array.splice(o,1),!0;while(++o<this._array.length&&this._getKey(this._array[o])===u);return!1}*getKeyIterator(c){if(this._array.length!==0&&(o=this._search(c),!(o<0||o>=this._array.length)&&this._getKey(this._array[o])===c))do yield this._array[o];while(++o<this._array.length&&this._getKey(this._array[o])===c)}forEachByKey(c,u){if(this._array.length!==0&&(o=this._search(c),!(o<0||o>=this._array.length)&&this._getKey(this._array[o])===c))do u(this._array[o]);while(++o<this._array.length&&this._getKey(this._array[o])===c)}values(){return[...this._array].values()}_search(c){let u=0,p=this._array.length-1;for(;p>=u;){let b=u+p>>1;const y=this._getKey(this._array[b]);if(y>c)p=b-1;else{if(!(y<c)){for(;b>0&&this._getKey(this._array[b-1])===c;)b--;return b}u=b+1}}return u}}},7226:(d,a,o)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.DebouncedIdleTask=a.IdleTaskQueue=a.PriorityTaskQueue=void 0;const c=o(6114);class u{constructor(){this._tasks=[],this._i=0}enqueue(y){this._tasks.push(y),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(y){this._idleCallback=void 0;let k=0,v=0,g=y.timeRemaining(),m=0;for(;this._i<this._tasks.length;){if(k=Date.now(),this._tasks[this._i]()||this._i++,k=Math.max(1,Date.now()-k),v=Math.max(k,v),m=y.timeRemaining(),1.5*v>m)return g-k<-20&&console.warn(`task queue exceeded allotted deadline by ${Math.abs(Math.round(g-k))}ms`),void this._start();g=m}this.clear()}}class p extends u{_requestCallback(y){return setTimeout((()=>y(this._createDeadline(16))))}_cancelCallback(y){clearTimeout(y)}_createDeadline(y){const k=Date.now()+y;return{timeRemaining:()=>Math.max(0,k-Date.now())}}}a.PriorityTaskQueue=p,a.IdleTaskQueue=!c.isNode&&"requestIdleCallback"in window?class extends u{_requestCallback(b){return requestIdleCallback(b)}_cancelCallback(b){cancelIdleCallback(b)}}:p,a.DebouncedIdleTask=class{constructor(){this._queue=new a.IdleTaskQueue}set(b){this._queue.clear(),this._queue.enqueue(b)}flush(){this._queue.flush()}}},9282:(d,a,o)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.updateWindowsModeWrappedState=void 0;const c=o(643);a.updateWindowsModeWrappedState=function(u){const p=u.buffer.lines.get(u.buffer.ybase+u.buffer.y-1),b=p==null?void 0:p.get(u.cols-1),y=u.buffer.lines.get(u.buffer.ybase+u.buffer.y);y&&b&&(y.isWrapped=b[c.CHAR_DATA_CODE_INDEX]!==c.NULL_CELL_CODE&&b[c.CHAR_DATA_CODE_INDEX]!==c.WHITESPACE_CELL_CODE)}},3734:(d,a)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.ExtendedAttrs=a.AttributeData=void 0;class o{constructor(){this.fg=0,this.bg=0,this.extended=new c}static toColorRGB(p){return[p>>>16&255,p>>>8&255,255&p]}static fromColorRGB(p){return(255&p[0])<<16|(255&p[1])<<8|255&p[2]}clone(){const p=new o;return p.fg=this.fg,p.bg=this.bg,p.extended=this.extended.clone(),p}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}}a.AttributeData=o;class c{get ext(){return this._urlId?-469762049&this._ext|this.underlineStyle<<26:this._ext}set ext(p){this._ext=p}get underlineStyle(){return this._urlId?5:(469762048&this._ext)>>26}set underlineStyle(p){this._ext&=-469762049,this._ext|=p<<26&469762048}get underlineColor(){return 67108863&this._ext}set underlineColor(p){this._ext&=-67108864,this._ext|=67108863&p}get urlId(){return this._urlId}set urlId(p){this._urlId=p}get underlineVariantOffset(){const p=(3758096384&this._ext)>>29;return p<0?4294967288^p:p}set underlineVariantOffset(p){this._ext&=536870911,this._ext|=p<<29&3758096384}constructor(p=0,b=0){this._ext=0,this._urlId=0,this._ext=p,this._urlId=b}clone(){return new c(this._ext,this._urlId)}isEmpty(){return this.underlineStyle===0&&this._urlId===0}}a.ExtendedAttrs=c},9092:(d,a,o)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.Buffer=a.MAX_BUFFER_SIZE=void 0;const c=o(6349),u=o(7226),p=o(3734),b=o(8437),y=o(4634),k=o(511),v=o(643),g=o(4863),m=o(7116);a.MAX_BUFFER_SIZE=4294967295,a.Buffer=class{constructor(h,f,x){this._hasScrollback=h,this._optionsService=f,this._bufferService=x,this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.tabs={},this.savedY=0,this.savedX=0,this.savedCurAttrData=b.DEFAULT_ATTR_DATA.clone(),this.savedCharset=m.DEFAULT_CHARSET,this.markers=[],this._nullCell=k.CellData.fromCharData([0,v.NULL_CELL_CHAR,v.NULL_CELL_WIDTH,v.NULL_CELL_CODE]),this._whitespaceCell=k.CellData.fromCharData([0,v.WHITESPACE_CELL_CHAR,v.WHITESPACE_CELL_WIDTH,v.WHITESPACE_CELL_CODE]),this._isClearing=!1,this._memoryCleanupQueue=new u.IdleTaskQueue,this._memoryCleanupPosition=0,this._cols=this._bufferService.cols,this._rows=this._bufferService.rows,this.lines=new c.CircularList(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}getNullCell(h){return h?(this._nullCell.fg=h.fg,this._nullCell.bg=h.bg,this._nullCell.extended=h.extended):(this._nullCell.fg=0,this._nullCell.bg=0,this._nullCell.extended=new p.ExtendedAttrs),this._nullCell}getWhitespaceCell(h){return h?(this._whitespaceCell.fg=h.fg,this._whitespaceCell.bg=h.bg,this._whitespaceCell.extended=h.extended):(this._whitespaceCell.fg=0,this._whitespaceCell.bg=0,this._whitespaceCell.extended=new p.ExtendedAttrs),this._whitespaceCell}getBlankLine(h,f){return new b.BufferLine(this._bufferService.cols,this.getNullCell(h),f)}get hasScrollback(){return this._hasScrollback&&this.lines.maxLength>this._rows}get isCursorInViewport(){const h=this.ybase+this.y-this.ydisp;return h>=0&&h<this._rows}_getCorrectBufferLength(h){if(!this._hasScrollback)return h;const f=h+this._optionsService.rawOptions.scrollback;return f>a.MAX_BUFFER_SIZE?a.MAX_BUFFER_SIZE:f}fillViewportRows(h){if(this.lines.length===0){h===void 0&&(h=b.DEFAULT_ATTR_DATA);let f=this._rows;for(;f--;)this.lines.push(this.getBlankLine(h))}}clear(){this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.lines=new c.CircularList(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}resize(h,f){const x=this.getNullCell(b.DEFAULT_ATTR_DATA);let E=0;const _=this._getCorrectBufferLength(f);if(_>this.lines.maxLength&&(this.lines.maxLength=_),this.lines.length>0){if(this._cols<h)for(let w=0;w<this.lines.length;w++)E+=+this.lines.get(w).resize(h,x);let S=0;if(this._rows<f)for(let w=this._rows;w<f;w++)this.lines.length<f+this.ybase&&(this._optionsService.rawOptions.windowsMode||this._optionsService.rawOptions.windowsPty.backend!==void 0||this._optionsService.rawOptions.windowsPty.buildNumber!==void 0?this.lines.push(new b.BufferLine(h,x)):this.ybase>0&&this.lines.length<=this.ybase+this.y+S+1?(this.ybase--,S++,this.ydisp>0&&this.ydisp--):this.lines.push(new b.BufferLine(h,x)));else for(let w=this._rows;w>f;w--)this.lines.length>f+this.ybase&&(this.lines.length>this.ybase+this.y+1?this.lines.pop():(this.ybase++,this.ydisp++));if(_<this.lines.maxLength){const w=this.lines.length-_;w>0&&(this.lines.trimStart(w),this.ybase=Math.max(this.ybase-w,0),this.ydisp=Math.max(this.ydisp-w,0),this.savedY=Math.max(this.savedY-w,0)),this.lines.maxLength=_}this.x=Math.min(this.x,h-1),this.y=Math.min(this.y,f-1),S&&(this.y+=S),this.savedX=Math.min(this.savedX,h-1),this.scrollTop=0}if(this.scrollBottom=f-1,this._isReflowEnabled&&(this._reflow(h,f),this._cols>h))for(let S=0;S<this.lines.length;S++)E+=+this.lines.get(S).resize(h,x);this._cols=h,this._rows=f,this._memoryCleanupQueue.clear(),E>.1*this.lines.length&&(this._memoryCleanupPosition=0,this._memoryCleanupQueue.enqueue((()=>this._batchedMemoryCleanup())))}_batchedMemoryCleanup(){let h=!0;this._memoryCleanupPosition>=this.lines.length&&(this._memoryCleanupPosition=0,h=!1);let f=0;for(;this._memoryCleanupPosition<this.lines.length;)if(f+=this.lines.get(this._memoryCleanupPosition++).cleanupMemory(),f>100)return!0;return h}get _isReflowEnabled(){const h=this._optionsService.rawOptions.windowsPty;return h&&h.buildNumber?this._hasScrollback&&h.backend==="conpty"&&h.buildNumber>=21376:this._hasScrollback&&!this._optionsService.rawOptions.windowsMode}_reflow(h,f){this._cols!==h&&(h>this._cols?this._reflowLarger(h,f):this._reflowSmaller(h,f))}_reflowLarger(h,f){const x=(0,y.reflowLargerGetLinesToRemove)(this.lines,this._cols,h,this.ybase+this.y,this.getNullCell(b.DEFAULT_ATTR_DATA));if(x.length>0){const E=(0,y.reflowLargerCreateNewLayout)(this.lines,x);(0,y.reflowLargerApplyNewLayout)(this.lines,E.layout),this._reflowLargerAdjustViewport(h,f,E.countRemoved)}}_reflowLargerAdjustViewport(h,f,x){const E=this.getNullCell(b.DEFAULT_ATTR_DATA);let _=x;for(;_-- >0;)this.ybase===0?(this.y>0&&this.y--,this.lines.length<f&&this.lines.push(new b.BufferLine(h,E))):(this.ydisp===this.ybase&&this.ydisp--,this.ybase--);this.savedY=Math.max(this.savedY-x,0)}_reflowSmaller(h,f){const x=this.getNullCell(b.DEFAULT_ATTR_DATA),E=[];let _=0;for(let S=this.lines.length-1;S>=0;S--){let w=this.lines.get(S);if(!w||!w.isWrapped&&w.getTrimmedLength()<=h)continue;const N=[w];for(;w.isWrapped&&S>0;)w=this.lines.get(--S),N.unshift(w);const L=this.ybase+this.y;if(L>=S&&L<S+N.length)continue;const R=N[N.length-1].getTrimmedLength(),j=(0,y.reflowSmallerGetNewLineLengths)(N,this._cols,h),$=j.length-N.length;let G;G=this.ybase===0&&this.y!==this.lines.length-1?Math.max(0,this.y-this.lines.maxLength+$):Math.max(0,this.lines.length-this.lines.maxLength+$);const F=[];for(let D=0;D<$;D++){const I=this.getBlankLine(b.DEFAULT_ATTR_DATA,!0);F.push(I)}F.length>0&&(E.push({start:S+N.length+_,newLines:F}),_+=F.length),N.push(...F);let W=j.length-1,V=j[W];V===0&&(W--,V=j[W]);let q=N.length-$-1,A=R;for(;q>=0;){const D=Math.min(A,V);if(N[W]===void 0)break;if(N[W].copyCellsFrom(N[q],A-D,V-D,D,!0),V-=D,V===0&&(W--,V=j[W]),A-=D,A===0){q--;const I=Math.max(q,0);A=(0,y.getWrappedLineTrimmedLength)(N,I,this._cols)}}for(let D=0;D<N.length;D++)j[D]<h&&N[D].setCell(j[D],x);let T=$-G;for(;T-- >0;)this.ybase===0?this.y<f-1?(this.y++,this.lines.pop()):(this.ybase++,this.ydisp++):this.ybase<Math.min(this.lines.maxLength,this.lines.length+_)-f&&(this.ybase===this.ydisp&&this.ydisp++,this.ybase++);this.savedY=Math.min(this.savedY+$,this.ybase+f-1)}if(E.length>0){const S=[],w=[];for(let W=0;W<this.lines.length;W++)w.push(this.lines.get(W));const N=this.lines.length;let L=N-1,R=0,j=E[R];this.lines.length=Math.min(this.lines.maxLength,this.lines.length+_);let $=0;for(let W=Math.min(this.lines.maxLength-1,N+_-1);W>=0;W--)if(j&&j.start>L+$){for(let V=j.newLines.length-1;V>=0;V--)this.lines.set(W--,j.newLines[V]);W++,S.push({index:L+1,amount:j.newLines.length}),$+=j.newLines.length,j=E[++R]}else this.lines.set(W,w[L--]);let G=0;for(let W=S.length-1;W>=0;W--)S[W].index+=G,this.lines.onInsertEmitter.fire(S[W]),G+=S[W].amount;const F=Math.max(0,N+_-this.lines.maxLength);F>0&&this.lines.onTrimEmitter.fire(F)}}translateBufferLineToString(h,f,x=0,E){const _=this.lines.get(h);return _?_.translateToString(f,x,E):""}getWrappedRangeForLine(h){let f=h,x=h;for(;f>0&&this.lines.get(f).isWrapped;)f--;for(;x+1<this.lines.length&&this.lines.get(x+1).isWrapped;)x++;return{first:f,last:x}}setupTabStops(h){for(h!=null?this.tabs[h]||(h=this.prevStop(h)):(this.tabs={},h=0);h<this._cols;h+=this._optionsService.rawOptions.tabStopWidth)this.tabs[h]=!0}prevStop(h){for(h==null&&(h=this.x);!this.tabs[--h]&&h>0;);return h>=this._cols?this._cols-1:h<0?0:h}nextStop(h){for(h==null&&(h=this.x);!this.tabs[++h]&&h<this._cols;);return h>=this._cols?this._cols-1:h<0?0:h}clearMarkers(h){this._isClearing=!0;for(let f=0;f<this.markers.length;f++)this.markers[f].line===h&&(this.markers[f].dispose(),this.markers.splice(f--,1));this._isClearing=!1}clearAllMarkers(){this._isClearing=!0;for(let h=0;h<this.markers.length;h++)this.markers[h].dispose(),this.markers.splice(h--,1);this._isClearing=!1}addMarker(h){const f=new g.Marker(h);return this.markers.push(f),f.register(this.lines.onTrim((x=>{f.line-=x,f.line<0&&f.dispose()}))),f.register(this.lines.onInsert((x=>{f.line>=x.index&&(f.line+=x.amount)}))),f.register(this.lines.onDelete((x=>{f.line>=x.index&&f.line<x.index+x.amount&&f.dispose(),f.line>x.index&&(f.line-=x.amount)}))),f.register(f.onDispose((()=>this._removeMarker(f)))),f}_removeMarker(h){this._isClearing||this.markers.splice(this.markers.indexOf(h),1)}}},8437:(d,a,o)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.BufferLine=a.DEFAULT_ATTR_DATA=void 0;const c=o(3734),u=o(511),p=o(643),b=o(482);a.DEFAULT_ATTR_DATA=Object.freeze(new c.AttributeData);let y=0;class k{constructor(g,m,h=!1){this.isWrapped=h,this._combined={},this._extendedAttrs={},this._data=new Uint32Array(3*g);const f=m||u.CellData.fromCharData([0,p.NULL_CELL_CHAR,p.NULL_CELL_WIDTH,p.NULL_CELL_CODE]);for(let x=0;x<g;++x)this.setCell(x,f);this.length=g}get(g){const m=this._data[3*g+0],h=2097151&m;return[this._data[3*g+1],2097152&m?this._combined[g]:h?(0,b.stringFromCodePoint)(h):"",m>>22,2097152&m?this._combined[g].charCodeAt(this._combined[g].length-1):h]}set(g,m){this._data[3*g+1]=m[p.CHAR_DATA_ATTR_INDEX],m[p.CHAR_DATA_CHAR_INDEX].length>1?(this._combined[g]=m[1],this._data[3*g+0]=2097152|g|m[p.CHAR_DATA_WIDTH_INDEX]<<22):this._data[3*g+0]=m[p.CHAR_DATA_CHAR_INDEX].charCodeAt(0)|m[p.CHAR_DATA_WIDTH_INDEX]<<22}getWidth(g){return this._data[3*g+0]>>22}hasWidth(g){return 12582912&this._data[3*g+0]}getFg(g){return this._data[3*g+1]}getBg(g){return this._data[3*g+2]}hasContent(g){return 4194303&this._data[3*g+0]}getCodePoint(g){const m=this._data[3*g+0];return 2097152&m?this._combined[g].charCodeAt(this._combined[g].length-1):2097151&m}isCombined(g){return 2097152&this._data[3*g+0]}getString(g){const m=this._data[3*g+0];return 2097152&m?this._combined[g]:2097151&m?(0,b.stringFromCodePoint)(2097151&m):""}isProtected(g){return 536870912&this._data[3*g+2]}loadCell(g,m){return y=3*g,m.content=this._data[y+0],m.fg=this._data[y+1],m.bg=this._data[y+2],2097152&m.content&&(m.combinedData=this._combined[g]),268435456&m.bg&&(m.extended=this._extendedAttrs[g]),m}setCell(g,m){2097152&m.content&&(this._combined[g]=m.combinedData),268435456&m.bg&&(this._extendedAttrs[g]=m.extended),this._data[3*g+0]=m.content,this._data[3*g+1]=m.fg,this._data[3*g+2]=m.bg}setCellFromCodepoint(g,m,h,f){268435456&f.bg&&(this._extendedAttrs[g]=f.extended),this._data[3*g+0]=m|h<<22,this._data[3*g+1]=f.fg,this._data[3*g+2]=f.bg}addCodepointToCell(g,m,h){let f=this._data[3*g+0];2097152&f?this._combined[g]+=(0,b.stringFromCodePoint)(m):2097151&f?(this._combined[g]=(0,b.stringFromCodePoint)(2097151&f)+(0,b.stringFromCodePoint)(m),f&=-2097152,f|=2097152):f=m|4194304,h&&(f&=-12582913,f|=h<<22),this._data[3*g+0]=f}insertCells(g,m,h){if((g%=this.length)&&this.getWidth(g-1)===2&&this.setCellFromCodepoint(g-1,0,1,h),m<this.length-g){const f=new u.CellData;for(let x=this.length-g-m-1;x>=0;--x)this.setCell(g+m+x,this.loadCell(g+x,f));for(let x=0;x<m;++x)this.setCell(g+x,h)}else for(let f=g;f<this.length;++f)this.setCell(f,h);this.getWidth(this.length-1)===2&&this.setCellFromCodepoint(this.length-1,0,1,h)}deleteCells(g,m,h){if(g%=this.length,m<this.length-g){const f=new u.CellData;for(let x=0;x<this.length-g-m;++x)this.setCell(g+x,this.loadCell(g+m+x,f));for(let x=this.length-m;x<this.length;++x)this.setCell(x,h)}else for(let f=g;f<this.length;++f)this.setCell(f,h);g&&this.getWidth(g-1)===2&&this.setCellFromCodepoint(g-1,0,1,h),this.getWidth(g)!==0||this.hasContent(g)||this.setCellFromCodepoint(g,0,1,h)}replaceCells(g,m,h,f=!1){if(f)for(g&&this.getWidth(g-1)===2&&!this.isProtected(g-1)&&this.setCellFromCodepoint(g-1,0,1,h),m<this.length&&this.getWidth(m-1)===2&&!this.isProtected(m)&&this.setCellFromCodepoint(m,0,1,h);g<m&&g<this.length;)this.isProtected(g)||this.setCell(g,h),g++;else for(g&&this.getWidth(g-1)===2&&this.setCellFromCodepoint(g-1,0,1,h),m<this.length&&this.getWidth(m-1)===2&&this.setCellFromCodepoint(m,0,1,h);g<m&&g<this.length;)this.setCell(g++,h)}resize(g,m){if(g===this.length)return 4*this._data.length*2<this._data.buffer.byteLength;const h=3*g;if(g>this.length){if(this._data.buffer.byteLength>=4*h)this._data=new Uint32Array(this._data.buffer,0,h);else{const f=new Uint32Array(h);f.set(this._data),this._data=f}for(let f=this.length;f<g;++f)this.setCell(f,m)}else{this._data=this._data.subarray(0,h);const f=Object.keys(this._combined);for(let E=0;E<f.length;E++){const _=parseInt(f[E],10);_>=g&&delete this._combined[_]}const x=Object.keys(this._extendedAttrs);for(let E=0;E<x.length;E++){const _=parseInt(x[E],10);_>=g&&delete this._extendedAttrs[_]}}return this.length=g,4*h*2<this._data.buffer.byteLength}cleanupMemory(){if(4*this._data.length*2<this._data.buffer.byteLength){const g=new Uint32Array(this._data.length);return g.set(this._data),this._data=g,1}return 0}fill(g,m=!1){if(m)for(let h=0;h<this.length;++h)this.isProtected(h)||this.setCell(h,g);else{this._combined={},this._extendedAttrs={};for(let h=0;h<this.length;++h)this.setCell(h,g)}}copyFrom(g){this.length!==g.length?this._data=new Uint32Array(g._data):this._data.set(g._data),this.length=g.length,this._combined={};for(const m in g._combined)this._combined[m]=g._combined[m];this._extendedAttrs={};for(const m in g._extendedAttrs)this._extendedAttrs[m]=g._extendedAttrs[m];this.isWrapped=g.isWrapped}clone(){const g=new k(0);g._data=new Uint32Array(this._data),g.length=this.length;for(const m in this._combined)g._combined[m]=this._combined[m];for(const m in this._extendedAttrs)g._extendedAttrs[m]=this._extendedAttrs[m];return g.isWrapped=this.isWrapped,g}getTrimmedLength(){for(let g=this.length-1;g>=0;--g)if(4194303&this._data[3*g+0])return g+(this._data[3*g+0]>>22);return 0}getNoBgTrimmedLength(){for(let g=this.length-1;g>=0;--g)if(4194303&this._data[3*g+0]||50331648&this._data[3*g+2])return g+(this._data[3*g+0]>>22);return 0}copyCellsFrom(g,m,h,f,x){const E=g._data;if(x)for(let S=f-1;S>=0;S--){for(let w=0;w<3;w++)this._data[3*(h+S)+w]=E[3*(m+S)+w];268435456&E[3*(m+S)+2]&&(this._extendedAttrs[h+S]=g._extendedAttrs[m+S])}else for(let S=0;S<f;S++){for(let w=0;w<3;w++)this._data[3*(h+S)+w]=E[3*(m+S)+w];268435456&E[3*(m+S)+2]&&(this._extendedAttrs[h+S]=g._extendedAttrs[m+S])}const _=Object.keys(g._combined);for(let S=0;S<_.length;S++){const w=parseInt(_[S],10);w>=m&&(this._combined[w-m+h]=g._combined[w])}}translateToString(g,m,h,f){m=m??0,h=h??this.length,g&&(h=Math.min(h,this.getTrimmedLength())),f&&(f.length=0);let x="";for(;m<h;){const E=this._data[3*m+0],_=2097151&E,S=2097152&E?this._combined[m]:_?(0,b.stringFromCodePoint)(_):p.WHITESPACE_CELL_CHAR;if(x+=S,f)for(let w=0;w<S.length;++w)f.push(m);m+=E>>22||1}return f&&f.push(m),x}}a.BufferLine=k},4841:(d,a)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.getRangeLength=void 0,a.getRangeLength=function(o,c){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 c*(o.end.y-o.start.y)+(o.end.x-o.start.x+1)}},4634:(d,a)=>{function o(c,u,p){if(u===c.length-1)return c[u].getTrimmedLength();const b=!c[u].hasContent(p-1)&&c[u].getWidth(p-1)===1,y=c[u+1].getWidth(0)===2;return b&&y?p-1:p}Object.defineProperty(a,"__esModule",{value:!0}),a.getWrappedLineTrimmedLength=a.reflowSmallerGetNewLineLengths=a.reflowLargerApplyNewLayout=a.reflowLargerCreateNewLayout=a.reflowLargerGetLinesToRemove=void 0,a.reflowLargerGetLinesToRemove=function(c,u,p,b,y){const k=[];for(let v=0;v<c.length-1;v++){let g=v,m=c.get(++g);if(!m.isWrapped)continue;const h=[c.get(v)];for(;g<c.length&&m.isWrapped;)h.push(m),m=c.get(++g);if(b>=v&&b<g){v+=h.length-1;continue}let f=0,x=o(h,f,u),E=1,_=0;for(;E<h.length;){const w=o(h,E,u),N=w-_,L=p-x,R=Math.min(N,L);h[f].copyCellsFrom(h[E],_,x,R,!1),x+=R,x===p&&(f++,x=0),_+=R,_===w&&(E++,_=0),x===0&&f!==0&&h[f-1].getWidth(p-1)===2&&(h[f].copyCellsFrom(h[f-1],p-1,x++,1,!1),h[f-1].setCell(p-1,y))}h[f].replaceCells(x,p,y);let S=0;for(let w=h.length-1;w>0&&(w>f||h[w].getTrimmedLength()===0);w--)S++;S>0&&(k.push(v+h.length-S),k.push(S)),v+=h.length-1}return k},a.reflowLargerCreateNewLayout=function(c,u){const p=[];let b=0,y=u[b],k=0;for(let v=0;v<c.length;v++)if(y===v){const g=u[++b];c.onDeleteEmitter.fire({index:v-k,amount:g}),v+=g-1,k+=g,y=u[++b]}else p.push(v);return{layout:p,countRemoved:k}},a.reflowLargerApplyNewLayout=function(c,u){const p=[];for(let b=0;b<u.length;b++)p.push(c.get(u[b]));for(let b=0;b<p.length;b++)c.set(b,p[b]);c.length=u.length},a.reflowSmallerGetNewLineLengths=function(c,u,p){const b=[],y=c.map(((m,h)=>o(c,h,u))).reduce(((m,h)=>m+h));let k=0,v=0,g=0;for(;g<y;){if(y-g<p){b.push(y-g);break}k+=p;const m=o(c,v,u);k>m&&(k-=m,v++);const h=c[v].getWidth(k-1)===2;h&&k--;const f=h?p-1:p;b.push(f),g+=f}return b},a.getWrappedLineTrimmedLength=o},5295:(d,a,o)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.BufferSet=void 0;const c=o(8460),u=o(844),p=o(9092);class b extends u.Disposable{constructor(k,v){super(),this._optionsService=k,this._bufferService=v,this._onBufferActivate=this.register(new c.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 p.Buffer(!0,this._optionsService,this._bufferService),this._normal.fillViewportRows(),this._alt=new p.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(k){this._activeBuffer!==this._alt&&(this._alt.fillViewportRows(k),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(k,v){this._normal.resize(k,v),this._alt.resize(k,v),this.setupTabStops(k)}setupTabStops(k){this._normal.setupTabStops(k),this._alt.setupTabStops(k)}}a.BufferSet=b},511:(d,a,o)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.CellData=void 0;const c=o(482),u=o(643),p=o(3734);class b extends p.AttributeData{constructor(){super(...arguments),this.content=0,this.fg=0,this.bg=0,this.extended=new p.ExtendedAttrs,this.combinedData=""}static fromCharData(k){const v=new b;return v.setFromCharData(k),v}isCombined(){return 2097152&this.content}getWidth(){return this.content>>22}getChars(){return 2097152&this.content?this.combinedData:2097151&this.content?(0,c.stringFromCodePoint)(2097151&this.content):""}getCode(){return this.isCombined()?this.combinedData.charCodeAt(this.combinedData.length-1):2097151&this.content}setFromCharData(k){this.fg=k[u.CHAR_DATA_ATTR_INDEX],this.bg=0;let v=!1;if(k[u.CHAR_DATA_CHAR_INDEX].length>2)v=!0;else if(k[u.CHAR_DATA_CHAR_INDEX].length===2){const g=k[u.CHAR_DATA_CHAR_INDEX].charCodeAt(0);if(55296<=g&&g<=56319){const m=k[u.CHAR_DATA_CHAR_INDEX].charCodeAt(1);56320<=m&&m<=57343?this.content=1024*(g-55296)+m-56320+65536|k[u.CHAR_DATA_WIDTH_INDEX]<<22:v=!0}else v=!0}else this.content=k[u.CHAR_DATA_CHAR_INDEX].charCodeAt(0)|k[u.CHAR_DATA_WIDTH_INDEX]<<22;v&&(this.combinedData=k[u.CHAR_DATA_CHAR_INDEX],this.content=2097152|k[u.CHAR_DATA_WIDTH_INDEX]<<22)}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}}a.CellData=b},643:(d,a)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.WHITESPACE_CELL_CODE=a.WHITESPACE_CELL_WIDTH=a.WHITESPACE_CELL_CHAR=a.NULL_CELL_CODE=a.NULL_CELL_WIDTH=a.NULL_CELL_CHAR=a.CHAR_DATA_CODE_INDEX=a.CHAR_DATA_WIDTH_INDEX=a.CHAR_DATA_CHAR_INDEX=a.CHAR_DATA_ATTR_INDEX=a.DEFAULT_EXT=a.DEFAULT_ATTR=a.DEFAULT_COLOR=void 0,a.DEFAULT_COLOR=0,a.DEFAULT_ATTR=256|a.DEFAULT_COLOR<<9,a.DEFAULT_EXT=0,a.CHAR_DATA_ATTR_INDEX=0,a.CHAR_DATA_CHAR_INDEX=1,a.CHAR_DATA_WIDTH_INDEX=2,a.CHAR_DATA_CODE_INDEX=3,a.NULL_CELL_CHAR="",a.NULL_CELL_WIDTH=1,a.NULL_CELL_CODE=0,a.WHITESPACE_CELL_CHAR=" ",a.WHITESPACE_CELL_WIDTH=1,a.WHITESPACE_CELL_CODE=32},4863:(d,a,o)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.Marker=void 0;const c=o(8460),u=o(844);class p{get id(){return this._id}constructor(y){this.line=y,this.isDisposed=!1,this._disposables=[],this._id=p._nextId++,this._onDispose=this.register(new c.EventEmitter),this.onDispose=this._onDispose.event}dispose(){this.isDisposed||(this.isDisposed=!0,this.line=-1,this._onDispose.fire(),(0,u.disposeArray)(this._disposables),this._disposables.length=0)}register(y){return this._disposables.push(y),y}}a.Marker=p,p._nextId=1},7116:(d,a)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.DEFAULT_CHARSET=a.CHARSETS=void 0,a.CHARSETS={},a.DEFAULT_CHARSET=a.CHARSETS.B,a.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:"≥","{":"π","|":"≠","}":"£","~":"·"},a.CHARSETS.A={"#":"£"},a.CHARSETS.B=void 0,a.CHARSETS[4]={"#":"£","@":"¾","[":"ij","\\":"½","]":"|","{":"¨","|":"f","}":"¼","~":"´"},a.CHARSETS.C=a.CHARSETS[5]={"[":"Ä","\\":"Ö","]":"Å","^":"Ü","`":"é","{":"ä","|":"ö","}":"å","~":"ü"},a.CHARSETS.R={"#":"£","@":"à","[":"°","\\":"ç","]":"§","{":"é","|":"ù","}":"è","~":"¨"},a.CHARSETS.Q={"@":"à","[":"â","\\":"ç","]":"ê","^":"î","`":"ô","{":"é","|":"ù","}":"è","~":"û"},a.CHARSETS.K={"@":"§","[":"Ä","\\":"Ö","]":"Ü","{":"ä","|":"ö","}":"ü","~":"ß"},a.CHARSETS.Y={"#":"£","@":"§","[":"°","\\":"ç","]":"é","`":"ù","{":"à","|":"ò","}":"è","~":"ì"},a.CHARSETS.E=a.CHARSETS[6]={"@":"Ä","[":"Æ","\\":"Ø","]":"Å","^":"Ü","`":"ä","{":"æ","|":"ø","}":"å","~":"ü"},a.CHARSETS.Z={"#":"£","@":"§","[":"¡","\\":"Ñ","]":"¿","{":"°","|":"ñ","}":"ç"},a.CHARSETS.H=a.CHARSETS[7]={"@":"É","[":"Ä","\\":"Ö","]":"Å","^":"Ü","`":"é","{":"ä","|":"ö","}":"å","~":"ü"},a.CHARSETS["="]={"#":"ù","@":"à","[":"é","\\":"ç","]":"ê","^":"î",_:"è","`":"ô","{":"ä","|":"ö","}":"ü","~":"û"}},2584:(d,a)=>{var o,c,u;Object.defineProperty(a,"__esModule",{value:!0}),a.C1_ESCAPED=a.C1=a.C0=void 0,(function(p){p.NUL="\0",p.SOH="",p.STX="",p.ETX="",p.EOT="",p.ENQ="",p.ACK="",p.BEL="\x07",p.BS="\b",p.HT=" ",p.LF=`
|
|
635
635
|
`,p.VT="\v",p.FF="\f",p.CR="\r",p.SO="",p.SI="",p.DLE="",p.DC1="",p.DC2="",p.DC3="",p.DC4="",p.NAK="",p.SYN="",p.ETB="",p.CAN="",p.EM="",p.SUB="",p.ESC="\x1B",p.FS="",p.GS="",p.RS="",p.US="",p.SP=" ",p.DEL=""})(o||(a.C0=o={})),(function(p){p.PAD="",p.HOP="",p.BPH="",p.NBH="",p.IND="",p.NEL="
",p.SSA="",p.ESA="",p.HTS="",p.HTJ="",p.VTS="",p.PLD="",p.PLU="",p.RI="",p.SS2="",p.SS3="",p.DCS="",p.PU1="",p.PU2="",p.STS="",p.CCH="",p.MW="",p.SPA="",p.EPA="",p.SOS="",p.SGCI="",p.SCI="",p.CSI="",p.ST="",p.OSC="",p.PM="",p.APC=""})(c||(a.C1=c={})),(function(p){p.ST=`${o.ESC}\\`})(u||(a.C1_ESCAPED=u={}))},7399:(d,a,o)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.evaluateKeyboardEvent=void 0;const c=o(2584),u={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:["'",'"']};a.evaluateKeyboardEvent=function(p,b,y,k){const v={type:0,cancel:!1,key:void 0},g=(p.shiftKey?1:0)|(p.altKey?2:0)|(p.ctrlKey?4:0)|(p.metaKey?8:0);switch(p.keyCode){case 0:p.key==="UIKeyInputUpArrow"?v.key=b?c.C0.ESC+"OA":c.C0.ESC+"[A":p.key==="UIKeyInputLeftArrow"?v.key=b?c.C0.ESC+"OD":c.C0.ESC+"[D":p.key==="UIKeyInputRightArrow"?v.key=b?c.C0.ESC+"OC":c.C0.ESC+"[C":p.key==="UIKeyInputDownArrow"&&(v.key=b?c.C0.ESC+"OB":c.C0.ESC+"[B");break;case 8:v.key=p.ctrlKey?"\b":c.C0.DEL,p.altKey&&(v.key=c.C0.ESC+v.key);break;case 9:if(p.shiftKey){v.key=c.C0.ESC+"[Z";break}v.key=c.C0.HT,v.cancel=!0;break;case 13:v.key=p.altKey?c.C0.ESC+c.C0.CR:c.C0.CR,v.cancel=!0;break;case 27:v.key=c.C0.ESC,p.altKey&&(v.key=c.C0.ESC+c.C0.ESC),v.cancel=!0;break;case 37:if(p.metaKey)break;g?(v.key=c.C0.ESC+"[1;"+(g+1)+"D",v.key===c.C0.ESC+"[1;3D"&&(v.key=c.C0.ESC+(y?"b":"[1;5D"))):v.key=b?c.C0.ESC+"OD":c.C0.ESC+"[D";break;case 39:if(p.metaKey)break;g?(v.key=c.C0.ESC+"[1;"+(g+1)+"C",v.key===c.C0.ESC+"[1;3C"&&(v.key=c.C0.ESC+(y?"f":"[1;5C"))):v.key=b?c.C0.ESC+"OC":c.C0.ESC+"[C";break;case 38:if(p.metaKey)break;g?(v.key=c.C0.ESC+"[1;"+(g+1)+"A",y||v.key!==c.C0.ESC+"[1;3A"||(v.key=c.C0.ESC+"[1;5A")):v.key=b?c.C0.ESC+"OA":c.C0.ESC+"[A";break;case 40:if(p.metaKey)break;g?(v.key=c.C0.ESC+"[1;"+(g+1)+"B",y||v.key!==c.C0.ESC+"[1;3B"||(v.key=c.C0.ESC+"[1;5B")):v.key=b?c.C0.ESC+"OB":c.C0.ESC+"[B";break;case 45:p.shiftKey||p.ctrlKey||(v.key=c.C0.ESC+"[2~");break;case 46:v.key=g?c.C0.ESC+"[3;"+(g+1)+"~":c.C0.ESC+"[3~";break;case 36:v.key=g?c.C0.ESC+"[1;"+(g+1)+"H":b?c.C0.ESC+"OH":c.C0.ESC+"[H";break;case 35:v.key=g?c.C0.ESC+"[1;"+(g+1)+"F":b?c.C0.ESC+"OF":c.C0.ESC+"[F";break;case 33:p.shiftKey?v.type=2:p.ctrlKey?v.key=c.C0.ESC+"[5;"+(g+1)+"~":v.key=c.C0.ESC+"[5~";break;case 34:p.shiftKey?v.type=3:p.ctrlKey?v.key=c.C0.ESC+"[6;"+(g+1)+"~":v.key=c.C0.ESC+"[6~";break;case 112:v.key=g?c.C0.ESC+"[1;"+(g+1)+"P":c.C0.ESC+"OP";break;case 113:v.key=g?c.C0.ESC+"[1;"+(g+1)+"Q":c.C0.ESC+"OQ";break;case 114:v.key=g?c.C0.ESC+"[1;"+(g+1)+"R":c.C0.ESC+"OR";break;case 115:v.key=g?c.C0.ESC+"[1;"+(g+1)+"S":c.C0.ESC+"OS";break;case 116:v.key=g?c.C0.ESC+"[15;"+(g+1)+"~":c.C0.ESC+"[15~";break;case 117:v.key=g?c.C0.ESC+"[17;"+(g+1)+"~":c.C0.ESC+"[17~";break;case 118:v.key=g?c.C0.ESC+"[18;"+(g+1)+"~":c.C0.ESC+"[18~";break;case 119:v.key=g?c.C0.ESC+"[19;"+(g+1)+"~":c.C0.ESC+"[19~";break;case 120:v.key=g?c.C0.ESC+"[20;"+(g+1)+"~":c.C0.ESC+"[20~";break;case 121:v.key=g?c.C0.ESC+"[21;"+(g+1)+"~":c.C0.ESC+"[21~";break;case 122:v.key=g?c.C0.ESC+"[23;"+(g+1)+"~":c.C0.ESC+"[23~";break;case 123:v.key=g?c.C0.ESC+"[24;"+(g+1)+"~":c.C0.ESC+"[24~";break;default:if(!p.ctrlKey||p.shiftKey||p.altKey||p.metaKey)if(y&&!k||!p.altKey||p.metaKey)!y||p.altKey||p.ctrlKey||p.shiftKey||!p.metaKey?p.key&&!p.ctrlKey&&!p.altKey&&!p.metaKey&&p.keyCode>=48&&p.key.length===1?v.key=p.key:p.key&&p.ctrlKey&&(p.key==="_"&&(v.key=c.C0.US),p.key==="@"&&(v.key=c.C0.NUL)):p.keyCode===65&&(v.type=1);else{const m=u[p.keyCode],h=m==null?void 0:m[p.shiftKey?1:0];if(h)v.key=c.C0.ESC+h;else if(p.keyCode>=65&&p.keyCode<=90){const f=p.ctrlKey?p.keyCode-64:p.keyCode+32;let x=String.fromCharCode(f);p.shiftKey&&(x=x.toUpperCase()),v.key=c.C0.ESC+x}else if(p.keyCode===32)v.key=c.C0.ESC+(p.ctrlKey?c.C0.NUL:" ");else if(p.key==="Dead"&&p.code.startsWith("Key")){let f=p.code.slice(3,4);p.shiftKey||(f=f.toLowerCase()),v.key=c.C0.ESC+f,v.cancel=!0}}else p.keyCode>=65&&p.keyCode<=90?v.key=String.fromCharCode(p.keyCode-64):p.keyCode===32?v.key=c.C0.NUL:p.keyCode>=51&&p.keyCode<=55?v.key=String.fromCharCode(p.keyCode-51+27):p.keyCode===56?v.key=c.C0.DEL:p.keyCode===219?v.key=c.C0.ESC:p.keyCode===220?v.key=c.C0.FS:p.keyCode===221&&(v.key=c.C0.GS)}return v}},482:(d,a)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.Utf8ToUtf32=a.StringToUtf32=a.utf32ToString=a.stringFromCodePoint=void 0,a.stringFromCodePoint=function(o){return o>65535?(o-=65536,String.fromCharCode(55296+(o>>10))+String.fromCharCode(o%1024+56320)):String.fromCharCode(o)},a.utf32ToString=function(o,c=0,u=o.length){let p="";for(let b=c;b<u;++b){let y=o[b];y>65535?(y-=65536,p+=String.fromCharCode(55296+(y>>10))+String.fromCharCode(y%1024+56320)):p+=String.fromCharCode(y)}return p},a.StringToUtf32=class{constructor(){this._interim=0}clear(){this._interim=0}decode(o,c){const u=o.length;if(!u)return 0;let p=0,b=0;if(this._interim){const y=o.charCodeAt(b++);56320<=y&&y<=57343?c[p++]=1024*(this._interim-55296)+y-56320+65536:(c[p++]=this._interim,c[p++]=y),this._interim=0}for(let y=b;y<u;++y){const k=o.charCodeAt(y);if(55296<=k&&k<=56319){if(++y>=u)return this._interim=k,p;const v=o.charCodeAt(y);56320<=v&&v<=57343?c[p++]=1024*(k-55296)+v-56320+65536:(c[p++]=k,c[p++]=v)}else k!==65279&&(c[p++]=k)}return p}},a.Utf8ToUtf32=class{constructor(){this.interim=new Uint8Array(3)}clear(){this.interim.fill(0)}decode(o,c){const u=o.length;if(!u)return 0;let p,b,y,k,v=0,g=0,m=0;if(this.interim[0]){let x=!1,E=this.interim[0];E&=(224&E)==192?31:(240&E)==224?15:7;let _,S=0;for(;(_=63&this.interim[++S])&&S<4;)E<<=6,E|=_;const w=(224&this.interim[0])==192?2:(240&this.interim[0])==224?3:4,N=w-S;for(;m<N;){if(m>=u)return 0;if(_=o[m++],(192&_)!=128){m--,x=!0;break}this.interim[S++]=_,E<<=6,E|=63&_}x||(w===2?E<128?m--:c[v++]=E:w===3?E<2048||E>=55296&&E<=57343||E===65279||(c[v++]=E):E<65536||E>1114111||(c[v++]=E)),this.interim.fill(0)}const h=u-4;let f=m;for(;f<u;){for(;!(!(f<h)||128&(p=o[f])||128&(b=o[f+1])||128&(y=o[f+2])||128&(k=o[f+3]));)c[v++]=p,c[v++]=b,c[v++]=y,c[v++]=k,f+=4;if(p=o[f++],p<128)c[v++]=p;else if((224&p)==192){if(f>=u)return this.interim[0]=p,v;if(b=o[f++],(192&b)!=128){f--;continue}if(g=(31&p)<<6|63&b,g<128){f--;continue}c[v++]=g}else if((240&p)==224){if(f>=u)return this.interim[0]=p,v;if(b=o[f++],(192&b)!=128){f--;continue}if(f>=u)return this.interim[0]=p,this.interim[1]=b,v;if(y=o[f++],(192&y)!=128){f--;continue}if(g=(15&p)<<12|(63&b)<<6|63&y,g<2048||g>=55296&&g<=57343||g===65279)continue;c[v++]=g}else if((248&p)==240){if(f>=u)return this.interim[0]=p,v;if(b=o[f++],(192&b)!=128){f--;continue}if(f>=u)return this.interim[0]=p,this.interim[1]=b,v;if(y=o[f++],(192&y)!=128){f--;continue}if(f>=u)return this.interim[0]=p,this.interim[1]=b,this.interim[2]=y,v;if(k=o[f++],(192&k)!=128){f--;continue}if(g=(7&p)<<18|(63&b)<<12|(63&y)<<6|63&k,g<65536||g>1114111)continue;c[v++]=g}}return v}}},225:(d,a,o)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.UnicodeV6=void 0;const c=o(1480),u=[[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]],p=[[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 b;a.UnicodeV6=class{constructor(){if(this.version="6",!b){b=new Uint8Array(65536),b.fill(1),b[0]=0,b.fill(0,1,32),b.fill(0,127,160),b.fill(2,4352,4448),b[9001]=2,b[9002]=2,b.fill(2,11904,42192),b[12351]=1,b.fill(2,44032,55204),b.fill(2,63744,64256),b.fill(2,65040,65050),b.fill(2,65072,65136),b.fill(2,65280,65377),b.fill(2,65504,65511);for(let y=0;y<u.length;++y)b.fill(0,u[y][0],u[y][1]+1)}}wcwidth(y){return y<32?0:y<127?1:y<65536?b[y]:(function(k,v){let g,m=0,h=v.length-1;if(k<v[0][0]||k>v[h][1])return!1;for(;h>=m;)if(g=m+h>>1,k>v[g][1])m=g+1;else{if(!(k<v[g][0]))return!0;h=g-1}return!1})(y,p)?0:y>=131072&&y<=196605||y>=196608&&y<=262141?2:1}charProperties(y,k){let v=this.wcwidth(y),g=v===0&&k!==0;if(g){const m=c.UnicodeService.extractWidth(k);m===0?g=!1:m>v&&(v=m)}return c.UnicodeService.createPropertyValue(0,v,g)}}},5981:(d,a,o)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.WriteBuffer=void 0;const c=o(8460),u=o(844);class p extends u.Disposable{constructor(y){super(),this._action=y,this._writeBuffer=[],this._callbacks=[],this._pendingData=0,this._bufferOffset=0,this._isSyncWriting=!1,this._syncCalls=0,this._didUserInput=!1,this._onWriteParsed=this.register(new c.EventEmitter),this.onWriteParsed=this._onWriteParsed.event}handleUserInput(){this._didUserInput=!0}writeSync(y,k){if(k!==void 0&&this._syncCalls>k)return void(this._syncCalls=0);if(this._pendingData+=y.length,this._writeBuffer.push(y),this._callbacks.push(void 0),this._syncCalls++,this._isSyncWriting)return;let v;for(this._isSyncWriting=!0;v=this._writeBuffer.shift();){this._action(v);const g=this._callbacks.shift();g&&g()}this._pendingData=0,this._bufferOffset=2147483647,this._isSyncWriting=!1,this._syncCalls=0}write(y,k){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+=y.length,this._writeBuffer.push(y),this._callbacks.push(k),void this._innerWrite();setTimeout((()=>this._innerWrite()))}this._pendingData+=y.length,this._writeBuffer.push(y),this._callbacks.push(k)}_innerWrite(y=0,k=!0){const v=y||Date.now();for(;this._writeBuffer.length>this._bufferOffset;){const g=this._writeBuffer[this._bufferOffset],m=this._action(g,k);if(m){const f=x=>Date.now()-v>=12?setTimeout((()=>this._innerWrite(0,x))):this._innerWrite(v,x);return void m.catch((x=>(queueMicrotask((()=>{throw x})),Promise.resolve(!1)))).then(f)}const h=this._callbacks[this._bufferOffset];if(h&&h(),this._bufferOffset++,this._pendingData-=g.length,Date.now()-v>=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()}}a.WriteBuffer=p},5941:(d,a)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.toRgbString=a.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})$/,c=/^[\da-f]+$/;function u(p,b){const y=p.toString(16),k=y.length<2?"0"+y:y;switch(b){case 4:return y[0];case 8:return k;case 12:return(k+k).slice(0,3);default:return k+k}}a.parseColor=function(p){if(!p)return;let b=p.toLowerCase();if(b.indexOf("rgb:")===0){b=b.slice(4);const y=o.exec(b);if(y){const k=y[1]?15:y[4]?255:y[7]?4095:65535;return[Math.round(parseInt(y[1]||y[4]||y[7]||y[10],16)/k*255),Math.round(parseInt(y[2]||y[5]||y[8]||y[11],16)/k*255),Math.round(parseInt(y[3]||y[6]||y[9]||y[12],16)/k*255)]}}else if(b.indexOf("#")===0&&(b=b.slice(1),c.exec(b)&&[3,6,9,12].includes(b.length))){const y=b.length/3,k=[0,0,0];for(let v=0;v<3;++v){const g=parseInt(b.slice(y*v,y*v+y),16);k[v]=y===1?g<<4:y===2?g:y===3?g>>4:g>>8}return k}},a.toRgbString=function(p,b=16){const[y,k,v]=p;return`rgb:${u(y,b)}/${u(k,b)}/${u(v,b)}`}},5770:(d,a)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.PAYLOAD_LIMIT=void 0,a.PAYLOAD_LIMIT=1e7},6351:(d,a,o)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.DcsHandler=a.DcsParser=void 0;const c=o(482),u=o(8742),p=o(5770),b=[];a.DcsParser=class{constructor(){this._handlers=Object.create(null),this._active=b,this._ident=0,this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=b}registerHandler(k,v){this._handlers[k]===void 0&&(this._handlers[k]=[]);const g=this._handlers[k];return g.push(v),{dispose:()=>{const m=g.indexOf(v);m!==-1&&g.splice(m,1)}}}clearHandler(k){this._handlers[k]&&delete this._handlers[k]}setHandlerFallback(k){this._handlerFb=k}reset(){if(this._active.length)for(let k=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;k>=0;--k)this._active[k].unhook(!1);this._stack.paused=!1,this._active=b,this._ident=0}hook(k,v){if(this.reset(),this._ident=k,this._active=this._handlers[k]||b,this._active.length)for(let g=this._active.length-1;g>=0;g--)this._active[g].hook(v);else this._handlerFb(this._ident,"HOOK",v)}put(k,v,g){if(this._active.length)for(let m=this._active.length-1;m>=0;m--)this._active[m].put(k,v,g);else this._handlerFb(this._ident,"PUT",(0,c.utf32ToString)(k,v,g))}unhook(k,v=!0){if(this._active.length){let g=!1,m=this._active.length-1,h=!1;if(this._stack.paused&&(m=this._stack.loopPosition-1,g=v,h=this._stack.fallThrough,this._stack.paused=!1),!h&&g===!1){for(;m>=0&&(g=this._active[m].unhook(k),g!==!0);m--)if(g instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=m,this._stack.fallThrough=!1,g;m--}for(;m>=0;m--)if(g=this._active[m].unhook(!1),g instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=m,this._stack.fallThrough=!0,g}else this._handlerFb(this._ident,"UNHOOK",k);this._active=b,this._ident=0}};const y=new u.Params;y.addParam(0),a.DcsHandler=class{constructor(k){this._handler=k,this._data="",this._params=y,this._hitLimit=!1}hook(k){this._params=k.length>1||k.params[0]?k.clone():y,this._data="",this._hitLimit=!1}put(k,v,g){this._hitLimit||(this._data+=(0,c.utf32ToString)(k,v,g),this._data.length>p.PAYLOAD_LIMIT&&(this._data="",this._hitLimit=!0))}unhook(k){let v=!1;if(this._hitLimit)v=!1;else if(k&&(v=this._handler(this._data,this._params),v instanceof Promise))return v.then((g=>(this._params=y,this._data="",this._hitLimit=!1,g)));return this._params=y,this._data="",this._hitLimit=!1,v}}},2015:(d,a,o)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.EscapeSequenceParser=a.VT500_TRANSITION_TABLE=a.TransitionTable=void 0;const c=o(844),u=o(8742),p=o(6242),b=o(6351);class y{constructor(m){this.table=new Uint8Array(m)}setDefault(m,h){this.table.fill(m<<4|h)}add(m,h,f,x){this.table[h<<8|m]=f<<4|x}addMany(m,h,f,x){for(let E=0;E<m.length;E++)this.table[h<<8|m[E]]=f<<4|x}}a.TransitionTable=y;const k=160;a.VT500_TRANSITION_TABLE=(function(){const g=new y(4095),m=Array.apply(null,Array(256)).map(((S,w)=>w)),h=(S,w)=>m.slice(S,w),f=h(32,127),x=h(0,24);x.push(25),x.push.apply(x,h(28,32));const E=h(0,14);let _;for(_ in g.setDefault(1,0),g.addMany(f,0,2,0),E)g.addMany([24,26,153,154],_,3,0),g.addMany(h(128,144),_,3,0),g.addMany(h(144,152),_,3,0),g.add(156,_,0,0),g.add(27,_,11,1),g.add(157,_,4,8),g.addMany([152,158,159],_,0,7),g.add(155,_,11,3),g.add(144,_,11,9);return g.addMany(x,0,3,0),g.addMany(x,1,3,1),g.add(127,1,0,1),g.addMany(x,8,0,8),g.addMany(x,3,3,3),g.add(127,3,0,3),g.addMany(x,4,3,4),g.add(127,4,0,4),g.addMany(x,6,3,6),g.addMany(x,5,3,5),g.add(127,5,0,5),g.addMany(x,2,3,2),g.add(127,2,0,2),g.add(93,1,4,8),g.addMany(f,8,5,8),g.add(127,8,5,8),g.addMany([156,27,24,26,7],8,6,0),g.addMany(h(28,32),8,0,8),g.addMany([88,94,95],1,0,7),g.addMany(f,7,0,7),g.addMany(x,7,0,7),g.add(156,7,0,0),g.add(127,7,0,7),g.add(91,1,11,3),g.addMany(h(64,127),3,7,0),g.addMany(h(48,60),3,8,4),g.addMany([60,61,62,63],3,9,4),g.addMany(h(48,60),4,8,4),g.addMany(h(64,127),4,7,0),g.addMany([60,61,62,63],4,0,6),g.addMany(h(32,64),6,0,6),g.add(127,6,0,6),g.addMany(h(64,127),6,0,0),g.addMany(h(32,48),3,9,5),g.addMany(h(32,48),5,9,5),g.addMany(h(48,64),5,0,6),g.addMany(h(64,127),5,7,0),g.addMany(h(32,48),4,9,5),g.addMany(h(32,48),1,9,2),g.addMany(h(32,48),2,9,2),g.addMany(h(48,127),2,10,0),g.addMany(h(48,80),1,10,0),g.addMany(h(81,88),1,10,0),g.addMany([89,90,92],1,10,0),g.addMany(h(96,127),1,10,0),g.add(80,1,11,9),g.addMany(x,9,0,9),g.add(127,9,0,9),g.addMany(h(28,32),9,0,9),g.addMany(h(32,48),9,9,12),g.addMany(h(48,60),9,8,10),g.addMany([60,61,62,63],9,9,10),g.addMany(x,11,0,11),g.addMany(h(32,128),11,0,11),g.addMany(h(28,32),11,0,11),g.addMany(x,10,0,10),g.add(127,10,0,10),g.addMany(h(28,32),10,0,10),g.addMany(h(48,60),10,8,10),g.addMany([60,61,62,63],10,0,11),g.addMany(h(32,48),10,9,12),g.addMany(x,12,0,12),g.add(127,12,0,12),g.addMany(h(28,32),12,0,12),g.addMany(h(32,48),12,9,12),g.addMany(h(48,64),12,0,11),g.addMany(h(64,127),12,12,13),g.addMany(h(64,127),10,12,13),g.addMany(h(64,127),9,12,13),g.addMany(x,13,13,13),g.addMany(f,13,13,13),g.add(127,13,0,13),g.addMany([27,156,24,26],13,14,0),g.add(k,0,2,0),g.add(k,8,5,8),g.add(k,6,0,6),g.add(k,11,0,11),g.add(k,13,13,13),g})();class v extends c.Disposable{constructor(m=a.VT500_TRANSITION_TABLE){super(),this._transitions=m,this._parseStack={state:0,handlers:[],handlerPos:0,transition:0,chunkPos:0},this.initialState=0,this.currentState=this.initialState,this._params=new u.Params,this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._printHandlerFb=(h,f,x)=>{},this._executeHandlerFb=h=>{},this._csiHandlerFb=(h,f)=>{},this._escHandlerFb=h=>{},this._errorHandlerFb=h=>h,this._printHandler=this._printHandlerFb,this._executeHandlers=Object.create(null),this._csiHandlers=Object.create(null),this._escHandlers=Object.create(null),this.register((0,c.toDisposable)((()=>{this._csiHandlers=Object.create(null),this._executeHandlers=Object.create(null),this._escHandlers=Object.create(null)}))),this._oscParser=this.register(new p.OscParser),this._dcsParser=this.register(new b.DcsParser),this._errorHandler=this._errorHandlerFb,this.registerEscHandler({final:"\\"},(()=>!0))}_identifier(m,h=[64,126]){let f=0;if(m.prefix){if(m.prefix.length>1)throw new Error("only one byte as prefix supported");if(f=m.prefix.charCodeAt(0),f&&60>f||f>63)throw new Error("prefix must be in range 0x3c .. 0x3f")}if(m.intermediates){if(m.intermediates.length>2)throw new Error("only two bytes as intermediates are supported");for(let E=0;E<m.intermediates.length;++E){const _=m.intermediates.charCodeAt(E);if(32>_||_>47)throw new Error("intermediate must be in range 0x20 .. 0x2f");f<<=8,f|=_}}if(m.final.length!==1)throw new Error("final must be a single byte");const x=m.final.charCodeAt(0);if(h[0]>x||x>h[1])throw new Error(`final must be in range ${h[0]} .. ${h[1]}`);return f<<=8,f|=x,f}identToString(m){const h=[];for(;m;)h.push(String.fromCharCode(255&m)),m>>=8;return h.reverse().join("")}setPrintHandler(m){this._printHandler=m}clearPrintHandler(){this._printHandler=this._printHandlerFb}registerEscHandler(m,h){const f=this._identifier(m,[48,126]);this._escHandlers[f]===void 0&&(this._escHandlers[f]=[]);const x=this._escHandlers[f];return x.push(h),{dispose:()=>{const E=x.indexOf(h);E!==-1&&x.splice(E,1)}}}clearEscHandler(m){this._escHandlers[this._identifier(m,[48,126])]&&delete this._escHandlers[this._identifier(m,[48,126])]}setEscHandlerFallback(m){this._escHandlerFb=m}setExecuteHandler(m,h){this._executeHandlers[m.charCodeAt(0)]=h}clearExecuteHandler(m){this._executeHandlers[m.charCodeAt(0)]&&delete this._executeHandlers[m.charCodeAt(0)]}setExecuteHandlerFallback(m){this._executeHandlerFb=m}registerCsiHandler(m,h){const f=this._identifier(m);this._csiHandlers[f]===void 0&&(this._csiHandlers[f]=[]);const x=this._csiHandlers[f];return x.push(h),{dispose:()=>{const E=x.indexOf(h);E!==-1&&x.splice(E,1)}}}clearCsiHandler(m){this._csiHandlers[this._identifier(m)]&&delete this._csiHandlers[this._identifier(m)]}setCsiHandlerFallback(m){this._csiHandlerFb=m}registerDcsHandler(m,h){return this._dcsParser.registerHandler(this._identifier(m),h)}clearDcsHandler(m){this._dcsParser.clearHandler(this._identifier(m))}setDcsHandlerFallback(m){this._dcsParser.setHandlerFallback(m)}registerOscHandler(m,h){return this._oscParser.registerHandler(m,h)}clearOscHandler(m){this._oscParser.clearHandler(m)}setOscHandlerFallback(m){this._oscParser.setHandlerFallback(m)}setErrorHandler(m){this._errorHandler=m}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(m,h,f,x,E){this._parseStack.state=m,this._parseStack.handlers=h,this._parseStack.handlerPos=f,this._parseStack.transition=x,this._parseStack.chunkPos=E}parse(m,h,f){let x,E=0,_=0,S=0;if(this._parseStack.state)if(this._parseStack.state===2)this._parseStack.state=0,S=this._parseStack.chunkPos+1;else{if(f===void 0||this._parseStack.state===1)throw this._parseStack.state=1,new Error("improper continuation due to previous async handler, giving up parsing");const w=this._parseStack.handlers;let N=this._parseStack.handlerPos-1;switch(this._parseStack.state){case 3:if(f===!1&&N>-1){for(;N>=0&&(x=w[N](this._params),x!==!0);N--)if(x instanceof Promise)return this._parseStack.handlerPos=N,x}this._parseStack.handlers=[];break;case 4:if(f===!1&&N>-1){for(;N>=0&&(x=w[N](),x!==!0);N--)if(x instanceof Promise)return this._parseStack.handlerPos=N,x}this._parseStack.handlers=[];break;case 6:if(E=m[this._parseStack.chunkPos],x=this._dcsParser.unhook(E!==24&&E!==26,f),x)return x;E===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0;break;case 5:if(E=m[this._parseStack.chunkPos],x=this._oscParser.end(E!==24&&E!==26,f),x)return x;E===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0}this._parseStack.state=0,S=this._parseStack.chunkPos+1,this.precedingJoinState=0,this.currentState=15&this._parseStack.transition}for(let w=S;w<h;++w){switch(E=m[w],_=this._transitions.table[this.currentState<<8|(E<160?E:k)],_>>4){case 2:for(let $=w+1;;++$){if($>=h||(E=m[$])<32||E>126&&E<k){this._printHandler(m,w,$),w=$-1;break}if(++$>=h||(E=m[$])<32||E>126&&E<k){this._printHandler(m,w,$),w=$-1;break}if(++$>=h||(E=m[$])<32||E>126&&E<k){this._printHandler(m,w,$),w=$-1;break}if(++$>=h||(E=m[$])<32||E>126&&E<k){this._printHandler(m,w,$),w=$-1;break}}break;case 3:this._executeHandlers[E]?this._executeHandlers[E]():this._executeHandlerFb(E),this.precedingJoinState=0;break;case 0:break;case 1:if(this._errorHandler({position:w,code:E,currentState:this.currentState,collect:this._collect,params:this._params,abort:!1}).abort)return;break;case 7:const N=this._csiHandlers[this._collect<<8|E];let L=N?N.length-1:-1;for(;L>=0&&(x=N[L](this._params),x!==!0);L--)if(x instanceof Promise)return this._preserveStack(3,N,L,_,w),x;L<0&&this._csiHandlerFb(this._collect<<8|E,this._params),this.precedingJoinState=0;break;case 8:do switch(E){case 59:this._params.addParam(0);break;case 58:this._params.addSubParam(-1);break;default:this._params.addDigit(E-48)}while(++w<h&&(E=m[w])>47&&E<60);w--;break;case 9:this._collect<<=8,this._collect|=E;break;case 10:const R=this._escHandlers[this._collect<<8|E];let j=R?R.length-1:-1;for(;j>=0&&(x=R[j](),x!==!0);j--)if(x instanceof Promise)return this._preserveStack(4,R,j,_,w),x;j<0&&this._escHandlerFb(this._collect<<8|E),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|E,this._params);break;case 13:for(let $=w+1;;++$)if($>=h||(E=m[$])===24||E===26||E===27||E>127&&E<k){this._dcsParser.put(m,w,$),w=$-1;break}break;case 14:if(x=this._dcsParser.unhook(E!==24&&E!==26),x)return this._preserveStack(6,[],0,_,w),x;E===27&&(_|=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 $=w+1;;$++)if($>=h||(E=m[$])<32||E>127&&E<k){this._oscParser.put(m,w,$),w=$-1;break}break;case 6:if(x=this._oscParser.end(E!==24&&E!==26),x)return this._preserveStack(5,[],0,_,w),x;E===27&&(_|=1),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0}this.currentState=15&_}}}a.EscapeSequenceParser=v},6242:(d,a,o)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.OscHandler=a.OscParser=void 0;const c=o(5770),u=o(482),p=[];a.OscParser=class{constructor(){this._state=0,this._active=p,this._id=-1,this._handlers=Object.create(null),this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}registerHandler(b,y){this._handlers[b]===void 0&&(this._handlers[b]=[]);const k=this._handlers[b];return k.push(y),{dispose:()=>{const v=k.indexOf(y);v!==-1&&k.splice(v,1)}}}clearHandler(b){this._handlers[b]&&delete this._handlers[b]}setHandlerFallback(b){this._handlerFb=b}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=p}reset(){if(this._state===2)for(let b=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;b>=0;--b)this._active[b].end(!1);this._stack.paused=!1,this._active=p,this._id=-1,this._state=0}_start(){if(this._active=this._handlers[this._id]||p,this._active.length)for(let b=this._active.length-1;b>=0;b--)this._active[b].start();else this._handlerFb(this._id,"START")}_put(b,y,k){if(this._active.length)for(let v=this._active.length-1;v>=0;v--)this._active[v].put(b,y,k);else this._handlerFb(this._id,"PUT",(0,u.utf32ToString)(b,y,k))}start(){this.reset(),this._state=1}put(b,y,k){if(this._state!==3){if(this._state===1)for(;y<k;){const v=b[y++];if(v===59){this._state=2,this._start();break}if(v<48||57<v)return void(this._state=3);this._id===-1&&(this._id=0),this._id=10*this._id+v-48}this._state===2&&k-y>0&&this._put(b,y,k)}}end(b,y=!0){if(this._state!==0){if(this._state!==3)if(this._state===1&&this._start(),this._active.length){let k=!1,v=this._active.length-1,g=!1;if(this._stack.paused&&(v=this._stack.loopPosition-1,k=y,g=this._stack.fallThrough,this._stack.paused=!1),!g&&k===!1){for(;v>=0&&(k=this._active[v].end(b),k!==!0);v--)if(k instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=v,this._stack.fallThrough=!1,k;v--}for(;v>=0;v--)if(k=this._active[v].end(!1),k instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=v,this._stack.fallThrough=!0,k}else this._handlerFb(this._id,"END",b);this._active=p,this._id=-1,this._state=0}}},a.OscHandler=class{constructor(b){this._handler=b,this._data="",this._hitLimit=!1}start(){this._data="",this._hitLimit=!1}put(b,y,k){this._hitLimit||(this._data+=(0,u.utf32ToString)(b,y,k),this._data.length>c.PAYLOAD_LIMIT&&(this._data="",this._hitLimit=!0))}end(b){let y=!1;if(this._hitLimit)y=!1;else if(b&&(y=this._handler(this._data),y instanceof Promise))return y.then((k=>(this._data="",this._hitLimit=!1,k)));return this._data="",this._hitLimit=!1,y}}},8742:(d,a)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.Params=void 0;const o=2147483647;class c{static fromArray(p){const b=new c;if(!p.length)return b;for(let y=Array.isArray(p[0])?1:0;y<p.length;++y){const k=p[y];if(Array.isArray(k))for(let v=0;v<k.length;++v)b.addSubParam(k[v]);else b.addParam(k)}return b}constructor(p=32,b=32){if(this.maxLength=p,this.maxSubParamsLength=b,b>256)throw new Error("maxSubParamsLength must not be greater than 256");this.params=new Int32Array(p),this.length=0,this._subParams=new Int32Array(b),this._subParamsLength=0,this._subParamsIdx=new Uint16Array(p),this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}clone(){const p=new c(this.maxLength,this.maxSubParamsLength);return p.params.set(this.params),p.length=this.length,p._subParams.set(this._subParams),p._subParamsLength=this._subParamsLength,p._subParamsIdx.set(this._subParamsIdx),p._rejectDigits=this._rejectDigits,p._rejectSubDigits=this._rejectSubDigits,p._digitIsSub=this._digitIsSub,p}toArray(){const p=[];for(let b=0;b<this.length;++b){p.push(this.params[b]);const y=this._subParamsIdx[b]>>8,k=255&this._subParamsIdx[b];k-y>0&&p.push(Array.prototype.slice.call(this._subParams,y,k))}return p}reset(){this.length=0,this._subParamsLength=0,this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}addParam(p){if(this._digitIsSub=!1,this.length>=this.maxLength)this._rejectDigits=!0;else{if(p<-1)throw new Error("values lesser than -1 are not allowed");this._subParamsIdx[this.length]=this._subParamsLength<<8|this._subParamsLength,this.params[this.length++]=p>o?o:p}}addSubParam(p){if(this._digitIsSub=!0,this.length)if(this._rejectDigits||this._subParamsLength>=this.maxSubParamsLength)this._rejectSubDigits=!0;else{if(p<-1)throw new Error("values lesser than -1 are not allowed");this._subParams[this._subParamsLength++]=p>o?o:p,this._subParamsIdx[this.length-1]++}}hasSubParams(p){return(255&this._subParamsIdx[p])-(this._subParamsIdx[p]>>8)>0}getSubParams(p){const b=this._subParamsIdx[p]>>8,y=255&this._subParamsIdx[p];return y-b>0?this._subParams.subarray(b,y):null}getSubParamsAll(){const p={};for(let b=0;b<this.length;++b){const y=this._subParamsIdx[b]>>8,k=255&this._subParamsIdx[b];k-y>0&&(p[b]=this._subParams.slice(y,k))}return p}addDigit(p){let b;if(this._rejectDigits||!(b=this._digitIsSub?this._subParamsLength:this.length)||this._digitIsSub&&this._rejectSubDigits)return;const y=this._digitIsSub?this._subParams:this.params,k=y[b-1];y[b-1]=~k?Math.min(10*k+p,o):p}}a.Params=c},5741:(d,a)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.AddonManager=void 0,a.AddonManager=class{constructor(){this._addons=[]}dispose(){for(let o=this._addons.length-1;o>=0;o--)this._addons[o].instance.dispose()}loadAddon(o,c){const u={instance:c,dispose:c.dispose,isDisposed:!1};this._addons.push(u),c.dispose=()=>this._wrappedAddonDispose(u),c.activate(o)}_wrappedAddonDispose(o){if(o.isDisposed)return;let c=-1;for(let u=0;u<this._addons.length;u++)if(this._addons[u]===o){c=u;break}if(c===-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(c,1)}}},8771:(d,a,o)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.BufferApiView=void 0;const c=o(3785),u=o(511);a.BufferApiView=class{constructor(p,b){this._buffer=p,this.type=b}init(p){return this._buffer=p,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(p){const b=this._buffer.lines.get(p);if(b)return new c.BufferLineApiView(b)}getNullCell(){return new u.CellData}}},3785:(d,a,o)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.BufferLineApiView=void 0;const c=o(511);a.BufferLineApiView=class{constructor(u){this._line=u}get isWrapped(){return this._line.isWrapped}get length(){return this._line.length}getCell(u,p){if(!(u<0||u>=this._line.length))return p?(this._line.loadCell(u,p),p):this._line.loadCell(u,new c.CellData)}translateToString(u,p,b){return this._line.translateToString(u,p,b)}}},8285:(d,a,o)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.BufferNamespaceApi=void 0;const c=o(8771),u=o(8460),p=o(844);class b extends p.Disposable{constructor(k){super(),this._core=k,this._onBufferChange=this.register(new u.EventEmitter),this.onBufferChange=this._onBufferChange.event,this._normal=new c.BufferApiView(this._core.buffers.normal,"normal"),this._alternate=new c.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)}}a.BufferNamespaceApi=b},7975:(d,a)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.ParserApi=void 0,a.ParserApi=class{constructor(o){this._core=o}registerCsiHandler(o,c){return this._core.registerCsiHandler(o,(u=>c(u.toArray())))}addCsiHandler(o,c){return this.registerCsiHandler(o,c)}registerDcsHandler(o,c){return this._core.registerDcsHandler(o,((u,p)=>c(u,p.toArray())))}addDcsHandler(o,c){return this.registerDcsHandler(o,c)}registerEscHandler(o,c){return this._core.registerEscHandler(o,c)}addEscHandler(o,c){return this.registerEscHandler(o,c)}registerOscHandler(o,c){return this._core.registerOscHandler(o,c)}addOscHandler(o,c){return this.registerOscHandler(o,c)}}},7090:(d,a)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.UnicodeApi=void 0,a.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(d,a,o){var c=this&&this.__decorate||function(g,m,h,f){var x,E=arguments.length,_=E<3?m:f===null?f=Object.getOwnPropertyDescriptor(m,h):f;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")_=Reflect.decorate(g,m,h,f);else for(var S=g.length-1;S>=0;S--)(x=g[S])&&(_=(E<3?x(_):E>3?x(m,h,_):x(m,h))||_);return E>3&&_&&Object.defineProperty(m,h,_),_},u=this&&this.__param||function(g,m){return function(h,f){m(h,f,g)}};Object.defineProperty(a,"__esModule",{value:!0}),a.BufferService=a.MINIMUM_ROWS=a.MINIMUM_COLS=void 0;const p=o(8460),b=o(844),y=o(5295),k=o(2585);a.MINIMUM_COLS=2,a.MINIMUM_ROWS=1;let v=a.BufferService=class extends b.Disposable{get buffer(){return this.buffers.active}constructor(g){super(),this.isUserScrolling=!1,this._onResize=this.register(new p.EventEmitter),this.onResize=this._onResize.event,this._onScroll=this.register(new p.EventEmitter),this.onScroll=this._onScroll.event,this.cols=Math.max(g.rawOptions.cols||0,a.MINIMUM_COLS),this.rows=Math.max(g.rawOptions.rows||0,a.MINIMUM_ROWS),this.buffers=this.register(new y.BufferSet(g,this))}resize(g,m){this.cols=g,this.rows=m,this.buffers.resize(g,m),this._onResize.fire({cols:g,rows:m})}reset(){this.buffers.reset(),this.isUserScrolling=!1}scroll(g,m=!1){const h=this.buffer;let f;f=this._cachedBlankLine,f&&f.length===this.cols&&f.getFg(0)===g.fg&&f.getBg(0)===g.bg||(f=h.getBlankLine(g,m),this._cachedBlankLine=f),f.isWrapped=m;const x=h.ybase+h.scrollTop,E=h.ybase+h.scrollBottom;if(h.scrollTop===0){const _=h.lines.isFull;E===h.lines.length-1?_?h.lines.recycle().copyFrom(f):h.lines.push(f.clone()):h.lines.splice(E+1,0,f.clone()),_?this.isUserScrolling&&(h.ydisp=Math.max(h.ydisp-1,0)):(h.ybase++,this.isUserScrolling||h.ydisp++)}else{const _=E-x+1;h.lines.shiftElements(x+1,_-1,-1),h.lines.set(E,f.clone())}this.isUserScrolling||(h.ydisp=h.ybase),this._onScroll.fire(h.ydisp)}scrollLines(g,m,h){const f=this.buffer;if(g<0){if(f.ydisp===0)return;this.isUserScrolling=!0}else g+f.ydisp>=f.ybase&&(this.isUserScrolling=!1);const x=f.ydisp;f.ydisp=Math.max(Math.min(f.ydisp+g,f.ybase),0),x!==f.ydisp&&(m||this._onScroll.fire(f.ydisp))}};a.BufferService=v=c([u(0,k.IOptionsService)],v)},7994:(d,a)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.CharsetService=void 0,a.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,c){this._charsets[o]=c,this.glevel===o&&(this.charset=c)}}},1753:function(d,a,o){var c=this&&this.__decorate||function(f,x,E,_){var S,w=arguments.length,N=w<3?x:_===null?_=Object.getOwnPropertyDescriptor(x,E):_;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")N=Reflect.decorate(f,x,E,_);else for(var L=f.length-1;L>=0;L--)(S=f[L])&&(N=(w<3?S(N):w>3?S(x,E,N):S(x,E))||N);return w>3&&N&&Object.defineProperty(x,E,N),N},u=this&&this.__param||function(f,x){return function(E,_){x(E,_,f)}};Object.defineProperty(a,"__esModule",{value:!0}),a.CoreMouseService=void 0;const p=o(2585),b=o(8460),y=o(844),k={NONE:{events:0,restrict:()=>!1},X10:{events:1,restrict:f=>f.button!==4&&f.action===1&&(f.ctrl=!1,f.alt=!1,f.shift=!1,!0)},VT200:{events:19,restrict:f=>f.action!==32},DRAG:{events:23,restrict:f=>f.action!==32||f.button!==3},ANY:{events:31,restrict:f=>!0}};function v(f,x){let E=(f.ctrl?16:0)|(f.shift?4:0)|(f.alt?8:0);return f.button===4?(E|=64,E|=f.action):(E|=3&f.button,4&f.button&&(E|=64),8&f.button&&(E|=128),f.action===32?E|=32:f.action!==0||x||(E|=3)),E}const g=String.fromCharCode,m={DEFAULT:f=>{const x=[v(f,!1)+32,f.col+32,f.row+32];return x[0]>255||x[1]>255||x[2]>255?"":`\x1B[M${g(x[0])}${g(x[1])}${g(x[2])}`},SGR:f=>{const x=f.action===0&&f.button!==4?"m":"M";return`\x1B[<${v(f,!0)};${f.col};${f.row}${x}`},SGR_PIXELS:f=>{const x=f.action===0&&f.button!==4?"m":"M";return`\x1B[<${v(f,!0)};${f.x};${f.y}${x}`}};let h=a.CoreMouseService=class extends y.Disposable{constructor(f,x){super(),this._bufferService=f,this._coreService=x,this._protocols={},this._encodings={},this._activeProtocol="",this._activeEncoding="",this._lastEvent=null,this._onProtocolChange=this.register(new b.EventEmitter),this.onProtocolChange=this._onProtocolChange.event;for(const E of Object.keys(k))this.addProtocol(E,k[E]);for(const E of Object.keys(m))this.addEncoding(E,m[E]);this.reset()}addProtocol(f,x){this._protocols[f]=x}addEncoding(f,x){this._encodings[f]=x}get activeProtocol(){return this._activeProtocol}get areMouseEventsActive(){return this._protocols[this._activeProtocol].events!==0}set activeProtocol(f){if(!this._protocols[f])throw new Error(`unknown protocol "${f}"`);this._activeProtocol=f,this._onProtocolChange.fire(this._protocols[f].events)}get activeEncoding(){return this._activeEncoding}set activeEncoding(f){if(!this._encodings[f])throw new Error(`unknown encoding "${f}"`);this._activeEncoding=f}reset(){this.activeProtocol="NONE",this.activeEncoding="DEFAULT",this._lastEvent=null}triggerMouseEvent(f){if(f.col<0||f.col>=this._bufferService.cols||f.row<0||f.row>=this._bufferService.rows||f.button===4&&f.action===32||f.button===3&&f.action!==32||f.button!==4&&(f.action===2||f.action===3)||(f.col++,f.row++,f.action===32&&this._lastEvent&&this._equalEvents(this._lastEvent,f,this._activeEncoding==="SGR_PIXELS"))||!this._protocols[this._activeProtocol].restrict(f))return!1;const x=this._encodings[this._activeEncoding](f);return x&&(this._activeEncoding==="DEFAULT"?this._coreService.triggerBinaryEvent(x):this._coreService.triggerDataEvent(x,!0)),this._lastEvent=f,!0}explainEvents(f){return{down:!!(1&f),up:!!(2&f),drag:!!(4&f),move:!!(8&f),wheel:!!(16&f)}}_equalEvents(f,x,E){if(E){if(f.x!==x.x||f.y!==x.y)return!1}else if(f.col!==x.col||f.row!==x.row)return!1;return f.button===x.button&&f.action===x.action&&f.ctrl===x.ctrl&&f.alt===x.alt&&f.shift===x.shift}};a.CoreMouseService=h=c([u(0,p.IBufferService),u(1,p.ICoreService)],h)},6975:function(d,a,o){var c=this&&this.__decorate||function(h,f,x,E){var _,S=arguments.length,w=S<3?f:E===null?E=Object.getOwnPropertyDescriptor(f,x):E;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")w=Reflect.decorate(h,f,x,E);else for(var N=h.length-1;N>=0;N--)(_=h[N])&&(w=(S<3?_(w):S>3?_(f,x,w):_(f,x))||w);return S>3&&w&&Object.defineProperty(f,x,w),w},u=this&&this.__param||function(h,f){return function(x,E){f(x,E,h)}};Object.defineProperty(a,"__esModule",{value:!0}),a.CoreService=void 0;const p=o(1439),b=o(8460),y=o(844),k=o(2585),v=Object.freeze({insertMode:!1}),g=Object.freeze({applicationCursorKeys:!1,applicationKeypad:!1,bracketedPasteMode:!1,origin:!1,reverseWraparound:!1,sendFocus:!1,wraparound:!0});let m=a.CoreService=class extends y.Disposable{constructor(h,f,x){super(),this._bufferService=h,this._logService=f,this._optionsService=x,this.isCursorInitialized=!1,this.isCursorHidden=!1,this._onData=this.register(new b.EventEmitter),this.onData=this._onData.event,this._onUserInput=this.register(new b.EventEmitter),this.onUserInput=this._onUserInput.event,this._onBinary=this.register(new b.EventEmitter),this.onBinary=this._onBinary.event,this._onRequestScrollToBottom=this.register(new b.EventEmitter),this.onRequestScrollToBottom=this._onRequestScrollToBottom.event,this.modes=(0,p.clone)(v),this.decPrivateModes=(0,p.clone)(g)}reset(){this.modes=(0,p.clone)(v),this.decPrivateModes=(0,p.clone)(g)}triggerDataEvent(h,f=!1){if(this._optionsService.rawOptions.disableStdin)return;const x=this._bufferService.buffer;f&&this._optionsService.rawOptions.scrollOnUserInput&&x.ybase!==x.ydisp&&this._onRequestScrollToBottom.fire(),f&&this._onUserInput.fire(),this._logService.debug(`sending data "${h}"`,(()=>h.split("").map((E=>E.charCodeAt(0))))),this._onData.fire(h)}triggerBinaryEvent(h){this._optionsService.rawOptions.disableStdin||(this._logService.debug(`sending binary "${h}"`,(()=>h.split("").map((f=>f.charCodeAt(0))))),this._onBinary.fire(h))}};a.CoreService=m=c([u(0,k.IBufferService),u(1,k.ILogService),u(2,k.IOptionsService)],m)},9074:(d,a,o)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.DecorationService=void 0;const c=o(8055),u=o(8460),p=o(844),b=o(6106);let y=0,k=0;class v extends p.Disposable{get decorations(){return this._decorations.values()}constructor(){super(),this._decorations=new b.SortedList((h=>h==null?void 0:h.marker.line)),this._onDecorationRegistered=this.register(new u.EventEmitter),this.onDecorationRegistered=this._onDecorationRegistered.event,this._onDecorationRemoved=this.register(new u.EventEmitter),this.onDecorationRemoved=this._onDecorationRemoved.event,this.register((0,p.toDisposable)((()=>this.reset())))}registerDecoration(h){if(h.marker.isDisposed)return;const f=new g(h);if(f){const x=f.marker.onDispose((()=>f.dispose()));f.onDispose((()=>{f&&(this._decorations.delete(f)&&this._onDecorationRemoved.fire(f),x.dispose())})),this._decorations.insert(f),this._onDecorationRegistered.fire(f)}return f}reset(){for(const h of this._decorations.values())h.dispose();this._decorations.clear()}*getDecorationsAtCell(h,f,x){let E=0,_=0;for(const S of this._decorations.getKeyIterator(f))E=S.options.x??0,_=E+(S.options.width??1),h>=E&&h<_&&(!x||(S.options.layer??"bottom")===x)&&(yield S)}forEachDecorationAtCell(h,f,x,E){this._decorations.forEachByKey(f,(_=>{y=_.options.x??0,k=y+(_.options.width??1),h>=y&&h<k&&(!x||(_.options.layer??"bottom")===x)&&E(_)}))}}a.DecorationService=v;class g extends p.Disposable{get isDisposed(){return this._isDisposed}get backgroundColorRGB(){return this._cachedBg===null&&(this.options.backgroundColor?this._cachedBg=c.css.toColor(this.options.backgroundColor):this._cachedBg=void 0),this._cachedBg}get foregroundColorRGB(){return this._cachedFg===null&&(this.options.foregroundColor?this._cachedFg=c.css.toColor(this.options.foregroundColor):this._cachedFg=void 0),this._cachedFg}constructor(h){super(),this.options=h,this.onRenderEmitter=this.register(new u.EventEmitter),this.onRender=this.onRenderEmitter.event,this._onDispose=this.register(new u.EventEmitter),this.onDispose=this._onDispose.event,this._cachedBg=null,this._cachedFg=null,this.marker=h.marker,this.options.overviewRulerOptions&&!this.options.overviewRulerOptions.position&&(this.options.overviewRulerOptions.position="full")}dispose(){this._onDispose.fire(),super.dispose()}}},4348:(d,a,o)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.InstantiationService=a.ServiceCollection=void 0;const c=o(2585),u=o(8343);class p{constructor(...y){this._entries=new Map;for(const[k,v]of y)this.set(k,v)}set(y,k){const v=this._entries.get(y);return this._entries.set(y,k),v}forEach(y){for(const[k,v]of this._entries.entries())y(k,v)}has(y){return this._entries.has(y)}get(y){return this._entries.get(y)}}a.ServiceCollection=p,a.InstantiationService=class{constructor(){this._services=new p,this._services.set(c.IInstantiationService,this)}setService(b,y){this._services.set(b,y)}getService(b){return this._services.get(b)}createInstance(b,...y){const k=(0,u.getServiceDependencies)(b).sort(((m,h)=>m.index-h.index)),v=[];for(const m of k){const h=this._services.get(m.id);if(!h)throw new Error(`[createInstance] ${b.name} depends on UNKNOWN service ${m.id}.`);v.push(h)}const g=k.length>0?k[0].index:y.length;if(y.length!==g)throw new Error(`[createInstance] First service dependency of ${b.name} at position ${g+1} conflicts with ${y.length} static arguments`);return new b(...y,...v)}}},7866:function(d,a,o){var c=this&&this.__decorate||function(g,m,h,f){var x,E=arguments.length,_=E<3?m:f===null?f=Object.getOwnPropertyDescriptor(m,h):f;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")_=Reflect.decorate(g,m,h,f);else for(var S=g.length-1;S>=0;S--)(x=g[S])&&(_=(E<3?x(_):E>3?x(m,h,_):x(m,h))||_);return E>3&&_&&Object.defineProperty(m,h,_),_},u=this&&this.__param||function(g,m){return function(h,f){m(h,f,g)}};Object.defineProperty(a,"__esModule",{value:!0}),a.traceCall=a.setTraceLogger=a.LogService=void 0;const p=o(844),b=o(2585),y={trace:b.LogLevelEnum.TRACE,debug:b.LogLevelEnum.DEBUG,info:b.LogLevelEnum.INFO,warn:b.LogLevelEnum.WARN,error:b.LogLevelEnum.ERROR,off:b.LogLevelEnum.OFF};let k,v=a.LogService=class extends p.Disposable{get logLevel(){return this._logLevel}constructor(g){super(),this._optionsService=g,this._logLevel=b.LogLevelEnum.OFF,this._updateLogLevel(),this.register(this._optionsService.onSpecificOptionChange("logLevel",(()=>this._updateLogLevel()))),k=this}_updateLogLevel(){this._logLevel=y[this._optionsService.rawOptions.logLevel]}_evalLazyOptionalParams(g){for(let m=0;m<g.length;m++)typeof g[m]=="function"&&(g[m]=g[m]())}_log(g,m,h){this._evalLazyOptionalParams(h),g.call(console,(this._optionsService.options.logger?"":"xterm.js: ")+m,...h)}trace(g,...m){var h;this._logLevel<=b.LogLevelEnum.TRACE&&this._log(((h=this._optionsService.options.logger)==null?void 0:h.trace.bind(this._optionsService.options.logger))??console.log,g,m)}debug(g,...m){var h;this._logLevel<=b.LogLevelEnum.DEBUG&&this._log(((h=this._optionsService.options.logger)==null?void 0:h.debug.bind(this._optionsService.options.logger))??console.log,g,m)}info(g,...m){var h;this._logLevel<=b.LogLevelEnum.INFO&&this._log(((h=this._optionsService.options.logger)==null?void 0:h.info.bind(this._optionsService.options.logger))??console.info,g,m)}warn(g,...m){var h;this._logLevel<=b.LogLevelEnum.WARN&&this._log(((h=this._optionsService.options.logger)==null?void 0:h.warn.bind(this._optionsService.options.logger))??console.warn,g,m)}error(g,...m){var h;this._logLevel<=b.LogLevelEnum.ERROR&&this._log(((h=this._optionsService.options.logger)==null?void 0:h.error.bind(this._optionsService.options.logger))??console.error,g,m)}};a.LogService=v=c([u(0,b.IOptionsService)],v),a.setTraceLogger=function(g){k=g},a.traceCall=function(g,m,h){if(typeof h.value!="function")throw new Error("not supported");const f=h.value;h.value=function(...x){if(k.logLevel!==b.LogLevelEnum.TRACE)return f.apply(this,x);k.trace(`GlyphRenderer#${f.name}(${x.map((_=>JSON.stringify(_))).join(", ")})`);const E=f.apply(this,x);return k.trace(`GlyphRenderer#${f.name} return`,E),E}}},7302:(d,a,o)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.OptionsService=a.DEFAULT_OPTIONS=void 0;const c=o(8460),u=o(844),p=o(6114);a.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:p.isMac,windowOptions:{},windowsMode:!1,windowsPty:{},wordSeparator:" ()[]{}',\"`",altClickMovesCursor:!0,convertEol:!1,termName:"xterm",cancelEvents:!1,overviewRulerWidth:0};const b=["normal","bold","100","200","300","400","500","600","700","800","900"];class y extends u.Disposable{constructor(v){super(),this._onOptionChange=this.register(new c.EventEmitter),this.onOptionChange=this._onOptionChange.event;const g={...a.DEFAULT_OPTIONS};for(const m in v)if(m in g)try{const h=v[m];g[m]=this._sanitizeAndValidateOption(m,h)}catch(h){console.error(h)}this.rawOptions=g,this.options={...g},this._setupOptions(),this.register((0,u.toDisposable)((()=>{this.rawOptions.linkHandler=null,this.rawOptions.documentOverride=null})))}onSpecificOptionChange(v,g){return this.onOptionChange((m=>{m===v&&g(this.rawOptions[v])}))}onMultipleOptionChange(v,g){return this.onOptionChange((m=>{v.indexOf(m)!==-1&&g()}))}_setupOptions(){const v=m=>{if(!(m in a.DEFAULT_OPTIONS))throw new Error(`No option with key "${m}"`);return this.rawOptions[m]},g=(m,h)=>{if(!(m in a.DEFAULT_OPTIONS))throw new Error(`No option with key "${m}"`);h=this._sanitizeAndValidateOption(m,h),this.rawOptions[m]!==h&&(this.rawOptions[m]=h,this._onOptionChange.fire(m))};for(const m in this.rawOptions){const h={get:v.bind(this,m),set:g.bind(this,m)};Object.defineProperty(this.options,m,h)}}_sanitizeAndValidateOption(v,g){switch(v){case"cursorStyle":if(g||(g=a.DEFAULT_OPTIONS[v]),!(function(m){return m==="block"||m==="underline"||m==="bar"})(g))throw new Error(`"${g}" is not a valid value for ${v}`);break;case"wordSeparator":g||(g=a.DEFAULT_OPTIONS[v]);break;case"fontWeight":case"fontWeightBold":if(typeof g=="number"&&1<=g&&g<=1e3)break;g=b.includes(g)?g:a.DEFAULT_OPTIONS[v];break;case"cursorWidth":g=Math.floor(g);case"lineHeight":case"tabStopWidth":if(g<1)throw new Error(`${v} cannot be less than 1, value: ${g}`);break;case"minimumContrastRatio":g=Math.max(1,Math.min(21,Math.round(10*g)/10));break;case"scrollback":if((g=Math.min(g,4294967295))<0)throw new Error(`${v} cannot be less than 0, value: ${g}`);break;case"fastScrollSensitivity":case"scrollSensitivity":if(g<=0)throw new Error(`${v} cannot be less than or equal to 0, value: ${g}`);break;case"rows":case"cols":if(!g&&g!==0)throw new Error(`${v} must be numeric, value: ${g}`);break;case"windowsPty":g=g??{}}return g}}a.OptionsService=y},2660:function(d,a,o){var c=this&&this.__decorate||function(y,k,v,g){var m,h=arguments.length,f=h<3?k:g===null?g=Object.getOwnPropertyDescriptor(k,v):g;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")f=Reflect.decorate(y,k,v,g);else for(var x=y.length-1;x>=0;x--)(m=y[x])&&(f=(h<3?m(f):h>3?m(k,v,f):m(k,v))||f);return h>3&&f&&Object.defineProperty(k,v,f),f},u=this&&this.__param||function(y,k){return function(v,g){k(v,g,y)}};Object.defineProperty(a,"__esModule",{value:!0}),a.OscLinkService=void 0;const p=o(2585);let b=a.OscLinkService=class{constructor(y){this._bufferService=y,this._nextId=1,this._entriesWithId=new Map,this._dataByLinkId=new Map}registerLink(y){const k=this._bufferService.buffer;if(y.id===void 0){const x=k.addMarker(k.ybase+k.y),E={data:y,id:this._nextId++,lines:[x]};return x.onDispose((()=>this._removeMarkerFromLink(E,x))),this._dataByLinkId.set(E.id,E),E.id}const v=y,g=this._getEntryIdKey(v),m=this._entriesWithId.get(g);if(m)return this.addLineToLink(m.id,k.ybase+k.y),m.id;const h=k.addMarker(k.ybase+k.y),f={id:this._nextId++,key:this._getEntryIdKey(v),data:v,lines:[h]};return h.onDispose((()=>this._removeMarkerFromLink(f,h))),this._entriesWithId.set(f.key,f),this._dataByLinkId.set(f.id,f),f.id}addLineToLink(y,k){const v=this._dataByLinkId.get(y);if(v&&v.lines.every((g=>g.line!==k))){const g=this._bufferService.buffer.addMarker(k);v.lines.push(g),g.onDispose((()=>this._removeMarkerFromLink(v,g)))}}getLinkData(y){var k;return(k=this._dataByLinkId.get(y))==null?void 0:k.data}_getEntryIdKey(y){return`${y.id};;${y.uri}`}_removeMarkerFromLink(y,k){const v=y.lines.indexOf(k);v!==-1&&(y.lines.splice(v,1),y.lines.length===0&&(y.data.id!==void 0&&this._entriesWithId.delete(y.key),this._dataByLinkId.delete(y.id)))}};a.OscLinkService=b=c([u(0,p.IBufferService)],b)},8343:(d,a)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.createDecorator=a.getServiceDependencies=a.serviceRegistry=void 0;const o="di$target",c="di$dependencies";a.serviceRegistry=new Map,a.getServiceDependencies=function(u){return u[c]||[]},a.createDecorator=function(u){if(a.serviceRegistry.has(u))return a.serviceRegistry.get(u);const p=function(b,y,k){if(arguments.length!==3)throw new Error("@IServiceName-decorator can only be used to decorate a parameter");(function(v,g,m){g[o]===g?g[c].push({id:v,index:m}):(g[c]=[{id:v,index:m}],g[o]=g)})(p,b,k)};return p.toString=()=>u,a.serviceRegistry.set(u,p),p}},2585:(d,a,o)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.IDecorationService=a.IUnicodeService=a.IOscLinkService=a.IOptionsService=a.ILogService=a.LogLevelEnum=a.IInstantiationService=a.ICharsetService=a.ICoreService=a.ICoreMouseService=a.IBufferService=void 0;const c=o(8343);var u;a.IBufferService=(0,c.createDecorator)("BufferService"),a.ICoreMouseService=(0,c.createDecorator)("CoreMouseService"),a.ICoreService=(0,c.createDecorator)("CoreService"),a.ICharsetService=(0,c.createDecorator)("CharsetService"),a.IInstantiationService=(0,c.createDecorator)("InstantiationService"),(function(p){p[p.TRACE=0]="TRACE",p[p.DEBUG=1]="DEBUG",p[p.INFO=2]="INFO",p[p.WARN=3]="WARN",p[p.ERROR=4]="ERROR",p[p.OFF=5]="OFF"})(u||(a.LogLevelEnum=u={})),a.ILogService=(0,c.createDecorator)("LogService"),a.IOptionsService=(0,c.createDecorator)("OptionsService"),a.IOscLinkService=(0,c.createDecorator)("OscLinkService"),a.IUnicodeService=(0,c.createDecorator)("UnicodeService"),a.IDecorationService=(0,c.createDecorator)("DecorationService")},1480:(d,a,o)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.UnicodeService=void 0;const c=o(8460),u=o(225);class p{static extractShouldJoin(y){return(1&y)!=0}static extractWidth(y){return y>>1&3}static extractCharKind(y){return y>>3}static createPropertyValue(y,k,v=!1){return(16777215&y)<<3|(3&k)<<1|(v?1:0)}constructor(){this._providers=Object.create(null),this._active="",this._onChange=new c.EventEmitter,this.onChange=this._onChange.event;const y=new u.UnicodeV6;this.register(y),this._active=y.version,this._activeProvider=y}dispose(){this._onChange.dispose()}get versions(){return Object.keys(this._providers)}get activeVersion(){return this._active}set activeVersion(y){if(!this._providers[y])throw new Error(`unknown Unicode version "${y}"`);this._active=y,this._activeProvider=this._providers[y],this._onChange.fire(y)}register(y){this._providers[y.version]=y}wcwidth(y){return this._activeProvider.wcwidth(y)}getStringCellWidth(y){let k=0,v=0;const g=y.length;for(let m=0;m<g;++m){let h=y.charCodeAt(m);if(55296<=h&&h<=56319){if(++m>=g)return k+this.wcwidth(h);const E=y.charCodeAt(m);56320<=E&&E<=57343?h=1024*(h-55296)+E-56320+65536:k+=this.wcwidth(E)}const f=this.charProperties(h,v);let x=p.extractWidth(f);p.extractShouldJoin(f)&&(x-=p.extractWidth(v)),k+=x,v=f}return k}charProperties(y,k){return this._activeProvider.charProperties(y,k)}}a.UnicodeService=p}},s={};function i(d){var a=s[d];if(a!==void 0)return a.exports;var o=s[d]={exports:{}};return r[d].call(o.exports,o,o.exports,i),o.exports}var l={};return(()=>{var d=l;Object.defineProperty(d,"__esModule",{value:!0}),d.Terminal=void 0;const a=i(9042),o=i(3236),c=i(844),u=i(5741),p=i(8285),b=i(7975),y=i(7090),k=["cols","rows"];class v extends c.Disposable{constructor(m){super(),this._core=this.register(new o.Terminal(m)),this._addonManager=this.register(new u.AddonManager),this._publicOptions={...this._core.options};const h=x=>this._core.options[x],f=(x,E)=>{this._checkReadonlyOptions(x),this._core.options[x]=E};for(const x in this._core.options){const E={get:h.bind(this,x),set:f.bind(this,x)};Object.defineProperty(this._publicOptions,x,E)}}_checkReadonlyOptions(m){if(k.includes(m))throw new Error(`Option "${m}" 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 b.ParserApi(this._core)),this._parser}get unicode(){return this._checkProposedApi(),new y.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 p.BufferNamespaceApi(this._core))),this._buffer}get markers(){return this._checkProposedApi(),this._core.markers}get modes(){const m=this._core.coreService.decPrivateModes;let h="none";switch(this._core.coreMouseService.activeProtocol){case"X10":h="x10";break;case"VT200":h="vt200";break;case"DRAG":h="drag";break;case"ANY":h="any"}return{applicationCursorKeysMode:m.applicationCursorKeys,applicationKeypadMode:m.applicationKeypad,bracketedPasteMode:m.bracketedPasteMode,insertMode:this._core.coreService.modes.insertMode,mouseTrackingMode:h,originMode:m.origin,reverseWraparoundMode:m.reverseWraparound,sendFocusMode:m.sendFocus,wraparoundMode:m.wraparound}}get options(){return this._publicOptions}set options(m){for(const h in m)this._publicOptions[h]=m[h]}blur(){this._core.blur()}focus(){this._core.focus()}input(m,h=!0){this._core.input(m,h)}resize(m,h){this._verifyIntegers(m,h),this._core.resize(m,h)}open(m){this._core.open(m)}attachCustomKeyEventHandler(m){this._core.attachCustomKeyEventHandler(m)}attachCustomWheelEventHandler(m){this._core.attachCustomWheelEventHandler(m)}registerLinkProvider(m){return this._core.registerLinkProvider(m)}registerCharacterJoiner(m){return this._checkProposedApi(),this._core.registerCharacterJoiner(m)}deregisterCharacterJoiner(m){this._checkProposedApi(),this._core.deregisterCharacterJoiner(m)}registerMarker(m=0){return this._verifyIntegers(m),this._core.registerMarker(m)}registerDecoration(m){return this._checkProposedApi(),this._verifyPositiveIntegers(m.x??0,m.width??0,m.height??0),this._core.registerDecoration(m)}hasSelection(){return this._core.hasSelection()}select(m,h,f){this._verifyIntegers(m,h,f),this._core.select(m,h,f)}getSelection(){return this._core.getSelection()}getSelectionPosition(){return this._core.getSelectionPosition()}clearSelection(){this._core.clearSelection()}selectAll(){this._core.selectAll()}selectLines(m,h){this._verifyIntegers(m,h),this._core.selectLines(m,h)}dispose(){super.dispose()}scrollLines(m){this._verifyIntegers(m),this._core.scrollLines(m)}scrollPages(m){this._verifyIntegers(m),this._core.scrollPages(m)}scrollToTop(){this._core.scrollToTop()}scrollToBottom(){this._core.scrollToBottom()}scrollToLine(m){this._verifyIntegers(m),this._core.scrollToLine(m)}clear(){this._core.clear()}write(m,h){this._core.write(m,h)}writeln(m,h){this._core.write(m),this._core.write(`\r
|
|
636
|
-
`,h)}paste(m){this._core.paste(m)}refresh(m,h){this._verifyIntegers(m,h),this._core.refresh(m,h)}reset(){this._core.reset()}clearTextureAtlas(){this._core.clearTextureAtlas()}loadAddon(m){this._addonManager.loadAddon(this,m)}static get strings(){return a}_verifyIntegers(...m){for(const h of m)if(h===1/0||isNaN(h)||h%1!=0)throw new Error("This API only accepts integers")}_verifyPositiveIntegers(...m){for(const h of m)if(h&&(h===1/0||isNaN(h)||h%1!=0||h<0))throw new Error("This API only accepts positive integers")}}d.Terminal=v})(),l})()))})(ts)),ts.exports}var qb=Wb();const Mp="codebuddy-locale";function Pp(){if(typeof navigator>"u")return"en";const e=[];Array.isArray(navigator.languages)&&navigator.languages.length>0&&e.push(...navigator.languages),navigator.language&&e.push(navigator.language);try{const t=Intl.DateTimeFormat().resolvedOptions().locale;t&&e.push(t)}catch{}for(const t of e)if(t.toLowerCase().startsWith("zh"))return"zh";return"en"}function rs(e){return e==="system"?Pp():e}function Vb(){try{const e=localStorage.getItem(Mp);if(e){const t=JSON.parse(e),r=(t==null?void 0:t.mode)??e;if(["zh","en","system"].includes(r))return r}}catch{}return"system"}const xn=Ae()(Pr((e,t)=>{const r=Vb(),s=rs(r);return typeof window<"u"&&window.addEventListener("languagechange",()=>{const i=xn.getState();if(i.mode==="system"){const l=Pp();l!==i.resolved&&xn.setState({resolved:l})}}),{mode:r,resolved:s,setLocale:i=>{const l=rs(i);e({mode:i,resolved:l})},toggle:()=>{const i=t().mode,l=i==="zh"?"en":i==="en"?"system":"zh";t().setLocale(l)}}},{namespace:"locale",fields:["mode"],scope:"global",debounceMs:300,localStorageKey:Mp,onLoad:(e,t)=>{if(e.mode){const r=rs(e.mode);t({mode:e.mode,resolved:r})}}})),Md={zh:{"app.connecting":"正在连接 CodeBuddy Code...","app.connectFailed":"连接失败","app.retry":"重试","app.pwa.newVersion":"检测到 Web UI 新版本","app.pwa.reloadNow":"立即刷新","app.pwa.reloadLater":"稍后","app.pwa.reloadedAfterIdle":"已切换到新版本","chat.empty.title":"CodeBuddy Code","chat.empty.subtitle":"今天有什么可以帮到你?","chat.empty.slogan":"Claw Your Ideas . Into Reality","chat.empty.tag.slides":"幻灯片生成","chat.empty.tag.research":"深度研究","chat.empty.tag.docs":"文档处理","chat.empty.tag.data":"数据分析","chat.thinking":"思考中","chat.waitingPermission":"等待权限确认","chat.waitingUser":"等待用户回答","chat.error":"错误","chat.sessionEnded":"会话已结束","chat.stopped":"已停止","chat.error.refusal":"Agent 拒绝继续执行。这可能是由于内容策略限制或其他限制。","chat.error.network":"网络连接异常或服务暂时不可用,请稍后重试。","chat.error.auth":"身份验证失败或权限不足,请重新登录后再试。","chat.error.quota":"已达到配额上限或请求过于频繁,请稍后再试。","chat.error.modelService":"模型服务返回异常,请重试或稍后再试。","chat.error.maxTokens":"响应因达到最大 token 限制而被截断。您可以继续对话或要求更简洁的回复。","chat.error.maxTurnRequests":"已超过单轮对话允许的最大模型请求次数。您可以发送新消息以继续。","chat.newChat":"新对话","chat.disclaimer":"回答由 AI 生成,仅供参考","chat.compacted":"已精简历史对话","chat.compacting":"正在精简历史对话...","chat.compactCancelled":"历史对话精简已取消","phase.preparing":"准备中","phase.modelRequesting":"等待模型响应","phase.modelStreaming":"接收中","phase.modelDone":"处理中","phase.toolExecuting":"执行工具","phase.modelStreamingTool":"正在写入","phase.retrying":"重试中","progress.compacting":"压缩上下文中","input.placeholder":"从一个想法开始...","input.placeholderRunning":"消息将排队等待处理...","input.placeholderPending":"请先处理权限请求...","input.send":"发送 (Enter)","input.stop":"停止","input.thinking":"思考中","input.deepThinking":"深度思考","input.promptFailed":"发送失败","input.sendQueued":"发送排队消息 (Enter)","input.dropHint":"拖拽文件到这里","input.addImage":"添加图片","input.addFile":"添加文件","input.imageTooLarge":"图片不能超过 10MB","input.tooManyImages":"最多添加 5 张图片","input.fileTooLarge":"文件不能超过 1MB","input.tooManyFiles":"最多添加 10 个文件","input.menu.image":"图片","input.menu.file":"文件","input.newline":"换行","input.contextMenu.newline":"换行","input.contextMenu.send":"发送","queue.more":" 条消息排队中","status.running":"运行中","tool.writeFile":"写入文件","tool.readFile":"读取文件","tool.execute":"执行指令","tool.searchFiles":"搜索文件","tool.searchContent":"搜索内容","tool.fetchWeb":"获取网页","tool.searchWeb":"搜索网络","tool.defaultName":"工具","tool.moreItems":"... 还有 {count} 项","interruption.title":"需要授权","interruption.tool":"工具","interruption.allow":"允许","interruption.allowAll":"全部允许","interruption.deny":"拒绝","interruption.approved":"已允许","interruption.denied":"已拒绝","interruption.edits":"{count} 处编辑","interruption.yes":"是","interruption.keepPlanning":"继续规划","interruption.exitPlanMode":"退出计划模式","interruption.readyToCode":"准备好开始编码了吗?","theme.light":"浅色","theme.dark":"深色","theme.system":"跟随系统","locale.zh":"中文","locale.en":"English","locale.system":"跟随系统","sidebar.nav.plugins":"插件","sidebar.nav.tasks":"任务","sidebar.search.placeholder":"搜索...","sidebar.chatHistory":"对话历史","sidebar.workspace":"工作区","sidebar.connectionStatus":"连接状态","sidebar.status":"状态","sidebar.sessionId":"会话ID","sidebar.notConnected":"未连接","sidebar.modelSelection":"模型选择","sidebar.noModels":"暂无可用模型","sidebar.environment":"环境信息","sidebar.cwd":"工作目录","sidebar.os":"操作系统","sidebar.nodeVersion":"Node.js","sidebar.gatewayMode":"网关模式","sidebar.tunnelUrl":"Tunnel 地址","sidebar.clickToCopy":"点击复制","sidebar.copied":"已复制","sidebar.permissionMode":"权限模式","sidebar.noModes":"暂无可用模式","sidebar.preferences":"设置","sidebar.keybindings":"快捷键","sidebar.group.workspace":"工作区","sidebar.group.observability":"可观测","sidebar.group.preferences":"配置","bottomSheet.attachments":"添加","bottomSheet.navigation":"导航","sidebar.theme":"界面主题","sidebar.language":"界面语言","sidebar.user":"用户","sidebar.authMethod":"密码认证","sidebar.noAuth":"无认证","sidebar.version":"Remote UI v1.0","connection.connected":"已连接","connection.connecting":"连接中","connection.disconnected":"未连接","connection.error":"连接错误","message.copyToClipboard":"复制到剪贴板","message.copied":"已复制","message.copy":"复制","message.assistantName":"CodeBuddy Code","thinking.title":"思考过程","thinking.thinking":"思考中","thinking.done":"已思考","thinking.seconds":"(用时 {n} 秒)","thinking.expand":"展开","thinking.collapse":"收起","diff.noChanges":"无变更","login.title":"CodeBuddy Remote Control","login.subtitle":"请输入终端中显示的密码","login.placeholder":"密码","login.submit":"登录","login.error.incorrect":"密码错误","login.error.rateLimit":"登录尝试次数过多,请稍后再试","login.error.required":"请输入密码","login.hint.password":"提示:密码在服务启动时显示在终端中。","login.hint.urlAuth":"也可以使用 <code>?password=xxx</code> 自动登录。","login.hint.disable":'或在 CodeBuddy 配置目录(默认 <code>~/.codebuddy</code>,可通过 <code>CODEBUDDY_CONFIG_DIR</code> 环境变量覆盖)下的 <code>settings.json</code> 中设置 <code>gateway.auth: "none"</code> 来禁用认证。',"login.slogan":"Claw Your Ideas . Into Reality","login.tagline":"Triggered Anywhere, Completed Locally.","login.privacy":"隐私政策","login.terms":"服务条款","sidebar.interactionMode":"交互模式","sidebar.chatMode":"对话","sidebar.terminalMode":"终端","sidebar.canvas":"画布","canvas.title":"无限画布","canvas.addTerminal":"添加终端","canvas.zoomIn":"放大","canvas.zoomOut":"缩小","canvas.fitView":"适应视图","canvas.resetView":"重置视图","canvas.empty":"点击工具栏 + 按钮添加终端","canvas.openStandalone":"在新窗口打开画布","canvas.tileMenu.close":"关闭","canvas.tileMenu.duplicate":"复刻终端","canvas.tileMenu.maximize":"最大化","canvas.tileMenu.minimize":"最小化","canvas.tileMenu.restore":"还原","canvas.tileMenu.openStandalone":"在新窗口打开","canvas.standalone.missingPaneId":"未指定终端 ID","canvas.defaultTitle":"终端","terminal.connecting":"终端连接中...","terminal.title":"终端","terminal.disconnected":"终端已断开","terminal.error":"终端连接失败","terminal.reconnect":"重新连接","terminal.splitHorizontal":"左右分屏","terminal.splitVertical":"上下分屏","terminal.closePane":"关闭终端","terminal.maxPanes":"已达最大面板数","sidebar.instances":"实例","sidebar.activeInstances":"个活跃实例","sidebar.manageInstances":"管理实例","sidebar.remoteControl":"远程控制","instance.title":"实例列表","instance.switch":"实例","instance.switchTitle":"切换实例","instance.current":"当前实例","instance.manual":"手动添加","instance.switchTo":"切换到此实例","instance.manage":"管理实例","instance.managerTitle":"实例管理","instance.addInstance":"添加实例","instance.name":"实例名称","instance.namePlaceholder":"自定义实例名称(可选,默认为目录名)","instance.url":"实例地址","instance.urlPlaceholder":"https://example.trycloudflare.com","instance.password":"密码","instance.optional":"可选","instance.passwordPlaceholder":"访问密码","instance.cancel":"取消","instance.add":"添加","instance.remove":"删除此实例","instance.noInstances":"暂无其他实例","instance.noInstancesHint":"启动更多 CodeBuddy Code 实例,或手动添加远程实例","instance.cwd":"工作目录","instance.topic":"当前话题","instance.startedAt":"启动于","instance.local":"本地","instance.tunnel":"隧道","instance.uptime.days":"天前","instance.uptime.hours":"小时前","instance.uptime.minutes":"分钟前","instance.uptime.justNow":"刚刚","instance.addError":"添加实例失败","instance.removeError":"删除实例失败","instance.copyUrl":"复制链接","instance.copied":"已复制","instance.subtitle":"管理和切换工作实例","instance.refresh":"刷新","instance.refreshed":"已刷新","instance.loading":"加载实例中...","instance.error":"加载实例列表失败","instance.retry":"重试","question.multiple":"多选","question.customAnswer":"或输入自定义答案...","question.reviewAnswers":"审核答案","question.singleTitle":"问题","question.titleWithCount":"问题({count})","question.reviewTab":"审核","question.next":"下一步","question.submit":"提交","question.cancel":"取消","question.answered":"已回答","question.cancelled":"问题已取消","todo.title":"任务清单","todo.executing":"任务{n}正在执行中","todo.untitled":"未命名","history.title":"会话历史","history.description":"点击会话可切换到该对话","history.noData":"暂无会话历史","history.noDataHint":"开始一段新对话吧","history.backToChat":"返回对话","history.loading":"加载中...","history.loadError":"加载失败","history.retry":"重试","history.current":"当前","history.messages":"{count} 条消息","history.delete":"删除","history.deleteConfirm":"确定要删除这个会话吗?","history.deleteCancel":"取消","history.deleteOk":"删除","history.rename":"重命名","history.renameTitle":"重命名会话","history.renamePlaceholder":"输入新名称","history.renameCancel":"取消","history.renameOk":"确定","history.cannotDeleteCurrent":"无法删除当前会话","settings.title":"设置","settings.appearance":"外观","settings.model":"模型选择","settings.mode":"权限模式","settings.systemInfo":"系统信息","settings.backToChat":"返回对话","settings.tab.user":"用户级","settings.tab.project":"工作空间级","settings.group.modelAndReasoning":"模型与推理","settings.group.behavior":"行为","settings.group.memory":"记忆","settings.group.language":"语言","settings.group.advanced":"高级","settings.group.sandbox":"安全沙箱","settings.item.model":"默认模型","settings.item.model.desc":"设置默认使用的 AI 模型","settings.item.reasoningEffort":"推理努力级别","settings.item.reasoningEffort.desc":"控制模型的推理深度","settings.item.alwaysThinkingEnabled":"始终启用深度思考","settings.item.autoCompactEnabled":"自动压缩上下文","settings.item.includeCoAuthoredBy":"提交包含 Co-authored-by","settings.item.fileCheckpointingEnabled":"文件检查点","settings.item.fileCheckpointingEnabled.desc":"启用文件版本回退功能","settings.item.promptSuggestionEnabled":"提示建议","settings.item.ignoreGitIgnore":"忽略 .gitignore","settings.item.ignoreGitIgnore.desc":"搜索文件时忽略 .gitignore 规则","settings.item.deferToolLoading":"延迟加载工具","settings.item.hookOutputCollapsed":"折叠 Hook 输出","settings.item.memory.enabled":"启用记忆功能","settings.item.memory.autoMemoryEnabled":"自动记忆","settings.item.memory.autoMemoryEnabled.desc":"自动保存重要信息到记忆库","settings.item.language":"响应语言","settings.item.language.desc":"设置 AI 回复使用的语言","settings.item.cleanupPeriodDays":"聊天记录保留天数","settings.item.imageHistoryRetainRounds":"图片保留轮数","settings.item.imageHistoryRetainRounds.desc":"对话历史中保留图片的最近轮数","settings.item.env":"环境变量","settings.item.env.desc":"应用于每个会话的环境变量 (JSON)","settings.item.sandbox.enabled":"启用安全沙箱","settings.item.sandbox.enabled.desc":"在沙箱中运行 Bash 命令,限制文件和网络访问","settings.item.sandbox.autoAllowBashIfSandboxed":"沙箱内自动批准命令","settings.item.sandbox.autoAllowBashIfSandboxed.desc":"命令在沙箱中运行时自动批准","settings.loading":"加载中...","settings.saved":"已保存","settings.saveFailed":"保存失败","settings.notSet":"未设置","settings.default":"默认","settings.reset":"重置","settings.noProjectSettings":"当前工作空间暂无可配置项","settings.effort.low":"低","settings.effort.medium":"中","settings.effort.high":"高","settings.effort.xhigh":"极高","page.title":"CodeBuddy Code","tool.processExited":"[进程已退出]","tool.itemsCount":"{count} 项","tool.showAllItems":"显示全部 {count} 项","tool.moreLinesCount":"... 还有 {count} 行","tool.generatedImage":"生成的图片","tool.editedImage":"编辑后的图片","tool.imageGen":"图片生成","tool.imageEdit":"图片编辑","tool.toolSearch":"工具搜索","tool.teamCreate":"创建团队","tool.teamDelete":"删除团队","tool.taskCreate":"创建任务","tool.taskUpdate":"更新任务","tool.taskList":"任务列表","tool.taskGet":"获取任务","tool.sendMessage":"发送消息","tool.shutdown":"关闭","tool.taskCompleted":"任务完成","tool.shutdownRejected":"关闭被拒绝","tool.planResponse":"计划回复","tool.approved":"已批准","tool.rejected":"已拒绝","tool.userRejectedResult":"用户已拒绝执行此操作","tool.webSearch":"网络搜索","tool.webFetch":"网页获取","tool.saveMemory":"保存记忆","tool.askUserQuestion":"询问用户","tool.enterPlanMode":"进入计划模式","tool.exitPlanMode":"退出计划模式","tool.allowedActions":"允许的操作:","tool.skill":"技能","tool.agent":"代理","tool.failed":"失败","tool.completed":"完成","tool.toolsCount":"{count} 个工具","tool.background":"后台","tool.permissionsCount":"{count} 项权限","terminal.unknownError":"未知错误","terminal.processExited":"[进程已退出]","terminal.connectionLost":"连接已断开","terminal.wsConnectionFailed":"WebSocket 连接失败","terminal.createSessionFailed":"创建终端会话失败","terminal.reconnectFailed":"重连失败","team.title":"团队","team.activeCount":"{count} 个活跃","team.doneCount":"{count} 个完成","team.waitingForTeammates":"等待 {count} 个成员完成…","team.backToMain":"返回主对话","team.loadingHistory":"加载对话历史…","team.noHistory":"暂无对话历史","team.agentRunning":"正在运行…","team.delivered":"已送达","team.showLess":"收起","team.moreLines":"… ({count} 更多行)","team.tools":"{count} 工具","team.tokens":"{count} tokens","instance.tunnelMode":"隧道","instance.localMode":"本地","workspace.searchPlaceholder":"搜索目录...","workspace.switch":"切换","workspace.switchHere":"切换到此目录","workspace.switching":"切换中...","workspace.noResults":"没有匹配的目录","workspace.emptyDir":"此目录为空","workspace.pathPlaceholder":"输入路径或目录名...","workspace.selectDir":"在此目录创建机器人","workspace.filterPlaceholder":"过滤子目录...","workspace.recent.title":"最近工作区","workspace.recent.daysAgo":"天前","workspace.recent.hoursAgo":"小时前","workspace.recent.minutesAgo":"分钟前","workspace.recent.justNow":"刚刚","workspace.recent.remove":"移除","workspace.browseTitle":"浏览工作区","workspace.recentWorkspaces":"最近工作区","workspace.createNew":"创建新机器人","workspace.browseDir":"浏览目录","workspace.instanceLocal":"本地","workspace.instanceTunnel":"隧道","workspace.instanceCurrent":"当前","workspace.switchInstance":"切换","workspace.switchingInstance":"切换中...","workspace.switchingWithGateway":"正在准备切换...","workspace.instanceStarted":"启动于","workspace.noWorkspaces":"暂无活跃的工作区","workspace.noWorkspacesHint":"浏览目录创建新机器人","workspace.instanceCount":"{count} 个机器人","question.multiLabel":"多选","tasks.title":"推荐模版","tasks.subtitle":"选择一个模版快速创建定时任务","tasks.loading":"正在获取推荐模版...","tasks.error":"获取模版失败","tasks.retry":"重试","tasks.refresh":"刷新推荐","tasks.refreshed":"已刷新","tasks.empty":"暂无推荐模版","tasks.interval":"每 {value}","tasks.interval.1d":"每天","tasks.interval.2d":"每 2 天","tasks.interval.3d":"每 3 天","tasks.interval.1w":"每周","tasks.interval.2w":"每 2 周","tasks.interval.1m":"每月","scheduled.title":"定时任务","scheduled.subtitle":"当前会话中的活跃定时任务","scheduled.loading":"加载中...","scheduled.empty":"暂无定时任务","scheduled.emptyHint":"在对话中使用 /loop 或 CronCreate 创建","scheduled.create":"创建任务","scheduled.creating":"创建中...","scheduled.delete":"删除","scheduled.cron":"Cron 表达式","scheduled.prompt":"执行内容","scheduled.promptPlaceholder":"定时触发时要执行的提示词...","scheduled.recurring":"循环","scheduled.oneShot":"一次性","scheduled.durable":"持久化","scheduled.sessionOnly":"仅会话","scheduled.lastFired":"上次触发","plugins.title":"插件管理","plugins.installedPlugins":"已安装插件","plugins.browseMarketplace":"浏览市场","plugins.marketplaces":"插件市场","plugins.enabled":"已启用","plugins.disabled":"已禁用","plugins.enable":"启用","plugins.disable":"禁用","plugins.uninstall":"卸载","plugins.install":"安装","plugins.confirmUninstall":"确定要卸载此插件吗?","plugins.marketplace":"市场","plugins.addMarketplace":"添加市场","plugins.removeMarketplace":"移除","plugins.confirmRemoveMarketplace":"确定要移除此市场吗?","plugins.noPlugins":"暂无已安装的插件","plugins.noPluginsHint":"通过插件市场安装插件来扩展功能","plugins.noMarketplaces":"暂无配置的市场","plugins.noMarketplacesHint":"添加一个插件市场来浏览和安装插件","plugins.selectMarketplace":"选择市场","plugins.selectMarketplaceHint":"选择一个市场来浏览可用插件","plugins.marketplaceNotFound":"市场不存在","plugins.noAvailablePlugins":"该市场暂无可用插件","plugins.noAvailablePluginsHint":"请尝试添加其他市场或稍后再试","plugins.installed":"已安装","plugins.browsingMarketplace":"浏览中...","plugins.loading":"加载中...","plugins.error":"加载插件失败","plugins.retry":"重试","plugins.sourcePlaceholder":"市场地址(Git URL 或本地路径)","plugins.namePlaceholder":"市场名称(可选)","plugins.cancel":"取消","plugins.add":"添加","plugins.version":"版本","plugins.operationFailed":"操作失败","plugins.searchPlaceholder":"搜索插件...","plugins.allMarketplaces":"全部市场","plugins.noSearchResults":"没有找到匹配的插件","plugins.totalCount":"个插件","plugins.refresh":"刷新","plugins.installedLabel":"已安装","plugins.category":"分类","plugins.author":"作者","plugins.license":"许可证","plugins.homepage":"主页","plugins.repository":"仓库","plugins.source":"来源","plugins.keywords":"关键词","plugins.features":"功能","plugins.scope":"范围","plugins.scope.user":"用户","plugins.scope.project":"项目","plugins.scope.project-local":"本地","plugins.installScope.user":"为你安装(用户级)","plugins.installScope.project":"为所有协作者安装(项目级)","plugins.installScope.local":"仅在此仓库为你安装(本地级)","plugins.policyCannotRemove":"不可卸载","plugins.policyCannotSwitchoff":"不可禁用","plugins.policyCannotEdit":"不可编辑","channel.from":"来自","channel.group":"群聊","channel.replyTo":"回复来自 {source}","channel.wechat":"微信","channel.wecom":"企业微信","channel.wecomBot":"企微机器人","remoteControl.title":"远程控制","remoteControl.subtitle":"管理渠道连接","remoteControl.connectedChannels":"已连接渠道","remoteControl.noChannels":"暂无已连接渠道","remoteControl.noChannelsHint":"添加微信或企业微信渠道,或从插件市场安装更多","remoteControl.addWeChat":"添加微信机器人","remoteControl.addWeCom":"添加企微机器人","remoteControl.connect":"连接","remoteControl.disconnect":"断开","remoteControl.delete":"删除","remoteControl.add":"添加","remoteControl.connected":"已连接","remoteControl.disconnected":"未连接","remoteControl.connecting":"连接中...","remoteControl.installMore":"安装更多渠道","remoteControl.installMoreHint":"浏览插件市场,安装第三方渠道插件","remoteControl.browseMarketplace":"浏览插件市场","remoteControl.builtIn":"内置","remoteControl.plugin":"插件","remoteControl.rebind":"重新绑定","remoteControl.unbind":"解绑","remoteControl.bot":"机器人","remoteControl.default":"默认","remoteControl.next":"下一步","remoteControl.cancel":"取消","remoteControl.wecomBotIdHint":"从企业微信管理后台 → 应用管理 → AI 助手获取","remoteControl.wecomSecretHint":"输入 Secret 后按回车或点“连接”","remoteControl.fetchingQr":"正在获取二维码...","remoteControl.scanQr":"请用微信扫描二维码","sidebar.docs":"文档","docs.title":"文档中心","docs.search.placeholder":"搜索文档...","docs.search.noResults":"未找到相关文档","docs.search.resultsCount":"{count} 个结果","docs.loading":"加载中...","docs.loadError":"文档加载失败","docs.notFound":"未找到该文档","docs.apiReference":"API 文档","docs.toc":"目录","docs.retry":"重试","docs.backToList":"返回文档列表","docs.expandAll":"展开全部","docs.collapseAll":"收起全部","docs.openStandalone":"独立窗口打开","sidebar.stats":"统计","stats.title":"统计","stats.loading":"正在加载统计数据...","stats.refresh":"刷新","stats.noData":"暂无统计数据","stats.tab.overview":"概览","stats.tab.models":"模型","stats.tab.tools":"工具","stats.sessions":"会话数","stats.messages":"消息数","stats.activeDays":"活跃天数","stats.currentStreak":"当前连续","stats.longestStreak":"最长连续","stats.peakHour":"高峰时段","stats.longestSession":"最长会话","stats.favoriteModel":"最常用模型","stats.totalTokens":"总 Token","stats.timeRange":"统计范围: 最近 {days} 天","stats.heatmap.less":"少","stats.heatmap.more":"多","stats.days":"天","stats.tokensPerDay":"每日 Token 趋势","stats.allModels":"所有模型","stats.input":"输入","stats.output":"输出","stats.cacheRead":"缓存读取","stats.cacheHitRate":"缓存命中率","stats.cost":"成本","stats.topTools":"工具使用排行","stats.session.title":"当前会话","stats.session.apiDuration":"API 时长","stats.session.wallTime":"总时长","stats.session.linesAdded":"新增行","stats.session.linesDeleted":"删除行","stats.session.tokens":"Token","stats.na":"N/A","stats.heatmap.messages":"条消息","stats.funFact.moreTokens":"你已使用约 {times} 倍于《{book}》的 Token 量","stats.funFact.sameTokens":"你使用的 Token 量约等于一本《{book}》","stats.funFact.longerSession":"你最长的会话时长约为「{activity}」的 {times} 倍","sidebar.traces":"链路","traces.title":"链路追踪","traces.loading":"加载中...","traces.refresh":"刷新","traces.clear":"清空","traces.clearConfirm":"确定清空所有链路数据?","traces.noData":"暂无链路数据,发送一条消息后将自动收集","traces.selectWorker":"选择 Worker","traces.current":"当前","traces.spanCount":"{count} spans","traces.duration":"耗时","traces.status.ok":"成功","traces.status.error":"错误","traces.status.running":"运行中","traces.status.cancelled":"已取消","traces.bottleneck":"瓶颈","traces.bottleneckTip":"耗时最长,占总时间 {pct}%","traces.spanDetail":"Span 详情","traces.spanDetail.type":"类型","traces.spanDetail.duration":"耗时","traces.spanDetail.model":"模型","traces.spanDetail.tokens":"Token","traces.spanDetail.input":"输入","traces.spanDetail.output":"输出","traces.spanDetail.error":"错误","traces.spanDetail.cancelReason":"取消原因","traces.spanDetail.attributes":"属性","traces.legend.agent":"Agent","traces.legend.generation":"模型调用","traces.legend.function":"工具","traces.legend.handoff":"切换","traces.legend.guardrail":"防护","traces.back":"返回","traces.tab.timeline":"时间线","traces.tab.tree":"树形","traces.tab.flame":"火焰图","traces.tab.graph":"依赖图","traces.expandAll":"全部展开","traces.collapseAll":"全部收起","traces.search":"搜索 span...","traces.selfTime":"自身耗时","traces.spanDetail.overview":"概览","traces.spanDetail.io":"输入/输出","traces.noSpans":"无 span 数据","traces.noSpansFiltered":"当前筛选下无 span。","traces.clearFilter":"清除筛选","traces.auto":"自动","traces.auxiliaryCount":"{count} 个辅助 trace(memory、title 等)","traces.noIO":"无输入/输出数据","traces.noAttrs":"无属性","traces.io.expand":"展开","traces.io.collapse":"收起","traces.io.messages":"消息","traces.io.less":"收起","traces.io.moreChars":"+{count} 字符","traces.fit":"适应","traces.allSessions":"所有会话","traces.allInstances":"所有实例","traces.llmCalls":"{count} 次 LLM","traces.errors":"错误","traces.noErrors":"没有失败的 trace","traces.errorBanner":"检测到 {count} 个失败的 trace","traces.errorBannerCta":"点击仅查看错误 →","traces.errorSummaryTitle":"本次共有 {count} 处错误","traces.jumpToFirstError":"跳转到首个错误 span","traces.copyError":"复制错误","traces.onlyErrors":"仅错误","traces.filter.all":"全部","traces.filter.error":"错误","traces.filter.running":"运行中","traces.filter.cancelled":"已取消","traces.filter.ok":"成功","sidebar.metrics":"监控","metrics.title":"系统监控","metrics.loading":"加载指标数据...","metrics.refresh":"刷新","metrics.cpu":"CPU","metrics.memory":"内存","metrics.disk":"磁盘","metrics.cores":"核心","metrics.workers":"Workers","metrics.noWorkers":"暂无运行中的 Worker","metrics.current":"当前","metrics.uptime":"运行时长","metrics.version":"版本","sidebar.editor":"文件","editor.title":"代码编辑器","editor.loading":"加载中...","editor.loadError":"加载失败","editor.noFile":"选择一个文件开始编辑","editor.unsaved":"未保存","editor.save":"保存","editor.saveAll":"全部保存","editor.close":"关闭","editor.closeOthers":"关闭其他","editor.closeAll":"关闭全部","editor.newFile":"新建文件","editor.newFolder":"新建文件夹","editor.rename":"重命名","editor.delete":"删除","editor.refresh":"刷新","editor.emptyFolder":"空文件夹","editor.explorer":"资源管理器","editor.toggleSidebar":"切换侧边栏","editor.collapseAll":"全部折叠","editor.openFolder":"打开目录","editor.openFolderPlaceholder":"输入目录路径...","editor.parentFolder":"上级目录","editor.pin":"固定","editor.unpin":"取消固定","editor.copyPath":"复制路径","editor.copyRelativePath":"复制相对路径","editor.revealInExplorer":"在文件树中定位","editor.closeToRight":"关闭右侧","editor.closeSaved":"关闭已保存","editor.quickOpen":"快速打开文件","editor.focusExplorer":"聚焦资源管理器","editor.recentFiles":"最近文件","editor.quickOpenPlaceholder":"输入文件名以搜索...","editor.quickOpenEmpty":"没有匹配的文件","editor.quickOpenLoading":"正在加载文件列表...","editor.selected":"已选","editor.lines":"行","editor.preview":"切换到预览","editor.source":"切换到源码","sidebar.workers":"实例","workers.title":"Agent 实例管理","workers.refresh":"刷新","workers.active":"活跃 Workers","workers.empty":"没有活跃的 worker 进程","workers.daemon":"Daemon 服务","workers.daemon.running":"运行中","workers.daemon.stopped":"已停止","workers.daemon.start":"启动","workers.daemon.starting":"启动中...","workers.daemon.stop":"停止","workers.daemon.restart":"重启","workers.action.logs":"查看日志","workers.action.open":"打开","workers.action.kill":"终止","workers.action.kill.confirm":"确定要终止这个 worker 进程吗?","sidebar.logs":"日志","logs.title":"日志查看器","logs.selectWorker":"选择 Worker","logs.current":"当前","logs.search":"搜索日志...","logs.autoRefresh":"自动刷新","logs.refresh":"刷新","logs.empty":"暂无日志内容","command.btw.description":"快速提问,不打断主要 Agent 工作","command.clear.description":"开始新的对话(之前的对话仍可通过 /resume 访问)","command.context.description":"计算并显示上下文 Token 分布","command.cost.description":"显示当前会话的总费用和持续时间","command.doctor.description":"诊断和验证 CodeBuddy 的安装和设置","command.feedback.description":"打开反馈页面以报告问题或提出建议","command.gateway.description":'管理远程控制网关。子命令: "status" 查看状态, "stop" 停止网关, "token" 重新生成访问令牌, "tunnel" 启动隧道',"command.remote-control.description":"管理远程控制长连接客户端(start, stop, status, list)","command.login.description":"切换腾讯云 CodeBuddy 账号","command.logout.description":"退出 CodeBuddy Code 账号","command.plan.description":"预览当前计划文件内容","command.pr-comments.description":"获取 GitHub Pull Request 的评论","command.release-notes.description":"查看更新日志","command.review.description":"审查 Pull Request","command.skills.description":"列出可用的技能","command.todos.description":"显示当前会话的任务清单","command.reload-plugins.description":"重新加载所有插件、技能、代理、钩子和 MCP/LSP 服务器(无需重启)","command.plugin-validate.description":"验证插件目录结构和清单文件","command.init.description":"正在分析你的代码库…","command.compact.description":"清除对话历史但保留摘要在上下文中。可选: /compact [摘要指令]","command.upgrade.description":"在浏览器中打开升级页面","command.statusline.description":"设置 CodeBuddy Code 的状态栏 UI","command.security-review.description":"对当前分支的待提交变更进行安全审查","command.insights.description":"生成 AI 驱动的 CodeBuddy Code 使用模式和活动洞察","command.loop.description":"按固定间隔运行提示或斜杠命令(例如 /loop 5m /foo,默认 10m)","command.task-manager.description":"团队任务管理 - 智能任务录入、分配、追踪和分析","sidebar.changes":"变更","fileChanges.title":"变更","fileChanges.changesSection":"文件变更","fileChanges.empty":"暂无文件变更","fileChanges.showChanges":"显示文件变更","fileChanges.hideChanges":"隐藏文件变更","fileChanges.revertAll":"撤回全部","fileChanges.revertCode":"回退代码","fileChanges.revertChat":"回退对话","fileChanges.revertCodeAndChat":"回退全部","fileChanges.checkpoints":"回退点","fileChanges.noCheckpoints":"暂无回退点","filePreview.binaryNotSupported":"该文件无法在编辑器中预览","filePreview.download":"下载文件","error.viewCrashed":"页面加载出错","error.appCrashed":"应用遇到了问题","error.newChatFailed":"创建新对话失败,请重试","error.switchSessionFailed":"切换会话失败,请重试","commandPalette.placeholder":"输入命令...","commandPalette.commands":"命令","commandPalette.views":"视图","commandPalette.actions":"操作","commandPalette.noResults":"没有匹配的命令","commandPalette.newChat":"新建对话","commandPalette.toggleTheme":"切换主题","commandPalette.toggleLocale":"切换语言","commandPalette.tip":"打开命令面板","app.confirm":"确定","app.cancel":"取消","tool.toolSingular":"个工具已执行","tool.toolPlural":"个工具已执行","keybindings.title":"快捷键","keybindings.search.placeholder":"搜索快捷键... (如 submit, ctrl+enter)","keybindings.source.default":"默认","keybindings.source.user":"自定义","keybindings.record.title":"录制快捷键","keybindings.record.hint":"请按下快捷键组合...","keybindings.record.conflict":"冲突","keybindings.action.edit":"编辑","keybindings.action.reset":"重置","keybindings.action.unbind":"解绑","keybindings.reset.all":"重置全部","keybindings.noResults":"没有匹配的快捷键","keybindings.empty":"暂无快捷键","keybindings.loading":"加载中...","keybindings.ctx.Global":"全局","keybindings.ctx.Chat":"聊天输入","keybindings.ctx.InputBox":"文本输入","keybindings.ctx.Terminal":"终端","keybindings.ctx.Autocomplete":"自动补全","keybindings.ctx.Confirmation":"确认对话框","keybindings.ctx.HistorySearch":"历史搜索","keybindings.ctx.Task":"任务运行中","keybindings.ctx.Settings":"设置","keybindings.ctx.CommandPalette":"命令面板","keybindings.ctx.Select":"选择列表","keybindings.ctx.PermissionDialog":"权限对话框","keybindings.ctx.Help":"帮助","keybindings.ctx.Plugin":"插件","keybindings.ctx.DiffDialog":"Diff 对话框","keybindings.ctx.MessageSelector":"消息选择器","keybindings.ctxDesc.Global":"在任何位置都生效","keybindings.ctxDesc.Chat":"聊天输入框获得焦点时","keybindings.ctxDesc.InputBox":"文本输入框处于活跃状态时","keybindings.ctxDesc.Terminal":"终端视图处于活跃状态时","keybindings.ctxDesc.Autocomplete":"自动补全菜单显示时","keybindings.ctxDesc.Confirmation":"确认/权限对话框显示时","keybindings.ctxDesc.HistorySearch":"搜索命令历史时 (ctrl+r)","keybindings.ctxDesc.Task":"任务/代理在前台运行时","keybindings.ctxDesc.Settings":"设置面板打开时","keybindings.ctxDesc.CommandPalette":"命令面板打开时","keybindings.ctxDesc.Select":"选择/列表组件获得焦点时","keybindings.ctxDesc.PermissionDialog":"工具权限对话框显示时","keybindings.ctxDesc.Help":"帮助页面打开时","keybindings.ctxDesc.Plugin":"插件对话框打开时","keybindings.ctxDesc.DiffDialog":"Diff 对话框打开时","keybindings.ctxDesc.MessageSelector":"消息选择器 (rewind) 打开时","keybindings.act.app:interrupt":"中断","keybindings.act.app:exit":"退出","keybindings.act.app:redraw":"刷新屏幕","keybindings.act.app:toggleTodos":"切换待办事项","keybindings.act.app:toggleTranscript":"切换转录","keybindings.act.app:toggleSidebar":"切换侧边栏","keybindings.act.app:toggleTerminal":"切换终端","keybindings.act.app:commandPalette":"命令面板","keybindings.act.app:newChat":"新对话","keybindings.act.app:settings":"设置","keybindings.act.app:focusInput":"聚焦输入框","keybindings.act.app:keybindings":"快捷键设置","keybindings.act.history:search":"搜索历史","keybindings.act.history:previous":"上一条历史","keybindings.act.history:next":"下一条历史","keybindings.act.history:open":"打开历史","keybindings.act.chat:cancel":"取消","keybindings.act.chat:submit":"发送","keybindings.act.chat:newline":"换行","keybindings.act.chat:killAgents":"终止代理","keybindings.act.chat:cycleMode":"切换模式","keybindings.act.chat:modelPicker":"选择模型","keybindings.act.chat:thinkingToggle":"切换思考","keybindings.act.chat:undo":"撤销","keybindings.act.chat:externalEditor":"外部编辑器","keybindings.act.chat:stash":"暂存","keybindings.act.chat:imagePaste":"粘贴图片","keybindings.act.autocomplete:accept":"接受补全","keybindings.act.autocomplete:dismiss":"关闭补全","keybindings.act.autocomplete:previous":"上一项","keybindings.act.autocomplete:next":"下一项","keybindings.act.confirm:yes":"确认","keybindings.act.confirm:no":"取消","keybindings.act.confirm:previous":"上一项","keybindings.act.confirm:next":"下一项","keybindings.act.confirm:toggle":"切换选中","keybindings.act.confirm:toggleExplanation":"切换说明","keybindings.act.task:background":"后台运行","keybindings.act.historySearch:next":"下一条","keybindings.act.historySearch:accept":"接受","keybindings.act.historySearch:cancel":"取消","keybindings.act.historySearch:execute":"执行","keybindings.act.settings:close":"关闭设置","keybindings.act.settings:search":"搜索设置","keybindings.act.select:previous":"上一项","keybindings.act.select:next":"下一项","keybindings.act.select:accept":"选择","keybindings.act.select:cancel":"取消","keybindings.act.commandPalette:close":"关闭面板","keybindings.act.commandPalette:execute":"执行命令","keybindings.act.commandPalette:previous":"上一项","keybindings.act.commandPalette:next":"下一项","keybindings.act.permission:toggleDebug":"切换调试","keybindings.act.diff:dismiss":"关闭 Diff","keybindings.act.diff:previousFile":"上一个文件","keybindings.act.diff:nextFile":"下一个文件","keybindings.act.diff:viewDetails":"查看详情","keybindings.act.plugin:toggle":"切换插件","keybindings.act.plugin:install":"安装插件","keybindings.act.help:dismiss":"关闭帮助","keybindings.act.transcript:exit":"退出转录","keybindings.act.transcript:toggleShowAll":"显示全部","keybindings.act.messageSelector:up":"向上","keybindings.act.messageSelector:down":"向下","keybindings.act.messageSelector:top":"到顶部","keybindings.act.messageSelector:bottom":"到底部","keybindings.act.messageSelector:select":"选择","common.close":"关闭","changes.revert":"还原","changes.revertDirectory":"还原目录","message.clickToEnlarge":"点击放大","channel.botIdPlaceholder":"输入 Bot ID","channel.secretPlaceholder":"输入 Secret","filePreview.zoomOut":"缩小","filePreview.zoomIn":"放大","filePreview.fitToWindow":"适应窗口","filePreview.actualSize":"实际大小 (1:1)","filePreview.pdfPreview":"PDF 预览","goal.status.usage":`用法:/goal <条件>
|
|
637
|
-
示例:/goal 所有测试通过`,"goal.status.tooLong":"目标条件长度上限 {max} 字符(当前 {actual})","goal.status.hooksDisabled":"/goal 在 Hooks 被禁用时不可用(settings 中关闭了 disableAllHooks 或 allowManagedHooksOnly)。","goal.status.set":"已设置目标:{condition}","goal.status.setReplaced":"替换目标:{prev} → {condition}","goal.status.cleared":"已清除目标:{prev}","goal.status.noGoal":"当前无目标","goal.status.active":"当前目标:{condition}","goal.progress.title":"目标尚未达成… 继续","goal.progress.expand":"点击展开","goal.progress.condition":"目标","goal.progress.reason":"原因","goal.recap.active":"当前活跃目标","goal.recap.achieved":"目标已达成","goal.recap.impossible":"目标无法达成","goal.recap.empty.title":"暂未设置目标","goal.recap.empty.hint":"使用 /goal <条件> 设置一个会话级停止条件。","goal.recap.empty.example":"示例:/goal 所有测试通过","goal.recap.footer.setAnother":"/goal <条件>","goal.recap.footer.toSetAnother":" 设置新目标 · ","goal.recap.footer.escDismiss":"关闭","goal.recap.stats.turn":"轮","goal.recap.stats.turns":"轮","goal.recap.stats.token":"token","goal.recap.stats.tokens":"tokens"},en:{"app.connecting":"Connecting to CodeBuddy Code...","app.connectFailed":"Connection failed","app.retry":"Retry","app.pwa.newVersion":"A new Web UI version is available","app.pwa.reloadNow":"Reload now","app.pwa.reloadLater":"Later","app.pwa.reloadedAfterIdle":"Updated to new version","chat.empty.title":"CodeBuddy Code","chat.empty.subtitle":"How can I help you today?","chat.empty.slogan":"Claw Your Ideas . Into Reality","chat.empty.tag.slides":"Slide Generation","chat.empty.tag.research":"Deep Research","chat.empty.tag.docs":"Document Processing","chat.empty.tag.data":"Data Analysis","chat.thinking":"Thinking","chat.waitingPermission":"Waiting for permission","chat.waitingUser":"Waiting for user","chat.error":"Error","chat.sessionEnded":"Session ended","chat.stopped":"Stopped","chat.error.refusal":"The agent refused to continue execution. This may be due to content policy restrictions or other limitations.","chat.error.network":"Network connection failed or the service is temporarily unavailable. Please try again later.","chat.error.auth":"Authentication failed or insufficient permissions. Please sign in again and retry.","chat.error.quota":"Quota limit reached or too many requests. Please try again later.","chat.error.modelService":"The model service returned an error. Please retry or try again later.","chat.error.maxTokens":"Response was truncated due to reaching the maximum token limit. You may continue the conversation or ask for a more concise response.","chat.error.maxTurnRequests":"The maximum number of model requests per turn has been exceeded. You may send a new message to continue.","chat.newChat":"New Chat","chat.disclaimer":"Answers generated by AI are for reference only","chat.compacted":"Conversation compacted","chat.compacting":"Compacting conversation...","chat.compactCancelled":"Compaction cancelled","phase.preparing":"Preparing","phase.modelRequesting":"Waiting for model","phase.modelStreaming":"Streaming","phase.modelDone":"Processing","phase.toolExecuting":"Running tool","phase.modelStreamingTool":"Writing","phase.retrying":"Retrying","progress.compacting":"Compacting context","input.placeholder":"Start from an idea...","input.placeholderRunning":"Messages will be queued...","input.placeholderPending":"Please handle the permission request first...","input.send":"Send (Enter)","input.stop":"Stop","input.thinking":"Thinking","input.deepThinking":"Deep Thinking","input.promptFailed":"Prompt failed","input.sendQueued":"Send queued (Enter)","input.dropHint":"Drop files here","input.addImage":"Add image","input.addFile":"Add file","input.imageTooLarge":"Image must be under 10MB","input.tooManyImages":"Up to 5 images allowed","input.fileTooLarge":"File must be under 1MB","input.tooManyFiles":"Up to 10 files allowed","input.menu.image":"Image","input.menu.file":"File","input.newline":"New line","input.contextMenu.newline":"New line","input.contextMenu.send":"Send","queue.more":" more queued","status.running":"Running","tool.writeFile":"Write file","tool.readFile":"Read file","tool.execute":"Execute","tool.searchFiles":"Search files","tool.searchContent":"Search content","tool.fetchWeb":"Fetch web","tool.searchWeb":"Search web","tool.defaultName":"Tool","tool.moreItems":"... {count} more","interruption.title":"Permission Required","interruption.tool":"Tool","interruption.allow":"Allow","interruption.allowAll":"Allow All","interruption.deny":"Deny","interruption.approved":"Approved","interruption.denied":"Denied","interruption.edits":"{count} edits","interruption.yes":"Yes","interruption.keepPlanning":"No, keep planning","interruption.exitPlanMode":"Exit plan mode","interruption.readyToCode":"Ready to code?","theme.light":"Light","theme.dark":"Dark","theme.system":"System","locale.zh":"Chinese","locale.en":"English","locale.system":"System","sidebar.nav.plugins":"Plugins","sidebar.nav.tasks":"Tasks","sidebar.search.placeholder":"Search...","sidebar.chatHistory":"Chat History","sidebar.workspace":"Workspace","sidebar.connectionStatus":"Connection Status","sidebar.status":"Status","sidebar.sessionId":"Session ID","sidebar.notConnected":"Not connected","sidebar.modelSelection":"Model Selection","sidebar.noModels":"No models available","sidebar.environment":"Environment","sidebar.cwd":"Working Directory","sidebar.os":"OS","sidebar.nodeVersion":"Node.js","sidebar.gatewayMode":"Gateway Mode","sidebar.tunnelUrl":"Tunnel URL","sidebar.clickToCopy":"Click to copy","sidebar.copied":"Copied","sidebar.permissionMode":"Permission Mode","sidebar.noModes":"No modes available","sidebar.preferences":"Preferences","sidebar.keybindings":"Keybindings","sidebar.group.workspace":"Workspace","sidebar.group.observability":"Observability","sidebar.group.preferences":"Preferences","bottomSheet.attachments":"Attach","bottomSheet.navigation":"Navigate","sidebar.theme":"Theme","sidebar.language":"Language","sidebar.user":"User","sidebar.authMethod":"Password","sidebar.noAuth":"No Auth","sidebar.version":"Remote UI v1.0","connection.connected":"Connected","connection.connecting":"Connecting","connection.disconnected":"Disconnected","connection.error":"Error","message.copyToClipboard":"Copy to clipboard","message.copied":"Copied","message.copy":"Copy","message.assistantName":"CodeBuddy Code","thinking.title":"Thinking Process","thinking.thinking":"Thinking","thinking.done":"Thought for","thinking.seconds":" {n}s","thinking.expand":"Expand","thinking.collapse":"Collapse","diff.noChanges":"No changes","login.title":"CodeBuddy Remote Control","login.subtitle":"Enter the password shown in your terminal","login.placeholder":"Password","login.submit":"Login","login.error.incorrect":"Incorrect password","login.error.rateLimit":"Too many login attempts. Please try again later.","login.error.required":"Password is required","login.hint.password":"Tip: The password is displayed when the server starts.","login.hint.urlAuth":"You can also use <code>?password=xxx</code> to login automatically.","login.hint.disable":'Or set <code>gateway.auth: "none"</code> in <code>settings.json</code> under the CodeBuddy config directory (defaults to <code>~/.codebuddy</code>; override via the <code>CODEBUDDY_CONFIG_DIR</code> environment variable) to disable.',"login.slogan":"Claw Your Ideas . Into Reality","login.tagline":"Triggered Anywhere, Completed Locally.","login.privacy":"Privacy Policy","login.terms":"Terms of Service","sidebar.interactionMode":"Interaction Mode","sidebar.chatMode":"Chat","sidebar.terminalMode":"Terminal","sidebar.canvas":"Canvas","canvas.title":"Infinite Canvas","canvas.addTerminal":"Add Terminal","canvas.zoomIn":"Zoom In","canvas.zoomOut":"Zoom Out","canvas.fitView":"Fit View","canvas.resetView":"Reset View","canvas.empty":"Click the + button in the toolbar to add a terminal","canvas.openStandalone":"Open canvas in new window","canvas.tileMenu.close":"Close","canvas.tileMenu.duplicate":"Duplicate Terminal","canvas.tileMenu.maximize":"Maximize","canvas.tileMenu.minimize":"Minimize","canvas.tileMenu.restore":"Restore","canvas.tileMenu.openStandalone":"Open in new window","canvas.standalone.missingPaneId":"Missing pane ID","canvas.defaultTitle":"Terminal","terminal.connecting":"Connecting terminal...","terminal.title":"Terminal","terminal.disconnected":"Terminal disconnected","terminal.error":"Terminal connection failed","terminal.reconnect":"Reconnect","terminal.splitHorizontal":"Split Right","terminal.splitVertical":"Split Down","terminal.closePane":"Close Terminal","terminal.maxPanes":"Max panes reached","sidebar.instances":"Instances","sidebar.activeInstances":"active instances","sidebar.manageInstances":"Manage Instances","sidebar.remoteControl":"Channels","instance.title":"Instance List","instance.switch":"Instance","instance.switchTitle":"Switch Instance","instance.current":"Current","instance.manual":"Manual","instance.switchTo":"Switch to this instance","instance.manage":"Manage Instances","instance.managerTitle":"Instance Manager","instance.addInstance":"Add Instance","instance.name":"Instance Name","instance.namePlaceholder":"Custom instance name (optional, defaults to directory name)","instance.url":"Instance URL","instance.urlPlaceholder":"https://example.trycloudflare.com","instance.password":"Password","instance.optional":"Optional","instance.passwordPlaceholder":"Access password","instance.cancel":"Cancel","instance.add":"Add","instance.remove":"Remove this instance","instance.noInstances":"No other instances","instance.noInstancesHint":"Start more CodeBuddy Code instances or add remote instances manually","instance.cwd":"Working Directory","instance.topic":"Topic","instance.startedAt":"Started at","instance.local":"Local","instance.tunnel":"Tunnel","instance.uptime.days":"d ago","instance.uptime.hours":"h ago","instance.uptime.minutes":"m ago","instance.uptime.justNow":"Just now","instance.addError":"Failed to add instance","instance.removeError":"Failed to remove instance","instance.copyUrl":"Copy URL","instance.copied":"Copied","instance.subtitle":"Manage and switch between instances","instance.refresh":"Refresh","instance.refreshed":"Refreshed","instance.loading":"Loading instances...","instance.error":"Failed to load instances","instance.retry":"Retry","question.multiple":"multiple","question.customAnswer":"Or type a custom answer...","question.reviewAnswers":"Review answers","question.singleTitle":"Question","question.titleWithCount":"Questions ({count})","question.reviewTab":"Review","question.next":"Next","question.submit":"Submit","question.cancel":"Cancel","question.answered":"Answered","question.cancelled":"Question cancelled","todo.title":"Tasks","todo.executing":"Task {n} executing","todo.untitled":"Untitled","history.title":"Sessions","history.description":"Click a session to switch to that conversation","history.noData":"No sessions","history.noDataHint":"Start a new conversation","history.backToChat":"Back to Chat","history.loading":"Loading...","history.loadError":"Failed to load","history.retry":"Retry","history.current":"Current","history.messages":"{count} messages","history.delete":"Delete","history.deleteConfirm":"Are you sure you want to delete this session?","history.deleteCancel":"Cancel","history.deleteOk":"Delete","history.rename":"Rename","history.renameTitle":"Rename Session","history.renamePlaceholder":"Enter new name","history.renameCancel":"Cancel","history.renameOk":"OK","history.cannotDeleteCurrent":"Cannot delete current session","settings.title":"Preferences","settings.appearance":"Appearance","settings.model":"Model Selection","settings.mode":"Permission Mode","settings.systemInfo":"System Info","settings.backToChat":"Back to Chat","settings.tab.user":"User","settings.tab.project":"Project","settings.group.modelAndReasoning":"Model & Reasoning","settings.group.behavior":"Behavior","settings.group.memory":"Memory","settings.group.language":"Language","settings.group.advanced":"Advanced","settings.group.sandbox":"Security Sandbox","settings.item.model":"Default Model","settings.item.model.desc":"Set the default AI model","settings.item.reasoningEffort":"Reasoning Effort","settings.item.reasoningEffort.desc":"Control model reasoning depth","settings.item.alwaysThinkingEnabled":"Always Enable Thinking","settings.item.autoCompactEnabled":"Auto Compact Context","settings.item.includeCoAuthoredBy":"Include Co-authored-by","settings.item.fileCheckpointingEnabled":"File Checkpointing","settings.item.fileCheckpointingEnabled.desc":"Enable file version rollback","settings.item.promptSuggestionEnabled":"Prompt Suggestions","settings.item.ignoreGitIgnore":"Ignore .gitignore","settings.item.ignoreGitIgnore.desc":"Ignore .gitignore rules when searching","settings.item.deferToolLoading":"Defer Tool Loading","settings.item.hookOutputCollapsed":"Collapse Hook Output","settings.item.memory.enabled":"Enable Memory","settings.item.memory.autoMemoryEnabled":"Auto Memory","settings.item.memory.autoMemoryEnabled.desc":"Auto-save important info to memory","settings.item.language":"Response Language","settings.item.language.desc":"Language for AI responses","settings.item.cleanupPeriodDays":"Chat History Retention (days)","settings.item.imageHistoryRetainRounds":"Image Retention Rounds","settings.item.imageHistoryRetainRounds.desc":"Rounds to retain images in history","settings.item.env":"Environment Variables","settings.item.env.desc":"Variables applied to each session (JSON)","settings.item.sandbox.enabled":"Enable Sandbox","settings.item.sandbox.enabled.desc":"Run Bash commands in sandbox, restrict file and network access","settings.item.sandbox.autoAllowBashIfSandboxed":"Auto-approve in Sandbox","settings.item.sandbox.autoAllowBashIfSandboxed.desc":"Auto-approve commands when running in sandbox","settings.loading":"Loading...","settings.saved":"Saved","settings.saveFailed":"Save failed","settings.notSet":"Not set","settings.default":"Default","settings.reset":"Reset","settings.noProjectSettings":"No project-level settings available","settings.effort.low":"Low","settings.effort.medium":"Medium","settings.effort.high":"High","settings.effort.xhigh":"Extra High","page.title":"CodeBuddy Code","tool.processExited":"[Process exited]","tool.itemsCount":"{count} items","tool.showAllItems":"Show all {count} items","tool.moreLinesCount":"... {count} more lines","tool.generatedImage":"Generated image","tool.editedImage":"Edited image","tool.imageGen":"ImageGen","tool.imageEdit":"ImageEdit","tool.toolSearch":"ToolSearch","tool.teamCreate":"TeamCreate","tool.teamDelete":"TeamDelete","tool.taskCreate":"TaskCreate","tool.taskUpdate":"TaskUpdate","tool.taskList":"TaskList","tool.taskGet":"TaskGet","tool.sendMessage":"SendMessage","tool.shutdown":"Shutdown","tool.taskCompleted":"Task completed","tool.shutdownRejected":"Shutdown rejected","tool.planResponse":"Plan response","tool.approved":"approved","tool.rejected":"rejected","tool.userRejectedResult":"User rejected this tool use","tool.webSearch":"WebSearch","tool.webFetch":"WebFetch","tool.saveMemory":"SaveMemory","tool.askUserQuestion":"AskUserQuestion","tool.enterPlanMode":"Enter Plan Mode","tool.exitPlanMode":"Exit Plan Mode","tool.allowedActions":"Allowed actions:","tool.skill":"Skill","tool.agent":"Agent","tool.failed":"failed","tool.completed":"completed","tool.toolsCount":"{count} tools","tool.background":"background","tool.permissionsCount":"{count} permissions","terminal.unknownError":"Unknown error","terminal.processExited":"[Process exited]","terminal.connectionLost":"Connection lost","terminal.wsConnectionFailed":"WebSocket connection failed","terminal.createSessionFailed":"Failed to create terminal session","terminal.reconnectFailed":"Reconnect failed","team.title":"Team","team.activeCount":"{count} active","team.doneCount":"{count} done","team.waitingForTeammates":"Waiting for {count} teammate{s}…","team.backToMain":"Back to main chat","team.loadingHistory":"Loading conversation…","team.noHistory":"No conversation history yet","team.agentRunning":"Agent is running…","team.delivered":"Delivered","team.showLess":"Show less","team.moreLines":"… ({count} more lines)","team.tools":"{count} tools","team.tokens":"{count} tokens","instance.tunnelMode":"Tunnel","instance.localMode":"Local","workspace.searchPlaceholder":"Search directories...","workspace.switch":"Switch","workspace.switchHere":"Switch to this directory","workspace.switching":"Switching...","workspace.noResults":"No matching directories","workspace.emptyDir":"This directory is empty","workspace.pathPlaceholder":"Enter path or directory name...","workspace.selectDir":"Create bot in this directory","workspace.filterPlaceholder":"Filter subdirectories...","workspace.recent.title":"Recent Workspaces","workspace.recent.daysAgo":"d ago","workspace.recent.hoursAgo":"h ago","workspace.recent.minutesAgo":"m ago","workspace.recent.justNow":"Just now","workspace.recent.remove":"Remove","workspace.browseTitle":"Browse Workspaces","workspace.recentWorkspaces":"Recent Workspaces","workspace.createNew":"Create New Bot","workspace.browseDir":"Browse Directory","workspace.instanceLocal":"Local","workspace.instanceTunnel":"Tunnel","workspace.instanceCurrent":"Current","workspace.switchInstance":"Switch","workspace.switchingInstance":"Switching...","workspace.switchingWithGateway":"Preparing to switch...","workspace.instanceStarted":"Started","workspace.noWorkspaces":"No active workspaces","workspace.noWorkspacesHint":"Browse directories to create a new bot","workspace.instanceCount":"{count} bots","question.multiLabel":"multi","tasks.title":"Recommended Templates","tasks.subtitle":"Select a template to create a scheduled task","tasks.loading":"Loading recommended templates...","tasks.error":"Failed to load templates","tasks.retry":"Retry","tasks.refresh":"Refresh","tasks.refreshed":"Refreshed","tasks.empty":"No templates available","tasks.interval":"Every {value}","tasks.interval.1d":"Daily","tasks.interval.2d":"Every 2 days","tasks.interval.3d":"Every 3 days","tasks.interval.1w":"Weekly","tasks.interval.2w":"Every 2 weeks","tasks.interval.1m":"Monthly","scheduled.title":"Scheduled Tasks","scheduled.subtitle":"Active scheduled tasks in the current session","scheduled.loading":"Loading...","scheduled.empty":"No scheduled tasks","scheduled.emptyHint":"Use /loop or CronCreate in chat to create one","scheduled.create":"Create Task","scheduled.creating":"Creating...","scheduled.delete":"Delete","scheduled.cron":"Cron Expression","scheduled.prompt":"Prompt","scheduled.promptPlaceholder":"Prompt to execute on each fire...","scheduled.recurring":"Recurring","scheduled.oneShot":"One-shot","scheduled.durable":"Durable","scheduled.sessionOnly":"Session-only","scheduled.lastFired":"Last fired","plugins.title":"Plugins","plugins.installedPlugins":"Installed Plugins","plugins.browseMarketplace":"Browse Marketplace","plugins.marketplaces":"Marketplaces","plugins.enabled":"Enabled","plugins.disabled":"Disabled","plugins.enable":"Enable","plugins.disable":"Disable","plugins.uninstall":"Uninstall","plugins.install":"Install","plugins.confirmUninstall":"Are you sure you want to uninstall this plugin?","plugins.marketplace":"Marketplace","plugins.addMarketplace":"Add Marketplace","plugins.removeMarketplace":"Remove","plugins.confirmRemoveMarketplace":"Are you sure you want to remove this marketplace?","plugins.noPlugins":"No plugins installed","plugins.noPluginsHint":"Install plugins from a marketplace to extend functionality","plugins.noMarketplaces":"No marketplaces configured","plugins.noMarketplacesHint":"Add a plugin marketplace to browse and install plugins","plugins.selectMarketplace":"Select Marketplace","plugins.selectMarketplaceHint":"Select a marketplace to browse available plugins","plugins.marketplaceNotFound":"Marketplace not found","plugins.noAvailablePlugins":"No available plugins in this marketplace","plugins.noAvailablePluginsHint":"Try adding other marketplaces or check back later","plugins.installed":"Installed","plugins.browsingMarketplace":"Loading...","plugins.loading":"Loading...","plugins.error":"Failed to load plugins","plugins.retry":"Retry","plugins.sourcePlaceholder":"Marketplace URL (Git URL or local path)","plugins.namePlaceholder":"Marketplace name (optional)","plugins.cancel":"Cancel","plugins.add":"Add","plugins.version":"Version","plugins.operationFailed":"Operation failed","plugins.searchPlaceholder":"Search plugins...","plugins.allMarketplaces":"All Marketplaces","plugins.noSearchResults":"No matching plugins found","plugins.totalCount":"plugins","plugins.refresh":"Refresh","plugins.installedLabel":"Installed","plugins.category":"Category","plugins.author":"Author","plugins.license":"License","plugins.homepage":"Homepage","plugins.repository":"Repository","plugins.source":"Source","plugins.keywords":"Keywords","plugins.features":"Features","plugins.scope":"Scope","plugins.scope.user":"User","plugins.scope.project":"Project","plugins.scope.project-local":"Local","plugins.installScope.user":"Install for you (user scope)","plugins.installScope.project":"Install for all collaborators (project scope)","plugins.installScope.local":"Install for you, in this repo only (local scope)","plugins.policyCannotRemove":"Cannot be uninstalled","plugins.policyCannotSwitchoff":"Cannot be disabled","plugins.policyCannotEdit":"Cannot be edited","channel.from":"From","channel.group":"Group","channel.replyTo":"Reply to {source}","channel.wechat":"WeChat","channel.wecom":"WeCom","channel.wecomBot":"WeCom Bot","remoteControl.title":"Remote Control","remoteControl.subtitle":"Manage channel connections","remoteControl.connectedChannels":"Connected Channels","remoteControl.noChannels":"No channels connected","remoteControl.noChannelsHint":"Add a WeChat or WeCom channel, or install more from the marketplace","remoteControl.addWeChat":"Add WeChat Bot","remoteControl.addWeCom":"Add WeCom Bot","remoteControl.connect":"Connect","remoteControl.disconnect":"Disconnect","remoteControl.delete":"Delete","remoteControl.add":"Add","remoteControl.connected":"Connected","remoteControl.disconnected":"Disconnected","remoteControl.connecting":"Connecting...","remoteControl.installMore":"Install More Channels","remoteControl.installMoreHint":"Browse the plugin marketplace for third-party channel plugins","remoteControl.browseMarketplace":"Browse Marketplace","remoteControl.builtIn":"Built-in","remoteControl.plugin":"Plugin","remoteControl.rebind":"Rebind","remoteControl.unbind":"Unbind","remoteControl.bot":" Bot","remoteControl.default":"Default ","remoteControl.next":"Next","remoteControl.cancel":"Cancel","remoteControl.wecomBotIdHint":"From: WeCom Admin → Apps → AI Assistant","remoteControl.wecomSecretHint":"Enter Secret and press Enter or click Connect","remoteControl.fetchingQr":"Fetching QR code...","remoteControl.scanQr":"Scan QR code with WeChat","sidebar.docs":"Docs","docs.title":"Documentation","docs.search.placeholder":"Search docs...","docs.search.noResults":"No matching documents found","docs.search.resultsCount":"{count} results","docs.loading":"Loading...","docs.loadError":"Failed to load document","docs.notFound":"Document not found","docs.apiReference":"API Reference","docs.toc":"On this page","docs.retry":"Retry","docs.backToList":"Back to docs","docs.expandAll":"Expand all","docs.collapseAll":"Collapse all","docs.openStandalone":"Open in new window","sidebar.stats":"Statistics","stats.title":"Statistics","stats.loading":"Loading statistics...","stats.refresh":"Refresh","stats.noData":"No statistics available","stats.tab.overview":"Overview","stats.tab.models":"Models","stats.tab.tools":"Tools","stats.sessions":"Sessions","stats.messages":"Messages","stats.activeDays":"Active Days","stats.currentStreak":"Current Streak","stats.longestStreak":"Longest Streak","stats.peakHour":"Peak Hour","stats.longestSession":"Longest Session","stats.favoriteModel":"Favorite Model","stats.totalTokens":"Total Tokens","stats.timeRange":"Stats from the last {days} days","stats.heatmap.less":"Less","stats.heatmap.more":"More","stats.days":"days","stats.tokensPerDay":"Tokens per Day","stats.allModels":"All Models","stats.input":"Input","stats.output":"Output","stats.cacheRead":"Cache Read","stats.cacheHitRate":"Cache Hit Rate","stats.cost":"Cost","stats.topTools":"Top Tools","stats.session.title":"Current Session","stats.session.apiDuration":"API Duration","stats.session.wallTime":"Wall Time","stats.session.linesAdded":"Lines Added","stats.session.linesDeleted":"Lines Deleted","stats.session.tokens":"Tokens","stats.na":"N/A","stats.heatmap.messages":"messages","stats.funFact.moreTokens":"You've used ~{times}x more tokens than {book}","stats.funFact.sameTokens":"You've used the same number of tokens as {book}","stats.funFact.longerSession":"Your longest session is ~{times}x longer than {activity}","sidebar.traces":"Traces","traces.title":"Traces","traces.loading":"Loading...","traces.refresh":"Refresh","traces.clear":"Clear","traces.clearConfirm":"Clear all trace data?","traces.noData":"No trace data yet. Send a message and traces will be collected automatically.","traces.selectWorker":"Select Worker","traces.current":"current","traces.spanCount":"{count} spans","traces.duration":"Duration","traces.status.ok":"OK","traces.status.error":"Error","traces.status.running":"Running","traces.status.cancelled":"Cancelled","traces.bottleneck":"Bottleneck","traces.bottleneckTip":"Slowest span, {pct}% of total","traces.spanDetail":"Span Detail","traces.spanDetail.type":"Type","traces.spanDetail.duration":"Duration","traces.spanDetail.model":"Model","traces.spanDetail.tokens":"Tokens","traces.spanDetail.input":"Input","traces.spanDetail.output":"Output","traces.spanDetail.error":"Error","traces.spanDetail.cancelReason":"Cancel reason","traces.spanDetail.attributes":"Attributes","traces.legend.agent":"Agent","traces.legend.generation":"Generation","traces.legend.function":"Function","traces.legend.handoff":"Handoff","traces.legend.guardrail":"Guardrail","traces.back":"Back","traces.tab.timeline":"Timeline","traces.tab.tree":"Tree","traces.tab.flame":"Flame","traces.tab.graph":"Graph","traces.expandAll":"Expand All","traces.collapseAll":"Collapse All","traces.search":"Search spans...","traces.selfTime":"Self Time","traces.spanDetail.overview":"Overview","traces.spanDetail.io":"Input/Output","traces.noSpans":"No spans","traces.noSpansFiltered":"No spans match the current filter.","traces.clearFilter":"Clear filter","traces.auto":"auto","traces.auxiliaryCount":"{count} auxiliary traces (memory, title, etc.)","traces.noIO":"No input/output data","traces.noAttrs":"No attributes","traces.io.expand":"Expand","traces.io.collapse":"Collapse","traces.io.messages":"Messages","traces.io.less":"Less","traces.io.moreChars":"+{count} chars","traces.fit":"Fit","traces.allSessions":"All sessions","traces.allInstances":"All instances","traces.llmCalls":"{count} LLM","traces.errors":"errors","traces.noErrors":"No failed traces","traces.errorBanner":"{count} failed trace(s) detected","traces.errorBannerCta":"Show only errors →","traces.errorSummaryTitle":"{count} error(s) in this trace","traces.jumpToFirstError":"Jump to first error span","traces.copyError":"Copy","traces.onlyErrors":"Errors only","traces.filter.all":"All","traces.filter.error":"Error","traces.filter.running":"Running","traces.filter.cancelled":"Cancelled","traces.filter.ok":"OK","sidebar.metrics":"Metrics","metrics.title":"System Metrics","metrics.loading":"Loading metrics...","metrics.refresh":"Refresh","metrics.cpu":"CPU","metrics.memory":"Memory","metrics.disk":"Disk","metrics.cores":"cores","metrics.workers":"Workers","metrics.noWorkers":"No running workers","metrics.current":"Current","metrics.uptime":"Uptime","metrics.version":"Version","sidebar.editor":"Files","editor.title":"Code Editor","editor.loading":"Loading...","editor.loadError":"Failed to load","editor.noFile":"Select a file to start editing","editor.unsaved":"Unsaved","editor.save":"Save","editor.saveAll":"Save All","editor.close":"Close","editor.closeOthers":"Close Others","editor.closeAll":"Close All","editor.newFile":"New File","editor.newFolder":"New Folder","editor.rename":"Rename","editor.delete":"Delete","editor.refresh":"Refresh","editor.emptyFolder":"Empty folder","editor.explorer":"EXPLORER","editor.toggleSidebar":"Toggle Sidebar","editor.collapseAll":"Collapse All","editor.openFolder":"Open Folder","editor.openFolderPlaceholder":"Enter directory path...","editor.parentFolder":"Parent Folder","editor.pin":"Pin","editor.unpin":"Unpin","editor.copyPath":"Copy Path","editor.copyRelativePath":"Copy Relative Path","editor.revealInExplorer":"Reveal in Explorer","editor.closeToRight":"Close to the Right","editor.closeSaved":"Close Saved","editor.quickOpen":"Quick Open File","editor.focusExplorer":"Focus Explorer","editor.recentFiles":"Recent Files","editor.quickOpenPlaceholder":"Type filename to search...","editor.quickOpenEmpty":"No matching files","editor.quickOpenLoading":"Loading file list...","editor.selected":"selected","editor.lines":"lines","editor.preview":"Switch to Preview","editor.source":"Switch to Source","sidebar.workers":"Workers","workers.title":"Worker Processes","workers.refresh":"Refresh","workers.active":"Active Workers","workers.empty":"No active worker processes","workers.daemon":"Daemon","workers.daemon.running":"Running","workers.daemon.stopped":"Stopped","workers.daemon.start":"Start","workers.daemon.starting":"Starting...","workers.daemon.stop":"Stop","workers.daemon.restart":"Restart","workers.action.logs":"Logs","workers.action.open":"Open","workers.action.kill":"Kill","workers.action.kill.confirm":"Are you sure you want to kill this worker process?","sidebar.logs":"Logs","logs.title":"Log Viewer","logs.selectWorker":"Select Worker","logs.current":"current","logs.search":"Search logs...","logs.autoRefresh":"Auto Refresh","logs.refresh":"Refresh","logs.empty":"No log content","command.btw.description":"Ask a quick side question without interrupting the main Agent work","command.clear.description":"Start a fresh conversation (previous chats remain accessible via /resume)","command.context.description":"Calculate and display context token distribution","command.cost.description":"Show the total cost and duration of the current session","command.doctor.description":"Diagnose and verify your CodeBuddy installation and settings","command.feedback.description":"Open the issue feedback page to report bugs or suggest features","command.gateway.description":'Manage the remote control gateway. Subcommands: "status" to show current status, "stop" to stop the gateway, "token" to regenerate access token, "tunnel" to start with tunnel',"command.remote-control.description":"Manage remote control long connection clients (start, stop, status, list)","command.login.description":"Switch Tencent Cloud CodeBuddy accounts","command.logout.description":"Sign out from your CodeBuddy Code account","command.plan.description":"Preview the current plan file content","command.pr-comments.description":"Get comments from a GitHub pull request","command.release-notes.description":"View release notes","command.review.description":"Review a pull request","command.skills.description":"List available skills","command.todos.description":"Display the current session's todo list","command.reload-plugins.description":"Reload all plugins, skills, agents, hooks, and MCP/LSP servers without restarting","command.plugin-validate.description":"Validate a plugin directory structure and manifest","command.init.description":"Analyzing your codebase…","command.compact.description":"Clear conversation history but keep a summary in context. Optional: /compact [instructions for summarization]","command.upgrade.description":"Open upgrade page in browser","command.statusline.description":"Set up Codebuddy Code's status line UI","command.security-review.description":"Complete a security review of the pending changes on the current branch","command.insights.description":"Generate AI-powered insights about your CodeBuddy Code usage patterns and activity","command.loop.description":"Run a prompt or slash command on a recurring interval (e.g. /loop 5m /foo, defaults to 10m)","command.task-manager.description":"Team task management - Smart task entry, assignment, tracking and analysis","sidebar.changes":"Changes","fileChanges.title":"Changes","fileChanges.changesSection":"FILE CHANGES","fileChanges.empty":"No file changes","fileChanges.showChanges":"Show file changes","fileChanges.hideChanges":"Hide file changes","fileChanges.revertAll":"Revert all","fileChanges.revertCode":"Revert code","fileChanges.revertChat":"Revert chat","fileChanges.revertCodeAndChat":"Revert all","fileChanges.checkpoints":"Checkpoints","fileChanges.noCheckpoints":"No checkpoints","filePreview.binaryNotSupported":"This file cannot be previewed in the editor","filePreview.download":"Download","error.viewCrashed":"This view encountered an error","error.appCrashed":"Something went wrong","error.newChatFailed":"Failed to create new chat, please try again","error.switchSessionFailed":"Failed to switch session, please try again","commandPalette.placeholder":"Type a command...","commandPalette.commands":"Commands","commandPalette.views":"Views","commandPalette.actions":"Actions","commandPalette.noResults":"No matching commands","commandPalette.newChat":"New Chat","commandPalette.toggleTheme":"Toggle Theme","commandPalette.toggleLocale":"Toggle Language","commandPalette.tip":"Open command palette","app.confirm":"Confirm","app.cancel":"Cancel","tool.toolSingular":"tool executed","tool.toolPlural":"tools executed","keybindings.title":"Keybindings","keybindings.search.placeholder":"Search keybindings... (e.g. submit, ctrl+enter)","keybindings.source.default":"Default","keybindings.source.user":"User","keybindings.record.title":"Record Shortcut","keybindings.record.hint":"Press desired key combination...","keybindings.record.conflict":"Conflicts with","keybindings.action.edit":"Edit","keybindings.action.reset":"Reset","keybindings.action.unbind":"Unbind","keybindings.reset.all":"Reset all","keybindings.noResults":"No matching keybindings","keybindings.empty":"No keybindings","keybindings.loading":"Loading...","keybindings.ctx.Global":"Global","keybindings.ctx.Chat":"Chat Input","keybindings.ctx.InputBox":"Text Input","keybindings.ctx.Terminal":"Terminal","keybindings.ctx.Autocomplete":"Autocomplete","keybindings.ctx.Confirmation":"Confirmation","keybindings.ctx.HistorySearch":"History Search","keybindings.ctx.Task":"Task Running","keybindings.ctx.Settings":"Settings","keybindings.ctx.CommandPalette":"Command Palette","keybindings.ctx.Select":"Select List","keybindings.ctx.PermissionDialog":"Permission Dialog","keybindings.ctx.Help":"Help","keybindings.ctx.Plugin":"Plugin","keybindings.ctx.DiffDialog":"Diff Dialog","keybindings.ctx.MessageSelector":"Message Selector","keybindings.ctxDesc.Global":"Active everywhere, regardless of focus","keybindings.ctxDesc.Chat":"When the chat input is focused","keybindings.ctxDesc.InputBox":"When a text input is active","keybindings.ctxDesc.Terminal":"When the terminal view is active","keybindings.ctxDesc.Autocomplete":"When autocomplete menu is visible","keybindings.ctxDesc.Confirmation":"When a confirmation/permission dialog is shown","keybindings.ctxDesc.HistorySearch":"When searching command history (ctrl+r)","keybindings.ctxDesc.Task":"When a task/agent is running in the foreground","keybindings.ctxDesc.Settings":"When the settings panel is open","keybindings.ctxDesc.CommandPalette":"When the command palette is open","keybindings.ctxDesc.Select":"When a select/list component is focused","keybindings.ctxDesc.PermissionDialog":"When a tool permission dialog is shown","keybindings.ctxDesc.Help":"When the help overlay is open","keybindings.ctxDesc.Plugin":"When the plugin dialog is open","keybindings.ctxDesc.DiffDialog":"When the diff dialog is open","keybindings.ctxDesc.MessageSelector":"When the message selector (rewind) is open","keybindings.act.app:interrupt":"Interrupt","keybindings.act.app:exit":"Exit","keybindings.act.app:redraw":"Redraw Screen","keybindings.act.app:toggleTodos":"Toggle Todos","keybindings.act.app:toggleTranscript":"Toggle Transcript","keybindings.act.app:toggleSidebar":"Toggle Sidebar","keybindings.act.app:toggleTerminal":"Toggle Terminal","keybindings.act.app:commandPalette":"Command Palette","keybindings.act.app:newChat":"New Chat","keybindings.act.app:settings":"Settings","keybindings.act.app:focusInput":"Focus Input","keybindings.act.app:keybindings":"Keybinding Settings","keybindings.act.history:search":"Search History","keybindings.act.history:previous":"Previous History","keybindings.act.history:next":"Next History","keybindings.act.history:open":"Open History","keybindings.act.chat:cancel":"Cancel","keybindings.act.chat:submit":"Submit","keybindings.act.chat:newline":"New Line","keybindings.act.chat:killAgents":"Kill Agents","keybindings.act.chat:cycleMode":"Cycle Mode","keybindings.act.chat:modelPicker":"Model Picker","keybindings.act.chat:thinkingToggle":"Toggle Thinking","keybindings.act.chat:undo":"Undo","keybindings.act.chat:externalEditor":"External Editor","keybindings.act.chat:stash":"Stash","keybindings.act.chat:imagePaste":"Paste Image","keybindings.act.autocomplete:accept":"Accept","keybindings.act.autocomplete:dismiss":"Dismiss","keybindings.act.autocomplete:previous":"Previous","keybindings.act.autocomplete:next":"Next","keybindings.act.confirm:yes":"Confirm","keybindings.act.confirm:no":"Cancel","keybindings.act.confirm:previous":"Previous","keybindings.act.confirm:next":"Next","keybindings.act.confirm:toggle":"Toggle","keybindings.act.confirm:toggleExplanation":"Toggle Explanation","keybindings.act.task:background":"Run in Background","keybindings.act.historySearch:next":"Next","keybindings.act.historySearch:accept":"Accept","keybindings.act.historySearch:cancel":"Cancel","keybindings.act.historySearch:execute":"Execute","keybindings.act.settings:close":"Close Settings","keybindings.act.settings:search":"Search Settings","keybindings.act.select:previous":"Previous","keybindings.act.select:next":"Next","keybindings.act.select:accept":"Select","keybindings.act.select:cancel":"Cancel","keybindings.act.commandPalette:close":"Close Palette","keybindings.act.commandPalette:execute":"Execute Command","keybindings.act.commandPalette:previous":"Previous","keybindings.act.commandPalette:next":"Next","keybindings.act.permission:toggleDebug":"Toggle Debug","keybindings.act.diff:dismiss":"Close Diff","keybindings.act.diff:previousFile":"Previous File","keybindings.act.diff:nextFile":"Next File","keybindings.act.diff:viewDetails":"View Details","keybindings.act.plugin:toggle":"Toggle Plugin","keybindings.act.plugin:install":"Install Plugin","keybindings.act.help:dismiss":"Close Help","keybindings.act.transcript:exit":"Exit Transcript","keybindings.act.transcript:toggleShowAll":"Show All","keybindings.act.messageSelector:up":"Up","keybindings.act.messageSelector:down":"Down","keybindings.act.messageSelector:top":"Top","keybindings.act.messageSelector:bottom":"Bottom","keybindings.act.messageSelector:select":"Select","common.close":"Close","changes.revert":"Revert","changes.revertDirectory":"Revert directory","message.clickToEnlarge":"Click to enlarge","channel.botIdPlaceholder":"Enter Bot ID","channel.secretPlaceholder":"Enter Secret","filePreview.zoomOut":"Zoom Out","filePreview.zoomIn":"Zoom In","filePreview.fitToWindow":"Fit to Window","filePreview.actualSize":"Actual Size (1:1)","filePreview.pdfPreview":"PDF Preview","goal.status.usage":`Usage: /goal <condition>
|
|
636
|
+
`,h)}paste(m){this._core.paste(m)}refresh(m,h){this._verifyIntegers(m,h),this._core.refresh(m,h)}reset(){this._core.reset()}clearTextureAtlas(){this._core.clearTextureAtlas()}loadAddon(m){this._addonManager.loadAddon(this,m)}static get strings(){return a}_verifyIntegers(...m){for(const h of m)if(h===1/0||isNaN(h)||h%1!=0)throw new Error("This API only accepts integers")}_verifyPositiveIntegers(...m){for(const h of m)if(h&&(h===1/0||isNaN(h)||h%1!=0||h<0))throw new Error("This API only accepts positive integers")}}d.Terminal=v})(),l})()))})(ts)),ts.exports}var qb=Wb();const Mp="codebuddy-locale";function Pp(){if(typeof navigator>"u")return"en";const e=[];Array.isArray(navigator.languages)&&navigator.languages.length>0&&e.push(...navigator.languages),navigator.language&&e.push(navigator.language);try{const t=Intl.DateTimeFormat().resolvedOptions().locale;t&&e.push(t)}catch{}for(const t of e)if(t.toLowerCase().startsWith("zh"))return"zh";return"en"}function rs(e){return e==="system"?Pp():e}function Vb(){try{const e=localStorage.getItem(Mp);if(e){const t=JSON.parse(e),r=(t==null?void 0:t.mode)??e;if(["zh","en","system"].includes(r))return r}}catch{}return"system"}const xn=Ae()(Pr((e,t)=>{const r=Vb(),s=rs(r);return typeof window<"u"&&window.addEventListener("languagechange",()=>{const i=xn.getState();if(i.mode==="system"){const l=Pp();l!==i.resolved&&xn.setState({resolved:l})}}),{mode:r,resolved:s,setLocale:i=>{const l=rs(i);e({mode:i,resolved:l})},toggle:()=>{const i=t().mode,l=i==="zh"?"en":i==="en"?"system":"zh";t().setLocale(l)}}},{namespace:"locale",fields:["mode"],scope:"global",debounceMs:300,localStorageKey:Mp,onLoad:(e,t)=>{if(e.mode){const r=rs(e.mode);t({mode:e.mode,resolved:r})}}})),Md={zh:{"app.connecting":"正在连接 CodeBuddy Code...","app.connectFailed":"连接失败","app.retry":"重试","app.pwa.newVersion":"检测到 Web UI 新版本","app.pwa.reloadNow":"立即刷新","app.pwa.reloadLater":"稍后","app.pwa.reloadedAfterIdle":"已切换到新版本","chat.empty.title":"CodeBuddy Code","chat.empty.subtitle":"今天有什么可以帮到你?","chat.empty.slogan":"Claw Your Ideas . Into Reality","chat.empty.tag.slides":"幻灯片生成","chat.empty.tag.research":"深度研究","chat.empty.tag.docs":"文档处理","chat.empty.tag.data":"数据分析","chat.thinking":"思考中","chat.waitingPermission":"等待权限确认","chat.waitingUser":"等待用户回答","chat.error":"错误","chat.sessionEnded":"会话已结束","chat.stopped":"已停止","chat.error.refusal":"Agent 拒绝继续执行。这可能是由于内容策略限制或其他限制。","chat.error.network":"网络连接异常或服务暂时不可用,请稍后重试。","chat.error.auth":"身份验证失败或权限不足,请重新登录后再试。","chat.error.quota":"已达到配额上限或请求过于频繁,请稍后再试。","chat.error.modelService":"模型服务返回异常,请重试或稍后再试。","chat.error.maxTokens":"响应因达到最大 token 限制而被截断。您可以继续对话或要求更简洁的回复。","chat.error.maxTurnRequests":"已超过单轮对话允许的最大模型请求次数。您可以发送新消息以继续。","chat.newChat":"新对话","chat.disclaimer":"回答由 AI 生成,仅供参考","chat.compacted":"已精简历史对话","chat.compacting":"正在精简历史对话...","chat.compactCancelled":"历史对话精简已取消","phase.preparing":"准备中","phase.modelRequesting":"等待模型响应","phase.modelStreaming":"接收中","phase.modelDone":"处理中","phase.toolExecuting":"执行工具","phase.modelStreamingTool":"正在写入","phase.retrying":"重试中","progress.compacting":"压缩上下文中","input.placeholder":"从一个想法开始...","input.placeholderRunning":"消息将排队等待处理...","input.placeholderPending":"请先处理权限请求...","input.send":"发送 (Enter)","input.stop":"停止","input.thinking":"思考中","input.deepThinking":"深度思考","input.promptFailed":"发送失败","input.sendQueued":"发送排队消息 (Enter)","input.dropHint":"拖拽文件到这里","input.addImage":"添加图片","input.addFile":"添加文件","input.imageTooLarge":"图片不能超过 10MB","input.tooManyImages":"最多添加 5 张图片","input.fileTooLarge":"文件不能超过 1MB","input.tooManyFiles":"最多添加 10 个文件","input.menu.image":"图片","input.menu.file":"文件","input.newline":"换行","input.contextMenu.newline":"换行","input.contextMenu.send":"发送","queue.more":" 条消息排队中","status.running":"运行中","tool.writeFile":"写入文件","tool.readFile":"读取文件","tool.execute":"执行指令","tool.searchFiles":"搜索文件","tool.searchContent":"搜索内容","tool.fetchWeb":"获取网页","tool.searchWeb":"搜索网络","tool.defaultName":"工具","tool.moreItems":"... 还有 {count} 项","interruption.title":"需要授权","interruption.tool":"工具","interruption.allow":"允许","interruption.allowAll":"全部允许","interruption.deny":"拒绝","interruption.approved":"已允许","interruption.denied":"已拒绝","interruption.edits":"{count} 处编辑","interruption.yes":"是","interruption.keepPlanning":"继续规划","interruption.exitPlanMode":"退出计划模式","interruption.readyToCode":"准备好开始编码了吗?","theme.light":"浅色","theme.dark":"深色","theme.system":"跟随系统","locale.zh":"中文","locale.en":"English","locale.system":"跟随系统","sidebar.nav.plugins":"插件","sidebar.nav.tasks":"任务","sidebar.search.placeholder":"搜索...","sidebar.chatHistory":"对话历史","sidebar.workspace":"工作区","sidebar.connectionStatus":"连接状态","sidebar.status":"状态","sidebar.sessionId":"会话ID","sidebar.notConnected":"未连接","sidebar.modelSelection":"模型选择","sidebar.noModels":"暂无可用模型","sidebar.environment":"环境信息","sidebar.cwd":"工作目录","sidebar.os":"操作系统","sidebar.nodeVersion":"Node.js","sidebar.gatewayMode":"网关模式","sidebar.tunnelUrl":"Tunnel 地址","sidebar.clickToCopy":"点击复制","sidebar.copied":"已复制","sidebar.permissionMode":"权限模式","sidebar.noModes":"暂无可用模式","sidebar.preferences":"设置","sidebar.keybindings":"快捷键","sidebar.group.workspace":"工作区","sidebar.group.observability":"可观测","sidebar.group.preferences":"配置","bottomSheet.attachments":"添加","bottomSheet.navigation":"导航","sidebar.theme":"界面主题","sidebar.language":"界面语言","sidebar.user":"用户","sidebar.authMethod":"密码认证","sidebar.noAuth":"无认证","sidebar.version":"Remote UI v1.0","connection.connected":"已连接","connection.connecting":"连接中","connection.disconnected":"未连接","connection.error":"连接错误","message.copyToClipboard":"复制到剪贴板","message.copied":"已复制","message.copy":"复制","message.assistantName":"CodeBuddy Code","thinking.title":"思考过程","thinking.thinking":"思考中","thinking.done":"已思考","thinking.seconds":"(用时 {n} 秒)","thinking.expand":"展开","thinking.collapse":"收起","diff.noChanges":"无变更","login.title":"CodeBuddy Remote Control","login.subtitle":"请输入终端中显示的密码","login.placeholder":"密码","login.submit":"登录","login.error.incorrect":"密码错误","login.error.rateLimit":"登录尝试次数过多,请稍后再试","login.error.required":"请输入密码","login.hint.password":"提示:密码在服务启动时显示在终端中。","login.hint.urlAuth":"也可以使用 <code>?password=xxx</code> 自动登录。","login.hint.disable":'或在 CodeBuddy 配置目录(默认 <code>~/.codebuddy</code>,可通过 <code>CODEBUDDY_CONFIG_DIR</code> 环境变量覆盖)下的 <code>settings.json</code> 中设置 <code>gateway.auth: "none"</code> 来禁用认证。',"login.slogan":"Claw Your Ideas . Into Reality","login.tagline":"Triggered Anywhere, Completed Locally.","login.privacy":"隐私政策","login.terms":"服务条款","sidebar.interactionMode":"交互模式","sidebar.chatMode":"对话","sidebar.terminalMode":"终端","sidebar.canvas":"画布","canvas.title":"无限画布","canvas.addTerminal":"添加终端","canvas.zoomIn":"放大","canvas.zoomOut":"缩小","canvas.fitView":"适应视图","canvas.resetView":"重置视图","canvas.empty":"点击工具栏 + 按钮添加终端","canvas.openStandalone":"在新窗口打开画布","canvas.tileMenu.close":"关闭","canvas.tileMenu.duplicate":"复刻终端","canvas.tileMenu.maximize":"最大化","canvas.tileMenu.minimize":"最小化","canvas.tileMenu.restore":"还原","canvas.tileMenu.openStandalone":"在新窗口打开","canvas.standalone.missingPaneId":"未指定终端 ID","canvas.defaultTitle":"终端","terminal.connecting":"终端连接中...","terminal.title":"终端","terminal.disconnected":"终端已断开","terminal.error":"终端连接失败","terminal.reconnect":"重新连接","terminal.splitHorizontal":"左右分屏","terminal.splitVertical":"上下分屏","terminal.closePane":"关闭终端","terminal.maxPanes":"已达最大面板数","sidebar.instances":"实例","sidebar.activeInstances":"个活跃实例","sidebar.manageInstances":"管理实例","sidebar.remoteControl":"远程控制","instance.title":"实例列表","instance.switch":"实例","instance.switchTitle":"切换实例","instance.current":"当前实例","instance.manual":"手动添加","instance.switchTo":"切换到此实例","instance.manage":"管理实例","instance.managerTitle":"实例管理","instance.addInstance":"添加实例","instance.name":"实例名称","instance.namePlaceholder":"自定义实例名称(可选,默认为目录名)","instance.url":"实例地址","instance.urlPlaceholder":"https://example.trycloudflare.com","instance.password":"密码","instance.optional":"可选","instance.passwordPlaceholder":"访问密码","instance.cancel":"取消","instance.add":"添加","instance.remove":"删除此实例","instance.noInstances":"暂无其他实例","instance.noInstancesHint":"启动更多 CodeBuddy Code 实例,或手动添加远程实例","instance.cwd":"工作目录","instance.topic":"当前话题","instance.startedAt":"启动于","instance.local":"本地","instance.tunnel":"隧道","instance.uptime.days":"天前","instance.uptime.hours":"小时前","instance.uptime.minutes":"分钟前","instance.uptime.justNow":"刚刚","instance.addError":"添加实例失败","instance.removeError":"删除实例失败","instance.copyUrl":"复制链接","instance.copied":"已复制","instance.subtitle":"管理和切换工作实例","instance.refresh":"刷新","instance.refreshed":"已刷新","instance.loading":"加载实例中...","instance.error":"加载实例列表失败","instance.retry":"重试","question.multiple":"多选","question.customAnswer":"或输入自定义答案...","question.reviewAnswers":"审核答案","question.singleTitle":"问题","question.titleWithCount":"问题({count})","question.reviewTab":"审核","question.next":"下一步","question.submit":"提交","question.cancel":"取消","question.answered":"已回答","question.cancelled":"问题已取消","todo.title":"任务清单","todo.executing":"任务{n}正在执行中","todo.untitled":"未命名","history.title":"会话历史","history.description":"点击会话可切换到该对话","history.noData":"暂无会话历史","history.noDataHint":"开始一段新对话吧","history.backToChat":"返回对话","history.loading":"加载中...","history.loadError":"加载失败","history.retry":"重试","history.current":"当前","history.messages":"{count} 条消息","history.delete":"删除","history.deleteConfirm":"确定要删除这个会话吗?","history.deleteCancel":"取消","history.deleteOk":"删除","history.rename":"重命名","history.renameTitle":"重命名会话","history.renamePlaceholder":"输入新名称","history.renameCancel":"取消","history.renameOk":"确定","history.cannotDeleteCurrent":"无法删除当前会话","settings.title":"设置","settings.appearance":"外观","settings.model":"模型选择","settings.mode":"权限模式","settings.systemInfo":"系统信息","settings.backToChat":"返回对话","settings.tab.user":"用户级","settings.tab.project":"工作空间级","settings.group.modelAndReasoning":"模型与推理","settings.group.behavior":"行为","settings.group.memory":"记忆","settings.group.language":"语言","settings.group.advanced":"高级","settings.group.sandbox":"安全沙箱","settings.item.model":"默认模型","settings.item.model.desc":"设置默认使用的 AI 模型","settings.item.reasoningEffort":"推理努力级别","settings.item.reasoningEffort.desc":"控制模型的推理深度","settings.item.alwaysThinkingEnabled":"始终启用深度思考","settings.item.autoCompactEnabled":"自动压缩上下文","settings.item.includeCoAuthoredBy":"提交包含 Co-authored-by","settings.item.fileCheckpointingEnabled":"文件检查点","settings.item.fileCheckpointingEnabled.desc":"启用文件版本回退功能","settings.item.promptSuggestionEnabled":"提示建议","settings.item.ignoreGitIgnore":"忽略 .gitignore","settings.item.ignoreGitIgnore.desc":"搜索文件时忽略 .gitignore 规则","settings.item.deferToolLoading":"延迟加载工具","settings.item.hookOutputCollapsed":"折叠 Hook 输出","settings.item.memory.enabled":"启用记忆功能","settings.item.memory.autoMemoryEnabled":"自动记忆","settings.item.memory.autoMemoryEnabled.desc":"自动保存重要信息到记忆库","settings.item.language":"响应语言","settings.item.language.desc":"设置 AI 回复使用的语言","settings.item.cleanupPeriodDays":"聊天记录保留天数","settings.item.imageHistoryRetainRounds":"图片保留轮数","settings.item.imageHistoryRetainRounds.desc":"对话历史中保留图片的最近轮数","settings.item.env":"环境变量","settings.item.env.desc":"应用于每个会话的环境变量 (JSON)","settings.item.sandbox.enabled":"启用安全沙箱","settings.item.sandbox.enabled.desc":"在沙箱中运行 Bash 命令,限制文件和网络访问","settings.item.sandbox.autoAllowBashIfSandboxed":"沙箱内自动批准命令","settings.item.sandbox.autoAllowBashIfSandboxed.desc":"命令在沙箱中运行时自动批准","settings.loading":"加载中...","settings.saved":"已保存","settings.saveFailed":"保存失败","settings.notSet":"未设置","settings.default":"默认","settings.reset":"重置","settings.noProjectSettings":"当前工作空间暂无可配置项","settings.effort.minimal":"最小","settings.effort.low":"低","settings.effort.medium":"中","settings.effort.high":"高","settings.effort.xhigh":"极高","settings.effort.max":"最大","page.title":"CodeBuddy Code","tool.processExited":"[进程已退出]","tool.itemsCount":"{count} 项","tool.showAllItems":"显示全部 {count} 项","tool.moreLinesCount":"... 还有 {count} 行","tool.generatedImage":"生成的图片","tool.editedImage":"编辑后的图片","tool.imageGen":"图片生成","tool.imageEdit":"图片编辑","tool.toolSearch":"工具搜索","tool.teamCreate":"创建团队","tool.teamDelete":"删除团队","tool.taskCreate":"创建任务","tool.taskUpdate":"更新任务","tool.taskList":"任务列表","tool.taskGet":"获取任务","tool.sendMessage":"发送消息","tool.shutdown":"关闭","tool.taskCompleted":"任务完成","tool.shutdownRejected":"关闭被拒绝","tool.planResponse":"计划回复","tool.approved":"已批准","tool.rejected":"已拒绝","tool.userRejectedResult":"用户已拒绝执行此操作","tool.webSearch":"网络搜索","tool.webFetch":"网页获取","tool.saveMemory":"保存记忆","tool.askUserQuestion":"询问用户","tool.enterPlanMode":"进入计划模式","tool.exitPlanMode":"退出计划模式","tool.allowedActions":"允许的操作:","tool.skill":"技能","tool.agent":"代理","tool.failed":"失败","tool.completed":"完成","tool.toolsCount":"{count} 个工具","tool.background":"后台","tool.permissionsCount":"{count} 项权限","terminal.unknownError":"未知错误","terminal.processExited":"[进程已退出]","terminal.connectionLost":"连接已断开","terminal.wsConnectionFailed":"WebSocket 连接失败","terminal.createSessionFailed":"创建终端会话失败","terminal.reconnectFailed":"重连失败","team.title":"团队","team.activeCount":"{count} 个活跃","team.doneCount":"{count} 个完成","team.waitingForTeammates":"等待 {count} 个成员完成…","team.backToMain":"返回主对话","team.loadingHistory":"加载对话历史…","team.noHistory":"暂无对话历史","team.agentRunning":"正在运行…","team.delivered":"已送达","team.showLess":"收起","team.moreLines":"… ({count} 更多行)","team.tools":"{count} 工具","team.tokens":"{count} tokens","instance.tunnelMode":"隧道","instance.localMode":"本地","workspace.searchPlaceholder":"搜索目录...","workspace.switch":"切换","workspace.switchHere":"切换到此目录","workspace.switching":"切换中...","workspace.noResults":"没有匹配的目录","workspace.emptyDir":"此目录为空","workspace.pathPlaceholder":"输入路径或目录名...","workspace.selectDir":"在此目录创建机器人","workspace.filterPlaceholder":"过滤子目录...","workspace.recent.title":"最近工作区","workspace.recent.daysAgo":"天前","workspace.recent.hoursAgo":"小时前","workspace.recent.minutesAgo":"分钟前","workspace.recent.justNow":"刚刚","workspace.recent.remove":"移除","workspace.browseTitle":"浏览工作区","workspace.recentWorkspaces":"最近工作区","workspace.createNew":"创建新机器人","workspace.browseDir":"浏览目录","workspace.instanceLocal":"本地","workspace.instanceTunnel":"隧道","workspace.instanceCurrent":"当前","workspace.switchInstance":"切换","workspace.switchingInstance":"切换中...","workspace.switchingWithGateway":"正在准备切换...","workspace.instanceStarted":"启动于","workspace.noWorkspaces":"暂无活跃的工作区","workspace.noWorkspacesHint":"浏览目录创建新机器人","workspace.instanceCount":"{count} 个机器人","question.multiLabel":"多选","tasks.title":"推荐模版","tasks.subtitle":"选择一个模版快速创建定时任务","tasks.loading":"正在获取推荐模版...","tasks.error":"获取模版失败","tasks.retry":"重试","tasks.refresh":"刷新推荐","tasks.refreshed":"已刷新","tasks.empty":"暂无推荐模版","tasks.interval":"每 {value}","tasks.interval.1d":"每天","tasks.interval.2d":"每 2 天","tasks.interval.3d":"每 3 天","tasks.interval.1w":"每周","tasks.interval.2w":"每 2 周","tasks.interval.1m":"每月","scheduled.title":"定时任务","scheduled.subtitle":"当前会话中的活跃定时任务","scheduled.loading":"加载中...","scheduled.empty":"暂无定时任务","scheduled.emptyHint":"在对话中使用 /loop 或 CronCreate 创建","scheduled.create":"创建任务","scheduled.creating":"创建中...","scheduled.delete":"删除","scheduled.cron":"Cron 表达式","scheduled.prompt":"执行内容","scheduled.promptPlaceholder":"定时触发时要执行的提示词...","scheduled.recurring":"循环","scheduled.oneShot":"一次性","scheduled.durable":"持久化","scheduled.sessionOnly":"仅会话","scheduled.lastFired":"上次触发","plugins.title":"插件管理","plugins.installedPlugins":"已安装插件","plugins.browseMarketplace":"浏览市场","plugins.marketplaces":"插件市场","plugins.enabled":"已启用","plugins.disabled":"已禁用","plugins.enable":"启用","plugins.disable":"禁用","plugins.uninstall":"卸载","plugins.install":"安装","plugins.confirmUninstall":"确定要卸载此插件吗?","plugins.marketplace":"市场","plugins.addMarketplace":"添加市场","plugins.removeMarketplace":"移除","plugins.confirmRemoveMarketplace":"确定要移除此市场吗?","plugins.noPlugins":"暂无已安装的插件","plugins.noPluginsHint":"通过插件市场安装插件来扩展功能","plugins.noMarketplaces":"暂无配置的市场","plugins.noMarketplacesHint":"添加一个插件市场来浏览和安装插件","plugins.selectMarketplace":"选择市场","plugins.selectMarketplaceHint":"选择一个市场来浏览可用插件","plugins.marketplaceNotFound":"市场不存在","plugins.noAvailablePlugins":"该市场暂无可用插件","plugins.noAvailablePluginsHint":"请尝试添加其他市场或稍后再试","plugins.installed":"已安装","plugins.browsingMarketplace":"浏览中...","plugins.loading":"加载中...","plugins.error":"加载插件失败","plugins.retry":"重试","plugins.sourcePlaceholder":"市场地址(Git URL 或本地路径)","plugins.namePlaceholder":"市场名称(可选)","plugins.cancel":"取消","plugins.add":"添加","plugins.version":"版本","plugins.operationFailed":"操作失败","plugins.searchPlaceholder":"搜索插件...","plugins.allMarketplaces":"全部市场","plugins.noSearchResults":"没有找到匹配的插件","plugins.totalCount":"个插件","plugins.refresh":"刷新","plugins.installedLabel":"已安装","plugins.category":"分类","plugins.author":"作者","plugins.license":"许可证","plugins.homepage":"主页","plugins.repository":"仓库","plugins.source":"来源","plugins.keywords":"关键词","plugins.features":"功能","plugins.scope":"范围","plugins.scope.user":"用户","plugins.scope.project":"项目","plugins.scope.project-local":"本地","plugins.installScope.user":"为你安装(用户级)","plugins.installScope.project":"为所有协作者安装(项目级)","plugins.installScope.local":"仅在此仓库为你安装(本地级)","plugins.policyCannotRemove":"不可卸载","plugins.policyCannotSwitchoff":"不可禁用","plugins.policyCannotEdit":"不可编辑","channel.from":"来自","channel.group":"群聊","channel.replyTo":"回复来自 {source}","channel.wechat":"微信","channel.wecom":"企业微信","channel.wecomBot":"企微机器人","remoteControl.title":"远程控制","remoteControl.subtitle":"管理渠道连接","remoteControl.connectedChannels":"已连接渠道","remoteControl.noChannels":"暂无已连接渠道","remoteControl.noChannelsHint":"添加微信或企业微信渠道,或从插件市场安装更多","remoteControl.addWeChat":"添加微信机器人","remoteControl.addWeCom":"添加企微机器人","remoteControl.connect":"连接","remoteControl.disconnect":"断开","remoteControl.delete":"删除","remoteControl.add":"添加","remoteControl.connected":"已连接","remoteControl.disconnected":"未连接","remoteControl.connecting":"连接中...","remoteControl.installMore":"安装更多渠道","remoteControl.installMoreHint":"浏览插件市场,安装第三方渠道插件","remoteControl.browseMarketplace":"浏览插件市场","remoteControl.builtIn":"内置","remoteControl.plugin":"插件","remoteControl.rebind":"重新绑定","remoteControl.unbind":"解绑","remoteControl.bot":"机器人","remoteControl.default":"默认","remoteControl.next":"下一步","remoteControl.cancel":"取消","remoteControl.wecomBotIdHint":"从企业微信管理后台 → 应用管理 → AI 助手获取","remoteControl.wecomSecretHint":"输入 Secret 后按回车或点“连接”","remoteControl.fetchingQr":"正在获取二维码...","remoteControl.scanQr":"请用微信扫描二维码","sidebar.docs":"文档","docs.title":"文档中心","docs.search.placeholder":"搜索文档...","docs.search.noResults":"未找到相关文档","docs.search.resultsCount":"{count} 个结果","docs.loading":"加载中...","docs.loadError":"文档加载失败","docs.notFound":"未找到该文档","docs.apiReference":"API 文档","docs.toc":"目录","docs.retry":"重试","docs.backToList":"返回文档列表","docs.expandAll":"展开全部","docs.collapseAll":"收起全部","docs.openStandalone":"独立窗口打开","sidebar.stats":"统计","stats.title":"统计","stats.loading":"正在加载统计数据...","stats.refresh":"刷新","stats.noData":"暂无统计数据","stats.tab.overview":"概览","stats.tab.models":"模型","stats.tab.tools":"工具","stats.sessions":"会话数","stats.messages":"消息数","stats.activeDays":"活跃天数","stats.currentStreak":"当前连续","stats.longestStreak":"最长连续","stats.peakHour":"高峰时段","stats.longestSession":"最长会话","stats.favoriteModel":"最常用模型","stats.totalTokens":"总 Token","stats.timeRange":"统计范围: 最近 {days} 天","stats.heatmap.less":"少","stats.heatmap.more":"多","stats.days":"天","stats.tokensPerDay":"每日 Token 趋势","stats.allModels":"所有模型","stats.input":"输入","stats.output":"输出","stats.cacheRead":"缓存读取","stats.cacheHitRate":"缓存命中率","stats.cost":"成本","stats.topTools":"工具使用排行","stats.session.title":"当前会话","stats.session.apiDuration":"API 时长","stats.session.wallTime":"总时长","stats.session.linesAdded":"新增行","stats.session.linesDeleted":"删除行","stats.session.tokens":"Token","stats.na":"N/A","stats.heatmap.messages":"条消息","stats.funFact.moreTokens":"你已使用约 {times} 倍于《{book}》的 Token 量","stats.funFact.sameTokens":"你使用的 Token 量约等于一本《{book}》","stats.funFact.longerSession":"你最长的会话时长约为「{activity}」的 {times} 倍","sidebar.traces":"链路","traces.title":"链路追踪","traces.loading":"加载中...","traces.refresh":"刷新","traces.clear":"清空","traces.clearConfirm":"确定清空所有链路数据?","traces.noData":"暂无链路数据,发送一条消息后将自动收集","traces.selectWorker":"选择 Worker","traces.current":"当前","traces.spanCount":"{count} spans","traces.duration":"耗时","traces.status.ok":"成功","traces.status.error":"错误","traces.status.running":"运行中","traces.status.cancelled":"已取消","traces.bottleneck":"瓶颈","traces.bottleneckTip":"耗时最长,占总时间 {pct}%","traces.spanDetail":"Span 详情","traces.spanDetail.type":"类型","traces.spanDetail.duration":"耗时","traces.spanDetail.model":"模型","traces.spanDetail.tokens":"Token","traces.spanDetail.input":"输入","traces.spanDetail.output":"输出","traces.spanDetail.error":"错误","traces.spanDetail.cancelReason":"取消原因","traces.spanDetail.attributes":"属性","traces.legend.agent":"Agent","traces.legend.generation":"模型调用","traces.legend.function":"工具","traces.legend.handoff":"切换","traces.legend.guardrail":"防护","traces.back":"返回","traces.tab.timeline":"时间线","traces.tab.tree":"树形","traces.tab.flame":"火焰图","traces.tab.graph":"依赖图","traces.expandAll":"全部展开","traces.collapseAll":"全部收起","traces.search":"搜索 span...","traces.selfTime":"自身耗时","traces.spanDetail.overview":"概览","traces.spanDetail.io":"输入/输出","traces.noSpans":"无 span 数据","traces.noSpansFiltered":"当前筛选下无 span。","traces.clearFilter":"清除筛选","traces.auto":"自动","traces.auxiliaryCount":"{count} 个辅助 trace(memory、title 等)","traces.noIO":"无输入/输出数据","traces.noAttrs":"无属性","traces.io.expand":"展开","traces.io.collapse":"收起","traces.io.messages":"消息","traces.io.less":"收起","traces.io.moreChars":"+{count} 字符","traces.fit":"适应","traces.allSessions":"所有会话","traces.allInstances":"所有实例","traces.llmCalls":"{count} 次 LLM","traces.errors":"错误","traces.noErrors":"没有失败的 trace","traces.errorBanner":"检测到 {count} 个失败的 trace","traces.errorBannerCta":"点击仅查看错误 →","traces.errorSummaryTitle":"本次共有 {count} 处错误","traces.jumpToFirstError":"跳转到首个错误 span","traces.copyError":"复制错误","traces.onlyErrors":"仅错误","traces.filter.all":"全部","traces.filter.error":"错误","traces.filter.running":"运行中","traces.filter.cancelled":"已取消","traces.filter.ok":"成功","sidebar.metrics":"监控","metrics.title":"系统监控","metrics.loading":"加载指标数据...","metrics.refresh":"刷新","metrics.cpu":"CPU","metrics.memory":"内存","metrics.disk":"磁盘","metrics.cores":"核心","metrics.workers":"Workers","metrics.noWorkers":"暂无运行中的 Worker","metrics.current":"当前","metrics.uptime":"运行时长","metrics.version":"版本","sidebar.editor":"文件","editor.title":"代码编辑器","editor.loading":"加载中...","editor.loadError":"加载失败","editor.noFile":"选择一个文件开始编辑","editor.unsaved":"未保存","editor.save":"保存","editor.saveAll":"全部保存","editor.close":"关闭","editor.closeOthers":"关闭其他","editor.closeAll":"关闭全部","editor.newFile":"新建文件","editor.newFolder":"新建文件夹","editor.rename":"重命名","editor.delete":"删除","editor.refresh":"刷新","editor.emptyFolder":"空文件夹","editor.explorer":"资源管理器","editor.toggleSidebar":"切换侧边栏","editor.collapseAll":"全部折叠","editor.openFolder":"打开目录","editor.openFolderPlaceholder":"输入目录路径...","editor.parentFolder":"上级目录","editor.pin":"固定","editor.unpin":"取消固定","editor.copyPath":"复制路径","editor.copyRelativePath":"复制相对路径","editor.revealInExplorer":"在文件树中定位","editor.closeToRight":"关闭右侧","editor.closeSaved":"关闭已保存","editor.quickOpen":"快速打开文件","editor.focusExplorer":"聚焦资源管理器","editor.recentFiles":"最近文件","editor.quickOpenPlaceholder":"输入文件名以搜索...","editor.quickOpenEmpty":"没有匹配的文件","editor.quickOpenLoading":"正在加载文件列表...","editor.selected":"已选","editor.lines":"行","editor.preview":"切换到预览","editor.source":"切换到源码","sidebar.workers":"实例","workers.title":"Agent 实例管理","workers.refresh":"刷新","workers.active":"活跃 Workers","workers.empty":"没有活跃的 worker 进程","workers.daemon":"Daemon 服务","workers.daemon.running":"运行中","workers.daemon.stopped":"已停止","workers.daemon.start":"启动","workers.daemon.starting":"启动中...","workers.daemon.stop":"停止","workers.daemon.restart":"重启","workers.action.logs":"查看日志","workers.action.open":"打开","workers.action.kill":"终止","workers.action.kill.confirm":"确定要终止这个 worker 进程吗?","sidebar.logs":"日志","logs.title":"日志查看器","logs.selectWorker":"选择 Worker","logs.current":"当前","logs.search":"搜索日志...","logs.autoRefresh":"自动刷新","logs.refresh":"刷新","logs.empty":"暂无日志内容","command.btw.description":"快速提问,不打断主要 Agent 工作","command.clear.description":"开始新的对话(之前的对话仍可通过 /resume 访问)","command.context.description":"计算并显示上下文 Token 分布","command.cost.description":"显示当前会话的总费用和持续时间","command.doctor.description":"诊断和验证 CodeBuddy 的安装和设置","command.feedback.description":"打开反馈页面以报告问题或提出建议","command.gateway.description":'管理远程控制网关。子命令: "status" 查看状态, "stop" 停止网关, "token" 重新生成访问令牌, "tunnel" 启动隧道',"command.remote-control.description":"管理远程控制长连接客户端(start, stop, status, list)","command.login.description":"切换腾讯云 CodeBuddy 账号","command.logout.description":"退出 CodeBuddy Code 账号","command.plan.description":"预览当前计划文件内容","command.pr-comments.description":"获取 GitHub Pull Request 的评论","command.release-notes.description":"查看更新日志","command.review.description":"审查 Pull Request","command.skills.description":"列出可用的技能","command.todos.description":"显示当前会话的任务清单","command.reload-plugins.description":"重新加载所有插件、技能、代理、钩子和 MCP/LSP 服务器(无需重启)","command.plugin-validate.description":"验证插件目录结构和清单文件","command.init.description":"正在分析你的代码库…","command.compact.description":"清除对话历史但保留摘要在上下文中。可选: /compact [摘要指令]","command.upgrade.description":"在浏览器中打开升级页面","command.statusline.description":"设置 CodeBuddy Code 的状态栏 UI","command.security-review.description":"对当前分支的待提交变更进行安全审查","command.insights.description":"生成 AI 驱动的 CodeBuddy Code 使用模式和活动洞察","command.loop.description":"按固定间隔运行提示或斜杠命令(例如 /loop 5m /foo,默认 10m)","command.task-manager.description":"团队任务管理 - 智能任务录入、分配、追踪和分析","sidebar.changes":"变更","fileChanges.title":"变更","fileChanges.changesSection":"文件变更","fileChanges.empty":"暂无文件变更","fileChanges.showChanges":"显示文件变更","fileChanges.hideChanges":"隐藏文件变更","fileChanges.revertAll":"撤回全部","fileChanges.revertCode":"回退代码","fileChanges.revertChat":"回退对话","fileChanges.revertCodeAndChat":"回退全部","fileChanges.checkpoints":"回退点","fileChanges.noCheckpoints":"暂无回退点","filePreview.binaryNotSupported":"该文件无法在编辑器中预览","filePreview.download":"下载文件","error.viewCrashed":"页面加载出错","error.appCrashed":"应用遇到了问题","error.newChatFailed":"创建新对话失败,请重试","error.switchSessionFailed":"切换会话失败,请重试","commandPalette.placeholder":"输入命令...","commandPalette.commands":"命令","commandPalette.views":"视图","commandPalette.actions":"操作","commandPalette.noResults":"没有匹配的命令","commandPalette.newChat":"新建对话","commandPalette.toggleTheme":"切换主题","commandPalette.toggleLocale":"切换语言","commandPalette.tip":"打开命令面板","app.confirm":"确定","app.cancel":"取消","tool.toolSingular":"个工具已执行","tool.toolPlural":"个工具已执行","keybindings.title":"快捷键","keybindings.search.placeholder":"搜索快捷键... (如 submit, ctrl+enter)","keybindings.source.default":"默认","keybindings.source.user":"自定义","keybindings.record.title":"录制快捷键","keybindings.record.hint":"请按下快捷键组合...","keybindings.record.conflict":"冲突","keybindings.action.edit":"编辑","keybindings.action.reset":"重置","keybindings.action.unbind":"解绑","keybindings.reset.all":"重置全部","keybindings.noResults":"没有匹配的快捷键","keybindings.empty":"暂无快捷键","keybindings.loading":"加载中...","keybindings.ctx.Global":"全局","keybindings.ctx.Chat":"聊天输入","keybindings.ctx.InputBox":"文本输入","keybindings.ctx.Terminal":"终端","keybindings.ctx.Autocomplete":"自动补全","keybindings.ctx.Confirmation":"确认对话框","keybindings.ctx.HistorySearch":"历史搜索","keybindings.ctx.Task":"任务运行中","keybindings.ctx.Settings":"设置","keybindings.ctx.CommandPalette":"命令面板","keybindings.ctx.Select":"选择列表","keybindings.ctx.PermissionDialog":"权限对话框","keybindings.ctx.Help":"帮助","keybindings.ctx.Plugin":"插件","keybindings.ctx.DiffDialog":"Diff 对话框","keybindings.ctx.MessageSelector":"消息选择器","keybindings.ctxDesc.Global":"在任何位置都生效","keybindings.ctxDesc.Chat":"聊天输入框获得焦点时","keybindings.ctxDesc.InputBox":"文本输入框处于活跃状态时","keybindings.ctxDesc.Terminal":"终端视图处于活跃状态时","keybindings.ctxDesc.Autocomplete":"自动补全菜单显示时","keybindings.ctxDesc.Confirmation":"确认/权限对话框显示时","keybindings.ctxDesc.HistorySearch":"搜索命令历史时 (ctrl+r)","keybindings.ctxDesc.Task":"任务/代理在前台运行时","keybindings.ctxDesc.Settings":"设置面板打开时","keybindings.ctxDesc.CommandPalette":"命令面板打开时","keybindings.ctxDesc.Select":"选择/列表组件获得焦点时","keybindings.ctxDesc.PermissionDialog":"工具权限对话框显示时","keybindings.ctxDesc.Help":"帮助页面打开时","keybindings.ctxDesc.Plugin":"插件对话框打开时","keybindings.ctxDesc.DiffDialog":"Diff 对话框打开时","keybindings.ctxDesc.MessageSelector":"消息选择器 (rewind) 打开时","keybindings.act.app:interrupt":"中断","keybindings.act.app:exit":"退出","keybindings.act.app:redraw":"刷新屏幕","keybindings.act.app:toggleTodos":"切换待办事项","keybindings.act.app:toggleTranscript":"切换转录","keybindings.act.app:toggleSidebar":"切换侧边栏","keybindings.act.app:toggleTerminal":"切换终端","keybindings.act.app:commandPalette":"命令面板","keybindings.act.app:newChat":"新对话","keybindings.act.app:settings":"设置","keybindings.act.app:focusInput":"聚焦输入框","keybindings.act.app:keybindings":"快捷键设置","keybindings.act.history:search":"搜索历史","keybindings.act.history:previous":"上一条历史","keybindings.act.history:next":"下一条历史","keybindings.act.history:open":"打开历史","keybindings.act.chat:cancel":"取消","keybindings.act.chat:submit":"发送","keybindings.act.chat:newline":"换行","keybindings.act.chat:killAgents":"终止代理","keybindings.act.chat:cycleMode":"切换模式","keybindings.act.chat:modelPicker":"选择模型","keybindings.act.chat:thinkingToggle":"切换思考","keybindings.act.chat:undo":"撤销","keybindings.act.chat:externalEditor":"外部编辑器","keybindings.act.chat:stash":"暂存","keybindings.act.chat:imagePaste":"粘贴图片","keybindings.act.autocomplete:accept":"接受补全","keybindings.act.autocomplete:dismiss":"关闭补全","keybindings.act.autocomplete:previous":"上一项","keybindings.act.autocomplete:next":"下一项","keybindings.act.confirm:yes":"确认","keybindings.act.confirm:no":"取消","keybindings.act.confirm:previous":"上一项","keybindings.act.confirm:next":"下一项","keybindings.act.confirm:toggle":"切换选中","keybindings.act.confirm:toggleExplanation":"切换说明","keybindings.act.task:background":"后台运行","keybindings.act.historySearch:next":"下一条","keybindings.act.historySearch:accept":"接受","keybindings.act.historySearch:cancel":"取消","keybindings.act.historySearch:execute":"执行","keybindings.act.settings:close":"关闭设置","keybindings.act.settings:search":"搜索设置","keybindings.act.select:previous":"上一项","keybindings.act.select:next":"下一项","keybindings.act.select:accept":"选择","keybindings.act.select:cancel":"取消","keybindings.act.commandPalette:close":"关闭面板","keybindings.act.commandPalette:execute":"执行命令","keybindings.act.commandPalette:previous":"上一项","keybindings.act.commandPalette:next":"下一项","keybindings.act.permission:toggleDebug":"切换调试","keybindings.act.diff:dismiss":"关闭 Diff","keybindings.act.diff:previousFile":"上一个文件","keybindings.act.diff:nextFile":"下一个文件","keybindings.act.diff:viewDetails":"查看详情","keybindings.act.plugin:toggle":"切换插件","keybindings.act.plugin:install":"安装插件","keybindings.act.help:dismiss":"关闭帮助","keybindings.act.transcript:exit":"退出转录","keybindings.act.transcript:toggleShowAll":"显示全部","keybindings.act.messageSelector:up":"向上","keybindings.act.messageSelector:down":"向下","keybindings.act.messageSelector:top":"到顶部","keybindings.act.messageSelector:bottom":"到底部","keybindings.act.messageSelector:select":"选择","common.close":"关闭","changes.revert":"还原","changes.revertDirectory":"还原目录","message.clickToEnlarge":"点击放大","channel.botIdPlaceholder":"输入 Bot ID","channel.secretPlaceholder":"输入 Secret","filePreview.zoomOut":"缩小","filePreview.zoomIn":"放大","filePreview.fitToWindow":"适应窗口","filePreview.actualSize":"实际大小 (1:1)","filePreview.pdfPreview":"PDF 预览","goal.status.usage":`用法:/goal <条件>
|
|
637
|
+
示例:/goal 所有测试通过`,"goal.status.tooLong":"目标条件长度上限 {max} 字符(当前 {actual})","goal.status.hooksDisabled":"/goal 在 Hooks 被禁用时不可用(settings 中关闭了 disableAllHooks 或 allowManagedHooksOnly)。","goal.status.set":"已设置目标:{condition}","goal.status.setReplaced":"替换目标:{prev} → {condition}","goal.status.cleared":"已清除目标:{prev}","goal.status.noGoal":"当前无目标","goal.status.active":"当前目标:{condition}","goal.progress.title":"目标尚未达成… 继续","goal.progress.expand":"点击展开","goal.progress.condition":"目标","goal.progress.reason":"原因","goal.recap.active":"当前活跃目标","goal.recap.achieved":"目标已达成","goal.recap.impossible":"目标无法达成","goal.recap.empty.title":"暂未设置目标","goal.recap.empty.hint":"使用 /goal <条件> 设置一个会话级停止条件。","goal.recap.empty.example":"示例:/goal 所有测试通过","goal.recap.footer.setAnother":"/goal <条件>","goal.recap.footer.toSetAnother":" 设置新目标 · ","goal.recap.footer.escDismiss":"关闭","goal.recap.stats.turn":"轮","goal.recap.stats.turns":"轮","goal.recap.stats.token":"token","goal.recap.stats.tokens":"tokens"},en:{"app.connecting":"Connecting to CodeBuddy Code...","app.connectFailed":"Connection failed","app.retry":"Retry","app.pwa.newVersion":"A new Web UI version is available","app.pwa.reloadNow":"Reload now","app.pwa.reloadLater":"Later","app.pwa.reloadedAfterIdle":"Updated to new version","chat.empty.title":"CodeBuddy Code","chat.empty.subtitle":"How can I help you today?","chat.empty.slogan":"Claw Your Ideas . Into Reality","chat.empty.tag.slides":"Slide Generation","chat.empty.tag.research":"Deep Research","chat.empty.tag.docs":"Document Processing","chat.empty.tag.data":"Data Analysis","chat.thinking":"Thinking","chat.waitingPermission":"Waiting for permission","chat.waitingUser":"Waiting for user","chat.error":"Error","chat.sessionEnded":"Session ended","chat.stopped":"Stopped","chat.error.refusal":"The agent refused to continue execution. This may be due to content policy restrictions or other limitations.","chat.error.network":"Network connection failed or the service is temporarily unavailable. Please try again later.","chat.error.auth":"Authentication failed or insufficient permissions. Please sign in again and retry.","chat.error.quota":"Quota limit reached or too many requests. Please try again later.","chat.error.modelService":"The model service returned an error. Please retry or try again later.","chat.error.maxTokens":"Response was truncated due to reaching the maximum token limit. You may continue the conversation or ask for a more concise response.","chat.error.maxTurnRequests":"The maximum number of model requests per turn has been exceeded. You may send a new message to continue.","chat.newChat":"New Chat","chat.disclaimer":"Answers generated by AI are for reference only","chat.compacted":"Conversation compacted","chat.compacting":"Compacting conversation...","chat.compactCancelled":"Compaction cancelled","phase.preparing":"Preparing","phase.modelRequesting":"Waiting for model","phase.modelStreaming":"Streaming","phase.modelDone":"Processing","phase.toolExecuting":"Running tool","phase.modelStreamingTool":"Writing","phase.retrying":"Retrying","progress.compacting":"Compacting context","input.placeholder":"Start from an idea...","input.placeholderRunning":"Messages will be queued...","input.placeholderPending":"Please handle the permission request first...","input.send":"Send (Enter)","input.stop":"Stop","input.thinking":"Thinking","input.deepThinking":"Deep Thinking","input.promptFailed":"Prompt failed","input.sendQueued":"Send queued (Enter)","input.dropHint":"Drop files here","input.addImage":"Add image","input.addFile":"Add file","input.imageTooLarge":"Image must be under 10MB","input.tooManyImages":"Up to 5 images allowed","input.fileTooLarge":"File must be under 1MB","input.tooManyFiles":"Up to 10 files allowed","input.menu.image":"Image","input.menu.file":"File","input.newline":"New line","input.contextMenu.newline":"New line","input.contextMenu.send":"Send","queue.more":" more queued","status.running":"Running","tool.writeFile":"Write file","tool.readFile":"Read file","tool.execute":"Execute","tool.searchFiles":"Search files","tool.searchContent":"Search content","tool.fetchWeb":"Fetch web","tool.searchWeb":"Search web","tool.defaultName":"Tool","tool.moreItems":"... {count} more","interruption.title":"Permission Required","interruption.tool":"Tool","interruption.allow":"Allow","interruption.allowAll":"Allow All","interruption.deny":"Deny","interruption.approved":"Approved","interruption.denied":"Denied","interruption.edits":"{count} edits","interruption.yes":"Yes","interruption.keepPlanning":"No, keep planning","interruption.exitPlanMode":"Exit plan mode","interruption.readyToCode":"Ready to code?","theme.light":"Light","theme.dark":"Dark","theme.system":"System","locale.zh":"Chinese","locale.en":"English","locale.system":"System","sidebar.nav.plugins":"Plugins","sidebar.nav.tasks":"Tasks","sidebar.search.placeholder":"Search...","sidebar.chatHistory":"Chat History","sidebar.workspace":"Workspace","sidebar.connectionStatus":"Connection Status","sidebar.status":"Status","sidebar.sessionId":"Session ID","sidebar.notConnected":"Not connected","sidebar.modelSelection":"Model Selection","sidebar.noModels":"No models available","sidebar.environment":"Environment","sidebar.cwd":"Working Directory","sidebar.os":"OS","sidebar.nodeVersion":"Node.js","sidebar.gatewayMode":"Gateway Mode","sidebar.tunnelUrl":"Tunnel URL","sidebar.clickToCopy":"Click to copy","sidebar.copied":"Copied","sidebar.permissionMode":"Permission Mode","sidebar.noModes":"No modes available","sidebar.preferences":"Preferences","sidebar.keybindings":"Keybindings","sidebar.group.workspace":"Workspace","sidebar.group.observability":"Observability","sidebar.group.preferences":"Preferences","bottomSheet.attachments":"Attach","bottomSheet.navigation":"Navigate","sidebar.theme":"Theme","sidebar.language":"Language","sidebar.user":"User","sidebar.authMethod":"Password","sidebar.noAuth":"No Auth","sidebar.version":"Remote UI v1.0","connection.connected":"Connected","connection.connecting":"Connecting","connection.disconnected":"Disconnected","connection.error":"Error","message.copyToClipboard":"Copy to clipboard","message.copied":"Copied","message.copy":"Copy","message.assistantName":"CodeBuddy Code","thinking.title":"Thinking Process","thinking.thinking":"Thinking","thinking.done":"Thought for","thinking.seconds":" {n}s","thinking.expand":"Expand","thinking.collapse":"Collapse","diff.noChanges":"No changes","login.title":"CodeBuddy Remote Control","login.subtitle":"Enter the password shown in your terminal","login.placeholder":"Password","login.submit":"Login","login.error.incorrect":"Incorrect password","login.error.rateLimit":"Too many login attempts. Please try again later.","login.error.required":"Password is required","login.hint.password":"Tip: The password is displayed when the server starts.","login.hint.urlAuth":"You can also use <code>?password=xxx</code> to login automatically.","login.hint.disable":'Or set <code>gateway.auth: "none"</code> in <code>settings.json</code> under the CodeBuddy config directory (defaults to <code>~/.codebuddy</code>; override via the <code>CODEBUDDY_CONFIG_DIR</code> environment variable) to disable.',"login.slogan":"Claw Your Ideas . Into Reality","login.tagline":"Triggered Anywhere, Completed Locally.","login.privacy":"Privacy Policy","login.terms":"Terms of Service","sidebar.interactionMode":"Interaction Mode","sidebar.chatMode":"Chat","sidebar.terminalMode":"Terminal","sidebar.canvas":"Canvas","canvas.title":"Infinite Canvas","canvas.addTerminal":"Add Terminal","canvas.zoomIn":"Zoom In","canvas.zoomOut":"Zoom Out","canvas.fitView":"Fit View","canvas.resetView":"Reset View","canvas.empty":"Click the + button in the toolbar to add a terminal","canvas.openStandalone":"Open canvas in new window","canvas.tileMenu.close":"Close","canvas.tileMenu.duplicate":"Duplicate Terminal","canvas.tileMenu.maximize":"Maximize","canvas.tileMenu.minimize":"Minimize","canvas.tileMenu.restore":"Restore","canvas.tileMenu.openStandalone":"Open in new window","canvas.standalone.missingPaneId":"Missing pane ID","canvas.defaultTitle":"Terminal","terminal.connecting":"Connecting terminal...","terminal.title":"Terminal","terminal.disconnected":"Terminal disconnected","terminal.error":"Terminal connection failed","terminal.reconnect":"Reconnect","terminal.splitHorizontal":"Split Right","terminal.splitVertical":"Split Down","terminal.closePane":"Close Terminal","terminal.maxPanes":"Max panes reached","sidebar.instances":"Instances","sidebar.activeInstances":"active instances","sidebar.manageInstances":"Manage Instances","sidebar.remoteControl":"Channels","instance.title":"Instance List","instance.switch":"Instance","instance.switchTitle":"Switch Instance","instance.current":"Current","instance.manual":"Manual","instance.switchTo":"Switch to this instance","instance.manage":"Manage Instances","instance.managerTitle":"Instance Manager","instance.addInstance":"Add Instance","instance.name":"Instance Name","instance.namePlaceholder":"Custom instance name (optional, defaults to directory name)","instance.url":"Instance URL","instance.urlPlaceholder":"https://example.trycloudflare.com","instance.password":"Password","instance.optional":"Optional","instance.passwordPlaceholder":"Access password","instance.cancel":"Cancel","instance.add":"Add","instance.remove":"Remove this instance","instance.noInstances":"No other instances","instance.noInstancesHint":"Start more CodeBuddy Code instances or add remote instances manually","instance.cwd":"Working Directory","instance.topic":"Topic","instance.startedAt":"Started at","instance.local":"Local","instance.tunnel":"Tunnel","instance.uptime.days":"d ago","instance.uptime.hours":"h ago","instance.uptime.minutes":"m ago","instance.uptime.justNow":"Just now","instance.addError":"Failed to add instance","instance.removeError":"Failed to remove instance","instance.copyUrl":"Copy URL","instance.copied":"Copied","instance.subtitle":"Manage and switch between instances","instance.refresh":"Refresh","instance.refreshed":"Refreshed","instance.loading":"Loading instances...","instance.error":"Failed to load instances","instance.retry":"Retry","question.multiple":"multiple","question.customAnswer":"Or type a custom answer...","question.reviewAnswers":"Review answers","question.singleTitle":"Question","question.titleWithCount":"Questions ({count})","question.reviewTab":"Review","question.next":"Next","question.submit":"Submit","question.cancel":"Cancel","question.answered":"Answered","question.cancelled":"Question cancelled","todo.title":"Tasks","todo.executing":"Task {n} executing","todo.untitled":"Untitled","history.title":"Sessions","history.description":"Click a session to switch to that conversation","history.noData":"No sessions","history.noDataHint":"Start a new conversation","history.backToChat":"Back to Chat","history.loading":"Loading...","history.loadError":"Failed to load","history.retry":"Retry","history.current":"Current","history.messages":"{count} messages","history.delete":"Delete","history.deleteConfirm":"Are you sure you want to delete this session?","history.deleteCancel":"Cancel","history.deleteOk":"Delete","history.rename":"Rename","history.renameTitle":"Rename Session","history.renamePlaceholder":"Enter new name","history.renameCancel":"Cancel","history.renameOk":"OK","history.cannotDeleteCurrent":"Cannot delete current session","settings.title":"Preferences","settings.appearance":"Appearance","settings.model":"Model Selection","settings.mode":"Permission Mode","settings.systemInfo":"System Info","settings.backToChat":"Back to Chat","settings.tab.user":"User","settings.tab.project":"Project","settings.group.modelAndReasoning":"Model & Reasoning","settings.group.behavior":"Behavior","settings.group.memory":"Memory","settings.group.language":"Language","settings.group.advanced":"Advanced","settings.group.sandbox":"Security Sandbox","settings.item.model":"Default Model","settings.item.model.desc":"Set the default AI model","settings.item.reasoningEffort":"Reasoning Effort","settings.item.reasoningEffort.desc":"Control model reasoning depth","settings.item.alwaysThinkingEnabled":"Always Enable Thinking","settings.item.autoCompactEnabled":"Auto Compact Context","settings.item.includeCoAuthoredBy":"Include Co-authored-by","settings.item.fileCheckpointingEnabled":"File Checkpointing","settings.item.fileCheckpointingEnabled.desc":"Enable file version rollback","settings.item.promptSuggestionEnabled":"Prompt Suggestions","settings.item.ignoreGitIgnore":"Ignore .gitignore","settings.item.ignoreGitIgnore.desc":"Ignore .gitignore rules when searching","settings.item.deferToolLoading":"Defer Tool Loading","settings.item.hookOutputCollapsed":"Collapse Hook Output","settings.item.memory.enabled":"Enable Memory","settings.item.memory.autoMemoryEnabled":"Auto Memory","settings.item.memory.autoMemoryEnabled.desc":"Auto-save important info to memory","settings.item.language":"Response Language","settings.item.language.desc":"Language for AI responses","settings.item.cleanupPeriodDays":"Chat History Retention (days)","settings.item.imageHistoryRetainRounds":"Image Retention Rounds","settings.item.imageHistoryRetainRounds.desc":"Rounds to retain images in history","settings.item.env":"Environment Variables","settings.item.env.desc":"Variables applied to each session (JSON)","settings.item.sandbox.enabled":"Enable Sandbox","settings.item.sandbox.enabled.desc":"Run Bash commands in sandbox, restrict file and network access","settings.item.sandbox.autoAllowBashIfSandboxed":"Auto-approve in Sandbox","settings.item.sandbox.autoAllowBashIfSandboxed.desc":"Auto-approve commands when running in sandbox","settings.loading":"Loading...","settings.saved":"Saved","settings.saveFailed":"Save failed","settings.notSet":"Not set","settings.default":"Default","settings.reset":"Reset","settings.noProjectSettings":"No project-level settings available","settings.effort.minimal":"Minimal","settings.effort.low":"Low","settings.effort.medium":"Medium","settings.effort.high":"High","settings.effort.xhigh":"Extra High","settings.effort.max":"Max","page.title":"CodeBuddy Code","tool.processExited":"[Process exited]","tool.itemsCount":"{count} items","tool.showAllItems":"Show all {count} items","tool.moreLinesCount":"... {count} more lines","tool.generatedImage":"Generated image","tool.editedImage":"Edited image","tool.imageGen":"ImageGen","tool.imageEdit":"ImageEdit","tool.toolSearch":"ToolSearch","tool.teamCreate":"TeamCreate","tool.teamDelete":"TeamDelete","tool.taskCreate":"TaskCreate","tool.taskUpdate":"TaskUpdate","tool.taskList":"TaskList","tool.taskGet":"TaskGet","tool.sendMessage":"SendMessage","tool.shutdown":"Shutdown","tool.taskCompleted":"Task completed","tool.shutdownRejected":"Shutdown rejected","tool.planResponse":"Plan response","tool.approved":"approved","tool.rejected":"rejected","tool.userRejectedResult":"User rejected this tool use","tool.webSearch":"WebSearch","tool.webFetch":"WebFetch","tool.saveMemory":"SaveMemory","tool.askUserQuestion":"AskUserQuestion","tool.enterPlanMode":"Enter Plan Mode","tool.exitPlanMode":"Exit Plan Mode","tool.allowedActions":"Allowed actions:","tool.skill":"Skill","tool.agent":"Agent","tool.failed":"failed","tool.completed":"completed","tool.toolsCount":"{count} tools","tool.background":"background","tool.permissionsCount":"{count} permissions","terminal.unknownError":"Unknown error","terminal.processExited":"[Process exited]","terminal.connectionLost":"Connection lost","terminal.wsConnectionFailed":"WebSocket connection failed","terminal.createSessionFailed":"Failed to create terminal session","terminal.reconnectFailed":"Reconnect failed","team.title":"Team","team.activeCount":"{count} active","team.doneCount":"{count} done","team.waitingForTeammates":"Waiting for {count} teammate{s}…","team.backToMain":"Back to main chat","team.loadingHistory":"Loading conversation…","team.noHistory":"No conversation history yet","team.agentRunning":"Agent is running…","team.delivered":"Delivered","team.showLess":"Show less","team.moreLines":"… ({count} more lines)","team.tools":"{count} tools","team.tokens":"{count} tokens","instance.tunnelMode":"Tunnel","instance.localMode":"Local","workspace.searchPlaceholder":"Search directories...","workspace.switch":"Switch","workspace.switchHere":"Switch to this directory","workspace.switching":"Switching...","workspace.noResults":"No matching directories","workspace.emptyDir":"This directory is empty","workspace.pathPlaceholder":"Enter path or directory name...","workspace.selectDir":"Create bot in this directory","workspace.filterPlaceholder":"Filter subdirectories...","workspace.recent.title":"Recent Workspaces","workspace.recent.daysAgo":"d ago","workspace.recent.hoursAgo":"h ago","workspace.recent.minutesAgo":"m ago","workspace.recent.justNow":"Just now","workspace.recent.remove":"Remove","workspace.browseTitle":"Browse Workspaces","workspace.recentWorkspaces":"Recent Workspaces","workspace.createNew":"Create New Bot","workspace.browseDir":"Browse Directory","workspace.instanceLocal":"Local","workspace.instanceTunnel":"Tunnel","workspace.instanceCurrent":"Current","workspace.switchInstance":"Switch","workspace.switchingInstance":"Switching...","workspace.switchingWithGateway":"Preparing to switch...","workspace.instanceStarted":"Started","workspace.noWorkspaces":"No active workspaces","workspace.noWorkspacesHint":"Browse directories to create a new bot","workspace.instanceCount":"{count} bots","question.multiLabel":"multi","tasks.title":"Recommended Templates","tasks.subtitle":"Select a template to create a scheduled task","tasks.loading":"Loading recommended templates...","tasks.error":"Failed to load templates","tasks.retry":"Retry","tasks.refresh":"Refresh","tasks.refreshed":"Refreshed","tasks.empty":"No templates available","tasks.interval":"Every {value}","tasks.interval.1d":"Daily","tasks.interval.2d":"Every 2 days","tasks.interval.3d":"Every 3 days","tasks.interval.1w":"Weekly","tasks.interval.2w":"Every 2 weeks","tasks.interval.1m":"Monthly","scheduled.title":"Scheduled Tasks","scheduled.subtitle":"Active scheduled tasks in the current session","scheduled.loading":"Loading...","scheduled.empty":"No scheduled tasks","scheduled.emptyHint":"Use /loop or CronCreate in chat to create one","scheduled.create":"Create Task","scheduled.creating":"Creating...","scheduled.delete":"Delete","scheduled.cron":"Cron Expression","scheduled.prompt":"Prompt","scheduled.promptPlaceholder":"Prompt to execute on each fire...","scheduled.recurring":"Recurring","scheduled.oneShot":"One-shot","scheduled.durable":"Durable","scheduled.sessionOnly":"Session-only","scheduled.lastFired":"Last fired","plugins.title":"Plugins","plugins.installedPlugins":"Installed Plugins","plugins.browseMarketplace":"Browse Marketplace","plugins.marketplaces":"Marketplaces","plugins.enabled":"Enabled","plugins.disabled":"Disabled","plugins.enable":"Enable","plugins.disable":"Disable","plugins.uninstall":"Uninstall","plugins.install":"Install","plugins.confirmUninstall":"Are you sure you want to uninstall this plugin?","plugins.marketplace":"Marketplace","plugins.addMarketplace":"Add Marketplace","plugins.removeMarketplace":"Remove","plugins.confirmRemoveMarketplace":"Are you sure you want to remove this marketplace?","plugins.noPlugins":"No plugins installed","plugins.noPluginsHint":"Install plugins from a marketplace to extend functionality","plugins.noMarketplaces":"No marketplaces configured","plugins.noMarketplacesHint":"Add a plugin marketplace to browse and install plugins","plugins.selectMarketplace":"Select Marketplace","plugins.selectMarketplaceHint":"Select a marketplace to browse available plugins","plugins.marketplaceNotFound":"Marketplace not found","plugins.noAvailablePlugins":"No available plugins in this marketplace","plugins.noAvailablePluginsHint":"Try adding other marketplaces or check back later","plugins.installed":"Installed","plugins.browsingMarketplace":"Loading...","plugins.loading":"Loading...","plugins.error":"Failed to load plugins","plugins.retry":"Retry","plugins.sourcePlaceholder":"Marketplace URL (Git URL or local path)","plugins.namePlaceholder":"Marketplace name (optional)","plugins.cancel":"Cancel","plugins.add":"Add","plugins.version":"Version","plugins.operationFailed":"Operation failed","plugins.searchPlaceholder":"Search plugins...","plugins.allMarketplaces":"All Marketplaces","plugins.noSearchResults":"No matching plugins found","plugins.totalCount":"plugins","plugins.refresh":"Refresh","plugins.installedLabel":"Installed","plugins.category":"Category","plugins.author":"Author","plugins.license":"License","plugins.homepage":"Homepage","plugins.repository":"Repository","plugins.source":"Source","plugins.keywords":"Keywords","plugins.features":"Features","plugins.scope":"Scope","plugins.scope.user":"User","plugins.scope.project":"Project","plugins.scope.project-local":"Local","plugins.installScope.user":"Install for you (user scope)","plugins.installScope.project":"Install for all collaborators (project scope)","plugins.installScope.local":"Install for you, in this repo only (local scope)","plugins.policyCannotRemove":"Cannot be uninstalled","plugins.policyCannotSwitchoff":"Cannot be disabled","plugins.policyCannotEdit":"Cannot be edited","channel.from":"From","channel.group":"Group","channel.replyTo":"Reply to {source}","channel.wechat":"WeChat","channel.wecom":"WeCom","channel.wecomBot":"WeCom Bot","remoteControl.title":"Remote Control","remoteControl.subtitle":"Manage channel connections","remoteControl.connectedChannels":"Connected Channels","remoteControl.noChannels":"No channels connected","remoteControl.noChannelsHint":"Add a WeChat or WeCom channel, or install more from the marketplace","remoteControl.addWeChat":"Add WeChat Bot","remoteControl.addWeCom":"Add WeCom Bot","remoteControl.connect":"Connect","remoteControl.disconnect":"Disconnect","remoteControl.delete":"Delete","remoteControl.add":"Add","remoteControl.connected":"Connected","remoteControl.disconnected":"Disconnected","remoteControl.connecting":"Connecting...","remoteControl.installMore":"Install More Channels","remoteControl.installMoreHint":"Browse the plugin marketplace for third-party channel plugins","remoteControl.browseMarketplace":"Browse Marketplace","remoteControl.builtIn":"Built-in","remoteControl.plugin":"Plugin","remoteControl.rebind":"Rebind","remoteControl.unbind":"Unbind","remoteControl.bot":" Bot","remoteControl.default":"Default ","remoteControl.next":"Next","remoteControl.cancel":"Cancel","remoteControl.wecomBotIdHint":"From: WeCom Admin → Apps → AI Assistant","remoteControl.wecomSecretHint":"Enter Secret and press Enter or click Connect","remoteControl.fetchingQr":"Fetching QR code...","remoteControl.scanQr":"Scan QR code with WeChat","sidebar.docs":"Docs","docs.title":"Documentation","docs.search.placeholder":"Search docs...","docs.search.noResults":"No matching documents found","docs.search.resultsCount":"{count} results","docs.loading":"Loading...","docs.loadError":"Failed to load document","docs.notFound":"Document not found","docs.apiReference":"API Reference","docs.toc":"On this page","docs.retry":"Retry","docs.backToList":"Back to docs","docs.expandAll":"Expand all","docs.collapseAll":"Collapse all","docs.openStandalone":"Open in new window","sidebar.stats":"Statistics","stats.title":"Statistics","stats.loading":"Loading statistics...","stats.refresh":"Refresh","stats.noData":"No statistics available","stats.tab.overview":"Overview","stats.tab.models":"Models","stats.tab.tools":"Tools","stats.sessions":"Sessions","stats.messages":"Messages","stats.activeDays":"Active Days","stats.currentStreak":"Current Streak","stats.longestStreak":"Longest Streak","stats.peakHour":"Peak Hour","stats.longestSession":"Longest Session","stats.favoriteModel":"Favorite Model","stats.totalTokens":"Total Tokens","stats.timeRange":"Stats from the last {days} days","stats.heatmap.less":"Less","stats.heatmap.more":"More","stats.days":"days","stats.tokensPerDay":"Tokens per Day","stats.allModels":"All Models","stats.input":"Input","stats.output":"Output","stats.cacheRead":"Cache Read","stats.cacheHitRate":"Cache Hit Rate","stats.cost":"Cost","stats.topTools":"Top Tools","stats.session.title":"Current Session","stats.session.apiDuration":"API Duration","stats.session.wallTime":"Wall Time","stats.session.linesAdded":"Lines Added","stats.session.linesDeleted":"Lines Deleted","stats.session.tokens":"Tokens","stats.na":"N/A","stats.heatmap.messages":"messages","stats.funFact.moreTokens":"You've used ~{times}x more tokens than {book}","stats.funFact.sameTokens":"You've used the same number of tokens as {book}","stats.funFact.longerSession":"Your longest session is ~{times}x longer than {activity}","sidebar.traces":"Traces","traces.title":"Traces","traces.loading":"Loading...","traces.refresh":"Refresh","traces.clear":"Clear","traces.clearConfirm":"Clear all trace data?","traces.noData":"No trace data yet. Send a message and traces will be collected automatically.","traces.selectWorker":"Select Worker","traces.current":"current","traces.spanCount":"{count} spans","traces.duration":"Duration","traces.status.ok":"OK","traces.status.error":"Error","traces.status.running":"Running","traces.status.cancelled":"Cancelled","traces.bottleneck":"Bottleneck","traces.bottleneckTip":"Slowest span, {pct}% of total","traces.spanDetail":"Span Detail","traces.spanDetail.type":"Type","traces.spanDetail.duration":"Duration","traces.spanDetail.model":"Model","traces.spanDetail.tokens":"Tokens","traces.spanDetail.input":"Input","traces.spanDetail.output":"Output","traces.spanDetail.error":"Error","traces.spanDetail.cancelReason":"Cancel reason","traces.spanDetail.attributes":"Attributes","traces.legend.agent":"Agent","traces.legend.generation":"Generation","traces.legend.function":"Function","traces.legend.handoff":"Handoff","traces.legend.guardrail":"Guardrail","traces.back":"Back","traces.tab.timeline":"Timeline","traces.tab.tree":"Tree","traces.tab.flame":"Flame","traces.tab.graph":"Graph","traces.expandAll":"Expand All","traces.collapseAll":"Collapse All","traces.search":"Search spans...","traces.selfTime":"Self Time","traces.spanDetail.overview":"Overview","traces.spanDetail.io":"Input/Output","traces.noSpans":"No spans","traces.noSpansFiltered":"No spans match the current filter.","traces.clearFilter":"Clear filter","traces.auto":"auto","traces.auxiliaryCount":"{count} auxiliary traces (memory, title, etc.)","traces.noIO":"No input/output data","traces.noAttrs":"No attributes","traces.io.expand":"Expand","traces.io.collapse":"Collapse","traces.io.messages":"Messages","traces.io.less":"Less","traces.io.moreChars":"+{count} chars","traces.fit":"Fit","traces.allSessions":"All sessions","traces.allInstances":"All instances","traces.llmCalls":"{count} LLM","traces.errors":"errors","traces.noErrors":"No failed traces","traces.errorBanner":"{count} failed trace(s) detected","traces.errorBannerCta":"Show only errors →","traces.errorSummaryTitle":"{count} error(s) in this trace","traces.jumpToFirstError":"Jump to first error span","traces.copyError":"Copy","traces.onlyErrors":"Errors only","traces.filter.all":"All","traces.filter.error":"Error","traces.filter.running":"Running","traces.filter.cancelled":"Cancelled","traces.filter.ok":"OK","sidebar.metrics":"Metrics","metrics.title":"System Metrics","metrics.loading":"Loading metrics...","metrics.refresh":"Refresh","metrics.cpu":"CPU","metrics.memory":"Memory","metrics.disk":"Disk","metrics.cores":"cores","metrics.workers":"Workers","metrics.noWorkers":"No running workers","metrics.current":"Current","metrics.uptime":"Uptime","metrics.version":"Version","sidebar.editor":"Files","editor.title":"Code Editor","editor.loading":"Loading...","editor.loadError":"Failed to load","editor.noFile":"Select a file to start editing","editor.unsaved":"Unsaved","editor.save":"Save","editor.saveAll":"Save All","editor.close":"Close","editor.closeOthers":"Close Others","editor.closeAll":"Close All","editor.newFile":"New File","editor.newFolder":"New Folder","editor.rename":"Rename","editor.delete":"Delete","editor.refresh":"Refresh","editor.emptyFolder":"Empty folder","editor.explorer":"EXPLORER","editor.toggleSidebar":"Toggle Sidebar","editor.collapseAll":"Collapse All","editor.openFolder":"Open Folder","editor.openFolderPlaceholder":"Enter directory path...","editor.parentFolder":"Parent Folder","editor.pin":"Pin","editor.unpin":"Unpin","editor.copyPath":"Copy Path","editor.copyRelativePath":"Copy Relative Path","editor.revealInExplorer":"Reveal in Explorer","editor.closeToRight":"Close to the Right","editor.closeSaved":"Close Saved","editor.quickOpen":"Quick Open File","editor.focusExplorer":"Focus Explorer","editor.recentFiles":"Recent Files","editor.quickOpenPlaceholder":"Type filename to search...","editor.quickOpenEmpty":"No matching files","editor.quickOpenLoading":"Loading file list...","editor.selected":"selected","editor.lines":"lines","editor.preview":"Switch to Preview","editor.source":"Switch to Source","sidebar.workers":"Workers","workers.title":"Worker Processes","workers.refresh":"Refresh","workers.active":"Active Workers","workers.empty":"No active worker processes","workers.daemon":"Daemon","workers.daemon.running":"Running","workers.daemon.stopped":"Stopped","workers.daemon.start":"Start","workers.daemon.starting":"Starting...","workers.daemon.stop":"Stop","workers.daemon.restart":"Restart","workers.action.logs":"Logs","workers.action.open":"Open","workers.action.kill":"Kill","workers.action.kill.confirm":"Are you sure you want to kill this worker process?","sidebar.logs":"Logs","logs.title":"Log Viewer","logs.selectWorker":"Select Worker","logs.current":"current","logs.search":"Search logs...","logs.autoRefresh":"Auto Refresh","logs.refresh":"Refresh","logs.empty":"No log content","command.btw.description":"Ask a quick side question without interrupting the main Agent work","command.clear.description":"Start a fresh conversation (previous chats remain accessible via /resume)","command.context.description":"Calculate and display context token distribution","command.cost.description":"Show the total cost and duration of the current session","command.doctor.description":"Diagnose and verify your CodeBuddy installation and settings","command.feedback.description":"Open the issue feedback page to report bugs or suggest features","command.gateway.description":'Manage the remote control gateway. Subcommands: "status" to show current status, "stop" to stop the gateway, "token" to regenerate access token, "tunnel" to start with tunnel',"command.remote-control.description":"Manage remote control long connection clients (start, stop, status, list)","command.login.description":"Switch Tencent Cloud CodeBuddy accounts","command.logout.description":"Sign out from your CodeBuddy Code account","command.plan.description":"Preview the current plan file content","command.pr-comments.description":"Get comments from a GitHub pull request","command.release-notes.description":"View release notes","command.review.description":"Review a pull request","command.skills.description":"List available skills","command.todos.description":"Display the current session's todo list","command.reload-plugins.description":"Reload all plugins, skills, agents, hooks, and MCP/LSP servers without restarting","command.plugin-validate.description":"Validate a plugin directory structure and manifest","command.init.description":"Analyzing your codebase…","command.compact.description":"Clear conversation history but keep a summary in context. Optional: /compact [instructions for summarization]","command.upgrade.description":"Open upgrade page in browser","command.statusline.description":"Set up Codebuddy Code's status line UI","command.security-review.description":"Complete a security review of the pending changes on the current branch","command.insights.description":"Generate AI-powered insights about your CodeBuddy Code usage patterns and activity","command.loop.description":"Run a prompt or slash command on a recurring interval (e.g. /loop 5m /foo, defaults to 10m)","command.task-manager.description":"Team task management - Smart task entry, assignment, tracking and analysis","sidebar.changes":"Changes","fileChanges.title":"Changes","fileChanges.changesSection":"FILE CHANGES","fileChanges.empty":"No file changes","fileChanges.showChanges":"Show file changes","fileChanges.hideChanges":"Hide file changes","fileChanges.revertAll":"Revert all","fileChanges.revertCode":"Revert code","fileChanges.revertChat":"Revert chat","fileChanges.revertCodeAndChat":"Revert all","fileChanges.checkpoints":"Checkpoints","fileChanges.noCheckpoints":"No checkpoints","filePreview.binaryNotSupported":"This file cannot be previewed in the editor","filePreview.download":"Download","error.viewCrashed":"This view encountered an error","error.appCrashed":"Something went wrong","error.newChatFailed":"Failed to create new chat, please try again","error.switchSessionFailed":"Failed to switch session, please try again","commandPalette.placeholder":"Type a command...","commandPalette.commands":"Commands","commandPalette.views":"Views","commandPalette.actions":"Actions","commandPalette.noResults":"No matching commands","commandPalette.newChat":"New Chat","commandPalette.toggleTheme":"Toggle Theme","commandPalette.toggleLocale":"Toggle Language","commandPalette.tip":"Open command palette","app.confirm":"Confirm","app.cancel":"Cancel","tool.toolSingular":"tool executed","tool.toolPlural":"tools executed","keybindings.title":"Keybindings","keybindings.search.placeholder":"Search keybindings... (e.g. submit, ctrl+enter)","keybindings.source.default":"Default","keybindings.source.user":"User","keybindings.record.title":"Record Shortcut","keybindings.record.hint":"Press desired key combination...","keybindings.record.conflict":"Conflicts with","keybindings.action.edit":"Edit","keybindings.action.reset":"Reset","keybindings.action.unbind":"Unbind","keybindings.reset.all":"Reset all","keybindings.noResults":"No matching keybindings","keybindings.empty":"No keybindings","keybindings.loading":"Loading...","keybindings.ctx.Global":"Global","keybindings.ctx.Chat":"Chat Input","keybindings.ctx.InputBox":"Text Input","keybindings.ctx.Terminal":"Terminal","keybindings.ctx.Autocomplete":"Autocomplete","keybindings.ctx.Confirmation":"Confirmation","keybindings.ctx.HistorySearch":"History Search","keybindings.ctx.Task":"Task Running","keybindings.ctx.Settings":"Settings","keybindings.ctx.CommandPalette":"Command Palette","keybindings.ctx.Select":"Select List","keybindings.ctx.PermissionDialog":"Permission Dialog","keybindings.ctx.Help":"Help","keybindings.ctx.Plugin":"Plugin","keybindings.ctx.DiffDialog":"Diff Dialog","keybindings.ctx.MessageSelector":"Message Selector","keybindings.ctxDesc.Global":"Active everywhere, regardless of focus","keybindings.ctxDesc.Chat":"When the chat input is focused","keybindings.ctxDesc.InputBox":"When a text input is active","keybindings.ctxDesc.Terminal":"When the terminal view is active","keybindings.ctxDesc.Autocomplete":"When autocomplete menu is visible","keybindings.ctxDesc.Confirmation":"When a confirmation/permission dialog is shown","keybindings.ctxDesc.HistorySearch":"When searching command history (ctrl+r)","keybindings.ctxDesc.Task":"When a task/agent is running in the foreground","keybindings.ctxDesc.Settings":"When the settings panel is open","keybindings.ctxDesc.CommandPalette":"When the command palette is open","keybindings.ctxDesc.Select":"When a select/list component is focused","keybindings.ctxDesc.PermissionDialog":"When a tool permission dialog is shown","keybindings.ctxDesc.Help":"When the help overlay is open","keybindings.ctxDesc.Plugin":"When the plugin dialog is open","keybindings.ctxDesc.DiffDialog":"When the diff dialog is open","keybindings.ctxDesc.MessageSelector":"When the message selector (rewind) is open","keybindings.act.app:interrupt":"Interrupt","keybindings.act.app:exit":"Exit","keybindings.act.app:redraw":"Redraw Screen","keybindings.act.app:toggleTodos":"Toggle Todos","keybindings.act.app:toggleTranscript":"Toggle Transcript","keybindings.act.app:toggleSidebar":"Toggle Sidebar","keybindings.act.app:toggleTerminal":"Toggle Terminal","keybindings.act.app:commandPalette":"Command Palette","keybindings.act.app:newChat":"New Chat","keybindings.act.app:settings":"Settings","keybindings.act.app:focusInput":"Focus Input","keybindings.act.app:keybindings":"Keybinding Settings","keybindings.act.history:search":"Search History","keybindings.act.history:previous":"Previous History","keybindings.act.history:next":"Next History","keybindings.act.history:open":"Open History","keybindings.act.chat:cancel":"Cancel","keybindings.act.chat:submit":"Submit","keybindings.act.chat:newline":"New Line","keybindings.act.chat:killAgents":"Kill Agents","keybindings.act.chat:cycleMode":"Cycle Mode","keybindings.act.chat:modelPicker":"Model Picker","keybindings.act.chat:thinkingToggle":"Toggle Thinking","keybindings.act.chat:undo":"Undo","keybindings.act.chat:externalEditor":"External Editor","keybindings.act.chat:stash":"Stash","keybindings.act.chat:imagePaste":"Paste Image","keybindings.act.autocomplete:accept":"Accept","keybindings.act.autocomplete:dismiss":"Dismiss","keybindings.act.autocomplete:previous":"Previous","keybindings.act.autocomplete:next":"Next","keybindings.act.confirm:yes":"Confirm","keybindings.act.confirm:no":"Cancel","keybindings.act.confirm:previous":"Previous","keybindings.act.confirm:next":"Next","keybindings.act.confirm:toggle":"Toggle","keybindings.act.confirm:toggleExplanation":"Toggle Explanation","keybindings.act.task:background":"Run in Background","keybindings.act.historySearch:next":"Next","keybindings.act.historySearch:accept":"Accept","keybindings.act.historySearch:cancel":"Cancel","keybindings.act.historySearch:execute":"Execute","keybindings.act.settings:close":"Close Settings","keybindings.act.settings:search":"Search Settings","keybindings.act.select:previous":"Previous","keybindings.act.select:next":"Next","keybindings.act.select:accept":"Select","keybindings.act.select:cancel":"Cancel","keybindings.act.commandPalette:close":"Close Palette","keybindings.act.commandPalette:execute":"Execute Command","keybindings.act.commandPalette:previous":"Previous","keybindings.act.commandPalette:next":"Next","keybindings.act.permission:toggleDebug":"Toggle Debug","keybindings.act.diff:dismiss":"Close Diff","keybindings.act.diff:previousFile":"Previous File","keybindings.act.diff:nextFile":"Next File","keybindings.act.diff:viewDetails":"View Details","keybindings.act.plugin:toggle":"Toggle Plugin","keybindings.act.plugin:install":"Install Plugin","keybindings.act.help:dismiss":"Close Help","keybindings.act.transcript:exit":"Exit Transcript","keybindings.act.transcript:toggleShowAll":"Show All","keybindings.act.messageSelector:up":"Up","keybindings.act.messageSelector:down":"Down","keybindings.act.messageSelector:top":"Top","keybindings.act.messageSelector:bottom":"Bottom","keybindings.act.messageSelector:select":"Select","common.close":"Close","changes.revert":"Revert","changes.revertDirectory":"Revert directory","message.clickToEnlarge":"Click to enlarge","channel.botIdPlaceholder":"Enter Bot ID","channel.secretPlaceholder":"Enter Secret","filePreview.zoomOut":"Zoom Out","filePreview.zoomIn":"Zoom In","filePreview.fitToWindow":"Fit to Window","filePreview.actualSize":"Actual Size (1:1)","filePreview.pdfPreview":"PDF Preview","goal.status.usage":`Usage: /goal <condition>
|
|
638
638
|
Example: /goal all tests pass`,"goal.status.tooLong":"Goal condition is limited to {max} characters (got {actual})","goal.status.hooksDisabled":"/goal cannot run while hooks are disabled (disableAllHooks or allowManagedHooksOnly is set).","goal.status.set":"Goal set: {condition}","goal.status.setReplaced":"Goal replaced: {prev} → {condition}","goal.status.cleared":"Goal cleared: {prev}","goal.status.noGoal":"No goal set","goal.status.active":"Goal active: {condition}","goal.progress.title":"Goal not yet met… continuing","goal.progress.expand":"click to expand","goal.progress.condition":"Goal","goal.progress.reason":"Reason","goal.recap.active":"Goal active","goal.recap.achieved":"Goal achieved","goal.recap.impossible":"Goal could not be achieved","goal.recap.empty.title":"No goal set yet","goal.recap.empty.hint":"Use /goal <condition> to set a session-scoped stop hook.","goal.recap.empty.example":"Example: /goal all tests pass","goal.recap.footer.setAnother":"/goal <condition>","goal.recap.footer.toSetAnother":" to set another · ","goal.recap.footer.escDismiss":"to dismiss","goal.recap.stats.turn":"turn","goal.recap.stats.turns":"turns","goal.recap.stats.token":"token","goal.recap.stats.tokens":"tokens"}};function Pd(e,t){return t?e.replace(/\{(\w+)\}/g,(r,s)=>{const i=t[s];return i==null?r:String(i)}):e}function ne(){const{mode:e,resolved:t,setLocale:r,toggle:s}=xn();function i(d,a){const o=Md[t][d]??d;return Pd(o,a)}function l(d,a){const o=Md[t][d];if(o!==void 0)return Pd(o,a)}return{t:i,tryT:l,locale:e,resolved:t,setLocale:r,toggleLocale:s}}const Fp=4;let Kb=0;function Yb(){return`pane-${Date.now()}-${++Kb}`}function Bp(e){return{id:Yb(),ptySessionId:null,ptyStatus:"disconnected",errorMessage:null}}function or(e){return e.type==="leaf"?1:or(e.children[0])+or(e.children[1])}function vn(e){return e.type==="leaf"?[e.paneId]:[...vn(e.children[0]),...vn(e.children[1])]}function As(e,t,r,s){return e.type==="leaf"?e.paneId===t?{type:"split",direction:r,children:[{type:"leaf",paneId:t},{type:"leaf",paneId:s}],ratio:.5}:e:{...e,children:[As(e.children[0],t,r,s),As(e.children[1],t,r,s)]}}function Is(e,t){if(e.type==="leaf")return e.paneId===t?null:e;const r=Is(e.children[0],t),s=Is(e.children[1],t);return r===null?s:s===null?r:{...e,children:[r,s]}}function Up(e,t,r){if(t.length===0)return e.type==="split"?{...e,ratio:r}:e;if(e.type==="split"){const[s,...i]=t,l=[...e.children];return l[s]=Up(l[s],i,r),{...e,children:l}}return e}function Fd(e){const t=ae({"Content-Type":"application/json"});fetch(`/api/v1/pty/${e}`,{method:"DELETE",headers:t}).catch(()=>{})}function zp(){const e=Bp();return{panes:{[e.id]:e},layout:{type:"leaf",paneId:e.id},activePaneId:e.id}}const ns=zp(),pe=Ae()(Pr((e,t)=>({mode:"chat",mainView:"chat",terminalTitle:null,panes:ns.panes,layout:ns.layout,activePaneId:ns.activePaneId,setMode:r=>{e({mode:r,mainView:r==="terminal"?"terminal":"chat"})},setMainView:r=>{e({mainView:r,mode:r==="terminal"?"terminal":"chat"})},setTerminalTitle:r=>e({terminalTitle:r}),splitPane:(r,s)=>{const i=t(),l=s??i.activePaneId;if(or(i.layout)>=Fp)return;const d=Bp(),a=As(i.layout,l,r,d.id),o={...i.panes,[d.id]:d};e({layout:a,panes:o,activePaneId:d.id})},closePane:r=>{const s=t();if(or(s.layout)<=1)return;const i=Is(s.layout,r);if(!i)return;const l=s.panes[r];l!=null&&l.ptySessionId&&Fd(l.ptySessionId);const d={...s.panes};delete d[r];const a=vn(i),o=a.includes(s.activePaneId)?s.activePaneId:a[0];e({layout:i,panes:d,activePaneId:o})},setActivePaneId:r=>e({activePaneId:r}),setRatio:(r,s)=>{const i=Math.max(.1,Math.min(.9,s)),l=Up(t().layout,r,i);e({layout:l})},setPaneSession:(r,s)=>{const i={...t().panes};i[r]&&(i[r]={...i[r],ptySessionId:s},e({panes:i}))},setPaneStatus:(r,s)=>{const i={...t().panes};i[r]&&(i[r]={...i[r],ptyStatus:s},e({panes:i}))},setPaneError:(r,s)=>{const i={...t().panes};i[r]&&(i[r]={...i[r],errorMessage:s},e({panes:i}))},setPaneTitle:(r,s)=>{const i={...t().panes};i[r]&&(i[r]={...i[r],title:s},e({panes:i}))},reset:()=>{const r=t().panes;for(const i of Object.values(r))i.ptySessionId&&Fd(i.ptySessionId);const s=zp();e({panes:s.panes,layout:s.layout,activePaneId:s.activePaneId})}}),{namespace:"terminal",fields:["layout","panes"],scope:"workspace",debounceMs:500,onLoad:(e,t)=>{if(e.layout&&e.panes){const r=e.layout,s=e.panes,i=vn(r);if(i.every(l=>l in s)){const l=pe.getState().panes,d={};for(const a of i){const o=l[a],c=s[a];d[a]={...c,ptySessionId:(o==null?void 0:o.ptySessionId)??c.ptySessionId??null,ptyStatus:"disconnected",errorMessage:null}}t({layout:r,panes:d,activePaneId:i[0]})}}}})),Hp="/assets/dark-claw-cat-D_ew_BKV.png",Gp="/assets/light-claw-cat-BgBWmnmi.png",Wp="/assets/red-claw-cat--t2EuBIB.png",qp={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 Vp({size:e="medium",className:t=""}){const s=Ke(l=>l.resolved)==="dark"?Hp:Gp,i=qp[e];return n.jsxs("div",{className:`relative ${i.container} ${t}`,children:[n.jsx("img",{src:s,alt:"",className:"cat-loading-layer cat-loading-layer-base absolute inset-0 w-full h-full object-contain",decoding:"async",loading:"eager"}),n.jsx("img",{src:Wp,alt:"",className:"cat-loading-layer cat-loading-layer-color absolute inset-0 w-full h-full object-contain",decoding:"async",loading:"eager"})]})}function pt({size:e="medium",text:t="Loading...",className:r=""}){const s=qp[e];return n.jsxs("div",{className:`flex flex-col items-center justify-center gap-4 ${r}`,children:[n.jsx(Vp,{size:e}),t&&n.jsx("div",{className:`text-text-secondary ${s.text} font-medium animate-pulse`,children:t})]})}function Xb({size:e="medium",className:t=""}){return n.jsx(Vp,{size:e,className:t})}const Jr={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"},Qr={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"},Zb=2e3;function mr(){return ae({"Content-Type":"application/json"})}function Jb(e){const t=In(),r=t?`?password=${encodeURIComponent(t)}`:"";return`/api/v1/pty/${e}/output${r}`}async function Qb(e,t){try{await fetch(`/api/v1/pty/${e}/input/send`,{method:"POST",headers:mr(),body:JSON.stringify({data:t})})}catch{}}async function Bd(e,t,r){try{await fetch(`/api/v1/pty/${e}/resize`,{method:"POST",headers:mr(),body:JSON.stringify({cols:t,rows:r})})}catch{}}async function Ud(e){try{return(await fetch(`/api/v1/pty/${e}`,{headers:mr()})).ok}catch{return!1}}async function zd(e,t,r){const s={cols:e,rows:t};r&&(s.cwd=r);const i=await fetch("/api/v1/pty",{method:"POST",headers:mr(),body:JSON.stringify(s)});if(!i.ok){const a=await i.json().catch(()=>null),o=typeof(a==null?void 0:a.error)=="string"?a.error:typeof(a==null?void 0:a.message)=="string"?a.message:`HTTP ${i.status}`;throw new Error(o)}const l=await i.json(),d=l.data??l;return{sessionId:d.sessionId,cwd:typeof d.cwd=="string"?d.cwd:""}}async function Hd(e){try{const t=await fetch(`/api/v1/pty/${e}`,{headers:mr()});if(!t.ok)return null;const r=await t.json(),s=r.data??r;return{cwd:typeof(s==null?void 0:s.cwd)=="string"?s.cwd:""}}catch{return null}}async function ey(){try{const e=await fetch("/api/v1/pty",{headers:mr()});if(!e.ok)return[];const t=await e.json();return(t.data??t).sessions||[]}catch{return[]}}function ty(e){const t=pe.getState().panes,r=new Set;for(const[s,i]of Object.entries(t))s!==e&&i.ptySessionId&&r.add(i.ptySessionId);return r}function ry(e,t){const r=[];let s="",i="",l=t;for(;l<e.length;){const d=e.indexOf(`
|
|
639
639
|
`,l);if(d===-1)break;const a=e.substring(l,d);l=d+1,a===""?(i&&r.push({event:s||"message",data:i}),s="",i=""):a.startsWith("event: ")?s=a.substring(7):a.startsWith("data: ")&&(i=a.substring(6))}return{events:r,newIndex:l}}function oi({paneId:e,initialCwd:t,onPtyCreated:r}){const{t:s}=ne(),{resolved:i}=Ke(),l=pe(T=>T.panes[e]),d=pe(T=>T.activePaneId),a=pe(T=>T.layout),o=pe(T=>T.mainView),c=pe(T=>T.setActivePaneId),u=pe(T=>T.closePane),p=pe(T=>T.setPaneSession),b=pe(T=>T.setPaneStatus),y=pe(T=>T.setPaneError),k=pe(T=>T.setPaneTitle),v=pe(T=>T.setTerminalTitle),g=d===e,m=or(a),h=C.useRef(null),f=C.useRef(null),x=C.useRef(null),E=C.useRef(null),_=C.useRef(!0),S=C.useRef(!1),w=C.useRef(!1),N=C.useRef(null),L=C.useRef(null),R=C.useRef(t);R.current=t;const j=C.useRef(r);j.current=r;const $=C.useCallback(()=>{const T=E.current;T&&(T.abort(),E.current=null)},[]),G=C.useCallback((T,D)=>{$(),b(e,"connecting"),L.current=D;const I=new XMLHttpRequest;E.current=I;let P=0;I.open("GET",Jb(D)),I.setRequestHeader(bt,kt);const M=In();M&&I.setRequestHeader("Authorization",`Bearer ${M}`),I.onreadystatechange=()=>{if(I.readyState===XMLHttpRequest.HEADERS_RECEIVED)if(I.status===200){if(!_.current)return;b(e,"connected"),y(e,null);const O=x.current;if(O)try{O.fit(),Bd(D,T.cols,T.rows)}catch{}T.focus()}else{if(!_.current)return;b(e,"error"),y(e,`HTTP ${I.status}`)}},I.onprogress=()=>{if(!_.current)return;const{events:O,newIndex:Y}=ry(I.responseText,P);P=Y;let X="";for(const Q of O)try{const J=JSON.parse(Q.data);switch(Q.event){case"output":X+=J.data;break;case"exit":X&&(T.write(X),X=""),p(e,null),b(e,"disconnected"),w.current=!1,L.current=null,T.write(`\r
|
|
640
640
|
${s("terminal.processExited")}\r
|
|
@@ -685,7 +685,7 @@ ${r("tool.moreLinesCount").replace("{count}",String(i.length-t))}`})]})}function
|
|
|
685
685
|
w-64 flex-shrink-0 border-r border-border-default bg-bg-primary overflow-y-auto
|
|
686
686
|
md:relative md:translate-x-0
|
|
687
687
|
${g?"fixed inset-y-0 left-0 z-30 translate-x-0":"hidden md:block"}
|
|
688
|
-
`,children:s?n.jsx("div",{className:"flex flex-col items-center justify-center h-32",children:n.jsx(pt,{size:"small",text:e("docs.loading")})}):r?n.jsx(xS,{items:r,currentPath:i,onSelect:w}):n.jsx("div",{className:"p-4 text-sm text-text-tertiary",children:e("docs.loadError")})}),n.jsx("div",{className:"flex-1 min-w-0 overflow-hidden flex flex-col",children:L?n.jsx(yS,{query:o,results:c,onSelect:N}):d?n.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:n.jsx(pt,{size:"small",text:e("docs.loading")})}):a?n.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:n.jsxs("div",{className:"text-center",children:[n.jsx("div",{className:"text-text-tertiary text-[48px] mb-4 opacity-30",children:"📄"}),n.jsx("div",{className:"text-text-secondary text-sm mb-2",children:e("docs.notFound")}),n.jsx("div",{className:"text-text-tertiary text-xs",children:a})]})}):l?n.jsx(bS,{content:l,onNavigate:w}):n.jsxs("div",{className:"flex-1 flex flex-col items-center justify-center text-text-tertiary",children:[n.jsx("div",{className:"text-[48px] mb-4 opacity-30",children:"📖"}),n.jsx("div",{className:"text-sm",children:e("docs.title")})]})})]})]})}async function qt(e,t){var i;const r=await fetch("/api/v1/fs/list",{method:"POST",headers:{...ae(),"Content-Type":"application/json"},body:JSON.stringify({path:e,depth:t})});if(!r.ok)throw new Error(`List directory failed: HTTP ${r.status}`);const s=await r.json();return((i=s.data)==null?void 0:i.entries)??s.entries??[]}async function vS(e){const t=await fetch(`/api/v1/files/download?path=${encodeURIComponent(e)}`,{headers:ae()});if(!t.ok)throw new Error(`Read file failed: HTTP ${t.status}`);const r=await t.text();if(r.length===0){const s=Number(t.headers.get("Content-Length"));if(Number.isFinite(s)&&s>0)throw new Error(`Read file failed: empty body but Content-Length=${s}`)}return r}async function Ou(e,t){const r=await fetch(`/api/v1/files/upload?path=${encodeURIComponent(e)}`,{method:"POST",headers:{...ae(),"Content-Type":"application/octet-stream"},body:t});if(!r.ok)throw new Error(`Write file failed: HTTP ${r.status}`)}async function _S(e){const t=await fetch("/api/v1/fs/mkdir",{method:"POST",headers:{...ae(),"Content-Type":"application/json"},body:JSON.stringify({path:e})});if(!t.ok)throw new Error(`Create directory failed: HTTP ${t.status}`)}async function SS(e){const t=await fetch("/api/v1/fs/remove",{method:"POST",headers:{...ae(),"Content-Type":"application/json"},body:JSON.stringify({path:e})});if(!t.ok)throw new Error(`Remove failed: HTTP ${t.status}`)}async function kS(e){try{return await qt(e,1),"directory"}catch{return"file"}}async function $u(e,t){const r=await fetch("/api/v1/fs/move",{method:"POST",headers:{...ae(),"Content-Type":"application/json"},body:JSON.stringify({source:e,destination:t})});if(!r.ok)throw new Error(`Move failed: HTTP ${r.status}`)}const wS={".ts":"typescript",".tsx":"typescript",".mts":"typescript",".cts":"typescript",".js":"javascript",".jsx":"javascript",".mjs":"javascript",".cjs":"javascript",".json":"json",".jsonc":"json",".md":"markdown",".mdx":"markdown",".css":"css",".scss":"scss",".less":"less",".html":"html",".htm":"html",".xml":"xml",".svg":"xml",".yaml":"yaml",".yml":"yaml",".py":"python",".pyw":"python",".go":"go",".rs":"rust",".java":"java",".c":"c",".h":"c",".cpp":"cpp",".cc":"cpp",".cxx":"cpp",".hpp":"cpp",".cs":"csharp",".rb":"ruby",".php":"php",".swift":"swift",".kt":"kotlin",".kts":"kotlin",".sh":"shell",".bash":"shell",".zsh":"shell",".sql":"sql",".graphql":"graphql",".gql":"graphql",".vue":"html",".lua":"lua",".r":"r",".R":"r",".dockerfile":"dockerfile",".toml":"ini",".ini":"ini",".cfg":"ini",".env":"ini",".gitignore":"ini"};function ES(e){const t=e.substring(e.lastIndexOf("/")+1);if(t==="Dockerfile"||t.startsWith("Dockerfile."))return"dockerfile";if(t==="Makefile"||t==="GNUmakefile")return"makefile";const r=e.substring(e.lastIndexOf("."));return wS[r]||"plaintext"}const CS=new Set([".png",".jpg",".jpeg",".gif",".webp",".bmp",".ico",".tiff",".tif",".mp3",".mp4",".wav",".avi",".mov",".mkv",".flac",".ogg",".zip",".gz",".tar",".bz2",".7z",".rar",".xz",".exe",".dll",".so",".dylib",".bin",".o",".a",".pdf",".doc",".docx",".xls",".xlsx",".ppt",".pptx",".woff",".woff2",".ttf",".otf",".eot",".sqlite",".db"]);function Yh(e){const t=e.substring(e.lastIndexOf(".")).toLowerCase();return CS.has(t)}const TS=new Set([".png",".jpg",".jpeg",".gif",".webp",".bmp",".ico",".tiff",".tif"]);function NS(e){const t=e.substring(e.lastIndexOf(".")).toLowerCase();return TS.has(t)?"image":t===".svg"?"svg":t===".md"||t===".mdx"?"markdown":t===".pdf"?"pdf":Yh(e)?"binary":"editor"}const AS=2*1024*1024,IS=10;function ys(e,t,r){const s=e.filter(i=>i.path!==t);return[{path:t,name:r,timestamp:Date.now()},...s].slice(0,IS)}function RS(e){return[...e].sort((t,r)=>t.type==="directory"&&r.type!=="directory"?-1:t.type!=="directory"&&r.type==="directory"?1:t.name.localeCompare(r.name,void 0,{numeric:!0,sensitivity:"base"}))}function ju(e){return RS(e).map(t=>({name:t.name,path:t.path,type:t.type,children:(t.type==="directory",void 0)}))}function Xh(e,t,r){return e.path===t?{...e,children:r,isLoading:!1}:e.children?{...e,children:e.children.map(s=>Xh(s,t,r))}:e}function gd(e,t){const r=[];if(e.children)for(const s of e.children)r.push(s.path),s.type==="directory"&&t.has(s.path)&&s.children&&r.push(...gd(s,t));return r}function qs(e,t,r){return e.path===t?{...e,isLoading:r}:e.children?{...e,children:e.children.map(s=>qs(s,t,r))}:e}function LS(e){const t=new Map,r=new Map;for(const s of e)r.set(s.name,(r.get(s.name)||0)+1);for(const s of e)if(r.get(s.name)>1){const i=s.path.split("/"),l=i.length>=2?i[i.length-2]:"";t.set(s.id,l?`${l}/`:"")}else t.set(s.id,"");return t}const Ut=Ae()(Pr((e,t)=>({rootPath:null,tree:null,treeLoading:!1,treeError:!1,expandedPaths:new Set,selectedPath:null,selectedPaths:new Set,renamingPath:null,renamingIsNew:!1,tabs:[],activeTabId:null,recentFiles:[],splitRatio:.22,setRootPath:async r=>{e({rootPath:r,treeLoading:!0,tree:null,treeError:!1});try{const s=await qt(r),i=ju(s),l={name:r.split("/").pop()||r,path:r,type:"directory",children:i},d=t().expandedPaths,a=d instanceof Set?d:new Set;e({tree:l,treeLoading:!1,expandedPaths:new Set([r,...a])})}catch(s){console.error("[editor-store] setRootPath failed:",s),e({treeLoading:!1,treeError:!0})}},loadDirectory:async r=>{const{tree:s}=t();if(s){e({tree:qs(s,r,!0)});try{const i=await qt(r),l=ju(i),d=Xh(t().tree,r,l);e({tree:d})}catch{const i=t().tree;i&&e({tree:qs(i,r,!1)})}}},toggleExpand:r=>{const{expandedPaths:s}=t(),i=new Set(s);if(i.has(r))i.delete(r);else{i.add(r);const{tree:l}=t();if(l){const d=o=>{if(o.path===r)return o;if(o.children)for(const c of o.children){const u=d(c);if(u)return u}return null},a=d(l);a&&a.type==="directory"&&!a.children&&t().loadDirectory(r)}}e({expandedPaths:i})},selectPath:(r,s)=>{const{selectedPaths:i,selectedPath:l,tree:d,expandedPaths:a}=t();if(s!=null&&s.ctrl){const o=new Set(i);o.has(r)?(o.delete(r),e({selectedPaths:o,selectedPath:o.size>0?[...o][o.size-1]:null})):(o.add(r),e({selectedPaths:o,selectedPath:r}))}else if(s!=null&&s.shift&&l&&d){const o=gd(d,a),c=o.indexOf(l),u=o.indexOf(r);if(c>=0&&u>=0){const p=Math.min(c,u),b=Math.max(c,u),y=new Set(o.slice(p,b+1));e({selectedPaths:y,selectedPath:r})}}else e({selectedPath:r,selectedPaths:new Set([r])})},refreshTree:async()=>{const{rootPath:r}=t();r&&await t().setRootPath(r)},collapseAll:()=>{const{rootPath:r}=t(),s=new Set;r&&s.add(r),e({expandedPaths:s})},createNewFile:()=>{const{selectedPath:r,rootPath:s,tree:i,expandedPaths:l}=t();let d=s;if(r&&i){const o=u=>{if(u.path===r)return u;if(u.children)for(const p of u.children){const b=o(p);if(b)return b}return null},c=o(i);c&&(d=c.type==="directory"?c.path:c.path.substring(0,c.path.lastIndexOf("/")))}if(!d)return;l.has(d)||t().toggleExpand(d);const a=d+"/__new_file__";t().startCreateFile(a)},createNewFolder:()=>{const{selectedPath:r,rootPath:s,tree:i,expandedPaths:l}=t();let d=s;if(r&&i){const o=u=>{if(u.path===r)return u;if(u.children)for(const p of u.children){const b=o(p);if(b)return b}return null},c=o(i);c&&(d=c.type==="directory"?c.path:c.path.substring(0,c.path.lastIndexOf("/")))}if(!d)return;l.has(d)||t().toggleExpand(d);const a=d+"/__new_folder__";t().startCreateFolder(a)},startRename:r=>{e({renamingPath:r,renamingIsNew:!1,selectedPath:r})},startCreateFile:r=>{const s=r.substring(0,r.lastIndexOf("/")),{tree:i}=t();if(!i)return;const l={name:"",path:r,type:"file"},d=a=>a.path===s?{...a,children:[l,...a.children||[]]}:a.children?{...a,children:a.children.map(o=>d(o))}:a;e({tree:d(i),renamingPath:r,renamingIsNew:!0,selectedPath:r})},startCreateFolder:r=>{const s=r.substring(0,r.lastIndexOf("/")),{tree:i}=t();if(!i)return;const l={name:"",path:r,type:"directory"},d=a=>a.path===s?{...a,children:[l,...a.children||[]]}:a.children?{...a,children:a.children.map(o=>d(o))}:a;e({tree:d(i),renamingPath:r,renamingIsNew:!0,selectedPath:r})},confirmRename:async(r,s)=>{const{renamingIsNew:i}=t();if(!s.trim()){if(i){const a=r.substring(0,r.lastIndexOf("/"));e({renamingPath:null,renamingIsNew:!1}),await t().loadDirectory(a)}else e({renamingPath:null,renamingIsNew:!1});return}const l=r.substring(0,r.lastIndexOf("/")),d=l+"/"+s.trim();if(i){try{const{tree:a}=t(),o=u=>{if(u.path===r)return u;if(u.children)for(const p of u.children){const b=o(p);if(b)return b}return null},c=a?o(a):null;(c==null?void 0:c.type)==="directory"?await _S(d):await Ou(d,""),e({renamingPath:null,renamingIsNew:!1,selectedPath:d}),await t().loadDirectory(l),(c==null?void 0:c.type)!=="directory"&&await t().openFile(d,s.trim())}catch{e({renamingPath:null,renamingIsNew:!1}),await t().loadDirectory(l)}return}if(d===r){e({renamingPath:null,renamingIsNew:!1});return}try{await $u(r,d),e(a=>({renamingPath:null,renamingIsNew:!1,selectedPath:d,tabs:a.tabs.map(o=>o.path===r?{...o,id:d,path:d,name:s.trim()}:o),activeTabId:a.activeTabId===r?d:a.activeTabId})),await t().loadDirectory(l)}catch{e({renamingPath:null,renamingIsNew:!1})}},cancelRename:()=>{const{renamingIsNew:r,renamingPath:s}=t();if(r&&s){const i=s.substring(0,s.lastIndexOf("/"));e({renamingPath:null,renamingIsNew:!1}),t().loadDirectory(i)}else e({renamingPath:null,renamingIsNew:!1})},openFile:async(r,s)=>{const{tabs:i}=t(),l=i.find(c=>c.path===r);if(l){e({activeTabId:l.id,selectedPath:r});return}const d=s||r.substring(r.lastIndexOf("/")+1),a=ES(r),o=NS(r);if(o==="image"||o==="pdf"||o==="binary"){const c={id:r,path:r,name:d,content:"",originalContent:"",language:a,isDirty:!1,isPinned:!1,viewMode:o};e(u=>({tabs:[...u.tabs,c],activeTabId:c.id,selectedPath:r,recentFiles:ys(u.recentFiles,r,d)}));return}try{const c=await vS(r);if(c.length>AS)return;const u={id:r,path:r,name:d,content:c,originalContent:c,language:a,isDirty:!1,isPinned:!1,viewMode:o};e(p=>({tabs:[...p.tabs,u],activeTabId:u.id,selectedPath:r,recentFiles:ys(p.recentFiles,r,d)}))}catch{}},closeTab:r=>{e(s=>{const i=s.tabs.find(c=>c.id===r),l=s.tabs.findIndex(c=>c.id===r),d=s.tabs.filter(c=>c.id!==r);let a=s.activeTabId;s.activeTabId===r&&(a=d.length>0?d[Math.min(l,d.length-1)].id:null);const o=i?ys(s.recentFiles,i.path,i.name):s.recentFiles;return{tabs:d,activeTabId:a,recentFiles:o}})},closeOtherTabs:r=>{e(s=>({tabs:s.tabs.filter(i=>i.id===r||i.isPinned),activeTabId:r}))},closeAllTabs:()=>{e(r=>{const s=r.tabs.filter(i=>i.isPinned);return{tabs:s,activeTabId:s.length>0?s[0].id:null}})},closeTabsToRight:r=>{e(s=>{const i=s.tabs.findIndex(a=>a.id===r);if(i<0)return s;const l=s.tabs.filter((a,o)=>o<=i||a.isPinned),d=l.some(a=>a.id===s.activeTabId);return{tabs:l,activeTabId:d?s.activeTabId:r}})},closeSavedTabs:()=>{e(r=>{const s=r.tabs.filter(l=>l.isPinned||l.isDirty),i=s.some(l=>l.id===r.activeTabId);return{tabs:s,activeTabId:i?r.activeTabId:s.length>0?s[0].id:null}})},setActiveTab:r=>{const s=t().tabs.find(i=>i.id===r);e({activeTabId:r,selectedPath:(s==null?void 0:s.path)||null})},updateTabContent:(r,s)=>{e(i=>({tabs:i.tabs.map(l=>l.id===r?{...l,content:s,isDirty:s!==l.originalContent}:l)}))},saveTab:async r=>{const s=t().tabs.find(i=>i.id===r);if(!(!s||!s.isDirty))try{await Ou(s.path,s.content),e(i=>({tabs:i.tabs.map(l=>l.id===r?{...l,originalContent:l.content,isDirty:!1}:l)}))}catch{}},deleteSelected:async()=>{const{selectedPaths:r,tabs:s}=t();if(r.size===0)return;const i=[...r],l=new Set(i.map(d=>d.substring(0,d.lastIndexOf("/"))));try{await Promise.all(i.map(a=>SS(a)));const d=s.filter(a=>!i.some(o=>a.path===o||a.path.startsWith(o+"/")));e(a=>({selectedPaths:new Set,selectedPath:null,tabs:d,activeTabId:d.length>0?d.find(o=>o.id===a.activeTabId)?a.activeTabId:d[0].id:null}));for(const a of l)await t().loadDirectory(a)}catch{for(const d of l)await t().loadDirectory(d)}},moveToDirectory:async(r,s)=>{if(r.length===0)return;const i=new Set(r.map(l=>l.substring(0,l.lastIndexOf("/"))));i.add(s);try{for(const l of r){const d=l.substring(l.lastIndexOf("/")+1),a=s+"/"+d;l!==a&&await $u(l,a)}e({selectedPaths:new Set,selectedPath:null});for(const l of i)await t().loadDirectory(l)}catch{for(const l of i)await t().loadDirectory(l)}},revealInTree:async r=>{const{rootPath:s}=t();if(!s||!r.startsWith(s))return;const l=r.slice(s.length).replace(/^\//,"").split("/").filter(Boolean),d=new Set(t().expandedPaths);let a=s;d.add(s);for(const o of l)if(a=a+"/"+o,a!==r){d.add(a);const{tree:c}=t();if(c){const u=b=>{if(b.path===a)return b;if(b.children)for(const y of b.children){const k=u(y);if(k)return k}return null},p=u(c);p&&p.type==="directory"&&!p.children&&await t().loadDirectory(a)}}e({expandedPaths:d,selectedPath:r})},reorderTabs:(r,s)=>{e(i=>{const l=[...i.tabs],[d]=l.splice(r,1);return l.splice(s,0,d),{tabs:l}})},pinTab:r=>{e(s=>{const i=s.tabs.findIndex(o=>o.id===r);if(i<0)return s;const l=[...s.tabs];l[i]={...l[i],isPinned:!0};const[d]=l.splice(i,1),a=l.reduce((o,c,u)=>c.isPinned?u:o,-1);return l.splice(a+1,0,d),{tabs:l}})},unpinTab:r=>{e(s=>({tabs:s.tabs.map(i=>i.id===r?{...i,isPinned:!1}:i)}))},setSplitRatio:r=>{const s=Math.max(.12,Math.min(.5,r));e({splitRatio:s})}}),{namespace:"editor",fields:["splitRatio","expandedPaths","recentFiles"],scope:"workspace",debounceMs:500,onLoad:(e,t)=>{const r={};if(e.splitRatio!==void 0&&(r.splitRatio=e.splitRatio),e.expandedPaths){const s=e.expandedPaths;r.expandedPaths=new Set(Array.isArray(s)?s:[])}e.recentFiles&&(r.recentFiles=e.recentFiles),Object.keys(r).length>0&&t(r)}}));function DS(e){return[...e].sort((t,r)=>t.type==="directory"&&r.type!=="directory"?-1:t.type!=="directory"&&r.type==="directory"?1:t.name.localeCompare(r.name,void 0,{numeric:!0,sensitivity:"base"}))}function OS({filePath:e,rootPath:t,onSegmentClick:r,onOpenFile:s}){const l=(e.startsWith(t)?e.slice(t.length).replace(/^\//,""):e).split("/").filter(Boolean),[d,a]=C.useState(null),[o,c]=C.useState([]),[u,p]=C.useState(!1),[b,y]=C.useState(-1),k=C.useRef(null),v=C.useRef(null),g=C.useCallback(async(E,_)=>{const S=_.getBoundingClientRect();a({dirPath:E,anchorRect:S}),p(!0),c([]),y(-1);try{const w=await qt(E);c(DS(w.map(N=>({name:N.name,path:N.path,type:N.type}))))}catch{c([])}p(!1)},[]),m=C.useCallback(()=>{a(null),c([]),y(-1)},[]),h=C.useCallback(E=>{E.type==="directory"?(r(E.path),m()):(s(E.path),m())},[r,s,m]);C.useEffect(()=>{if(!d)return;const E=_=>{if(_.key==="Escape"){_.preventDefault(),m();return}_.key==="ArrowDown"?(_.preventDefault(),y(S=>S<o.length-1?S+1:0)):_.key==="ArrowUp"?(_.preventDefault(),y(S=>S>0?S-1:o.length-1)):_.key==="Enter"&&b>=0&&b<o.length&&(_.preventDefault(),h(o[b]))};return window.addEventListener("keydown",E),()=>window.removeEventListener("keydown",E)},[d,o,b,m,h]),C.useEffect(()=>{var E;b>=0&&v.current&&((E=v.current.querySelectorAll(".breadcrumb-dropdown-item")[b])==null||E.scrollIntoView({block:"nearest"}))},[b]);const f=C.useCallback((E,_)=>{E.stopPropagation();const S=E.currentTarget;d&&d.dirPath===_?m():g(_,S)},[d,g,m]),x=C.useCallback((E,_)=>{E.stopPropagation();const S=E.currentTarget;d&&d.dirPath===_?m():g(_,S)},[d,g,m]);return n.jsxs("div",{className:"editor-breadcrumbs",children:[n.jsx("span",{style:{display:"inline-flex",alignItems:"center"},children:n.jsx("span",{className:`editor-breadcrumb-segment ${l.length===0?"active":""}`,onClick:E=>f(E,t),children:n.jsx("span",{children:t.split("/").pop()||t})})}),l.map((E,_)=>{const S=_===l.length-1,w=t+"/"+l.slice(0,_+1).join("/"),N=_===0?t:t+"/"+l.slice(0,_).join("/");return n.jsxs("span",{style:{display:"inline-flex",alignItems:"center"},children:[n.jsx("span",{className:"editor-breadcrumb-separator",children:n.jsx(Ne,{size:10})}),n.jsxs("span",{className:`editor-breadcrumb-segment ${S?"active":""} ${(d==null?void 0:d.dirPath)===(S?N:w)?"dropdown-open":""}`,onClick:L=>S?x(L,N):f(L,w),children:[S&&n.jsx(Gt,{name:E,type:"file",size:14}),n.jsx("span",{style:S?{fontWeight:500}:void 0,children:E})]})]},w)}),d&&n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"breadcrumb-dropdown-overlay",onClick:m}),n.jsx("div",{ref:k,className:"breadcrumb-dropdown",style:{left:Math.min(d.anchorRect.left,window.innerWidth-260),top:d.anchorRect.bottom+2},children:u?n.jsx("div",{className:"breadcrumb-dropdown-loading",children:n.jsx(we,{size:14,className:"animate-spin"})}):o.length===0?n.jsx("div",{className:"breadcrumb-dropdown-empty",children:"Empty"}):n.jsx("div",{className:"breadcrumb-dropdown-list",ref:v,children:o.map((E,_)=>{const S=E.path===e,w=_===b;return n.jsxs("div",{className:`breadcrumb-dropdown-item ${S?"current":""} ${w?"highlighted":""}`,onClick:()=>h(E),children:[E.type==="directory"?n.jsx(Ne,{size:12,style:{flexShrink:0,opacity:.5}}):n.jsx(Gt,{name:E.name,type:E.type,size:16}),n.jsx("span",{className:"breadcrumb-dropdown-item-name",children:E.name})]},E.path)})})})]})]})}function $S({path:e,content:t,language:r,onContentChange:s,onSave:i,minimap:l=!0,onCursorChange:d}){const{t:a}=ne(),{resolved:o}=Ke(),c=C.useRef(null),u=C.useRef(d);u.current=d;const p=o==="dark"?"vs-dark":"vs",b=C.useCallback((k,v)=>{c.current=k,k.addCommand(v.KeyMod.CtrlCmd|v.KeyCode.KeyS,()=>{i()});const g=()=>{const m=u.current;if(!m)return;const h=k.getPosition(),f=k.getSelection();if(!h)return;let x=0,E=0;if(f&&!f.isEmpty()){const _=k.getModel();_&&(x=_.getValueInRange(f).length,E=Math.abs(f.endLineNumber-f.startLineNumber)+1)}m(h.lineNumber,h.column,x,E)};k.onDidChangeCursorPosition(g),k.onDidChangeCursorSelection(g),g()},[i]),y=C.useCallback(k=>{k!==void 0&&s(k)},[s]);return C.useEffect(()=>{const k=c.current;if(!k)return;const v=k.getModel();v&&t.length>0&&v.getValue()!==t&&v.setValue(t)},[t]),n.jsx(Ex,{height:"100%",language:r,theme:p,defaultValue:t,onChange:y,onMount:b,loading:n.jsxs("div",{className:"flex items-center justify-center h-full gap-2",style:{color:"var(--color-text-tertiary)"},children:[n.jsx(we,{size:16,className:"animate-spin"}),n.jsx("span",{style:{fontSize:13},children:a("editor.loading")})]}),options:{fontSize:13,fontFamily:"'Menlo', 'Monaco', 'Consolas', 'Courier New', monospace",lineHeight:20,minimap:{enabled:l,maxColumn:80},scrollBeyondLastLine:!1,automaticLayout:!0,wordWrap:"off",tabSize:4,insertSpaces:!0,renderWhitespace:"selection",bracketPairColorization:{enabled:!0},padding:{top:8},smoothScrolling:!0,cursorBlinking:"smooth",cursorSmoothCaretAnimation:"on",fixedOverflowWidgets:!0}},e)}const Mu={image:"Image",svg:"SVG",markdown:"Markdown Preview",pdf:"PDF",binary:"Binary"};function Pu({language:e,cursorLine:t,cursorColumn:r,selectedCount:s,selectedLines:i,viewMode:l="editor",imageInfo:d,zoom:a,extraRight:o}){const{t:c}=ne();if(l==="image"||l==="svg")return n.jsxs("div",{className:"editor-statusbar",children:[n.jsx("div",{className:"editor-statusbar-left",children:d&&n.jsxs("span",{className:"editor-statusbar-item",children:[d.width," × ",d.height]})}),n.jsxs("div",{className:"editor-statusbar-right",children:[a!=null&&n.jsxs("span",{className:"editor-statusbar-item",children:[Math.round(a*100),"%"]}),n.jsx("span",{className:"editor-statusbar-item",children:Mu[l]}),o]})]});if(l!=="editor")return n.jsxs("div",{className:"editor-statusbar",children:[n.jsx("div",{className:"editor-statusbar-left"}),n.jsxs("div",{className:"editor-statusbar-right",children:[n.jsx("span",{className:"editor-statusbar-item",children:Mu[l]||l}),o]})]});const u=`Ln ${t}, Col ${r}`,p=s&&s>0?i&&i>1?` (${s} ${c("editor.selected")}, ${i} ${c("editor.lines")})`:` (${s} ${c("editor.selected")})`:"";return n.jsxs("div",{className:"editor-statusbar",children:[n.jsx("div",{className:"editor-statusbar-left",children:n.jsxs("span",{className:"editor-statusbar-item",children:[u,p]})}),n.jsxs("div",{className:"editor-statusbar-right",children:[n.jsx("span",{className:"editor-statusbar-item",children:e}),n.jsx("span",{className:"editor-statusbar-item",children:"UTF-8"}),n.jsx("span",{className:"editor-statusbar-item",children:"LF"}),n.jsx("span",{className:"editor-statusbar-item",children:"Spaces: 4"}),o]})]})}function Fu({actions:e}={}){const{t}=ne(),{tabs:r,activeTabId:s,rootPath:i,setActiveTab:l,closeTab:d,closeOtherTabs:a,closeAllTabs:o,closeTabsToRight:c,closeSavedTabs:u,reorderTabs:p,pinTab:b,unpinTab:y}=Ut(),[k,v]=C.useState(null),g=C.useRef(null),[m,h]=C.useState(null),f=C.useRef(-1),x=C.useRef(null),[E,_]=C.useState(!1),[S,w]=C.useState(!1),N=C.useMemo(()=>LS(r),[r]),L=C.useCallback(()=>{const M=x.current;M&&(_(M.scrollLeft>0),w(M.scrollLeft+M.clientWidth<M.scrollWidth-1))},[]);C.useEffect(()=>{const M=x.current;if(!M)return;L(),M.addEventListener("scroll",L,{passive:!0});const H=new ResizeObserver(L);return H.observe(M),()=>{M.removeEventListener("scroll",L),H.disconnect()}},[L,r.length]);const R=C.useCallback(()=>{var M;(M=x.current)==null||M.scrollBy({left:-150,behavior:"smooth"})},[]),j=C.useCallback(()=>{var M;(M=x.current)==null||M.scrollBy({left:150,behavior:"smooth"})},[]),$=C.useCallback((M,H)=>{M.preventDefault(),v({x:M.clientX,y:M.clientY,tabId:H})},[]),G=C.useCallback(()=>{v(null)},[]),F=C.useCallback((M,H)=>{M.button===1&&(M.preventDefault(),d(H))},[d]),W=C.useCallback((M,H)=>{f.current=H,M.dataTransfer.effectAllowed="move",M.currentTarget instanceof HTMLElement&&M.dataTransfer.setDragImage(M.currentTarget,0,0)},[]),V=C.useCallback((M,H)=>{M.preventDefault(),M.dataTransfer.dropEffect="move",h(H)},[]),q=C.useCallback((M,H)=>{M.preventDefault();const z=f.current;z>=0&&z!==H&&p(z,H),f.current=-1,h(null)},[p]),A=C.useCallback(()=>{f.current=-1,h(null)},[]),T=C.useCallback(M=>{const H=r.find(z=>z.id===M);H&&navigator.clipboard.writeText(H.path),G()},[r,G]),D=C.useCallback(M=>{const H=r.find(z=>z.id===M);if(H&&i){const z=H.path.startsWith(i+"/")?H.path.slice(i.length+1):H.path;navigator.clipboard.writeText(z)}else H&&navigator.clipboard.writeText(H.path);G()},[r,i,G]),I=C.useCallback(M=>{const H=r.find(z=>z.id===M);if(H){const{selectPath:z,toggleExpand:U,expandedPaths:O}=Ut.getState(),Y=H.path.split("/");for(let X=1;X<Y.length;X++){const Q=Y.slice(0,X).join("/");Q&&!O.has(Q)&&U(Q)}z(H.path)}G()},[r,G]);if(r.length===0)return null;const P=k?r.find(M=>M.id===k.tabId):null;return n.jsxs(n.Fragment,{children:[n.jsxs("div",{className:"editor-tabs-wrapper",children:[E&&n.jsx("button",{className:"editor-tabs-scroll-btn",onClick:R,children:n.jsx(tg,{size:14})}),n.jsx("div",{className:"editor-tabs",ref:x,children:r.map((M,H)=>n.jsxs("div",{className:`editor-tab${M.id===s?" active":""}${m===H?" drag-indicator":""}`,onClick:()=>l(M.id),onMouseDown:z=>F(z,M.id),onContextMenu:z=>$(z,M.id),title:M.path,draggable:!0,onDragStart:z=>W(z,H),onDragOver:z=>V(z,H),onDrop:z=>q(z,H),onDragEnd:A,children:[n.jsx(Gt,{name:M.name,type:"file",size:14}),n.jsx("span",{className:"editor-tab-name",children:M.name}),N.get(M.id)&&n.jsx("span",{className:"editor-tab-description",children:N.get(M.id)}),M.isPinned?M.isDirty?n.jsx("span",{className:"dirty-dot"}):n.jsx("span",{className:"pin-icon",children:n.jsx(Wf,{size:14})}):M.isDirty?n.jsx("span",{className:"dirty-dot"}):n.jsx("button",{className:"close-btn",onClick:z=>{z.stopPropagation(),d(M.id)},children:n.jsx(Te,{size:12})})]},M.id))}),S&&n.jsx("button",{className:"editor-tabs-scroll-btn",onClick:j,children:n.jsx(Ne,{size:14})}),e&&n.jsx("div",{className:"editor-tabs-actions",children:e})]}),k&&n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"editor-context-overlay",onClick:G}),n.jsxs("div",{ref:g,className:"editor-context-menu",style:{left:k.x,top:k.y},children:[P!=null&&P.isPinned?n.jsx("button",{onClick:()=>{y(k.tabId),G()},children:t("editor.unpin")}):n.jsx("button",{onClick:()=>{b(k.tabId),G()},children:t("editor.pin")}),n.jsx("div",{className:"editor-context-separator"}),n.jsx("button",{onClick:()=>T(k.tabId),children:t("editor.copyPath")}),n.jsx("button",{onClick:()=>D(k.tabId),children:t("editor.copyRelativePath")}),n.jsx("button",{onClick:()=>I(k.tabId),children:t("editor.revealInExplorer")}),n.jsx("div",{className:"editor-context-separator"}),n.jsx("button",{onClick:()=>{d(k.tabId),G()},children:t("editor.close")}),n.jsx("button",{onClick:()=>{a(k.tabId),G()},children:t("editor.closeOthers")}),n.jsx("button",{onClick:()=>{c(k.tabId),G()},children:t("editor.closeToRight")}),n.jsx("button",{onClick:()=>{u(),G()},children:t("editor.closeSaved")}),n.jsx("button",{onClick:()=>{o(),G()},children:t("editor.closeAll")})]})]})]})}const jS=_r;function fd(e){return`/api/v1/files/download?path=${encodeURIComponent(e)}`}function Bu({path:e,onImageInfo:t,onZoomChange:r}){const{t:s}=ne(),i=C.useRef(null),l=C.useRef(null),[d,a]=C.useState("fit"),[o,c]=C.useState(null),[u,p]=C.useState(!1),[b,y]=C.useState({x:0,y:0}),k=C.useRef({x:0,y:0,tx:0,ty:0}),v=C.useCallback(()=>{if(!i.current||!o)return 1;const R=i.current.clientWidth-40,j=i.current.clientHeight-80;return R<=0||j<=0?1:Math.min(R/o.w,j/o.h,1)},[o]),g=d==="fit"?v():d,m=C.useCallback(()=>{const R=l.current;if(!R)return;const j=R.naturalWidth,$=R.naturalHeight;c({w:j,h:$}),t==null||t({width:j,height:$})},[t]);C.useEffect(()=>{r==null||r(g)},[g,r]);const h=C.useCallback(R=>{!R.ctrlKey&&!R.metaKey||(R.preventDefault(),a(j=>{const $=j==="fit"?v():j,G=R.deltaY<0?.1:-.1;return Math.min(5,Math.max(.1,$+G))}))},[v]),f=C.useCallback(R=>{d!=="fit"&&(R.preventDefault(),p(!0),k.current={x:R.clientX,y:R.clientY,tx:b.x,ty:b.y})},[d,b]),x=C.useCallback(R=>{if(!u)return;const j=R.clientX-k.current.x,$=R.clientY-k.current.y;y({x:k.current.tx+j,y:k.current.ty+$})},[u]),E=C.useCallback(()=>{p(!1)},[]),_=()=>a(R=>Math.min(5,(R==="fit"?v():R)+.1)),S=()=>a(R=>Math.max(.1,(R==="fit"?v():R)-.1)),w=()=>{a("fit"),y({x:0,y:0})},N=()=>{a(1),y({x:0,y:0})},L=g>=3;return n.jsxs("div",{ref:i,className:"file-preview-image-container checkerboard",onWheel:h,onMouseDown:f,onMouseMove:x,onMouseUp:E,onMouseLeave:E,style:{cursor:d!=="fit"?u?"grabbing":"grab":"default"},children:[n.jsx("img",{ref:l,src:fd(e),alt:e,onLoad:m,className:L?"pixelated":"",style:{transform:`translate(${b.x}px, ${b.y}px) scale(${g})`,transformOrigin:"center center",maxWidth:"none",maxHeight:"none",userSelect:"none",pointerEvents:"none"},draggable:!1}),n.jsxs("div",{className:"image-zoom-toolbar",children:[n.jsx("button",{onClick:S,title:s("filePreview.zoomOut"),children:n.jsx(Cp,{size:16})}),n.jsxs("span",{className:"image-zoom-label",children:[Math.round(g*100),"%"]}),n.jsx("button",{onClick:_,title:s("filePreview.zoomIn"),children:n.jsx(ot,{size:16})}),n.jsx("button",{onClick:w,title:s("filePreview.fitToWindow"),children:n.jsx(ni,{size:16})}),n.jsx("button",{onClick:N,title:s("filePreview.actualSize"),children:n.jsx(lb,{size:16})})]})]})}function MS({className:e,children:t}){const r=Ke(l=>l.resolved),s=(e||"").match(/language-(\w+)/),i=String(t).replace(/\n$/,"");return s?n.jsx("div",{className:"relative group my-3",children:n.jsx(jS,{style:r==="dark"?Vr:Kr,language:s[1],PreTag:"div",customStyle:{margin:0,borderRadius:"8px",fontSize:"13px",lineHeight:"1.6"},codeTagProps:{style:{background:"transparent",textShadow:"none"}},children:i})}):n.jsx("code",{className:"bg-[var(--color-bg-tertiary)] px-1.5 py-0.5 rounded text-[13px]",children:t})}function PS({content:e}){return n.jsx("div",{className:"file-preview-markdown",children:n.jsx("div",{className:"file-preview-markdown-content",children:n.jsx(lr,{remarkPlugins:[cr],components:{code:MS},children:e})})})}function FS({path:e}){const{t}=ne();return n.jsx("iframe",{src:fd(e),className:"file-preview-pdf",title:t("filePreview.pdfPreview")})}function BS({path:e,name:t}){const{t:r}=ne();return n.jsxs("div",{className:"file-preview-binary",children:[n.jsx(mp,{size:48,className:"text-[var(--color-text-tertiary)]"}),n.jsx("div",{className:"mt-4 text-lg font-medium text-[var(--color-text-primary)]",children:t}),n.jsx("div",{className:"mt-2 text-sm text-[var(--color-text-secondary)]",children:r("filePreview.binaryNotSupported")}),n.jsxs("a",{href:fd(e),download:t,className:"mt-4 inline-flex items-center gap-2 px-4 py-2 rounded-lg bg-[var(--color-bg-tertiary)] text-[var(--color-text-primary)] hover:bg-[var(--color-bg-quaternary)] transition-colors text-sm",children:[n.jsx(pp,{size:16}),r("filePreview.download")]})]})}function US({path:e,name:t,content:r,viewMode:s,onImageInfo:i,onZoomChange:l}){switch(s){case"image":return n.jsx(Bu,{path:e,onImageInfo:i,onZoomChange:l});case"svg":return n.jsx(Bu,{path:e,onImageInfo:i,onZoomChange:l});case"markdown":return n.jsx(PS,{content:r});case"pdf":return n.jsx(FS,{path:e});case"binary":return n.jsx(BS,{path:e,name:t});default:return null}}function Zh({node:e,depth:t,isExpanded:r,isSelected:s,isMultiSelected:i,isRenaming:l,expandedPaths:d,selectedPath:a,selectedPaths:o,renamingPath:c,onToggleExpand:u,onSelect:p,onOpenFile:b,onConfirmRename:y,onCancelRename:k,onContextMenu:v,onDragStart:g,onDrop:m}){var D;const h=e.type==="directory",f=12+t*12,[x,E]=C.useState(e.name),_=C.useRef(null),[S,w]=C.useState(!1);C.useEffect(()=>{if(l&&_.current){E(e.name),_.current.focus();const I=e.name.lastIndexOf(".");!h&&I>0?_.current.setSelectionRange(0,I):_.current.select()}},[l,e.name,h]);const N=C.useCallback(I=>{l||(p(e.path,{ctrl:I.ctrlKey||I.metaKey,shift:I.shiftKey}),h?u(e.path):!I.ctrlKey&&!I.metaKey&&!I.shiftKey&&b(e.path,e.name))},[l,e.path,h,e.name,p,u,b]),L=C.useCallback(()=>{l||h||b(e.path,e.name)},[l,h,e.path,e.name,b]),R=C.useCallback(I=>{I.stopPropagation(),I.key==="Enter"?(I.preventDefault(),y(e.path,x)):I.key==="Escape"&&(I.preventDefault(),k())},[e.path,x,y,k]),j=C.useCallback(()=>{y(e.path,x)},[e.path,x,y]),$=C.useCallback(I=>{I.preventDefault(),v(I,e.path)},[v,e.path]),G=C.useCallback(I=>{const P=i?[...o]:[e.path];I.dataTransfer.effectAllowed="move",I.dataTransfer.setData("text/plain",JSON.stringify(P)),g(P)},[i,o,e.path,g]),F=C.useCallback(I=>{h&&(I.preventDefault(),I.dataTransfer.dropEffect="move",w(!0))},[h]),W=C.useCallback(()=>{w(!1)},[]),V=C.useCallback(I=>{I.preventDefault(),w(!1),h&&m(e.path)},[h,e.path,m]),q=s||i,A=12,T=12;return n.jsxs(n.Fragment,{children:[n.jsxs("div",{className:`file-tree-item ${q?"selected":""} ${S?"drag-over":""}`,onClick:N,onDoubleClick:L,onContextMenu:$,draggable:!l,onDragStart:G,onDragOver:F,onDragLeave:W,onDrop:V,"data-path":e.path,title:e.path,children:[Array.from({length:t},(I,P)=>n.jsx("span",{className:"file-tree-indent-guide",style:{left:T+P*A+6}},P)),n.jsx("span",{style:{width:f,flexShrink:0}}),h?e.isLoading?n.jsx(we,{size:16,className:"file-tree-chevron animate-spin"}):n.jsx(Ne,{size:16,className:`file-tree-chevron ${r?"expanded":""}`}):n.jsx(Gt,{name:e.name,type:e.type,isExpanded:r,size:16}),l?n.jsx("input",{ref:_,className:"file-tree-rename-input",value:x,onChange:I=>E(I.target.value),onKeyDown:R,onBlur:j,onClick:I=>I.stopPropagation()}):n.jsx("span",{className:"file-tree-item-name",children:e.name})]}),h&&r&&((D=e.children)==null?void 0:D.map(I=>n.jsx(Zh,{node:I,depth:t+1,isExpanded:d.has(I.path),isSelected:a===I.path,isMultiSelected:o.has(I.path),isRenaming:c===I.path,expandedPaths:d,selectedPath:a,selectedPaths:o,renamingPath:c,onToggleExpand:u,onSelect:p,onOpenFile:b,onConfirmRename:y,onCancelRename:k,onContextMenu:v,onDragStart:g,onDrop:m},I.path)))]})}function zS({initialPath:e,onSelect:t,onClose:r}){const{t:s}=ne(),[i,l]=C.useState(e||"/"),[d,a]=C.useState([]),[o,c]=C.useState(!0),[u,p]=C.useState(null),[b,y]=C.useState(!1),k=C.useRef(null),v=C.useCallback(async x=>{c(!0),p(null);try{const _=(await qt(x,1)).filter(S=>S.type==="directory").sort((S,w)=>S.name.localeCompare(w.name,void 0,{numeric:!0,sensitivity:"base"}));a(_),l(x)}catch{const E=x.replace(/\/[^/]+\/?$/,"")||"/";if(E!==x&&E.length>0)try{const S=(await qt(E,1)).filter(w=>w.type==="directory").sort((w,N)=>w.name.localeCompare(N.name,void 0,{numeric:!0,sensitivity:"base"}));a(S),l(E),c(!1);return}catch{}p(s("editor.loadError"))}finally{c(!1)}},[s]);C.useEffect(()=>{v(i)},[]);const g=C.useCallback(()=>{const x=i.replace(/\/[^/]+\/?$/,"")||"/";v(x)},[i,v]),m=C.useCallback(x=>{v(x)},[v]),h=C.useCallback(()=>{t(i)},[i,t]),f=C.useCallback(x=>{const E=x.trim();E&&v(E),y(!1)},[v]);return C.useEffect(()=>{b&&k.current&&(k.current.focus(),k.current.select())},[b]),C.useEffect(()=>{const x=E=>{E.key==="Escape"&&r()};return window.addEventListener("keydown",x),()=>window.removeEventListener("keydown",x)},[r]),n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"fixed inset-0 z-50 bg-black/40",onClick:r}),n.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4",onClick:x=>x.target===x.currentTarget&&r(),children:n.jsxs("div",{className:"bg-bg-primary border border-border-default rounded-xl shadow-xl flex flex-col",style:{width:"480px",maxWidth:"90vw",maxHeight:"70vh"},children:[n.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-b border-border-muted/30",children:[n.jsx("span",{className:"text-sm font-medium text-text-primary",children:s("editor.openFolder")}),n.jsx("button",{className:"text-text-tertiary hover:text-text-primary",onClick:r,children:n.jsx(Te,{size:16})})]}),n.jsxs("div",{className:"flex items-center gap-1.5 px-3 py-2 border-b border-border-muted/30",children:[n.jsx("button",{className:"p-1 rounded hover:bg-bg-hover text-text-tertiary hover:text-text-primary flex-shrink-0",onClick:g,title:s("editor.parentFolder"),children:n.jsx(Es,{size:14})}),b?n.jsx("input",{ref:k,type:"text",defaultValue:i,className:"flex-1 px-1.5 py-0.5 text-xs font-mono bg-bg-secondary border border-accent-brand rounded outline-none",onKeyDown:x=>{x.key==="Enter"&&f(x.target.value),x.key==="Escape"&&y(!1)},onBlur:x=>f(x.target.value)}):n.jsx("button",{className:"flex-1 text-left text-xs font-mono text-text-secondary truncate px-1.5 py-0.5 rounded hover:bg-bg-hover",onClick:()=>y(!0),title:i,children:i})]}),n.jsxs("div",{className:"flex-1 overflow-y-auto min-h-[200px]",children:[o&&n.jsx("div",{className:"flex items-center justify-center py-8 text-text-tertiary",children:n.jsx(we,{size:16,className:"animate-spin"})}),u&&n.jsx("div",{className:"px-4 py-3 text-xs text-accent-red",children:u}),!o&&!u&&d.length===0&&n.jsx("div",{className:"px-4 py-8 text-center text-xs text-text-tertiary",children:s("editor.emptyFolder")}),!o&&!u&&d.map(x=>n.jsxs("button",{className:"flex items-center gap-2 w-full px-4 py-1.5 text-left text-sm text-text-primary hover:bg-bg-hover/50 cursor-pointer",onClick:()=>m(x.path),children:[n.jsx(Xg,{size:14,className:"text-text-tertiary flex-shrink-0"}),n.jsx("span",{className:"truncate",children:x.name}),n.jsx(Ne,{size:12,className:"text-text-tertiary flex-shrink-0 ml-auto"})]},x.path))]}),n.jsxs("div",{className:"flex items-center justify-end gap-2 px-4 py-3 border-t border-border-muted/30",children:[n.jsx("button",{className:"px-3 py-1.5 text-xs rounded-md text-text-secondary hover:bg-bg-hover border border-border-muted",onClick:r,children:s("editor.close")}),n.jsx("button",{className:"px-3 py-1.5 text-xs rounded-md bg-accent-brand text-white hover:opacity-90",onClick:h,children:s("editor.openFolder")})]})]})})]})}function Uu({onMenuClick:e}){var ie,Oe,_e;const{t}=ne(),r=Wt(se=>se.info),{rootPath:s,tree:i,treeLoading:l,treeError:d,expandedPaths:a,selectedPath:o,selectedPaths:c,renamingPath:u,setRootPath:p,toggleExpand:b,selectPath:y,openFile:k,refreshTree:v,collapseAll:g,createNewFile:m,createNewFolder:h,startRename:f,startCreateFile:x,startCreateFolder:E,confirmRename:_,cancelRename:S,deleteSelected:w,moveToDirectory:N}=Ut(),[L,R]=C.useState(!1),[j,$]=C.useState(!1),[G,F]=C.useState(!1),W=C.useRef(null),[V,q]=C.useState(null),A=C.useRef([]);C.useEffect(()=>{const se=Sn().has("path");r!=null&&r.cwd&&!s&&!se?p(r.cwd):s&&!i&&!l&&!d&&p(s)},[r==null?void 0:r.cwd,s,i,l,d,p]);const T=C.useCallback(se=>{F(!1),p(se)},[p]),D=C.useCallback((se,ce)=>{k(se,ce)},[k]),I=C.useCallback((se,ce)=>{_(se,ce)},[_]),P=C.useCallback((se,ce)=>{se.preventDefault(),c.has(ce)||y(ce),q({x:se.clientX,y:se.clientY,path:ce})},[c,y]),M=C.useCallback(()=>q(null),[]),H=C.useCallback(()=>{V&&(f(V.path),q(null))},[V,f]),z=C.useCallback(()=>{q(null),w()},[w]),U=C.useCallback((se,ce)=>{if(!se)return null;if(se.path===ce)return se;if(se.children)for(const Ee of se.children){const xe=U(Ee,ce);if(xe)return xe}return null},[]),O=V?((ie=U(i,V.path))==null?void 0:ie.type)==="directory":!1,Y=C.useCallback(()=>{if(V){const se=U(i,V.path),ce=(se==null?void 0:se.type)==="directory"?V.path:V.path.substring(0,V.path.lastIndexOf("/"));if(ce){a.has(ce)||b(ce);const Ee=ce+"/__new_file__";x(Ee)}q(null)}},[V,i,a,b,x,U]),X=C.useCallback(()=>{if(V){const se=U(i,V.path),ce=(se==null?void 0:se.type)==="directory"?V.path:V.path.substring(0,V.path.lastIndexOf("/"));if(ce){a.has(ce)||b(ce);const Ee=ce+"/__new_folder__";E(Ee)}q(null)}},[V,i,a,b,E,U]),Q=C.useCallback(()=>{V&&(navigator.clipboard.writeText(V.path).catch(()=>{}),q(null))},[V]),J=C.useCallback(()=>{if(V&&s){const se=V.path.startsWith(s+"/")?V.path.slice(s.length+1):V.path;navigator.clipboard.writeText(se).catch(()=>{}),q(null)}},[V,s]),re=C.useCallback(se=>{A.current=se},[]),ue=C.useCallback(se=>{A.current.length>0&&(N(A.current,se),A.current=[])},[N]),de=C.useCallback(se=>{var xe,Ze,ee,oe;if(u||!i)return;const ce=gd(i,a);if(ce.length===0)return;const Ee=o?ce.indexOf(o):-1;switch(se.key){case"ArrowDown":{se.preventDefault();const fe=Ee<ce.length-1?Ee+1:0;y(ce[fe],{shift:se.shiftKey}),(Ze=(xe=W.current)==null?void 0:xe.querySelector(`[data-path="${CSS.escape(ce[fe])}"]`))==null||Ze.scrollIntoView({block:"nearest"});break}case"ArrowUp":{se.preventDefault();const fe=Ee>0?Ee-1:ce.length-1;y(ce[fe],{shift:se.shiftKey}),(oe=(ee=W.current)==null?void 0:ee.querySelector(`[data-path="${CSS.escape(ce[fe])}"]`))==null||oe.scrollIntoView({block:"nearest"});break}case"ArrowRight":{se.preventDefault(),o&&!a.has(o)&&b(o);break}case"ArrowLeft":{se.preventDefault(),o&&a.has(o)&&b(o);break}case"Enter":{se.preventDefault(),o&&f(o);break}case"Delete":case"Backspace":{se.preventDefault(),c.size>0&&w();break}case" ":{if(se.preventDefault(),o){const fe=Je=>{if(!Je)return null;if(Je.path===o)return Je;if(Je.children)for(const Qe of Je.children){const ht=fe(Qe);if(ht)return ht}return null},$e=fe(i);($e==null?void 0:$e.type)==="directory"?b(o):$e&&k($e.path,$e.name)}break}}},[i,a,o,c,u,y,b,f,k,w]),me=(i==null?void 0:i.name)||(s==null?void 0:s.split("/").pop())||"WORKSPACE";return n.jsxs("div",{className:"file-tree",ref:W,tabIndex:0,onKeyDown:de,onClick:()=>{var se;return(se=W.current)==null?void 0:se.focus()},children:[n.jsxs("div",{className:"file-tree-title-bar",children:[e&&n.jsx("button",{className:"file-tree-title-menu",onClick:e,title:t("editor.toggleSidebar"),children:n.jsx(si,{size:16})}),n.jsx("span",{className:"file-tree-title-text",children:t("editor.explorer")})]}),n.jsxs("div",{className:"file-tree-section-header",onClick:()=>R(!L),onMouseEnter:()=>$(!0),onMouseLeave:()=>$(!1),children:[L?n.jsx(Ne,{size:12,style:{flexShrink:0}}):n.jsx(nt,{size:12,style:{flexShrink:0}}),n.jsx("span",{className:"file-tree-section-name",children:me.toUpperCase()}),j&&!L&&n.jsxs("div",{className:"file-tree-section-actions",onClick:se=>se.stopPropagation(),children:[n.jsx("button",{className:"file-tree-section-action",onClick:m,title:t("editor.newFile"),children:n.jsx(Bg,{size:14})}),n.jsx("button",{className:"file-tree-section-action",onClick:h,title:t("editor.newFolder"),children:n.jsx(Kg,{size:14})}),n.jsx("button",{className:"file-tree-section-action",onClick:()=>F(!0),title:t("editor.openFolder"),children:n.jsx(ti,{size:14})}),n.jsx("button",{className:"file-tree-section-action",onClick:v,title:t("editor.refresh"),children:n.jsx(Ve,{size:14})}),n.jsx("button",{className:"file-tree-section-action",onClick:g,title:t("editor.collapseAll"),children:n.jsx(Ng,{size:14})})]})]}),G&&n.jsx(zS,{initialPath:s||(r==null?void 0:r.cwd)||"/",onSelect:T,onClose:()=>F(!1)}),!L&&n.jsxs("div",{className:"file-tree-content",children:[l&&!i&&n.jsx("div",{className:"file-tree-loading",children:n.jsx(we,{size:16,className:"animate-spin"})}),!l&&!i&&d&&s&&n.jsxs("div",{className:"file-tree-empty",children:[n.jsx("span",{children:t("editor.loadError")}),n.jsxs("button",{className:"file-tree-retry-btn",onClick:()=>p(s),children:[n.jsx(Ve,{size:12}),t("editor.refresh")]})]}),(Oe=i==null?void 0:i.children)==null?void 0:Oe.map(se=>n.jsx(Zh,{node:se,depth:0,isExpanded:a.has(se.path),isSelected:o===se.path,isMultiSelected:c.has(se.path),isRenaming:u===se.path,expandedPaths:a,selectedPath:o,selectedPaths:c,renamingPath:u,onToggleExpand:b,onSelect:y,onOpenFile:D,onConfirmRename:I,onCancelRename:S,onContextMenu:P,onDragStart:re,onDrop:ue},se.path)),((_e=i==null?void 0:i.children)==null?void 0:_e.length)===0&&n.jsx("div",{className:"file-tree-empty",children:t("editor.emptyFolder")})]}),V&&n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"editor-context-overlay",onClick:M}),n.jsxs("div",{className:"editor-context-menu",style:{left:V.x,top:V.y},children:[O&&n.jsxs(n.Fragment,{children:[n.jsx("button",{onClick:Y,children:t("editor.newFile")}),n.jsx("button",{onClick:X,children:t("editor.newFolder")}),n.jsx("div",{className:"editor-context-separator"})]}),n.jsx("button",{onClick:Q,children:t("editor.copyPath")}),n.jsx("button",{onClick:J,children:t("editor.copyRelativePath")}),n.jsx("div",{className:"editor-context-separator"}),c.size<=1&&n.jsx("button",{onClick:H,children:t("editor.rename")}),n.jsx("button",{className:"danger",onClick:z,children:c.size>1?`${t("editor.delete")} (${c.size})`:t("editor.delete")})]})]})]})}function HS(e,t){const r=e.toLowerCase(),s=t.toLowerCase();let i=0,l=0,d=-1;for(let a=0;a<s.length&&i<r.length;a++)s[a]===r[i]&&(l+=a===d+1?2:1,(a===0||s[a-1]==="/"||s[a-1]===".")&&(l+=3),d=a,i++);return{match:i===r.length,score:l}}const zu=20,GS=3;function WS({isOpen:e,onClose:t,onSelect:r,rootPath:s}){const{t:i}=ne(),[l,d]=C.useState(""),[a,o]=C.useState(0),[c,u]=C.useState([]),[p,b]=C.useState(!1),y=C.useRef(null),k=C.useRef(null),v=C.useRef(""),g=C.useRef([]),m=C.useCallback(async(x,E,_)=>{if(E>GS)return[];try{const S=await qt(x),w=[];for(const N of S){const L=_?`${_}/${N.name}`:N.name;if(N.type==="file"&&!Yh(N.path))w.push({name:N.name,path:N.path,relativePath:L});else if(N.type==="directory"&&!N.name.startsWith(".")&&N.name!=="node_modules"){const R=await m(N.path,E+1,L);w.push(...R)}}return w}catch{return[]}},[]);C.useEffect(()=>{if(e){if(d(""),o(0),setTimeout(()=>{var x;return(x=y.current)==null?void 0:x.focus()},0),v.current===s&&g.current.length>0){u(g.current);return}b(!0),m(s,0,"").then(x=>{v.current=s,g.current=x,u(x),b(!1)})}},[e,s,m]);const h=C.useMemo(()=>{if(!l.trim())return c.slice(0,zu);const x=[];for(const E of c){const _=HS(l,E.relativePath);_.match&&x.push({entry:E,score:_.score})}return x.sort((E,_)=>_.score-E.score),x.slice(0,zu).map(E=>E.entry)},[c,l]);C.useEffect(()=>{o(0)},[h.length,l]);const f=C.useCallback(x=>{switch(x.key){case"ArrowDown":x.preventDefault(),o(E=>(E+1)%Math.max(h.length,1));break;case"ArrowUp":x.preventDefault(),o(E=>(E-1+h.length)%Math.max(h.length,1));break;case"Enter":x.preventDefault(),h[a]&&r(h[a].path);break;case"Escape":x.preventDefault(),t();break}},[h,a,r,t]);return C.useEffect(()=>{var E;const x=(E=k.current)==null?void 0:E.children[a];x==null||x.scrollIntoView({block:"nearest"})},[a]),e?n.jsx("div",{className:"quick-open-overlay",onClick:t,children:n.jsxs("div",{className:"quick-open-dialog",onClick:x=>x.stopPropagation(),onKeyDown:f,children:[n.jsx("input",{ref:y,className:"quick-open-input",type:"text",value:l,onChange:x=>d(x.target.value),placeholder:i("editor.quickOpenPlaceholder")}),n.jsx("div",{className:"quick-open-list",ref:k,children:p?n.jsx("div",{className:"quick-open-empty",children:i("editor.quickOpenLoading")}):h.length===0?n.jsx("div",{className:"quick-open-empty",children:(l.trim(),i("editor.quickOpenEmpty"))}):h.map((x,E)=>n.jsxs("div",{className:`quick-open-item${E===a?" active":""}`,onClick:()=>r(x.path),onMouseEnter:()=>o(E),children:[n.jsx(Gt,{name:x.name,type:"file",size:14}),n.jsx("span",{className:"quick-open-item-name",children:x.name}),n.jsx("span",{className:"quick-open-item-path",children:x.relativePath})]},x.path))})]})}):null}const qS=1e3;function VS({onMenuClick:e}){const{t}=ne(),{tabs:r,activeTabId:s,splitRatio:i,setSplitRatio:l,updateTabContent:d,saveTab:a,closeTab:o,recentFiles:c}=Ut(),{setRootPath:u,openFile:p,rootPath:b,revealInTree:y}=Ut(),[k,v]=C.useState(!1),g=typeof navigator<"u"&&navigator.platform.includes("Mac"),[m,h]=C.useState(()=>window.innerWidth<768),[f,x]=C.useState(!1),E=C.useRef("");C.useEffect(()=>{const z=async()=>{if(li()!=="editor")return;const Y=Sn().get("path");if(!Y||Y===E.current)return;if(E.current=Y,await kS(Y)==="directory")await u(Y);else{const Q=Y.substring(0,Y.lastIndexOf("/"));Q&&await u(Q),p(Y)}};z();const U=()=>z();return window.addEventListener("hashchange",U),()=>window.removeEventListener("hashchange",U)},[]),C.useEffect(()=>{const z=window.matchMedia("(min-width: 768px)"),U=O=>{h(!O.matches),O.matches&&x(!1)};return z.addEventListener("change",U),()=>z.removeEventListener("change",U)},[]);const _=Ut(z=>z.tabs.length);C.useEffect(()=>{m&&s&&x(!0)},[m,s,_]);const S=r.find(z=>z.id===s)||null,w=C.useRef(),N=C.useCallback(z=>{if(!s)return;d(s,z),clearTimeout(w.current);const U=s;w.current=setTimeout(()=>{const O=Ut.getState().tabs.find(Y=>Y.id===U);!O||!O.isDirty||a(U)},qS)},[s,d,a]);C.useEffect(()=>()=>clearTimeout(w.current),[]),C.useEffect(()=>{const z=U=>{const O=U.metaKey||U.ctrlKey;O&&U.key==="p"&&!U.shiftKey&&(U.preventDefault(),v(!0)),O&&U.key==="w"&&!U.shiftKey&&(U.preventDefault(),s&&o(s))};return window.addEventListener("keydown",z),()=>window.removeEventListener("keydown",z)},[s,o]);const L=C.useCallback(()=>{clearTimeout(w.current),s&&a(s)},[s,a]),R=C.useCallback(()=>{x(!1)},[]),[j,$]=C.useState({line:1,col:1,selectedChars:0,selectedLines:0}),G=C.useCallback((z,U,O,Y)=>{$({line:z,col:U,selectedChars:O,selectedLines:Y})},[]),[F,W]=C.useState(null),[V,q]=C.useState(1),[A,T]=C.useState(new Set),D=(S==null?void 0:S.viewMode)==="markdown"&&A.has(S.id),I=C.useCallback(()=>{s&&T(z=>{const U=new Set(z);return U.has(s)?U.delete(s):U.add(s),U})},[s]),P=(S==null?void 0:S.viewMode)==="markdown"?D?n.jsx("button",{className:"editor-action-btn",onClick:I,title:t("editor.preview"),children:n.jsx(Js,{size:16})}):n.jsx("button",{className:"editor-action-btn",onClick:I,title:t("editor.source"),children:n.jsx(up,{size:16})}):null,M=S?S.viewMode==="editor"||D?n.jsx("div",{className:"editor-container",children:n.jsx($S,{path:S.path,content:S.content,language:S.language,onContentChange:N,onSave:L,minimap:!m,onCursorChange:G})}):n.jsx(US,{path:S.path,name:S.name,content:S.content,viewMode:S.viewMode,onImageInfo:W,onZoomChange:q}):n.jsxs("div",{className:"editor-empty",children:[n.jsx(Mg,{size:48,strokeWidth:1,style:{opacity:.12}}),n.jsx("span",{className:"editor-empty-title",children:t("editor.noFile")}),n.jsx("div",{className:"editor-empty-shortcuts",children:n.jsxs("div",{className:"editor-empty-hint",children:[n.jsxs("kbd",{children:[g?"⌘":"Ctrl","+P"]}),n.jsx("span",{children:t("editor.quickOpen")})]})}),c.length>0&&n.jsxs("div",{className:"editor-empty-recent",children:[n.jsx("span",{className:"editor-empty-recent-title",children:t("editor.recentFiles")}),c.slice(0,8).map(z=>n.jsxs("button",{className:"editor-empty-recent-item",onClick:()=>p(z.path),title:z.path,children:[n.jsx(Gt,{name:z.name,type:"file",size:14}),n.jsx("span",{className:"editor-empty-recent-name",children:z.name}),n.jsx("span",{className:"editor-empty-recent-path",children:z.path.split("/").slice(-2,-1)[0]})]},z.path))]})]}),H=k&&b&&n.jsx(WS,{isOpen:k,onClose:()=>v(!1),onSelect:z=>{p(z),v(!1)},rootPath:b});return m?n.jsxs("div",{className:"editor-view",children:[H,n.jsx("div",{className:"editor-sidebar editor-sidebar-mobile",children:n.jsx(Uu,{onMenuClick:e})}),n.jsx("div",{className:`editor-mobile-panel ${f?"open":""}`,children:n.jsxs("div",{className:"editor-main",children:[n.jsxs("div",{className:"editor-mobile-header",children:[n.jsx("button",{className:"editor-mobile-back",onClick:R,children:n.jsx(dr,{size:18})}),n.jsx("div",{className:"editor-mobile-tabs-wrap",children:n.jsx(Fu,{actions:P})})]}),M,S&&n.jsx(Pu,{language:S.language,cursorLine:j.line,cursorColumn:j.col,selectedCount:j.selectedChars,selectedLines:j.selectedLines,viewMode:D?"editor":S.viewMode,imageInfo:F,zoom:V})]})})]}):n.jsxs("div",{className:"editor-view",children:[H,n.jsxs(On,{direction:"horizontal",ratio:i,onRatioChange:l,children:[n.jsx("div",{className:"editor-sidebar",children:n.jsx(Uu,{onMenuClick:e})}),n.jsxs("div",{className:"editor-main",children:[n.jsx(Fu,{actions:P}),S&&b&&n.jsx(OS,{filePath:S.path,rootPath:b,onSegmentClick:y,onOpenFile:p}),M,S&&n.jsx(Pu,{language:S.language,cursorLine:j.line,cursorColumn:j.col,selectedCount:j.selectedChars,selectedLines:j.selectedLines,viewMode:D?"editor":S.viewMode,imageInfo:F,zoom:V})]})]})]})}class Be extends C.Component{constructor(r){super(r);be(this,"handleRetry",()=>{this.setState({hasError:!1,error:null})});this.state={hasError:!1,error:null}}static getDerivedStateFromError(r){return{hasError:!0,error:r}}componentDidCatch(r,s){console.error(`[ErrorBoundary${this.props.viewName?` - ${this.props.viewName}`:""}]`,r,s)}render(){var r;return this.state.hasError?n.jsx("div",{className:"flex-1 flex items-center justify-center p-6",children:n.jsxs("div",{className:"text-center max-w-md",children:[n.jsx("div",{className:"text-[48px] mb-4 text-text-tertiary",children:"!"}),n.jsx("h2",{className:"text-text-primary text-[16px] font-semibold mb-2",children:this.props.errorTitle||"Something went wrong"}),n.jsx("p",{className:"text-text-tertiary text-[13px] mb-4 break-words",children:((r=this.state.error)==null?void 0:r.message)||"An unexpected error occurred"}),n.jsx("button",{onClick:this.handleRetry,className:"px-6 py-2 bg-accent-brand text-bg-primary rounded-lg text-[13px] font-medium hover:opacity-90 active:scale-95 transition-all",children:this.props.retryLabel||"Retry"})]})}):this.props.children}}function KS(e){return!Number.isFinite(e)||e<0?"0":e<1e3?String(e):e<1e6?`${(e/1e3).toFixed(1)}k`:`${(e/1e6).toFixed(1)}M`}function YS(e,t,r,s){const i=Math.max(1,Math.round(e/1e3)),l=s(t===1?"goal.recap.stats.turn":"goal.recap.stats.turns"),d=s(r===1?"goal.recap.stats.token":"goal.recap.stats.tokens");return`${i}s · ${t} ${l} · ${KS(r)} ${d}`}function XS(){const e=Me(l=>l.goalRecap),t=Me(l=>l.dismissGoalRecap),{t:r}=ne();C.useEffect(()=>{if(!e)return;const l=d=>{d.key==="Escape"&&(d.preventDefault(),t())};return document.addEventListener("keydown",l),()=>document.removeEventListener("keydown",l)},[e,t]);const s=C.useCallback(()=>t(),[t]),i=C.useMemo(()=>ZS(e,r),[e,r]);return e?n.jsxs("div",{className:"fixed inset-0 z-[200] flex items-center justify-center",children:[n.jsx("div",{className:"absolute inset-0 bg-black/30",onClick:s}),n.jsxs("div",{role:"dialog","aria-modal":"true","aria-labelledby":"goal-recap-title",className:"relative bg-bg-card border border-border-default rounded-xl shadow-2xl w-full max-w-[480px] mx-4 overflow-hidden",children:[n.jsx("div",{className:"px-5 pt-5 pb-4 flex flex-col gap-3",children:i}),n.jsxs("div",{className:"px-5 pb-4 pt-2 border-t border-border-default text-text-tertiary text-[12px]",children:[n.jsx("span",{className:"text-text-secondary",children:r("goal.recap.footer.setAnother")}),n.jsx("span",{children:r("goal.recap.footer.toSetAnother")}),n.jsx("span",{className:"text-text-secondary",children:"Esc"}),n.jsxs("span",{children:[" ",r("goal.recap.footer.escDismiss")]})]})]})]}):null}function ZS(e,t){if(!e)return null;if(e.active)return n.jsxs(n.Fragment,{children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(Ns,{size:18,className:"text-accent-brand"}),n.jsx("h3",{id:"goal-recap-title",className:"text-text-primary text-[15px] font-semibold",children:t("goal.recap.active")})]}),n.jsxs("div",{className:"text-text-secondary text-[13px] break-words leading-relaxed",children:[t("goal.progress.condition"),": ",e.active.condition]})]});if(e.latest){const{ok:r,reason:s,condition:i,durationMs:l,turnCount:d,tokenDelta:a}=e.latest,o=r?Rn:ar,c=r?"text-accent-green":"text-accent-red",u=t(r?"goal.recap.achieved":"goal.recap.impossible"),p=YS(l,d,a,t);return n.jsxs(n.Fragment,{children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(o,{size:18,className:c}),n.jsx("h3",{id:"goal-recap-title",className:`text-[15px] font-semibold ${c}`,children:u})]}),n.jsx("div",{className:"text-text-secondary text-[12px]",children:p}),n.jsxs("div",{className:"text-text-secondary text-[13px] break-words leading-relaxed mt-2",children:[t("goal.progress.condition"),": ",i]}),s?n.jsxs("div",{className:"text-text-tertiary text-[12px] break-words leading-relaxed",children:[t("goal.progress.reason"),": ",s]}):null]})}return n.jsxs(n.Fragment,{children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(Ns,{size:18,className:"text-text-tertiary"}),n.jsx("h3",{id:"goal-recap-title",className:"text-text-primary text-[15px] font-semibold",children:t("goal.recap.empty.title")})]}),n.jsx("div",{className:"text-text-secondary text-[13px] leading-relaxed",children:t("goal.recap.empty.hint")}),n.jsx("div",{className:"text-text-tertiary text-[12px] leading-relaxed",children:t("goal.recap.empty.example")})]})}function JS(e,t){const s=Date.now()-e,i=Math.floor(s/6e4),l=Math.floor(s/36e5),d=Math.floor(s/864e5);return t==="zh"?i<1?"刚刚":i<60?`${i} 分钟前`:l<24?`${l} 小时前`:d<30?`${d} 天前`:new Date(e).toLocaleDateString("zh-CN"):i<1?"Just now":i<60?`${i}m ago`:l<24?`${l}h ago`:d<30?`${d}d ago`:new Date(e).toLocaleDateString("en-US")}function QS({isOpen:e,onClose:t,onSwitchSession:r}){const{t:s,resolved:i}=ne(),[l,d]=C.useState([]),[a,o]=C.useState(!0),[c,u]=C.useState(null),[p,b]=C.useState(null),[y,k]=C.useState(null),[v,g]=C.useState(""),m=C.useRef(null),[h,f]=C.useState(null),x=C.useCallback(async()=>{o(!0),u(null);try{const R=await fetch("/api/v1/sessions",{headers:ae()});if(!R.ok)throw new Error(`HTTP ${R.status}`);const j=await R.json(),$=j.data??j;d($.sessions||[])}catch(R){u(R.message||"Unknown error")}finally{o(!1)}},[]);C.useEffect(()=>{e&&x()},[e,x]);const E=C.useCallback(async R=>{var j;try{const $=await fetch(`/api/v1/sessions/${encodeURIComponent(R.id)}`,{method:"DELETE",headers:ae()});if(!$.ok){const G=await $.json().catch(()=>({}));throw new Error(((j=G.error)==null?void 0:j.message)||G.error||`HTTP ${$.status}`)}d(G=>G.filter(F=>F.id!==R.id))}catch($){console.error("[history] Delete failed:",$)}finally{f(null)}},[]),_=C.useCallback(async(R,j)=>{var G;const $=j.trim();if($)try{const F=await fetch(`/api/v1/sessions/${encodeURIComponent(R.id)}/rename`,{method:"POST",headers:ae({"Content-Type":"application/json"}),body:JSON.stringify({name:$})});if(!F.ok){const W=await F.json().catch(()=>({}));throw new Error(((G=W.error)==null?void 0:G.message)||W.error||`HTTP ${F.status}`)}d(W=>W.map(V=>V.id===R.id?{...V,name:$}:V))}catch(F){console.error("[history] Rename failed:",F)}finally{k(null),g("")}},[]),S=C.useCallback((R,j)=>{j.stopPropagation(),k(R),g(R.name),setTimeout(()=>{var $;return($=m.current)==null?void 0:$.focus()},50)},[]),w=C.useCallback((R,j)=>{j.stopPropagation(),!R.isCurrent&&f(R)},[]),N=C.useCallback(async R=>{if(!(R.isCurrent||p)){b(R.id);try{await(r==null?void 0:r(R.id)),t()}finally{b(null)}}},[p,r,t]),L=()=>a?n.jsx("div",{className:"history-loading",children:n.jsx(pt,{size:"small",text:s("history.loading")})}):c?n.jsxs("div",{className:"history-error",children:[n.jsx("p",{className:"history-error-text",children:s("history.loadError")}),n.jsx("button",{className:"history-retry-btn",onClick:x,children:s("history.retry")})]}):l.length===0?n.jsxs("div",{className:"history-empty",children:[n.jsx(ur,{size:48,className:"text-text-tertiary"}),n.jsx("p",{className:"history-empty-title",children:s("history.noData")}),n.jsx("p",{className:"history-empty-hint",children:s("history.noDataHint")})]}):n.jsx("div",{className:"history-list",children:l.map((R,j)=>{const $=En(R.updatedAt),G=j>0?En(l[j-1].updatedAt):null,F=$!==G;return n.jsxs("div",{children:[F&&n.jsx(Nt,{label:Eh(R.updatedAt,i)}),n.jsxs("div",{className:`history-session-item${R.isCurrent?" current":""}${!R.isCurrent&&!p?" clickable":""}`,onClick:()=>!R.isCurrent&&!p&&N(R),children:[n.jsxs("div",{className:"history-session-info",children:[n.jsx("p",{className:"history-session-name",children:R.name}),n.jsxs("div",{className:"history-session-meta",children:[R.isCurrent&&n.jsx("span",{className:"history-session-badge",children:s("history.current")}),n.jsx("span",{children:s("history.messages").replace("{count}",String(R.messageCount))}),n.jsx("span",{children:JS(R.updatedAt,i)})]})]}),n.jsxs("div",{className:"history-session-actions",children:[p===R.id&&n.jsx("div",{className:"history-session-switching",children:n.jsx("div",{className:"history-session-spinner"})}),p!==R.id&&n.jsxs(n.Fragment,{children:[n.jsx("button",{className:"history-action-btn",title:s("history.rename"),onClick:W=>S(R,W),children:n.jsx(zf,{size:14})}),!R.isCurrent&&n.jsx("button",{className:"history-action-btn danger",title:s("history.delete"),onClick:W=>w(R,W),children:n.jsx(hr,{size:14})})]})]})]})]},R.id)})});return n.jsxs(n.Fragment,{children:[n.jsx("div",{className:`history-drawer-overlay ${e?"open":""}`,onClick:t}),n.jsxs("div",{className:`history-drawer ${e?"open":""}`,children:[n.jsxs("div",{className:"history-drawer-header",children:[n.jsxs("div",{children:[n.jsx("h2",{className:"history-drawer-title",children:s("history.title")}),n.jsx("p",{className:"history-drawer-subtitle",children:s("history.description")})]}),n.jsx("button",{onClick:t,className:"history-drawer-close",children:n.jsx(Te,{size:16})})]}),n.jsx("div",{className:"history-content",children:L()})]}),y&&n.jsx("div",{className:"history-rename-overlay",onClick:()=>k(null),children:n.jsxs("div",{className:"history-rename-dialog",onClick:R=>R.stopPropagation(),children:[n.jsx("h3",{children:s("history.renameTitle")}),n.jsx("input",{ref:m,className:"history-rename-input",value:v,onChange:R=>g(R.target.value),placeholder:s("history.renamePlaceholder"),onKeyDown:R=>{R.key==="Enter"&&v.trim()&&_(y,v),R.key==="Escape"&&k(null)}}),n.jsxs("div",{className:"history-rename-actions",children:[n.jsx("button",{className:"history-rename-cancel",onClick:()=>k(null),children:s("history.renameCancel")}),n.jsx("button",{className:"history-rename-ok",disabled:!v.trim(),onClick:()=>_(y,v),children:s("history.renameOk")})]})]})}),h&&n.jsx("div",{className:"history-delete-overlay",onClick:()=>f(null),children:n.jsxs("div",{className:"history-delete-dialog",onClick:R=>R.stopPropagation(),children:[n.jsx("p",{children:s("history.deleteConfirm")}),n.jsxs("div",{className:"history-delete-actions",children:[n.jsx("button",{className:"history-delete-cancel",onClick:()=>f(null),children:s("history.deleteCancel")}),n.jsx("button",{className:"history-delete-ok",onClick:()=>E(h),children:s("history.deleteOk")})]})]})})]})}function ln(e,t){return`${e}@${t}`}async function Pt(e,t){return ve(e,{method:"POST",headers:{"Content-Type":"application/json",...ae()},body:t?JSON.stringify(t):void 0})}async function ek(e){return ve(e,{method:"DELETE",headers:ae()})}async function Hu(e){return ve(e,{method:"GET",headers:ae()})}const tk=Ae((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 Hu("/api/v1/plugins");if(!r.ok)throw new Error(`HTTP ${r.status}`);const i=(await r.json()).data,l=Array.isArray(i)?i.map(d=>({...d,canRemove:d.canRemove,canSwitchoff:d.canSwitchoff,canEdit:d.canEdit})):[];e({plugins:l,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 Hu("/api/v1/plugins/marketplaces");if(!r.ok)throw new Error(`HTTP ${r.status}`);const i=(await r.json()).data;e({marketplaces:Array.isArray(i)?i:[],marketplaceLoading:!1})}catch(r){console.warn("[plugin-store] fetchMarketplaces failed:",r),e({marketplaceLoading:!1})}},browseMarketplace:async r=>{var s;e({browsingMarketplace:r,browsingLoading:!0,browsingError:null});try{const i=await Pt("/api/v1/plugins/marketplaces/browse",{marketplace:r});if(!i.ok){const o=await i.json().catch(()=>null);throw new Error(((s=o==null?void 0:o.error)==null?void 0:s.message)||`HTTP ${i.status}`)}const l=await i.json(),a=(Array.isArray(l.data)?l.data:[]).map(o=>({name:o.name,version:o.version,description:o.description,marketplace:o.marketplaceName||r,installed:!!o.status,author:o.author,license:o.license,homepage:o.homepage,repository:o.repository,keywords:o.keywords,category:o.category,features:o.features,source:o.source}));e({availablePlugins:a,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 s=await Promise.allSettled(r.map(async o=>{var b;const c=await Pt("/api/v1/plugins/marketplaces/browse",{marketplace:o.name});if(!c.ok){const y=await c.json().catch(()=>null);throw new Error(((b=y==null?void 0:y.error)==null?void 0:b.message)||`HTTP ${c.status}`)}const u=await c.json();return(Array.isArray(u.data)?u.data:[]).map(y=>({name:y.name,version:y.version,description:y.description,marketplace:y.marketplaceName||o.name,installed:!!y.status,author:y.author,license:y.license,homepage:y.homepage,repository:y.repository,keywords:y.keywords,category:y.category,features:y.features,source:y.source}))})),i=[];let l=!1;for(const o of s)o.status==="fulfilled"?i.push(...o.value):l=!0;const d=new Set,a=i.filter(o=>{const c=`${o.name}@${o.marketplace}`;return d.has(c)?!1:(d.add(c),!0)});e({availablePlugins:a,browsingLoading:!1,browsingError:l&&a.length===0?"Some marketplaces failed to load":null})}catch(s){console.warn("[plugin-store] browseAllMarketplaces failed:",s),e({browsingError:s.message,browsingLoading:!1})}}},enablePlugin:async(r,s)=>{var l;const i=ln(r,s);e(d=>({operatingPlugins:new Set(d.operatingPlugins).add(i)}));try{const d=await Pt("/api/v1/plugins/enable",{plugin:i});if(!d.ok){const a=await d.json().catch(()=>null);throw new Error(((l=a==null?void 0:a.error)==null?void 0:l.message)||`HTTP ${d.status}`)}await t().fetchPlugins()}finally{e(d=>{const a=new Set(d.operatingPlugins);return a.delete(i),{operatingPlugins:a}})}},disablePlugin:async(r,s)=>{var l;const i=ln(r,s);e(d=>({operatingPlugins:new Set(d.operatingPlugins).add(i)}));try{const d=await Pt("/api/v1/plugins/disable",{plugin:i});if(!d.ok){const a=await d.json().catch(()=>null);throw new Error(((l=a==null?void 0:a.error)==null?void 0:l.message)||`HTTP ${d.status}`)}await t().fetchPlugins()}finally{e(d=>{const a=new Set(d.operatingPlugins);return a.delete(i),{operatingPlugins:a}})}},uninstallPlugin:async(r,s)=>{var l;const i=ln(r,s);e(d=>({operatingPlugins:new Set(d.operatingPlugins).add(i)}));try{const d=await Pt("/api/v1/plugins/uninstall",{plugin:i});if(!d.ok){const a=await d.json().catch(()=>null);throw new Error(((l=a==null?void 0:a.error)==null?void 0:l.message)||`HTTP ${d.status}`)}await t().fetchPlugins()}finally{e(d=>{const a=new Set(d.operatingPlugins);return a.delete(i),{operatingPlugins:a}})}},installPlugin:async(r,s,i)=>{var d;const l=ln(r,s);e(a=>({operatingPlugins:new Set(a.operatingPlugins).add(l)}));try{const a=await Pt("/api/v1/plugins",{plugin:l,options:i?{scope:i}:void 0});if(!a.ok){const c=await a.json().catch(()=>null);throw new Error(((d=c==null?void 0:c.error)==null?void 0:d.message)||`HTTP ${a.status}`)}await t().fetchPlugins();const o=t();o.browsingMarketplace&&(o.browsingMarketplace==="__all__"?await t().browseAllMarketplaces():await t().browseMarketplace(o.browsingMarketplace))}finally{e(a=>{const o=new Set(a.operatingPlugins);return o.delete(l),{operatingPlugins:o}})}},addMarketplace:async(r,s)=>{var l;const i=await Pt("/api/v1/plugins/marketplaces",{source:r,name:s});if(!i.ok){const d=await i.json().catch(()=>null);throw new Error(((l=d==null?void 0:d.error)==null?void 0:l.message)||`HTTP ${i.status}`)}await t().fetchMarketplaces()},removeMarketplace:async r=>{var i;const s=await ek(`/api/v1/plugins/marketplaces/${encodeURIComponent(r)}`);if(!s.ok){const l=await s.json().catch(()=>null);throw new Error(((i=l==null?void 0:l.error)==null?void 0:i.message)||`HTTP ${s.status}`)}await t().fetchMarketplaces()}}));function Jh(){const{t:e}=ne(),{plugins:t,marketplaces:r,loading:s,marketplaceLoading:i,error:l,operatingPlugins:d,availablePlugins:a,browsingLoading:o,browsingError:c,fetchPlugins:u,fetchMarketplaces:p,browseMarketplace:b,browseAllMarketplaces:y,enablePlugin:k,disablePlugin:v,uninstallPlugin:g,installPlugin:m,addMarketplace:h,removeMarketplace:f}=tk(),[x,E]=C.useState("installed"),[_,S]=C.useState(""),[w,N]=C.useState("all"),[L,R]=C.useState(null),[j,$]=C.useState(!1),[G,F]=C.useState(""),[W,V]=C.useState(""),[q,A]=C.useState(!1),[T,D]=C.useState(null),[I,P]=C.useState(null),[M,H]=C.useState(null),[z,U]=C.useState(""),[O,Y]=C.useState(""),[X,Q]=C.useState(null),J=C.useCallback(ee=>{Q(oe=>oe===ee?null:ee)},[]);C.useEffect(()=>{u(),p()},[u,p]),C.useEffect(()=>{x==="browse"&&!z&&r.length>0&&(U("__all__"),y())},[x,r,z,y]);const re=C.useCallback(async ee=>{R(null);try{ee.status==="enabled"?await v(ee.name,ee.marketplace):await k(ee.name,ee.marketplace)}catch(oe){R(oe.message)}},[k,v]),ue=C.useCallback(async ee=>{R(null),P(null);try{await g(ee.name,ee.marketplace)}catch(oe){R(oe.message)}},[g]),de=C.useCallback(async(ee,oe)=>{R(null);try{await m(ee.name,ee.marketplace,oe)}catch(fe){R(fe.message)}},[m]),me=C.useCallback(async()=>{const ee=G.trim();if(ee){A(!0),D(null);try{await h(ee,W.trim()||void 0),F(""),V(""),$(!1)}catch(oe){D(oe.message)}finally{A(!1)}}},[G,W,h]),ie=C.useCallback(async ee=>{R(null),H(null);try{if(await f(ee),z===ee&&r.length>1){const oe=r.find(fe=>fe.name!==ee);oe&&(U(oe.name),b(oe.name))}}catch(oe){R(oe.message)}},[f,z,r,b]),Oe=C.useCallback(()=>{u(),p(),x==="browse"&&z&&(z==="__all__"?y():b(z))},[u,p,x,z,b,y]),_e=C.useCallback(ee=>{U(ee),Y(""),ee==="__all__"?y():b(ee)},[b,y]),se=ee=>`${ee.name}@${ee.marketplace}`,ce=C.useMemo(()=>{const ee=new Set(t.map(oe=>oe.marketplace));return Array.from(ee).sort()},[t]),Ee=C.useMemo(()=>{let ee=t;w!=="all"&&(ee=ee.filter(fe=>fe.marketplace===w));const oe=_.trim().toLowerCase();return oe&&(ee=ee.filter(fe=>fe.name.toLowerCase().includes(oe)||fe.description&&fe.description.toLowerCase().includes(oe)||fe.marketplace.toLowerCase().includes(oe))),ee},[t,w,_]),xe=C.useMemo(()=>{let ee=a;const oe=O.trim().toLowerCase();return oe&&(ee=ee.filter(fe=>fe.name.toLowerCase().includes(oe)||fe.description&&fe.description.toLowerCase().includes(oe))),ee},[a,O]),Ze=t.filter(ee=>ee.status==="enabled").length;return n.jsxs("div",{className:"flex-1 flex flex-col overflow-hidden bg-bg-primary",children:[n.jsx("div",{className:"flex-none border-b border-border-muted px-6 py-4",children:n.jsxs("div",{className:"max-w-3xl mx-auto",children:[n.jsxs("div",{className:"flex items-center justify-between mb-4",children:[n.jsxs("div",{children:[n.jsx("h1",{className:"text-lg font-semibold text-text-primary",children:e("plugins.title")}),x==="installed"&&t.length>0&&n.jsxs("p",{className:"text-sm text-text-tertiary mt-0.5",children:[t.length," ",e("plugins.totalCount")," · ",Ze," ",e("plugins.enabled")]}),x==="browse"&&z&&!o&&a.length>0&&n.jsxs("p",{className:"text-sm text-text-tertiary mt-0.5",children:[a.length," ",e("plugins.totalCount")]}),x==="marketplaces"&&r.length>0&&n.jsxs("p",{className:"text-sm text-text-tertiary mt-0.5",children:[r.length," ",e("plugins.totalCount")]})]}),n.jsx("button",{onClick:Oe,disabled:s||o,className:`flex items-center gap-2 px-3 py-2 rounded-lg border transition-all ${s||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:n.jsx(Ve,{size:14,className:s||o?"animate-spin":""})})]}),n.jsxs("div",{className:"flex gap-1 border-b border-border-muted",children:[n.jsx("button",{onClick:()=>{E("installed"),R(null)},className:`px-4 py-2.5 text-[13px] font-medium border-b-2 transition-colors ${x==="installed"?"text-text-primary border-text-primary":"text-text-secondary border-transparent hover:text-text-primary"}`,children:e("plugins.installedPlugins")}),n.jsx("button",{onClick:()=>{E("browse"),R(null)},className:`px-4 py-2.5 text-[13px] font-medium border-b-2 transition-colors ${x==="browse"?"text-text-primary border-text-primary":"text-text-secondary border-transparent hover:text-text-primary"}`,children:e("plugins.browseMarketplace")}),n.jsx("button",{onClick:()=>{E("marketplaces"),R(null)},className:`px-4 py-2.5 text-[13px] font-medium border-b-2 transition-colors ${x==="marketplaces"?"text-text-primary border-text-primary":"text-text-secondary border-transparent hover:text-text-primary"}`,children:e("plugins.marketplaces")})]}),x==="installed"&&t.length>0&&n.jsxs("div",{className:"flex items-center gap-2 mt-4",children:[n.jsxs("div",{className:"flex-1 relative",children:[n.jsx(at,{size:14,className:"absolute left-3 top-1/2 -translate-y-1/2 text-text-tertiary pointer-events-none"}),n.jsx("input",{type:"text",value:_,onChange:ee=>S(ee.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"}),_&&n.jsx("button",{onClick:()=>S(""),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:n.jsx(Te,{size:12})})]}),ce.length>1&&n.jsxs("select",{value:w,onChange:ee=>N(ee.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:[n.jsx("option",{value:"all",children:e("plugins.allMarketplaces")}),ce.map(ee=>n.jsx("option",{value:ee,children:ee},ee))]})]}),x==="browse"&&r.length>0&&n.jsxs("div",{className:"flex items-center gap-2 mt-4",children:[n.jsxs("div",{className:"flex-1 relative",children:[n.jsx(at,{size:14,className:"absolute left-3 top-1/2 -translate-y-1/2 text-text-tertiary pointer-events-none"}),n.jsx("input",{type:"text",value:O,onChange:ee=>Y(ee.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"}),O&&n.jsx("button",{onClick:()=>Y(""),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:n.jsx(Te,{size:12})})]}),n.jsxs("select",{value:z,onChange:ee=>_e(ee.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:[n.jsx("option",{value:"__all__",children:e("plugins.allMarketplaces")}),r.map(ee=>n.jsx("option",{value:ee.name,children:ee.name},ee.name))]})]})]})}),n.jsx("div",{className:"flex-1 overflow-y-auto px-6 py-6",children:n.jsxs("div",{className:"max-w-3xl mx-auto space-y-6",children:[L&&n.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:[n.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[n.jsx(lt,{size:14,className:"shrink-0"}),n.jsxs("span",{className:"truncate",children:[e("plugins.operationFailed"),": ",L]})]}),n.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:n.jsx(Te,{size:12})})]}),x==="installed"&&n.jsxs(n.Fragment,{children:[s&&t.length===0&&n.jsx("div",{className:"flex flex-col items-center justify-center py-20",children:n.jsx(pt,{size:"small",text:e("plugins.loading")})}),l&&!s&&t.length===0&&n.jsxs("div",{className:"flex flex-col items-center justify-center py-20",children:[n.jsx(lt,{size:40,className:"text-text-tertiary opacity-40 mb-4"}),n.jsx("div",{className:"text-[14px] text-text-secondary font-medium mb-3",children:e("plugins.error")}),n.jsx("button",{onClick:u,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")})]}),!s&&!l&&t.length===0&&n.jsxs("div",{className:"flex flex-col items-center justify-center py-20 text-text-tertiary",children:[n.jsx(zt,{size:48,className:"mb-4 opacity-30"}),n.jsx("div",{className:"text-[15px] font-medium mb-1.5 text-text-secondary",children:e("plugins.noPlugins")}),n.jsx("div",{className:"text-[13px]",children:e("plugins.noPluginsHint")})]}),t.length>0&&Ee.length===0&&!s&&n.jsxs("div",{className:"flex flex-col items-center justify-center py-16 text-text-tertiary",children:[n.jsx(at,{size:36,className:"mb-3 opacity-30"}),n.jsx("div",{className:"text-[13px]",children:e("plugins.noSearchResults")})]}),Ee.length>0&&n.jsx("div",{className:"space-y-3",children:Ee.map(ee=>{const oe=se(ee);return n.jsx(rk,{plugin:ee,isEnabled:ee.status==="enabled",isOperating:d.has(oe),isExpanded:X===oe,confirmUninstall:I===oe,onToggle:()=>re(ee),onUninstall:()=>ue(ee),onConfirmUninstall:()=>P(oe),onCancelUninstall:()=>P(null),onExpand:()=>J(oe),t:e},oe)})})]}),x==="browse"&&n.jsxs(n.Fragment,{children:[!i&&r.length===0&&n.jsxs("div",{className:"flex flex-col items-center justify-center py-20 text-text-tertiary",children:[n.jsx(Rr,{size:48,className:"mb-4 opacity-30"}),n.jsx("div",{className:"text-[15px] font-medium mb-1.5 text-text-secondary",children:e("plugins.noMarketplaces")}),n.jsx("div",{className:"text-[13px]",children:e("plugins.noMarketplacesHint")})]}),o&&a.length===0&&z&&n.jsx("div",{className:"flex flex-col items-center justify-center py-20",children:n.jsx(pt,{size:"small",text:e("plugins.browsingMarketplace")})}),c&&a.length===0&&z&&n.jsxs("div",{className:"flex flex-col items-center justify-center py-20",children:[n.jsx(lt,{size:40,className:"text-text-tertiary opacity-40 mb-4"}),n.jsx("div",{className:"text-[14px] text-text-secondary font-medium mb-3",children:e("plugins.error")}),n.jsx("button",{onClick:()=>z&&b(z),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")})]}),z&&a.length===0&&!o&&!c&&n.jsxs("div",{className:"flex flex-col items-center justify-center py-20 text-text-tertiary",children:[n.jsx(zt,{size:48,className:"mb-4 opacity-30"}),n.jsx("div",{className:"text-[15px] font-medium mb-1.5 text-text-secondary",children:e("plugins.noAvailablePlugins")}),n.jsx("div",{className:"text-[13px]",children:e("plugins.noAvailablePluginsHint")})]}),a.length>0&&xe.length===0&&!o&&n.jsxs("div",{className:"flex flex-col items-center justify-center py-16 text-text-tertiary",children:[n.jsx(at,{size:36,className:"mb-3 opacity-30"}),n.jsx("div",{className:"text-[13px]",children:e("plugins.noSearchResults")})]}),xe.length>0&&n.jsx("div",{className:"space-y-3",children:xe.map(ee=>{const oe=`${ee.name}@${ee.marketplace}`;return n.jsx(nk,{plugin:ee,isInstalled:ee.installed,isOperating:d.has(oe),isExpanded:X===oe,onInstall:fe=>de(ee,fe),onExpand:()=>J(oe),t:e},oe)})})]}),x==="marketplaces"&&n.jsxs("div",{className:"space-y-3",children:[!j&&n.jsxs("button",{onClick:()=>$(!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:[n.jsx(ot,{size:12}),e("plugins.addMarketplace")]}),j&&n.jsxs("div",{className:"bg-bg-secondary rounded-xl border border-border-muted p-4 space-y-3",children:[n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsx("span",{className:"text-[13px] font-medium",children:e("plugins.addMarketplace")}),n.jsx("button",{onClick:()=>{$(!1),D(null)},className:"w-6 h-6 flex items-center justify-center rounded-full hover:bg-bg-tertiary transition-colors text-text-secondary",children:n.jsx(Te,{size:12})})]}),n.jsx("input",{type:"text",value:G,onChange:ee=>F(ee.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"}),n.jsx("input",{type:"text",value:W,onChange:ee=>V(ee.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"}),T&&n.jsx("div",{className:"text-accent-red text-[12px]",children:T}),n.jsxs("div",{className:"flex justify-end gap-2",children:[n.jsx("button",{onClick:()=>{$(!1),D(null)},className:"px-3 py-1.5 rounded-lg text-[12px] text-text-secondary hover:bg-bg-tertiary transition-colors",children:e("plugins.cancel")}),n.jsxs("button",{onClick:me,disabled:!G.trim()||q,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:[q&&n.jsx(we,{size:12,className:"animate-spin"}),e("plugins.add")]})]})]}),i&&r.length===0&&n.jsx("div",{className:"flex items-center justify-center py-6",children:n.jsx(we,{size:18,className:"animate-spin text-text-tertiary"})}),!i&&r.length===0&&!j&&n.jsxs("div",{className:"flex flex-col items-center justify-center py-20 text-text-tertiary",children:[n.jsx(Rr,{size:48,className:"mb-4 opacity-30"}),n.jsx("div",{className:"text-[15px] font-medium mb-1.5 text-text-secondary",children:e("plugins.noMarketplaces")}),n.jsx("div",{className:"text-[13px]",children:e("plugins.noMarketplacesHint")})]}),r.length>0&&n.jsx("div",{className:"bg-bg-secondary rounded-xl border border-border-muted overflow-hidden",children:r.map((ee,oe)=>n.jsxs("div",{className:`flex items-center justify-between px-4 py-3 ${oe>0?"border-t border-border-muted":""}`,children:[n.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[n.jsx(Rr,{size:14,className:"text-text-tertiary shrink-0"}),n.jsxs("div",{className:"min-w-0",children:[n.jsx("div",{className:"text-[13px] font-medium truncate",children:ee.name}),ee.type&&n.jsx("div",{className:"text-[11px] text-text-tertiary",children:ee.type})]})]}),n.jsx("div",{className:"flex items-center gap-2 shrink-0",children:M===ee.name?n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("button",{onClick:()=>ie(ee.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")}),n.jsx("button",{onClick:()=>H(null),className:"px-2.5 py-1 rounded-md text-[11px] text-text-secondary hover:bg-bg-tertiary transition-colors",children:e("plugins.cancel")})]}):n.jsx("button",{onClick:()=>H(ee.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:n.jsx(hr,{size:13})})})]},ee.name))})]})]})})]})}function rk({plugin:e,isEnabled:t,isOperating:r,isExpanded:s,confirmUninstall:i,onToggle:l,onUninstall:d,onConfirmUninstall:a,onCancelUninstall:o,onExpand:c,t:u}){return n.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:[n.jsxs("div",{className:"flex items-start gap-4 px-5 py-4 cursor-pointer",onClick:c,children:[n.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:n.jsx(zt,{size:18,className:t?"text-text-primary":"text-text-tertiary"})}),n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsxs("div",{className:"flex items-center gap-2 mb-0.5",children:[n.jsx("span",{className:"text-[14px] font-semibold text-text-primary truncate",children:e.name}),e.version&&n.jsxs("span",{className:"text-[11px] text-text-tertiary shrink-0 font-mono",children:["v",e.version]}),n.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:u(t?"plugins.enabled":"plugins.disabled")})]}),e.description&&n.jsx("div",{className:`text-[12px] text-text-secondary leading-relaxed mb-1.5 ${s?"":"line-clamp-2"}`,children:e.description}),n.jsxs("div",{className:"flex items-center gap-1.5 text-[11px] text-text-tertiary",children:[n.jsx(Rr,{size:10,className:"shrink-0"}),n.jsx("span",{children:e.marketplace}),e.installScope&&n.jsx("span",{className:"px-1.5 py-px rounded bg-bg-tertiary text-[10px] font-medium",children:u(`plugins.scope.${e.installScope}`)})]})]}),n.jsx("div",{className:"flex items-center gap-1.5 shrink-0 pt-0.5",onClick:p=>p.stopPropagation(),children:r?n.jsx("div",{className:"w-[72px] flex justify-center",children:n.jsx(we,{size:16,className:"animate-spin text-text-tertiary"})}):i?n.jsxs("div",{className:"flex items-center gap-1.5",children:[n.jsx("button",{onClick:d,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:u("plugins.uninstall")}),n.jsx("button",{onClick:o,className:"px-2.5 py-1 rounded-md text-[11px] text-text-secondary hover:bg-bg-tertiary transition-colors",children:u("plugins.cancel")})]}):n.jsxs(n.Fragment,{children:[n.jsxs("button",{onClick:e.canSwitchoff===!1?void 0:l,disabled:e.canSwitchoff===!1,className:`px-2.5 py-1.5 rounded-md text-[11px] font-medium transition-colors flex items-center gap-1 ${e.canSwitchoff===!1?"text-text-tertiary border border-border-muted cursor-not-allowed opacity-50":t?"text-text-secondary border border-border-muted hover:bg-bg-tertiary":"text-text-primary border border-border-muted hover:bg-bg-tertiary"}`,title:e.canSwitchoff===!1?u("plugins.policyCannotSwitchoff"):u(t?"plugins.disable":"plugins.enable"),children:[t?n.jsx(Jf,{size:11}):n.jsx(Ip,{size:11}),u(t?"plugins.disable":"plugins.enable")]}),n.jsx("button",{onClick:e.canRemove===!1?void 0:a,disabled:e.canRemove===!1,className:`w-7 h-7 flex items-center justify-center rounded-md transition-colors ${e.canRemove===!1?"text-text-tertiary cursor-not-allowed opacity-30":"text-text-tertiary hover:text-accent-red hover:bg-accent-red/10 opacity-0 group-hover:opacity-100"}`,title:e.canRemove===!1?u("plugins.policyCannotRemove"):u("plugins.uninstall"),children:n.jsx(hr,{size:13})})]})})]}),s&&n.jsx(Qh,{plugin:e,t:u})]})}function nk({plugin:e,isInstalled:t,isOperating:r,isExpanded:s,onInstall:i,onExpand:l,t:d}){return n.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:[n.jsxs("div",{className:"flex items-start gap-4 px-5 py-4 cursor-pointer",onClick:l,children:[n.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:n.jsx(zt,{size:18,className:t?"text-text-primary":"text-text-tertiary"})}),n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsxs("div",{className:"flex items-center gap-2 mb-0.5",children:[n.jsx("span",{className:"text-[14px] font-semibold text-text-primary truncate",children:e.name}),e.version&&n.jsxs("span",{className:"text-[11px] text-text-tertiary shrink-0 font-mono",children:["v",e.version]}),t&&n.jsx("span",{className:"text-[10px] px-1.5 py-px rounded font-medium shrink-0 bg-accent-green/15 text-accent-green",children:d("plugins.installedLabel")})]}),e.description&&n.jsx("div",{className:`text-[12px] text-text-secondary leading-relaxed mb-1.5 ${s?"":"line-clamp-2"}`,children:e.description}),n.jsxs("div",{className:"flex items-center gap-1 text-[11px] text-text-tertiary",children:[n.jsx(Rr,{size:10,className:"shrink-0"}),n.jsx("span",{children:e.marketplace})]})]}),n.jsx("div",{className:"flex items-center gap-1.5 shrink-0 pt-0.5",onClick:a=>a.stopPropagation(),children:t?n.jsx("div",{className:"px-2.5 py-1.5 rounded-md text-[11px] font-medium text-text-tertiary bg-bg-tertiary",children:d("plugins.installed")}):r?n.jsx("div",{className:"w-[72px] flex justify-center",children:n.jsx(we,{size:16,className:"animate-spin text-text-tertiary"})}):n.jsx(sk,{onInstall:i,t:d})})]}),s&&n.jsx(Qh,{plugin:e,t:d})]})}function Qh({plugin:e,t}){const r=e.source,s=typeof r=="object"&&r!==null?r.url:void 0,i=typeof r=="object"&&r!==null?r.source:typeof r=="string"?r:void 0,l="installScope"in e?e.installScope:void 0;return n.jsxs("div",{className:"border-t border-border-muted mx-5 px-0 py-3.5 space-y-2.5",children:[l&&n.jsx(vt,{label:t("plugins.scope"),children:n.jsx("span",{className:"text-[12px] text-text-secondary",children:t(`plugins.scope.${l}`)})}),e.category&&n.jsx(vt,{label:t("plugins.category"),children:n.jsx("span",{className:"text-[11px] px-2 py-0.5 rounded bg-[#f5a623]/8 text-[#b8860b] font-medium",children:e.category})}),e.author&&n.jsxs(vt,{label:t("plugins.author"),children:[n.jsx("span",{className:"text-[12px] text-text-primary font-medium",children:e.author.name}),e.author.email&&n.jsx("a",{href:`mailto:${e.author.email}`,className:"text-[11px] text-text-tertiary hover:text-text-primary hover:underline ml-1",onClick:d=>d.stopPropagation(),children:e.author.email}),e.author.url&&n.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:d=>d.stopPropagation(),children:[e.author.url,n.jsx(it,{size:9})]})]}),e.license&&n.jsx(vt,{label:t("plugins.license"),children:n.jsx("span",{className:"text-[12px] text-text-secondary",children:e.license})}),e.homepage&&n.jsx(vt,{label:t("plugins.homepage"),children:n.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:d=>d.stopPropagation(),children:[e.homepage,n.jsx(it,{size:10,className:"shrink-0 text-text-tertiary"})]})}),e.repository&&n.jsx(vt,{label:t("plugins.repository"),children:n.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:d=>d.stopPropagation(),children:[e.repository,n.jsx(it,{size:10,className:"shrink-0 text-text-tertiary"})]})}),i&&n.jsx(vt,{label:t("plugins.source"),children:s?n.jsxs("a",{href:s,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:d=>d.stopPropagation(),children:[i,n.jsx(it,{size:10,className:"shrink-0 text-text-tertiary"})]}):n.jsx("span",{className:"text-[12px] text-text-secondary font-mono",children:i})}),e.keywords&&e.keywords.length>0&&n.jsx(vt,{label:t("plugins.keywords"),children:n.jsx("div",{className:"flex flex-wrap gap-1",children:e.keywords.map(d=>n.jsx("span",{className:"text-[10px] px-1.5 py-px rounded bg-bg-tertiary text-text-tertiary",children:d},d))})}),e.features&&e.features.length>0&&n.jsx(vt,{label:t("plugins.features"),children:n.jsx("ul",{className:"space-y-0.5",children:e.features.map((d,a)=>n.jsxs("li",{className:"text-[12px] text-text-secondary flex items-start gap-1.5",children:[n.jsx("span",{className:"text-text-tertiary shrink-0",children:"·"}),d]},a))})})]})}function vt({label:e,children:t}){return n.jsxs("div",{className:"flex items-baseline gap-3",children:[n.jsx("span",{className:"text-[11px] text-text-tertiary w-12 shrink-0 text-right",children:e}),n.jsx("div",{className:"flex-1 min-w-0 flex items-baseline flex-wrap gap-1",children:t})]})}function sk({onInstall:e,t}){const[r,s]=C.useState(!1);return n.jsxs("div",{className:"relative",children:[n.jsxs("button",{onClick:()=>s(!r),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:t("plugins.install"),children:[n.jsx(pp,{size:11}),t("plugins.install")]}),r&&n.jsxs("div",{className:"absolute right-0 top-full mt-1 z-50 bg-bg-primary border border-border-muted rounded-lg shadow-lg py-1 min-w-[220px]",children:[n.jsx("button",{onClick:()=>{e("user"),s(!1)},className:"w-full text-left px-3 py-2 text-[12px] text-text-primary hover:bg-bg-secondary transition-colors",children:t("plugins.installScope.user")}),n.jsx("button",{onClick:()=>{e("project"),s(!1)},className:"w-full text-left px-3 py-2 text-[12px] text-text-primary hover:bg-bg-secondary transition-colors",children:t("plugins.installScope.project")}),n.jsx("button",{onClick:()=>{e("project-local"),s(!1)},className:"w-full text-left px-3 py-2 text-[12px] text-text-primary hover:bg-bg-secondary transition-colors",children:t("plugins.installScope.local")})]})]})}const ik=[{value:"low",labelKey:"settings.effort.low"},{value:"medium",labelKey:"settings.effort.medium"},{value:"high",labelKey:"settings.effort.high"},{value:"xhigh",labelKey:"settings.effort.xhigh"}],ak=[{titleKey:"settings.group.modelAndReasoning",items:[{key:"model",labelKey:"settings.item.model",descKey:"settings.item.model.desc",type:"text"},{key:"reasoningEffort",labelKey:"settings.item.reasoningEffort",descKey:"settings.item.reasoningEffort.desc",type:"select",options:ik},{key:"alwaysThinkingEnabled",labelKey:"settings.item.alwaysThinkingEnabled",type:"toggle"}]},{titleKey:"settings.group.behavior",items:[{key:"autoCompactEnabled",labelKey:"settings.item.autoCompactEnabled",type:"toggle"},{key:"includeCoAuthoredBy",labelKey:"settings.item.includeCoAuthoredBy",type:"toggle"},{key:"fileCheckpointingEnabled",labelKey:"settings.item.fileCheckpointingEnabled",descKey:"settings.item.fileCheckpointingEnabled.desc",type:"toggle"},{key:"promptSuggestionEnabled",labelKey:"settings.item.promptSuggestionEnabled",type:"toggle"},{key:"ignoreGitIgnore",labelKey:"settings.item.ignoreGitIgnore",descKey:"settings.item.ignoreGitIgnore.desc",type:"toggle"},{key:"deferToolLoading",labelKey:"settings.item.deferToolLoading",type:"toggle"},{key:"hookOutputCollapsed",labelKey:"settings.item.hookOutputCollapsed",type:"toggle"}]},{titleKey:"settings.group.memory",items:[{key:"memory.enabled",labelKey:"settings.item.memory.enabled",type:"toggle"},{key:"memory.autoMemoryEnabled",labelKey:"settings.item.memory.autoMemoryEnabled",descKey:"settings.item.memory.autoMemoryEnabled.desc",type:"toggle"}]},{titleKey:"settings.group.language",items:[{key:"language",labelKey:"settings.item.language",descKey:"settings.item.language.desc",type:"text"}]},{titleKey:"settings.group.advanced",items:[{key:"cleanupPeriodDays",labelKey:"settings.item.cleanupPeriodDays",type:"number"},{key:"imageHistoryRetainRounds",labelKey:"settings.item.imageHistoryRetainRounds",descKey:"settings.item.imageHistoryRetainRounds.desc",type:"number"},{key:"env",labelKey:"settings.item.env",descKey:"settings.item.env.desc",type:"json"}]},{titleKey:"settings.group.sandbox",items:[{key:"sandbox.enabled",labelKey:"settings.item.sandbox.enabled",descKey:"settings.item.sandbox.enabled.desc",type:"toggle"},{key:"sandbox.autoAllowBashIfSandboxed",labelKey:"settings.item.sandbox.autoAllowBashIfSandboxed",descKey:"settings.item.sandbox.autoAllowBashIfSandboxed.desc",type:"toggle"}]}];function ok(e,t){const r=t.split(".");let s=e;for(const i of r){if(s==null||typeof s!="object")return;s=s[i]}return s}function em(){const{status:e,sessionId:t,currentModel:r,models:s,modes:i,currentMode:l}=rt(),{info:d,fetch:a}=Wt(),{mode:o,toggle:c}=Ke(),{t:u,locale:p,toggleLocale:b}=ne(),[y,k]=C.useState(null),[v,g]=C.useState({}),m=C.useRef({}),[h,f]=C.useState(!1),[x,E]=C.useState({}),_=C.useRef({});C.useEffect(()=>{let q=!1;return f(!0),Promise.all([fetch("/api/v1/settings",{headers:ae()}).then(A=>{if(!A.ok)throw new Error(`Settings API: ${A.status}`);return A.json()}).then(A=>(A==null?void 0:A.data)??A??{}),fetch("/api/v1/settings?scope=user",{headers:ae()}).then(A=>{if(!A.ok)throw new Error(`User settings API: ${A.status}`);return A.json()}).then(A=>(A==null?void 0:A.data)??A??{})]).then(([A,T])=>{q||(g(A),m.current=T,f(!1))}).catch(A=>{console.error("Failed to load settings:",A),q||f(!1)}),()=>{q=!0}},[]),C.useEffect(()=>()=>{Object.values(_.current).forEach(clearTimeout)},[]),C.useEffect(()=>{d||a()},[d,a]);const S=C.useCallback((q,A)=>{navigator.clipboard.writeText(q).then(()=>{k(A),setTimeout(()=>k(null),1500)})},[]),w=async q=>{if(L("model",q),t)try{await Re().setModel(t,q)}catch(A){console.error("Model change failed:",A)}},N=async q=>{if(L("permissions.defaultMode",q),t)try{await Re().setMode(t,q)}catch(A){console.error("Mode change failed:",A)}},L=C.useCallback(async(q,A)=>{const T=q.split(".")[0];let D=A;if(q.includes(".")){const I=q.split("."),M={...m.current[T]??{}};let H=M;for(let z=1;z<I.length-1;z++)H[I[z]]=H[I[z]]?{...H[I[z]]}:{},H=H[I[z]];H[I[I.length-1]]=A,D=M}try{const I=await fetch(`/api/v1/settings/${T}?scope=user`,{method:"PUT",headers:ae({"Content-Type":"application/json"}),body:JSON.stringify({value:D})});I.ok||I.status===204?(q.includes(".")?(m.current={...m.current,[T]:D},g(P=>({...P,[T]:{...P[T]??{},...D}}))):(m.current={...m.current,[q]:A},g(P=>({...P,[q]:A}))),R(q,"success")):(console.error(`Failed to save setting "${q}": HTTP ${I.status}`),R(q,"error"))}catch(I){console.error(`Failed to save setting "${q}":`,I),R(q,"error")}},[]),R=C.useCallback((q,A)=>{E(T=>({...T,[q]:A})),_.current[q]&&clearTimeout(_.current[q]),_.current[q]=setTimeout(()=>{E(T=>{const D={...T};return delete D[q],D})},1500)},[]),j={disconnected:"bg-gray-400",connecting:"bg-accent-yellow animate-pulse",connected:"bg-accent-green",error:"bg-accent-red"}[e],$={connected:"connection.connected",connecting:"connection.connecting",disconnected:"connection.disconnected",error:"connection.error"},G=o==="light"?Lp:o==="dark"?Tp:Eb,F=u(o==="light"?"theme.light":o==="dark"?"theme.dark":"theme.system"),W=p==="system"?uf:bp,V=u(p==="zh"?"locale.zh":p==="en"?"locale.en":"locale.system");return n.jsx("div",{className:"settings-view",children:n.jsx("div",{className:"settings-content",children:n.jsxs("div",{className:"settings-sections",children:[n.jsxs("div",{className:"settings-group",children:[n.jsx("h2",{className:"settings-group-title",children:u("sidebar.connectionStatus")}),n.jsxs("div",{className:"settings-card",children:[n.jsxs("div",{className:"settings-row",children:[n.jsx("span",{className:"settings-label",children:u("sidebar.status")}),n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("span",{className:`w-2 h-2 rounded-full ${j}`}),n.jsx("span",{className:"settings-value",children:u($[e]||"connection.disconnected")})]})]}),n.jsxs("div",{className:"settings-row",children:[n.jsx("span",{className:"settings-label",children:u("sidebar.sessionId")}),n.jsx("span",{className:"settings-value font-mono text-[12px]",children:t?t.substring(0,12):u("sidebar.notConnected")})]})]})]}),n.jsxs("div",{className:"settings-group",children:[n.jsx("h2",{className:"settings-group-title",children:u("settings.appearance")}),n.jsxs("div",{className:"settings-card",children:[n.jsxs("div",{className:"settings-row",children:[n.jsx("span",{className:"settings-label",children:u("sidebar.theme")}),n.jsxs("button",{onClick:c,className:"settings-toggle-btn",children:[n.jsx(G,{size:14,className:"text-accent-brand"}),n.jsx("span",{children:F})]})]}),n.jsxs("div",{className:"settings-row",children:[n.jsx("span",{className:"settings-label",children:u("sidebar.language")}),n.jsxs("button",{onClick:b,className:"settings-toggle-btn",children:[n.jsx(W,{size:14,className:"text-accent-brand"}),n.jsx("span",{children:V})]})]})]})]}),s.length>0&&n.jsxs("div",{className:"settings-group",children:[n.jsx("h2",{className:"settings-group-title",children:u("settings.model")}),n.jsx("div",{className:"settings-card",children:n.jsx("select",{value:r,onChange:q=>w(q.target.value),className:"settings-select",children:s.map(q=>n.jsx("option",{value:q.id,children:q.name||q.id},q.id))})})]}),i.length>0&&n.jsxs("div",{className:"settings-group",children:[n.jsx("h2",{className:"settings-group-title",children:u("settings.mode")}),n.jsx("div",{className:"settings-card",children:n.jsx("select",{value:l,onChange:q=>N(q.target.value),className:"settings-select",children:i.map(q=>n.jsx("option",{value:q.id,title:q.description,children:q.name},q.id))})})]}),h?n.jsx("div",{className:"settings-group",children:n.jsx("span",{className:"settings-value",children:u("settings.loading")})}):ak.map(q=>n.jsxs("div",{className:"settings-group",children:[n.jsx("h2",{className:"settings-group-title",children:u(q.titleKey)}),n.jsx("div",{className:"settings-card",children:q.items.map(A=>n.jsx(lk,{item:A,value:ok(v,A.key),feedback:x[A.key],onSave:L},A.key))})]},q.titleKey)),d&&n.jsxs("div",{className:"settings-group",children:[n.jsx("h2",{className:"settings-group-title",children:u("settings.systemInfo")}),n.jsxs("div",{className:"settings-card",children:[n.jsxs("div",{className:"settings-row",children:[n.jsx("span",{className:"settings-label",children:u("sidebar.cwd")}),n.jsxs("button",{onClick:()=>S(d.cwd,"cwd"),className:"settings-copy-btn",title:d.cwd,children:[n.jsx("span",{className:"truncate cursor-pointer hover:underline hover:text-accent-brand",onClick:q=>{q.stopPropagation(),Kp(d.cwd)},children:d.cwd}),y==="cwd"?n.jsx(Ht,{size:12,className:"shrink-0 text-accent-green"}):n.jsx($r,{size:12,className:"shrink-0 text-text-tertiary"})]})]}),n.jsxs("div",{className:"settings-row",children:[n.jsx("span",{className:"settings-label",children:u("sidebar.os")}),n.jsxs("span",{className:"settings-value",children:[d.os," ",d.arch]})]}),n.jsxs("div",{className:"settings-row",children:[n.jsx("span",{className:"settings-label",children:u("sidebar.nodeVersion")}),n.jsx("span",{className:"settings-value",children:d.nodeVersion})]}),n.jsxs("div",{className:"settings-row",children:[n.jsx("span",{className:"settings-label",children:u("sidebar.gatewayMode")}),n.jsx("span",{className:"settings-value capitalize",children:d.gatewayMode})]}),d.tunnelUrl&&n.jsxs("div",{className:"settings-row",children:[n.jsx("span",{className:"settings-label",children:u("sidebar.tunnelUrl")}),n.jsxs("button",{onClick:()=>S(d.tunnelUrl,"tunnel"),className:"settings-copy-btn",title:d.tunnelUrl,children:[n.jsx("span",{className:"truncate",children:d.tunnelUrl.replace(/^https?:\/\//,"")}),y==="tunnel"?n.jsx(Ht,{size:12,className:"shrink-0 text-accent-green"}):n.jsx($r,{size:12,className:"shrink-0 text-text-tertiary"})]})]})]})]})]})})})}function lk({item:e,value:t,feedback:r,onSave:s}){const{t:i}=ne(),[l,d]=C.useState(""),a=C.useRef(null);C.useEffect(()=>()=>{a.current&&clearTimeout(a.current)},[]),C.useEffect(()=>{e.type==="text"||e.type==="number"?d(t!=null?String(t):""):e.type==="json"&&d(t!=null?JSON.stringify(t,null,2):"")},[t,e.type]);const o=C.useCallback(()=>{s(e.key,!t)},[e.key,t,s]),c=C.useCallback(p=>{s(e.key,p||void 0)},[e.key,s]),u=C.useCallback(p=>{d(p),a.current&&clearTimeout(a.current),a.current=setTimeout(()=>{if(e.type==="number"){const b=Number(p);!isNaN(b)&&p.trim()!==""&&s(e.key,b)}else if(e.type==="json")try{const b=JSON.parse(p);s(e.key,b)}catch{}else s(e.key,p)},600)},[e.key,e.type,s]);return n.jsxs("div",{className:"settings-row",children:[n.jsxs("div",{className:"flex flex-col gap-0.5 min-w-0 flex-1",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("span",{className:"settings-label",children:i(e.labelKey)}),r&&n.jsx("span",{className:`settings-save-feedback ${r==="success"?"success":"error"}`,children:i(r==="success"?"settings.saved":"settings.saveFailed")})]}),e.descKey&&n.jsx("span",{className:"settings-desc",children:i(e.descKey)})]}),n.jsxs("div",{className:"flex items-center shrink-0 ml-3",children:[e.type==="toggle"&&n.jsx("button",{className:`settings-toggle-switch ${t?"on":""}`,onClick:o}),e.type==="select"&&e.options&&n.jsxs("select",{value:t??"",onChange:p=>c(p.target.value),className:"settings-inline-select",children:[n.jsx("option",{value:"",children:"-"}),e.options.map(p=>n.jsx("option",{value:p.value,children:i(p.labelKey)},p.value))]}),e.type==="text"&&n.jsx("input",{type:"text",value:l,onChange:p=>u(p.target.value),placeholder:i("settings.notSet"),className:"settings-input"}),e.type==="number"&&n.jsx("input",{type:"number",value:l,onChange:p=>u(p.target.value),className:"settings-input",style:{width:80}}),e.type==="json"&&n.jsx("textarea",{value:l,onChange:p=>u(p.target.value),placeholder:"{}",className:"settings-input wide",rows:3,style:{width:"100%",resize:"vertical"}})]})]})}function xs(){return rt.getState().sessionId??void 0}const ck=Ae((e,t)=>({tasks:[],loading:!1,error:null,fetchTasks:async()=>{const r=xs();if(r){e({loading:!0,error:null});try{const s=new URLSearchParams({sessionId:r}),i=await fetch(`/api/v1/scheduled-tasks?${s}`,{headers:ae()});if(!i.ok)throw new Error(`HTTP ${i.status}`);const l=await i.json(),d=l.data??l;e({tasks:d.tasks||[],loading:!1})}catch(s){console.error("[ScheduledTasks] Fetch error:",s),e({error:s.message,loading:!1})}}},createTask:async(r,s,i=!0,l=!1)=>{var a;const d=xs();if(d)try{const o=await fetch("/api/v1/scheduled-tasks",{method:"POST",headers:{"Content-Type":"application/json",...ae()},body:JSON.stringify({cron:r,prompt:s,recurring:i,durable:l,sessionId:d})});if(!o.ok){const c=await o.json().catch(()=>({}));throw new Error(((a=c.error)==null?void 0:a.message)||`HTTP ${o.status}`)}await t().fetchTasks()}catch(o){throw console.error("[ScheduledTasks] Create error:",o),e({error:o.message}),o}},deleteTask:async r=>{const s=xs();if(s)try{const i=new URLSearchParams({sessionId:s}),l=await fetch(`/api/v1/scheduled-tasks/${r}?${i}`,{method:"DELETE",headers:ae()});if(!l.ok&&l.status!==204)throw new Error(`HTTP ${l.status}`);await t().fetchTasks()}catch(i){throw console.error("[ScheduledTasks] Delete error:",i),e({error:i.message}),i}}})),dk=[{label:"5m",cron:"*/5 * * * *"},{label:"30m",cron:"*/30 * * * *"},{label:"1h",cron:"7 * * * *"},{label:"1d",cron:"3 9 * * *"},{label:"1w",cron:"3 9 * * 1"}];function uk({onSubmit:e,onCancel:t}){const{t:r}=ne(),[s,i]=C.useState("*/5 * * * *"),[l,d]=C.useState(""),[a,o]=C.useState(!0),[c,u]=C.useState(!1),[p,b]=C.useState(!1),[y,k]=C.useState(null),v=async()=>{if(!(!s.trim()||!l.trim())){b(!0),k(null);try{await e(s.trim(),l.trim(),a,c),t()}catch(g){k(g.message||"Failed to create task")}finally{b(!1)}}};return n.jsxs("div",{className:"border border-accent-brand/30 rounded-xl p-4 bg-bg-secondary/30",children:[n.jsxs("div",{className:"flex items-center justify-between mb-3",children:[n.jsx("h3",{className:"text-sm font-medium text-text-primary",children:r("scheduled.create")}),n.jsx("button",{onClick:t,className:"p-1 rounded hover:bg-bg-secondary text-text-tertiary",children:n.jsx(Te,{size:14})})]}),n.jsxs("div",{className:"mb-3",children:[n.jsx("label",{className:"text-xs text-text-secondary mb-1 block",children:r("scheduled.cron")}),n.jsx("input",{type:"text",value:s,onChange:g=>i(g.target.value),placeholder:"*/5 * * * *",className:"w-full px-3 py-1.5 text-sm rounded-lg border border-border-default bg-bg-primary text-text-primary focus:border-accent-brand/50 outline-none font-mono"}),n.jsx("div",{className:"flex gap-1.5 mt-1.5",children:dk.map(g=>n.jsx("button",{onClick:()=>i(g.cron),className:`text-[10px] px-2 py-0.5 rounded-full border transition-colors ${s===g.cron?"border-accent-brand/50 text-accent-brand bg-accent-brand/5":"border-border-default text-text-tertiary hover:text-text-secondary hover:border-border-default/80"}`,children:g.label},g.label))})]}),n.jsxs("div",{className:"mb-3",children:[n.jsx("label",{className:"text-xs text-text-secondary mb-1 block",children:r("scheduled.prompt")}),n.jsx("textarea",{value:l,onChange:g=>d(g.target.value),placeholder:r("scheduled.promptPlaceholder"),rows:2,className:"w-full px-3 py-1.5 text-sm rounded-lg border border-border-default bg-bg-primary text-text-primary focus:border-accent-brand/50 outline-none resize-none"})]}),n.jsxs("div",{className:"flex items-center gap-4 mb-3",children:[n.jsxs("label",{className:"flex items-center gap-2 text-xs text-text-secondary cursor-pointer",children:[n.jsx("input",{type:"checkbox",checked:a,onChange:g=>o(g.target.checked),className:"rounded"}),r("scheduled.recurring")]}),n.jsxs("label",{className:"flex items-center gap-2 text-xs text-text-secondary cursor-pointer",children:[n.jsx("input",{type:"checkbox",checked:c,onChange:g=>u(g.target.checked),className:"rounded"}),r("scheduled.durable")]})]}),y&&n.jsx("div",{className:"text-xs text-accent-red mb-2",children:y}),n.jsxs("button",{onClick:v,disabled:p||!s.trim()||!l.trim(),className:"flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-accent-brand text-white text-sm font-medium hover:bg-accent-brand/90 disabled:opacity-50 disabled:cursor-not-allowed transition-colors",children:[n.jsx(ot,{size:14}),r(p?"scheduled.creating":"scheduled.create")]})]})}function pk({task:e,onDelete:t}){const{t:r}=ne(),[s,i]=C.useState(!1),l=async()=>{i(!0);try{await t(e.id)}finally{i(!1)}},d=e.durable||e.permanent;return n.jsxs("div",{className:"group flex items-start gap-3 px-4 py-3 rounded-xl border border-border-default hover:border-accent-brand/30 transition-colors",children:[n.jsx("div",{className:"flex-shrink-0 mt-0.5",children:e.recurring?n.jsx(nb,{size:18,className:"text-accent-blue"}):n.jsx(Dp,{size:18,className:"text-accent-yellow"})}),n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[n.jsx("span",{className:"text-sm font-medium text-text-primary",children:e.humanSchedule}),n.jsx("span",{className:`text-[10px] px-1.5 py-0.5 rounded-full ${e.recurring?"bg-accent-blue/10 text-accent-blue":"bg-accent-yellow/10 text-accent-yellow"}`,children:e.recurring?r("scheduled.recurring"):r("scheduled.oneShot")}),d&&n.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded-full bg-accent-green/10 text-accent-green",children:r("scheduled.durable")})]}),n.jsx("p",{className:"text-xs text-text-secondary truncate",title:e.prompt,children:e.prompt}),n.jsxs("div",{className:"flex items-center gap-3 mt-1.5 text-[10px] text-text-tertiary",children:[n.jsxs("span",{className:"flex items-center gap-1",children:[n.jsx(Dt,{size:10}),"ID: ",e.id]}),e.lastFiredAt&&n.jsxs("span",{children:[r("scheduled.lastFired"),": ",new Date(e.lastFiredAt).toLocaleString()]})]})]}),n.jsx("button",{onClick:l,disabled:s,className:"flex-shrink-0 p-1.5 rounded-lg opacity-0 group-hover:opacity-100 hover:bg-accent-red/10 text-text-tertiary hover:text-accent-red transition-all disabled:opacity-50",title:r("scheduled.delete"),children:n.jsx(hr,{size:14})})]})}const hk=3e3;function tm(){const{t:e}=ne(),{setMainView:t}=pe(),{setExternalInput:r,sessionId:s}=rt(),{tasks:i,loading:l,fetchTasks:d,createTask:a,deleteTask:o}=ck(),[c,u]=C.useState(!1);C.useEffect(()=>{d()},[d,s]);const[p,b]=C.useState([]),[y,k]=C.useState(!0),[v,g]=C.useState(null),[m,h]=C.useState(!1),[f,x]=C.useState(!1),E=C.useRef(s);E.current=s;const _=C.useRef(null),S=C.useCallback(()=>{_.current&&(clearInterval(_.current),_.current=null)},[]),w=C.useCallback(async()=>{const j=new URLSearchParams,$=E.current;$&&j.append("sessionId",$);const G=j.toString(),F=await fetch(`/api/v1/tasks/templates${G?"?"+G:""}`,{headers:ae()});if(!F.ok)throw new Error(`HTTP ${F.status}`);const W=await F.json(),V=W.data??W;return b(V.templates||[]),g(V.error||null),V.status},[]),N=C.useCallback(()=>{S(),_.current=setInterval(async()=>{try{const j=await w();j!=="loading"&&(S(),h(!1),j==="done"&&(x(!0),setTimeout(()=>x(!1),2e3)))}catch(j){S(),h(!1),g(j.message||"Failed to load templates")}},hk)},[w,S]);C.useEffect(()=>{let j=!1;return(async()=>{try{if(!E.current){j||k(!1);return}const $=await w();if(j)return;$==="loading"&&(h(!0),N())}catch($){j||g($.message)}finally{j||k(!1)}})(),()=>{j=!0,S()}},[w,N,S,s]);const L=C.useCallback(async()=>{h(!0),g(null),x(!1);try{const j=new URLSearchParams,$=E.current;$&&j.append("sessionId",$);const G=j.toString(),F=await fetch(`/api/v1/tasks/templates/refresh${G?"?"+G:""}`,{method:"POST",headers:ae()});if(!F.ok)throw new Error(`HTTP ${F.status}`);N()}catch(j){g(j.message||"Failed to trigger refresh"),h(!1)}},[N]),R=C.useCallback(j=>{r(j.command),t("chat")},[r,t]);return n.jsx("div",{className:"flex-1 flex flex-col overflow-hidden bg-bg-primary",children:n.jsxs("div",{className:"flex-1 overflow-y-auto",children:[n.jsx("div",{className:"border-b border-border-default",children:n.jsxs("div",{className:"px-6 py-4",children:[n.jsxs("div",{className:"flex items-center justify-between mb-3",children:[n.jsxs("div",{children:[n.jsx("h2",{className:"text-lg font-semibold text-text-primary",children:e("scheduled.title")}),n.jsx("p",{className:"text-xs text-text-tertiary mt-0.5",children:e("scheduled.subtitle")})]}),n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("button",{onClick:()=>d(),className:"p-2 rounded-lg border border-border-default text-text-secondary hover:text-text-primary hover:bg-bg-secondary transition-colors",title:e("tasks.refresh"),children:n.jsx(Ve,{size:14,className:l?"animate-spin":""})}),n.jsxs("button",{onClick:()=>u(!c),className:`flex items-center gap-1.5 px-3 py-1.5 rounded-lg border text-sm transition-colors ${c?"border-accent-brand/50 text-accent-brand bg-accent-brand/5":"border-border-default text-text-secondary hover:text-text-primary hover:border-accent-brand/30"}`,children:[n.jsx(ot,{size:14}),e("scheduled.create")]})]})]}),c&&n.jsx("div",{className:"mb-3",children:n.jsx(uk,{onSubmit:a,onCancel:()=>u(!1)})}),l&&i.length===0?n.jsxs("div",{className:"py-8 text-center text-text-tertiary text-sm",children:[n.jsx(Ve,{size:16,className:"animate-spin mx-auto mb-2"}),e("scheduled.loading")]}):i.length===0?n.jsxs("div",{className:"py-8 text-center",children:[n.jsx(Dt,{size:32,className:"mx-auto mb-2 text-text-tertiary opacity-30"}),n.jsx("p",{className:"text-sm text-text-tertiary",children:e("scheduled.empty")}),n.jsx("p",{className:"text-xs text-text-tertiary mt-1",children:e("scheduled.emptyHint")})]}):n.jsx("div",{className:"space-y-2",children:i.map(j=>n.jsx(pk,{task:j,onDelete:o},j.id))})]})}),n.jsxs("div",{className:"px-6 py-4",children:[n.jsxs("div",{className:"flex items-center justify-between mb-3",children:[n.jsxs("div",{children:[n.jsx("h2",{className:"text-lg font-semibold text-text-primary",children:e("tasks.title")}),n.jsx("p",{className:"text-xs text-text-tertiary mt-0.5",children:e("tasks.subtitle")})]}),n.jsxs("button",{onClick:L,disabled:m,className:`flex items-center gap-2 px-3 py-1.5 rounded-lg border text-sm transition-all ${f?"border-green-500/50 text-green-500":m?"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"}`,children:[f?n.jsx(Ht,{size:14}):n.jsx(Ve,{size:14,className:m?"animate-spin":""}),n.jsx("span",{children:e(f?"tasks.refreshed":"tasks.refresh")})]})]}),y&&!m&&n.jsx("div",{className:"flex flex-col items-center justify-center py-12 text-text-tertiary",children:n.jsx(pt,{size:"small",text:e("tasks.loading")})}),v&&!y&&n.jsxs("div",{className:"flex flex-col items-center justify-center py-12",children:[n.jsx("div",{className:"text-text-tertiary text-[48px] mb-4 opacity-30",children:"!"}),n.jsx("div",{className:"text-text-secondary text-sm mb-4",children:e("tasks.error")}),n.jsx("button",{onClick:L,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")})]}),!y&&p.length===0&&!v&&n.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-text-tertiary",children:[n.jsx(of,{size:32,className:"mb-2 opacity-30"}),n.jsx("div",{className:"text-sm",children:e("tasks.empty")})]}),p.length>0&&n.jsx("div",{className:`grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3 max-w-6xl transition-opacity duration-300 ${m?"opacity-50 pointer-events-none":"opacity-100"}`,children:p.map(j=>{const $=mk(j.icon);return n.jsxs("div",{onClick:()=>R(j),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:[n.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:n.jsx($,{size:20,className:"text-text-tertiary group-hover:text-accent-brand transition-colors"})}),n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsx("h3",{className:"text-sm font-semibold text-text-primary truncate",children:j.title}),n.jsx("p",{className:"text-xs text-text-tertiary mt-0.5 truncate",children:j.description})]})]},j.id)})})]})]})})}function mk(e){switch(e){case"Newspaper":return Od;case"MessageSquare":return Od;case"GitBranch":return fp;case"Package":return Ff;case"FileText":return ut;case"Zap":return nr;case"Clock":return Dt;default:return Dt}}function Vs({node:e,path:t}){const r=pe(i=>i.setRatio),s=C.useCallback(i=>{r(t,i)},[r,t]);return e.type==="leaf"?n.jsx(oi,{paneId:e.paneId}):n.jsxs(On,{direction:e.direction,ratio:e.ratio,onRatioChange:s,children:[n.jsx(Vs,{node:e.children[0],path:[...t,0]}),n.jsx(Vs,{node:e.children[1],path:[...t,1]})]})}function rm(){const e=pe(t=>t.layout);return n.jsx("div",{className:"flex-1 w-full h-full overflow-hidden",children:n.jsx(Vs,{node:e,path:[]})})}function gk({isOpen:e,onClose:t,onImageSelect:r,onFileSelect:s,onNewChat:i,onHistory:l,mainView:d}){const{t:a}=ne(),o=C.useRef(null),[c,u]=C.useState(null),[p,b]=C.useState(0),y=C.useCallback(()=>{r(),t()},[r,t]),k=C.useCallback(()=>{s(),t()},[s,t]),v=[{type:"attachment",icon:n.jsx(vp,{size:22}),label:a("input.menu.image"),action:y},{type:"attachment",icon:n.jsx(ut,{size:22}),label:a("input.menu.file"),action:k},{type:"action",icon:n.jsx(ot,{size:20}),label:a("chat.newChat"),action:i},{type:"action",icon:n.jsx(xp,{size:20}),label:a("sidebar.chatHistory"),action:l},{type:"nav",view:"changes",icon:n.jsx(Ln,{size:20}),label:a("sidebar.changes")},{type:"nav",view:"tasks",icon:n.jsx(ri,{size:20}),label:a("sidebar.nav.tasks")},{type:"nav",view:"terminal",icon:n.jsx(pr,{size:20}),label:a("sidebar.terminalMode")},{type:"nav",view:"plugins",icon:n.jsx(zt,{size:20}),label:a("sidebar.nav.plugins")},{type:"nav",view:"settings",icon:n.jsx(ii,{size:20}),label:a("sidebar.preferences")}].filter(E=>!(E.type==="action"&&!E.action)),g=8,m=Math.ceil(v.length/g),h=[];for(let E=0;E<m;E++)h.push(v.slice(E*g,(E+1)*g));C.useEffect(()=>{const E=o.current;if(!E)return;const _=()=>{const S=E.clientWidth;if(S>0){const w=Math.round(E.scrollLeft/S);b(w)}};return E.addEventListener("scroll",_,{passive:!0}),()=>E.removeEventListener("scroll",_)},[]);const f=C.useCallback(E=>{const _=o.current;_&&_.scrollTo({left:E*_.clientWidth,behavior:"smooth"})},[]),x=C.useCallback(()=>{u(null)},[]);return e?n.jsxs(n.Fragment,{children:[n.jsxs("div",{className:"bottom-sheet-inline",children:[n.jsx("div",{ref:o,className:"bottom-sheet-scroll",children:h.map((E,_)=>n.jsx("div",{className:"bottom-sheet-page",children:n.jsx("div",{className:"bottom-sheet-grid",children:E.map((S,w)=>n.jsxs("button",{className:S.type==="nav"&&d===S.view?"active":"",onClick:()=>{var N;S.type==="attachment"||S.type==="action"?(N=S.action)==null||N.call(S):S.type==="nav"&&S.view&&u(S.view)},children:[S.icon,n.jsx("span",{children:S.label})]},w))})},_))}),m>1&&n.jsx("div",{className:"bottom-sheet-pagination",children:Array.from({length:m}).map((E,_)=>n.jsx("button",{className:`pagination-dot ${_===p?"active":""}`,onClick:()=>f(_)},_))})]}),c&&n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"floating-panel-overlay",onClick:x}),n.jsxs("div",{className:"floating-panel-container",children:[n.jsx("div",{className:"floating-panel-header",children:n.jsx("button",{onClick:x,className:"floating-panel-close-btn",title:a("common.close"),children:n.jsx(Te,{size:24})})}),n.jsxs("div",{className:"floating-panel-content",children:[c==="changes"&&n.jsx(dh,{}),c==="tasks"&&n.jsx(tm,{}),c==="terminal"&&n.jsx(rm,{}),c==="plugins"&&n.jsx(Jh,{}),c==="settings"&&n.jsx(em,{})]})]})]})]}):null}const fk=5,nm=10*1024*1024,Ar=["image/jpeg","image/png","image/gif","image/webp"];let bk=0;function yk(e){return!Ar.includes(e.type)||e.size>nm?Promise.resolve(null):new Promise(t=>{const r=new FileReader;r.onload=()=>{const s=r.result,i=s.split(",")[1]||"";t({id:`img-${++bk}`,dataUrl:s,data:i,mimeType:e.type})},r.onerror=()=>t(null),r.readAsDataURL(e)})}const xk=10,vk=1*1024*1024,_k=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 Sk=0;function sm(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 i=t.slice(r);if(_k.has(i))return!0}const s=t.split("/").pop()||t;return!!["makefile","dockerfile","cmakelists.txt","gemfile","rakefile","procfile"].includes(s)}function kk(e){return!sm(e)||e.size>vk?Promise.resolve(null):new Promise(t=>{const r=new FileReader;r.onload=()=>{const s=r.result;t({id:`file-${++Sk}`,name:e.name,size:e.size,text:s,mimeType:e.type||"text/plain"})},r.onerror=()=>t(null),r.readAsText(e)})}function wk(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function Ek({onNavigate:e,onNewChat:t,onHistory:r,mainView:s,showBottomSheet:i=!1,setShowBottomSheet:l}){const d=C.useCallback(K=>{l&&l(typeof K=="function"?K(i):K)},[l,i]),[a,o]=C.useState(()=>window.innerWidth<=768),[c,u]=C.useState(""),[p,b]=C.useState([]),[y,k]=C.useState([]),[v,g]=C.useState(0),[m,h]=C.useState(!1),[f,x]=C.useState(null),[E,_]=C.useState(0),[S,w]=C.useState([]),[N,L]=C.useState(0),[R,j]=C.useState(null),$=C.useRef(null),G=C.useRef(null),F=C.useRef(null),W=C.useRef(null),V=C.useRef(null),q=C.useRef(null),A=C.useRef(null),T=C.useRef(null),D=C.useRef(0),I=C.useRef(!1),P=C.useRef(!1),{sessionId:M,commands:H,thinkingEnabled:z,setThinkingEnabled:U,promptSuggestion:O,setPromptSuggestion:Y,externalInput:X,setExternalInput:Q}=rt(),{isAgentRunning:J,hasPendingInterruption:re,timeline:ue,addUserMessage:de,addQueuedUserMessage:me,setSessionEnd:ie,resolveInterruption:Oe}=Me(),{t:_e,tryT:se}=ne();C.useEffect(()=>{X!==null&&(u(X),Q(null),Y(null),requestAnimationFrame(()=>{var K;(K=$.current)==null||K.focus()}))},[X,Q,Y]);const ce=C.useCallback(async K=>{const te=Array.from(K).filter(ge=>Ar.includes(ge.type)&&ge.size<=nm);if(te.length===0)return;g(ge=>ge+te.length);const ke=(await Promise.all(te.map(yk))).filter(ge=>ge!==null);g(ge=>Math.max(0,ge-te.length)),ke.length>0&&b(ge=>{const Fe=fk-ge.length;return[...ge,...ke.slice(0,Fe)]})},[]),Ee=C.useCallback(K=>{b(te=>te.filter(le=>le.id!==K))},[]),xe=C.useCallback(async K=>{const te=Array.from(K),ke=(await Promise.all(te.map(kk))).filter(ge=>ge!==null);ke.length!==0&&k(ge=>{const Fe=xk-ge.length;return[...ge,...ke.slice(0,Fe)]})},[]),Ze=C.useCallback(K=>{k(te=>te.filter(le=>le.id!==K))},[]),ee=C.useCallback(K=>{var te;K.preventDefault(),K.stopPropagation(),D.current++,(te=K.dataTransfer)!=null&&te.types.includes("Files")&&h(!0)},[]),oe=C.useCallback(K=>{K.preventDefault(),K.stopPropagation(),D.current--,D.current===0&&h(!1)},[]),fe=C.useCallback(K=>{K.preventDefault(),K.stopPropagation()},[]),$e=C.useCallback(K=>{var te;if(K.preventDefault(),K.stopPropagation(),D.current=0,h(!1),(te=K.dataTransfer)!=null&&te.files){const le=Array.from(K.dataTransfer.files),ke=le.filter(Fe=>Ar.includes(Fe.type)),ge=le.filter(Fe=>!Ar.includes(Fe.type)&&sm(Fe));ke.length>0&&ce(ke),ge.length>0&&xe(ge)}},[ce,xe]),Je=C.useCallback(K=>{var le;const te=(le=K.clipboardData)==null?void 0:le.files;te&&te.length>0&&Array.from(te).some(ge=>Ar.includes(ge.type))&&(K.preventDefault(),ce(te))},[ce]),Qe=C.useCallback(()=>{var K;(K=G.current)==null||K.click()},[]),ht=C.useCallback(()=>{var K;(K=F.current)==null||K.click()},[]),Se=C.useCallback(K=>{K.target.files&&ce(K.target.files),K.target.value=""},[ce]),qn=C.useCallback(K=>{K.target.files&&xe(K.target.files),K.target.value=""},[xe]),$t=C.useMemo(()=>{const K=c.trimStart();if(!K.startsWith("/")||K.includes(" "))return[];const te=K.substring(1).toLowerCase();return H.filter(le=>{const ke=se(`command.${le.name}.description`)??le.description;return le.name.toLowerCase().includes(te)||le.description.toLowerCase().includes(te)||ke.toLowerCase().includes(te)}).slice(0,8)},[c,H,se]),Et=$t.length>0;C.useEffect(()=>{_(0)},[$t.length]),C.useEffect(()=>{if(Et&&W.current){const K=W.current.children[E];K==null||K.scrollIntoView({block:"nearest"})}},[E,Et]);const Sr=C.useMemo(()=>{if(R===null)return null;const K=c.substring(R+1),te=K.search(/\s/),le=te===-1?K:K.substring(0,te);return te===0?null:le},[c,R]),Ct=Sr!==null&&S.length>0,kr=C.useRef(null);C.useEffect(()=>{if(Sr===null){w([]);return}return kr.current&&clearTimeout(kr.current),kr.current=setTimeout(async()=>{try{const K=new URLSearchParams;Sr&&K.set("query",Sr),K.set("limit","15");const te=await fetch(`/api/v1/fs/search?${K.toString()}`,{headers:ae()});if(te.ok){const le=await te.json();w(le.items||[]),L(0)}else w([])}catch{w([])}},150),()=>{kr.current&&clearTimeout(kr.current)}},[Sr]),C.useEffect(()=>{if(Ct&&V.current){const K=V.current.children[N];K==null||K.scrollIntoView({block:"nearest"})}},[N,Ct]);const Vn=C.useRef(!1),Kn=C.useCallback(K=>{if(R===null)return;const te=c.substring(0,R),le=c.substring(R+1),ke=le.search(/\s/),ge=ke===-1?"":le.substring(ke),mt=ge.length===0||!/^\s/.test(ge)?" ":"",Mt=`${te}@${K.path}${mt}${ge}`,wr=te.length+1+K.path.length+mt.length;u(Mt),w([]),j(null),Vn.current=!0,requestAnimationFrame(()=>{const Yt=$.current;Yt&&(Yt.focus(),Yt.setSelectionRange(wr,wr))})},[c,R]);C.useEffect(()=>{const K=()=>o(window.innerWidth<=768);return window.addEventListener("resize",K),()=>window.removeEventListener("resize",K)},[]),C.useEffect(()=>{var K;!a&&!J&&((K=$.current)==null||K.focus())},[a,J]),C.useEffect(()=>{const K=$.current;if(K){K.style.height="auto";const te=window.innerHeight*.2,le=Math.min(K.scrollHeight,te);K.style.height=`${le}px`,K.style.overflowY=K.scrollHeight>te?"auto":"hidden"}},[c]);const Yn=C.useCallback(K=>{var te;u(`/${K.name} `),(te=$.current)==null||te.focus()},[]),jt=C.useCallback(async K=>{var vd;const te=(K??c).trim(),le=p.length>0,ke=y.length>0;if(!te&&!(le||ke)||!M||re)return;u(""),Y(null);const Fe=[...p],mt=[...y];b([]),k([]);const Mt=Fe.length>0?Fe.map(Ie=>({data:Ie.data,mimeType:Ie.mimeType})):void 0,wr=mt.length>0?mt.map(Ie=>({name:Ie.name,text:Ie.text,mimeType:Ie.mimeType})):void 0,Yt=mt.length>0?mt.map(Ie=>({name:Ie.name,size:Ie.size,mimeType:Ie.mimeType})):void 0;if((vd=$.current)==null||vd.blur(),J)me(te,Mt,Yt),Re().prompt(M,te,Mt,wr).catch(Ie=>{console.error("Queued prompt failed:",Ie)});else{if(P.current)return;P.current=!0,de(te,Mt,Yt);try{const Ie=await Re().prompt(M,te,Mt,wr);ie(Ie.stopReason,Ie.errorMessage,Ie.errorCategory)}catch(Ie){console.error("Prompt failed:",Ie),ie("error",Ie instanceof Error?Ie.message:_e("input.promptFailed"))}finally{P.current=!1}}},[c,p,y,M,J,re,de,me,ie,Y,_e]),lm=C.useCallback(async()=>{if(M)try{const K=Re(),te=ue.filter(le=>le.type==="interruption"&&!le.resolved);for(const le of te)if(le.type==="interruption")try{await K.respondToInterruption(M,le.id,"deny",le.toolCallId),Oe(le.id,"deny")}catch{}await K.cancel(M)}catch(K){console.error("Cancel failed:",K)}},[M,ue,Oe]),cm=C.useCallback(()=>{I.current=!0},[]),dm=C.useCallback(()=>{I.current=!1},[]),um=C.useCallback(K=>{K.preventDefault(),x({x:K.clientX,y:K.clientY})},[]),pm=C.useCallback(()=>{const K=$.current;if(!K)return;const te=K.selectionStart??c.length,le=K.selectionEnd??te,ke=c.slice(0,te)+`
|
|
688
|
+
`,children:s?n.jsx("div",{className:"flex flex-col items-center justify-center h-32",children:n.jsx(pt,{size:"small",text:e("docs.loading")})}):r?n.jsx(xS,{items:r,currentPath:i,onSelect:w}):n.jsx("div",{className:"p-4 text-sm text-text-tertiary",children:e("docs.loadError")})}),n.jsx("div",{className:"flex-1 min-w-0 overflow-hidden flex flex-col",children:L?n.jsx(yS,{query:o,results:c,onSelect:N}):d?n.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:n.jsx(pt,{size:"small",text:e("docs.loading")})}):a?n.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:n.jsxs("div",{className:"text-center",children:[n.jsx("div",{className:"text-text-tertiary text-[48px] mb-4 opacity-30",children:"📄"}),n.jsx("div",{className:"text-text-secondary text-sm mb-2",children:e("docs.notFound")}),n.jsx("div",{className:"text-text-tertiary text-xs",children:a})]})}):l?n.jsx(bS,{content:l,onNavigate:w}):n.jsxs("div",{className:"flex-1 flex flex-col items-center justify-center text-text-tertiary",children:[n.jsx("div",{className:"text-[48px] mb-4 opacity-30",children:"📖"}),n.jsx("div",{className:"text-sm",children:e("docs.title")})]})})]})]})}async function qt(e,t){var i;const r=await fetch("/api/v1/fs/list",{method:"POST",headers:{...ae(),"Content-Type":"application/json"},body:JSON.stringify({path:e,depth:t})});if(!r.ok)throw new Error(`List directory failed: HTTP ${r.status}`);const s=await r.json();return((i=s.data)==null?void 0:i.entries)??s.entries??[]}async function vS(e){const t=await fetch(`/api/v1/files/download?path=${encodeURIComponent(e)}`,{headers:ae()});if(!t.ok)throw new Error(`Read file failed: HTTP ${t.status}`);const r=await t.text();if(r.length===0){const s=Number(t.headers.get("Content-Length"));if(Number.isFinite(s)&&s>0)throw new Error(`Read file failed: empty body but Content-Length=${s}`)}return r}async function Ou(e,t){const r=await fetch(`/api/v1/files/upload?path=${encodeURIComponent(e)}`,{method:"POST",headers:{...ae(),"Content-Type":"application/octet-stream"},body:t});if(!r.ok)throw new Error(`Write file failed: HTTP ${r.status}`)}async function _S(e){const t=await fetch("/api/v1/fs/mkdir",{method:"POST",headers:{...ae(),"Content-Type":"application/json"},body:JSON.stringify({path:e})});if(!t.ok)throw new Error(`Create directory failed: HTTP ${t.status}`)}async function SS(e){const t=await fetch("/api/v1/fs/remove",{method:"POST",headers:{...ae(),"Content-Type":"application/json"},body:JSON.stringify({path:e})});if(!t.ok)throw new Error(`Remove failed: HTTP ${t.status}`)}async function kS(e){try{return await qt(e,1),"directory"}catch{return"file"}}async function $u(e,t){const r=await fetch("/api/v1/fs/move",{method:"POST",headers:{...ae(),"Content-Type":"application/json"},body:JSON.stringify({source:e,destination:t})});if(!r.ok)throw new Error(`Move failed: HTTP ${r.status}`)}const wS={".ts":"typescript",".tsx":"typescript",".mts":"typescript",".cts":"typescript",".js":"javascript",".jsx":"javascript",".mjs":"javascript",".cjs":"javascript",".json":"json",".jsonc":"json",".md":"markdown",".mdx":"markdown",".css":"css",".scss":"scss",".less":"less",".html":"html",".htm":"html",".xml":"xml",".svg":"xml",".yaml":"yaml",".yml":"yaml",".py":"python",".pyw":"python",".go":"go",".rs":"rust",".java":"java",".c":"c",".h":"c",".cpp":"cpp",".cc":"cpp",".cxx":"cpp",".hpp":"cpp",".cs":"csharp",".rb":"ruby",".php":"php",".swift":"swift",".kt":"kotlin",".kts":"kotlin",".sh":"shell",".bash":"shell",".zsh":"shell",".sql":"sql",".graphql":"graphql",".gql":"graphql",".vue":"html",".lua":"lua",".r":"r",".R":"r",".dockerfile":"dockerfile",".toml":"ini",".ini":"ini",".cfg":"ini",".env":"ini",".gitignore":"ini"};function ES(e){const t=e.substring(e.lastIndexOf("/")+1);if(t==="Dockerfile"||t.startsWith("Dockerfile."))return"dockerfile";if(t==="Makefile"||t==="GNUmakefile")return"makefile";const r=e.substring(e.lastIndexOf("."));return wS[r]||"plaintext"}const CS=new Set([".png",".jpg",".jpeg",".gif",".webp",".bmp",".ico",".tiff",".tif",".mp3",".mp4",".wav",".avi",".mov",".mkv",".flac",".ogg",".zip",".gz",".tar",".bz2",".7z",".rar",".xz",".exe",".dll",".so",".dylib",".bin",".o",".a",".pdf",".doc",".docx",".xls",".xlsx",".ppt",".pptx",".woff",".woff2",".ttf",".otf",".eot",".sqlite",".db"]);function Yh(e){const t=e.substring(e.lastIndexOf(".")).toLowerCase();return CS.has(t)}const TS=new Set([".png",".jpg",".jpeg",".gif",".webp",".bmp",".ico",".tiff",".tif"]);function NS(e){const t=e.substring(e.lastIndexOf(".")).toLowerCase();return TS.has(t)?"image":t===".svg"?"svg":t===".md"||t===".mdx"?"markdown":t===".pdf"?"pdf":Yh(e)?"binary":"editor"}const AS=2*1024*1024,IS=10;function ys(e,t,r){const s=e.filter(i=>i.path!==t);return[{path:t,name:r,timestamp:Date.now()},...s].slice(0,IS)}function RS(e){return[...e].sort((t,r)=>t.type==="directory"&&r.type!=="directory"?-1:t.type!=="directory"&&r.type==="directory"?1:t.name.localeCompare(r.name,void 0,{numeric:!0,sensitivity:"base"}))}function ju(e){return RS(e).map(t=>({name:t.name,path:t.path,type:t.type,children:(t.type==="directory",void 0)}))}function Xh(e,t,r){return e.path===t?{...e,children:r,isLoading:!1}:e.children?{...e,children:e.children.map(s=>Xh(s,t,r))}:e}function gd(e,t){const r=[];if(e.children)for(const s of e.children)r.push(s.path),s.type==="directory"&&t.has(s.path)&&s.children&&r.push(...gd(s,t));return r}function qs(e,t,r){return e.path===t?{...e,isLoading:r}:e.children?{...e,children:e.children.map(s=>qs(s,t,r))}:e}function LS(e){const t=new Map,r=new Map;for(const s of e)r.set(s.name,(r.get(s.name)||0)+1);for(const s of e)if(r.get(s.name)>1){const i=s.path.split("/"),l=i.length>=2?i[i.length-2]:"";t.set(s.id,l?`${l}/`:"")}else t.set(s.id,"");return t}const Ut=Ae()(Pr((e,t)=>({rootPath:null,tree:null,treeLoading:!1,treeError:!1,expandedPaths:new Set,selectedPath:null,selectedPaths:new Set,renamingPath:null,renamingIsNew:!1,tabs:[],activeTabId:null,recentFiles:[],splitRatio:.22,setRootPath:async r=>{e({rootPath:r,treeLoading:!0,tree:null,treeError:!1});try{const s=await qt(r),i=ju(s),l={name:r.split("/").pop()||r,path:r,type:"directory",children:i},d=t().expandedPaths,a=d instanceof Set?d:new Set;e({tree:l,treeLoading:!1,expandedPaths:new Set([r,...a])})}catch(s){console.error("[editor-store] setRootPath failed:",s),e({treeLoading:!1,treeError:!0})}},loadDirectory:async r=>{const{tree:s}=t();if(s){e({tree:qs(s,r,!0)});try{const i=await qt(r),l=ju(i),d=Xh(t().tree,r,l);e({tree:d})}catch{const i=t().tree;i&&e({tree:qs(i,r,!1)})}}},toggleExpand:r=>{const{expandedPaths:s}=t(),i=new Set(s);if(i.has(r))i.delete(r);else{i.add(r);const{tree:l}=t();if(l){const d=o=>{if(o.path===r)return o;if(o.children)for(const c of o.children){const u=d(c);if(u)return u}return null},a=d(l);a&&a.type==="directory"&&!a.children&&t().loadDirectory(r)}}e({expandedPaths:i})},selectPath:(r,s)=>{const{selectedPaths:i,selectedPath:l,tree:d,expandedPaths:a}=t();if(s!=null&&s.ctrl){const o=new Set(i);o.has(r)?(o.delete(r),e({selectedPaths:o,selectedPath:o.size>0?[...o][o.size-1]:null})):(o.add(r),e({selectedPaths:o,selectedPath:r}))}else if(s!=null&&s.shift&&l&&d){const o=gd(d,a),c=o.indexOf(l),u=o.indexOf(r);if(c>=0&&u>=0){const p=Math.min(c,u),b=Math.max(c,u),y=new Set(o.slice(p,b+1));e({selectedPaths:y,selectedPath:r})}}else e({selectedPath:r,selectedPaths:new Set([r])})},refreshTree:async()=>{const{rootPath:r}=t();r&&await t().setRootPath(r)},collapseAll:()=>{const{rootPath:r}=t(),s=new Set;r&&s.add(r),e({expandedPaths:s})},createNewFile:()=>{const{selectedPath:r,rootPath:s,tree:i,expandedPaths:l}=t();let d=s;if(r&&i){const o=u=>{if(u.path===r)return u;if(u.children)for(const p of u.children){const b=o(p);if(b)return b}return null},c=o(i);c&&(d=c.type==="directory"?c.path:c.path.substring(0,c.path.lastIndexOf("/")))}if(!d)return;l.has(d)||t().toggleExpand(d);const a=d+"/__new_file__";t().startCreateFile(a)},createNewFolder:()=>{const{selectedPath:r,rootPath:s,tree:i,expandedPaths:l}=t();let d=s;if(r&&i){const o=u=>{if(u.path===r)return u;if(u.children)for(const p of u.children){const b=o(p);if(b)return b}return null},c=o(i);c&&(d=c.type==="directory"?c.path:c.path.substring(0,c.path.lastIndexOf("/")))}if(!d)return;l.has(d)||t().toggleExpand(d);const a=d+"/__new_folder__";t().startCreateFolder(a)},startRename:r=>{e({renamingPath:r,renamingIsNew:!1,selectedPath:r})},startCreateFile:r=>{const s=r.substring(0,r.lastIndexOf("/")),{tree:i}=t();if(!i)return;const l={name:"",path:r,type:"file"},d=a=>a.path===s?{...a,children:[l,...a.children||[]]}:a.children?{...a,children:a.children.map(o=>d(o))}:a;e({tree:d(i),renamingPath:r,renamingIsNew:!0,selectedPath:r})},startCreateFolder:r=>{const s=r.substring(0,r.lastIndexOf("/")),{tree:i}=t();if(!i)return;const l={name:"",path:r,type:"directory"},d=a=>a.path===s?{...a,children:[l,...a.children||[]]}:a.children?{...a,children:a.children.map(o=>d(o))}:a;e({tree:d(i),renamingPath:r,renamingIsNew:!0,selectedPath:r})},confirmRename:async(r,s)=>{const{renamingIsNew:i}=t();if(!s.trim()){if(i){const a=r.substring(0,r.lastIndexOf("/"));e({renamingPath:null,renamingIsNew:!1}),await t().loadDirectory(a)}else e({renamingPath:null,renamingIsNew:!1});return}const l=r.substring(0,r.lastIndexOf("/")),d=l+"/"+s.trim();if(i){try{const{tree:a}=t(),o=u=>{if(u.path===r)return u;if(u.children)for(const p of u.children){const b=o(p);if(b)return b}return null},c=a?o(a):null;(c==null?void 0:c.type)==="directory"?await _S(d):await Ou(d,""),e({renamingPath:null,renamingIsNew:!1,selectedPath:d}),await t().loadDirectory(l),(c==null?void 0:c.type)!=="directory"&&await t().openFile(d,s.trim())}catch{e({renamingPath:null,renamingIsNew:!1}),await t().loadDirectory(l)}return}if(d===r){e({renamingPath:null,renamingIsNew:!1});return}try{await $u(r,d),e(a=>({renamingPath:null,renamingIsNew:!1,selectedPath:d,tabs:a.tabs.map(o=>o.path===r?{...o,id:d,path:d,name:s.trim()}:o),activeTabId:a.activeTabId===r?d:a.activeTabId})),await t().loadDirectory(l)}catch{e({renamingPath:null,renamingIsNew:!1})}},cancelRename:()=>{const{renamingIsNew:r,renamingPath:s}=t();if(r&&s){const i=s.substring(0,s.lastIndexOf("/"));e({renamingPath:null,renamingIsNew:!1}),t().loadDirectory(i)}else e({renamingPath:null,renamingIsNew:!1})},openFile:async(r,s)=>{const{tabs:i}=t(),l=i.find(c=>c.path===r);if(l){e({activeTabId:l.id,selectedPath:r});return}const d=s||r.substring(r.lastIndexOf("/")+1),a=ES(r),o=NS(r);if(o==="image"||o==="pdf"||o==="binary"){const c={id:r,path:r,name:d,content:"",originalContent:"",language:a,isDirty:!1,isPinned:!1,viewMode:o};e(u=>({tabs:[...u.tabs,c],activeTabId:c.id,selectedPath:r,recentFiles:ys(u.recentFiles,r,d)}));return}try{const c=await vS(r);if(c.length>AS)return;const u={id:r,path:r,name:d,content:c,originalContent:c,language:a,isDirty:!1,isPinned:!1,viewMode:o};e(p=>({tabs:[...p.tabs,u],activeTabId:u.id,selectedPath:r,recentFiles:ys(p.recentFiles,r,d)}))}catch{}},closeTab:r=>{e(s=>{const i=s.tabs.find(c=>c.id===r),l=s.tabs.findIndex(c=>c.id===r),d=s.tabs.filter(c=>c.id!==r);let a=s.activeTabId;s.activeTabId===r&&(a=d.length>0?d[Math.min(l,d.length-1)].id:null);const o=i?ys(s.recentFiles,i.path,i.name):s.recentFiles;return{tabs:d,activeTabId:a,recentFiles:o}})},closeOtherTabs:r=>{e(s=>({tabs:s.tabs.filter(i=>i.id===r||i.isPinned),activeTabId:r}))},closeAllTabs:()=>{e(r=>{const s=r.tabs.filter(i=>i.isPinned);return{tabs:s,activeTabId:s.length>0?s[0].id:null}})},closeTabsToRight:r=>{e(s=>{const i=s.tabs.findIndex(a=>a.id===r);if(i<0)return s;const l=s.tabs.filter((a,o)=>o<=i||a.isPinned),d=l.some(a=>a.id===s.activeTabId);return{tabs:l,activeTabId:d?s.activeTabId:r}})},closeSavedTabs:()=>{e(r=>{const s=r.tabs.filter(l=>l.isPinned||l.isDirty),i=s.some(l=>l.id===r.activeTabId);return{tabs:s,activeTabId:i?r.activeTabId:s.length>0?s[0].id:null}})},setActiveTab:r=>{const s=t().tabs.find(i=>i.id===r);e({activeTabId:r,selectedPath:(s==null?void 0:s.path)||null})},updateTabContent:(r,s)=>{e(i=>({tabs:i.tabs.map(l=>l.id===r?{...l,content:s,isDirty:s!==l.originalContent}:l)}))},saveTab:async r=>{const s=t().tabs.find(i=>i.id===r);if(!(!s||!s.isDirty))try{await Ou(s.path,s.content),e(i=>({tabs:i.tabs.map(l=>l.id===r?{...l,originalContent:l.content,isDirty:!1}:l)}))}catch{}},deleteSelected:async()=>{const{selectedPaths:r,tabs:s}=t();if(r.size===0)return;const i=[...r],l=new Set(i.map(d=>d.substring(0,d.lastIndexOf("/"))));try{await Promise.all(i.map(a=>SS(a)));const d=s.filter(a=>!i.some(o=>a.path===o||a.path.startsWith(o+"/")));e(a=>({selectedPaths:new Set,selectedPath:null,tabs:d,activeTabId:d.length>0?d.find(o=>o.id===a.activeTabId)?a.activeTabId:d[0].id:null}));for(const a of l)await t().loadDirectory(a)}catch{for(const d of l)await t().loadDirectory(d)}},moveToDirectory:async(r,s)=>{if(r.length===0)return;const i=new Set(r.map(l=>l.substring(0,l.lastIndexOf("/"))));i.add(s);try{for(const l of r){const d=l.substring(l.lastIndexOf("/")+1),a=s+"/"+d;l!==a&&await $u(l,a)}e({selectedPaths:new Set,selectedPath:null});for(const l of i)await t().loadDirectory(l)}catch{for(const l of i)await t().loadDirectory(l)}},revealInTree:async r=>{const{rootPath:s}=t();if(!s||!r.startsWith(s))return;const l=r.slice(s.length).replace(/^\//,"").split("/").filter(Boolean),d=new Set(t().expandedPaths);let a=s;d.add(s);for(const o of l)if(a=a+"/"+o,a!==r){d.add(a);const{tree:c}=t();if(c){const u=b=>{if(b.path===a)return b;if(b.children)for(const y of b.children){const k=u(y);if(k)return k}return null},p=u(c);p&&p.type==="directory"&&!p.children&&await t().loadDirectory(a)}}e({expandedPaths:d,selectedPath:r})},reorderTabs:(r,s)=>{e(i=>{const l=[...i.tabs],[d]=l.splice(r,1);return l.splice(s,0,d),{tabs:l}})},pinTab:r=>{e(s=>{const i=s.tabs.findIndex(o=>o.id===r);if(i<0)return s;const l=[...s.tabs];l[i]={...l[i],isPinned:!0};const[d]=l.splice(i,1),a=l.reduce((o,c,u)=>c.isPinned?u:o,-1);return l.splice(a+1,0,d),{tabs:l}})},unpinTab:r=>{e(s=>({tabs:s.tabs.map(i=>i.id===r?{...i,isPinned:!1}:i)}))},setSplitRatio:r=>{const s=Math.max(.12,Math.min(.5,r));e({splitRatio:s})}}),{namespace:"editor",fields:["splitRatio","expandedPaths","recentFiles"],scope:"workspace",debounceMs:500,onLoad:(e,t)=>{const r={};if(e.splitRatio!==void 0&&(r.splitRatio=e.splitRatio),e.expandedPaths){const s=e.expandedPaths;r.expandedPaths=new Set(Array.isArray(s)?s:[])}e.recentFiles&&(r.recentFiles=e.recentFiles),Object.keys(r).length>0&&t(r)}}));function DS(e){return[...e].sort((t,r)=>t.type==="directory"&&r.type!=="directory"?-1:t.type!=="directory"&&r.type==="directory"?1:t.name.localeCompare(r.name,void 0,{numeric:!0,sensitivity:"base"}))}function OS({filePath:e,rootPath:t,onSegmentClick:r,onOpenFile:s}){const l=(e.startsWith(t)?e.slice(t.length).replace(/^\//,""):e).split("/").filter(Boolean),[d,a]=C.useState(null),[o,c]=C.useState([]),[u,p]=C.useState(!1),[b,y]=C.useState(-1),k=C.useRef(null),v=C.useRef(null),g=C.useCallback(async(E,_)=>{const S=_.getBoundingClientRect();a({dirPath:E,anchorRect:S}),p(!0),c([]),y(-1);try{const w=await qt(E);c(DS(w.map(N=>({name:N.name,path:N.path,type:N.type}))))}catch{c([])}p(!1)},[]),m=C.useCallback(()=>{a(null),c([]),y(-1)},[]),h=C.useCallback(E=>{E.type==="directory"?(r(E.path),m()):(s(E.path),m())},[r,s,m]);C.useEffect(()=>{if(!d)return;const E=_=>{if(_.key==="Escape"){_.preventDefault(),m();return}_.key==="ArrowDown"?(_.preventDefault(),y(S=>S<o.length-1?S+1:0)):_.key==="ArrowUp"?(_.preventDefault(),y(S=>S>0?S-1:o.length-1)):_.key==="Enter"&&b>=0&&b<o.length&&(_.preventDefault(),h(o[b]))};return window.addEventListener("keydown",E),()=>window.removeEventListener("keydown",E)},[d,o,b,m,h]),C.useEffect(()=>{var E;b>=0&&v.current&&((E=v.current.querySelectorAll(".breadcrumb-dropdown-item")[b])==null||E.scrollIntoView({block:"nearest"}))},[b]);const f=C.useCallback((E,_)=>{E.stopPropagation();const S=E.currentTarget;d&&d.dirPath===_?m():g(_,S)},[d,g,m]),x=C.useCallback((E,_)=>{E.stopPropagation();const S=E.currentTarget;d&&d.dirPath===_?m():g(_,S)},[d,g,m]);return n.jsxs("div",{className:"editor-breadcrumbs",children:[n.jsx("span",{style:{display:"inline-flex",alignItems:"center"},children:n.jsx("span",{className:`editor-breadcrumb-segment ${l.length===0?"active":""}`,onClick:E=>f(E,t),children:n.jsx("span",{children:t.split("/").pop()||t})})}),l.map((E,_)=>{const S=_===l.length-1,w=t+"/"+l.slice(0,_+1).join("/"),N=_===0?t:t+"/"+l.slice(0,_).join("/");return n.jsxs("span",{style:{display:"inline-flex",alignItems:"center"},children:[n.jsx("span",{className:"editor-breadcrumb-separator",children:n.jsx(Ne,{size:10})}),n.jsxs("span",{className:`editor-breadcrumb-segment ${S?"active":""} ${(d==null?void 0:d.dirPath)===(S?N:w)?"dropdown-open":""}`,onClick:L=>S?x(L,N):f(L,w),children:[S&&n.jsx(Gt,{name:E,type:"file",size:14}),n.jsx("span",{style:S?{fontWeight:500}:void 0,children:E})]})]},w)}),d&&n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"breadcrumb-dropdown-overlay",onClick:m}),n.jsx("div",{ref:k,className:"breadcrumb-dropdown",style:{left:Math.min(d.anchorRect.left,window.innerWidth-260),top:d.anchorRect.bottom+2},children:u?n.jsx("div",{className:"breadcrumb-dropdown-loading",children:n.jsx(we,{size:14,className:"animate-spin"})}):o.length===0?n.jsx("div",{className:"breadcrumb-dropdown-empty",children:"Empty"}):n.jsx("div",{className:"breadcrumb-dropdown-list",ref:v,children:o.map((E,_)=>{const S=E.path===e,w=_===b;return n.jsxs("div",{className:`breadcrumb-dropdown-item ${S?"current":""} ${w?"highlighted":""}`,onClick:()=>h(E),children:[E.type==="directory"?n.jsx(Ne,{size:12,style:{flexShrink:0,opacity:.5}}):n.jsx(Gt,{name:E.name,type:E.type,size:16}),n.jsx("span",{className:"breadcrumb-dropdown-item-name",children:E.name})]},E.path)})})})]})]})}function $S({path:e,content:t,language:r,onContentChange:s,onSave:i,minimap:l=!0,onCursorChange:d}){const{t:a}=ne(),{resolved:o}=Ke(),c=C.useRef(null),u=C.useRef(d);u.current=d;const p=o==="dark"?"vs-dark":"vs",b=C.useCallback((k,v)=>{c.current=k,k.addCommand(v.KeyMod.CtrlCmd|v.KeyCode.KeyS,()=>{i()});const g=()=>{const m=u.current;if(!m)return;const h=k.getPosition(),f=k.getSelection();if(!h)return;let x=0,E=0;if(f&&!f.isEmpty()){const _=k.getModel();_&&(x=_.getValueInRange(f).length,E=Math.abs(f.endLineNumber-f.startLineNumber)+1)}m(h.lineNumber,h.column,x,E)};k.onDidChangeCursorPosition(g),k.onDidChangeCursorSelection(g),g()},[i]),y=C.useCallback(k=>{k!==void 0&&s(k)},[s]);return C.useEffect(()=>{const k=c.current;if(!k)return;const v=k.getModel();v&&t.length>0&&v.getValue()!==t&&v.setValue(t)},[t]),n.jsx(Ex,{height:"100%",language:r,theme:p,defaultValue:t,onChange:y,onMount:b,loading:n.jsxs("div",{className:"flex items-center justify-center h-full gap-2",style:{color:"var(--color-text-tertiary)"},children:[n.jsx(we,{size:16,className:"animate-spin"}),n.jsx("span",{style:{fontSize:13},children:a("editor.loading")})]}),options:{fontSize:13,fontFamily:"'Menlo', 'Monaco', 'Consolas', 'Courier New', monospace",lineHeight:20,minimap:{enabled:l,maxColumn:80},scrollBeyondLastLine:!1,automaticLayout:!0,wordWrap:"off",tabSize:4,insertSpaces:!0,renderWhitespace:"selection",bracketPairColorization:{enabled:!0},padding:{top:8},smoothScrolling:!0,cursorBlinking:"smooth",cursorSmoothCaretAnimation:"on",fixedOverflowWidgets:!0}},e)}const Mu={image:"Image",svg:"SVG",markdown:"Markdown Preview",pdf:"PDF",binary:"Binary"};function Pu({language:e,cursorLine:t,cursorColumn:r,selectedCount:s,selectedLines:i,viewMode:l="editor",imageInfo:d,zoom:a,extraRight:o}){const{t:c}=ne();if(l==="image"||l==="svg")return n.jsxs("div",{className:"editor-statusbar",children:[n.jsx("div",{className:"editor-statusbar-left",children:d&&n.jsxs("span",{className:"editor-statusbar-item",children:[d.width," × ",d.height]})}),n.jsxs("div",{className:"editor-statusbar-right",children:[a!=null&&n.jsxs("span",{className:"editor-statusbar-item",children:[Math.round(a*100),"%"]}),n.jsx("span",{className:"editor-statusbar-item",children:Mu[l]}),o]})]});if(l!=="editor")return n.jsxs("div",{className:"editor-statusbar",children:[n.jsx("div",{className:"editor-statusbar-left"}),n.jsxs("div",{className:"editor-statusbar-right",children:[n.jsx("span",{className:"editor-statusbar-item",children:Mu[l]||l}),o]})]});const u=`Ln ${t}, Col ${r}`,p=s&&s>0?i&&i>1?` (${s} ${c("editor.selected")}, ${i} ${c("editor.lines")})`:` (${s} ${c("editor.selected")})`:"";return n.jsxs("div",{className:"editor-statusbar",children:[n.jsx("div",{className:"editor-statusbar-left",children:n.jsxs("span",{className:"editor-statusbar-item",children:[u,p]})}),n.jsxs("div",{className:"editor-statusbar-right",children:[n.jsx("span",{className:"editor-statusbar-item",children:e}),n.jsx("span",{className:"editor-statusbar-item",children:"UTF-8"}),n.jsx("span",{className:"editor-statusbar-item",children:"LF"}),n.jsx("span",{className:"editor-statusbar-item",children:"Spaces: 4"}),o]})]})}function Fu({actions:e}={}){const{t}=ne(),{tabs:r,activeTabId:s,rootPath:i,setActiveTab:l,closeTab:d,closeOtherTabs:a,closeAllTabs:o,closeTabsToRight:c,closeSavedTabs:u,reorderTabs:p,pinTab:b,unpinTab:y}=Ut(),[k,v]=C.useState(null),g=C.useRef(null),[m,h]=C.useState(null),f=C.useRef(-1),x=C.useRef(null),[E,_]=C.useState(!1),[S,w]=C.useState(!1),N=C.useMemo(()=>LS(r),[r]),L=C.useCallback(()=>{const M=x.current;M&&(_(M.scrollLeft>0),w(M.scrollLeft+M.clientWidth<M.scrollWidth-1))},[]);C.useEffect(()=>{const M=x.current;if(!M)return;L(),M.addEventListener("scroll",L,{passive:!0});const H=new ResizeObserver(L);return H.observe(M),()=>{M.removeEventListener("scroll",L),H.disconnect()}},[L,r.length]);const R=C.useCallback(()=>{var M;(M=x.current)==null||M.scrollBy({left:-150,behavior:"smooth"})},[]),j=C.useCallback(()=>{var M;(M=x.current)==null||M.scrollBy({left:150,behavior:"smooth"})},[]),$=C.useCallback((M,H)=>{M.preventDefault(),v({x:M.clientX,y:M.clientY,tabId:H})},[]),G=C.useCallback(()=>{v(null)},[]),F=C.useCallback((M,H)=>{M.button===1&&(M.preventDefault(),d(H))},[d]),W=C.useCallback((M,H)=>{f.current=H,M.dataTransfer.effectAllowed="move",M.currentTarget instanceof HTMLElement&&M.dataTransfer.setDragImage(M.currentTarget,0,0)},[]),V=C.useCallback((M,H)=>{M.preventDefault(),M.dataTransfer.dropEffect="move",h(H)},[]),q=C.useCallback((M,H)=>{M.preventDefault();const z=f.current;z>=0&&z!==H&&p(z,H),f.current=-1,h(null)},[p]),A=C.useCallback(()=>{f.current=-1,h(null)},[]),T=C.useCallback(M=>{const H=r.find(z=>z.id===M);H&&navigator.clipboard.writeText(H.path),G()},[r,G]),D=C.useCallback(M=>{const H=r.find(z=>z.id===M);if(H&&i){const z=H.path.startsWith(i+"/")?H.path.slice(i.length+1):H.path;navigator.clipboard.writeText(z)}else H&&navigator.clipboard.writeText(H.path);G()},[r,i,G]),I=C.useCallback(M=>{const H=r.find(z=>z.id===M);if(H){const{selectPath:z,toggleExpand:U,expandedPaths:O}=Ut.getState(),Y=H.path.split("/");for(let X=1;X<Y.length;X++){const Q=Y.slice(0,X).join("/");Q&&!O.has(Q)&&U(Q)}z(H.path)}G()},[r,G]);if(r.length===0)return null;const P=k?r.find(M=>M.id===k.tabId):null;return n.jsxs(n.Fragment,{children:[n.jsxs("div",{className:"editor-tabs-wrapper",children:[E&&n.jsx("button",{className:"editor-tabs-scroll-btn",onClick:R,children:n.jsx(tg,{size:14})}),n.jsx("div",{className:"editor-tabs",ref:x,children:r.map((M,H)=>n.jsxs("div",{className:`editor-tab${M.id===s?" active":""}${m===H?" drag-indicator":""}`,onClick:()=>l(M.id),onMouseDown:z=>F(z,M.id),onContextMenu:z=>$(z,M.id),title:M.path,draggable:!0,onDragStart:z=>W(z,H),onDragOver:z=>V(z,H),onDrop:z=>q(z,H),onDragEnd:A,children:[n.jsx(Gt,{name:M.name,type:"file",size:14}),n.jsx("span",{className:"editor-tab-name",children:M.name}),N.get(M.id)&&n.jsx("span",{className:"editor-tab-description",children:N.get(M.id)}),M.isPinned?M.isDirty?n.jsx("span",{className:"dirty-dot"}):n.jsx("span",{className:"pin-icon",children:n.jsx(Wf,{size:14})}):M.isDirty?n.jsx("span",{className:"dirty-dot"}):n.jsx("button",{className:"close-btn",onClick:z=>{z.stopPropagation(),d(M.id)},children:n.jsx(Te,{size:12})})]},M.id))}),S&&n.jsx("button",{className:"editor-tabs-scroll-btn",onClick:j,children:n.jsx(Ne,{size:14})}),e&&n.jsx("div",{className:"editor-tabs-actions",children:e})]}),k&&n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"editor-context-overlay",onClick:G}),n.jsxs("div",{ref:g,className:"editor-context-menu",style:{left:k.x,top:k.y},children:[P!=null&&P.isPinned?n.jsx("button",{onClick:()=>{y(k.tabId),G()},children:t("editor.unpin")}):n.jsx("button",{onClick:()=>{b(k.tabId),G()},children:t("editor.pin")}),n.jsx("div",{className:"editor-context-separator"}),n.jsx("button",{onClick:()=>T(k.tabId),children:t("editor.copyPath")}),n.jsx("button",{onClick:()=>D(k.tabId),children:t("editor.copyRelativePath")}),n.jsx("button",{onClick:()=>I(k.tabId),children:t("editor.revealInExplorer")}),n.jsx("div",{className:"editor-context-separator"}),n.jsx("button",{onClick:()=>{d(k.tabId),G()},children:t("editor.close")}),n.jsx("button",{onClick:()=>{a(k.tabId),G()},children:t("editor.closeOthers")}),n.jsx("button",{onClick:()=>{c(k.tabId),G()},children:t("editor.closeToRight")}),n.jsx("button",{onClick:()=>{u(),G()},children:t("editor.closeSaved")}),n.jsx("button",{onClick:()=>{o(),G()},children:t("editor.closeAll")})]})]})]})}const jS=_r;function fd(e){return`/api/v1/files/download?path=${encodeURIComponent(e)}`}function Bu({path:e,onImageInfo:t,onZoomChange:r}){const{t:s}=ne(),i=C.useRef(null),l=C.useRef(null),[d,a]=C.useState("fit"),[o,c]=C.useState(null),[u,p]=C.useState(!1),[b,y]=C.useState({x:0,y:0}),k=C.useRef({x:0,y:0,tx:0,ty:0}),v=C.useCallback(()=>{if(!i.current||!o)return 1;const R=i.current.clientWidth-40,j=i.current.clientHeight-80;return R<=0||j<=0?1:Math.min(R/o.w,j/o.h,1)},[o]),g=d==="fit"?v():d,m=C.useCallback(()=>{const R=l.current;if(!R)return;const j=R.naturalWidth,$=R.naturalHeight;c({w:j,h:$}),t==null||t({width:j,height:$})},[t]);C.useEffect(()=>{r==null||r(g)},[g,r]);const h=C.useCallback(R=>{!R.ctrlKey&&!R.metaKey||(R.preventDefault(),a(j=>{const $=j==="fit"?v():j,G=R.deltaY<0?.1:-.1;return Math.min(5,Math.max(.1,$+G))}))},[v]),f=C.useCallback(R=>{d!=="fit"&&(R.preventDefault(),p(!0),k.current={x:R.clientX,y:R.clientY,tx:b.x,ty:b.y})},[d,b]),x=C.useCallback(R=>{if(!u)return;const j=R.clientX-k.current.x,$=R.clientY-k.current.y;y({x:k.current.tx+j,y:k.current.ty+$})},[u]),E=C.useCallback(()=>{p(!1)},[]),_=()=>a(R=>Math.min(5,(R==="fit"?v():R)+.1)),S=()=>a(R=>Math.max(.1,(R==="fit"?v():R)-.1)),w=()=>{a("fit"),y({x:0,y:0})},N=()=>{a(1),y({x:0,y:0})},L=g>=3;return n.jsxs("div",{ref:i,className:"file-preview-image-container checkerboard",onWheel:h,onMouseDown:f,onMouseMove:x,onMouseUp:E,onMouseLeave:E,style:{cursor:d!=="fit"?u?"grabbing":"grab":"default"},children:[n.jsx("img",{ref:l,src:fd(e),alt:e,onLoad:m,className:L?"pixelated":"",style:{transform:`translate(${b.x}px, ${b.y}px) scale(${g})`,transformOrigin:"center center",maxWidth:"none",maxHeight:"none",userSelect:"none",pointerEvents:"none"},draggable:!1}),n.jsxs("div",{className:"image-zoom-toolbar",children:[n.jsx("button",{onClick:S,title:s("filePreview.zoomOut"),children:n.jsx(Cp,{size:16})}),n.jsxs("span",{className:"image-zoom-label",children:[Math.round(g*100),"%"]}),n.jsx("button",{onClick:_,title:s("filePreview.zoomIn"),children:n.jsx(ot,{size:16})}),n.jsx("button",{onClick:w,title:s("filePreview.fitToWindow"),children:n.jsx(ni,{size:16})}),n.jsx("button",{onClick:N,title:s("filePreview.actualSize"),children:n.jsx(lb,{size:16})})]})]})}function MS({className:e,children:t}){const r=Ke(l=>l.resolved),s=(e||"").match(/language-(\w+)/),i=String(t).replace(/\n$/,"");return s?n.jsx("div",{className:"relative group my-3",children:n.jsx(jS,{style:r==="dark"?Vr:Kr,language:s[1],PreTag:"div",customStyle:{margin:0,borderRadius:"8px",fontSize:"13px",lineHeight:"1.6"},codeTagProps:{style:{background:"transparent",textShadow:"none"}},children:i})}):n.jsx("code",{className:"bg-[var(--color-bg-tertiary)] px-1.5 py-0.5 rounded text-[13px]",children:t})}function PS({content:e}){return n.jsx("div",{className:"file-preview-markdown",children:n.jsx("div",{className:"file-preview-markdown-content",children:n.jsx(lr,{remarkPlugins:[cr],components:{code:MS},children:e})})})}function FS({path:e}){const{t}=ne();return n.jsx("iframe",{src:fd(e),className:"file-preview-pdf",title:t("filePreview.pdfPreview")})}function BS({path:e,name:t}){const{t:r}=ne();return n.jsxs("div",{className:"file-preview-binary",children:[n.jsx(mp,{size:48,className:"text-[var(--color-text-tertiary)]"}),n.jsx("div",{className:"mt-4 text-lg font-medium text-[var(--color-text-primary)]",children:t}),n.jsx("div",{className:"mt-2 text-sm text-[var(--color-text-secondary)]",children:r("filePreview.binaryNotSupported")}),n.jsxs("a",{href:fd(e),download:t,className:"mt-4 inline-flex items-center gap-2 px-4 py-2 rounded-lg bg-[var(--color-bg-tertiary)] text-[var(--color-text-primary)] hover:bg-[var(--color-bg-quaternary)] transition-colors text-sm",children:[n.jsx(pp,{size:16}),r("filePreview.download")]})]})}function US({path:e,name:t,content:r,viewMode:s,onImageInfo:i,onZoomChange:l}){switch(s){case"image":return n.jsx(Bu,{path:e,onImageInfo:i,onZoomChange:l});case"svg":return n.jsx(Bu,{path:e,onImageInfo:i,onZoomChange:l});case"markdown":return n.jsx(PS,{content:r});case"pdf":return n.jsx(FS,{path:e});case"binary":return n.jsx(BS,{path:e,name:t});default:return null}}function Zh({node:e,depth:t,isExpanded:r,isSelected:s,isMultiSelected:i,isRenaming:l,expandedPaths:d,selectedPath:a,selectedPaths:o,renamingPath:c,onToggleExpand:u,onSelect:p,onOpenFile:b,onConfirmRename:y,onCancelRename:k,onContextMenu:v,onDragStart:g,onDrop:m}){var D;const h=e.type==="directory",f=12+t*12,[x,E]=C.useState(e.name),_=C.useRef(null),[S,w]=C.useState(!1);C.useEffect(()=>{if(l&&_.current){E(e.name),_.current.focus();const I=e.name.lastIndexOf(".");!h&&I>0?_.current.setSelectionRange(0,I):_.current.select()}},[l,e.name,h]);const N=C.useCallback(I=>{l||(p(e.path,{ctrl:I.ctrlKey||I.metaKey,shift:I.shiftKey}),h?u(e.path):!I.ctrlKey&&!I.metaKey&&!I.shiftKey&&b(e.path,e.name))},[l,e.path,h,e.name,p,u,b]),L=C.useCallback(()=>{l||h||b(e.path,e.name)},[l,h,e.path,e.name,b]),R=C.useCallback(I=>{I.stopPropagation(),I.key==="Enter"?(I.preventDefault(),y(e.path,x)):I.key==="Escape"&&(I.preventDefault(),k())},[e.path,x,y,k]),j=C.useCallback(()=>{y(e.path,x)},[e.path,x,y]),$=C.useCallback(I=>{I.preventDefault(),v(I,e.path)},[v,e.path]),G=C.useCallback(I=>{const P=i?[...o]:[e.path];I.dataTransfer.effectAllowed="move",I.dataTransfer.setData("text/plain",JSON.stringify(P)),g(P)},[i,o,e.path,g]),F=C.useCallback(I=>{h&&(I.preventDefault(),I.dataTransfer.dropEffect="move",w(!0))},[h]),W=C.useCallback(()=>{w(!1)},[]),V=C.useCallback(I=>{I.preventDefault(),w(!1),h&&m(e.path)},[h,e.path,m]),q=s||i,A=12,T=12;return n.jsxs(n.Fragment,{children:[n.jsxs("div",{className:`file-tree-item ${q?"selected":""} ${S?"drag-over":""}`,onClick:N,onDoubleClick:L,onContextMenu:$,draggable:!l,onDragStart:G,onDragOver:F,onDragLeave:W,onDrop:V,"data-path":e.path,title:e.path,children:[Array.from({length:t},(I,P)=>n.jsx("span",{className:"file-tree-indent-guide",style:{left:T+P*A+6}},P)),n.jsx("span",{style:{width:f,flexShrink:0}}),h?e.isLoading?n.jsx(we,{size:16,className:"file-tree-chevron animate-spin"}):n.jsx(Ne,{size:16,className:`file-tree-chevron ${r?"expanded":""}`}):n.jsx(Gt,{name:e.name,type:e.type,isExpanded:r,size:16}),l?n.jsx("input",{ref:_,className:"file-tree-rename-input",value:x,onChange:I=>E(I.target.value),onKeyDown:R,onBlur:j,onClick:I=>I.stopPropagation()}):n.jsx("span",{className:"file-tree-item-name",children:e.name})]}),h&&r&&((D=e.children)==null?void 0:D.map(I=>n.jsx(Zh,{node:I,depth:t+1,isExpanded:d.has(I.path),isSelected:a===I.path,isMultiSelected:o.has(I.path),isRenaming:c===I.path,expandedPaths:d,selectedPath:a,selectedPaths:o,renamingPath:c,onToggleExpand:u,onSelect:p,onOpenFile:b,onConfirmRename:y,onCancelRename:k,onContextMenu:v,onDragStart:g,onDrop:m},I.path)))]})}function zS({initialPath:e,onSelect:t,onClose:r}){const{t:s}=ne(),[i,l]=C.useState(e||"/"),[d,a]=C.useState([]),[o,c]=C.useState(!0),[u,p]=C.useState(null),[b,y]=C.useState(!1),k=C.useRef(null),v=C.useCallback(async x=>{c(!0),p(null);try{const _=(await qt(x,1)).filter(S=>S.type==="directory").sort((S,w)=>S.name.localeCompare(w.name,void 0,{numeric:!0,sensitivity:"base"}));a(_),l(x)}catch{const E=x.replace(/\/[^/]+\/?$/,"")||"/";if(E!==x&&E.length>0)try{const S=(await qt(E,1)).filter(w=>w.type==="directory").sort((w,N)=>w.name.localeCompare(N.name,void 0,{numeric:!0,sensitivity:"base"}));a(S),l(E),c(!1);return}catch{}p(s("editor.loadError"))}finally{c(!1)}},[s]);C.useEffect(()=>{v(i)},[]);const g=C.useCallback(()=>{const x=i.replace(/\/[^/]+\/?$/,"")||"/";v(x)},[i,v]),m=C.useCallback(x=>{v(x)},[v]),h=C.useCallback(()=>{t(i)},[i,t]),f=C.useCallback(x=>{const E=x.trim();E&&v(E),y(!1)},[v]);return C.useEffect(()=>{b&&k.current&&(k.current.focus(),k.current.select())},[b]),C.useEffect(()=>{const x=E=>{E.key==="Escape"&&r()};return window.addEventListener("keydown",x),()=>window.removeEventListener("keydown",x)},[r]),n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"fixed inset-0 z-50 bg-black/40",onClick:r}),n.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4",onClick:x=>x.target===x.currentTarget&&r(),children:n.jsxs("div",{className:"bg-bg-primary border border-border-default rounded-xl shadow-xl flex flex-col",style:{width:"480px",maxWidth:"90vw",maxHeight:"70vh"},children:[n.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-b border-border-muted/30",children:[n.jsx("span",{className:"text-sm font-medium text-text-primary",children:s("editor.openFolder")}),n.jsx("button",{className:"text-text-tertiary hover:text-text-primary",onClick:r,children:n.jsx(Te,{size:16})})]}),n.jsxs("div",{className:"flex items-center gap-1.5 px-3 py-2 border-b border-border-muted/30",children:[n.jsx("button",{className:"p-1 rounded hover:bg-bg-hover text-text-tertiary hover:text-text-primary flex-shrink-0",onClick:g,title:s("editor.parentFolder"),children:n.jsx(Es,{size:14})}),b?n.jsx("input",{ref:k,type:"text",defaultValue:i,className:"flex-1 px-1.5 py-0.5 text-xs font-mono bg-bg-secondary border border-accent-brand rounded outline-none",onKeyDown:x=>{x.key==="Enter"&&f(x.target.value),x.key==="Escape"&&y(!1)},onBlur:x=>f(x.target.value)}):n.jsx("button",{className:"flex-1 text-left text-xs font-mono text-text-secondary truncate px-1.5 py-0.5 rounded hover:bg-bg-hover",onClick:()=>y(!0),title:i,children:i})]}),n.jsxs("div",{className:"flex-1 overflow-y-auto min-h-[200px]",children:[o&&n.jsx("div",{className:"flex items-center justify-center py-8 text-text-tertiary",children:n.jsx(we,{size:16,className:"animate-spin"})}),u&&n.jsx("div",{className:"px-4 py-3 text-xs text-accent-red",children:u}),!o&&!u&&d.length===0&&n.jsx("div",{className:"px-4 py-8 text-center text-xs text-text-tertiary",children:s("editor.emptyFolder")}),!o&&!u&&d.map(x=>n.jsxs("button",{className:"flex items-center gap-2 w-full px-4 py-1.5 text-left text-sm text-text-primary hover:bg-bg-hover/50 cursor-pointer",onClick:()=>m(x.path),children:[n.jsx(Xg,{size:14,className:"text-text-tertiary flex-shrink-0"}),n.jsx("span",{className:"truncate",children:x.name}),n.jsx(Ne,{size:12,className:"text-text-tertiary flex-shrink-0 ml-auto"})]},x.path))]}),n.jsxs("div",{className:"flex items-center justify-end gap-2 px-4 py-3 border-t border-border-muted/30",children:[n.jsx("button",{className:"px-3 py-1.5 text-xs rounded-md text-text-secondary hover:bg-bg-hover border border-border-muted",onClick:r,children:s("editor.close")}),n.jsx("button",{className:"px-3 py-1.5 text-xs rounded-md bg-accent-brand text-white hover:opacity-90",onClick:h,children:s("editor.openFolder")})]})]})})]})}function Uu({onMenuClick:e}){var ie,Oe,_e;const{t}=ne(),r=Wt(se=>se.info),{rootPath:s,tree:i,treeLoading:l,treeError:d,expandedPaths:a,selectedPath:o,selectedPaths:c,renamingPath:u,setRootPath:p,toggleExpand:b,selectPath:y,openFile:k,refreshTree:v,collapseAll:g,createNewFile:m,createNewFolder:h,startRename:f,startCreateFile:x,startCreateFolder:E,confirmRename:_,cancelRename:S,deleteSelected:w,moveToDirectory:N}=Ut(),[L,R]=C.useState(!1),[j,$]=C.useState(!1),[G,F]=C.useState(!1),W=C.useRef(null),[V,q]=C.useState(null),A=C.useRef([]);C.useEffect(()=>{const se=Sn().has("path");r!=null&&r.cwd&&!s&&!se?p(r.cwd):s&&!i&&!l&&!d&&p(s)},[r==null?void 0:r.cwd,s,i,l,d,p]);const T=C.useCallback(se=>{F(!1),p(se)},[p]),D=C.useCallback((se,ce)=>{k(se,ce)},[k]),I=C.useCallback((se,ce)=>{_(se,ce)},[_]),P=C.useCallback((se,ce)=>{se.preventDefault(),c.has(ce)||y(ce),q({x:se.clientX,y:se.clientY,path:ce})},[c,y]),M=C.useCallback(()=>q(null),[]),H=C.useCallback(()=>{V&&(f(V.path),q(null))},[V,f]),z=C.useCallback(()=>{q(null),w()},[w]),U=C.useCallback((se,ce)=>{if(!se)return null;if(se.path===ce)return se;if(se.children)for(const Ee of se.children){const xe=U(Ee,ce);if(xe)return xe}return null},[]),O=V?((ie=U(i,V.path))==null?void 0:ie.type)==="directory":!1,Y=C.useCallback(()=>{if(V){const se=U(i,V.path),ce=(se==null?void 0:se.type)==="directory"?V.path:V.path.substring(0,V.path.lastIndexOf("/"));if(ce){a.has(ce)||b(ce);const Ee=ce+"/__new_file__";x(Ee)}q(null)}},[V,i,a,b,x,U]),X=C.useCallback(()=>{if(V){const se=U(i,V.path),ce=(se==null?void 0:se.type)==="directory"?V.path:V.path.substring(0,V.path.lastIndexOf("/"));if(ce){a.has(ce)||b(ce);const Ee=ce+"/__new_folder__";E(Ee)}q(null)}},[V,i,a,b,E,U]),Q=C.useCallback(()=>{V&&(navigator.clipboard.writeText(V.path).catch(()=>{}),q(null))},[V]),J=C.useCallback(()=>{if(V&&s){const se=V.path.startsWith(s+"/")?V.path.slice(s.length+1):V.path;navigator.clipboard.writeText(se).catch(()=>{}),q(null)}},[V,s]),re=C.useCallback(se=>{A.current=se},[]),ue=C.useCallback(se=>{A.current.length>0&&(N(A.current,se),A.current=[])},[N]),de=C.useCallback(se=>{var xe,Ze,ee,oe;if(u||!i)return;const ce=gd(i,a);if(ce.length===0)return;const Ee=o?ce.indexOf(o):-1;switch(se.key){case"ArrowDown":{se.preventDefault();const fe=Ee<ce.length-1?Ee+1:0;y(ce[fe],{shift:se.shiftKey}),(Ze=(xe=W.current)==null?void 0:xe.querySelector(`[data-path="${CSS.escape(ce[fe])}"]`))==null||Ze.scrollIntoView({block:"nearest"});break}case"ArrowUp":{se.preventDefault();const fe=Ee>0?Ee-1:ce.length-1;y(ce[fe],{shift:se.shiftKey}),(oe=(ee=W.current)==null?void 0:ee.querySelector(`[data-path="${CSS.escape(ce[fe])}"]`))==null||oe.scrollIntoView({block:"nearest"});break}case"ArrowRight":{se.preventDefault(),o&&!a.has(o)&&b(o);break}case"ArrowLeft":{se.preventDefault(),o&&a.has(o)&&b(o);break}case"Enter":{se.preventDefault(),o&&f(o);break}case"Delete":case"Backspace":{se.preventDefault(),c.size>0&&w();break}case" ":{if(se.preventDefault(),o){const fe=Je=>{if(!Je)return null;if(Je.path===o)return Je;if(Je.children)for(const Qe of Je.children){const ht=fe(Qe);if(ht)return ht}return null},$e=fe(i);($e==null?void 0:$e.type)==="directory"?b(o):$e&&k($e.path,$e.name)}break}}},[i,a,o,c,u,y,b,f,k,w]),me=(i==null?void 0:i.name)||(s==null?void 0:s.split("/").pop())||"WORKSPACE";return n.jsxs("div",{className:"file-tree",ref:W,tabIndex:0,onKeyDown:de,onClick:()=>{var se;return(se=W.current)==null?void 0:se.focus()},children:[n.jsxs("div",{className:"file-tree-title-bar",children:[e&&n.jsx("button",{className:"file-tree-title-menu",onClick:e,title:t("editor.toggleSidebar"),children:n.jsx(si,{size:16})}),n.jsx("span",{className:"file-tree-title-text",children:t("editor.explorer")})]}),n.jsxs("div",{className:"file-tree-section-header",onClick:()=>R(!L),onMouseEnter:()=>$(!0),onMouseLeave:()=>$(!1),children:[L?n.jsx(Ne,{size:12,style:{flexShrink:0}}):n.jsx(nt,{size:12,style:{flexShrink:0}}),n.jsx("span",{className:"file-tree-section-name",children:me.toUpperCase()}),j&&!L&&n.jsxs("div",{className:"file-tree-section-actions",onClick:se=>se.stopPropagation(),children:[n.jsx("button",{className:"file-tree-section-action",onClick:m,title:t("editor.newFile"),children:n.jsx(Bg,{size:14})}),n.jsx("button",{className:"file-tree-section-action",onClick:h,title:t("editor.newFolder"),children:n.jsx(Kg,{size:14})}),n.jsx("button",{className:"file-tree-section-action",onClick:()=>F(!0),title:t("editor.openFolder"),children:n.jsx(ti,{size:14})}),n.jsx("button",{className:"file-tree-section-action",onClick:v,title:t("editor.refresh"),children:n.jsx(Ve,{size:14})}),n.jsx("button",{className:"file-tree-section-action",onClick:g,title:t("editor.collapseAll"),children:n.jsx(Ng,{size:14})})]})]}),G&&n.jsx(zS,{initialPath:s||(r==null?void 0:r.cwd)||"/",onSelect:T,onClose:()=>F(!1)}),!L&&n.jsxs("div",{className:"file-tree-content",children:[l&&!i&&n.jsx("div",{className:"file-tree-loading",children:n.jsx(we,{size:16,className:"animate-spin"})}),!l&&!i&&d&&s&&n.jsxs("div",{className:"file-tree-empty",children:[n.jsx("span",{children:t("editor.loadError")}),n.jsxs("button",{className:"file-tree-retry-btn",onClick:()=>p(s),children:[n.jsx(Ve,{size:12}),t("editor.refresh")]})]}),(Oe=i==null?void 0:i.children)==null?void 0:Oe.map(se=>n.jsx(Zh,{node:se,depth:0,isExpanded:a.has(se.path),isSelected:o===se.path,isMultiSelected:c.has(se.path),isRenaming:u===se.path,expandedPaths:a,selectedPath:o,selectedPaths:c,renamingPath:u,onToggleExpand:b,onSelect:y,onOpenFile:D,onConfirmRename:I,onCancelRename:S,onContextMenu:P,onDragStart:re,onDrop:ue},se.path)),((_e=i==null?void 0:i.children)==null?void 0:_e.length)===0&&n.jsx("div",{className:"file-tree-empty",children:t("editor.emptyFolder")})]}),V&&n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"editor-context-overlay",onClick:M}),n.jsxs("div",{className:"editor-context-menu",style:{left:V.x,top:V.y},children:[O&&n.jsxs(n.Fragment,{children:[n.jsx("button",{onClick:Y,children:t("editor.newFile")}),n.jsx("button",{onClick:X,children:t("editor.newFolder")}),n.jsx("div",{className:"editor-context-separator"})]}),n.jsx("button",{onClick:Q,children:t("editor.copyPath")}),n.jsx("button",{onClick:J,children:t("editor.copyRelativePath")}),n.jsx("div",{className:"editor-context-separator"}),c.size<=1&&n.jsx("button",{onClick:H,children:t("editor.rename")}),n.jsx("button",{className:"danger",onClick:z,children:c.size>1?`${t("editor.delete")} (${c.size})`:t("editor.delete")})]})]})]})}function HS(e,t){const r=e.toLowerCase(),s=t.toLowerCase();let i=0,l=0,d=-1;for(let a=0;a<s.length&&i<r.length;a++)s[a]===r[i]&&(l+=a===d+1?2:1,(a===0||s[a-1]==="/"||s[a-1]===".")&&(l+=3),d=a,i++);return{match:i===r.length,score:l}}const zu=20,GS=3;function WS({isOpen:e,onClose:t,onSelect:r,rootPath:s}){const{t:i}=ne(),[l,d]=C.useState(""),[a,o]=C.useState(0),[c,u]=C.useState([]),[p,b]=C.useState(!1),y=C.useRef(null),k=C.useRef(null),v=C.useRef(""),g=C.useRef([]),m=C.useCallback(async(x,E,_)=>{if(E>GS)return[];try{const S=await qt(x),w=[];for(const N of S){const L=_?`${_}/${N.name}`:N.name;if(N.type==="file"&&!Yh(N.path))w.push({name:N.name,path:N.path,relativePath:L});else if(N.type==="directory"&&!N.name.startsWith(".")&&N.name!=="node_modules"){const R=await m(N.path,E+1,L);w.push(...R)}}return w}catch{return[]}},[]);C.useEffect(()=>{if(e){if(d(""),o(0),setTimeout(()=>{var x;return(x=y.current)==null?void 0:x.focus()},0),v.current===s&&g.current.length>0){u(g.current);return}b(!0),m(s,0,"").then(x=>{v.current=s,g.current=x,u(x),b(!1)})}},[e,s,m]);const h=C.useMemo(()=>{if(!l.trim())return c.slice(0,zu);const x=[];for(const E of c){const _=HS(l,E.relativePath);_.match&&x.push({entry:E,score:_.score})}return x.sort((E,_)=>_.score-E.score),x.slice(0,zu).map(E=>E.entry)},[c,l]);C.useEffect(()=>{o(0)},[h.length,l]);const f=C.useCallback(x=>{switch(x.key){case"ArrowDown":x.preventDefault(),o(E=>(E+1)%Math.max(h.length,1));break;case"ArrowUp":x.preventDefault(),o(E=>(E-1+h.length)%Math.max(h.length,1));break;case"Enter":x.preventDefault(),h[a]&&r(h[a].path);break;case"Escape":x.preventDefault(),t();break}},[h,a,r,t]);return C.useEffect(()=>{var E;const x=(E=k.current)==null?void 0:E.children[a];x==null||x.scrollIntoView({block:"nearest"})},[a]),e?n.jsx("div",{className:"quick-open-overlay",onClick:t,children:n.jsxs("div",{className:"quick-open-dialog",onClick:x=>x.stopPropagation(),onKeyDown:f,children:[n.jsx("input",{ref:y,className:"quick-open-input",type:"text",value:l,onChange:x=>d(x.target.value),placeholder:i("editor.quickOpenPlaceholder")}),n.jsx("div",{className:"quick-open-list",ref:k,children:p?n.jsx("div",{className:"quick-open-empty",children:i("editor.quickOpenLoading")}):h.length===0?n.jsx("div",{className:"quick-open-empty",children:(l.trim(),i("editor.quickOpenEmpty"))}):h.map((x,E)=>n.jsxs("div",{className:`quick-open-item${E===a?" active":""}`,onClick:()=>r(x.path),onMouseEnter:()=>o(E),children:[n.jsx(Gt,{name:x.name,type:"file",size:14}),n.jsx("span",{className:"quick-open-item-name",children:x.name}),n.jsx("span",{className:"quick-open-item-path",children:x.relativePath})]},x.path))})]})}):null}const qS=1e3;function VS({onMenuClick:e}){const{t}=ne(),{tabs:r,activeTabId:s,splitRatio:i,setSplitRatio:l,updateTabContent:d,saveTab:a,closeTab:o,recentFiles:c}=Ut(),{setRootPath:u,openFile:p,rootPath:b,revealInTree:y}=Ut(),[k,v]=C.useState(!1),g=typeof navigator<"u"&&navigator.platform.includes("Mac"),[m,h]=C.useState(()=>window.innerWidth<768),[f,x]=C.useState(!1),E=C.useRef("");C.useEffect(()=>{const z=async()=>{if(li()!=="editor")return;const Y=Sn().get("path");if(!Y||Y===E.current)return;if(E.current=Y,await kS(Y)==="directory")await u(Y);else{const Q=Y.substring(0,Y.lastIndexOf("/"));Q&&await u(Q),p(Y)}};z();const U=()=>z();return window.addEventListener("hashchange",U),()=>window.removeEventListener("hashchange",U)},[]),C.useEffect(()=>{const z=window.matchMedia("(min-width: 768px)"),U=O=>{h(!O.matches),O.matches&&x(!1)};return z.addEventListener("change",U),()=>z.removeEventListener("change",U)},[]);const _=Ut(z=>z.tabs.length);C.useEffect(()=>{m&&s&&x(!0)},[m,s,_]);const S=r.find(z=>z.id===s)||null,w=C.useRef(),N=C.useCallback(z=>{if(!s)return;d(s,z),clearTimeout(w.current);const U=s;w.current=setTimeout(()=>{const O=Ut.getState().tabs.find(Y=>Y.id===U);!O||!O.isDirty||a(U)},qS)},[s,d,a]);C.useEffect(()=>()=>clearTimeout(w.current),[]),C.useEffect(()=>{const z=U=>{const O=U.metaKey||U.ctrlKey;O&&U.key==="p"&&!U.shiftKey&&(U.preventDefault(),v(!0)),O&&U.key==="w"&&!U.shiftKey&&(U.preventDefault(),s&&o(s))};return window.addEventListener("keydown",z),()=>window.removeEventListener("keydown",z)},[s,o]);const L=C.useCallback(()=>{clearTimeout(w.current),s&&a(s)},[s,a]),R=C.useCallback(()=>{x(!1)},[]),[j,$]=C.useState({line:1,col:1,selectedChars:0,selectedLines:0}),G=C.useCallback((z,U,O,Y)=>{$({line:z,col:U,selectedChars:O,selectedLines:Y})},[]),[F,W]=C.useState(null),[V,q]=C.useState(1),[A,T]=C.useState(new Set),D=(S==null?void 0:S.viewMode)==="markdown"&&A.has(S.id),I=C.useCallback(()=>{s&&T(z=>{const U=new Set(z);return U.has(s)?U.delete(s):U.add(s),U})},[s]),P=(S==null?void 0:S.viewMode)==="markdown"?D?n.jsx("button",{className:"editor-action-btn",onClick:I,title:t("editor.preview"),children:n.jsx(Js,{size:16})}):n.jsx("button",{className:"editor-action-btn",onClick:I,title:t("editor.source"),children:n.jsx(up,{size:16})}):null,M=S?S.viewMode==="editor"||D?n.jsx("div",{className:"editor-container",children:n.jsx($S,{path:S.path,content:S.content,language:S.language,onContentChange:N,onSave:L,minimap:!m,onCursorChange:G})}):n.jsx(US,{path:S.path,name:S.name,content:S.content,viewMode:S.viewMode,onImageInfo:W,onZoomChange:q}):n.jsxs("div",{className:"editor-empty",children:[n.jsx(Mg,{size:48,strokeWidth:1,style:{opacity:.12}}),n.jsx("span",{className:"editor-empty-title",children:t("editor.noFile")}),n.jsx("div",{className:"editor-empty-shortcuts",children:n.jsxs("div",{className:"editor-empty-hint",children:[n.jsxs("kbd",{children:[g?"⌘":"Ctrl","+P"]}),n.jsx("span",{children:t("editor.quickOpen")})]})}),c.length>0&&n.jsxs("div",{className:"editor-empty-recent",children:[n.jsx("span",{className:"editor-empty-recent-title",children:t("editor.recentFiles")}),c.slice(0,8).map(z=>n.jsxs("button",{className:"editor-empty-recent-item",onClick:()=>p(z.path),title:z.path,children:[n.jsx(Gt,{name:z.name,type:"file",size:14}),n.jsx("span",{className:"editor-empty-recent-name",children:z.name}),n.jsx("span",{className:"editor-empty-recent-path",children:z.path.split("/").slice(-2,-1)[0]})]},z.path))]})]}),H=k&&b&&n.jsx(WS,{isOpen:k,onClose:()=>v(!1),onSelect:z=>{p(z),v(!1)},rootPath:b});return m?n.jsxs("div",{className:"editor-view",children:[H,n.jsx("div",{className:"editor-sidebar editor-sidebar-mobile",children:n.jsx(Uu,{onMenuClick:e})}),n.jsx("div",{className:`editor-mobile-panel ${f?"open":""}`,children:n.jsxs("div",{className:"editor-main",children:[n.jsxs("div",{className:"editor-mobile-header",children:[n.jsx("button",{className:"editor-mobile-back",onClick:R,children:n.jsx(dr,{size:18})}),n.jsx("div",{className:"editor-mobile-tabs-wrap",children:n.jsx(Fu,{actions:P})})]}),M,S&&n.jsx(Pu,{language:S.language,cursorLine:j.line,cursorColumn:j.col,selectedCount:j.selectedChars,selectedLines:j.selectedLines,viewMode:D?"editor":S.viewMode,imageInfo:F,zoom:V})]})})]}):n.jsxs("div",{className:"editor-view",children:[H,n.jsxs(On,{direction:"horizontal",ratio:i,onRatioChange:l,children:[n.jsx("div",{className:"editor-sidebar",children:n.jsx(Uu,{onMenuClick:e})}),n.jsxs("div",{className:"editor-main",children:[n.jsx(Fu,{actions:P}),S&&b&&n.jsx(OS,{filePath:S.path,rootPath:b,onSegmentClick:y,onOpenFile:p}),M,S&&n.jsx(Pu,{language:S.language,cursorLine:j.line,cursorColumn:j.col,selectedCount:j.selectedChars,selectedLines:j.selectedLines,viewMode:D?"editor":S.viewMode,imageInfo:F,zoom:V})]})]})]})}class Be extends C.Component{constructor(r){super(r);be(this,"handleRetry",()=>{this.setState({hasError:!1,error:null})});this.state={hasError:!1,error:null}}static getDerivedStateFromError(r){return{hasError:!0,error:r}}componentDidCatch(r,s){console.error(`[ErrorBoundary${this.props.viewName?` - ${this.props.viewName}`:""}]`,r,s)}render(){var r;return this.state.hasError?n.jsx("div",{className:"flex-1 flex items-center justify-center p-6",children:n.jsxs("div",{className:"text-center max-w-md",children:[n.jsx("div",{className:"text-[48px] mb-4 text-text-tertiary",children:"!"}),n.jsx("h2",{className:"text-text-primary text-[16px] font-semibold mb-2",children:this.props.errorTitle||"Something went wrong"}),n.jsx("p",{className:"text-text-tertiary text-[13px] mb-4 break-words",children:((r=this.state.error)==null?void 0:r.message)||"An unexpected error occurred"}),n.jsx("button",{onClick:this.handleRetry,className:"px-6 py-2 bg-accent-brand text-bg-primary rounded-lg text-[13px] font-medium hover:opacity-90 active:scale-95 transition-all",children:this.props.retryLabel||"Retry"})]})}):this.props.children}}function KS(e){return!Number.isFinite(e)||e<0?"0":e<1e3?String(e):e<1e6?`${(e/1e3).toFixed(1)}k`:`${(e/1e6).toFixed(1)}M`}function YS(e,t,r,s){const i=Math.max(1,Math.round(e/1e3)),l=s(t===1?"goal.recap.stats.turn":"goal.recap.stats.turns"),d=s(r===1?"goal.recap.stats.token":"goal.recap.stats.tokens");return`${i}s · ${t} ${l} · ${KS(r)} ${d}`}function XS(){const e=Me(l=>l.goalRecap),t=Me(l=>l.dismissGoalRecap),{t:r}=ne();C.useEffect(()=>{if(!e)return;const l=d=>{d.key==="Escape"&&(d.preventDefault(),t())};return document.addEventListener("keydown",l),()=>document.removeEventListener("keydown",l)},[e,t]);const s=C.useCallback(()=>t(),[t]),i=C.useMemo(()=>ZS(e,r),[e,r]);return e?n.jsxs("div",{className:"fixed inset-0 z-[200] flex items-center justify-center",children:[n.jsx("div",{className:"absolute inset-0 bg-black/30",onClick:s}),n.jsxs("div",{role:"dialog","aria-modal":"true","aria-labelledby":"goal-recap-title",className:"relative bg-bg-card border border-border-default rounded-xl shadow-2xl w-full max-w-[480px] mx-4 overflow-hidden",children:[n.jsx("div",{className:"px-5 pt-5 pb-4 flex flex-col gap-3",children:i}),n.jsxs("div",{className:"px-5 pb-4 pt-2 border-t border-border-default text-text-tertiary text-[12px]",children:[n.jsx("span",{className:"text-text-secondary",children:r("goal.recap.footer.setAnother")}),n.jsx("span",{children:r("goal.recap.footer.toSetAnother")}),n.jsx("span",{className:"text-text-secondary",children:"Esc"}),n.jsxs("span",{children:[" ",r("goal.recap.footer.escDismiss")]})]})]})]}):null}function ZS(e,t){if(!e)return null;if(e.active)return n.jsxs(n.Fragment,{children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(Ns,{size:18,className:"text-accent-brand"}),n.jsx("h3",{id:"goal-recap-title",className:"text-text-primary text-[15px] font-semibold",children:t("goal.recap.active")})]}),n.jsxs("div",{className:"text-text-secondary text-[13px] break-words leading-relaxed",children:[t("goal.progress.condition"),": ",e.active.condition]})]});if(e.latest){const{ok:r,reason:s,condition:i,durationMs:l,turnCount:d,tokenDelta:a}=e.latest,o=r?Rn:ar,c=r?"text-accent-green":"text-accent-red",u=t(r?"goal.recap.achieved":"goal.recap.impossible"),p=YS(l,d,a,t);return n.jsxs(n.Fragment,{children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(o,{size:18,className:c}),n.jsx("h3",{id:"goal-recap-title",className:`text-[15px] font-semibold ${c}`,children:u})]}),n.jsx("div",{className:"text-text-secondary text-[12px]",children:p}),n.jsxs("div",{className:"text-text-secondary text-[13px] break-words leading-relaxed mt-2",children:[t("goal.progress.condition"),": ",i]}),s?n.jsxs("div",{className:"text-text-tertiary text-[12px] break-words leading-relaxed",children:[t("goal.progress.reason"),": ",s]}):null]})}return n.jsxs(n.Fragment,{children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(Ns,{size:18,className:"text-text-tertiary"}),n.jsx("h3",{id:"goal-recap-title",className:"text-text-primary text-[15px] font-semibold",children:t("goal.recap.empty.title")})]}),n.jsx("div",{className:"text-text-secondary text-[13px] leading-relaxed",children:t("goal.recap.empty.hint")}),n.jsx("div",{className:"text-text-tertiary text-[12px] leading-relaxed",children:t("goal.recap.empty.example")})]})}function JS(e,t){const s=Date.now()-e,i=Math.floor(s/6e4),l=Math.floor(s/36e5),d=Math.floor(s/864e5);return t==="zh"?i<1?"刚刚":i<60?`${i} 分钟前`:l<24?`${l} 小时前`:d<30?`${d} 天前`:new Date(e).toLocaleDateString("zh-CN"):i<1?"Just now":i<60?`${i}m ago`:l<24?`${l}h ago`:d<30?`${d}d ago`:new Date(e).toLocaleDateString("en-US")}function QS({isOpen:e,onClose:t,onSwitchSession:r}){const{t:s,resolved:i}=ne(),[l,d]=C.useState([]),[a,o]=C.useState(!0),[c,u]=C.useState(null),[p,b]=C.useState(null),[y,k]=C.useState(null),[v,g]=C.useState(""),m=C.useRef(null),[h,f]=C.useState(null),x=C.useCallback(async()=>{o(!0),u(null);try{const R=await fetch("/api/v1/sessions",{headers:ae()});if(!R.ok)throw new Error(`HTTP ${R.status}`);const j=await R.json(),$=j.data??j;d($.sessions||[])}catch(R){u(R.message||"Unknown error")}finally{o(!1)}},[]);C.useEffect(()=>{e&&x()},[e,x]);const E=C.useCallback(async R=>{var j;try{const $=await fetch(`/api/v1/sessions/${encodeURIComponent(R.id)}`,{method:"DELETE",headers:ae()});if(!$.ok){const G=await $.json().catch(()=>({}));throw new Error(((j=G.error)==null?void 0:j.message)||G.error||`HTTP ${$.status}`)}d(G=>G.filter(F=>F.id!==R.id))}catch($){console.error("[history] Delete failed:",$)}finally{f(null)}},[]),_=C.useCallback(async(R,j)=>{var G;const $=j.trim();if($)try{const F=await fetch(`/api/v1/sessions/${encodeURIComponent(R.id)}/rename`,{method:"POST",headers:ae({"Content-Type":"application/json"}),body:JSON.stringify({name:$})});if(!F.ok){const W=await F.json().catch(()=>({}));throw new Error(((G=W.error)==null?void 0:G.message)||W.error||`HTTP ${F.status}`)}d(W=>W.map(V=>V.id===R.id?{...V,name:$}:V))}catch(F){console.error("[history] Rename failed:",F)}finally{k(null),g("")}},[]),S=C.useCallback((R,j)=>{j.stopPropagation(),k(R),g(R.name),setTimeout(()=>{var $;return($=m.current)==null?void 0:$.focus()},50)},[]),w=C.useCallback((R,j)=>{j.stopPropagation(),!R.isCurrent&&f(R)},[]),N=C.useCallback(async R=>{if(!(R.isCurrent||p)){b(R.id);try{await(r==null?void 0:r(R.id)),t()}finally{b(null)}}},[p,r,t]),L=()=>a?n.jsx("div",{className:"history-loading",children:n.jsx(pt,{size:"small",text:s("history.loading")})}):c?n.jsxs("div",{className:"history-error",children:[n.jsx("p",{className:"history-error-text",children:s("history.loadError")}),n.jsx("button",{className:"history-retry-btn",onClick:x,children:s("history.retry")})]}):l.length===0?n.jsxs("div",{className:"history-empty",children:[n.jsx(ur,{size:48,className:"text-text-tertiary"}),n.jsx("p",{className:"history-empty-title",children:s("history.noData")}),n.jsx("p",{className:"history-empty-hint",children:s("history.noDataHint")})]}):n.jsx("div",{className:"history-list",children:l.map((R,j)=>{const $=En(R.updatedAt),G=j>0?En(l[j-1].updatedAt):null,F=$!==G;return n.jsxs("div",{children:[F&&n.jsx(Nt,{label:Eh(R.updatedAt,i)}),n.jsxs("div",{className:`history-session-item${R.isCurrent?" current":""}${!R.isCurrent&&!p?" clickable":""}`,onClick:()=>!R.isCurrent&&!p&&N(R),children:[n.jsxs("div",{className:"history-session-info",children:[n.jsx("p",{className:"history-session-name",children:R.name}),n.jsxs("div",{className:"history-session-meta",children:[R.isCurrent&&n.jsx("span",{className:"history-session-badge",children:s("history.current")}),n.jsx("span",{children:s("history.messages").replace("{count}",String(R.messageCount))}),n.jsx("span",{children:JS(R.updatedAt,i)})]})]}),n.jsxs("div",{className:"history-session-actions",children:[p===R.id&&n.jsx("div",{className:"history-session-switching",children:n.jsx("div",{className:"history-session-spinner"})}),p!==R.id&&n.jsxs(n.Fragment,{children:[n.jsx("button",{className:"history-action-btn",title:s("history.rename"),onClick:W=>S(R,W),children:n.jsx(zf,{size:14})}),!R.isCurrent&&n.jsx("button",{className:"history-action-btn danger",title:s("history.delete"),onClick:W=>w(R,W),children:n.jsx(hr,{size:14})})]})]})]})]},R.id)})});return n.jsxs(n.Fragment,{children:[n.jsx("div",{className:`history-drawer-overlay ${e?"open":""}`,onClick:t}),n.jsxs("div",{className:`history-drawer ${e?"open":""}`,children:[n.jsxs("div",{className:"history-drawer-header",children:[n.jsxs("div",{children:[n.jsx("h2",{className:"history-drawer-title",children:s("history.title")}),n.jsx("p",{className:"history-drawer-subtitle",children:s("history.description")})]}),n.jsx("button",{onClick:t,className:"history-drawer-close",children:n.jsx(Te,{size:16})})]}),n.jsx("div",{className:"history-content",children:L()})]}),y&&n.jsx("div",{className:"history-rename-overlay",onClick:()=>k(null),children:n.jsxs("div",{className:"history-rename-dialog",onClick:R=>R.stopPropagation(),children:[n.jsx("h3",{children:s("history.renameTitle")}),n.jsx("input",{ref:m,className:"history-rename-input",value:v,onChange:R=>g(R.target.value),placeholder:s("history.renamePlaceholder"),onKeyDown:R=>{R.key==="Enter"&&v.trim()&&_(y,v),R.key==="Escape"&&k(null)}}),n.jsxs("div",{className:"history-rename-actions",children:[n.jsx("button",{className:"history-rename-cancel",onClick:()=>k(null),children:s("history.renameCancel")}),n.jsx("button",{className:"history-rename-ok",disabled:!v.trim(),onClick:()=>_(y,v),children:s("history.renameOk")})]})]})}),h&&n.jsx("div",{className:"history-delete-overlay",onClick:()=>f(null),children:n.jsxs("div",{className:"history-delete-dialog",onClick:R=>R.stopPropagation(),children:[n.jsx("p",{children:s("history.deleteConfirm")}),n.jsxs("div",{className:"history-delete-actions",children:[n.jsx("button",{className:"history-delete-cancel",onClick:()=>f(null),children:s("history.deleteCancel")}),n.jsx("button",{className:"history-delete-ok",onClick:()=>E(h),children:s("history.deleteOk")})]})]})})]})}function ln(e,t){return`${e}@${t}`}async function Pt(e,t){return ve(e,{method:"POST",headers:{"Content-Type":"application/json",...ae()},body:t?JSON.stringify(t):void 0})}async function ek(e){return ve(e,{method:"DELETE",headers:ae()})}async function Hu(e){return ve(e,{method:"GET",headers:ae()})}const tk=Ae((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 Hu("/api/v1/plugins");if(!r.ok)throw new Error(`HTTP ${r.status}`);const i=(await r.json()).data,l=Array.isArray(i)?i.map(d=>({...d,canRemove:d.canRemove,canSwitchoff:d.canSwitchoff,canEdit:d.canEdit})):[];e({plugins:l,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 Hu("/api/v1/plugins/marketplaces");if(!r.ok)throw new Error(`HTTP ${r.status}`);const i=(await r.json()).data;e({marketplaces:Array.isArray(i)?i:[],marketplaceLoading:!1})}catch(r){console.warn("[plugin-store] fetchMarketplaces failed:",r),e({marketplaceLoading:!1})}},browseMarketplace:async r=>{var s;e({browsingMarketplace:r,browsingLoading:!0,browsingError:null});try{const i=await Pt("/api/v1/plugins/marketplaces/browse",{marketplace:r});if(!i.ok){const o=await i.json().catch(()=>null);throw new Error(((s=o==null?void 0:o.error)==null?void 0:s.message)||`HTTP ${i.status}`)}const l=await i.json(),a=(Array.isArray(l.data)?l.data:[]).map(o=>({name:o.name,version:o.version,description:o.description,marketplace:o.marketplaceName||r,installed:!!o.status,author:o.author,license:o.license,homepage:o.homepage,repository:o.repository,keywords:o.keywords,category:o.category,features:o.features,source:o.source}));e({availablePlugins:a,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 s=await Promise.allSettled(r.map(async o=>{var b;const c=await Pt("/api/v1/plugins/marketplaces/browse",{marketplace:o.name});if(!c.ok){const y=await c.json().catch(()=>null);throw new Error(((b=y==null?void 0:y.error)==null?void 0:b.message)||`HTTP ${c.status}`)}const u=await c.json();return(Array.isArray(u.data)?u.data:[]).map(y=>({name:y.name,version:y.version,description:y.description,marketplace:y.marketplaceName||o.name,installed:!!y.status,author:y.author,license:y.license,homepage:y.homepage,repository:y.repository,keywords:y.keywords,category:y.category,features:y.features,source:y.source}))})),i=[];let l=!1;for(const o of s)o.status==="fulfilled"?i.push(...o.value):l=!0;const d=new Set,a=i.filter(o=>{const c=`${o.name}@${o.marketplace}`;return d.has(c)?!1:(d.add(c),!0)});e({availablePlugins:a,browsingLoading:!1,browsingError:l&&a.length===0?"Some marketplaces failed to load":null})}catch(s){console.warn("[plugin-store] browseAllMarketplaces failed:",s),e({browsingError:s.message,browsingLoading:!1})}}},enablePlugin:async(r,s)=>{var l;const i=ln(r,s);e(d=>({operatingPlugins:new Set(d.operatingPlugins).add(i)}));try{const d=await Pt("/api/v1/plugins/enable",{plugin:i});if(!d.ok){const a=await d.json().catch(()=>null);throw new Error(((l=a==null?void 0:a.error)==null?void 0:l.message)||`HTTP ${d.status}`)}await t().fetchPlugins()}finally{e(d=>{const a=new Set(d.operatingPlugins);return a.delete(i),{operatingPlugins:a}})}},disablePlugin:async(r,s)=>{var l;const i=ln(r,s);e(d=>({operatingPlugins:new Set(d.operatingPlugins).add(i)}));try{const d=await Pt("/api/v1/plugins/disable",{plugin:i});if(!d.ok){const a=await d.json().catch(()=>null);throw new Error(((l=a==null?void 0:a.error)==null?void 0:l.message)||`HTTP ${d.status}`)}await t().fetchPlugins()}finally{e(d=>{const a=new Set(d.operatingPlugins);return a.delete(i),{operatingPlugins:a}})}},uninstallPlugin:async(r,s)=>{var l;const i=ln(r,s);e(d=>({operatingPlugins:new Set(d.operatingPlugins).add(i)}));try{const d=await Pt("/api/v1/plugins/uninstall",{plugin:i});if(!d.ok){const a=await d.json().catch(()=>null);throw new Error(((l=a==null?void 0:a.error)==null?void 0:l.message)||`HTTP ${d.status}`)}await t().fetchPlugins()}finally{e(d=>{const a=new Set(d.operatingPlugins);return a.delete(i),{operatingPlugins:a}})}},installPlugin:async(r,s,i)=>{var d;const l=ln(r,s);e(a=>({operatingPlugins:new Set(a.operatingPlugins).add(l)}));try{const a=await Pt("/api/v1/plugins",{plugin:l,options:i?{scope:i}:void 0});if(!a.ok){const c=await a.json().catch(()=>null);throw new Error(((d=c==null?void 0:c.error)==null?void 0:d.message)||`HTTP ${a.status}`)}await t().fetchPlugins();const o=t();o.browsingMarketplace&&(o.browsingMarketplace==="__all__"?await t().browseAllMarketplaces():await t().browseMarketplace(o.browsingMarketplace))}finally{e(a=>{const o=new Set(a.operatingPlugins);return o.delete(l),{operatingPlugins:o}})}},addMarketplace:async(r,s)=>{var l;const i=await Pt("/api/v1/plugins/marketplaces",{source:r,name:s});if(!i.ok){const d=await i.json().catch(()=>null);throw new Error(((l=d==null?void 0:d.error)==null?void 0:l.message)||`HTTP ${i.status}`)}await t().fetchMarketplaces()},removeMarketplace:async r=>{var i;const s=await ek(`/api/v1/plugins/marketplaces/${encodeURIComponent(r)}`);if(!s.ok){const l=await s.json().catch(()=>null);throw new Error(((i=l==null?void 0:l.error)==null?void 0:i.message)||`HTTP ${s.status}`)}await t().fetchMarketplaces()}}));function Jh(){const{t:e}=ne(),{plugins:t,marketplaces:r,loading:s,marketplaceLoading:i,error:l,operatingPlugins:d,availablePlugins:a,browsingLoading:o,browsingError:c,fetchPlugins:u,fetchMarketplaces:p,browseMarketplace:b,browseAllMarketplaces:y,enablePlugin:k,disablePlugin:v,uninstallPlugin:g,installPlugin:m,addMarketplace:h,removeMarketplace:f}=tk(),[x,E]=C.useState("installed"),[_,S]=C.useState(""),[w,N]=C.useState("all"),[L,R]=C.useState(null),[j,$]=C.useState(!1),[G,F]=C.useState(""),[W,V]=C.useState(""),[q,A]=C.useState(!1),[T,D]=C.useState(null),[I,P]=C.useState(null),[M,H]=C.useState(null),[z,U]=C.useState(""),[O,Y]=C.useState(""),[X,Q]=C.useState(null),J=C.useCallback(ee=>{Q(oe=>oe===ee?null:ee)},[]);C.useEffect(()=>{u(),p()},[u,p]),C.useEffect(()=>{x==="browse"&&!z&&r.length>0&&(U("__all__"),y())},[x,r,z,y]);const re=C.useCallback(async ee=>{R(null);try{ee.status==="enabled"?await v(ee.name,ee.marketplace):await k(ee.name,ee.marketplace)}catch(oe){R(oe.message)}},[k,v]),ue=C.useCallback(async ee=>{R(null),P(null);try{await g(ee.name,ee.marketplace)}catch(oe){R(oe.message)}},[g]),de=C.useCallback(async(ee,oe)=>{R(null);try{await m(ee.name,ee.marketplace,oe)}catch(fe){R(fe.message)}},[m]),me=C.useCallback(async()=>{const ee=G.trim();if(ee){A(!0),D(null);try{await h(ee,W.trim()||void 0),F(""),V(""),$(!1)}catch(oe){D(oe.message)}finally{A(!1)}}},[G,W,h]),ie=C.useCallback(async ee=>{R(null),H(null);try{if(await f(ee),z===ee&&r.length>1){const oe=r.find(fe=>fe.name!==ee);oe&&(U(oe.name),b(oe.name))}}catch(oe){R(oe.message)}},[f,z,r,b]),Oe=C.useCallback(()=>{u(),p(),x==="browse"&&z&&(z==="__all__"?y():b(z))},[u,p,x,z,b,y]),_e=C.useCallback(ee=>{U(ee),Y(""),ee==="__all__"?y():b(ee)},[b,y]),se=ee=>`${ee.name}@${ee.marketplace}`,ce=C.useMemo(()=>{const ee=new Set(t.map(oe=>oe.marketplace));return Array.from(ee).sort()},[t]),Ee=C.useMemo(()=>{let ee=t;w!=="all"&&(ee=ee.filter(fe=>fe.marketplace===w));const oe=_.trim().toLowerCase();return oe&&(ee=ee.filter(fe=>fe.name.toLowerCase().includes(oe)||fe.description&&fe.description.toLowerCase().includes(oe)||fe.marketplace.toLowerCase().includes(oe))),ee},[t,w,_]),xe=C.useMemo(()=>{let ee=a;const oe=O.trim().toLowerCase();return oe&&(ee=ee.filter(fe=>fe.name.toLowerCase().includes(oe)||fe.description&&fe.description.toLowerCase().includes(oe))),ee},[a,O]),Ze=t.filter(ee=>ee.status==="enabled").length;return n.jsxs("div",{className:"flex-1 flex flex-col overflow-hidden bg-bg-primary",children:[n.jsx("div",{className:"flex-none border-b border-border-muted px-6 py-4",children:n.jsxs("div",{className:"max-w-3xl mx-auto",children:[n.jsxs("div",{className:"flex items-center justify-between mb-4",children:[n.jsxs("div",{children:[n.jsx("h1",{className:"text-lg font-semibold text-text-primary",children:e("plugins.title")}),x==="installed"&&t.length>0&&n.jsxs("p",{className:"text-sm text-text-tertiary mt-0.5",children:[t.length," ",e("plugins.totalCount")," · ",Ze," ",e("plugins.enabled")]}),x==="browse"&&z&&!o&&a.length>0&&n.jsxs("p",{className:"text-sm text-text-tertiary mt-0.5",children:[a.length," ",e("plugins.totalCount")]}),x==="marketplaces"&&r.length>0&&n.jsxs("p",{className:"text-sm text-text-tertiary mt-0.5",children:[r.length," ",e("plugins.totalCount")]})]}),n.jsx("button",{onClick:Oe,disabled:s||o,className:`flex items-center gap-2 px-3 py-2 rounded-lg border transition-all ${s||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:n.jsx(Ve,{size:14,className:s||o?"animate-spin":""})})]}),n.jsxs("div",{className:"flex gap-1 border-b border-border-muted",children:[n.jsx("button",{onClick:()=>{E("installed"),R(null)},className:`px-4 py-2.5 text-[13px] font-medium border-b-2 transition-colors ${x==="installed"?"text-text-primary border-text-primary":"text-text-secondary border-transparent hover:text-text-primary"}`,children:e("plugins.installedPlugins")}),n.jsx("button",{onClick:()=>{E("browse"),R(null)},className:`px-4 py-2.5 text-[13px] font-medium border-b-2 transition-colors ${x==="browse"?"text-text-primary border-text-primary":"text-text-secondary border-transparent hover:text-text-primary"}`,children:e("plugins.browseMarketplace")}),n.jsx("button",{onClick:()=>{E("marketplaces"),R(null)},className:`px-4 py-2.5 text-[13px] font-medium border-b-2 transition-colors ${x==="marketplaces"?"text-text-primary border-text-primary":"text-text-secondary border-transparent hover:text-text-primary"}`,children:e("plugins.marketplaces")})]}),x==="installed"&&t.length>0&&n.jsxs("div",{className:"flex items-center gap-2 mt-4",children:[n.jsxs("div",{className:"flex-1 relative",children:[n.jsx(at,{size:14,className:"absolute left-3 top-1/2 -translate-y-1/2 text-text-tertiary pointer-events-none"}),n.jsx("input",{type:"text",value:_,onChange:ee=>S(ee.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"}),_&&n.jsx("button",{onClick:()=>S(""),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:n.jsx(Te,{size:12})})]}),ce.length>1&&n.jsxs("select",{value:w,onChange:ee=>N(ee.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:[n.jsx("option",{value:"all",children:e("plugins.allMarketplaces")}),ce.map(ee=>n.jsx("option",{value:ee,children:ee},ee))]})]}),x==="browse"&&r.length>0&&n.jsxs("div",{className:"flex items-center gap-2 mt-4",children:[n.jsxs("div",{className:"flex-1 relative",children:[n.jsx(at,{size:14,className:"absolute left-3 top-1/2 -translate-y-1/2 text-text-tertiary pointer-events-none"}),n.jsx("input",{type:"text",value:O,onChange:ee=>Y(ee.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"}),O&&n.jsx("button",{onClick:()=>Y(""),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:n.jsx(Te,{size:12})})]}),n.jsxs("select",{value:z,onChange:ee=>_e(ee.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:[n.jsx("option",{value:"__all__",children:e("plugins.allMarketplaces")}),r.map(ee=>n.jsx("option",{value:ee.name,children:ee.name},ee.name))]})]})]})}),n.jsx("div",{className:"flex-1 overflow-y-auto px-6 py-6",children:n.jsxs("div",{className:"max-w-3xl mx-auto space-y-6",children:[L&&n.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:[n.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[n.jsx(lt,{size:14,className:"shrink-0"}),n.jsxs("span",{className:"truncate",children:[e("plugins.operationFailed"),": ",L]})]}),n.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:n.jsx(Te,{size:12})})]}),x==="installed"&&n.jsxs(n.Fragment,{children:[s&&t.length===0&&n.jsx("div",{className:"flex flex-col items-center justify-center py-20",children:n.jsx(pt,{size:"small",text:e("plugins.loading")})}),l&&!s&&t.length===0&&n.jsxs("div",{className:"flex flex-col items-center justify-center py-20",children:[n.jsx(lt,{size:40,className:"text-text-tertiary opacity-40 mb-4"}),n.jsx("div",{className:"text-[14px] text-text-secondary font-medium mb-3",children:e("plugins.error")}),n.jsx("button",{onClick:u,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")})]}),!s&&!l&&t.length===0&&n.jsxs("div",{className:"flex flex-col items-center justify-center py-20 text-text-tertiary",children:[n.jsx(zt,{size:48,className:"mb-4 opacity-30"}),n.jsx("div",{className:"text-[15px] font-medium mb-1.5 text-text-secondary",children:e("plugins.noPlugins")}),n.jsx("div",{className:"text-[13px]",children:e("plugins.noPluginsHint")})]}),t.length>0&&Ee.length===0&&!s&&n.jsxs("div",{className:"flex flex-col items-center justify-center py-16 text-text-tertiary",children:[n.jsx(at,{size:36,className:"mb-3 opacity-30"}),n.jsx("div",{className:"text-[13px]",children:e("plugins.noSearchResults")})]}),Ee.length>0&&n.jsx("div",{className:"space-y-3",children:Ee.map(ee=>{const oe=se(ee);return n.jsx(rk,{plugin:ee,isEnabled:ee.status==="enabled",isOperating:d.has(oe),isExpanded:X===oe,confirmUninstall:I===oe,onToggle:()=>re(ee),onUninstall:()=>ue(ee),onConfirmUninstall:()=>P(oe),onCancelUninstall:()=>P(null),onExpand:()=>J(oe),t:e},oe)})})]}),x==="browse"&&n.jsxs(n.Fragment,{children:[!i&&r.length===0&&n.jsxs("div",{className:"flex flex-col items-center justify-center py-20 text-text-tertiary",children:[n.jsx(Rr,{size:48,className:"mb-4 opacity-30"}),n.jsx("div",{className:"text-[15px] font-medium mb-1.5 text-text-secondary",children:e("plugins.noMarketplaces")}),n.jsx("div",{className:"text-[13px]",children:e("plugins.noMarketplacesHint")})]}),o&&a.length===0&&z&&n.jsx("div",{className:"flex flex-col items-center justify-center py-20",children:n.jsx(pt,{size:"small",text:e("plugins.browsingMarketplace")})}),c&&a.length===0&&z&&n.jsxs("div",{className:"flex flex-col items-center justify-center py-20",children:[n.jsx(lt,{size:40,className:"text-text-tertiary opacity-40 mb-4"}),n.jsx("div",{className:"text-[14px] text-text-secondary font-medium mb-3",children:e("plugins.error")}),n.jsx("button",{onClick:()=>z&&b(z),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")})]}),z&&a.length===0&&!o&&!c&&n.jsxs("div",{className:"flex flex-col items-center justify-center py-20 text-text-tertiary",children:[n.jsx(zt,{size:48,className:"mb-4 opacity-30"}),n.jsx("div",{className:"text-[15px] font-medium mb-1.5 text-text-secondary",children:e("plugins.noAvailablePlugins")}),n.jsx("div",{className:"text-[13px]",children:e("plugins.noAvailablePluginsHint")})]}),a.length>0&&xe.length===0&&!o&&n.jsxs("div",{className:"flex flex-col items-center justify-center py-16 text-text-tertiary",children:[n.jsx(at,{size:36,className:"mb-3 opacity-30"}),n.jsx("div",{className:"text-[13px]",children:e("plugins.noSearchResults")})]}),xe.length>0&&n.jsx("div",{className:"space-y-3",children:xe.map(ee=>{const oe=`${ee.name}@${ee.marketplace}`;return n.jsx(nk,{plugin:ee,isInstalled:ee.installed,isOperating:d.has(oe),isExpanded:X===oe,onInstall:fe=>de(ee,fe),onExpand:()=>J(oe),t:e},oe)})})]}),x==="marketplaces"&&n.jsxs("div",{className:"space-y-3",children:[!j&&n.jsxs("button",{onClick:()=>$(!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:[n.jsx(ot,{size:12}),e("plugins.addMarketplace")]}),j&&n.jsxs("div",{className:"bg-bg-secondary rounded-xl border border-border-muted p-4 space-y-3",children:[n.jsxs("div",{className:"flex items-center justify-between",children:[n.jsx("span",{className:"text-[13px] font-medium",children:e("plugins.addMarketplace")}),n.jsx("button",{onClick:()=>{$(!1),D(null)},className:"w-6 h-6 flex items-center justify-center rounded-full hover:bg-bg-tertiary transition-colors text-text-secondary",children:n.jsx(Te,{size:12})})]}),n.jsx("input",{type:"text",value:G,onChange:ee=>F(ee.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"}),n.jsx("input",{type:"text",value:W,onChange:ee=>V(ee.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"}),T&&n.jsx("div",{className:"text-accent-red text-[12px]",children:T}),n.jsxs("div",{className:"flex justify-end gap-2",children:[n.jsx("button",{onClick:()=>{$(!1),D(null)},className:"px-3 py-1.5 rounded-lg text-[12px] text-text-secondary hover:bg-bg-tertiary transition-colors",children:e("plugins.cancel")}),n.jsxs("button",{onClick:me,disabled:!G.trim()||q,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:[q&&n.jsx(we,{size:12,className:"animate-spin"}),e("plugins.add")]})]})]}),i&&r.length===0&&n.jsx("div",{className:"flex items-center justify-center py-6",children:n.jsx(we,{size:18,className:"animate-spin text-text-tertiary"})}),!i&&r.length===0&&!j&&n.jsxs("div",{className:"flex flex-col items-center justify-center py-20 text-text-tertiary",children:[n.jsx(Rr,{size:48,className:"mb-4 opacity-30"}),n.jsx("div",{className:"text-[15px] font-medium mb-1.5 text-text-secondary",children:e("plugins.noMarketplaces")}),n.jsx("div",{className:"text-[13px]",children:e("plugins.noMarketplacesHint")})]}),r.length>0&&n.jsx("div",{className:"bg-bg-secondary rounded-xl border border-border-muted overflow-hidden",children:r.map((ee,oe)=>n.jsxs("div",{className:`flex items-center justify-between px-4 py-3 ${oe>0?"border-t border-border-muted":""}`,children:[n.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[n.jsx(Rr,{size:14,className:"text-text-tertiary shrink-0"}),n.jsxs("div",{className:"min-w-0",children:[n.jsx("div",{className:"text-[13px] font-medium truncate",children:ee.name}),ee.type&&n.jsx("div",{className:"text-[11px] text-text-tertiary",children:ee.type})]})]}),n.jsx("div",{className:"flex items-center gap-2 shrink-0",children:M===ee.name?n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("button",{onClick:()=>ie(ee.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")}),n.jsx("button",{onClick:()=>H(null),className:"px-2.5 py-1 rounded-md text-[11px] text-text-secondary hover:bg-bg-tertiary transition-colors",children:e("plugins.cancel")})]}):n.jsx("button",{onClick:()=>H(ee.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:n.jsx(hr,{size:13})})})]},ee.name))})]})]})})]})}function rk({plugin:e,isEnabled:t,isOperating:r,isExpanded:s,confirmUninstall:i,onToggle:l,onUninstall:d,onConfirmUninstall:a,onCancelUninstall:o,onExpand:c,t:u}){return n.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:[n.jsxs("div",{className:"flex items-start gap-4 px-5 py-4 cursor-pointer",onClick:c,children:[n.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:n.jsx(zt,{size:18,className:t?"text-text-primary":"text-text-tertiary"})}),n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsxs("div",{className:"flex items-center gap-2 mb-0.5",children:[n.jsx("span",{className:"text-[14px] font-semibold text-text-primary truncate",children:e.name}),e.version&&n.jsxs("span",{className:"text-[11px] text-text-tertiary shrink-0 font-mono",children:["v",e.version]}),n.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:u(t?"plugins.enabled":"plugins.disabled")})]}),e.description&&n.jsx("div",{className:`text-[12px] text-text-secondary leading-relaxed mb-1.5 ${s?"":"line-clamp-2"}`,children:e.description}),n.jsxs("div",{className:"flex items-center gap-1.5 text-[11px] text-text-tertiary",children:[n.jsx(Rr,{size:10,className:"shrink-0"}),n.jsx("span",{children:e.marketplace}),e.installScope&&n.jsx("span",{className:"px-1.5 py-px rounded bg-bg-tertiary text-[10px] font-medium",children:u(`plugins.scope.${e.installScope}`)})]})]}),n.jsx("div",{className:"flex items-center gap-1.5 shrink-0 pt-0.5",onClick:p=>p.stopPropagation(),children:r?n.jsx("div",{className:"w-[72px] flex justify-center",children:n.jsx(we,{size:16,className:"animate-spin text-text-tertiary"})}):i?n.jsxs("div",{className:"flex items-center gap-1.5",children:[n.jsx("button",{onClick:d,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:u("plugins.uninstall")}),n.jsx("button",{onClick:o,className:"px-2.5 py-1 rounded-md text-[11px] text-text-secondary hover:bg-bg-tertiary transition-colors",children:u("plugins.cancel")})]}):n.jsxs(n.Fragment,{children:[n.jsxs("button",{onClick:e.canSwitchoff===!1?void 0:l,disabled:e.canSwitchoff===!1,className:`px-2.5 py-1.5 rounded-md text-[11px] font-medium transition-colors flex items-center gap-1 ${e.canSwitchoff===!1?"text-text-tertiary border border-border-muted cursor-not-allowed opacity-50":t?"text-text-secondary border border-border-muted hover:bg-bg-tertiary":"text-text-primary border border-border-muted hover:bg-bg-tertiary"}`,title:e.canSwitchoff===!1?u("plugins.policyCannotSwitchoff"):u(t?"plugins.disable":"plugins.enable"),children:[t?n.jsx(Jf,{size:11}):n.jsx(Ip,{size:11}),u(t?"plugins.disable":"plugins.enable")]}),n.jsx("button",{onClick:e.canRemove===!1?void 0:a,disabled:e.canRemove===!1,className:`w-7 h-7 flex items-center justify-center rounded-md transition-colors ${e.canRemove===!1?"text-text-tertiary cursor-not-allowed opacity-30":"text-text-tertiary hover:text-accent-red hover:bg-accent-red/10 opacity-0 group-hover:opacity-100"}`,title:e.canRemove===!1?u("plugins.policyCannotRemove"):u("plugins.uninstall"),children:n.jsx(hr,{size:13})})]})})]}),s&&n.jsx(Qh,{plugin:e,t:u})]})}function nk({plugin:e,isInstalled:t,isOperating:r,isExpanded:s,onInstall:i,onExpand:l,t:d}){return n.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:[n.jsxs("div",{className:"flex items-start gap-4 px-5 py-4 cursor-pointer",onClick:l,children:[n.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:n.jsx(zt,{size:18,className:t?"text-text-primary":"text-text-tertiary"})}),n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsxs("div",{className:"flex items-center gap-2 mb-0.5",children:[n.jsx("span",{className:"text-[14px] font-semibold text-text-primary truncate",children:e.name}),e.version&&n.jsxs("span",{className:"text-[11px] text-text-tertiary shrink-0 font-mono",children:["v",e.version]}),t&&n.jsx("span",{className:"text-[10px] px-1.5 py-px rounded font-medium shrink-0 bg-accent-green/15 text-accent-green",children:d("plugins.installedLabel")})]}),e.description&&n.jsx("div",{className:`text-[12px] text-text-secondary leading-relaxed mb-1.5 ${s?"":"line-clamp-2"}`,children:e.description}),n.jsxs("div",{className:"flex items-center gap-1 text-[11px] text-text-tertiary",children:[n.jsx(Rr,{size:10,className:"shrink-0"}),n.jsx("span",{children:e.marketplace})]})]}),n.jsx("div",{className:"flex items-center gap-1.5 shrink-0 pt-0.5",onClick:a=>a.stopPropagation(),children:t?n.jsx("div",{className:"px-2.5 py-1.5 rounded-md text-[11px] font-medium text-text-tertiary bg-bg-tertiary",children:d("plugins.installed")}):r?n.jsx("div",{className:"w-[72px] flex justify-center",children:n.jsx(we,{size:16,className:"animate-spin text-text-tertiary"})}):n.jsx(sk,{onInstall:i,t:d})})]}),s&&n.jsx(Qh,{plugin:e,t:d})]})}function Qh({plugin:e,t}){const r=e.source,s=typeof r=="object"&&r!==null?r.url:void 0,i=typeof r=="object"&&r!==null?r.source:typeof r=="string"?r:void 0,l="installScope"in e?e.installScope:void 0;return n.jsxs("div",{className:"border-t border-border-muted mx-5 px-0 py-3.5 space-y-2.5",children:[l&&n.jsx(vt,{label:t("plugins.scope"),children:n.jsx("span",{className:"text-[12px] text-text-secondary",children:t(`plugins.scope.${l}`)})}),e.category&&n.jsx(vt,{label:t("plugins.category"),children:n.jsx("span",{className:"text-[11px] px-2 py-0.5 rounded bg-[#f5a623]/8 text-[#b8860b] font-medium",children:e.category})}),e.author&&n.jsxs(vt,{label:t("plugins.author"),children:[n.jsx("span",{className:"text-[12px] text-text-primary font-medium",children:e.author.name}),e.author.email&&n.jsx("a",{href:`mailto:${e.author.email}`,className:"text-[11px] text-text-tertiary hover:text-text-primary hover:underline ml-1",onClick:d=>d.stopPropagation(),children:e.author.email}),e.author.url&&n.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:d=>d.stopPropagation(),children:[e.author.url,n.jsx(it,{size:9})]})]}),e.license&&n.jsx(vt,{label:t("plugins.license"),children:n.jsx("span",{className:"text-[12px] text-text-secondary",children:e.license})}),e.homepage&&n.jsx(vt,{label:t("plugins.homepage"),children:n.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:d=>d.stopPropagation(),children:[e.homepage,n.jsx(it,{size:10,className:"shrink-0 text-text-tertiary"})]})}),e.repository&&n.jsx(vt,{label:t("plugins.repository"),children:n.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:d=>d.stopPropagation(),children:[e.repository,n.jsx(it,{size:10,className:"shrink-0 text-text-tertiary"})]})}),i&&n.jsx(vt,{label:t("plugins.source"),children:s?n.jsxs("a",{href:s,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:d=>d.stopPropagation(),children:[i,n.jsx(it,{size:10,className:"shrink-0 text-text-tertiary"})]}):n.jsx("span",{className:"text-[12px] text-text-secondary font-mono",children:i})}),e.keywords&&e.keywords.length>0&&n.jsx(vt,{label:t("plugins.keywords"),children:n.jsx("div",{className:"flex flex-wrap gap-1",children:e.keywords.map(d=>n.jsx("span",{className:"text-[10px] px-1.5 py-px rounded bg-bg-tertiary text-text-tertiary",children:d},d))})}),e.features&&e.features.length>0&&n.jsx(vt,{label:t("plugins.features"),children:n.jsx("ul",{className:"space-y-0.5",children:e.features.map((d,a)=>n.jsxs("li",{className:"text-[12px] text-text-secondary flex items-start gap-1.5",children:[n.jsx("span",{className:"text-text-tertiary shrink-0",children:"·"}),d]},a))})})]})}function vt({label:e,children:t}){return n.jsxs("div",{className:"flex items-baseline gap-3",children:[n.jsx("span",{className:"text-[11px] text-text-tertiary w-12 shrink-0 text-right",children:e}),n.jsx("div",{className:"flex-1 min-w-0 flex items-baseline flex-wrap gap-1",children:t})]})}function sk({onInstall:e,t}){const[r,s]=C.useState(!1);return n.jsxs("div",{className:"relative",children:[n.jsxs("button",{onClick:()=>s(!r),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:t("plugins.install"),children:[n.jsx(pp,{size:11}),t("plugins.install")]}),r&&n.jsxs("div",{className:"absolute right-0 top-full mt-1 z-50 bg-bg-primary border border-border-muted rounded-lg shadow-lg py-1 min-w-[220px]",children:[n.jsx("button",{onClick:()=>{e("user"),s(!1)},className:"w-full text-left px-3 py-2 text-[12px] text-text-primary hover:bg-bg-secondary transition-colors",children:t("plugins.installScope.user")}),n.jsx("button",{onClick:()=>{e("project"),s(!1)},className:"w-full text-left px-3 py-2 text-[12px] text-text-primary hover:bg-bg-secondary transition-colors",children:t("plugins.installScope.project")}),n.jsx("button",{onClick:()=>{e("project-local"),s(!1)},className:"w-full text-left px-3 py-2 text-[12px] text-text-primary hover:bg-bg-secondary transition-colors",children:t("plugins.installScope.local")})]})]})}const ik=[{value:"minimal",labelKey:"settings.effort.minimal"},{value:"low",labelKey:"settings.effort.low"},{value:"medium",labelKey:"settings.effort.medium"},{value:"high",labelKey:"settings.effort.high"},{value:"xhigh",labelKey:"settings.effort.xhigh"},{value:"max",labelKey:"settings.effort.max"}],ak=[{titleKey:"settings.group.modelAndReasoning",items:[{key:"model",labelKey:"settings.item.model",descKey:"settings.item.model.desc",type:"text"},{key:"reasoningEffort",labelKey:"settings.item.reasoningEffort",descKey:"settings.item.reasoningEffort.desc",type:"select",options:ik},{key:"alwaysThinkingEnabled",labelKey:"settings.item.alwaysThinkingEnabled",type:"toggle"}]},{titleKey:"settings.group.behavior",items:[{key:"autoCompactEnabled",labelKey:"settings.item.autoCompactEnabled",type:"toggle"},{key:"includeCoAuthoredBy",labelKey:"settings.item.includeCoAuthoredBy",type:"toggle"},{key:"fileCheckpointingEnabled",labelKey:"settings.item.fileCheckpointingEnabled",descKey:"settings.item.fileCheckpointingEnabled.desc",type:"toggle"},{key:"promptSuggestionEnabled",labelKey:"settings.item.promptSuggestionEnabled",type:"toggle"},{key:"ignoreGitIgnore",labelKey:"settings.item.ignoreGitIgnore",descKey:"settings.item.ignoreGitIgnore.desc",type:"toggle"},{key:"deferToolLoading",labelKey:"settings.item.deferToolLoading",type:"toggle"},{key:"hookOutputCollapsed",labelKey:"settings.item.hookOutputCollapsed",type:"toggle"}]},{titleKey:"settings.group.memory",items:[{key:"memory.enabled",labelKey:"settings.item.memory.enabled",type:"toggle"},{key:"memory.autoMemoryEnabled",labelKey:"settings.item.memory.autoMemoryEnabled",descKey:"settings.item.memory.autoMemoryEnabled.desc",type:"toggle"}]},{titleKey:"settings.group.language",items:[{key:"language",labelKey:"settings.item.language",descKey:"settings.item.language.desc",type:"text"}]},{titleKey:"settings.group.advanced",items:[{key:"cleanupPeriodDays",labelKey:"settings.item.cleanupPeriodDays",type:"number"},{key:"imageHistoryRetainRounds",labelKey:"settings.item.imageHistoryRetainRounds",descKey:"settings.item.imageHistoryRetainRounds.desc",type:"number"},{key:"env",labelKey:"settings.item.env",descKey:"settings.item.env.desc",type:"json"}]},{titleKey:"settings.group.sandbox",items:[{key:"sandbox.enabled",labelKey:"settings.item.sandbox.enabled",descKey:"settings.item.sandbox.enabled.desc",type:"toggle"},{key:"sandbox.autoAllowBashIfSandboxed",labelKey:"settings.item.sandbox.autoAllowBashIfSandboxed",descKey:"settings.item.sandbox.autoAllowBashIfSandboxed.desc",type:"toggle"}]}];function ok(e,t){const r=t.split(".");let s=e;for(const i of r){if(s==null||typeof s!="object")return;s=s[i]}return s}function em(){const{status:e,sessionId:t,currentModel:r,models:s,modes:i,currentMode:l}=rt(),{info:d,fetch:a}=Wt(),{mode:o,toggle:c}=Ke(),{t:u,locale:p,toggleLocale:b}=ne(),[y,k]=C.useState(null),[v,g]=C.useState({}),m=C.useRef({}),[h,f]=C.useState(!1),[x,E]=C.useState({}),_=C.useRef({});C.useEffect(()=>{let q=!1;return f(!0),Promise.all([fetch("/api/v1/settings",{headers:ae()}).then(A=>{if(!A.ok)throw new Error(`Settings API: ${A.status}`);return A.json()}).then(A=>(A==null?void 0:A.data)??A??{}),fetch("/api/v1/settings?scope=user",{headers:ae()}).then(A=>{if(!A.ok)throw new Error(`User settings API: ${A.status}`);return A.json()}).then(A=>(A==null?void 0:A.data)??A??{})]).then(([A,T])=>{q||(g(A),m.current=T,f(!1))}).catch(A=>{console.error("Failed to load settings:",A),q||f(!1)}),()=>{q=!0}},[]),C.useEffect(()=>()=>{Object.values(_.current).forEach(clearTimeout)},[]),C.useEffect(()=>{d||a()},[d,a]);const S=C.useCallback((q,A)=>{navigator.clipboard.writeText(q).then(()=>{k(A),setTimeout(()=>k(null),1500)})},[]),w=async q=>{if(L("model",q),t)try{await Re().setModel(t,q)}catch(A){console.error("Model change failed:",A)}},N=async q=>{if(L("permissions.defaultMode",q),t)try{await Re().setMode(t,q)}catch(A){console.error("Mode change failed:",A)}},L=C.useCallback(async(q,A)=>{const T=q.split(".")[0];let D=A;if(q.includes(".")){const I=q.split("."),M={...m.current[T]??{}};let H=M;for(let z=1;z<I.length-1;z++)H[I[z]]=H[I[z]]?{...H[I[z]]}:{},H=H[I[z]];H[I[I.length-1]]=A,D=M}try{const I=await fetch(`/api/v1/settings/${T}?scope=user`,{method:"PUT",headers:ae({"Content-Type":"application/json"}),body:JSON.stringify({value:D})});I.ok||I.status===204?(q.includes(".")?(m.current={...m.current,[T]:D},g(P=>({...P,[T]:{...P[T]??{},...D}}))):(m.current={...m.current,[q]:A},g(P=>({...P,[q]:A}))),R(q,"success")):(console.error(`Failed to save setting "${q}": HTTP ${I.status}`),R(q,"error"))}catch(I){console.error(`Failed to save setting "${q}":`,I),R(q,"error")}},[]),R=C.useCallback((q,A)=>{E(T=>({...T,[q]:A})),_.current[q]&&clearTimeout(_.current[q]),_.current[q]=setTimeout(()=>{E(T=>{const D={...T};return delete D[q],D})},1500)},[]),j={disconnected:"bg-gray-400",connecting:"bg-accent-yellow animate-pulse",connected:"bg-accent-green",error:"bg-accent-red"}[e],$={connected:"connection.connected",connecting:"connection.connecting",disconnected:"connection.disconnected",error:"connection.error"},G=o==="light"?Lp:o==="dark"?Tp:Eb,F=u(o==="light"?"theme.light":o==="dark"?"theme.dark":"theme.system"),W=p==="system"?uf:bp,V=u(p==="zh"?"locale.zh":p==="en"?"locale.en":"locale.system");return n.jsx("div",{className:"settings-view",children:n.jsx("div",{className:"settings-content",children:n.jsxs("div",{className:"settings-sections",children:[n.jsxs("div",{className:"settings-group",children:[n.jsx("h2",{className:"settings-group-title",children:u("sidebar.connectionStatus")}),n.jsxs("div",{className:"settings-card",children:[n.jsxs("div",{className:"settings-row",children:[n.jsx("span",{className:"settings-label",children:u("sidebar.status")}),n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("span",{className:`w-2 h-2 rounded-full ${j}`}),n.jsx("span",{className:"settings-value",children:u($[e]||"connection.disconnected")})]})]}),n.jsxs("div",{className:"settings-row",children:[n.jsx("span",{className:"settings-label",children:u("sidebar.sessionId")}),n.jsx("span",{className:"settings-value font-mono text-[12px]",children:t?t.substring(0,12):u("sidebar.notConnected")})]})]})]}),n.jsxs("div",{className:"settings-group",children:[n.jsx("h2",{className:"settings-group-title",children:u("settings.appearance")}),n.jsxs("div",{className:"settings-card",children:[n.jsxs("div",{className:"settings-row",children:[n.jsx("span",{className:"settings-label",children:u("sidebar.theme")}),n.jsxs("button",{onClick:c,className:"settings-toggle-btn",children:[n.jsx(G,{size:14,className:"text-accent-brand"}),n.jsx("span",{children:F})]})]}),n.jsxs("div",{className:"settings-row",children:[n.jsx("span",{className:"settings-label",children:u("sidebar.language")}),n.jsxs("button",{onClick:b,className:"settings-toggle-btn",children:[n.jsx(W,{size:14,className:"text-accent-brand"}),n.jsx("span",{children:V})]})]})]})]}),s.length>0&&n.jsxs("div",{className:"settings-group",children:[n.jsx("h2",{className:"settings-group-title",children:u("settings.model")}),n.jsx("div",{className:"settings-card",children:n.jsx("select",{value:r,onChange:q=>w(q.target.value),className:"settings-select",children:s.map(q=>n.jsx("option",{value:q.id,children:q.name||q.id},q.id))})})]}),i.length>0&&n.jsxs("div",{className:"settings-group",children:[n.jsx("h2",{className:"settings-group-title",children:u("settings.mode")}),n.jsx("div",{className:"settings-card",children:n.jsx("select",{value:l,onChange:q=>N(q.target.value),className:"settings-select",children:i.map(q=>n.jsx("option",{value:q.id,title:q.description,children:q.name},q.id))})})]}),h?n.jsx("div",{className:"settings-group",children:n.jsx("span",{className:"settings-value",children:u("settings.loading")})}):ak.map(q=>n.jsxs("div",{className:"settings-group",children:[n.jsx("h2",{className:"settings-group-title",children:u(q.titleKey)}),n.jsx("div",{className:"settings-card",children:q.items.map(A=>n.jsx(lk,{item:A,value:ok(v,A.key),feedback:x[A.key],onSave:L},A.key))})]},q.titleKey)),d&&n.jsxs("div",{className:"settings-group",children:[n.jsx("h2",{className:"settings-group-title",children:u("settings.systemInfo")}),n.jsxs("div",{className:"settings-card",children:[n.jsxs("div",{className:"settings-row",children:[n.jsx("span",{className:"settings-label",children:u("sidebar.cwd")}),n.jsxs("button",{onClick:()=>S(d.cwd,"cwd"),className:"settings-copy-btn",title:d.cwd,children:[n.jsx("span",{className:"truncate cursor-pointer hover:underline hover:text-accent-brand",onClick:q=>{q.stopPropagation(),Kp(d.cwd)},children:d.cwd}),y==="cwd"?n.jsx(Ht,{size:12,className:"shrink-0 text-accent-green"}):n.jsx($r,{size:12,className:"shrink-0 text-text-tertiary"})]})]}),n.jsxs("div",{className:"settings-row",children:[n.jsx("span",{className:"settings-label",children:u("sidebar.os")}),n.jsxs("span",{className:"settings-value",children:[d.os," ",d.arch]})]}),n.jsxs("div",{className:"settings-row",children:[n.jsx("span",{className:"settings-label",children:u("sidebar.nodeVersion")}),n.jsx("span",{className:"settings-value",children:d.nodeVersion})]}),n.jsxs("div",{className:"settings-row",children:[n.jsx("span",{className:"settings-label",children:u("sidebar.gatewayMode")}),n.jsx("span",{className:"settings-value capitalize",children:d.gatewayMode})]}),d.tunnelUrl&&n.jsxs("div",{className:"settings-row",children:[n.jsx("span",{className:"settings-label",children:u("sidebar.tunnelUrl")}),n.jsxs("button",{onClick:()=>S(d.tunnelUrl,"tunnel"),className:"settings-copy-btn",title:d.tunnelUrl,children:[n.jsx("span",{className:"truncate",children:d.tunnelUrl.replace(/^https?:\/\//,"")}),y==="tunnel"?n.jsx(Ht,{size:12,className:"shrink-0 text-accent-green"}):n.jsx($r,{size:12,className:"shrink-0 text-text-tertiary"})]})]})]})]})]})})})}function lk({item:e,value:t,feedback:r,onSave:s}){const{t:i}=ne(),[l,d]=C.useState(""),a=C.useRef(null);C.useEffect(()=>()=>{a.current&&clearTimeout(a.current)},[]),C.useEffect(()=>{e.type==="text"||e.type==="number"?d(t!=null?String(t):""):e.type==="json"&&d(t!=null?JSON.stringify(t,null,2):"")},[t,e.type]);const o=C.useCallback(()=>{s(e.key,!t)},[e.key,t,s]),c=C.useCallback(p=>{s(e.key,p||void 0)},[e.key,s]),u=C.useCallback(p=>{d(p),a.current&&clearTimeout(a.current),a.current=setTimeout(()=>{if(e.type==="number"){const b=Number(p);!isNaN(b)&&p.trim()!==""&&s(e.key,b)}else if(e.type==="json")try{const b=JSON.parse(p);s(e.key,b)}catch{}else s(e.key,p)},600)},[e.key,e.type,s]);return n.jsxs("div",{className:"settings-row",children:[n.jsxs("div",{className:"flex flex-col gap-0.5 min-w-0 flex-1",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("span",{className:"settings-label",children:i(e.labelKey)}),r&&n.jsx("span",{className:`settings-save-feedback ${r==="success"?"success":"error"}`,children:i(r==="success"?"settings.saved":"settings.saveFailed")})]}),e.descKey&&n.jsx("span",{className:"settings-desc",children:i(e.descKey)})]}),n.jsxs("div",{className:"flex items-center shrink-0 ml-3",children:[e.type==="toggle"&&n.jsx("button",{className:`settings-toggle-switch ${t?"on":""}`,onClick:o}),e.type==="select"&&e.options&&n.jsxs("select",{value:t??"",onChange:p=>c(p.target.value),className:"settings-inline-select",children:[n.jsx("option",{value:"",children:"-"}),e.options.map(p=>n.jsx("option",{value:p.value,children:i(p.labelKey)},p.value))]}),e.type==="text"&&n.jsx("input",{type:"text",value:l,onChange:p=>u(p.target.value),placeholder:i("settings.notSet"),className:"settings-input"}),e.type==="number"&&n.jsx("input",{type:"number",value:l,onChange:p=>u(p.target.value),className:"settings-input",style:{width:80}}),e.type==="json"&&n.jsx("textarea",{value:l,onChange:p=>u(p.target.value),placeholder:"{}",className:"settings-input wide",rows:3,style:{width:"100%",resize:"vertical"}})]})]})}function xs(){return rt.getState().sessionId??void 0}const ck=Ae((e,t)=>({tasks:[],loading:!1,error:null,fetchTasks:async()=>{const r=xs();if(r){e({loading:!0,error:null});try{const s=new URLSearchParams({sessionId:r}),i=await fetch(`/api/v1/scheduled-tasks?${s}`,{headers:ae()});if(!i.ok)throw new Error(`HTTP ${i.status}`);const l=await i.json(),d=l.data??l;e({tasks:d.tasks||[],loading:!1})}catch(s){console.error("[ScheduledTasks] Fetch error:",s),e({error:s.message,loading:!1})}}},createTask:async(r,s,i=!0,l=!1)=>{var a;const d=xs();if(d)try{const o=await fetch("/api/v1/scheduled-tasks",{method:"POST",headers:{"Content-Type":"application/json",...ae()},body:JSON.stringify({cron:r,prompt:s,recurring:i,durable:l,sessionId:d})});if(!o.ok){const c=await o.json().catch(()=>({}));throw new Error(((a=c.error)==null?void 0:a.message)||`HTTP ${o.status}`)}await t().fetchTasks()}catch(o){throw console.error("[ScheduledTasks] Create error:",o),e({error:o.message}),o}},deleteTask:async r=>{const s=xs();if(s)try{const i=new URLSearchParams({sessionId:s}),l=await fetch(`/api/v1/scheduled-tasks/${r}?${i}`,{method:"DELETE",headers:ae()});if(!l.ok&&l.status!==204)throw new Error(`HTTP ${l.status}`);await t().fetchTasks()}catch(i){throw console.error("[ScheduledTasks] Delete error:",i),e({error:i.message}),i}}})),dk=[{label:"5m",cron:"*/5 * * * *"},{label:"30m",cron:"*/30 * * * *"},{label:"1h",cron:"7 * * * *"},{label:"1d",cron:"3 9 * * *"},{label:"1w",cron:"3 9 * * 1"}];function uk({onSubmit:e,onCancel:t}){const{t:r}=ne(),[s,i]=C.useState("*/5 * * * *"),[l,d]=C.useState(""),[a,o]=C.useState(!0),[c,u]=C.useState(!1),[p,b]=C.useState(!1),[y,k]=C.useState(null),v=async()=>{if(!(!s.trim()||!l.trim())){b(!0),k(null);try{await e(s.trim(),l.trim(),a,c),t()}catch(g){k(g.message||"Failed to create task")}finally{b(!1)}}};return n.jsxs("div",{className:"border border-accent-brand/30 rounded-xl p-4 bg-bg-secondary/30",children:[n.jsxs("div",{className:"flex items-center justify-between mb-3",children:[n.jsx("h3",{className:"text-sm font-medium text-text-primary",children:r("scheduled.create")}),n.jsx("button",{onClick:t,className:"p-1 rounded hover:bg-bg-secondary text-text-tertiary",children:n.jsx(Te,{size:14})})]}),n.jsxs("div",{className:"mb-3",children:[n.jsx("label",{className:"text-xs text-text-secondary mb-1 block",children:r("scheduled.cron")}),n.jsx("input",{type:"text",value:s,onChange:g=>i(g.target.value),placeholder:"*/5 * * * *",className:"w-full px-3 py-1.5 text-sm rounded-lg border border-border-default bg-bg-primary text-text-primary focus:border-accent-brand/50 outline-none font-mono"}),n.jsx("div",{className:"flex gap-1.5 mt-1.5",children:dk.map(g=>n.jsx("button",{onClick:()=>i(g.cron),className:`text-[10px] px-2 py-0.5 rounded-full border transition-colors ${s===g.cron?"border-accent-brand/50 text-accent-brand bg-accent-brand/5":"border-border-default text-text-tertiary hover:text-text-secondary hover:border-border-default/80"}`,children:g.label},g.label))})]}),n.jsxs("div",{className:"mb-3",children:[n.jsx("label",{className:"text-xs text-text-secondary mb-1 block",children:r("scheduled.prompt")}),n.jsx("textarea",{value:l,onChange:g=>d(g.target.value),placeholder:r("scheduled.promptPlaceholder"),rows:2,className:"w-full px-3 py-1.5 text-sm rounded-lg border border-border-default bg-bg-primary text-text-primary focus:border-accent-brand/50 outline-none resize-none"})]}),n.jsxs("div",{className:"flex items-center gap-4 mb-3",children:[n.jsxs("label",{className:"flex items-center gap-2 text-xs text-text-secondary cursor-pointer",children:[n.jsx("input",{type:"checkbox",checked:a,onChange:g=>o(g.target.checked),className:"rounded"}),r("scheduled.recurring")]}),n.jsxs("label",{className:"flex items-center gap-2 text-xs text-text-secondary cursor-pointer",children:[n.jsx("input",{type:"checkbox",checked:c,onChange:g=>u(g.target.checked),className:"rounded"}),r("scheduled.durable")]})]}),y&&n.jsx("div",{className:"text-xs text-accent-red mb-2",children:y}),n.jsxs("button",{onClick:v,disabled:p||!s.trim()||!l.trim(),className:"flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-accent-brand text-white text-sm font-medium hover:bg-accent-brand/90 disabled:opacity-50 disabled:cursor-not-allowed transition-colors",children:[n.jsx(ot,{size:14}),r(p?"scheduled.creating":"scheduled.create")]})]})}function pk({task:e,onDelete:t}){const{t:r}=ne(),[s,i]=C.useState(!1),l=async()=>{i(!0);try{await t(e.id)}finally{i(!1)}},d=e.durable||e.permanent;return n.jsxs("div",{className:"group flex items-start gap-3 px-4 py-3 rounded-xl border border-border-default hover:border-accent-brand/30 transition-colors",children:[n.jsx("div",{className:"flex-shrink-0 mt-0.5",children:e.recurring?n.jsx(nb,{size:18,className:"text-accent-blue"}):n.jsx(Dp,{size:18,className:"text-accent-yellow"})}),n.jsxs("div",{className:"flex-1 min-w-0",children:[n.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[n.jsx("span",{className:"text-sm font-medium text-text-primary",children:e.humanSchedule}),n.jsx("span",{className:`text-[10px] px-1.5 py-0.5 rounded-full ${e.recurring?"bg-accent-blue/10 text-accent-blue":"bg-accent-yellow/10 text-accent-yellow"}`,children:e.recurring?r("scheduled.recurring"):r("scheduled.oneShot")}),d&&n.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded-full bg-accent-green/10 text-accent-green",children:r("scheduled.durable")})]}),n.jsx("p",{className:"text-xs text-text-secondary truncate",title:e.prompt,children:e.prompt}),n.jsxs("div",{className:"flex items-center gap-3 mt-1.5 text-[10px] text-text-tertiary",children:[n.jsxs("span",{className:"flex items-center gap-1",children:[n.jsx(Dt,{size:10}),"ID: ",e.id]}),e.lastFiredAt&&n.jsxs("span",{children:[r("scheduled.lastFired"),": ",new Date(e.lastFiredAt).toLocaleString()]})]})]}),n.jsx("button",{onClick:l,disabled:s,className:"flex-shrink-0 p-1.5 rounded-lg opacity-0 group-hover:opacity-100 hover:bg-accent-red/10 text-text-tertiary hover:text-accent-red transition-all disabled:opacity-50",title:r("scheduled.delete"),children:n.jsx(hr,{size:14})})]})}const hk=3e3;function tm(){const{t:e}=ne(),{setMainView:t}=pe(),{setExternalInput:r,sessionId:s}=rt(),{tasks:i,loading:l,fetchTasks:d,createTask:a,deleteTask:o}=ck(),[c,u]=C.useState(!1);C.useEffect(()=>{d()},[d,s]);const[p,b]=C.useState([]),[y,k]=C.useState(!0),[v,g]=C.useState(null),[m,h]=C.useState(!1),[f,x]=C.useState(!1),E=C.useRef(s);E.current=s;const _=C.useRef(null),S=C.useCallback(()=>{_.current&&(clearInterval(_.current),_.current=null)},[]),w=C.useCallback(async()=>{const j=new URLSearchParams,$=E.current;$&&j.append("sessionId",$);const G=j.toString(),F=await fetch(`/api/v1/tasks/templates${G?"?"+G:""}`,{headers:ae()});if(!F.ok)throw new Error(`HTTP ${F.status}`);const W=await F.json(),V=W.data??W;return b(V.templates||[]),g(V.error||null),V.status},[]),N=C.useCallback(()=>{S(),_.current=setInterval(async()=>{try{const j=await w();j!=="loading"&&(S(),h(!1),j==="done"&&(x(!0),setTimeout(()=>x(!1),2e3)))}catch(j){S(),h(!1),g(j.message||"Failed to load templates")}},hk)},[w,S]);C.useEffect(()=>{let j=!1;return(async()=>{try{if(!E.current){j||k(!1);return}const $=await w();if(j)return;$==="loading"&&(h(!0),N())}catch($){j||g($.message)}finally{j||k(!1)}})(),()=>{j=!0,S()}},[w,N,S,s]);const L=C.useCallback(async()=>{h(!0),g(null),x(!1);try{const j=new URLSearchParams,$=E.current;$&&j.append("sessionId",$);const G=j.toString(),F=await fetch(`/api/v1/tasks/templates/refresh${G?"?"+G:""}`,{method:"POST",headers:ae()});if(!F.ok)throw new Error(`HTTP ${F.status}`);N()}catch(j){g(j.message||"Failed to trigger refresh"),h(!1)}},[N]),R=C.useCallback(j=>{r(j.command),t("chat")},[r,t]);return n.jsx("div",{className:"flex-1 flex flex-col overflow-hidden bg-bg-primary",children:n.jsxs("div",{className:"flex-1 overflow-y-auto",children:[n.jsx("div",{className:"border-b border-border-default",children:n.jsxs("div",{className:"px-6 py-4",children:[n.jsxs("div",{className:"flex items-center justify-between mb-3",children:[n.jsxs("div",{children:[n.jsx("h2",{className:"text-lg font-semibold text-text-primary",children:e("scheduled.title")}),n.jsx("p",{className:"text-xs text-text-tertiary mt-0.5",children:e("scheduled.subtitle")})]}),n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx("button",{onClick:()=>d(),className:"p-2 rounded-lg border border-border-default text-text-secondary hover:text-text-primary hover:bg-bg-secondary transition-colors",title:e("tasks.refresh"),children:n.jsx(Ve,{size:14,className:l?"animate-spin":""})}),n.jsxs("button",{onClick:()=>u(!c),className:`flex items-center gap-1.5 px-3 py-1.5 rounded-lg border text-sm transition-colors ${c?"border-accent-brand/50 text-accent-brand bg-accent-brand/5":"border-border-default text-text-secondary hover:text-text-primary hover:border-accent-brand/30"}`,children:[n.jsx(ot,{size:14}),e("scheduled.create")]})]})]}),c&&n.jsx("div",{className:"mb-3",children:n.jsx(uk,{onSubmit:a,onCancel:()=>u(!1)})}),l&&i.length===0?n.jsxs("div",{className:"py-8 text-center text-text-tertiary text-sm",children:[n.jsx(Ve,{size:16,className:"animate-spin mx-auto mb-2"}),e("scheduled.loading")]}):i.length===0?n.jsxs("div",{className:"py-8 text-center",children:[n.jsx(Dt,{size:32,className:"mx-auto mb-2 text-text-tertiary opacity-30"}),n.jsx("p",{className:"text-sm text-text-tertiary",children:e("scheduled.empty")}),n.jsx("p",{className:"text-xs text-text-tertiary mt-1",children:e("scheduled.emptyHint")})]}):n.jsx("div",{className:"space-y-2",children:i.map(j=>n.jsx(pk,{task:j,onDelete:o},j.id))})]})}),n.jsxs("div",{className:"px-6 py-4",children:[n.jsxs("div",{className:"flex items-center justify-between mb-3",children:[n.jsxs("div",{children:[n.jsx("h2",{className:"text-lg font-semibold text-text-primary",children:e("tasks.title")}),n.jsx("p",{className:"text-xs text-text-tertiary mt-0.5",children:e("tasks.subtitle")})]}),n.jsxs("button",{onClick:L,disabled:m,className:`flex items-center gap-2 px-3 py-1.5 rounded-lg border text-sm transition-all ${f?"border-green-500/50 text-green-500":m?"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"}`,children:[f?n.jsx(Ht,{size:14}):n.jsx(Ve,{size:14,className:m?"animate-spin":""}),n.jsx("span",{children:e(f?"tasks.refreshed":"tasks.refresh")})]})]}),y&&!m&&n.jsx("div",{className:"flex flex-col items-center justify-center py-12 text-text-tertiary",children:n.jsx(pt,{size:"small",text:e("tasks.loading")})}),v&&!y&&n.jsxs("div",{className:"flex flex-col items-center justify-center py-12",children:[n.jsx("div",{className:"text-text-tertiary text-[48px] mb-4 opacity-30",children:"!"}),n.jsx("div",{className:"text-text-secondary text-sm mb-4",children:e("tasks.error")}),n.jsx("button",{onClick:L,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")})]}),!y&&p.length===0&&!v&&n.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-text-tertiary",children:[n.jsx(of,{size:32,className:"mb-2 opacity-30"}),n.jsx("div",{className:"text-sm",children:e("tasks.empty")})]}),p.length>0&&n.jsx("div",{className:`grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3 max-w-6xl transition-opacity duration-300 ${m?"opacity-50 pointer-events-none":"opacity-100"}`,children:p.map(j=>{const $=mk(j.icon);return n.jsxs("div",{onClick:()=>R(j),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:[n.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:n.jsx($,{size:20,className:"text-text-tertiary group-hover:text-accent-brand transition-colors"})}),n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsx("h3",{className:"text-sm font-semibold text-text-primary truncate",children:j.title}),n.jsx("p",{className:"text-xs text-text-tertiary mt-0.5 truncate",children:j.description})]})]},j.id)})})]})]})})}function mk(e){switch(e){case"Newspaper":return Od;case"MessageSquare":return Od;case"GitBranch":return fp;case"Package":return Ff;case"FileText":return ut;case"Zap":return nr;case"Clock":return Dt;default:return Dt}}function Vs({node:e,path:t}){const r=pe(i=>i.setRatio),s=C.useCallback(i=>{r(t,i)},[r,t]);return e.type==="leaf"?n.jsx(oi,{paneId:e.paneId}):n.jsxs(On,{direction:e.direction,ratio:e.ratio,onRatioChange:s,children:[n.jsx(Vs,{node:e.children[0],path:[...t,0]}),n.jsx(Vs,{node:e.children[1],path:[...t,1]})]})}function rm(){const e=pe(t=>t.layout);return n.jsx("div",{className:"flex-1 w-full h-full overflow-hidden",children:n.jsx(Vs,{node:e,path:[]})})}function gk({isOpen:e,onClose:t,onImageSelect:r,onFileSelect:s,onNewChat:i,onHistory:l,mainView:d}){const{t:a}=ne(),o=C.useRef(null),[c,u]=C.useState(null),[p,b]=C.useState(0),y=C.useCallback(()=>{r(),t()},[r,t]),k=C.useCallback(()=>{s(),t()},[s,t]),v=[{type:"attachment",icon:n.jsx(vp,{size:22}),label:a("input.menu.image"),action:y},{type:"attachment",icon:n.jsx(ut,{size:22}),label:a("input.menu.file"),action:k},{type:"action",icon:n.jsx(ot,{size:20}),label:a("chat.newChat"),action:i},{type:"action",icon:n.jsx(xp,{size:20}),label:a("sidebar.chatHistory"),action:l},{type:"nav",view:"changes",icon:n.jsx(Ln,{size:20}),label:a("sidebar.changes")},{type:"nav",view:"tasks",icon:n.jsx(ri,{size:20}),label:a("sidebar.nav.tasks")},{type:"nav",view:"terminal",icon:n.jsx(pr,{size:20}),label:a("sidebar.terminalMode")},{type:"nav",view:"plugins",icon:n.jsx(zt,{size:20}),label:a("sidebar.nav.plugins")},{type:"nav",view:"settings",icon:n.jsx(ii,{size:20}),label:a("sidebar.preferences")}].filter(E=>!(E.type==="action"&&!E.action)),g=8,m=Math.ceil(v.length/g),h=[];for(let E=0;E<m;E++)h.push(v.slice(E*g,(E+1)*g));C.useEffect(()=>{const E=o.current;if(!E)return;const _=()=>{const S=E.clientWidth;if(S>0){const w=Math.round(E.scrollLeft/S);b(w)}};return E.addEventListener("scroll",_,{passive:!0}),()=>E.removeEventListener("scroll",_)},[]);const f=C.useCallback(E=>{const _=o.current;_&&_.scrollTo({left:E*_.clientWidth,behavior:"smooth"})},[]),x=C.useCallback(()=>{u(null)},[]);return e?n.jsxs(n.Fragment,{children:[n.jsxs("div",{className:"bottom-sheet-inline",children:[n.jsx("div",{ref:o,className:"bottom-sheet-scroll",children:h.map((E,_)=>n.jsx("div",{className:"bottom-sheet-page",children:n.jsx("div",{className:"bottom-sheet-grid",children:E.map((S,w)=>n.jsxs("button",{className:S.type==="nav"&&d===S.view?"active":"",onClick:()=>{var N;S.type==="attachment"||S.type==="action"?(N=S.action)==null||N.call(S):S.type==="nav"&&S.view&&u(S.view)},children:[S.icon,n.jsx("span",{children:S.label})]},w))})},_))}),m>1&&n.jsx("div",{className:"bottom-sheet-pagination",children:Array.from({length:m}).map((E,_)=>n.jsx("button",{className:`pagination-dot ${_===p?"active":""}`,onClick:()=>f(_)},_))})]}),c&&n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"floating-panel-overlay",onClick:x}),n.jsxs("div",{className:"floating-panel-container",children:[n.jsx("div",{className:"floating-panel-header",children:n.jsx("button",{onClick:x,className:"floating-panel-close-btn",title:a("common.close"),children:n.jsx(Te,{size:24})})}),n.jsxs("div",{className:"floating-panel-content",children:[c==="changes"&&n.jsx(dh,{}),c==="tasks"&&n.jsx(tm,{}),c==="terminal"&&n.jsx(rm,{}),c==="plugins"&&n.jsx(Jh,{}),c==="settings"&&n.jsx(em,{})]})]})]})]}):null}const fk=5,nm=10*1024*1024,Ar=["image/jpeg","image/png","image/gif","image/webp"];let bk=0;function yk(e){return!Ar.includes(e.type)||e.size>nm?Promise.resolve(null):new Promise(t=>{const r=new FileReader;r.onload=()=>{const s=r.result,i=s.split(",")[1]||"";t({id:`img-${++bk}`,dataUrl:s,data:i,mimeType:e.type})},r.onerror=()=>t(null),r.readAsDataURL(e)})}const xk=10,vk=1*1024*1024,_k=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 Sk=0;function sm(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 i=t.slice(r);if(_k.has(i))return!0}const s=t.split("/").pop()||t;return!!["makefile","dockerfile","cmakelists.txt","gemfile","rakefile","procfile"].includes(s)}function kk(e){return!sm(e)||e.size>vk?Promise.resolve(null):new Promise(t=>{const r=new FileReader;r.onload=()=>{const s=r.result;t({id:`file-${++Sk}`,name:e.name,size:e.size,text:s,mimeType:e.type||"text/plain"})},r.onerror=()=>t(null),r.readAsText(e)})}function wk(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function Ek({onNavigate:e,onNewChat:t,onHistory:r,mainView:s,showBottomSheet:i=!1,setShowBottomSheet:l}){const d=C.useCallback(K=>{l&&l(typeof K=="function"?K(i):K)},[l,i]),[a,o]=C.useState(()=>window.innerWidth<=768),[c,u]=C.useState(""),[p,b]=C.useState([]),[y,k]=C.useState([]),[v,g]=C.useState(0),[m,h]=C.useState(!1),[f,x]=C.useState(null),[E,_]=C.useState(0),[S,w]=C.useState([]),[N,L]=C.useState(0),[R,j]=C.useState(null),$=C.useRef(null),G=C.useRef(null),F=C.useRef(null),W=C.useRef(null),V=C.useRef(null),q=C.useRef(null),A=C.useRef(null),T=C.useRef(null),D=C.useRef(0),I=C.useRef(!1),P=C.useRef(!1),{sessionId:M,commands:H,thinkingEnabled:z,setThinkingEnabled:U,promptSuggestion:O,setPromptSuggestion:Y,externalInput:X,setExternalInput:Q}=rt(),{isAgentRunning:J,hasPendingInterruption:re,timeline:ue,addUserMessage:de,addQueuedUserMessage:me,setSessionEnd:ie,resolveInterruption:Oe}=Me(),{t:_e,tryT:se}=ne();C.useEffect(()=>{X!==null&&(u(X),Q(null),Y(null),requestAnimationFrame(()=>{var K;(K=$.current)==null||K.focus()}))},[X,Q,Y]);const ce=C.useCallback(async K=>{const te=Array.from(K).filter(ge=>Ar.includes(ge.type)&&ge.size<=nm);if(te.length===0)return;g(ge=>ge+te.length);const ke=(await Promise.all(te.map(yk))).filter(ge=>ge!==null);g(ge=>Math.max(0,ge-te.length)),ke.length>0&&b(ge=>{const Fe=fk-ge.length;return[...ge,...ke.slice(0,Fe)]})},[]),Ee=C.useCallback(K=>{b(te=>te.filter(le=>le.id!==K))},[]),xe=C.useCallback(async K=>{const te=Array.from(K),ke=(await Promise.all(te.map(kk))).filter(ge=>ge!==null);ke.length!==0&&k(ge=>{const Fe=xk-ge.length;return[...ge,...ke.slice(0,Fe)]})},[]),Ze=C.useCallback(K=>{k(te=>te.filter(le=>le.id!==K))},[]),ee=C.useCallback(K=>{var te;K.preventDefault(),K.stopPropagation(),D.current++,(te=K.dataTransfer)!=null&&te.types.includes("Files")&&h(!0)},[]),oe=C.useCallback(K=>{K.preventDefault(),K.stopPropagation(),D.current--,D.current===0&&h(!1)},[]),fe=C.useCallback(K=>{K.preventDefault(),K.stopPropagation()},[]),$e=C.useCallback(K=>{var te;if(K.preventDefault(),K.stopPropagation(),D.current=0,h(!1),(te=K.dataTransfer)!=null&&te.files){const le=Array.from(K.dataTransfer.files),ke=le.filter(Fe=>Ar.includes(Fe.type)),ge=le.filter(Fe=>!Ar.includes(Fe.type)&&sm(Fe));ke.length>0&&ce(ke),ge.length>0&&xe(ge)}},[ce,xe]),Je=C.useCallback(K=>{var le;const te=(le=K.clipboardData)==null?void 0:le.files;te&&te.length>0&&Array.from(te).some(ge=>Ar.includes(ge.type))&&(K.preventDefault(),ce(te))},[ce]),Qe=C.useCallback(()=>{var K;(K=G.current)==null||K.click()},[]),ht=C.useCallback(()=>{var K;(K=F.current)==null||K.click()},[]),Se=C.useCallback(K=>{K.target.files&&ce(K.target.files),K.target.value=""},[ce]),qn=C.useCallback(K=>{K.target.files&&xe(K.target.files),K.target.value=""},[xe]),$t=C.useMemo(()=>{const K=c.trimStart();if(!K.startsWith("/")||K.includes(" "))return[];const te=K.substring(1).toLowerCase();return H.filter(le=>{const ke=se(`command.${le.name}.description`)??le.description;return le.name.toLowerCase().includes(te)||le.description.toLowerCase().includes(te)||ke.toLowerCase().includes(te)}).slice(0,8)},[c,H,se]),Et=$t.length>0;C.useEffect(()=>{_(0)},[$t.length]),C.useEffect(()=>{if(Et&&W.current){const K=W.current.children[E];K==null||K.scrollIntoView({block:"nearest"})}},[E,Et]);const Sr=C.useMemo(()=>{if(R===null)return null;const K=c.substring(R+1),te=K.search(/\s/),le=te===-1?K:K.substring(0,te);return te===0?null:le},[c,R]),Ct=Sr!==null&&S.length>0,kr=C.useRef(null);C.useEffect(()=>{if(Sr===null){w([]);return}return kr.current&&clearTimeout(kr.current),kr.current=setTimeout(async()=>{try{const K=new URLSearchParams;Sr&&K.set("query",Sr),K.set("limit","15");const te=await fetch(`/api/v1/fs/search?${K.toString()}`,{headers:ae()});if(te.ok){const le=await te.json();w(le.items||[]),L(0)}else w([])}catch{w([])}},150),()=>{kr.current&&clearTimeout(kr.current)}},[Sr]),C.useEffect(()=>{if(Ct&&V.current){const K=V.current.children[N];K==null||K.scrollIntoView({block:"nearest"})}},[N,Ct]);const Vn=C.useRef(!1),Kn=C.useCallback(K=>{if(R===null)return;const te=c.substring(0,R),le=c.substring(R+1),ke=le.search(/\s/),ge=ke===-1?"":le.substring(ke),mt=ge.length===0||!/^\s/.test(ge)?" ":"",Mt=`${te}@${K.path}${mt}${ge}`,wr=te.length+1+K.path.length+mt.length;u(Mt),w([]),j(null),Vn.current=!0,requestAnimationFrame(()=>{const Yt=$.current;Yt&&(Yt.focus(),Yt.setSelectionRange(wr,wr))})},[c,R]);C.useEffect(()=>{const K=()=>o(window.innerWidth<=768);return window.addEventListener("resize",K),()=>window.removeEventListener("resize",K)},[]),C.useEffect(()=>{var K;!a&&!J&&((K=$.current)==null||K.focus())},[a,J]),C.useEffect(()=>{const K=$.current;if(K){K.style.height="auto";const te=window.innerHeight*.2,le=Math.min(K.scrollHeight,te);K.style.height=`${le}px`,K.style.overflowY=K.scrollHeight>te?"auto":"hidden"}},[c]);const Yn=C.useCallback(K=>{var te;u(`/${K.name} `),(te=$.current)==null||te.focus()},[]),jt=C.useCallback(async K=>{var vd;const te=(K??c).trim(),le=p.length>0,ke=y.length>0;if(!te&&!(le||ke)||!M||re)return;u(""),Y(null);const Fe=[...p],mt=[...y];b([]),k([]);const Mt=Fe.length>0?Fe.map(Ie=>({data:Ie.data,mimeType:Ie.mimeType})):void 0,wr=mt.length>0?mt.map(Ie=>({name:Ie.name,text:Ie.text,mimeType:Ie.mimeType})):void 0,Yt=mt.length>0?mt.map(Ie=>({name:Ie.name,size:Ie.size,mimeType:Ie.mimeType})):void 0;if((vd=$.current)==null||vd.blur(),J)me(te,Mt,Yt),Re().prompt(M,te,Mt,wr).catch(Ie=>{console.error("Queued prompt failed:",Ie)});else{if(P.current)return;P.current=!0,de(te,Mt,Yt);try{const Ie=await Re().prompt(M,te,Mt,wr);ie(Ie.stopReason,Ie.errorMessage,Ie.errorCategory)}catch(Ie){console.error("Prompt failed:",Ie),ie("error",Ie instanceof Error?Ie.message:_e("input.promptFailed"))}finally{P.current=!1}}},[c,p,y,M,J,re,de,me,ie,Y,_e]),lm=C.useCallback(async()=>{if(M)try{const K=Re(),te=ue.filter(le=>le.type==="interruption"&&!le.resolved);for(const le of te)if(le.type==="interruption")try{await K.respondToInterruption(M,le.id,"deny",le.toolCallId),Oe(le.id,"deny")}catch{}await K.cancel(M)}catch(K){console.error("Cancel failed:",K)}},[M,ue,Oe]),cm=C.useCallback(()=>{I.current=!0},[]),dm=C.useCallback(()=>{I.current=!1},[]),um=C.useCallback(K=>{K.preventDefault(),x({x:K.clientX,y:K.clientY})},[]),pm=C.useCallback(()=>{const K=$.current;if(!K)return;const te=K.selectionStart??c.length,le=K.selectionEnd??te,ke=c.slice(0,te)+`
|
|
689
689
|
`+c.slice(le);u(ke),x(null),requestAnimationFrame(()=>{K.selectionStart=K.selectionEnd=te+1,K.focus()})},[c]),hm=C.useCallback(()=>{x(null),jt()},[jt]);C.useEffect(()=>{if(!f)return;const K=()=>x(null),te=()=>x(null);return document.addEventListener("mousedown",K),document.addEventListener("scroll",te,!0),()=>{document.removeEventListener("mousedown",K),document.removeEventListener("scroll",te,!0)}},[f]),C.useEffect(()=>{if(!Et)return;const K=te=>{W.current&&!W.current.contains(te.target)&&u("")};return document.addEventListener("mousedown",K),()=>document.removeEventListener("mousedown",K)},[Et]),C.useEffect(()=>{if(!i)return;const K=te=>{const le=te.target;A.current&&!A.current.contains(le)&&T.current&&!T.current.contains(le)&&d(!1)};return document.addEventListener("mousedown",K),()=>document.removeEventListener("mousedown",K)},[i,d]),C.useEffect(()=>{if(!Ct)return;const K=te=>{V.current&&!V.current.contains(te.target)&&(j(null),w([]))};return document.addEventListener("mousedown",K),()=>document.removeEventListener("mousedown",K)},[Ct]);const mm=C.useCallback(K=>{if(Et){if(K.key==="ArrowUp"){K.preventDefault(),_(te=>te>0?te-1:$t.length-1);return}if(K.key==="ArrowDown"){K.preventDefault(),_(te=>te<$t.length-1?te+1:0);return}if(K.key==="Tab"||K.key==="Enter"&&!K.shiftKey&&!I.current&&!K.nativeEvent.isComposing){K.preventDefault(),Yn($t[E]);return}if(K.key==="Escape"){K.preventDefault(),u("");return}}if(Ct){if(K.key==="ArrowUp"){K.preventDefault(),L(te=>te>0?te-1:S.length-1);return}if(K.key==="ArrowDown"){K.preventDefault(),L(te=>te<S.length-1?te+1:0);return}if(K.key==="Tab"||K.key==="Enter"&&!K.shiftKey&&!I.current&&!K.nativeEvent.isComposing){K.preventDefault(),Kn(S[N]);return}if(K.key==="Escape"){K.preventDefault(),j(null),w([]);return}}if(K.key==="Tab"&&!Et&&!Ct&&O&&!c){K.preventDefault(),u(O),Y(null);return}if(K.key==="Enter"&&!K.shiftKey&&!I.current&&!K.nativeEvent.isComposing){if(K.preventDefault(),!c&&O&&!J&&!re){jt(O);return}jt()}},[jt,Et,$t,E,Yn,Ct,S,N,Kn,O,c,Y,J,re]),gm=C.useCallback(async()=>{if(!M)return;const K=!z;U(K);try{await Re().setConfigOption(M,"thought_level",K?"enabled":"disabled")}catch(te){U(!K),console.error("Toggle thinking failed:",te)}},[M,z,U]),xd=!re&&(c.trim().length>0||p.length>0||y.length>0||!!O&&!c&&!J),fm=p.length>0||y.length>0||v>0;return n.jsx("div",{className:"px-0 pb-[env(safe-area-inset-bottom)] pt-0 md:px-4 md:pb-6 md:pt-2",children:n.jsxs("div",{className:"max-w-3xl mx-auto",children:[e&&s!==void 0&&n.jsx("div",{ref:A,children:n.jsx(gk,{isOpen:i,onClose:()=>d(!1),onImageSelect:Qe,onFileSelect:ht,onNewChat:t,onHistory:r,mainView:s,onNavigate:e})}),n.jsxs("div",{className:`relative bg-bg-secondary rounded-none md:rounded-2xl shadow-sm transition-all focus-within:shadow-md border-t md:border ${m?"border-accent-brand border-dashed bg-accent-brand/5":"border-border-default"}`,onDragEnter:ee,onDragLeave:oe,onDragOver:fe,onDrop:$e,children:[m&&n.jsx("div",{className:"absolute inset-0 z-20 rounded-2xl flex items-center justify-center bg-accent-brand/5 pointer-events-none",children:n.jsx("span",{className:"text-accent-brand text-[14px] font-medium",children:_e("input.dropHint")})}),Et&&n.jsx("div",{ref:W,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 py-1",children:$t.map((K,te)=>n.jsxs("button",{className:`w-full text-left px-3 py-2 flex items-baseline gap-3 transition-colors ${te===E?"bg-bg-primary text-text-primary":"text-text-primary hover:bg-bg-primary"}`,onMouseEnter:()=>_(te),onMouseDown:le=>{le.preventDefault(),Yn(K)},children:[n.jsxs("span",{className:"font-mono text-[13px] font-medium shrink-0",children:["/",K.name]}),K.type==="skill"&&n.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"}),n.jsx("span",{className:"text-text-tertiary text-[12px] truncate",children:se(`command.${K.name}.description`)??K.description})]},K.name))}),Ct&&n.jsx("div",{ref:V,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 py-1",children:S.map((K,te)=>n.jsxs("button",{className:`w-full text-left px-3 py-2 flex items-center gap-3 transition-colors ${te===N?"bg-bg-primary text-text-primary":"text-text-primary hover:bg-bg-primary"}`,onMouseEnter:()=>L(te),onMouseDown:le=>{le.preventDefault(),Kn(K)},children:[K.type==="directory"?n.jsx(ti,{size:14,className:"shrink-0 text-accent-brand"}):n.jsx(ut,{size:14,className:"shrink-0 text-text-tertiary"}),n.jsx("span",{className:"font-mono text-[13px] truncate",children:K.name}),n.jsx("span",{className:"text-text-tertiary text-[11px] truncate ml-auto",children:K.path})]},K.path))}),fm&&n.jsxs("div",{className:"px-4 pt-3 pb-1 flex flex-wrap gap-2",children:[p.map(K=>n.jsxs("div",{className:"relative group",children:[n.jsx("img",{src:K.dataUrl,alt:"",className:"w-16 h-16 rounded-lg object-cover border border-border-default"}),n.jsx("button",{onClick:()=>Ee(K.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:n.jsx(Te,{size:12})})]},K.id)),Array.from({length:v}).map((K,te)=>n.jsx("div",{className:"w-16 h-16 rounded-lg border border-border-default skeleton-shimmer"},`skeleton-${te}`)),y.map(K=>n.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:[n.jsx(ut,{size:16,className:"shrink-0 text-text-tertiary"}),n.jsxs("div",{className:"min-w-0 flex-1",children:[n.jsx("div",{className:"text-[12px] text-text-primary truncate",title:K.name,children:K.name}),n.jsx("div",{className:"text-[11px] text-text-tertiary",children:wk(K.size)})]}),n.jsx("button",{onClick:()=>Ze(K.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:n.jsx(Te,{size:12})})]},K.id))]}),n.jsxs("div",{className:"relative",children:[n.jsx("textarea",{ref:$,value:c,onChange:K=>{const te=K.target.value,le=K.target.selectionStart??te.length;if(u(te),Vn.current){Vn.current=!1;return}let ke=null;for(let ge=le-1;ge>=0;ge--){const Fe=te[ge];if(Fe==="@"){const mt=ge>0?te[ge-1]:" ";(mt===" "||mt===`
|
|
690
690
|
`||ge===0)&&(te.substring(ge+1,le).includes(" ")||(ke=ge));break}if(Fe===" "||Fe===`
|
|
691
691
|
`)break}ke!==null?R!==ke&&(j(ke),L(0)):R!==null&&(j(null),w([]))},onCompositionStart:cm,onCompositionEnd:dm,onKeyDown:mm,onPaste:Je,onContextMenu:um,onFocus:()=>d(!1),placeholder:re?_e("input.placeholderPending"):J?_e("input.placeholderRunning"):O?"":_e("input.placeholder"),enterKeyHint:"send",rows:1,"aria-label":"Message input",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(" ")}),O&&!c&&!J&&!re&&n.jsx("div",{className:"absolute inset-0 flex items-start px-5 pt-4 pb-2 pointer-events-none overflow-hidden",children:n.jsx("span",{className:"text-[15px] leading-relaxed text-text-tertiary truncate max-w-full",children:O})})]}),f&&n.jsxs("div",{ref:q,className:"fixed z-50 bg-bg-secondary rounded-xl border border-border-default shadow-lg overflow-hidden min-w-[120px]",style:{left:f.x,top:f.y},onMouseDown:K=>K.stopPropagation(),children:[n.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:K=>{K.preventDefault(),K.stopPropagation(),pm()},children:[n.jsx(Ld,{size:14,className:"text-text-tertiary"}),_e("input.contextMenu.newline")]}),xd&&n.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:K=>{K.preventDefault(),K.stopPropagation(),hm()},children:[n.jsx(Es,{size:14,className:"text-text-tertiary"}),_e("input.contextMenu.send")]})]}),n.jsx("input",{ref:G,type:"file",accept:"image/jpeg,image/png,image/gif,image/webp",multiple:!0,className:"hidden",onChange:Se}),n.jsx("input",{ref:F,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:qn}),n.jsxs("div",{className:"flex items-center justify-between px-3 py-2",onClick:K=>{var te;K.target===K.currentTarget&&((te=$.current)==null||te.focus())},children:[n.jsx("div",{className:"flex items-center",children:n.jsxs("button",{onClick:gm,className:`flex items-center gap-1 px-2.5 py-1 rounded-full border transition-colors ${z?"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:[n.jsx("span",{className:"w-3.5 h-3.5 flex items-center justify-center text-[10px] font-semibold",children:"∞"}),n.jsx("span",{className:"text-[12px] font-medium",children:_e("input.deepThinking")})]})}),n.jsxs("div",{className:"flex items-center gap-1",children:[!J&&n.jsx("button",{ref:T,onClick:()=>d(K=>!K),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:_e("input.addFile"),children:n.jsx(ot,{size:18})}),a&&n.jsx("button",{onClick:()=>{const K=$.current;if(!K)return;const te=K.selectionStart??c.length,le=K.selectionEnd??te,ke=c.slice(0,te)+`
|