@tencent-ai/codebuddy-code 2.137.1-dev.06080a1.202608181343 → 2.137.1-dev.ff5b760.202608181454

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.
Files changed (43) hide show
  1. package/dist/codebuddy-headless.js +5 -5
  2. package/dist/codebuddy.js +6 -6
  3. package/dist/web-ui/assets/{CanvasPaneStandaloneView-zfXxWldi.js → CanvasPaneStandaloneView-D-16hIRq.js} +1 -1
  4. package/dist/web-ui/assets/{CanvasView-C1zt0xeq.js → CanvasView-Cmy_OwhG.js} +1 -1
  5. package/dist/web-ui/assets/{DocsView-BY-czkuI.js → DocsView-D7ltd1Cn.js} +1 -1
  6. package/dist/web-ui/assets/{EditorView-DYhVx-By.js → EditorView-DabwBpf2.js} +4 -4
  7. package/dist/web-ui/assets/{KeybindingsView-CmZBQZ08.js → KeybindingsView-DyEXBinT.js} +1 -1
  8. package/dist/web-ui/assets/{LogsView-CEkiw-ej.js → LogsView-DIUDc9aM.js} +1 -1
  9. package/dist/web-ui/assets/{MetricsView-BAiZLSTx.js → MetricsView-Bsob5-BK.js} +1 -1
  10. package/dist/web-ui/assets/{RemoteControlView-CkEGw9Rf.js → RemoteControlView-Bxl8WsqR.js} +1 -1
  11. package/dist/web-ui/assets/{StatsView-WoO5FWv8.js → StatsView-DvKDHaY1.js} +1 -1
  12. package/dist/web-ui/assets/{TracesView-fTXf2HNv.js → TracesView-RT1cgwUv.js} +1 -1
  13. package/dist/web-ui/assets/{WorkersView-B4GA22wu.js → WorkersView-Cv62Qqhl.js} +1 -1
  14. package/dist/web-ui/assets/{canvas-store-CHBKvXUv.js → canvas-store-CU9idWxO.js} +1 -1
  15. package/dist/web-ui/assets/{cssMode-t95y0VvC.js → cssMode-C1Xy-pGH.js} +1 -1
  16. package/dist/web-ui/assets/{editor.main-BuKvQHbu.js → editor.main-ClnGNr0F.js} +3 -3
  17. package/dist/web-ui/assets/{freemarker2-B5nIbzcO.js → freemarker2-CEuj96J6.js} +1 -1
  18. package/dist/web-ui/assets/{handlebars-CJ1X0Wkb.js → handlebars-CCtral8C.js} +1 -1
  19. package/dist/web-ui/assets/{html-C5ysU8Zs.js → html-C_tyZ8wA.js} +1 -1
  20. package/dist/web-ui/assets/{htmlMode-hdvHdMIV.js → htmlMode-C1H7A14A.js} +1 -1
  21. package/dist/web-ui/assets/{index-cl1GS6Hx.js → index-13j4cK6E.js} +4 -4
  22. package/dist/web-ui/assets/{javascript-DHVWRK-u.js → javascript-DH2SY8bg.js} +1 -1
  23. package/dist/web-ui/assets/{jsonMode-BezIdJsH.js → jsonMode-DRzudXvG.js} +1 -1
  24. package/dist/web-ui/assets/{liquid-DvJFXfRS.js → liquid-3eKUnGqD.js} +1 -1
  25. package/dist/web-ui/assets/{lspLanguageFeatures-BN1JiD5D.js → lspLanguageFeatures-Byww3fZ1.js} +1 -1
  26. package/dist/web-ui/assets/{mdx-DnStEace.js → mdx-vvilG4uu.js} +1 -1
  27. package/dist/web-ui/assets/{minus-BaRykPkI.js → minus-B4FdYLU4.js} +1 -1
  28. package/dist/web-ui/assets/{python-BOBIG9Di.js → python-Bk1QBpLK.js} +1 -1
  29. package/dist/web-ui/assets/{razor-BZQcVgfK.js → razor-i0Iz7o4r.js} +1 -1
  30. package/dist/web-ui/assets/{server-CZfmU7si.js → server-BDf20Hy5.js} +1 -1
  31. package/dist/web-ui/assets/{tsMode-BwUuVJUe.js → tsMode-DTDeYfse.js} +1 -1
  32. package/dist/web-ui/assets/{typescript-B9TczXLg.js → typescript-2HSmcnEt.js} +1 -1
  33. package/dist/web-ui/assets/{worker-store-BigbFW9j.js → worker-store-B3vmTQZb.js} +1 -1
  34. package/dist/web-ui/assets/{xml-BEXHIq5N.js → xml-CsH6BKZL.js} +1 -1
  35. package/dist/web-ui/assets/{yaml-CQQPLZO4.js → yaml-BICoCEJ7.js} +1 -1
  36. package/dist/web-ui/index.html +1 -1
  37. package/dist/web-ui/sw.js +1 -1
  38. package/package.json +1 -1
  39. package/product.cloudhosted.json +2 -2
  40. package/product.internal.json +2 -2
  41. package/product.ioa.json +2 -2
  42. package/product.json +2 -2
  43. package/product.selfhosted.json +2 -2
@@ -1,4 +1,4 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/editor.main-BuKvQHbu.js","assets/editor-B_19GPAS.css","assets/CanvasPaneStandaloneView-zfXxWldi.js","assets/markdown-DIY6o85n.js","assets/canvas-store-CHBKvXUv.js","assets/vendor-D35k0Cos.js","assets/CanvasView-C1zt0xeq.js","assets/minus-BaRykPkI.js","assets/DocsView-BY-czkuI.js","assets/EditorView-DYhVx-By.js","assets/KeybindingsView-CmZBQZ08.js","assets/LogsView-CEkiw-ej.js","assets/worker-store-BigbFW9j.js","assets/MetricsView-BAiZLSTx.js","assets/server-CZfmU7si.js","assets/RemoteControlView-CkEGw9Rf.js","assets/StatsView-WoO5FWv8.js","assets/TracesView-fTXf2HNv.js","assets/WorkersView-B4GA22wu.js"])))=>i.map(i=>d[i]);
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/editor.main-ClnGNr0F.js","assets/editor-B_19GPAS.css","assets/CanvasPaneStandaloneView-D-16hIRq.js","assets/markdown-DIY6o85n.js","assets/canvas-store-CU9idWxO.js","assets/vendor-D35k0Cos.js","assets/CanvasView-Cmy_OwhG.js","assets/minus-B4FdYLU4.js","assets/DocsView-D7ltd1Cn.js","assets/EditorView-DabwBpf2.js","assets/KeybindingsView-DyEXBinT.js","assets/LogsView-DIUDc9aM.js","assets/worker-store-B3vmTQZb.js","assets/MetricsView-Bsob5-BK.js","assets/server-BDf20Hy5.js","assets/RemoteControlView-Bxl8WsqR.js","assets/StatsView-DvKDHaY1.js","assets/TracesView-RT1cgwUv.js","assets/WorkersView-Cv62Qqhl.js"])))=>i.map(i=>d[i]);
2
2
  var SR=Object.defineProperty;var Lw=e=>{throw TypeError(e)};var kR=(e,t,n)=>t in e?SR(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var we=(e,t,n)=>kR(e,typeof t!="symbol"?t+"":t,n),Lh=(e,t,n)=>t.has(e)||Lw("Cannot "+n);var B=(e,t,n)=>(Lh(e,t,"read from private field"),n?n.call(e):t.get(e)),ht=(e,t,n)=>t.has(e)?Lw("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),He=(e,t,n,r)=>(Lh(e,t,"write to private field"),r?r.call(e,n):t.set(e,n),n),Te=(e,t,n)=>(Lh(e,t,"access private method"),n);var Yc=(e,t,n,r)=>({set _(i){He(e,t,i,n)},get _(){return B(e,t,r)}});import{W as Wn,a as g,j as l,f as AR,p as Mw,b as Dw,n as $w,h as CR,s as ER,d as Ow,M as Yo,c as Zo}from"./markdown-DIY6o85n.js";import{r as y1}from"./vendor-D35k0Cos.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))r(i);new MutationObserver(i=>{for(const s of i)if(s.type==="childList")for(const a of s.addedNodes)a.tagName==="LINK"&&a.rel==="modulepreload"&&r(a)}).observe(document,{childList:!0,subtree:!0});function n(i){const s={};return i.integrity&&(s.integrity=i.integrity),i.referrerPolicy&&(s.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?s.credentials="include":i.crossOrigin==="anonymous"?s.credentials="omit":s.credentials="same-origin",s}function r(i){if(i.ep)return;i.ep=!0;const s=n(i);fetch(i.href,s)}})();const _1="codebuddy.agent-frame-state",IR=3e3;function TR(e){if(!e||typeof e!="object")return!1;const t=e;return t.type===_1&&(t.sessionId===null||typeof t.sessionId=="string")&&(t.topic===null||typeof t.topic=="string")&&(t.needsInput===void 0||typeof t.needsInput=="boolean")}function NR(e){const t=e==null?void 0:e.trim().toLowerCase();if(t)return t.startsWith("[")&&t.endsWith("]")?t.slice(1,-1):t}function RR(e){const t=e.trim().toLowerCase();return t?t==="localhost"||t==="0.0.0.0"||/^(?:\d{1,3}\.){3}\d{1,3}$/.test(t)?!0:t.includes(":"):!1}function LR(e,t){const n=NR(t);if(!n)return e;try{const r=new URL(e);return r.protocol!=="http:"&&r.protocol!=="https:"||r.hostname===n||!RR(r.hostname)?e:(r.hostname=n,r.toString())}catch{return e}}function MR(e){return!!e}function Ji(e){const t=typeof window>"u"?"":window.location.search;return new URLSearchParams(t).get("embedded")==="agent"}const Pw=new Set(["codebuddy.auth.token"]);function DR(e,t,n){return n.has(e)?e:`${t}${e}`}const Bw=new WeakSet;function jw(e,t,n=new Set){if(Bw.has(e))return;Bw.add(e);const r=e.getItem.bind(e),i=e.setItem.bind(e),s=e.removeItem.bind(e),a=e.key.bind(e),o=d=>DR(d,t,n),c=()=>{const d=[];for(let u=0;u<e.length;u++){const h=a(u);h&&!n.has(h)&&h.startsWith(t)&&d.push(h)}for(const u of d)s(u)};try{Object.defineProperty(e,"getItem",{configurable:!0,value:d=>r(o(d))}),Object.defineProperty(e,"setItem",{configurable:!0,value:(d,u)=>{i(o(d),u)}}),Object.defineProperty(e,"removeItem",{configurable:!0,value:d=>{s(o(d))}}),Object.defineProperty(e,"clear",{configurable:!0,value:()=>{c()}})}catch{e.getItem=d=>r(o(d)),e.setItem=(d,u)=>{i(o(d),u)},e.removeItem=d=>{s(o(d))},e.clear=()=>{c()}}}function $R(){var t,n;return`cb-embed:${((n=(t=v1(typeof window>"u"?"":window.location.pathname))==null?void 0:t.match(/\/jobs\/([^/]+)\//))==null?void 0:n[1])??"embed"}:`}function OR(){if(!(typeof window>"u")){if(Ji()){const e=$R();jw(window.sessionStorage,e,Pw),jw(window.localStorage,e,Pw)}x1()}}function v1(e){const t=e.match(/^(\/api\/v1\/jobs\/[^/]+\/frame)(?:\/|$)/);return t?t[1].replace(/\/$/,""):null}let Fw=!1;function x1(){if(Fw||typeof window>"u")return;const e=v1(window.location.pathname);if(!e)return;const t=e;Fw=!0;const n=window.fetch.bind(window);window.fetch=(a,o)=>n(PR(a,t),o);const r=XMLHttpRequest.prototype.open;XMLHttpRequest.prototype.open=function(a,o,c,d,u){return r.call(this,a,vo(String(o),t),c??!0,d,u)};const i=window.WebSocket;window.WebSocket=class extends i{constructor(a,o){super(vo(String(a),t),o)}};const s=window.EventSource;typeof s=="function"&&(window.EventSource=class extends s{constructor(a,o){super(vo(String(a),t),o)}})}function PR(e,t){if(typeof e=="string")return vo(e,t);if(e instanceof URL)return new URL(vo(e.href,t));const n=vo(e.url,t);return n===e.url?e:new Request(n,e)}function vo(e,t){try{const n=new URL(e,typeof window>"u"?"http://localhost":window.location.href),r=typeof window>"u"?n.hostname:window.location.hostname;if(n.hostname!==r||n.pathname===t||n.pathname.startsWith(`${t}/`))return e;if(BR(n.pathname))return n.pathname=`${t}${n.pathname}`,n.toString()}catch{return e}return e}function BR(e){return e==="/api/v1/acp"||e.startsWith("/api/v1/acp/")||e==="/api/v1/goal"||e.startsWith("/api/v1/goal/")||e==="/internal"||e.startsWith("/internal/")}function Uw(e,t,n,r,i,s,a){const o=MR(a);if(o&&!a)throw new Error("Missing agent job id");if(!o&&!e)throw new Error("Missing agent Web URL");const c=o?new URL(`/api/v1/jobs/${encodeURIComponent(a)}/frame/`,"http://agent-frame.local"):new URL(LR(e,s));if(c.protocol!=="http:"&&c.protocol!=="https:")throw new Error(`Unsupported agent Web URL protocol: ${c.protocol}`);if(c.searchParams.set("embedded","agent"),c.searchParams.set("sessionId",t),c.searchParams.set("folder",n),i?c.searchParams.set("theme",i):c.searchParams.delete("theme"),o){if(c.searchParams.delete("token"),e)try{c.searchParams.set("_ep",new URL(e).port||new URL(e).hostname)}catch{}return c.hash="/chat",`${c.pathname}${c.search}${c.hash}`}return r?c.searchParams.set("token",r):c.searchParams.delete("token"),c.hash="/chat",c.toString()}function jR(e,t=!1,n=Date.now()){if(!e.sessionId||e.webUrl||e.foregroundHeld||e.alive)return null;if(e.state==="done"||e.state==="failed"||e.state==="stopped"||e.settled===!0||e.tempo==="idle"||!t)return 0;const i=Number.isFinite(e.startedAt)?e.startedAt:0;return Math.max(0,IR-(n-i))}function FR(e,t,n){if(!Number.isFinite(e)||e<0)return t;const r=2**Math.floor(e);return Math.min(t*r,n)}const UR=1600;function zw(e){var t;try{return new URL(e,"http://agent-frame.local").pathname}catch{return((t=e.split("?")[0])==null?void 0:t.split("#")[0])??""}}function Hw(e,t){if(!e)return"dead";try{const n=e.contentWindow;if(!n)return"dead";const r=e.contentDocument;if(!r)return"opaque";const i=n.location.href;if(!i||i==="about:blank")return"dead";if(r.readyState!=="complete")return"pending";if(t&&n.location.pathname&&!n.location.pathname.startsWith(t.replace(/\/$/,"")))return"dead";const s=r.body;return!r.documentElement||!s?"dead":s.childElementCount===0&&!s.innerHTML.trim()?"pending":"alive"}catch{return"opaque"}}function zR(e,t=Date.now()){const n=new URL(e,"http://agent-frame.local");return n.searchParams.set("_r",String(t)),e.startsWith("http://")||e.startsWith("https://")?n.toString():`${n.pathname}${n.search}${n.hash}`}function HR(e){const t=new URL(e,"http://agent-frame.local");return t.searchParams.delete("_r"),e.startsWith("http://")||e.startsWith("https://")?t.toString():`${t.pathname}${t.search}${t.hash}`}const GR=120;function WR(e){return{display:"block",opacity:e?1:0,pointerEvents:e?"auto":"none",zIndex:e?1:0,transition:`opacity ${GR}ms ease`,willChange:"opacity",transform:"translateZ(0)"}}function qR(e){return e.showingAgentStage&&!e.newJobMode&&e.loaded&&e.jobId===e.selectedJobId}function VR(e){return e?{display:"flex"}:{display:"flex",position:"absolute",inset:0,opacity:0,pointerEvents:"none",zIndex:0}}OR();const Gw=e=>{let t;const n=new Set,r=(d,u)=>{const h=typeof d=="function"?d(t):d;if(!Object.is(h,t)){const p=t;t=u??(typeof h!="object"||h===null)?h:Object.assign({},t,h),n.forEach(m=>m(t,p))}},i=()=>t,o={setState:r,getState:i,getInitialState:()=>c,subscribe:d=>(n.add(d),()=>n.delete(d))},c=t=e(r,i,o);return o},QR=(e=>e?Gw(e):Gw),KR=e=>e;function YR(e,t=KR){const n=Wn.useSyncExternalStore(e.subscribe,Wn.useCallback(()=>t(e.getState()),[e,t]),Wn.useCallback(()=>t(e.getInitialState()),[e,t]));return Wn.useDebugValue(n),n}const Ww=e=>{const t=QR(e),n=r=>YR(t,r);return Object.assign(n,t),n},Rt=(e=>e?Ww(e):Ww),ZR="modulepreload",JR=function(e){return"/"+e},qw={},Ct=function(t,n,r){let i=Promise.resolve();if(n&&n.length>0){let a=function(d){return Promise.all(d.map(u=>Promise.resolve(u).then(h=>({status:"fulfilled",value:h}),h=>({status:"rejected",reason:h}))))};document.getElementsByTagName("link");const o=document.querySelector("meta[property=csp-nonce]"),c=(o==null?void 0:o.nonce)||(o==null?void 0:o.getAttribute("nonce"));i=a(n.map(d=>{if(d=JR(d),d in qw)return;qw[d]=!0;const u=d.endsWith(".css"),h=u?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${d}"]${h}`))return;const p=document.createElement("link");if(p.rel=u?"stylesheet":ZR,u||(p.as="script"),p.crossOrigin="",p.href=d,c&&p.setAttribute("nonce",c),document.head.appendChild(p),u)return new Promise((m,f)=>{p.addEventListener("load",m),p.addEventListener("error",()=>f(new Error(`Unable to preload CSS for ${d}`)))})}))}function s(a){const o=new Event("vite:preloadError",{cancelable:!0});if(o.payload=a,window.dispatchEvent(o),!o.defaultPrevented)throw a}return i.then(a=>{for(const o of a||[])o.status==="rejected"&&s(o.reason);return t().catch(s)})},w1="This topic is currently outside the scope of my capabilities, so I'm unable to discuss it further.",Vw="codebuddy.ai/errorMessage",Qw="codebuddy.ai/finishReason",XR="codebuddy.ai/contentFilterNotice";function eL(e){return(e==null?void 0:e[XR])===!0}function au(e){return(e==null?void 0:e.trim())===w1}function tL(e){return e==="content_filter"||e==="content-filter"||e==="refusal"}function nL(e){return e.errorCategory==="content_filter"||e.errorCategory==="model_safety"||tL(e.finishReason)?!0:au(e.errorMessage)}function rL(e){const t=e.trim();return!(!t||t.startsWith("{")&&t.endsWith("}")||/^internal error\b/i.test(t)||/^unknown error\b/i.test(t)||/^request cancelled\b/i.test(t))}function iL(e){try{const t=JSON.parse(e);if(!t||typeof t!="object")return{details:e};const n=t.data&&typeof t.data=="object"?t.data:void 0,r=typeof(n==null?void 0:n.details)=="string"?n.details:typeof t.details=="string"?t.details:void 0,i=typeof t.message=="string"?t.message:void 0,s=typeof(n==null?void 0:n.category)=="string"?n.category:void 0;return{details:r,message:i,category:s}}catch{return{details:e}}}function Vg(e){if(!e)return{};const t=e._meta,n=e.finishReason??(typeof(t==null?void 0:t[Qw])=="string"?t[Qw]:void 0),r=typeof e.errorMessage=="string"&&e.errorMessage.length>0?e.errorMessage:typeof(t==null?void 0:t[Vw])=="string"?t[Vw]:void 0;if(!r)return{category:e.errorCategory,finishReason:n};const i=iL(r);return{...i,category:i.category??e.errorCategory,finishReason:n}}function Qg(e){for(const t of[e.details,e.message])if(t&&rL(t))return t}function Kw(e){const t=Vg(e);return{...e,errorMessage:Qg(t),errorCategory:t.category??e.errorCategory,finishReason:t.finishReason??e.finishReason}}function sL(e,t){switch(e){case"network":return t("chat.error.network");case"auth":case"custom_model_auth":return t("chat.error.auth");case"quota":return t("chat.error.quota");case"model_service":return t("chat.error.modelService");case"cancelled":return t("chat.error.cancelled");default:return t("chat.error.refusal")}}function aL(e,t,n){var c;const r=e.stopReason;if(!r||r==="end_turn"||r==="cancelled")return null;if(r==="max_tokens")return t("chat.error.maxTokens");if(r==="max_turn_requests")return t("chat.error.maxTurnRequests");const i=Vg({errorMessage:e.errorMessage??void 0,errorCategory:e.errorCategory??void 0,finishReason:e.finishReason??void 0}),s=e.errorCategory||i.category,a=e.finishReason||i.finishReason,o=Qg({...i,details:i.details??e.errorMessage??void 0});if(nL({errorCategory:s,finishReason:a,errorMessage:o??e.errorMessage})){const d=t("message.contentFilter.notice"),u=(c=n==null?void 0:n.lastAssistantContent)==null?void 0:c.trim();return u&&(au(u)||u===d)?null:d}return o&&!au(o)?o:r==="refusal"?sL(s,t):o||t("chat.stopped")}function qp(e){const t=[`event=${e.event}`];for(const[n,r]of Object.entries(e))n==="event"||r===void 0||t.push(`${n}=${typeof r=="string"?r:JSON.stringify(r)}`);t.push(`t=${new Date().toISOString()}`),console.debug(`[McpUiDiag] ${t.join(" ")}`)}class Qs extends Error{constructor(t="Queued ACP prompt was cancelled before dispatch"){super(t),this.name="AcpPromptQueueCancelledError"}}const oL=1,ou="codebuddy.last-session-id";function lL(){try{return Ji()||typeof localStorage>"u"?null:localStorage.getItem(ou)}catch{return null}}function Yw(e){return{...e.agents?{agents:e.agents}:{},...e.currentAgentName!==void 0?{currentAgentName:e.currentAgentName}:{},...e.defaultAgentName!==void 0?{defaultAgentName:e.defaultAgentName}:{},...e.sessionBlank!==void 0?{sessionBlank:e.sessionBlank}:{}}}function _l(e){try{if(Ji())return;localStorage==null||localStorage.setItem(ou,e)}catch{}}function cL(e){try{if(Ji())return;(typeof localStorage>"u"||!e||localStorage.getItem(ou)===e)&&(localStorage==null||localStorage.removeItem(ou))}catch{}}class Hu extends Error{constructor(n,r){super(n.message);we(this,"code");we(this,"data");we(this,"method");this.name="AcpRpcError",this.code=n.code,this.data=n.data,this.method=r}}function dL(e){if(!e.data||typeof e.data!="object")return;const t=e.data.details;return typeof t=="string"&&t.trim()?t:void 0}function Oo(e){if(e instanceof Hu){const t=dL(e);return`${e.method?`${e.method} [${e.code}]`:`ACP [${e.code}]`}: ${t||e.message}`}return e instanceof Error?e.message:String(e)}function uL(e,t){if(!e||typeof e!="object")return;const n=e;if(!(typeof n.code!="number"||typeof n.message!="string"))return new Hu({code:n.code,message:n.message,data:n.data},t)}const Js="x-codebuddy-request",Da="1",Vp={maxRetries:5,baseDelay:200,retryOnStatus:e=>e===404||e>=500};async function Kt(e,t,n){const r=(n==null?void 0:n.maxRetries)??3,i=(n==null?void 0:n.baseDelay)??500,s=(n==null?void 0:n.retryOnStatus)??(c=>c>=500),a=new Headers(t==null?void 0:t.headers);a.has(Js)||a.set(Js,Da);const o={...t,headers:a};for(let c=0;c<=r;c++)try{const d=await fetch(e,o);if(s(d.status)&&c<r){console.warn(`Request failed with ${d.status}, retrying (${c+1}/${r})...`),await new Promise(u=>setTimeout(u,i*Math.pow(2,c)));continue}return d}catch(d){if(c<r){console.warn(`Request failed with network error, retrying (${c+1}/${r})...`,d),await new Promise(u=>setTimeout(u,i*Math.pow(2,c)));continue}throw d}throw new Error("fetchWithRetry: max retries exceeded")}const Gr=class Gr{constructor(t,n){we(this,"baseUrl");we(this,"token");we(this,"connectionId",null);we(this,"sessionToken",null);we(this,"nextId",1);we(this,"pageHideHandler",null);we(this,"reconnecting",null);we(this,"currentSessionId",null);we(this,"notificationController",null);we(this,"notificationRetryTimer",null);we(this,"notificationResumeTimer",null);we(this,"notificationStreamActive",!1);we(this,"notificationStreamDesired",!1);we(this,"activeAcpPostCount",0);we(this,"requestTransports",new Map);we(this,"activePrompt",null);we(this,"promptQueue",[]);we(this,"notificationReconnectAttempts",0);we(this,"listeners",new Map);we(this,"_status","disconnected");we(this,"pendingRequests",new Map);we(this,"permissionRequestIds",new Map);we(this,"permissionRequestToolCallIds",new Map);we(this,"extMethodRequestIds",new Map);we(this,"cancellingSessionIds",new Set);this.baseUrl=t||window.location.origin,this.token=n}get status(){return this._status}async connect(){var t;this.setStatus("connecting");try{const n={[Js]:Da};this.token&&(n.Authorization=`Bearer ${this.token}`);const r=await Kt(`${this.baseUrl}/api/v1/acp/connect`,{method:"POST",headers:n},Vp);if(!r.ok){let i="";try{const s=await r.json();(t=s==null?void 0:s.error)!=null&&t.message&&(i=s.error.message)}catch{}throw new Error(i||`ACP connect failed: ${r.status} ${r.statusText}`)}this.applyConnectionGrant(await r.json()),this.setStatus("connected")}catch(n){throw this.setStatus("error"),n}}async reconnect(){if(this.reconnecting)return this.reconnecting;if(this.closeNotificationStream(),this.connectionId){const n=this.buildAcpHeaders();delete n["Content-Type"],this.fetchAcpWithTimeout({method:"DELETE",headers:n},Gr.ACP_DISCONNECT_TIMEOUT_MS,"ACP stale connection release").catch(()=>{})}const t=new Set([...this.pendingRequests.keys(),...this.requestTransports.keys()]).size;return t>0&&(console.warn(`[ACP] reconnect: aborting ${t} in-flight request(s) tied to old connection`),this.abortAllRequestTransports(new Error("ACP connection reset, request aborted"))),this.reconnecting=(async()=>{try{const n={[Js]:Da};this.token&&(n.Authorization=`Bearer ${this.token}`);const r=await Kt(`${this.baseUrl}/api/v1/acp/connect`,{method:"POST",headers:n},Vp);if(!r.ok)throw new Error(`Reconnect failed: ${r.status}`);this.applyConnectionGrant(await r.json()),await this.request("initialize",{protocolVersion:1,clientInfo:{name:"codebuddy-web-ui",version:"1.0.0"},clientCapabilities:{_meta:{"codebuddy.ai":{question:!0,promptSuggestion:!0,terminalOutput:!0,fileReferencesPathOnly:!0,mainAgentSupport:!0}}}},0,void 0,!1,!1);const i=this.currentSessionId??(typeof window<"u"?new URLSearchParams(window.location.search).get("sessionId"):null)??(typeof sessionStorage<"u"?sessionStorage.getItem("acp-session-id"):null);i&&await this.request("session/load",{sessionId:i,cwd:".",mcpServers:[]},0,void 0,!1,!1),console.info("ACP connection re-established successfully"),this.openNotificationStream()}finally{this.reconnecting=null,this.dispatchNextPrompt()}})(),this.reconnecting}async disconnect(){this.closeNotificationStream();const t=new Qs("ACP connection disconnected before prompt completion");if(this.clearQueuedPrompts(void 0,t.message),this.rejectActivePrompt(t),this.abortAllRequestTransports(t),this.cancellingSessionIds.clear(),this.connectionId)try{const n=this.buildAcpHeaders();delete n["Content-Type"],await this.fetchAcpWithTimeout({method:"DELETE",headers:n},Gr.ACP_DISCONNECT_TIMEOUT_MS,"ACP disconnect")}catch{}this.connectionId=null,this.sessionToken=null,this.removePageHideCleanup(),this.setStatus("disconnected"),this.listeners.clear()}openNotificationStream(){if(this.notificationStreamDesired=!0,this.activeAcpPostCount>0||!this.connectionId||this.notificationStreamActive||this.notificationController)return;this.notificationStreamActive=!0;const t=new AbortController;this.notificationController=t,(async()=>{try{const r=this.buildAcpHeaders();delete r["Content-Type"];const i=await fetch(`${this.baseUrl}/api/v1/acp`,{headers:r,signal:t.signal});if(!i.ok||!i.body)throw new Error(`GET SSE failed: ${i.status}`);this.notificationReconnectAttempts=0;const s=i.body.getReader(),a=new TextDecoder;let o="";for(;;){const{done:c,value:d}=await s.read();if(c)break;if(t.signal.aborted)return;o+=a.decode(d,{stream:!0});const u=o.split(`
3
3
 
4
4
  `);o=u.pop()||"";for(const h of u){const p=h.split(`
@@ -576,7 +576,7 @@ var SR=Object.defineProperty;var Lw=e=>{throw TypeError(e)};var kR=(e,t,n)=>t in
576
576
  `).replace(/^\n+/,"").replace(/\n+$/,""),paths:jo(t)}}function L$(e,t){const n=[],r=new RegExp(tC.source,"g");let i;for(;(i=r.exec(e))!==null;){const s=i[1]!=null?nC(i[1]):i[2]??"",a=rC(s,t);a&&n.push(a)}return jo(n).slice(0,Wu)}function M$(e,t){const n=new RegExp(tC.source,"g"),r=e.replace(n,(i,s,a)=>{const o=s!=null?nC(s):a??"";return rC(o,t)?"":i});return r===e?e:r.replace(/[ \t]+\n/g,`
577
577
  `).replace(/\n{3,}/g,`
578
578
 
579
- `).replace(/^\n+/,"").replace(/\n+$/,"")}function nC(e){return e.replace(/\\"/g,'"').replace(/\\\\/g,"\\")}function rC(e,t){const n=e.trim().replace(/\\/g,"/");if(!n||n.includes("\0")||n.includes(".."))return null;if(em(n)||n.toLowerCase().startsWith("file://"))return Bi(n);if(!t)return null;const r=t.replace(/[\\/]+$/,"").replace(/\\/g,"/");return!em(r)||r.includes("..")?null:Bi(`${r}/${n.replace(/^\.\//,"")}`)}function D$(e){const t=e.trim();if(!t)return null;const n=t.toLowerCase();if(n.startsWith("javascript:")||n.startsWith("vbscript:")||n.startsWith("blob:"))return null;if(n.startsWith("data:"))return t.length>x$?null:B$(t)?t:null;if(t.length>v$)return null;if(n.startsWith("http://")||n.startsWith("https://"))return t;if(t.startsWith("/api/v1/files/download")){const i=aC(t);return!i||i.includes("..")||oC(i)?null:Ua(i)}if(t.startsWith("/api/"))return null;const r=Bi(t);return r?Ua(r):null}function iC(e){const t=[];for(const n of jo(e).slice(0,Wu)){const r=nf(n);r&&t.push({url:Ua(n),mimeType:r})}return t}function qu(e,t){const n=[],r=new Set;for(const i of[...e??[],...t]){const s=F$(i);if(!r.has(s)&&(r.add(s),n.push(i),n.length>=Wu))break}return n}function sC(e,t){const n=$$(t),r=O$(e),i=typeof(e==null?void 0:e.text)=="string"?e.text:"",s=rf(i),a=iC(s.paths);return r&&"data"in r&&r.data.length>0?{text:s.text,images:[r]}:{text:s.text,images:qu(n,[...r?[r]:[],...a])}}function $$(e){const t=e==null?void 0:e["codebuddy.ai/images"];if(!Array.isArray(t))return[];const n=[];for(const r of t){const i=typeof(r==null?void 0:r.blobPath)=="string"?Bi(r.blobPath,{requireImageExt:!ko(r==null?void 0:r.mimeType)}):null,s=typeof(r==null?void 0:r.mimeType)=="string"&&ko(r.mimeType)?r.mimeType:i?nf(i):void 0;!i||!s||n.push({url:Ua(i),mimeType:s})}return n}function O$(e){const t=U$(e);if(!t||t.type!=="image")return;const n=typeof t.mimeType=="string"?t.mimeType:typeof t.mediaType=="string"?t.mediaType:void 0;if(typeof t.data=="string"&&t.data.length>0&&ko(n))return{data:t.data,mimeType:n};const r=typeof t._meta=="object"&&t._meta&&typeof t._meta.blobPath=="string"?Bi(t._meta.blobPath,{requireImageExt:!ko(n)}):Bi(typeof t.uri=="string"?t.uri:""),i=ko(n)?n:r?nf(r):void 0;if(!(!r||!i))return{url:Ua(r),mimeType:i}}function P$(e){return"url"in e?e.url:`data:${e.mimeType};base64,${e.data}`}function B$(e){const t=/^data:([^;,]+)(;base64)?,/i.exec(e);return t?ko(t[1]):!1}function aC(e){try{const n=new URL(e,"http://web-ui.local").searchParams.get("path");return n?Bi(n,{requireImageExt:!1}):null}catch{return null}}function em(e){return e.startsWith("/")||tf.test(e)}function j$(e){const t=new Set,n=new RegExp(C$.source,"g");let r;for(;(r=n.exec(e))!==null;){const i=Bi(r[1]??"");i&&t.add(Vu(i))}return t}function Vu(e){const t=e.replace(/\\/g,"/");return tf.test(t)?`${t[0].toLowerCase()}${t.slice(1)}`:t}function oC(e){const t=e.replace(/\\/g,"/");return/^[A-Za-z]:\/windows(\/|$)/i.test(t)||/^[A-Za-z]:\/\$recycle\.bin(\/|$)/i.test(t)?!0:k$.some(n=>t===n.slice(0,-1)||t.startsWith(n))}function lC(e){const t=e.split(/[\\/]/).pop()??"",n=t.lastIndexOf(".");return n>=0?t.slice(n).toLowerCase():""}function jo(e){const t=new Set,n=[];for(const r of e){const i=Bi(r)??r,s=Vu(i);t.has(s)||(t.add(s),n.push(i))}return n}function F$(e){if("data"in e)return`data:${e.mimeType}:${e.data.slice(0,48)}`;const t=aC(e.url);return t?`path:${Vu(t)}`:`url:${e.url}`}function U$(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}let Wi=0;function cC(e,t,n){return t??(e==null?void 0:e.createdAt)??n??Date.now()}function dC(e,t){switch(t.kind){case"set":case"active":return t.condition?{condition:t.condition,createdAt:cC(e,t.createdAt,t.timestamp)}:e;case"cleared":case"no-goal":return null;default:return e}}function uC(e){for(let t=e.length-1;t>=0;t--){const n=e[t];if(n.type==="message"&&n.role==="assistant"&&n.streaming)return t}return-1}function uS(e,t){if(!t)return uC(e);for(let n=e.length-1;n>=0;n--){const r=e[n];if(r.type==="message"&&r.role==="assistant"&&r.streaming&&r.messageId===t)return n}return-1}function Qu(e){return!e||!e.trim()}function hC(e){for(let t=e.length-1;t>=0;t--){const n=e[t];if(n.type==="message"&&n.role==="assistant"&&n.streaming&&Qu(n.content)&&n.thinking)return t}return-1}function z$(e){for(let t=e.length-1;t>=0;t--){const n=e[t];if(n.type==="message"&&n.role==="assistant"&&n.streaming&&n.thinking)return t}return-1}function H$(e){const t=hC(e);return t!==-1?t:z$(e)}function sf(e,t){return t?!e||t.startsWith(e)?t:e.startsWith(t)?e:e+t:e}function pC(e,t){var n;if(!(!e||e.role!=="assistant"||t.role!=="assistant")&&!(!t.thinking||!Qu(t.content)||(n=t.images)!=null&&n.length))return{...e,thinking:sf(e.thinking||"",t.thinking),thinkingStartTime:e.thinkingStartTime||t.thinkingStartTime,thinkingDuration:e.thinkingDuration??t.thinkingDuration,streaming:!!(e.streaming||t.streaming)}}function Fi(e){const t=uC(e);if(t===-1)return e;const n=[...e],r=n[t],i={streaming:!1};return r.thinking&&r.thinkingStartTime&&!r.thinkingDuration&&(i.thinkingDuration=Math.round((Date.now()-r.thinkingStartTime)/1e3)),n[t]={...r,...i},n}function hS(e,t,n){if(!n)return null;const r=e.timeline.findIndex(o=>o.type==="tool_call"&&o.id===n);if(r!==-1){const o=e.timeline[r],c=[...o.subagentTimeline||[]],d=c[c.length-1];d&&d.type==="message"&&d.streaming?c[c.length-1]={...d,content:d.content+t}:c.push({type:"message",id:`sub-msg-${++Wi}`,content:t,streaming:!0});const u=[...e.timeline];return u[r]={...o,subagentTimeline:c},{timeline:u}}const i=new Map(e.pendingSubagentChunks),s=i.get(n)||[],a=s[s.length-1];return a&&a.type==="message"?s[s.length-1]={...a,content:a.content+t}:s.push({type:"message",content:t}),i.set(n,s),{pendingSubagentChunks:i}}const ot=Rt((e,t)=>({timeline:[],childToolCalls:new Map,pendingSubagentChunks:new Map,isAgentRunning:!1,agentRunSuppressed:!1,stopReason:null,errorMessage:null,errorCategory:null,finishReason:null,agentPhaseLabel:null,progressLabel:null,historyLoading:!1,hasPendingInterruption:!1,compactCancelled:!1,goalRecap:null,activeGoal:null,pausedGoal:null,addUserMessage:(n,r,i)=>{e(s=>({timeline:[...Fi(s.timeline),{type:"message",id:`msg-${++Wi}`,role:"user",content:n,...r&&r.length>0?{images:r}:{},...i&&i.length>0?{files:i}:{},timestamp:Date.now()}],isAgentRunning:!0,agentRunSuppressed:!1,stopReason:null,errorMessage:null,errorCategory:null,finishReason:null}))},addQueuedUserMessage:(n,r,i)=>{e(s=>({timeline:[...s.timeline,{type:"message",id:`msg-${++Wi}`,role:"user",content:n,...r&&r.length>0?{images:r}:{},...i&&i.length>0?{files:i}:{},timestamp:Date.now()}]}))},addChunk:(n,r,i,s)=>{e(a=>{const o=hS(a,n,r);if(o)return o;const c=[...a.timeline],d=uS(c,s),u=d!==-1||!s?d:hC(c);if(u!==-1){const h=c[u],p={content:h.content+n,...s&&s!==h.messageId?{messageId:s}:{}};i&&!h.isCompactInternal&&(p.isCompactInternal=!0),h.thinking&&h.thinkingStartTime&&!h.thinkingDuration&&Qu(h.content)&&n.trim()&&(p.thinkingDuration=Math.round((Date.now()-h.thinkingStartTime)/1e3)),c[u]={...h,...p}}else c.push({type:"message",id:`msg-${++Wi}`,role:"assistant",content:n,...s?{messageId:s}:{},timestamp:Date.now(),streaming:!0,...i?{isCompactInternal:i}:{}});return{timeline:c}})},addThinkingChunk:(n,r,i)=>{e(s=>{const a=hS(s,n,r);if(a)return a;const o=[...s.timeline],c=uS(o,i),d=c!==-1||!i?c:H$(o);if(d!==-1){const u=o[d];o[d]={...u,...i&&i!==u.messageId?{messageId:i}:{},thinking:sf(u.thinking||"",n),thinkingStartTime:u.thinkingStartTime||Date.now()}}else o.push({type:"message",id:`msg-${++Wi}`,role:"assistant",content:"",...i?{messageId:i}:{},thinking:n,thinkingStartTime:Date.now(),timestamp:Date.now(),streaming:!0});return{timeline:o}})},finalizeAssistantMessage:()=>{e(n=>({timeline:Fi(n.timeline)}))},addSubagentUserMessage:(n,r,i)=>{e(s=>{const a=s.timeline.findIndex(d=>d.type==="tool_call"&&d.id===n);if(a!==-1){const d=s.timeline[a],u=[...d.subagentTimeline||[]];u.push({type:"user_message",id:`sub-msg-${++Wi}`,content:r,...i&&i.length>0?{images:i}:{}});const h=[...s.timeline];return h[a]={...d,subagentTimeline:u},{timeline:h}}const o=new Map(s.pendingSubagentChunks),c=o.get(n)||[];return c.push({type:"user_message",content:r,...i&&i.length>0?{images:i}:{}}),o.set(n,c),{pendingSubagentChunks:o}})},addToolCall:n=>{e(r=>{const i=Fi(r.timeline);if(n.parentToolCallId){const o=new Map(r.childToolCalls);return o.set(n.id,{...n,type:"tool_call"}),{timeline:i.map(c=>{if(c.type==="tool_call"&&c.id===n.parentToolCallId){const d=(c.subagentTimeline||[]).map(u=>u.type==="message"&&u.streaming?{...u,streaming:!1}:u);return{...c,children:[...c.children||[],n.id],subagentTimeline:[...d,{type:"tool_call_ref",toolCallId:n.id}]}}return c}),childToolCalls:o}}const s={...n,type:"tool_call"},a=r.pendingSubagentChunks.get(n.id);if(a&&a.length>0){const o=a.map(d=>d.type==="user_message"?{type:"user_message",id:`sub-msg-${++Wi}`,content:d.content,images:d.images}:{type:"message",id:`sub-msg-${++Wi}`,content:d.content,streaming:!1});s.subagentTimeline=o;const c=new Map(r.pendingSubagentChunks);return c.delete(n.id),{timeline:[...i,s],pendingSubagentChunks:c}}return{timeline:[...i,s]}})},updateToolCall:(n,r)=>{e(i=>{const s=d=>!d||!Array.isArray(d)?!1:d.some(u=>u.type==="diff"),a=d=>{let u=r;if(s(d.content)&&r.content!==void 0&&!s(r.content)){const{content:p,...m}=r;u=m}const h={...d,...u,type:"tool_call"};return r.metaData&&d.metaData&&(h.metaData={...d.metaData,...r.metaData}),h};if(i.timeline.some(d=>d.type==="tool_call"&&d.id===n))return{timeline:i.timeline.map(d=>d.type==="tool_call"&&d.id===n?a(d):d)};const c=i.childToolCalls.get(n);if(c){const d=new Map(i.childToolCalls);return d.set(n,a(c)),{childToolCalls:d}}return{}})},getChildToolCall:n=>t().childToolCalls.get(n),getToolCall:n=>{const r=t();return r.timeline.find(s=>s.type==="tool_call"&&s.id===n)??r.childToolCalls.get(n)},addQuestion:n=>{e(r=>r.timeline.some(s=>s.type==="question"&&s.toolCallId===n.toolCallId&&s.status==="pending")?r:{timeline:[...Fi(r.timeline),{...n,type:"question",status:"pending"}],hasPendingInterruption:!0})},submitQuestion:(n,r)=>{e(i=>{const s=i.timeline.map(o=>o.type==="question"&&o.id===n?{...o,status:"answered",answers:r}:o),a=s.some(o=>o.type==="interruption"&&!o.resolved||o.type==="question"&&o.status==="pending");return{timeline:s,hasPendingInterruption:a}})},cancelQuestion:n=>{e(r=>{const i=r.timeline.map(a=>a.type==="question"&&a.id===n?{...a,status:"cancelled"}:a),s=i.some(a=>a.type==="interruption"&&!a.resolved||a.type==="question"&&a.status==="pending");return{timeline:i,hasPendingInterruption:s}})},resolveQuestionByToolCallId:n=>{e(r=>{const i=r.timeline.map(a=>a.type==="question"&&a.toolCallId===n&&a.status==="pending"&&a.source==="interruption"?{...a,status:"cancelled"}:a),s=i.some(a=>a.type==="interruption"&&!a.resolved||a.type==="question"&&a.status==="pending");return{timeline:i,hasPendingInterruption:s}})},addInterruption:n=>{e(r=>n.toolCallId&&r.timeline.some(s=>s.type==="interruption"&&s.toolCallId===n.toolCallId&&!s.resolved)?r:{timeline:[...Fi(r.timeline),{...n,type:"interruption"}],hasPendingInterruption:!0})},resolveInterruption:(n,r)=>{e(i=>{const s=i.timeline.map(o=>o.type==="interruption"&&o.id===n?{...o,resolved:!0,decision:r}:o),a=s.some(o=>o.type==="interruption"&&!o.resolved||o.type==="question"&&o.status==="pending");return{timeline:s,hasPendingInterruption:a}})},resolveInterruptionByToolCallId:(n,r)=>{e(i=>{const s=i.timeline.map(o=>o.type==="interruption"&&o.toolCallId===n&&!o.resolved?{...o,resolved:!0,decision:r}:o),a=s.some(o=>o.type==="interruption"&&!o.resolved||o.type==="question"&&o.status==="pending");return{timeline:s,hasPendingInterruption:a}})},setHistoryLoading:n=>e({historyLoading:n}),addHistoryUserMessage:(n,r,i,s,a)=>{e(o=>({timeline:[...Fi(o.timeline),{type:"message",id:`msg-${++Wi}`,role:"user",content:n,...r&&r.length>0?{images:r}:{},timestamp:Date.now(),...i?{isCompactInternal:i}:{},...s?{channel:s}:{},...a?{commandKind:a}:{}}]}))},addHistoryUserMessageChunk:(n,r,i,s,a,o)=>{!r&&!(i&&i.length>0)||e(c=>{const d=Fi(c.timeline),u=d[d.length-1];if(u&&u.type==="message"&&u.role==="user"&&n&&u.messageId===n){const h=qu(u.images,i||[]);return d[d.length-1]={...u,content:u.content+r,...h.length>0?{images:h}:{},...s?{isCompactInternal:!0}:{},...a?{channel:a}:{},...o?{commandKind:o}:{}},{timeline:d}}return{timeline:[...d,{type:"message",id:`msg-${++Wi}`,...n?{messageId:n}:{},role:"user",content:r,...i&&i.length>0?{images:i}:{},timestamp:Date.now(),...s?{isCompactInternal:s}:{},...a?{channel:a}:{},...o?{commandKind:o}:{}}]}})},setAgentRunning:n=>e({isAgentRunning:n,...n?{agentRunSuppressed:!1}:{agentPhaseLabel:null,progressLabel:null}}),noteAgentActivity:()=>e(n=>n.agentRunSuppressed?n:{isAgentRunning:!0}),suppressAgentRun:()=>e({isAgentRunning:!1,agentRunSuppressed:!0,agentPhaseLabel:null,progressLabel:null}),setAgentPhaseLabel:n=>e({agentPhaseLabel:n}),setProgressLabel:n=>e({progressLabel:n}),setSessionEnd:(n,r,i,s)=>{t().finalizeAssistantMessage();const a=n==="end_turn";e(o=>{const c=o.timeline.map(u=>u.type==="tool_call"&&u.status==="running"?{...u,status:"completed"}:u.type==="interruption"&&!u.resolved?u.mcpUiIntercept===!0||typeof u.toolCallId=="string"&&u.toolCallId.startsWith("mcpui-")||u.toolName==="ExitPlanMode"?u:{...u,resolved:!0,decision:"deny"}:u.type==="question"&&u.status==="pending"?{...u,status:"cancelled"}:u),d=new Map(o.childToolCalls);for(const[u,h]of d)h.status==="running"&&d.set(u,{...h,status:"completed"});return{isAgentRunning:!1,agentRunSuppressed:n==="cancelled",hasPendingInterruption:c.some(u=>u.type==="interruption"&&!u.resolved),agentPhaseLabel:null,progressLabel:null,stopReason:a?null:n,errorMessage:a?null:r||o.errorMessage||null,errorCategory:a?null:i||o.errorCategory||null,finishReason:a?null:s||o.finishReason||null,timeline:c,childToolCalls:d}})},setCompactCancelled:n=>e({compactCancelled:n}),addGoalProgress:n=>{e(r=>{if(r.timeline.some(a=>a.type==="goal-progress"&&a.id===n.id))return r;const i=Fi(r.timeline),s={type:"goal-progress",id:n.id,condition:n.condition,reason:n.reason,turnCount:n.turnCount,createdAt:n.createdAt,timestamp:n.timestamp??Date.now()};return{timeline:[...i,s],activeGoal:{condition:s.condition,createdAt:cC(r.activeGoal,s.createdAt,s.timestamp)}}})},showGoalRecap:n=>e(r=>{var i;return{goalRecap:n,activeGoal:n.active?{condition:n.active.condition,createdAt:((i=r.activeGoal)==null?void 0:i.condition)===n.active.condition?r.activeGoal.createdAt:Date.now()}:null}}),dismissGoalRecap:()=>e({goalRecap:null}),addGoalStatus:n=>{e(r=>{if(r.timeline.some(a=>a.type==="goal-status"&&a.id===n.id))return r;const i=Fi(r.timeline),s={type:"goal-status",id:n.id,kind:n.kind,condition:n.condition,prev:n.prev,actual:n.actual,max:n.max,createdAt:n.createdAt,timestamp:n.timestamp??Date.now()};return{timeline:[...i,s],activeGoal:dC(r.activeGoal,s),...s.kind==="set"||s.kind==="set-replaced"||s.kind==="active"?{pausedGoal:null}:{},...s.kind==="set"||s.kind==="set-replaced"?{isAgentRunning:!0,agentRunSuppressed:!1}:{}}})},addGoalResult:n=>{e(r=>{if(r.timeline.some(a=>a.type==="goal-result"&&a.id===n.id))return{...r,activeGoal:null,pausedGoal:null};const i=Fi(r.timeline),s={type:"goal-result",id:n.id,ok:n.ok,reason:n.reason,condition:n.condition,durationMs:n.durationMs,turnCount:n.turnCount,tokenDelta:n.tokenDelta,timestamp:n.timestamp??Date.now()};return{timeline:[...i,s],activeGoal:null,pausedGoal:null}})},hydrateActiveGoal:n=>e({activeGoal:n&&n.condition?{condition:n.condition,createdAt:n.createdAt}:null}),pauseActiveGoal:n=>e(r=>{var a;const i=r.pausedGoal??r.activeGoal;if(!i)return r;const s=typeof n=="number"?n:i.pausedAt??Date.now();return((a=r.pausedGoal)==null?void 0:a.condition)===i.condition&&r.pausedGoal.pausedAt===s?r:{pausedGoal:{...i,pausedAt:s}}}),dismissPausedGoal:()=>e({pausedGoal:null}),applyReconnectSnapshot:n=>e(r=>({...typeof n.busy=="boolean"?n.busy?r.agentRunSuppressed?{}:{isAgentRunning:!0}:{isAgentRunning:!1,agentPhaseLabel:null,progressLabel:null}:{},..."activeGoal"in n?(()=>{const i=n.activeGoal&&n.activeGoal.condition?{condition:n.activeGoal.condition,createdAt:n.activeGoal.createdAt,...typeof n.activeGoal.pausedAt=="number"?{pausedAt:n.activeGoal.pausedAt}:{}}:null;return{activeGoal:i,pausedGoal:i&&i.pausedAt!=null?i:null}})():{}})),clearMessages:()=>e({timeline:[],childToolCalls:new Map,pendingSubagentChunks:new Map,stopReason:null,errorMessage:null,errorCategory:null,finishReason:null,agentPhaseLabel:null,progressLabel:null,historyLoading:!1,hasPendingInterruption:!1,compactCancelled:!1,goalRecap:null}),clearChat:()=>{t().clearMessages()},resetForSessionChange:()=>{t().clearMessages(),e({isAgentRunning:!1,agentRunSuppressed:!1,agentPhaseLabel:null,progressLabel:null,activeGoal:null,pausedGoal:null})}})),G$=Object.freeze(Object.defineProperty({__proto__:null,activeGoalAfterStatus:dC,isBlankAssistantText:Qu,mergeThinkingChunk:sf,tryFoldThoughtOnlyAssistant:pC,useChatStore:ot},Symbol.toStringTag,{value:"Module"}));async function Ku(e){return Kt(e,{headers:Fe()})}async function Yu(e,t){return Kt(e,{method:"POST",headers:{"Content-Type":"application/json",...Fe()},body:t!=null?JSON.stringify(t):void 0})}async function mC(e,t){return Kt(e,{method:"PUT",headers:{"Content-Type":"application/json",...Fe()},body:t!=null?JSON.stringify(t):void 0})}async function W$(e){return Kt(e,{method:"DELETE",headers:Fe()})}async function tm(e){const t=await Ku(e);if(!t.ok)throw new Error(`HTTP ${t.status}`);const n=await t.json();return n.data??n}async function q$(e){return tm(`/api/v1/goal?sessionId=${encodeURIComponent(e)}`)}async function V$(e){const t=await Yu("/api/v1/goal/clear",{sessionId:e});if(!t.ok)throw new Error(`HTTP ${t.status}`);const n=await t.json();return n.data??n}async function Q$(e){const t=await Yu("/api/v1/goal/pause",{sessionId:e});if(!t.ok)throw new Error(`HTTP ${t.status}`);const n=await t.json();return n.data??n}async function K$(e){const t=await Yu("/api/v1/goal/resume",{sessionId:e});if(!t.ok)throw new Error(`HTTP ${t.status}`);const n=await t.json();return n.data??n}function Y$(e){const t=e.active;return t!=null&&t.condition?{condition:t.condition,createdAt:t.createdAt,...typeof t.pausedAt=="number"?{pausedAt:t.pausedAt}:{}}:null}function gC(e){var r;const t=Y$(e);if(!t)return;const n=ot.getState();if(n.hydrateActiveGoal(t),(r=e.active)!=null&&r.paused){n.pauseActiveGoal(typeof e.active.pausedAt=="number"?e.active.pausedAt:void 0);return}n.dismissPausedGoal()}const $i=Rt(e=>({terminals:{},terminalIdByToolCall:{},applyTerminalUpdate:(t,n)=>{const{terminalId:r}=t;r&&e(i=>{const s=i.terminals[r],a=s?{...s,seen:!0}:{terminalId:r,seen:!0};return a.startedAt===void 0&&n!==void 0&&(a.startedAt=n),t.command!==void 0&&(a.command=t.command??void 0),t.cwd!==void 0&&(a.cwd=t.cwd??void 0),t.exitStatus!==void 0&&(a.exitStatus=t.exitStatus??void 0),{terminals:{...i.terminals,[r]:a}}})},linkToolCall:(t,n)=>{!t||!n||e(r=>{if(r.terminalIdByToolCall[t]===n)return r;const i=r.terminals[n];return{terminalIdByToolCall:{...r.terminalIdByToolCall,[t]:n},terminals:{...r.terminals,[n]:i?{...i,toolCallId:t}:{terminalId:n,toolCallId:t,seen:!1}}}})},reset:()=>e({terminals:{},terminalIdByToolCall:{}})}));function Zu(e){return!!e&&e.seen&&e.exitStatus===void 0}function Z$(e,t){return e==="connected"&&typeof t=="string"&&t.length>0}const Ge=Rt((e,t)=>({status:"disconnected",sessionId:null,sessionSwitching:!1,models:[],currentModel:"",modes:[],currentMode:"default",commands:[],error:null,topic:null,thinkingEnabled:!1,thoughtLevel:null,promptSuggestion:null,externalInput:null,setStatus:n=>e({status:n}),setSessionId:n=>e({sessionId:n}),setSessionSwitching:n=>e({sessionSwitching:n}),setModels:n=>e({models:n}),setCurrentModel:n=>e({currentModel:n}),setModes:n=>e({modes:n}),setCurrentMode:n=>e({currentMode:n}),setCommands:n=>e({commands:n}),setTopic:n=>e({topic:n}),setThinkingEnabled:n=>e({thinkingEnabled:n}),setThoughtLevel:n=>e({thoughtLevel:n}),setPromptSuggestion:n=>e({promptSuggestion:n}),setExternalInput:n=>e({externalInput:n}),connect:async n=>{const r=st();try{if(e({status:"connecting",error:null}),n){const{AcpClient:i}=await Ct(async()=>{const{AcpClient:o}=await Promise.resolve().then(()=>hL);return{AcpClient:o}},void 0),s=new i(void 0,n);s.on("status_change",o=>e({status:o})),s.on("model_update",o=>{e({models:o.availableModels||[],currentModel:o.currentModelId||""})});const{sessionId:a}=await s.initializeSession({continue:!0});e({status:"connected",sessionId:a})}else{const{sessionId:i}=await r.initializeSession({continue:!0});e({status:"connected",sessionId:i})}}catch(i){e({status:"error",error:i.message})}},disconnect:async()=>{await st().disconnect(),e({status:"disconnected",sessionId:null,sessionSwitching:!1})}})),bs=Rt((e,t)=>({usage:null,setUsage:n=>{var i,s,a,o;const r=t().usage;if(n.sessionId&&(r!=null&&r.sessionId)&&n.sessionId!==r.sessionId){e({usage:{sessionId:n.sessionId,used:n.used,size:n.size,cost:n.cost,usageByCategory:n.usageByCategory,updatedAt:Date.now()}});return}r&&r.used>0&&n.used===0||r&&r.used===n.used&&r.size===n.size&&((i=r.cost)==null?void 0:i.amount)===((s=n.cost)==null?void 0:s.amount)&&((a=r.cost)==null?void 0:a.currency)===((o=n.cost)==null?void 0:o.currency)&&!n.usageByCategory||e({usage:{sessionId:n.sessionId??(r==null?void 0:r.sessionId),used:n.used,size:n.size,cost:n.cost,usageByCategory:n.usageByCategory??(r==null?void 0:r.usageByCategory),updatedAt:Date.now()}})},reset:()=>e({usage:null})})),ui=Rt((e,t)=>({fileChanges:[],selectedFile:null,selectedDiff:null,diffLoading:!1,isCollapsed:!0,checkpoints:[],showCheckpoints:!1,reverting:!1,recentlyReverted:new Set,onCheckpoint:n=>{const{recentlyReverted:r}=t(),i=r.size>0?n.fileChanges.files.filter(a=>!r.has(a.uri)):n.fileChanges.files,s=new Set(i.map(a=>a.uri));e(a=>({fileChanges:i,selectedFile:a.selectedFile&&!s.has(a.selectedFile)?null:a.selectedFile,selectedDiff:a.selectedFile&&!s.has(a.selectedFile)?null:a.selectedDiff}))},selectFile:async n=>{const{selectedFile:r}=t();if(r===n){e({selectedFile:null,selectedDiff:null});return}e({selectedFile:n,selectedDiff:null,diffLoading:!0});try{const i=await Kt("/internal/file-changes/diff",{method:"POST",headers:{...Fe(),"Content-Type":"application/json"},body:JSON.stringify({path:n})});if(i.ok){const s=await i.json();e({selectedDiff:s.data??s,diffLoading:!1})}else e({diffLoading:!1})}catch{e({diffLoading:!1})}},setCollapsed:n=>e({isCollapsed:n}),setShowCheckpoints:n=>e({showCheckpoints:n}),loadCheckpoints:async()=>{try{const n=await Kt("/internal/file-changes/checkpoints",{method:"POST",headers:{...Fe(),"Content-Type":"application/json"},body:JSON.stringify({})});if(n.ok){const r=await n.json(),s=((r.data??r).checkpoints||[]).sort((a,o)=>o.createdAt-a.createdAt);e({checkpoints:s})}}catch{}},revertFiles:async n=>{e({reverting:!0});try{const r=await Kt("/internal/file-changes/revert",{method:"POST",headers:{...Fe(),"Content-Type":"application/json"},body:JSON.stringify({paths:n})});if(r.ok){const i=await r.json(),a=(i.data??i).revertedFiles||[],o=new Set(a);e(c=>({fileChanges:c.fileChanges.filter(d=>!o.has(d.uri)),selectedFile:o.has(c.selectedFile||"")?null:c.selectedFile,selectedDiff:o.has(c.selectedFile||"")?null:c.selectedDiff,recentlyReverted:new Set([...c.recentlyReverted,...a])})),setTimeout(()=>{e(c=>{const d=new Set(c.recentlyReverted);for(const u of a)d.delete(u);return{recentlyReverted:d}})},5e3)}}finally{e({reverting:!1})}},revertAll:async()=>{e({reverting:!0});try{const n=t().fileChanges.map(i=>i.uri);(await Kt("/internal/file-changes/revert",{method:"POST",headers:{...Fe(),"Content-Type":"application/json"},body:JSON.stringify({})})).ok&&(e(i=>({fileChanges:[],selectedFile:null,selectedDiff:null,recentlyReverted:new Set([...i.recentlyReverted,...n])})),setTimeout(()=>{e(i=>{const s=new Set(i.recentlyReverted);for(const a of n)s.delete(a);return{recentlyReverted:s}})},5e3))}finally{e({reverting:!1})}},revertToCheckpoint:async(n,r="CodeAndConversation")=>{e({reverting:!0});try{if((await Kt("/internal/file-changes/revert",{method:"POST",headers:{...Fe(),"Content-Type":"application/json"},body:JSON.stringify({checkpointId:n,scope:r})})).ok){if((r==="Code"||r==="CodeAndConversation")&&e({fileChanges:[],selectedFile:null,selectedDiff:null}),r==="Conversation"||r==="CodeAndConversation")try{const{useChatStore:s}=await Ct(async()=>{const{useChatStore:c}=await Promise.resolve().then(()=>G$);return{useChatStore:c}},void 0);s.getState().clearChat();const a=st(),o=sessionStorage.getItem("acp-session-id");a&&o&&await a.loadSession(o)}catch(s){console.error("Failed to reload session after revert:",s)}t().loadCheckpoints()}}finally{e({reverting:!1})}},reset:()=>e({fileChanges:[],selectedFile:null,selectedDiff:null,diffLoading:!1,isCollapsed:!0,checkpoints:[],showCheckpoints:!1,reverting:!1,recentlyReverted:new Set})}));let af=Promise.resolve(),Ks;const J$=8e3;function fC(){Ks==null||Ks(),af=new Promise(e=>{Ks=e})}function Ao(){Ks==null||Ks(),Ks=void 0,af=Promise.resolve()}async function X$(e=J$){let t;const n=await Promise.race([af.then(()=>!1),new Promise(r=>{t=setTimeout(()=>r(!0),e)})]);return t!==void 0&&clearTimeout(t),n?(Ao(),"timeout"):"ready"}const Aa="codebuddy.mainAgent.staged",bC=[{name:"cli",displayName:"cli",source:"built-in",custom:!1},{name:"ptc",displayName:"ptc",source:"built-in",custom:!1},{name:"minimal",displayName:"minimal",source:"built-in",custom:!1},{name:"create",displayName:"create",source:"built-in",custom:!1}];function e5(){try{return typeof localStorage>"u"?null:localStorage.getItem(Aa)}catch{return null}}const pS={agents:bC,currentAgentName:"",defaultAgentName:"",sessionBlank:!0,models:[],currentModelId:"",status:"idle",error:null,stagedAgent:e5(),backendSupport:void 0,processAgent:null,processPermissionMode:null},nt=Rt()(e=>({...pS,applyAgentFromResponse:t=>e(n=>({agents:t.agents??n.agents,currentAgentName:t.currentAgentName??n.currentAgentName,defaultAgentName:t.defaultAgentName??n.defaultAgentName,sessionBlank:t.sessionBlank??n.sessionBlank,status:"ready",error:null})),applySetAgentResult:t=>(Ao(),e(()=>({currentAgentName:t.agentName,models:t.models,currentModelId:t.currentModelId,sessionBlank:t.sessionBlank,status:"ready",error:null}))),applyAgentConfigEntry:t=>e(()=>{const n={};return t.currentValue&&(n.currentAgentName=t.currentValue),n}),applyBackendSupport:t=>e(()=>({backendSupport:t})),applyProcessDefaults:t=>e(n=>{const r=typeof t.agent=="string"?t.agent.trim():void 0,i=typeof t.permissionMode=="string"?t.permissionMode.trim():void 0;return{processAgent:r===void 0?n.processAgent:r||null,processPermissionMode:i===void 0?n.processPermissionMode:i||null}}),setSessionBlank:t=>e(()=>({sessionBlank:t})),setStagedAgent:t=>{typeof localStorage<"u"&&localStorage.setItem(Aa,t),e(()=>({stagedAgent:t}))},hydrateStagedAgent:t=>{t&&(typeof localStorage<"u"&&localStorage.setItem(Aa,t),e(n=>({stagedAgent:t,currentAgentName:n.currentAgentName||t})))},clearStagedAgent:()=>{typeof localStorage<"u"&&localStorage.removeItem(Aa),e(()=>({stagedAgent:null}))},setLoading:()=>e(()=>({status:"loading",error:null})),setError:t=>(Ao(),e(()=>({status:"error",error:t}))),reset:t=>{Ao(),!(t!=null&&t.keepLastUsed)&&typeof localStorage<"u"&&localStorage.removeItem(Aa);const n=(t==null?void 0:t.keepProcessDefaults)??(t==null?void 0:t.keepLastUsed);e(r=>({...pS,agents:[...bC],stagedAgent:t!=null&&t.keepLastUsed?r.stagedAgent:null,backendSupport:n?r.backendSupport:void 0,processAgent:n?r.processAgent:null,processPermissionMode:n?r.processPermissionMode:null}))}}));let Ja=new Map;const qi=Rt((e,t)=>({visible:!1,total:0,completed:0,connectingServers:[],finished:!1,startedAt:void 0,failed:[],timedOut:[],applyEvent:n=>{if(n.event==="start"){Ja=new Map;const r=n.servers??[];for(const i of r)Ja.set(i,"connecting");e({total:n.total_count??r.length,completed:0,connectingServers:[...r].sort(),finished:!1,failed:[],timedOut:[],visible:r.length>0,startedAt:r.length>0?Date.now():void 0});return}if(n.event==="server"){if(t().finished)return;n.name&&n.state&&Ja.set(n.name,n.state);const r=[];let i=0;for(const[s,a]of Ja)a==="connecting"?r.push(s):i+=1;e({connectingServers:r.sort(),completed:i});return}Ja=new Map,e({finished:!0,visible:!0,connectingServers:[],completed:t().total,failed:[...n.failed??[]],timedOut:[...n.timed_out??[]]})},hide:()=>{e({visible:!1})},reset:()=>{Ja=new Map,e({visible:!1,total:0,completed:0,connectingServers:[],finished:!1,startedAt:void 0,failed:[],timedOut:[]})}})),Ir=Rt(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,n)=>e(r=>({memberHistories:{...r.memberHistories,[t]:n}})),clearTeam:()=>e({isInTeam:!1,teamName:null,isAutoTeam:!1,members:[],focusedMemberName:null,memberHistories:{}})})),yC=Rt(e=>({userInfo:null,loading:!1,error:null,fetchUserInfo:async t=>{e({loading:!0,error:null});try{const n=await t.getUserInfo();n.userInfo?e({userInfo:n.userInfo,loading:!1}):e({loading:!1})}catch(n){console.warn("[user] Failed to fetch user info:",n),e({error:n.message,loading:!1})}},clearUserInfo:()=>{e({userInfo:null,error:null})}}));function t5(e,t){return e&&typeof e=="object"&&!Array.isArray(e)?{...e,defaultMode:t}:{defaultMode:t}}function _C(e){const t=e&&typeof e=="object"&&"data"in e?e.data:e;return t&&typeof t=="object"&&"value"in t?t.value:t}function n5(e,t){const n=e&&typeof e=="object"&&!Array.isArray(e)?{...e}:{},r=n.mainAgent&&typeof n.mainAgent=="object"&&!Array.isArray(n.mainAgent)?{...n.mainAgent}:{};return{...n,mainAgent:{...r,lastUsed:t}}}async function r5(e){const t=await Ku("/api/v1/settings/codebuddy?scope=user");if(!t.ok)throw new Error(`HTTP ${t.status}`);const n=n5(_C(await t.json()),e),r=await mC("/api/v1/settings/codebuddy?scope=user",{value:n});if(!r.ok&&r.status!==204)throw new Error(`HTTP ${r.status}`)}async function i5(e){const t=await Ku("/api/v1/settings/permissions?scope=user");if(!t.ok)throw new Error(`HTTP ${t.status}`);const n=t5(_C(await t.json()),e),r=await mC("/api/v1/settings/permissions?scope=user",{value:n});if(!r.ok&&r.status!==204)throw new Error(`HTTP ${r.status}`)}const vC="codebuddy.permissionMode.staged",s5=new Set(["default","acceptEdits","plan","auto","dontAsk","bypassPermissions","fullAccess","work","delegate"]),a5=new Set(["default","acceptEdits","plan","auto","dontAsk","bypassPermissions"]);function qa(e){return s5.has(e)}function o5(e){return e==="fullAccess"?"bypassPermissions":a5.has(e)?e:""}function xC(){try{if(typeof localStorage>"u")return null;const e=localStorage.getItem(vC);return e&&qa(e)?e:null}catch{return null}}function of(e){if(qa(e))try{if(typeof localStorage>"u")return;localStorage.setItem(vC,e)}catch{}}function lf(e){qa(e)&&(of(e),i5(e).catch(t=>{console.warn("[composer-prefs] persist permissions.defaultMode failed:",t)}))}function l5(e){const t=typeof e.currentMode=="string"?e.currentMode.trim():"";if(!t||!qa(t))return!1;const n=typeof e.processPermissionMode=="string"?e.processPermissionMode.trim():"";return!n||t!==n}function c5(e){const t=e.stored||e.currentMode||"";return t&&qa(t)?t:null}function d5(e){return c5({stored:e.stored,currentMode:e.currentMode&&e.currentMode!=="default"?e.currentMode:void 0})??""}const u5=["cli","ptc","minimal","create"];function nm(e){return u5.includes(e)}function h5(e,t){return e||t}function p5(e,t){return t.length>0&&e===t}function m5(e){return{builtin:e.filter(t=>nm(t.name)),custom:e.filter(t=>!nm(t.name)&&(t.custom===!0||t.source!=="built-in"))}}function mS(e){return e.id==="agent"?(nt.getState().applyAgentConfigEntry(e),!0):!1}function g5(e){if(e.sessionBlank!==!0)return null;const t=e.stagedAgent??e.stored;return!t||!e.sessionId||e.currentAgentName&&e.defaultAgentName&&e.currentAgentName===e.defaultAgentName&&t!==e.defaultAgentName?null:{agentName:t,sessionId:e.sessionId}}function rm(e){e&&(nt.getState().setStagedAgent(e),r5(e).catch(t=>{console.warn("[main-agent] persist lastUsed failed:",t)}))}function f5(e){var s,a;const t=e&&typeof e=="object"?e:{},n=(s=t.codebuddy)==null?void 0:s.mainAgent,r=typeof(n==null?void 0:n.lastUsed)=="string"?n.lastUsed.trim():"",i=(a=t.permissions)==null?void 0:a.defaultMode;return{lastUsedAgent:r||null,lastPermissionMode:typeof i=="string"&&qa(i)?i:null}}async function b5(){try{const[e,t]=await Promise.all([tm("/api/v1/settings?scope=user"),tm("/api/v1/runtime-defaults").catch(()=>({}))]),n=t&&typeof t=="object"?t:{},r=typeof n.agent=="string"?n.agent.trim():"",i=typeof n.permissionMode=="string"?n.permissionMode.trim():"";(r||i)&&nt.getState().applyProcessDefaults({...r?{agent:r}:{},...i?{permissionMode:i}:{}}),i&&qa(i)&&Ge.getState().setCurrentMode(i);const s=f5(e);if(!nt.getState().processAgent&&s.lastUsedAgent&&nt.getState().hydrateStagedAgent(s.lastUsedAgent),!nt.getState().processPermissionMode&&s.lastPermissionMode){of(s.lastPermissionMode);const a=Ge.getState().currentMode;(!a||a==="default")&&Ge.getState().setCurrentMode(s.lastPermissionMode)}}catch{}}class gS{constructor(){we(this,"inFlight",null)}run(t){if(this.inFlight)return this.inFlight;const n=t();this.inFlight=n;const r=()=>{this.inFlight===n&&(this.inFlight=null)};return n.then(r,r),n}}class y5{constructor(){we(this,"generation",0);we(this,"pending")}begin(t,n){const r=n.trim();if(!t||!r)throw new Error("Session switch requires current and target session ids");if(this.pending)throw new Error(`Session switch already in progress: ${this.pending.targetSessionId}`);const i=Object.freeze({generation:++this.generation,previousSessionId:t,targetSessionId:r});return this.pending=i,i}expectedSessionId(t){var n;return((n=this.pending)==null?void 0:n.targetSessionId)??t}isCurrent(t){return this.pending===t}adoptRetargetedSession(t){const n=t.trim();if(!n)throw new Error("Retargeted session id is required");return this.generation++,this.pending=void 0,n}finish(t){this.pending===t&&(this.pending=void 0)}}function td(e){q$(e).then(t=>{Ge.getState().sessionId===e&&gC(t)}).catch(()=>{})}function fS(e){if(!e||typeof e!="object")return;const t=e;ot.getState().applyReconnectSnapshot({...typeof t.busy=="boolean"?{busy:t.busy}:{},..."activeGoal"in t?{activeGoal:t.activeGoal&&typeof t.activeGoal.condition=="string"&&t.activeGoal.condition&&typeof t.activeGoal.createdAt=="number"?{condition:t.activeGoal.condition,createdAt:t.activeGoal.createdAt,...typeof t.activeGoal.pausedAt=="number"?{pausedAt:t.activeGoal.pausedAt}:{}}:null}:{}})}function bS(e,t){const n=e.options||e.answers;let r=[];return Array.isArray(n)&&(r=n.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:r,multiSelect:!!e.multiSelect}}const _5={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},v5=new Set(["preparing","model_requesting","model_streaming","tool_executing","waiting_for_permission","waiting_for_user","retrying"]);function x5(e){return e.phase==="tool_executing"&&e.toolName?`phase.toolExecutingName:${e.toolName}`:e.phase==="model_streaming"&&e.streamingToolName?`phase.modelStreamingName:${e.streamingToolName}`:_5[e.phase]??null}const $h=100;let Ca=null;function st(){return Ca||(Ca=new rc),Ca}function w5(){const e=g.useRef(st()),t=g.useRef(new y5),n=g.useRef(null),r=g.useRef(new gS),i=g.useRef(new gS),s=g.useRef(null),a=g.useRef({fingerprint:"",at:0}),o=g.useRef({fingerprint:"",at:0}),c=g.useRef({fingerprint:"",at:0}),d=g.useRef(!1),[u,h]=g.useState(0),{setStatus:p,setSessionId:m,setSessionSwitching:f,setModels:b,setCurrentModel:_,setModes:v,setCurrentMode:A,setCommands:S,setTopic:y,setThinkingEnabled:x,setThoughtLevel:k,setPromptSuggestion:C}=Ge(),{addChunk:E,addThinkingChunk:N,addToolCall:z,updateToolCall:Q,addInterruption:T,addQuestion:w,setSessionEnd:L,resolveInterruptionByToolCallId:I,resolveQuestionByToolCallId:R,setHistoryLoading:$,addHistoryUserMessageChunk:D,addSubagentUserMessage:U,finalizeAssistantMessage:Y,clearChat:ee,resetForSessionChange:P,setAgentPhaseLabel:q,setProgressLabel:ue,setAgentRunning:_e,noteAgentActivity:ke,setCompactCancelled:H,addGoalProgress:G,showGoalRecap:V,addGoalStatus:oe,addGoalResult:J}=ot();g.useEffect(()=>{const ce=e.current;a.current={fingerprint:"",at:0},o.current={fingerprint:"",at:0},c.current={fingerprint:"",at:0};const ae=[],Ae=(F,ie)=>{if(!ie)return!1;try{const X=(ie._meta||{})["codebuddy.ai/memberEvent"];if(!X)return!1;const Ce=Ir.getState(),Ee=Ce.memberHistories[X]||[];return Ce.setMemberHistory(X,[...Ee,{sessionUpdate:F,...ie}]),!0}catch{return!1}},de=F=>{const ie=F==null?void 0:F.sessionId,fe=t.current.expectedSessionId(Ge.getState().sessionId);return typeof ie=="string"&&ie.length>0&&!!fe&&ie!==fe};return ae.push(ce.on("user_message_chunk",F=>{if(Ae("user_message_chunk",F)||de(F))return;const ie=F.content,fe=F._meta||{},X=!!fe["codebuddy.ai/isCompactInternal"],Ce=fe["codebuddy.ai/parentToolCallId"],Ee=typeof F.messageId=="string"?F.messageId:typeof fe["codebuddy.ai/messageId"]=="string"?fe["codebuddy.ai/messageId"]:void 0,Le=sC(ie,fe),We=Le.images.length>0?Le.images:void 0;let je;const et=fe["codebuddy.ai/channelSource"];et&&(je={source:et,sender:fe["codebuddy.ai/channelSender"]||"",senderName:fe["codebuddy.ai/channelSenderName"],chatId:fe["codebuddy.ai/channelChatId"],chatType:fe["codebuddy.ai/channelChatType"]});const ct=fe["codebuddy.ai/commandKind"]==="slash"?"slash":void 0;if(Le.text||We){if(!d.current){const gt=(We??[]).map(Nt=>"url"in Nt?Nt.url:"data").join(","),qe=`${F.sessionId??""}|${Ce??""}|${Le.text}|${gt}`,wt=Date.now();if(qe===c.current.fingerprint&&wt-c.current.at<$h)return;c.current={fingerprint:qe,at:wt}}Ce?U(Ce,Le.text,We):D(Ee,Le.text,We,X,je,ct)}})),ae.push(ce.on("agent_message_chunk",F=>{if(Ae("agent_message_chunk",F)||de(F))return;const ie=F.content,fe=F._meta||{},X=fe["codebuddy.ai/parentToolCallId"],Ce=!!fe["codebuddy.ai/isCompactInternal"],Ee=typeof F.messageId=="string"?F.messageId:typeof fe["codebuddy.ai/messageId"]=="string"?fe["codebuddy.ai/messageId"]:void 0,Le=eL(fe)?w1:typeof ie=="string"?ie:typeof(ie==null?void 0:ie.text)=="string"?ie.text:void 0;if(Le===void 0)return;const We=`${X??""}|${Le}`,je=Date.now();We===a.current.fingerprint&&je-a.current.at<$h||(a.current={fingerprint:We,at:je},d.current||ke(),!Ce&&!X&&nt.getState().setSessionBlank(!1),E(Le,X,Ce,Ee))})),ae.push(ce.on("agent_thought_chunk",F=>{if(Ae("agent_thought_chunk",F)||de(F))return;const ie=F.content,fe=F._meta||{},X=fe["codebuddy.ai/parentToolCallId"],Ce=typeof F.messageId=="string"?F.messageId:typeof fe["codebuddy.ai/messageId"]=="string"?fe["codebuddy.ai/messageId"]:void 0,Ee=typeof(ie==null?void 0:ie.text)=="string"?ie.text:void 0;if(Ee===void 0||!Ee.trim())return;const Le=`${X??""}|${Ee}`,We=Date.now();Le===o.current.fingerprint&&We-o.current.at<$h||(o.current={fingerprint:Le,at:We},d.current||ke(),N(Ee,X,Ce))})),ae.push(ce.on("tool_call",F=>{if(Ae("tool_call",F)||de(F))return;const ie=F._meta||{},fe=ie["codebuddy.ai/parentToolCallId"],X=!!ie["codebuddy.ai/isSubagent"],Ce=F.toolName||ie["codebuddy.ai/toolName"]||"",Ee=ie["codebuddy.ai/planContent"];d.current||ke();const Le={id:F.toolCallId,name:F.title||Ce||F.kind||"tool",kind:F.kind||"other",toolName:Ce,input:F.rawInput||F.input,status:"running",locations:F.locations,content:F.content,parentToolCallId:fe,subagent:X?{type:ie["codebuddy.ai/subagentType"]||"general-purpose",description:ie["codebuddy.ai/description"]||"",isBackground:!!ie["codebuddy.ai/isBackground"],memberName:ie["codebuddy.ai/memberName"]||void 0}:void 0,planContent:Ee};if(ot.getState().getToolCall(F.toolCallId)){const{id:je,input:et,...ct}=Le,qe=et&&typeof et=="object"&&Object.keys(et).length>0?{...ct,input:et}:ct;Q(F.toolCallId,qe)}else z(Le)})),ae.push(ce.on("tool_call_update",F=>{if(Ae("tool_call_update",F)||de(F))return;const fe={status:F.status==="completed"?"completed":F.status==="failed"?"failed":F.toolStatus==="completed"?"completed":F.toolStatus==="failed"?"failed":"running",result:F.rawOutput||F.toolResult};if(F.content!==void 0){const Le=(Array.isArray(F.content)?F.content:[]).filter(We=>{var je;return!We||typeof We!="object"?!0:!(We.type==="content"&&((je=We.content)==null?void 0:je.type)==="text")});Le.length>0&&(fe.content=Le)}F.rawInput&&typeof F.rawInput=="object"&&Object.keys(F.rawInput).length>0&&(fe.input=F.rawInput);const X=(F._meta||{})["codebuddy.ai"];X!=null&&X.toolMetaData&&(fe.metaData=X.toolMetaData);const Ce=(Array.isArray(F.content)?F.content:[]).find(Ee=>(Ee==null?void 0:Ee.type)==="terminal"&&typeof Ee.terminalId=="string");Ce!=null&&Ce.terminalId&&F.toolCallId&&$i.getState().linkToolCall(F.toolCallId,Ce.terminalId),Q(F.toolCallId,fe)})),ae.push(ce.on("terminal_update",F=>{if(de(F))return;const ie=(F._meta||{}).timestamp,fe=typeof ie=="string"?Date.parse(ie):void 0;$i.getState().applyTerminalUpdate(F,Number.isFinite(fe)?fe:void 0)})),ae.push(ce.on("interruption_request",F=>{var ie;if(!de(F)){if(F.toolName==="AskUserQuestion"){const fe=Array.isArray((ie=F.toolInput)==null?void 0:ie.questions)?F.toolInput.questions:[];w({id:F.toolCallId,toolCallId:F.toolCallId,sessionId:F.sessionId||Ge.getState().sessionId||"",source:"interruption",questions:fe.map(bS)});return}T({id:F.interruptionId,sessionId:F.sessionId,reason:F.reason,options:F.options,toolName:F.toolName,toolTitle:F.toolTitle,toolInput:F.toolInput,toolCallId:F.toolCallId,workflowSourceText:F.workflowSourceText,mcpUiIntercept:F.mcpUiIntercept===!0||typeof F.toolCallId=="string"&&F.toolCallId.startsWith("mcpui-")})}})),ae.push(ce.on("question_request",F=>{if(de(F))return;const ie=Array.isArray(F.questions)?F.questions:[];w({id:F.toolCallId,toolCallId:F.toolCallId,sessionId:F.sessionId||Ge.getState().sessionId||"",source:"extMethod",questions:ie.map(bS)})})),ae.push(ce.on("session_end",F=>{if(de(F))return;const ie=Vg(F);L(F.stopReason,Qg(ie)??F.errorMessage,ie.category,ie.finishReason??F.finishReason)})),ae.push(ce.on("session_info_update",F=>{F.title&&!de(F)&&y(F.title);const ie=F._meta||{};if(ie["codebuddy.ai/historyReplay"]==="start"?de(F)||(d.current=!0,s.current=typeof(F==null?void 0:F.sessionId)=="string"?F.sessionId:t.current.expectedSessionId(Ge.getState().sessionId),ee(),$i.getState().reset(),$(!0)):ie["codebuddy.ai/historyReplay"]==="end"&&(de(F)||(d.current=!1,$(!1),fS(ie["codebuddy.ai/sessionSnapshot"]),ot.getState().isAgentRunning||Y())),!de(F)&&"codebuddy.ai/sessionSnapshot"in ie&&ie["codebuddy.ai/historyReplay"]!=="start"&&ie["codebuddy.ai/historyReplay"]!=="end"&&fS(ie["codebuddy.ai/sessionSnapshot"]),!de(F)&&ie["codebuddy.ai/agentPhase"]){const X=ie["codebuddy.ai/agentPhase"];q(x5(X)),v5.has(X.phase)&&ke()}if("codebuddy.ai/progress"in ie){const X=ie["codebuddy.ai/progress"];X?(ue(`progress.${X.type}`),ke(),X.type==="compacting"&&H(!1)):ue(null)}if("codebuddy.ai/compact-cancelled"in ie){const X=ie["codebuddy.ai/compact-cancelled"];X&&typeof X=="object"&&H(!0)}if("codebuddy.ai/goalProgress"in ie){const X=ie["codebuddy.ai/goalProgress"];X&&typeof X=="object"&&X.condition&&G({id:X.id??`goal-progress-${Date.now()}`,condition:X.condition,reason:X.reason,turnCount:X.turnCount??1,createdAt:typeof X.createdAt=="number"?X.createdAt:void 0})}if("codebuddy.ai/goalResult"in ie){const X=ie["codebuddy.ai/goalResult"];X&&typeof X=="object"&&X.condition&&J({id:X.id??`goal-result-${Date.now()}`,ok:X.ok!==!1,reason:X.reason,condition:X.condition,durationMs:X.durationMs??0,turnCount:X.turnCount??1,tokenDelta:X.tokenDelta??0})}if("codebuddy.ai/goalRecap"in ie){const X=ie["codebuddy.ai/goalRecap"];X&&typeof X=="object"&&V(X)}if("codebuddy.ai/mcpFirstRunStatus"in ie){const X=ie["codebuddy.ai/mcpFirstRunStatus"];X&&typeof X=="object"&&qi.getState().applyEvent(X)}if("codebuddy.ai/goalStatus"in ie){const X=ie["codebuddy.ai/goalStatus"];X&&typeof X=="object"&&X.kind&&oe({id:X.id??`goal-status-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,kind:X.kind,condition:X.condition,prev:X.prev,actual:X.actual,max:X.max,createdAt:typeof X.createdAt=="number"?X.createdAt:void 0})}if(ie["codebuddy.ai/sessionReset"]){const X=ie["codebuddy.ai/newSessionId"];if(X)try{const Ce=t.current.adoptRetargetedSession(X);if(n.current=null,s.current=null,d.current=!1,P(),$(!1),f(!1),m(Ce),td(Ce),Ge.setState({topic:null}),C(null),bs.getState().reset(),ui.getState().reset(),typeof sessionStorage<"u"&&sessionStorage.setItem("acp-session-id",Ce),typeof localStorage<"u"&&localStorage.setItem("codebuddy.last-session-id",Ce),typeof window<"u"&&window.history&&window.location){const Ee=new URL(window.location.href);Ee.searchParams.set("sessionId",Ce),window.history.replaceState({},"",Ee.toString())}}catch(Ce){console.error(`Failed to commit new session after reset: ${Oo(Ce)}`,Ce)}}if(ie["codebuddy.ai/permissionResolved"]){const X=ie["codebuddy.ai/toolCallId"],Ce=ie["codebuddy.ai/decision"];X&&Ce?(qp({event:"client-resolved",toolCallId:X,decision:Ce}),st().clearPermissionRequestByToolCallId(X),I(X,Ce),R(X)):console.warn("[use-acp] permissionResolved missing toolCallId or decision, NOT dispatching",{toolCallId:X,decision:Ce})}if("codebuddy.ai/promptSuggestion"in ie){const X=ie["codebuddy.ai/promptSuggestion"];C(X||null)}const fe=ie["codebuddy.ai/teamUpdate"];if(fe)switch(fe.type){case"member_status_change":fe.members&&(fe.teamName?Ir.getState().setTeamStatus({isInTeam:!0,teamName:fe.teamName,isAutoTeam:fe.isAutoTeam,members:fe.members}):Ir.getState().updateMembers(fe.members));break;case"team_created":Ir.getState().setTeamStatus({isInTeam:!0,teamName:fe.teamName,members:[]});break;case"team_deleted":Ir.getState().clearTeam();break}})),ae.push(ce.on("model_update",F=>{de(F)||(b((F.availableModels||[]).map(ie=>{var fe,X;return{id:ie.modelId??ie.id,name:ie.name||ie.modelId||ie.id,description:ie.description??null,credits:((fe=ie._meta)==null?void 0:fe.credits)??null,contextWindow:((X=ie._meta)==null?void 0:X.maxInputTokens)??null}})),_(F.currentModelId||""))})),ae.push(ce.on("mode_update",F=>{de(F)||(F.availableModes&&v(F.availableModes),F.currentModeId&&A(F.currentModeId))})),ae.push(ce.on("current_mode_update",F=>{de(F)||F.currentModeId&&A(F.currentModeId)})),ae.push(ce.on("config_option_update",F=>{if(de(F))return;const ie=F.configOptions||[];for(const fe of ie)if(!mS(fe)){if(fe.id==="thought_level")x(fe.currentValue!=="disabled"),k({currentValue:fe.currentValue,options:fe.options||[]});else if(fe.id==="mode"&&fe.currentValue)A(fe.currentValue);else if(fe.id==="model"&&fe.currentValue&&(_(fe.currentValue),fe.options)){const X=Ge.getState().models;b(fe.options.map(Ce=>{const Ee=X.find(Le=>Le.id===Ce.value);return{id:Ce.value,name:Ce.name||Ce.value,description:Ce.description??(Ee==null?void 0:Ee.description)??null,credits:(Ee==null?void 0:Ee.credits)??null,contextWindow:(Ee==null?void 0:Ee.contextWindow)??null}}))}}})),ae.push(ce.on("status_change",F=>{F==="connected"&&!Ge.getState().sessionId||p(F)})),ae.push(ce.on("usage_update",F=>{if(typeof(F==null?void 0:F.used)!="number"||typeof(F==null?void 0:F.size)!="number")return;const ie=t.current.expectedSessionId(Ge.getState().sessionId);if(F.sessionId&&ie&&F.sessionId!==ie)return;const fe=F._meta||{};bs.getState().setUsage({sessionId:F.sessionId,used:F.used,size:F.size,cost:F.cost,usageByCategory:fe["codebuddy.ai/usageByCategory"]})})),ae.push(ce.on("available_commands_update",F=>{de(F)||F.availableCommands&&S(F.availableCommands.map(ie=>{var fe,X;return{name:ie.name,description:ie.description||"",...((fe=ie._meta)==null?void 0:fe.type)==="skill"?{type:"skill"}:{},...typeof((X=ie._meta)==null?void 0:X.source)=="string"&&ie._meta.source?{source:ie._meta.source}:{}}}))})),ae.push(ce.on("checkpointCreated",F=>{ui.getState().onCheckpoint(F)})),ae.push(ce.on("checkpointUpdated",F=>{ui.getState().onCheckpoint(F)})),ae.push(ce.on("checkpointReverted",()=>{ui.getState().reset()})),()=>{ae.forEach(F=>F())}},[u]);const he=g.useCallback((ce,ae)=>{var Ae;if(ce.models&&(b(ce.models.availableModels.map(de=>{var F,ie;return{id:de.modelId??de.id,name:de.name||de.modelId||de.id,description:de.description??null,credits:((F=de._meta)==null?void 0:F.credits)??null,contextWindow:((ie=de._meta)==null?void 0:ie.maxInputTokens)??null}})),_(ce.models.currentModelId)),ce.modes&&(v(ce.modes.availableModes),A(ce.modes.currentModeId)),ce.configOptions)for(const de of ce.configOptions)de.id==="thought_level"&&(x(de.currentValue!=="disabled"),k({currentValue:de.currentValue,options:de.options||[]})),mS(de);if((ce.agents||ce.currentAgentName!==void 0||ce.sessionBlank!==void 0)&&nt.getState().applyAgentFromResponse({agents:ce.agents,currentAgentName:ce.currentAgentName,defaultAgentName:ce.defaultAgentName,sessionBlank:ce.sessionBlank}),ae!=null&&ae.applyLastUsedPrefs){const de=nt.getState().processAgent,F=nt.getState().processPermissionMode,ie=de?null:g5({sessionBlank:ce.sessionBlank??!0,stagedAgent:nt.getState().stagedAgent,stored:typeof localStorage<"u"?localStorage.getItem(Aa):null,sessionId:Ge.getState().sessionId,currentAgentName:ce.currentAgentName,defaultAgentName:ce.defaultAgentName});ie&&ie.agentName!==ce.currentAgentName&&(fC(),nt.getState().setLoading(),st().callExtMethod("session/set_agent",{sessionId:ie.sessionId,agentName:ie.agentName}).then(Le=>{Le!=null&&Le.agentName?nt.getState().applySetAgentResult({agentName:Le.agentName,models:Le.models??[],currentModelId:Le.currentModelId??"",sessionBlank:Le.sessionBlank??!1}):Ao()}).catch(Le=>{Ao(),console.warn("[use-acp] staged main agent injection failed (kept for retry):",Le)}));const fe=F??xC(),X=Ge.getState().sessionId,Ce=(Ae=ce.modes)==null?void 0:Ae.currentModeId,Ee=(ie==null?void 0:ie.agentName)??de??ce.currentAgentName;fe&&X&&fe!==Ce&&!(Ee==="minimal"&&fe==="plan")&&st().setMode(X,fe).then(()=>{Ge.getState().setCurrentMode(fe)}).catch(Le=>{console.warn("[use-acp] last permission mode injection failed:",Le)})}},[]),ne=g.useCallback(ce=>{const ae=ce.trim(),Ae=Ge.getState().sessionId;if(!Ae||!ae)return Promise.reject(new Error("Session switch requires current and target session ids"));if(Ae===ae)return Promise.resolve(!0);const de=n.current;if(de)return de.targetSessionId===ae?de.promise:Promise.reject(new Error(`Session switch already in progress: ${de.targetSessionId}`));const F=t.current.begin(Ae,ae),ie=Ge.getState(),fe=ot.getState(),X=bs.getState(),Ce=ui.getState(),Ee=$i.getState(),Le=nt.getState();f(!0),Ge.setState({topic:null}),C(null),bs.getState().reset(),ui.getState().reset(),$i.getState().reset(),nt.getState().reset({keepProcessDefaults:!0}),s.current=null,d.current=!1;const We={targetSessionId:ae,promise:Promise.resolve(!1)},je=(async()=>{try{const et=await e.current.loadSession(ae);if(!t.current.isCurrent(F))throw new Error(`Stale session switch response: ${ae}`);if(s.current!==ae?P():_e(!1),m(ae),td(ae),he(et),typeof sessionStorage<"u"&&sessionStorage.setItem("acp-session-id",ae),typeof localStorage<"u"&&localStorage.setItem("codebuddy.last-session-id",ae),typeof window<"u"&&window.history&&window.location){const ct=new URL(window.location.href);ct.searchParams.get("sessionId")!==ae&&(ct.searchParams.set("sessionId",ae),window.history.replaceState({},"",ct.toString()))}return!0}catch(et){throw t.current.isCurrent(F)&&(Ge.setState(ie),ot.setState(fe),bs.setState(X),ui.setState(Ce),$i.setState(Ee),nt.setState(Le)),et}finally{t.current.finish(F),s.current=null,d.current=!1,f(!1),n.current===We&&(n.current=null)}})();return We.promise=je,n.current=We,je},[he,P,_e,C,m,f]),pe=g.useCallback(ce=>i.current.run(async()=>{const ae=(ce==null?void 0:ce.persistLastId)!==!1,Ae=Ge.getState(),de=ot.getState(),F=bs.getState(),ie=ui.getState();if(!ae)return(await e.current.newSession({persistLastId:!1})).sessionId;f(!0);try{l5({currentMode:Ae.currentMode,processPermissionMode:nt.getState().processPermissionMode})&&lf(Ae.currentMode);const fe=await e.current.newSession();return t.current.adoptRetargetedSession(fe.sessionId),n.current=null,s.current=null,d.current=!1,P(),m(fe.sessionId),td(fe.sessionId),he(fe,{applyLastUsedPrefs:!0}),Ge.setState({topic:null}),C(null),bs.getState().reset(),ui.getState().reset(),fe.sessionId}catch(fe){throw Ge.setState(Ae),ot.setState(de),bs.setState(F),ui.setState(ie),fe}finally{f(!1)}}),[he,P,C,m,f]),re=g.useCallback(ce=>r.current.run(async()=>{const ae=typeof ce=="string"?ce:ce==null?void 0:ce.token,Ae=typeof ce=="object"?ce==null?void 0:ce.continue:!1;if(ae){if(Ca)try{await Ca.disconnect()}catch{}Ca=new rc(void 0,ae),e.current=Ca,h(de=>de+1),await new Promise(de=>setTimeout(de,0))}try{p("connecting"),C(null);const de=await e.current.initializeSession({continue:Ae});m(de.sessionId),td(de.sessionId),de.processDefaults&&(nt.getState().applyProcessDefaults(de.processDefaults),de.processDefaults.permissionMode&&Ge.getState().setCurrentMode(de.processDefaults.permissionMode)),he(de,{applyLastUsedPrefs:de.sessionBlank===!0}),nt.getState().applyBackendSupport(de.mainAgentSupport===!0),p("connected"),yC.getState().fetchUserInfo(e.current)}catch(de){console.error("Connection failed:",de),p("error")}}),[]);return{client:e.current,connect:re,switchSession:ne,createSession:pe}}const cf="/assets/red-claw-cat--t2EuBIB.png",wC="codebuddy-locale";function SC(){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 Oh(e){return e==="system"?SC():e}function S5(){try{const e=localStorage.getItem(wC);if(e){const t=JSON.parse(e),n=(t==null?void 0:t.mode)??e;if(["zh","en","system"].includes(n))return n}}catch{}return"system"}const uu=Rt()(Ga((e,t)=>{const n=S5(),r=Oh(n);return typeof window<"u"&&window.addEventListener("languagechange",()=>{const i=uu.getState();if(i.mode==="system"){const s=SC();s!==i.resolved&&uu.setState({resolved:s})}}),{mode:n,resolved:r,setLocale:i=>{const s=Oh(i);e({mode:i,resolved:s})},toggle:()=>{const i=t().mode,s=i==="zh"?"en":i==="en"?"system":"zh";t().setLocale(s)}}},{namespace:"locale",fields:["mode"],scope:"global",debounceMs:300,localStorageKey:wC,onLoad:(e,t)=>{if(e.mode){const n=Oh(e.mode);t({mode:e.mode,resolved:n})}}})),yS={zh:{"app.connecting":"正在连接 CodeBuddy Code...","agents.action.delete":"删除","agents.action.delete.confirm":"确定要删除这个智能体吗?","agents.action.delete.failed":"未能删除这个智能体","agents.action.delete.worktreeKept":"智能体已删除,工作树保留在 {path}","agents.action.more":"更多操作","agents.action.new":"新建智能体","agents.action.cancelNew":"取消新建","agents.action.newConversation":"在当前智能体中新建对话","agents.action.rename":"重命名","agents.action.restart":"重新启动","agents.action.stop":"停止","agents.action.pin":"置顶","agents.action.unpin":"取消置顶","agents.action.ungroup":"从项目中移除","agents.action.copySessionId":"复制会话 ID","agents.action.copyCwd":"复制工作目录","agents.action.openInNewWindow":"在新窗口中打开","agents.action.copyOk":"已复制到剪贴板","agents.action.copyFailed":"复制失败","agents.empty":"暂无活跃的智能体","agents.empty.hint":"点击面板顶部 + 新建智能体","agents.group.attention":"需要你输入","agents.group.needsInput":"需要输入","agents.group.working":"运行中","agents.group.showMore":"展开显示({count})","agents.group.showLess":"收起显示","agents.group.pinned":"置顶","agents.panel.title":"智能体实例","agents.panel.resize":"调整智能体面板宽度","agents.project.rename":"重命名项目","agents.search.clear":"清空搜索","agents.search.noMatch":"没有匹配的智能体","agents.search.placeholder":"搜索智能体","layout.toggle":"布局","layout.sidebar":"导航侧边栏","layout.agents":"智能体面板","agents.title":"智能体","agents.instanceFallback":"智能体 {id}","agents.panel.close":"关闭","agents.input.placeholder":"描述这个智能体要做什么…","agents.input.hint":"在所选工作目录启动一个 CodeBuddy 智能体","agents.input.submit":"创建智能体","agents.input.permission":"启动权限","agents.input.permission.default":"跟随默认设置","agents.input.permission.default.desc":"不覆盖权限模式,使用当前配置的默认权限","agents.input.permission.ask":"每次询问","agents.input.model":"模型","agents.input.model.default":"默认模型","agents.input.effort":"思考强度","agents.input.effort.default":"跟随模型","agents.input.effort.default.desc":"使用所选模型配置的默认思考强度","agents.input.directory":"工作目录","agents.input.directory.hint":"智能体将在此目录执行命令、读写文件","agents.input.directory.choose":"选择工作目录","agents.input.directory.current":"当前工作区","agents.input.directory.more":"另有 {count} 个","agents.input.directory.loading":"正在发现仓库与工作树…","agents.input.directory.browse":"选择其他目录…","agents.input.agent":"当前智能体","agents.input.agent.menu":"选择智能体","agents.input.agent.default":"默认智能体","agents.input.agent.default.desc":"使用当前项目的默认智能体配置","agents.input.settings":"智能体设置","agents.input.modelAndEffort":"模型与思考","agents.input.shellJob":"Shell 任务","agents.input.shellPlaceholder":"输入要在后台执行的命令…","agents.input.attachmentsNotForShell":"Shell 任务不能携带附件,请先去掉文件或去掉命令前的 !","agents.input.startFrom":"上下文","agents.input.startFrom.continue":"继承当前对话","agents.input.startFrom.session":"继承所选对话","agents.input.startFrom.blank":"不继承","agents.input.startFrom.unavailable":"当前没有可继承的上下文","agents.input.worktree":"工作树","agents.input.worktree.on":"已开启工作树隔离","agents.input.worktree.off":"已关闭工作树隔离(Web 默认)","inherit.drawer.title":"选择上下文","inherit.fromCurrent":"当前对话","inherit.fromSession":"可继承的对话","inherit.emptyForDirectory":"这个目录还没有可继承的对话","agents.worker.standalone":"独立进程","agents.worker.remote":"远程","agents.worker.openTabHint":"点击在标签页打开完整实例","agents.worker.noUrl":"无访问地址,仅可在宿主侧操作","agents.worker.kind.interactive":"交互终端","agents.worker.kind.daemon":"服务进程","agents.worker.kind.daemonWorker":"工作进程","agents.worker.kind.bg":"后台任务","agents.state.failed":"失败","agents.state.stopped":"已停止","agents.state.idle":"空闲","agents.state.draft":"待创建","agents.state.completed":"已完成","agents.notice.failed":"会话意外结束,点击查看并可重新启动","agents.state.recovering":"恢复中…","recent.title":"最近会话","sessions.current":"当前","sessions.currentTitle":"主智能体","sessions.deleteCurrent":"删除当前对话","sessions.deleteCurrent.confirm":"将结束当前对话并删除其历史记录,确定吗?","sessions.foregroundHandoff":"已转为后台,仍由主对话承载","sessions.worker.openTab":"在新标签页打开","sessions.section":"实例列表","sessions.togglePanel":"切换会话面板","agents.phase.preparing":"准备中","agents.phase.modelRequesting":"请求模型中…","agents.phase.modelStreaming":"正在生成回复…","agents.phase.modelDone":"收尾中…","agents.phase.toolExecuting":"执行工具中…","agents.phase.working":"工作中…","agents.phase.retrying":"重试中…","agents.phase.compacting":"压缩上下文中…","agents.phase.cancelling":"取消中…","agents.phase.resuming":"恢复中…","agents.phase.starting":"启动中…","agents.phase.waitingPermission":"等待权限确认","agents.phase.waitingInput":"等待输入","agents.live.background":"由后台进程继续执行","agents.live.creating":"正在创建智能体,启动后将自动进入","agents.live.restoring":"正在恢复智能体,可先查看完整对话","agents.live.settled":"智能体已结束运行","agents.live.foregroundHeld":"宿主对话正在持有,可继续投递","agents.live.latest":"智能体最新回复","agents.live.tool":"正在使用工具","agents.live.result":"执行结果","agents.reply.sent":"已发送给这个智能体","agents.reply.saved":"已保存,将在智能体恢复后发送","agents.reply.failed":"发送给智能体失败","agents.reply.answerPlaceholder":"回答这个智能体…","agents.reply.useSuggestion":"采用建议回复","agents.reply.tabSuggestion":"Tab 采用建议 · 数字键选择选项","agents.reply.shellHint":"输入 ! 可在智能体内执行 Shell 命令","agents.reply.shellMode":"Shell","agents.reply.sendShell":"执行 Shell 命令","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.messages":"聊天消息","chat.scrollToLatest":"跳到最新","chat.error.refusal":"Agent 拒绝继续执行。这可能是由于内容策略限制或其他限制。","chat.error.network":"网络连接异常或服务暂时不可用,请稍后重试。","chat.error.auth":"身份验证失败或权限不足,请重新登录后再试。","chat.error.quota":"已达到配额上限或请求过于频繁,请稍后再试。","chat.error.modelService":"模型服务返回异常,请重试或稍后再试。","chat.error.cancelled":"请求已被取消,可能由系统休眠或网络中断导致,请重试。","chat.error.maxTokens":"响应因达到最大 token 限制而被截断。您可以继续对话或要求更简洁的回复。","chat.error.maxTurnRequests":"已超过单轮对话允许的最大模型请求次数。您可以发送新消息以继续。","message.contentFilter.notice":"这个话题目前不在我的能力覆盖范围内,我没有办法就此展开讨论。","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":"压缩上下文中","hero.headline":"CodeBuddy Code","hero.newAgent":"新建智能体","input.placeholder":"告诉这个智能体下一步要做什么...","input.placeholderGoal":"描述你的目标,定义可衡量的成果,以获得最佳效果","input.placeholderRunning":"消息将排队等待处理...","input.placeholderPending":"请先处理权限请求...","input.draft":"草稿","input.send":"发送 (Enter)","input.stop":"停止","input.thinking":"思考中","input.deepThinking":"深度思考","input.promptFailed":"发送失败","input.sessionNotReady":"会话尚未就绪,请稍后再发送","input.agentSwitchTimeout":"Agent 预设切换超时,请重试","input.sendQueued":"发送排队消息 (Enter)","input.dropHint":"拖拽文件到这里","input.addImage":"添加图片","input.addFile":"添加文件","input.goal":"目标","input.imageTooLarge":"图片不能超过 10MB","input.tooManyImages":"最多添加 5 张图片","input.fileTooLarge":"文件不能超过 50MB","input.tooManyFiles":"最多添加 10 个文件","input.attachmentUploadFailed":"附件上传失败,请重试","input.menu.image":"图片","input.menu.file":"文件","input.menu.directory":"目录","input.directory.current":"当前目录","input.directory.add":"添加目录","input.menu.mode":"模式","input.menu.model":"模型","input.modeSelector":"模式","input.modelSelector":"模型","mainAgent.defaultLabel":"默认预设","mainAgent.selectAgent":"即将开始的这个会话所用的 Agent 预设","mainAgent.lockedHint":"本会话运行的 Agent 预设,开始时即固定","mainAgent.customTag":"本地创作","mainAgent.empty":"暂无可用预设","mainAgent.sectionTitle":"Agent 预设","mainAgent.manage":"管理预设","mainAgent.currentDefault":"当前默认","mainAgent.currentDefaultHint":"对此后新建的会话生效。运行中的会话保持它开始时的预设。","mainAgent.isDefault":"默认","mainAgent.setDefault":"设为默认","mainAgent.defaultSaved":"默认预设已保存","mainAgent.groupBuiltin":"内置","mainAgent.groupCustom":"自定义","mainAgent.createByAI":"用 AI 快速创建","mainAgent.createByAIHint":"用一句话描述你想要的智能体,AI 会生成名字、说明和系统提示(写入用户级目录;工具按最小权限自动选择)。这不是创造模式会话。","mainAgent.createByAIPlaceholder":"例如:做一个只读的代码评审智能体,用 hy3 模型","mainAgent.creating":"正在生成","mainAgent.createSuccess":"智能体已创建,可在会话中选用","mainAgent.capability":"Agent 预设","mainAgent.capabilityHint":"开启后可在本 Web 选择标准 / PTC / 极简 / 创造。WorkBuddy 默认不走预设解析;若与 sidecar 共用同一份 settings,再打开「允许未声明宿主」才会影响 WorkBuddy。","mainAgent.capabilityOn":"已开启","mainAgent.capabilityOff":"已关闭","mainAgent.noDescription":"暂无描述。","mainAgent.mode.cli":"标准模式","mainAgent.mode.ptc":"PTC 模式","mainAgent.mode.minimal":"极简模式","mainAgent.mode.create":"创造模式","mainAgent.modeDesc.cli":"功能完整的编码 Agent:改文件、跑命令、检索代码和网页,以及 Skills、计划、目标和子代理。","mainAgent.modeDesc.ptc":"标准模式的工作工具改走 REPL / Code Mode,用一段程序组合多步,而不是逐个直连调用。","mainAgent.modeDesc.minimal":"只开 REPL,沙箱内仅 Bash 与 Edit。没有 Read、Write、Glob、Grep、检索、计划、子代理。看文件用 Bash,读 r.stdout。","mainAgent.modeDesc.create":"标准模式全工具,外加编写 .codebuddy/agents 自定义智能体的指导。","mainAgent.scope.user":"用户级","mainAgent.scope.project":"项目级","mainAgent.delete":"删除","mainAgent.deleteConfirm":"确认删除?","mainAgent.deleted":"已删除 {name}","mainAgent.deleteFailed":"删除失败","mainAgent.searchPlaceholder":"搜索智能体名称或描述","mainAgent.filterEmpty":"没有匹配的智能体","mainAgent.openFile":"打开文件","mainAgent.openFailed":"打开文件失败","mainAgent.openInCreate":"在创造模式中打开","mainAgent.openInCreateSuccess":"已切换到创造模式","mainAgent.openInCreateFailed":"仅空白会话可切换到创造模式","mainAgent.trustLocal":"本地","input.deepThinkingDesc":"让模型在回答前进行更深入的推理","input.thinkingLevel":"思考强度","input.thinkingMode":"思考模式","input.thoughtDefault":"默认","input.contextWindow":"上下文窗口","input.editThinking":"编辑思考配置","input.modelHeader":"模型","input.contextUsage.title":"上下文用量","input.contextUsage.used":"已用上下文","input.contextUsage.usedLabel":"已使用","input.contextUsage.compact":"压缩当前会话","input.contextUsage.systemPrompt":"系统提示词","input.contextUsage.conversation":"对话消息","input.contextUsage.tools":"工具及子智能体","input.contextUsage.mcp":"连接器及MCP","input.contextUsage.skills":"技能","mode.default":"默认","mode.default.desc":"每次首次使用工具时都请求权限","mode.acceptEdits":"自动通过编辑","mode.acceptEdits.desc":"本会话自动通过文件编辑权限","mode.plan":"规划模式","mode.plan.desc":"只分析、不修改文件或执行命令","mode.auto":"自动","mode.auto.desc":"AI 分类器审查操作:安全的自动通过,高风险的拒绝。分类器不可用时回退为弹窗确认(或拒绝)","mode.dontAsk":"免打扰","mode.dontAsk.desc":"不弹出权限确认;执行预批准和安全操作,拒绝需要审批的操作","mode.bypassPermissions":"跳过权限确认","mode.bypassPermissions.desc":"跳过所有权限确认","mode.fullAccess":"完全访问","mode.fullAccess.desc":"跳过所有权限检查,包括所有代理的危险命令","mode.work":"工作","mode.work.desc":"标准工作模式,按常规流程请求权限","mode.delegate":"委托","mode.delegate.desc":"权限由上级会话集中管理","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.replSubagentSummary":"REPL 内子 agent 输出已在上方/下方独立展示,这里不重复展开原始文本。","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.toggle":"切换菜单栏","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":"复制","clipboard.copyFailed":"复制失败:当前环境不支持剪贴板操作,请使用 HTTPS 访问或手动选择文本复制","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":"服务条款","account.login.title":"账户登录","account.login.subtitle":"CodeBuddy 尚未登录,请选择登录方式完成认证","account.login.button":"登录","account.login.polling":"等待登录完成...","account.login.polling.hint":"请在浏览器中完成登录,完成后此页面将自动跳转","account.login.openBrowser":"打开浏览器登录","account.login.copyUrl":"复制登录链接","account.login.copied":"已复制","account.login.failed":"登录失败,请重试","account.login.retry":"重试","account.logout":"退出登录","account.logout.confirm":"确认退出当前账户?","account.method.internal":"国内站点登录","account.method.external":"国际站点登录","account.method.selfhosted":"企业域名登录","account.method.iOA":"iOA 登录(仅限腾讯)","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.split":"拆分终端","terminal.splitHorizontal":"左右分屏","terminal.splitVertical":"上下分屏","terminal.closePane":"关闭终端","terminal.close":"关闭","terminal.closeOthers":"关闭其他","terminal.closeToRight":"关闭右侧","terminal.closeAll":"关闭全部","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":"问题已取消","question.invalid":"问题参数无效,无法显示","todo.title":"任务清单","todo.executing":"任务{n}正在执行中","todo.untitled":"未命名","bgTasks.summary":"{total} 个后台任务 · {running} 个运行中","bgTasks.status.done":"已完成","bgTasks.status.failed":"已失败","bgTasks.status.ended":"已结束","bgTasks.status.elapsed":"已运行 {duration}","bgTasks.untitled":"后台命令","history.title":"智能体历史","history.description":"在当前智能体内继续项目对话","history.backgroundDescription":"智能体正在后台工作,完成接管后可切换对话","history.target":"载入到 {name}","history.project":"项目","history.noProjects":"暂无可用项目","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":"无法删除当前会话","history.renameFailed":"重命名失败","history.deleteFailed":"删除失败","history.restore":"在当前智能体中打开","history.restoreSuccess":"已在当前智能体中继续该对话","history.restoreFailed":"载入历史对话失败","settings.title":"设置","settings.appearance":"外观","settings.model":"模型选择","settings.customModels.manage":"管理自定义模型","settings.customModels.entryLabel":"自定义模型","settings.customModels.entryDesc":"添加 OpenAI 兼容端点,支持增删改","settings.customModels.title":"自定义模型","settings.customModels.addTitle":"添加自定义模型","settings.customModels.editTitle":"编辑自定义模型","settings.customModels.add":"添加","settings.customModels.edit":"编辑","settings.customModels.delete":"删除","settings.customModels.deleteTitle":"删除自定义模型?","settings.customModels.deleteMessage":"将删除模型 {id},此操作不可撤销。","settings.customModels.cancel":"取消","settings.customModels.save":"保存","settings.customModels.close":"关闭","settings.customModels.empty":"暂无自定义模型","settings.customModels.hint":"数据保存在本机 ~/.codebuddy/models.json","settings.customModels.loadFailed":"加载自定义模型失败","settings.customModels.saveFailed":"保存失败","settings.customModels.deleteFailed":"删除失败","settings.customModels.apiKeyKeep":"留空则保留原密钥","settings.customModels.field.id":"模型 ID","settings.customModels.field.name":"显示名称","settings.customModels.field.vendor":"提供商","settings.customModels.field.url":"接口 URL","settings.customModels.field.apiKey":"API Key","settings.customModels.field.maxInputTokens":"最大输入 Tokens","settings.customModels.field.maxOutputTokens":"最大输出 Tokens","settings.customModels.field.temperature":"Temperature","settings.customModels.field.temperatureDefault":"留空使用默认值(不发送)","settings.customModels.field.supportsToolCall":"支持工具调用","settings.customModels.field.supportsImages":"支持图片","settings.customModels.field.supportsReasoning":"支持推理","settings.customModels.field.useCustomProtocol":"自定义协议(不自动补 /chat/completions)","settings.customModels.err.idRequired":"请填写模型 ID","settings.customModels.err.idInvalid":"模型 ID 仅允许字母、数字与 . _ : -","settings.customModels.err.idDuplicate":"模型 ID 已存在","settings.customModels.err.urlRequired":"请填写接口 URL","settings.customModels.err.urlInvalid":"URL 需以 http:// 或 https:// 开头","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.mainAgent":"Agent 预设","settings.item.mainAgent.enabled":"启用 Agent 预设","settings.item.mainAgent.enabled.desc":"Web / CLI 可选择标准、PTC、极简、创造。关闭后始终走原生标准模式。","settings.item.mainAgent.allowUnopted":"允许未声明的 ACP 宿主","settings.item.mainAgent.allowUnopted.desc":"默认关闭,且仅在上方总闸开启时生效。打开后,与本机共用 settings 的 WorkBuddy sidecar 也会走预设解析。平时请保持关闭。","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.autoCompactWindow":"自动压缩窗口 (token)","settings.item.autoCompactWindow.desc":"压缩计算的上下文窗口基准值,触发点 = min(该值, 模型窗口) × 阈值;留空跟随模型窗口。环境变量 CODEBUDDY_AUTO_COMPACT_WINDOW 优先级更高","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.reconnecting":"正在重新连接...","terminal.reconnectFailed":"重连失败","terminal.search.placeholder":"查找","terminal.search.noResults":"无结果","terminal.search.caseSensitive":"区分大小写","terminal.search.wholeWord":"全字匹配","terminal.search.regex":"使用正则表达式","terminal.search.previous":"上一个匹配","terminal.search.next":"下一个匹配","terminal.search.close":"关闭","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":"上次触发","scheduled.custom":"自定义","scheduled.every":"每","scheduled.unit.minutes":"分钟","scheduled.unit.hours":"小时","scheduled.unit.days":"天","scheduled.unit.weeks":"周","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.kindAll":"全部","plugins.kindSkills":"Skills","plugins.kindMcp":"MCP","plugins.kindHooks":"Hooks","plugins.kindTools":"Tools","plugins.kindUnknown":"其他","plugins.filterStatusAll":"全部状态","plugins.filterStatusEnabled":"已启用","plugins.filterStatusDisabled":"未启用","plugins.infiniteRange":"已显示 {visible} / {total}","plugins.infiniteLoading":"向下滚动加载更多","plugins.infiniteEnd":"已显示全部","plugins.backToTop":"回到顶部","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.loadingFile":"正在加载文件...","editor.loadError":"加载失败","editor.retryLoad":"重试加载","editor.fileTooLarge":"超过 2 MB,无法在编辑器打开","editor.noFile":"选择一个文件开始编辑","editor.unsaved":"未保存","editor.saving":"正在保存","editor.saveFailed":"保存失败","editor.moveFailed":"移动失败","editor.save":"保存","editor.saveAll":"全部保存","editor.close":"关闭","editor.closeTabAriaLabel":"关闭标签页 {name}","editor.closeOthers":"关闭其他","editor.closeAll":"关闭全部","editor.newFile":"新建文件","editor.newFolder":"新建文件夹","editor.rename":"重命名","editor.delete":"删除","editor.deleteConfirmTitle":"确认删除","editor.deleteConfirmMessage":"确定要删除选中的 {count} 个项目吗?此操作无法撤销。","editor.refresh":"刷新","editor.backToWorkDir":"回到工作目录","editor.emptyFolder":"空文件夹","editor.explorer":"资源管理器","editor.fileTreeAriaLabel":"工作区文件树","editor.toggleSidebar":"切换侧边栏","editor.collapseAll":"全部折叠","editor.showHiddenFiles":"显示隐藏文件","editor.hideHiddenFiles":"隐藏隐藏文件","editor.openFolder":"打开目录","editor.openFolderPlaceholder":"输入目录路径...","editor.parentFolder":"上级目录","editor.pin":"固定","editor.unpin":"取消固定","editor.copyPath":"复制路径","editor.copyRelativePath":"复制相对路径","editor.revealInExplorer":"在文件树中定位","editor.closeToRight":"关闭右侧","editor.closeSaved":"关闭已保存","editor.closeSaveFailedTitle":"无法关闭:{count} 个标签页保存失败","editor.closeSaveFailedMessage":"{count} 个标签页保存失败。是否放弃更改并关闭?","editor.discardAndClose":"放弃并关闭","editor.quickOpen":"快速打开文件","editor.focusExplorer":"聚焦资源管理器","editor.recentFiles":"最近文件","editor.quickOpenPlaceholder":"输入文件名以搜索...","editor.quickOpenEmpty":"没有匹配的文件","editor.quickOpenLoading":"正在加载文件列表...","editor.openEditors":"已打开的编辑器","editor.scrollTabsLeft":"向左滚动标签页","editor.scrollTabsRight":"向右滚动标签页","editor.selected":"已选","editor.lines":"行","editor.preview":"切换到预览","editor.source":"切换到源码","editor.openInNewWindow":"在新窗口中打开","editor.mobileBack":"返回文件树","ide.explorer":"资源管理器","ide.search":"搜索","ide.sourceControl":"源代码管理","ide.terminal":"终端","ide.newTerminal":"新建终端","ide.toggleSidebar":"切换侧栏","ide.toggleTerminal":"切换终端","ide.resizeSidebar":"调整侧栏宽度","ide.resizeSidePanel":"调整侧边面板宽度","ide.resizeBottomPanel":"调整底部面板高度","ide.resizeSplit":"调整分屏比例","ide.hidePanel":"隐藏面板","ide.maximizePanel":"最大化面板","ide.restorePanel":"还原面板大小","ide.listView":"列表视图","ide.treeView":"树视图","ide.refresh":"刷新","ide.scm.title":"源代码管理","ide.scm.repositories":"仓库","ide.scm.changes":"变更","ide.scm.stagedChanges":"已暂存的更改","ide.scm.untracked":"未跟踪","ide.scm.noChanges":"没有更改","ide.scm.notGitRepo":"不是 Git 仓库","ide.scm.commitPlaceholder":"消息 (⌘Enter 提交)","ide.scm.commit":"提交","ide.scm.push":"推送","ide.scm.pull":"拉取","ide.scm.stage":"暂存","ide.scm.unstage":"取消暂存","ide.scm.stageAll":"全部暂存","ide.scm.unstageAll":"全部取消暂存","ide.scm.discard":"放弃更改","ide.scm.discardAll":"全部放弃","ide.scm.copyPath":"复制路径","ide.scm.openFile":"打开文件","ide.scm.createBranch":"创建新分支...","ide.scm.newBranchPlaceholder":"新分支名称...","ide.scm.branchSearchPlaceholder":"搜索分支或标签...","ide.scm.switchBranch":"切换分支","ide.scm.localBranches":"本地分支","ide.scm.remoteBranches":"远程分支","ide.scm.noBranchMatch":"没有匹配的分支","ide.scm.graph":"提交记录","ide.scm.closeDiff":"关闭差异","ide.scm.loadingDiff":"加载差异中...","ide.scm.diff":"差异","ide.search.title":"搜索","ide.search.placeholder":"搜索","ide.search.searching":"搜索中...","ide.search.noResults":"未找到结果","ide.search.results":"{count} 个结果,{files} 个文件","ide.search.matchCase":"区分大小写","ide.search.wholeWord":"全字匹配","ide.search.regex":"使用正则表达式","ide.search.filesToInclude":"要包含的文件","ide.search.includePlaceholder":"例如 *.ts, src/**/include","ide.search.filesToExclude":"要排除的文件","ide.search.excludePlaceholder":"例如 node_modules, *.min.js","ide.search.useExcludeSettings":"使用排除设置和忽略文件","ide.search.toggleFilters":"文件筛选器","ide.search.failed":"搜索失败","ide.search.timedOut":"搜索超时","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.goal.title":"Goal","command.goal.description":"设置要持续追求的目标","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.jobCreateFailed":"创建智能体失败,请重试","error.switchSessionFailed":"切换会话失败,请重试","error.sessionOccupied":"该会话正被其他终端或进程占用,无法同时切换","error.sessionUnavailable":"该会话当前不可用,请稍后重试","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":"个工具已执行","tool.mcpAppLoadHint":"点击加载交互式界面","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 <条件>
579
+ `).replace(/^\n+/,"").replace(/\n+$/,"")}function nC(e){return e.replace(/\\"/g,'"').replace(/\\\\/g,"\\")}function rC(e,t){const n=e.trim().replace(/\\/g,"/");if(!n||n.includes("\0")||n.includes(".."))return null;if(em(n)||n.toLowerCase().startsWith("file://"))return Bi(n);if(!t)return null;const r=t.replace(/[\\/]+$/,"").replace(/\\/g,"/");return!em(r)||r.includes("..")?null:Bi(`${r}/${n.replace(/^\.\//,"")}`)}function D$(e){const t=e.trim();if(!t)return null;const n=t.toLowerCase();if(n.startsWith("javascript:")||n.startsWith("vbscript:")||n.startsWith("blob:"))return null;if(n.startsWith("data:"))return t.length>x$?null:B$(t)?t:null;if(t.length>v$)return null;if(n.startsWith("http://")||n.startsWith("https://"))return t;if(t.startsWith("/api/v1/files/download")){const i=aC(t);return!i||i.includes("..")||oC(i)?null:Ua(i)}if(t.startsWith("/api/"))return null;const r=Bi(t);return r?Ua(r):null}function iC(e){const t=[];for(const n of jo(e).slice(0,Wu)){const r=nf(n);r&&t.push({url:Ua(n),mimeType:r})}return t}function qu(e,t){const n=[],r=new Set;for(const i of[...e??[],...t]){const s=F$(i);if(!r.has(s)&&(r.add(s),n.push(i),n.length>=Wu))break}return n}function sC(e,t){const n=$$(t),r=O$(e),i=typeof(e==null?void 0:e.text)=="string"?e.text:"",s=rf(i),a=iC(s.paths);return r&&"data"in r&&r.data.length>0?{text:s.text,images:[r]}:{text:s.text,images:qu(n,[...r?[r]:[],...a])}}function $$(e){const t=e==null?void 0:e["codebuddy.ai/images"];if(!Array.isArray(t))return[];const n=[];for(const r of t){const i=typeof(r==null?void 0:r.blobPath)=="string"?Bi(r.blobPath,{requireImageExt:!ko(r==null?void 0:r.mimeType)}):null,s=typeof(r==null?void 0:r.mimeType)=="string"&&ko(r.mimeType)?r.mimeType:i?nf(i):void 0;!i||!s||n.push({url:Ua(i),mimeType:s})}return n}function O$(e){const t=U$(e);if(!t||t.type!=="image")return;const n=typeof t.mimeType=="string"?t.mimeType:typeof t.mediaType=="string"?t.mediaType:void 0;if(typeof t.data=="string"&&t.data.length>0&&ko(n))return{data:t.data,mimeType:n};const r=typeof t._meta=="object"&&t._meta&&typeof t._meta.blobPath=="string"?Bi(t._meta.blobPath,{requireImageExt:!ko(n)}):Bi(typeof t.uri=="string"?t.uri:""),i=ko(n)?n:r?nf(r):void 0;if(!(!r||!i))return{url:Ua(r),mimeType:i}}function P$(e){return"url"in e?e.url:`data:${e.mimeType};base64,${e.data}`}function B$(e){const t=/^data:([^;,]+)(;base64)?,/i.exec(e);return t?ko(t[1]):!1}function aC(e){try{const n=new URL(e,"http://web-ui.local").searchParams.get("path");return n?Bi(n,{requireImageExt:!1}):null}catch{return null}}function em(e){return e.startsWith("/")||tf.test(e)}function j$(e){const t=new Set,n=new RegExp(C$.source,"g");let r;for(;(r=n.exec(e))!==null;){const i=Bi(r[1]??"");i&&t.add(Vu(i))}return t}function Vu(e){const t=e.replace(/\\/g,"/");return tf.test(t)?`${t[0].toLowerCase()}${t.slice(1)}`:t}function oC(e){const t=e.replace(/\\/g,"/");return/^[A-Za-z]:\/windows(\/|$)/i.test(t)||/^[A-Za-z]:\/\$recycle\.bin(\/|$)/i.test(t)?!0:k$.some(n=>t===n.slice(0,-1)||t.startsWith(n))}function lC(e){const t=e.split(/[\\/]/).pop()??"",n=t.lastIndexOf(".");return n>=0?t.slice(n).toLowerCase():""}function jo(e){const t=new Set,n=[];for(const r of e){const i=Bi(r)??r,s=Vu(i);t.has(s)||(t.add(s),n.push(i))}return n}function F$(e){if("data"in e)return`data:${e.mimeType}:${e.data.slice(0,48)}`;const t=aC(e.url);return t?`path:${Vu(t)}`:`url:${e.url}`}function U$(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}let Wi=0;function cC(e,t,n){return t??(e==null?void 0:e.createdAt)??n??Date.now()}function dC(e,t){switch(t.kind){case"set":case"active":return t.condition?{condition:t.condition,createdAt:cC(e,t.createdAt,t.timestamp)}:e;case"cleared":case"no-goal":return null;default:return e}}function uC(e){for(let t=e.length-1;t>=0;t--){const n=e[t];if(n.type==="message"&&n.role==="assistant"&&n.streaming)return t}return-1}function uS(e,t){if(!t)return uC(e);for(let n=e.length-1;n>=0;n--){const r=e[n];if(r.type==="message"&&r.role==="assistant"&&r.streaming&&r.messageId===t)return n}return-1}function Qu(e){return!e||!e.trim()}function hC(e){for(let t=e.length-1;t>=0;t--){const n=e[t];if(n.type==="message"&&n.role==="assistant"&&n.streaming&&Qu(n.content)&&n.thinking)return t}return-1}function z$(e){for(let t=e.length-1;t>=0;t--){const n=e[t];if(n.type==="message"&&n.role==="assistant"&&n.streaming&&n.thinking)return t}return-1}function H$(e){const t=hC(e);return t!==-1?t:z$(e)}function sf(e,t){return t?!e||t.startsWith(e)?t:e.startsWith(t)?e:e+t:e}function pC(e,t){var n;if(!(!e||e.role!=="assistant"||t.role!=="assistant")&&!(!t.thinking||!Qu(t.content)||(n=t.images)!=null&&n.length))return{...e,thinking:sf(e.thinking||"",t.thinking),thinkingStartTime:e.thinkingStartTime||t.thinkingStartTime,thinkingDuration:e.thinkingDuration??t.thinkingDuration,streaming:!!(e.streaming||t.streaming)}}function Fi(e){const t=uC(e);if(t===-1)return e;const n=[...e],r=n[t],i={streaming:!1};return r.thinking&&r.thinkingStartTime&&!r.thinkingDuration&&(i.thinkingDuration=Math.round((Date.now()-r.thinkingStartTime)/1e3)),n[t]={...r,...i},n}function hS(e,t,n){if(!n)return null;const r=e.timeline.findIndex(o=>o.type==="tool_call"&&o.id===n);if(r!==-1){const o=e.timeline[r],c=[...o.subagentTimeline||[]],d=c[c.length-1];d&&d.type==="message"&&d.streaming?c[c.length-1]={...d,content:d.content+t}:c.push({type:"message",id:`sub-msg-${++Wi}`,content:t,streaming:!0});const u=[...e.timeline];return u[r]={...o,subagentTimeline:c},{timeline:u}}const i=new Map(e.pendingSubagentChunks),s=i.get(n)||[],a=s[s.length-1];return a&&a.type==="message"?s[s.length-1]={...a,content:a.content+t}:s.push({type:"message",content:t}),i.set(n,s),{pendingSubagentChunks:i}}const ot=Rt((e,t)=>({timeline:[],childToolCalls:new Map,pendingSubagentChunks:new Map,isAgentRunning:!1,agentRunSuppressed:!1,stopReason:null,errorMessage:null,errorCategory:null,finishReason:null,agentPhaseLabel:null,progressLabel:null,historyLoading:!1,hasPendingInterruption:!1,compactCancelled:!1,goalRecap:null,activeGoal:null,pausedGoal:null,addUserMessage:(n,r,i)=>{e(s=>({timeline:[...Fi(s.timeline),{type:"message",id:`msg-${++Wi}`,role:"user",content:n,...r&&r.length>0?{images:r}:{},...i&&i.length>0?{files:i}:{},timestamp:Date.now()}],isAgentRunning:!0,agentRunSuppressed:!1,stopReason:null,errorMessage:null,errorCategory:null,finishReason:null}))},addQueuedUserMessage:(n,r,i)=>{e(s=>({timeline:[...s.timeline,{type:"message",id:`msg-${++Wi}`,role:"user",content:n,...r&&r.length>0?{images:r}:{},...i&&i.length>0?{files:i}:{},timestamp:Date.now()}]}))},addChunk:(n,r,i,s)=>{e(a=>{const o=hS(a,n,r);if(o)return o;const c=[...a.timeline],d=uS(c,s),u=d!==-1||!s?d:hC(c);if(u!==-1){const h=c[u],p={content:h.content+n,...s&&s!==h.messageId?{messageId:s}:{}};i&&!h.isCompactInternal&&(p.isCompactInternal=!0),h.thinking&&h.thinkingStartTime&&!h.thinkingDuration&&Qu(h.content)&&n.trim()&&(p.thinkingDuration=Math.round((Date.now()-h.thinkingStartTime)/1e3)),c[u]={...h,...p}}else c.push({type:"message",id:`msg-${++Wi}`,role:"assistant",content:n,...s?{messageId:s}:{},timestamp:Date.now(),streaming:!0,...i?{isCompactInternal:i}:{}});return{timeline:c}})},addThinkingChunk:(n,r,i)=>{e(s=>{const a=hS(s,n,r);if(a)return a;const o=[...s.timeline],c=uS(o,i),d=c!==-1||!i?c:H$(o);if(d!==-1){const u=o[d];o[d]={...u,...i&&i!==u.messageId?{messageId:i}:{},thinking:sf(u.thinking||"",n),thinkingStartTime:u.thinkingStartTime||Date.now()}}else o.push({type:"message",id:`msg-${++Wi}`,role:"assistant",content:"",...i?{messageId:i}:{},thinking:n,thinkingStartTime:Date.now(),timestamp:Date.now(),streaming:!0});return{timeline:o}})},finalizeAssistantMessage:()=>{e(n=>({timeline:Fi(n.timeline)}))},addSubagentUserMessage:(n,r,i)=>{e(s=>{const a=s.timeline.findIndex(d=>d.type==="tool_call"&&d.id===n);if(a!==-1){const d=s.timeline[a],u=[...d.subagentTimeline||[]];u.push({type:"user_message",id:`sub-msg-${++Wi}`,content:r,...i&&i.length>0?{images:i}:{}});const h=[...s.timeline];return h[a]={...d,subagentTimeline:u},{timeline:h}}const o=new Map(s.pendingSubagentChunks),c=o.get(n)||[];return c.push({type:"user_message",content:r,...i&&i.length>0?{images:i}:{}}),o.set(n,c),{pendingSubagentChunks:o}})},addToolCall:n=>{e(r=>{const i=Fi(r.timeline);if(n.parentToolCallId){const o=new Map(r.childToolCalls);return o.set(n.id,{...n,type:"tool_call"}),{timeline:i.map(c=>{if(c.type==="tool_call"&&c.id===n.parentToolCallId){const d=(c.subagentTimeline||[]).map(u=>u.type==="message"&&u.streaming?{...u,streaming:!1}:u);return{...c,children:[...c.children||[],n.id],subagentTimeline:[...d,{type:"tool_call_ref",toolCallId:n.id}]}}return c}),childToolCalls:o}}const s={...n,type:"tool_call"},a=r.pendingSubagentChunks.get(n.id);if(a&&a.length>0){const o=a.map(d=>d.type==="user_message"?{type:"user_message",id:`sub-msg-${++Wi}`,content:d.content,images:d.images}:{type:"message",id:`sub-msg-${++Wi}`,content:d.content,streaming:!1});s.subagentTimeline=o;const c=new Map(r.pendingSubagentChunks);return c.delete(n.id),{timeline:[...i,s],pendingSubagentChunks:c}}return{timeline:[...i,s]}})},updateToolCall:(n,r)=>{e(i=>{const s=d=>!d||!Array.isArray(d)?!1:d.some(u=>u.type==="diff"),a=d=>{let u=r;if(s(d.content)&&r.content!==void 0&&!s(r.content)){const{content:p,...m}=r;u=m}const h={...d,...u,type:"tool_call"};return r.metaData&&d.metaData&&(h.metaData={...d.metaData,...r.metaData}),h};if(i.timeline.some(d=>d.type==="tool_call"&&d.id===n))return{timeline:i.timeline.map(d=>d.type==="tool_call"&&d.id===n?a(d):d)};const c=i.childToolCalls.get(n);if(c){const d=new Map(i.childToolCalls);return d.set(n,a(c)),{childToolCalls:d}}return{}})},getChildToolCall:n=>t().childToolCalls.get(n),getToolCall:n=>{const r=t();return r.timeline.find(s=>s.type==="tool_call"&&s.id===n)??r.childToolCalls.get(n)},addQuestion:n=>{e(r=>r.timeline.some(s=>s.type==="question"&&s.toolCallId===n.toolCallId&&s.status==="pending")?r:{timeline:[...Fi(r.timeline),{...n,type:"question",status:"pending"}],hasPendingInterruption:!0})},submitQuestion:(n,r)=>{e(i=>{const s=i.timeline.map(o=>o.type==="question"&&o.id===n?{...o,status:"answered",answers:r}:o),a=s.some(o=>o.type==="interruption"&&!o.resolved||o.type==="question"&&o.status==="pending");return{timeline:s,hasPendingInterruption:a}})},cancelQuestion:n=>{e(r=>{const i=r.timeline.map(a=>a.type==="question"&&a.id===n?{...a,status:"cancelled"}:a),s=i.some(a=>a.type==="interruption"&&!a.resolved||a.type==="question"&&a.status==="pending");return{timeline:i,hasPendingInterruption:s}})},resolveQuestionByToolCallId:n=>{e(r=>{const i=r.timeline.map(a=>a.type==="question"&&a.toolCallId===n&&a.status==="pending"&&a.source==="interruption"?{...a,status:"cancelled"}:a),s=i.some(a=>a.type==="interruption"&&!a.resolved||a.type==="question"&&a.status==="pending");return{timeline:i,hasPendingInterruption:s}})},addInterruption:n=>{e(r=>n.toolCallId&&r.timeline.some(s=>s.type==="interruption"&&s.toolCallId===n.toolCallId&&!s.resolved)?r:{timeline:[...Fi(r.timeline),{...n,type:"interruption"}],hasPendingInterruption:!0})},resolveInterruption:(n,r)=>{e(i=>{const s=i.timeline.map(o=>o.type==="interruption"&&o.id===n?{...o,resolved:!0,decision:r}:o),a=s.some(o=>o.type==="interruption"&&!o.resolved||o.type==="question"&&o.status==="pending");return{timeline:s,hasPendingInterruption:a}})},resolveInterruptionByToolCallId:(n,r)=>{e(i=>{const s=i.timeline.map(o=>o.type==="interruption"&&o.toolCallId===n&&!o.resolved?{...o,resolved:!0,decision:r}:o),a=s.some(o=>o.type==="interruption"&&!o.resolved||o.type==="question"&&o.status==="pending");return{timeline:s,hasPendingInterruption:a}})},setHistoryLoading:n=>e({historyLoading:n}),addHistoryUserMessage:(n,r,i,s,a)=>{e(o=>({timeline:[...Fi(o.timeline),{type:"message",id:`msg-${++Wi}`,role:"user",content:n,...r&&r.length>0?{images:r}:{},timestamp:Date.now(),...i?{isCompactInternal:i}:{},...s?{channel:s}:{},...a?{commandKind:a}:{}}]}))},addHistoryUserMessageChunk:(n,r,i,s,a,o)=>{!r&&!(i&&i.length>0)||e(c=>{const d=Fi(c.timeline),u=d[d.length-1];if(u&&u.type==="message"&&u.role==="user"&&n&&u.messageId===n){const h=qu(u.images,i||[]);return d[d.length-1]={...u,content:u.content+r,...h.length>0?{images:h}:{},...s?{isCompactInternal:!0}:{},...a?{channel:a}:{},...o?{commandKind:o}:{}},{timeline:d}}return{timeline:[...d,{type:"message",id:`msg-${++Wi}`,...n?{messageId:n}:{},role:"user",content:r,...i&&i.length>0?{images:i}:{},timestamp:Date.now(),...s?{isCompactInternal:s}:{},...a?{channel:a}:{},...o?{commandKind:o}:{}}]}})},setAgentRunning:n=>e({isAgentRunning:n,...n?{agentRunSuppressed:!1}:{agentPhaseLabel:null,progressLabel:null}}),noteAgentActivity:()=>e(n=>n.agentRunSuppressed?n:{isAgentRunning:!0}),suppressAgentRun:()=>e({isAgentRunning:!1,agentRunSuppressed:!0,agentPhaseLabel:null,progressLabel:null}),setAgentPhaseLabel:n=>e({agentPhaseLabel:n}),setProgressLabel:n=>e({progressLabel:n}),setSessionEnd:(n,r,i,s)=>{t().finalizeAssistantMessage();const a=n==="end_turn";e(o=>{const c=o.timeline.map(u=>u.type==="tool_call"&&u.status==="running"?{...u,status:"completed"}:u.type==="interruption"&&!u.resolved?u.mcpUiIntercept===!0||typeof u.toolCallId=="string"&&u.toolCallId.startsWith("mcpui-")||u.toolName==="ExitPlanMode"?u:{...u,resolved:!0,decision:"deny"}:u.type==="question"&&u.status==="pending"?{...u,status:"cancelled"}:u),d=new Map(o.childToolCalls);for(const[u,h]of d)h.status==="running"&&d.set(u,{...h,status:"completed"});return{isAgentRunning:!1,agentRunSuppressed:n==="cancelled",hasPendingInterruption:c.some(u=>u.type==="interruption"&&!u.resolved),agentPhaseLabel:null,progressLabel:null,stopReason:a?null:n,errorMessage:a?null:r||o.errorMessage||null,errorCategory:a?null:i||o.errorCategory||null,finishReason:a?null:s||o.finishReason||null,timeline:c,childToolCalls:d}})},setCompactCancelled:n=>e({compactCancelled:n}),addGoalProgress:n=>{e(r=>{if(r.timeline.some(a=>a.type==="goal-progress"&&a.id===n.id))return r;const i=Fi(r.timeline),s={type:"goal-progress",id:n.id,condition:n.condition,reason:n.reason,turnCount:n.turnCount,createdAt:n.createdAt,timestamp:n.timestamp??Date.now()};return{timeline:[...i,s],activeGoal:{condition:s.condition,createdAt:cC(r.activeGoal,s.createdAt,s.timestamp)}}})},showGoalRecap:n=>e(r=>{var i;return{goalRecap:n,activeGoal:n.active?{condition:n.active.condition,createdAt:((i=r.activeGoal)==null?void 0:i.condition)===n.active.condition?r.activeGoal.createdAt:Date.now()}:null}}),dismissGoalRecap:()=>e({goalRecap:null}),addGoalStatus:n=>{e(r=>{if(r.timeline.some(a=>a.type==="goal-status"&&a.id===n.id))return r;const i=Fi(r.timeline),s={type:"goal-status",id:n.id,kind:n.kind,condition:n.condition,prev:n.prev,actual:n.actual,max:n.max,createdAt:n.createdAt,timestamp:n.timestamp??Date.now()};return{timeline:[...i,s],activeGoal:dC(r.activeGoal,s),...s.kind==="set"||s.kind==="set-replaced"||s.kind==="active"?{pausedGoal:null}:{},...s.kind==="set"||s.kind==="set-replaced"?{isAgentRunning:!0,agentRunSuppressed:!1}:{}}})},addGoalResult:n=>{e(r=>{if(r.timeline.some(a=>a.type==="goal-result"&&a.id===n.id))return{...r,activeGoal:null,pausedGoal:null};const i=Fi(r.timeline),s={type:"goal-result",id:n.id,ok:n.ok,reason:n.reason,condition:n.condition,durationMs:n.durationMs,turnCount:n.turnCount,tokenDelta:n.tokenDelta,timestamp:n.timestamp??Date.now()};return{timeline:[...i,s],activeGoal:null,pausedGoal:null}})},hydrateActiveGoal:n=>e({activeGoal:n&&n.condition?{condition:n.condition,createdAt:n.createdAt}:null}),pauseActiveGoal:n=>e(r=>{var a;const i=r.pausedGoal??r.activeGoal;if(!i)return r;const s=typeof n=="number"?n:i.pausedAt??Date.now();return((a=r.pausedGoal)==null?void 0:a.condition)===i.condition&&r.pausedGoal.pausedAt===s?r:{pausedGoal:{...i,pausedAt:s}}}),dismissPausedGoal:()=>e({pausedGoal:null}),applyReconnectSnapshot:n=>e(r=>({...typeof n.busy=="boolean"?n.busy?r.agentRunSuppressed?{}:{isAgentRunning:!0}:{isAgentRunning:!1,agentPhaseLabel:null,progressLabel:null}:{},..."activeGoal"in n?(()=>{const i=n.activeGoal&&n.activeGoal.condition?{condition:n.activeGoal.condition,createdAt:n.activeGoal.createdAt,...typeof n.activeGoal.pausedAt=="number"?{pausedAt:n.activeGoal.pausedAt}:{}}:null;return{activeGoal:i,pausedGoal:i&&i.pausedAt!=null?i:null}})():{}})),clearMessages:()=>e({timeline:[],childToolCalls:new Map,pendingSubagentChunks:new Map,stopReason:null,errorMessage:null,errorCategory:null,finishReason:null,agentPhaseLabel:null,progressLabel:null,historyLoading:!1,hasPendingInterruption:!1,compactCancelled:!1,goalRecap:null}),clearChat:()=>{t().clearMessages()},resetForSessionChange:()=>{t().clearMessages(),e({isAgentRunning:!1,agentRunSuppressed:!1,agentPhaseLabel:null,progressLabel:null,activeGoal:null,pausedGoal:null})}})),G$=Object.freeze(Object.defineProperty({__proto__:null,activeGoalAfterStatus:dC,isBlankAssistantText:Qu,mergeThinkingChunk:sf,tryFoldThoughtOnlyAssistant:pC,useChatStore:ot},Symbol.toStringTag,{value:"Module"}));async function Ku(e){return Kt(e,{headers:Fe()})}async function Yu(e,t){return Kt(e,{method:"POST",headers:{"Content-Type":"application/json",...Fe()},body:t!=null?JSON.stringify(t):void 0})}async function mC(e,t){return Kt(e,{method:"PUT",headers:{"Content-Type":"application/json",...Fe()},body:t!=null?JSON.stringify(t):void 0})}async function W$(e){return Kt(e,{method:"DELETE",headers:Fe()})}async function tm(e){const t=await Ku(e);if(!t.ok)throw new Error(`HTTP ${t.status}`);const n=await t.json();return n.data??n}async function q$(e){return tm(`/api/v1/goal?sessionId=${encodeURIComponent(e)}`)}async function V$(e){const t=await Yu("/api/v1/goal/clear",{sessionId:e});if(!t.ok)throw new Error(`HTTP ${t.status}`);const n=await t.json();return n.data??n}async function Q$(e){const t=await Yu("/api/v1/goal/pause",{sessionId:e});if(!t.ok)throw new Error(`HTTP ${t.status}`);const n=await t.json();return n.data??n}async function K$(e){const t=await Yu("/api/v1/goal/resume",{sessionId:e});if(!t.ok)throw new Error(`HTTP ${t.status}`);const n=await t.json();return n.data??n}function Y$(e){const t=e.active;return t!=null&&t.condition?{condition:t.condition,createdAt:t.createdAt,...typeof t.pausedAt=="number"?{pausedAt:t.pausedAt}:{}}:null}function gC(e){var r;const t=Y$(e);if(!t)return;const n=ot.getState();if(n.hydrateActiveGoal(t),(r=e.active)!=null&&r.paused){n.pauseActiveGoal(typeof e.active.pausedAt=="number"?e.active.pausedAt:void 0);return}n.dismissPausedGoal()}const $i=Rt(e=>({terminals:{},terminalIdByToolCall:{},applyTerminalUpdate:(t,n)=>{const{terminalId:r}=t;r&&e(i=>{const s=i.terminals[r],a=s?{...s,seen:!0}:{terminalId:r,seen:!0};return a.startedAt===void 0&&n!==void 0&&(a.startedAt=n),t.command!==void 0&&(a.command=t.command??void 0),t.cwd!==void 0&&(a.cwd=t.cwd??void 0),t.exitStatus!==void 0&&(a.exitStatus=t.exitStatus??void 0),{terminals:{...i.terminals,[r]:a}}})},linkToolCall:(t,n)=>{!t||!n||e(r=>{if(r.terminalIdByToolCall[t]===n)return r;const i=r.terminals[n];return{terminalIdByToolCall:{...r.terminalIdByToolCall,[t]:n},terminals:{...r.terminals,[n]:i?{...i,toolCallId:t}:{terminalId:n,toolCallId:t,seen:!1}}}})},reset:()=>e({terminals:{},terminalIdByToolCall:{}})}));function Zu(e){return!!e&&e.seen&&e.exitStatus===void 0}function Z$(e,t){return e==="connected"&&typeof t=="string"&&t.length>0}const Ge=Rt((e,t)=>({status:"disconnected",sessionId:null,sessionSwitching:!1,models:[],currentModel:"",modes:[],currentMode:"default",commands:[],error:null,topic:null,thinkingEnabled:!1,thoughtLevel:null,promptSuggestion:null,externalInput:null,setStatus:n=>e({status:n}),setSessionId:n=>e({sessionId:n}),setSessionSwitching:n=>e({sessionSwitching:n}),setModels:n=>e({models:n}),setCurrentModel:n=>e({currentModel:n}),setModes:n=>e({modes:n}),setCurrentMode:n=>e({currentMode:n}),setCommands:n=>e({commands:n}),setTopic:n=>e({topic:n}),setThinkingEnabled:n=>e({thinkingEnabled:n}),setThoughtLevel:n=>e({thoughtLevel:n}),setPromptSuggestion:n=>e({promptSuggestion:n}),setExternalInput:n=>e({externalInput:n}),connect:async n=>{const r=st();try{if(e({status:"connecting",error:null}),n){const{AcpClient:i}=await Ct(async()=>{const{AcpClient:o}=await Promise.resolve().then(()=>hL);return{AcpClient:o}},void 0),s=new i(void 0,n);s.on("status_change",o=>e({status:o})),s.on("model_update",o=>{e({models:o.availableModels||[],currentModel:o.currentModelId||""})});const{sessionId:a}=await s.initializeSession({continue:!0});e({status:"connected",sessionId:a})}else{const{sessionId:i}=await r.initializeSession({continue:!0});e({status:"connected",sessionId:i})}}catch(i){e({status:"error",error:i.message})}},disconnect:async()=>{await st().disconnect(),e({status:"disconnected",sessionId:null,sessionSwitching:!1})}})),bs=Rt((e,t)=>({usage:null,setUsage:n=>{var i,s,a,o;const r=t().usage;if(n.sessionId&&(r!=null&&r.sessionId)&&n.sessionId!==r.sessionId){e({usage:{sessionId:n.sessionId,used:n.used,size:n.size,cost:n.cost,usageByCategory:n.usageByCategory,updatedAt:Date.now()}});return}r&&r.used>0&&n.used===0||r&&r.used===n.used&&r.size===n.size&&((i=r.cost)==null?void 0:i.amount)===((s=n.cost)==null?void 0:s.amount)&&((a=r.cost)==null?void 0:a.currency)===((o=n.cost)==null?void 0:o.currency)&&!n.usageByCategory||e({usage:{sessionId:n.sessionId??(r==null?void 0:r.sessionId),used:n.used,size:n.size,cost:n.cost,usageByCategory:n.usageByCategory??(r==null?void 0:r.usageByCategory),updatedAt:Date.now()}})},reset:()=>e({usage:null})})),ui=Rt((e,t)=>({fileChanges:[],selectedFile:null,selectedDiff:null,diffLoading:!1,isCollapsed:!0,checkpoints:[],showCheckpoints:!1,reverting:!1,recentlyReverted:new Set,onCheckpoint:n=>{const{recentlyReverted:r}=t(),i=r.size>0?n.fileChanges.files.filter(a=>!r.has(a.uri)):n.fileChanges.files,s=new Set(i.map(a=>a.uri));e(a=>({fileChanges:i,selectedFile:a.selectedFile&&!s.has(a.selectedFile)?null:a.selectedFile,selectedDiff:a.selectedFile&&!s.has(a.selectedFile)?null:a.selectedDiff}))},selectFile:async n=>{const{selectedFile:r}=t();if(r===n){e({selectedFile:null,selectedDiff:null});return}e({selectedFile:n,selectedDiff:null,diffLoading:!0});try{const i=await Kt("/internal/file-changes/diff",{method:"POST",headers:{...Fe(),"Content-Type":"application/json"},body:JSON.stringify({path:n})});if(i.ok){const s=await i.json();e({selectedDiff:s.data??s,diffLoading:!1})}else e({diffLoading:!1})}catch{e({diffLoading:!1})}},setCollapsed:n=>e({isCollapsed:n}),setShowCheckpoints:n=>e({showCheckpoints:n}),loadCheckpoints:async()=>{try{const n=await Kt("/internal/file-changes/checkpoints",{method:"POST",headers:{...Fe(),"Content-Type":"application/json"},body:JSON.stringify({})});if(n.ok){const r=await n.json(),s=((r.data??r).checkpoints||[]).sort((a,o)=>o.createdAt-a.createdAt);e({checkpoints:s})}}catch{}},revertFiles:async n=>{e({reverting:!0});try{const r=await Kt("/internal/file-changes/revert",{method:"POST",headers:{...Fe(),"Content-Type":"application/json"},body:JSON.stringify({paths:n})});if(r.ok){const i=await r.json(),a=(i.data??i).revertedFiles||[],o=new Set(a);e(c=>({fileChanges:c.fileChanges.filter(d=>!o.has(d.uri)),selectedFile:o.has(c.selectedFile||"")?null:c.selectedFile,selectedDiff:o.has(c.selectedFile||"")?null:c.selectedDiff,recentlyReverted:new Set([...c.recentlyReverted,...a])})),setTimeout(()=>{e(c=>{const d=new Set(c.recentlyReverted);for(const u of a)d.delete(u);return{recentlyReverted:d}})},5e3)}}finally{e({reverting:!1})}},revertAll:async()=>{e({reverting:!0});try{const n=t().fileChanges.map(i=>i.uri);(await Kt("/internal/file-changes/revert",{method:"POST",headers:{...Fe(),"Content-Type":"application/json"},body:JSON.stringify({})})).ok&&(e(i=>({fileChanges:[],selectedFile:null,selectedDiff:null,recentlyReverted:new Set([...i.recentlyReverted,...n])})),setTimeout(()=>{e(i=>{const s=new Set(i.recentlyReverted);for(const a of n)s.delete(a);return{recentlyReverted:s}})},5e3))}finally{e({reverting:!1})}},revertToCheckpoint:async(n,r="CodeAndConversation")=>{e({reverting:!0});try{if((await Kt("/internal/file-changes/revert",{method:"POST",headers:{...Fe(),"Content-Type":"application/json"},body:JSON.stringify({checkpointId:n,scope:r})})).ok){if((r==="Code"||r==="CodeAndConversation")&&e({fileChanges:[],selectedFile:null,selectedDiff:null}),r==="Conversation"||r==="CodeAndConversation")try{const{useChatStore:s}=await Ct(async()=>{const{useChatStore:c}=await Promise.resolve().then(()=>G$);return{useChatStore:c}},void 0);s.getState().clearChat();const a=st(),o=sessionStorage.getItem("acp-session-id");a&&o&&await a.loadSession(o)}catch(s){console.error("Failed to reload session after revert:",s)}t().loadCheckpoints()}}finally{e({reverting:!1})}},reset:()=>e({fileChanges:[],selectedFile:null,selectedDiff:null,diffLoading:!1,isCollapsed:!0,checkpoints:[],showCheckpoints:!1,reverting:!1,recentlyReverted:new Set})}));let af=Promise.resolve(),Ks;const J$=8e3;function fC(){Ks==null||Ks(),af=new Promise(e=>{Ks=e})}function Ao(){Ks==null||Ks(),Ks=void 0,af=Promise.resolve()}async function X$(e=J$){let t;const n=await Promise.race([af.then(()=>!1),new Promise(r=>{t=setTimeout(()=>r(!0),e)})]);return t!==void 0&&clearTimeout(t),n?(Ao(),"timeout"):"ready"}const Aa="codebuddy.mainAgent.staged",bC=[{name:"cli",displayName:"cli",source:"built-in",custom:!1},{name:"ptc",displayName:"ptc",source:"built-in",custom:!1},{name:"minimal",displayName:"minimal",source:"built-in",custom:!1},{name:"create",displayName:"create",source:"built-in",custom:!1}];function e5(){try{return typeof localStorage>"u"?null:localStorage.getItem(Aa)}catch{return null}}const pS={agents:bC,currentAgentName:"",defaultAgentName:"",sessionBlank:!0,models:[],currentModelId:"",status:"idle",error:null,stagedAgent:e5(),backendSupport:void 0,processAgent:null,processPermissionMode:null},nt=Rt()(e=>({...pS,applyAgentFromResponse:t=>e(n=>({agents:t.agents??n.agents,currentAgentName:t.currentAgentName??n.currentAgentName,defaultAgentName:t.defaultAgentName??n.defaultAgentName,sessionBlank:t.sessionBlank??n.sessionBlank,status:"ready",error:null})),applySetAgentResult:t=>(Ao(),e(()=>({currentAgentName:t.agentName,models:t.models,currentModelId:t.currentModelId,sessionBlank:t.sessionBlank,status:"ready",error:null}))),applyAgentConfigEntry:t=>e(()=>{const n={};return t.currentValue&&(n.currentAgentName=t.currentValue),n}),applyBackendSupport:t=>e(()=>({backendSupport:t})),applyProcessDefaults:t=>e(n=>{const r=typeof t.agent=="string"?t.agent.trim():void 0,i=typeof t.permissionMode=="string"?t.permissionMode.trim():void 0;return{processAgent:r===void 0?n.processAgent:r||null,processPermissionMode:i===void 0?n.processPermissionMode:i||null}}),setSessionBlank:t=>e(()=>({sessionBlank:t})),setStagedAgent:t=>{typeof localStorage<"u"&&localStorage.setItem(Aa,t),e(()=>({stagedAgent:t}))},hydrateStagedAgent:t=>{t&&(typeof localStorage<"u"&&localStorage.setItem(Aa,t),e(n=>({stagedAgent:t,currentAgentName:n.currentAgentName||t})))},clearStagedAgent:()=>{typeof localStorage<"u"&&localStorage.removeItem(Aa),e(()=>({stagedAgent:null}))},setLoading:()=>e(()=>({status:"loading",error:null})),setError:t=>(Ao(),e(()=>({status:"error",error:t}))),reset:t=>{Ao(),!(t!=null&&t.keepLastUsed)&&typeof localStorage<"u"&&localStorage.removeItem(Aa);const n=(t==null?void 0:t.keepProcessDefaults)??(t==null?void 0:t.keepLastUsed);e(r=>({...pS,agents:[...bC],stagedAgent:t!=null&&t.keepLastUsed?r.stagedAgent:null,backendSupport:n?r.backendSupport:void 0,processAgent:n?r.processAgent:null,processPermissionMode:n?r.processPermissionMode:null}))}}));let Ja=new Map;const qi=Rt((e,t)=>({visible:!1,total:0,completed:0,connectingServers:[],finished:!1,startedAt:void 0,failed:[],timedOut:[],applyEvent:n=>{if(n.event==="start"){Ja=new Map;const r=n.servers??[];for(const i of r)Ja.set(i,"connecting");e({total:n.total_count??r.length,completed:0,connectingServers:[...r].sort(),finished:!1,failed:[],timedOut:[],visible:r.length>0,startedAt:r.length>0?Date.now():void 0});return}if(n.event==="server"){if(t().finished)return;n.name&&n.state&&Ja.set(n.name,n.state);const r=[];let i=0;for(const[s,a]of Ja)a==="connecting"?r.push(s):i+=1;e({connectingServers:r.sort(),completed:i});return}Ja=new Map,e({finished:!0,visible:!0,connectingServers:[],completed:t().total,failed:[...n.failed??[]],timedOut:[...n.timed_out??[]]})},hide:()=>{e({visible:!1})},reset:()=>{Ja=new Map,e({visible:!1,total:0,completed:0,connectingServers:[],finished:!1,startedAt:void 0,failed:[],timedOut:[]})}})),Ir=Rt(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,n)=>e(r=>({memberHistories:{...r.memberHistories,[t]:n}})),clearTeam:()=>e({isInTeam:!1,teamName:null,isAutoTeam:!1,members:[],focusedMemberName:null,memberHistories:{}})})),yC=Rt(e=>({userInfo:null,loading:!1,error:null,fetchUserInfo:async t=>{e({loading:!0,error:null});try{const n=await t.getUserInfo();n.userInfo?e({userInfo:n.userInfo,loading:!1}):e({loading:!1})}catch(n){console.warn("[user] Failed to fetch user info:",n),e({error:n.message,loading:!1})}},clearUserInfo:()=>{e({userInfo:null,error:null})}}));function t5(e,t){return e&&typeof e=="object"&&!Array.isArray(e)?{...e,defaultMode:t}:{defaultMode:t}}function _C(e){const t=e&&typeof e=="object"&&"data"in e?e.data:e;return t&&typeof t=="object"&&"value"in t?t.value:t}function n5(e,t){const n=e&&typeof e=="object"&&!Array.isArray(e)?{...e}:{},r=n.mainAgent&&typeof n.mainAgent=="object"&&!Array.isArray(n.mainAgent)?{...n.mainAgent}:{};return{...n,mainAgent:{...r,lastUsed:t}}}async function r5(e){const t=await Ku("/api/v1/settings/codebuddy?scope=user");if(!t.ok)throw new Error(`HTTP ${t.status}`);const n=n5(_C(await t.json()),e),r=await mC("/api/v1/settings/codebuddy?scope=user",{value:n});if(!r.ok&&r.status!==204)throw new Error(`HTTP ${r.status}`)}async function i5(e){const t=await Ku("/api/v1/settings/permissions?scope=user");if(!t.ok)throw new Error(`HTTP ${t.status}`);const n=t5(_C(await t.json()),e),r=await mC("/api/v1/settings/permissions?scope=user",{value:n});if(!r.ok&&r.status!==204)throw new Error(`HTTP ${r.status}`)}const vC="codebuddy.permissionMode.staged",s5=new Set(["default","acceptEdits","plan","auto","dontAsk","bypassPermissions","fullAccess","work","delegate"]),a5=new Set(["default","acceptEdits","plan","auto","dontAsk","bypassPermissions"]);function qa(e){return s5.has(e)}function o5(e){return e==="fullAccess"?"bypassPermissions":a5.has(e)?e:""}function xC(){try{if(typeof localStorage>"u")return null;const e=localStorage.getItem(vC);return e&&qa(e)?e:null}catch{return null}}function of(e){if(qa(e))try{if(typeof localStorage>"u")return;localStorage.setItem(vC,e)}catch{}}function lf(e){qa(e)&&(of(e),i5(e).catch(t=>{console.warn("[composer-prefs] persist permissions.defaultMode failed:",t)}))}function l5(e){const t=typeof e.currentMode=="string"?e.currentMode.trim():"";if(!t||!qa(t))return!1;const n=typeof e.processPermissionMode=="string"?e.processPermissionMode.trim():"";return!n||t!==n}function c5(e){const t=e.stored||e.currentMode||"";return t&&qa(t)?t:null}function d5(e){return c5({stored:e.stored,currentMode:e.currentMode&&e.currentMode!=="default"?e.currentMode:void 0})??""}const u5=["cli","ptc","minimal","create"];function nm(e){return u5.includes(e)}function h5(e,t){return e||t}function p5(e,t){return t.length>0&&e===t}function m5(e){return{builtin:e.filter(t=>nm(t.name)),custom:e.filter(t=>!nm(t.name)&&(t.custom===!0||t.source!=="built-in"))}}function mS(e){return e.id==="agent"?(nt.getState().applyAgentConfigEntry(e),!0):!1}function g5(e){if(e.sessionBlank!==!0)return null;const t=e.stagedAgent??e.stored;return!t||!e.sessionId||e.currentAgentName&&e.defaultAgentName&&e.currentAgentName===e.defaultAgentName&&t!==e.defaultAgentName?null:{agentName:t,sessionId:e.sessionId}}function rm(e){e&&(nt.getState().setStagedAgent(e),r5(e).catch(t=>{console.warn("[main-agent] persist lastUsed failed:",t)}))}function f5(e){var s,a;const t=e&&typeof e=="object"?e:{},n=(s=t.codebuddy)==null?void 0:s.mainAgent,r=typeof(n==null?void 0:n.lastUsed)=="string"?n.lastUsed.trim():"",i=(a=t.permissions)==null?void 0:a.defaultMode;return{lastUsedAgent:r||null,lastPermissionMode:typeof i=="string"&&qa(i)?i:null}}async function b5(){try{const[e,t]=await Promise.all([tm("/api/v1/settings?scope=user"),tm("/api/v1/runtime-defaults").catch(()=>({}))]),n=t&&typeof t=="object"?t:{},r=typeof n.agent=="string"?n.agent.trim():"",i=typeof n.permissionMode=="string"?n.permissionMode.trim():"";(r||i)&&nt.getState().applyProcessDefaults({...r?{agent:r}:{},...i?{permissionMode:i}:{}}),i&&qa(i)&&Ge.getState().setCurrentMode(i);const s=f5(e);if(!nt.getState().processAgent&&s.lastUsedAgent&&nt.getState().hydrateStagedAgent(s.lastUsedAgent),!nt.getState().processPermissionMode&&s.lastPermissionMode){of(s.lastPermissionMode);const a=Ge.getState().currentMode;(!a||a==="default")&&Ge.getState().setCurrentMode(s.lastPermissionMode)}}catch{}}class gS{constructor(){we(this,"inFlight",null)}run(t){if(this.inFlight)return this.inFlight;const n=t();this.inFlight=n;const r=()=>{this.inFlight===n&&(this.inFlight=null)};return n.then(r,r),n}}class y5{constructor(){we(this,"generation",0);we(this,"pending")}begin(t,n){const r=n.trim();if(!t||!r)throw new Error("Session switch requires current and target session ids");if(this.pending)throw new Error(`Session switch already in progress: ${this.pending.targetSessionId}`);const i=Object.freeze({generation:++this.generation,previousSessionId:t,targetSessionId:r});return this.pending=i,i}expectedSessionId(t){var n;return((n=this.pending)==null?void 0:n.targetSessionId)??t}isCurrent(t){return this.pending===t}adoptRetargetedSession(t){const n=t.trim();if(!n)throw new Error("Retargeted session id is required");return this.generation++,this.pending=void 0,n}finish(t){this.pending===t&&(this.pending=void 0)}}function td(e){q$(e).then(t=>{Ge.getState().sessionId===e&&gC(t)}).catch(()=>{})}function fS(e){if(!e||typeof e!="object")return;const t=e;ot.getState().applyReconnectSnapshot({...typeof t.busy=="boolean"?{busy:t.busy}:{},..."activeGoal"in t?{activeGoal:t.activeGoal&&typeof t.activeGoal.condition=="string"&&t.activeGoal.condition&&typeof t.activeGoal.createdAt=="number"?{condition:t.activeGoal.condition,createdAt:t.activeGoal.createdAt,...typeof t.activeGoal.pausedAt=="number"?{pausedAt:t.activeGoal.pausedAt}:{}}:null}:{}})}function bS(e,t){const n=e.options||e.answers;let r=[];return Array.isArray(n)&&(r=n.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:r,multiSelect:!!e.multiSelect}}const _5={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},v5=new Set(["preparing","model_requesting","model_streaming","tool_executing","waiting_for_permission","waiting_for_user","retrying"]);function x5(e){return e.phase==="tool_executing"&&e.toolName?`phase.toolExecutingName:${e.toolName}`:e.phase==="model_streaming"&&e.streamingToolName?`phase.modelStreamingName:${e.streamingToolName}`:_5[e.phase]??null}const $h=100;let Ca=null;function st(){return Ca||(Ca=new rc),Ca}function w5(){const e=g.useRef(st()),t=g.useRef(new y5),n=g.useRef(null),r=g.useRef(new gS),i=g.useRef(new gS),s=g.useRef(null),a=g.useRef({fingerprint:"",at:0}),o=g.useRef({fingerprint:"",at:0}),c=g.useRef({fingerprint:"",at:0}),d=g.useRef(!1),[u,h]=g.useState(0),{setStatus:p,setSessionId:m,setSessionSwitching:f,setModels:b,setCurrentModel:_,setModes:v,setCurrentMode:A,setCommands:S,setTopic:y,setThinkingEnabled:x,setThoughtLevel:k,setPromptSuggestion:C}=Ge(),{addChunk:E,addThinkingChunk:N,addToolCall:z,updateToolCall:Q,addInterruption:T,addQuestion:w,setSessionEnd:L,resolveInterruptionByToolCallId:I,resolveQuestionByToolCallId:R,setHistoryLoading:$,addHistoryUserMessageChunk:D,addSubagentUserMessage:U,finalizeAssistantMessage:Y,clearChat:ee,resetForSessionChange:P,setAgentPhaseLabel:q,setProgressLabel:ue,setAgentRunning:_e,noteAgentActivity:ke,setCompactCancelled:H,addGoalProgress:G,showGoalRecap:V,addGoalStatus:oe,addGoalResult:J}=ot();g.useEffect(()=>{const ce=e.current;a.current={fingerprint:"",at:0},o.current={fingerprint:"",at:0},c.current={fingerprint:"",at:0};const ae=[],Ae=(F,ie)=>{if(!ie)return!1;try{const X=(ie._meta||{})["codebuddy.ai/memberEvent"];if(!X)return!1;const Ce=Ir.getState(),Ee=Ce.memberHistories[X]||[];return Ce.setMemberHistory(X,[...Ee,{sessionUpdate:F,...ie}]),!0}catch{return!1}},de=F=>{const ie=F==null?void 0:F.sessionId,fe=t.current.expectedSessionId(Ge.getState().sessionId);return typeof ie=="string"&&ie.length>0&&!!fe&&ie!==fe};return ae.push(ce.on("user_message_chunk",F=>{if(Ae("user_message_chunk",F)||de(F))return;const ie=F.content,fe=F._meta||{},X=!!fe["codebuddy.ai/isCompactInternal"],Ce=fe["codebuddy.ai/parentToolCallId"],Ee=typeof F.messageId=="string"?F.messageId:typeof fe["codebuddy.ai/messageId"]=="string"?fe["codebuddy.ai/messageId"]:void 0,Le=sC(ie,fe),We=Le.images.length>0?Le.images:void 0;let je;const et=fe["codebuddy.ai/channelSource"];et&&(je={source:et,sender:fe["codebuddy.ai/channelSender"]||"",senderName:fe["codebuddy.ai/channelSenderName"],chatId:fe["codebuddy.ai/channelChatId"],chatType:fe["codebuddy.ai/channelChatType"]});const ct=fe["codebuddy.ai/commandKind"]==="slash"?"slash":void 0;if(Le.text||We){if(!d.current){const gt=(We??[]).map(Nt=>"url"in Nt?Nt.url:"data").join(","),qe=`${F.sessionId??""}|${Ce??""}|${Le.text}|${gt}`,wt=Date.now();if(qe===c.current.fingerprint&&wt-c.current.at<$h)return;c.current={fingerprint:qe,at:wt}}Ce?U(Ce,Le.text,We):D(Ee,Le.text,We,X,je,ct)}})),ae.push(ce.on("agent_message_chunk",F=>{if(Ae("agent_message_chunk",F)||de(F))return;const ie=F.content,fe=F._meta||{},X=fe["codebuddy.ai/parentToolCallId"],Ce=!!fe["codebuddy.ai/isCompactInternal"],Ee=typeof F.messageId=="string"?F.messageId:typeof fe["codebuddy.ai/messageId"]=="string"?fe["codebuddy.ai/messageId"]:void 0,Le=eL(fe)?w1:typeof ie=="string"?ie:typeof(ie==null?void 0:ie.text)=="string"?ie.text:void 0;if(Le===void 0)return;const We=`${X??""}|${Le}`,je=Date.now();We===a.current.fingerprint&&je-a.current.at<$h||(a.current={fingerprint:We,at:je},d.current||ke(),!Ce&&!X&&nt.getState().setSessionBlank(!1),E(Le,X,Ce,Ee))})),ae.push(ce.on("agent_thought_chunk",F=>{if(Ae("agent_thought_chunk",F)||de(F))return;const ie=F.content,fe=F._meta||{},X=fe["codebuddy.ai/parentToolCallId"],Ce=typeof F.messageId=="string"?F.messageId:typeof fe["codebuddy.ai/messageId"]=="string"?fe["codebuddy.ai/messageId"]:void 0,Ee=typeof(ie==null?void 0:ie.text)=="string"?ie.text:void 0;if(Ee===void 0||!Ee.trim())return;const Le=`${X??""}|${Ee}`,We=Date.now();Le===o.current.fingerprint&&We-o.current.at<$h||(o.current={fingerprint:Le,at:We},d.current||ke(),N(Ee,X,Ce))})),ae.push(ce.on("tool_call",F=>{if(Ae("tool_call",F)||de(F))return;const ie=F._meta||{},fe=ie["codebuddy.ai/parentToolCallId"],X=!!ie["codebuddy.ai/isSubagent"],Ce=F.toolName||ie["codebuddy.ai/toolName"]||"",Ee=ie["codebuddy.ai/planContent"];d.current||ke();const Le={id:F.toolCallId,name:F.title||Ce||F.kind||"tool",kind:F.kind||"other",toolName:Ce,input:F.rawInput||F.input,status:"running",locations:F.locations,content:F.content,parentToolCallId:fe,subagent:X?{type:ie["codebuddy.ai/subagentType"]||"general-purpose",description:ie["codebuddy.ai/description"]||"",isBackground:!!ie["codebuddy.ai/isBackground"],memberName:ie["codebuddy.ai/memberName"]||void 0}:void 0,planContent:Ee};if(ot.getState().getToolCall(F.toolCallId)){const{id:je,input:et,...ct}=Le,qe=et&&typeof et=="object"&&Object.keys(et).length>0?{...ct,input:et}:ct;Q(F.toolCallId,qe)}else z(Le)})),ae.push(ce.on("tool_call_update",F=>{if(Ae("tool_call_update",F)||de(F))return;const fe={status:F.status==="completed"?"completed":F.status==="failed"?"failed":F.toolStatus==="completed"?"completed":F.toolStatus==="failed"?"failed":"running",result:F.rawOutput||F.toolResult};if(F.content!==void 0){const Le=(Array.isArray(F.content)?F.content:[]).filter(We=>{var je;return!We||typeof We!="object"?!0:!(We.type==="content"&&((je=We.content)==null?void 0:je.type)==="text")});Le.length>0&&(fe.content=Le)}F.rawInput&&typeof F.rawInput=="object"&&Object.keys(F.rawInput).length>0&&(fe.input=F.rawInput);const X=(F._meta||{})["codebuddy.ai"];X!=null&&X.toolMetaData&&(fe.metaData=X.toolMetaData);const Ce=(Array.isArray(F.content)?F.content:[]).find(Ee=>(Ee==null?void 0:Ee.type)==="terminal"&&typeof Ee.terminalId=="string");Ce!=null&&Ce.terminalId&&F.toolCallId&&$i.getState().linkToolCall(F.toolCallId,Ce.terminalId),Q(F.toolCallId,fe)})),ae.push(ce.on("terminal_update",F=>{if(de(F))return;const ie=(F._meta||{}).timestamp,fe=typeof ie=="string"?Date.parse(ie):void 0;$i.getState().applyTerminalUpdate(F,Number.isFinite(fe)?fe:void 0)})),ae.push(ce.on("interruption_request",F=>{var ie;if(!de(F)){if(F.toolName==="AskUserQuestion"){const fe=Array.isArray((ie=F.toolInput)==null?void 0:ie.questions)?F.toolInput.questions:[];w({id:F.toolCallId,toolCallId:F.toolCallId,sessionId:F.sessionId||Ge.getState().sessionId||"",source:"interruption",questions:fe.map(bS)});return}T({id:F.interruptionId,sessionId:F.sessionId,reason:F.reason,options:F.options,toolName:F.toolName,toolTitle:F.toolTitle,toolInput:F.toolInput,toolCallId:F.toolCallId,workflowSourceText:F.workflowSourceText,mcpUiIntercept:F.mcpUiIntercept===!0||typeof F.toolCallId=="string"&&F.toolCallId.startsWith("mcpui-")})}})),ae.push(ce.on("question_request",F=>{if(de(F))return;const ie=Array.isArray(F.questions)?F.questions:[];w({id:F.toolCallId,toolCallId:F.toolCallId,sessionId:F.sessionId||Ge.getState().sessionId||"",source:"extMethod",questions:ie.map(bS)})})),ae.push(ce.on("session_end",F=>{if(de(F))return;const ie=Vg(F);L(F.stopReason,Qg(ie)??F.errorMessage,ie.category,ie.finishReason??F.finishReason)})),ae.push(ce.on("session_info_update",F=>{F.title&&!de(F)&&y(F.title);const ie=F._meta||{};if(ie["codebuddy.ai/historyReplay"]==="start"?de(F)||(d.current=!0,s.current=typeof(F==null?void 0:F.sessionId)=="string"?F.sessionId:t.current.expectedSessionId(Ge.getState().sessionId),ee(),$i.getState().reset(),$(!0)):ie["codebuddy.ai/historyReplay"]==="end"&&(de(F)||(d.current=!1,$(!1),fS(ie["codebuddy.ai/sessionSnapshot"]),ot.getState().isAgentRunning||Y())),!de(F)&&"codebuddy.ai/sessionSnapshot"in ie&&ie["codebuddy.ai/historyReplay"]!=="start"&&ie["codebuddy.ai/historyReplay"]!=="end"&&fS(ie["codebuddy.ai/sessionSnapshot"]),!de(F)&&ie["codebuddy.ai/agentPhase"]){const X=ie["codebuddy.ai/agentPhase"];q(x5(X)),v5.has(X.phase)&&ke()}if("codebuddy.ai/progress"in ie){const X=ie["codebuddy.ai/progress"];X?(ue(`progress.${X.type}`),ke(),X.type==="compacting"&&H(!1)):ue(null)}if("codebuddy.ai/compact-cancelled"in ie){const X=ie["codebuddy.ai/compact-cancelled"];X&&typeof X=="object"&&H(!0)}if("codebuddy.ai/goalProgress"in ie){const X=ie["codebuddy.ai/goalProgress"];X&&typeof X=="object"&&X.condition&&G({id:X.id??`goal-progress-${Date.now()}`,condition:X.condition,reason:X.reason,turnCount:X.turnCount??1,createdAt:typeof X.createdAt=="number"?X.createdAt:void 0})}if("codebuddy.ai/goalResult"in ie){const X=ie["codebuddy.ai/goalResult"];X&&typeof X=="object"&&X.condition&&J({id:X.id??`goal-result-${Date.now()}`,ok:X.ok!==!1,reason:X.reason,condition:X.condition,durationMs:X.durationMs??0,turnCount:X.turnCount??1,tokenDelta:X.tokenDelta??0})}if("codebuddy.ai/goalRecap"in ie){const X=ie["codebuddy.ai/goalRecap"];X&&typeof X=="object"&&V(X)}if("codebuddy.ai/mcpFirstRunStatus"in ie){const X=ie["codebuddy.ai/mcpFirstRunStatus"];X&&typeof X=="object"&&qi.getState().applyEvent(X)}if("codebuddy.ai/goalStatus"in ie){const X=ie["codebuddy.ai/goalStatus"];X&&typeof X=="object"&&X.kind&&oe({id:X.id??`goal-status-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,kind:X.kind,condition:X.condition,prev:X.prev,actual:X.actual,max:X.max,createdAt:typeof X.createdAt=="number"?X.createdAt:void 0})}if(ie["codebuddy.ai/sessionReset"]){const X=ie["codebuddy.ai/newSessionId"];if(X)try{const Ce=t.current.adoptRetargetedSession(X);if(n.current=null,s.current=null,d.current=!1,P(),$(!1),f(!1),m(Ce),td(Ce),Ge.setState({topic:null}),C(null),bs.getState().reset(),ui.getState().reset(),typeof sessionStorage<"u"&&sessionStorage.setItem("acp-session-id",Ce),typeof localStorage<"u"&&localStorage.setItem("codebuddy.last-session-id",Ce),typeof window<"u"&&window.history&&window.location){const Ee=new URL(window.location.href);Ee.searchParams.set("sessionId",Ce),window.history.replaceState({},"",Ee.toString())}}catch(Ce){console.error(`Failed to commit new session after reset: ${Oo(Ce)}`,Ce)}}if(ie["codebuddy.ai/permissionResolved"]){const X=ie["codebuddy.ai/toolCallId"],Ce=ie["codebuddy.ai/decision"];X&&Ce?(qp({event:"client-resolved",toolCallId:X,decision:Ce}),st().clearPermissionRequestByToolCallId(X),I(X,Ce),R(X)):console.warn("[use-acp] permissionResolved missing toolCallId or decision, NOT dispatching",{toolCallId:X,decision:Ce})}if("codebuddy.ai/promptSuggestion"in ie){const X=ie["codebuddy.ai/promptSuggestion"];C(X||null)}const fe=ie["codebuddy.ai/teamUpdate"];if(fe)switch(fe.type){case"member_status_change":fe.members&&(fe.teamName?Ir.getState().setTeamStatus({isInTeam:!0,teamName:fe.teamName,isAutoTeam:fe.isAutoTeam,members:fe.members}):Ir.getState().updateMembers(fe.members));break;case"team_created":Ir.getState().setTeamStatus({isInTeam:!0,teamName:fe.teamName,members:[]});break;case"team_deleted":Ir.getState().clearTeam();break}})),ae.push(ce.on("model_update",F=>{de(F)||(b((F.availableModels||[]).map(ie=>{var fe,X;return{id:ie.modelId??ie.id,name:ie.name||ie.modelId||ie.id,description:ie.description??null,credits:((fe=ie._meta)==null?void 0:fe.credits)??null,contextWindow:((X=ie._meta)==null?void 0:X.maxInputTokens)??null}})),_(F.currentModelId||""))})),ae.push(ce.on("mode_update",F=>{de(F)||(F.availableModes&&v(F.availableModes),F.currentModeId&&A(F.currentModeId))})),ae.push(ce.on("current_mode_update",F=>{de(F)||F.currentModeId&&A(F.currentModeId)})),ae.push(ce.on("config_option_update",F=>{if(de(F))return;const ie=F.configOptions||[];for(const fe of ie)if(!mS(fe)){if(fe.id==="thought_level")x(fe.currentValue!=="disabled"),k({currentValue:fe.currentValue,options:fe.options||[]});else if(fe.id==="mode"&&fe.currentValue)A(fe.currentValue);else if(fe.id==="model"&&fe.currentValue&&(_(fe.currentValue),fe.options)){const X=Ge.getState().models;b(fe.options.map(Ce=>{const Ee=X.find(Le=>Le.id===Ce.value);return{id:Ce.value,name:Ce.name||Ce.value,description:Ce.description??(Ee==null?void 0:Ee.description)??null,credits:(Ee==null?void 0:Ee.credits)??null,contextWindow:(Ee==null?void 0:Ee.contextWindow)??null}}))}}})),ae.push(ce.on("status_change",F=>{F==="connected"&&!Ge.getState().sessionId||p(F)})),ae.push(ce.on("usage_update",F=>{if(typeof(F==null?void 0:F.used)!="number"||typeof(F==null?void 0:F.size)!="number")return;const ie=t.current.expectedSessionId(Ge.getState().sessionId);if(F.sessionId&&ie&&F.sessionId!==ie)return;const fe=F._meta||{};bs.getState().setUsage({sessionId:F.sessionId,used:F.used,size:F.size,cost:F.cost,usageByCategory:fe["codebuddy.ai/usageByCategory"]})})),ae.push(ce.on("available_commands_update",F=>{de(F)||F.availableCommands&&S(F.availableCommands.map(ie=>{var fe,X;return{name:ie.name,description:ie.description||"",...((fe=ie._meta)==null?void 0:fe.type)==="skill"?{type:"skill"}:{},...typeof((X=ie._meta)==null?void 0:X.source)=="string"&&ie._meta.source?{source:ie._meta.source}:{}}}))})),ae.push(ce.on("checkpointCreated",F=>{ui.getState().onCheckpoint(F)})),ae.push(ce.on("checkpointUpdated",F=>{ui.getState().onCheckpoint(F)})),ae.push(ce.on("checkpointReverted",()=>{ui.getState().reset()})),()=>{ae.forEach(F=>F())}},[u]);const he=g.useCallback((ce,ae)=>{var Ae;if(ce.models&&(b(ce.models.availableModels.map(de=>{var F,ie;return{id:de.modelId??de.id,name:de.name||de.modelId||de.id,description:de.description??null,credits:((F=de._meta)==null?void 0:F.credits)??null,contextWindow:((ie=de._meta)==null?void 0:ie.maxInputTokens)??null}})),_(ce.models.currentModelId)),ce.modes&&(v(ce.modes.availableModes),A(ce.modes.currentModeId)),ce.configOptions)for(const de of ce.configOptions)de.id==="thought_level"&&(x(de.currentValue!=="disabled"),k({currentValue:de.currentValue,options:de.options||[]})),mS(de);if((ce.agents||ce.currentAgentName!==void 0||ce.sessionBlank!==void 0)&&nt.getState().applyAgentFromResponse({agents:ce.agents,currentAgentName:ce.currentAgentName,defaultAgentName:ce.defaultAgentName,sessionBlank:ce.sessionBlank}),ae!=null&&ae.applyLastUsedPrefs){const de=nt.getState().processAgent,F=nt.getState().processPermissionMode,ie=de?null:g5({sessionBlank:ce.sessionBlank??!0,stagedAgent:nt.getState().stagedAgent,stored:typeof localStorage<"u"?localStorage.getItem(Aa):null,sessionId:Ge.getState().sessionId,currentAgentName:ce.currentAgentName,defaultAgentName:ce.defaultAgentName});ie&&ie.agentName!==ce.currentAgentName&&(fC(),nt.getState().setLoading(),st().callExtMethod("session/set_agent",{sessionId:ie.sessionId,agentName:ie.agentName}).then(Le=>{Le!=null&&Le.agentName?nt.getState().applySetAgentResult({agentName:Le.agentName,models:Le.models??[],currentModelId:Le.currentModelId??"",sessionBlank:Le.sessionBlank??!1}):Ao()}).catch(Le=>{Ao(),console.warn("[use-acp] staged main agent injection failed (kept for retry):",Le)}));const fe=F??xC(),X=Ge.getState().sessionId,Ce=(Ae=ce.modes)==null?void 0:Ae.currentModeId,Ee=(ie==null?void 0:ie.agentName)??de??ce.currentAgentName;fe&&X&&fe!==Ce&&!(Ee==="minimal"&&fe==="plan")&&st().setMode(X,fe).then(()=>{Ge.getState().setCurrentMode(fe)}).catch(Le=>{console.warn("[use-acp] last permission mode injection failed:",Le)})}},[]),ne=g.useCallback(ce=>{const ae=ce.trim(),Ae=Ge.getState().sessionId;if(!Ae||!ae)return Promise.reject(new Error("Session switch requires current and target session ids"));if(Ae===ae)return Promise.resolve(!0);const de=n.current;if(de)return de.targetSessionId===ae?de.promise:Promise.reject(new Error(`Session switch already in progress: ${de.targetSessionId}`));const F=t.current.begin(Ae,ae),ie=Ge.getState(),fe=ot.getState(),X=bs.getState(),Ce=ui.getState(),Ee=$i.getState(),Le=nt.getState();f(!0),Ge.setState({topic:null}),C(null),bs.getState().reset(),ui.getState().reset(),$i.getState().reset(),nt.getState().reset({keepProcessDefaults:!0}),s.current=null,d.current=!1;const We={targetSessionId:ae,promise:Promise.resolve(!1)},je=(async()=>{try{const et=await e.current.loadSession(ae);if(!t.current.isCurrent(F))throw new Error(`Stale session switch response: ${ae}`);if(s.current!==ae?P():_e(!1),m(ae),td(ae),he(et),typeof sessionStorage<"u"&&sessionStorage.setItem("acp-session-id",ae),typeof localStorage<"u"&&localStorage.setItem("codebuddy.last-session-id",ae),typeof window<"u"&&window.history&&window.location){const ct=new URL(window.location.href);ct.searchParams.get("sessionId")!==ae&&(ct.searchParams.set("sessionId",ae),window.history.replaceState({},"",ct.toString()))}return!0}catch(et){throw t.current.isCurrent(F)&&(Ge.setState(ie),ot.setState(fe),bs.setState(X),ui.setState(Ce),$i.setState(Ee),nt.setState(Le)),et}finally{t.current.finish(F),s.current=null,d.current=!1,f(!1),n.current===We&&(n.current=null)}})();return We.promise=je,n.current=We,je},[he,P,_e,C,m,f]),pe=g.useCallback(ce=>i.current.run(async()=>{const ae=(ce==null?void 0:ce.persistLastId)!==!1,Ae=Ge.getState(),de=ot.getState(),F=bs.getState(),ie=ui.getState();if(!ae)return(await e.current.newSession({persistLastId:!1})).sessionId;f(!0);try{l5({currentMode:Ae.currentMode,processPermissionMode:nt.getState().processPermissionMode})&&lf(Ae.currentMode);const fe=await e.current.newSession();return t.current.adoptRetargetedSession(fe.sessionId),n.current=null,s.current=null,d.current=!1,P(),m(fe.sessionId),td(fe.sessionId),he(fe,{applyLastUsedPrefs:!0}),Ge.setState({topic:null}),C(null),bs.getState().reset(),ui.getState().reset(),fe.sessionId}catch(fe){throw Ge.setState(Ae),ot.setState(de),bs.setState(F),ui.setState(ie),fe}finally{f(!1)}}),[he,P,C,m,f]),re=g.useCallback(ce=>r.current.run(async()=>{const ae=typeof ce=="string"?ce:ce==null?void 0:ce.token,Ae=typeof ce=="object"?ce==null?void 0:ce.continue:!1;if(ae){if(Ca)try{await Ca.disconnect()}catch{}Ca=new rc(void 0,ae),e.current=Ca,h(de=>de+1),await new Promise(de=>setTimeout(de,0))}try{p("connecting"),C(null);const de=await e.current.initializeSession({continue:Ae});m(de.sessionId),td(de.sessionId),de.processDefaults&&(nt.getState().applyProcessDefaults(de.processDefaults),de.sessionBlank===!0&&de.processDefaults.permissionMode&&Ge.getState().setCurrentMode(de.processDefaults.permissionMode)),he(de,{applyLastUsedPrefs:de.sessionBlank===!0}),nt.getState().applyBackendSupport(de.mainAgentSupport===!0),p("connected"),yC.getState().fetchUserInfo(e.current)}catch(de){console.error("Connection failed:",de),p("error")}}),[]);return{client:e.current,connect:re,switchSession:ne,createSession:pe}}const cf="/assets/red-claw-cat--t2EuBIB.png",wC="codebuddy-locale";function SC(){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 Oh(e){return e==="system"?SC():e}function S5(){try{const e=localStorage.getItem(wC);if(e){const t=JSON.parse(e),n=(t==null?void 0:t.mode)??e;if(["zh","en","system"].includes(n))return n}}catch{}return"system"}const uu=Rt()(Ga((e,t)=>{const n=S5(),r=Oh(n);return typeof window<"u"&&window.addEventListener("languagechange",()=>{const i=uu.getState();if(i.mode==="system"){const s=SC();s!==i.resolved&&uu.setState({resolved:s})}}),{mode:n,resolved:r,setLocale:i=>{const s=Oh(i);e({mode:i,resolved:s})},toggle:()=>{const i=t().mode,s=i==="zh"?"en":i==="en"?"system":"zh";t().setLocale(s)}}},{namespace:"locale",fields:["mode"],scope:"global",debounceMs:300,localStorageKey:wC,onLoad:(e,t)=>{if(e.mode){const n=Oh(e.mode);t({mode:e.mode,resolved:n})}}})),yS={zh:{"app.connecting":"正在连接 CodeBuddy Code...","agents.action.delete":"删除","agents.action.delete.confirm":"确定要删除这个智能体吗?","agents.action.delete.failed":"未能删除这个智能体","agents.action.delete.worktreeKept":"智能体已删除,工作树保留在 {path}","agents.action.more":"更多操作","agents.action.new":"新建智能体","agents.action.cancelNew":"取消新建","agents.action.newConversation":"在当前智能体中新建对话","agents.action.rename":"重命名","agents.action.restart":"重新启动","agents.action.stop":"停止","agents.action.pin":"置顶","agents.action.unpin":"取消置顶","agents.action.ungroup":"从项目中移除","agents.action.copySessionId":"复制会话 ID","agents.action.copyCwd":"复制工作目录","agents.action.openInNewWindow":"在新窗口中打开","agents.action.copyOk":"已复制到剪贴板","agents.action.copyFailed":"复制失败","agents.empty":"暂无活跃的智能体","agents.empty.hint":"点击面板顶部 + 新建智能体","agents.group.attention":"需要你输入","agents.group.needsInput":"需要输入","agents.group.working":"运行中","agents.group.showMore":"展开显示({count})","agents.group.showLess":"收起显示","agents.group.pinned":"置顶","agents.panel.title":"智能体实例","agents.panel.resize":"调整智能体面板宽度","agents.project.rename":"重命名项目","agents.search.clear":"清空搜索","agents.search.noMatch":"没有匹配的智能体","agents.search.placeholder":"搜索智能体","layout.toggle":"布局","layout.sidebar":"导航侧边栏","layout.agents":"智能体面板","agents.title":"智能体","agents.instanceFallback":"智能体 {id}","agents.panel.close":"关闭","agents.input.placeholder":"描述这个智能体要做什么…","agents.input.hint":"在所选工作目录启动一个 CodeBuddy 智能体","agents.input.submit":"创建智能体","agents.input.permission":"启动权限","agents.input.permission.default":"跟随默认设置","agents.input.permission.default.desc":"不覆盖权限模式,使用当前配置的默认权限","agents.input.permission.ask":"每次询问","agents.input.model":"模型","agents.input.model.default":"默认模型","agents.input.effort":"思考强度","agents.input.effort.default":"跟随模型","agents.input.effort.default.desc":"使用所选模型配置的默认思考强度","agents.input.directory":"工作目录","agents.input.directory.hint":"智能体将在此目录执行命令、读写文件","agents.input.directory.choose":"选择工作目录","agents.input.directory.current":"当前工作区","agents.input.directory.more":"另有 {count} 个","agents.input.directory.loading":"正在发现仓库与工作树…","agents.input.directory.browse":"选择其他目录…","agents.input.agent":"当前智能体","agents.input.agent.menu":"选择智能体","agents.input.agent.default":"默认智能体","agents.input.agent.default.desc":"使用当前项目的默认智能体配置","agents.input.settings":"智能体设置","agents.input.modelAndEffort":"模型与思考","agents.input.shellJob":"Shell 任务","agents.input.shellPlaceholder":"输入要在后台执行的命令…","agents.input.attachmentsNotForShell":"Shell 任务不能携带附件,请先去掉文件或去掉命令前的 !","agents.input.startFrom":"上下文","agents.input.startFrom.continue":"继承当前对话","agents.input.startFrom.session":"继承所选对话","agents.input.startFrom.blank":"不继承","agents.input.startFrom.unavailable":"当前没有可继承的上下文","agents.input.worktree":"工作树","agents.input.worktree.on":"已开启工作树隔离","agents.input.worktree.off":"已关闭工作树隔离(Web 默认)","inherit.drawer.title":"选择上下文","inherit.fromCurrent":"当前对话","inherit.fromSession":"可继承的对话","inherit.emptyForDirectory":"这个目录还没有可继承的对话","agents.worker.standalone":"独立进程","agents.worker.remote":"远程","agents.worker.openTabHint":"点击在标签页打开完整实例","agents.worker.noUrl":"无访问地址,仅可在宿主侧操作","agents.worker.kind.interactive":"交互终端","agents.worker.kind.daemon":"服务进程","agents.worker.kind.daemonWorker":"工作进程","agents.worker.kind.bg":"后台任务","agents.state.failed":"失败","agents.state.stopped":"已停止","agents.state.idle":"空闲","agents.state.draft":"待创建","agents.state.completed":"已完成","agents.notice.failed":"会话意外结束,点击查看并可重新启动","agents.state.recovering":"恢复中…","recent.title":"最近会话","sessions.current":"当前","sessions.currentTitle":"主智能体","sessions.deleteCurrent":"删除当前对话","sessions.deleteCurrent.confirm":"将结束当前对话并删除其历史记录,确定吗?","sessions.foregroundHandoff":"已转为后台,仍由主对话承载","sessions.worker.openTab":"在新标签页打开","sessions.section":"实例列表","sessions.togglePanel":"切换会话面板","agents.phase.preparing":"准备中","agents.phase.modelRequesting":"请求模型中…","agents.phase.modelStreaming":"正在生成回复…","agents.phase.modelDone":"收尾中…","agents.phase.toolExecuting":"执行工具中…","agents.phase.working":"工作中…","agents.phase.retrying":"重试中…","agents.phase.compacting":"压缩上下文中…","agents.phase.cancelling":"取消中…","agents.phase.resuming":"恢复中…","agents.phase.starting":"启动中…","agents.phase.waitingPermission":"等待权限确认","agents.phase.waitingInput":"等待输入","agents.live.background":"由后台进程继续执行","agents.live.creating":"正在创建智能体,启动后将自动进入","agents.live.restoring":"正在恢复智能体,可先查看完整对话","agents.live.settled":"智能体已结束运行","agents.live.foregroundHeld":"宿主对话正在持有,可继续投递","agents.live.latest":"智能体最新回复","agents.live.tool":"正在使用工具","agents.live.result":"执行结果","agents.reply.sent":"已发送给这个智能体","agents.reply.saved":"已保存,将在智能体恢复后发送","agents.reply.failed":"发送给智能体失败","agents.reply.answerPlaceholder":"回答这个智能体…","agents.reply.useSuggestion":"采用建议回复","agents.reply.tabSuggestion":"Tab 采用建议 · 数字键选择选项","agents.reply.shellHint":"输入 ! 可在智能体内执行 Shell 命令","agents.reply.shellMode":"Shell","agents.reply.sendShell":"执行 Shell 命令","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.messages":"聊天消息","chat.scrollToLatest":"跳到最新","chat.error.refusal":"Agent 拒绝继续执行。这可能是由于内容策略限制或其他限制。","chat.error.network":"网络连接异常或服务暂时不可用,请稍后重试。","chat.error.auth":"身份验证失败或权限不足,请重新登录后再试。","chat.error.quota":"已达到配额上限或请求过于频繁,请稍后再试。","chat.error.modelService":"模型服务返回异常,请重试或稍后再试。","chat.error.cancelled":"请求已被取消,可能由系统休眠或网络中断导致,请重试。","chat.error.maxTokens":"响应因达到最大 token 限制而被截断。您可以继续对话或要求更简洁的回复。","chat.error.maxTurnRequests":"已超过单轮对话允许的最大模型请求次数。您可以发送新消息以继续。","message.contentFilter.notice":"这个话题目前不在我的能力覆盖范围内,我没有办法就此展开讨论。","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":"压缩上下文中","hero.headline":"CodeBuddy Code","hero.newAgent":"新建智能体","input.placeholder":"告诉这个智能体下一步要做什么...","input.placeholderGoal":"描述你的目标,定义可衡量的成果,以获得最佳效果","input.placeholderRunning":"消息将排队等待处理...","input.placeholderPending":"请先处理权限请求...","input.draft":"草稿","input.send":"发送 (Enter)","input.stop":"停止","input.thinking":"思考中","input.deepThinking":"深度思考","input.promptFailed":"发送失败","input.sessionNotReady":"会话尚未就绪,请稍后再发送","input.agentSwitchTimeout":"Agent 预设切换超时,请重试","input.sendQueued":"发送排队消息 (Enter)","input.dropHint":"拖拽文件到这里","input.addImage":"添加图片","input.addFile":"添加文件","input.goal":"目标","input.imageTooLarge":"图片不能超过 10MB","input.tooManyImages":"最多添加 5 张图片","input.fileTooLarge":"文件不能超过 50MB","input.tooManyFiles":"最多添加 10 个文件","input.attachmentUploadFailed":"附件上传失败,请重试","input.menu.image":"图片","input.menu.file":"文件","input.menu.directory":"目录","input.directory.current":"当前目录","input.directory.add":"添加目录","input.menu.mode":"模式","input.menu.model":"模型","input.modeSelector":"模式","input.modelSelector":"模型","mainAgent.defaultLabel":"默认预设","mainAgent.selectAgent":"即将开始的这个会话所用的 Agent 预设","mainAgent.lockedHint":"本会话运行的 Agent 预设,开始时即固定","mainAgent.customTag":"本地创作","mainAgent.empty":"暂无可用预设","mainAgent.sectionTitle":"Agent 预设","mainAgent.manage":"管理预设","mainAgent.currentDefault":"当前默认","mainAgent.currentDefaultHint":"对此后新建的会话生效。运行中的会话保持它开始时的预设。","mainAgent.isDefault":"默认","mainAgent.setDefault":"设为默认","mainAgent.defaultSaved":"默认预设已保存","mainAgent.groupBuiltin":"内置","mainAgent.groupCustom":"自定义","mainAgent.createByAI":"用 AI 快速创建","mainAgent.createByAIHint":"用一句话描述你想要的智能体,AI 会生成名字、说明和系统提示(写入用户级目录;工具按最小权限自动选择)。这不是创造模式会话。","mainAgent.createByAIPlaceholder":"例如:做一个只读的代码评审智能体,用 hy3 模型","mainAgent.creating":"正在生成","mainAgent.createSuccess":"智能体已创建,可在会话中选用","mainAgent.capability":"Agent 预设","mainAgent.capabilityHint":"开启后可在本 Web 选择标准 / PTC / 极简 / 创造。WorkBuddy 默认不走预设解析;若与 sidecar 共用同一份 settings,再打开「允许未声明宿主」才会影响 WorkBuddy。","mainAgent.capabilityOn":"已开启","mainAgent.capabilityOff":"已关闭","mainAgent.noDescription":"暂无描述。","mainAgent.mode.cli":"标准模式","mainAgent.mode.ptc":"PTC 模式","mainAgent.mode.minimal":"极简模式","mainAgent.mode.create":"创造模式","mainAgent.modeDesc.cli":"功能完整的编码 Agent:改文件、跑命令、检索代码和网页,以及 Skills、计划、目标和子代理。","mainAgent.modeDesc.ptc":"标准模式的工作工具改走 REPL / Code Mode,用一段程序组合多步,而不是逐个直连调用。","mainAgent.modeDesc.minimal":"只开 REPL,沙箱内仅 Bash 与 Edit。没有 Read、Write、Glob、Grep、检索、计划、子代理。看文件用 Bash,读 r.stdout。","mainAgent.modeDesc.create":"标准模式全工具,外加编写 .codebuddy/agents 自定义智能体的指导。","mainAgent.scope.user":"用户级","mainAgent.scope.project":"项目级","mainAgent.delete":"删除","mainAgent.deleteConfirm":"确认删除?","mainAgent.deleted":"已删除 {name}","mainAgent.deleteFailed":"删除失败","mainAgent.searchPlaceholder":"搜索智能体名称或描述","mainAgent.filterEmpty":"没有匹配的智能体","mainAgent.openFile":"打开文件","mainAgent.openFailed":"打开文件失败","mainAgent.openInCreate":"在创造模式中打开","mainAgent.openInCreateSuccess":"已切换到创造模式","mainAgent.openInCreateFailed":"仅空白会话可切换到创造模式","mainAgent.trustLocal":"本地","input.deepThinkingDesc":"让模型在回答前进行更深入的推理","input.thinkingLevel":"思考强度","input.thinkingMode":"思考模式","input.thoughtDefault":"默认","input.contextWindow":"上下文窗口","input.editThinking":"编辑思考配置","input.modelHeader":"模型","input.contextUsage.title":"上下文用量","input.contextUsage.used":"已用上下文","input.contextUsage.usedLabel":"已使用","input.contextUsage.compact":"压缩当前会话","input.contextUsage.systemPrompt":"系统提示词","input.contextUsage.conversation":"对话消息","input.contextUsage.tools":"工具及子智能体","input.contextUsage.mcp":"连接器及MCP","input.contextUsage.skills":"技能","mode.default":"默认","mode.default.desc":"每次首次使用工具时都请求权限","mode.acceptEdits":"自动通过编辑","mode.acceptEdits.desc":"本会话自动通过文件编辑权限","mode.plan":"规划模式","mode.plan.desc":"只分析、不修改文件或执行命令","mode.auto":"自动","mode.auto.desc":"AI 分类器审查操作:安全的自动通过,高风险的拒绝。分类器不可用时回退为弹窗确认(或拒绝)","mode.dontAsk":"免打扰","mode.dontAsk.desc":"不弹出权限确认;执行预批准和安全操作,拒绝需要审批的操作","mode.bypassPermissions":"跳过权限确认","mode.bypassPermissions.desc":"跳过所有权限确认","mode.fullAccess":"完全访问","mode.fullAccess.desc":"跳过所有权限检查,包括所有代理的危险命令","mode.work":"工作","mode.work.desc":"标准工作模式,按常规流程请求权限","mode.delegate":"委托","mode.delegate.desc":"权限由上级会话集中管理","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.replSubagentSummary":"REPL 内子 agent 输出已在上方/下方独立展示,这里不重复展开原始文本。","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.toggle":"切换菜单栏","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":"复制","clipboard.copyFailed":"复制失败:当前环境不支持剪贴板操作,请使用 HTTPS 访问或手动选择文本复制","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":"服务条款","account.login.title":"账户登录","account.login.subtitle":"CodeBuddy 尚未登录,请选择登录方式完成认证","account.login.button":"登录","account.login.polling":"等待登录完成...","account.login.polling.hint":"请在浏览器中完成登录,完成后此页面将自动跳转","account.login.openBrowser":"打开浏览器登录","account.login.copyUrl":"复制登录链接","account.login.copied":"已复制","account.login.failed":"登录失败,请重试","account.login.retry":"重试","account.logout":"退出登录","account.logout.confirm":"确认退出当前账户?","account.method.internal":"国内站点登录","account.method.external":"国际站点登录","account.method.selfhosted":"企业域名登录","account.method.iOA":"iOA 登录(仅限腾讯)","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.split":"拆分终端","terminal.splitHorizontal":"左右分屏","terminal.splitVertical":"上下分屏","terminal.closePane":"关闭终端","terminal.close":"关闭","terminal.closeOthers":"关闭其他","terminal.closeToRight":"关闭右侧","terminal.closeAll":"关闭全部","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":"问题已取消","question.invalid":"问题参数无效,无法显示","todo.title":"任务清单","todo.executing":"任务{n}正在执行中","todo.untitled":"未命名","bgTasks.summary":"{total} 个后台任务 · {running} 个运行中","bgTasks.status.done":"已完成","bgTasks.status.failed":"已失败","bgTasks.status.ended":"已结束","bgTasks.status.elapsed":"已运行 {duration}","bgTasks.untitled":"后台命令","history.title":"智能体历史","history.description":"在当前智能体内继续项目对话","history.backgroundDescription":"智能体正在后台工作,完成接管后可切换对话","history.target":"载入到 {name}","history.project":"项目","history.noProjects":"暂无可用项目","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":"无法删除当前会话","history.renameFailed":"重命名失败","history.deleteFailed":"删除失败","history.restore":"在当前智能体中打开","history.restoreSuccess":"已在当前智能体中继续该对话","history.restoreFailed":"载入历史对话失败","settings.title":"设置","settings.appearance":"外观","settings.model":"模型选择","settings.customModels.manage":"管理自定义模型","settings.customModels.entryLabel":"自定义模型","settings.customModels.entryDesc":"添加 OpenAI 兼容端点,支持增删改","settings.customModels.title":"自定义模型","settings.customModels.addTitle":"添加自定义模型","settings.customModels.editTitle":"编辑自定义模型","settings.customModels.add":"添加","settings.customModels.edit":"编辑","settings.customModels.delete":"删除","settings.customModels.deleteTitle":"删除自定义模型?","settings.customModels.deleteMessage":"将删除模型 {id},此操作不可撤销。","settings.customModels.cancel":"取消","settings.customModels.save":"保存","settings.customModels.close":"关闭","settings.customModels.empty":"暂无自定义模型","settings.customModels.hint":"数据保存在本机 ~/.codebuddy/models.json","settings.customModels.loadFailed":"加载自定义模型失败","settings.customModels.saveFailed":"保存失败","settings.customModels.deleteFailed":"删除失败","settings.customModels.apiKeyKeep":"留空则保留原密钥","settings.customModels.field.id":"模型 ID","settings.customModels.field.name":"显示名称","settings.customModels.field.vendor":"提供商","settings.customModels.field.url":"接口 URL","settings.customModels.field.apiKey":"API Key","settings.customModels.field.maxInputTokens":"最大输入 Tokens","settings.customModels.field.maxOutputTokens":"最大输出 Tokens","settings.customModels.field.temperature":"Temperature","settings.customModels.field.temperatureDefault":"留空使用默认值(不发送)","settings.customModels.field.supportsToolCall":"支持工具调用","settings.customModels.field.supportsImages":"支持图片","settings.customModels.field.supportsReasoning":"支持推理","settings.customModels.field.useCustomProtocol":"自定义协议(不自动补 /chat/completions)","settings.customModels.err.idRequired":"请填写模型 ID","settings.customModels.err.idInvalid":"模型 ID 仅允许字母、数字与 . _ : -","settings.customModels.err.idDuplicate":"模型 ID 已存在","settings.customModels.err.urlRequired":"请填写接口 URL","settings.customModels.err.urlInvalid":"URL 需以 http:// 或 https:// 开头","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.mainAgent":"Agent 预设","settings.item.mainAgent.enabled":"启用 Agent 预设","settings.item.mainAgent.enabled.desc":"Web / CLI 可选择标准、PTC、极简、创造。关闭后始终走原生标准模式。","settings.item.mainAgent.allowUnopted":"允许未声明的 ACP 宿主","settings.item.mainAgent.allowUnopted.desc":"默认关闭,且仅在上方总闸开启时生效。打开后,与本机共用 settings 的 WorkBuddy sidecar 也会走预设解析。平时请保持关闭。","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.autoCompactWindow":"自动压缩窗口 (token)","settings.item.autoCompactWindow.desc":"压缩计算的上下文窗口基准值,触发点 = min(该值, 模型窗口) × 阈值;留空跟随模型窗口。环境变量 CODEBUDDY_AUTO_COMPACT_WINDOW 优先级更高","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.reconnecting":"正在重新连接...","terminal.reconnectFailed":"重连失败","terminal.search.placeholder":"查找","terminal.search.noResults":"无结果","terminal.search.caseSensitive":"区分大小写","terminal.search.wholeWord":"全字匹配","terminal.search.regex":"使用正则表达式","terminal.search.previous":"上一个匹配","terminal.search.next":"下一个匹配","terminal.search.close":"关闭","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":"上次触发","scheduled.custom":"自定义","scheduled.every":"每","scheduled.unit.minutes":"分钟","scheduled.unit.hours":"小时","scheduled.unit.days":"天","scheduled.unit.weeks":"周","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.kindAll":"全部","plugins.kindSkills":"Skills","plugins.kindMcp":"MCP","plugins.kindHooks":"Hooks","plugins.kindTools":"Tools","plugins.kindUnknown":"其他","plugins.filterStatusAll":"全部状态","plugins.filterStatusEnabled":"已启用","plugins.filterStatusDisabled":"未启用","plugins.infiniteRange":"已显示 {visible} / {total}","plugins.infiniteLoading":"向下滚动加载更多","plugins.infiniteEnd":"已显示全部","plugins.backToTop":"回到顶部","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.loadingFile":"正在加载文件...","editor.loadError":"加载失败","editor.retryLoad":"重试加载","editor.fileTooLarge":"超过 2 MB,无法在编辑器打开","editor.noFile":"选择一个文件开始编辑","editor.unsaved":"未保存","editor.saving":"正在保存","editor.saveFailed":"保存失败","editor.moveFailed":"移动失败","editor.save":"保存","editor.saveAll":"全部保存","editor.close":"关闭","editor.closeTabAriaLabel":"关闭标签页 {name}","editor.closeOthers":"关闭其他","editor.closeAll":"关闭全部","editor.newFile":"新建文件","editor.newFolder":"新建文件夹","editor.rename":"重命名","editor.delete":"删除","editor.deleteConfirmTitle":"确认删除","editor.deleteConfirmMessage":"确定要删除选中的 {count} 个项目吗?此操作无法撤销。","editor.refresh":"刷新","editor.backToWorkDir":"回到工作目录","editor.emptyFolder":"空文件夹","editor.explorer":"资源管理器","editor.fileTreeAriaLabel":"工作区文件树","editor.toggleSidebar":"切换侧边栏","editor.collapseAll":"全部折叠","editor.showHiddenFiles":"显示隐藏文件","editor.hideHiddenFiles":"隐藏隐藏文件","editor.openFolder":"打开目录","editor.openFolderPlaceholder":"输入目录路径...","editor.parentFolder":"上级目录","editor.pin":"固定","editor.unpin":"取消固定","editor.copyPath":"复制路径","editor.copyRelativePath":"复制相对路径","editor.revealInExplorer":"在文件树中定位","editor.closeToRight":"关闭右侧","editor.closeSaved":"关闭已保存","editor.closeSaveFailedTitle":"无法关闭:{count} 个标签页保存失败","editor.closeSaveFailedMessage":"{count} 个标签页保存失败。是否放弃更改并关闭?","editor.discardAndClose":"放弃并关闭","editor.quickOpen":"快速打开文件","editor.focusExplorer":"聚焦资源管理器","editor.recentFiles":"最近文件","editor.quickOpenPlaceholder":"输入文件名以搜索...","editor.quickOpenEmpty":"没有匹配的文件","editor.quickOpenLoading":"正在加载文件列表...","editor.openEditors":"已打开的编辑器","editor.scrollTabsLeft":"向左滚动标签页","editor.scrollTabsRight":"向右滚动标签页","editor.selected":"已选","editor.lines":"行","editor.preview":"切换到预览","editor.source":"切换到源码","editor.openInNewWindow":"在新窗口中打开","editor.mobileBack":"返回文件树","ide.explorer":"资源管理器","ide.search":"搜索","ide.sourceControl":"源代码管理","ide.terminal":"终端","ide.newTerminal":"新建终端","ide.toggleSidebar":"切换侧栏","ide.toggleTerminal":"切换终端","ide.resizeSidebar":"调整侧栏宽度","ide.resizeSidePanel":"调整侧边面板宽度","ide.resizeBottomPanel":"调整底部面板高度","ide.resizeSplit":"调整分屏比例","ide.hidePanel":"隐藏面板","ide.maximizePanel":"最大化面板","ide.restorePanel":"还原面板大小","ide.listView":"列表视图","ide.treeView":"树视图","ide.refresh":"刷新","ide.scm.title":"源代码管理","ide.scm.repositories":"仓库","ide.scm.changes":"变更","ide.scm.stagedChanges":"已暂存的更改","ide.scm.untracked":"未跟踪","ide.scm.noChanges":"没有更改","ide.scm.notGitRepo":"不是 Git 仓库","ide.scm.commitPlaceholder":"消息 (⌘Enter 提交)","ide.scm.commit":"提交","ide.scm.push":"推送","ide.scm.pull":"拉取","ide.scm.stage":"暂存","ide.scm.unstage":"取消暂存","ide.scm.stageAll":"全部暂存","ide.scm.unstageAll":"全部取消暂存","ide.scm.discard":"放弃更改","ide.scm.discardAll":"全部放弃","ide.scm.copyPath":"复制路径","ide.scm.openFile":"打开文件","ide.scm.createBranch":"创建新分支...","ide.scm.newBranchPlaceholder":"新分支名称...","ide.scm.branchSearchPlaceholder":"搜索分支或标签...","ide.scm.switchBranch":"切换分支","ide.scm.localBranches":"本地分支","ide.scm.remoteBranches":"远程分支","ide.scm.noBranchMatch":"没有匹配的分支","ide.scm.graph":"提交记录","ide.scm.closeDiff":"关闭差异","ide.scm.loadingDiff":"加载差异中...","ide.scm.diff":"差异","ide.search.title":"搜索","ide.search.placeholder":"搜索","ide.search.searching":"搜索中...","ide.search.noResults":"未找到结果","ide.search.results":"{count} 个结果,{files} 个文件","ide.search.matchCase":"区分大小写","ide.search.wholeWord":"全字匹配","ide.search.regex":"使用正则表达式","ide.search.filesToInclude":"要包含的文件","ide.search.includePlaceholder":"例如 *.ts, src/**/include","ide.search.filesToExclude":"要排除的文件","ide.search.excludePlaceholder":"例如 node_modules, *.min.js","ide.search.useExcludeSettings":"使用排除设置和忽略文件","ide.search.toggleFilters":"文件筛选器","ide.search.failed":"搜索失败","ide.search.timedOut":"搜索超时","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.goal.title":"Goal","command.goal.description":"设置要持续追求的目标","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.jobCreateFailed":"创建智能体失败,请重试","error.switchSessionFailed":"切换会话失败,请重试","error.sessionOccupied":"该会话正被其他终端或进程占用,无法同时切换","error.sessionUnavailable":"该会话当前不可用,请稍后重试","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":"个工具已执行","tool.mcpAppLoadHint":"点击加载交互式界面","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 <条件>
580
580
  示例:/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","goal.bar.active":"进行中的目标 {condition} · {elapsed}","goal.bar.paused":"已暂停的目标 {condition} · {elapsed}","goal.bar.edit":"编辑目标","goal.bar.pause":"暂停目标","goal.bar.resume":"继续目标","goal.bar.clear":"清除目标","goal.resume.prompt":"继续当前目标:{condition}","goal.edit.title":"编辑目标","goal.edit.save":"保存","goal.edit.cancel":"取消","goal.edit.placeholder":"描述你的目标,定义可衡量的成果,以获得最佳效果","mcp.startup.booting":"正在启动 MCP 服务:{name}","mcp.startup.starting":"正在启动 MCP 服务 ({completed}/{total}):{names}","mcp.startup.elapsed":"{seconds}s","mcp.startup.ready":"MCP 服务已就绪({total})","mcp.startup.failed":"MCP 连接失败:{names}","mcp.startup.timedOut":"MCP 连接超时:{names}"},en:{"app.connecting":"Connecting to CodeBuddy Code...","agents.action.delete":"Delete","agents.action.delete.confirm":"Are you sure you want to delete this agent?","agents.action.delete.failed":"Could not delete this agent","agents.action.delete.worktreeKept":"Agent deleted; worktree kept at {path}","agents.action.more":"More actions","agents.action.new":"New agent","agents.action.cancelNew":"Cancel","agents.action.newConversation":"New chat in this agent","agents.action.rename":"Rename","agents.action.restart":"Restart","agents.action.stop":"Stop","agents.action.pin":"Pin to top","agents.action.unpin":"Unpin","agents.action.ungroup":"Remove from project","agents.action.copySessionId":"Copy session ID","agents.action.copyCwd":"Copy working directory","agents.action.openInNewWindow":"Open in new window","agents.action.copyOk":"Copied to clipboard","agents.action.copyFailed":"Copy failed","agents.empty":"No active agents","agents.empty.hint":"Click + at the top of the panel to create one","agents.group.attention":"Waiting on you","agents.group.needsInput":"Needs Input","agents.group.working":"Working","agents.group.showMore":"Show {count} more","agents.group.showLess":"Show less","agents.group.pinned":"Pinned","agents.panel.title":"Agent instances","agents.panel.resize":"Resize agents panel","agents.project.rename":"Rename project","agents.search.clear":"Clear search","agents.search.noMatch":"No matching agents","agents.search.placeholder":"Search agents","layout.toggle":"Layout","layout.sidebar":"Navigation sidebar","layout.agents":"Agent panel","agents.title":"Agents","agents.instanceFallback":"Agent {id}","agents.panel.close":"Close","agents.input.placeholder":"Describe what this agent should do…","agents.input.hint":"Start a CodeBuddy agent in the selected working directory","agents.input.submit":"Create agent","agents.input.permission":"Launch permission","agents.input.permission.default":"Use default setting","agents.input.permission.default.desc":"Do not override the permission mode; use the configured default","agents.input.permission.ask":"Always ask","agents.input.model":"Model","agents.input.model.default":"Default model","agents.input.effort":"Thinking effort","agents.input.effort.default":"Use model default","agents.input.effort.default.desc":"Use the selected model's configured default thinking effort","agents.input.directory":"Working directory","agents.input.directory.hint":"The agent will run commands and edit files here","agents.input.directory.choose":"Choose working directory","agents.input.directory.current":"Current workspace","agents.input.directory.more":"+{count} more","agents.input.directory.loading":"Discovering repositories and worktrees…","agents.input.directory.browse":"Choose another directory…","agents.input.agent":"Current agent","agents.input.agent.menu":"Choose an agent","agents.input.agent.default":"Default agent","agents.input.agent.default.desc":"Use this project's default agent configuration","agents.input.settings":"Agent settings","agents.input.modelAndEffort":"Model & thinking","agents.input.shellJob":"Shell job","agents.input.shellPlaceholder":"Enter a command to run in the background…","agents.input.attachmentsNotForShell":"Shell jobs cannot carry attachments. Remove the files or the leading !","agents.input.startFrom":"Context","agents.input.startFrom.continue":"Inherit current chat","agents.input.startFrom.session":"Inherit selected chat","agents.input.startFrom.blank":"None","agents.input.startFrom.unavailable":"No context is available from the current chat","agents.input.worktree":"Worktree","agents.input.worktree.on":"Worktree isolation enabled","agents.input.worktree.off":"Worktree isolation disabled (Web default)","inherit.drawer.title":"Choose context","inherit.fromCurrent":"Current chat","inherit.fromSession":"Available chats","inherit.emptyForDirectory":"No conversations in this directory can be inherited yet","agents.worker.standalone":"Standalone process","agents.worker.remote":"Remote","agents.worker.openTabHint":"Open full instance in a new tab","agents.worker.noUrl":"No accessible address, host-side only","agents.worker.kind.interactive":"Terminal","agents.worker.kind.daemon":"Service","agents.worker.kind.daemonWorker":"Worker","agents.worker.kind.bg":"Background job","agents.state.failed":"Failed","agents.state.stopped":"Stopped","agents.state.idle":"Idle","agents.state.draft":"Not created","agents.state.completed":"Completed","agents.notice.failed":"Session ended unexpectedly. Click to review and restart.","agents.state.recovering":"Recovering…","recent.title":"Recent chats","sessions.current":"Active","sessions.currentTitle":"Main agent","sessions.deleteCurrent":"Delete current chat","sessions.deleteCurrent.confirm":"This will end the current chat and delete its history. Continue?","sessions.foregroundHandoff":"Running in background; still owned by main chat","sessions.worker.openTab":"Open in new tab","sessions.section":"Instances","sessions.togglePanel":"Toggle sessions panel","agents.phase.preparing":"Preparing","agents.phase.modelRequesting":"Requesting the model…","agents.phase.modelStreaming":"Writing a response…","agents.phase.modelDone":"Finishing the turn…","agents.phase.toolExecuting":"Running a tool…","agents.phase.working":"Working…","agents.phase.retrying":"Retrying…","agents.phase.compacting":"Compacting the conversation…","agents.phase.cancelling":"Cancelling…","agents.phase.resuming":"Resuming…","agents.phase.starting":"Starting…","agents.phase.waitingPermission":"Waiting for permission","agents.phase.waitingInput":"Waiting for input","agents.live.background":"Continuing in its background process","agents.live.creating":"Creating the agent; it will open automatically when ready","agents.live.restoring":"Restoring the agent; the complete conversation is already available","agents.live.settled":"Agent has finished running","agents.live.foregroundHeld":"Owned by its host chat; prompts can still be queued","agents.live.latest":"Latest agent response","agents.live.tool":"Using tool","agents.live.result":"Result","agents.reply.sent":"Sent to this agent","agents.reply.saved":"Saved and will send when the agent resumes","agents.reply.failed":"Failed to send to the agent","agents.reply.answerPlaceholder":"Answer this agent…","agents.reply.useSuggestion":"Use suggested reply","agents.reply.tabSuggestion":"Tab uses suggestion · number keys choose an option","agents.reply.shellHint":"Start with ! to run a shell command inside this agent","agents.reply.shellMode":"Shell","agents.reply.sendShell":"Run shell command","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.messages":"Chat messages","chat.scrollToLatest":"Scroll to latest","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.cancelled":"Request was cancelled. This can happen after system sleep or network interruption. Please try again.","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.","message.contentFilter.notice":"This topic is currently outside the scope of my capabilities, so I'm unable to discuss it further.","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","hero.headline":"CodeBuddy Code","hero.newAgent":"New agent","input.placeholder":"Tell this agent what to do next...","input.placeholderGoal":"Describe your goal and define measurable outcomes for best results","input.placeholderRunning":"Messages will be queued...","input.placeholderPending":"Please handle the permission request first...","input.draft":"Draft","input.send":"Send (Enter)","input.stop":"Stop","input.thinking":"Thinking","input.deepThinking":"Deep Thinking","input.promptFailed":"Prompt failed","input.sessionNotReady":"Session is not ready yet. Try sending again in a moment.","input.agentSwitchTimeout":"Agent preset switch timed out. Please try again.","input.sendQueued":"Send queued (Enter)","input.dropHint":"Drop files here","input.addImage":"Add image","input.addFile":"Add file","input.goal":"Goal","input.imageTooLarge":"Image must be under 10MB","input.tooManyImages":"Up to 5 images allowed","input.fileTooLarge":"File must be under 50MB","input.tooManyFiles":"Up to 10 files allowed","input.attachmentUploadFailed":"Attachment upload failed. Please try again.","input.menu.image":"Image","input.menu.file":"File","input.menu.directory":"Directory","input.directory.current":"Current directory","input.directory.add":"Add directory","input.menu.mode":"Mode","input.menu.model":"Model","input.modeSelector":"Mode","input.modelSelector":"Model","mainAgent.defaultLabel":"Default preset","mainAgent.selectAgent":"Agent preset for the session you are about to start","mainAgent.lockedHint":"The agent preset this session runs, fixed when it started","mainAgent.customTag":"local","mainAgent.empty":"No presets available","mainAgent.sectionTitle":"Agent presets","mainAgent.manage":"Manage presets","mainAgent.currentDefault":"Current default","mainAgent.currentDefaultHint":"Applies to sessions you start from now on. Running sessions keep the preset they began with.","mainAgent.isDefault":"Default","mainAgent.setDefault":"Set as default","mainAgent.defaultSaved":"Default preset saved","mainAgent.groupBuiltin":"Built-in","mainAgent.groupCustom":"Custom","mainAgent.createByAI":"Quick create with AI","mainAgent.createByAIHint":"Describe the agent in one sentence; AI generates its name, description and system prompt (saved to your user agents folder; tools auto-selected with least privilege). This is not Creator mode.","mainAgent.createByAIPlaceholder":"e.g. A read-only code reviewer agent using the hy3 model","mainAgent.creating":"Generating","mainAgent.createSuccess":"Agent created — pick it in any session","mainAgent.capability":"Agent presets","mainAgent.capabilityHint":"When on, this Web UI can pick Standard / PTC / Minimal / Creator. WorkBuddy stays on native cli unless you also turn on “Allow unopted ACP hosts” and share the same settings file with the sidecar.","mainAgent.capabilityOn":"On","mainAgent.capabilityOff":"Off","mainAgent.noDescription":"No description.","mainAgent.mode.cli":"Standard mode","mainAgent.mode.ptc":"PTC mode","mainAgent.mode.minimal":"Minimal mode","mainAgent.mode.create":"Creator mode","mainAgent.modeDesc.cli":"Full coding agent: edit files, run commands, search code and the web, plus Skills, plans, goals, and sub-agents.","mainAgent.modeDesc.ptc":"Standard capabilities, but worker tools go through REPL / Code Mode so the model composes steps in one program.","mainAgent.modeDesc.minimal":"REPL only; sandbox has Bash and Edit. No Read, Write, Glob, Grep, search, plan, or sub-agents. Inspect files with Bash and read r.stdout.","mainAgent.modeDesc.create":"Full Standard tools, plus guidance for writing custom agents under .codebuddy/agents.","mainAgent.scope.user":"User","mainAgent.scope.project":"Project","mainAgent.delete":"Delete","mainAgent.deleteConfirm":"Confirm delete?","mainAgent.deleted":"Deleted {name}","mainAgent.deleteFailed":"Delete failed","mainAgent.searchPlaceholder":"Search agents by name or description","mainAgent.filterEmpty":"No matching agents","mainAgent.openFile":"Open file","mainAgent.openFailed":"Failed to open file","mainAgent.openInCreate":"Open in Creator mode","mainAgent.openInCreateSuccess":"Switched to Creator mode","mainAgent.openInCreateFailed":"Only blank sessions can switch to Creator mode","mainAgent.trustLocal":"local","input.deepThinkingDesc":"Let the model reason more deeply before answering","input.thinkingLevel":"Thinking level","input.thinkingMode":"Thinking","input.thoughtDefault":"Default","input.contextWindow":"Context window","input.editThinking":"Edit thinking config","input.modelHeader":"Model","input.contextUsage.title":"Context usage","input.contextUsage.used":"context used","input.contextUsage.usedLabel":"Used","input.contextUsage.compact":"Compact conversation","input.contextUsage.systemPrompt":"System prompt","input.contextUsage.conversation":"Messages","input.contextUsage.tools":"Tools & agents","input.contextUsage.mcp":"Connectors & MCP","input.contextUsage.skills":"Skills","mode.default":"Default","mode.default.desc":"Prompts for permission on first use of each tool","mode.acceptEdits":"Accept Edits","mode.acceptEdits.desc":"Automatically accepts file edit permissions for the session","mode.plan":"Plan","mode.plan.desc":"Can analyze but not modify files or execute commands","mode.auto":"Auto","mode.auto.desc":"An AI classifier reviews actions: safe ones are auto-approved, risky ones are denied. Falls back to prompting if unavailable","mode.dontAsk":"Don't Ask","mode.dontAsk.desc":"Never shows permission prompts; runs pre-approved and safe actions, denies anything requiring approval","mode.bypassPermissions":"Bypass Permissions","mode.bypassPermissions.desc":"Skips all permission prompts","mode.fullAccess":"Full Access","mode.fullAccess.desc":"Skips ALL permission checks including dangerous commands for all agents","mode.work":"Work","mode.work.desc":"Standard work mode with normal permission flow","mode.delegate":"Delegate","mode.delegate.desc":"Permissions managed by parent session","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.replSubagentSummary":"Sub-agent output from REPL is shown separately above/below; raw REPL text is not repeated here.","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":"Agent 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.toggle":"Toggle Sidebar","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","clipboard.copyFailed":"Copy failed: clipboard is not available in this environment. Please use HTTPS or manually select and copy the text.","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","account.login.title":"Account Login","account.login.subtitle":"CodeBuddy is not signed in. Please choose a login method to authenticate.","account.login.button":"Login","account.login.polling":"Waiting for login...","account.login.polling.hint":"Please complete login in your browser. This page will redirect automatically.","account.login.openBrowser":"Open Browser to Login","account.login.copyUrl":"Copy Login URL","account.login.copied":"Copied","account.login.failed":"Login failed. Please try again.","account.login.retry":"Retry","account.logout":"Sign Out","account.logout.confirm":"Sign out of current account?","account.method.internal":"Chinese Site","account.method.external":"International Site","account.method.selfhosted":"Enterprise Domain","account.method.iOA":"iOA (Tencent only)","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.split":"Split terminal","terminal.splitHorizontal":"Split Right","terminal.splitVertical":"Split Down","terminal.closePane":"Close Terminal","terminal.close":"Close","terminal.closeOthers":"Close Others","terminal.closeToRight":"Close to the Right","terminal.closeAll":"Close All","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","question.invalid":"Invalid question parameters, cannot display","todo.title":"Tasks","todo.executing":"Task {n} executing","todo.untitled":"Untitled","bgTasks.summary":"{total} background tasks · {running} running","bgTasks.status.done":"Completed","bgTasks.status.failed":"Failed","bgTasks.status.ended":"Ended","bgTasks.status.elapsed":"Running {duration}","bgTasks.untitled":"Background command","history.title":"Agent history","history.description":"Continue a project conversation in the current agent","history.backgroundDescription":"This agent is working in the background; switch conversations after handoff","history.target":"Load into {name}","history.project":"Project","history.noProjects":"No projects available","history.noData":"No conversation history","history.noDataHint":"This project has no conversations to continue yet","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","history.renameFailed":"Rename failed","history.deleteFailed":"Delete failed","history.restore":"Open in current agent","history.restoreSuccess":"Continuing the conversation in the current agent","history.restoreFailed":"Failed to open historical conversation","settings.title":"Preferences","settings.appearance":"Appearance","settings.model":"Model Selection","settings.customModels.manage":"Manage custom models","settings.customModels.entryLabel":"Custom models","settings.customModels.entryDesc":"Add OpenAI-compatible endpoints; create, edit, delete","settings.customModels.title":"Custom models","settings.customModels.addTitle":"Add custom model","settings.customModels.editTitle":"Edit custom model","settings.customModels.add":"Add","settings.customModels.edit":"Edit","settings.customModels.delete":"Delete","settings.customModels.deleteTitle":"Delete custom model?","settings.customModels.deleteMessage":"Delete model {id}. This cannot be undone.","settings.customModels.cancel":"Cancel","settings.customModels.save":"Save","settings.customModels.close":"Close","settings.customModels.empty":"No custom models yet","settings.customModels.hint":"Stored in ~/.codebuddy/models.json on this machine","settings.customModels.loadFailed":"Failed to load custom models","settings.customModels.saveFailed":"Save failed","settings.customModels.deleteFailed":"Delete failed","settings.customModels.apiKeyKeep":"Leave blank to keep existing key","settings.customModels.field.id":"Model ID","settings.customModels.field.name":"Display name","settings.customModels.field.vendor":"Vendor","settings.customModels.field.url":"Endpoint URL","settings.customModels.field.apiKey":"API Key","settings.customModels.field.maxInputTokens":"Max input tokens","settings.customModels.field.maxOutputTokens":"Max output tokens","settings.customModels.field.temperature":"Temperature","settings.customModels.field.temperatureDefault":"Leave blank for default (omit)","settings.customModels.field.supportsToolCall":"Tool calling","settings.customModels.field.supportsImages":"Images","settings.customModels.field.supportsReasoning":"Reasoning","settings.customModels.field.useCustomProtocol":"Custom protocol (skip /chat/completions suffix)","settings.customModels.err.idRequired":"Model ID is required","settings.customModels.err.idInvalid":"Model ID allows letters, digits, and . _ : - only","settings.customModels.err.idDuplicate":"Model ID already exists","settings.customModels.err.urlRequired":"Endpoint URL is required","settings.customModels.err.urlInvalid":"URL must start with http:// or https://","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.mainAgent":"Agent presets","settings.item.mainAgent.enabled":"Enable agent presets","settings.item.mainAgent.enabled.desc":"Lets Web / CLI pick Standard, PTC, Minimal, or Creator. Off = always native Standard.","settings.item.mainAgent.allowUnopted":"Allow unopted ACP hosts","settings.item.mainAgent.allowUnopted.desc":"Off by default, and only takes effect when the switch above is on. When on, a WorkBuddy sidecar that shares this settings file also uses preset resolution. Leave off unless you need that.","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.autoCompactWindow":"Auto-Compact Window (tokens)","settings.item.autoCompactWindow.desc":"Context window baseline for compaction. Trigger = min(this, model window) × threshold; leave empty to follow the model window. Env CODEBUDDY_AUTO_COMPACT_WINDOW takes precedence","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.reconnecting":"Reconnecting...","terminal.reconnectFailed":"Reconnect failed","terminal.search.placeholder":"Find","terminal.search.noResults":"No results","terminal.search.caseSensitive":"Match Case","terminal.search.wholeWord":"Match Whole Word","terminal.search.regex":"Use Regular Expression","terminal.search.previous":"Previous Match","terminal.search.next":"Next Match","terminal.search.close":"Close","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","scheduled.custom":"Custom","scheduled.every":"Every","scheduled.unit.minutes":"minutes","scheduled.unit.hours":"hours","scheduled.unit.days":"days","scheduled.unit.weeks":"weeks","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.kindAll":"All","plugins.kindSkills":"Skills","plugins.kindMcp":"MCP","plugins.kindHooks":"Hooks","plugins.kindTools":"Tools","plugins.kindUnknown":"Other","plugins.filterStatusAll":"All status","plugins.filterStatusEnabled":"Enabled","plugins.filterStatusDisabled":"Disabled","plugins.infiniteRange":"Showing {visible} / {total}","plugins.infiniteLoading":"Scroll for more","plugins.infiniteEnd":"All loaded","plugins.backToTop":"Back to top","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":"Editor","editor.title":"Code Editor","editor.loading":"Loading...","editor.loadingFile":"Loading file...","editor.loadError":"Failed to load","editor.retryLoad":"Retry loading","editor.fileTooLarge":"This file exceeds 2 MB and cannot be opened in the editor","editor.noFile":"Select a file to start editing","editor.unsaved":"Unsaved","editor.saving":"Saving","editor.saveFailed":"Failed to save","editor.moveFailed":"Failed to move","editor.save":"Save","editor.saveAll":"Save All","editor.close":"Close","editor.closeTabAriaLabel":"Close tab {name}","editor.closeOthers":"Close Others","editor.closeAll":"Close All","editor.newFile":"New File","editor.newFolder":"New Folder","editor.rename":"Rename","editor.delete":"Delete","editor.deleteConfirmTitle":"Confirm Delete","editor.deleteConfirmMessage":"Delete the {count} selected item(s)? This action cannot be undone.","editor.refresh":"Refresh","editor.backToWorkDir":"Back to workspace","editor.emptyFolder":"Empty folder","editor.explorer":"EXPLORER","editor.fileTreeAriaLabel":"Workspace file tree","editor.toggleSidebar":"Toggle Sidebar","editor.collapseAll":"Collapse All","editor.showHiddenFiles":"Show Hidden Files","editor.hideHiddenFiles":"Hide Hidden Files","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.closeSaveFailedTitle":"Unable to Close: {count} Save(s) Failed","editor.closeSaveFailedMessage":"{count} tab(s) failed to save. Discard the changes and close?","editor.discardAndClose":"Discard and Close","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.openEditors":"Open editors","editor.scrollTabsLeft":"Scroll tabs left","editor.scrollTabsRight":"Scroll tabs right","editor.selected":"selected","editor.lines":"lines","editor.preview":"Switch to Preview","editor.source":"Switch to Source","editor.openInNewWindow":"Open in New Window","editor.mobileBack":"Back to file tree","ide.explorer":"Explorer","ide.search":"Search","ide.sourceControl":"Source Control","ide.terminal":"Terminal","ide.newTerminal":"New Terminal","ide.toggleSidebar":"Toggle Sidebar","ide.toggleTerminal":"Toggle Terminal","ide.resizeSidebar":"Resize sidebar","ide.resizeSidePanel":"Resize side panel","ide.resizeBottomPanel":"Resize bottom panel","ide.resizeSplit":"Resize split panes","ide.hidePanel":"Hide Panel","ide.maximizePanel":"Maximize Panel","ide.restorePanel":"Restore Panel Size","ide.listView":"List View","ide.treeView":"Tree View","ide.refresh":"Refresh","ide.scm.title":"Source Control","ide.scm.repositories":"Repositories","ide.scm.changes":"Changes","ide.scm.stagedChanges":"Staged Changes","ide.scm.untracked":"Untracked","ide.scm.noChanges":"No changes","ide.scm.notGitRepo":"Not a Git repository","ide.scm.commitPlaceholder":"Message (⌘Enter to commit)","ide.scm.commit":"Commit","ide.scm.push":"Push","ide.scm.pull":"Pull","ide.scm.stage":"Stage","ide.scm.unstage":"Unstage","ide.scm.stageAll":"Stage All","ide.scm.unstageAll":"Unstage All","ide.scm.discard":"Discard Changes","ide.scm.discardAll":"Discard All","ide.scm.copyPath":"Copy Path","ide.scm.openFile":"Open File","ide.scm.createBranch":"Create new branch...","ide.scm.newBranchPlaceholder":"New branch name...","ide.scm.branchSearchPlaceholder":"Select a branch or tag to checkout","ide.scm.switchBranch":"Switch Branch","ide.scm.localBranches":"branches","ide.scm.remoteBranches":"remotes","ide.scm.noBranchMatch":"No matching branches","ide.scm.graph":"Graph","ide.scm.closeDiff":"Close Diff","ide.scm.loadingDiff":"Loading diff...","ide.scm.diff":"Diff","ide.search.title":"Search","ide.search.placeholder":"Search","ide.search.searching":"Searching...","ide.search.noResults":"No results found","ide.search.results":"{count} results in {files} files","ide.search.matchCase":"Match Case","ide.search.wholeWord":"Match Whole Word","ide.search.regex":"Use Regular Expression","ide.search.filesToInclude":"files to include","ide.search.includePlaceholder":"e.g. *.ts, src/**/include","ide.search.filesToExclude":"files to exclude","ide.search.excludePlaceholder":"e.g. node_modules, *.min.js","ide.search.useExcludeSettings":"Use Exclude Settings and Ignore Files","ide.search.toggleFilters":"Toggle Filters","ide.search.failed":"Search failed","ide.search.timedOut":"Search timed out","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.goal.title":"Goal","command.goal.description":"Set a goal to keep working toward","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.jobCreateFailed":"Failed to create agent, please try again","error.switchSessionFailed":"Failed to switch session, please try again","error.sessionOccupied":"This session is occupied by another terminal or process and cannot be switched to","error.sessionUnavailable":"This session is currently unavailable. Please try again later.","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","tool.mcpAppLoadHint":"Click to load interactive UI","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>
581
581
  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","goal.bar.active":"Active goal {condition} · {elapsed}","goal.bar.paused":"Paused goal {condition} · {elapsed}","goal.bar.edit":"Edit goal","goal.bar.pause":"Pause goal","goal.bar.resume":"Resume goal","goal.bar.clear":"Clear goal","goal.resume.prompt":"Continue the active goal: {condition}","goal.edit.title":"Edit goal","goal.edit.save":"Save","goal.edit.cancel":"Cancel","goal.edit.placeholder":"Describe your goal and define measurable outcomes for best results","mcp.startup.booting":"Booting MCP server: {name}","mcp.startup.starting":"Starting MCP servers ({completed}/{total}): {names}","mcp.startup.elapsed":"{seconds}s","mcp.startup.ready":"MCP servers ready ({total})","mcp.startup.failed":"MCP failed: {names}","mcp.startup.timedOut":"MCP timed out: {names}"}};function _S(e,t){return t?e.replace(/\{(\w+)\}/g,(n,r)=>{const i=t[r];return i==null?n:String(i)}):e}function Re(){const{mode:e,resolved:t,setLocale:n,toggle:r}=uu();function i(a,o){const c=yS[t][a]??a;return _S(c,o)}function s(a,o){const c=yS[t][a];if(c!==void 0)return _S(c,o)}return{t:i,tryT:s,locale:e,resolved:t,setLocale:n,toggleLocale:r}}function k5(){const{tryT:e}=Re();return t=>e(`account.method.${t.id}`)||t.label}function A5(){const{t:e}=Re(),t=k5(),{accountState:n,loginMethods:r,authUrl:i,isSubmitting:s,error:a,accountLogin:o,startAccountPolling:c,clearError:d}=Zr(),[u,h]=g.useState(!1),p=g.useRef(null);g.useEffect(()=>{if(n==="polling")return c()},[n,c]),g.useEffect(()=>{if(n!=="polling")return;const A=()=>{document.visibilityState==="visible"&&Zr.getState().pollAccountStatusOnce()};return document.addEventListener("visibilitychange",A),window.addEventListener("focus",A),()=>{document.removeEventListener("visibilitychange",A),window.removeEventListener("focus",A)}},[n]),g.useEffect(()=>{if(n==="authenticated"){const A=p.current;if(A&&!A.closed)try{A.close()}catch{}p.current=null,window.focus()}},[n]);const m=g.useCallback(A=>{p.current=window.open(A,"_blank")},[]),f=g.useCallback(async A=>{d();const S=await o(A);S&&m(S)},[o,d,m]),b=g.useCallback(()=>{i&&navigator.clipboard.writeText(i).then(()=>{h(!0),setTimeout(()=>h(!1),2e3)})},[i]),_=g.useCallback(()=>{d(),Zr.getState().checkAccountAuth()},[d]),v=a?e(a)!==a?e(a):a:null;return l.jsxs("div",{className:"login-page",children:[l.jsxs("div",{className:"login-orb login-orb-right",children:[l.jsx("div",{className:"login-orb-layer login-orb-layer-1"}),l.jsx("div",{className:"login-orb-layer login-orb-layer-2"})]}),l.jsx("div",{className:"login-ellipse login-ellipse-outer"}),l.jsx("div",{className:"login-ellipse login-ellipse-outer2"}),l.jsx("div",{className:"login-ellipse login-ellipse-inner"}),l.jsxs("div",{className:"login-orb login-orb-left",children:[l.jsx("div",{className:"login-orb-layer login-orb-layer-1"}),l.jsx("div",{className:"login-orb-layer login-orb-layer-2"})]}),l.jsx("div",{className:"login-ellipse login-ellipse-left"}),l.jsx("div",{className:"login-ellipse login-ellipse-left2"}),l.jsxs("div",{className:"login-content",children:[l.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",gap:"16px"},children:[l.jsx("div",{className:"login-logo",children:l.jsx("img",{src:cf,alt:"CodeBuddy"})}),l.jsx("h1",{className:"login-title",children:e("account.login.title")}),n!=="polling"&&l.jsx("p",{className:"login-tagline",children:e("account.login.subtitle")})]}),l.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",gap:"16px",width:"100%",maxWidth:"340px"},children:[v&&l.jsx("div",{className:"login-error",children:v}),n==="polling"&&l.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",gap:"20px",padding:"24px 0"},children:[l.jsx(yt,{size:28,className:"animate-spin",style:{color:"var(--accent-brand, #646cff)"}}),l.jsx("div",{style:{fontSize:"16px",fontWeight:500,color:"var(--text-primary)"},children:e("account.login.polling")}),l.jsx("p",{style:{fontSize:"14px",color:"var(--text-tertiary)",textAlign:"center",lineHeight:1.7,maxWidth:"320px"},children:e("account.login.polling.hint")}),l.jsx("div",{style:{display:"flex",gap:"12px",marginTop:"12px"},children:i&&l.jsxs(l.Fragment,{children:[l.jsx("button",{onClick:()=>m(i),style:{fontSize:"14px",padding:"10px 20px",background:"var(--bg-secondary, rgba(255,255,255,0.06))",border:"1px solid var(--border-primary, rgba(255,255,255,0.12))",borderRadius:"10px",color:"var(--text-primary)",cursor:"pointer",transition:"all 0.2s"},children:e("account.login.openBrowser")}),l.jsx("button",{onClick:b,style:{fontSize:"14px",padding:"10px 20px",background:"var(--bg-secondary, rgba(255,255,255,0.06))",border:"1px solid var(--border-primary, rgba(255,255,255,0.12))",borderRadius:"10px",color:"var(--text-secondary)",cursor:"pointer",transition:"all 0.2s"},children:e(u?"account.login.copied":"account.login.copyUrl")})]})}),l.jsx("button",{onClick:_,style:{fontSize:"13px",padding:"6px 12px",marginTop:"4px",background:"transparent",border:"none",color:"var(--text-tertiary)",cursor:"pointer",textDecoration:"underline",textUnderlineOffset:"3px"},children:e("account.login.retry")})]}),n==="needLogin"&&l.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"12px",width:"100%"},children:[r.length>0?r.map(A=>l.jsx("button",{disabled:s,onClick:()=>f(A.id),style:{width:"100%",padding:"14px 24px",fontSize:"14px",fontWeight:500,display:"flex",alignItems:"center",justifyContent:"center",gap:"10px",background:"var(--bg-secondary, rgba(255,255,255,0.06))",border:"1px solid var(--border-primary, rgba(255,255,255,0.12))",borderRadius:"12px",color:"var(--text-primary)",cursor:s?"not-allowed":"pointer",opacity:s?.6:1,transition:"all 0.2s ease"},onMouseEnter:S=>{s||(S.currentTarget.style.background="var(--bg-hover, rgba(255,255,255,0.1))",S.currentTarget.style.borderColor="var(--accent-brand, #646cff)")},onMouseLeave:S=>{S.currentTarget.style.background="var(--bg-secondary, rgba(255,255,255,0.06))",S.currentTarget.style.borderColor="var(--border-primary, rgba(255,255,255,0.12))"},children:s?l.jsx(yt,{size:16,className:"animate-spin"}):l.jsx("span",{children:t(A)})},A.id)):l.jsx("button",{className:"login-btn",disabled:s,onClick:()=>f(),style:{width:"100%",padding:"14px 24px",fontSize:"14px"},children:s?l.jsx(yt,{size:16,className:"animate-spin"}):e("account.login.button")}),a&&l.jsx("button",{onClick:_,style:{fontSize:"13px",padding:"8px 16px",alignSelf:"center",background:"transparent",border:"none",color:"var(--text-tertiary)",cursor:"pointer",textDecoration:"underline",textUnderlineOffset:"3px"},children:e("account.login.retry")})]}),n==="checking"&&l.jsx("div",{style:{padding:"24px 0",display:"flex",alignItems:"center",justifyContent:"center"},children:l.jsx(yt,{size:24,className:"animate-spin",style:{color:"var(--text-tertiary)"}})})]})]}),l.jsxs("div",{className:"login-footer",children:[l.jsx("a",{href:"#privacy",children:e("login.privacy")}),l.jsx("a",{href:"#terms",children:e("login.terms")})]})]})}const kC="codebuddy-sidebar";function C5(){if(typeof localStorage>"u")return{};try{const e=localStorage.getItem(kC);if(!e)return{};const t=JSON.parse(e);return{...typeof t.isOpen=="boolean"?{isOpen:t.isOpen}:{},...typeof t.sessionsOpen=="boolean"?{sessionsOpen:t.sessionsOpen}:{},...Array.isArray(t.collapsedAgentGroups)?{collapsedAgentGroups:t.collapsedAgentGroups}:{},...Array.isArray(t.expandedAgentGroups)?{expandedAgentGroups:t.expandedAgentGroups}:{}}}catch{return{}}}const Oi=Rt()(Ga((e,t)=>{const n=C5();return{isOpen:n.isOpen??!0,setOpen:r=>e({isOpen:r}),toggle:()=>e({isOpen:!t().isOpen}),sessionsOpen:n.sessionsOpen??!1,setSessionsOpen:r=>e({sessionsOpen:r}),toggleSessionsPanel:()=>e({sessionsOpen:!t().sessionsOpen}),sessionsPanelWidth:280,setSessionsPanelWidth:r=>e({sessionsPanelWidth:Math.min(360,Math.max(240,Math.round(r)))}),collapsedAgentGroups:n.collapsedAgentGroups??[],toggleAgentGroupCollapsed:r=>e(i=>({collapsedAgentGroups:i.collapsedAgentGroups.includes(r)?i.collapsedAgentGroups.filter(a=>a!==r):[...i.collapsedAgentGroups,r]})),expandedAgentGroups:n.expandedAgentGroups??[],toggleAgentGroupExpanded:r=>e(i=>({expandedAgentGroups:i.expandedAgentGroups.includes(r)?i.expandedAgentGroups.filter(a=>a!==r):[...i.expandedAgentGroups,r]}))}},{namespace:"sidebar",fields:["isOpen","sessionsOpen","sessionsPanelWidth","collapsedAgentGroups","expandedAgentGroups"],scope:"workspace",folderScoped:!0,debounceMs:300,localStorageKey:kC})),oa="/api/v1/jobs";class Ju extends Error{constructor(n,r){super(n);we(this,"status");we(this,"code");we(this,"details");this.name="JobsApiError",this.status=r.status,this.code=r.code,this.details=r.details}}function df(e,t){const n=new URLSearchParams;for(const[i,s]of Object.entries(t))s!==void 0&&s!==""&&n.set(i,typeof s=="boolean"?s?"1":"0":String(s));const r=n.toString();return r?`${e}?${r}`:e}function el(e,t=""){return`${oa}/${encodeURIComponent(e)}${t}`}async function AC(e){const t=await e.text();if(t)try{return JSON.parse(t)}catch{return}}function E5(e){return e&&typeof e=="object"?e:{}}function CC(e,t){const n=E5(t).error;return new Ju((n==null?void 0:n.message)||`HTTP ${e.status}`,{status:e.status,code:n==null?void 0:n.code,details:n==null?void 0:n.details})}async function yi(e,t={}){const n=t.body!==void 0,r=await Kt(e,{method:t.method??"GET",headers:Fe({Accept:"application/json",...n?{"Content-Type":"application/json"}:{}}),body:n?JSON.stringify(t.body):void 0},t.retry===!1?{maxRetries:0}:void 0),i=await AC(r);if(!r.ok)throw CC(r,i);if(!i||typeof i!="object"||!("data"in i))throw new Ju(`Unexpected response from ${e}`,{status:r.status,code:"INVALID_RESPONSE"});return i.data}async function I5(e,t,n){var c;const r=await Kt(e,{headers:Fe({Accept:"text/event-stream"}),signal:t});if(!r.ok||!r.body)throw CC(r,await AC(r));const i=r.body.getReader(),s=new TextDecoder;let a="";const o=d=>{let u="message";const h=[];for(const p of d.split(/\r?\n/))p.startsWith("event:")?u=p.slice(6).trim():p.startsWith("data:")&&h.push(p.slice(5).replace(/^ /,""));if(h.length!==0)try{n({event:u,data:JSON.parse(h.join(`
582
582
  `))})}catch{}};for(;!t.aborted;){const{done:d,value:u}=await i.read();if(d){a+=s.decode();break}a+=s.decode(u,{stream:!0});let h=a.search(/\r?\n\r?\n/);for(;h>=0;){const p=((c=a.slice(h).match(/^\r?\n\r?\n/))==null?void 0:c[0])??`
@@ -606,7 +606,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
606
606
  monaco.config({ paths: { vs: '...' } })
607
607
 
608
608
  For more please check the link https://github.com/suren-atoyan/monaco-loader#config
609
- `},ZS=GP(QP)(fE),KP={config:qP},YP=function(){for(var t=arguments.length,n=new Array(t),r=0;r<t;r++)n[r]=arguments[r];return function(i){return n.reduceRight(function(s,a){return a(s)},i)}};function bE(e,t){return Object.keys(t).forEach(function(n){t[n]instanceof Object&&e[n]&&Object.assign(t[n],bE(e[n],t[n]))}),QS(QS({},e),t)}var ZP={type:"cancelation",msg:"operation is manually canceled"};function Vh(e){var t=!1,n=new Promise(function(r,i){e.then(function(s){return t?i(ZP):r(s)}),e.catch(i)});return n.cancel=function(){return t=!0},n}var JP=["monaco"],XP=zP.create({config:HP,isInitialized:!1,resolve:null,reject:null,monaco:null}),yE=kP(XP,2),$c=yE[0],hh=yE[1];function eB(e){var t=KP.config(e),n=t.monaco,r=wP(t,JP);hh(function(i){return{config:bE(i.config,r),monaco:n}})}function tB(){var e=$c(function(t){var n=t.monaco,r=t.isInitialized,i=t.resolve;return{monaco:n,isInitialized:r,resolve:i}});if(!e.isInitialized){if(hh({isInitialized:!0}),e.monaco)return e.resolve(e.monaco),Vh(Qh);if(window.monaco&&window.monaco.editor)return _E(window.monaco),e.resolve(window.monaco),Vh(Qh);YP(nB,iB)(sB)}return Vh(Qh)}function nB(e){return document.body.appendChild(e)}function rB(e){var t=document.createElement("script");return e&&(t.src=e),t}function iB(e){var t=$c(function(r){var i=r.config,s=r.reject;return{config:i,reject:s}}),n=rB("".concat(t.config.paths.vs,"/loader.js"));return n.onload=function(){return e()},n.onerror=t.reject,n}function sB(){var e=$c(function(n){var r=n.config,i=n.resolve,s=n.reject;return{config:r,resolve:i,reject:s}}),t=window.require;t.config(e.config),t(["vs/editor/editor.main"],function(n){var r=n.m||n;_E(r),e.resolve(r)},function(n){e.reject(n)})}function _E(e){$c().monaco||hh({monaco:e})}function aB(){return $c(function(e){var t=e.monaco;return t})}var Qh=new Promise(function(e,t){return hh({resolve:e,reject:t})}),bx={config:eB,init:tB,__getMonacoInstance:aB},oB={wrapper:{display:"flex",position:"relative",textAlign:"initial"},fullWidth:{width:"100%"},hide:{display:"none"}},Kh=oB,lB={container:{display:"flex",height:"100%",width:"100%",justifyContent:"center",alignItems:"center"}},cB=lB;function dB({children:e}){return Wn.createElement("div",{style:cB.container},e)}var uB=dB,hB=uB;function pB({width:e,height:t,isEditorReady:n,loading:r,_ref:i,className:s,wrapperProps:a}){return Wn.createElement("section",{style:{...Kh.wrapper,width:e,height:t},...a},!n&&Wn.createElement(hB,null,r),Wn.createElement("div",{ref:i,style:{...Kh.fullWidth,...!n&&Kh.hide},className:s}))}var mB=pB,vE=g.memo(mB);function gB(e){g.useEffect(e,[])}var xE=gB;function fB(e,t,n=!0){let r=g.useRef(!0);g.useEffect(r.current||!n?()=>{r.current=!1}:e,t)}var Yr=fB;function ec(){}function uo(e,t,n,r){return bB(e,r)||yB(e,t,n,r)}function bB(e,t){return e.editor.getModel(wE(e,t))}function yB(e,t,n,r){return e.editor.createModel(t,n,r?wE(e,r):void 0)}function wE(e,t){return e.Uri.parse(t)}function _B({original:e,modified:t,language:n,originalLanguage:r,modifiedLanguage:i,originalModelPath:s,modifiedModelPath:a,keepCurrentOriginalModel:o=!1,keepCurrentModifiedModel:c=!1,theme:d="light",loading:u="Loading...",options:h={},height:p="100%",width:m="100%",className:f,wrapperProps:b={},beforeMount:_=ec,onMount:v=ec}){let[A,S]=g.useState(!1),[y,x]=g.useState(!0),k=g.useRef(null),C=g.useRef(null),E=g.useRef(null),N=g.useRef(v),z=g.useRef(_),Q=g.useRef(!1);xE(()=>{let I=bx.init();return I.then(R=>(C.current=R)&&x(!1)).catch(R=>(R==null?void 0:R.type)!=="cancelation"&&console.error("Monaco initialization: error:",R)),()=>k.current?L():I.cancel()}),Yr(()=>{if(k.current&&C.current){let I=k.current.getOriginalEditor(),R=uo(C.current,e||"",r||n||"text",s||"");R!==I.getModel()&&I.setModel(R)}},[s],A),Yr(()=>{if(k.current&&C.current){let I=k.current.getModifiedEditor(),R=uo(C.current,t||"",i||n||"text",a||"");R!==I.getModel()&&I.setModel(R)}},[a],A),Yr(()=>{let I=k.current.getModifiedEditor();I.getOption(C.current.editor.EditorOption.readOnly)?I.setValue(t||""):t!==I.getValue()&&(I.executeEdits("",[{range:I.getModel().getFullModelRange(),text:t||"",forceMoveMarkers:!0}]),I.pushUndoStop())},[t],A),Yr(()=>{var I,R;(R=(I=k.current)==null?void 0:I.getModel())==null||R.original.setValue(e||"")},[e],A),Yr(()=>{let{original:I,modified:R}=k.current.getModel();C.current.editor.setModelLanguage(I,r||n||"text"),C.current.editor.setModelLanguage(R,i||n||"text")},[n,r,i],A),Yr(()=>{var I;(I=C.current)==null||I.editor.setTheme(d)},[d],A),Yr(()=>{var I;(I=k.current)==null||I.updateOptions(h)},[h],A);let T=g.useCallback(()=>{var $;if(!C.current)return;z.current(C.current);let I=uo(C.current,e||"",r||n||"text",s||""),R=uo(C.current,t||"",i||n||"text",a||"");($=k.current)==null||$.setModel({original:I,modified:R})},[n,t,i,e,r,s,a]),w=g.useCallback(()=>{var I;!Q.current&&E.current&&(k.current=C.current.editor.createDiffEditor(E.current,{automaticLayout:!0,...h}),T(),(I=C.current)==null||I.editor.setTheme(d),S(!0),Q.current=!0)},[h,d,T]);g.useEffect(()=>{A&&N.current(k.current,C.current)},[A]),g.useEffect(()=>{!y&&!A&&w()},[y,A,w]);function L(){var R,$,D,U;let I=(R=k.current)==null?void 0:R.getModel();o||(($=I==null?void 0:I.original)==null||$.dispose()),c||((D=I==null?void 0:I.modified)==null||D.dispose()),(U=k.current)==null||U.dispose()}return Wn.createElement(vE,{width:m,height:p,isEditorReady:A,loading:u,_ref:E,className:f,wrapperProps:b})}var vB=_B,xB=g.memo(vB);function wB(e){let t=g.useRef();return g.useEffect(()=>{t.current=e},[e]),t.current}var SB=wB,ud=new Map;function kB({defaultValue:e,defaultLanguage:t,defaultPath:n,value:r,language:i,path:s,theme:a="light",line:o,loading:c="Loading...",options:d={},overrideServices:u={},saveViewState:h=!0,keepCurrentModel:p=!1,width:m="100%",height:f="100%",className:b,wrapperProps:_={},beforeMount:v=ec,onMount:A=ec,onChange:S,onValidate:y=ec}){let[x,k]=g.useState(!1),[C,E]=g.useState(!0),N=g.useRef(null),z=g.useRef(null),Q=g.useRef(null),T=g.useRef(A),w=g.useRef(v),L=g.useRef(),I=g.useRef(r),R=SB(s),$=g.useRef(!1),D=g.useRef(!1);xE(()=>{let ee=bx.init();return ee.then(P=>(N.current=P)&&E(!1)).catch(P=>(P==null?void 0:P.type)!=="cancelation"&&console.error("Monaco initialization: error:",P)),()=>z.current?Y():ee.cancel()}),Yr(()=>{var P,q,ue,_e;let ee=uo(N.current,e||r||"",t||i||"",s||n||"");ee!==((P=z.current)==null?void 0:P.getModel())&&(h&&ud.set(R,(q=z.current)==null?void 0:q.saveViewState()),(ue=z.current)==null||ue.setModel(ee),h&&((_e=z.current)==null||_e.restoreViewState(ud.get(s))))},[s],x),Yr(()=>{var ee;(ee=z.current)==null||ee.updateOptions(d)},[d],x),Yr(()=>{!z.current||r===void 0||(z.current.getOption(N.current.editor.EditorOption.readOnly)?z.current.setValue(r):r!==z.current.getValue()&&(D.current=!0,z.current.executeEdits("",[{range:z.current.getModel().getFullModelRange(),text:r,forceMoveMarkers:!0}]),z.current.pushUndoStop(),D.current=!1))},[r],x),Yr(()=>{var P,q;let ee=(P=z.current)==null?void 0:P.getModel();ee&&i&&((q=N.current)==null||q.editor.setModelLanguage(ee,i))},[i],x),Yr(()=>{var ee;o!==void 0&&((ee=z.current)==null||ee.revealLine(o))},[o],x),Yr(()=>{var ee;(ee=N.current)==null||ee.editor.setTheme(a)},[a],x);let U=g.useCallback(()=>{var ee;if(!(!Q.current||!N.current)&&!$.current){w.current(N.current);let P=s||n,q=uo(N.current,r||e||"",t||i||"",P||"");z.current=(ee=N.current)==null?void 0:ee.editor.create(Q.current,{model:q,automaticLayout:!0,...d},u),h&&z.current.restoreViewState(ud.get(P)),N.current.editor.setTheme(a),o!==void 0&&z.current.revealLine(o),k(!0),$.current=!0}},[e,t,n,r,i,s,d,u,h,a,o]);g.useEffect(()=>{x&&T.current(z.current,N.current)},[x]),g.useEffect(()=>{!C&&!x&&U()},[C,x,U]),I.current=r,g.useEffect(()=>{var ee,P;x&&S&&((ee=L.current)==null||ee.dispose(),L.current=(P=z.current)==null?void 0:P.onDidChangeModelContent(q=>{D.current||S(z.current.getValue(),q)}))},[x,S]),g.useEffect(()=>{if(x){let ee=N.current.editor.onDidChangeMarkers(P=>{var ue;let q=(ue=z.current.getModel())==null?void 0:ue.uri;if(q&&P.find(_e=>_e.path===q.path)){let _e=N.current.editor.getModelMarkers({resource:q});y==null||y(_e)}});return()=>{ee==null||ee.dispose()}}return()=>{}},[x,y]);function Y(){var ee,P;(ee=L.current)==null||ee.dispose(),p?h&&ud.set(s,z.current.saveViewState()):(P=z.current.getModel())==null||P.dispose(),z.current.dispose()}return Wn.createElement(vE,{width:m,height:f,isEditorReady:x,loading:c,_ref:Q,className:b,wrapperProps:_})}var AB=kB,CB=g.memo(AB),kX=CB;let Yh=null;function EB(){return Yh||(Yh=(async()=>{const[e,{default:t},{default:n},{default:r},{default:i},{default:s}]=await Promise.all([Ct(()=>import("./editor.main-BuKvQHbu.js").then(a=>a.b),__vite__mapDeps([0,1])),Ct(()=>import("./editor.worker-B3KqdXMd.js"),[]),Ct(()=>import("./css.worker-DcdNs0h7.js"),[]),Ct(()=>import("./html.worker-yNrQJy_v.js"),[]),Ct(()=>import("./json.worker-BuQktY-_.js"),[]),Ct(()=>import("./ts.worker-CRrITQ3A.js"),[])]);self.MonacoEnvironment={getWorker(a,o){switch(o){case"json":return new i;case"css":case"scss":case"less":return new n;case"html":case"handlebars":case"razor":return new r;case"typescript":case"javascript":return new s;default:return new t}}},bx.config({monaco:e})})()),Yh}const IB={fontSize:13,fontFamily:"'Menlo', 'Monaco', 'Consolas', 'Courier New', monospace",lineHeight:20,minimap:{enabled:!1},scrollBeyondLastLine:!1,automaticLayout:!0,wordWrap:"off",tabSize:4,insertSpaces:!0,renderWhitespace:"selection",padding:{top:0,bottom:0},smoothScrolling:!0,fixedOverflowWidgets:!0,readOnly:!0,renderSideBySide:!1,ignoreTrimWhitespace:!1,enableSplitViewResizing:!0,originalEditable:!1};function Co({path:e,oldText:t,newText:n,maxHeight:r="100%"}){const{t:i}=Re(),{resolved:s}=Xi(),a=g.useRef(null),o=s==="dark"?"vs-dark":"vs",c=TB(e),[d,u]=g.useState(!1);g.useEffect(()=>{let m=!1;return EB().then(()=>{m||u(!0)}),()=>{m=!0}},[]);const h=g.useCallback(m=>{a.current=m;const f=()=>{const b=m.getLineChanges();if(b&&b.length>0){const _=b[0].modifiedStartLineNumber||b[0].originalStartLineNumber||1,v=m.getModifiedEditor();return v&&(v.revealLineInCenter(_),v.setPosition({lineNumber:_,column:1})),!0}return!1};if(!f()){let b=0;const _=setInterval(()=>{b++,(f()||b>=20)&&clearInterval(_)},100)}},[]),p=l.jsxs("div",{className:"flex items-center justify-center h-full gap-2",style:{color:"var(--color-text-tertiary)"},children:[l.jsx(yt,{size:16,className:"animate-spin"}),l.jsx("span",{style:{fontSize:13},children:i("editor.loading")})]});return d?l.jsx("div",{style:{height:r},className:"overflow-hidden",children:l.jsx(xB,{original:t??"",modified:n,language:c,theme:o,height:"100%",onMount:h,loading:p,options:IB})}):l.jsx("div",{style:{height:r},className:"overflow-hidden",children:p})}function TB(e){var r;const t=((r=e.split(".").pop())==null?void 0:r.toLowerCase())||"";return{ts:"typescript",tsx:"typescript",js:"javascript",jsx:"javascript",py:"python",go:"go",java:"java",rs:"rust",rb:"ruby",php:"php",cpp:"cpp",c:"c",cs:"csharp",swift:"swift",kt:"kotlin",scala:"scala",sh:"shell",bash:"shell",zsh:"shell",json:"json",xml:"xml",html:"html",css:"css",scss:"scss",less:"less",yaml:"yaml",yml:"yaml",md:"markdown",sql:"sql",dockerfile:"dockerfile"}[t]||"text"}const NB="Dynamic workflows can use a lot of tokens quickly by running many subagents in parallel — which counts against your usage limit. Stop a running workflow at any time with /workflows, or disable dynamic workflows in /config.";function RB({phases:e,script:t}){const[n,r]=g.useState(!1),i=g.useMemo(()=>t?t.split(`
609
+ `},ZS=GP(QP)(fE),KP={config:qP},YP=function(){for(var t=arguments.length,n=new Array(t),r=0;r<t;r++)n[r]=arguments[r];return function(i){return n.reduceRight(function(s,a){return a(s)},i)}};function bE(e,t){return Object.keys(t).forEach(function(n){t[n]instanceof Object&&e[n]&&Object.assign(t[n],bE(e[n],t[n]))}),QS(QS({},e),t)}var ZP={type:"cancelation",msg:"operation is manually canceled"};function Vh(e){var t=!1,n=new Promise(function(r,i){e.then(function(s){return t?i(ZP):r(s)}),e.catch(i)});return n.cancel=function(){return t=!0},n}var JP=["monaco"],XP=zP.create({config:HP,isInitialized:!1,resolve:null,reject:null,monaco:null}),yE=kP(XP,2),$c=yE[0],hh=yE[1];function eB(e){var t=KP.config(e),n=t.monaco,r=wP(t,JP);hh(function(i){return{config:bE(i.config,r),monaco:n}})}function tB(){var e=$c(function(t){var n=t.monaco,r=t.isInitialized,i=t.resolve;return{monaco:n,isInitialized:r,resolve:i}});if(!e.isInitialized){if(hh({isInitialized:!0}),e.monaco)return e.resolve(e.monaco),Vh(Qh);if(window.monaco&&window.monaco.editor)return _E(window.monaco),e.resolve(window.monaco),Vh(Qh);YP(nB,iB)(sB)}return Vh(Qh)}function nB(e){return document.body.appendChild(e)}function rB(e){var t=document.createElement("script");return e&&(t.src=e),t}function iB(e){var t=$c(function(r){var i=r.config,s=r.reject;return{config:i,reject:s}}),n=rB("".concat(t.config.paths.vs,"/loader.js"));return n.onload=function(){return e()},n.onerror=t.reject,n}function sB(){var e=$c(function(n){var r=n.config,i=n.resolve,s=n.reject;return{config:r,resolve:i,reject:s}}),t=window.require;t.config(e.config),t(["vs/editor/editor.main"],function(n){var r=n.m||n;_E(r),e.resolve(r)},function(n){e.reject(n)})}function _E(e){$c().monaco||hh({monaco:e})}function aB(){return $c(function(e){var t=e.monaco;return t})}var Qh=new Promise(function(e,t){return hh({resolve:e,reject:t})}),bx={config:eB,init:tB,__getMonacoInstance:aB},oB={wrapper:{display:"flex",position:"relative",textAlign:"initial"},fullWidth:{width:"100%"},hide:{display:"none"}},Kh=oB,lB={container:{display:"flex",height:"100%",width:"100%",justifyContent:"center",alignItems:"center"}},cB=lB;function dB({children:e}){return Wn.createElement("div",{style:cB.container},e)}var uB=dB,hB=uB;function pB({width:e,height:t,isEditorReady:n,loading:r,_ref:i,className:s,wrapperProps:a}){return Wn.createElement("section",{style:{...Kh.wrapper,width:e,height:t},...a},!n&&Wn.createElement(hB,null,r),Wn.createElement("div",{ref:i,style:{...Kh.fullWidth,...!n&&Kh.hide},className:s}))}var mB=pB,vE=g.memo(mB);function gB(e){g.useEffect(e,[])}var xE=gB;function fB(e,t,n=!0){let r=g.useRef(!0);g.useEffect(r.current||!n?()=>{r.current=!1}:e,t)}var Yr=fB;function ec(){}function uo(e,t,n,r){return bB(e,r)||yB(e,t,n,r)}function bB(e,t){return e.editor.getModel(wE(e,t))}function yB(e,t,n,r){return e.editor.createModel(t,n,r?wE(e,r):void 0)}function wE(e,t){return e.Uri.parse(t)}function _B({original:e,modified:t,language:n,originalLanguage:r,modifiedLanguage:i,originalModelPath:s,modifiedModelPath:a,keepCurrentOriginalModel:o=!1,keepCurrentModifiedModel:c=!1,theme:d="light",loading:u="Loading...",options:h={},height:p="100%",width:m="100%",className:f,wrapperProps:b={},beforeMount:_=ec,onMount:v=ec}){let[A,S]=g.useState(!1),[y,x]=g.useState(!0),k=g.useRef(null),C=g.useRef(null),E=g.useRef(null),N=g.useRef(v),z=g.useRef(_),Q=g.useRef(!1);xE(()=>{let I=bx.init();return I.then(R=>(C.current=R)&&x(!1)).catch(R=>(R==null?void 0:R.type)!=="cancelation"&&console.error("Monaco initialization: error:",R)),()=>k.current?L():I.cancel()}),Yr(()=>{if(k.current&&C.current){let I=k.current.getOriginalEditor(),R=uo(C.current,e||"",r||n||"text",s||"");R!==I.getModel()&&I.setModel(R)}},[s],A),Yr(()=>{if(k.current&&C.current){let I=k.current.getModifiedEditor(),R=uo(C.current,t||"",i||n||"text",a||"");R!==I.getModel()&&I.setModel(R)}},[a],A),Yr(()=>{let I=k.current.getModifiedEditor();I.getOption(C.current.editor.EditorOption.readOnly)?I.setValue(t||""):t!==I.getValue()&&(I.executeEdits("",[{range:I.getModel().getFullModelRange(),text:t||"",forceMoveMarkers:!0}]),I.pushUndoStop())},[t],A),Yr(()=>{var I,R;(R=(I=k.current)==null?void 0:I.getModel())==null||R.original.setValue(e||"")},[e],A),Yr(()=>{let{original:I,modified:R}=k.current.getModel();C.current.editor.setModelLanguage(I,r||n||"text"),C.current.editor.setModelLanguage(R,i||n||"text")},[n,r,i],A),Yr(()=>{var I;(I=C.current)==null||I.editor.setTheme(d)},[d],A),Yr(()=>{var I;(I=k.current)==null||I.updateOptions(h)},[h],A);let T=g.useCallback(()=>{var $;if(!C.current)return;z.current(C.current);let I=uo(C.current,e||"",r||n||"text",s||""),R=uo(C.current,t||"",i||n||"text",a||"");($=k.current)==null||$.setModel({original:I,modified:R})},[n,t,i,e,r,s,a]),w=g.useCallback(()=>{var I;!Q.current&&E.current&&(k.current=C.current.editor.createDiffEditor(E.current,{automaticLayout:!0,...h}),T(),(I=C.current)==null||I.editor.setTheme(d),S(!0),Q.current=!0)},[h,d,T]);g.useEffect(()=>{A&&N.current(k.current,C.current)},[A]),g.useEffect(()=>{!y&&!A&&w()},[y,A,w]);function L(){var R,$,D,U;let I=(R=k.current)==null?void 0:R.getModel();o||(($=I==null?void 0:I.original)==null||$.dispose()),c||((D=I==null?void 0:I.modified)==null||D.dispose()),(U=k.current)==null||U.dispose()}return Wn.createElement(vE,{width:m,height:p,isEditorReady:A,loading:u,_ref:E,className:f,wrapperProps:b})}var vB=_B,xB=g.memo(vB);function wB(e){let t=g.useRef();return g.useEffect(()=>{t.current=e},[e]),t.current}var SB=wB,ud=new Map;function kB({defaultValue:e,defaultLanguage:t,defaultPath:n,value:r,language:i,path:s,theme:a="light",line:o,loading:c="Loading...",options:d={},overrideServices:u={},saveViewState:h=!0,keepCurrentModel:p=!1,width:m="100%",height:f="100%",className:b,wrapperProps:_={},beforeMount:v=ec,onMount:A=ec,onChange:S,onValidate:y=ec}){let[x,k]=g.useState(!1),[C,E]=g.useState(!0),N=g.useRef(null),z=g.useRef(null),Q=g.useRef(null),T=g.useRef(A),w=g.useRef(v),L=g.useRef(),I=g.useRef(r),R=SB(s),$=g.useRef(!1),D=g.useRef(!1);xE(()=>{let ee=bx.init();return ee.then(P=>(N.current=P)&&E(!1)).catch(P=>(P==null?void 0:P.type)!=="cancelation"&&console.error("Monaco initialization: error:",P)),()=>z.current?Y():ee.cancel()}),Yr(()=>{var P,q,ue,_e;let ee=uo(N.current,e||r||"",t||i||"",s||n||"");ee!==((P=z.current)==null?void 0:P.getModel())&&(h&&ud.set(R,(q=z.current)==null?void 0:q.saveViewState()),(ue=z.current)==null||ue.setModel(ee),h&&((_e=z.current)==null||_e.restoreViewState(ud.get(s))))},[s],x),Yr(()=>{var ee;(ee=z.current)==null||ee.updateOptions(d)},[d],x),Yr(()=>{!z.current||r===void 0||(z.current.getOption(N.current.editor.EditorOption.readOnly)?z.current.setValue(r):r!==z.current.getValue()&&(D.current=!0,z.current.executeEdits("",[{range:z.current.getModel().getFullModelRange(),text:r,forceMoveMarkers:!0}]),z.current.pushUndoStop(),D.current=!1))},[r],x),Yr(()=>{var P,q;let ee=(P=z.current)==null?void 0:P.getModel();ee&&i&&((q=N.current)==null||q.editor.setModelLanguage(ee,i))},[i],x),Yr(()=>{var ee;o!==void 0&&((ee=z.current)==null||ee.revealLine(o))},[o],x),Yr(()=>{var ee;(ee=N.current)==null||ee.editor.setTheme(a)},[a],x);let U=g.useCallback(()=>{var ee;if(!(!Q.current||!N.current)&&!$.current){w.current(N.current);let P=s||n,q=uo(N.current,r||e||"",t||i||"",P||"");z.current=(ee=N.current)==null?void 0:ee.editor.create(Q.current,{model:q,automaticLayout:!0,...d},u),h&&z.current.restoreViewState(ud.get(P)),N.current.editor.setTheme(a),o!==void 0&&z.current.revealLine(o),k(!0),$.current=!0}},[e,t,n,r,i,s,d,u,h,a,o]);g.useEffect(()=>{x&&T.current(z.current,N.current)},[x]),g.useEffect(()=>{!C&&!x&&U()},[C,x,U]),I.current=r,g.useEffect(()=>{var ee,P;x&&S&&((ee=L.current)==null||ee.dispose(),L.current=(P=z.current)==null?void 0:P.onDidChangeModelContent(q=>{D.current||S(z.current.getValue(),q)}))},[x,S]),g.useEffect(()=>{if(x){let ee=N.current.editor.onDidChangeMarkers(P=>{var ue;let q=(ue=z.current.getModel())==null?void 0:ue.uri;if(q&&P.find(_e=>_e.path===q.path)){let _e=N.current.editor.getModelMarkers({resource:q});y==null||y(_e)}});return()=>{ee==null||ee.dispose()}}return()=>{}},[x,y]);function Y(){var ee,P;(ee=L.current)==null||ee.dispose(),p?h&&ud.set(s,z.current.saveViewState()):(P=z.current.getModel())==null||P.dispose(),z.current.dispose()}return Wn.createElement(vE,{width:m,height:f,isEditorReady:x,loading:c,_ref:Q,className:b,wrapperProps:_})}var AB=kB,CB=g.memo(AB),kX=CB;let Yh=null;function EB(){return Yh||(Yh=(async()=>{const[e,{default:t},{default:n},{default:r},{default:i},{default:s}]=await Promise.all([Ct(()=>import("./editor.main-ClnGNr0F.js").then(a=>a.b),__vite__mapDeps([0,1])),Ct(()=>import("./editor.worker-B3KqdXMd.js"),[]),Ct(()=>import("./css.worker-DcdNs0h7.js"),[]),Ct(()=>import("./html.worker-yNrQJy_v.js"),[]),Ct(()=>import("./json.worker-BuQktY-_.js"),[]),Ct(()=>import("./ts.worker-CRrITQ3A.js"),[])]);self.MonacoEnvironment={getWorker(a,o){switch(o){case"json":return new i;case"css":case"scss":case"less":return new n;case"html":case"handlebars":case"razor":return new r;case"typescript":case"javascript":return new s;default:return new t}}},bx.config({monaco:e})})()),Yh}const IB={fontSize:13,fontFamily:"'Menlo', 'Monaco', 'Consolas', 'Courier New', monospace",lineHeight:20,minimap:{enabled:!1},scrollBeyondLastLine:!1,automaticLayout:!0,wordWrap:"off",tabSize:4,insertSpaces:!0,renderWhitespace:"selection",padding:{top:0,bottom:0},smoothScrolling:!0,fixedOverflowWidgets:!0,readOnly:!0,renderSideBySide:!1,ignoreTrimWhitespace:!1,enableSplitViewResizing:!0,originalEditable:!1};function Co({path:e,oldText:t,newText:n,maxHeight:r="100%"}){const{t:i}=Re(),{resolved:s}=Xi(),a=g.useRef(null),o=s==="dark"?"vs-dark":"vs",c=TB(e),[d,u]=g.useState(!1);g.useEffect(()=>{let m=!1;return EB().then(()=>{m||u(!0)}),()=>{m=!0}},[]);const h=g.useCallback(m=>{a.current=m;const f=()=>{const b=m.getLineChanges();if(b&&b.length>0){const _=b[0].modifiedStartLineNumber||b[0].originalStartLineNumber||1,v=m.getModifiedEditor();return v&&(v.revealLineInCenter(_),v.setPosition({lineNumber:_,column:1})),!0}return!1};if(!f()){let b=0;const _=setInterval(()=>{b++,(f()||b>=20)&&clearInterval(_)},100)}},[]),p=l.jsxs("div",{className:"flex items-center justify-center h-full gap-2",style:{color:"var(--color-text-tertiary)"},children:[l.jsx(yt,{size:16,className:"animate-spin"}),l.jsx("span",{style:{fontSize:13},children:i("editor.loading")})]});return d?l.jsx("div",{style:{height:r},className:"overflow-hidden",children:l.jsx(xB,{original:t??"",modified:n,language:c,theme:o,height:"100%",onMount:h,loading:p,options:IB})}):l.jsx("div",{style:{height:r},className:"overflow-hidden",children:p})}function TB(e){var r;const t=((r=e.split(".").pop())==null?void 0:r.toLowerCase())||"";return{ts:"typescript",tsx:"typescript",js:"javascript",jsx:"javascript",py:"python",go:"go",java:"java",rs:"rust",rb:"ruby",php:"php",cpp:"cpp",c:"c",cs:"csharp",swift:"swift",kt:"kotlin",scala:"scala",sh:"shell",bash:"shell",zsh:"shell",json:"json",xml:"xml",html:"html",css:"css",scss:"scss",less:"less",yaml:"yaml",yml:"yaml",md:"markdown",sql:"sql",dockerfile:"dockerfile"}[t]||"text"}const NB="Dynamic workflows can use a lot of tokens quickly by running many subagents in parallel — which counts against your usage limit. Stop a running workflow at any time with /workflows, or disable dynamic workflows in /config.";function RB({phases:e,script:t}){const[n,r]=g.useState(!1),i=g.useMemo(()=>t?t.split(`
610
610
  `).length:0,[t]);return l.jsxs("div",{className:"space-y-2.5",children:[e&&e.length>0&&l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"text-xs text-text-secondary",children:"This dynamic workflow will spin up multiple subagents across the following phases:"}),l.jsx("ol",{className:"text-xs space-y-0.5 pl-5 list-decimal text-text-secondary",children:e.map((s,a)=>l.jsxs("li",{children:[l.jsx("span",{className:"text-text-primary font-medium",children:s.title}),s.detail&&l.jsxs("span",{className:"text-text-tertiary",children:[" — ",s.detail]})]},a))})]}),l.jsx("div",{className:"text-[11px] leading-relaxed text-accent-yellow",children:NB}),t&&l.jsxs("div",{className:"space-y-1.5",children:[l.jsxs("button",{type:"button",onClick:()=>r(s=>!s),className:`inline-flex items-center gap-1 text-[11px] text-text-secondary
611
611
  hover:text-text-primary transition-colors`,children:[l.jsx(Or,{size:12,className:`transition-transform ${n?"rotate-90":""}`}),l.jsxs("span",{children:[n?"Hide raw script":"View raw script"," (",i," lines)"]})]}),n&&l.jsx("pre",{className:`rounded-lg bg-bg-secondary/50 px-3.5 py-2.5
612
612
  font-mono text-[11px] text-text-secondary
@@ -941,4 +941,4 @@ ${n}`:n}async function tJ(e){if(e.size>ww)return null;if(DN(e)&&e.size<=LN){cons
941
941
  `+f.slice(Me);b(xt),S(null),requestAnimationFrame(()=>{O.selectionStart=O.selectionEnd=ge+1,O.focus()})},[f]),uR=g.useCallback(()=>{S(null),dr()},[dr]);g.useEffect(()=>{if(!A)return;const O=Me=>{const xt=C.current;(!xt||!Me.composedPath().includes(xt))&&S(null)},ge=()=>S(null);return document.addEventListener("pointerdown",O,!0),document.addEventListener("scroll",ge,!0),()=>{document.removeEventListener("pointerdown",O,!0),document.removeEventListener("scroll",ge,!0)}},[A]),g.useEffect(()=>{if(!s)return;const O=ge=>{const Me=ge.composedPath();(!E.current||!Me.includes(E.current))&&(!N.current||!Me.includes(N.current))&&h(!1)};return document.addEventListener("pointerdown",O,!0),()=>document.removeEventListener("pointerdown",O,!0)},[s,h]),g.useEffect(()=>{if(!Le&&!je&&!ct)return;const O=[z,Q],ge=xt=>{const bt=xt.composedPath();for(const Fr of O)if(Fr.current&&bt.includes(Fr.current))return;We(!1),et(!1),gt(null)},Me=xt=>{xt.key==="Escape"&&(We(!1),et(!1),gt(null))};return document.addEventListener("pointerdown",ge,!0),document.addEventListener("keydown",Me),()=>{document.removeEventListener("pointerdown",ge,!0),document.removeEventListener("keydown",Me)}},[Le,je,ct]);const hR=g.useCallback(O=>{if(mn){if(O.key==="ArrowUp"){O.preventDefault(),ls(Me=>Me>0?Me-1:ut.length-1);return}if(O.key==="ArrowDown"){O.preventDefault(),ls(Me=>Me<ut.length-1?Me+1:0);return}if(O.key==="Tab"||O.key==="Enter"&&!O.shiftKey&&!w.current&&!O.nativeEvent.isComposing){O.preventDefault(),Th(ut[ri]);return}if(O.key==="Escape"){O.preventDefault(),b("");return}}if(ye){if(O.key==="ArrowUp"){O.preventDefault(),wn(Me=>Me>0?Me-1:$e.length-1);return}if(O.key==="ArrowDown"){O.preventDefault(),wn(Me=>Me<$e.length-1?Me+1:0);return}if(O.key==="Tab"||O.key==="Enter"&&!O.shiftKey&&!w.current&&!O.nativeEvent.isComposing){O.preventDefault(),Oe($e[kt]);return}if(O.key==="Escape"){O.preventDefault(),ni(null),Z([]);return}}if(O.key==="Escape"&&Tn){O.preventDefault(),pn(!1);return}if(O.key==="Tab"&&!mn&&!ye&&oe&&!f){O.preventDefault(),b(oe),J(null);return}const ge=w.current||O.nativeEvent.isComposing;if(!q&&!ge&&(O.key==="ArrowUp"||O.key==="ArrowDown")){const Me=ee.current,xt=O.key==="ArrowUp"&&CH(f,O.currentTarget.selectionStart??f.length,O.currentTarget.selectionEnd??f.length);if(Me.index!==null||xt){const bt=EH(Br,f,Me,O.key==="ArrowUp"?"up":"down");if(bt.handled){O.preventDefault(),ee.current=bt.cursor,b(bt.value),requestAnimationFrame(()=>{const Fr=y.current;Fr&&(Fr.selectionStart=Fr.selectionEnd=bt.value.length)});return}}}if(O.key==="Enter"&&!O.shiftKey&&!w.current&&!O.nativeEvent.isComposing){if(O.preventDefault(),!f&&oe&&!qe&&!wt){dr(oe);return}dr()}},[dr,q,mn,ut,ri,Th,ls,ye,$e,kt,Oe,wn,ni,Z,oe,f,J,qe,wt,Br,Tn]),pR=g.useCallback(async()=>{if(!P)return;const O=!ke;H(O);try{await st().setConfigOption(P,"thought_level",O?"enabled":"disabled")}catch(ge){H(!O),console.error("Toggle thinking failed:",ge)}},[P,ke,H]),Cw=g.useCallback(async O=>{if(!P||!G||O===G.currentValue)return;const ge=G,Me=ke;V({...G,currentValue:O}),H(O!=="disabled");try{await st().setConfigOption(P,"thought_level",O),O!=="enabled"&&O!=="disabled"&&ae&&hH(ae,O).catch(xt=>{console.warn("Persist defaultEffort failed:",xt)})}catch(xt){V(ge),H(Me),console.error("Set thought_level failed:",xt)}},[P,G,ke,V,H,ae]),mR=g.useCallback(async O=>{if(gt(O),O!==ae&&P){const ge=ae;de(O);try{await st().setModel(P,O)}catch(Me){de(ge),console.error("[InputBox] setModel failed:",Me)}}},[ae,P,de]);g.useEffect(()=>{je||gt(null)},[je]);const gR=g.useCallback(async O=>{if(We(!1),lf(O),!P||O===re)return;const ge=re;Ae(O);try{await st().setMode(P,O)}catch(Me){Ae(ge),console.error("[InputBox] setMode failed:",Me)}},[P,re,Ae]),fR=g.useCallback(async O=>{if(et(!1),!P||O===ae)return;const ge=ae;de(O);try{await st().setModel(P,O)}catch(Me){de(ge),console.error("[InputBox] setModel failed:",Me)}},[P,ae,de]),Nh=g.useCallback((O,ge)=>vn(`mode.${O}`)||ge||O,[vn]),bR=g.useCallback((O,ge)=>vn(`mode.${O}.desc`)||ge,[vn]),yR=g.useMemo(()=>{const O=fe.find(ge=>ge.id===re);return Nh(re,O==null?void 0:O.name)||"Mode"},[fe,re,Nh]),_R=g.useMemo(()=>{const O=ce.find(ge=>ge.id===ae);return(O==null?void 0:O.name)||ae||"Model"},[ce,ae]),vR=!!(G!=null&&G.options.some(O=>O.value==="disabled")),xR=(G==null?void 0:G.options.filter(O=>O.value!=="disabled"))??[],yl=!!G&&G.options.length>0,Vc=G?G.currentValue!=="disabled":ke,Qc=ct?ce.find(O=>O.id===ct):void 0,Ew=!!P&&ue==="connected"&&!q&&!wt&&(f.trim().length>0||K.length>0||tt.length>0||!!oe&&!f&&!qe),wR=K.length>0||tt.length>0||Pe>0;return l.jsxs("div",{className:"composer-input-wrap pb-[env(safe-area-inset-bottom)] md:pb-0",children:[l.jsxs("div",{className:"w-full",children:[n&&i!==void 0&&l.jsx("div",{ref:E,children:l.jsx(PZ,{isOpen:s,onClose:()=>h(!1),onImageSelect:JN,onFileSelect:XN,onAddDirectory:()=>o==null?void 0:o(),onNewChat:r,mainView:i,onNavigate:n})}),l.jsxs("div",{className:`composer-card relative overflow-visible transition-colors ${_?"composer-card-dragging":""}`,onDragEnter:VN,onDragLeave:QN,onDragOver:KN,onDrop:YN,children:[_&&l.jsx("div",{className:"pointer-events-none absolute inset-0 z-20 flex items-center justify-center rounded-[22px] bg-accent-brand/5",children:l.jsx("span",{className:"text-[14px] font-medium text-accent-brand",children:Je("input.dropHint")})}),Qe?l.jsx(HZ,{goal:$t??Qe,running:!$t,onEdit:()=>Qn(!0),onPause:rR,onResume:iR,onClear:sR}):Tn?l.jsx(zZ,{onDismiss:()=>pn(!1)}):null,mn&&l.jsx("div",{ref:bl,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:ut.map((O,ge)=>l.jsxs("button",{className:`w-full text-left px-3 py-2 flex items-baseline gap-3 transition-colors ${ge===ri?"bg-bg-primary text-text-primary":"text-text-primary hover:bg-bg-primary"}`,onMouseEnter:()=>ls(ge),onMouseDown:Me=>{Me.preventDefault(),Th(O)},children:[l.jsxs("span",{className:"font-mono text-[13px] font-medium shrink-0",children:["/",O.name]}),O.type==="skill"&&l.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"}),J0(O.name)&&l.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded bg-accent-brand/15 text-accent-brand font-medium shrink-0",children:vn("command.goal.title")??"Goal"}),l.jsx("span",{className:"text-text-tertiary text-[12px] truncate",children:vn(`command.${O.name}.description`)??O.description})]},O.name))}),ye&&l.jsx("div",{ref:dt,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:$e.map((O,ge)=>l.jsxs("button",{className:`w-full text-left px-3 py-2 flex items-center gap-3 transition-colors ${ge===kt?"bg-bg-primary text-text-primary":"text-text-primary hover:bg-bg-primary"}`,onMouseEnter:()=>wn(ge),onMouseDown:Me=>{Me.preventDefault(),Oe(O)},children:[O.type==="directory"?l.jsx(Bo,{size:14,className:"shrink-0 text-accent-brand"}):l.jsx(Pi,{size:14,className:"shrink-0 text-text-tertiary"}),l.jsx("span",{className:"font-mono text-[13px] truncate",children:O.name}),l.jsx("span",{className:"text-text-tertiary text-[11px] truncate ml-auto",title:O.path,children:O.path})]},O.path))}),wR&&l.jsxs("div",{className:"flex flex-wrap gap-2 px-3 pt-1",children:[K.map(O=>l.jsxs("div",{className:"relative group",children:[l.jsx("img",{src:O.dataUrl,alt:"",className:"w-16 h-16 rounded-lg object-cover border border-border-default"}),l.jsx("button",{onClick:()=>Vt(O.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:l.jsx(Bt,{size:12})})]},O.id)),Array.from({length:Pe}).map((O,ge)=>l.jsx("div",{className:"w-16 h-16 rounded-lg border border-border-default skeleton-shimmer"},`skeleton-${ge}`)),tt.map(O=>l.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:[l.jsx(Pi,{size:16,className:"shrink-0 text-text-tertiary"}),l.jsxs("div",{className:"min-w-0 flex-1",children:[l.jsx("div",{className:"text-[12px] text-text-primary truncate",title:O.name,children:O.name}),l.jsx("div",{className:"text-[11px] text-text-tertiary",children:PN(O.size)})]}),l.jsx("button",{onClick:()=>Lt(O.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:l.jsx(Bt,{size:12})})]},O.id))]}),l.jsxs("div",{className:"relative",children:[l.jsx("textarea",{ref:y,value:f,onChange:O=>{const ge=O.target.value,Me=O.target.selectionStart??ge.length;if(Rr(),b(ge),it.current){it.current=!1;return}let xt=null;for(let bt=Me-1;bt>=0;bt--){const Fr=ge[bt];if(Fr==="@"){const da=bt>0?ge[bt-1]:" ";(da===" "||da===`
942
942
  `||bt===0)&&(ge.substring(bt+1,Me).includes(" ")||(xt=bt));break}if(Fr===" "||Fr===`
943
943
  `)break}xt!==null?Kn!==xt&&(ni(xt),wn(0)):Kn!==null&&(ni(null),Z([]))},onCompositionStart:oR,onCompositionEnd:lR,onKeyDown:hR,onPaste:ZN,onContextMenu:cR,onFocus:()=>h(!1),placeholder:wt?Je("input.placeholderPending"):qe?Je("input.placeholderRunning"):oe?"":Je(Tn?"input.placeholderGoal":"input.placeholder"),enterKeyHint:"send",rows:1,"aria-label":Je("input.placeholder"),className:`composer-textarea ${u?"composer-textarea-hero":""}`}),oe&&!f&&!qe&&!wt&&l.jsx("div",{className:"pointer-events-none absolute inset-0 flex items-start overflow-hidden px-4 pt-1",children:l.jsx("span",{className:"max-w-full truncate text-[16px] leading-6 text-text-tertiary",children:oe})})]}),A&&l.jsxs("div",{ref:C,className:"fixed z-50 bg-bg-secondary rounded-xl border border-border-default shadow-lg overflow-hidden min-w-[120px]",style:{left:A.x,top:A.y},onMouseDown:O=>O.stopPropagation(),children:[l.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:O=>{O.preventDefault(),O.stopPropagation(),dR()},children:[l.jsx(aS,{size:14,className:"text-text-tertiary"}),Je("input.contextMenu.newline")]}),Ew&&l.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:O=>{O.preventDefault(),O.stopPropagation(),uR()},children:[l.jsx(ic,{size:14,className:"text-text-tertiary"}),Je("input.contextMenu.send")]})]}),l.jsx("input",{ref:x,type:"file",accept:"image/jpeg,image/png,image/gif,image/webp",multiple:!0,className:"hidden",onChange:eR}),l.jsx("input",{ref:k,type:"file",accept:"*/*",multiple:!0,className:"hidden",onChange:tR}),l.jsxs("div",{className:"composer-toolbar",onClick:O=>{var ge;O.target===O.currentTarget&&((ge=y.current)==null||ge.focus())},children:[l.jsxs("div",{className:"composer-tools",children:[!qe&&l.jsx("button",{ref:N,onClick:()=>h(O=>!O),className:"composer-add",title:Je("input.addFile"),"aria-label":Je("input.addFile"),children:l.jsx(is,{size:16})}),!u&&!ie&&l.jsx(RN,{}),fe.length>0&&l.jsxs("div",{className:"relative min-w-0 shrink",ref:z,children:[l.jsxs("button",{type:"button",onClick:()=>{We(O=>!O),et(!1)},className:"composer-chip",title:Je("input.modeSelector"),"aria-expanded":Le,children:[l.jsx("span",{className:"min-w-0 truncate",children:yR}),l.jsx(sr,{size:12,className:`shrink-0 text-text-tertiary transition-transform ${Le?"rotate-180":""}`})]}),Le&&l.jsx("div",{className:"composer-menu absolute bottom-full left-0 z-50 mb-2 max-h-[280px] min-w-[200px] overflow-y-auto py-1",children:fe.map(O=>{const ge=Nh(O.id,O.name),Me=bR(O.id,O.description);return l.jsxs("button",{onClick:()=>gR(O.id),className:`w-full text-left px-3 py-1.5 text-[13px] transition-colors ${re===O.id?"bg-bg-primary text-text-primary font-medium":"text-text-secondary hover:bg-bg-primary hover:text-text-primary"}`,title:Me,children:[l.jsx("div",{className:"truncate",children:ge}),Me&&l.jsx("div",{className:"text-[11px] text-text-tertiary mt-0.5 truncate",children:Me})]},O.id)})})]}),ce.length>0&&l.jsxs("div",{className:"relative ml-auto min-w-0 shrink",ref:Q,children:[l.jsxs("button",{type:"button",onClick:()=>{et(O=>!O),We(!1)},className:"composer-chip max-w-[220px]",title:ke?`${Je("input.modelSelector")} · ${Je("input.deepThinking")}`:Je("input.modelSelector"),"aria-expanded":je,children:[ke&&l.jsx("span",{className:"flex h-3 w-3 shrink-0 items-center justify-center text-[11px] font-semibold",children:"∞"}),l.jsx("span",{className:"min-w-0 truncate",children:_R}),l.jsx(sr,{size:12,className:`shrink-0 text-text-tertiary transition-transform ${je?"rotate-180":""}`})]}),je&&l.jsxs("div",{className:"absolute bottom-full right-0 mb-2 z-50",children:[l.jsx("div",{className:"composer-menu w-[248px] max-w-[calc(100vw-24px)] overflow-hidden",children:l.jsxs("div",{className:"max-h-[340px] overflow-y-auto py-1",children:[!yl&&l.jsxs(l.Fragment,{children:[l.jsxs("button",{type:"button",onClick:pR,className:"w-full flex items-center justify-between px-3 py-1.5 hover:bg-bg-primary transition-colors",title:Je("input.deepThinkingDesc"),children:[l.jsx("span",{className:"text-[12px] leading-tight text-text-primary truncate",children:Je("input.deepThinking")}),l.jsx("span",{className:`relative inline-flex w-9 h-5 rounded-full transition-colors flex-shrink-0 ${ke?"bg-accent-green":"bg-border-default"}`,children:l.jsx("span",{className:`absolute top-[2px] w-4 h-4 rounded-full bg-white shadow-sm transition-transform ${ke?"translate-x-[18px]":"translate-x-[2px]"}`})})]}),l.jsx("div",{className:"mx-3 my-1 border-t border-border-default"})]}),ce.map(O=>{const ge=ae===O.id,Me=ct===O.id,xt=cJ(O.credits??"")||(O.contextWindow?e1(O.contextWindow):"");return l.jsxs("div",{className:"group relative mx-1 flex items-center rounded-md hover:bg-bg-primary transition-colors",onMouseEnter:()=>{yl&&gt(O.id)},children:[l.jsxs("button",{onClick:()=>fR(O.id),className:"flex-1 min-w-0 flex items-center gap-2 pl-2 pr-1 py-1 text-left",children:[l.jsx("span",{className:"flex-1 min-w-0 truncate text-[12px] leading-tight text-text-primary",children:O.name}),l.jsx("span",{className:"w-10 flex-shrink-0 text-right text-[11px] leading-tight text-text-tertiary tabular-nums",children:xt})]}),l.jsxs("span",{className:"relative w-4 mr-1.5 flex-shrink-0 flex items-center justify-center",children:[ge&&l.jsx(gr,{size:12,className:`text-text-primary transition-opacity ${yl?"group-hover:opacity-0":""} ${Me?"opacity-0":""}`}),yl&&l.jsx("button",{type:"button",onMouseEnter:bt=>{bt.stopPropagation(),gt(O.id)},onClick:bt=>{bt.stopPropagation(),mR(O.id)},className:`absolute inset-0 flex items-center justify-center rounded transition-opacity ${Me?"opacity-100 text-text-primary":"opacity-0 group-hover:opacity-100 text-text-tertiary hover:text-text-primary"}`,title:Je("input.editThinking"),children:l.jsx(Wa,{size:11})})]})]},O.id)})]})}),Qc&&yl&&l.jsxs("div",{className:"absolute right-full top-0 mr-2 w-[212px] max-w-[calc(100vw-24px)] bg-bg-secondary border border-border-default rounded-xl shadow-lg py-1",onMouseLeave:()=>gt(null),children:[l.jsx("div",{className:"px-3 pt-1 pb-1 text-[12px] font-semibold text-text-primary truncate",children:Qc.name}),Qc.contextWindow&&l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"mx-3 border-t border-border-default"}),l.jsxs("div",{className:"flex items-center justify-between px-3 py-1.5",children:[l.jsx("span",{className:"text-[11px] text-text-tertiary",children:Je("input.contextWindow")}),l.jsx("span",{className:"text-[11px] text-text-secondary tabular-nums",children:e1(Qc.contextWindow)})]})]}),vR&&l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"mx-3 border-t border-border-default"}),l.jsxs("button",{type:"button",onClick:()=>Cw(Vc?"disabled":"enabled"),className:"w-full flex items-center justify-between px-3 py-1.5 hover:bg-bg-primary transition-colors",children:[l.jsx("span",{className:"text-[12px] text-text-primary",children:Je("input.thinkingMode")}),l.jsx("span",{className:`relative inline-flex w-9 h-5 rounded-full transition-colors flex-shrink-0 ${Vc?"bg-accent-green":"bg-border-default"}`,children:l.jsx("span",{className:`absolute top-[2px] w-4 h-4 rounded-full bg-white shadow-sm transition-transform ${Vc?"translate-x-[18px]":"translate-x-[2px]"}`})})]})]}),l.jsx("div",{className:"px-3 pt-1 pb-0.5 text-[11px] text-text-tertiary",children:Je("input.thinkingLevel")}),l.jsx("div",{className:Vc?"":"opacity-40 pointer-events-none",children:xR.map(O=>l.jsx("div",{className:"mx-1 rounded-md hover:bg-bg-primary transition-colors",children:l.jsxs("button",{type:"button",onClick:()=>Cw(O.value),className:"w-full flex items-center justify-between gap-2 pl-2 pr-1.5 py-1 text-left",title:O.description??void 0,children:[l.jsx("span",{className:"truncate text-[12px] leading-tight text-text-primary",children:O.value==="enabled"?Je("input.thoughtDefault"):O.name}),G.currentValue===O.value&&l.jsx(gr,{size:12,className:"flex-shrink-0 text-text-primary"})]})},O.value))})]})]})]})]}),l.jsxs("div",{className:"composer-trailing",children:[l.jsx(UZ,{onCompact:aR}),p&&l.jsx("button",{onClick:()=>{const O=y.current;if(!O)return;const ge=O.selectionStart??f.length,Me=O.selectionEnd??ge,xt=f.slice(0,ge)+`
944
- `+f.slice(Me);b(xt),requestAnimationFrame(()=>{O.selectionStart=O.selectionEnd=ge+1,O.focus()})},className:"composer-add",title:Je("input.newline"),children:l.jsx(aS,{size:15})}),l.jsx("button",{type:"button",disabled:$||!qe&&!Ew,onClick:()=>{qe?kw():!f&&oe&&!qe?dr(oe):dr()},className:"composer-send",title:Je(qe?"input.stop":"input.send"),"aria-label":Je(qe?"input.stop":"input.send"),children:$?l.jsx(yt,{size:14,className:"animate-spin"}):qe?l.jsx(Q1,{size:14,fill:"currentColor",strokeWidth:0}):l.jsx(ic,{size:18,strokeWidth:2.5})})]})]})]})]}),c&&l.jsx(NN,{initialPath:xn,onSelect:O=>{O!==xn&&an(O),d==null||d()},onClose:()=>d==null?void 0:d()}),Ls&&Qe&&l.jsx(GZ,{initialCondition:Qe.condition,onSave:O=>{Qn(!1);const ge=()=>{dr(`/goal ${O}`).catch(()=>{})};nR(()=>{if(qe){kw().then(ge).catch(ge);return}ge()})},onCancel:()=>Qn(!1)})]})}const uJ={JOB_NOT_FOUND:"该智能体会话不存在,可能已被清理",SESSION_OCCUPIED:"该会话正被其他终端或进程占用",SESSION_UNAVAILABLE:"该会话当前不可用,请稍后重试",ADMISSION_FAILED:"会话准入失败,请稍后重试",INTERNAL_ERROR:"服务内部错误,请稍后重试",INVALID_RESPONSE:"服务返回异常,请稍后重试"};function hJ(e,t){if(e instanceof Ju){const n=e.code?uJ[e.code]:void 0;return n||e.message||t}return e instanceof Error?e.message||t:e?String(e):t}const qg=["cli","ptc","minimal","create"],pJ=new Set(qg),Ol=12,Bd=8,Gp=96,mJ=520;function gJ(e){const{trigger:t,viewport:n,menuWidth:r,prefer:i="auto"}=e,s=t.top-Ol-Bd,a=n.height-t.bottom-Ol-Bd;let o=i==="up"||i==="auto"&&s>=a?"up":"down";o==="up"&&s<Gp&&a>s?o="down":o==="down"&&a<Gp&&s>a&&(o="up");const c=Math.min(mJ,Math.max(Gp,o==="up"?s:a)),d=Math.min(Math.max(t.left,Ol),Math.max(Ol,n.width-r-Ol));return o==="up"?{left:d,maxHeight:c,side:o,bottom:n.height-t.top+Bd}:{left:d,maxHeight:c,side:o,top:t.bottom+Bd}}function GN(e){return!e.custom&&pJ.has(e.value)}function fJ(e){const t=[],n=[];for(const r of e)GN(r)?t.push(r):n.push(r);return t.sort((r,i)=>{const s=qg.indexOf(r.value),a=qg.indexOf(i.value);return(s===-1?99:s)-(a===-1?99:a)}),{builtin:t,rest:n}}function bJ(e){const{builtin:t,rest:n}=fJ(e);return[...t,...n]}function yJ(e,t){if(!e)return t;const n=e.replace(/<[^>]+>/g," ").replace(/[#*_`]+/g," ").replace(/\s+/g," ").trim();return n?n.length>96?`${n.slice(0,96).trimEnd()}…`:n:t}const t1=360;function WN({options:e,value:t,label:n,disabled:r=!1,open:i,onOpenChange:s,onSelect:a,direction:o="auto",error:c=null,emptyText:d,noDescriptionText:u,customTagText:h,title:p,buttonClassName:m}){const f=g.useRef(null),b=g.useRef(null),_=g.useRef(null),[v,A]=g.useState(null),S=g.useMemo(()=>bJ(e),[e]);g.useLayoutEffect(()=>{if(!i){A(null);return}const x=k=>{var E,N;if(k&&((E=_.current)!=null&&E.contains(k.target)))return;const C=(N=b.current)==null?void 0:N.getBoundingClientRect();C&&A(gJ({trigger:C,viewport:{width:window.innerWidth,height:window.innerHeight},menuWidth:Math.min(t1,window.innerWidth-24),prefer:o}))};return x(),window.addEventListener("scroll",x,!0),window.addEventListener("resize",x),()=>{window.removeEventListener("scroll",x,!0),window.removeEventListener("resize",x)}},[i,o,S.length]),g.useEffect(()=>{if(!i)return;const x=C=>{var N,z;const E=C.target;(N=f.current)!=null&&N.contains(E)||(z=_.current)!=null&&z.contains(E)||s(!1)},k=C=>{C.key==="Escape"&&s(!1)};return document.addEventListener("pointerdown",x,!0),document.addEventListener("keydown",k),()=>{document.removeEventListener("pointerdown",x,!0),document.removeEventListener("keydown",k)}},[i,s]);const y=i&&v&&l.jsx("div",{ref:_,role:"menu",className:"composer-menu composer-menu-agent",style:{position:"fixed",left:v.left,width:Math.min(t1,window.innerWidth-24),maxHeight:v.maxHeight,...v.side==="up"?{bottom:v.bottom,top:"auto"}:{top:v.top,bottom:"auto"}},onClick:x=>x.stopPropagation(),children:l.jsxs("div",{className:"composer-menu-agent-scroll",children:[c&&l.jsx("div",{className:"composer-menu-agent-error",children:c}),S.length===0&&d&&l.jsx("div",{className:"composer-menu-agent-empty",children:d}),S.map(x=>{const k=x.value===t,C=x.broken?x.broken:GN(x)?x.description||u:yJ(x.description,u);return l.jsxs("button",{type:"button",role:"menuitemradio","aria-checked":k,onClick:()=>{s(!1),a(x.value)},disabled:!!x.broken,className:`composer-menu-agent-item ${k?"is-current":""} ${x.broken?"is-broken":""}`,title:x.broken??x.description,children:[l.jsxs("span",{className:"composer-menu-agent-copy",children:[l.jsxs("span",{className:"composer-menu-agent-name",children:[x.label,x.custom&&l.jsxs("span",{className:"composer-menu-agent-tag",children:[" · ",h]})]}),l.jsx("span",{className:`composer-menu-agent-desc ${x.broken?"is-broken":""}`,children:C})]}),l.jsx("span",{className:"composer-menu-agent-check","aria-hidden":!0,children:k&&l.jsx(gr,{size:16})})]},x.value)})]})});return l.jsxs("div",{ref:f,className:"relative min-w-0 shrink",children:[l.jsxs("button",{ref:b,type:"button",disabled:r,"aria-haspopup":"menu","aria-expanded":i,onClick:()=>s(!i),className:`composer-seat-chip ${r?"cursor-not-allowed opacity-40":""} ${m??""}`,title:p,children:[l.jsx(Is,{size:16,className:"shrink-0"}),l.jsx("span",{className:"min-w-0 truncate",children:n}),l.jsx(sr,{size:12,className:`shrink-0 text-text-tertiary transition-transform ${i?"rotate-180":""}`})]}),y&&eh.createPortal(y,document.body)]})}function _J({targetCwd:e}){const{t}=Re(),n=Ge(E=>E.sessionId),{contextInheritOpen:r,contextSourceSessionId:i,setContextSourceSessionId:s,setContextInheritOpen:a}=en(),[o,c]=g.useState([]),[d,u]=g.useState(!1),[h,p]=g.useState(!1),[m,f]=g.useState(!1),[b,_]=g.useState(0),[v,A]=g.useState(null),S=g.useRef(0),y=g.useCallback(()=>a(!1),[a]),x=e.split("/").filter(Boolean).pop()||e||"/",k=g.useCallback(async()=>{const E=++S.current;if(!e){c([]),u(!1);return}u(!0),A(null);try{const N=await hu(e,{includeAttached:!0,offset:0,limit:20});if(E!==S.current)return;c(N.candidates),f(N.hasMore),_(N.nextOffset??N.candidates.length),!N.hasMore&&i&&!N.candidates.some(z=>z.sessionId===i)&&s(null)}catch(N){E===S.current&&(c([]),A(N instanceof Error?N.message:String(N)))}finally{E===S.current&&u(!1)}},[i,s,e]),C=g.useCallback(async()=>{if(!e||!m||h)return;const E=S.current;p(!0);try{const N=await hu(e,{includeAttached:!0,offset:b,limit:20});if(E!==S.current)return;c(z=>{const Q=new Set(z.map(T=>T.sessionId));return z.concat(N.candidates.filter(T=>!Q.has(T.sessionId)))}),f(N.hasMore),_(N.nextOffset??b+N.candidates.length)}catch(N){E===S.current&&A(N instanceof Error?N.message:String(N))}finally{E===S.current&&p(!1)}},[m,h,b,e]);return g.useEffect(()=>{r&&k().catch(()=>{})},[r,k]),r?l.jsxs("div",{className:"absolute bottom-full left-0 z-50 mb-2 flex max-h-[360px] w-[320px] max-w-[90vw] flex-col overflow-hidden rounded-lg border border-border-muted bg-bg-card shadow-sm",role:"dialog","aria-label":t("inherit.drawer.title"),children:[l.jsxs("div",{className:"flex min-h-12 shrink-0 items-center gap-2 border-b border-border-muted px-3 py-2",children:[l.jsx(P1,{size:13,className:"shrink-0 text-text-tertiary"}),l.jsxs("div",{className:"min-w-0 flex-1",children:[l.jsx("div",{className:"truncate text-[12px] font-medium text-text-primary",children:t("inherit.drawer.title")}),l.jsx("div",{className:"truncate text-[10px] text-text-tertiary",title:e,children:x})]}),l.jsx("button",{type:"button",onClick:y,className:"flex h-6 w-6 shrink-0 items-center justify-center rounded-md text-text-tertiary outline-none transition-colors hover:bg-bg-hover hover:text-text-primary","aria-label":t("agents.panel.close"),children:l.jsx(Bt,{size:14})})]}),l.jsxs("div",{className:"min-h-0 flex-1 overflow-y-auto overscroll-contain px-1.5 pb-2 pt-1",onScroll:E=>{const N=E.currentTarget;N.scrollHeight-N.scrollTop-N.clientHeight<120&&C().catch(()=>{})},children:[l.jsxs("button",{type:"button",onClick:()=>{s(null),y()},className:`flex w-full items-center gap-2 rounded-md px-2 py-2 text-left transition-colors ${i===null?"bg-bg-hover":"hover:bg-bg-hover"}`,children:[l.jsx(Is,{size:14,className:"shrink-0 text-text-tertiary"}),l.jsx("span",{className:"min-w-0 flex-1 truncate text-[13px] text-text-primary",children:t("agents.input.startFrom.blank")}),i===null&&l.jsx(gr,{size:14,className:"shrink-0 text-text-primary"})]}),l.jsx("div",{className:"mt-1.5 px-2 pb-0.5 pt-1 text-[10px] font-medium text-text-tertiary",children:t("inherit.fromSession")}),d&&l.jsxs("div",{className:"flex items-center justify-center gap-2 px-2 py-5 text-[11px] text-text-tertiary",children:[l.jsx(yt,{size:13,className:"animate-spin"}),t("history.loading")]}),!d&&v&&l.jsx("button",{type:"button",onClick:()=>k().catch(()=>{}),className:"w-full px-2 py-4 text-center text-[11px] text-text-tertiary transition-colors hover:text-text-primary",title:v,children:t("history.retry")}),!d&&!v&&o.length===0&&l.jsx("div",{className:"px-2 py-5 text-center text-[11px] text-text-tertiary",children:t("inherit.emptyForDirectory")}),!d&&!v&&o.map(E=>{const N=E.sessionId===n,z=i===E.sessionId;return l.jsxs("button",{type:"button",onClick:()=>{s(E.sessionId),y()},className:`flex w-full items-center gap-2 rounded-md px-2 py-2 text-left transition-colors ${z?"bg-bg-hover":"hover:bg-bg-hover"}`,children:[l.jsx(Jo,{size:14,className:"shrink-0 text-text-tertiary"}),l.jsx("span",{className:"min-w-0 flex-1 truncate text-[13px] text-text-primary",children:E.label}),N&&l.jsx("span",{className:"shrink-0 text-[10px] text-accent-blue",children:t("sessions.current")}),z&&l.jsx(gr,{size:14,className:"shrink-0 text-text-primary"})]},E.sessionId)}),h&&l.jsx("div",{className:"flex items-center justify-center py-2 text-text-tertiary","aria-label":t("history.loading"),children:l.jsx(yt,{size:13,className:"animate-spin"})})]})]}):null}const vJ=[{value:"",labelKey:"agents.input.permission.default",descriptionKey:"agents.input.permission.default.desc"},{value:"default",labelKey:"agents.input.permission.ask",descriptionKey:"mode.default.desc"},{value:"acceptEdits",labelKey:"mode.acceptEdits",descriptionKey:"mode.acceptEdits.desc"},{value:"plan",labelKey:"mode.plan",descriptionKey:"mode.plan.desc"},{value:"auto",labelKey:"mode.auto",descriptionKey:"mode.auto.desc"},{value:"dontAsk",labelKey:"mode.dontAsk",descriptionKey:"mode.dontAsk.desc"},{value:"bypassPermissions",labelKey:"mode.bypassPermissions",descriptionKey:"mode.bypassPermissions.desc"},{value:"fullAccess",labelKey:"mode.fullAccess",descriptionKey:"mode.fullAccess.desc"}];function xJ(e,t,n){var r;return((r=e.find(i=>i.id===t))==null?void 0:r.name)||t||n}function wJ(e){if(e>=1e6){const t=e/1e6;return`${Number.isInteger(t)?t:t.toFixed(1)}M`}return e>=1e3?`${Math.round(e/1e3)}K`:String(e)}function SJ(e){const t=e.replace(/\s*credits\s*$/i,"").trim(),n=Number.parseFloat(t.replace(/^[x×]/i,""));return Number.isFinite(n)&&n>0?`${n}x`:""}function qN(e){return d5({stored:xC(),currentMode:e})}function kJ(){const e=nt.getState();return e.processAgent??e.stagedAgent??(typeof localStorage<"u"?localStorage.getItem(Aa):null)??""}function AJ(){const e=nt.getState().processPermissionMode;return e||qN(Ge.getState().currentMode)}function CJ({model:e,title:t,open:n,onToggle:r,options:i,value:s,onSelect:a,disabled:o=!1,canEditThinking:c,thinkingEditModelId:d,onPreviewThinking:u,onClearThinkingEdit:h,thinkingOptions:p,thinkingValue:m,onSelectThinking:f}){const{t:b}=Re(),_=d?i.find(v=>v.value===d):void 0;return l.jsxs("div",{className:"relative min-w-0 shrink","data-composer-model-select":!0,children:[l.jsxs("button",{type:"button",onClick:r,disabled:o,className:["composer-chip max-w-[220px]",o?"cursor-not-allowed opacity-40":""].join(" "),title:t,"aria-label":`${t}: ${e}`,"aria-expanded":n,children:[l.jsx("span",{className:"min-w-0 truncate",children:e}),!o&&l.jsx(sr,{size:12,className:`shrink-0 text-text-tertiary transition-transform ${n?"rotate-180":""}`})]}),n&&!o&&l.jsxs("div",{className:"absolute bottom-full right-0 z-50 mb-2",children:[l.jsx("div",{className:"composer-menu w-[248px] max-w-[calc(100vw-24px)] overflow-hidden",role:"menu","aria-label":t,children:l.jsx("div",{className:"max-h-[340px] overflow-y-auto py-1",children:i.map(v=>{const A=v.value===s,S=d===v.value;return l.jsxs("div",{className:"group relative mx-1 flex items-center rounded-md transition-colors hover:bg-bg-primary",onMouseEnter:()=>{c&&u(v.value)},children:[l.jsxs("button",{type:"button",role:"menuitemradio","aria-checked":A,onClick:()=>a(v.value),className:"flex min-w-0 flex-1 items-center gap-2 py-1 pl-2 pr-1 text-left",title:v.description,children:[l.jsx("span",{className:"min-w-0 flex-1 truncate text-[12px] leading-tight text-text-primary",children:v.label}),l.jsx("span",{className:"w-10 shrink-0 text-right text-[11px] leading-tight tabular-nums text-text-tertiary",children:v.meta})]}),l.jsxs("span",{className:"relative mr-1.5 flex w-4 shrink-0 items-center justify-center",children:[A&&l.jsx(gr,{size:12,className:`text-text-primary transition-opacity ${c?"group-hover:opacity-0":""} ${S?"opacity-0":""}`}),c&&l.jsx("button",{type:"button",onMouseEnter:y=>{y.stopPropagation(),u(v.value)},onClick:y=>{y.stopPropagation(),u(v.value)},className:`absolute inset-0 flex items-center justify-center rounded transition-opacity ${S?"opacity-100 text-text-primary":"opacity-0 group-hover:opacity-100 text-text-tertiary hover:text-text-primary"}`,title:b("input.editThinking"),children:l.jsx(Wa,{size:11})})]})]},v.value)})})}),_&&c&&l.jsxs("div",{className:"composer-menu absolute right-full top-0 mr-2 w-[212px] max-w-[calc(100vw-24px)] py-1",onMouseLeave:h,children:[l.jsx("div",{className:"px-3 pb-1 pt-1 text-[12px] font-semibold text-text-primary",children:_.label}),_.description&&l.jsx("div",{className:"px-3 pb-1.5 text-[10px] leading-snug text-text-tertiary",children:_.description}),l.jsx("div",{className:"px-3 pb-0.5 pt-1 text-[11px] text-text-tertiary",children:b("input.thinkingLevel")}),p.map(v=>l.jsx("div",{className:"mx-1 rounded-md transition-colors hover:bg-bg-primary",children:l.jsxs("button",{type:"button",onClick:()=>f(v.value),className:"flex w-full items-center justify-between gap-2 py-1 pl-2 pr-1.5 text-left",title:v.description,children:[l.jsx("span",{className:"truncate text-[12px] leading-tight text-text-primary",children:v.label}),m===v.value&&l.jsx(gr,{size:12,className:"shrink-0 text-text-primary"})]})},v.value))]})]})]})}function EJ({onCreated:e,onCancel:t}){var Jt,Lt;const{t:n,tryT:r}=Re(),{createJob:i}=tn(),{models:s,currentModel:a,currentMode:o,modes:c,thoughtLevel:d}=Ge(),u=Ge(se=>se.sessionId),{contextSourceSessionId:h,contextInheritOpen:p,setContextSourceSessionId:m,setContextInheritOpen:f,setNewJobMode:b}=en(),_=Xr(se=>se.cwd),v=nt(se=>se.stagedAgent),A=nt(se=>se.processAgent),S=nt(se=>se.processPermissionMode),y=nt(se=>se.agents),[x,k]=g.useState(""),[C,E]=g.useState(!1),[N,z]=g.useState(null),[Q,T]=g.useState(null),[w,L]=g.useState(AJ),I=g.useRef(w!==""),[R,$]=g.useState(!1),[D,U]=g.useState(kJ),Y=g.useRef(!!nt.getState().processAgent),[ee,P]=g.useState(_||""),[q,ue]=g.useState(null),[_e,ke]=g.useState(!1),[H,G]=g.useState(null),[V,oe]=g.useState(!1),[J,he]=g.useState(!1),[ne,pe]=g.useState(null),[re,ce]=g.useState(!1),[ae,Ae]=g.useState(!1),[de,F]=g.useState(null),ie=g.useRef(null),fe=g.useRef(null),X=g.useRef(null),Ce=g.useRef(null),Ee=g.useRef(null),Le=g.useRef(null),We=g.useRef(ee),je=g.useRef(0),[et,ct]=g.useState(!1),{images:gt,setImages:qe,addImages:wt,removeImage:Nt,loadingImageCount:qt}=HN(),{files:$t,setFiles:It,addFiles:cr,removeFile:Vn}=BN();g.useEffect(()=>{N===null&&a&&z(a)},[a,N]),g.useEffect(()=>{!ee&&_&&P(_)},[ee,_]),g.useEffect(()=>{We.current!==ee&&(We.current=ee,m(null),f(!1))},[ee,f,m]),g.useEffect(()=>{const se=ee||_||"";if(!se){ue(null);return}let $e=!1;return ke(!0),B5(se).then(kt=>{$e||ue(kt)}).catch(()=>{$e||ue(null)}).finally(()=>{$e||ke(!1)}),()=>{$e=!0}},[ee,_]),g.useEffect(()=>{!D&&v&&U(v)},[D,v]),g.useEffect(()=>{const se=ie.current;!se||se.offsetParent===null||(se.style.height="auto",se.style.height=`${Math.max(52,Math.min(se.scrollHeight,336))}px`)},[x]),g.useEffect(()=>{if(!V&&ne===null&&H!=="model"&&!re&&!p)return;const se=$e=>{const kt=$e.composedPath();fe.current&&kt.includes(fe.current)||X.current&&kt.includes(X.current)||Ce.current&&kt.includes(Ce.current)||Ee.current&&kt.includes(Ee.current)||(oe(!1),pe(null),G(null),F(null),ce(!1))};return document.addEventListener("pointerdown",se,!0),()=>{document.removeEventListener("pointerdown",se,!0)}},[H,V,ne,re,p]),g.useEffect(()=>{const se=$e=>{if($e.key==="Escape"&&!ae){if(V||H||re||p){oe(!1),pe(null),G(null),F(null),ce(!1),f(!1),$e.preventDefault();return}t==null||t()}};return document.addEventListener("keydown",se),()=>{document.removeEventListener("keydown",se)}},[p,re,t,H,f,V,ae]);const ze=g.useMemo(()=>[{value:"",label:n("agents.input.model.default")},...s.map(se=>({value:se.id,label:se.name,description:se.description||void 0,meta:SJ(se.credits??"")||(se.contextWindow?wJ(se.contextWindow):"")}))],[s,n]),rt=g.useMemo(()=>[{value:"",label:n("agents.input.effort.default"),description:n("agents.input.effort.default.desc")},...(N===a?(d==null?void 0:d.options)??[]:[]).filter(se=>!["disabled","enabled"].includes(se.value)).map(se=>({value:se.value,label:se.name,description:se.description||void 0}))],[a,N,d,n]),Ot=rt.length>1,le=g.useCallback(se=>{z(se),T(null),G(null)},[]),Ne=g.useCallback(se=>{T(se||null)},[]),Qe=g.useMemo(()=>{const se=D||(q==null?void 0:q.defaultAgentName);return vJ.filter($e=>se!=="minimal"||$e.value!=="plan").map($e=>{const kt=c.find(wn=>wn.id===$e.value);return{value:$e.value,label:r($e.labelKey)||(kt==null?void 0:kt.name)||$e.value,description:r($e.descriptionKey)||(kt==null?void 0:kt.description)}})},[c,r,D,q==null?void 0:q.defaultAgentName]),os=g.useMemo(()=>{var se;return((se=q==null?void 0:q.agents)!=null&&se.length?q.agents:y).map($e=>({value:$e.name,label:Es($e,r),description:Qo($e,r),custom:$e.custom,source:$e.source,broken:$e.broken}))},[q==null?void 0:q.agents,y,r]),Br=D||(q==null?void 0:q.defaultAgentName)||"";g.useEffect(()=>{Y.current||!A||(Y.current=!0,U(A))},[A]),g.useEffect(()=>{const se=S||(q==null?void 0:q.permissionMode);se&&(I.current=!0,L(se))},[S,q==null?void 0:q.permissionMode]),g.useEffect(()=>{if(I.current)return;const se=qN(o);se&&(I.current=!0,L(se))},[o]),g.useEffect(()=>{Br==="minimal"&&w==="plan"&&L("")},[Br,w]);const Je=((Jt=os.find(se=>se.value===Br))==null?void 0:Jt.label)??(D||n("agents.input.agent.default")),vn=((Lt=Qe.find(se=>se.value===w))==null?void 0:Lt.label)||n("agents.input.permission.default"),Rr=g.useMemo(()=>n(h?h===u?"agents.input.startFrom.continue":"agents.input.startFrom.session":"agents.input.startFrom.blank"),[h,u,n]),an=x.trimStart().startsWith("!"),jr=an?x.trim().slice(1).trim():x.trim(),xn=gt.length>0||$t.length>0,Tn=ee||_||"",pn=QC(Tn),Ls=Math.max(0,((q==null?void 0:q.repoTargets.length)??1)-1),Qn=g.useCallback(se=>{const $e=se.filter((Kn,ni,Z)=>Z.findIndex(ye=>ye===Kn||ye.name===Kn.name&&ye.type===Kn.type&&ye.size===Kn.size&&ye.lastModified===Kn.lastModified)===ni),{images:kt,others:wn}=FN($e);kt.some(Kn=>Kn.size>Ih)&&Dt.error(n("input.imageTooLarge")),wn.some(Kn=>Kn.size>ww)&&Dt.error(n("input.fileTooLarge")),kt.length>0&&wt(kt).catch(()=>{}),wn.length>0&&cr(wn).catch(()=>{})},[cr,wt,n]),K=g.useCallback(se=>{var $e;se.preventDefault(),se.stopPropagation(),je.current++,($e=se.dataTransfer)!=null&&$e.types.includes("Files")&&ct(!0)},[]),xe=g.useCallback(se=>{se.preventDefault(),se.stopPropagation(),je.current--,je.current===0&&ct(!1)},[]),Pe=g.useCallback(se=>{se.preventDefault(),se.stopPropagation()},[]),ft=g.useCallback(se=>{se.preventDefault(),se.stopPropagation(),je.current=0,ct(!1),Qn(zu(se.dataTransfer))},[Qn]),Vt=g.useCallback(se=>{const $e=zu(se.clipboardData),kt=zN(se.clipboardData),wn=$e.filter(Kn=>!fl.includes(Kn.type));(kt.length>0||wn.length>0)&&(se.preventDefault(),Qn([...kt,...wn]))},[Qn]),tt=g.useCallback(async()=>{var se;if(!C){if(an&&xn){Dt.error(n("agents.input.attachmentsNotForShell"));return}if(!(!jr&&!xn)){if(xn&&!Tn){Dt.error(n("input.attachmentUploadFailed"));return}E(!0);try{const $e=[...gt.map((Z,ye)=>({id:Z.id,name:sJ(Z.mimeType,ye),blob:aJ(Z),mimeType:Z.mimeType})),...$t.filter(Sw).map(Z=>({id:Z.id,name:Z.name,blob:Wg(Z),mimeType:Z.mimeType})),...$t.filter($N).map(Z=>({id:Z.id,name:Z.name,blob:Wg(Z),mimeType:Z.mimeType}))],kt=$e.length>0?await ON(Tn,"new-agent",$e,X1):[],wn=kt.map(Z=>R?Z.absolutePath:Z.relativePath),Kn=eJ(jr,wn),ni=await i(Kn,{cwd:ee||void 0,name:Ec(jr||((se=kt[0])==null?void 0:se.name)||"")||void 0,...an?{bash:!0}:{agent:D||Br||void 0,model:N||void 0,effort:Q||void 0,permissionMode:o5(w)||void 0,bgIsolation:R?"worktree":"none",sourceSessionId:h??void 0}});ni&&(k(""),qe([]),It([]),await(e==null?void 0:e(ni)),b(!1))}catch($e){const kt=$e instanceof Error&&$e.message.startsWith("Upload file failed")?n("input.attachmentUploadFailed"):hJ($e,n("error.jobCreateFailed"));Dt.error(kt)}finally{E(!1)}}}},[h,i,C,D,ee,Q,N,jr,Br,$t,xn,gt,e,w,b,an,n,Tn,R]),Ke=g.useCallback(se=>{se.nativeEvent.isComposing||se.key==="Enter"&&!se.shiftKey&&(se.preventDefault(),tt())},[tt]);return l.jsxs(l.Fragment,{children:[l.jsxs("div",{className:"composer-hero-row",ref:Ee,children:[l.jsxs("button",{type:"button",onClick:()=>ce(se=>!se),className:"composer-seat-chip",title:`${n("agents.input.directory")}: ${Tn||"/"}`,"aria-label":n("agents.input.directory"),"aria-expanded":re,children:[l.jsx(Bo,{size:16,className:"shrink-0"}),l.jsx("span",{className:"min-w-0 truncate",children:pn}),Ls>0&&l.jsxs("span",{className:"shrink-0 text-[12px] font-medium text-text-tertiary",children:["+",Ls]}),l.jsx(sr,{size:12,className:`shrink-0 text-text-tertiary transition-transform ${re?"rotate-180":""}`})]}),re&&l.jsxs("div",{className:"composer-menu absolute left-0 top-full z-50 mt-2 max-h-[280px] w-[320px] max-w-[calc(100vw-24px)] overflow-y-auto overscroll-contain py-1",children:[l.jsxs("div",{className:"px-3 py-2",children:[l.jsx("div",{className:"text-[13px] font-medium text-text-primary",children:n("agents.input.directory.choose")}),l.jsx("div",{className:"mt-0.5 text-[12px] leading-snug text-text-tertiary",children:n("agents.input.directory.hint")})]}),q==null?void 0:q.repoTargets.map(se=>{const $e=se.path===Tn;return l.jsxs("button",{type:"button",onClick:()=>{P(se.path),ce(!1)},className:`flex w-full items-center gap-2 px-3 py-2 text-left transition-colors hover:bg-bg-hover ${$e?"text-text-primary":"text-text-secondary"}`,title:se.path,children:[l.jsx(Jp,{size:12,className:"shrink-0 text-text-tertiary"}),l.jsxs("span",{className:"min-w-0 flex-1",children:[l.jsx("span",{className:"block truncate text-[13px]",children:se.name}),l.jsx("span",{className:"block truncate text-[12px] text-text-tertiary",children:se.branch||se.path})]}),$e&&l.jsx(gr,{size:12,className:"shrink-0 text-text-primary"})]},se.path)}),_e&&l.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 text-[12px] text-text-tertiary",children:[l.jsx(yt,{size:12,className:"animate-spin"}),n("agents.input.directory.loading")]}),l.jsxs("button",{type:"button",onClick:()=>{ce(!1),Ae(!0)},className:"flex w-full items-center gap-2 px-3 py-2 text-left text-[13px] text-text-secondary transition-colors hover:bg-bg-hover hover:text-text-primary",children:[l.jsx(IM,{size:12,className:"shrink-0 text-text-tertiary"}),n("agents.input.directory.browse")]})]}),l.jsx(WN,{options:os,value:Br,label:Je,disabled:an,open:J,onOpenChange:se=>{he(se),se&&(oe(!1),pe(null),G(null))},onSelect:se=>{U(se),rm(se)},noDescriptionText:n("mainAgent.noDescription"),customTagText:n("mainAgent.customTag"),title:n("agents.input.agent")})]}),l.jsx("div",{className:"composer-input-wrap pb-[env(safe-area-inset-bottom)] md:pb-0",children:l.jsxs("div",{className:`composer-card relative overflow-visible transition-colors ${et?"composer-card-dragging":""}`,onDragEnter:K,onDragLeave:xe,onDragOver:Pe,onDrop:ft,children:[et&&l.jsx("div",{className:"pointer-events-none absolute inset-0 z-20 flex items-center justify-center rounded-[22px] bg-accent-brand/5",children:l.jsx("span",{className:"text-[14px] font-medium text-accent-brand",children:n("input.dropHint")})}),l.jsx("input",{ref:Le,type:"file",accept:"*/*",multiple:!0,className:"hidden",onChange:se=>{se.target.files&&Qn(Array.from(se.target.files)),se.target.value=""}}),xn&&l.jsxs("div",{className:"flex flex-wrap gap-2 px-3 pt-1",children:[gt.map(se=>l.jsxs("div",{className:"group relative",children:[l.jsx("img",{src:se.dataUrl,alt:"",className:"h-16 w-16 rounded-lg border border-border-default object-cover"}),l.jsx("button",{type:"button",onClick:()=>Nt(se.id),className:"absolute -right-1.5 -top-1.5 flex h-5 w-5 items-center justify-center rounded-full border border-border-default bg-bg-tertiary opacity-0 transition-opacity hover:border-accent-red hover:bg-accent-red hover:text-white group-hover:opacity-100",children:l.jsx(Bt,{size:12})})]},se.id)),Array.from({length:qt}).map((se,$e)=>l.jsx("div",{className:"h-16 w-16 rounded-lg border border-border-default skeleton-shimmer"},`skeleton-${$e}`)),$t.map(se=>l.jsxs("div",{className:"group relative flex max-w-[200px] items-center gap-2 rounded-lg border border-border-default bg-bg-primary px-3 py-2",children:[l.jsx(Pi,{size:16,className:"shrink-0 text-text-tertiary"}),l.jsxs("div",{className:"min-w-0 flex-1",children:[l.jsx("div",{className:"truncate text-[12px] text-text-primary",title:se.name,children:se.name}),l.jsx("div",{className:"text-[11px] text-text-tertiary",children:PN(se.size)})]}),l.jsx("button",{type:"button",onClick:()=>Vn(se.id),className:"flex h-4 w-4 shrink-0 items-center justify-center rounded-full text-text-tertiary opacity-0 transition-opacity hover:text-accent-red group-hover:opacity-100",children:l.jsx(Bt,{size:12})})]},se.id))]}),l.jsx("div",{className:"relative",children:l.jsx("textarea",{ref:ie,value:x,onChange:se=>k(se.target.value),onKeyDown:Ke,onPaste:Vt,placeholder:n(an?"agents.input.shellPlaceholder":"agents.input.placeholder"),rows:1,enterKeyHint:"send","aria-label":n("agents.input.placeholder"),className:"composer-textarea composer-textarea-hero"})}),l.jsxs("div",{className:"composer-toolbar",onClick:se=>{var $e;se.target===se.currentTarget&&(($e=ie.current)==null||$e.focus())},children:[l.jsxs("div",{className:"composer-tools",children:[l.jsx("button",{type:"button",onClick:()=>{var se;oe(!1),pe(null),G(null),(se=Le.current)==null||se.click()},className:"composer-add",title:n("input.addFile"),"aria-label":n("input.addFile"),children:l.jsx(is,{size:16})}),l.jsxs("div",{ref:X,className:"relative min-w-0 shrink",children:[l.jsxs("button",{type:"button",disabled:an,onClick:()=>{an||(pe(se=>se==="permission"?null:"permission"),oe(!1),G(null))},className:"composer-chip",title:n("agents.input.permission"),"aria-expanded":ne==="permission",children:[l.jsx(QD,{size:14,className:"shrink-0"}),l.jsx("span",{className:"min-w-0 truncate",children:vn}),l.jsx(sr,{size:12,className:`shrink-0 text-text-tertiary transition-transform ${ne==="permission"?"rotate-180":""}`})]}),ne==="permission"&&!an&&l.jsx("div",{className:"composer-menu absolute bottom-full left-0 z-50 mb-2 max-h-[280px] w-[240px] max-w-[calc(100vw-24px)] overflow-y-auto py-1",children:Qe.map(se=>l.jsxs("button",{type:"button",role:"menuitemradio","aria-checked":se.value===w,onClick:()=>{L(se.value),se.value&&lf(se.value),pe(null)},className:"flex w-full items-center gap-2 rounded-[10px] px-2.5 py-2 text-left text-[13px] text-text-secondary transition-colors hover:bg-bg-hover hover:text-text-primary",title:se.description,children:[l.jsx("span",{className:"min-w-0 flex-1 truncate",children:se.label}),se.value===w&&l.jsx(gr,{size:12,className:"shrink-0 text-text-primary"})]},se.value))})]}),l.jsxs("div",{ref:fe,className:"relative shrink-0",children:[l.jsx("button",{type:"button",onClick:()=>{an||(oe(se=>!se),pe(null),G(null))},disabled:an,className:"composer-add",title:n("agents.input.settings"),"aria-label":n("agents.input.settings"),"aria-expanded":V,children:l.jsx(V1,{size:15})}),V&&!an&&l.jsx("div",{className:"composer-menu absolute bottom-full left-0 z-50 mb-2 max-h-[320px] w-[264px] max-w-[calc(100vw-24px)] overflow-y-auto overscroll-contain py-1",role:"menu","aria-label":n("agents.input.settings"),children:l.jsxs("div",{className:"px-1",children:[l.jsxs("button",{type:"button",onClick:()=>{u&&(oe(!1),pe(null),f(!0))},disabled:!u,className:"flex w-full items-center gap-2 rounded-md px-2 py-2 text-left text-text-secondary transition-colors hover:bg-bg-hover hover:text-text-primary disabled:cursor-not-allowed disabled:opacity-40",title:n(u?"agents.input.startFrom":"agents.input.startFrom.unavailable"),children:[l.jsx(P1,{size:13,className:"shrink-0 text-text-tertiary"}),l.jsx("span",{className:"min-w-0 flex-1 truncate text-[13px]",children:n("agents.input.startFrom")}),l.jsx("span",{className:"max-w-[116px] truncate text-[12px] text-text-tertiary",children:Rr}),l.jsx(sr,{size:11,className:"shrink-0 -rotate-90 text-text-tertiary"})]}),l.jsxs("button",{type:"button",role:"switch","aria-checked":R,onClick:()=>$(se=>!se),className:"flex w-full items-center gap-2 rounded-md px-2 py-2 text-left text-text-secondary outline-none transition-colors hover:bg-bg-hover hover:text-text-primary",title:n(R?"agents.input.worktree.on":"agents.input.worktree.off"),children:[l.jsx(Jp,{size:13,className:"shrink-0 text-text-tertiary"}),l.jsx("span",{className:"min-w-0 flex-1 truncate text-[13px]",children:n("agents.input.worktree")}),l.jsx("span",{className:`relative h-3 w-5 shrink-0 overflow-hidden rounded-full transition-colors ${R?"bg-text-primary":"bg-border-default"}`,children:l.jsx("span",{className:`absolute left-0.5 top-0.5 h-2 w-2 rounded-full bg-bg-card transition-transform ${R?"translate-x-2":"translate-x-0"}`})})]})]})}),l.jsx(_J,{targetCwd:ee||_||""})]}),an&&l.jsxs("span",{className:"flex h-7 items-center gap-1 px-1 text-[13px] text-text-tertiary",children:[l.jsx(Xo,{size:13}),n("agents.input.shellJob")]})]}),l.jsxs("div",{className:"composer-trailing",children:[l.jsx("div",{ref:Ce,className:"min-w-0",children:l.jsx(CJ,{model:xJ(s,N||"",n("agents.input.model.default")),title:n("agents.input.model"),open:H==="model",onToggle:()=>{G(H==="model"?null:"model"),oe(!1),pe(null)},options:ze,value:N||"",onSelect:le,disabled:an,canEditThinking:Ot,thinkingEditModelId:de,onPreviewThinking:F,onClearThinkingEdit:()=>F(null),thinkingOptions:rt,thinkingValue:Q||"",onSelectThinking:Ne})}),l.jsx("button",{type:"button",onClick:()=>tt(),disabled:C||!jr&&!xn,className:"composer-send",title:n("agents.input.submit"),"aria-label":n("agents.input.submit"),children:C?l.jsx(yt,{size:14,className:"animate-spin"}):l.jsx(ic,{size:18,strokeWidth:2.5})})]})]})]})}),ae&&l.jsx(NN,{initialPath:ee||_||"/",onSelect:se=>{P(se),Ae(!1)},onClose:()=>Ae(!1)})]})}function IJ({children:e}){return l.jsx("code",{className:"bg-bg-tertiary px-1.5 py-0.5 rounded text-xs text-accent-brand",children:e})}function n1(e){const t=[];let n=e,r=0;for(;n.length>0;){const i=n.indexOf("<code>");if(i===-1){t.push(l.jsx("span",{children:n},r));break}i>0&&(t.push(l.jsx("span",{children:n.substring(0,i)},r)),r++);const s=n.indexOf("</code>",i);if(s===-1){t.push(l.jsx("span",{children:n},r));break}const a=n.substring(i+6,s);t.push(l.jsx(IJ,{children:a},r)),r++,n=n.substring(s+7)}return l.jsx(l.Fragment,{children:t})}function TJ(){const{error:e,isSubmitting:t,login:n,clearError:r}=Zr(),{t:i}=Re(),[s,a]=g.useState(""),o=g.useCallback(async d=>{d.preventDefault(),s.trim()&&await n(s)},[s,n]),c=e?i(e)!==e?i(e):e:null;return l.jsxs("div",{className:"login-page",children:[l.jsxs("div",{className:"login-orb login-orb-right",children:[l.jsx("div",{className:"login-orb-layer login-orb-layer-1"}),l.jsx("div",{className:"login-orb-layer login-orb-layer-2"})]}),l.jsx("div",{className:"login-ellipse login-ellipse-outer"}),l.jsx("div",{className:"login-ellipse login-ellipse-outer2"}),l.jsx("div",{className:"login-ellipse login-ellipse-inner"}),l.jsxs("div",{className:"login-orb login-orb-left",children:[l.jsx("div",{className:"login-orb-layer login-orb-layer-1"}),l.jsx("div",{className:"login-orb-layer login-orb-layer-2"})]}),l.jsx("div",{className:"login-ellipse login-ellipse-left"}),l.jsx("div",{className:"login-ellipse login-ellipse-left2"}),l.jsxs("div",{className:"login-content",children:[l.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",gap:"16px"},children:[l.jsx("div",{className:"login-logo",children:l.jsx("img",{src:cf,alt:"CodeBuddy"})}),l.jsx("h1",{className:"login-title",children:i("login.slogan")}),l.jsx("p",{className:"login-tagline",children:i("login.tagline")})]}),l.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",gap:"4px"},children:[c&&l.jsx("div",{className:"login-error",style:{marginBottom:"8px"},children:c}),l.jsxs("form",{onSubmit:o,style:{display:"flex",flexDirection:"column",alignItems:"center",gap:"8px"},children:[l.jsx("input",{type:"password",name:"password",value:s,onChange:d=>{a(d.target.value),e&&r()},placeholder:i("login.placeholder"),autoFocus:!0,autoComplete:"current-password",disabled:t,className:"login-input"}),l.jsx("button",{type:"submit",disabled:t||!s.trim(),className:"login-btn",children:t?l.jsx("span",{className:"thinking-text",children:i("login.submit")}):i("login.submit")})]}),l.jsxs("div",{className:"login-hints",children:[l.jsx("p",{children:i("login.hint.password")}),l.jsx("p",{children:i("login.hint.urlAuth").includes("<code>")?n1(i("login.hint.urlAuth")):i("login.hint.urlAuth")}),l.jsx("p",{children:i("login.hint.disable").includes("<code>")?n1(i("login.hint.disable")):i("login.hint.disable")})]})]})]}),l.jsxs("div",{className:"login-footer",children:[l.jsx("a",{href:"#privacy",children:i("login.privacy")}),l.jsx("a",{href:"#terms",children:i("login.terms")})]})]})}function NJ({sessionId:e}){const{t,tryT:n}=Re(),[r,i]=g.useState(!1),s=nt(E=>E.backendSupport),a=ew(s),{agents:o,currentAgentName:c,sessionBlank:d,status:u,error:h,applyAgentFromResponse:p,applySetAgentResult:m,setLoading:f,setError:b}=nt(),_=nt(E=>E.stagedAgent),v=nt(E=>E.processAgent),A=c||_||v||"cli",S=o.find(E=>E.name===A),y=S?`${Es(S,n)}${S.custom?` · ${t("mainAgent.trustLocal")}`:""}`:Es({name:A},n),x=S?Qo(S,n):void 0;g.useEffect(()=>{if(!r||!e||s!==!0)return;let E=!1;return f(),st().callExtMethod("_codebuddy.ai/getAgents",{sessionId:e}).then(N=>{!E&&(N!=null&&N.agents)&&p({agents:N.agents,currentAgentName:N.currentAgentName,defaultAgentName:N.defaultAgentName,sessionBlank:N.sessionBlank})}).catch(N=>{E||b(N instanceof Error?N.message:String(N))}),()=>{E=!0}},[r,e,s,f,b,p]);const k=g.useCallback(async E=>{if(!(!e||E===c)){rm(E),fC(),f();try{const N=await st().callExtMethod("session/set_agent",{sessionId:e,agentName:E});if(N!=null&&N.agentName){m({agentName:N.agentName,models:N.models??[],currentModelId:N.currentModelId??"",sessionBlank:N.sessionBlank??!1});const z=N.models??[];Array.isArray(z)&&Ge.getState().setModels(z.map(Q=>{var T,w;return{id:Q.modelId??Q.id,name:Q.name||Q.modelId||Q.id,description:Q.description??null,credits:((T=Q._meta)==null?void 0:T.credits)??null,contextWindow:((w=Q._meta)==null?void 0:w.maxInputTokens)??null}})),N.currentModelId&&Ge.getState().setCurrentModel(N.currentModelId),rm(E)}}catch(N){b(N instanceof Error?N.message:String(N)),i(!0)}}},[e,c,f,b,m]);if(!a.enabled)return null;const C=o.map(E=>({value:E.name,label:Es(E,n),description:Qo(E,n),custom:E.custom,source:E.source,broken:E.broken}));return d?l.jsx(WN,{options:C,value:A,label:y,open:r,onOpenChange:i,onSelect:E=>{k(E).catch(()=>{})},error:u==="error"?h:null,emptyText:t("mainAgent.empty"),noDescriptionText:t("mainAgent.noDescription"),customTagText:t("mainAgent.customTag"),title:x||t("mainAgent.selectAgent")}):l.jsx(RN,{tone:"seat"})}const RJ=300,LJ=5e3;function MJ(){const{t:e}=Re(),t=qi(S=>S.visible),n=qi(S=>S.total),r=qi(S=>S.completed),i=qi(S=>S.connectingServers),s=qi(S=>S.startedAt),a=qi(S=>S.finished),o=qi(S=>S.failed),c=qi(S=>S.timedOut),d=qi(S=>S.hide),[u,h]=g.useState(!1),p=g.useRef(void 0),[,m]=g.useState(0),[f,b]=g.useState(!1);g.useEffect(()=>(t?(p.current&&clearTimeout(p.current),p.current=setTimeout(()=>{h(!0),p.current=void 0},RJ)):(p.current&&(clearTimeout(p.current),p.current=void 0),h(!1)),()=>{p.current&&(clearTimeout(p.current),p.current=void 0)}),[t]),g.useEffect(()=>{if(!a||!t||f)return;const S=setTimeout(()=>d(),LJ);return()=>clearTimeout(S)},[a,t,f,d]);const _=u&&(i.length>0||a);g.useEffect(()=>{if(!_||a||s===void 0)return;const S=setInterval(()=>m(y=>(y+1)%1e6),1e3);return()=>clearInterval(S)},[_,a,s]);const v=g.useMemo(()=>{if(!_)return null;if(a){if(o.length===0&&c.length===0)return{tone:"ok",text:e("mcp.startup.ready",{total:n})};const E=[];return o.length>0&&E.push(e("mcp.startup.failed",{names:o.join(", ")})),c.length>0&&E.push(e("mcp.startup.timedOut",{names:c.join(", ")})),{tone:"warn",text:E.join(" · ")}}const S=3,y=i.slice(0,S).join(", ")+(i.length>S?", …":""),x=s===void 0?0:Math.max(0,Math.floor((Date.now()-s)/1e3)),k=e("mcp.startup.elapsed",{seconds:x});return{tone:"busy",text:`${n===1&&i.length===1?e("mcp.startup.booting",{name:i[0]}):e("mcp.startup.starting",{completed:r,total:n,names:y})} (${k})`}},[_,a,o,c,i,n,r,s,e]);if(!v)return null;const A=v.tone==="busy"?"animate-pulse bg-accent-brand":v.tone==="ok"?"bg-accent-green":"bg-accent-yellow";return l.jsx("div",{className:"max-w-3xl mx-auto px-3 pb-1 md:px-0",children:l.jsxs("div",{className:"flex items-center gap-2 text-xs text-text-secondary",onMouseEnter:()=>b(!0),onMouseLeave:()=>b(!1),children:[l.jsx("span",{className:`inline-block h-1.5 w-1.5 flex-shrink-0 rounded-full ${A}`}),l.jsx("span",{className:"truncate",children:v.text})]})})}const DJ="data:image/svg+xml,%3csvg%20width='24'%20height='24'%20viewBox='0%200%2024%2024'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3cg%20clip-path='url(%23copilot-clip-34e811bed903495093b85bf96a98fb1b_0)'%3e%3crect%20width='24'%20height='24'%20rx='12'%20fill='%234C4F6B'%3e%3c/rect%3e%3cpath%20d='M3.4689%2011.0144C3.32344%2011.2025%203.31607%2011.4567%203.4345%2012.0298C3.65883%2013.0748%204.24029%2014.4426%205.15579%2016.0716L5.747%2017.1172L5.72862%2017.511C5.70544%2017.9326%205.72848%2018.5857%205.77921%2019.0271C5.80994%2019.2967%205.8055%2019.3035%205.66483%2019.4638C5.12042%2020.0864%205.03916%2021.1287%205.44787%2022.2839C5.62456%2022.7775%206.16958%2023.6999%206.50726%2024.0756C7.35392%2025.0154%208.35051%2025.4646%209.11147%2025.246C9.25446%2025.2051%209.28403%2025.213%209.47117%2025.3424C10.182%2025.8233%2011.3834%2026.2377%2012.4447%2026.3663C14.2242%2026.5843%2016.2727%2026.143%2018.8281%2024.9925C19.8948%2024.5099%2022.2541%2023.1352%2023.2513%2022.4096C25.1083%2021.0667%2026.4805%2019.6414%2027.251%2018.2635C27.9337%2017.0364%2028.2735%2015.7781%2028.2495%2014.5174C28.2466%2014.2525%2028.2536%2014.2359%2028.3599%2014.1746C28.8797%2013.8703%2029.1497%2013.198%2029.0927%2012.3562C29.075%2012.1165%2029.0266%2011.7946%2028.9902%2011.6448C28.7404%2010.7144%2028.0885%209.59971%2027.4078%208.94729C26.6515%208.22182%2025.7943%207.9129%2025.1958%208.14598C25.0631%208.19758%2025.0452%208.19542%2024.9177%208.08995C24.6357%207.86124%2023.9604%207.43473%2023.5488%207.22673L23.1224%207.01477L22.8206%206.45595C22.0392%205.01609%2020.7826%203.33003%2019.8801%202.50992C19.4937%202.15818%2019.2668%202.03929%2019.019%202.05739C18.866%202.06657%2018.8535%202.07379%2018.645%202.26084C18.0389%202.79819%2017.1889%204.41355%2016.3588%206.60463L16.1271%207.21325L15.7053%207.34845C14.3909%207.76995%2013.2238%208.30219%2012.1896%208.94928C11.1973%209.56799%2010.6591%209.97037%209.84886%2010.688L9.36087%2011.1197L9.13878%2011.0813C7.00072%2010.7039%205.07892%2010.5639%204.19776%2010.7186C3.84772%2010.7832%203.55743%2010.9008%203.4689%2011.0144Z'%20fill='%23D2D3E0'%3e%3c/path%3e%3crect%20x='6.68555'%20y='16.3788'%20width='17.7918'%20height='11.5605'%20rx='4.61469'%20transform='rotate(-30%206.68555%2016.3788)'%20fill='%23212234'%3e%3c/rect%3e%3cg%3e%3crect%20x='12.2119'%20y='17.2593'%20width='2.13173'%20height='4.42744'%20rx='1.06587'%20transform='rotate(-30%2012.2119%2017.2593)'%20fill='%23D2D3E0'%3e%3canimate%20attributeName='height'%20values='4.42744;2.2;4.42744;4.42744;2.2;4.42744'%20dur='0.6s'%20begin='0s;blink134e811bed903495093b85bf96a98fb1b_0.end+3s'%20id='blink134e811bed903495093b85bf96a98fb1b_0'%3e%3c/animate%3e%3canimate%20attributeName='y'%20values='17.2593;18.2593;17.2593;17.2593;18.2593;17.2593'%20dur='0.6s'%20begin='0s;blink134e811bed903495093b85bf96a98fb1b_0.end+3s'%3e%3c/animate%3e%3canimate%20attributeName='opacity'%20values='1;0.2;1;1;0.2;1'%20dur='0.6s'%20begin='0s;blink134e811bed903495093b85bf96a98fb1b_0.end+3s'%3e%3c/animate%3e%3c/rect%3e%3c/g%3e%3cg%3e%3crect%20x='17.9634'%20y='13.9387'%20width='2.13173'%20height='4.42744'%20rx='1.06587'%20transform='rotate(-30%2017.9634%2013.9387)'%20fill='%23D2D3E0'%3e%3canimate%20attributeName='height'%20values='4.42744;2.2;4.42744;4.42744;2.2;4.42744'%20dur='0.6s'%20begin='0s;blink234e811bed903495093b85bf96a98fb1b_0.end+3s'%20id='blink234e811bed903495093b85bf96a98fb1b_0'%3e%3c/animate%3e%3canimate%20attributeName='y'%20values='13.9387;14.9387;13.9387;13.9387;14.9387;13.9387'%20dur='0.6s'%20begin='0s;blink234e811bed903495093b85bf96a98fb1b_0.end+3s'%3e%3c/animate%3e%3canimate%20attributeName='opacity'%20values='1;0.2;1;1;0.2;1'%20dur='0.6s'%20begin='0s;blink234e811bed903495093b85bf96a98fb1b_0.end+3s'%3e%3c/animate%3e%3c/rect%3e%3c/g%3e%3c/g%3e%3cdefs%3e%3cclipPath%20id='copilot-clip-34e811bed903495093b85bf96a98fb1b_0'%3e%3crect%20width='24'%20height='24'%20rx='12'%20fill='white'%3e%3c/rect%3e%3c/clipPath%3e%3c/defs%3e%3c/svg%3e",$J="data:image/svg+xml,%3csvg%20width='873'%20height='612'%20viewBox='0%200%20873%20612'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M611.24%200C631.42%200.472994%20652.67%200.151247%20672.917%200.149414L783.53%200.125977L783.58%20114.446C783.58%20131.188%20782.828%20155.62%20783.732%20171.959C793.764%20172.165%20866.262%20170.817%20869.239%20173.294C869.728%20173.699%20870.138%20174.379%20870.486%20174.905L872.008%20175.384C873.402%20179.664%20872.344%20228.902%20872.338%20236.71C872.313%20263.731%20873.157%20518.745%20871.959%20521.349C871.837%20521.605%20871.58%20521.905%20871.415%20522.119L869.141%20522.375C841.374%20521.684%20811.566%20522.247%20783.646%20522.271C784.001%20538.325%20783.695%20555.229%20783.72%20571.344C783.738%20583.932%20784.056%20598.74%20783.451%20611.182C613.783%20610.846%20273.598%20611.469%2087.6807%20611.041C87.3452%20610.736%2087.0093%20610.436%2086.6738%20610.137L86.2393%20607.375C86.831%20602.028%2086.4052%20585.668%2086.3984%20579.416L86.2812%20521.838C82.9453%20522.522%2063.9127%20522.272%2059.0283%20522.266L0.391602%20522.259L0.398438%20278.798L0.427734%20209.334C0.430803%20201.523%200.934097%20181.445%200%20174.62C0.578928%20172.779%200.0735528%20173.48%201.33105%20172.293C17.2444%20171.377%2036.4875%20172.458%2052.7188%20172.065C59.0087%20171.913%2081.4327%20171.805%2086.0195%20172.717L85.9805%2056.9336L85.9072%2021.3467C85.895%2015.7024%2085.6474%205.58945%2086.2832%200.297852L89.3057%200.0224609C145.847%201.00635%20204.767%200.149918%20261.493%200.137695L261.571%2058.8008C261.576%2063.634%20261.865%2082.5764%20261.06%2086.293C288.984%2085.6006%20319.108%2086.1736%20347.17%2086.1797L509.068%2086.1846L576.67%2086.1357C582.985%2086.1314%20604.124%2085.7374%20608.728%2086.8135C607.982%2081.7879%20608.33%2064.0733%20608.33%2058.0186L608.428%201.34473C609.424%20-0.0534957%20608.978%200.391111%20611.24%200ZM697.12%20173.048C694.553%20171.797%20619.805%20172.389%20610.134%20172.389L279.41%20172.397L201.266%20172.392C193.899%20172.39%20184.497%20172.27%20176.995%20172.399C175.636%20172.423%20175.324%20173.65%20174.702%20174.81L172.704%20175.383C172.033%20177.999%20172.341%20204.836%20172.348%20208.9L172.398%20294.312L172.37%20445.969L172.349%20494.032C172.347%20501.781%20172.011%20513.954%20172.658%20521.324C174.533%20523.401%20174.111%20521.52%20174.854%20522.534C175.611%20523.561%20175.655%20525.034%20177.928%20525.016C181.545%20524.988%20185.335%20524.97%20189.044%20524.966H347.752L604.785%20524.96L669.054%20525.009C673.406%20525.009%20693.575%20525.296%20696.857%20524.643C697.499%20523.408%20697.493%20523.505%20697.542%20522.118C696.815%20500.607%20697.389%20475.931%20697.389%20454.243V327.045L697.383%20228.248C697.383%20211.843%20696.729%20190.781%20697.64%20174.935L697.12%20173.048Z'%20fill='%2300BC90'/%3e%3cpath%20d='M347.56%20260.864L349.808%20261.441C351.42%20265.483%20350.329%20418.222%20350.229%20435.792C344.53%20436.85%20263.503%20436.929%20260.894%20435.722L261.464%20433.765C261.114%20420.392%20261.416%20405.532%20261.413%20392.005L261.412%20313.381C261.422%20299.699%20262.22%20276.275%20261.106%20263.652C261.428%20261.859%20261.059%20262.619%20262.19%20261.257C268.232%20260.664%20277.082%20261.319%20283.456%20261.111C303.554%20260.454%20327.973%20262.241%20347.56%20260.864Z'%20fill='%2300BC90'/%3e%3cpath%20d='M608.752%20260.881L610.641%20261.353C612.854%20266.169%20610.268%20347.019%20611.302%20358.962C611.693%20363.539%20611.436%20434.199%20610.892%20435.767C610.293%20435.847%20609.248%20436.027%20608.685%20436.028C584.88%20436.436%20548.549%20435.89%20523.533%20435.943C522.702%20435.945%20522.567%20435.098%20522.127%20434.149C522.787%20429.284%20522.445%20415.565%20522.445%20410.114L522.415%20362.246L522.457%20298.316C522.463%20288.598%20522.94%20272.837%20522.097%20263.668L522.586%20261.78C525.887%20259.891%20595.756%20261.699%20608.752%20260.881Z'%20fill='%2300BC90'/%3e%3c/svg%3e";function OJ({isOpen:e,onClose:t,mainView:n,onNavigate:r,remoteControlEnabled:i}){const{t:s}=Re(),{userInfo:a}=yC(),o=Jr(m=>m.info),c=Jr(m=>m.fetch),d=ui(m=>m.fileChanges.length);g.useEffect(()=>{o||c()},[c,o]);const u=(a==null?void 0:a.userName)||(o==null?void 0:o.userName)||s("sidebar.user"),h=Zr(m=>m.accountState),p=g.useCallback(async()=>{window.confirm(s("account.logout.confirm"))&&await Zr.getState().accountLogout()},[s]);return l.jsxs(l.Fragment,{children:[l.jsx("div",{className:`sidebar-overlay ${e?"":"sidebar-overlay-hidden"}`,onClick:t}),l.jsxs("aside",{className:`sidebar ${e?"":"sidebar-closed"}`,role:"navigation","aria-label":"Main navigation",children:[l.jsxs("div",{className:"sidebar-header",children:[l.jsx("img",{src:$J,alt:"CodeBuddy",className:"sidebar-logo"}),l.jsx("span",{className:"sidebar-brand",children:"CodeBuddy"}),l.jsx("div",{className:"flex-1"}),l.jsx("button",{onClick:t,className:"flex h-7 w-7 items-center justify-center rounded-md text-text-tertiary transition-colors hover:bg-bg-hover hover:text-text-primary md:hidden","aria-label":"Close sidebar",children:l.jsx(Bt,{size:16})})]}),l.jsxs("nav",{className:"sidebar-nav","aria-label":"Primary",children:[l.jsxs("button",{className:`sidebar-nav-item ${n==="chat"?"active":""}`,onClick:()=>r("chat"),"aria-current":n==="chat"?"page":void 0,title:s("sidebar.chatMode"),children:[l.jsx(Jo,{size:16}),l.jsx("span",{children:s("sidebar.chatMode")})]}),l.jsxs("button",{className:`sidebar-nav-item ${n==="workers"?"active":""}`,onClick:()=>r("workers"),title:s("sidebar.workers"),children:[l.jsx($1,{size:16}),l.jsx("span",{children:s("sidebar.workers")})]}),i&&l.jsxs("button",{className:`sidebar-nav-item ${n==="remote-control"?"active":""}`,onClick:()=>r("remote-control"),title:s("sidebar.remoteControl"),children:[l.jsx(q1,{size:16}),l.jsx("span",{children:s("sidebar.remoteControl")})]})]}),l.jsx("div",{className:"sidebar-content",children:l.jsxs("div",{className:"px-3 py-1",children:[l.jsx("div",{className:"sidebar-section-title",children:s("sidebar.group.workspace")}),l.jsxs("button",{className:`sidebar-nav-item ${n==="tasks"?"active":""}`,onClick:()=>r("tasks"),title:s("sidebar.nav.tasks"),children:[l.jsx(Xg,{size:16}),l.jsx("span",{children:s("sidebar.nav.tasks")})]}),l.jsxs("button",{className:`sidebar-nav-item ${n==="terminal"?"active":""}`,onClick:()=>r("terminal"),title:s("sidebar.terminalMode"),children:[l.jsx(Xo,{size:16}),l.jsx("span",{children:s("sidebar.terminalMode")})]}),l.jsxs("button",{className:`sidebar-nav-item ${n==="canvas"?"active":""}`,onClick:()=>r("canvas"),title:s("sidebar.canvas"),children:[l.jsx(z1,{size:16}),l.jsx("span",{children:s("sidebar.canvas")})]}),l.jsxs("button",{className:`sidebar-nav-item ${n==="editor"?"active":""}`,onClick:()=>r("editor"),title:s("sidebar.editor"),children:[l.jsx(Jg,{size:16}),l.jsx("span",{children:s("sidebar.editor")})]}),l.jsxs("button",{className:`sidebar-nav-item ${n==="changes"?"active":""}`,onClick:()=>r("changes"),title:s("sidebar.changes"),children:[l.jsx(Gu,{size:16}),l.jsx("span",{children:s("sidebar.changes")}),d>0&&l.jsx("span",{className:"sidebar-badge",children:d})]}),l.jsxs("button",{className:`sidebar-nav-item ${n==="plugins"?"active":""}`,onClick:()=>r("plugins"),title:s("sidebar.nav.plugins"),children:[l.jsx(ja,{size:16}),l.jsx("span",{children:s("sidebar.nav.plugins")})]}),l.jsx("div",{className:"sidebar-section-title",children:s("sidebar.group.observability")}),l.jsxs("button",{className:`sidebar-nav-item ${n==="stats"?"active":""}`,onClick:()=>r("stats"),title:s("sidebar.stats"),children:[l.jsx(M1,{size:16}),l.jsx("span",{children:s("sidebar.stats")})]}),l.jsxs("button",{className:`sidebar-nav-item ${n==="traces"?"active":""}`,onClick:()=>r("traces"),title:s("sidebar.traces"),children:[l.jsx(J1,{size:16}),l.jsx("span",{children:s("sidebar.traces")})]}),l.jsxs("button",{className:`sidebar-nav-item ${n==="metrics"?"active":""}`,onClick:()=>r("metrics"),title:s("sidebar.metrics"),children:[l.jsx(N1,{size:16}),l.jsx("span",{children:s("sidebar.metrics")})]}),l.jsxs("button",{className:`sidebar-nav-item ${n==="logs"?"active":""}`,onClick:()=>r("logs"),title:s("sidebar.logs"),children:[l.jsx(D1,{size:16}),l.jsx("span",{children:s("sidebar.logs")})]}),l.jsx("div",{className:"sidebar-section-title",children:s("sidebar.group.preferences")}),l.jsxs("button",{className:`sidebar-nav-item ${n==="settings"?"active":""}`,onClick:()=>r("settings"),title:s("sidebar.preferences"),children:[l.jsx(ef,{size:16}),l.jsx("span",{children:s("sidebar.preferences")})]}),l.jsxs("button",{className:`sidebar-nav-item ${n==="keybindings"?"active":""}`,onClick:()=>r("keybindings"),title:s("sidebar.keybindings"),children:[l.jsx(U1,{size:16}),l.jsx("span",{children:s("sidebar.keybindings")})]}),l.jsxs("button",{className:`sidebar-nav-item ${n==="docs"?"active":""}`,onClick:()=>r("docs"),title:s("sidebar.docs"),children:[l.jsx(L1,{size:16}),l.jsx("span",{children:s("sidebar.docs")})]})]})}),l.jsx("div",{className:"sidebar-footer",children:l.jsxs("div",{className:"sidebar-user",children:[l.jsx("img",{src:DJ,alt:"User",className:"sidebar-user-avatar"}),l.jsxs("div",{className:"sidebar-user-info",children:[l.jsx("div",{className:"sidebar-user-name",children:u}),(o==null?void 0:o.version)&&l.jsxs("div",{className:"sidebar-user-status",children:["v",o.version]})]}),h==="authenticated"&&l.jsx("button",{onClick:p,className:"w-7 h-7 flex items-center justify-center rounded-md text-text-tertiary hover:text-text-primary hover:bg-bg-hover transition-colors ml-auto",title:s("account.logout"),"aria-label":s("account.logout"),children:l.jsx(YM,{size:14})})]})})]})]})}function PJ({onMenuClick:e,sessionsPanelOpen:t=!0,onSplitTerminal:n,onHistory:r,onNewChat:i,onCancelNewAgent:s,onToggleSessionsPanel:a,rightActions:o,newAgentMode:c=!1,agentTransitionMode:d=null,agentFrameNeedsInput:u=null,conversationTitleOverride:h}){const{t:p}=Re(),{topic:m,sessionId:f,sessionSwitching:b}=Ge(),_=tn(J=>J.jobs),v=tn(J=>J.selectedJobId),A=tn(J=>J.selectedJobTitle),{mainChatActive:S,mainAgentSessionId:y,agentSessionIds:x}=en(),{isAgentRunning:k,hasPendingInterruption:C,timeline:E}=ot(),{mainView:N,layout:z,terminalTitle:Q}=zt(),[T,w]=g.useState(!1),L=g.useRef(null),I=N==="terminal",$=Fo(z)<RC,D=S?void 0:_.find(J=>J.id===v),U=g.useMemo(()=>new Set(E.flatMap(J=>J.type==="question"&&J.status==="pending"?J.sessionId?[J.sessionId]:[]:J.type==="interruption"&&!J.resolved?J.sessionId?[J.sessionId]:[]:[])),[E]),Y=S?y??f:v?x[v]??(D==null?void 0:D.sessionId)??null:null,ee=!!(Y&&U.has(Y)),P=!S&&u===!0,q=S?_.find(J=>!!(y??f)&&J.sessionId===(y??f)):void 0,ue=D??q,_e=h||bm(m)||p("chat.newChat"),ke=!S&&v?A||(D==null?void 0:D.name)||Ec((D==null?void 0:D.intent)||"")||p("agents.instanceFallback").replace("{id}",v.slice(0,8)):p("sessions.currentTitle"),H=()=>(ue==null?void 0:ue.state)==="failed"?p("agents.state.failed"):ee||P||S&&C||(ue==null?void 0:ue.status)==="waiting"||(ue==null?void 0:ue.state)==="blocked"||ue!=null&&ue.waitingFor?p("agents.group.attention"):S&&k||(ue==null?void 0:ue.status)==="busy"||(ue==null?void 0:ue.tempo)==="active"||(ue==null?void 0:ue.state)==="working"&&(ue==null?void 0:ue.status)!=="idle"&&(ue==null?void 0:ue.tempo)!=="idle"?p("agents.group.working"):(ue==null?void 0:ue.state)==="stopped"?p("agents.state.stopped"):(ue==null?void 0:ue.state)==="done"||ue!=null&&ue.settled?p("agents.state.completed"):p("agents.state.idle");g.useEffect(()=>{if(!T)return;const J=he=>{L.current&&!L.current.contains(he.target)&&w(!1)};return document.addEventListener("mousedown",J),()=>document.removeEventListener("mousedown",J)},[T]);const G=g.useCallback(J=>{w(!1),n==null||n(J)},[n]),V=()=>{switch(N){case"chat":return c?p("agents.action.new"):ke;case"terminal":return Q||p("terminal.title");case"settings":return p("settings.title");case"tasks":return p("scheduled.title");case"plugins":return p("sidebar.nav.plugins");case"workers":return p("workers.title");case"metrics":return p("sidebar.metrics");case"logs":return p("sidebar.logs");case"docs":return p("sidebar.docs");case"remote-control":return p("sidebar.remoteControl");case"keybindings":return p("keybindings.title");default:return""}},oe=()=>o||(I?l.jsxs("div",{ref:L,className:"relative",children:[l.jsx("button",{onClick:()=>$&&w(!T),className:`text-text-secondary transition-colors flex items-center justify-center w-8 h-8 rounded-full ${$?"hover:text-text-primary hover:bg-bg-secondary":"opacity-40 cursor-not-allowed"}`,title:$?void 0:p("terminal.maxPanes"),"aria-label":p("terminal.split"),children:l.jsx(sS,{size:20})}),T&&l.jsxs("div",{className:"absolute right-0 top-full mt-1 bg-bg-secondary border border-border-muted rounded-lg shadow-lg py-1 z-50 min-w-[140px]",children:[l.jsxs("button",{onClick:()=>G("horizontal"),className:"w-full flex items-center gap-3 px-4 py-2.5 text-[13px] text-text-primary hover:bg-bg-hover transition-colors",children:[l.jsx(sS,{size:16,className:"text-text-secondary"}),l.jsx("span",{children:p("terminal.splitHorizontal")})]}),l.jsxs("button",{onClick:()=>G("vertical"),className:"w-full flex items-center gap-3 px-4 py-2.5 text-[13px] text-text-primary hover:bg-bg-hover transition-colors",children:[l.jsx(OD,{size:16,className:"text-text-secondary"}),l.jsx("span",{children:p("terminal.splitVertical")})]})]})]}):N==="chat"?l.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[c&&s&&l.jsx("button",{onClick:s,className:"flex h-8 shrink-0 items-center whitespace-nowrap rounded-full px-3 text-[12px] text-text-tertiary transition-colors hover:bg-bg-hover hover:text-text-primary",title:`${p("agents.action.cancelNew")} (Esc)`,"aria-label":p("agents.action.cancelNew"),children:p("agents.action.cancelNew")}),i&&!c&&l.jsx("button",{onClick:i,disabled:!f||b,className:"flex h-8 w-8 items-center justify-center rounded-full text-text-tertiary transition-colors hover:bg-bg-hover hover:text-text-primary disabled:cursor-not-allowed disabled:opacity-40 disabled:hover:bg-transparent",title:p("agents.action.newConversation"),"aria-label":p("agents.action.newConversation"),children:l.jsx(sD,{size:17})}),l.jsx("button",{onClick:r,className:"flex h-8 w-8 items-center justify-center rounded-full text-text-tertiary transition-colors hover:bg-bg-hover hover:text-text-primary",title:p("sidebar.chatHistory"),"aria-label":p("sidebar.chatHistory"),children:l.jsx(PM,{size:17})})]}):null);return l.jsxs("div",{className:"sticky top-0 z-10 isolate grid h-14 flex-shrink-0 grid-cols-[minmax(0,1fr)_minmax(0,2fr)_minmax(0,1fr)] items-center border-b border-border-muted bg-bg-primary px-3 text-xs transition-colors duration-200 sm:px-4",role:"banner","aria-label":p("sidebar.status"),children:[l.jsxs("div",{className:"relative z-10 flex min-w-0 items-center gap-1",children:[e&&l.jsx("button",{type:"button",onClick:e,className:"flex h-8 w-8 shrink-0 items-center justify-center rounded-full text-text-tertiary transition-colors hover:bg-bg-hover hover:text-text-primary md:hidden","aria-label":p("layout.sidebar"),title:p("layout.sidebar"),children:l.jsx(W1,{size:18})}),N==="chat"&&a&&l.jsx("button",{type:"button",onClick:a,className:`flex h-8 w-8 shrink-0 items-center justify-center rounded-full transition-colors ${t?"bg-bg-hover text-text-primary":"text-text-tertiary hover:bg-bg-hover hover:text-text-primary"}`,"aria-label":p("layout.agents"),title:p("layout.agents"),"aria-pressed":t,children:l.jsx(Is,{size:18})})]}),l.jsxs("div",{className:"relative z-0 flex min-w-0 flex-col items-center justify-center px-3 text-center",children:[l.jsx("span",{className:"max-w-full truncate text-[14px] font-medium text-text-primary",children:V()}),N==="chat"&&l.jsx("span",{className:"mt-0.5 block max-w-full truncate text-[10px] text-text-tertiary","aria-live":"polite","aria-atomic":"true",children:c?p("agents.input.hint"):d==="creating"?p("agents.phase.starting"):d==="restoring"?p("agents.phase.resuming"):`${H()} · ${_e}`})]}),l.jsx("div",{className:"relative z-10 flex items-center justify-self-end",children:oe()})]})}let Wp=1e5;function BJ(e){if(!Array.isArray(e))return[];const t=[];let n=null;for(const r of e)if(r.sessionUpdate==="user_message_chunk"){n&&(t.push(n),n=null);const i=r.content,s=(i==null?void 0:i.text)||"";if(!s.trim())continue;t.push({type:"message",id:`member-msg-${++Wp}`,role:"user",content:s,timestamp:Date.now()})}else if(r.sessionUpdate==="agent_message_chunk"){const i=r.content;if((i==null?void 0:i.type)==="thinking")continue;const s=(i==null?void 0:i.text)||"";if(!s)continue;n?n={...n,content:n.content+s}:n={type:"message",id:`member-msg-${++Wp}`,role:"assistant",content:s,timestamp:Date.now()}}else if(r.sessionUpdate==="tool_call"){n&&(t.push(n),n=null);const s=(r._meta||{})["codebuddy.ai/toolName"]||"";t.push({type:"tool_call",id:r.toolCallId||`member-tc-${++Wp}`,name:r.title||s||r.kind||"tool",kind:r.kind||"other",toolName:s,input:r.rawInput||r.input,status:r.status==="completed"?"completed":r.status==="failed"?"failed":"running",locations:r.locations,content:r.content})}else if(r.sessionUpdate==="tool_call_update"){const i=t.findIndex(s=>s.type==="tool_call"&&s.id===r.toolCallId);if(i!==-1){const s=t[i];t[i]={...s,status:r.status==="completed"?"completed":r.status==="failed"?"failed":s.status,result:r.rawOutput||r.toolResult||s.result,...r.content!==void 0?{content:r.content}:{}}}}return n&&t.push(n),t}function jJ(){var p;const e=Ir(m=>m.focusedMemberName),t=Ir(m=>m.memberHistories),n=Ir(m=>m.members),r=Ir(m=>m.setFocusedMember),i=g.useRef(null),s=n.find(m=>m.name===e),a=e&&t[e]||[],o=g.useMemo(()=>BJ(a),[a]),c=g.useMemo(()=>Jx(o),[o]);g.useEffect(()=>{i.current&&(i.current.scrollTop=i.current.scrollHeight)},[c]);const d=g.useCallback(()=>{r(null)},[r]),u=(s==null?void 0:s.status)==="running"||(s==null?void 0:s.status)==="pending",{t:h}=Re();return l.jsxs("div",{ref:i,className:"absolute inset-0 overflow-y-auto overflow-x-hidden",children:[l.jsx("div",{className:"sticky top-0 z-10 bg-bg-primary/95 backdrop-blur-sm border-b border-border-muted/30",children:l.jsxs("div",{className:"max-w-3xl mx-auto px-4 sm:px-6 py-3 flex items-center gap-3",children:[l.jsx("button",{type:"button",onClick:d,className:"p-1.5 rounded-md hover:bg-bg-secondary text-text-tertiary hover:text-text-secondary transition-colors",title:h("team.backToMain"),children:l.jsx(R1,{size:16})}),l.jsx(Is,{size:16,className:"text-accent-purple flex-shrink-0"}),l.jsxs("span",{className:"text-[14px] font-semibold text-accent-purple",children:["@",e]}),(s==null?void 0:s.description)&&l.jsx("span",{className:"text-[12px] text-text-tertiary truncate flex-1",children:s.description}),u&&l.jsx(yt,{size:14,className:"animate-spin text-accent-purple flex-shrink-0"}),l.jsx("div",{className:"flex-1"}),s&&l.jsxs("span",{className:"text-[11px] text-text-tertiary flex-shrink-0",children:[s.toolCallCount?h("team.tools").replace("{count}",String(s.toolCallCount)):"",(p=s.tokenUsage)!=null&&p.lastContextWindow?`${s.toolCallCount?" · ":""}${h("team.tokens").replace("{count}",String(Math.round(s.tokenUsage.lastContextWindow/1e3))+"k")}`:""]})]})}),l.jsx("div",{className:"px-4 sm:px-6 pt-4 pb-8",children:l.jsxs("div",{className:"max-w-3xl mx-auto flex flex-col",children:[u&&c.length===0?l.jsxs("div",{className:"flex items-center justify-center gap-2 py-20 text-text-tertiary text-[13px]",children:[l.jsx(yt,{size:16,className:"animate-spin"}),l.jsx("span",{children:h("team.loadingHistory")})]}):c.length===0?l.jsx("div",{className:"flex items-center justify-center py-20 text-text-tertiary text-[13px]",children:h("team.noHistory")}):c.map((m,f)=>{if(m.kind==="user"){const b=m.entry.content?oI(m.entry.content):void 0;if(b)return b.from==="system"?null:l.jsx("div",{children:l.jsx(lI,{msg:b})},m.entry.id);let _=m.entry.content||"";return _=_.replace(/<system-reminder>[\s\S]*?<\/system-reminder>\s*/g,"").trim(),_?l.jsx("div",{className:"flex justify-end mb-6",children:l.jsx("div",{className:"max-w-[85%] rounded-lg rounded-tr-sm bg-bg-secondary px-4 py-2.5 sm:max-w-[75%]",children:l.jsx("p",{className:"whitespace-pre-wrap break-words text-text-primary text-chat",children:_})})},m.entry.id):null}return m.kind==="assistant_message"?l.jsx("div",{className:"mb-6",children:l.jsx(uh,{message:m.entry})},m.entry.id):m.kind==="assistant_tools"?l.jsx("div",{className:"mb-6",children:l.jsx(aI,{entries:m.entries})},`tools-${f}`):null}),u&&c.length>0&&l.jsxs("div",{className:"flex items-center gap-2 py-4 text-text-tertiary text-[12px]",children:[l.jsx(yt,{size:12,className:"animate-spin"}),l.jsx("span",{children:h("team.agentRunning")})]})]})})]})}const FJ={info:F1,success:VL,warn:wo,error:Fa},UJ={info:"text-accent-blue",success:"text-accent-green",warn:"text-accent-yellow",error:"text-accent-red"};function zJ({item:e}){const t=Ea(o=>o.removeToast),[n,r]=g.useState(!1),i=FJ[e.type],s=()=>{r(!0),setTimeout(()=>t(e.id),200)},a=async()=>{if(e.action)try{await e.action.onClick()!==!1&&s()}catch{s()}};return l.jsxs("div",{role:"alert",className:["flex items-start gap-3 px-4 py-3 rounded-xl border border-border-default shadow-lg","bg-bg-card backdrop-blur-sm","max-w-[360px] min-w-[280px]","transition-all duration-200",n?"opacity-0 translate-x-4":"opacity-100 translate-x-0","animate-fadeIn"].join(" "),children:[l.jsx(i,{size:18,className:`${UJ[e.type]} shrink-0 mt-0.5`}),l.jsxs("div",{className:"flex-1 min-w-0 flex flex-col gap-2",children:[l.jsx("p",{className:"text-[13px] text-text-primary leading-[1.5] break-words",children:e.message}),e.action&&l.jsx("button",{type:"button",onClick:a,className:"self-start px-2.5 py-1 rounded-md text-[12px] font-medium bg-accent-blue text-white hover:opacity-90 transition-opacity",children:e.action.label})]}),l.jsx("button",{onClick:s,"aria-label":"Dismiss",className:"shrink-0 w-5 h-5 flex items-center justify-center rounded text-text-tertiary hover:text-text-primary transition-colors",children:l.jsx(Bt,{size:14})})]})}function r1(){const e=Ea(t=>t.toasts);return e.length===0?null:l.jsx("div",{className:"fixed bottom-6 right-6 z-[999] flex flex-col-reverse gap-2 pointer-events-auto max-md:bottom-20 max-md:right-4 max-md:left-4 max-md:items-stretch",children:e.map(t=>l.jsx(zJ,{item:t},t.id))})}function HJ(e,t){const n=[];for(const r of e)r.type==="tool_call"&&n.push(r);for(const r of t.values())n.push(r);return n}function GJ(e,t){const n={};for(const r of e){const i=r.input||{},s=r.toolName;if(s==="TaskCreate"){const a=r.result,o=typeof a=="string"?a:a&&typeof a=="object"?String(a.text??a.output??""):"",c=!o&&Array.isArray(r.content)?r.content.reduce((p,m)=>{var f;return p||String(((f=m==null?void 0:m.content)==null?void 0:f.text)??(m==null?void 0:m.text)??"")},""):"",d=(o||c).match(/Task #(\d+)/),u=d?d[1]:`t-${Object.keys(n).length+1}`;let h=i.owner?String(i.owner):void 0;if(!h&&(t!=null&&t.length)){const p=i.subject?String(i.subject).toLowerCase():"",m=i.description?String(i.description).toLowerCase():"",f=p+" "+m;for(const b of t)if(f.includes(b.toLowerCase())){h=b;break}}n[u]={id:u,subject:i.subject?String(i.subject):"",status:"pending",owner:h,activeForm:i.activeForm?String(i.activeForm):void 0}}else if(s==="TaskUpdate"){const a=i.taskId?String(i.taskId):void 0;if(a&&n[a]){const o=n[a];i.status&&i.status!=="deleted"&&(o.status=String(i.status)),i.subject&&(o.subject=String(i.subject)),i.owner!==void 0&&(o.owner=i.owner?String(i.owner):void 0),i.activeForm&&(o.activeForm=String(i.activeForm)),i.status==="deleted"&&delete n[a]}}}return Object.values(n)}function WJ(e){return e.filter(t=>t.toolName==="TaskCreate"||t.toolName==="TaskUpdate").length}function qJ({status:e}){switch(e){case"completed":return l.jsx(Cc,{size:14,className:"text-accent-green flex-shrink-0"});case"in_progress":return l.jsx(yt,{size:14,className:"text-accent-brand flex-shrink-0 animate-spin"});default:return l.jsx(Kl,{size:14,className:"text-text-tertiary flex-shrink-0"})}}function VJ({member:e,isFocused:t,onClick:n}){var c;const r=e.status==="running"||e.status==="pending",i=e.status==="failed"||e.status==="killed",s=GO(e.color),a=gf(e.color),o=[];return e.toolCallCount&&o.push(`${e.toolCallCount} tools`),(c=e.tokenUsage)!=null&&c.lastContextWindow&&o.push(`${(e.tokenUsage.lastContextWindow/1e3).toFixed(1)}k`),l.jsxs("button",{type:"button",onClick:n,className:`inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-[11px] transition-colors cursor-pointer ${t?`${s.bg}`:r?`${s.bg} hover:opacity-80`:i?"bg-accent-red/10 text-accent-red":"bg-bg-secondary/50 text-text-tertiary hover:bg-bg-secondary/70"}`,style:{color:t||r?a:void 0,...t?{boxShadow:`0 0 0 1px ${a}40`}:{}},children:[l.jsxs("span",{className:"font-medium",children:["@",e.name]}),o.length>0&&l.jsx("span",{className:"opacity-70",children:o.join(" · ")}),r&&l.jsx(yt,{size:9,className:"animate-spin flex-shrink-0"}),i&&l.jsx(Fa,{size:9,className:"flex-shrink-0"}),!r&&!i&&l.jsx(gr,{size:9,className:"flex-shrink-0"})]})}function QJ(){const e=ot(P=>P.timeline),t=ot(P=>P.childToolCalls),n=ot(P=>P.isAgentRunning),{t:r}=Re(),[i,s]=g.useState(!0),a=Ir(P=>P.isInTeam),o=Ir(P=>P.members),c=Ir(P=>P.focusedMemberName),d=Ir(P=>P.setFocusedMember),u=g.useMemo(()=>{const P=new Map;for(const q of o)q.color&&P.set(q.name,q.color);return P},[o]),h=g.useRef(0),[p,m]=g.useState(!1),f=g.useRef(n),b=g.useMemo(()=>HJ(e,t),[e,t]),_=g.useMemo(()=>o.map(P=>P.name),[o]),v=g.useMemo(()=>GJ(b,_),[b,_]),A=g.useMemo(()=>WJ(b),[b]);g.useEffect(()=>{!f.current&&n&&(h.current=A,m(!0)),f.current=n},[n,A]),g.useEffect(()=>{p&&A>h.current&&m(!1)},[p,A]);const S=g.useCallback(()=>s(P=>!P),[]),y=g.useCallback(P=>{P.stopPropagation(),h.current=A,m(!0)},[A]),x=g.useCallback(P=>{d(c===P?null:P)},[c,d]),k=g.useCallback(P=>{P.owner&&u.has(P.owner)&&d(c===P.owner?null:P.owner)},[c,u,d]),C=o.filter(P=>P.status==="running"||P.status==="pending"),E=C.length>0,N=!n&&E,z=a&&o.length>0,Q=v.length>0,T=Q&&v.every(P=>P.status==="completed"),w=z&&!E&&!n,L=Q&&v.every(P=>P.status==="pending")&&!n&&!E,R=Q&&!(T||w||L)&&!p,$=z&&(E||c);if(!R&&!$)return null;const D=v.filter(P=>P.status==="completed").length,U=v.length,Y=v.find(P=>P.status==="in_progress"),ee=Y?Y.activeForm||Y.subject:`${D}/${U}`;return l.jsx("div",{className:"flex-none px-4 sm:px-6 pb-1",children:l.jsx("div",{className:"max-w-3xl mx-auto",children:l.jsxs("div",{className:"rounded-lg border border-border-muted/15 bg-bg-secondary/30 overflow-hidden",children:[l.jsxs("button",{onClick:S,className:"flex items-center gap-2 w-full px-3 py-1.5 hover:bg-bg-hover/30 transition-colors cursor-pointer",children:[N?l.jsx(yt,{size:13,className:"animate-spin text-accent-purple flex-shrink-0"}):$?l.jsx(Z1,{size:13,className:"text-accent-purple flex-shrink-0"}):l.jsx(H1,{size:13,className:"text-text-tertiary flex-shrink-0"}),N?l.jsx("span",{className:"text-xs font-medium text-accent-purple",children:r("team.waitingForTeammates").replace("{count}",String(C.length)).replace("{s}",C.length>1?"s":"")}):l.jsxs(l.Fragment,{children:[R&&l.jsxs(l.Fragment,{children:[l.jsx("span",{className:"text-xs font-medium text-text-primary",children:r("todo.title")}),l.jsxs("span",{className:"text-[11px] text-text-tertiary tabular-nums",children:[D,"/",U]})]}),$&&R&&l.jsx("span",{className:"text-border-muted/40",children:"·"}),$&&l.jsxs("span",{className:"text-[11px] text-text-tertiary",children:[r("team.title")," ",C.length>0?r("team.activeCount").replace("{count}",String(C.length)):""]})]}),!i&&R&&l.jsxs(l.Fragment,{children:[l.jsx("span",{className:"text-border-muted/60 select-none",children:"|"}),Y&&n&&l.jsx(yt,{size:10,className:"text-accent-brand animate-spin flex-shrink-0"}),l.jsx("span",{className:"text-xs text-text-secondary truncate flex-1 text-left",children:ee})]}),l.jsx("span",{className:"flex-1"}),!n&&!N&&l.jsx("span",{role:"button",tabIndex:0,onClick:y,onKeyDown:P=>{P.key==="Enter"&&y(P)},className:"text-text-tertiary hover:text-text-primary p-0.5 rounded transition-colors flex-shrink-0",children:l.jsx(Bt,{size:12})}),i?l.jsx(sr,{size:12,className:"text-text-tertiary flex-shrink-0"}):l.jsx(Or,{size:12,className:"text-text-tertiary flex-shrink-0"})]}),i&&l.jsxs("div",{className:"border-t border-border-muted/40",children:[$&&l.jsx("div",{className:"flex flex-wrap gap-1.5 px-3 py-1.5",children:o.map(P=>l.jsx(VJ,{member:P,isFocused:c===P.name,onClick:()=>x(P.name)},P.name))}),R&&l.jsx("div",{className:`px-3 py-1.5 space-y-0.5 max-h-52 overflow-y-auto ${$?"border-t border-border-muted/30":""}`,children:v.map((P,q)=>{const ue=P.owner?u.get(P.owner):void 0,_e=!!ue,ke=ue?gf(ue):void 0;return l.jsxs("div",{onClick:_e?()=>k(P):void 0,className:`flex items-center gap-2 py-0.5 text-xs ${_e?"cursor-pointer hover:bg-bg-hover/30 rounded px-1 -mx-1":""} ${P.status==="in_progress"?"text-text-primary":P.status==="completed"?"text-text-tertiary":"text-text-secondary"}`,children:[l.jsx(qJ,{status:P.status}),l.jsxs("span",{className:`truncate ${P.status==="completed"?"line-through":""}`,children:[q+1,". ",P.status==="in_progress"?P.activeForm||P.subject||r("todo.untitled"):P.subject||r("todo.untitled")]}),ue&&l.jsxs("span",{className:"text-[10px] font-medium flex-shrink-0 ml-auto",style:{color:ke},children:["@",P.owner]})]},P.id)})})]})]})})})}function KJ({activeCwd:e,onOpenDirectoryPicker:t}){const{t:n}=Re(),r=g.useRef(null),[i,s]=g.useState(!1),a=Um(p=>p.dirs),o=Um(p=>p.removeDir),c=Jr(p=>{var m;return(m=p.info)==null?void 0:m.cwd})||"/",d=e||c,u=g.useMemo(()=>a.filter(p=>p!==d),[d,a]),h=g.useMemo(()=>QC(d),[d]);return g.useEffect(()=>{if(!i)return;const p=f=>{r.current&&!r.current.contains(f.target)&&s(!1)},m=f=>{f.key==="Escape"&&s(!1)};return document.addEventListener("pointerdown",p,!0),document.addEventListener("keydown",m),()=>{document.removeEventListener("pointerdown",p,!0),document.removeEventListener("keydown",m)}},[i]),l.jsxs("div",{ref:r,className:"relative min-w-0 shrink",children:[l.jsxs("button",{type:"button",onClick:()=>{if(u.length===0){t==null||t();return}s(p=>!p)},className:"composer-seat-chip",title:d,"aria-label":n("input.menu.directory"),"aria-haspopup":"menu","aria-expanded":i,children:[l.jsx(Bo,{size:16,className:"shrink-0"}),l.jsx("span",{className:"min-w-0 truncate",children:h}),u.length>0&&l.jsxs("span",{className:"shrink-0 text-[12px] font-medium text-text-tertiary",children:["+",u.length]}),u.length>0&&l.jsx(sr,{size:12,className:`shrink-0 text-text-tertiary transition-transform ${i?"rotate-180":""}`})]}),i&&l.jsxs("div",{role:"menu",className:"composer-menu absolute left-0 top-full z-50 mt-2 w-[260px] max-w-[calc(100vw-24px)] overflow-hidden py-1",children:[l.jsx("div",{className:"max-h-52 overflow-y-auto py-1",children:u.map(p=>l.jsxs("div",{className:"group/item flex items-center gap-2 px-3 py-2 text-[11px] transition-colors hover:bg-bg-hover",title:p,children:[l.jsx(Bo,{size:12,className:"shrink-0 text-text-tertiary"}),l.jsx("span",{className:"min-w-0 flex-1 truncate text-text-secondary",children:VC(p)||p}),l.jsx("button",{type:"button",onClick:()=>{o(p),u.length===1&&s(!1)},className:"flex h-5 w-5 shrink-0 items-center justify-center rounded-full text-text-tertiary opacity-0 transition-opacity group-hover/item:opacity-100 hover:bg-bg-hover hover:text-accent-red",title:n("workspace.recent.remove"),"aria-label":n("workspace.recent.remove"),children:l.jsx(Bt,{size:11})})]},p))}),l.jsxs("button",{type:"button",onClick:()=>{s(!1),t==null||t()},className:`flex w-full items-center gap-2 px-3 py-2 text-left text-[11px] text-text-secondary transition-colors hover:bg-bg-hover hover:text-text-primary ${u.length>0?"border-t border-border-muted":""}`,children:[l.jsx(is,{size:12,className:"shrink-0"}),n("input.directory.add")]})]})]})}function YJ(e={}){const{immediate:t=!1,onNeedReload:n,onNeedRefresh:r,onOfflineReady:i,onRegistered:s,onRegisteredSW:a,onRegisterError:o}=e;let c,d,u;const h=async(m=!0)=>{await d,u==null||u()};async function p(){if("serviceWorker"in navigator){if(c=await Ct(async()=>{const{Workbox:m}=await import("./workbox-window.prod.es5-BBnX5xw4.js");return{Workbox:m}},[]).then(({Workbox:m})=>new m("/sw.js",{scope:"/",type:"classic"})).catch(m=>{o==null||o(m)}),!c)return;u=()=>{c==null||c.messageSkipWaiting()};{let m=!1;const f=()=>{m=!0,c==null||c.addEventListener("controlling",b=>{b.isUpdate&&(n?n():window.location.reload())}),r==null||r()};c.addEventListener("installed",b=>{typeof b.isUpdate>"u"?typeof b.isExternal<"u"&&b.isExternal?f():!m&&(i==null||i()):b.isUpdate||i==null||i()}),c.addEventListener("waiting",f)}c.register({immediate:t}).then(m=>{a?a("/sw.js",m):s==null||s(m)}).catch(m=>{o==null||o(m)})}}return d=p(),h}function ZJ(e={}){const{immediate:t=!0,onNeedReload:n,onNeedRefresh:r,onOfflineReady:i,onRegistered:s,onRegisteredSW:a,onRegisterError:o}=e,[c,d]=g.useState(!1),[u,h]=g.useState(!1),[p]=g.useState(()=>YJ({immediate:t,onNeedReload:n,onOfflineReady(){h(!0),i==null||i()},onNeedRefresh(){d(!0),r==null||r()},onRegistered:s,onRegisteredSW:a,onRegisterError:o}));return{needRefresh:[c,d],offlineReady:[u,h],updateServiceWorker:p}}const JJ=900*1e3,XJ="pwa-new-version";function eX(e=!0){const{t}=Re(),n=g.useRef(null),r=g.useRef(!1),{updateServiceWorker:i}=ZJ({immediate:e,onRegisteredSW(o,c){if(!c)return;const d=()=>{c.update().catch(()=>{})};d(),setInterval(d,JJ)},onNeedRefresh(){if(r.current=!0,!ot.getState().isAgentRunning){s();return}a()}});g.useEffect(()=>{e||!("serviceWorker"in navigator)||Ji()||window.parent!==window||navigator.serviceWorker.getRegistrations().then(o=>Promise.all(o.map(c=>c.unregister()))).catch(()=>{})},[e]),g.useEffect(()=>{n.current=i},[i]),g.useEffect(()=>ot.subscribe((c,d)=>{r.current&&d.isAgentRunning&&!c.isAgentRunning&&s()}),[]);function s(){r.current=!1;const o=n.current;return o?o(!0).catch(()=>{}):Promise.resolve()}function a(){Dt.info(t("app.pwa.newVersion"),{id:XJ,durationMs:0,action:{label:t("app.pwa.reloadNow"),onClick:()=>(s(),!0)}})}}function tX(e,t,n,r,i){const s=Object.keys(e);if(s.length<=r)return e;const a=new Set(i.filter(u=>!!u)),o=s.filter(u=>!a.has(u)).map(u=>{const h=n.find(p=>p.id===u);return{id:u,lastAccess:e[u].lastAccess,settled:h?Xs(h):!0}}).sort((u,h)=>u.settled!==h.settled?u.settled?-1:1:u.lastAccess-h.lastAccess),c=s.length-r;if(c<=0)return e;const d={...e};for(const{id:u}of o.slice(0,c))delete d[u],delete t[u];return d}const nX=g.lazy(()=>Ct(()=>import("./CanvasPaneStandaloneView-zfXxWldi.js"),__vite__mapDeps([2,3,4,5])).then(e=>({default:e.CanvasPaneStandaloneView}))),i1=g.lazy(()=>Ct(()=>import("./CanvasView-C1zt0xeq.js"),__vite__mapDeps([6,3,4,7,5])).then(e=>({default:e.CanvasView}))),rX=g.lazy(()=>Ct(()=>Promise.resolve().then(()=>WH),void 0).then(e=>({default:e.ChangesView}))),s1=g.lazy(()=>Ct(()=>import("./DocsView-BY-czkuI.js"),__vite__mapDeps([8,3,5])).then(e=>({default:e.DocsView}))),a1=g.lazy(()=>Ct(()=>import("./EditorView-DYhVx-By.js"),__vite__mapDeps([9,3,7,5])).then(e=>({default:e.EditorView}))),iX=g.lazy(()=>Ct(()=>import("./KeybindingsView-CmZBQZ08.js"),__vite__mapDeps([10,3,5])).then(e=>({default:e.KeybindingsView}))),sX=g.lazy(()=>Ct(()=>import("./LogsView-CEkiw-ej.js"),__vite__mapDeps([11,3,12,5])).then(e=>({default:e.LogsView}))),aX=g.lazy(()=>Ct(()=>import("./MetricsView-BAiZLSTx.js"),__vite__mapDeps([13,3,12,14,5])).then(e=>({default:e.MetricsView}))),oX=g.lazy(()=>Ct(()=>Promise.resolve().then(()=>ZH),void 0).then(e=>({default:e.PluginsView}))),lX=g.lazy(()=>Ct(()=>import("./RemoteControlView-CkEGw9Rf.js"),__vite__mapDeps([15,3,5])).then(e=>({default:e.RemoteControlView}))),cX=g.lazy(()=>Ct(()=>Promise.resolve().then(()=>dG),void 0).then(e=>({default:e.SettingsView}))),dX=g.lazy(()=>Ct(()=>import("./StatsView-WoO5FWv8.js"),__vite__mapDeps([16,3,5])).then(e=>({default:e.StatsView}))),uX=g.lazy(()=>Ct(()=>Promise.resolve().then(()=>yG),void 0).then(e=>({default:e.TasksView}))),hX=g.lazy(()=>Ct(()=>Promise.resolve().then(()=>OZ),void 0).then(e=>({default:e.TerminalView}))),pX=g.lazy(()=>Ct(()=>import("./TracesView-fTXf2HNv.js"),__vite__mapDeps([17,3,12,5])).then(e=>({default:e.TracesView}))),mX=g.lazy(()=>Ct(()=>import("./WorkersView-B4GA22wu.js"),__vite__mapDeps([18,3,12,14,5])).then(e=>({default:e.WorkersView})));function Si(){return l.jsx("div",{className:"flex min-h-0 flex-1 items-center justify-center bg-bg-primary",children:l.jsx(ea,{size:"small"})})}x1();function gX(){var ni;const e=new URLSearchParams(window.location.search).get("embedded")==="agent";eX(!e);const{viewState:t,checkAuth:n,accountState:r}=Zr(),{status:i,sessionId:s,topic:a}=Ge(),o=Z$(i,s),c=Xi(Z=>Z.resolved),d=ot(Z=>Z.hasPendingInterruption),{connect:u,switchSession:h,createSession:p}=w5(),m=Ir(Z=>Z.focusedMemberName),{t:f,resolved:b}=Re(),_=Oi(Z=>Z.isOpen),v=Oi(Z=>Z.setOpen),A=Oi(Z=>Z.sessionsOpen),S=Oi(Z=>Z.toggleSessionsPanel),y=Oi(Z=>Z.setSessionsOpen),x=uf(),[k,C]=g.useState(!1),[E,N]=g.useState(!1),z=x?k:!0,Q=en(Z=>Z.recentOpen),T=en(Z=>Z.recentProjectCwd),w=en(Z=>Z.setRecentOpen),L=en(Z=>Z.setRecentProjectCwd),I=en(Z=>Z.activeAgentCwd),R=en(Z=>Z.setActiveAgentCwd),$=en(Z=>Z.mainChatActive),D=en(Z=>Z.setMainChatActive),U=en(Z=>Z.setSelectedWorkerPid),Y=en(Z=>Z.mainAgentSessionId),ee=en(Z=>Z.setMainAgentSessionId),P=en(Z=>Z.setAgentSessionId),q=en(Z=>Z.agentSessionIds),[ue,_e]=g.useState({}),ke=g.useRef({}),H=g.useRef(ue);H.current=ue;const G=g.useRef(new Map),V=2,[oe,J]=g.useState(null),he=Xr(Z=>Z.cwd),ne=tn(Z=>Z.selectedJobId),pe=tn(Z=>Z.selectedJobTitle),re=tn(Z=>Z.jobs.find(ye=>ye.id===ne)??null);g.useEffect(()=>{if(!(e||!ne))try{if(typeof sessionStorage>"u")return;const ye=JSON.parse(sessionStorage.getItem("agent-session-map")??"{}")[ne];ye&&typeof ye=="string"&&!q[ne]&&P(ne,ye)}catch{}},[e,ne,q,P]),g.useEffect(()=>{e||ne&&$&&D(!1)},[e,ne,$,D]),g.useEffect(()=>{!$&&(re!=null&&re.cwd)&&I!==re.cwd&&R(re.cwd)},[I,$,re==null?void 0:re.cwd,R]);const ce=en(Z=>Z.newJobMode),ae=en(Z=>Z.setNewJobMode),Ae=(re==null?void 0:re.cwd)??null,de=re?q[re.id]??re.sessionId??null:null,F=!e&&!$&&ne!==null,ie=tn(Z=>Z.jobs);g.useEffect(()=>{if(e||!re||!F)return;const Z=re.id;if(!re.webUrl)return;const ye=re.webUrl,Oe=ke.current[Z]instanceof HTMLIFrameElement;_e(dt=>{const it=dt[Z];if(it&&it.webUrl===ye&&it.theme===c&&it.loaded&&Oe)return dt;const ut=(it==null?void 0:it.sessionId)??q[Z]??re.sessionId??null;if(!ut)return dt;let mn;try{mn=Uw(ye,ut,re.cwd,As(),c,window.location.hostname,Z)}catch{return dt}if(it&&HR(it.url)===mn)return dt;const ri=it?{...dt,[Z]:{...it,webUrl:ye,sessionId:ut,url:mn,theme:c,loaded:!1}}:{...dt,[Z]:{jobId:Z,webUrl:ye,sessionId:ut,url:mn,theme:c,loaded:!1,needsInput:null,topic:null,lastAccess:Date.now()}};return tX(ri,ke.current,ie,V,[Z])})},[e,re,F,q,ie,V,ne,c]),g.useEffect(()=>{_e(Z=>{const ye={...Z};let Oe=!1;for(const dt of Object.keys(ye))ie.some(it=>it.id===dt)||(delete ye[dt],delete ke.current[dt],Oe=!0);return Oe?ye:Z})},[ie]),g.useEffect(()=>{ne&&_e(Z=>{const ye=Z[ne];return!ye||ye.lastAccess===Date.now()?Z:{...Z,[ne]:{...ye,lastAccess:Date.now()}}})},[ne]);const fe=pe||(re==null?void 0:re.name)||Ec((re==null?void 0:re.intent)??"")||(ne?f("agents.instanceFallback").replace("{id}",ne.slice(0,8)):null),X=ne?ue[ne]:null,Ce=(X==null?void 0:X.loaded)===!0,Ee=oe!==null&&oe===ne,Le=F&&!ce&&!Ce?Ee?"creating":re!=null&&re.foregroundHeld?null:"restoring":null;g.useEffect(()=>{Ee&&(X!=null&&X.loaded)&&J(null)},[X==null?void 0:X.loaded,Ee]);const We=$||!ne?pH:mH(ne),je=$?I??he:Ae??I??he,et=g.useRef(new Set),ct=g.useRef(new Set),gt=g.useRef(new Map),qe=1e3,wt=8e3,[Nt,qt]=g.useState(!1),[$t,It]=g.useState(!1),[cr,Vn]=g.useState(!1),[ze,rt]=g.useState(void 0),{splitPane:Ot,mainView:le,setMainView:Ne}=zt(),Qe=ot(Z=>Z.timeline),os=ot(Z=>Z.historyLoading),Br=nt(Z=>Z.sessionBlank),Je=g.useMemo(()=>Jx(Qe).length,[Qe]),vn=le==="chat"&&!F&&!ce&&!m&&o&&!os&&Je===0&&Br,[Rr,an]=g.useState(!1);g.useEffect(()=>{if(x){an(!1);return}if(le!=="chat"){A&&(an(!0),y(!1));return}Rr&&(an(!1),A||y(!0))},[x,le,A,y]),g.useEffect(()=>{C(!1),N(!1)},[x,le]),g.useEffect(()=>{!x&&!_&&v(!0)},[x,_,v]);const jr=le==="chat"&&(x?E:A),xn=g.useCallback(()=>{if(x){C(!1),N(Z=>!Z);return}S()},[x,S]),Tn=g.useCallback(()=>{if(x){N(!1);return}y(!1)},[x,y]),pn=g.useCallback(()=>{x&&(N(!1),C(Z=>!Z))},[x]),Ls=g.useCallback(()=>{x&&C(!1)},[x]);g.useEffect(()=>{const Z=ye=>kr.handleKeyDown(ye);return window.addEventListener("keydown",Z),()=>window.removeEventListener("keydown",Z)},[]),g.useEffect(()=>{if(t!=="authenticated"||e)return;let Z=!1;return(async()=>{var ye;try{const Oe=await Kt("/api/v1/channels",{headers:Fe()});if(!Oe.ok||Z)return;const dt=await Oe.json();rt(((ye=dt.capabilities)==null?void 0:ye.remoteControlEnabled)===!0)}catch{}})(),()=>{Z=!0}},[t]),g.useEffect(()=>{i==="connected"&&dI.getState().loadBindings()},[i]);const Qn=g.useCallback((Z,ye)=>{const Oe=tn.getState().jobs.find(ut=>ut.id===Z);if(!Oe)return;const dt=Oe.webUrl;if(!dt)return;let it;try{it=Uw(dt,ye,Oe.cwd,As(),c,window.location.hostname,Z)}catch{return}_e(ut=>{const mn=ut[Z];return mn?{...ut,[Z]:{...mn,webUrl:dt,sessionId:ye,url:it,theme:c,loaded:!1}}:ut})},[c]),K=g.useCallback(Z=>{G.current.delete(Z),_e(ye=>{const Oe=ye[Z];return!Oe||Oe.loaded?ye:{...ye,[Z]:{...Oe,loaded:!0}}})},[]);g.useEffect(()=>{if(e||!F||ce||!ne)return;const Z=ne;G.current.delete(Z);const ye=it=>{const ut=ke.current[Z],mn=H.current[Z];if(!ut||!mn)return;const ri=Hw(ut,zw(mn.url));if(ri==="alive"||ri==="opaque"){K(Z);return}if(!it||ri!=="dead")return;const ls=G.current.get(Z)??0;ls>=2||(G.current.set(Z,ls+1),_e(Ms=>{const bl=Ms[Z];return bl?{...Ms,[Z]:{...bl,loaded:!1,url:zR(bl.url)}}:Ms}))},Oe=window.requestAnimationFrame(()=>ye(!1)),dt=window.setTimeout(()=>ye(!0),UR);return()=>{window.cancelAnimationFrame(Oe),window.clearTimeout(dt)}},[e,F,ce,ne,K]);const xe=g.useCallback(Z=>{Ot(Z)},[Ot]),Pe=g.useCallback(async()=>{if(!s)return null;let Z;try{const dt=en.getState(),it=tn.getState().selectedJobId;Z=await p({persistLastId:dt.mainChatActive||!it})}catch{return Dt.error(f("error.newChatFailed")),null}const ye=en.getState(),Oe=tn.getState().selectedJobId;return ye.mainChatActive||!Oe?(ee(Z),he&&R(he)):(P(Oe,Z),Qn(Oe,Z)),ae(!1),Ne("chat"),window.location.hash="/chat",Z},[s,p,Qn,Ne,f,he,R,ae,ee,P]),ft=g.useCallback(async(Z,ye,Oe)=>{if(!s)return!1;try{return await h(Z),R(ye??he??null),ae(!1),Ne("chat"),window.location.hash="/chat",!0}catch(dt){const it=Oo(dt);console.error(`[App] Session switch failed: ${it}`,dt);const ut=/external writer|Persistent Session already has|current external writer/i.test(it),mn=/ADMISSION_FAILED|admission did not commit/i.test(it);return ut&&(Oe!=null&&Oe.silentOccupied)||(ut?Dt.info(f("error.sessionOccupied")):Dt.error(mn?f("error.sessionUnavailable"):`${f("error.switchSessionFailed")}: ${it}`)),!1}},[s,Ne,h,f,he,R,ae]),Vt=g.useCallback((Z,ye)=>ft(Z,ye,{silentOccupied:!0}),[ft]),tt=g.useCallback(Z=>{const ye=Z==="remote-control"&&ze===!1?"chat":Z;x&&C(!1),Ne(ye),window.location.hash=`/${ye}`},[x,ze,Ne]),Ke=g.useCallback(()=>{if(Q){w(!1);return}L(he??null),w(!0)},[Q,he,L,w]),Jt=g.useCallback(async(Z,ye)=>{const dt=en.getState().mainChatActive?null:tn.getState().selectedJobId;return dt?(P(dt,Z),Qn(dt,Z),tn.getState().selectJob(dt,tn.getState().selectedJobTitle),D(!1),U(null),R(ye),!0):await ft(Z,ye)?(ee(Z),tn.getState().selectJob(null),D(!0),U(null),R(ye),!0):!1},[ft,R,P,ee,D,U,Qn]),Lt=g.useCallback(()=>{ae(!0),Ne("chat"),window.location.hash="/chat"},[Ne,ae]),se=g.useCallback(()=>{ae(!1),Ne("chat"),window.location.hash="/chat"},[Ne,ae]),$e=g.useCallback(Z=>{ct.current.add(Z),J(Z);const ye=tn.getState().jobs.find(Oe=>Oe.id===Z);tn.getState().selectJob(Z,(ye==null?void 0:ye.name)??null),U(null),D(!1),R((ye==null?void 0:ye.cwd)??he??null),ae(!1)},[R,D,ae,U,he]);if(g.useEffect(()=>{if($||ce||!(re!=null&&re.sessionId)||re.foregroundHeld)return;let Z;const ye=()=>{const Oe=tn.getState().jobs.find(Ms=>Ms.id===re.id);if(!Oe)return;if(tn.getState().manuallyStoppedAgentIds[Oe.id]){ct.current.delete(Oe.id),gt.current.delete(Oe.id);return}const dt=jR(Oe,ct.current.has(Oe.id));if(dt===null){(Oe.webUrl||Oe.alive)&&(ct.current.delete(Oe.id),gt.current.delete(Oe.id));return}if(dt>0){Z=setTimeout(ye,dt);return}if(ct.current.delete(Oe.id),et.current.has(Oe.id))return;const it=Date.now(),ut=gt.current.get(Oe.id),mn=(ut==null?void 0:ut.nextRetryAt)??0;if(it<mn){Z=setTimeout(ye,mn-it);return}const ri=(ut==null?void 0:ut.failures)??0,ls=FR(ri,qe,wt);gt.current.set(Oe.id,{failures:ri+1,nextRetryAt:it+ls}),et.current.add(Oe.id),tn.getState().respawnJob(Oe.id).finally(()=>et.current.delete(Oe.id))};return ye(),()=>{Z&&clearTimeout(Z)}},[$,ce,re]),g.useEffect(()=>{const Z=ye=>{const Oe=Object.keys(ke.current).find(it=>{var ut;return((ut=ke.current[it])==null?void 0:ut.contentWindow)===ye.source});!Oe||!tn.getState().jobs.find(it=>it.id===Oe)||!TR(ye.data)||ye.origin===window.location.origin&&(ye.data.sessionId&&typeof ye.data.sessionId=="string"&&P(Oe,ye.data.sessionId),_e(it=>{const ut=it[Oe];return ut?{...it,[Oe]:{...ut,sessionId:typeof ye.data.sessionId=="string"&&ye.data.sessionId?ye.data.sessionId:ut.sessionId,needsInput:typeof ye.data.needsInput=="boolean"?ye.data.needsInput:ut.needsInput,topic:ye.data.topic}}:it}))};return window.addEventListener("message",Z),()=>window.removeEventListener("message",Z)},[P]),g.useEffect(()=>{const Z=[kr.register({id:"commandPalette.toggle",key:"p",meta:!0,shift:!0,handler:()=>Vn(ye=>!ye)}),kr.register({id:"sidebar.toggle",key:"b",meta:!0,when:()=>le!=="editor",handler:()=>{if(x){pn();return}le==="chat"&&xn()}}),kr.register({id:"terminal.toggle",key:"j",meta:!0,handler:()=>{const ye=le==="terminal"?"chat":"terminal";Ne(ye),window.location.hash="/"+ye}}),kr.register({id:"newChat",key:"n",meta:!0,handler:()=>Pe()}),kr.register({id:"settings",key:",",meta:!0,handler:()=>{Ne("settings"),window.location.hash="/settings"}}),kr.registerAction("app:commandPalette",()=>Vn(ye=>!ye)),kr.registerAction("app:toggleSidebar",()=>{if(x){pn();return}le==="chat"&&xn()},()=>le!=="editor"),kr.registerAction("app:toggleTerminal",()=>{const ye=le==="terminal"?"chat":"terminal";Ne(ye),window.location.hash="/"+ye}),kr.registerAction("app:newChat",()=>Pe()),kr.registerAction("app:settings",()=>{Ne("settings"),window.location.hash="/settings"}),kr.registerAction("app:focusInput",()=>{const ye=document.querySelector("textarea");ye==null||ye.focus()}),kr.registerAction("app:keybindings",()=>{Ne("keybindings"),window.location.hash="/keybindings"})];return()=>Z.forEach(ye=>ye())},[x,le,Pe,Ne,xn,pn]),g.useEffect(()=>{const Z=new URLSearchParams(window.location.search),ye=Z.get("password"),Oe=Z.get("token");if(ye||Oe){Kg(ye||Oe),Z.delete("password"),Z.delete("token");const dt=Z.toString()?`${window.location.pathname}?${Z.toString()}`:window.location.pathname;window.history.replaceState({},"",dt)}n()},[n]),g.useEffect(()=>{if(t==="authenticated")return Zr.getState().startHeartbeat()},[t]),g.useEffect(()=>{t==="authenticated"&&Zr.getState().checkAccountAuth()},[t]),g.useEffect(()=>{if(t==="authenticated"){const Z=k1(),ye=Z==="remote-control"&&ze!==!0?"chat":Z;Ne(ye),(!window.location.hash||window.location.hash==="#")&&(window.location.hash=`/${ye}`)}},[ze,t,Ne]),g.useEffect(()=>bL(ye=>{if(ye==="remote-control"&&ze!==!0){ze===!1&&(Ne("chat"),window.location.hash="/chat");return}Ne(ye)}),[ze,Ne]),g.useEffect(()=>{ze===!1&&le==="remote-control"&&(Ne("chat"),window.location.hash="/chat")},[le,ze,Ne]),g.useEffect(()=>{if(t==="authenticated"&&r==="authenticated"){const Z=As()||void 0;b5().catch(()=>{}),u({token:Z,continue:!0}),A1()}},[t,r,u]),g.useEffect(()=>{he&&!I&&R(he)},[he,I,R]),g.useEffect(()=>{if(!s)return;const Z=en.getState(),ye=tn.getState().selectedJobId;(Z.mainChatActive||!ye)&&ee(s)},[s,ee]),g.useEffect(()=>{document.documentElement.lang=b;const Z=F?(X==null?void 0:X.topic)||fe:a;document.title=bm(Z)||f("page.title")},[b,f,a,F,X==null?void 0:X.topic,fe]),g.useEffect(()=>{if(!e||window.parent===window)return;let Z=null;try{Z=window.parent.location.origin}catch{try{document.referrer&&(Z=new URL(document.referrer).origin)}catch{}}Z&&window.parent.postMessage({type:_1,sessionId:s,topic:bm(a)||null,needsInput:d},Z)},[e,d,s,a]),t==="loading")return l.jsx("div",{className:"flex h-screen h-[100dvh] bg-bg-primary text-text-primary transition-colors duration-200 font-sans overflow-hidden",children:l.jsx("div",{className:"flex-1 flex items-center justify-center",children:l.jsx(ea,{size:"large",text:f("app.connecting")})})});if(t==="login")return l.jsx(TJ,{});if(r==="needLogin"||r==="polling")return l.jsx(A5,{});const kt=()=>l.jsx(Jn,{viewName:F?"agents":"chat",errorTitle:f("error.viewCrashed"),retryLabel:f("app.retry"),children:l.jsxs("div",{className:`relative isolate flex min-h-0 flex-1 flex-col overflow-hidden bg-bg-primary ${vn||ce?"justify-center":""}`,children:[Object.values(ue).map(Z=>{if(e)return null;const ye=qR({showingAgentStage:F,newJobMode:ce,jobId:Z.jobId,selectedJobId:ne,loaded:Z.loaded});return l.jsx("iframe",{ref:Oe=>{ke.current[Z.jobId]=Oe},src:Z.url,title:Z.jobId===ne?(re==null?void 0:re.name)||(re==null?void 0:re.intent)||f("agents.instanceFallback").replace("{id}",ne.slice(0,8)):void 0,className:"absolute inset-0 z-0 h-full w-full border-0 bg-bg-primary",allow:"clipboard-read; clipboard-write",loading:"eager",onLoad:()=>{const Oe=ke.current[Z.jobId];Hw(Oe,zw(Z.url))!=="dead"&&K(Z.jobId)},style:WR(ye)},Z.jobId)}),ce?l.jsxs("div",{className:"composer-stack composer-stack-hero flex-none",children:[l.jsx(Sa,{compact:!0,cwd:je??void 0}),l.jsx(EJ,{onCreated:$e,onCancel:se})]}):F?Ce?l.jsx("div",{className:"min-h-0 flex-1","aria-hidden":!0}):l.jsx("div",{className:"relative z-10 flex min-h-0 flex-1 flex-col bg-bg-primary",children:Le==="creating"?l.jsx("div",{className:"empty-state-wrapper",children:l.jsx(Sa,{cwd:(re==null?void 0:re.cwd)??je??void 0,footer:l.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-text-tertiary",children:[l.jsx(yt,{size:12,className:"animate-spin"}),l.jsx("span",{children:f("agents.live.creating")})]})})}):re!=null&&re.foregroundHeld?l.jsx("div",{className:"empty-state-wrapper",children:l.jsx(Sa,{cwd:(re==null?void 0:re.cwd)??je??void 0,footer:l.jsx("p",{className:"text-[11px] text-text-tertiary",children:f("agents.live.foregroundHeld")})})}):re!=null&&re.sessionId?l.jsx("div",{className:"relative flex min-h-0 flex-1 flex-col",children:l.jsx(B9,{job:re})}):l.jsx("div",{className:"empty-state-wrapper",children:l.jsx(Sa,{cwd:(re==null?void 0:re.cwd)??je??void 0,footer:l.jsx("p",{className:"text-[11px] text-text-tertiary",children:f("agents.live.restoring")})})})}):l.jsxs(l.Fragment,{children:[l.jsx("div",{className:vn?"hidden":"flex-1 overflow-hidden w-full relative bg-bg-primary",children:m?l.jsx(jJ,{}):l.jsx(cI,{onClickCloseBottomSheet:()=>qt(!1),skipWelcomeTransition:e})}),!vn&&l.jsx(QJ,{}),!vn&&l.jsx(U9,{}),l.jsxs("div",{className:`bg-bg-primary ${vn?"composer-stack composer-stack-hero flex-none":"composer-stack flex-none"}`,children:[l.jsxs("div",{className:vn?"contents":"hidden",children:[l.jsx(Sa,{compact:!0,cwd:je??void 0}),l.jsxs("div",{className:"composer-hero-row",children:[l.jsx(KJ,{activeCwd:je,onOpenDirectoryPicker:()=>It(!0)}),!m&&l.jsx(NJ,{sessionId:s})]})]}),l.jsx(MJ,{}),l.jsx(dJ,{agentKey:We,agentCwd:je,onNavigate:tt,onNewChat:Pe,mainView:le,showBottomSheet:Nt,setShowBottomSheet:qt,onOpenDirectoryPicker:()=>It(!0),directoryPickerOpen:$t,onDirectoryPickerClose:()=>It(!1),hero:vn})]})]})]})}),wn=()=>{if(!o&&i!=="error"&&!e)return l.jsx("div",{className:"flex-1 flex items-center justify-center",children:l.jsx(ea,{size:"large",text:f("app.connecting")})});if(!o&&!e&&le!=="settings"&&le!=="docs")return l.jsx("div",{className:"flex-1 flex items-center justify-center",children:l.jsxs("div",{className:"text-center",children:[l.jsx("div",{className:"text-text-secondary mb-4 font-medium",children:f("app.connectFailed")}),l.jsx("button",{onClick:()=>u({continue:!0}),className:["px-6 py-2.5 bg-accent-brand text-accent-brand-foreground rounded-full","text-sm font-medium transition-all hover:bg-accent-brand/90","hover:scale-105 active:scale-95 shadow-sm"].join(" "),children:f("app.retry")})]})});switch(le){case"chat":return e?kt():null;case"tasks":return l.jsx(Jn,{viewName:"tasks",errorTitle:f("error.viewCrashed"),retryLabel:f("app.retry"),children:l.jsx(uX,{})});case"plugins":return l.jsx(Jn,{viewName:"plugins",errorTitle:f("error.viewCrashed"),retryLabel:f("app.retry"),children:l.jsx(oX,{})});case"terminal":return null;case"canvas":return null;case"canvas-pane":return null;case"remote-control":return ze!==!0?null:l.jsx(Jn,{viewName:"remote-control",errorTitle:f("error.viewCrashed"),retryLabel:f("app.retry"),children:l.jsx(lX,{onNavigate:tt})});case"editor":return null;case"changes":return null;case"settings":return l.jsx(Jn,{viewName:"settings",errorTitle:f("error.viewCrashed"),retryLabel:f("app.retry"),children:l.jsx(cX,{})});case"keybindings":return l.jsx(Jn,{viewName:"keybindings",errorTitle:f("error.viewCrashed"),retryLabel:f("app.retry"),children:l.jsx(iX,{})});case"metrics":return l.jsx(Jn,{viewName:"metrics",errorTitle:f("error.viewCrashed"),retryLabel:f("app.retry"),children:l.jsx(aX,{})});case"stats":return l.jsx(Jn,{viewName:"stats",errorTitle:f("error.viewCrashed"),retryLabel:f("app.retry"),children:l.jsx(dX,{})});case"traces":return l.jsx(Jn,{viewName:"traces",errorTitle:f("error.viewCrashed"),retryLabel:f("app.retry"),children:l.jsx(pX,{})});case"workers":return l.jsx(Jn,{viewName:"workers",errorTitle:f("error.viewCrashed"),retryLabel:f("app.retry"),children:l.jsx(mX,{})});case"logs":return l.jsx(Jn,{viewName:"logs",errorTitle:f("error.viewCrashed"),retryLabel:f("app.retry"),children:l.jsx(sX,{})});case"docs":return l.jsx(Jn,{viewName:"docs",errorTitle:f("error.viewCrashed"),retryLabel:f("app.retry"),children:l.jsx(s1,{})});default:return null}};return e?l.jsxs("div",{className:"flex h-screen h-[100dvh] flex-col overflow-hidden bg-bg-primary font-sans text-text-primary",children:[l.jsx(g.Suspense,{fallback:l.jsx(Si,{}),children:wn()}),l.jsx(r1,{}),l.jsx(V0,{})]}):le==="docs"&&window.location.hash.includes("standalone")?l.jsx("div",{className:"flex h-screen h-[100dvh] bg-bg-primary text-text-primary transition-colors duration-200 font-sans overflow-hidden",children:l.jsx(g.Suspense,{fallback:l.jsx(Si,{}),children:l.jsx(s1,{})})}):le==="editor"&&window.location.hash.includes("standalone")?l.jsx("div",{className:"flex h-screen h-[100dvh] bg-bg-primary text-text-primary transition-colors duration-200 font-sans overflow-hidden",children:l.jsx(g.Suspense,{fallback:l.jsx(Si,{}),children:l.jsx(a1,{isVisible:!0})})}):le==="canvas-pane"?l.jsx("div",{className:"flex h-screen h-[100dvh] bg-bg-primary text-text-primary transition-colors duration-200 font-sans overflow-hidden",children:l.jsx(g.Suspense,{fallback:l.jsx(Si,{}),children:l.jsx(nX,{})})}):le==="canvas"&&window.location.hash.includes("standalone")?l.jsx("div",{className:"flex h-screen h-[100dvh] bg-bg-primary text-text-primary transition-colors duration-200 font-sans overflow-hidden",children:l.jsx(g.Suspense,{fallback:l.jsx(Si,{}),children:l.jsx(i1,{})})}):l.jsxs("div",{className:`flex h-screen h-[100dvh] bg-bg-primary text-text-primary transition-colors duration-200 font-sans overflow-hidden${Q?" history-rail-open":""}`,children:[l.jsx(OJ,{isOpen:z,onClose:Ls,mainView:le,onNavigate:tt,remoteControlEnabled:ze===!0}),l.jsx(DO,{open:jr,onClose:Tn,onSwitchSession:Vt,onNewChat:Pe,onNewAgent:Lt,agentFrameNeedsInput:(X==null?void 0:X.needsInput)??null}),l.jsxs("div",{className:"flex min-h-0 min-w-0 flex-1",children:[l.jsxs("div",{className:"flex-1 flex flex-col min-w-0 min-h-0 relative h-full",children:[l.jsx("div",{style:{display:le!=="editor"&&le!=="changes"?void 0:"none"},children:l.jsx(PJ,{onMenuClick:pn,sessionsPanelOpen:jr,onSplitTerminal:xe,onHistory:Ke,onNewChat:Pe,onCancelNewAgent:se,onToggleSessionsPanel:xn,newAgentMode:ce,agentTransitionMode:Le,conversationTitleOverride:(X==null?void 0:X.topic)??void 0,agentFrameNeedsInput:(X==null?void 0:X.needsInput)??null})}),l.jsxs("div",{className:"flex-1 flex flex-col w-full overflow-hidden relative",children:[l.jsxs("div",{className:"flex-1 flex flex-col w-full min-h-0 overflow-hidden relative",style:VR(le==="chat"),children:[l.jsx(g.Suspense,{fallback:l.jsx(Si,{}),children:kt()}),!o&&!F&&l.jsx("div",{className:"absolute inset-0 z-20 flex flex-1 items-center justify-center bg-bg-primary",style:{display:le==="chat"?"flex":"none"},children:i!=="error"?l.jsx(ea,{size:"large",text:f("app.connecting")}):l.jsxs("div",{className:"text-center",children:[l.jsx("div",{className:"text-text-secondary mb-4 font-medium",children:f("app.connectFailed")}),l.jsx("button",{onClick:()=>u({continue:!0}),className:["px-6 py-2.5 bg-accent-brand text-accent-brand-foreground rounded-full","text-sm font-medium transition-all hover:bg-accent-brand/90","hover:scale-105 active:scale-95 shadow-sm"].join(" "),children:f("app.retry")})]})})]}),l.jsx("div",{className:"flex-1 flex flex-col w-full min-h-0 overflow-hidden",style:{display:le==="terminal"?"flex":"none"},children:l.jsx(g.Suspense,{fallback:l.jsx(Si,{}),children:l.jsx(hX,{})})}),l.jsx("div",{className:"flex-1 flex flex-col w-full",style:{display:le==="canvas"?"flex":"none"},children:l.jsx(Jn,{viewName:"canvas",errorTitle:f("error.viewCrashed"),retryLabel:f("app.retry"),children:l.jsx(g.Suspense,{fallback:l.jsx(Si,{}),children:l.jsx(i1,{})})})}),l.jsx("div",{className:"flex-1 flex flex-col w-full min-h-0 overflow-hidden",style:{display:le==="editor"?"flex":"none"},children:l.jsx(Jn,{viewName:"editor",errorTitle:f("error.viewCrashed"),retryLabel:f("app.retry"),children:l.jsx(g.Suspense,{fallback:l.jsx(Si,{}),children:l.jsx(a1,{onMenuClick:x?pn:void 0,isVisible:le==="editor"})})})}),l.jsx("div",{className:"flex-1 flex flex-col w-full min-h-0 overflow-hidden",style:{display:le==="changes"?"flex":"none"},children:l.jsx(Jn,{viewName:"changes",errorTitle:f("error.viewCrashed"),retryLabel:f("app.retry"),children:l.jsx(g.Suspense,{fallback:l.jsx(Si,{}),children:l.jsx(rX,{onMenuClick:x?pn:void 0})})})}),le!=="chat"&&le!=="terminal"&&le!=="canvas"&&le!=="editor"&&le!=="changes"&&l.jsx(g.Suspense,{fallback:l.jsx(Si,{}),children:wn()})]})]}),l.jsx(cH,{isOpen:Q,onClose:()=>w(!1),projectCwd:Q?T:null,activeSessionId:F?de:Y??s,canSwitchConversations:!0,targetLabel:$?f("sessions.currentTitle"):(re==null?void 0:re.name)||((ni=re==null?void 0:re.intent)==null?void 0:ni.split(/\r?\n/)[0])||f("agents.instanceFallback").replace("{id}",(re==null?void 0:re.id.slice(0,8))||""),onOpenSession:Jt})]}),l.jsx(r1,{}),l.jsx(nH,{isOpen:cr,onClose:()=>Vn(!1),onNavigate:tt,onNewChat:Pe,remoteControlEnabled:ze===!0}),l.jsx(V0,{})]})}SL.createRoot(document.getElementById("root")).render(l.jsx(g.StrictMode,{children:l.jsx(Jn,{children:l.jsx(gX,{})})}));export{NN as $,rp as A,eh as B,ac as C,gr as D,Xc as E,Pi as F,Jp as G,mO as H,hE as I,FH as J,vD as K,yt as L,lD as M,SM as N,yM as O,is as P,SX as Q,Ua as R,Xo as S,$Z as T,cO as U,Dt as V,gu as W,Bt as X,Bo as Y,xo as Z,Ct as _,zt as a,um as a0,SS as a1,Xr as a2,So as a3,hf as a4,$C as a5,Oi as a6,W1 as a7,ef as a8,Zp as a9,q1 as aA,Ts as aB,rD as aC,tm as aD,Xp as aE,$M as aF,m$ as aG,Jo as aH,a$ as aI,M1 as aJ,Y1 as aK,Is as aL,wo as aM,Ge as aN,yI as aO,wD as aP,TD as aQ,hL as aR,_X as aS,_L as aT,du as aa,LL as ab,ic as ac,Co as ad,$J as ae,uf as af,Ea as ag,PC as ah,L1 as ai,Jg as aj,R1 as ak,k1 as al,y$ as am,W9 as an,Q9 as ao,q9 as ap,dI as aq,cu as ar,Wa as as,D1 as at,Uo as au,N1 as av,$1 as aw,sc as ax,Xw as ay,xX as az,Q1 as b,ve as c,eD as d,Rt as e,Ga as f,wX as g,Fe as h,Xi as i,uE as j,Q3 as k,ka as l,sr as m,Or as n,V3 as o,Jr as p,vX as q,ea as r,EB as s,es as t,Re as u,kX as v,WL as w,UC as x,Kt as y,fO as z};
944
+ `+f.slice(Me);b(xt),requestAnimationFrame(()=>{O.selectionStart=O.selectionEnd=ge+1,O.focus()})},className:"composer-add",title:Je("input.newline"),children:l.jsx(aS,{size:15})}),l.jsx("button",{type:"button",disabled:$||!qe&&!Ew,onClick:()=>{qe?kw():!f&&oe&&!qe?dr(oe):dr()},className:"composer-send",title:Je(qe?"input.stop":"input.send"),"aria-label":Je(qe?"input.stop":"input.send"),children:$?l.jsx(yt,{size:14,className:"animate-spin"}):qe?l.jsx(Q1,{size:14,fill:"currentColor",strokeWidth:0}):l.jsx(ic,{size:18,strokeWidth:2.5})})]})]})]})]}),c&&l.jsx(NN,{initialPath:xn,onSelect:O=>{O!==xn&&an(O),d==null||d()},onClose:()=>d==null?void 0:d()}),Ls&&Qe&&l.jsx(GZ,{initialCondition:Qe.condition,onSave:O=>{Qn(!1);const ge=()=>{dr(`/goal ${O}`).catch(()=>{})};nR(()=>{if(qe){kw().then(ge).catch(ge);return}ge()})},onCancel:()=>Qn(!1)})]})}const uJ={JOB_NOT_FOUND:"该智能体会话不存在,可能已被清理",SESSION_OCCUPIED:"该会话正被其他终端或进程占用",SESSION_UNAVAILABLE:"该会话当前不可用,请稍后重试",ADMISSION_FAILED:"会话准入失败,请稍后重试",INTERNAL_ERROR:"服务内部错误,请稍后重试",INVALID_RESPONSE:"服务返回异常,请稍后重试"};function hJ(e,t){if(e instanceof Ju){const n=e.code?uJ[e.code]:void 0;return n||e.message||t}return e instanceof Error?e.message||t:e?String(e):t}const qg=["cli","ptc","minimal","create"],pJ=new Set(qg),Ol=12,Bd=8,Gp=96,mJ=520;function gJ(e){const{trigger:t,viewport:n,menuWidth:r,prefer:i="auto"}=e,s=t.top-Ol-Bd,a=n.height-t.bottom-Ol-Bd;let o=i==="up"||i==="auto"&&s>=a?"up":"down";o==="up"&&s<Gp&&a>s?o="down":o==="down"&&a<Gp&&s>a&&(o="up");const c=Math.min(mJ,Math.max(Gp,o==="up"?s:a)),d=Math.min(Math.max(t.left,Ol),Math.max(Ol,n.width-r-Ol));return o==="up"?{left:d,maxHeight:c,side:o,bottom:n.height-t.top+Bd}:{left:d,maxHeight:c,side:o,top:t.bottom+Bd}}function GN(e){return!e.custom&&pJ.has(e.value)}function fJ(e){const t=[],n=[];for(const r of e)GN(r)?t.push(r):n.push(r);return t.sort((r,i)=>{const s=qg.indexOf(r.value),a=qg.indexOf(i.value);return(s===-1?99:s)-(a===-1?99:a)}),{builtin:t,rest:n}}function bJ(e){const{builtin:t,rest:n}=fJ(e);return[...t,...n]}function yJ(e,t){if(!e)return t;const n=e.replace(/<[^>]+>/g," ").replace(/[#*_`]+/g," ").replace(/\s+/g," ").trim();return n?n.length>96?`${n.slice(0,96).trimEnd()}…`:n:t}const t1=360;function WN({options:e,value:t,label:n,disabled:r=!1,open:i,onOpenChange:s,onSelect:a,direction:o="auto",error:c=null,emptyText:d,noDescriptionText:u,customTagText:h,title:p,buttonClassName:m}){const f=g.useRef(null),b=g.useRef(null),_=g.useRef(null),[v,A]=g.useState(null),S=g.useMemo(()=>bJ(e),[e]);g.useLayoutEffect(()=>{if(!i){A(null);return}const x=k=>{var E,N;if(k&&((E=_.current)!=null&&E.contains(k.target)))return;const C=(N=b.current)==null?void 0:N.getBoundingClientRect();C&&A(gJ({trigger:C,viewport:{width:window.innerWidth,height:window.innerHeight},menuWidth:Math.min(t1,window.innerWidth-24),prefer:o}))};return x(),window.addEventListener("scroll",x,!0),window.addEventListener("resize",x),()=>{window.removeEventListener("scroll",x,!0),window.removeEventListener("resize",x)}},[i,o,S.length]),g.useEffect(()=>{if(!i)return;const x=C=>{var N,z;const E=C.target;(N=f.current)!=null&&N.contains(E)||(z=_.current)!=null&&z.contains(E)||s(!1)},k=C=>{C.key==="Escape"&&s(!1)};return document.addEventListener("pointerdown",x,!0),document.addEventListener("keydown",k),()=>{document.removeEventListener("pointerdown",x,!0),document.removeEventListener("keydown",k)}},[i,s]);const y=i&&v&&l.jsx("div",{ref:_,role:"menu",className:"composer-menu composer-menu-agent",style:{position:"fixed",left:v.left,width:Math.min(t1,window.innerWidth-24),maxHeight:v.maxHeight,...v.side==="up"?{bottom:v.bottom,top:"auto"}:{top:v.top,bottom:"auto"}},onClick:x=>x.stopPropagation(),children:l.jsxs("div",{className:"composer-menu-agent-scroll",children:[c&&l.jsx("div",{className:"composer-menu-agent-error",children:c}),S.length===0&&d&&l.jsx("div",{className:"composer-menu-agent-empty",children:d}),S.map(x=>{const k=x.value===t,C=x.broken?x.broken:GN(x)?x.description||u:yJ(x.description,u);return l.jsxs("button",{type:"button",role:"menuitemradio","aria-checked":k,onClick:()=>{s(!1),a(x.value)},disabled:!!x.broken,className:`composer-menu-agent-item ${k?"is-current":""} ${x.broken?"is-broken":""}`,title:x.broken??x.description,children:[l.jsxs("span",{className:"composer-menu-agent-copy",children:[l.jsxs("span",{className:"composer-menu-agent-name",children:[x.label,x.custom&&l.jsxs("span",{className:"composer-menu-agent-tag",children:[" · ",h]})]}),l.jsx("span",{className:`composer-menu-agent-desc ${x.broken?"is-broken":""}`,children:C})]}),l.jsx("span",{className:"composer-menu-agent-check","aria-hidden":!0,children:k&&l.jsx(gr,{size:16})})]},x.value)})]})});return l.jsxs("div",{ref:f,className:"relative min-w-0 shrink",children:[l.jsxs("button",{ref:b,type:"button",disabled:r,"aria-haspopup":"menu","aria-expanded":i,onClick:()=>s(!i),className:`composer-seat-chip ${r?"cursor-not-allowed opacity-40":""} ${m??""}`,title:p,children:[l.jsx(Is,{size:16,className:"shrink-0"}),l.jsx("span",{className:"min-w-0 truncate",children:n}),l.jsx(sr,{size:12,className:`shrink-0 text-text-tertiary transition-transform ${i?"rotate-180":""}`})]}),y&&eh.createPortal(y,document.body)]})}function _J({targetCwd:e}){const{t}=Re(),n=Ge(E=>E.sessionId),{contextInheritOpen:r,contextSourceSessionId:i,setContextSourceSessionId:s,setContextInheritOpen:a}=en(),[o,c]=g.useState([]),[d,u]=g.useState(!1),[h,p]=g.useState(!1),[m,f]=g.useState(!1),[b,_]=g.useState(0),[v,A]=g.useState(null),S=g.useRef(0),y=g.useCallback(()=>a(!1),[a]),x=e.split("/").filter(Boolean).pop()||e||"/",k=g.useCallback(async()=>{const E=++S.current;if(!e){c([]),u(!1);return}u(!0),A(null);try{const N=await hu(e,{includeAttached:!0,offset:0,limit:20});if(E!==S.current)return;c(N.candidates),f(N.hasMore),_(N.nextOffset??N.candidates.length),!N.hasMore&&i&&!N.candidates.some(z=>z.sessionId===i)&&s(null)}catch(N){E===S.current&&(c([]),A(N instanceof Error?N.message:String(N)))}finally{E===S.current&&u(!1)}},[i,s,e]),C=g.useCallback(async()=>{if(!e||!m||h)return;const E=S.current;p(!0);try{const N=await hu(e,{includeAttached:!0,offset:b,limit:20});if(E!==S.current)return;c(z=>{const Q=new Set(z.map(T=>T.sessionId));return z.concat(N.candidates.filter(T=>!Q.has(T.sessionId)))}),f(N.hasMore),_(N.nextOffset??b+N.candidates.length)}catch(N){E===S.current&&A(N instanceof Error?N.message:String(N))}finally{E===S.current&&p(!1)}},[m,h,b,e]);return g.useEffect(()=>{r&&k().catch(()=>{})},[r,k]),r?l.jsxs("div",{className:"absolute bottom-full left-0 z-50 mb-2 flex max-h-[360px] w-[320px] max-w-[90vw] flex-col overflow-hidden rounded-lg border border-border-muted bg-bg-card shadow-sm",role:"dialog","aria-label":t("inherit.drawer.title"),children:[l.jsxs("div",{className:"flex min-h-12 shrink-0 items-center gap-2 border-b border-border-muted px-3 py-2",children:[l.jsx(P1,{size:13,className:"shrink-0 text-text-tertiary"}),l.jsxs("div",{className:"min-w-0 flex-1",children:[l.jsx("div",{className:"truncate text-[12px] font-medium text-text-primary",children:t("inherit.drawer.title")}),l.jsx("div",{className:"truncate text-[10px] text-text-tertiary",title:e,children:x})]}),l.jsx("button",{type:"button",onClick:y,className:"flex h-6 w-6 shrink-0 items-center justify-center rounded-md text-text-tertiary outline-none transition-colors hover:bg-bg-hover hover:text-text-primary","aria-label":t("agents.panel.close"),children:l.jsx(Bt,{size:14})})]}),l.jsxs("div",{className:"min-h-0 flex-1 overflow-y-auto overscroll-contain px-1.5 pb-2 pt-1",onScroll:E=>{const N=E.currentTarget;N.scrollHeight-N.scrollTop-N.clientHeight<120&&C().catch(()=>{})},children:[l.jsxs("button",{type:"button",onClick:()=>{s(null),y()},className:`flex w-full items-center gap-2 rounded-md px-2 py-2 text-left transition-colors ${i===null?"bg-bg-hover":"hover:bg-bg-hover"}`,children:[l.jsx(Is,{size:14,className:"shrink-0 text-text-tertiary"}),l.jsx("span",{className:"min-w-0 flex-1 truncate text-[13px] text-text-primary",children:t("agents.input.startFrom.blank")}),i===null&&l.jsx(gr,{size:14,className:"shrink-0 text-text-primary"})]}),l.jsx("div",{className:"mt-1.5 px-2 pb-0.5 pt-1 text-[10px] font-medium text-text-tertiary",children:t("inherit.fromSession")}),d&&l.jsxs("div",{className:"flex items-center justify-center gap-2 px-2 py-5 text-[11px] text-text-tertiary",children:[l.jsx(yt,{size:13,className:"animate-spin"}),t("history.loading")]}),!d&&v&&l.jsx("button",{type:"button",onClick:()=>k().catch(()=>{}),className:"w-full px-2 py-4 text-center text-[11px] text-text-tertiary transition-colors hover:text-text-primary",title:v,children:t("history.retry")}),!d&&!v&&o.length===0&&l.jsx("div",{className:"px-2 py-5 text-center text-[11px] text-text-tertiary",children:t("inherit.emptyForDirectory")}),!d&&!v&&o.map(E=>{const N=E.sessionId===n,z=i===E.sessionId;return l.jsxs("button",{type:"button",onClick:()=>{s(E.sessionId),y()},className:`flex w-full items-center gap-2 rounded-md px-2 py-2 text-left transition-colors ${z?"bg-bg-hover":"hover:bg-bg-hover"}`,children:[l.jsx(Jo,{size:14,className:"shrink-0 text-text-tertiary"}),l.jsx("span",{className:"min-w-0 flex-1 truncate text-[13px] text-text-primary",children:E.label}),N&&l.jsx("span",{className:"shrink-0 text-[10px] text-accent-blue",children:t("sessions.current")}),z&&l.jsx(gr,{size:14,className:"shrink-0 text-text-primary"})]},E.sessionId)}),h&&l.jsx("div",{className:"flex items-center justify-center py-2 text-text-tertiary","aria-label":t("history.loading"),children:l.jsx(yt,{size:13,className:"animate-spin"})})]})]}):null}const vJ=[{value:"",labelKey:"agents.input.permission.default",descriptionKey:"agents.input.permission.default.desc"},{value:"default",labelKey:"agents.input.permission.ask",descriptionKey:"mode.default.desc"},{value:"acceptEdits",labelKey:"mode.acceptEdits",descriptionKey:"mode.acceptEdits.desc"},{value:"plan",labelKey:"mode.plan",descriptionKey:"mode.plan.desc"},{value:"auto",labelKey:"mode.auto",descriptionKey:"mode.auto.desc"},{value:"dontAsk",labelKey:"mode.dontAsk",descriptionKey:"mode.dontAsk.desc"},{value:"bypassPermissions",labelKey:"mode.bypassPermissions",descriptionKey:"mode.bypassPermissions.desc"},{value:"fullAccess",labelKey:"mode.fullAccess",descriptionKey:"mode.fullAccess.desc"}];function xJ(e,t,n){var r;return((r=e.find(i=>i.id===t))==null?void 0:r.name)||t||n}function wJ(e){if(e>=1e6){const t=e/1e6;return`${Number.isInteger(t)?t:t.toFixed(1)}M`}return e>=1e3?`${Math.round(e/1e3)}K`:String(e)}function SJ(e){const t=e.replace(/\s*credits\s*$/i,"").trim(),n=Number.parseFloat(t.replace(/^[x×]/i,""));return Number.isFinite(n)&&n>0?`${n}x`:""}function qN(e){return d5({stored:xC(),currentMode:e})}function kJ(){const e=nt.getState();return e.processAgent??e.stagedAgent??(typeof localStorage<"u"?localStorage.getItem(Aa):null)??""}function AJ(){const e=nt.getState().processPermissionMode;return e||qN(Ge.getState().currentMode)}function CJ({model:e,title:t,open:n,onToggle:r,options:i,value:s,onSelect:a,disabled:o=!1,canEditThinking:c,thinkingEditModelId:d,onPreviewThinking:u,onClearThinkingEdit:h,thinkingOptions:p,thinkingValue:m,onSelectThinking:f}){const{t:b}=Re(),_=d?i.find(v=>v.value===d):void 0;return l.jsxs("div",{className:"relative min-w-0 shrink","data-composer-model-select":!0,children:[l.jsxs("button",{type:"button",onClick:r,disabled:o,className:["composer-chip max-w-[220px]",o?"cursor-not-allowed opacity-40":""].join(" "),title:t,"aria-label":`${t}: ${e}`,"aria-expanded":n,children:[l.jsx("span",{className:"min-w-0 truncate",children:e}),!o&&l.jsx(sr,{size:12,className:`shrink-0 text-text-tertiary transition-transform ${n?"rotate-180":""}`})]}),n&&!o&&l.jsxs("div",{className:"absolute bottom-full right-0 z-50 mb-2",children:[l.jsx("div",{className:"composer-menu w-[248px] max-w-[calc(100vw-24px)] overflow-hidden",role:"menu","aria-label":t,children:l.jsx("div",{className:"max-h-[340px] overflow-y-auto py-1",children:i.map(v=>{const A=v.value===s,S=d===v.value;return l.jsxs("div",{className:"group relative mx-1 flex items-center rounded-md transition-colors hover:bg-bg-primary",onMouseEnter:()=>{c&&u(v.value)},children:[l.jsxs("button",{type:"button",role:"menuitemradio","aria-checked":A,onClick:()=>a(v.value),className:"flex min-w-0 flex-1 items-center gap-2 py-1 pl-2 pr-1 text-left",title:v.description,children:[l.jsx("span",{className:"min-w-0 flex-1 truncate text-[12px] leading-tight text-text-primary",children:v.label}),l.jsx("span",{className:"w-10 shrink-0 text-right text-[11px] leading-tight tabular-nums text-text-tertiary",children:v.meta})]}),l.jsxs("span",{className:"relative mr-1.5 flex w-4 shrink-0 items-center justify-center",children:[A&&l.jsx(gr,{size:12,className:`text-text-primary transition-opacity ${c?"group-hover:opacity-0":""} ${S?"opacity-0":""}`}),c&&l.jsx("button",{type:"button",onMouseEnter:y=>{y.stopPropagation(),u(v.value)},onClick:y=>{y.stopPropagation(),u(v.value)},className:`absolute inset-0 flex items-center justify-center rounded transition-opacity ${S?"opacity-100 text-text-primary":"opacity-0 group-hover:opacity-100 text-text-tertiary hover:text-text-primary"}`,title:b("input.editThinking"),children:l.jsx(Wa,{size:11})})]})]},v.value)})})}),_&&c&&l.jsxs("div",{className:"composer-menu absolute right-full top-0 mr-2 w-[212px] max-w-[calc(100vw-24px)] py-1",onMouseLeave:h,children:[l.jsx("div",{className:"px-3 pb-1 pt-1 text-[12px] font-semibold text-text-primary",children:_.label}),_.description&&l.jsx("div",{className:"px-3 pb-1.5 text-[10px] leading-snug text-text-tertiary",children:_.description}),l.jsx("div",{className:"px-3 pb-0.5 pt-1 text-[11px] text-text-tertiary",children:b("input.thinkingLevel")}),p.map(v=>l.jsx("div",{className:"mx-1 rounded-md transition-colors hover:bg-bg-primary",children:l.jsxs("button",{type:"button",onClick:()=>f(v.value),className:"flex w-full items-center justify-between gap-2 py-1 pl-2 pr-1.5 text-left",title:v.description,children:[l.jsx("span",{className:"truncate text-[12px] leading-tight text-text-primary",children:v.label}),m===v.value&&l.jsx(gr,{size:12,className:"shrink-0 text-text-primary"})]})},v.value))]})]})]})}function EJ({onCreated:e,onCancel:t}){var Jt,Lt;const{t:n,tryT:r}=Re(),{createJob:i}=tn(),{models:s,currentModel:a,currentMode:o,modes:c,thoughtLevel:d}=Ge(),u=Ge(se=>se.sessionId),{contextSourceSessionId:h,contextInheritOpen:p,setContextSourceSessionId:m,setContextInheritOpen:f,setNewJobMode:b}=en(),_=Xr(se=>se.cwd),v=nt(se=>se.stagedAgent),A=nt(se=>se.processAgent),S=nt(se=>se.processPermissionMode),y=nt(se=>se.agents),[x,k]=g.useState(""),[C,E]=g.useState(!1),[N,z]=g.useState(null),[Q,T]=g.useState(null),[w,L]=g.useState(AJ),I=g.useRef(w!==""),[R,$]=g.useState(!1),[D,U]=g.useState(kJ),Y=g.useRef(!!nt.getState().processAgent),[ee,P]=g.useState(_||""),[q,ue]=g.useState(null),[_e,ke]=g.useState(!1),[H,G]=g.useState(null),[V,oe]=g.useState(!1),[J,he]=g.useState(!1),[ne,pe]=g.useState(null),[re,ce]=g.useState(!1),[ae,Ae]=g.useState(!1),[de,F]=g.useState(null),ie=g.useRef(null),fe=g.useRef(null),X=g.useRef(null),Ce=g.useRef(null),Ee=g.useRef(null),Le=g.useRef(null),We=g.useRef(ee),je=g.useRef(0),[et,ct]=g.useState(!1),{images:gt,setImages:qe,addImages:wt,removeImage:Nt,loadingImageCount:qt}=HN(),{files:$t,setFiles:It,addFiles:cr,removeFile:Vn}=BN();g.useEffect(()=>{N===null&&a&&z(a)},[a,N]),g.useEffect(()=>{!ee&&_&&P(_)},[ee,_]),g.useEffect(()=>{We.current!==ee&&(We.current=ee,m(null),f(!1))},[ee,f,m]),g.useEffect(()=>{const se=ee||_||"";if(!se){ue(null);return}let $e=!1;return ke(!0),B5(se).then(kt=>{$e||ue(kt)}).catch(()=>{$e||ue(null)}).finally(()=>{$e||ke(!1)}),()=>{$e=!0}},[ee,_]),g.useEffect(()=>{!D&&v&&U(v)},[D,v]),g.useEffect(()=>{const se=ie.current;!se||se.offsetParent===null||(se.style.height="auto",se.style.height=`${Math.max(52,Math.min(se.scrollHeight,336))}px`)},[x]),g.useEffect(()=>{if(!V&&ne===null&&H!=="model"&&!re&&!p)return;const se=$e=>{const kt=$e.composedPath();fe.current&&kt.includes(fe.current)||X.current&&kt.includes(X.current)||Ce.current&&kt.includes(Ce.current)||Ee.current&&kt.includes(Ee.current)||(oe(!1),pe(null),G(null),F(null),ce(!1))};return document.addEventListener("pointerdown",se,!0),()=>{document.removeEventListener("pointerdown",se,!0)}},[H,V,ne,re,p]),g.useEffect(()=>{const se=$e=>{if($e.key==="Escape"&&!ae){if(V||H||re||p){oe(!1),pe(null),G(null),F(null),ce(!1),f(!1),$e.preventDefault();return}t==null||t()}};return document.addEventListener("keydown",se),()=>{document.removeEventListener("keydown",se)}},[p,re,t,H,f,V,ae]);const ze=g.useMemo(()=>[{value:"",label:n("agents.input.model.default")},...s.map(se=>({value:se.id,label:se.name,description:se.description||void 0,meta:SJ(se.credits??"")||(se.contextWindow?wJ(se.contextWindow):"")}))],[s,n]),rt=g.useMemo(()=>[{value:"",label:n("agents.input.effort.default"),description:n("agents.input.effort.default.desc")},...(N===a?(d==null?void 0:d.options)??[]:[]).filter(se=>!["disabled","enabled"].includes(se.value)).map(se=>({value:se.value,label:se.name,description:se.description||void 0}))],[a,N,d,n]),Ot=rt.length>1,le=g.useCallback(se=>{z(se),T(null),G(null)},[]),Ne=g.useCallback(se=>{T(se||null)},[]),Qe=g.useMemo(()=>{const se=D||(q==null?void 0:q.defaultAgentName);return vJ.filter($e=>se!=="minimal"||$e.value!=="plan").map($e=>{const kt=c.find(wn=>wn.id===$e.value);return{value:$e.value,label:r($e.labelKey)||(kt==null?void 0:kt.name)||$e.value,description:r($e.descriptionKey)||(kt==null?void 0:kt.description)}})},[c,r,D,q==null?void 0:q.defaultAgentName]),os=g.useMemo(()=>{var se;return((se=q==null?void 0:q.agents)!=null&&se.length?q.agents:y).map($e=>({value:$e.name,label:Es($e,r),description:Qo($e,r),custom:$e.custom,source:$e.source,broken:$e.broken}))},[q==null?void 0:q.agents,y,r]),Br=D||(q==null?void 0:q.defaultAgentName)||"";g.useEffect(()=>{Y.current||!A||(Y.current=!0,U(A))},[A]),g.useEffect(()=>{const se=S||(q==null?void 0:q.permissionMode);se&&(I.current=!0,L(se))},[S,q==null?void 0:q.permissionMode]),g.useEffect(()=>{if(I.current)return;const se=qN(o);se&&(I.current=!0,L(se))},[o]),g.useEffect(()=>{Br==="minimal"&&w==="plan"&&L("")},[Br,w]);const Je=((Jt=os.find(se=>se.value===Br))==null?void 0:Jt.label)??(D||n("agents.input.agent.default")),vn=((Lt=Qe.find(se=>se.value===w))==null?void 0:Lt.label)||n("agents.input.permission.default"),Rr=g.useMemo(()=>n(h?h===u?"agents.input.startFrom.continue":"agents.input.startFrom.session":"agents.input.startFrom.blank"),[h,u,n]),an=x.trimStart().startsWith("!"),jr=an?x.trim().slice(1).trim():x.trim(),xn=gt.length>0||$t.length>0,Tn=ee||_||"",pn=QC(Tn),Ls=Math.max(0,((q==null?void 0:q.repoTargets.length)??1)-1),Qn=g.useCallback(se=>{const $e=se.filter((Kn,ni,Z)=>Z.findIndex(ye=>ye===Kn||ye.name===Kn.name&&ye.type===Kn.type&&ye.size===Kn.size&&ye.lastModified===Kn.lastModified)===ni),{images:kt,others:wn}=FN($e);kt.some(Kn=>Kn.size>Ih)&&Dt.error(n("input.imageTooLarge")),wn.some(Kn=>Kn.size>ww)&&Dt.error(n("input.fileTooLarge")),kt.length>0&&wt(kt).catch(()=>{}),wn.length>0&&cr(wn).catch(()=>{})},[cr,wt,n]),K=g.useCallback(se=>{var $e;se.preventDefault(),se.stopPropagation(),je.current++,($e=se.dataTransfer)!=null&&$e.types.includes("Files")&&ct(!0)},[]),xe=g.useCallback(se=>{se.preventDefault(),se.stopPropagation(),je.current--,je.current===0&&ct(!1)},[]),Pe=g.useCallback(se=>{se.preventDefault(),se.stopPropagation()},[]),ft=g.useCallback(se=>{se.preventDefault(),se.stopPropagation(),je.current=0,ct(!1),Qn(zu(se.dataTransfer))},[Qn]),Vt=g.useCallback(se=>{const $e=zu(se.clipboardData),kt=zN(se.clipboardData),wn=$e.filter(Kn=>!fl.includes(Kn.type));(kt.length>0||wn.length>0)&&(se.preventDefault(),Qn([...kt,...wn]))},[Qn]),tt=g.useCallback(async()=>{var se;if(!C){if(an&&xn){Dt.error(n("agents.input.attachmentsNotForShell"));return}if(!(!jr&&!xn)){if(xn&&!Tn){Dt.error(n("input.attachmentUploadFailed"));return}E(!0);try{const $e=[...gt.map((Z,ye)=>({id:Z.id,name:sJ(Z.mimeType,ye),blob:aJ(Z),mimeType:Z.mimeType})),...$t.filter(Sw).map(Z=>({id:Z.id,name:Z.name,blob:Wg(Z),mimeType:Z.mimeType})),...$t.filter($N).map(Z=>({id:Z.id,name:Z.name,blob:Wg(Z),mimeType:Z.mimeType}))],kt=$e.length>0?await ON(Tn,"new-agent",$e,X1):[],wn=kt.map(Z=>R?Z.absolutePath:Z.relativePath),Kn=eJ(jr,wn),ni=await i(Kn,{cwd:ee||void 0,name:Ec(jr||((se=kt[0])==null?void 0:se.name)||"")||void 0,...an?{bash:!0}:{agent:D||Br||void 0,model:N||void 0,effort:Q||void 0,permissionMode:o5(w)||void 0,bgIsolation:R?"worktree":"none",sourceSessionId:h??void 0}});ni&&(k(""),qe([]),It([]),await(e==null?void 0:e(ni)),b(!1))}catch($e){const kt=$e instanceof Error&&$e.message.startsWith("Upload file failed")?n("input.attachmentUploadFailed"):hJ($e,n("error.jobCreateFailed"));Dt.error(kt)}finally{E(!1)}}}},[h,i,C,D,ee,Q,N,jr,Br,$t,xn,gt,e,w,b,an,n,Tn,R]),Ke=g.useCallback(se=>{se.nativeEvent.isComposing||se.key==="Enter"&&!se.shiftKey&&(se.preventDefault(),tt())},[tt]);return l.jsxs(l.Fragment,{children:[l.jsxs("div",{className:"composer-hero-row",ref:Ee,children:[l.jsxs("button",{type:"button",onClick:()=>ce(se=>!se),className:"composer-seat-chip",title:`${n("agents.input.directory")}: ${Tn||"/"}`,"aria-label":n("agents.input.directory"),"aria-expanded":re,children:[l.jsx(Bo,{size:16,className:"shrink-0"}),l.jsx("span",{className:"min-w-0 truncate",children:pn}),Ls>0&&l.jsxs("span",{className:"shrink-0 text-[12px] font-medium text-text-tertiary",children:["+",Ls]}),l.jsx(sr,{size:12,className:`shrink-0 text-text-tertiary transition-transform ${re?"rotate-180":""}`})]}),re&&l.jsxs("div",{className:"composer-menu absolute left-0 top-full z-50 mt-2 max-h-[280px] w-[320px] max-w-[calc(100vw-24px)] overflow-y-auto overscroll-contain py-1",children:[l.jsxs("div",{className:"px-3 py-2",children:[l.jsx("div",{className:"text-[13px] font-medium text-text-primary",children:n("agents.input.directory.choose")}),l.jsx("div",{className:"mt-0.5 text-[12px] leading-snug text-text-tertiary",children:n("agents.input.directory.hint")})]}),q==null?void 0:q.repoTargets.map(se=>{const $e=se.path===Tn;return l.jsxs("button",{type:"button",onClick:()=>{P(se.path),ce(!1)},className:`flex w-full items-center gap-2 px-3 py-2 text-left transition-colors hover:bg-bg-hover ${$e?"text-text-primary":"text-text-secondary"}`,title:se.path,children:[l.jsx(Jp,{size:12,className:"shrink-0 text-text-tertiary"}),l.jsxs("span",{className:"min-w-0 flex-1",children:[l.jsx("span",{className:"block truncate text-[13px]",children:se.name}),l.jsx("span",{className:"block truncate text-[12px] text-text-tertiary",children:se.branch||se.path})]}),$e&&l.jsx(gr,{size:12,className:"shrink-0 text-text-primary"})]},se.path)}),_e&&l.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 text-[12px] text-text-tertiary",children:[l.jsx(yt,{size:12,className:"animate-spin"}),n("agents.input.directory.loading")]}),l.jsxs("button",{type:"button",onClick:()=>{ce(!1),Ae(!0)},className:"flex w-full items-center gap-2 px-3 py-2 text-left text-[13px] text-text-secondary transition-colors hover:bg-bg-hover hover:text-text-primary",children:[l.jsx(IM,{size:12,className:"shrink-0 text-text-tertiary"}),n("agents.input.directory.browse")]})]}),l.jsx(WN,{options:os,value:Br,label:Je,disabled:an,open:J,onOpenChange:se=>{he(se),se&&(oe(!1),pe(null),G(null))},onSelect:se=>{U(se),rm(se)},noDescriptionText:n("mainAgent.noDescription"),customTagText:n("mainAgent.customTag"),title:n("agents.input.agent")})]}),l.jsx("div",{className:"composer-input-wrap pb-[env(safe-area-inset-bottom)] md:pb-0",children:l.jsxs("div",{className:`composer-card relative overflow-visible transition-colors ${et?"composer-card-dragging":""}`,onDragEnter:K,onDragLeave:xe,onDragOver:Pe,onDrop:ft,children:[et&&l.jsx("div",{className:"pointer-events-none absolute inset-0 z-20 flex items-center justify-center rounded-[22px] bg-accent-brand/5",children:l.jsx("span",{className:"text-[14px] font-medium text-accent-brand",children:n("input.dropHint")})}),l.jsx("input",{ref:Le,type:"file",accept:"*/*",multiple:!0,className:"hidden",onChange:se=>{se.target.files&&Qn(Array.from(se.target.files)),se.target.value=""}}),xn&&l.jsxs("div",{className:"flex flex-wrap gap-2 px-3 pt-1",children:[gt.map(se=>l.jsxs("div",{className:"group relative",children:[l.jsx("img",{src:se.dataUrl,alt:"",className:"h-16 w-16 rounded-lg border border-border-default object-cover"}),l.jsx("button",{type:"button",onClick:()=>Nt(se.id),className:"absolute -right-1.5 -top-1.5 flex h-5 w-5 items-center justify-center rounded-full border border-border-default bg-bg-tertiary opacity-0 transition-opacity hover:border-accent-red hover:bg-accent-red hover:text-white group-hover:opacity-100",children:l.jsx(Bt,{size:12})})]},se.id)),Array.from({length:qt}).map((se,$e)=>l.jsx("div",{className:"h-16 w-16 rounded-lg border border-border-default skeleton-shimmer"},`skeleton-${$e}`)),$t.map(se=>l.jsxs("div",{className:"group relative flex max-w-[200px] items-center gap-2 rounded-lg border border-border-default bg-bg-primary px-3 py-2",children:[l.jsx(Pi,{size:16,className:"shrink-0 text-text-tertiary"}),l.jsxs("div",{className:"min-w-0 flex-1",children:[l.jsx("div",{className:"truncate text-[12px] text-text-primary",title:se.name,children:se.name}),l.jsx("div",{className:"text-[11px] text-text-tertiary",children:PN(se.size)})]}),l.jsx("button",{type:"button",onClick:()=>Vn(se.id),className:"flex h-4 w-4 shrink-0 items-center justify-center rounded-full text-text-tertiary opacity-0 transition-opacity hover:text-accent-red group-hover:opacity-100",children:l.jsx(Bt,{size:12})})]},se.id))]}),l.jsx("div",{className:"relative",children:l.jsx("textarea",{ref:ie,value:x,onChange:se=>k(se.target.value),onKeyDown:Ke,onPaste:Vt,placeholder:n(an?"agents.input.shellPlaceholder":"agents.input.placeholder"),rows:1,enterKeyHint:"send","aria-label":n("agents.input.placeholder"),className:"composer-textarea composer-textarea-hero"})}),l.jsxs("div",{className:"composer-toolbar",onClick:se=>{var $e;se.target===se.currentTarget&&(($e=ie.current)==null||$e.focus())},children:[l.jsxs("div",{className:"composer-tools",children:[l.jsx("button",{type:"button",onClick:()=>{var se;oe(!1),pe(null),G(null),(se=Le.current)==null||se.click()},className:"composer-add",title:n("input.addFile"),"aria-label":n("input.addFile"),children:l.jsx(is,{size:16})}),l.jsxs("div",{ref:X,className:"relative min-w-0 shrink",children:[l.jsxs("button",{type:"button",disabled:an,onClick:()=>{an||(pe(se=>se==="permission"?null:"permission"),oe(!1),G(null))},className:"composer-chip",title:n("agents.input.permission"),"aria-expanded":ne==="permission",children:[l.jsx(QD,{size:14,className:"shrink-0"}),l.jsx("span",{className:"min-w-0 truncate",children:vn}),l.jsx(sr,{size:12,className:`shrink-0 text-text-tertiary transition-transform ${ne==="permission"?"rotate-180":""}`})]}),ne==="permission"&&!an&&l.jsx("div",{className:"composer-menu absolute bottom-full left-0 z-50 mb-2 max-h-[280px] w-[240px] max-w-[calc(100vw-24px)] overflow-y-auto py-1",children:Qe.map(se=>l.jsxs("button",{type:"button",role:"menuitemradio","aria-checked":se.value===w,onClick:()=>{L(se.value),se.value&&lf(se.value),pe(null)},className:"flex w-full items-center gap-2 rounded-[10px] px-2.5 py-2 text-left text-[13px] text-text-secondary transition-colors hover:bg-bg-hover hover:text-text-primary",title:se.description,children:[l.jsx("span",{className:"min-w-0 flex-1 truncate",children:se.label}),se.value===w&&l.jsx(gr,{size:12,className:"shrink-0 text-text-primary"})]},se.value))})]}),l.jsxs("div",{ref:fe,className:"relative shrink-0",children:[l.jsx("button",{type:"button",onClick:()=>{an||(oe(se=>!se),pe(null),G(null))},disabled:an,className:"composer-add",title:n("agents.input.settings"),"aria-label":n("agents.input.settings"),"aria-expanded":V,children:l.jsx(V1,{size:15})}),V&&!an&&l.jsx("div",{className:"composer-menu absolute bottom-full left-0 z-50 mb-2 max-h-[320px] w-[264px] max-w-[calc(100vw-24px)] overflow-y-auto overscroll-contain py-1",role:"menu","aria-label":n("agents.input.settings"),children:l.jsxs("div",{className:"px-1",children:[l.jsxs("button",{type:"button",onClick:()=>{u&&(oe(!1),pe(null),f(!0))},disabled:!u,className:"flex w-full items-center gap-2 rounded-md px-2 py-2 text-left text-text-secondary transition-colors hover:bg-bg-hover hover:text-text-primary disabled:cursor-not-allowed disabled:opacity-40",title:n(u?"agents.input.startFrom":"agents.input.startFrom.unavailable"),children:[l.jsx(P1,{size:13,className:"shrink-0 text-text-tertiary"}),l.jsx("span",{className:"min-w-0 flex-1 truncate text-[13px]",children:n("agents.input.startFrom")}),l.jsx("span",{className:"max-w-[116px] truncate text-[12px] text-text-tertiary",children:Rr}),l.jsx(sr,{size:11,className:"shrink-0 -rotate-90 text-text-tertiary"})]}),l.jsxs("button",{type:"button",role:"switch","aria-checked":R,onClick:()=>$(se=>!se),className:"flex w-full items-center gap-2 rounded-md px-2 py-2 text-left text-text-secondary outline-none transition-colors hover:bg-bg-hover hover:text-text-primary",title:n(R?"agents.input.worktree.on":"agents.input.worktree.off"),children:[l.jsx(Jp,{size:13,className:"shrink-0 text-text-tertiary"}),l.jsx("span",{className:"min-w-0 flex-1 truncate text-[13px]",children:n("agents.input.worktree")}),l.jsx("span",{className:`relative h-3 w-5 shrink-0 overflow-hidden rounded-full transition-colors ${R?"bg-text-primary":"bg-border-default"}`,children:l.jsx("span",{className:`absolute left-0.5 top-0.5 h-2 w-2 rounded-full bg-bg-card transition-transform ${R?"translate-x-2":"translate-x-0"}`})})]})]})}),l.jsx(_J,{targetCwd:ee||_||""})]}),an&&l.jsxs("span",{className:"flex h-7 items-center gap-1 px-1 text-[13px] text-text-tertiary",children:[l.jsx(Xo,{size:13}),n("agents.input.shellJob")]})]}),l.jsxs("div",{className:"composer-trailing",children:[l.jsx("div",{ref:Ce,className:"min-w-0",children:l.jsx(CJ,{model:xJ(s,N||"",n("agents.input.model.default")),title:n("agents.input.model"),open:H==="model",onToggle:()=>{G(H==="model"?null:"model"),oe(!1),pe(null)},options:ze,value:N||"",onSelect:le,disabled:an,canEditThinking:Ot,thinkingEditModelId:de,onPreviewThinking:F,onClearThinkingEdit:()=>F(null),thinkingOptions:rt,thinkingValue:Q||"",onSelectThinking:Ne})}),l.jsx("button",{type:"button",onClick:()=>tt(),disabled:C||!jr&&!xn,className:"composer-send",title:n("agents.input.submit"),"aria-label":n("agents.input.submit"),children:C?l.jsx(yt,{size:14,className:"animate-spin"}):l.jsx(ic,{size:18,strokeWidth:2.5})})]})]})]})}),ae&&l.jsx(NN,{initialPath:ee||_||"/",onSelect:se=>{P(se),Ae(!1)},onClose:()=>Ae(!1)})]})}function IJ({children:e}){return l.jsx("code",{className:"bg-bg-tertiary px-1.5 py-0.5 rounded text-xs text-accent-brand",children:e})}function n1(e){const t=[];let n=e,r=0;for(;n.length>0;){const i=n.indexOf("<code>");if(i===-1){t.push(l.jsx("span",{children:n},r));break}i>0&&(t.push(l.jsx("span",{children:n.substring(0,i)},r)),r++);const s=n.indexOf("</code>",i);if(s===-1){t.push(l.jsx("span",{children:n},r));break}const a=n.substring(i+6,s);t.push(l.jsx(IJ,{children:a},r)),r++,n=n.substring(s+7)}return l.jsx(l.Fragment,{children:t})}function TJ(){const{error:e,isSubmitting:t,login:n,clearError:r}=Zr(),{t:i}=Re(),[s,a]=g.useState(""),o=g.useCallback(async d=>{d.preventDefault(),s.trim()&&await n(s)},[s,n]),c=e?i(e)!==e?i(e):e:null;return l.jsxs("div",{className:"login-page",children:[l.jsxs("div",{className:"login-orb login-orb-right",children:[l.jsx("div",{className:"login-orb-layer login-orb-layer-1"}),l.jsx("div",{className:"login-orb-layer login-orb-layer-2"})]}),l.jsx("div",{className:"login-ellipse login-ellipse-outer"}),l.jsx("div",{className:"login-ellipse login-ellipse-outer2"}),l.jsx("div",{className:"login-ellipse login-ellipse-inner"}),l.jsxs("div",{className:"login-orb login-orb-left",children:[l.jsx("div",{className:"login-orb-layer login-orb-layer-1"}),l.jsx("div",{className:"login-orb-layer login-orb-layer-2"})]}),l.jsx("div",{className:"login-ellipse login-ellipse-left"}),l.jsx("div",{className:"login-ellipse login-ellipse-left2"}),l.jsxs("div",{className:"login-content",children:[l.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",gap:"16px"},children:[l.jsx("div",{className:"login-logo",children:l.jsx("img",{src:cf,alt:"CodeBuddy"})}),l.jsx("h1",{className:"login-title",children:i("login.slogan")}),l.jsx("p",{className:"login-tagline",children:i("login.tagline")})]}),l.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",gap:"4px"},children:[c&&l.jsx("div",{className:"login-error",style:{marginBottom:"8px"},children:c}),l.jsxs("form",{onSubmit:o,style:{display:"flex",flexDirection:"column",alignItems:"center",gap:"8px"},children:[l.jsx("input",{type:"password",name:"password",value:s,onChange:d=>{a(d.target.value),e&&r()},placeholder:i("login.placeholder"),autoFocus:!0,autoComplete:"current-password",disabled:t,className:"login-input"}),l.jsx("button",{type:"submit",disabled:t||!s.trim(),className:"login-btn",children:t?l.jsx("span",{className:"thinking-text",children:i("login.submit")}):i("login.submit")})]}),l.jsxs("div",{className:"login-hints",children:[l.jsx("p",{children:i("login.hint.password")}),l.jsx("p",{children:i("login.hint.urlAuth").includes("<code>")?n1(i("login.hint.urlAuth")):i("login.hint.urlAuth")}),l.jsx("p",{children:i("login.hint.disable").includes("<code>")?n1(i("login.hint.disable")):i("login.hint.disable")})]})]})]}),l.jsxs("div",{className:"login-footer",children:[l.jsx("a",{href:"#privacy",children:i("login.privacy")}),l.jsx("a",{href:"#terms",children:i("login.terms")})]})]})}function NJ({sessionId:e}){const{t,tryT:n}=Re(),[r,i]=g.useState(!1),s=nt(E=>E.backendSupport),a=ew(s),{agents:o,currentAgentName:c,sessionBlank:d,status:u,error:h,applyAgentFromResponse:p,applySetAgentResult:m,setLoading:f,setError:b}=nt(),_=nt(E=>E.stagedAgent),v=nt(E=>E.processAgent),A=c||_||v||"cli",S=o.find(E=>E.name===A),y=S?`${Es(S,n)}${S.custom?` · ${t("mainAgent.trustLocal")}`:""}`:Es({name:A},n),x=S?Qo(S,n):void 0;g.useEffect(()=>{if(!r||!e||s!==!0)return;let E=!1;return f(),st().callExtMethod("_codebuddy.ai/getAgents",{sessionId:e}).then(N=>{!E&&(N!=null&&N.agents)&&p({agents:N.agents,currentAgentName:N.currentAgentName,defaultAgentName:N.defaultAgentName,sessionBlank:N.sessionBlank})}).catch(N=>{E||b(N instanceof Error?N.message:String(N))}),()=>{E=!0}},[r,e,s,f,b,p]);const k=g.useCallback(async E=>{if(!(!e||E===c)){rm(E),fC(),f();try{const N=await st().callExtMethod("session/set_agent",{sessionId:e,agentName:E});if(N!=null&&N.agentName){m({agentName:N.agentName,models:N.models??[],currentModelId:N.currentModelId??"",sessionBlank:N.sessionBlank??!1});const z=N.models??[];Array.isArray(z)&&Ge.getState().setModels(z.map(Q=>{var T,w;return{id:Q.modelId??Q.id,name:Q.name||Q.modelId||Q.id,description:Q.description??null,credits:((T=Q._meta)==null?void 0:T.credits)??null,contextWindow:((w=Q._meta)==null?void 0:w.maxInputTokens)??null}})),N.currentModelId&&Ge.getState().setCurrentModel(N.currentModelId),rm(E)}}catch(N){b(N instanceof Error?N.message:String(N)),i(!0)}}},[e,c,f,b,m]);if(!a.enabled)return null;const C=o.map(E=>({value:E.name,label:Es(E,n),description:Qo(E,n),custom:E.custom,source:E.source,broken:E.broken}));return d?l.jsx(WN,{options:C,value:A,label:y,open:r,onOpenChange:i,onSelect:E=>{k(E).catch(()=>{})},error:u==="error"?h:null,emptyText:t("mainAgent.empty"),noDescriptionText:t("mainAgent.noDescription"),customTagText:t("mainAgent.customTag"),title:x||t("mainAgent.selectAgent")}):l.jsx(RN,{tone:"seat"})}const RJ=300,LJ=5e3;function MJ(){const{t:e}=Re(),t=qi(S=>S.visible),n=qi(S=>S.total),r=qi(S=>S.completed),i=qi(S=>S.connectingServers),s=qi(S=>S.startedAt),a=qi(S=>S.finished),o=qi(S=>S.failed),c=qi(S=>S.timedOut),d=qi(S=>S.hide),[u,h]=g.useState(!1),p=g.useRef(void 0),[,m]=g.useState(0),[f,b]=g.useState(!1);g.useEffect(()=>(t?(p.current&&clearTimeout(p.current),p.current=setTimeout(()=>{h(!0),p.current=void 0},RJ)):(p.current&&(clearTimeout(p.current),p.current=void 0),h(!1)),()=>{p.current&&(clearTimeout(p.current),p.current=void 0)}),[t]),g.useEffect(()=>{if(!a||!t||f)return;const S=setTimeout(()=>d(),LJ);return()=>clearTimeout(S)},[a,t,f,d]);const _=u&&(i.length>0||a);g.useEffect(()=>{if(!_||a||s===void 0)return;const S=setInterval(()=>m(y=>(y+1)%1e6),1e3);return()=>clearInterval(S)},[_,a,s]);const v=g.useMemo(()=>{if(!_)return null;if(a){if(o.length===0&&c.length===0)return{tone:"ok",text:e("mcp.startup.ready",{total:n})};const E=[];return o.length>0&&E.push(e("mcp.startup.failed",{names:o.join(", ")})),c.length>0&&E.push(e("mcp.startup.timedOut",{names:c.join(", ")})),{tone:"warn",text:E.join(" · ")}}const S=3,y=i.slice(0,S).join(", ")+(i.length>S?", …":""),x=s===void 0?0:Math.max(0,Math.floor((Date.now()-s)/1e3)),k=e("mcp.startup.elapsed",{seconds:x});return{tone:"busy",text:`${n===1&&i.length===1?e("mcp.startup.booting",{name:i[0]}):e("mcp.startup.starting",{completed:r,total:n,names:y})} (${k})`}},[_,a,o,c,i,n,r,s,e]);if(!v)return null;const A=v.tone==="busy"?"animate-pulse bg-accent-brand":v.tone==="ok"?"bg-accent-green":"bg-accent-yellow";return l.jsx("div",{className:"max-w-3xl mx-auto px-3 pb-1 md:px-0",children:l.jsxs("div",{className:"flex items-center gap-2 text-xs text-text-secondary",onMouseEnter:()=>b(!0),onMouseLeave:()=>b(!1),children:[l.jsx("span",{className:`inline-block h-1.5 w-1.5 flex-shrink-0 rounded-full ${A}`}),l.jsx("span",{className:"truncate",children:v.text})]})})}const DJ="data:image/svg+xml,%3csvg%20width='24'%20height='24'%20viewBox='0%200%2024%2024'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3cg%20clip-path='url(%23copilot-clip-34e811bed903495093b85bf96a98fb1b_0)'%3e%3crect%20width='24'%20height='24'%20rx='12'%20fill='%234C4F6B'%3e%3c/rect%3e%3cpath%20d='M3.4689%2011.0144C3.32344%2011.2025%203.31607%2011.4567%203.4345%2012.0298C3.65883%2013.0748%204.24029%2014.4426%205.15579%2016.0716L5.747%2017.1172L5.72862%2017.511C5.70544%2017.9326%205.72848%2018.5857%205.77921%2019.0271C5.80994%2019.2967%205.8055%2019.3035%205.66483%2019.4638C5.12042%2020.0864%205.03916%2021.1287%205.44787%2022.2839C5.62456%2022.7775%206.16958%2023.6999%206.50726%2024.0756C7.35392%2025.0154%208.35051%2025.4646%209.11147%2025.246C9.25446%2025.2051%209.28403%2025.213%209.47117%2025.3424C10.182%2025.8233%2011.3834%2026.2377%2012.4447%2026.3663C14.2242%2026.5843%2016.2727%2026.143%2018.8281%2024.9925C19.8948%2024.5099%2022.2541%2023.1352%2023.2513%2022.4096C25.1083%2021.0667%2026.4805%2019.6414%2027.251%2018.2635C27.9337%2017.0364%2028.2735%2015.7781%2028.2495%2014.5174C28.2466%2014.2525%2028.2536%2014.2359%2028.3599%2014.1746C28.8797%2013.8703%2029.1497%2013.198%2029.0927%2012.3562C29.075%2012.1165%2029.0266%2011.7946%2028.9902%2011.6448C28.7404%2010.7144%2028.0885%209.59971%2027.4078%208.94729C26.6515%208.22182%2025.7943%207.9129%2025.1958%208.14598C25.0631%208.19758%2025.0452%208.19542%2024.9177%208.08995C24.6357%207.86124%2023.9604%207.43473%2023.5488%207.22673L23.1224%207.01477L22.8206%206.45595C22.0392%205.01609%2020.7826%203.33003%2019.8801%202.50992C19.4937%202.15818%2019.2668%202.03929%2019.019%202.05739C18.866%202.06657%2018.8535%202.07379%2018.645%202.26084C18.0389%202.79819%2017.1889%204.41355%2016.3588%206.60463L16.1271%207.21325L15.7053%207.34845C14.3909%207.76995%2013.2238%208.30219%2012.1896%208.94928C11.1973%209.56799%2010.6591%209.97037%209.84886%2010.688L9.36087%2011.1197L9.13878%2011.0813C7.00072%2010.7039%205.07892%2010.5639%204.19776%2010.7186C3.84772%2010.7832%203.55743%2010.9008%203.4689%2011.0144Z'%20fill='%23D2D3E0'%3e%3c/path%3e%3crect%20x='6.68555'%20y='16.3788'%20width='17.7918'%20height='11.5605'%20rx='4.61469'%20transform='rotate(-30%206.68555%2016.3788)'%20fill='%23212234'%3e%3c/rect%3e%3cg%3e%3crect%20x='12.2119'%20y='17.2593'%20width='2.13173'%20height='4.42744'%20rx='1.06587'%20transform='rotate(-30%2012.2119%2017.2593)'%20fill='%23D2D3E0'%3e%3canimate%20attributeName='height'%20values='4.42744;2.2;4.42744;4.42744;2.2;4.42744'%20dur='0.6s'%20begin='0s;blink134e811bed903495093b85bf96a98fb1b_0.end+3s'%20id='blink134e811bed903495093b85bf96a98fb1b_0'%3e%3c/animate%3e%3canimate%20attributeName='y'%20values='17.2593;18.2593;17.2593;17.2593;18.2593;17.2593'%20dur='0.6s'%20begin='0s;blink134e811bed903495093b85bf96a98fb1b_0.end+3s'%3e%3c/animate%3e%3canimate%20attributeName='opacity'%20values='1;0.2;1;1;0.2;1'%20dur='0.6s'%20begin='0s;blink134e811bed903495093b85bf96a98fb1b_0.end+3s'%3e%3c/animate%3e%3c/rect%3e%3c/g%3e%3cg%3e%3crect%20x='17.9634'%20y='13.9387'%20width='2.13173'%20height='4.42744'%20rx='1.06587'%20transform='rotate(-30%2017.9634%2013.9387)'%20fill='%23D2D3E0'%3e%3canimate%20attributeName='height'%20values='4.42744;2.2;4.42744;4.42744;2.2;4.42744'%20dur='0.6s'%20begin='0s;blink234e811bed903495093b85bf96a98fb1b_0.end+3s'%20id='blink234e811bed903495093b85bf96a98fb1b_0'%3e%3c/animate%3e%3canimate%20attributeName='y'%20values='13.9387;14.9387;13.9387;13.9387;14.9387;13.9387'%20dur='0.6s'%20begin='0s;blink234e811bed903495093b85bf96a98fb1b_0.end+3s'%3e%3c/animate%3e%3canimate%20attributeName='opacity'%20values='1;0.2;1;1;0.2;1'%20dur='0.6s'%20begin='0s;blink234e811bed903495093b85bf96a98fb1b_0.end+3s'%3e%3c/animate%3e%3c/rect%3e%3c/g%3e%3c/g%3e%3cdefs%3e%3cclipPath%20id='copilot-clip-34e811bed903495093b85bf96a98fb1b_0'%3e%3crect%20width='24'%20height='24'%20rx='12'%20fill='white'%3e%3c/rect%3e%3c/clipPath%3e%3c/defs%3e%3c/svg%3e",$J="data:image/svg+xml,%3csvg%20width='873'%20height='612'%20viewBox='0%200%20873%20612'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M611.24%200C631.42%200.472994%20652.67%200.151247%20672.917%200.149414L783.53%200.125977L783.58%20114.446C783.58%20131.188%20782.828%20155.62%20783.732%20171.959C793.764%20172.165%20866.262%20170.817%20869.239%20173.294C869.728%20173.699%20870.138%20174.379%20870.486%20174.905L872.008%20175.384C873.402%20179.664%20872.344%20228.902%20872.338%20236.71C872.313%20263.731%20873.157%20518.745%20871.959%20521.349C871.837%20521.605%20871.58%20521.905%20871.415%20522.119L869.141%20522.375C841.374%20521.684%20811.566%20522.247%20783.646%20522.271C784.001%20538.325%20783.695%20555.229%20783.72%20571.344C783.738%20583.932%20784.056%20598.74%20783.451%20611.182C613.783%20610.846%20273.598%20611.469%2087.6807%20611.041C87.3452%20610.736%2087.0093%20610.436%2086.6738%20610.137L86.2393%20607.375C86.831%20602.028%2086.4052%20585.668%2086.3984%20579.416L86.2812%20521.838C82.9453%20522.522%2063.9127%20522.272%2059.0283%20522.266L0.391602%20522.259L0.398438%20278.798L0.427734%20209.334C0.430803%20201.523%200.934097%20181.445%200%20174.62C0.578928%20172.779%200.0735528%20173.48%201.33105%20172.293C17.2444%20171.377%2036.4875%20172.458%2052.7188%20172.065C59.0087%20171.913%2081.4327%20171.805%2086.0195%20172.717L85.9805%2056.9336L85.9072%2021.3467C85.895%2015.7024%2085.6474%205.58945%2086.2832%200.297852L89.3057%200.0224609C145.847%201.00635%20204.767%200.149918%20261.493%200.137695L261.571%2058.8008C261.576%2063.634%20261.865%2082.5764%20261.06%2086.293C288.984%2085.6006%20319.108%2086.1736%20347.17%2086.1797L509.068%2086.1846L576.67%2086.1357C582.985%2086.1314%20604.124%2085.7374%20608.728%2086.8135C607.982%2081.7879%20608.33%2064.0733%20608.33%2058.0186L608.428%201.34473C609.424%20-0.0534957%20608.978%200.391111%20611.24%200ZM697.12%20173.048C694.553%20171.797%20619.805%20172.389%20610.134%20172.389L279.41%20172.397L201.266%20172.392C193.899%20172.39%20184.497%20172.27%20176.995%20172.399C175.636%20172.423%20175.324%20173.65%20174.702%20174.81L172.704%20175.383C172.033%20177.999%20172.341%20204.836%20172.348%20208.9L172.398%20294.312L172.37%20445.969L172.349%20494.032C172.347%20501.781%20172.011%20513.954%20172.658%20521.324C174.533%20523.401%20174.111%20521.52%20174.854%20522.534C175.611%20523.561%20175.655%20525.034%20177.928%20525.016C181.545%20524.988%20185.335%20524.97%20189.044%20524.966H347.752L604.785%20524.96L669.054%20525.009C673.406%20525.009%20693.575%20525.296%20696.857%20524.643C697.499%20523.408%20697.493%20523.505%20697.542%20522.118C696.815%20500.607%20697.389%20475.931%20697.389%20454.243V327.045L697.383%20228.248C697.383%20211.843%20696.729%20190.781%20697.64%20174.935L697.12%20173.048Z'%20fill='%2300BC90'/%3e%3cpath%20d='M347.56%20260.864L349.808%20261.441C351.42%20265.483%20350.329%20418.222%20350.229%20435.792C344.53%20436.85%20263.503%20436.929%20260.894%20435.722L261.464%20433.765C261.114%20420.392%20261.416%20405.532%20261.413%20392.005L261.412%20313.381C261.422%20299.699%20262.22%20276.275%20261.106%20263.652C261.428%20261.859%20261.059%20262.619%20262.19%20261.257C268.232%20260.664%20277.082%20261.319%20283.456%20261.111C303.554%20260.454%20327.973%20262.241%20347.56%20260.864Z'%20fill='%2300BC90'/%3e%3cpath%20d='M608.752%20260.881L610.641%20261.353C612.854%20266.169%20610.268%20347.019%20611.302%20358.962C611.693%20363.539%20611.436%20434.199%20610.892%20435.767C610.293%20435.847%20609.248%20436.027%20608.685%20436.028C584.88%20436.436%20548.549%20435.89%20523.533%20435.943C522.702%20435.945%20522.567%20435.098%20522.127%20434.149C522.787%20429.284%20522.445%20415.565%20522.445%20410.114L522.415%20362.246L522.457%20298.316C522.463%20288.598%20522.94%20272.837%20522.097%20263.668L522.586%20261.78C525.887%20259.891%20595.756%20261.699%20608.752%20260.881Z'%20fill='%2300BC90'/%3e%3c/svg%3e";function OJ({isOpen:e,onClose:t,mainView:n,onNavigate:r,remoteControlEnabled:i}){const{t:s}=Re(),{userInfo:a}=yC(),o=Jr(m=>m.info),c=Jr(m=>m.fetch),d=ui(m=>m.fileChanges.length);g.useEffect(()=>{o||c()},[c,o]);const u=(a==null?void 0:a.userName)||(o==null?void 0:o.userName)||s("sidebar.user"),h=Zr(m=>m.accountState),p=g.useCallback(async()=>{window.confirm(s("account.logout.confirm"))&&await Zr.getState().accountLogout()},[s]);return l.jsxs(l.Fragment,{children:[l.jsx("div",{className:`sidebar-overlay ${e?"":"sidebar-overlay-hidden"}`,onClick:t}),l.jsxs("aside",{className:`sidebar ${e?"":"sidebar-closed"}`,role:"navigation","aria-label":"Main navigation",children:[l.jsxs("div",{className:"sidebar-header",children:[l.jsx("img",{src:$J,alt:"CodeBuddy",className:"sidebar-logo"}),l.jsx("span",{className:"sidebar-brand",children:"CodeBuddy"}),l.jsx("div",{className:"flex-1"}),l.jsx("button",{onClick:t,className:"flex h-7 w-7 items-center justify-center rounded-md text-text-tertiary transition-colors hover:bg-bg-hover hover:text-text-primary md:hidden","aria-label":"Close sidebar",children:l.jsx(Bt,{size:16})})]}),l.jsxs("nav",{className:"sidebar-nav","aria-label":"Primary",children:[l.jsxs("button",{className:`sidebar-nav-item ${n==="chat"?"active":""}`,onClick:()=>r("chat"),"aria-current":n==="chat"?"page":void 0,title:s("sidebar.chatMode"),children:[l.jsx(Jo,{size:16}),l.jsx("span",{children:s("sidebar.chatMode")})]}),l.jsxs("button",{className:`sidebar-nav-item ${n==="workers"?"active":""}`,onClick:()=>r("workers"),title:s("sidebar.workers"),children:[l.jsx($1,{size:16}),l.jsx("span",{children:s("sidebar.workers")})]}),i&&l.jsxs("button",{className:`sidebar-nav-item ${n==="remote-control"?"active":""}`,onClick:()=>r("remote-control"),title:s("sidebar.remoteControl"),children:[l.jsx(q1,{size:16}),l.jsx("span",{children:s("sidebar.remoteControl")})]})]}),l.jsx("div",{className:"sidebar-content",children:l.jsxs("div",{className:"px-3 py-1",children:[l.jsx("div",{className:"sidebar-section-title",children:s("sidebar.group.workspace")}),l.jsxs("button",{className:`sidebar-nav-item ${n==="tasks"?"active":""}`,onClick:()=>r("tasks"),title:s("sidebar.nav.tasks"),children:[l.jsx(Xg,{size:16}),l.jsx("span",{children:s("sidebar.nav.tasks")})]}),l.jsxs("button",{className:`sidebar-nav-item ${n==="terminal"?"active":""}`,onClick:()=>r("terminal"),title:s("sidebar.terminalMode"),children:[l.jsx(Xo,{size:16}),l.jsx("span",{children:s("sidebar.terminalMode")})]}),l.jsxs("button",{className:`sidebar-nav-item ${n==="canvas"?"active":""}`,onClick:()=>r("canvas"),title:s("sidebar.canvas"),children:[l.jsx(z1,{size:16}),l.jsx("span",{children:s("sidebar.canvas")})]}),l.jsxs("button",{className:`sidebar-nav-item ${n==="editor"?"active":""}`,onClick:()=>r("editor"),title:s("sidebar.editor"),children:[l.jsx(Jg,{size:16}),l.jsx("span",{children:s("sidebar.editor")})]}),l.jsxs("button",{className:`sidebar-nav-item ${n==="changes"?"active":""}`,onClick:()=>r("changes"),title:s("sidebar.changes"),children:[l.jsx(Gu,{size:16}),l.jsx("span",{children:s("sidebar.changes")}),d>0&&l.jsx("span",{className:"sidebar-badge",children:d})]}),l.jsxs("button",{className:`sidebar-nav-item ${n==="plugins"?"active":""}`,onClick:()=>r("plugins"),title:s("sidebar.nav.plugins"),children:[l.jsx(ja,{size:16}),l.jsx("span",{children:s("sidebar.nav.plugins")})]}),l.jsx("div",{className:"sidebar-section-title",children:s("sidebar.group.observability")}),l.jsxs("button",{className:`sidebar-nav-item ${n==="stats"?"active":""}`,onClick:()=>r("stats"),title:s("sidebar.stats"),children:[l.jsx(M1,{size:16}),l.jsx("span",{children:s("sidebar.stats")})]}),l.jsxs("button",{className:`sidebar-nav-item ${n==="traces"?"active":""}`,onClick:()=>r("traces"),title:s("sidebar.traces"),children:[l.jsx(J1,{size:16}),l.jsx("span",{children:s("sidebar.traces")})]}),l.jsxs("button",{className:`sidebar-nav-item ${n==="metrics"?"active":""}`,onClick:()=>r("metrics"),title:s("sidebar.metrics"),children:[l.jsx(N1,{size:16}),l.jsx("span",{children:s("sidebar.metrics")})]}),l.jsxs("button",{className:`sidebar-nav-item ${n==="logs"?"active":""}`,onClick:()=>r("logs"),title:s("sidebar.logs"),children:[l.jsx(D1,{size:16}),l.jsx("span",{children:s("sidebar.logs")})]}),l.jsx("div",{className:"sidebar-section-title",children:s("sidebar.group.preferences")}),l.jsxs("button",{className:`sidebar-nav-item ${n==="settings"?"active":""}`,onClick:()=>r("settings"),title:s("sidebar.preferences"),children:[l.jsx(ef,{size:16}),l.jsx("span",{children:s("sidebar.preferences")})]}),l.jsxs("button",{className:`sidebar-nav-item ${n==="keybindings"?"active":""}`,onClick:()=>r("keybindings"),title:s("sidebar.keybindings"),children:[l.jsx(U1,{size:16}),l.jsx("span",{children:s("sidebar.keybindings")})]}),l.jsxs("button",{className:`sidebar-nav-item ${n==="docs"?"active":""}`,onClick:()=>r("docs"),title:s("sidebar.docs"),children:[l.jsx(L1,{size:16}),l.jsx("span",{children:s("sidebar.docs")})]})]})}),l.jsx("div",{className:"sidebar-footer",children:l.jsxs("div",{className:"sidebar-user",children:[l.jsx("img",{src:DJ,alt:"User",className:"sidebar-user-avatar"}),l.jsxs("div",{className:"sidebar-user-info",children:[l.jsx("div",{className:"sidebar-user-name",children:u}),(o==null?void 0:o.version)&&l.jsxs("div",{className:"sidebar-user-status",children:["v",o.version]})]}),h==="authenticated"&&l.jsx("button",{onClick:p,className:"w-7 h-7 flex items-center justify-center rounded-md text-text-tertiary hover:text-text-primary hover:bg-bg-hover transition-colors ml-auto",title:s("account.logout"),"aria-label":s("account.logout"),children:l.jsx(YM,{size:14})})]})})]})]})}function PJ({onMenuClick:e,sessionsPanelOpen:t=!0,onSplitTerminal:n,onHistory:r,onNewChat:i,onCancelNewAgent:s,onToggleSessionsPanel:a,rightActions:o,newAgentMode:c=!1,agentTransitionMode:d=null,agentFrameNeedsInput:u=null,conversationTitleOverride:h}){const{t:p}=Re(),{topic:m,sessionId:f,sessionSwitching:b}=Ge(),_=tn(J=>J.jobs),v=tn(J=>J.selectedJobId),A=tn(J=>J.selectedJobTitle),{mainChatActive:S,mainAgentSessionId:y,agentSessionIds:x}=en(),{isAgentRunning:k,hasPendingInterruption:C,timeline:E}=ot(),{mainView:N,layout:z,terminalTitle:Q}=zt(),[T,w]=g.useState(!1),L=g.useRef(null),I=N==="terminal",$=Fo(z)<RC,D=S?void 0:_.find(J=>J.id===v),U=g.useMemo(()=>new Set(E.flatMap(J=>J.type==="question"&&J.status==="pending"?J.sessionId?[J.sessionId]:[]:J.type==="interruption"&&!J.resolved?J.sessionId?[J.sessionId]:[]:[])),[E]),Y=S?y??f:v?x[v]??(D==null?void 0:D.sessionId)??null:null,ee=!!(Y&&U.has(Y)),P=!S&&u===!0,q=S?_.find(J=>!!(y??f)&&J.sessionId===(y??f)):void 0,ue=D??q,_e=h||bm(m)||p("chat.newChat"),ke=!S&&v?A||(D==null?void 0:D.name)||Ec((D==null?void 0:D.intent)||"")||p("agents.instanceFallback").replace("{id}",v.slice(0,8)):p("sessions.currentTitle"),H=()=>(ue==null?void 0:ue.state)==="failed"?p("agents.state.failed"):ee||P||S&&C||(ue==null?void 0:ue.status)==="waiting"||(ue==null?void 0:ue.state)==="blocked"||ue!=null&&ue.waitingFor?p("agents.group.attention"):S&&k||(ue==null?void 0:ue.status)==="busy"||(ue==null?void 0:ue.tempo)==="active"||(ue==null?void 0:ue.state)==="working"&&(ue==null?void 0:ue.status)!=="idle"&&(ue==null?void 0:ue.tempo)!=="idle"?p("agents.group.working"):(ue==null?void 0:ue.state)==="stopped"?p("agents.state.stopped"):(ue==null?void 0:ue.state)==="done"||ue!=null&&ue.settled?p("agents.state.completed"):p("agents.state.idle");g.useEffect(()=>{if(!T)return;const J=he=>{L.current&&!L.current.contains(he.target)&&w(!1)};return document.addEventListener("mousedown",J),()=>document.removeEventListener("mousedown",J)},[T]);const G=g.useCallback(J=>{w(!1),n==null||n(J)},[n]),V=()=>{switch(N){case"chat":return c?p("agents.action.new"):ke;case"terminal":return Q||p("terminal.title");case"settings":return p("settings.title");case"tasks":return p("scheduled.title");case"plugins":return p("sidebar.nav.plugins");case"workers":return p("workers.title");case"metrics":return p("sidebar.metrics");case"logs":return p("sidebar.logs");case"docs":return p("sidebar.docs");case"remote-control":return p("sidebar.remoteControl");case"keybindings":return p("keybindings.title");default:return""}},oe=()=>o||(I?l.jsxs("div",{ref:L,className:"relative",children:[l.jsx("button",{onClick:()=>$&&w(!T),className:`text-text-secondary transition-colors flex items-center justify-center w-8 h-8 rounded-full ${$?"hover:text-text-primary hover:bg-bg-secondary":"opacity-40 cursor-not-allowed"}`,title:$?void 0:p("terminal.maxPanes"),"aria-label":p("terminal.split"),children:l.jsx(sS,{size:20})}),T&&l.jsxs("div",{className:"absolute right-0 top-full mt-1 bg-bg-secondary border border-border-muted rounded-lg shadow-lg py-1 z-50 min-w-[140px]",children:[l.jsxs("button",{onClick:()=>G("horizontal"),className:"w-full flex items-center gap-3 px-4 py-2.5 text-[13px] text-text-primary hover:bg-bg-hover transition-colors",children:[l.jsx(sS,{size:16,className:"text-text-secondary"}),l.jsx("span",{children:p("terminal.splitHorizontal")})]}),l.jsxs("button",{onClick:()=>G("vertical"),className:"w-full flex items-center gap-3 px-4 py-2.5 text-[13px] text-text-primary hover:bg-bg-hover transition-colors",children:[l.jsx(OD,{size:16,className:"text-text-secondary"}),l.jsx("span",{children:p("terminal.splitVertical")})]})]})]}):N==="chat"?l.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[c&&s&&l.jsx("button",{onClick:s,className:"flex h-8 shrink-0 items-center whitespace-nowrap rounded-full px-3 text-[12px] text-text-tertiary transition-colors hover:bg-bg-hover hover:text-text-primary",title:`${p("agents.action.cancelNew")} (Esc)`,"aria-label":p("agents.action.cancelNew"),children:p("agents.action.cancelNew")}),i&&!c&&l.jsx("button",{onClick:i,disabled:!f||b,className:"flex h-8 w-8 items-center justify-center rounded-full text-text-tertiary transition-colors hover:bg-bg-hover hover:text-text-primary disabled:cursor-not-allowed disabled:opacity-40 disabled:hover:bg-transparent",title:p("agents.action.newConversation"),"aria-label":p("agents.action.newConversation"),children:l.jsx(sD,{size:17})}),l.jsx("button",{onClick:r,className:"flex h-8 w-8 items-center justify-center rounded-full text-text-tertiary transition-colors hover:bg-bg-hover hover:text-text-primary",title:p("sidebar.chatHistory"),"aria-label":p("sidebar.chatHistory"),children:l.jsx(PM,{size:17})})]}):null);return l.jsxs("div",{className:"sticky top-0 z-10 isolate grid h-14 flex-shrink-0 grid-cols-[minmax(0,1fr)_minmax(0,2fr)_minmax(0,1fr)] items-center border-b border-border-muted bg-bg-primary px-3 text-xs transition-colors duration-200 sm:px-4",role:"banner","aria-label":p("sidebar.status"),children:[l.jsxs("div",{className:"relative z-10 flex min-w-0 items-center gap-1",children:[e&&l.jsx("button",{type:"button",onClick:e,className:"flex h-8 w-8 shrink-0 items-center justify-center rounded-full text-text-tertiary transition-colors hover:bg-bg-hover hover:text-text-primary md:hidden","aria-label":p("layout.sidebar"),title:p("layout.sidebar"),children:l.jsx(W1,{size:18})}),N==="chat"&&a&&l.jsx("button",{type:"button",onClick:a,className:`flex h-8 w-8 shrink-0 items-center justify-center rounded-full transition-colors ${t?"bg-bg-hover text-text-primary":"text-text-tertiary hover:bg-bg-hover hover:text-text-primary"}`,"aria-label":p("layout.agents"),title:p("layout.agents"),"aria-pressed":t,children:l.jsx(Is,{size:18})})]}),l.jsxs("div",{className:"relative z-0 flex min-w-0 flex-col items-center justify-center px-3 text-center",children:[l.jsx("span",{className:"max-w-full truncate text-[14px] font-medium text-text-primary",children:V()}),N==="chat"&&l.jsx("span",{className:"mt-0.5 block max-w-full truncate text-[10px] text-text-tertiary","aria-live":"polite","aria-atomic":"true",children:c?p("agents.input.hint"):d==="creating"?p("agents.phase.starting"):d==="restoring"?p("agents.phase.resuming"):`${H()} · ${_e}`})]}),l.jsx("div",{className:"relative z-10 flex items-center justify-self-end",children:oe()})]})}let Wp=1e5;function BJ(e){if(!Array.isArray(e))return[];const t=[];let n=null;for(const r of e)if(r.sessionUpdate==="user_message_chunk"){n&&(t.push(n),n=null);const i=r.content,s=(i==null?void 0:i.text)||"";if(!s.trim())continue;t.push({type:"message",id:`member-msg-${++Wp}`,role:"user",content:s,timestamp:Date.now()})}else if(r.sessionUpdate==="agent_message_chunk"){const i=r.content;if((i==null?void 0:i.type)==="thinking")continue;const s=(i==null?void 0:i.text)||"";if(!s)continue;n?n={...n,content:n.content+s}:n={type:"message",id:`member-msg-${++Wp}`,role:"assistant",content:s,timestamp:Date.now()}}else if(r.sessionUpdate==="tool_call"){n&&(t.push(n),n=null);const s=(r._meta||{})["codebuddy.ai/toolName"]||"";t.push({type:"tool_call",id:r.toolCallId||`member-tc-${++Wp}`,name:r.title||s||r.kind||"tool",kind:r.kind||"other",toolName:s,input:r.rawInput||r.input,status:r.status==="completed"?"completed":r.status==="failed"?"failed":"running",locations:r.locations,content:r.content})}else if(r.sessionUpdate==="tool_call_update"){const i=t.findIndex(s=>s.type==="tool_call"&&s.id===r.toolCallId);if(i!==-1){const s=t[i];t[i]={...s,status:r.status==="completed"?"completed":r.status==="failed"?"failed":s.status,result:r.rawOutput||r.toolResult||s.result,...r.content!==void 0?{content:r.content}:{}}}}return n&&t.push(n),t}function jJ(){var p;const e=Ir(m=>m.focusedMemberName),t=Ir(m=>m.memberHistories),n=Ir(m=>m.members),r=Ir(m=>m.setFocusedMember),i=g.useRef(null),s=n.find(m=>m.name===e),a=e&&t[e]||[],o=g.useMemo(()=>BJ(a),[a]),c=g.useMemo(()=>Jx(o),[o]);g.useEffect(()=>{i.current&&(i.current.scrollTop=i.current.scrollHeight)},[c]);const d=g.useCallback(()=>{r(null)},[r]),u=(s==null?void 0:s.status)==="running"||(s==null?void 0:s.status)==="pending",{t:h}=Re();return l.jsxs("div",{ref:i,className:"absolute inset-0 overflow-y-auto overflow-x-hidden",children:[l.jsx("div",{className:"sticky top-0 z-10 bg-bg-primary/95 backdrop-blur-sm border-b border-border-muted/30",children:l.jsxs("div",{className:"max-w-3xl mx-auto px-4 sm:px-6 py-3 flex items-center gap-3",children:[l.jsx("button",{type:"button",onClick:d,className:"p-1.5 rounded-md hover:bg-bg-secondary text-text-tertiary hover:text-text-secondary transition-colors",title:h("team.backToMain"),children:l.jsx(R1,{size:16})}),l.jsx(Is,{size:16,className:"text-accent-purple flex-shrink-0"}),l.jsxs("span",{className:"text-[14px] font-semibold text-accent-purple",children:["@",e]}),(s==null?void 0:s.description)&&l.jsx("span",{className:"text-[12px] text-text-tertiary truncate flex-1",children:s.description}),u&&l.jsx(yt,{size:14,className:"animate-spin text-accent-purple flex-shrink-0"}),l.jsx("div",{className:"flex-1"}),s&&l.jsxs("span",{className:"text-[11px] text-text-tertiary flex-shrink-0",children:[s.toolCallCount?h("team.tools").replace("{count}",String(s.toolCallCount)):"",(p=s.tokenUsage)!=null&&p.lastContextWindow?`${s.toolCallCount?" · ":""}${h("team.tokens").replace("{count}",String(Math.round(s.tokenUsage.lastContextWindow/1e3))+"k")}`:""]})]})}),l.jsx("div",{className:"px-4 sm:px-6 pt-4 pb-8",children:l.jsxs("div",{className:"max-w-3xl mx-auto flex flex-col",children:[u&&c.length===0?l.jsxs("div",{className:"flex items-center justify-center gap-2 py-20 text-text-tertiary text-[13px]",children:[l.jsx(yt,{size:16,className:"animate-spin"}),l.jsx("span",{children:h("team.loadingHistory")})]}):c.length===0?l.jsx("div",{className:"flex items-center justify-center py-20 text-text-tertiary text-[13px]",children:h("team.noHistory")}):c.map((m,f)=>{if(m.kind==="user"){const b=m.entry.content?oI(m.entry.content):void 0;if(b)return b.from==="system"?null:l.jsx("div",{children:l.jsx(lI,{msg:b})},m.entry.id);let _=m.entry.content||"";return _=_.replace(/<system-reminder>[\s\S]*?<\/system-reminder>\s*/g,"").trim(),_?l.jsx("div",{className:"flex justify-end mb-6",children:l.jsx("div",{className:"max-w-[85%] rounded-lg rounded-tr-sm bg-bg-secondary px-4 py-2.5 sm:max-w-[75%]",children:l.jsx("p",{className:"whitespace-pre-wrap break-words text-text-primary text-chat",children:_})})},m.entry.id):null}return m.kind==="assistant_message"?l.jsx("div",{className:"mb-6",children:l.jsx(uh,{message:m.entry})},m.entry.id):m.kind==="assistant_tools"?l.jsx("div",{className:"mb-6",children:l.jsx(aI,{entries:m.entries})},`tools-${f}`):null}),u&&c.length>0&&l.jsxs("div",{className:"flex items-center gap-2 py-4 text-text-tertiary text-[12px]",children:[l.jsx(yt,{size:12,className:"animate-spin"}),l.jsx("span",{children:h("team.agentRunning")})]})]})})]})}const FJ={info:F1,success:VL,warn:wo,error:Fa},UJ={info:"text-accent-blue",success:"text-accent-green",warn:"text-accent-yellow",error:"text-accent-red"};function zJ({item:e}){const t=Ea(o=>o.removeToast),[n,r]=g.useState(!1),i=FJ[e.type],s=()=>{r(!0),setTimeout(()=>t(e.id),200)},a=async()=>{if(e.action)try{await e.action.onClick()!==!1&&s()}catch{s()}};return l.jsxs("div",{role:"alert",className:["flex items-start gap-3 px-4 py-3 rounded-xl border border-border-default shadow-lg","bg-bg-card backdrop-blur-sm","max-w-[360px] min-w-[280px]","transition-all duration-200",n?"opacity-0 translate-x-4":"opacity-100 translate-x-0","animate-fadeIn"].join(" "),children:[l.jsx(i,{size:18,className:`${UJ[e.type]} shrink-0 mt-0.5`}),l.jsxs("div",{className:"flex-1 min-w-0 flex flex-col gap-2",children:[l.jsx("p",{className:"text-[13px] text-text-primary leading-[1.5] break-words",children:e.message}),e.action&&l.jsx("button",{type:"button",onClick:a,className:"self-start px-2.5 py-1 rounded-md text-[12px] font-medium bg-accent-blue text-white hover:opacity-90 transition-opacity",children:e.action.label})]}),l.jsx("button",{onClick:s,"aria-label":"Dismiss",className:"shrink-0 w-5 h-5 flex items-center justify-center rounded text-text-tertiary hover:text-text-primary transition-colors",children:l.jsx(Bt,{size:14})})]})}function r1(){const e=Ea(t=>t.toasts);return e.length===0?null:l.jsx("div",{className:"fixed bottom-6 right-6 z-[999] flex flex-col-reverse gap-2 pointer-events-auto max-md:bottom-20 max-md:right-4 max-md:left-4 max-md:items-stretch",children:e.map(t=>l.jsx(zJ,{item:t},t.id))})}function HJ(e,t){const n=[];for(const r of e)r.type==="tool_call"&&n.push(r);for(const r of t.values())n.push(r);return n}function GJ(e,t){const n={};for(const r of e){const i=r.input||{},s=r.toolName;if(s==="TaskCreate"){const a=r.result,o=typeof a=="string"?a:a&&typeof a=="object"?String(a.text??a.output??""):"",c=!o&&Array.isArray(r.content)?r.content.reduce((p,m)=>{var f;return p||String(((f=m==null?void 0:m.content)==null?void 0:f.text)??(m==null?void 0:m.text)??"")},""):"",d=(o||c).match(/Task #(\d+)/),u=d?d[1]:`t-${Object.keys(n).length+1}`;let h=i.owner?String(i.owner):void 0;if(!h&&(t!=null&&t.length)){const p=i.subject?String(i.subject).toLowerCase():"",m=i.description?String(i.description).toLowerCase():"",f=p+" "+m;for(const b of t)if(f.includes(b.toLowerCase())){h=b;break}}n[u]={id:u,subject:i.subject?String(i.subject):"",status:"pending",owner:h,activeForm:i.activeForm?String(i.activeForm):void 0}}else if(s==="TaskUpdate"){const a=i.taskId?String(i.taskId):void 0;if(a&&n[a]){const o=n[a];i.status&&i.status!=="deleted"&&(o.status=String(i.status)),i.subject&&(o.subject=String(i.subject)),i.owner!==void 0&&(o.owner=i.owner?String(i.owner):void 0),i.activeForm&&(o.activeForm=String(i.activeForm)),i.status==="deleted"&&delete n[a]}}}return Object.values(n)}function WJ(e){return e.filter(t=>t.toolName==="TaskCreate"||t.toolName==="TaskUpdate").length}function qJ({status:e}){switch(e){case"completed":return l.jsx(Cc,{size:14,className:"text-accent-green flex-shrink-0"});case"in_progress":return l.jsx(yt,{size:14,className:"text-accent-brand flex-shrink-0 animate-spin"});default:return l.jsx(Kl,{size:14,className:"text-text-tertiary flex-shrink-0"})}}function VJ({member:e,isFocused:t,onClick:n}){var c;const r=e.status==="running"||e.status==="pending",i=e.status==="failed"||e.status==="killed",s=GO(e.color),a=gf(e.color),o=[];return e.toolCallCount&&o.push(`${e.toolCallCount} tools`),(c=e.tokenUsage)!=null&&c.lastContextWindow&&o.push(`${(e.tokenUsage.lastContextWindow/1e3).toFixed(1)}k`),l.jsxs("button",{type:"button",onClick:n,className:`inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-[11px] transition-colors cursor-pointer ${t?`${s.bg}`:r?`${s.bg} hover:opacity-80`:i?"bg-accent-red/10 text-accent-red":"bg-bg-secondary/50 text-text-tertiary hover:bg-bg-secondary/70"}`,style:{color:t||r?a:void 0,...t?{boxShadow:`0 0 0 1px ${a}40`}:{}},children:[l.jsxs("span",{className:"font-medium",children:["@",e.name]}),o.length>0&&l.jsx("span",{className:"opacity-70",children:o.join(" · ")}),r&&l.jsx(yt,{size:9,className:"animate-spin flex-shrink-0"}),i&&l.jsx(Fa,{size:9,className:"flex-shrink-0"}),!r&&!i&&l.jsx(gr,{size:9,className:"flex-shrink-0"})]})}function QJ(){const e=ot(P=>P.timeline),t=ot(P=>P.childToolCalls),n=ot(P=>P.isAgentRunning),{t:r}=Re(),[i,s]=g.useState(!0),a=Ir(P=>P.isInTeam),o=Ir(P=>P.members),c=Ir(P=>P.focusedMemberName),d=Ir(P=>P.setFocusedMember),u=g.useMemo(()=>{const P=new Map;for(const q of o)q.color&&P.set(q.name,q.color);return P},[o]),h=g.useRef(0),[p,m]=g.useState(!1),f=g.useRef(n),b=g.useMemo(()=>HJ(e,t),[e,t]),_=g.useMemo(()=>o.map(P=>P.name),[o]),v=g.useMemo(()=>GJ(b,_),[b,_]),A=g.useMemo(()=>WJ(b),[b]);g.useEffect(()=>{!f.current&&n&&(h.current=A,m(!0)),f.current=n},[n,A]),g.useEffect(()=>{p&&A>h.current&&m(!1)},[p,A]);const S=g.useCallback(()=>s(P=>!P),[]),y=g.useCallback(P=>{P.stopPropagation(),h.current=A,m(!0)},[A]),x=g.useCallback(P=>{d(c===P?null:P)},[c,d]),k=g.useCallback(P=>{P.owner&&u.has(P.owner)&&d(c===P.owner?null:P.owner)},[c,u,d]),C=o.filter(P=>P.status==="running"||P.status==="pending"),E=C.length>0,N=!n&&E,z=a&&o.length>0,Q=v.length>0,T=Q&&v.every(P=>P.status==="completed"),w=z&&!E&&!n,L=Q&&v.every(P=>P.status==="pending")&&!n&&!E,R=Q&&!(T||w||L)&&!p,$=z&&(E||c);if(!R&&!$)return null;const D=v.filter(P=>P.status==="completed").length,U=v.length,Y=v.find(P=>P.status==="in_progress"),ee=Y?Y.activeForm||Y.subject:`${D}/${U}`;return l.jsx("div",{className:"flex-none px-4 sm:px-6 pb-1",children:l.jsx("div",{className:"max-w-3xl mx-auto",children:l.jsxs("div",{className:"rounded-lg border border-border-muted/15 bg-bg-secondary/30 overflow-hidden",children:[l.jsxs("button",{onClick:S,className:"flex items-center gap-2 w-full px-3 py-1.5 hover:bg-bg-hover/30 transition-colors cursor-pointer",children:[N?l.jsx(yt,{size:13,className:"animate-spin text-accent-purple flex-shrink-0"}):$?l.jsx(Z1,{size:13,className:"text-accent-purple flex-shrink-0"}):l.jsx(H1,{size:13,className:"text-text-tertiary flex-shrink-0"}),N?l.jsx("span",{className:"text-xs font-medium text-accent-purple",children:r("team.waitingForTeammates").replace("{count}",String(C.length)).replace("{s}",C.length>1?"s":"")}):l.jsxs(l.Fragment,{children:[R&&l.jsxs(l.Fragment,{children:[l.jsx("span",{className:"text-xs font-medium text-text-primary",children:r("todo.title")}),l.jsxs("span",{className:"text-[11px] text-text-tertiary tabular-nums",children:[D,"/",U]})]}),$&&R&&l.jsx("span",{className:"text-border-muted/40",children:"·"}),$&&l.jsxs("span",{className:"text-[11px] text-text-tertiary",children:[r("team.title")," ",C.length>0?r("team.activeCount").replace("{count}",String(C.length)):""]})]}),!i&&R&&l.jsxs(l.Fragment,{children:[l.jsx("span",{className:"text-border-muted/60 select-none",children:"|"}),Y&&n&&l.jsx(yt,{size:10,className:"text-accent-brand animate-spin flex-shrink-0"}),l.jsx("span",{className:"text-xs text-text-secondary truncate flex-1 text-left",children:ee})]}),l.jsx("span",{className:"flex-1"}),!n&&!N&&l.jsx("span",{role:"button",tabIndex:0,onClick:y,onKeyDown:P=>{P.key==="Enter"&&y(P)},className:"text-text-tertiary hover:text-text-primary p-0.5 rounded transition-colors flex-shrink-0",children:l.jsx(Bt,{size:12})}),i?l.jsx(sr,{size:12,className:"text-text-tertiary flex-shrink-0"}):l.jsx(Or,{size:12,className:"text-text-tertiary flex-shrink-0"})]}),i&&l.jsxs("div",{className:"border-t border-border-muted/40",children:[$&&l.jsx("div",{className:"flex flex-wrap gap-1.5 px-3 py-1.5",children:o.map(P=>l.jsx(VJ,{member:P,isFocused:c===P.name,onClick:()=>x(P.name)},P.name))}),R&&l.jsx("div",{className:`px-3 py-1.5 space-y-0.5 max-h-52 overflow-y-auto ${$?"border-t border-border-muted/30":""}`,children:v.map((P,q)=>{const ue=P.owner?u.get(P.owner):void 0,_e=!!ue,ke=ue?gf(ue):void 0;return l.jsxs("div",{onClick:_e?()=>k(P):void 0,className:`flex items-center gap-2 py-0.5 text-xs ${_e?"cursor-pointer hover:bg-bg-hover/30 rounded px-1 -mx-1":""} ${P.status==="in_progress"?"text-text-primary":P.status==="completed"?"text-text-tertiary":"text-text-secondary"}`,children:[l.jsx(qJ,{status:P.status}),l.jsxs("span",{className:`truncate ${P.status==="completed"?"line-through":""}`,children:[q+1,". ",P.status==="in_progress"?P.activeForm||P.subject||r("todo.untitled"):P.subject||r("todo.untitled")]}),ue&&l.jsxs("span",{className:"text-[10px] font-medium flex-shrink-0 ml-auto",style:{color:ke},children:["@",P.owner]})]},P.id)})})]})]})})})}function KJ({activeCwd:e,onOpenDirectoryPicker:t}){const{t:n}=Re(),r=g.useRef(null),[i,s]=g.useState(!1),a=Um(p=>p.dirs),o=Um(p=>p.removeDir),c=Jr(p=>{var m;return(m=p.info)==null?void 0:m.cwd})||"/",d=e||c,u=g.useMemo(()=>a.filter(p=>p!==d),[d,a]),h=g.useMemo(()=>QC(d),[d]);return g.useEffect(()=>{if(!i)return;const p=f=>{r.current&&!r.current.contains(f.target)&&s(!1)},m=f=>{f.key==="Escape"&&s(!1)};return document.addEventListener("pointerdown",p,!0),document.addEventListener("keydown",m),()=>{document.removeEventListener("pointerdown",p,!0),document.removeEventListener("keydown",m)}},[i]),l.jsxs("div",{ref:r,className:"relative min-w-0 shrink",children:[l.jsxs("button",{type:"button",onClick:()=>{if(u.length===0){t==null||t();return}s(p=>!p)},className:"composer-seat-chip",title:d,"aria-label":n("input.menu.directory"),"aria-haspopup":"menu","aria-expanded":i,children:[l.jsx(Bo,{size:16,className:"shrink-0"}),l.jsx("span",{className:"min-w-0 truncate",children:h}),u.length>0&&l.jsxs("span",{className:"shrink-0 text-[12px] font-medium text-text-tertiary",children:["+",u.length]}),u.length>0&&l.jsx(sr,{size:12,className:`shrink-0 text-text-tertiary transition-transform ${i?"rotate-180":""}`})]}),i&&l.jsxs("div",{role:"menu",className:"composer-menu absolute left-0 top-full z-50 mt-2 w-[260px] max-w-[calc(100vw-24px)] overflow-hidden py-1",children:[l.jsx("div",{className:"max-h-52 overflow-y-auto py-1",children:u.map(p=>l.jsxs("div",{className:"group/item flex items-center gap-2 px-3 py-2 text-[11px] transition-colors hover:bg-bg-hover",title:p,children:[l.jsx(Bo,{size:12,className:"shrink-0 text-text-tertiary"}),l.jsx("span",{className:"min-w-0 flex-1 truncate text-text-secondary",children:VC(p)||p}),l.jsx("button",{type:"button",onClick:()=>{o(p),u.length===1&&s(!1)},className:"flex h-5 w-5 shrink-0 items-center justify-center rounded-full text-text-tertiary opacity-0 transition-opacity group-hover/item:opacity-100 hover:bg-bg-hover hover:text-accent-red",title:n("workspace.recent.remove"),"aria-label":n("workspace.recent.remove"),children:l.jsx(Bt,{size:11})})]},p))}),l.jsxs("button",{type:"button",onClick:()=>{s(!1),t==null||t()},className:`flex w-full items-center gap-2 px-3 py-2 text-left text-[11px] text-text-secondary transition-colors hover:bg-bg-hover hover:text-text-primary ${u.length>0?"border-t border-border-muted":""}`,children:[l.jsx(is,{size:12,className:"shrink-0"}),n("input.directory.add")]})]})]})}function YJ(e={}){const{immediate:t=!1,onNeedReload:n,onNeedRefresh:r,onOfflineReady:i,onRegistered:s,onRegisteredSW:a,onRegisterError:o}=e;let c,d,u;const h=async(m=!0)=>{await d,u==null||u()};async function p(){if("serviceWorker"in navigator){if(c=await Ct(async()=>{const{Workbox:m}=await import("./workbox-window.prod.es5-BBnX5xw4.js");return{Workbox:m}},[]).then(({Workbox:m})=>new m("/sw.js",{scope:"/",type:"classic"})).catch(m=>{o==null||o(m)}),!c)return;u=()=>{c==null||c.messageSkipWaiting()};{let m=!1;const f=()=>{m=!0,c==null||c.addEventListener("controlling",b=>{b.isUpdate&&(n?n():window.location.reload())}),r==null||r()};c.addEventListener("installed",b=>{typeof b.isUpdate>"u"?typeof b.isExternal<"u"&&b.isExternal?f():!m&&(i==null||i()):b.isUpdate||i==null||i()}),c.addEventListener("waiting",f)}c.register({immediate:t}).then(m=>{a?a("/sw.js",m):s==null||s(m)}).catch(m=>{o==null||o(m)})}}return d=p(),h}function ZJ(e={}){const{immediate:t=!0,onNeedReload:n,onNeedRefresh:r,onOfflineReady:i,onRegistered:s,onRegisteredSW:a,onRegisterError:o}=e,[c,d]=g.useState(!1),[u,h]=g.useState(!1),[p]=g.useState(()=>YJ({immediate:t,onNeedReload:n,onOfflineReady(){h(!0),i==null||i()},onNeedRefresh(){d(!0),r==null||r()},onRegistered:s,onRegisteredSW:a,onRegisterError:o}));return{needRefresh:[c,d],offlineReady:[u,h],updateServiceWorker:p}}const JJ=900*1e3,XJ="pwa-new-version";function eX(e=!0){const{t}=Re(),n=g.useRef(null),r=g.useRef(!1),{updateServiceWorker:i}=ZJ({immediate:e,onRegisteredSW(o,c){if(!c)return;const d=()=>{c.update().catch(()=>{})};d(),setInterval(d,JJ)},onNeedRefresh(){if(r.current=!0,!ot.getState().isAgentRunning){s();return}a()}});g.useEffect(()=>{e||!("serviceWorker"in navigator)||Ji()||window.parent!==window||navigator.serviceWorker.getRegistrations().then(o=>Promise.all(o.map(c=>c.unregister()))).catch(()=>{})},[e]),g.useEffect(()=>{n.current=i},[i]),g.useEffect(()=>ot.subscribe((c,d)=>{r.current&&d.isAgentRunning&&!c.isAgentRunning&&s()}),[]);function s(){r.current=!1;const o=n.current;return o?o(!0).catch(()=>{}):Promise.resolve()}function a(){Dt.info(t("app.pwa.newVersion"),{id:XJ,durationMs:0,action:{label:t("app.pwa.reloadNow"),onClick:()=>(s(),!0)}})}}function tX(e,t,n,r,i){const s=Object.keys(e);if(s.length<=r)return e;const a=new Set(i.filter(u=>!!u)),o=s.filter(u=>!a.has(u)).map(u=>{const h=n.find(p=>p.id===u);return{id:u,lastAccess:e[u].lastAccess,settled:h?Xs(h):!0}}).sort((u,h)=>u.settled!==h.settled?u.settled?-1:1:u.lastAccess-h.lastAccess),c=s.length-r;if(c<=0)return e;const d={...e};for(const{id:u}of o.slice(0,c))delete d[u],delete t[u];return d}const nX=g.lazy(()=>Ct(()=>import("./CanvasPaneStandaloneView-D-16hIRq.js"),__vite__mapDeps([2,3,4,5])).then(e=>({default:e.CanvasPaneStandaloneView}))),i1=g.lazy(()=>Ct(()=>import("./CanvasView-Cmy_OwhG.js"),__vite__mapDeps([6,3,4,7,5])).then(e=>({default:e.CanvasView}))),rX=g.lazy(()=>Ct(()=>Promise.resolve().then(()=>WH),void 0).then(e=>({default:e.ChangesView}))),s1=g.lazy(()=>Ct(()=>import("./DocsView-D7ltd1Cn.js"),__vite__mapDeps([8,3,5])).then(e=>({default:e.DocsView}))),a1=g.lazy(()=>Ct(()=>import("./EditorView-DabwBpf2.js"),__vite__mapDeps([9,3,7,5])).then(e=>({default:e.EditorView}))),iX=g.lazy(()=>Ct(()=>import("./KeybindingsView-DyEXBinT.js"),__vite__mapDeps([10,3,5])).then(e=>({default:e.KeybindingsView}))),sX=g.lazy(()=>Ct(()=>import("./LogsView-DIUDc9aM.js"),__vite__mapDeps([11,3,12,5])).then(e=>({default:e.LogsView}))),aX=g.lazy(()=>Ct(()=>import("./MetricsView-Bsob5-BK.js"),__vite__mapDeps([13,3,12,14,5])).then(e=>({default:e.MetricsView}))),oX=g.lazy(()=>Ct(()=>Promise.resolve().then(()=>ZH),void 0).then(e=>({default:e.PluginsView}))),lX=g.lazy(()=>Ct(()=>import("./RemoteControlView-Bxl8WsqR.js"),__vite__mapDeps([15,3,5])).then(e=>({default:e.RemoteControlView}))),cX=g.lazy(()=>Ct(()=>Promise.resolve().then(()=>dG),void 0).then(e=>({default:e.SettingsView}))),dX=g.lazy(()=>Ct(()=>import("./StatsView-DvKDHaY1.js"),__vite__mapDeps([16,3,5])).then(e=>({default:e.StatsView}))),uX=g.lazy(()=>Ct(()=>Promise.resolve().then(()=>yG),void 0).then(e=>({default:e.TasksView}))),hX=g.lazy(()=>Ct(()=>Promise.resolve().then(()=>OZ),void 0).then(e=>({default:e.TerminalView}))),pX=g.lazy(()=>Ct(()=>import("./TracesView-RT1cgwUv.js"),__vite__mapDeps([17,3,12,5])).then(e=>({default:e.TracesView}))),mX=g.lazy(()=>Ct(()=>import("./WorkersView-Cv62Qqhl.js"),__vite__mapDeps([18,3,12,14,5])).then(e=>({default:e.WorkersView})));function Si(){return l.jsx("div",{className:"flex min-h-0 flex-1 items-center justify-center bg-bg-primary",children:l.jsx(ea,{size:"small"})})}x1();function gX(){var ni;const e=new URLSearchParams(window.location.search).get("embedded")==="agent";eX(!e);const{viewState:t,checkAuth:n,accountState:r}=Zr(),{status:i,sessionId:s,topic:a}=Ge(),o=Z$(i,s),c=Xi(Z=>Z.resolved),d=ot(Z=>Z.hasPendingInterruption),{connect:u,switchSession:h,createSession:p}=w5(),m=Ir(Z=>Z.focusedMemberName),{t:f,resolved:b}=Re(),_=Oi(Z=>Z.isOpen),v=Oi(Z=>Z.setOpen),A=Oi(Z=>Z.sessionsOpen),S=Oi(Z=>Z.toggleSessionsPanel),y=Oi(Z=>Z.setSessionsOpen),x=uf(),[k,C]=g.useState(!1),[E,N]=g.useState(!1),z=x?k:!0,Q=en(Z=>Z.recentOpen),T=en(Z=>Z.recentProjectCwd),w=en(Z=>Z.setRecentOpen),L=en(Z=>Z.setRecentProjectCwd),I=en(Z=>Z.activeAgentCwd),R=en(Z=>Z.setActiveAgentCwd),$=en(Z=>Z.mainChatActive),D=en(Z=>Z.setMainChatActive),U=en(Z=>Z.setSelectedWorkerPid),Y=en(Z=>Z.mainAgentSessionId),ee=en(Z=>Z.setMainAgentSessionId),P=en(Z=>Z.setAgentSessionId),q=en(Z=>Z.agentSessionIds),[ue,_e]=g.useState({}),ke=g.useRef({}),H=g.useRef(ue);H.current=ue;const G=g.useRef(new Map),V=2,[oe,J]=g.useState(null),he=Xr(Z=>Z.cwd),ne=tn(Z=>Z.selectedJobId),pe=tn(Z=>Z.selectedJobTitle),re=tn(Z=>Z.jobs.find(ye=>ye.id===ne)??null);g.useEffect(()=>{if(!(e||!ne))try{if(typeof sessionStorage>"u")return;const ye=JSON.parse(sessionStorage.getItem("agent-session-map")??"{}")[ne];ye&&typeof ye=="string"&&!q[ne]&&P(ne,ye)}catch{}},[e,ne,q,P]),g.useEffect(()=>{e||ne&&$&&D(!1)},[e,ne,$,D]),g.useEffect(()=>{!$&&(re!=null&&re.cwd)&&I!==re.cwd&&R(re.cwd)},[I,$,re==null?void 0:re.cwd,R]);const ce=en(Z=>Z.newJobMode),ae=en(Z=>Z.setNewJobMode),Ae=(re==null?void 0:re.cwd)??null,de=re?q[re.id]??re.sessionId??null:null,F=!e&&!$&&ne!==null,ie=tn(Z=>Z.jobs);g.useEffect(()=>{if(e||!re||!F)return;const Z=re.id;if(!re.webUrl)return;const ye=re.webUrl,Oe=ke.current[Z]instanceof HTMLIFrameElement;_e(dt=>{const it=dt[Z];if(it&&it.webUrl===ye&&it.theme===c&&it.loaded&&Oe)return dt;const ut=(it==null?void 0:it.sessionId)??q[Z]??re.sessionId??null;if(!ut)return dt;let mn;try{mn=Uw(ye,ut,re.cwd,As(),c,window.location.hostname,Z)}catch{return dt}if(it&&HR(it.url)===mn)return dt;const ri=it?{...dt,[Z]:{...it,webUrl:ye,sessionId:ut,url:mn,theme:c,loaded:!1}}:{...dt,[Z]:{jobId:Z,webUrl:ye,sessionId:ut,url:mn,theme:c,loaded:!1,needsInput:null,topic:null,lastAccess:Date.now()}};return tX(ri,ke.current,ie,V,[Z])})},[e,re,F,q,ie,V,ne,c]),g.useEffect(()=>{_e(Z=>{const ye={...Z};let Oe=!1;for(const dt of Object.keys(ye))ie.some(it=>it.id===dt)||(delete ye[dt],delete ke.current[dt],Oe=!0);return Oe?ye:Z})},[ie]),g.useEffect(()=>{ne&&_e(Z=>{const ye=Z[ne];return!ye||ye.lastAccess===Date.now()?Z:{...Z,[ne]:{...ye,lastAccess:Date.now()}}})},[ne]);const fe=pe||(re==null?void 0:re.name)||Ec((re==null?void 0:re.intent)??"")||(ne?f("agents.instanceFallback").replace("{id}",ne.slice(0,8)):null),X=ne?ue[ne]:null,Ce=(X==null?void 0:X.loaded)===!0,Ee=oe!==null&&oe===ne,Le=F&&!ce&&!Ce?Ee?"creating":re!=null&&re.foregroundHeld?null:"restoring":null;g.useEffect(()=>{Ee&&(X!=null&&X.loaded)&&J(null)},[X==null?void 0:X.loaded,Ee]);const We=$||!ne?pH:mH(ne),je=$?I??he:Ae??I??he,et=g.useRef(new Set),ct=g.useRef(new Set),gt=g.useRef(new Map),qe=1e3,wt=8e3,[Nt,qt]=g.useState(!1),[$t,It]=g.useState(!1),[cr,Vn]=g.useState(!1),[ze,rt]=g.useState(void 0),{splitPane:Ot,mainView:le,setMainView:Ne}=zt(),Qe=ot(Z=>Z.timeline),os=ot(Z=>Z.historyLoading),Br=nt(Z=>Z.sessionBlank),Je=g.useMemo(()=>Jx(Qe).length,[Qe]),vn=le==="chat"&&!F&&!ce&&!m&&o&&!os&&Je===0&&Br,[Rr,an]=g.useState(!1);g.useEffect(()=>{if(x){an(!1);return}if(le!=="chat"){A&&(an(!0),y(!1));return}Rr&&(an(!1),A||y(!0))},[x,le,A,y]),g.useEffect(()=>{C(!1),N(!1)},[x,le]),g.useEffect(()=>{!x&&!_&&v(!0)},[x,_,v]);const jr=le==="chat"&&(x?E:A),xn=g.useCallback(()=>{if(x){C(!1),N(Z=>!Z);return}S()},[x,S]),Tn=g.useCallback(()=>{if(x){N(!1);return}y(!1)},[x,y]),pn=g.useCallback(()=>{x&&(N(!1),C(Z=>!Z))},[x]),Ls=g.useCallback(()=>{x&&C(!1)},[x]);g.useEffect(()=>{const Z=ye=>kr.handleKeyDown(ye);return window.addEventListener("keydown",Z),()=>window.removeEventListener("keydown",Z)},[]),g.useEffect(()=>{if(t!=="authenticated"||e)return;let Z=!1;return(async()=>{var ye;try{const Oe=await Kt("/api/v1/channels",{headers:Fe()});if(!Oe.ok||Z)return;const dt=await Oe.json();rt(((ye=dt.capabilities)==null?void 0:ye.remoteControlEnabled)===!0)}catch{}})(),()=>{Z=!0}},[t]),g.useEffect(()=>{i==="connected"&&dI.getState().loadBindings()},[i]);const Qn=g.useCallback((Z,ye)=>{const Oe=tn.getState().jobs.find(ut=>ut.id===Z);if(!Oe)return;const dt=Oe.webUrl;if(!dt)return;let it;try{it=Uw(dt,ye,Oe.cwd,As(),c,window.location.hostname,Z)}catch{return}_e(ut=>{const mn=ut[Z];return mn?{...ut,[Z]:{...mn,webUrl:dt,sessionId:ye,url:it,theme:c,loaded:!1}}:ut})},[c]),K=g.useCallback(Z=>{G.current.delete(Z),_e(ye=>{const Oe=ye[Z];return!Oe||Oe.loaded?ye:{...ye,[Z]:{...Oe,loaded:!0}}})},[]);g.useEffect(()=>{if(e||!F||ce||!ne)return;const Z=ne;G.current.delete(Z);const ye=it=>{const ut=ke.current[Z],mn=H.current[Z];if(!ut||!mn)return;const ri=Hw(ut,zw(mn.url));if(ri==="alive"||ri==="opaque"){K(Z);return}if(!it||ri!=="dead")return;const ls=G.current.get(Z)??0;ls>=2||(G.current.set(Z,ls+1),_e(Ms=>{const bl=Ms[Z];return bl?{...Ms,[Z]:{...bl,loaded:!1,url:zR(bl.url)}}:Ms}))},Oe=window.requestAnimationFrame(()=>ye(!1)),dt=window.setTimeout(()=>ye(!0),UR);return()=>{window.cancelAnimationFrame(Oe),window.clearTimeout(dt)}},[e,F,ce,ne,K]);const xe=g.useCallback(Z=>{Ot(Z)},[Ot]),Pe=g.useCallback(async()=>{if(!s)return null;let Z;try{const dt=en.getState(),it=tn.getState().selectedJobId;Z=await p({persistLastId:dt.mainChatActive||!it})}catch{return Dt.error(f("error.newChatFailed")),null}const ye=en.getState(),Oe=tn.getState().selectedJobId;return ye.mainChatActive||!Oe?(ee(Z),he&&R(he)):(P(Oe,Z),Qn(Oe,Z)),ae(!1),Ne("chat"),window.location.hash="/chat",Z},[s,p,Qn,Ne,f,he,R,ae,ee,P]),ft=g.useCallback(async(Z,ye,Oe)=>{if(!s)return!1;try{return await h(Z),R(ye??he??null),ae(!1),Ne("chat"),window.location.hash="/chat",!0}catch(dt){const it=Oo(dt);console.error(`[App] Session switch failed: ${it}`,dt);const ut=/external writer|Persistent Session already has|current external writer/i.test(it),mn=/ADMISSION_FAILED|admission did not commit/i.test(it);return ut&&(Oe!=null&&Oe.silentOccupied)||(ut?Dt.info(f("error.sessionOccupied")):Dt.error(mn?f("error.sessionUnavailable"):`${f("error.switchSessionFailed")}: ${it}`)),!1}},[s,Ne,h,f,he,R,ae]),Vt=g.useCallback((Z,ye)=>ft(Z,ye,{silentOccupied:!0}),[ft]),tt=g.useCallback(Z=>{const ye=Z==="remote-control"&&ze===!1?"chat":Z;x&&C(!1),Ne(ye),window.location.hash=`/${ye}`},[x,ze,Ne]),Ke=g.useCallback(()=>{if(Q){w(!1);return}L(he??null),w(!0)},[Q,he,L,w]),Jt=g.useCallback(async(Z,ye)=>{const dt=en.getState().mainChatActive?null:tn.getState().selectedJobId;return dt?(P(dt,Z),Qn(dt,Z),tn.getState().selectJob(dt,tn.getState().selectedJobTitle),D(!1),U(null),R(ye),!0):await ft(Z,ye)?(ee(Z),tn.getState().selectJob(null),D(!0),U(null),R(ye),!0):!1},[ft,R,P,ee,D,U,Qn]),Lt=g.useCallback(()=>{ae(!0),Ne("chat"),window.location.hash="/chat"},[Ne,ae]),se=g.useCallback(()=>{ae(!1),Ne("chat"),window.location.hash="/chat"},[Ne,ae]),$e=g.useCallback(Z=>{ct.current.add(Z),J(Z);const ye=tn.getState().jobs.find(Oe=>Oe.id===Z);tn.getState().selectJob(Z,(ye==null?void 0:ye.name)??null),U(null),D(!1),R((ye==null?void 0:ye.cwd)??he??null),ae(!1)},[R,D,ae,U,he]);if(g.useEffect(()=>{if($||ce||!(re!=null&&re.sessionId)||re.foregroundHeld)return;let Z;const ye=()=>{const Oe=tn.getState().jobs.find(Ms=>Ms.id===re.id);if(!Oe)return;if(tn.getState().manuallyStoppedAgentIds[Oe.id]){ct.current.delete(Oe.id),gt.current.delete(Oe.id);return}const dt=jR(Oe,ct.current.has(Oe.id));if(dt===null){(Oe.webUrl||Oe.alive)&&(ct.current.delete(Oe.id),gt.current.delete(Oe.id));return}if(dt>0){Z=setTimeout(ye,dt);return}if(ct.current.delete(Oe.id),et.current.has(Oe.id))return;const it=Date.now(),ut=gt.current.get(Oe.id),mn=(ut==null?void 0:ut.nextRetryAt)??0;if(it<mn){Z=setTimeout(ye,mn-it);return}const ri=(ut==null?void 0:ut.failures)??0,ls=FR(ri,qe,wt);gt.current.set(Oe.id,{failures:ri+1,nextRetryAt:it+ls}),et.current.add(Oe.id),tn.getState().respawnJob(Oe.id).finally(()=>et.current.delete(Oe.id))};return ye(),()=>{Z&&clearTimeout(Z)}},[$,ce,re]),g.useEffect(()=>{const Z=ye=>{const Oe=Object.keys(ke.current).find(it=>{var ut;return((ut=ke.current[it])==null?void 0:ut.contentWindow)===ye.source});!Oe||!tn.getState().jobs.find(it=>it.id===Oe)||!TR(ye.data)||ye.origin===window.location.origin&&(ye.data.sessionId&&typeof ye.data.sessionId=="string"&&P(Oe,ye.data.sessionId),_e(it=>{const ut=it[Oe];return ut?{...it,[Oe]:{...ut,sessionId:typeof ye.data.sessionId=="string"&&ye.data.sessionId?ye.data.sessionId:ut.sessionId,needsInput:typeof ye.data.needsInput=="boolean"?ye.data.needsInput:ut.needsInput,topic:ye.data.topic}}:it}))};return window.addEventListener("message",Z),()=>window.removeEventListener("message",Z)},[P]),g.useEffect(()=>{const Z=[kr.register({id:"commandPalette.toggle",key:"p",meta:!0,shift:!0,handler:()=>Vn(ye=>!ye)}),kr.register({id:"sidebar.toggle",key:"b",meta:!0,when:()=>le!=="editor",handler:()=>{if(x){pn();return}le==="chat"&&xn()}}),kr.register({id:"terminal.toggle",key:"j",meta:!0,handler:()=>{const ye=le==="terminal"?"chat":"terminal";Ne(ye),window.location.hash="/"+ye}}),kr.register({id:"newChat",key:"n",meta:!0,handler:()=>Pe()}),kr.register({id:"settings",key:",",meta:!0,handler:()=>{Ne("settings"),window.location.hash="/settings"}}),kr.registerAction("app:commandPalette",()=>Vn(ye=>!ye)),kr.registerAction("app:toggleSidebar",()=>{if(x){pn();return}le==="chat"&&xn()},()=>le!=="editor"),kr.registerAction("app:toggleTerminal",()=>{const ye=le==="terminal"?"chat":"terminal";Ne(ye),window.location.hash="/"+ye}),kr.registerAction("app:newChat",()=>Pe()),kr.registerAction("app:settings",()=>{Ne("settings"),window.location.hash="/settings"}),kr.registerAction("app:focusInput",()=>{const ye=document.querySelector("textarea");ye==null||ye.focus()}),kr.registerAction("app:keybindings",()=>{Ne("keybindings"),window.location.hash="/keybindings"})];return()=>Z.forEach(ye=>ye())},[x,le,Pe,Ne,xn,pn]),g.useEffect(()=>{const Z=new URLSearchParams(window.location.search),ye=Z.get("password"),Oe=Z.get("token");if(ye||Oe){Kg(ye||Oe),Z.delete("password"),Z.delete("token");const dt=Z.toString()?`${window.location.pathname}?${Z.toString()}`:window.location.pathname;window.history.replaceState({},"",dt)}n()},[n]),g.useEffect(()=>{if(t==="authenticated")return Zr.getState().startHeartbeat()},[t]),g.useEffect(()=>{t==="authenticated"&&Zr.getState().checkAccountAuth()},[t]),g.useEffect(()=>{if(t==="authenticated"){const Z=k1(),ye=Z==="remote-control"&&ze!==!0?"chat":Z;Ne(ye),(!window.location.hash||window.location.hash==="#")&&(window.location.hash=`/${ye}`)}},[ze,t,Ne]),g.useEffect(()=>bL(ye=>{if(ye==="remote-control"&&ze!==!0){ze===!1&&(Ne("chat"),window.location.hash="/chat");return}Ne(ye)}),[ze,Ne]),g.useEffect(()=>{ze===!1&&le==="remote-control"&&(Ne("chat"),window.location.hash="/chat")},[le,ze,Ne]),g.useEffect(()=>{if(t==="authenticated"&&r==="authenticated"){const Z=As()||void 0;b5().catch(()=>{}),u({token:Z,continue:!0}),A1()}},[t,r,u]),g.useEffect(()=>{he&&!I&&R(he)},[he,I,R]),g.useEffect(()=>{if(!s)return;const Z=en.getState(),ye=tn.getState().selectedJobId;(Z.mainChatActive||!ye)&&ee(s)},[s,ee]),g.useEffect(()=>{document.documentElement.lang=b;const Z=F?(X==null?void 0:X.topic)||fe:a;document.title=bm(Z)||f("page.title")},[b,f,a,F,X==null?void 0:X.topic,fe]),g.useEffect(()=>{if(!e||window.parent===window)return;let Z=null;try{Z=window.parent.location.origin}catch{try{document.referrer&&(Z=new URL(document.referrer).origin)}catch{}}Z&&window.parent.postMessage({type:_1,sessionId:s,topic:bm(a)||null,needsInput:d},Z)},[e,d,s,a]),t==="loading")return l.jsx("div",{className:"flex h-screen h-[100dvh] bg-bg-primary text-text-primary transition-colors duration-200 font-sans overflow-hidden",children:l.jsx("div",{className:"flex-1 flex items-center justify-center",children:l.jsx(ea,{size:"large",text:f("app.connecting")})})});if(t==="login")return l.jsx(TJ,{});if(r==="needLogin"||r==="polling")return l.jsx(A5,{});const kt=()=>l.jsx(Jn,{viewName:F?"agents":"chat",errorTitle:f("error.viewCrashed"),retryLabel:f("app.retry"),children:l.jsxs("div",{className:`relative isolate flex min-h-0 flex-1 flex-col overflow-hidden bg-bg-primary ${vn||ce?"justify-center":""}`,children:[Object.values(ue).map(Z=>{if(e)return null;const ye=qR({showingAgentStage:F,newJobMode:ce,jobId:Z.jobId,selectedJobId:ne,loaded:Z.loaded});return l.jsx("iframe",{ref:Oe=>{ke.current[Z.jobId]=Oe},src:Z.url,title:Z.jobId===ne?(re==null?void 0:re.name)||(re==null?void 0:re.intent)||f("agents.instanceFallback").replace("{id}",ne.slice(0,8)):void 0,className:"absolute inset-0 z-0 h-full w-full border-0 bg-bg-primary",allow:"clipboard-read; clipboard-write",loading:"eager",onLoad:()=>{const Oe=ke.current[Z.jobId];Hw(Oe,zw(Z.url))!=="dead"&&K(Z.jobId)},style:WR(ye)},Z.jobId)}),ce?l.jsxs("div",{className:"composer-stack composer-stack-hero flex-none",children:[l.jsx(Sa,{compact:!0,cwd:je??void 0}),l.jsx(EJ,{onCreated:$e,onCancel:se})]}):F?Ce?l.jsx("div",{className:"min-h-0 flex-1","aria-hidden":!0}):l.jsx("div",{className:"relative z-10 flex min-h-0 flex-1 flex-col bg-bg-primary",children:Le==="creating"?l.jsx("div",{className:"empty-state-wrapper",children:l.jsx(Sa,{cwd:(re==null?void 0:re.cwd)??je??void 0,footer:l.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-text-tertiary",children:[l.jsx(yt,{size:12,className:"animate-spin"}),l.jsx("span",{children:f("agents.live.creating")})]})})}):re!=null&&re.foregroundHeld?l.jsx("div",{className:"empty-state-wrapper",children:l.jsx(Sa,{cwd:(re==null?void 0:re.cwd)??je??void 0,footer:l.jsx("p",{className:"text-[11px] text-text-tertiary",children:f("agents.live.foregroundHeld")})})}):re!=null&&re.sessionId?l.jsx("div",{className:"relative flex min-h-0 flex-1 flex-col",children:l.jsx(B9,{job:re})}):l.jsx("div",{className:"empty-state-wrapper",children:l.jsx(Sa,{cwd:(re==null?void 0:re.cwd)??je??void 0,footer:l.jsx("p",{className:"text-[11px] text-text-tertiary",children:f("agents.live.restoring")})})})}):l.jsxs(l.Fragment,{children:[l.jsx("div",{className:vn?"hidden":"flex-1 overflow-hidden w-full relative bg-bg-primary",children:m?l.jsx(jJ,{}):l.jsx(cI,{onClickCloseBottomSheet:()=>qt(!1),skipWelcomeTransition:e})}),!vn&&l.jsx(QJ,{}),!vn&&l.jsx(U9,{}),l.jsxs("div",{className:`bg-bg-primary ${vn?"composer-stack composer-stack-hero flex-none":"composer-stack flex-none"}`,children:[l.jsxs("div",{className:vn?"contents":"hidden",children:[l.jsx(Sa,{compact:!0,cwd:je??void 0}),l.jsxs("div",{className:"composer-hero-row",children:[l.jsx(KJ,{activeCwd:je,onOpenDirectoryPicker:()=>It(!0)}),!m&&l.jsx(NJ,{sessionId:s})]})]}),l.jsx(MJ,{}),l.jsx(dJ,{agentKey:We,agentCwd:je,onNavigate:tt,onNewChat:Pe,mainView:le,showBottomSheet:Nt,setShowBottomSheet:qt,onOpenDirectoryPicker:()=>It(!0),directoryPickerOpen:$t,onDirectoryPickerClose:()=>It(!1),hero:vn})]})]})]})}),wn=()=>{if(!o&&i!=="error"&&!e)return l.jsx("div",{className:"flex-1 flex items-center justify-center",children:l.jsx(ea,{size:"large",text:f("app.connecting")})});if(!o&&!e&&le!=="settings"&&le!=="docs")return l.jsx("div",{className:"flex-1 flex items-center justify-center",children:l.jsxs("div",{className:"text-center",children:[l.jsx("div",{className:"text-text-secondary mb-4 font-medium",children:f("app.connectFailed")}),l.jsx("button",{onClick:()=>u({continue:!0}),className:["px-6 py-2.5 bg-accent-brand text-accent-brand-foreground rounded-full","text-sm font-medium transition-all hover:bg-accent-brand/90","hover:scale-105 active:scale-95 shadow-sm"].join(" "),children:f("app.retry")})]})});switch(le){case"chat":return e?kt():null;case"tasks":return l.jsx(Jn,{viewName:"tasks",errorTitle:f("error.viewCrashed"),retryLabel:f("app.retry"),children:l.jsx(uX,{})});case"plugins":return l.jsx(Jn,{viewName:"plugins",errorTitle:f("error.viewCrashed"),retryLabel:f("app.retry"),children:l.jsx(oX,{})});case"terminal":return null;case"canvas":return null;case"canvas-pane":return null;case"remote-control":return ze!==!0?null:l.jsx(Jn,{viewName:"remote-control",errorTitle:f("error.viewCrashed"),retryLabel:f("app.retry"),children:l.jsx(lX,{onNavigate:tt})});case"editor":return null;case"changes":return null;case"settings":return l.jsx(Jn,{viewName:"settings",errorTitle:f("error.viewCrashed"),retryLabel:f("app.retry"),children:l.jsx(cX,{})});case"keybindings":return l.jsx(Jn,{viewName:"keybindings",errorTitle:f("error.viewCrashed"),retryLabel:f("app.retry"),children:l.jsx(iX,{})});case"metrics":return l.jsx(Jn,{viewName:"metrics",errorTitle:f("error.viewCrashed"),retryLabel:f("app.retry"),children:l.jsx(aX,{})});case"stats":return l.jsx(Jn,{viewName:"stats",errorTitle:f("error.viewCrashed"),retryLabel:f("app.retry"),children:l.jsx(dX,{})});case"traces":return l.jsx(Jn,{viewName:"traces",errorTitle:f("error.viewCrashed"),retryLabel:f("app.retry"),children:l.jsx(pX,{})});case"workers":return l.jsx(Jn,{viewName:"workers",errorTitle:f("error.viewCrashed"),retryLabel:f("app.retry"),children:l.jsx(mX,{})});case"logs":return l.jsx(Jn,{viewName:"logs",errorTitle:f("error.viewCrashed"),retryLabel:f("app.retry"),children:l.jsx(sX,{})});case"docs":return l.jsx(Jn,{viewName:"docs",errorTitle:f("error.viewCrashed"),retryLabel:f("app.retry"),children:l.jsx(s1,{})});default:return null}};return e?l.jsxs("div",{className:"flex h-screen h-[100dvh] flex-col overflow-hidden bg-bg-primary font-sans text-text-primary",children:[l.jsx(g.Suspense,{fallback:l.jsx(Si,{}),children:wn()}),l.jsx(r1,{}),l.jsx(V0,{})]}):le==="docs"&&window.location.hash.includes("standalone")?l.jsx("div",{className:"flex h-screen h-[100dvh] bg-bg-primary text-text-primary transition-colors duration-200 font-sans overflow-hidden",children:l.jsx(g.Suspense,{fallback:l.jsx(Si,{}),children:l.jsx(s1,{})})}):le==="editor"&&window.location.hash.includes("standalone")?l.jsx("div",{className:"flex h-screen h-[100dvh] bg-bg-primary text-text-primary transition-colors duration-200 font-sans overflow-hidden",children:l.jsx(g.Suspense,{fallback:l.jsx(Si,{}),children:l.jsx(a1,{isVisible:!0})})}):le==="canvas-pane"?l.jsx("div",{className:"flex h-screen h-[100dvh] bg-bg-primary text-text-primary transition-colors duration-200 font-sans overflow-hidden",children:l.jsx(g.Suspense,{fallback:l.jsx(Si,{}),children:l.jsx(nX,{})})}):le==="canvas"&&window.location.hash.includes("standalone")?l.jsx("div",{className:"flex h-screen h-[100dvh] bg-bg-primary text-text-primary transition-colors duration-200 font-sans overflow-hidden",children:l.jsx(g.Suspense,{fallback:l.jsx(Si,{}),children:l.jsx(i1,{})})}):l.jsxs("div",{className:`flex h-screen h-[100dvh] bg-bg-primary text-text-primary transition-colors duration-200 font-sans overflow-hidden${Q?" history-rail-open":""}`,children:[l.jsx(OJ,{isOpen:z,onClose:Ls,mainView:le,onNavigate:tt,remoteControlEnabled:ze===!0}),l.jsx(DO,{open:jr,onClose:Tn,onSwitchSession:Vt,onNewChat:Pe,onNewAgent:Lt,agentFrameNeedsInput:(X==null?void 0:X.needsInput)??null}),l.jsxs("div",{className:"flex min-h-0 min-w-0 flex-1",children:[l.jsxs("div",{className:"flex-1 flex flex-col min-w-0 min-h-0 relative h-full",children:[l.jsx("div",{style:{display:le!=="editor"&&le!=="changes"?void 0:"none"},children:l.jsx(PJ,{onMenuClick:pn,sessionsPanelOpen:jr,onSplitTerminal:xe,onHistory:Ke,onNewChat:Pe,onCancelNewAgent:se,onToggleSessionsPanel:xn,newAgentMode:ce,agentTransitionMode:Le,conversationTitleOverride:(X==null?void 0:X.topic)??void 0,agentFrameNeedsInput:(X==null?void 0:X.needsInput)??null})}),l.jsxs("div",{className:"flex-1 flex flex-col w-full overflow-hidden relative",children:[l.jsxs("div",{className:"flex-1 flex flex-col w-full min-h-0 overflow-hidden relative",style:VR(le==="chat"),children:[l.jsx(g.Suspense,{fallback:l.jsx(Si,{}),children:kt()}),!o&&!F&&l.jsx("div",{className:"absolute inset-0 z-20 flex flex-1 items-center justify-center bg-bg-primary",style:{display:le==="chat"?"flex":"none"},children:i!=="error"?l.jsx(ea,{size:"large",text:f("app.connecting")}):l.jsxs("div",{className:"text-center",children:[l.jsx("div",{className:"text-text-secondary mb-4 font-medium",children:f("app.connectFailed")}),l.jsx("button",{onClick:()=>u({continue:!0}),className:["px-6 py-2.5 bg-accent-brand text-accent-brand-foreground rounded-full","text-sm font-medium transition-all hover:bg-accent-brand/90","hover:scale-105 active:scale-95 shadow-sm"].join(" "),children:f("app.retry")})]})})]}),l.jsx("div",{className:"flex-1 flex flex-col w-full min-h-0 overflow-hidden",style:{display:le==="terminal"?"flex":"none"},children:l.jsx(g.Suspense,{fallback:l.jsx(Si,{}),children:l.jsx(hX,{})})}),l.jsx("div",{className:"flex-1 flex flex-col w-full",style:{display:le==="canvas"?"flex":"none"},children:l.jsx(Jn,{viewName:"canvas",errorTitle:f("error.viewCrashed"),retryLabel:f("app.retry"),children:l.jsx(g.Suspense,{fallback:l.jsx(Si,{}),children:l.jsx(i1,{})})})}),l.jsx("div",{className:"flex-1 flex flex-col w-full min-h-0 overflow-hidden",style:{display:le==="editor"?"flex":"none"},children:l.jsx(Jn,{viewName:"editor",errorTitle:f("error.viewCrashed"),retryLabel:f("app.retry"),children:l.jsx(g.Suspense,{fallback:l.jsx(Si,{}),children:l.jsx(a1,{onMenuClick:x?pn:void 0,isVisible:le==="editor"})})})}),l.jsx("div",{className:"flex-1 flex flex-col w-full min-h-0 overflow-hidden",style:{display:le==="changes"?"flex":"none"},children:l.jsx(Jn,{viewName:"changes",errorTitle:f("error.viewCrashed"),retryLabel:f("app.retry"),children:l.jsx(g.Suspense,{fallback:l.jsx(Si,{}),children:l.jsx(rX,{onMenuClick:x?pn:void 0})})})}),le!=="chat"&&le!=="terminal"&&le!=="canvas"&&le!=="editor"&&le!=="changes"&&l.jsx(g.Suspense,{fallback:l.jsx(Si,{}),children:wn()})]})]}),l.jsx(cH,{isOpen:Q,onClose:()=>w(!1),projectCwd:Q?T:null,activeSessionId:F?de:Y??s,canSwitchConversations:!0,targetLabel:$?f("sessions.currentTitle"):(re==null?void 0:re.name)||((ni=re==null?void 0:re.intent)==null?void 0:ni.split(/\r?\n/)[0])||f("agents.instanceFallback").replace("{id}",(re==null?void 0:re.id.slice(0,8))||""),onOpenSession:Jt})]}),l.jsx(r1,{}),l.jsx(nH,{isOpen:cr,onClose:()=>Vn(!1),onNavigate:tt,onNewChat:Pe,remoteControlEnabled:ze===!0}),l.jsx(V0,{})]})}SL.createRoot(document.getElementById("root")).render(l.jsx(g.StrictMode,{children:l.jsx(Jn,{children:l.jsx(gX,{})})}));export{NN as $,rp as A,eh as B,ac as C,gr as D,Xc as E,Pi as F,Jp as G,mO as H,hE as I,FH as J,vD as K,yt as L,lD as M,SM as N,yM as O,is as P,SX as Q,Ua as R,Xo as S,$Z as T,cO as U,Dt as V,gu as W,Bt as X,Bo as Y,xo as Z,Ct as _,zt as a,um as a0,SS as a1,Xr as a2,So as a3,hf as a4,$C as a5,Oi as a6,W1 as a7,ef as a8,Zp as a9,q1 as aA,Ts as aB,rD as aC,tm as aD,Xp as aE,$M as aF,m$ as aG,Jo as aH,a$ as aI,M1 as aJ,Y1 as aK,Is as aL,wo as aM,Ge as aN,yI as aO,wD as aP,TD as aQ,hL as aR,_X as aS,_L as aT,du as aa,LL as ab,ic as ac,Co as ad,$J as ae,uf as af,Ea as ag,PC as ah,L1 as ai,Jg as aj,R1 as ak,k1 as al,y$ as am,W9 as an,Q9 as ao,q9 as ap,dI as aq,cu as ar,Wa as as,D1 as at,Uo as au,N1 as av,$1 as aw,sc as ax,Xw as ay,xX as az,Q1 as b,ve as c,eD as d,Rt as e,Ga as f,wX as g,Fe as h,Xi as i,uE as j,Q3 as k,ka as l,sr as m,Or as n,V3 as o,Jr as p,vX as q,ea as r,EB as s,es as t,Re as u,kX as v,WL as w,UC as x,Kt as y,fO as z};