cuelo 0.10.34 → 0.10.35

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 (76) hide show
  1. package/.next/BUILD_ID +1 -1
  2. package/.next/app-path-routes-manifest.json +6 -6
  3. package/.next/build-manifest.json +2 -2
  4. package/.next/prerender-manifest.json +3 -3
  5. package/.next/required-server-files.js +1 -1
  6. package/.next/required-server-files.json +1 -1
  7. package/.next/server/app/_global-error/page_client-reference-manifest.js +1 -1
  8. package/.next/server/app/_global-error.html +1 -1
  9. package/.next/server/app/_global-error.rsc +1 -1
  10. package/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
  11. package/.next/server/app/_global-error.segments/_global-error/__PAGE__.segment.rsc +1 -1
  12. package/.next/server/app/_global-error.segments/_global-error.segment.rsc +1 -1
  13. package/.next/server/app/_global-error.segments/_head.segment.rsc +1 -1
  14. package/.next/server/app/_global-error.segments/_index.segment.rsc +1 -1
  15. package/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
  16. package/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
  17. package/.next/server/app/_not-found.html +1 -1
  18. package/.next/server/app/_not-found.rsc +2 -2
  19. package/.next/server/app/_not-found.segments/_full.segment.rsc +2 -2
  20. package/.next/server/app/_not-found.segments/_head.segment.rsc +1 -1
  21. package/.next/server/app/_not-found.segments/_index.segment.rsc +2 -2
  22. package/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +1 -1
  23. package/.next/server/app/_not-found.segments/_not-found.segment.rsc +1 -1
  24. package/.next/server/app/_not-found.segments/_tree.segment.rsc +1 -1
  25. package/.next/server/app/api/updates/route.js +1 -1
  26. package/.next/server/app/index.html +1 -1
  27. package/.next/server/app/index.rsc +4 -4
  28. package/.next/server/app/index.segments/__PAGE__.segment.rsc +3 -3
  29. package/.next/server/app/index.segments/_full.segment.rsc +4 -4
  30. package/.next/server/app/index.segments/_head.segment.rsc +1 -1
  31. package/.next/server/app/index.segments/_index.segment.rsc +2 -2
  32. package/.next/server/app/index.segments/_tree.segment.rsc +1 -1
  33. package/.next/server/app/office/page_client-reference-manifest.js +1 -1
  34. package/.next/server/app/office-preview/page_client-reference-manifest.js +1 -1
  35. package/.next/server/app/office-preview.html +1 -1
  36. package/.next/server/app/office-preview.rsc +2 -2
  37. package/.next/server/app/office-preview.segments/_full.segment.rsc +2 -2
  38. package/.next/server/app/office-preview.segments/_head.segment.rsc +1 -1
  39. package/.next/server/app/office-preview.segments/_index.segment.rsc +2 -2
  40. package/.next/server/app/office-preview.segments/_tree.segment.rsc +1 -1
  41. package/.next/server/app/office-preview.segments/office-preview/__PAGE__.segment.rsc +1 -1
  42. package/.next/server/app/office-preview.segments/office-preview.segment.rsc +1 -1
  43. package/.next/server/app/office.html +1 -1
  44. package/.next/server/app/office.rsc +4 -4
  45. package/.next/server/app/office.segments/_full.segment.rsc +4 -4
  46. package/.next/server/app/office.segments/_head.segment.rsc +1 -1
  47. package/.next/server/app/office.segments/_index.segment.rsc +2 -2
  48. package/.next/server/app/office.segments/_tree.segment.rsc +1 -1
  49. package/.next/server/app/office.segments/office/__PAGE__.segment.rsc +3 -3
  50. package/.next/server/app/office.segments/office.segment.rsc +1 -1
  51. package/.next/server/app/page_client-reference-manifest.js +1 -1
  52. package/.next/server/app/recover/page_client-reference-manifest.js +1 -1
  53. package/.next/server/app/recover.html +1 -1
  54. package/.next/server/app/recover.rsc +2 -2
  55. package/.next/server/app/recover.segments/_full.segment.rsc +2 -2
  56. package/.next/server/app/recover.segments/_head.segment.rsc +1 -1
  57. package/.next/server/app/recover.segments/_index.segment.rsc +2 -2
  58. package/.next/server/app/recover.segments/_tree.segment.rsc +1 -1
  59. package/.next/server/app/recover.segments/recover/__PAGE__.segment.rsc +1 -1
  60. package/.next/server/app/recover.segments/recover.segment.rsc +1 -1
  61. package/.next/server/app-paths-manifest.json +6 -6
  62. package/.next/server/chunks/5489.js +2 -2
  63. package/.next/server/middleware-build-manifest.js +1 -1
  64. package/.next/server/pages/404.html +1 -1
  65. package/.next/server/pages/500.html +1 -1
  66. package/.next/server/server-reference-manifest.json +1 -1
  67. package/.next/static/chunks/{9575-2856c95d5dbe6a12.js → 9575-931a7b262e380621.js} +2 -2
  68. package/.next/static/chunks/app/{layout-115605510901fd4d.js → layout-730743fa7222a654.js} +1 -1
  69. package/.next/trace +108 -108
  70. package/.next/trace-build +1 -1
  71. package/Tools/CUELO_Setup/files/native-runtime-patch.js +1 -1
  72. package/Tools/OMP_Global_Config/agent/AGENTS.md +2 -0
  73. package/Tools/OMP_Global_Config/agent/prompt-copies/AGENTS.en.md +3 -1
  74. package/package.json +1 -1
  75. /package/.next/static/{afgMpjnnQ7OLr19etIHxe → HocI0WzjNFKEHO2ctehZM}/_buildManifest.js +0 -0
  76. /package/.next/static/{afgMpjnnQ7OLr19etIHxe → HocI0WzjNFKEHO2ctehZM}/_ssgManifest.js +0 -0
@@ -1,4 +1,4 @@
1
- (self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[9575],{13004:e=>{e.exports={backdrop:"SettingsConfig_backdrop__i6KYG",window:"SettingsConfig_window__m7dcs",sidebar:"SettingsConfig_sidebar__vEMEr",brand:"SettingsConfig_brand__DlYlu",eyebrow:"SettingsConfig_eyebrow__uTa5R",title:"SettingsConfig_title__DWTnA",context:"SettingsConfig_context__N0fl0",searchWrap:"SettingsConfig_searchWrap___PWrc",searchIcon:"SettingsConfig_searchIcon__8_YYE",search:"SettingsConfig_search__DUhSs",nav:"SettingsConfig_nav__V8P9S",navLabel:"SettingsConfig_navLabel__M1wMP",navButton:"SettingsConfig_navButton__CUOqu",navIcon:"SettingsConfig_navIcon__Wagpr",closeRail:"SettingsConfig_closeRail__PW3pT",closeButton:"SettingsConfig_closeButton__5y_6F",content:"SettingsConfig_content__n_a5Z",scrollContent:"SettingsConfig_scrollContent__03BsO",contentHeader:"SettingsConfig_contentHeader__tNmzv",contentTitle:"SettingsConfig_contentTitle__oiHOO",contentDescription:"SettingsConfig_contentDescription___l2QU",reloadNotice:"SettingsConfig_reloadNotice__enzeE",settingsBody:"SettingsConfig_settingsBody__QRFVu",group:"SettingsConfig_group__JQ_dy",groupTitle:"SettingsConfig_groupTitle__0SrM9",settingRow:"SettingsConfig_settingRow__Jy73r",settingLabel:"SettingsConfig_settingLabel__n8vtU",settingDescription:"SettingsConfig_settingDescription__TGWfP",settingControl:"SettingsConfig_settingControl__oz5Gn",select:"SettingsConfig_select__A5aGy",textInput:"SettingsConfig_textInput___NjZ2",jsonEditor:"SettingsConfig_jsonEditor__yTYDb",numberInput:"SettingsConfig_numberInput__TVVeJ",switch:"SettingsConfig_switch__5UYqz",multiSelect:"SettingsConfig_multiSelect__PTjyr",choice:"SettingsConfig_choice__Os8WR",choiceToggle:"SettingsConfig_choiceToggle__lyl75",reorder:"SettingsConfig_reorder__JR6tX",error:"SettingsConfig_error__j6wEj",saveState:"SettingsConfig_saveState__1tIL4",themeGrid:"SettingsConfig_themeGrid__7Lw8A",themeCard:"SettingsConfig_themeCard__DQFsT",themePreview:"SettingsConfig_themePreview__QzqXK",themePreviewBar:"SettingsConfig_themePreviewBar__ZbchX",themePreviewPanel:"SettingsConfig_themePreviewPanel__YN9ty",themePreviewLine:"SettingsConfig_themePreviewLine__jP0qg",themeCardBody:"SettingsConfig_themeCardBody__xiOe6",themeCardHeader:"SettingsConfig_themeCardHeader__YPRN2",themeSlot:"SettingsConfig_themeSlot__vGn9a",themeActive:"SettingsConfig_themeActive__PNmdk",mcpLayout:"SettingsConfig_mcpLayout__ek_Fi",mcpList:"SettingsConfig_mcpList__gZ9_o",scopeTabs:"SettingsConfig_scopeTabs__9bybS",scopeButton:"SettingsConfig_scopeButton__d4XPe",serverRows:"SettingsConfig_serverRows__JSJy0",serverRow:"SettingsConfig_serverRow__6gJdE",serverSelect:"SettingsConfig_serverSelect__cuYFx",serverToggle:"SettingsConfig_serverToggle__X5N_o",serverName:"SettingsConfig_serverName__lbfcK",sourceBadge:"SettingsConfig_sourceBadge__XDE2u",serverListEmpty:"SettingsConfig_serverListEmpty___icit",statusDot:"SettingsConfig_statusDot__dVcD4",addServer:"SettingsConfig_addServer__g0ivB",mcpEditor:"SettingsConfig_mcpEditor__XGcLp",editorHeader:"SettingsConfig_editorHeader__qDvAk",readOnlyNotice:"SettingsConfig_readOnlyNotice__KNzML",editorActions:"SettingsConfig_editorActions__h9p7Y",linkButton:"SettingsConfig_linkButton__0DH3I",primaryButton:"SettingsConfig_primaryButton__Eocwv",dangerButton:"SettingsConfig_dangerButton__XF_f_",empty:"SettingsConfig_empty__erg3A"}},14755:(e,t,n)=>{"use strict";n.d(t,{C1:()=>a,IN:()=>i,getPresetFromTools:()=>l,xG:()=>o});let r=[],i=["read","bash","edit","write"],a=["read","bash","edit","write","grep","glob"],s=Object.fromEntries(a.map(e=>[e,!0]));function l(e){let t=e.filter(e=>e.active);if(0===t.length)return"none";let n=t.map(e=>e.name).filter(e=>!0===s[e]).sort().join(",");return n===[...i].sort().join(",")?"default":n===[...a].sort().join(",")?"full":"default"}function o(e){return"none"===e?[...r]:"full"===e?[...a]:[...i]}},20625:(e,t,n)=>{"use strict";n.d(t,{AppShell:()=>pH});var r=n(95155),i=n(12115),a=n(73321),s=n(16871),l=n(81886),o=n(68890),d=n(6057);let c=["chat","process","subagents","files","resource","sidechat","efficiency"],u=["characters","usage","models"];Object.freeze({transcript:550,composer:384,navigator:240,deck:384});let p=Object.freeze({navigator:791,deck:1176}),h=Object.freeze({activeView:"chat",transientLayer:null,deckExpanded:!1}),m=Object.fromEntries(c.map(e=>[e,!0]));function f(e){return"string"==typeof e&&!0===m[e]?e:h.activeView}function g(e,t){switch(t.type){case"select-view":{let n,r=f(t.view);return{activeView:r,transientLayer:null,deckExpanded:(n=!0===e.deckExpanded,"chat"!==r&&n)}}case"open-layer":{let n,r=f(e.activeView);return{activeView:r,transientLayer:t.layer,deckExpanded:(n=!0===e.deckExpanded,"chat"!==r&&n)}}case"toggle-layer":{let n,r=f(e.activeView);return{activeView:r,transientLayer:e.transientLayer===t.layer?null:t.layer,deckExpanded:(n=!0===e.deckExpanded,"chat"!==r&&n)}}case"close-layer":{let t,n=f(e.activeView);return{activeView:n,transientLayer:null,deckExpanded:(t=!0===e.deckExpanded,"chat"!==n&&t)}}case"set-deck-expanded":{let n,r=f(e.activeView);return{activeView:r,transientLayer:e.transientLayer,deckExpanded:(n=t.expanded,"chat"!==r&&n)}}}}function x(e){let t=Number.isFinite(e)?Math.max(0,e):0;return{availableWidth:t,navigator:t>=p.navigator?"pinned":"drawer",deck:t>=p.deck?"pinned":"view-stack"}}let v=null,b=!1,y=-1/0;function w(e,t=Date.now()){b=e,e||(y=t)}let k=["projects","priority"],j="omp-web:navigator-mode",S="omp-prio-on",C=["omp-relay-session-","omp-cwd-","ompscope_"];function N(e){let t=e.trim().replace(/\\/g,"/");return"/"===(t=t.startsWith("//")?`//${t.slice(2).replace(/\/{2,}/g,"/")}`:t.replace(/\/{2,}/g,"/"))||/^[a-zA-Z]:\/$/.test(t)||(t=t.replace(/\/+$/,"")),/^[a-zA-Z]:\//.test(t)||t.startsWith("//")?t.toLowerCase():t}function I(e){let t=new Map;for(let n of e){let e=n.projectRoot??n.cwd;if(!e)continue;let r=N(e),i=t.get(r);(!i||n.modified>i.modified)&&t.set(r,{project:e,modified:n.modified})}return[...t.values()].sort((e,t)=>t.modified.localeCompare(e.modified)).map(e=>e.project)}function T(e,t){let n=new Map;for(let e of t)"number"==typeof e.order&&Number.isFinite(e.order)&&n.set(N(e.key),e.order);let r=[...e],i=new Set(e.map(N));for(let e of t){let t=N(e.key);!t||i.has(t)||(r.push(e.path??e.key),i.add(t))}return r.map((e,t)=>({project:e,defaultIndex:t,order:n.get(N(e))})).sort((e,t)=>{let n=void 0!==e.order,r=void 0!==t.order;return n!==r?n?-1:1:n&&r&&e.order!==t.order?e.order-t.order:e.defaultIndex-t.defaultIndex}).map(({project:e})=>e)}let M=/^<skill name="([^"\n]+)" location="([^"\n]+)">\nReferences are relative to [^\n]+\.\n\n([\s\S]*)\n<\/skill>(?:\n\n([\s\S]+))?$/;function $(e){let t=e.match(M);if(!t)return null;let[,n,,,r]=t;return r?`/skill:${n} ${r}`:`/skill:${n}`}var R=n(92176);let E=`(max-width: ${p.navigator-1}px)`;function L(e){return{subscribe(t){if(!window.matchMedia)return()=>{};let n=window.matchMedia(e);return n.addEventListener("change",t),()=>n.removeEventListener("change",t)},getSnapshot:()=>!!window.matchMedia&&window.matchMedia(e).matches}}let A=L("(max-width: 640px)"),z=L(E);function P(){return!1}function W(){return(0,i.useSyncExternalStore)(A.subscribe,A.getSnapshot,P)}var F=n(47650);async function _(e){let t=e?`?path=${encodeURIComponent(e)}`:"",n=await fetch(`/api/cwd/browse${t}`),r=await n.json();if(!n.ok||r.error)throw Error(r.error??`HTTP ${n.status}`);return r}function D(){return(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.3","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M1.5 3h4l1.5 2h7.5v7.5h-13z"})})}function O(){return(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.3",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("rect",{x:"2",y:"3",width:"12",height:"10",rx:"1.5"}),(0,r.jsx)("path",{d:"M2 9h12"}),(0,r.jsx)("circle",{cx:"11.5",cy:"11",r:"0.6",fill:"currentColor",stroke:"none"})]})}function H({onCancel:e,onSelect:t,busy:n=!1,error:a}){let{t:s}=(0,R.s)(),[l,o]=(0,i.useState)(null),[d,c]=(0,i.useState)(""),[u,p]=(0,i.useState)(null),[h,m]=(0,i.useState)(!1),[f,g]=(0,i.useState)(""),[x,v]=(0,i.useState)([]),[b,y]=(0,i.useState)(null),[w,k]=(0,i.useState)(null),[j,S]=(0,i.useState)(!0),C=(0,i.useCallback)(async e=>{S(!0),k(null);try{let t=await _(e),n=t.path??e??"/";c(n),p(t.parentPath??null),m(!0===t.upToDrives),g(n),v(t.directories??[]),y(t.drives??null)}catch(e){k(e instanceof Error?e.message:String(e))}finally{S(!1)}},[]);(0,i.useEffect)(()=>{o(document.body),C()},[C]);let N=f.trim()!==d,I=!!d&&!N&&!n,T=!!u||h||/^[a-zA-Z]:[\\/]?$/.test(d);return l?(0,F.createPortal)((0,r.jsx)("div",{className:"directory-picker-backdrop",role:"dialog","aria-modal":"true","aria-label":s("directoryPicker.selectDirectory"),onClick:t=>{t.target!==t.currentTarget||n||e()},onKeyDown:t=>{"Escape"!==t.key||n||e()},style:{position:"fixed",inset:0,zIndex:1e3,display:"flex",alignItems:"center",justifyContent:"center",background:"rgba(0,0,0,0.35)"},children:(0,r.jsxs)("div",{className:"directory-picker-panel",style:{width:520,maxWidth:"calc(100vw - 16px)",height:"min(620px, calc(100dvh - 16px))",maxHeight:"calc(100dvh - 16px)",display:"flex",flexDirection:"column",overflow:"hidden",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:10,boxShadow:"0 8px 32px rgba(0,0,0,0.18)"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",flexShrink:0,padding:"12px 18px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("div",{style:{minWidth:0,flex:1},children:(0,r.jsx)("div",{style:{color:"var(--text)",fontWeight:700,fontSize:15},children:s("directoryPicker.selectDirectory")})}),(0,r.jsx)("button",{type:"button",onClick:e,disabled:n,title:s("i18n.close"),"aria-label":s("i18n.close"),style:{padding:"2px 6px",border:0,background:"none",color:"var(--text-muted)",fontSize:20,lineHeight:1,cursor:n?"default":"pointer",opacity:n?.5:1},children:"\xd7"})]}),(0,r.jsxs)("form",{onSubmit:e=>{e.preventDefault();let t=f.trim();t&&C(t)},style:{display:"flex",alignItems:"center",gap:8,flexShrink:0,padding:"10px 14px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("button",{className:"directory-picker-back",type:"button",onClick:()=>void C(u??void 0),disabled:j||!T,title:s("directoryPicker.goToParent"),"aria-label":s("directoryPicker.goToParent"),style:{width:36,height:36,padding:0,display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-hover)",color:"var(--text-muted)",cursor:T?"pointer":"default",opacity:T?1:.45},children:(0,r.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m18 15-6-6-6 6"})})}),(0,r.jsx)("label",{htmlFor:"directory-path",style:{position:"absolute",width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",border:0},children:s("directoryPicker.directoryPath")}),(0,r.jsx)("input",{className:"directory-picker-path",id:"directory-path",type:"text",value:f,placeholder:"/path/to/project or ~/project",autoFocus:!0,autoComplete:"off",spellCheck:!1,onChange:e=>{g(e.target.value),k(null)},style:{minWidth:0,flex:1,height:36,padding:"0 10px",border:"1px solid var(--border)",borderRadius:6,outline:"none",background:"var(--bg-panel)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:12}}),(0,r.jsx)("button",{className:"directory-picker-action",type:"submit",disabled:j||!f.trim(),title:s("directoryPicker.goToDirectory"),style:{minWidth:58,height:36,padding:"0 12px",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-hover)",color:"var(--text-muted)",cursor:j||!f.trim()?"default":"pointer",opacity:j||!f.trim()?.6:1},children:s("directoryPicker.go")})]}),(0,r.jsxs)("div",{className:"directory-picker-list",style:{flex:1,minHeight:0,overflow:"auto",padding:"8px 10px"},children:[j?(0,r.jsx)("div",{style:{padding:8,color:"var(--text-dim)",fontSize:11},children:s("directoryPicker.loadingDirectories")}):null!==b?(0,r.jsx)(r.Fragment,{children:b.length>0?b.map(e=>(0,r.jsxs)("button",{className:"directory-picker-entry",type:"button",onClick:()=>void C(e.path),title:e.path,style:{width:"100%",minHeight:34,display:"flex",alignItems:"center",gap:7,padding:"6px 8px",border:0,borderRadius:5,background:"none",color:"var(--text-muted)",cursor:"pointer",textAlign:"left",fontFamily:"var(--font-mono)",fontSize:11},children:[(0,r.jsx)(O,{}),(0,r.jsx)("span",{children:e.name})]},e.path)):(0,r.jsx)("div",{style:{padding:8,color:"var(--text-dim)",fontSize:11},children:s("directoryPicker.noDrives")})}):x.length>0?x.map(e=>(0,r.jsxs)("button",{className:"directory-picker-entry",type:"button",onClick:()=>void C(e.path),title:e.path,style:{width:"100%",minHeight:30,display:"flex",alignItems:"center",gap:7,padding:"5px 8px",border:0,borderRadius:5,background:"none",color:"var(--text-muted)",cursor:"pointer",textAlign:"left",fontFamily:"var(--font-mono)",fontSize:11},children:[(0,r.jsx)(D,{}),(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name})]},e.path)):(0,r.jsx)("div",{style:{padding:8,color:"var(--text-dim)",fontSize:11},children:s("directoryPicker.noSubdirectories")}),(w||a)&&(0,r.jsx)("div",{style:{padding:"8px",color:"#dc2626",fontSize:11},children:w??a})]}),(0,r.jsxs)("div",{className:"directory-picker-footer",style:{display:"flex",justifyContent:"flex-end",alignItems:"center",gap:10,flexShrink:0,padding:"10px 18px",borderTop:"1px solid var(--border)"},children:[(0,r.jsx)("button",{className:"directory-picker-action",type:"button",onClick:e,disabled:n,style:{padding:"6px 14px",border:"1px solid var(--border)",borderRadius:6,background:"none",color:"var(--text-muted)",cursor:n?"default":"pointer",fontSize:13},children:s("i18n.cancel")}),(0,r.jsx)("button",{className:"directory-picker-action",type:"button",onClick:()=>t(d),disabled:!I,title:s(N?"directoryPicker.openBeforeSelecting":"directoryPicker.selectCurrentDirectory"),style:{padding:"6px 16px",border:0,borderRadius:6,background:"var(--seed-color-bg-neutral-inverted)",color:"var(--seed-color-fg-neutral-inverted)",fontSize:13,fontWeight:600,opacity:I?1:.6,cursor:I?"pointer":"default"},children:s(n?"i18n.checking":"directoryPicker.selectThisFolder")})]})]})}),l):null}var B=n(21443),U=n.n(B);async function q(e,t){let n=await fetch(e,t?{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}:void 0),r=await n.json();if(!n.ok)throw Error(r.error||`HTTP ${n.status}`);return r}function K({onCancel:e,onSelect:t,busy:n=!1,error:a}){let{t:s}=(0,R.s)(),l=(0,i.useRef)(null),[o,d]=(0,i.useState)(!1),[c,u]=(0,i.useState)(!1),[p,h]=(0,i.useState)(null),[m,f]=(0,i.useState)([]),[g,x]=(0,i.useState)(""),[v,b]=(0,i.useState)(""),[y,w]=(0,i.useState)(!0),[k,j]=(0,i.useState)(!1),[S,C]=(0,i.useState)(!1),[N,I]=(0,i.useState)(null),[T,M]=(0,i.useState)(!1),[$,E]=(0,i.useState)(50),L=p?.device?.state==="pending",A=n||S,z=(0,i.useCallback)(async()=>{w(!0),I(null);try{let e=await q("/api/github/projects");h(e),e.connected&&f((await q("/api/github/projects?view=repositories")).repositories)}catch(e){I(e instanceof Error?e.message:String(e))}finally{w(!1)}},[]);async function P(){j(!0),I(null);try{let{device:e}=await q("/api/github/projects",{action:"login"});h({connected:!1,login:null,device:e})}catch(e){I(e instanceof Error?e.message:String(e))}finally{j(!1)}}async function W(e){if(e.preventDefault(),v.trim()&&!A){C(!0),I(null);try{let{cwd:e}=await q("/api/github/projects",{action:"open",repository:v});t(e)}catch(e){I(e instanceof Error?e.message:String(e))}finally{C(!1)}}}if((0,i.useEffect)(()=>{d(!0),z()},[z]),(0,i.useEffect)(()=>{if(!o||c)return;let e=l.current;return e?.showModal(),()=>e?.close()},[o,c]),(0,i.useEffect)(()=>{let e;if(!L||c)return;let t=!1,n=async()=>{try{let e=await q("/api/github/projects");if(t)return;if(h(e),e.connected)return void await z();if(e.device?.state!=="pending")return}catch(e){t||I(e instanceof Error?e.message:String(e));return}t||(e=window.setTimeout(n,3e3))};return e=window.setTimeout(n,1500),()=>{t=!0,clearTimeout(e)}},[L,c,z]),!o)return null;if(c)return(0,r.jsx)(H,{onCancel:()=>u(!1),onSelect:t,busy:n,error:a});let _=m.filter(e=>`${e.fullName} ${e.description??""}`.toLowerCase().includes(g.toLowerCase())),D=N??a??p?.device?.error;return(0,F.createPortal)((0,r.jsx)("dialog",{ref:l,className:U().dialog,"aria-labelledby":"cloud-project-title",onCancel:t=>{t.preventDefault(),A||e()},children:(0,r.jsxs)("form",{onSubmit:W,className:U().form,children:[(0,r.jsxs)("header",{className:U().header,children:[(0,r.jsx)("h2",{id:"cloud-project-title",children:s("cloudProjects.title")}),(0,r.jsx)("p",{children:s("cloudProjects.description")})]}),(0,r.jsxs)("div",{className:U().sources,children:[(0,r.jsx)("span",{className:U().activeSource,children:s("cloudProjects.github")}),(0,r.jsx)("button",{type:"button",onClick:()=>u(!0),disabled:A,children:s("cloudProjects.serverFolder")})]}),(0,r.jsxs)("div",{className:U().body,children:[(0,r.jsxs)("section",{className:U().account,"aria-label":s("cloudProjects.account"),children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("strong",{children:p?.connected?p.login:s("cloudProjects.connectTitle")}),(0,r.jsx)("p",{children:p?.connected?s("cloudProjects.connected"):s("cloudProjects.connectHelp")})]}),p?.connected?(0,r.jsx)("button",{type:"button",className:U().secondary,onClick:()=>void z(),disabled:y||A,children:s("cloudProjects.refresh")}):(0,r.jsx)("button",{type:"button",className:U().secondary,onClick:()=>void P(),disabled:y||k||L||A,children:k||L?s("cloudProjects.waiting"):s("cloudProjects.connect")})]}),L&&(0,r.jsxs)("div",{className:U().login,role:"status",children:[(0,r.jsx)("p",{children:s("cloudProjects.deviceHelp")}),p.device?.code?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("div",{className:U().codeRow,children:[(0,r.jsx)("code",{children:p.device.code}),(0,r.jsx)("button",{type:"button",className:U().secondary,onClick:()=>{navigator.clipboard.writeText(p.device.code).then(()=>M(!0)).catch(()=>I(s("cloudProjects.copyFailure")))},children:T?s("cloudProjects.copied"):s("cloudProjects.copyCode")})]}),(0,r.jsx)("a",{href:"https://github.com/login/device",target:"_blank",rel:"noreferrer",className:U().loginLink,children:s("cloudProjects.openLogin")}),(0,r.jsx)("small",{children:s("cloudProjects.permissionHelp")})]}):(0,r.jsx)("p",{children:s("cloudProjects.preparingCode")})]}),p?.connected&&(0,r.jsxs)("section",{className:U().repositories,"aria-label":s("cloudProjects.repositories"),children:[(0,r.jsx)("label",{htmlFor:"cloud-repo-search",children:s("cloudProjects.search")}),(0,r.jsx)("input",{id:"cloud-repo-search",value:g,onChange:e=>{x(e.target.value),E(50)},placeholder:s("cloudProjects.searchPlaceholder"),type:"search",disabled:A}),y?(0,r.jsx)("p",{role:"status",children:s("cloudProjects.loading")}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("ul",{className:U().list,children:_.slice(0,$).map(e=>(0,r.jsx)("li",{children:(0,r.jsxs)("button",{type:"button",className:U().repo,"aria-pressed":v===e.fullName,disabled:A,onClick:()=>b(e.fullName),children:[(0,r.jsxs)("span",{className:U().repoHeading,children:[(0,r.jsx)("strong",{children:e.fullName}),(0,r.jsx)("small",{children:e.private?s("cloudProjects.private"):s("cloudProjects.public")})]}),e.description&&(0,r.jsx)("span",{className:U().repoDescription,children:e.description})]})},e.fullName))}),!_.length&&(0,r.jsx)("p",{children:s("cloudProjects.empty")}),_.length>$&&(0,r.jsx)("button",{type:"button",className:U().secondary,onClick:()=>E(e=>e+50),children:s("cloudProjects.more")})]})]}),(0,r.jsxs)("div",{className:U().repositoryInput,children:[(0,r.jsx)("label",{htmlFor:"cloud-repository",children:s("cloudProjects.urlLabel")}),(0,r.jsx)("input",{id:"cloud-repository",value:v,onChange:e=>b(e.target.value),placeholder:"owner/repository",autoComplete:"off",spellCheck:!1,disabled:A,"aria-describedby":"cloud-repo-help"}),(0,r.jsx)("small",{id:"cloud-repo-help",children:s("cloudProjects.publicHelp")})]}),D&&(0,r.jsxs)("div",{className:U().error,role:"alert",children:[(0,r.jsx)("strong",{children:s("cloudProjects.error")}),(0,r.jsx)("p",{children:D}),(0,r.jsx)("button",{type:"button",className:U().secondary,onClick:()=>void z(),disabled:A,children:s("cloudProjects.refresh")})]}),S&&(0,r.jsx)("p",{role:"status",className:U().progress,children:s("cloudProjects.openingHelp")})]}),(0,r.jsxs)("footer",{className:U().footer,children:[(0,r.jsx)("button",{type:"button",className:U().secondary,onClick:e,disabled:A,children:s("i18n.cancel")}),(0,r.jsx)("button",{type:"submit",className:U().primary,disabled:A||!v.trim(),children:A?s("cloudProjects.opening"):s("cloudProjects.open")})]})]})}),document.body)}function V({label:e="CUELO",markSize:t=22,gap:n=10,style:i,labelStyle:a}){return(0,r.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:n,minWidth:0,color:"var(--text)",...i},children:[(0,r.jsxs)("svg",{viewBox:"0 0 100 100",width:t,height:t,"aria-hidden":"true",style:{flexShrink:0},children:[(0,r.jsx)("path",{d:"M77.9 30.5 A34 34 0 0 0 16 50 A26 26 0 0 0 68 50",fill:"none",stroke:"currentColor",strokeWidth:"10",strokeLinecap:"round"}),(0,r.jsx)("circle",{cx:"42",cy:"50",r:"8.5",fill:"var(--brand-lamp)"})]}),(0,r.jsx)("span",{style:{minWidth:0,overflow:"hidden",color:"inherit",fontFamily:"var(--font-heading)",fontSize:15,fontWeight:700,letterSpacing:"-0.025em",whiteSpace:"nowrap",...a},children:e})]})}var J=n(2730);let G={ko:{"translator.tab":"통역","translator.title":"통역","translator.back":"대화로","translator.panelHint":"통역을 시작하면 ChatGPT 계정의 Codex 라이브 통화로 두 사람의 말을 서로의 언어로 바로 소리 내어 옮깁니다. 작업 세션과 하네스 규칙을 거치지 않고, 기록은 저장하지 않습니다.","translator.open":"통역 화면 열기","translator.me":"나","translator.them":"상대","translator.myLanguage":"내 언어","translator.theirLanguage":"상대 언어","translator.swap":"두 언어 바꾸기","translator.clear":"지우기","translator.start":"통역 시작","translator.stop":"통역 끝내기","translator.empty":"통역 시작을 누르고 폰을 두 사람 사이에 두세요. 누가 말하든 상대 언어로 바로 옮겨 말합니다.","translator.connecting":"연결 중…","translator.live":"듣는 중 \xb7 그냥 말하세요","translator.unsupported":"이 브라우저는 실시간 통화(WebRTC\xb7마이크)를 지원하지 않습니다. 폰에서는 Chrome이나 Safari로 여세요.","translator.insecure":"마이크는 HTTPS 주소에서만 켜집니다.","translator.micDenied":"마이크 권한이 막혀 있습니다. 브라우저 설정에서 이 주소의 마이크를 허용하세요.","translator.micUnavailable":"마이크를 켜지 못했습니다. 다른 앱이 쓰고 있지 않은지 확인하세요.","translator.auth":"Codex 로그인이 없거나 만료됐습니다. 모델 설정에서 ChatGPT 계정으로 다시 로그인하세요.","translator.upstream":"Codex 라이브 연결이 끊겼습니다: {error}","translator.failed":"통역을 시작하지 못했습니다: {error}","translator.original":"원문","translator.translationPending":"통역 중…","translator.conversation":"통역 기록"},en:{"translator.tab":"Interpret","translator.title":"Interpreter","translator.back":"Back to chat","translator.panelHint":"Start interpreting and a Codex live call on your ChatGPT account speaks each person's words in the other's language right away. It bypasses work sessions and harness rules, and nothing is saved.","translator.open":"Open interpreter","translator.me":"Me","translator.them":"Them","translator.myLanguage":"My language","translator.theirLanguage":"Their language","translator.swap":"Swap languages","translator.clear":"Clear","translator.start":"Start interpreting","translator.stop":"Stop interpreting","translator.empty":"Press Start interpreting and put the phone between you. Whoever speaks is interpreted into the other language right away.","translator.connecting":"Connecting…","translator.live":"Listening \xb7 just talk","translator.unsupported":"This browser cannot make live calls (WebRTC and microphone). On a phone, open this page in Chrome or Safari.","translator.insecure":"The microphone only works on an HTTPS address.","translator.micDenied":"Microphone access is blocked. Allow the microphone for this address in the browser settings.","translator.micUnavailable":"The microphone could not be opened. Check that no other app is using it.","translator.auth":"The Codex sign-in is missing or expired. Sign in again with your ChatGPT account in model settings.","translator.upstream":"The Codex live connection dropped: {error}","translator.failed":"Interpreting could not start: {error}","translator.original":"Original","translator.translationPending":"Interpreting…","translator.conversation":"Interpretation log"},"zh-CN":{"translator.tab":"口译","translator.title":"口译","translator.back":"返回对话","translator.panelHint":"开始口译后,通过 ChatGPT 账号的 Codex 实时通话,把双方的话立即用对方的语言说出来。不经过工作会话和规则,也不保存记录。","translator.open":"打开口译","translator.me":"我","translator.them":"对方","translator.myLanguage":"我的语言","translator.theirLanguage":"对方语言","translator.swap":"交换语言","translator.clear":"清除","translator.start":"开始口译","translator.stop":"结束口译","translator.empty":"按开始口译,把手机放在两人之间。无论谁说话,都会立即译成对方的语言说出来。","translator.connecting":"连接中…","translator.live":"正在听 \xb7 直接说话","translator.unsupported":"此浏览器不支持实时通话(WebRTC 和麦克风)。手机请用 Chrome 或 Safari 打开。","translator.insecure":"麦克风只能在 HTTPS 地址上使用。","translator.micDenied":"麦克风权限被阻止。请在浏览器设置中允许此地址使用麦克风。","translator.micUnavailable":"无法打开麦克风。请确认没有其他应用正在使用。","translator.auth":"Codex 登录不存在或已过期。请在模型设置中用 ChatGPT 账号重新登录。","translator.upstream":"Codex 实时连接已断开:{error}","translator.failed":"无法开始口译:{error}","translator.original":"原文","translator.translationPending":"口译中…","translator.conversation":"口译记录"}};function Y(){let{locale:e}=(0,R.s)();return{tt:(0,i.useCallback)((t,n)=>(0,J.u0)(e,t,G,n),[e]),locale:e}}let Z="omp-web:unread-session-ids",X="omp-web:pinned-session-ids",Q="omp-web:removed-projects";function ee(e,t){return{minHeight:t?36:30,padding:"3px 10px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"transparent",color:e?"var(--text-dim)":"var(--text-muted)",cursor:e?"default":"pointer",fontSize:"var(--seed-font-size-t2-static)",lineHeight:1.3,textAlign:"left",whiteSpace:"normal",overflowWrap:"anywhere"}}function et(e,t){return t&&e.startsWith(t)?"~"+e.slice(t.length):e}function en({text:e,style:t}){return(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",display:"block",minWidth:0,lineHeight:1.35,direction:"rtl",textAlign:"left",...t},children:(0,r.jsx)("span",{style:{unicodeBidi:"plaintext"},children:e})})}function er({open:e,children:t,style:n}){let[a,s]=(0,i.useState)(e),[l,o]=(0,i.useState)(e);return((0,i.useEffect)(()=>{let t,n;return e?(s(!0),o(!1),t=window.requestAnimationFrame(()=>{t=window.requestAnimationFrame(()=>o(!0))})):(o(!1),n=setTimeout(()=>s(!1),140)),()=>{void 0!==t&&window.cancelAnimationFrame(t),n&&clearTimeout(n)}},[e]),a)?(0,r.jsx)("div",{style:{...n,opacity:+!!l,transform:l?"translateY(0) scale(1)":"translateY(-8px) scale(0.96)",transformOrigin:"top center",transition:"opacity 140ms ease, transform 140ms ease",pointerEvents:e?"auto":"none"},children:t}):null}let ei="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*";function ea(){let[e,t]=(0,i.useState)(!1),[n,a]=(0,i.useState)(!1),s=(0,i.useRef)(null),l=function(e,t){let[n,r]=(0,i.useState)(e),a=(0,i.useRef)(null),s=(0,i.useRef)(0);return(0,i.useEffect)(()=>{if(!t)return void r(e);s.current=0;let n=4*e.length,i=()=>{s.current+=1;let t=Math.floor(s.current/n*e.length);r(e.split("").map((e,n)=>" "===e?" ":n<t?e:ei[Math.floor(Math.random()*ei.length)]).join("")),s.current<n?a.current=requestAnimationFrame(i):r(e)};return a.current=requestAnimationFrame(i),()=>{a.current&&cancelAnimationFrame(a.current)}},[e,t]),n}(e?"0.10.34/18.12.1":"CUELO",n),o=(0,i.useCallback)(e=>{t(e),a(!0),setTimeout(()=>a(!1),(e?6:8)*4*(1e3/60)+100)},[]),d=(0,i.useCallback)(()=>{s.current&&clearTimeout(s.current);let t=!e;o(t),t&&(s.current=setTimeout(()=>o(!1),3e3))},[e,o]);return(0,i.useEffect)(()=>()=>{s.current&&clearTimeout(s.current)},[]),(0,r.jsx)("button",{className:"navigator-brand",onClick:d,style:{display:"flex",alignItems:"center",background:"none",border:"none",padding:0,cursor:"default",color:e?"var(--accent)":"var(--text)",flex:"0 1 auto",minWidth:0,overflow:"hidden"},children:(0,r.jsx)(V,{label:l,labelStyle:e?{fontFamily:"var(--font-mono)",fontSize:12,letterSpacing:"-0.02em",textOverflow:"ellipsis"}:void 0})})}async function es(e){let t=await fetch("/api/projects",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({updates:e})});if(!t.ok)throw Error(`HTTP ${t.status}`)}function el({selectedSessionId:e,optimisticSession:t,onSelectSession:n,onNewSession:a,initialSessionId:s,skipInitialProjectSelection:l,onInitialRestoreDone:o,refreshKey:d,onSessionDeleted:c,selectedCwd:u,onCwdChange:p,onBackgroundTaskDone:h,translatorPanel:m,translatorActive:f=!1,onTranslatorActiveChange:g}){let x,{tt:v}=Y(),{t:b,locale:y}=(0,R.s)(),w=W(),[M,$]=(0,i.useState)([]),E=t&&!M.some(e=>e.id===t.id)?[t,...M]:M,[L,A]=(0,i.useState)(!0),[z,P]=(0,i.useState)(null),[F,_]=(0,i.useState)(null),[D,O]=(0,i.useState)(""),[B,U]=(0,i.useState)(!1),[q,V]=(0,i.useState)(""),[J,G]=(0,i.useState)("projects"),[ei,ed]=(0,i.useState)(()=>new Set),[eh,em]=(0,i.useState)(()=>new Set),[eg,ex]=(0,i.useState)(null),[ev,eb]=(0,i.useState)(null),[ey,ew]=(0,i.useState)({version:1,projects:[]}),[ek,ej]=(0,i.useState)(!1),[eS,eC]=(0,i.useState)(!1),[eN,eI]=(0,i.useState)(!1),[eT,eM]=(0,i.useState)(null),[e$,eR]=(0,i.useState)(""),[eE,eL]=(0,i.useState)(!1),[eA,ez]=(0,i.useState)(null),[eP,eW]=(0,i.useState)(""),[eF,e_]=(0,i.useState)(!1),[eD,eO]=(0,i.useState)(null),[eH,eB]=(0,i.useState)(!1),[eU,eq]=(0,i.useState)(null),[eK,eV]=(0,i.useState)(!1),[eJ,eG]=(0,i.useState)(!1),[eY,eZ]=(0,i.useState)(""),[eX,eQ]=(0,i.useState)(null),[e0,e1]=(0,i.useState)(!1),[e2,e4]=(0,i.useState)(null),e5=(0,i.useRef)(null),e6=(0,i.useRef)(null),e8=(0,i.useRef)(null),e3=(0,i.useRef)(!1),e7=(0,i.useRef)(!1),[e9,te]=(0,i.useState)(!1),[tt,tn]=(0,i.useState)(()=>new Set),[tr,ti]=(0,i.useState)(()=>(function(){try{let e=window.localStorage.getItem(Z);if(!e)return new Set;let t=JSON.parse(e);if(Array.isArray(t))return new Set(t.filter(e=>"string"==typeof e));return new Set}catch{return new Set}})()),[ta,ts]=(0,i.useState)(()=>new Set),tl=(0,i.useRef)(new Set),to=(0,i.useRef)(!1),td=(0,i.useRef)(null);(0,i.useEffect)(()=>{ts(function(){try{let e=window.localStorage.getItem(X);if(!e)return new Set;let t=JSON.parse(e);return Array.isArray(t)?new Set(t.filter(e=>"string"==typeof e)):new Set}catch{return new Set}}())},[]);let tc=(0,i.useCallback)(async()=>{try{let e=await fetch("/api/projects",{cache:"no-store",signal:AbortSignal.timeout(5e3)});if(!e.ok)throw Error(`HTTP ${e.status}`);ew(await e.json())}catch{ew({version:1,projects:[]})}finally{ej(!0)}},[]);(0,i.useEffect)(()=>{tc()},[tc,d]),(0,i.useEffect)(()=>{let e=null;try{e=window.localStorage.getItem(Q)}catch{return}if(!e)return;let t=[];try{let n=JSON.parse(e);Array.isArray(n)&&(t=n.filter(e=>"string"==typeof e))}catch{t=[]}(async()=>{try{for(let e=0;e<t.length;e+=500){let n=t.slice(e,e+500);await es(n.map(e=>({key:N(e),path:e,hidden:!0})))}}catch{return}try{window.localStorage.removeItem(Q)}catch{}await tc()})()},[tc]);let tu=(0,i.useCallback)(async e=>{if(e7.current)throw Error("Project update in progress");e7.current=!0,eL(!0);try{await es(e),await tc()}finally{e7.current=!1,eL(!1)}},[tc]);(0,i.useEffect)(()=>{eT&&e8.current?.select()},[eT]);let tp=(0,i.useCallback)(async(e=!1,t=!1)=>{try{e&&A(!0);let n=await fetch(t?"/api/sessions?force=1":"/api/sessions",{cache:"no-store"});if(!n.ok)throw Error(`HTTP ${n.status}`);let r=await n.json();$(r.sessions),to.current||tn(new Set(r.runningSessionIds??[])),P(null),e||(te(!0),td.current&&clearTimeout(td.current),td.current=setTimeout(()=>te(!1),2e3))}catch(e){P(String(e))}finally{e&&A(!1)}},[]),th=(0,i.useCallback)(e=>{ti(t=>{if(!t.has(e))return t;let n=new Set(t);return n.delete(e),n}),ts(t=>{if(!t.has(e))return t;let n=new Set(t);return n.delete(e),n}),c?.(e),tp()},[tp,c]),[tm,tf]=(0,i.useState)(null),[tg,tx]=(0,i.useState)(!1),[tv,tb]=(0,i.useState)(null),ty=(0,i.useCallback)(()=>{tg||(tf(null),tb(null))},[tg]),tw=(0,i.useCallback)(async e=>{tx(!0),tb(null);let t=[],n=[],r=[];for(let i of e)if(!i.transient)try{let e=await fetch(`/api/sessions/${encodeURIComponent(i.id)}?skipRunning=1`,{method:"DELETE"});if(409===e.status){n.push(i.id);continue}if(!e.ok)throw Error(`HTTP ${e.status}`);t.push(i.id)}catch{r.push(i.name?.trim()||i.id.slice(0,8))}if(n.length>0&&(to.current=!0,tn(e=>{if(n.every(t=>e.has(t)))return e;let t=new Set(e);for(let e of n)t.add(e);return t})),t.length>0){let e=new Set(t),n=n=>t.some(e=>n.has(e))?new Set([...n].filter(t=>!e.has(t))):n;for(let e of(ti(n),ts(n),t))c?.(e)}(await tp(),tx(!1),r.length>0)?tb(b("sidebar.clearSessionsFailed",{count:r.length,names:r.join(", ")})):n.length>0||tf(null)},[tp,c,b]),[tk,tj]=(0,i.useState)(0),tS=(0,i.useCallback)(()=>{tj(e=>e+1),tp()},[tp]),tC=(0,i.useRef)(!1);(0,i.useEffect)(()=>{let e=!tC.current;tC.current=!0,tp(e,!e)},[tp,d]),(0,i.useEffect)(()=>{try{G(function(e,t){return"gpt6"===e?"projects":"string"==typeof e&&k.includes(e)?e:"1"===t?"priority":"projects"}(window.localStorage.getItem(j),window.localStorage.getItem(S)))}catch{}},[]);let tN=(0,i.useCallback)(e=>{G(e);try{window.localStorage.setItem(j,e),window.localStorage.setItem(S,"priority"===e?"1":"0")}catch{}},[]);(0,i.useEffect)(()=>{if("priority"!==J)return;let e=()=>{"visible"===document.visibilityState&&tp(!1,!0)};e();let t=window.setInterval(e,15e3);return()=>window.clearInterval(t)},[tp,J]),(0,i.useEffect)(()=>{try{0===tr.size?window.localStorage.removeItem(Z):window.localStorage.setItem(Z,JSON.stringify([...tr]))}catch{}},[tr]),(0,i.useEffect)(()=>{try{0===ta.size?window.localStorage.removeItem(X):window.localStorage.setItem(X,JSON.stringify([...ta]))}catch{}},[ta]);let tI=(0,i.useCallback)(e=>{ts(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]);(0,i.useEffect)(()=>{let e=!1,t=null,n=null,r=()=>{t&&clearTimeout(t),t=null},i=async()=>{if(e||"visible"!==document.visibilityState)return;let a=new AbortController;n?.abort(),n=a;try{let t=await fetch("/api/agent/running",{cache:"no-store",signal:a.signal});if(!t.ok)return;let r=await t.json();if(e||n!==a)return;to.current=!0,tn(new Set(r.runningSessionIds??[]))}catch{}finally{n===a&&(n=null),r(),e||"visible"!==document.visibilityState||(t=setTimeout(()=>void i(),2500))}},a=()=>{"visible"===document.visibilityState?i():(r(),n?.abort(),n=null)};return i(),document.addEventListener("visibilitychange",a),()=>{e=!0,r(),n?.abort(),document.removeEventListener("visibilitychange",a)}},[]),(0,i.useEffect)(()=>{let t=tl.current,n=[...t].filter(t=>!tt.has(t)&&t!==e),r=[...tt].filter(e=>!t.has(e));(n.length>0||r.length>0)&&ti(e=>{let t=new Set(e);return tt.forEach(e=>t.delete(e)),n.forEach(e=>t.add(e)),t});let i=r.some(e=>!M.some(t=>t.id===e));(n.length>0||i)&&tp(!1,!0),n.length>0&&h?.(),tl.current=tt},[tt,e,M,tp,h]),(0,i.useEffect)(()=>{e&&ti(t=>{if(!t.has(e))return t;let n=new Set(t);return n.delete(e),n})},[e]),(0,i.useEffect)(()=>{fetch("/api/home").then(e=>e.json()).then(e=>{e.home&&O(e.home),U(!0===e.cloudProjects)}).catch(()=>{})},[]);let tT=(0,i.useRef)(!1),tM=(0,i.useCallback)(e=>{if(!e)return null;if(eU&&eU.forCwd===e||eU?.worktrees.some(t=>t.path===e))return eU.projectRoot;let t=E.find(t=>t.cwd===e);return t?.projectRoot??e},[eU,E]),t$=(0,i.useRef)(null);(0,i.useEffect)(()=>{t$.current!==F&&(t$.current=F,p?.(F,tM(F)))},[F,p,tM]);let tR=(0,i.useRef)(null);(0,i.useEffect)(()=>{u&&u!==tR.current&&(tR.current=u,_(u))},[u]);let[tE,tL]=(0,i.useState)(0);(0,i.useLayoutEffect)(()=>{if(!F)return void eq(null);let e=!1;return fetch(`/api/worktrees?cwd=${encodeURIComponent(F)}`).then(e=>e.json()).then(t=>{if(!e){if(t.error||!t.projectRoot)return void eq(null);eq({forCwd:F,projectRoot:t.projectRoot,isGit:t.isGit??!1,isTopLevel:t.isTopLevel??!1,worktrees:t.worktrees??[]})}}).catch(()=>{e||eq(null)}),()=>{e=!0}},[F,tE,d]),(0,i.useEffect)(()=>{if(0!==M.length&&!l&&null===F){if(s&&!tT.current){tT.current=!0;let e=M.find(e=>e.id===s);if(e){_(e.cwd),n(e,!0);return}o?.()}if(!ek)return;let e=new Map(ey.projects.map(e=>[e.key,e])),t=T(M.length>0?I(M):[],ey.projects).filter(t=>!e.get(N(t))?.hidden);t.length>0&&_(t[0])}},[M,F,s,l,n,o,ey,ek]);let tA=(0,i.useCallback)(async e=>{let t=e.trim();if(t&&!eH){eB(!0),eO(null);try{let e=await fetch("/api/cwd/validate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:t})}),n=await e.json().catch(()=>({}));if(!e.ok||n.error)return void eO(n.error??b("workspace.unable"));let r=n.cwd??t,i=N(r),a=ey.projects.find(e=>e.key===i);if(a?.hidden===!0)try{await tu([{key:i,path:r,hidden:!1}])}catch{}_(r),e_(!1)}catch{eO(b("workspace.unable"))}finally{eB(!1)}}},[tu,eH,ey.projects,b]),tz=(0,i.useCallback)(()=>{e_(!0),eO(null)},[]),tP=(0,i.useCallback)(async()=>{let e=eY.trim();if(e&&!e0&&eU){e1(!0),eQ(null);try{let t=await fetch("/api/worktrees",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:eU.projectRoot,branch:e})}),n=await t.json().catch(()=>({}));if(!t.ok||n.error||!n.path)return void eQ(n.error??`HTTP ${t.status}`);eG(!1),eZ(""),eV(!1),eq(t=>t?{...t,forCwd:n.path,worktrees:[...t.worktrees,{path:n.path,branch:e,isMain:!1}]}:t),_(n.path),tL(e=>e+1)}catch(e){eQ(e instanceof Error?e.message:String(e))}finally{e1(!1)}}},[eY,e0,eU]),tW=(0,i.useCallback)(async(e,t)=>{if(eU&&!e0){e1(!0),eQ(null);try{let n=await fetch("/api/worktrees",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:eU.projectRoot,path:e,force:t})}),r=await n.json().catch(()=>({}));if(!n.ok){if(r.dirty&&!t)return void e4(e);eQ(r.error??`HTTP ${n.status}`);return}e4(null),F===e&&_(eU.projectRoot),tL(e=>e+1)}catch(e){eQ(e instanceof Error?e.message:String(e))}finally{e1(!1)}}},[eU,e0,F]);(0,i.useEffect)(()=>{let e=e=>{e5.current&&!e5.current.contains(e.target)&&(eb(null),eV(!1),eG(!1),eZ(""),eQ(null),e4(null),eW(""),ex(null))};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[]);let tF=(0,i.useCallback)(e=>{e.cwd&&_(e.cwd),n(e)},[n]),t_=(0,i.useCallback)((e=F)=>{if(!e)return;let t="function"==typeof crypto.randomUUID?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}-${Math.random().toString(36).slice(2)}`;_(e),a?.(t,e)},[F,a]),[tD,tO]=(0,i.useState)(!1),[tH,tB]=(0,i.useState)(null),tU=(0,i.useCallback)(async()=>{tO(!0),tB(null);try{let e=await fetch("/api/default-cwd",{method:"POST"}),t=await e.json().catch(()=>({}));if(!e.ok||!t.cwd)throw Error(t.error??`HTTP ${e.status}`);t_(t.cwd)}catch(e){tB(b("sidebar.newScratchSessionFailed",{error:e instanceof Error?e.message:String(e)}))}finally{tO(!1)}},[t_,b]),tq=(0,i.useCallback)(e=>{em(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]),tK=tM(F),tV=null===tK?null:N(tK),tJ=(0,i.useMemo)(()=>new Map(ey.projects.map(e=>[e.key,e])),[ey.projects]),tG=I(E);if(null!==tK){let e=N(tK);tG.some(t=>N(t)===e)||tG.unshift(tK)}let tY=T(tG,ey.projects),tZ=tY.filter(e=>eS||!tJ.get(N(e))?.hidden),tX=tY.some(e=>tJ.get(N(e))?.hidden),tQ=()=>{eb(null),eV(!1),eG(!1),eZ(""),eQ(null),e4(null),eW("")},t0=async(e,t)=>{tQ();try{await tu([{key:N(e),path:e,hidden:t}]),t&&tV&&tV===N(e)&&_(null),t||tY.some(t=>N(t)!==N(e)&&tJ.get(N(t))?.hidden)||eC(!1)}catch{}},t1=async e=>{if(e3.current){e3.current=!1,eM(null);return}let t=e$.trim();if(t===(tJ.get(N(e))?.alias??""))return void eM(null);ez(null);try{await tu([{key:N(e),path:e,alias:t||null}]),eM(null)}catch{ez(b("sidebar.projectUpdateFailed"))}},t2=async(e,t)=>{if(q)return;let n=tZ.indexOf(e),r=n+t;if(n<0||r<0||r>=tZ.length)return;let i=new Set(tZ),a=tY.map((e,t)=>i.has(e)?t:-1).filter(e=>e>=0),s=[...tY],l=a[n],o=a[r];[s[l],s[o]]=[s[o],s[l]],tQ();try{await tu(s.map((e,t)=>({key:N(e),path:e,order:t})))}catch{}},t4=new Map;for(let e of E){let t=e.projectRoot??e.cwd;if(!t)continue;let n=N(t),r=t4.get(n);r?r.push(e):t4.set(n,[e])}let t5=(0,i.useMemo)(()=>{let e=new Map;for(let t of E){let n=t.projectRoot??t.cwd;if(!n)continue;let r=N(n),i=e.get(r);i||(i={running:0,unread:0},e.set(r,i)),tt.has(t.id)&&i.running++,tr.has(t.id)&&i.unread++}return e},[E,tt,tr]),t6=q.trim().toLowerCase(),t8=q.length>0,t3=tZ.flatMap(e=>{let t=e.replace(/[\\/]+$/,"").split(/[\\/]/).at(-1)||e,n=N(e),r=tJ.get(n),i=r?.alias??t,a=(t4.get(n)??[]).slice().sort((e,t)=>{let n=Number(ta.has(t.id))-Number(ta.has(e.id));return 0!==n?n:t.modified.localeCompare(e.modified)});if(!t6)return[{project:e,key:n,name:i,sessions:a,hidden:r?.hidden===!0}];let s=i.toLowerCase().includes(t6)||t.toLowerCase().includes(t6),l=a.filter(e=>(e.name||e.firstMessage.slice(0,50)||e.id.slice(0,12)).toLowerCase().includes(t6));return s||0!==l.length?[{project:e,key:n,name:i,sessions:s?a:l,hidden:r?.hidden===!0}]:[]}),t7=[],t9=[];for(let e of t3){let t=e.key===tV||(t5.get(e.key)?.running??0)>0;(function(e){let t=e.trim().replace(/\\/g,"/").toLowerCase();return!!(/^[a-z]:\/?$/.test(t)||"/"===t||/(^|\/)appdata\/local\/temp(\/|$)/.test(t)||/^\/(?:var\/|private\/)?tmp(?:\/|$)/.test(t)||/^[a-z]:\/(?:tmp|temp)(?:\/|$)/.test(t)||/(^|\/)(?:users|home)\/[^/]+\/\.omp(\/|$)/.test(t))||t.split("/").some(e=>C.some(t=>e.startsWith(t)))})(e.project)&&!t?t9.push(e):t7.push(e)}let ne={running:0,unread:0};for(let e of t9){let t=t5.get(e.key);t&&(ne.running+=t.running,ne.unread+=t.unread)}let nt=t8||eN,nn=[...t7.map(e=>({kind:"project",group:e})),...t9.length>0?[{kind:"temporary"}]:[],...nt?t9.map(e=>({kind:"project",group:e})):[]],nr=function(e){let t=new Map;for(let n of e){let e=n.toLowerCase();t.set(e,(t.get(e)??0)+1)}return new Set([...t].filter(([,e])=>e>1).map(([e])=>e))}(nn.flatMap(e=>"project"===e.kind?[e.group.name]:[])),ni=(0,i.useMemo)(()=>(function(e,t,n,r,i="Priority",a=new Set,s="Pinned"){let l=e.filter(e=>!e.transient).slice().sort((e,t)=>{let n=Date.parse(e.modified),r=Date.parse(t.modified);return(Number.isFinite(r)?r:0)-(Number.isFinite(n)?n:0)}),o=l.filter(e=>a.has(e.id)),d=[],c=new Map,u=0;for(let e of l){if(a.has(e.id))continue;if(t.has(e.id)){d.push(e);continue}let n=new Date(e.modified);if(u>=10)continue;u+=1;let r=[n.getFullYear(),String(n.getMonth()+1).padStart(2,"0"),String(n.getDate()).padStart(2,"0")].join("-"),i=c.get(r);i?i.push(e):c.set(r,[e])}let p=[];for(let e of(o.length>0&&p.push({key:"pinned",label:s,running:!1,sessions:o}),d.length>0&&p.push({key:"priority",label:i,running:!0,sessions:d}),[...c.keys()].sort().reverse()))p.push({key:e,label:function(e,t,n){let[r,i,a]=e.split("-").map(Number),s=new Date(r,i-1,a),l=Math.round((Date.UTC(t.getFullYear(),t.getMonth(),t.getDate())-Date.UTC(s.getFullYear(),s.getMonth(),s.getDate()))/864e5);return 0===l||1===l?new Intl.RelativeTimeFormat(n,{numeric:"auto"}).format(-l,"day"):l>=0&&l<7?new Intl.DateTimeFormat(n,{weekday:"long"}).format(s):new Intl.DateTimeFormat(n,{month:"short",day:"numeric"}).format(s)}(e,n,r),running:!1,sessions:c.get(e)??[]});return p})(E,tt,new Date,y,b("navigator.priority"),ta,b("sidebar.pinned")),[y,ta,tt,E,b]),na=!!(eU?.isGit&&eU.isTopLevel&&F&&tK===eU.projectRoot),ns=eU?.worktrees.find(e=>e.path===F)??eU?.worktrees.find(e=>e.isMain),nl=(eU?.worktrees.length??0)>=8,no=nl&&eP.trim()?(eU?.worktrees??[]).filter(e=>(e.branch??et(e.path,D)).toLowerCase().includes(eP.trim().toLowerCase())):eU?.worktrees??[],nd=(()=>{if(!tm)return[];let e="project"===tm.kind?t4.get(N(tm.project))??[]:ni.flatMap(e=>e.sessions),t=new Set;return e.filter(e=>!(e.transient||t.has(e.id))&&(t.add(e.id),!0))})(),nc=nd.filter(e=>!tt.has(e.id)),nu=e=>{let t=new Set;for(let n of e)n.transient||tt.has(n.id)||t.has(n.id)||t.add(n.id);return t.size},np=void 0!==m&&f;return(0,r.jsxs)("div",{className:"session-navigator",tabIndex:-1,style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden",outline:"none"},children:[eF&&(0,r.jsx)(B?K:H,{busy:eH,error:eD,onCancel:()=>{e_(!1),eO(null)},onSelect:e=>void tA(e)}),tm&&(0,r.jsx)(eo,{scope:tm,eligible:nc.length,runningExcluded:nd.length-nc.length,busy:tg,error:tv,onCancel:ty,onConfirm:()=>void tw(nc)}),(0,r.jsx)("div",{className:"session-navigator-header",style:{padding:"4px 10px",borderBottom:"1px solid var(--border)",flexShrink:0},children:(0,r.jsxs)("div",{className:"session-navigator-titlebar",style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[(0,r.jsx)(ea,{}),(0,r.jsxs)("div",{style:{display:"flex",gap:12},children:[(0,r.jsx)("button",{className:"navigator-icon-action",onClick:()=>t_(),disabled:!F,style:{display:"flex",alignItems:"center",justifyContent:"center",background:"var(--bg-hover)",border:"1px solid var(--border)",color:F?"var(--text-muted)":"var(--text-dim)",cursor:F?"pointer":"not-allowed",width:32,height:32,padding:0,borderRadius:7,fontSize:12,flexShrink:0,transition:"background 0.12s, color 0.12s, border-color 0.12s"},title:F?b("sidebar.newSessionTitle",{path:F}):b("sidebar.selectProject"),"aria-label":F?b("sidebar.newSessionTitle",{path:F}):b("sidebar.selectProject"),onMouseEnter:e=>{F&&(e.currentTarget.style.background="var(--bg-selected)",e.currentTarget.style.color="var(--accent)")},onMouseLeave:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color=F?"var(--text-muted)":"var(--text-dim)",e.currentTarget.style.borderColor="var(--border)"},children:(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"6",y1:"1",x2:"6",y2:"11"}),(0,r.jsx)("line",{x1:"1",y1:"6",x2:"11",y2:"6"})]})}),(0,r.jsx)("button",{className:`navigator-icon-action${e9?" is-success":""}`,onClick:()=>tp(!1,!0),style:{display:"flex",alignItems:"center",justifyContent:"center",background:e9?"rgba(74,222,128,0.18)":"var(--bg-hover)",border:`1px solid ${e9?"rgba(74,222,128,0.4)":"var(--border)"}`,color:e9?"#4ade80":"var(--text-muted)",cursor:"pointer",width:32,height:32,borderRadius:7,padding:0,flexShrink:0,transition:"background 0.3s, color 0.3s, border-color 0.3s"},onMouseEnter:e=>{e9||(e.currentTarget.style.background="var(--bg-selected)",e.currentTarget.style.color="var(--accent)")},onMouseLeave:e=>{e9||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text-muted)",e.currentTarget.style.borderColor="var(--border)")},title:b("sidebar.refresh"),children:e9?(0,r.jsx)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"var(--success)",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}):(0,r.jsxs)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}),(0,r.jsx)("path",{d:"M3 3v5h5"})]})})]})]})}),B&&!np&&(0,r.jsx)("button",{type:"button",className:"navigator-cloud-project",onClick:tz,style:{margin:"10px 12px 0",minHeight:44,flexShrink:0,border:"1px solid var(--border)",borderRadius:7,background:"var(--bg-panel)",color:"var(--text)",fontSize:13,fontWeight:600,cursor:"pointer"},children:b("cloudProjects.launch")}),(0,r.jsxs)("div",{className:"navigator-mode-bar",style:{display:"flex",alignItems:"center",gap:6,minHeight:42,padding:"6px 8px 4px",flexShrink:0},children:[(0,r.jsxs)("div",{className:"navigator-mode-switcher",role:"toolbar","aria-label":b("navigator.toolbar"),style:{display:"flex",alignItems:"center",gap:2,flex:1,minWidth:0,padding:2,border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-panel)"},children:[k.map(e=>{let t="projects"===e?b("sidebar.projects"):b("navigator.priority"),n=!np&&J===e;return(0,r.jsx)("button",{type:"button","aria-label":b("navigator.view",{label:t}),"aria-pressed":n,"aria-controls":`navigator-${e}-panel`,"data-navigator-mode":e,onClick:()=>{tN(e),np&&g?.(!1)},style:{minWidth:0,minHeight:26,flex:1,padding:"3px 4px",border:"none",borderRadius:4,background:n?"var(--bg-selected)":"transparent",color:n?"var(--text)":"var(--text-dim)",cursor:"pointer",fontSize:10,fontWeight:n?600:500,whiteSpace:"nowrap"},children:t},e)}),void 0!==m&&(0,r.jsx)("button",{type:"button","aria-label":b("navigator.view",{label:v("translator.tab")}),"aria-pressed":np,"aria-controls":"navigator-translator-panel","data-navigator-mode":"translator",onClick:()=>g?.(!np),style:{minWidth:0,minHeight:26,flex:1,padding:"3px 4px",border:"none",borderRadius:4,background:np?"var(--bg-selected)":"transparent",color:np?"var(--text)":"var(--text-dim)",cursor:"pointer",fontSize:10,fontWeight:np?600:500,whiteSpace:"nowrap"},children:v("translator.tab")})]}),!np&&"projects"===J&&(0,r.jsx)("button",{type:"button",onClick:()=>eC(e=>!e),disabled:!tX,title:b("sidebar.projectShowHidden"),"aria-label":b("sidebar.projectShowHidden"),"aria-pressed":eS,style:{display:"flex",alignItems:"center",justifyContent:"center",width:26,height:26,padding:0,border:"none",borderRadius:5,background:eS?"var(--bg-selected)":"transparent",color:eS?"var(--accent)":"var(--text-dim)",cursor:tX?"pointer":"default",opacity:tX?1:.45,flexShrink:0},children:(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M2.5 12s3.5-6 9.5-6 9.5 6 9.5 6-3.5 6-9.5 6-9.5-6-9.5-6Z"}),(0,r.jsx)("circle",{cx:"12",cy:"12",r:"2.5"}),!eS&&(0,r.jsx)("path",{d:"m4 4 16 16"})]})}),!np&&"projects"===J&&(0,r.jsx)("button",{className:"navigator-add-project",type:"button",onClick:tz,title:b("sidebar.addProject"),"aria-label":b("sidebar.addProject"),style:{display:"flex",alignItems:"center",justifyContent:"center",width:28,height:28,padding:0,border:"none",borderRadius:6,background:"var(--bg-hover)",color:"var(--text-muted)",cursor:"pointer",transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)"},onMouseLeave:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text-muted)"},children:(0,r.jsxs)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M3 7.5A2.5 2.5 0 0 1 5.5 5H9l2 2h7.5A2.5 2.5 0 0 1 21 9.5v7A2.5 2.5 0 0 1 18.5 19h-13A2.5 2.5 0 0 1 3 16.5v-9Z"}),(0,r.jsx)("path",{d:"M15.5 10.5v5M13 13h5"})]})})]}),np&&m,!np&&"projects"===J&&(0,r.jsxs)("label",{className:"navigator-search",style:{position:"relative",display:"block",margin:"0 8px 8px"},children:[(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",style:{position:"absolute",left:10,top:"50%",transform:"translateY(-50%)",color:"var(--text-dim)",pointerEvents:"none"},children:[(0,r.jsx)("circle",{cx:"11",cy:"11",r:"7"}),(0,r.jsx)("path",{d:"m20 20-3.5-3.5"})]}),(0,r.jsx)("input",{className:"navigator-search-input",type:"search",value:q,onChange:e=>V(e.target.value),onKeyDown:e=>{"Escape"===e.key&&(e.preventDefault(),V(""),e.currentTarget.blur())},placeholder:b("sidebar.searchProjectsAndSessions"),"aria-label":b("sidebar.searchProjectsAndSessions"),style:{width:"100%",height:34,padding:"0 10px 0 32px",border:"1px solid var(--border)",borderRadius:7,outline:"none",background:"var(--bg-hover)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:11}})]}),!np&&"projects"===J&&(0,r.jsxs)("div",{id:"navigator-projects-panel",className:"navigator-session-list",style:{flex:"1 1 auto",overflowY:"auto",minHeight:80,padding:"0 6px 10px"},children:[(L||!ek)&&(0,r.jsx)("div",{style:{padding:"12px 8px",color:"var(--text-muted)",fontSize:12},children:b("sidebar.loading")}),z&&(0,r.jsx)("div",{style:{padding:"10px 8px",color:"var(--danger)",fontSize:12},children:z}),eA&&(0,r.jsx)("div",{style:{padding:"10px 8px",color:"var(--danger)",fontSize:12},children:eA}),!L&&ek&&!z&&0===t3.length&&(0,r.jsx)("div",{style:{padding:"12px 8px",color:"var(--text-muted)",fontSize:12},children:t6?b("sidebar.noMatchingProjects"):b("sidebar.noSessions")}),!L&&ek&&!z&&nn.map(t=>{let n,i,a;if("temporary"===t.kind)return(0,r.jsx)("div",{className:"navigator-project-group",children:(0,r.jsxs)("button",{type:"button",className:"navigator-project-row","aria-expanded":nt,title:b("sidebar.temporaryProjects"),onClick:()=>eI(e=>!e),style:{display:"flex",alignItems:"center",gap:6,width:"100%",minHeight:34,padding:"0 6px 0 2px",border:"none",background:"transparent",color:"var(--text-muted)",cursor:"pointer",textAlign:"left",fontSize:"var(--seed-font-size-t2-static)",fontWeight:600},children:[(0,r.jsx)("span",{style:{display:"flex",alignItems:"center",justifyContent:"center",width:24,height:28,flexShrink:0,color:"var(--text-dim)"},children:(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{transform:nt?"rotate(0deg)":"rotate(-90deg)",transition:"transform 0.12s"},children:(0,r.jsx)("polyline",{points:"2.5 4 6 7.5 9.5 4"})})}),(0,r.jsx)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:b("sidebar.temporaryProjects")}),(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:10,flexShrink:0},children:t9.length}),ef(ne,b)]})},"navigator-temporary-projects");let{project:s,key:l,name:o,sessions:d,hidden:c}=t.group,u=l===tV,p=nr.has(o.toLowerCase())&&et((i=Math.max((n=s.trim().replace(/[\\/]+$/,"")).lastIndexOf("\\"),n.lastIndexOf("/")))<=0?"":n.slice(0,i),D)||null,h=!eh.has(s)&&!t6,m=ei.has(s),f=eT===s,g=tZ.indexOf(s),x=eE||t8||g<=0,v=eE||t8||g>=tZ.length-1,y=function(e){let t=new Map;for(let n of e)t.set(n.id,{session:n,children:[]});let n=new Map;for(let t of e)t.parentSessionId&&n.set(t.id,t.parentSessionId);let r=[];for(let e of t.values()){let i=function(e){let r=n.get(e),i=new Set;for(;r&&!i.has(r);){if(i.add(r),t.has(r))return r;r=n.get(r)}return null}(e.session.id);i?t.get(i).children.push(e):r.push(e)}let i=e=>{e.sort((e,t)=>t.session.modified.localeCompare(e.session.modified)),e.forEach(e=>i(e.children))};return i(r),r}(m?d:d.slice(0,5)),k=d.length>5;return(0,r.jsxs)("section",{className:"navigator-project-group",style:{marginBottom:h?3:9},children:[(0,r.jsxs)("div",{className:`navigator-project-row${u?" is-selected":""}`,ref:ev===s?e5:void 0,onMouseEnter:()=>ex(s),onMouseLeave:()=>ex(e=>e===s&&ev!==s?null:e),style:{display:"flex",alignItems:"center",minHeight:34,position:"relative",borderRadius:6,background:u?"var(--bg-hover)":"transparent",opacity:c?.55:1},children:[(0,r.jsx)("button",{type:"button",onClick:()=>tq(s),title:h?b("sidebar.expandProject"):b("sidebar.collapseProject"),"aria-label":h?b("sidebar.expandProject"):b("sidebar.collapseProject"),"aria-expanded":!h,style:{display:"flex",alignItems:"center",justifyContent:"center",width:24,height:28,marginLeft:2,padding:0,border:"none",background:"transparent",color:"var(--text-dim)",cursor:"pointer",flexShrink:0},children:(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{transform:h?"rotate(-90deg)":"rotate(0deg)",transition:"transform 0.12s"},children:(0,r.jsx)("polyline",{points:"2.5 4 6 7.5 9.5 4"})})}),f?(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,flex:1,minWidth:0,height:34,padding:"0 4px"},children:[(0,r.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0,color:"var(--accent)"},children:(0,r.jsx)("path",{d:"M3 7.5A2.5 2.5 0 0 1 5.5 5H9l2 2h7.5A2.5 2.5 0 0 1 21 9.5v7A2.5 2.5 0 0 1 18.5 19h-13A2.5 2.5 0 0 1 3 16.5v-9Z"})}),(0,r.jsx)("input",{ref:e8,value:e$,onChange:e=>eR(e.target.value),onBlur:()=>void t1(s),onKeyDown:e=>{"Enter"===e.key?(e.preventDefault(),e.currentTarget.blur()):"Escape"===e.key&&(e.preventDefault(),e3.current=!0,eM(null))},"aria-label":b("sidebar.projectAlias"),style:{flex:1,minWidth:0,height:24,padding:"2px 6px",border:"1px solid var(--accent)",borderRadius:5,outline:"none",background:"var(--bg)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:12,fontWeight:600}})]}):(0,r.jsxs)("button",{className:"navigator-project-name",type:"button",onClick:()=>_(s),title:s,style:{display:"flex",alignItems:"center",gap:8,flex:1,minWidth:0,height:34,padding:"0 4px",border:"none",background:"transparent",color:u?"var(--text)":"var(--text-muted)",cursor:"pointer",textAlign:"left",fontSize:12.5,fontWeight:u?600:500},children:[(0,r.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0,color:u?"var(--accent)":"var(--text-dim)"},children:(0,r.jsx)("path",{d:"M3 7.5A2.5 2.5 0 0 1 5.5 5H9l2 2h7.5A2.5 2.5 0 0 1 21 9.5v7A2.5 2.5 0 0 1 18.5 19h-13A2.5 2.5 0 0 1 3 16.5v-9Z"})}),(0,r.jsx)("span",{style:{flexShrink:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:o}),null===p?null:(0,r.jsx)("span",{style:{flexShrink:2,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:10},children:p}),ef(t5.get(l),b)]}),(0,r.jsx)("button",{type:"button",onClick:()=>t_(s),title:b("sidebar.newSessionTitle",{path:s}),"aria-label":b("sidebar.newSessionTitle",{path:s}),style:{display:"flex",alignItems:"center",justifyContent:"center",width:28,height:28,padding:0,border:"none",borderRadius:5,background:"transparent",color:"var(--text-dim)",cursor:"pointer",opacity:w||eg===s?1:0,pointerEvents:w||eg===s?"auto":"none",transition:"opacity 0.12s, background 0.12s, color 0.12s",flexShrink:0},onFocus:()=>ex(s),onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-selected)",e.currentTarget.style.color="var(--accent)"},onMouseLeave:e=>{e.currentTarget.style.background="transparent",e.currentTarget.style.color="var(--text-dim)"},children:(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"6",y1:"1.5",x2:"6",y2:"10.5"}),(0,r.jsx)("line",{x1:"1.5",y1:"6",x2:"10.5",y2:"6"})]})}),(0,r.jsxs)("div",{style:{position:"static",flexShrink:0},children:[(0,r.jsx)("button",{type:"button",onClick:()=>{eb(ev===s?null:s),eV(!1),eG(!1),eQ(null),u||_(s)},title:b("sidebar.projectActions"),"aria-label":b("sidebar.projectActions"),"aria-expanded":ev===s,style:{display:"flex",alignItems:"center",justifyContent:"center",width:26,height:26,marginRight:3,padding:0,border:"none",borderRadius:5,background:ev===s?"var(--bg-selected)":"transparent",color:u&&ns&&!ns.isMain?"var(--accent)":"var(--text-dim)",cursor:"pointer",opacity:w||eg===s||ev===s?1:0,pointerEvents:w||eg===s||ev===s?"auto":"none",transition:"opacity 0.12s, background 0.12s, color 0.12s"},onFocus:()=>ex(s),children:(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"currentColor","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"3",cy:"7",r:"1.1"}),(0,r.jsx)("circle",{cx:"7",cy:"7",r:"1.1"}),(0,r.jsx)("circle",{cx:"11",cy:"7",r:"1.1"})]})}),(0,r.jsxs)(er,{open:ev===s,style:{position:"absolute",top:"calc(100% + 4px)",right:3,width:"min(260px, calc(100vw - 24px))",zIndex:110,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:8,boxShadow:"var(--shadow-float)",boxSizing:"border-box",overflow:"hidden"},children:[na&&eU&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("button",{type:"button",onClick:()=>eV(e=>!e),title:ns?b("sidebar.switchWorktreeTitle",{path:ns.path}):b("sidebar.switchWorktree"),"aria-label":b("sidebar.worktrees"),"aria-expanded":eK,style:{display:"flex",alignItems:"center",gap:8,width:"100%",minHeight:34,padding:"0 10px",border:"none",borderBottom:eK?"1px solid var(--border)":"none",background:eK?"var(--bg-selected)":"transparent",color:"var(--text-muted)",cursor:"pointer",textAlign:"left",fontSize:11},children:[(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"6",y1:"3",x2:"6",y2:"15"}),(0,r.jsx)("circle",{cx:"18",cy:"6",r:"3"}),(0,r.jsx)("circle",{cx:"6",cy:"18",r:"3"}),(0,r.jsx)("path",{d:"M18 9a9 9 0 0 1-9 9"})]}),(0,r.jsx)("span",{style:{flex:1},children:b("sidebar.worktrees")}),(0,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"4 2.5 8 6 4 9.5"})})]}),(0,r.jsxs)(er,{open:eK,style:{position:"static",width:"auto",zIndex:100,background:"var(--bg)",border:"none",borderTop:"1px solid var(--border)",borderRadius:0,boxShadow:"none",boxSizing:"border-box",overflow:"hidden"},children:[nl&&(0,r.jsx)("div",{style:{padding:"6px 8px",borderBottom:"1px solid var(--border)"},children:(0,r.jsx)("input",{value:eP,onChange:e=>eW(e.target.value),onKeyDown:e=>{"Escape"===e.key&&(eW(""),eV(!1))},placeholder:b("sidebar.filterWorktrees"),autoFocus:!0,style:{width:"100%",fontSize:11,fontFamily:"var(--font-mono)",padding:"5px 8px",border:"1px solid var(--border)",borderRadius:5,outline:"none",background:"var(--bg)",color:"var(--text)",boxSizing:"border-box"}})}),(0,r.jsxs)("div",{style:{maxHeight:"min(40vh, 300px)",overflowY:"auto"},children:[no.map(e=>{let t=e.path===F||e.isMain&&!eU.worktrees.some(e=>e.path===F);return e2===e.path?(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6,padding:"7px 10px",borderBottom:"1px solid var(--border)",background:"rgba(239,68,68,0.06)"},children:[(0,r.jsx)("span",{style:{flex:1,fontSize:11,color:"var(--text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:b("sidebar.forceRemoveCheckout")}),(0,r.jsx)("button",{onClick:()=>void tW(e.path,!0),disabled:e0,style:{padding:"3px 9px",background:"var(--danger)",border:"none",borderRadius:5,color:"var(--bg)",fontSize:11,fontWeight:600,cursor:"pointer",flexShrink:0},children:b("sidebar.force")}),(0,r.jsx)("button",{onClick:()=>e4(null),style:{padding:"3px 9px",background:"var(--bg-hover)",border:"1px solid var(--border)",borderRadius:5,color:"var(--text-muted)",fontSize:11,cursor:"pointer",flexShrink:0},children:b("sidebar.cancel")})]},e.path):(0,r.jsxs)("div",{className:"wt-row",style:{display:"flex",alignItems:"center",borderBottom:"1px solid var(--border)"},children:[(0,r.jsxs)("button",{onClick:()=>{_(e.path),eV(!1),eQ(null),eW("")},title:e.path,style:{flex:1,minWidth:0,display:"flex",alignItems:"center",gap:7,padding:"8px 10px",background:"var(--bg)",border:"none",color:t?"var(--text)":"var(--text-muted)",cursor:"pointer",textAlign:"left",fontSize:11,fontFamily:"var(--font-mono)"},children:[t?(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,r.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,r.jsx)("span",{style:{width:10,flexShrink:0}}),(0,r.jsx)(en,{text:e.branch??et(e.path,D),style:{flex:1}}),e.isMain&&(0,r.jsx)("span",{style:{flexShrink:0,color:"var(--text-dim)",fontSize:10},children:b("sidebar.main")})]}),!e.isMain&&(0,r.jsx)("button",{onClick:()=>void tW(e.path,!1),disabled:e0,title:b("sidebar.removeWorktreeTitle",{path:e.path}),style:{display:"flex",alignItems:"center",justifyContent:"center",width:34,height:28,padding:0,marginRight:4,background:"none",border:"none",color:"var(--text-dim)",cursor:"pointer",borderRadius:5,flexShrink:0,transition:"color 0.12s, background 0.12s"},onMouseEnter:e=>{e.currentTarget.style.color="#ef4444",e.currentTarget.style.background="rgba(239,68,68,0.08)"},onMouseLeave:e=>{e.currentTarget.style.color="var(--text-dim)",e.currentTarget.style.background="none"},children:(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("polyline",{points:"3 6 5 6 21 6"}),(0,r.jsx)("path",{d:"M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"}),(0,r.jsx)("path",{d:"M10 11v6M14 11v6"}),(0,r.jsx)("path",{d:"M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2"})]})})]},e.path)}),nl&&0===no.length&&eP.trim()&&(0,r.jsx)("div",{style:{padding:"8px 10px",fontSize:11,color:"var(--text-dim)"},children:b("sidebar.noMatchingWorktrees")})]}),eJ?(0,r.jsxs)("div",{style:{padding:"6px 8px"},children:[(0,r.jsx)("input",{ref:e6,value:eY,onChange:e=>{eZ(e.target.value),eQ(null)},onKeyDown:e=>{"Enter"===e.key&&(e.preventDefault(),tP()),"Escape"===e.key&&(eG(!1),eZ(""),eQ(null))},placeholder:b("sidebar.branchName"),style:{width:"100%",fontSize:11,fontFamily:"var(--font-mono)",padding:"5px 8px",border:"1px solid var(--accent)",borderRadius:5,outline:"none",background:"var(--bg)",color:"var(--text)",boxSizing:"border-box"}}),(0,r.jsxs)("div",{style:{display:"flex",gap:5,marginTop:5},children:[(0,r.jsx)("button",{onClick:()=>void tP(),disabled:e0||!eY.trim(),style:{flex:1,padding:"4px 0",background:"var(--accent)",border:"none",borderRadius:5,color:"var(--bg)",fontSize:11,fontWeight:600,cursor:e0||!eY.trim()?"not-allowed":"pointer",opacity:e0||!eY.trim()?.65:1},children:e0?b("sidebar.creating"):b("sidebar.create")}),(0,r.jsx)("button",{onClick:()=>{eG(!1),eZ(""),eQ(null)},style:{flex:1,padding:"4px 0",background:"var(--bg-hover)",border:"1px solid var(--border)",borderRadius:5,color:"var(--text-muted)",fontSize:11,cursor:"pointer"},children:b("sidebar.cancel")})]})]}):(0,r.jsxs)("button",{onClick:e=>{e.stopPropagation(),eG(!0),eQ(null),setTimeout(()=>e6.current?.focus(),0)},title:b("sidebar.createWorktreeTitle"),style:{display:"flex",alignItems:"center",gap:7,width:"100%",padding:"8px 10px",background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",textAlign:"left",fontSize:11},children:[(0,r.jsxs)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.1",strokeLinecap:"round",style:{flexShrink:0},children:[(0,r.jsx)("line",{x1:"5",y1:"1",x2:"5",y2:"9"}),(0,r.jsx)("line",{x1:"1",y1:"5",x2:"9",y2:"5"})]}),(0,r.jsx)("span",{children:b("sidebar.newWorktree")})]}),eX&&(0,r.jsx)("div",{style:{padding:"5px 10px 8px",color:"var(--danger)",fontSize:11,lineHeight:1.35,overflowWrap:"anywhere"},children:eX})]})]}),(0,r.jsxs)("button",{type:"button",disabled:eE,onClick:()=>{let e;return e=tJ.get(N(s))?.alias??"",void(e3.current=!1,ez(null),eR(e),eM(s),tQ())},style:{display:"flex",alignItems:"center",gap:8,width:"100%",minHeight:34,padding:"0 10px",border:"none",borderTop:"1px solid var(--border)",background:"transparent",color:"var(--text-muted)",cursor:eE?"default":"pointer",textAlign:"left",fontSize:11,opacity:eE?.55:1},children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"m4 20 4.5-1 10-10a2.1 2.1 0 0 0-3-3l-10 10L4 20Z"}),(0,r.jsx)("path",{d:"m13.5 8 3 3"})]}),b(tJ.get(N(s))?.alias?"sidebar.projectAliasEdit":"sidebar.projectAlias")]}),(0,r.jsxs)("button",{type:"button",disabled:x,title:t8?b("sidebar.projectMoveDisabledWhileFiltering"):void 0,onClick:()=>void t2(s,-1),style:{display:"flex",alignItems:"center",gap:8,width:"100%",minHeight:34,padding:"0 10px",border:"none",background:"transparent",color:"var(--text-muted)",cursor:x?"default":"pointer",textAlign:"left",fontSize:11,opacity:x?.55:1},children:[(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m6 15 6-6 6 6"})}),b("sidebar.projectMoveUp")]}),(0,r.jsxs)("button",{type:"button",disabled:v,title:t8?b("sidebar.projectMoveDisabledWhileFiltering"):void 0,onClick:()=>void t2(s,1),style:{display:"flex",alignItems:"center",gap:8,width:"100%",minHeight:34,padding:"0 10px",border:"none",background:"transparent",color:"var(--text-muted)",cursor:v?"default":"pointer",textAlign:"left",fontSize:11,opacity:v?.55:1},children:[(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m6 9 6 6 6-6"})}),b("sidebar.projectMoveDown")]}),(0,r.jsxs)("button",{type:"button",disabled:eE,onClick:()=>void t0(s,!c),style:{display:"flex",alignItems:"center",gap:8,width:"100%",minHeight:34,padding:"0 10px",border:"none",background:"transparent",color:"var(--text-muted)",cursor:eE?"default":"pointer",textAlign:"left",fontSize:11,opacity:eE?.55:1},children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M2.5 12s3.5-6 9.5-6 9.5 6 9.5 6-3.5 6-9.5 6-9.5-6-9.5-6Z"}),(0,r.jsx)("circle",{cx:"12",cy:"12",r:"2.5"}),!c&&(0,r.jsx)("path",{d:"m4 4 16 16"})]}),b(c?"sidebar.projectUnhide":"sidebar.projectHide")]}),(a=0===nu(t4.get(l)??[])||tg,(0,r.jsxs)("button",{type:"button",disabled:a,onClick:()=>{tQ(),tb(null),tf({kind:"project",project:s,label:o})},style:{display:"flex",alignItems:"center",gap:8,width:"100%",minHeight:34,padding:"0 10px",border:"none",borderTop:"1px solid var(--border)",background:"transparent",color:"var(--text-muted)",cursor:a?"default":"pointer",textAlign:"left",fontSize:11,opacity:a?.55:1},children:[(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M4 7h16M9 7V5h6v2M6 7l1 13h10l1-13"})}),b("sidebar.clearProjectSessions")]}))]})]})]}),!h&&0===d.length&&u&&(0,r.jsx)("div",{style:{padding:"6px 12px 7px 32px",color:"var(--text-dim)",fontSize:11},children:b("sidebar.noSessions")}),!h&&y.length>0&&(0,r.jsx)("div",{style:{paddingLeft:12},children:y.map(t=>(0,r.jsx)(ep,{node:t,selectedSessionId:e,runningSessionIds:tt,unreadSessionIds:tr,pinnedSessionIds:ta,onSelectSession:tF,onTogglePinnedSession:tI,onRenamed:tp,onSessionDeleted:th,onSessionArchived:tS,depth:0},t.session.id))}),!h&&k&&(0,r.jsx)("button",{type:"button",onClick:()=>{ed(e=>{let t=new Set(e);return t.has(s)?t.delete(s):t.add(s),t})},style:{display:"block",margin:"3px 0 3px 32px",padding:"5px 8px",border:"none",background:"transparent",color:"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left"},children:m?b("sidebar.showLess"):b("sidebar.showMore")})]},s)})]}),!np&&(0,r.jsx)(eu,{refreshKey:tk,selectedSessionId:e,onSelectSession:tF,onRestored:tS}),!np&&"priority"===J&&(0,r.jsxs)("div",{id:"navigator-priority-panel",style:{flex:"1 1 auto",minHeight:80,overflowY:"auto",padding:"0 6px 10px"},children:[L&&(0,r.jsx)("div",{style:{padding:"12px 8px",color:"var(--text-muted)",fontSize:12},children:b("sidebar.loading")}),z&&(0,r.jsx)("div",{role:"alert",style:{padding:"10px 8px",color:"var(--danger)",fontSize:12},children:z}),!L&&!z&&(x=nu(ni.flatMap(e=>e.sessions)),(0,r.jsxs)("div",{style:{display:"flex",justifyContent:"space-between",gap:8,padding:"8px 2px 2px"},children:[(0,r.jsx)("button",{type:"button",disabled:tD,onClick:()=>void tU(),title:b("sidebar.newScratchSessionTitle"),style:ee(tD,w),children:b("sidebar.newScratchSession")}),ni.length>0&&(0,r.jsx)("button",{type:"button",disabled:0===x||tg,onClick:()=>{tb(null),tf({kind:"priority"})},style:ee(0===x||tg,w),children:b("sidebar.clearPriorityList")})]})),tH&&(0,r.jsx)("div",{role:"alert",style:{padding:"6px 8px",color:"var(--danger)",fontSize:12},children:tH}),!L&&!z&&0===ni.length&&(0,r.jsx)("div",{style:{padding:"12px 8px",color:"var(--text-muted)",fontSize:12},children:b("sidebar.noSessions")}),!L&&!z&&ni.map((t,n)=>(0,r.jsxs)("section",{"aria-labelledby":`priority-group-${t.key}`,children:[(0,r.jsx)("h2",{id:`priority-group-${t.key}`,style:{margin:0,padding:0===n?"2px 8px 4px":"14px 8px 4px",color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontWeight:600},children:t.label}),t.sessions.map(t=>(0,r.jsx)(ec,{session:t,selected:t.id===e,running:tt.has(t.id),unread:tr.has(t.id),pinned:ta.has(t.id),onSelect:tF,onTogglePin:tI},t.id))]},t.key))]})]})}function eo({scope:e,eligible:t,runningExcluded:n,busy:a,error:s,onCancel:l,onConfirm:o}){let{t:d}=(0,R.s)(),c=a||0===t,u=(0,i.useRef)(null),p=(0,i.useRef)(null),h=(0,i.useRef)(a);h.current=a;let m=(0,i.useRef)(l);return m.current=l,(0,i.useEffect)(()=>{let e=u.current;if(!e)return;let t=document.activeElement,n=t instanceof HTMLElement&&t!==document.body&&t!==document.documentElement&&!e.contains(t)?t:null;(p.current??e).focus();let r=t=>{if("Escape"===t.key){if(h.current)return;t.preventDefault(),m.current();return}if("Tab"!==t.key)return;let n=Array.from(e.querySelectorAll('a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])')).filter(e=>e.getClientRects().length>0),r=document.activeElement;if(0===n.length){t.preventDefault(),e.focus();return}let i=n[0],a=n[n.length-1];t.shiftKey&&(r===i||!e.contains(r))?(t.preventDefault(),a.focus()):t.shiftKey||r!==a&&e.contains(r)||(t.preventDefault(),i.focus())};return e.addEventListener("keydown",r),()=>{e.removeEventListener("keydown",r);let t=n?.isConnected?n:e.closest(".session-navigator");t?.focus()}},[]),(0,r.jsx)("div",{role:"presentation",style:{position:"fixed",inset:0,zIndex:1100,display:"flex",alignItems:"center",justifyContent:"center",padding:16,background:"var(--scrim)"},onClick:e=>{a||e.target!==e.currentTarget||l()},children:(0,r.jsxs)("div",{ref:u,role:"alertdialog","aria-modal":"true","aria-labelledby":"bulk-clear-title","aria-describedby":"bulk-clear-body",tabIndex:-1,style:{width:420,maxWidth:"100%",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",background:"var(--bg-panel)",boxShadow:"var(--shadow-float)",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{padding:"18px 18px 14px"},children:[(0,r.jsx)("div",{id:"bulk-clear-title",style:{color:"var(--text)",fontSize:"var(--seed-font-size-t4-static)",fontWeight:600},children:d("sidebar.clearSessionsTitle")}),(0,r.jsxs)("div",{id:"bulk-clear-body",style:{marginTop:8,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.6,overflowWrap:"anywhere"},children:["project"===e.kind?d("sidebar.clearSessionsProjectBody",{project:e.label,count:t}):d("sidebar.clearSessionsPriorityBody",{count:t}),n>0&&(0,r.jsx)("div",{style:{marginTop:6},children:d("sidebar.clearSessionsRunningExcluded",{count:n})}),0===t&&(0,r.jsx)("div",{style:{marginTop:6},children:d("sidebar.clearSessionsNone")})]}),s&&(0,r.jsx)("div",{role:"alert",style:{marginTop:10,color:"var(--danger)",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.5,overflowWrap:"anywhere"},children:s})]}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",justifyContent:"flex-end",gap:8,padding:"12px 18px",borderTop:"1px solid var(--border)"},children:[(0,r.jsx)("button",{ref:p,type:"button",onClick:l,disabled:a,style:{minHeight:36,padding:"0 12px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"transparent",color:"var(--text-muted)",cursor:a?"default":"pointer",fontSize:"var(--seed-font-size-t3-static)"},children:d("sidebar.clearSessionsCancel")}),(0,r.jsx)("button",{type:"button",onClick:o,disabled:c,"aria-busy":a,style:{minHeight:36,padding:"0 14px",border:"1px solid var(--danger)",borderRadius:"var(--radius-control)",background:"transparent",color:c?"var(--text-dim)":"var(--danger)",cursor:c?"default":"pointer",fontSize:"var(--seed-font-size-t3-static)",fontWeight:600},children:d(a?"sidebar.clearSessionsBusy":"sidebar.clearSessionsConfirm")})]})]})})}function ed({filled:e=!1}){return(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:e?"currentColor":"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M12 17v5"}),(0,r.jsx)("path",{d:"M5 17h14"}),(0,r.jsx)("path",{d:"M6 3h12l-1 8 2 3H5l2-3-1-8z"})]})}function ec({session:e,selected:t,running:n,unread:i,pinned:a,onSelect:s,onTogglePin:l}){let{t:o}=(0,R.s)(),d=(e.name||e.firstMessage||e.id.slice(0,8)).replace(/\s+/g," ").trim(),c=e.cwd.split(/[\\/]/).filter(Boolean).at(-1)??"";return(0,r.jsxs)("div",{className:`priority-session-row${t?" is-selected":""}${n?" is-running":""}${i?" is-unread":""}`,style:{display:"flex",alignItems:"stretch",borderRadius:5,background:t?"var(--bg-selected)":"transparent"},children:[(0,r.jsxs)("button",{type:"button","aria-current":t?"page":void 0,onClick:()=>s(e),title:`${d}
1
+ (self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[9575],{13004:e=>{e.exports={backdrop:"SettingsConfig_backdrop__i6KYG",window:"SettingsConfig_window__m7dcs",sidebar:"SettingsConfig_sidebar__vEMEr",brand:"SettingsConfig_brand__DlYlu",eyebrow:"SettingsConfig_eyebrow__uTa5R",title:"SettingsConfig_title__DWTnA",context:"SettingsConfig_context__N0fl0",searchWrap:"SettingsConfig_searchWrap___PWrc",searchIcon:"SettingsConfig_searchIcon__8_YYE",search:"SettingsConfig_search__DUhSs",nav:"SettingsConfig_nav__V8P9S",navLabel:"SettingsConfig_navLabel__M1wMP",navButton:"SettingsConfig_navButton__CUOqu",navIcon:"SettingsConfig_navIcon__Wagpr",closeRail:"SettingsConfig_closeRail__PW3pT",closeButton:"SettingsConfig_closeButton__5y_6F",content:"SettingsConfig_content__n_a5Z",scrollContent:"SettingsConfig_scrollContent__03BsO",contentHeader:"SettingsConfig_contentHeader__tNmzv",contentTitle:"SettingsConfig_contentTitle__oiHOO",contentDescription:"SettingsConfig_contentDescription___l2QU",reloadNotice:"SettingsConfig_reloadNotice__enzeE",settingsBody:"SettingsConfig_settingsBody__QRFVu",group:"SettingsConfig_group__JQ_dy",groupTitle:"SettingsConfig_groupTitle__0SrM9",settingRow:"SettingsConfig_settingRow__Jy73r",settingLabel:"SettingsConfig_settingLabel__n8vtU",settingDescription:"SettingsConfig_settingDescription__TGWfP",settingControl:"SettingsConfig_settingControl__oz5Gn",select:"SettingsConfig_select__A5aGy",textInput:"SettingsConfig_textInput___NjZ2",jsonEditor:"SettingsConfig_jsonEditor__yTYDb",numberInput:"SettingsConfig_numberInput__TVVeJ",switch:"SettingsConfig_switch__5UYqz",multiSelect:"SettingsConfig_multiSelect__PTjyr",choice:"SettingsConfig_choice__Os8WR",choiceToggle:"SettingsConfig_choiceToggle__lyl75",reorder:"SettingsConfig_reorder__JR6tX",error:"SettingsConfig_error__j6wEj",saveState:"SettingsConfig_saveState__1tIL4",themeGrid:"SettingsConfig_themeGrid__7Lw8A",themeCard:"SettingsConfig_themeCard__DQFsT",themePreview:"SettingsConfig_themePreview__QzqXK",themePreviewBar:"SettingsConfig_themePreviewBar__ZbchX",themePreviewPanel:"SettingsConfig_themePreviewPanel__YN9ty",themePreviewLine:"SettingsConfig_themePreviewLine__jP0qg",themeCardBody:"SettingsConfig_themeCardBody__xiOe6",themeCardHeader:"SettingsConfig_themeCardHeader__YPRN2",themeSlot:"SettingsConfig_themeSlot__vGn9a",themeActive:"SettingsConfig_themeActive__PNmdk",mcpLayout:"SettingsConfig_mcpLayout__ek_Fi",mcpList:"SettingsConfig_mcpList__gZ9_o",scopeTabs:"SettingsConfig_scopeTabs__9bybS",scopeButton:"SettingsConfig_scopeButton__d4XPe",serverRows:"SettingsConfig_serverRows__JSJy0",serverRow:"SettingsConfig_serverRow__6gJdE",serverSelect:"SettingsConfig_serverSelect__cuYFx",serverToggle:"SettingsConfig_serverToggle__X5N_o",serverName:"SettingsConfig_serverName__lbfcK",sourceBadge:"SettingsConfig_sourceBadge__XDE2u",serverListEmpty:"SettingsConfig_serverListEmpty___icit",statusDot:"SettingsConfig_statusDot__dVcD4",addServer:"SettingsConfig_addServer__g0ivB",mcpEditor:"SettingsConfig_mcpEditor__XGcLp",editorHeader:"SettingsConfig_editorHeader__qDvAk",readOnlyNotice:"SettingsConfig_readOnlyNotice__KNzML",editorActions:"SettingsConfig_editorActions__h9p7Y",linkButton:"SettingsConfig_linkButton__0DH3I",primaryButton:"SettingsConfig_primaryButton__Eocwv",dangerButton:"SettingsConfig_dangerButton__XF_f_",empty:"SettingsConfig_empty__erg3A"}},14755:(e,t,n)=>{"use strict";n.d(t,{C1:()=>a,IN:()=>i,getPresetFromTools:()=>l,xG:()=>o});let r=[],i=["read","bash","edit","write"],a=["read","bash","edit","write","grep","glob"],s=Object.fromEntries(a.map(e=>[e,!0]));function l(e){let t=e.filter(e=>e.active);if(0===t.length)return"none";let n=t.map(e=>e.name).filter(e=>!0===s[e]).sort().join(",");return n===[...i].sort().join(",")?"default":n===[...a].sort().join(",")?"full":"default"}function o(e){return"none"===e?[...r]:"full"===e?[...a]:[...i]}},20625:(e,t,n)=>{"use strict";n.d(t,{AppShell:()=>pH});var r=n(95155),i=n(12115),a=n(73321),s=n(16871),l=n(81886),o=n(68890),d=n(6057);let c=["chat","process","subagents","files","resource","sidechat","efficiency"],u=["characters","usage","models"];Object.freeze({transcript:550,composer:384,navigator:240,deck:384});let p=Object.freeze({navigator:791,deck:1176}),h=Object.freeze({activeView:"chat",transientLayer:null,deckExpanded:!1}),m=Object.fromEntries(c.map(e=>[e,!0]));function f(e){return"string"==typeof e&&!0===m[e]?e:h.activeView}function g(e,t){switch(t.type){case"select-view":{let n,r=f(t.view);return{activeView:r,transientLayer:null,deckExpanded:(n=!0===e.deckExpanded,"chat"!==r&&n)}}case"open-layer":{let n,r=f(e.activeView);return{activeView:r,transientLayer:t.layer,deckExpanded:(n=!0===e.deckExpanded,"chat"!==r&&n)}}case"toggle-layer":{let n,r=f(e.activeView);return{activeView:r,transientLayer:e.transientLayer===t.layer?null:t.layer,deckExpanded:(n=!0===e.deckExpanded,"chat"!==r&&n)}}case"close-layer":{let t,n=f(e.activeView);return{activeView:n,transientLayer:null,deckExpanded:(t=!0===e.deckExpanded,"chat"!==n&&t)}}case"set-deck-expanded":{let n,r=f(e.activeView);return{activeView:r,transientLayer:e.transientLayer,deckExpanded:(n=t.expanded,"chat"!==r&&n)}}}}function x(e){let t=Number.isFinite(e)?Math.max(0,e):0;return{availableWidth:t,navigator:t>=p.navigator?"pinned":"drawer",deck:t>=p.deck?"pinned":"view-stack"}}let v=null,b=!1,y=-1/0;function w(e,t=Date.now()){b=e,e||(y=t)}let k=["projects","priority"],j="omp-web:navigator-mode",S="omp-prio-on",C=["omp-relay-session-","omp-cwd-","ompscope_"];function N(e){let t=e.trim().replace(/\\/g,"/");return"/"===(t=t.startsWith("//")?`//${t.slice(2).replace(/\/{2,}/g,"/")}`:t.replace(/\/{2,}/g,"/"))||/^[a-zA-Z]:\/$/.test(t)||(t=t.replace(/\/+$/,"")),/^[a-zA-Z]:\//.test(t)||t.startsWith("//")?t.toLowerCase():t}function I(e){let t=new Map;for(let n of e){let e=n.projectRoot??n.cwd;if(!e)continue;let r=N(e),i=t.get(r);(!i||n.modified>i.modified)&&t.set(r,{project:e,modified:n.modified})}return[...t.values()].sort((e,t)=>t.modified.localeCompare(e.modified)).map(e=>e.project)}function T(e,t){let n=new Map;for(let e of t)"number"==typeof e.order&&Number.isFinite(e.order)&&n.set(N(e.key),e.order);let r=[...e],i=new Set(e.map(N));for(let e of t){let t=N(e.key);!t||i.has(t)||(r.push(e.path??e.key),i.add(t))}return r.map((e,t)=>({project:e,defaultIndex:t,order:n.get(N(e))})).sort((e,t)=>{let n=void 0!==e.order,r=void 0!==t.order;return n!==r?n?-1:1:n&&r&&e.order!==t.order?e.order-t.order:e.defaultIndex-t.defaultIndex}).map(({project:e})=>e)}let M=/^<skill name="([^"\n]+)" location="([^"\n]+)">\nReferences are relative to [^\n]+\.\n\n([\s\S]*)\n<\/skill>(?:\n\n([\s\S]+))?$/;function $(e){let t=e.match(M);if(!t)return null;let[,n,,,r]=t;return r?`/skill:${n} ${r}`:`/skill:${n}`}var R=n(92176);let E=`(max-width: ${p.navigator-1}px)`;function L(e){return{subscribe(t){if(!window.matchMedia)return()=>{};let n=window.matchMedia(e);return n.addEventListener("change",t),()=>n.removeEventListener("change",t)},getSnapshot:()=>!!window.matchMedia&&window.matchMedia(e).matches}}let A=L("(max-width: 640px)"),z=L(E);function P(){return!1}function W(){return(0,i.useSyncExternalStore)(A.subscribe,A.getSnapshot,P)}var F=n(47650);async function _(e){let t=e?`?path=${encodeURIComponent(e)}`:"",n=await fetch(`/api/cwd/browse${t}`),r=await n.json();if(!n.ok||r.error)throw Error(r.error??`HTTP ${n.status}`);return r}function D(){return(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.3","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M1.5 3h4l1.5 2h7.5v7.5h-13z"})})}function O(){return(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.3",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("rect",{x:"2",y:"3",width:"12",height:"10",rx:"1.5"}),(0,r.jsx)("path",{d:"M2 9h12"}),(0,r.jsx)("circle",{cx:"11.5",cy:"11",r:"0.6",fill:"currentColor",stroke:"none"})]})}function H({onCancel:e,onSelect:t,busy:n=!1,error:a}){let{t:s}=(0,R.s)(),[l,o]=(0,i.useState)(null),[d,c]=(0,i.useState)(""),[u,p]=(0,i.useState)(null),[h,m]=(0,i.useState)(!1),[f,g]=(0,i.useState)(""),[x,v]=(0,i.useState)([]),[b,y]=(0,i.useState)(null),[w,k]=(0,i.useState)(null),[j,S]=(0,i.useState)(!0),C=(0,i.useCallback)(async e=>{S(!0),k(null);try{let t=await _(e),n=t.path??e??"/";c(n),p(t.parentPath??null),m(!0===t.upToDrives),g(n),v(t.directories??[]),y(t.drives??null)}catch(e){k(e instanceof Error?e.message:String(e))}finally{S(!1)}},[]);(0,i.useEffect)(()=>{o(document.body),C()},[C]);let N=f.trim()!==d,I=!!d&&!N&&!n,T=!!u||h||/^[a-zA-Z]:[\\/]?$/.test(d);return l?(0,F.createPortal)((0,r.jsx)("div",{className:"directory-picker-backdrop",role:"dialog","aria-modal":"true","aria-label":s("directoryPicker.selectDirectory"),onClick:t=>{t.target!==t.currentTarget||n||e()},onKeyDown:t=>{"Escape"!==t.key||n||e()},style:{position:"fixed",inset:0,zIndex:1e3,display:"flex",alignItems:"center",justifyContent:"center",background:"rgba(0,0,0,0.35)"},children:(0,r.jsxs)("div",{className:"directory-picker-panel",style:{width:520,maxWidth:"calc(100vw - 16px)",height:"min(620px, calc(100dvh - 16px))",maxHeight:"calc(100dvh - 16px)",display:"flex",flexDirection:"column",overflow:"hidden",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:10,boxShadow:"0 8px 32px rgba(0,0,0,0.18)"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",flexShrink:0,padding:"12px 18px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("div",{style:{minWidth:0,flex:1},children:(0,r.jsx)("div",{style:{color:"var(--text)",fontWeight:700,fontSize:15},children:s("directoryPicker.selectDirectory")})}),(0,r.jsx)("button",{type:"button",onClick:e,disabled:n,title:s("i18n.close"),"aria-label":s("i18n.close"),style:{padding:"2px 6px",border:0,background:"none",color:"var(--text-muted)",fontSize:20,lineHeight:1,cursor:n?"default":"pointer",opacity:n?.5:1},children:"\xd7"})]}),(0,r.jsxs)("form",{onSubmit:e=>{e.preventDefault();let t=f.trim();t&&C(t)},style:{display:"flex",alignItems:"center",gap:8,flexShrink:0,padding:"10px 14px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("button",{className:"directory-picker-back",type:"button",onClick:()=>void C(u??void 0),disabled:j||!T,title:s("directoryPicker.goToParent"),"aria-label":s("directoryPicker.goToParent"),style:{width:36,height:36,padding:0,display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-hover)",color:"var(--text-muted)",cursor:T?"pointer":"default",opacity:T?1:.45},children:(0,r.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m18 15-6-6-6 6"})})}),(0,r.jsx)("label",{htmlFor:"directory-path",style:{position:"absolute",width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",border:0},children:s("directoryPicker.directoryPath")}),(0,r.jsx)("input",{className:"directory-picker-path",id:"directory-path",type:"text",value:f,placeholder:"/path/to/project or ~/project",autoFocus:!0,autoComplete:"off",spellCheck:!1,onChange:e=>{g(e.target.value),k(null)},style:{minWidth:0,flex:1,height:36,padding:"0 10px",border:"1px solid var(--border)",borderRadius:6,outline:"none",background:"var(--bg-panel)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:12}}),(0,r.jsx)("button",{className:"directory-picker-action",type:"submit",disabled:j||!f.trim(),title:s("directoryPicker.goToDirectory"),style:{minWidth:58,height:36,padding:"0 12px",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-hover)",color:"var(--text-muted)",cursor:j||!f.trim()?"default":"pointer",opacity:j||!f.trim()?.6:1},children:s("directoryPicker.go")})]}),(0,r.jsxs)("div",{className:"directory-picker-list",style:{flex:1,minHeight:0,overflow:"auto",padding:"8px 10px"},children:[j?(0,r.jsx)("div",{style:{padding:8,color:"var(--text-dim)",fontSize:11},children:s("directoryPicker.loadingDirectories")}):null!==b?(0,r.jsx)(r.Fragment,{children:b.length>0?b.map(e=>(0,r.jsxs)("button",{className:"directory-picker-entry",type:"button",onClick:()=>void C(e.path),title:e.path,style:{width:"100%",minHeight:34,display:"flex",alignItems:"center",gap:7,padding:"6px 8px",border:0,borderRadius:5,background:"none",color:"var(--text-muted)",cursor:"pointer",textAlign:"left",fontFamily:"var(--font-mono)",fontSize:11},children:[(0,r.jsx)(O,{}),(0,r.jsx)("span",{children:e.name})]},e.path)):(0,r.jsx)("div",{style:{padding:8,color:"var(--text-dim)",fontSize:11},children:s("directoryPicker.noDrives")})}):x.length>0?x.map(e=>(0,r.jsxs)("button",{className:"directory-picker-entry",type:"button",onClick:()=>void C(e.path),title:e.path,style:{width:"100%",minHeight:30,display:"flex",alignItems:"center",gap:7,padding:"5px 8px",border:0,borderRadius:5,background:"none",color:"var(--text-muted)",cursor:"pointer",textAlign:"left",fontFamily:"var(--font-mono)",fontSize:11},children:[(0,r.jsx)(D,{}),(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name})]},e.path)):(0,r.jsx)("div",{style:{padding:8,color:"var(--text-dim)",fontSize:11},children:s("directoryPicker.noSubdirectories")}),(w||a)&&(0,r.jsx)("div",{style:{padding:"8px",color:"#dc2626",fontSize:11},children:w??a})]}),(0,r.jsxs)("div",{className:"directory-picker-footer",style:{display:"flex",justifyContent:"flex-end",alignItems:"center",gap:10,flexShrink:0,padding:"10px 18px",borderTop:"1px solid var(--border)"},children:[(0,r.jsx)("button",{className:"directory-picker-action",type:"button",onClick:e,disabled:n,style:{padding:"6px 14px",border:"1px solid var(--border)",borderRadius:6,background:"none",color:"var(--text-muted)",cursor:n?"default":"pointer",fontSize:13},children:s("i18n.cancel")}),(0,r.jsx)("button",{className:"directory-picker-action",type:"button",onClick:()=>t(d),disabled:!I,title:s(N?"directoryPicker.openBeforeSelecting":"directoryPicker.selectCurrentDirectory"),style:{padding:"6px 16px",border:0,borderRadius:6,background:"var(--seed-color-bg-neutral-inverted)",color:"var(--seed-color-fg-neutral-inverted)",fontSize:13,fontWeight:600,opacity:I?1:.6,cursor:I?"pointer":"default"},children:s(n?"i18n.checking":"directoryPicker.selectThisFolder")})]})]})}),l):null}var B=n(21443),U=n.n(B);async function q(e,t){let n=await fetch(e,t?{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}:void 0),r=await n.json();if(!n.ok)throw Error(r.error||`HTTP ${n.status}`);return r}function K({onCancel:e,onSelect:t,busy:n=!1,error:a}){let{t:s}=(0,R.s)(),l=(0,i.useRef)(null),[o,d]=(0,i.useState)(!1),[c,u]=(0,i.useState)(!1),[p,h]=(0,i.useState)(null),[m,f]=(0,i.useState)([]),[g,x]=(0,i.useState)(""),[v,b]=(0,i.useState)(""),[y,w]=(0,i.useState)(!0),[k,j]=(0,i.useState)(!1),[S,C]=(0,i.useState)(!1),[N,I]=(0,i.useState)(null),[T,M]=(0,i.useState)(!1),[$,E]=(0,i.useState)(50),L=p?.device?.state==="pending",A=n||S,z=(0,i.useCallback)(async()=>{w(!0),I(null);try{let e=await q("/api/github/projects");h(e),e.connected&&f((await q("/api/github/projects?view=repositories")).repositories)}catch(e){I(e instanceof Error?e.message:String(e))}finally{w(!1)}},[]);async function P(){j(!0),I(null);try{let{device:e}=await q("/api/github/projects",{action:"login"});h({connected:!1,login:null,device:e})}catch(e){I(e instanceof Error?e.message:String(e))}finally{j(!1)}}async function W(e){if(e.preventDefault(),v.trim()&&!A){C(!0),I(null);try{let{cwd:e}=await q("/api/github/projects",{action:"open",repository:v});t(e)}catch(e){I(e instanceof Error?e.message:String(e))}finally{C(!1)}}}if((0,i.useEffect)(()=>{d(!0),z()},[z]),(0,i.useEffect)(()=>{if(!o||c)return;let e=l.current;return e?.showModal(),()=>e?.close()},[o,c]),(0,i.useEffect)(()=>{let e;if(!L||c)return;let t=!1,n=async()=>{try{let e=await q("/api/github/projects");if(t)return;if(h(e),e.connected)return void await z();if(e.device?.state!=="pending")return}catch(e){t||I(e instanceof Error?e.message:String(e));return}t||(e=window.setTimeout(n,3e3))};return e=window.setTimeout(n,1500),()=>{t=!0,clearTimeout(e)}},[L,c,z]),!o)return null;if(c)return(0,r.jsx)(H,{onCancel:()=>u(!1),onSelect:t,busy:n,error:a});let _=m.filter(e=>`${e.fullName} ${e.description??""}`.toLowerCase().includes(g.toLowerCase())),D=N??a??p?.device?.error;return(0,F.createPortal)((0,r.jsx)("dialog",{ref:l,className:U().dialog,"aria-labelledby":"cloud-project-title",onCancel:t=>{t.preventDefault(),A||e()},children:(0,r.jsxs)("form",{onSubmit:W,className:U().form,children:[(0,r.jsxs)("header",{className:U().header,children:[(0,r.jsx)("h2",{id:"cloud-project-title",children:s("cloudProjects.title")}),(0,r.jsx)("p",{children:s("cloudProjects.description")})]}),(0,r.jsxs)("div",{className:U().sources,children:[(0,r.jsx)("span",{className:U().activeSource,children:s("cloudProjects.github")}),(0,r.jsx)("button",{type:"button",onClick:()=>u(!0),disabled:A,children:s("cloudProjects.serverFolder")})]}),(0,r.jsxs)("div",{className:U().body,children:[(0,r.jsxs)("section",{className:U().account,"aria-label":s("cloudProjects.account"),children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("strong",{children:p?.connected?p.login:s("cloudProjects.connectTitle")}),(0,r.jsx)("p",{children:p?.connected?s("cloudProjects.connected"):s("cloudProjects.connectHelp")})]}),p?.connected?(0,r.jsx)("button",{type:"button",className:U().secondary,onClick:()=>void z(),disabled:y||A,children:s("cloudProjects.refresh")}):(0,r.jsx)("button",{type:"button",className:U().secondary,onClick:()=>void P(),disabled:y||k||L||A,children:k||L?s("cloudProjects.waiting"):s("cloudProjects.connect")})]}),L&&(0,r.jsxs)("div",{className:U().login,role:"status",children:[(0,r.jsx)("p",{children:s("cloudProjects.deviceHelp")}),p.device?.code?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("div",{className:U().codeRow,children:[(0,r.jsx)("code",{children:p.device.code}),(0,r.jsx)("button",{type:"button",className:U().secondary,onClick:()=>{navigator.clipboard.writeText(p.device.code).then(()=>M(!0)).catch(()=>I(s("cloudProjects.copyFailure")))},children:T?s("cloudProjects.copied"):s("cloudProjects.copyCode")})]}),(0,r.jsx)("a",{href:"https://github.com/login/device",target:"_blank",rel:"noreferrer",className:U().loginLink,children:s("cloudProjects.openLogin")}),(0,r.jsx)("small",{children:s("cloudProjects.permissionHelp")})]}):(0,r.jsx)("p",{children:s("cloudProjects.preparingCode")})]}),p?.connected&&(0,r.jsxs)("section",{className:U().repositories,"aria-label":s("cloudProjects.repositories"),children:[(0,r.jsx)("label",{htmlFor:"cloud-repo-search",children:s("cloudProjects.search")}),(0,r.jsx)("input",{id:"cloud-repo-search",value:g,onChange:e=>{x(e.target.value),E(50)},placeholder:s("cloudProjects.searchPlaceholder"),type:"search",disabled:A}),y?(0,r.jsx)("p",{role:"status",children:s("cloudProjects.loading")}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("ul",{className:U().list,children:_.slice(0,$).map(e=>(0,r.jsx)("li",{children:(0,r.jsxs)("button",{type:"button",className:U().repo,"aria-pressed":v===e.fullName,disabled:A,onClick:()=>b(e.fullName),children:[(0,r.jsxs)("span",{className:U().repoHeading,children:[(0,r.jsx)("strong",{children:e.fullName}),(0,r.jsx)("small",{children:e.private?s("cloudProjects.private"):s("cloudProjects.public")})]}),e.description&&(0,r.jsx)("span",{className:U().repoDescription,children:e.description})]})},e.fullName))}),!_.length&&(0,r.jsx)("p",{children:s("cloudProjects.empty")}),_.length>$&&(0,r.jsx)("button",{type:"button",className:U().secondary,onClick:()=>E(e=>e+50),children:s("cloudProjects.more")})]})]}),(0,r.jsxs)("div",{className:U().repositoryInput,children:[(0,r.jsx)("label",{htmlFor:"cloud-repository",children:s("cloudProjects.urlLabel")}),(0,r.jsx)("input",{id:"cloud-repository",value:v,onChange:e=>b(e.target.value),placeholder:"owner/repository",autoComplete:"off",spellCheck:!1,disabled:A,"aria-describedby":"cloud-repo-help"}),(0,r.jsx)("small",{id:"cloud-repo-help",children:s("cloudProjects.publicHelp")})]}),D&&(0,r.jsxs)("div",{className:U().error,role:"alert",children:[(0,r.jsx)("strong",{children:s("cloudProjects.error")}),(0,r.jsx)("p",{children:D}),(0,r.jsx)("button",{type:"button",className:U().secondary,onClick:()=>void z(),disabled:A,children:s("cloudProjects.refresh")})]}),S&&(0,r.jsx)("p",{role:"status",className:U().progress,children:s("cloudProjects.openingHelp")})]}),(0,r.jsxs)("footer",{className:U().footer,children:[(0,r.jsx)("button",{type:"button",className:U().secondary,onClick:e,disabled:A,children:s("i18n.cancel")}),(0,r.jsx)("button",{type:"submit",className:U().primary,disabled:A||!v.trim(),children:A?s("cloudProjects.opening"):s("cloudProjects.open")})]})]})}),document.body)}function V({label:e="CUELO",markSize:t=22,gap:n=10,style:i,labelStyle:a}){return(0,r.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:n,minWidth:0,color:"var(--text)",...i},children:[(0,r.jsxs)("svg",{viewBox:"0 0 100 100",width:t,height:t,"aria-hidden":"true",style:{flexShrink:0},children:[(0,r.jsx)("path",{d:"M77.9 30.5 A34 34 0 0 0 16 50 A26 26 0 0 0 68 50",fill:"none",stroke:"currentColor",strokeWidth:"10",strokeLinecap:"round"}),(0,r.jsx)("circle",{cx:"42",cy:"50",r:"8.5",fill:"var(--brand-lamp)"})]}),(0,r.jsx)("span",{style:{minWidth:0,overflow:"hidden",color:"inherit",fontFamily:"var(--font-heading)",fontSize:15,fontWeight:700,letterSpacing:"-0.025em",whiteSpace:"nowrap",...a},children:e})]})}var J=n(2730);let G={ko:{"translator.tab":"통역","translator.title":"통역","translator.back":"대화로","translator.panelHint":"통역을 시작하면 ChatGPT 계정의 Codex 라이브 통화로 두 사람의 말을 서로의 언어로 바로 소리 내어 옮깁니다. 작업 세션과 하네스 규칙을 거치지 않고, 기록은 저장하지 않습니다.","translator.open":"통역 화면 열기","translator.me":"나","translator.them":"상대","translator.myLanguage":"내 언어","translator.theirLanguage":"상대 언어","translator.swap":"두 언어 바꾸기","translator.clear":"지우기","translator.start":"통역 시작","translator.stop":"통역 끝내기","translator.empty":"통역 시작을 누르고 폰을 두 사람 사이에 두세요. 누가 말하든 상대 언어로 바로 옮겨 말합니다.","translator.connecting":"연결 중…","translator.live":"듣는 중 \xb7 그냥 말하세요","translator.unsupported":"이 브라우저는 실시간 통화(WebRTC\xb7마이크)를 지원하지 않습니다. 폰에서는 Chrome이나 Safari로 여세요.","translator.insecure":"마이크는 HTTPS 주소에서만 켜집니다.","translator.micDenied":"마이크 권한이 막혀 있습니다. 브라우저 설정에서 이 주소의 마이크를 허용하세요.","translator.micUnavailable":"마이크를 켜지 못했습니다. 다른 앱이 쓰고 있지 않은지 확인하세요.","translator.auth":"Codex 로그인이 없거나 만료됐습니다. 모델 설정에서 ChatGPT 계정으로 다시 로그인하세요.","translator.upstream":"Codex 라이브 연결이 끊겼습니다: {error}","translator.failed":"통역을 시작하지 못했습니다: {error}","translator.original":"원문","translator.translationPending":"통역 중…","translator.conversation":"통역 기록"},en:{"translator.tab":"Interpret","translator.title":"Interpreter","translator.back":"Back to chat","translator.panelHint":"Start interpreting and a Codex live call on your ChatGPT account speaks each person's words in the other's language right away. It bypasses work sessions and harness rules, and nothing is saved.","translator.open":"Open interpreter","translator.me":"Me","translator.them":"Them","translator.myLanguage":"My language","translator.theirLanguage":"Their language","translator.swap":"Swap languages","translator.clear":"Clear","translator.start":"Start interpreting","translator.stop":"Stop interpreting","translator.empty":"Press Start interpreting and put the phone between you. Whoever speaks is interpreted into the other language right away.","translator.connecting":"Connecting…","translator.live":"Listening \xb7 just talk","translator.unsupported":"This browser cannot make live calls (WebRTC and microphone). On a phone, open this page in Chrome or Safari.","translator.insecure":"The microphone only works on an HTTPS address.","translator.micDenied":"Microphone access is blocked. Allow the microphone for this address in the browser settings.","translator.micUnavailable":"The microphone could not be opened. Check that no other app is using it.","translator.auth":"The Codex sign-in is missing or expired. Sign in again with your ChatGPT account in model settings.","translator.upstream":"The Codex live connection dropped: {error}","translator.failed":"Interpreting could not start: {error}","translator.original":"Original","translator.translationPending":"Interpreting…","translator.conversation":"Interpretation log"},"zh-CN":{"translator.tab":"口译","translator.title":"口译","translator.back":"返回对话","translator.panelHint":"开始口译后,通过 ChatGPT 账号的 Codex 实时通话,把双方的话立即用对方的语言说出来。不经过工作会话和规则,也不保存记录。","translator.open":"打开口译","translator.me":"我","translator.them":"对方","translator.myLanguage":"我的语言","translator.theirLanguage":"对方语言","translator.swap":"交换语言","translator.clear":"清除","translator.start":"开始口译","translator.stop":"结束口译","translator.empty":"按开始口译,把手机放在两人之间。无论谁说话,都会立即译成对方的语言说出来。","translator.connecting":"连接中…","translator.live":"正在听 \xb7 直接说话","translator.unsupported":"此浏览器不支持实时通话(WebRTC 和麦克风)。手机请用 Chrome 或 Safari 打开。","translator.insecure":"麦克风只能在 HTTPS 地址上使用。","translator.micDenied":"麦克风权限被阻止。请在浏览器设置中允许此地址使用麦克风。","translator.micUnavailable":"无法打开麦克风。请确认没有其他应用正在使用。","translator.auth":"Codex 登录不存在或已过期。请在模型设置中用 ChatGPT 账号重新登录。","translator.upstream":"Codex 实时连接已断开:{error}","translator.failed":"无法开始口译:{error}","translator.original":"原文","translator.translationPending":"口译中…","translator.conversation":"口译记录"}};function Y(){let{locale:e}=(0,R.s)();return{tt:(0,i.useCallback)((t,n)=>(0,J.u0)(e,t,G,n),[e]),locale:e}}let Z="omp-web:unread-session-ids",X="omp-web:pinned-session-ids",Q="omp-web:removed-projects";function ee(e,t){return{minHeight:t?36:30,padding:"3px 10px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"transparent",color:e?"var(--text-dim)":"var(--text-muted)",cursor:e?"default":"pointer",fontSize:"var(--seed-font-size-t2-static)",lineHeight:1.3,textAlign:"left",whiteSpace:"normal",overflowWrap:"anywhere"}}function et(e,t){return t&&e.startsWith(t)?"~"+e.slice(t.length):e}function en({text:e,style:t}){return(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",display:"block",minWidth:0,lineHeight:1.35,direction:"rtl",textAlign:"left",...t},children:(0,r.jsx)("span",{style:{unicodeBidi:"plaintext"},children:e})})}function er({open:e,children:t,style:n}){let[a,s]=(0,i.useState)(e),[l,o]=(0,i.useState)(e);return((0,i.useEffect)(()=>{let t,n;return e?(s(!0),o(!1),t=window.requestAnimationFrame(()=>{t=window.requestAnimationFrame(()=>o(!0))})):(o(!1),n=setTimeout(()=>s(!1),140)),()=>{void 0!==t&&window.cancelAnimationFrame(t),n&&clearTimeout(n)}},[e]),a)?(0,r.jsx)("div",{style:{...n,opacity:+!!l,transform:l?"translateY(0) scale(1)":"translateY(-8px) scale(0.96)",transformOrigin:"top center",transition:"opacity 140ms ease, transform 140ms ease",pointerEvents:e?"auto":"none"},children:t}):null}let ei="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*";function ea(){let[e,t]=(0,i.useState)(!1),[n,a]=(0,i.useState)(!1),s=(0,i.useRef)(null),l=function(e,t){let[n,r]=(0,i.useState)(e),a=(0,i.useRef)(null),s=(0,i.useRef)(0);return(0,i.useEffect)(()=>{if(!t)return void r(e);s.current=0;let n=4*e.length,i=()=>{s.current+=1;let t=Math.floor(s.current/n*e.length);r(e.split("").map((e,n)=>" "===e?" ":n<t?e:ei[Math.floor(Math.random()*ei.length)]).join("")),s.current<n?a.current=requestAnimationFrame(i):r(e)};return a.current=requestAnimationFrame(i),()=>{a.current&&cancelAnimationFrame(a.current)}},[e,t]),n}(e?"0.10.35/18.12.1":"CUELO",n),o=(0,i.useCallback)(e=>{t(e),a(!0),setTimeout(()=>a(!1),(e?6:8)*4*(1e3/60)+100)},[]),d=(0,i.useCallback)(()=>{s.current&&clearTimeout(s.current);let t=!e;o(t),t&&(s.current=setTimeout(()=>o(!1),3e3))},[e,o]);return(0,i.useEffect)(()=>()=>{s.current&&clearTimeout(s.current)},[]),(0,r.jsx)("button",{className:"navigator-brand",onClick:d,style:{display:"flex",alignItems:"center",background:"none",border:"none",padding:0,cursor:"default",color:e?"var(--accent)":"var(--text)",flex:"0 1 auto",minWidth:0,overflow:"hidden"},children:(0,r.jsx)(V,{label:l,labelStyle:e?{fontFamily:"var(--font-mono)",fontSize:12,letterSpacing:"-0.02em",textOverflow:"ellipsis"}:void 0})})}async function es(e){let t=await fetch("/api/projects",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({updates:e})});if(!t.ok)throw Error(`HTTP ${t.status}`)}function el({selectedSessionId:e,optimisticSession:t,onSelectSession:n,onNewSession:a,initialSessionId:s,skipInitialProjectSelection:l,onInitialRestoreDone:o,refreshKey:d,onSessionDeleted:c,selectedCwd:u,onCwdChange:p,onBackgroundTaskDone:h,translatorPanel:m,translatorActive:f=!1,onTranslatorActiveChange:g}){let x,{tt:v}=Y(),{t:b,locale:y}=(0,R.s)(),w=W(),[M,$]=(0,i.useState)([]),E=t&&!M.some(e=>e.id===t.id)?[t,...M]:M,[L,A]=(0,i.useState)(!0),[z,P]=(0,i.useState)(null),[F,_]=(0,i.useState)(null),[D,O]=(0,i.useState)(""),[B,U]=(0,i.useState)(!1),[q,V]=(0,i.useState)(""),[J,G]=(0,i.useState)("projects"),[ei,ed]=(0,i.useState)(()=>new Set),[eh,em]=(0,i.useState)(()=>new Set),[eg,ex]=(0,i.useState)(null),[ev,eb]=(0,i.useState)(null),[ey,ew]=(0,i.useState)({version:1,projects:[]}),[ek,ej]=(0,i.useState)(!1),[eS,eC]=(0,i.useState)(!1),[eN,eI]=(0,i.useState)(!1),[eT,eM]=(0,i.useState)(null),[e$,eR]=(0,i.useState)(""),[eE,eL]=(0,i.useState)(!1),[eA,ez]=(0,i.useState)(null),[eP,eW]=(0,i.useState)(""),[eF,e_]=(0,i.useState)(!1),[eD,eO]=(0,i.useState)(null),[eH,eB]=(0,i.useState)(!1),[eU,eq]=(0,i.useState)(null),[eK,eV]=(0,i.useState)(!1),[eJ,eG]=(0,i.useState)(!1),[eY,eZ]=(0,i.useState)(""),[eX,eQ]=(0,i.useState)(null),[e0,e1]=(0,i.useState)(!1),[e2,e4]=(0,i.useState)(null),e5=(0,i.useRef)(null),e6=(0,i.useRef)(null),e8=(0,i.useRef)(null),e3=(0,i.useRef)(!1),e7=(0,i.useRef)(!1),[e9,te]=(0,i.useState)(!1),[tt,tn]=(0,i.useState)(()=>new Set),[tr,ti]=(0,i.useState)(()=>(function(){try{let e=window.localStorage.getItem(Z);if(!e)return new Set;let t=JSON.parse(e);if(Array.isArray(t))return new Set(t.filter(e=>"string"==typeof e));return new Set}catch{return new Set}})()),[ta,ts]=(0,i.useState)(()=>new Set),tl=(0,i.useRef)(new Set),to=(0,i.useRef)(!1),td=(0,i.useRef)(null);(0,i.useEffect)(()=>{ts(function(){try{let e=window.localStorage.getItem(X);if(!e)return new Set;let t=JSON.parse(e);return Array.isArray(t)?new Set(t.filter(e=>"string"==typeof e)):new Set}catch{return new Set}}())},[]);let tc=(0,i.useCallback)(async()=>{try{let e=await fetch("/api/projects",{cache:"no-store",signal:AbortSignal.timeout(5e3)});if(!e.ok)throw Error(`HTTP ${e.status}`);ew(await e.json())}catch{ew({version:1,projects:[]})}finally{ej(!0)}},[]);(0,i.useEffect)(()=>{tc()},[tc,d]),(0,i.useEffect)(()=>{let e=null;try{e=window.localStorage.getItem(Q)}catch{return}if(!e)return;let t=[];try{let n=JSON.parse(e);Array.isArray(n)&&(t=n.filter(e=>"string"==typeof e))}catch{t=[]}(async()=>{try{for(let e=0;e<t.length;e+=500){let n=t.slice(e,e+500);await es(n.map(e=>({key:N(e),path:e,hidden:!0})))}}catch{return}try{window.localStorage.removeItem(Q)}catch{}await tc()})()},[tc]);let tu=(0,i.useCallback)(async e=>{if(e7.current)throw Error("Project update in progress");e7.current=!0,eL(!0);try{await es(e),await tc()}finally{e7.current=!1,eL(!1)}},[tc]);(0,i.useEffect)(()=>{eT&&e8.current?.select()},[eT]);let tp=(0,i.useCallback)(async(e=!1,t=!1)=>{try{e&&A(!0);let n=await fetch(t?"/api/sessions?force=1":"/api/sessions",{cache:"no-store"});if(!n.ok)throw Error(`HTTP ${n.status}`);let r=await n.json();$(r.sessions),to.current||tn(new Set(r.runningSessionIds??[])),P(null),e||(te(!0),td.current&&clearTimeout(td.current),td.current=setTimeout(()=>te(!1),2e3))}catch(e){P(String(e))}finally{e&&A(!1)}},[]),th=(0,i.useCallback)(e=>{ti(t=>{if(!t.has(e))return t;let n=new Set(t);return n.delete(e),n}),ts(t=>{if(!t.has(e))return t;let n=new Set(t);return n.delete(e),n}),c?.(e),tp()},[tp,c]),[tm,tf]=(0,i.useState)(null),[tg,tx]=(0,i.useState)(!1),[tv,tb]=(0,i.useState)(null),ty=(0,i.useCallback)(()=>{tg||(tf(null),tb(null))},[tg]),tw=(0,i.useCallback)(async e=>{tx(!0),tb(null);let t=[],n=[],r=[];for(let i of e)if(!i.transient)try{let e=await fetch(`/api/sessions/${encodeURIComponent(i.id)}?skipRunning=1`,{method:"DELETE"});if(409===e.status){n.push(i.id);continue}if(!e.ok)throw Error(`HTTP ${e.status}`);t.push(i.id)}catch{r.push(i.name?.trim()||i.id.slice(0,8))}if(n.length>0&&(to.current=!0,tn(e=>{if(n.every(t=>e.has(t)))return e;let t=new Set(e);for(let e of n)t.add(e);return t})),t.length>0){let e=new Set(t),n=n=>t.some(e=>n.has(e))?new Set([...n].filter(t=>!e.has(t))):n;for(let e of(ti(n),ts(n),t))c?.(e)}(await tp(),tx(!1),r.length>0)?tb(b("sidebar.clearSessionsFailed",{count:r.length,names:r.join(", ")})):n.length>0||tf(null)},[tp,c,b]),[tk,tj]=(0,i.useState)(0),tS=(0,i.useCallback)(()=>{tj(e=>e+1),tp()},[tp]),tC=(0,i.useRef)(!1);(0,i.useEffect)(()=>{let e=!tC.current;tC.current=!0,tp(e,!e)},[tp,d]),(0,i.useEffect)(()=>{try{G(function(e,t){return"gpt6"===e?"projects":"string"==typeof e&&k.includes(e)?e:"1"===t?"priority":"projects"}(window.localStorage.getItem(j),window.localStorage.getItem(S)))}catch{}},[]);let tN=(0,i.useCallback)(e=>{G(e);try{window.localStorage.setItem(j,e),window.localStorage.setItem(S,"priority"===e?"1":"0")}catch{}},[]);(0,i.useEffect)(()=>{if("priority"!==J)return;let e=()=>{"visible"===document.visibilityState&&tp(!1,!0)};e();let t=window.setInterval(e,15e3);return()=>window.clearInterval(t)},[tp,J]),(0,i.useEffect)(()=>{try{0===tr.size?window.localStorage.removeItem(Z):window.localStorage.setItem(Z,JSON.stringify([...tr]))}catch{}},[tr]),(0,i.useEffect)(()=>{try{0===ta.size?window.localStorage.removeItem(X):window.localStorage.setItem(X,JSON.stringify([...ta]))}catch{}},[ta]);let tI=(0,i.useCallback)(e=>{ts(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]);(0,i.useEffect)(()=>{let e=!1,t=null,n=null,r=()=>{t&&clearTimeout(t),t=null},i=async()=>{if(e||"visible"!==document.visibilityState)return;let a=new AbortController;n?.abort(),n=a;try{let t=await fetch("/api/agent/running",{cache:"no-store",signal:a.signal});if(!t.ok)return;let r=await t.json();if(e||n!==a)return;to.current=!0,tn(new Set(r.runningSessionIds??[]))}catch{}finally{n===a&&(n=null),r(),e||"visible"!==document.visibilityState||(t=setTimeout(()=>void i(),2500))}},a=()=>{"visible"===document.visibilityState?i():(r(),n?.abort(),n=null)};return i(),document.addEventListener("visibilitychange",a),()=>{e=!0,r(),n?.abort(),document.removeEventListener("visibilitychange",a)}},[]),(0,i.useEffect)(()=>{let t=tl.current,n=[...t].filter(t=>!tt.has(t)&&t!==e),r=[...tt].filter(e=>!t.has(e));(n.length>0||r.length>0)&&ti(e=>{let t=new Set(e);return tt.forEach(e=>t.delete(e)),n.forEach(e=>t.add(e)),t});let i=r.some(e=>!M.some(t=>t.id===e));(n.length>0||i)&&tp(!1,!0),n.length>0&&h?.(),tl.current=tt},[tt,e,M,tp,h]),(0,i.useEffect)(()=>{e&&ti(t=>{if(!t.has(e))return t;let n=new Set(t);return n.delete(e),n})},[e]),(0,i.useEffect)(()=>{fetch("/api/home").then(e=>e.json()).then(e=>{e.home&&O(e.home),U(!0===e.cloudProjects)}).catch(()=>{})},[]);let tT=(0,i.useRef)(!1),tM=(0,i.useCallback)(e=>{if(!e)return null;if(eU&&eU.forCwd===e||eU?.worktrees.some(t=>t.path===e))return eU.projectRoot;let t=E.find(t=>t.cwd===e);return t?.projectRoot??e},[eU,E]),t$=(0,i.useRef)(null);(0,i.useEffect)(()=>{t$.current!==F&&(t$.current=F,p?.(F,tM(F)))},[F,p,tM]);let tR=(0,i.useRef)(null);(0,i.useEffect)(()=>{u&&u!==tR.current&&(tR.current=u,_(u))},[u]);let[tE,tL]=(0,i.useState)(0);(0,i.useLayoutEffect)(()=>{if(!F)return void eq(null);let e=!1;return fetch(`/api/worktrees?cwd=${encodeURIComponent(F)}`).then(e=>e.json()).then(t=>{if(!e){if(t.error||!t.projectRoot)return void eq(null);eq({forCwd:F,projectRoot:t.projectRoot,isGit:t.isGit??!1,isTopLevel:t.isTopLevel??!1,worktrees:t.worktrees??[]})}}).catch(()=>{e||eq(null)}),()=>{e=!0}},[F,tE,d]),(0,i.useEffect)(()=>{if(0!==M.length&&!l&&null===F){if(s&&!tT.current){tT.current=!0;let e=M.find(e=>e.id===s);if(e){_(e.cwd),n(e,!0);return}o?.()}if(!ek)return;let e=new Map(ey.projects.map(e=>[e.key,e])),t=T(M.length>0?I(M):[],ey.projects).filter(t=>!e.get(N(t))?.hidden);t.length>0&&_(t[0])}},[M,F,s,l,n,o,ey,ek]);let tA=(0,i.useCallback)(async e=>{let t=e.trim();if(t&&!eH){eB(!0),eO(null);try{let e=await fetch("/api/cwd/validate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:t})}),n=await e.json().catch(()=>({}));if(!e.ok||n.error)return void eO(n.error??b("workspace.unable"));let r=n.cwd??t,i=N(r),a=ey.projects.find(e=>e.key===i);if(a?.hidden===!0)try{await tu([{key:i,path:r,hidden:!1}])}catch{}_(r),e_(!1)}catch{eO(b("workspace.unable"))}finally{eB(!1)}}},[tu,eH,ey.projects,b]),tz=(0,i.useCallback)(()=>{e_(!0),eO(null)},[]),tP=(0,i.useCallback)(async()=>{let e=eY.trim();if(e&&!e0&&eU){e1(!0),eQ(null);try{let t=await fetch("/api/worktrees",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:eU.projectRoot,branch:e})}),n=await t.json().catch(()=>({}));if(!t.ok||n.error||!n.path)return void eQ(n.error??`HTTP ${t.status}`);eG(!1),eZ(""),eV(!1),eq(t=>t?{...t,forCwd:n.path,worktrees:[...t.worktrees,{path:n.path,branch:e,isMain:!1}]}:t),_(n.path),tL(e=>e+1)}catch(e){eQ(e instanceof Error?e.message:String(e))}finally{e1(!1)}}},[eY,e0,eU]),tW=(0,i.useCallback)(async(e,t)=>{if(eU&&!e0){e1(!0),eQ(null);try{let n=await fetch("/api/worktrees",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:eU.projectRoot,path:e,force:t})}),r=await n.json().catch(()=>({}));if(!n.ok){if(r.dirty&&!t)return void e4(e);eQ(r.error??`HTTP ${n.status}`);return}e4(null),F===e&&_(eU.projectRoot),tL(e=>e+1)}catch(e){eQ(e instanceof Error?e.message:String(e))}finally{e1(!1)}}},[eU,e0,F]);(0,i.useEffect)(()=>{let e=e=>{e5.current&&!e5.current.contains(e.target)&&(eb(null),eV(!1),eG(!1),eZ(""),eQ(null),e4(null),eW(""),ex(null))};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[]);let tF=(0,i.useCallback)(e=>{e.cwd&&_(e.cwd),n(e)},[n]),t_=(0,i.useCallback)((e=F)=>{if(!e)return;let t="function"==typeof crypto.randomUUID?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}-${Math.random().toString(36).slice(2)}`;_(e),a?.(t,e)},[F,a]),[tD,tO]=(0,i.useState)(!1),[tH,tB]=(0,i.useState)(null),tU=(0,i.useCallback)(async()=>{tO(!0),tB(null);try{let e=await fetch("/api/default-cwd",{method:"POST"}),t=await e.json().catch(()=>({}));if(!e.ok||!t.cwd)throw Error(t.error??`HTTP ${e.status}`);t_(t.cwd)}catch(e){tB(b("sidebar.newScratchSessionFailed",{error:e instanceof Error?e.message:String(e)}))}finally{tO(!1)}},[t_,b]),tq=(0,i.useCallback)(e=>{em(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]),tK=tM(F),tV=null===tK?null:N(tK),tJ=(0,i.useMemo)(()=>new Map(ey.projects.map(e=>[e.key,e])),[ey.projects]),tG=I(E);if(null!==tK){let e=N(tK);tG.some(t=>N(t)===e)||tG.unshift(tK)}let tY=T(tG,ey.projects),tZ=tY.filter(e=>eS||!tJ.get(N(e))?.hidden),tX=tY.some(e=>tJ.get(N(e))?.hidden),tQ=()=>{eb(null),eV(!1),eG(!1),eZ(""),eQ(null),e4(null),eW("")},t0=async(e,t)=>{tQ();try{await tu([{key:N(e),path:e,hidden:t}]),t&&tV&&tV===N(e)&&_(null),t||tY.some(t=>N(t)!==N(e)&&tJ.get(N(t))?.hidden)||eC(!1)}catch{}},t1=async e=>{if(e3.current){e3.current=!1,eM(null);return}let t=e$.trim();if(t===(tJ.get(N(e))?.alias??""))return void eM(null);ez(null);try{await tu([{key:N(e),path:e,alias:t||null}]),eM(null)}catch{ez(b("sidebar.projectUpdateFailed"))}},t2=async(e,t)=>{if(q)return;let n=tZ.indexOf(e),r=n+t;if(n<0||r<0||r>=tZ.length)return;let i=new Set(tZ),a=tY.map((e,t)=>i.has(e)?t:-1).filter(e=>e>=0),s=[...tY],l=a[n],o=a[r];[s[l],s[o]]=[s[o],s[l]],tQ();try{await tu(s.map((e,t)=>({key:N(e),path:e,order:t})))}catch{}},t4=new Map;for(let e of E){let t=e.projectRoot??e.cwd;if(!t)continue;let n=N(t),r=t4.get(n);r?r.push(e):t4.set(n,[e])}let t5=(0,i.useMemo)(()=>{let e=new Map;for(let t of E){let n=t.projectRoot??t.cwd;if(!n)continue;let r=N(n),i=e.get(r);i||(i={running:0,unread:0},e.set(r,i)),tt.has(t.id)&&i.running++,tr.has(t.id)&&i.unread++}return e},[E,tt,tr]),t6=q.trim().toLowerCase(),t8=q.length>0,t3=tZ.flatMap(e=>{let t=e.replace(/[\\/]+$/,"").split(/[\\/]/).at(-1)||e,n=N(e),r=tJ.get(n),i=r?.alias??t,a=(t4.get(n)??[]).slice().sort((e,t)=>{let n=Number(ta.has(t.id))-Number(ta.has(e.id));return 0!==n?n:t.modified.localeCompare(e.modified)});if(!t6)return[{project:e,key:n,name:i,sessions:a,hidden:r?.hidden===!0}];let s=i.toLowerCase().includes(t6)||t.toLowerCase().includes(t6),l=a.filter(e=>(e.name||e.firstMessage.slice(0,50)||e.id.slice(0,12)).toLowerCase().includes(t6));return s||0!==l.length?[{project:e,key:n,name:i,sessions:s?a:l,hidden:r?.hidden===!0}]:[]}),t7=[],t9=[];for(let e of t3){let t=e.key===tV||(t5.get(e.key)?.running??0)>0;(function(e){let t=e.trim().replace(/\\/g,"/").toLowerCase();return!!(/^[a-z]:\/?$/.test(t)||"/"===t||/(^|\/)appdata\/local\/temp(\/|$)/.test(t)||/^\/(?:var\/|private\/)?tmp(?:\/|$)/.test(t)||/^[a-z]:\/(?:tmp|temp)(?:\/|$)/.test(t)||/(^|\/)(?:users|home)\/[^/]+\/\.omp(\/|$)/.test(t))||t.split("/").some(e=>C.some(t=>e.startsWith(t)))})(e.project)&&!t?t9.push(e):t7.push(e)}let ne={running:0,unread:0};for(let e of t9){let t=t5.get(e.key);t&&(ne.running+=t.running,ne.unread+=t.unread)}let nt=t8||eN,nn=[...t7.map(e=>({kind:"project",group:e})),...t9.length>0?[{kind:"temporary"}]:[],...nt?t9.map(e=>({kind:"project",group:e})):[]],nr=function(e){let t=new Map;for(let n of e){let e=n.toLowerCase();t.set(e,(t.get(e)??0)+1)}return new Set([...t].filter(([,e])=>e>1).map(([e])=>e))}(nn.flatMap(e=>"project"===e.kind?[e.group.name]:[])),ni=(0,i.useMemo)(()=>(function(e,t,n,r,i="Priority",a=new Set,s="Pinned"){let l=e.filter(e=>!e.transient).slice().sort((e,t)=>{let n=Date.parse(e.modified),r=Date.parse(t.modified);return(Number.isFinite(r)?r:0)-(Number.isFinite(n)?n:0)}),o=l.filter(e=>a.has(e.id)),d=[],c=new Map,u=0;for(let e of l){if(a.has(e.id))continue;if(t.has(e.id)){d.push(e);continue}let n=new Date(e.modified);if(u>=10)continue;u+=1;let r=[n.getFullYear(),String(n.getMonth()+1).padStart(2,"0"),String(n.getDate()).padStart(2,"0")].join("-"),i=c.get(r);i?i.push(e):c.set(r,[e])}let p=[];for(let e of(o.length>0&&p.push({key:"pinned",label:s,running:!1,sessions:o}),d.length>0&&p.push({key:"priority",label:i,running:!0,sessions:d}),[...c.keys()].sort().reverse()))p.push({key:e,label:function(e,t,n){let[r,i,a]=e.split("-").map(Number),s=new Date(r,i-1,a),l=Math.round((Date.UTC(t.getFullYear(),t.getMonth(),t.getDate())-Date.UTC(s.getFullYear(),s.getMonth(),s.getDate()))/864e5);return 0===l||1===l?new Intl.RelativeTimeFormat(n,{numeric:"auto"}).format(-l,"day"):l>=0&&l<7?new Intl.DateTimeFormat(n,{weekday:"long"}).format(s):new Intl.DateTimeFormat(n,{month:"short",day:"numeric"}).format(s)}(e,n,r),running:!1,sessions:c.get(e)??[]});return p})(E,tt,new Date,y,b("navigator.priority"),ta,b("sidebar.pinned")),[y,ta,tt,E,b]),na=!!(eU?.isGit&&eU.isTopLevel&&F&&tK===eU.projectRoot),ns=eU?.worktrees.find(e=>e.path===F)??eU?.worktrees.find(e=>e.isMain),nl=(eU?.worktrees.length??0)>=8,no=nl&&eP.trim()?(eU?.worktrees??[]).filter(e=>(e.branch??et(e.path,D)).toLowerCase().includes(eP.trim().toLowerCase())):eU?.worktrees??[],nd=(()=>{if(!tm)return[];let e="project"===tm.kind?t4.get(N(tm.project))??[]:ni.flatMap(e=>e.sessions),t=new Set;return e.filter(e=>!(e.transient||t.has(e.id))&&(t.add(e.id),!0))})(),nc=nd.filter(e=>!tt.has(e.id)),nu=e=>{let t=new Set;for(let n of e)n.transient||tt.has(n.id)||t.has(n.id)||t.add(n.id);return t.size},np=void 0!==m&&f;return(0,r.jsxs)("div",{className:"session-navigator",tabIndex:-1,style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden",outline:"none"},children:[eF&&(0,r.jsx)(B?K:H,{busy:eH,error:eD,onCancel:()=>{e_(!1),eO(null)},onSelect:e=>void tA(e)}),tm&&(0,r.jsx)(eo,{scope:tm,eligible:nc.length,runningExcluded:nd.length-nc.length,busy:tg,error:tv,onCancel:ty,onConfirm:()=>void tw(nc)}),(0,r.jsx)("div",{className:"session-navigator-header",style:{padding:"4px 10px",borderBottom:"1px solid var(--border)",flexShrink:0},children:(0,r.jsxs)("div",{className:"session-navigator-titlebar",style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[(0,r.jsx)(ea,{}),(0,r.jsxs)("div",{style:{display:"flex",gap:12},children:[(0,r.jsx)("button",{className:"navigator-icon-action",onClick:()=>t_(),disabled:!F,style:{display:"flex",alignItems:"center",justifyContent:"center",background:"var(--bg-hover)",border:"1px solid var(--border)",color:F?"var(--text-muted)":"var(--text-dim)",cursor:F?"pointer":"not-allowed",width:32,height:32,padding:0,borderRadius:7,fontSize:12,flexShrink:0,transition:"background 0.12s, color 0.12s, border-color 0.12s"},title:F?b("sidebar.newSessionTitle",{path:F}):b("sidebar.selectProject"),"aria-label":F?b("sidebar.newSessionTitle",{path:F}):b("sidebar.selectProject"),onMouseEnter:e=>{F&&(e.currentTarget.style.background="var(--bg-selected)",e.currentTarget.style.color="var(--accent)")},onMouseLeave:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color=F?"var(--text-muted)":"var(--text-dim)",e.currentTarget.style.borderColor="var(--border)"},children:(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"6",y1:"1",x2:"6",y2:"11"}),(0,r.jsx)("line",{x1:"1",y1:"6",x2:"11",y2:"6"})]})}),(0,r.jsx)("button",{className:`navigator-icon-action${e9?" is-success":""}`,onClick:()=>tp(!1,!0),style:{display:"flex",alignItems:"center",justifyContent:"center",background:e9?"rgba(74,222,128,0.18)":"var(--bg-hover)",border:`1px solid ${e9?"rgba(74,222,128,0.4)":"var(--border)"}`,color:e9?"#4ade80":"var(--text-muted)",cursor:"pointer",width:32,height:32,borderRadius:7,padding:0,flexShrink:0,transition:"background 0.3s, color 0.3s, border-color 0.3s"},onMouseEnter:e=>{e9||(e.currentTarget.style.background="var(--bg-selected)",e.currentTarget.style.color="var(--accent)")},onMouseLeave:e=>{e9||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text-muted)",e.currentTarget.style.borderColor="var(--border)")},title:b("sidebar.refresh"),children:e9?(0,r.jsx)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"var(--success)",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}):(0,r.jsxs)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}),(0,r.jsx)("path",{d:"M3 3v5h5"})]})})]})]})}),B&&!np&&(0,r.jsx)("button",{type:"button",className:"navigator-cloud-project",onClick:tz,style:{margin:"10px 12px 0",minHeight:44,flexShrink:0,border:"1px solid var(--border)",borderRadius:7,background:"var(--bg-panel)",color:"var(--text)",fontSize:13,fontWeight:600,cursor:"pointer"},children:b("cloudProjects.launch")}),(0,r.jsxs)("div",{className:"navigator-mode-bar",style:{display:"flex",alignItems:"center",gap:6,minHeight:42,padding:"6px 8px 4px",flexShrink:0},children:[(0,r.jsxs)("div",{className:"navigator-mode-switcher",role:"toolbar","aria-label":b("navigator.toolbar"),style:{display:"flex",alignItems:"center",gap:2,flex:1,minWidth:0,padding:2,border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-panel)"},children:[k.map(e=>{let t="projects"===e?b("sidebar.projects"):b("navigator.priority"),n=!np&&J===e;return(0,r.jsx)("button",{type:"button","aria-label":b("navigator.view",{label:t}),"aria-pressed":n,"aria-controls":`navigator-${e}-panel`,"data-navigator-mode":e,onClick:()=>{tN(e),np&&g?.(!1)},style:{minWidth:0,minHeight:26,flex:1,padding:"3px 4px",border:"none",borderRadius:4,background:n?"var(--bg-selected)":"transparent",color:n?"var(--text)":"var(--text-dim)",cursor:"pointer",fontSize:10,fontWeight:n?600:500,whiteSpace:"nowrap"},children:t},e)}),void 0!==m&&(0,r.jsx)("button",{type:"button","aria-label":b("navigator.view",{label:v("translator.tab")}),"aria-pressed":np,"aria-controls":"navigator-translator-panel","data-navigator-mode":"translator",onClick:()=>g?.(!np),style:{minWidth:0,minHeight:26,flex:1,padding:"3px 4px",border:"none",borderRadius:4,background:np?"var(--bg-selected)":"transparent",color:np?"var(--text)":"var(--text-dim)",cursor:"pointer",fontSize:10,fontWeight:np?600:500,whiteSpace:"nowrap"},children:v("translator.tab")})]}),!np&&"projects"===J&&(0,r.jsx)("button",{type:"button",onClick:()=>eC(e=>!e),disabled:!tX,title:b("sidebar.projectShowHidden"),"aria-label":b("sidebar.projectShowHidden"),"aria-pressed":eS,style:{display:"flex",alignItems:"center",justifyContent:"center",width:26,height:26,padding:0,border:"none",borderRadius:5,background:eS?"var(--bg-selected)":"transparent",color:eS?"var(--accent)":"var(--text-dim)",cursor:tX?"pointer":"default",opacity:tX?1:.45,flexShrink:0},children:(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M2.5 12s3.5-6 9.5-6 9.5 6 9.5 6-3.5 6-9.5 6-9.5-6-9.5-6Z"}),(0,r.jsx)("circle",{cx:"12",cy:"12",r:"2.5"}),!eS&&(0,r.jsx)("path",{d:"m4 4 16 16"})]})}),!np&&"projects"===J&&(0,r.jsx)("button",{className:"navigator-add-project",type:"button",onClick:tz,title:b("sidebar.addProject"),"aria-label":b("sidebar.addProject"),style:{display:"flex",alignItems:"center",justifyContent:"center",width:28,height:28,padding:0,border:"none",borderRadius:6,background:"var(--bg-hover)",color:"var(--text-muted)",cursor:"pointer",transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)"},onMouseLeave:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text-muted)"},children:(0,r.jsxs)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M3 7.5A2.5 2.5 0 0 1 5.5 5H9l2 2h7.5A2.5 2.5 0 0 1 21 9.5v7A2.5 2.5 0 0 1 18.5 19h-13A2.5 2.5 0 0 1 3 16.5v-9Z"}),(0,r.jsx)("path",{d:"M15.5 10.5v5M13 13h5"})]})})]}),np&&m,!np&&"projects"===J&&(0,r.jsxs)("label",{className:"navigator-search",style:{position:"relative",display:"block",margin:"0 8px 8px"},children:[(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",style:{position:"absolute",left:10,top:"50%",transform:"translateY(-50%)",color:"var(--text-dim)",pointerEvents:"none"},children:[(0,r.jsx)("circle",{cx:"11",cy:"11",r:"7"}),(0,r.jsx)("path",{d:"m20 20-3.5-3.5"})]}),(0,r.jsx)("input",{className:"navigator-search-input",type:"search",value:q,onChange:e=>V(e.target.value),onKeyDown:e=>{"Escape"===e.key&&(e.preventDefault(),V(""),e.currentTarget.blur())},placeholder:b("sidebar.searchProjectsAndSessions"),"aria-label":b("sidebar.searchProjectsAndSessions"),style:{width:"100%",height:34,padding:"0 10px 0 32px",border:"1px solid var(--border)",borderRadius:7,outline:"none",background:"var(--bg-hover)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:11}})]}),!np&&"projects"===J&&(0,r.jsxs)("div",{id:"navigator-projects-panel",className:"navigator-session-list",style:{flex:"1 1 auto",overflowY:"auto",minHeight:80,padding:"0 6px 10px"},children:[(L||!ek)&&(0,r.jsx)("div",{style:{padding:"12px 8px",color:"var(--text-muted)",fontSize:12},children:b("sidebar.loading")}),z&&(0,r.jsx)("div",{style:{padding:"10px 8px",color:"var(--danger)",fontSize:12},children:z}),eA&&(0,r.jsx)("div",{style:{padding:"10px 8px",color:"var(--danger)",fontSize:12},children:eA}),!L&&ek&&!z&&0===t3.length&&(0,r.jsx)("div",{style:{padding:"12px 8px",color:"var(--text-muted)",fontSize:12},children:t6?b("sidebar.noMatchingProjects"):b("sidebar.noSessions")}),!L&&ek&&!z&&nn.map(t=>{let n,i,a;if("temporary"===t.kind)return(0,r.jsx)("div",{className:"navigator-project-group",children:(0,r.jsxs)("button",{type:"button",className:"navigator-project-row","aria-expanded":nt,title:b("sidebar.temporaryProjects"),onClick:()=>eI(e=>!e),style:{display:"flex",alignItems:"center",gap:6,width:"100%",minHeight:34,padding:"0 6px 0 2px",border:"none",background:"transparent",color:"var(--text-muted)",cursor:"pointer",textAlign:"left",fontSize:"var(--seed-font-size-t2-static)",fontWeight:600},children:[(0,r.jsx)("span",{style:{display:"flex",alignItems:"center",justifyContent:"center",width:24,height:28,flexShrink:0,color:"var(--text-dim)"},children:(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{transform:nt?"rotate(0deg)":"rotate(-90deg)",transition:"transform 0.12s"},children:(0,r.jsx)("polyline",{points:"2.5 4 6 7.5 9.5 4"})})}),(0,r.jsx)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:b("sidebar.temporaryProjects")}),(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:10,flexShrink:0},children:t9.length}),ef(ne,b)]})},"navigator-temporary-projects");let{project:s,key:l,name:o,sessions:d,hidden:c}=t.group,u=l===tV,p=nr.has(o.toLowerCase())&&et((i=Math.max((n=s.trim().replace(/[\\/]+$/,"")).lastIndexOf("\\"),n.lastIndexOf("/")))<=0?"":n.slice(0,i),D)||null,h=!eh.has(s)&&!t6,m=ei.has(s),f=eT===s,g=tZ.indexOf(s),x=eE||t8||g<=0,v=eE||t8||g>=tZ.length-1,y=function(e){let t=new Map;for(let n of e)t.set(n.id,{session:n,children:[]});let n=new Map;for(let t of e)t.parentSessionId&&n.set(t.id,t.parentSessionId);let r=[];for(let e of t.values()){let i=function(e){let r=n.get(e),i=new Set;for(;r&&!i.has(r);){if(i.add(r),t.has(r))return r;r=n.get(r)}return null}(e.session.id);i?t.get(i).children.push(e):r.push(e)}let i=e=>{e.sort((e,t)=>t.session.modified.localeCompare(e.session.modified)),e.forEach(e=>i(e.children))};return i(r),r}(m?d:d.slice(0,5)),k=d.length>5;return(0,r.jsxs)("section",{className:"navigator-project-group",style:{marginBottom:h?3:9},children:[(0,r.jsxs)("div",{className:`navigator-project-row${u?" is-selected":""}`,ref:ev===s?e5:void 0,onMouseEnter:()=>ex(s),onMouseLeave:()=>ex(e=>e===s&&ev!==s?null:e),style:{display:"flex",alignItems:"center",minHeight:34,position:"relative",borderRadius:6,background:u?"var(--bg-hover)":"transparent",opacity:c?.55:1},children:[(0,r.jsx)("button",{type:"button",onClick:()=>tq(s),title:h?b("sidebar.expandProject"):b("sidebar.collapseProject"),"aria-label":h?b("sidebar.expandProject"):b("sidebar.collapseProject"),"aria-expanded":!h,style:{display:"flex",alignItems:"center",justifyContent:"center",width:24,height:28,marginLeft:2,padding:0,border:"none",background:"transparent",color:"var(--text-dim)",cursor:"pointer",flexShrink:0},children:(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{transform:h?"rotate(-90deg)":"rotate(0deg)",transition:"transform 0.12s"},children:(0,r.jsx)("polyline",{points:"2.5 4 6 7.5 9.5 4"})})}),f?(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,flex:1,minWidth:0,height:34,padding:"0 4px"},children:[(0,r.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0,color:"var(--accent)"},children:(0,r.jsx)("path",{d:"M3 7.5A2.5 2.5 0 0 1 5.5 5H9l2 2h7.5A2.5 2.5 0 0 1 21 9.5v7A2.5 2.5 0 0 1 18.5 19h-13A2.5 2.5 0 0 1 3 16.5v-9Z"})}),(0,r.jsx)("input",{ref:e8,value:e$,onChange:e=>eR(e.target.value),onBlur:()=>void t1(s),onKeyDown:e=>{"Enter"===e.key?(e.preventDefault(),e.currentTarget.blur()):"Escape"===e.key&&(e.preventDefault(),e3.current=!0,eM(null))},"aria-label":b("sidebar.projectAlias"),style:{flex:1,minWidth:0,height:24,padding:"2px 6px",border:"1px solid var(--accent)",borderRadius:5,outline:"none",background:"var(--bg)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:12,fontWeight:600}})]}):(0,r.jsxs)("button",{className:"navigator-project-name",type:"button",onClick:()=>_(s),title:s,style:{display:"flex",alignItems:"center",gap:8,flex:1,minWidth:0,height:34,padding:"0 4px",border:"none",background:"transparent",color:u?"var(--text)":"var(--text-muted)",cursor:"pointer",textAlign:"left",fontSize:12.5,fontWeight:u?600:500},children:[(0,r.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0,color:u?"var(--accent)":"var(--text-dim)"},children:(0,r.jsx)("path",{d:"M3 7.5A2.5 2.5 0 0 1 5.5 5H9l2 2h7.5A2.5 2.5 0 0 1 21 9.5v7A2.5 2.5 0 0 1 18.5 19h-13A2.5 2.5 0 0 1 3 16.5v-9Z"})}),(0,r.jsx)("span",{style:{flexShrink:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:o}),null===p?null:(0,r.jsx)("span",{style:{flexShrink:2,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:10},children:p}),ef(t5.get(l),b)]}),(0,r.jsx)("button",{type:"button",onClick:()=>t_(s),title:b("sidebar.newSessionTitle",{path:s}),"aria-label":b("sidebar.newSessionTitle",{path:s}),style:{display:"flex",alignItems:"center",justifyContent:"center",width:28,height:28,padding:0,border:"none",borderRadius:5,background:"transparent",color:"var(--text-dim)",cursor:"pointer",opacity:w||eg===s?1:0,pointerEvents:w||eg===s?"auto":"none",transition:"opacity 0.12s, background 0.12s, color 0.12s",flexShrink:0},onFocus:()=>ex(s),onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-selected)",e.currentTarget.style.color="var(--accent)"},onMouseLeave:e=>{e.currentTarget.style.background="transparent",e.currentTarget.style.color="var(--text-dim)"},children:(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"6",y1:"1.5",x2:"6",y2:"10.5"}),(0,r.jsx)("line",{x1:"1.5",y1:"6",x2:"10.5",y2:"6"})]})}),(0,r.jsxs)("div",{style:{position:"static",flexShrink:0},children:[(0,r.jsx)("button",{type:"button",onClick:()=>{eb(ev===s?null:s),eV(!1),eG(!1),eQ(null),u||_(s)},title:b("sidebar.projectActions"),"aria-label":b("sidebar.projectActions"),"aria-expanded":ev===s,style:{display:"flex",alignItems:"center",justifyContent:"center",width:26,height:26,marginRight:3,padding:0,border:"none",borderRadius:5,background:ev===s?"var(--bg-selected)":"transparent",color:u&&ns&&!ns.isMain?"var(--accent)":"var(--text-dim)",cursor:"pointer",opacity:w||eg===s||ev===s?1:0,pointerEvents:w||eg===s||ev===s?"auto":"none",transition:"opacity 0.12s, background 0.12s, color 0.12s"},onFocus:()=>ex(s),children:(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"currentColor","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"3",cy:"7",r:"1.1"}),(0,r.jsx)("circle",{cx:"7",cy:"7",r:"1.1"}),(0,r.jsx)("circle",{cx:"11",cy:"7",r:"1.1"})]})}),(0,r.jsxs)(er,{open:ev===s,style:{position:"absolute",top:"calc(100% + 4px)",right:3,width:"min(260px, calc(100vw - 24px))",zIndex:110,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:8,boxShadow:"var(--shadow-float)",boxSizing:"border-box",overflow:"hidden"},children:[na&&eU&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("button",{type:"button",onClick:()=>eV(e=>!e),title:ns?b("sidebar.switchWorktreeTitle",{path:ns.path}):b("sidebar.switchWorktree"),"aria-label":b("sidebar.worktrees"),"aria-expanded":eK,style:{display:"flex",alignItems:"center",gap:8,width:"100%",minHeight:34,padding:"0 10px",border:"none",borderBottom:eK?"1px solid var(--border)":"none",background:eK?"var(--bg-selected)":"transparent",color:"var(--text-muted)",cursor:"pointer",textAlign:"left",fontSize:11},children:[(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"6",y1:"3",x2:"6",y2:"15"}),(0,r.jsx)("circle",{cx:"18",cy:"6",r:"3"}),(0,r.jsx)("circle",{cx:"6",cy:"18",r:"3"}),(0,r.jsx)("path",{d:"M18 9a9 9 0 0 1-9 9"})]}),(0,r.jsx)("span",{style:{flex:1},children:b("sidebar.worktrees")}),(0,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"4 2.5 8 6 4 9.5"})})]}),(0,r.jsxs)(er,{open:eK,style:{position:"static",width:"auto",zIndex:100,background:"var(--bg)",border:"none",borderTop:"1px solid var(--border)",borderRadius:0,boxShadow:"none",boxSizing:"border-box",overflow:"hidden"},children:[nl&&(0,r.jsx)("div",{style:{padding:"6px 8px",borderBottom:"1px solid var(--border)"},children:(0,r.jsx)("input",{value:eP,onChange:e=>eW(e.target.value),onKeyDown:e=>{"Escape"===e.key&&(eW(""),eV(!1))},placeholder:b("sidebar.filterWorktrees"),autoFocus:!0,style:{width:"100%",fontSize:11,fontFamily:"var(--font-mono)",padding:"5px 8px",border:"1px solid var(--border)",borderRadius:5,outline:"none",background:"var(--bg)",color:"var(--text)",boxSizing:"border-box"}})}),(0,r.jsxs)("div",{style:{maxHeight:"min(40vh, 300px)",overflowY:"auto"},children:[no.map(e=>{let t=e.path===F||e.isMain&&!eU.worktrees.some(e=>e.path===F);return e2===e.path?(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6,padding:"7px 10px",borderBottom:"1px solid var(--border)",background:"rgba(239,68,68,0.06)"},children:[(0,r.jsx)("span",{style:{flex:1,fontSize:11,color:"var(--text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:b("sidebar.forceRemoveCheckout")}),(0,r.jsx)("button",{onClick:()=>void tW(e.path,!0),disabled:e0,style:{padding:"3px 9px",background:"var(--danger)",border:"none",borderRadius:5,color:"var(--bg)",fontSize:11,fontWeight:600,cursor:"pointer",flexShrink:0},children:b("sidebar.force")}),(0,r.jsx)("button",{onClick:()=>e4(null),style:{padding:"3px 9px",background:"var(--bg-hover)",border:"1px solid var(--border)",borderRadius:5,color:"var(--text-muted)",fontSize:11,cursor:"pointer",flexShrink:0},children:b("sidebar.cancel")})]},e.path):(0,r.jsxs)("div",{className:"wt-row",style:{display:"flex",alignItems:"center",borderBottom:"1px solid var(--border)"},children:[(0,r.jsxs)("button",{onClick:()=>{_(e.path),eV(!1),eQ(null),eW("")},title:e.path,style:{flex:1,minWidth:0,display:"flex",alignItems:"center",gap:7,padding:"8px 10px",background:"var(--bg)",border:"none",color:t?"var(--text)":"var(--text-muted)",cursor:"pointer",textAlign:"left",fontSize:11,fontFamily:"var(--font-mono)"},children:[t?(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,r.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,r.jsx)("span",{style:{width:10,flexShrink:0}}),(0,r.jsx)(en,{text:e.branch??et(e.path,D),style:{flex:1}}),e.isMain&&(0,r.jsx)("span",{style:{flexShrink:0,color:"var(--text-dim)",fontSize:10},children:b("sidebar.main")})]}),!e.isMain&&(0,r.jsx)("button",{onClick:()=>void tW(e.path,!1),disabled:e0,title:b("sidebar.removeWorktreeTitle",{path:e.path}),style:{display:"flex",alignItems:"center",justifyContent:"center",width:34,height:28,padding:0,marginRight:4,background:"none",border:"none",color:"var(--text-dim)",cursor:"pointer",borderRadius:5,flexShrink:0,transition:"color 0.12s, background 0.12s"},onMouseEnter:e=>{e.currentTarget.style.color="#ef4444",e.currentTarget.style.background="rgba(239,68,68,0.08)"},onMouseLeave:e=>{e.currentTarget.style.color="var(--text-dim)",e.currentTarget.style.background="none"},children:(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("polyline",{points:"3 6 5 6 21 6"}),(0,r.jsx)("path",{d:"M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"}),(0,r.jsx)("path",{d:"M10 11v6M14 11v6"}),(0,r.jsx)("path",{d:"M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2"})]})})]},e.path)}),nl&&0===no.length&&eP.trim()&&(0,r.jsx)("div",{style:{padding:"8px 10px",fontSize:11,color:"var(--text-dim)"},children:b("sidebar.noMatchingWorktrees")})]}),eJ?(0,r.jsxs)("div",{style:{padding:"6px 8px"},children:[(0,r.jsx)("input",{ref:e6,value:eY,onChange:e=>{eZ(e.target.value),eQ(null)},onKeyDown:e=>{"Enter"===e.key&&(e.preventDefault(),tP()),"Escape"===e.key&&(eG(!1),eZ(""),eQ(null))},placeholder:b("sidebar.branchName"),style:{width:"100%",fontSize:11,fontFamily:"var(--font-mono)",padding:"5px 8px",border:"1px solid var(--accent)",borderRadius:5,outline:"none",background:"var(--bg)",color:"var(--text)",boxSizing:"border-box"}}),(0,r.jsxs)("div",{style:{display:"flex",gap:5,marginTop:5},children:[(0,r.jsx)("button",{onClick:()=>void tP(),disabled:e0||!eY.trim(),style:{flex:1,padding:"4px 0",background:"var(--accent)",border:"none",borderRadius:5,color:"var(--bg)",fontSize:11,fontWeight:600,cursor:e0||!eY.trim()?"not-allowed":"pointer",opacity:e0||!eY.trim()?.65:1},children:e0?b("sidebar.creating"):b("sidebar.create")}),(0,r.jsx)("button",{onClick:()=>{eG(!1),eZ(""),eQ(null)},style:{flex:1,padding:"4px 0",background:"var(--bg-hover)",border:"1px solid var(--border)",borderRadius:5,color:"var(--text-muted)",fontSize:11,cursor:"pointer"},children:b("sidebar.cancel")})]})]}):(0,r.jsxs)("button",{onClick:e=>{e.stopPropagation(),eG(!0),eQ(null),setTimeout(()=>e6.current?.focus(),0)},title:b("sidebar.createWorktreeTitle"),style:{display:"flex",alignItems:"center",gap:7,width:"100%",padding:"8px 10px",background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",textAlign:"left",fontSize:11},children:[(0,r.jsxs)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.1",strokeLinecap:"round",style:{flexShrink:0},children:[(0,r.jsx)("line",{x1:"5",y1:"1",x2:"5",y2:"9"}),(0,r.jsx)("line",{x1:"1",y1:"5",x2:"9",y2:"5"})]}),(0,r.jsx)("span",{children:b("sidebar.newWorktree")})]}),eX&&(0,r.jsx)("div",{style:{padding:"5px 10px 8px",color:"var(--danger)",fontSize:11,lineHeight:1.35,overflowWrap:"anywhere"},children:eX})]})]}),(0,r.jsxs)("button",{type:"button",disabled:eE,onClick:()=>{let e;return e=tJ.get(N(s))?.alias??"",void(e3.current=!1,ez(null),eR(e),eM(s),tQ())},style:{display:"flex",alignItems:"center",gap:8,width:"100%",minHeight:34,padding:"0 10px",border:"none",borderTop:"1px solid var(--border)",background:"transparent",color:"var(--text-muted)",cursor:eE?"default":"pointer",textAlign:"left",fontSize:11,opacity:eE?.55:1},children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"m4 20 4.5-1 10-10a2.1 2.1 0 0 0-3-3l-10 10L4 20Z"}),(0,r.jsx)("path",{d:"m13.5 8 3 3"})]}),b(tJ.get(N(s))?.alias?"sidebar.projectAliasEdit":"sidebar.projectAlias")]}),(0,r.jsxs)("button",{type:"button",disabled:x,title:t8?b("sidebar.projectMoveDisabledWhileFiltering"):void 0,onClick:()=>void t2(s,-1),style:{display:"flex",alignItems:"center",gap:8,width:"100%",minHeight:34,padding:"0 10px",border:"none",background:"transparent",color:"var(--text-muted)",cursor:x?"default":"pointer",textAlign:"left",fontSize:11,opacity:x?.55:1},children:[(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m6 15 6-6 6 6"})}),b("sidebar.projectMoveUp")]}),(0,r.jsxs)("button",{type:"button",disabled:v,title:t8?b("sidebar.projectMoveDisabledWhileFiltering"):void 0,onClick:()=>void t2(s,1),style:{display:"flex",alignItems:"center",gap:8,width:"100%",minHeight:34,padding:"0 10px",border:"none",background:"transparent",color:"var(--text-muted)",cursor:v?"default":"pointer",textAlign:"left",fontSize:11,opacity:v?.55:1},children:[(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m6 9 6 6 6-6"})}),b("sidebar.projectMoveDown")]}),(0,r.jsxs)("button",{type:"button",disabled:eE,onClick:()=>void t0(s,!c),style:{display:"flex",alignItems:"center",gap:8,width:"100%",minHeight:34,padding:"0 10px",border:"none",background:"transparent",color:"var(--text-muted)",cursor:eE?"default":"pointer",textAlign:"left",fontSize:11,opacity:eE?.55:1},children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M2.5 12s3.5-6 9.5-6 9.5 6 9.5 6-3.5 6-9.5 6-9.5-6-9.5-6Z"}),(0,r.jsx)("circle",{cx:"12",cy:"12",r:"2.5"}),!c&&(0,r.jsx)("path",{d:"m4 4 16 16"})]}),b(c?"sidebar.projectUnhide":"sidebar.projectHide")]}),(a=0===nu(t4.get(l)??[])||tg,(0,r.jsxs)("button",{type:"button",disabled:a,onClick:()=>{tQ(),tb(null),tf({kind:"project",project:s,label:o})},style:{display:"flex",alignItems:"center",gap:8,width:"100%",minHeight:34,padding:"0 10px",border:"none",borderTop:"1px solid var(--border)",background:"transparent",color:"var(--text-muted)",cursor:a?"default":"pointer",textAlign:"left",fontSize:11,opacity:a?.55:1},children:[(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M4 7h16M9 7V5h6v2M6 7l1 13h10l1-13"})}),b("sidebar.clearProjectSessions")]}))]})]})]}),!h&&0===d.length&&u&&(0,r.jsx)("div",{style:{padding:"6px 12px 7px 32px",color:"var(--text-dim)",fontSize:11},children:b("sidebar.noSessions")}),!h&&y.length>0&&(0,r.jsx)("div",{style:{paddingLeft:12},children:y.map(t=>(0,r.jsx)(ep,{node:t,selectedSessionId:e,runningSessionIds:tt,unreadSessionIds:tr,pinnedSessionIds:ta,onSelectSession:tF,onTogglePinnedSession:tI,onRenamed:tp,onSessionDeleted:th,onSessionArchived:tS,depth:0},t.session.id))}),!h&&k&&(0,r.jsx)("button",{type:"button",onClick:()=>{ed(e=>{let t=new Set(e);return t.has(s)?t.delete(s):t.add(s),t})},style:{display:"block",margin:"3px 0 3px 32px",padding:"5px 8px",border:"none",background:"transparent",color:"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left"},children:m?b("sidebar.showLess"):b("sidebar.showMore")})]},s)})]}),!np&&(0,r.jsx)(eu,{refreshKey:tk,selectedSessionId:e,onSelectSession:tF,onRestored:tS}),!np&&"priority"===J&&(0,r.jsxs)("div",{id:"navigator-priority-panel",style:{flex:"1 1 auto",minHeight:80,overflowY:"auto",padding:"0 6px 10px"},children:[L&&(0,r.jsx)("div",{style:{padding:"12px 8px",color:"var(--text-muted)",fontSize:12},children:b("sidebar.loading")}),z&&(0,r.jsx)("div",{role:"alert",style:{padding:"10px 8px",color:"var(--danger)",fontSize:12},children:z}),!L&&!z&&(x=nu(ni.flatMap(e=>e.sessions)),(0,r.jsxs)("div",{style:{display:"flex",justifyContent:"space-between",gap:8,padding:"8px 2px 2px"},children:[(0,r.jsx)("button",{type:"button",disabled:tD,onClick:()=>void tU(),title:b("sidebar.newScratchSessionTitle"),style:ee(tD,w),children:b("sidebar.newScratchSession")}),ni.length>0&&(0,r.jsx)("button",{type:"button",disabled:0===x||tg,onClick:()=>{tb(null),tf({kind:"priority"})},style:ee(0===x||tg,w),children:b("sidebar.clearPriorityList")})]})),tH&&(0,r.jsx)("div",{role:"alert",style:{padding:"6px 8px",color:"var(--danger)",fontSize:12},children:tH}),!L&&!z&&0===ni.length&&(0,r.jsx)("div",{style:{padding:"12px 8px",color:"var(--text-muted)",fontSize:12},children:b("sidebar.noSessions")}),!L&&!z&&ni.map((t,n)=>(0,r.jsxs)("section",{"aria-labelledby":`priority-group-${t.key}`,children:[(0,r.jsx)("h2",{id:`priority-group-${t.key}`,style:{margin:0,padding:0===n?"2px 8px 4px":"14px 8px 4px",color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontWeight:600},children:t.label}),t.sessions.map(t=>(0,r.jsx)(ec,{session:t,selected:t.id===e,running:tt.has(t.id),unread:tr.has(t.id),pinned:ta.has(t.id),onSelect:tF,onTogglePin:tI},t.id))]},t.key))]})]})}function eo({scope:e,eligible:t,runningExcluded:n,busy:a,error:s,onCancel:l,onConfirm:o}){let{t:d}=(0,R.s)(),c=a||0===t,u=(0,i.useRef)(null),p=(0,i.useRef)(null),h=(0,i.useRef)(a);h.current=a;let m=(0,i.useRef)(l);return m.current=l,(0,i.useEffect)(()=>{let e=u.current;if(!e)return;let t=document.activeElement,n=t instanceof HTMLElement&&t!==document.body&&t!==document.documentElement&&!e.contains(t)?t:null;(p.current??e).focus();let r=t=>{if("Escape"===t.key){if(h.current)return;t.preventDefault(),m.current();return}if("Tab"!==t.key)return;let n=Array.from(e.querySelectorAll('a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])')).filter(e=>e.getClientRects().length>0),r=document.activeElement;if(0===n.length){t.preventDefault(),e.focus();return}let i=n[0],a=n[n.length-1];t.shiftKey&&(r===i||!e.contains(r))?(t.preventDefault(),a.focus()):t.shiftKey||r!==a&&e.contains(r)||(t.preventDefault(),i.focus())};return e.addEventListener("keydown",r),()=>{e.removeEventListener("keydown",r);let t=n?.isConnected?n:e.closest(".session-navigator");t?.focus()}},[]),(0,r.jsx)("div",{role:"presentation",style:{position:"fixed",inset:0,zIndex:1100,display:"flex",alignItems:"center",justifyContent:"center",padding:16,background:"var(--scrim)"},onClick:e=>{a||e.target!==e.currentTarget||l()},children:(0,r.jsxs)("div",{ref:u,role:"alertdialog","aria-modal":"true","aria-labelledby":"bulk-clear-title","aria-describedby":"bulk-clear-body",tabIndex:-1,style:{width:420,maxWidth:"100%",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",background:"var(--bg-panel)",boxShadow:"var(--shadow-float)",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{padding:"18px 18px 14px"},children:[(0,r.jsx)("div",{id:"bulk-clear-title",style:{color:"var(--text)",fontSize:"var(--seed-font-size-t4-static)",fontWeight:600},children:d("sidebar.clearSessionsTitle")}),(0,r.jsxs)("div",{id:"bulk-clear-body",style:{marginTop:8,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.6,overflowWrap:"anywhere"},children:["project"===e.kind?d("sidebar.clearSessionsProjectBody",{project:e.label,count:t}):d("sidebar.clearSessionsPriorityBody",{count:t}),n>0&&(0,r.jsx)("div",{style:{marginTop:6},children:d("sidebar.clearSessionsRunningExcluded",{count:n})}),0===t&&(0,r.jsx)("div",{style:{marginTop:6},children:d("sidebar.clearSessionsNone")})]}),s&&(0,r.jsx)("div",{role:"alert",style:{marginTop:10,color:"var(--danger)",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.5,overflowWrap:"anywhere"},children:s})]}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",justifyContent:"flex-end",gap:8,padding:"12px 18px",borderTop:"1px solid var(--border)"},children:[(0,r.jsx)("button",{ref:p,type:"button",onClick:l,disabled:a,style:{minHeight:36,padding:"0 12px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"transparent",color:"var(--text-muted)",cursor:a?"default":"pointer",fontSize:"var(--seed-font-size-t3-static)"},children:d("sidebar.clearSessionsCancel")}),(0,r.jsx)("button",{type:"button",onClick:o,disabled:c,"aria-busy":a,style:{minHeight:36,padding:"0 14px",border:"1px solid var(--danger)",borderRadius:"var(--radius-control)",background:"transparent",color:c?"var(--text-dim)":"var(--danger)",cursor:c?"default":"pointer",fontSize:"var(--seed-font-size-t3-static)",fontWeight:600},children:d(a?"sidebar.clearSessionsBusy":"sidebar.clearSessionsConfirm")})]})]})})}function ed({filled:e=!1}){return(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:e?"currentColor":"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M12 17v5"}),(0,r.jsx)("path",{d:"M5 17h14"}),(0,r.jsx)("path",{d:"M6 3h12l-1 8 2 3H5l2-3-1-8z"})]})}function ec({session:e,selected:t,running:n,unread:i,pinned:a,onSelect:s,onTogglePin:l}){let{t:o}=(0,R.s)(),d=(e.name||e.firstMessage||e.id.slice(0,8)).replace(/\s+/g," ").trim(),c=e.cwd.split(/[\\/]/).filter(Boolean).at(-1)??"";return(0,r.jsxs)("div",{className:`priority-session-row${t?" is-selected":""}${n?" is-running":""}${i?" is-unread":""}`,style:{display:"flex",alignItems:"stretch",borderRadius:5,background:t?"var(--bg-selected)":"transparent"},children:[(0,r.jsxs)("button",{type:"button","aria-current":t?"page":void 0,onClick:()=>s(e),title:`${d}
2
2
  ${e.cwd}
3
3
  ${new Date(e.modified).toLocaleString()}`,style:{minWidth:0,flex:1,display:"block",padding:"7px 8px",border:"none",background:"transparent",color:"var(--text)",cursor:"pointer",textAlign:"left"},children:[(0,r.jsxs)("span",{style:{display:"flex",alignItems:"center",gap:6,minWidth:0},children:[(0,r.jsx)("span",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text)",fontSize:12.5,fontWeight:500,lineHeight:1.4},children:d}),n&&(0,r.jsx)(eh,{}),!n&&i&&(0,r.jsx)(em,{})]}),(0,r.jsx)("span",{style:{display:"block",marginTop:2,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-dim)",fontSize:10,fontFamily:"var(--font-mono)"},children:c})]}),(0,r.jsx)("button",{type:"button","aria-pressed":a,"aria-label":o(a?"sidebar.unpin":"sidebar.pin"),title:o(a?"sidebar.unpin":"sidebar.pin"),onClick:()=>l(e.id),style:{width:30,border:"none",background:"transparent",color:a?"var(--accent)":"var(--text-dim)",cursor:"pointer",flexShrink:0},children:(0,r.jsx)(ed,{filled:a})})]})}function eu({refreshKey:e,selectedSessionId:t,onSelectSession:n,onRestored:a}){let{t:s}=(0,R.s)(),[l,o]=(0,i.useState)(!1),[d,c]=(0,i.useState)([]);(0,i.useEffect)(()=>{let e=!1;return(async()=>{try{let t=await fetch("/api/sessions?archived=1",{cache:"no-store"});if(!t.ok)throw Error(`HTTP ${t.status}`);let n=await t.json();e||c(n.sessions)}catch{}})(),()=>{e=!0}},[e]);let u=(0,i.useCallback)(async(e,t)=>{e.stopPropagation();try{await fetch(`/api/sessions/${encodeURIComponent(t)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({archived:!1})}),a(t)}catch{}},[a]);return 0!==d.length||l?(0,r.jsxs)("section",{style:{borderTop:"1px solid var(--border)",marginTop:4},children:[(0,r.jsxs)("button",{type:"button",onClick:()=>o(e=>!e),style:{display:"flex",alignItems:"center",gap:6,width:"100%",padding:"7px 12px",background:"transparent",border:"none",color:"var(--text-muted)",cursor:"pointer",fontSize:12,fontWeight:600,textAlign:"left"},children:[(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",style:{transform:l?"rotate(0deg)":"rotate(-90deg)",transition:"transform 0.1s"},children:(0,r.jsx)("polyline",{points:"2 3.5 5 6.5 8 3.5"})}),s("sidebar.archived")," (",d.length,")"]}),l&&(0,r.jsxs)("div",{style:{paddingLeft:12},children:[0===d.length&&(0,r.jsx)("div",{style:{padding:"4px 12px 8px 20px",color:"var(--text-dim)",fontSize:11},children:s("sidebar.noArchivedSessions")}),d.map(e=>{let i=$(e.firstMessage)??e.firstMessage,a=e.name||i.slice(0,50)||e.id.slice(0,12);return(0,r.jsxs)("div",{onClick:()=>n(e),style:{height:40,display:"flex",alignItems:"center",paddingLeft:20,paddingRight:4,gap:4,cursor:"pointer",overflow:"hidden",borderLeft:e.id===t?"2px solid var(--accent)":"2px solid transparent",background:e.id===t?"var(--bg-selected)":"transparent"},children:[(0,r.jsx)("div",{style:{flex:1,minWidth:0,fontSize:12,color:"var(--text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:a}),(0,r.jsx)("button",{onClick:t=>u(t,e.id),title:s("sidebar.restore"),style:{display:"flex",alignItems:"center",justifyContent:"center",height:24,padding:"0 8px",flexShrink:0,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:5,color:"var(--text-muted)",cursor:"pointer",fontSize:11,fontWeight:500},children:s("sidebar.restore")})]},e.id)})]})]}):null}function ep({node:e,selectedSessionId:t,runningSessionIds:n,unreadSessionIds:a,pinnedSessionIds:s,onSelectSession:l,onRenamed:o,onSessionDeleted:d,onTogglePinnedSession:c,onSessionArchived:u,depth:p}){let[h,m]=(0,i.useState)(!1),f=e.children.length>0;return(0,r.jsxs)("div",{children:[(0,r.jsxs)("div",{style:{position:"relative"},children:[p>0&&(0,r.jsx)("div",{style:{position:"absolute",left:10*p+6,top:0,bottom:0,width:1,background:"var(--border)",pointerEvents:"none"}}),(0,r.jsx)(eg,{session:e.session,isSelected:e.session.id===t,isRunning:n.has(e.session.id),isUnread:a.has(e.session.id),isPinned:s.has(e.session.id),onClick:()=>l(e.session),onTogglePin:()=>c(e.session.id),onRenamed:o,onDeleted:e=>d?.(e),onArchived:e=>u?.(e),depth:p,hasChildren:f,collapsed:h,onToggleCollapse:()=>m(e=>!e)})]}),f&&!h&&(0,r.jsx)("div",{children:e.children.map(e=>(0,r.jsx)(ep,{node:e,selectedSessionId:t,runningSessionIds:n,unreadSessionIds:a,pinnedSessionIds:s,onSelectSession:l,onTogglePinnedSession:c,onRenamed:o,onSessionDeleted:d,onSessionArchived:u,depth:p+1},e.session.id))})]})}function eh(){let{t:e}=(0,R.s)();return(0,r.jsx)("span",{title:e("sidebar.agentRunning"),"aria-label":e("sidebar.agentRunning"),style:{width:14,height:14,display:"inline-flex",alignItems:"center",justifyContent:"center",flexShrink:0,color:"var(--accent)"},children:(0,r.jsx)("svg",{className:"session-running-spinner",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none","aria-hidden":"true",style:{display:"block"},children:(0,r.jsx)("path",{d:"M21 12a9 9 0 1 1-3.8-7.4",stroke:"currentColor",strokeWidth:"2.8",strokeLinecap:"round"})})})}function em(){let{t:e}=(0,R.s)();return(0,r.jsx)("span",{title:e("sidebar.newActivity"),"aria-label":e("sidebar.newSessionActivity"),style:{width:14,height:14,display:"inline-flex",alignItems:"center",justifyContent:"center",flexShrink:0,color:"var(--accent)"},children:(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none","aria-hidden":"true",style:{display:"block"},children:[(0,r.jsx)("circle",{cx:"7",cy:"7",r:"2.5",fill:"currentColor"}),(0,r.jsx)("circle",{className:"session-unread-ring",cx:"7",cy:"7",r:"3",stroke:"currentColor",strokeWidth:"1.4"})]})})}function ef(e,t){return e&&(0!==e.running||0!==e.unread)?(0,r.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:5,flexShrink:0,marginLeft:6},children:[e.running>0&&(0,r.jsxs)("span",{title:t("sidebar.agentRunning"),"aria-label":`${t("sidebar.agentRunning")} (${e.running})`,style:{display:"inline-flex",alignItems:"center",gap:3,color:"var(--accent)",fontSize:10,fontFamily:"var(--font-mono)"},children:[(0,r.jsx)("svg",{className:"session-running-spinner",width:"10",height:"10",viewBox:"0 0 24 24",fill:"none","aria-hidden":"true",style:{display:"block"},children:(0,r.jsx)("path",{d:"M21 12a9 9 0 1 1-3.8-7.4",stroke:"currentColor",strokeWidth:"2.8",strokeLinecap:"round"})}),e.running]}),e.unread>0&&(0,r.jsxs)("span",{title:t("sidebar.newSessionActivity"),"aria-label":`${t("sidebar.newSessionActivity")} (${e.unread})`,style:{display:"inline-flex",alignItems:"center",gap:3,color:"var(--accent)",fontSize:10,fontFamily:"var(--font-mono)"},children:[(0,r.jsx)("span",{style:{width:6,height:6,borderRadius:"50%",background:"currentColor",display:"inline-block"}}),e.unread]})]}):null}function eg({session:e,isSelected:t,isRunning:n,isUnread:a,isPinned:s,onClick:l,onTogglePin:o,onRenamed:d,onDeleted:c,onArchived:u,depth:p=0,hasChildren:h=!1,collapsed:m=!1,onToggleCollapse:f}){let{t:g}=(0,R.s)(),[x,v]=(0,i.useState)(!1),[b,y]=(0,i.useState)(!1),[w,k]=(0,i.useState)(""),[j,S]=(0,i.useState)(!1),[C,N]=(0,i.useState)(!1),I=(0,i.useRef)(null);(0,i.useEffect)(()=>{if(b){let e=requestAnimationFrame(()=>I.current?.select());return()=>cancelAnimationFrame(e)}},[b]);let T=$(e.firstMessage)??e.firstMessage,M=e.name||T.slice(0,50)||e.id.slice(0,12),E=(0,i.useCallback)(t=>{t.stopPropagation(),e.transient||(k(e.name||T.slice(0,50)||e.id.slice(0,12)),y(!0))},[e.name,e.transient,T,e.id]),L=(0,i.useCallback)(async()=>{let t=w.trim();if(y(!1),w!==M&&t!==(e.name??""))try{await fetch(`/api/sessions/${encodeURIComponent(e.id)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:t})}),d?.()}catch{}},[w,e.id,e.name,d,M]),A=(0,i.useCallback)(async()=>{if(!e.transient){S(!1),N(!0);try{await fetch(`/api/sessions/${encodeURIComponent(e.id)}`,{method:"DELETE"}),c?.(e.id)}catch{N(!1)}}},[e.id,e.transient,c]),z=(0,i.useCallback)(async t=>{if(t.stopPropagation(),!e.transient)try{await fetch(`/api/sessions/${encodeURIComponent(e.id)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({archived:!0})}),u?.(e.id)}catch{}},[e.id,e.transient,u]),P=(0,i.useCallback)(e=>{e.stopPropagation(),e.shiftKey?A():S(!0)},[A]),W=(0,i.useCallback)(e=>{e.stopPropagation(),A()},[A]),F=(0,i.useCallback)(e=>{e.stopPropagation(),S(!1)},[]),_=(0,i.useCallback)(t=>{(function(e,t=window){let n=new CustomEvent("pi-web:session-row-contextmenu",{cancelable:!0,detail:e});return!t.dispatchEvent(n)})({id:e.id,path:e.path,cwd:e.cwd,name:e.name,clientX:t.clientX,clientY:t.clientY,refresh:()=>{d?.()}})&&(t.preventDefault(),t.stopPropagation())},[d,e.cwd,e.id,e.name,e.path]);return(0,r.jsx)("div",{className:`navigator-session-row${t?" is-selected":""}${n?" is-running":""}${a?" is-unread":""}${j?" is-confirming":""}`,onClick:j||b?void 0:l,onContextMenu:j||b?void 0:_,onMouseEnter:()=>v(!0),onMouseLeave:()=>{v(!1)},style:{height:40,display:"flex",alignItems:"center",paddingLeft:p>0?10*p+8:8,paddingRight:4,cursor:j||b?"default":"pointer",background:t?"var(--bg-selected)":x?"var(--bg-hover)":"transparent",borderLeft:"2px solid transparent",transition:"background 0.1s",opacity:C?.5:1,gap:4,overflow:"hidden"},children:j?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{style:{flex:1,minWidth:0,fontSize:12,color:"var(--text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:g("sidebar.deleteSession",{title:M.slice(0,22)+(M.length>22?"…":"")})}),(0,r.jsxs)("div",{style:{display:"flex",gap:5,flexShrink:0},children:[(0,r.jsxs)("button",{onClick:W,style:{display:"flex",alignItems:"center",justifyContent:"center",gap:4,height:30,padding:"0 11px",background:"var(--danger)",border:"none",borderRadius:"var(--radius-control)",color:"var(--bg)",cursor:"pointer",fontSize:12,fontWeight:600,whiteSpace:"nowrap"},children:[(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("polyline",{points:"3 6 5 6 21 6"}),(0,r.jsx)("path",{d:"M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"}),(0,r.jsx)("path",{d:"M10 11v6M14 11v6"}),(0,r.jsx)("path",{d:"M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2"})]}),g("sidebar.delete")]}),(0,r.jsx)("button",{onClick:F,style:{display:"flex",alignItems:"center",justifyContent:"center",height:30,padding:"0 11px",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",color:"var(--text-muted)",cursor:"pointer",fontSize:12,fontWeight:500,whiteSpace:"nowrap"},children:g("sidebar.cancel")})]})]}):b?(0,r.jsx)("input",{ref:I,value:w,onChange:e=>k(e.target.value),onBlur:L,onKeyDown:e=>{"Enter"===e.key&&L(),"Escape"===e.key&&y(!1)},autoFocus:!0,style:{flex:1,fontSize:12,padding:"5px 8px",border:"1px solid var(--accent)",borderRadius:5,outline:"none",background:"var(--bg)",color:"var(--text)",height:30}}):(0,r.jsxs)(r.Fragment,{children:[p>0&&(0,r.jsxs)("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"var(--text-dim)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:[(0,r.jsx)("line",{x1:"6",y1:"3",x2:"6",y2:"15"}),(0,r.jsx)("circle",{cx:"18",cy:"6",r:"3"}),(0,r.jsx)("circle",{cx:"6",cy:"18",r:"3"}),(0,r.jsx)("path",{d:"M18 9a9 9 0 0 1-9 9"})]}),(0,r.jsxs)("button",{type:"button",onClick:e=>{e.stopPropagation(),l()},"aria-current":t?"page":void 0,title:M,style:{display:"flex",alignItems:"center",gap:6,flex:1,minWidth:0,color:"var(--text)",fontSize:12.5,fontWeight:t?500:400,lineHeight:1.35,padding:0,border:"none",background:"transparent",fontFamily:"inherit",textAlign:"left",cursor:"pointer"},children:[(0,r.jsx)("span",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:M}),n&&(0,r.jsx)(eh,{}),!n&&a&&(0,r.jsx)(em,{}),e.worktreeBranch&&(0,r.jsx)("span",{title:g("sidebar.worktreePath",{path:e.cwd}),style:{display:"flex",color:"var(--accent)",flexShrink:0},children:(0,r.jsxs)("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.4",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"6",y1:"3",x2:"6",y2:"15"}),(0,r.jsx)("circle",{cx:"18",cy:"6",r:"3"}),(0,r.jsx)("circle",{cx:"6",cy:"18",r:"3"}),(0,r.jsx)("path",{d:"M18 9a9 9 0 0 1-9 9"})]})})]}),h&&(0,r.jsx)("button",{onClick:e=>{e.stopPropagation(),f?.()},title:g(m?"sidebar.expandForks":"sidebar.collapseForks"),style:{display:"flex",alignItems:"center",justifyContent:"center",width:20,height:20,padding:0,flexShrink:0,background:"none",border:"none",color:"var(--text-dim)",cursor:"pointer",transform:m?"rotate(-90deg)":"none",transition:"transform 0.15s"},children:(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:(0,r.jsx)("polyline",{points:"2 3.5 5 6.5 8 3.5"})})}),!e.transient&&(0,r.jsxs)("div",{style:{display:"flex",gap:4,flexShrink:0},children:[(0,r.jsx)("button",{onClick:e=>{e.stopPropagation(),o?.()},title:g(s?"sidebar.unpin":"sidebar.pin"),"aria-label":g(s?"sidebar.unpin":"sidebar.pin"),"aria-pressed":s,style:{display:"flex",alignItems:"center",justifyContent:"center",width:26,height:26,padding:0,background:s?"var(--bg-selected)":"transparent",border:"none",borderRadius:5,color:s?"var(--accent)":"var(--text-muted)",cursor:"pointer",flexShrink:0,opacity:x||s?1:0,pointerEvents:x||s?"auto":"none",transition:"opacity 0.12s, background 0.12s, color 0.12s"},onFocus:()=>v(!0),children:(0,r.jsx)(ed,{filled:s})}),(0,r.jsx)("button",{onClick:E,title:g("sidebar.rename"),style:{display:"flex",alignItems:"center",justifyContent:"center",width:26,height:26,padding:0,background:"transparent",border:"none",borderRadius:5,color:"var(--text-muted)",cursor:"pointer",flexShrink:0,opacity:+!!x,pointerEvents:x?"auto":"none",transition:"opacity 0.12s, background 0.12s, color 0.12s, border-color 0.12s"},onFocus:()=>v(!0),onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-selected)",e.currentTarget.style.color="var(--accent)"},onMouseLeave:e=>{e.currentTarget.style.background="transparent",e.currentTarget.style.color="var(--text-muted)",e.currentTarget.style.borderColor="transparent"},children:(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:(0,r.jsx)("path",{d:"M17 3a2.828 2.828 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5L17 3z"})})}),(0,r.jsx)("button",{onClick:z,title:g("sidebar.archive"),style:{display:"flex",alignItems:"center",justifyContent:"center",width:26,height:26,padding:0,background:"transparent",border:"none",borderRadius:5,color:"var(--text-muted)",cursor:"pointer",flexShrink:0,transition:"background 0.12s, color 0.12s, border-color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-selected)",e.currentTarget.style.color="var(--accent)"},onMouseLeave:e=>{e.currentTarget.style.background="transparent",e.currentTarget.style.color="var(--text-muted)"},children:(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("rect",{x:"3",y:"4",width:"18",height:"4",rx:"1"}),(0,r.jsx)("path",{d:"M5 8v10a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8"}),(0,r.jsx)("path",{d:"M10 12h4"})]})}),(0,r.jsx)("button",{onClick:P,title:g("sidebar.deleteWithShiftClick"),style:{display:"flex",alignItems:"center",justifyContent:"center",width:26,height:26,padding:0,background:"transparent",border:"none",borderRadius:5,color:"var(--text-muted)",cursor:"pointer",flexShrink:0,opacity:+!!x,pointerEvents:x?"auto":"none",transition:"opacity 0.12s, background 0.12s, color 0.12s, border-color 0.12s"},onFocus:()=>v(!0),onMouseEnter:e=>{e.currentTarget.style.background="rgba(239,68,68,0.08)",e.currentTarget.style.color="#ef4444",e.currentTarget.style.borderColor="rgba(239,68,68,0.35)"},onMouseLeave:e=>{e.currentTarget.style.background="transparent",e.currentTarget.style.color="var(--text-muted)",e.currentTarget.style.borderColor="transparent"},children:(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("polyline",{points:"3 6 5 6 21 6"}),(0,r.jsx)("path",{d:"M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"}),(0,r.jsx)("path",{d:"M10 11v6M14 11v6"}),(0,r.jsx)("path",{d:"M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2"})]})})]})]})})}let ex=/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~]|\][^\x07]*(?:\x07|\x1B\\))/g,ev=/^\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~]|\][^\x07]*(?:\x07|\x1B\\))/,eb=/\x1B\[([0-9;]*)m/g,ey=/\x1B_pi:c\x07/g,ew=["#1f2937","#dc2626","#16a34a","#d97706","#2563eb","#9333ea","#0891b2","#6b7280"],ek=["#9ca3af","#ef4444","#22c55e","#f59e0b","#3b82f6","#a855f7","#06b6d4","#e5e7eb"];function ej(e){return e.replace(ey,"").replace(ex,"")}function eS(e){let t=[],n=0;for(;n<e.length;){if(27===e.charCodeAt(n)){let t=e.slice(n).match(ev);if(t){n+=t[0].length;continue}}let r=e.codePointAt(n);if(void 0===r)break;let i=String.fromCodePoint(r);t.push({start:n,end:n+i.length,char:i}),n+=i.length}return t}function eC(e,t){let n=eS(e)[t];return n?e.slice(0,n.start)+e.slice(n.end):e}function eN(e){return eS(e)[0]?.char}function eI(e){let t=/^[┌├└╭╰][─┬┴┼]+[┐┤┘╮╯]$/,n=[];for(let r of e){let e=r.replace(ey,""),i=ej(e).trimEnd();if(t.test(i))continue;let a=e,s=eN(a);("│"===s||"┃"===s)&&" "===eN(a=eC(a,0))&&(a=eC(a,0));let l=function(e){let t=eS(e);for(let e=t.length-1;e>=0;e--)if(""!==t[e].char.trim())return e;return -1}(a),o=l>=0?eS(a)[l]?.char:void 0;("│"===o||"┃"===o)&&(a=eC(a,l)),n.push(function(e){let t=e;for(;;){let e=eS(t),n=e[e.length-1];if(!n||""!==n.char.trim())return t;t=t.slice(0,n.start)+t.slice(n.end)}}(a))}for(;n.length>0&&""===ej(n[0]).trim();)n.shift();for(;n.length>0&&""===ej(n[n.length-1]).trim();)n.pop();return n.length?n:e}function eT(e){let t,n=[],r={},i=0;for(eb.lastIndex=0;null!==(t=eb.exec(e));)t.index>i&&n.push({text:e.slice(i,t.index),style:r}),r=function(e,t){let n={...e};for(let e=0;e<t.length;e++){let r=t[e];if(0===r)for(let e of Object.keys(n))delete n[e];else if(1===r)n.fontWeight=700;else if(2===r)n.opacity=.65;else if(3===r)n.fontStyle="italic";else if(4===r)n.textDecoration="underline";else if(22===r)delete n.fontWeight,delete n.opacity;else if(23===r)delete n.fontStyle;else if(24===r)delete n.textDecoration;else if(39===r)delete n.color;else if(49===r)delete n.backgroundColor;else if(r>=30&&r<=37)n.color=ew[r-30];else if(r>=90&&r<=97)n.color=ek[r-90];else if(r>=40&&r<=47)n.backgroundColor=ew[r-40];else if(r>=100&&r<=107)n.backgroundColor=ek[r-100];else if((38===r||48===r)&&2===t[e+1]){let[i,a,s]=[t[e+2],t[e+3],t[e+4]];[i,a,s].every(e=>"number"==typeof e&&Number.isFinite(e))&&(38===r?n.color=`rgb(${i}, ${a}, ${s})`:n.backgroundColor=`rgb(${i}, ${a}, ${s})`),e+=4}else if((38===r||48===r)&&5===t[e+1]){let i=function(e){if(e>=0&&e<8)return ew[e];if(e>=8&&e<16)return ek[e-8];if(e>=16&&e<=231){let t=e-16,n=Math.floor(t/36),r=Math.floor(t%36/6),i=e=>0===e?0:55+40*e;return`rgb(${i(n)}, ${i(r)}, ${i(t%6)})`}if(e>=232&&e<=255){let t=8+(e-232)*10;return`rgb(${t}, ${t}, ${t})`}}(t[e+2]);i&&(38===r?n.color=i:n.backgroundColor=i),e+=2}}return n}(r,t[1]?t[1].split(";").map(e=>Number(e||"0")):[0]),i=t.index+t[0].length;return i<e.length&&n.push({text:e.slice(i),style:r}),n}let eM={ArrowUp:"\x1b[A",ArrowDown:"\x1b[B",ArrowRight:"\x1b[C",ArrowLeft:"\x1b[D",Home:"\x1b[H",End:"\x1b[F",Insert:"\x1b[2~",Delete:"\x1b[3~",PageUp:"\x1b[5~",PageDown:"\x1b[6~",Escape:"\x1b",Backspace:""},e$={ArrowLeft:"\x1bb",ArrowRight:"\x1bf",ArrowUp:"\x1bp",ArrowDown:"\x1bn"},eR={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",bmp:"image/bmp",ico:"image/x-icon",avif:"image/avif"},eE={mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",oga:"audio/ogg",opus:"audio/ogg",m4a:"audio/mp4",aac:"audio/aac",flac:"audio/flac",weba:"audio/webm",webm:"audio/webm"};function eL(e){return(e.replace(/\\/g,"/").split("/").pop()??"").toLowerCase().split(".").pop()??""}function eA(e){return null!==(eR[eL(e)]??null)}function ez(e,t,n={}){let r={...e,content:t};return n.omitUsage&&(r.usage=void 0),r}function eP(e,t={}){return!!t.hideThinking&&"thinking"===e.type||function(e,t={}){return"thinking"===e.type&&!e.deferred&&!t.isStreaming&&""===e.thinking.trim()}(e,t)}function eW(e,t={}){return t.isStreaming||"error"!==e.stopReason?null:e.errorMessage?.trim()||"Unknown provider error"}function eF(e,t={}){let n=[];for(let r of function(e,t={}){return(e.content??[]).filter(e=>!eP(e,t))}(e,t)){let e="image"===r.type||"text"===r.type&&r.text.trim().length>0?"answer":"process",t=n[n.length-1];t?.kind===e?t.blocks.push(r):n.push({kind:e,blocks:[r]})}return n}function e_(e){return e.filter(e=>"toolCall"===e.type).length}function eD(e,t,n){let r=new URLSearchParams({sessionId:e,toolCallId:t});return void 0!==n&&r.set("index",String(n)),`/api/tool-image?${r}`}let eO=/^\[[1-9]\d* tool result images? omitted from initial history payload(?:: [^\]\n]*)?, ~\d+ bytes\]$/;function eH(e){let t=new Map;for(let n of e)"toolResult"===n.role&&t.set(n.toolCallId,n);let n=[],r=-1;return{collect(e,i){for(let a of i)"toolCall"===a.type&&function(e,t){if(!t||t.isError)return!1;if(t.content?.some(e=>"image"===e.type))return!0;let n=e.input??{};if("generate_image"===e.toolName)return!0;if("write"===e.toolName)return"xd://generate_image"===n.path;if("eval"===e.toolName){let e;return e=t.content?.at(-1),e?.type==="text"&&eO.test(e.text)}return"read"===e.toolName&&"string"==typeof n.path&&eA(n.path)}(a,t.get(a.toolCallId))&&(n.push({type:"image",source:{type:"url",url:""},toolImage:{toolCallId:a.toolCallId}}),r=e)},attach(e){if(0===n.length)return e;let t=[...n,...e];return n=[],t},takeRemaining(){if(0===n.length)return null;let e={idx:r,blocks:n};return n=[],e}}}let eB=new Map,eU=new Map,eq="command",eK="autolearn-saved";function eV(e){return"custom"===e.role&&(e.customType===eq||e.customType===eK&&!1!==e.display)}let eJ="local-command:";function eG(e){return e?.startsWith(eJ)===!0}function eY(e,t,n){let r=new Set(n.map(e=>e.message)),i=[],a=[];for(let n=0;n<e.length;n++){let s=n<t.length;!(r.has(e[n])||s&&eG(t[n]))&&(i.push(e[n]),s&&a.push(t[n]))}for(let e of n){let t=0;if(null!==e.baseEntryId){let n=a.indexOf(e.baseEntryId);if(-1===n)continue;t=n+1}let n=e.message.timestamp??0;for(;t<i.length;){let e=i[t];if(!r.has(e)&&"number"==typeof e.timestamp&&e.timestamp>n)break;t+=1}i.splice(t,0,e.message),t<=a.length&&a.splice(t,0,e.entryId)}return{messages:i,entryIds:a}}function eZ(e){return"user"===e.role||"custom"===e.role&&"compaction"===e.customType}let eX={create:!0,update:!0};function eQ(e){return"string"==typeof e?e.replace(/\s+/g," ").trim():""}function e0(e){if("string"==typeof e)return e;if(!Array.isArray(e))return"";let t=[];for(let n of e)n&&"object"==typeof n&&"type"in n&&"text"===n.type&&"text"in n&&"string"==typeof n.text&&t.push(n.text);return t.join("\n")}function e1(e,t){if(0===e.length)return -1;if(!t)return 0;let n=-1;for(let r=0;r<e.length;r++){let i=e[r];if(i.item===t.item){if(i.k===t.k)return r;n=r}}return -1===n?0:n}function e2(e){try{return decodeURIComponent(e)}catch{return e}}function e4(e){return/^[a-zA-Z]:[\\/]/.test(e)||e.startsWith("\\\\")?e.replace(/\\/g,"/"):e}function e5(e){let t=e4(e),n=/^[a-zA-Z]:\//.test(t),r=t.startsWith("//"),i=t.startsWith("/")&&!n&&!r,a=[];for(let e of t.split("/"))if(e&&"."!==e){if(".."===e){a.length>0&&".."!==a[a.length-1]?a.pop():i||n||r||a.push(e);continue}a.push(e)}let s=a.join("/");return n?s:r?`//${s}`:i?`/${s}`:s}function e6(e,t,n=t){let r,i,a,s,l;if(!e)return null;let o=e.split("#",1)[0].split("?",1)[0].trim();if(!o)return null;let d=null,c=null,u=e2(o),p=u.startsWith("\\\\"),h=e4(u),m=h.toLowerCase();if(m.startsWith("/api/")||m.startsWith("/_next/")||!p&&h.startsWith("//")||/^[a-zA-Z][a-zA-Z0-9+.-]*:/i.test(h)&&!m.startsWith("file:")&&!/^[a-zA-Z]:\//.test(h))return null;if(m.startsWith("file:")?c=(d=function(e){try{let t=new URL(e);if("file:"!==t.protocol)return null;let n=e2(t.pathname);if(t.hostname)return`//${t.hostname}${n.startsWith("/")?n:`/${n}`}`;if(/^\/[a-zA-Z]:\//.test(n))return n.slice(1);return n}catch{return null}}(h))?"absolute":null:/^[a-zA-Z]:\//.test(h)||h.startsWith("/")?(d=h,c="absolute"):t&&!(h.startsWith("#")||h.startsWith("?"))&&(h.startsWith("./")||h.startsWith("../")||h.includes("/")||/(^|\/)\.?[^/]+\.[^/.]+$/.test(h))&&(d=`${e4(t).replace(/\/+$/,"")}/${h}`,c="relative"),!d)return null;let f=e5(d).replace(/:\d+(?::\d+)?$/,"");return"relative"===c&&n&&(r=e5(f).replace(/\/+$/,""),i=e5(n).replace(/\/+$/,""),s=(a=/^[a-zA-Z]:\//.test(r)||/^[a-zA-Z]:\//.test(i))?r.toLowerCase():r,!(s===(l=a?i.toLowerCase():i)||s.startsWith(`${l}/`)))?null:f}function e8(e,t,n){let r=new Set,i=[];for(let a of e){if("toolCall"!==a.type||!function(e){let t,n;return"write"===(t=e.toLowerCase())||t.startsWith("write_")||t.endsWith(".write")||t.endsWith("_write")||"edit"===(n=e.toLowerCase())||n.startsWith("edit_")||n.endsWith(".edit")||n.endsWith("_edit")||n.includes("str_replace")||n.includes("replace_editor")}(a.toolName))continue;let e=t?.get(a.toolCallId);if(!e||e.isError)continue;let s=function(e){if(!e)return null;let t=e.file_path??e.path;return"string"==typeof t&&t.length>0?t:null}(a.input);if(!s||!/^[a-zA-Z]:[\\/]/.test(s)&&/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//.test(s))continue;let l=function(e,t){let n;if(!e)return null;let r=/^[a-zA-Z]:[\\/]/.test(e)||e.startsWith("\\\\")||void 0!==t&&(/^[a-zA-Z]:[\\/]/.test(t)||t.startsWith("\\\\")),i=e=>r?e.replace(/\\/g,"/"):e,a=i(e),s=t?i(t).replace(/\/+$/,""):void 0,l=/^[a-zA-Z]:\//.test(a),o=a.startsWith("//");if(l||o)n=a;else if(a.startsWith("/")){let e=s?.match(/^([a-zA-Z]:)(?:\/|$)/)?.[1]??s?.match(/^(\/\/[^/]+\/[^/]+)(?:\/|$)/)?.[1];n=e?`${e}${a}`:a}else{if(!s)return null;n=`${s}/${a}`}return e5(n)}(s,n);l&&(r.has(l)||(r.add(l),i.push({filePath:l})))}return i}function e3(e,t){var n;let r;if(t){let e=t.details,n=e&&"object"==typeof e&&"phases"in e?e.phases:void 0;if(!Array.isArray(n))return{kind:"unknown"};let{phases:r,malformed:i}=function(e){let t=[];for(let n of e){if(!n||"object"!=typeof n||!("name"in n)||!("tasks"in n))return{phases:t,malformed:!0};let{name:e,tasks:r}=n;if("string"!=typeof e||!Array.isArray(r))return{phases:t,malformed:!0};let i=Array.isArray(r)?r.flatMap(e=>{if(!e||"object"!=typeof e||!("content"in e)||!("status"in e))return[];let{content:t,status:n}=e;return"string"!=typeof t||"pending"!==n&&"in_progress"!==n&&"completed"!==n&&"abandoned"!==n&&"blocked"!==n?[]:[{content:t,status:n,blocker:"blocker"in e&&"string"==typeof e.blocker?e.blocker:void 0}]}):[];if(i.length!==r.length)return{phases:t,malformed:!0};i.length>0&&t.push({name:e,tasks:i})}return{phases:t,malformed:!1}}(n);return i?{kind:"unknown"}:{kind:"authoritative",phases:r}}let i=Array.isArray(r=(n=e.input)&&"object"==typeof n&&"list"in n?n.list:void 0)?r.flatMap(e=>{if(!e||"object"!=typeof e||!("phase"in e)||!("items"in e))return[];let{phase:t,items:n}=e;if("string"!=typeof t||!Array.isArray(n))return[];let r=n.filter(e=>"string"==typeof e).map(e=>({content:e,status:"pending"}));return r.length>0?[{name:t,tasks:r}]:[]}):[];return i.length>0?{kind:"preview",phases:i}:{kind:"unknown"}}function e7(e,t,n=null,r=null){return n||(function(e,t){for(let n=e.length-1;n>=0;n-=1){let r=e[n];if("assistant"!==r.role)continue;let i=r.content;if(Array.isArray(i))for(let e=i.length-1;e>=0;e-=1){let n=i[e];if("toolCall"!==n.type||!function(e){if(!e)return!1;let t=e.toLowerCase();return"todo"===t||t.endsWith(".todo")||t.endsWith("_todo")}(n.toolName))continue;let r=e3(n,t.get(n.toolCallId));if("unknown"!==r.kind)return r.phases}}return null}(e,t)??r)}function e9(e){let t=0,n=0,r=null,i=null,a=null;for(let s of e)for(let e of s.tasks){if("completed"===e.status){t+=1;continue}"abandoned"!==e.status&&(n+=1,"in_progress"===e.status?r||(r={phase:s,task:e}):"blocked"===e.status?a||(a={phase:s,task:e}):i||(i={phase:s,task:e}))}let s=r??i??a,l=t+n;return{currentPhase:s?.phase??null,activeTask:s?.task??null,remaining:n,completed:t,total:l,percent:l>0?Math.round(t/l*100):null}}var te=n(65063),tt=n(7644),tn=n(32316);function tr(e){return/^[a-zA-Z]:[\\/]/.test(e)||e.startsWith("\\\\")?e.replace(/\\/g,"/"):e}function ti(e){return tr(e).split("/").filter(Boolean).map(encodeURIComponent).join("/")}function ta(e){let t=tr(e).replace(/\/+$/,"");return t.split("/").pop()??t}function ts(e,t){if(!t)return e;let n=tr(e),r=tr(t).replace(/\/$/,"");return n.startsWith(r+"/")?n.slice(r.length+1):e}var tl=n(88374),to=n(63280),td=n(94764),tc=n(63835),tu=n(54152),tp=n(84678),th=n(98164);let tm={...td.j,attributes:{...td.j.attributes,code:[["className",/^language-./,"math-inline","math-display"]]},strip:[...td.j.strip||[],"iframe","object","style","form"]};function tf(e){let t=e.includes("\r\n")?"\r\n":"\n",n=e.split(/\r?\n/),r=[],i=null,a=0,s=null,l=new Map;for(let e=0;e<n.length;e++){var o;let t=n[e];if(s){r.push(t),RegExp(`</${s}\\s*>`,"i").test(t)&&(s=null);continue}let d=t.match(/^ {0,3}(`{3,}|~{3,})/);if(d){let e=d[1][0],n=d[1].length;i?e===i.marker&&n>=i.size&&(i=null):i={marker:e,size:n},a=0,r.push(t);continue}if(i){r.push(t);continue}let c=t.match(/<(code|pre|script|style)\b/i);if(c){let e=c[1].toLowerCase(),n=t.slice((c.index??0)+c[0].length);RegExp(`</${e}\\s*>`,"i").test(n)||(s=e),a=0,r.push(t);continue}if(/^(?: {4}|\t)/.test(t)||""===t.trim()){a=0,r.push(t);continue}if(a||t.includes("`")){a=function(e,t){let n=t;for(let t=0;t<e.length;){if("`"!==e[t]){t++;continue}let r=t+1;for(;"`"===e[r];)r++;let i=r-t;0===n?n=i:i===n&&(n=0),t=r}return n}(t,a),r.push(t);continue}let u=t.match(/^([ ]{0,3})\\\[[ \t]*(.+?)[ \t]*\\\][ \t]*$/);if(u){let e=u[2].trim();if(e){r.push(`${u[1]}$$`,`${u[1]}${e}`,`${u[1]}$$`);continue}}let p=t.match(/^([ ]{0,3})\\\[[ \t]*$/);if(p){let t=function(e,t){for(let n=t;n<e.length;n++){let t=e[n];if(/^ {0,3}\\\][ \t]*$/.test(t))return n;if(/^ {0,3}(`{3,}|~{3,})/.test(t)||/^ {0,3}\\\[[ \t]*$/.test(t)||/<(code|pre|script|style)\b/i.test(t))break}return -1}(n,e+1);if(-1!==t){r.push(`${p[1]}$$`,...n.slice(e+1,t).map(e=>tx(e,p[1])),`${p[1]}$$`),e=t;continue}}let h=t.match(/^([ \t]{0,3})\$\$(.+)\$\$[ \t]*$/);if(h){let e=h[2].trim();if(e){r.push(`${h[1]}$$`,`${h[1]}${e}`,`${h[1]}$$`);continue}}let m=t.match(/^([ \t]{0,3})\$\$(.+)$/);if(m){let t=m[1],i=m[2].trimEnd();if(i&&!i.includes("$$")){let a=tg(n,e+1,t,l);if(a){r.push(`${t}$$`,`${t}${i}`);for(let i=e+1;i<a.index;i++)r.push(tx(n[i],t));a.content&&r.push(`${t}${a.content}`),r.push(`${t}$$`),e=a.index;continue}}}let f=t.match(/^([ \t]{0,3})\$\$\s*$/);if(f){let t=f[1],i=tg(n,e+1,t,l);if(i&&(i.glued||""!==t)){r.push(`${t}$$`);for(let a=e+1;a<i.index;a++)r.push(tx(n[a],t));i.content&&r.push(`${t}${i.content}`),r.push(`${t}$$`),e=i.index;continue}}r.push((o=t,/^\s{0,3}\[[^\]]+\]:/.test(o)||/]\s*\(/.test(o)||/<(?:!--|\/?[A-Za-z][^>]*>)/.test(o)||/\b(?:https?|file|mailto):/i.test(o)||/\b[A-Za-z]:\\/.test(o)?o:o.replace(/(?<!\\)\\\(([^`\r\n$]+?)(?<!\\)\\\)/g,(e,t)=>t.trim()?`$${t}$`:e)))}return r.join(t)}function tg(e,t,n,r){let i=r.get(n);if(void 0!==i&&t<i)return null;for(let i=t;i<e.length;i++){var a,s,l,o;let t=e[i];if(a=t,""===(s=n)?/^ {0,3}\$\$\s*$/.test(a):a.startsWith(s)&&/^\$\$\s*$/.test(a.slice(s.length)))return{index:i,content:"",glued:!1};if(l=t,/^ {0,3}(`{3,}|~{3,})/.test(l)||/^[ \t]*(?:[-+*]|\d{1,9}[.)])(?:[ \t]+|$)/.test(l)||/^ {0,3}#{1,6}(?:[ \t]+|$)/.test(l)||/^ {0,3}>/.test(l)||/<(code|pre|script|style)\b/i.test(l)||(o=t,/^ {0,3}\$\$(?:\S|[ \t]+\S)/.test(o)))return r.set(n,i),null;let d=function(e,t){if(!e.startsWith(t))return null;let n=e.slice(t.length).match(/^(.+?)\$\$\s*$/);if(!n)return null;let r=n[1].trimEnd();return r&&!r.includes("$$")?r:null}(t,n);if(null!==d)return{index:i,content:d,glued:!0}}return r.set(n,e.length),null}function tx(e,t){if(!t||!e||e.startsWith(" "))return e;let n=e.match(/^ */)?.[0].length??0;return n>=t.length?e:`${t.slice(n)}${e}`}let tv={singleTilde:!1},tb=[[tu.A,["yaml"]],[tp.A,tv],th.A],ty=[[tu.A,["yaml"]],[tp.A,tv],th.A],tw=[to.A,[tc.A,tm],[tl.A,{throwOnError:!1,strict:!1}]],tk=[to.A,[tc.A,tm],[tl.A,{throwOnError:!1,strict:!1}]],tj="pi-theme",tS=["light","dark","auto"],tC={preference:"auto",theme:"light"},tN="omp-theme",tI=null,tT=0,tM=new Set,t$=null,tR=!1;function tE(){return window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}function tL(e){return"auto"===e?tE():e}let tA="--omp-md-";function tz(e){let t=document.documentElement,n=tI?.palettes[e];t.dataset.ompThemeMode=e,t.setAttribute("data-seed-color-mode","dark"===e?"dark-only":"light-only"),t.classList.toggle("dark","dark"===e);for(let e=t.style.length-1;e>=0;e-=1){let n=t.style.item(e);n.startsWith("--")&&!n.startsWith(tA)&&t.style.removeProperty(n)}if(n){for(let[e,r]of Object.entries(n.variables))e.startsWith(tA)&&t.style.setProperty(e,r);t.dataset.ompThemeName=n.name}try{localStorage.setItem(tN,e)}catch{}}function tP(){if(t$)return t$;let e=function(){try{let e=localStorage.getItem(tj);if("light"===e||"dark"===e||"auto"===e)return e;let t=localStorage.getItem(tN);if("light"===t||"dark"===t)return t}catch{}return"auto"}(),t=tL(e);return tz(t),t$={preference:e,theme:t}}function tW(e,t,n){if(tz(t),n)try{localStorage.setItem(tj,e)}catch{}t$={preference:e,theme:t},tM.forEach(e=>e())}function tF(){let e=tP();if("auto"!==e.preference)return;let t=tE();t!==e.theme&&tW("auto",t,!1)}function t_(e){return tM.add(e),tP(),tR||!window.matchMedia||(window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change",tF),window.addEventListener("focus",tF),document.addEventListener("visibilitychange",()=>{"visible"===document.visibilityState&&tF()}),tR=!0),tF(),()=>{tM.delete(e)}}function tD(){return tP()}function tO(){return tC}async function tH(e){let t=++tT,n=e?`?cwd=${encodeURIComponent(e)}`:"",r=await fetch(`/api/theme${n}`,{cache:"no-store"});if(!r.ok)throw Error(`Theme request failed (${r.status})`);let i=await r.json();if(t===tT){tI=i;try{localStorage.setItem("omp-theme-config",JSON.stringify(tI))}catch{}tz(tP().theme)}}function tB(e){let t=(0,i.useSyncExternalStore)(t_,tD,tO);(0,i.useEffect)(()=>{e?.syncWithOmp&&tH(e.cwd).catch(()=>{})},[e?.cwd,e?.syncWithOmp]);let n=(0,i.useCallback)((e,t)=>{let n=tL(e),r=()=>{tW(e,n,!0)},i=window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;if("function"!=typeof document.startViewTransition||i)return void r();let a=t?.x??window.innerWidth/2,s=t?.y??window.innerHeight/2,l=Math.hypot(Math.max(a,window.innerWidth-a),Math.max(s,window.innerHeight-s));document.startViewTransition(r).ready.then(()=>{document.documentElement.animate({clipPath:[`circle(0px at ${a}px ${s}px)`,`circle(${l}px at ${a}px ${s}px)`]},{duration:450,easing:"cubic-bezier(0.22, 0.61, 0.36, 1)",pseudoElement:"::view-transition-new(root)"})}).catch(()=>{})},[]),r=(0,i.useCallback)(e=>{var t;let r;n((t=tP().preference,r=tS.indexOf(t),tS[(r+1)%tS.length]),e)},[n]),a=(0,i.useCallback)((e,t)=>{n(e,t)},[n]);return{theme:t.theme,preference:t.preference,toggleTheme:r,setPreference:a,isDark:"dark"===t.theme}}function tU(e){if(navigator.clipboard?.writeText)return navigator.clipboard.writeText(e);try{let t=document.createElement("textarea");return t.value=e,t.style.position="fixed",t.style.opacity="0",document.body.appendChild(t),t.select(),document.execCommand("copy"),document.body.removeChild(t),Promise.resolve()}catch{return Promise.reject()}}let tq={...tt.vs,...Object.fromEntries(["url","symbol","number","boolean","variable","constant","inserted"].map(e=>[e,{...tt.vs[e],color:"var(--seed-color-palette-green-800)"}]))};function tK({code:e,isStreaming:t,defaultPreview:a=!1}){let{isDark:s}=tB(),{t:l}=(0,R.s)(),[o,d]=(0,i.useState)(a),[c,u]=(0,i.useState)(null),[p,h]=(0,i.useState)(!1),m=`${s?"dark":"light"}
4
4
  ${e}`,f=o&&!t;(0,i.useEffect)(()=>{if(!f)return;let t=!1;return u({key:m,status:"loading"}),(async()=>{let{default:r}=await Promise.all([n.e(866),n.e(8367),n.e(3308)]).then(n.bind(n,43328)),i=getComputedStyle(document.body).fontFamily;if(await document.fonts.load(`16px ${i}`,e),await document.fonts.ready,t)return;if(r.initialize({startOnLoad:!1,securityLevel:"strict",suppressErrorRendering:!0,theme:s?"dark":"default",fontFamily:i}),!await r.parse(e,{suppressErrors:!0}))throw Error("Invalid Mermaid diagram");let a="u">typeof crypto&&"randomUUID"in crypto?`mermaid-${crypto.randomUUID()}`:`mermaid-${Date.now()}-${Math.random().toString(36).slice(2)}`,l=await r.render(a,e);t||u({key:m,status:"ready",svg:l.svg})})().catch(()=>{t||u({key:m,status:"error"})}),()=>{t=!0}},[e,m,s,f]);let g=(0,i.useMemo)(()=>(0,r.jsx)("button",{type:"button",onClick:()=>d(e=>!e),disabled:t,title:t?l("i18n.previewAfterStreaming"):f?l("i18n.showMermaidSource"):l("i18n.previewMermaid"),className:["markdown-code-action",f?"is-active":""].filter(Boolean).join(" "),children:f?l("i18n.source"):l("i18n.preview")}),[t,f,l]);if(!f)return(0,r.jsx)(tJ,{code:e,lang:"mermaid",headerAction:g,isStreaming:t});let x=c?.key===m&&"error"===c.status?(0,r.jsx)("div",{className:"mermaid-block mermaid-block-error",children:l("i18n.invalidMermaid")}):c?.key!==m||"ready"!==c.status?(0,r.jsx)("div",{className:"mermaid-block mermaid-block-loading","aria-label":l("i18n.renderingMermaid")}):(0,r.jsxs)(r.Fragment,{children:[!p&&(0,r.jsx)("button",{type:"button",className:"mermaid-block mermaid-preview-button",title:l("i18n.openMermaidViewer"),"aria-label":l("i18n.openMermaidViewer"),onClick:()=>h(!0),dangerouslySetInnerHTML:{__html:c.svg}}),p&&(0,r.jsx)(tV,{svg:c.svg,onClose:()=>h(!1)})]});return(0,r.jsxs)("div",{className:"markdown-code-block",children:[(0,r.jsxs)("div",{className:"markdown-code-header",children:[(0,r.jsx)("span",{className:"markdown-code-lang",children:"mermaid"}),g]}),x]})}function tV({svg:e,onClose:t}){let{t:n}=(0,R.s)(),a=(0,i.useRef)(null),[s,l]=(0,i.useState)(1);return(0,i.useEffect)(()=>{let e=a.current;if(!e)return;let t=document.body.style.overflow;return document.body.style.overflow="hidden",e.showModal(),()=>{document.body.style.overflow=t,e.open&&e.close()}},[]),(0,r.jsx)("dialog",{ref:a,className:"mermaid-zoom-dialog","aria-label":n("i18n.mermaidViewer"),onCancel:e=>{e.preventDefault(),t()},onKeyDown:e=>{"Escape"===e.key&&(e.preventDefault(),t())},children:(0,r.jsxs)("div",{className:"mermaid-zoom-layout",children:[(0,r.jsxs)("div",{className:"mermaid-zoom-toolbar",children:[(0,r.jsx)("span",{className:"mermaid-zoom-title",children:n("i18n.mermaidDiagram")}),(0,r.jsxs)("div",{className:"mermaid-zoom-actions",children:[(0,r.jsxs)("div",{className:"mermaid-zoom-stepper",children:[(0,r.jsx)("button",{type:"button",onClick:()=>l(e=>Math.max(.5,e-.25)),disabled:s<=.5,title:n("i18n.zoomOut"),"aria-label":n("i18n.zoomOut"),children:(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M5 12h14"})})}),(0,r.jsxs)("span",{className:"mermaid-zoom-value",children:[Math.round(100*s),"%"]}),(0,r.jsx)("button",{type:"button",onClick:()=>l(e=>Math.min(3,e+.25)),disabled:s>=3,title:n("i18n.zoomIn"),"aria-label":n("i18n.zoomIn"),children:(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M12 5v14M5 12h14"})})})]}),(0,r.jsx)("button",{type:"button",className:"mermaid-zoom-icon-button",onClick:()=>l(1),title:n("i18n.fitToWidth"),"aria-label":n("i18n.fitToWidth"),children:(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M8 3H3v5M16 3h5v5M8 21H3v-5M16 21h5v-5"})})}),(0,r.jsx)("button",{type:"button",className:"mermaid-zoom-icon-button",onClick:t,title:n("i18n.close"),"aria-label":n("i18n.close"),children:(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M6 6l12 12M18 6 6 18"})})})]})]}),(0,r.jsx)("div",{className:"mermaid-zoom-viewport",onClick:e=>{e.target===e.currentTarget&&t()},children:(0,r.jsx)("div",{className:"mermaid-zoom-canvas",style:{width:`${100*s}%`},dangerouslySetInnerHTML:{__html:e}})})]})})}let tJ=(0,i.memo)(function({code:e,lang:t,headerAction:n,isStreaming:a}){let{isDark:s}=tB(),{t:l}=(0,R.s)(),[o,d]=(0,i.useState)(!1);return(0,r.jsxs)("div",{className:"markdown-code-block",children:[(0,r.jsxs)("div",{className:"markdown-code-header",children:[(0,r.jsx)("span",{className:"markdown-code-lang",children:t||"text"}),(0,r.jsxs)("div",{className:"markdown-code-actions",children:[n,(0,r.jsx)("button",{onClick:()=>{tU(e).then(()=>{d(!0),setTimeout(()=>d(!1),1500)})},className:"markdown-code-action",children:l(o?"i18n.copied":"i18n.copy")})]})]}),a?(0,r.jsx)("pre",{style:{margin:0,padding:"11px 13px",fontSize:12.5,lineHeight:1.62,overflowX:"auto",background:"color-mix(in srgb, var(--bg) 92%, var(--bg-panel))"},children:(0,r.jsx)("code",{style:{fontFamily:"var(--font-mono)"},children:e})}):(0,r.jsx)(te.A,{language:t||"text",style:s?tt.xJ:tq,showLineNumbers:!0,lineNumberStyle:{color:"var(--text-muted)",fontStyle:"normal"},customStyle:{margin:0,padding:"11px 13px",fontSize:12.5,lineHeight:1.62,borderRadius:0,background:"color-mix(in srgb, var(--bg) 92%, var(--bg-panel))"},codeTagProps:{style:{fontFamily:"var(--font-mono)"}},children:e})]})});function tG({children:e,className:t,isStreaming:n,cwd:a,onOpenFile:s}){let l=(0,i.useMemo)(()=>tf(e),[e]),o=(0,i.useMemo)(()=>({code({className:e,children:t,...i}){let a=e?.replace("language-","").toLowerCase()??"",s=String(t);return e?.includes("language-")||s.includes("\n")?"mermaid"===a?(0,r.jsx)(tK,{code:s.replace(/\n$/,""),isStreaming:n}):(0,r.jsx)(tJ,{code:s.replace(/\n$/,""),lang:a,isStreaming:n}):(0,r.jsx)("code",{className:"markdown-inline-code",...i,children:t})},pre:({children:e})=>(0,r.jsx)(r.Fragment,{children:e}),a({href:e,children:t,...n}){delete n.node;let i=s?e6(e,a):null;return i&&s?(0,r.jsx)("a",{href:e,...n,onClick:e=>{if(e.defaultPrevented||0!==e.button||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey)return;let t=e.currentTarget.getAttribute("target");t&&"_self"!==t||(e.preventDefault(),s(i))},children:t}):(0,r.jsx)("a",{href:e,...n,target:"_blank",rel:"noopener noreferrer",children:t})},img({src:e,alt:t,...n}){delete n.node;let i="string"==typeof e?e6(e,a):null,s=i?`/api/files/${ti(i)}?type=read`:e;return(0,r.jsx)("img",{src:s,alt:t??"",loading:"lazy",...n})},table:({children:e})=>(0,r.jsx)("div",{className:"markdown-table-wrap",children:(0,r.jsx)("table",{children:e})})}),[a,n,s]);return(0,r.jsx)("div",{className:["markdown-body",t].filter(Boolean).join(" "),children:(0,r.jsx)(tn.oz,{remarkPlugins:tb,rehypePlugins:tw,components:o,children:l})})}function tY(e){let[t,n]=(0,i.useState)(()=>Date.now());return(0,i.useEffect)(()=>{let t=setInterval(()=>n(Date.now()),e);return()=>clearInterval(t)},[e]),t}var tZ=n(54265);function tX(e){let t=e.details;if("number"==typeof t?.exitCode)return t.exitCode;let n=e.content.map(e=>"text"===e.type?e.text:"").join("\n"),r=/Command exited with code (-?\d+)\s*$/.exec(n.trimEnd());return r?Number(r[1]):null}let tQ=/<(read-files|modified-files)>\s*([\s\S]*?)\s*<\/\1>/g,t0=/(?:\r?\n){2,}((?:[ \t]*<(?:read-files|modified-files)>[ \t]*\r?\n[\s\S]*?\r?\n[ \t]*<\/(?:read-files|modified-files)>[ \t]*(?:\r?\n)?)+)\s*$/;function t1(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${Math.round(e/1e3)}k`:e.toLocaleString()}let t2={hideThinkingBlock:!1},t4=new Set,t5=t2,t6=0;function t8(e){return t4.add(e),()=>{t4.delete(e)}}function t3(){return t5}function t7(){return t2}async function t9(e){let t=++t6,n=e?`?cwd=${encodeURIComponent(e)}`:"",r=await fetch(`/api/display-settings${n}`,{cache:"no-store"});if(!r.ok)throw Error(`Display settings request failed (${r.status})`);let i=await r.json();t!==t6||i.hideThinkingBlock!==t5.hideThinkingBlock&&(t5={hideThinkingBlock:!0===i.hideThinkingBlock},t4.forEach(e=>e()))}function ne(){return(0,i.useSyncExternalStore)(t8,t3,t7)}var nt=n(64178);let nn={faces:new Map,pins:new Map},nr=[],ni=nn,na=null,ns=new Map,nl=new Set;function no(e){return nl.add(e),()=>{nl.delete(e)}}function nd(e){ni=e,nl.forEach(e=>e())}function nc(e){return Number.isSafeInteger(e)&&e>0}function nu(e,t){return`${e}:${t}`}function np(e,t,n){if(!t)return null;if(nc(n)){let e=ni.faces.get(nu(t,n));if(e)return e}let r=e?ni.pins.get(e):void 0;if(r&&r.provider===t){let e=ni.faces.get(nu(t,r.credentialId));if(e)return e}return(0,nt.e$)(t)}async function nh(e,t,n){if(!t||nc(n)||(0,nt.e$)(t))return np(e,t,n);try{let{data:n}=await (0,nt.ST)(e);if(n?.state==="resolved"&&n.provider===t&&nc(n.credentialId)){let r=new Map(ni.pins);r.set(e,{provider:t,credentialId:n.credentialId,observedAt:Date.now()}),nd({faces:ni.faces,pins:r})}}catch{}return np(e,t,void 0)}function nm(e,t,n){let r=!!t&&!nc(n)&&!!e;return(0,i.useEffect)(()=>{r&&e&&t&&function(e,t){let n=Date.now(),r=ni.pins.get(e);if(r&&r.provider===t&&n-r.observedAt<3e4)return;let i=`${e}\u0000${t}`,a=ns.get(i);void 0!==a&&n-a<3e4||(ns.set(i,n),(0,nt.ST)(e).then(t=>{let n=t.data;if(!n||"resolved"!==n.state)return;let{provider:r,credentialId:i}=n;if("string"!=typeof r||""===r||!nc(i))return;let a=new Map(ni.pins);a.set(e,{provider:r,credentialId:i,observedAt:Date.now()}),nd({faces:ni.faces,pins:a})}).catch(()=>{}))}(e,t)},[r,e,t]),(0,i.useSyncExternalStore)(no,()=>np(e,t,n),()=>null)}let nf={ko:{"dispatch.title":"서브에이전트 {count}명","dispatch.tally":"실행 중 {running} \xb7 실행 완료 {done} \xb7 Main 수용 {accepted}","dispatch.expand":"발주 상세 펼치기","dispatch.collapse":"발주 상세 접기","dock.label":"서브에이전트","dock.running":"실행 중 {count}","dock.awaiting":"판정 대기 {count}","dock.jump":"발주 카드로 이동 — {title}","dock.openPanel":"서브에이전트 상세 열기 — {title}","run.dispatching":"발주 중","run.pending":"대기","run.running":"실행 중","run.completed":"실행 완료","run.failed":"실행 실패","run.aborted":"중단됨","run.unobserved":"실행 상태 미관측","verdict.accepted":"Main 수용","verdict.rework":"Main 재작업 요청","verdict.held":"Main 보류","verdict.none":"검수 미기록","verdict.attempt":"{attempt}차","detail.stage":"현재 단계","detail.stageNone":"기록 없음","detail.model":"모델","detail.modelNone":"미관측","detail.fallback":"대체 모델","detail.agentId":"담당 ID","detail.reason":"판정 사유","detail.source.live":"실시간 관측","detail.source.record":"세션 기록","detail.openSubagents":"서브에이전트 상세 열기","detail.openProcess":"작업 기록 열기","summary.files":"변경 파일 {count}","summary.checks":"검사 {count}","summary.checksFailed":"실패 {count}","summary.unverified":"미확인 {count}","summary.expand":"턴 요약 펼치기","summary.collapse":"턴 요약 접기","summary.heading.files":"변경 파일","summary.heading.checks":"실행한 검사","summary.heading.unverified":"미확인","summary.check.exit":"exit {code}","summary.check.error":"오류로 끝남","summary.check.unobserved":"결과 미관측","summary.u.checkFailed":"검사 실패 — {command}","summary.u.checkUnobserved":"검사 결과 미관측 — {command}","delivery.title":"보낸 입력 {count}","delivery.kind.steer":"지금 지시","delivery.kind.followUp":"완료 후 요청","delivery.stage.sending":"보내는 중","delivery.stage.accepted":"접수됨 \xb7 전달 대기","delivery.stage.delivered":"전달됨 \xb7 대화에 들어감","delivery.stage.failed":"보내지 못함 \xb7 입력창에 되돌림","delivery.stage.unconfirmed":"전달 확인 못 함 \xb7 큐에서 빠짐","delivery.images":"이미지 {count}개","delivery.showOlder":"이전 {count}개 더 보기","delivery.showRecent":"최근 {count}개만 보기","live.nativeVoice":"기본 음성","progress.label":"진행","phase.investigate":"조사","phase.implement":"구현","phase.verify":"검증","phase.report":"보고","phase.current":"지금 단계 {phase}","phase.hint":"도구 호출로 읽은 지금 단계입니다. 고친 뒤 다시 고치면 앞 단계로 돌아갑니다.","progress.todo":"할 일 {completed}/{total} ({percent}%)","eta.label":"예상 시간","eta.elapsed":"경과 {duration}","eta.remaining":"남은 시간 보통 {range} (과거 {samples}건)","eta.percent":"약 {percent}% 추정","eta.overrun":"과거 최장 기록({longest}) 이상 경과","eta.sparseTail":"과거 {samples}건 중 {longerRuns}건만 이보다 오래 걸림","eta.hint":"같은 모델\xb7작업 등급의 과거 첫 시도 가운데 지금 경과보다 오래 걸린 실행들의 남은 시간 분포(가운데 절반)입니다.","eta.byTodo":"할 일 기준 약 {duration} 남음 ({completed}/{total} 단계)","eta.byTodoSoon":"할 일 기준 1분 이내 ({completed}/{total} 단계)","eta.byTodoHint":"todo 완료 비율로만 잰 값입니다. 단계마다 걸리는 시간이 달라 오차가 큽니다.","eta.rework":"재작업 {attempt}차 \xb7 첫 발주부터 {duration}","eta.reworkAttempt":"재작업 {attempt}차","eta.reworkHint":"재작업 시도는 과거 소요 기록이 거의 없어 남은 시간\xb7%를 추정하지 않습니다. 첫 발주부터의 시간에는 시도 사이 Main 검수\xb7대기 시간이 들어 있습니다.","eta.rangeMinutes":"{low}~{high}분","eta.range":"{low}~{high}","duration.seconds":"{seconds}초","duration.minutesSeconds":"{minutes}분 {seconds}초","duration.minutes":"{minutes}분","duration.hours":"{hours}시간","duration.hoursMinutes":"{hours}시간 {minutes}분","duration.underMinute":"1분 미만"},en:{"dispatch.title":"Subagents: {count}","dispatch.tally":"{running} running \xb7 {done} finished \xb7 {accepted} accepted by Main","dispatch.expand":"Show dispatch details","dispatch.collapse":"Hide dispatch details","dock.label":"Subagents","dock.running":"{count} running","dock.awaiting":"{count} awaiting verdict","dock.jump":"Go to the dispatch card — {title}","dock.openPanel":"Open subagent details — {title}","run.dispatching":"Dispatching","run.pending":"Queued","run.running":"Running","run.completed":"Run finished","run.failed":"Run failed","run.aborted":"Stopped","run.unobserved":"Run state not observed","verdict.accepted":"Accepted by Main","verdict.rework":"Main asked for rework","verdict.held":"Held by Main","verdict.none":"No review recorded","verdict.attempt":"attempt {attempt}","detail.stage":"Current step","detail.stageNone":"Not recorded","detail.model":"Model","detail.modelNone":"Not observed","detail.fallback":"fallback","detail.agentId":"Agent ID","detail.reason":"Review note","detail.source.live":"live","detail.source.record":"session record","detail.openSubagents":"Open subagent details","detail.openProcess":"Open work log","summary.files":"{count} files changed","summary.checks":"{count} checks","summary.checksFailed":"{count} failed","summary.unverified":"{count} unverified","summary.expand":"Show turn summary","summary.collapse":"Hide turn summary","summary.heading.files":"Files changed","summary.heading.checks":"Checks run","summary.heading.unverified":"Unverified","summary.check.exit":"exit {code}","summary.check.error":"ended with an error","summary.check.unobserved":"result not observed","summary.u.checkFailed":"Check failed — {command}","summary.u.checkUnobserved":"Check result not observed — {command}","delivery.title":"{count} sent","delivery.kind.steer":"Now","delivery.kind.followUp":"After this run","delivery.stage.sending":"Sending","delivery.stage.accepted":"Received \xb7 waiting to deliver","delivery.stage.delivered":"Delivered \xb7 in the conversation","delivery.stage.failed":"Not sent \xb7 back in the composer","delivery.stage.unconfirmed":"Delivery not confirmed \xb7 left the queue","delivery.images":"{count} image(s)","delivery.showOlder":"Show {count} earlier","delivery.showRecent":"Show only the latest {count}","live.nativeVoice":"default voice","progress.label":"Progress","phase.investigate":"Investigate","phase.implement":"Implement","phase.verify":"Verify","phase.report":"Report","phase.current":"current phase {phase}","phase.hint":"Current phase read from tool calls. It goes back when the child edits again after checking.","progress.todo":"todo {completed}/{total} ({percent}%)","eta.label":"Estimate","eta.elapsed":"{duration} elapsed","eta.remaining":"usually {range} left ({samples} past runs)","eta.percent":"about {percent}% (estimate)","eta.overrun":"At or beyond the longest past run ({longest})","eta.sparseTail":"Only {longerRuns} of {samples} past runs took longer","eta.hint":"Middle half of the remaining time among past first attempts of the same model and class that ran longer than this one has so far.","eta.byTodo":"about {duration} left by todo ({completed}/{total} steps)","eta.byTodoSoon":"under a minute left by todo ({completed}/{total} steps)","eta.byTodoHint":"Measured from the todo completion ratio only. Steps take different amounts of time, so this can be far off.","eta.rework":"rework attempt {attempt} \xb7 {duration} since first dispatch","eta.reworkAttempt":"rework attempt {attempt}","eta.reworkHint":"Rework attempts have almost no recorded durations, so no remaining time or % is estimated. Time since the first dispatch includes Main review and waiting between attempts.","eta.rangeMinutes":"{low}–{high} min","eta.range":"{low}–{high}","duration.seconds":"{seconds} s","duration.minutesSeconds":"{minutes} min {seconds} s","duration.minutes":"{minutes} min","duration.hours":"{hours} h","duration.hoursMinutes":"{hours} h {minutes} min","duration.underMinute":"under 1 min"},"zh-CN":{"dispatch.title":"{count} 个子代理","dispatch.tally":"运行中 {running} \xb7 运行完成 {done} \xb7 Main 已接受 {accepted}","dispatch.expand":"展开派发详情","dispatch.collapse":"收起派发详情","dock.label":"子代理","dock.running":"运行中 {count}","dock.awaiting":"等待判定 {count}","dock.jump":"转到派发卡片 — {title}","dock.openPanel":"打开子代理详情 — {title}","run.dispatching":"派发中","run.pending":"等待中","run.running":"运行中","run.completed":"运行完成","run.failed":"运行失败","run.aborted":"已中止","run.unobserved":"未观测到运行状态","verdict.accepted":"Main 已接受","verdict.rework":"Main 要求返工","verdict.held":"Main 暂缓","verdict.none":"未记录审查","verdict.attempt":"第 {attempt} 次","detail.stage":"当前步骤","detail.stageNone":"无记录","detail.model":"模型","detail.modelNone":"未观测","detail.fallback":"备用模型","detail.agentId":"代理 ID","detail.reason":"审查说明","detail.source.live":"实时观测","detail.source.record":"会话记录","detail.openSubagents":"打开子代理详情","detail.openProcess":"打开工作记录","summary.files":"变更文件 {count}","summary.checks":"检查 {count}","summary.checksFailed":"失败 {count}","summary.unverified":"未确认 {count}","summary.expand":"展开本轮摘要","summary.collapse":"收起本轮摘要","summary.heading.files":"变更文件","summary.heading.checks":"已运行的检查","summary.heading.unverified":"未确认","summary.check.exit":"exit {code}","summary.check.error":"以错误结束","summary.check.unobserved":"未观测到结果","summary.u.checkFailed":"检查失败 — {command}","summary.u.checkUnobserved":"未观测到检查结果 — {command}","delivery.title":"已发送 {count}","delivery.kind.steer":"立即指示","delivery.kind.followUp":"完成后请求","delivery.stage.sending":"发送中","delivery.stage.accepted":"已接收 \xb7 等待送达","delivery.stage.delivered":"已送达 \xb7 已进入对话","delivery.stage.failed":"未发送 \xb7 已退回输入框","delivery.stage.unconfirmed":"未能确认送达 \xb7 已离开队列","delivery.images":"图片 {count} 张","delivery.showOlder":"显示更早的 {count} 条","delivery.showRecent":"仅显示最近 {count} 条","live.nativeVoice":"默认语音","progress.label":"进度","phase.investigate":"调查","phase.implement":"实现","phase.verify":"验证","phase.report":"报告","phase.current":"当前阶段 {phase}","phase.hint":"根据工具调用判断的当前阶段。验证后再次修改时会回到前一阶段。","progress.todo":"待办 {completed}/{total}({percent}%)","eta.label":"预计时间","eta.elapsed":"已用 {duration}","eta.remaining":"通常还需 {range}(过去 {samples} 次)","eta.percent":"约 {percent}%(估计)","eta.overrun":"已达到或超过过去最长记录({longest})","eta.sparseTail":"过去 {samples} 次中仅 {longerRuns} 次用时更长","eta.hint":"同模型、同等级的过去首次尝试中,运行时间超过当前已用时间的那些实行的剩余时间分布(中间一半)。","eta.byTodo":"按待办约还需 {duration}({completed}/{total} 步)","eta.byTodoSoon":"按待办 1 分钟内({completed}/{total} 步)","eta.byTodoHint":"仅按 todo 完成比例估算。各步骤耗时不同,误差可能很大。","eta.rework":"返工第 {attempt} 次 \xb7 自首次派发 {duration}","eta.reworkAttempt":"返工第 {attempt} 次","eta.reworkHint":"返工尝试几乎没有耗时记录,因此不估算剩余时间和百分比。自首次派发起的时间包含各次尝试之间 Main 审查和等待的时间。","eta.rangeMinutes":"{low}~{high} 分钟","eta.range":"{low}~{high}","duration.seconds":"{seconds} 秒","duration.minutesSeconds":"{minutes} 分 {seconds} 秒","duration.minutes":"{minutes} 分钟","duration.hours":"{hours} 小时","duration.hoursMinutes":"{hours} 小时 {minutes} 分钟","duration.underMinute":"不到 1 分钟"}};function ng(){let{locale:e}=(0,R.s)();return{st:(0,i.useCallback)((t,n)=>(0,J.u0)(e,t,nf,n),[e]),locale:e}}function nx({seed:e,size:t,provider:n}){let[a,s]=(0,i.useState)(!1),[l,o]=(0,i.useState)(!1);return a?(0,r.jsx)("span",{className:"account-avatar account-avatar-mono","data-tone":e%6,style:{width:t,height:t,fontSize:Math.round(.46*t)},"aria-hidden":"true",children:(0,nt.xl)(e).slice(0,1)}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("button",{type:"button",className:"account-avatar-button",style:{width:t,height:t},onClick:e=>{e.stopPropagation(),o(!0)},"aria-label":(0,nt.xl)(e),children:(0,r.jsx)("img",{className:"account-avatar",src:(0,nt.uk)(e),width:t,height:t,alt:"","aria-hidden":"true",draggable:!1,onError:()=>s(!0)})}),l&&(0,r.jsx)(nv,{seed:e,provider:n,onClose:()=>o(!1)})]})}function nv({seed:e,provider:t,onClose:n}){let{t:a}=(0,R.s)(),s=(0,i.useRef)(null);(0,i.useEffect)(()=>{let e=s.current;if(!e)return;let t=document.body.style.overflow;return document.body.style.overflow="hidden",e.showModal(),()=>{document.body.style.overflow=t,e.open&&e.close()}},[]);let l=(0,nt.xl)(e);return(0,F.createPortal)((0,r.jsxs)("dialog",{ref:s,className:"account-avatar-dialog","aria-label":l,onCancel:e=>{e.preventDefault(),n()},onKeyDown:e=>{"Escape"===e.key&&(e.preventDefault(),n())},onClick:e=>{e.stopPropagation(),e.target===e.currentTarget&&n()},children:[(0,r.jsx)("img",{className:"account-avatar-full",src:(0,nt.uk)(e),width:256,height:256,alt:l,draggable:!1}),(0,r.jsxs)("p",{className:"account-avatar-caption",children:[(0,r.jsx)("span",{className:"account-avatar-caption-alias",children:l}),t?(0,r.jsx)("span",{className:"account-avatar-caption-provider",children:(0,nt.bN)(t)}):null]}),(0,r.jsx)("button",{type:"button",className:"account-avatar-close",onClick:n,children:a("i18n.close")})]}),document.body)}function nb(e){let t,n=[],r=null,i=0,a=0,s=0,l=0,o=[],d=[],c=()=>({lineNo:null,text:"",type:"empty"}),u=()=>{if(!r){o=[],d=[];return}let e=Math.max(o.length,d.length);for(let t=0;t<e;t++){let e=o[t]?{lineNo:o[t].lineNo,text:o[t].text,type:"removed"}:c(),n=d[t]?{lineNo:d[t].lineNo,text:d[t].text,type:"added"}:c();r.rows.push({type:"line",left:e,right:n})}o=[],d=[]};for(let c of e.split(/\r?\n/)){if(!(s>0||l>0)){if(c.startsWith("--- ")){u(),t=ny(c.slice(4));continue}if(c.startsWith("+++ ")){u(),r={oldPath:t,newPath:ny(c.slice(4)),rows:[]},n.push(r);continue}}let e=c.match(/^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/);if(e){r||(r={rows:[]},n.push(r)),u(),i=Number(e[1]),a=Number(e[3]),s=void 0===e[2]?1:Number(e[2]),l=void 0===e[4]?1:Number(e[4]),r.rows.push({type:"hunk",text:c});continue}if(!r)continue;if(c.startsWith("\\ ")){u(),r.rows.push({type:"hunk",text:c});continue}let p=c[0],h=c.slice(1);" "===p?(u(),r.rows.push({type:"line",left:{lineNo:i++,text:h,type:"context"},right:{lineNo:a++,text:h,type:"context"}}),s>0&&s--,l>0&&l--):"-"===p?(o.push({lineNo:i++,text:h}),s>0&&s--):"+"===p?(d.push({lineNo:a++,text:h}),l>0&&l--):""!==c&&(u(),r.rows.push({type:"hunk",text:c}))}u();let p=n.filter(e=>e.rows.some(e=>"line"===e.type));return p.length>0?p:null}function ny(e){return e.split(" ")[0].trim()}function nw({task:e}){let t="completed"===e.status,n="abandoned"===e.status,i="in_progress"===e.status,a="blocked"===e.status;return(0,r.jsxs)("div",{role:"listitem","aria-label":`${e.status}: ${e.content}`,className:`todo-checklist-row ${t?"is-completed":n?"is-abandoned":a?"is-blocked":i?"is-active":"is-pending"}`,children:[(0,r.jsx)("span",{"aria-hidden":"true",className:"todo-checklist-marker",children:t?"✓":n?"\xd7":a?"!":i?"›":""}),(0,r.jsxs)("span",{className:"todo-checklist-content",children:[e.content,a&&e.blocker?(0,r.jsxs)("span",{className:"todo-checklist-blocker",children:[" (",e.blocker,")"]}):null]})]})}let nk="/icons/catppuccin";function nj({name:e,size:t=14}){let n={width:t,height:t,"--catppuccin-icon-light":`url(${nk}/latte/${e}.svg)`,"--catppuccin-icon-dark":`url(${nk}/mocha/${e}.svg)`};return(0,r.jsx)("span",{"aria-hidden":"true",className:"catppuccin-file-icon",style:n})}function nS({size:e=14,open:t=!1}){return(0,r.jsx)(nj,{name:t?"_folder_open":"_folder",size:e})}function nC({size:e=14}){return(0,r.jsx)(nj,{name:"_file",size:e})}let nN={ts:"typescript",tsx:"typescript-react",js:"javascript",mjs:"javascript",cjs:"javascript",jsx:"javascript-react",py:"python",json:"json",jsonl:"json",css:"css",less:"css",scss:"sass",html:"html",htm:"html",md:"markdown",markdown:"markdown",mdx:"markdown",yaml:"yaml",yml:"yaml",toml:"toml",sh:"bash",bash:"bash",zsh:"bash",fish:"bash",rs:"rust",go:"go",sql:"database",graphql:"graphql",gql:"graphql",tf:"terraform",hcl:"terraform",docx:"ms-word",pdf:"pdf",lock:"lock"};function nI(e,t=14){let n=e.toLowerCase(),i="dockerfile"===n||n.startsWith("dockerfile.")?"docker":".env"===n||n.startsWith(".env.")?"env":[".gitignore",".gitattributes",".gitmodules"].includes(n)?"git":"package-lock.json"===n?"npm-lock":"bun.lock"===n?"bun-lock":["next.config.js","next.config.mjs","next.config.cjs","next.config.ts"].includes(n)?"next":[".eslintrc",".eslintrc.js",".eslintrc.json",".eslintrc.yml","eslint.config.mjs","eslint.config.js"].includes(n)?"eslint":["yarn.lock","pnpm-lock.yaml","cargo.lock"].includes(n)?"lock":n.endsWith(".config.ts")||n.endsWith(".config.js")||n.endsWith(".config.mjs")||n.endsWith(".config.cjs")?"config":void 0;if(i)return(0,r.jsx)(nj,{name:i,size:t});let a=nN[n.split(".").pop()??""];return a?(0,r.jsx)(nj,{name:a,size:t}):(0,r.jsx)(nC,{size:t})}function nT({files:e,onOpenFile:t}){let{t:n}=(0,R.s)();return 0===e.length?null:(0,r.jsx)("div",{"aria-label":n("chat.filesWritten"),style:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:6,marginTop:6},children:e.map(({filePath:e})=>{let i=ta(e);return(0,r.jsxs)("button",{type:"button",title:e,"aria-label":n("chat.openWrittenFile",{name:i}),onClick:()=>t?.(e),style:{display:"inline-flex",alignItems:"center",gap:4,padding:"2px 8px",fontSize:12,fontFamily:"var(--font-mono)",color:"var(--text)",background:"var(--bg-subtle)",border:"1px solid var(--border)",borderRadius:6,cursor:"pointer"},children:[nI(i,12),(0,r.jsx)("span",{children:i})]},e)})})}var nM=n(59959);let n$={verdicts:new Map,runs:new Map,latestByAgent:new Map};function nR(e){return Array.isArray(e)?e.filter(e=>"object"==typeof e&&null!==e):[]}function nE(e){return"string"==typeof e&&e.trim()?e:null}function nL(e){switch(e){case"pending":case"queued":return"pending";case"running":return"running";case"completed":case"success":return"completed";case"failed":case"error":return"failed";case"aborted":case"cancelled":case"canceled":return"aborted";default:return null}}function nA(e){return"string"==typeof e?e:e.map(e=>"text"===e.type?e.text:"").join("\n")}function nz(e,t){if(t?.isError)return null;let n=nR(e.input.tasks),r=nR(t?.details?.progress),i=Math.max(n.length,r.length),a=[];for(let s=0;s<i;s++){let i=r.find(e=>e.index===s)??r[s],l=n[s],o=nE(i?.id)??nE(l?.name);o&&a.push({key:`${e.toolCallId}#${s}`,toolCallId:e.toolCallId,index:s,agentId:o,agent:nE(i?.agent)??nE(l?.agent),task:nE(i?.task)??nE(l?.task)??"",spawned:!!t})}return a}let nP=/<task-result\b([^>]*)>/g,nW=/(\w+)="([^"]*)"/g;function nF(e,t,n){return t.find(t=>t.parentToolCallId?t.parentToolCallId===e.toolCallId&&t.id===e.agentId:t.id===e.agentId&&n.latestByAgent.get(e.agentId)===e.key)}function n_(e,t,n){let r,i=nF(e,t,n),a=i?{key:e.key,identity:"live",live:i.assignment?i:{...i,assignment:e.task}}:{key:e.key,identity:"live",live:{id:e.agentId,index:e.index,agent:e.agent??"",agentSource:"user",status:"unknown",task:e.task,lastUpdate:0}},s=(0,nM.$V)(a),l=n.runs.get(e.key),o=null;i&&"unknown"!==i.status?(r=i.status,o="live"):l&&"unknown"!==l.status?(r=l.status,o="record"):r=e.spawned?"unobserved":"dispatching";let d=n.verdicts.get(e.key);return{member:e,title:s.title,explicitTitle:s.explicitTitle,stage:i?s.stage:null,model:i?(0,nM.A7)(a):null,run:r,runSource:o,verdict:d&&d.length>0?d[d.length-1]:null}}function nD(e){return"assistant"!==e.role?[]:e.content?.filter(e=>"toolCall"===e.type&&"task"===e.toolName)??[]}function nO(e,t,n){let r=-1;n.forEach((e,t)=>{"user"===e.role&&(r=t)});let i=n.slice(0,r+1).flatMap(nD),a=n.slice(r+1).flatMap(nD),s=t.findIndex(e=>"user"===e.role),l=0===a.length?-1:e.findIndex(e=>"answer"===e.kind&&(-1===s||e.idx<s));return -1===l?{continuing:null,atCompaction:[...i,...a]}:{continuing:{position:l,calls:a},atCompaction:i}}let nH={dispatching:"running",pending:"running",running:"running",completed:"awaiting",failed:"awaiting",aborted:"awaiting",unobserved:null},nB=/(?:^|[^\w-])(?:tests?|typecheck|tsc|lint|eslint|vitest|jest|pytest|build|check|verify|smoke)(?![\w])/i;function nU(e,t,n){let r=[],i=[];for(let n of e){if("toolCall"!==n.type)continue;if("task"===n.toolName){i.push(n);continue}if("bash"!==n.toolName)continue;let e="string"==typeof n.input.command?n.input.command.trim():"";if(!e||!nB.test(e))continue;let a=t.get(n.toolCallId),s=a?tX(a):null,l=null===s?a?.isError?"failed":"unobserved":0===s?"passed":"failed";r.push({toolCallId:n.toolCallId,command:e,state:l,exitCode:s})}return{checks:r,dispatchCalls:i,files:e8(e,t,n)}}var nq=n(75514);let nK=(0,i.createContext)({ledger:n$,subagents:[],toolResults:new Map});function nV(e,t){if(0===e.length)return null;let n=[...e].sort((e,t)=>e-t),r=(n.length-1)*t,i=Math.floor(r),a=Math.ceil(r);return n[i]+(n[a]-n[i])*(r-i)}let nJ=["investigate","implement","verify","report"],nG={edit:!0,write:!0,ast_edit:!0,multiedit:!0,notebookedit:!0},nY={bash:!0,eval:!0};function nZ(e){if(e<6e4)return null;let t=Math.round(e/6e4);return{hours:Math.floor(t/60),minutes:t%60}}function nX({sessionId:e,snapshots:t,client:n,enabled:r,transcripts:a=!0}){let s=(0,i.useMemo)(()=>t.filter(e=>(0,nq.Ch)(e.status)),[t]),l=r&&!!e&&s.length>0,o=(0,i.useMemo)(()=>s.map(e=>({key:e.id,liveId:e.id,status:e.status})),[s]),d=(0,nq._Z)(o,{sessionId:e??"",client:n,enabled:l&&a}),[c,u]=(0,i.useState)(null),p=s.map(e=>e.id).sort().join("\n");return(0,i.useEffect)(()=>{let t;if(!l||!e)return;let n=new AbortController,r=p.split("\n"),i=`/api/subagents/eta?sessionId=${encodeURIComponent(e)}`,a=!0,s=0;async function o(){try{let t=await fetch(i,{signal:AbortSignal.any([n.signal,AbortSignal.timeout(15e3)])}),s=t.ok?await t.json():null;!n.signal.aborted&&s&&s.sessionId===e&&s.histories&&"object"==typeof s.histories&&(u(s),a=r.some(e=>!s.histories[e]))}catch{}finally{if(!n.signal.aborted){let e=a&&s<3;e&&(s+=1),t=window.setTimeout(o,e?1e4:6e4)}}}return o(),()=>{n.abort(),window.clearTimeout(t)}},[p,l,e]),(0,i.useMemo)(()=>{let t=new Map;if(!l)return t;let n=c&&c.sessionId===e?c.histories:void 0;for(let e of s){let r=(a?d.get(e.id)?.entries??[]:[]).flatMap(e=>"message"in e?[e.message]:[]);t.set(e.id,{phase:function(e){if(0===e.length)return null;let t="investigate",n=!1;for(let r of e){if("assistant"!==r.role)continue;let e=r.content;if(Array.isArray(e))for(let r of e){if("toolCall"!==r.type)continue;let e=(r.toolName??"").toLowerCase().split(/[.:/]/).pop()??"";nG[e]?(n=!0,t="implement"):nY[e]?t=n?"verify":"investigate":"yield"===e&&(t="report",n=!1)}}return t}(r),todo:function(e){let t=new Map;for(let n of e)"toolResult"===n.role&&t.set(n.toolCallId,n);let n=e7([...e],t);if(!n)return null;let r=e9(n);return 0===r.total||null===r.percent?null:{completed:r.completed,total:r.total,percent:r.percent,activeTask:r.activeTask?.content??null}}(r),history:n?.[e.id]??null})}return t},[s,c,l,d,e,a])}function nQ(e,t){let n=nZ(t);return n?0===n.hours?e("duration.minutes",{minutes:n.minutes}):0===n.minutes?e("duration.hours",{hours:n.hours}):e("duration.hoursMinutes",{hours:n.hours,minutes:n.minutes}):e("duration.underMinute")}function n0(e,t){let n=Math.floor(t/1e3);return n<60?e("duration.seconds",{seconds:n}):n<3600?e("duration.minutesSeconds",{minutes:Math.floor(n/60),seconds:n%60}):nQ(e,t)}function n1({phase:e}){let{st:t}=ng();return(0,r.jsxs)("span",{className:"subagent-phase-steps","data-phase":e,title:t("phase.hint"),style:{position:"relative"},children:[(0,r.jsx)("span",{className:"sr-only",children:t("phase.current",{phase:t(`phase.${e}`)})}),(0,r.jsx)("span",{"aria-hidden":"true",children:nJ.map((n,i)=>(0,r.jsxs)("span",{children:[i>0&&(0,r.jsx)("span",{style:{color:"var(--seed-color-fg-neutral-subtle, var(--text-muted))"},children:" › "}),(0,r.jsx)("span",{"data-current":n===e?"":void 0,style:n===e?{color:"var(--accent)",fontWeight:700}:{color:"var(--seed-color-fg-neutral-subtle, var(--text-muted))"},children:t(`phase.${n}`)})]},n))})]})}function n2(e,t){let n=e("progress.todo",{completed:t.completed,total:t.total,percent:t.percent});return t.activeTask?`${n} \xb7 ${t.activeTask}`:n}function n4({snapshot:e,view:t,id:n}){var i,a,s;let l,o,d,{st:c}=ng(),u=tY(5e3),p="number"!=typeof(l=e.progress?.durationMs)?null:l+(("pending"===e.status||"running"===e.status)&&e.lastUpdate>0?Math.max(0,u-e.lastUpdate):0);if(null===p)return null;let h=function(e,t){if(!e||e.rework||null===t||e.durationsSec.length<3)return null;let n=e.durationsSec.map(e=>1e3*e-t).filter(e=>e>0);if(n.length<3)return{kind:"overrun",longestMs:1e3*Math.max(...e.durationsSec),samples:e.durationsSec.length,longerRuns:n.length};let r=nV(n,.5)??0;return{kind:"remaining",p25Ms:nV(n,.25)??0,medianMs:r,p75Ms:nV(n,.75)??0,samples:n.length,percent:Math.round(t/(t+r)*100)}}(t.history,p),m=(i=t.todo,!i||null===p||0===i.completed||i.completed>=i.total?null:p*(i.total-i.completed)/i.completed),f={color:"var(--seed-color-fg-neutral-subtle, var(--text-muted))"},g=t.history,x=g?.rework&&null!==g.firstDispatchedAtMs?u-g.firstDispatchedAtMs:null;return(0,r.jsxs)("span",{id:n,className:"subagent-live-eta","data-eta":h?.kind??(g?.rework?"rework":"none"),children:[(0,r.jsx)("span",{"data-elapsed":Math.floor(p/1e3),children:c("eta.elapsed",{duration:n0(c,p)})}),g?.rework&&(0,r.jsxs)(r.Fragment,{children:[" \xb7 ",(0,r.jsx)("span",{style:f,title:c("eta.reworkHint"),children:null!==x&&x>=0?c("eta.rework",{attempt:g.attempt,duration:n0(c,x)}):c("eta.reworkAttempt",{attempt:g.attempt})})]}),h?.kind==="remaining"&&(0,r.jsxs)(r.Fragment,{children:[" \xb7 ",(0,r.jsx)("span",{title:c("eta.hint"),children:c("eta.remaining",{range:(a=h.p25Ms,s=h.p75Ms,o=nZ(a),d=nZ(s),o&&d&&0===o.hours&&0===d.hours?o.minutes===d.minutes?c("duration.minutes",{minutes:o.minutes}):c("eta.rangeMinutes",{low:o.minutes,high:d.minutes}):c("eta.range",{low:nQ(c,a),high:nQ(c,s)})),samples:h.samples})})," \xb7 ",(0,r.jsx)("span",{style:f,children:c("eta.percent",{percent:h.percent})})]}),h?.kind==="overrun"&&(0,r.jsxs)(r.Fragment,{children:[" \xb7 ",(0,r.jsx)("span",{style:{color:"var(--warning)"},title:c("eta.hint"),children:0===h.longerRuns?c("eta.overrun",{longest:nQ(c,h.longestMs)}):c("eta.sparseTail",{samples:h.samples,longerRuns:h.longerRuns})})]}),null!==m&&t.todo&&(0,r.jsxs)(r.Fragment,{children:[" \xb7 ",(0,r.jsx)("span",{style:f,title:c("eta.byTodoHint"),children:m<6e4?c("eta.byTodoSoon",{completed:t.todo.completed,total:t.todo.total}):c("eta.byTodo",{duration:nQ(c,m),completed:t.todo.completed,total:t.todo.total})})]})]})}let n5={dispatching:"run.dispatching",pending:"run.pending",running:"run.running",completed:"run.completed",failed:"run.failed",aborted:"run.aborted",unobserved:"run.unobserved"},n6={accepted:"verdict.accepted",rework:"verdict.rework",held:"verdict.held",none:"verdict.none"};function n8({maker:e,st:t}){let n=e.verdict?.verdict??"none",i=e.verdict?.attempt;return(0,r.jsxs)("span",{className:"answer-status-pair",children:[(0,r.jsx)("span",{className:"answer-status-run","data-state":e.run,children:t(n5[e.run])}),(0,r.jsx)("span",{className:"answer-status-arrow","aria-hidden":"true",children:"→"}),(0,r.jsxs)("span",{className:"answer-status-verdict","data-verdict":n,children:[t(n6[n]),null!=i&&i>1?` \xb7 ${t("verdict.attempt",{attempt:i})}`:null]})]})}function n3(e,t){let n=[],r=new Map;for(let t of e)"message"in t&&("assistant"===t.message.role?n.push(...t.message.content??[]):"toolResult"===t.message.role&&r.set(t.message.toolCallId,t.message));return nU(n,r,t)}function n7({calls:e}){let{ledger:t,subagents:n,toolResults:a,onOpenPanel:s,focusedDispatch:l,sessionId:o,onOpenMaker:d,selectedMaker:c}=(0,i.useContext)(nK),{st:u}=ng(),{t:p}=(0,R.s)(),[h,m]=(0,i.useState)(!1),f=(0,i.useId)(),g=(0,i.useMemo)(()=>(0,nM.Et)(),[]),x=(0,i.useMemo)(()=>e.flatMap(e=>nz(e,a.get(e.toolCallId))??[]).map(e=>n_(e,n,t)),[e,a,n,t]),v=(0,i.useMemo)(()=>x.flatMap(e=>{if("pending"!==e.run&&"running"!==e.run)return[];let r=nF(e.member,n,t);return r?[r]:[]}),[x,n,t]),b=nX({sessionId:o,snapshots:v,client:g,enabled:!0,transcripts:h}),y=(0,i.useMemo)(()=>new Map(x.flatMap(e=>{var t;let r=(t=e.member,n.find(e=>e.parentToolCallId===t.toolCallId&&e.id===t.agentId));return r?[[e.member.key,r]]:[]})),[x,n]),w=(0,i.useMemo)(()=>h?[...y].filter(([,e])=>!(0,nq.Ch)(e.status)).map(([e,t])=>({key:e,liveId:t.id,status:t.status,archiveName:t.sessionFile?.split(/[\\/]/).pop()?.replace(/\.jsonl$/i,"")||void 0})):[],[y,h]),k=(0,nq._Z)(w,{sessionId:o??"",client:g,enabled:h&&!!o&&w.length>0}),j=c?.origin?x.find(e=>e.member.key===c.origin):void 0,S=j?.run,C=j?.verdict??null;if((0,i.useEffect)(()=>{if(!c||!d||!S)return;let e=c.status;e&&e.run===S&&e.verdict?.order===C?.order||d({...c,status:{run:S,verdict:C}},!1)},[d,c,S,C]),0===x.length)return null;let N=0,I=0,T=0;for(let e of x)("dispatching"===e.run||"pending"===e.run||"running"===e.run)&&(N+=1),"completed"===e.run&&(I+=1),e.verdict?.verdict==="accepted"&&(T+=1);return(0,r.jsxs)("section",{className:l&&x.some(e=>e.member.key===l)?"answer-dispatch answer-dispatch-flash":"answer-dispatch","aria-label":u("dispatch.title",{count:x.length}),children:[(0,r.jsxs)("button",{type:"button",className:"answer-dispatch-toggle","aria-expanded":h,"aria-controls":f,title:u(h?"dispatch.collapse":"dispatch.expand"),onClick:()=>m(e=>!e),children:[(0,r.jsx)("span",{className:"answer-dispatch-heading",children:u("dispatch.title",{count:x.length})}),(0,r.jsx)("span",{className:"answer-dispatch-tally",children:u("dispatch.tally",{running:N,done:I,accepted:T})}),(0,r.jsx)("svg",{className:"answer-chevron",width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"6 9 12 15 18 9"})})]}),(0,r.jsx)("ul",{className:"answer-dispatch-list",id:f,"aria-label":h?p("dispatchLane.label"):void 0,children:x.map(e=>{let t="pending"===e.run||"running"===e.run,n=t?v.find(t=>t.id===e.member.agentId):void 0,i=n?b.get(n.id):void 0,a=y.get(e.member.key),s=e.member.key===l||e.member.key===c?.origin;return(0,r.jsxs)("li",{className:"answer-dispatch-row","data-dispatch-key":e.member.key,"data-focused":s?"":void 0,children:[h?(0,r.jsx)(n9,{maker:e,phase:i?.phase?u(`phase.${i.phase}`):null,checks:function(e,t){if(!t)return{kind:"unobserved"};if((0,nq.Ch)(t.status))return{kind:"running"};let n=e?.state;if(!n||"loading"===n.kind)return{kind:"loading"};if("ready-live"===n.kind){let{checks:e}=n3(n.entries);return{kind:"counted",passed:e.filter(e=>"passed"===e.state).length,total:e.length}}return"empty"===n.kind&&"live"===n.source?{kind:"counted",passed:0,total:0}:{kind:"unobserved"}}(k.get(e.member.key),a),onOpen:a&&d?()=>d({key:`live:${a.id}`,toolCallId:e.member.toolCallId,origin:e.member.key,status:{run:e.run,verdict:e.verdict}}):null}):(0,r.jsxs)("div",{className:"answer-dispatch-line",children:[(0,r.jsx)("span",{className:"answer-dispatch-name",title:e.title,children:e.title}),(0,r.jsx)(n8,{maker:e,st:u})]}),h&&(0,r.jsx)(re,{maker:e}),n&&i&&(0,r.jsxs)("div",{className:"answer-dispatch-progress",children:[i.phase&&(0,r.jsx)(n1,{phase:i.phase}),i.phase&&i.todo?` \xb7 ${n2(u,i.todo)}`:null,i.phase?" \xb7 ":null,(0,r.jsx)(n4,{snapshot:n,view:i})]}),h&&(0,r.jsxs)("dl",{className:"answer-dispatch-detail",children:[t&&(0,r.jsxs)("div",{children:[(0,r.jsx)("dt",{children:u("detail.stage")}),(0,r.jsx)("dd",{children:e.stage??u("detail.stageNone")})]}),(0,r.jsxs)("div",{children:[(0,r.jsx)("dt",{children:u("detail.model")}),(0,r.jsx)("dd",{title:e.model?.model??void 0,children:e.model?.modelShort?`${e.model.modelShort}${e.model.effort?` \xb7 ${e.model.effort}`:""}${e.model.modelIsFallback?` \xb7 ${u("detail.fallback")}`:""}`:u("detail.modelNone")})]}),(0,r.jsxs)("div",{children:[(0,r.jsx)("dt",{children:u("detail.agentId")}),(0,r.jsxs)("dd",{children:[(0,r.jsx)("span",{className:"answer-mono",children:e.member.agentId}),e.runSource?` \xb7 ${u("live"===e.runSource?"detail.source.live":"detail.source.record")}`:""]})]}),e.verdict?.reason&&(0,r.jsxs)("div",{children:[(0,r.jsx)("dt",{children:u("detail.reason")}),(0,r.jsx)("dd",{children:e.verdict.reason})]})]})]},e.member.key)})}),h&&s&&(0,r.jsxs)("div",{className:"answer-dispatch-links",children:[(0,r.jsx)("button",{type:"button",className:"answer-link",onClick:()=>s("subagents"),children:u("detail.openSubagents")}),(0,r.jsx)("button",{type:"button",className:"answer-link",onClick:()=>s("process"),children:u("detail.openProcess")})]})]})}function n9({maker:e,phase:t,checks:n,onOpen:i}){let{st:a}=ng(),{t:s}=(0,R.s)(),l=e.verdict?.verdict??"none",o=a(n5[e.run]),d="running"===n.kind?null:"counted"===n.kind?s("dispatchLane.checks",{passed:n.passed,total:n.total}):s("loading"===n.kind?"dispatchLane.checksLoading":"dispatchLane.checksUnobserved");return(0,r.jsxs)("div",{className:"answer-dispatch-line is-lane",children:[(0,r.jsx)("span",{className:"answer-dispatch-name",title:e.title,children:e.title}),(0,r.jsxs)("span",{className:"answer-status-pair",children:[(0,r.jsx)("span",{className:"answer-status-run","data-state":e.run,children:t?s("dispatchLane.runPhase",{run:o,phase:t}):o}),d&&(0,r.jsx)("span",{className:"answer-dispatch-checks","data-checks":"counted"===n.kind&&n.passed<n.total?"failed":n.kind,children:d}),(0,r.jsx)("span",{className:"answer-status-arrow","aria-hidden":"true",children:"→"}),(0,r.jsx)("span",{className:"answer-status-verdict","data-verdict":l,children:a(n6[l])})]}),i?(0,r.jsx)("button",{type:"button",className:"answer-link answer-dispatch-open","aria-label":s("dispatchLane.openLabel",{title:e.title}),onClick:i,children:s("dispatchLane.open")}):(0,r.jsx)("span",{className:"answer-dispatch-unavailable",title:s("makerDetail.unavailable"),children:s("dispatchLane.unavailable")})]})}function re({maker:e}){let{ledger:t}=(0,i.useContext)(nK),{t:n}=(0,R.s)(),a=function(e,t){let n=[...t.verdicts.get(e.key)??[]].sort((e,t)=>e.order-t.order),r=new Map,i=[];for(let e of n){let t={attempt:e.attempt,verdict:e.verdict,reason:e.reason};null===e.attempt?i.push(t):r.set(e.attempt,t)}return[...i,...[...r.values()].sort((e,t)=>(e.attempt??0)-(t.attempt??0))]}(e.member,t);return a.length<2?null:(0,r.jsx)("ol",{className:"answer-dispatch-attempts","aria-label":n("dispatchLane.label"),children:a.map((e,t)=>(0,r.jsxs)("li",{"data-verdict":e.verdict,title:e.reason??void 0,children:[t>0&&(0,r.jsx)("span",{className:"answer-status-arrow","aria-hidden":"true",children:"→ "}),null===e.attempt?n("dispatchLane.attemptUnknown"):n("dispatchLane.attempt",{attempt:e.attempt})," ",n(`dispatchLane.verdict.${e.verdict}`)]},`${e.attempt??"n"}-${t}`))})}function rt({summary:e,onOpenFile:t}){let{ledger:n,subagents:a,toolResults:s}=(0,i.useContext)(nK),{st:l}=ng(),[o,d]=(0,i.useState)(!1),c=(0,i.useId)(),u=(0,i.useMemo)(()=>e.dispatchCalls.flatMap(e=>nz(e,s.get(e.toolCallId))??[]).map(e=>n_(e,a,n)),[e.dispatchCalls,s,a,n]),p=e.checks.filter(e=>"failed"===e.state),h=e.checks.filter(e=>"passed"!==e.state),m=u.filter(e=>"failed"===e.run||"aborted"===e.run||"unobserved"===e.run||e.verdict?.verdict!=="accepted"),f=h.length+m.length;if(0===e.files.length&&0===e.checks.length&&0===u.length)return null;let g=[l("summary.files",{count:e.files.length}),l("summary.checks",{count:e.checks.length})];return p.length>0&&g.push(l("summary.checksFailed",{count:p.length})),f>0&&g.push(l("summary.unverified",{count:f})),(0,r.jsxs)("div",{className:"answer-summary",children:[(0,r.jsxs)("button",{type:"button",className:"answer-summary-toggle","aria-expanded":o,"aria-controls":c,title:l(o?"summary.collapse":"summary.expand"),onClick:()=>d(e=>!e),children:[(0,r.jsx)("span",{className:"answer-summary-text","data-unverified":f>0?"":void 0,children:g.join(" \xb7 ")}),(0,r.jsx)("svg",{className:"answer-chevron",width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"6 9 12 15 18 9"})})]}),o&&(0,r.jsxs)("div",{className:"answer-summary-body",id:c,children:[e.files.length>0&&(0,r.jsxs)("section",{children:[(0,r.jsx)("h4",{className:"answer-summary-heading",children:l("summary.heading.files")}),(0,r.jsx)(nT,{files:e.files,onOpenFile:t})]}),e.checks.length>0&&(0,r.jsxs)("section",{children:[(0,r.jsx)("h4",{className:"answer-summary-heading",children:l("summary.heading.checks")}),(0,r.jsx)("ul",{className:"answer-summary-list",children:e.checks.map(e=>(0,r.jsxs)("li",{className:"answer-check","data-state":e.state,children:[(0,r.jsx)("code",{className:"answer-check-command",title:e.command,children:e.command}),(0,r.jsx)("span",{className:"answer-check-result",children:null!==e.exitCode?l("summary.check.exit",{code:e.exitCode}):l("failed"===e.state?"summary.check.error":"summary.check.unobserved")})]},e.toolCallId))})]}),f>0&&(0,r.jsxs)("section",{children:[(0,r.jsx)("h4",{className:"answer-summary-heading",children:l("summary.heading.unverified")}),(0,r.jsxs)("ul",{className:"answer-summary-list",children:[h.map(e=>(0,r.jsx)("li",{children:l("failed"===e.state?"summary.u.checkFailed":"summary.u.checkUnobserved",{command:e.command})},`check-${e.toolCallId}`)),m.map(e=>(0,r.jsxs)("li",{className:"answer-summary-maker",children:[(0,r.jsx)("span",{className:"answer-dispatch-name",title:e.title,children:e.title}),(0,r.jsx)(n8,{maker:e,st:l})]},`maker-${e.member.key}`))]})]})]})]})}let rn=/^att_[0-9a-f]{32}$/,rr=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function ri(e){return"string"==typeof e&&rn.test(e)}function ra(e){return"string"==typeof e&&rr.test(e)}class rs extends Error{constructor(e,t){super(t),this.code=e,this.name="DocumentAttachmentError"}}let rl={markdown:"text/markdown",text:"text/plain",pdf:"application/pdf"},ro={".txt":!0,".csv":!0,".tsv":!0,".json":!0,".log":!0},rd={"text/plain":!0,"text/csv":!0,"text/tab-separated-values":!0,"application/json":!0,"text/json":!0};function rc(e){let t=e.name.toLocaleLowerCase();if(t.endsWith(".md")||t.endsWith(".markdown"))return"markdown";if(t.endsWith(".pdf"))return"pdf";let n=t.lastIndexOf(".");if(n>0&&ro[t.slice(n)])return"text";let r=e.type.toLocaleLowerCase().split(";",1)[0]?.trim();return"text/markdown"===r?"markdown":"application/pdf"===r?"pdf":r&&rd[r]?"text":null}let ru={".mp3":"audio/mpeg",".wav":"audio/wav",".wave":"audio/wav",".m4a":"audio/mp4",".ogg":"audio/ogg",".oga":"audio/ogg",".opus":"audio/ogg",".flac":"audio/flac",".webm":"audio/webm",".aac":"audio/aac",".aif":"audio/aiff",".aiff":"audio/aiff"};function rp(e){let t=e.name.toLocaleLowerCase(),n=t.lastIndexOf("."),r=n>0?ru[t.slice(n)]:void 0;if(r)return r;let i=e.type.toLocaleLowerCase().split(";",1)[0]?.trim();return i?.startsWith("audio/")?i:null}function rh(e,t){try{let n=new TextDecoder(e,{fatal:!0}).decode(t);return n.includes("\0")?null:n}catch{return null}}function rm(e){if(!Array.isArray(e))return[];let t=[],n=0,r=0;for(let i of e){if(i&&"object"==typeof i&&"string"==typeof i.name&&i.name.length>0&&("text/markdown"===i.mimeType||"text/plain"===i.mimeType||"application/pdf"===i.mimeType)&&"number"==typeof i.size&&Number.isSafeInteger(i.size)&&i.size>=0&&i.size<=8388608&&"string"==typeof i.text&&i.text.length<=12e4){if(t.length>=3)break;!(n+i.size>0x1000000)&&(r+i.text.length>24e4||(t.push({name:i.name,mimeType:i.mimeType,size:i.size,text:i.text,...ri(i.attachmentId)?{attachmentId:i.attachmentId}:{}}),n+=i.size,r+=i.text.length))}}return t}async function rf(e){let t,n=rc(e);if(!n)throw new rs("unsupported",`Unsupported document type: ${e.name}`);if(e.size>8388608)throw new rs("file_too_large",`${e.name} exceeds the document size limit`);if("pdf"===n)t=await rC(e);else{try{t=await e.text()}catch(e){throw new rs("read_failed",e instanceof Error?e.message:String(e))}rN(t)}return{name:e.name,mimeType:rl[n],size:e.size,text:t}}function rg(e,t){let n=rm(t);if(0===n.length)return e;let r={userMessageLength:e.length,documents:n.map(({name:e,mimeType:t,size:n,text:r})=>({name:e,mimeType:t,size:n,textLength:r.length}))},i=`${rI}${JSON.stringify(r)}${rT}
@@ -16,7 +16,7 @@ Attached: ${n}`:`Attached: ${n}`}(g)).then(()=>{f(!0),setTimeout(()=>f(!1),1500)
16
16
  ${t}`)),[l,o]=(0,i.useState)(null),[d,c]=(0,i.useState)(()=>new Set);if((0,i.useEffect)(()=>{if(void 0!==a)return;let n=!0;return(function(e,t){let n=`${e}
17
17
  ${t}`,r=eB.get(n);if(void 0!==r)return Promise.resolve(r);let i=eU.get(n);if(i)return i;let a=fetch(eD(e,t),{cache:"no-store"}).then(async e=>{if(!e.ok)return 0;let t=await e.json(),r=Number.isSafeInteger(t.count)&&t.count>=0?t.count:0;return eB.set(n,r),r}).catch(()=>0).finally(()=>eU.delete(n));return eU.set(n,a),a})(e,t).then(e=>{n&&s(e)}),()=>{n=!1}},[a,e,t]),!a)return null;let u=Array.from({length:a},(e,t)=>t).filter(e=>!d.has(e));return 0===u.length?null:(0,r.jsxs)("div",{className:"tool-image-strip","data-tool-call-id":t,children:[u.map(i=>(0,r.jsx)("button",{type:"button",className:"tool-image-thumb","aria-label":n("i18n.zoomIn"),onClick:()=>o(i),children:(0,r.jsx)("img",{src:eD(e,t,i),alt:"",loading:"lazy",draggable:!1,onError:()=>c(e=>new Set(e).add(i))})},i)),null!==l&&(0,r.jsx)(rV,{src:eD(e,t,l),onClose:()=>o(null)})]})}function rV({src:e,onClose:t}){let{t:n}=(0,R.s)(),a=(0,i.useRef)(null);return(0,i.useEffect)(()=>{let e=a.current;if(!e)return;let t=document.body.style.overflow;return document.body.style.overflow="hidden",e.showModal(),()=>{document.body.style.overflow=t,e.open&&e.close()}},[]),(0,F.createPortal)((0,r.jsxs)("dialog",{ref:a,className:"tool-image-dialog",onCancel:e=>{e.preventDefault(),t()},onClick:e=>{e.target===e.currentTarget&&t()},children:[(0,r.jsx)("img",{className:"tool-image-full",src:e,alt:"",draggable:!1}),(0,r.jsx)("button",{type:"button",className:"tool-image-close",onClick:t,children:n("i18n.close")})]}),document.body)}function rJ({block:e,isStreaming:t,cwd:n,onOpenFile:i}){return(0,r.jsx)(rP,{isStreaming:t,cwd:n,onOpenFile:i,children:e.text})}function rG({block:e,duration:t,sessionId:n,entryId:a,blockIndex:s}){let{t:l}=(0,R.s)(),[o,d]=(0,i.useState)(null),[c,u]=(0,i.useState)(!0===e.deferred),[p,h]=(0,i.useState)(null);(0,i.useEffect)(()=>{if(!e.deferred){d(null),u(!1),h(null);return}let t=!1;return n&&a?(u(!0),h(null),(function(e,t,n){let r=`${e}:${t}:${n}`,i=rz.get(r);if(i)return rz.delete(r),rz.set(r,i),i;let a=fetch(`/api/sessions/${encodeURIComponent(e)}/entries/${encodeURIComponent(t)}/thinking?blockIndex=${n}`).then(async e=>{if(!e.ok)throw Error(`HTTP ${e.status}`);let t=await e.json();if("string"!=typeof t.thinking)throw Error("Invalid thinking response");return t.thinking}).catch(e=>{throw rz.delete(r),e});if(rz.set(r,a),rz.size>100){let e=rz.keys().next().value;e&&rz.delete(e)}return a})(n,a,s).then(e=>{t||d(e)}).catch(e=>{t||h(e instanceof Error?e.message:String(e))}).finally(()=>{t||u(!1)}),()=>{t=!0}):(u(!1),h(l("i18n.thinkingUnavailable")),()=>{t=!0})},[e.deferred,e.thinking,s,a,n,l]);let m=e.deferred?o:e.thinking,f="string"==typeof m&&m.trim().length>0;return(0,r.jsxs)("div",{className:"markdown-thinking","aria-label":l("i18n.thinking"),children:[(0,r.jsx)("div",{className:"markdown-thinking-content",children:c?(0,r.jsx)("span",{className:"markdown-thinking-status",children:l("i18n.loadingThinking")}):p?(0,r.jsx)("span",{className:"markdown-thinking-error",children:p}):f?(0,r.jsx)(tG,{className:"markdown-thinking-body",children:m}):(0,r.jsx)("span",{className:"markdown-thinking-status",children:l("chat.thinking")})}),void 0!==t&&f&&(0,r.jsxs)("span",{className:"markdown-thinking-duration",children:[t,"s"]})]})}function rY({block:e,result:t,duration:n,runStartedAt:a}){let s,{t:l}=(0,R.s)(),o=(0,i.useId)(),[d]=(0,i.useState)(()=>Date.now()),[c,u]=(0,i.useState)(null),p=e.toolName.toLowerCase(),h=JSON.stringify(e.input,null,2),m="todo"===p||p.endsWith(".todo")||p.endsWith("_todo"),f="bash"===p||p.startsWith("bash ")||p.endsWith(".bash")||p.endsWith("_bash"),g=t&&!t.isError?function(e){var t;let n=e.details;if(!("object"==typeof(t=n)&&null!==t&&!Array.isArray(t)))return null;let r="string"==typeof n.patch?n.patch:null;if(r)return{text:r};let i="string"==typeof n.diff?n.diff:null;return i?{text:i}:null}(t):null,x=m?"unknown"===(s=e3(e,t)).kind||0===s.phases.length?null:s.phases:null,v=g?g.text.split(/\r?\n/).reduce((e,t)=>(t.startsWith("+")&&!t.startsWith("+++")&&(e.added+=1),t.startsWith("-")&&!t.startsWith("---")&&(e.removed+=1),e),{added:0,removed:0}):null,b=t?t.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n"):null,y=null!==b&&("(no output)"===b.trim()||""===b.trim()),w=t?tX(t):null,k=t?t.isError||null!==w&&0!==w?"failed":"done":"running",j="failed"===k,S=c??j;if(m&&x)return(0,r.jsx)(r2,{phases:x});let C=f&&"string"==typeof e.input.command?e.input.command:"",N=!!(x||g),I=f?C.split(/\r?\n/,1)[0]??"":function(e,t){if(t){let e=t.flatMap(e=>e.tasks),n=e.filter(e=>"completed"===e.status||"abandoned"===e.status).length;return`${n}/${e.length} tasks`}return function(e){var t;let n=e.input;if(!n||"object"!=typeof n)return"";let r=Object.keys(n);if(0===r.length)return"";let i=e.toolName.toLowerCase();if(t=i,["grep","read","write","glob"].some(e=>t===e||t.endsWith(`.${e}`)||t.endsWith(`_${e}`))&&"string"==typeof n.i){let e=n.i.trim();if(e)return e.slice(0,120)}if(("eval"===i||i.endsWith(".eval")||i.endsWith("_eval"))&&"string"==typeof n.title){let e=n.title.trim();if(e)return e.slice(0,120)}if("command"in n)return String(n.command).slice(0,120);if("path"in n)return String(n.path).slice(-120);if("file_path"in n)return String(n.file_path).slice(-120);if("pattern"in n)return String(n.pattern).slice(0,120);if("query"in n)return String(n.query).slice(0,120);let a=r.map(e=>n[e]).find(e=>"string"==typeof e||"number"==typeof e||"boolean"==typeof e);if(void 0!==a)return String(a).slice(0,120);try{return JSON.stringify(n).slice(0,120)}catch{return r.join(", ").slice(0,120)}}(e)}(e,x),T=!f&&/^\S+$/.test(I)&&/[\\/]/.test(I),M=v?l("toolRun.diffStats",{added:v.added,removed:v.removed}):"";return(0,r.jsxs)("div",{className:`tool-call-card ${j?"is-error":"running"===k?"is-running":"is-done"}${f?" is-shell":""}`,"aria-busy":"running"===k||void 0,style:{overflow:"hidden",fontSize:12},children:[(0,r.jsxs)("button",{type:"button",className:"tool-call-header",onClick:()=>u(!S),"aria-expanded":S,"aria-controls":S?o:void 0,style:{display:"flex",alignItems:"center",gap:7,width:"100%",padding:"6px 10px",background:"none",border:"none",cursor:"pointer",fontSize:12,textAlign:"left",minWidth:0},children:[(0,r.jsx)(r0,{toolName:e.toolName}),(0,r.jsx)("span",{className:"tool-call-name",children:f?"bash":e.toolName}),f&&p.includes("(local)")&&(0,r.jsx)("span",{className:"shell-local-label",children:"local"}),(0,r.jsx)("span",{className:`tool-call-target${T?" is-path":""}`,title:f?C:I,children:T?(0,r.jsx)("bdi",{dir:"ltr",children:I}):I}),v&&(0,r.jsxs)("span",{className:"tool-call-diffstats",title:M,"aria-label":M,children:[(0,r.jsxs)("span",{style:{color:"var(--success)"},children:["+",v.added]}),(0,r.jsxs)("span",{style:{color:"var(--danger)"},children:["−",v.removed]})]}),(0,r.jsx)(rZ,{state:k,duration:n,exitCode:w,startedAt:a??d}),(0,r.jsx)("svg",{className:"tool-call-chevron",width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--text-dim)",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{transform:S?"rotate(180deg)":"none",transition:"transform 0.15s"},children:(0,r.jsx)("polyline",{points:"2 3.5 5 6.5 8 3.5"})})]}),S&&(0,r.jsx)("div",{id:o,className:"tool-call-body",children:f?(0,r.jsx)(r4,{command:C,output:b??"",pending:!t,isError:j}):(0,r.jsxs)(r.Fragment,{children:[g&&(0,r.jsx)("div",{style:{maxHeight:560,overflowY:"auto",overflowX:"hidden"},children:(0,r.jsx)(r5,{diff:g})}),t&&j&&(0,r.jsx)(r9,{text:b??"",isEmpty:y,isError:!0}),!N&&(0,r.jsx)("pre",{className:"tool-call-input",style:{margin:0,padding:"8px 10px",color:"var(--text-muted)",fontSize:12,lineHeight:1.5,overflow:"auto",maxHeight:400,whiteSpace:"pre-wrap",wordBreak:"break-all"},children:h}),t&&!N&&!j&&(0,r.jsx)(r9,{text:b??"",isEmpty:y,isError:!1})]})})]})}function rZ({state:e,duration:t,exitCode:n,startedAt:i}){let{t:a}=(0,R.s)();return"running"===e?(0,r.jsx)(rX,{startedAt:i}):(0,r.jsxs)(r.Fragment,{children:[void 0!==t&&(0,r.jsxs)("span",{className:"tool-run-duration",children:[t,"s"]}),"failed"===e&&(0,r.jsxs)("span",{className:"tool-run-failed",children:[(0,r.jsx)(tZ.E,{tone:"critical",variant:"weak",size:"medium",children:a("toolRun.failed")}),null!==n&&(0,r.jsx)("span",{className:"tool-run-exit",children:a("toolRun.exitCode",{code:n})})]})]})}function rX({startedAt:e}){let{t}=(0,R.s)(),n=tY(500)-e;return n<400?null:(0,r.jsxs)("span",{className:"tool-run-running",children:[t("toolRun.running"),(0,r.jsxs)("span",{className:"tool-run-duration",children:[Math.floor(n/1e3),"s"]})]})}function rQ(e,t){let n=e.trim().toLowerCase();return n===t||n.endsWith(`.${t}`)||n.endsWith(`_${t}`)||n.split(/[.\s:_-]+/).includes(t)}function r0({toolName:e}){let t,n=(t=e.trim().toLowerCase()).includes("str_replace")||t.includes("replace_editor")||rQ(t,"edit")?"edit":rQ(t,"read")||rQ(t,"cat")?"read":rQ(t,"write")||rQ(t,"save")?"write":rQ(t,"glob")||rQ(t,"find")?"glob":rQ(t,"grep")||rQ(t,"search")?"grep":rQ(t,"bash")||rQ(t,"shell")||rQ(t,"exec")?"bash":rQ(t,"todo")?"todo":rQ(t,"eval")?"eval":rQ(t,"task")||rQ(t,"agent")?"task":rQ(t,"browser")||rQ(t,"web_search")||rQ(t,"fetch")?"browser":rQ(t,"image")||rQ(t,"inspect_image")?"image":"generic";return(0,r.jsx)("span",{"aria-hidden":"true","data-tool-icon":n,style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:14,height:14,flexShrink:0,color:"var(--text-muted)"},children:(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",stroke:"currentColor",strokeWidth:"1.15",strokeLinecap:"round",strokeLinejoin:"round",children:(0,r.jsx)(r1,{kind:n})})})}function r1({kind:e}){switch(e){case"read":return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("path",{d:"M2.75 1.75h5.5l3 3v7.5h-8.5V1.75Z"}),(0,r.jsx)("path",{d:"M8.25 1.75v3h3"}),(0,r.jsx)("path",{d:"M4.2 9.1c1.1-1.4 3.6-1.4 4.7 0-1.1 1.4-3.6 1.4-4.7 0Z"}),(0,r.jsx)("circle",{cx:"6.55",cy:"9.1",r:"0.7",fill:"currentColor",stroke:"none"})]});case"write":return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("path",{d:"M2.75 1.75h5.5l3 3v7.5h-8.5V1.75Z"}),(0,r.jsx)("path",{d:"M8.25 1.75v3h3"}),(0,r.jsx)("path",{d:"M6.55 6.25v4.15m-1.7-1.55 1.7 1.7 1.7-1.7"})]});case"glob":return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("path",{d:"M1.75 4.5A1.25 1.25 0 0 1 3 3.25h2.25l1.35 1.35h4.4A1.25 1.25 0 0 1 12.25 5.85v5.1A1.25 1.25 0 0 1 11 12.2H3a1.25 1.25 0 0 1-1.25-1.25V4.5Z"}),(0,r.jsx)("path",{d:"M9 7.1v3.8M7.1 9h3.8M7.65 7.65l2.7 2.7m0-2.7-2.7 2.7"})]});case"grep":return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("circle",{cx:"5.9",cy:"5.9",r:"3.25"}),(0,r.jsx)("path",{d:"m8.35 8.35 3.25 3.25"}),(0,r.jsx)("path",{d:"M4.6 5.2h2.5M4.6 6.8h1.7"})]});case"edit":return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("path",{d:"M2.75 1.75h5.5l3 3v7.5h-8.5V1.75Z"}),(0,r.jsx)("path",{d:"M8.25 1.75v3h3"}),(0,r.jsx)("path",{d:"m4.45 10.55 4.75-4.75 1.45 1.45-4.75 4.75-1.95.5.5-1.95Z"}),(0,r.jsx)("path",{d:"m8.45 6.55 1.45 1.45"})]});case"bash":return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("rect",{x:"1.5",y:"2.1",width:"11",height:"9.8",rx:"1.3"}),(0,r.jsx)("path",{d:"m4 5.2 1.8 1.8L4 8.8M7.2 8.8h2.3"})]});case"todo":return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("path",{d:"M5.5 3.25h7M5.5 7h7M5.5 10.75h7"}),(0,r.jsx)("path",{d:"m1.5 3.1 1 1 1.7-1.9M1.5 6.85l1 1 1.7-1.9M1.5 10.6l1 1 1.7-1.9"})]});case"eval":return(0,r.jsx)(r.Fragment,{children:(0,r.jsx)("path",{d:"m5 2.5-3 4.5 3 4.5M9 2.5l3 4.5-3 4.5M7.8 2 6.2 12"})});case"task":return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("circle",{cx:"3.1",cy:"3.2",r:"1.25"}),(0,r.jsx)("circle",{cx:"10.9",cy:"3.2",r:"1.25"}),(0,r.jsx)("circle",{cx:"10.9",cy:"10.8",r:"1.25"}),(0,r.jsx)("path",{d:"M4.35 3.2h2.1a2.9 2.9 0 0 1 2.9 2.9v3.45"}),(0,r.jsx)("path",{d:"M9.35 3.2h-1.1"})]});case"browser":return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("circle",{cx:"7",cy:"7",r:"5.2"}),(0,r.jsx)("path",{d:"M1.9 7h10.2M7 1.8c1.45 1.4 2.2 3.15 2.2 5.2S8.45 10.8 7 12.2C5.55 10.8 4.8 9.05 4.8 7S5.55 3.2 7 1.8Z"})]});case"image":return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("rect",{x:"1.75",y:"2.25",width:"10.5",height:"9.5",rx:"1.15"}),(0,r.jsx)("circle",{cx:"4.8",cy:"5.1",r:"1"}),(0,r.jsx)("path",{d:"m2.6 10 2.6-2.7 1.8 1.8 1.45-1.45 2.95 2.95"})]});case"generic":return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("rect",{x:"1.75",y:"2",width:"10.5",height:"10",rx:"1.3"}),(0,r.jsx)("path",{d:"M4.35 5h5.3M4.35 7.35h3.8M4.35 9.7h4.6"})]})}}function r2({phases:e}){let t=e.reduce((e,t)=>e+t.tasks.length,0),n=e.reduce((e,t)=>e+t.tasks.filter(e=>"completed"===e.status).length,0);return(0,r.jsxs)("div",{className:"todo-checklist-preview",role:"list","aria-label":`Todo ${t} tasks`,children:[(0,r.jsxs)("div",{className:"todo-checklist-header",children:[(0,r.jsxs)("svg",{className:"todo-checklist-icon",width:"14",height:"14",viewBox:"0 0 14 14",fill:"none","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M5.5 3.25h7M5.5 7h7M5.5 10.75h7",stroke:"currentColor",strokeWidth:"1.3",strokeLinecap:"round"}),(0,r.jsx)("path",{d:"m1.5 3.1 1 1 1.7-1.9M1.5 6.85l1 1 1.7-1.9M1.5 10.6l1 1 1.7-1.9",stroke:"currentColor",strokeWidth:"1.3",strokeLinecap:"round",strokeLinejoin:"round"})]}),(0,r.jsx)("span",{className:"todo-checklist-title",children:"Todo"}),(0,r.jsxs)("span",{className:"todo-checklist-count",children:[t," ",1===t?"task":"tasks"]}),n>0&&n<t&&(0,r.jsxs)("span",{className:"todo-checklist-progress",children:[n,"/",t]})]}),(0,r.jsx)("div",{className:"todo-checklist-body",children:e.map((t,n)=>(0,r.jsxs)("div",{className:"todo-checklist-phase",children:[e.length>1&&(0,r.jsx)("div",{className:"todo-checklist-phase-name",children:t.name}),t.tasks.map((e,t)=>(0,r.jsx)(nw,{task:e},`${e.content}-${t}`))]},`${t.name}-${n}`))})]})}function r4({command:e,output:t,pending:n,isError:i}){let{isDark:a}=tB(),{t:s}=(0,R.s)(),l=eI(t.split(/\r?\n/)),o=1===l.length&&""===l[0]?[]:l;return(0,r.jsxs)("div",{className:`shell-output-preview${i?" is-error":""}`,children:[(0,r.jsxs)("div",{className:"shell-command-line",children:[(0,r.jsx)("span",{className:"shell-command-prompt","aria-hidden":"true",children:"$"}),(0,r.jsx)(te.A,{className:"shell-command-code",language:"bash",style:a?tt.xJ:tt.vs,PreTag:"span",CodeTag:"span",wrapLongLines:!0,customStyle:{flex:1,minWidth:0,margin:0,padding:0,border:"none",overflow:"visible",background:"transparent",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:13,lineHeight:1.55,whiteSpace:"pre-wrap",overflowWrap:"anywhere"},codeTagProps:{style:{fontFamily:"var(--font-mono)"}},children:e||" "})]}),(0,r.jsxs)("div",{className:"shell-output-panel",children:[(0,r.jsx)("div",{className:"shell-output-divider",children:(0,r.jsx)("span",{className:"shell-output-label",children:"Output"})}),(0,r.jsxs)("div",{className:"shell-output-body",children:[0===o.length&&!n&&(0,r.jsx)("span",{className:"shell-output-empty",children:s("i18n.noOutput")}),o.map((e,t)=>{let n=ej(e).trimStart(),a=i||/^(?:error|fatal|failed|failure|✖|x\b)/i.test(n)?"is-error":/^(?:warning|warn|!)/i.test(n)?"is-warning":/^(?:success|passed|ok\b|✓|\+)/i.test(n)?"is-success":"";return(0,r.jsxs)("div",{className:`shell-output-line ${a}`.trim(),children:[eT(e).map((e,t)=>Object.keys(e.style).length>0?(0,r.jsx)("span",{style:e.style,children:e.text},t):(0,r.jsx)("span",{children:e.text},t)),""===e?"\xa0":null]},t)})]})]})]})}function r5({diff:e}){return(0,r.jsx)("div",{style:{borderTop:"1px solid var(--success-line)",background:"var(--bg)"},children:(0,r.jsx)(r6,{text:e.text})})}function r6({text:e}){let{t}=(0,R.s)(),n=(0,i.useMemo)(()=>nb(e),[e]);if(!n)return(0,r.jsx)(r7,{text:e});let a=n.length>1;return(0,r.jsx)("div",{style:{background:"var(--bg)"},children:n.map((e,n)=>(0,r.jsxs)("div",{style:{minWidth:0,borderTop:0===n?"none":"1px solid var(--border)",fontFamily:"var(--font-mono)",fontSize:12,lineHeight:1.55},children:[a&&(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"minmax(0, 1fr) minmax(0, 1fr)",position:"sticky",top:0,zIndex:1,background:"var(--bg-panel)",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)(r8,{title:e.oldPath||t("i18n.before"),side:"left"}),(0,r.jsx)(r8,{title:e.newPath||t("i18n.after"),side:"right"})]}),(0,r.jsx)("div",{style:{display:"grid",gridTemplateColumns:"minmax(0, 1fr) minmax(0, 1fr)"},children:e.rows.map((e,t)=>"hunk"===e.type?null:(0,r.jsxs)("div",{style:{display:"contents"},children:[(0,r.jsx)(r3,{cell:e.left,side:"left"}),(0,r.jsx)(r3,{cell:e.right,side:"right"})]},t))})]},n))})}function r8({title:e,side:t}){return(0,r.jsx)("div",{title:e,style:{padding:"5px 10px",color:"var(--text-dim)",borderRight:"left"===t?"1px solid var(--border)":"none",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e})}function r3({cell:e,side:t}){let n="added"===e.type?"var(--success-soft)":"removed"===e.type?"var(--danger-soft)":"empty"===e.type?"var(--bg-subtle)":"transparent",i="added"===e.type?"+":"removed"===e.type?"-":" ",a="added"===e.type?"var(--success)":"removed"===e.type?"var(--danger)":"var(--text-dim)";return(0,r.jsxs)("div",{style:{display:"flex",minWidth:0,background:n,borderRight:"left"===t?"1px solid var(--border)":"none"},children:[(0,r.jsx)("span",{style:{width:42,padding:"0 6px",textAlign:"right",color:"var(--text-dim)",userSelect:"none",background:"var(--bg-panel)",borderRight:"1px solid var(--border)",flexShrink:0},children:e.lineNo??""}),(0,r.jsx)("span",{style:{width:18,padding:"0 5px",color:a,userSelect:"none",fontWeight:"context"===e.type||"empty"===e.type?400:700,flexShrink:0},children:i}),(0,r.jsx)("span",{style:{flex:1,minWidth:0,padding:"0 10px 0 0",color:"empty"===e.type?"var(--text-dim)":"var(--text)",whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:e.text||"\xa0"})]})}function r7({text:e}){let t=e.split(/\r?\n/);return(0,r.jsx)("div",{style:{fontFamily:"var(--font-mono)",fontSize:12,lineHeight:1.55,minWidth:0},children:t.map((e,t)=>{let n=e.startsWith("@@")?"hunk":e.startsWith("+")&&!e.startsWith("+++")?"added":e.startsWith("-")&&!e.startsWith("---")?"removed":"context";return(0,r.jsxs)("div",{style:{display:"flex",background:"added"===n?"var(--success-soft)":"removed"===n?"var(--danger-soft)":"hunk"===n?"var(--accent-soft)":"transparent",borderLeft:"added"===n?"3px solid var(--success)":"removed"===n?"3px solid var(--danger)":"hunk"===n?"3px solid var(--accent)":"3px solid transparent"},children:[(0,r.jsx)("span",{style:{width:48,padding:"0 8px",color:"var(--text-dim)",background:"var(--bg-panel)",borderRight:"1px solid var(--border)",textAlign:"right",userSelect:"none",flexShrink:0},children:t+1}),(0,r.jsx)("span",{style:{padding:"0 10px",whiteSpace:"pre-wrap",overflowWrap:"anywhere",color:"added"===n?"var(--success)":"removed"===n?"var(--danger)":"hunk"===n?"var(--accent)":"var(--text)"},children:e||"\xa0"})]},t)})})}function r9({text:e,isEmpty:t,isError:n}){let{t:i}=(0,R.s)();return(0,r.jsx)("div",{style:{borderTop:`1px solid ${n?"var(--danger-line)":"var(--success-line)"}`,background:n?"var(--danger-soft)":"var(--bg-subtle)"},children:(0,r.jsx)("pre",{style:{margin:0,padding:"8px 10px",color:n?"var(--danger)":t?"var(--text-dim)":"var(--text-muted)",fontSize:12,lineHeight:1.5,overflow:"auto",maxHeight:400,background:"var(--bg)",whiteSpace:"pre-wrap",wordBreak:"break-all",fontStyle:t?"italic":"normal",opacity:t?.6:1},children:t?i("i18n.noOutput"):e})})}function ie({message:e}){let{t}=(0,R.s)(),n=ia(e.content),a=(0,i.useMemo)(()=>{let e,t,r,i,a;return e=[],t=[],r=n.match(t0),i=r?.[1]??"",a=r?.index===void 0?n:n.slice(0,r.index),i.replace(tQ,(n,r,i)=>{let a=i.split(/\r?\n/).map(e=>e.trim()).filter(Boolean);return"read-files"===r?e.push(...a):t.push(...a),""}),{body:a.trim(),readFiles:e,modifiedFiles:t}},[n]),s=rD(e.timestamp),l=e.details&&"object"==typeof e.details&&"tokensBefore"in e.details&&"number"==typeof e.details.tokensBefore&&e.details.tokensBefore>0?e.details.tokensBefore:null;return(0,r.jsx)("div",{style:{marginBottom:16},children:(0,r.jsxs)("div",{style:{border:"1px solid var(--border)",borderRadius:8,overflow:"hidden",background:"var(--bg)"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"7px 10px",borderBottom:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)"},children:[(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:11,fontWeight:650},children:"compaction"}),null!==l&&(0,r.jsx)("span",{style:{fontSize:11},children:t("chat.compactedFrom",{tokens:t1(l)})}),s&&(0,r.jsx)("span",{style:{marginLeft:"auto",color:"var(--text-dim)",fontSize:10},children:s})]}),(0,r.jsxs)("div",{style:{padding:"11px 13px 12px"},children:[(0,r.jsx)("div",{style:{color:"var(--text)",fontSize:15,fontWeight:700,lineHeight:1.35},children:t("i18n.conversationCompacted")}),(0,r.jsx)("div",{style:{marginTop:3,marginBottom:10,color:"var(--text)",fontSize:14,lineHeight:1.5},children:t("i18n.compactionDescription")}),a.body?(0,r.jsx)(tG,{className:"markdown-compaction-message",children:a.body}):(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:12},children:t("i18n.noSummary")}),(0,r.jsx)(it,{readFiles:a.readFiles,modifiedFiles:a.modifiedFiles})]})]})})}function it({readFiles:e,modifiedFiles:t}){let{t:n}=(0,R.s)();if(0===e.length+t.length)return null;let i=[];return e.length>0&&i.push(`${e.length} read`),t.length>0&&i.push(`${t.length} modified`),(0,r.jsxs)("details",{className:"compaction-file-details",children:[(0,r.jsx)("summary",{children:n("i18n.fileContext",{details:i.join(", ")})}),t.length>0&&(0,r.jsx)(ir,{title:n("i18n.modifiedFiles"),files:t}),e.length>0&&(0,r.jsx)(ir,{title:n("i18n.readFiles"),files:e})]})}function ir({title:e,files:t}){return(0,r.jsxs)("div",{className:"compaction-file-section",children:[(0,r.jsx)("div",{className:"compaction-file-title",children:e}),(0,r.jsx)("ul",{className:"compaction-file-list",children:t.map(e=>(0,r.jsx)("li",{children:e},e))})]})}function ii({message:e,cwd:t,onOpenFile:n}){var a;let s,{t:l}=(0,R.s)(),o=!1===e.display,[d,c]=(0,i.useState)(!o),[u,p]=(0,i.useState)(!1),[h,m]=(0,i.useState)(!1),f=ia(e.content),g="string"==typeof(a=e.content)?[]:a.filter(e=>"image"===e.type),x=void 0!==e.details,v=x?function(e){try{return JSON.stringify(e,null,2)}catch{return String(e)}}(e.details):"",b=e.customType||"extension",y=rD(e.timestamp);return(0,r.jsx)("div",{style:{marginBottom:16},children:(0,r.jsxs)("div",{style:{border:"1px solid var(--border)",borderRadius:8,overflow:"hidden",background:o?"var(--bg-subtle)":"var(--bg)",opacity:o&&!d?.82:1},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"7px 10px",borderBottom:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)",fontSize:12},children:[(0,r.jsx)("span",{style:{color:"var(--text-muted)",fontFamily:"var(--font-mono)",fontSize:11,fontWeight:650},children:b}),o&&(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:11},children:l("i18n.hiddenExtensionMessage")}),y&&(0,r.jsx)("span",{style:{marginLeft:"auto",color:"var(--text-dim)",fontSize:10},children:y})]}),d?(0,r.jsxs)("div",{style:{padding:"6px 9px"},children:[g.length>0&&(0,r.jsx)("div",{style:{display:"flex",gap:6,flexWrap:"wrap",marginBottom:8*!!f},children:g.map((e,t)=>{let n=is(e);return n?(0,r.jsx)("img",{src:n,alt:"",style:{maxWidth:240,maxHeight:240,borderRadius:"var(--radius-control)",objectFit:"contain",display:"block",border:"1px solid var(--border)"}},t):null})}),f?(0,r.jsx)(tG,{className:"markdown-custom-message",cwd:t,onOpenFile:n,children:f}):(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:12},children:l("i18n.noMessage")})]}):(0,r.jsx)("button",{onClick:()=>c(!0),style:{display:"block",width:"100%",padding:"8px 10px",border:"none",background:"transparent",color:"var(--text-dim)",cursor:"pointer",fontSize:12,textAlign:"left"},children:f?(s=f.replace(/\s+/g," ").trim())?s.length>140?`${s.slice(0,140)}...`:s:"Show extension message":l("i18n.showExtensionMessage")}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"4px 9px",borderTop:"1px solid var(--border)",background:"var(--bg-subtle)"},children:[f||v?(0,r.jsx)("button",{onClick:()=>{tU(f||v).then(()=>{m(!0),setTimeout(()=>m(!1),1500)})},style:{padding:"3px 7px",border:"none",background:"none",color:h?"var(--accent)":"var(--text-dim)",cursor:"pointer",fontSize:11},children:l(h?"i18n.copied":"i18n.copy")}):null,(x||o)&&(0,r.jsx)("button",{onClick:()=>{o?c(e=>!e):p(e=>!e)},style:{marginLeft:"auto",padding:"3px 7px",border:"none",background:"none",color:"var(--text-dim)",cursor:"pointer",fontSize:11},children:l(o?d?"i18n.collapse":"i18n.expand":u?"i18n.hideDetails":"i18n.showDetails")})]}),x&&(o&&d||!o&&u)&&(0,r.jsx)("pre",{style:{margin:0,padding:"9px 10px",borderTop:"1px solid var(--border)",background:"var(--bg)",color:"var(--text-muted)",fontSize:12,lineHeight:1.5,whiteSpace:"pre-wrap",wordBreak:"break-word",maxHeight:360,overflow:"auto",fontFamily:"var(--font-mono)"},children:v})]})})}function ia(e){return"string"==typeof e?e:e.filter(e=>"text"===e.type).map(e=>e.text).join("\n")}function is(e){return e.source?"base64"===e.source.type?`data:${e.source.media_type};base64,${e.source.data}`:e.source.url??"":e.data?`data:${e.mimeType};base64,${e.data}`:""}function il({message:e,sessionId:t}){let[n,a]=(0,i.useState)(null),[s,l]=(0,i.useState)(!1),[o,d]=(0,i.useState)(null),c=!e.output&&void 0===e.exitCode&&!e.cancelled,u=e.cancelled||void 0!==e.exitCode&&0!==e.exitCode,p=t&&e.fullOutputPath?`/api/agent/${encodeURIComponent(t)}/bash-output?path=${encodeURIComponent(e.fullOutputPath)}`:null,h=e.truncated&&p&&null===n,m=n??e.output;async function f(){if(p){l(!0),d(null);try{let e=await fetch(p),t=await e.json();t.success?a(t.data?.output??""):d(t.error??"failed")}catch(e){d(String(e))}finally{l(!1)}}}let g=e.excludeFromContext?"bash (local)":"bash",x={type:"toolCall",toolCallId:`bash-${e.timestamp??""}`,toolName:g,input:{command:e.command}},v=c?void 0:{role:"toolResult",toolCallId:x.toolCallId,toolName:g,content:m?[{type:"text",text:m}]:[],isError:u,details:void 0!==e.exitCode?{exitCode:e.exitCode}:void 0,timestamp:e.timestamp};return(0,r.jsxs)("div",{style:{margin:"6px 0"},children:[(0,r.jsx)(rY,{block:x,result:v,runStartedAt:e.timestamp}),e.truncated&&p&&(0,r.jsxs)("div",{style:{padding:"4px 10px",fontSize:11,marginTop:-1},children:[h&&(0,r.jsx)("button",{onClick:f,disabled:s,style:{background:"none",border:"none",color:"var(--accent)",cursor:s?"default":"pointer",fontSize:11,padding:0,textDecoration:"underline"},children:s?"loading…":"view full output"}),(0,r.jsx)("a",{href:`${p}&download=1`,style:{marginLeft:10*!!h,color:"var(--accent)",fontSize:11,textDecoration:"underline"},children:"download full output"}),o&&(0,r.jsxs)("span",{style:{marginLeft:6,color:"var(--text-dim)",fontSize:11},children:["(",o,")"]})]})]})}function io({summary:e,onJump:t,onOpenPanel:n}){let{st:i}=ng();if(!e)return null;let{target:a}=e,s=a.position;if(null===s&&!n)return null;let l=i(null!==s?"dock.jump":"dock.openPanel",{title:a.maker.title});return(0,r.jsxs)("button",{type:"button",className:"run-status-line answer-dock-line","data-tone":"accent",title:l,onClick:()=>{null!==s?t(s,a.maker.member.key):n?.()},children:[(0,r.jsx)("span",{className:"run-status-label",children:i("dock.label")}),(0,r.jsxs)("span",{className:"answer-dock-counts",children:[e.running>0&&(0,r.jsx)("span",{className:"answer-dock-count","data-phase":"running",children:i("dock.running",{count:e.running})}),e.awaiting>0&&(0,r.jsx)("span",{className:"answer-dock-count","data-phase":"awaiting",children:i("dock.awaiting",{count:e.awaiting})})]}),(0,r.jsx)("span",{className:"answer-dock-title",children:a.maker.title}),(0,r.jsx)("svg",{className:"answer-dock-go",width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"18 15 12 9 6 15"})})]})}n(21340);let id="cuelo-chat-search",ic="cuelo-chat-search-active";function iu(e,t){if("u">typeof CSS&&"highlights"in CSS){if(0===t.length||"u"<typeof Highlight)return void CSS.highlights.delete(e);CSS.highlights.set(e,new Highlight(...t))}}function ip({open:e,onClose:t,containerRef:n,index:a,renderedStart:s,renderedEnd:l,contentKey:o,onReveal:d,onProgrammaticScroll:c,focusRequest:u,t:p}){let h=(0,i.useRef)(null),[m,f]=(0,i.useState)(""),[g,x]=(0,i.useState)(null),[v,b]=(0,i.useState)({index:-1,total:0}),y=(0,i.useDeferredValue)(m),w=e?y.trim().toLowerCase():"",k=(0,i.useRef)(g);k.current=g;let j=(0,i.useRef)([]),S=(0,i.useRef)({key:null,needle:"",rendered:!1});(0,i.useEffect)(()=>{if(!e)return;let t=requestAnimationFrame(()=>h.current?.select());return()=>cancelAnimationFrame(t)},[e,u]),(0,i.useEffect)(()=>()=>{iu(id,[]),iu(ic,[])},[]),(0,i.useLayoutEffect)(()=>{let t=n.current;if(!e||!w||!t){iu(id,[]),iu(ic,[]),j.current=[],S.current={key:null,needle:"",rendered:!1},b(e=>0===e.total&&-1===e.index?e:{index:-1,total:0});return}let r=requestAnimationFrame(()=>{let e=function(e,t){let n=new Map,r=document.createTreeWalker(e,NodeFilter.SHOW_TEXT,{acceptNode:e=>(e.textContent??"").toLowerCase().includes(t)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP});for(let e=r.nextNode();e;e=r.nextNode()){let r=e.parentElement?.closest("[data-chat-item]"),i=r?Number(r.dataset.chatItem):NaN;if(!Number.isInteger(i))continue;let a=(e.textContent??"").toLowerCase(),s=n.get(i);s||(s=[],n.set(i,s));for(let n=a.indexOf(t);-1!==n;n=a.indexOf(t,n+t.length)){let r=document.createRange();r.setStart(e,n),r.setEnd(e,n+t.length),s.push(r)}}return n}(t,w),n=new Map;for(let[t,r]of e)n.set(t,r.length);let r=function(e,t,n,r,i){let a=[];if(!t)return a;for(let s=0;s<e.length;s++){let l=s>=r&&s<i?n.get(s)??0:function(e,t){if(!t)return 0;let n=0;for(let r=e.indexOf(t);-1!==r;r=e.indexOf(t,r+t.length))n+=1;return n}(e[s],t);for(let e=0;e<l;e++)a.push({item:s,k:e})}return a}(a,w,n,s,l);j.current=r;let i=e1(r,k.current);b(e=>e.index===i&&e.total===r.length?e:{index:i,total:r.length});let o=[];for(let t of e.values())for(let e of t)o.push(e);if(iu(id,o),i<0){iu(ic,[]),S.current={key:null,needle:w,rendered:!1};return}let u=r[i],p=k.current;p&&p.item===u.item&&p.k===u.k||x(u);let h=u.item>=s&&u.item<l,m=S.current,f=m.needle!==w||m.key?.item!==u.item||m.key?.k!==u.k||!m.rendered&&h;if(S.current={key:u,needle:w,rendered:h},!h){iu(ic,[]),f&&d(u.item);return}let g=e.get(u.item)?.[u.k];if(iu(ic,g?[g]:[]),f)if(c(),g){let e,n;e=g.getBoundingClientRect(),n=t.getBoundingClientRect(),e.height<=0||e.top>=n.top+48&&e.bottom<=n.bottom-48||(t.scrollTop+=e.top-n.top-(t.clientHeight-e.height)/2)}else t.querySelector(`[data-chat-item="${u.item}"] > *`)?.scrollIntoView({block:"center"})});return()=>cancelAnimationFrame(r)},[e,w,a,s,l,o,g,n,d,c]);let C=(0,i.useCallback)(e=>{let t=j.current;if(0===t.length)return;let n=e1(t,k.current);x(t[(n+e+t.length)%t.length])},[]);if(!e)return null;let N=m.trim().length>0?0===v.total?p("chat.searchNoResults"):p("chat.searchCount",{index:v.index+1,total:v.total}):"";return(0,r.jsxs)("div",{className:"chat-find-bar",role:"search","data-dismissible-layer":"",onKeyDown:e=>{"Escape"===e.key&&(e.preventDefault(),e.stopPropagation(),t())},children:[(0,r.jsx)("input",{ref:h,type:"search",value:m,onChange:e=>f(e.target.value),onKeyDown:e=>{"Enter"!==e.key||e.nativeEvent.isComposing||(e.preventDefault(),C(e.shiftKey?-1:1))},placeholder:p("chat.searchPlaceholder"),"aria-label":p("chat.searchPlaceholder"),autoComplete:"off",spellCheck:!1}),(0,r.jsx)("span",{className:"chat-find-count","aria-live":"polite",children:N}),(0,r.jsx)("button",{type:"button",onClick:()=>C(-1),disabled:0===v.total,"aria-label":p("chat.searchPrevious"),title:`${p("chat.searchPrevious")} (Shift+Enter)`,children:(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m18 15-6-6-6 6"})})}),(0,r.jsx)("button",{type:"button",onClick:()=>C(1),disabled:0===v.total,"aria-label":p("chat.searchNext"),title:`${p("chat.searchNext")} (Enter)`,children:(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m6 9 6 6 6-6"})})}),(0,r.jsx)("button",{type:"button",onClick:t,"aria-label":p("chat.searchClose"),title:`${p("chat.searchClose")} (Esc)`,children:(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M18 6 6 18"}),(0,r.jsx)("path",{d:"m6 6 12 12"})]})})]})}function ih({questions:e,containerRef:t,layoutKey:n,onJump:a,label:s}){let l=(0,i.useRef)(null),[o,d]=(0,i.useState)(-1),[c,u]=(0,i.useState)(!1);(0,i.useEffect)(()=>{let e=setTimeout(()=>u(!0),0);return()=>clearTimeout(e)},[]);let p=c&&e.length>=2;(0,i.useEffect)(()=>{let n=t.current;if(!n||!p)return;let r=0,i=null,a=()=>{r=0,i?.[0]?.isConnected||(i=n.querySelectorAll("[data-chat-item]"));let t=n.getBoundingClientRect().top+8,a=0,s=i.length-1,l=i.length-1;for(;a<=s;){let e=a+s>>1,n=i[e].firstElementChild?.getBoundingClientRect();n&&n.bottom>t?(l=e,s=e-1):a=e+1}let o=l>=0?Number(i[l].dataset.chatItem):-1,c=-1;for(let t of e){if(t.item>o)break;c=t.item}d(c)},s=()=>{r||(r=requestAnimationFrame(a))};return r=requestAnimationFrame(a),n.addEventListener("scroll",s,{passive:!0}),()=>{n.removeEventListener("scroll",s),r&&cancelAnimationFrame(r)}},[e,p,n,t]),(0,i.useEffect)(()=>{let e=l.current,t=e?.querySelector("[aria-current='true']");if(!e||!t)return;let n=t.offsetTop-e.scrollTop;(n<0||n+t.offsetHeight>e.clientHeight)&&(e.scrollTop=t.offsetTop-(e.clientHeight-t.offsetHeight)/2)},[o]);let h=e.length,m=(0,i.useCallback)((e,t)=>{let n="ArrowUp"===e.key?t-1:"ArrowDown"===e.key?t+1:"Home"===e.key?0:"End"===e.key?h-1:null;if(null===n)return;e.preventDefault();let r=Math.max(0,Math.min(h-1,n));l.current?.querySelectorAll("button")[r]?.focus()},[h]);if(!p)return null;let f=e.some(e=>e.item===o)?o:e[0].item;return(0,r.jsx)("nav",{className:"question-rail","aria-label":s,children:(0,r.jsx)("div",{ref:l,className:"question-rail-list",children:e.map((e,t)=>(0,r.jsx)(im,{question:e,position:t,count:h,active:e.item===o,focusable:e.item===f,onJump:a,onMoveFocus:m},e.item))})})}let im=(0,i.memo)(function({question:e,position:t,count:n,active:i,focusable:a,onJump:s,onMoveFocus:l}){let o=e.text.length>140?`${e.text.slice(0,140)}…`:e.text;return(0,r.jsx)("button",{type:"button",className:"question-rail-tick",tabIndex:a?0:-1,"aria-current":i?"true":void 0,"aria-label":`${t+1}/${n} ${o}`,title:o,onClick:()=>s(e.item),onKeyDown:e=>l(e,t),children:(0,r.jsx)("span",{"aria-hidden":"true"})})});function ig({label:e,tone:t,children:n}){return(0,r.jsxs)("div",{className:"run-status-line","data-tone":t,role:"status","aria-live":"polite",children:[(0,r.jsx)("span",{className:"run-status-label",children:e}),(0,r.jsx)("span",{className:"run-status-text",children:n})]})}let ix={manual:!0,threshold:!0,overflow:!0,idle:!0,incomplete:!0};function iv({compaction:e,t}){let[n,a]=(0,i.useState)(()=>Date.now());if((0,i.useEffect)(()=>{if(!e)return;a(Date.now());let t=setInterval(()=>a(Date.now()),1e3);return()=>clearInterval(t)},[e]),!e)return null;let s=Math.max(0,Math.floor((n-e.startedAt)/1e3)),l=e.reason&&!0===ix[e.reason]?t(`chat.compactionReason.${e.reason}`):null;return(0,r.jsxs)(ig,{label:t("chat.compactionLabel"),tone:"accent",children:[t("chat.compactionProgress",{seconds:s}),l?` \xb7 ${l}`:""]})}function ib({onDismiss:e,t}){return(0,r.jsxs)("div",{className:"interrupted-run-notice",role:"status",children:[(0,r.jsx)("span",{className:"interrupted-run-mark","aria-hidden":"true"}),(0,r.jsxs)("span",{className:"interrupted-run-text",children:[(0,r.jsx)("strong",{children:t("chat.interruptedTitle")}),(0,r.jsx)("span",{children:t("chat.interruptedDetail")})]}),(0,r.jsx)("button",{type:"button",onClick:e,"aria-label":t("chat.interruptedDismiss"),title:t("chat.interruptedDismiss"),children:(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M18 6 6 18"}),(0,r.jsx)("path",{d:"m6 6 12 12"})]})})]})}var iy=n(39092),iw=n.n(iy);let ik=["YUKI(유키)","ISANA(이사나)","MIO(미오)","RIN(린)","NOVA(노바)","SHION(시온)","HIKARI(히카리)"],ij={"YUKI(유키)":"yuki","ISANA(이사나)":"isana","MIO(미오)":"mio","RIN(린)":"rin","NOVA(노바)":"nova","SHION(시온)":"shion","HIKARI(히카리)":"hikari"},iS=["approval","choice","done","failed","blocked","working"],iC={approval:"부름",choice:"물음",done:"기쁨",failed:"사과",blocked:"난처",working:"시작"},iN={approval:!1,choice:!1,done:!1,failed:!1,blocked:!1,working:!0};function iI(e){switch(e){case"completed":return"done";case"failed":return"failed";case"aborted":return null;default:return"neutral"}}function iT(e){return void 0===e?"done":"string"==typeof e&&Object.hasOwn(iC,e)?e:null}function iM(e,t){let n=new Map,r=new Map;if(!Array.isArray(e))return{files:n,lines:r};for(let i of e){if("object"!=typeof i||null===i)continue;let{file:e,tag:a,ko:s}=i;if("string"!=typeof e||""===e)continue;let l=iT(a);if(null===l)continue;let o=t+e.replace(/^\/+/,""),d=n.get(l);d?d.push(o):n.set(l,[o]),"string"==typeof s&&""!==s.trim()&&r.set(o,s.trim())}return{files:n,lines:r}}function i$(e,t,n){let r=t&&Object.hasOwn(ij,t)?ij[t]:null;return r?e.get(r)?.get(n)??null:null}async function iR(e=fetch){try{let t=await e("/audio/completion/voices.json");if(!t.ok)return new Map;return function(e){let t=new Map;if("object"!=typeof e||null===e)return t;let{characters:n}=e;if(!Array.isArray(n))return t;for(let e of n){if("object"!=typeof e||null===e)continue;let{id:n,clips:r,stickers:i,captions:a}=e;if("string"!=typeof n||""===n)continue;let s=iM(r,"/audio/completion/"),l=iM(i,"/stickers/"),o=function(e){let t=new Map;if(!Array.isArray(e))return t;for(let n of e){if("object"!=typeof n||null===n)continue;let{tag:e,ko:r}=n;if("string"!=typeof r||""===r.trim())continue;let i=iT(e);if(null===i)continue;let a=t.get(i);a?a.push(r.trim()):t.set(i,[r.trim()])}return t}(a),d=new Map;for(let e of iS){let t=s.files.get(e)??[],n=new Map;for(let e of t){let t=s.lines.get(e);void 0!==t&&n.set(e,t)}d.set(e,{voices:t,stickers:l.files.get(e)??[],lines:n,captions:o.get(e)??[]})}t.set(n,d)}return t}(await t.json())}catch{return new Map}}function iE(e,t,n=Math.random){if(0===e.length)return null;if(1===e.length)return e[0];let r=null===t?-1:e.indexOf(t),i=-1===r?e.length:e.length-1,a=Math.min(i-1,Math.max(0,Math.floor(n()*i)));return e[-1!==r&&a>=r?a+1:a]}function iL(e){let t=[];if("bashExecution"!==e.role){if("string"==typeof e.content)t.push(e.content.trim());else for(let n of e.content)if("text"===n.type)t.push(n.text.trim());else if("toolCall"===n.type){let e="id"in n&&"string"==typeof n.id?n.id:"";t.push(`toolCall:${n.toolCallId||e}`)}}let n="toolResult"===e.role?e.toolCallId:"custom"===e.role?e.customType:"bashExecution"===e.role?e.command:null;return JSON.stringify([e.role,n,t.filter(Boolean)])}function iA(e,t,n){if(t&&("web6"!==t.provider||t.model!==iz))return{provider:t.provider,credentialId:t.credentialId};for(let t=e.length-1;t>=0;t--){let n=e[t];if("user"===n.role)break;if("assistant"===n.role&&("web6"!==n.provider||n.model!==iz))return{provider:n.provider,credentialId:n.credentialId}}return{provider:n,credentialId:void 0}}let iz="ChatGPT 6PRO",iP=["01","02","03"];function iW(e,t,n){if(!e||"streaming"===t||!ik.includes(e))return null;let r="failed"===t?"failed":"done",i=e.slice(0,e.indexOf("(")).toLowerCase(),a=iE(iP.map(e=>`/stickers/${i}/${r}/${e}.webp`),null,()=>(function(e){let t=0x811c9dc5;for(let n=0;n<e.length;n+=1)t=Math.imul(t^e.charCodeAt(n),0x1000193);return(t>>>0)/0x100000000})(n));return a?{src:a,alt:iC[r]}:null}let iF=new Map,i_=(0,i.createContext)(iF);function iD({utterances:e,children:t}){return(0,r.jsx)(i_.Provider,{value:e,children:t})}function iO({turnIndex:e,turnEntryId:t,sessionId:n,cwd:a,onOpenFile:s}){let l=(0,i.useContext)(i_).get(e);return l&&0!==l.length?(0,r.jsx)("div",{className:"inline-utterance-thread","data-turn":e,"data-turn-entry":t,style:{display:"contents"},children:l.map(e=>(0,r.jsx)(iH,{utterance:e,sessionId:n,cwd:a,onOpenFile:s},e.key))}):null}function iH({utterance:e,sessionId:t,cwd:n,onOpenFile:a}){let s=nm(null===e.accountSessionId?void 0:e.accountSessionId??t,e.provider,e.credentialId),[l,o]=(0,i.useState)(!1),[d,c]=(0,i.useState)(!1),u=(0,i.useRef)(null);(0,i.useLayoutEffect)(()=>{let e=u.current;e&&!l&&c(e.scrollHeight>e.clientHeight+1)},[e.text,l]);let p=e.text.trim().length>0,h=e.label?.trim(),m=s?.alias??h??(0,nt.bN)(e.provider),f=s?.alias.split("(",1)[0]?.trim(),g=s&&h&&h!==s.alias&&h!==f?`작업 \xb7 ${h}`:null,x=iW(s?.alias,e.status,e.key),v="failed"===e.status?"중단됨":"streaming"===e.status&&p?"작업 중":null;return(0,r.jsxs)("div",{className:"inline-utterance","data-status":e.status,style:{marginBottom:16},children:[(0,r.jsxs)("div",{className:"inline-utterance-role",style:{display:"flex",alignItems:"center",gap:9,marginBottom:2,fontSize:11,color:"var(--text-dim)",...s?{minHeight:40}:null},children:[s&&(0,r.jsx)(nx,{seed:s.seed,size:40,provider:e.provider}),(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:0},children:[(0,r.jsx)("span",{style:{fontSize:15,fontWeight:600,color:"var(--text)"},children:m}),v&&(0,r.jsx)("span",{style:{color:"failed"===e.status?"var(--danger)":"var(--text-dim)"},children:v})]}),g&&(0,r.jsx)("div",{style:{marginTop:1,fontSize:11,lineHeight:1.35,color:"var(--text-muted)",overflowWrap:"anywhere"},children:g})]})]}),p?(0,r.jsx)("div",{ref:u,style:{fontSize:12.5,lineHeight:1.6,...l?null:{maxHeight:240,overflow:"hidden"}},children:(0,r.jsx)(tG,{isStreaming:"streaming"===e.status,cwd:n,onOpenFile:a,children:e.text})}):(0,r.jsx)("div",{role:"status",style:{color:"var(--text-muted)",fontSize:11.5,lineHeight:1.6},children:"failed"===e.status?"발화 없이 중단되었습니다":"아직 발화가 없습니다"}),p&&(d||l)&&(0,r.jsx)("button",{type:"button",onClick:()=>o(e=>!e),"aria-expanded":l,style:{marginTop:4,padding:"3px 9px",height:22,border:"1px solid var(--border)",borderRadius:5,background:"none",color:"var(--text-muted)",cursor:"pointer",fontSize:11},children:l?"접기":"더보기"}),x&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("img",{src:x.src,alt:x.alt,style:{display:"block",width:"min(148px, 34vw)",maxWidth:"100%",height:"auto"},className:"jsx-8e1a78d1ba768be9 inline-utterance-sticker"}),(0,r.jsx)(iw(),{id:"8e1a78d1ba768be9",children:".inline-utterance-sticker{transform-origin:center 75%;animation:inline-utterance-sticker-pop 200ms cubic-bezier(0,0,.15,1)both}@keyframes inline-utterance-sticker-pop{from{opacity:0;transform:scale(.88)}to{opacity:1;transform:scale(1)}}@media(prefers-reduced-motion:reduce){.inline-utterance-sticker{animation:none}}"})]})]})}let iB=/^\[character-summon alias="([^"\r\n]+)" model="([^"\r\n]+)"(?: oauth-position="\d+")?\]\r?$/mu;function iU(e,t,n,r){if("string"!=typeof n)return[];let i=iB.exec(n),a=i?.[1],s=i?.[2];return a&&s?[{toolCallId:e,...t?{name:t}:{},alias:a,model:s,batchSize:r}]:[]}function iq(e){if(!e||"assistant"!==e.role)return[];let t=[];for(let n of e.content??[]){if("toolCall"!==n.type||"task"!==n.toolName)continue;let e=n.input,r=+(void 0!==e.task)+(Array.isArray(e.tasks)?e.tasks.length:0);if(t.push(...iU(n.toolCallId,"string"==typeof e.name?e.name:void 0,e.task,r)),Array.isArray(e.tasks))for(let i of e.tasks)!i||"object"!=typeof i||Array.isArray(i)||t.push(...iU(n.toolCallId,"name"in i&&"string"==typeof i.name?i.name:void 0,"task"in i?i.task:void 0,r))}return t}function iK(e){if(!e||"assistant"!==e.role)return[];let t=[];for(let n of e.content??[])"toolCall"===n.type&&"task"===n.toolName&&t.push(n.toolCallId);return t}let iV=/^agent:\/\/([^/?#]+)\/?$/i;function iJ(e,t){if(!e||"assistant"!==e.role)return[];let n=[];for(let r of e.content??[]){if("toolCall"!==r.type||"write"!==r.toolName)continue;let e=r.input,i="string"==typeof e.path?iV.exec(e.path):null,a=i?.[1],s=e.content;if(!a||"string"!=typeof s)continue;let l=t?.get(r.toolCallId);n.push({toolCallId:r.toolCallId,to:a,message:s,...l?.from?{from:l.from}:{},...l?.receipts?{receipts:l.receipts}:{}})}return n}let iG=["greeting","utterance","message","text"],iY=function(e){let t=(0,i.useMemo)(()=>(0,nM.Et)(),[]),n=function(e,t){let[n,r]=(0,i.useState)(null);return(0,i.useEffect)(()=>{if(!t)return void r(null);let n=!1,i=new AbortController;return r(null),e.getArchive(t,i.signal).then(e=>{n||r(e)}).catch(()=>{}),()=>{n=!0,i.abort()}},[e,t]),n}(t,e.sessionId),r=(0,i.useMemo)(()=>{let t=new Set(e.subagents.map(e=>e.id)),r=[];if(n&&n.sessionId===e.sessionId){let i=e.turns.flatMap(e=>e.characterSummons);for(let a of n.subagents){if(t.has(a.name))continue;let n=[...i].reverse().find(e=>e.name===a.name);n&&r.push(function(e,t,n){let r=e.status??"unknown",i={id:e.name,index:n,agent:"",agentSource:"bundled",status:r,task:e.firstTask||void 0,lastUpdate:e.modified,parentToolCallId:t.toolCallId},a="string"==typeof e.model&&e.model.trim()?e.model.trim():void 0,s="string"==typeof e.errorMessage&&e.errorMessage.trim()?e.errorMessage.trim():void 0;return(void 0!==a||void 0!==s)&&(i.progress={index:n,id:e.name,agent:"",status:r,task:e.firstTask,recentTools:[],recentOutput:[],toolCount:0,requests:0,tokens:0,cost:0,durationMs:0,...void 0!==a?{resolvedModel:a,resolvedModelIsFallback:!0===e.modelIsFallback}:{},...void 0!==s?{retryFailure:{attempt:0,errorMessage:s}}:{}}),i}(a,n,e.subagents.length+r.length))}}return function(e,t){let n=new Map;for(let t of e)for(let e of t.characterSummons){let r=n.get(e.toolCallId)??{turnIndex:t.index,requests:[]};r.requests.push(e),n.set(e.toolCallId,r)}return t.flatMap(t=>{let r=t.parentToolCallId?n.get(t.parentToolCallId):void 0;if(!r)return[];let i=r.requests.filter(e=>e.name),a="string"==typeof t.task?iB.exec(t.task):null,s=a?.[1],l=a?.[2],o=i.find(e=>e.name===t.id)??(s&&l?r.requests.find(e=>e.alias===s&&e.model===l):void 0)??(1===r.requests.length&&1===r.requests[0].batchSize?r.requests[0]:void 0);if(!o)return[];let d=e.flatMap(e=>e.peerSends.filter(e=>e.to===t.id||"all"===e.to).map(t=>({turnIndex:e.index,send:t})));return[{snapshot:t,turnIndex:r.turnIndex,summon:o,sends:d}]})}(e.turns,[...e.subagents,...r])},[e.subagents,e.turns,e.sessionId,n]),a=(0,i.useMemo)(()=>r.map(({snapshot:t})=>{let n=t.sessionFile?.split(/[\\/]/).pop()?.replace(/\.jsonl$/i,"")||t.id;return e.subagents.some(e=>e.id===t.id)?{key:t.id,liveId:t.id,status:t.status,archiveName:n}:{key:t.id,status:t.status,archiveName:n}}),[r,e.subagents]),s=(0,nq._Z)(a,{sessionId:e.sessionId??"",client:t,enabled:!!e.sessionId&&a.length>0});return(0,i.useMemo)(()=>r.flatMap(t=>(function(e,t,n){var r;let{snapshot:i,summon:a}=e,s="completed"===(r=i.status)||"unknown"===r?"settled":"failed"===r||"aborted"===r?"failed":"streaming",l="failed"===s,o=a?.model.split("/",1)[0]?.trim()||void 0,d=l&&o?o:function(e,t,n){let r="string"==typeof e.progress?.resolvedModel?e.progress.resolvedModel.trim():"",i=r.indexOf("/");if(i>0)return r.slice(0,i);let a=t?.model.trim()??"",s=a.indexOf("/");return s>0?a.slice(0,s):n?.trim()||void 0}(i,a,n),c=i.id.trim()||void 0,u=`subagent:${i.id}`,p=[],h=e.turnIndex,m=0;if((t?.entries??[]).forEach((t,n)=>{var r;let f;if("irc"in t){let{from:n,message:r,truncated:a}=t.irc;if(a||"string"!=typeof n||"string"!=typeof r)return;for(let t=m;t<e.sends.length;t+=1){let a=e.sends[t];if(a.send.message===r&&function(e,t){if(!e.from)return!1;let n=e.receipts;return!!n&&n.some(e=>e.to===t&&("injected"===e.outcome||"woken"===e.outcome||"revived"===e.outcome))}(a.send,i.id)&&a.send.from===n){h=a.turnIndex,m=t+1;break}}return}if("assistant"!==t.message.role)return;let g=t.message.provider||d;if(!g||l&&o&&g!==o)return;let x=((f=((r=t.message).content??[]).filter(e=>"text"===e.type).map(e=>e.text.trim()).filter(e=>e.length>0).join("\n\n")).length>0?f:function(e){let t="";for(let n of e.content??[]){if("toolCall"!==n.type||"yield"!==n.toolName)continue;let e=n.input.data,r="";if("string"==typeof e)r=e;else if("object"==typeof e&&null!==e&&!Array.isArray(e))for(let t of["report",...iG]){let n=e[t];if("string"==typeof n&&n.trim().length>0){r=n;break}}let i=r.trim();i.length>0&&(t=i)}return t}(r))||(l?t.message.errorMessage?.trim()??"":"");0!==x.length&&p.push({key:`${i.id}:${n}`,turnIndex:h,speakerId:u,provider:g,credentialId:t.message.credentialId,accountSessionId:null,label:l&&a?a.alias:c,text:x,status:s})}),0===p.length&&"settled"!==s&&d){let e=l?i.progress?.retryFailure?.errorMessage?.trim():void 0;p.push({key:`${i.id}:pending`,turnIndex:h,speakerId:u,provider:d,accountSessionId:null,label:l&&a?a.alias:c,text:e||"",status:s})}return p})(t,s.get(t.snapshot.id),e.sessionProvider)),[r,s,e.sessionProvider])},iZ="web6",iX=[],iQ=[],i0=function(e){let t=(0,i.useMemo)(()=>(function(e=(e,t)=>fetch(e,t),t="/api/web6/consults"){return{async listConsults(n,r){let i=n.trim();if(!i)throw Error("sessionId가 필요하다");let a=`${t}?sessionId=${encodeURIComponent(i)}`,s=await e(a,{signal:r});if(!s.ok)throw Error(`HTTP ${s.status}`);let l=await s.json(),o=l&&"object"==typeof l&&"consults"in l?l.consults:null;if(!Array.isArray(o))throw Error("consults 배열이 아니다");return o.flatMap(e=>{let t=function(e){if(!e||"object"!=typeof e||Array.isArray(e))return null;let t="string"==typeof e.sessionId?e.sessionId.trim():"";if(!t)return null;let n=e.startedAt;if("number"!=typeof n||!Number.isFinite(n))return null;let r=e.status;if("ok"!==r&&"failed"!==r)return null;let i="number"==typeof e.finishedAt&&Number.isFinite(e.finishedAt)?e.finishedAt:n,{conversationId:a,text:s,error:l}=e;return{sessionId:t,startedAt:n,finishedAt:i,elapsedMs:"number"==typeof e.elapsedMs&&Number.isFinite(e.elapsedMs)?e.elapsedMs:i-n,model:"string"==typeof e.model?e.model:"",status:r,conversationId:"string"==typeof a&&""!==a?a:void 0,text:"string"==typeof s&&""!==s?s:void 0,error:"string"==typeof l&&""!==l?l:void 0}}(e);return t?.sessionId===i?[t]:[]})}}})(),[]),[n,r]=(0,i.useState)(iQ),a=(0,i.useRef)(""),s=e.sessionId??"",l=s.length>0;return(0,i.useEffect)(()=>{if(!l){a.current="",r(iQ);return}let e=new AbortController,n=async()=>{if("u"<typeof document||"hidden"!==document.visibilityState)try{let n=await t.listConsults(s,e.signal),i=n.map(e=>`${e.startedAt}.${e.finishedAt}.${e.status}`).join("|");if(i===a.current)return;a.current=i,r(n)}catch{}};n();let i=setInterval(()=>void n(),5e3);return()=>{e.abort(),clearInterval(i)}},[t,l,s]),(0,i.useMemo)(()=>(function(e,t,n){if(0===e.length)return iX;let r=function(e){let t=[];for(let n=0;n<e.length;n+=1){let r=e[n];if("user"!==r.role)continue;let i=r.timestamp;"number"==typeof i&&Number.isFinite(i)&&t.push({index:n,openedAt:i})}return t}(t);if(0===r.length)return iX;let i=[];for(let t of[...e].sort((e,t)=>e.startedAt-t.startedAt)){if(t.sessionId!==n||"failed"!==t.status)continue;let e=function(e,t){let n;for(let r of e)r.openedAt>t||(!n||r.openedAt>=n.openedAt)&&(n=r);return n?.index}(r,t.startedAt);if(void 0===e)continue;let a=t.error??"";0!==a.trim().length&&i.push({key:`${iZ}:${t.startedAt}:${t.finishedAt}`,turnIndex:e,provider:"web6",speakerId:`${iZ}:${t.conversationId??"unknown"}`,text:a,status:"failed"})}return i.length>0?i:iX})(n,e.messages,s),[n,e.messages,s])},i1={sending:!0,accepted:!0,delivered:!1,unconfirmed:!1,failed:!1};function i2(e){return e.trim()}function i4(e){return i2(e.text)||(e.images>0?"[Image]":"")}function i5(e){let t=e.filter(e=>!i1[e.stage]);if(t.length<=4)return e;let n=new Set(t.slice(0,t.length-4).map(e=>e.id));return e.filter(e=>!n.has(e.id))}function i6(e,t){switch(t.type){case"submit":return i5([...e,{id:t.id,kind:t.kind,text:t.text,images:t.images??0,stage:"sending",inQueue:!1}]);case"ack":return e.map(e=>e.id===t.id&&"sending"===e.stage?{...e,stage:"accepted"}:e);case"fail":return i5(e.map(e=>e.id===t.id&&i1[e.stage]?{...e,stage:"failed",inQueue:!1}:e));case"queue":return function(e,t,n){let r=new Map,i=(e,t)=>{let n=`${e}\u0000${i2(t)}`;r.set(n,(r.get(n)??0)+1)};for(let e of t)i("steer",e);for(let e of n)i("followUp",e);let a=!1,s=e.map(e=>{if(!i1[e.stage])return e;let t=`${e.kind}\u0000${i4(e)}`,n=r.get(t)??0;return n>0?(r.set(t,n-1),e.inQueue&&"accepted"===e.stage)?e:(a=!0,{...e,stage:"accepted",inQueue:!0}):e.inQueue?(a=!0,{...e,stage:"unconfirmed",inQueue:!1}):e});return a?s:e}(e,t.steering,t.followUp);case"user-message":{let n=i2(t.text);if(!n&&0===t.images)return e;let r=e.find(e=>(i1[e.stage]||"unconfirmed"===e.stage)&&e.kind===t.kind&&i2(e.text)===n&&e.images===t.images);if(!r)return e;return i5(e.map(e=>e===r?{...e,stage:"delivered",inQueue:!1}:e))}case"withdraw":{let n=e=>i1[e.stage]||"unconfirmed"===e.stage;if(void 0===t.text)return e.filter(e=>!n(e));let r=i2(t.text),i=e.find(e=>n(e)&&e.kind===t.kind&&(i2(e.text)===r||i4(e)===r));return i?e.filter(e=>e!==i):e}case"idle":{let t=e.filter(e=>e.inQueue);return t.length===e.length?e:t}case"reset":return 0===e.length?e:[]}}let i8={steer:"delivery.kind.steer",followUp:"delivery.kind.followUp"},i3={sending:"delivery.stage.sending",accepted:"delivery.stage.accepted",delivered:"delivery.stage.delivered",unconfirmed:"delivery.stage.unconfirmed",failed:"delivery.stage.failed"};function i7({rows:e,removeLabel:t,onRemove:n}){let a,{st:s}=ng(),[l,o]=(0,i.useState)(!1),{rows:d,hidden:c}=(a=Math.max(0,e.length-4),l||0===a?{rows:e,hidden:a}:{rows:e.slice(a),hidden:a}),u=e.length>4;return(0,i.useEffect)(()=>{u||o(!1)},[u]),(0,r.jsxs)(r.Fragment,{children:[u&&(0,r.jsx)("button",{type:"button",className:"answer-delivery-toggle","aria-expanded":l,onClick:()=>o(e=>!e),children:l?s("delivery.showRecent",{count:4}):s("delivery.showOlder",{count:c})}),(0,r.jsx)("ul",{className:"answer-delivery-list","aria-live":"polite",children:d.map(e=>{let i=rx(e.text),a=[i?[i.message,i.documents.map(e=>e.name).join(", ")].filter(Boolean).join(" \xb7 "):e.text.trim(),e.images>0?s("delivery.images",{count:e.images}):""].filter(Boolean).join(" \xb7 ");return(0,r.jsxs)("li",{className:"answer-delivery-row","data-kind":e.kind,"data-stage":e.stage,children:[(0,r.jsx)("span",{className:"answer-delivery-kind",children:s(i8[e.kind])}),(0,r.jsx)("span",{className:"answer-delivery-text",title:a,children:a}),(0,r.jsx)("span",{className:"answer-delivery-stage",children:s(i3[e.stage])}),e.removable&&n&&(0,r.jsx)("button",{type:"button",className:"answer-delivery-remove",title:t,"aria-label":`${t}: ${a}`,onClick:()=>n(e.kind,e.text),children:(0,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M18 6 6 18M6 6l12 12"})})})]},e.key)})})]})}let i9=(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),(0,r.jsx)("path",{d:"M15.54 8.46a5 5 0 0 1 0 7.07"})]}),ae=(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),(0,r.jsx)("path",{d:"m22 9-6 6m0-6 6 6"})]});function at({soundEnabled:e,onToggle:t}){let n=e?"완료음 끄기":"완료음 켜기";return(0,r.jsx)("div",{role:"group","aria-label":"오디오",style:{display:"flex",alignItems:"center",gap:6},children:(0,r.jsx)("button",{type:"button",className:`composer-icon-button${e?" is-active":""}`,onClick:t,"aria-pressed":e,title:n,"aria-label":n,children:(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:e?i9:ae})})})}let an=RegExp("^(?:아|어|음|응|네|자|그럼|이제|일단|그만|좀|알았어|알겠어|아니|그래)*(?:(?:통화|전화)(?:를|좀|그만)*)?(?:좀|그만)*(?:끊어|끊어봐|끊을게|끊자|끊겠습니다|끊으라고)(?:줘|주세요|요)?$|^(?:아|어|음|응|네|자|그럼|이제|일단|그만|좀|알았어|알겠어|아니|그래)*(?:통화|전화)(?:를|좀|그만)*(?:종료|종료해|종료해봐|종료할게|종료하자|종료하라고)(?:줘|주세요|요)?$","u"),ar={idle:!0,connecting:!0,live:!0,working:!0,error:!0,closed:!0};function ai(e){if("complete"===e.iceGatheringState)return Promise.resolve();let{promise:t,resolve:n}=Promise.withResolvers(),r=()=>{clearTimeout(a),e.removeEventListener("icegatheringstatechange",i),n()},i=()=>{"complete"===e.iceGatheringState&&r()},a=setTimeout(r,3e3);return e.addEventListener("icegatheringstatechange",i),t}function aa(e,t){return 401===e||"live-auth"===t?"auth":502===e||"live-upstream"===t?"upstream":"failed"}let as={unsupported:"chat.liveUnsupported","mic-denied":"chat.liveMicDenied","mic-unavailable":"chat.liveMicUnavailable",auth:"chat.liveAuthRequired",upstream:"chat.liveUpstreamFailed",failed:"chat.liveFailed"},al=(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("path",{d:"M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3z"}),(0,r.jsx)("path",{d:"M19 10v2a7 7 0 0 1-14 0v-2"}),(0,r.jsx)("line",{x1:"12",y1:"19",x2:"12",y2:"22"})]}),ao=(0,r.jsx)(r.Fragment,{children:(0,r.jsx)("rect",{x:"4",y:"4",width:"16",height:"16",rx:"3"})});function ad({sessionId:e,onEnsureSession:t,onTranscriptPersisted:n}){let{t:a}=(0,R.s)(),s=function(e,t,n){let{locale:r}=(0,R.s)(),[a,s]=(0,i.useState)("idle"),[l,o]=(0,i.useState)(null),[d,c]=(0,i.useState)(null),[u,p]=(0,i.useState)(null),[h,m]=(0,i.useState)(null),[f,g]=(0,i.useState)(!1),x=(0,i.useRef)(null),v=(0,i.useRef)(null),b=(0,i.useRef)(null),y=(0,i.useRef)(null),w=(0,i.useRef)(null),k=(0,i.useRef)(0);(0,i.useEffect)(()=>{m("u">typeof RTCPeerConnection&&"u">typeof navigator&&"function"==typeof navigator.mediaDevices?.getUserMedia)},[]);let j=(0,i.useCallback)(e=>{k.current+=1;let t=w.current;for(let e of(w.current=null,y.current?.close(),y.current=null,x.current?.close(),x.current=null,v.current?.getTracks()??[]))e.stop();v.current=null;let n=b.current;b.current=null,n&&(n.srcObject=null,n.remove()),t&&fetch(`/api/live/call/${encodeURIComponent(t)}`,{method:"DELETE"}).catch(()=>{}),s(e),p(null),g(!1)},[]),S=(0,i.useCallback)((e,t)=>{o(e),c(t??null),j("error")},[j]),C=(0,i.useCallback)(async()=>{let i,a=k.current+1;k.current=a,o(null),c(null),g(!0),s("connecting");let l=e;if(!l&&t){try{l=await t()}catch{l=void 0}if(k.current!==a)return}if(!l){k.current===a&&(g(!1),S("failed"));return}try{i=await navigator.mediaDevices.getUserMedia({audio:!0})}catch(t){let e=t instanceof DOMException?t.name:"";k.current===a&&(g(!1),S("NotAllowedError"===e||"SecurityError"===e?"mic-denied":"mic-unavailable"));return}if(k.current!==a){for(let e of i.getTracks())e.stop();return}v.current=i;try{let e,t,o=new RTCPeerConnection;for(let e of(x.current=o,i.getTracks()))o.addTrack(e,i);let d=document.createElement("audio");if(d.autoplay=!0,b.current=d,o.ontrack=e=>{let[t]=e.streams;t&&(d.srcObject=t)},await o.setLocalDescription(await o.createOffer()),await ai(o),k.current!==a)return;let c=o.localDescription?.sdp;if(!c)throw Error("The browser produced no offer SDP.");let u=await fetch("/api/live/offer",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionId:l,sdp:c,locale:r})}),h=await u.json().catch(()=>({})),m="",f="";if(h&&"object"==typeof h&&("error"in h&&(e=h.error),"message"in h&&"string"==typeof h.message&&(t=h.message),"callId"in h&&"string"==typeof h.callId&&(m=h.callId),"sdp"in h&&"string"==typeof h.sdp&&(f=h.sdp)),!u.ok||!m||!f){k.current===a&&(g(!1),S(aa(u.status,e),t));return}if(k.current!==a)return void fetch(`/api/live/call/${encodeURIComponent(m)}`,{method:"DELETE"}).catch(()=>{});if(await o.setRemoteDescription({type:"answer",sdp:f}),k.current!==a){o.close(),fetch(`/api/live/call/${encodeURIComponent(m)}`,{method:"DELETE"}).catch(()=>{});return}w.current=m;let v=new EventSource(`/api/live/events?callId=${encodeURIComponent(m)}`);y.current=v,v.onmessage=e=>{let t;if(k.current===a){try{t=JSON.parse(e.data)}catch{return}if(t&&"object"==typeof t&&"type"in t){if("state"===t.type&&"state"in t){var r;if("string"!=typeof t.state||(r=t.state,!0!==ar[r]))return;"closed"===t.state?j("closed"):s(t.state);return}if("transcript"===t.type&&"role"in t&&"text"in t){if(("user"===t.role||"assistant"===t.role)&&"string"==typeof t.text){let e;p({role:t.role,text:t.text}),"final"in t&&!0===t.final&&n&&Promise.resolve().then(()=>n(l)).catch(()=>{}),"final"in t&&!0===t.final&&"user"===t.role&&(e=t.text.normalize("NFC").replace(/[^\p{L}\p{N}]+/gu,"")).length>0&&an.test(e)&&j("idle")}return}"error"===t.type&&"message"in t&&"string"==typeof t.message&&S("upstream",t.message)}}},v.onerror=()=>{k.current===a&&w.current&&S("failed")},s("live")}catch(e){k.current===a&&S("failed",e instanceof Error?e.message:String(e))}finally{k.current===a&&g(!1)}},[e,t,n,r,S,j]),N=(0,i.useCallback)(()=>{if("idle"===a||"closed"===a||"error"===a){f||C();return}j("idle")},[f,a,C,j]);return(0,i.useEffect)(()=>()=>j("closed"),[j]),{state:a,failure:l,detail:d,transcript:u,supported:h,toggle:N}}(e,t,n),l="connecting"===s.state||"live"===s.state||"working"===s.state,o="connecting"===s.state?"chat.liveConnecting":"working"===s.state?"chat.liveWorking":"live"===s.state?"chat.liveOn":null,d=a(l?"chat.liveStop":"chat.liveStart"),c=!1===s.supported?as.unsupported:s.failure?as[s.failure]:null,u=!!(e||t),p=u?null:"chat.liveNeedsSession";return(0,r.jsxs)("div",{role:"group","aria-label":a("chat.liveVoice"),style:{display:"flex",alignItems:"center",gap:6,flex:"0 1 auto",minWidth:0},children:[c&&(0,r.jsx)("span",{role:"status",style:{fontSize:11,color:"var(--danger)",maxWidth:220,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:s.detail??void 0,children:a(c)}),o&&(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-muted)",minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:a(o)}),(0,r.jsx)("button",{type:"button",className:`composer-icon-button${l?" is-active":""}`,onClick:s.toggle,disabled:!s.supported||!u,"aria-pressed":l,title:p?a(p):d,"aria-label":p?a(p):d,children:(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:l?ao:al})})]})}let ac={display:"inline-flex",alignItems:"center",flexShrink:0,height:32,padding:"0 10px",border:"1px solid var(--accent-line)",borderRadius:"var(--radius-control)",background:"var(--accent-soft)",color:"var(--accent-hover)",fontFamily:"var(--font-mono)",fontSize:11,fontWeight:600,lineHeight:1.3,whiteSpace:"nowrap"};function au({sessionId:e}){let{t}=(0,R.s)(),[n,a]=(0,i.useState)(null);return((0,i.useEffect)(()=>{if(!e)return void a(null);let t=!1,n=0,r=!1,i=async()=>{if("visible"===document.visibilityState)try{let n=await fetch("/api/gpt6/handles",{cache:"no-store"});if(!n.ok)return;let i=await n.json();if(t)return;let s=Array.isArray(i.handles)?i.handles:[],l=s.find(t=>t.sessionId===e&&"active"===t.status)?.handle??null;r=null!==l,a(l)}catch{}},s=async()=>{await i(),t||(n=window.setTimeout(()=>void s(),r?5e3:3e4))};return s(),document.addEventListener("visibilitychange",i),()=>{t=!0,window.clearTimeout(n),document.removeEventListener("visibilitychange",i)}},[e]),n)?(0,r.jsx)("span",{style:ac,title:t("gpt6.boundBadgeHint",{handle:n}),children:t("gpt6.boundBadge",{handle:n})}):null}function ap(e){if(!e||"object"!=typeof e||"string"!=typeof e.data||"string"!=typeof e.mimeType||!e.mimeType.startsWith("image/"))return!1;let t=function(e){if(!e||e.length%4!=0)return null;let t=e.endsWith("==")?2:+!!e.endsWith("="),n=e.length-t;for(let t=0;t<n;t+=1){var r;if(!((r=e.charCodeAt(t))>=65&&r<=90||r>=97&&r<=122||r>=48&&r<=57||43===r||47===r))return null}for(let t=n;t<e.length;t+=1)if("="!==e[t])return null;return e.length/4*3-t}(e.data);return null!==t&&t<=0xa00000}let ah=new Map,am="ompweb-drafts-for-reload-v1",af=!1,ag=new Map,ax=new Map,av="\0stale",ab=new Map,ay=0,aw=new Map,ak=new Map,aj=new Map,aS=new Map,aC=new Map,aN=(e,t,n)=>rS(e,t,n.length?{sentAttachmentIds:n}:{}),aI=null,aT=!1;function aM(){if(af||"u"<typeof sessionStorage)return;af=!0;let e=sessionStorage.getItem(am);if(e){sessionStorage.removeItem(am);try{let t=JSON.parse(e);if(!Array.isArray(t))return;for(let e of t){if(!Array.isArray(e)||2!==e.length||"string"!=typeof e[0])continue;let t=e[1];t&&"string"==typeof t.value&&Array.isArray(t.images)&&Array.isArray(t.documents)&&(ah.set(e[0],aR(t)),"string"==typeof t.draftId&&t.draftId&&(ag.set(e[0],t.draftId),ax.set(t.draftId,av)),aD(e[0]))}}catch{}}}function a$(){if("u"<typeof sessionStorage)return{ok:!1,error:"sessionStorage unavailable"};try{return sessionStorage.setItem(am,JSON.stringify([...ah.entries()].map(([e,t])=>{let n=ag.get(e);return[e,n?{...aR(t),draftId:n}:aR(t)]}))),{ok:!0}}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}}function aR(e){return{value:e.value,images:e.images.map(e=>({...e})),documents:e.documents.map(e=>({...e}))}}function aE(e){return!e.value&&0===e.images.length&&0===e.documents.length}function aL(e){aM();let t=ah.get(e);return t?aR(t):null}function aA(e,t){aM(),aE(t)?ah.delete(e):ah.set(e,aR(t)),aD(e)}function az(e){ah.delete(e),aD(e)}function aP(e,t,n,r,i,a=[]){let s=[...t??[],...r].filter(ap).slice(0,10).map(({data:e,mimeType:t})=>({data:e,mimeType:t})),l=rm([...i??[],...a]);return{value:e.trim()?n.trim()?`${e}
18
18
 
19
- ${n}`:e:n,images:s,documents:l}}function aW(e,t,n){if(e===t)return n?aR(n):aL(t);let r=aL(e),i=n&&!aE(n)?aR(n):r??(n?aR(n):null),a=aL(t),s=ag.get(e);if(ag.delete(e),s&&!ag.has(t)&&ag.set(t,s),az(e),!i)return a;let l=a?aP(a.value,a.images,i.value,i.images,a.documents,i.documents):i;return aA(t,l),aR(l)}function aF(e){let t=[];for(let n of e??[])n.attachmentId&&!t.includes(n.attachmentId)&&t.push(n.attachmentId);return t}function a_(e){aM();let t=ag.get(e);return t||(t=function(){let e=globalThis.crypto;if("function"==typeof e?.randomUUID)return e.randomUUID();let t=e.getRandomValues(new Uint8Array(16));t[6]=15&t[6]|64,t[8]=63&t[8]|128;let n=[...t].map(e=>e.toString(16).padStart(2,"0")).join("");return`${n.slice(0,8)}-${n.slice(8,12)}-${n.slice(12,16)}-${n.slice(16,20)}-${n.slice(20)}`}(),ag.set(e,t)),t}function aD(e){let t=aF(ah.get(e)?.documents),n=t.length?a_(e):ag.get(e);for(let[e,n]of ak){for(let e of t)n.delete(e);0===n.size&&ak.delete(e)}let r=`${n??""}|${t.join(",")}`;aS.get(e)!==r&&(0!==t.length||n?aS.set(e,r):aS.delete(e),aV())}async function aO(e){let t=a_(e);aw.set(t,(aw.get(t)??0)+1),await aC.get(t);let n=!1;return{draftId:t,end(e){if(n)return;n=!0;let r=(aw.get(t)??1)-1;if(r>0?aw.set(t,r):aw.delete(t),e){let n=ak.get(t)??new Set;n.add(e),ak.set(t,n)}ax.set(t,av),aV()}}}function aH(e,t){let n=aj.get(e);if(!n)return[];for(let e of t)n.delete(e);return 0===n.size&&aj.delete(e),[...n].sort()}async function aB(){if(!aN)return;let e=[...function(){let e=new Map,t=(t,n)=>{let r=e.get(t)??new Set;for(let e of n)r.add(e);e.set(t,r)};for(let[e,n]of ag)t(n,aF(ah.get(e)?.documents));for(let{draftId:e,ids:n}of ab.values())t(e,n);for(let[e,n]of ak)t(e,n);for(let e of ax.keys())t(e,[]);for(let e of aj.keys())t(e,[]);return new Map([...e].map(([e,t])=>[e,[...t].sort()]))}()].filter(([e,t])=>{if(aw.has(e))return!1;let n=ax.get(e);return aH(e,t).length>0||(0===t.length?void 0!==n:n!==t.join(","))}),t=aw.size>0,n=!1;for(let[r,i]of[...e.filter(([,e])=>e.length>0),...e.filter(([,e])=>0===e.length)]){if(0===i.length&&t)continue;let e=aH(r,i),a=aN(r,i,e).then(()=>{0===i.length?ax.delete(r):ax.set(r,i.join(","));let t=aj.get(r);if(t){for(let n of e)t.delete(n);0===t.size&&aj.delete(r)}},()=>{n=!0,i.length>0&&(t=!0)});aC.set(r,a),await a,aC.get(r)===a&&aC.delete(r)}n?function(){if(aK)return;aK=!0;let e=setTimeout(()=>{aK=!1,aV()},aq);"object"==typeof e&&"unref"in e&&e.unref(),aq=Math.min(2*aq,6e4)}():aq=aU}let aU=5e3,aq=5e3,aK=!1;function aV(){if(aN){if(aI){aT=!0;return}aI=Promise.resolve().then(aB).finally(()=>{aI=null,aT&&(aT=!1,aV())})}}let aJ=Math.floor(Number.MAX_SAFE_INTEGER/1048576),aG=Object.freeze({uploadLimitMb:100,autoCleanupEnabled:!0,orphanGraceDays:7});function aY(e){return"number"==typeof e&&Number.isSafeInteger(e)&&e>=1&&e<=aJ}async function aZ(e){let t,n=await e.json().catch(()=>null);if(!e.ok||!n||!aY(n.uploadLimitMb)||"boolean"!=typeof n.autoCleanupEnabled)throw Error("string"==typeof n?.error?n.error:`HTTP ${e.status}`);return{uploadLimitMb:aY((t=n&&"object"==typeof n?n:{}).uploadLimitMb)?t.uploadLimitMb:aG.uploadLimitMb,autoCleanupEnabled:"boolean"==typeof t.autoCleanupEnabled?t.autoCleanupEnabled:aG.autoCleanupEnabled,orphanGraceDays:7}}async function aX(e={}){return aZ(await fetch("/api/attachment-settings",{cache:"no-store",signal:e.signal}))}async function aQ(e){return aZ(await fetch("/api/attachment-settings",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}))}function a0(e){let t=/(?:^|\s)@"([^"\n]*)$/.exec(e);if(t)return{start:e.length-(t[1].length+2),query:t[1],quoted:!0};let n=/(?:^|\s)@([^\s"]*)$/.exec(e);return n?{start:e.length-(n[1].length+1),query:n[1],quoted:!1}:null}function a1(e){let t=0;for(let n=0;n<e.length;n++)"/"===e[n]&&t++;return t}function a2(e,t){if(!e)return!0;let n=0;for(let r=0;r<t.length&&n<e.length;r++)t[r]===e[n]&&n++;return n===e.length}let a4="omp-web:model-picks";function a5(){try{let e=JSON.parse(window.localStorage.getItem(a4)??"{}");if(!e||"object"!=typeof e||Array.isArray(e))return{};let t={};for(let[n,r]of Object.entries(e))"number"==typeof r&&Number.isFinite(r)&&r>0&&(t[n]=Math.floor(r));return t}catch{return{}}}function a6(e,t,n,r,i={}){let a=i.gap??8,s=i.margin??8,l=i.prefer??"above",o=Math.min(i.minHeight??120,Math.max(0,n-2*s)),d=Math.max(0,e-a-s),c=Math.max(0,n-t-a-s),u="above"===l?d:c,p="above"===l?c:d,h=u>=r||u>=p;return{side:h?l:"above"===l?"below":"above",maxHeight:Math.max(o,Math.min(r,h?u:p))}}function a8(e,t,n){return Math.min(e*t,n)}function a3(e,t,n){let{viewportFraction:r,cap:a,gap:s,margin:l,minHeight:o,prefer:d}=n,[c,u]=(0,i.useState)({side:d??"above",maxHeight:a}),p=(0,i.useCallback)(()=>{let t=e.current;if(!t)return;let n=window.visualViewport?.height??window.innerHeight,i=t.getBoundingClientRect(),c=a6(i.top,i.bottom,n,a8(n,r,a),{gap:s,margin:l,minHeight:o,prefer:d});u(e=>e.side===c.side&&e.maxHeight===c.maxHeight?e:c)},[e,a,s,l,o,d,r]);return(0,i.useEffect)(()=>{if(!t)return;p();let n=e.current,r=n?new ResizeObserver(p):null;return n&&r&&r.observe(n),window.addEventListener("resize",p),window.addEventListener("scroll",p,!0),window.visualViewport?.addEventListener("resize",p),window.visualViewport?.addEventListener("scroll",p),()=>{r?.disconnect(),window.removeEventListener("resize",p),window.removeEventListener("scroll",p,!0),window.visualViewport?.removeEventListener("resize",p),window.visualViewport?.removeEventListener("scroll",p)}},[e,p,t]),c}var a7=n(14755);async function a9(e,t,n,r,i,a,s){let l=e.slice(1).split(/\s/,1)[0];try{let o=t?.length?t:await s?.()??[],d=[...sh,...o].find(e=>e.name===l||"aliases"in e&&e.aliases?.includes(l));if(a&&(!d||"builtin"===d.source))return i(`/${l} cannot run with attachments. Remove them and retry.`),!1;let c=await n?.(e);if(c?.handled){if(c.error)return!1;return c.prompt&&r(c.prompt),!0}if(d&&"builtin"!==d.source)return r(e),!0;return i(`/${l} is not available in this web session.`),!1}catch(e){return i(e instanceof Error?e.message:String(e)),!1}}function se(e){let t=e.transcription?.state;return"planning"===t||"confirm"===t||"running"===t}let st=["off","default","full"],sn={off:"none",default:"default",full:"full"},sr=a7.IN.join(" \xb7 "),si=a7.C1.filter(e=>!a7.IN.includes(e)).join(" \xb7 ");function sa(e){return"above"===e?{bottom:"calc(100% + 8px)"}:{top:"calc(100% + 8px)"}}let ss=new Intl.Collator(void 0,{numeric:!0,sensitivity:"base"}),sl=0,so={"text/markdown":"Markdown","text/plain":"Text","application/pdf":"PDF"};function sd(e,t){return ss.compare(e.name||e.modelId,t.name||t.modelId)||ss.compare(e.provider,t.provider)||ss.compare(e.modelId,t.modelId)}let sc=["auto","off","minimal","low","medium","high","xhigh","max"],su=["low","medium","high","xhigh"],sp={auto:"chat.thinkingAuto",off:"chat.thinkingOff",minimal:"chat.thinkingMinimal",low:"chat.thinkingLow",medium:"chat.thinkingMedium",high:"chat.thinkingHigh",xhigh:"chat.thinkingXhigh",max:"chat.thinkingMax"},sh=[{name:"compact",descriptionKey:"chat.commandCompact",source:"builtin"},{name:"reload",descriptionKey:"chat.commandReload",source:"builtin"},{name:"name",descriptionKey:"chat.commandName",source:"builtin"},{name:"session",descriptionKey:"chat.commandSession",source:"builtin"},{name:"copy",descriptionKey:"chat.commandCopy",source:"builtin"}],sm=["builtin","extension","custom","mcp_prompt","prompt","file","skill"],sf={builtin:"chat.builtIn",extension:"chat.extensions",custom:"chat.customCommands",mcp_prompt:"chat.mcpPrompts",prompt:"chat.prompts",file:"chat.fileCommands",skill:"chat.skills"},sg={builtin:0,extension:1,custom:2,mcp_prompt:3,prompt:4,file:5,skill:6};function sx(e,t,n){let r=e.name.toLowerCase(),i=sv(e,n).toLowerCase();return r===t?0:r.startsWith(t)?1:r.includes(t)?2:i.includes(t)?3:4}function sv(e,t){return"descriptionKey"in e?t(e.descriptionKey):e.description??""}function sb(e,t){return"skill"===e.source&&!!e.name.startsWith("skill:")&&!0===t[e.name.slice(6)]}function sy(e){return{data:e.data,mimeType:e.mimeType}}function sw(e){return{...e,previewUrl:`data:${e.mimeType};base64,${e.data}`}}function sk(e){return(e??[]).filter(ap).slice(0,10).map(sw)}let sj=/^File saved at: (.+)\n\(([^,\n]+), (\d+) bytes\)/,sS="\n\nTranscript of the audio ";function sC(e){return rm(e).map(e=>{let t=rw(e),n="audio"===t&&e.attachmentId&&!e.text.includes(sS)?sj.exec(e.text):null;return{...e,id:++sl,status:"ready",..."audio"===t||"file"===t?{stored:t}:{},...n?{storedInfo:{path:n[1],mimeType:n[2],size:Number(n[3])}}:{}}})}function sN({name:e,mimeType:t,size:n,text:r,attachmentId:i}){return i?{name:e,mimeType:t,size:n,text:r,attachmentId:i}:{name:e,mimeType:t,size:n,text:r}}function sI(e,t){let n=new Map(t.flatMap(e=>e.attachmentId?[[e.attachmentId,e]]:[]));return[...e.map(e=>{let t=e.attachmentId?n.get(e.attachmentId):void 0;return t?(n.delete(e.attachmentId),{...e,id:t.id,sourceSize:t.sourceSize,storedInfo:t.storedInfo??e.storedInfo,transcription:t.transcription}):e}),...t.filter(e=>"ready"!==e.status)]}class sT extends Error{constructor(e,t,n,r){super(e),this.code=t,this.completedParts=n,this.parts=r}}let sM="composer:unkeyed";async function s$(e){let t=await e.json().catch(()=>null),n=t&&"object"==typeof t?{...t}:{};if(e.ok)return n;throw new sT("string"==typeof n.error?n.error:`HTTP ${e.status}`,"string"==typeof n.code?n.code:null,"number"==typeof n.completedParts?n.completedParts:null,"number"==typeof n.parts?n.parts:null)}function sR(e){e.previewUrl.startsWith("blob:")&&URL.revokeObjectURL(e.previewUrl)}function sE({tone:e,title:t,body:n}){let i="error"===e?"danger":"warning";return(0,r.jsxs)("div",{role:"alert",style:{display:"flex",alignItems:"flex-start",gap:8,maxHeight:120,marginBottom:8,padding:"7px 10px",overflowY:"auto",border:`1px solid var(--${i}-line)`,borderRadius:"var(--radius-control)",background:`var(--${i}-soft)`,color:`var(--${i})`,fontSize:11,lineHeight:1.45},children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0,marginTop:1},"aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M10.3 2.9 1.8 17a2 2 0 0 0 1.7 3h17a2 2 0 0 0 1.7-3L13.7 2.9a2 2 0 0 0-3.4 0Z"}),(0,r.jsx)("line",{x1:"12",y1:"9",x2:"12",y2:"13"}),(0,r.jsx)("line",{x1:"12",y1:"17",x2:"12.01",y2:"17"})]}),(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("div",{style:{fontWeight:600},children:t}),(0,r.jsx)("div",{style:{whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:n})]})]})}function sL({error:e}){return e?(0,r.jsx)(sE,{tone:"error",title:"Model error",body:e}):null}function sA({warnings:e}){return e&&0!==e.length?(0,r.jsx)(sE,{tone:"warning",title:e.length>1?"Model scope warnings":"Model scope warning",body:e.join("\n")}):null}let sz=(0,i.forwardRef)(function({onSend:e,onAbort:t,onSteer:n,onFollowUp:a,isStreaming:l,model:o,isAutoModelSelection:d,modelNames:c,modelList:u,modelError:p,modelScopeWarnings:h,onModelChange:m,onMainPresetChange:f,mainPresetActiveAlias:g,modelRoles:x,onRoleModelChange:v,modelSwitching:b,onCompact:y,onAbortCompaction:w,isCompacting:k,compactError:j,compactResult:S,toolPreset:C,onToolPresetChange:N,thinkingLevel:I,effectiveThinkingLevel:T,thinkingCeiling:M,onThinkingLevelChange:$,availableThinkingLevels:E,thinkingLevelMap:L,fastMode:A=null,fastModeBusy:z=!1,onFastModeToggle:P,retryInfo:F,deliveryRows:_=[],inputHistory:D=[],onRecallQueue:O,onRemoveQueuedMessage:H,slashCommands:B,slashCommandsLoading:U,onLoadSlashCommands:q,onBuiltinCommand:K,soundEnabled:V,onSoundToggle:J,onAudioUnlock:G,onPromptWithStreamingBehavior:Y,draftKey:Z,cwd:X,sessionId:Q,onEnsureSession:ee,onLiveTranscriptPersisted:et},en){let er,ei,ea,es,el,eo,ed,ec,eu,ep,{t:eh}=(0,R.s)(),{st:em}=ng(),ef=_.some(e=>e.removable),eg=W(),[ex,ev]=(0,i.useState)(()=>Z?aL(Z)?.value??"":""),[eb,ey]=(0,i.useState)(!1),[ew,ek]=(0,i.useState)(null),[ej,eS]=(0,i.useState)(""),[eC,eN]=(0,i.useState)({});(0,i.useEffect)(()=>{eb&&eN(a5())},[eb]);let[eI,eT]=(0,i.useState)(!1),[eM,e$]=(0,i.useState)(null),[eR,eE]=(0,i.useState)(!1),[eL,eA]=(0,i.useState)(!1),[ez,eP]=(0,i.useState)(null),[eW,eF]=(0,i.useState)(!1),[e_,eD]=(0,i.useState)(()=>Z?sk(aL(Z)?.images):[]),[eO,eH]=(0,i.useState)(()=>Z?sC(aL(Z)?.documents):[]),[eB,eU]=(0,i.useState)(null),eq=(0,i.useMemo)(()=>eO.filter(e=>"ready"===e.status),[eO]),eK=eO.some(e=>"ready"!==e.status||se(e)),eV=eO.filter(e=>"audio"===e.stored&&e.attachmentId&&e.storedInfo&&(void 0!==e.transcription||!e.text.includes(sS))),eJ=ex.trimStart(),eG=0===e_.length&&0===eO.length&&eJ.startsWith("!"),eY=eG&&eJ.startsWith("!!"),[eZ,eX]=(0,i.useState)(!1),[eQ,e0]=(0,i.useState)(0),[e1,e2]=(0,i.useState)(null),[e4,e5]=(0,i.useState)(!1),[e6,e8]=(0,i.useState)(0),[e3,e7]=(0,i.useState)(!1),[e9,te]=(0,i.useState)(0),[tt,tn]=(0,i.useState)(null),[tr,ti]=(0,i.useState)(!1),[ta,ts]=(0,i.useState)(null),[tl,to]=(0,i.useState)(null),td=X&&tl?.cwd===X?tl.values:{},tc=(0,i.useRef)(null),tu=(0,i.useRef)(null),tp=(0,i.useRef)(null),th=(0,i.useRef)(null),tm=(0,i.useRef)(null),tf=(0,i.useRef)(null),tg=(0,i.useRef)(null),tx=(0,i.useRef)(null),tv=(0,i.useRef)(null),tb=(0,i.useRef)(null),ty=(0,i.useRef)(null),tw=(0,i.useRef)(!1),tk=(0,i.useRef)(0),tj=(0,i.useRef)(!1),tS=(0,i.useRef)([]),tC=(0,i.useRef)([]),tN=(0,i.useRef)([]),tI=(0,i.useRef)(null),tT=(0,i.useRef)(null),tM=(0,i.useRef)(Z),t$=(0,i.useRef)(ex),tR=(0,i.useRef)(e_),tE=(0,i.useRef)(0),tL=(0,i.useRef)(eO);t$.current=ex,tR.current=e_,tL.current=eO,(0,i.useImperativeHandle)(en,()=>({insertIfEmpty(e){let t=tc.current;(t?t.value:ex).trim()||(t$.current=e,ev(e),e2(null),requestAnimationFrame(()=>{t&&(t.focus(),t.style.height="auto",t.style.height=`${Math.min(t.scrollHeight,200)}px`)}))},replaceMessage(e){let t,n,r=tc.current;if(!function(e,t,n,r=0){return!e.trim()&&0===t&&0===n&&0===r}(r?r.value:ex,tR.current.length,tE.current,tL.current.length))return;let i=(t="string"==typeof e.content?e.content:e.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n"),rx(t)?.message??t),a=sk("string"==typeof e.content?[]:e.content.flatMap(e=>{if("image"!==e.type)return[];let t=e.source?.type==="base64"?e.source.data:e.data,n=e.source?.type==="base64"?e.source.media_type:e.mimeType;if("string"!=typeof t||"string"!=typeof n)return[];let r={data:t,mimeType:n};return ap(r)?[r]:[]})),s=sC((n="string"==typeof e.content?e.content:e.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n"),rx(n)?.documents??[]));t$.current=i,tR.current=a,tL.current=s,ev(i),e2(null),e7(!1),eD(e=>(e.forEach(sR),a)),eH(s),requestAnimationFrame(()=>{r&&(r.focus(),r.style.height="auto",r.style.height=`${Math.min(r.scrollHeight,200)}px`)})},rekeyDraft(e,t){if(e===t)return;if(tM.current!==e)return void aW(e,t);let n={value:t$.current,images:tR.current.map(sy),documents:tL.current.filter(e=>"ready"===e.status).map(sN)},r=aW(e,t,n)??{value:"",images:[],documents:[]},i=r.value===n.value&&r.images.length===n.images.length&&r.images.every((e,t)=>e.data===n.images[t]?.data&&e.mimeType===n.images[t]?.mimeType)&&r.documents.length===n.documents.length&&r.documents.every((e,t)=>e.name===n.documents[t]?.name&&e.mimeType===n.documents[t]?.mimeType&&e.size===n.documents[t]?.size&&e.text===n.documents[t]?.text&&e.attachmentId===n.documents[t]?.attachmentId);if(tM.current=t,i)return;let a=sk(r.images),s=sI(sC(r.documents),tL.current),l=r.value;t$.current=l,tR.current=a,tL.current=s,ev(l),eD(e=>(e.forEach(sR),a)),eH(s),e2(null),e7(!1)},restoreSubmission(e,t,n,r){if(!e.trim()&&!t?.length&&!n?.length)return;let i=tM.current,a=r??i,s=a===i,l=!s&&a?aL(a):null,o=aP(e,t,s?t$.current:l?.value??"",s?tR.current.map(sy):l?.images??[],n,s?tL.current.filter(e=>"ready"===e.status).map(sN):l?.documents??[]);if(a&&aA(a,o),!s)return;let d=t?.length?[...sk(t).slice(0,Math.max(0,10-tR.current.length)),...tR.current].slice(0,10):tR.current,c=sI(sC(o.documents),tL.current);t$.current=o.value,tR.current=d,tL.current=c,ev(o.value),e2(null),e7(!1),t?.length&&eD(e=>{let n=Math.max(0,10-e.length),r=sk(t).slice(0,n),i=r.length>0?[...r,...e]:e;return tR.current=i,i}),eH(c),requestAnimationFrame(()=>{let e=tc.current;e&&(e.focus(),e.setSelectionRange(e.value.length,e.value.length),e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)})},insertText(e){let t=tc.current;if(!t)return void ev(t=>t+(t?" ":"")+e);let n=t.selectionStart??t.value.length,r=t.selectionEnd??t.value.length,i=t.value.slice(0,n),a=t.value.slice(r),s=i.length>0&&!i.endsWith(" ")?" ":"",l=i+s+e+a;t$.current=l,ev(l),e2(null),requestAnimationFrame(()=>{if(!t)return;let r=n+s.length+e.length;t.setSelectionRange(r,r),t.focus(),t.style.height="auto",t.style.height=`${Math.min(t.scrollHeight,200)}px`})},addAttachments(e){tG(e)}}));let tA=(0,i.useCallback)(async e=>{let t=Math.max(0,10-tR.current.length-tE.current),n=e.filter(e=>e.size>0xa00000);n.length>0&&eU(eh("chat.attachImageTooLarge",{name:n.map(e=>e.name).join(", "),limit:rv(0xa00000)}));let r=e.filter(e=>e.size<=0xa00000),i=r.slice(0,t);if(i.length<r.length&&eU(eh("chat.attachImageLimit",{count:10})),i.length){tE.current+=i.length;try{let e=await Promise.all(i.map(e=>new Promise((t,n)=>{let r=new FileReader;r.onload=()=>{let n=r.result.split(",")[1];t({data:n,mimeType:e.type,previewUrl:URL.createObjectURL(e)})},r.onerror=n,r.readAsDataURL(e)})));eD(t=>{let n=e.slice(0,Math.max(0,10-t.length));e.slice(n.length).forEach(sR);let r=[...t,...n];return tR.current=r,r})}finally{tE.current-=i.length}}},[eh]),tz=(0,i.useCallback)(async e=>{for(let t of e){let e=rc(t);if(!e)continue;if(tL.current.length>=3){eU(eh("chat.attachLimit",{count:3}));continue}if(t.size>8388608){eU(eh("chat.attachTooLarge",{name:t.name,limit:rv(8388608)}));continue}if(tL.current.reduce((e,t)=>e+t.size,0)+t.size>0x1000000){eU(eh("chat.attachTotalTooLarge",{limit:rv(0x1000000)}));continue}let n={id:++sl,name:t.name,mimeType:rl[e],size:t.size,text:"",status:"extracting"},r=[...tL.current,n];tL.current=r,eH(r);try{let e=await rf(t);if(tL.current.reduce((e,t)=>e+(t.id===n.id?0:t.text.length),0)+e.text.length>24e4)throw new rs("text_too_large","Total extracted text exceeds 240000 characters");let r=tL.current.map(t=>t.id===n.id?{...e,id:t.id,status:"ready"}:t);tL.current=r,eH(r)}catch(i){let e=tL.current.some(e=>e.id===n.id),r=tL.current.filter(e=>e.id!==n.id);if(tL.current=r,eH(r),!e)continue;i instanceof rs?"text_too_large"===i.code?eU(eh("chat.attachTextTooLarge",{name:t.name,limit:12e4.toLocaleString()})):"too_many_pages"===i.code?eU(eh("chat.attachTooManyPages",{name:t.name,limit:250})):"no_extractable_text"===i.code?eU(eh("chat.attachNoPdfText",{name:t.name})):"password_protected"===i.code?eU(eh("chat.attachPasswordProtected",{name:t.name})):eU(eh("chat.attachExtractFailed",{name:t.name})):eU(eh("chat.attachExtractFailed",{name:t.name}))}}},[eh]),tP=(0,i.useCallback)((e,t)=>{if(!tL.current.some(t=>t.id===e))return!1;let n=t?tL.current.map(n=>n.id===e?t:n):tL.current.filter(t=>t.id!==e);return tL.current=n,eH(n),!0},[]),tW=(0,i.useCallback)((e,t)=>{if(!tL.current.some(t=>t.attachmentId===e))return!1;let n=tL.current.map(n=>n.attachmentId===e?t(n):n);return tL.current=n,eH(n),!0},[]),tF=(0,i.useCallback)((e,t,n)=>{if(!e||e===tM.current)return;let r=aL(e);r?.documents.some(e=>e.attachmentId===t)&&aA(e,{...r,documents:sC(r.documents).map(e=>e.attachmentId===t?n(e):e).map(sN)})},[]),t_=(0,i.useRef)(new Map),tD=(0,i.useRef)(new Map),tO=(0,i.useRef)(new Set),tH=(0,i.useCallback)((e,t,n)=>{if(!e.storedInfo)return null;let r=Math.min(12e4,24e4-n.reduce((t,n)=>t+(n.attachmentId===e.attachmentId?0:n.text.length),0)),i=rk({...e.storedInfo,transcript:t},r);return i.length>r?null:{...e,text:i,size:new TextEncoder().encode(i).byteLength,transcription:void 0}},[]),tB=(0,i.useCallback)(e=>e instanceof sT&&"media_tool_unavailable"===e.code?eh("chat.transcribeToolMissing"):e instanceof sT&&"transcription_failed"===e.code&&null!==e.completedParts&&null!==e.parts?eh("chat.transcribePartialFailed",{done:e.completedParts,total:e.parts}):e instanceof Error?e.message:String(e),[eh]),tU=(0,i.useCallback)(async(e,t)=>{let n=tM.current,r=tL.current.find(t=>t.attachmentId===e);if(!r?.storedInfo)return;let i=r.transcription?.state==="confirm"?r.transcription.plan:null;tD.current.get(e)?.abort();let a=new AbortController;tD.current.set(e,a),tW(e,e=>({...e,transcription:{state:"running",plan:i}}));try{let r=await s$(await fetch(`/api/attachments/${encodeURIComponent(e)}/transcription`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t?{confirmed:!0}:{}),signal:a.signal}));if("string"!=typeof r.transcript)throw new sT("Invalid transcription result",null,null,null);let i=r.transcript;tW(e,e=>tH(e,i,tL.current)??{...e,transcription:{state:"failed",error:eh("chat.transcribeTooLong")}})||tF(n,e,e=>tH(e,i,[])??e)}catch(n){if(a.signal.aborted)return void tW(e,e=>({...e,transcription:{state:"skipped"}}));if(n instanceof sT&&"confirmation_required"===n.code)return void tq.current?.(e);let t=tB(n);tW(e,e=>({...e,transcription:{state:"failed",error:t}}))}finally{tD.current.get(e)===a&&tD.current.delete(e)}},[eh,tB,tW,tF,tH]),tq=(0,i.useRef)(null),tK=(0,i.useCallback)(async e=>{let t;tD.current.get(e)?.abort();let n=new AbortController;tD.current.set(e,n),tW(e,e=>({...e,transcription:{state:"planning"}}));try{t=function(e){if("boolean"!=typeof e.requiresConfirmation||"number"!=typeof e.estimatedCalls||"string"!=typeof e.notice||null!==e.durationSeconds&&"number"!=typeof e.durationSeconds||"direct"!==e.processing&&"compress-and-split"!==e.processing)throw new sT("Invalid transcription plan",null,null,null);return{durationSeconds:e.durationSeconds,estimatedCalls:e.estimatedCalls,requiresConfirmation:e.requiresConfirmation,processing:e.processing,notice:e.notice}}(await s$(await fetch(`/api/attachments/${encodeURIComponent(e)}/transcription`,{cache:"no-store",signal:n.signal})))}catch(t){if(n.signal.aborted)tW(e,e=>({...e,transcription:{state:"skipped"}}));else{let n=tB(t);tW(e,e=>({...e,transcription:{state:"failed",error:n}}))}return}finally{tD.current.get(e)===n&&tD.current.delete(e)}t.requiresConfirmation?tW(e,e=>({...e,transcription:{state:"confirm",plan:t}})):await tU(e,!1)},[tU,tB,tW]);tq.current=tK;let tV=(0,i.useCallback)(e=>{let t=tD.current.get(e);t?t.abort():tW(e,e=>({...e,transcription:{state:"skipped"}}))},[tW]),tJ=(0,i.useCallback)(async(e,t)=>{let n=null;for(let r of e){if(tL.current.length>=3){eU(eh("chat.attachLimit",{count:3}));continue}let e="file"===t&&r.size<=8388608,i={id:++sl,name:r.name,mimeType:"text/plain",size:e?r.size:0,text:"",status:e?"extracting":"uploading",sourceSize:r.size},a=[...tL.current,i];tL.current=a,eH(a);let s=(e,t)=>{let n=tL.current.filter(e=>e.id!==i.id);return e<=12e4&&n.reduce((e,t)=>e+t.text.length,0)+e<=24e4&&n.reduce((e,t)=>e+t.size,0)+t<=0x1000000};if(e){let e=await r.arrayBuffer().then(e=>{var t;return 255===(t=new Uint8Array(e))[0]&&254===t[1]?rh("utf-16le",t.subarray(2)):254===t[0]&&255===t[1]?rh("utf-16be",t.subarray(2)):t.includes(0)?null:rh("utf-8",t)??rh("euc-kr",t)},()=>null);if(null!==e&&s(e.length,r.size)){tP(i.id,{...i,text:e,status:"ready"});continue}}if(null===n&&(n=1048576*(await aX().catch(()=>aG)).uploadLimitMb),r.size>n){tP(i.id,null)&&eU(eh("chat.attachStoredTooLarge",{name:r.name,limit:rv(n)}));continue}let l={...i,stored:t,status:"uploading",size:0};if(!tP(i.id,l))continue;let o=tM.current??sM,d=await aO(o),c=null,u=new AbortController;t_.current.set(i.id,u);try{if(tO.current.has(i.id))continue;let e=await rj(r,{sessionId:Q,draftId:d.draftId,signal:u.signal}),n=tL.current.filter(e=>e.id!==i.id).reduce((e,t)=>e+t.text.length,0),a=rk({path:e.path,size:e.size,mimeType:e.mimeType},Math.min(12e4,24e4-n)),p=new TextEncoder().encode(a).byteLength;if(!s(a.length,p)){tP(i.id,null)&&eU(eh("chat.attachTotalTooLarge",{limit:rv(0x1000000)}));continue}let h={...l,attachmentId:e.id,text:a,size:p,status:"ready",storedInfo:{path:e.path,size:e.size,mimeType:e.mimeType},..."audio"===t?{transcription:{state:"planning"}}:{}};if(tP(i.id,h))c=e.id;else if(!tO.current.has(i.id)&&o!==tM.current){let t=aL(o)??{value:"",images:[],documents:[]};aA(o,{...t,documents:[...t.documents,sN(h)]}),c=e.id}}catch(e){if(u.signal.aborted)continue;tP(i.id,null)&&eU(eh("chat.attachUploadFailed",{name:r.name,error:e instanceof Error?e.message:String(e)}))}finally{t_.current.delete(i.id),d.end(c)}c&&"audio"===t&&tL.current.some(e=>e.attachmentId===c)&&tK(c)}},[tP,tK,Q,eh]),tG=(0,i.useCallback)(async e=>{eU(null);let{images:t,documents:n,audio:r,files:i}=function(e){let t=[],n=[],r=[],i=[];for(let a of e)a.type.startsWith("image/")?t.push(a):null!==rc(a)?n.push(a):rp(a)?r.push(a):i.push(a);return{images:t,documents:n,audio:r,files:i}}(e),a=n.filter(e=>e.size>8388608);await Promise.all([tA(t),tz(n.filter(e=>e.size<=8388608)),tJ(r,"audio"),tJ([...i,...a],"file")])},[tz,tJ,tA]),tY=(0,i.useCallback)(e=>{eD(t=>{let n=[...t],[r]=n.splice(e,1);return r&&sR(r),tR.current=n,n})},[]),tZ=(0,i.useCallback)(e=>{let t=tL.current.find(t=>t.id===e);if(tO.current.add(e),t_.current.get(e)?.abort(),t?.attachmentId){tD.current.get(t.attachmentId)?.abort();var n=t.attachmentId;for(let[e,t]of ak)t.delete(n)&&(0===t.size&&ak.delete(e),aV())}let r=tL.current.filter(t=>t.id!==e);tL.current=r,eH(r)},[]),tX=(0,i.useCallback)(()=>{tR.current=[],eD(e=>(e.forEach(sR),[]))},[]),tQ=(0,i.useCallback)(()=>{tL.current=[],eH([])},[]),t0=(0,i.useCallback)(()=>{t$.current="",ev(""),e2(null),e7(!1),Z&&az(Z),tM.current&&tM.current!==Z&&az(tM.current),tX(),tQ(),eU(null),tc.current&&(tc.current.style.height="auto")},[tQ,tX,Z]);(0,i.useEffect)(()=>{Z&&tM.current===Z&&aA(Z,{value:ex,images:e_.map(sy),documents:eq.map(sN)})},[e_,Z,eq,ex]),(0,i.useEffect)(()=>{let e=tM.current;if(e===Z)return;e&&aA(e,{value:t$.current,images:tR.current.map(sy),documents:tL.current.filter(e=>"ready"===e.status).map(sN)});let t=Z?aL(Z):null;tM.current=Z;let n=t?.value??"",r=sk(t?.images),i=sC(t?.documents);t$.current=n,tR.current=r,tL.current=i,ev(n),e2(null),e7(!1),eD(e=>(e.forEach(sR),r)),eH(i)},[Z]),(0,i.useEffect)(()=>{let e=tc.current;e&&(e.style.height="auto",ex&&(e.style.height=`${Math.min(e.scrollHeight,200)}px`))},[ex]),(0,i.useEffect)(()=>()=>{tR.current.forEach(sR)},[]);let t2=(0,i.useCallback)((e,t)=>{let n=function(e,t){let n=aF(t);if(0===n.length)return()=>{};let r=++ay;return ab.set(r,{draftId:a_(e),ids:n}),e=>{if("accepted"!==e&&"returned"!==e)return;let t=ab.get(r);if(t){if(ab.delete(r),"accepted"===e){let e=aj.get(t.draftId)??new Set;for(let n of t.ids)e.add(n);aj.set(t.draftId,e)}aV()}}}(tM.current??sM,e);Promise.resolve(t()).then(e=>n("accepted"===e||"returned"===e?e:void 0),()=>void 0)},[]),t4=(0,i.useCallback)(async()=>{let t=ex.trim(),n=eJ.trim(),r=n.startsWith("/")||n.startsWith("!")?n:t;if(!r&&!e_.length&&!eq.length||l||eK)return;G?.();let i=e_.length?e_:void 0,a=eq.length?eq:void 0;if(r.startsWith("/")){await a9(r,B,K,t=>t2(a,()=>e(t,i,a)),eU,!!(i||a),q)&&t0();return}t0(),t2(a,()=>e(r,i,a))},[ex,eJ,e_,eq,eK,l,K,B,q,e,t0,G,t2]),t5=eJ.startsWith("/")&&!/\s/.test(eJ.slice(1))?eJ.slice(1).toLowerCase():null,t6=(()=>{if(null===t5)return[];let e=[...l?[]:sh,...B??[]],t=new Set;return[...e].filter(e=>{let t=e.name.toLowerCase(),n=sv(e,eh).toLowerCase();return t.includes(t5)||n.includes(t5)}).sort((e,t)=>{let n=sx(e,t5,eh)-sx(t,t5,eh);return 0!==n?n:sg[e.source]-sg[t.source]||ss.compare(e.name,t.name)}).filter(e=>{let n=e.name.toLowerCase();return!t.has(n)&&(t.add(n),!0)})})(),{commands:t8,groups:t3}=(er=0,{commands:(ei=sm.map(e=>{let t=t6.filter(t=>t.source===e),n="skill"===e?[...t.filter(e=>!sb(e,td)),...t.filter(e=>sb(e,td))]:t;return{source:e,items:n.map(e=>({command:e,index:er++}))}}).filter(e=>e.items.length>0)).flatMap(e=>e.items.map(({command:e})=>e)),groups:ei}),t7=1===t6.length?eh(t5?"chat.match":"chat.command"):eh(t5?"chat.matches":"chat.commands",{count:t6.length}),t9=!!ex.trim(),ne=!eK&&(t9||e_.length>0||eq.length>0),nn=(0,i.useCallback)((e,t)=>{if(!X)return void e2(null);let n=t??e.length;e2(a0(e.slice(0,n)))},[X]),nr=e1?.query??null,ni=i.useMemo(()=>null!==nr&&tt&&tt.cwd===X?function(e,t,n=20){let r=t.toLowerCase();if(!r)return e.slice(0,n);let i=[];for(let t of e){let e=function(e,t){let n=e.path.toLowerCase(),r=0;if(t.includes("/"))n===t?r=100:n.startsWith(t)?r=80:n.includes(t)?r=50:a2(t,n)&&(r=10);else{let e=n.lastIndexOf("/"),i=-1===e?n:n.slice(e+1);i===t?r=100:i.startsWith(t)?r=80:i.includes(t)?r=50:n.includes(t)?r=30:a2(t,n)&&(r=10)}return e.isDir&&r>0&&(r+=10),r}(t,r);e>0&&i.push({entry:t,score:e})}return i.sort((e,t)=>t.score-e.score||a1(e.entry.path)-a1(t.entry.path)||e.entry.path.localeCompare(t.entry.path)),i.slice(0,n).map(e=>e.entry)}(tt.entries,nr):[],[nr,tt,X]),na=!!(nr&&tt?.truncated&&tt.cwd===X);(0,i.useEffect)(()=>{if(!na||!X||!nr)return;let e=setTimeout(()=>{fetch(`/api/file-index?cwd=${encodeURIComponent(X)}&q=${encodeURIComponent(nr)}`).then(e=>{if(!e.ok)throw Error(`file search failed: ${e.status}`);return e.json()}).then(e=>ts({cwd:X,query:nr,matches:e.matches??[]})).catch(()=>{})},150);return()=>clearTimeout(e)},[na,nr,X]);let ns=na&&null!==ta&&ta.cwd===X&&ta.query===nr,nl=ns?ta.matches:ni,no=null===e1?null:`${e1.start}:${+!!e1.quoted}:${e1.query}`;(0,i.useEffect)(()=>{if(null===no){e5(!1),e8(0);return}e5(!0),e8(0)},[no]);let nd=null!==e1,nc=a3(tb,e3,{viewportFraction:.44,cap:360}),nu=a3(tb,eZ,{viewportFraction:.56,cap:460}),np=a3(tb,e4,{viewportFraction:.48,cap:400});(0,i.useEffect)(()=>{if(!nd||!X)return;let e=tI.current;e&&e.cwd===X&&Date.now()-e.fetchedAt<1e4||tT.current===X||(tT.current=X,ti(!0),fetch(`/api/file-index?cwd=${encodeURIComponent(X)}`).then(e=>{if(!e.ok)throw Error(`file index failed: ${e.status}`);return e.json()}).then(e=>{tn({cwd:X,entries:function(e){let t=new Set;for(let n of e){let e=n.indexOf("/");for(;-1!==e;)t.add(n.slice(0,e)),e=n.indexOf("/",e+1)}let n=[];for(let e of t)n.push({path:e,isDir:!0});for(let t of e)t&&n.push({path:t,isDir:!1});return n.sort((e,t)=>a1(e.path)-a1(t.path)||e.path.localeCompare(t.path)),n}(e.files??[]),truncated:!!e.truncated}),tI.current={cwd:X,fetchedAt:Date.now()}}).catch(()=>{tI.current=null}).finally(()=>{tT.current=null,ti(!1)}))},[nd,X]);let nh=(0,i.useCallback)(e=>{if(!e1)return;let t=tc.current,n=t?.selectionStart??ex.length,r=ex.slice(0,e1.start),i=ex.slice(n);e1.quoted&&i.startsWith('"')&&(i=i.slice(1));let a=function(e,t,n=!1){let r=t?`${e}/`:e,i=n||r.includes(" ");if(t){let e=i?`@"${r}"`:`@${r}`;return{text:e,cursorOffset:i?e.length-1:e.length}}let a=i?`@"${r}" `:`@${r} `;return{text:a,cursorOffset:a.length}}(e.path,e.isDir,e1.quoted),s=r+a.text+i,l=r.length+a.cursorOffset;ev(s),e2(a0(s.slice(0,l))),requestAnimationFrame(()=>{let e=tc.current;e&&(e.focus(),e.setSelectionRange(l,l),e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)})},[e1,ex]);(0,i.useEffect)(()=>{e6>=nl.length&&e8(Math.max(0,nl.length-1))},[nl.length,e6]),(0,i.useEffect)(()=>{tC.current.length=nl.length},[nl.length]),(0,i.useEffect)(()=>{e4&&tC.current[e6]?.scrollIntoView({block:"nearest",inline:"nearest"})},[e6,e4]),(0,i.useEffect)(()=>{e9>=D.length&&te(Math.max(0,D.length-1))},[D.length,e9]),(0,i.useEffect)(()=>{tN.current.length=D.length},[D.length]),(0,i.useEffect)(()=>{e3&&tN.current[e9]?.scrollIntoView({block:"nearest",inline:"nearest"})},[e9,e3]);let nm=(0,i.useCallback)(e=>{t$.current=e,ev(e),e7(!1),te(0),e2(null),requestAnimationFrame(()=>{let t=tc.current;t&&(t.focus(),t.setSelectionRange(e.length,e.length),t.style.height="auto",t.style.height=`${Math.min(t.scrollHeight,200)}px`)})},[]),nf=(0,i.useCallback)(e=>{let t=`/${e.name} `;t$.current=t,ev(t),eX(!1),e0(0),requestAnimationFrame(()=>{let e=tc.current;e&&(e.focus(),e.setSelectionRange(t.length,t.length),e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)})},[]),nx=(0,i.useCallback)(async e=>{let t=ex.trim(),r=eJ.trim(),i=r.startsWith("/")||r.startsWith("!")?r:t,s=eK||!i&&0===e_.length&&0===eq.length?null:{message:i,images:e_.length?e_:void 0,documents:eq.length?eq:void 0};if(!s)return;G?.();let l="steer"===e?"steer":"followUp";if(i.startsWith("/")){await a9(i,B,K,e=>{if(!Y)throw Error("Cannot queue this command while the session is busy.");t2(s.documents,()=>Y(e,l,s.images,s.documents))},eU,!!(s.images?.length||s.documents?.length),q)&&t0();return}t0(),"steer"===e&&n?t2(s.documents,()=>n(s.message,s.images,s.documents)):"followup"===e&&a&&t2(s.documents,()=>a(s.message,s.images,s.documents))},[ex,eJ,e_,eq,eK,B,q,K,Y,n,a,t0,G,t2]),nv=(0,i.useCallback)(e=>{let t=t8.length-1;if(t<0)return 0;if("left"===e)return Math.max(0,eQ-1);if("right"===e)return Math.min(t,eQ+1);let n=tS.current[eQ];if(!n)return"down"===e?Math.min(t,eQ+1):Math.max(0,eQ-1);let r=n.getBoundingClientRect(),i=r.left+r.width/2,a=r.top+r.height/2,s=-1,l=1/0;for(let n=0;n<=t;n+=1){if(n===eQ)continue;let t=tS.current[n];if(!t)continue;let r=t.getBoundingClientRect(),o=r.top+r.height/2-a;if("down"===e?o<=4:o>=-4)continue;let d=1e3*Math.abs(o)+Math.abs(r.left+r.width/2-i);d<l&&(s=n,l=d)}return s>=0?s:"down"===e?Math.min(t,eQ+1):Math.max(0,eQ-1)},[t8.length,eQ]),nb=(0,i.useCallback)(e=>{let r=e.nativeEvent,i=Date.now()-tk.current<100,s=tw.current||r.isComposing||229===r.keyCode;if("Enter"===e.key&&!e.shiftKey&&(s||i)){i&&e.preventDefault();return}if(e3&&!s){if("ArrowDown"===e.key){e.preventDefault(),te(e=>Math.min(Math.max(0,D.length-1),e+1));return}if("ArrowUp"===e.key){e.preventDefault(),te(e=>Math.max(0,e-1));return}if("Escape"===e.key){e.preventDefault(),e7(!1);return}if(("Tab"===e.key||"Enter"===e.key&&!e.shiftKey)&&D[e9]){e.preventDefault(),nm(D[e9]);return}}if(eZ&&null!==t5){if("ArrowDown"===e.key){e.preventDefault(),e0(nv("down"));return}if("ArrowUp"===e.key){e.preventDefault(),e0(nv("up"));return}if("ArrowRight"===e.key){e.preventDefault(),e0(nv("right"));return}if("ArrowLeft"===e.key){e.preventDefault(),e0(nv("left"));return}if("Escape"===e.key){e.preventDefault(),eX(!1);return}if(("Tab"===e.key||"Enter"===e.key&&!e.shiftKey)&&t8[eQ]){e.preventDefault(),nf(t8[eQ]);return}}if(e4&&null!==e1&&!s){if("ArrowDown"===e.key){e.preventDefault(),e8(e=>Math.min(Math.max(0,nl.length-1),e+1));return}if("ArrowUp"===e.key){e.preventDefault(),e8(e=>Math.max(0,e-1));return}if("Escape"===e.key){e.preventDefault(),e5(!1);return}if(("Tab"===e.key||"Enter"===e.key&&!e.shiftKey)&&nl[e6]){e.preventDefault(),nh(nl[e6]);return}}if("ArrowUp"===e.key&&!s&&!l&&D.length>0&&0===ex.trim().length){e.preventDefault(),eX(!1),e5(!1),te(D.length-1),e7(!0);return}if("Escape"===e.key&&!s&&l&&t){e.preventDefault(),t();return}"Enter"!==e.key||e.shiftKey||(e.preventDefault(),l&&(n||a)?nx(n?"steer":"followup"):t4())},[l,n,a,t,eZ,t5,t8,eQ,nf,nx,t4,nv,e4,e1,nl,e6,nh,e3,D,e9,nm,ex]),ny=(0,i.useCallback)(()=>{let e=tc.current;e&&(e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)},[]),nw=(0,i.useCallback)(e=>{let t=function(e){let t=Array.from(e.files??[]);if(t.length>0)return t;let n=[];for(let t of Array.from(e.items??[])){if("file"!==t.kind)continue;let e=t.getAsFile();e&&n.push(e)}return n}(e.clipboardData);t.length&&(e.preventDefault(),tG(t))},[tG]);(0,i.useEffect)(()=>{if(null===t5){eX(!1),e0(0),tj.current=!1;return}eX(!0),e0(0),!tj.current&&q&&(tj.current=!0,Promise.resolve(q()).catch(()=>{tj.current=!1}))},[t5,q]),(0,i.useEffect)(()=>{if(!eZ||!X)return;let e=!1;return to({cwd:X,values:{}}),fetch(`/api/skills?cwd=${encodeURIComponent(X)}`).then(e=>{if(!e.ok)throw Error(`skills fetch failed: ${e.status}`);return e.json()}).then(t=>{if(e)return;let n={};for(let e of t.skills??[])n[e.name]=e.disableModelInvocation;to({cwd:X,values:n})}).catch(()=>{e||to({cwd:X,values:{}})}),()=>{e=!0}},[eZ,X]),(0,i.useEffect)(()=>{eQ>=t8.length&&e0(Math.max(0,t8.length-1))},[t8.length,eQ]),(0,i.useEffect)(()=>{tS.current.length=t8.length},[t8.length]),(0,i.useEffect)(()=>{eZ&&tS.current[eQ]?.scrollIntoView({block:"nearest",inline:"nearest"})},[eQ,eZ]);let nk=u&&u.length>0?u.map(e=>({provider:e.provider,modelId:e.id,name:e.name})).sort(sd):Object.entries(c??{}).map(([e,t])=>({provider:o?.provider??"unknown",modelId:e,name:t})).sort(sd),nj=g??null,nC=nt.bo.find(e=>e.alias===nj)?.provider??null,nN=nC?nk.filter(e=>e.provider===nC):nk,nT=(ea=ej.trim().toLocaleLowerCase())?nN.filter(e=>`${e.name} ${e.modelId}`.toLocaleLowerCase().includes(ea)):nN,nM=nN.length>8,n$=[];for(let e of nT){let t=n$.find(t=>t.provider===e.provider);t?t.options.push(e):n$.push({provider:e.provider,options:[e]})}let nR=nC?[]:(x??[]).filter(e=>!e.hidden&&e.resolved),nE=o?nR.find(e=>e.resolved?.provider===o.provider&&e.resolved?.modelId===o.modelId):void 0,nL=ej.trim()?[]:nN.map((e,t)=>{var n,r;return{option:e,order:t,count:eC[n=e.provider,r=e.modelId,`${n}/${r}`]??0}}).filter(e=>e.count>=2).sort((e,t)=>t.count-e.count||e.order-t.order).slice(0,5).map(({option:e,count:t})=>({option:e,count:t})),nA=(e,t,n)=>{let i=e.modelId===o?.modelId&&e.provider===o?.provider;return(0,r.jsxs)("button",{onClick:()=>{if(ey(!1),eS(""),!i||d){var t,n;let r=function(e,t){let n={...e,[t]:(e[t]??0)+1},r=Object.keys(n);if(r.length<=30)return n;for(let e of(r.sort((e,t)=>n[e]-n[t]),r)){if(Object.keys(n).length<=30)break;e!==t&&delete n[e]}return n}(a5(),(t=e.provider,n=e.modelId,`${t}/${n}`));try{window.localStorage.setItem(a4,JSON.stringify(r))}catch{}eN(r),m?.(e.provider,e.modelId)}},style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",background:i?"var(--bg-selected)":"none",border:"none",color:i?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left",fontWeight:i?600:400,whiteSpace:"nowrap"},onMouseEnter:e=>{i||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{i||(e.currentTarget.style.background="none")},children:[i?(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,r.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,r.jsx)("span",{style:{width:10,flexShrink:0}}),e.name,void 0!==n&&n>=2&&(0,r.jsx)("span",{style:{marginLeft:"auto",paddingLeft:12,color:"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:10.5},children:eh("chat.modelPickCount",{count:n})})]},`${t}:${e.provider}:${e.modelId}`)},nz=o?nk.find(e=>e.modelId===o.modelId&&e.provider===o.provider)?.name??o.modelId:null,nP=S?Math.max(0,S.tokensBefore-S.estimatedTokensAfter):0,nW=S?`${S.reason&&"manual"!==S.reason?`${S.reason[0].toUpperCase()}${S.reason.slice(1)} `:eh("chat.compacted")} ${t1(S.tokensBefore)} -> ${t1(S.estimatedTokensAfter)} tokens (${eh("chat.tokensSaved",{saved:t1(nP)})})`:null,nF=e=>{let t=L?.[e];return null!=t&&t!==e?t:null},n_="auto"===(es=I??"auto")?M?`auto ≤ ${nF(M)??M}`:"auto":L?L[es]??es:es,nD=(I??"auto")==="auto"&&T&&"auto"!==T?L?.[T]??T:null,nO=$&&nD?eh("chat.currentReasoning",{level:nD}):null,nH=e=>!E||E.includes(e),nB=[{level:"auto",ceiling:null},...su.filter(nH).map(e=>({level:"auto",ceiling:e})),...sc.filter(e=>"auto"!==e&&nH(e)).map(e=>({level:e,ceiling:null}))],nU=Object.entries(sn).find(([,e])=>e===(C??"default"))?.[0]??"default";(0,i.useEffect)(()=>{let e=e=>{tu.current&&!tu.current.contains(e.target)&&tp.current&&!tp.current.contains(e.target)&&(ey(!1),eS("")),th.current&&!th.current.contains(e.target)&&tm.current&&!tm.current.contains(e.target)&&eT(!1),tf.current&&!tf.current.contains(e.target)&&eE(!1),tg.current&&!tg.current.contains(e.target)&&eA(!1),tx.current&&!tx.current.contains(e.target)&&eF(!1),!tv.current||tv.current.contains(e.target)||tc.current?.contains(e.target)||e7(!1)};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[]),(0,i.useEffect)(()=>{eg||eF(!1)},[eg]);let nq=(0,r.jsx)("button",{type:"button",className:`composer-icon-button${e_.length||eO.length?" is-active":""}`,onClick:()=>ty.current?.click(),title:eh("chat.attachFile"),"aria-label":eh("chat.attachFile"),style:{flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center",width:32,height:32,padding:0,background:"none",border:"none",borderRadius:"var(--radius-control)",color:e_.length||eO.length?"var(--accent)":"var(--text-muted)",cursor:"pointer",opacity:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color=e_.length||eO.length?"var(--accent)":"var(--text)"},onMouseLeave:e=>{e.currentTarget.style.background="none",e.currentTarget.style.color=e_.length||eO.length?"var(--accent)":"var(--text-muted)"},children:(0,r.jsxs)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2",ry:"2"}),(0,r.jsx)("circle",{cx:"8.5",cy:"8.5",r:"1.5"}),(0,r.jsx)("polyline",{points:"21 15 16 10 5 21"})]})}),nK=f&&nt.bo.length>0?(0,r.jsxs)("div",{ref:th,style:{position:"relative",flexShrink:+!!eg,minWidth:0},children:[(0,r.jsxs)("button",{className:`${eg?"composer-icon-button":"composer-chip"}${eI?" is-active":""}`,onClick:e=>{let t=e.currentTarget.getBoundingClientRect();e$({top:t.top,bottom:t.bottom,left:t.left,width:t.width}),ey(!1),eS(""),eT(e=>!e)},disabled:l||b,"aria-haspopup":"menu","aria-expanded":eI,onKeyDown:e=>{"Escape"===e.key&&eI&&(e.stopPropagation(),eT(!1))},style:{display:"flex",alignItems:"center",gap:6,maxWidth:"100%",padding:"4px 8px",background:eI?"var(--bg-hover)":"none",border:"none",borderRadius:"var(--radius-control)",color:"var(--text-muted)",cursor:l||b?"not-allowed":"pointer",fontSize:12,opacity:l?.5:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{l||b||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{e.currentTarget.style.background=eI?"var(--bg-hover)":"none",e.currentTarget.style.color="var(--text-muted)"},title:eh("chat.mainPreset"),"aria-label":eh("chat.mainPreset"),children:[(0,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},"aria-hidden":"true",children:(0,r.jsx)("path",{d:"M12 3l2.2 5.1 5.6.5-4.2 3.7 1.2 5.5L12 15l-4.8 2.8 1.2-5.5L4.2 8.6l5.6-.5z"})}),eg?null:(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:eh("chat.mainPreset")})]}),eI&&eM&&(()=>{let e=window.visualViewport?.height??window.innerHeight,{side:t,maxHeight:n}=a6(eM.top,eM.bottom,e,a8(e,.6,460),{gap:6,prefer:"above"}),i="above"===t?{bottom:e-eM.top+6}:{top:eM.bottom+6},a=eg?{left:8,right:8,maxWidth:"calc(100vw - 16px)"}:{left:eM.left,width:"max-content",minWidth:eM.width};return(0,r.jsx)("div",{ref:tm,role:"menu","aria-label":eh("chat.mainPreset"),onKeyDown:e=>{"Escape"===e.key&&(eT(!1),th.current?.querySelector("button")?.focus())},style:{position:"fixed",...i,...a,zIndex:500,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s2)",overflow:"hidden",maxHeight:n,display:"flex",flexDirection:"column"},children:(0,r.jsx)("div",{style:{minHeight:0,overflowY:"auto"},children:nt.bo.map(e=>{let t=e.alias===nj;return(0,r.jsxs)("button",{role:"menuitemradio","aria-checked":t,onClick:()=>{eT(!1),f((0,nt.zq)(e))},title:`${e.provider}/${e.model}`,style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",background:t?"var(--bg-selected)":"none",border:"none",color:t?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left",fontWeight:t?600:400,whiteSpace:"nowrap"},onMouseEnter:e=>{t||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{t||(e.currentTarget.style.background="none")},children:[t?(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,r.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,r.jsx)("span",{style:{width:10,flexShrink:0}}),(0,r.jsx)("img",{className:"account-avatar",src:(0,nt.uk)(e.seed),width:20,height:20,alt:"","aria-hidden":"true",draggable:!1}),(0,r.jsx)("span",{children:e.alias}),(0,r.jsxs)("span",{style:{marginLeft:"auto",paddingLeft:12,color:"var(--text-dim)",fontSize:11,overflow:"hidden",textOverflow:"ellipsis"},children:[e.provider,"/",e.model,void 0!==e.oauthPosition?` \xb7 OAuth ${e.oauthPosition}`:""]})]},e.alias)})})})})()]}):null,nV=$?(0,r.jsxs)("div",{ref:tg,style:{position:"relative",flexShrink:0,minWidth:0},children:[(0,r.jsxs)("button",{type:"button",className:`${eg?"composer-icon-button":"composer-chip"}${eL?" is-active":""}`,onClick:e=>{let t=e.currentTarget.getBoundingClientRect();eP({top:t.top,bottom:t.bottom,left:t.left,width:t.width}),ey(!1),eS(""),eT(!1),eA(e=>!e)},disabled:l||b,"aria-haspopup":"menu","aria-expanded":eL,onKeyDown:e=>{"Escape"===e.key&&eL&&(e.stopPropagation(),eA(!1))},title:eh("chat.changeReasoning",{level:n_}),"aria-label":eh("chat.changeReasoning",{level:n_}),style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,padding:eg?0:"8px 12px",height:32,background:eL?"var(--bg-hover)":"none",border:"none",borderRadius:"var(--radius-control)",color:"var(--text-muted)",cursor:l||b?"not-allowed":"pointer",fontSize:12,opacity:l?.5:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{l||b||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{e.currentTarget.style.background=eL?"var(--bg-hover)":"none",e.currentTarget.style.color="var(--text-muted)"},children:[(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},"aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M9.5 2A5.5 5.5 0 0 0 4 7.5c0 1.7.78 3.21 2 4.21V14a1 1 0 0 0 1 1h5a1 1 0 0 0 1-1v-2.29c1.22-1 2-2.51 2-4.21A5.5 5.5 0 0 0 9.5 2z"}),(0,r.jsx)("line",{x1:"7",y1:"18",x2:"12",y2:"18"}),(0,r.jsx)("line",{x1:"8",y1:"21",x2:"11",y2:"21"})]}),eg?null:(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:n_})]}),eL&&ez&&(()=>{let e=window.visualViewport?.height??window.innerHeight,{side:t,maxHeight:n}=a6(ez.top,ez.bottom,e,a8(e,.6,460),{gap:6,prefer:"above"}),i="above"===t?{bottom:e-ez.top+6}:{top:ez.bottom+6},a=eg?{left:8,right:8,maxWidth:"calc(100vw - 16px)"}:{left:ez.left,width:"max-content",minWidth:Math.max(180,ez.width)};return(0,r.jsx)("div",{role:"menu","aria-label":eh("chat.changeReasoningLabel"),onKeyDown:e=>{"Escape"===e.key&&(eA(!1),tg.current?.querySelector("button")?.focus())},style:{position:"fixed",...i,...a,zIndex:500,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s2)",overflowY:"auto",maxHeight:n},children:nB.map(({level:e,ceiling:t})=>{let n=(I??"auto")===e&&("auto"!==e||(M??null)===t),i=t??e,a="auto"===e&&null===t?null:nF(i),s=t?`auto ≤ ${a??t}`:a??e,l=t?eh("chat.thinkingAutoCapped",{level:a??t}):eh(sp[e]);return(0,r.jsxs)("button",{type:"button",role:"menuitemradio","aria-checked":n,onClick:()=>{eA(!1),$(e,t)},style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",background:n?"var(--bg-selected)":"none",border:"none",color:n?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left",fontWeight:n?600:400,whiteSpace:"nowrap"},onMouseEnter:e=>{n||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{n||(e.currentTarget.style.background="none")},children:[n?(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,r.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,r.jsx)("span",{style:{width:10,flexShrink:0}}),(0,r.jsxs)("span",{style:{flex:1},children:[s,null!==a&&(0,r.jsxs)("span",{style:{fontSize:10,color:"var(--text-dim)",fontFamily:"var(--font-mono)",marginLeft:5},children:["(",i,")"]})]}),(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)",marginLeft:8},children:l})]},t?`auto-${t}`:e)})})})()]}):null,nJ=P?(el=z?eh("chat.fastModeBusy"):null===A?eh("chat.fastModeUnknown"):A.active?eh("chat.fastModeActive"):A.enabled?eh("chat.fastModeInactive"):eh("chat.fastModeOff"),eo=z||l||b,ed=A?.enabled===!0,(0,r.jsx)("button",{type:"button",className:`composer-icon-button${A?.active?" is-active":""}`,onClick:P,disabled:eo,"aria-pressed":null===A?void 0:A.enabled,"aria-busy":z||void 0,title:el,"aria-label":el,style:{flexShrink:0,opacity:l?.5:1},children:(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:A?.active?"var(--accent)":"none",stroke:ed?"var(--accent)":"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",strokeDasharray:null===A?"3 2":void 0,style:{opacity:ed&&!A?.active?.6:1},"aria-hidden":"true",children:(0,r.jsx)("path",{d:"M13 2 4 14h7l-1 8 9-12h-7l1-8z"})})})):null,nG=(0,r.jsxs)(r.Fragment,{children:[n&&(0,r.jsxs)("button",{className:"composer-stream-action is-warning",onClick:()=>nx("steer"),disabled:!ne,title:eK?eh("chat.attachExtractingWait"):eh("chat.steerTitle"),style:{display:"flex",alignItems:"center",gap:5,padding:"7px 12px",background:ne?"var(--warning-soft)":"none",border:"1px solid var(--warning-line)",borderRadius:"var(--radius-control)",color:ne?"var(--warning)":"var(--text-dim)",cursor:ne?"pointer":"not-allowed",fontSize:13,fontWeight:600,letterSpacing:"-0.01em",transition:"background 0.12s"},children:[(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("path",{d:"M5 1 L9 5 L5 9"}),(0,r.jsx)("line",{x1:"1",y1:"5",x2:"9",y2:"5"})]}),eh("chat.steer")]}),a&&(0,r.jsxs)("button",{className:"composer-stream-action is-followup",onClick:()=>nx("followup"),disabled:!ne,title:eK?eh("chat.attachExtractingWait"):eh("chat.followUpTitle"),style:{display:"flex",alignItems:"center",gap:5,padding:"7px 12px",background:ne?"var(--accent-soft)":"none",border:"1px solid var(--accent-line)",borderRadius:"var(--radius-control)",color:ne?"var(--accent-hover)":"var(--text-dim)",cursor:ne?"pointer":"not-allowed",fontSize:13,fontWeight:600,letterSpacing:"-0.01em",transition:"background 0.12s"},children:[(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("line",{x1:"5",y1:"1",x2:"5",y2:"6"}),(0,r.jsx)("polyline",{points:"2.5 3.5 5 1 7.5 3.5"}),(0,r.jsx)("line",{x1:"2",y1:"9",x2:"8",y2:"9"})]}),eh("chat.followUp")]})]}),nY=void 0!==J?(0,r.jsx)(at,{soundEnabled:V??!0,onToggle:J}):null;return(0,r.jsxs)("div",{className:"chat-composer",style:{flexShrink:0,background:"transparent",padding:"0 16px 8px"},children:[(0,r.jsx)("input",{ref:ty,type:"file",multiple:!0,style:{display:"none"},onChange:e=>{tG(Array.from(e.target.files??[])),e.target.value=""}}),(0,r.jsxs)("div",{className:"chat-column-cap",style:{maxWidth:820,margin:"0 auto"},children:[(0,r.jsx)(sL,{error:p}),(0,r.jsx)(sA,{warnings:h}),_.length>0&&(0,r.jsxs)("div",{style:{marginBottom:8,border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"var(--bg-panel)",padding:"5px 0"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,padding:"2px 8px 4px 10px"},children:[(0,r.jsx)("span",{style:{fontSize:10,fontFamily:"var(--font-mono)",color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:.4},children:em("delivery.title",{count:_.length})}),O&&ef&&(0,r.jsxs)("button",{onClick:O,title:eh("chat.recallTitle"),style:{display:"flex",alignItems:"center",gap:6,padding:"4px 12px",fontSize:12,color:"var(--text)",background:"transparent",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",cursor:"pointer",transition:"background 0.12s, border-color 0.12s",whiteSpace:"nowrap"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.borderColor="color-mix(in srgb, var(--accent) 45%, var(--border))"},onMouseLeave:e=>{e.currentTarget.style.background="transparent",e.currentTarget.style.borderColor="var(--border)"},children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("polyline",{points:"9 14 4 9 9 4"}),(0,r.jsx)("path",{d:"M20 20v-7a4 4 0 0 0-4-4H4"})]}),eh("chat.recall")]})]}),(0,r.jsx)(i7,{rows:_,removeLabel:eh("chat.queueRemove"),onRemove:H?(e,t)=>H("steer"===e?"steering":"followUp",t):void 0})]}),F&&(0,r.jsxs)("div",{style:{marginBottom:8,padding:"5px 10px",background:"var(--warning-soft)",border:"1px solid var(--warning-line)",borderRadius:"var(--radius-control)",fontSize:12,color:"var(--warning)",display:"flex",alignItems:"center",gap:6},children:[(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:[(0,r.jsx)("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}),(0,r.jsx)("path",{d:"M3 3v5h5"})]}),eh("chat.retrying",{attempt:F.attempt,max:F.maxAttempts}),F.errorMessage&&(0,r.jsxs)("span",{style:{opacity:.7,marginLeft:4},children:["— ",F.errorMessage]})]}),nW&&(0,r.jsxs)("div",{style:{marginBottom:8,padding:"5px 10px",background:"var(--success-soft)",border:"1px solid var(--success-line)",borderRadius:"var(--radius-control)",fontSize:12,color:"var(--success)",display:"flex",alignItems:"center",gap:6},children:[(0,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}),nW]}),j&&(0,r.jsx)("div",{role:"alert",style:{marginBottom:8,padding:"7px 10px",background:"var(--danger-soft)",border:"1px solid var(--danger-line)",borderRadius:"var(--radius-control)",color:"var(--danger)",fontFamily:"var(--font-mono)",fontSize:12,lineHeight:1.5,whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:j}),eB&&(0,r.jsxs)("div",{role:"alert",style:{display:"flex",alignItems:"center",gap:8,marginBottom:8,padding:"7px 10px",background:"var(--danger-soft)",border:"1px solid var(--danger-line)",borderRadius:"var(--radius-control)",color:"var(--danger)",fontSize:12,lineHeight:1.5},children:[(0,r.jsx)("span",{style:{flex:1,minWidth:0,overflowWrap:"anywhere"},children:eB}),(0,r.jsx)("button",{type:"button",onClick:()=>eU(null),"aria-label":eh("i18n.close"),title:eh("i18n.close"),style:{flexShrink:0,width:24,height:24,display:"flex",alignItems:"center",justifyContent:"center",padding:0,border:"none",background:"transparent",color:"inherit",cursor:"pointer"},children:(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"2",y1:"2",x2:"10",y2:"10"}),(0,r.jsx)("line",{x1:"10",y1:"2",x2:"2",y2:"10"})]})})]}),(e_.length>0||eO.length>0)&&(0,r.jsxs)("div",{role:"list","aria-label":eh("chat.attachments"),style:{display:"flex",alignItems:"center",gap:6,marginBottom:6,flexWrap:"wrap"},children:[e_.map((e,t)=>(0,r.jsxs)("div",{role:"listitem",style:{position:"relative",flexShrink:0},children:[(0,r.jsx)("img",{src:e.previewUrl,alt:"",style:{width:56,height:56,objectFit:"cover",borderRadius:"var(--radius-control)",border:"1px solid var(--border)",display:"block"}}),(0,r.jsx)("button",{type:"button","aria-label":eh("chat.removeImage",{index:t+1}),onClick:()=>tY(t),style:{position:"absolute",top:-4,right:-4,width:16,height:16,borderRadius:"50%",background:"var(--bg-panel)",border:"1px solid var(--border)",display:"flex",alignItems:"center",justifyContent:"center",cursor:"pointer",padding:0,color:"var(--text-muted)"},children:(0,r.jsxs)("svg",{width:"8",height:"8",viewBox:"0 0 8 8",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"1",y1:"1",x2:"7",y2:"7"}),(0,r.jsx)("line",{x1:"7",y1:"1",x2:"1",y2:"7"})]})})]},`image-${t}`)),eO.map(e=>(0,r.jsxs)("div",{className:"composer-chip",role:"listitem","aria-busy":"ready"!==e.status||se(e)||void 0,style:{display:"flex",alignItems:"center",gap:7,minWidth:0,maxWidth:320,height:32,padding:"0 7px 0 9px"},children:["ready"!==e.status||e.transcription?.state==="planning"||e.transcription?.state==="running"?(0,r.jsx)("span",{"aria-hidden":"true",style:{width:13,height:13,flexShrink:0,border:"1.5px solid var(--border-strong)",borderTopColor:"var(--accent)",borderRadius:"50%",animation:"spin 0.8s linear infinite"}}):nI(e.name,14),(0,r.jsxs)("span",{style:{minWidth:0,display:"flex",flexDirection:"column",lineHeight:1.15},children:[(0,r.jsx)("span",{title:e.name,style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text)",fontSize:12},children:e.name}),(0,r.jsxs)("span",{style:{color:"var(--text-dim)",fontSize:10},children:["audio"===e.stored?eh("chat.attachKindAudio"):"file"===e.stored?eh("chat.attachKindFile"):so[e.mimeType]," \xb7 ",rv(e.sourceSize??e.size),"extracting"===e.status?` \xb7 ${eh("chat.attachExtracting")}`:"","uploading"===e.status?` \xb7 ${eh("chat.attachUploading")}`:"",e.transcription?.state==="planning"?` \xb7 ${eh("chat.transcribeChecking")}`:"",e.transcription?.state==="confirm"?` \xb7 ${eh("chat.attachTranscribePending")}`:"",e.transcription?.state==="running"?` \xb7 ${eh("chat.attachTranscribing")}`:"",e.transcription?.state==="failed"&&(0,r.jsx)("span",{style:{color:"var(--danger)"},children:` \xb7 ${eh("chat.attachTranscribeFailed")}`})]})]}),(0,r.jsx)("button",{type:"button",onClick:()=>tZ(e.id),"aria-label":eh("chat.removeAttachment",{name:e.name}),title:eh("chat.removeAttachment",{name:e.name}),style:{width:24,height:24,flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center",padding:0,border:"none",background:"transparent",color:"var(--text-muted)",cursor:"pointer"},children:(0,r.jsxs)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"1.5",y1:"1.5",x2:"8.5",y2:"8.5"}),(0,r.jsx)("line",{x1:"8.5",y1:"1.5",x2:"1.5",y2:"8.5"})]})})]},e.id))]}),eV.length>0&&(0,r.jsx)("div",{role:"group","aria-label":eh("chat.transcribeGroup"),"aria-live":"polite",style:{display:"flex",flexDirection:"column",gap:6,marginBottom:6},children:eV.map(e=>{let t,n,i,a,l=e.attachmentId,o=e.transcription,d=o?.state==="confirm"||o?.state==="running"?o.plan:null,c=d?eh("chat.transcribePlanSummary",{duration:null===d.durationSeconds?eh("chat.transcribeDurationUnknown"):(n=Math.floor((t=Math.round(d.durationSeconds))/3600),i=Math.floor(t%3600/60),a=String(t%60).padStart(2,"0"),n>0?`${n}:${String(i).padStart(2,"0")}:${a}`:`${i}:${a}`),calls:d.estimatedCalls}):null,u=o?.state==="confirm"?eh("chat.transcribeConfirmTitle",{name:e.name}):o?.state==="running"?eh("chat.transcribeRunning",{name:e.name}):o?.state==="planning"?`${e.name} \xb7 ${eh("chat.transcribeChecking")}`:o?.state==="failed"?eh("chat.transcribeFailedRow",{name:e.name,error:o.error}):eh("chat.transcribeSkipped",{name:e.name});return(0,r.jsxs)("div",{"data-transcription-state":o?.state??"idle",style:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:8,padding:"7px 10px",border:`1px solid ${o?.state==="failed"?"var(--danger-line)":"var(--border)"}`,borderRadius:"var(--radius-control)",background:o?.state==="failed"?"var(--danger-soft)":"var(--bg-panel)",fontSize:12,lineHeight:1.45},children:[(0,r.jsxs)("div",{style:{flex:"1 1 220px",minWidth:0},children:[(0,r.jsx)("div",{style:{color:o?.state==="failed"?"var(--danger)":"var(--text)",overflowWrap:"anywhere"},children:u}),c&&(0,r.jsx)("div",{style:{color:"var(--text-dim)",fontVariantNumeric:"tabular-nums"},children:c}),o?.state==="confirm"&&(0,r.jsxs)(r.Fragment,{children:[o.plan.notice&&(0,r.jsx)("div",{style:{color:"var(--text-dim)",overflowWrap:"anywhere"},children:o.plan.notice}),(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:eh("chat.transcribeUsageNotice")})]})]}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",gap:6},children:[o?.state==="confirm"&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(s.r,{type:"button",variant:"neutralSolid",size:"small",onClick:()=>void tU(l,!0),children:eh("chat.transcribeStart")}),(0,r.jsx)(s.r,{type:"button",variant:"neutralWeak",size:"small",onClick:()=>tV(l),children:eh("chat.transcribeSkip")})]}),(o?.state==="planning"||o?.state==="running")&&(0,r.jsx)(s.r,{type:"button",variant:"neutralWeak",size:"small",onClick:()=>tV(l),children:eh("chat.transcribeCancel")}),(void 0===o||"skipped"===o.state||"failed"===o.state)&&(0,r.jsx)(s.r,{type:"button",variant:"neutralWeak",size:"small",onClick:()=>void tK(l),children:eh(o?.state==="failed"?"chat.transcribeRetry":"chat.transcribeAction")})]})]},e.id)})}),(0,r.jsxs)("div",{ref:tb,style:{position:"relative",minWidth:0},children:[e3&&D.length>0&&(0,r.jsxs)("div",{ref:tv,style:{position:"absolute",left:0,right:0,...sa(nc.side),zIndex:120,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s3)",overflow:"hidden",maxHeight:nc.maxHeight},children:[(0,r.jsx)("div",{title:"Input history",style:{height:30,padding:"0 10px",borderBottom:"1px solid var(--border)",display:"flex",alignItems:"center",color:"var(--text-dim)"},children:(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M3 12a9 9 0 1 0 3-6.7"}),(0,r.jsx)("path",{d:"M3 4v5h5"}),(0,r.jsx)("path",{d:"M12 7v5l3 2"})]})}),(0,r.jsx)("div",{style:{maxHeight:Math.max(0,nc.maxHeight-31),overflowY:"auto",padding:4},children:D.map((e,t)=>{let n=t===e9;return(0,r.jsxs)("button",{ref:e=>{tN.current[t]=e},type:"button",onMouseDown:t=>{t.preventDefault(),nm(e)},onMouseEnter:()=>te(t),style:{width:"100%",display:"flex",alignItems:"flex-start",gap:8,padding:"7px 8px",border:"none",borderRadius:"var(--radius-control)",background:n?"var(--bg-selected)":"none",color:"var(--text)",cursor:"pointer",textAlign:"left",fontSize:12.5,lineHeight:1.45},children:[(0,r.jsx)("span",{style:{flexShrink:0,fontFamily:"var(--font-mono)",fontSize:11,color:"var(--text-dim)",paddingTop:1},children:t+1}),(0,r.jsx)("span",{style:{minWidth:0,display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:2,overflow:"hidden",overflowWrap:"anywhere"},children:e})]},`${t}:${e}`)})})]}),eZ&&null!==t5&&(0,r.jsxs)("div",{style:{position:"absolute",left:0,right:0,...sa(nu.side),zIndex:120,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s3)",overflow:"hidden",maxHeight:nu.maxHeight},children:[(0,r.jsxs)("div",{style:{padding:"8px 10px",borderBottom:"1px solid var(--border)",display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,fontSize:11,color:"var(--text-dim)"},children:[(0,r.jsx)("span",{children:U?eh("chat.loadingCommands"):eh("chat.slashCommands",{label:t7})}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},children:eh("chat.tabEnter")})]}),(0,r.jsx)("div",{style:{maxHeight:Math.max(0,nu.maxHeight-34),overflowY:"auto",padding:10},children:U||0!==t6.length?t3.map(e=>(0,r.jsxs)("section",{style:{marginBottom:12},children:[(0,r.jsxs)("div",{style:{position:"sticky",top:-10,zIndex:1,display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,padding:"4px 0 6px",background:"var(--bg)",color:"var(--text-dim)",fontSize:10,fontWeight:600,textTransform:"uppercase"},children:[(0,r.jsx)("span",{children:eh(sf[e.source])}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontWeight:500},children:e.items.length})]}),(0,r.jsx)("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(220px, 1fr))",gap:8},children:e.items.map(({command:e,index:t})=>{let n=t===eQ,i=sb(e,td);return(0,r.jsxs)("button",{ref:e=>{tS.current[t]=e},type:"button",onMouseDown:t=>{t.preventDefault(),nf(e)},onMouseEnter:()=>e0(t),style:{width:"100%",minWidth:0,minHeight:58,display:"flex",flexDirection:"column",gap:4,justifyContent:"center",padding:"9px 10px",border:`1px solid ${n?"var(--accent)":"var(--border)"}`,borderRadius:"var(--radius-control)",background:n?"var(--bg-selected)":"var(--bg-panel)",color:"var(--text)",cursor:"pointer",textAlign:"left",boxShadow:n?"0 0 0 1px color-mix(in srgb, var(--accent) 28%, transparent)":"none"},children:[(0,r.jsxs)("span",{style:{fontSize:13,fontFamily:"var(--font-mono)",overflowWrap:"anywhere",wordBreak:"break-word",color:i?"var(--text-dim)":void 0},children:["/",e.name,i&&(0,r.jsx)("span",{style:{marginLeft:6,padding:"0 4px",border:"1px solid var(--border)",borderRadius:3,fontSize:9,color:"var(--text-dim)",whiteSpace:"nowrap"},children:eh("chat.dormant")})]}),sv(e,eh)&&(0,r.jsx)("span",{style:{display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:2,overflow:"hidden",fontSize:11,lineHeight:1.35,color:"var(--text-dim)"},children:sv(e,eh)})]},`${e.source}:${e.name}`)})})]},e.source)):(0,r.jsx)("div",{style:{padding:"2px 2px 4px",fontSize:12,color:"var(--text-dim)"},children:eh("chat.noCommands")})})]}),e4&&null!==e1&&(ec=tr&&(!tt||tt.cwd!==X),eu=1===nl.length?eh("chat.match"):eh("chat.matches",{count:nl.length}),ep=tt?.truncated&&!ns?e1.query?eh("chat.searchingAll"):eh("chat.indexTruncated"):"",(0,r.jsxs)("div",{style:{position:"absolute",left:0,right:0,...sa(np.side),zIndex:120,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s3)",overflow:"hidden",maxHeight:np.maxHeight},children:[(0,r.jsxs)("div",{style:{padding:"8px 10px",borderBottom:"1px solid var(--border)",display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,fontSize:11,color:"var(--text-dim)"},children:[(0,r.jsx)("span",{children:ec?eh("chat.loadingFiles"):eh("chat.files",{label:eu,hint:ep})}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},children:eh("chat.tabEnter")})]}),(0,r.jsx)("div",{style:{maxHeight:Math.max(0,np.maxHeight-34),overflowY:"auto",padding:4},children:ec||0!==nl.length?nl.map((e,t)=>{let n=t===e6,i=e.path.split("/").pop()??e.path,a=e.path.slice(0,e.path.length-i.length);return(0,r.jsxs)("button",{ref:e=>{tC.current[t]=e},type:"button",onMouseDown:t=>{t.preventDefault(),nh(e)},onMouseEnter:()=>e8(t),style:{width:"100%",display:"flex",alignItems:"center",gap:8,padding:"6px 8px",border:"none",borderRadius:"var(--radius-control)",background:n?"var(--bg-selected)":"none",color:"var(--text)",cursor:"pointer",textAlign:"left",fontSize:12.5,fontFamily:"var(--font-mono)"},children:[(0,r.jsx)("span",{style:{flexShrink:0,display:"flex",alignItems:"center"},children:e.isDir?(0,r.jsx)(nS,{size:14}):nI(i,14)}),(0,r.jsxs)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[a&&(0,r.jsx)("span",{style:{color:"var(--text-dim)"},children:a}),i,e.isDir&&(0,r.jsx)("span",{style:{color:"var(--text-dim)"},children:"/"})]})]},`${e.isDir?"d":"f"}:${e.path}`)}):(0,r.jsx)("div",{style:{padding:"6px 8px",fontSize:12,color:"var(--text-dim)"},children:na&&!ns?eh("chat.searching"):eh("chat.noMatchingFiles")})})]})),(0,r.jsxs)("div",{className:`chat-composer-field${eG?" is-bash":""}${l?" is-streaming":""}`,style:{minWidth:0,display:"flex",gap:8,alignItems:"center",background:"var(--bg)",border:`1px solid ${eG?"var(--tool-bg)":l&&(n||a)?"var(--warning-line)":"var(--border)"}`,borderRadius:"var(--seed-radius-r3)",padding:"10px 10px 10px 14px",boxShadow:"var(--seed-shadow-s1)",transition:"border-color 0.15s, background 0.15s, box-shadow 0.15s"},children:[(0,r.jsx)("textarea",{className:"chat-composer-textarea",ref:tc,value:ex,onChange:e=>{t$.current=e.target.value,ev(e.target.value),e7(!1),nn(e.target.value,e.target.selectionStart)},onSelect:e=>{let t=e.currentTarget;nn(t.value,t.selectionStart)},onKeyDown:nb,onCompositionStart:()=>{tw.current=!0},onCompositionEnd:e=>{tw.current=!1,tk.current=Date.now();let t=e.currentTarget;nn(t.value,t.selectionStart)},onInput:ny,onPaste:nw,placeholder:l&&(n||a)?eh("chat.steerPlaceholder"):l?eh("chat.agentPlaceholder"):eh("chat.messagePlaceholder"),rows:1,style:{flex:1,minWidth:0,width:"100%",background:"none",border:"none",outline:"none",resize:"none",color:"var(--text)",fontSize:14,lineHeight:1.6,fontFamily:"inherit",minHeight:24,maxHeight:200,overflow:"auto"}}),l?eg?null:(0,r.jsx)("div",{style:{display:"flex",alignItems:"center",gap:6,flexShrink:0,alignSelf:"flex-end"},children:nG}):(0,r.jsxs)("button",{className:"chat-composer-send",onClick:t4,disabled:!ne,"aria-busy":eK||void 0,"aria-label":eg?eh("chat.send"):void 0,title:eK?eh("chat.attachExtractingWait"):void 0,style:{flexShrink:0,alignSelf:"flex-end",display:"flex",alignItems:"center",justifyContent:"center",gap:6,minWidth:eg?44:void 0,padding:eg?0:"7px 14px",background:ne?"var(--accent-soft)":"var(--bg-raised)",border:"none",borderRadius:"var(--radius-control)",color:ne?"var(--accent-hover)":"var(--text-dim)",cursor:ne?"pointer":"not-allowed",fontSize:13,fontWeight:600,letterSpacing:"-0.01em",transition:"background 0.15s, color 0.15s"},children:[(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("line",{x1:"2",y1:"7",x2:"11",y2:"7"}),(0,r.jsx)("polyline",{points:"7.5 3 12 7 7.5 11"})]}),eg?null:eh("chat.send")]})]})]}),eG&&(0,r.jsxs)("div",{className:"text-xs px-2 py-1",style:{color:eY?"var(--text-muted)":"var(--accent)",marginTop:4},children:[eh("chat.shell")," \xb7 ",eY?eh("chat.outputLocal"):eh("chat.outputModel")]}),(0,r.jsxs)("div",{className:"composer-action-bar",style:{marginTop:8,display:"flex",alignItems:"center",gap:6},children:[(0,r.jsxs)("div",{style:{flex:eg?"1 1 0%":"0 0 auto",minWidth:eg?"min-content":0,display:"flex",alignItems:"center",gap:2},children:[(!eg||!l)&&nq,!eg&&nK,!(eg&&l)&&(nk.length>0||nz||p)&&m&&(0,r.jsxs)("div",{ref:tu,style:{position:"relative",flex:eg?"1 1 0%":void 0,width:eg?0:void 0,minWidth:44*!!eg},children:[(0,r.jsxs)("button",{className:`composer-chip${eb?" is-active":""}`,onClick:e=>{let t=e.currentTarget.getBoundingClientRect();ek({top:t.top,bottom:t.bottom,left:t.left,width:t.width}),ey(e=>(e&&eS(""),!e))},disabled:l||b,"aria-busy":b||void 0,style:{display:"flex",alignItems:"center",gap:6,justifyContent:eg?"flex-start":void 0,padding:eg?"8px 10px":"8px 12px",height:32,width:eg?"100%":void 0,maxWidth:eg?"100%":220,overflow:"hidden",background:eb?"var(--bg-hover)":"none",border:"none",borderRadius:"var(--radius-control)",color:"var(--text-muted)",cursor:l||b?"not-allowed":"pointer",fontSize:12,opacity:l?.5:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{l||b||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{e.currentTarget.style.background=eb?"var(--bg-hover)":"none",e.currentTarget.style.color="var(--text-muted)"},title:b?"Switching model":nk.length>0?"Change model":"No available models",children:[b?(0,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.4",strokeLinecap:"round",style:{animation:"spin 0.8s linear infinite",flexShrink:0},"aria-hidden":"true",children:(0,r.jsx)("path",{d:"M21 12a9 9 0 1 1-2.64-6.36"})}):(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"}),(0,r.jsx)("rect",{x:"9",y:"9",width:"6",height:"6"}),(0,r.jsx)("line",{x1:"9",y1:"1",x2:"9",y2:"4"}),(0,r.jsx)("line",{x1:"15",y1:"1",x2:"15",y2:"4"}),(0,r.jsx)("line",{x1:"9",y1:"20",x2:"9",y2:"23"}),(0,r.jsx)("line",{x1:"15",y1:"20",x2:"15",y2:"23"}),(0,r.jsx)("line",{x1:"20",y1:"9",x2:"23",y2:"9"}),(0,r.jsx)("line",{x1:"20",y1:"14",x2:"23",y2:"14"}),(0,r.jsx)("line",{x1:"1",y1:"9",x2:"4",y2:"9"}),(0,r.jsx)("line",{x1:"1",y1:"14",x2:"4",y2:"14"})]}),(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:nz??(nk.length>0?"Select model":"No models")})]}),eb&&ew&&(()=>{let e=window.visualViewport?.height??window.innerHeight,{side:t,maxHeight:n}=a6(ew.top,ew.bottom,e,a8(e,.6,460),{gap:6,prefer:"above"}),i="above"===t?{bottom:e-ew.top+6}:{top:ew.bottom+6},a=eg?{left:8,right:8,maxWidth:"calc(100vw - 16px)"}:{left:ew.left,width:"max-content",minWidth:ew.width};return(0,r.jsxs)("div",{ref:tp,style:{position:"fixed",...i,...a,zIndex:500,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s2)",overflow:"hidden",maxHeight:n,display:"flex",flexDirection:"column"},children:[nM&&(0,r.jsx)("div",{style:{padding:"6px 8px",borderBottom:"1px solid var(--border)",flexShrink:0},children:(0,r.jsx)("input",{value:ej,onChange:e=>eS(e.target.value),onKeyDown:e=>{"Escape"===e.key&&(eS(""),ey(!1))},placeholder:eh("chat.filterModels"),"aria-label":eh("chat.filterModels"),autoFocus:!0,autoComplete:"off",spellCheck:!1,style:{width:"100%",minWidth:220*!eg,fontSize:11,fontFamily:"var(--font-mono)",padding:"5px 8px",border:"1px solid var(--border)",borderRadius:5,outline:"none",background:"var(--bg)",color:"var(--text)",boxSizing:"border-box"}})}),(0,r.jsxs)("div",{style:{minHeight:0,overflowY:"auto"},children:[nL.length>0&&(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{style:{padding:"6px 12px 4px",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:eh("chat.frequentModels")}),nL.map(({option:e,count:t})=>nA(e,"frequent",t))]}),nR.length>0&&!ej.trim()&&v&&(0,r.jsxs)("div",{style:{borderTop:nL.length>0?"1px solid var(--border)":"none"},children:[(0,r.jsx)("div",{style:{padding:"6px 12px 4px",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:eh("chat.modelRoles")}),nR.map(e=>{let t=nE?.role===e.role,n=e.resolved?.name??e.resolved?.modelId??"";return(0,r.jsxs)("button",{onClick:()=>{ey(!1),eS(""),v(e.role)},title:e.selector??n,style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",background:t?"var(--bg-selected)":"none",border:"none",color:t?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left",whiteSpace:"nowrap"},onMouseEnter:e=>{t||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{t||(e.currentTarget.style.background="none")},children:[t?(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,r.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,r.jsx)("span",{style:{width:10,flexShrink:0}}),(0,r.jsx)("span",{style:{flexShrink:0,minWidth:58,padding:"1px 6px",borderRadius:4,border:"1px solid var(--border)",background:"var(--bg-subtle)",color:t?"var(--accent)":"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:9.5,fontWeight:700,letterSpacing:"0.06em",textAlign:"center"},children:e.tag??e.role.toUpperCase()}),(0,r.jsx)("span",{style:{fontWeight:t?600:500},children:e.name}),(0,r.jsxs)("span",{style:{marginLeft:"auto",paddingLeft:12,color:"var(--text-dim)",fontSize:11,overflow:"hidden",textOverflow:"ellipsis"},children:[n,e.resolved?.thinkingLevel?` \xb7 ${e.resolved.thinkingLevel}`:""]})]},e.role)}),(0,r.jsx)("div",{style:{padding:"6px 12px 4px",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em",borderTop:"1px solid var(--border)"},children:eh("chat.allModels")})]}),0===n$.length?(0,r.jsx)("div",{style:{padding:"8px 12px",color:"var(--text-dim)",fontSize:12,whiteSpace:"nowrap"},children:ej.trim()?eh("chat.noMatchingModels"):"No available models"}):n$.map((e,t)=>(0,r.jsxs)("div",{children:[n$.length>1&&(0,r.jsx)("div",{style:{padding:"6px 12px 4px",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em",borderTop:t>0?"1px solid var(--border)":"none"},children:e.provider}),e.options.map(e=>nA(e,"all"))]},e.provider))]})]})})()]}),eg&&l&&(0,r.jsx)("div",{style:{display:"flex",alignItems:"center",gap:6,minWidth:0},children:nG}),!eg&&nV,!eg&&nJ,!eg&&nO&&(0,r.jsx)("span",{style:{flexShrink:0,padding:"0 6px",fontSize:12,color:"var(--text-muted)",whiteSpace:"nowrap"},children:nO}),(0,r.jsx)(au,{sessionId:Q})]}),(0,r.jsxs)("div",{ref:tx,style:{flex:"0 1 auto",minWidth:0,display:"flex",alignItems:"center",justifyContent:"flex-end",position:"relative",marginLeft:"auto",gap:eg?4:2},children:[eg?(0,r.jsx)("button",{type:"button",className:`composer-icon-button${eW?" is-active":""}`,title:eh("chat.moreControls"),"aria-label":eh("chat.moreControls"),"aria-expanded":eW,onClick:()=>{ey(!1),eS(""),eF(e=>!e)},children:(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"4",y1:"7",x2:"20",y2:"7"}),(0,r.jsx)("line",{x1:"4",y1:"17",x2:"20",y2:"17"}),(0,r.jsx)("circle",{cx:"10",cy:"7",r:"2.2"}),(0,r.jsx)("circle",{cx:"16",cy:"17",r:"2.2"})]})}):(0,r.jsx)(s.r,{type:"button",variant:"neutralWeak",size:"small",layout:"withText",title:eW?void 0:eh("chat.moreControls"),"aria-label":eh("chat.moreControls"),"aria-expanded":eW,onClick:()=>{ey(!1),eS(""),eF(e=>!e)},children:eh("chat.moreControls")}),(0,r.jsxs)("div",{role:"group","aria-label":eh("chat.moreControls"),style:{display:eW?"flex":"none",alignItems:"center",gap:1,position:"absolute",right:0,bottom:"100%",marginBottom:"var(--seed-dimension-x1)",zIndex:60,padding:1,width:"max-content",maxWidth:"calc(100vw - 32px)",flexWrap:"wrap",justifyContent:"flex-end",border:"1px solid var(--seed-color-stroke-neutral-muted)",borderRadius:"var(--seed-radius-r2)",background:"var(--seed-color-bg-layer-floating)",boxShadow:"var(--seed-shadow-s2)"},children:[eg&&(0,r.jsxs)(r.Fragment,{children:[l&&nq,nK,nV,nJ]}),!l&&N&&(0,r.jsxs)("div",{ref:tf,style:{position:"relative"},children:[(0,r.jsxs)("button",{className:`composer-chip${eR?" is-active":""}`,onClick:()=>!l&&eE(e=>!e),disabled:l,title:eh("chat.changeToolPreset")+`: ${nU}`,"aria-label":eh("chat.changeToolPreset"),style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,padding:"8px 12px",height:32,background:eR?"var(--bg-hover)":"none",border:"none",borderRadius:"var(--radius-control)",color:"var(--text-muted)",cursor:l?"not-allowed":"pointer",fontSize:12,opacity:l?.5:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{l||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{e.currentTarget.style.background=eR?"var(--bg-hover)":"none",e.currentTarget.style.color="var(--text-muted)"},children:[(0,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:(0,r.jsx)("path",{d:"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"})}),(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:nU})]}),eR&&(0,r.jsx)("div",{style:{position:"absolute",bottom:"calc(100% + 6px)",right:0,zIndex:100,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s2)",overflow:"hidden",minWidth:120},children:st.map(e=>{let t=sn[e],n=(C??"default")===t,i="off"===e?eh("chat.noTools"):"default"===e?eh("chat.builtInTools",{tools:sr}):eh("chat.allBuiltInTools",{tools:`${sr} + ${si}`});return(0,r.jsxs)("button",{onClick:()=>{eE(!1),n||N(t)},style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",background:n?"var(--bg-selected)":"none",border:"none",color:n?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left",fontWeight:n?600:400,whiteSpace:"nowrap"},onMouseEnter:e=>{n||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{n||(e.currentTarget.style.background="none")},children:[n?(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,r.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,r.jsx)("span",{style:{width:10,flexShrink:0}}),(0,r.jsx)("span",{style:{flex:1},children:e}),(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)",marginLeft:8},children:i})]},e)})})]}),!l&&y&&(0,r.jsx)("div",{children:(0,r.jsx)("button",{className:`composer-chip${k?" is-active is-danger":""}`,onClick:k?w:y,disabled:l&&!k,style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,padding:"8px 12px",height:32,background:k?"var(--danger-soft)":"none",border:"none",borderRadius:"var(--radius-control)",color:k?"var(--danger)":"var(--text-muted)",cursor:l&&!k?"not-allowed":"pointer",fontSize:12,opacity:l&&!k?.5:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{(!l||k)&&(e.currentTarget.style.background=k?"var(--danger-soft)":"var(--bg-hover)",e.currentTarget.style.color=k?"var(--danger)":"var(--text)")},onMouseLeave:e=>{e.currentTarget.style.background=k?"var(--danger-soft)":"none",e.currentTarget.style.color=k?"var(--danger)":"var(--text-muted)"},title:k?eh("chat.stopCompaction"):eh("chat.compactContext"),"aria-label":k?eh("chat.stopCompaction"):eh("chat.compactContext"),children:k?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",children:(0,r.jsx)("rect",{x:"2",y:"2",width:"6",height:"6",rx:"1",fill:"currentColor"})}),(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:eh("chat.compacting")})]}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("polyline",{points:"4 14 10 14 10 20"}),(0,r.jsx)("polyline",{points:"20 10 14 10 14 4"}),(0,r.jsx)("line",{x1:"10",y1:"14",x2:"3",y2:"21"}),(0,r.jsx)("line",{x1:"21",y1:"3",x2:"14",y2:"10"})]}),(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:eh("chat.compact")})]})})}),eg&&nY,eW&&(0,r.jsx)("button",{className:"composer-icon-button is-active",type:"button",title:eh("chat.collapseControls"),"aria-label":eh("chat.collapseControls"),"aria-expanded":!0,onClick:()=>{eE(!1),eA(!1),eF(!1)},style:{display:"flex",alignItems:"center",justifyContent:"center",width:36,height:32,padding:0,marginLeft:0,background:"var(--bg-hover)",border:"none",borderLeft:"1px solid color-mix(in srgb, var(--border) 72%, transparent)",borderRadius:"0 9px 9px 0",color:"var(--text)",cursor:"pointer",transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-selected)"},onMouseLeave:e=>{e.currentTarget.style.background="var(--bg-hover)"},children:(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[(0,r.jsx)("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),(0,r.jsx)("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),l&&(0,r.jsxs)("button",{className:"composer-chip is-danger is-active",onClick:t,title:eh("chat.stopAgent"),"aria-label":eg?eh("chat.stopAgent"):void 0,style:{display:"flex",alignItems:"center",justifyContent:"center",gap:6,minWidth:eg?44:void 0,padding:eg?0:"8px 14px",height:32,background:"var(--danger-soft)",border:"1px solid var(--danger-line)",borderRadius:"var(--radius-control)",color:"var(--danger)",cursor:"pointer",fontSize:12,fontWeight:600,whiteSpace:"nowrap",letterSpacing:"-0.01em",transition:"background 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.background="var(--danger-soft)"},children:[(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",children:(0,r.jsx)("rect",{x:"1.5",y:"1.5",width:"7",height:"7",rx:"1.5",fill:"currentColor"})}),eg?null:eh("chat.stop")]}),(0,r.jsx)(ad,{sessionId:Q,onEnsureSession:ee,onTranscriptPersisted:et}),!eg&&nY]})]})]})]})});function sP({statuses:e}){if(0===e.length)return null;let t=[...e].sort((e,t)=>e.key.localeCompare(t.key)).map(({text:e})=>e.replace(/[\r\n\t]/g," ").replace(/ +/g," ").trim()).join(" "),n=ej(t);return(0,r.jsx)("div",{role:"status","aria-label":n,title:n,style:{display:"flex",alignItems:"center",flexShrink:0,minWidth:0,height:36,padding:"0 12px",borderTop:"1px solid var(--border)",background:"transparent"},children:(0,r.jsx)("span",{style:{minWidth:0,overflow:"hidden",color:"var(--text-muted)",fontFamily:"var(--font-mono)",fontSize:11,textOverflow:"ellipsis",whiteSpace:"nowrap"},children:eT(t).map((e,t)=>(0,r.jsx)("span",{style:e.style,children:e.text},t))})})}function sW({phases:e}){let{t}=(0,R.s)(),[n,a]=(0,i.useState)(!1),[s,l]=(0,i.useState)(!1),{currentPhase:o,activeTask:d,remaining:c,completed:u,total:p,percent:h}=e9(e);if(0===p)return null;let m=0===c;return(0,r.jsxs)("div",{className:`todo-strip${m?" is-done":""}`,children:[(0,r.jsxs)("button",{type:"button",className:"todo-strip-summary","aria-expanded":n,onClick:()=>a(e=>!e),children:[(0,r.jsx)("span",{"aria-hidden":"true",className:"todo-strip-marker",children:m?"✓":"›"}),o&&(0,r.jsx)("span",{className:"todo-strip-phase",children:o.name}),(0,r.jsx)("span",{className:"todo-strip-task",children:m?t("todo.allDone",{count:u}):d?.content??""}),(0,r.jsx)("span",{className:"todo-strip-count",children:m?t("todo.progressDone",{percent:h??0,completed:u,total:p}):t("todo.progress",{percent:h??0,completed:u,total:p,remaining:c})})]}),n&&(0,r.jsxs)("div",{className:"todo-strip-body",children:[e.map((t,n)=>{let i=t.tasks.filter(e=>s||"completed"!==e.status);return 0===i.length?null:(0,r.jsxs)("div",{className:"todo-checklist-phase",role:"list",children:[e.length>1&&(0,r.jsx)("div",{className:"todo-checklist-phase-name",children:t.name}),i.map((e,t)=>(0,r.jsx)(nw,{task:e},`${e.content}-${t}`))]},`${t.name}-${n}`)}),u>0&&(0,r.jsx)("button",{type:"button",className:"todo-strip-completed-toggle","aria-expanded":s,onClick:()=>l(e=>!e),children:t(s?"todo.hideCompleted":"todo.showCompleted",{count:u})})]})]})}function sF(e=document){return"visible"!==e.visibilityState||!e.hasFocus()}function s_(e){switch(e.method){case"select":case"confirm":case"input":case"editor":case"ask":case"plan_review":return!0;case"custom":return!0!==e.closed;default:return!1}}async function sD(e,t={createWindowNotification:(e,t)=>new Notification(e,t),getServiceWorkerRegistration:"serviceWorker"in navigator?()=>navigator.serviceWorker.getRegistration():null}){let n={body:e.body,...e.tag?{tag:e.tag}:{}};if(t.getServiceWorkerRegistration)try{let r=await t.getServiceWorkerRegistration();if(r)return await r.showNotification(e.title,{...n,data:{url:e.sessionUrl}}),"service-worker"}catch{}try{let r=t.createWindowNotification(e.title,n);return r.onclick=()=>{r.close(),e.onClick()},"window"}catch{return null}}var sO=n(62503);class sH extends Error{constructor(e,t,n,r){super(e),this.status=t,this.code=n,this.accepted=r,this.name="AgentCommandError"}}async function sB(e,t){let n=await fetch(`/api/agent/${encodeURIComponent(e)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),r=await n.json().catch(()=>({}));if(!n.ok||r.error)throw new sH(r.error??`HTTP ${n.status}`,n.status,r.code,r.accepted);return r.data}let sU="ompweb-update-client-id",sq="ompweb-update-resume-intent-v2",sK="ompweb-update-return-v1",sV="cuelo-restart-return-v1",sJ="ompweb-update-failure-return-v1",sG="ompweb:update-wake";function sY(e){return null===e?2e4:"running"===e?null:"failed"===e?3e4:8e3}function sZ(){let e=sessionStorage.getItem(sU);if(e&&/^[A-Za-z0-9_-]{16,128}$/.test(e))return e;let t="function"==typeof crypto.randomUUID?crypto.randomUUID().replaceAll("-",""):Array.from(crypto.getRandomValues(new Uint8Array(16)),e=>e.toString(16).padStart(2,"0")).join("");return sessionStorage.setItem(sU,t),t}function sX(){sessionStorage.removeItem(sq)}function sQ(){let e=sessionStorage.getItem(sK);if(!e)return null;try{let t=JSON.parse(e);if(1!==t.schemaVersion||"string"!=typeof t.requestId||!/^[0-9a-f]{32}$/.test(t.requestId)||"string"!=typeof t.stageHash||!/^[0-9a-f]{64}$/.test(t.stageHash)||"boolean"!=typeof t.dismissed)return null;return t}catch{return null}}function s0(e){let t=sQ();if(!t||t.requestId!==e)return t;let n={...t,dismissed:!0};try{sessionStorage.setItem(sK,JSON.stringify(n))}catch{}return n}async function s1(e){let t=await fetch("/api/update-maintenance",{method:"POST",headers:{"Content-Type":"application/json","Cache-Control":"no-cache"},body:JSON.stringify({action:"heartbeat",clientId:sZ(),sessionId:e.sessionId,resumeUrl:e.resumeUrl,preservationError:e.preservationError??null,...e.update?{requestId:e.update.requestId,stageHash:e.update.stageHash}:{}}),cache:"no-store"});if(!t.ok)throw Error(`maintenance heartbeat HTTP ${t.status}`);return await t.json()}async function s2(e){if(e.sessionId){let t=await fetch(`/api/sessions/${encodeURIComponent(e.sessionId)}?deferThinking=1&deferMedia=1`,{cache:"no-store",headers:{"Cache-Control":"no-cache"}});if(!t.ok)throw Error(`session resume HTTP ${t.status}`);if((await t.json()).sessionId!==e.sessionId)throw Error("resumed session identity mismatch")}let t=await fetch("/api/update-maintenance",{method:"POST",headers:{"Content-Type":"application/json","Cache-Control":"no-cache"},body:JSON.stringify({action:"resume-confirm",requestId:e.requestId,stageHash:e.stageHash,clientId:e.clientId,sessionId:e.sessionId}),cache:"no-store"});if(!t.ok)throw Error(`resume confirm HTTP ${t.status}`);let n=await t.json().catch(()=>null);!function(e){let t=sQ();if(t&&t.requestId===e.requestId&&t.stageHash===e.stageHash)return;let n={schemaVersion:1,requestId:e.requestId,stageHash:e.stageHash,dismissed:!1};try{sessionStorage.setItem(sK,JSON.stringify(n))}catch{}}({requestId:e.requestId,stageHash:e.stageHash}),sX();let r=n?.wake;e.sessionId&&(r?.wake===!0||r?.reason==="already-claimed"||r?.reason==="user-already-active")&&window.dispatchEvent(new CustomEvent(sG,{detail:{sessionId:e.sessionId}}))}async function s4(e){let t=function(e){let t=sessionStorage.getItem(sJ);if(!t)return null;sessionStorage.removeItem(sJ);try{let n=JSON.parse(t);if(1!==n.schemaVersion||n.requestId!==e.requestId||n.stageHash!==e.stageHash||n.clientId!==e.clientId)return null;return{wake:!0===n.wake}}catch{return null}}(e);return t?(sX(),t.wake&&e.sessionId&&window.dispatchEvent(new CustomEvent(sG,{detail:{sessionId:e.sessionId}})),"failed"):(await s2(e),"resumed")}function s5(e,t){let n=new Map(e.map(e=>[e.id,e]));for(let e of t)n.set(e.id,function(e,t){return e&&(void 0!==e.parentToolCallId&&void 0!==t.parentToolCallId?e.parentToolCallId===t.parentToolCallId:void 0===e.sessionFile||void 0===t.sessionFile||e.sessionFile===t.sessionFile)?{...t,index:e.index,agent:e.agent,agentSource:e.agentSource,description:e.description??t.description,task:e.task??t.task,assignment:e.assignment??t.assignment,sessionFile:t.sessionFile??e.sessionFile,parentToolCallId:t.parentToolCallId??e.parentToolCallId}:t}(n.get(e.id),e));let r=[...n.values()];return[...r.filter(e=>"pending"===e.status||"running"===e.status).sort((e,t)=>e.index-t.index||e.id.localeCompare(t.id)),...r.filter(e=>"pending"!==e.status&&"running"!==e.status).sort((e,t)=>t.lastUpdate-e.lastUpdate||e.id.localeCompare(t.id))].slice(0,128)}function s6(e,t){switch(t.type){case"start":return{isStreaming:!0,streamingMessage:null};case"update":return{isStreaming:!0,streamingMessage:t.message};case"end":case"reset":return{isStreaming:!1,streamingMessage:null};default:return e}}function s8(e){return{steering:e?.steering??[],followUp:e?.followUp??[]}}function s3(e){if(e&&"boolean"==typeof e.fastModeEnabled)return{enabled:e.fastModeEnabled,active:!0===e.fastModeActive}}function s7(e){return t=>{let n=e?.isCompacting?e.compaction:null;if(!n)return t;let r=Date.now()-n.elapsedMs;return{startedAt:t?Math.min(t.startedAt,r):r,reason:t?.reason??n.reason}}}function s9(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1){let r=e[n],i=t[n];if(!r||!i||r.name!==i.name||r.tasks.length!==i.tasks.length)return!1;for(let e=0;e<r.tasks.length;e+=1){let t=r.tasks[e],n=i.tasks[e];if(!t||!n||t.content!==n.content||t.status!==n.status||t.blocker!==n.blocker)return!1}}return!0}function le(e){return"aborted"===e.stopReason?"aborted":"error"===e.stopReason||e.errorMessage?"failed":e.stopReason?"completed":"unknown"}function lt(e,t){for(let n=e.length-1;n>=0;n--){let r=t[n]??null;if(!eG(r??void 0))return{message:e[n],entryId:r}}return null}let ln=new Set(["ArrowUp","ArrowDown","PageUp","PageDown","Home","End"," ","Space","Spacebar"]);class lr extends Error{constructor(e){super("timeout"===e?"Timed out connecting to the agent event stream. Please try again.":"Failed to connect to the agent event stream. Please try again."),this.status=e,this.name="EventStreamConnectionError"}}function li(){return"u">typeof crypto&&"function"==typeof crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2)}`}function la(e){return new Promise(t=>setTimeout(t,e))}function ls(e){let t=e.findIndex(e=>!e.exiting);return -1===t?e:e.map((e,n)=>n===t?{...e,exiting:!0}:e)}function ll(e,t){switch(t.type){case"add":if(e.visible.some(e=>e.exiting)||e.visible.length>=5)return{visible:e.visible.some(e=>e.exiting)?e.visible:ls(e.visible),pending:[...e.pending,t.notice]};return{...e,visible:[...e.visible,t.notice]};case"mark_oldest_exiting":return{...e,visible:ls(e.visible)};case"remove":return function(e,t){let n=e,r=t;for(;r.length>0&&n.length<5;){let[e,...t]=r;n=[...n,e],r=t}return r.length>0&&!n.some(e=>e.exiting)&&(n=ls(n)),{visible:n,pending:r}}(e.visible.filter(e=>e.id!==t.id),e.pending);default:return e}}function lo(e){if(!e||"object"!=typeof e||"image"!==e.type)return"";let t=e.source;return t&&"object"==typeof t?["url"===t.type?"url":"base64","string"==typeof t.media_type?t.media_type:"","string"==typeof t.data?t.data:"","string"==typeof t.url?t.url:""].join(":"):["base64","string"==typeof e.mimeType?e.mimeType:"","string"==typeof e.data?e.data:"",""].join(":")}function ld(e){let t,n=e.content;return"string"==typeof n?JSON.stringify({text:n,images:[]}):Array.isArray(n)?JSON.stringify({text:"string"==typeof(t=e.content)?t:Array.isArray(t)?t.map(e=>e&&"object"==typeof e&&"text"===e.type&&"string"==typeof e.text?e.text:"").filter(Boolean).join("\n"):"",images:n.map(lo).filter(Boolean)}):JSON.stringify({text:"",images:[]})}function lc(e){return"user"===e.role?`user:${ld(e)}`:"bashExecution"===e.role?JSON.stringify({role:e.role,command:e.command,output:e.output,exitCode:e.exitCode,cancelled:e.cancelled,truncated:e.truncated,fullOutputPath:e.fullOutputPath,excludeFromContext:e.excludeFromContext}):JSON.stringify({role:e.role,content:e.content,model:e.model,provider:e.provider,customType:e.customType})}function lu(e,t){return e&&"object"==typeof e?"number"!=typeof e.tokensBefore||"number"!=typeof e.estimatedTokensAfter?null:{reason:t,tokensBefore:e.tokensBefore,estimatedTokensAfter:e.estimatedTokensAfter}:null}function lp(e){return e?.map(({data:e,mimeType:t})=>({data:e,mimeType:t}))}function lh(){let e=document.activeElement;return e instanceof HTMLElement&&(e.isContentEditable||"INPUT"===e.tagName||"SELECT"===e.tagName||"TEXTAREA"===e.tagName)}let lm=!1,lf={width:0,height:0},lg=new Set,lx=null;function lv(){let e=window.visualViewport,t=lh();lf.width!==window.innerWidth?lf={width:window.innerWidth,height:window.innerHeight}:t||(lf.height=Math.max(lf.height,window.innerHeight));let n=function({hasFocusedEditable:e,innerHeight:t,viewportHeight:n,viewportScale:r,baselineHeight:i}){return!(!e||Math.abs(r-1)>=.01)&&(t-n>120||i-t>120)}({hasFocusedEditable:t,innerHeight:window.innerHeight,viewportHeight:e?.height??window.innerHeight,viewportScale:e?.scale??1,baselineHeight:lf.height});if(n!==lm)for(let e of(lm=n,lg))e()}function lb(e){if(lg.add(e),!lx){let e=null,t=()=>{null!==e&&window.cancelAnimationFrame(e),e=window.requestAnimationFrame(()=>{e=null,lv()})},n=window.visualViewport;n?.addEventListener("resize",t),window.addEventListener("resize",t),window.addEventListener("focusin",t),window.addEventListener("focusout",t),lv(),lx=()=>{n?.removeEventListener("resize",t),window.removeEventListener("resize",t),window.removeEventListener("focusin",t),window.removeEventListener("focusout",t),null!==e&&window.cancelAnimationFrame(e)}}return()=>{lg.delete(e),0===lg.size&&lx&&(lx(),lx=null)}}function ly(){return(0,i.useSyncExternalStore)(lb,()=>lm,()=>!1)}let lw={count:50,end:null};function lk(e,t){let n=Math.max(e,0),r=null===t.end?n:Math.min(Math.max(t.end,0),n),i=Math.min(Math.max(t.count,0),r),a=r-i;return{startIndex:a,endIndex:r,hasMore:a>0,hasLater:r<n}}function lj(e,t,n){let{startIndex:r,endIndex:i}=lk(e,n);if(t>=r&&t<i)return n;let a=Math.max(0,t-10),s=Math.max(t+1,a+50);return s>=e?{count:e-a,end:null}:{count:s-a,end:s}}function lS({sticker:e,text:t,tag:n,followRef:a}){let s=(0,i.useRef)(null);return((0,i.useEffect)(()=>{(!a||a.current)&&s.current?.scrollIntoView({block:"nearest",behavior:"smooth"})},[]),e||t)?(0,r.jsxs)("div",{ref:s,className:"cue-bubble-dock",role:"status","aria-live":"polite",children:[e&&(0,r.jsx)("img",{className:"cue-bubble-sticker",src:e,alt:iC[n]}),t&&(0,r.jsx)("p",{className:e?"cue-bubble":"cue-bubble cue-bubble--solo",children:t}),e&&(0,r.jsx)(iw(),{id:"ad10be785ccf4f7",children:".cue-bubble-sticker{transform-origin:center 75%;animation:cue-sticker-pop 200ms cubic-bezier(0,0,.15,1)both}@keyframes cue-sticker-pop{from{opacity:0;transform:scale(.88)}to{opacity:1;transform:scale(1)}}@media(prefers-reduced-motion:reduce){.cue-bubble-sticker{animation:none}}"})]}):null}function lC(e){if("user"!==e.role)return null;let t="string"==typeof e.content?e.content:e.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n"),n=(rx(t)?.message??t).trim();return n.length>0?n:null}function lN(e){return`omp-cues:${e}`}function lI(e,t){let n=[];for(let r of t)r.sessionId===e&&null!==r.anchorEntryId&&n.push({id:r.id,anchorEntryId:r.anchorEntryId,sticker:r.sticker,text:r.text,tag:r.tag});try{window.localStorage.setItem(lN(e),JSON.stringify(n.slice(-200)))}catch{}}let lT=[];function lM(e){return`omp-web:interrupted-dismissed:${e}`}let l$=(0,i.memo)(function({messages:e,entryIds:t,toolResultsMap:n,modelNames:a,messageCwd:s,onOpenFile:l,sessionBusy:o,isNew:d,isStreaming:c,handleFork:u,forkingEntryId:p,handleNavigate:h,handleEditContent:m,sessionId:f,main:g,process:x,dispatchSlots:v,compactedDispatch:b,startIndex:y,endIndex:w,sentinelRef:k,laterSentinelRef:j,flashItem:S,t:C,onProcessLogChange:N,cues:I,cueFollowRef:T}){(0,i.useEffect)(()=>{N({groups:x,messages:e,entryIds:t,toolResults:n,modelNames:a,cwd:s,sessionId:f})},[N,x,e,t,n,a,s,f]);let M=(0,i.useMemo)(()=>{let t=new Map;for(let[r,i]of function(e,t,n,r){let i=new Map;e.forEach((e,t)=>{"answer"===e.kind&&i.set(e.idx,t)});let a=new Map,s=new Map;for(let e of t){let t=s.get(e.anchorIdx);for(let l of(t||(t=new Set,s.set(e.anchorIdx,t)),e.entries)){let e=n[l.idx];if(e?.role!=="assistant")continue;let s=Math.max(0,(l.blocks?i.get(l.idx):void 0)??l.afterMainIndex??-1),o=t;!function(e,t,n){for(let r of e){if("toolCall"!==r.type||"learn"!==r.toolName&&"manage_skill"!==r.toolName)continue;let e=t?.get(r.toolCallId);if(!e||e.isError)continue;let i=r.input??{};if("manage_skill"===r.toolName){let e=eQ(i.action);if(!0===eX[e]){let t={kind:"skill",action:e,name:eQ(i.name)};n(JSON.stringify(t),t)}continue}let a=eQ(i.memory),s=i.skill,l=s?{action:eQ(s.action),name:eQ(s.name)}:void 0;n(JSON.stringify({kind:"lesson",memory:a,skill:l}),{kind:"lesson",memory:a.length>160?`${a.slice(0,160)}…`:a,...l?{skill:l}:{}})}}(l.blocks??e.content??[],r,(e,t)=>{if(o.has(e))return;o.add(e);let n=a.get(s);n?n.push(t):a.set(s,[t])})}}return a}(g,x,e,n)){let e=i.map(e=>{if("skill"===e.kind)return C("chat.savedSkill",{action:e.action,name:e.name});let t=C("chat.savedLesson",{memory:e.memory});return e.skill?`${t} (${C("chat.savedSkill",e.skill)})`:t});t.set(r,{role:"custom",customType:eK,content:[C("chat.lessonsSaved"),...e.map(e=>`- ${e}`)].join("\n"),display:!0})}return t},[g,x,e,n,C]),$=(0,i.useMemo)(()=>{let t=null;if(o)for(let n of g)"message"===n.kind&&e[n.idx]?.role==="user"&&(t=n.idx);let r=new Map;for(let[i,a]of function(e,t,n){let r=new Map,i=e.filter(e=>"message"===e.kind&&t[e.idx]?.role==="user").map(e=>e.idx),a=new Map;for(let[s,l]of(e.forEach((e,t)=>{"answer"===e.kind&&a.set(e.anchorIdx,t)}),a)){if(s===n)continue;let e=i.find(e=>e>s);r.set(l,{from:s+1,to:e??t.length})}return r}(g,e,t))r.set(i,nU(function(e,t,n){let r=[];for(let i=Math.max(0,t);i<Math.min(e.length,n);i++){let t=e[i];"assistant"===t.role&&r.push(...t.content??[])}return r}(e,a.from,a.to),n,s));return r},[g,e,n,s,o]),R=y>0,E=w<g.length,L=(i,g={})=>{let x=g.messageOverride??e[i],v=i-1;for(;v>=0&&eG(t[v]);)v-=1;let b="user"===x.role&&v>=0&&"assistant"===e[v].role?t[v]:void 0,y=g.keyPrefix??"message",w=!1;if("assistant"===x.role){w=!0;for(let t=i+1;t<e.length;t++){let n=e[t].role;if("user"===n)break;if("assistant"===n){w=!1;break}}w&&c&&i===e.length-1&&(w=!1)}return void 0!==g.showTimestamp&&(w=g.showTimestamp),(0,r.jsx)(rO,{message:x,toolResults:n,modelNames:a,cwd:s,onOpenFile:l,entryId:t[i],onFork:o||d||0===i&&"user"===x.role?void 0:u,forking:p===t[i],onNavigate:o?void 0:h,prevAssistantEntryId:o?void 0:b,onEditContent:m,showTimestamp:w,prevTimestamp:i>0?e[i-1].timestamp:void 0,sessionId:f,writtenFiles:g.writtenFiles,dispatchSlot:g.dispatchSlot,turnSummary:g.turnSummary},`${y}-view-${i}`)},A=(t,n)=>{let i=g[t],a="message"===i.kind&&e[i.idx]?.role==="user";return(0,r.jsx)("div",{"data-chat-item":t,"data-chat-question":a?"":void 0,className:S===t?"chat-item chat-jump-flash":"chat-item",children:n})};return(0,r.jsxs)(r.Fragment,{children:[R&&(0,r.jsx)("div",{ref:k,className:"py-3 text-center text-xs text-text-muted",children:C("chat.loadEarlier",{count:y})}),g.slice(y,w).map((a,o)=>{let d=y+o,c=b?.position===d?(0,r.jsx)(n7,{calls:b.calls}):null,u="message"===a.kind?a.anchorIdx??a.idx:a.anchorIdx,p=g[d+1],h=p?"message"===p.kind?p.anchorIdx??p.idx:p.anchorIdx:null,m=p?p.idx:1/0,x=I.filter(n=>{let r=null!==n.anchorEntryId?t.indexOf(n.anchorEntryId):Math.min(n.liveIndex??-1,e.length-1);return r>=a.idx&&r<m}).map(e=>(0,r.jsx)(lS,{sticker:e.sticker,text:e.text,tag:e.tag,followRef:T},`cue-${e.id}`)),w=h!==u,k=M.get(d),j=k?(0,r.jsx)(rO,{message:k,cwd:s,onOpenFile:l},`saved-lessons-${d}`):null,S=w?(0,r.jsx)(iO,{turnIndex:u,turnEntryId:t[u],sessionId:f,cwd:s,onOpenFile:l}):null;if("message"===a.kind)return(0,r.jsxs)(i.Fragment,{children:[c,A(d,L(a.idx)),j,S,x]},`message-${a.idx}`);let C=e8(a.precedingBlocks,n,s);return(0,r.jsxs)(i.Fragment,{children:[c,A(d,L(a.idx,{keyPrefix:`answer-${a.runIndex}`,messageOverride:ez(e[a.idx],a.blocks),writtenFiles:C,dispatchSlot:v.get(d),turnSummary:$.get(d)})),j,S,x]},`answer-${a.idx}-${a.runIndex}`)}),b?.position===g.length&&w===g.length&&(0,r.jsx)(n7,{calls:b.calls}),E&&(0,r.jsx)("div",{ref:j,className:"py-3 text-center text-xs text-text-muted",children:C("chat.loadLater",{count:g.length-w})})]})});function lR({session:e,newSessionCwd:t,initialSessionData:a,transitioning:s=!1,onAgentEnd:l,onAttentionNeeded:o,onSessionCreated:d,onSessionForked:c,modelsRefreshKey:u,chatInputRef:p,onBranchDataChange:h,onSystemPromptChange:m,onSessionStatsChange:f,onSessionStatsPanelOpen:g,onContextUsageChange:x,onSubagentsChange:b,onMainIdentityChange:y,onOpenWorkspaceView:w,onOpenMaker:k,selectedMaker:j,onProcessLogChange:S,onOpenFile:C,transcriptReplacement:N,onComposerFocusChange:I,onSessionBusyChange:T,onWaitingChange:M,onAttentionChange:$,soundEnabled:E=!0,onSoundToggle:L,playCueSound:A=async()=>({sticker:null,text:null}),preloadCueSound:z,unlockAudio:P,jumpRequest:_=null,onJumpHandled:D}){var O,H;let B,U,q,{t:K}=(0,R.s)(),J=ly(),G=W(),Y=J&&G,Z=(0,i.useRef)(A);Z.current=A;let X=(0,i.useRef)(null),Q=(0,i.useRef)(z);Q.current=z;let[ee,et]=(0,i.useState)([]),en=(0,i.useRef)(ee);en.current=ee;let er=(0,i.useRef)(0),ei=(0,i.useRef)([]),ea=(0,i.useRef)([]),es=(0,i.useRef)(null),el=(0,i.useRef)(0),eo=(0,i.useRef)(-1),ed=(0,i.useRef)(-1),ec=(0,i.useCallback)(()=>{let e=es.current?.current;return e?{sessionId:e,turn:el.current}:null},[]),eu=(0,i.useCallback)(e=>es.current?.current===e.sessionId&&el.current===e.turn,[]),ep=(0,i.useCallback)((e,t,n,r)=>{if(!e.sticker&&!e.text)return;er.current=Math.max(er.current+1,Date.now());let i={id:er.current,sticker:e.sticker,text:e.text,tag:t,sessionId:n.sessionId},a="entry"===r.kind?{...i,anchorEntryId:r.entryId}:{...i,anchorEntryId:null,liveIndex:r.liveIndex,intent:r.intent};et(e=>{let t=[...e,a];return null!==a.anchorEntryId&&lI(n.sessionId,t),t})},[]),eh=(0,i.useCallback)((e,t,n,r)=>{let i=()=>eu(n)&&("working"!==t||ed.current!==n.turn);i()&&Z.current(e,t,i).then(e=>{null!==t&&null!==r&&i()&&ep(e,t,n,r)}).catch(()=>{})},[eu,ep]),em=(0,i.useCallback)(async(e,t,n)=>{let r=(await nh(e,t,n))?.alias??null;return r&&Q.current?.(r),r},[]),ef=(0,i.useCallback)((e,t,n,r)=>{let i=function(e,t){let n=e.length-1;if(n<0)return null;let r=Math.min(e.length,t.length);if(n<r)return{kind:"entry",entryId:t[n]};let i=iL(e[n]),a=0;for(let t=r;t<=n;t++)iL(e[t])===i&&(a+=1);return{kind:"pending",liveIndex:n,intent:{baseEntryId:r>0?t[r-1]:null,identity:i,occurrence:a}}}(ei.current,ea.current);em(t.sessionId,n,r).then(n=>{eh(n,e,t,i)})},[eh,em]),[eg,ex]=(0,i.useState)(0),ev=(0,i.useRef)([]),eb=(0,i.useCallback)(e=>{if(el.current+=1,null!==iI(e.outcome)){let t=e.sessionId;ev.current.push({completion:e,trigger:t?{sessionId:t,turn:el.current}:null}),ex(e=>e+1)}l?.(e)},[l]);(0,i.useEffect)(()=>{for(let{completion:e,trigger:t}of ev.current.splice(0)){let n=iI(e.outcome),r="neutral"===n?null:n;t?ef(r,t,e.provider,e.credentialId):Z.current(null,r).catch(()=>{})}},[eg,ef]);let ey=(0,i.useCallback)(e=>{p?.current?.replaceMessage(e)},[p]),{loading:ew,error:ek,messages:eS,entryIds:eC,streamState:eN,agentRunning:eI,bashRunning:eT,pendingBash:eM,modelNames:e$,modelList:eR,modelError:eE,modelScopeWarnings:eL,modelThinkingLevels:eA,modelThinkingLevelMaps:eP,modelRoles:eD,toolPreset:eO,thinkingLevel:eB,effectiveThinkingLevel:eU,thinkingCeiling:eK,fastMode:eX,fastModeBusy:eQ,handleFastModeToggle:e1,retryInfo:e2,contextUsage:e4,forkingEntryId:e5,isCompacting:e6,compaction:e8,compactError:e3,compactResult:e9,displayModel:te,modelSwitching:tt,sessionStats:tn,runStateKnown:tr,compactedWork:ti,slashCommands:ta,slashCommandsLoading:ts,deliveryRows:tl,subagents:to,todoPhases:td,notices:tc,extensionDialog:tu,extensionResponse:tp,extensionCustomUi:th,extensionStatuses:tm,extensionWidgets:tf,respondToExtensionUi:tg,sendExtensionCustomInput:tx,isAutoModelSelection:tv,agentPhase:tb,isNew:ty,autoFollowPaused:tw,resumeAutoFollow:tk,pauseAutoFollow:tj,goalStatus:tS,sessionIdRef:tC,messagesEndRef:tN,scrollContainerRef:tI,handleSend:tT,handleAbort:tM,handleFork:t$,handleNavigate:tR,handleModelChange:tE,handleRoleModelChange:tL,handleMainPresetChange:tA,newSessionAccount:tz,handleCompact:tP,handleSteer:tW,handleFollowUp:tF,handlePromptWithStreamingBehavior:t_,handleAbortCompaction:tD,handleRecallQueue:tO,handleRemoveQueuedMessage:tH,handleBuiltinSlashCommand:tB,handleToolPresetChange:tU,handleThinkingLevelChange:tq,loadSlashCommands:tK,ensureNewSession:tV,refreshLiveTranscript:tJ}=function(e){let{session:t,newSessionCwd:r,initialData:a,onAgentEnd:s,onAttentionNeeded:l,onSessionCreated:o,onSessionForked:d,modelsRefreshKey:c,onBranchDataChange:u,onSystemPromptChange:p,onSessionStatsPanelOpen:h}=e,m=null===t&&null!==r,f=a&&a.sessionId===t?.id?a:null,[g,x]=(0,i.useState)(f),[v,b]=(0,i.useState)(!m&&!f),[y,w]=(0,i.useState)(null),[k,j]=(0,i.useState)(f?.leafId??null),[S,C]=(0,i.useState)(f?.context.messages??[]),[N,I]=(0,i.useState)(f?.context.entryIds??[]),[T,M]=(0,i.useState)(f?.context.compactedWork??null),[$,R]=(0,i.useReducer)(s6,{isStreaming:!1,streamingMessage:null}),[E,L]=(0,i.useState)(!1),[A,z]=(0,i.useState)(!1),[P,W]=(0,i.useState)(null),[F,_]=(0,i.useState)({}),[D,O]=(0,i.useState)([]),[H,B]=(0,i.useState)(null),[U,q]=(0,i.useState)([]),[K,V]=(0,i.useState)({}),[J,G]=(0,i.useState)({}),[Y,Z]=(0,i.useState)([]),[X,Q]=(0,i.useState)(null),[ee,et]=(0,i.useState)(null),[en,er]=(0,i.useState)(null),[ei,ea]=(0,i.useState)("default"),[es,el]=(0,i.useState)(()=>{let e=f?.context.thinkingLevel;return e&&"off"!==e?e:"auto"}),[eo,ed]=(0,i.useState)(),[ec,eu]=(0,i.useState)(null),[ep,eh]=(0,i.useState)(null),[em,ef]=(0,i.useState)(!1),eg=(0,i.useRef)(0),ex=(0,i.useRef)(0),ev=(0,i.useRef)(""),[eb,ey]=(0,i.useState)(null),[ew,ek]=(0,i.useState)(f?.contextUsage??null),[eS,eC]=(0,i.useState)(null),[eN,eI]=(0,i.useState)(null),[eT,eM]=(0,i.useState)(null),[e$,eR]=(0,i.useState)(null),[eE,eL]=(0,i.useState)(!1),[eA,ez]=(0,i.useState)(!1),[eP,eW]=(0,i.useState)(null),[eF,e_]=(0,i.useState)(null),[eD,eO]=(0,i.useState)(null),eH=(0,i.useRef)(null),[eB,eU]=(0,i.useState)(!1),[eK,eV]=(0,i.useState)(null),[eZ,eX]=(0,i.useState)([]),[eQ,e0]=(0,i.useState)(!1),[e1,e2]=(0,i.useReducer)(ll,{visible:[],pending:[]}),[e4,e5]=(0,i.useState)(null),[e6,e8]=(0,i.useState)(null),[e3,e7]=(0,i.useState)(null),e9=(0,i.useRef)(null),[te,tt]=(0,i.useState)(null),[tn,tr]=(0,i.useState)([]),[ti,ta]=(0,i.useState)([]),[ts,tl]=(0,i.useState)({steering:[],followUp:[]}),[to,td]=(0,i.useState)([]),[tc,tu]=(0,i.useReducer)(i6,[]),tp=(0,i.useRef)(0);(0,i.useEffect)(()=>{tu({type:"queue",steering:ts.steering,followUp:ts.followUp})},[ts]),(0,i.useEffect)(()=>{E||tu({type:"idle"})},[E]),(0,i.useEffect)(()=>{tu({type:"reset"})},[t?.id]);let th=(0,i.useMemo)(()=>(function(e,t){let n=new Map;for(let t of e){if(!t.inQueue)continue;let e=`${t.kind}\u0000${i4(t)}`;n.set(e,(n.get(e)??0)+1)}let r=[],i=(e,t)=>{t.forEach((t,i)=>{let a=`${e}\u0000${i2(t)}`,s=n.get(a)??0;s>0?n.set(a,s-1):r.push({key:`queue-${e}-${i}`,kind:e,text:t,images:0,stage:"accepted",removable:!0})})};for(let n of(i("steer",t?.steering??[]),i("followUp",t?.followUp??[]),e))r.push({key:`sent-${n.id}`,kind:n.kind,text:n.text,images:n.images,stage:n.stage,removable:n.inQueue});return r})(tc,ts),[tc,ts]),[tm,tf]=(0,i.useState)(null),tg=(0,i.useRef)(null),tx=(0,i.useRef)(null),tv=(0,i.useRef)(null),tb=(0,i.useRef)(null),ty=(0,i.useRef)(null),tw=(0,i.useRef)(0),tk=(0,i.useRef)(!1),tj=(0,i.useRef)(t?.id??null),tS=(0,i.useRef)(f?.leafId??null),tC=(0,i.useRef)(S),tN=(0,i.useRef)(N);tC.current=S,tN.current=N;let tI=(0,i.useRef)({sessionId:t?.id??null,outputs:[],seq:0}),tT=(0,i.useRef)(!1),tM=(0,i.useRef)(!1),t$=(0,i.useRef)(!1),tR=(0,i.useRef)(-1),tE=(0,i.useRef)("unknown"),tL=(0,i.useRef)(null),tA=(0,i.useRef)(null),tz=(0,i.useRef)(0),tP=(0,i.useRef)(!1),tW=(0,i.useRef)(0),tF=(0,i.useRef)(null),t_=(0,i.useRef)(null),tD=(0,i.useRef)(null),tO=(0,i.useRef)(!1),tH=(0,i.useRef)(!0),[tB,tU]=(0,i.useState)(!1),[tq,tK]=(0,i.useState)(null),tV=(0,i.useRef)(void 0),tJ=(0,i.useRef)(0),tG=(0,i.useRef)(0),tY=(0,i.useRef)(()=>{}),tZ=(0,i.useRef)(null),tX=(0,i.useRef)(null),tQ=(0,i.useRef)(null),t0=(0,i.useRef)(null),t1=(0,i.useRef)(!1),t2=(0,i.useRef)(null),t4=(0,i.useRef)(null),t5=(0,i.useRef)(null),t6=(0,i.useRef)(null),t8=(0,i.useRef)(0),t3=(0,i.useRef)(null),t7=(0,i.useRef)(null),t9=(0,i.useRef)(!1);t9.current=e.transitioning??!1;let ne=(0,i.useRef)(Date.now()),nt=(0,i.useRef)(0),nn=(0,i.useRef)(0),nr=(0,i.useRef)(null),ni=(0,i.useRef)(!1),na=(0,i.useRef)(Promise.resolve()),ns=e.setToolPreset??ea,nl=eT??g?.context.model??e$??null,no=m?X??en:nl,nd=(0,i.useMemo)(()=>{if(e4)return{...e4,totalActiveMs:g?.totalActiveMs};let e={input:0,output:0,cacheRead:0,cacheWrite:0,total:0},n=0,r=0,i=0,a=0,s=0;for(let t of S){if("user"===t.role&&(r+=1),"toolResult"===t.role&&(a+=1),"assistant"!==t.role)continue;i+=1;let l=t.usage;s+=t.content.filter(e=>"toolCall"===e.type).length,l&&(e.input+=l.input??0,e.output+=l.output??0,e.cacheRead+=l.cacheRead??0,e.cacheWrite+=l.cacheWrite??0,n+=l.cost?.total??0)}return(e.total=e.input+e.output+e.cacheRead+e.cacheWrite,0===e.total&&0===S.length)?null:{sessionFile:g?.filePath||void 0,sessionId:tj.current??t?.id??"",sessionName:t?.name,userMessages:r,assistantMessages:i,toolCalls:s,toolResults:a,totalMessages:S.length,tokens:e,cost:n,totalActiveMs:g?.totalActiveMs,...ew?{contextUsage:ew}:{}}},[S,e4,ew,g?.filePath,g?.totalActiveMs,t?.id,t?.name]),nc=(0,i.useRef)(0),nu=(0,i.useCallback)((e,t)=>{e&&tj.current===e&&Array.isArray(t)&&(nc.current+=1,tf(n=>n?.sid===e&&s9(n.phases,t)?n:{sid:e,phases:t}))},[]),np=(0,i.useCallback)((e,t,n)=>{tj.current===e&&nc.current===n&&Array.isArray(t)&&tf(n=>n?.sid===e&&s9(n.phases,t)?n:{sid:e,phases:t})},[]),nh=(0,i.useCallback)(e=>{let t="function"==typeof e?e(tC.current):e;tC.current=t,C(t)},[]),nm=(0,i.useCallback)(e=>{tN.current=e,I(e)},[]),nf=(0,i.useCallback)(async(e,t=!1,n=!1,r)=>{let i=!1;try{t&&b(!0);let a=r??null;if(!a){let n=new URLSearchParams({deferThinking:"1",deferMedia:"1"}),r=await fetch(`/api/sessions/${encodeURIComponent(e)}?${n}`);if(404===r.status)return t&&(x(null),j(null),nh([]),M(null),w(null)),null;if(!r.ok)throw Error(`HTTP ${r.status}`);a=await r.json()}if(tj.current!==e)return null;x(a),j(a.leafId),tS.current=a.leafId??null;let s=eY(a.context.messages,a.context.entryIds??[],tI.current.sessionId===e?tI.current.outputs:[]);nh(s.messages),nm(s.entryIds),M(a.context.compactedWork??null),ek(a.contextUsage??null),eM(e=>ni.current?e:null),w(null);let l=!n&&t6.current===e;if(l||(el(a.context.configuredThinkingLevel??a.context.thinkingLevel??"off"),ed(a.context.thinkingLevel)),eu(a.context.thinkingCeiling??null),i=!0,t&&b(!1),!n){if(l)try{let t=t8.current,n=await fetch(`/api/sessions/${encodeURIComponent(e)}/state`);if(n.ok&&tj.current===e){let r=await n.json();tj.current===e&&t8.current===t&&(r.state?.thinkingLevel!==void 0?(el(r.state.configuredThinkingLevel??r.state.thinkingLevel),ed(r.state.thinkingLevel)):r.running||(t6.current=null,el(a.context.configuredThinkingLevel??a.context.thinkingLevel??"off"),ed(a.context.thinkingLevel)))}}catch(e){console.error("Failed to refresh live thinking level:",e)}return null}try{let t=nc.current,n=await fetch(`/api/sessions/${encodeURIComponent(e)}/state`);if(!n.ok)throw Error(`HTTP ${n.status}`);let r=await n.json();if(tj.current!==e)return null;let i=r.state;return i?(void 0!==i.contextUsage&&ek(i.contextUsage??null),void 0!==i.systemPrompt&&eC(i.systemPrompt??null),void 0!==i.thinkingLevel&&(t6.current=e,el(i.configuredThinkingLevel??i.thinkingLevel),ed(i.thinkingLevel)),void 0!==i.thinkingCeiling&&eu(i.thinkingCeiling??null),void 0!==i.extensionStatuses&&tr(i.extensionStatuses??[]),void 0!==i.extensionWidgets&&ta(i.extensionWidgets??[]),void 0!==i.queuedMessages&&tl(s8(i.queuedMessages)),void 0!==i.subagents&&td(e=>s5(e,i.subagents??[])),np(e,i.todoPhases,t)):r.running||tl({steering:[],followUp:[]}),r}catch(e){return console.error("Failed to load agent state:",e),null}}catch(e){return w(String(e)),null}finally{t&&!i&&b(!1)}},[np,nm,nh]),ng=(0,i.useCallback)(e=>{let t=na.current.then(async()=>{tj.current===e&&await nf(e)});return na.current=t.catch(()=>{}),t},[nf]),nx=(0,i.useCallback)(async(e,t)=>{let n=++ex.current;try{let r=new URLSearchParams({deferThinking:"1",deferMedia:"1"});t&&r.set("leafId",t);let i=`/api/sessions/${encodeURIComponent(e)}/context?${r}`,a=await fetch(i);if(!a.ok)throw Error(`HTTP ${a.status}`);let s=await a.json();if(ex.current!==n||tj.current!==e)return;tS.current=t;let l=eY(s.context.messages,s.context.entryIds??[],tI.current.sessionId===e?tI.current.outputs:[]);nh(l.messages),nm(l.entryIds),M(s.context.compactedWork??null),ek(s.contextUsage??null)}catch(e){console.error("Failed to load context:",e)}},[nm,nh]),nv=(0,i.useCallback)(async e=>{try{let t=await sB(e,{type:"get_tools"});if(t){let{getPresetFromTools:e}=await Promise.resolve().then(n.bind(n,14755));ns(e(t))}}catch(e){console.error("Failed to load tools:",e)}},[ns]),nb=(0,i.useCallback)((e=0,t="(no messages)")=>{let n=tj.current;m&&r&&n&&!t1.current&&(t1.current=!0,o?.({id:n,path:"",cwd:r,name:void 0,created:new Date().toISOString(),modified:new Date().toISOString(),messageCount:e,firstMessage:t,transient:!0}))},[m,r,o]),ny=(0,i.useCallback)(async()=>{if(tQ.current)return tQ.current;let e=tj.current;if(e&&t7.current!==e||!e&&(!m||!r))return e;let t=(async()=>{let t=e;if(!t){let e=t2.current,n=t5.current,i=t4.current;e&&eR(e);let a={cwd:r,type:"ensure_session",toolNames:(0,a7.xG)(ei),...e?{provider:e.provider,modelId:e.modelId}:{},...n?{thinkingLevel:n}:{},...e&&null!==i?{oauthPosition:i}:{}},s=JSON.stringify(a),l=t0.current,o=l?.body===s?l.createRequestId:li();t0.current={body:s,createRequestId:o};let d=await fetch("/api/agent/new",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...a,createRequestId:o})});if(!d.ok)throw Error(`HTTP ${d.status}`);let c=await d.json();t0.current=null,t=c.sessionId,tj.current=t,null!==t3.current&&(t7.current=t),c.model&&t2.current===e&&(eR(c.model),e||er(c.model)),c.thinkingLevel&&t5.current===n&&(el(c.configuredThinkingLevel??c.thinkingLevel),ed(c.thinkingLevel))}for(;t7.current===t;){let e=t3.current;await sB(t,{type:"set_thinking_ceiling",ceiling:e}),t3.current===e&&t7.current===t&&(t7.current=null)}return t})();tQ.current=t;try{return await t}finally{tQ.current=null}},[m,r,ei]),nw=(0,i.useCallback)(async()=>{let e=tj.current??await ny();if(!e)return eX([]),[];e0(!0);try{let t=await sB(e,{type:"get_commands"}),n=t?.commands??[];return eX(n),n}catch(e){return console.error("Failed to load slash commands:",e),eX([]),[]}finally{e0(!1)}},[ny]),nk=(0,i.useCallback)(()=>{tw.current+=1,tk.current=!1,ty.current&&(clearTimeout(ty.current),ty.current=null)},[]),nj=(0,i.useCallback)(()=>{tg.current?.close(),tg.current=null,tx.current=null,tv.current=null},[]),nS=(0,i.useCallback)(()=>{tb.current?.close(),tb.current=null},[]),nC=(0,i.useCallback)(e=>{nS();let t=new EventSource(`/api/agent/${encodeURIComponent(e)}/events?entries=1`);tb.current=t,t.onmessage=t=>{try{let n=JSON.parse(t.data);"session_snapshot"===n.type?tF.current?.(n):"agent_start"===n.type&&t_.current?.(e)}catch{}}},[nS]),nN=(0,i.useCallback)(e=>{nj();let t=new EventSource(`/api/agent/${encodeURIComponent(e)}/events`);tg.current=t,tx.current=e;let n=new Promise(n=>{let r=!1,i=e=>{r||(r=!0,clearTimeout(a),tv.current?.source===t&&(tv.current.pending=!1),n({status:e,source:t}))},a=setTimeout(()=>i("timeout"),5e3);t.onmessage=e=>{try{let t=JSON.parse(e.data);"update_maintenance"===t.type&&window.dispatchEvent(new CustomEvent("ompweb:update-maintenance",{detail:t})),"connected"===t.type&&i("connected"),tF.current?.(t)}catch{}},t.onerror=()=>{if(t.readyState===EventSource.CLOSED&&(i("closed"),tg.current===t&&(tT.current||tk.current))){tg.current=null,tx.current=null,tv.current=null;let t=tw.current;setTimeout(()=>{t===tw.current&&!tg.current&&(tT.current||tk.current)&&nN(e)},1e3)}}});return tv.current={source:t,promise:n,pending:!0},n},[nj]),nI=(0,i.useCallback)(async e=>{let t=tg.current;if(t&&tx.current===e){if(t.readyState===EventSource.OPEN)return;let e=tv.current;if(e?.source===t&&e.pending&&(await e.promise,tg.current===t&&t.readyState===EventSource.OPEN))return}let n=await nN(e);if("connected"!==n.status&&n.source.readyState!==EventSource.OPEN)throw tg.current===n.source&&(tg.current=null),tx.current===e&&(tx.current=null),tv.current?.source===n.source&&(tv.current=null),n.source.close(),new lr(n.status)},[nN]),nT=(0,i.useCallback)(async(e,t)=>{let n=e9.current;if(n?.id===e.id&&"sending"===n.status)return;let r=tj.current,i=e=>{e9.current=e,e7(e)};if(!r)return void i({id:e.id,status:"failed",error:"no session"});i({id:e.id,status:"sending"});try{await sB(r,{type:"extension_ui_response",id:e.id,...t})}catch(t){i({id:e.id,status:"failed",error:t instanceof Error?t.message:String(t)});return}i(null),e8(t=>t?.id===e.id?null:t)},[]),nM=(0,i.useCallback)(async(e,t)=>{let n=tj.current;if(n)try{await sB(n,{type:"extension_ui_input",id:e.id,data:t})}catch(e){console.error("Failed to send extension custom UI input:",e)}},[]),n$=(0,i.useCallback)(e=>{let t=e.message.trim();t&&e2({type:"add",notice:{id:e.id??li(),message:t,type:e.type??"info"}})},[]),nR=(0,i.useCallback)(e=>{let t={role:"custom",customType:eq,content:ej(e).trim(),display:!0,timestamp:Date.now()},n=tI.current,r=tj.current;n.sessionId!==r&&(n.sessionId=r,n.outputs=[]);let i=tN.current.slice(0,tC.current.length),a=null;for(let e=i.length-1;e>=0;e--)if(!eG(i[e])){a=i[e];break}n.seq+=1,n.outputs.push({entryId:`${eJ}${n.seq}`,baseEntryId:a,message:t}),nh(e=>[...e,t])},[nh]),nE=(0,i.useCallback)(t=>{if("custom"!==t.method&&"closed"in t&&t.closed){e8(e=>e?.id===t.id?null:e),e9.current?.id===t.id&&(e9.current=null,e7(null));return}switch(s_(t)&&l?.(t),t.method){case"select":case"confirm":case"input":case"editor":case"ask":case"plan_review":e8(t);break;case"notify":n$({id:t.id,message:t.message,type:t.notifyType??"info"});break;case"setStatus":tr(e=>{let n=e.filter(e=>e.key!==t.statusKey);return void 0!==t.statusText?[...n,{key:t.statusKey,text:t.statusText}]:n});break;case"setWidget":ta(e=>{let n=e.filter(e=>e.key!==t.widgetKey);return t.widgetLines?[...n,{key:t.widgetKey,lines:t.widgetLines,placement:t.widgetPlacement??"aboveEditor"}]:n});break;case"setTitle":t.title&&(document.title=t.title);break;case"set_editor_text":e.chatInputRef?.current?.insertText(t.text);break;case"custom":tt(e=>t.closed?e?.id===t.id?null:e:t)}},[n$,l,e.chatInputRef]),nL=(0,i.useCallback)(()=>{let e=tT.current;return tT.current=!1,L(!1),eV(null),ey(null),R({type:"end"}),e},[]),nA=(0,i.useCallback)(()=>{tE.current="unknown",tL.current=null;let e=lt(tC.current,tN.current);tA.current=e?{entryId:e.entryId,key:lc(e.message)}:null,tz.current+=1},[]),nz=(0,i.useCallback)(()=>{let e=tE.current,t=tL.current;if("unknown"===e){let n=lt(tC.current,tN.current),r=n?.message,i=tA.current;null!==n&&(null===i||(null!==n.entryId&&null!==i.entryId?n.entryId!==i.entryId:lc(n.message)!==i.key))&&r?.role==="assistant"&&r.stopReason&&(e=le(r),t??={provider:r.provider,...void 0!==r.credentialId?{credentialId:r.credentialId}:{}})}return{outcome:e,sessionId:tj.current,...t?{provider:t.provider,...void 0!==t.credentialId?{credentialId:t.credentialId}:{}}:{}}},[]),nP=(0,i.useCallback)(e=>{let t=nz();if("unknown"!==t.outcome||!e)return void s?.(t);let n=tz.current;e.catch(()=>void 0).then(()=>{let e=tj.current===t.sessionId&&tz.current===n;s?.(e?nz():t)})},[s,nz]),nW=(0,i.useCallback)((e,t)=>tR.current!==e&&(tR.current=e,nP(t),!0),[nP]),nF=(0,i.useCallback)(e=>{nk(),tk.current=!0;let t=tw.current,n=async()=>{if(t===tw.current&&tj.current===e&&tk.current)try{let r=nc.current,i=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(!i.ok)throw Error(`HTTP ${i.status}`);let a=await i.json();if(t!==tw.current||tj.current!==e||!tk.current)return;let s=a.state;if(td(e=>s5(e,s?.subagents??[])),np(e,s?.todoPhases,r),a.running&&s&&(s.isStreaming||s.isPromptRunning||s.isHandoffRunning)){tk.current=!1,ty.current=null,tM.current=!!s?.isStreaming,t$.current=!!s?.isPromptRunning,tT.current=!0,L(!0),eV(s?.isStreaming?{kind:"waiting_model"}:{kind:"running_command"});return}if(a.running&&s?.isCompacting){ez(!0),eO(s7(s)),ty.current=setTimeout(()=>void n(),600);return}if(a.running&&(s?.subagents?.length??0)>0){ty.current=setTimeout(()=>void n(),1e3);return}tk.current=!1,ty.current=null,nj()}catch{if(t!==tw.current||tj.current!==e||!tk.current)return;ty.current=setTimeout(()=>void n(),600)}};ty.current=setTimeout(()=>void n(),3e4)},[np,nk,nj]),n_=(0,i.useCallback)(async(e=tj.current,t=nt.current)=>{if(nt.current===t)try{e&&await nf(e)}finally{if(nt.current!==t)return;let n=t$.current,r=tM.current;t$.current=!1,tM.current=!1,nr.current=null;let i=nL();n?nW(t):r&&i&&nP(),e&&nF(e)}},[nf,nP,nW,nF,nL]),nD=(0,i.useCallback)(async(e,t)=>{await la(800);let n=Date.now();for(;tT.current&&Date.now()-n<2e4;){if(void 0!==t&&nt.current!==t)return;try{let n=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(n.ok){let r=await n.json(),i=r.state;if(!r.running||!i||!i.isStreaming&&!i.isPromptRunning)return void await n_(e,t)}}catch{}await la(600)}},[n_]),nO=(0,i.useCallback)(async e=>{let t=tW.current+1;for(tW.current=t;tP.current&&tW.current===t&&tj.current===e;){await la(1e3);try{let n=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(!n.ok)continue;let r=await n.json();if(r.state?.isBashRunning)continue;if(await nf(e),tW.current!==t||tj.current!==e)return;tP.current=!1,z(!1),W(null);return}catch{}}},[nf]),nH=(0,i.useCallback)(async e=>{if(!tT.current)return;let t=nt.current;try{let n=nc.current,r=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(!r.ok)return;let i=await r.json();if(nt.current!==t)return;let a=i.state;if(ez(a?.isCompacting??!1),eO(s7(a)),tl(s8(a?.queuedMessages)),a?.contextUsage!==void 0&&ek(a.contextUsage??null),td(e=>s5(e,a?.subagents??[])),np(e,a?.todoPhases,n),i.running&&a&&(a.isStreaming||a.isPromptRunning||a.isCompacting||a.isHandoffRunning)||!tT.current)return;a&&(void 0!==a.systemPrompt&&eC(a.systemPrompt??null),void 0!==a.extensionStatuses&&tr(a.extensionStatuses??[]),void 0!==a.extensionWidgets&&ta(a.extensionWidgets??[])),await n_(e,t)}catch{}},[np,n_]),nB=(0,i.useCallback)(async e=>{let t=await nf(e,!1,!0),n=t?.state;return!!t?.running&&!!n&&tj.current===e&&!tT.current&&!!(n.isStreaming||n.isPromptRunning||n.isHandoffRunning)&&(tM.current=!!n.isStreaming,t$.current=!!n.isPromptRunning,tT.current=!0,L(!0),eV(n.isStreaming?{kind:"waiting_model"}:{kind:"running_command"}),R({type:"start"}),nN(e),!n.isStreaming&&n.isPromptRunning&&nD(e),!0)},[nN,nf,nD]),nU=(0,i.useCallback)(async(e,t=nt.current)=>{let n=nn.current+1;nn.current=n;try{let r=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(!r.ok)return;let i=await r.json();if(n!==nn.current||tj.current!==e||nt.current!==t)return;i.state?.contextUsage!==void 0&&ek(i.state.contextUsage??null)}catch{}},[]);(0,i.useEffect)(()=>{if(!eA){eH.current=null,eO(null);return}eO(e=>e??{startedAt:Date.now(),reason:eH.current})},[eA]),(0,i.useEffect)(()=>{if(!E&&!eA)return;let e=()=>{let e=tj.current;e&&nU(e)};e();let t=setInterval(e,1e3);return()=>clearInterval(t)},[E,eA,nU]),(0,i.useEffect)(()=>{if(!E)return;let e=()=>{let e=tj.current;e&&nH(e)},t=()=>{"visible"===document.visibilityState&&e()},n=setInterval(e,15e3);return document.addEventListener("visibilitychange",t),window.addEventListener("online",e),()=>{clearInterval(n),document.removeEventListener("visibilitychange",t),window.removeEventListener("online",e)}},[E,nH]),(0,i.useEffect)(()=>{if(E)return;let e=()=>{let e=tj.current;e&&!tT.current&&nB(e)},t=()=>{"visible"===document.visibilityState&&e()},n=e=>{let t=tj.current,n=e.detail?.sessionId;t&&n===t&&!tT.current&&nB(t).then(e=>{e||tj.current!==t||tT.current||nf(t)})};return document.addEventListener("visibilitychange",t),window.addEventListener("online",e),window.addEventListener(sG,n),()=>{document.removeEventListener("visibilitychange",t),window.removeEventListener("online",e),window.removeEventListener(sG,n)}},[E,nB,nf]),t_.current=e=>{if(tj.current!==e||tT.current||tg.current||tD.current)return;let t=nB(e).then(async t=>{t||tj.current!==e||tT.current||await nf(e)}).catch(()=>{}).finally(()=>{tD.current===t&&(tD.current=null)});tD.current=t},(0,i.useEffect)(()=>{tT.current=E},[E]),tF.current=(0,i.useCallback)(e=>{switch(e.type){case"session_snapshot":{let t=function(e,t,n,r,i){if("session_snapshot"!==e.type||"string"!=typeof e.sessionId||e.sessionId!==t||"string"!=typeof e.entryId||""===e.entryId||e.entryId===n||!e.context||!Array.isArray(e.context.messages)||!Array.isArray(e.context.entryIds)||e.context.messages.length!==e.context.entryIds.length)return null;let a=e.context.messages,s=new Map;for(let e of a){let t=lc(e);s.set(t,(s.get(t)??0)+1)}let l=Math.min(r.length,i.length);for(let e of r.slice(0,l)){let t=lc(e),n=s.get(t)??0;n>0&&s.set(t,n-1)}let o=r.slice(l).filter(e=>{let t=lc(e),n=s.get(t)??0;return 0===n||(s.set(t,n-1),!1)});return{entryId:e.entryId,messages:[...a,...o],entryIds:[...e.context.entryIds],compactedWork:e.context.compactedWork??null}}(e,tj.current,tS.current,tC.current,tN.current);if(!t)break;tS.current=t.entryId;let n=eY(t.messages,t.entryIds,tI.current.sessionId===tj.current?tI.current.outputs:[]);nh(n.messages),nm(n.entryIds),M(t.compactedWork);break}case"agent_start":{let e=!tT.current;nk(),e&&nA(),tM.current=!0,tT.current=!0,L(!0),eV({kind:"waiting_model"}),R({type:"start"});break}case"agent_end":if(!tT.current)break;if(eV(null),ey(null),R({type:"end"}),tj.current){nf(tj.current);let e=nc.current;fetch(`/api/agent/${encodeURIComponent(tj.current)}`).then(e=>e.json()).then(t=>{t.state?.contextUsage!==void 0&&ek(t.state.contextUsage??null),t.state?.systemPrompt!==void 0&&eC(t.state.systemPrompt??null),t.state?.extensionStatuses!==void 0&&tr(t.state.extensionStatuses??[]),t.state?.extensionWidgets!==void 0&&ta(t.state.extensionWidgets??[]),t.state?.subagents!==void 0&&td(e=>s5(e,t.state?.subagents??[])),tj.current&&np(tj.current,t.state?.todoPhases,e),t.state?.goal!==void 0&&tK(t.state.goal??null),tl(s8(t.state?.queuedMessages))}).catch(()=>{})}break;case"goal_status":tK(e.status??null);break;case"agent_settled":{let e=tM.current;if(tM.current=!1,!e||t$.current)break;let t=tj.current,n=nL();ez(!1);let r=t?nf(t):void 0;t&&nF(t),n&&nP(r);break}case"prompt_done":{let e=nt.current,t=t$.current;t$.current=!1,nr.current=null;let n=tR.current!==e;if(!t&&!n)break;let r=tj.current;nW(e,r?nf(r):void 0),!tM.current&&(nL(),r&&nF(r))}break;case"prompt_error":tE.current="failed",n$({type:"error",message:e.errorMessage??"Command failed"});break;case"extension_error":tE.current="failed",n$({type:"error",message:e.error??"Extension command failed"});break;case"message_start":case"message_update":{if(!tT.current)break;let t=e.message;if(t?.role!=="assistant")break;t&&R({type:"update",message:(0,sO.B)(t)}),eV(null);break}case"message_end":{if(!tT.current)break;let t=e.message;if(t?.role==="assistant"&&(tL.current={provider:t.provider,...void 0!==t.credentialId?{credentialId:t.credentialId}:{}},tE.current=le(t)),t&&"user"===t.role){let e=(0,sO.B)(t),n=ld(e),r=nr.current;nr.current=null,nh(t=>{let i=t[t.length-1];return r&&i?.role==="user"&&ld(i)===r?r===n?t:[...t.slice(0,-1),e]:[...t,e]}),r||tu({type:"user-message",kind:"steering"in e&&!0===e.steering?"steer":"followUp",text:"user"!==e.role?"":"string"==typeof e.content?e.content:e.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n"),images:"user"!==e.role||"string"==typeof e.content?0:e.content.filter(e=>"image"===e.type).length})}else t&&nh(e=>[...e,(0,sO.B)(t)]);let n=tj.current;n&&nU(n),R({type:"reset"}),eV({kind:"waiting_model"});break}case"thinking_level_changed":{let t=tj.current,n=e.thinkingLevel;t&&void 0!==n&&(t6.current=t,t8.current+=1,el(e.configured??n),ed(n));break}case"todo_changed":nu(tj.current,e.phases);break;case"tool_execution_start":{let t=e.toolCallId,n=e.toolName,r=e.args;eV(e=>{let i=e?.kind==="running_tools"?[...e.tools]:[];return i.some(e=>e.id===t)||i.push({id:t,name:n,args:r}),{kind:"running_tools",tools:i}});break}case"tool_execution_end":{let t=e.toolCallId;eV(e=>{if(e?.kind!=="running_tools")return e;let n=e.tools.filter(e=>e.id!==t);return 0===n.length?{kind:"waiting_model"}:{kind:"running_tools",tools:n}});break}case"subagent_lifecycle":{let t=e.payload;if(!t?.id)break;if("started"!==t.status){let e="failed"===t.status?"failed":"aborted"===t.status?"aborted":"completed";td(n=>{let r=n.find(e=>e.id===t.id);return s5(n,[{id:t.id,index:t.index??r?.index??0,agent:t.agent??r?.agent??t.id,agentSource:t.agentSource??r?.agentSource??"bundled",description:t.description??r?.description,status:e,task:r?.task,assignment:r?.assignment,sessionFile:t.sessionFile??r?.sessionFile,parentToolCallId:t.parentToolCallId??r?.parentToolCallId,lastUpdate:Date.now(),progress:r?.progress?{...r.progress,status:e}:void 0}])});break}let n={id:t.id,index:t.index??0,agent:t.agent??t.id,agentSource:t.agentSource??"bundled",description:t.description,status:"running",sessionFile:t.sessionFile,parentToolCallId:t.parentToolCallId,lastUpdate:Date.now()};td(e=>s5(e,[n]));break}case"subagent_progress":{let t=e.payload;if(!t?.progress)break;let n=t.progress,r={id:n.id,index:t.index??n.index,agent:t.agent??n.agent,agentSource:t.agentSource??"bundled",description:n.description,status:n.status,task:t.task??n.task,assignment:t.assignment??n.assignment,sessionFile:t.sessionFile,parentToolCallId:t.parentToolCallId,lastUpdate:Date.now(),progress:n};td(e=>s5(e,[r]));break}case"queue_update":tl({steering:[...e.steering??[]],followUp:[...e.followUp??[]]});break;case"auto_retry_start":ey({attempt:e.attempt,maxAttempts:e.maxAttempts,errorMessage:e.errorMessage});break;case"auto_retry_end":ey(null);break;case"auto_compaction_start":case"compaction_start":if("string"==typeof e.reason){eH.current=e.reason;let t=e.reason;eO(e=>e?{...e,reason:t}:e)}ez(!0),eW(null),e_(null);break;case"auto_compaction_end":case"compaction_end":if(ez(!1),e.errorMessage)eW(e.errorMessage),e_(null);else if(!e.aborted){e_(lu(e.result,e.reason??"auto"));let t=tj.current;t&&(nf(t),nU(t))}break;case"extension_ui_request":nE(e)}},[n$,nu,np,nk,nE,nf,nP,nW,nU,nA,nF,nL,nm,nh]);let nq=(0,i.useCallback)(async(n,i,a)=>{let s=n.trim();if(!s&&!i?.length&&!a?.length)return"returned";if(tT.current||tP.current||ni.current)return"unknown";let l=rg(n,a??[]),o=!i?.length&&!a?.length&&s.startsWith("/");if(!i?.length&&!a?.length&&s.startsWith("!")){let e=s.startsWith("!!"),t=(e?s.slice(2):s.slice(1)).trim();return t?(await tV.current?.(t,e),"accepted"):"unknown"}nA();let d=nt.current+1;nk(),t$.current=!0;let c=i?.map(e=>({type:"image",source:{type:"base64",media_type:e.mimeType,data:e.data}})),u={role:"user",content:c?.length?[...l.trim()?[{type:"text",text:l}]:[],...c]:l,timestamp:Date.now()};nh(e=>[...e,u]),nr.current=ld(u),nt.current=d,tT.current=!0,L(!0),eV(o?{kind:"running_command"}:{kind:"waiting_model"}),R({type:"start"}),tY.current(!0);let p=i?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),h=null,f=!1,g="unknown";try{if(m&&r){let e=tj.current??await tQ.current,t=await ny();t&&(h=t,X&&(eR(X),e&&await sB(t,{type:"set_model",provider:X.provider,modelId:X.modelId})),await nI(t),f=!0,await sB(t,{type:"prompt",message:l,...p?.length?{images:p}:{}}),nb(1,n),g="accepted")}else t&&(h=t.id,await nI(t.id),f=!0,await sB(t.id,{type:"prompt",message:l,...p?.length?{images:p}:{}}),g="accepted");return o&&h&&nD(h,d),g}catch(l){console.error("Failed to send message:",l);let r=l instanceof sH&&"update_draining"===l.code&&!1===l.accepted;if(!(!f||l instanceof sH&&"prompt_rejected"===l.code&&!1===l.accepted||r)&&h)return nD(h,d),"unknown";t$.current=!1,tT.current=!1,nj();let s=nr.current;return s&&nh(e=>{let t=e[e.length-1];return t?.role==="user"&&ld(t)===s?e.slice(0,-1):e}),n$({type:"error",message:l instanceof Error?l.message:String(l)}),e.chatInputRef?.current?.restoreSubmission?.(n,lp(i),a,t?.id??h??void 0),nr.current=null,L(!1),eV(null),R({type:"end"}),"returned"}},[m,r,X,t,ny,nI,nb,nD,n$,nk,nj,e.chatInputRef,nA,nh]);tV.current=(0,i.useCallback)(async(n,r)=>{if(tT.current||tP.current)return;let i=`${r?"!!":"!"}${n}`;tP.current=!0,tY.current(!0),W({command:n,excludeFromContext:r}),z(!0);try{let e=tj.current??t?.id??await ny();if(!e)throw Error("Unable to create a session for the shell command");await sB(e,{type:"bash",command:n,excludeFromContext:r}),await nf(e),nb(1,i)}catch(t){console.error("Failed to execute shell command:",t),n$({type:"error",message:t instanceof Error?t.message:String(t)}),e.chatInputRef?.current?.insertIfEmpty(i)}finally{tP.current=!1,W(null),z(!1)}},[n$,ny,nf,e.chatInputRef,nb,t]);let nK=(0,i.useCallback)(async()=>{let e=tj.current;if(e){if(tP.current){try{await sB(e,{type:"abort_bash"})}catch(e){console.error("Failed to abort bash:",e)}return}try{await sB(e,{type:"abort"}),tE.current="aborted"}catch(e){console.error("Failed to abort:",e)}}},[]),nV=(0,i.useCallback)(async e=>{if(tP.current)return{forked:!1,error:"Cannot fork while a shell command is running"};let t=tj.current;if(!t)return{forked:!1,error:"No active session to fork"};eI(e??null);try{let{cancelled:n,newSessionId:r}=await sB(t,{type:"fork",...e?{entryId:e}:{}})??{};if(!n&&r)return d?.(r),{forked:!0};return{forked:!1,error:"Fork was cancelled"}}catch(e){return console.error("Fork failed:",e),{forked:!1,error:e instanceof Error?e.message:String(e)}}finally{eI(null)}},[d]),nJ=(0,i.useCallback)(async e=>{if(tP.current)return;let t=tj.current;t&&(sB(t,{type:"navigate_tree",targetId:e}).catch(()=>{}),j(e),await nx(t,e))},[nx]),nG=(0,i.useCallback)(async e=>{if(tP.current)return;j(e);let t=tj.current;t&&(await nx(t,e),e&&sB(t,{type:"navigate_tree",targetId:e}).catch(()=>{}))},[nx]),nY=(0,i.useCallback)(async(e,t)=>{if(m){let n={provider:e,modelId:t},r=t2.current?.provider===e;t2.current=n,r||(t4.current=null,et(null)),Q(n),eR(n);let i=tj.current??await tQ.current;if(!i)return;try{await sB(i,{type:"set_model",provider:e,modelId:t})}catch(e){console.error("Failed to set model:",e)}return}let n=tj.current;if(n&&!ni.current){ni.current=!0,eM({provider:e,modelId:t}),eL(!0);try{await sB(n,{type:"set_model",provider:e,modelId:t}),ni.current=!1,await nf(n)}catch(e){console.error("Failed to set model:",e),ni.current=!1,eM(eT),n$({type:"error",message:`Failed to switch model: ${e instanceof Error?e.message:String(e)}`}),await nf(n)}finally{ni.current=!1,eL(!1)}}},[n$,eT,m,nf,Q]),nZ=(0,i.useCallback)(async e=>{let t={provider:e.provider,modelId:e.modelId},n=e.oauthPosition,r={type:"set_model",provider:e.provider,modelId:e.modelId,thinkingLevel:"auto",...void 0!==n?{oauthPosition:n}:{}},i=t=>`${e.alias} preset was not applied: ${t instanceof Error?t.message:String(t)}`;if(m){if(ni.current)return!1;ni.current=!0,eL(!0);let e=t2.current,a=t4.current,s=t5.current;try{t2.current=t,t4.current=n??null,t5.current="auto";let e=tj.current??await tQ.current;return e&&await sB(e,r),Q(t),et(n??null),eR(t),el("auto"),ed(void 0),e&&await nf(e),!0}catch(n){console.error("Failed to apply Main preset:",n),t2.current=e,t4.current=a,t5.current=s,n$({type:"error",message:i(n)});let t=tj.current;return t&&await nf(t),!1}finally{ni.current=!1,eL(!1)}}let a=tj.current;if(!a||ni.current)return!1;ni.current=!0,eM(t),eL(!0);try{return await sB(a,r),await nf(a),!0}catch(e){return console.error("Failed to apply Main preset:",e),eM(eT),n$({type:"error",message:i(e)}),await nf(a),!1}finally{ni.current=!1,eL(!1)}},[n$,eT,eo,m,nf,Q,es]),nX=(0,i.useCallback)(async e=>{let t=Y.find(t=>t.role===e),n=t?.resolved;if(!n)return;if(m){let e={provider:n.provider,modelId:n.modelId},t=n.thinkingLevel;t5.current=t??null,el(t??"auto"),ed(void 0),t2.current=e,t4.current=null,et(null),Q(e),eR(e)}let r=tj.current??(m?await tQ.current:null);if(r)try{await sB(r,{type:"set_role_model",role:e}),m||eM({provider:n.provider,modelId:n.modelId})}catch(e){console.error("Failed to set role model:",e)}},[m,Y,Q]),nQ=(0,i.useCallback)(async()=>{let e=tj.current;if(e&&!eA){eH.current="manual",ez(!0),eW(null),e_(null);try{let t=await sB(e,{type:"compact"});e_(lu(t,"manual")),await nf(e,!0)}catch(e){eW(e instanceof Error?e.message:String(e)),e_(null)}finally{ez(!1)}}},[eA,nf]),n0=(0,i.useCallback)(async e=>{let n=r??t?.cwd??"",i=n?`/api/models?cwd=${encodeURIComponent(n)}`:"/api/models",a=await fetch(i,e?{signal:e}:void 0);if(!a.ok)throw Error(`HTTP ${a.status}`);let s=await a.json();_(s.models),B(s.modelError??null),q(s.modelScopeWarnings??[]),V(s.thinkingLevels??{}),G(s.thinkingLevelMaps??{}),Z(s.roles??[]);let l=s.modelList??[];if(O(l),m&&!tj.current){let e=(s.defaultModel?l.find(e=>e.id===s.defaultModel?.modelId&&e.provider===s.defaultModel?.provider):void 0)??l[0];er(e?{provider:e.provider,modelId:e.id}:null);let t=e&&s.thinkingLevelPins?.[`${e.provider}/${e.id}`];null===t5.current&&el(t??"auto")}},[m,r,t?.cwd]),n1=(0,i.useCallback)(async e=>{if(!e.startsWith("/"))return{handled:!1};let t=e.match(/^\/([^\s]+)(?:\s+([\s\S]*))?$/);if(!t)return{handled:!1};let[,n,r=""]=t,i=r.trim(),a=await ny(),s=e=>(e.handled&&(e.error?n$({type:"error",message:e.error}):"openSessionStats"!==e.action&&n$({type:"success",message:e.message??"Command completed"})),e);try{switch(n){case"compact":{if(!a||eA)return s({handled:!0,error:"No active session to compact"});eH.current="manual",ez(!0),eW(null),e_(null);let e=await sB(a,{type:"compact",...i?{customInstructions:i}:{}});return e_(lu(e,"manual")),await nf(a,!0)&&nb(),s({handled:!0,message:"Compacted context"})}case"reload":if(!a)return s({handled:!0,error:"No active session to reload"});return await sB(a,{type:"reload"}),await Promise.all([nf(a,!1,!0),nv(a),nw(),n0()]),s({handled:!0,message:"Reloaded session resources"});case"name":if(!a)return s({handled:!0,error:"No active session to name"});if(!i)return s({handled:!0,error:"Usage: /name <name>"});return await sB(a,{type:"set_session_name",name:i}),await nf(a)&&nb(),s({handled:!0,message:`Session renamed to ${i}`});case"session":{if(!a)return s({handled:!0,error:"No active session"});let e=await sB(a,{type:"get_session_stats"});return e&&e5(e),h?.(),s({handled:!0,action:"openSessionStats"})}case"copy":{if(!a)return s({handled:!0,error:"No active session"});let e=await sB(a,{type:"get_last_assistant_text"}),t=e?.text??"";if(!t)return s({handled:!0,error:"No assistant message to copy"});return await navigator.clipboard.writeText(t),s({handled:!0,message:"Copied last assistant message"})}case"fork":{if(!a)return s({handled:!0,error:"No active session to fork"});let e=await nV();if(!e.forked)return s({handled:!0,error:e.error??"Fork failed"});return s({handled:!0,message:"Forked a new session"})}case"goal":{if(!a)return s({handled:!0,error:"No active session"});let e=await sB(a,{type:"goal",args:i});if(tK(e?.status??null),e?.error)return s({handled:!0,error:e.error});if(e?.message&&e.message.includes("\n")){if(nR(e.message),e.prompt)return{handled:!0,prompt:e.prompt};return{handled:!0}}if(e?.prompt)return e.message&&n$({type:"success",message:e.message}),{handled:!0,prompt:e.prompt};return s({handled:!0,message:e?.message??"Command completed"})}case"handoff":if(!a)return s({handled:!0,error:"No active session"});if(tT.current||tP.current)return s({handled:!0,error:"Cannot hand off while the session is busy"});tT.current=!0,L(!0),eV({kind:"running_command"});try{await nI(a);let e=await sB(a,{type:"handoff",...i?{customInstructions:i}:{}});if(!e||e.cancelled)return s({handled:!0,error:"Handoff cancelled"});return await nf(a,!0)&&nb(),s({handled:!0,message:"컨텍스트를 현재 세션에 압축했습니다"})}finally{tT.current=!1,L(!1),eV(null),tj.current===a&&nF(a)}default:{if(!a)return s({handled:!0,error:"No active session"});let t=await sB(a,{type:"execute_slash_command",message:e});if(!t?.handled)return{handled:!1};let n=t.output?.filter(e=>e.trim()).join("\n\n")??"";if(n&&nR(n),t.prompt)return{handled:!0,prompt:t.prompt};if(n)return{handled:!0};return s({handled:!0,message:"Command completed"})}}}catch(e){return s({handled:!0,error:e instanceof Error?e.message:String(e)})}finally{"compact"===n&&ez(!1)}},[n$,nR,nI,ny,nV,eA,n0,nf,nw,nv,nb,h,nF]),n2=(0,i.useCallback)(async(t,n,r)=>{let i=tj.current;if(!i)return n$({type:"error",message:"The session is not ready yet, so the message was returned to the composer."}),e.chatInputRef?.current?.restoreSubmission?.(t,lp(n),r),"returned";let a=rg(t,r??[]),s=n?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),l=++tp.current;tu({type:"submit",id:l,kind:"steer",text:a,images:s?.length??0});try{return await sB(i,{type:"steer",message:a,...s?.length?{images:s}:{}}),tu({type:"ack",id:l}),"accepted"}catch(a){return tu({type:"fail",id:l}),console.error("Failed to steer:",a),n$({type:"error",message:a instanceof Error?a.message:String(a)}),e.chatInputRef?.current?.restoreSubmission?.(t,lp(n),r,i),"returned"}},[n$,e.chatInputRef]),n4=(0,i.useCallback)(async(t,n,r,i)=>{let a=tj.current;if(!a)return n$({type:"error",message:"The session is not ready yet, so the message was returned to the composer."}),e.chatInputRef?.current?.restoreSubmission?.(t,lp(r),i),"returned";let s=rg(t,i??[]),l=r?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),o=++tp.current;tu({type:"submit",id:o,kind:n,text:s,images:l?.length??0});try{return await sB(a,{type:"prompt",message:s,streamingBehavior:n,...l?.length?{images:l}:{}}),tu({type:"ack",id:o}),"accepted"}catch(n){return tu({type:"fail",id:o}),console.error("Failed to queue prompt:",n),n$({type:"error",message:n instanceof Error?n.message:String(n)}),e.chatInputRef?.current?.restoreSubmission?.(t,lp(r),i,a),"returned"}},[n$,e.chatInputRef]),n5=(0,i.useCallback)(async(t,n,r)=>{let i=tj.current;if(!i)return n$({type:"error",message:"The session is not ready yet, so the message was returned to the composer."}),e.chatInputRef?.current?.restoreSubmission?.(t,lp(n),r),"returned";let a=rg(t,r??[]),s=n?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),l=++tp.current;tu({type:"submit",id:l,kind:"followUp",text:a,images:s?.length??0});try{return await sB(i,{type:"follow_up",message:a,...s?.length?{images:s}:{}}),tu({type:"ack",id:l}),"accepted"}catch(a){return tu({type:"fail",id:l}),console.error("Failed to follow up:",a),n$({type:"error",message:a instanceof Error?a.message:String(a)}),e.chatInputRef?.current?.restoreSubmission?.(t,lp(n),r,i),"returned"}},[n$,e.chatInputRef]),n6=(0,i.useCallback)(async()=>{let e=tj.current;if(e)try{await sB(e,{type:"abort_compaction"})}catch(e){console.error("Failed to abort compaction:",e)}},[]),n8=(0,i.useCallback)(async()=>{let t=tj.current;if(t)try{var n;let r=await sB(t,{type:"clear_queue"});tu({type:"withdraw"}),tl({steering:[],followUp:[]});let i={text:(n=[...r?.steering??[],...r?.followUp??[]]).map(({text:e,images:t})=>t?.length&&"[Image]"===e?"":e).filter(e=>e.trim()).join("\n\n"),images:n.flatMap(({images:e})=>e??[]).map(({data:e,mimeType:t})=>({data:e,mimeType:t}))};e.chatInputRef?.current?.restoreSubmission?.(i.text,i.images.length?i.images:void 0,void 0,t)}catch(e){console.error("Failed to recall queued messages:",e),n$({type:"error",message:"Failed to recall queued messages"})}},[e.chatInputRef,n$]),n3=(0,i.useCallback)(async(e,t)=>{let n=tj.current;if(n)try{let r=await sB(n,{type:"remove_queued_message",message:t,queue:e});if(!r?.removed)return;tu({type:"withdraw",kind:"steering"===e?"steer":"followUp",text:t}),tl(n=>{let r=n[e].indexOf(t);return(r<0&&""===t.trim()&&(r=n[e].indexOf("[Image]")),r<0)?n:{...n,[e]:n[e].filter((e,t)=>t!==r)}})}catch(e){console.error("Failed to remove queued message:",e),n$({type:"error",message:"Failed to remove queued message"})}},[n$]),n7=(0,i.useCallback)(async(e,t=null)=>{let n="auto"===e?t:null,r=n!==ec;el(e),eu(n),m&&(!tj.current||t7.current===tj.current)&&(t5.current=e,t3.current=n),ed(void 0);let i=tj.current??await tQ.current;if(i)try{t7.current===i?await ny():r&&await sB(i,{type:"set_thinking_ceiling",ceiling:n}),await sB(i,{type:"set_thinking_level",level:e}),await nf(i)}catch(e){console.error("Failed to set thinking level:",e),n$({type:"error",message:"Failed to set thinking level"}),await nf(i)}},[m,nf,n$,ec,ny]);ev.current=no?`${no.provider}/${no.modelId}`:"";let n9=e=>e?`${e}|${ev.current}`:null,re=t?.id??tj.current,rt=n9(re),rn=ep&&ep.key===rt?ep.value:null;(0,i.useEffect)(()=>{let e=++eg.current;rt&&re&&!E&&!eE&&fetch(`/api/agent/${encodeURIComponent(re)}`).then(e=>e.json()).then(t=>{eg.current===e&&n9(tj.current)===rt&&eh({key:rt,value:(t.running?s3(t.state):void 0)??null})}).catch(()=>{})},[rt,E,eE]);let rr=(0,i.useCallback)(async()=>{let e=tj.current??await ny(),t=n9(tj.current);if(!e||!t)return;let n=++eg.current,r=()=>eg.current===n&&n9(tj.current)===t,i=e=>{r()&&eh({key:t,value:e})};ef(!0);try{let n=ep?.key===t?ep.value?.enabled:void 0;if(void 0===n){let t=s3(await sB(e,{type:"get_state"}));if(!t)throw Error("Could not read the session's Fast state");n=t.enabled}if(!r())return;let a=await sB(e,{type:"set_fast_mode",enabled:!n});i({enabled:a?.enabled===!0,active:a?.active===!0})}catch(t){if(!r())return;n$({type:"error",message:t instanceof Error?t.message:String(t)});try{i(s3(await sB(e,{type:"get_state"}))??null)}catch{i(null)}}finally{ef(!1)}},[ny,ep,n$]),ri=(0,i.useCallback)(async e=>{let t=(0,a7.xG)(e);ns(e);let n=tj.current??await tQ.current;if(n)try{await sB(n,{type:"set_tools",toolNames:t})}catch(e){console.error("Failed to set tools:",e)}},[ns]),ra=(0,i.useCallback)(e=>{tH.current=e,tU(t=>!e===t?t:!e)},[]);tY.current=ra;let rs=(0,i.useCallback)((e="smooth")=>{tG.current=Date.now()+700,tZ.current?.scrollIntoView({behavior:e})},[]),rl=(0,i.useCallback)(()=>{tJ.current=0,ra(!0),rs("smooth")},[rs,ra]),ro=(0,i.useCallback)(()=>{tJ.current=0,ra(!1)},[ra]),rd=(0,i.useCallback)(e=>{e instanceof KeyboardEvent&&(!ln.has(e.key)||e.target instanceof Element&&e.target.closest("input, textarea, [contenteditable='true']"))||(tJ.current=Date.now()+1200)},[]),rc=(0,i.useCallback)(()=>{if(!tT.current&&!tP.current)return;let e=tX.current;if(!e)return;let t=Date.now()<=tJ.current;!t&&Date.now()<tG.current||(e.scrollHeight-e.scrollTop-e.clientHeight<=72?ra(!0):t&&ra(!1))},[ra]);return(0,i.useEffect)(()=>(tj.current=t?.id??null,tI.current.sessionId!==tj.current&&(tI.current={sessionId:tj.current,outputs:[],seq:0}),t&&nf(t.id,!f,!0,f).then(e=>{if(tj.current!==t.id)return;nC(t.id),e?.running&&(nv(t.id),(e.state?.isStreaming||e.state?.isPromptRunning||e.state?.isHandoffRunning)&&(tM.current=!!e.state.isStreaming,t$.current=!!e.state.isPromptRunning,tT.current=!0,L(!0),eV(e.state.isStreaming?{kind:"waiting_model"}:{kind:"running_command"}),R({type:"start"}),nN(t.id),!e.state.isStreaming&&e.state.isPromptRunning&&nD(t.id)),e.state?.isBashRunning&&(tP.current=!0,z(!0),nO(t.id)),(e.state?.subagents?.length??0)>0&&nN(t.id));let n=e?.state;n&&(void 0!==n.isCompacting&&ez(n.isCompacting),eO(s7(n)),void 0!==n.contextUsage&&ek(n.contextUsage??null),void 0!==n.systemPrompt&&eC(n.systemPrompt??null),void 0!==n.thinkingLevel&&(t6.current=t.id,el(n.configuredThinkingLevel??n.thinkingLevel),ed(n.thinkingLevel)),void 0!==n.thinkingCeiling&&eu(n.thinkingCeiling??null),void 0!==n.extensionStatuses&&tr(n.extensionStatuses??[]),void 0!==n.extensionWidgets&&ta(n.extensionWidgets??[]),void 0!==n.queuedMessages&&tl(s8(n.queuedMessages)),void 0!==n.subagents&&td(e=>s5(e,n.subagents??[])),void 0!==n.goal&&tK(n.goal??null)),e&&eU(!0)}),()=>{tW.current+=1,nk(),nj(),nS()}),[t?.id]),(0,i.useEffect)(()=>{p?.(eS)},[eS,p]),(0,i.useEffect)(()=>{u&&u(g?.tree??[],k,nG)},[g?.tree,k,nG,u]),(0,i.useEffect)(()=>(window.addEventListener("keydown",rd),()=>{window.removeEventListener("keydown",rd)}),[rd]),(0,i.useEffect)(()=>{let e=tX.current;if(e)return e.addEventListener("pointerdown",rd,{passive:!0}),e.addEventListener("wheel",rd,{passive:!0}),e.addEventListener("touchstart",rd,{passive:!0}),e.addEventListener("scroll",rc,{passive:!0}),()=>{e.removeEventListener("pointerdown",rd),e.removeEventListener("wheel",rd),e.removeEventListener("touchstart",rd),e.removeEventListener("scroll",rc)}},[S.length,v,rc,rd]),(0,i.useEffect)(()=>{if(t9.current||!E&&!A||!tH.current)return;let e=tX.current;if(!e)return;let t=requestAnimationFrame(()=>{tG.current=Date.now()+700,e.scrollTo({top:e.scrollHeight,behavior:"instant"})});return()=>cancelAnimationFrame(t)},[E,A,S.length,$.streamingMessage,eK,P,e.transitioning]),(0,i.useLayoutEffect)(()=>{if(0!==S.length){if(!tO.current){tO.current=!0,rs("instant");return}if(!t9.current&&tH.current){let e=Date.now()-ne.current<1500;rs(tT.current||tP.current||e?"instant":"smooth")}}},[S.length,E,A,rs,e.transitioning]),(0,i.useEffect)(()=>{let e=new AbortController;return n0(e.signal).catch(e=>{if(e instanceof DOMException&&"AbortError"===e.name)return}),()=>e.abort()},[n0,c]),(0,i.useEffect)(()=>{if(!eF)return;let e=setTimeout(()=>e_(null),6e3);return()=>clearTimeout(e)},[eF]),(0,i.useEffect)(()=>{if(0===e1.visible.length)return;let e=e1.visible.find(e=>e.exiting);if(e){let t=setTimeout(()=>{e2({type:"remove",id:e.id})},180);return()=>clearTimeout(t)}if(!e1.visible[0])return;let t=setTimeout(()=>{e2({type:"mark_oldest_exiting"})},5e3);return()=>clearTimeout(t)},[e1.visible]),(0,i.useEffect)(()=>{e5(null)},[S.length,ew?.tokens,ew?.percent,ew?.contextWindow]),{data:g,loading:v,error:y,activeLeafId:k,messages:S,entryIds:N,streamState:$,agentRunning:E,modelNames:F,modelList:D,modelError:H,modelScopeWarnings:U,modelThinkingLevels:K,modelThinkingLevelMaps:J,modelRoles:Y,newSessionModel:X,toolPreset:ei,thinkingLevel:es,effectiveThinkingLevel:eo,thinkingCeiling:ec,retryInfo:eb,contextUsage:ew,systemPrompt:eS,forkingEntryId:eN,isCompacting:eA,compaction:eD,compactError:eP,compactResult:eF,currentModel:nl,displayModel:no,modelSwitching:eE,sessionStats:nd,runStateKnown:eB,slashCommands:eZ,slashCommandsLoading:eQ,queuedMessages:ts,deliveryRows:th,subagents:to,todoPhases:tm&&tm.sid===tj.current?tm.phases:null,compactedWork:T,notices:e1.visible,extensionDialog:e6,extensionResponse:e3,extensionCustomUi:te,extensionStatuses:tn,extensionWidgets:ti,respondToExtensionUi:nT,sendExtensionCustomInput:nM,isAutoModelSelection:m&&null===X,agentPhase:eK,isNew:m,autoFollowPaused:tB,resumeAutoFollow:rl,pauseAutoFollow:ro,goalStatus:tq,sessionIdRef:tj,eventSourceRef:tg,messagesEndRef:tZ,scrollContainerRef:tX,handleSend:nq,handleAbort:nK,handleFork:nV,handleNavigate:nJ,handleModelChange:nY,handleRoleModelChange:nX,handleMainPresetChange:nZ,newSessionAccount:ee,handleCompact:nQ,handleSteer:n2,handleFollowUp:n5,handlePromptWithStreamingBehavior:n4,handleAbortCompaction:n6,handleRecallQueue:n8,handleRemoveQueuedMessage:n3,handleBuiltinSlashCommand:n1,handleToolPresetChange:ri,handleThinkingLevelChange:n7,fastMode:rn,fastModeBusy:em,handleFastModeToggle:rr,loadTools:nv,loadSlashCommands:nw,ensureNewSession:ny,refreshLiveTranscript:ng,setActiveLeafId:j,setData:x,setMessages:C,dispatch:R,setAgentRunning:L,setForkingEntryId:eI,bashRunning:A,pendingBash:P,handleAgentEventRef:tF}}({session:e,newSessionCwd:t,initialData:a,transitioning:s,onAgentEnd:eb,onAttentionNeeded:o,onSessionCreated:d,onSessionForked:c,modelsRefreshKey:u,chatInputRef:p,onBranchDataChange:h,onSystemPromptChange:m,onSessionStatsPanelOpen:g}),tG=nm(e?.id,te?.provider,void 0),tY=tG?.alias;(0,i.useEffect)(()=>{tY&&Q.current?.(tY)},[tY]);let tZ=(0,i.useMemo)(()=>{if(!te)return null;let e=ty?tz:nt.bo.find(e=>e.alias===tG?.alias)?.oauthPosition;return nt.bo.find(t=>t.provider===te.provider&&(void 0===t.oauthPosition||t.oauthPosition===e))?.alias??null},[te,ty,tz,tG]),tX=te?.provider,tQ=te?.modelId,t0=tG?.alias,t1=tG?.seed,t2=(0,i.useRef)(tG);t2.current=tG,(0,i.useEffect)(()=>{y&&y(tX&&tQ?{provider:tX,modelId:tQ,face:t2.current,presetAlias:tZ,isNew:ty}:null)},[y,tX,tQ,t0,t1,tZ,ty]),(0,i.useEffect)(()=>()=>{y?.(null)},[y]);let t4=eI||eT,t5=e?.id;ei.current=eS,ea.current=eC,es.current=tC;let t6=(0,i.useRef)(!0);t6.current=!tw;let t8=(0,i.useRef)(!1);(0,i.useEffect)(()=>{eI&&!t8.current&&(el.current+=1),t8.current=eI},[eI]),(0,i.useEffect)(()=>()=>{el.current+=1},[]),(0,i.useEffect)(()=>{et(e=>[...function(e){if(!e)return[];try{let t=JSON.parse(window.localStorage.getItem(lN(e))??"[]");if(!Array.isArray(t))return[];return t.filter(e=>e&&"string"==typeof e.anchorEntryId).map(t=>({..."string"==typeof t.sticker?{...t,sticker:t.sticker.replace(/^(\/stickers\/.+)\.png$/,"$1.webp")}:t,sessionId:e}))}catch{return[]}}(t5),...e.filter(e=>null===e.anchorEntryId&&e.sessionId===t5)])},[t5]),(0,i.useEffect)(()=>{let e=tC.current;e&&en.current.some(t=>null===t.anchorEntryId&&t.sessionId===e)&&et(t=>{let n=!1,r=[];for(let i of t){if(null!==i.anchorEntryId||!i.intent||i.sessionId!==e){r.push(i);continue}let a=function(e,t,n){let r=Math.min(t.length,n.length),i=0;if(null!==e.baseEntryId){let t=n.indexOf(e.baseEntryId);if(-1===t||t>=r)return{kind:"drop"};i=t+1}let a=0;for(let s=i;s<r;s++)if(iL(t[s])===e.identity&&(a+=1)===e.occurrence)return{kind:"entry",entryId:n[s]};return null}(i.intent,eS,eC);if(null===a){r.push(i);continue}n=!0,"drop"!==a.kind&&("working"===i.tag&&[...t,...r].some(e=>"working"===e.tag&&e.anchorEntryId===a.entryId)||r.push({id:i.id,anchorEntryId:a.entryId,sticker:i.sticker,text:i.text,tag:i.tag,sessionId:i.sessionId}))}return n?(lI(e,r),r):t})},[eS,eC,tC]);let t3=(0,i.useRef)(null);(0,i.useEffect)(()=>{let e=tC.current,t=t3.current;if(t3.current=e?{sessionId:e,entryIds:eC}:null,!e||!t||t.sessionId!==e)return;let n=function(e,t,n){if(0===e.length||t.length<=e.length)return[];for(let n=0;n<e.length;n++)if(e[n]!==t[n])return[];let r=[],i=Math.min(n.length,t.length);for(let a=e.length;a<i;a++){let e=n[a];"assistant"===e.role&&"web6"===e.provider&&e.model===iz&&r.push(t[a])}return r}(t.entryIds,eC,eS),r=ec();if(0===n.length||!r)return;let i=np(e,"web6",void 0)?.alias??null;for(let e of n)en.current.some(t=>t.anchorEntryId===e)||eh(i,"done",r,{kind:"entry",entryId:e})},[eC,eS,tC,ec,eh]);let t7=eI&&tb?.kind==="running_tools"&&tb.tools.length>0&&tb.tools.every(e=>"wait"===e.name),nn=ew||s,{hideThinkingBlock:nr}=(O=t??e?.cwd??null,B=ne(),(0,i.useEffect)(()=>{t9(O).catch(()=>{})},[O]),B),ni=(0,i.useMemo)(()=>({hideThinking:nr}),[nr]);(0,i.useEffect)(()=>{var e;if(!tu||X.current===tu.id)return;X.current=tu.id;let t=ec();if(!t)return;ed.current=t.turn;let n=eN.streamingMessage?.role==="assistant"?eN.streamingMessage:null,r=iA(ei.current,n,te?.provider);ef("select"===(e=tu.method)||"ask"===e?"choice":"approval",t,r.provider,r.credentialId)},[tu,eN.streamingMessage,te?.provider,ec,ef]),(0,i.useEffect)(()=>(v=t4?tM:null,()=>void(v=null)),[t4,tM]),(0,i.useEffect)(()=>{T?.(t4)},[T,t4]),(0,i.useEffect)(()=>()=>T?.(!1),[T]),(0,i.useEffect)(()=>{M?.(t7)},[t7,M]),(0,i.useEffect)(()=>()=>M?.(!1),[M]),(0,i.useEffect)(()=>{$?.(null!==tu)},[$,tu]),(0,i.useEffect)(()=>()=>$?.(!1),[$]);let{main:na,process:ns}=(0,i.useMemo)(()=>(function(e,t,n={}){let r=[],i=[],a=-1,s=null,l=(e,t,n)=>{if(0===t.length)return;let a=(s&&s.anchorIdx===e||(s={anchorIdx:e,entries:[],messageCount:0,toolCallCount:0},i.push(s)),s),l=r.length-1;for(let e of t)a.entries.push({...e,afterMainIndex:l});a.messageCount+=t.length,a.toolCallCount+=n},o=eH(e),d=new Map,c=(e,t)=>{let n=d.get(e)??0;d.set(e,n+1),r.push({kind:"answer",anchorIdx:a,idx:e,runIndex:n,blocks:o.attach(t),precedingBlocks:[]})},u=()=>{let e=o.takeRemaining();e&&c(e.idx,e.blocks)};for(let i of t){if("answer"===i.kind){r.push(i);continue}if("process"===i.kind){l(i.anchorIdx,i.entries,i.toolCallCount);continue}let t=e[i.idx];if(!t)continue;if("user"===t.role){u(),a=i.idx,r.push(i);continue}if(eV(t)){r.push(void 0!==i.anchorIdx||a<0?i:{...i,anchorIdx:a});continue}if("assistant"!==t.role){"toolResult"!==t.role&&l(a,[{idx:i.idx}],0);continue}let s=eF(t,n),d=!1;for(let e of s){if("answer"===e.kind){c(i.idx,e.blocks),d=!0;continue}l(a,[{idx:i.idx,blocks:e.blocks}],e_(e.blocks)),o.collect(i.idx,e.blocks)}!d&&eW(t,n)&&c(i.idx,[])}return u(),{main:r,process:i}})(eS,function(e,t={}){let n=-1;for(let t=e.length-1;t>=0;t--)if(eZ(e[t])){n=t;break}let r=[];for(let i=0;i<e.length;){if(!eZ(e[i])){r.push({kind:"message",idx:i}),i+=1;continue}let a=i,s=a+1;for(;s<e.length&&!eZ(e[s]);)s+=1;if((t.sessionBusy||t.isStreaming)&&s===e.length&&a===n||!function(e,t,n){for(let r=t;r<n;r++)if(e[r]?.role==="assistant")return!0;return!1}(e,a+1,s)){for(let e=a;e<s;e++)r.push({kind:"message",idx:e});i=s;continue}for(let n of(r.push({kind:"message",idx:a}),function(e,t,n,r){let i=[],a=[],s=0,l=[],o=0,d=0,c=eH(e.slice(t+1,n)),u=()=>{0!==a.length&&(i.push({kind:"process",anchorIdx:t,idx:a[0].idx,groupIndex:d++,entries:a,messageCount:a.length,toolCallCount:s,turnHasAnswer:!1}),a=[],s=0)},p=(e,n)=>{u(),i.push({kind:"answer",anchorIdx:t,idx:e,runIndex:o++,blocks:c.attach(n),precedingBlocks:l}),l=[]};for(let o=t+1;o<n;o++){let n=e[o];if("assistant"!==n.role){if(eV(n)){u(),i.push({kind:"message",idx:o,anchorIdx:t});continue}"toolResult"!==n.role&&a.push({idx:o});continue}let d=eF(n,r),h=d.reduce((e,t)=>"answer"===t.kind?e+1:e,0);for(let e of d){if("answer"===e.kind){p(o,e.blocks);continue}for(let t of(a.push(h>0?{idx:o,blocks:e.blocks}:{idx:o}),s+=e_(e.blocks),c.collect(o,e.blocks),e.blocks))l.push(t)}0===h&&eW(n,r)&&p(o,[])}u();let h=c.takeRemaining();h&&i.push({kind:"answer",anchorIdx:t,idx:h.idx,runIndex:o++,blocks:h.blocks,precedingBlocks:[]});let m=i.some(e=>"answer"===e.kind);for(let e of i)"process"===e.kind&&(e.turnHasAnswer=m);return i}(e,a,s,{hideThinking:t.hideThinking})))r.push(n);i=s}return r}(eS,{sessionBusy:t4,isStreaming:eN.isStreaming,hideThinking:ni.hideThinking}),ni),[eS,t4,eN.isStreaming,ni]),nl=(0,i.useMemo)(()=>(function(e,t,n=[]){let r=new Map,i=e.map((e,t)=>({item:e,position:t})).filter(e=>"answer"===e.item.kind);if(0===i.length)return r;let a=-1,s=-1;t.forEach((e,t)=>{let n=nD(e);if(n.length>0){let e=i.filter(e=>e.item.anchorIdx===a||e.item.anchorIdx===s),l=e.filter(e=>e.item.idx<=t).pop(),o=l??e.find(e=>e.item.idx>t);if(o){let e=r.get(o.position);e?e.calls.push(...n):r.set(o.position,{calls:[...n],placement:l?"after":"before"})}}"user"===e.role&&(a=t),eZ(e)&&(s=t)});let{continuing:l}=nO(e,t,n);if(l){let e=r.get(l.position);e?e.calls.unshift(...l.calls):r.set(l.position,{calls:l.calls,placement:"before"})}return r})(na,eS,ti?.messages),[na,eS,ti]),no=(0,i.useMemo)(()=>(function(e,t,n=[]){let{atCompaction:r}=nO(e,t,n);if(0===r.length)return null;let i=-1;t.forEach((e,t)=>{"custom"===e.role&&"compaction"===e.customType&&(i=t)});let a=e.findIndex(e=>e.idx>i),s=-1===a?e.length:a;return{position:s,jumpTo:s<e.length?s:e.length>0?e.length-1:null,calls:r}})(na,eS,ti?.messages),[na,eS,ti]),[nd,nc]=(0,i.useState)(lw),{startIndex:nu,endIndex:nf,hasLater:ng}=lk(na.length,nd),nx=null!==nd.end&&ng,nv=(0,i.useRef)(na.length);nv.current=na.length;let nb=(0,i.useRef)(null),ny=(0,i.useRef)(null),nw=(0,i.useRef)(null);(0,i.useEffect)(()=>{null!==nd.end&&nd.end>=na.length&&nc(e=>({count:e.count,end:null}))},[nd.end,na.length]),(0,i.useEffect)(()=>{let e=nb.current,t=tI.current;if(!e||!t)return;let n=new IntersectionObserver(e=>{e[0]?.isIntersecting&&(nw.current=t.scrollHeight-t.scrollTop,nc(e=>(function(e,t=50){return{...e,count:e.count+t}})(e)))},{root:t,threshold:0});return n.observe(e),()=>n.disconnect()},[nd,na.length,tI]),(0,i.useEffect)(()=>{if(null==nw.current)return;let e=tI.current;if(e){var t;t=e.scrollHeight,e.scrollTop=Math.max(0,t-nw.current),nw.current=null}},[nd.count,tI]),(0,i.useEffect)(()=>{let e=ny.current,t=tI.current;if(!e||!t)return;let n=new IntersectionObserver(e=>{e[0]?.isIntersecting&&nc(e=>(function(e,t,n=50){if(null===t.end)return t;let{startIndex:r,endIndex:i}=lk(e,t),a=i+n;return a>=e?{count:e-r,end:null}:{count:a-r,end:a}})(nv.current,e))},{root:t,threshold:0});return n.observe(e),()=>n.disconnect()},[nd,na.length,tI]);let[nk,nj]=(0,i.useState)(null),[nS,nC]=(0,i.useState)(null),[nN,nI]=(0,i.useState)(0),nT=(0,i.useRef)(null),nM=(0,i.useCallback)((e,t=null)=>{tj(),nT.current={item:e,dispatchKey:t},nj(null),nC(null),nc(t=>lj(nv.current,e,t)),nI(e=>e+1)},[tj]);(0,i.useLayoutEffect)(()=>{let e,t=nT.current,n=tI.current;if(null===t||!n)return;let r=n.querySelector(`[data-chat-item="${t.item}"]`);if(!r)return;nT.current=null;let i=t.dispatchKey?r.querySelector(".answer-dispatch"):null;if(i)e=i.getBoundingClientRect().top;else{let t=document.createRange();t.selectNodeContents(r),e=t.getBoundingClientRect().top}n.scrollTop+=e-n.getBoundingClientRect().top-24,i&&t.dispatchKey?nC(t.dispatchKey):nj(t.item)},[nN,nd,na,tI]),(0,i.useEffect)(()=>{if(null===nk)return;let e=setTimeout(()=>nj(null),1800);return()=>clearTimeout(e)},[nk]),(0,i.useEffect)(()=>{if(null===nS)return;let e=setTimeout(()=>nC(null),1800);return()=>clearTimeout(e)},[nS]);let n$=(0,i.useCallback)(()=>{(0,F.flushSync)(()=>nc(lw));let e=tI.current;e&&(e.scrollTop=e.scrollHeight)},[tI]),nF=(0,i.useCallback)(()=>{nx&&n$(),tk()},[nx,n$,tk]),nB=(0,i.useRef)(null),[nU,nq]=(0,i.useState)(!1);(0,i.useEffect)(()=>{if(!_||nB.current===_.id||_.sessionId!==e?.id||ew||0===eS.length)return;nB.current=_.id,D?.(_.id);let t=eC.indexOf(_.entryId);if(t<0)return void nq(!0);let n=0;for(let e=0;e<na.length;e++){let r=na[e].idx;if(r>t||(n=e,r===t))break}nM(n)},[_,e?.id,ew,eS.length,eC,na,nM,D]),(0,i.useEffect)(()=>{if(!nU)return;let e=setTimeout(()=>nq(!1),6e3);return()=>clearTimeout(e)},[nU]);let[nV,nJ]=(0,i.useState)(!1),[nG,nY]=(0,i.useState)(0),nZ=(0,i.useMemo)(()=>nV?na.map(e=>(function(e,t){if("answer"===e.kind)return e0(e.blocks);let n=t[e.idx];return n&&"content"in n?e0(n.content):""})(e,eS).toLowerCase()):lT,[nV,na,eS]),nX=(0,i.useCallback)(e=>{tj(),nc(t=>lj(nv.current,e,t))},[tj]),nQ=(0,i.useCallback)(()=>nJ(!1),[]);(0,i.useEffect)(()=>{let e=e=>{if(e.defaultPrevented||e.isComposing||e.altKey||e.shiftKey||!(e.ctrlKey||e.metaKey)||"f"!==e.key.toLowerCase())return;let t=tI.current;if(!t||!t.checkVisibility({visibilityProperty:!0}))return;let n=e.target instanceof Element?e.target:null;if(n?.closest("[data-capture-keys], [role='dialog']"))return;let r=n?.closest("input, textarea, select, [contenteditable='true']");(!r||r.closest("[data-chat-composer], .chat-find-bar"))&&(e.preventDefault(),nJ(!0),nY(e=>e+1))};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[tI]);let n0=(0,i.useMemo)(()=>{let e=[];return na.forEach((t,n)=>{if("message"!==t.kind)return;let r=lC(eS[t.idx]);null!==r&&e.push({item:n,text:r})}),e},[na,eS]),n1=`${nu}:${nf}`,n2=eC.length>0?eC[eC.length-1]:null,[n4,n5]=(0,i.useState)(null),n6=(0,i.useRef)(!1);(0,i.useEffect)(()=>{n6.current||!tr||ew||!e?.id||(n6.current=!0,t4||!n2||!function(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if("user"===n.role||"toolResult"===n.role)return!0;if("assistant"===n.role){if(!n.stopReason)return!0;if("aborted"===n.stopReason||"error"===n.stopReason||"length"===n.stopReason)break;return n.content.some(e=>"toolCall"===e.type)}}return!1}(eS)||function(e){try{return window.localStorage.getItem(lM(e))}catch{return null}}(e.id)!==n2&&n5(n2))},[tr,ew,e?.id,t4,n2,eS]);let n8=(0,i.useCallback)(()=>{e?.id&&n4&&function(e,t){try{window.localStorage.setItem(lM(e),t)}catch{}}(e.id,n4),n5(null)},[e?.id,n4]),n3=null!==n4&&n4===n2&&!t4&&!nx,n7=tn?[tn.sessionId,tn.sessionFile??"",tn.sessionName??"",tn.userMessages,tn.assistantMessages,tn.toolCalls,tn.toolResults,tn.totalMessages,tn.tokens.input,tn.tokens.output,tn.tokens.cacheRead,tn.tokens.cacheWrite,tn.tokens.total,tn.cost??0,tn.totalActiveMs??0].join("|"):null,n9=(0,i.useRef)(tn);n9.current=tn,(0,i.useEffect)(()=>{f?.(n9.current)},[n7,f]),(0,i.useEffect)(()=>()=>{f?.(null)},[f]);let re=e4?`${e4.percent??"null"}|${e4.contextWindow}|${e4.tokens??"null"}`:null,rt=(0,i.useRef)(e4);rt.current=e4,(0,i.useEffect)(()=>{x?.(rt.current)},[re,x]),(0,i.useEffect)(()=>()=>{x?.(null)},[x]),(0,i.useEffect)(()=>{b?.(to)},[b,to]),(0,i.useEffect)(()=>()=>{b?.([])},[b]);let{isDragOver:rn,handleDragEnter:rr,handleDragOver:ri,handleDragLeave:ra,handleDrop:rs}=function(e){let[t,n]=(0,i.useState)(!1),r=(0,i.useRef)(0),a=(0,i.useCallback)(e=>{Array.from(e.dataTransfer.items).some(e=>"file"===e.kind)&&(e.preventDefault(),r.current+=1,n(!0))},[]),s=(0,i.useCallback)(e=>{Array.from(e.dataTransfer.items).some(e=>"file"===e.kind)&&e.preventDefault()},[]);return{isDragOver:t,handleDragEnter:a,handleDragOver:s,handleDragLeave:(0,i.useCallback)(()=>{r.current-=1,r.current<=0&&(r.current=0,n(!1))},[]),handleDrop:(0,i.useCallback)(t=>{t.preventDefault(),r.current=0,n(!1),e(Array.from(t.dataTransfer.files))},[e])}}((0,i.useCallback)(e=>{t4||p?.current?.addAttachments(e)},[t4,p])),rl=(0,i.useMemo)(()=>{var e;return e=ti?.messages,e&&e.length>0?[...e,...eS]:eS},[ti,eS]),ro=(0,i.useMemo)(()=>{let e=new Map;for(let t of rl)"toolResult"===t.role&&e.set(t.toolCallId,t);return e},[rl]),rd=(0,i.useMemo)(()=>{let e,t,n,r;return e=new Map,t=new Map,n=new Map,r=(e,r,i)=>{let a=n.get(e);a&&r&&t.set(a,{status:r,order:i})},rl.forEach((t,i)=>{if("assistant"===t.role){for(let e of t.content??[]){if("toolCall"!==e.type||"task"!==e.toolName)continue;let t=ro.get(e.toolCallId);if(t)for(let r of nz(e,t)??[])n.set(r.agentId,r.key)}return}if("toolResult"===t.role){if("routing_verdict"===t.toolName){let n=function(e){let t=function(e){if(e.isError)return null;let t=e.details?.record;if("object"!=typeof t||null===t)try{let n=JSON.parse(nA(e.content));t=n?.ok===!0?n.record:void 0}catch{return null}return"object"==typeof t&&null!==t?t:null}(e);if(!t)return null;let n=t.verdict;if("accepted"!==n&&"rework"!==n&&"held"!==n)return null;let r=nE(t.assignmentId),i=r?.split("#")??[];if(i.length<3)return null;let a=i[i.length-1],s=i.slice(1,-1).join("#");return/^\d+$/.test(a)&&s?{key:`${s}#${a}`,record:{verdict:n,attempt:"number"==typeof t.attempt?t.attempt:null,reason:nE(t.reason)}}:null}(t);if(!n)return;let r=e.get(n.key)??[];r.push({...n.record,order:i}),e.set(n.key,r);return}if("wait"===t.toolName)for(let e of nR(t.details?.jobs)){if("task"!==e.type)continue;let t=nE(e.id);t&&r(t,nL(e.status),i)}return}if("custom"===t.role&&"async-result"===t.customType)for(let e of nA(t.content).matchAll(nP)){let t=Object.fromEntries([...e[1].matchAll(nW)].map(e=>[e[1],e[2]]));t.id&&r(t.id,nL(t.status),i)}}),{verdicts:e,runs:t,latestByAgent:n}},[rl,ro]),rc=(0,i.useMemo)(()=>({ledger:rd,subagents:to,toolResults:ro,onOpenPanel:w,focusedDispatch:nS,sessionId:e?.id??null,onOpenMaker:k,selectedMaker:j}),[rd,to,ro,w,nS,e?.id,k,j]),ru=(0,i.useMemo)(()=>(function(e,t,n,r,i,a,s=null){let l=-1;e.forEach((e,t)=>{"user"===e.role&&(l=t)});let o=new Map;for(let[e,t]of n)for(let n of t.calls)o.set(n.toolCallId,e);if(s?.jumpTo!=null)for(let e of s.calls)o.set(e.toolCallId,s.jumpTo);let d=[];if(e.forEach((e,n)=>{if("assistant"!==e.role)return;let s=n>l;for(let n of e.content??[])if("toolCall"===n.type&&"task"===n.toolName)for(let e of nz(n,t.get(n.toolCallId))??[]){let t=n_(e,r,i),l=nH[t.run],c=null;"running"===l&&("live"===t.runSource||s&&a)?c="running":"awaiting"===l&&s&&!t.verdict&&(c="awaiting"),c&&d.push({maker:t,phase:c,position:o.get(n.toolCallId)??null})}}),0===d.length)return null;let c=0;for(let e of d)"running"===e.phase&&(c+=1);let u=d.filter(e=>null!==e.position);return{running:c,awaiting:d.length-c,target:u.length>0?u[u.length-1]:d[d.length-1]}})(rl,ro,nl,to,rd,t4,no),[rl,ro,nl,to,rd,t4,no]),rp=(0,i.useMemo)(()=>w?()=>w("subagents"):void 0,[w]),rh=(0,i.useMemo)(()=>{let e=new Set,t=[];for(let n=eS.length-1;n>=0;n-=1){let r=lC(eS[n]);if(!(!r||e.has(r))&&(e.add(r),t.push(r),t.length>=50))break}return t.reverse()},[eS]),rm=(0,i.useMemo)(()=>e7(eS,ro,td,ti?.todoPhases??null),[eS,ro,td,ti]),rf=(0,i.useMemo)(()=>iK(eN.streamingMessage).join("|"),[eN.streamingMessage]),rx=(0,i.useMemo)(()=>JSON.stringify(iq(eN.streamingMessage)),[eN.streamingMessage]),rv=(0,i.useMemo)(()=>JSON.stringify(iJ(eN.streamingMessage)),[eN.streamingMessage]),rb=(0,i.useMemo)(()=>(function(e,t,n=[],r=[],i=[]){let a=function(e){let t=new Map;for(let n of e){if("toolResult"!==n.role||"write"!==n.toolName)continue;let e=n.details;if(!e||"object"!=typeof e||Array.isArray(e))continue;let r=e.message;if(!r||"object"!=typeof r||Array.isArray(r)||"send"!==r.op)continue;let i=Array.isArray(r.receipts)?r.receipts.filter(e=>"object"==typeof e&&null!==e&&!Array.isArray(e)).map(e=>({to:"string"==typeof e.to?e.to:void 0,outcome:"string"==typeof e.outcome?e.outcome:void 0})):void 0;t.set(n.toolCallId,{from:"string"==typeof r.from?r.from:void 0,receipts:i})}return t}(e),s=[],l=new Map,o=-1;for(let n=0;n<e.length;n+=1){let r=e[n];if("user"===r.role){o=n;continue}let i=iK(r),d=iJ(r,a);if(0===i.length&&0===d.length||o<0)continue;let c=iq(r),u=l.get(o);u||(u={index:o,entryId:t[o],taskToolCallIds:[],characterSummons:[],peerSends:[]},l.set(o,u),s.push(u)),u.taskToolCallIds=[...u.taskToolCallIds,...i],u.characterSummons=[...u.characterSummons,...c],u.peerSends=[...u.peerSends,...d]}if(n.length>0||i.length>0){let a=-1;for(let t=e.length-1;t>=0;t-=1)if("user"===e[t].role){a=t;break}if(a>=0){let e=l.get(a);e||(e={index:a,entryId:t[a],taskToolCallIds:[],characterSummons:[],peerSends:[]},l.set(a,e),s.push(e));let o=new Set(e.taskToolCallIds);e.taskToolCallIds=[...e.taskToolCallIds,...n.filter(e=>!o.has(e))];let d=new Set(e.characterSummons.map(e=>`${e.toolCallId} ${e.name??""}`));e.characterSummons=[...e.characterSummons,...r.filter(e=>!d.has(`${e.toolCallId} ${e.name??""}`))];let c=new Set(e.peerSends.map(e=>e.toolCallId));e.peerSends=[...e.peerSends,...i.filter(e=>!c.has(e.toolCallId))]}}return s.sort((e,t)=>e.index-t.index)})(eS,eC,rf.length>0?rf.split("|"):[],JSON.parse(rx),JSON.parse(rv)),[eS,eC,rf,rx,rv]),ry=e?.id??tC.current??void 0,rw=(U=iY(H=(0,i.useMemo)(()=>({sessionId:ry,sessionProvider:te?.provider,turns:rb,messages:eS,subagents:to}),[ry,te?.provider,rb,eS,to])),q=i0(H),(0,i.useMemo)(()=>(function(e){let t=new Map;for(let n of e){let e=t.get(n.turnIndex);e?e.push(n):t.set(n.turnIndex,[n])}return t})(function(e){let t=[];for(let n of e){let e=t[t.length-1];if(e&&e.speakerId===n.speakerId&&e.turnIndex===n.turnIndex&&e.text===n.text){t[t.length-1]=n;continue}t.push(n)}return t}([...U,...q])),[U,q])),rk=ty&&0===eS.length&&!eN.isStreaming&&!t4,rj=e?.cwd??t??void 0,rS=te?eA[`${te.provider}:${te.modelId}`]??null:null,rC=te?eP[`${te.provider}:${te.modelId}`]??null:null,rN=(0,i.useRef)(null),rI=(0,i.useRef)(null),rT=(0,i.useCallback)(()=>{rN.current?.querySelector("textarea")?.focus({preventScroll:!0})},[]);(0,i.useEffect)(()=>(I?.(rT),()=>I?.(null)),[rT,I]),(0,i.useLayoutEffect)(()=>{let e=rI.current,t=e?.closest(".workspace-shell");if(!e||!t)return;let n=tI.current?.clientHeight??0,r=()=>{let r=Math.ceil(e.getBoundingClientRect().height);r>0&&t.style.setProperty("--omp-dock-h",`${r}px`);let i=tI.current;if(!i)return;let a=n-i.clientHeight;n=i.clientHeight,a<=0||i.scrollHeight-i.scrollTop-i.clientHeight-a<=1&&(i.scrollTop+=a)};r();let i=new ResizeObserver(r);return i.observe(e),()=>i.disconnect()},[ew,tI]);let rM=(0,i.useCallback)((...e)=>(null!==nd.end&&n$(),tT(...e)),[tT,nd.end,n$]),r$=(0,r.jsx)("div",{ref:rN,"data-chat-composer":"",style:{display:"contents"},children:(0,r.jsx)(sz,{ref:p,sessionId:e?.id??tC.current??void 0,onEnsureSession:ty&&t?tV:void 0,onLiveTranscriptPersisted:tJ,onSend:rM,onAbort:tM,onSteer:eI?tW:void 0,onFollowUp:eI?tF:void 0,onPromptWithStreamingBehavior:eI?t_:void 0,isStreaming:t4,model:te,isAutoModelSelection:tv,modelNames:e$,modelList:eR,modelError:eE,modelScopeWarnings:eL,onModelChange:tE,onMainPresetChange:e||ty?tA:void 0,mainPresetActiveAlias:tZ,modelRoles:eD,onRoleModelChange:tL,modelSwitching:tt,onCompact:e||ty?tP:void 0,onAbortCompaction:tD,isCompacting:e6,compactError:e3,compactResult:e9,toolPreset:eO,onToolPresetChange:e||ty?tU:void 0,thinkingLevel:eB,effectiveThinkingLevel:eU,thinkingCeiling:eK,onThinkingLevelChange:e||ty?tq:void 0,fastMode:eX,fastModeBusy:eQ,onFastModeToggle:e||ty?e1:void 0,availableThinkingLevels:rS,thinkingLevelMap:rC,retryInfo:e2,deliveryRows:tl,inputHistory:rh,onRecallQueue:tO,onRemoveQueuedMessage:tH,slashCommands:ta,slashCommandsLoading:ts,onLoadSlashCommands:tK,onBuiltinCommand:tB,soundEnabled:E,onSoundToggle:L,onAudioUnlock:P,draftKey:e?.id??(t?`new:${t}`:void 0),cwd:e?.cwd??t})}),rR=eN.streamingMessage,rE=(0,i.useMemo)(()=>rR?eF(rR,{isStreaming:!0}):[],[rR]),rL=(0,i.useMemo)(()=>rE.filter(e=>"answer"===e.kind).flatMap(e=>e.blocks),[rE]),rA=(0,i.useMemo)(()=>rE.filter(e=>"answer"!==e.kind).map(e=>e.blocks),[rE]),rz=rR?.role==="assistant"?rR:null,rP=eI&&(tb?.kind==="running_tools"||(rz?.content??[]).some(e=>"text"===e.type&&/\S/.test(e.text)||"toolCall"===e.type)),rW=iA(eS,rz,te?.provider),rF=rW.provider,r_=rW.credentialId;(0,i.useEffect)(()=>{if(!rP)return;let e=ec();e&&eo.current!==e.turn&&ed.current!==e.turn&&(eo.current=e.turn,ef("working",e,rF,r_))},[rP,rF,r_,ec,ef]);let[rD,rH]=(0,i.useState)(null),rB=(0,i.useCallback)(e=>{rH(e)},[]),rU=(0,i.useMemo)(()=>eM?{role:"bashExecution",command:eM.command,output:"",excludeFromContext:eM.excludeFromContext}:null,[eM]),rq=(0,i.useMemo)(()=>{let e=[eI&&!rR&&tb?function(e,t){if(e?.kind==="running_tools"){let n=e.tools.map(e=>e.name);return 0===n.length?t("chat.runningTool"):1===n.length?t("chat.runningNamedTool",{name:n[0]}):n.length<=3?t("chat.runningTools",{names:n.join(", ")}):t("chat.runningToolsMore",{names:n.slice(0,2).join(", "),count:n.length-2})}return e?.kind==="waiting_model"?t("chat.waitingModel"):e?.kind==="running_command"?t("chat.runningCommand"):null}(tb,K):null,eT&&!eM?K("chat.runningCommand"):null].filter(e=>!!e);return e.length>0?e.join(" \xb7 "):null},[eI,rR,tb,eT,eM,K]);(0,i.useEffect)(()=>{if(!rD)return void S?.(null);let e=[],t=[],n=0;if(rR&&rA.length>0){let r=rD.messages.length+e.length;for(let i of(e.push(rR),rA))t.push({idx:r,blocks:i}),n+=e_(i)}if(rU&&(t.push({idx:rD.messages.length+e.length}),e.push(rU)),0===t.length)return void S?.(rq?{...rD,status:rq}:rD);let r=-1;for(let e=rD.messages.length-1;e>=0;e--)if(eZ(rD.messages[e])){r=e;break}let i=rD.groups.slice(),a=i.length>0?i[i.length-1]:void 0;a&&a.anchorIdx===r?i[i.length-1]={...a,entries:[...a.entries,...t],messageCount:a.messageCount+t.length,toolCallCount:a.toolCallCount+n}:i.push({anchorIdx:r,entries:t,messageCount:t.length,toolCallCount:n}),S?.({...rD,groups:i,messages:[...rD.messages,...e],status:rq})},[rD,rA,rR,rU,rq,S]),(0,i.useEffect)(()=>()=>S?.(null),[S]);let rK=tf.filter(e=>"belowEditor"!==e.placement),rV=tf.filter(e=>"belowEditor"===e.placement);return ek?(0,r.jsx)("div",{className:"flex h-full items-center justify-center text-red-400",children:ek}):(0,r.jsxs)("div",{className:"chat-window relative flex h-full min-w-0 flex-col overflow-hidden","aria-busy":nn,style:{paddingBottom:"env(safe-area-inset-bottom)"},onDragEnter:rr,onDragOver:ri,onDragLeave:ra,onDrop:rs,children:[nn?(0,r.jsx)("div",{className:"absolute inset-0 z-40 cursor-wait",children:(0,r.jsx)("div",{className:"absolute right-3 top-3 border border-border bg-bg-panel px-3 py-2 text-sm text-text-muted shadow-sm",role:"status",children:K("chat.loadingSession")})}):null,rn&&!t4&&(0,r.jsx)("div",{className:"pointer-events-none absolute inset-0 z-50 flex animate-[drop-zone-in_0.15s_ease_both] items-center justify-center",style:{background:"var(--accent-soft)",border:"2px dashed var(--accent-line)"},children:(0,r.jsx)("span",{className:"px-3 py-1 text-sm font-medium",style:{background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",color:"var(--text)"},children:K("chat.attachFile")})}),th&&(0,r.jsx)(lW,{request:th,onInput:tx}),rk&&!N?(0,r.jsx)("div",{className:"flex flex-1 flex-col items-center overflow-y-auto px-4",children:(0,r.jsxs)("div",{className:"my-auto w-full max-w-[820px] py-8",children:[(0,r.jsxs)("div",{className:"mb-3",style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12,marginLeft:16,marginRight:52,fontFamily:"var(--font-mono)"},children:[(0,r.jsx)("div",{style:{minWidth:0,flex:1,overflow:"hidden"},children:(0,r.jsx)(V,{})}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",alignItems:"flex-end",gap:2,flexShrink:0},children:[(0,r.jsxs)("span",{style:{fontSize:11,color:"var(--text-muted)"},children:["web ",(0,r.jsxs)("span",{style:{color:"var(--text)"},children:["v","0.10.34"]})]}),(0,r.jsxs)("span",{style:{fontSize:11,color:"var(--text-muted)"},children:["omp ",(0,r.jsxs)("span",{style:{color:"var(--text)"},children:["v","18.12.1"]})]})]})]}),(0,r.jsx)(lA,{notices:tc,align:"right"})]})}):(0,r.jsxs)(r.Fragment,{children:[N&&(0,r.jsx)("div",{className:"min-h-0 min-w-0 flex-1 overflow-hidden",children:N}),(0,r.jsxs)("div",{className:"relative min-w-0 flex-1 overflow-hidden","aria-hidden":!!N,style:{display:N?"none":"flex"},children:[(0,r.jsx)("div",{style:{position:"absolute",top:12,left:0,right:0,zIndex:40,padding:"0 16px",pointerEvents:"none"},children:(0,r.jsxs)("div",{className:"chat-column-cap",style:{maxWidth:820,margin:"0 auto",display:"flex",flexDirection:"column",alignItems:"flex-end",gap:8},children:[(0,r.jsx)(ip,{open:nV,onClose:nQ,containerRef:tI,index:nZ,renderedStart:nu,renderedEnd:nf,contentKey:eS,onReveal:nX,onProgrammaticScroll:tj,focusRequest:nG,t:K}),nU&&(0,r.jsx)("div",{className:"chat-jump-missing",role:"status",children:K("chat.jumpMissing")}),(0,r.jsx)(lA,{notices:tc,floating:!0,align:"right"})]})}),(0,r.jsx)("div",{ref:tI,className:"chat-session-scroll relative min-w-0 flex-1 overflow-x-hidden overflow-y-auto pt-4 [scrollbar-width:none]",children:(0,r.jsx)("div",{style:{minWidth:0,padding:"0 16px"},children:(0,r.jsxs)("div",{className:"chat-column-cap",style:{width:"100%",minWidth:0,maxWidth:820,margin:"0 auto"},children:[(0,r.jsx)(lL,{widgets:rK}),(0,r.jsx)(nK.Provider,{value:rc,children:(0,r.jsx)(iD,{utterances:rw,children:(0,r.jsx)(l$,{messages:eS,entryIds:eC,toolResultsMap:ro,modelNames:e$,messageCwd:rj,onOpenFile:C,sessionBusy:t4,isNew:ty,isStreaming:eN.isStreaming,handleFork:t$,forkingEntryId:e5,handleNavigate:tR,handleEditContent:ey,sessionId:e?.id??tC.current??void 0,main:na,dispatchSlots:nl,compactedDispatch:no,process:ns,startIndex:nu,endIndex:nf,sentinelRef:nb,laterSentinelRef:ny,flashItem:nk,t:K,cues:ee,cueFollowRef:t6,onProcessLogChange:rB})})}),!nx&&eN.isStreaming&&eN.streamingMessage&&rL.length>0&&(0,r.jsx)(rO,{message:ez(eN.streamingMessage,rL),sessionId:e?.id??tC.current??void 0,isStreaming:!0,modelNames:e$,cwd:rj,onOpenFile:C}),n3&&(0,r.jsx)(ib,{onDismiss:n8,t:K}),(0,r.jsx)("div",{ref:tN})]})})}),(0,r.jsx)(ih,{questions:n0,containerRef:tI,layoutKey:n1,onJump:nM,label:K("chat.questionRail")}),(t4&&tw||nx)&&(0,r.jsxs)("button",{type:"button",onClick:nF,"aria-label":K("chat.jumpToBottom"),title:K("chat.jumpToBottom"),style:{position:"absolute",bottom:16,left:"50%",transform:"translateX(-50%)",zIndex:40,display:"flex",alignItems:"center",gap:6,padding:"6px 12px",minHeight:G?44:void 0,borderRadius:999,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)",fontSize:11,fontFamily:"var(--font-mono)",cursor:"pointer",boxShadow:"0 2px 10px rgba(0,0,0,0.28)"},children:[(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M12 5v14"}),(0,r.jsx)("path",{d:"m19 12-7 7-7-7"})]}),K("chat.jumpToBottom")]})]})]}),(0,r.jsxs)("div",{ref:rI,className:"relative chat-composer-dock flex min-h-0 flex-col",children:[tu&&(0,r.jsx)("div",{style:{padding:"0 16px"},children:(0,r.jsx)("div",{className:"chat-column-cap",style:{maxWidth:820,margin:"0 auto"},children:(0,r.jsx)(lP,{request:tu,onRespond:tg,onActivity:e=>void tx(e,"activity"),delivery:tp})})}),(0,r.jsx)("div",{className:"min-h-0 overflow-y-auto",style:{padding:"0 16px"},children:(0,r.jsxs)("div",{className:"chat-column-cap",style:{maxWidth:820,margin:"0 auto"},children:[(0,r.jsx)(iv,{compaction:e8,t:K}),(0,r.jsx)(lE,{goal:tS,t:K}),!Y&&(0,r.jsx)(io,{summary:ru,onJump:nM,onOpenPanel:rp}),(0,r.jsx)(lL,{widgets:rV}),rm&&!Y&&(0,r.jsx)(sW,{phases:rm})]})}),r$,(0,r.jsx)(sP,{statuses:tm})]})]})}function lE({goal:e,t}){if(!e)return null;let n=!e.enabled,i=void 0!==e.tokenBudget?t("chat.goalBudgetLeft",{left:t1(Math.max(0,e.tokenBudget-e.tokensUsed))}):t("chat.goalTokensUsed",{used:t1(e.tokensUsed)});return(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:8,padding:"5px 10px",border:"1px solid var(--border)",borderRadius:7,background:"var(--bg-panel)",color:"var(--text-muted)",fontSize:11,fontFamily:"var(--font-mono)",opacity:n?.7:1},children:[(0,r.jsx)("span",{style:{color:n?"var(--text-dim)":"var(--accent)",fontWeight:700,letterSpacing:"0.06em",textTransform:"uppercase",flexShrink:0},children:t("chat.goalLabel")}),(0,r.jsx)("span",{style:{minWidth:0,flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text)"},children:e.objective}),(0,r.jsx)("span",{style:{flexShrink:0,color:"var(--text-dim)"},children:n?t("chat.goalPaused"):e.status}),(0,r.jsx)("span",{style:{flexShrink:0,color:"var(--text-dim)"},children:i})]})}function lL({widgets:e}){return 0===e.length?null:(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:8,marginBottom:10},children:e.map(e=>(0,r.jsxs)("div",{style:{border:"1px solid var(--border)",borderRadius:7,background:"var(--bg-panel)",overflow:"hidden"},children:[(0,r.jsx)("div",{style:{padding:"5px 9px",borderBottom:"1px solid var(--border)",color:"var(--text-dim)",fontSize:11,fontFamily:"var(--font-mono)"},children:e.key}),(0,r.jsx)("pre",{style:{margin:0,padding:"8px 9px",color:"var(--text-muted)",fontSize:12,lineHeight:1.5,whiteSpace:"pre-wrap",wordBreak:"break-word",fontFamily:"var(--font-mono)"},children:e.lines.join("\n")})]},e.key))})}function lA({notices:e,floating:t=!1,align:n="left"}){return 0===e.length?null:(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",alignItems:"right"===n?"flex-end":"stretch",marginBottom:10*!t},children:e.map((n,i)=>{let a="error"===n.type?"var(--danger)":"warning"===n.type?"var(--warning)":"success"===n.type?"var(--success)":"var(--accent)";return(0,r.jsxs)("div",{className:"notice-shelf-item",style:{display:"flex",alignItems:"center",gap:10,minHeight:60,height:60,maxHeight:60,marginBottom:6*(i!==e.length-1),overflow:"hidden",borderRadius:"var(--seed-radius-r3)",border:"1px solid var(--border)",background:"var(--bg)",color:"var(--text-muted)",width:"fit-content",maxWidth:"min(100%, 620px)",boxShadow:t?"var(--seed-shadow-s3)":"var(--seed-shadow-s2)",fontSize:18,lineHeight:1.45,transformOrigin:"top center",animation:n.exiting?"notice-shelf-out 0.18s ease-in forwards":"notice-shelf-in 0.18s ease-out both",padding:"0 12px"},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:a,flexShrink:0}}),(0,r.jsx)("span",{style:{padding:"14px 0",minWidth:0,maxWidth:"100%",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:n.message})]},n.id)})})}function lz({focusKey:e,label:t,labelledBy:n,maxBlockSize:a="min(56dvh, 620px)",onCancel:s,delivery:l,children:o}){let{t:d}=(0,R.s)(),c=(0,i.useRef)(null),u=(0,i.useRef)({key:"",element:null});if(u.current.key!==e){let t="u"<typeof document?null:document.activeElement;u.current={key:e,element:t instanceof HTMLElement&&!c.current?.contains(t)?t:null}}return(0,i.useEffect)(()=>{let e=c.current;e&&!e.contains(document.activeElement)&&(e.querySelector('button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])')??e).focus();let t=u.current.element;return()=>{if(!t?.isConnected)return;let n=document.activeElement;(null===n||n===document.body||e?.contains(n))&&t.focus()}},[e]),(0,r.jsxs)("div",{ref:c,role:"dialog","aria-modal":"false","aria-label":t,"aria-labelledby":n,className:"chat-response-surface",tabIndex:-1,onKeyDown:s?e=>{"Escape"===e.key&&(e.stopPropagation(),s())}:void 0,"aria-busy":l?.status==="sending"||void 0,style:{maxBlockSize:a},children:[l?(0,r.jsx)("p",{className:"chat-response-delivery",role:"failed"===l.status?"alert":"status","data-state":l.status,children:"sending"===l.status?d("chat.responseSending"):`${d("chat.responseFailed")}${l.error?` (${l.error})`:""}`}):null,o]})}function lP({request:e,onRespond:t,onActivity:n,delivery:a}){let{t:s}=(0,R.s)(),[l,o]=(0,i.useState)("editor"===e.method?e.prefill??"":""),[d,c]=(0,i.useState)({selected:{},custom:{}}),[u,p]=(0,i.useState)(""),h=(0,i.useRef)(0),m=(0,i.useCallback)(()=>{if("ask"!==e.method||!e.timeout||!n)return;let t=Date.now();t-h.current<1e3||(h.current=t,n(e))},[e,n]);(0,i.useEffect)(()=>{o("editor"===e.method?e.prefill??"":""),p(""),c("ask"===e.method?function(e){let t={};for(let n of e)t[n.id]=void 0!==n.recommended&&void 0!==n.options[n.recommended]?[n.recommended]:[];return{selected:t,custom:{}}}(e.questions):{selected:{},custom:{}})},[e]);let f=()=>{"confirm"===e.method?t(e,{confirmed:!0}):t(e,{value:l})};if("ask"===e.method){var g;let n=(g=e.questions,g.every(e=>(d.selected[e.id]?.length??0)>0||(d.custom[e.id]?.trim().length??0)>0)),i=()=>{if(n){var r;t(e,{value:(r=e.questions,JSON.stringify({kind:"submit",results:r.map(e=>{let t=d.custom[e.id]?.trim();return{id:e.id,question:e.question,options:e.options.map(e=>e.label),multi:e.multi??!1,selectedOptions:(d.selected[e.id]??[]).map(t=>e.options[t]?.label).filter(e=>void 0!==e),...t?{customInput:t}:{}}})}))})}};return(0,r.jsx)(lz,{focusKey:e.id,label:s("chat.agentQuestion"),onCancel:()=>t(e,{cancelled:!0}),delivery:a,children:(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",minHeight:0},children:[(0,r.jsx)("div",{style:{display:"flex",alignItems:"center",gap:10,padding:"12px 16px",borderBottom:"1px solid var(--border)"},children:(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("div",{style:{color:"var(--text)",fontSize:"var(--seed-font-size-t4-static)",fontWeight:600},children:s("chat.agentQuestion")}),(0,r.jsx)("div",{style:{marginTop:2,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)"},children:s("chat.agentQuestionHint")}),e.timeout?(0,r.jsx)("div",{style:{marginTop:2,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)"},children:s("chat.askAutoSelectHint",{seconds:Math.round(e.timeout/1e3)})}):null]})}),(0,r.jsx)("div",{style:{flex:"1 1 auto",minHeight:0,overflowY:"auto",padding:16},children:(0,r.jsx)("div",{style:{display:"grid",gap:20},children:e.questions.map((t,n)=>{let a=d.selected[t.id]??[];return(0,r.jsxs)("section",{style:{paddingTop:20*(0!==n),borderTop:0===n?"none":"1px solid var(--hairline)"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"baseline",gap:8,marginBottom:10},children:[t.header&&(0,r.jsx)("span",{style:{color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontWeight:600},children:t.header}),e.questions.length>1&&(0,r.jsxs)("span",{style:{marginLeft:"auto",color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontVariantNumeric:"tabular-nums"},children:[n+1,"/",e.questions.length]})]}),(0,r.jsx)("div",{style:{marginBottom:10,color:"var(--text)",fontSize:"var(--seed-font-size-t4-static)",fontWeight:600,lineHeight:1.5},children:t.question}),(0,r.jsx)("div",{role:t.multi?"group":"radiogroup","aria-label":t.question,style:{display:"grid",gap:4},children:t.options.map((e,n)=>{let i=a.includes(n),l=t.recommended===n;return(0,r.jsxs)("button",{type:"button",role:t.multi?"checkbox":"radio","aria-checked":i,onClick:()=>{m(),c(e=>(function(e,t,n){let r=e.selected[t.id]??[];if(t.multi){let i=r.includes(n)?r.filter(e=>e!==n):[...r,n];return{...e,selected:{...e.selected,[t.id]:i}}}return{selected:{...e.selected,[t.id]:[n]},custom:{...e.custom,[t.id]:""}}})(e,t,n))},style:{display:"grid",gridTemplateColumns:"18px minmax(0, 1fr) auto",alignItems:"start",gap:9,width:"100%",minHeight:40,padding:"9px 10px",border:`1px solid ${i?"var(--border-strong)":"transparent"}`,borderRadius:"var(--radius-control)",background:i?"var(--bg-selected)":"transparent",color:"var(--text)",cursor:"pointer",textAlign:"left"},children:[(0,r.jsx)("span",{"aria-hidden":"true",style:{display:"grid",placeItems:"center",width:16,height:16,marginTop:1,border:`1px solid ${i?"var(--text)":"var(--text-dim)"}`,borderRadius:t.multi?"var(--radius-control)":"50%",background:i?"var(--seed-color-fg-neutral)":"transparent",color:"var(--seed-color-fg-neutral-inverted)",fontSize:"var(--seed-font-size-t2-static)",lineHeight:1},children:i&&(t.multi?(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"2 5.2 4.1 7.2 8 2.8"})}):(0,r.jsx)("span",{style:{width:5,height:5,borderRadius:"50%",background:"currentColor"}}))}),(0,r.jsxs)("span",{style:{minWidth:0},children:[(0,r.jsx)("span",{style:{display:"block",fontSize:"var(--seed-font-size-t4-static)",fontWeight:i?600:500},children:e.label}),e.description&&(0,r.jsx)("span",{style:{display:"block",marginTop:3,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.45},children:e.description}),i&&e.preview&&(0,r.jsx)("span",{style:{display:"block",marginTop:8,padding:"7px 8px",borderLeft:"2px solid var(--border-strong)",background:"var(--bg-subtle)",color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.5,whiteSpace:"pre-wrap"},children:e.preview})]}),l&&(0,r.jsx)("span",{style:{color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontWeight:600},children:s("chat.recommended")})]},`${t.id}:${n}`)})}),(0,r.jsx)("input",{value:d.custom[t.id]??"",onChange:e=>{m();let n=e.target.value;c(e=>{let r;return r={...e.custom,[t.id]:n},t.multi||0===n.trim().length?{...e,custom:r}:{selected:{...e.selected,[t.id]:[]},custom:r}})},onKeyDown:e=>{(e.metaKey||e.ctrlKey)&&"Enter"===e.key&&i()},placeholder:s("chat.customAnswer"),"aria-label":s("chat.customAnswer"),style:{width:"100%",height:36,marginTop:9,padding:"0 10px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"var(--bg)",color:"var(--text)",fontFamily:"var(--seed-font-family)",fontSize:"var(--seed-font-size-t4-static)"}})]},t.id)})})}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",justifyContent:"flex-end",gap:8,padding:"12px 16px",borderTop:"1px solid var(--border)"},children:[(0,r.jsx)("button",{type:"button",onClick:()=>t(e,{cancelled:!0}),style:{minHeight:36,padding:"0 12px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"transparent",color:"var(--text-muted)",cursor:"pointer"},children:s("chat.cancel")}),(0,r.jsx)("button",{type:"button",onClick:()=>t(e,{value:JSON.stringify({kind:"chat"})}),style:{minHeight:36,padding:"0 12px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"transparent",color:"var(--text)",cursor:"pointer"},children:s("chat.chatAboutThis")}),(0,r.jsx)("button",{type:"button",disabled:!n||a?.status==="sending",onClick:i,style:{minHeight:36,padding:"0 14px",border:"1px solid transparent",borderRadius:"var(--radius-control)",background:n&&a?.status!=="sending"?"var(--seed-color-bg-neutral-inverted)":"var(--seed-color-bg-disabled)",color:n&&a?.status!=="sending"?"var(--seed-color-fg-neutral-inverted)":"var(--seed-color-fg-disabled)",cursor:n&&a?.status!=="sending"?"pointer":"not-allowed",fontWeight:600},children:a?.status==="sending"?s("chat.responseSending"):s("chat.submitAnswer")})]})]})})}return"plan_review"===e.method?(0,r.jsx)(lz,{focusKey:e.id,labelledBy:`plan-review-${e.id}`,maxBlockSize:"min(64dvh, 760px)",delivery:a,children:(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",minHeight:0},children:[(0,r.jsxs)("div",{style:{padding:"12px 16px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("div",{style:{color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontWeight:600},children:s("chat.planApproval")}),(0,r.jsx)("div",{id:`plan-review-${e.id}`,style:{marginTop:4,color:"var(--text)",fontSize:"var(--seed-font-size-t5-static)",fontWeight:600},children:e.title}),(0,r.jsx)("div",{style:{marginTop:5,color:"var(--text-muted)",fontFamily:"var(--font-mono)",fontSize:"var(--seed-font-size-t2-static)",overflowWrap:"anywhere"},children:e.planFilePath})]}),(0,r.jsx)("div",{style:{flex:"1 1 auto",minHeight:0,overflowY:"auto",padding:"18px 20px"},children:(0,r.jsx)(tG,{children:e.planContent})}),(0,r.jsxs)("div",{style:{padding:"12px 16px",borderTop:"1px solid var(--border)"},children:[(0,r.jsx)("textarea",{value:u,onChange:e=>p(e.target.value),placeholder:s("chat.planFeedback"),"aria-label":s("chat.planFeedback"),style:{width:"100%",minHeight:64,maxHeight:150,padding:"9px 10px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",outline:"none",resize:"vertical",background:"var(--bg)",color:"var(--text)",fontFamily:"var(--seed-font-family)",fontSize:"var(--seed-font-size-t4-static)",lineHeight:1.5}}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",justifyContent:"flex-end",gap:8,marginTop:9},children:[(0,r.jsx)("button",{type:"button",onClick:()=>t(e,{value:JSON.stringify({action:"refine",feedback:u.trim()})}),style:{minHeight:36,padding:"0 12px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"transparent",color:"var(--text)",cursor:"pointer"},children:s("chat.refinePlan")}),(0,r.jsx)("button",{type:"button",onClick:()=>t(e,{value:JSON.stringify({action:"approve"})}),style:{minHeight:36,padding:"0 14px",border:"1px solid transparent",borderRadius:"var(--radius-control)",background:"var(--seed-color-bg-neutral-inverted)",color:"var(--seed-color-fg-neutral-inverted)",cursor:"pointer",fontWeight:600},children:s("chat.approvePlan")})]})]})]})}):(0,r.jsx)(lz,{focusKey:e.id,labelledBy:`extension-request-${e.id}`,onCancel:()=>t(e,{cancelled:!0}),delivery:a,children:(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",minHeight:0},children:[(0,r.jsxs)("div",{style:{padding:"12px 14px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("div",{id:`extension-request-${e.id}`,style:{color:"var(--text)",fontSize:"var(--seed-font-size-t4-static)",fontWeight:600},children:e.title}),(0,r.jsx)("div",{style:{marginTop:3,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontFamily:"var(--font-mono)"},children:s("chat.extensionRequest")})]}),(0,r.jsxs)("div",{style:{flex:"1 1 auto",minHeight:0,overflowY:"auto",padding:14},children:["confirm"===e.method&&(0,r.jsx)("div",{style:{color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.6,whiteSpace:"pre-wrap"},children:e.message}),"select"===e.method&&(0,r.jsx)("div",{style:{display:"grid",gap:8},children:e.options.map(n=>(0,r.jsx)("button",{onClick:()=>t(e,{value:n}),style:{width:"100%",minHeight:40,padding:"9px 10px",borderRadius:"var(--radius-control)",border:"1px solid var(--border)",background:"transparent",color:"var(--text)",cursor:"pointer",textAlign:"left",fontSize:"var(--seed-font-size-t4-static)"},children:n},n))}),"input"===e.method&&(0,r.jsx)("input",{autoFocus:!0,value:l,placeholder:e.placeholder,onChange:e=>o(e.target.value),onKeyDown:e=>{"Enter"===e.key&&f()},style:{width:"100%",padding:"9px 10px",borderRadius:"var(--radius-control)",border:"1px solid var(--border)",background:"var(--bg)",color:"var(--text)",outline:"none",fontSize:"var(--seed-font-size-t4-static)"}}),"editor"===e.method&&(0,r.jsx)("textarea",{autoFocus:!0,value:l,onChange:e=>o(e.target.value),onKeyDown:e=>{(e.metaKey||e.ctrlKey)&&"Enter"===e.key&&f()},style:{width:"100%",minHeight:220,padding:10,borderRadius:"var(--radius-control)",border:"1px solid var(--border)",background:"var(--bg)",color:"var(--text)",outline:"none",resize:"vertical",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.55,fontFamily:"var(--font-mono)"}})]}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",justifyContent:"flex-end",gap:8,padding:"12px 14px",borderTop:"1px solid var(--border)"},children:[(0,r.jsx)("button",{onClick:()=>t(e,{cancelled:!0}),style:{minHeight:36,padding:"0 12px",borderRadius:"var(--radius-control)",border:"1px solid var(--border)",background:"transparent",color:"var(--text-muted)",cursor:"pointer"},children:s("chat.cancel")}),"confirm"===e.method?(0,r.jsx)("button",{onClick:f,style:{minHeight:36,padding:"0 14px",borderRadius:"var(--radius-control)",border:"1px solid transparent",background:"var(--seed-color-bg-neutral-inverted)",color:"var(--seed-color-fg-neutral-inverted)",cursor:"pointer",fontWeight:600},children:s("chat.confirm")}):"select"!==e.method?(0,r.jsx)("button",{onClick:f,style:{minHeight:36,padding:"0 14px",borderRadius:"var(--radius-control)",border:"1px solid transparent",background:"var(--seed-color-bg-neutral-inverted)",color:"var(--seed-color-fg-neutral-inverted)",cursor:"pointer",fontWeight:600},children:s("chat.submit")}):null]})]})})}function lW({request:e,onInput:t}){let{t:n}=(0,R.s)(),a=(0,i.useRef)(null),s=(0,i.useRef)(!1),l=eI(e.lines);return(0,i.useEffect)(()=>{a.current?.focus()},[e.id]),(0,r.jsx)("div",{style:{position:"absolute",inset:0,zIndex:95,display:"flex",alignItems:"center",justifyContent:"center",padding:20,background:"var(--seed-color-bg-overlay-muted)"},children:(0,r.jsxs)("div",{role:"dialog","aria-modal":"true",onClick:e=>{e.target.closest("button")||a.current?.focus()},style:{position:"relative",width:"min(920px, 100%)",maxHeight:"min(760px, calc(100vh - 40px))",border:"1px solid var(--border)",borderRadius:8,background:"var(--bg)",boxShadow:"var(--seed-shadow-s3)",overflow:"hidden",outline:"none"},children:[(0,r.jsx)("textarea",{ref:a,"aria-label":n("chat.extensionInput"),autoCapitalize:"off",autoComplete:"off",autoCorrect:"off",spellCheck:!1,onKeyDown:n=>{if(s.current||n.nativeEvent.isComposing)return;let r=function(e){if(e.metaKey||e.ctrlKey&&!e.altKey&&"v"===e.key.toLowerCase())return null;if(e.ctrlKey&&!e.altKey){let t=function(e){if(1!==e.length)return null;let t=e.toUpperCase().charCodeAt(0);return t>=64&&t<=95?String.fromCharCode(31&t):"?"===e?"":null}(e.key);if(t)return t}if(e.altKey&&!e.ctrlKey){if("Backspace"===e.key)return"\x1b\x7f";let t=e$[e.key];if(t)return t;if(1===e.key.length)return`\x1b${e.key}`}return"Enter"===e.key?e.shiftKey?"\n":"\r":"Tab"===e.key?e.shiftKey?"\x1b[Z":" ":eM[e.key]??null}(n);r&&(n.preventDefault(),n.stopPropagation(),t(e,r))},onInput:n=>{if(s.current||n.nativeEvent.isComposing)return;let r=n.currentTarget.value;n.currentTarget.value="",r&&t(e,r)},onCompositionStart:()=>{s.current=!0},onCompositionEnd:n=>{s.current=!1;let r=n.currentTarget;queueMicrotask(()=>{let n=r.value;r.value="",n&&t(e,n)})},onPaste:n=>{n.preventDefault();let r=n.clipboardData.getData("text");r&&t(e,`\x1b[200~${r}\x1b[201~`)},style:{position:"absolute",width:1,height:1,padding:0,border:0,opacity:0,pointerEvents:"none"}}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12,padding:"10px 12px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("div",{style:{color:"var(--text)",fontSize:13,fontWeight:650},children:n("chat.extensionPanel")}),(0,r.jsx)("button",{onClick:()=>t(e,"\x03"),style:{padding:"5px 9px",borderRadius:6,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)",cursor:"pointer",fontSize:12},children:n("chat.close")})]}),(0,r.jsx)("pre",{style:{margin:0,padding:14,maxHeight:"calc(min(760px, 100vh - 40px) - 48px)",overflow:"auto",background:"var(--bg-panel)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:13,lineHeight:1.45,whiteSpace:"pre"},children:(l.length?l:[""]).map((e,t,n)=>{var a;return(0,r.jsxs)(i.Fragment,{children:[(a=`line-${t}`,eT(e).map((e,t)=>Object.keys(e.style).length>0?(0,r.jsx)("span",{style:e.style,children:e.text},`${a}-${t}`):e.text)),t<n.length-1?"\n":null]},t)})})]})})}function lF({onPick:e,t}){let[n,a]=(0,i.useState)(""),[s,l]=(0,i.useState)({kind:"idle"}),o=(0,i.useRef)(null),d=n.trim();(0,i.useEffect)(()=>{if(d.length<2)return void l({kind:"idle"});let e=new AbortController;l({kind:"loading"});let t=setTimeout(()=>{fetch(`/api/sessions/search?q=${encodeURIComponent(d)}`,{signal:e.signal,cache:"no-store"}).then(async e=>{if(!e.ok)throw Error(`HTTP ${e.status}`);l({kind:"done",data:await e.json()})}).catch(()=>{e.signal.aborted||l({kind:"error"})})},250);return()=>{clearTimeout(t),e.abort()}},[d]);let c=e=>{let t=o.current?.querySelectorAll("button");t&&0!==t.length&&t[Math.max(0,Math.min(t.length-1,e))]?.focus()},u="done"===s.kind?s.data:null,p=u?.truncated?t(`palette.searchTruncated.${u.truncated}`,{scanned:u.scannedSessions,total:u.totalSessions}):null;return(0,r.jsxs)("div",{className:"palette-search",children:[(0,r.jsx)("input",{type:"search",value:n,onChange:e=>a(e.target.value),onKeyDown:t=>{if(!t.nativeEvent.isComposing){if("ArrowDown"===t.key)t.preventDefault(),c(0);else if("Enter"===t.key&&u&&u.hits.length>0){t.preventDefault();let n=u.hits[0],r=u.sessions[n.sessionId];r&&e(r,n,u.query)}}},placeholder:t("palette.searchPlaceholder"),"aria-label":t("palette.searchPlaceholder"),autoComplete:"off",spellCheck:!1}),d.length>=2&&(0,r.jsxs)("div",{className:"palette-search-results",role:"region","aria-label":t("palette.searchResults"),"aria-busy":"loading"===s.kind,children:[(0,r.jsxs)("p",{className:"palette-search-status","aria-live":"polite",children:["loading"===s.kind&&t("palette.searching"),"error"===s.kind&&t("palette.searchFailed"),u&&(0===u.hits.length?t("palette.searchEmpty"):t("palette.searchHits",{count:u.hits.length})),p?` \xb7 ${p}`:"",u&&u.compactedHits>0?` \xb7 ${t("palette.searchCompacted",{count:u.compactedHits})}`:""]}),u&&u.hits.length>0&&(0,r.jsx)("div",{ref:o,className:"palette-search-list",children:u.hits.map((n,i)=>{let a=u.sessions[n.sessionId],s=n.matchStart+u.query.length;return(0,r.jsxs)("button",{type:"button",disabled:!a,onClick:()=>a&&e(a,n,u.query),onKeyDown:e=>{("ArrowDown"===e.key||"ArrowUp"===e.key)&&(e.preventDefault(),c(i+("ArrowDown"===e.key?1:-1)))},children:[(0,r.jsxs)("span",{className:"palette-search-title",children:[(0,r.jsx)("span",{children:a?a.name?.trim()||a.firstMessage?.trim()||a.id:""}),(0,r.jsx)("small",{children:"user"===n.role?t("palette.searchRoleUser"):t("palette.searchRoleAssistant")})]}),(0,r.jsxs)("span",{className:"palette-search-snippet",children:[n.snippet.slice(0,n.matchStart),(0,r.jsx)("mark",{children:n.snippet.slice(n.matchStart,s)}),n.snippet.slice(s)]})]},`${n.sessionId}:${n.entryId}`)})})]})]})}var l_=n(50640),lD=n(73620);let lO=/^(?:\uFEFF)?---[ \t]*(?:\r\n|\n|\r)/;function lH(e){return function e(t,n){if(null==t)return"";if("string"==typeof t)return t;if("number"==typeof t||"boolean"==typeof t)return String(t);if(Array.isArray(t)){if(n.has(t))return"[Circular]";n.add(t);try{return t.map(t=>e(t,n)).filter(Boolean).join(", ")}finally{n.delete(t)}}if("object"==typeof t)try{return JSON.stringify(t)??Object.prototype.toString.call(t)}catch{return Object.prototype.toString.call(t)}return String(t)}(e,new WeakSet)}let lB=["tags","categories","keywords","tag","category"];function lU({data:e}){var t;if(!e)return null;let n=Object.entries(e);if(0===n.length)return null;let i="string"==typeof(t=e.title)?t.trim()||null:"number"==typeof t||"boolean"==typeof t?String(t):null,a=lB.find(t=>Array.isArray(e[t])),s=a?e[a].map(lH).filter(Boolean):[],l=n.filter(([e])=>e!==a&&("title"!==e||!i));return(0,r.jsxs)("div",{className:"markdown-frontmatter",children:[i&&(0,r.jsx)("div",{className:"markdown-frontmatter-title",children:i}),s.length>0&&(0,r.jsx)("div",{className:"markdown-frontmatter-tags",children:s.map((e,t)=>(0,r.jsx)("span",{className:"markdown-frontmatter-tag",children:e},`${e}-${t}`))}),l.length>0&&(0,r.jsx)("dl",{className:"markdown-frontmatter-rows",children:l.map(([e,t])=>(0,r.jsxs)("div",{className:"markdown-frontmatter-row",children:[(0,r.jsx)("dt",{children:e}),(0,r.jsx)("dd",{children:function(e){let t=lH(e);return t?"string"==typeof e&&/^(https?:\/\/|mailto:)/i.test(e)?(0,r.jsx)("a",{href:e,target:"_blank",rel:"noopener noreferrer",children:t}):t:null}(t)})]},e))})]})}var lq=n(8745);let lK=(0,i.createContext)(null),lV=(0,r.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M9.5 2.5h4v4M6.5 13.5h-4v-4M13.5 2.5 9 7M2.5 13.5 7 9"})}),lJ=(0,r.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M13.5 6.5h-4v-4M2.5 9.5h4v4M9.5 6.5l4-4M6.5 9.5l-4 4"})}),lG=(0,r.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m10 3-5 5 5 5"})}),lY=(0,r.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m4 4 8 8M12 4l-8 8"})}),lZ=(0,r.jsxs)("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"currentColor","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"3.5",cy:"8",r:"1.2"}),(0,r.jsx)("circle",{cx:"8",cy:"8",r:"1.2"}),(0,r.jsx)("circle",{cx:"12.5",cy:"8",r:"1.2"})]});function lX({back:e,title:t,titleTooltip:n,titleRef:i,titleAdornment:a,subtitle:o,subtitleKind:c="text",state:u,viewSwitch:p,actions:h=[],close:m}){let{t:f}=(0,R.s)();return(0,r.jsxs)("header",{className:"panel-header",children:[e&&(0,r.jsx)(s.r,{className:"panel-header-button",variant:"ghost",size:"small",layout:"iconOnly",onClick:e.onClick,"aria-label":e.label,title:e.label,children:(0,r.jsx)(l.In,{size:"16px",svg:lG})}),(0,r.jsxs)("div",{className:"panel-header-heading",children:[(0,r.jsx)("h2",{className:"panel-header-title",title:n,ref:i,tabIndex:i?-1:void 0,children:t}),a,o&&("path"===c?(0,r.jsx)("span",{className:"panel-header-subtitle is-path",title:o,dir:"rtl",children:(0,r.jsx)("bdi",{dir:"ltr",children:o})}):(0,r.jsx)("span",{className:"panel-header-subtitle",title:o,children:o}))]}),u&&(0,r.jsx)("div",{className:"panel-header-state",children:u}),p&&p.options.length>1&&(0,r.jsxs)(lq.A.Root,{className:"panel-header-switch","aria-label":p.label,value:p.value,onValueChange:e=>p.onChange(e),children:[p.options.map(e=>(0,r.jsxs)(lq.A.Item,{value:e.value,title:e.title,children:[(0,r.jsx)(lq.A.ItemHiddenInput,{}),e.label]},e.value)),(0,r.jsx)(lq.A.Indicator,{})]}),h.length>0&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{className:"panel-header-actions",children:h.map(e=>e.href?(0,r.jsx)("a",{className:"panel-header-link-button",href:e.href,download:e.download,"aria-label":e.label,title:e.title??e.label,children:e.icon},e.id):(0,r.jsx)(s.r,{className:"panel-header-button",variant:"ghost",size:"small",layout:"iconOnly",onClick:e.onClick,onPointerDown:e.onPointerDown,disabled:e.disabled,"aria-pressed":e.pressed,"aria-label":e.label,title:e.title??e.label,children:(0,r.jsx)(l.In,{size:"16px",svg:e.icon})},e.id))}),(0,r.jsxs)(d.k.Root,{placement:"bottom-end",strategy:"fixed",children:[(0,r.jsx)(d.k.Trigger,{asChild:!0,children:(0,r.jsx)(s.r,{className:"panel-header-button panel-header-more",variant:"ghost",size:"small",layout:"iconOnly","aria-label":f("panel.more"),title:f("panel.more"),children:(0,r.jsx)(l.In,{size:"16px",svg:lZ})})}),(0,r.jsx)(d.k.Positioner,{children:(0,r.jsx)(d.k.Content,{"aria-label":f("panel.more"),children:(0,r.jsx)(d.k.ScrollArea,{children:(0,r.jsx)(d.k.Group,{children:h.map(e=>(0,r.jsx)(d.k.Item,{disabled:e.disabled,onClick:()=>(function(e){if(e.onClick)return void e.onClick();if(!e.href)return;let t=document.createElement("a");t.href=e.href,e.download&&(t.download=e.download),t.click()})(e),children:(0,r.jsx)(d.k.ItemBody,{children:(0,r.jsx)(d.k.ItemLabel,{children:e.label})})},e.id))})})})})]})]}),(0,r.jsx)(lQ,{}),m&&(0,r.jsx)(s.r,{className:"panel-header-button",variant:"ghost",size:"small",layout:"iconOnly",onClick:m.onClick,"aria-label":m.label,title:m.label,children:(0,r.jsx)(l.In,{size:"16px",svg:lY})})]})}function lQ({className:e="panel-header-button"}){let{t}=(0,R.s)(),n=(0,i.useContext)(lK);if(!n)return null;let a=t(n.expanded?"panel.restore":"panel.expand");return(0,r.jsx)(s.r,{className:e,"data-panel-expand":"",variant:"ghost",size:"small",layout:"iconOnly","aria-pressed":n.expanded,"aria-label":a,title:a,onClick:n.onToggle,children:(0,r.jsx)(l.In,{size:"16px",svg:n.expanded?lJ:lV})})}let l0={source:"Source",preview:"Preview",diff:"Diff"},l1={fontFamily:"var(--font-mono)",fontSize:13,lineHeight:1.6},l2={width:48,minWidth:48,padding:"0 10px",textAlign:"right",color:"var(--text-dim)",background:"var(--bg-panel)",borderRight:"1px solid var(--border)",fontFamily:"var(--font-mono)",fontSize:11,fontStyle:"normal",fontVariantNumeric:"tabular-nums",lineHeight:"20.8px",userSelect:"none",flexShrink:0,verticalAlign:"top"};function l4(){return(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"4"}),(0,r.jsx)("path",{d:"M16 8v5a3 3 0 0 0 6 0v-1a10 10 0 1 0-4 8"})]})}function l5(e){let t=e.nodeType===Node.ELEMENT_NODE?e:e.parentElement;return t?.closest(".file-source-line[data-line-number]")??null}function l6(e,t){if(!t||t.isCollapsed||0===t.rangeCount)return null;let n=t.getRangeAt(0);if(!e.contains(n.startContainer)||!e.contains(n.endContainer))return null;let r=l5(n.startContainer),i=l5(n.endContainer);if(!r||!i||!e.contains(r)||!e.contains(i))return null;let a=Number(r.dataset.lineNumber),s=Number(i.dataset.lineNumber);if(!Number.isInteger(a)||!Number.isInteger(s))return null;if(a<s){let e=r.querySelector(".file-source-line-content");if(e?.contains(n.startContainer)){let t=document.createRange();if(t.selectNodeContents(e),t.setStart(n.startContainer,n.startOffset),0===t.toString().length){let e=r.nextElementSibling;e instanceof HTMLElement&&e.matches(".file-source-line[data-line-number]")&&(a=Number((r=e).dataset.lineNumber))}}let t=i.querySelector(".file-source-line-content");if(t?.contains(n.endContainer)){let e=document.createRange();if(e.selectNodeContents(t),e.setEnd(n.endContainer,n.endOffset),0===e.toString().length){let e=i.previousElementSibling;e instanceof HTMLElement&&e.matches(".file-source-line[data-line-number]")&&(s=Number((i=e).dataset.lineNumber))}}}return a>s?null:{startLine:a,endLine:s}}function l8({rows:e,stylesheet:t,useInlineStyles:n,wrapLines:i}){return e.map((e,a)=>{let s=e.children??[],l=s[0]?.properties?.className,o=Array.isArray(l)&&l.includes("react-syntax-highlighter-line-number"),d=o?s[0]:null,c=o?s.slice(1):s;return(0,r.jsxs)("span",{className:"file-source-line","data-line-number":a+1,style:{display:"flex",minWidth:"100%"},children:[d&&(0,l_.Ay)({node:d,stylesheet:t,useInlineStyles:n,key:`source-line-number-${a}`}),(0,r.jsx)("span",{className:"file-source-line-content",style:{flex:"1 1 auto",minWidth:0,overflowWrap:i?"anywhere":"normal",whiteSpace:i?"pre-wrap":"pre"},children:c.map((e,r)=>(0,l_.Ay)({node:e,stylesheet:t,useInlineStyles:n,key:`source-token-${a}-${r}`}))})]},`source-line-${a}`)})}let l3=(0,i.memo)(function({content:e,language:t,isDark:n,wrapLines:i}){return(0,r.jsx)(te.A,{className:i?"file-source-view is-wrapped":"file-source-view",language:"text"===t?"plaintext":t,style:n?tt.xJ:tt.vs,showLineNumbers:!0,lineNumberStyle:{...l2},customStyle:{margin:0,padding:0,border:0,background:"var(--bg)",...l1,width:i?"100%":"max-content",minWidth:"100%",minHeight:"100%",overflow:"visible"},codeTagProps:{style:{fontFamily:"var(--font-mono)",overflowWrap:i?"anywhere":"normal"}},renderer:e=>(0,r.jsx)(l8,{...e,wrapLines:i}),wrapLongLines:i,children:e})});function l7(e,t,n,r={}){let i=ti(e),a=new URLSearchParams({type:t});for(let[e,t]of(n&&a.set("sessionId",n),Object.entries(r)))void 0!==t&&a.set(e,String(t));return`/api/files/${i}?${a.toString()}`}let l9=(0,r.jsxs)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),(0,r.jsx)("polyline",{points:"7 10 12 15 17 10"}),(0,r.jsx)("line",{x1:"12",y1:"15",x2:"12",y2:"3"})]}),oe=(0,r.jsxs)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M3 6h18"}),(0,r.jsx)("path",{d:"M3 12h15a3 3 0 1 1 0 6h-4"}),(0,r.jsx)("path",{d:"m16 16-2 2 2 2"}),(0,r.jsx)("path",{d:"M3 18h7"})]});function ot({filePath:e,cwd:t,sourceSessionId:n,meta:i,watching:a,viewSwitch:s,actions:l=[],downloadable:o=!0}){let{t:d}=(0,R.s)(),c=ta(e),u=ts(e,t),p=u.endsWith(c)?u.slice(0,u.length-c.length).replace(/[\\/]+$/,""):"",h=d(a?"panel.liveSync":"i18n.notWatching");return(0,r.jsx)(lX,{title:c,titleTooltip:`${u}
19
+ ${n}`:e:n,images:s,documents:l}}function aW(e,t,n){if(e===t)return n?aR(n):aL(t);let r=aL(e),i=n&&!aE(n)?aR(n):r??(n?aR(n):null),a=aL(t),s=ag.get(e);if(ag.delete(e),s&&!ag.has(t)&&ag.set(t,s),az(e),!i)return a;let l=a?aP(a.value,a.images,i.value,i.images,a.documents,i.documents):i;return aA(t,l),aR(l)}function aF(e){let t=[];for(let n of e??[])n.attachmentId&&!t.includes(n.attachmentId)&&t.push(n.attachmentId);return t}function a_(e){aM();let t=ag.get(e);return t||(t=function(){let e=globalThis.crypto;if("function"==typeof e?.randomUUID)return e.randomUUID();let t=e.getRandomValues(new Uint8Array(16));t[6]=15&t[6]|64,t[8]=63&t[8]|128;let n=[...t].map(e=>e.toString(16).padStart(2,"0")).join("");return`${n.slice(0,8)}-${n.slice(8,12)}-${n.slice(12,16)}-${n.slice(16,20)}-${n.slice(20)}`}(),ag.set(e,t)),t}function aD(e){let t=aF(ah.get(e)?.documents),n=t.length?a_(e):ag.get(e);for(let[e,n]of ak){for(let e of t)n.delete(e);0===n.size&&ak.delete(e)}let r=`${n??""}|${t.join(",")}`;aS.get(e)!==r&&(0!==t.length||n?aS.set(e,r):aS.delete(e),aV())}async function aO(e){let t=a_(e);aw.set(t,(aw.get(t)??0)+1),await aC.get(t);let n=!1;return{draftId:t,end(e){if(n)return;n=!0;let r=(aw.get(t)??1)-1;if(r>0?aw.set(t,r):aw.delete(t),e){let n=ak.get(t)??new Set;n.add(e),ak.set(t,n)}ax.set(t,av),aV()}}}function aH(e,t){let n=aj.get(e);if(!n)return[];for(let e of t)n.delete(e);return 0===n.size&&aj.delete(e),[...n].sort()}async function aB(){if(!aN)return;let e=[...function(){let e=new Map,t=(t,n)=>{let r=e.get(t)??new Set;for(let e of n)r.add(e);e.set(t,r)};for(let[e,n]of ag)t(n,aF(ah.get(e)?.documents));for(let{draftId:e,ids:n}of ab.values())t(e,n);for(let[e,n]of ak)t(e,n);for(let e of ax.keys())t(e,[]);for(let e of aj.keys())t(e,[]);return new Map([...e].map(([e,t])=>[e,[...t].sort()]))}()].filter(([e,t])=>{if(aw.has(e))return!1;let n=ax.get(e);return aH(e,t).length>0||(0===t.length?void 0!==n:n!==t.join(","))}),t=aw.size>0,n=!1;for(let[r,i]of[...e.filter(([,e])=>e.length>0),...e.filter(([,e])=>0===e.length)]){if(0===i.length&&t)continue;let e=aH(r,i),a=aN(r,i,e).then(()=>{0===i.length?ax.delete(r):ax.set(r,i.join(","));let t=aj.get(r);if(t){for(let n of e)t.delete(n);0===t.size&&aj.delete(r)}},()=>{n=!0,i.length>0&&(t=!0)});aC.set(r,a),await a,aC.get(r)===a&&aC.delete(r)}n?function(){if(aK)return;aK=!0;let e=setTimeout(()=>{aK=!1,aV()},aq);"object"==typeof e&&"unref"in e&&e.unref(),aq=Math.min(2*aq,6e4)}():aq=aU}let aU=5e3,aq=5e3,aK=!1;function aV(){if(aN){if(aI){aT=!0;return}aI=Promise.resolve().then(aB).finally(()=>{aI=null,aT&&(aT=!1,aV())})}}let aJ=Math.floor(Number.MAX_SAFE_INTEGER/1048576),aG=Object.freeze({uploadLimitMb:100,autoCleanupEnabled:!0,orphanGraceDays:7});function aY(e){return"number"==typeof e&&Number.isSafeInteger(e)&&e>=1&&e<=aJ}async function aZ(e){let t,n=await e.json().catch(()=>null);if(!e.ok||!n||!aY(n.uploadLimitMb)||"boolean"!=typeof n.autoCleanupEnabled)throw Error("string"==typeof n?.error?n.error:`HTTP ${e.status}`);return{uploadLimitMb:aY((t=n&&"object"==typeof n?n:{}).uploadLimitMb)?t.uploadLimitMb:aG.uploadLimitMb,autoCleanupEnabled:"boolean"==typeof t.autoCleanupEnabled?t.autoCleanupEnabled:aG.autoCleanupEnabled,orphanGraceDays:7}}async function aX(e={}){return aZ(await fetch("/api/attachment-settings",{cache:"no-store",signal:e.signal}))}async function aQ(e){return aZ(await fetch("/api/attachment-settings",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}))}function a0(e){let t=/(?:^|\s)@"([^"\n]*)$/.exec(e);if(t)return{start:e.length-(t[1].length+2),query:t[1],quoted:!0};let n=/(?:^|\s)@([^\s"]*)$/.exec(e);return n?{start:e.length-(n[1].length+1),query:n[1],quoted:!1}:null}function a1(e){let t=0;for(let n=0;n<e.length;n++)"/"===e[n]&&t++;return t}function a2(e,t){if(!e)return!0;let n=0;for(let r=0;r<t.length&&n<e.length;r++)t[r]===e[n]&&n++;return n===e.length}let a4="omp-web:model-picks";function a5(){try{let e=JSON.parse(window.localStorage.getItem(a4)??"{}");if(!e||"object"!=typeof e||Array.isArray(e))return{};let t={};for(let[n,r]of Object.entries(e))"number"==typeof r&&Number.isFinite(r)&&r>0&&(t[n]=Math.floor(r));return t}catch{return{}}}function a6(e,t,n,r,i={}){let a=i.gap??8,s=i.margin??8,l=i.prefer??"above",o=Math.min(i.minHeight??120,Math.max(0,n-2*s)),d=Math.max(0,e-a-s),c=Math.max(0,n-t-a-s),u="above"===l?d:c,p="above"===l?c:d,h=u>=r||u>=p;return{side:h?l:"above"===l?"below":"above",maxHeight:Math.max(o,Math.min(r,h?u:p))}}function a8(e,t,n){return Math.min(e*t,n)}function a3(e,t,n){let{viewportFraction:r,cap:a,gap:s,margin:l,minHeight:o,prefer:d}=n,[c,u]=(0,i.useState)({side:d??"above",maxHeight:a}),p=(0,i.useCallback)(()=>{let t=e.current;if(!t)return;let n=window.visualViewport?.height??window.innerHeight,i=t.getBoundingClientRect(),c=a6(i.top,i.bottom,n,a8(n,r,a),{gap:s,margin:l,minHeight:o,prefer:d});u(e=>e.side===c.side&&e.maxHeight===c.maxHeight?e:c)},[e,a,s,l,o,d,r]);return(0,i.useEffect)(()=>{if(!t)return;p();let n=e.current,r=n?new ResizeObserver(p):null;return n&&r&&r.observe(n),window.addEventListener("resize",p),window.addEventListener("scroll",p,!0),window.visualViewport?.addEventListener("resize",p),window.visualViewport?.addEventListener("scroll",p),()=>{r?.disconnect(),window.removeEventListener("resize",p),window.removeEventListener("scroll",p,!0),window.visualViewport?.removeEventListener("resize",p),window.visualViewport?.removeEventListener("scroll",p)}},[e,p,t]),c}var a7=n(14755);async function a9(e,t,n,r,i,a,s){let l=e.slice(1).split(/\s/,1)[0];try{let o=t?.length?t:await s?.()??[],d=[...sh,...o].find(e=>e.name===l||"aliases"in e&&e.aliases?.includes(l));if(a&&(!d||"builtin"===d.source))return i(`/${l} cannot run with attachments. Remove them and retry.`),!1;let c=await n?.(e);if(c?.handled){if(c.error)return!1;return c.prompt&&r(c.prompt),!0}if(d&&"builtin"!==d.source)return r(e),!0;return i(`/${l} is not available in this web session.`),!1}catch(e){return i(e instanceof Error?e.message:String(e)),!1}}function se(e){let t=e.transcription?.state;return"planning"===t||"confirm"===t||"running"===t}let st=["off","default","full"],sn={off:"none",default:"default",full:"full"},sr=a7.IN.join(" \xb7 "),si=a7.C1.filter(e=>!a7.IN.includes(e)).join(" \xb7 ");function sa(e){return"above"===e?{bottom:"calc(100% + 8px)"}:{top:"calc(100% + 8px)"}}let ss=new Intl.Collator(void 0,{numeric:!0,sensitivity:"base"}),sl=0,so={"text/markdown":"Markdown","text/plain":"Text","application/pdf":"PDF"};function sd(e,t){return ss.compare(e.name||e.modelId,t.name||t.modelId)||ss.compare(e.provider,t.provider)||ss.compare(e.modelId,t.modelId)}let sc=["auto","off","minimal","low","medium","high","xhigh","max"],su=["low","medium","high","xhigh"],sp={auto:"chat.thinkingAuto",off:"chat.thinkingOff",minimal:"chat.thinkingMinimal",low:"chat.thinkingLow",medium:"chat.thinkingMedium",high:"chat.thinkingHigh",xhigh:"chat.thinkingXhigh",max:"chat.thinkingMax"},sh=[{name:"compact",descriptionKey:"chat.commandCompact",source:"builtin"},{name:"reload",descriptionKey:"chat.commandReload",source:"builtin"},{name:"name",descriptionKey:"chat.commandName",source:"builtin"},{name:"session",descriptionKey:"chat.commandSession",source:"builtin"},{name:"copy",descriptionKey:"chat.commandCopy",source:"builtin"}],sm=["builtin","extension","custom","mcp_prompt","prompt","file","skill"],sf={builtin:"chat.builtIn",extension:"chat.extensions",custom:"chat.customCommands",mcp_prompt:"chat.mcpPrompts",prompt:"chat.prompts",file:"chat.fileCommands",skill:"chat.skills"},sg={builtin:0,extension:1,custom:2,mcp_prompt:3,prompt:4,file:5,skill:6};function sx(e,t,n){let r=e.name.toLowerCase(),i=sv(e,n).toLowerCase();return r===t?0:r.startsWith(t)?1:r.includes(t)?2:i.includes(t)?3:4}function sv(e,t){return"descriptionKey"in e?t(e.descriptionKey):e.description??""}function sb(e,t){return"skill"===e.source&&!!e.name.startsWith("skill:")&&!0===t[e.name.slice(6)]}function sy(e){return{data:e.data,mimeType:e.mimeType}}function sw(e){return{...e,previewUrl:`data:${e.mimeType};base64,${e.data}`}}function sk(e){return(e??[]).filter(ap).slice(0,10).map(sw)}let sj=/^File saved at: (.+)\n\(([^,\n]+), (\d+) bytes\)/,sS="\n\nTranscript of the audio ";function sC(e){return rm(e).map(e=>{let t=rw(e),n="audio"===t&&e.attachmentId&&!e.text.includes(sS)?sj.exec(e.text):null;return{...e,id:++sl,status:"ready",..."audio"===t||"file"===t?{stored:t}:{},...n?{storedInfo:{path:n[1],mimeType:n[2],size:Number(n[3])}}:{}}})}function sN({name:e,mimeType:t,size:n,text:r,attachmentId:i}){return i?{name:e,mimeType:t,size:n,text:r,attachmentId:i}:{name:e,mimeType:t,size:n,text:r}}function sI(e,t){let n=new Map(t.flatMap(e=>e.attachmentId?[[e.attachmentId,e]]:[]));return[...e.map(e=>{let t=e.attachmentId?n.get(e.attachmentId):void 0;return t?(n.delete(e.attachmentId),{...e,id:t.id,sourceSize:t.sourceSize,storedInfo:t.storedInfo??e.storedInfo,transcription:t.transcription}):e}),...t.filter(e=>"ready"!==e.status)]}class sT extends Error{constructor(e,t,n,r){super(e),this.code=t,this.completedParts=n,this.parts=r}}let sM="composer:unkeyed";async function s$(e){let t=await e.json().catch(()=>null),n=t&&"object"==typeof t?{...t}:{};if(e.ok)return n;throw new sT("string"==typeof n.error?n.error:`HTTP ${e.status}`,"string"==typeof n.code?n.code:null,"number"==typeof n.completedParts?n.completedParts:null,"number"==typeof n.parts?n.parts:null)}function sR(e){e.previewUrl.startsWith("blob:")&&URL.revokeObjectURL(e.previewUrl)}function sE({tone:e,title:t,body:n}){let i="error"===e?"danger":"warning";return(0,r.jsxs)("div",{role:"alert",style:{display:"flex",alignItems:"flex-start",gap:8,maxHeight:120,marginBottom:8,padding:"7px 10px",overflowY:"auto",border:`1px solid var(--${i}-line)`,borderRadius:"var(--radius-control)",background:`var(--${i}-soft)`,color:`var(--${i})`,fontSize:11,lineHeight:1.45},children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0,marginTop:1},"aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M10.3 2.9 1.8 17a2 2 0 0 0 1.7 3h17a2 2 0 0 0 1.7-3L13.7 2.9a2 2 0 0 0-3.4 0Z"}),(0,r.jsx)("line",{x1:"12",y1:"9",x2:"12",y2:"13"}),(0,r.jsx)("line",{x1:"12",y1:"17",x2:"12.01",y2:"17"})]}),(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("div",{style:{fontWeight:600},children:t}),(0,r.jsx)("div",{style:{whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:n})]})]})}function sL({error:e}){return e?(0,r.jsx)(sE,{tone:"error",title:"Model error",body:e}):null}function sA({warnings:e}){return e&&0!==e.length?(0,r.jsx)(sE,{tone:"warning",title:e.length>1?"Model scope warnings":"Model scope warning",body:e.join("\n")}):null}let sz=(0,i.forwardRef)(function({onSend:e,onAbort:t,onSteer:n,onFollowUp:a,isStreaming:l,model:o,isAutoModelSelection:d,modelNames:c,modelList:u,modelError:p,modelScopeWarnings:h,onModelChange:m,onMainPresetChange:f,mainPresetActiveAlias:g,modelRoles:x,onRoleModelChange:v,modelSwitching:b,onCompact:y,onAbortCompaction:w,isCompacting:k,compactError:j,compactResult:S,toolPreset:C,onToolPresetChange:N,thinkingLevel:I,effectiveThinkingLevel:T,thinkingCeiling:M,onThinkingLevelChange:$,availableThinkingLevels:E,thinkingLevelMap:L,fastMode:A=null,fastModeBusy:z=!1,onFastModeToggle:P,retryInfo:F,deliveryRows:_=[],inputHistory:D=[],onRecallQueue:O,onRemoveQueuedMessage:H,slashCommands:B,slashCommandsLoading:U,onLoadSlashCommands:q,onBuiltinCommand:K,soundEnabled:V,onSoundToggle:J,onAudioUnlock:G,onPromptWithStreamingBehavior:Y,draftKey:Z,cwd:X,sessionId:Q,onEnsureSession:ee,onLiveTranscriptPersisted:et},en){let er,ei,ea,es,el,eo,ed,ec,eu,ep,{t:eh}=(0,R.s)(),{st:em}=ng(),ef=_.some(e=>e.removable),eg=W(),[ex,ev]=(0,i.useState)(()=>Z?aL(Z)?.value??"":""),[eb,ey]=(0,i.useState)(!1),[ew,ek]=(0,i.useState)(null),[ej,eS]=(0,i.useState)(""),[eC,eN]=(0,i.useState)({});(0,i.useEffect)(()=>{eb&&eN(a5())},[eb]);let[eI,eT]=(0,i.useState)(!1),[eM,e$]=(0,i.useState)(null),[eR,eE]=(0,i.useState)(!1),[eL,eA]=(0,i.useState)(!1),[ez,eP]=(0,i.useState)(null),[eW,eF]=(0,i.useState)(!1),[e_,eD]=(0,i.useState)(()=>Z?sk(aL(Z)?.images):[]),[eO,eH]=(0,i.useState)(()=>Z?sC(aL(Z)?.documents):[]),[eB,eU]=(0,i.useState)(null),eq=(0,i.useMemo)(()=>eO.filter(e=>"ready"===e.status),[eO]),eK=eO.some(e=>"ready"!==e.status||se(e)),eV=eO.filter(e=>"audio"===e.stored&&e.attachmentId&&e.storedInfo&&(void 0!==e.transcription||!e.text.includes(sS))),eJ=ex.trimStart(),eG=0===e_.length&&0===eO.length&&eJ.startsWith("!"),eY=eG&&eJ.startsWith("!!"),[eZ,eX]=(0,i.useState)(!1),[eQ,e0]=(0,i.useState)(0),[e1,e2]=(0,i.useState)(null),[e4,e5]=(0,i.useState)(!1),[e6,e8]=(0,i.useState)(0),[e3,e7]=(0,i.useState)(!1),[e9,te]=(0,i.useState)(0),[tt,tn]=(0,i.useState)(null),[tr,ti]=(0,i.useState)(!1),[ta,ts]=(0,i.useState)(null),[tl,to]=(0,i.useState)(null),td=X&&tl?.cwd===X?tl.values:{},tc=(0,i.useRef)(null),tu=(0,i.useRef)(null),tp=(0,i.useRef)(null),th=(0,i.useRef)(null),tm=(0,i.useRef)(null),tf=(0,i.useRef)(null),tg=(0,i.useRef)(null),tx=(0,i.useRef)(null),tv=(0,i.useRef)(null),tb=(0,i.useRef)(null),ty=(0,i.useRef)(null),tw=(0,i.useRef)(!1),tk=(0,i.useRef)(0),tj=(0,i.useRef)(!1),tS=(0,i.useRef)([]),tC=(0,i.useRef)([]),tN=(0,i.useRef)([]),tI=(0,i.useRef)(null),tT=(0,i.useRef)(null),tM=(0,i.useRef)(Z),t$=(0,i.useRef)(ex),tR=(0,i.useRef)(e_),tE=(0,i.useRef)(0),tL=(0,i.useRef)(eO);t$.current=ex,tR.current=e_,tL.current=eO,(0,i.useImperativeHandle)(en,()=>({insertIfEmpty(e){let t=tc.current;(t?t.value:ex).trim()||(t$.current=e,ev(e),e2(null),requestAnimationFrame(()=>{t&&(t.focus(),t.style.height="auto",t.style.height=`${Math.min(t.scrollHeight,200)}px`)}))},replaceMessage(e){let t,n,r=tc.current;if(!function(e,t,n,r=0){return!e.trim()&&0===t&&0===n&&0===r}(r?r.value:ex,tR.current.length,tE.current,tL.current.length))return;let i=(t="string"==typeof e.content?e.content:e.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n"),rx(t)?.message??t),a=sk("string"==typeof e.content?[]:e.content.flatMap(e=>{if("image"!==e.type)return[];let t=e.source?.type==="base64"?e.source.data:e.data,n=e.source?.type==="base64"?e.source.media_type:e.mimeType;if("string"!=typeof t||"string"!=typeof n)return[];let r={data:t,mimeType:n};return ap(r)?[r]:[]})),s=sC((n="string"==typeof e.content?e.content:e.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n"),rx(n)?.documents??[]));t$.current=i,tR.current=a,tL.current=s,ev(i),e2(null),e7(!1),eD(e=>(e.forEach(sR),a)),eH(s),requestAnimationFrame(()=>{r&&(r.focus(),r.style.height="auto",r.style.height=`${Math.min(r.scrollHeight,200)}px`)})},rekeyDraft(e,t){if(e===t)return;if(tM.current!==e)return void aW(e,t);let n={value:t$.current,images:tR.current.map(sy),documents:tL.current.filter(e=>"ready"===e.status).map(sN)},r=aW(e,t,n)??{value:"",images:[],documents:[]},i=r.value===n.value&&r.images.length===n.images.length&&r.images.every((e,t)=>e.data===n.images[t]?.data&&e.mimeType===n.images[t]?.mimeType)&&r.documents.length===n.documents.length&&r.documents.every((e,t)=>e.name===n.documents[t]?.name&&e.mimeType===n.documents[t]?.mimeType&&e.size===n.documents[t]?.size&&e.text===n.documents[t]?.text&&e.attachmentId===n.documents[t]?.attachmentId);if(tM.current=t,i)return;let a=sk(r.images),s=sI(sC(r.documents),tL.current),l=r.value;t$.current=l,tR.current=a,tL.current=s,ev(l),eD(e=>(e.forEach(sR),a)),eH(s),e2(null),e7(!1)},restoreSubmission(e,t,n,r){if(!e.trim()&&!t?.length&&!n?.length)return;let i=tM.current,a=r??i,s=a===i,l=!s&&a?aL(a):null,o=aP(e,t,s?t$.current:l?.value??"",s?tR.current.map(sy):l?.images??[],n,s?tL.current.filter(e=>"ready"===e.status).map(sN):l?.documents??[]);if(a&&aA(a,o),!s)return;let d=t?.length?[...sk(t).slice(0,Math.max(0,10-tR.current.length)),...tR.current].slice(0,10):tR.current,c=sI(sC(o.documents),tL.current);t$.current=o.value,tR.current=d,tL.current=c,ev(o.value),e2(null),e7(!1),t?.length&&eD(e=>{let n=Math.max(0,10-e.length),r=sk(t).slice(0,n),i=r.length>0?[...r,...e]:e;return tR.current=i,i}),eH(c),requestAnimationFrame(()=>{let e=tc.current;e&&(e.focus(),e.setSelectionRange(e.value.length,e.value.length),e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)})},insertText(e){let t=tc.current;if(!t)return void ev(t=>t+(t?" ":"")+e);let n=t.selectionStart??t.value.length,r=t.selectionEnd??t.value.length,i=t.value.slice(0,n),a=t.value.slice(r),s=i.length>0&&!i.endsWith(" ")?" ":"",l=i+s+e+a;t$.current=l,ev(l),e2(null),requestAnimationFrame(()=>{if(!t)return;let r=n+s.length+e.length;t.setSelectionRange(r,r),t.focus(),t.style.height="auto",t.style.height=`${Math.min(t.scrollHeight,200)}px`})},addAttachments(e){tG(e)}}));let tA=(0,i.useCallback)(async e=>{let t=Math.max(0,10-tR.current.length-tE.current),n=e.filter(e=>e.size>0xa00000);n.length>0&&eU(eh("chat.attachImageTooLarge",{name:n.map(e=>e.name).join(", "),limit:rv(0xa00000)}));let r=e.filter(e=>e.size<=0xa00000),i=r.slice(0,t);if(i.length<r.length&&eU(eh("chat.attachImageLimit",{count:10})),i.length){tE.current+=i.length;try{let e=await Promise.all(i.map(e=>new Promise((t,n)=>{let r=new FileReader;r.onload=()=>{let n=r.result.split(",")[1];t({data:n,mimeType:e.type,previewUrl:URL.createObjectURL(e)})},r.onerror=n,r.readAsDataURL(e)})));eD(t=>{let n=e.slice(0,Math.max(0,10-t.length));e.slice(n.length).forEach(sR);let r=[...t,...n];return tR.current=r,r})}finally{tE.current-=i.length}}},[eh]),tz=(0,i.useCallback)(async e=>{for(let t of e){let e=rc(t);if(!e)continue;if(tL.current.length>=3){eU(eh("chat.attachLimit",{count:3}));continue}if(t.size>8388608){eU(eh("chat.attachTooLarge",{name:t.name,limit:rv(8388608)}));continue}if(tL.current.reduce((e,t)=>e+t.size,0)+t.size>0x1000000){eU(eh("chat.attachTotalTooLarge",{limit:rv(0x1000000)}));continue}let n={id:++sl,name:t.name,mimeType:rl[e],size:t.size,text:"",status:"extracting"},r=[...tL.current,n];tL.current=r,eH(r);try{let e=await rf(t);if(tL.current.reduce((e,t)=>e+(t.id===n.id?0:t.text.length),0)+e.text.length>24e4)throw new rs("text_too_large","Total extracted text exceeds 240000 characters");let r=tL.current.map(t=>t.id===n.id?{...e,id:t.id,status:"ready"}:t);tL.current=r,eH(r)}catch(i){let e=tL.current.some(e=>e.id===n.id),r=tL.current.filter(e=>e.id!==n.id);if(tL.current=r,eH(r),!e)continue;i instanceof rs?"text_too_large"===i.code?eU(eh("chat.attachTextTooLarge",{name:t.name,limit:12e4.toLocaleString()})):"too_many_pages"===i.code?eU(eh("chat.attachTooManyPages",{name:t.name,limit:250})):"no_extractable_text"===i.code?eU(eh("chat.attachNoPdfText",{name:t.name})):"password_protected"===i.code?eU(eh("chat.attachPasswordProtected",{name:t.name})):eU(eh("chat.attachExtractFailed",{name:t.name})):eU(eh("chat.attachExtractFailed",{name:t.name}))}}},[eh]),tP=(0,i.useCallback)((e,t)=>{if(!tL.current.some(t=>t.id===e))return!1;let n=t?tL.current.map(n=>n.id===e?t:n):tL.current.filter(t=>t.id!==e);return tL.current=n,eH(n),!0},[]),tW=(0,i.useCallback)((e,t)=>{if(!tL.current.some(t=>t.attachmentId===e))return!1;let n=tL.current.map(n=>n.attachmentId===e?t(n):n);return tL.current=n,eH(n),!0},[]),tF=(0,i.useCallback)((e,t,n)=>{if(!e||e===tM.current)return;let r=aL(e);r?.documents.some(e=>e.attachmentId===t)&&aA(e,{...r,documents:sC(r.documents).map(e=>e.attachmentId===t?n(e):e).map(sN)})},[]),t_=(0,i.useRef)(new Map),tD=(0,i.useRef)(new Map),tO=(0,i.useRef)(new Set),tH=(0,i.useCallback)((e,t,n)=>{if(!e.storedInfo)return null;let r=Math.min(12e4,24e4-n.reduce((t,n)=>t+(n.attachmentId===e.attachmentId?0:n.text.length),0)),i=rk({...e.storedInfo,transcript:t},r);return i.length>r?null:{...e,text:i,size:new TextEncoder().encode(i).byteLength,transcription:void 0}},[]),tB=(0,i.useCallback)(e=>e instanceof sT&&"media_tool_unavailable"===e.code?eh("chat.transcribeToolMissing"):e instanceof sT&&"transcription_failed"===e.code&&null!==e.completedParts&&null!==e.parts?eh("chat.transcribePartialFailed",{done:e.completedParts,total:e.parts}):e instanceof Error?e.message:String(e),[eh]),tU=(0,i.useCallback)(async(e,t)=>{let n=tM.current,r=tL.current.find(t=>t.attachmentId===e);if(!r?.storedInfo)return;let i=r.transcription?.state==="confirm"?r.transcription.plan:null;tD.current.get(e)?.abort();let a=new AbortController;tD.current.set(e,a),tW(e,e=>({...e,transcription:{state:"running",plan:i}}));try{let r=await s$(await fetch(`/api/attachments/${encodeURIComponent(e)}/transcription`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t?{confirmed:!0}:{}),signal:a.signal}));if("string"!=typeof r.transcript)throw new sT("Invalid transcription result",null,null,null);let i=r.transcript;tW(e,e=>tH(e,i,tL.current)??{...e,transcription:{state:"failed",error:eh("chat.transcribeTooLong")}})||tF(n,e,e=>tH(e,i,[])??e)}catch(n){if(a.signal.aborted)return void tW(e,e=>({...e,transcription:{state:"skipped"}}));if(n instanceof sT&&"confirmation_required"===n.code)return void tq.current?.(e);let t=tB(n);tW(e,e=>({...e,transcription:{state:"failed",error:t}}))}finally{tD.current.get(e)===a&&tD.current.delete(e)}},[eh,tB,tW,tF,tH]),tq=(0,i.useRef)(null),tK=(0,i.useCallback)(async e=>{let t;tD.current.get(e)?.abort();let n=new AbortController;tD.current.set(e,n),tW(e,e=>({...e,transcription:{state:"planning"}}));try{t=function(e){if("boolean"!=typeof e.requiresConfirmation||"number"!=typeof e.estimatedCalls||"string"!=typeof e.notice||null!==e.durationSeconds&&"number"!=typeof e.durationSeconds||"direct"!==e.processing&&"compress-and-split"!==e.processing)throw new sT("Invalid transcription plan",null,null,null);return{durationSeconds:e.durationSeconds,estimatedCalls:e.estimatedCalls,requiresConfirmation:e.requiresConfirmation,processing:e.processing,notice:e.notice}}(await s$(await fetch(`/api/attachments/${encodeURIComponent(e)}/transcription`,{cache:"no-store",signal:n.signal})))}catch(t){if(n.signal.aborted)tW(e,e=>({...e,transcription:{state:"skipped"}}));else{let n=tB(t);tW(e,e=>({...e,transcription:{state:"failed",error:n}}))}return}finally{tD.current.get(e)===n&&tD.current.delete(e)}t.requiresConfirmation?tW(e,e=>({...e,transcription:{state:"confirm",plan:t}})):await tU(e,!1)},[tU,tB,tW]);tq.current=tK;let tV=(0,i.useCallback)(e=>{let t=tD.current.get(e);t?t.abort():tW(e,e=>({...e,transcription:{state:"skipped"}}))},[tW]),tJ=(0,i.useCallback)(async(e,t)=>{let n=null;for(let r of e){if(tL.current.length>=3){eU(eh("chat.attachLimit",{count:3}));continue}let e="file"===t&&r.size<=8388608,i={id:++sl,name:r.name,mimeType:"text/plain",size:e?r.size:0,text:"",status:e?"extracting":"uploading",sourceSize:r.size},a=[...tL.current,i];tL.current=a,eH(a);let s=(e,t)=>{let n=tL.current.filter(e=>e.id!==i.id);return e<=12e4&&n.reduce((e,t)=>e+t.text.length,0)+e<=24e4&&n.reduce((e,t)=>e+t.size,0)+t<=0x1000000};if(e){let e=await r.arrayBuffer().then(e=>{var t;return 255===(t=new Uint8Array(e))[0]&&254===t[1]?rh("utf-16le",t.subarray(2)):254===t[0]&&255===t[1]?rh("utf-16be",t.subarray(2)):t.includes(0)?null:rh("utf-8",t)??rh("euc-kr",t)},()=>null);if(null!==e&&s(e.length,r.size)){tP(i.id,{...i,text:e,status:"ready"});continue}}if(null===n&&(n=1048576*(await aX().catch(()=>aG)).uploadLimitMb),r.size>n){tP(i.id,null)&&eU(eh("chat.attachStoredTooLarge",{name:r.name,limit:rv(n)}));continue}let l={...i,stored:t,status:"uploading",size:0};if(!tP(i.id,l))continue;let o=tM.current??sM,d=await aO(o),c=null,u=new AbortController;t_.current.set(i.id,u);try{if(tO.current.has(i.id))continue;let e=await rj(r,{sessionId:Q,draftId:d.draftId,signal:u.signal}),n=tL.current.filter(e=>e.id!==i.id).reduce((e,t)=>e+t.text.length,0),a=rk({path:e.path,size:e.size,mimeType:e.mimeType},Math.min(12e4,24e4-n)),p=new TextEncoder().encode(a).byteLength;if(!s(a.length,p)){tP(i.id,null)&&eU(eh("chat.attachTotalTooLarge",{limit:rv(0x1000000)}));continue}let h={...l,attachmentId:e.id,text:a,size:p,status:"ready",storedInfo:{path:e.path,size:e.size,mimeType:e.mimeType},..."audio"===t?{transcription:{state:"planning"}}:{}};if(tP(i.id,h))c=e.id;else if(!tO.current.has(i.id)&&o!==tM.current){let t=aL(o)??{value:"",images:[],documents:[]};aA(o,{...t,documents:[...t.documents,sN(h)]}),c=e.id}}catch(e){if(u.signal.aborted)continue;tP(i.id,null)&&eU(eh("chat.attachUploadFailed",{name:r.name,error:e instanceof Error?e.message:String(e)}))}finally{t_.current.delete(i.id),d.end(c)}c&&"audio"===t&&tL.current.some(e=>e.attachmentId===c)&&tK(c)}},[tP,tK,Q,eh]),tG=(0,i.useCallback)(async e=>{eU(null);let{images:t,documents:n,audio:r,files:i}=function(e){let t=[],n=[],r=[],i=[];for(let a of e)a.type.startsWith("image/")?t.push(a):null!==rc(a)?n.push(a):rp(a)?r.push(a):i.push(a);return{images:t,documents:n,audio:r,files:i}}(e),a=n.filter(e=>e.size>8388608);await Promise.all([tA(t),tz(n.filter(e=>e.size<=8388608)),tJ(r,"audio"),tJ([...i,...a],"file")])},[tz,tJ,tA]),tY=(0,i.useCallback)(e=>{eD(t=>{let n=[...t],[r]=n.splice(e,1);return r&&sR(r),tR.current=n,n})},[]),tZ=(0,i.useCallback)(e=>{let t=tL.current.find(t=>t.id===e);if(tO.current.add(e),t_.current.get(e)?.abort(),t?.attachmentId){tD.current.get(t.attachmentId)?.abort();var n=t.attachmentId;for(let[e,t]of ak)t.delete(n)&&(0===t.size&&ak.delete(e),aV())}let r=tL.current.filter(t=>t.id!==e);tL.current=r,eH(r)},[]),tX=(0,i.useCallback)(()=>{tR.current=[],eD(e=>(e.forEach(sR),[]))},[]),tQ=(0,i.useCallback)(()=>{tL.current=[],eH([])},[]),t0=(0,i.useCallback)(()=>{t$.current="",ev(""),e2(null),e7(!1),Z&&az(Z),tM.current&&tM.current!==Z&&az(tM.current),tX(),tQ(),eU(null),tc.current&&(tc.current.style.height="auto")},[tQ,tX,Z]);(0,i.useEffect)(()=>{Z&&tM.current===Z&&aA(Z,{value:ex,images:e_.map(sy),documents:eq.map(sN)})},[e_,Z,eq,ex]),(0,i.useEffect)(()=>{let e=tM.current;if(e===Z)return;e&&aA(e,{value:t$.current,images:tR.current.map(sy),documents:tL.current.filter(e=>"ready"===e.status).map(sN)});let t=Z?aL(Z):null;tM.current=Z;let n=t?.value??"",r=sk(t?.images),i=sC(t?.documents);t$.current=n,tR.current=r,tL.current=i,ev(n),e2(null),e7(!1),eD(e=>(e.forEach(sR),r)),eH(i)},[Z]),(0,i.useEffect)(()=>{let e=tc.current;e&&(e.style.height="auto",ex&&(e.style.height=`${Math.min(e.scrollHeight,200)}px`))},[ex]),(0,i.useEffect)(()=>()=>{tR.current.forEach(sR)},[]);let t2=(0,i.useCallback)((e,t)=>{let n=function(e,t){let n=aF(t);if(0===n.length)return()=>{};let r=++ay;return ab.set(r,{draftId:a_(e),ids:n}),e=>{if("accepted"!==e&&"returned"!==e)return;let t=ab.get(r);if(t){if(ab.delete(r),"accepted"===e){let e=aj.get(t.draftId)??new Set;for(let n of t.ids)e.add(n);aj.set(t.draftId,e)}aV()}}}(tM.current??sM,e);Promise.resolve(t()).then(e=>n("accepted"===e||"returned"===e?e:void 0),()=>void 0)},[]),t4=(0,i.useCallback)(async()=>{let t=ex.trim(),n=eJ.trim(),r=n.startsWith("/")||n.startsWith("!")?n:t;if(!r&&!e_.length&&!eq.length||l||eK)return;G?.();let i=e_.length?e_:void 0,a=eq.length?eq:void 0;if(r.startsWith("/")){await a9(r,B,K,t=>t2(a,()=>e(t,i,a)),eU,!!(i||a),q)&&t0();return}t0(),t2(a,()=>e(r,i,a))},[ex,eJ,e_,eq,eK,l,K,B,q,e,t0,G,t2]),t5=eJ.startsWith("/")&&!/\s/.test(eJ.slice(1))?eJ.slice(1).toLowerCase():null,t6=(()=>{if(null===t5)return[];let e=[...l?[]:sh,...B??[]],t=new Set;return[...e].filter(e=>{let t=e.name.toLowerCase(),n=sv(e,eh).toLowerCase();return t.includes(t5)||n.includes(t5)}).sort((e,t)=>{let n=sx(e,t5,eh)-sx(t,t5,eh);return 0!==n?n:sg[e.source]-sg[t.source]||ss.compare(e.name,t.name)}).filter(e=>{let n=e.name.toLowerCase();return!t.has(n)&&(t.add(n),!0)})})(),{commands:t8,groups:t3}=(er=0,{commands:(ei=sm.map(e=>{let t=t6.filter(t=>t.source===e),n="skill"===e?[...t.filter(e=>!sb(e,td)),...t.filter(e=>sb(e,td))]:t;return{source:e,items:n.map(e=>({command:e,index:er++}))}}).filter(e=>e.items.length>0)).flatMap(e=>e.items.map(({command:e})=>e)),groups:ei}),t7=1===t6.length?eh(t5?"chat.match":"chat.command"):eh(t5?"chat.matches":"chat.commands",{count:t6.length}),t9=!!ex.trim(),ne=!eK&&(t9||e_.length>0||eq.length>0),nn=(0,i.useCallback)((e,t)=>{if(!X)return void e2(null);let n=t??e.length;e2(a0(e.slice(0,n)))},[X]),nr=e1?.query??null,ni=i.useMemo(()=>null!==nr&&tt&&tt.cwd===X?function(e,t,n=20){let r=t.toLowerCase();if(!r)return e.slice(0,n);let i=[];for(let t of e){let e=function(e,t){let n=e.path.toLowerCase(),r=0;if(t.includes("/"))n===t?r=100:n.startsWith(t)?r=80:n.includes(t)?r=50:a2(t,n)&&(r=10);else{let e=n.lastIndexOf("/"),i=-1===e?n:n.slice(e+1);i===t?r=100:i.startsWith(t)?r=80:i.includes(t)?r=50:n.includes(t)?r=30:a2(t,n)&&(r=10)}return e.isDir&&r>0&&(r+=10),r}(t,r);e>0&&i.push({entry:t,score:e})}return i.sort((e,t)=>t.score-e.score||a1(e.entry.path)-a1(t.entry.path)||e.entry.path.localeCompare(t.entry.path)),i.slice(0,n).map(e=>e.entry)}(tt.entries,nr):[],[nr,tt,X]),na=!!(nr&&tt?.truncated&&tt.cwd===X);(0,i.useEffect)(()=>{if(!na||!X||!nr)return;let e=setTimeout(()=>{fetch(`/api/file-index?cwd=${encodeURIComponent(X)}&q=${encodeURIComponent(nr)}`).then(e=>{if(!e.ok)throw Error(`file search failed: ${e.status}`);return e.json()}).then(e=>ts({cwd:X,query:nr,matches:e.matches??[]})).catch(()=>{})},150);return()=>clearTimeout(e)},[na,nr,X]);let ns=na&&null!==ta&&ta.cwd===X&&ta.query===nr,nl=ns?ta.matches:ni,no=null===e1?null:`${e1.start}:${+!!e1.quoted}:${e1.query}`;(0,i.useEffect)(()=>{if(null===no){e5(!1),e8(0);return}e5(!0),e8(0)},[no]);let nd=null!==e1,nc=a3(tb,e3,{viewportFraction:.44,cap:360}),nu=a3(tb,eZ,{viewportFraction:.56,cap:460}),np=a3(tb,e4,{viewportFraction:.48,cap:400});(0,i.useEffect)(()=>{if(!nd||!X)return;let e=tI.current;e&&e.cwd===X&&Date.now()-e.fetchedAt<1e4||tT.current===X||(tT.current=X,ti(!0),fetch(`/api/file-index?cwd=${encodeURIComponent(X)}`).then(e=>{if(!e.ok)throw Error(`file index failed: ${e.status}`);return e.json()}).then(e=>{tn({cwd:X,entries:function(e){let t=new Set;for(let n of e){let e=n.indexOf("/");for(;-1!==e;)t.add(n.slice(0,e)),e=n.indexOf("/",e+1)}let n=[];for(let e of t)n.push({path:e,isDir:!0});for(let t of e)t&&n.push({path:t,isDir:!1});return n.sort((e,t)=>a1(e.path)-a1(t.path)||e.path.localeCompare(t.path)),n}(e.files??[]),truncated:!!e.truncated}),tI.current={cwd:X,fetchedAt:Date.now()}}).catch(()=>{tI.current=null}).finally(()=>{tT.current=null,ti(!1)}))},[nd,X]);let nh=(0,i.useCallback)(e=>{if(!e1)return;let t=tc.current,n=t?.selectionStart??ex.length,r=ex.slice(0,e1.start),i=ex.slice(n);e1.quoted&&i.startsWith('"')&&(i=i.slice(1));let a=function(e,t,n=!1){let r=t?`${e}/`:e,i=n||r.includes(" ");if(t){let e=i?`@"${r}"`:`@${r}`;return{text:e,cursorOffset:i?e.length-1:e.length}}let a=i?`@"${r}" `:`@${r} `;return{text:a,cursorOffset:a.length}}(e.path,e.isDir,e1.quoted),s=r+a.text+i,l=r.length+a.cursorOffset;ev(s),e2(a0(s.slice(0,l))),requestAnimationFrame(()=>{let e=tc.current;e&&(e.focus(),e.setSelectionRange(l,l),e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)})},[e1,ex]);(0,i.useEffect)(()=>{e6>=nl.length&&e8(Math.max(0,nl.length-1))},[nl.length,e6]),(0,i.useEffect)(()=>{tC.current.length=nl.length},[nl.length]),(0,i.useEffect)(()=>{e4&&tC.current[e6]?.scrollIntoView({block:"nearest",inline:"nearest"})},[e6,e4]),(0,i.useEffect)(()=>{e9>=D.length&&te(Math.max(0,D.length-1))},[D.length,e9]),(0,i.useEffect)(()=>{tN.current.length=D.length},[D.length]),(0,i.useEffect)(()=>{e3&&tN.current[e9]?.scrollIntoView({block:"nearest",inline:"nearest"})},[e9,e3]);let nm=(0,i.useCallback)(e=>{t$.current=e,ev(e),e7(!1),te(0),e2(null),requestAnimationFrame(()=>{let t=tc.current;t&&(t.focus(),t.setSelectionRange(e.length,e.length),t.style.height="auto",t.style.height=`${Math.min(t.scrollHeight,200)}px`)})},[]),nf=(0,i.useCallback)(e=>{let t=`/${e.name} `;t$.current=t,ev(t),eX(!1),e0(0),requestAnimationFrame(()=>{let e=tc.current;e&&(e.focus(),e.setSelectionRange(t.length,t.length),e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)})},[]),nx=(0,i.useCallback)(async e=>{let t=ex.trim(),r=eJ.trim(),i=r.startsWith("/")||r.startsWith("!")?r:t,s=eK||!i&&0===e_.length&&0===eq.length?null:{message:i,images:e_.length?e_:void 0,documents:eq.length?eq:void 0};if(!s)return;G?.();let l="steer"===e?"steer":"followUp";if(i.startsWith("/")){await a9(i,B,K,e=>{if(!Y)throw Error("Cannot queue this command while the session is busy.");t2(s.documents,()=>Y(e,l,s.images,s.documents))},eU,!!(s.images?.length||s.documents?.length),q)&&t0();return}t0(),"steer"===e&&n?t2(s.documents,()=>n(s.message,s.images,s.documents)):"followup"===e&&a&&t2(s.documents,()=>a(s.message,s.images,s.documents))},[ex,eJ,e_,eq,eK,B,q,K,Y,n,a,t0,G,t2]),nv=(0,i.useCallback)(e=>{let t=t8.length-1;if(t<0)return 0;if("left"===e)return Math.max(0,eQ-1);if("right"===e)return Math.min(t,eQ+1);let n=tS.current[eQ];if(!n)return"down"===e?Math.min(t,eQ+1):Math.max(0,eQ-1);let r=n.getBoundingClientRect(),i=r.left+r.width/2,a=r.top+r.height/2,s=-1,l=1/0;for(let n=0;n<=t;n+=1){if(n===eQ)continue;let t=tS.current[n];if(!t)continue;let r=t.getBoundingClientRect(),o=r.top+r.height/2-a;if("down"===e?o<=4:o>=-4)continue;let d=1e3*Math.abs(o)+Math.abs(r.left+r.width/2-i);d<l&&(s=n,l=d)}return s>=0?s:"down"===e?Math.min(t,eQ+1):Math.max(0,eQ-1)},[t8.length,eQ]),nb=(0,i.useCallback)(e=>{let r=e.nativeEvent,i=Date.now()-tk.current<100,s=tw.current||r.isComposing||229===r.keyCode;if("Enter"===e.key&&!e.shiftKey&&(s||i)){i&&e.preventDefault();return}if(e3&&!s){if("ArrowDown"===e.key){e.preventDefault(),te(e=>Math.min(Math.max(0,D.length-1),e+1));return}if("ArrowUp"===e.key){e.preventDefault(),te(e=>Math.max(0,e-1));return}if("Escape"===e.key){e.preventDefault(),e7(!1);return}if(("Tab"===e.key||"Enter"===e.key&&!e.shiftKey)&&D[e9]){e.preventDefault(),nm(D[e9]);return}}if(eZ&&null!==t5){if("ArrowDown"===e.key){e.preventDefault(),e0(nv("down"));return}if("ArrowUp"===e.key){e.preventDefault(),e0(nv("up"));return}if("ArrowRight"===e.key){e.preventDefault(),e0(nv("right"));return}if("ArrowLeft"===e.key){e.preventDefault(),e0(nv("left"));return}if("Escape"===e.key){e.preventDefault(),eX(!1);return}if(("Tab"===e.key||"Enter"===e.key&&!e.shiftKey)&&t8[eQ]){e.preventDefault(),nf(t8[eQ]);return}}if(e4&&null!==e1&&!s){if("ArrowDown"===e.key){e.preventDefault(),e8(e=>Math.min(Math.max(0,nl.length-1),e+1));return}if("ArrowUp"===e.key){e.preventDefault(),e8(e=>Math.max(0,e-1));return}if("Escape"===e.key){e.preventDefault(),e5(!1);return}if(("Tab"===e.key||"Enter"===e.key&&!e.shiftKey)&&nl[e6]){e.preventDefault(),nh(nl[e6]);return}}if("ArrowUp"===e.key&&!s&&!l&&D.length>0&&0===ex.trim().length){e.preventDefault(),eX(!1),e5(!1),te(D.length-1),e7(!0);return}if("Escape"===e.key&&!s&&l&&t){e.preventDefault(),t();return}"Enter"!==e.key||e.shiftKey||(e.preventDefault(),l&&(n||a)?nx(n?"steer":"followup"):t4())},[l,n,a,t,eZ,t5,t8,eQ,nf,nx,t4,nv,e4,e1,nl,e6,nh,e3,D,e9,nm,ex]),ny=(0,i.useCallback)(()=>{let e=tc.current;e&&(e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)},[]),nw=(0,i.useCallback)(e=>{let t=function(e){let t=Array.from(e.files??[]);if(t.length>0)return t;let n=[];for(let t of Array.from(e.items??[])){if("file"!==t.kind)continue;let e=t.getAsFile();e&&n.push(e)}return n}(e.clipboardData);t.length&&(e.preventDefault(),tG(t))},[tG]);(0,i.useEffect)(()=>{if(null===t5){eX(!1),e0(0),tj.current=!1;return}eX(!0),e0(0),!tj.current&&q&&(tj.current=!0,Promise.resolve(q()).catch(()=>{tj.current=!1}))},[t5,q]),(0,i.useEffect)(()=>{if(!eZ||!X)return;let e=!1;return to({cwd:X,values:{}}),fetch(`/api/skills?cwd=${encodeURIComponent(X)}`).then(e=>{if(!e.ok)throw Error(`skills fetch failed: ${e.status}`);return e.json()}).then(t=>{if(e)return;let n={};for(let e of t.skills??[])n[e.name]=e.disableModelInvocation;to({cwd:X,values:n})}).catch(()=>{e||to({cwd:X,values:{}})}),()=>{e=!0}},[eZ,X]),(0,i.useEffect)(()=>{eQ>=t8.length&&e0(Math.max(0,t8.length-1))},[t8.length,eQ]),(0,i.useEffect)(()=>{tS.current.length=t8.length},[t8.length]),(0,i.useEffect)(()=>{eZ&&tS.current[eQ]?.scrollIntoView({block:"nearest",inline:"nearest"})},[eQ,eZ]);let nk=u&&u.length>0?u.map(e=>({provider:e.provider,modelId:e.id,name:e.name})).sort(sd):Object.entries(c??{}).map(([e,t])=>({provider:o?.provider??"unknown",modelId:e,name:t})).sort(sd),nj=g??null,nC=nt.bo.find(e=>e.alias===nj)?.provider??null,nN=nC?nk.filter(e=>e.provider===nC):nk,nT=(ea=ej.trim().toLocaleLowerCase())?nN.filter(e=>`${e.name} ${e.modelId}`.toLocaleLowerCase().includes(ea)):nN,nM=nN.length>8,n$=[];for(let e of nT){let t=n$.find(t=>t.provider===e.provider);t?t.options.push(e):n$.push({provider:e.provider,options:[e]})}let nR=nC?[]:(x??[]).filter(e=>!e.hidden&&e.resolved),nE=o?nR.find(e=>e.resolved?.provider===o.provider&&e.resolved?.modelId===o.modelId):void 0,nL=ej.trim()?[]:nN.map((e,t)=>{var n,r;return{option:e,order:t,count:eC[n=e.provider,r=e.modelId,`${n}/${r}`]??0}}).filter(e=>e.count>=2).sort((e,t)=>t.count-e.count||e.order-t.order).slice(0,5).map(({option:e,count:t})=>({option:e,count:t})),nA=(e,t,n)=>{let i=e.modelId===o?.modelId&&e.provider===o?.provider;return(0,r.jsxs)("button",{onClick:()=>{if(ey(!1),eS(""),!i||d){var t,n;let r=function(e,t){let n={...e,[t]:(e[t]??0)+1},r=Object.keys(n);if(r.length<=30)return n;for(let e of(r.sort((e,t)=>n[e]-n[t]),r)){if(Object.keys(n).length<=30)break;e!==t&&delete n[e]}return n}(a5(),(t=e.provider,n=e.modelId,`${t}/${n}`));try{window.localStorage.setItem(a4,JSON.stringify(r))}catch{}eN(r),m?.(e.provider,e.modelId)}},style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",background:i?"var(--bg-selected)":"none",border:"none",color:i?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left",fontWeight:i?600:400,whiteSpace:"nowrap"},onMouseEnter:e=>{i||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{i||(e.currentTarget.style.background="none")},children:[i?(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,r.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,r.jsx)("span",{style:{width:10,flexShrink:0}}),e.name,void 0!==n&&n>=2&&(0,r.jsx)("span",{style:{marginLeft:"auto",paddingLeft:12,color:"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:10.5},children:eh("chat.modelPickCount",{count:n})})]},`${t}:${e.provider}:${e.modelId}`)},nz=o?nk.find(e=>e.modelId===o.modelId&&e.provider===o.provider)?.name??o.modelId:null,nP=S?Math.max(0,S.tokensBefore-S.estimatedTokensAfter):0,nW=S?`${S.reason&&"manual"!==S.reason?`${S.reason[0].toUpperCase()}${S.reason.slice(1)} `:eh("chat.compacted")} ${t1(S.tokensBefore)} -> ${t1(S.estimatedTokensAfter)} tokens (${eh("chat.tokensSaved",{saved:t1(nP)})})`:null,nF=e=>{let t=L?.[e];return null!=t&&t!==e?t:null},n_="auto"===(es=I??"auto")?M?`auto ≤ ${nF(M)??M}`:"auto":L?L[es]??es:es,nD=(I??"auto")==="auto"&&T&&"auto"!==T?L?.[T]??T:null,nO=$&&nD?eh("chat.currentReasoning",{level:nD}):null,nH=e=>!E||E.includes(e),nB=[{level:"auto",ceiling:null},...su.filter(nH).map(e=>({level:"auto",ceiling:e})),...sc.filter(e=>"auto"!==e&&nH(e)).map(e=>({level:e,ceiling:null}))],nU=Object.entries(sn).find(([,e])=>e===(C??"default"))?.[0]??"default";(0,i.useEffect)(()=>{let e=e=>{tu.current&&!tu.current.contains(e.target)&&tp.current&&!tp.current.contains(e.target)&&(ey(!1),eS("")),th.current&&!th.current.contains(e.target)&&tm.current&&!tm.current.contains(e.target)&&eT(!1),tf.current&&!tf.current.contains(e.target)&&eE(!1),tg.current&&!tg.current.contains(e.target)&&eA(!1),tx.current&&!tx.current.contains(e.target)&&eF(!1),!tv.current||tv.current.contains(e.target)||tc.current?.contains(e.target)||e7(!1)};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[]),(0,i.useEffect)(()=>{eg||eF(!1)},[eg]);let nq=(0,r.jsx)("button",{type:"button",className:`composer-icon-button${e_.length||eO.length?" is-active":""}`,onClick:()=>ty.current?.click(),title:eh("chat.attachFile"),"aria-label":eh("chat.attachFile"),style:{flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center",width:32,height:32,padding:0,background:"none",border:"none",borderRadius:"var(--radius-control)",color:e_.length||eO.length?"var(--accent)":"var(--text-muted)",cursor:"pointer",opacity:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color=e_.length||eO.length?"var(--accent)":"var(--text)"},onMouseLeave:e=>{e.currentTarget.style.background="none",e.currentTarget.style.color=e_.length||eO.length?"var(--accent)":"var(--text-muted)"},children:(0,r.jsxs)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2",ry:"2"}),(0,r.jsx)("circle",{cx:"8.5",cy:"8.5",r:"1.5"}),(0,r.jsx)("polyline",{points:"21 15 16 10 5 21"})]})}),nK=f&&nt.bo.length>0?(0,r.jsxs)("div",{ref:th,style:{position:"relative",flexShrink:+!!eg,minWidth:0},children:[(0,r.jsxs)("button",{className:`${eg?"composer-icon-button":"composer-chip"}${eI?" is-active":""}`,onClick:e=>{let t=e.currentTarget.getBoundingClientRect();e$({top:t.top,bottom:t.bottom,left:t.left,width:t.width}),ey(!1),eS(""),eT(e=>!e)},disabled:l||b,"aria-haspopup":"menu","aria-expanded":eI,onKeyDown:e=>{"Escape"===e.key&&eI&&(e.stopPropagation(),eT(!1))},style:{display:"flex",alignItems:"center",gap:6,maxWidth:"100%",padding:"4px 8px",background:eI?"var(--bg-hover)":"none",border:"none",borderRadius:"var(--radius-control)",color:"var(--text-muted)",cursor:l||b?"not-allowed":"pointer",fontSize:12,opacity:l?.5:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{l||b||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{e.currentTarget.style.background=eI?"var(--bg-hover)":"none",e.currentTarget.style.color="var(--text-muted)"},title:eh("chat.mainPreset"),"aria-label":eh("chat.mainPreset"),children:[(0,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},"aria-hidden":"true",children:(0,r.jsx)("path",{d:"M12 3l2.2 5.1 5.6.5-4.2 3.7 1.2 5.5L12 15l-4.8 2.8 1.2-5.5L4.2 8.6l5.6-.5z"})}),eg?null:(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:eh("chat.mainPreset")})]}),eI&&eM&&(()=>{let e=window.visualViewport?.height??window.innerHeight,{side:t,maxHeight:n}=a6(eM.top,eM.bottom,e,a8(e,.6,460),{gap:6,prefer:"above"}),i="above"===t?{bottom:e-eM.top+6}:{top:eM.bottom+6},a=eg?{left:8,right:8,maxWidth:"calc(100vw - 16px)"}:{left:eM.left,width:"max-content",minWidth:eM.width};return(0,r.jsx)("div",{ref:tm,role:"menu","aria-label":eh("chat.mainPreset"),onKeyDown:e=>{"Escape"===e.key&&(eT(!1),th.current?.querySelector("button")?.focus())},style:{position:"fixed",...i,...a,zIndex:500,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s2)",overflow:"hidden",maxHeight:n,display:"flex",flexDirection:"column"},children:(0,r.jsx)("div",{style:{minHeight:0,overflowY:"auto"},children:nt.bo.map(e=>{let t=e.alias===nj;return(0,r.jsxs)("button",{role:"menuitemradio","aria-checked":t,onClick:()=>{eT(!1),f((0,nt.zq)(e))},title:`${e.provider}/${e.model}`,style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",background:t?"var(--bg-selected)":"none",border:"none",color:t?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left",fontWeight:t?600:400,whiteSpace:"nowrap"},onMouseEnter:e=>{t||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{t||(e.currentTarget.style.background="none")},children:[t?(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,r.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,r.jsx)("span",{style:{width:10,flexShrink:0}}),(0,r.jsx)("img",{className:"account-avatar",src:(0,nt.uk)(e.seed),width:20,height:20,alt:"","aria-hidden":"true",draggable:!1}),(0,r.jsx)("span",{children:e.alias}),(0,r.jsxs)("span",{style:{marginLeft:"auto",paddingLeft:12,color:"var(--text-dim)",fontSize:11,overflow:"hidden",textOverflow:"ellipsis"},children:[e.provider,"/",e.model,void 0!==e.oauthPosition?` \xb7 OAuth ${e.oauthPosition}`:""]})]},e.alias)})})})})()]}):null,nV=$?(0,r.jsxs)("div",{ref:tg,style:{position:"relative",flexShrink:0,minWidth:0},children:[(0,r.jsxs)("button",{type:"button",className:`${eg?"composer-icon-button":"composer-chip"}${eL?" is-active":""}`,onClick:e=>{let t=e.currentTarget.getBoundingClientRect();eP({top:t.top,bottom:t.bottom,left:t.left,width:t.width}),ey(!1),eS(""),eT(!1),eA(e=>!e)},disabled:l||b,"aria-haspopup":"menu","aria-expanded":eL,onKeyDown:e=>{"Escape"===e.key&&eL&&(e.stopPropagation(),eA(!1))},title:eh("chat.changeReasoning",{level:n_}),"aria-label":eh("chat.changeReasoning",{level:n_}),style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,padding:eg?0:"8px 12px",height:32,background:eL?"var(--bg-hover)":"none",border:"none",borderRadius:"var(--radius-control)",color:"var(--text-muted)",cursor:l||b?"not-allowed":"pointer",fontSize:12,opacity:l?.5:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{l||b||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{e.currentTarget.style.background=eL?"var(--bg-hover)":"none",e.currentTarget.style.color="var(--text-muted)"},children:[(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},"aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M9.5 2A5.5 5.5 0 0 0 4 7.5c0 1.7.78 3.21 2 4.21V14a1 1 0 0 0 1 1h5a1 1 0 0 0 1-1v-2.29c1.22-1 2-2.51 2-4.21A5.5 5.5 0 0 0 9.5 2z"}),(0,r.jsx)("line",{x1:"7",y1:"18",x2:"12",y2:"18"}),(0,r.jsx)("line",{x1:"8",y1:"21",x2:"11",y2:"21"})]}),eg?null:(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:n_})]}),eL&&ez&&(()=>{let e=window.visualViewport?.height??window.innerHeight,{side:t,maxHeight:n}=a6(ez.top,ez.bottom,e,a8(e,.6,460),{gap:6,prefer:"above"}),i="above"===t?{bottom:e-ez.top+6}:{top:ez.bottom+6},a=eg?{left:8,right:8,maxWidth:"calc(100vw - 16px)"}:{left:ez.left,width:"max-content",minWidth:Math.max(180,ez.width)};return(0,r.jsx)("div",{role:"menu","aria-label":eh("chat.changeReasoningLabel"),onKeyDown:e=>{"Escape"===e.key&&(eA(!1),tg.current?.querySelector("button")?.focus())},style:{position:"fixed",...i,...a,zIndex:500,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s2)",overflowY:"auto",maxHeight:n},children:nB.map(({level:e,ceiling:t})=>{let n=(I??"auto")===e&&("auto"!==e||(M??null)===t),i=t??e,a="auto"===e&&null===t?null:nF(i),s=t?`auto ≤ ${a??t}`:a??e,l=t?eh("chat.thinkingAutoCapped",{level:a??t}):eh(sp[e]);return(0,r.jsxs)("button",{type:"button",role:"menuitemradio","aria-checked":n,onClick:()=>{eA(!1),$(e,t)},style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",background:n?"var(--bg-selected)":"none",border:"none",color:n?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left",fontWeight:n?600:400,whiteSpace:"nowrap"},onMouseEnter:e=>{n||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{n||(e.currentTarget.style.background="none")},children:[n?(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,r.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,r.jsx)("span",{style:{width:10,flexShrink:0}}),(0,r.jsxs)("span",{style:{flex:1},children:[s,null!==a&&(0,r.jsxs)("span",{style:{fontSize:10,color:"var(--text-dim)",fontFamily:"var(--font-mono)",marginLeft:5},children:["(",i,")"]})]}),(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)",marginLeft:8},children:l})]},t?`auto-${t}`:e)})})})()]}):null,nJ=P?(el=z?eh("chat.fastModeBusy"):null===A?eh("chat.fastModeUnknown"):A.active?eh("chat.fastModeActive"):A.enabled?eh("chat.fastModeInactive"):eh("chat.fastModeOff"),eo=z||l||b,ed=A?.enabled===!0,(0,r.jsx)("button",{type:"button",className:`composer-icon-button${A?.active?" is-active":""}`,onClick:P,disabled:eo,"aria-pressed":null===A?void 0:A.enabled,"aria-busy":z||void 0,title:el,"aria-label":el,style:{flexShrink:0,opacity:l?.5:1},children:(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:A?.active?"var(--accent)":"none",stroke:ed?"var(--accent)":"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",strokeDasharray:null===A?"3 2":void 0,style:{opacity:ed&&!A?.active?.6:1},"aria-hidden":"true",children:(0,r.jsx)("path",{d:"M13 2 4 14h7l-1 8 9-12h-7l1-8z"})})})):null,nG=(0,r.jsxs)(r.Fragment,{children:[n&&(0,r.jsxs)("button",{className:"composer-stream-action is-warning",onClick:()=>nx("steer"),disabled:!ne,title:eK?eh("chat.attachExtractingWait"):eh("chat.steerTitle"),style:{display:"flex",alignItems:"center",gap:5,padding:"7px 12px",background:ne?"var(--warning-soft)":"none",border:"1px solid var(--warning-line)",borderRadius:"var(--radius-control)",color:ne?"var(--warning)":"var(--text-dim)",cursor:ne?"pointer":"not-allowed",fontSize:13,fontWeight:600,letterSpacing:"-0.01em",transition:"background 0.12s"},children:[(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("path",{d:"M5 1 L9 5 L5 9"}),(0,r.jsx)("line",{x1:"1",y1:"5",x2:"9",y2:"5"})]}),eh("chat.steer")]}),a&&(0,r.jsxs)("button",{className:"composer-stream-action is-followup",onClick:()=>nx("followup"),disabled:!ne,title:eK?eh("chat.attachExtractingWait"):eh("chat.followUpTitle"),style:{display:"flex",alignItems:"center",gap:5,padding:"7px 12px",background:ne?"var(--accent-soft)":"none",border:"1px solid var(--accent-line)",borderRadius:"var(--radius-control)",color:ne?"var(--accent-hover)":"var(--text-dim)",cursor:ne?"pointer":"not-allowed",fontSize:13,fontWeight:600,letterSpacing:"-0.01em",transition:"background 0.12s"},children:[(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("line",{x1:"5",y1:"1",x2:"5",y2:"6"}),(0,r.jsx)("polyline",{points:"2.5 3.5 5 1 7.5 3.5"}),(0,r.jsx)("line",{x1:"2",y1:"9",x2:"8",y2:"9"})]}),eh("chat.followUp")]})]}),nY=void 0!==J?(0,r.jsx)(at,{soundEnabled:V??!0,onToggle:J}):null;return(0,r.jsxs)("div",{className:"chat-composer",style:{flexShrink:0,background:"transparent",padding:"0 16px 8px"},children:[(0,r.jsx)("input",{ref:ty,type:"file",multiple:!0,style:{display:"none"},onChange:e=>{tG(Array.from(e.target.files??[])),e.target.value=""}}),(0,r.jsxs)("div",{className:"chat-column-cap",style:{maxWidth:820,margin:"0 auto"},children:[(0,r.jsx)(sL,{error:p}),(0,r.jsx)(sA,{warnings:h}),_.length>0&&(0,r.jsxs)("div",{style:{marginBottom:8,border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"var(--bg-panel)",padding:"5px 0"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,padding:"2px 8px 4px 10px"},children:[(0,r.jsx)("span",{style:{fontSize:10,fontFamily:"var(--font-mono)",color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:.4},children:em("delivery.title",{count:_.length})}),O&&ef&&(0,r.jsxs)("button",{onClick:O,title:eh("chat.recallTitle"),style:{display:"flex",alignItems:"center",gap:6,padding:"4px 12px",fontSize:12,color:"var(--text)",background:"transparent",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",cursor:"pointer",transition:"background 0.12s, border-color 0.12s",whiteSpace:"nowrap"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.borderColor="color-mix(in srgb, var(--accent) 45%, var(--border))"},onMouseLeave:e=>{e.currentTarget.style.background="transparent",e.currentTarget.style.borderColor="var(--border)"},children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("polyline",{points:"9 14 4 9 9 4"}),(0,r.jsx)("path",{d:"M20 20v-7a4 4 0 0 0-4-4H4"})]}),eh("chat.recall")]})]}),(0,r.jsx)(i7,{rows:_,removeLabel:eh("chat.queueRemove"),onRemove:H?(e,t)=>H("steer"===e?"steering":"followUp",t):void 0})]}),F&&(0,r.jsxs)("div",{style:{marginBottom:8,padding:"5px 10px",background:"var(--warning-soft)",border:"1px solid var(--warning-line)",borderRadius:"var(--radius-control)",fontSize:12,color:"var(--warning)",display:"flex",alignItems:"center",gap:6},children:[(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:[(0,r.jsx)("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}),(0,r.jsx)("path",{d:"M3 3v5h5"})]}),eh("chat.retrying",{attempt:F.attempt,max:F.maxAttempts}),F.errorMessage&&(0,r.jsxs)("span",{style:{opacity:.7,marginLeft:4},children:["— ",F.errorMessage]})]}),nW&&(0,r.jsxs)("div",{style:{marginBottom:8,padding:"5px 10px",background:"var(--success-soft)",border:"1px solid var(--success-line)",borderRadius:"var(--radius-control)",fontSize:12,color:"var(--success)",display:"flex",alignItems:"center",gap:6},children:[(0,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}),nW]}),j&&(0,r.jsx)("div",{role:"alert",style:{marginBottom:8,padding:"7px 10px",background:"var(--danger-soft)",border:"1px solid var(--danger-line)",borderRadius:"var(--radius-control)",color:"var(--danger)",fontFamily:"var(--font-mono)",fontSize:12,lineHeight:1.5,whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:j}),eB&&(0,r.jsxs)("div",{role:"alert",style:{display:"flex",alignItems:"center",gap:8,marginBottom:8,padding:"7px 10px",background:"var(--danger-soft)",border:"1px solid var(--danger-line)",borderRadius:"var(--radius-control)",color:"var(--danger)",fontSize:12,lineHeight:1.5},children:[(0,r.jsx)("span",{style:{flex:1,minWidth:0,overflowWrap:"anywhere"},children:eB}),(0,r.jsx)("button",{type:"button",onClick:()=>eU(null),"aria-label":eh("i18n.close"),title:eh("i18n.close"),style:{flexShrink:0,width:24,height:24,display:"flex",alignItems:"center",justifyContent:"center",padding:0,border:"none",background:"transparent",color:"inherit",cursor:"pointer"},children:(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"2",y1:"2",x2:"10",y2:"10"}),(0,r.jsx)("line",{x1:"10",y1:"2",x2:"2",y2:"10"})]})})]}),(e_.length>0||eO.length>0)&&(0,r.jsxs)("div",{role:"list","aria-label":eh("chat.attachments"),style:{display:"flex",alignItems:"center",gap:6,marginBottom:6,flexWrap:"wrap"},children:[e_.map((e,t)=>(0,r.jsxs)("div",{role:"listitem",style:{position:"relative",flexShrink:0},children:[(0,r.jsx)("img",{src:e.previewUrl,alt:"",style:{width:56,height:56,objectFit:"cover",borderRadius:"var(--radius-control)",border:"1px solid var(--border)",display:"block"}}),(0,r.jsx)("button",{type:"button","aria-label":eh("chat.removeImage",{index:t+1}),onClick:()=>tY(t),style:{position:"absolute",top:-4,right:-4,width:16,height:16,borderRadius:"50%",background:"var(--bg-panel)",border:"1px solid var(--border)",display:"flex",alignItems:"center",justifyContent:"center",cursor:"pointer",padding:0,color:"var(--text-muted)"},children:(0,r.jsxs)("svg",{width:"8",height:"8",viewBox:"0 0 8 8",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"1",y1:"1",x2:"7",y2:"7"}),(0,r.jsx)("line",{x1:"7",y1:"1",x2:"1",y2:"7"})]})})]},`image-${t}`)),eO.map(e=>(0,r.jsxs)("div",{className:"composer-chip",role:"listitem","aria-busy":"ready"!==e.status||se(e)||void 0,style:{display:"flex",alignItems:"center",gap:7,minWidth:0,maxWidth:320,height:32,padding:"0 7px 0 9px"},children:["ready"!==e.status||e.transcription?.state==="planning"||e.transcription?.state==="running"?(0,r.jsx)("span",{"aria-hidden":"true",style:{width:13,height:13,flexShrink:0,border:"1.5px solid var(--border-strong)",borderTopColor:"var(--accent)",borderRadius:"50%",animation:"spin 0.8s linear infinite"}}):nI(e.name,14),(0,r.jsxs)("span",{style:{minWidth:0,display:"flex",flexDirection:"column",lineHeight:1.15},children:[(0,r.jsx)("span",{title:e.name,style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text)",fontSize:12},children:e.name}),(0,r.jsxs)("span",{style:{color:"var(--text-dim)",fontSize:10},children:["audio"===e.stored?eh("chat.attachKindAudio"):"file"===e.stored?eh("chat.attachKindFile"):so[e.mimeType]," \xb7 ",rv(e.sourceSize??e.size),"extracting"===e.status?` \xb7 ${eh("chat.attachExtracting")}`:"","uploading"===e.status?` \xb7 ${eh("chat.attachUploading")}`:"",e.transcription?.state==="planning"?` \xb7 ${eh("chat.transcribeChecking")}`:"",e.transcription?.state==="confirm"?` \xb7 ${eh("chat.attachTranscribePending")}`:"",e.transcription?.state==="running"?` \xb7 ${eh("chat.attachTranscribing")}`:"",e.transcription?.state==="failed"&&(0,r.jsx)("span",{style:{color:"var(--danger)"},children:` \xb7 ${eh("chat.attachTranscribeFailed")}`})]})]}),(0,r.jsx)("button",{type:"button",onClick:()=>tZ(e.id),"aria-label":eh("chat.removeAttachment",{name:e.name}),title:eh("chat.removeAttachment",{name:e.name}),style:{width:24,height:24,flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center",padding:0,border:"none",background:"transparent",color:"var(--text-muted)",cursor:"pointer"},children:(0,r.jsxs)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"1.5",y1:"1.5",x2:"8.5",y2:"8.5"}),(0,r.jsx)("line",{x1:"8.5",y1:"1.5",x2:"1.5",y2:"8.5"})]})})]},e.id))]}),eV.length>0&&(0,r.jsx)("div",{role:"group","aria-label":eh("chat.transcribeGroup"),"aria-live":"polite",style:{display:"flex",flexDirection:"column",gap:6,marginBottom:6},children:eV.map(e=>{let t,n,i,a,l=e.attachmentId,o=e.transcription,d=o?.state==="confirm"||o?.state==="running"?o.plan:null,c=d?eh("chat.transcribePlanSummary",{duration:null===d.durationSeconds?eh("chat.transcribeDurationUnknown"):(n=Math.floor((t=Math.round(d.durationSeconds))/3600),i=Math.floor(t%3600/60),a=String(t%60).padStart(2,"0"),n>0?`${n}:${String(i).padStart(2,"0")}:${a}`:`${i}:${a}`),calls:d.estimatedCalls}):null,u=o?.state==="confirm"?eh("chat.transcribeConfirmTitle",{name:e.name}):o?.state==="running"?eh("chat.transcribeRunning",{name:e.name}):o?.state==="planning"?`${e.name} \xb7 ${eh("chat.transcribeChecking")}`:o?.state==="failed"?eh("chat.transcribeFailedRow",{name:e.name,error:o.error}):eh("chat.transcribeSkipped",{name:e.name});return(0,r.jsxs)("div",{"data-transcription-state":o?.state??"idle",style:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:8,padding:"7px 10px",border:`1px solid ${o?.state==="failed"?"var(--danger-line)":"var(--border)"}`,borderRadius:"var(--radius-control)",background:o?.state==="failed"?"var(--danger-soft)":"var(--bg-panel)",fontSize:12,lineHeight:1.45},children:[(0,r.jsxs)("div",{style:{flex:"1 1 220px",minWidth:0},children:[(0,r.jsx)("div",{style:{color:o?.state==="failed"?"var(--danger)":"var(--text)",overflowWrap:"anywhere"},children:u}),c&&(0,r.jsx)("div",{style:{color:"var(--text-dim)",fontVariantNumeric:"tabular-nums"},children:c}),o?.state==="confirm"&&(0,r.jsxs)(r.Fragment,{children:[o.plan.notice&&(0,r.jsx)("div",{style:{color:"var(--text-dim)",overflowWrap:"anywhere"},children:o.plan.notice}),(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:eh("chat.transcribeUsageNotice")})]})]}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",gap:6},children:[o?.state==="confirm"&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(s.r,{type:"button",variant:"neutralSolid",size:"small",onClick:()=>void tU(l,!0),children:eh("chat.transcribeStart")}),(0,r.jsx)(s.r,{type:"button",variant:"neutralWeak",size:"small",onClick:()=>tV(l),children:eh("chat.transcribeSkip")})]}),(o?.state==="planning"||o?.state==="running")&&(0,r.jsx)(s.r,{type:"button",variant:"neutralWeak",size:"small",onClick:()=>tV(l),children:eh("chat.transcribeCancel")}),(void 0===o||"skipped"===o.state||"failed"===o.state)&&(0,r.jsx)(s.r,{type:"button",variant:"neutralWeak",size:"small",onClick:()=>void tK(l),children:eh(o?.state==="failed"?"chat.transcribeRetry":"chat.transcribeAction")})]})]},e.id)})}),(0,r.jsxs)("div",{ref:tb,style:{position:"relative",minWidth:0},children:[e3&&D.length>0&&(0,r.jsxs)("div",{ref:tv,style:{position:"absolute",left:0,right:0,...sa(nc.side),zIndex:120,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s3)",overflow:"hidden",maxHeight:nc.maxHeight},children:[(0,r.jsx)("div",{title:"Input history",style:{height:30,padding:"0 10px",borderBottom:"1px solid var(--border)",display:"flex",alignItems:"center",color:"var(--text-dim)"},children:(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M3 12a9 9 0 1 0 3-6.7"}),(0,r.jsx)("path",{d:"M3 4v5h5"}),(0,r.jsx)("path",{d:"M12 7v5l3 2"})]})}),(0,r.jsx)("div",{style:{maxHeight:Math.max(0,nc.maxHeight-31),overflowY:"auto",padding:4},children:D.map((e,t)=>{let n=t===e9;return(0,r.jsxs)("button",{ref:e=>{tN.current[t]=e},type:"button",onMouseDown:t=>{t.preventDefault(),nm(e)},onMouseEnter:()=>te(t),style:{width:"100%",display:"flex",alignItems:"flex-start",gap:8,padding:"7px 8px",border:"none",borderRadius:"var(--radius-control)",background:n?"var(--bg-selected)":"none",color:"var(--text)",cursor:"pointer",textAlign:"left",fontSize:12.5,lineHeight:1.45},children:[(0,r.jsx)("span",{style:{flexShrink:0,fontFamily:"var(--font-mono)",fontSize:11,color:"var(--text-dim)",paddingTop:1},children:t+1}),(0,r.jsx)("span",{style:{minWidth:0,display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:2,overflow:"hidden",overflowWrap:"anywhere"},children:e})]},`${t}:${e}`)})})]}),eZ&&null!==t5&&(0,r.jsxs)("div",{style:{position:"absolute",left:0,right:0,...sa(nu.side),zIndex:120,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s3)",overflow:"hidden",maxHeight:nu.maxHeight},children:[(0,r.jsxs)("div",{style:{padding:"8px 10px",borderBottom:"1px solid var(--border)",display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,fontSize:11,color:"var(--text-dim)"},children:[(0,r.jsx)("span",{children:U?eh("chat.loadingCommands"):eh("chat.slashCommands",{label:t7})}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},children:eh("chat.tabEnter")})]}),(0,r.jsx)("div",{style:{maxHeight:Math.max(0,nu.maxHeight-34),overflowY:"auto",padding:10},children:U||0!==t6.length?t3.map(e=>(0,r.jsxs)("section",{style:{marginBottom:12},children:[(0,r.jsxs)("div",{style:{position:"sticky",top:-10,zIndex:1,display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,padding:"4px 0 6px",background:"var(--bg)",color:"var(--text-dim)",fontSize:10,fontWeight:600,textTransform:"uppercase"},children:[(0,r.jsx)("span",{children:eh(sf[e.source])}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontWeight:500},children:e.items.length})]}),(0,r.jsx)("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(220px, 1fr))",gap:8},children:e.items.map(({command:e,index:t})=>{let n=t===eQ,i=sb(e,td);return(0,r.jsxs)("button",{ref:e=>{tS.current[t]=e},type:"button",onMouseDown:t=>{t.preventDefault(),nf(e)},onMouseEnter:()=>e0(t),style:{width:"100%",minWidth:0,minHeight:58,display:"flex",flexDirection:"column",gap:4,justifyContent:"center",padding:"9px 10px",border:`1px solid ${n?"var(--accent)":"var(--border)"}`,borderRadius:"var(--radius-control)",background:n?"var(--bg-selected)":"var(--bg-panel)",color:"var(--text)",cursor:"pointer",textAlign:"left",boxShadow:n?"0 0 0 1px color-mix(in srgb, var(--accent) 28%, transparent)":"none"},children:[(0,r.jsxs)("span",{style:{fontSize:13,fontFamily:"var(--font-mono)",overflowWrap:"anywhere",wordBreak:"break-word",color:i?"var(--text-dim)":void 0},children:["/",e.name,i&&(0,r.jsx)("span",{style:{marginLeft:6,padding:"0 4px",border:"1px solid var(--border)",borderRadius:3,fontSize:9,color:"var(--text-dim)",whiteSpace:"nowrap"},children:eh("chat.dormant")})]}),sv(e,eh)&&(0,r.jsx)("span",{style:{display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:2,overflow:"hidden",fontSize:11,lineHeight:1.35,color:"var(--text-dim)"},children:sv(e,eh)})]},`${e.source}:${e.name}`)})})]},e.source)):(0,r.jsx)("div",{style:{padding:"2px 2px 4px",fontSize:12,color:"var(--text-dim)"},children:eh("chat.noCommands")})})]}),e4&&null!==e1&&(ec=tr&&(!tt||tt.cwd!==X),eu=1===nl.length?eh("chat.match"):eh("chat.matches",{count:nl.length}),ep=tt?.truncated&&!ns?e1.query?eh("chat.searchingAll"):eh("chat.indexTruncated"):"",(0,r.jsxs)("div",{style:{position:"absolute",left:0,right:0,...sa(np.side),zIndex:120,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s3)",overflow:"hidden",maxHeight:np.maxHeight},children:[(0,r.jsxs)("div",{style:{padding:"8px 10px",borderBottom:"1px solid var(--border)",display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,fontSize:11,color:"var(--text-dim)"},children:[(0,r.jsx)("span",{children:ec?eh("chat.loadingFiles"):eh("chat.files",{label:eu,hint:ep})}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},children:eh("chat.tabEnter")})]}),(0,r.jsx)("div",{style:{maxHeight:Math.max(0,np.maxHeight-34),overflowY:"auto",padding:4},children:ec||0!==nl.length?nl.map((e,t)=>{let n=t===e6,i=e.path.split("/").pop()??e.path,a=e.path.slice(0,e.path.length-i.length);return(0,r.jsxs)("button",{ref:e=>{tC.current[t]=e},type:"button",onMouseDown:t=>{t.preventDefault(),nh(e)},onMouseEnter:()=>e8(t),style:{width:"100%",display:"flex",alignItems:"center",gap:8,padding:"6px 8px",border:"none",borderRadius:"var(--radius-control)",background:n?"var(--bg-selected)":"none",color:"var(--text)",cursor:"pointer",textAlign:"left",fontSize:12.5,fontFamily:"var(--font-mono)"},children:[(0,r.jsx)("span",{style:{flexShrink:0,display:"flex",alignItems:"center"},children:e.isDir?(0,r.jsx)(nS,{size:14}):nI(i,14)}),(0,r.jsxs)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[a&&(0,r.jsx)("span",{style:{color:"var(--text-dim)"},children:a}),i,e.isDir&&(0,r.jsx)("span",{style:{color:"var(--text-dim)"},children:"/"})]})]},`${e.isDir?"d":"f"}:${e.path}`)}):(0,r.jsx)("div",{style:{padding:"6px 8px",fontSize:12,color:"var(--text-dim)"},children:na&&!ns?eh("chat.searching"):eh("chat.noMatchingFiles")})})]})),(0,r.jsxs)("div",{className:`chat-composer-field${eG?" is-bash":""}${l?" is-streaming":""}`,style:{minWidth:0,display:"flex",gap:8,alignItems:"center",background:"var(--bg)",border:`1px solid ${eG?"var(--tool-bg)":l&&(n||a)?"var(--warning-line)":"var(--border)"}`,borderRadius:"var(--seed-radius-r3)",padding:"10px 10px 10px 14px",boxShadow:"var(--seed-shadow-s1)",transition:"border-color 0.15s, background 0.15s, box-shadow 0.15s"},children:[(0,r.jsx)("textarea",{className:"chat-composer-textarea",ref:tc,value:ex,onChange:e=>{t$.current=e.target.value,ev(e.target.value),e7(!1),nn(e.target.value,e.target.selectionStart)},onSelect:e=>{let t=e.currentTarget;nn(t.value,t.selectionStart)},onKeyDown:nb,onCompositionStart:()=>{tw.current=!0},onCompositionEnd:e=>{tw.current=!1,tk.current=Date.now();let t=e.currentTarget;nn(t.value,t.selectionStart)},onInput:ny,onPaste:nw,placeholder:l&&(n||a)?eh("chat.steerPlaceholder"):l?eh("chat.agentPlaceholder"):eh("chat.messagePlaceholder"),rows:1,style:{flex:1,minWidth:0,width:"100%",background:"none",border:"none",outline:"none",resize:"none",color:"var(--text)",fontSize:14,lineHeight:1.6,fontFamily:"inherit",minHeight:24,maxHeight:200,overflow:"auto"}}),l?eg?null:(0,r.jsx)("div",{style:{display:"flex",alignItems:"center",gap:6,flexShrink:0,alignSelf:"flex-end"},children:nG}):(0,r.jsxs)("button",{className:"chat-composer-send",onClick:t4,disabled:!ne,"aria-busy":eK||void 0,"aria-label":eg?eh("chat.send"):void 0,title:eK?eh("chat.attachExtractingWait"):void 0,style:{flexShrink:0,alignSelf:"flex-end",display:"flex",alignItems:"center",justifyContent:"center",gap:6,minWidth:eg?44:void 0,padding:eg?0:"7px 14px",background:ne?"var(--accent-soft)":"var(--bg-raised)",border:"none",borderRadius:"var(--radius-control)",color:ne?"var(--accent-hover)":"var(--text-dim)",cursor:ne?"pointer":"not-allowed",fontSize:13,fontWeight:600,letterSpacing:"-0.01em",transition:"background 0.15s, color 0.15s"},children:[(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("line",{x1:"2",y1:"7",x2:"11",y2:"7"}),(0,r.jsx)("polyline",{points:"7.5 3 12 7 7.5 11"})]}),eg?null:eh("chat.send")]})]})]}),eG&&(0,r.jsxs)("div",{className:"text-xs px-2 py-1",style:{color:eY?"var(--text-muted)":"var(--accent)",marginTop:4},children:[eh("chat.shell")," \xb7 ",eY?eh("chat.outputLocal"):eh("chat.outputModel")]}),(0,r.jsxs)("div",{className:"composer-action-bar",style:{marginTop:8,display:"flex",alignItems:"center",gap:6},children:[(0,r.jsxs)("div",{style:{flex:eg?"1 1 0%":"0 0 auto",minWidth:eg?"min-content":0,display:"flex",alignItems:"center",gap:2},children:[(!eg||!l)&&nq,!eg&&nK,!(eg&&l)&&(nk.length>0||nz||p)&&m&&(0,r.jsxs)("div",{ref:tu,style:{position:"relative",flex:eg?"1 1 0%":void 0,width:eg?0:void 0,minWidth:44*!!eg},children:[(0,r.jsxs)("button",{className:`composer-chip${eb?" is-active":""}`,onClick:e=>{let t=e.currentTarget.getBoundingClientRect();ek({top:t.top,bottom:t.bottom,left:t.left,width:t.width}),ey(e=>(e&&eS(""),!e))},disabled:l||b,"aria-busy":b||void 0,style:{display:"flex",alignItems:"center",gap:6,justifyContent:eg?"flex-start":void 0,padding:eg?"8px 10px":"8px 12px",height:32,width:eg?"100%":void 0,maxWidth:eg?"100%":220,overflow:"hidden",background:eb?"var(--bg-hover)":"none",border:"none",borderRadius:"var(--radius-control)",color:"var(--text-muted)",cursor:l||b?"not-allowed":"pointer",fontSize:12,opacity:l?.5:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{l||b||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{e.currentTarget.style.background=eb?"var(--bg-hover)":"none",e.currentTarget.style.color="var(--text-muted)"},title:b?"Switching model":nk.length>0?"Change model":"No available models",children:[b?(0,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.4",strokeLinecap:"round",style:{animation:"spin 0.8s linear infinite",flexShrink:0},"aria-hidden":"true",children:(0,r.jsx)("path",{d:"M21 12a9 9 0 1 1-2.64-6.36"})}):(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"}),(0,r.jsx)("rect",{x:"9",y:"9",width:"6",height:"6"}),(0,r.jsx)("line",{x1:"9",y1:"1",x2:"9",y2:"4"}),(0,r.jsx)("line",{x1:"15",y1:"1",x2:"15",y2:"4"}),(0,r.jsx)("line",{x1:"9",y1:"20",x2:"9",y2:"23"}),(0,r.jsx)("line",{x1:"15",y1:"20",x2:"15",y2:"23"}),(0,r.jsx)("line",{x1:"20",y1:"9",x2:"23",y2:"9"}),(0,r.jsx)("line",{x1:"20",y1:"14",x2:"23",y2:"14"}),(0,r.jsx)("line",{x1:"1",y1:"9",x2:"4",y2:"9"}),(0,r.jsx)("line",{x1:"1",y1:"14",x2:"4",y2:"14"})]}),(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:nz??(nk.length>0?"Select model":"No models")})]}),eb&&ew&&(()=>{let e=window.visualViewport?.height??window.innerHeight,{side:t,maxHeight:n}=a6(ew.top,ew.bottom,e,a8(e,.6,460),{gap:6,prefer:"above"}),i="above"===t?{bottom:e-ew.top+6}:{top:ew.bottom+6},a=eg?{left:8,right:8,maxWidth:"calc(100vw - 16px)"}:{left:ew.left,width:"max-content",minWidth:ew.width};return(0,r.jsxs)("div",{ref:tp,style:{position:"fixed",...i,...a,zIndex:500,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s2)",overflow:"hidden",maxHeight:n,display:"flex",flexDirection:"column"},children:[nM&&(0,r.jsx)("div",{style:{padding:"6px 8px",borderBottom:"1px solid var(--border)",flexShrink:0},children:(0,r.jsx)("input",{value:ej,onChange:e=>eS(e.target.value),onKeyDown:e=>{"Escape"===e.key&&(eS(""),ey(!1))},placeholder:eh("chat.filterModels"),"aria-label":eh("chat.filterModels"),autoFocus:!0,autoComplete:"off",spellCheck:!1,style:{width:"100%",minWidth:220*!eg,fontSize:11,fontFamily:"var(--font-mono)",padding:"5px 8px",border:"1px solid var(--border)",borderRadius:5,outline:"none",background:"var(--bg)",color:"var(--text)",boxSizing:"border-box"}})}),(0,r.jsxs)("div",{style:{minHeight:0,overflowY:"auto"},children:[nL.length>0&&(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{style:{padding:"6px 12px 4px",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:eh("chat.frequentModels")}),nL.map(({option:e,count:t})=>nA(e,"frequent",t))]}),nR.length>0&&!ej.trim()&&v&&(0,r.jsxs)("div",{style:{borderTop:nL.length>0?"1px solid var(--border)":"none"},children:[(0,r.jsx)("div",{style:{padding:"6px 12px 4px",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:eh("chat.modelRoles")}),nR.map(e=>{let t=nE?.role===e.role,n=e.resolved?.name??e.resolved?.modelId??"";return(0,r.jsxs)("button",{onClick:()=>{ey(!1),eS(""),v(e.role)},title:e.selector??n,style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",background:t?"var(--bg-selected)":"none",border:"none",color:t?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left",whiteSpace:"nowrap"},onMouseEnter:e=>{t||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{t||(e.currentTarget.style.background="none")},children:[t?(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,r.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,r.jsx)("span",{style:{width:10,flexShrink:0}}),(0,r.jsx)("span",{style:{flexShrink:0,minWidth:58,padding:"1px 6px",borderRadius:4,border:"1px solid var(--border)",background:"var(--bg-subtle)",color:t?"var(--accent)":"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:9.5,fontWeight:700,letterSpacing:"0.06em",textAlign:"center"},children:e.tag??e.role.toUpperCase()}),(0,r.jsx)("span",{style:{fontWeight:t?600:500},children:e.name}),(0,r.jsxs)("span",{style:{marginLeft:"auto",paddingLeft:12,color:"var(--text-dim)",fontSize:11,overflow:"hidden",textOverflow:"ellipsis"},children:[n,e.resolved?.thinkingLevel?` \xb7 ${e.resolved.thinkingLevel}`:""]})]},e.role)}),(0,r.jsx)("div",{style:{padding:"6px 12px 4px",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em",borderTop:"1px solid var(--border)"},children:eh("chat.allModels")})]}),0===n$.length?(0,r.jsx)("div",{style:{padding:"8px 12px",color:"var(--text-dim)",fontSize:12,whiteSpace:"nowrap"},children:ej.trim()?eh("chat.noMatchingModels"):"No available models"}):n$.map((e,t)=>(0,r.jsxs)("div",{children:[n$.length>1&&(0,r.jsx)("div",{style:{padding:"6px 12px 4px",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em",borderTop:t>0?"1px solid var(--border)":"none"},children:e.provider}),e.options.map(e=>nA(e,"all"))]},e.provider))]})]})})()]}),eg&&l&&(0,r.jsx)("div",{style:{display:"flex",alignItems:"center",gap:6,minWidth:0},children:nG}),!eg&&nV,!eg&&nJ,!eg&&nO&&(0,r.jsx)("span",{style:{flexShrink:0,padding:"0 6px",fontSize:12,color:"var(--text-muted)",whiteSpace:"nowrap"},children:nO}),(0,r.jsx)(au,{sessionId:Q})]}),(0,r.jsxs)("div",{ref:tx,style:{flex:"0 1 auto",minWidth:0,display:"flex",alignItems:"center",justifyContent:"flex-end",position:"relative",marginLeft:"auto",gap:eg?4:2},children:[eg?(0,r.jsx)("button",{type:"button",className:`composer-icon-button${eW?" is-active":""}`,title:eh("chat.moreControls"),"aria-label":eh("chat.moreControls"),"aria-expanded":eW,onClick:()=>{ey(!1),eS(""),eF(e=>!e)},children:(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"4",y1:"7",x2:"20",y2:"7"}),(0,r.jsx)("line",{x1:"4",y1:"17",x2:"20",y2:"17"}),(0,r.jsx)("circle",{cx:"10",cy:"7",r:"2.2"}),(0,r.jsx)("circle",{cx:"16",cy:"17",r:"2.2"})]})}):(0,r.jsx)(s.r,{type:"button",variant:"neutralWeak",size:"small",layout:"withText",title:eW?void 0:eh("chat.moreControls"),"aria-label":eh("chat.moreControls"),"aria-expanded":eW,onClick:()=>{ey(!1),eS(""),eF(e=>!e)},children:eh("chat.moreControls")}),(0,r.jsxs)("div",{role:"group","aria-label":eh("chat.moreControls"),style:{display:eW?"flex":"none",alignItems:"center",gap:1,position:"absolute",right:0,bottom:"100%",marginBottom:"var(--seed-dimension-x1)",zIndex:60,padding:1,width:"max-content",maxWidth:"calc(100vw - 32px)",flexWrap:"wrap",justifyContent:"flex-end",border:"1px solid var(--seed-color-stroke-neutral-muted)",borderRadius:"var(--seed-radius-r2)",background:"var(--seed-color-bg-layer-floating)",boxShadow:"var(--seed-shadow-s2)"},children:[eg&&(0,r.jsxs)(r.Fragment,{children:[l&&nq,nK,nV,nJ]}),!l&&N&&(0,r.jsxs)("div",{ref:tf,style:{position:"relative"},children:[(0,r.jsxs)("button",{className:`composer-chip${eR?" is-active":""}`,onClick:()=>!l&&eE(e=>!e),disabled:l,title:eh("chat.changeToolPreset")+`: ${nU}`,"aria-label":eh("chat.changeToolPreset"),style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,padding:"8px 12px",height:32,background:eR?"var(--bg-hover)":"none",border:"none",borderRadius:"var(--radius-control)",color:"var(--text-muted)",cursor:l?"not-allowed":"pointer",fontSize:12,opacity:l?.5:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{l||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{e.currentTarget.style.background=eR?"var(--bg-hover)":"none",e.currentTarget.style.color="var(--text-muted)"},children:[(0,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:(0,r.jsx)("path",{d:"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"})}),(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:nU})]}),eR&&(0,r.jsx)("div",{style:{position:"absolute",bottom:"calc(100% + 6px)",right:0,zIndex:100,background:"var(--bg)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s2)",overflow:"hidden",minWidth:120},children:st.map(e=>{let t=sn[e],n=(C??"default")===t,i="off"===e?eh("chat.noTools"):"default"===e?eh("chat.builtInTools",{tools:sr}):eh("chat.allBuiltInTools",{tools:`${sr} + ${si}`});return(0,r.jsxs)("button",{onClick:()=>{eE(!1),n||N(t)},style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",background:n?"var(--bg-selected)":"none",border:"none",color:n?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left",fontWeight:n?600:400,whiteSpace:"nowrap"},onMouseEnter:e=>{n||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{n||(e.currentTarget.style.background="none")},children:[n?(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:(0,r.jsx)("polyline",{points:"1.5 5 4 7.5 8.5 2.5"})}):(0,r.jsx)("span",{style:{width:10,flexShrink:0}}),(0,r.jsx)("span",{style:{flex:1},children:e}),(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)",marginLeft:8},children:i})]},e)})})]}),!l&&y&&(0,r.jsx)("div",{children:(0,r.jsx)("button",{className:`composer-chip${k?" is-active is-danger":""}`,onClick:k?w:y,disabled:l&&!k,style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,padding:"8px 12px",height:32,background:k?"var(--danger-soft)":"none",border:"none",borderRadius:"var(--radius-control)",color:k?"var(--danger)":"var(--text-muted)",cursor:l&&!k?"not-allowed":"pointer",fontSize:12,opacity:l&&!k?.5:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{(!l||k)&&(e.currentTarget.style.background=k?"var(--danger-soft)":"var(--bg-hover)",e.currentTarget.style.color=k?"var(--danger)":"var(--text)")},onMouseLeave:e=>{e.currentTarget.style.background=k?"var(--danger-soft)":"none",e.currentTarget.style.color=k?"var(--danger)":"var(--text-muted)"},title:k?eh("chat.stopCompaction"):eh("chat.compactContext"),"aria-label":k?eh("chat.stopCompaction"):eh("chat.compactContext"),children:k?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",children:(0,r.jsx)("rect",{x:"2",y:"2",width:"6",height:"6",rx:"1",fill:"currentColor"})}),(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:eh("chat.compacting")})]}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("polyline",{points:"4 14 10 14 10 20"}),(0,r.jsx)("polyline",{points:"20 10 14 10 14 4"}),(0,r.jsx)("line",{x1:"10",y1:"14",x2:"3",y2:"21"}),(0,r.jsx)("line",{x1:"21",y1:"3",x2:"14",y2:"10"})]}),(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:eh("chat.compact")})]})})}),eg&&nY,eW&&(0,r.jsx)("button",{className:"composer-icon-button is-active",type:"button",title:eh("chat.collapseControls"),"aria-label":eh("chat.collapseControls"),"aria-expanded":!0,onClick:()=>{eE(!1),eA(!1),eF(!1)},style:{display:"flex",alignItems:"center",justifyContent:"center",width:36,height:32,padding:0,marginLeft:0,background:"var(--bg-hover)",border:"none",borderLeft:"1px solid color-mix(in srgb, var(--border) 72%, transparent)",borderRadius:"0 9px 9px 0",color:"var(--text)",cursor:"pointer",transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-selected)"},onMouseLeave:e=>{e.currentTarget.style.background="var(--bg-hover)"},children:(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[(0,r.jsx)("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),(0,r.jsx)("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),l&&(0,r.jsxs)("button",{className:"composer-chip is-danger is-active",onClick:t,title:eh("chat.stopAgent"),"aria-label":eg?eh("chat.stopAgent"):void 0,style:{display:"flex",alignItems:"center",justifyContent:"center",gap:6,minWidth:eg?44:void 0,padding:eg?0:"8px 14px",height:32,background:"var(--danger-soft)",border:"1px solid var(--danger-line)",borderRadius:"var(--radius-control)",color:"var(--danger)",cursor:"pointer",fontSize:12,fontWeight:600,whiteSpace:"nowrap",letterSpacing:"-0.01em",transition:"background 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.background="var(--danger-soft)"},children:[(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",children:(0,r.jsx)("rect",{x:"1.5",y:"1.5",width:"7",height:"7",rx:"1.5",fill:"currentColor"})}),eg?null:eh("chat.stop")]}),(0,r.jsx)(ad,{sessionId:Q,onEnsureSession:ee,onTranscriptPersisted:et}),!eg&&nY]})]})]})]})});function sP({statuses:e}){if(0===e.length)return null;let t=[...e].sort((e,t)=>e.key.localeCompare(t.key)).map(({text:e})=>e.replace(/[\r\n\t]/g," ").replace(/ +/g," ").trim()).join(" "),n=ej(t);return(0,r.jsx)("div",{role:"status","aria-label":n,title:n,style:{display:"flex",alignItems:"center",flexShrink:0,minWidth:0,height:36,padding:"0 12px",borderTop:"1px solid var(--border)",background:"transparent"},children:(0,r.jsx)("span",{style:{minWidth:0,overflow:"hidden",color:"var(--text-muted)",fontFamily:"var(--font-mono)",fontSize:11,textOverflow:"ellipsis",whiteSpace:"nowrap"},children:eT(t).map((e,t)=>(0,r.jsx)("span",{style:e.style,children:e.text},t))})})}function sW({phases:e}){let{t}=(0,R.s)(),[n,a]=(0,i.useState)(!1),[s,l]=(0,i.useState)(!1),{currentPhase:o,activeTask:d,remaining:c,completed:u,total:p,percent:h}=e9(e);if(0===p)return null;let m=0===c;return(0,r.jsxs)("div",{className:`todo-strip${m?" is-done":""}`,children:[(0,r.jsxs)("button",{type:"button",className:"todo-strip-summary","aria-expanded":n,onClick:()=>a(e=>!e),children:[(0,r.jsx)("span",{"aria-hidden":"true",className:"todo-strip-marker",children:m?"✓":"›"}),o&&(0,r.jsx)("span",{className:"todo-strip-phase",children:o.name}),(0,r.jsx)("span",{className:"todo-strip-task",children:m?t("todo.allDone",{count:u}):d?.content??""}),(0,r.jsx)("span",{className:"todo-strip-count",children:m?t("todo.progressDone",{percent:h??0,completed:u,total:p}):t("todo.progress",{percent:h??0,completed:u,total:p,remaining:c})})]}),n&&(0,r.jsxs)("div",{className:"todo-strip-body",children:[e.map((t,n)=>{let i=t.tasks.filter(e=>s||"completed"!==e.status);return 0===i.length?null:(0,r.jsxs)("div",{className:"todo-checklist-phase",role:"list",children:[e.length>1&&(0,r.jsx)("div",{className:"todo-checklist-phase-name",children:t.name}),i.map((e,t)=>(0,r.jsx)(nw,{task:e},`${e.content}-${t}`))]},`${t.name}-${n}`)}),u>0&&(0,r.jsx)("button",{type:"button",className:"todo-strip-completed-toggle","aria-expanded":s,onClick:()=>l(e=>!e),children:t(s?"todo.hideCompleted":"todo.showCompleted",{count:u})})]})]})}function sF(e=document){return"visible"!==e.visibilityState||!e.hasFocus()}function s_(e){switch(e.method){case"select":case"confirm":case"input":case"editor":case"ask":case"plan_review":return!0;case"custom":return!0!==e.closed;default:return!1}}async function sD(e,t={createWindowNotification:(e,t)=>new Notification(e,t),getServiceWorkerRegistration:"serviceWorker"in navigator?()=>navigator.serviceWorker.getRegistration():null}){let n={body:e.body,...e.tag?{tag:e.tag}:{}};if(t.getServiceWorkerRegistration)try{let r=await t.getServiceWorkerRegistration();if(r)return await r.showNotification(e.title,{...n,data:{url:e.sessionUrl}}),"service-worker"}catch{}try{let r=t.createWindowNotification(e.title,n);return r.onclick=()=>{r.close(),e.onClick()},"window"}catch{return null}}var sO=n(62503);class sH extends Error{constructor(e,t,n,r){super(e),this.status=t,this.code=n,this.accepted=r,this.name="AgentCommandError"}}async function sB(e,t){let n=await fetch(`/api/agent/${encodeURIComponent(e)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),r=await n.json().catch(()=>({}));if(!n.ok||r.error)throw new sH(r.error??`HTTP ${n.status}`,n.status,r.code,r.accepted);return r.data}let sU="ompweb-update-client-id",sq="ompweb-update-resume-intent-v2",sK="ompweb-update-return-v1",sV="cuelo-restart-return-v1",sJ="ompweb-update-failure-return-v1",sG="ompweb:update-wake";function sY(e){return null===e?2e4:"running"===e?null:"failed"===e?3e4:8e3}function sZ(){let e=sessionStorage.getItem(sU);if(e&&/^[A-Za-z0-9_-]{16,128}$/.test(e))return e;let t="function"==typeof crypto.randomUUID?crypto.randomUUID().replaceAll("-",""):Array.from(crypto.getRandomValues(new Uint8Array(16)),e=>e.toString(16).padStart(2,"0")).join("");return sessionStorage.setItem(sU,t),t}function sX(){sessionStorage.removeItem(sq)}function sQ(){let e=sessionStorage.getItem(sK);if(!e)return null;try{let t=JSON.parse(e);if(1!==t.schemaVersion||"string"!=typeof t.requestId||!/^[0-9a-f]{32}$/.test(t.requestId)||"string"!=typeof t.stageHash||!/^[0-9a-f]{64}$/.test(t.stageHash)||"boolean"!=typeof t.dismissed)return null;return t}catch{return null}}function s0(e){let t=sQ();if(!t||t.requestId!==e)return t;let n={...t,dismissed:!0};try{sessionStorage.setItem(sK,JSON.stringify(n))}catch{}return n}async function s1(e){let t=await fetch("/api/update-maintenance",{method:"POST",headers:{"Content-Type":"application/json","Cache-Control":"no-cache"},body:JSON.stringify({action:"heartbeat",clientId:sZ(),sessionId:e.sessionId,resumeUrl:e.resumeUrl,preservationError:e.preservationError??null,...e.update?{requestId:e.update.requestId,stageHash:e.update.stageHash}:{}}),cache:"no-store"});if(!t.ok)throw Error(`maintenance heartbeat HTTP ${t.status}`);return await t.json()}async function s2(e){if(e.sessionId){let t=await fetch(`/api/sessions/${encodeURIComponent(e.sessionId)}?deferThinking=1&deferMedia=1`,{cache:"no-store",headers:{"Cache-Control":"no-cache"}});if(!t.ok)throw Error(`session resume HTTP ${t.status}`);if((await t.json()).sessionId!==e.sessionId)throw Error("resumed session identity mismatch")}let t=await fetch("/api/update-maintenance",{method:"POST",headers:{"Content-Type":"application/json","Cache-Control":"no-cache"},body:JSON.stringify({action:"resume-confirm",requestId:e.requestId,stageHash:e.stageHash,clientId:e.clientId,sessionId:e.sessionId}),cache:"no-store"});if(!t.ok)throw Error(`resume confirm HTTP ${t.status}`);let n=await t.json().catch(()=>null);!function(e){let t=sQ();if(t&&t.requestId===e.requestId&&t.stageHash===e.stageHash)return;let n={schemaVersion:1,requestId:e.requestId,stageHash:e.stageHash,dismissed:!1};try{sessionStorage.setItem(sK,JSON.stringify(n))}catch{}}({requestId:e.requestId,stageHash:e.stageHash}),sX();let r=n?.wake;e.sessionId&&(r?.wake===!0||r?.reason==="already-claimed"||r?.reason==="user-already-active")&&window.dispatchEvent(new CustomEvent(sG,{detail:{sessionId:e.sessionId}}))}async function s4(e){let t=function(e){let t=sessionStorage.getItem(sJ);if(!t)return null;sessionStorage.removeItem(sJ);try{let n=JSON.parse(t);if(1!==n.schemaVersion||n.requestId!==e.requestId||n.stageHash!==e.stageHash||n.clientId!==e.clientId)return null;return{wake:!0===n.wake}}catch{return null}}(e);return t?(sX(),t.wake&&e.sessionId&&window.dispatchEvent(new CustomEvent(sG,{detail:{sessionId:e.sessionId}})),"failed"):(await s2(e),"resumed")}function s5(e,t){let n=new Map(e.map(e=>[e.id,e]));for(let e of t)n.set(e.id,function(e,t){return e&&(void 0!==e.parentToolCallId&&void 0!==t.parentToolCallId?e.parentToolCallId===t.parentToolCallId:void 0===e.sessionFile||void 0===t.sessionFile||e.sessionFile===t.sessionFile)?{...t,index:e.index,agent:e.agent,agentSource:e.agentSource,description:e.description??t.description,task:e.task??t.task,assignment:e.assignment??t.assignment,sessionFile:t.sessionFile??e.sessionFile,parentToolCallId:t.parentToolCallId??e.parentToolCallId}:t}(n.get(e.id),e));let r=[...n.values()];return[...r.filter(e=>"pending"===e.status||"running"===e.status).sort((e,t)=>e.index-t.index||e.id.localeCompare(t.id)),...r.filter(e=>"pending"!==e.status&&"running"!==e.status).sort((e,t)=>t.lastUpdate-e.lastUpdate||e.id.localeCompare(t.id))].slice(0,128)}function s6(e,t){switch(t.type){case"start":return{isStreaming:!0,streamingMessage:null};case"update":return{isStreaming:!0,streamingMessage:t.message};case"end":case"reset":return{isStreaming:!1,streamingMessage:null};default:return e}}function s8(e){return{steering:e?.steering??[],followUp:e?.followUp??[]}}function s3(e){if(e&&"boolean"==typeof e.fastModeEnabled)return{enabled:e.fastModeEnabled,active:!0===e.fastModeActive}}function s7(e){return t=>{let n=e?.isCompacting?e.compaction:null;if(!n)return t;let r=Date.now()-n.elapsedMs;return{startedAt:t?Math.min(t.startedAt,r):r,reason:t?.reason??n.reason}}}function s9(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1){let r=e[n],i=t[n];if(!r||!i||r.name!==i.name||r.tasks.length!==i.tasks.length)return!1;for(let e=0;e<r.tasks.length;e+=1){let t=r.tasks[e],n=i.tasks[e];if(!t||!n||t.content!==n.content||t.status!==n.status||t.blocker!==n.blocker)return!1}}return!0}function le(e){return"aborted"===e.stopReason?"aborted":"error"===e.stopReason||e.errorMessage?"failed":e.stopReason?"completed":"unknown"}function lt(e,t){for(let n=e.length-1;n>=0;n--){let r=t[n]??null;if(!eG(r??void 0))return{message:e[n],entryId:r}}return null}let ln=new Set(["ArrowUp","ArrowDown","PageUp","PageDown","Home","End"," ","Space","Spacebar"]);class lr extends Error{constructor(e){super("timeout"===e?"Timed out connecting to the agent event stream. Please try again.":"Failed to connect to the agent event stream. Please try again."),this.status=e,this.name="EventStreamConnectionError"}}function li(){return"u">typeof crypto&&"function"==typeof crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2)}`}function la(e){return new Promise(t=>setTimeout(t,e))}function ls(e){let t=e.findIndex(e=>!e.exiting);return -1===t?e:e.map((e,n)=>n===t?{...e,exiting:!0}:e)}function ll(e,t){switch(t.type){case"add":if(e.visible.some(e=>e.exiting)||e.visible.length>=5)return{visible:e.visible.some(e=>e.exiting)?e.visible:ls(e.visible),pending:[...e.pending,t.notice]};return{...e,visible:[...e.visible,t.notice]};case"mark_oldest_exiting":return{...e,visible:ls(e.visible)};case"remove":return function(e,t){let n=e,r=t;for(;r.length>0&&n.length<5;){let[e,...t]=r;n=[...n,e],r=t}return r.length>0&&!n.some(e=>e.exiting)&&(n=ls(n)),{visible:n,pending:r}}(e.visible.filter(e=>e.id!==t.id),e.pending);default:return e}}function lo(e){if(!e||"object"!=typeof e||"image"!==e.type)return"";let t=e.source;return t&&"object"==typeof t?["url"===t.type?"url":"base64","string"==typeof t.media_type?t.media_type:"","string"==typeof t.data?t.data:"","string"==typeof t.url?t.url:""].join(":"):["base64","string"==typeof e.mimeType?e.mimeType:"","string"==typeof e.data?e.data:"",""].join(":")}function ld(e){let t,n=e.content;return"string"==typeof n?JSON.stringify({text:n,images:[]}):Array.isArray(n)?JSON.stringify({text:"string"==typeof(t=e.content)?t:Array.isArray(t)?t.map(e=>e&&"object"==typeof e&&"text"===e.type&&"string"==typeof e.text?e.text:"").filter(Boolean).join("\n"):"",images:n.map(lo).filter(Boolean)}):JSON.stringify({text:"",images:[]})}function lc(e){return"user"===e.role?`user:${ld(e)}`:"bashExecution"===e.role?JSON.stringify({role:e.role,command:e.command,output:e.output,exitCode:e.exitCode,cancelled:e.cancelled,truncated:e.truncated,fullOutputPath:e.fullOutputPath,excludeFromContext:e.excludeFromContext}):JSON.stringify({role:e.role,content:e.content,model:e.model,provider:e.provider,customType:e.customType})}function lu(e,t){return e&&"object"==typeof e?"number"!=typeof e.tokensBefore||"number"!=typeof e.estimatedTokensAfter?null:{reason:t,tokensBefore:e.tokensBefore,estimatedTokensAfter:e.estimatedTokensAfter}:null}function lp(e){return e?.map(({data:e,mimeType:t})=>({data:e,mimeType:t}))}function lh(){let e=document.activeElement;return e instanceof HTMLElement&&(e.isContentEditable||"INPUT"===e.tagName||"SELECT"===e.tagName||"TEXTAREA"===e.tagName)}let lm=!1,lf={width:0,height:0},lg=new Set,lx=null;function lv(){let e=window.visualViewport,t=lh();lf.width!==window.innerWidth?lf={width:window.innerWidth,height:window.innerHeight}:t||(lf.height=Math.max(lf.height,window.innerHeight));let n=function({hasFocusedEditable:e,innerHeight:t,viewportHeight:n,viewportScale:r,baselineHeight:i}){return!(!e||Math.abs(r-1)>=.01)&&(t-n>120||i-t>120)}({hasFocusedEditable:t,innerHeight:window.innerHeight,viewportHeight:e?.height??window.innerHeight,viewportScale:e?.scale??1,baselineHeight:lf.height});if(n!==lm)for(let e of(lm=n,lg))e()}function lb(e){if(lg.add(e),!lx){let e=null,t=()=>{null!==e&&window.cancelAnimationFrame(e),e=window.requestAnimationFrame(()=>{e=null,lv()})},n=window.visualViewport;n?.addEventListener("resize",t),window.addEventListener("resize",t),window.addEventListener("focusin",t),window.addEventListener("focusout",t),lv(),lx=()=>{n?.removeEventListener("resize",t),window.removeEventListener("resize",t),window.removeEventListener("focusin",t),window.removeEventListener("focusout",t),null!==e&&window.cancelAnimationFrame(e)}}return()=>{lg.delete(e),0===lg.size&&lx&&(lx(),lx=null)}}function ly(){return(0,i.useSyncExternalStore)(lb,()=>lm,()=>!1)}let lw={count:50,end:null};function lk(e,t){let n=Math.max(e,0),r=null===t.end?n:Math.min(Math.max(t.end,0),n),i=Math.min(Math.max(t.count,0),r),a=r-i;return{startIndex:a,endIndex:r,hasMore:a>0,hasLater:r<n}}function lj(e,t,n){let{startIndex:r,endIndex:i}=lk(e,n);if(t>=r&&t<i)return n;let a=Math.max(0,t-10),s=Math.max(t+1,a+50);return s>=e?{count:e-a,end:null}:{count:s-a,end:s}}function lS({sticker:e,text:t,tag:n,followRef:a}){let s=(0,i.useRef)(null);return((0,i.useEffect)(()=>{(!a||a.current)&&s.current?.scrollIntoView({block:"nearest",behavior:"smooth"})},[]),e||t)?(0,r.jsxs)("div",{ref:s,className:"cue-bubble-dock",role:"status","aria-live":"polite",children:[e&&(0,r.jsx)("img",{className:"cue-bubble-sticker",src:e,alt:iC[n]}),t&&(0,r.jsx)("p",{className:e?"cue-bubble":"cue-bubble cue-bubble--solo",children:t}),e&&(0,r.jsx)(iw(),{id:"ad10be785ccf4f7",children:".cue-bubble-sticker{transform-origin:center 75%;animation:cue-sticker-pop 200ms cubic-bezier(0,0,.15,1)both}@keyframes cue-sticker-pop{from{opacity:0;transform:scale(.88)}to{opacity:1;transform:scale(1)}}@media(prefers-reduced-motion:reduce){.cue-bubble-sticker{animation:none}}"})]}):null}function lC(e){if("user"!==e.role)return null;let t="string"==typeof e.content?e.content:e.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n"),n=(rx(t)?.message??t).trim();return n.length>0?n:null}function lN(e){return`omp-cues:${e}`}function lI(e,t){let n=[];for(let r of t)r.sessionId===e&&null!==r.anchorEntryId&&n.push({id:r.id,anchorEntryId:r.anchorEntryId,sticker:r.sticker,text:r.text,tag:r.tag});try{window.localStorage.setItem(lN(e),JSON.stringify(n.slice(-200)))}catch{}}let lT=[];function lM(e){return`omp-web:interrupted-dismissed:${e}`}let l$=(0,i.memo)(function({messages:e,entryIds:t,toolResultsMap:n,modelNames:a,messageCwd:s,onOpenFile:l,sessionBusy:o,isNew:d,isStreaming:c,handleFork:u,forkingEntryId:p,handleNavigate:h,handleEditContent:m,sessionId:f,main:g,process:x,dispatchSlots:v,compactedDispatch:b,startIndex:y,endIndex:w,sentinelRef:k,laterSentinelRef:j,flashItem:S,t:C,onProcessLogChange:N,cues:I,cueFollowRef:T}){(0,i.useEffect)(()=>{N({groups:x,messages:e,entryIds:t,toolResults:n,modelNames:a,cwd:s,sessionId:f})},[N,x,e,t,n,a,s,f]);let M=(0,i.useMemo)(()=>{let t=new Map;for(let[r,i]of function(e,t,n,r){let i=new Map;e.forEach((e,t)=>{"answer"===e.kind&&i.set(e.idx,t)});let a=new Map,s=new Map;for(let e of t){let t=s.get(e.anchorIdx);for(let l of(t||(t=new Set,s.set(e.anchorIdx,t)),e.entries)){let e=n[l.idx];if(e?.role!=="assistant")continue;let s=Math.max(0,(l.blocks?i.get(l.idx):void 0)??l.afterMainIndex??-1),o=t;!function(e,t,n){for(let r of e){if("toolCall"!==r.type||"learn"!==r.toolName&&"manage_skill"!==r.toolName)continue;let e=t?.get(r.toolCallId);if(!e||e.isError)continue;let i=r.input??{};if("manage_skill"===r.toolName){let e=eQ(i.action);if(!0===eX[e]){let t={kind:"skill",action:e,name:eQ(i.name)};n(JSON.stringify(t),t)}continue}let a=eQ(i.memory),s=i.skill,l=s?{action:eQ(s.action),name:eQ(s.name)}:void 0;n(JSON.stringify({kind:"lesson",memory:a,skill:l}),{kind:"lesson",memory:a.length>160?`${a.slice(0,160)}…`:a,...l?{skill:l}:{}})}}(l.blocks??e.content??[],r,(e,t)=>{if(o.has(e))return;o.add(e);let n=a.get(s);n?n.push(t):a.set(s,[t])})}}return a}(g,x,e,n)){let e=i.map(e=>{if("skill"===e.kind)return C("chat.savedSkill",{action:e.action,name:e.name});let t=C("chat.savedLesson",{memory:e.memory});return e.skill?`${t} (${C("chat.savedSkill",e.skill)})`:t});t.set(r,{role:"custom",customType:eK,content:[C("chat.lessonsSaved"),...e.map(e=>`- ${e}`)].join("\n"),display:!0})}return t},[g,x,e,n,C]),$=(0,i.useMemo)(()=>{let t=null;if(o)for(let n of g)"message"===n.kind&&e[n.idx]?.role==="user"&&(t=n.idx);let r=new Map;for(let[i,a]of function(e,t,n){let r=new Map,i=e.filter(e=>"message"===e.kind&&t[e.idx]?.role==="user").map(e=>e.idx),a=new Map;for(let[s,l]of(e.forEach((e,t)=>{"answer"===e.kind&&a.set(e.anchorIdx,t)}),a)){if(s===n)continue;let e=i.find(e=>e>s);r.set(l,{from:s+1,to:e??t.length})}return r}(g,e,t))r.set(i,nU(function(e,t,n){let r=[];for(let i=Math.max(0,t);i<Math.min(e.length,n);i++){let t=e[i];"assistant"===t.role&&r.push(...t.content??[])}return r}(e,a.from,a.to),n,s));return r},[g,e,n,s,o]),R=y>0,E=w<g.length,L=(i,g={})=>{let x=g.messageOverride??e[i],v=i-1;for(;v>=0&&eG(t[v]);)v-=1;let b="user"===x.role&&v>=0&&"assistant"===e[v].role?t[v]:void 0,y=g.keyPrefix??"message",w=!1;if("assistant"===x.role){w=!0;for(let t=i+1;t<e.length;t++){let n=e[t].role;if("user"===n)break;if("assistant"===n){w=!1;break}}w&&c&&i===e.length-1&&(w=!1)}return void 0!==g.showTimestamp&&(w=g.showTimestamp),(0,r.jsx)(rO,{message:x,toolResults:n,modelNames:a,cwd:s,onOpenFile:l,entryId:t[i],onFork:o||d||0===i&&"user"===x.role?void 0:u,forking:p===t[i],onNavigate:o?void 0:h,prevAssistantEntryId:o?void 0:b,onEditContent:m,showTimestamp:w,prevTimestamp:i>0?e[i-1].timestamp:void 0,sessionId:f,writtenFiles:g.writtenFiles,dispatchSlot:g.dispatchSlot,turnSummary:g.turnSummary},`${y}-view-${i}`)},A=(t,n)=>{let i=g[t],a="message"===i.kind&&e[i.idx]?.role==="user";return(0,r.jsx)("div",{"data-chat-item":t,"data-chat-question":a?"":void 0,className:S===t?"chat-item chat-jump-flash":"chat-item",children:n})};return(0,r.jsxs)(r.Fragment,{children:[R&&(0,r.jsx)("div",{ref:k,className:"py-3 text-center text-xs text-text-muted",children:C("chat.loadEarlier",{count:y})}),g.slice(y,w).map((a,o)=>{let d=y+o,c=b?.position===d?(0,r.jsx)(n7,{calls:b.calls}):null,u="message"===a.kind?a.anchorIdx??a.idx:a.anchorIdx,p=g[d+1],h=p?"message"===p.kind?p.anchorIdx??p.idx:p.anchorIdx:null,m=p?p.idx:1/0,x=I.filter(n=>{let r=null!==n.anchorEntryId?t.indexOf(n.anchorEntryId):Math.min(n.liveIndex??-1,e.length-1);return r>=a.idx&&r<m}).map(e=>(0,r.jsx)(lS,{sticker:e.sticker,text:e.text,tag:e.tag,followRef:T},`cue-${e.id}`)),w=h!==u,k=M.get(d),j=k?(0,r.jsx)(rO,{message:k,cwd:s,onOpenFile:l},`saved-lessons-${d}`):null,S=w?(0,r.jsx)(iO,{turnIndex:u,turnEntryId:t[u],sessionId:f,cwd:s,onOpenFile:l}):null;if("message"===a.kind)return(0,r.jsxs)(i.Fragment,{children:[c,A(d,L(a.idx)),j,S,x]},`message-${a.idx}`);let C=e8(a.precedingBlocks,n,s);return(0,r.jsxs)(i.Fragment,{children:[c,A(d,L(a.idx,{keyPrefix:`answer-${a.runIndex}`,messageOverride:ez(e[a.idx],a.blocks),writtenFiles:C,dispatchSlot:v.get(d),turnSummary:$.get(d)})),j,S,x]},`answer-${a.idx}-${a.runIndex}`)}),b?.position===g.length&&w===g.length&&(0,r.jsx)(n7,{calls:b.calls}),E&&(0,r.jsx)("div",{ref:j,className:"py-3 text-center text-xs text-text-muted",children:C("chat.loadLater",{count:g.length-w})})]})});function lR({session:e,newSessionCwd:t,initialSessionData:a,transitioning:s=!1,onAgentEnd:l,onAttentionNeeded:o,onSessionCreated:d,onSessionForked:c,modelsRefreshKey:u,chatInputRef:p,onBranchDataChange:h,onSystemPromptChange:m,onSessionStatsChange:f,onSessionStatsPanelOpen:g,onContextUsageChange:x,onSubagentsChange:b,onMainIdentityChange:y,onOpenWorkspaceView:w,onOpenMaker:k,selectedMaker:j,onProcessLogChange:S,onOpenFile:C,transcriptReplacement:N,onComposerFocusChange:I,onSessionBusyChange:T,onWaitingChange:M,onAttentionChange:$,soundEnabled:E=!0,onSoundToggle:L,playCueSound:A=async()=>({sticker:null,text:null}),preloadCueSound:z,unlockAudio:P,jumpRequest:_=null,onJumpHandled:D}){var O,H;let B,U,q,{t:K}=(0,R.s)(),J=ly(),G=W(),Y=J&&G,Z=(0,i.useRef)(A);Z.current=A;let X=(0,i.useRef)(null),Q=(0,i.useRef)(z);Q.current=z;let[ee,et]=(0,i.useState)([]),en=(0,i.useRef)(ee);en.current=ee;let er=(0,i.useRef)(0),ei=(0,i.useRef)([]),ea=(0,i.useRef)([]),es=(0,i.useRef)(null),el=(0,i.useRef)(0),eo=(0,i.useRef)(-1),ed=(0,i.useRef)(-1),ec=(0,i.useCallback)(()=>{let e=es.current?.current;return e?{sessionId:e,turn:el.current}:null},[]),eu=(0,i.useCallback)(e=>es.current?.current===e.sessionId&&el.current===e.turn,[]),ep=(0,i.useCallback)((e,t,n,r)=>{if(!e.sticker&&!e.text)return;er.current=Math.max(er.current+1,Date.now());let i={id:er.current,sticker:e.sticker,text:e.text,tag:t,sessionId:n.sessionId},a="entry"===r.kind?{...i,anchorEntryId:r.entryId}:{...i,anchorEntryId:null,liveIndex:r.liveIndex,intent:r.intent};et(e=>{let t=[...e,a];return null!==a.anchorEntryId&&lI(n.sessionId,t),t})},[]),eh=(0,i.useCallback)((e,t,n,r)=>{let i=()=>eu(n)&&("working"!==t||ed.current!==n.turn);i()&&Z.current(e,t,i).then(e=>{null!==t&&null!==r&&i()&&ep(e,t,n,r)}).catch(()=>{})},[eu,ep]),em=(0,i.useCallback)(async(e,t,n)=>{let r=(await nh(e,t,n))?.alias??null;return r&&Q.current?.(r),r},[]),ef=(0,i.useCallback)((e,t,n,r)=>{let i=function(e,t){let n=e.length-1;if(n<0)return null;let r=Math.min(e.length,t.length);if(n<r)return{kind:"entry",entryId:t[n]};let i=iL(e[n]),a=0;for(let t=r;t<=n;t++)iL(e[t])===i&&(a+=1);return{kind:"pending",liveIndex:n,intent:{baseEntryId:r>0?t[r-1]:null,identity:i,occurrence:a}}}(ei.current,ea.current);em(t.sessionId,n,r).then(n=>{eh(n,e,t,i)})},[eh,em]),[eg,ex]=(0,i.useState)(0),ev=(0,i.useRef)([]),eb=(0,i.useCallback)(e=>{if(el.current+=1,null!==iI(e.outcome)){let t=e.sessionId;ev.current.push({completion:e,trigger:t?{sessionId:t,turn:el.current}:null}),ex(e=>e+1)}l?.(e)},[l]);(0,i.useEffect)(()=>{for(let{completion:e,trigger:t}of ev.current.splice(0)){let n=iI(e.outcome),r="neutral"===n?null:n;t?ef(r,t,e.provider,e.credentialId):Z.current(null,r).catch(()=>{})}},[eg,ef]);let ey=(0,i.useCallback)(e=>{p?.current?.replaceMessage(e)},[p]),{loading:ew,error:ek,messages:eS,entryIds:eC,streamState:eN,agentRunning:eI,bashRunning:eT,pendingBash:eM,modelNames:e$,modelList:eR,modelError:eE,modelScopeWarnings:eL,modelThinkingLevels:eA,modelThinkingLevelMaps:eP,modelRoles:eD,toolPreset:eO,thinkingLevel:eB,effectiveThinkingLevel:eU,thinkingCeiling:eK,fastMode:eX,fastModeBusy:eQ,handleFastModeToggle:e1,retryInfo:e2,contextUsage:e4,forkingEntryId:e5,isCompacting:e6,compaction:e8,compactError:e3,compactResult:e9,displayModel:te,modelSwitching:tt,sessionStats:tn,runStateKnown:tr,compactedWork:ti,slashCommands:ta,slashCommandsLoading:ts,deliveryRows:tl,subagents:to,todoPhases:td,notices:tc,extensionDialog:tu,extensionResponse:tp,extensionCustomUi:th,extensionStatuses:tm,extensionWidgets:tf,respondToExtensionUi:tg,sendExtensionCustomInput:tx,isAutoModelSelection:tv,agentPhase:tb,isNew:ty,autoFollowPaused:tw,resumeAutoFollow:tk,pauseAutoFollow:tj,goalStatus:tS,sessionIdRef:tC,messagesEndRef:tN,scrollContainerRef:tI,handleSend:tT,handleAbort:tM,handleFork:t$,handleNavigate:tR,handleModelChange:tE,handleRoleModelChange:tL,handleMainPresetChange:tA,newSessionAccount:tz,handleCompact:tP,handleSteer:tW,handleFollowUp:tF,handlePromptWithStreamingBehavior:t_,handleAbortCompaction:tD,handleRecallQueue:tO,handleRemoveQueuedMessage:tH,handleBuiltinSlashCommand:tB,handleToolPresetChange:tU,handleThinkingLevelChange:tq,loadSlashCommands:tK,ensureNewSession:tV,refreshLiveTranscript:tJ}=function(e){let{session:t,newSessionCwd:r,initialData:a,onAgentEnd:s,onAttentionNeeded:l,onSessionCreated:o,onSessionForked:d,modelsRefreshKey:c,onBranchDataChange:u,onSystemPromptChange:p,onSessionStatsPanelOpen:h}=e,m=null===t&&null!==r,f=a&&a.sessionId===t?.id?a:null,[g,x]=(0,i.useState)(f),[v,b]=(0,i.useState)(!m&&!f),[y,w]=(0,i.useState)(null),[k,j]=(0,i.useState)(f?.leafId??null),[S,C]=(0,i.useState)(f?.context.messages??[]),[N,I]=(0,i.useState)(f?.context.entryIds??[]),[T,M]=(0,i.useState)(f?.context.compactedWork??null),[$,R]=(0,i.useReducer)(s6,{isStreaming:!1,streamingMessage:null}),[E,L]=(0,i.useState)(!1),[A,z]=(0,i.useState)(!1),[P,W]=(0,i.useState)(null),[F,_]=(0,i.useState)({}),[D,O]=(0,i.useState)([]),[H,B]=(0,i.useState)(null),[U,q]=(0,i.useState)([]),[K,V]=(0,i.useState)({}),[J,G]=(0,i.useState)({}),[Y,Z]=(0,i.useState)([]),[X,Q]=(0,i.useState)(null),[ee,et]=(0,i.useState)(null),[en,er]=(0,i.useState)(null),[ei,ea]=(0,i.useState)("default"),[es,el]=(0,i.useState)(()=>{let e=f?.context.thinkingLevel;return e&&"off"!==e?e:"auto"}),[eo,ed]=(0,i.useState)(),[ec,eu]=(0,i.useState)(null),[ep,eh]=(0,i.useState)(null),[em,ef]=(0,i.useState)(!1),eg=(0,i.useRef)(0),ex=(0,i.useRef)(0),ev=(0,i.useRef)(""),[eb,ey]=(0,i.useState)(null),[ew,ek]=(0,i.useState)(f?.contextUsage??null),[eS,eC]=(0,i.useState)(null),[eN,eI]=(0,i.useState)(null),[eT,eM]=(0,i.useState)(null),[e$,eR]=(0,i.useState)(null),[eE,eL]=(0,i.useState)(!1),[eA,ez]=(0,i.useState)(!1),[eP,eW]=(0,i.useState)(null),[eF,e_]=(0,i.useState)(null),[eD,eO]=(0,i.useState)(null),eH=(0,i.useRef)(null),[eB,eU]=(0,i.useState)(!1),[eK,eV]=(0,i.useState)(null),[eZ,eX]=(0,i.useState)([]),[eQ,e0]=(0,i.useState)(!1),[e1,e2]=(0,i.useReducer)(ll,{visible:[],pending:[]}),[e4,e5]=(0,i.useState)(null),[e6,e8]=(0,i.useState)(null),[e3,e7]=(0,i.useState)(null),e9=(0,i.useRef)(null),[te,tt]=(0,i.useState)(null),[tn,tr]=(0,i.useState)([]),[ti,ta]=(0,i.useState)([]),[ts,tl]=(0,i.useState)({steering:[],followUp:[]}),[to,td]=(0,i.useState)([]),[tc,tu]=(0,i.useReducer)(i6,[]),tp=(0,i.useRef)(0);(0,i.useEffect)(()=>{tu({type:"queue",steering:ts.steering,followUp:ts.followUp})},[ts]),(0,i.useEffect)(()=>{E||tu({type:"idle"})},[E]),(0,i.useEffect)(()=>{tu({type:"reset"})},[t?.id]);let th=(0,i.useMemo)(()=>(function(e,t){let n=new Map;for(let t of e){if(!t.inQueue)continue;let e=`${t.kind}\u0000${i4(t)}`;n.set(e,(n.get(e)??0)+1)}let r=[],i=(e,t)=>{t.forEach((t,i)=>{let a=`${e}\u0000${i2(t)}`,s=n.get(a)??0;s>0?n.set(a,s-1):r.push({key:`queue-${e}-${i}`,kind:e,text:t,images:0,stage:"accepted",removable:!0})})};for(let n of(i("steer",t?.steering??[]),i("followUp",t?.followUp??[]),e))r.push({key:`sent-${n.id}`,kind:n.kind,text:n.text,images:n.images,stage:n.stage,removable:n.inQueue});return r})(tc,ts),[tc,ts]),[tm,tf]=(0,i.useState)(null),tg=(0,i.useRef)(null),tx=(0,i.useRef)(null),tv=(0,i.useRef)(null),tb=(0,i.useRef)(null),ty=(0,i.useRef)(null),tw=(0,i.useRef)(0),tk=(0,i.useRef)(!1),tj=(0,i.useRef)(t?.id??null),tS=(0,i.useRef)(f?.leafId??null),tC=(0,i.useRef)(S),tN=(0,i.useRef)(N);tC.current=S,tN.current=N;let tI=(0,i.useRef)({sessionId:t?.id??null,outputs:[],seq:0}),tT=(0,i.useRef)(!1),tM=(0,i.useRef)(!1),t$=(0,i.useRef)(!1),tR=(0,i.useRef)(-1),tE=(0,i.useRef)("unknown"),tL=(0,i.useRef)(null),tA=(0,i.useRef)(null),tz=(0,i.useRef)(0),tP=(0,i.useRef)(!1),tW=(0,i.useRef)(0),tF=(0,i.useRef)(null),t_=(0,i.useRef)(null),tD=(0,i.useRef)(null),tO=(0,i.useRef)(!1),tH=(0,i.useRef)(!0),[tB,tU]=(0,i.useState)(!1),[tq,tK]=(0,i.useState)(null),tV=(0,i.useRef)(void 0),tJ=(0,i.useRef)(0),tG=(0,i.useRef)(0),tY=(0,i.useRef)(()=>{}),tZ=(0,i.useRef)(null),tX=(0,i.useRef)(null),tQ=(0,i.useRef)(null),t0=(0,i.useRef)(null),t1=(0,i.useRef)(!1),t2=(0,i.useRef)(null),t4=(0,i.useRef)(null),t5=(0,i.useRef)(null),t6=(0,i.useRef)(null),t8=(0,i.useRef)(0),t3=(0,i.useRef)(null),t7=(0,i.useRef)(null),t9=(0,i.useRef)(!1);t9.current=e.transitioning??!1;let ne=(0,i.useRef)(Date.now()),nt=(0,i.useRef)(0),nn=(0,i.useRef)(0),nr=(0,i.useRef)(null),ni=(0,i.useRef)(!1),na=(0,i.useRef)(Promise.resolve()),ns=e.setToolPreset??ea,nl=eT??g?.context.model??e$??null,no=m?X??en:nl,nd=(0,i.useMemo)(()=>{if(e4)return{...e4,totalActiveMs:g?.totalActiveMs};let e={input:0,output:0,cacheRead:0,cacheWrite:0,total:0},n=0,r=0,i=0,a=0,s=0;for(let t of S){if("user"===t.role&&(r+=1),"toolResult"===t.role&&(a+=1),"assistant"!==t.role)continue;i+=1;let l=t.usage;s+=t.content.filter(e=>"toolCall"===e.type).length,l&&(e.input+=l.input??0,e.output+=l.output??0,e.cacheRead+=l.cacheRead??0,e.cacheWrite+=l.cacheWrite??0,n+=l.cost?.total??0)}return(e.total=e.input+e.output+e.cacheRead+e.cacheWrite,0===e.total&&0===S.length)?null:{sessionFile:g?.filePath||void 0,sessionId:tj.current??t?.id??"",sessionName:t?.name,userMessages:r,assistantMessages:i,toolCalls:s,toolResults:a,totalMessages:S.length,tokens:e,cost:n,totalActiveMs:g?.totalActiveMs,...ew?{contextUsage:ew}:{}}},[S,e4,ew,g?.filePath,g?.totalActiveMs,t?.id,t?.name]),nc=(0,i.useRef)(0),nu=(0,i.useCallback)((e,t)=>{e&&tj.current===e&&Array.isArray(t)&&(nc.current+=1,tf(n=>n?.sid===e&&s9(n.phases,t)?n:{sid:e,phases:t}))},[]),np=(0,i.useCallback)((e,t,n)=>{tj.current===e&&nc.current===n&&Array.isArray(t)&&tf(n=>n?.sid===e&&s9(n.phases,t)?n:{sid:e,phases:t})},[]),nh=(0,i.useCallback)(e=>{let t="function"==typeof e?e(tC.current):e;tC.current=t,C(t)},[]),nm=(0,i.useCallback)(e=>{tN.current=e,I(e)},[]),nf=(0,i.useCallback)(async(e,t=!1,n=!1,r)=>{let i=!1;try{t&&b(!0);let a=r??null;if(!a){let n=new URLSearchParams({deferThinking:"1",deferMedia:"1"}),r=await fetch(`/api/sessions/${encodeURIComponent(e)}?${n}`);if(404===r.status)return t&&(x(null),j(null),nh([]),M(null),w(null)),null;if(!r.ok)throw Error(`HTTP ${r.status}`);a=await r.json()}if(tj.current!==e)return null;x(a),j(a.leafId),tS.current=a.leafId??null;let s=eY(a.context.messages,a.context.entryIds??[],tI.current.sessionId===e?tI.current.outputs:[]);nh(s.messages),nm(s.entryIds),M(a.context.compactedWork??null),ek(a.contextUsage??null),eM(e=>ni.current?e:null),w(null);let l=!n&&t6.current===e;if(l||(el(a.context.configuredThinkingLevel??a.context.thinkingLevel??"off"),ed(a.context.thinkingLevel)),eu(a.context.thinkingCeiling??null),i=!0,t&&b(!1),!n){if(l)try{let t=t8.current,n=await fetch(`/api/sessions/${encodeURIComponent(e)}/state`);if(n.ok&&tj.current===e){let r=await n.json();tj.current===e&&t8.current===t&&(r.state?.thinkingLevel!==void 0?(el(r.state.configuredThinkingLevel??r.state.thinkingLevel),ed(r.state.thinkingLevel)):r.running||(t6.current=null,el(a.context.configuredThinkingLevel??a.context.thinkingLevel??"off"),ed(a.context.thinkingLevel)))}}catch(e){console.error("Failed to refresh live thinking level:",e)}return null}try{let t=nc.current,n=await fetch(`/api/sessions/${encodeURIComponent(e)}/state`);if(!n.ok)throw Error(`HTTP ${n.status}`);let r=await n.json();if(tj.current!==e)return null;let i=r.state;return i?(void 0!==i.contextUsage&&ek(i.contextUsage??null),void 0!==i.systemPrompt&&eC(i.systemPrompt??null),void 0!==i.thinkingLevel&&(t6.current=e,el(i.configuredThinkingLevel??i.thinkingLevel),ed(i.thinkingLevel)),void 0!==i.thinkingCeiling&&eu(i.thinkingCeiling??null),void 0!==i.extensionStatuses&&tr(i.extensionStatuses??[]),void 0!==i.extensionWidgets&&ta(i.extensionWidgets??[]),void 0!==i.queuedMessages&&tl(s8(i.queuedMessages)),void 0!==i.subagents&&td(e=>s5(e,i.subagents??[])),np(e,i.todoPhases,t)):r.running||tl({steering:[],followUp:[]}),r}catch(e){return console.error("Failed to load agent state:",e),null}}catch(e){return w(String(e)),null}finally{t&&!i&&b(!1)}},[np,nm,nh]),ng=(0,i.useCallback)(e=>{let t=na.current.then(async()=>{tj.current===e&&await nf(e)});return na.current=t.catch(()=>{}),t},[nf]),nx=(0,i.useCallback)(async(e,t)=>{let n=++ex.current;try{let r=new URLSearchParams({deferThinking:"1",deferMedia:"1"});t&&r.set("leafId",t);let i=`/api/sessions/${encodeURIComponent(e)}/context?${r}`,a=await fetch(i);if(!a.ok)throw Error(`HTTP ${a.status}`);let s=await a.json();if(ex.current!==n||tj.current!==e)return;tS.current=t;let l=eY(s.context.messages,s.context.entryIds??[],tI.current.sessionId===e?tI.current.outputs:[]);nh(l.messages),nm(l.entryIds),M(s.context.compactedWork??null),ek(s.contextUsage??null)}catch(e){console.error("Failed to load context:",e)}},[nm,nh]),nv=(0,i.useCallback)(async e=>{try{let t=await sB(e,{type:"get_tools"});if(t){let{getPresetFromTools:e}=await Promise.resolve().then(n.bind(n,14755));ns(e(t))}}catch(e){console.error("Failed to load tools:",e)}},[ns]),nb=(0,i.useCallback)((e=0,t="(no messages)")=>{let n=tj.current;m&&r&&n&&!t1.current&&(t1.current=!0,o?.({id:n,path:"",cwd:r,name:void 0,created:new Date().toISOString(),modified:new Date().toISOString(),messageCount:e,firstMessage:t,transient:!0}))},[m,r,o]),ny=(0,i.useCallback)(async()=>{if(tQ.current)return tQ.current;let e=tj.current;if(e&&t7.current!==e||!e&&(!m||!r))return e;let t=(async()=>{let t=e;if(!t){let e=t2.current,n=t5.current,i=t4.current;e&&eR(e);let a={cwd:r,type:"ensure_session",toolNames:(0,a7.xG)(ei),...e?{provider:e.provider,modelId:e.modelId}:{},...n?{thinkingLevel:n}:{},...e&&null!==i?{oauthPosition:i}:{}},s=JSON.stringify(a),l=t0.current,o=l?.body===s?l.createRequestId:li();t0.current={body:s,createRequestId:o};let d=await fetch("/api/agent/new",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...a,createRequestId:o})});if(!d.ok)throw Error(`HTTP ${d.status}`);let c=await d.json();t0.current=null,t=c.sessionId,tj.current=t,null!==t3.current&&(t7.current=t),c.model&&t2.current===e&&(eR(c.model),e||er(c.model)),c.thinkingLevel&&t5.current===n&&(el(c.configuredThinkingLevel??c.thinkingLevel),ed(c.thinkingLevel))}for(;t7.current===t;){let e=t3.current;await sB(t,{type:"set_thinking_ceiling",ceiling:e}),t3.current===e&&t7.current===t&&(t7.current=null)}return t})();tQ.current=t;try{return await t}finally{tQ.current=null}},[m,r,ei]),nw=(0,i.useCallback)(async()=>{let e=tj.current??await ny();if(!e)return eX([]),[];e0(!0);try{let t=await sB(e,{type:"get_commands"}),n=t?.commands??[];return eX(n),n}catch(e){return console.error("Failed to load slash commands:",e),eX([]),[]}finally{e0(!1)}},[ny]),nk=(0,i.useCallback)(()=>{tw.current+=1,tk.current=!1,ty.current&&(clearTimeout(ty.current),ty.current=null)},[]),nj=(0,i.useCallback)(()=>{tg.current?.close(),tg.current=null,tx.current=null,tv.current=null},[]),nS=(0,i.useCallback)(()=>{tb.current?.close(),tb.current=null},[]),nC=(0,i.useCallback)(e=>{nS();let t=new EventSource(`/api/agent/${encodeURIComponent(e)}/events?entries=1`);tb.current=t,t.onmessage=t=>{try{let n=JSON.parse(t.data);"session_snapshot"===n.type?tF.current?.(n):"agent_start"===n.type&&t_.current?.(e)}catch{}}},[nS]),nN=(0,i.useCallback)(e=>{nj();let t=new EventSource(`/api/agent/${encodeURIComponent(e)}/events`);tg.current=t,tx.current=e;let n=new Promise(n=>{let r=!1,i=e=>{r||(r=!0,clearTimeout(a),tv.current?.source===t&&(tv.current.pending=!1),n({status:e,source:t}))},a=setTimeout(()=>i("timeout"),5e3);t.onmessage=e=>{try{let t=JSON.parse(e.data);"update_maintenance"===t.type&&window.dispatchEvent(new CustomEvent("ompweb:update-maintenance",{detail:t})),"connected"===t.type&&i("connected"),tF.current?.(t)}catch{}},t.onerror=()=>{if(t.readyState===EventSource.CLOSED&&(i("closed"),tg.current===t&&(tT.current||tk.current))){tg.current=null,tx.current=null,tv.current=null;let t=tw.current;setTimeout(()=>{t===tw.current&&!tg.current&&(tT.current||tk.current)&&nN(e)},1e3)}}});return tv.current={source:t,promise:n,pending:!0},n},[nj]),nI=(0,i.useCallback)(async e=>{let t=tg.current;if(t&&tx.current===e){if(t.readyState===EventSource.OPEN)return;let e=tv.current;if(e?.source===t&&e.pending&&(await e.promise,tg.current===t&&t.readyState===EventSource.OPEN))return}let n=await nN(e);if("connected"!==n.status&&n.source.readyState!==EventSource.OPEN)throw tg.current===n.source&&(tg.current=null),tx.current===e&&(tx.current=null),tv.current?.source===n.source&&(tv.current=null),n.source.close(),new lr(n.status)},[nN]),nT=(0,i.useCallback)(async(e,t)=>{let n=e9.current;if(n?.id===e.id&&"sending"===n.status)return;let r=tj.current,i=e=>{e9.current=e,e7(e)};if(!r)return void i({id:e.id,status:"failed",error:"no session"});i({id:e.id,status:"sending"});try{await sB(r,{type:"extension_ui_response",id:e.id,...t})}catch(t){i({id:e.id,status:"failed",error:t instanceof Error?t.message:String(t)});return}i(null),e8(t=>t?.id===e.id?null:t)},[]),nM=(0,i.useCallback)(async(e,t)=>{let n=tj.current;if(n)try{await sB(n,{type:"extension_ui_input",id:e.id,data:t})}catch(e){console.error("Failed to send extension custom UI input:",e)}},[]),n$=(0,i.useCallback)(e=>{let t=e.message.trim();t&&e2({type:"add",notice:{id:e.id??li(),message:t,type:e.type??"info"}})},[]),nR=(0,i.useCallback)(e=>{let t={role:"custom",customType:eq,content:ej(e).trim(),display:!0,timestamp:Date.now()},n=tI.current,r=tj.current;n.sessionId!==r&&(n.sessionId=r,n.outputs=[]);let i=tN.current.slice(0,tC.current.length),a=null;for(let e=i.length-1;e>=0;e--)if(!eG(i[e])){a=i[e];break}n.seq+=1,n.outputs.push({entryId:`${eJ}${n.seq}`,baseEntryId:a,message:t}),nh(e=>[...e,t])},[nh]),nE=(0,i.useCallback)(t=>{if("custom"!==t.method&&"closed"in t&&t.closed){e8(e=>e?.id===t.id?null:e),e9.current?.id===t.id&&(e9.current=null,e7(null));return}switch(s_(t)&&l?.(t),t.method){case"select":case"confirm":case"input":case"editor":case"ask":case"plan_review":e8(t);break;case"notify":n$({id:t.id,message:t.message,type:t.notifyType??"info"});break;case"setStatus":tr(e=>{let n=e.filter(e=>e.key!==t.statusKey);return void 0!==t.statusText?[...n,{key:t.statusKey,text:t.statusText}]:n});break;case"setWidget":ta(e=>{let n=e.filter(e=>e.key!==t.widgetKey);return t.widgetLines?[...n,{key:t.widgetKey,lines:t.widgetLines,placement:t.widgetPlacement??"aboveEditor"}]:n});break;case"setTitle":t.title&&(document.title=t.title);break;case"set_editor_text":e.chatInputRef?.current?.insertText(t.text);break;case"custom":tt(e=>t.closed?e?.id===t.id?null:e:t)}},[n$,l,e.chatInputRef]),nL=(0,i.useCallback)(()=>{let e=tT.current;return tT.current=!1,L(!1),eV(null),ey(null),R({type:"end"}),e},[]),nA=(0,i.useCallback)(()=>{tE.current="unknown",tL.current=null;let e=lt(tC.current,tN.current);tA.current=e?{entryId:e.entryId,key:lc(e.message)}:null,tz.current+=1},[]),nz=(0,i.useCallback)(()=>{let e=tE.current,t=tL.current;if("unknown"===e){let n=lt(tC.current,tN.current),r=n?.message,i=tA.current;null!==n&&(null===i||(null!==n.entryId&&null!==i.entryId?n.entryId!==i.entryId:lc(n.message)!==i.key))&&r?.role==="assistant"&&r.stopReason&&(e=le(r),t??={provider:r.provider,...void 0!==r.credentialId?{credentialId:r.credentialId}:{}})}return{outcome:e,sessionId:tj.current,...t?{provider:t.provider,...void 0!==t.credentialId?{credentialId:t.credentialId}:{}}:{}}},[]),nP=(0,i.useCallback)(e=>{let t=nz();if("unknown"!==t.outcome||!e)return void s?.(t);let n=tz.current;e.catch(()=>void 0).then(()=>{let e=tj.current===t.sessionId&&tz.current===n;s?.(e?nz():t)})},[s,nz]),nW=(0,i.useCallback)((e,t)=>tR.current!==e&&(tR.current=e,nP(t),!0),[nP]),nF=(0,i.useCallback)(e=>{nk(),tk.current=!0;let t=tw.current,n=async()=>{if(t===tw.current&&tj.current===e&&tk.current)try{let r=nc.current,i=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(!i.ok)throw Error(`HTTP ${i.status}`);let a=await i.json();if(t!==tw.current||tj.current!==e||!tk.current)return;let s=a.state;if(td(e=>s5(e,s?.subagents??[])),np(e,s?.todoPhases,r),a.running&&s&&(s.isStreaming||s.isPromptRunning||s.isHandoffRunning)){tk.current=!1,ty.current=null,tM.current=!!s?.isStreaming,t$.current=!!s?.isPromptRunning,tT.current=!0,L(!0),eV(s?.isStreaming?{kind:"waiting_model"}:{kind:"running_command"});return}if(a.running&&s?.isCompacting){ez(!0),eO(s7(s)),ty.current=setTimeout(()=>void n(),600);return}if(a.running&&(s?.subagents?.length??0)>0){ty.current=setTimeout(()=>void n(),1e3);return}tk.current=!1,ty.current=null,nj()}catch{if(t!==tw.current||tj.current!==e||!tk.current)return;ty.current=setTimeout(()=>void n(),600)}};ty.current=setTimeout(()=>void n(),3e4)},[np,nk,nj]),n_=(0,i.useCallback)(async(e=tj.current,t=nt.current)=>{if(nt.current===t)try{e&&await nf(e)}finally{if(nt.current!==t)return;let n=t$.current,r=tM.current;t$.current=!1,tM.current=!1,nr.current=null;let i=nL();n?nW(t):r&&i&&nP(),e&&nF(e)}},[nf,nP,nW,nF,nL]),nD=(0,i.useCallback)(async(e,t)=>{await la(800);let n=Date.now();for(;tT.current&&Date.now()-n<2e4;){if(void 0!==t&&nt.current!==t)return;try{let n=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(n.ok){let r=await n.json(),i=r.state;if(!r.running||!i||!i.isStreaming&&!i.isPromptRunning)return void await n_(e,t)}}catch{}await la(600)}},[n_]),nO=(0,i.useCallback)(async e=>{let t=tW.current+1;for(tW.current=t;tP.current&&tW.current===t&&tj.current===e;){await la(1e3);try{let n=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(!n.ok)continue;let r=await n.json();if(r.state?.isBashRunning)continue;if(await nf(e),tW.current!==t||tj.current!==e)return;tP.current=!1,z(!1),W(null);return}catch{}}},[nf]),nH=(0,i.useCallback)(async e=>{if(!tT.current)return;let t=nt.current;try{let n=nc.current,r=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(!r.ok)return;let i=await r.json();if(nt.current!==t)return;let a=i.state;if(ez(a?.isCompacting??!1),eO(s7(a)),tl(s8(a?.queuedMessages)),a?.contextUsage!==void 0&&ek(a.contextUsage??null),td(e=>s5(e,a?.subagents??[])),np(e,a?.todoPhases,n),i.running&&a&&(a.isStreaming||a.isPromptRunning||a.isCompacting||a.isHandoffRunning)||!tT.current)return;a&&(void 0!==a.systemPrompt&&eC(a.systemPrompt??null),void 0!==a.extensionStatuses&&tr(a.extensionStatuses??[]),void 0!==a.extensionWidgets&&ta(a.extensionWidgets??[])),await n_(e,t)}catch{}},[np,n_]),nB=(0,i.useCallback)(async e=>{let t=await nf(e,!1,!0),n=t?.state;return!!t?.running&&!!n&&tj.current===e&&!tT.current&&!!(n.isStreaming||n.isPromptRunning||n.isHandoffRunning)&&(tM.current=!!n.isStreaming,t$.current=!!n.isPromptRunning,tT.current=!0,L(!0),eV(n.isStreaming?{kind:"waiting_model"}:{kind:"running_command"}),R({type:"start"}),nN(e),!n.isStreaming&&n.isPromptRunning&&nD(e),!0)},[nN,nf,nD]),nU=(0,i.useCallback)(async(e,t=nt.current)=>{let n=nn.current+1;nn.current=n;try{let r=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(!r.ok)return;let i=await r.json();if(n!==nn.current||tj.current!==e||nt.current!==t)return;i.state?.contextUsage!==void 0&&ek(i.state.contextUsage??null)}catch{}},[]);(0,i.useEffect)(()=>{if(!eA){eH.current=null,eO(null);return}eO(e=>e??{startedAt:Date.now(),reason:eH.current})},[eA]),(0,i.useEffect)(()=>{if(!E&&!eA)return;let e=()=>{let e=tj.current;e&&nU(e)};e();let t=setInterval(e,1e3);return()=>clearInterval(t)},[E,eA,nU]),(0,i.useEffect)(()=>{if(!E)return;let e=()=>{let e=tj.current;e&&nH(e)},t=()=>{"visible"===document.visibilityState&&e()},n=setInterval(e,15e3);return document.addEventListener("visibilitychange",t),window.addEventListener("online",e),()=>{clearInterval(n),document.removeEventListener("visibilitychange",t),window.removeEventListener("online",e)}},[E,nH]),(0,i.useEffect)(()=>{if(E)return;let e=()=>{let e=tj.current;e&&!tT.current&&nB(e)},t=()=>{"visible"===document.visibilityState&&e()},n=e=>{let t=tj.current,n=e.detail?.sessionId;t&&n===t&&!tT.current&&nB(t).then(e=>{e||tj.current!==t||tT.current||nf(t)})};return document.addEventListener("visibilitychange",t),window.addEventListener("online",e),window.addEventListener(sG,n),()=>{document.removeEventListener("visibilitychange",t),window.removeEventListener("online",e),window.removeEventListener(sG,n)}},[E,nB,nf]),t_.current=e=>{if(tj.current!==e||tT.current||tg.current||tD.current)return;let t=nB(e).then(async t=>{t||tj.current!==e||tT.current||await nf(e)}).catch(()=>{}).finally(()=>{tD.current===t&&(tD.current=null)});tD.current=t},(0,i.useEffect)(()=>{tT.current=E},[E]),tF.current=(0,i.useCallback)(e=>{switch(e.type){case"session_snapshot":{let t=function(e,t,n,r,i){if("session_snapshot"!==e.type||"string"!=typeof e.sessionId||e.sessionId!==t||"string"!=typeof e.entryId||""===e.entryId||e.entryId===n||!e.context||!Array.isArray(e.context.messages)||!Array.isArray(e.context.entryIds)||e.context.messages.length!==e.context.entryIds.length)return null;let a=e.context.messages,s=new Map;for(let e of a){let t=lc(e);s.set(t,(s.get(t)??0)+1)}let l=Math.min(r.length,i.length);for(let e of r.slice(0,l)){let t=lc(e),n=s.get(t)??0;n>0&&s.set(t,n-1)}let o=r.slice(l).filter(e=>{let t=lc(e),n=s.get(t)??0;return 0===n||(s.set(t,n-1),!1)});return{entryId:e.entryId,messages:[...a,...o],entryIds:[...e.context.entryIds],compactedWork:e.context.compactedWork??null}}(e,tj.current,tS.current,tC.current,tN.current);if(!t)break;tS.current=t.entryId;let n=eY(t.messages,t.entryIds,tI.current.sessionId===tj.current?tI.current.outputs:[]);nh(n.messages),nm(n.entryIds),M(t.compactedWork);break}case"agent_start":{let e=!tT.current;nk(),e&&nA(),tM.current=!0,tT.current=!0,L(!0),eV({kind:"waiting_model"}),R({type:"start"});break}case"agent_end":if(!tT.current)break;if(eV(null),ey(null),R({type:"end"}),tj.current){nf(tj.current);let e=nc.current;fetch(`/api/agent/${encodeURIComponent(tj.current)}`).then(e=>e.json()).then(t=>{t.state?.contextUsage!==void 0&&ek(t.state.contextUsage??null),t.state?.systemPrompt!==void 0&&eC(t.state.systemPrompt??null),t.state?.extensionStatuses!==void 0&&tr(t.state.extensionStatuses??[]),t.state?.extensionWidgets!==void 0&&ta(t.state.extensionWidgets??[]),t.state?.subagents!==void 0&&td(e=>s5(e,t.state?.subagents??[])),tj.current&&np(tj.current,t.state?.todoPhases,e),t.state?.goal!==void 0&&tK(t.state.goal??null),tl(s8(t.state?.queuedMessages))}).catch(()=>{})}break;case"goal_status":tK(e.status??null);break;case"agent_settled":{let e=tM.current;if(tM.current=!1,!e||t$.current)break;let t=tj.current,n=nL();ez(!1);let r=t?nf(t):void 0;t&&nF(t),n&&nP(r);break}case"prompt_done":{let e=nt.current,t=t$.current;t$.current=!1,nr.current=null;let n=tR.current!==e;if(!t&&!n)break;let r=tj.current;nW(e,r?nf(r):void 0),!tM.current&&(nL(),r&&nF(r))}break;case"prompt_error":tE.current="failed",n$({type:"error",message:e.errorMessage??"Command failed"});break;case"extension_error":tE.current="failed",n$({type:"error",message:e.error??"Extension command failed"});break;case"message_start":case"message_update":{if(!tT.current)break;let t=e.message;if(t?.role!=="assistant")break;t&&R({type:"update",message:(0,sO.B)(t)}),eV(null);break}case"message_end":{if(!tT.current)break;let t=e.message;if(t?.role==="assistant"&&(tL.current={provider:t.provider,...void 0!==t.credentialId?{credentialId:t.credentialId}:{}},tE.current=le(t)),t&&"user"===t.role){let e=(0,sO.B)(t),n=ld(e),r=nr.current;nr.current=null,nh(t=>{let i=t[t.length-1];return r&&i?.role==="user"&&ld(i)===r?r===n?t:[...t.slice(0,-1),e]:[...t,e]}),r||tu({type:"user-message",kind:"steering"in e&&!0===e.steering?"steer":"followUp",text:"user"!==e.role?"":"string"==typeof e.content?e.content:e.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n"),images:"user"!==e.role||"string"==typeof e.content?0:e.content.filter(e=>"image"===e.type).length})}else t&&nh(e=>[...e,(0,sO.B)(t)]);let n=tj.current;n&&nU(n),R({type:"reset"}),eV({kind:"waiting_model"});break}case"thinking_level_changed":{let t=tj.current,n=e.thinkingLevel;t&&void 0!==n&&(t6.current=t,t8.current+=1,el(e.configured??n),ed(n));break}case"todo_changed":nu(tj.current,e.phases);break;case"tool_execution_start":{let t=e.toolCallId,n=e.toolName,r=e.args;eV(e=>{let i=e?.kind==="running_tools"?[...e.tools]:[];return i.some(e=>e.id===t)||i.push({id:t,name:n,args:r}),{kind:"running_tools",tools:i}});break}case"tool_execution_end":{let t=e.toolCallId;eV(e=>{if(e?.kind!=="running_tools")return e;let n=e.tools.filter(e=>e.id!==t);return 0===n.length?{kind:"waiting_model"}:{kind:"running_tools",tools:n}});break}case"subagent_lifecycle":{let t=e.payload;if(!t?.id)break;if("started"!==t.status){let e="failed"===t.status?"failed":"aborted"===t.status?"aborted":"completed";td(n=>{let r=n.find(e=>e.id===t.id);return s5(n,[{id:t.id,index:t.index??r?.index??0,agent:t.agent??r?.agent??t.id,agentSource:t.agentSource??r?.agentSource??"bundled",description:t.description??r?.description,status:e,task:r?.task,assignment:r?.assignment,sessionFile:t.sessionFile??r?.sessionFile,parentToolCallId:t.parentToolCallId??r?.parentToolCallId,lastUpdate:Date.now(),progress:r?.progress?{...r.progress,status:e}:void 0}])});break}let n={id:t.id,index:t.index??0,agent:t.agent??t.id,agentSource:t.agentSource??"bundled",description:t.description,status:"running",sessionFile:t.sessionFile,parentToolCallId:t.parentToolCallId,lastUpdate:Date.now()};td(e=>s5(e,[n]));break}case"subagent_progress":{let t=e.payload;if(!t?.progress)break;let n=t.progress,r={id:n.id,index:t.index??n.index,agent:t.agent??n.agent,agentSource:t.agentSource??"bundled",description:n.description,status:n.status,task:t.task??n.task,assignment:t.assignment??n.assignment,sessionFile:t.sessionFile,parentToolCallId:t.parentToolCallId,lastUpdate:Date.now(),progress:n};td(e=>s5(e,[r]));break}case"queue_update":tl({steering:[...e.steering??[]],followUp:[...e.followUp??[]]});break;case"auto_retry_start":ey({attempt:e.attempt,maxAttempts:e.maxAttempts,errorMessage:e.errorMessage});break;case"auto_retry_end":ey(null);break;case"auto_compaction_start":case"compaction_start":if("string"==typeof e.reason){eH.current=e.reason;let t=e.reason;eO(e=>e?{...e,reason:t}:e)}ez(!0),eW(null),e_(null);break;case"auto_compaction_end":case"compaction_end":if(ez(!1),e.errorMessage)eW(e.errorMessage),e_(null);else if(!e.aborted){e_(lu(e.result,e.reason??"auto"));let t=tj.current;t&&(nf(t),nU(t))}break;case"extension_ui_request":nE(e)}},[n$,nu,np,nk,nE,nf,nP,nW,nU,nA,nF,nL,nm,nh]);let nq=(0,i.useCallback)(async(n,i,a)=>{let s=n.trim();if(!s&&!i?.length&&!a?.length)return"returned";if(tT.current||tP.current||ni.current)return"unknown";let l=rg(n,a??[]),o=!i?.length&&!a?.length&&s.startsWith("/");if(!i?.length&&!a?.length&&s.startsWith("!")){let e=s.startsWith("!!"),t=(e?s.slice(2):s.slice(1)).trim();return t?(await tV.current?.(t,e),"accepted"):"unknown"}nA();let d=nt.current+1;nk(),t$.current=!0;let c=i?.map(e=>({type:"image",source:{type:"base64",media_type:e.mimeType,data:e.data}})),u={role:"user",content:c?.length?[...l.trim()?[{type:"text",text:l}]:[],...c]:l,timestamp:Date.now()};nh(e=>[...e,u]),nr.current=ld(u),nt.current=d,tT.current=!0,L(!0),eV(o?{kind:"running_command"}:{kind:"waiting_model"}),R({type:"start"}),tY.current(!0);let p=i?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),h=null,f=!1,g="unknown";try{if(m&&r){let e=tj.current??await tQ.current,t=await ny();t&&(h=t,X&&(eR(X),e&&await sB(t,{type:"set_model",provider:X.provider,modelId:X.modelId})),await nI(t),f=!0,await sB(t,{type:"prompt",message:l,...p?.length?{images:p}:{}}),nb(1,n),g="accepted")}else t&&(h=t.id,await nI(t.id),f=!0,await sB(t.id,{type:"prompt",message:l,...p?.length?{images:p}:{}}),g="accepted");return o&&h&&nD(h,d),g}catch(l){console.error("Failed to send message:",l);let r=l instanceof sH&&"update_draining"===l.code&&!1===l.accepted;if(!(!f||l instanceof sH&&"prompt_rejected"===l.code&&!1===l.accepted||r)&&h)return nD(h,d),"unknown";t$.current=!1,tT.current=!1,nj();let s=nr.current;return s&&nh(e=>{let t=e[e.length-1];return t?.role==="user"&&ld(t)===s?e.slice(0,-1):e}),n$({type:"error",message:l instanceof Error?l.message:String(l)}),e.chatInputRef?.current?.restoreSubmission?.(n,lp(i),a,t?.id??h??void 0),nr.current=null,L(!1),eV(null),R({type:"end"}),"returned"}},[m,r,X,t,ny,nI,nb,nD,n$,nk,nj,e.chatInputRef,nA,nh]);tV.current=(0,i.useCallback)(async(n,r)=>{if(tT.current||tP.current)return;let i=`${r?"!!":"!"}${n}`;tP.current=!0,tY.current(!0),W({command:n,excludeFromContext:r}),z(!0);try{let e=tj.current??t?.id??await ny();if(!e)throw Error("Unable to create a session for the shell command");await sB(e,{type:"bash",command:n,excludeFromContext:r}),await nf(e),nb(1,i)}catch(t){console.error("Failed to execute shell command:",t),n$({type:"error",message:t instanceof Error?t.message:String(t)}),e.chatInputRef?.current?.insertIfEmpty(i)}finally{tP.current=!1,W(null),z(!1)}},[n$,ny,nf,e.chatInputRef,nb,t]);let nK=(0,i.useCallback)(async()=>{let e=tj.current;if(e){if(tP.current){try{await sB(e,{type:"abort_bash"})}catch(e){console.error("Failed to abort bash:",e)}return}try{await sB(e,{type:"abort"}),tE.current="aborted"}catch(e){console.error("Failed to abort:",e)}}},[]),nV=(0,i.useCallback)(async e=>{if(tP.current)return{forked:!1,error:"Cannot fork while a shell command is running"};let t=tj.current;if(!t)return{forked:!1,error:"No active session to fork"};eI(e??null);try{let{cancelled:n,newSessionId:r}=await sB(t,{type:"fork",...e?{entryId:e}:{}})??{};if(!n&&r)return d?.(r),{forked:!0};return{forked:!1,error:"Fork was cancelled"}}catch(e){return console.error("Fork failed:",e),{forked:!1,error:e instanceof Error?e.message:String(e)}}finally{eI(null)}},[d]),nJ=(0,i.useCallback)(async e=>{if(tP.current)return;let t=tj.current;t&&(sB(t,{type:"navigate_tree",targetId:e}).catch(()=>{}),j(e),await nx(t,e))},[nx]),nG=(0,i.useCallback)(async e=>{if(tP.current)return;j(e);let t=tj.current;t&&(await nx(t,e),e&&sB(t,{type:"navigate_tree",targetId:e}).catch(()=>{}))},[nx]),nY=(0,i.useCallback)(async(e,t)=>{if(m){let n={provider:e,modelId:t},r=t2.current?.provider===e;t2.current=n,r||(t4.current=null,et(null)),Q(n),eR(n);let i=tj.current??await tQ.current;if(!i)return;try{await sB(i,{type:"set_model",provider:e,modelId:t})}catch(e){console.error("Failed to set model:",e)}return}let n=tj.current;if(n&&!ni.current){ni.current=!0,eM({provider:e,modelId:t}),eL(!0);try{await sB(n,{type:"set_model",provider:e,modelId:t}),ni.current=!1,await nf(n)}catch(e){console.error("Failed to set model:",e),ni.current=!1,eM(eT),n$({type:"error",message:`Failed to switch model: ${e instanceof Error?e.message:String(e)}`}),await nf(n)}finally{ni.current=!1,eL(!1)}}},[n$,eT,m,nf,Q]),nZ=(0,i.useCallback)(async e=>{let t={provider:e.provider,modelId:e.modelId},n=e.oauthPosition,r={type:"set_model",provider:e.provider,modelId:e.modelId,thinkingLevel:"auto",...void 0!==n?{oauthPosition:n}:{}},i=t=>`${e.alias} preset was not applied: ${t instanceof Error?t.message:String(t)}`;if(m){if(ni.current)return!1;ni.current=!0,eL(!0);let e=t2.current,a=t4.current,s=t5.current;try{t2.current=t,t4.current=n??null,t5.current="auto";let e=tj.current??await tQ.current;return e&&await sB(e,r),Q(t),et(n??null),eR(t),el("auto"),ed(void 0),e&&await nf(e),!0}catch(n){console.error("Failed to apply Main preset:",n),t2.current=e,t4.current=a,t5.current=s,n$({type:"error",message:i(n)});let t=tj.current;return t&&await nf(t),!1}finally{ni.current=!1,eL(!1)}}let a=tj.current;if(!a||ni.current)return!1;ni.current=!0,eM(t),eL(!0);try{return await sB(a,r),await nf(a),!0}catch(e){return console.error("Failed to apply Main preset:",e),eM(eT),n$({type:"error",message:i(e)}),await nf(a),!1}finally{ni.current=!1,eL(!1)}},[n$,eT,eo,m,nf,Q,es]),nX=(0,i.useCallback)(async e=>{let t=Y.find(t=>t.role===e),n=t?.resolved;if(!n)return;if(m){let e={provider:n.provider,modelId:n.modelId},t=n.thinkingLevel;t5.current=t??null,el(t??"auto"),ed(void 0),t2.current=e,t4.current=null,et(null),Q(e),eR(e)}let r=tj.current??(m?await tQ.current:null);if(r)try{await sB(r,{type:"set_role_model",role:e}),m||eM({provider:n.provider,modelId:n.modelId})}catch(e){console.error("Failed to set role model:",e)}},[m,Y,Q]),nQ=(0,i.useCallback)(async()=>{let e=tj.current;if(e&&!eA){eH.current="manual",ez(!0),eW(null),e_(null);try{let t=await sB(e,{type:"compact"});e_(lu(t,"manual")),await nf(e,!0)}catch(e){eW(e instanceof Error?e.message:String(e)),e_(null)}finally{ez(!1)}}},[eA,nf]),n0=(0,i.useCallback)(async e=>{let n=r??t?.cwd??"",i=n?`/api/models?cwd=${encodeURIComponent(n)}`:"/api/models",a=await fetch(i,e?{signal:e}:void 0);if(!a.ok)throw Error(`HTTP ${a.status}`);let s=await a.json();_(s.models),B(s.modelError??null),q(s.modelScopeWarnings??[]),V(s.thinkingLevels??{}),G(s.thinkingLevelMaps??{}),Z(s.roles??[]);let l=s.modelList??[];if(O(l),m&&!tj.current){let e=(s.defaultModel?l.find(e=>e.id===s.defaultModel?.modelId&&e.provider===s.defaultModel?.provider):void 0)??l[0];er(e?{provider:e.provider,modelId:e.id}:null);let t=e&&s.thinkingLevelPins?.[`${e.provider}/${e.id}`];null===t5.current&&el(t??"auto")}},[m,r,t?.cwd]),n1=(0,i.useCallback)(async e=>{if(!e.startsWith("/"))return{handled:!1};let t=e.match(/^\/([^\s]+)(?:\s+([\s\S]*))?$/);if(!t)return{handled:!1};let[,n,r=""]=t,i=r.trim(),a=await ny(),s=e=>(e.handled&&(e.error?n$({type:"error",message:e.error}):"openSessionStats"!==e.action&&n$({type:"success",message:e.message??"Command completed"})),e);try{switch(n){case"compact":{if(!a||eA)return s({handled:!0,error:"No active session to compact"});eH.current="manual",ez(!0),eW(null),e_(null);let e=await sB(a,{type:"compact",...i?{customInstructions:i}:{}});return e_(lu(e,"manual")),await nf(a,!0)&&nb(),s({handled:!0,message:"Compacted context"})}case"reload":if(!a)return s({handled:!0,error:"No active session to reload"});return await sB(a,{type:"reload"}),await Promise.all([nf(a,!1,!0),nv(a),nw(),n0()]),s({handled:!0,message:"Reloaded session resources"});case"name":if(!a)return s({handled:!0,error:"No active session to name"});if(!i)return s({handled:!0,error:"Usage: /name <name>"});return await sB(a,{type:"set_session_name",name:i}),await nf(a)&&nb(),s({handled:!0,message:`Session renamed to ${i}`});case"session":{if(!a)return s({handled:!0,error:"No active session"});let e=await sB(a,{type:"get_session_stats"});return e&&e5(e),h?.(),s({handled:!0,action:"openSessionStats"})}case"copy":{if(!a)return s({handled:!0,error:"No active session"});let e=await sB(a,{type:"get_last_assistant_text"}),t=e?.text??"";if(!t)return s({handled:!0,error:"No assistant message to copy"});return await navigator.clipboard.writeText(t),s({handled:!0,message:"Copied last assistant message"})}case"fork":{if(!a)return s({handled:!0,error:"No active session to fork"});let e=await nV();if(!e.forked)return s({handled:!0,error:e.error??"Fork failed"});return s({handled:!0,message:"Forked a new session"})}case"goal":{if(!a)return s({handled:!0,error:"No active session"});let e=await sB(a,{type:"goal",args:i});if(tK(e?.status??null),e?.error)return s({handled:!0,error:e.error});if(e?.message&&e.message.includes("\n")){if(nR(e.message),e.prompt)return{handled:!0,prompt:e.prompt};return{handled:!0}}if(e?.prompt)return e.message&&n$({type:"success",message:e.message}),{handled:!0,prompt:e.prompt};return s({handled:!0,message:e?.message??"Command completed"})}case"handoff":if(!a)return s({handled:!0,error:"No active session"});if(tT.current||tP.current)return s({handled:!0,error:"Cannot hand off while the session is busy"});tT.current=!0,L(!0),eV({kind:"running_command"});try{await nI(a);let e=await sB(a,{type:"handoff",...i?{customInstructions:i}:{}});if(!e||e.cancelled)return s({handled:!0,error:"Handoff cancelled"});return await nf(a,!0)&&nb(),s({handled:!0,message:"컨텍스트를 현재 세션에 압축했습니다"})}finally{tT.current=!1,L(!1),eV(null),tj.current===a&&nF(a)}default:{if(!a)return s({handled:!0,error:"No active session"});let t=await sB(a,{type:"execute_slash_command",message:e});if(!t?.handled)return{handled:!1};let n=t.output?.filter(e=>e.trim()).join("\n\n")??"";if(n&&nR(n),t.prompt)return{handled:!0,prompt:t.prompt};if(n)return{handled:!0};return s({handled:!0,message:"Command completed"})}}}catch(e){return s({handled:!0,error:e instanceof Error?e.message:String(e)})}finally{"compact"===n&&ez(!1)}},[n$,nR,nI,ny,nV,eA,n0,nf,nw,nv,nb,h,nF]),n2=(0,i.useCallback)(async(t,n,r)=>{let i=tj.current;if(!i)return n$({type:"error",message:"The session is not ready yet, so the message was returned to the composer."}),e.chatInputRef?.current?.restoreSubmission?.(t,lp(n),r),"returned";let a=rg(t,r??[]),s=n?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),l=++tp.current;tu({type:"submit",id:l,kind:"steer",text:a,images:s?.length??0});try{return await sB(i,{type:"steer",message:a,...s?.length?{images:s}:{}}),tu({type:"ack",id:l}),"accepted"}catch(a){return tu({type:"fail",id:l}),console.error("Failed to steer:",a),n$({type:"error",message:a instanceof Error?a.message:String(a)}),e.chatInputRef?.current?.restoreSubmission?.(t,lp(n),r,i),"returned"}},[n$,e.chatInputRef]),n4=(0,i.useCallback)(async(t,n,r,i)=>{let a=tj.current;if(!a)return n$({type:"error",message:"The session is not ready yet, so the message was returned to the composer."}),e.chatInputRef?.current?.restoreSubmission?.(t,lp(r),i),"returned";let s=rg(t,i??[]),l=r?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),o=++tp.current;tu({type:"submit",id:o,kind:n,text:s,images:l?.length??0});try{return await sB(a,{type:"prompt",message:s,streamingBehavior:n,...l?.length?{images:l}:{}}),tu({type:"ack",id:o}),"accepted"}catch(n){return tu({type:"fail",id:o}),console.error("Failed to queue prompt:",n),n$({type:"error",message:n instanceof Error?n.message:String(n)}),e.chatInputRef?.current?.restoreSubmission?.(t,lp(r),i,a),"returned"}},[n$,e.chatInputRef]),n5=(0,i.useCallback)(async(t,n,r)=>{let i=tj.current;if(!i)return n$({type:"error",message:"The session is not ready yet, so the message was returned to the composer."}),e.chatInputRef?.current?.restoreSubmission?.(t,lp(n),r),"returned";let a=rg(t,r??[]),s=n?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),l=++tp.current;tu({type:"submit",id:l,kind:"followUp",text:a,images:s?.length??0});try{return await sB(i,{type:"follow_up",message:a,...s?.length?{images:s}:{}}),tu({type:"ack",id:l}),"accepted"}catch(a){return tu({type:"fail",id:l}),console.error("Failed to follow up:",a),n$({type:"error",message:a instanceof Error?a.message:String(a)}),e.chatInputRef?.current?.restoreSubmission?.(t,lp(n),r,i),"returned"}},[n$,e.chatInputRef]),n6=(0,i.useCallback)(async()=>{let e=tj.current;if(e)try{await sB(e,{type:"abort_compaction"})}catch(e){console.error("Failed to abort compaction:",e)}},[]),n8=(0,i.useCallback)(async()=>{let t=tj.current;if(t)try{var n;let r=await sB(t,{type:"clear_queue"});tu({type:"withdraw"}),tl({steering:[],followUp:[]});let i={text:(n=[...r?.steering??[],...r?.followUp??[]]).map(({text:e,images:t})=>t?.length&&"[Image]"===e?"":e).filter(e=>e.trim()).join("\n\n"),images:n.flatMap(({images:e})=>e??[]).map(({data:e,mimeType:t})=>({data:e,mimeType:t}))};e.chatInputRef?.current?.restoreSubmission?.(i.text,i.images.length?i.images:void 0,void 0,t)}catch(e){console.error("Failed to recall queued messages:",e),n$({type:"error",message:"Failed to recall queued messages"})}},[e.chatInputRef,n$]),n3=(0,i.useCallback)(async(e,t)=>{let n=tj.current;if(n)try{let r=await sB(n,{type:"remove_queued_message",message:t,queue:e});if(!r?.removed)return;tu({type:"withdraw",kind:"steering"===e?"steer":"followUp",text:t}),tl(n=>{let r=n[e].indexOf(t);return(r<0&&""===t.trim()&&(r=n[e].indexOf("[Image]")),r<0)?n:{...n,[e]:n[e].filter((e,t)=>t!==r)}})}catch(e){console.error("Failed to remove queued message:",e),n$({type:"error",message:"Failed to remove queued message"})}},[n$]),n7=(0,i.useCallback)(async(e,t=null)=>{let n="auto"===e?t:null,r=n!==ec;el(e),eu(n),m&&(!tj.current||t7.current===tj.current)&&(t5.current=e,t3.current=n),ed(void 0);let i=tj.current??await tQ.current;if(i)try{t7.current===i?await ny():r&&await sB(i,{type:"set_thinking_ceiling",ceiling:n}),await sB(i,{type:"set_thinking_level",level:e}),await nf(i)}catch(e){console.error("Failed to set thinking level:",e),n$({type:"error",message:"Failed to set thinking level"}),await nf(i)}},[m,nf,n$,ec,ny]);ev.current=no?`${no.provider}/${no.modelId}`:"";let n9=e=>e?`${e}|${ev.current}`:null,re=t?.id??tj.current,rt=n9(re),rn=ep&&ep.key===rt?ep.value:null;(0,i.useEffect)(()=>{let e=++eg.current;rt&&re&&!E&&!eE&&fetch(`/api/agent/${encodeURIComponent(re)}`).then(e=>e.json()).then(t=>{eg.current===e&&n9(tj.current)===rt&&eh({key:rt,value:(t.running?s3(t.state):void 0)??null})}).catch(()=>{})},[rt,E,eE]);let rr=(0,i.useCallback)(async()=>{let e=tj.current??await ny(),t=n9(tj.current);if(!e||!t)return;let n=++eg.current,r=()=>eg.current===n&&n9(tj.current)===t,i=e=>{r()&&eh({key:t,value:e})};ef(!0);try{let n=ep?.key===t?ep.value?.enabled:void 0;if(void 0===n){let t=s3(await sB(e,{type:"get_state"}));if(!t)throw Error("Could not read the session's Fast state");n=t.enabled}if(!r())return;let a=await sB(e,{type:"set_fast_mode",enabled:!n});i({enabled:a?.enabled===!0,active:a?.active===!0})}catch(t){if(!r())return;n$({type:"error",message:t instanceof Error?t.message:String(t)});try{i(s3(await sB(e,{type:"get_state"}))??null)}catch{i(null)}}finally{ef(!1)}},[ny,ep,n$]),ri=(0,i.useCallback)(async e=>{let t=(0,a7.xG)(e);ns(e);let n=tj.current??await tQ.current;if(n)try{await sB(n,{type:"set_tools",toolNames:t})}catch(e){console.error("Failed to set tools:",e)}},[ns]),ra=(0,i.useCallback)(e=>{tH.current=e,tU(t=>!e===t?t:!e)},[]);tY.current=ra;let rs=(0,i.useCallback)((e="smooth")=>{tG.current=Date.now()+700,tZ.current?.scrollIntoView({behavior:e})},[]),rl=(0,i.useCallback)(()=>{tJ.current=0,ra(!0),rs("smooth")},[rs,ra]),ro=(0,i.useCallback)(()=>{tJ.current=0,ra(!1)},[ra]),rd=(0,i.useCallback)(e=>{e instanceof KeyboardEvent&&(!ln.has(e.key)||e.target instanceof Element&&e.target.closest("input, textarea, [contenteditable='true']"))||(tJ.current=Date.now()+1200)},[]),rc=(0,i.useCallback)(()=>{if(!tT.current&&!tP.current)return;let e=tX.current;if(!e)return;let t=Date.now()<=tJ.current;!t&&Date.now()<tG.current||(e.scrollHeight-e.scrollTop-e.clientHeight<=72?ra(!0):t&&ra(!1))},[ra]);return(0,i.useEffect)(()=>(tj.current=t?.id??null,tI.current.sessionId!==tj.current&&(tI.current={sessionId:tj.current,outputs:[],seq:0}),t&&nf(t.id,!f,!0,f).then(e=>{if(tj.current!==t.id)return;nC(t.id),e?.running&&(nv(t.id),(e.state?.isStreaming||e.state?.isPromptRunning||e.state?.isHandoffRunning)&&(tM.current=!!e.state.isStreaming,t$.current=!!e.state.isPromptRunning,tT.current=!0,L(!0),eV(e.state.isStreaming?{kind:"waiting_model"}:{kind:"running_command"}),R({type:"start"}),nN(t.id),!e.state.isStreaming&&e.state.isPromptRunning&&nD(t.id)),e.state?.isBashRunning&&(tP.current=!0,z(!0),nO(t.id)),(e.state?.subagents?.length??0)>0&&nN(t.id));let n=e?.state;n&&(void 0!==n.isCompacting&&ez(n.isCompacting),eO(s7(n)),void 0!==n.contextUsage&&ek(n.contextUsage??null),void 0!==n.systemPrompt&&eC(n.systemPrompt??null),void 0!==n.thinkingLevel&&(t6.current=t.id,el(n.configuredThinkingLevel??n.thinkingLevel),ed(n.thinkingLevel)),void 0!==n.thinkingCeiling&&eu(n.thinkingCeiling??null),void 0!==n.extensionStatuses&&tr(n.extensionStatuses??[]),void 0!==n.extensionWidgets&&ta(n.extensionWidgets??[]),void 0!==n.queuedMessages&&tl(s8(n.queuedMessages)),void 0!==n.subagents&&td(e=>s5(e,n.subagents??[])),void 0!==n.goal&&tK(n.goal??null)),e&&eU(!0)}),()=>{tW.current+=1,nk(),nj(),nS()}),[t?.id]),(0,i.useEffect)(()=>{p?.(eS)},[eS,p]),(0,i.useEffect)(()=>{u&&u(g?.tree??[],k,nG)},[g?.tree,k,nG,u]),(0,i.useEffect)(()=>(window.addEventListener("keydown",rd),()=>{window.removeEventListener("keydown",rd)}),[rd]),(0,i.useEffect)(()=>{let e=tX.current;if(e)return e.addEventListener("pointerdown",rd,{passive:!0}),e.addEventListener("wheel",rd,{passive:!0}),e.addEventListener("touchstart",rd,{passive:!0}),e.addEventListener("scroll",rc,{passive:!0}),()=>{e.removeEventListener("pointerdown",rd),e.removeEventListener("wheel",rd),e.removeEventListener("touchstart",rd),e.removeEventListener("scroll",rc)}},[S.length,v,rc,rd]),(0,i.useEffect)(()=>{if(t9.current||!E&&!A||!tH.current)return;let e=tX.current;if(!e)return;let t=requestAnimationFrame(()=>{tG.current=Date.now()+700,e.scrollTo({top:e.scrollHeight,behavior:"instant"})});return()=>cancelAnimationFrame(t)},[E,A,S.length,$.streamingMessage,eK,P,e.transitioning]),(0,i.useLayoutEffect)(()=>{if(0!==S.length){if(!tO.current){tO.current=!0,rs("instant");return}if(!t9.current&&tH.current){let e=Date.now()-ne.current<1500;rs(tT.current||tP.current||e?"instant":"smooth")}}},[S.length,E,A,rs,e.transitioning]),(0,i.useEffect)(()=>{let e=new AbortController;return n0(e.signal).catch(e=>{if(e instanceof DOMException&&"AbortError"===e.name)return}),()=>e.abort()},[n0,c]),(0,i.useEffect)(()=>{if(!eF)return;let e=setTimeout(()=>e_(null),6e3);return()=>clearTimeout(e)},[eF]),(0,i.useEffect)(()=>{if(0===e1.visible.length)return;let e=e1.visible.find(e=>e.exiting);if(e){let t=setTimeout(()=>{e2({type:"remove",id:e.id})},180);return()=>clearTimeout(t)}if(!e1.visible[0])return;let t=setTimeout(()=>{e2({type:"mark_oldest_exiting"})},5e3);return()=>clearTimeout(t)},[e1.visible]),(0,i.useEffect)(()=>{e5(null)},[S.length,ew?.tokens,ew?.percent,ew?.contextWindow]),{data:g,loading:v,error:y,activeLeafId:k,messages:S,entryIds:N,streamState:$,agentRunning:E,modelNames:F,modelList:D,modelError:H,modelScopeWarnings:U,modelThinkingLevels:K,modelThinkingLevelMaps:J,modelRoles:Y,newSessionModel:X,toolPreset:ei,thinkingLevel:es,effectiveThinkingLevel:eo,thinkingCeiling:ec,retryInfo:eb,contextUsage:ew,systemPrompt:eS,forkingEntryId:eN,isCompacting:eA,compaction:eD,compactError:eP,compactResult:eF,currentModel:nl,displayModel:no,modelSwitching:eE,sessionStats:nd,runStateKnown:eB,slashCommands:eZ,slashCommandsLoading:eQ,queuedMessages:ts,deliveryRows:th,subagents:to,todoPhases:tm&&tm.sid===tj.current?tm.phases:null,compactedWork:T,notices:e1.visible,extensionDialog:e6,extensionResponse:e3,extensionCustomUi:te,extensionStatuses:tn,extensionWidgets:ti,respondToExtensionUi:nT,sendExtensionCustomInput:nM,isAutoModelSelection:m&&null===X,agentPhase:eK,isNew:m,autoFollowPaused:tB,resumeAutoFollow:rl,pauseAutoFollow:ro,goalStatus:tq,sessionIdRef:tj,eventSourceRef:tg,messagesEndRef:tZ,scrollContainerRef:tX,handleSend:nq,handleAbort:nK,handleFork:nV,handleNavigate:nJ,handleModelChange:nY,handleRoleModelChange:nX,handleMainPresetChange:nZ,newSessionAccount:ee,handleCompact:nQ,handleSteer:n2,handleFollowUp:n5,handlePromptWithStreamingBehavior:n4,handleAbortCompaction:n6,handleRecallQueue:n8,handleRemoveQueuedMessage:n3,handleBuiltinSlashCommand:n1,handleToolPresetChange:ri,handleThinkingLevelChange:n7,fastMode:rn,fastModeBusy:em,handleFastModeToggle:rr,loadTools:nv,loadSlashCommands:nw,ensureNewSession:ny,refreshLiveTranscript:ng,setActiveLeafId:j,setData:x,setMessages:C,dispatch:R,setAgentRunning:L,setForkingEntryId:eI,bashRunning:A,pendingBash:P,handleAgentEventRef:tF}}({session:e,newSessionCwd:t,initialData:a,transitioning:s,onAgentEnd:eb,onAttentionNeeded:o,onSessionCreated:d,onSessionForked:c,modelsRefreshKey:u,chatInputRef:p,onBranchDataChange:h,onSystemPromptChange:m,onSessionStatsPanelOpen:g}),tG=nm(e?.id,te?.provider,void 0),tY=tG?.alias;(0,i.useEffect)(()=>{tY&&Q.current?.(tY)},[tY]);let tZ=(0,i.useMemo)(()=>{if(!te)return null;let e=ty?tz:nt.bo.find(e=>e.alias===tG?.alias)?.oauthPosition;return nt.bo.find(t=>t.provider===te.provider&&(void 0===t.oauthPosition||t.oauthPosition===e))?.alias??null},[te,ty,tz,tG]),tX=te?.provider,tQ=te?.modelId,t0=tG?.alias,t1=tG?.seed,t2=(0,i.useRef)(tG);t2.current=tG,(0,i.useEffect)(()=>{y&&y(tX&&tQ?{provider:tX,modelId:tQ,face:t2.current,presetAlias:tZ,isNew:ty}:null)},[y,tX,tQ,t0,t1,tZ,ty]),(0,i.useEffect)(()=>()=>{y?.(null)},[y]);let t4=eI||eT,t5=e?.id;ei.current=eS,ea.current=eC,es.current=tC;let t6=(0,i.useRef)(!0);t6.current=!tw;let t8=(0,i.useRef)(!1);(0,i.useEffect)(()=>{eI&&!t8.current&&(el.current+=1),t8.current=eI},[eI]),(0,i.useEffect)(()=>()=>{el.current+=1},[]),(0,i.useEffect)(()=>{et(e=>[...function(e){if(!e)return[];try{let t=JSON.parse(window.localStorage.getItem(lN(e))??"[]");if(!Array.isArray(t))return[];return t.filter(e=>e&&"string"==typeof e.anchorEntryId).map(t=>({..."string"==typeof t.sticker?{...t,sticker:t.sticker.replace(/^(\/stickers\/.+)\.png$/,"$1.webp")}:t,sessionId:e}))}catch{return[]}}(t5),...e.filter(e=>null===e.anchorEntryId&&e.sessionId===t5)])},[t5]),(0,i.useEffect)(()=>{let e=tC.current;e&&en.current.some(t=>null===t.anchorEntryId&&t.sessionId===e)&&et(t=>{let n=!1,r=[];for(let i of t){if(null!==i.anchorEntryId||!i.intent||i.sessionId!==e){r.push(i);continue}let a=function(e,t,n){let r=Math.min(t.length,n.length),i=0;if(null!==e.baseEntryId){let t=n.indexOf(e.baseEntryId);if(-1===t||t>=r)return{kind:"drop"};i=t+1}let a=0;for(let s=i;s<r;s++)if(iL(t[s])===e.identity&&(a+=1)===e.occurrence)return{kind:"entry",entryId:n[s]};return null}(i.intent,eS,eC);if(null===a){r.push(i);continue}n=!0,"drop"!==a.kind&&("working"===i.tag&&[...t,...r].some(e=>"working"===e.tag&&e.anchorEntryId===a.entryId)||r.push({id:i.id,anchorEntryId:a.entryId,sticker:i.sticker,text:i.text,tag:i.tag,sessionId:i.sessionId}))}return n?(lI(e,r),r):t})},[eS,eC,tC]);let t3=(0,i.useRef)(null);(0,i.useEffect)(()=>{let e=tC.current,t=t3.current;if(t3.current=e?{sessionId:e,entryIds:eC}:null,!e||!t||t.sessionId!==e)return;let n=function(e,t,n){if(0===e.length||t.length<=e.length)return[];for(let n=0;n<e.length;n++)if(e[n]!==t[n])return[];let r=[],i=Math.min(n.length,t.length);for(let a=e.length;a<i;a++){let e=n[a];"assistant"===e.role&&"web6"===e.provider&&e.model===iz&&r.push(t[a])}return r}(t.entryIds,eC,eS),r=ec();if(0===n.length||!r)return;let i=np(e,"web6",void 0)?.alias??null;for(let e of n)en.current.some(t=>t.anchorEntryId===e)||eh(i,"done",r,{kind:"entry",entryId:e})},[eC,eS,tC,ec,eh]);let t7=eI&&tb?.kind==="running_tools"&&tb.tools.length>0&&tb.tools.every(e=>"wait"===e.name),nn=ew||s,{hideThinkingBlock:nr}=(O=t??e?.cwd??null,B=ne(),(0,i.useEffect)(()=>{t9(O).catch(()=>{})},[O]),B),ni=(0,i.useMemo)(()=>({hideThinking:nr}),[nr]);(0,i.useEffect)(()=>{var e;if(!tu||X.current===tu.id)return;X.current=tu.id;let t=ec();if(!t)return;ed.current=t.turn;let n=eN.streamingMessage?.role==="assistant"?eN.streamingMessage:null,r=iA(ei.current,n,te?.provider);ef("select"===(e=tu.method)||"ask"===e?"choice":"approval",t,r.provider,r.credentialId)},[tu,eN.streamingMessage,te?.provider,ec,ef]),(0,i.useEffect)(()=>(v=t4?tM:null,()=>void(v=null)),[t4,tM]),(0,i.useEffect)(()=>{T?.(t4)},[T,t4]),(0,i.useEffect)(()=>()=>T?.(!1),[T]),(0,i.useEffect)(()=>{M?.(t7)},[t7,M]),(0,i.useEffect)(()=>()=>M?.(!1),[M]),(0,i.useEffect)(()=>{$?.(null!==tu)},[$,tu]),(0,i.useEffect)(()=>()=>$?.(!1),[$]);let{main:na,process:ns}=(0,i.useMemo)(()=>(function(e,t,n={}){let r=[],i=[],a=-1,s=null,l=(e,t,n)=>{if(0===t.length)return;let a=(s&&s.anchorIdx===e||(s={anchorIdx:e,entries:[],messageCount:0,toolCallCount:0},i.push(s)),s),l=r.length-1;for(let e of t)a.entries.push({...e,afterMainIndex:l});a.messageCount+=t.length,a.toolCallCount+=n},o=eH(e),d=new Map,c=(e,t)=>{let n=d.get(e)??0;d.set(e,n+1),r.push({kind:"answer",anchorIdx:a,idx:e,runIndex:n,blocks:o.attach(t),precedingBlocks:[]})},u=()=>{let e=o.takeRemaining();e&&c(e.idx,e.blocks)};for(let i of t){if("answer"===i.kind){r.push(i);continue}if("process"===i.kind){l(i.anchorIdx,i.entries,i.toolCallCount);continue}let t=e[i.idx];if(!t)continue;if("user"===t.role){u(),a=i.idx,r.push(i);continue}if(eV(t)){r.push(void 0!==i.anchorIdx||a<0?i:{...i,anchorIdx:a});continue}if("assistant"!==t.role){"toolResult"!==t.role&&l(a,[{idx:i.idx}],0);continue}let s=eF(t,n),d=!1;for(let e of s){if("answer"===e.kind){c(i.idx,e.blocks),d=!0;continue}l(a,[{idx:i.idx,blocks:e.blocks}],e_(e.blocks)),o.collect(i.idx,e.blocks)}!d&&eW(t,n)&&c(i.idx,[])}return u(),{main:r,process:i}})(eS,function(e,t={}){let n=-1;for(let t=e.length-1;t>=0;t--)if(eZ(e[t])){n=t;break}let r=[];for(let i=0;i<e.length;){if(!eZ(e[i])){r.push({kind:"message",idx:i}),i+=1;continue}let a=i,s=a+1;for(;s<e.length&&!eZ(e[s]);)s+=1;if((t.sessionBusy||t.isStreaming)&&s===e.length&&a===n||!function(e,t,n){for(let r=t;r<n;r++)if(e[r]?.role==="assistant")return!0;return!1}(e,a+1,s)){for(let e=a;e<s;e++)r.push({kind:"message",idx:e});i=s;continue}for(let n of(r.push({kind:"message",idx:a}),function(e,t,n,r){let i=[],a=[],s=0,l=[],o=0,d=0,c=eH(e.slice(t+1,n)),u=()=>{0!==a.length&&(i.push({kind:"process",anchorIdx:t,idx:a[0].idx,groupIndex:d++,entries:a,messageCount:a.length,toolCallCount:s,turnHasAnswer:!1}),a=[],s=0)},p=(e,n)=>{u(),i.push({kind:"answer",anchorIdx:t,idx:e,runIndex:o++,blocks:c.attach(n),precedingBlocks:l}),l=[]};for(let o=t+1;o<n;o++){let n=e[o];if("assistant"!==n.role){if(eV(n)){u(),i.push({kind:"message",idx:o,anchorIdx:t});continue}"toolResult"!==n.role&&a.push({idx:o});continue}let d=eF(n,r),h=d.reduce((e,t)=>"answer"===t.kind?e+1:e,0);for(let e of d){if("answer"===e.kind){p(o,e.blocks);continue}for(let t of(a.push(h>0?{idx:o,blocks:e.blocks}:{idx:o}),s+=e_(e.blocks),c.collect(o,e.blocks),e.blocks))l.push(t)}0===h&&eW(n,r)&&p(o,[])}u();let h=c.takeRemaining();h&&i.push({kind:"answer",anchorIdx:t,idx:h.idx,runIndex:o++,blocks:h.blocks,precedingBlocks:[]});let m=i.some(e=>"answer"===e.kind);for(let e of i)"process"===e.kind&&(e.turnHasAnswer=m);return i}(e,a,s,{hideThinking:t.hideThinking})))r.push(n);i=s}return r}(eS,{sessionBusy:t4,isStreaming:eN.isStreaming,hideThinking:ni.hideThinking}),ni),[eS,t4,eN.isStreaming,ni]),nl=(0,i.useMemo)(()=>(function(e,t,n=[]){let r=new Map,i=e.map((e,t)=>({item:e,position:t})).filter(e=>"answer"===e.item.kind);if(0===i.length)return r;let a=-1,s=-1;t.forEach((e,t)=>{let n=nD(e);if(n.length>0){let e=i.filter(e=>e.item.anchorIdx===a||e.item.anchorIdx===s),l=e.filter(e=>e.item.idx<=t).pop(),o=l??e.find(e=>e.item.idx>t);if(o){let e=r.get(o.position);e?e.calls.push(...n):r.set(o.position,{calls:[...n],placement:l?"after":"before"})}}"user"===e.role&&(a=t),eZ(e)&&(s=t)});let{continuing:l}=nO(e,t,n);if(l){let e=r.get(l.position);e?e.calls.unshift(...l.calls):r.set(l.position,{calls:l.calls,placement:"before"})}return r})(na,eS,ti?.messages),[na,eS,ti]),no=(0,i.useMemo)(()=>(function(e,t,n=[]){let{atCompaction:r}=nO(e,t,n);if(0===r.length)return null;let i=-1;t.forEach((e,t)=>{"custom"===e.role&&"compaction"===e.customType&&(i=t)});let a=e.findIndex(e=>e.idx>i),s=-1===a?e.length:a;return{position:s,jumpTo:s<e.length?s:e.length>0?e.length-1:null,calls:r}})(na,eS,ti?.messages),[na,eS,ti]),[nd,nc]=(0,i.useState)(lw),{startIndex:nu,endIndex:nf,hasLater:ng}=lk(na.length,nd),nx=null!==nd.end&&ng,nv=(0,i.useRef)(na.length);nv.current=na.length;let nb=(0,i.useRef)(null),ny=(0,i.useRef)(null),nw=(0,i.useRef)(null);(0,i.useEffect)(()=>{null!==nd.end&&nd.end>=na.length&&nc(e=>({count:e.count,end:null}))},[nd.end,na.length]),(0,i.useEffect)(()=>{let e=nb.current,t=tI.current;if(!e||!t)return;let n=new IntersectionObserver(e=>{e[0]?.isIntersecting&&(nw.current=t.scrollHeight-t.scrollTop,nc(e=>(function(e,t=50){return{...e,count:e.count+t}})(e)))},{root:t,threshold:0});return n.observe(e),()=>n.disconnect()},[nd,na.length,tI]),(0,i.useEffect)(()=>{if(null==nw.current)return;let e=tI.current;if(e){var t;t=e.scrollHeight,e.scrollTop=Math.max(0,t-nw.current),nw.current=null}},[nd.count,tI]),(0,i.useEffect)(()=>{let e=ny.current,t=tI.current;if(!e||!t)return;let n=new IntersectionObserver(e=>{e[0]?.isIntersecting&&nc(e=>(function(e,t,n=50){if(null===t.end)return t;let{startIndex:r,endIndex:i}=lk(e,t),a=i+n;return a>=e?{count:e-r,end:null}:{count:a-r,end:a}})(nv.current,e))},{root:t,threshold:0});return n.observe(e),()=>n.disconnect()},[nd,na.length,tI]);let[nk,nj]=(0,i.useState)(null),[nS,nC]=(0,i.useState)(null),[nN,nI]=(0,i.useState)(0),nT=(0,i.useRef)(null),nM=(0,i.useCallback)((e,t=null)=>{tj(),nT.current={item:e,dispatchKey:t},nj(null),nC(null),nc(t=>lj(nv.current,e,t)),nI(e=>e+1)},[tj]);(0,i.useLayoutEffect)(()=>{let e,t=nT.current,n=tI.current;if(null===t||!n)return;let r=n.querySelector(`[data-chat-item="${t.item}"]`);if(!r)return;nT.current=null;let i=t.dispatchKey?r.querySelector(".answer-dispatch"):null;if(i)e=i.getBoundingClientRect().top;else{let t=document.createRange();t.selectNodeContents(r),e=t.getBoundingClientRect().top}n.scrollTop+=e-n.getBoundingClientRect().top-24,i&&t.dispatchKey?nC(t.dispatchKey):nj(t.item)},[nN,nd,na,tI]),(0,i.useEffect)(()=>{if(null===nk)return;let e=setTimeout(()=>nj(null),1800);return()=>clearTimeout(e)},[nk]),(0,i.useEffect)(()=>{if(null===nS)return;let e=setTimeout(()=>nC(null),1800);return()=>clearTimeout(e)},[nS]);let n$=(0,i.useCallback)(()=>{(0,F.flushSync)(()=>nc(lw));let e=tI.current;e&&(e.scrollTop=e.scrollHeight)},[tI]),nF=(0,i.useCallback)(()=>{nx&&n$(),tk()},[nx,n$,tk]),nB=(0,i.useRef)(null),[nU,nq]=(0,i.useState)(!1);(0,i.useEffect)(()=>{if(!_||nB.current===_.id||_.sessionId!==e?.id||ew||0===eS.length)return;nB.current=_.id,D?.(_.id);let t=eC.indexOf(_.entryId);if(t<0)return void nq(!0);let n=0;for(let e=0;e<na.length;e++){let r=na[e].idx;if(r>t||(n=e,r===t))break}nM(n)},[_,e?.id,ew,eS.length,eC,na,nM,D]),(0,i.useEffect)(()=>{if(!nU)return;let e=setTimeout(()=>nq(!1),6e3);return()=>clearTimeout(e)},[nU]);let[nV,nJ]=(0,i.useState)(!1),[nG,nY]=(0,i.useState)(0),nZ=(0,i.useMemo)(()=>nV?na.map(e=>(function(e,t){if("answer"===e.kind)return e0(e.blocks);let n=t[e.idx];return n&&"content"in n?e0(n.content):""})(e,eS).toLowerCase()):lT,[nV,na,eS]),nX=(0,i.useCallback)(e=>{tj(),nc(t=>lj(nv.current,e,t))},[tj]),nQ=(0,i.useCallback)(()=>nJ(!1),[]);(0,i.useEffect)(()=>{let e=e=>{if(e.defaultPrevented||e.isComposing||e.altKey||e.shiftKey||!(e.ctrlKey||e.metaKey)||"f"!==e.key.toLowerCase())return;let t=tI.current;if(!t||!t.checkVisibility({visibilityProperty:!0}))return;let n=e.target instanceof Element?e.target:null;if(n?.closest("[data-capture-keys], [role='dialog']"))return;let r=n?.closest("input, textarea, select, [contenteditable='true']");(!r||r.closest("[data-chat-composer], .chat-find-bar"))&&(e.preventDefault(),nJ(!0),nY(e=>e+1))};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[tI]);let n0=(0,i.useMemo)(()=>{let e=[];return na.forEach((t,n)=>{if("message"!==t.kind)return;let r=lC(eS[t.idx]);null!==r&&e.push({item:n,text:r})}),e},[na,eS]),n1=`${nu}:${nf}`,n2=eC.length>0?eC[eC.length-1]:null,[n4,n5]=(0,i.useState)(null),n6=(0,i.useRef)(!1);(0,i.useEffect)(()=>{n6.current||!tr||ew||!e?.id||(n6.current=!0,t4||!n2||!function(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if("user"===n.role||"toolResult"===n.role)return!0;if("assistant"===n.role){if(!n.stopReason)return!0;if("aborted"===n.stopReason||"error"===n.stopReason||"length"===n.stopReason)break;return n.content.some(e=>"toolCall"===e.type)}}return!1}(eS)||function(e){try{return window.localStorage.getItem(lM(e))}catch{return null}}(e.id)!==n2&&n5(n2))},[tr,ew,e?.id,t4,n2,eS]);let n8=(0,i.useCallback)(()=>{e?.id&&n4&&function(e,t){try{window.localStorage.setItem(lM(e),t)}catch{}}(e.id,n4),n5(null)},[e?.id,n4]),n3=null!==n4&&n4===n2&&!t4&&!nx,n7=tn?[tn.sessionId,tn.sessionFile??"",tn.sessionName??"",tn.userMessages,tn.assistantMessages,tn.toolCalls,tn.toolResults,tn.totalMessages,tn.tokens.input,tn.tokens.output,tn.tokens.cacheRead,tn.tokens.cacheWrite,tn.tokens.total,tn.cost??0,tn.totalActiveMs??0].join("|"):null,n9=(0,i.useRef)(tn);n9.current=tn,(0,i.useEffect)(()=>{f?.(n9.current)},[n7,f]),(0,i.useEffect)(()=>()=>{f?.(null)},[f]);let re=e4?`${e4.percent??"null"}|${e4.contextWindow}|${e4.tokens??"null"}`:null,rt=(0,i.useRef)(e4);rt.current=e4,(0,i.useEffect)(()=>{x?.(rt.current)},[re,x]),(0,i.useEffect)(()=>()=>{x?.(null)},[x]),(0,i.useEffect)(()=>{b?.(to)},[b,to]),(0,i.useEffect)(()=>()=>{b?.([])},[b]);let{isDragOver:rn,handleDragEnter:rr,handleDragOver:ri,handleDragLeave:ra,handleDrop:rs}=function(e){let[t,n]=(0,i.useState)(!1),r=(0,i.useRef)(0),a=(0,i.useCallback)(e=>{Array.from(e.dataTransfer.items).some(e=>"file"===e.kind)&&(e.preventDefault(),r.current+=1,n(!0))},[]),s=(0,i.useCallback)(e=>{Array.from(e.dataTransfer.items).some(e=>"file"===e.kind)&&e.preventDefault()},[]);return{isDragOver:t,handleDragEnter:a,handleDragOver:s,handleDragLeave:(0,i.useCallback)(()=>{r.current-=1,r.current<=0&&(r.current=0,n(!1))},[]),handleDrop:(0,i.useCallback)(t=>{t.preventDefault(),r.current=0,n(!1),e(Array.from(t.dataTransfer.files))},[e])}}((0,i.useCallback)(e=>{t4||p?.current?.addAttachments(e)},[t4,p])),rl=(0,i.useMemo)(()=>{var e;return e=ti?.messages,e&&e.length>0?[...e,...eS]:eS},[ti,eS]),ro=(0,i.useMemo)(()=>{let e=new Map;for(let t of rl)"toolResult"===t.role&&e.set(t.toolCallId,t);return e},[rl]),rd=(0,i.useMemo)(()=>{let e,t,n,r;return e=new Map,t=new Map,n=new Map,r=(e,r,i)=>{let a=n.get(e);a&&r&&t.set(a,{status:r,order:i})},rl.forEach((t,i)=>{if("assistant"===t.role){for(let e of t.content??[]){if("toolCall"!==e.type||"task"!==e.toolName)continue;let t=ro.get(e.toolCallId);if(t)for(let r of nz(e,t)??[])n.set(r.agentId,r.key)}return}if("toolResult"===t.role){if("routing_verdict"===t.toolName){let n=function(e){let t=function(e){if(e.isError)return null;let t=e.details?.record;if("object"!=typeof t||null===t)try{let n=JSON.parse(nA(e.content));t=n?.ok===!0?n.record:void 0}catch{return null}return"object"==typeof t&&null!==t?t:null}(e);if(!t)return null;let n=t.verdict;if("accepted"!==n&&"rework"!==n&&"held"!==n)return null;let r=nE(t.assignmentId),i=r?.split("#")??[];if(i.length<3)return null;let a=i[i.length-1],s=i.slice(1,-1).join("#");return/^\d+$/.test(a)&&s?{key:`${s}#${a}`,record:{verdict:n,attempt:"number"==typeof t.attempt?t.attempt:null,reason:nE(t.reason)}}:null}(t);if(!n)return;let r=e.get(n.key)??[];r.push({...n.record,order:i}),e.set(n.key,r);return}if("wait"===t.toolName)for(let e of nR(t.details?.jobs)){if("task"!==e.type)continue;let t=nE(e.id);t&&r(t,nL(e.status),i)}return}if("custom"===t.role&&"async-result"===t.customType)for(let e of nA(t.content).matchAll(nP)){let t=Object.fromEntries([...e[1].matchAll(nW)].map(e=>[e[1],e[2]]));t.id&&r(t.id,nL(t.status),i)}}),{verdicts:e,runs:t,latestByAgent:n}},[rl,ro]),rc=(0,i.useMemo)(()=>({ledger:rd,subagents:to,toolResults:ro,onOpenPanel:w,focusedDispatch:nS,sessionId:e?.id??null,onOpenMaker:k,selectedMaker:j}),[rd,to,ro,w,nS,e?.id,k,j]),ru=(0,i.useMemo)(()=>(function(e,t,n,r,i,a,s=null){let l=-1;e.forEach((e,t)=>{"user"===e.role&&(l=t)});let o=new Map;for(let[e,t]of n)for(let n of t.calls)o.set(n.toolCallId,e);if(s?.jumpTo!=null)for(let e of s.calls)o.set(e.toolCallId,s.jumpTo);let d=[];if(e.forEach((e,n)=>{if("assistant"!==e.role)return;let s=n>l;for(let n of e.content??[])if("toolCall"===n.type&&"task"===n.toolName)for(let e of nz(n,t.get(n.toolCallId))??[]){let t=n_(e,r,i),l=nH[t.run],c=null;"running"===l&&("live"===t.runSource||s&&a)?c="running":"awaiting"===l&&s&&!t.verdict&&(c="awaiting"),c&&d.push({maker:t,phase:c,position:o.get(n.toolCallId)??null})}}),0===d.length)return null;let c=0;for(let e of d)"running"===e.phase&&(c+=1);let u=d.filter(e=>null!==e.position);return{running:c,awaiting:d.length-c,target:u.length>0?u[u.length-1]:d[d.length-1]}})(rl,ro,nl,to,rd,t4,no),[rl,ro,nl,to,rd,t4,no]),rp=(0,i.useMemo)(()=>w?()=>w("subagents"):void 0,[w]),rh=(0,i.useMemo)(()=>{let e=new Set,t=[];for(let n=eS.length-1;n>=0;n-=1){let r=lC(eS[n]);if(!(!r||e.has(r))&&(e.add(r),t.push(r),t.length>=50))break}return t.reverse()},[eS]),rm=(0,i.useMemo)(()=>e7(eS,ro,td,ti?.todoPhases??null),[eS,ro,td,ti]),rf=(0,i.useMemo)(()=>iK(eN.streamingMessage).join("|"),[eN.streamingMessage]),rx=(0,i.useMemo)(()=>JSON.stringify(iq(eN.streamingMessage)),[eN.streamingMessage]),rv=(0,i.useMemo)(()=>JSON.stringify(iJ(eN.streamingMessage)),[eN.streamingMessage]),rb=(0,i.useMemo)(()=>(function(e,t,n=[],r=[],i=[]){let a=function(e){let t=new Map;for(let n of e){if("toolResult"!==n.role||"write"!==n.toolName)continue;let e=n.details;if(!e||"object"!=typeof e||Array.isArray(e))continue;let r=e.message;if(!r||"object"!=typeof r||Array.isArray(r)||"send"!==r.op)continue;let i=Array.isArray(r.receipts)?r.receipts.filter(e=>"object"==typeof e&&null!==e&&!Array.isArray(e)).map(e=>({to:"string"==typeof e.to?e.to:void 0,outcome:"string"==typeof e.outcome?e.outcome:void 0})):void 0;t.set(n.toolCallId,{from:"string"==typeof r.from?r.from:void 0,receipts:i})}return t}(e),s=[],l=new Map,o=-1;for(let n=0;n<e.length;n+=1){let r=e[n];if("user"===r.role){o=n;continue}let i=iK(r),d=iJ(r,a);if(0===i.length&&0===d.length||o<0)continue;let c=iq(r),u=l.get(o);u||(u={index:o,entryId:t[o],taskToolCallIds:[],characterSummons:[],peerSends:[]},l.set(o,u),s.push(u)),u.taskToolCallIds=[...u.taskToolCallIds,...i],u.characterSummons=[...u.characterSummons,...c],u.peerSends=[...u.peerSends,...d]}if(n.length>0||i.length>0){let a=-1;for(let t=e.length-1;t>=0;t-=1)if("user"===e[t].role){a=t;break}if(a>=0){let e=l.get(a);e||(e={index:a,entryId:t[a],taskToolCallIds:[],characterSummons:[],peerSends:[]},l.set(a,e),s.push(e));let o=new Set(e.taskToolCallIds);e.taskToolCallIds=[...e.taskToolCallIds,...n.filter(e=>!o.has(e))];let d=new Set(e.characterSummons.map(e=>`${e.toolCallId} ${e.name??""}`));e.characterSummons=[...e.characterSummons,...r.filter(e=>!d.has(`${e.toolCallId} ${e.name??""}`))];let c=new Set(e.peerSends.map(e=>e.toolCallId));e.peerSends=[...e.peerSends,...i.filter(e=>!c.has(e.toolCallId))]}}return s.sort((e,t)=>e.index-t.index)})(eS,eC,rf.length>0?rf.split("|"):[],JSON.parse(rx),JSON.parse(rv)),[eS,eC,rf,rx,rv]),ry=e?.id??tC.current??void 0,rw=(U=iY(H=(0,i.useMemo)(()=>({sessionId:ry,sessionProvider:te?.provider,turns:rb,messages:eS,subagents:to}),[ry,te?.provider,rb,eS,to])),q=i0(H),(0,i.useMemo)(()=>(function(e){let t=new Map;for(let n of e){let e=t.get(n.turnIndex);e?e.push(n):t.set(n.turnIndex,[n])}return t})(function(e){let t=[];for(let n of e){let e=t[t.length-1];if(e&&e.speakerId===n.speakerId&&e.turnIndex===n.turnIndex&&e.text===n.text){t[t.length-1]=n;continue}t.push(n)}return t}([...U,...q])),[U,q])),rk=ty&&0===eS.length&&!eN.isStreaming&&!t4,rj=e?.cwd??t??void 0,rS=te?eA[`${te.provider}:${te.modelId}`]??null:null,rC=te?eP[`${te.provider}:${te.modelId}`]??null:null,rN=(0,i.useRef)(null),rI=(0,i.useRef)(null),rT=(0,i.useCallback)(()=>{rN.current?.querySelector("textarea")?.focus({preventScroll:!0})},[]);(0,i.useEffect)(()=>(I?.(rT),()=>I?.(null)),[rT,I]),(0,i.useLayoutEffect)(()=>{let e=rI.current,t=e?.closest(".workspace-shell");if(!e||!t)return;let n=tI.current?.clientHeight??0,r=()=>{let r=Math.ceil(e.getBoundingClientRect().height);r>0&&t.style.setProperty("--omp-dock-h",`${r}px`);let i=tI.current;if(!i)return;let a=n-i.clientHeight;n=i.clientHeight,a<=0||i.scrollHeight-i.scrollTop-i.clientHeight-a<=1&&(i.scrollTop+=a)};r();let i=new ResizeObserver(r);return i.observe(e),()=>i.disconnect()},[ew,tI]);let rM=(0,i.useCallback)((...e)=>(null!==nd.end&&n$(),tT(...e)),[tT,nd.end,n$]),r$=(0,r.jsx)("div",{ref:rN,"data-chat-composer":"",style:{display:"contents"},children:(0,r.jsx)(sz,{ref:p,sessionId:e?.id??tC.current??void 0,onEnsureSession:ty&&t?tV:void 0,onLiveTranscriptPersisted:tJ,onSend:rM,onAbort:tM,onSteer:eI?tW:void 0,onFollowUp:eI?tF:void 0,onPromptWithStreamingBehavior:eI?t_:void 0,isStreaming:t4,model:te,isAutoModelSelection:tv,modelNames:e$,modelList:eR,modelError:eE,modelScopeWarnings:eL,onModelChange:tE,onMainPresetChange:e||ty?tA:void 0,mainPresetActiveAlias:tZ,modelRoles:eD,onRoleModelChange:tL,modelSwitching:tt,onCompact:e||ty?tP:void 0,onAbortCompaction:tD,isCompacting:e6,compactError:e3,compactResult:e9,toolPreset:eO,onToolPresetChange:e||ty?tU:void 0,thinkingLevel:eB,effectiveThinkingLevel:eU,thinkingCeiling:eK,onThinkingLevelChange:e||ty?tq:void 0,fastMode:eX,fastModeBusy:eQ,onFastModeToggle:e||ty?e1:void 0,availableThinkingLevels:rS,thinkingLevelMap:rC,retryInfo:e2,deliveryRows:tl,inputHistory:rh,onRecallQueue:tO,onRemoveQueuedMessage:tH,slashCommands:ta,slashCommandsLoading:ts,onLoadSlashCommands:tK,onBuiltinCommand:tB,soundEnabled:E,onSoundToggle:L,onAudioUnlock:P,draftKey:e?.id??(t?`new:${t}`:void 0),cwd:e?.cwd??t})}),rR=eN.streamingMessage,rE=(0,i.useMemo)(()=>rR?eF(rR,{isStreaming:!0}):[],[rR]),rL=(0,i.useMemo)(()=>rE.filter(e=>"answer"===e.kind).flatMap(e=>e.blocks),[rE]),rA=(0,i.useMemo)(()=>rE.filter(e=>"answer"!==e.kind).map(e=>e.blocks),[rE]),rz=rR?.role==="assistant"?rR:null,rP=eI&&(tb?.kind==="running_tools"||(rz?.content??[]).some(e=>"text"===e.type&&/\S/.test(e.text)||"toolCall"===e.type)),rW=iA(eS,rz,te?.provider),rF=rW.provider,r_=rW.credentialId;(0,i.useEffect)(()=>{if(!rP)return;let e=ec();e&&eo.current!==e.turn&&ed.current!==e.turn&&(eo.current=e.turn,ef("working",e,rF,r_))},[rP,rF,r_,ec,ef]);let[rD,rH]=(0,i.useState)(null),rB=(0,i.useCallback)(e=>{rH(e)},[]),rU=(0,i.useMemo)(()=>eM?{role:"bashExecution",command:eM.command,output:"",excludeFromContext:eM.excludeFromContext}:null,[eM]),rq=(0,i.useMemo)(()=>{let e=[eI&&!rR&&tb?function(e,t){if(e?.kind==="running_tools"){let n=e.tools.map(e=>e.name);return 0===n.length?t("chat.runningTool"):1===n.length?t("chat.runningNamedTool",{name:n[0]}):n.length<=3?t("chat.runningTools",{names:n.join(", ")}):t("chat.runningToolsMore",{names:n.slice(0,2).join(", "),count:n.length-2})}return e?.kind==="waiting_model"?t("chat.waitingModel"):e?.kind==="running_command"?t("chat.runningCommand"):null}(tb,K):null,eT&&!eM?K("chat.runningCommand"):null].filter(e=>!!e);return e.length>0?e.join(" \xb7 "):null},[eI,rR,tb,eT,eM,K]);(0,i.useEffect)(()=>{if(!rD)return void S?.(null);let e=[],t=[],n=0;if(rR&&rA.length>0){let r=rD.messages.length+e.length;for(let i of(e.push(rR),rA))t.push({idx:r,blocks:i}),n+=e_(i)}if(rU&&(t.push({idx:rD.messages.length+e.length}),e.push(rU)),0===t.length)return void S?.(rq?{...rD,status:rq}:rD);let r=-1;for(let e=rD.messages.length-1;e>=0;e--)if(eZ(rD.messages[e])){r=e;break}let i=rD.groups.slice(),a=i.length>0?i[i.length-1]:void 0;a&&a.anchorIdx===r?i[i.length-1]={...a,entries:[...a.entries,...t],messageCount:a.messageCount+t.length,toolCallCount:a.toolCallCount+n}:i.push({anchorIdx:r,entries:t,messageCount:t.length,toolCallCount:n}),S?.({...rD,groups:i,messages:[...rD.messages,...e],status:rq})},[rD,rA,rR,rU,rq,S]),(0,i.useEffect)(()=>()=>S?.(null),[S]);let rK=tf.filter(e=>"belowEditor"!==e.placement),rV=tf.filter(e=>"belowEditor"===e.placement);return ek?(0,r.jsx)("div",{className:"flex h-full items-center justify-center text-red-400",children:ek}):(0,r.jsxs)("div",{className:"chat-window relative flex h-full min-w-0 flex-col overflow-hidden","aria-busy":nn,style:{paddingBottom:"env(safe-area-inset-bottom)"},onDragEnter:rr,onDragOver:ri,onDragLeave:ra,onDrop:rs,children:[nn?(0,r.jsx)("div",{className:"absolute inset-0 z-40 cursor-wait",children:(0,r.jsx)("div",{className:"absolute right-3 top-3 border border-border bg-bg-panel px-3 py-2 text-sm text-text-muted shadow-sm",role:"status",children:K("chat.loadingSession")})}):null,rn&&!t4&&(0,r.jsx)("div",{className:"pointer-events-none absolute inset-0 z-50 flex animate-[drop-zone-in_0.15s_ease_both] items-center justify-center",style:{background:"var(--accent-soft)",border:"2px dashed var(--accent-line)"},children:(0,r.jsx)("span",{className:"px-3 py-1 text-sm font-medium",style:{background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:"var(--radius-surface)",color:"var(--text)"},children:K("chat.attachFile")})}),th&&(0,r.jsx)(lW,{request:th,onInput:tx}),rk&&!N?(0,r.jsx)("div",{className:"flex flex-1 flex-col items-center overflow-y-auto px-4",children:(0,r.jsxs)("div",{className:"my-auto w-full max-w-[820px] py-8",children:[(0,r.jsxs)("div",{className:"mb-3",style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12,marginLeft:16,marginRight:52,fontFamily:"var(--font-mono)"},children:[(0,r.jsx)("div",{style:{minWidth:0,flex:1,overflow:"hidden"},children:(0,r.jsx)(V,{})}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",alignItems:"flex-end",gap:2,flexShrink:0},children:[(0,r.jsxs)("span",{style:{fontSize:11,color:"var(--text-muted)"},children:["web ",(0,r.jsxs)("span",{style:{color:"var(--text)"},children:["v","0.10.35"]})]}),(0,r.jsxs)("span",{style:{fontSize:11,color:"var(--text-muted)"},children:["omp ",(0,r.jsxs)("span",{style:{color:"var(--text)"},children:["v","18.12.1"]})]})]})]}),(0,r.jsx)(lA,{notices:tc,align:"right"})]})}):(0,r.jsxs)(r.Fragment,{children:[N&&(0,r.jsx)("div",{className:"min-h-0 min-w-0 flex-1 overflow-hidden",children:N}),(0,r.jsxs)("div",{className:"relative min-w-0 flex-1 overflow-hidden","aria-hidden":!!N,style:{display:N?"none":"flex"},children:[(0,r.jsx)("div",{style:{position:"absolute",top:12,left:0,right:0,zIndex:40,padding:"0 16px",pointerEvents:"none"},children:(0,r.jsxs)("div",{className:"chat-column-cap",style:{maxWidth:820,margin:"0 auto",display:"flex",flexDirection:"column",alignItems:"flex-end",gap:8},children:[(0,r.jsx)(ip,{open:nV,onClose:nQ,containerRef:tI,index:nZ,renderedStart:nu,renderedEnd:nf,contentKey:eS,onReveal:nX,onProgrammaticScroll:tj,focusRequest:nG,t:K}),nU&&(0,r.jsx)("div",{className:"chat-jump-missing",role:"status",children:K("chat.jumpMissing")}),(0,r.jsx)(lA,{notices:tc,floating:!0,align:"right"})]})}),(0,r.jsx)("div",{ref:tI,className:"chat-session-scroll relative min-w-0 flex-1 overflow-x-hidden overflow-y-auto pt-4 [scrollbar-width:none]",children:(0,r.jsx)("div",{style:{minWidth:0,padding:"0 16px"},children:(0,r.jsxs)("div",{className:"chat-column-cap",style:{width:"100%",minWidth:0,maxWidth:820,margin:"0 auto"},children:[(0,r.jsx)(lL,{widgets:rK}),(0,r.jsx)(nK.Provider,{value:rc,children:(0,r.jsx)(iD,{utterances:rw,children:(0,r.jsx)(l$,{messages:eS,entryIds:eC,toolResultsMap:ro,modelNames:e$,messageCwd:rj,onOpenFile:C,sessionBusy:t4,isNew:ty,isStreaming:eN.isStreaming,handleFork:t$,forkingEntryId:e5,handleNavigate:tR,handleEditContent:ey,sessionId:e?.id??tC.current??void 0,main:na,dispatchSlots:nl,compactedDispatch:no,process:ns,startIndex:nu,endIndex:nf,sentinelRef:nb,laterSentinelRef:ny,flashItem:nk,t:K,cues:ee,cueFollowRef:t6,onProcessLogChange:rB})})}),!nx&&eN.isStreaming&&eN.streamingMessage&&rL.length>0&&(0,r.jsx)(rO,{message:ez(eN.streamingMessage,rL),sessionId:e?.id??tC.current??void 0,isStreaming:!0,modelNames:e$,cwd:rj,onOpenFile:C}),n3&&(0,r.jsx)(ib,{onDismiss:n8,t:K}),(0,r.jsx)("div",{ref:tN})]})})}),(0,r.jsx)(ih,{questions:n0,containerRef:tI,layoutKey:n1,onJump:nM,label:K("chat.questionRail")}),(t4&&tw||nx)&&(0,r.jsxs)("button",{type:"button",onClick:nF,"aria-label":K("chat.jumpToBottom"),title:K("chat.jumpToBottom"),style:{position:"absolute",bottom:16,left:"50%",transform:"translateX(-50%)",zIndex:40,display:"flex",alignItems:"center",gap:6,padding:"6px 12px",minHeight:G?44:void 0,borderRadius:999,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)",fontSize:11,fontFamily:"var(--font-mono)",cursor:"pointer",boxShadow:"0 2px 10px rgba(0,0,0,0.28)"},children:[(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M12 5v14"}),(0,r.jsx)("path",{d:"m19 12-7 7-7-7"})]}),K("chat.jumpToBottom")]})]})]}),(0,r.jsxs)("div",{ref:rI,className:"relative chat-composer-dock flex min-h-0 flex-col",children:[tu&&(0,r.jsx)("div",{style:{padding:"0 16px"},children:(0,r.jsx)("div",{className:"chat-column-cap",style:{maxWidth:820,margin:"0 auto"},children:(0,r.jsx)(lP,{request:tu,onRespond:tg,onActivity:e=>void tx(e,"activity"),delivery:tp})})}),(0,r.jsx)("div",{className:"min-h-0 overflow-y-auto",style:{padding:"0 16px"},children:(0,r.jsxs)("div",{className:"chat-column-cap",style:{maxWidth:820,margin:"0 auto"},children:[(0,r.jsx)(iv,{compaction:e8,t:K}),(0,r.jsx)(lE,{goal:tS,t:K}),!Y&&(0,r.jsx)(io,{summary:ru,onJump:nM,onOpenPanel:rp}),(0,r.jsx)(lL,{widgets:rV}),rm&&!Y&&(0,r.jsx)(sW,{phases:rm})]})}),r$,(0,r.jsx)(sP,{statuses:tm})]})]})}function lE({goal:e,t}){if(!e)return null;let n=!e.enabled,i=void 0!==e.tokenBudget?t("chat.goalBudgetLeft",{left:t1(Math.max(0,e.tokenBudget-e.tokensUsed))}):t("chat.goalTokensUsed",{used:t1(e.tokensUsed)});return(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:8,padding:"5px 10px",border:"1px solid var(--border)",borderRadius:7,background:"var(--bg-panel)",color:"var(--text-muted)",fontSize:11,fontFamily:"var(--font-mono)",opacity:n?.7:1},children:[(0,r.jsx)("span",{style:{color:n?"var(--text-dim)":"var(--accent)",fontWeight:700,letterSpacing:"0.06em",textTransform:"uppercase",flexShrink:0},children:t("chat.goalLabel")}),(0,r.jsx)("span",{style:{minWidth:0,flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text)"},children:e.objective}),(0,r.jsx)("span",{style:{flexShrink:0,color:"var(--text-dim)"},children:n?t("chat.goalPaused"):e.status}),(0,r.jsx)("span",{style:{flexShrink:0,color:"var(--text-dim)"},children:i})]})}function lL({widgets:e}){return 0===e.length?null:(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:8,marginBottom:10},children:e.map(e=>(0,r.jsxs)("div",{style:{border:"1px solid var(--border)",borderRadius:7,background:"var(--bg-panel)",overflow:"hidden"},children:[(0,r.jsx)("div",{style:{padding:"5px 9px",borderBottom:"1px solid var(--border)",color:"var(--text-dim)",fontSize:11,fontFamily:"var(--font-mono)"},children:e.key}),(0,r.jsx)("pre",{style:{margin:0,padding:"8px 9px",color:"var(--text-muted)",fontSize:12,lineHeight:1.5,whiteSpace:"pre-wrap",wordBreak:"break-word",fontFamily:"var(--font-mono)"},children:e.lines.join("\n")})]},e.key))})}function lA({notices:e,floating:t=!1,align:n="left"}){return 0===e.length?null:(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",alignItems:"right"===n?"flex-end":"stretch",marginBottom:10*!t},children:e.map((n,i)=>{let a="error"===n.type?"var(--danger)":"warning"===n.type?"var(--warning)":"success"===n.type?"var(--success)":"var(--accent)";return(0,r.jsxs)("div",{className:"notice-shelf-item",style:{display:"flex",alignItems:"center",gap:10,minHeight:60,height:60,maxHeight:60,marginBottom:6*(i!==e.length-1),overflow:"hidden",borderRadius:"var(--seed-radius-r3)",border:"1px solid var(--border)",background:"var(--bg)",color:"var(--text-muted)",width:"fit-content",maxWidth:"min(100%, 620px)",boxShadow:t?"var(--seed-shadow-s3)":"var(--seed-shadow-s2)",fontSize:18,lineHeight:1.45,transformOrigin:"top center",animation:n.exiting?"notice-shelf-out 0.18s ease-in forwards":"notice-shelf-in 0.18s ease-out both",padding:"0 12px"},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:a,flexShrink:0}}),(0,r.jsx)("span",{style:{padding:"14px 0",minWidth:0,maxWidth:"100%",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:n.message})]},n.id)})})}function lz({focusKey:e,label:t,labelledBy:n,maxBlockSize:a="min(56dvh, 620px)",onCancel:s,delivery:l,children:o}){let{t:d}=(0,R.s)(),c=(0,i.useRef)(null),u=(0,i.useRef)({key:"",element:null});if(u.current.key!==e){let t="u"<typeof document?null:document.activeElement;u.current={key:e,element:t instanceof HTMLElement&&!c.current?.contains(t)?t:null}}return(0,i.useEffect)(()=>{let e=c.current;e&&!e.contains(document.activeElement)&&(e.querySelector('button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])')??e).focus();let t=u.current.element;return()=>{if(!t?.isConnected)return;let n=document.activeElement;(null===n||n===document.body||e?.contains(n))&&t.focus()}},[e]),(0,r.jsxs)("div",{ref:c,role:"dialog","aria-modal":"false","aria-label":t,"aria-labelledby":n,className:"chat-response-surface",tabIndex:-1,onKeyDown:s?e=>{"Escape"===e.key&&(e.stopPropagation(),s())}:void 0,"aria-busy":l?.status==="sending"||void 0,style:{maxBlockSize:a},children:[l?(0,r.jsx)("p",{className:"chat-response-delivery",role:"failed"===l.status?"alert":"status","data-state":l.status,children:"sending"===l.status?d("chat.responseSending"):`${d("chat.responseFailed")}${l.error?` (${l.error})`:""}`}):null,o]})}function lP({request:e,onRespond:t,onActivity:n,delivery:a}){let{t:s}=(0,R.s)(),[l,o]=(0,i.useState)("editor"===e.method?e.prefill??"":""),[d,c]=(0,i.useState)({selected:{},custom:{}}),[u,p]=(0,i.useState)(""),h=(0,i.useRef)(0),m=(0,i.useCallback)(()=>{if("ask"!==e.method||!e.timeout||!n)return;let t=Date.now();t-h.current<1e3||(h.current=t,n(e))},[e,n]);(0,i.useEffect)(()=>{o("editor"===e.method?e.prefill??"":""),p(""),c("ask"===e.method?function(e){let t={};for(let n of e)t[n.id]=void 0!==n.recommended&&void 0!==n.options[n.recommended]?[n.recommended]:[];return{selected:t,custom:{}}}(e.questions):{selected:{},custom:{}})},[e]);let f=()=>{"confirm"===e.method?t(e,{confirmed:!0}):t(e,{value:l})};if("ask"===e.method){var g;let n=(g=e.questions,g.every(e=>(d.selected[e.id]?.length??0)>0||(d.custom[e.id]?.trim().length??0)>0)),i=()=>{if(n){var r;t(e,{value:(r=e.questions,JSON.stringify({kind:"submit",results:r.map(e=>{let t=d.custom[e.id]?.trim();return{id:e.id,question:e.question,options:e.options.map(e=>e.label),multi:e.multi??!1,selectedOptions:(d.selected[e.id]??[]).map(t=>e.options[t]?.label).filter(e=>void 0!==e),...t?{customInput:t}:{}}})}))})}};return(0,r.jsx)(lz,{focusKey:e.id,label:s("chat.agentQuestion"),onCancel:()=>t(e,{cancelled:!0}),delivery:a,children:(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",minHeight:0},children:[(0,r.jsx)("div",{style:{display:"flex",alignItems:"center",gap:10,padding:"12px 16px",borderBottom:"1px solid var(--border)"},children:(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("div",{style:{color:"var(--text)",fontSize:"var(--seed-font-size-t4-static)",fontWeight:600},children:s("chat.agentQuestion")}),(0,r.jsx)("div",{style:{marginTop:2,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)"},children:s("chat.agentQuestionHint")}),e.timeout?(0,r.jsx)("div",{style:{marginTop:2,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)"},children:s("chat.askAutoSelectHint",{seconds:Math.round(e.timeout/1e3)})}):null]})}),(0,r.jsx)("div",{style:{flex:"1 1 auto",minHeight:0,overflowY:"auto",padding:16},children:(0,r.jsx)("div",{style:{display:"grid",gap:20},children:e.questions.map((t,n)=>{let a=d.selected[t.id]??[];return(0,r.jsxs)("section",{style:{paddingTop:20*(0!==n),borderTop:0===n?"none":"1px solid var(--hairline)"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"baseline",gap:8,marginBottom:10},children:[t.header&&(0,r.jsx)("span",{style:{color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontWeight:600},children:t.header}),e.questions.length>1&&(0,r.jsxs)("span",{style:{marginLeft:"auto",color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontVariantNumeric:"tabular-nums"},children:[n+1,"/",e.questions.length]})]}),(0,r.jsx)("div",{style:{marginBottom:10,color:"var(--text)",fontSize:"var(--seed-font-size-t4-static)",fontWeight:600,lineHeight:1.5},children:t.question}),(0,r.jsx)("div",{role:t.multi?"group":"radiogroup","aria-label":t.question,style:{display:"grid",gap:4},children:t.options.map((e,n)=>{let i=a.includes(n),l=t.recommended===n;return(0,r.jsxs)("button",{type:"button",role:t.multi?"checkbox":"radio","aria-checked":i,onClick:()=>{m(),c(e=>(function(e,t,n){let r=e.selected[t.id]??[];if(t.multi){let i=r.includes(n)?r.filter(e=>e!==n):[...r,n];return{...e,selected:{...e.selected,[t.id]:i}}}return{selected:{...e.selected,[t.id]:[n]},custom:{...e.custom,[t.id]:""}}})(e,t,n))},style:{display:"grid",gridTemplateColumns:"18px minmax(0, 1fr) auto",alignItems:"start",gap:9,width:"100%",minHeight:40,padding:"9px 10px",border:`1px solid ${i?"var(--border-strong)":"transparent"}`,borderRadius:"var(--radius-control)",background:i?"var(--bg-selected)":"transparent",color:"var(--text)",cursor:"pointer",textAlign:"left"},children:[(0,r.jsx)("span",{"aria-hidden":"true",style:{display:"grid",placeItems:"center",width:16,height:16,marginTop:1,border:`1px solid ${i?"var(--text)":"var(--text-dim)"}`,borderRadius:t.multi?"var(--radius-control)":"50%",background:i?"var(--seed-color-fg-neutral)":"transparent",color:"var(--seed-color-fg-neutral-inverted)",fontSize:"var(--seed-font-size-t2-static)",lineHeight:1},children:i&&(t.multi?(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("polyline",{points:"2 5.2 4.1 7.2 8 2.8"})}):(0,r.jsx)("span",{style:{width:5,height:5,borderRadius:"50%",background:"currentColor"}}))}),(0,r.jsxs)("span",{style:{minWidth:0},children:[(0,r.jsx)("span",{style:{display:"block",fontSize:"var(--seed-font-size-t4-static)",fontWeight:i?600:500},children:e.label}),e.description&&(0,r.jsx)("span",{style:{display:"block",marginTop:3,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.45},children:e.description}),i&&e.preview&&(0,r.jsx)("span",{style:{display:"block",marginTop:8,padding:"7px 8px",borderLeft:"2px solid var(--border-strong)",background:"var(--bg-subtle)",color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.5,whiteSpace:"pre-wrap"},children:e.preview})]}),l&&(0,r.jsx)("span",{style:{color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontWeight:600},children:s("chat.recommended")})]},`${t.id}:${n}`)})}),(0,r.jsx)("input",{value:d.custom[t.id]??"",onChange:e=>{m();let n=e.target.value;c(e=>{let r;return r={...e.custom,[t.id]:n},t.multi||0===n.trim().length?{...e,custom:r}:{selected:{...e.selected,[t.id]:[]},custom:r}})},onKeyDown:e=>{(e.metaKey||e.ctrlKey)&&"Enter"===e.key&&i()},placeholder:s("chat.customAnswer"),"aria-label":s("chat.customAnswer"),style:{width:"100%",height:36,marginTop:9,padding:"0 10px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"var(--bg)",color:"var(--text)",fontFamily:"var(--seed-font-family)",fontSize:"var(--seed-font-size-t4-static)"}})]},t.id)})})}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",justifyContent:"flex-end",gap:8,padding:"12px 16px",borderTop:"1px solid var(--border)"},children:[(0,r.jsx)("button",{type:"button",onClick:()=>t(e,{cancelled:!0}),style:{minHeight:36,padding:"0 12px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"transparent",color:"var(--text-muted)",cursor:"pointer"},children:s("chat.cancel")}),(0,r.jsx)("button",{type:"button",onClick:()=>t(e,{value:JSON.stringify({kind:"chat"})}),style:{minHeight:36,padding:"0 12px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"transparent",color:"var(--text)",cursor:"pointer"},children:s("chat.chatAboutThis")}),(0,r.jsx)("button",{type:"button",disabled:!n||a?.status==="sending",onClick:i,style:{minHeight:36,padding:"0 14px",border:"1px solid transparent",borderRadius:"var(--radius-control)",background:n&&a?.status!=="sending"?"var(--seed-color-bg-neutral-inverted)":"var(--seed-color-bg-disabled)",color:n&&a?.status!=="sending"?"var(--seed-color-fg-neutral-inverted)":"var(--seed-color-fg-disabled)",cursor:n&&a?.status!=="sending"?"pointer":"not-allowed",fontWeight:600},children:a?.status==="sending"?s("chat.responseSending"):s("chat.submitAnswer")})]})]})})}return"plan_review"===e.method?(0,r.jsx)(lz,{focusKey:e.id,labelledBy:`plan-review-${e.id}`,maxBlockSize:"min(64dvh, 760px)",delivery:a,children:(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",minHeight:0},children:[(0,r.jsxs)("div",{style:{padding:"12px 16px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("div",{style:{color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontWeight:600},children:s("chat.planApproval")}),(0,r.jsx)("div",{id:`plan-review-${e.id}`,style:{marginTop:4,color:"var(--text)",fontSize:"var(--seed-font-size-t5-static)",fontWeight:600},children:e.title}),(0,r.jsx)("div",{style:{marginTop:5,color:"var(--text-muted)",fontFamily:"var(--font-mono)",fontSize:"var(--seed-font-size-t2-static)",overflowWrap:"anywhere"},children:e.planFilePath})]}),(0,r.jsx)("div",{style:{flex:"1 1 auto",minHeight:0,overflowY:"auto",padding:"18px 20px"},children:(0,r.jsx)(tG,{children:e.planContent})}),(0,r.jsxs)("div",{style:{padding:"12px 16px",borderTop:"1px solid var(--border)"},children:[(0,r.jsx)("textarea",{value:u,onChange:e=>p(e.target.value),placeholder:s("chat.planFeedback"),"aria-label":s("chat.planFeedback"),style:{width:"100%",minHeight:64,maxHeight:150,padding:"9px 10px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",outline:"none",resize:"vertical",background:"var(--bg)",color:"var(--text)",fontFamily:"var(--seed-font-family)",fontSize:"var(--seed-font-size-t4-static)",lineHeight:1.5}}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",justifyContent:"flex-end",gap:8,marginTop:9},children:[(0,r.jsx)("button",{type:"button",onClick:()=>t(e,{value:JSON.stringify({action:"refine",feedback:u.trim()})}),style:{minHeight:36,padding:"0 12px",border:"1px solid var(--border)",borderRadius:"var(--radius-control)",background:"transparent",color:"var(--text)",cursor:"pointer"},children:s("chat.refinePlan")}),(0,r.jsx)("button",{type:"button",onClick:()=>t(e,{value:JSON.stringify({action:"approve"})}),style:{minHeight:36,padding:"0 14px",border:"1px solid transparent",borderRadius:"var(--radius-control)",background:"var(--seed-color-bg-neutral-inverted)",color:"var(--seed-color-fg-neutral-inverted)",cursor:"pointer",fontWeight:600},children:s("chat.approvePlan")})]})]})]})}):(0,r.jsx)(lz,{focusKey:e.id,labelledBy:`extension-request-${e.id}`,onCancel:()=>t(e,{cancelled:!0}),delivery:a,children:(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",minHeight:0},children:[(0,r.jsxs)("div",{style:{padding:"12px 14px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("div",{id:`extension-request-${e.id}`,style:{color:"var(--text)",fontSize:"var(--seed-font-size-t4-static)",fontWeight:600},children:e.title}),(0,r.jsx)("div",{style:{marginTop:3,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontFamily:"var(--font-mono)"},children:s("chat.extensionRequest")})]}),(0,r.jsxs)("div",{style:{flex:"1 1 auto",minHeight:0,overflowY:"auto",padding:14},children:["confirm"===e.method&&(0,r.jsx)("div",{style:{color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.6,whiteSpace:"pre-wrap"},children:e.message}),"select"===e.method&&(0,r.jsx)("div",{style:{display:"grid",gap:8},children:e.options.map(n=>(0,r.jsx)("button",{onClick:()=>t(e,{value:n}),style:{width:"100%",minHeight:40,padding:"9px 10px",borderRadius:"var(--radius-control)",border:"1px solid var(--border)",background:"transparent",color:"var(--text)",cursor:"pointer",textAlign:"left",fontSize:"var(--seed-font-size-t4-static)"},children:n},n))}),"input"===e.method&&(0,r.jsx)("input",{autoFocus:!0,value:l,placeholder:e.placeholder,onChange:e=>o(e.target.value),onKeyDown:e=>{"Enter"===e.key&&f()},style:{width:"100%",padding:"9px 10px",borderRadius:"var(--radius-control)",border:"1px solid var(--border)",background:"var(--bg)",color:"var(--text)",outline:"none",fontSize:"var(--seed-font-size-t4-static)"}}),"editor"===e.method&&(0,r.jsx)("textarea",{autoFocus:!0,value:l,onChange:e=>o(e.target.value),onKeyDown:e=>{(e.metaKey||e.ctrlKey)&&"Enter"===e.key&&f()},style:{width:"100%",minHeight:220,padding:10,borderRadius:"var(--radius-control)",border:"1px solid var(--border)",background:"var(--bg)",color:"var(--text)",outline:"none",resize:"vertical",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.55,fontFamily:"var(--font-mono)"}})]}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",justifyContent:"flex-end",gap:8,padding:"12px 14px",borderTop:"1px solid var(--border)"},children:[(0,r.jsx)("button",{onClick:()=>t(e,{cancelled:!0}),style:{minHeight:36,padding:"0 12px",borderRadius:"var(--radius-control)",border:"1px solid var(--border)",background:"transparent",color:"var(--text-muted)",cursor:"pointer"},children:s("chat.cancel")}),"confirm"===e.method?(0,r.jsx)("button",{onClick:f,style:{minHeight:36,padding:"0 14px",borderRadius:"var(--radius-control)",border:"1px solid transparent",background:"var(--seed-color-bg-neutral-inverted)",color:"var(--seed-color-fg-neutral-inverted)",cursor:"pointer",fontWeight:600},children:s("chat.confirm")}):"select"!==e.method?(0,r.jsx)("button",{onClick:f,style:{minHeight:36,padding:"0 14px",borderRadius:"var(--radius-control)",border:"1px solid transparent",background:"var(--seed-color-bg-neutral-inverted)",color:"var(--seed-color-fg-neutral-inverted)",cursor:"pointer",fontWeight:600},children:s("chat.submit")}):null]})]})})}function lW({request:e,onInput:t}){let{t:n}=(0,R.s)(),a=(0,i.useRef)(null),s=(0,i.useRef)(!1),l=eI(e.lines);return(0,i.useEffect)(()=>{a.current?.focus()},[e.id]),(0,r.jsx)("div",{style:{position:"absolute",inset:0,zIndex:95,display:"flex",alignItems:"center",justifyContent:"center",padding:20,background:"var(--seed-color-bg-overlay-muted)"},children:(0,r.jsxs)("div",{role:"dialog","aria-modal":"true",onClick:e=>{e.target.closest("button")||a.current?.focus()},style:{position:"relative",width:"min(920px, 100%)",maxHeight:"min(760px, calc(100vh - 40px))",border:"1px solid var(--border)",borderRadius:8,background:"var(--bg)",boxShadow:"var(--seed-shadow-s3)",overflow:"hidden",outline:"none"},children:[(0,r.jsx)("textarea",{ref:a,"aria-label":n("chat.extensionInput"),autoCapitalize:"off",autoComplete:"off",autoCorrect:"off",spellCheck:!1,onKeyDown:n=>{if(s.current||n.nativeEvent.isComposing)return;let r=function(e){if(e.metaKey||e.ctrlKey&&!e.altKey&&"v"===e.key.toLowerCase())return null;if(e.ctrlKey&&!e.altKey){let t=function(e){if(1!==e.length)return null;let t=e.toUpperCase().charCodeAt(0);return t>=64&&t<=95?String.fromCharCode(31&t):"?"===e?"":null}(e.key);if(t)return t}if(e.altKey&&!e.ctrlKey){if("Backspace"===e.key)return"\x1b\x7f";let t=e$[e.key];if(t)return t;if(1===e.key.length)return`\x1b${e.key}`}return"Enter"===e.key?e.shiftKey?"\n":"\r":"Tab"===e.key?e.shiftKey?"\x1b[Z":" ":eM[e.key]??null}(n);r&&(n.preventDefault(),n.stopPropagation(),t(e,r))},onInput:n=>{if(s.current||n.nativeEvent.isComposing)return;let r=n.currentTarget.value;n.currentTarget.value="",r&&t(e,r)},onCompositionStart:()=>{s.current=!0},onCompositionEnd:n=>{s.current=!1;let r=n.currentTarget;queueMicrotask(()=>{let n=r.value;r.value="",n&&t(e,n)})},onPaste:n=>{n.preventDefault();let r=n.clipboardData.getData("text");r&&t(e,`\x1b[200~${r}\x1b[201~`)},style:{position:"absolute",width:1,height:1,padding:0,border:0,opacity:0,pointerEvents:"none"}}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12,padding:"10px 12px",borderBottom:"1px solid var(--border)"},children:[(0,r.jsx)("div",{style:{color:"var(--text)",fontSize:13,fontWeight:650},children:n("chat.extensionPanel")}),(0,r.jsx)("button",{onClick:()=>t(e,"\x03"),style:{padding:"5px 9px",borderRadius:6,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)",cursor:"pointer",fontSize:12},children:n("chat.close")})]}),(0,r.jsx)("pre",{style:{margin:0,padding:14,maxHeight:"calc(min(760px, 100vh - 40px) - 48px)",overflow:"auto",background:"var(--bg-panel)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:13,lineHeight:1.45,whiteSpace:"pre"},children:(l.length?l:[""]).map((e,t,n)=>{var a;return(0,r.jsxs)(i.Fragment,{children:[(a=`line-${t}`,eT(e).map((e,t)=>Object.keys(e.style).length>0?(0,r.jsx)("span",{style:e.style,children:e.text},`${a}-${t}`):e.text)),t<n.length-1?"\n":null]},t)})})]})})}function lF({onPick:e,t}){let[n,a]=(0,i.useState)(""),[s,l]=(0,i.useState)({kind:"idle"}),o=(0,i.useRef)(null),d=n.trim();(0,i.useEffect)(()=>{if(d.length<2)return void l({kind:"idle"});let e=new AbortController;l({kind:"loading"});let t=setTimeout(()=>{fetch(`/api/sessions/search?q=${encodeURIComponent(d)}`,{signal:e.signal,cache:"no-store"}).then(async e=>{if(!e.ok)throw Error(`HTTP ${e.status}`);l({kind:"done",data:await e.json()})}).catch(()=>{e.signal.aborted||l({kind:"error"})})},250);return()=>{clearTimeout(t),e.abort()}},[d]);let c=e=>{let t=o.current?.querySelectorAll("button");t&&0!==t.length&&t[Math.max(0,Math.min(t.length-1,e))]?.focus()},u="done"===s.kind?s.data:null,p=u?.truncated?t(`palette.searchTruncated.${u.truncated}`,{scanned:u.scannedSessions,total:u.totalSessions}):null;return(0,r.jsxs)("div",{className:"palette-search",children:[(0,r.jsx)("input",{type:"search",value:n,onChange:e=>a(e.target.value),onKeyDown:t=>{if(!t.nativeEvent.isComposing){if("ArrowDown"===t.key)t.preventDefault(),c(0);else if("Enter"===t.key&&u&&u.hits.length>0){t.preventDefault();let n=u.hits[0],r=u.sessions[n.sessionId];r&&e(r,n,u.query)}}},placeholder:t("palette.searchPlaceholder"),"aria-label":t("palette.searchPlaceholder"),autoComplete:"off",spellCheck:!1}),d.length>=2&&(0,r.jsxs)("div",{className:"palette-search-results",role:"region","aria-label":t("palette.searchResults"),"aria-busy":"loading"===s.kind,children:[(0,r.jsxs)("p",{className:"palette-search-status","aria-live":"polite",children:["loading"===s.kind&&t("palette.searching"),"error"===s.kind&&t("palette.searchFailed"),u&&(0===u.hits.length?t("palette.searchEmpty"):t("palette.searchHits",{count:u.hits.length})),p?` \xb7 ${p}`:"",u&&u.compactedHits>0?` \xb7 ${t("palette.searchCompacted",{count:u.compactedHits})}`:""]}),u&&u.hits.length>0&&(0,r.jsx)("div",{ref:o,className:"palette-search-list",children:u.hits.map((n,i)=>{let a=u.sessions[n.sessionId],s=n.matchStart+u.query.length;return(0,r.jsxs)("button",{type:"button",disabled:!a,onClick:()=>a&&e(a,n,u.query),onKeyDown:e=>{("ArrowDown"===e.key||"ArrowUp"===e.key)&&(e.preventDefault(),c(i+("ArrowDown"===e.key?1:-1)))},children:[(0,r.jsxs)("span",{className:"palette-search-title",children:[(0,r.jsx)("span",{children:a?a.name?.trim()||a.firstMessage?.trim()||a.id:""}),(0,r.jsx)("small",{children:"user"===n.role?t("palette.searchRoleUser"):t("palette.searchRoleAssistant")})]}),(0,r.jsxs)("span",{className:"palette-search-snippet",children:[n.snippet.slice(0,n.matchStart),(0,r.jsx)("mark",{children:n.snippet.slice(n.matchStart,s)}),n.snippet.slice(s)]})]},`${n.sessionId}:${n.entryId}`)})})]})]})}var l_=n(50640),lD=n(73620);let lO=/^(?:\uFEFF)?---[ \t]*(?:\r\n|\n|\r)/;function lH(e){return function e(t,n){if(null==t)return"";if("string"==typeof t)return t;if("number"==typeof t||"boolean"==typeof t)return String(t);if(Array.isArray(t)){if(n.has(t))return"[Circular]";n.add(t);try{return t.map(t=>e(t,n)).filter(Boolean).join(", ")}finally{n.delete(t)}}if("object"==typeof t)try{return JSON.stringify(t)??Object.prototype.toString.call(t)}catch{return Object.prototype.toString.call(t)}return String(t)}(e,new WeakSet)}let lB=["tags","categories","keywords","tag","category"];function lU({data:e}){var t;if(!e)return null;let n=Object.entries(e);if(0===n.length)return null;let i="string"==typeof(t=e.title)?t.trim()||null:"number"==typeof t||"boolean"==typeof t?String(t):null,a=lB.find(t=>Array.isArray(e[t])),s=a?e[a].map(lH).filter(Boolean):[],l=n.filter(([e])=>e!==a&&("title"!==e||!i));return(0,r.jsxs)("div",{className:"markdown-frontmatter",children:[i&&(0,r.jsx)("div",{className:"markdown-frontmatter-title",children:i}),s.length>0&&(0,r.jsx)("div",{className:"markdown-frontmatter-tags",children:s.map((e,t)=>(0,r.jsx)("span",{className:"markdown-frontmatter-tag",children:e},`${e}-${t}`))}),l.length>0&&(0,r.jsx)("dl",{className:"markdown-frontmatter-rows",children:l.map(([e,t])=>(0,r.jsxs)("div",{className:"markdown-frontmatter-row",children:[(0,r.jsx)("dt",{children:e}),(0,r.jsx)("dd",{children:function(e){let t=lH(e);return t?"string"==typeof e&&/^(https?:\/\/|mailto:)/i.test(e)?(0,r.jsx)("a",{href:e,target:"_blank",rel:"noopener noreferrer",children:t}):t:null}(t)})]},e))})]})}var lq=n(8745);let lK=(0,i.createContext)(null),lV=(0,r.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M9.5 2.5h4v4M6.5 13.5h-4v-4M13.5 2.5 9 7M2.5 13.5 7 9"})}),lJ=(0,r.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M13.5 6.5h-4v-4M2.5 9.5h4v4M9.5 6.5l4-4M6.5 9.5l-4 4"})}),lG=(0,r.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m10 3-5 5 5 5"})}),lY=(0,r.jsx)("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m4 4 8 8M12 4l-8 8"})}),lZ=(0,r.jsxs)("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"currentColor","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"3.5",cy:"8",r:"1.2"}),(0,r.jsx)("circle",{cx:"8",cy:"8",r:"1.2"}),(0,r.jsx)("circle",{cx:"12.5",cy:"8",r:"1.2"})]});function lX({back:e,title:t,titleTooltip:n,titleRef:i,titleAdornment:a,subtitle:o,subtitleKind:c="text",state:u,viewSwitch:p,actions:h=[],close:m}){let{t:f}=(0,R.s)();return(0,r.jsxs)("header",{className:"panel-header",children:[e&&(0,r.jsx)(s.r,{className:"panel-header-button",variant:"ghost",size:"small",layout:"iconOnly",onClick:e.onClick,"aria-label":e.label,title:e.label,children:(0,r.jsx)(l.In,{size:"16px",svg:lG})}),(0,r.jsxs)("div",{className:"panel-header-heading",children:[(0,r.jsx)("h2",{className:"panel-header-title",title:n,ref:i,tabIndex:i?-1:void 0,children:t}),a,o&&("path"===c?(0,r.jsx)("span",{className:"panel-header-subtitle is-path",title:o,dir:"rtl",children:(0,r.jsx)("bdi",{dir:"ltr",children:o})}):(0,r.jsx)("span",{className:"panel-header-subtitle",title:o,children:o}))]}),u&&(0,r.jsx)("div",{className:"panel-header-state",children:u}),p&&p.options.length>1&&(0,r.jsxs)(lq.A.Root,{className:"panel-header-switch","aria-label":p.label,value:p.value,onValueChange:e=>p.onChange(e),children:[p.options.map(e=>(0,r.jsxs)(lq.A.Item,{value:e.value,title:e.title,children:[(0,r.jsx)(lq.A.ItemHiddenInput,{}),e.label]},e.value)),(0,r.jsx)(lq.A.Indicator,{})]}),h.length>0&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{className:"panel-header-actions",children:h.map(e=>e.href?(0,r.jsx)("a",{className:"panel-header-link-button",href:e.href,download:e.download,"aria-label":e.label,title:e.title??e.label,children:e.icon},e.id):(0,r.jsx)(s.r,{className:"panel-header-button",variant:"ghost",size:"small",layout:"iconOnly",onClick:e.onClick,onPointerDown:e.onPointerDown,disabled:e.disabled,"aria-pressed":e.pressed,"aria-label":e.label,title:e.title??e.label,children:(0,r.jsx)(l.In,{size:"16px",svg:e.icon})},e.id))}),(0,r.jsxs)(d.k.Root,{placement:"bottom-end",strategy:"fixed",children:[(0,r.jsx)(d.k.Trigger,{asChild:!0,children:(0,r.jsx)(s.r,{className:"panel-header-button panel-header-more",variant:"ghost",size:"small",layout:"iconOnly","aria-label":f("panel.more"),title:f("panel.more"),children:(0,r.jsx)(l.In,{size:"16px",svg:lZ})})}),(0,r.jsx)(d.k.Positioner,{children:(0,r.jsx)(d.k.Content,{"aria-label":f("panel.more"),children:(0,r.jsx)(d.k.ScrollArea,{children:(0,r.jsx)(d.k.Group,{children:h.map(e=>(0,r.jsx)(d.k.Item,{disabled:e.disabled,onClick:()=>(function(e){if(e.onClick)return void e.onClick();if(!e.href)return;let t=document.createElement("a");t.href=e.href,e.download&&(t.download=e.download),t.click()})(e),children:(0,r.jsx)(d.k.ItemBody,{children:(0,r.jsx)(d.k.ItemLabel,{children:e.label})})},e.id))})})})})]})]}),(0,r.jsx)(lQ,{}),m&&(0,r.jsx)(s.r,{className:"panel-header-button",variant:"ghost",size:"small",layout:"iconOnly",onClick:m.onClick,"aria-label":m.label,title:m.label,children:(0,r.jsx)(l.In,{size:"16px",svg:lY})})]})}function lQ({className:e="panel-header-button"}){let{t}=(0,R.s)(),n=(0,i.useContext)(lK);if(!n)return null;let a=t(n.expanded?"panel.restore":"panel.expand");return(0,r.jsx)(s.r,{className:e,"data-panel-expand":"",variant:"ghost",size:"small",layout:"iconOnly","aria-pressed":n.expanded,"aria-label":a,title:a,onClick:n.onToggle,children:(0,r.jsx)(l.In,{size:"16px",svg:n.expanded?lJ:lV})})}let l0={source:"Source",preview:"Preview",diff:"Diff"},l1={fontFamily:"var(--font-mono)",fontSize:13,lineHeight:1.6},l2={width:48,minWidth:48,padding:"0 10px",textAlign:"right",color:"var(--text-dim)",background:"var(--bg-panel)",borderRight:"1px solid var(--border)",fontFamily:"var(--font-mono)",fontSize:11,fontStyle:"normal",fontVariantNumeric:"tabular-nums",lineHeight:"20.8px",userSelect:"none",flexShrink:0,verticalAlign:"top"};function l4(){return(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"4"}),(0,r.jsx)("path",{d:"M16 8v5a3 3 0 0 0 6 0v-1a10 10 0 1 0-4 8"})]})}function l5(e){let t=e.nodeType===Node.ELEMENT_NODE?e:e.parentElement;return t?.closest(".file-source-line[data-line-number]")??null}function l6(e,t){if(!t||t.isCollapsed||0===t.rangeCount)return null;let n=t.getRangeAt(0);if(!e.contains(n.startContainer)||!e.contains(n.endContainer))return null;let r=l5(n.startContainer),i=l5(n.endContainer);if(!r||!i||!e.contains(r)||!e.contains(i))return null;let a=Number(r.dataset.lineNumber),s=Number(i.dataset.lineNumber);if(!Number.isInteger(a)||!Number.isInteger(s))return null;if(a<s){let e=r.querySelector(".file-source-line-content");if(e?.contains(n.startContainer)){let t=document.createRange();if(t.selectNodeContents(e),t.setStart(n.startContainer,n.startOffset),0===t.toString().length){let e=r.nextElementSibling;e instanceof HTMLElement&&e.matches(".file-source-line[data-line-number]")&&(a=Number((r=e).dataset.lineNumber))}}let t=i.querySelector(".file-source-line-content");if(t?.contains(n.endContainer)){let e=document.createRange();if(e.selectNodeContents(t),e.setEnd(n.endContainer,n.endOffset),0===e.toString().length){let e=i.previousElementSibling;e instanceof HTMLElement&&e.matches(".file-source-line[data-line-number]")&&(s=Number((i=e).dataset.lineNumber))}}}return a>s?null:{startLine:a,endLine:s}}function l8({rows:e,stylesheet:t,useInlineStyles:n,wrapLines:i}){return e.map((e,a)=>{let s=e.children??[],l=s[0]?.properties?.className,o=Array.isArray(l)&&l.includes("react-syntax-highlighter-line-number"),d=o?s[0]:null,c=o?s.slice(1):s;return(0,r.jsxs)("span",{className:"file-source-line","data-line-number":a+1,style:{display:"flex",minWidth:"100%"},children:[d&&(0,l_.Ay)({node:d,stylesheet:t,useInlineStyles:n,key:`source-line-number-${a}`}),(0,r.jsx)("span",{className:"file-source-line-content",style:{flex:"1 1 auto",minWidth:0,overflowWrap:i?"anywhere":"normal",whiteSpace:i?"pre-wrap":"pre"},children:c.map((e,r)=>(0,l_.Ay)({node:e,stylesheet:t,useInlineStyles:n,key:`source-token-${a}-${r}`}))})]},`source-line-${a}`)})}let l3=(0,i.memo)(function({content:e,language:t,isDark:n,wrapLines:i}){return(0,r.jsx)(te.A,{className:i?"file-source-view is-wrapped":"file-source-view",language:"text"===t?"plaintext":t,style:n?tt.xJ:tt.vs,showLineNumbers:!0,lineNumberStyle:{...l2},customStyle:{margin:0,padding:0,border:0,background:"var(--bg)",...l1,width:i?"100%":"max-content",minWidth:"100%",minHeight:"100%",overflow:"visible"},codeTagProps:{style:{fontFamily:"var(--font-mono)",overflowWrap:i?"anywhere":"normal"}},renderer:e=>(0,r.jsx)(l8,{...e,wrapLines:i}),wrapLongLines:i,children:e})});function l7(e,t,n,r={}){let i=ti(e),a=new URLSearchParams({type:t});for(let[e,t]of(n&&a.set("sessionId",n),Object.entries(r)))void 0!==t&&a.set(e,String(t));return`/api/files/${i}?${a.toString()}`}let l9=(0,r.jsxs)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),(0,r.jsx)("polyline",{points:"7 10 12 15 17 10"}),(0,r.jsx)("line",{x1:"12",y1:"15",x2:"12",y2:"3"})]}),oe=(0,r.jsxs)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M3 6h18"}),(0,r.jsx)("path",{d:"M3 12h15a3 3 0 1 1 0 6h-4"}),(0,r.jsx)("path",{d:"m16 16-2 2 2 2"}),(0,r.jsx)("path",{d:"M3 18h7"})]});function ot({filePath:e,cwd:t,sourceSessionId:n,meta:i,watching:a,viewSwitch:s,actions:l=[],downloadable:o=!0}){let{t:d}=(0,R.s)(),c=ta(e),u=ts(e,t),p=u.endsWith(c)?u.slice(0,u.length-c.length).replace(/[\\/]+$/,""):"",h=d(a?"panel.liveSync":"i18n.notWatching");return(0,r.jsx)(lX,{title:c,titleTooltip:`${u}
20
20
  ${i}`,titleAdornment:null===a?void 0:(0,r.jsx)("span",{className:"panel-header-live",role:"img","aria-label":h,"data-live":a?"true":"false",title:h}),subtitle:p||void 0,subtitleKind:"path",viewSwitch:s,actions:o?[...l,{id:"download",label:d("i18n.downloadFile"),icon:l9,href:l7(e,"download",n),download:c}]:l})}function on(e){return e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(1)} KB`:`${(e/1048576).toFixed(1)} MB`}function or({patch:e}){let t,{t:n}=(0,R.s)(),i=(t=nb(e))?t.flatMap(e=>e.rows.flatMap(e=>{if("hunk"===e.type)return[];if("context"===e.left.type&&"context"===e.right.type)return[{type:"unchanged",text:e.right.text,oldLineNo:e.left.lineNo,newLineNo:e.right.lineNo}];let t=[];return"removed"===e.left.type&&t.push({type:"removed",text:e.left.text,oldLineNo:e.left.lineNo,newLineNo:null}),"added"===e.right.type&&t.push({type:"added",text:e.right.text,oldLineNo:null,newLineNo:e.right.lineNo}),t})):[];if(!i.some(e=>"unchanged"!==e.type))return(0,r.jsx)("div",{style:{padding:"12px 16px",fontSize:12,color:"var(--text-dim)",fontFamily:"var(--font-mono)"},children:n("i18n.noChanges")});let a=new Set(i.flatMap((e,t)=>"unchanged"!==e.type?[t]:[])),s=new Set;for(let e of a)for(let t=Math.max(0,e-3);t<=Math.min(i.length-1,e+3);t++)s.add(t);let l=[],o=0;for(;o<i.length;)if(s.has(o)){let e=[];for(;o<i.length&&s.has(o);)e.push(i[o]),o++;l.push({hidden:!1,lines:e})}else{let e=0;for(;o<i.length&&!s.has(o);)e++,o++;l.push({hidden:!0,count:e})}return(0,r.jsx)("div",{className:"file-diff-view",style:{width:"max-content",minWidth:"100%",...l1},children:l.map((e,t)=>{if(e.hidden)return(0,r.jsxs)("div",{style:{padding:"2px 16px",color:"var(--text-dim)",background:"var(--bg-panel)",fontSize:11,borderTop:"1px solid var(--border)",borderBottom:"1px solid var(--border)"},children:["... ",e.count," unchanged lines ..."]},t);let n=e.lines.map((e,t)=>{let n="added"===e.type?"rgba(0,200,80,0.12)":"removed"===e.type?"rgba(240,60,60,0.14)":"transparent",i="added"===e.type?"+":"removed"===e.type?"-":" ",a="added"===e.type?"#4ade80":"removed"===e.type?"#f87171":"var(--text-dim)";return(0,r.jsxs)("div",{className:"file-diff-line",style:{display:"flex",minWidth:"100%",background:n,borderLeft:"added"===e.type?"3px solid #4ade80":"removed"===e.type?"3px solid #f87171":"3px solid transparent"},children:[(0,r.jsx)("span",{style:l2,children:"removed"===e.type?e.oldLineNo:e.newLineNo}),(0,r.jsx)("span",{style:{minWidth:16,padding:"0 6px",color:a,userSelect:"none",flexShrink:0,fontWeight:600},children:i}),(0,r.jsx)("span",{className:"file-diff-line-content",style:{flexShrink:0,padding:"0 8px 0 0",whiteSpace:"pre",color:"var(--text)"},children:e.text||"\xa0"})]},t)});return(0,r.jsx)("div",{children:n},t)})})}function oi({filePath:e,cwd:t,sourceSessionId:n}){let[a,s]=(0,i.useState)(!1),[l,o]=(0,i.useState)(0),[d,c]=(0,i.useState)(null),[u,p]=(0,i.useState)(null),[h,m]=(0,i.useState)(null),f=(0,i.useRef)(null),g=ta(e).toLowerCase().split(".").pop()??"";(0,i.useEffect)(()=>{o(0),c(null),p(null),m(null),s(!1),f.current&&(f.current.close(),f.current=null);let t=new EventSource(l7(e,"watch",n));return f.current=t,t.addEventListener("connected",()=>s(!0)),t.addEventListener("change",e=>{try{let t=JSON.parse(e.data);"number"==typeof t.size&&c(t.size)}catch{}o(e=>e+1)}),t.addEventListener("error",()=>s(!1)),t.onerror=()=>s(!1),()=>{t.close(),f.current=null}},[e,n]);let x=l7(e,"read",n,l?{v:l}:void 0),v=null!=d?on(d):null;return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,r.jsx)(ot,{filePath:e,cwd:t,sourceSessionId:n,watching:a,meta:[g||"image",u?`${u.w} \xd7 ${u.h}`:null,v].filter(Boolean).join(" \xb7 ")}),(0,r.jsx)("div",{style:{flex:1,overflow:"auto",background:"var(--bg-panel)",display:"flex",alignItems:"center",justifyContent:"center",padding:16,backgroundImage:"linear-gradient(45deg, var(--bg) 25%, transparent 25%), linear-gradient(-45deg, var(--bg) 25%, transparent 25%), linear-gradient(45deg, transparent 75%, var(--bg) 75%), linear-gradient(-45deg, transparent 75%, var(--bg) 75%)",backgroundSize:"16px 16px",backgroundPosition:"0 0, 0 8px, 8px -8px, -8px 0px"},children:h?(0,r.jsx)("div",{style:{color:"#f87171",fontSize:13},children:h}):(0,r.jsx)("img",{src:x,alt:e,onLoad:e=>{let t=e.currentTarget;p({w:t.naturalWidth,h:t.naturalHeight})},onError:()=>m("Failed to load image"),style:{maxWidth:"100%",maxHeight:"100%",objectFit:"contain",boxShadow:"0 2px 8px rgba(0,0,0,0.15)"}})})]})}function oa({filePath:e,cwd:t,sourceSessionId:n}){let[a,s]=(0,i.useState)(!1),[l,o]=(0,i.useState)(0),[d,c]=(0,i.useState)(null),[u,p]=(0,i.useState)(null),[h,m]=(0,i.useState)(null),f=(0,i.useRef)(null),g=ta(e).toLowerCase().split(".").pop()??"";(0,i.useEffect)(()=>{o(0),c(null),p(null),m(null),s(!1),f.current&&(f.current.close(),f.current=null);let t=new EventSource(l7(e,"watch",n));return f.current=t,t.addEventListener("connected",()=>s(!0)),t.addEventListener("change",e=>{try{let t=JSON.parse(e.data);"number"==typeof t.size&&c(t.size)}catch{}p(null),m(null),o(e=>e+1)}),t.addEventListener("error",()=>s(!1)),t.onerror=()=>s(!1),()=>{t.close(),f.current=null}},[e,n]);let x=l7(e,"read",n,l?{v:l}:void 0);return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,r.jsx)(ot,{filePath:e,cwd:t,sourceSessionId:n,watching:a,meta:[g||"audio",null!=u?function(e){if(!Number.isFinite(e))return"";let t=Math.round(e),n=Math.floor(t/60);return`${n}:${String(t%60).padStart(2,"0")}`}(u):null,null!=d?on(d):null].filter(Boolean).join(" \xb7 ")}),(0,r.jsx)("div",{style:{flex:1,display:"flex",alignItems:"center",justifyContent:"center",padding:24,background:"var(--bg-panel)"},children:(0,r.jsxs)("div",{style:{width:"min(680px, 100%)"},children:[h&&(0,r.jsx)("div",{style:{color:"#f87171",fontSize:13,marginBottom:12,textAlign:"center"},children:h}),(0,r.jsx)("audio",{controls:!0,preload:"metadata",src:x,onLoadedMetadata:e=>p(e.currentTarget.duration),onError:()=>m("Failed to load audio"),style:{width:"100%"}},x)]})})]})}function os({filePath:e,cwd:t,sourceSessionId:n}){let{t:a}=(0,R.s)(),[s,l]=(0,i.useState)(!1),[o,d]=(0,i.useState)(0),[c,u]=(0,i.useState)(null),[p,h]=(0,i.useState)(null),m=(0,i.useRef)(null),f=eL(e),g="pdf"===f,x=g?l7(e,"read",n,o?{v:o}:void 0):l7(e,"preview",n,o?{v:o}:void 0);return(0,i.useEffect)(()=>{d(0),u(null),h(null),l(!1),m.current&&(m.current.close(),m.current=null),fetch(l7(e,"meta",n)).then(e=>e.json()).then(e=>{e.error&&h(e.error),"number"==typeof e.size&&(u(e.size),!g&&e.size>0xa00000&&h("DOCX too large for preview (>10MB)"))}).catch(e=>h(String(e)));let t=new EventSource(l7(e,"watch",n));return m.current=t,t.addEventListener("connected",()=>l(!0)),t.addEventListener("change",e=>{try{let t=JSON.parse(e.data);if("number"==typeof t.size&&(u(t.size),!g&&t.size>0xa00000))return void h("DOCX too large for preview (>10MB)")}catch{}h(null),d(e=>e+1)}),t.addEventListener("error",()=>l(!1)),t.onerror=()=>l(!1),()=>{t.close(),m.current=null}},[e,g,n]),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,r.jsx)(ot,{filePath:e,cwd:t,sourceSessionId:n,watching:s,meta:["docx"===f?"docx preview":"pdf",null!=c?on(c):null].filter(Boolean).join(" \xb7 ")}),(0,r.jsx)("div",{style:{flex:1,minHeight:0,background:"var(--bg-panel)"},children:p?(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",padding:24,color:"#f87171",fontSize:13,textAlign:"center"},children:p}):(0,r.jsx)("iframe",{src:x,sandbox:g?void 0:"allow-same-origin",title:a("i18n.previewFile",{file:ta(e)}),style:{width:"100%",height:"100%",border:"none",background:g?"var(--bg)":"#eef1f5"}},x)})]})}function ol({filePath:e,cwd:t,sourceSessionId:n,onOpenFile:i,onMentionLines:a,onAtMention:s,gitRefreshKey:l,initialDisplayMode:o,viewStateStore:d,viewStateKey:c}){let u;return eA(e)?(0,r.jsx)(oi,{filePath:e,cwd:t,sourceSessionId:n}):null!==(eE[eL(e)]??null)?(0,r.jsx)(oa,{filePath:e,cwd:t,sourceSessionId:n}):null!==("pdf"===(u=eL(e))||"docx"===u?u:null)?(0,r.jsx)(os,{filePath:e,cwd:t,sourceSessionId:n}):(0,r.jsx)(oo,{filePath:e,cwd:t,sourceSessionId:n,onOpenFile:i,onMentionLines:a,onAtMention:s,gitRefreshKey:l,initialDisplayMode:o,viewStateStore:d,viewStateKey:c})}function oo({filePath:e,cwd:t,sourceSessionId:n,onOpenFile:a,onMentionLines:s,onAtMention:l,gitRefreshKey:o,initialDisplayMode:d,viewStateStore:c,viewStateKey:u}){let p,h,{isDark:m}=tB(),{t:f}=(0,R.s)(),g=u?c?.get(u):void 0,x=(0,i.useCallback)(e=>{c&&u&&c.set(u,{...c.get(u),...e})},[u,c]),v=g?.mode,[b,y]=(0,i.useState)(null),[w,k]=(0,i.useState)(null),[j,S]=(0,i.useState)(!1),[C,N]=(0,i.useState)(!0),[I,T]=(0,i.useState)(null),[M,$]=(0,i.useState)("source"),[E,L]=(0,i.useState)(!1),[A,z]=(0,i.useState)(!1),P=(0,i.useRef)(null),W=(0,i.useRef)(0),F=(0,i.useRef)(null),[_,D]=(0,i.useState)(null),O=(0,i.useCallback)(e=>fetch(l7(e,"read",n)).then(e=>e.json()).then(e=>e.error?(T(e.error),null):(T(null),y(e),e)).catch(e=>(T(String(e)),null)),[n]),H=(0,i.useCallback)(async e=>{let n=++W.current;if(S(!0),!t){k(null),S(!1);return}try{let r=new URLSearchParams({cwd:t,path:e}),i=await fetch(`/api/git/diff?${r.toString()}`),a=await i.json();if(n!==W.current)return;k(i.ok&&a.supported&&"string"==typeof a.patch?a:null)}catch{n===W.current&&k(null)}finally{n===W.current&&S(!1)}},[t]);(0,i.useEffect)(()=>{N(!0),T(null),y(null),k(null),$("source"),L(!1),z(!1),P.current&&(P.current.close(),P.current=null),O(e).finally(()=>N(!1));let t=new EventSource(l7(e,"watch",n));return P.current=t,t.addEventListener("connected",()=>{z(!0)}),t.addEventListener("change",()=>{O(e),H(e)}),t.addEventListener("error",()=>{z(!1)}),t.onerror=()=>{z(!1)},()=>{t.close(),P.current=null}},[e,O,H,n]),(0,i.useEffect)(()=>{H(e)},[H,e,o]),(0,i.useEffect)(()=>{let e=b?.language==="markdown"||b?.language==="html";if(v){"preview"===v&&e&&$("preview");return}e&&"diff"!==d&&$("preview")},[b?.language,d,v]);let B=w?.supported===!0&&"string"==typeof w.patch,U=B&&"deleted"===w.status;(0,i.useEffect)(()=>{B||"diff"!==M||$("source")},[M,B]),(0,i.useEffect)(()=>{U&&P.current&&(P.current.close(),P.current=null,z(!1))},[U]);let q=(0,i.useRef)(!1);(0,i.useEffect)(()=>{q.current=!1},[e]),(0,i.useEffect)(()=>{(v?"diff"===v:"diff"===d)&&B&&!q.current&&(q.current=!0,$("diff"))},[d,B,v]);let K=(0,i.useRef)(!1);(0,i.useEffect)(()=>{K.current=!1},[u]);let V=g?.scrollTop;(0,i.useEffect)(()=>{if(K.current||!b)return;if(!V){K.current=!0;return}if(v&&M!==v)return;let e=requestAnimationFrame(()=>{let e=F.current;e&&(e.scrollTop=V,K.current=!0)});return()=>cancelAnimationFrame(e)},[b,M,v,V]);let J=(0,i.useMemo)(()=>b?.language==="markdown"?tf(b.content):"",[b]),G=(0,i.useMemo)(()=>b?.language==="markdown"?function(e){let t=function(e){let t=lO.exec(e);if(!t)return null;let n=/^---[ \t]*(?:(?:\r\n|\n|\r)|$)/gm;n.lastIndex=t[0].length;let r=n.exec(e);return r?{yaml:e.slice(t[0].length,r.index).replace(/(?:\r\n|\n|\r)$/,""),rest:e.slice(r.index+r[0].length)}:null}(e);if(!t)return{data:null,rest:e};try{let e=(0,lD.Hh)(t.yaml);if(e&&"object"==typeof e&&!Array.isArray(e))return{data:e,rest:t.rest}}catch{}return{data:null,rest:t.rest}}(b.content):null,[b]);(0,i.useEffect)(()=>{let e=()=>{let e=F.current,t=s&&"source"===M&&e?l6(e,window.getSelection()):null;D(e=>e?.startLine===t?.startLine&&e?.endLine===t?.endLine?e:t)};if(e(),s&&"source"===M)return document.addEventListener("selectionchange",e),()=>document.removeEventListener("selectionchange",e)},[b?.content,M,s]);let Y=(0,i.useCallback)(n=>{s&&n&&s(ts(e,t),n.startLine,n.endLine)},[t,e,s]);if((0,i.useEffect)(()=>{if(!s||"source"!==M)return;let e=e=>{if(e.repeat||"i"!==e.key.toLowerCase()||!e.metaKey&&!e.ctrlKey||e.altKey||e.shiftKey)return;let t=e.target;if(t instanceof Element&&t.closest("input, textarea, [contenteditable='true']"))return;let n=F.current,r=n?l6(n,window.getSelection()):null;r&&(e.preventDefault(),Y(r))};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[M,Y,s]),C||"diff"===d&&j&&!b)return(0,r.jsxs)("div",{className:"file-viewer-shell",style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,r.jsx)(ot,{filePath:e,cwd:t,sourceSessionId:n,meta:f("i18n.loading"),watching:null,downloadable:!1}),(0,r.jsx)("div",{role:"status",style:{flex:1,display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-muted)",fontSize:13},children:f("i18n.loading")})]});if(I&&!U)return(0,r.jsxs)("div",{className:"file-viewer-shell",style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,r.jsx)(ot,{filePath:e,cwd:t,sourceSessionId:n,meta:I,watching:null,downloadable:!1}),(0,r.jsx)("div",{role:"alert",style:{flex:1,display:"flex",alignItems:"center",justifyContent:"center",color:"var(--danger)",fontSize:13},children:I})]});if(!b&&!U)return null;let Z=b?.language??"text",X=b?.content??"",Q="html"===Z,ee="markdown"===Z,et=(h=(p=tr(e).replace(/\/+$/,"")).lastIndexOf("/"))<0?"":0===h?"/":2===h&&/^[a-zA-Z]:\//.test(p)?p.slice(0,3):p.slice(0,h),en=X.split("\n"),er=U?"diff":M,ei=U?["diff"]:["source",...Q||ee?["preview"]:[],...B?["diff"]:[]],ea=U?f("files.deleted"):`${Z} \xb7 ${en.length} lines \xb7 ${on(b.size)}`;return(0,r.jsxs)("div",{className:"file-viewer-shell",style:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden"},children:[(0,r.jsx)(ot,{filePath:e,cwd:t,sourceSessionId:n,meta:ea,watching:U?null:A,downloadable:!U,viewSwitch:{label:f("i18n.fileViewMode"),value:er,options:ei.map(e=>({value:e,label:l0[e],title:"diff"===e?f("i18n.compareHead"):void 0})),onChange:e=>{$(e),x({mode:e})}},actions:[...l||s?[{id:"mention",label:f("files.mention"),icon:(0,r.jsx)(l4,{}),onPointerDown:e=>e.preventDefault(),onClick:()=>{_&&s?Y(_):l?.(ts(e,t),!1)},title:_&&s?`${f("i18n.mentionSelectedLines")} (L${_.startLine}${_.startLine!==_.endLine?`-L${_.endLine}`:""})`:f("files.insertPath")}]:[],..."source"===er?[{id:"wrap",label:E?f("i18n.disableWrap"):f("i18n.enableWrap"),icon:oe,pressed:E,onClick:()=>L(e=>!e)}]:[]]}),(0,r.jsx)("div",{ref:F,className:"file-viewer-content",style:{flex:1,overflow:"auto",background:"var(--bg)"},onScroll:e=>x({scrollTop:e.currentTarget.scrollTop}),children:"diff"===er&&B?(0,r.jsx)(or,{patch:w.patch}):Q&&"preview"===er?(0,r.jsx)("iframe",{srcDoc:X,sandbox:"allow-scripts",style:{width:"100%",height:"100%",border:"none",background:"var(--bg)"},title:f("i18n.htmlPreview")}):ee&&"preview"===er?(0,r.jsxs)("div",{className:"markdown-body markdown-file-preview",style:{padding:"24px 32px"},children:[G?.data&&(0,r.jsx)(lU,{data:G.data}),(0,r.jsx)(tn.oz,{remarkPlugins:ty,rehypePlugins:tk,components:{code({className:e,children:t,...n}){let i=e?.replace("language-","").toLowerCase()??"",a=String(t);return e?.includes("language-")||a.includes("\n")?"mermaid"===i?(0,r.jsx)(tK,{code:a.replace(/\n$/,""),defaultPreview:!0}):(0,r.jsx)(tJ,{code:a.replace(/\n$/,""),lang:i}):(0,r.jsx)("code",{className:e,...n,children:t})},pre:({children:e})=>(0,r.jsx)(r.Fragment,{children:e}),a({href:e,children:n,...i}){delete i.node;let s=a?e6(e,et,t??et):null;return s&&a?(0,r.jsx)("a",{href:e,...i,onClick:e=>{e.defaultPrevented||0!==e.button||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey||(e.preventDefault(),a(s))},children:n}):(0,r.jsx)("a",{href:e,...i,children:n})},img({src:e,alt:i,...a}){delete a.node;let s="string"==typeof e?e6(e,et,t??et):null,l=s?l7(s,"read",n):e;return(0,r.jsx)("img",{src:l,alt:i??"",loading:"lazy",...a})},table:({children:e})=>(0,r.jsx)("div",{className:"markdown-table-wrap",children:(0,r.jsx)("table",{children:e})})},children:J})]}):(0,r.jsx)(l3,{content:X,language:Z,isDark:m,wrapLines:E})})]})}function od({tabs:e,activeTabId:t,onSelectTab:n,onCloseTab:a}){let{t:s,locale:l}=(0,R.s)(),[o,d]=(0,i.useState)(null);return(0,r.jsx)("div",{className:"file-tab-list",role:"tablist","aria-label":"ko"===l?"열린 파일 탭":"Open file tabs",style:{display:"flex",alignItems:"flex-end",overflowX:"auto",flexShrink:0,height:36},children:e.map(e=>{let i=e.id===t;return(0,r.jsxs)("div",{className:`file-tab${i?" is-active":""}`,role:"presentation",onMouseDown:e=>{1===e.button&&e.preventDefault()},onAuxClick:t=>{1===t.button&&(t.preventDefault(),t.stopPropagation(),a(e.id))},style:{display:"flex",alignItems:"center",height:36,paddingRight:6,borderRight:"1px solid var(--border)",fontSize:12,whiteSpace:"nowrap",maxWidth:180,minWidth:80,flexShrink:0,userSelect:"none",transition:"background 0.1s, color 0.1s"},children:[(0,r.jsxs)("button",{type:"button",role:"tab","aria-selected":i,onClick:()=>n(e.id),title:e.filePath,style:{display:"flex",alignItems:"center",gap:6,flex:1,minWidth:0,height:"100%",padding:"0 0 0 12px",border:"none",background:"none",color:"inherit",font:"inherit",textAlign:"left",cursor:"pointer"},children:[(0,r.jsx)("span",{style:{flexShrink:0,opacity:i?1:.7,display:"flex",alignItems:"center"},children:nI(e.label,13)}),(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",flex:1,fontWeight:i?500:400},children:e.label})]}),(0,r.jsx)("button",{className:"file-tab-close",onClick:t=>{t.stopPropagation(),a(e.id)},onMouseEnter:()=>d(e.id),onMouseLeave:()=>d(null),style:{display:"flex",alignItems:"center",justifyContent:"center",width:24,height:24,background:o===e.id?"var(--bg-hover)":"transparent",border:"none",color:o===e.id?"var(--text)":"var(--text-dim)",cursor:"pointer",padding:0,flexShrink:0,transition:"background 0.1s, color 0.1s"},title:s("i18n.close"),"aria-label":`${s("i18n.close")} ${e.label}`,children:(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("line",{x1:"2",y1:"2",x2:"8",y2:"8"}),(0,r.jsx)("line",{x1:"8",y1:"2",x2:"2",y2:"8"})]})})]},e.id)})})}let oc=["inherit","off","auto","minimal","low","medium","high","xhigh","max"],ou=new Set(oc);function op(e){return void 0!==e&&ou.has(e)}function oh(e){if(!e)return[...oc];let t=new Set(e);return oc.filter(e=>"inherit"===e||"off"===e||"auto"===e||t.has(e))}function om(e){if(!e)return"inherit";let t=e.lastIndexOf(":"),n=t>=0?e.slice(t+1):void 0;return op(n)?n:"inherit"}function of(e,t){let n=e.lastIndexOf(":"),r=op(n>=0?e.slice(n+1):void 0)?e.slice(0,n):e;return"inherit"===t?r:`${r}:${t}`}var og=n(98795),ox=n.n(og);function ov(e){return e.normalize("NFD").replace(/[\u0300-\u036f]/g,"").toLocaleLowerCase()}function ob({value:e,options:t,onChange:n,disabled:a=!1,placeholder:s="Select…",searchPlaceholder:l="Search options…",noResultsLabel:o="No matching options",ariaLabel:d,className:c,style:u}){let p=(0,i.useRef)(null),h=(0,i.useRef)(null),m=(0,i.useRef)(null),f=(0,i.useRef)([]),[g,x]=(0,i.useState)(!1),[v,b]=(0,i.useState)(""),[y,w]=(0,i.useState)(0),k=(0,i.useId)(),j=t.find(t=>t.value===e),S=(0,i.useMemo)(()=>{let e=ov(v.trim());return e?t.filter(t=>ov(`${t.label} ${t.value} ${t.searchText??""}`).includes(e)):t},[t,v]);(0,i.useEffect)(()=>{if(!g)return;let e=e=>{p.current?.contains(e.target)||x(!1)};return document.addEventListener("pointerdown",e),()=>document.removeEventListener("pointerdown",e)},[g]),(0,i.useEffect)(()=>{g?requestAnimationFrame(()=>m.current?.focus()):b("")},[g]),(0,i.useEffect)(()=>{if(!g)return;let t=S.findIndex(t=>t.value===e&&!t.disabled);w(t>=0?t:Math.max(0,S.findIndex(e=>!e.disabled)))},[S,g,e]),(0,i.useEffect)(()=>{(y>=S.length||S[y]?.disabled)&&w(Math.max(0,S.findIndex(e=>!e.disabled)))},[y,S]),(0,i.useEffect)(()=>{g&&f.current[y]?.scrollIntoView({block:"nearest"})},[y,g]);let{side:C,maxHeight:N}=a3(p,g,{viewportFraction:.6,cap:296,gap:5,prefer:"below",minHeight:160}),I=e=>{e.disabled||(n(e.value),x(!1))},T=e=>{if(!S.length)return;let t=y;for(let n=0;n<S.length;n+=1)if(t=(t+e+S.length)%S.length,!S[t].disabled)return void w(t)};return(0,r.jsxs)("div",{ref:p,className:`${ox().root}${c?` ${c}`:""}`,style:u,children:[(0,r.jsxs)("button",{ref:h,type:"button",className:ox().trigger,disabled:a,"aria-label":d,"aria-haspopup":"listbox","aria-expanded":g,"aria-controls":g?k:void 0,onClick:()=>x(e=>!e),onKeyDown:e=>{("ArrowDown"===e.key||"ArrowUp"===e.key)&&(e.preventDefault(),x(!0))},children:[(0,r.jsx)("span",{className:j?ox().value:ox().placeholder,children:j?.label??(e||s)}),(0,r.jsx)("svg",{className:ox().chevron,viewBox:"0 0 12 12","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m3 4.5 3 3 3-3"})})]}),g&&(0,r.jsxs)("div",{className:ox().popover,style:"above"===C?{bottom:"calc(100% + 5px)",maxHeight:N}:{top:"calc(100% + 5px)",maxHeight:N},"data-dismissible-layer":"searchable-select",onKeyDown:e=>{"Escape"===e.key&&(e.preventDefault(),e.stopPropagation(),x(!1),h.current?.focus())},children:[(0,r.jsxs)("div",{className:ox().searchWrap,children:[(0,r.jsxs)("svg",{className:ox().searchIcon,viewBox:"0 0 16 16","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"7",cy:"7",r:"4.25"}),(0,r.jsx)("path",{d:"m10.2 10.2 3.1 3.1"})]}),(0,r.jsx)("input",{ref:m,className:ox().search,value:v,placeholder:l,"aria-label":l,role:"combobox","aria-expanded":"true","aria-controls":k,"aria-activedescendant":S[y]?`${k}-${y}`:void 0,autoComplete:"off",spellCheck:!1,onChange:e=>{b(e.target.value),w(0)},onKeyDown:e=>{if("ArrowDown"===e.key)e.preventDefault(),T(1);else if("ArrowUp"===e.key)e.preventDefault(),T(-1);else if("Enter"===e.key){e.preventDefault();let t=S[y];t&&I(t)}else"Tab"===e.key&&x(!1)}})]}),(0,r.jsx)("div",{id:k,className:ox().options,role:"listbox","aria-label":d,style:{maxHeight:Math.max(0,N-46)},children:S.length?S.map((t,n)=>(0,r.jsxs)("button",{ref:e=>{f.current[n]=e},id:`${k}-${n}`,type:"button",role:"option","aria-selected":t.value===e,className:ox().option,"data-active":n===y,"data-selected":t.value===e,disabled:t.disabled,onMouseEnter:()=>w(n),onClick:()=>I(t),children:[(0,r.jsxs)("span",{className:ox().optionCopy,children:[(0,r.jsx)("span",{className:ox().optionLabel,children:t.label}),t.description&&(0,r.jsx)("span",{className:ox().optionDescription,children:t.description})]}),t.value===e&&(0,r.jsx)("svg",{className:ox().check,viewBox:"0 0 12 12","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m2.3 6.2 2.2 2.2 5.2-5.2"})})]},t.value)):(0,r.jsx)("div",{className:ox().empty,children:o})})]})]})}let oy=["global","project"],ow=["implSonnet","implOpus","implDeepSeek","makerHardUiOpus","makerHardCodeOpus","makerHardCodeSonnet"];function ok(e){return`${e.provider}/${e.id}`}function oj({cwd:e,onRolesChanged:t}){let{t:n}=(0,R.s)(),[a,s]=(0,i.useState)([]),[l,o]=(0,i.useState)([]),[d,c]=(0,i.useState)({}),[u,p]=(0,i.useState)("global"),[h,m]=(0,i.useState)(!0),[f,g]=(0,i.useState)(null),[x,v]=(0,i.useState)(null),b=(0,i.useCallback)(async t=>{if(!e){s([]),o([]),c({}),m(!1);return}m(!0),g(null);try{let n=`?cwd=${encodeURIComponent(e)}`,[r,i]=await Promise.all([fetch(`/api/model-roles${n}`,t?{signal:t}:void 0),fetch(`/api/models${n}`,t?{signal:t}:void 0)]);if(!r.ok)throw Error(`HTTP ${r.status}`);let a=await r.json();if(a.error)throw Error(a.error);if(!i.ok)throw Error(`HTTP ${i.status}`);let l=await i.json();s(a.roles??[]),o(l.modelList??[]),c(l.thinkingLevels??{})}catch(e){if("AbortError"===e.name)return;g(e instanceof Error?e.message:String(e))}finally{m(!1)}},[e]);(0,i.useEffect)(()=>{let e=new AbortController;return b(e.signal),()=>e.abort()},[b]);let y=(0,i.useCallback)(async(n,r)=>{if(e){v(n),g(null);try{let i=await fetch("/api/model-roles",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e,role:n,selector:r,scope:u})}),a=await i.json();if(!i.ok||a.error)throw Error(a.error??`HTTP ${i.status}`);s(a.roles??[]),t?.()}catch(e){g(e instanceof Error?e.message:String(e))}finally{v(null)}}},[e,u,t]),w=(0,i.useMemo)(()=>a.filter(e=>!e.hidden),[a]),k=w.some(e=>ow.includes(e.role)&&!e.selector);return e?(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:14},children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{style:{fontSize:13,fontWeight:700,color:"var(--text)",marginBottom:4},children:n("roles.title")}),(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:n("roles.description")}),!h&&k&&(0,r.jsx)("div",{style:{fontSize:11,color:"var(--text-dim)",lineHeight:1.5,marginTop:4},children:n("roles.harnessNote")})]}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:8},children:[(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-muted)"},children:n("roles.scope")}),(0,r.jsx)("div",{style:{display:"flex",flexShrink:0,border:"1px solid var(--border)",borderRadius:6,overflow:"hidden"},children:oy.map(e=>(0,r.jsx)("button",{onClick:()=>p(e),style:{padding:"4px 10px",border:"none",background:u===e?"var(--bg-selected)":"transparent",color:u===e?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:11,fontWeight:u===e?600:400},children:"global"===e?n("roles.scopeGlobal"):n("roles.scopeProject")},e))}),(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-muted)",fontFamily:"var(--font-mono)"},children:"global"===u?"~/.omp/agent/config.yml":".omp/config.yml"})]}),f&&(0,r.jsx)("div",{style:{fontSize:12,color:"var(--danger, #ff4757)"},children:f}),h?(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text-muted)"},children:n("i18n.loading")}):(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:w.map(e=>{let t=e.resolved?`${e.resolved.provider}/${e.resolved.modelId}`:of(e.selector??"","inherit"),i=om(e.selector),a=oh(d[e.resolved?`${e.resolved.provider}:${e.resolved.modelId}`:""]),s=ow.includes(e.role);return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:8,padding:"8px 10px",border:"1px solid var(--border)",borderRadius:7,background:"var(--bg-panel)"},children:[(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:10,rowGap:6},children:[(0,r.jsx)("span",{style:{flexShrink:0,minWidth:62,padding:"2px 6px",borderRadius:4,border:"1px solid var(--border)",background:"var(--bg-subtle)",color:"var(--accent)",fontFamily:"var(--font-mono)",fontSize:9.5,fontWeight:700,letterSpacing:"0.06em",textAlign:"center"},children:e.tag??e.role.toUpperCase()}),(0,r.jsxs)("div",{style:{minWidth:0,flex:"0 0 auto",width:128},children:[(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text)",fontWeight:600},children:e.name}),s&&(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-muted)",lineHeight:1.35},children:n(`roles.harness.${e.role}`)}),(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)"},children:s&&!e.selector?n("roles.harnessUnset"):n(`roles.source.${e.source}`)})]}),(0,r.jsx)(ob,{value:t,disabled:x===e.role,ariaLabel:e.name,style:{flex:"1 1 160px",minWidth:0},onChange:t=>{if(!t)return void y(e.role,null);let n=l.find(e=>ok(e)===t),r=n?d[`${n.provider}:${n.id}`]:void 0,i=om(e.selector),a=oh(r).includes(i)?i:"inherit";y(e.role,of(t,a))},options:[{value:"",label:n("roles.unset")},...l.map(e=>({value:ok(e),label:`${e.name} — ${e.provider}`,searchText:ok(e)})),...t&&!l.some(e=>ok(e)===t)?[{value:t,label:t}]:[]]}),e.warning&&(0,r.jsx)("span",{title:e.warning,style:{color:"var(--warning, #ffb347)",fontSize:12},children:"!"})]}),e.resolved&&(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap",paddingLeft:72},children:[(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:10,whiteSpace:"nowrap"},children:n("roles.thinking")}),(0,r.jsx)("div",{role:"group","aria-label":`${e.name} ${n("roles.thinking")}`,style:{display:"flex",flex:"1 1 auto",minWidth:0,flexWrap:"wrap",gap:3},children:a.map(a=>{let s=i===a;return(0,r.jsx)("button",{type:"button","aria-pressed":s,disabled:x===e.role,title:"inherit"===a?n("roles.thinkingInherit"):a,onClick:()=>{s||y(e.role,of(t,a))},style:{padding:"3px 7px",border:`1px solid ${s?"var(--accent)":"var(--border)"}`,borderRadius:4,background:s?"var(--bg-selected)":"transparent",color:s?"var(--accent)":"var(--text-muted)",cursor:x===e.role?"not-allowed":"pointer",fontFamily:"var(--font-mono)",fontSize:10,fontWeight:s?700:500,lineHeight:1.2,opacity:x===e.role?.55:1},children:a},a)})})]})]},e.role)})})]}):(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text-muted)"},children:n("roles.needsProject")})}function oS(e){window.open(e,"_blank","noopener,noreferrer")}var oC=n(67381),oN=n(64433),oI=n(70350),oT=n(88195),oM=n(9312),o$=n(87275),oR=n(22008),oE=n(95476),oL=n(35029),oA=n(14489),oz=n(78728),oP=n(19872),oW=n(7751),oF=n(92526),o_=n(48238),oD=n(57794),oO=n(41098),oH=n(84604),oB=n(15315),oU=n(74278),oq=n(55457),oK=n(71437),oV=n(29167),oJ=n(97283),oG=n(34166),oY=n(33889),oZ=n(85486),oX=n(74068),oQ=n(83546),o0=n(83709);let o1={anthropic:{Icon:oC.A,hasColor:!1},openai:{Icon:oN.A,hasColor:!1},"openai-codex":{Icon:oN.A,hasColor:!1},google:{Icon:oI.A,hasColor:!0},"google-vertex":{Icon:oI.A,hasColor:!0},"ant-ling":{Icon:oY.A,hasColor:!0},deepseek:{Icon:oT.A,hasColor:!0},groq:{Icon:oM.A,hasColor:!1},mistral:{Icon:o$.A,hasColor:!0},moonshotai:{Icon:oR.A,hasColor:!1},"moonshotai-cn":{Icon:oR.A,hasColor:!1},moonshot:{Icon:oR.A,hasColor:!1},minimax:{Icon:oE.A,hasColor:!0},"minimax-cn":{Icon:oE.A,hasColor:!0},fireworks:{Icon:oL.A,hasColor:!0},huggingface:{Icon:oA.A,hasColor:!0},cerebras:{Icon:oz.A,hasColor:!0},openrouter:{Icon:oP.A,hasColor:!1},xai:{Icon:oW.A,hasColor:!1},"cloudflare-ai-gateway":{Icon:oF.A,hasColor:!0},"cloudflare-workers-ai":{Icon:oF.A,hasColor:!0},"vercel-ai-gateway":{Icon:o_.A,hasColor:!1},"github-copilot":{Icon:oD.A,hasColor:!1},"amazon-bedrock":{Icon:oO.A,hasColor:!0},"azure-openai-responses":{Icon:oH.A,hasColor:!0},"kimi-coding":{Icon:oB.A,hasColor:!0},nvidia:{Icon:oZ.A,hasColor:!0},opencode:{Icon:oX.A,hasColor:!1},"opencode-go":{Icon:oX.A,hasColor:!1},qwen:{Icon:oU.A,hasColor:!0},xiaomi:{Icon:oQ.A,hasColor:!1},"xiaomi-token-plan-ams":{Icon:oQ.A,hasColor:!1},"xiaomi-token-plan-cn":{Icon:oQ.A,hasColor:!1},"xiaomi-token-plan-sgp":{Icon:oQ.A,hasColor:!1},zai:{Icon:o0.A,hasColor:!1},"zai-coding-cn":{Icon:o0.A,hasColor:!1},zhipu:{Icon:oq.A,hasColor:!0},cohere:{Icon:oK.A,hasColor:!0},perplexity:{Icon:oV.A,hasColor:!0},together:{Icon:oJ.A,hasColor:!0},grok:{Icon:oG.A,hasColor:!1}},o2=["openai-completions","openai-responses","anthropic-messages","google-generative-ai"];function o4({label:e,children:t}){return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[(0,r.jsx)("label",{style:{fontSize:11,color:"var(--text-muted)",fontWeight:500},children:e}),t]})}let o5={padding:"6px 9px",background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:5,color:"var(--text)",fontSize:12,outline:"none",width:"100%",boxSizing:"border-box"};function o6({value:e,onChange:t,placeholder:n,mono:i}){return(0,r.jsx)("input",{value:e,onChange:e=>t(e.target.value),placeholder:n,style:{...o5,fontFamily:i?"var(--font-mono)":"inherit"}})}function o8({value:e,onChange:t,placeholder:n,mono:a,onKeyDown:s,autoComplete:l="off",spellCheck:o=!1,style:d}){let[c,u]=(0,i.useState)(!1),{t:p}=(0,R.s)();return(0,i.useEffect)(()=>{e||u(!1)},[e]),(0,r.jsxs)("div",{style:{position:"relative",width:"100%",...d},children:[(0,r.jsx)("input",{type:c?"text":"password",value:e,onChange:e=>t(e.target.value),onKeyDown:s,placeholder:n,style:{...o5,paddingRight:34,fontFamily:a?"var(--font-mono)":"inherit"},autoComplete:l,spellCheck:o}),(0,r.jsx)("button",{type:"button",onClick:()=>u(e=>!e),"aria-label":p(c?"i18n.hideDetails":"i18n.showDetails"),title:p(c?"i18n.hideDetails":"i18n.showDetails"),style:{position:"absolute",right:5,top:"50%",transform:"translateY(-50%)",width:24,height:24,padding:0,border:"none",background:"transparent",color:"var(--text-dim)",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center"},children:c?(0,r.jsxs)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("path",{d:"M17.94 17.94A10.94 10.94 0 0 1 12 20C7 20 2.73 16.89 1 12a18.45 18.45 0 0 1 5.06-6.94"}),(0,r.jsx)("path",{d:"M9.9 4.24A10.94 10.94 0 0 1 12 4c5 0 9.27 3.11 11 8a18.5 18.5 0 0 1-2.16 3.19"}),(0,r.jsx)("path",{d:"M14.12 14.12A3 3 0 0 1 9.88 9.88"}),(0,r.jsx)("path",{d:"M1 1l22 22"})]}):(0,r.jsxs)("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("path",{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8S1 12 1 12Z"}),(0,r.jsx)("circle",{cx:"12",cy:"12",r:"3"})]})})]})}function o3({value:e,onChange:t,placeholder:n}){return(0,r.jsx)("input",{type:"number",value:e,onChange:e=>t(e.target.value),placeholder:n,style:o5})}function o7({value:e,onChange:t,options:n,required:i}){let{t:a}=(0,R.s)();return(0,r.jsx)(ob,{value:e,onChange:t,options:[...i?[]:[{value:"",label:`— ${a("i18n.default")} / none —`}],...n.map(e=>({value:e,label:e}))]})}function o9({label:e,checked:t,onChange:n}){return(0,r.jsxs)("label",{style:{display:"flex",alignItems:"center",gap:6,cursor:"pointer",fontSize:12,color:"var(--text-muted)"},children:[(0,r.jsx)("input",{type:"checkbox",checked:t,onChange:e=>n(e.target.checked),style:{width:13,height:13,accentColor:"var(--accent)",cursor:"pointer"}}),e]})}function de({children:e}){return(0,r.jsx)("div",{style:{fontSize:11,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:2},children:e})}function dt({name:e,provider:t,onChange:n,onRename:a,onDelete:s,onAddModels:l}){let{t:o}=(0,R.s)(),[d,c]=(0,i.useState)(e),[u,p]=(0,i.useState)({phase:"idle"}),[h,m]=(0,i.useState)(""),[f,g]=(0,i.useState)([]),x=(0,i.useRef)(0),v=(0,i.useRef)(null);(0,i.useEffect)(()=>c(e),[e]);let b=(e,r)=>n({...t,[e]:r});(0,i.useEffect)(()=>{t.api||n({...t,api:"openai-completions"})},[t.api]),(0,i.useEffect)(()=>{x.current+=1,p({phase:"idle"}),m(""),g([])},[e,t.baseUrl,t.api,t.apiKey]);let y=(0,i.useCallback)(async()=>{if(!t.baseUrl?.trim()||"loading"===u.phase)return;let n=++x.current;p({phase:"loading"}),g([]);try{let r=await fetch("/api/models-config/discover",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({providerName:e,provider:{...t,models:void 0}})}),i=await r.json();if(n!==x.current)return;if(!r.ok||i.error||!i.models)return void p({phase:"error",message:i.error??`HTTP ${r.status}`});p({phase:"success",models:i.models,endpoint:i.endpoint??t.baseUrl})}catch(e){if(n!==x.current)return;p({phase:"error",message:e instanceof Error?e.message:String(e)})}},[u.phase,e,t]),w=new Set((t.models??[]).map(e=>e.id)),k="success"===u.phase?u.models:[],j=h.trim().toLocaleLowerCase(),S=k.filter(e=>!j||e.id.toLocaleLowerCase().includes(j)||e.name?.toLocaleLowerCase().includes(j)),C=S.slice(0,300),N=C.filter(e=>!w.has(e.id)).map(e=>e.id),I=f.filter(e=>!w.has(e)).length,T=N.length>0&&N.every(e=>f.includes(e)),M=!T&&N.some(e=>f.includes(e));return(0,i.useEffect)(()=>{v.current&&(v.current.indeterminate=M)},[M]),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[(0,r.jsx)(de,{children:o("i18n.provider")}),(0,r.jsx)("button",{onClick:s,style:{padding:"3px 8px",background:"none",border:"1px solid rgba(239,68,68,0.3)",borderRadius:4,color:"#ef4444",cursor:"pointer",fontSize:11},children:o("i18n.delete")})]}),(0,r.jsxs)(o4,{label:o("i18n.providerName"),children:[(0,r.jsx)(o6,{value:d,onChange:c,placeholder:"provider-name",mono:!0}),d!==e&&d.trim()&&(0,r.jsx)("button",{onClick:()=>a(d.trim()),style:{marginTop:4,padding:"3px 10px",background:"var(--seed-color-bg-neutral-inverted)",border:"none",borderRadius:4,color:"var(--seed-color-fg-neutral-inverted)",cursor:"pointer",fontSize:11,alignSelf:"flex-start"},children:o("i18n.rename")})]}),(0,r.jsx)(o4,{label:"Base URL",children:(0,r.jsx)(o6,{value:t.baseUrl??"",onChange:e=>b("baseUrl",e||void 0),placeholder:"https://api.example.com/v1",mono:!0})}),(0,r.jsxs)(o4,{label:"API Key",children:[(0,r.jsx)(o8,{value:t.apiKey??"",onChange:e=>b("apiKey",e||void 0),placeholder:"ENV_VAR_NAME, !shell-command, or literal key",mono:!0}),(0,r.jsxs)("span",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:["Prefix with ",(0,r.jsx)("code",{style:{fontFamily:"var(--font-mono)"},children:"!"})," to run a shell command, or use an env var name"]})]}),(0,r.jsx)(o4,{label:"API",children:(0,r.jsx)(o7,{value:t.api??"openai-completions",onChange:e=>b("api",e),options:o2,required:!0})}),(0,r.jsxs)(o4,{label:"Headers",children:[(0,r.jsx)(ds,{headers:t.headers,onChange:e=>b("headers",e)}),(0,r.jsx)("span",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:"Added to every request from this provider (e.g. User-Agent). Useful for gateways with bot detection."})]}),(0,r.jsxs)("div",{style:{borderTop:"1px solid var(--border)",paddingTop:14,display:"flex",flexDirection:"column",gap:10},children:["success"!==u.phase&&(0,r.jsx)("button",{onClick:y,disabled:!t.baseUrl?.trim()||"loading"===u.phase,style:{alignSelf:"flex-start",height:30,padding:"0 12px",border:"1px solid var(--border)",borderRadius:5,background:"var(--bg-panel)",color:t.baseUrl?.trim()&&"loading"!==u.phase?"var(--text-muted)":"var(--text-dim)",cursor:t.baseUrl?.trim()&&"loading"!==u.phase?"pointer":"not-allowed",fontSize:11},children:"loading"===u.phase?o("models.discoveryFetching"):o("models.discoveryFetch")}),"error"===u.phase&&(0,r.jsx)("div",{style:{padding:"7px 9px",border:"1px solid rgba(239,68,68,0.3)",borderRadius:5,color:"#ef4444",fontSize:11,lineHeight:1.4},children:u.message}),"success"===u.phase&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("input",{value:h,onChange:e=>m(e.target.value),placeholder:o("models.discoveryFilterPlaceholder",{count:u.models.length}),"aria-label":o("models.discoveryFilter"),style:{...o5,width:"100%",minWidth:0}}),(0,r.jsxs)("div",{style:{maxHeight:220,overflowY:"auto",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-panel)"},children:[(0,r.jsxs)("label",{style:{minHeight:32,padding:"5px 9px",display:"flex",alignItems:"center",gap:8,position:"sticky",top:0,zIndex:1,borderBottom:"1px solid var(--border)",background:"var(--bg)",cursor:N.length?"pointer":"default",color:"var(--text-muted)",fontSize:10,fontWeight:600},children:[(0,r.jsx)("input",{ref:v,type:"checkbox",checked:T,disabled:0===N.length,onChange:()=>{let e=new Set(N);g(t=>T?t.filter(t=>!e.has(t)):Array.from(new Set([...t,...N])))},style:{width:13,height:13,accentColor:"var(--accent)",flexShrink:0}}),o("models.discoverySelectShown")]}),0===C.length?(0,r.jsx)("div",{style:{padding:12,color:"var(--text-dim)",fontSize:11},children:o("models.discoveryNoMatches")}):C.map((e,t)=>{let n=w.has(e.id),i=f.includes(e.id);return(0,r.jsxs)("label",{style:{minHeight:36,padding:"6px 9px",display:"flex",alignItems:"center",gap:8,borderTop:0===t?"none":"1px solid var(--border)",cursor:n?"default":"pointer",opacity:n?.65:1},children:[(0,r.jsx)("input",{type:"checkbox",checked:i||n,disabled:n,onChange:()=>{var t;return t=e.id,void g(e=>e.includes(t)?e.filter(e=>e!==t):[...e,t])},style:{width:13,height:13,accentColor:"var(--accent)",flexShrink:0}}),(0,r.jsxs)("span",{style:{minWidth:0,flex:1},children:[(0,r.jsx)("span",{style:{display:"block",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text)",fontSize:11},children:e.name??e.id}),e.name&&(0,r.jsx)("code",{style:{display:"block",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-dim)",fontSize:10,fontFamily:"var(--font-mono)"},children:e.id})]}),n&&(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:10},children:o("models.discoveryAdded")})]},e.id)})]}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:10},children:[(0,r.jsx)("span",{title:u.endpoint,style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-dim)",fontSize:10},children:S.length>C.length?o("models.discoveryShowing",{shown:C.length,total:S.length}):o("models.discoveryFetched",{count:u.models.length})}),(0,r.jsx)("button",{onClick:()=>{if("success"!==u.phase)return;let e=new Set(f),t=u.models.filter(t=>e.has(t.id)&&!w.has(t.id));0!==t.length&&(l(t),g([]))},disabled:0===I,style:{height:28,padding:"0 11px",border:"none",borderRadius:5,background:I?"var(--seed-color-bg-neutral-inverted)":"var(--bg-panel)",color:I?"var(--seed-color-fg-neutral-inverted)":"var(--text-dim)",cursor:I?"pointer":"not-allowed",fontSize:11,fontWeight:600,whiteSpace:"nowrap"},children:I?o("models.discoveryAddSelectedCount",{count:I}):o("models.discoveryAddSelected")})]})]})]})]})}let dn=["off","minimal","low","medium","high","xhigh","max"],dr={off:"var(--text-dim)",minimal:"#6b7280",low:"#60a5fa",medium:"#a78bfa",high:"#f472b6",xhigh:"#fb923c",max:"#ef4444"};function di({value:e,onChange:t}){let n=e??{},i=(e,r)=>{let i={...n};"omit"===r?delete i[e]:i[e]=r,t(Object.keys(i).length?i:void 0)};return(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:2},children:dn.map(e=>{let t=n[e],a=e in n?null===t?"null":"string":"omit",s="string"==typeof t?t:"",l=dr[e],o={padding:"4px 10px",fontSize:10,border:"none",cursor:"pointer",fontWeight:400,transition:"background 0.1s, color 0.1s",whiteSpace:"nowrap",background:"var(--bg-panel)",color:"var(--text-dim)"},d={background:"var(--seed-color-bg-neutral-inverted)",color:"var(--seed-color-fg-neutral-inverted)",fontWeight:600};return(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"5px 4px",borderRadius:6,background:"transparent",border:"1px solid transparent"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:5,width:68,flexShrink:0},children:[(0,r.jsx)("span",{style:{width:6,height:6,borderRadius:"50%",background:l,flexShrink:0,opacity:"null"===a?.3:1}}),(0,r.jsx)("span",{style:{fontSize:11,fontFamily:"var(--font-mono)",color:"null"===a?"var(--text-dim)":"var(--text-muted)",textDecoration:"null"===a?"line-through":"none"},children:e})]}),(0,r.jsxs)("div",{style:{display:"flex",borderRadius:5,border:"1px solid var(--border)",overflow:"hidden",flexShrink:0},children:[(0,r.jsx)("button",{onClick:()=>i(e,"omit"),style:{...o,..."omit"===a?d:{}},children:"Default"}),(0,r.jsx)("button",{onClick:()=>i(e,null),style:{...o,borderLeft:"1px solid var(--border)",..."null"===a?{background:"#ef4444",color:"#fff",fontWeight:600}:{}},children:"Disabled"})]}),(0,r.jsxs)("div",{style:{display:"flex",borderRadius:5,border:`1px solid ${"string"===a?"var(--accent)":"var(--border)"}`,overflow:"hidden",transition:"border-color 0.1s"},children:[(0,r.jsx)("button",{onClick:()=>i(e,s||e),style:{...o,..."string"===a?d:{},borderRight:"1px solid var(--border)",flexShrink:0},children:"Custom"}),(0,r.jsx)("input",{value:s,onChange:t=>i(e,t.target.value),onFocus:()=>{"string"!==a&&i(e,s||e)},placeholder:e,maxLength:10,style:{width:"12ch",background:"string"===a?"var(--bg)":"var(--bg-panel)",border:"none",outline:"none",color:"string"===a?"var(--text)":"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:11,padding:"4px 7px",transition:"background 0.1s, color 0.1s"}})]})]},e)})})}let da={thinkingFormat:"deepseek",requiresReasoningContentOnAssistantMessages:!0};function ds({headers:e,onChange:t}){let[n,a]=(0,i.useState)(()=>Object.entries(e??{}).map(([e,t],n)=>({id:n,name:e,value:t}))),s=(0,i.useRef)(n.length),l=e=>{a(e),t(function(e){let t={};for(let n of e){let e=n.name.trim();e&&(t[e]=n.value)}return Object.keys(t).length?t:void 0}(e))},o=(e,t)=>{l(n.map(n=>n.id===e?{...n,...t}:n))},d={padding:"6px 9px",background:"none",border:"1px solid rgba(239,68,68,0.3)",borderRadius:4,color:"#ef4444",cursor:"pointer",fontSize:11,lineHeight:1};return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[n.map(e=>(0,r.jsxs)("div",{style:{display:"flex",gap:6},children:[(0,r.jsx)("input",{value:e.name,onChange:t=>o(e.id,{name:t.target.value}),placeholder:"Header-Name",style:{...o5,fontFamily:"var(--font-mono)",flex:1}}),(0,r.jsx)("input",{value:e.value,onChange:t=>o(e.id,{value:t.target.value}),placeholder:"value",style:{...o5,fontFamily:"var(--font-mono)",flex:1}}),(0,r.jsx)("button",{onClick:()=>{var t;return t=e.id,void l(n.filter(e=>e.id!==t))},style:d,children:"✕"})]},e.id)),(0,r.jsx)("button",{onClick:()=>a(e=>[...e,{id:s.current++,name:"",value:""}]),style:{padding:"5px 9px",background:"none",border:"1px solid var(--border)",borderRadius:4,color:"var(--text-muted)",cursor:"pointer",fontSize:11,display:"inline-flex",alignItems:"center",justifyContent:"center",gap:5,alignSelf:"flex-start"},children:"+ Add header"})]})}function dl({providerName:e,provider:t,model:n,onChange:a,onDelete:s}){let[l,o]=(0,i.useState)({phase:"idle"}),{t:d}=(0,R.s)(),[c,u]=(0,i.useState)({phase:"idle"}),p=(0,i.useRef)(0),h=(0,i.useRef)(null),m=(e,t)=>a({...n,[e]:t}),f=(()=>{if("idle"===l.phase)return null;if("testing"===l.phase)return d("i18n.testingModel");let e=[void 0!==l.latencyMs?`${l.latencyMs}ms`:null,void 0!==l.status?`HTTP ${l.status}`:null].filter(Boolean);return"success"===l.phase?[d("i18n.connected"),...e,l.responseText||null].filter(Boolean).join(" \xb7 "):[d("i18n.failed"),...e,l.message].filter(Boolean).join(" \xb7 ")})();(0,i.useEffect)(()=>{o({phase:"idle"})},[e,t.baseUrl,t.api,t.apiKey,n.id,n.api]),(0,i.useEffect)(()=>{p.current+=1,u({phase:"idle"}),h.current=null},[e,t.baseUrl,n.id]);let g=(0,i.useCallback)(async()=>{if(n.id.trim()&&"testing"!==l.phase){o({phase:"testing"});try{let r=await fetch("/api/models-config/test",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({providerName:e,provider:t,model:n})}),i=await r.json();if(!r.ok||!i.ok)return void o({phase:"error",message:i.error??`HTTP ${r.status}`,latencyMs:i.latencyMs,status:i.status});o({phase:"success",latencyMs:i.latencyMs,status:i.status,responseText:i.responseText})}catch(e){o({phase:"error",message:e instanceof Error?e.message:String(e)})}}},[n,t,e,l.phase]),x=(0,i.useCallback)(async()=>{let r=n.id.trim();if(!r||"loading"===c.phase)return;let i=++p.current;u({phase:"loading"});try{let s=new URLSearchParams({q:r,provider:e,limit:"50"});t.baseUrl?.trim()&&s.set("baseUrl",t.baseUrl.trim());let l=await fetch(`/api/models-config/catalog?${s}`),o=await l.json();if(i!==p.current)return;if(!l.ok||o.error||!o.recommendation)return void u({phase:"error",message:o.error??`HTTP ${l.status}`});let d=function(e,t){let n={...e},r=0;if(!e.name?.trim()&&t.name&&(n.name=t.name,r+=1),void 0===e.reasoning&&!0===t.reasoning&&(n.reasoning=!0,r+=1),!e.input?.length&&t.input?.length&&(n.input=[...t.input],r+=1),void 0===e.contextWindow&&void 0!==t.contextWindow&&(n.contextWindow=t.contextWindow,r+=1),void 0===e.maxTokens&&void 0!==t.maxTokens&&(n.maxTokens=t.maxTokens,r+=1),t.cost){let i={...e.cost??{}},a=!1;for(let e of["input","output","cacheRead","cacheWrite"])void 0===i[e]&&void 0!==t.cost[e]&&(i[e]=t.cost[e],a=!0,r+=1);a&&(n.cost=i)}return{model:n,appliedCount:r}}(n,o.recommendation.preset);d.appliedCount>0&&(h.current=n,a(d.model)),u({phase:"success",recommendation:o.recommendation,appliedCount:d.appliedCount})}catch(e){if(i!==p.current)return;u({phase:"error",message:e instanceof Error?e.message:String(e)})}},[c.phase,n,a,t.baseUrl,e]),v=(()=>{if("success"!==c.phase)return null;let{recommendation:t,appliedCount:n}=c,r=n>0?d("models.catalogFilled",{count:n}):d("models.catalogNoEmptyFields");if("unreliable"===t.price.status){let e="no-exact-match"===t.price.reason?d("models.catalogNoExactMatch"):d("models.catalogPriceUnreliable");return`${r} \xb7 ${e}`}let i="provider"===t.price.method?d("models.catalogPriceProvider",{provider:t.price.providerName??t.price.providerId??e}):"base-url"===t.price.method?d("models.catalogPriceBaseUrl",{provider:t.price.providerName??t.price.providerId??e}):d("models.catalogPriceConsensus",{support:t.price.support,total:t.price.total});return`${r} \xb7 ${i}`})(),b="error"===c.phase?c.message:v,y="error"===c.phase?"#ef4444":"success"===c.phase&&"unreliable"===c.recommendation.price.status?"#d97706":"var(--text-dim)";return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[(0,r.jsx)(de,{children:d("i18n.model")}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8},children:[f&&(0,r.jsx)("span",{title:f,style:{maxWidth:260,height:24,padding:"0 8px",border:`1px solid ${"error"===l.phase?"#fecaca":"success"===l.phase?"#bbf7d0":"var(--border)"}`,borderRadius:4,background:"error"===l.phase?"#fee2e2":"success"===l.phase?"#dcfce7":"#e5e7eb",color:"#111827",fontSize:11,display:"inline-flex",alignItems:"center",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",boxSizing:"border-box"},children:f}),(0,r.jsxs)("button",{onClick:g,disabled:!n.id.trim()||"testing"===l.phase,title:d("i18n.testConnection"),style:{height:24,padding:"0 8px",background:"success"===l.phase?"#16a34a":"none",border:`1px solid ${"success"===l.phase?"#16a34a":"var(--border)"}`,borderRadius:4,color:"success"===l.phase?"#fff":n.id.trim()&&"testing"!==l.phase?"var(--text-muted)":"var(--text-dim)",cursor:n.id.trim()&&"testing"!==l.phase?"pointer":"not-allowed",fontSize:11,display:"inline-flex",alignItems:"center",justifyContent:"center",boxSizing:"border-box",gap:5},children:["success"===l.phase&&(0,r.jsx)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}),"testing"===l.phase?d("i18n.checking"):"success"===l.phase?d("common.ok"):d("i18n.test")]}),(0,r.jsx)("button",{onClick:s,style:{height:24,padding:"0 8px",background:"none",border:"1px solid rgba(239,68,68,0.3)",borderRadius:4,color:"#ef4444",cursor:"pointer",fontSize:11,boxSizing:"border-box"},children:d("i18n.remove")})]})]}),(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:10},children:[(0,r.jsx)(o4,{label:"ID *",children:(0,r.jsx)(o6,{value:n.id,onChange:e=>m("id",e),placeholder:"model-id",mono:!0})}),(0,r.jsx)(o4,{label:"Name",children:(0,r.jsx)(o6,{value:n.name??"",onChange:e=>m("name",e||void 0),placeholder:"Display name"})})]}),(0,r.jsxs)("div",{style:{padding:"10px 0",borderTop:"1px solid var(--border)",borderBottom:"1px solid var(--border)"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:[(0,r.jsx)("button",{onClick:()=>void x(),disabled:!n.id.trim()||"loading"===c.phase,style:{height:28,padding:"0 10px",border:"1px solid var(--border)",borderRadius:5,background:"var(--bg-panel)",color:n.id.trim()&&"loading"!==c.phase?"var(--text-muted)":"var(--text-dim)",cursor:n.id.trim()&&"loading"!==c.phase?"pointer":"not-allowed",fontSize:11},children:"loading"===c.phase?d("models.catalogFilling"):d("models.catalogFill")}),(0,r.jsx)("a",{href:"https://github.com/anomalyco/models.dev",target:"_blank",rel:"noreferrer",style:{marginLeft:"auto",color:"var(--text-dim)",fontSize:10,textDecoration:"none"},children:d("models.catalogSource")})]}),(0,r.jsxs)("div",{"aria-live":"polite",style:{marginTop:6,height:20,display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,color:y,fontSize:10},children:[(0,r.jsx)("span",{title:b??void 0,style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:b}),h.current&&(0,r.jsx)("button",{onClick:()=>{let e=h.current;e&&(h.current=null,a(e),u({phase:"idle"}))},style:{flexShrink:0,padding:"0 2px",border:"none",background:"none",color:"var(--accent)",cursor:"pointer",fontSize:10},children:d("models.catalogUndo")})]})]}),(0,r.jsx)(o4,{label:"API override",children:(0,r.jsx)(o7,{value:n.api??"",onChange:e=>m("api",e||void 0),options:o2})}),(0,r.jsxs)(o4,{label:"Headers",children:[(0,r.jsx)(ds,{headers:n.headers,onChange:e=>m("headers",e)}),(0,r.jsx)("span",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:"Added to this model's requests; overrides the provider headers for this model."})]}),(0,r.jsxs)("div",{style:{display:"flex",gap:20,flexWrap:"wrap"},children:[(0,r.jsx)(o9,{label:"Reasoning / thinking",checked:n.reasoning??!1,onChange:e=>m("reasoning",e||void 0)}),(0,r.jsx)(o9,{label:"Image input",checked:n.input?.includes("image")??!1,onChange:e=>m("input",e?["text","image"]:void 0)})]}),n.reasoning&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(o9,{label:"DeepSeek thinking compat",checked:n.compat?.thinkingFormat==="deepseek",onChange:e=>a(function(e,t){if(t)return{...e,compat:{...e.compat??{},...da}};if(!e.compat)return e;let n={...e.compat};return delete n.thinkingFormat,delete n.requiresReasoningContentOnAssistantMessages,{...e,compat:Object.keys(n).length?n:void 0}}(n,e))}),(0,r.jsx)(o9,{label:"Use 'developer' role for the system prompt (disable if server rejects it)",checked:!1!==({...t.compat??{},...n.compat??{}}).supportsDeveloperRole,onChange:e=>a({...n,compat:{...n.compat??{},supportsDeveloperRole:e}})}),(0,r.jsxs)("div",{children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:8},children:[(0,r.jsx)(de,{children:"Thinking level map"}),n.thinkingLevelMap&&(0,r.jsx)("button",{onClick:()=>m("thinkingLevelMap",void 0),style:{fontSize:10,padding:"2px 7px",background:"none",border:"1px solid var(--border)",borderRadius:4,color:"var(--text-dim)",cursor:"pointer"},children:"clear all"})]}),(0,r.jsx)(di,{value:n.thinkingLevelMap,onChange:e=>m("thinkingLevelMap",e)})]})]}),(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:10},children:[(0,r.jsx)(o4,{label:"Context window (tokens)",children:(0,r.jsx)(o3,{value:void 0!==n.contextWindow?String(n.contextWindow):"",onChange:e=>m("contextWindow",e?parseInt(e):void 0),placeholder:"128000"})}),(0,r.jsx)(o4,{label:"Max output tokens",children:(0,r.jsx)(o3,{value:void 0!==n.maxTokens?String(n.maxTokens):"",onChange:e=>m("maxTokens",e?parseInt(e):void 0),placeholder:"16384"})})]}),(0,r.jsxs)("div",{children:[(0,r.jsx)(de,{children:"Cost (per million tokens)"}),(0,r.jsx)("div",{style:{marginTop:8,display:"grid",gridTemplateColumns:"1fr 1fr 1fr 1fr",gap:8},children:["input","output","cacheRead","cacheWrite"].map(e=>(0,r.jsx)(o4,{label:e,children:(0,r.jsx)(o3,{value:n.cost?.[e]!==void 0?String(n.cost[e]):"",onChange:t=>{let r;return r=parseFloat(t),void a({...n,cost:{...n.cost??{},[e]:isNaN(r)?void 0:r}})},placeholder:"0"})},e))})]})]})}let dd={checking:"relogin.checking",recovered:"relogin.recovered","still-failing":"relogin.stillFailing",unknown:"relogin.unknown"};function dc({provider:e,onRefresh:t,relogin:n}){let a=n?.onLoginSucceeded,[s,l]=(0,i.useState)({phase:"idle"}),{t:o}=(0,R.s)(),[d,c]=(0,i.useState)(""),u=(0,i.useRef)(null),p=(0,i.useRef)(!1),h=(0,i.useRef)(null),m=(0,i.useRef)(null),f=void 0!==n;(0,i.useEffect)(()=>{f&&m.current?.focus()},[f]),(0,i.useEffect)(()=>{("auth"===s.phase||"prompt"===s.phase)&&setTimeout(()=>h.current?.focus(),50)},[s.phase]),(0,i.useEffect)(()=>{l({phase:"idle"}),c(""),u.current?.close(),u.current=null},[e.id]),(0,i.useEffect)(()=>()=>{u.current?.close()},[]);let g=(0,i.useCallback)(()=>{u.current?.close(),p.current||(p.current=!0,c(""),l({phase:"success"}),t(),a?.())},[t,a]),x=(0,i.useCallback)(()=>{u.current?.close(),p.current=!1,l({phase:"connecting"}),c("");let t=new EventSource(`/api/auth/login/${encodeURIComponent(e.id)}`);u.current=t,t.onmessage=e=>{let n=JSON.parse(e.data);"auth"===n.type?(l({phase:"auth",url:n.url,instructions:n.instructions??null,token:n.token}),oS(n.url)):"device_code"===n.type?(l({phase:"device_code",userCode:n.userCode,verificationUri:n.verificationUri,intervalSeconds:n.intervalSeconds??null,expiresInSeconds:n.expiresInSeconds??null}),oS(n.verificationUri)):"prompt_request"===n.type?l({phase:"prompt",message:n.message,placeholder:n.placeholder??null,token:n.token}):"select_request"===n.type?l({phase:"select",message:n.message,options:n.options??[],token:n.token}):"progress"===n.type?l({phase:"progress",message:n.message}):"success"===n.type?g():"error"===n.type?(t.close(),l({phase:"error",message:n.message})):"cancelled"===n.type&&(t.close(),l({phase:"idle"}))},t.onerror=()=>{t.close(),l(e=>"success"===e.phase||"auth"===e.phase||"prompt"===e.phase||"select"===e.phase?e:{phase:"error",message:"Connection lost"})}},[e.id,g]),v=(0,i.useCallback)(async()=>{await fetch(`/api/auth/logout/${encodeURIComponent(e.id)}`,{method:"POST"}),l({phase:"idle"}),t()},[e.id,t]),b=(0,i.useCallback)(async(t,n,r)=>{l({phase:"progress",message:r});try{let r=await fetch(`/api/auth/login/${encodeURIComponent(e.id)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:t,code:n})}),i=await r.json().catch(()=>({}));if(!r.ok)return void l({phase:"error",message:i.error??`Server error ${r.status}`});if(c(""),"success"===i.state)return void g();u.current?.readyState===EventSource.CLOSED&&l({phase:"error",message:"Connection lost. Start the login again."})}catch(e){l({phase:"error",message:e instanceof Error?e.message:"Network error"})}},[e.id,g]),y=(0,i.useCallback)(async(e,t)=>{t.trim()&&await b(e,t.trim(),"Verifying…")},[b]),w=(0,i.useCallback)(async(e,t)=>{await b(e,t,"Continuing…")},[b]),k="connecting"===s.phase||"progress"===s.phase||"auth"===s.phase||"device_code"===s.phase||"prompt"===s.phase||"select"===s.phase;return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[(0,r.jsx)(de,{children:o("i18n.subscription")}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:e.loggedIn?"#4ade80":"var(--border)",display:"inline-block"}}),(0,r.jsx)("span",{style:{fontSize:11,color:e.loggedIn?"#4ade80":"var(--text-dim)"},children:o(e.loggedIn?"i18n.connected":"i18n.notConnected")})]})]}),n&&(0,r.jsxs)("div",{role:"note","aria-label":o("relogin.title"),style:{display:"flex",alignItems:"flex-start",gap:10,padding:"10px 12px",border:"1px solid var(--border)",borderRadius:8,background:"var(--bg-panel)"},children:[(0,r.jsx)(nx,{seed:n.target.seed,size:32,provider:n.target.provider}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:4,minWidth:0},children:[(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)"},children:o("relogin.title")}),(0,r.jsxs)("span",{style:{fontSize:13,fontWeight:600,color:"var(--text)",overflowWrap:"anywhere"},children:[n.target.alias,n.target.masked&&(0,r.jsx)("span",{style:{marginLeft:6,fontSize:11,fontWeight:400,color:"var(--text-muted)",fontFamily:"var(--font-mono)"},children:n.target.masked})]}),n.target.reason&&(0,r.jsx)("span",{style:{fontSize:12,color:"var(--seed-color-fg-critical-contrast)",lineHeight:1.5,overflowWrap:"anywhere"},children:n.target.reason})]})]}),(0,r.jsxs)("div",{style:{minHeight:48},children:["idle"===s.phase&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:n?o("relogin.guide",{action:o(e.loggedIn?"i18n.relogin":"i18n.login")}):e.loggedIn?"Already connected. You can re-login or disconnect.":`Connect your ${e.name} account.`}),"connecting"===s.phase&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)"},children:o("i18n.openingBrowser")}),"select"===s.phase&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:s.message}),(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:s.options.map(e=>(0,r.jsx)("button",{onClick:()=>w(s.token,e.id),style:{padding:"6px 9px",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:5,color:"var(--text)",cursor:"pointer",fontSize:12,textAlign:"left"},children:e.label},e.id))})]}),("auth"===s.phase||"prompt"===s.phase)&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:"auth"===s.phase?"Complete sign-in in the browser. If the last page does not load (for example on a phone), copy its address from the address bar and paste it below.":s.message}),"auth"===s.phase&&(0,r.jsxs)("p",{style:{margin:0,fontSize:11,color:"var(--text-dim)",lineHeight:1.5},children:["If the browser window did not open,"," ",(0,r.jsx)("a",{href:s.url,target:"_blank",rel:"noopener noreferrer",style:{color:"var(--accent)",wordBreak:"break-all"},children:"click here to open the login page"}),"."]}),(0,r.jsxs)("div",{style:{display:"flex",gap:6},children:[(0,r.jsx)("input",{ref:h,value:d,onChange:e=>c(e.target.value),onKeyDown:e=>{"Enter"===e.key&&y(s.token,d)},placeholder:"auth"===s.phase?"Paste the redirect URL or code":s.placeholder??"Enter value…",style:{flex:1,padding:"6px 9px",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:5,color:"var(--text)",fontSize:12,outline:"none",fontFamily:"var(--font-mono)",boxSizing:"border-box"}}),(0,r.jsx)("button",{onClick:()=>y(s.token,d),disabled:!d.trim(),style:{padding:"6px 12px",background:d.trim()?"var(--seed-color-bg-neutral-inverted)":"var(--bg-panel)",border:"none",borderRadius:5,color:d.trim()?"var(--seed-color-fg-neutral-inverted)":"var(--text-dim)",cursor:d.trim()?"pointer":"not-allowed",fontSize:12,fontWeight:600,flexShrink:0},children:o("i18n.submit")})]})]}),"device_code"===s.phase&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:"Open the verification page and enter this code:"}),(0,r.jsx)("div",{style:{padding:"8px 10px",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:5,color:"var(--text)",fontSize:16,fontWeight:700,fontFamily:"var(--font-mono)",letterSpacing:0},children:s.userCode}),(0,r.jsxs)("p",{style:{margin:0,fontSize:11,color:"var(--text-dim)",lineHeight:1.5},children:[(0,r.jsx)("a",{href:s.verificationUri,target:"_blank",rel:"noopener noreferrer",style:{color:"var(--accent)",wordBreak:"break-all"},children:s.verificationUri}),s.expiresInSeconds?` Expires in ${Math.ceil(s.expiresInSeconds/60)} minutes.`:""]})]}),"progress"===s.phase&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)"},children:s.message}),"success"===s.phase&&(n?(0,r.jsxs)("div",{role:"status",style:{display:"flex",flexDirection:"column",gap:4},children:[(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)"},children:o("relogin.done")}),n.outcome&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,lineHeight:1.5,color:"recovered"===n.outcome?"var(--seed-color-fg-positive-contrast)":"still-failing"===n.outcome?"var(--seed-color-fg-critical-contrast)":"var(--text-muted)"},children:o(dd[n.outcome],{account:n.target.alias})})]}):(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"#4ade80"},children:o("i18n.connectedSuccessfully")})),"error"===s.phase&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"#f87171"},children:s.message})]}),(0,r.jsx)("div",{style:{display:"flex",gap:8},children:k?(0,r.jsx)("button",{onClick:()=>{u.current?.close(),l({phase:"idle"})},style:{padding:"5px 12px",background:"none",border:"1px solid var(--border)",borderRadius:5,color:"var(--text-muted)",cursor:"pointer",fontSize:12},children:o("i18n.cancel")}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("button",{ref:m,onClick:x,style:{padding:"5px 14px",background:"var(--seed-color-bg-neutral-inverted)",border:"none",borderRadius:5,color:"var(--seed-color-fg-neutral-inverted)",cursor:"pointer",fontSize:12,fontWeight:600},children:o(e.loggedIn?"i18n.relogin":"i18n.login")}),e.loggedIn&&!n&&(0,r.jsx)("button",{onClick:v,style:{padding:"5px 12px",background:"none",border:"1px solid rgba(239,68,68,0.3)",borderRadius:5,color:"#ef4444",cursor:"pointer",fontSize:12},children:o("i18n.disconnect")})]})})]})}function du({provider:e,onRefresh:t}){let[n,a]=(0,i.useState)(""),[s,l]=(0,i.useState)(!1),[o,d]=(0,i.useState)(!1),[c,u]=(0,i.useState)(null),[p,h]=(0,i.useState)(!1),{t:m}=(0,R.s)();(0,i.useEffect)(()=>{a(""),u(null),h(!1)},[e.id]);let f=(0,i.useCallback)(async()=>{if(n.trim()){l(!0),u(null),h(!1);try{let r=await fetch(`/api/auth/api-key/${encodeURIComponent(e.id)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:n.trim()})}),i=await r.json();!r.ok||i.error?u(i.error??`HTTP ${r.status}`):(a(""),h(!0),setTimeout(()=>h(!1),2e3),t())}catch(e){u(String(e))}finally{l(!1)}}},[n,e.id,t]),g=(0,i.useCallback)(async()=>{d(!0),u(null);try{let n=await fetch(`/api/auth/api-key/${encodeURIComponent(e.id)}`,{method:"DELETE"}),r=await n.json();!n.ok||r.error?u(r.error??`HTTP ${n.status}`):t()}catch(e){u(String(e))}finally{d(!1)}},[e.id,t]);return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[(0,r.jsx)(de,{children:"API Key"}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6},children:[(0,r.jsx)("span",{style:{width:7,height:7,borderRadius:"50%",background:e.configured?"#4ade80":"var(--border)",display:"inline-block"}}),(0,r.jsx)("span",{style:{fontSize:11,color:e.configured?"#4ade80":"var(--text-dim)"},children:m(e.configured?"i18n.configured":"i18n.notConfigured")})]})]}),(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"var(--text-muted)",lineHeight:1.5},children:e.configured?"API key is stored. Enter a new key below to replace it, or disconnect to remove it.":`Enter your ${e.displayName} API key to enable ${e.modelCount} model${1!==e.modelCount?"s":""}.`}),(0,r.jsx)(o4,{label:"API Key",children:(0,r.jsxs)("div",{style:{display:"flex",gap:6},children:[(0,r.jsx)(o8,{value:n,onChange:a,onKeyDown:e=>{"Enter"===e.key&&n.trim()&&f()},placeholder:e.configured?"Enter new key to replace…":"sk-…",style:{flex:1},autoComplete:"off",spellCheck:!1,mono:!0}),(0,r.jsxs)("button",{onClick:f,disabled:s||!n.trim()||p,style:{padding:"6px 12px",background:p?"#16a34a":n.trim()?"var(--seed-color-bg-neutral-inverted)":"var(--bg-panel)",border:"none",borderRadius:5,color:p?"#fff":n.trim()?"var(--seed-color-fg-neutral-inverted)":"var(--text-dim)",cursor:s||!n.trim()||p?"not-allowed":"pointer",fontSize:12,fontWeight:600,flexShrink:0,display:"flex",alignItems:"center",gap:5},children:[p&&(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}),m(p?"i18n.saved":s?"i18n.saving":"i18n.save")]})]})}),c&&(0,r.jsx)("p",{style:{margin:0,fontSize:12,color:"#f87171"},children:c}),e.configured&&(0,r.jsx)("button",{onClick:g,disabled:o,style:{alignSelf:"flex-start",padding:"5px 12px",background:"none",border:"1px solid rgba(239,68,68,0.3)",borderRadius:5,color:"#ef4444",cursor:o?"not-allowed":"pointer",fontSize:12},children:m(o?"i18n.removing":"i18n.disconnect")})]})}function dp({id:e,size:t}){let n=o1[e];if(!n){let n=e.split(/[-_]/).filter(Boolean).slice(0,2).map(e=>e[0]).join("").toUpperCase()||"?";return(0,r.jsx)("span",{"aria-hidden":"true",style:{width:t,height:t,border:"1px solid var(--border)",borderRadius:4,color:"var(--text-dim)",display:"inline-flex",alignItems:"center",justifyContent:"center",flexShrink:0,fontSize:Math.max(8,Math.floor(.42*t)),fontWeight:700,lineHeight:1},children:n})}return n.hasColor?(0,r.jsx)(n.Icon,{size:t}):(0,r.jsx)(n.Icon,{size:t,style:{color:"var(--text-muted)"}})}function dh({oauthProviders:e,apiKeyProviders:t,onSelectOAuth:n,onSelectApiKey:a,onAddCustom:s,onClose:l}){let[o,d]=(0,i.useState)(""),{t:c}=(0,R.s)(),u=(0,i.useRef)(null);(0,i.useEffect)(()=>{setTimeout(()=>u.current?.focus(),30)},[]);let p=o.trim().toLowerCase(),h=e.filter(e=>!e.loggedIn&&(!p||e.name.toLowerCase().includes(p))),m=t.filter(e=>!e.configured&&(!p||e.displayName.toLowerCase().includes(p)||e.id.toLowerCase().includes(p))),f=!p||"custom".includes(p)||"openai-compatible".includes(p)||"anthropic-compatible".includes(p),g=h.length+m.length+ +!!f,x={display:"flex",flexDirection:"row",alignItems:"center",gap:8,padding:"10px 12px",background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:7,boxSizing:"border-box",cursor:"pointer",minWidth:0,textAlign:"left",transition:"border-color 0.12s, background 0.12s",width:"100%"};return(0,r.jsx)("div",{style:{position:"fixed",inset:0,zIndex:1100,background:"rgba(0,0,0,0.4)",display:"flex",alignItems:"center",justifyContent:"center"},onClick:e=>{e.target===e.currentTarget&&l()},children:(0,r.jsxs)("div",{style:{width:820,maxWidth:"calc(100vw - 32px)",maxHeight:"min(72vh, calc(100vh - 32px))",background:"var(--bg)",border:"1px solid var(--border)",borderRadius:10,display:"flex",flexDirection:"column",boxShadow:"0 8px 32px rgba(0,0,0,0.22)",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{padding:"10px 14px",borderBottom:"1px solid var(--border)",flexShrink:0,display:"flex",alignItems:"center",gap:8},children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{color:"var(--text-dim)",flexShrink:0},children:[(0,r.jsx)("circle",{cx:"11",cy:"11",r:"8"}),(0,r.jsx)("line",{x1:"21",y1:"21",x2:"16.65",y2:"16.65"})]}),(0,r.jsx)("input",{ref:u,value:o,onChange:e=>d(e.target.value),onKeyDown:e=>{"Escape"===e.key&&l()},placeholder:c("i18n.searchProviders"),style:{flex:1,background:"none",border:"none",outline:"none",color:"var(--text)",fontSize:13,boxSizing:"border-box"}})]}),(0,r.jsx)("div",{style:{flex:1,overflowY:"auto",padding:14},children:0===g?(0,r.jsx)("div",{style:{padding:"20px 0",fontSize:12,color:"var(--text-dim)",textAlign:"center"},children:c("i18n.noProviders")}):(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(min(240px, 100%), 1fr))",gap:8},children:[f&&(0,r.jsx)("div",{style:{gridColumn:"1 / -1",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:c("i18n.custom")}),f&&(0,r.jsxs)("button",{onClick:()=>{s(),l()},style:x,onMouseEnter:e=>{e.currentTarget.style.borderColor="var(--accent)",e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.borderColor="var(--border)",e.currentTarget.style.background="var(--bg-panel)"},children:[(0,r.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text)",lineHeight:1.3,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:"OpenAI / Anthropic compatible"}),(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:c("i18n.customEndpoint")})]}),(0,r.jsx)("span",{style:{width:26,height:26,borderRadius:5,background:"var(--bg-hover)",border:"1px dashed var(--border)",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0},children:(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{color:"var(--text-dim)"},children:[(0,r.jsx)("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),(0,r.jsx)("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})})]}),h.length>0&&(0,r.jsx)("div",{style:{gridColumn:"1 / -1",paddingTop:6*!!f,fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:c("i18n.subscriptions")}),h.map(e=>(0,r.jsxs)("button",{onClick:()=>{n(e.id),l()},style:x,onMouseEnter:e=>{e.currentTarget.style.borderColor="var(--accent)",e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.borderColor="var(--border)",e.currentTarget.style.background="var(--bg-panel)"},children:[(0,r.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text)",lineHeight:1.3,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name}),(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:"OAuth"})]}),(0,r.jsx)(dp,{id:e.id,size:28})]},e.id)),m.length>0&&(0,r.jsx)("div",{style:{gridColumn:"1 / -1",paddingTop:6*(h.length>0),fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em"},children:"API Key"}),m.map(e=>(0,r.jsxs)("button",{onClick:()=>{a(e.id),l()},style:x,onMouseEnter:e=>{e.currentTarget.style.borderColor="var(--accent)",e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.borderColor="var(--border)",e.currentTarget.style.background="var(--bg-panel)"},children:[(0,r.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text)",lineHeight:1.3,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.displayName}),(0,r.jsxs)("div",{style:{fontSize:10,color:"var(--text-dim)",marginTop:2},children:[e.modelCount," models"]})]}),(0,r.jsx)(dp,{id:e.id,size:28})]},e.id))]})})]})})}function dm({cwd:e,onClose:t,embedded:n=!1,onModelsChanged:a,relogin:s}){let l=W(),{t:o}=(0,R.s)(),[d,c]=(0,i.useState)({providers:{}}),[u,p]=(0,i.useState)(!0),[h,m]=(0,i.useState)(!1),[f,g]=(0,i.useState)(null),[x,v]=(0,i.useState)(!1),[b,y]=(0,i.useState)(s?{type:"oauth",providerId:s.target.provider}:{type:"roles"}),[w,k]=(0,i.useState)([]),[j,S]=(0,i.useState)([]),[C,N]=(0,i.useState)(!1),I=(0,i.useCallback)(()=>{fetch("/api/auth/providers").then(e=>e.json()).then(e=>k(e.providers)).catch(()=>{})},[]),T=(0,i.useCallback)(()=>{fetch("/api/auth/all-providers").then(e=>e.json()).then(e=>S(e.providers)).catch(()=>{})},[]),M=(0,i.useCallback)(()=>{I(),T()},[I,T]);(0,i.useEffect)(()=>{fetch("/api/models-config").then(e=>e.json()).then(e=>{c(e.providers?e:{...e,providers:{}})}).catch(()=>c({providers:{}})).finally(()=>p(!1)),M()},[M]);let $=(0,i.useCallback)(()=>{let e="new-provider",t=1;for(;d.providers?.[e];)e=`new-provider-${t++}`;c(t=>({...t,providers:{...t.providers??{},[e]:{api:"openai-completions"}}})),y({type:"provider",name:e})},[d.providers]),E=(0,i.useCallback)((e,t)=>{c(n=>({...n,providers:{...n.providers??{},[e]:t}}))},[]),L=(0,i.useCallback)((e,t)=>{c(n=>{let r=Object.entries(n.providers??{}),i=r.findIndex(([t])=>t===e);return -1===i?n:(r[i]=[t,r[i][1]],{...n,providers:Object.fromEntries(r)})}),y(n=>n?"provider"===n.type&&n.name===e?{type:"provider",name:t}:"model"===n.type&&n.providerName===e?{...n,providerName:t}:n:n)},[]),A=(0,i.useCallback)(e=>{c(t=>{let n={...t.providers??{}};return delete n[e],{...t,providers:n}}),c(e=>{let t=Object.keys(e.providers??{});return y(t.length>0?{type:"provider",name:t[0]}:null),e})},[]),z=(0,i.useCallback)(e=>{c(t=>{let n=t.providers?.[e]??{},r=[...n.models??[],{id:""}];return{...t,providers:{...t.providers??{},[e]:{...n,models:r}}}}),c(t=>{let n=(t.providers?.[e]?.models?.length??1)-1;return y({type:"model",providerName:e,index:n}),t})},[]),P=(0,i.useCallback)((e,t)=>{c(n=>{let r=n.providers?.[e]??{},i=[...r.models??[]],a=new Set(i.map(e=>e.id));for(let e of t)a.has(e.id)||(a.add(e.id),i.push({id:e.id,name:e.name}));return{...n,providers:{...n.providers??{},[e]:{...r,models:i}}}})},[]),F=(0,i.useCallback)((e,t,n)=>{c(r=>{let i=r.providers?.[e]??{},a=[...i.models??[]];return a[t]=n,{...r,providers:{...r.providers??{},[e]:{...i,models:a}}}})},[]),_=(0,i.useCallback)((e,t)=>{c(n=>{let r=n.providers?.[e]??{},i=[...r.models??[]];return i.splice(t,1),{...n,providers:{...n.providers??{},[e]:{...r,models:i.length?i:void 0}}}}),y({type:"provider",name:e})},[]),D=(0,i.useCallback)(async()=>{m(!0),g(null),v(!1);try{let e=await fetch("/api/models-config",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(d)}),t=await e.json();!e.ok||t.error?g(t.error??`HTTP ${e.status}`):(v(!0),a?.(),setTimeout(()=>v(!1),2e3))}catch(e){g(String(e))}finally{m(!1)}},[d,a]),O=Object.entries(d.providers??{}),H=w.filter(e=>e.loggedIn),B=j.filter(e=>e.configured),U=(()=>{if(!b)return null;if("roles"===b.type)return(0,r.jsx)(oj,{cwd:e??null,onRolesChanged:a});if("oauth"===b.type){let e=w.find(e=>e.id===b.providerId);return e?(0,r.jsx)(dc,{provider:e,onRefresh:M,relogin:s?.target.provider===e.id?s:void 0},e.id):null}if("apikey"===b.type){let e=j.find(e=>e.id===b.providerId);return e?(0,r.jsx)(du,{provider:e,onRefresh:M},e.id):null}if("provider"===b.type){let e=d.providers?.[b.name];return e?(0,r.jsx)(dt,{name:b.name,provider:e,onChange:e=>E(b.name,e),onRename:e=>L(b.name,e),onDelete:()=>A(b.name),onAddModels:e=>P(b.name,e)},b.name):null}let t=d.providers?.[b.providerName],n=t?.models?.[b.index];return n?(0,r.jsx)(dl,{providerName:b.providerName,provider:t,model:n,onChange:e=>F(b.providerName,b.index,e),onDelete:()=>_(b.providerName,b.index)},`${b.providerName}-${b.index}`):null})();return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{style:{position:n?"relative":"fixed",inset:n?void 0:0,width:"100%",height:"100%",zIndex:n?void 0:1e3,background:n?"transparent":"rgba(0,0,0,0.35)",display:"flex",alignItems:"center",justifyContent:"center"},onClick:e=>{n||e.target!==e.currentTarget||t()},...n?{}:{role:"dialog","aria-modal":!0,"aria-label":o("common.models"),onKeyDown:e=>{"Escape"===e.key&&(e.stopPropagation(),t())}},children:(0,r.jsxs)("div",{style:{width:n?"100%":l?"calc(100vw - 16px)":860,maxWidth:n?"none":"calc(100vw - 16px)",height:n?"100%":l?"calc(100dvh - 16px)":"78vh",maxHeight:n?"none":"calc(100dvh - 16px)",background:"var(--bg)",border:n?"none":"1px solid var(--border)",borderRadius:10*!n,display:"flex",flexDirection:"column",boxShadow:n?"none":"0 8px 32px rgba(0,0,0,0.18)",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 18px",borderBottom:"1px solid var(--border)",flexShrink:0},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"baseline",gap:10},children:[(0,r.jsx)("span",{style:{fontSize:15,fontWeight:700,color:"var(--text)"},children:o("common.models")}),(0,r.jsx)("code",{style:{fontSize:11,color:"var(--text-muted)",fontFamily:"var(--font-mono)"},children:"~/.omp/agent/models.yml"})]}),(0,r.jsx)("button",{onClick:t,"aria-label":o("i18n.close"),style:{background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",fontSize:20,lineHeight:1,padding:"2px 6px"},children:"\xd7"})]}),(0,r.jsxs)("div",{style:{flex:1,display:"flex",flexDirection:l?"column":"row",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{width:l?"100%":210,maxHeight:l?"40vh":void 0,borderRight:l?"none":"1px solid var(--border)",borderBottom:l?"1px solid var(--border)":"none",display:"flex",flexDirection:"column",flexShrink:0,background:"var(--bg-panel)"},children:[(0,r.jsxs)("div",{style:{flex:1,overflowY:"auto",padding:"8px 6px"},children:[(0,r.jsxs)("div",{onClick:()=>y({type:"roles"}),style:{display:"flex",alignItems:"center",gap:7,padding:"5px 8px",borderRadius:5,cursor:"pointer",background:b?.type==="roles"?"var(--bg-selected)":"none"},onMouseEnter:e=>{b?.type!=="roles"&&(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{b?.type!=="roles"&&(e.currentTarget.style.background="none")},children:[(0,r.jsxs)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",style:{color:"var(--text-muted)",flexShrink:0},children:[(0,r.jsx)("line",{x1:"4",y1:"7",x2:"20",y2:"7"}),(0,r.jsx)("circle",{cx:"9",cy:"7",r:"2.2"}),(0,r.jsx)("line",{x1:"4",y1:"17",x2:"20",y2:"17"}),(0,r.jsx)("circle",{cx:"15",cy:"17",r:"2.2"})]}),(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text)",flex:1},children:o("roles.title")})]}),(0,r.jsx)("div",{style:{margin:"4px 8px",borderTop:"1px solid var(--border)"}}),H.map(e=>{let t=b?.type==="oauth"&&b.providerId===e.id;return(0,r.jsxs)("div",{onClick:()=>y({type:"oauth",providerId:e.id}),style:{display:"flex",alignItems:"center",gap:7,padding:"5px 8px",borderRadius:5,cursor:"pointer",background:t?"var(--bg-selected)":"none"},onMouseEnter:e=>{t||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{t||(e.currentTarget.style.background="none")},children:[(0,r.jsx)(dp,{id:e.id,size:16}),(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text)",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name})]},e.id)}),B.map(e=>{let t=b?.type==="apikey"&&b.providerId===e.id;return(0,r.jsxs)("div",{onClick:()=>y({type:"apikey",providerId:e.id}),style:{display:"flex",alignItems:"center",gap:7,padding:"5px 8px",borderRadius:5,cursor:"pointer",background:t?"var(--bg-selected)":"none"},onMouseEnter:e=>{t||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{t||(e.currentTarget.style.background="none")},children:[(0,r.jsx)(dp,{id:e.id,size:16}),(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text)",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.displayName})]},e.id)}),(H.length>0||B.length>0)&&O.length>0&&(0,r.jsx)("div",{style:{margin:"4px 8px",borderTop:"1px solid var(--border)"}}),u?(0,r.jsx)("div",{style:{padding:"10px 8px",fontSize:12,color:"var(--text-muted)"},children:o("i18n.loading")}):O.map(([e,t])=>{let n=b?.type==="provider"&&b.name===e,i=t.models??[];return(0,r.jsxs)("div",{style:{marginBottom:2},children:[(0,r.jsxs)("div",{onClick:()=>y({type:"provider",name:e}),style:{display:"flex",alignItems:"center",gap:6,padding:"7px 8px",borderRadius:5,cursor:"pointer",background:n?"var(--bg-selected)":"none"},onMouseEnter:e=>{n||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{n||(e.currentTarget.style.background="none")},children:[(0,r.jsxs)("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{color:"var(--text-dim)",flexShrink:0},children:[(0,r.jsx)("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"}),(0,r.jsx)("rect",{x:"9",y:"9",width:"6",height:"6"}),(0,r.jsx)("line",{x1:"9",y1:"1",x2:"9",y2:"4"}),(0,r.jsx)("line",{x1:"15",y1:"1",x2:"15",y2:"4"}),(0,r.jsx)("line",{x1:"9",y1:"20",x2:"9",y2:"23"}),(0,r.jsx)("line",{x1:"15",y1:"20",x2:"15",y2:"23"}),(0,r.jsx)("line",{x1:"20",y1:"9",x2:"23",y2:"9"}),(0,r.jsx)("line",{x1:"20",y1:"14",x2:"23",y2:"14"}),(0,r.jsx)("line",{x1:"1",y1:"9",x2:"4",y2:"9"}),(0,r.jsx)("line",{x1:"1",y1:"14",x2:"4",y2:"14"})]}),(0,r.jsx)("span",{style:{fontSize:12,fontWeight:n?600:400,color:"var(--text)",fontFamily:"var(--font-mono)",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e})]}),i.map((t,n)=>{let i=b?.type==="model"&&b.providerName===e&&b.index===n;return(0,r.jsxs)("div",{onClick:()=>y({type:"model",providerName:e,index:n}),style:{display:"flex",alignItems:"center",gap:6,padding:"5px 8px 5px 26px",borderRadius:5,cursor:"pointer",background:i?"var(--bg-selected)":"none"},onMouseEnter:e=>{i||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{i||(e.currentTarget.style.background="none")},children:[(0,r.jsx)("span",{style:{fontSize:11,fontFamily:"var(--font-mono)",color:t.id?"var(--text-muted)":"var(--text-dim)",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:t.id||o("i18n.newModel")}),t.reasoning&&(0,r.jsx)("span",{style:{fontSize:9,padding:"1px 4px",background:"rgba(99,102,241,0.12)",color:"rgba(99,102,241,0.8)",borderRadius:3,flexShrink:0},children:"T"})]},n)}),(0,r.jsx)("div",{onClick:t=>{t.stopPropagation(),z(e)},style:{display:"flex",alignItems:"center",gap:4,padding:"4px 8px 4px 26px",borderRadius:5,cursor:"pointer",color:"var(--text-dim)"},onMouseEnter:e=>{e.currentTarget.style.color="var(--accent)",e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.color="var(--text-dim)",e.currentTarget.style.background="none"},children:(0,r.jsxs)("span",{style:{fontSize:11},children:["+ ",o("i18n.model")]})})]},e)})]}),(0,r.jsx)("div",{style:{borderTop:"1px solid var(--border)",padding:"8px 6px"},children:(0,r.jsxs)("button",{onClick:()=>N(!0),style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,width:"100%",padding:"6px 0",background:"none",border:"1px dashed var(--border)",borderRadius:5,color:"var(--text-muted)",cursor:"pointer",fontSize:12},onMouseEnter:e=>{e.currentTarget.style.borderColor="var(--accent)",e.currentTarget.style.color="var(--accent)"},onMouseLeave:e=>{e.currentTarget.style.borderColor="var(--border)",e.currentTarget.style.color="var(--text-muted)"},children:["+ ",o("i18n.addProvider")]})})]}),(0,r.jsx)("div",{style:{flex:1,overflowY:"auto",padding:20},children:u?null:U??(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-dim)",fontSize:13},children:o("i18n.selectProviderModel")})})]}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"flex-end",gap:10,padding:"10px 18px",borderTop:"1px solid var(--border)",flexShrink:0},children:[f&&(0,r.jsx)("span",{style:{fontSize:12,color:"#f87171",flex:1},children:f}),(0,r.jsx)("button",{onClick:t,style:{padding:"6px 14px",background:"none",border:"1px solid var(--border)",borderRadius:6,color:"var(--text-muted)",cursor:"pointer",fontSize:13},children:o("i18n.cancel")}),(0,r.jsxs)("button",{onClick:D,disabled:h||x,style:{position:"relative",padding:"6px 16px",minWidth:92,background:x?"#16a34a":h?"var(--bg-panel)":"var(--seed-color-bg-neutral-inverted)",border:"none",borderRadius:6,color:x?"#fff":h?"var(--text-muted)":"var(--seed-color-fg-neutral-inverted)",cursor:h||x?"default":"pointer",fontSize:13,fontWeight:600,display:"inline-flex",alignItems:"center",justifyContent:"center",gap:6,transition:"background-color 0.2s ease, color 0.2s ease",animation:x?"saved-pop 0.45s ease":void 0},children:[x&&(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",style:{strokeDasharray:18,animation:"saved-check-draw 0.35s ease forwards",flexShrink:0},children:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}),(0,r.jsx)("span",{children:x?o("i18n.saved"):h?o("i18n.saving"):o("i18n.save")})]})]})]})}),C&&(0,r.jsx)(dh,{oauthProviders:w,apiKeyProviders:j,onSelectOAuth:e=>y({type:"oauth",providerId:e}),onSelectApiKey:e=>y({type:"apikey",providerId:e}),onAddCustom:$,onClose:()=>N(!1)})]})}function df(e){return e.replace(/^\/(?:Users|home)\/[^/]+/,"~")}function dg(e){let t=e.sourceInfo?.source,n=e.sourceInfo?.scope;return"user"===n||"user"===t?"global":"project"===n||"project"===t?"project":"path"}function dx(e){let t=dg(e);return"path"===t?t:e.install?.skillsShUrl?`${t} / skills.sh`:t}function dv(e){return e.install?`${e.install.scope}\0${e.install.package}`:null}function db(e){return e?e.slice(0,8):"unknown"}function dy({enabled:e,loading:t,onToggle:n}){let{t:i}=(0,R.s)();return(0,r.jsx)("button",{onClick:n,disabled:t,title:i(e?"i18n.visibleInPrompt":"i18n.hiddenFromPrompt"),style:{flexShrink:0,width:40,height:22,borderRadius:11,border:"none",padding:0,cursor:t?"wait":"pointer",background:e?"var(--accent)":"var(--border)",position:"relative",transition:"background 0.18s",outline:"none"},children:(0,r.jsx)("span",{style:{position:"absolute",top:3,left:e?21:3,width:16,height:16,borderRadius:"50%",background:"var(--bg)",boxShadow:"0 1px 4px rgba(0,0,0,0.22)",transition:"left 0.18s cubic-bezier(.4,0,.2,1)"}})})}function dw({skill:e,cwd:t,onToggle:n,toggling:i,saveError:a,updateStatus:s,checkingUpdate:l,updating:o,updateError:d,onCheckUpdate:c,onUpdate:u}){let{t:p}=(0,R.s)(),h=dg(e),m=!e.disableModelInvocation;return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:20},children:[(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:7},children:[(0,r.jsx)("span",{style:{fontSize:10,padding:"1px 5px",borderRadius:3,flexShrink:0,background:"project"===h?"rgba(99,102,241,0.12)":"rgba(120,120,120,0.12)",color:"project"===h?"rgba(99,102,241,0.8)":"var(--text-dim)"},children:h}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:11,color:"var(--text-dim)",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:function(e){if("project"===h&&e.startsWith(t)){let n=e.slice(t.length).replace(/^[/\\]/,"");return`./${n}`}return df(e)}(e.filePath)}),(0,r.jsx)(dy,{enabled:m,loading:i,onToggle:()=>n(e)})]}),(0,r.jsxs)("div",{style:{minHeight:16,display:"flex",alignItems:"center",justifyContent:"flex-end",gap:8,flexWrap:"wrap",textAlign:"right"},children:[!m&&(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)"},children:p("i18n.hiddenButInvocable")}),a&&(0,r.jsx)("span",{style:{fontSize:12,color:"#f87171",overflowWrap:"anywhere"},children:a})]})]}),e.install?.skillsShUrl&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:5},children:[(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",fontWeight:500},children:"Source"}),(0,r.jsx)("a",{href:e.install.skillsShUrl,target:"_blank",rel:"noreferrer",title:e.install.skillsShUrl,style:{display:"flex",alignItems:"center",gap:8,width:"fit-content",maxWidth:"100%",color:"var(--accent)",textDecoration:"none"},children:(0,r.jsxs)("span",{style:{fontFamily:"var(--font-mono)",fontSize:12,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[e.install.skillsShUrl.replace(/^https?:\/\//,"")," ↗"]})})]}),e.install&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:7},children:[(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",fontWeight:500},children:"Version"}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10,flexWrap:"wrap"},children:[(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:12,color:"var(--text-muted)"},children:db(s?.currentVersion??e.install.versionHash)}),e.install.canCheckForUpdates&&(0,r.jsx)("button",{onClick:c,disabled:l||o,style:{padding:"4px 9px",border:"1px solid var(--border)",borderRadius:5,background:"none",color:"var(--text-muted)",cursor:l||o?"not-allowed":"pointer",opacity:l||o?.5:1,fontSize:11},children:p("i18n.check")}),s?.state==="update-available"&&(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:12,color:"#d97706"},children:db(s.latestVersion)}),(l||s&&"update-available"!==s.state)&&(0,r.jsx)("span",{style:{fontSize:12,color:l?"var(--accent)":s?.state==="up-to-date"?"#16a34a":s?.state==="error"?"#ef4444":"var(--text-dim)"},children:l?p("i18n.checking"):s?.state==="up-to-date"?p("i18n.upToDate"):s?.state==="unsupported"?p("i18n.automaticChecksUnavailable"):s?.message||p("i18n.checkFailed")}),s?.state==="update-available"&&(0,r.jsx)("button",{onClick:u,disabled:o||l,style:{padding:"4px 10px",border:"none",borderRadius:5,background:"var(--seed-color-bg-neutral-inverted)",color:"var(--seed-color-fg-neutral-inverted)",cursor:o||l?"not-allowed":"pointer",opacity:o||l?.5:1,fontSize:11,fontWeight:600},children:p(o?"i18n.updating":"i18n.update")})]}),d&&(0,r.jsx)("span",{style:{fontSize:12,color:"#ef4444"},children:d})]}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:5},children:[(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",fontWeight:500},children:"Name"}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:14,color:"var(--text)"},children:e.name})]}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:5},children:[(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",fontWeight:500},children:"Description"}),(0,r.jsx)("span",{style:{fontSize:14,color:"var(--text-muted)",lineHeight:1.6},children:e.description})]})]})}function dk({cwd:e,installedPackages:t,projectResourcesLoaded:n,onInstalled:a}){let{t:s}=(0,R.s)(),[l,o]=(0,i.useState)(""),[d,c]=(0,i.useState)([]),[u,p]=(0,i.useState)(!1),[h,m]=(0,i.useState)(null),[f,g]=(0,i.useState)(null),[x,v]=(0,i.useState)(null),[b,y]=(0,i.useState)(new Set),[w,k]=(0,i.useState)("global"),j=(0,i.useRef)(null);(0,i.useEffect)(()=>{j.current?.focus()},[]);let S=(0,i.useCallback)(async e=>{if(e.trim()){p(!0),m(null),c([]);try{let t=await fetch("/api/skills/search",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({query:e.trim()})}),n=await t.json();if(n.error)return void m(n.error);c(n.results??[]),0===(n.results??[]).length&&m("No skills found")}catch(e){m(String(e))}finally{p(!1)}}},[]),C=(0,i.useCallback)(async t=>{g(t),v(null);try{let n=await fetch("/api/skills/install",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({package:t,scope:w,cwd:e})}),r=await n.json();if(!n.ok||r.error)return void v(r.error??`HTTP ${n.status}`);y(e=>new Set(e).add(`${w}:${t}`)),a()}catch(e){v(String(e))}finally{g(null)}},[a,w,e]),N="global"===w?"~/.claude/skills/":`${df(e)}/.claude/skills/`;return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%"},children:[(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:12,marginBottom:20},children:[(0,r.jsx)("div",{style:{fontSize:14,fontWeight:600,color:"var(--text)"},children:s("i18n.addSkill")}),(0,r.jsxs)("div",{style:{display:"flex",gap:8},children:[(0,r.jsx)("input",{ref:j,value:l,onChange:e=>o(e.target.value),onKeyDown:e=>{"Enter"===e.key&&S(l)},placeholder:s("i18n.skillSearchPlaceholder"),style:{flex:1,padding:"7px 10px",fontSize:13,background:"var(--bg-panel)",border:"1px solid var(--border)",borderRadius:6,color:"var(--text)",outline:"none"}}),(0,r.jsx)("button",{onClick:()=>S(l),disabled:u||!l.trim(),style:{padding:"7px 16px",fontSize:13,borderRadius:6,border:"none",background:"var(--seed-color-bg-neutral-inverted)",color:"var(--seed-color-fg-neutral-inverted)",cursor:u||!l.trim()?"not-allowed":"pointer",opacity:u||!l.trim()?.5:1,flexShrink:0},children:u?s("i18n.searching"):s("i18n.search")})]}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10},children:[(0,r.jsx)("div",{style:{display:"flex",borderRadius:5,border:"1px solid var(--border)",overflow:"hidden",fontSize:12,flexShrink:0},children:["global","project"].map(e=>(0,r.jsx)("button",{onClick:()=>{("global"===e||n)&&k(e)},disabled:"project"===e&&!n,title:"project"!==e||n?void 0:s("trust.projectScopeUnavailable"),style:{padding:"3px 10px",border:"none",cursor:"project"!==e||n?"pointer":"not-allowed",background:w===e?"var(--bg-selected)":"none",color:w===e?"var(--text)":"var(--text-dim)",fontWeight:w===e?600:400,opacity:"project"!==e||n?1:.45,borderRight:"global"===e?"1px solid var(--border)":"none"},children:e},e))}),(0,r.jsxs)("span",{style:{fontSize:12,color:"var(--text-dim)",fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:["→ ",N]})]}),h&&(0,r.jsx)("div",{style:{fontSize:12,color:"#f87171"},children:h}),x&&(0,r.jsx)("div",{style:{fontSize:12,color:"#f87171",wordBreak:"break-word"},children:x})]}),d.length>0?(0,r.jsx)("div",{style:{flex:1,overflowY:"auto"},children:d.map(e=>{let n=t[w].has(e.package)||b.has(`${w}:${e.package}`),i=f===e.package,a=e.package.indexOf("@"),l=a>-1?e.package.slice(0,a):e.package,o=a>-1?e.package.slice(a+1):null;return(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:14,padding:"12px 0",borderBottom:"1px solid var(--border)"},children:[(0,r.jsxs)("div",{style:{flex:1,minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:13,fontWeight:600,color:"var(--text)",marginBottom:3},children:o??l}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10,flexWrap:"wrap"},children:[(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:11,color:"var(--text-dim)"},children:l}),(0,r.jsx)("span",{style:{fontSize:12,color:"var(--text-muted)",fontWeight:500},children:e.installs}),e.url&&(0,r.jsx)("a",{href:e.url,target:"_blank",rel:"noreferrer",style:{fontSize:12,color:"var(--accent)",textDecoration:"none"},children:"skills.sh ↗"})]})]}),(0,r.jsx)("button",{onClick:()=>!n&&!i&&C(e.package),disabled:n||i||null!==f,style:{flexShrink:0,padding:"5px 14px",fontSize:12,fontWeight:500,borderRadius:5,border:"1px solid var(--border)",cursor:n||i||null!==f?"not-allowed":"pointer",background:n?"rgba(34,197,94,0.1)":"none",color:n?"#16a34a":i?"var(--accent)":"var(--text-muted)",transition:"color 0.12s"},children:n?`✓ ${s("i18n.installed")}`:i?s("i18n.installing"):s("i18n.install")})]},e.package)})}):!h&&!u&&(0,r.jsxs)("div",{style:{fontSize:13,color:"var(--text-dim)",lineHeight:1.8},children:["Search"," ",(0,r.jsx)("a",{href:"https://skills.sh",target:"_blank",rel:"noreferrer",style:{color:"var(--accent)",textDecoration:"none"},children:"skills.sh"})," ","to discover and install skills for your agent."]})]})}function dj({cwd:e,onClose:t,embedded:n=!1}){let a=W(),{t:s}=(0,R.s)(),[l,o]=(0,i.useState)([]),[d,c]=(0,i.useState)(!0),[u,p]=(0,i.useState)(null),[h,m]=(0,i.useState)(null),[f,g]=(0,i.useState)(new Set),[x,v]=(0,i.useState)(null),[b,y]=(0,i.useState)(!1),[w,k]=(0,i.useState)({}),[j,S]=(0,i.useState)(new Set),[C,N]=(0,i.useState)(!1),[I,T]=(0,i.useState)(null),[M,$]=(0,i.useState)(null),[E,L]=(0,i.useState)(!0),[A,z]=(0,i.useState)({}),P=(0,i.useCallback)(async()=>{c(!0),p(null);try{let t=await fetch(`/api/skills?cwd=${encodeURIComponent(e)}`),n=await t.json();if(!t.ok||n.error)throw Error(n.error??`HTTP ${t.status}`);let r=n.skills??[];if(o(r),L(n.projectResourcesLoaded??!0),r.length>0&&!h){let e=r.find(e=>!e.disableModelInvocation)??r[0];m(e.filePath),e.disableModelInvocation&&z(t=>({...t,[dx(e)]:!0}))}return r}catch(e){return p(String(e)),[]}finally{c(!1)}},[e,h]);(0,i.useEffect)(()=>{k({}),$(null),P()},[e]);let F=(0,i.useCallback)(async t=>{let n=(t?[t]:l.filter(e=>!!e.install)).map(dv).filter(e=>!!e);if(0!==n.length){$(null),S(e=>new Set([...e,...n])),t||N(!0);try{let n=await fetch("/api/skills/check",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e,package:t?.install?.package,scope:t?.install?.scope})}),r=await n.json();if(!n.ok||r.error)throw Error(r.error??`HTTP ${n.status}`);k(e=>{let t={...e};for(let e of r.updates??[])t[`${e.scope}\0${e.package}`]=e;return t})}catch(e){$(e instanceof Error?e.message:String(e))}finally{S(e=>{let t=new Set(e);for(let e of n)t.delete(e);return t}),t||N(!1)}}},[e,l]),_=(0,i.useCallback)(async t=>{if(!t.install)return;let n=dv(t);T(n),$(null);try{let r=await fetch("/api/skills/update",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e,package:t.install.package,scope:t.install.scope})}),i=await r.json();if(!r.ok||i.error||!i.success)throw Error(i.error??`HTTP ${r.status}`);await P();let a=i.skill?.install?.versionHash;k(e=>({...e,[n]:{package:t.install.package,scope:t.install.scope,state:"up-to-date",currentVersion:a,latestVersion:a}}))}catch(e){$(e instanceof Error?e.message:String(e))}finally{T(null)}},[e,P]),D=(0,i.useCallback)(async e=>{let t=!e.disableModelInvocation;g(t=>new Set(t).add(e.filePath)),v(null);try{let n=await fetch("/api/skills",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({filePath:e.filePath,disableModelInvocation:t})}),r=await n.json();if(!n.ok||r.error)return void v(r.error??`HTTP ${n.status}`);o(n=>n.map(n=>n.filePath===e.filePath?{...n,disableModelInvocation:t}:n)),t&&z(t=>({...t,[dx(e)]:!0}))}catch(e){v(String(e))}finally{g(t=>{let n=new Set(t);return n.delete(e.filePath),n})}},[]),O=l.find(e=>e.filePath===h)??null;return(0,r.jsx)("div",{style:{position:n?"relative":"fixed",inset:n?void 0:0,width:"100%",height:"100%",zIndex:n?void 0:1e3,background:n?"transparent":"rgba(0,0,0,0.35)",display:"flex",alignItems:"center",justifyContent:"center"},onClick:e=>{n||e.target!==e.currentTarget||t()},children:(0,r.jsxs)("div",{style:{width:n?"100%":a?"calc(100vw - 16px)":860,maxWidth:n?"none":"calc(100vw - 16px)",height:n?"100%":a?"calc(100dvh - 16px)":"78vh",maxHeight:n?"none":"calc(100dvh - 16px)",background:"var(--bg)",border:n?"none":"1px solid var(--border)",borderRadius:10*!n,display:"flex",flexDirection:"column",boxShadow:n?"none":"0 8px 32px rgba(0,0,0,0.18)",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 18px",borderBottom:"1px solid var(--border)",flexShrink:0},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"baseline",gap:10},children:[(0,r.jsx)("span",{style:{fontSize:15,fontWeight:700,color:"var(--text)"},children:s("common.skills")}),(0,r.jsx)("code",{style:{fontSize:11,color:"var(--text-muted)",fontFamily:"var(--font-mono)",maxWidth:320,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:df(e)})]}),(0,r.jsx)("button",{onClick:t,style:{background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",fontSize:20,lineHeight:1,padding:"2px 6px"},children:"\xd7"})]}),!E&&(0,r.jsx)("div",{role:"status",style:{padding:"8px 18px",borderBottom:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)",fontSize:12},children:s("trust.skillsNotLoaded")}),(0,r.jsxs)("div",{style:{flex:1,display:"flex",flexDirection:a?"column":"row",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{width:a?"100%":210,maxHeight:a?"40vh":void 0,borderRight:a?"none":"1px solid var(--border)",borderBottom:a?"1px solid var(--border)":"none",display:"flex",flexDirection:"column",flexShrink:0,background:"var(--bg-panel)"},children:[(0,r.jsx)("div",{style:{flex:1,overflowY:"auto",padding:"8px 6px"},children:d?(0,r.jsx)("div",{style:{padding:"10px 8px",fontSize:12,color:"var(--text-muted)"},children:s("i18n.loading")}):u?(0,r.jsx)("div",{style:{padding:"10px 8px",fontSize:11,color:"#f87171"},children:u}):0===l.length?(0,r.jsx)("div",{style:{padding:"10px 8px",fontSize:11,color:"var(--text-dim)"},children:s("i18n.noSkills")}):(()=>{let e=[];for(let{label:t,matches:n}of[{label:"project / skills.sh",matches:e=>"project"===dg(e)&&!!e.install?.skillsShUrl},{label:"project",matches:e=>"project"===dg(e)&&!e.install?.skillsShUrl},{label:"global / skills.sh",matches:e=>"global"===dg(e)&&!!e.install?.skillsShUrl},{label:"global",matches:e=>"global"===dg(e)&&!e.install?.skillsShUrl},{label:"path",matches:e=>"path"===dg(e)}]){let r=l.filter(n);r.length>0&&e.push({label:t,skills:r})}let t=e=>{let t,n,i=!b&&h===e.filePath,a=e.disableModelInvocation;return(0,r.jsxs)("div",{onClick:()=>{m(e.filePath),y(!1)},style:{display:"flex",alignItems:"center",gap:7,padding:"8px 8px",borderRadius:5,cursor:"pointer",background:i?"var(--bg-selected)":"none"},onMouseEnter:e=>{i||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{i||(e.currentTarget.style.background="none")},children:[(0,r.jsx)("span",{style:{flexShrink:0,width:7,height:7,borderRadius:"50%",background:a?"var(--border)":"var(--accent)",boxShadow:a?"none":"0 0 4px var(--accent)",transition:"background 0.15s, box-shadow 0.15s"}}),(0,r.jsx)("span",{style:{fontSize:12,fontWeight:i?600:400,color:a?"var(--text-dim)":"var(--text)",fontFamily:"var(--font-mono)",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name}),(n=(t=dv(e))?w[t]:void 0,n?.state!=="update-available"?null:(0,r.jsx)("span",{title:s("i18n.updateAvailable"),style:{color:"#d97706",fontSize:13,lineHeight:1,flexShrink:0},children:"↑"}))]},e.filePath)};return e.map(({label:e,skills:n})=>{let i=n.filter(e=>!e.disableModelInvocation),a=n.filter(e=>e.disableModelInvocation),l=A[e]??!1;return(0,r.jsxs)("div",{style:{marginBottom:6},children:[(0,r.jsx)("div",{style:{padding:"4px 8px 3px",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.06em"},children:e}),i.map(t),a.length>0&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("div",{onClick:()=>z(t=>({...t,[e]:!l})),style:{display:"flex",alignItems:"center",gap:5,padding:"4px 8px 3px",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.06em",cursor:"pointer",userSelect:"none"},children:[(0,r.jsx)("span",{style:{fontSize:8},children:l?"▾":"▸"}),s("i18n.dormant")," (",a.length,")"]}),l&&a.map(t)]})]},e)})})()}),(0,r.jsx)("div",{style:{padding:"8px 6px",borderTop:"1px solid var(--border)",flexShrink:0},children:(0,r.jsxs)("div",{onClick:()=>y(!0),style:{display:"flex",alignItems:"center",gap:6,padding:"7px 8px",borderRadius:5,cursor:"pointer",background:b?"var(--bg-selected)":"none",color:b?"var(--accent)":"var(--text-dim)",fontSize:12},onMouseEnter:e=>{b||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{b||(e.currentTarget.style.background="none")},children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),(0,r.jsx)("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]}),s("i18n.addSkill")]})})]}),(0,r.jsx)("div",{style:{flex:1,overflowY:"auto",padding:20},children:b?(0,r.jsx)(dk,{cwd:e,projectResourcesLoaded:E,installedPackages:{global:new Set(l.filter(e=>e.install?.scope==="global").map(e=>e.install.package)),project:new Set(l.filter(e=>e.install?.scope==="project").map(e=>e.install.package))},onInstalled:()=>{P()}}):d?null:O?(0,r.jsx)(dw,{skill:O,cwd:e,onToggle:D,toggling:f.has(O.filePath),saveError:x,updateStatus:dv(O)?w[dv(O)]:void 0,checkingUpdate:!!dv(O)&&j.has(dv(O)),updating:I===dv(O),updateError:M,onCheckUpdate:()=>void F(O),onUpdate:()=>void _(O)},O.filePath):(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-dim)",fontSize:13},children:s("i18n.selectSkill")})})]}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 18px",borderTop:"1px solid var(--border)",flexShrink:0},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10},children:[l.some(e=>!!e.install)&&(0,r.jsx)("button",{onClick:()=>void F(),disabled:C||null!==I,style:{padding:"6px 12px",background:"none",border:"1px solid var(--border)",borderRadius:6,color:"var(--text-muted)",cursor:C||null!==I?"not-allowed":"pointer",opacity:C||null!==I?.5:1,fontSize:12},children:C?s("i18n.checking"):s("i18n.checkUpdates")}),Object.values(w).filter(e=>"update-available"===e.state).length>0&&(0,r.jsxs)("span",{style:{fontSize:12,color:"#d97706"},children:[Object.values(w).filter(e=>"update-available"===e.state).length," ",1===Object.values(w).filter(e=>"update-available"===e.state).length?s("i18n.update"):s("i18n.updates")]})]}),(0,r.jsx)("button",{onClick:t,style:{padding:"6px 14px",background:"none",border:"1px solid var(--border)",borderRadius:6,color:"var(--text-muted)",cursor:"pointer",fontSize:13},children:s("i18n.close")})]})]})})}let dS="global";function dC(e){return e.replace(/^\/(?:Users|home)\/[^/]+/,"~")}function dN(e){let t=e.trim().match(/^\$?\s*omp\s+plugin\s+(?:add|install)\s+(\S+)\s*$/);return t?.[1]??e}function dI(e){return`${e.scope}\0${e.source}`}function dT(e,t){if(e.disabled)return t("i18n.disabled");let n=[e.counts.extensions?t("i18n.resourceCount",{count:e.counts.extensions,label:t("i18n.extensionShort")}):"",e.counts.skills?t("i18n.resourceCount",{count:e.counts.skills,label:t("i18n.skillShort")}):"",e.counts.prompts?t("i18n.resourceCount",{count:e.counts.prompts,label:t("i18n.promptShort")}):"",e.counts.themes?t("i18n.resourceCount",{count:e.counts.themes,label:t("i18n.themeShort")}):""].filter(Boolean);return n.length?n.join(" \xb7 "):t("i18n.noResources")}function dM(e,t){let n=[];return e.version&&n.push(t("i18n.installedVersion",{version:e.version})),e.configuredVersion&&n.push(t("i18n.configuredVersion",{version:e.configuredVersion})),n.length?n.join(" \xb7 "):t("i18n.unknown")}function d$(e){return"loaded"===e?"var(--accent)":"installed"===e?"#f59e0b":"disabled"===e?"var(--text-dim)":"#ef4444"}function dR({pkg:e}){let{t}=(0,R.s)(),n=[["extension",t("i18n.extensions")],["skill",t("i18n.skills")],["prompt",t("i18n.prompts")],["theme",t("i18n.themes")]].map(([t,n])=>({kind:t,label:n,resources:e.resources.filter(e=>e.kind===t)})).filter(e=>e.resources.length>0);return 0===n.length?(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text-dim)"},children:t(e.disabled?"i18n.packageDisabled":"i18n.noResolvedResources")}):(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:12},children:n.map((e,t)=>(0,r.jsxs)("div",{style:{borderTop:0===t?"none":"1px solid var(--border)",paddingTop:12*(0!==t)},children:[(0,r.jsx)("div",{style:{fontSize:10,fontWeight:700,color:"var(--text-dim)",textTransform:"uppercase",marginBottom:6},children:e.label}),(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:e.resources.map(e=>(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text)",fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:e.path,children:e.name}),(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",marginTop:1},title:e.path,children:e.relativePath})]},`${e.kind}:${e.path}`))})]},e.kind))})}function dE({scope:e}){return(0,r.jsx)("span",{style:{fontSize:10,padding:"1px 5px",borderRadius:3,flexShrink:0,background:"project"===e?"rgba(99,102,241,0.12)":"rgba(120,120,120,0.12)",color:"project"===e?"rgba(99,102,241,0.85)":"var(--text-dim)"},children:e})}function dL(e,t){return{padding:"6px 12px",background:t?"rgba(239,68,68,0.08)":"none",border:"1px solid var(--border)",borderRadius:6,color:t?"#ef4444":"var(--text-muted)",cursor:e?"not-allowed":"pointer",fontSize:12,opacity:e?.5:1}}function dA({enabled:e,loading:t,onToggle:n,label:i}){return(0,r.jsx)("button",{type:"button",onClick:n,disabled:t,title:i,"aria-label":i,"aria-pressed":e,style:{flexShrink:0,width:40,height:22,borderRadius:11,border:"none",padding:0,cursor:t?"wait":"pointer",background:e?"var(--accent)":"var(--border)",position:"relative",transition:"background 0.18s",outline:"none",opacity:t?.65:1},children:(0,r.jsx)("span",{style:{position:"absolute",top:3,left:e?21:3,width:16,height:16,borderRadius:"50%",background:"var(--bg)",boxShadow:"0 1px 4px rgba(0,0,0,0.22)",transition:"left 0.18s cubic-bezier(.4,0,.2,1)"}})})}function dz({installDir:e,source:t,busy:n,actionError:a,onSourceChange:s,onInstall:l}){let{t:o}=(0,R.s)(),d=(0,i.useRef)(null);return(0,i.useEffect)(()=>{d.current?.focus()},[]),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:18,maxWidth:660,minHeight:"100%"},children:[(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:5},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12,flexWrap:"wrap"},children:[(0,r.jsx)("div",{style:{fontSize:14,fontWeight:700,color:"var(--text)"},children:o("i18n.addPlugin")}),(0,r.jsxs)("a",{href:"https://github.com/can1357/oh-my-pi#plugins",target:"_blank",rel:"noopener noreferrer",style:{display:"inline-flex",alignItems:"center",gap:5,color:"var(--accent)",fontSize:12,textDecoration:"none",whiteSpace:"nowrap"},children:[(0,r.jsxs)("svg",{width:"28",height:"28",viewBox:"0 0 800 800","aria-hidden":"true",focusable:"false",style:{flexShrink:0},children:[(0,r.jsx)("path",{fill:"#000",fillRule:"evenodd",d:"M165.29 165.29H517.36V400H400V517.36H282.65V634.72H165.29ZM282.65 282.65V400H400V282.65Z"}),(0,r.jsx)("path",{fill:"#000",d:"M517.36 400H634.72V634.72H517.36Z"})]}),"oh-my-pi plugins"]})]}),e&&(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text-dim)",fontFamily:"var(--font-mono)",overflowWrap:"anywhere"},children:dC(e)})]}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:7},children:[(0,r.jsx)("label",{htmlFor:"plugin-source",style:{fontSize:12,fontWeight:600,color:"var(--text-muted)"},children:"Source"}),(0,r.jsx)("input",{id:"plugin-source",ref:d,value:t,onChange:e=>s(e.target.value),onPaste:e=>{let t=e.clipboardData.getData("text"),n=dN(t);n!==t&&(e.preventDefault(),s(n))},onBlur:e=>s(dN(e.currentTarget.value)),placeholder:"@scope/package or github:user/repo",style:{width:"100%",height:36,padding:"0 11px",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-panel)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:13,outline:"none"},onKeyDown:e=>{"Enter"===e.key&&t.trim()&&!n&&l()}})]}),(0,r.jsx)("div",{style:{display:"flex",alignItems:"center",gap:10,flexWrap:"wrap"},children:(0,r.jsx)("button",{type:"button",onClick:l,disabled:n||!t.trim(),style:{...dL(n||!t.trim()),background:"var(--seed-color-bg-neutral-inverted)",color:"var(--seed-color-fg-neutral-inverted)",borderColor:"transparent"},children:o(n?"i18n.installing":"i18n.install")})}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:7},children:[(0,r.jsx)("div",{style:{fontSize:12,fontWeight:600,color:"var(--text-muted)"},children:"Examples"}),(0,r.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:["@scope/omp-plugin","github:user/repo","pkg[feature]"].map(e=>(0,r.jsx)("button",{type:"button",onClick:()=>s(e),style:{width:"100%",minHeight:30,textAlign:"left",padding:"6px 9px",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg-panel)",color:"var(--text-dim)",cursor:"pointer",fontFamily:"var(--font-mono)",fontSize:11},onMouseEnter:e=>{e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text-muted)"},onMouseLeave:e=>{e.currentTarget.style.background="var(--bg-panel)",e.currentTarget.style.color="var(--text-dim)"},children:e},e))})]}),a&&(0,r.jsx)("div",{style:{fontSize:12,color:"#ef4444",whiteSpace:"pre-wrap"},children:a})]})}function dP({pkg:e,cwd:t,busyKey:n,actionError:i,actionMessage:a,sessionId:s,onAction:l,onReloadSession:o}){let{t:d}=(0,R.s)(),c=dI(e),u=n?.endsWith(c)??!1,p="reload"===n,h=!e.disabled;return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:20,maxWidth:680},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:12,minWidth:0,flexWrap:"wrap"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:180,flex:1},children:[(0,r.jsx)(dA,{enabled:h,loading:u||p,onToggle:()=>l(e.disabled?"enable":"disable",e),label:d(e.disabled?"i18n.enablePackage":"i18n.disablePackage")}),(0,r.jsx)(dE,{scope:e.scope}),e.disabled?(0,r.jsx)("span",{style:{fontSize:10,padding:"1px 5px",borderRadius:3,background:"rgba(120,120,120,0.12)",color:"var(--text-dim)"},children:d("i18n.disabled")}):e.filtered&&(0,r.jsx)("span",{style:{fontSize:10,padding:"1px 5px",borderRadius:3,background:"rgba(245,158,11,0.12)",color:"#d97706"},children:d("i18n.filtered")}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",fontSize:12,color:"var(--text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.source})]}),(0,r.jsxs)("div",{style:{display:"flex",gap:8,flexWrap:"wrap"},children:[(0,r.jsx)("button",{onClick:()=>l("update",e),disabled:u||p,style:dL(u||p),children:d(n===`update:${c}`?"i18n.updating":"i18n.update")}),(0,r.jsx)("button",{onClick:o,disabled:!s||p||u,style:dL(!s||p||u),title:d(s?"i18n.reloadSessionHint":"i18n.openSessionToReload"),children:d(p?"i18n.reloading":"i18n.reloadSession")}),(0,r.jsx)("button",{onClick:()=>l("remove",e),disabled:u||p,style:dL(u||p,!0),children:d(n===`remove:${c}`?"i18n.removing":"i18n.remove")})]})]}),(0,r.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"minmax(96px, 130px) minmax(0, 1fr)",gap:"9px 14px",fontSize:12,lineHeight:1.45},children:[(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:d("i18n.status")}),(0,r.jsx)("div",{style:{color:d$(e.status),textTransform:"capitalize"},children:e.status}),(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:d("i18n.version")}),(0,r.jsx)("div",{style:{color:"var(--text-muted)",fontFamily:"var(--font-mono)"},children:dM(e,d)}),(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:d("i18n.package")}),(0,r.jsx)("div",{style:{color:"var(--text-muted)",fontFamily:"var(--font-mono)",overflowWrap:"anywhere"},children:e.packageName??d("i18n.unknown")}),(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:d("i18n.resources")}),(0,r.jsx)("div",{style:{color:"var(--text-muted)"},children:dT(e,d)}),(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:d("i18n.installedPath")}),(0,r.jsx)("div",{style:{color:e.installedPath?"var(--text-muted)":"#ef4444",fontFamily:"var(--font-mono)",overflowWrap:"anywhere"},children:e.installedPath?dC(e.installedPath):d("i18n.notFound")}),(0,r.jsx)("div",{style:{color:"var(--text-dim)"},children:d("i18n.cwd")}),(0,r.jsx)("div",{style:{color:"var(--text-dim)",fontFamily:"var(--font-mono)",overflowWrap:"anywhere"},children:dC(t)})]}),(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[(0,r.jsx)("div",{style:{fontSize:12,fontWeight:700,color:"var(--text)"},children:d("i18n.resolvedResources")}),(0,r.jsx)(dR,{pkg:e})]}),a&&(0,r.jsx)("div",{style:{fontSize:12,color:"#16a34a"},children:a}),i&&(0,r.jsx)("div",{style:{fontSize:12,color:"#ef4444",whiteSpace:"pre-wrap"},children:i})]})}function dW({cwd:e,sessionId:t,onClose:n,onReloaded:a,embedded:s=!1}){let l=W(),{t:o}=(0,R.s)(),[d,c]=(0,i.useState)(null),[u,p]=(0,i.useState)(!0),[h,m]=(0,i.useState)(null),[f,g]=(0,i.useState)(null),[x,v]=(0,i.useState)(!1),[b,y]=(0,i.useState)(""),[w,k]=(0,i.useState)(null),[j,S]=(0,i.useState)(null),[C,N]=(0,i.useState)(null),I=(0,i.useMemo)(()=>d?.packages??[],[d?.packages]),T=I.find(e=>dI(e)===f)??null,M=d?.projectResourcesLoaded??!0,$=(0,i.useMemo)(()=>["project","global"].map(e=>({scope:e,packages:I.filter(t=>t.scope===e)})).filter(e=>e.packages.length>0),[I]),E=(0,i.useCallback)(async()=>{p(!0),m(null);try{let t=await fetch(`/api/plugins?cwd=${encodeURIComponent(e)}`),n=await t.json();if(!t.ok||n.error)throw Error(n.error??`HTTP ${t.status}`);c(n),v(e=>0===n.packages.length||e),g(e=>e&&n.packages.some(t=>dI(t)===e)?e:n.packages[0]?dI(n.packages[0]):null)}catch(e){m(e instanceof Error?e.message:String(e))}finally{p(!1)}},[e]);(0,i.useEffect)(()=>{E()},[E]);let L=(0,i.useCallback)(async(t,n)=>{let r=dI(n);k(`${t}:${r}`),S(null),N(null);try{let r=await fetch("/api/plugins",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:t,source:n.source,scope:n.scope,cwd:e})}),i=await r.json();if(!r.ok||i.error)throw Error(i.error??`HTTP ${r.status}`);if(c(i),"remove"===t)g(i.packages[0]?dI(i.packages[0]):null),0===i.packages.length&&v(!0),N(o("i18n.packageRemoved"));else{let e={install:o("i18n.packageInstalled"),update:o("i18n.packageUpdated"),disable:o("i18n.packageDisabledRestartRequired"),enable:o("i18n.packageEnabled")};N(e[t])}}catch(e){S(e instanceof Error?e.message:String(e))}finally{k(null)}},[e,o]),A=(0,i.useCallback)(async()=>{let t=dN(b).trim();if(!t)return;y(t);let n=`${dS}\0${t}`;k(`install:${n}`),S(null),N(null);try{var r;let i,a,s=await fetch("/api/plugins",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"install",source:t,scope:dS,cwd:e})}),l=await s.json();if(!s.ok||l.error)throw Error(l.error??`HTTP ${s.status}`);c(l);let d=(r=l.packages,a=(i=t.trim()).startsWith("npm:")?i.slice(4):i,r.find(e=>e.scope===dS&&e.source===i)??r.find(e=>e.scope===dS&&e.source===`npm:${a}`)??r.find(e=>e.scope===dS&&e.source.endsWith(i)));g(d?dI(d):n),v(!1),y(""),N(o("i18n.packageInstalled"))}catch(e){S(e instanceof Error?e.message:String(e))}finally{k(null)}},[e,b,o]),z=(0,i.useCallback)(async()=>{if(t){k("reload"),S(null),N(null);try{await sB(t,{type:"reload"}),a?.(),await E(),N(o("i18n.sessionReloaded"))}catch(e){S(e instanceof Error?e.message:String(e))}finally{k(null)}}},[E,a,t,o]),P=w?.startsWith("install:")??!1;return(0,r.jsx)("div",{style:{position:s?"relative":"fixed",inset:s?void 0:0,width:"100%",height:"100%",zIndex:s?void 0:1e3,background:s?"transparent":"rgba(0,0,0,0.35)",display:"flex",alignItems:"center",justifyContent:"center"},onClick:e=>{s||e.target!==e.currentTarget||n()},children:(0,r.jsxs)("div",{style:{width:s?"100%":l?"calc(100vw - 16px)":860,maxWidth:s?"none":"calc(100vw - 16px)",height:s?"100%":l?"calc(100dvh - 16px)":"76vh",maxHeight:s?"none":"calc(100dvh - 16px)",background:"var(--bg)",border:s?"none":"1px solid var(--border)",borderRadius:8*!s,display:"flex",flexDirection:"column",boxShadow:s?"none":"0 8px 32px rgba(0,0,0,0.18)",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 18px",borderBottom:"1px solid var(--border)",flexShrink:0},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"baseline",gap:10,minWidth:0},children:[(0,r.jsx)("span",{style:{fontSize:15,fontWeight:700,color:"var(--text)"},children:o("common.plugins")}),(0,r.jsx)("code",{style:{fontSize:11,color:"var(--text-muted)",fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:dC(e)})]}),(0,r.jsx)("button",{onClick:n,style:{background:"none",border:"none",color:"var(--text-muted)",cursor:"pointer",fontSize:20,lineHeight:1,padding:"2px 6px"},children:"\xd7"})]}),!M&&(0,r.jsx)("div",{role:"status",style:{padding:"8px 18px",borderBottom:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--text-muted)",fontSize:12},children:o("trust.pluginsNotLoaded")}),(0,r.jsxs)("div",{style:{flex:1,display:"flex",flexDirection:l?"column":"row",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{width:l?"100%":245,maxHeight:l?"40vh":void 0,borderRight:l?"none":"1px solid var(--border)",borderBottom:l?"1px solid var(--border)":"none",display:"flex",flexDirection:"column",flexShrink:0,background:"var(--bg-panel)"},children:[(0,r.jsx)("div",{style:{flex:1,overflowY:"auto",padding:"8px 6px"},children:u?(0,r.jsx)("div",{style:{padding:"10px 8px",fontSize:12,color:"var(--text-muted)"},children:"Loading..."}):h?(0,r.jsx)("div",{style:{padding:"10px 8px",fontSize:11,color:"#ef4444"},children:h}):0===I.length?(0,r.jsx)("div",{style:{padding:"10px 8px",fontSize:11,color:"var(--text-dim)"},children:"No plugins configured"}):$.map(e=>(0,r.jsxs)("div",{style:{marginBottom:6},children:[(0,r.jsx)("div",{style:{padding:"4px 8px 3px",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase"},children:e.scope}),e.packages.map(e=>{let t=dI(e),n=!x&&f===t;return(0,r.jsxs)("div",{onClick:()=>{g(t),v(!1),S(null),N(null)},style:{display:"flex",alignItems:"center",gap:7,padding:"8px 8px",borderRadius:5,cursor:"pointer",background:n?"var(--bg-selected)":"none"},onMouseEnter:e=>{n||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{n||(e.currentTarget.style.background="none")},children:[(0,r.jsx)("span",{style:{flexShrink:0,width:7,height:7,borderRadius:"50%",background:d$(e.status)}}),(0,r.jsxs)("div",{style:{minWidth:0,flex:1},children:[(0,r.jsx)("div",{style:{fontSize:12,fontWeight:n?600:400,color:"var(--text)",fontFamily:"var(--font-mono)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.source}),(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",marginTop:2},children:dT(e,o)}),(e.version||e.configuredVersion)&&(0,r.jsx)("div",{style:{fontSize:10,color:"var(--text-dim)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",marginTop:2},children:dM(e,o)})]})]},t)})]},e.scope))}),(0,r.jsx)("div",{style:{padding:"8px 6px",borderTop:"1px solid var(--border)",flexShrink:0},children:(0,r.jsxs)("button",{type:"button",onClick:()=>{v(!0),S(null),N(null)},style:{display:"flex",alignItems:"center",gap:6,padding:"7px 8px",borderRadius:5,border:"none",width:"100%",cursor:"pointer",background:x?"var(--bg-selected)":"none",color:x?"var(--accent)":"var(--text-dim)",fontSize:12},onMouseEnter:e=>{x||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{x||(e.currentTarget.style.background="none")},children:[(0,r.jsxs)("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,r.jsx)("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),(0,r.jsx)("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]}),o("i18n.addPlugin")]})})]}),(0,r.jsx)("div",{style:{flex:1,overflowY:"auto",padding:20},children:x?(0,r.jsx)(dz,{installDir:d?.installDir,source:b,busy:P,actionError:j,onSourceChange:y,onInstall:A}):u?null:T?(0,r.jsx)(dP,{pkg:T,cwd:e,busyKey:w,actionError:j,actionMessage:C,sessionId:t,onAction:L,onReloadSession:z},dI(T)):(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-dim)",fontSize:13},children:o("i18n.selectPackage")})})]}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12,padding:"10px 18px",borderTop:"1px solid var(--border)",flexShrink:0},children:[(0,r.jsx)("div",{style:{minWidth:0,flex:1,fontSize:11,color:"var(--text-dim)",overflow:"hidden"},children:d?.diagnostics.length?(0,r.jsxs)("span",{title:d.diagnostics.map(e=>`${e.type}: ${e.source?`${e.source}: `:""}${e.message}`).join("\n"),style:{color:d.diagnostics.some(e=>"error"===e.type)?"#ef4444":"#d97706"},children:[d.diagnostics.length," diagnostic",1===d.diagnostics.length?"":"s"]}):(0,r.jsx)("span",{children:d?`${d.totals.extensions} ext \xb7 ${d.totals.skills} skills \xb7 ${d.totals.prompts} prompts \xb7 ${d.totals.themes} themes`:""})}),(0,r.jsx)("button",{onClick:()=>void E(),disabled:u||null!==w,style:dL(u||null!==w),children:o("i18n.refresh")}),(0,r.jsx)("button",{onClick:n,style:dL(!1),children:o("i18n.close")})]})]})})}var dF=n(13004),d_=n.n(dF);function dD(){let[e,t]=(0,i.useState)(null),[n,a]=(0,i.useState)(null),[s,l]=(0,i.useState)(null),[o,d]=(0,i.useState)(null),[c,u]=(0,i.useState)(!1),[p,h]=(0,i.useState)(""),[m,f]=(0,i.useState)(""),g=(0,i.useCallback)(async()=>{try{let e=await fetch("/api/web-access",{cache:"no-store"}),n=await e.json();if(!e.ok||n.error)throw Error(n.error??`HTTP ${e.status}`);t(n),a(null)}catch(e){a(e instanceof Error?e.message:String(e))}},[]);(0,i.useEffect)(()=>{g()},[g]);let x=(0,i.useCallback)(async(e,n={})=>{u(!0),l(null),d(null);try{let r=await fetch("/api/web-access",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:e,...n})}),i=await r.json();if(!r.ok||i.error)throw Error(i.error??`HTTP ${r.status}`);return t(i),i}catch(e){return l(e instanceof Error?e.message:String(e)),null}finally{u(!1)}},[]),v=(0,i.useCallback)(async()=>{if(p!==m)return void l("The two passwords do not match.");let e=await x("set-password",{password:p});e&&(h(""),f(""),d(`Password saved and password access turned on. The browser will ask for the username "${e.username}" and this password on the next request.`))},[m,p,x]),b=(0,i.useCallback)(async()=>{if(!e)return;let t=await x(e.enabled?"disable":"enable");t&&d(t.enabled?`Password access is on. The browser will ask for the username "${t.username}" and your password on the next request.`:"Password access is off. The stored password is kept and can be switched back on here.")},[x,e]),y=(0,i.useCallback)(async()=>{await x("clear")&&d("The stored password was removed and password access is off.")},[x]);if(!e)return(0,r.jsx)("div",{className:d_().empty,children:n??"Loading password access…"});let w=e.managedByEnvironment,k=!c&&!w&&p.length>=8&&p===m;return(0,r.jsxs)("div",{className:d_().scrollContent,children:[(0,r.jsxs)("header",{className:d_().contentHeader,children:[(0,r.jsx)("h2",{className:d_().contentTitle,children:"Access"}),(0,r.jsxs)("p",{className:d_().contentDescription,children:["A password locks the web interface and every API endpoint behind HTTP Basic Auth, with the fixed username ",(0,r.jsx)("code",{children:e.username}),". It is stored as a scrypt hash in ",(0,r.jsx)("code",{children:e.file})," — CUELO never keeps the password itself, which is why forgetting it means recovering rather than reading it back."]}),w&&(0,r.jsxs)("div",{className:d_().readOnlyNotice,children:["Read-only \xb7 ",(0,r.jsx)("code",{children:"CUELO_PASSWORD"})," is set and overrides the stored credential. Unset it and restart CUELO to manage the password here."]}),o&&(0,r.jsx)("div",{className:d_().reloadNotice,children:(0,r.jsx)("span",{children:o})})]}),(0,r.jsxs)("div",{className:d_().settingsBody,children:[(0,r.jsxs)("section",{className:d_().group,children:[(0,r.jsx)("h3",{className:d_().groupTitle,children:"Password access"}),(0,r.jsxs)("div",{className:d_().settingRow,children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{className:d_().settingLabel,children:"Require a password"}),(0,r.jsx)("div",{className:d_().settingDescription,children:e.managedByEnvironment?"Every request needs the password from CUELO_PASSWORD.":e.unreadable?"The credential file exists but could not be read, so every request is being refused.":e.configured?e.enabled?"Every request needs the username and password.":"A password is stored but the lock is off.":"No password is set. Anyone who can reach this server can use it."}),!e.configured&&!w&&(0,r.jsx)("div",{className:d_().settingDescription,children:"Set a password below before turning this on."}),s&&(0,r.jsx)("div",{className:d_().error,children:s})]}),(0,r.jsx)("div",{className:d_().settingControl,children:(0,r.jsx)("button",{type:"button",className:d_().switch,"data-on":e.enabled,"aria-pressed":e.enabled,"aria-label":"Require a password",disabled:c||w||!e.enabled&&!e.stored,onClick:()=>void b()})})]})]}),(0,r.jsxs)("section",{className:d_().group,children:[(0,r.jsx)("h3",{className:d_().groupTitle,children:e.stored?"Replace the password":"Set a password"}),(0,r.jsxs)("div",{className:d_().settingRow,children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{className:d_().settingLabel,children:"New password"}),(0,r.jsxs)("div",{className:d_().settingDescription,children:["At least ",8," characters. Saving a password also turns password access on."]})]}),(0,r.jsx)("div",{className:d_().settingControl,children:(0,r.jsx)("input",{className:d_().textInput,type:"password",autoComplete:"new-password",value:p,disabled:c||w,onChange:e=>h(e.target.value)})})]}),(0,r.jsxs)("div",{className:d_().settingRow,children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{className:d_().settingLabel,children:"Confirm password"}),(0,r.jsx)("div",{className:d_().settingDescription,children:"Both entries have to match before it can be saved."})]}),(0,r.jsx)("div",{className:d_().settingControl,children:(0,r.jsx)("input",{className:d_().textInput,type:"password",autoComplete:"new-password",value:m,disabled:c||w,onChange:e=>f(e.target.value),onKeyDown:e=>{"Enter"===e.key&&k&&v()}})})]}),(0,r.jsxs)("div",{className:d_().editorActions,children:[(0,r.jsx)("div",{children:(0,r.jsx)("div",{className:d_().saveState,children:e.stored&&e.updatedAt?`Last changed ${new Date(e.updatedAt).toLocaleString()}`:"No password stored yet"})}),(0,r.jsxs)("div",{style:{display:"flex",gap:8},children:[e.stored&&!w&&(0,r.jsx)("button",{type:"button",className:d_().dangerButton,disabled:c,onClick:()=>void y(),children:"Remove password"}),(0,r.jsx)("button",{type:"button",className:d_().primaryButton,disabled:!k,onClick:()=>void v(),children:c?"Saving…":"Save password"})]})]})]}),(0,r.jsxs)("section",{className:d_().group,children:[(0,r.jsx)("h3",{className:d_().groupTitle,children:"If you forget it"}),(0,r.jsxs)("div",{className:d_().settingRow,children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{className:d_().settingLabel,children:"Recovery"}),(0,r.jsxs)("div",{className:d_().settingDescription,children:["Run ",(0,r.jsx)("code",{children:"cuelo --reset-password"})," on this machine to set a new one, or open ",(0,r.jsx)("code",{children:"/recover"})," in the browser: CUELO prints a one-time code on its own console, and entering that code sets a new password. Both paths require access to the machine running the server — nothing can hand the password back."]})]}),(0,r.jsx)("div",{className:d_().settingControl,children:(0,r.jsx)("a",{className:d_().linkButton,href:"/recover",target:"_blank",rel:"noreferrer",children:"Open /recover"})})]}),(0,r.jsxs)("div",{className:d_().settingRow,children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{className:d_().settingLabel,children:"Basic Auth is not encryption"}),(0,r.jsx)("div",{className:d_().settingDescription,children:"The password crosses the network in a reversible encoding. Over plain HTTP on an untrusted network it can be read in transit, so put CUELO behind HTTPS or a trusted VPN before exposing it beyond loopback."})]}),(0,r.jsx)("div",{className:d_().settingControl})]})]})]})]})}function dO(){let{t:e}=(0,R.s)(),[t,n]=(0,i.useState)(null),[a,s]=(0,i.useState)(!1),[l,o]=(0,i.useState)(null),d=(0,i.useCallback)(async()=>{try{let e=await fetch("/api/live/voices",{cache:"no-store"}),t=await e.json().catch(()=>({}));if(!e.ok||!Array.isArray(t.voices)||"string"!=typeof t.defaultVoice)throw Error(`HTTP ${e.status}`);n({voices:t.voices,defaultVoice:t.defaultVoice})}catch(e){o(e instanceof Error?e.message:String(e))}},[]);(0,i.useEffect)(()=>{d()},[d]);let c=async e=>{s(!0),o(null);try{let t=await fetch("/api/settings",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:"live.voice",value:e})}),r=await t.json().catch(()=>({}));if(!t.ok||r.error)throw Error(r.error??`HTTP ${t.status}`);let i="string"==typeof r.value?r.value:e;n(e=>e?{...e,defaultVoice:i}:e)}catch(e){o(e instanceof Error?e.message:String(e))}finally{s(!1)}};return t?(0,r.jsxs)("div",{className:d_().scrollContent,children:[(0,r.jsxs)("header",{className:d_().contentHeader,children:[(0,r.jsx)("h2",{className:d_().contentTitle,children:e("chat.liveVoiceSettingsTitle")}),(0,r.jsx)("p",{className:d_().contentDescription,children:e("chat.liveVoiceSettingsDescription")})]}),(0,r.jsx)("div",{className:d_().settingsBody,children:(0,r.jsxs)("section",{className:d_().group,children:[(0,r.jsx)("h3",{className:d_().groupTitle,children:e("chat.liveVoiceSpeakerGroup")}),(0,r.jsxs)("div",{className:d_().settingRow,children:[(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("div",{className:d_().settingLabel,children:e("chat.liveVoiceCodexLabel")}),(0,r.jsx)("div",{className:d_().settingDescription,children:e("chat.liveVoiceCodexHelp")}),l&&(0,r.jsx)("div",{className:d_().error,role:"alert",style:{overflowWrap:"anywhere"},children:l})]}),(0,r.jsx)("div",{className:d_().settingControl,children:(0,r.jsx)(ob,{value:t.defaultVoice,disabled:a,ariaLabel:e("chat.liveVoiceCodexLabel"),options:t.voices,onChange:e=>{e!==t.defaultVoice&&c(e)}})})]})]})})]}):(0,r.jsx)("div",{className:d_().empty,children:l?`${e("chat.liveVoiceLoadFailed")}: ${l}`:"…"})}function dH(){let{t:e}=(0,R.s)(),t=(0,i.useId)(),n=(0,i.useId)(),[a,s]=(0,i.useState)(null),[l,o]=(0,i.useState)(""),[d,c]=(0,i.useState)(null),[u,p]=(0,i.useState)(!1),[h,m]=(0,i.useState)(!1);(0,i.useEffect)(()=>{let e=new AbortController;return aX({signal:e.signal}).then(e=>{s(e),o(String(e.uploadLimitMb))}).catch(t=>{e.signal.aborted||c(t instanceof Error?t.message:String(t))}),()=>e.abort()},[]);let f=(0,i.useCallback)(async e=>{p(!0),c(null),m(!1);try{let t=await aQ(e);s(t),o(String(t.uploadLimitMb)),m(!0)}catch(e){c(e instanceof Error?e.message:String(e))}finally{p(!1)}},[]);return a?(0,r.jsxs)("div",{className:d_().scrollContent,children:[(0,r.jsxs)("header",{className:d_().contentHeader,children:[(0,r.jsx)("h2",{className:d_().contentTitle,children:e("chat.attachmentSettingsTitle")}),(0,r.jsx)("p",{className:d_().contentDescription,children:e("chat.attachmentSettingsDescription")})]}),(0,r.jsx)("div",{className:d_().settingsBody,children:(0,r.jsxs)("section",{className:d_().group,children:[(0,r.jsxs)("div",{className:d_().settingRow,children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("label",{htmlFor:t,className:d_().settingLabel,style:{display:"block"},children:e("chat.attachmentUploadLimit")}),(0,r.jsx)("div",{className:d_().settingDescription,children:e("chat.attachmentUploadLimitHelp")})]}),(0,r.jsx)("div",{className:d_().settingControl,children:(0,r.jsx)("input",{id:t,className:d_().numberInput,type:"number",inputMode:"numeric",min:1,step:1,value:l,disabled:u,onChange:e=>o(e.target.value),onBlur:()=>{let t=l.trim();if(t===String(a.uploadLimitMb))return;let n=Number(t);if(!/^\d+$/.test(t)||!Number.isSafeInteger(n)||n<1){m(!1),c(e("chat.attachmentUploadLimitInvalid"));return}f({uploadLimitMb:n})},onKeyDown:e=>{"Enter"===e.key&&e.currentTarget.blur()}})})]}),(0,r.jsxs)("div",{className:d_().settingRow,children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{id:n,className:d_().settingLabel,children:e("chat.attachmentAutoCleanup")}),(0,r.jsx)("div",{className:d_().settingDescription,children:e("chat.attachmentAutoCleanupHelp",{days:a.orphanGraceDays})})]}),(0,r.jsx)("div",{className:d_().settingControl,children:(0,r.jsx)("button",{type:"button",className:d_().switch,"data-on":a.autoCleanupEnabled,"aria-pressed":a.autoCleanupEnabled,"aria-labelledby":n,disabled:u,onClick:()=>void f({autoCleanupEnabled:!a.autoCleanupEnabled})})})]}),d&&(0,r.jsx)("div",{className:d_().error,role:"alert",style:{overflowWrap:"anywhere"},children:d}),h&&!d&&(0,r.jsx)("div",{className:d_().saveState,role:"status",children:e("chat.attachmentSettingsSaved")})]})})]}):(0,r.jsx)("div",{className:d_().empty,children:d?`${e("chat.attachmentSettingsLoadFailed")}: ${d}`:"…"})}function dB({cwd:e}){let{t}=(0,R.s)(),[n,a]=(0,i.useState)(null),[s,l]=(0,i.useState)(null),[o,d]=(0,i.useState)(null),[c,u]=(0,i.useState)(null),[p,h]=(0,i.useState)({}),[m,f]=(0,i.useState)(null),[g,x]=(0,i.useState)(null),v=(0,i.useRef)(new Map);(0,i.useEffect)(()=>{g&&c!==g&&(v.current.get(g)?.querySelector("button:not(:disabled)")?.focus(),x(null))},[c,n,g]);let b=(0,i.useRef)(0),y=(0,i.useRef)(null),w=(0,i.useRef)(null),k=(0,i.useRef)(!1),j=(0,i.useCallback)(async()=>{if(k.current||"visible"!==document.visibilityState)return;let n=++b.current;y.current?.abort();let r=new AbortController;y.current=r;try{let i=e?`?include=${encodeURIComponent(e)}`:"",s=await fetch(`/api/project-trust${i}`,{cache:"no-store",signal:r.signal}),o=await s.json();if(n!==b.current||r.signal.aborted)return;if(!s.ok||!o.projects)throw Error(o.error??`HTTP ${s.status}`);let d=o.projects.find(e=>null===e.pending&&!e.error&&w.current?.some(t=>t.cwd===e.cwd&&("grant"===t.pending?e.trusted:"revoke"===t.pending&&!e.trusted)));w.current=o.projects,a(o.projects),l(null),d&&f({cwd:d.cwd,text:t("trust.doneApplied")})}catch(e){if(n!==b.current||r.signal.aborted)return;l(e instanceof Error?e.message:String(e))}finally{y.current===r&&(y.current=null)}},[e,t]);(0,i.useEffect)(()=>(j(),()=>{y.current?.abort()}),[j]);let S=n?.some(e=>null!==e.pending)??!1;(0,i.useEffect)(()=>{let e;if(!S||null!==c||null!==o)return;let t=()=>{window.clearTimeout(e),e="visible"===document.visibilityState?window.setTimeout(()=>void j(),2500):void 0},n=()=>{"visible"===document.visibilityState?j():(t(),++b.current,y.current?.abort())};return t(),document.addEventListener("visibilitychange",n),()=>{window.clearTimeout(e),document.removeEventListener("visibilitychange",n)}},[c,o,n,S,j]);let C=(0,i.useCallback)(async(e,n)=>{if(!k.current){k.current=!0,++b.current,y.current?.abort(),u(e),d(null),x(e),f(null),h(t=>{let n={...t};return delete n[e],n});try{let r=await fetch("/api/project-trust",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e,action:n})}),i=await r.json();if(!r.ok)throw Error(i.error??`HTTP ${r.status}`);let s=w.current?.map(t=>t.cwd===e?{...i,cwd:e}:t)??null;w.current=s,a(s),"cancel"===n?f({cwd:e,text:t("trust.doneCancelled")}):i.error||null!==i.pending||f({cwd:e,text:t("trust.doneApplied")})}catch(t){h(n=>({...n,[e]:t instanceof Error?t.message:String(t)}))}finally{k.current=!1,u(null)}}},[t]);if(!n)return(0,r.jsxs)("div",{className:d_().empty,children:[s?t("trust.loadFailed",{error:s}):"…",s&&(0,r.jsx)("button",{type:"button",className:d_().linkButton,onClick:()=>void j(),children:t("trust.refresh")})]});let N=null!==c;return(0,r.jsxs)("div",{className:d_().scrollContent,children:[(0,r.jsxs)("header",{className:d_().contentHeader,children:[(0,r.jsx)("h2",{className:d_().contentTitle,children:t("trust.settingsNav")}),(0,r.jsx)("p",{className:d_().contentDescription,children:t("trust.settingsDescription")}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:10,marginTop:12},children:[(0,r.jsx)("button",{type:"button",className:d_().linkButton,style:{background:"transparent",cursor:"pointer"},disabled:N,onClick:()=>void j(),children:t("trust.refresh")}),s&&(0,r.jsx)("div",{className:d_().error,role:"alert",children:t("trust.loadFailed",{error:s})})]})]}),(0,r.jsx)("div",{className:d_().settingsBody,children:(0,r.jsxs)("section",{className:d_().group,children:[0===n.length&&(0,r.jsx)("div",{className:d_().settingDescription,children:t("trust.settingsEmpty")}),n.map(e=>{var n;let i=c===e.cwd,a=o?.cwd===e.cwd?o:null,s=e.requiresTrust?e.trusted?t("trust.stateTrusted"):t("trust.stateRestricted"):t("trust.stateNotRequired"),l=p[e.cwd]??(e.error?t("trust.applyFailed",{error:e.error}):null);return(0,r.jsxs)("div",{className:d_().settingRow,children:[(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsxs)("div",{className:d_().settingLabel,style:{display:"flex",alignItems:"center",gap:7},children:[(0,r.jsx)("span",{className:d_().statusDot,"data-off":!e.trusted||!e.requiresTrust,"aria-hidden":"true"}),(0,r.jsx)("span",{children:(n=e.cwd).split(/[\\/]/).filter(Boolean).pop()??n}),(0,r.jsx)("span",{className:d_().settingDescription,style:{fontWeight:600},children:s})]}),(0,r.jsx)("code",{className:d_().settingDescription,style:{display:"block",overflowWrap:"anywhere"},children:e.cwd}),(0,r.jsx)("div",{className:d_().saveState,children:t("trust.runtime",{sessions:e.runtime.sessions,running:e.runtime.running,loaded:e.requiresTrust?e.runtime.projectCodeLoaded:0})}),(0,r.jsxs)("div",{"aria-live":"polite",children:["grant"===e.pending&&(0,r.jsx)("div",{className:d_().settingDescription,children:t("trust.pendingGrant")}),"revoke"===e.pending&&(0,r.jsx)("div",{className:d_().settingDescription,children:t("trust.pendingRevoke",{count:e.runtime.projectCodeLoaded})}),a&&(0,r.jsx)("div",{className:d_().settingDescription,style:{color:"var(--text)"},children:"revoke"===a.action?t("trust.confirmRevoke"):a.again?t("trust.confirmTrustAgain"):t("trust.confirmGrant")}),m?.cwd===e.cwd&&(0,r.jsx)("div",{className:d_().saveState,children:m.text})]}),l&&(0,r.jsx)("div",{className:d_().error,role:"alert",children:l})]}),(0,r.jsx)("div",{ref:t=>{t?v.current.set(e.cwd,t):v.current.delete(e.cwd)},className:d_().settingControl,style:{flexWrap:"wrap",gap:8,alignItems:"flex-start"},children:a?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("button",{type:"button",className:d_().linkButton,style:{background:"transparent",cursor:"pointer"},autoFocus:!0,onClick:()=>{d(null),x(e.cwd)},children:t("trust.cancel")}),(0,r.jsx)("button",{type:"button",className:"revoke"===a.action?d_().dangerButton:d_().primaryButton,disabled:N,onClick:()=>void C(e.cwd,a.action),children:"revoke"===a.action?t("trust.revoke"):t("trust.confirm")})]}):i?(0,r.jsx)("button",{type:"button",className:d_().primaryButton,disabled:!0,children:t("trust.working")}):(0,r.jsxs)(r.Fragment,{children:["grant"===e.pending&&(0,r.jsx)("button",{type:"button",className:d_().linkButton,style:{background:"transparent",cursor:"pointer"},disabled:N,onClick:()=>void C(e.cwd,"cancel"),children:t("trust.cancelSchedule")}),e.requiresTrust&&!e.trusted&&"grant"!==e.pending&&(0,r.jsx)("button",{type:"button",className:d_().primaryButton,disabled:N,onClick:()=>d({cwd:e.cwd,action:"grant",again:"revoke"===e.pending}),children:"revoke"===e.pending?t("trust.trustAgain"):t("trust.trustProject")}),e.trusted&&(0,r.jsx)("button",{type:"button",className:d_().dangerButton,disabled:N,onClick:()=>d({cwd:e.cwd,action:"revoke",again:!1}),children:t("trust.revoke")})]})})]},e.cwd)})]})})]})}let dU=JSON.parse('{"tabs":{"appearance":"외관","model":"모델","interaction":"상호작용","context":"컨텍스트","memory":"메모리","files":"파일","shell":"Shell","tools":"도구","tasks":"작업","providers":"제공자"},"groups":{"Theme":"테마","Status Line":"상태 표시줄","Display":"표시","Images":"이미지","Thinking":"사고","Sampling":"샘플링","Prompt":"프롬프트","Retry & Fallback":"재시도 및 폴백","Advisor":"어드바이저","Prewalk":"Prewalk","Vision":"비전","Input":"입력","Approvals":"승인","Notifications":"알림","Speech":"음성","Collab":"협업","Magic Keywords":"매직 키워드","Startup & Updates":"시작 및 업데이트","Power (macOS)":"전원 (macOS)","Agent":"에이전트","Git":"Git","General":"일반","Compaction":"압축","Rules (TTSR)":"규칙 (TTSR)","Experimental":"실험적 기능","Auto-Learn":"자동 학습","Mnemopi":"Mnemopi","Hindsight":"Hindsight","Editing":"편집","Reading":"읽기","Read Summaries":"읽기 요약","LSP":"LSP","Bash":"Bash","Eval & Runtimes":"평가 및 런타임","Available Tools":"사용 가능한 도구","Todos":"할 일","Grep & Browser":"Grep 및 브라우저","Computer":"컴퓨터","GitHub":"GitHub","Output Limits":"출력 제한","Execution":"실행","Discovery & MCP":"탐색 및 MCP","Developer":"개발자","Modes":"모드","Subagents":"서브에이전트","Isolation":"격리","Commands & Skills":"명령 및 스킬","Services":"서비스","Fireworks":"Fireworks","Tiny Model":"Tiny Model","Protocol":"프로토콜","Timeouts":"타임아웃","Privacy":"개인정보"},"shell":{"Loading omp settings…":"omp 설정을 불러오는 중…","Settings unavailable":"설정을 사용할 수 없음","Matching canonical /settings entries across every category.":"모든 카테고리에서 표준 /settings 항목을 일치시킨다.","Canonical omp /settings values. Changes are saved immediately to the shared agent configuration.":"표준 omp /settings 값이다. 변경 사항은 공유 에이전트 설정에 즉시 저장된다.","Saved. Reload the active session to apply runtime settings.":"저장됨. 런타임 설정을 적용하려면 활성 세션을 다시 불러온다.","Reloading…":"다시 불러오는 중…","Reload session":"세션 다시 불러오기","No settings match this search.":"이 검색과 일치하는 설정이 없다.","Search /settings":"/settings 검색","Configuration":"구성","OMP settings":"OMP 설정","Close settings":"설정 닫기","Global configuration":"전역 구성","Settings":"설정","Search":"검색","Models":"모델","Themes":"테마","Skills":"스킬","Plugins":"플러그인","MCP":"MCP","Loading themes…":"테마를 불러오는 중…","Themes unavailable":"테마를 사용할 수 없음","Active on web":"웹에서 활성","Preview ":"미리보기 ","The web interface uses the same dark and light theme mappings as omp. Changes are persisted to ":"웹 인터페이스는 omp와 동일한 다크 및 라이트 테마 매핑을 사용한다. 변경 사항은 다음에 저장된다: "," and applied here immediately.":" 그리고 여기에 즉시 적용된다."," mapping":" 매핑","requires a project":"프로젝트가 필요하다"},"fields":{"theme.dark":{"label":"다크 테마","description":"터미널 배경이 어두울 때 사용하는 테마이다"},"theme.light":{"label":"라이트 테마","description":"터미널 배경이 밝을 때 사용하는 테마이다"},"symbolPreset":{"label":"심볼 프리셋","description":"아이콘과 기호에 사용하는 글리프 세트이다 (Unicode, Nerd Font, ASCII)"},"colorBlindMode":{"label":"색맹 모드","description":"diff 추가 표시에 초록색 대신 파란색을 사용한다"},"statusLine.preset":{"label":"상태 표시줄 프리셋","description":"미리 구성된 상태 표시줄 설정이다"},"statusLine.separator":{"label":"상태 표시줄 구분자","description":"세그먼트 사이 구분자의 스타일이다"},"statusLine.sessionAccent":{"label":"세션 강조색","description":"에디터 테두리와 상태 표시줄 여백에 세션 이름 색상을 사용한다"},"statusLine.transparent":{"label":"투명 상태 표시줄","description":"상태 표시줄에 테마의 `statusLineBg` 대신 터미널 기본 배경을 사용한다. Powerline 끝 캡은 주변 터미널로 이어지려면 대비되는 채움색이 필요하므로 제거된다."},"statusLine.compactThinkingLevel":{"label":"간결한 thinking 레벨","description":"thinking 레벨을 별도의 ` \xb7 <level>` 접미사 대신 모델 이름에 아이콘 하나로 표시한다."},"statusLine.showHookStatus":{"label":"hook 상태 표시","description":"상태 표시줄 아래에 hook 상태 메시지를 표시한다"},"terminal.showImages":{"label":"인라인 이미지 표시","description":"터미널에 이미지를 인라인으로 렌더링한다"},"images.autoResize":{"label":"이미지 자동 크기 조정","description":"모델 호환성을 높이기 위해 큰 이미지를 최대 2000x2000으로 축소한다"},"images.blockImages":{"label":"이미지 차단","description":"이미지가 LLM 제공자에게 전송되지 않도록 한다"},"terminal.showProgress":{"label":"네이티브 터미널 진행 표시","description":"에이전트나 컨텍스트 유지 작업이 실행되는 동안 OSC 9;4 부정형 진행 표시를 내보낸다"},"tui.textSizing":{"label":"큰 제목 (Kitty)","description":"Kitty의 OSC 66 text-sizing 프로토콜을 사용해 Markdown H1 제목을 2배 크기로 렌더링한다. Kitty 터미널에서만 적용되며 그 외에서는 무시된다. 기본값은 꺼짐이다."},"tui.renderMermaid":{"label":"Mermaid 다이어그램 렌더링","description":"Mermaid 코드 블록을 ASCII 다이어그램으로 렌더링한다"},"tui.codexResetFireworks":{"label":"Codex 리셋 불꽃놀이","description":"예정에 없던 Codex 주간 사용량 리셋과 새로 적립된 저장 리셋을 화면 상단 1/3의 불꽃놀이 오버레이로 축하하며, Escape를 누를 때까지 유지된다"},"tui.titleState":{"label":"터미널 제목 실행 상태","description":"터미널 제목의 구분자에 에이전트 실행 상태를 표시한다 — 작업 중에는 애니메이션 스피너(Windows에서는 고정된 \':\'), 사용자 차례일 때는 \'>\', 에이전트가 사용자를 기다릴 때는 \'!\'이다"},"tui.hyperlinks":{"label":"터미널 하이퍼링크","description":"터미널 자체의 클릭 열기를 위해 경로와 URL을 OSC 8 하이퍼링크로 감싼다 (auto: 지원 여부 감지, off: 사용 안 함, always: 무조건 사용)"},"tui.tight":{"label":"조밀한 레이아웃","description":"터미널 출력 좌우의 1문자 가로 여백을 제거한다"},"tui.scrollbackRebuild":{"label":"스크롤백 다시 쓰기","description":"블록의 최종 형태가 실시간 미리보기를 대체할 때 터미널 스크롤백을 지우고 다시 출력한다. 꺼짐(기본값)일 때는 오래된 미리보기 사본이 기록에 남고 최종 내용이 그 아래에 추가된다."},"display.shimmer":{"label":"셔머","description":"작업/로딩 메시지의 애니메이션 스타일이다"},"display.smoothStreaming":{"label":"부드러운 스트리밍","description":"청크가 도착하는 동안 어시스턴트 텍스트와 스트리밍되는 도구 입력을 부드럽게 표시한다"},"display.hideToolActivity":{"label":"도구 활동 숨김","description":"모델이 시작한 도구 호출과 결과를 대화 기록에서 숨긴다"},"display.showTokenUsage":{"label":"토큰 사용량 표시","description":"어시스턴트 메시지에 턴별 토큰 사용량을 표시한다"},"display.cacheMissMarker":{"label":"캐시 미스 표시","description":"요청이 프롬프트 캐시를 놓친(miss) 어시스턴트 턴 위에 구분선을 표시한다"},"display.collapseCompacted":{"label":"압축 히스토리 접기","description":"라이브 트랜스크립트에서 compaction 이전 히스토리를 요약 구분선 뒤로 접는다. 비활성화하면 각 compaction 지점에 구분선을 둔 채 전체 트랜스크립트를 인라인으로 유지한다"},"showHardwareCursor":{"label":"하드웨어 커서 표시","description":"IME 지원을 위해 터미널 커서를 표시한다"},"tui.imeSafeCursor":{"label":"IME 안전 프롬프트 레이아웃","description":"macOS IME preedit가 프롬프트 하단 테두리를 밀어내지 못하도록 테두리를 별도 행으로 옮긴다"},"task.showResolvedModelBadge":{"label":"확정 모델 배지 표시","description":"task 위젯 상태줄에 각 subagent가 실제로 사용한 모델 ID를 표시한다"},"advisor.enabled":{"label":"Advisor 활성화","description":"\'advisor\' 역할에 배정된 두 번째 모델을 함께 두어 각 턴을 수동적으로 검토하고 메모를 주입한다."},"prewalk.enabled":{"label":"Prewalk 활성화","description":"활성 모델로 시작한 뒤, plan nudge의 todo 목록이 생성된 이후 첫 edit/write 시점에 빠르고 저렴한 모델(기본값은 \'smol\' 역할)로 전환한다 — 강한 모델이 계획하고 todo를 확정하며 구현을 시작한 후 인계한다. 세션별로 --prewalk / --no-prewalk로 재정의할 수 있다."},"advisor.syncBacklog":{"label":"Advisor 동기화 백로그","description":"advisor가 이 턴 수만큼 뒤처지면 메인 에이전트를 최대 30초 동안 멈춘다. Off로 두면 따라잡기 지연을 비활성화한다."},"advisor.immuneTurns":{"label":"Advisor 면역 턴","description":"advisor의 concern 또는 blocker가 한 번 인터럽트한 뒤에는, 이 primary 턴 수 동안 이후 concern/blocker를 인터럽트 없이 전달한다."},"modelRoleStorage":{"label":"모델 역할 저장소","description":"모델 선택기의 역할 배정이 저장되는 위치이다"},"images.describeForTextModels":{"label":"텍스트 모델용 이미지 설명","description":"vision을 지원하지 않는 모델에 이미지가 첨부되면, 이미지를 버리지 않고 local:// 아래에 저장한 뒤 vision 지원 모델이 만든 설명을 주입한다"},"defaultThinkingLevel":{"label":"Thinking 레벨","description":"thinking을 지원하는 모델의 추론 깊이이다"},"hideThinkingBlock":{"label":"Thinking 블록 숨김","description":"어시스턴트 응답에서 thinking 블록을 숨긴다"},"proseOnlyThinking":{"label":"산문 전용 Thinking","description":"thinking 요약에서 코드 블록을 제외하고 생략 부호로 대체한다"},"omitThinking":{"label":"Thinking 요약 생략","description":"응답에서 thinking 요약을 완전히 생략하도록 업스트림 provider에 지시한다(지원되는 경우)"},"externalThinking":{"label":"외부 Thinking","description":"사용자에게 표시되지 않는 비공개 스크래치패드이다. 지원되는 GPT, Claude, Gemini의 reasoning을 비활성화한다"},"model.loopGuard.enabled":{"label":"Loop Guard","description":"모델 reasoning과 산문에 대한 자동 스트림 루프 감지를 활성화한다"},"model.loopGuard.checkAssistantContent":{"label":"Loop Guard 산문 검사","description":"thinking 로그 외에 어시스턴트 산문 메시지에도 loop guard를 적용한다"},"model.loopGuard.toolCallReminder":{"label":"Loop Guard 도구 호출 알림","description":"Gemini reasoning 스트림이 도구를 호출하지 않고 계획 헤더를 연속으로 다수 출력하면 중단하고 도구 호출을 요구하는 알림을 주입한다(Loop Guard 필요)"},"model.toolCallLoopGuard.enabled":{"label":"도구 호출 Loop Guard","description":"여러 턴에 걸친 동일한 연속 도구 호출을 감지하고 교정용 steer를 주입한다"},"inlineToolDescriptors":{"label":"인라인 도구 디스크립터","description":"시스템 프롬프트에 전체 도구 디스크립터를 렌더링하고 provider 도구 스키마에서 최상위/중첩 description을 제거해 디스크립터 텍스트를 한 번만 전송한다. Auto는 Gemini 모델에서 이를 활성화하고 그 외에는 비활성화한다"},"includeModelInPrompt":{"label":"프롬프트에 모델 포함","description":"에이전트가 자신이 어떤 모델인지 알 수 있도록 시스템 프롬프트에 활성 모델 식별자를 노출한다"},"includeWorkspaceTree":{"label":"워크스페이스 트리 포함","description":"시스템 프롬프트에 워크스페이스 디렉터리 트리를 렌더링한다. 경고: 파일이 수정되면 세션 간 프롬프트 캐싱이 깨질 수 있다."},"personality":{"label":"성격","description":"시스템 프롬프트의 personality 블록에 렌더링되는 의사소통 스타일이다"},"temperature":{"label":"Temperature","description":"샘플링 temperature이다(0 = 결정적, 1 = 창의적, -1 = provider 기본값)"},"topP":{"label":"Top P","description":"Nucleus 샘플링 컷오프이다(0-1, -1 = provider 기본값)"},"topK":{"label":"Top K","description":"상위 K개 토큰에서 샘플링한다(-1 = provider 기본값)"},"minP":{"label":"Min P","description":"최소 확률 임계값 (0-1, -1 = provider 기본값)"},"presencePenalty":{"label":"Presence Penalty","description":"이미 등장한 토큰을 도입하는 데 대한 페널티 (-1 = provider 기본값)"},"repetitionPenalty":{"label":"Repetition Penalty","description":"반복된 토큰에 대한 페널티 (-1 = provider 기본값)"},"textVerbosity":{"label":"텍스트 상세도","description":"OpenAI Responses 및 Codex 응답의 상세도 (low, medium, high)"},"tier.openai":{"label":"서비스 티어 — OpenAI","description":"OpenAI / OpenAI-Codex 요청 및 OpenRouter를 경유하는 OpenAI 계열 모델의 처리 티어 (none = 생략). `service_tier`로 전송한다."},"tier.anthropic":{"label":"서비스 티어 — Anthropic","description":"Claude 요청의 처리 티어. `priority`는 지원되는 직접 Anthropic 모델에서 fast 모드(`speed: \\"fast\\"`)를 활성화하며, Bedrock/Vertex Claude 및 OpenRouter 경유에서는 무시된다."},"tier.google":{"label":"서비스 티어 — Google","description":"Gemini(Google AI Studio + Vertex) 요청 및 OpenRouter를 경유하는 Google 계열 모델의 처리 티어 (none = 생략). 최상위 `serviceTier` 필드로 전송한다."},"tier.subagent":{"label":"서비스 티어 — 서브에이전트","description":"생성된 task/eval 서브에이전트의 서비스 티어. Inherit = 메인 에이전트의 실시간 계열별 티어를 따른다(/fast를 추적한다). 값을 지정하면 서브에이전트 모델이 속한 계열에 그 값을 적용한다."},"tier.advisor":{"label":"서비스 티어 — Advisor","description":"advisor 모델의 서비스 티어. None = 표준 처리, Inherit = 메인 에이전트의 실시간 계열별 티어를 따른다. 값을 지정하면 advisor 모델의 계열에 그 값을 적용한다."},"retry.maxRetries":{"label":"재시도 횟수","description":"API 오류 시 최대 재시도 횟수"},"retry.modelFallback":{"label":"재시도 모델 폴백","description":"재시도 복구 시 설정된 폴백 모델로 전환하도록 허용한다"},"retry.usageAwareFallback":{"label":"사용량 인식 폴백","description":"신뢰할 수 있는 coding-plan 할당량 보고를 활용해, 하드 사용량 한도에 도달하기 전에 동일 provider 계정을 먼저 사용하고 그다음 설정된 폴백 모델을 사용한다. 일반 설정 API 키는 제외한다."},"retry.usageReservePct":{"label":"예비 마진","description":"남은 비율이 이 값 미만이면 coding-plan 모델이 한도에 근접한 것으로 간주한다. 사용량을 알 수 없거나 매핑되지 않은 경우 주 모델을 유지한다."},"retry.usageReservePolicy":{"label":"예비 정책","description":"동일 provider의 모든 coding-plan 계정이 예비 마진 안에 들어왔을 때의 동작이다."},"retry.fallbackChains":{"label":"재시도 폴백 체인","description":"모델 역할, 모델 선택자(\\"provider/model-id\\"), 또는 provider 와일드카드(\\"provider/*\\")를 순서가 있는 폴백 선택자에 매핑하는 JSON 객체이다. 예: {\\"default\\":[\\"openai/gpt-4o-mini\\"],\\"google-antigravity/*\\":[\\"google/*\\",\\"google-vertex/*\\"]}. 모델 지향 키는 역할과 무관하게 해당 모델/provider가 활성일 때마다 적용되며, \\"provider/*\\" 항목은 실패한 모델의 id를 유지한 채 provider만 교체한다. id 접두사 와일드카드(\\"openrouter/google/*\\")는 실패한 모델의 순수 id에 접두사를 다시 붙이고(google-antigravity/gemini-x -> openrouter/google/gemini-x), 키로 사용될 때는 해당 접두사 아래의 그 provider id에만 매칭된다."},"retry.fallbackRevertPolicy":{"label":"폴백 복귀 정책","description":"폴백 이후 주 모델로 되돌아가는 시점이다"},"providers.anthropic.serverSideFallback":{"label":"Anthropic 서버 사이드 폴백 (Fable 5)","description":"Claude Fable 5 / Mythos 5 요청이 Anthropic의 안전 분류기에 의해 차단되면 서버 사이드에서 Claude Opus 4.8로 재시도한다(Anthropic `server-side-fallback-2026-06-01` 베타). 옵트인 방식이며, 끄면 모든 요청에 대해 폴백 이전 동작이 유지된다."},"providers.autoThinkingModel":{"label":"Auto Thinking 모델","description":"`auto` thinking 레벨의 난이도 분류기이다. 기본값은 온라인(/models의 TINY 역할, 없으면 smol)이며, 로컬 온디바이스 모델도 사용할 수 있다"},"providers.autoThinkingMaxEffort":{"label":"Auto Thinking 상한","description":"`auto` 분류기가 도달할 수 있는 최고 effort이다. `xhigh`는 분류기를 최상위보다 한 단계 아래로 유지해 명시적인 `ultrathink`만 `max`에 도달하게 하며, `max`는 분류기가 예외적이라고 판단한 턴이 이를 노출하는 모델에서 최상위 티어로 과금되도록 허용한다."},"autoResume":{"label":"자동 재개","description":"현재 디렉터리의 가장 최근 세션을 자동으로 재개한다"},"power.sleepPrevention":{"label":"절전 방지","description":"활성 세션 동안 macOS 절전을 방지한다. 각 레벨은 누적되며, 하위 레벨의 플래그를 모두 포함한다."},"git.enabled":{"label":"Git 통합 활성화","description":"TUI에 git 브랜치, 상태, PR 정보를 표시하고 저장소 메타데이터를 감시한다."},"steeringMode":{"label":"Steering 모드","description":"에이전트가 작업하는 동안 대기 중인 메시지를 처리하는 방식이다"},"followUpMode":{"label":"후속 메시지 모드","description":"턴이 완료된 후 후속 메시지를 처리하는 방식이다"},"interruptMode":{"label":"인터럽트 모드","description":"steering 메시지가 도구 실행을 중단하는 시점이다"},"loop.mode":{"label":"Loop 모드","description":"/loop 반복 사이에 프롬프트를 다시 제출하기 전에 일어나는 동작이다"},"doubleEscapeAction":{"label":"이중 Escape 동작","description":"편집기가 비어 있는 상태에서 Escape를 두 번 누를 때의 동작이다"},"treeFilterMode":{"label":"세션 트리 필터","description":"세션 트리를 열 때의 기본 필터 모드이다"},"autocompleteMaxVisible":{"label":"자동완성 항목 수","description":"자동완성 드롭다운에 표시되는 최대 항목 수이다 (3-20)"},"emojiAutocomplete":{"label":"이모지 자동완성","description":"`:name:` 숏코드로 이모지를 제안하고 `:D` 또는 `:-)` 같은 텍스트 이모티콘을 확장한다"},"paste.largeMenuThreshold":{"label":"대용량 붙여넣기 메뉴","description":"붙여넣기가 이 줄 수에 도달하면 코드 블록으로 감싸기, XML 태그로 감싸기, 파일로 저장하기 메뉴를 제공한다. 0은 메뉴를 비활성화한다(대용량 붙여넣기는 여전히 [Paste] 마커로 축약된다)."},"startup.quiet":{"label":"조용한 시작","description":"환영 화면과 시작 상태 메시지를 건너뛴다"},"startup.showSplash":{"label":"시작 스플래시 표시","description":"설정을 다시 실행하지 않고 일반 대화형 시작 시 전체 애니메이션 설정 스플래시를 표시한다. 조용한 시작은 여전히 이를 억제한다."},"startup.setupWizard":{"label":"설정 위저드","description":"새로 추가된 온보딩 단계를 설정 버전마다 한 번 표시한다"},"startup.checkUpdate":{"label":"업데이트 확인","description":"시작 시 omp 업데이트를 확인한다"},"marketplace.autoUpdate":{"label":"마켓플레이스 자동 업데이트","description":"시작 시 플러그인 업데이트를 확인한다"},"startup.changelogMode":{"label":"시작 변경 내역","description":"업데이트 노트를 요약으로 시작할지, 전체 상세로 시작할지, 숨긴 상태로 둘지 선택한다"},"magicKeywords.enabled":{"label":"매직 키워드","description":"단독으로 쓰인 ultrathink, orchestrate, workflowz 키워드에 대한 숨겨진 공지를 활성화한다"},"magicKeywords.ultrathink":{"label":"Ultrathink 키워드","description":"단독으로 쓰인 ultrathink가 최대 자동 사고를 요청하고 숨겨진 공지를 덧붙이도록 한다"},"magicKeywords.orchestrate":{"label":"Orchestrate 키워드","description":"단독으로 쓰인 orchestrate가 숨겨진 멀티 에이전트 오케스트레이션 공지를 덧붙이도록 한다"},"magicKeywords.workflow":{"label":"Workflow 키워드","description":"단독으로 쓰인 workflowz가 숨겨진 eval 워크플로 공지를 덧붙이도록 한다"},"completion.notify":{"label":"완료 알림","description":"에이전트가 턴을 마쳤을 때 알린다"},"error.notify":{"label":"오류 알림","description":"에이전트가 오류로 중단되었을 때 알린다"},"ask.timeout":{"label":"Ask 타임아웃","description":"이 초가 지나면 권장 ask 옵션을 자동 선택한다 (0은 비활성화)"},"ask.notify":{"label":"Ask 알림","description":"ask 도구가 입력을 기다릴 때 알린다"},"recap.enabled":{"label":"유휴 요약","description":"터미널이 유휴 상태가 된 후 현재 상황에 대한 간단한 LLM 요약을 생성한다"},"recap.idleSeconds":{"label":"유휴 요약 지연","description":"요약을 표시하기 전 유휴 상태로 대기하는 초이다"},"collab.relayUrl":{"label":"Relay URL","description":"/collab에서 사용하는 relay이다 (wss://host[:port])"},"collab.webUrl":{"label":"웹 UI URL","description":"/collab 링크에 사용되는 브라우저 UI이다. 비어 있으면 collab.relayUrl에서 파생되며, 명시적인 http://는 localhost에서만 사용된다"},"collab.displayName":{"label":"표시 이름","description":"다른 collab 참가자에게 표시되는 이름이다 (기본값: OS 사용자 이름)"},"share.serverUrl":{"label":"Share 서버","description":"/share에서 사용하는 공유 뷰어/업로드 기준 주소이다 (암호화된 blob 업로드 + 뷰어, 링크는 <base>/<id>#<key> 형식이다)"},"share.store":{"label":"Share 저장소","description":"/share가 암호화된 세션 blob을 업로드하는 위치이다"},"share.redactSecrets":{"label":"공유 시 비밀정보 삭제","description":"업로드 전에 /share 스냅샷에 대해 secret obfuscator를 실행한다(secrets.* 설정을 사용한다)"},"stt.enabled":{"label":"음성 인식","description":"마이크를 통한 speech-to-text 입력을 활성화한다"},"stt.modelName":{"label":"음성 모델","description":"로컬 온디바이스 음성 모델이다. Parakeet TDT v3(sherpa-onnx)가 SoTA 기본값이며, Whisper base/small/large-v3-turbo 등급(transformers.js)은 크기를 다국어 지원과 맞바꾼다. 첫 사용 시 다운로드된다."},"stt.submitTrigger":{"label":"음성 입력 전송 트리거","description":"음성 받아쓰기가 자동으로 전송되는 시점을 선택한다: Never, Release(2단어 이상), 완전한 문장으로 Release, 또는 When I Say Submit."},"tools.approval":{"label":"도구 승인 정책","description":"도구별 승인 정책이다. \'allow\'는 자동 승인, \'prompt\'는 확인 요구, \'deny\'는 차단으로 설정한다. 재정의는 모든 승인 모드에서 적용된다."},"tools.approvalMode":{"label":"도구 승인","description":"도구 호출의 기본 승인 동작이다. \'Always ask\'는 읽기 전용 도구만 자동 승인한다. \'Write\'는 읽기 및 workspace-write 도구를 자동 승인한다. \'Yolo\'는 모든 등급을 자동 승인하지만, 사용자 정책에 따라 확인이나 차단이 발생할 수 있다."},"features.unexpectedStopDetection":{"label":"예상치 못한 중단","description":"어시스턴트가 예상치 못하게 멈추면 자동으로 복구한다. \'기계적\'(기본값)은 표시할 답변 없이 끝난 경우를 재시도하고 도구 호출이 있었던 중단은 제외한다. \'스마트\'는 기계적 감지에 더해 작은 모델로 텍스트만 남긴 중단도 판별하며, \'사용 안 함\'은 감지를 끈다."},"contextPromotion.enabled":{"label":"컨텍스트 자동 승격","description":"컨텍스트 초과 시 compaction 대신 더 큰 컨텍스트 모델로 승격한다"},"compaction.enabled":{"label":"자동 Compact","description":"컨텍스트가 너무 커지면 자동으로 compact한다"},"compaction.midTurnEnabled":{"label":"턴 중간 Compaction","description":"다음 provider 요청 전에 안전한 턴 중간 tool-loop 경계에서 임계값을 확인한다"},"compaction.strategy":{"label":"Compaction 전략","description":"제자리 context-full 유지, auto-handoff, surgical shake(무거운 콘텐츠 제거), snapcompact(히스토리를 밀집 이미지로 보관) 중에서 선택하거나 자동 유지를 비활성화(off)한다"},"compaction.thresholdPercent":{"label":"Compaction 임계값","description":"컨텍스트 유지의 퍼센트 임계값이다. Default로 설정하면 기존 reserve 기반 동작을 사용한다"},"compaction.thresholdTokens":{"label":"Compaction 토큰 한도","description":"컨텍스트 유지의 고정 토큰 한도이다. 설정하면 퍼센트 값을 재정의한다"},"compaction.handoffSaveToDisk":{"label":"Handoff 문서 저장","description":"auto-handoff 흐름에서 생성된 handoff 문서를 markdown 파일로 저장한다"},"compaction.remoteEnabled":{"label":"원격 Compaction","description":"가능한 경우 로컬 요약 대신 원격 compaction 엔드포인트를 사용한다"},"compaction.remoteStreamingV2Enabled":{"label":"원격 Compaction V2","description":"호환되는 원격 compaction 모델에 대해 Responses 스트리밍 compaction을 사용한다"},"compaction.idleEnabled":{"label":"유휴 Compaction","description":"토큰 수가 임계값을 넘으면 유휴 상태에서 컨텍스트를 compact한다"},"compaction.idleThresholdTokens":{"label":"유휴 Compaction 임계값","description":"유휴 compaction이 트리거되는 토큰 수 기준이다"},"compaction.idleTimeoutSeconds":{"label":"유휴 Compaction 지연","description":"compact하기 전 유휴 상태로 대기하는 초이다"},"compaction.supersedeReads":{"label":"오래된 읽기 대체","description":"같은 파일을 다시 읽으면 이전 읽기 결과를 정리한다(캐시 인식, 매 턴 실행)"},"compaction.dropUseless":{"label":"무의미한 결과 제거","description":"컨텍스트상 무용하다고 표시된 도구 결과(일치 없음, 시간 초과된 대기)를 소비된 후 정리한다(캐시 인식)"},"snapcompact.systemPrompt":{"label":"Snapcompact 시스템 프롬프트","description":"실험적 기능이다: 선택한 시스템 프롬프트 텍스트를 밀집 PNG 이미지로 렌더링해 첫 사용자 메시지에 첨부한다(비전 모델 전용). 토큰을 절약하지만 이미지화된 텍스트의 prompt caching을 잃는다."},"snapcompact.toolResults":{"label":"Snapcompact 도구 결과","description":"실험적 기능이다: 큰 과거 도구 결과를 텍스트 대신 밀집 PNG 이미지로 렌더링한다(비전 모델 전용). 누적된 읽기/검색 출력의 토큰을 절약한다."},"tools.format":{"label":"도구 호출 모드","description":"도구가 모델에 노출되는 방식을 제어한다. Auto는 provider-native 도구 호출을 사용하지만, 선택된 모델이 이를 지원하지 않는다고 표시된 경우 GLM owned dialect로 대체한다. Native는 provider-native 도구를 강제하고, 나머지 값은 지정된 owned dialect를 강제한다. 세션 시작 시 적용된다."},"snapcompact.shape":{"label":"Snapcompact 형태","description":"snapcompact가 텍스트를 출력하는 프레임 형태이다(compaction 보관 및 인라인 이미지화). Auto는 현재 모델에 맞게 조정된 형태를 선택한다."},"branchSummary.enabled":{"label":"브랜치 요약","description":"브랜치를 떠날 때 요약을 요청한다"},"ttsr.enabled":{"label":"TTSR","description":"출력이 규칙 패턴과 일치하면 스트리밍 도중에 에이전트를 중단한다(Time-Traveling Stream Rules)"},"ttsr.contextMode":{"label":"TTSR 컨텍스트 모드","description":"TTSR이 발동할 때 부분 출력을 어떻게 처리할지 정한다"},"ttsr.interruptMode":{"label":"TTSR 인터럽트 모드","description":"스트리밍 도중에 중단할지, 완료 후 경고를 주입할지 정한다"},"ttsr.repeatMode":{"label":"TTSR 반복 모드","description":"규칙이 반복되는 방식을 정한다: 세션당 한 번 또는 메시지 간격 이후"},"ttsr.repeatGap":{"label":"TTSR 반복 간격","description":"규칙이 다시 발동할 수 있기까지의 메시지 수이다"},"ttsr.builtinRules":{"label":"기본 제공 규칙","description":"에이전트에 기본 포함된 규칙을 로드한다(ttsr.disabledRules로 개별 해제 가능)"},"memory.backend":{"label":"메모리 백엔드","description":"끄기, 로컬 요약 파이프라인, Mnemopi SQLite, 또는 Hindsight 원격 메모리 중에서 선택한다"},"autolearn.enabled":{"label":"자동 학습 (실험적)","description":"에이전트가 멈춘 뒤 교훈을 메모리에 기록하고 격리된 관리형 skill을 생성/보강하도록 유도한다"},"autolearn.autoContinue":{"label":"중지 시 캡처 자동 실행","description":"켜면 중지 시 비공개 캡처 턴을 한 번 자동 실행한다(추가 토큰을 사용한다). 끄면 상시 자동 학습 안내만 남는다."},"mnemopi.dbPath":{"label":"Mnemopi DB 경로","description":"선택적 SQLite DB 경로이다. 기본값은 에이전트 memories 디렉터리이다."},"mnemopi.bank":{"label":"Mnemopi 뱅크","description":"선택적 공유 뱅크 기본 이름이다. per-project 모드는 이를 기반으로 프로젝트 로컬 뱅크를 파생한다."},"mnemopi.scoping":{"label":"Mnemopi 스코핑","description":"global = 공유 뱅크 하나, per-project = cwd별 격리 뱅크, per-project-tagged = 프로젝트 로컬 쓰기에 global recall 가시성을 더한 방식이다"},"mnemopi.embeddingVariant":{"label":"임베딩 variant","description":"로컬 임베딩 모델 계열이다. en = 더 강력한 영어 모델, multilingual = 교차 언어 모델이다. 이를 변경하면 다음 시작 시 기존 메모리 임베딩을 다시 생성한다."},"mnemopi.autoRecall":{"label":"Mnemopi 자동 recall","description":"각 세션의 첫 턴에 로컬 메모리를 recall한다"},"mnemopi.autoRetain":{"label":"Mnemopi 자동 retain","description":"완료된 대화 턴을 로컬 Mnemopi 메모리에 retain한다"},"mnemopi.polyphonicRecall":{"label":"Mnemopi 폴리포닉 recall","description":"reciprocal rank fusion으로 융합한 4-voice recall(vector, graph, fact, temporal)을 활성화한다"},"mnemopi.enhancedRecall":{"label":"Mnemopi 향상된 recall","description":"반복되거나 유사한 recall 쿼리를 위한 계층형 쿼리 결과 캐시를 활성화한다"},"mnemopi.proactiveLinking":{"label":"Mnemopi 선제적 링킹","description":"새 메모리를 저장하는 즉시 episodic 그래프에 수집해 관련 엔터티 및 메모리와 연결한다"},"mnemopi.noEmbeddings":{"label":"Mnemopi 임베딩 비활성화","description":"vector 임베딩 대신 결정적인 FTS 전용 recall을 강제한다"},"mnemopi.embeddingModel":{"label":"Mnemopi 임베딩 모델","description":"고급: variant를 재정의하는 명시적 임베딩 모델 id이다. 비워 두면 mnemopi.embeddingVariant를 사용한다."},"mnemopi.embeddingApiUrl":{"label":"Mnemopi 임베딩 API URL","description":"Mnemopi에 전달하는 선택적 OpenAI 호환 임베딩 엔드포인트이다"},"mnemopi.embeddingApiKey":{"label":"Mnemopi 임베딩 API 키","description":"Mnemopi에 전달하는 선택적 임베딩 API 키이다"},"mnemopi.llmMode":{"label":"Mnemopi LLM 모드","description":"LLM 미사용, 온라인 tiny 모델(/models의 TINY 역할, 없으면 @smol), 또는 원격 OpenAI 호환 엔드포인트를 사용한다"},"mnemopi.llmBaseUrl":{"label":"Mnemopi LLM Base URL","description":"Mnemopi 원격 모드를 위한 선택적 OpenAI 호환 LLM 엔드포인트이다"},"mnemopi.llmApiKey":{"label":"Mnemopi LLM API 키","description":"Mnemopi 원격 모드를 위한 선택적 LLM API 키이다"},"mnemopi.llmModel":{"label":"Mnemopi LLM 모델","description":"Mnemopi 원격 모드를 위한 선택적 LLM 모델 이름이다"},"hindsight.apiUrl":{"label":"Hindsight API URL","description":"Hindsight 서버 URL(Cloud 또는 self-hosted)이다"},"hindsight.apiToken":{"label":"Hindsight API 토큰","description":"인증이 필요한 Hindsight 서버용 Bearer 토큰이다"},"hindsight.bankId":{"label":"Hindsight Bank ID","description":"메모리 뱅크 식별자다(기본값: 프로젝트 이름)"},"hindsight.scoping":{"label":"Hindsight 범위","description":"global = 하나의 공유 뱅크, per-project = cwd별로 격리된 뱅크, per-project-tagged = 프로젝트 태그가 붙은 공유 뱅크로 recall 시 global 메모리와 프로젝트 메모리가 병합된다"},"hindsight.autoRecall":{"label":"Hindsight 자동 recall","description":"각 세션의 첫 턴에 메모리를 recall한다"},"hindsight.autoRetain":{"label":"Hindsight 자동 retain","description":"N턴마다 그리고 세션 경계에서 대화 기록을 retain한다"},"hindsight.retainMode":{"label":"Hindsight retain 모드","description":"full-session = 세션당 문서 하나를 upsert하고, last-turn = 청크 단위로 저장한다"},"hindsight.mentalModelsEnabled":{"label":"Hindsight 멘탈 모델","description":"부팅 시 정리된 reflect 요약(멘탈 모델)을 developer instructions로 읽어들인다. 뱅크에 있는 기존 모델을 로드하며 쓰기는 하지 않는다. 내장 seed 세트를 자동 생성하려면 hindsight.mentalModelAutoSeed와 함께 사용한다."},"hindsight.mentalModelAutoSeed":{"label":"Hindsight 멘탈 모델 자동 seed","description":"세션 시작 시 뱅크에 아직 없는 내장 멘탈 모델(project-conventions, project-decisions, user-preferences)을 생성한다."},"providers.memoryModel":{"label":"메모리 모델","description":"사실 추출 및 통합에 사용하는 Mnemopi LLM이다: 기본값은 online(/models의 TINY 역할, 없으면 smol/remote)이며, 로컬 on-device 모델도 사용할 수 있다"},"edit.mode":{"label":"편집 모드","description":"edit 도구 변형을 선택한다(replace, patch, hashline, apply_patch)"},"edit.fuzzyMatch":{"label":"퍼지 매치","description":"공백 차이에 대해 신뢰도가 높은 퍼지 매치를 허용한다"},"edit.fuzzyThreshold":{"label":"퍼지 매치 임계값","description":"퍼지 매치를 허용하는 유사도 임계값(0-1)이다"},"edit.streamingAbort":{"label":"프리뷰 실패 시 중단","description":"패치 프리뷰가 실패하면 스트리밍 edit 도구 호출을 중단한다"},"edit.blockAutoGenerated":{"label":"자동 생성 파일 차단","description":"자동 생성된 것으로 보이는 파일(protoc, sqlc, swagger 등)의 편집을 막는다"},"edit.enforceSeenLines":{"label":"확인된 줄 가드 적용","description":"이전 read/search가 전체를 표시하지 않은 줄을 기준으로 하는 편집을 거부한다"},"readLineNumbers":{"label":"줄 번호","description":"기본적으로 read 도구 출력에 줄 번호를 앞에 붙인다"},"read.defaultLimit":{"label":"기본 read 제한","description":"에이전트가 limit 없이 read를 호출할 때 반환하는 기본 줄 수다"},"read.renderMarkdown":{"label":"Markdown 프리뷰","description":"Markdown read 결과를 원본 소스가 아니라 서식이 적용된 터미널 Markdown 프리뷰로 렌더링한다"},"read.summarize.enabled":{"label":"read 요약","description":"명시적 selector 없이 read가 호출되면 구조적 코드 요약을 반환한다"},"read.summarize.prose":{"label":"산문 요약","description":"Markdown 및 일반 텍스트 read에 대해 구조적 요약을 반환한다"},"read.toolResultPreview":{"label":"인라인 read 프리뷰","description":"read 도구 결과를 요약 행이 아니라 대화 기록에 인라인으로 렌더링한다"},"lsp.enabled":{"label":"LSP","description":"코드 인텔리전스(정의, 참조, 진단, 이름 변경)를 위한 lsp 도구를 활성화한다"},"lsp.lazy":{"label":"LSP 지연 시작","description":"세션 시작 시점이 아니라 처음 사용할 때(lsp 도구 호출 또는 해당 파일 타입 편집) language server를 시작한다"},"lsp.shared":{"label":"공유 language server","description":"daemon broker를 통해 프로젝트당 하나의 language server를 omp 인스턴스 간에 공유한다(사용할 수 없으면 개별 서버로 대체된다)"},"lsp.formatOnWrite":{"label":"쓰기 시 포맷","description":"파일을 쓴 후 LSP로 코드 파일을 자동 포맷한다"},"lsp.diagnosticsOnWrite":{"label":"쓰기 시 진단","description":"코드 파일을 쓴 후 LSP 진단을 반환한다"},"lsp.diagnosticsOnEdit":{"label":"편집 시 진단","description":"코드 파일을 편집한 후 LSP 진단을 반환한다"},"lsp.diagnosticsDeduplicate":{"label":"진단 중복 제거","description":"파일에 대해 이미 표시된 편집 후 LSP 진단을 억제하고, 새롭거나 변경된 것만 표시한다"},"bash.enabled":{"label":"Bash","description":"셸 명령 실행을 위한 bash 도구를 활성화한다"},"bash.autoBackground.enabled":{"label":"Bash 자동 백그라운드","description":"오래 실행되는 bash 명령을 자동으로 백그라운드로 보내고 결과를 나중에 전달한다"},"bashInterceptor.enabled":{"label":"Bash 인터셉터","description":"전용 도구가 있는 셸 명령을 차단한다"},"bash.direnv":{"label":"direnv 자동 로드","description":"저장소의 direnv/devenv `.envrc`를 bash 세션에 자동으로 로드해 수동 `direnv exec` 없이 devenv 도구와 환경 변수를 사용할 수 있게 한다. direnv의 허용 목록을 따르며, `direnv allow`하지 않은 `.envrc`는 절대 실행되지 않는다"},"shellMinimizer.enabled":{"label":"셸 출력 축소","description":"장황한 셸 출력(git, npm, cargo 등)을 에이전트에 반환하기 전에 압축한다"},"shellMinimizer.sourceOutlineLevel":{"label":"셸 축소 소스 아웃라인","description":"소스 파일의 cat/read에 대한 소스 아웃라인 모드: default 또는 aggressive"},"eval.py":{"label":"Python Eval 백엔드","description":"eval 도구가 Python 셀을 IPython 커널로 보내도록 허용한다"},"eval.js":{"label":"JavaScript Eval 백엔드","description":"eval 도구가 JavaScript 셀을 인프로세스 런타임으로 보내도록 허용한다"},"eval.rb":{"label":"Ruby Eval 백엔드","description":"eval 도구가 Ruby 셀을 상시 유지되는 Ruby 커널로 보내도록 허용한다"},"eval.jl":{"label":"Julia Eval 백엔드","description":"eval 도구가 Julia 셀을 상시 유지되는 Julia 커널로 보내도록 허용한다"},"python.kernelMode":{"label":"Python 커널 모드","description":"eval 호출 간에 IPython 커널을 유지할지 매번 새로 시작할지 정한다"},"python.interpreter":{"label":"Python 인터프리터","description":"정확한 Python 실행 파일의 선택적 경로이다. 설정하면 자동 Python 런타임 탐색을 건너뛴다."},"ruby.interpreter":{"label":"Ruby 인터프리터","description":"정확한 Ruby 실행 파일의 선택적 경로이다. 설정하면 자동 Ruby 런타임 탐색을 건너뛴다."},"julia.interpreter":{"label":"Julia 인터프리터","description":"정확한 Julia 실행 파일의 선택적 경로이다. 설정하면 자동 Julia 런타임 탐색을 건너뛴다."},"tools.artifactSpillThreshold":{"label":"아티팩트 분리 임계값(KB)","description":"이 크기를 넘는 도구 출력은 아티팩트로 저장되고, 끝부분은 인라인으로 유지된다"},"tools.artifactTailBytes":{"label":"아티팩트 끝부분 크기(KB)","description":"출력이 아티팩트로 넘어갈 때 인라인으로 유지되는 끝부분 내용의 양이다"},"tools.artifactHeadBytes":{"label":"아티팩트 앞부분 크기(KB)","description":"출력이 아티팩트로 넘어갈 때 끝부분과 함께 인라인으로 유지되는 앞부분 내용의 양이다(중간 생략). 0이면 비활성화되어 끝부분만 유지한다."},"tools.outputMaxColumns":{"label":"출력 열 제한","description":"스트리밍 도구 출력(bash, python, js eval)과 `read`에 대한 줄당 바이트 제한이다. 이보다 긴 줄은 말줄임표로 잘리고, 다음 줄바꿈까지 남은 바이트는 버려진다. 0이면 비활성화된다."},"tools.artifactTailLines":{"label":"아티팩트 끝부분 줄 수","description":"출력이 아티팩트로 넘어갈 때 인라인으로 유지되는 끝부분 내용의 최대 줄 수이다"},"todo.enabled":{"label":"할 일 목록","description":"작업 추적을 위한 todo 도구를 활성화한다"},"todo.reminders":{"label":"할 일 알림","description":"중지하기 전에 할 일을 완료하도록 에이전트에 상기시킨다"},"todo.remindersMax":{"label":"할 일 알림 제한","description":"포기하기 전까지의 최대 할 일 알림 횟수이다"},"todo.eager":{"label":"할 일 자동 생성","description":"첫 메시지 이후 자동 할 일 목록 생성을 얼마나 강하게 유도할지 정한다"},"glob.enabled":{"label":"Glob","description":"glob 기반 파일 조회를 위한 glob 도구를 활성화한다"},"grep.enabled":{"label":"Grep","description":"정규식 내용 검색을 위한 grep 도구를 활성화한다"},"grep.contextBefore":{"label":"Grep 앞 컨텍스트","description":"각 grep 일치 항목 앞에 표시할 컨텍스트 줄 수이다"},"grep.contextAfter":{"label":"Grep 뒤 컨텍스트","description":"각 grep 일치 항목 뒤에 표시할 컨텍스트 줄 수이다"},"astGrep.enabled":{"label":"AST Grep","description":"구조적 AST 검색을 위한 ast_grep 도구를 활성화한다"},"astEdit.enabled":{"label":"AST Edit","description":"구조적 AST 재작성을 위한 ast_edit 도구를 활성화한다"},"debug.enabled":{"label":"디버그","description":"DAP 기반 디버깅을 위한 debug 도구를 활성화한다"},"launch.enabled":{"label":"Launch","description":"공유되는 장기 실행 프로젝트 프로세스를 감독하는 launch 도구를 활성화한다"},"speechgen.enabled":{"label":"음성 생성","description":"온디바이스(Kokoro) 또는 xAI Grok Voice 음성 파일 합성을 위한 tts 도구를 활성화한다"},"generate_image.enabled":{"label":"이미지 생성","description":"generate_image 도구(텍스트-이미지 생성 및 편집)를 활성화한다. tools.xdev가 켜져 있으면 xd:// 장치로 노출된다."},"inspect_image.mode":{"label":"이미지 분석","description":"이미지 이해를 비전 지원 모델에 위임하는 inspect_image 도구를 제어한다. \'auto\'는 활성 모델이 네이티브 이미지 입력을 지원하지 않을 때만 노출하고, \'on\'은 항상 노출하며, \'off\'는 노출하지 않는다."},"computer.enabled":{"label":"컴퓨터","description":"스크립트 가능한 호스트 데스크톱 제어 도구(스크린샷, 입력, 접근성)를 활성화한다"},"computer.display":{"label":"컴퓨터 디스플레이","description":"모든 디스플레이를 합성하거나 네이티브 display id를 선택한다"},"inspect_image.timeoutMs":{"label":"이미지 분석 타임아웃","description":"inspect_image 비전 모델 호출의 요청당 타임아웃이며 단위는 milliseconds이다. 응답이 멈춘 제공자는 수동 중단까지 차단되지 않고 타임아웃 오류로 빠르게 실패한다. 0으로 설정하면 타임아웃을 비활성화한다."},"checkpoint.enabled":{"label":"체크포인트/되돌리기","description":"컨텍스트 체크포인팅을 위한 checkpoint 및 rewind 도구를 활성화한다"},"fetch.enabled":{"label":"URL 읽기","description":"read 도구가 URL을 가져와 처리하도록 허용한다"},"vault.enabled":{"label":"Obsidian Vault","description":"Obsidian CLI를 통해 Obsidian vault 내용을 읽고 편집하는 vault:// 내부 URL을 활성화한다. 비활성화하면 vault:// 해석이 거부되고 시스템 프롬프트에서 vault:// 항목이 생략된다."},"github.enabled":{"label":"GitHub CLI","description":"github 도구(리포지터리, 이슈, pull request, diff, 검색, checkout, push, Actions watch 워크플로에 대한 op 기반 디스패치)를 활성화한다"},"github.cache.enabled":{"label":"GitHub 뷰 캐시","description":"렌더링된 이슈/PR 뷰 출력을 ~/.omp/cache/github-cache.db에 캐시해 반복 읽기 비용을 없앤다"},"web_search.enabled":{"label":"웹 검색","description":"실시간 웹 결과를 위한 web_search 도구를 활성화한다"},"security.enabled":{"label":"보안","description":"OMP 네이티브 보안 스캔 계획과 실행, 그리고 읽기 전용 security:// 리소스 네임스페이스를 활성화한다"},"ask.enabled":{"label":"Ask","description":"대화형 사용자 질문을 위한 ask 도구를 활성화한다"},"browser.enabled":{"label":"브라우저","description":"스크립트 기반 Chromium 자동화(puppeteer)를 위한 browser 도구를 활성화한다"},"browser.cdpUrl":{"label":"브라우저 CDP URL","description":"브라우저를 실행하는 대신 연결할 기본 HTTP CDP 디스커버리 엔드포인트이다(예: http://127.0.0.1:9222). 도구 호출에 명시된 app.cdp_url 또는 app.path가 우선한다."},"browser.relay":{"label":"브라우저 릴레이","description":"omp browser relay를 통해 사용자의 Chrome 탭을 제어한다. 확장 프로그램을 한 번 설치하면(`omp browser-relay install`) browser 도구가 필요할 때 릴레이 서버가 자동으로 시작된다. Browser CDP URL보다 우선하며, PI_BROWSER_RELAY=0 또는 PI_BROWSER_RELAY=1로 재정의한다."},"browser.relayUrl":{"label":"브라우저 릴레이 URL","description":"omp browser relay 엔드포인트이다(기본값 http://127.0.0.1:9224)."},"browser.headless":{"label":"헤드리스 브라우저","description":"브라우저를 headless 모드로 실행한다(비활성화하면 브라우저 UI를 표시한다)"},"browser.cmux":{"label":"cmux 브라우저","description":"cmux 소켓을 사용할 수 있을 때 브라우저 자동화에 cmux WKWebView 서피스를 사용한다. PI_BROWSER_CMUX=0 또는 PI_BROWSER_CMUX=1로 재정의한다."},"browser.screenshotDir":{"label":"스크린샷 디렉터리","description":"스크린샷을 저장할 디렉터리이다. 설정하지 않으면 스크린샷은 임시 파일로 저장된다. ~를 지원한다. 예: ~/Downloads, ~/Desktop, /sdcard/Download (Android)"},"tools.intentTracing":{"label":"인텐트 트레이싱","description":"각 도구 호출을 실행하기 전에 그 의도를 설명하도록 에이전트에 요청한다"},"tools.abortOnFabricatedResult":{"label":"조작된 도구 결과 시 중단","description":"in-band 도구 호출에서 모델이 턴 중간에 도구 결과를 환각하기 시작하면 즉시 중단한다. 비활성화하면 모델이 생성을 끝내도록 두고 조작된 이어쓰기를 폐기한다."},"tools.maxTimeout":{"label":"최대 도구 타임아웃","description":"에이전트가 임의의 도구에 설정할 수 있는 최대 타임아웃(초, 0 = 무제한)"},"async.enabled":{"label":"비동기 실행","description":"비동기 bash 명령과 백그라운드 작업 실행을 활성화한다"},"tools.xdev":{"label":"xd:// 도구","description":"드물게 쓰이는(탐색 가능한) 도구의 스키마를 매 요청마다 보내는 대신 read/write로 구동되는 xd:// 디바이스 URL 아래에 마운트한다. write 도구가 허용되지 않은 세션은 마운트를 건너뛰고 모든 도구를 최상위로 노출한다. 비활성화하면 활성화된 모든 도구를 최상위로 노출한다."},"tools.xdevDocs":{"label":"xd:// 프롬프트 문서","description":"시스템 프롬프트에 인라인으로 포함할 마운트된 디바이스 문서와 스키마를 선택한다. Built-ins는 핵심 도구를 인라인으로 유지하고 MCP 및 확장 도구는 on-demand로 남긴다."},"mcp.selection":{"label":"MCP 연결 선택","description":"all은 시작 시 기존 설정대로 연결한다. per-request는 JEV가 요청에 필요한 서버를 선택해 연결하며, 설치\xb7인증\xb7권한은 자동 승인하지 않는다. 변경 후 새 세션에서 적용된다."},"mcp.enableProjectConfig":{"label":"MCP 프로젝트 설정","description":"프로젝트 루트에서 .mcp.json/mcp.json을 로드한다"},"mcp.renderMarkdownResults":{"label":"MCP Markdown 결과","description":"JSON이 아닌 MCP 텍스트 결과를 트랜스크립트에서 Markdown으로 렌더링한다"},"mcp.notifications":{"label":"MCP 업데이트 주입","description":"MCP 리소스 업데이트를 에이전트 대화에 주입한다"},"tasks.todoClearDelay":{"label":"Todo 자동 정리 지연","description":"완료되거나 중단된 todo가 todo 위젯에서 제거되기까지의 지연 시간이다"},"dev.autoqa":{"label":"Auto QA","description":"자동 도구 이슈 보고(xd://report_issue)이다. 기본적으로 켜져 있으며, 첫 보고 시 동의를 요청하고 거부하면 명시적으로 다시 활성화할 때까지 보고를 비활성화한다"},"dev.autoqaPush.endpoint":{"label":"Auto QA 푸시 엔드포인트","description":"Auto QA JSON 보고를 수신하는 전체 URL이다(기본값 https://qa.omp.sh/v1/grievances)"},"plan.enabled":{"label":"Plan 모드","description":"실행 전 읽기 전용 탐색과 계획 수립을 위한 plan 모드를 활성화한다"},"plan.defaultOnStartup":{"label":"Plan 모드로 시작","description":"모든 새 세션 시작 시 자동으로 plan 모드로 진입한다"},"goal.enabled":{"label":"Goal 모드","description":"세션별 goal 모드와 숨겨진 goal 도구를 활성화한다"},"goal.statusInFooter":{"label":"푸터의 Goal 상태","description":"상태 표시줄에서 goal 표시기와 함께 토큰 예산을 표시한다"},"title.refreshOnReplan":{"label":"재계획 시 제목 갱신","description":"사용자가 제목을 설정한 경우가 아니면 todo init 재계획 이후 생성된 세션 제목을 갱신한다"},"task.isolation.mode":{"label":"격리 모드","description":"서브에이전트의 격리 백엔드이다. \\"auto\\"는 네이티브 PAL이 사용 가능한 최적 백엔드를 선택하게 한다(CoW를 지원하는 파일시스템, 그다음 overlayfs/ProjFS, 그다음 git worktree / 재귀 복사 폴백)."},"task.isolation.apply":{"label":"격리 변경 적용","description":"성공한 격리 작업의 변경을 부모 체크아웃에 자동으로 적용한다. 비활성화하면 patch 또는 branch 아티팩트를 유지한다"},"task.isolation.merge":{"label":"격리 병합 전략","description":"격리 작업의 변경을 통합하는 방식이다(patch apply 또는 branch merge)"},"task.isolation.commits":{"label":"격리 커밋 스타일","description":"중첩 저장소 변경의 커밋 메시지 스타일이다(generic 또는 AI 생성)"},"worktree.base":{"label":"Worktree 기본 디렉터리","description":"에이전트가 관리하는 worktree의 기본 디렉터리로, 작업 격리 사본, `github` PR 체크아웃, `omp worktree` 정리가 모두 여기에 위치한다. 설정하지 않으면 ~/.omp/wt를 사용한다. 절대 경로 또는 ~ 기준 경로여야 하며, 상대 경로는 무시된다. OMP_WORKTREE_DIR 환경 변수가 이 값을 재정의한다."},"task.eager":{"label":"작업 위임 선호도","description":"서브에이전트에 작업을 위임하도록 얼마나 강하게 유도할지를 정한다"},"task.batch":{"label":"작업 호출 배치","description":"task 도구를 배치 형태로 전환한다: 한 번의 호출이 { context, tasks[] }를 전달하며, 항목당 서브에이전트 하나가 실행되고, 항목별 agent(기본값은 세션 spawn-policy 에이전트)와 항목별 격리를 지정할 수 있으며, 공유 context는 모든 assignment 앞에 필수로 붙는다. async.enabled=true인 경우 각 spawn은 일반적인 idle/parked 수명 주기를 갖는 독립 백그라운드 에이전트로 실행되고, 그렇지 않으면 호출은 병합된 결과를 기다리며 블로킹된다. 비활성화하면 평면적인 단일 spawn 스키마로 되돌아간다."},"task.enableEffort":{"label":"작업별 effort","description":"task spawn에서 선택적 effort 파라미터를 노출해, 호출자가 각 서브에이전트의 thinking 레벨을 재정의할 수 있게 한다"},"task.maxConcurrency":{"label":"최대 동시 작업 수","description":"동시에 실행되는 서브에이전트의 최대 개수이다"},"task.enableLsp":{"label":"서브에이전트 LSP","description":"task 도구로 생성된 서브에이전트가 lsp 도구를 사용할 수 있게 한다. 서브에이전트 비용을 낮게 유지하기 위해 기본적으로 꺼져 있으며, LSP를 활용한 위임이 추가 토큰만큼 가치가 있을 때 활성화한다."},"task.maxRecursionDepth":{"label":"최대 작업 재귀 깊이","description":"서브에이전트가 자신의 서브에이전트를 생성할 수 있는 최대 깊이이다"},"task.maxRuntimeMs":{"label":"서브에이전트 최대 실행 시간","description":"서브에이전트당 절대 실행 시간 제한(ms)이다. 0이면 비활성화된다. 추론 계층 워치독을 빠져나가는 프로바이더 측 스트림 정지에 대한 심층 방어 수단이며, \'timed out\' 사유로 일반적인 서브에이전트 중단을 발생시킨다."},"task.softRequestBudget":{"label":"서브에이전트 소프트 요청 예산","description":"서브에이전트당 소프트 요청 예산(실행당 assistant 요청 수)이다. 이를 초과하면 마무리를 유도하는 steering 알림이 주입되며(task.softRequestBudgetNotice 참고), 예산의 1.5배에 도달하면 실행이 강제 중단되고 에이전트는 부분 결과를 내놓아야 한다. 0이면 이 보호 장치가 비활성화된다. 번들된 scout/sonic 에이전트는 더 낮은 내장 예산이 상한이므로, 그 상한보다 낮은 값은 이들에게도 적용된다."},"task.softRequestBudgetNotice":{"label":"소프트 요청 예산 알림","description":"서브에이전트가 소프트 요청 예산을 초과할 때 steering 알림을 한 번 주입해, 1.5배 강제 중단 전에 마무리하도록 요청한다."},"task.maxEffort":{"label":"spawn당 최대 effort","description":"task 도구의 spawn별 effort 힌트에 허용되는 최대 추론 effort이다. 값을 낮추면 호출자가 서브에이전트를 이 상한 이상으로 올릴 수 없으며, 기본값은 모델의 전체 범위를 유지한다."},"task.prewalk":{"label":"일반 작업 prewalk","description":"번들된 일반 `task` 서브에이전트에 prewalk를 적용한다: 해석된 모델로 시작해 계획을 세우고 구현을 시작한 뒤, 첫 편집/쓰기 시점에 \'smol\' 역할로 넘긴다. 에이전트별 재정의(/agents 허브에서 설정하는 task.agentPrewalk)와 사용자 에이전트의 `prewalk` frontmatter는 이 토글과 무관하게 적용된다."},"skills.enableSkillCommands":{"label":"스킬 명령","description":"스킬을 /skill:name 명령으로 등록한다"},"commands.enableClaudeUser":{"label":"Claude 사용자 명령","description":"~/.claude/commands/에서 명령을 로드한다"},"commands.enableClaudeProject":{"label":"Claude 프로젝트 명령","description":".claude/commands/에서 명령을 로드한다"},"commands.enableOpencodeUser":{"label":"OpenCode 사용자 명령","description":"~/.config/opencode/commands/에서 명령을 로드한다"},"commands.enableOpencodeProject":{"label":"OpenCode 프로젝트 명령","description":".opencode/commands/에서 명령을 로드한다"},"providers.maxInFlightRequests":{"label":"최대 동시 요청 수","description":"프로바이더 id별(예: \\"openai\\" 또는 \\"anthropic\\") 최대 동시 LLM 요청 수로, 같은 config root를 쓰는 로컬 OMP 프로세스 간에 공유된다. 명시되지 않은 프로바이더는 제한이 없다."},"secrets.enabled":{"label":"시크릿 숨김","description":"AI 프로바이더로 전송하기 전에 설정된 시크릿을 난독화하고 자격 증명 형태의 토큰을 마스킹한다"},"providers.webSearchOrder":{"label":"웹 검색 프로바이더 순서","description":"web_search 도구에 사용할 프로바이더의 우선순위이며, 목록에 없는 프로바이더는 그 뒤에 기본 순서를 유지한다"},"providers.webSearchExclude":{"label":"제외할 웹 검색 프로바이더","description":"web_search가 폴백으로도 절대 사용하지 않을 프로바이더이다"},"providers.webSearchTimeoutSeconds":{"label":"웹 검색 타임아웃","description":"web_search가 다음 폴백으로 넘어가기 전 각 프로바이더 검색 전송에 적용되는 절대 타임아웃이며 단위는 초이다(최대 300)"},"providers.webSearchGeminiModel":{"label":"Gemini web_search 모델","description":"Gemini Google Search grounding에 사용할 모델 ID이다. 기본값은 gemini-2.5-flash이다."},"providers.antigravityEndpoint":{"label":"Antigravity 엔드포인트 모드","description":"google-antigravity 프로바이더의 엔드포인트 라우팅 전략이다(chat, search, image, discovery)"},"providers.imageOrder":{"label":"이미지 프로바이더 순서","description":"이미지 생성에 사용할 프로바이더의 우선순위이며, 목록에 없는 프로바이더는 활성 세션 프로바이더와 내장 순서를 따른다"},"providers.fireworksTier":{"label":"Fireworks 티어","description":"Fireworks 요청의 서빙 경로이다. Priority는 `service_tier: \\"priority\\"`를 전송해 트래픽이 몰릴 때 더 높은 신뢰성을 더 높은 가격에 제공하고, Standard는 이를 생략한다. Fast(`-fast`) 모델은 이 설정을 무시하며, Fast는 별도의 서빙 경로이다."},"live.voice":{"label":"Live 음성","description":"Codex 기반 realtime 음성 세션에서 사용하는 음성이다"},"providers.tts":{"label":"TTS 제공자","description":"tts 도구의 백엔드이다: 로컬 온디바이스 신경망 TTS(Kokoro-82M) 또는 xAI Grok Voice 중 하나이다"},"tts.localModel":{"label":"로컬 TTS 모델","description":"로컬 TTS 백엔드가 사용하는 온디바이스 신경망 TTS 모델(Kokoro-82M)이다"},"tts.localVoice":{"label":"로컬 TTS 음성","description":"로컬 TTS 백엔드가 사용하는 Kokoro 음성이다(미국/영국, 여성/남성)"},"speech.enabled":{"label":"음성 출력","description":"어시스턴트의 출력을 스트리밍되는 대로 스피커로 소리내어 읽는다"},"speech.mode":{"label":"음성 출력 모드","description":"읽을 대상이다: all = 어시스턴트 메시지 + 사고 과정, assistant = 메시지만, yield = 턴 종료 시 마지막 메시지만이다"},"speech.enhanced":{"label":"향상된 음성 재작성","description":"합성 전에 tiny/smol 모델로 어시스턴트 출력을 자연스러운 구어체 산문으로 재작성한다(코드는 설명으로 바꾸고 링크와 markdown은 제거한다). 실패하면 기계적 정리로 대체된다"},"speech.voice":{"label":"음성 출력 목소리","description":"어시스턴트의 출력을 소리내어 읽을 때 사용하는 Kokoro 음성이다"},"providers.tinyModel":{"label":"Tiny 모델","description":"세션 제목 생성 모델이다: 기본값은 온라인(/models의 TINY 역할, 없으면 @smol)이며, 로컬 온디바이스 모델도 가능하다"},"providers.tinyModelDevice":{"label":"Tiny 모델 디바이스","description":"로컬 tiny 모델(제목 + 메모리)에 사용하는 ONNX 실행 제공자이다. 기본값은 CPU 전용 추론을 사용한다. PI_TINY_DEVICE 환경 변수가 이 값을 덮어쓴다."},"providers.tinyModelDtype":{"label":"Tiny 모델 정밀도","description":"로컬 tiny 모델의 ONNX 양자화/정밀도이다. 기본값은 각 모델에 포함된 dtype(q4)을 사용하며, 정밀도가 낮으면 더 빠르고 높으면 원본에 더 충실하다. PI_TINY_DTYPE 환경 변수가 이 값을 덮어쓴다."},"providers.unexpectedStopModel":{"label":"예기치 않은 중단 모델","description":"예기치 않은 중단 감지용 분류기이다: 기본값은 온라인(/models의 TINY 역할, 없으면 smol)이며, 로컬 온디바이스 모델도 가능하다."},"providers.kimiApiFormat":{"label":"Kimi API 형식","description":"Kimi Code 제공자의 API 형식이다(auto는 라이브 모델 메타데이터를 따른다)"},"providers.openaiWebsockets":{"label":"OpenAI WebSockets","description":"OpenAI Codex 모델의 websocket 정책이다(auto는 모델 기본값을 사용하고, on은 강제하며, off는 비활성화한다)"},"providers.streamFirstEventTimeoutSeconds":{"label":"스트림 첫 이벤트 타임아웃","description":"모델 스트림의 첫 이벤트를 기다리는 초이다. -1은 provider/env 기본값을 사용하고, 0은 워치독을 비활성화한다"},"providers.streamIdleTimeoutSeconds":{"label":"스트림 유휴 타임아웃","description":"모델 스트림이 이벤트 사이에 무응답 상태로 있을 수 있는 초이다. -1은 provider/env 기본값을 사용하고, 0은 워치독을 비활성화한다"},"providers.openrouterVariant":{"label":"OpenRouter 라우팅","description":"OpenRouter 모델 ID에 덧붙이는 기본 라우팅 variant 접미사이다(선택기에서 이미 variant를 지정한 경우 무시된다)"},"providers.fetch":{"label":"Fetch 제공자","description":"fetch/read URL 도구의 리더 백엔드 우선순위이다"},"codexResets.autoRedeem":{"label":"Codex 리셋 자동 사용","description":"저장된 Codex rate-limit 리셋을 자동으로 사용한다: 턴이 멈추고 다른 계정이 대체할 수 없을 때 5h 또는 weekly 창을 소진해 차단된 계정을 복구하고, 곧 만료될 크레딧을 회수한다. unset은 첫 사용 전에 확인하고, yes는 확인 없이 사용하며, no는 두 검사 모두 비활성화한다."},"provider.appendOnlyContext":{"label":"추가 전용 컨텍스트","description":"시스템 프롬프트 + 도구 명세를 캐시하고 추가 전용 메시지 로그를 유지해 provider prefix 캐시(DeepSeek, Xiaomi/SGLang, Anthropic) 적중률을 최대화한다. auto는 prefix 캐시가 알려진 제공자에 대해 활성화한다."},"exa.enabled":{"label":"Exa","description":"Exa 웹 검색 제공자를 활성화한다"},"searxng.endpoint":{"label":"SearXNG 엔드포인트","description":"웹 검색에 사용하는 자체 호스팅 SearXNG 인스턴스의 기본 URL이다"}}}'),dq=[{id:"models",label:"Models",icon:"model"},{id:"themes",label:"Themes",icon:"theme"},{id:"skills",label:"Skills",icon:"skill",requiresCwd:!0},{id:"plugins",label:"Plugins",icon:"plugin",requiresCwd:!0},{id:"mcp",label:"MCP",icon:"mcp"},{id:"access",label:"Access",icon:"access"},{id:"trust",label:"Project trust",labelKey:"trust.settingsNav",icon:"trust"},{id:"live-voice",label:"Call voice",labelKey:"chat.liveVoiceSettingsNav",icon:"liveVoice"},{id:"attachments",label:"Attachments",labelKey:"chat.attachmentSettingsNav",icon:"attachments"}],dK={model:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("rect",{x:"4",y:"4",width:"16",height:"16",rx:"3"}),(0,r.jsx)("path",{d:"M9 9h6v6H9zM9 1v3m6-3v3M9 20v3m6-3v3M1 9h3m16 0h3M1 15h3m16 0h3"})]}),theme:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"8"}),(0,r.jsx)("path",{d:"M12 4a8 8 0 0 0 0 16z"})]}),skill:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("path",{d:"m12 3 8 4-8 4-8-4 8-4Z"}),(0,r.jsx)("path",{d:"m4 12 8 4 8-4M4 17l8 4 8-4"})]}),plugin:(0,r.jsx)(r.Fragment,{children:(0,r.jsx)("path",{d:"M8 3v5m8-5v5M6 8h12v5a6 6 0 0 1-12 0V8Zm6 11v3"})}),mcp:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("circle",{cx:"6",cy:"6",r:"2"}),(0,r.jsx)("circle",{cx:"18",cy:"6",r:"2"}),(0,r.jsx)("circle",{cx:"12",cy:"18",r:"2"}),(0,r.jsx)("path",{d:"M8 7.5 11 16m5-8.5L13 16M8 6h8"})]}),access:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("rect",{x:"4",y:"10",width:"16",height:"10",rx:"2"}),(0,r.jsx)("path",{d:"M8 10V7a4 4 0 0 1 8 0v3M12 14v2"})]}),trust:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("path",{d:"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10Z"}),(0,r.jsx)("path",{d:"m9 12 2 2 4-4"})]}),liveVoice:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("path",{d:"M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3z"}),(0,r.jsx)("path",{d:"M19 10v2a7 7 0 0 1-14 0v-2M12 19v3"})]}),attachments:(0,r.jsx)("path",{d:"m21 12-8.6 8.6a5 5 0 0 1-7-7l8.5-8.6a3.3 3.3 0 0 1 4.7 4.7l-8.5 8.6a1.7 1.7 0 0 1-2.4-2.4l7.9-7.9"}),appearance:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"9"}),(0,r.jsx)("path",{d:"M12 3v18M3 12h18"})]}),interaction:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("path",{d:"M4 5h16v11H9l-5 4V5Z"}),(0,r.jsx)("path",{d:"M8 9h8m-8 3h5"})]}),context:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("path",{d:"M5 3h11l3 3v15H5z"}),(0,r.jsx)("path",{d:"M15 3v4h4M8 11h8m-8 4h8"})]}),memory:(0,r.jsx)(r.Fragment,{children:(0,r.jsx)("path",{d:"M9 4a3 3 0 0 0-3 3v1a3 3 0 0 0-1 5v1a3 3 0 0 0 3 3h1m6-13a3 3 0 0 1 3 3v1a3 3 0 0 1 1 5v1a3 3 0 0 1-3 3h-1M9 4v16m6-16v16"})}),files:(0,r.jsx)(r.Fragment,{children:(0,r.jsx)("path",{d:"M3 6h7l2 2h9v11H3z"})}),shell:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("rect",{x:"3",y:"4",width:"18",height:"16",rx:"2"}),(0,r.jsx)("path",{d:"m7 9 3 3-3 3m6 0h4"})]}),tools:(0,r.jsx)(r.Fragment,{children:(0,r.jsx)("path",{d:"m14 6 4-4 4 4-4 4M3 18l8-8m-6 4 5 5-3 3-5-5 3-3Z"})}),tasks:(0,r.jsx)(r.Fragment,{children:(0,r.jsx)("path",{d:"M9 6h11M9 12h11M9 18h11M4 6l1 1 2-2m-3 7 1 1 2-2m-3 7 1 1 2-2"})}),providers:(0,r.jsx)(r.Fragment,{children:(0,r.jsx)("path",{d:"M7 4h10v5H7zM4 15h6v5H4zm10 0h6v5h-6zM12 9v3m-5 0h10M7 12v3m10-3v3"})})};function dV({kind:e}){return(0,r.jsx)("svg",{className:d_().navIcon,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round",children:dK[e]??dK.tools})}function dJ({field:e,busy:t,onSave:n}){let[a,s]=(0,i.useState)("secret"===e.type?"":String(e.value??""));(0,i.useEffect)(()=>{s("secret"===e.type?"":String(e.value??""))},[e.path,e.type,e.value]);let l="secret"===e.type?"":String(e.value??"");return(0,r.jsx)("input",{className:d_().textInput,type:"secret"===e.type?"password":"text",value:a,disabled:t,placeholder:"secret"===e.type&&e.configured?"Configured — enter to replace":void 0,onChange:e=>s(e.target.value),onBlur:()=>{a!==l&&("secret"!==e.type||a.length>0)&&n(a)},onKeyDown:e=>{"Enter"===e.key&&e.currentTarget.blur()}})}function dG({field:e,busy:t,onSave:n}){let a=JSON.stringify(e.value??{},null,2),[s,l]=(0,i.useState)(a),[o,d]=(0,i.useState)(null);return(0,i.useEffect)(()=>{l(a),d(null)},[a]),(0,r.jsxs)("div",{style:{width:"100%"},children:[(0,r.jsx)("textarea",{className:d_().jsonEditor,style:{minHeight:92},value:s,disabled:t,onChange:e=>l(e.target.value),onBlur:()=>{if(s!==a)try{n(JSON.parse(s)),d(null)}catch(e){d(e instanceof Error?e.message:String(e))}}}),o&&(0,r.jsx)("div",{className:d_().error,children:o})]})}function dY({field:e,busy:t,onSave:n}){let i=Array.isArray(e.value)?e.value:[],a=(e,t)=>{let r=e+t;if(r<0||r>=i.length)return;let a=[...i];[a[e],a[r]]=[a[r],a[e]],n(a)};return(0,r.jsx)("div",{className:d_().multiSelect,children:e.options?.map(s=>{let l=i.indexOf(s.value);return(0,r.jsxs)("span",{className:d_().choice,"data-selected":l>=0,title:s.description,children:[(0,r.jsx)("button",{type:"button",className:d_().choiceToggle,disabled:t,onClick:()=>{let e;return e=s.value,n(i.includes(e)?i.filter(t=>t!==e):[...i,e])},children:s.label}),e.ordered&&l>=0&&(0,r.jsxs)("span",{className:d_().reorder,children:[(0,r.jsx)("button",{type:"button",disabled:t||0===l,onClick:()=>a(l,-1),children:"←"}),(0,r.jsx)("button",{type:"button",disabled:t||l===i.length-1,onClick:()=>a(l,1),children:"→"})]})]},s.value)})})}function dZ({field:e,busy:t,onSave:n}){return"boolean"===e.type?(0,r.jsx)("button",{type:"button",className:d_().switch,"data-on":!0===e.value,disabled:t,"aria-pressed":!0===e.value,onClick:()=>n(!0!==e.value)}):"select"===e.type?(0,r.jsx)(ob,{value:String(e.value??""),disabled:t,ariaLabel:e.label,options:(e.options??[]).map(e=>({value:e.value,label:e.label,description:e.description})),onChange:t=>n("number"==typeof e.value||"number"==typeof e.defaultValue?Number(t):t)}):"multiselect"===e.type?(0,r.jsx)(dY,{field:e,busy:t,onSave:n}):"providerLimits"===e.type?(0,r.jsx)(dG,{field:e,busy:t,onSave:n}):(0,r.jsx)(dJ,{field:e,busy:t,onSave:n})}function dX({field:e,busy:t,error:n,onSave:i}){return(0,r.jsxs)("div",{className:d_().settingRow,children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{className:d_().settingLabel,children:e.label}),(0,r.jsx)("div",{className:d_().settingDescription,children:e.description}),n&&(0,r.jsx)("div",{className:d_().error,children:n})]}),(0,r.jsx)("div",{className:d_().settingControl,children:(0,r.jsx)(dZ,{field:e,busy:t,onSave:i})})]})}function dQ({mode:e,palette:t}){let n=t.variables["--omp-md-heading"];return(0,r.jsxs)("div",{className:d_().themePreview,"data-seed-color-mode":"dark"===e?"dark-only":"light-only",children:[(0,r.jsx)("div",{className:d_().themePreviewBar,style:n?{background:n}:void 0}),(0,r.jsxs)("div",{className:d_().themePreviewPanel,children:[(0,r.jsx)("div",{className:d_().themePreviewLine}),(0,r.jsx)("div",{className:d_().themePreviewLine})]})]})}let d0='a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])',d1=new Set(["hideThinkingBlock"]);function d2({cwd:e,sessionId:t,initialSection:n="models",onClose:a,onModelsChanged:s,onReloaded:l}){let[o,d]=(0,i.useState)(n),[c,u]=(0,i.useState)(null),[p,h]=(0,i.useState)(!0),[m,f]=(0,i.useState)(null),[g,x]=(0,i.useState)(""),[v,b]=(0,i.useState)(new Set),[y,w]=(0,i.useState)({}),[k,j]=(0,i.useState)(!1),[S,C]=(0,i.useState)(!1),{theme:N,setPreference:I}=tB(),{locale:T,t:M}=(0,R.s)(),$=(0,i.useRef)(null),E=e=>"ko"===T?dU.shell[e]??e:e,L=(0,i.useCallback)(async()=>{h(!0),f(null);try{let t=e?`?cwd=${encodeURIComponent(e)}`:"",n=await fetch(`/api/settings${t}`,{cache:"no-store"}),r=await n.json();if(!n.ok||r.error)throw Error(r.error??`HTTP ${n.status}`);u(r)}catch(e){f(e instanceof Error?e.message:String(e))}finally{h(!1)}},[e]);(0,i.useEffect)(()=>{L()},[L]),(0,i.useEffect)(()=>{let e=$.current;if(!e)return;(Array.from(e.querySelectorAll(d0)).find(e=>e.getClientRects().length>0)??e).focus();let t=t=>{if("Tab"!==t.key)return;let n=Array.from(e.querySelectorAll(d0)).filter(e=>e.getClientRects().length>0),r=document.activeElement;if(0===n.length){t.preventDefault(),e.focus();return}let i=n[0],a=n[n.length-1];t.shiftKey&&(r===i||!e.contains(r))?(t.preventDefault(),a.focus()):t.shiftKey||r!==a&&e.contains(r)||(t.preventDefault(),i.focus())};return e.addEventListener("keydown",t),()=>e.removeEventListener("keydown",t)},[]);let A=(0,i.useCallback)(async(t,n)=>{b(e=>new Set(e).add(t.path)),w(e=>{let n={...e};return delete n[t.path],n});try{let r=await fetch("/api/settings",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:t.path,value:n})}),i=await r.json();if(!r.ok||i.error)throw Error(i.error??`HTTP ${r.status}`);u(e=>e?{...e,fields:e.fields.map(e=>e.path===t.path?{...e,value:i.value??n,configured:!0}:e)}:e),"theme.dark"===t.path||"theme.light"===t.path?(await tH(e),await L()):d1.has(t.path)?await t9(e):j(!0)}catch(e){w(n=>({...n,[t.path]:e instanceof Error?e.message:String(e)}))}finally{b(e=>{let n=new Set(e);return n.delete(t.path),n})}},[e,L]),z=(0,i.useMemo)(()=>new Map(c?.fields.map(e=>[e.path,e.value])??[]),[c?.fields]),P=(0,i.useMemo)(()=>c?.fields.filter(e=>(function(e,t){switch(e.condition){case void 0:default:return!0;case"hasImageProtocol":return!1;case"advisorEnabled":return!0===t.get("advisor.enabled");case"hindsightActive":return"hindsight"===t.get("memory.backend");case"mnemopiActive":return"mnemopi"===t.get("memory.backend");case"autolearnActive":return!0===t.get("autolearn.enabled");case"autoThinkingActive":return"auto"===t.get("defaultThinkingLevel");case"usageAwareFallbackEnabled":return!0===t.get("retry.usageAwareFallback");case"planModeEnabled":return!0===t.get("plan.enabled");case"unexpectedStopDetection":return!0===t.get("features.unexpectedStopDetection")}})(e,z))??[],[c?.fields,z]),W=o.startsWith("settings:")?o.slice(9):null,F=(0,i.useMemo)(()=>{let e=g.trim().toLowerCase();return e?P.filter(t=>`${t.label} ${t.description} ${t.path} ${t.group??""}`.toLowerCase().includes(e)):W?P.filter(e=>e.tab===W&&("appearance"!==W||"Theme"!==e.group)):[]},[W,g,P]),_=(0,i.useCallback)(()=>{s?.(),a()},[a,s]),D=(0,i.useCallback)(async()=>{if(t){C(!0);try{await sB(t,{type:"reload"}),j(!1),l?.()}catch(e){f(e instanceof Error?e.message:String(e))}finally{C(!1)}}},[l,t]),O=c?.tabs.find(e=>e.id===W),H=g.trim()?`${E("Search")} \xb7 ${F.length}`:O?.label??E("Settings"),B=(e,t)=>[...new Set([...t,...e.map(e=>e.group??"General").filter(e=>!t.includes(e))])].map(t=>{let n=e.filter(e=>(e.group??"General")===t);return n.length?(0,r.jsxs)("section",{className:d_().group,children:[(0,r.jsx)("h3",{className:d_().groupTitle,children:t}),n.map(e=>(0,r.jsx)(dX,{field:e,busy:v.has(e.path),error:y[e.path],onSave:t=>void A(e,t)},e.path))]},t):null}),U=()=>p?(0,r.jsx)("div",{className:d_().empty,children:E("Loading omp settings…")}):m||!c?(0,r.jsx)("div",{className:d_().empty,children:m??E("Settings unavailable")}):(0,r.jsxs)("div",{className:d_().scrollContent,children:[(0,r.jsxs)("header",{className:d_().contentHeader,children:[(0,r.jsx)("h2",{className:d_().contentTitle,children:H}),(0,r.jsx)("p",{className:d_().contentDescription,children:E(g.trim()?"Matching canonical /settings entries across every category.":"Canonical omp /settings values. Changes are saved immediately to the shared agent configuration.")}),k&&t&&(0,r.jsxs)("div",{className:d_().reloadNotice,children:[(0,r.jsx)("span",{children:E("Saved. Reload the active session to apply runtime settings.")}),(0,r.jsx)("button",{type:"button",onClick:()=>void D(),disabled:S,children:E(S?"Reloading…":"Reload session")})]})]}),(0,r.jsx)("div",{className:d_().settingsBody,children:F.length?B(F,O?.groups??[]):(0,r.jsx)("div",{className:d_().empty,children:E("No settings match this search.")})})]});return(0,r.jsx)("div",{className:d_().backdrop,onMouseDown:e=>{e.target===e.currentTarget&&_()},children:(0,r.jsxs)("div",{ref:$,tabIndex:-1,className:d_().window,role:"dialog","aria-modal":"true","aria-label":E("Settings"),children:[(0,r.jsxs)("aside",{className:d_().sidebar,children:[(0,r.jsxs)("div",{className:d_().brand,children:[(0,r.jsx)("div",{className:d_().eyebrow,children:"omp /settings"}),(0,r.jsx)("h1",{className:d_().title,children:E("Settings")}),(0,r.jsx)("code",{className:d_().context,title:e??E("Global configuration"),children:e??E("Global configuration")})]}),(0,r.jsxs)("div",{className:d_().searchWrap,children:[(0,r.jsxs)("svg",{className:d_().searchIcon,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"11",cy:"11",r:"7"}),(0,r.jsx)("path",{d:"m20 20-4-4"})]}),(0,r.jsx)("input",{className:d_().search,value:g,"aria-label":E("Search /settings"),placeholder:E("Search /settings"),onChange:e=>x(e.target.value)})]}),(0,r.jsxs)("nav",{className:d_().nav,children:[(0,r.jsx)("div",{className:d_().navLabel,children:E("Configuration")}),dq.map(t=>{let n=t.labelKey?M(t.labelKey):E(t.label);return(0,r.jsxs)("button",{type:"button",className:d_().navButton,"data-active":!g&&o===t.id,disabled:t.requiresCwd&&!e,title:t.requiresCwd&&!e?`${n} ${E("requires a project")}`:n,onClick:()=>{x(""),d(t.id)},children:[(0,r.jsx)(dV,{kind:t.icon}),(0,r.jsx)("span",{children:n})]},t.id)}),(0,r.jsx)("div",{className:d_().navLabel,children:E("OMP settings")}),c?.tabs.map(e=>(0,r.jsxs)("button",{type:"button",className:d_().navButton,"data-active":!g&&W===e.id,onClick:()=>{x(""),d(`settings:${e.id}`)},children:[(0,r.jsx)(dV,{kind:e.id}),(0,r.jsx)("span",{children:e.label})]},e.id))]}),(0,r.jsx)("div",{className:d_().closeRail,children:(0,r.jsxs)("button",{type:"button",className:d_().closeButton,onClick:_,children:[(0,r.jsx)("span",{children:E("Close settings")}),(0,r.jsx)("span",{"aria-hidden":"true",children:"\xd7"})]})})]}),(0,r.jsx)("main",{className:d_().content,children:g.trim()?U():"models"===o?(0,r.jsx)(dm,{cwd:e,embedded:!0,onClose:_,onModelsChanged:s}):"themes"===o?c?(0,r.jsxs)("div",{className:d_().scrollContent,children:[(0,r.jsxs)("header",{className:d_().contentHeader,children:[(0,r.jsx)("h2",{className:d_().contentTitle,children:E("Themes")}),(0,r.jsxs)("p",{className:d_().contentDescription,children:[E("The web interface uses the same dark and light theme mappings as omp. Changes are persisted to "),(0,r.jsx)("code",{children:"~/.omp/agent/config.yml"}),E(" and applied here immediately.")]})]}),(0,r.jsxs)("div",{className:d_().settingsBody,children:[(0,r.jsx)("div",{className:d_().themeGrid,children:["dark","light"].map(e=>{let t=c.fields.find(t=>t.path===`theme.${e}`),n=c.theme.palettes[e];return(0,r.jsxs)("div",{className:d_().themeCard,children:[(0,r.jsx)(dQ,{mode:e,palette:n}),(0,r.jsxs)("div",{className:d_().themeCardBody,children:[(0,r.jsxs)("div",{className:d_().themeCardHeader,children:[(0,r.jsxs)("span",{className:d_().themeSlot,children:[e,E(" mapping")]}),N===e&&(0,r.jsx)("span",{className:d_().themeActive,children:E("Active on web")})]}),(0,r.jsx)(ob,{value:String(t.value),disabled:v.has(t.path),ariaLabel:`${e} theme`,options:(t.options??[]).map(e=>({value:e.value,label:e.label,description:e.description})),onChange:e=>void A(t,e)}),N!==e&&(0,r.jsxs)("button",{type:"button",className:d_().closeButton,style:{marginTop:8},onClick:()=>I(e),children:[E("Preview "),e]})]})]},e)})}),B(c.fields.filter(e=>"appearance"===e.tab&&"Theme"===e.group&&!e.path.startsWith("theme.")),["Theme"])]})]}):(0,r.jsx)("div",{className:d_().empty,children:p?E("Loading themes…"):m??E("Themes unavailable")}):"skills"===o&&e?(0,r.jsx)(dj,{cwd:e,embedded:!0,onClose:_}):"plugins"===o&&e?(0,r.jsx)(dW,{cwd:e,sessionId:t,embedded:!0,onClose:_,onReloaded:l}):"mcp"===o?(0,r.jsx)(d4,{cwd:e,sessionId:t,onReloaded:l}):"access"===o?(0,r.jsx)(dD,{}):"trust"===o?(0,r.jsx)(dB,{cwd:e}):"live-voice"===o?(0,r.jsx)(dO,{}):"attachments"===o?(0,r.jsx)(dH,{}):U()})]})})}function d4({cwd:e,sessionId:t,onReloaded:n}){let[a,s]=(0,i.useState)(null),[l,o]=(0,i.useState)("user"),[d,c]=(0,i.useState)(0),[u,p]=(0,i.useState)(""),[h,m]=(0,i.useState)(""),[f,g]=(0,i.useState)(null),[x,v]=(0,i.useState)(!1),[b,y]=(0,i.useState)(null),w=(0,i.useCallback)(async()=>{try{let t=e?`?cwd=${encodeURIComponent(e)}`:"",n=await fetch(`/api/mcp${t}`,{cache:"no-store"}),r=await n.json();if(!n.ok||r.error)throw Error(r.error??`HTTP ${n.status}`);s(r),g(null)}catch(e){g(e instanceof Error?e.message:String(e))}},[e]);(0,i.useEffect)(()=>{w()},[w]);let k=a?"user"===l?a.user:a.project:null,j=k?.servers[d]??null;(0,i.useEffect)(()=>{m(j?.name??""),p(j?JSON.stringify(j.config,null,2):"")},[j]);let S=e=>{s(t=>{if(!t)return t;let n={..."user"===l?t.user:t.project,servers:e};return"user"===l?{...t,user:n}:{...t,project:n}})},C=async()=>{if(k){v(!0),g(null);try{let t,n=(t=k?.servers??[],(j?.editable===!1?t:t.map((e,t)=>t===d?{...e,name:h,config:JSON.parse(u)}:e)).filter(e=>!1!==e.editable).map(({name:e,config:t})=>({name:e,config:t}))),r=e?`?cwd=${encodeURIComponent(e)}`:"",i=await fetch(`/api/mcp${r}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({scope:l,servers:n})}),a=await i.json();if(!i.ok||a.error)throw Error(a.error??`HTTP ${i.status}`);await w()}catch(e){g(e instanceof Error?e.message:String(e))}finally{v(!1)}}},N=async r=>{y(`${l}:${r.name}`),g(null);try{let i=e?`?cwd=${encodeURIComponent(e)}`:"",a=await fetch(`/api/mcp${i}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({scope:l,name:r.name,enabled:!r.enabled})}),s=await a.json();if(!a.ok||s.error)throw Error(s.error??`HTTP ${a.status}`);await w(),t&&(await sB(t,{type:"reload"}),n?.())}catch(e){g(e instanceof Error?e.message:String(e))}finally{y(null)}};return(0,r.jsxs)("div",{className:d_().scrollContent,children:[(0,r.jsxs)("header",{className:d_().contentHeader,children:[(0,r.jsx)("h2",{className:d_().contentTitle,children:"MCP servers"}),(0,r.jsx)("p",{className:d_().contentDescription,children:"All MCP servers discovered by OMP are listed by scope and can be enabled or disabled here. Native OMP entries are editable; configurations owned by Claude, Codex, Gemini, plugins, or other providers remain read-only at their source."})]}),(0,r.jsx)("div",{className:d_().settingsBody,children:a?(0,r.jsxs)("div",{className:d_().mcpLayout,children:[(0,r.jsxs)("aside",{className:d_().mcpList,children:[(0,r.jsxs)("div",{className:d_().scopeTabs,children:[(0,r.jsxs)("button",{type:"button",className:d_().scopeButton,"data-active":"user"===l,onClick:()=>{o("user"),c(0)},children:["User \xb7 ",a.user.servers.length]}),(0,r.jsxs)("button",{type:"button",className:d_().scopeButton,"data-active":"project"===l,disabled:!a.project,onClick:()=>{o("project"),c(0)},children:["Project \xb7 ",a.project?.servers.length??0]})]}),k?.error?(0,r.jsx)("div",{className:d_().error,style:{padding:12},children:k.error}):(0,r.jsx)("div",{className:d_().serverRows,children:k?.servers.length?k.servers.map((e,t)=>{let n=`${l}:${e.name}`;return(0,r.jsxs)("div",{className:d_().serverRow,"data-active":d===t,children:[(0,r.jsxs)("button",{type:"button",className:d_().serverSelect,title:e.source?.path,onClick:()=>c(t),children:[(0,r.jsx)("span",{className:d_().statusDot,"data-off":!e.enabled}),(0,r.jsx)("span",{className:d_().serverName,children:e.name}),!1===e.editable&&(0,r.jsx)("span",{className:d_().sourceBadge,children:e.source?.provider??"external"})]}),(0,r.jsx)("button",{type:"button",className:d_().serverToggle,"data-on":e.enabled,disabled:b===n,"aria-pressed":e.enabled,"aria-label":`${e.enabled?"Disable":"Enable"} ${e.name}`,title:`${e.enabled?"Disable":"Enable"} ${e.name}`,onClick:()=>void N(e),children:b===n?"…":e.enabled?"ON":"OFF"})]},`${e.name}-${e.source?.path??t}`)}):(0,r.jsx)("div",{className:d_().serverListEmpty,children:"No servers in this scope."})}),(0,r.jsx)("button",{type:"button",className:d_().addServer,disabled:!!k?.error,onClick:()=>{if(!k)return;let e="new-server",t=2;for(;k.servers.some(t=>t.name===e);)e=`new-server-${t++}`;let n=[...k.servers,{name:e,config:{type:"stdio",command:""},enabled:!0,editable:!0}];S(n),c(n.length-1)},children:"+ Add OMP server"})]}),(0,r.jsx)("section",{className:d_().mcpEditor,children:j?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("div",{className:d_().editorHeader,children:[(0,r.jsx)("input",{className:d_().textInput,value:h,readOnly:!1===j.editable,onChange:e=>m(e.target.value),placeholder:"server-name"}),!1!==j.editable&&(0,r.jsx)("button",{type:"button",className:d_().dangerButton,onClick:()=>{k&&j&&!1!==j.editable&&(S(k.servers.filter((e,t)=>t!==d)),c(Math.max(0,d-1)))},children:"Delete"})]}),!1===j.editable&&(0,r.jsxs)("div",{className:d_().readOnlyNotice,children:["Configuration read-only \xb7 managed by ",j.source?.provider??"an external provider",". Status can be changed from the server list."]}),(0,r.jsx)("textarea",{className:d_().jsonEditor,value:u,readOnly:!1===j.editable,spellCheck:!1,onChange:e=>p(e.target.value)}),(0,r.jsxs)("div",{className:d_().editorActions,children:[(0,r.jsxs)("div",{children:[f&&(0,r.jsx)("div",{className:d_().error,children:f}),(0,r.jsx)("div",{className:d_().saveState,children:j.source?.path??k?.path})]}),!1!==j.editable&&(0,r.jsx)("button",{type:"button",className:d_().primaryButton,disabled:x,onClick:()=>void C(),children:x?"Saving…":"Save MCP"})]})]}):(0,r.jsx)("div",{className:d_().empty,children:"Add or select an MCP server."})})]}):(0,r.jsx)("div",{className:d_().empty,children:f??"Loading MCP configuration…"})})]})}let d5="cuelo-notification-prompt-dismissed";function d6({variant:e,locale:t,permission:n,dismissed:i,request:a,dismiss:s}){let l="ko"===t;return null===n||"granted"===n?null:"banner"===e?"default"!==n||i?null:(0,r.jsxs)("div",{className:"workspace-update-banner",role:"region","aria-label":l?"알림 권한 안내":"Notification permission",children:[(0,r.jsx)("span",{className:"workspace-update-banner-detail",style:{fontFamily:"inherit",fontSize:"inherit",color:"inherit"},children:l?"백그라운드 작업 완료 알림을 받으세요.":"Get notified when background work finishes."}),(0,r.jsx)("button",{type:"button",className:"workspace-update-banner-dismiss",onClick:a,children:l?"알림 켜기":"Enable notifications"}),(0,r.jsx)("button",{type:"button",className:"workspace-update-banner-dismiss",onClick:s,"aria-label":l?"알림 권한 안내 닫기":"Dismiss notification prompt",children:l?"닫기":"Dismiss"})]}):(0,r.jsx)(d.k.Item,{disabled:"denied"===n,onClick:"default"===n?a:void 0,children:(0,r.jsxs)(d.k.ItemBody,{children:[(0,r.jsx)(d.k.ItemLabel,{children:"default"===n?l?"알림 켜기":"Enable notifications":l?"알림 차단됨":"Notifications blocked"}),"denied"===n&&(0,r.jsx)(d.k.ItemDescription,{children:l?"주소창 옆 사이트 설정에서 알림을 허용하세요.":"Allow notifications in site settings beside the address bar."})]})})}function d8({cwd:e,busy:t,scheduled:n,error:a,onCancel:s,onConfirm:l,onCancelSchedule:o}){let{t:d}=(0,R.s)(),c=(0,i.useRef)(null);(0,i.useEffect)(()=>{c.current?.focus()},[n]);let u={height:32,padding:"0 12px",borderRadius:5,cursor:t?"not-allowed":"pointer",fontSize:12};return(0,r.jsx)("div",{role:"presentation",style:{position:"fixed",inset:0,zIndex:1100,display:"flex",alignItems:"center",justifyContent:"center",padding:16,background:"rgba(0,0,0,0.4)"},onClick:e=>{t||e.target!==e.currentTarget||s()},children:(0,r.jsxs)("div",{role:"dialog","aria-modal":"true","aria-labelledby":"project-trust-title","aria-describedby":"project-trust-body",style:{width:440,maxWidth:"100%",border:"1px solid var(--border)",borderRadius:8,background:"var(--bg-panel)",boxShadow:"0 12px 36px rgba(0,0,0,0.24)",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{display:"flex",gap:12,padding:"18px 18px 14px"},children:[(0,r.jsxs)("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"#f59e0b",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0,marginTop:1},children:[(0,r.jsx)("path",{d:"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10Z"}),n?(0,r.jsx)("path",{d:"M12 8v4l2 2"}):(0,r.jsx)("path",{d:"m9 12 2 2 4-4"})]}),(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("div",{id:"project-trust-title",style:{fontSize:15,fontWeight:700,color:"var(--text)"},children:d(n?"trust.scheduledTitle":"trust.dialogTitle")}),(0,r.jsx)("div",{id:"project-trust-body","aria-live":"polite",style:{marginTop:7,fontSize:12,lineHeight:1.6,color:"var(--text-muted)"},children:d(n?"trust.scheduledBody":"trust.dialogBody")}),(0,r.jsx)("code",{style:{display:"block",marginTop:10,padding:"8px 10px",border:"1px solid var(--border)",borderRadius:5,background:"var(--bg)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:11,overflowWrap:"anywhere"},children:e}),a&&(0,r.jsx)("div",{role:"alert",style:{marginTop:10,color:"#ef4444",fontSize:12,lineHeight:1.5},children:a})]})]}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",justifyContent:"flex-end",gap:8,padding:"10px 18px",borderTop:"1px solid var(--border)"},children:[n&&(0,r.jsx)("button",{type:"button",onClick:o,disabled:t,style:{...u,border:"1px solid var(--border)",background:"transparent",color:"var(--text-muted)"},children:d("trust.cancelSchedule")}),(0,r.jsx)("button",{ref:c,type:"button",onClick:s,disabled:t,style:{...u,border:"1px solid var(--border)",background:"transparent",color:"var(--text-muted)"},children:d(n?"trust.close":"trust.cancel")}),!n&&(0,r.jsx)("button",{type:"button",onClick:l,disabled:t,style:{...u,border:"1px solid transparent",background:"var(--seed-color-bg-neutral-inverted)",color:"var(--seed-color-fg-neutral-inverted)",cursor:t?"wait":"pointer",opacity:t?.7:1,fontWeight:600},children:d(t?"trust.trusting":"trust.trustProject")})]})]})})}var d3=n(75273);let d7={kind:"loading"};function d9(e){return"failed"===e.status?"var(--danger)":"aborted"===e.status||e.progress?.retryState?"var(--warning)":(0,nq.Ch)(e.status)?"var(--accent)":"var(--success)"}function ce(e){return"live-archive"===e.identity?"실시간 + 디스크":"live"===e.identity?"실시간":"디스크 기록"}let ct={bundled:"기본 제공",user:"사용자 정의",project:"프로젝트 정의"};function cn(e){return e.lastUpdate||e.progress?.durationMs||0}let cr=(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M13 5V2m0 0h-3m3 0-2.1 2.1A5.5 5.5 0 1 0 13.3 9"})}),ci=[];function ca({state:e,summary:t,reason:n,onOpenFile:i}){let{st:a}=ng(),{t:s}=(0,R.s)(),l="ready-archive"===e.kind||"empty"===e.kind&&"archive"===e.source;if(!t&&!l)return null;let o=t?.files??[],d=t?.checks??[];return(0,r.jsxs)("div",{className:"maker-detail-outcome",children:[n&&(0,r.jsxs)("p",{className:"maker-detail-reason",children:[(0,r.jsx)("span",{children:a("detail.reason")})," ",n]}),(0,r.jsxs)("section",{children:[(0,r.jsx)("h3",{className:"maker-detail-heading",children:a("summary.heading.files")}),l?(0,r.jsx)("p",{className:"maker-detail-empty",children:s("makerDetail.archiveUnobserved")}):o.length>0?(0,r.jsx)(nT,{files:o,onOpenFile:i}):(0,r.jsx)("p",{className:"maker-detail-empty",children:s("makerDetail.noFiles")})]}),(0,r.jsxs)("section",{children:[(0,r.jsx)("h3",{className:"maker-detail-heading",children:a("summary.heading.checks")}),l?(0,r.jsx)("p",{className:"maker-detail-empty",children:s("makerDetail.archiveUnobserved")}):d.length>0?(0,r.jsx)("ul",{className:"answer-summary-list",children:d.map(e=>(0,r.jsxs)("li",{className:"answer-check","data-state":e.state,children:[(0,r.jsx)("code",{className:"answer-check-command",title:e.command,children:e.command}),(0,r.jsxs)("span",{className:"answer-check-result",children:[s(cs[e.state]),null!==e.exitCode?` \xb7 ${a("summary.check.exit",{code:e.exitCode})}`:null]})]},e.toolCallId))}):(0,r.jsx)("p",{className:"maker-detail-empty",children:s("makerDetail.noChecks")})]})]})}let cs={passed:"makerDetail.checkPassed",failed:"makerDetail.checkFailed",unobserved:"makerDetail.checkUnobserved"};function cl({sessionId:e,sessionCwd:t,record:n,selection:a,client:s,visible:l,onBack:o,onOpenFile:d}){let{st:c}=ng(),{t:u}=(0,R.s)(),p=n?.key,h=n?.live?.id,m=n?.live?.status,f=n?.archive?.name,g=(0,i.useMemo)(()=>p?[{key:p,liveId:h,status:m,archiveName:f}]:[],[p,h,m,f]),x=(0,i.useRef)(null),v=(0,i.useRef)(null),b=(0,nq._Z)(g,{sessionId:e,client:s,enabled:l&&g.length>0}),y=(p?b.get(p)?.state:void 0)??d7;(0,i.useEffect)(()=>{l&&v.current?.focus({preventScroll:!0})},[a.key,l]),(0,i.useEffect)(()=>{if(!l||"ready-live"!==y.kind&&"ready-archive"!==y.kind)return;let e=requestAnimationFrame(()=>{let e=x.current;e&&(e.scrollTop=e.scrollHeight)});return()=>cancelAnimationFrame(e)},[y,l]);let w="ready-live"===y.kind?y.entries:ci,k=(0,i.useMemo)(()=>{let e=new Map;for(let t of w)"message"in t&&"toolResult"===t.message.role&&e.set(t.message.toolCallId,t.message);return e},[w]),j=(0,i.useMemo)(()=>"ready-live"===y.kind?n3(y.entries,t):null,[y,t]),S=n?.live?.id||n?.archive?.name||"Subagent",C=n?(0,nM.$V)(n).title:S,N=a.status;return(0,r.jsxs)("div",{role:"region","aria-label":u("makerDetail.region",{title:S}),style:{display:"flex",flexDirection:"column",width:"100%",height:"100%",minHeight:0},children:[(0,r.jsx)(lX,{back:{label:u("subagents.back"),onClick:o},title:C,titleTooltip:n?`${C}
21
21
  ${S} \xb7 ${ce(n)}`:void 0,titleRef:v,subtitle:n?`${S} \xb7 ${ce(n)}`:void 0,state:N?(0,r.jsx)(n8,{maker:N,st:c}):n?.live&&(0,r.jsx)("span",{style:{color:d9(n.live),fontFamily:"var(--font-mono)",fontSize:11},children:n.live.status})}),!n&&(0,r.jsx)("div",{role:"status",className:"maker-detail-empty",style:{padding:24,textAlign:"center"},children:u("makerDetail.unavailable")}),n&&(0,r.jsx)(ca,{state:y,summary:j,reason:N?.verdict?.reason??null,onOpenFile:d}),n&&(0,r.jsxs)("div",{ref:x,style:{flex:1,minHeight:0,overflowY:"auto",padding:"10px 12px 18px"},children:["loading"===y.kind&&(0,r.jsx)("div",{role:"status",style:{padding:24,color:"var(--text-muted)",textAlign:"center",fontSize:10.5},children:"기록 불러오는 중…"}),"ready-live"===y.kind&&y.entries.flatMap((e,n)=>{if(!("message"in e))return[];let i=y.entries[n-1];return[(0,r.jsx)(rO,{message:e.message,toolResults:k,cwd:t,showTimestamp:!0,prevTimestamp:i&&"message"in i?i.message.timestamp:void 0},e.id)]}),"ready-archive"===y.kind&&(0,r.jsxs)(r.Fragment,{children:[y.note&&(0,r.jsx)("div",{role:"status",style:{marginBottom:8,color:"var(--text-muted)",fontSize:9.5,lineHeight:1.5},children:y.note}),y.truncated&&(0,r.jsx)("div",{role:"status",style:{marginBottom:8,color:"var(--warning)",fontSize:9.5},children:"최근 400개 기록만 표시합니다."}),y.entries.map((e,t)=>(0,r.jsxs)("div",{style:{margin:"0 0 7px",padding:"8px 9px",border:"1px solid var(--border)",borderRadius:6,background:"var(--bg)",color:"var(--text)",whiteSpace:"pre-wrap",overflowWrap:"anywhere",fontSize:11,lineHeight:1.55},children:[(0,r.jsxs)("div",{style:{marginBottom:5,color:"var(--text-dim)",fontFamily:"var(--font-mono)",fontSize:8.5,letterSpacing:"0.04em"},children:[e.role," \xb7 ",e.kind]}),e.text||"(내용 없음)"]},`${e.at??0}:${t}`))]}),"empty"===y.kind&&(0,r.jsxs)("div",{role:"status",style:{padding:24,color:"var(--text-muted)",textAlign:"center",fontSize:10.5,lineHeight:1.6},children:[y.note&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{children:y.note}),(0,r.jsx)("br",{})]}),"대화 내용이 없습니다."]}),"unreachable"===y.kind&&(0,r.jsx)("div",{role:"status",style:{padding:10,border:"1px solid var(--border)",borderRadius:6,background:"var(--bg)",color:"var(--text-muted)",fontSize:10.5,lineHeight:1.5},children:y.message}),"error"===y.kind&&(0,r.jsx)("div",{role:"alert",style:{padding:10,border:"1px solid var(--border)",borderRadius:6,background:"var(--bg)",color:"var(--danger)",fontSize:10.5,lineHeight:1.5},children:y.message})]})]})}function co({record:e,view:t,onSelect:n}){let{st:a}=ng(),s=(0,i.useId)(),l=e.live,o=e.archive,d=(0,nM.$V)(e),c=!!(l&&(0,nq.Ch)(l.status)),u=c?d.stage:null,p=c&&t?t:null,h=p?.phase?a("phase.current",{phase:a(`phase.${p.phase}`)}):"",m=p?.todo?n2(a,p.todo):"",f=l?.id||o?.name||"Subagent",g=ce(e),x=(0,nM.wX)(e),v=(0,nM.A7)(e),b=v.modelShort??"모델 미확인",y=v.effort??"추론 미확인",w="known"===x.kind?x.label:"역할 미확인";return(0,r.jsx)("div",{role:"listitem",children:(0,r.jsxs)("button",{type:"button",onClick:n,"data-identity":e.identity,"data-subagent-key":e.key,title:`${f}
22
22
  ${v.model??"모델 미확인"} \xb7 ${y}