cuelo 0.10.355 → 0.10.359

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 (158) hide show
  1. package/.next/BUILD_ID +1 -1
  2. package/.next/app-path-routes-manifest.json +51 -51
  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 +3 -3
  19. package/.next/server/app/_not-found.segments/_full.segment.rsc +3 -3
  20. package/.next/server/app/_not-found.segments/_head.segment.rsc +1 -1
  21. package/.next/server/app/_not-found.segments/_index.segment.rsc +3 -3
  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 +2 -2
  25. package/.next/server/app/api/agent/[id]/account/route.js +1 -1
  26. package/.next/server/app/api/agent/[id]/account/route.js.nft.json +1 -1
  27. package/.next/server/app/api/agent/[id]/browser/events/route.js +1 -1
  28. package/.next/server/app/api/agent/[id]/browser/events/route.js.nft.json +1 -1
  29. package/.next/server/app/api/agent/[id]/browser/input/route.js +1 -1
  30. package/.next/server/app/api/agent/[id]/browser/input/route.js.nft.json +1 -1
  31. package/.next/server/app/api/agent/[id]/browser/route.js +1 -1
  32. package/.next/server/app/api/agent/[id]/browser/route.js.nft.json +1 -1
  33. package/.next/server/app/api/agent/[id]/computer-takeover/route.js +1 -1
  34. package/.next/server/app/api/agent/[id]/computer-takeover/route.js.nft.json +1 -1
  35. package/.next/server/app/api/agent/[id]/events/route.js +1 -1
  36. package/.next/server/app/api/agent/[id]/events/route.js.nft.json +1 -1
  37. package/.next/server/app/api/agent/[id]/route.js +1 -1
  38. package/.next/server/app/api/agent/[id]/route.js.nft.json +1 -1
  39. package/.next/server/app/api/agent/new/route.js +1 -1
  40. package/.next/server/app/api/agent/new/route.js.nft.json +1 -1
  41. package/.next/server/app/api/agent/running/route.js +1 -1
  42. package/.next/server/app/api/agent/running/route.js.nft.json +1 -1
  43. package/.next/server/app/api/gpt6/handles/route.js +1 -1
  44. package/.next/server/app/api/gpt6/handles/route.js.nft.json +1 -1
  45. package/.next/server/app/api/gpt6/reply/route.js +1 -1
  46. package/.next/server/app/api/gpt6/reply/route.js.nft.json +1 -1
  47. package/.next/server/app/api/gpt6/token/route.js +1 -1
  48. package/.next/server/app/api/gpt6/token/route.js.nft.json +1 -1
  49. package/.next/server/app/api/gpt6/web6-session/route.js +1 -1
  50. package/.next/server/app/api/gpt6/web6-session/route.js.nft.json +1 -1
  51. package/.next/server/app/api/live/call/[callId]/route.js +1 -1
  52. package/.next/server/app/api/live/call/[callId]/route.js.nft.json +1 -1
  53. package/.next/server/app/api/live/draft-secret/route.js +1 -1
  54. package/.next/server/app/api/live/draft-secret/route.js.nft.json +1 -1
  55. package/.next/server/app/api/live/events/route.js +1 -1
  56. package/.next/server/app/api/live/events/route.js.nft.json +1 -1
  57. package/.next/server/app/api/live/interpret/assist/route.js +1 -1
  58. package/.next/server/app/api/live/interpret/assist/route.js.nft.json +1 -1
  59. package/.next/server/app/api/live/interpret/reading/route.js +1 -1
  60. package/.next/server/app/api/live/interpret/reading/route.js.nft.json +1 -1
  61. package/.next/server/app/api/live/interpret/route.js +1 -1
  62. package/.next/server/app/api/live/interpret/route.js.nft.json +1 -1
  63. package/.next/server/app/api/live/interpret/scan/route.js +1 -1
  64. package/.next/server/app/api/live/interpret/scan/route.js.nft.json +1 -1
  65. package/.next/server/app/api/live/interpret/text/route.js +1 -1
  66. package/.next/server/app/api/live/interpret/text/route.js.nft.json +1 -1
  67. package/.next/server/app/api/live/offer/route.js +1 -1
  68. package/.next/server/app/api/live/offer/route.js.nft.json +1 -1
  69. package/.next/server/app/api/live/speech/route.js +1 -1
  70. package/.next/server/app/api/live/speech/route.js.nft.json +1 -1
  71. package/.next/server/app/api/live/voices/route.js +1 -1
  72. package/.next/server/app/api/live/voices/route.js.nft.json +1 -1
  73. package/.next/server/app/api/project-trust/route.js +1 -1
  74. package/.next/server/app/api/project-trust/route.js.nft.json +1 -1
  75. package/.next/server/app/api/runs/[runId]/prelude/route.js +1 -1
  76. package/.next/server/app/api/runs/[runId]/prelude/route.js.nft.json +1 -1
  77. package/.next/server/app/api/sessions/[id]/auto-name/route.js +1 -1
  78. package/.next/server/app/api/sessions/[id]/auto-name/route.js.nft.json +1 -1
  79. package/.next/server/app/api/sessions/[id]/context/route.js +1 -1
  80. package/.next/server/app/api/sessions/[id]/context/route.js.nft.json +1 -1
  81. package/.next/server/app/api/sessions/[id]/route.js +1 -1
  82. package/.next/server/app/api/sessions/[id]/route.js.nft.json +1 -1
  83. package/.next/server/app/api/sessions/[id]/state/route.js +1 -1
  84. package/.next/server/app/api/sessions/[id]/state/route.js.nft.json +1 -1
  85. package/.next/server/app/api/sessions/route.js +1 -1
  86. package/.next/server/app/api/sessions/route.js.nft.json +1 -1
  87. package/.next/server/app/api/tool-image/route.js +1 -1
  88. package/.next/server/app/api/tool-image/route.js.nft.json +1 -1
  89. package/.next/server/app/api/update-maintenance/route.js +1 -1
  90. package/.next/server/app/api/update-maintenance/route.js.nft.json +1 -1
  91. package/.next/server/app/api/updates/apply/route.js +2 -2
  92. package/.next/server/app/api/updates/route.js +1 -1
  93. package/.next/server/app/api/upkeep/check/route.js +1 -1
  94. package/.next/server/app/api/upkeep/check/route.js.nft.json +1 -1
  95. package/.next/server/app/api/upkeep/morning/route.js +1 -1
  96. package/.next/server/app/api/upkeep/morning/route.js.nft.json +1 -1
  97. package/.next/server/app/api/upkeep/nightly/export/route.js +1 -1
  98. package/.next/server/app/api/upkeep/nightly/export/route.js.nft.json +1 -1
  99. package/.next/server/app/api/upkeep/nightly/result/route.js +1 -1
  100. package/.next/server/app/api/upkeep/nightly/result/route.js.nft.json +1 -1
  101. package/.next/server/app/api/upkeep/nightly/route.js +1 -1
  102. package/.next/server/app/api/upkeep/nightly/route.js.nft.json +1 -1
  103. package/.next/server/app/api/upkeep/route.js +1 -1
  104. package/.next/server/app/api/upkeep/route.js.nft.json +1 -1
  105. package/.next/server/app/api/worktrees/route.js +1 -1
  106. package/.next/server/app/api/worktrees/route.js.nft.json +1 -1
  107. package/.next/server/app/index.html +1 -1
  108. package/.next/server/app/index.rsc +5 -5
  109. package/.next/server/app/index.segments/__PAGE__.segment.rsc +3 -3
  110. package/.next/server/app/index.segments/_full.segment.rsc +5 -5
  111. package/.next/server/app/index.segments/_head.segment.rsc +1 -1
  112. package/.next/server/app/index.segments/_index.segment.rsc +3 -3
  113. package/.next/server/app/index.segments/_tree.segment.rsc +2 -2
  114. package/.next/server/app/page.js +3 -3
  115. package/.next/server/app/page_client-reference-manifest.js +1 -1
  116. package/.next/server/app/recover/page_client-reference-manifest.js +1 -1
  117. package/.next/server/app/recover.html +1 -1
  118. package/.next/server/app/recover.rsc +3 -3
  119. package/.next/server/app/recover.segments/_full.segment.rsc +3 -3
  120. package/.next/server/app/recover.segments/_head.segment.rsc +1 -1
  121. package/.next/server/app/recover.segments/_index.segment.rsc +3 -3
  122. package/.next/server/app/recover.segments/_tree.segment.rsc +2 -2
  123. package/.next/server/app/recover.segments/recover/__PAGE__.segment.rsc +1 -1
  124. package/.next/server/app/recover.segments/recover.segment.rsc +1 -1
  125. package/.next/server/app-paths-manifest.json +51 -51
  126. package/.next/server/chunks/2908.js +1 -0
  127. package/.next/server/chunks/3267.js +1 -1
  128. package/.next/server/chunks/5228.js +5 -5
  129. package/.next/server/chunks/7106.js +1 -0
  130. package/.next/server/chunks/8041.js +2 -2
  131. package/.next/server/chunks/8685.js +16 -16
  132. package/.next/server/chunks/9467.js +6 -6
  133. package/.next/server/instrumentation.js +1 -1
  134. package/.next/server/instrumentation.js.nft.json +1 -1
  135. package/.next/server/middleware-build-manifest.js +1 -1
  136. package/.next/server/pages/404.html +1 -1
  137. package/.next/server/pages/500.html +1 -1
  138. package/.next/server/server-reference-manifest.json +1 -1
  139. package/.next/static/chunks/app/{layout-2e1f3361ad019c87.js → layout-ee5121c5bdcf8ed2.js} +1 -1
  140. package/.next/static/chunks/app/{page-a51b6d8b9800dc9b.js → page-850a3c23b950a55b.js} +3 -3
  141. package/.next/static/css/d8d2a25163838be6.css +1 -0
  142. package/.next/trace +118 -118
  143. package/.next/trace-build +1 -1
  144. package/Tools/CUELO_Setup/files/native-runtime-patch.js +1 -1
  145. package/Tools/OMP_Global_Config/agent/cuelo-plugins/goal-lane/index.ts +106 -61
  146. package/Tools/OMP_Global_Config/agent/cuelo-plugins/goal-lane/plugin.json +4 -0
  147. package/Tools/OMP_Global_Config/agent/cuelo-plugins/screen-fast-path/index.ts +28 -3
  148. package/Tools/OMP_Global_Config/agent/cuelo-plugins/screen-fast-path/plugin.json +3 -1
  149. package/Tools/OMP_Global_Config/agent/cuelo-plugins/todo-language/index.ts +49 -10
  150. package/Tools/OMP_Global_Config/agent/cuelo-plugins/todo-language/plugin.json +4 -0
  151. package/Tools/OMP_Global_Config/agent/extensions/edit-lessons.ts +35 -19
  152. package/Tools/OMP_Global_Config/agent/extensions/lib/finalize-checks.ts +139 -19
  153. package/Tools/OMP_Global_Config/agent/tools/git-finalizer/index.ts +68 -24
  154. package/bin/ci-local.mjs +1 -2
  155. package/package.json +1 -1
  156. package/.next/static/css/fe2e76f96aee275e.css +0 -1
  157. /package/.next/static/{D-td92MNj1e9bUxdQYele → Fv9DSUHJTmKsAWWcOTAUo}/_buildManifest.js +0 -0
  158. /package/.next/static/{D-td92MNj1e9bUxdQYele → Fv9DSUHJTmKsAWWcOTAUo}/_ssgManifest.js +0 -0
@@ -1,4 +1,4 @@
1
- (self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[8974],{1682:e=>{e.exports={root:"ProcessLogPanel_root__KhilQ"}},2498:e=>{e.exports={view:"MemoryTraceView_view__62Ck_",body:"MemoryTraceView_body__gELit",message:"MemoryTraceView_message__pDO_k",errorText:"MemoryTraceView_errorText__GkoKJ",sectionTitle:"MemoryTraceView_sectionTitle__lmuuo",sectionCount:"MemoryTraceView_sectionCount__9yRSn",requests:"MemoryTraceView_requests__scPBk",requestScroller:"MemoryTraceView_requestScroller__4ALfU",requestList:"MemoryTraceView_requestList__rQ4G0",requestRow:"MemoryTraceView_requestRow__LZd3A",requestIndex:"MemoryTraceView_requestIndex__TacwG",requestTime:"MemoryTraceView_requestTime__fJjQF",noticeChip:"MemoryTraceView_noticeChip__gz9AO",requestPreview:"MemoryTraceView_requestPreview__HwG7v",miniRail:"MemoryTraceView_miniRail__84C2v",flow:"MemoryTraceView_flow__UCgmI",titleText:"MemoryTraceView_titleText__38Tl7",flowPreview:"MemoryTraceView_flowPreview__HjgKe",rail:"MemoryTraceView_rail__HlWbE",station:"MemoryTraceView_station__ulNBH",stationButton:"MemoryTraceView_stationButton__BztyW",stationStep:"MemoryTraceView_stationStep__CgFYZ",stationCount:"MemoryTraceView_stationCount__2_rrN",stationLabel:"MemoryTraceView_stationLabel__QGYpC",stationNote:"MemoryTraceView_stationNote__Jc30I",detail:"MemoryTraceView_detail__Rnn_d",stageEmpty:"MemoryTraceView_stageEmpty__x0H_J",group:"MemoryTraceView_group__1SCqK",bucket:"MemoryTraceView_bucket__Vmuau",groupTitle:"MemoryTraceView_groupTitle__6Q1oM",groupCode:"MemoryTraceView_groupCode__qgzOG",query:"MemoryTraceView_query__DK87N",items:"MemoryTraceView_items__D8Wz8",item:"MemoryTraceView_item__wyulb",idList:"MemoryTraceView_idList__mQArH",path:"MemoryTraceView_path__97O3u",itemHead:"MemoryTraceView_itemHead__B0bQo",memoryId:"MemoryTraceView_memoryId__5KjoX",itemMeta:"MemoryTraceView_itemMeta__wbj6K",itemText:"MemoryTraceView_itemText__O92R_",graph:"MemoryTraceView_graph__RHbn9",graphHead:"MemoryTraceView_graphHead__sEDhc",scopeSwitch:"MemoryTraceView_scopeSwitch__3HBI2",legend:"MemoryTraceView_legend__52_dq",legendMark:"MemoryTraceView_legendMark__hS7sK",legendTitle:"MemoryTraceView_legendTitle__z_lgW",legendMemory:"MemoryTraceView_legendMemory__mkYqP",graphCaption:"MemoryTraceView_graphCaption__ot7gW",captionKind:"MemoryTraceView_captionKind__e1fLD",graphFrame:"MemoryTraceView_graphFrame__SgiqG",graphSvg:"MemoryTraceView_graphSvg___JeWV",columnHeads:"MemoryTraceView_columnHeads__drsYb",edges:"MemoryTraceView_edges__4zMSL",node:"MemoryTraceView_node__ymwrL",hit:"MemoryTraceView_hit__HS6HS",mark:"MemoryTraceView_mark__WxCZl",arrow:"MemoryTraceView_arrow__oz9U4",nodeText:"MemoryTraceView_nodeText__Tp4ud",ring:"MemoryTraceView_ring___LM5n"}},2730:(e,t,n)=>{"use strict";function r(e,t,n,s={}){let a=n[e]?.[t]??n.en?.[t];return void 0===a?t:function(e,t={}){return e.replace(/\{([\w.-]+)\}/g,(e,n)=>{let r=t[n];return void 0===r?e:String(r)})}(a,s)}function s(e,t,n=new Date){let r=(e instanceof Date?e:new Date(e)).getTime()-n.getTime(),a=Math.abs(r),[i,l]=a<6e4?["second",1e3]:a<36e5?["minute",6e4]:a<864e5?["hour",36e5]:["day",864e5],o=Math.round(r/l);return new Intl.RelativeTimeFormat(t,{numeric:"always"}).format(o,i)}n.d(t,{fw:()=>s,u0:()=>r})},4378:(e,t,n)=>{"use strict";n.d(t,{AppShell:()=>jh});var r=n(95155),s=n(12115),a=n(47650),i=n(73321),l=n(16871),o=n(66919),c=n(81886);let d=["chat","process","subagents","files","resource","sidechat","efficiency","plugins","memory","browser"];Object.freeze({rail:60,transcript:560,composer:384,navigator:240,deck:372});let u=Object.freeze({navigator:860,deck:1232}),h=Object.freeze({activeView:"chat",transientLayer:null,deckExpanded:!1}),p=Object.fromEntries(d.map(e=>[e,!0]));function m(e){return"string"==typeof e&&!0===p[e]?e:h.activeView}function f(e,t){switch(t.type){case"select-view":{let n,r=m(t.view);return{activeView:r,transientLayer:null,deckExpanded:(n=!0===e.deckExpanded,"chat"!==r&&n)}}case"open-layer":{let n,r=m(e.activeView);return{activeView:r,transientLayer:t.layer,deckExpanded:(n=!0===e.deckExpanded,"chat"!==r&&n)}}case"toggle-layer":{let n,r=m(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=m(e.activeView);return{activeView:n,transientLayer:null,deckExpanded:(t=!0===e.deckExpanded,"chat"!==n&&t)}}case"set-deck-expanded":{let n,r=m(e.activeView);return{activeView:r,transientLayer:e.transientLayer,deckExpanded:(n=t.expanded,"chat"!==r&&n)}}}}function g(e){let t=Number.isFinite(e)?Math.max(0,e):0;return{availableWidth:t,navigator:t>=u.navigator?"pinned":"drawer",deck:t>=u.deck?"pinned":"view-stack"}}let x=null,v=!1,y=-1/0;function b(e,t=Date.now()){v=e,e||(y=t)}let w=["projects","priority"],k="omp-web:navigator-mode",j="omp-prio-on",S=["omp-relay-session-","omp-cwd-","ompscope_"],C="omp-web:session-opened-at";function N(e,t){if(e)try{let t=JSON.parse(e);if(t&&"object"==typeof t&&"number"==typeof t.since&&Number.isFinite(t.since)){let e={};if(t.opened&&"object"==typeof t.opened)for(let[n,r]of Object.entries(t.opened))"number"==typeof r&&Number.isFinite(r)&&(e[n]=r);return{since:t.since,opened:e}}}catch{}return{since:t,opened:{}}}function T(e,t){let n=null;for(let[r,s]of Object.entries(t.opened))(e.opened[r]??-1/0)>=s||((n??={...e.opened})[r]=s);return!n&&t.since>=e.since?e:{since:Math.min(e.since,t.since),opened:n??e.opened}}function I(e){let t=Date.parse(e.conversationModified??e.modified);return Number.isFinite(t)?t:null}function M(e,t,n){let r=Math.max(n,I(t)??0);return(e.opened[t.id]??-1/0)>=r?e:{since:e.since,opened:{...e.opened,[t.id]:r}}}let E=new Set;function $(e,t){let n=null;for(let r of t)Object.hasOwn(e.opened,r)&&(n??={...e.opened},delete n[r]);return n?{since:e.since,opened:n}:e}function R(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 L(e){let t=new Map;for(let n of e){let e=n.projectRoot??n.cwd;if(!e)continue;let r=R(e),s=t.get(r);(!s||n.modified>s.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 P(e,t){let n=new Map;for(let e of t)"number"==typeof e.order&&Number.isFinite(e.order)&&n.set(R(e.key),e.order);let r=[...e],s=new Set(e.map(R));for(let e of t){let t=R(e.key);!t||s.has(t)||(r.push(e.path??e.key),s.add(t))}return r.map((e,t)=>({project:e,defaultIndex:t,order:n.get(R(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 A=/^<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(A);if(!t)return null;let[,n,,,r]=t;return r?`/skill:${n} ${r}`:`/skill:${n}`}var F=n(84183);let O=`(max-width: ${u.navigator-1}px)`;function z(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 D=z("(max-width: 640px)"),W=z(O);function H(){return!1}function U(){return(0,s.useSyncExternalStore)(D.subscribe,D.getSnapshot,H)}var B=n(13004),q=n.n(B);async function V(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 K(){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 J(){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 G({onCancel:e,onSelect:t,busy:n=!1,error:i}){let{t:l}=(0,F.s)(),[o,c]=(0,s.useState)(null),[d,u]=(0,s.useState)(""),[h,p]=(0,s.useState)(null),[m,f]=(0,s.useState)(!1),[g,x]=(0,s.useState)(""),[v,y]=(0,s.useState)([]),[b,w]=(0,s.useState)(null),[k,j]=(0,s.useState)(null),[S,C]=(0,s.useState)(!0),N=(0,s.useCallback)(async e=>{C(!0),j(null);try{let t=await V(e),n=t.path??e??"/";u(n),p(t.parentPath??null),f(!0===t.upToDrives),x(n),y(t.directories??[]),w(t.drives??null)}catch(e){j(e instanceof Error?e.message:String(e))}finally{C(!1)}},[]);(0,s.useEffect)(()=>{c(document.body),N()},[N]);let T=g.trim()!==d,I=!!d&&!T&&!n,M=!!h||m||/^[a-zA-Z]:[\\/]?$/.test(d);return o?(0,a.createPortal)((0,r.jsx)("div",{className:"directory-picker-backdrop",role:"dialog","aria-modal":"true","aria-label":l("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:"var(--scrim)"},children:(0,r.jsxs)("div",{className:`directory-picker-panel ${q().sheet}`,style:{width:520,maxWidth:"calc(100vw - 16px)",height:"min(620px, calc(100dvh - 16px))",maxHeight:"calc(100dvh - 16px)",display:"flex",flexDirection:"column",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",flexShrink:0,padding:"12px 18px"},children:[(0,r.jsx)("div",{style:{minWidth:0,flex:1},children:(0,r.jsx)("div",{style:{color:"var(--text)",fontWeight:700,fontSize:15},children:l("directoryPicker.selectDirectory")})}),(0,r.jsx)("button",{type:"button",onClick:e,disabled:n,title:l("i18n.close"),"aria-label":l("i18n.close"),className:q().btnQuiet,style:{fontSize:20,lineHeight:1},children:"\xd7"})]}),(0,r.jsxs)("form",{onSubmit:e=>{e.preventDefault();let t=g.trim();t&&N(t)},style:{display:"flex",alignItems:"center",gap:8,flexShrink:0,padding:"10px 14px"},children:[(0,r.jsx)("button",{className:`directory-picker-back ${q().btn}`,type:"button",onClick:()=>void N(h??void 0),disabled:S||!M,title:l("directoryPicker.goToParent"),"aria-label":l("directoryPicker.goToParent"),style:{width:36,height:36,padding:0,flexShrink:0,cursor:M?"pointer":"default"},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"},children:l("directoryPicker.directoryPath")}),(0,r.jsx)("input",{className:`directory-picker-path ${q().field}`,id:"directory-path",type:"text",value:g,placeholder:"/path/to/project or ~/project",autoFocus:!0,autoComplete:"off",spellCheck:!1,onChange:e=>{x(e.target.value),j(null)},style:{minWidth:0,flex:1,height:36,fontFamily:"var(--font-mono)"}}),(0,r.jsx)("button",{className:`directory-picker-action ${q().btn}`,type:"submit",disabled:S||!g.trim(),title:l("directoryPicker.goToDirectory"),style:{minWidth:58,height:36},children:l("directoryPicker.go")})]}),(0,r.jsxs)("div",{className:"directory-picker-list",style:{flex:1,minHeight:0,overflow:"auto",padding:"8px 10px"},children:[S?(0,r.jsx)("div",{style:{padding:8,color:"var(--text-dim)",fontSize:11},children:l("directoryPicker.loadingDirectories")}):null!==b?(0,r.jsx)(r.Fragment,{children:b.length>0?b.map(e=>(0,r.jsxs)("button",{className:`directory-picker-entry ${q().navRow}`,type:"button",onClick:()=>void N(e.path),title:e.path,style:{minHeight:34,gap:7,padding:"6px 8px",color:"var(--text-muted)",fontFamily:"var(--font-mono)",fontSize:11},children:[(0,r.jsx)(J,{}),(0,r.jsx)("span",{children:e.name})]},e.path)):(0,r.jsx)("div",{style:{padding:8,color:"var(--text-dim)",fontSize:11},children:l("directoryPicker.noDrives")})}):v.length>0?v.map(e=>(0,r.jsxs)("button",{className:`directory-picker-entry ${q().navRow}`,type:"button",onClick:()=>void N(e.path),title:e.path,style:{minHeight:30,gap:7,padding:"5px 8px",color:"var(--text-muted)",fontFamily:"var(--font-mono)",fontSize:11},children:[(0,r.jsx)(K,{}),(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:l("directoryPicker.noSubdirectories")}),(k||i)&&(0,r.jsx)("div",{style:{padding:"8px",color:"var(--danger)",fontSize:11},children:k??i})]}),(0,r.jsxs)("div",{className:"directory-picker-footer",style:{display:"flex",justifyContent:"flex-end",alignItems:"center",gap:10,flexShrink:0,padding:"10px 18px"},children:[(0,r.jsx)("button",{className:`directory-picker-action ${q().btn}`,type:"button",onClick:e,disabled:n,style:{padding:"6px 14px",fontSize:13},children:l("i18n.cancel")}),(0,r.jsx)("button",{className:`directory-picker-action ${q().btnPrimary}`,type:"button",onClick:()=>t(d),disabled:!I,title:l(T?"directoryPicker.openBeforeSelecting":"directoryPicker.selectCurrentDirectory"),style:{padding:"6px 16px",fontSize:13},children:l(n?"i18n.checking":"directoryPicker.selectThisFolder")})]})]})}),o):null}var Y=n(21443),Z=n.n(Y);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 X({onCancel:e,onSelect:t,busy:n=!1,error:i}){let{t:l}=(0,F.s)(),o=(0,s.useRef)(null),[c,d]=(0,s.useState)(!1),[u,h]=(0,s.useState)(!1),[p,m]=(0,s.useState)(null),[f,g]=(0,s.useState)([]),[x,v]=(0,s.useState)(""),[y,b]=(0,s.useState)(""),[w,k]=(0,s.useState)(!0),[j,S]=(0,s.useState)(!1),[C,N]=(0,s.useState)(!1),[T,I]=(0,s.useState)(null),[M,E]=(0,s.useState)(!1),[$,R]=(0,s.useState)(50),L=p?.device?.state==="pending",P=n||C,A=(0,s.useCallback)(async()=>{k(!0),I(null);try{let e=await Q("/api/github/projects");m(e),e.connected&&g((await Q("/api/github/projects?view=repositories")).repositories)}catch(e){I(e instanceof Error?e.message:String(e))}finally{k(!1)}},[]);async function _(){S(!0),I(null);try{let{device:e}=await Q("/api/github/projects",{action:"login"});m({connected:!1,login:null,device:e})}catch(e){I(e instanceof Error?e.message:String(e))}finally{S(!1)}}async function O(e){if(e.preventDefault(),y.trim()&&!P){N(!0),I(null);try{let{cwd:e}=await Q("/api/github/projects",{action:"open",repository:y});t(e)}catch(e){I(e instanceof Error?e.message:String(e))}finally{N(!1)}}}if((0,s.useEffect)(()=>{d(!0),A()},[A]),(0,s.useEffect)(()=>{if(!c||u)return;let e=o.current;return e?.showModal(),()=>e?.close()},[c,u]),(0,s.useEffect)(()=>{let e;if(!L||u)return;let t=!1,n=async()=>{try{let e=await Q("/api/github/projects");if(t)return;if(m(e),e.connected)return void await A();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,u,A]),!c)return null;if(u)return(0,r.jsx)(G,{onCancel:()=>h(!1),onSelect:t,busy:n,error:i});let z=f.filter(e=>`${e.fullName} ${e.description??""}`.toLowerCase().includes(x.toLowerCase())),D=T??i??p?.device?.error;return(0,a.createPortal)((0,r.jsx)("dialog",{ref:o,className:Z().dialog,"aria-labelledby":"cloud-project-title",onCancel:t=>{t.preventDefault(),P||e()},children:(0,r.jsxs)("form",{onSubmit:O,className:Z().form,children:[(0,r.jsxs)("header",{className:Z().header,children:[(0,r.jsx)("h2",{id:"cloud-project-title",children:l("cloudProjects.title")}),(0,r.jsx)("p",{children:l("cloudProjects.description")})]}),(0,r.jsxs)("div",{className:Z().sources,children:[(0,r.jsx)("span",{className:Z().activeSource,children:l("cloudProjects.github")}),(0,r.jsx)("button",{type:"button",onClick:()=>h(!0),disabled:P,children:l("cloudProjects.serverFolder")})]}),(0,r.jsxs)("div",{className:Z().body,children:[(0,r.jsxs)("section",{className:Z().account,"aria-label":l("cloudProjects.account"),children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("strong",{children:p?.connected?p.login:l("cloudProjects.connectTitle")}),(0,r.jsx)("p",{children:p?.connected?l("cloudProjects.connected"):l("cloudProjects.connectHelp")})]}),p?.connected?(0,r.jsx)("button",{type:"button",className:Z().secondary,onClick:()=>void A(),disabled:w||P,children:l("cloudProjects.refresh")}):(0,r.jsx)("button",{type:"button",className:Z().secondary,onClick:()=>void _(),disabled:w||j||L||P,children:j||L?l("cloudProjects.waiting"):l("cloudProjects.connect")})]}),L&&(0,r.jsxs)("div",{className:Z().login,role:"status",children:[(0,r.jsx)("p",{children:l("cloudProjects.deviceHelp")}),p.device?.code?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("div",{className:Z().codeRow,children:[(0,r.jsx)("code",{children:p.device.code}),(0,r.jsx)("button",{type:"button",className:Z().secondary,onClick:()=>{navigator.clipboard.writeText(p.device.code).then(()=>E(!0)).catch(()=>I(l("cloudProjects.copyFailure")))},children:M?l("cloudProjects.copied"):l("cloudProjects.copyCode")})]}),(0,r.jsx)("a",{href:"https://github.com/login/device",target:"_blank",rel:"noreferrer",className:Z().loginLink,children:l("cloudProjects.openLogin")}),(0,r.jsx)("small",{children:l("cloudProjects.permissionHelp")})]}):(0,r.jsx)("p",{children:l("cloudProjects.preparingCode")})]}),p?.connected&&(0,r.jsxs)("section",{className:Z().repositories,"aria-label":l("cloudProjects.repositories"),children:[(0,r.jsx)("label",{htmlFor:"cloud-repo-search",children:l("cloudProjects.search")}),(0,r.jsx)("input",{id:"cloud-repo-search",value:x,onChange:e=>{v(e.target.value),R(50)},placeholder:l("cloudProjects.searchPlaceholder"),type:"search",disabled:P}),w?(0,r.jsx)("p",{role:"status",children:l("cloudProjects.loading")}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("ul",{className:Z().list,children:z.slice(0,$).map(e=>(0,r.jsx)("li",{children:(0,r.jsxs)("button",{type:"button",className:Z().repo,"aria-pressed":y===e.fullName,disabled:P,onClick:()=>b(e.fullName),children:[(0,r.jsxs)("span",{className:Z().repoHeading,children:[(0,r.jsx)("strong",{children:e.fullName}),(0,r.jsx)("small",{children:e.private?l("cloudProjects.private"):l("cloudProjects.public")})]}),e.description&&(0,r.jsx)("span",{className:Z().repoDescription,children:e.description})]})},e.fullName))}),!z.length&&(0,r.jsx)("p",{children:l("cloudProjects.empty")}),z.length>$&&(0,r.jsx)("button",{type:"button",className:Z().secondary,onClick:()=>R(e=>e+50),children:l("cloudProjects.more")})]})]}),(0,r.jsxs)("div",{className:Z().repositoryInput,children:[(0,r.jsx)("label",{htmlFor:"cloud-repository",children:l("cloudProjects.urlLabel")}),(0,r.jsx)("input",{id:"cloud-repository",value:y,onChange:e=>b(e.target.value),placeholder:"owner/repository",autoComplete:"off",spellCheck:!1,disabled:P,"aria-describedby":"cloud-repo-help"}),(0,r.jsx)("small",{id:"cloud-repo-help",children:l("cloudProjects.publicHelp")})]}),D&&(0,r.jsxs)("div",{className:Z().error,role:"alert",children:[(0,r.jsx)("strong",{children:l("cloudProjects.error")}),(0,r.jsx)("p",{children:D}),(0,r.jsx)("button",{type:"button",className:Z().secondary,onClick:()=>void A(),disabled:P,children:l("cloudProjects.refresh")})]}),C&&(0,r.jsx)("p",{role:"status",className:Z().progress,children:l("cloudProjects.openingHelp")})]}),(0,r.jsxs)("footer",{className:Z().footer,children:[(0,r.jsx)("button",{type:"button",className:Z().secondary,onClick:e,disabled:P,children:l("i18n.cancel")}),(0,r.jsx)("button",{type:"submit",className:Z().primary,disabled:P||!y.trim(),children:P?l("cloudProjects.opening"):l("cloudProjects.open")})]})]})}),document.body)}function ee({label:e="CUELO",markSize:t=22,gap:n=10,style:s,labelStyle:a}){return(0,r.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:n,minWidth:0,color:"var(--text)",...s},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 et=n(2730);let en={ko:{"translator.more":"더보기","translator.keyboard":"글자로 입력","translator.keyboardClose":"글자 입력 닫기","translator.volumeHint":"소리가 안 나면 폰의 미디어 음량을 올려 주세요.","translator.source":"입력 언어","translator.swapDirection":"방향 바꾸기","translator.typeLabel":"번역할 문장","translator.typePlaceholder":"여행 중 전할 말을 입력하세요.","translator.typeSubmit":"번역","translator.typePending":"번역 중…","translator.typeError":"번역하지 못했어요. 다시 시도해 주세요.","translator.typeAuth":"Codex 로그인 상태를 확인해 주세요.","translator.assistMeaning":"속뜻과 전달 확인","translator.assistMeaningHint":"대화 속 숨은 뜻과 타자 통역의 전달 내용을 확인합니다.","translator.assistNuance":"속뜻","translator.assistWarning":"전달 확인","translator.assistBackTranslation":"다시 옮기면","translator.assistNumberWarning":"원문과 통역의 숫자가 다릅니다. 확인해 주세요.","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":"통역 기록","translator.mood":"분위기","translator.mood.casual":"편하게","translator.mood.polite":"정중하게","translator.mood.formal":"격식 있게","translator.mood.haggling":"흥정","translator.mood.urgent":"긴급","translator.gender":"내 성별","translator.gender.male":"남성","translator.gender.female":"여성","translator.age":"내 나이대","translator.age.20s":"20대","translator.age.30s":"30대","translator.age.40s":"40대","translator.age.50s":"50대","translator.age.60s":"60대 이상","translator.partnerGender":"상대 성별","translator.partnerAge":"상대 나이","translator.partnerAge.child":"아이","translator.partnerAge.younger":"나보다 어리거나 비슷","translator.partnerAge.older":"나보다 위","translator.partnerAge.parent":"부모님 또래","translator.partnerAge.grandparent":"조부모님 또래","translator.notSet":"선택 안 함","translator.face":"마주보기","translator.faceHint":"상대 쪽 자막을 뒤집어 마주 앉은 사람이 읽게 합니다","translator.reconnecting":"다시 연결 중…","translator.idleStopped":"한동안 대화가 없어 통역을 멈췄습니다. 다시 시작하면 앞 대화에 이어집니다.","translator.generationSkipped":"방금 말은 통역하지 못하고 넘어갔습니다. 이어서 말씀하시면 계속 통역합니다.","translator.setup":"언어\xb7상황 설정","translator.sizeDown":"글자 작게","translator.sizeUp":"글자 크게","translator.faceExit":"마주보기 끄기","translator.translating":"옮기는 중…","translator.errorStatus":"통역이 멈췄습니다","translator.translation":"통역","translator.unknownLanguage":"언어 모름","translator.jumpLatest":"최근 말로","translator.voice":"통역 음성 듣기","translator.voiceHint":"끄면 통역을 글로만 보여 줍니다. 스피커가 조용하니 마이크를 막지 않아 통역 중에 끼어든 말도 들립니다.","translator.echoGuard":"통역 음성이 나올 때 마이크 끄기","translator.echoGuardHint":"스피커로 나온 통역이 다시 통역되지 않게 합니다. 그동안 상대가 한 말은 들리지 않으니 이어폰을 쓰면 꺼 두세요.","translator.naturalVoice":"자연스러운 목소리로 읽기 (ElevenLabs)","translator.naturalVoiceHint":"통역 음성과 들려주기를 ElevenLabs 목소리로 읽습니다. 크레딧을 쓰고, 안 되면 폰 기본 목소리로 읽습니다.","translator.naturalVoiceButtonHint":"들려주기 버튼만 ElevenLabs 목소리로 읽고, 이 엔진의 통역 음성은 그대로입니다. 안 되면 폰 기본 목소리로 읽습니다.","translator.noiseSuppression":"AI 소음 제거","translator.fastDrafts":"빠른 초안 자막","translator.fastDraftsHint":"전용 번역 모델이 초안 자막을 먼저 띄우고 Codex가 곧 바로잡습니다. 켜 둔 동안 추가 요금이 들 수 있습니다.","translator.noiseSuppressionHint":"시끄러운 곳에서 마이크 소음을 줄여 통역이 말을 더 잘 알아듣게 합니다. 목소리가 뭉개지면 꺼 두세요.","translator.cardTitle":"크게 보여 주기","translator.cardClose":"닫기","translator.speak":"들려주기","translator.speakStop":"그만 읽기","translator.speakFailed":"읽어 주는 소리를 재생하지 못했어요. 다시 시도해 주세요.","translator.share":"대화 공유","translator.shareTitle":"CUELO 통역 기록","translator.shareCopied":"대화를 복사했어요. 붙여 넣어 보내세요.","translator.shareFailed":"대화를 복사하지 못했어요.","translator.phrases":"자주 쓰는 문장","translator.phrasesClose":"자주 쓰는 문장 닫기","translator.phrases.food":"음식과 알레르기","translator.phrases.restroom":"화장실","translator.phrases.payment":"계산","translator.phrases.directions":"길 묻기","translator.phrases.emergency":"응급","translator.phrasesMine":"내 문장","translator.phrasesTranslateAll":"모두 미리 번역","translator.phrasesRemaining":"아직 번역하지 않은 문장 {count}개","translator.phrasesAllCached":"모두 번역해 뒀어요. 데이터가 끊겨도 쓸 수 있어요.","translator.phrasesNoBuiltIn":"기본 문장은 내 언어가 한국어나 영어일 때 보여요. 아래에 직접 더할 수 있어요.","translator.phraseNotCached":"아직 번역 전","translator.phraseFailed":"번역하지 못했어요. 눌러서 다시 시도","translator.phraseAddLabel":"문장 더하기","translator.phraseAddPlaceholder":"자주 하는 말을 적어 두세요","translator.phraseAdd":"추가","translator.phraseDelete":"지우기: {text}","translator.scan":"메뉴판과 간판 사진","translator.scan.title":"메뉴판과 간판 해설","translator.scan.close":"닫기","translator.scan.takePhoto":"사진 찍기","translator.scan.pickAlbum":"앨범에서 고르기","translator.scan.avoidLabel":"내가 못 먹는 것","translator.scan.avoidPlaceholder":"예: 새우, 땅콩","translator.scan.avoidHint":"적어 두면 해당 메뉴에 경고를 표시해요. 이 기기에만 저장돼요.","translator.scan.pickHint":"메뉴판이나 간판을 찍으면 항목별로 번역하고 설명해요.","translator.scan.loading":"사진을 읽는 중이에요","translator.scan.error":"사진을 읽지 못했어요.","translator.scan.authError":"Codex 로그인이 필요해요.","translator.scan.retry":"다시 시도","translator.scan.empty":"읽을 수 있는 글자가 없어요.","translator.scan.show":"보여주기","translator.scan.pick":"합계에 넣기","translator.scan.total":"고른 {count}개 합계","translator.scan.missing":"가격이 없는 {count}개는 빠졌어요","translator.scan.avoidChanged":"못 먹는 것을 바꿨어요. 이 사진을 다시 풀 수 있어요.","translator.scan.rescan":"다시 보기","translator.scan.warning":"주의"},en:{"translator.more":"More","translator.keyboard":"Type a message","translator.keyboardClose":"Close text input","translator.volumeHint":"If you hear nothing, turn up your phone's media volume.","translator.source":"Input language","translator.swapDirection":"Swap direction","translator.typeLabel":"Text to translate","translator.typePlaceholder":"Type what you want to say.","translator.typeSubmit":"Translate","translator.typePending":"Translating…","translator.typeError":"Translation failed. Try again.","translator.typeAuth":"Check your Codex sign-in.","translator.assistMeaning":"Implied meaning and delivery check","translator.assistMeaningHint":"Shows implied meaning in conversation and checks how typed interpretation comes across.","translator.assistNuance":"Implied meaning","translator.assistWarning":"Delivery check","translator.assistBackTranslation":"Translated back","translator.assistNumberWarning":"Numbers in the original and interpretation differ. Please check.","translator.tab":"Interpret","translator.title":"Interpreter","translator.back":"Back to chat","translator.panelHint":"Start interpreting and Codex Live on your ChatGPT account speaks each person's words in the other's language right away. It bypasses work sessions and harness rules. The voice conversation stays on this phone only; Clear removes it.","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","translator.mood":"Mood","translator.mood.casual":"Casual","translator.mood.polite":"Polite","translator.mood.formal":"Formal","translator.mood.haggling":"Haggling","translator.mood.urgent":"Urgent","translator.gender":"My gender","translator.gender.male":"Male","translator.gender.female":"Female","translator.age":"My age","translator.age.20s":"20s","translator.age.30s":"30s","translator.age.40s":"40s","translator.age.50s":"50s","translator.age.60s":"60+","translator.partnerGender":"Their gender","translator.partnerAge":"Their age","translator.partnerAge.child":"Child","translator.partnerAge.younger":"Younger or same age","translator.partnerAge.older":"Older than me","translator.partnerAge.parent":"My parents' age","translator.partnerAge.grandparent":"My grandparents' age","translator.notSet":"Not set","translator.face":"Face to face","translator.faceHint":"Flip the other side's captions so the person across from you can read them","translator.reconnecting":"Reconnecting…","translator.idleStopped":"Interpreting stopped after a long silence. Start again to continue the conversation.","translator.generationSkipped":"That last line couldn't be interpreted and was skipped. Keep talking; interpreting continues.","translator.setup":"Languages and setting","translator.sizeDown":"Smaller text","translator.sizeUp":"Larger text","translator.faceExit":"Leave face to face","translator.translating":"Interpreting…","translator.errorStatus":"Interpreting stopped","translator.translation":"Interpretation","translator.unknownLanguage":"Language unknown","translator.jumpLatest":"Jump to latest","translator.voice":"Play the interpretation aloud","translator.voiceHint":"Off, the interpretation is shown as text only. With the speaker silent the mic stays open, so words spoken over an interpretation are heard too.","translator.echoGuard":"Mute the mic while the interpretation plays","translator.echoGuardHint":"Keeps the speaker's interpretation from being interpreted again. Words spoken meanwhile are not heard, so turn it off with earphones.","translator.naturalVoice":"Read with a natural voice (ElevenLabs)","translator.naturalVoiceHint":"Reads the interpretation and Read aloud with an ElevenLabs voice. Uses credits; falls back to the phone voice.","translator.naturalVoiceButtonHint":"Only the Read aloud button uses the ElevenLabs voice; this engine's interpretation audio is unchanged. Falls back to the phone voice.","translator.noiseSuppression":"AI noise suppression","translator.fastDrafts":"Quick draft captions","translator.fastDraftsHint":"A dedicated translation model shows a quick draft first and Codex corrects it. Extra charges may apply while this is on.","translator.noiseSuppressionHint":"Cuts background noise from the mic in a loud place so the interpreter hears you better. Turn it off if your voice sounds muffled.","translator.cardTitle":"Show full screen","translator.cardClose":"Close","translator.speak":"Read aloud","translator.speakStop":"Stop reading","translator.speakFailed":"Couldn’t play the audio. Try again.","translator.share":"Share conversation","translator.shareTitle":"CUELO interpretation log","translator.shareCopied":"Conversation copied. Paste it to send.","translator.shareFailed":"Couldn't copy the conversation.","translator.phrases":"Saved phrases","translator.phrasesClose":"Close saved phrases","translator.phrases.food":"Food and allergies","translator.phrases.restroom":"Restroom","translator.phrases.payment":"Paying","translator.phrases.directions":"Directions","translator.phrases.emergency":"Emergency","translator.phrasesMine":"My phrases","translator.phrasesTranslateAll":"Translate all now","translator.phrasesRemaining":"{count} phrases not translated yet","translator.phrasesAllCached":"All phrases are translated and work offline.","translator.phrasesNoBuiltIn":"Built-in phrases appear when your language is Korean or English. You can add your own below.","translator.phraseNotCached":"Not translated yet","translator.phraseFailed":"Translation failed. Tap to retry","translator.phraseAddLabel":"Add a phrase","translator.phraseAddPlaceholder":"Type something you say often","translator.phraseAdd":"Add","translator.phraseDelete":"Delete: {text}","translator.scan":"Menu or sign photo","translator.scan.title":"Menu and sign help","translator.scan.close":"Close","translator.scan.takePhoto":"Take photo","translator.scan.pickAlbum":"Choose from album","translator.scan.avoidLabel":"Foods I avoid","translator.scan.avoidPlaceholder":"e.g. shrimp, peanuts","translator.scan.avoidHint":"Matching dishes get a warning. Saved on this device only.","translator.scan.pickHint":"Photograph a menu or sign to get each item translated and explained.","translator.scan.loading":"Reading the photo","translator.scan.error":"Could not read the photo.","translator.scan.authError":"Codex sign-in required.","translator.scan.retry":"Try again","translator.scan.empty":"No readable text found.","translator.scan.show":"Show","translator.scan.pick":"Add to total","translator.scan.total":"Total of {count} picked","translator.scan.missing":"{count} without a price left out","translator.scan.avoidChanged":"You changed what you avoid. This photo can be read again.","translator.scan.rescan":"Read again","translator.scan.warning":"Warning"}};function er(){let{locale:e}=(0,F.s)();return{tt:(0,s.useCallback)((t,n)=>(0,et.u0)(e,t,en,n),[e]),locale:e}}let es={en:{issueLabel:"GitHub issue (optional)",issuePlaceholder:"#123 or GitHub issue URL",issueStart:"Start issue session",issueBusy:"Starting…",fallbackBase:"Fetch failed; started from local {branch}"},ko:{issueLabel:"GitHub 이슈 (선택)",issuePlaceholder:"#123 또는 GitHub 이슈 URL",issueStart:"이슈 세션 시작",issueBusy:"시작 중…",fallbackBase:"가져오기 실패; 로컬 {branch}에서 시작됨"},zh:{issueLabel:"GitHub Issue(可选)",issuePlaceholder:"#123 或 GitHub Issue URL",issueStart:"开始 Issue 会话",issueBusy:"正在启动…",fallbackBase:"拉取失败;已从本地 {branch} 启动"}},ea={en:"The subdirectory {path} is not in this worktree; opened its root instead",ko:"이 워크트리에 하위 디렉터리 {path}이(가) 없어 루트 디렉터리를 대신 열었습니다",zh:"此工作树中不存在子目录 {path},已改为打开其根目录"};function ei(e,t){if(t)try{sessionStorage.setItem(`cuelo:worktree:${e}`,JSON.stringify(t))}catch{}}let el="application/x-cuelo-session",eo=(0,s.createContext)(null);function ec(){return(0,s.useContext)(eo)}let ed=(0,s.createContext)(null);function eu({label:e,x:t,y:n,items:i,onClose:l}){let o=(0,s.useRef)(null),[c,d]=(0,s.useState)({left:t,top:n});return(0,s.useLayoutEffect)(()=>{let e=o.current;if(!e)return;let r=e.getBoundingClientRect();d({left:Math.max(8,Math.min(t,window.innerWidth-r.width-8)),top:Math.max(8,Math.min(n,window.innerHeight-r.height-8))}),e.querySelector('button:not([aria-disabled="true"])')?.focus()},[t,n]),(0,s.useEffect)(()=>{let e=e=>{e.target instanceof Node&&o.current?.contains(e.target)||l()};return document.addEventListener("pointerdown",e,!0),window.addEventListener("blur",l),window.addEventListener("resize",l),()=>{document.removeEventListener("pointerdown",e,!0),window.removeEventListener("blur",l),window.removeEventListener("resize",l)}},[l]),(0,a.createPortal)((0,r.jsx)("div",{ref:o,className:"session-row-menu",role:"menu","aria-label":e,style:{left:c.left,top:c.top},onKeyDown:e=>{if("Escape"===e.key||"Tab"===e.key){e.preventDefault(),e.stopPropagation(),l();return}if("ArrowDown"!==e.key&&"ArrowUp"!==e.key)return;e.preventDefault();let t=[...o.current?.querySelectorAll('button:not([aria-disabled="true"])')??[]];if(0===t.length)return;let n=t.findIndex(e=>e===document.activeElement),r="ArrowDown"===e.key?1:-1;t[(n+r+t.length)%t.length]?.focus()},onClick:e=>e.stopPropagation(),onContextMenu:e=>e.preventDefault(),children:i.map(e=>(0,r.jsx)("button",{type:"button",role:"menuitem","aria-disabled":!!e.disabledReason||void 0,title:e.disabledReason??void 0,onClick:()=>{e.disabledReason||(l(),e.onSelect())},children:e.label},e.id))}),document.body)}let eh={folder:(0,r.jsx)("path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z"}),"list-ordered":(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("path",{d:"M10 12h11"}),(0,r.jsx)("path",{d:"M10 18h11"}),(0,r.jsx)("path",{d:"M10 6h11"}),(0,r.jsx)("path",{d:"M4 10h2"}),(0,r.jsx)("path",{d:"M4 6h1v4"}),(0,r.jsx)("path",{d:"M6 18H4c0-1 2-2 2-3s-1-1.5-2-1"})]}),languages:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("path",{d:"m5 8 6 6"}),(0,r.jsx)("path",{d:"m4 14 6-6 2-3"}),(0,r.jsx)("path",{d:"M2 5h12"}),(0,r.jsx)("path",{d:"M7 2h1"}),(0,r.jsx)("path",{d:"m22 22-5-10-5 10"}),(0,r.jsx)("path",{d:"M14 18h6"})]}),repeat:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("path",{d:"m17 2 4 4-4 4"}),(0,r.jsx)("path",{d:"M3 11v-1a4 4 0 0 1 4-4h14"}),(0,r.jsx)("path",{d:"m7 22-4-4 4-4"}),(0,r.jsx)("path",{d:"M21 13v1a4 4 0 0 1-4 4H3"})]}),activity:(0,r.jsx)("path",{d:"M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2"}),settings:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("path",{d:"M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z"}),(0,r.jsx)("circle",{cx:"12",cy:"12",r:"3"})]}),"panel-right":(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}),(0,r.jsx)("path",{d:"M15 3v18"})]}),"panel-left":(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}),(0,r.jsx)("path",{d:"M9 3v18"})]}),"columns-2":(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}),(0,r.jsx)("path",{d:"M12 3v18"})]}),globe:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"10"}),(0,r.jsx)("path",{d:"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20"}),(0,r.jsx)("path",{d:"M2 12h20"})]}),menu:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("line",{x1:"4",x2:"20",y1:"12",y2:"12"}),(0,r.jsx)("line",{x1:"4",x2:"20",y1:"6",y2:"6"}),(0,r.jsx)("line",{x1:"4",x2:"20",y1:"18",y2:"18"})]}),"chevron-right":(0,r.jsx)("path",{d:"m9 18 6-6-6-6"}),"chevron-up":(0,r.jsx)("path",{d:"m18 15-6-6-6 6"}),"chevron-down":(0,r.jsx)("path",{d:"m6 9 6 6 6-6"}),"circle-check":(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"10"}),(0,r.jsx)("path",{d:"m9 12 2 2 4-4"})]}),"circle-alert":(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"10"}),(0,r.jsx)("line",{x1:"12",x2:"12",y1:"8",y2:"12"}),(0,r.jsx)("line",{x1:"12",x2:"12.01",y1:"16",y2:"16"})]}),ellipsis:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"1"}),(0,r.jsx)("circle",{cx:"19",cy:"12",r:"1"}),(0,r.jsx)("circle",{cx:"5",cy:"12",r:"1"})]}),x:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("path",{d:"M18 6 6 18"}),(0,r.jsx)("path",{d:"m6 6 12 12"})]}),check:(0,r.jsx)("path",{d:"M20 6 9 17l-5-5"}),"message-square":(0,r.jsx)("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"}),"messages-square":(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("path",{d:"M14 9a2 2 0 0 1-2 2H6l-4 4V4a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2z"}),(0,r.jsx)("path",{d:"M18 9h2a2 2 0 0 1 2 2v11l-4-4h-6a2 2 0 0 1-2-2v-1"})]}),"list-tree":(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("path",{d:"M21 12h-8"}),(0,r.jsx)("path",{d:"M21 6H8"}),(0,r.jsx)("path",{d:"M21 18h-8"}),(0,r.jsx)("path",{d:"M3 6v4c0 1.1.9 2 2 2h3"}),(0,r.jsx)("path",{d:"M3 10v6c0 1.1.9 2 2 2h3"})]}),bot:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("path",{d:"M12 8V4H8"}),(0,r.jsx)("rect",{width:"16",height:"12",x:"4",y:"8",rx:"2"}),(0,r.jsx)("path",{d:"M2 14h2"}),(0,r.jsx)("path",{d:"M20 14h2"}),(0,r.jsx)("path",{d:"M15 13v2"}),(0,r.jsx)("path",{d:"M9 13v2"})]}),"file-text":(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z"}),(0,r.jsx)("path",{d:"M14 2v4a2 2 0 0 0 2 2h4"}),(0,r.jsx)("path",{d:"M10 9H8"}),(0,r.jsx)("path",{d:"M16 13H8"}),(0,r.jsx)("path",{d:"M16 17H8"})]}),users:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"}),(0,r.jsx)("circle",{cx:"9",cy:"7",r:"4"}),(0,r.jsx)("path",{d:"M22 21v-2a4 4 0 0 0-3-3.87"}),(0,r.jsx)("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]}),"user-round":(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("circle",{cx:"12",cy:"8",r:"5"}),(0,r.jsx)("path",{d:"M20 21a8 8 0 0 0-16 0"})]}),gauge:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("path",{d:"m12 14 4-4"}),(0,r.jsx)("path",{d:"M3.34 19a10 10 0 1 1 17.32 0"})]}),puzzle:(0,r.jsx)("path",{d:"M15.39 4.39a1 1 0 0 0 1.68-.474 2.5 2.5 0 1 1 3.014 3.015 1 1 0 0 0-.474 1.68l1.683 1.682a2.414 2.414 0 0 1 0 3.414L19.61 15.39a1 1 0 0 1-1.68-.474 2.5 2.5 0 1 0-3.014 3.015 1 1 0 0 1 .474 1.68l-1.683 1.682a2.414 2.414 0 0 1-3.414 0L8.61 19.61a1 1 0 0 0-1.68.474 2.5 2.5 0 1 1-3.014-3.015 1 1 0 0 0 .474-1.68l-1.683-1.682a2.414 2.414 0 0 1 0-3.414L4.39 8.61a1 1 0 0 1 1.68.474 2.5 2.5 0 1 0 3.014-3.015 1 1 0 0 1-.474-1.68l1.683-1.682a2.414 2.414 0 0 1 3.414 0z"}),brain:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("path",{d:"M12 5a3 3 0 1 0-5.997.125 4 4 0 0 0-2.526 5.77 4 4 0 0 0 .556 6.588A4 4 0 1 0 12 18Z"}),(0,r.jsx)("path",{d:"M12 5a3 3 0 1 1 5.997.125 4 4 0 0 1 2.526 5.77 4 4 0 0 1-.556 6.588A4 4 0 1 1 12 18Z"}),(0,r.jsx)("path",{d:"M15 13a4.5 4.5 0 0 1-3-4 4.5 4.5 0 0 1-3 4"}),(0,r.jsx)("path",{d:"M17.599 6.5a3 3 0 0 0 .399-1.375"}),(0,r.jsx)("path",{d:"M6.003 5.125A3 3 0 0 0 6.401 6.5"}),(0,r.jsx)("path",{d:"M3.477 10.896a4 4 0 0 1 .585-.396"}),(0,r.jsx)("path",{d:"M19.938 10.5a4 4 0 0 1 .585.396"}),(0,r.jsx)("path",{d:"M6 18a4 4 0 0 1-1.967-.516"}),(0,r.jsx)("path",{d:"M19.967 17.484A4 4 0 0 1 18 18"})]}),"chart-column":(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("path",{d:"M3 3v16a2 2 0 0 0 2 2h16"}),(0,r.jsx)("path",{d:"M18 17V9"}),(0,r.jsx)("path",{d:"M13 17V5"}),(0,r.jsx)("path",{d:"M8 17v-3"})]}),"maximize-2":(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("polyline",{points:"15 3 21 3 21 9"}),(0,r.jsx)("polyline",{points:"9 21 3 21 3 15"}),(0,r.jsx)("line",{x1:"21",x2:"14",y1:"3",y2:"10"}),(0,r.jsx)("line",{x1:"3",x2:"10",y1:"21",y2:"14"})]}),search:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("circle",{cx:"11",cy:"11",r:"8"}),(0,r.jsx)("path",{d:"m21 21-4.3-4.3"})]})};function ep({name:e,size:t=16}){return(0,r.jsx)("svg",{className:"workbench-icon",width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",focusable:"false",children:eh[e]})}function em({size:e=28}){return(0,r.jsx)("svg",{className:"workbench-mark",width:e,height:e,viewBox:"0 0 100 100","aria-hidden":"true",focusable:"false",children:(0,r.jsxs)("g",{transform:"translate(15 15) scale(0.7)",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)"})]})})}let ef="omp-web:unread-session-ids",eg="omp-web:pinned-session-ids",ex="omp-web:removed-projects";function ev(e,t){return{minHeight:t?44:30,padding:"3px 10px",border:0,borderRadius:"var(--radius-control)",background:"var(--bg-hover)",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 ey(e,t){return t&&e.startsWith(t)?"~"+e.slice(t.length):e}function eb({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 ew({open:e,children:t,style:n}){let[a,i]=(0,s.useState)(e),[l,o]=(0,s.useState)(e);return((0,s.useEffect)(()=>{let t,n;return e?(i(!0),o(!1),t=window.requestAnimationFrame(()=>{t=window.requestAnimationFrame(()=>o(!0))})):(o(!1),n=setTimeout(()=>i(!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 ek="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*";function ej(){let[e,t]=(0,s.useState)(!1),[n,a]=(0,s.useState)(!1),i=(0,s.useRef)(null),l=function(e,t){let[n,r]=(0,s.useState)(e),a=(0,s.useRef)(null),i=(0,s.useRef)(0);return(0,s.useEffect)(()=>{if(!t)return void r(e);i.current=0;let n=4*e.length,s=()=>{i.current+=1;let t=Math.floor(i.current/n*e.length);r(e.split("").map((e,n)=>" "===e?" ":n<t?e:ek[Math.floor(Math.random()*ek.length)]).join("")),i.current<n?a.current=requestAnimationFrame(s):r(e)};return a.current=requestAnimationFrame(s),()=>{a.current&&cancelAnimationFrame(a.current)}},[e,t]),n}(e?"0.10.355/19.1.1":"CUELO",n),o=(0,s.useCallback)(e=>{t(e),a(!0),setTimeout(()=>a(!1),(e?6:8)*4*(1e3/60)+100)},[]),c=(0,s.useCallback)(()=>{i.current&&clearTimeout(i.current);let t=!e;o(t),t&&(i.current=setTimeout(()=>o(!1),3e3))},[e,o]);return(0,s.useEffect)(()=>()=>{i.current&&clearTimeout(i.current)},[]),(0,r.jsx)("button",{className:"navigator-brand",onClick:c,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)(ee,{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 eC({selectedSessionId:e,optimisticSession:t,onSelectSession:n,onNewSession:a,initialSessionId:i,skipInitialProjectSelection:l,onInitialRestoreDone:o,refreshKey:c,onSessionDeleted:d,selectedCwd:u,onCwdChange:h,onBackgroundTaskDone:p,translatorPanel:m,translatorActive:f=!1,navigatorMode:g="projects",onActivityChange:x}){let v,{tt:y}=er(),{t:b,locale:w}=(0,F.s)(),k=U(),[j,A]=(0,s.useState)([]),_=(0,s.useMemo)(()=>t&&!j.some(e=>e.id===t.id)?[t,...j]:j,[j,t]),[O,z]=(0,s.useState)(!0),[D,W]=(0,s.useState)(null),[H,B]=(0,s.useState)(null),[q,V]=(0,s.useState)(""),[K,J]=(0,s.useState)(!1),[Y,Z]=(0,s.useState)(""),[Q,ee]=(0,s.useState)(()=>new Set),[et,en]=(0,s.useState)(()=>new Set),[el,eo]=(0,s.useState)(null),[ed,eu]=(0,s.useState)(null),[eh,ep]=(0,s.useState)({version:1,projects:[]}),[em,ek]=(0,s.useState)(!1),[eT,e$]=(0,s.useState)(!1),[eR,eL]=(0,s.useState)(!1),[eA,e_]=(0,s.useState)(null),[eF,eO]=(0,s.useState)(""),[ez,eD]=(0,s.useState)(!1),[eW,eH]=(0,s.useState)(null),[eU,eB]=(0,s.useState)(""),[eq,eV]=(0,s.useState)(!1),[eK,eJ]=(0,s.useState)(null),[eG,eY]=(0,s.useState)(!1),[eZ,eQ]=(0,s.useState)(null),[eX,e0]=(0,s.useState)(!1),[e1,e2]=(0,s.useState)(!1),[e4,e8]=(0,s.useState)(""),[e5,e6]=(0,s.useState)(null),[e3,e7]=(0,s.useState)(""),[e9,te]=(0,s.useState)(!1),[tt,tn]=(0,s.useState)(null),tr=(0,s.useRef)(null),[ts,ta]=(0,s.useState)(!1),[ti,tl]=(0,s.useState)(null),to=(0,s.useRef)(null),tc=(0,s.useRef)(null),td=(0,s.useRef)(null),tu=(0,s.useRef)(!1),th=(0,s.useRef)(!1),[tp,tm]=(0,s.useState)(!1),[tf,tg]=(0,s.useState)(()=>new Set),[tx,tv]=(0,s.useState)(()=>new Set),[ty,tb]=(0,s.useState)(()=>(function(){try{let e=window.localStorage.getItem(ef);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}})()),[tw,tk]=(0,s.useState)(()=>new Set),[tj,tS]=(0,s.useState)(null),[tC,tN]=(0,s.useState)(!1),tT=(0,s.useRef)(new Set),tI=(0,s.useRef)(!1),tM=(0,s.useRef)(null);(0,s.useEffect)(()=>{tk(function(){try{let e=window.localStorage.getItem(eg);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}}())},[]),(0,s.useEffect)(()=>{let e=null;try{e=window.localStorage.getItem(C)}catch{}tS(N(e,Date.now()));let t=e=>{if(e.key!==C||null===e.newValue)return;let t=N(e.newValue,Date.now());tS(e=>e?T(e,t):e)};return window.addEventListener("storage",t),()=>window.removeEventListener("storage",t)},[]);let tE=(0,s.useCallback)(async()=>{try{let e=await fetch("/api/projects",{cache:"no-store",signal:AbortSignal.timeout(5e3)});if(!e.ok)throw Error(`HTTP ${e.status}`);ep(await e.json())}catch{ep({version:1,projects:[]})}finally{ek(!0)}},[]);(0,s.useEffect)(()=>{tE()},[tE,c]),(0,s.useEffect)(()=>{let e=null;try{e=window.localStorage.getItem(ex)}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:R(e),path:e,hidden:!0})))}}catch{return}try{window.localStorage.removeItem(ex)}catch{}await tE()})()},[tE]);let t$=(0,s.useCallback)(async e=>{if(th.current)throw Error("Project update in progress");th.current=!0,eD(!0);try{await eS(e),await tE()}finally{th.current=!1,eD(!1)}},[tE]);(0,s.useEffect)(()=>{eA&&td.current?.select()},[eA]);let tR=(0,s.useCallback)(async(e=!1,t=!1)=>{try{e&&z(!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();A(r.sessions),tI.current||tg(new Set(r.runningSessionIds??[])),W(null),e||(tm(!0),tM.current&&clearTimeout(tM.current),tM.current=setTimeout(()=>tm(!1),2e3))}catch(e){W(String(e))}finally{e&&z(!1)}},[]),tL=(0,s.useCallback)(e=>{tb(t=>{if(!t.has(e))return t;let n=new Set(t);return n.delete(e),n}),tk(t=>{if(!t.has(e))return t;let n=new Set(t);return n.delete(e),n}),tS(t=>t&&$(t,[e])),d?.(e),tR()},[tR,d]),[tP,tA]=(0,s.useState)(null),[t_,tF]=(0,s.useState)(!1),[tO,tz]=(0,s.useState)(null),tD=(0,s.useCallback)(()=>{t_||(tA(null),tz(null))},[t_]),tW=(0,s.useCallback)(async e=>{tF(!0),tz(null);let t=[],n=[],r=[];for(let s of e)if(!s.transient)try{let e=await fetch(`/api/sessions/${encodeURIComponent(s.id)}?skipRunning=1`,{method:"DELETE"});if(409===e.status){n.push(s.id);continue}if(!e.ok)throw Error(`HTTP ${e.status}`);t.push(s.id)}catch{r.push(s.name?.trim()||s.id.slice(0,8))}if(n.length>0&&(tI.current=!0,tg(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(tb(n),tk(n),tS(e=>e&&$(e,t)),t))d?.(e)}(await tR(),tF(!1),r.length>0)?tz(b("sidebar.clearSessionsFailed",{count:r.length,names:r.join(", ")})):n.length>0||tA(null)},[tR,d,b]),[tH,tU]=(0,s.useState)(0),tB=(0,s.useCallback)(()=>{tU(e=>e+1),tR()},[tR]),tq=(0,s.useRef)(!1);(0,s.useEffect)(()=>{let e=!tq.current;tq.current=!0,tR(e,!e)},[tR,c]),(0,s.useEffect)(()=>{if("priority"!==g)return;let e=()=>{"visible"===document.visibilityState&&tR(!1,!0)};e();let t=window.setInterval(e,15e3);return()=>window.clearInterval(t)},[tR,g]),(0,s.useEffect)(()=>{x?.({running:tf.size,waiting:j.filter(e=>tx.has(e.id))})},[j,x,tf,tx]),(0,s.useEffect)(()=>{try{0===ty.size?window.localStorage.removeItem(ef):window.localStorage.setItem(ef,JSON.stringify([...ty]))}catch{}},[ty]),(0,s.useEffect)(()=>{try{0===tw.size?window.localStorage.removeItem(eg):window.localStorage.setItem(eg,JSON.stringify([...tw]))}catch{}},[tw]),(0,s.useEffect)(()=>{if(tj)try{var e,t,n;let r=window.localStorage;r.setItem(C,(e=r.getItem(C),t=Date.now(),JSON.stringify({since:(n=T(tj,N(e,t))).since,opened:n.opened})))}catch{}},[tj]);let tV=(0,s.useCallback)(e=>{tk(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]);(0,s.useEffect)(()=>{let e=!1,t=null,n=null,r=()=>{t&&clearTimeout(t),t=null},s=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;tI.current=!0,tg(new Set(r.runningSessionIds??[])),tv(new Set(r.waitingSessionIds??[]))}catch{}finally{n===a&&(n=null),r(),e||"visible"!==document.visibilityState||(t=setTimeout(()=>void s(),2500))}},a=()=>{"visible"===document.visibilityState?s():(r(),n?.abort(),n=null)};return s(),document.addEventListener("visibilitychange",a),()=>{e=!0,r(),n?.abort(),document.removeEventListener("visibilitychange",a)}},[]);let tK=ec()?.besideSessionId??null;(0,s.useEffect)(()=>{let t=tT.current,n=[...t].filter(t=>!tf.has(t)&&t!==e&&t!==tK),r=[...tf].filter(e=>!t.has(e));(n.length>0||r.length>0)&&tb(e=>{let t=new Set(e);return tf.forEach(e=>t.delete(e)),n.forEach(e=>t.add(e)),t});let s=r.some(e=>!j.some(t=>t.id===e));(n.length>0||s)&&tR(!1,!0),n.length>0&&p?.(),tT.current=tf},[tf,e,tK,j,tR,p]),(0,s.useEffect)(()=>{let t=[e,tK].filter(e=>null!==e);0!==t.length&&tb(e=>{if(!t.some(t=>e.has(t)))return e;let n=new Set(e);return t.forEach(e=>n.delete(e)),n})},[e,tK]);let tJ=e?_.find(t=>t.id===e):void 0,tG=tJ?.conversationModified??tJ?.modified,tY=null!==tj;(0,s.useEffect)(()=>{e&&void 0!==tG&&tY&&tS(t=>t&&M(t,{id:e,modified:tG},Date.now()))},[e,tG,tY]),(0,s.useEffect)(()=>{fetch("/api/home").then(e=>e.json()).then(e=>{e.home&&V(e.home),J(!0===e.cloudProjects)}).catch(()=>{})},[]);let tZ=(0,s.useRef)(!1),tQ=(0,s.useCallback)(e=>{if(!e)return null;if(eZ&&eZ.forCwd===e||eZ?.worktrees.some(t=>t.path===e))return eZ.projectRoot;let t=_.find(t=>t.cwd===e);return t?.projectRoot??e},[eZ,_]),tX=(0,s.useRef)(null);(0,s.useEffect)(()=>{tX.current!==H&&(tX.current=H,h?.(H,tQ(H)))},[H,h,tQ]);let t0=(0,s.useRef)(null);(0,s.useEffect)(()=>{u&&u!==t0.current&&(t0.current=u,B(u))},[u]);let[t1,t2]=(0,s.useState)(0);(0,s.useLayoutEffect)(()=>{if(!H)return void eQ(null);let e=!1;return fetch(`/api/worktrees?cwd=${encodeURIComponent(H)}`).then(e=>e.json()).then(t=>{if(!e){if(t.error||!t.projectRoot)return void eQ(null);eQ({forCwd:H,projectRoot:t.projectRoot,isGit:t.isGit??!1,isTopLevel:t.isTopLevel??!1,worktrees:t.worktrees??[]})}}).catch(()=>{e||eQ(null)}),()=>{e=!0}},[H,t1,c]),(0,s.useEffect)(()=>{if(0!==j.length&&!l&&null===H){if(i&&!tZ.current){tZ.current=!0;let e=j.find(e=>e.id===i);if(e){B(e.cwd),n(e,!0);return}o?.()}if(!em)return;let e=new Map(eh.projects.map(e=>[e.key,e])),t=P(j.length>0?L(j):[],eh.projects).filter(t=>!e.get(R(t))?.hidden);t.length>0&&B(t[0])}},[j,H,i,l,n,o,eh,em]);let t4=(0,s.useCallback)(async e=>{let t=e.trim();if(t&&!eG){eY(!0),eJ(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 eJ(n.error??b("workspace.unable"));let r=n.cwd??t,s=R(r),a=eh.projects.find(e=>e.key===s);if(a?.hidden===!0)try{await t$([{key:s,path:r,hidden:!1}])}catch{}B(r),eV(!1)}catch{eJ(b("workspace.unable"))}finally{eY(!1)}}},[t$,eG,eh.projects,b]),t8=(0,s.useCallback)(()=>{eV(!0),eJ(null)},[]),t5=(0,s.useCallback)(async()=>{let e=e4.trim();if(e&&!ts&&eZ){ta(!0),e6(null);try{let t=await fetch("/api/worktrees",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:eZ.projectRoot,branch:e})}),n=await t.json().catch(()=>({}));if(!t.ok||n.error||!n.path)return void e6(n.error??`HTTP ${t.status}`);e2(!1),e8(""),e0(!1),eQ(t=>t?{...t,forCwd:n.path,worktrees:[...t.worktrees,{path:n.path,branch:e,isMain:!1}]}:t),B(n.path),t2(e=>e+1)}catch(e){e6(e instanceof Error?e.message:String(e))}finally{ta(!1)}}},[e4,ts,eZ]),t6=(0,s.useCallback)(async(e,t)=>{if(eZ&&!ts){ta(!0),e6(null);try{let n=await fetch("/api/worktrees",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:eZ.projectRoot,path:e,force:t})}),r=await n.json().catch(()=>({}));if(!n.ok){if(r.dirty&&!t)return void tl(e);e6(r.error??`HTTP ${n.status}`);return}tl(null),H===e&&B(eZ.projectRoot),t2(e=>e+1)}catch(e){e6(e instanceof Error?e.message:String(e))}finally{ta(!1)}}},[eZ,ts,H]);(0,s.useEffect)(()=>{let e=e=>{to.current&&!to.current.contains(e.target)&&(eu(null),e0(!1),e2(!1),e8(""),e6(null),tl(null),eB(""),eo(null))};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[]);let t3=(0,s.useCallback)(e=>{e.cwd&&B(e.cwd),n(e)},[n]),t7=(0,s.useCallback)((e=H)=>{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)}`;B(e),a?.(t,e)},[H,a]),t9=(0,s.useCallback)(async()=>{let e=eZ?.projectRoot,t=e3.trim();if(!e||!t||e9)return;te(!0),tn(null);let r=tr.current,s=r?.issue===t&&r.cwd===e?r.id:"function"==typeof crypto.randomUUID?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}-${Math.random().toString(36).slice(2)}`;tr.current={issue:t,cwd:e,id:s};try{let r=await fetch("/api/agent/new",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e,issue:t,type:"ensure_session",createRequestId:s})}),a=await r.json();if(!r.ok||!a.sessionId||!a.cwd)throw Error(a.error??`HTTP ${r.status}`);ei(a.cwd,a.worktree),tr.current=null,e7(""),B(a.cwd),t2(e=>e+1),n({id:a.sessionId,cwd:a.cwd,projectRoot:e,path:"",created:new Date().toISOString(),modified:new Date().toISOString(),messageCount:0,firstMessage:"(no messages)",transient:!0})}catch(e){tn(e instanceof Error?e.message:String(e))}finally{te(!1)}},[eZ,e3,e9,n]),[ne,nt]=(0,s.useState)(!1),[nn,nr]=(0,s.useState)(null),ns=(0,s.useCallback)(async()=>{nt(!0),nr(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}`);t7(t.cwd)}catch(e){nr(b("sidebar.newScratchSessionFailed",{error:e instanceof Error?e.message:String(e)}))}finally{nt(!1)}},[t7,b]),na=(0,s.useCallback)(e=>{en(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]),ni=tQ(H),nl=null===ni?null:R(ni),no=(0,s.useMemo)(()=>new Map(eh.projects.map(e=>[e.key,e])),[eh.projects]),nc=L(_);if(null!==ni){let e=R(ni);nc.some(t=>R(t)===e)||nc.unshift(ni)}let nd=P(nc,eh.projects),nu=nd.filter(e=>eT||!no.get(R(e))?.hidden),nh=nd.some(e=>no.get(R(e))?.hidden),np=()=>{eu(null),e0(!1),e2(!1),e8(""),e6(null),tl(null),eB("")},nm=async(e,t)=>{np();try{await t$([{key:R(e),path:e,hidden:t}]),t&&nl&&nl===R(e)&&B(null),t||nd.some(t=>R(t)!==R(e)&&no.get(R(t))?.hidden)||e$(!1)}catch{}},nf=async e=>{if(tu.current){tu.current=!1,e_(null);return}let t=eF.trim();if(t===(no.get(R(e))?.alias??""))return void e_(null);eH(null);try{await t$([{key:R(e),path:e,alias:t||null}]),e_(null)}catch{eH(b("sidebar.projectUpdateFailed"))}},ng=async(e,t)=>{if(Y)return;let n=nu.indexOf(e),r=n+t;if(n<0||r<0||r>=nu.length)return;let s=new Set(nu),a=nd.map((e,t)=>s.has(e)?t:-1).filter(e=>e>=0),i=[...nd],l=a[n],o=a[r];[i[l],i[o]]=[i[o],i[l]],np();try{await t$(i.map((e,t)=>({key:R(e),path:e,order:t})))}catch{}},nx=new Map;for(let e of _){let t=e.projectRoot??e.cwd;if(!t)continue;let n=R(t),r=nx.get(n);r?r.push(e):nx.set(n,[e])}let nv=(0,s.useMemo)(()=>{let e=new Map;for(let t of _){let n=t.projectRoot??t.cwd;if(!n)continue;let r=R(n),s=e.get(r);s||(s={running:0,unread:0},e.set(r,s)),tf.has(t.id)&&s.running++,ty.has(t.id)&&s.unread++}return e},[_,tf,ty]),ny=Y.trim().toLowerCase(),nb=Y.length>0,nw=nu.flatMap(e=>{let t=e.replace(/[\\/]+$/,"").split(/[\\/]/).at(-1)||e,n=R(e),r=no.get(n),s=r?.alias??t,a=(nx.get(n)??[]).slice().sort((e,t)=>{let n=Number(tw.has(t.id))-Number(tw.has(e.id));return 0!==n?n:t.modified.localeCompare(e.modified)});if(!ny)return[{project:e,key:n,name:s,sessions:a,hidden:r?.hidden===!0}];let i=s.toLowerCase().includes(ny)||t.toLowerCase().includes(ny),l=a.filter(e=>(e.name||e.firstMessage.slice(0,50)||e.id.slice(0,12)).toLowerCase().includes(ny));return i||0!==l.length?[{project:e,key:n,name:s,sessions:i?a:l,hidden:r?.hidden===!0}]:[]}),nk=[],nj=[];for(let e of nw){let t=e.key===nl||(nv.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=>S.some(t=>e.startsWith(t)))})(e.project)&&!t?nj.push(e):nk.push(e)}let nS={running:0,unread:0};for(let e of nj){let t=nv.get(e.key);t&&(nS.running+=t.running,nS.unread+=t.unread)}let nC=nb||eR,nN=[...nk.map(e=>({kind:"project",group:e})),...nj.length>0?[{kind:"temporary"}]:[],...nC?nj.map(e=>({kind:"project",group:e})):[]],nT=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,s.useMemo)(()=>tj?_.filter(e=>(function(e,t,n,r=E){if(e.transient||e.trial)return!1;if(r.has(e.id))return!0;if(t.has(e.id))return!1;let s=I(e);return null!==s&&s>(n.opened[e.id]??n.since)})(e,tf,tj,tx)):[],[tj,tf,_,tx]),nM=tC&&null!==tj,[nE,n$]=(0,s.useState)(null),nR=(0,s.useMemo)(()=>(function(e,t,n,r,s="Priority",a=new Set,i="Pinned",l=10){let o=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)}),c=o.filter(e=>a.has(e.id)),d=[],u=new Map,h=0;for(let e of o){if(a.has(e.id))continue;if(t.has(e.id)){d.push(e);continue}let n=new Date(e.modified);if(h>=l)continue;h+=1;let r=[n.getFullYear(),String(n.getMonth()+1).padStart(2,"0"),String(n.getDate()).padStart(2,"0")].join("-"),s=u.get(r);s?s.push(e):u.set(r,[e])}let p=[];for(let e of(c.length>0&&p.push({key:"pinned",label:i,running:!1,sessions:c}),d.length>0&&p.push({key:"priority",label:s,running:!0,sessions:d}),[...u.keys()].sort().reverse()))p.push({key:e,label:function(e,t,n){let[r,s,a]=e.split("-").map(Number),i=new Date(r,s-1,a),l=Math.round((Date.UTC(t.getFullYear(),t.getMonth(),t.getDate())-Date.UTC(i.getFullYear(),i.getMonth(),i.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(i):new Intl.DateTimeFormat(n,{month:"short",day:"numeric"}).format(i)}(e,n,r),running:!1,sessions:u.get(e)??[]});return p})(nM?_.filter(e=>e.id===nE&&!tf.has(e.id)||nI.includes(e)):_,tf,new Date,w,b("navigator.priority"),tw,b("sidebar.pinned"),nM?1/0:void 0),[nE,w,tw,nI,nM,tf,_,b]),nL=(0,s.useMemo)(()=>{let e=new Set(nI.map(e=>e.id)),t=[],n=[],r=[],s=null,a=[];for(let i of nR)if("pinned"===i.key){let a=i.sessions.filter(s=>{if(tx.has(s.id))t.push(s);else if(tf.has(s.id))n.push(s);else{if(!e.has(s.id))return!0;r.push(s)}return!1});a.length>0&&(s={...i,sessions:a})}else if(i.running)for(let e of i.sessions)(tx.has(e.id)?t:n).push(e);else{let t=i.sessions.filter(t=>!e.has(t.id)||(r.push(t),!1));t.length>0&&a.push({...i,sessions:t})}let i=[];return t.length>0&&i.push({key:"input",kind:"input",label:b("navigator.group.input"),sessions:t}),n.length>0&&i.push({key:"running",kind:"running",label:b("navigator.group.running"),sessions:n}),r.length>0&&i.push({key:"review",kind:"review",label:b("navigator.resultsToCheck"),sessions:r}),s&&i.push({key:"pinned",kind:"pinned",label:s.label,sessions:s.sessions}),a.forEach((e,t)=>i.push({key:e.key,kind:"done",label:e.label,heading:0===t?b("navigator.group.done"):void 0,sessions:e.sessions})),i},[nR,nI,tf,b,tx]),nP=(0,s.useCallback)(e=>{n$(e.id),t3(e)},[t3]),nA=!!(eZ?.isGit&&eZ.isTopLevel&&H&&ni===eZ.projectRoot),n_=eZ?.worktrees.find(e=>e.path===H)??eZ?.worktrees.find(e=>e.isMain),nF=(eZ?.worktrees.length??0)>=8,nO=nF&&eU.trim()?(eZ?.worktrees??[]).filter(e=>(e.branch??ey(e.path,q)).toLowerCase().includes(eU.trim().toLowerCase())):eZ?.worktrees??[],nz=es[w.startsWith("ko")?"ko":w.startsWith("zh")?"zh":"en"],nD=function(e){if(e&&"u">typeof sessionStorage)try{return JSON.parse(sessionStorage.getItem(`cuelo:worktree:${e}`)??"null")??void 0}catch{return}}(H),nW=(()=>{if(!tP)return[];let e="project"===tP.kind?nx.get(R(tP.project))??[]:nR.flatMap(e=>e.sessions),t=new Set;return e.filter(e=>!(e.transient||t.has(e.id))&&(t.add(e.id),!0))})(),nH=nW.filter(e=>!tf.has(e.id)),nU=e=>{let t=new Set;for(let n of e)n.transient||tf.has(n.id)||t.has(n.id)||t.add(n.id);return t.size},nB=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:[eq&&(0,r.jsx)(K?X:G,{busy:eG,error:eK,onCancel:()=>{eV(!1),eJ(null)},onSelect:e=>void t4(e)}),tP&&(0,r.jsx)(eN,{scope:tP,eligible:nH.length,runningExcluded:nW.length-nH.length,busy:t_,error:tO,onCancel:tD,onConfirm:()=>void tW(nH)}),(0,r.jsxs)("div",{className:"session-navigator-header",style:{padding:"4px 10px",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)(ej,{}),(0,r.jsxs)("div",{style:{display:"flex",gap:12},children:[(0,r.jsx)("button",{className:"navigator-icon-action",onClick:()=>t7(),disabled:!H,style:{display:"flex",alignItems:"center",justifyContent:"center",background:"var(--bg-hover)",border:0,color:H?"var(--text-muted)":"var(--text-dim)",cursor:H?"pointer":"not-allowed",width:32,height:32,padding:0,borderRadius:"var(--radius-control)",fontSize:12,flexShrink:0,transition:"background 0.12s, color 0.12s"},title:H?b("sidebar.newSessionTitle",{path:H}):b("sidebar.selectProject"),"aria-label":H?b("sidebar.newSessionTitle",{path:H}):b("sidebar.selectProject"),onMouseEnter:e=>{H&&(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=H?"var(--text-muted)":"var(--text-dim)"},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${tp?" is-success":""}`,onClick:()=>tR(!1,!0),style:{display:"flex",alignItems:"center",justifyContent:"center",background:tp?"var(--success-soft)":"var(--bg-hover)",border:0,color:tp?"var(--success)":"var(--text-muted)",cursor:"pointer",width:32,height:32,borderRadius:"var(--radius-control)",padding:0,flexShrink:0,transition:"background 0.3s, color 0.3s"},onMouseEnter:e=>{tp||(e.currentTarget.style.background="var(--bg-selected)",e.currentTarget.style.color="var(--accent)")},onMouseLeave:e=>{tp||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text-muted)")},title:b("sidebar.refresh"),children:tp?(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"})]})})]})]}),nA&&(0,r.jsxs)("form",{onSubmit:e=>{e.preventDefault(),t9()},style:{marginTop:8},children:[(0,r.jsx)("label",{htmlFor:"session-issue",style:{display:"block",fontSize:12,color:"var(--text-muted)"},children:nz.issueLabel}),(0,r.jsxs)("div",{style:{display:"flex",gap:4,marginTop:4},children:[(0,r.jsx)("input",{id:"session-issue",value:e3,disabled:e9,onChange:e=>{e7(e.target.value),tn(null)},placeholder:nz.issuePlaceholder,"aria-describedby":tt?"session-issue-error":void 0,"aria-invalid":!!tt,style:{minWidth:0,flex:1,padding:"6px 8px",fontSize:12,background:"var(--bg)",color:"var(--text)",border:0,borderRadius:"var(--radius-control)"}}),(0,r.jsx)("button",{type:"submit",disabled:e9||!e3.trim(),title:nz.issueStart,"aria-label":nz.issueStart,style:{minWidth:32,padding:"4px 8px",border:0,borderRadius:"var(--radius-control)",background:"var(--bg-hover)",color:"var(--text)",cursor:e9?"wait":"pointer"},children:e9?"…":"↵"})]}),e9&&(0,r.jsx)("div",{role:"status",style:{fontSize:12},children:nz.issueBusy}),tt&&(0,r.jsx)("div",{id:"session-issue-error",role:"alert",style:{fontSize:12,color:"var(--danger)",overflowWrap:"anywhere"},children:tt})]}),(nD||n_&&!n_.isMain)&&(0,r.jsxs)("div",{role:"status",title:H??void 0,style:{marginTop:4,fontSize:12,color:"var(--text-muted)",overflowWrap:"anywhere"},children:[nD?.branch??n_?.branch,nD?.fallback&&(0,r.jsx)("div",{children:nz.fallbackBase.replace("{branch}",nD.base)}),nD?.missingSubdirectory&&(0,r.jsx)("div",{children:ea[w.startsWith("ko")?"ko":w.startsWith("zh")?"zh":"en"].replace("{path}",nD.missingSubdirectory)})]})]}),K&&!nB&&(0,r.jsx)("button",{type:"button",className:"navigator-cloud-project",onClick:t8,style:{margin:"10px 12px 0",minHeight:44,flexShrink:0,border:0,borderRadius:"var(--radius-control)",background:"var(--bg)",color:"var(--text)",fontSize:13,fontWeight:600,cursor:"pointer"},children:b("cloudProjects.launch")}),(0,r.jsxs)("div",{className:"navigator-mode-bar",children:[(0,r.jsx)("h2",{className:"navigator-place-title",children:nB?y("translator.tab"):"projects"===g?b("sidebar.projects"):b("navigator.priority")}),(0,r.jsx)("span",{className:"navigator-mode-spacer"}),!nB&&"projects"===g&&(0,r.jsx)("button",{type:"button",onClick:()=>e$(e=>!e),disabled:!nh,title:b("sidebar.projectShowHidden"),"aria-label":b("sidebar.projectShowHidden"),"aria-pressed":eT,style:{display:"flex",alignItems:"center",justifyContent:"center",width:26,height:26,padding:0,border:"none",borderRadius:"var(--radius-control)",background:eT?"var(--bg-selected)":"transparent",color:eT?"var(--accent)":"var(--text-dim)",cursor:nh?"pointer":"default",opacity:nh?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"}),!eT&&(0,r.jsx)("path",{d:"m4 4 16 16"})]})}),!nB&&"projects"===g&&(0,r.jsx)("button",{className:"navigator-add-project",type:"button",onClick:t8,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:"var(--radius-control)",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"})]})})]}),nB&&m,!nB&&"projects"===g&&(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:Y,onChange:e=>Z(e.target.value),onKeyDown:e=>{"Escape"===e.key&&(e.preventDefault(),Z(""),e.currentTarget.blur())},placeholder:b("sidebar.searchProjectsAndSessions"),"aria-label":b("sidebar.searchProjectsAndSessions"),style:{width:"100%",height:34,padding:"0 10px 0 32px",border:0,borderRadius:"var(--radius-control)",outline:"none",background:"var(--bg-hover)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:11}})]}),!nB&&"projects"===g&&(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:[(O||!em)&&(0,r.jsx)("div",{style:{padding:"12px 8px",color:"var(--text-muted)",fontSize:12},children:b("sidebar.loading")}),D&&(0,r.jsx)("div",{style:{padding:"10px 8px",color:"var(--danger)",fontSize:12},children:D}),eW&&(0,r.jsx)("div",{style:{padding:"10px 8px",color:"var(--danger)",fontSize:12},children:eW}),!O&&em&&!D&&0===nw.length&&(0,r.jsx)("div",{style:{padding:"12px 8px",color:"var(--text-muted)",fontSize:12},children:ny?b("sidebar.noMatchingProjects"):b("sidebar.noSessions")}),!O&&em&&!D&&nN.map(t=>{let n,s,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":nC,title:b("sidebar.temporaryProjects"),onClick:()=>eL(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:nC?"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-muted)",fontFamily:"var(--font-mono)",fontSize:11,flexShrink:0},children:nj.length}),eP(nS,b)]})},"navigator-temporary-projects");let{project:i,key:l,name:o,sessions:c,hidden:d}=t.group,u=l===nl,h=nT.has(o.toLowerCase())&&ey((s=Math.max((n=i.trim().replace(/[\\/]+$/,"")).lastIndexOf("\\"),n.lastIndexOf("/")))<=0?"":n.slice(0,s),q)||null,p=!et.has(i)&&!ny,m=Q.has(i),f=eA===i,g=nu.indexOf(i),x=ez||nb||g<=0,v=ez||nb||g>=nu.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 s=function(e){let r=n.get(e),s=new Set;for(;r&&!s.has(r);){if(s.add(r),t.has(r))return r;r=n.get(r)}return null}(e.session.id);s?t.get(s).children.push(e):r.push(e)}let s=e=>{e.sort((e,t)=>t.session.modified.localeCompare(e.session.modified)),e.forEach(e=>s(e.children))};return s(r),r}(m?c:c.slice(0,5)),w=c.length>5;return(0,r.jsxs)("section",{className:"navigator-project-group",style:{marginBottom:p?3:9},children:[(0,r.jsxs)("div",{className:`navigator-project-row${u?" is-selected":""}`,ref:ed===i?to:void 0,onMouseEnter:()=>eo(i),onMouseLeave:()=>eo(e=>e===i&&ed!==i?null:e),style:{display:"flex",alignItems:"center",minHeight:34,position:"relative",borderRadius:"var(--radius-control)",background:u?"var(--bg-hover)":"transparent",opacity:d?.55:1},children:[(0,r.jsx)("button",{type:"button",onClick:()=>na(i),title:p?b("sidebar.expandProject"):b("sidebar.collapseProject"),"aria-label":p?b("sidebar.expandProject"):b("sidebar.collapseProject"),"aria-expanded":!p,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:p?"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:td,value:eF,onChange:e=>eO(e.target.value),onBlur:()=>void nf(i),onKeyDown:e=>{"Enter"===e.key?(e.preventDefault(),e.currentTarget.blur()):"Escape"===e.key&&(e.preventDefault(),tu.current=!0,e_(null))},"aria-label":b("sidebar.projectAlias"),style:{flex:1,minWidth:0,height:24,padding:"2px 6px",border:0,borderRadius:"var(--radius-control)",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:()=>B(i),title:i,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===h?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:h}),eP(nv.get(l),b)]}),!k&&(0,r.jsx)("button",{type:"button",onClick:()=>t7(i),title:b("sidebar.newSessionTitle",{path:i}),"aria-label":b("sidebar.newSessionTitle",{path:i}),style:{display:"flex",alignItems:"center",justifyContent:"center",width:28,height:28,padding:0,border:"none",borderRadius:"var(--radius-control)",background:"transparent",color:"var(--text-dim)",cursor:"pointer",opacity:+(el===i),pointerEvents:el===i?"auto":"none",transition:"opacity 0.12s, background 0.12s, color 0.12s",flexShrink:0},onFocus:()=>eo(i),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:()=>{eu(ed===i?null:i),e0(!1),e2(!1),e6(null),u||B(i)},title:b("sidebar.projectActions"),"aria-label":b("sidebar.projectActions"),"aria-expanded":ed===i,style:{display:"flex",alignItems:"center",justifyContent:"center",width:26,height:26,marginRight:3,padding:0,border:"none",borderRadius:"var(--radius-control)",background:ed===i?"var(--bg-selected)":"transparent",color:u&&n_&&!n_.isMain?"var(--accent)":"var(--text-dim)",cursor:"pointer",opacity:k||el===i||ed===i?1:0,pointerEvents:k||el===i||ed===i?"auto":"none",transition:"opacity 0.12s, background 0.12s, color 0.12s"},onFocus:()=>eo(i),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)(ew,{open:ed===i,style:{position:"absolute",top:"calc(100% + 4px)",right:3,width:"min(260px, calc(100vw - 24px))",zIndex:110,background:"var(--bg-raised)",border:0,borderRadius:"var(--radius-surface)",boxShadow:"var(--shadow-float)",boxSizing:"border-box",overflow:"hidden"},children:[k&&(0,r.jsxs)("button",{type:"button",className:"navigator-project-menu-new-session",onClick:()=>{eu(null),t7(i)},title:b("sidebar.newSessionTitle",{path:i}),style:{display:"flex",alignItems:"center",gap:8,width:"100%",minHeight:44,padding:"0 10px",border:"none",background:"transparent",color:"var(--text)",cursor:"pointer",textAlign:"left",fontSize:13},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"})]}),b("i18n.newSession")]}),nA&&eZ&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("button",{type:"button",onClick:()=>e0(e=>!e),title:n_?b("sidebar.switchWorktreeTitle",{path:n_.path}):b("sidebar.switchWorktree"),"aria-label":b("sidebar.worktrees"),"aria-expanded":eX,style:{display:"flex",alignItems:"center",gap:8,width:"100%",minHeight:34,padding:"0 10px",border:"none",background:eX?"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)(ew,{open:eX,style:{position:"static",width:"auto",zIndex:100,background:"var(--bg)",border:"none",borderRadius:0,boxShadow:"none",boxSizing:"border-box",overflow:"hidden"},children:[nF&&(0,r.jsx)("div",{style:{padding:"6px 8px"},children:(0,r.jsx)("input",{value:eU,onChange:e=>eB(e.target.value),onKeyDown:e=>{"Escape"===e.key&&(eB(""),e0(!1))},placeholder:b("sidebar.filterWorktrees"),autoFocus:!0,style:{width:"100%",fontSize:11,fontFamily:"var(--font-mono)",padding:"5px 8px",border:0,borderRadius:"var(--radius-control)",outline:"none",background:"var(--bg-subtle)",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===H||e.isMain&&!eZ.worktrees.some(e=>e.path===H);return ti===e.path?(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6,padding:"7px 10px",background:"var(--danger-soft)"},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 t6(e.path,!0),disabled:ts,style:{padding:"3px 9px",background:"var(--danger)",border:"none",borderRadius:"var(--radius-control)",color:"var(--bg)",fontSize:11,fontWeight:600,cursor:"pointer",flexShrink:0},children:b("sidebar.force")}),(0,r.jsx)("button",{onClick:()=>tl(null),style:{padding:"3px 9px",background:"var(--bg-hover)",border:0,borderRadius:"var(--radius-control)",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"},children:[(0,r.jsxs)("button",{onClick:()=>{B(e.path),e0(!1),e6(null),eB("")},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)(eb,{text:e.branch??ey(e.path,q),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 t6(e.path,!1),disabled:ts,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:"var(--radius-control)",flexShrink:0,transition:"color 0.12s, background 0.12s"},onMouseEnter:e=>{e.currentTarget.style.color="var(--danger)",e.currentTarget.style.background="var(--danger-soft)"},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)}),nF&&0===nO.length&&eU.trim()&&(0,r.jsx)("div",{style:{padding:"8px 10px",fontSize:11,color:"var(--text-dim)"},children:b("sidebar.noMatchingWorktrees")})]}),e1?(0,r.jsxs)("div",{style:{padding:"6px 8px"},children:[(0,r.jsx)("input",{ref:tc,value:e4,onChange:e=>{e8(e.target.value),e6(null)},onKeyDown:e=>{"Enter"===e.key&&(e.preventDefault(),t5()),"Escape"===e.key&&(e2(!1),e8(""),e6(null))},placeholder:b("sidebar.branchName"),style:{width:"100%",fontSize:11,fontFamily:"var(--font-mono)",padding:"5px 8px",border:0,borderRadius:"var(--radius-control)",outline:"none",background:"var(--bg-subtle)",color:"var(--text)",boxSizing:"border-box"}}),(0,r.jsxs)("div",{style:{display:"flex",gap:5,marginTop:5},children:[(0,r.jsx)("button",{onClick:()=>void t5(),disabled:ts||!e4.trim(),style:{flex:1,padding:"4px 0",background:"var(--accent)",border:"none",borderRadius:"var(--radius-control)",color:"var(--bg)",fontSize:11,fontWeight:600,cursor:ts||!e4.trim()?"not-allowed":"pointer",opacity:ts||!e4.trim()?.65:1},children:ts?b("sidebar.creating"):b("sidebar.create")}),(0,r.jsx)("button",{onClick:()=>{e2(!1),e8(""),e6(null)},style:{flex:1,padding:"4px 0",background:"var(--bg-hover)",border:0,borderRadius:"var(--radius-control)",color:"var(--text-muted)",fontSize:11,cursor:"pointer"},children:b("sidebar.cancel")})]})]}):(0,r.jsxs)("button",{onClick:e=>{e.stopPropagation(),e2(!0),e6(null),setTimeout(()=>tc.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")})]}),e5&&(0,r.jsx)("div",{style:{padding:"5px 10px 8px",color:"var(--danger)",fontSize:11,lineHeight:1.35,overflowWrap:"anywhere"},children:e5})]})]}),(0,r.jsxs)("button",{type:"button",disabled:ez,onClick:()=>{let e;return e=no.get(R(i))?.alias??"",void(tu.current=!1,eH(null),eO(e),e_(i),np())},style:{display:"flex",alignItems:"center",gap:8,width:"100%",minHeight:34,padding:"0 10px",border:"none",background:"transparent",color:"var(--text-muted)",cursor:ez?"default":"pointer",textAlign:"left",fontSize:11,opacity:ez?.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(no.get(R(i))?.alias?"sidebar.projectAliasEdit":"sidebar.projectAlias")]}),(0,r.jsxs)("button",{type:"button",disabled:x,title:nb?b("sidebar.projectMoveDisabledWhileFiltering"):void 0,onClick:()=>void ng(i,-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:nb?b("sidebar.projectMoveDisabledWhileFiltering"):void 0,onClick:()=>void ng(i,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:ez,onClick:()=>void nm(i,!d),style:{display:"flex",alignItems:"center",gap:8,width:"100%",minHeight:34,padding:"0 10px",border:"none",background:"transparent",color:"var(--text-muted)",cursor:ez?"default":"pointer",textAlign:"left",fontSize:11,opacity:ez?.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"}),!d&&(0,r.jsx)("path",{d:"m4 4 16 16"})]}),b(d?"sidebar.projectUnhide":"sidebar.projectHide")]}),(a=0===nU(nx.get(l)??[])||t_,(0,r.jsxs)("button",{type:"button",disabled:a,onClick:()=>{np(),tz(null),tA({kind:"project",project:i,label:o})},style:{display:"flex",alignItems:"center",gap:8,width:"100%",minHeight:34,padding:"0 10px",border:"none",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")]}))]})]})]}),!p&&0===c.length&&u&&(0,r.jsx)("div",{style:{padding:"6px 12px 7px 32px",color:"var(--text-dim)",fontSize:11},children:b("sidebar.noSessions")}),!p&&y.length>0&&(0,r.jsx)("div",{style:{paddingLeft:12},children:y.map(t=>(0,r.jsx)(eE,{node:t,selectedSessionId:e,runningSessionIds:tf,unreadSessionIds:ty,pinnedSessionIds:tw,onSelectSession:t3,onTogglePinnedSession:tV,onRenamed:tR,onSessionDeleted:tL,onSessionArchived:tB,depth:0},t.session.id))}),!p&&w&&(0,r.jsx)("button",{type:"button",onClick:()=>{ee(e=>{let t=new Set(e);return t.has(i)?t.delete(i):t.add(i),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")})]},i)})]}),!nB&&(0,r.jsx)(eM,{refreshKey:tH,selectedSessionId:e,onSelectSession:t3,onRestored:tB}),!nB&&"priority"===g&&(0,r.jsxs)("div",{id:"navigator-priority-panel",style:{flex:"1 1 auto",minHeight:80,overflowY:"auto",padding:"0 6px 10px"},children:[O&&(0,r.jsx)("div",{style:{padding:"12px 8px",color:"var(--text-muted)",fontSize:12},children:b("sidebar.loading")}),D&&(0,r.jsx)("div",{role:"alert",style:{padding:"10px 8px",color:"var(--danger)",fontSize:12},children:D}),!O&&!D&&(v=nU(nR.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:ne,onClick:()=>void ns(),title:b("sidebar.newScratchSessionTitle"),style:ev(ne,k),children:b("sidebar.newScratchSession")}),nR.length>0&&!nM&&(0,r.jsx)("button",{type:"button",disabled:0===v||t_,onClick:()=>{tz(null),tA({kind:"priority"})},style:ev(0===v||t_,k),children:b("sidebar.clearPriorityList")})]})),!O&&!D&&tj&&(0,r.jsxs)("div",{style:{display:"flex",justifyContent:"space-between",gap:8,padding:"6px 2px 4px"},children:[(0,r.jsxs)("button",{type:"button","aria-pressed":nM,"aria-label":b("navigator.resultsToCheckCount",{count:nI.length}),title:b("navigator.resultsToCheckHint"),onClick:()=>{n$(null),tN(e=>!e)},style:{...ev(!1,k),display:"inline-flex",alignItems:"center",gap:6,background:nM?"var(--bg-selected)":"var(--bg-hover)",color:nM||nI.length>0?"var(--text)":"var(--text-muted)",fontWeight:nM?600:500,whiteSpace:"nowrap"},children:[b("navigator.resultsToCheck"),(0,r.jsx)("span",{"aria-hidden":"true",style:{minWidth:18,padding:"0 5px",borderRadius:"var(--radius-surface)",background:nI.length>0?"var(--seed-color-bg-neutral-inverted)":"var(--bg-subtle)",color:nI.length>0?"var(--seed-color-fg-neutral-inverted)":"var(--text-muted)",fontSize:11,fontVariantNumeric:"tabular-nums",lineHeight:"18px",textAlign:"center"},children:nI.length})]}),nI.some(e=>!tx.has(e.id))&&(0,r.jsx)("button",{type:"button",title:b("navigator.acknowledgeResultsHint"),onClick:()=>{n$(null),tS(e=>e&&function(e,t,n){let r=e;for(let e of t)r=M(r,e,n);return r}(e,nI,Date.now()))},style:ev(!1,k),children:b("navigator.acknowledgeResults")})]}),nn&&(0,r.jsx)("div",{role:"alert",style:{padding:"6px 8px",color:"var(--danger)",fontSize:12},children:nn}),!O&&!D&&0===nR.length&&(0,r.jsx)("div",{style:{padding:"12px 8px",color:"var(--text-muted)",fontSize:12},children:nM?b("navigator.resultsToCheckEmpty"):b("sidebar.noSessions")}),!O&&!D&&nL.map((t,n)=>(0,r.jsxs)("section",{"aria-labelledby":`priority-group-${t.key}`,className:"priority-group","data-group":t.kind,children:[t.heading&&(0,r.jsx)("h2",{className:"priority-group-heading","data-first":0===n?"":void 0,children:t.heading}),(0,r.jsxs)("h3",{id:`priority-group-${t.key}`,className:t.heading?"priority-group-day":"priority-group-heading","data-first":0!==n||t.heading?void 0:"",children:["input"===t.kind&&(0,r.jsx)("span",{className:"workbench-lamp","data-kind":"input","aria-hidden":"true"}),"running"===t.kind&&(0,r.jsx)("span",{className:"workbench-lamp","aria-hidden":"true"}),t.label,(0,r.jsx)("span",{className:"priority-group-count",children:t.sessions.length})]}),t.sessions.map(t=>(0,r.jsx)(eI,{session:t,selected:t.id===e,running:tf.has(t.id),waiting:tx.has(t.id),unread:ty.has(t.id),pinned:tw.has(t.id),onSelect:nM?nP:t3,onTogglePin:tV},t.id))]},t.key))]})]})}function eN({scope:e,eligible:t,runningExcluded:n,busy:a,error:i,onCancel:l,onConfirm:o}){let{t:c}=(0,F.s)(),d=a||0===t,u=(0,s.useRef)(null),h=(0,s.useRef)(null),p=(0,s.useRef)(a);p.current=a;let m=(0,s.useRef)(l);return m.current=l,(0,s.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;(h.current??e).focus();let r=t=>{if("Escape"===t.key){if(p.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 s=n[0],a=n[n.length-1];t.shiftKey&&(r===s||!e.contains(r))?(t.preventDefault(),a.focus()):t.shiftKey||r!==a&&e.contains(r)||(t.preventDefault(),s.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:0,borderRadius:"var(--radius-surface)",background:"var(--bg-raised)",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:c("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?c("sidebar.clearSessionsProjectBody",{project:e.label,count:t}):c("sidebar.clearSessionsPriorityBody",{count:t}),n>0&&(0,r.jsx)("div",{style:{marginTop:6},children:c("sidebar.clearSessionsRunningExcluded",{count:n})}),0===t&&(0,r.jsx)("div",{style:{marginTop:6},children:c("sidebar.clearSessionsNone")})]}),i&&(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:i})]}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",justifyContent:"flex-end",gap:8,padding:"12px 18px"},children:[(0,r.jsx)("button",{ref:h,type:"button",onClick:l,disabled:a,style:{minHeight:36,padding:"0 12px",border:0,borderRadius:"var(--radius-control)",background:"var(--bg-hover)",color:"var(--text-muted)",cursor:a?"default":"pointer",fontSize:"var(--seed-font-size-t3-static)"},children:c("sidebar.clearSessionsCancel")}),(0,r.jsx)("button",{type:"button",onClick:o,disabled:d,"aria-busy":a,style:{minHeight:36,padding:"0 14px",border:0,borderRadius:"var(--radius-control)",background:d?"var(--bg-hover)":"var(--danger-soft)",color:d?"var(--text-dim)":"var(--danger)",cursor:d?"default":"pointer",fontSize:"var(--seed-font-size-t3-static)",fontWeight:600},children:c(a?"sidebar.clearSessionsBusy":"sidebar.clearSessionsConfirm")})]})]})})}function eT({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 eI({session:e,selected:t,running:n,waiting:s,unread:a,pinned:i,onSelect:l,onTogglePin:o}){let{t:c}=(0,F.s)(),d=(e.name||e.firstMessage||e.id.slice(0,8)).replace(/\s+/g," ").trim(),u=e.cwd.split(/[\\/]/).filter(Boolean).at(-1)??"";return(0,r.jsxs)("div",{className:`priority-session-row${t?" is-selected":""}${n?" is-running":""}${a?" is-unread":""}`,style:{display:"flex",alignItems:"stretch",borderRadius:"var(--radius-control)",background:t?"var(--bg-selected)":"transparent"},children:[(0,r.jsxs)("button",{type:"button","aria-current":t?"page":void 0,onClick:()=>l(e),title:`${d}
1
+ (self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[8974],{1682:e=>{e.exports={root:"ProcessLogPanel_root__KhilQ"}},2498:e=>{e.exports={view:"MemoryTraceView_view__62Ck_",body:"MemoryTraceView_body__gELit",message:"MemoryTraceView_message__pDO_k",errorText:"MemoryTraceView_errorText__GkoKJ",sectionTitle:"MemoryTraceView_sectionTitle__lmuuo",sectionCount:"MemoryTraceView_sectionCount__9yRSn",requests:"MemoryTraceView_requests__scPBk",requestScroller:"MemoryTraceView_requestScroller__4ALfU",requestList:"MemoryTraceView_requestList__rQ4G0",requestRow:"MemoryTraceView_requestRow__LZd3A",requestIndex:"MemoryTraceView_requestIndex__TacwG",requestTime:"MemoryTraceView_requestTime__fJjQF",noticeChip:"MemoryTraceView_noticeChip__gz9AO",requestPreview:"MemoryTraceView_requestPreview__HwG7v",miniRail:"MemoryTraceView_miniRail__84C2v",flow:"MemoryTraceView_flow__UCgmI",titleText:"MemoryTraceView_titleText__38Tl7",flowPreview:"MemoryTraceView_flowPreview__HjgKe",rail:"MemoryTraceView_rail__HlWbE",station:"MemoryTraceView_station__ulNBH",stationButton:"MemoryTraceView_stationButton__BztyW",stationStep:"MemoryTraceView_stationStep__CgFYZ",stationCount:"MemoryTraceView_stationCount__2_rrN",stationLabel:"MemoryTraceView_stationLabel__QGYpC",stationNote:"MemoryTraceView_stationNote__Jc30I",detail:"MemoryTraceView_detail__Rnn_d",stageEmpty:"MemoryTraceView_stageEmpty__x0H_J",group:"MemoryTraceView_group__1SCqK",bucket:"MemoryTraceView_bucket__Vmuau",groupTitle:"MemoryTraceView_groupTitle__6Q1oM",groupCode:"MemoryTraceView_groupCode__qgzOG",query:"MemoryTraceView_query__DK87N",items:"MemoryTraceView_items__D8Wz8",item:"MemoryTraceView_item__wyulb",idList:"MemoryTraceView_idList__mQArH",path:"MemoryTraceView_path__97O3u",itemHead:"MemoryTraceView_itemHead__B0bQo",memoryId:"MemoryTraceView_memoryId__5KjoX",itemMeta:"MemoryTraceView_itemMeta__wbj6K",itemText:"MemoryTraceView_itemText__O92R_",graph:"MemoryTraceView_graph__RHbn9",graphHead:"MemoryTraceView_graphHead__sEDhc",scopeSwitch:"MemoryTraceView_scopeSwitch__3HBI2",legend:"MemoryTraceView_legend__52_dq",legendMark:"MemoryTraceView_legendMark__hS7sK",legendTitle:"MemoryTraceView_legendTitle__z_lgW",legendMemory:"MemoryTraceView_legendMemory__mkYqP",graphCaption:"MemoryTraceView_graphCaption__ot7gW",captionKind:"MemoryTraceView_captionKind__e1fLD",graphFrame:"MemoryTraceView_graphFrame__SgiqG",graphSvg:"MemoryTraceView_graphSvg___JeWV",columnHeads:"MemoryTraceView_columnHeads__drsYb",edges:"MemoryTraceView_edges__4zMSL",node:"MemoryTraceView_node__ymwrL",hit:"MemoryTraceView_hit__HS6HS",mark:"MemoryTraceView_mark__WxCZl",arrow:"MemoryTraceView_arrow__oz9U4",nodeText:"MemoryTraceView_nodeText__Tp4ud",ring:"MemoryTraceView_ring___LM5n"}},2730:(e,t,n)=>{"use strict";function r(e,t,n,s={}){let a=n[e]?.[t]??n.en?.[t];return void 0===a?t:function(e,t={}){return e.replace(/\{([\w.-]+)\}/g,(e,n)=>{let r=t[n];return void 0===r?e:String(r)})}(a,s)}function s(e,t,n=new Date){let r=(e instanceof Date?e:new Date(e)).getTime()-n.getTime(),a=Math.abs(r),[i,l]=a<6e4?["second",1e3]:a<36e5?["minute",6e4]:a<864e5?["hour",36e5]:["day",864e5],o=Math.round(r/l);return new Intl.RelativeTimeFormat(t,{numeric:"always"}).format(o,i)}n.d(t,{fw:()=>s,u0:()=>r})},4378:(e,t,n)=>{"use strict";n.d(t,{AppShell:()=>jh});var r=n(95155),s=n(12115),a=n(47650),i=n(73321),l=n(16871),o=n(66919),c=n(81886);let d=["chat","process","subagents","files","resource","sidechat","efficiency","plugins","memory","browser"];Object.freeze({rail:60,transcript:560,composer:384,navigator:240,deck:372});let u=Object.freeze({navigator:860,deck:1232}),h=Object.freeze({activeView:"chat",transientLayer:null,deckExpanded:!1}),p=Object.fromEntries(d.map(e=>[e,!0]));function m(e){return"string"==typeof e&&!0===p[e]?e:h.activeView}function f(e,t){switch(t.type){case"select-view":{let n,r=m(t.view);return{activeView:r,transientLayer:null,deckExpanded:(n=!0===e.deckExpanded,"chat"!==r&&n)}}case"open-layer":{let n,r=m(e.activeView);return{activeView:r,transientLayer:t.layer,deckExpanded:(n=!0===e.deckExpanded,"chat"!==r&&n)}}case"toggle-layer":{let n,r=m(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=m(e.activeView);return{activeView:n,transientLayer:null,deckExpanded:(t=!0===e.deckExpanded,"chat"!==n&&t)}}case"set-deck-expanded":{let n,r=m(e.activeView);return{activeView:r,transientLayer:e.transientLayer,deckExpanded:(n=t.expanded,"chat"!==r&&n)}}}}function g(e){let t=Number.isFinite(e)?Math.max(0,e):0;return{availableWidth:t,navigator:t>=u.navigator?"pinned":"drawer",deck:t>=u.deck?"pinned":"view-stack"}}let x=null,v=!1,y=-1/0;function b(e,t=Date.now()){v=e,e||(y=t)}let w=["projects","priority"],k="omp-web:navigator-mode",j="omp-prio-on",S=["omp-relay-session-","omp-cwd-","ompscope_"],C="omp-web:session-opened-at";function N(e,t){if(e)try{let t=JSON.parse(e);if(t&&"object"==typeof t&&"number"==typeof t.since&&Number.isFinite(t.since)){let e={};if(t.opened&&"object"==typeof t.opened)for(let[n,r]of Object.entries(t.opened))"number"==typeof r&&Number.isFinite(r)&&(e[n]=r);return{since:t.since,opened:e}}}catch{}return{since:t,opened:{}}}function T(e,t){let n=null;for(let[r,s]of Object.entries(t.opened))(e.opened[r]??-1/0)>=s||((n??={...e.opened})[r]=s);return!n&&t.since>=e.since?e:{since:Math.min(e.since,t.since),opened:n??e.opened}}function I(e){let t=Date.parse(e.conversationModified??e.modified);return Number.isFinite(t)?t:null}function M(e,t,n){let r=Math.max(n,I(t)??0);return(e.opened[t.id]??-1/0)>=r?e:{since:e.since,opened:{...e.opened,[t.id]:r}}}let E=new Set;function $(e,t){let n=null;for(let r of t)Object.hasOwn(e.opened,r)&&(n??={...e.opened},delete n[r]);return n?{since:e.since,opened:n}:e}function R(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 L(e){let t=new Map;for(let n of e){let e=n.projectRoot??n.cwd;if(!e)continue;let r=R(e),s=t.get(r);(!s||n.modified>s.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 P(e,t){let n=new Map;for(let e of t)"number"==typeof e.order&&Number.isFinite(e.order)&&n.set(R(e.key),e.order);let r=[...e],s=new Set(e.map(R));for(let e of t){let t=R(e.key);!t||s.has(t)||(r.push(e.path??e.key),s.add(t))}return r.map((e,t)=>({project:e,defaultIndex:t,order:n.get(R(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 A=/^<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(A);if(!t)return null;let[,n,,,r]=t;return r?`/skill:${n} ${r}`:`/skill:${n}`}var F=n(84183);let O=`(max-width: ${u.navigator-1}px)`;function z(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 D=z("(max-width: 640px)"),W=z(O);function H(){return!1}function U(){return(0,s.useSyncExternalStore)(D.subscribe,D.getSnapshot,H)}var B=n(13004),q=n.n(B);async function V(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 K(){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 J(){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 G({onCancel:e,onSelect:t,busy:n=!1,error:i}){let{t:l}=(0,F.s)(),[o,c]=(0,s.useState)(null),[d,u]=(0,s.useState)(""),[h,p]=(0,s.useState)(null),[m,f]=(0,s.useState)(!1),[g,x]=(0,s.useState)(""),[v,y]=(0,s.useState)([]),[b,w]=(0,s.useState)(null),[k,j]=(0,s.useState)(null),[S,C]=(0,s.useState)(!0),N=(0,s.useCallback)(async e=>{C(!0),j(null);try{let t=await V(e),n=t.path??e??"/";u(n),p(t.parentPath??null),f(!0===t.upToDrives),x(n),y(t.directories??[]),w(t.drives??null)}catch(e){j(e instanceof Error?e.message:String(e))}finally{C(!1)}},[]);(0,s.useEffect)(()=>{c(document.body),N()},[N]);let T=g.trim()!==d,I=!!d&&!T&&!n,M=!!h||m||/^[a-zA-Z]:[\\/]?$/.test(d);return o?(0,a.createPortal)((0,r.jsx)("div",{className:"directory-picker-backdrop",role:"dialog","aria-modal":"true","aria-label":l("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:"var(--scrim)"},children:(0,r.jsxs)("div",{className:`directory-picker-panel ${q().sheet}`,style:{width:520,maxWidth:"calc(100vw - 16px)",height:"min(620px, calc(100dvh - 16px))",maxHeight:"calc(100dvh - 16px)",display:"flex",flexDirection:"column",overflow:"hidden"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",flexShrink:0,padding:"12px 18px"},children:[(0,r.jsx)("div",{style:{minWidth:0,flex:1},children:(0,r.jsx)("div",{style:{color:"var(--text)",fontWeight:700,fontSize:15},children:l("directoryPicker.selectDirectory")})}),(0,r.jsx)("button",{type:"button",onClick:e,disabled:n,title:l("i18n.close"),"aria-label":l("i18n.close"),className:q().btnQuiet,style:{fontSize:20,lineHeight:1},children:"\xd7"})]}),(0,r.jsxs)("form",{onSubmit:e=>{e.preventDefault();let t=g.trim();t&&N(t)},style:{display:"flex",alignItems:"center",gap:8,flexShrink:0,padding:"10px 14px"},children:[(0,r.jsx)("button",{className:`directory-picker-back ${q().btn}`,type:"button",onClick:()=>void N(h??void 0),disabled:S||!M,title:l("directoryPicker.goToParent"),"aria-label":l("directoryPicker.goToParent"),style:{width:36,height:36,padding:0,flexShrink:0,cursor:M?"pointer":"default"},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"},children:l("directoryPicker.directoryPath")}),(0,r.jsx)("input",{className:`directory-picker-path ${q().field}`,id:"directory-path",type:"text",value:g,placeholder:"/path/to/project or ~/project",autoFocus:!0,autoComplete:"off",spellCheck:!1,onChange:e=>{x(e.target.value),j(null)},style:{minWidth:0,flex:1,height:36,fontFamily:"var(--font-mono)"}}),(0,r.jsx)("button",{className:`directory-picker-action ${q().btn}`,type:"submit",disabled:S||!g.trim(),title:l("directoryPicker.goToDirectory"),style:{minWidth:58,height:36},children:l("directoryPicker.go")})]}),(0,r.jsxs)("div",{className:"directory-picker-list",style:{flex:1,minHeight:0,overflow:"auto",padding:"8px 10px"},children:[S?(0,r.jsx)("div",{style:{padding:8,color:"var(--text-dim)",fontSize:11},children:l("directoryPicker.loadingDirectories")}):null!==b?(0,r.jsx)(r.Fragment,{children:b.length>0?b.map(e=>(0,r.jsxs)("button",{className:`directory-picker-entry ${q().navRow}`,type:"button",onClick:()=>void N(e.path),title:e.path,style:{minHeight:34,gap:7,padding:"6px 8px",color:"var(--text-muted)",fontFamily:"var(--font-mono)",fontSize:11},children:[(0,r.jsx)(J,{}),(0,r.jsx)("span",{children:e.name})]},e.path)):(0,r.jsx)("div",{style:{padding:8,color:"var(--text-dim)",fontSize:11},children:l("directoryPicker.noDrives")})}):v.length>0?v.map(e=>(0,r.jsxs)("button",{className:`directory-picker-entry ${q().navRow}`,type:"button",onClick:()=>void N(e.path),title:e.path,style:{minHeight:30,gap:7,padding:"5px 8px",color:"var(--text-muted)",fontFamily:"var(--font-mono)",fontSize:11},children:[(0,r.jsx)(K,{}),(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:l("directoryPicker.noSubdirectories")}),(k||i)&&(0,r.jsx)("div",{style:{padding:"8px",color:"var(--danger)",fontSize:11},children:k??i})]}),(0,r.jsxs)("div",{className:"directory-picker-footer",style:{display:"flex",justifyContent:"flex-end",alignItems:"center",gap:10,flexShrink:0,padding:"10px 18px"},children:[(0,r.jsx)("button",{className:`directory-picker-action ${q().btn}`,type:"button",onClick:e,disabled:n,style:{padding:"6px 14px",fontSize:13},children:l("i18n.cancel")}),(0,r.jsx)("button",{className:`directory-picker-action ${q().btnPrimary}`,type:"button",onClick:()=>t(d),disabled:!I,title:l(T?"directoryPicker.openBeforeSelecting":"directoryPicker.selectCurrentDirectory"),style:{padding:"6px 16px",fontSize:13},children:l(n?"i18n.checking":"directoryPicker.selectThisFolder")})]})]})}),o):null}var Y=n(21443),Z=n.n(Y);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 X({onCancel:e,onSelect:t,busy:n=!1,error:i}){let{t:l}=(0,F.s)(),o=(0,s.useRef)(null),[c,d]=(0,s.useState)(!1),[u,h]=(0,s.useState)(!1),[p,m]=(0,s.useState)(null),[f,g]=(0,s.useState)([]),[x,v]=(0,s.useState)(""),[y,b]=(0,s.useState)(""),[w,k]=(0,s.useState)(!0),[j,S]=(0,s.useState)(!1),[C,N]=(0,s.useState)(!1),[T,I]=(0,s.useState)(null),[M,E]=(0,s.useState)(!1),[$,R]=(0,s.useState)(50),L=p?.device?.state==="pending",P=n||C,A=(0,s.useCallback)(async()=>{k(!0),I(null);try{let e=await Q("/api/github/projects");m(e),e.connected&&g((await Q("/api/github/projects?view=repositories")).repositories)}catch(e){I(e instanceof Error?e.message:String(e))}finally{k(!1)}},[]);async function _(){S(!0),I(null);try{let{device:e}=await Q("/api/github/projects",{action:"login"});m({connected:!1,login:null,device:e})}catch(e){I(e instanceof Error?e.message:String(e))}finally{S(!1)}}async function O(e){if(e.preventDefault(),y.trim()&&!P){N(!0),I(null);try{let{cwd:e}=await Q("/api/github/projects",{action:"open",repository:y});t(e)}catch(e){I(e instanceof Error?e.message:String(e))}finally{N(!1)}}}if((0,s.useEffect)(()=>{d(!0),A()},[A]),(0,s.useEffect)(()=>{if(!c||u)return;let e=o.current;return e?.showModal(),()=>e?.close()},[c,u]),(0,s.useEffect)(()=>{let e;if(!L||u)return;let t=!1,n=async()=>{try{let e=await Q("/api/github/projects");if(t)return;if(m(e),e.connected)return void await A();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,u,A]),!c)return null;if(u)return(0,r.jsx)(G,{onCancel:()=>h(!1),onSelect:t,busy:n,error:i});let z=f.filter(e=>`${e.fullName} ${e.description??""}`.toLowerCase().includes(x.toLowerCase())),D=T??i??p?.device?.error;return(0,a.createPortal)((0,r.jsx)("dialog",{ref:o,className:Z().dialog,"aria-labelledby":"cloud-project-title",onCancel:t=>{t.preventDefault(),P||e()},children:(0,r.jsxs)("form",{onSubmit:O,className:Z().form,children:[(0,r.jsxs)("header",{className:Z().header,children:[(0,r.jsx)("h2",{id:"cloud-project-title",children:l("cloudProjects.title")}),(0,r.jsx)("p",{children:l("cloudProjects.description")})]}),(0,r.jsxs)("div",{className:Z().sources,children:[(0,r.jsx)("span",{className:Z().activeSource,children:l("cloudProjects.github")}),(0,r.jsx)("button",{type:"button",onClick:()=>h(!0),disabled:P,children:l("cloudProjects.serverFolder")})]}),(0,r.jsxs)("div",{className:Z().body,children:[(0,r.jsxs)("section",{className:Z().account,"aria-label":l("cloudProjects.account"),children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("strong",{children:p?.connected?p.login:l("cloudProjects.connectTitle")}),(0,r.jsx)("p",{children:p?.connected?l("cloudProjects.connected"):l("cloudProjects.connectHelp")})]}),p?.connected?(0,r.jsx)("button",{type:"button",className:Z().secondary,onClick:()=>void A(),disabled:w||P,children:l("cloudProjects.refresh")}):(0,r.jsx)("button",{type:"button",className:Z().secondary,onClick:()=>void _(),disabled:w||j||L||P,children:j||L?l("cloudProjects.waiting"):l("cloudProjects.connect")})]}),L&&(0,r.jsxs)("div",{className:Z().login,role:"status",children:[(0,r.jsx)("p",{children:l("cloudProjects.deviceHelp")}),p.device?.code?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("div",{className:Z().codeRow,children:[(0,r.jsx)("code",{children:p.device.code}),(0,r.jsx)("button",{type:"button",className:Z().secondary,onClick:()=>{navigator.clipboard.writeText(p.device.code).then(()=>E(!0)).catch(()=>I(l("cloudProjects.copyFailure")))},children:M?l("cloudProjects.copied"):l("cloudProjects.copyCode")})]}),(0,r.jsx)("a",{href:"https://github.com/login/device",target:"_blank",rel:"noreferrer",className:Z().loginLink,children:l("cloudProjects.openLogin")}),(0,r.jsx)("small",{children:l("cloudProjects.permissionHelp")})]}):(0,r.jsx)("p",{children:l("cloudProjects.preparingCode")})]}),p?.connected&&(0,r.jsxs)("section",{className:Z().repositories,"aria-label":l("cloudProjects.repositories"),children:[(0,r.jsx)("label",{htmlFor:"cloud-repo-search",children:l("cloudProjects.search")}),(0,r.jsx)("input",{id:"cloud-repo-search",value:x,onChange:e=>{v(e.target.value),R(50)},placeholder:l("cloudProjects.searchPlaceholder"),type:"search",disabled:P}),w?(0,r.jsx)("p",{role:"status",children:l("cloudProjects.loading")}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("ul",{className:Z().list,children:z.slice(0,$).map(e=>(0,r.jsx)("li",{children:(0,r.jsxs)("button",{type:"button",className:Z().repo,"aria-pressed":y===e.fullName,disabled:P,onClick:()=>b(e.fullName),children:[(0,r.jsxs)("span",{className:Z().repoHeading,children:[(0,r.jsx)("strong",{children:e.fullName}),(0,r.jsx)("small",{children:e.private?l("cloudProjects.private"):l("cloudProjects.public")})]}),e.description&&(0,r.jsx)("span",{className:Z().repoDescription,children:e.description})]})},e.fullName))}),!z.length&&(0,r.jsx)("p",{children:l("cloudProjects.empty")}),z.length>$&&(0,r.jsx)("button",{type:"button",className:Z().secondary,onClick:()=>R(e=>e+50),children:l("cloudProjects.more")})]})]}),(0,r.jsxs)("div",{className:Z().repositoryInput,children:[(0,r.jsx)("label",{htmlFor:"cloud-repository",children:l("cloudProjects.urlLabel")}),(0,r.jsx)("input",{id:"cloud-repository",value:y,onChange:e=>b(e.target.value),placeholder:"owner/repository",autoComplete:"off",spellCheck:!1,disabled:P,"aria-describedby":"cloud-repo-help"}),(0,r.jsx)("small",{id:"cloud-repo-help",children:l("cloudProjects.publicHelp")})]}),D&&(0,r.jsxs)("div",{className:Z().error,role:"alert",children:[(0,r.jsx)("strong",{children:l("cloudProjects.error")}),(0,r.jsx)("p",{children:D}),(0,r.jsx)("button",{type:"button",className:Z().secondary,onClick:()=>void A(),disabled:P,children:l("cloudProjects.refresh")})]}),C&&(0,r.jsx)("p",{role:"status",className:Z().progress,children:l("cloudProjects.openingHelp")})]}),(0,r.jsxs)("footer",{className:Z().footer,children:[(0,r.jsx)("button",{type:"button",className:Z().secondary,onClick:e,disabled:P,children:l("i18n.cancel")}),(0,r.jsx)("button",{type:"submit",className:Z().primary,disabled:P||!y.trim(),children:P?l("cloudProjects.opening"):l("cloudProjects.open")})]})]})}),document.body)}function ee({label:e="CUELO",markSize:t=22,gap:n=10,style:s,labelStyle:a}){return(0,r.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:n,minWidth:0,color:"var(--text)",...s},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 et=n(2730);let en={ko:{"translator.more":"더보기","translator.keyboard":"글자로 입력","translator.keyboardClose":"글자 입력 닫기","translator.volumeHint":"소리가 안 나면 폰의 미디어 음량을 올려 주세요.","translator.source":"입력 언어","translator.swapDirection":"방향 바꾸기","translator.typeLabel":"번역할 문장","translator.typePlaceholder":"여행 중 전할 말을 입력하세요.","translator.typeSubmit":"번역","translator.typePending":"번역 중…","translator.typeError":"번역하지 못했어요. 다시 시도해 주세요.","translator.typeAuth":"Codex 로그인 상태를 확인해 주세요.","translator.assistMeaning":"속뜻과 전달 확인","translator.assistMeaningHint":"대화 속 숨은 뜻과 타자 통역의 전달 내용을 확인합니다.","translator.assistNuance":"속뜻","translator.assistWarning":"전달 확인","translator.assistBackTranslation":"다시 옮기면","translator.assistNumberWarning":"원문과 통역의 숫자가 다릅니다. 확인해 주세요.","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":"통역 기록","translator.mood":"분위기","translator.mood.casual":"편하게","translator.mood.polite":"정중하게","translator.mood.formal":"격식 있게","translator.mood.haggling":"흥정","translator.mood.urgent":"긴급","translator.gender":"내 성별","translator.gender.male":"남성","translator.gender.female":"여성","translator.age":"내 나이대","translator.age.20s":"20대","translator.age.30s":"30대","translator.age.40s":"40대","translator.age.50s":"50대","translator.age.60s":"60대 이상","translator.partnerGender":"상대 성별","translator.partnerAge":"상대 나이","translator.partnerAge.child":"아이","translator.partnerAge.younger":"나보다 어리거나 비슷","translator.partnerAge.older":"나보다 위","translator.partnerAge.parent":"부모님 또래","translator.partnerAge.grandparent":"조부모님 또래","translator.notSet":"선택 안 함","translator.face":"마주보기","translator.faceHint":"상대 쪽 자막을 뒤집어 마주 앉은 사람이 읽게 합니다","translator.reconnecting":"다시 연결 중…","translator.idleStopped":"한동안 대화가 없어 통역을 멈췄습니다. 다시 시작하면 앞 대화에 이어집니다.","translator.generationSkipped":"방금 말은 통역하지 못하고 넘어갔습니다. 이어서 말씀하시면 계속 통역합니다.","translator.setup":"언어\xb7상황 설정","translator.sizeDown":"글자 작게","translator.sizeUp":"글자 크게","translator.faceExit":"마주보기 끄기","translator.translating":"옮기는 중…","translator.errorStatus":"통역이 멈췄습니다","translator.translation":"통역","translator.unknownLanguage":"언어 모름","translator.jumpLatest":"최근 말로","translator.voice":"통역 음성 듣기","translator.voiceHint":"끄면 통역을 글로만 보여 줍니다. 스피커가 조용하니 마이크를 막지 않아 통역 중에 끼어든 말도 들립니다.","translator.echoGuard":"통역 음성이 나올 때 마이크 끄기","translator.echoGuardHint":"스피커로 나온 통역이 다시 통역되지 않게 합니다. 그동안 상대가 한 말은 들리지 않으니 이어폰을 쓰면 꺼 두세요.","translator.naturalVoice":"자연스러운 목소리로 읽기 (ElevenLabs)","translator.naturalVoiceHint":"통역 음성과 들려주기를 ElevenLabs 목소리로 읽습니다. 크레딧을 쓰고, 안 되면 폰 기본 목소리로 읽습니다.","translator.naturalVoiceButtonHint":"들려주기 버튼만 ElevenLabs 목소리로 읽고, 이 엔진의 통역 음성은 그대로입니다. 안 되면 폰 기본 목소리로 읽습니다.","translator.noiseSuppression":"AI 소음 제거","translator.fastDrafts":"빠른 초안 자막","translator.fastDraftsHint":"전용 번역 모델이 초안 자막을 먼저 띄우고 Codex가 곧 바로잡습니다. 켜 둔 동안 추가 요금이 들 수 있습니다.","translator.noiseSuppressionHint":"시끄러운 곳에서 마이크 소음을 줄여 통역이 말을 더 잘 알아듣게 합니다. 목소리가 뭉개지면 꺼 두세요.","translator.cardTitle":"크게 보여 주기","translator.cardClose":"닫기","translator.speak":"들려주기","translator.speakStop":"그만 읽기","translator.speakFailed":"읽어 주는 소리를 재생하지 못했어요. 다시 시도해 주세요.","translator.share":"대화 공유","translator.shareTitle":"CUELO 통역 기록","translator.shareCopied":"대화를 복사했어요. 붙여 넣어 보내세요.","translator.shareFailed":"대화를 복사하지 못했어요.","translator.phrases":"자주 쓰는 문장","translator.phrasesClose":"자주 쓰는 문장 닫기","translator.phrases.food":"음식과 알레르기","translator.phrases.restroom":"화장실","translator.phrases.payment":"계산","translator.phrases.directions":"길 묻기","translator.phrases.emergency":"응급","translator.phrasesMine":"내 문장","translator.phrasesTranslateAll":"모두 미리 번역","translator.phrasesRemaining":"아직 번역하지 않은 문장 {count}개","translator.phrasesAllCached":"모두 번역해 뒀어요. 데이터가 끊겨도 쓸 수 있어요.","translator.phrasesNoBuiltIn":"기본 문장은 내 언어가 한국어나 영어일 때 보여요. 아래에 직접 더할 수 있어요.","translator.phraseNotCached":"아직 번역 전","translator.phraseFailed":"번역하지 못했어요. 눌러서 다시 시도","translator.phraseAddLabel":"문장 더하기","translator.phraseAddPlaceholder":"자주 하는 말을 적어 두세요","translator.phraseAdd":"추가","translator.phraseDelete":"지우기: {text}","translator.scan":"메뉴판과 간판 사진","translator.scan.title":"메뉴판과 간판 해설","translator.scan.close":"닫기","translator.scan.takePhoto":"사진 찍기","translator.scan.pickAlbum":"앨범에서 고르기","translator.scan.avoidLabel":"내가 못 먹는 것","translator.scan.avoidPlaceholder":"예: 새우, 땅콩","translator.scan.avoidHint":"적어 두면 해당 메뉴에 경고를 표시해요. 이 기기에만 저장돼요.","translator.scan.pickHint":"메뉴판이나 간판을 찍으면 항목별로 번역하고 설명해요.","translator.scan.loading":"사진을 읽는 중이에요","translator.scan.error":"사진을 읽지 못했어요.","translator.scan.authError":"Codex 로그인이 필요해요.","translator.scan.retry":"다시 시도","translator.scan.empty":"읽을 수 있는 글자가 없어요.","translator.scan.show":"보여주기","translator.scan.pick":"합계에 넣기","translator.scan.total":"고른 {count}개 합계","translator.scan.missing":"가격이 없는 {count}개는 빠졌어요","translator.scan.avoidChanged":"못 먹는 것을 바꿨어요. 이 사진을 다시 풀 수 있어요.","translator.scan.rescan":"다시 보기","translator.scan.warning":"주의"},en:{"translator.more":"More","translator.keyboard":"Type a message","translator.keyboardClose":"Close text input","translator.volumeHint":"If you hear nothing, turn up your phone's media volume.","translator.source":"Input language","translator.swapDirection":"Swap direction","translator.typeLabel":"Text to translate","translator.typePlaceholder":"Type what you want to say.","translator.typeSubmit":"Translate","translator.typePending":"Translating…","translator.typeError":"Translation failed. Try again.","translator.typeAuth":"Check your Codex sign-in.","translator.assistMeaning":"Implied meaning and delivery check","translator.assistMeaningHint":"Shows implied meaning in conversation and checks how typed interpretation comes across.","translator.assistNuance":"Implied meaning","translator.assistWarning":"Delivery check","translator.assistBackTranslation":"Translated back","translator.assistNumberWarning":"Numbers in the original and interpretation differ. Please check.","translator.tab":"Interpret","translator.title":"Interpreter","translator.back":"Back to chat","translator.panelHint":"Start interpreting and Codex Live on your ChatGPT account speaks each person's words in the other's language right away. It bypasses work sessions and harness rules. The voice conversation stays on this phone only; Clear removes it.","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","translator.mood":"Mood","translator.mood.casual":"Casual","translator.mood.polite":"Polite","translator.mood.formal":"Formal","translator.mood.haggling":"Haggling","translator.mood.urgent":"Urgent","translator.gender":"My gender","translator.gender.male":"Male","translator.gender.female":"Female","translator.age":"My age","translator.age.20s":"20s","translator.age.30s":"30s","translator.age.40s":"40s","translator.age.50s":"50s","translator.age.60s":"60+","translator.partnerGender":"Their gender","translator.partnerAge":"Their age","translator.partnerAge.child":"Child","translator.partnerAge.younger":"Younger or same age","translator.partnerAge.older":"Older than me","translator.partnerAge.parent":"My parents' age","translator.partnerAge.grandparent":"My grandparents' age","translator.notSet":"Not set","translator.face":"Face to face","translator.faceHint":"Flip the other side's captions so the person across from you can read them","translator.reconnecting":"Reconnecting…","translator.idleStopped":"Interpreting stopped after a long silence. Start again to continue the conversation.","translator.generationSkipped":"That last line couldn't be interpreted and was skipped. Keep talking; interpreting continues.","translator.setup":"Languages and setting","translator.sizeDown":"Smaller text","translator.sizeUp":"Larger text","translator.faceExit":"Leave face to face","translator.translating":"Interpreting…","translator.errorStatus":"Interpreting stopped","translator.translation":"Interpretation","translator.unknownLanguage":"Language unknown","translator.jumpLatest":"Jump to latest","translator.voice":"Play the interpretation aloud","translator.voiceHint":"Off, the interpretation is shown as text only. With the speaker silent the mic stays open, so words spoken over an interpretation are heard too.","translator.echoGuard":"Mute the mic while the interpretation plays","translator.echoGuardHint":"Keeps the speaker's interpretation from being interpreted again. Words spoken meanwhile are not heard, so turn it off with earphones.","translator.naturalVoice":"Read with a natural voice (ElevenLabs)","translator.naturalVoiceHint":"Reads the interpretation and Read aloud with an ElevenLabs voice. Uses credits; falls back to the phone voice.","translator.naturalVoiceButtonHint":"Only the Read aloud button uses the ElevenLabs voice; this engine's interpretation audio is unchanged. Falls back to the phone voice.","translator.noiseSuppression":"AI noise suppression","translator.fastDrafts":"Quick draft captions","translator.fastDraftsHint":"A dedicated translation model shows a quick draft first and Codex corrects it. Extra charges may apply while this is on.","translator.noiseSuppressionHint":"Cuts background noise from the mic in a loud place so the interpreter hears you better. Turn it off if your voice sounds muffled.","translator.cardTitle":"Show full screen","translator.cardClose":"Close","translator.speak":"Read aloud","translator.speakStop":"Stop reading","translator.speakFailed":"Couldn’t play the audio. Try again.","translator.share":"Share conversation","translator.shareTitle":"CUELO interpretation log","translator.shareCopied":"Conversation copied. Paste it to send.","translator.shareFailed":"Couldn't copy the conversation.","translator.phrases":"Saved phrases","translator.phrasesClose":"Close saved phrases","translator.phrases.food":"Food and allergies","translator.phrases.restroom":"Restroom","translator.phrases.payment":"Paying","translator.phrases.directions":"Directions","translator.phrases.emergency":"Emergency","translator.phrasesMine":"My phrases","translator.phrasesTranslateAll":"Translate all now","translator.phrasesRemaining":"{count} phrases not translated yet","translator.phrasesAllCached":"All phrases are translated and work offline.","translator.phrasesNoBuiltIn":"Built-in phrases appear when your language is Korean or English. You can add your own below.","translator.phraseNotCached":"Not translated yet","translator.phraseFailed":"Translation failed. Tap to retry","translator.phraseAddLabel":"Add a phrase","translator.phraseAddPlaceholder":"Type something you say often","translator.phraseAdd":"Add","translator.phraseDelete":"Delete: {text}","translator.scan":"Menu or sign photo","translator.scan.title":"Menu and sign help","translator.scan.close":"Close","translator.scan.takePhoto":"Take photo","translator.scan.pickAlbum":"Choose from album","translator.scan.avoidLabel":"Foods I avoid","translator.scan.avoidPlaceholder":"e.g. shrimp, peanuts","translator.scan.avoidHint":"Matching dishes get a warning. Saved on this device only.","translator.scan.pickHint":"Photograph a menu or sign to get each item translated and explained.","translator.scan.loading":"Reading the photo","translator.scan.error":"Could not read the photo.","translator.scan.authError":"Codex sign-in required.","translator.scan.retry":"Try again","translator.scan.empty":"No readable text found.","translator.scan.show":"Show","translator.scan.pick":"Add to total","translator.scan.total":"Total of {count} picked","translator.scan.missing":"{count} without a price left out","translator.scan.avoidChanged":"You changed what you avoid. This photo can be read again.","translator.scan.rescan":"Read again","translator.scan.warning":"Warning"}};function er(){let{locale:e}=(0,F.s)();return{tt:(0,s.useCallback)((t,n)=>(0,et.u0)(e,t,en,n),[e]),locale:e}}let es={en:{issueLabel:"GitHub issue (optional)",issuePlaceholder:"#123 or GitHub issue URL",issueStart:"Start issue session",issueBusy:"Starting…",fallbackBase:"Fetch failed; started from local {branch}"},ko:{issueLabel:"GitHub 이슈 (선택)",issuePlaceholder:"#123 또는 GitHub 이슈 URL",issueStart:"이슈 세션 시작",issueBusy:"시작 중…",fallbackBase:"가져오기 실패; 로컬 {branch}에서 시작됨"},zh:{issueLabel:"GitHub Issue(可选)",issuePlaceholder:"#123 或 GitHub Issue URL",issueStart:"开始 Issue 会话",issueBusy:"正在启动…",fallbackBase:"拉取失败;已从本地 {branch} 启动"}},ea={en:"The subdirectory {path} is not in this worktree; opened its root instead",ko:"이 워크트리에 하위 디렉터리 {path}이(가) 없어 루트 디렉터리를 대신 열었습니다",zh:"此工作树中不存在子目录 {path},已改为打开其根目录"};function ei(e,t){if(t)try{sessionStorage.setItem(`cuelo:worktree:${e}`,JSON.stringify(t))}catch{}}let el="application/x-cuelo-session",eo=(0,s.createContext)(null);function ec(){return(0,s.useContext)(eo)}let ed=(0,s.createContext)(null);function eu({label:e,x:t,y:n,items:i,onClose:l}){let o=(0,s.useRef)(null),[c,d]=(0,s.useState)({left:t,top:n});return(0,s.useLayoutEffect)(()=>{let e=o.current;if(!e)return;let r=e.getBoundingClientRect();d({left:Math.max(8,Math.min(t,window.innerWidth-r.width-8)),top:Math.max(8,Math.min(n,window.innerHeight-r.height-8))}),e.querySelector('button:not([aria-disabled="true"])')?.focus()},[t,n]),(0,s.useEffect)(()=>{let e=e=>{e.target instanceof Node&&o.current?.contains(e.target)||l()};return document.addEventListener("pointerdown",e,!0),window.addEventListener("blur",l),window.addEventListener("resize",l),()=>{document.removeEventListener("pointerdown",e,!0),window.removeEventListener("blur",l),window.removeEventListener("resize",l)}},[l]),(0,a.createPortal)((0,r.jsx)("div",{ref:o,className:"session-row-menu",role:"menu","aria-label":e,style:{left:c.left,top:c.top},onKeyDown:e=>{if("Escape"===e.key||"Tab"===e.key){e.preventDefault(),e.stopPropagation(),l();return}if("ArrowDown"!==e.key&&"ArrowUp"!==e.key)return;e.preventDefault();let t=[...o.current?.querySelectorAll('button:not([aria-disabled="true"])')??[]];if(0===t.length)return;let n=t.findIndex(e=>e===document.activeElement),r="ArrowDown"===e.key?1:-1;t[(n+r+t.length)%t.length]?.focus()},onClick:e=>e.stopPropagation(),onContextMenu:e=>e.preventDefault(),children:i.map(e=>(0,r.jsx)("button",{type:"button",role:"menuitem","aria-disabled":!!e.disabledReason||void 0,title:e.disabledReason??void 0,onClick:()=>{e.disabledReason||(l(),e.onSelect())},children:e.label},e.id))}),document.body)}let eh={folder:(0,r.jsx)("path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z"}),"list-ordered":(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("path",{d:"M10 12h11"}),(0,r.jsx)("path",{d:"M10 18h11"}),(0,r.jsx)("path",{d:"M10 6h11"}),(0,r.jsx)("path",{d:"M4 10h2"}),(0,r.jsx)("path",{d:"M4 6h1v4"}),(0,r.jsx)("path",{d:"M6 18H4c0-1 2-2 2-3s-1-1.5-2-1"})]}),languages:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("path",{d:"m5 8 6 6"}),(0,r.jsx)("path",{d:"m4 14 6-6 2-3"}),(0,r.jsx)("path",{d:"M2 5h12"}),(0,r.jsx)("path",{d:"M7 2h1"}),(0,r.jsx)("path",{d:"m22 22-5-10-5 10"}),(0,r.jsx)("path",{d:"M14 18h6"})]}),repeat:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("path",{d:"m17 2 4 4-4 4"}),(0,r.jsx)("path",{d:"M3 11v-1a4 4 0 0 1 4-4h14"}),(0,r.jsx)("path",{d:"m7 22-4-4 4-4"}),(0,r.jsx)("path",{d:"M21 13v1a4 4 0 0 1-4 4H3"})]}),activity:(0,r.jsx)("path",{d:"M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2"}),settings:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("path",{d:"M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z"}),(0,r.jsx)("circle",{cx:"12",cy:"12",r:"3"})]}),"panel-right":(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}),(0,r.jsx)("path",{d:"M15 3v18"})]}),"panel-left":(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}),(0,r.jsx)("path",{d:"M9 3v18"})]}),"columns-2":(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}),(0,r.jsx)("path",{d:"M12 3v18"})]}),globe:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"10"}),(0,r.jsx)("path",{d:"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20"}),(0,r.jsx)("path",{d:"M2 12h20"})]}),menu:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("line",{x1:"4",x2:"20",y1:"12",y2:"12"}),(0,r.jsx)("line",{x1:"4",x2:"20",y1:"6",y2:"6"}),(0,r.jsx)("line",{x1:"4",x2:"20",y1:"18",y2:"18"})]}),"chevron-right":(0,r.jsx)("path",{d:"m9 18 6-6-6-6"}),"chevron-up":(0,r.jsx)("path",{d:"m18 15-6-6-6 6"}),"chevron-down":(0,r.jsx)("path",{d:"m6 9 6 6 6-6"}),"circle-check":(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"10"}),(0,r.jsx)("path",{d:"m9 12 2 2 4-4"})]}),"circle-alert":(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"10"}),(0,r.jsx)("line",{x1:"12",x2:"12",y1:"8",y2:"12"}),(0,r.jsx)("line",{x1:"12",x2:"12.01",y1:"16",y2:"16"})]}),ellipsis:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"1"}),(0,r.jsx)("circle",{cx:"19",cy:"12",r:"1"}),(0,r.jsx)("circle",{cx:"5",cy:"12",r:"1"})]}),x:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("path",{d:"M18 6 6 18"}),(0,r.jsx)("path",{d:"m6 6 12 12"})]}),check:(0,r.jsx)("path",{d:"M20 6 9 17l-5-5"}),"message-square":(0,r.jsx)("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"}),"messages-square":(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("path",{d:"M14 9a2 2 0 0 1-2 2H6l-4 4V4a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2z"}),(0,r.jsx)("path",{d:"M18 9h2a2 2 0 0 1 2 2v11l-4-4h-6a2 2 0 0 1-2-2v-1"})]}),"list-tree":(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("path",{d:"M21 12h-8"}),(0,r.jsx)("path",{d:"M21 6H8"}),(0,r.jsx)("path",{d:"M21 18h-8"}),(0,r.jsx)("path",{d:"M3 6v4c0 1.1.9 2 2 2h3"}),(0,r.jsx)("path",{d:"M3 10v6c0 1.1.9 2 2 2h3"})]}),bot:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("path",{d:"M12 8V4H8"}),(0,r.jsx)("rect",{width:"16",height:"12",x:"4",y:"8",rx:"2"}),(0,r.jsx)("path",{d:"M2 14h2"}),(0,r.jsx)("path",{d:"M20 14h2"}),(0,r.jsx)("path",{d:"M15 13v2"}),(0,r.jsx)("path",{d:"M9 13v2"})]}),"file-text":(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z"}),(0,r.jsx)("path",{d:"M14 2v4a2 2 0 0 0 2 2h4"}),(0,r.jsx)("path",{d:"M10 9H8"}),(0,r.jsx)("path",{d:"M16 13H8"}),(0,r.jsx)("path",{d:"M16 17H8"})]}),users:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"}),(0,r.jsx)("circle",{cx:"9",cy:"7",r:"4"}),(0,r.jsx)("path",{d:"M22 21v-2a4 4 0 0 0-3-3.87"}),(0,r.jsx)("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]}),"user-round":(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("circle",{cx:"12",cy:"8",r:"5"}),(0,r.jsx)("path",{d:"M20 21a8 8 0 0 0-16 0"})]}),gauge:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("path",{d:"m12 14 4-4"}),(0,r.jsx)("path",{d:"M3.34 19a10 10 0 1 1 17.32 0"})]}),puzzle:(0,r.jsx)("path",{d:"M15.39 4.39a1 1 0 0 0 1.68-.474 2.5 2.5 0 1 1 3.014 3.015 1 1 0 0 0-.474 1.68l1.683 1.682a2.414 2.414 0 0 1 0 3.414L19.61 15.39a1 1 0 0 1-1.68-.474 2.5 2.5 0 1 0-3.014 3.015 1 1 0 0 1 .474 1.68l-1.683 1.682a2.414 2.414 0 0 1-3.414 0L8.61 19.61a1 1 0 0 0-1.68.474 2.5 2.5 0 1 1-3.014-3.015 1 1 0 0 0 .474-1.68l-1.683-1.682a2.414 2.414 0 0 1 0-3.414L4.39 8.61a1 1 0 0 1 1.68.474 2.5 2.5 0 1 0 3.014-3.015 1 1 0 0 1-.474-1.68l1.683-1.682a2.414 2.414 0 0 1 3.414 0z"}),brain:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("path",{d:"M12 5a3 3 0 1 0-5.997.125 4 4 0 0 0-2.526 5.77 4 4 0 0 0 .556 6.588A4 4 0 1 0 12 18Z"}),(0,r.jsx)("path",{d:"M12 5a3 3 0 1 1 5.997.125 4 4 0 0 1 2.526 5.77 4 4 0 0 1-.556 6.588A4 4 0 1 1 12 18Z"}),(0,r.jsx)("path",{d:"M15 13a4.5 4.5 0 0 1-3-4 4.5 4.5 0 0 1-3 4"}),(0,r.jsx)("path",{d:"M17.599 6.5a3 3 0 0 0 .399-1.375"}),(0,r.jsx)("path",{d:"M6.003 5.125A3 3 0 0 0 6.401 6.5"}),(0,r.jsx)("path",{d:"M3.477 10.896a4 4 0 0 1 .585-.396"}),(0,r.jsx)("path",{d:"M19.938 10.5a4 4 0 0 1 .585.396"}),(0,r.jsx)("path",{d:"M6 18a4 4 0 0 1-1.967-.516"}),(0,r.jsx)("path",{d:"M19.967 17.484A4 4 0 0 1 18 18"})]}),"chart-column":(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("path",{d:"M3 3v16a2 2 0 0 0 2 2h16"}),(0,r.jsx)("path",{d:"M18 17V9"}),(0,r.jsx)("path",{d:"M13 17V5"}),(0,r.jsx)("path",{d:"M8 17v-3"})]}),"maximize-2":(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("polyline",{points:"15 3 21 3 21 9"}),(0,r.jsx)("polyline",{points:"9 21 3 21 3 15"}),(0,r.jsx)("line",{x1:"21",x2:"14",y1:"3",y2:"10"}),(0,r.jsx)("line",{x1:"3",x2:"10",y1:"21",y2:"14"})]}),search:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("circle",{cx:"11",cy:"11",r:"8"}),(0,r.jsx)("path",{d:"m21 21-4.3-4.3"})]})};function ep({name:e,size:t=16}){return(0,r.jsx)("svg",{className:"workbench-icon",width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",focusable:"false",children:eh[e]})}function em({size:e=28}){return(0,r.jsx)("svg",{className:"workbench-mark",width:e,height:e,viewBox:"0 0 100 100","aria-hidden":"true",focusable:"false",children:(0,r.jsxs)("g",{transform:"translate(15 15) scale(0.7)",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)"})]})})}let ef="omp-web:unread-session-ids",eg="omp-web:pinned-session-ids",ex="omp-web:removed-projects";function ev(e,t){return{minHeight:t?44:30,padding:"3px 10px",border:0,borderRadius:"var(--radius-control)",background:"var(--bg-hover)",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 ey(e,t){return t&&e.startsWith(t)?"~"+e.slice(t.length):e}function eb({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 ew({open:e,children:t,style:n}){let[a,i]=(0,s.useState)(e),[l,o]=(0,s.useState)(e);return((0,s.useEffect)(()=>{let t,n;return e?(i(!0),o(!1),t=window.requestAnimationFrame(()=>{t=window.requestAnimationFrame(()=>o(!0))})):(o(!1),n=setTimeout(()=>i(!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 ek="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*";function ej(){let[e,t]=(0,s.useState)(!1),[n,a]=(0,s.useState)(!1),i=(0,s.useRef)(null),l=function(e,t){let[n,r]=(0,s.useState)(e),a=(0,s.useRef)(null),i=(0,s.useRef)(0);return(0,s.useEffect)(()=>{if(!t)return void r(e);i.current=0;let n=4*e.length,s=()=>{i.current+=1;let t=Math.floor(i.current/n*e.length);r(e.split("").map((e,n)=>" "===e?" ":n<t?e:ek[Math.floor(Math.random()*ek.length)]).join("")),i.current<n?a.current=requestAnimationFrame(s):r(e)};return a.current=requestAnimationFrame(s),()=>{a.current&&cancelAnimationFrame(a.current)}},[e,t]),n}(e?"0.10.359/19.1.1":"CUELO",n),o=(0,s.useCallback)(e=>{t(e),a(!0),setTimeout(()=>a(!1),(e?6:8)*4*(1e3/60)+100)},[]),c=(0,s.useCallback)(()=>{i.current&&clearTimeout(i.current);let t=!e;o(t),t&&(i.current=setTimeout(()=>o(!1),3e3))},[e,o]);return(0,s.useEffect)(()=>()=>{i.current&&clearTimeout(i.current)},[]),(0,r.jsx)("button",{className:"navigator-brand",onClick:c,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)(ee,{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 eC({selectedSessionId:e,optimisticSession:t,onSelectSession:n,onNewSession:a,initialSessionId:i,skipInitialProjectSelection:l,onInitialRestoreDone:o,refreshKey:c,onSessionDeleted:d,selectedCwd:u,onCwdChange:h,onBackgroundTaskDone:p,translatorPanel:m,translatorActive:f=!1,navigatorMode:g="projects",onActivityChange:x}){let v,{tt:y}=er(),{t:b,locale:w}=(0,F.s)(),k=U(),[j,A]=(0,s.useState)([]),_=(0,s.useMemo)(()=>t&&!j.some(e=>e.id===t.id)?[t,...j]:j,[j,t]),[O,z]=(0,s.useState)(!0),[D,W]=(0,s.useState)(null),[H,B]=(0,s.useState)(null),[q,V]=(0,s.useState)(""),[K,J]=(0,s.useState)(!1),[Y,Z]=(0,s.useState)(""),[Q,ee]=(0,s.useState)(()=>new Set),[et,en]=(0,s.useState)(()=>new Set),[el,eo]=(0,s.useState)(null),[ed,eu]=(0,s.useState)(null),[eh,ep]=(0,s.useState)({version:1,projects:[]}),[em,ek]=(0,s.useState)(!1),[eT,e$]=(0,s.useState)(!1),[eR,eL]=(0,s.useState)(!1),[eA,e_]=(0,s.useState)(null),[eF,eO]=(0,s.useState)(""),[ez,eD]=(0,s.useState)(!1),[eW,eH]=(0,s.useState)(null),[eU,eB]=(0,s.useState)(""),[eq,eV]=(0,s.useState)(!1),[eK,eJ]=(0,s.useState)(null),[eG,eY]=(0,s.useState)(!1),[eZ,eQ]=(0,s.useState)(null),[eX,e0]=(0,s.useState)(!1),[e1,e2]=(0,s.useState)(!1),[e4,e8]=(0,s.useState)(""),[e5,e6]=(0,s.useState)(null),[e3,e7]=(0,s.useState)(""),[e9,te]=(0,s.useState)(!1),[tt,tn]=(0,s.useState)(null),tr=(0,s.useRef)(null),[ts,ta]=(0,s.useState)(!1),[ti,tl]=(0,s.useState)(null),to=(0,s.useRef)(null),tc=(0,s.useRef)(null),td=(0,s.useRef)(null),tu=(0,s.useRef)(!1),th=(0,s.useRef)(!1),[tp,tm]=(0,s.useState)(!1),[tf,tg]=(0,s.useState)(()=>new Set),[tx,tv]=(0,s.useState)(()=>new Set),[ty,tb]=(0,s.useState)(()=>(function(){try{let e=window.localStorage.getItem(ef);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}})()),[tw,tk]=(0,s.useState)(()=>new Set),[tj,tS]=(0,s.useState)(null),[tC,tN]=(0,s.useState)(!1),tT=(0,s.useRef)(new Set),tI=(0,s.useRef)(!1),tM=(0,s.useRef)(null);(0,s.useEffect)(()=>{tk(function(){try{let e=window.localStorage.getItem(eg);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}}())},[]),(0,s.useEffect)(()=>{let e=null;try{e=window.localStorage.getItem(C)}catch{}tS(N(e,Date.now()));let t=e=>{if(e.key!==C||null===e.newValue)return;let t=N(e.newValue,Date.now());tS(e=>e?T(e,t):e)};return window.addEventListener("storage",t),()=>window.removeEventListener("storage",t)},[]);let tE=(0,s.useCallback)(async()=>{try{let e=await fetch("/api/projects",{cache:"no-store",signal:AbortSignal.timeout(5e3)});if(!e.ok)throw Error(`HTTP ${e.status}`);ep(await e.json())}catch{ep({version:1,projects:[]})}finally{ek(!0)}},[]);(0,s.useEffect)(()=>{tE()},[tE,c]),(0,s.useEffect)(()=>{let e=null;try{e=window.localStorage.getItem(ex)}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:R(e),path:e,hidden:!0})))}}catch{return}try{window.localStorage.removeItem(ex)}catch{}await tE()})()},[tE]);let t$=(0,s.useCallback)(async e=>{if(th.current)throw Error("Project update in progress");th.current=!0,eD(!0);try{await eS(e),await tE()}finally{th.current=!1,eD(!1)}},[tE]);(0,s.useEffect)(()=>{eA&&td.current?.select()},[eA]);let tR=(0,s.useCallback)(async(e=!1,t=!1)=>{try{e&&z(!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();A(r.sessions),tI.current||tg(new Set(r.runningSessionIds??[])),W(null),e||(tm(!0),tM.current&&clearTimeout(tM.current),tM.current=setTimeout(()=>tm(!1),2e3))}catch(e){W(String(e))}finally{e&&z(!1)}},[]),tL=(0,s.useCallback)(e=>{tb(t=>{if(!t.has(e))return t;let n=new Set(t);return n.delete(e),n}),tk(t=>{if(!t.has(e))return t;let n=new Set(t);return n.delete(e),n}),tS(t=>t&&$(t,[e])),d?.(e),tR()},[tR,d]),[tP,tA]=(0,s.useState)(null),[t_,tF]=(0,s.useState)(!1),[tO,tz]=(0,s.useState)(null),tD=(0,s.useCallback)(()=>{t_||(tA(null),tz(null))},[t_]),tW=(0,s.useCallback)(async e=>{tF(!0),tz(null);let t=[],n=[],r=[];for(let s of e)if(!s.transient)try{let e=await fetch(`/api/sessions/${encodeURIComponent(s.id)}?skipRunning=1`,{method:"DELETE"});if(409===e.status){n.push(s.id);continue}if(!e.ok)throw Error(`HTTP ${e.status}`);t.push(s.id)}catch{r.push(s.name?.trim()||s.id.slice(0,8))}if(n.length>0&&(tI.current=!0,tg(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(tb(n),tk(n),tS(e=>e&&$(e,t)),t))d?.(e)}(await tR(),tF(!1),r.length>0)?tz(b("sidebar.clearSessionsFailed",{count:r.length,names:r.join(", ")})):n.length>0||tA(null)},[tR,d,b]),[tH,tU]=(0,s.useState)(0),tB=(0,s.useCallback)(()=>{tU(e=>e+1),tR()},[tR]),tq=(0,s.useRef)(!1);(0,s.useEffect)(()=>{let e=!tq.current;tq.current=!0,tR(e,!e)},[tR,c]),(0,s.useEffect)(()=>{if("priority"!==g)return;let e=()=>{"visible"===document.visibilityState&&tR(!1,!0)};e();let t=window.setInterval(e,15e3);return()=>window.clearInterval(t)},[tR,g]),(0,s.useEffect)(()=>{x?.({running:tf.size,waiting:j.filter(e=>tx.has(e.id))})},[j,x,tf,tx]),(0,s.useEffect)(()=>{try{0===ty.size?window.localStorage.removeItem(ef):window.localStorage.setItem(ef,JSON.stringify([...ty]))}catch{}},[ty]),(0,s.useEffect)(()=>{try{0===tw.size?window.localStorage.removeItem(eg):window.localStorage.setItem(eg,JSON.stringify([...tw]))}catch{}},[tw]),(0,s.useEffect)(()=>{if(tj)try{var e,t,n;let r=window.localStorage;r.setItem(C,(e=r.getItem(C),t=Date.now(),JSON.stringify({since:(n=T(tj,N(e,t))).since,opened:n.opened})))}catch{}},[tj]);let tV=(0,s.useCallback)(e=>{tk(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]);(0,s.useEffect)(()=>{let e=!1,t=null,n=null,r=()=>{t&&clearTimeout(t),t=null},s=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;tI.current=!0,tg(new Set(r.runningSessionIds??[])),tv(new Set(r.waitingSessionIds??[]))}catch{}finally{n===a&&(n=null),r(),e||"visible"!==document.visibilityState||(t=setTimeout(()=>void s(),2500))}},a=()=>{"visible"===document.visibilityState?s():(r(),n?.abort(),n=null)};return s(),document.addEventListener("visibilitychange",a),()=>{e=!0,r(),n?.abort(),document.removeEventListener("visibilitychange",a)}},[]);let tK=ec()?.besideSessionId??null;(0,s.useEffect)(()=>{let t=tT.current,n=[...t].filter(t=>!tf.has(t)&&t!==e&&t!==tK),r=[...tf].filter(e=>!t.has(e));(n.length>0||r.length>0)&&tb(e=>{let t=new Set(e);return tf.forEach(e=>t.delete(e)),n.forEach(e=>t.add(e)),t});let s=r.some(e=>!j.some(t=>t.id===e));(n.length>0||s)&&tR(!1,!0),n.length>0&&p?.(),tT.current=tf},[tf,e,tK,j,tR,p]),(0,s.useEffect)(()=>{let t=[e,tK].filter(e=>null!==e);0!==t.length&&tb(e=>{if(!t.some(t=>e.has(t)))return e;let n=new Set(e);return t.forEach(e=>n.delete(e)),n})},[e,tK]);let tJ=e?_.find(t=>t.id===e):void 0,tG=tJ?.conversationModified??tJ?.modified,tY=null!==tj;(0,s.useEffect)(()=>{e&&void 0!==tG&&tY&&tS(t=>t&&M(t,{id:e,modified:tG},Date.now()))},[e,tG,tY]),(0,s.useEffect)(()=>{fetch("/api/home").then(e=>e.json()).then(e=>{e.home&&V(e.home),J(!0===e.cloudProjects)}).catch(()=>{})},[]);let tZ=(0,s.useRef)(!1),tQ=(0,s.useCallback)(e=>{if(!e)return null;if(eZ&&eZ.forCwd===e||eZ?.worktrees.some(t=>t.path===e))return eZ.projectRoot;let t=_.find(t=>t.cwd===e);return t?.projectRoot??e},[eZ,_]),tX=(0,s.useRef)(null);(0,s.useEffect)(()=>{tX.current!==H&&(tX.current=H,h?.(H,tQ(H)))},[H,h,tQ]);let t0=(0,s.useRef)(null);(0,s.useEffect)(()=>{u&&u!==t0.current&&(t0.current=u,B(u))},[u]);let[t1,t2]=(0,s.useState)(0);(0,s.useLayoutEffect)(()=>{if(!H)return void eQ(null);let e=!1;return fetch(`/api/worktrees?cwd=${encodeURIComponent(H)}`).then(e=>e.json()).then(t=>{if(!e){if(t.error||!t.projectRoot)return void eQ(null);eQ({forCwd:H,projectRoot:t.projectRoot,isGit:t.isGit??!1,isTopLevel:t.isTopLevel??!1,worktrees:t.worktrees??[]})}}).catch(()=>{e||eQ(null)}),()=>{e=!0}},[H,t1,c]),(0,s.useEffect)(()=>{if(0!==j.length&&!l&&null===H){if(i&&!tZ.current){tZ.current=!0;let e=j.find(e=>e.id===i);if(e){B(e.cwd),n(e,!0);return}o?.()}if(!em)return;let e=new Map(eh.projects.map(e=>[e.key,e])),t=P(j.length>0?L(j):[],eh.projects).filter(t=>!e.get(R(t))?.hidden);t.length>0&&B(t[0])}},[j,H,i,l,n,o,eh,em]);let t4=(0,s.useCallback)(async e=>{let t=e.trim();if(t&&!eG){eY(!0),eJ(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 eJ(n.error??b("workspace.unable"));let r=n.cwd??t,s=R(r),a=eh.projects.find(e=>e.key===s);if(a?.hidden===!0)try{await t$([{key:s,path:r,hidden:!1}])}catch{}B(r),eV(!1)}catch{eJ(b("workspace.unable"))}finally{eY(!1)}}},[t$,eG,eh.projects,b]),t8=(0,s.useCallback)(()=>{eV(!0),eJ(null)},[]),t5=(0,s.useCallback)(async()=>{let e=e4.trim();if(e&&!ts&&eZ){ta(!0),e6(null);try{let t=await fetch("/api/worktrees",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:eZ.projectRoot,branch:e})}),n=await t.json().catch(()=>({}));if(!t.ok||n.error||!n.path)return void e6(n.error??`HTTP ${t.status}`);e2(!1),e8(""),e0(!1),eQ(t=>t?{...t,forCwd:n.path,worktrees:[...t.worktrees,{path:n.path,branch:e,isMain:!1}]}:t),B(n.path),t2(e=>e+1)}catch(e){e6(e instanceof Error?e.message:String(e))}finally{ta(!1)}}},[e4,ts,eZ]),t6=(0,s.useCallback)(async(e,t)=>{if(eZ&&!ts){ta(!0),e6(null);try{let n=await fetch("/api/worktrees",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:eZ.projectRoot,path:e,force:t})}),r=await n.json().catch(()=>({}));if(!n.ok){if(r.dirty&&!t)return void tl(e);e6(r.error??`HTTP ${n.status}`);return}tl(null),H===e&&B(eZ.projectRoot),t2(e=>e+1)}catch(e){e6(e instanceof Error?e.message:String(e))}finally{ta(!1)}}},[eZ,ts,H]);(0,s.useEffect)(()=>{let e=e=>{to.current&&!to.current.contains(e.target)&&(eu(null),e0(!1),e2(!1),e8(""),e6(null),tl(null),eB(""),eo(null))};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[]);let t3=(0,s.useCallback)(e=>{e.cwd&&B(e.cwd),n(e)},[n]),t7=(0,s.useCallback)((e=H)=>{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)}`;B(e),a?.(t,e)},[H,a]),t9=(0,s.useCallback)(async()=>{let e=eZ?.projectRoot,t=e3.trim();if(!e||!t||e9)return;te(!0),tn(null);let r=tr.current,s=r?.issue===t&&r.cwd===e?r.id:"function"==typeof crypto.randomUUID?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}-${Math.random().toString(36).slice(2)}`;tr.current={issue:t,cwd:e,id:s};try{let r=await fetch("/api/agent/new",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e,issue:t,type:"ensure_session",createRequestId:s})}),a=await r.json();if(!r.ok||!a.sessionId||!a.cwd)throw Error(a.error??`HTTP ${r.status}`);ei(a.cwd,a.worktree),tr.current=null,e7(""),B(a.cwd),t2(e=>e+1),n({id:a.sessionId,cwd:a.cwd,projectRoot:e,path:"",created:new Date().toISOString(),modified:new Date().toISOString(),messageCount:0,firstMessage:"(no messages)",transient:!0})}catch(e){tn(e instanceof Error?e.message:String(e))}finally{te(!1)}},[eZ,e3,e9,n]),[ne,nt]=(0,s.useState)(!1),[nn,nr]=(0,s.useState)(null),ns=(0,s.useCallback)(async()=>{nt(!0),nr(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}`);t7(t.cwd)}catch(e){nr(b("sidebar.newScratchSessionFailed",{error:e instanceof Error?e.message:String(e)}))}finally{nt(!1)}},[t7,b]),na=(0,s.useCallback)(e=>{en(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]),ni=tQ(H),nl=null===ni?null:R(ni),no=(0,s.useMemo)(()=>new Map(eh.projects.map(e=>[e.key,e])),[eh.projects]),nc=L(_);if(null!==ni){let e=R(ni);nc.some(t=>R(t)===e)||nc.unshift(ni)}let nd=P(nc,eh.projects),nu=nd.filter(e=>eT||!no.get(R(e))?.hidden),nh=nd.some(e=>no.get(R(e))?.hidden),np=()=>{eu(null),e0(!1),e2(!1),e8(""),e6(null),tl(null),eB("")},nm=async(e,t)=>{np();try{await t$([{key:R(e),path:e,hidden:t}]),t&&nl&&nl===R(e)&&B(null),t||nd.some(t=>R(t)!==R(e)&&no.get(R(t))?.hidden)||e$(!1)}catch{}},nf=async e=>{if(tu.current){tu.current=!1,e_(null);return}let t=eF.trim();if(t===(no.get(R(e))?.alias??""))return void e_(null);eH(null);try{await t$([{key:R(e),path:e,alias:t||null}]),e_(null)}catch{eH(b("sidebar.projectUpdateFailed"))}},ng=async(e,t)=>{if(Y)return;let n=nu.indexOf(e),r=n+t;if(n<0||r<0||r>=nu.length)return;let s=new Set(nu),a=nd.map((e,t)=>s.has(e)?t:-1).filter(e=>e>=0),i=[...nd],l=a[n],o=a[r];[i[l],i[o]]=[i[o],i[l]],np();try{await t$(i.map((e,t)=>({key:R(e),path:e,order:t})))}catch{}},nx=new Map;for(let e of _){let t=e.projectRoot??e.cwd;if(!t)continue;let n=R(t),r=nx.get(n);r?r.push(e):nx.set(n,[e])}let nv=(0,s.useMemo)(()=>{let e=new Map;for(let t of _){let n=t.projectRoot??t.cwd;if(!n)continue;let r=R(n),s=e.get(r);s||(s={running:0,unread:0},e.set(r,s)),tf.has(t.id)&&s.running++,ty.has(t.id)&&s.unread++}return e},[_,tf,ty]),ny=Y.trim().toLowerCase(),nb=Y.length>0,nw=nu.flatMap(e=>{let t=e.replace(/[\\/]+$/,"").split(/[\\/]/).at(-1)||e,n=R(e),r=no.get(n),s=r?.alias??t,a=(nx.get(n)??[]).slice().sort((e,t)=>{let n=Number(tw.has(t.id))-Number(tw.has(e.id));return 0!==n?n:t.modified.localeCompare(e.modified)});if(!ny)return[{project:e,key:n,name:s,sessions:a,hidden:r?.hidden===!0}];let i=s.toLowerCase().includes(ny)||t.toLowerCase().includes(ny),l=a.filter(e=>(e.name||e.firstMessage.slice(0,50)||e.id.slice(0,12)).toLowerCase().includes(ny));return i||0!==l.length?[{project:e,key:n,name:s,sessions:i?a:l,hidden:r?.hidden===!0}]:[]}),nk=[],nj=[];for(let e of nw){let t=e.key===nl||(nv.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=>S.some(t=>e.startsWith(t)))})(e.project)&&!t?nj.push(e):nk.push(e)}let nS={running:0,unread:0};for(let e of nj){let t=nv.get(e.key);t&&(nS.running+=t.running,nS.unread+=t.unread)}let nC=nb||eR,nN=[...nk.map(e=>({kind:"project",group:e})),...nj.length>0?[{kind:"temporary"}]:[],...nC?nj.map(e=>({kind:"project",group:e})):[]],nT=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,s.useMemo)(()=>tj?_.filter(e=>(function(e,t,n,r=E){if(e.transient||e.trial)return!1;if(r.has(e.id))return!0;if(t.has(e.id))return!1;let s=I(e);return null!==s&&s>(n.opened[e.id]??n.since)})(e,tf,tj,tx)):[],[tj,tf,_,tx]),nM=tC&&null!==tj,[nE,n$]=(0,s.useState)(null),nR=(0,s.useMemo)(()=>(function(e,t,n,r,s="Priority",a=new Set,i="Pinned",l=10){let o=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)}),c=o.filter(e=>a.has(e.id)),d=[],u=new Map,h=0;for(let e of o){if(a.has(e.id))continue;if(t.has(e.id)){d.push(e);continue}let n=new Date(e.modified);if(h>=l)continue;h+=1;let r=[n.getFullYear(),String(n.getMonth()+1).padStart(2,"0"),String(n.getDate()).padStart(2,"0")].join("-"),s=u.get(r);s?s.push(e):u.set(r,[e])}let p=[];for(let e of(c.length>0&&p.push({key:"pinned",label:i,running:!1,sessions:c}),d.length>0&&p.push({key:"priority",label:s,running:!0,sessions:d}),[...u.keys()].sort().reverse()))p.push({key:e,label:function(e,t,n){let[r,s,a]=e.split("-").map(Number),i=new Date(r,s-1,a),l=Math.round((Date.UTC(t.getFullYear(),t.getMonth(),t.getDate())-Date.UTC(i.getFullYear(),i.getMonth(),i.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(i):new Intl.DateTimeFormat(n,{month:"short",day:"numeric"}).format(i)}(e,n,r),running:!1,sessions:u.get(e)??[]});return p})(nM?_.filter(e=>e.id===nE&&!tf.has(e.id)||nI.includes(e)):_,tf,new Date,w,b("navigator.priority"),tw,b("sidebar.pinned"),nM?1/0:void 0),[nE,w,tw,nI,nM,tf,_,b]),nL=(0,s.useMemo)(()=>{let e=new Set(nI.map(e=>e.id)),t=[],n=[],r=[],s=null,a=[];for(let i of nR)if("pinned"===i.key){let a=i.sessions.filter(s=>{if(tx.has(s.id))t.push(s);else if(tf.has(s.id))n.push(s);else{if(!e.has(s.id))return!0;r.push(s)}return!1});a.length>0&&(s={...i,sessions:a})}else if(i.running)for(let e of i.sessions)(tx.has(e.id)?t:n).push(e);else{let t=i.sessions.filter(t=>!e.has(t.id)||(r.push(t),!1));t.length>0&&a.push({...i,sessions:t})}let i=[];return t.length>0&&i.push({key:"input",kind:"input",label:b("navigator.group.input"),sessions:t}),n.length>0&&i.push({key:"running",kind:"running",label:b("navigator.group.running"),sessions:n}),r.length>0&&i.push({key:"review",kind:"review",label:b("navigator.resultsToCheck"),sessions:r}),s&&i.push({key:"pinned",kind:"pinned",label:s.label,sessions:s.sessions}),a.forEach((e,t)=>i.push({key:e.key,kind:"done",label:e.label,heading:0===t?b("navigator.group.done"):void 0,sessions:e.sessions})),i},[nR,nI,tf,b,tx]),nP=(0,s.useCallback)(e=>{n$(e.id),t3(e)},[t3]),nA=!!(eZ?.isGit&&eZ.isTopLevel&&H&&ni===eZ.projectRoot),n_=eZ?.worktrees.find(e=>e.path===H)??eZ?.worktrees.find(e=>e.isMain),nF=(eZ?.worktrees.length??0)>=8,nO=nF&&eU.trim()?(eZ?.worktrees??[]).filter(e=>(e.branch??ey(e.path,q)).toLowerCase().includes(eU.trim().toLowerCase())):eZ?.worktrees??[],nz=es[w.startsWith("ko")?"ko":w.startsWith("zh")?"zh":"en"],nD=function(e){if(e&&"u">typeof sessionStorage)try{return JSON.parse(sessionStorage.getItem(`cuelo:worktree:${e}`)??"null")??void 0}catch{return}}(H),nW=(()=>{if(!tP)return[];let e="project"===tP.kind?nx.get(R(tP.project))??[]:nR.flatMap(e=>e.sessions),t=new Set;return e.filter(e=>!(e.transient||t.has(e.id))&&(t.add(e.id),!0))})(),nH=nW.filter(e=>!tf.has(e.id)),nU=e=>{let t=new Set;for(let n of e)n.transient||tf.has(n.id)||t.has(n.id)||t.add(n.id);return t.size},nB=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:[eq&&(0,r.jsx)(K?X:G,{busy:eG,error:eK,onCancel:()=>{eV(!1),eJ(null)},onSelect:e=>void t4(e)}),tP&&(0,r.jsx)(eN,{scope:tP,eligible:nH.length,runningExcluded:nW.length-nH.length,busy:t_,error:tO,onCancel:tD,onConfirm:()=>void tW(nH)}),(0,r.jsxs)("div",{className:"session-navigator-header",style:{padding:"4px 10px",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)(ej,{}),(0,r.jsxs)("div",{style:{display:"flex",gap:12},children:[(0,r.jsx)("button",{className:"navigator-icon-action",onClick:()=>t7(),disabled:!H,style:{display:"flex",alignItems:"center",justifyContent:"center",background:"var(--bg-hover)",border:0,color:H?"var(--text-muted)":"var(--text-dim)",cursor:H?"pointer":"not-allowed",width:32,height:32,padding:0,borderRadius:"var(--radius-control)",fontSize:12,flexShrink:0,transition:"background 0.12s, color 0.12s"},title:H?b("sidebar.newSessionTitle",{path:H}):b("sidebar.selectProject"),"aria-label":H?b("sidebar.newSessionTitle",{path:H}):b("sidebar.selectProject"),onMouseEnter:e=>{H&&(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=H?"var(--text-muted)":"var(--text-dim)"},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${tp?" is-success":""}`,onClick:()=>tR(!1,!0),style:{display:"flex",alignItems:"center",justifyContent:"center",background:tp?"var(--success-soft)":"var(--bg-hover)",border:0,color:tp?"var(--success)":"var(--text-muted)",cursor:"pointer",width:32,height:32,borderRadius:"var(--radius-control)",padding:0,flexShrink:0,transition:"background 0.3s, color 0.3s"},onMouseEnter:e=>{tp||(e.currentTarget.style.background="var(--bg-selected)",e.currentTarget.style.color="var(--accent)")},onMouseLeave:e=>{tp||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text-muted)")},title:b("sidebar.refresh"),children:tp?(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"})]})})]})]}),nA&&(0,r.jsxs)("form",{onSubmit:e=>{e.preventDefault(),t9()},style:{marginTop:8},children:[(0,r.jsx)("label",{htmlFor:"session-issue",style:{display:"block",fontSize:12,color:"var(--text-muted)"},children:nz.issueLabel}),(0,r.jsxs)("div",{style:{display:"flex",gap:4,marginTop:4},children:[(0,r.jsx)("input",{id:"session-issue",value:e3,disabled:e9,onChange:e=>{e7(e.target.value),tn(null)},placeholder:nz.issuePlaceholder,"aria-describedby":tt?"session-issue-error":void 0,"aria-invalid":!!tt,style:{minWidth:0,flex:1,padding:"6px 8px",fontSize:12,background:"var(--bg)",color:"var(--text)",border:0,borderRadius:"var(--radius-control)"}}),(0,r.jsx)("button",{type:"submit",disabled:e9||!e3.trim(),title:nz.issueStart,"aria-label":nz.issueStart,style:{minWidth:32,padding:"4px 8px",border:0,borderRadius:"var(--radius-control)",background:"var(--bg-hover)",color:"var(--text)",cursor:e9?"wait":"pointer"},children:e9?"…":"↵"})]}),e9&&(0,r.jsx)("div",{role:"status",style:{fontSize:12},children:nz.issueBusy}),tt&&(0,r.jsx)("div",{id:"session-issue-error",role:"alert",style:{fontSize:12,color:"var(--danger)",overflowWrap:"anywhere"},children:tt})]}),(nD||n_&&!n_.isMain)&&(0,r.jsxs)("div",{role:"status",title:H??void 0,style:{marginTop:4,fontSize:12,color:"var(--text-muted)",overflowWrap:"anywhere"},children:[nD?.branch??n_?.branch,nD?.fallback&&(0,r.jsx)("div",{children:nz.fallbackBase.replace("{branch}",nD.base)}),nD?.missingSubdirectory&&(0,r.jsx)("div",{children:ea[w.startsWith("ko")?"ko":w.startsWith("zh")?"zh":"en"].replace("{path}",nD.missingSubdirectory)})]})]}),K&&!nB&&(0,r.jsx)("button",{type:"button",className:"navigator-cloud-project",onClick:t8,style:{margin:"10px 12px 0",minHeight:44,flexShrink:0,border:0,borderRadius:"var(--radius-control)",background:"var(--bg)",color:"var(--text)",fontSize:13,fontWeight:600,cursor:"pointer"},children:b("cloudProjects.launch")}),(0,r.jsxs)("div",{className:"navigator-mode-bar",children:[(0,r.jsx)("h2",{className:"navigator-place-title",children:nB?y("translator.tab"):"projects"===g?b("sidebar.projects"):b("navigator.priority")}),(0,r.jsx)("span",{className:"navigator-mode-spacer"}),!nB&&"projects"===g&&(0,r.jsx)("button",{type:"button",onClick:()=>e$(e=>!e),disabled:!nh,title:b("sidebar.projectShowHidden"),"aria-label":b("sidebar.projectShowHidden"),"aria-pressed":eT,style:{display:"flex",alignItems:"center",justifyContent:"center",width:26,height:26,padding:0,border:"none",borderRadius:"var(--radius-control)",background:eT?"var(--bg-selected)":"transparent",color:eT?"var(--accent)":"var(--text-dim)",cursor:nh?"pointer":"default",opacity:nh?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"}),!eT&&(0,r.jsx)("path",{d:"m4 4 16 16"})]})}),!nB&&"projects"===g&&(0,r.jsx)("button",{className:"navigator-add-project",type:"button",onClick:t8,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:"var(--radius-control)",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"})]})})]}),nB&&m,!nB&&"projects"===g&&(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:Y,onChange:e=>Z(e.target.value),onKeyDown:e=>{"Escape"===e.key&&(e.preventDefault(),Z(""),e.currentTarget.blur())},placeholder:b("sidebar.searchProjectsAndSessions"),"aria-label":b("sidebar.searchProjectsAndSessions"),style:{width:"100%",height:34,padding:"0 10px 0 32px",border:0,borderRadius:"var(--radius-control)",outline:"none",background:"var(--bg-hover)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:11}})]}),!nB&&"projects"===g&&(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:[(O||!em)&&(0,r.jsx)("div",{style:{padding:"12px 8px",color:"var(--text-muted)",fontSize:12},children:b("sidebar.loading")}),D&&(0,r.jsx)("div",{style:{padding:"10px 8px",color:"var(--danger)",fontSize:12},children:D}),eW&&(0,r.jsx)("div",{style:{padding:"10px 8px",color:"var(--danger)",fontSize:12},children:eW}),!O&&em&&!D&&0===nw.length&&(0,r.jsx)("div",{style:{padding:"12px 8px",color:"var(--text-muted)",fontSize:12},children:ny?b("sidebar.noMatchingProjects"):b("sidebar.noSessions")}),!O&&em&&!D&&nN.map(t=>{let n,s,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":nC,title:b("sidebar.temporaryProjects"),onClick:()=>eL(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:nC?"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-muted)",fontFamily:"var(--font-mono)",fontSize:11,flexShrink:0},children:nj.length}),eP(nS,b)]})},"navigator-temporary-projects");let{project:i,key:l,name:o,sessions:c,hidden:d}=t.group,u=l===nl,h=nT.has(o.toLowerCase())&&ey((s=Math.max((n=i.trim().replace(/[\\/]+$/,"")).lastIndexOf("\\"),n.lastIndexOf("/")))<=0?"":n.slice(0,s),q)||null,p=!et.has(i)&&!ny,m=Q.has(i),f=eA===i,g=nu.indexOf(i),x=ez||nb||g<=0,v=ez||nb||g>=nu.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 s=function(e){let r=n.get(e),s=new Set;for(;r&&!s.has(r);){if(s.add(r),t.has(r))return r;r=n.get(r)}return null}(e.session.id);s?t.get(s).children.push(e):r.push(e)}let s=e=>{e.sort((e,t)=>t.session.modified.localeCompare(e.session.modified)),e.forEach(e=>s(e.children))};return s(r),r}(m?c:c.slice(0,5)),w=c.length>5;return(0,r.jsxs)("section",{className:"navigator-project-group",style:{marginBottom:p?3:9},children:[(0,r.jsxs)("div",{className:`navigator-project-row${u?" is-selected":""}`,ref:ed===i?to:void 0,onMouseEnter:()=>eo(i),onMouseLeave:()=>eo(e=>e===i&&ed!==i?null:e),style:{display:"flex",alignItems:"center",minHeight:34,position:"relative",borderRadius:"var(--radius-control)",background:u?"var(--bg-hover)":"transparent",opacity:d?.55:1},children:[(0,r.jsx)("button",{type:"button",onClick:()=>na(i),title:p?b("sidebar.expandProject"):b("sidebar.collapseProject"),"aria-label":p?b("sidebar.expandProject"):b("sidebar.collapseProject"),"aria-expanded":!p,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:p?"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:td,value:eF,onChange:e=>eO(e.target.value),onBlur:()=>void nf(i),onKeyDown:e=>{"Enter"===e.key?(e.preventDefault(),e.currentTarget.blur()):"Escape"===e.key&&(e.preventDefault(),tu.current=!0,e_(null))},"aria-label":b("sidebar.projectAlias"),style:{flex:1,minWidth:0,height:24,padding:"2px 6px",border:0,borderRadius:"var(--radius-control)",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:()=>B(i),title:i,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===h?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:h}),eP(nv.get(l),b)]}),!k&&(0,r.jsx)("button",{type:"button",onClick:()=>t7(i),title:b("sidebar.newSessionTitle",{path:i}),"aria-label":b("sidebar.newSessionTitle",{path:i}),style:{display:"flex",alignItems:"center",justifyContent:"center",width:28,height:28,padding:0,border:"none",borderRadius:"var(--radius-control)",background:"transparent",color:"var(--text-dim)",cursor:"pointer",opacity:+(el===i),pointerEvents:el===i?"auto":"none",transition:"opacity 0.12s, background 0.12s, color 0.12s",flexShrink:0},onFocus:()=>eo(i),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:()=>{eu(ed===i?null:i),e0(!1),e2(!1),e6(null),u||B(i)},title:b("sidebar.projectActions"),"aria-label":b("sidebar.projectActions"),"aria-expanded":ed===i,style:{display:"flex",alignItems:"center",justifyContent:"center",width:26,height:26,marginRight:3,padding:0,border:"none",borderRadius:"var(--radius-control)",background:ed===i?"var(--bg-selected)":"transparent",color:u&&n_&&!n_.isMain?"var(--accent)":"var(--text-dim)",cursor:"pointer",opacity:k||el===i||ed===i?1:0,pointerEvents:k||el===i||ed===i?"auto":"none",transition:"opacity 0.12s, background 0.12s, color 0.12s"},onFocus:()=>eo(i),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)(ew,{open:ed===i,style:{position:"absolute",top:"calc(100% + 4px)",right:3,width:"min(260px, calc(100vw - 24px))",zIndex:110,background:"var(--bg-raised)",border:0,borderRadius:"var(--radius-surface)",boxShadow:"var(--shadow-float)",boxSizing:"border-box",overflow:"hidden"},children:[k&&(0,r.jsxs)("button",{type:"button",className:"navigator-project-menu-new-session",onClick:()=>{eu(null),t7(i)},title:b("sidebar.newSessionTitle",{path:i}),style:{display:"flex",alignItems:"center",gap:8,width:"100%",minHeight:44,padding:"0 10px",border:"none",background:"transparent",color:"var(--text)",cursor:"pointer",textAlign:"left",fontSize:13},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"})]}),b("i18n.newSession")]}),nA&&eZ&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("button",{type:"button",onClick:()=>e0(e=>!e),title:n_?b("sidebar.switchWorktreeTitle",{path:n_.path}):b("sidebar.switchWorktree"),"aria-label":b("sidebar.worktrees"),"aria-expanded":eX,style:{display:"flex",alignItems:"center",gap:8,width:"100%",minHeight:34,padding:"0 10px",border:"none",background:eX?"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)(ew,{open:eX,style:{position:"static",width:"auto",zIndex:100,background:"var(--bg)",border:"none",borderRadius:0,boxShadow:"none",boxSizing:"border-box",overflow:"hidden"},children:[nF&&(0,r.jsx)("div",{style:{padding:"6px 8px"},children:(0,r.jsx)("input",{value:eU,onChange:e=>eB(e.target.value),onKeyDown:e=>{"Escape"===e.key&&(eB(""),e0(!1))},placeholder:b("sidebar.filterWorktrees"),autoFocus:!0,style:{width:"100%",fontSize:11,fontFamily:"var(--font-mono)",padding:"5px 8px",border:0,borderRadius:"var(--radius-control)",outline:"none",background:"var(--bg-subtle)",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===H||e.isMain&&!eZ.worktrees.some(e=>e.path===H);return ti===e.path?(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6,padding:"7px 10px",background:"var(--danger-soft)"},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 t6(e.path,!0),disabled:ts,style:{padding:"3px 9px",background:"var(--danger)",border:"none",borderRadius:"var(--radius-control)",color:"var(--bg)",fontSize:11,fontWeight:600,cursor:"pointer",flexShrink:0},children:b("sidebar.force")}),(0,r.jsx)("button",{onClick:()=>tl(null),style:{padding:"3px 9px",background:"var(--bg-hover)",border:0,borderRadius:"var(--radius-control)",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"},children:[(0,r.jsxs)("button",{onClick:()=>{B(e.path),e0(!1),e6(null),eB("")},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)(eb,{text:e.branch??ey(e.path,q),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 t6(e.path,!1),disabled:ts,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:"var(--radius-control)",flexShrink:0,transition:"color 0.12s, background 0.12s"},onMouseEnter:e=>{e.currentTarget.style.color="var(--danger)",e.currentTarget.style.background="var(--danger-soft)"},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)}),nF&&0===nO.length&&eU.trim()&&(0,r.jsx)("div",{style:{padding:"8px 10px",fontSize:11,color:"var(--text-dim)"},children:b("sidebar.noMatchingWorktrees")})]}),e1?(0,r.jsxs)("div",{style:{padding:"6px 8px"},children:[(0,r.jsx)("input",{ref:tc,value:e4,onChange:e=>{e8(e.target.value),e6(null)},onKeyDown:e=>{"Enter"===e.key&&(e.preventDefault(),t5()),"Escape"===e.key&&(e2(!1),e8(""),e6(null))},placeholder:b("sidebar.branchName"),style:{width:"100%",fontSize:11,fontFamily:"var(--font-mono)",padding:"5px 8px",border:0,borderRadius:"var(--radius-control)",outline:"none",background:"var(--bg-subtle)",color:"var(--text)",boxSizing:"border-box"}}),(0,r.jsxs)("div",{style:{display:"flex",gap:5,marginTop:5},children:[(0,r.jsx)("button",{onClick:()=>void t5(),disabled:ts||!e4.trim(),style:{flex:1,padding:"4px 0",background:"var(--accent)",border:"none",borderRadius:"var(--radius-control)",color:"var(--bg)",fontSize:11,fontWeight:600,cursor:ts||!e4.trim()?"not-allowed":"pointer",opacity:ts||!e4.trim()?.65:1},children:ts?b("sidebar.creating"):b("sidebar.create")}),(0,r.jsx)("button",{onClick:()=>{e2(!1),e8(""),e6(null)},style:{flex:1,padding:"4px 0",background:"var(--bg-hover)",border:0,borderRadius:"var(--radius-control)",color:"var(--text-muted)",fontSize:11,cursor:"pointer"},children:b("sidebar.cancel")})]})]}):(0,r.jsxs)("button",{onClick:e=>{e.stopPropagation(),e2(!0),e6(null),setTimeout(()=>tc.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")})]}),e5&&(0,r.jsx)("div",{style:{padding:"5px 10px 8px",color:"var(--danger)",fontSize:11,lineHeight:1.35,overflowWrap:"anywhere"},children:e5})]})]}),(0,r.jsxs)("button",{type:"button",disabled:ez,onClick:()=>{let e;return e=no.get(R(i))?.alias??"",void(tu.current=!1,eH(null),eO(e),e_(i),np())},style:{display:"flex",alignItems:"center",gap:8,width:"100%",minHeight:34,padding:"0 10px",border:"none",background:"transparent",color:"var(--text-muted)",cursor:ez?"default":"pointer",textAlign:"left",fontSize:11,opacity:ez?.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(no.get(R(i))?.alias?"sidebar.projectAliasEdit":"sidebar.projectAlias")]}),(0,r.jsxs)("button",{type:"button",disabled:x,title:nb?b("sidebar.projectMoveDisabledWhileFiltering"):void 0,onClick:()=>void ng(i,-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:nb?b("sidebar.projectMoveDisabledWhileFiltering"):void 0,onClick:()=>void ng(i,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:ez,onClick:()=>void nm(i,!d),style:{display:"flex",alignItems:"center",gap:8,width:"100%",minHeight:34,padding:"0 10px",border:"none",background:"transparent",color:"var(--text-muted)",cursor:ez?"default":"pointer",textAlign:"left",fontSize:11,opacity:ez?.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"}),!d&&(0,r.jsx)("path",{d:"m4 4 16 16"})]}),b(d?"sidebar.projectUnhide":"sidebar.projectHide")]}),(a=0===nU(nx.get(l)??[])||t_,(0,r.jsxs)("button",{type:"button",disabled:a,onClick:()=>{np(),tz(null),tA({kind:"project",project:i,label:o})},style:{display:"flex",alignItems:"center",gap:8,width:"100%",minHeight:34,padding:"0 10px",border:"none",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")]}))]})]})]}),!p&&0===c.length&&u&&(0,r.jsx)("div",{style:{padding:"6px 12px 7px 32px",color:"var(--text-dim)",fontSize:11},children:b("sidebar.noSessions")}),!p&&y.length>0&&(0,r.jsx)("div",{style:{paddingLeft:12},children:y.map(t=>(0,r.jsx)(eE,{node:t,selectedSessionId:e,runningSessionIds:tf,unreadSessionIds:ty,pinnedSessionIds:tw,onSelectSession:t3,onTogglePinnedSession:tV,onRenamed:tR,onSessionDeleted:tL,onSessionArchived:tB,depth:0},t.session.id))}),!p&&w&&(0,r.jsx)("button",{type:"button",onClick:()=>{ee(e=>{let t=new Set(e);return t.has(i)?t.delete(i):t.add(i),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")})]},i)})]}),!nB&&(0,r.jsx)(eM,{refreshKey:tH,selectedSessionId:e,onSelectSession:t3,onRestored:tB}),!nB&&"priority"===g&&(0,r.jsxs)("div",{id:"navigator-priority-panel",style:{flex:"1 1 auto",minHeight:80,overflowY:"auto",padding:"0 6px 10px"},children:[O&&(0,r.jsx)("div",{style:{padding:"12px 8px",color:"var(--text-muted)",fontSize:12},children:b("sidebar.loading")}),D&&(0,r.jsx)("div",{role:"alert",style:{padding:"10px 8px",color:"var(--danger)",fontSize:12},children:D}),!O&&!D&&(v=nU(nR.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:ne,onClick:()=>void ns(),title:b("sidebar.newScratchSessionTitle"),style:ev(ne,k),children:b("sidebar.newScratchSession")}),nR.length>0&&!nM&&(0,r.jsx)("button",{type:"button",disabled:0===v||t_,onClick:()=>{tz(null),tA({kind:"priority"})},style:ev(0===v||t_,k),children:b("sidebar.clearPriorityList")})]})),!O&&!D&&tj&&(0,r.jsxs)("div",{style:{display:"flex",justifyContent:"space-between",gap:8,padding:"6px 2px 4px"},children:[(0,r.jsxs)("button",{type:"button","aria-pressed":nM,"aria-label":b("navigator.resultsToCheckCount",{count:nI.length}),title:b("navigator.resultsToCheckHint"),onClick:()=>{n$(null),tN(e=>!e)},style:{...ev(!1,k),display:"inline-flex",alignItems:"center",gap:6,background:nM?"var(--bg-selected)":"var(--bg-hover)",color:nM||nI.length>0?"var(--text)":"var(--text-muted)",fontWeight:nM?600:500,whiteSpace:"nowrap"},children:[b("navigator.resultsToCheck"),(0,r.jsx)("span",{"aria-hidden":"true",style:{minWidth:18,padding:"0 5px",borderRadius:"var(--radius-surface)",background:nI.length>0?"var(--seed-color-bg-neutral-inverted)":"var(--bg-subtle)",color:nI.length>0?"var(--seed-color-fg-neutral-inverted)":"var(--text-muted)",fontSize:11,fontVariantNumeric:"tabular-nums",lineHeight:"18px",textAlign:"center"},children:nI.length})]}),nI.some(e=>!tx.has(e.id))&&(0,r.jsx)("button",{type:"button",title:b("navigator.acknowledgeResultsHint"),onClick:()=>{n$(null),tS(e=>e&&function(e,t,n){let r=e;for(let e of t)r=M(r,e,n);return r}(e,nI,Date.now()))},style:ev(!1,k),children:b("navigator.acknowledgeResults")})]}),nn&&(0,r.jsx)("div",{role:"alert",style:{padding:"6px 8px",color:"var(--danger)",fontSize:12},children:nn}),!O&&!D&&0===nR.length&&(0,r.jsx)("div",{style:{padding:"12px 8px",color:"var(--text-muted)",fontSize:12},children:nM?b("navigator.resultsToCheckEmpty"):b("sidebar.noSessions")}),!O&&!D&&nL.map((t,n)=>(0,r.jsxs)("section",{"aria-labelledby":`priority-group-${t.key}`,className:"priority-group","data-group":t.kind,children:[t.heading&&(0,r.jsx)("h2",{className:"priority-group-heading","data-first":0===n?"":void 0,children:t.heading}),(0,r.jsxs)("h3",{id:`priority-group-${t.key}`,className:t.heading?"priority-group-day":"priority-group-heading","data-first":0!==n||t.heading?void 0:"",children:["input"===t.kind&&(0,r.jsx)("span",{className:"workbench-lamp","data-kind":"input","aria-hidden":"true"}),"running"===t.kind&&(0,r.jsx)("span",{className:"workbench-lamp","aria-hidden":"true"}),t.label,(0,r.jsx)("span",{className:"priority-group-count",children:t.sessions.length})]}),t.sessions.map(t=>(0,r.jsx)(eI,{session:t,selected:t.id===e,running:tf.has(t.id),waiting:tx.has(t.id),unread:ty.has(t.id),pinned:tw.has(t.id),onSelect:nM?nP:t3,onTogglePin:tV},t.id))]},t.key))]})]})}function eN({scope:e,eligible:t,runningExcluded:n,busy:a,error:i,onCancel:l,onConfirm:o}){let{t:c}=(0,F.s)(),d=a||0===t,u=(0,s.useRef)(null),h=(0,s.useRef)(null),p=(0,s.useRef)(a);p.current=a;let m=(0,s.useRef)(l);return m.current=l,(0,s.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;(h.current??e).focus();let r=t=>{if("Escape"===t.key){if(p.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 s=n[0],a=n[n.length-1];t.shiftKey&&(r===s||!e.contains(r))?(t.preventDefault(),a.focus()):t.shiftKey||r!==a&&e.contains(r)||(t.preventDefault(),s.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:0,borderRadius:"var(--radius-surface)",background:"var(--bg-raised)",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:c("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?c("sidebar.clearSessionsProjectBody",{project:e.label,count:t}):c("sidebar.clearSessionsPriorityBody",{count:t}),n>0&&(0,r.jsx)("div",{style:{marginTop:6},children:c("sidebar.clearSessionsRunningExcluded",{count:n})}),0===t&&(0,r.jsx)("div",{style:{marginTop:6},children:c("sidebar.clearSessionsNone")})]}),i&&(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:i})]}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",justifyContent:"flex-end",gap:8,padding:"12px 18px"},children:[(0,r.jsx)("button",{ref:h,type:"button",onClick:l,disabled:a,style:{minHeight:36,padding:"0 12px",border:0,borderRadius:"var(--radius-control)",background:"var(--bg-hover)",color:"var(--text-muted)",cursor:a?"default":"pointer",fontSize:"var(--seed-font-size-t3-static)"},children:c("sidebar.clearSessionsCancel")}),(0,r.jsx)("button",{type:"button",onClick:o,disabled:d,"aria-busy":a,style:{minHeight:36,padding:"0 14px",border:0,borderRadius:"var(--radius-control)",background:d?"var(--bg-hover)":"var(--danger-soft)",color:d?"var(--text-dim)":"var(--danger)",cursor:d?"default":"pointer",fontSize:"var(--seed-font-size-t3-static)",fontWeight:600},children:c(a?"sidebar.clearSessionsBusy":"sidebar.clearSessionsConfirm")})]})]})})}function eT({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 eI({session:e,selected:t,running:n,waiting:s,unread:a,pinned:i,onSelect:l,onTogglePin:o}){let{t:c}=(0,F.s)(),d=(e.name||e.firstMessage||e.id.slice(0,8)).replace(/\s+/g," ").trim(),u=e.cwd.split(/[\\/]/).filter(Boolean).at(-1)??"";return(0,r.jsxs)("div",{className:`priority-session-row${t?" is-selected":""}${n?" is-running":""}${a?" is-unread":""}`,style:{display:"flex",alignItems:"stretch",borderRadius:"var(--radius-control)",background:t?"var(--bg-selected)":"transparent"},children:[(0,r.jsxs)("button",{type:"button","aria-current":t?"page":void 0,onClick:()=>l(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}),s&&(0,r.jsx)(e$,{}),n&&!s&&(0,r.jsx)(eR,{}),!n&&a&&(0,r.jsx)(eL,{})]}),(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:u})]}),(0,r.jsx)("button",{type:"button","aria-pressed":i,"aria-label":c(i?"sidebar.unpin":"sidebar.pin"),title:c(i?"sidebar.unpin":"sidebar.pin"),onClick:()=>o(e.id),style:{width:30,border:"none",background:"transparent",color:i?"var(--accent)":"var(--text-dim)",cursor:"pointer",flexShrink:0},children:(0,r.jsx)(eT,{filled:i})})]})}function eM({refreshKey:e,selectedSessionId:t,onSelectSession:n,onRestored:a}){let{t:i}=(0,F.s)(),[l,o]=(0,s.useState)(!1),[c,d]=(0,s.useState)([]);(0,s.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||d(n.sessions)}catch{}})(),()=>{e=!0}},[e]);let u=(0,s.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!==c.length||l?(0,r.jsxs)("section",{style:{marginTop:8},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"})}),i("sidebar.archived")," (",c.length,")"]}),l&&(0,r.jsxs)("div",{style:{paddingLeft:12},children:[0===c.length&&(0,r.jsx)("div",{style:{padding:"4px 12px 8px 20px",color:"var(--text-dim)",fontSize:11},children:i("sidebar.noArchivedSessions")}),c.map(e=>{let s=_(e.firstMessage)??e.firstMessage,a=e.name||s.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",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:i("sidebar.restore"),style:{display:"flex",alignItems:"center",justifyContent:"center",height:24,padding:"0 8px",flexShrink:0,background:"var(--bg-hover)",border:0,borderRadius:"var(--radius-control)",color:"var(--text-muted)",cursor:"pointer",fontSize:11,fontWeight:500},children:i("sidebar.restore")})]},e.id)})]})]}):null}function eE({node:e,selectedSessionId:t,runningSessionIds:n,unreadSessionIds:a,pinnedSessionIds:i,onSelectSession:l,onRenamed:o,onSessionDeleted:c,onTogglePinnedSession:d,onSessionArchived:u,depth:h}){let[p,m]=(0,s.useState)(!1),f=e.children.length>0;return(0,r.jsxs)("div",{children:[(0,r.jsxs)("div",{style:{position:"relative"},children:[h>0&&(0,r.jsx)("div",{style:{position:"absolute",left:10*h+6,top:0,bottom:0,width:1,background:"var(--border)",pointerEvents:"none"}}),(0,r.jsx)(eA,{session:e.session,isSelected:e.session.id===t,isRunning:n.has(e.session.id),isUnread:a.has(e.session.id),isPinned:i.has(e.session.id),onClick:()=>l(e.session),onTogglePin:()=>d(e.session.id),onRenamed:o,onDeleted:e=>c?.(e),onArchived:e=>u?.(e),depth:h,hasChildren:f,collapsed:p,onToggleCollapse:()=>m(e=>!e)})]}),f&&!p&&(0,r.jsx)("div",{children:e.children.map(e=>(0,r.jsx)(eE,{node:e,selectedSessionId:t,runningSessionIds:n,unreadSessionIds:a,pinnedSessionIds:i,onSelectSession:l,onTogglePinnedSession:d,onRenamed:o,onSessionDeleted:c,onSessionArchived:u,depth:h+1},e.session.id))})]})}function e$(){let{t:e}=(0,F.s)();return(0,r.jsxs)("span",{className:"session-waiting-indicator",title:e("sidebar.waitingForAnswerHint"),children:[(0,r.jsx)("span",{className:"workbench-lamp","data-kind":"input","aria-hidden":"true"}),e("sidebar.waitingForAnswer")]})}function eR(){let{t:e}=(0,F.s)();return(0,r.jsx)("span",{className:"session-running-indicator",title:e("sidebar.agentRunning"),"aria-label":e("sidebar.agentRunning"),role:"img",children:(0,r.jsx)("span",{className:"workbench-lamp","aria-hidden":"true"})})}function eL(){let{t:e}=(0,F.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(--text)"},children:(0,r.jsx)("span",{style:{width:6,height:6,borderRadius:3,background:"currentColor"}})})}function eP(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:4,color:"var(--text-muted)",fontSize:11,fontFamily:"var(--font-mono)"},children:[(0,r.jsx)("span",{className:"workbench-lamp","aria-hidden":"true"}),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(--text-muted)",fontSize:11,fontFamily:"var(--font-mono)"},children:[(0,r.jsx)("span",{style:{width:6,height:6,borderRadius:3,background:"var(--text)",display:"inline-block"}}),e.unread]})]}):null}function eA({session:e,isSelected:t,isRunning:n,isUnread:a,isPinned:i,onClick:l,onTogglePin:o,onRenamed:c,onDeleted:d,onArchived:u,depth:h=0,hasChildren:p=!1,collapsed:m=!1,onToggleCollapse:f}){let{t:g}=(0,F.s)(),[x,v]=(0,s.useState)(!1),y=ec(),b=null!==y&&y.besideSessionId===e.id,w=null!==y&&!e.transient&&!t&&!b,[k,j]=(0,s.useState)(!1),[S,C]=(0,s.useState)(""),[N,T]=(0,s.useState)(!1),[I,M]=(0,s.useState)(!1),E=(0,s.useRef)(null);(0,s.useEffect)(()=>{if(k){let e=requestAnimationFrame(()=>E.current?.select());return()=>cancelAnimationFrame(e)}},[k]);let $=_(e.firstMessage)??e.firstMessage,R=e.name||$.slice(0,50)||e.id.slice(0,12),L=(0,s.useCallback)(()=>{e.transient||(C(e.name||$.slice(0,50)||e.id.slice(0,12)),j(!0))},[e.name,e.transient,$,e.id]),P=(0,s.useCallback)(e=>{e.stopPropagation(),L()},[L]),A=(0,s.useCallback)(async()=>{let t=S.trim();if(j(!1),S!==R&&t!==(e.name??""))try{await fetch(`/api/sessions/${encodeURIComponent(e.id)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:t})}),c?.()}catch{}},[S,e.id,e.name,c,R]),O=(0,s.useCallback)(async()=>{if(!e.transient){T(!1),M(!0);try{await fetch(`/api/sessions/${encodeURIComponent(e.id)}`,{method:"DELETE"}),d?.(e.id)}catch{M(!1)}}},[e.id,e.transient,d]),z=(0,s.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]),D=(0,s.useCallback)(e=>{e.stopPropagation(),e.shiftKey?O():T(!0)},[O]),W=(0,s.useCallback)(e=>{e.stopPropagation(),O()},[O]),H=(0,s.useCallback)(e=>{e.stopPropagation(),T(!1)},[]),U=(0,s.useContext)(ed),[B,q]=(0,s.useState)(null),V=(0,s.useCallback)(()=>q(null),[]),K=(0,s.useCallback)(t=>{let n=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:()=>{c?.()}});if(!n&&e.transient||(t.preventDefault(),t.stopPropagation(),n))return;let r=t.currentTarget.getBoundingClientRect(),s=0!==t.clientX||0!==t.clientY;q({x:s?t.clientX:r.left+24,y:s?t.clientY:r.bottom})},[c,e.cwd,e.id,e.name,e.path,e.transient]),J=[];B&&(w&&y&&J.push({id:"beside",label:g("sidebar.openBeside"),disabledReason:y.blockedReason,onSelect:()=>y.openBeside(e)}),U&&J.push({id:"browser",label:g("sidebar.openBrowserBeside"),onSelect:()=>U(e)}),J.push({id:"rename",label:g("sidebar.rename"),onSelect:L}),o&&J.push({id:"pin",label:g(i?"sidebar.unpin":"sidebar.pin"),onSelect:o}));let G=(0,s.useCallback)(t=>{t.dataTransfer.setData(el,e.id),t.dataTransfer.effectAllowed="copy"},[e.id]);return(0,r.jsxs)("div",{className:`navigator-session-row${t?" is-selected":""}${b?" is-beside":""}${n?" is-running":""}${a?" is-unread":""}${N?" is-confirming":""}`,onClick:N||k?void 0:l,onContextMenu:N||k?void 0:K,draggable:w&&!N&&!k,onDragStart:!w||N||k?void 0:G,onMouseEnter:()=>v(!0),onMouseLeave:()=>{v(!1)},style:{height:40,display:"flex",alignItems:"center",paddingLeft:h>0?10*h+8:8,paddingRight:4,cursor:N||k?"default":"pointer",background:t?"var(--bg-selected)":x||b?"var(--bg-hover)":"transparent",transition:"background 0.1s",opacity:I?.5:1,gap:4,overflow:"hidden"},children:[N?(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:R.slice(0,22)+(R.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:H,style:{display:"flex",alignItems:"center",justifyContent:"center",height:30,padding:"0 11px",background:"var(--bg-hover)",border:0,borderRadius:"var(--radius-control)",color:"var(--text-muted)",cursor:"pointer",fontSize:12,fontWeight:500,whiteSpace:"nowrap"},children:g("sidebar.cancel")})]})]}):k?(0,r.jsx)("input",{ref:E,value:S,onChange:e=>C(e.target.value),onBlur:A,onKeyDown:e=>{"Enter"===e.key&&A(),"Escape"===e.key&&j(!1)},autoFocus:!0,style:{flex:1,fontSize:12,padding:"5px 8px",border:0,borderRadius:"var(--radius-control)",outline:"none",background:"var(--bg)",color:"var(--text)",height:30}}):(0,r.jsxs)(r.Fragment,{children:[h>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:R,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:R}),n&&(0,r.jsx)(eR,{}),!n&&a&&(0,r.jsx)(eL,{}),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"})]})})]}),p&&(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"})})}),b&&(0,r.jsx)("span",{style:{flexShrink:0,fontSize:11,color:"var(--text-dim)",whiteSpace:"nowrap"},children:g("sidebar.besidePane")}),!e.transient&&(0,r.jsxs)("div",{style:{display:"flex",gap:4,flexShrink:0},children:[w&&y&&(0,r.jsx)("button",{type:"button",className:"navigator-session-action",onClick:t=>{t.stopPropagation(),y.blockedReason||y.openBeside(e)},title:y.blockedReason??g("sidebar.openBeside"),"aria-label":g("sidebar.openBeside"),"aria-disabled":!!y.blockedReason||void 0,style:{display:"flex",alignItems:"center",justifyContent:"center",width:26,height:26,padding:0,background:"transparent",border:"none",borderRadius:"var(--radius-control)",color:"var(--text-muted)",cursor:y.blockedReason?"not-allowed":"pointer",flexShrink:0,opacity:x?y.blockedReason?.45:1:0,pointerEvents:x?"auto":"none",transition:"opacity 0.12s, background 0.12s, color 0.12s"},onFocus:()=>v(!0),children:(0,r.jsx)(ep,{name:"columns-2",size:13})}),(0,r.jsx)("button",{className:"navigator-session-action",onClick:e=>{e.stopPropagation(),o?.()},title:g(i?"sidebar.unpin":"sidebar.pin"),"aria-label":g(i?"sidebar.unpin":"sidebar.pin"),"aria-pressed":i,style:{display:"flex",alignItems:"center",justifyContent:"center",width:26,height:26,padding:0,background:i?"var(--bg-selected)":"transparent",border:"none",borderRadius:"var(--radius-control)",color:i?"var(--accent)":"var(--text-muted)",cursor:"pointer",flexShrink:0,opacity:x||i?1:0,pointerEvents:x||i?"auto":"none",transition:"opacity 0.12s, background 0.12s, color 0.12s"},onFocus:()=>v(!0),children:(0,r.jsx)(eT,{filled:i})}),(0,r.jsx)("button",{className:"navigator-session-action",onClick:P,title:g("sidebar.rename"),style:{display:"flex",alignItems:"center",justifyContent:"center",width:26,height:26,padding:0,background:"transparent",border:"none",borderRadius:"var(--radius-control)",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)"},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",{className:"navigator-session-action",onClick:z,title:g("sidebar.archive"),style:{display:"flex",alignItems:"center",justifyContent:"center",width:26,height:26,padding:0,background:"transparent",border:"none",borderRadius:"var(--radius-control)",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",{className:"navigator-session-action",onClick:D,title:g("sidebar.deleteWithShiftClick"),style:{display:"flex",alignItems:"center",justifyContent:"center",width:26,height:26,padding:0,background:"transparent",border:"none",borderRadius:"var(--radius-control)",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(--danger-soft)",e.currentTarget.style.color="var(--danger)"},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)("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"})]})})]})]}),B&&(0,r.jsx)(eu,{label:g("sidebar.rowMenu"),x:B.x,y:B.y,items:J,onClose:V})]})}let e_=/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~]|\][^\x07]*(?:\x07|\x1B\\))/g,eF=/^\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~]|\][^\x07]*(?:\x07|\x1B\\))/,eO=/\x1B\[([0-9;]*)m/g,ez=/\x1B_pi:c\x07/g,eD=["#1f2937","#dc2626","#16a34a","#d97706","#2563eb","#9333ea","#0891b2","#6b7280"],eW=["#9ca3af","#ef4444","#22c55e","#f59e0b","#3b82f6","#a855f7","#06b6d4","#e5e7eb"];function eH(e){return e.replace(ez,"").replace(e_,"")}function eU(e){let t=[],n=0;for(;n<e.length;){if(27===e.charCodeAt(n)){let t=e.slice(n).match(eF);if(t){n+=t[0].length;continue}}let r=e.codePointAt(n);if(void 0===r)break;let s=String.fromCodePoint(r);t.push({start:n,end:n+s.length,char:s}),n+=s.length}return t}function eB(e,t){let n=eU(e)[t];return n?e.slice(0,n.start)+e.slice(n.end):e}function eq(e){return eU(e)[0]?.char}function eV(e){let t=/^[┌├└╭╰][─┬┴┼]+[┐┤┘╮╯]$/,n=[];for(let r of e){let e=r.replace(ez,""),s=eH(e).trimEnd();if(t.test(s))continue;let a=e,i=eq(a);("│"===i||"┃"===i)&&" "===eq(a=eB(a,0))&&(a=eB(a,0));let l=function(e){let t=eU(e);for(let e=t.length-1;e>=0;e--)if(""!==t[e].char.trim())return e;return -1}(a),o=l>=0?eU(a)[l]?.char:void 0;("│"===o||"┃"===o)&&(a=eB(a,l)),n.push(function(e){let t=e;for(;;){let e=eU(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&&""===eH(n[0]).trim();)n.shift();for(;n.length>0&&""===eH(n[n.length-1]).trim();)n.pop();return n.length?n:e}function eK(e){let t,n=[],r={},s=0;for(eO.lastIndex=0;null!==(t=eO.exec(e));)t.index>s&&n.push({text:e.slice(s,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=eD[r-30];else if(r>=90&&r<=97)n.color=eW[r-90];else if(r>=40&&r<=47)n.backgroundColor=eD[r-40];else if(r>=100&&r<=107)n.backgroundColor=eW[r-100];else if((38===r||48===r)&&2===t[e+1]){let[s,a,i]=[t[e+2],t[e+3],t[e+4]];[s,a,i].every(e=>"number"==typeof e&&Number.isFinite(e))&&(38===r?n.color=`rgb(${s}, ${a}, ${i})`:n.backgroundColor=`rgb(${s}, ${a}, ${i})`),e+=4}else if((38===r||48===r)&&5===t[e+1]){let s=function(e){if(e>=0&&e<8)return eD[e];if(e>=8&&e<16)return eW[e-8];if(e>=16&&e<=231){let t=e-16,n=Math.floor(t/36),r=Math.floor(t%36/6),s=e=>0===e?0:55+40*e;return`rgb(${s(n)}, ${s(r)}, ${s(t%6)})`}if(e>=232&&e<=255){let t=8+(e-232)*10;return`rgb(${t}, ${t}, ${t})`}}(t[e+2]);s&&(38===r?n.color=s:n.backgroundColor=s),e+=2}}return n}(r,t[1]?t[1].split(";").map(e=>Number(e||"0")):[0]),s=t.index+t[0].length;return s<e.length&&n.push({text:e.slice(s),style:r}),n}let eJ={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:""},eG={ArrowLeft:"\x1bb",ArrowRight:"\x1bf",ArrowUp:"\x1bp",ArrowDown:"\x1bn"},eY={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"},eZ={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 eQ(e){return(e.replace(/\\/g,"/").split("/").pop()??"").toLowerCase().split(".").pop()??""}function eX(e){return null!==(eY[eQ(e)]??null)}function e0(e){let t;return null!==("pdf"===(t=eQ(e))||"docx"===t?t:null)}function e1(e,t,n={}){let r={...e,content:t};return n.omitUsage&&(r.usage=void 0),r}function e2(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 e4(e,t={}){return t.isStreaming||"error"!==e.stopReason?null:e.errorMessage?.trim()||"Unknown provider error"}function e8(e,t){let n=e[t];if(n?.role!=="assistant"||"error"!==n.stopReason)return!1;for(let n=t+1;n<e.length;n++){let t=e[n].role;if("user"===t)break;if("assistant"===t)return!0}return!1}function e5(e,t={}){let n=[];for(let r of function(e,t={}){return(e.content??[]).filter(e=>!e2(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 e6(e){return e.filter(e=>"toolCall"===e.type).length}let e3=/[\u3000-\u30ff\u3400-\u9fff\uf900-\ufaff\u{20000}-\u{2fa1f}\uac00-\ud7af]/u;function e7(e){let t=0,n=0;for(let r of e)e3.test(r)?t++:n++;return t+n/4}function e9(e){return"text"===e.type?e.text:"thinking"===e.type?e.thinking:"toolCall"===e.type?JSON.stringify(e.input??{})??"":null}function te(e,t){if(!e)return e7(t);let n=Math.min(e.text.length,t.length),r=0;for(;r<n&&e.text.charCodeAt(r)===t.charCodeAt(r);)r++;let s=r>0?t.charCodeAt(r-1):0;return s>=55296&&s<=56319&&r--,e.tokens-e7(e.text.slice(r))+e7(t.slice(r))}function tt(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 tn=/^\[[1-9]\d* tool result images? omitted from initial history payload(?:: [^\]\n]*)?, ~\d+ bytes\]$/;function tr(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,s){for(let a of s)"toolCall"===a.type&&function(e,t){let n;if(!t||t.isError)return!1;if(n=t.content?.at(-1),n?.type==="text"&&tn.test(n.text)||t.content?.some(e=>"image"===e.type))return!0;let r=e.input??{};if("generate_image"===e.toolName)return!0;if("write"===e.toolName)return"xd://generate_image"===r.path;if("bash"===e.toolName){let e=t.details;return"object"==typeof e&&null!==e&&"toolCommands"in e&&Array.isArray(e.toolCommands)&&e.toolCommands.some(e=>e?.tool==="generate_image"&&"execute"===e.mode&&0===e.exitCode)}return"read"===e.toolName&&"string"==typeof r.path&&eX(r.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 ts=new Map,ta=new Map,ti="[한국어 번역]\n";function tl(e){return e.filter(e=>"text"===e.type&&"string"==typeof e.text).map(e=>e.text).join("\n")}function to(e){if("custom"!==e.role||"korean-reply-translation"!==e.customType)return null;let t=e.details;if(!t||"object"!=typeof t)return null;let n="sourceTimestamp"in t&&"number"==typeof t.sourceTimestamp?t.sourceTimestamp:void 0,r="sourceHash"in t&&"string"==typeof t.sourceHash?t.sourceHash:void 0;return void 0===n&&void 0===r?null:{sourceTimestamp:n,sourceHash:r}}let tc="command",td="autolearn-saved";function tu(e){return"custom"===e.role&&(e.customType===tc||e.customType===td&&!1!==e.display)}function th(e,t){let n=e[t];if(n?.role!=="custom"||"user-input-translation"!==n.customType)return -1;for(let n=t-1;n>=0;n--)if("user"===e[n].role)return n;return -1}let tp="local-command:";function tm(e){return e?.startsWith(tp)===!0}function tf(e,t,n){let r=new Set(n.map(e=>e.message)),s=[],a=[];for(let n=0;n<e.length;n++){let i=n<t.length;!(r.has(e[n])||i&&tm(t[n]))&&(s.push(e[n]),i&&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<s.length;){let e=s[t];if(!r.has(e)&&"number"==typeof e.timestamp&&e.timestamp>n)break;t+=1}s.splice(t,0,e.message),t<=a.length&&a.splice(t,0,e.entryId)}return{messages:s,entryIds:a}}function tg(e){return"user"===e.role||"custom"===e.role&&"compaction"===e.customType}let tx={create:!0,update:!0};function tv(e){return"string"==typeof e?e.replace(/\s+/g," ").trim():""}function ty(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 tb(e,t){if(0===e.length)return -1;if(!t)return 0;let n=-1;for(let r=0;r<e.length;r++){let s=e[r];if(s.item===t.item){if(s.k===t.k)return r;n=r}}return -1===n?0:n}function tw(e){try{return decodeURIComponent(e)}catch{return e}}function tk(e){return/^[a-zA-Z]:[\\/]/.test(e)||e.startsWith("\\\\")?e.replace(/\\/g,"/"):e}function tj(e){let t=tk(e),n=/^[a-zA-Z]:\//.test(t),r=t.startsWith("//"),s=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():s||n||r||a.push(e);continue}a.push(e)}let i=a.join("/");return n?i:r?`//${i}`:s?`/${i}`:i}function tS(e,t,n=t){let r,s,a,i,l;if(!e)return null;let o=e.split("#",1)[0].split("?",1)[0].trim();if(!o)return null;let c=null,d=null,u=tw(o),h=u.startsWith("\\\\"),p=tk(u),m=p.toLowerCase();if(m.startsWith("/api/")||m.startsWith("/_next/")||!h&&p.startsWith("//")||/^[a-zA-Z][a-zA-Z0-9+.-]*:/i.test(p)&&!m.startsWith("file:")&&!/^[a-zA-Z]:\//.test(p))return null;if(m.startsWith("file:")?d=(c=function(e){try{let t=new URL(e);if("file:"!==t.protocol)return null;let n=tw(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}}(p))?"absolute":null:/^[a-zA-Z]:\//.test(p)||p.startsWith("/")?(c=p,d="absolute"):t&&!(p.startsWith("#")||p.startsWith("?"))&&(p.startsWith("./")||p.startsWith("../")||p.includes("/")||/(^|\/)\.?[^/]+\.[^/.]+$/.test(p))&&(c=`${tk(t).replace(/\/+$/,"")}/${p}`,d="relative"),!c)return null;let f=tj(c).replace(/:\d+(?::\d+)?$/,"");return"relative"===d&&n&&(r=tj(f).replace(/\/+$/,""),s=tj(n).replace(/\/+$/,""),i=(a=/^[a-zA-Z]:\//.test(r)||/^[a-zA-Z]:\//.test(s))?r.toLowerCase():r,!(i===(l=a?s.toLowerCase():s)||i.startsWith(`${l}/`)))?null:f}function tC(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("\\\\")),s=e=>r?e.replace(/\\/g,"/"):e,a=s(e),i=t?s(t).replace(/\/+$/,""):void 0,l=/^[a-zA-Z]:\//.test(a),o=a.startsWith("//");if(l||o)n=a;else if(a.startsWith("/")){let e=i?.match(/^([a-zA-Z]:)(?:\/|$)/)?.[1]??i?.match(/^(\/\/[^/]+\/[^/]+)(?:\/|$)/)?.[1];n=e?`${e}${a}`:a}else{if(!i)return null;n=`${i}/${a}`}return tj(n)}function tN(e){let t=e.toLowerCase();return"write"===t||t.startsWith("write_")||t.endsWith(".write")||t.endsWith("_write")}function tT(e){let t=e.toLowerCase();return"edit"===t||t.startsWith("edit_")||t.endsWith(".edit")||t.endsWith("_edit")||t.includes("str_replace")||t.includes("replace_editor")}function tI(e){if(!e)return null;let t=e.file_path??e.path;return"string"==typeof t&&t.length>0?t:null}function tM(e,t){if(!e||"object"!=typeof e||"delete"===e.op&&!t)return null;let n=e.path??e.resolvedPath;return"string"==typeof n&&n.length>0?n:null}function tE(e,t,n=!1){let r=t.details,s=tI(e);if(s)return!n&&r&&"object"==typeof r&&"delete"===r.op?[]:[s];if(!r||"object"!=typeof r)return[];if(Array.isArray(r.perFileResults))return r.perFileResults.map(e=>tM(e,n)).filter(e=>null!==e);let a=tM(r,n);return a?[a]:[]}function t$(e,t){let n=tI(e);return(t?tE(e,t,!0):n?[n]:[]).filter(t_)}function tR(e,t,n){let r=t$(e,t);return r.length>0&&r.every(e=>tA(e,n))}let tL=new Map(["skills","commands","rules","prompts","extensions","instructions","hooks","tools","agents","plugins","mcp.json",".mcp.json","SYSTEM.md","SYSTEM_TEMPLATE.md","APPEND_SYSTEM.md","AGENTS.md","settings.json","config.yml","secrets.yml"].map(e=>[e.toLowerCase(),e])),tP=[/^\/(?:private\/)?(?:var\/)?tmp(?:\/|$)/,/^\/(?:private\/)?var\/folders\/[^/]+\/[^/]+\/T(?:\/|$)/,/^(?:[a-z]:|\/mnt\/[a-z])\/(?:windows\/)?temp(?:\/|$)/i,/^(?:[a-z]:|\/mnt\/[a-z])\/users\/[^/]+\/appdata\/local\/temp(?:\/|$)/i];function tA(e,t){let n=tC(e,t),r=t?tC(t)?.replace(/\/+$/,""):void 0,s=n??e.replace(/\\/g,"/"),a=/^(?:[a-zA-Z]:\/|\/\/|\/mnt\/[a-zA-Z](?:\/|$))/.test(s)||void 0!==r&&/^(?:[a-zA-Z]:\/|\/\/)/.test(r),i=e=>a?e.toLowerCase():e,l=null===n||void 0!==r&&(i(n)===i(r)||i(n).startsWith(`${i(r)}/`));return!!function(e,t){let n=(e,n)=>void 0!==e&&(t?e.toLowerCase()===n:e===n),r=e.findIndex(e=>n(e,".omp"));if(r<0||r===e.length-1)return!1;let s=e[r+1];if(n(s,"agent")||n(s,"wt")||n(s,"profiles")&&n(e[r+3],"agent"))return!1;let a=tL.get(s.toLowerCase());return!(void 0!==a&&(t||a===s))}((null!==n&&l&&void 0!==r?n.slice(r.length):s).split("/").filter(e=>""!==e&&"."!==e),a)||!l&&tP.some(e=>e.test(s))}function t_(e){return!!/^[a-zA-Z]:[\\/]/.test(e)||!/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//.test(e)}function tF(e,t,n){let r=new Set,s=[];for(let i of e){var a;if("toolCall"!==i.type||!(tN(a=i.toolName)||tT(a)))continue;let e=t?.get(i.toolCallId);if(e&&!e.isError)for(let t of tE(i.input,e)){if(!t_(t))continue;let e=tC(t,n);!(!e||tA(t,n))&&(r.has(e)||(r.add(e),s.push({filePath:e})))}}return s}function tO(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 s=Array.isArray(r)?r.flatMap(e=>{if(!e||"object"!=typeof e||!("content"in e)||!("status"in e))return[];let{content:t,status:n}=e;if("string"!=typeof t||"pending"!==n&&"in_progress"!==n&&"completed"!==n&&"abandoned"!==n&&"blocked"!==n)return[];let r="blocker"in e&&"string"==typeof e.blocker?e.blocker:void 0,s="dependsOn"in e&&Array.isArray(e.dependsOn)?e.dependsOn.filter(e=>"string"==typeof e):[];return[{content:t,status:n,blocker:r,...s.length>0?{dependsOn:s}:{}}]}):[];if(s.length!==r.length)return{phases:t,malformed:!0};s.length>0&&t.push({name:e,tasks:s})}return{phases:t,malformed:!1}}function tz(e){if(!Array.isArray(e))return null;let{phases:t,malformed:n}=tO(e);return n?null:t}function tD(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:s}=tO(n);return s?{kind:"unknown"}:{kind:"authoritative",phases:r}}let s=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 s.length>0?{kind:"preview",phases:s}:{kind:"unknown"}}function tW(e){if(!e)return!1;let t=e.toLowerCase();return"todo"===t||t.endsWith(".todo")||t.endsWith("_todo")}function tH(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],s=r.trackerTodos??[];for(let e=s.length-1;e>=0;e-=1){let t=tz(s[e]);if(t)return t}if("assistant"!==r.role)continue;let a=r.content;if(Array.isArray(a))for(let e=a.length-1;e>=0;e-=1){let n=a[e];if("toolCall"!==n.type||!tW(n.toolName))continue;let r=tD(n,t.get(n.toolCallId));if("unknown"!==r.kind)return r.phases}}return null}(e,t)??r)}function tU(e,t){if(!e.dependsOn?.length)return[];let n=new Set(t.flatMap(e=>e.tasks.filter(e=>"completed"===e.status).map(e=>e.content)));return e.dependsOn.filter(e=>!n.has(e))}function tB(e){let t=0,n=0,r=null,s=null,a=null;for(let i of e)for(let l of i.tasks){if("completed"===l.status){t+=1;continue}"abandoned"!==l.status&&(n+=1,tU(l,e).length>0?a||(a={phase:i,task:l}):"in_progress"===l.status?r||(r={phase:i,task:l}):"blocked"===l.status?a||(a={phase:i,task:l}):s||(s={phase:i,task:l}))}let i=r??s??a,l=t+n;return{currentPhase:i?.phase??null,activeTask:i?.task??null,remaining:n,completed:t,total:l,percent:l>0?Math.round(t/l*100):null}}function tq(e){return/^[a-zA-Z]:[\\/]/.test(e)||e.startsWith("\\\\")?e.replace(/\\/g,"/"):e}function tV(e){return tq(e).split("/").filter(Boolean).map(encodeURIComponent).join("/")}function tK(e){let t=tq(e).replace(/\/+$/,"");return t.split("/").pop()??t}function tJ(e,t){if(!t)return e;let n=tq(e),r=tq(t).replace(/\/$/,"");return n.startsWith(r+"/")?n.slice(r.length+1):e}let tG=(0,s.createContext)(null),tY=(0,s.createContext)(null);var tZ=n(65063),tQ=n(7644),tX=n(32316),t0=n(88374),t1=n(47680),t2=n(94764),t4=n(63835),t8=n(54152),t5=n(84678),t6=n(98164);let t3={...t2.j,attributes:{...t2.j.attributes,code:[["className",/^language-./,"math-inline","math-display"]]},strip:[...t2.j.strip||[],"iframe","object","style","form"]};function t7(e){let t=e.includes("\r\n")?"\r\n":"\n",n=e.split(/\r?\n/),r=[],s=null,a=0,i=null,l=new Map;for(let e=0;e<n.length;e++){var o;let t=n[e];if(i){r.push(t),RegExp(`</${i}\\s*>`,"i").test(t)&&(i=null);continue}let c=t.match(/^ {0,3}(`{3,}|~{3,})/);if(c){let e=c[1][0],n=c[1].length;s?e===s.marker&&n>=s.size&&(s=null):s={marker:e,size:n},a=0,r.push(t);continue}if(s){r.push(t);continue}let d=t.match(/<(code|pre|script|style)\b/i);if(d){let e=d[1].toLowerCase(),n=t.slice((d.index??0)+d[0].length);RegExp(`</${e}\\s*>`,"i").test(n)||(i=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 s=r-t;0===n?n=s:s===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 h=t.match(/^([ ]{0,3})\\\[[ \t]*$/);if(h){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(`${h[1]}$$`,...n.slice(e+1,t).map(e=>ne(e,h[1])),`${h[1]}$$`),e=t;continue}}let p=t.match(/^([ \t]{0,3})\$\$(.+)\$\$[ \t]*$/);if(p){let e=p[2].trim();if(e){r.push(`${p[1]}$$`,`${p[1]}${e}`,`${p[1]}$$`);continue}}let m=t.match(/^([ \t]{0,3})\$\$(.+)$/);if(m){let t=m[1],s=m[2].trimEnd();if(s&&!s.includes("$$")){let a=t9(n,e+1,t,l);if(a){r.push(`${t}$$`,`${t}${s}`);for(let s=e+1;s<a.index;s++)r.push(ne(n[s],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],s=t9(n,e+1,t,l);if(s&&(s.glued||""!==t)){r.push(`${t}$$`);for(let a=e+1;a<s.index;a++)r.push(ne(n[a],t));s.content&&r.push(`${t}${s.content}`),r.push(`${t}$$`),e=s.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 t9(e,t,n,r){let s=r.get(n);if(void 0!==s&&t<s)return null;for(let s=t;s<e.length;s++){var a,i,l,o;let t=e[s];if(a=t,""===(i=n)?/^ {0,3}\$\$\s*$/.test(a):a.startsWith(i)&&/^\$\$\s*$/.test(a.slice(i.length)))return{index:s,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,s),null;let c=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!==c)return{index:s,content:c,glued:!0}}return r.set(n,e.length),null}function ne(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 nt={singleTilde:!1},nn=[[t8.A,["yaml"]],[t5.A,nt],t6.A],nr=[[t8.A,["yaml"]],[t5.A,nt],t6.A],ns=[t1.A,[t4.A,t3],[t0.A,{throwOnError:!1,strict:!1}]],na=[t1.A,[t4.A,t3],[t0.A,{throwOnError:!1,strict:!1}]],ni="pi-theme",nl=["light","dark","auto"],no={preference:"auto",theme:"light"},nc="omp-theme",nd=null,nu=0,nh=new Set,np=null,nm=!1;function nf(){return window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}function ng(e){return"auto"===e?nf():e}let nx="--omp-md-";function nv(e){let t=document.documentElement,n=nd?.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(nx)&&t.style.removeProperty(n)}if(n){for(let[e,r]of Object.entries(n.variables))e.startsWith(nx)&&t.style.setProperty(e,r);t.dataset.ompThemeName=n.name}try{localStorage.setItem(nc,e)}catch{}}function ny(){if(np)return np;let e=function(){try{let e=localStorage.getItem(ni);if("light"===e||"dark"===e||"auto"===e)return e;let t=localStorage.getItem(nc);if("light"===t||"dark"===t)return t}catch{}return"auto"}(),t=ng(e);return nv(t),np={preference:e,theme:t}}function nb(e,t,n){if(nv(t),n)try{localStorage.setItem(ni,e)}catch{}np={preference:e,theme:t},nh.forEach(e=>e())}function nw(){let e=ny();if("auto"!==e.preference)return;let t=nf();t!==e.theme&&nb("auto",t,!1)}function nk(e){return nh.add(e),ny(),nm||!window.matchMedia||(window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change",nw),window.addEventListener("focus",nw),document.addEventListener("visibilitychange",()=>{"visible"===document.visibilityState&&nw()}),nm=!0),nw(),()=>{nh.delete(e)}}function nj(){return ny()}function nS(){return no}async function nC(e){let t=++nu,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 s=await r.json();if(t===nu){nd=s;try{localStorage.setItem("omp-theme-config",JSON.stringify(nd))}catch{}nv(ny().theme)}}function nN(e){let t=(0,s.useSyncExternalStore)(nk,nj,nS);(0,s.useEffect)(()=>{e?.syncWithOmp&&nC(e.cwd).catch(()=>{})},[e?.cwd,e?.syncWithOmp]);let n=(0,s.useCallback)((e,t)=>{let n=ng(e),r=()=>{nb(e,n,!0)},s=window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;if("function"!=typeof document.startViewTransition||s)return void r();let a=t?.x??window.innerWidth/2,i=t?.y??window.innerHeight/2,l=Math.hypot(Math.max(a,window.innerWidth-a),Math.max(i,window.innerHeight-i));document.startViewTransition(r).ready.then(()=>{document.documentElement.animate({clipPath:[`circle(0px at ${a}px ${i}px)`,`circle(${l}px at ${a}px ${i}px)`]},{duration:450,easing:"cubic-bezier(0.22, 0.61, 0.36, 1)",pseudoElement:"::view-transition-new(root)"})}).catch(()=>{})},[]),r=(0,s.useCallback)(e=>{var t;let r;n((t=ny().preference,r=nl.indexOf(t),nl[(r+1)%nl.length]),e)},[n]),a=(0,s.useCallback)((e,t)=>{n(e,t)},[n]);return{theme:t.theme,preference:t.preference,toggleTheme:r,setPreference:a,isDark:"dark"===t.theme}}function nT(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 nI={...tQ.vs,...Object.fromEntries(["url","symbol","number","boolean","variable","constant","inserted"].map(e=>[e,{...tQ.vs[e],color:"var(--seed-color-palette-green-800)"}]))};function nM({code:e,isStreaming:t}){let{isDark:a}=nN(),{t:i}=(0,F.s)(),[l,o]=(0,s.useState)(!0),[c,d]=(0,s.useState)(null),[u,h]=(0,s.useState)(!1),p=`${a?"dark":"light"}
4
4
  ${e}`,m=l&&!t;(0,s.useEffect)(()=>{if(!m)return;let t=!1;return d({key:p,status:"loading"}),(async()=>{let{default:r}=await Promise.all([n.e(866),n.e(8367),n.e(3308)]).then(n.bind(n,43328)),s=getComputedStyle(document.body).fontFamily;if(await document.fonts.load(`16px ${s}`,e),await document.fonts.ready,t)return;if(r.initialize({startOnLoad:!1,securityLevel:"strict",suppressErrorRendering:!0,theme:a?"dark":"default",fontFamily:s}),!await r.parse(e,{suppressErrors:!0}))throw Error("Invalid Mermaid diagram");let i="u">typeof crypto&&"randomUUID"in crypto?`mermaid-${crypto.randomUUID()}`:`mermaid-${Date.now()}-${Math.random().toString(36).slice(2)}`,l=await r.render(i,e);t||d({key:p,status:"ready",svg:l.svg})})().catch(()=>{t||d({key:p,status:"error"})}),()=>{t=!0}},[e,p,a,m]);let f=(0,s.useMemo)(()=>(0,r.jsx)("button",{type:"button",onClick:()=>o(e=>!e),disabled:t,title:t?i("i18n.previewAfterStreaming"):m?i("i18n.showMermaidSource"):i("i18n.previewMermaid"),className:["markdown-code-action",m?"is-active":""].filter(Boolean).join(" "),children:m?i("i18n.source"):i("i18n.preview")}),[t,m,i]);if(!m)return(0,r.jsx)(n$,{code:e,lang:"mermaid",headerAction:f,isStreaming:t});let g=c?.key===p&&"error"===c.status?(0,r.jsx)("div",{className:"mermaid-block mermaid-block-error",children:i("i18n.invalidMermaid")}):c?.key!==p||"ready"!==c.status?(0,r.jsx)("div",{className:"mermaid-block mermaid-block-loading","aria-label":i("i18n.renderingMermaid")}):(0,r.jsxs)(r.Fragment,{children:[!u&&(0,r.jsx)("button",{type:"button",className:"mermaid-block mermaid-preview-button",title:i("i18n.openMermaidViewer"),"aria-label":i("i18n.openMermaidViewer"),onClick:()=>h(!0),dangerouslySetInnerHTML:{__html:c.svg}}),u&&(0,r.jsx)(nE,{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"}),f]}),g]})}function nE({svg:e,onClose:t}){let{t:n}=(0,F.s)(),a=(0,s.useRef)(null),[i,l]=(0,s.useState)(1);return(0,s.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:i<=.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*i),"%"]}),(0,r.jsx)("button",{type:"button",onClick:()=>l(e=>Math.min(3,e+.25)),disabled:i>=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*i}%`},dangerouslySetInnerHTML:{__html:e}})})]})})}let n$=(0,s.memo)(function({code:e,lang:t,headerAction:n,isStreaming:a}){let{isDark:i}=nN(),{t:l}=(0,F.s)(),[o,c]=(0,s.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:()=>{nT(e).then(()=>{c(!0),setTimeout(()=>c(!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)(tZ.A,{language:t||"text",style:i?tQ.xJ:nI,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})]})});var nR=n(24568);let nL=/surface not found/i;class nP{constructor(e,t){this.createProcessor=e,this.send=t,this.applied=[],this.byPosition=new Map,this.partPosition=new Map,this.lastMessages=null,this.sentCodes=new Set,this.pending=new Map,this.listeners=new Set,this.version=0,this.dirty=!1,this.subscribe=e=>(this.listeners.add(e),()=>this.listeners.delete(e)),this.getVersion=()=>this.version,this.handleAction=e=>{let t=this.processor.getSurface(e.surfaceId);if("sending"===this.pending.get(e.surfaceId)||"queued"===this.pending.get(e.surfaceId))return;let n=(0,nR.Df)(e,t?.sendDataModel?t.dataModel.get("/"):void 0),r=(0,nR.fG)(n);this.sentCodes.add(JSON.stringify(n)),this.pending.set(e.surfaceId,"sending"),this.bump();let s=t=>{void 0!==this.pending.get(e.surfaceId)&&("failed"===t?this.pending.set(e.surfaceId,"failed"):"followUp"===t&&this.pending.set(e.surfaceId,"queued"),this.bump())};Promise.resolve().then(()=>this.send(r)).then(s,()=>s("failed"))},this.processor=e(this.handleAction)}sync(e){if(e===this.lastMessages)return;this.lastMessages=e,this.partPosition=new Map,e.forEach((e,t)=>{"assistant"===e.role&&Array.isArray(e.content)&&e.content.forEach((e,n)=>{var r,s;"object"==typeof e&&null!==e&&this.partPosition.set(e,(r=t,s=n,`${r}:${s}`))})});let t=(0,nR.Kn)(e),n=(0,nR.U5)(this.applied,t);if(n<this.applied.length)for(let e of(this.processor.dispose(),this.processor=this.createProcessor(this.handleAction),this.applied=[],this.pending.clear(),this.sentCodes.clear(),t))this.applied.push(this.apply(e,!1));else for(let e of t.slice(n))this.applied.push(this.apply(e,!0));this.byPosition=new Map,t.forEach((e,t)=>{var n,r;let s=(n=e.messageIndex,r=e.partIndex,`${n}:${r}`),a=this.byPosition.get(s)??[];a.push(this.applied[t]),this.byPosition.set(s,a)}),this.dirty=!0}flush(){this.dirty&&(this.dirty=!1,this.bump())}lookup(e,t,n){let r=this.partPosition.get(e);if(void 0===r)return;let s=this.byPosition.get(r)??[],a=void 0===t?void 0:s[t],i=a?.code===n?a:s.find(e=>e.code===n);return i?.view??void 0}liveSurface(e){return this.processor.getSurface(e.id)===e}actionState(e){return this.pending.get(e)}dispose(){this.processor.dispose(),this.listeners.clear()}bump(){for(let e of(this.version+=1,this.listeners))e()}apply(e,t){return"action"===e.kind?(this.applyAction(e.code,t),{kind:e.kind,code:e.code,view:null}):{kind:e.kind,code:e.code,view:this.applyAgent(e.code)}}applyAgent(e){let t=(0,nR.in)(e);if(!t.ok)return{error:{reason:t.reason},surfaces:[],created:[],updated:[],deleted:[],missing:[]};let n=(0,nR.Oe)(t.messages),r=new Set(this.processor.getSurfaces().keys()),s=this.processor.processMessagesWithErrors(t.messages).map(e=>e.error),a=e=>!!e.surfaceId&&nL.test(e.message),i=[...new Set(s.filter(a).map(e=>e.surfaceId))],l=s.filter(e=>!a(e)),o=new Set(l.map(e=>e.surfaceId).filter(Boolean)),c=n.created.filter(e=>!r.has(e)).map(e=>this.processor.getSurface(e)).filter(e=>void 0!==e);return{error:l.length>0?{reason:"processor",detail:l.map(e=>e.message||e.code).filter(Boolean).join(" / ")}:null,surfaces:c,created:n.created,updated:n.updated.filter(e=>!o.has(e)&&!i.includes(e)),deleted:n.deleted.filter(e=>!o.has(e)&&!i.includes(e)),missing:i}}applyAction(e,t){let n=(0,nR.v6)(e);if(!n)return;let r=n.action.surfaceId;if(this.sentCodes.has(e)&&(this.pending.delete(r),t))return;let s=n.metadata?.a2uiClientDataModel.surfaces[r];void 0!==s&&this.processor.getSurface(r)&&this.processor.processMessagesWithErrors([{version:"1.0",updateDataModel:{surfaceId:r,path:"/",value:s}}])}}let nA=(0,s.createContext)(void 0),n_=(0,s.createContext)(null);function nF({part:e,children:t}){return(0,r.jsx)(n_.Provider,{value:e,children:t})}function nO({sessionKey:e,messages:t,onSend:a,children:i}){let[l,o]=(0,s.useState)(null),[c,d]=(0,s.useState)(!1),u=(0,s.useMemo)(()=>null!==l||t.some(e=>("assistant"===e.role||"user"===e.role)&&JSON.stringify(e.content??"").includes(nR.di)),[l,t]);(0,s.useEffect)(()=>{if(!u||l||c)return;let e=!0;return Promise.all([n.e(4562),n.e(8517)]).then(n.bind(n,38517)).then(t=>{e&&o(t)},()=>{e&&d(!0)}),()=>{e=!1}},[u,l,c]);let h=(0,s.useRef)(a);(0,s.useEffect)(()=>{h.current=a},[a]);let p=(0,s.useMemo)(()=>l?new nP(l.createProcessor,e=>h.current(e)):null,[l,e]);(0,s.useEffect)(()=>()=>p?.dispose(),[p]),(0,s.useLayoutEffect)(()=>{p?.sync(t),p?.flush()},[p,t]);let m=(0,s.useMemo)(()=>p&&l?{store:p,runtime:l}:null,[p,l]);return(0,r.jsx)(nA.Provider,{value:c?void 0:m,children:i})}let nz={json:"카드 내용을 읽지 못했어요. JSON이 끝까지 쓰이지 않았거나 형식이 틀렸어요.",shape:"카드 메시지 형식이 맞지 않아요.",empty:"카드 블록이 비어 있어요.",processor:"카드의 일부를 그리지 못했어요."},nD={sending:"보내는 중…",queued:"지금 답이 끝나면 전달돼요.",failed:"보내지 못했어요. 다시 눌러 주세요."};function nW({children:e,tone:t}){return(0,r.jsx)("p",{className:"a2ui-answer-note","data-tone":t,children:e})}function nH({surface:e,store:t,runtime:n}){let s=t.actionState(e.id),a="sending"===s||"queued"===s;return(0,r.jsxs)("div",{className:"a2ui-answer-card","data-surface-id":e.id,"aria-busy":a||void 0,inert:a||void 0,children:[(0,r.jsx)(n.SurfaceView,{surface:e}),s&&(0,r.jsx)("p",{className:"a2ui-answer-status",role:"status","data-state":s,children:nD[s]})]})}let nU=(0,s.createContext)("");function nB({code:e,offset:t,isStreaming:n}){let a=(0,s.useContext)(nA),i=(0,s.useContext)(n_),l=(0,s.useContext)(nU),o=a?.store;if((0,s.useSyncExternalStore)(o?.subscribe??nV,o?.getVersion??nK,nK),void 0===a||!i&&!n)return(0,r.jsx)(n$,{code:e,lang:nR.di,isStreaming:n});if(n||!a)return(0,r.jsx)(nW,{children:"카드를 그리는 중…"});let c=void 0===t?void 0:(0,nR.$y)(l.slice(0,t),nR.di).length,d=a.store.lookup(i,c,e);if(!d)return(0,r.jsx)(n$,{code:e,lang:nR.di});let u=d.surfaces.filter(e=>a.store.liveSurface(e)),h=d.surfaces.filter(e=>!u.includes(e)).map(e=>e.id),p=d.updated.filter(e=>!d.created.includes(e)),m=d.deleted,f=d.error&&(0,r.jsxs)(nW,{tone:"error",children:[nz[d.error.reason],d.error.detail?` (${d.error.detail})`:""]});if(d.error&&"processor"!==d.error.reason)return(0,r.jsxs)("div",{className:"a2ui-answer-invalid",children:[(0,r.jsx)(n$,{code:e,lang:nR.di}),f]});let g=[...p.map(e=>`‘${e}’ 카드를 고쳤어요.`),...m.map(e=>`‘${e}’ 카드를 닫았어요.`),...h.filter(e=>!m.includes(e)).map(e=>`‘${e}’ 카드는 닫혔어요.`),...d.missing.map(e=>`‘${e}’ 카드가 이 대화에 없어 변경을 건너뛰었어요.`)];return 0===u.length&&0===g.length?(0,r.jsxs)("div",{className:"a2ui-answer-invalid",children:[(0,r.jsx)(n$,{code:e,lang:nR.di}),f]}):(0,r.jsxs)("div",{className:"a2ui-answer",children:[u.map(e=>(0,r.jsx)(nH,{surface:e,store:a.store,runtime:a.runtime},e.id)),g.map(e=>(0,r.jsx)(nW,{children:e},e)),d.error&&(0,r.jsx)(n$,{code:e,lang:nR.di}),f]})}function nq({envelope:e,code:t}){let n=Object.entries(e.action.context??{}).map(([e,t])=>`${e}: ${"string"==typeof t?t:JSON.stringify(t)}`).join(", ");return(0,r.jsxs)("details",{className:"a2ui-action-chip",children:[(0,r.jsxs)("summary",{children:[(0,r.jsxs)("span",{className:"a2ui-action-chip-name",children:["카드 동작: ",e.action.name]}),(0,r.jsx)("span",{className:"a2ui-action-chip-meta",children:[`카드 ${e.action.surfaceId}`,n].filter(Boolean).join(", ")})]}),(0,r.jsx)(n$,{code:t,lang:nR.aO})]})}let nV=()=>()=>{},nK=()=>0;function nJ({children:e,className:t,isStreaming:n,cwd:a,onOpenFile:i}){let l=(0,s.useMemo)(()=>t7(e),[e]),o=(0,s.useMemo)(()=>({code({className:e,children:t,node:s,...a}){let i=e?.replace("language-","").toLowerCase()??"",l=String(t);return e?.includes("language-")||l.includes("\n")?"mermaid"===i?(0,r.jsx)(nM,{code:l.replace(/\n$/,""),isStreaming:n}):i===nR.di?(0,r.jsx)(nB,{code:l.replace(/\n$/,""),offset:s?.position?.start.offset,isStreaming:n}):(0,r.jsx)(n$,{code:l.replace(/\n$/,""),lang:i,isStreaming:n}):(0,r.jsx)("code",{className:"markdown-inline-code",...a,children:t})},pre:({children:e})=>(0,r.jsx)(r.Fragment,{children:e}),a({href:e,children:t,...n}){delete n.node;let s=i?tS(e,a):null;return s&&i?(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(),i(s))},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 s="string"==typeof e?tS(e,a):null,i=s?`/api/files/${tV(s)}?type=read`:e;return(0,r.jsx)("img",{src:i,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,i]);return(0,r.jsx)("div",{className:["markdown-body",t].filter(Boolean).join(" "),children:(0,r.jsx)(nU.Provider,{value:l,children:(0,r.jsx)(tX.oz,{remarkPlugins:nn,rehypePlugins:ns,components:o,children:l})})})}function nG(e){let[t,n]=(0,s.useState)(()=>Date.now());return(0,s.useEffect)(()=>{let t=setInterval(()=>n(Date.now()),e);return()=>clearInterval(t)},[e]),t}let nY=new Map,nZ=new Set;function nQ(){nZ.forEach(e=>e())}function nX(e){return nZ.add(e),()=>{nZ.delete(e)}}function n0(e,t){return e&&t?`${e}\u0000${t}`:null}function n1(e){let t=!1;for(let n of e)t=nY.delete(n)||t;t&&nQ()}var n2=n(54265);let n4=(0,s.createContext)(null);function n8(e,t,n){return Math.min(n,Math.max(t,e))}function n5(e,t,n){let r=t.width>0?n.width/t.width:0,s=t.height>0?n.height/t.height:0;return{x:n8((e.x-t.left)*r,0,n.width),y:n8((e.y-t.top)*s,0,n.height)}}function n6(e){let t=n8(Math.round(.004*Math.max(e.width,e.height)),2,12);return{inner:t,outer:2*t}}let n3="#e5191f",n7="#ffffff";function n9(e){let{promise:t,resolve:n,reject:r}=Promise.withResolvers();return e.toBlob(e=>e?n(e):r(Error("canvas encode failed")),"image/png"),t}function re(e,t){let n=document.createElement("canvas");n.width=e,n.height=t;let r=n.getContext("2d");if(!r)throw Error("canvas 2d unavailable");return[n,r]}async function rt(e,t){let n=await createImageBitmap(e);try{let e={width:n.width,height:n.height},{inner:r,outer:s}=n6(e),a=Math.max(14,7*n6(e).inner),[i,l]=re(e.width,e.height);l.drawImage(n,0,0),t.forEach((t,n)=>{let i=function(e,t){let{inner:n,outer:r}=n6(t),s=(n,r)=>{let s=n8(e.x-n,r,t.width-r),a=n8(e.y-n,r,t.height-r),i=n8(e.x+e.w+n,r,t.width-r);return{x:s,y:a,w:Math.max(0,i-s),h:Math.max(0,n8(e.y+e.h+n,r,t.height-r)-a)}};return{inner:s(n/2,n/2),outer:s(n+r/2,r/2)}}(t,e);l.lineJoin="miter",l.strokeStyle=n7,l.lineWidth=s,l.strokeRect(i.outer.x,i.outer.y,i.outer.w,i.outer.h),l.strokeStyle=n3,l.lineWidth=r,l.strokeRect(i.inner.x,i.inner.y,i.inner.w,i.inner.h);let o=String(n+1);l.font=`700 ${a}px sans-serif`;let c=Math.round(.35*a),d=Math.ceil(l.measureText(o).width)+2*c,u=Math.round(1.3*a),h=Math.min(Math.max(0,t.x-r),e.width-d),p=t.y-r-u,m=p>=0?p:Math.min(t.y,e.height-u);l.fillStyle=n7,l.fillRect(h-1,m-1,d+2,u+2),l.fillStyle=n3,l.fillRect(h,m,d,u),l.fillStyle=n7,l.textBaseline="middle",l.textAlign="center",l.fillText(o,h+d/2,m+u/2)});let o=await Promise.all(t.map(t=>{let r=function(e,t,n=.12){let r=Math.round(e.w*n),s=Math.round(e.h*n),a=n8(e.x-r,0,t.width),i=n8(e.y-s,0,t.height),l=n8(e.x+e.w+r,0,t.width);return{x:a,y:i,w:l-a,h:n8(e.y+e.h+s,0,t.height)-i}}(t,e),[s,a]=re(r.w,r.h);return a.drawImage(n,r.x,r.y,r.w,r.h,0,0,r.w,r.h),n9(s)}));return{marked:await n9(i),crops:o}}finally{n.close()}}function rn({src:e,regions:t,max:n,onAdd:a,onNaturalSize:i,regionLabel:l}){let o=(0,s.useRef)(null),[c,d]=(0,s.useState)(null),u=(0,s.useRef)(null),[h,p]=(0,s.useState)(null),m=e=>{let t=o.current,n=u.current;return t&&n&&c?function(e,t,n,r){let s=n8(Math.min(e.x,t.x),n.left,n.left+n.width),a=n8(Math.max(e.x,t.x),n.left,n.left+n.width),i=n8(Math.min(e.y,t.y),n.top,n.top+n.height),l=n8(Math.max(e.y,t.y),n.top,n.top+n.height);if(a-s<6||l-i<6)return null;let o=n5({x:s,y:i},n,r),c=n5({x:a,y:l},n,r),d=Math.floor(o.x),u=Math.floor(o.y),h=Math.min(r.width,Math.ceil(c.x))-d,p=Math.min(r.height,Math.ceil(c.y))-u;return h>0&&p>0?{x:d,y:u,w:h,h:p}:null}(n.start,e,t.getBoundingClientRect(),c):null},f=(e,t)=>{if(u.current?.pointerId!==e.pointerId)return;let n=t?m({x:e.clientX,y:e.clientY}):null;u.current=null,p(null),n&&a(n)};return(0,r.jsxs)("div",{className:"tool-image-marker","data-drawing":c&&t.length<n?"true":void 0,onPointerDown:e=>{c&&!(t.length>=n)&&("mouse"!==e.pointerType||0===e.button)&&(e.preventDefault(),e.currentTarget.setPointerCapture(e.pointerId),u.current={pointerId:e.pointerId,start:{x:e.clientX,y:e.clientY}})},onPointerMove:e=>{u.current?.pointerId===e.pointerId&&p(m({x:e.clientX,y:e.clientY}))},onPointerUp:e=>f(e,!0),onPointerCancel:e=>f(e,!1),children:[(0,r.jsx)("img",{ref:o,className:"tool-image-full",src:e,alt:"",draggable:!1,onLoad:e=>{let t={width:e.currentTarget.naturalWidth,height:e.currentTarget.naturalHeight};d(t),i(t)}}),c&&t.map((e,t)=>(0,r.jsx)(rr,{region:e,natural:c,label:String(t+1),title:l(t+1)},`${t}-${e.x}-${e.y}`)),c&&h&&(0,r.jsx)(rr,{region:h,natural:c})]})}function rr({region:e,natural:t,label:n,title:s}){let a={left:e.x/t.width*100,top:e.y/t.height*100,width:e.w/t.width*100,height:e.h/t.height*100};return(0,r.jsx)("span",{className:"tool-image-region","data-draft":n?void 0:"true",role:n?"img":void 0,"aria-label":s,style:{left:`${a.left}%`,top:`${a.top}%`,width:`${a.width}%`,height:`${a.height}%`},children:n&&(0,r.jsx)("span",{className:"tool-image-region-number","aria-hidden":"true",children:n})})}function rs(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}function ra(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 ri=/<(read-files|modified-files)>\s*([\s\S]*?)\s*<\/\1>/g,rl=/(?:\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 ro(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${Math.round(e/1e3)}k`:e.toLocaleString()}let rc={hideThinkingBlock:!1},rd=new Set,ru=rc,rh=0;function rp(e){return rd.add(e),()=>{rd.delete(e)}}function rm(){return ru}function rf(){return rc}async function rg(e){let t=++rh,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 s=await r.json();t!==rh||s.hideThinkingBlock!==ru.hideThinkingBlock&&(ru={hideThinkingBlock:!0===s.hideThinkingBlock},rd.forEach(e=>e()))}function rx(){return(0,s.useSyncExternalStore)(rp,rm,rf)}function rv(e){let t=new Date(e),n=e=>String(e).padStart(2,"0");return`${t.getFullYear()}-${n(t.getMonth()+1)}-${n(t.getDate())}T${n(t.getHours())}:${n(t.getMinutes())}`}let ry=["YUKI(유키)","ISANA(이사나)","MIO(미오)","RIN(린)","MITSU(미츠)","SHION(시온)"],rb={"YUKI(유키)":"yuki","ISANA(이사나)":"isana","MIO(미오)":"mio","RIN(린)":"rin","MITSU(미츠)":"mitsu","SHION(시온)":"shion"},rw=["approval","choice","done","failed","blocked","working"],rk={approval:"부름",choice:"물음",done:"기쁨",failed:"사과",blocked:"난처",working:"시작"},rj={approval:!1,choice:!1,done:!1,failed:!1,blocked:!1,working:!0},rS="/api/office-characters/",rC={voice:"/audio/completion/",sticker:"/stickers/"};function rN(e){switch(e){case"completed":return"done";case"failed":return"failed";case"aborted":return null;default:return"neutral"}}function rT(e){return void 0===e?"done":"string"==typeof e&&Object.hasOwn(rk,e)?e:null}function rI(e,t){let n=new Map,r=new Map;if(!Array.isArray(e))return{files:n,lines:r};for(let s of e){if("object"!=typeof s||null===s)continue;let{file:e,tag:a,ko:i}=s;if("string"!=typeof e||""===e)continue;let l=rT(a);if(null===l)continue;let o=t+e.replace(/^\/+/,""),c=n.get(l);c?c.push(o):n.set(l,[o]),"string"==typeof i&&""!==i.trim()&&r.set(o,i.trim())}return{files:n,lines:r}}function rM(e,t=rC){let n=new Map;if("object"!=typeof e||null===e)return n;let{characters:r}=e;if(!Array.isArray(r))return n;for(let e of r){if("object"!=typeof e||null===e)continue;let{id:r,clips:s,stickers:a,captions:i}=e;if("string"!=typeof r||""===r)continue;let l=rI(s,t.voice),o=rI(a,t.sticker),c=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 s=rT(e);if(null===s)continue;let a=t.get(s);a?a.push(r.trim()):t.set(s,[r.trim()])}return t}(i),d=new Map;for(let e of rw){let t=l.files.get(e)??[],n=new Map;for(let e of t){let t=l.lines.get(e);void 0!==t&&n.set(e,t)}d.set(e,{voices:t,stickers:o.files.get(e)??[],lines:n,captions:c.get(e)??[]})}n.set(r,d)}return n}function rE(e,t,n){let r=t&&Object.hasOwn(rb,t)?rb[t]:null;return r?e.get(r)?.get(n)??null:null}function r$(e,t,n){return e.get(t)?.get(n)??null}async function rR(e=fetch){try{let t=await e("/audio/completion/voices.json");if(!t.ok)return new Map;return rM(await t.json())}catch{return new Map}}function rL(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),s=-1===r?e.length:e.length-1,a=Math.min(s-1,Math.max(0,Math.floor(n()*s)));return e[-1!==r&&a>=r?a+1:a]}function rP(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 rA(e,t,n,r){if(t&&("web6"!==t.provider||t.model!==r_))return{provider:t.provider,model:t.model,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!==r_))return{provider:n.provider,model:n.model,credentialId:n.credentialId}}return{provider:n,model:r,credentialId:void 0}}let r_="ChatGPT 6PRO",rF="/api/sidecars/resource";function rO(e){if("string"==typeof e.status&&"unknown"!==e.status)return"exhausted"===e.status;let t=e.amount??{},n=e=>{let n=t[e];return"number"==typeof n&&Number.isFinite(n)?n:null},r=n("usedFraction");if(null!==r&&r>=1)return!0;let s=n("remainingFraction");if(null!==s&&s<=0)return!0;let a=n("used"),i=n("limit");if(null!==a&&null!==i&&a>=i)return!0;let l=n("remaining");return null!==l&&l<=0||"percent"===t.unit&&null!==a&&a>=100}let rz=[{alias:"RIN(린)",file:"rin.webp"},{alias:"MIO(미오)",file:"mio.webp"},{alias:"MITSU(미츠)",file:"mitsu.webp",provider:"hive",model:"zai-org/glm-5.3-flash"},{alias:"YUKI(유키)",file:"yuki.webp",provider:"openai-codex"},{alias:"ISANA(이사나)",file:"isana.webp",provider:"hive"},{alias:"SHION(시온)",file:"shion.webp",provider:"web6"}],rD=[{seed:3,alias:rz[3].alias,provider:"openai-codex",model:"gpt-6.2-astra",voice:"빠른 판단\xb7선명한 결론\xb7영리한 장난기",summonExample:"유키 불러와",switchExample:"유키로 교체해"},{seed:4,alias:rz[4].alias,provider:"hive",model:"deepseek-ai/deepseek-v4.1-flash-1017",voice:"호기심과 실행력\xb7생기 있는 관찰\xb7솔직함",summonExample:"이사나 불러와",switchExample:"이사나로 교체해"},{seed:0,alias:rz[0].alias,provider:"anthropic",model:"claude-opus-5-5",oauthPosition:0,voice:"조용한 집중\xb7날카로운 분석\xb7건조한 유머",summonExample:"린 불러와",switchExample:"린으로 교체해"},{seed:1,alias:rz[1].alias,provider:"anthropic",model:"claude-opus-5-5",oauthPosition:1,voice:"따뜻하고 세심함\xb7부드럽고 안정적인 설명",summonExample:"미오 불러와",switchExample:"미오로 교체해"},{seed:2,alias:rz[2].alias,provider:"hive",model:"zai-org/glm-5.3-flash",voice:"부지런한 배달\xb7통통 튀는 보고\xb7끈질긴 재도전",summonExample:"미츠 불러와",switchExample:"미츠로 교체해"},{seed:5,alias:rz[5].alias,provider:"web6",model:"gpt-6-pro",voice:"우아한 전략\xb7넓은 시야\xb7은근한 장난기",summonExample:"시온 불러와",switchExample:null,summonNote:"WEB6 상담으로 호출합니다.",switchNote:"SHION은 WEB6 상담 전용이라 Main으로 교체할 수 없습니다."}],rW=rD.filter(e=>null!==e.switchExample),rH={mode:"default",rosterAvailable:!1,seats:[]},rU=rH,rB=new Map,rq=new Map,rV=rD,rK=new Set,rJ=null,rG=0,rY=null,rZ=!1;function rQ(e){let t="office"===e.mode?e.seats.filter(e=>rz.some(t=>t.alias===e.seat)&&!rz.some(t=>t.alias===e.alias)&&"MITSU(미츠)"!==e.seat):[];rG+=1;let n=JSON.stringify([e.mode,e.rosterAvailable,t]);if(n!==rY)for(let r of(rY=n,rU={...e,seats:t},rq=new Map([...rB=new Map(t.flatMap(e=>{let t=rz.findIndex(t=>t.alias===e.seat);return t>=0?[[t,e]]:[]}))].flatMap(([e,t])=>{let n=rz[e];return"provider"in n&&!("model"in n)?[[n.provider,{seed:e,alias:t.alias}]]:[]})),rV=0===rB.size?rD:rD.map(e=>{let t,n,r,s=rB.get(rz.findIndex(t=>t.alias===e.alias));return s?(t=s.names.findLast(e=>/[가-힣]/.test(e))??s.names[0]??s.alias.split("(",1)[0],{...e,alias:s.alias,voice:s.voice.temperament.split(/(?<=[.。])\s/,1)[0].replace(/[.。]$/,""),summonExample:`${t} 불러와`,switchExample:`${r=(n=t.charCodeAt(t.length-1)-44032)>=0&&n<=11171?n%28:0,`${t}${0===r||8===r?"로":"으로"}`} 교체해`}):e}),rK))r()}function rX(){return rU}function r0(e){return rK.add(e),()=>{rK.delete(e)}}async function r1(e=fetch){let t=rG;try{let n=await e("/api/character-mode",{cache:"no-store"});if(!n.ok)return!1;let r=await n.json();if("object"!=typeof r||null===r)return!1;if(t!==rG)return!0;let{mode:s,rosterAvailable:a,seats:i}=r;return rQ({mode:"office"===s?"office":"default",rosterAvailable:!0===a,seats:Array.isArray(i)?i:[]}),!0}catch{return!1}}let r2=new WeakMap;function r4(e){let t=r2.get(e);return t||(t=rM(e.manifest,{voice:rS,sticker:rS}),r2.set(e,t)),t}function r8(e){return e?rU.seats.find(t=>t.seat===e||t.alias===e)??null:null}function r5(e){return rU.seats.find(t=>t.seat===e)?.alias??e}let r6=rz.filter(e=>!("provider"in e)).length,r3=new Map(rz.flatMap((e,t)=>"provider"in e&&!("model"in e)?[[e.provider,t]]:[])),r7=new Map(rz.flatMap((e,t)=>"model"in e?[[`${e.provider}/${e.model}`,{seed:t,alias:e.alias}]]:[])),r9=new Map([...r3].map(([e,t])=>[e,{seed:t,alias:rz[t].alias}]));function se(e,t){return void 0===t?null:r7.get(`${e}/${t}`)??null}function st(e){return rq.get(e)??r9.get(e)??null}function sn(e){let t=e%rz.length;return rB.get(t)?.alias??rz[t].alias}function sr(e){let t=e%rz.length;return rB.get(t)?.faceUrl??`/avatars/${rz[t].file}`}function ss(e){return 0===e.length?"":1===e.length?"•••":2===e.length?`${e[0]}•••`:`${e[0]}•••${e[e.length-1]}`}function sa(e){return({"openai-codex":"OpenAI Codex",anthropic:"Anthropic","github-copilot":"GitHub Copilot","opencode-go":"OpenCode Go",devin:"Devin","b-ai":"B.AI",web6:"WEB6"})[e]??e.replace(/(^|-)(\w)/g,(e,t,n)=>`${t?" ":""}${n.toUpperCase()}`)}function si(e){let t=new Map;for(let n of e){if(!Number.isSafeInteger(n.oauthPosition)||n.oauthPosition<0)continue;let e=t.get(n.provider)??new Set;e.add(n.oauthPosition),t.set(n.provider,e)}return e.map(e=>{var n;let r=e.metadata?.email,s=e.metadata?.accountId,a="string"==typeof r&&r.length>0?r:"string"==typeof s?s:"",i=a.length>0?function(e){let t=e.lastIndexOf("@");if(t<=0)return ss(e);let n=e.slice(t+1),r=n.lastIndexOf("."),s=r<0?n:n.slice(0,r),a=r<0?"":n.slice(r);return`${ss(e.slice(0,t))}@${0===s.length?"":`${s[0]}•••`}${a}`}(a):"",l=(n=e.provider,r3.get(n)??-1);if(l>=0)return{seed:l,alias:sn(l),masked:i,raw:a};let o=e.oauthPosition;if(!Number.isSafeInteger(o)||o<0){let n=t.get(e.provider)??new Set;for(o=0;n.has(o);)o++;n.add(o),t.set(e.provider,n)}let c=o%r6,d=o<r6?sn(c):`${sn(c)}${o+1}`;return{seed:c,alias:d,masked:i,raw:a}})}class sl extends Error{constructor(e,t,n,r){super(e,r),this.kind=t,this.status=n,this.name="ResourceClientError",this.code=r?.code,this.outcomeUnknown=r?.outcomeUnknown}}function so(e,t){return`${rF}${e}${t?"?refresh=1":""}`}function sc(e,t,n=!1){return e instanceof sl?e:t?new sl("요청 시간이 초과되었습니다.","timeout",void 0,{cause:e}):n||e instanceof DOMException&&"AbortError"===e.name?new sl("요청이 취소되었습니다.","aborted",void 0,{cause:e}):new sl(e instanceof Error?e.message:String(e),"network",void 0,{cause:e})}function sd(e,t){return null==e?{status:"error",data:null,error:t}:{status:"stale",data:e,error:t}}async function su(e,t){let n,r=t.fetchImpl??fetch,s=new AbortController,a=!1,i=()=>s.abort(t.signal?.reason);t.signal?.aborted?i():t.signal?.addEventListener("abort",i,{once:!0}),null!=t.timeoutMs&&(n=setTimeout(()=>{a=!0,s.abort(new DOMException("Timeout","TimeoutError"))},t.timeoutMs));try{let t,n=await r(e,{signal:s.signal});try{t=await n.json()}catch(e){throw new sl("리소스 서버 응답이 JSON이 아닙니다.","invalid-response",n.status,{cause:e})}let a=t&&"object"==typeof t?t:null,i="string"==typeof a?.error?a.error:null;if(!n.ok||i)throw new sl(i??`HTTP ${n.status}`,"http",n.status,{code:"string"==typeof a?.code?a.code:void 0,outcomeUnknown:a?.outcomeUnknown===!0});return t}catch(e){throw sc(e,a,s.signal.aborted)}finally{clearTimeout(n),t.signal?.removeEventListener("abort",i)}}async function sh(e={}){try{let t=await su(so("/usage",!0===e.refresh),e);if(!t||!Array.isArray(t.reports))throw new sl("사용량 응답 형식이 올바르지 않습니다.","invalid-response");return{status:"fresh",data:t,error:null}}catch(t){return sd(e.previous,sc(t,!1))}}async function sp(e,t={}){if(!e)return sd(void 0,new sl("세션 id가 올바르지 않습니다.","invalid-response"));try{let n=await su(`/api/agent/${encodeURIComponent(e)}/account`,t),r=n?.state==="resolved"||n?.state==="unresolved"||n?.state==="not-running"||n?.state==="unsupported";if(!n||n.sessionId!==e||"number"!=typeof n.observedAt||!r||!Array.isArray(n.resetRecommendations))throw new sl("현재 계정 응답 형식이 올바르지 않습니다.","invalid-response");return{status:"fresh",data:n,error:null}}catch(e){return sd(void 0,sc(e,!1))}}async function sm(e={}){try{let t=await su(so("/models",!0===e.refresh),{...e,timeoutMs:e.timeoutMs??12e4});if(!t||!Array.isArray(t.models)||!Array.isArray(t.agents)||!Array.isArray(t.daily))throw new sl("모델 집계 응답 형식이 올바르지 않습니다.","invalid-response");return{status:"fresh",data:t,error:null}}catch(t){return sd(e.previous,sc(t,!1))}}async function sf(e={}){try{let t=await su(`${rF}/credits${!0===e.refresh?"?refresh=1":""}`,{...e,timeoutMs:e.timeoutMs??6e4});if(!(t&&"object"==typeof t&&t.settings&&"object"==typeof t.settings&&t.hive&&Array.isArray(t.hive.rows)&&(void 0===t.anthropic||Array.isArray(t.anthropic?.rows))&&(void 0===t.balances||Array.isArray(t.balances)&&t.balances.every(e=>!!e&&"string"==typeof e.wallet&&(null===e.recorded||"object"==typeof e.recorded&&Number.isFinite(e.recorded?.amountUsd)&&Number.isFinite(e.recorded?.observedAt))))))throw new sl("API 크레딧 응답 형식이 올바르지 않습니다.","invalid-response");return{status:"fresh",data:t,error:null}}catch(t){return sd(e.previous,sc(t,!1))}}async function sg(e,t,n={}){await sv({wallet:e,value:t},n)}async function sx(e,t,n={}){await sv({kind:"balance",wallet:e,value:t},n)}async function sv(e,t){await su(`${rF}/credits/settings`,{...t,timeoutMs:t.timeoutMs??2e4,fetchImpl:async(n,r)=>{let s=new Headers(r?.headers);return s.set("Content-Type","application/json"),(t.fetchImpl??fetch)(n,{...r,method:"POST",headers:s,body:JSON.stringify(e)})}})}async function sy(e,t,n={}){if(!Number.isSafeInteger(e)||e<=0)throw new sl("credential id가 올바르지 않습니다.","invalid-response");let r=await su(`${rF}/credential/${e}/${t?"enable":"disable"}`,{...n,timeoutMs:n.timeoutMs??2e4,fetchImpl:async(e,t)=>(n.fetchImpl??fetch)(e,{...t,method:"POST"})});if(!r||!0!==r.ok||r.credentialId!==e||!t!==r.disabled)throw new sl("계정 전환 응답 형식이 올바르지 않습니다.","invalid-response");return r}async function sb(e,t,n={}){if(!Number.isSafeInteger(e)||e<=0)throw new sl("credential id가 올바르지 않습니다.","invalid-response");if(!t)throw new sl("credit id가 올바르지 않습니다.","invalid-response");let r=await su(`${rF}/credential/${e}/reset`,{...n,timeoutMs:n.timeoutMs??2e4,fetchImpl:async(e,r)=>{let s=new Headers(r?.headers);return s.set("Content-Type","application/json"),(n.fetchImpl??fetch)(e,{...r,method:"POST",headers:s,body:JSON.stringify({confirm:!0,creditId:t})})}});if(!r||"boolean"!=typeof r.ok||r.credentialId!==e||r.creditId!==t||"string"!=typeof r.code||r.ok!==("reset"===r.code))throw new sl("리셋 사용 응답 형식이 올바르지 않습니다.","invalid-response");return r}function sw(e,t){if(e.has(t))return null;e.add(t);let n=!1;return()=>{n||(n=!0,e.delete(t))}}let sk={faces:new Map,pins:new Map},sj=[],sS=sk,sC=null,sN=sj,sT=new Map,sI=new Set;function sM(e){let t=(sI.add(e),()=>{sI.delete(e)}),n=r0(e);return()=>{t(),n()}}function sE(e){sS=e,sI.forEach(e=>e())}function s$(e){return Number.isSafeInteger(e)&&e>0}function sR(e,t){return`${e}:${t}`}function sL(e){let t=e??sj;sN=t;let n=t.map(e=>[e.provider,e.credentialId??"",e.oauthPosition??"",e.metadata?.accountId??"",e.metadata?.email??""].join("\0")).join("|");if(n===sC)return;sC=n;let r=si(t),s=new Map;t.forEach((e,t)=>{let n=e.credentialId;if(!s$(n))return;let a=sR(e.provider,n);s.has(a)||s.set(a,{seed:r[t].seed,alias:r[t].alias})}),sE({faces:s,pins:sS.pins})}function sP(e,t,n,r){if(!t)return null;let s=se(t,r);if(s)return s;if(s$(n)){let e=sS.faces.get(sR(t,n));if(e)return e}let a=e?sS.pins.get(e):void 0;if(a&&a.provider===t){let e=sS.faces.get(sR(t,a.credentialId));if(e)return e}return st(t)??("anthropic"!==t||s$(n)||a?.provider===t?null:rV.find(e=>e.provider===t&&0===e.oauthPosition)??null)}async function sA(e,t,n,r){if(!t||s$(n)||st(t))return sP(e,t,n,r);try{let{data:n}=await sp(e);if(n?.state==="resolved"&&n.provider===t&&s$(n.credentialId)){let r=new Map(sS.pins);r.set(e,{provider:t,credentialId:n.credentialId,observedAt:Date.now()}),sE({faces:sS.faces,pins:r})}}catch{}return sP(e,t,void 0,r)}function s_(e,t,n,r){let a=!!t&&!s$(n)&&!!e;return(0,s.useEffect)(()=>{a&&e&&t&&function(e,t){let n=Date.now(),r=sS.pins.get(e);if(r&&r.provider===t&&n-r.observedAt<3e4)return;let s=`${e}\u0000${t}`,a=sT.get(s);void 0!==a&&n-a<3e4||(sT.set(s,n),sp(e).then(t=>{let n=t.data;if(!n||"resolved"!==n.state)return;let{provider:r,credentialId:s}=n;if("string"!=typeof r||""===r||!s$(s))return;let a=new Map(sS.pins);a.set(e,{provider:r,credentialId:s,observedAt:Date.now()}),sE({faces:sS.faces,pins:a})}).catch(()=>{}))}(e,t)},[a,e,t]),(0,s.useSyncExternalStore)(sM,()=>sP(e,t,n,r),()=>null)}function sF(){return(0,s.useEffect)(()=>{if(!rZ){rZ=!0;let e=()=>{"visible"===document.visibilityState&&r1()};window.addEventListener("focus",e),document.addEventListener("visibilitychange",e)}null===rJ&&(rJ=r1().then(e=>{e||(rJ=null)}))},[]),(0,s.useSyncExternalStore)(r0,rX,()=>rH)}r0(()=>{sC=null,sL(sN)});let sO={ko:{"dispatch.title":"서브에이전트 {count}명","dispatch.tally":"실행 중 {running} \xb7 실행 완료 {done} \xb7 Main 수용 {accepted}","dispatch.expand":"발주 상세 펼치기","dispatch.collapse":"발주 상세 접기","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.live":"진행 중","summary.files":"변경 파일 {count}","summary.files.one":"변경 파일 {count}","summary.checks":"검사 {count}","summary.checks.one":"검사 {count}","summary.checksFailed":"실패 {count}","summary.unverified":"미확인 {count}","summary.verdictUnverified":"판정 미확인 {count}","summary.verdictUnverified.one":"판정 미확인 {count}","result.label":"이번 결과","result.open":"결과 보기","result.openNamed":"{name} 결과 보기","result.previewTitle":"{name} 미리보기","result.previewFailed":"미리보기를 불러오지 못했습니다. 결과 보기를 누르세요.","result.more":"다른 결과 {count}","result.previewLoading":"미리보기를 불러오는 중","result.kind.html":"화면","result.kind.pdf":"PDF","result.kind.document":"문서","result.kind.image":"이미지","summary.heading.files":"변경 파일","summary.heading.checks":"실행한 검사","summary.check.exit":"exit {code}","summary.makers":"Maker {count}","summary.makers.one":"Maker {count}","summary.remaining":"남은 일 {count}","summary.heading.remaining":"남은 일","summary.time.unobserved":"시간 기록 없음","summary.time.running":"아직 실행 중","summary.todo.pending":"대기","summary.todo.in_progress":"진행 중","summary.todo.blocked":"막힘","summary.todo.blocker":"막힌 이유: {blocker}","summary.todo.none":"남은 일 없음","flow.heading":"작업 흐름","flow.aria":"이번 턴의 작업 단계","flow.toggle":"작업 흐름","flow.stage.investigate":"조사","flow.stage.edit":"수정","flow.stage.check":"검사","flow.stage.review":"교차리뷰","flow.stage.commit":"커밋\xb7푸시","flow.stage.ci":"CI","flow.stage.deploy":"배포","flow.state.waiting":"대기","flow.state.running":"진행 중","flow.state.done":"완료","flow.state.redone":"다시 고침","flow.state.passed":"통과","flow.state.unverified":"판정 미확인","flow.state.failed":"실패","flow.state.unobserved":"결과 미관측","flow.state.findings":"지적 {count}건","flow.state.findings.one":"지적 {count}건","flow.state.noFindings":"지적 없음","flow.state.open":"미해결 {count}건","flow.state.reviewUnusable":"리뷰 불가","flow.state.skipped":"건너뜀","flow.state.notNeeded":"필요 없음","flow.count.passed":"통과 {count}","flow.count.unverified":"판정 미확인 {count}","flow.count.failed":"실패 {count}","flow.count.unobserved":"결과 미관측 {count}","flow.count.running":"진행 중 {count}","flow.earlier":"이전 회차 {count}건","flow.attempt":"{attempt}회차","flow.label.typecheck":"타입 검사","flow.label.lint":"린트","flow.label.test":"테스트","flow.label.build":"빌드","flow.label.verify":"검증","flow.label.smoke":"스모크 확인","flow.label.check":"검사","flow.label.ci":"CI 확인","flow.label.deploy":"배포 실행","flow.label.review":"리뷰","flow.label.resolve":"지적 처리","flow.label.commit":"커밋\xb7푸시","flow.details":"자세히","flow.commandOmitted":"명령 본문은 압축된 요청의 요약에서 생략했어요.","flow.exit":"셸 종료 코드 {code}","flow.exit.none":"종료 코드 기록 없음","flow.exit.error":"오류로 끝남","flow.evidence":"판정에 쓴 기록","flow.why.confirmed":"확인된 것","flow.why.missing":"없는 것","flow.why.exitZero":"셸 종료 코드 0","flow.why.check":"{label} 명령의 종료 코드. 뒤에 이어 붙인 명령(파이프, ;, || 등)이 결과를 가릴 수 있어서 통과로 세지 않았어요.","flow.why.ci":"CI 결과를 종료 코드로 돌려준 기록. gh run watch --exit-status처럼 결과를 돌려주는 명령이 아니라서 통과로 세지 않았어요.","flow.why.ciOtherRun":"이 커밋의 CI 실행이라는 기록. 기다린 실행은 기록상 다른 커밋 {sha}의 실행이에요.","flow.why.ciPublishRun":"이 커밋의 CI 실행 결과. 이 명령이 기다린 실행은 게시 실행이라 CI 판정으로 세지 않았어요.","flow.why.watched.passed":"기다린 실행이 통과로 끝남","flow.why.watched.failed":"기다린 실행이 실패로 끝남","flow.why.watched.unjudged":"기다린 실행이 판정 없이 끝남({conclusion})","flow.why.ciUnjudged":"이 커밋의 CI 판정. 기다린 실행이 통과도 실패도 아닌 {conclusion} 상태로 끝나서, 명령의 실패를 CI 실패로 세지 않았어요.","flow.why.deploy":"배포가 끝났다는 기록. 배포를 띄우고 바로 돌아오는 명령이라 셸 종료 코드만으로는 끝났는지 알 수 없어요.","flow.strip.running":"{stage} 진행 중","flow.loop.badge":"↻ {attempt}회차","flow.loop.failed":"{stage} {attempt}회차 실패로 수정에 되돌아옴","flow.loop.findings":"{stage} {attempt}회차 지적으로 수정에 되돌아옴","flow.state.stale":"수정 전 통과","flow.state.staleDone":"수정 전 완료","flow.count.stale":"수정 전 통과 {count}","flow.why.stale":"이 결과 뒤에 파일을 다시 고쳐서, 마지막 수정본은 아직 확인하지 않았어요.","flow.compound.failed":"묶은 명령 실패","flow.why.compoundConfirmed":"{stages}를 한 명령으로 돌렸고, 명령 전체가 실패로 끝남","flow.why.compoundMissing":"어느 단계에서 실패했는지","flow.why.next":"다음에 할 일","flow.why.check.syntax":"{label} 명령의 종료 코드. 명령에 $(…)\xb7백틱\xb7( ) 묶음\xb7{ } 같은 셸 구문이 있어서, 그 종료 코드가 셸 종료 코드까지 그대로 왔는지 이 화면은 따지지 않아요. 그래서 통과로 세지 않았어요.","flow.why.check.optional":"{label} 스크립트가 실제로 실행된 기록. --if-present를 쓰면 스크립트가 없을 때 실행기가 아무것도 실행하지 않고 종료 코드 0으로 끝나요.","flow.why.noExit":"이 호출의 종료 코드. 결과 기록에 종료 코드가 없어요.","flow.why.noResult":"이 호출의 결과. 결과 기록이 없어요.","flow.why.interrupted":"이 호출의 결과. 호출이 끝나기 전에 끊겼어요.","flow.why.noCompletion":"이 호출의 종료 코드. 호출이 백그라운드 job으로 넘어갔고, 그 job의 완료 기록이 없어요.","flow.next.rerun":"먼저 이 호출의 완료 기록과 출력을 확인하세요. 실행이 끝났고 검사 명령 자체의 종료 코드를 찾을 수 없을 때만 파이프, ;, ||, 감싸는 구문 없이 검사 명령을 단독으로 다시 실행하세요. 긴 출력은 tail이나 grep으로 자르지 말고 결과 artifact에서 확인하세요.","flow.next.optional":"먼저 이 호출의 완료 기록과 출력을 확인하세요. 실행이 끝났고 스크립트 실행 기록을 찾을 수 없을 때만 --if-present 없이 스크립트 이름으로 다시 실행하세요.","flow.next.compound":"먼저 이 호출의 완료 기록과 출력을 확인하세요. 실행이 끝났고 어느 단계가 실패했는지 찾을 수 없을 때만 단계마다 명령을 나눠 다시 실행하세요.","flow.next.again":"먼저 이 호출의 완료 기록과 출력을 확인하세요. 실행이 끝났고 종료 코드를 찾을 수 없을 때만 같은 검사를 다시 실행하세요.","flow.repeats":"반복 실행 {count}건","flow.ci.notNeeded":"비공개 저장소에만 반영됐어요. 게시 실행 {run} 뒤에도 공개 {repo}의 {ref}는 CI를 통과한 {sha} 그대로예요.","flow.ci.nothingToPublish":"커밋 {sha}의 게시 실행 로그에 「Public tree already matches; nothing to publish」가 남았어요. 공개 저장소가 그대로라 새로 돌 CI가 없어요.","summary.stale":"수정 전 통과 {count}","summary.compoundFailed":"묶은 명령 실패 {count}","graph.branch":"수정 중 맡긴 Maker {count}","graph.branch.one":"수정 중 맡긴 Maker {count}","graph.parallel.observed":"동시 실행 관측","graph.join":"Main 판정","graph.parallel.batch":"같은 발주 묶음","graph.concurrency.overlapped":"겹쳐 실행","graph.concurrency.unknown":"겹침 여부 모름","graph.kind.feature":"기능","graph.kind.maintenance":"유지보수","graph.kind.diagnostic":"진단","graph.kind.unknown":"종류 미기록","graph.outputs":"변경 결과","graph.files":"파일 {count}","graph.docs":"문서 {count}","graph.files.one":"파일 {count}","graph.docs.one":"문서 {count}","graph.detail.aria":"선택한 노드 자세히","graph.maker.open":"Maker 기록 열기","graph.maker.unavailable":"실시간 기록이 없어 여기서 열 수 없어요.","graph.motion.pause":"움직임 멈춤","graph.replay":"재생","graph.replay.stop":"재생 멈춤","turn.heading":"{time} 턴","turn.headingLive":"진행 중인 턴","turn.headingUnknown":"이 턴","turn.show":"인스펙터에서 보기","turn.shown":"인스펙터에 표시 중","turn.peek":"흐름 보기","turn.numbers":"턴 결과 수","turn.metric.files":"변경 파일","turn.metric.checks":"검사","turn.metric.remaining":"남은 일","turn.metric.unverified":"미확인","turn.metric.verdict":"판정 미확인","turn.metric.stale":"수정 전 통과","turn.metric.failed":"실패","turn.dispatches":"서브에이전트","turn.empty":"이 턴에는 기록된 작업 단계가 없습니다.","turn.none":"아직 턴이 없습니다.","subflow.aria":"이 서브에이전트 실행의 단계","subflow.calls":"도구 {count}회","subflow.reedits":"다시 수정 {count}회","subflow.checks":"검사 {passed}/{total} 통과","subflow.reported":"보고함","subflow.unobserved":"기록 미관측","subflow.rework":"↻ Main 재작업 요청 {count}회로 구현에 되돌아옴","subflow.prior":"이전 판정","subflow.firstTitle":"첫 발주 제목","subflow.runTitle":"이번 실행 제목","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.images.one":"이미지 {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","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.live":"In progress","summary.files":"{count} files changed","summary.files.one":"{count} file changed","summary.checks":"{count} checks","summary.checks.one":"{count} check","summary.checksFailed":"{count} failed","summary.unverified":"{count} unverified","summary.verdictUnverified":"{count} verdicts not confirmed","summary.verdictUnverified.one":"{count} verdict not confirmed","result.label":"Result","result.open":"View result","result.openNamed":"View result: {name}","result.previewTitle":"Preview of {name}","result.previewFailed":"Couldn't load the preview. Use View result to open it.","result.more":"{count} more","result.previewLoading":"Loading preview","result.kind.html":"Page","result.kind.pdf":"PDF","result.kind.document":"Document","result.kind.image":"Image","summary.heading.files":"Files changed","summary.heading.checks":"Checks run","summary.check.exit":"exit {code}","summary.makers":"{count} Makers","summary.makers.one":"{count} Maker","summary.remaining":"{count} left","summary.heading.remaining":"Still to do","summary.time.unobserved":"time not recorded","summary.time.running":"still running","summary.todo.pending":"pending","summary.todo.in_progress":"in progress","summary.todo.blocked":"blocked","summary.todo.blocker":"blocked by: {blocker}","summary.todo.none":"nothing left","flow.heading":"Work flow","flow.aria":"Work stages of this turn","flow.toggle":"Work flow","flow.stage.investigate":"Investigate","flow.stage.edit":"Edit","flow.stage.check":"Check","flow.stage.review":"Cross review","flow.stage.commit":"Commit & push","flow.stage.ci":"CI","flow.stage.deploy":"Deploy","flow.state.waiting":"waiting","flow.state.running":"in progress","flow.state.done":"done","flow.state.redone":"fixed again","flow.state.passed":"passed","flow.state.unverified":"verdict not confirmed","flow.state.failed":"failed","flow.state.unobserved":"result not observed","flow.state.findings":"{count} findings","flow.state.findings.one":"{count} finding","flow.state.noFindings":"no findings","flow.state.open":"{count} open","flow.state.reviewUnusable":"review unusable","flow.state.skipped":"skipped","flow.state.notNeeded":"not needed","flow.count.passed":"{count} passed","flow.count.unverified":"{count} not confirmed","flow.count.failed":"{count} failed","flow.count.unobserved":"{count} not observed","flow.count.running":"{count} running","flow.earlier":"{count} from earlier attempts","flow.attempt":"Attempt {attempt}","flow.label.typecheck":"Type check","flow.label.lint":"Lint","flow.label.test":"Tests","flow.label.build":"Build","flow.label.verify":"Verification","flow.label.smoke":"Smoke check","flow.label.check":"Check","flow.label.ci":"CI check","flow.label.deploy":"Deploy run","flow.label.review":"Review","flow.label.resolve":"Resolve","flow.label.commit":"Commit & push","flow.details":"Details","flow.commandOmitted":"The command body is omitted from this compacted request summary.","flow.exit":"shell exit code {code}","flow.exit.none":"no exit code recorded","flow.exit.error":"ended with an error","flow.evidence":"Judged from","flow.why.confirmed":"Confirmed","flow.why.missing":"Missing","flow.why.exitZero":"shell exit code 0","flow.why.check":"The exit code of the {label} command itself. Commands chained after it (a pipe, ;, || and so on) can hide its result, so it was not counted as passed.","flow.why.ci":"A CI result returned as an exit code. The command does not return one the way gh run watch --exit-status does, so it was not counted as passed.","flow.why.ciOtherRun":"A record that the run belongs to this commit. The watched run is recorded for another commit, {sha}.","flow.why.ciPublishRun":"The result of this commit's CI run. The run this command waited on is the publish run, so its result was not counted as CI.","flow.why.watched.passed":"The watched run ended as passed","flow.why.watched.failed":"The watched run ended as failed","flow.why.watched.unjudged":"The watched run ended without a verdict ({conclusion})","flow.why.ciUnjudged":"This commit's CI verdict. The watched run ended as {conclusion}, neither passed nor failed, so the command's failure was not counted as a CI failure.","flow.why.deploy":"A record that the deploy finished. The command starts the deploy and returns at once, so its exit code cannot tell whether the deploy finished.","flow.strip.running":"{stage} in progress","flow.loop.badge":"↻ attempt {attempt}","flow.loop.failed":"{stage} failed in attempt {attempt}, so the flow went back to edit","flow.loop.findings":"{stage} raised findings in attempt {attempt}, so the flow went back to edit","flow.state.stale":"Passed before edit","flow.state.staleDone":"Done before edit","flow.count.stale":"{count} passed before edit","flow.why.stale":"Files were edited after this result, so the latest revision has not been checked.","flow.compound.failed":"Combined command failed","flow.why.compoundConfirmed":"{stages} ran as one command, and the whole command failed","flow.why.compoundMissing":"Which stage failed","flow.why.next":"Next","flow.why.check.syntax":"The exit code of the {label} command itself. The command contains shell syntax such as $(…), backticks, ( ) grouping or { } braces, and this panel does not trace whether that exit code reaches the shell exit code, so it was not counted as passed.","flow.why.check.optional":"A record that the {label} script actually ran. With --if-present, the runner exits 0 without running anything when the script does not exist.","flow.why.noExit":"The exit code of this call. The result record has no exit code.","flow.why.noResult":"The result of this call. There is no result record for it.","flow.why.interrupted":"The result of this call. The call was interrupted before it finished.","flow.why.noCompletion":"The exit code of this call. The call moved to a background job and has no completion record for that job.","flow.next.rerun":"First check this call's completion record and output. Rerun the check command on its own without a pipe, ;, || or wrapping syntax only if the run has ended and the check's own exit code cannot be recovered. Read long output from the result artifact instead of cutting it with tail or grep.","flow.next.optional":"First check this call's completion record and output. Rerun the script by name without --if-present only if the run has ended and proof that the script ran cannot be recovered.","flow.next.compound":"First check this call's completion record and output. Rerun each stage as a separate command only if the run has ended and the failing stage cannot be recovered.","flow.next.again":"First check this call's completion record and output. Rerun the same check only if the run has ended and no exit code can be recovered.","flow.repeats":"{count} repeated runs","flow.ci.notNeeded":"Only the private repository changed. After publish run {run}, public {repo} {ref} still points at {sha}, which already passed CI.","flow.ci.nothingToPublish":"The publish run log for commit {sha} says “Public tree already matches; nothing to publish”. The public repository did not change, so there is no new CI run.","summary.stale":"{count} passed before edit","summary.compoundFailed":"{count} combined failed","graph.branch":"{count} Makers dispatched during edit","graph.branch.one":"{count} Maker dispatched during edit","graph.parallel.observed":"Seen running together","graph.join":"Main verdict","graph.parallel.batch":"Same dispatch batch","graph.concurrency.overlapped":"Overlapped","graph.concurrency.unknown":"Overlap unknown","graph.kind.feature":"Feature","graph.kind.maintenance":"Maintenance","graph.kind.diagnostic":"Diagnostic","graph.kind.unknown":"Kind not recorded","graph.outputs":"Changed","graph.files":"{count} files","graph.docs":"{count} docs","graph.files.one":"{count} file","graph.docs.one":"{count} doc","graph.detail.aria":"Selected node details","graph.maker.open":"Open Maker record","graph.maker.unavailable":"No live record, so it can't be opened here.","graph.motion.pause":"Pause motion","graph.replay":"Replay","graph.replay.stop":"Stop replay","turn.heading":"Turn at {time}","turn.headingLive":"Turn in progress","turn.headingUnknown":"This turn","turn.show":"Open in the inspector","turn.shown":"Shown in the inspector","turn.peek":"View flow","turn.numbers":"Turn result counts","turn.metric.files":"Files changed","turn.metric.checks":"Checks","turn.metric.remaining":"Left","turn.metric.unverified":"Unverified","turn.metric.verdict":"Verdict unconfirmed","turn.metric.stale":"Passed before edit","turn.metric.failed":"Failed","turn.dispatches":"Subagents","turn.empty":"This turn recorded no work steps.","turn.none":"No turn yet.","subflow.aria":"Stages of this subagent run","subflow.calls":"tool calls: {count}","subflow.reedits":"re-edited {count}\xd7","subflow.checks":"{passed}/{total} checks passed","subflow.reported":"Reported","subflow.unobserved":"Not observed","subflow.rework":"↻ Back to implement \xb7 Main rework requests: {count}","subflow.prior":"Previous verdict","subflow.firstTitle":"First dispatch title","subflow.runTitle":"Current run title","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} images","delivery.images.one":"{count} image","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"}};function sz(){let{locale:e}=(0,F.s)();return{st:(0,s.useCallback)((t,n)=>(0,et.u0)(e,t,sO,n),[e]),locale:e}}function sD({seed:e,size:t,provider:n}){sF();let a=sr(e),[i,l]=(0,s.useState)(null),o=i===a,[c,d]=(0,s.useState)(!1);return o?(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:sn(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(),d(!0)},"aria-label":sn(e),children:(0,r.jsx)("img",{className:"account-avatar",src:a,width:t,height:t,alt:"","aria-hidden":"true",draggable:!1,onError:()=>l(a)})}),c&&(0,r.jsx)(sW,{seed:e,provider:n,onClose:()=>d(!1)})]})}function sW({seed:e,provider:t,onClose:n}){let{t:i}=(0,F.s)(),l=(0,s.useRef)(null);(0,s.useEffect)(()=>{let e=l.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 o=sn(e);return(0,a.createPortal)((0,r.jsxs)("dialog",{ref:l,className:"account-avatar-dialog","aria-label":o,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:sr(e),width:256,height:256,alt:o,draggable:!1}),(0,r.jsxs)("p",{className:"account-avatar-caption",children:[(0,r.jsx)("span",{className:"account-avatar-caption-alias",children:o}),t?(0,r.jsx)("span",{className:"account-avatar-caption-provider",children:sa(t)}):null]}),(0,r.jsx)("button",{type:"button",className:"account-avatar-close",onClick:n,children:i("i18n.close")})]}),document.body)}function sH(e){let t,n=[],r=null,s=0,a=0,i=0,l=0,o=[],c=[],d=()=>({lineNo:null,text:"",type:"empty"}),u=()=>{if(!r){o=[],c=[];return}let e=Math.max(o.length,c.length);for(let t=0;t<e;t++){let e=o[t]?{lineNo:o[t].lineNo,text:o[t].text,type:"removed"}:d(),n=c[t]?{lineNo:c[t].lineNo,text:c[t].text,type:"added"}:d();r.rows.push({type:"line",left:e,right:n})}o=[],c=[]};for(let d of e.split(/\r?\n/)){if(!(i>0||l>0)){if(d.startsWith("--- ")){u(),t=sU(d.slice(4));continue}if(d.startsWith("+++ ")){u(),r={oldPath:t,newPath:sU(d.slice(4)),rows:[]},n.push(r);continue}}let e=d.match(/^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/);if(e){r||(r={rows:[]},n.push(r)),u(),s=Number(e[1]),a=Number(e[3]),i=void 0===e[2]?1:Number(e[2]),l=void 0===e[4]?1:Number(e[4]),r.rows.push({type:"hunk",text:d});continue}if(!r)continue;if(d.startsWith("\\ ")){u(),r.rows.push({type:"hunk",text:d});continue}let h=d[0],p=d.slice(1);" "===h?(u(),r.rows.push({type:"line",left:{lineNo:s++,text:p,type:"context"},right:{lineNo:a++,text:p,type:"context"}}),i>0&&i--,l>0&&l--):"-"===h?(o.push({lineNo:s++,text:p}),i>0&&i--):"+"===h?(c.push({lineNo:a++,text:p}),l>0&&l--):""!==d&&(u(),r.rows.push({type:"hunk",text:d}))}u();let h=n.filter(e=>e.rows.some(e=>"line"===e.type));return h.length>0?h:null}function sU(e){return e.split(" ")[0].trim()}function sB({task:e,phases:t}){let{t:n}=(0,F.s)(),s="completed"===e.status,a="abandoned"===e.status,i="in_progress"===e.status,l="blocked"===e.status,o=!t||s||a?[]:tU(e,t),c=o.length>0?n("todo.waiting",{tasks:o.join(", ")}):!t||s||a||l?null:n("todo.ready"),d=s?"✓":a?"\xd7":l?"!":i?"›":"",u=s?"is-completed":a?"is-abandoned":l?"is-blocked":i?"is-active":"is-pending";return(0,r.jsxs)("div",{role:"listitem","aria-label":`${e.status}: ${e.content}${c?`; ${c}`:""}`,className:`todo-checklist-row ${u}`,children:[(0,r.jsx)("span",{"aria-hidden":"true",className:"todo-checklist-marker",children:d}),(0,r.jsxs)("span",{className:"todo-checklist-content",children:[e.content,l&&e.blocker?(0,r.jsxs)("span",{className:"todo-checklist-blocker",children:[" (",e.blocker,")"]}):null,c&&(0,r.jsxs)("span",{className:`todo-checklist-readiness${o.length>0?" is-waiting":""}`,children:[" \xb7 ",c]})]})]})}let sq="/icons/catppuccin";function sV({name:e,size:t=14}){let n={width:t,height:t,"--catppuccin-icon-light":`url(${sq}/latte/${e}.svg)`,"--catppuccin-icon-dark":`url(${sq}/mocha/${e}.svg)`};return(0,r.jsx)("span",{"aria-hidden":"true",className:"catppuccin-file-icon",style:n})}function sK({size:e=14,open:t=!1}){return(0,r.jsx)(sV,{name:t?"_folder_open":"_folder",size:e})}function sJ({size:e=14}){return(0,r.jsx)(sV,{name:"_file",size:e})}let sG={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 sY(e,t=14){let n=e.toLowerCase(),s="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(s)return(0,r.jsx)(sV,{name:s,size:t});let a=sG[n.split(".").pop()??""];return a?(0,r.jsx)(sV,{name:a,size:t}):(0,r.jsx)(sJ,{size:t})}function sZ({files:e,onOpenFile:t}){let{t:n}=(0,F.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 s=tK(e);return(0,r.jsxs)("button",{className:"turn-written-file",type:"button",title:e,"aria-label":n("chat.openWrittenFile",{name:s}),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:0,borderRadius:"var(--radius-control)",cursor:"pointer"},children:[sY(s,12),(0,r.jsx)("span",{children:s})]},e)})})}let sQ=/^att_[0-9a-f]{32}$/,sX=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function s0(e){return"string"==typeof e&&sQ.test(e)}function s1(e){return"string"==typeof e&&sX.test(e)}class s2 extends Error{constructor(e,t){super(t),this.code=e,this.name="DocumentAttachmentError"}}let s4={markdown:"text/markdown",text:"text/plain",pdf:"application/pdf"},s8={".txt":!0,".csv":!0,".tsv":!0,".json":!0,".log":!0},s5={"text/plain":!0,"text/csv":!0,"text/tab-separated-values":!0,"application/json":!0,"text/json":!0};function s6(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&&s8[t.slice(n)])return"text";let r=e.type.toLocaleLowerCase().split(";",1)[0]?.trim();return"text/markdown"===r?"markdown":"application/pdf"===r?"pdf":r&&s5[r]?"text":null}let s3={".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 s7(e){let t=e.name.toLocaleLowerCase(),n=t.lastIndexOf("."),r=n>0?s3[t.slice(n)]:void 0;if(r)return r;let s=e.type.toLocaleLowerCase().split(";",1)[0]?.trim();return s?.startsWith("audio/")?s:null}function s9(e,t){try{let n=new TextDecoder(e,{fatal:!0}).decode(t);return n.includes("\0")?null:n}catch{return null}}function ae(e){if(!Array.isArray(e))return[];let t=[],n=0,r=0;for(let s of e){if(s&&"object"==typeof s&&"string"==typeof s.name&&s.name.length>0&&("text/markdown"===s.mimeType||"text/plain"===s.mimeType||"application/pdf"===s.mimeType)&&"number"==typeof s.size&&Number.isSafeInteger(s.size)&&s.size>=0&&s.size<=8388608&&"string"==typeof s.text&&s.text.length<=12e4){if(t.length>=3)break;!(n+s.size>0x1000000)&&(r+s.text.length>24e4||(t.push({name:s.name,mimeType:s.mimeType,size:s.size,text:s.text,...s0(s.attachmentId)?{attachmentId:s.attachmentId}:{}}),n+=s.size,r+=s.text.length))}}return t}async function at(e){let t,n=s6(e);if(!n)throw new s2("unsupported",`Unsupported document type: ${e.name}`);if(e.size>8388608)throw new s2("file_too_large",`${e.name} exceeds the document size limit`);if("pdf"===n)t=await au(e);else{try{t=await e.text()}catch(e){throw new s2("read_failed",e instanceof Error?e.message:String(e))}ah(t)}return{name:e.name,mimeType:s4[n],size:e.size,text:t}}function an(e,t){let n=ae(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}))},s=`${ap}${JSON.stringify(r)}${am}
@@ -17,7 +17,7 @@ ${t}`)),[l,o]=(0,s.useState)(null),[c,d]=(0,s.useState)(()=>new Set);if((0,s.use
17
17
  ${t}`,r=ts.get(n);if(void 0!==r)return Promise.resolve(r);let s=ta.get(n);if(s)return s;let a=fetch(tt(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 ts.set(n,r),r}).catch(()=>0).finally(()=>ta.delete(n));return ta.set(n,a),a})(e,t).then(e=>{n&&i(e)}),()=>{n=!1}},[a,e,t]),!a)return null;let u=Array.from({length:a},(e,t)=>t).filter(e=>!c.has(e));return 0===u.length?null:(0,r.jsxs)("div",{className:"tool-image-strip","data-tool-call-id":t,children:[u.map(s=>(0,r.jsx)("button",{type:"button",className:"tool-image-thumb","aria-label":n("i18n.zoomIn"),onClick:()=>o(s),children:(0,r.jsx)("img",{src:tt(e,t,s),alt:"",loading:"lazy",draggable:!1,onError:()=>d(e=>new Set(e).add(s))})},s)),null!==l&&(0,r.jsx)(aP,{src:tt(e,t,l),fileName:`screen-${t.slice(-8)}-${l+1}`,onClose:()=>o(null)})]})}let aL={"image/png":"png","image/jpeg":"jpg","image/webp":"webp","image/gif":"gif"};function aP({src:e,fileName:t,onClose:n}){let{t:i}=(0,F.s)(),o=(0,s.useContext)(n4),c=(0,s.useRef)(null),[d,u]=(0,s.useState)(!1),[h,p]=(0,s.useState)(null),[m,f]=(0,s.useState)([]),[g,x]=(0,s.useState)(null),v=(0,s.useRef)(null);(0,s.useEffect)(()=>{let e=c.current;if(!e)return;let t=document.body.style.overflow;return document.body.style.overflow="hidden",e.showModal(),()=>{v.current?.abort(),document.body.style.overflow=t,e.open&&e.close()}},[]);let y=()=>{v.current?.abort(),n()},b=async()=>{let r,s;if(!o)return void p(i("toolImage.noComposer"));v.current?.abort();let a=new AbortController;v.current=a,u(!0),p(null);try{let n=await fetch(e,{signal:a.signal});if(!n.ok)throw Error(`HTTP ${n.status}`);let l=await n.blob(),o=aL[l.type];if(!o)throw Error(`unsupported ${l.type}`);if(0!==m.length&&g){let e=await rt(l,m);r=[new File([e.marked],`${t}-marked.png`,{type:"image/png"}),...e.crops.map((e,n)=>new File([e],`${t}-region-${n+1}.png`,{type:"image/png"}))];let n=1===m.length?"1":`1~${m.length}`;s=[i("toolImage.locatorIntro",{range:n}),...m.map((e,t)=>i("toolImage.locatorRegion",{n:t+1,x:e.x,y:e.y,w:e.w,h:e.h,width:g.width,height:g.height}))].join("\n")+"\n"}else r=[new File([l],`${t}.${o}`,{type:l.type})]}catch{if(a.signal.aborted)return;u(!1),p(i("toolImage.loadFailed"));return}if(!a.signal.aborted&&c.current?.open){if(!o(r,s)){u(!1),p(i("toolImage.noComposer"));return}n()}};return(0,a.createPortal)((0,r.jsxs)("dialog",{ref:c,className:"tool-image-dialog","aria-label":i("toolImage.dialogLabel"),onCancel:e=>{e.preventDefault(),y()},onClick:e=>{e.target===e.currentTarget&&y()},children:[(0,r.jsx)(rn,{src:e,regions:m,max:9,onAdd:e=>f(t=>t.length<9?[...t,e]:t),onNaturalSize:x,regionLabel:e=>i("toolImage.regionLabel",{n:e})}),h?(0,r.jsx)("p",{role:"alert",className:"tool-image-error",children:h}):(0,r.jsx)("p",{className:"tool-image-hint","data-hidden":m.length>0&&m.length<9?"true":void 0,children:m.length>=9?i("toolImage.markLimit",{count:9}):i("toolImage.markHint")}),(0,r.jsxs)("div",{className:"tool-image-actions",children:[(0,r.jsx)(l.r,{variant:"neutralSolid",size:"medium",loading:d,onClick:()=>void b(),title:i("toolImage.requestEditHint"),children:i("toolImage.requestEdit")}),(0,r.jsx)(l.r,{variant:"neutralWeak",size:"medium",disabled:0===m.length,onClick:()=>f([]),children:i("toolImage.clearMarks")}),(0,r.jsx)(l.r,{variant:"neutralWeak",size:"medium",onClick:y,children:i("i18n.close")})]})]}),document.body)}function aA({block:e,isStreaming:t,cwd:n,onOpenFile:s}){return(0,r.jsx)(ab,{isStreaming:t,cwd:n,onOpenFile:s,children:e.text})}function a_({block:e,duration:t,sessionId:n,entryId:a,blockIndex:i}){let{t:l}=(0,F.s)(),[o,c]=(0,s.useState)(null),[d,u]=(0,s.useState)(!0===e.deferred),[h,p]=(0,s.useState)(null);(0,s.useEffect)(()=>{if(!e.deferred){c(null),u(!1),p(null);return}let t=!1;return n&&a?(u(!0),p(null),(function(e,t,n){let r=`${e}:${t}:${n}`,s=ay.get(r);if(s)return ay.delete(r),ay.set(r,s),s;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 ay.delete(r),e});if(ay.set(r,a),ay.size>100){let e=ay.keys().next().value;e&&ay.delete(e)}return a})(n,a,i).then(e=>{t||c(e)}).catch(e=>{t||p(e instanceof Error?e.message:String(e))}).finally(()=>{t||u(!1)}),()=>{t=!0}):(u(!1),p(l("i18n.thinkingUnavailable")),()=>{t=!0})},[e.deferred,e.thinking,i,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:d?(0,r.jsx)("span",{className:"markdown-thinking-status",children:l("i18n.loadingThinking")}):h?(0,r.jsx)("span",{className:"markdown-thinking-error",children:h}):f?(0,r.jsx)(nJ,{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 aF({block:e,result:t,duration:n,runStartedAt:a,sessionId:i}){var l;let o,{t:c}=(0,F.s)(),d=(0,s.useId)(),[u]=(0,s.useState)(()=>Date.now()),[h,p]=(0,s.useState)(null),m=(0,s.useContext)(tY),f=m?.toolCallId===e.toolCallId?m.nonce:null,[g,x]=(0,s.useState)(null);null!==f&&f!==g&&(x(f),p(!0));let v=(l=t?null:n0(i,e.toolCallId),(0,s.useSyncExternalStore)(nX,()=>l?nY.get(l)??null:null,()=>null)),y=e.toolName.toLowerCase(),b=JSON.stringify(e.input,null,2),w="todo"===y||y.endsWith(".todo")||y.endsWith("_todo"),k="bash"===y||y.startsWith("bash ")||y.endsWith(".bash")||y.endsWith("_bash"),j=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 s="string"==typeof n.diff?n.diff:null;return s?{text:s}:null}(t):null,S=w?"unknown"===(o=tD(e,t)).kind||0===o.phases.length?null:o.phases:null,C=j?j.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,N=t?t.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n"):null,T=null!==N&&("(no output)"===N.trim()||""===N.trim()),I=t?ra(t):null,M=t?t.isError||null!==I&&0!==I?"failed":"done":"running",E="failed"===M,$=h??E;if(w&&S)return(0,r.jsx)(aB,{phases:S});let R=k&&"string"==typeof e.input.command?e.input.command:"",L=function(e,t,n){let r,s=t.html;if(!("ask"===(r=e.trim().toLowerCase())||r.endsWith(".ask")||r.endsWith("_ask"))||"string"!=typeof s)return null;let a="object"==typeof n&&null!==n?n:{},i=[];if(Array.isArray(a.answers))for(let e of a.answers)"string"==typeof e?.question&&"string"==typeof e.answer&&i.push({question:e.question,answer:e.answer});let l=!0===a.timedOut,o=i[0]?.question||s.replace(/<(script|style|template)\b[\s\S]*?<\/\1>/gi," ").replace(/<[^>]*>/g," ").replace(/&nbsp;/gi," ").replace(/&amp;/gi,"&").replace(/&lt;/gi,"<").replace(/&gt;/gi,">").replace(/&quot;/gi,'"').replace(/&#39;/gi,"'").replace(/\s+/g," ").trim(),c=i.length>1?` (+${i.length-1})`:"",d=Math.max(0,120-c.length),u=o.length>d?`${o.slice(0,Math.max(0,d-1))}…`:o;return{target:`${u}${c}`,rows:i,timedOut:l}}(e.toolName,e.input,t?.details),P=null!==L&&L.rows.length>0?L:null,A=!!(S||j||P),_=k?R.split(/\r?\n/,1)[0]??"":L?.target??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 s=e.toolName.toLowerCase();if(t=s,["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"===s||s.endsWith(".eval")||s.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,S),O=!k&&/^\S+$/.test(_)&&/[\\/]/.test(_),z=C?c("toolRun.diffStats",{added:C.added,removed:C.removed}):"";return(0,r.jsxs)("div",{className:`tool-call-card ${E?"is-error":"running"===M?"is-running":"is-done"}${k?" is-shell":""}${null!==f?" is-reveal-target":""}`,"data-tool-call-id":e.toolCallId,"aria-busy":"running"===M||void 0,style:{overflow:"hidden",fontSize:12},children:[(0,r.jsxs)("button",{type:"button",className:"tool-call-header",onClick:()=>p(!$),"aria-expanded":$,"aria-controls":$?d: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)(aH,{toolName:e.toolName}),(0,r.jsx)("span",{className:"tool-call-name",children:k?"bash":e.toolName}),k&&y.includes("(local)")&&(0,r.jsx)("span",{className:"shell-local-label",children:"local"}),(0,r.jsx)("span",{className:`tool-call-target${O?" is-path":""}`,title:k?R:_,children:O?(0,r.jsx)("bdi",{dir:"ltr",children:_}):_}),C&&(0,r.jsxs)("span",{className:"tool-call-diffstats",title:z,"aria-label":z,children:[(0,r.jsxs)("span",{style:{color:"var(--success)"},children:["+",C.added]}),(0,r.jsxs)("span",{style:{color:"var(--danger)"},children:["−",C.removed]})]}),(0,r.jsx)(az,{state:M,duration:n,exitCode:I,startedAt:a??u}),(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:$?"rotate(180deg)":"none",transition:"transform 0.15s"},children:(0,r.jsx)("polyline",{points:"2 3.5 5 6.5 8 3.5"})})]}),"running"===M&&v&&(0,r.jsx)("div",{className:"tool-call-progress",title:v,style:{padding:"0 10px 6px 29px",color:"var(--text-dim)",fontSize:11,lineHeight:1.4,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:v}),$&&(0,r.jsx)("div",{id:d,className:"tool-call-body",children:k?(0,r.jsx)(aq,{command:R,output:N??"",pending:!t,isError:E}):(0,r.jsxs)(r.Fragment,{children:[j&&(0,r.jsx)("div",{style:{maxHeight:560,overflowY:"auto",overflowX:"hidden"},children:(0,r.jsx)(aV,{diff:j})}),t&&E&&(0,r.jsx)(aZ,{text:N??"",isEmpty:T,isError:!0}),P&&!E&&(0,r.jsx)(aO,{summary:P}),!A&&(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:b}),t&&!A&&!E&&(0,r.jsx)(aZ,{text:N??"",isEmpty:T,isError:!1})]})})]})}function aO({summary:e}){let{t}=(0,F.s)();return(0,r.jsxs)("div",{className:"tool-call-ask",style:{padding:"8px 10px"},children:[(0,r.jsx)("dl",{style:{margin:0,display:"grid",gap:8},children:e.rows.map((e,t)=>(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("dt",{style:{color:"var(--text-muted)",fontSize:12,lineHeight:1.5,overflowWrap:"anywhere"},children:e.question}),(0,r.jsx)("dd",{style:{margin:"2px 0 0",color:"var(--text)",fontSize:12,lineHeight:1.5,whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:""===e.answer?"—":e.answer})]},t))}),e.timedOut&&(0,r.jsx)("p",{style:{margin:"8px 0 0",color:"var(--text-muted)",fontSize:12,lineHeight:1.5},children:t("toolRun.askTimedOut")})]})}function az({state:e,duration:t,exitCode:n,startedAt:s}){let{t:a}=(0,F.s)();return"running"===e?(0,r.jsx)(aD,{startedAt:s}):(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)(n2.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 aD({startedAt:e}){let{t}=(0,F.s)(),n=nG(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 aW(e,t){let n=e.trim().toLowerCase();return n===t||n.endsWith(`.${t}`)||n.endsWith(`_${t}`)||n.split(/[.\s:_-]+/).includes(t)}function aH({toolName:e}){let t,n=(t=e.trim().toLowerCase()).includes("str_replace")||t.includes("replace_editor")||aW(t,"edit")?"edit":aW(t,"read")||aW(t,"cat")?"read":aW(t,"write")||aW(t,"save")?"write":aW(t,"glob")||aW(t,"find")?"glob":aW(t,"grep")||aW(t,"search")?"grep":aW(t,"bash")||aW(t,"shell")||aW(t,"exec")?"bash":aW(t,"todo")?"todo":aW(t,"eval")?"eval":aW(t,"task")||aW(t,"agent")?"task":aW(t,"browser")||aW(t,"web_search")||aW(t,"fetch")?"browser":aW(t,"image")||aW(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)(aU,{kind:n})})})}function aU({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 aB({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)(sB,{task:e},`${e.content}-${t}`))]},`${t.name}-${n}`))})]})}function aq({command:e,output:t,pending:n,isError:s}){let{isDark:a}=nN(),{t:i}=(0,F.s)(),l=eV(t.split(/\r?\n/)),o=1===l.length&&""===l[0]?[]:l;return(0,r.jsxs)("div",{className:`shell-output-preview${s?" 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)(tZ.A,{className:"shell-command-code",language:"bash",style:a?tQ.xJ:tQ.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:i("i18n.noOutput")}),o.map((e,t)=>{let n=eH(e).trimStart(),a=s||/^(?: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:[eK(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 aV({diff:e}){return(0,r.jsx)("div",{style:{background:"var(--bg)"},children:(0,r.jsx)(aK,{text:e.text})})}function aK({text:e}){let{t}=(0,F.s)(),n=(0,s.useMemo)(()=>sH(e),[e]);if(!n)return(0,r.jsx)(aY,{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,marginTop:8*(0!==n),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)"},children:[(0,r.jsx)(aJ,{title:e.oldPath||t("i18n.before"),side:"left"}),(0,r.jsx)(aJ,{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)(aG,{cell:e.left,side:"left"}),(0,r.jsx)(aG,{cell:e.right,side:"right"})]},t))})]},n))})}function aJ({title:e,side:t}){return(0,r.jsx)("div",{title:e,style:{padding:"left"===t?"5px 14px 5px 10px":"5px 10px 5px 14px",color:"var(--text-dim)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e})}function aG({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",s="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,marginInlineEnd:4*("left"===t)},children:[(0,r.jsx)("span",{style:{width:42,padding:"0 6px",textAlign:"right",color:"var(--text-dim)",userSelect:"none",background:"var(--bg-panel)",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:s}),(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 aY({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"},children:[(0,r.jsx)("span",{style:{width:48,padding:"0 8px",color:"var(--text-dim)",background:"var(--bg-panel)",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 aZ({text:e,isEmpty:t,isError:n}){let{t:s}=(0,F.s)();return(0,r.jsx)("div",{style:{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?s("i18n.noOutput"):e})})}function aQ({message:e}){let{t}=(0,F.s)(),n=a2(e.content),a=(0,s.useMemo)(()=>{let e,t,r,s,a;return e=[],t=[],r=n.match(rl),s=r?.[1]??"",a=r?.index===void 0?n:n.slice(0,r.index),s.replace(ri,(n,r,s)=>{let a=s.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]),i=aS(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:0,borderRadius:"var(--radius-surface)",overflow:"hidden",background:"var(--bg-subtle)"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"7px 10px",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:ro(l)})}),i&&(0,r.jsx)("span",{style:{marginLeft:"auto",color:"var(--text-dim)",fontSize:10},children:i})]}),(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)(nJ,{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)(aX,{readFiles:a.readFiles,modifiedFiles:a.modifiedFiles})]})]})})}function aX({readFiles:e,modifiedFiles:t}){let{t:n}=(0,F.s)();if(0===e.length+t.length)return null;let s=[];return e.length>0&&s.push(`${e.length} read`),t.length>0&&s.push(`${t.length} modified`),(0,r.jsxs)("details",{className:"compaction-file-details",children:[(0,r.jsx)("summary",{children:n("i18n.fileContext",{details:s.join(", ")})}),t.length>0&&(0,r.jsx)(a0,{title:n("i18n.modifiedFiles"),files:t}),e.length>0&&(0,r.jsx)(a0,{title:n("i18n.readFiles"),files:e})]})}function a0({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 a1({message:e,cwd:t,onOpenFile:n}){var a;let i,{t:l}=(0,F.s)(),o=!1===e.display,[c,d]=(0,s.useState)(!o),[u,h]=(0,s.useState)(!1),[p,m]=(0,s.useState)(!1),f=a2(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):"",y=e.customType||"extension",b=aS(e.timestamp);return(0,r.jsx)("div",{style:{marginBottom:16},children:(0,r.jsxs)("div",{style:{border:0,borderRadius:"var(--radius-surface)",overflow:"hidden",background:o?"var(--bg-hover)":"var(--bg-subtle)",opacity:o&&!c?.82:1},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"7px 10px",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:y}),o&&(0,r.jsx)("span",{style:{color:"var(--text-dim)",fontSize:11},children:l("i18n.hiddenExtensionMessage")}),b&&(0,r.jsx)("span",{style:{marginLeft:"auto",color:"var(--text-dim)",fontSize:10},children:b})]}),c?(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=a4(e);return n?(0,r.jsx)("img",{src:n,alt:"",style:{maxWidth:240,maxHeight:240,borderRadius:"var(--radius-control)",objectFit:"contain",display:"block"}},t):null})}),f?(0,r.jsx)(nJ,{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:()=>d(!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?(i=f.replace(/\s+/g," ").trim())?i.length>140?`${i.slice(0,140)}...`:i:"Show extension message":l("i18n.showExtensionMessage")}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"4px 9px",background:"var(--bg-subtle)"},children:[f||v?(0,r.jsx)("button",{className:"message-meta-action",onClick:()=>{nT(f||v).then(()=>{m(!0),setTimeout(()=>m(!1),1500)})},style:{padding:"3px 7px",border:"none",background:"none",color:p?"var(--accent)":"var(--text-dim)",cursor:"pointer",fontSize:11},children:l(p?"i18n.copied":"i18n.copy")}):null,(x||o)&&(0,r.jsx)("button",{onClick:()=>{o?d(e=>!e):h(e=>!e)},style:{marginLeft:"auto",padding:"3px 7px",border:"none",background:"none",color:"var(--text-dim)",cursor:"pointer",fontSize:11},children:l(o?c?"i18n.collapse":"i18n.expand":u?"i18n.hideDetails":"i18n.showDetails")})]}),x&&(o&&c||!o&&u)&&(0,r.jsx)("pre",{style:{margin:0,padding:"9px 10px",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 a2(e){return"string"==typeof e?e:e.filter(e=>"text"===e.type).map(e=>e.text).join("\n")}function a4(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 a8({message:e,sessionId:t}){let[n,a]=(0,s.useState)(null),[i,l]=(0,s.useState)(!1),[o,c]=(0,s.useState)(null),d=!e.output&&void 0===e.exitCode&&!e.cancelled,u=e.cancelled||void 0!==e.exitCode&&0!==e.exitCode,h=t&&e.fullOutputPath?`/api/agent/${encodeURIComponent(t)}/bash-output?path=${encodeURIComponent(e.fullOutputPath)}`:null,p=e.truncated&&h&&null===n,m=n??e.output;async function f(){if(h){l(!0),c(null);try{let e=await fetch(h),t=await e.json();t.success?a(t.data?.output??""):c(t.error??"failed")}catch(e){c(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=d?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)(aF,{block:x,result:v,runStartedAt:e.timestamp}),e.truncated&&h&&(0,r.jsxs)("div",{style:{padding:"4px 10px",fontSize:11,marginTop:-1},children:[p&&(0,r.jsx)("button",{onClick:f,disabled:i,style:{background:"none",border:"none",color:"var(--accent)",cursor:i?"default":"pointer",fontSize:11,padding:0,textDecoration:"underline"},children:i?"loading…":"view full output"}),(0,r.jsx)("a",{href:`${h}&download=1`,style:{marginLeft:10*!!p,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,")"]})]})]})}let a5=/^[\t ]*(?:WORK_CLASS|PURPOSE|BLOCKS_PRIMARY|PRIMARY_DELIVERABLE|OWNED_PATHS|FINDING_ID)[\t ]*:[^\r\n]*$/i;function a6(e){if(!e)return null;let t=/^\s*TASK_GUARD\s*:\s*$/im.exec(e),n=e;if(t){let r=t.index+t[0].length;"\r"===e[r]&&(r+=1),"\n"===e[r]&&(r+=1);let s=r;for(;r<e.length;){let t=e.indexOf("\n",r),n=-1===t?e.length:t,a=n>r&&"\r"===e[n-1]?n-1:n;if(!a5.test(e.slice(r,a)))break;s=a,r=-1===t?e.length:t+1}let a=t[0].length-t[0].trimStart().length;n=`${e.slice(0,t.index+a)}${e.slice(s)}`}let r=[...n.matchAll(/^\s*TASK_TITLE\s*:\s*(.*?)\s*$/gim)].map(e=>e[1]??"");return 1===r.length&&r[0]&&r[0]===r[0].trim()&&/[가-힣]/u.test(r[0])?r[0]:null}function a3(e){let t=e.live,n=e.archive&&("archive"===e.identity||"session-file"===e.archiveMatch)?e.archive:void 0,r=[t?.assignment,t?.progress?.assignment,t?.task].map(a6).find(e=>null!==e)??(n?.taskTitle?.trim()||null),s=t?.progress?.lastIntent?.trim()||"",a=t?.progress?.currentTool?.trim()||"";return{title:r??"담당 업무 미확인",stage:s&&a?`${s} \xb7 ${a}`:s||(a?`${a} 실행 중`:null),explicitTitle:null!==r}}function a7(e){let t=e.live?.progress,n="string"==typeof t?.resolvedModel?t.resolvedModel.trim():"",r=e.archive&&("archive"===e.identity||"session-file"===e.archiveMatch)?e.archive:void 0,s="string"==typeof t?.resolvedThinkingLevel?t.resolvedThinkingLevel.trim():"",a="string"==typeof r?.thinkingLevel?r.thinkingLevel.trim():"";if(n){let e=n.split("/").pop()||n;return{model:n,modelShort:s&&e.endsWith(`:${s}`)?e.slice(0,-(s.length+1)):e,modelIsFallback:t?.resolvedModelIsFallback===!0,effort:s||a||null}}let i="string"==typeof r?.model?r.model.trim():"";return{model:i||null,modelShort:i?i.split("/").pop()||i:null,modelIsFallback:!!i&&r?.modelIsFallback===!0,effort:a||null}}class a9 extends Error{constructor(e,t,n){super(t),this.kind=e,this.status=n,this.name="SubagentClientError"}}async function ie(e){try{return await e.json()}catch{throw new a9("invalid-response","응답 JSON을 해석할 수 없습니다.",e.status)}}function it(e){return!!e&&"object"==typeof e&&"string"==typeof e.name&&"number"==typeof e.bytes&&"number"==typeof e.modified&&(null===e.messages||"number"==typeof e.messages)&&(void 0===e.taskTitle||"string"==typeof e.taskTitle)&&"string"==typeof e.firstTask}function ir(e){return!!e&&"object"==typeof e&&"string"==typeof e.role&&("message"===e.kind||"custom"===e.kind)&&"string"==typeof e.text&&(null===e.at||"number"==typeof e.at)}function is(e){return!!e&&"object"==typeof e&&!!("id"in e&&"string"==typeof e.id)&&!!("index"in e&&"number"==typeof e.index)&&!!("agent"in e&&"string"==typeof e.agent)&&!!("agentSource"in e&&("bundled"===e.agentSource||"user"===e.agentSource||"project"===e.agentSource))&&!!("status"in e&&("pending"===e.status||"running"===e.status||"completed"===e.status||"failed"===e.status||"aborted"===e.status||"unknown"===e.status))&&!!("lastUpdate"in e&&"number"==typeof e.lastUpdate)&&!0}function ia(e){return!!e&&"object"==typeof e&&(!("id"in e)||void 0===e.id||"string"==typeof e.id)&&(!("type"in e)||void 0===e.type||"string"==typeof e.type)&&(!("message"in e)||void 0===e.message||null!==e.message&&"object"==typeof e.message)}function ii(e=(e,t)=>fetch(e,t),t="/api/sidecars/subagent"){let n=async(t,n,r)=>{let s;try{s=await e(t,n)}catch(e){if(n.signal?.aborted)throw e;throw new a9(r,"sidecar-unreachable"===r?"Subagent 기록 사이드카(30144)에 연결할 수 없습니다.":"실시간 Subagent 상태에 연결할 수 없습니다.")}let a=await ie(s);if(!s.ok)throw new a9("http",function(e,t){if(e&&"object"==typeof e&&"error"in e){let t=e.error;if("string"==typeof t&&t)return t}return t}(a,`HTTP ${s.status}`),s.status);return{response:s,body:a}};return{async getLiveSnapshots(e,t){let{body:r}=await n(`/api/agent/${encodeURIComponent(e)}`,{method:"GET",signal:t},"live-unreachable");if(!r||"object"!=typeof r)throw new a9("invalid-response","실시간 Subagent 응답이 올바르지 않습니다.");if("string"==typeof r.error&&r.error)throw new a9("http",r.error);if(!0!==r.running)return{runtime:"detached",subagents:[]};let s=r.state?.subagents;if(void 0!==s&&(!Array.isArray(s)||!s.every(is)))throw new a9("invalid-response","실시간 Subagent 목록이 올바르지 않습니다.");return{runtime:"running",subagents:s??[]}},async getLiveTranscript(e,t,r,s){let{body:a}=await n(`/api/agent/${encodeURIComponent(e)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:"get_subagent_messages",subagentId:t,fromByte:r}),signal:s},"live-unreachable");if(!a||"object"!=typeof a)throw new a9("invalid-response","실시간 Subagent 기록 응답이 올바르지 않습니다.");if("string"==typeof a.error&&a.error)throw new a9("http",a.error);if(!0!==a.success||!a.data||"object"!=typeof a.data)throw new a9("invalid-response","실시간 Subagent 기록 응답이 올바르지 않습니다.");let i=a.data;if(!Array.isArray(i.entries)||!i.entries.every(ia)||"number"!=typeof i.fromByte||"number"!=typeof i.nextByte||"boolean"!=typeof i.reset)throw new a9("invalid-response","실시간 Subagent 기록 응답이 올바르지 않습니다.");return{fromByte:i.fromByte,nextByte:i.nextByte,reset:i.reset,entries:i.entries}},async getArchive(e,r){let s=`${t}/archive?session=${encodeURIComponent(e)}`,{body:a}=await n(s,{method:"GET",signal:r},"sidecar-unreachable");if(!a||"object"!=typeof a||"string"!=typeof a.sessionId||"string"!=typeof a.dir||"boolean"!=typeof a.found||!Array.isArray(a.subagents)||!a.subagents.every(it))throw new a9("invalid-response","Subagent 기록 목록 응답이 올바르지 않습니다.");return{sessionId:a.sessionId,dir:a.dir,found:a.found,subagents:a.subagents,...!0===a.listTruncated?{listTruncated:!0}:{}}},async getArchiveTranscript(e,r,s=400,a){let i=`${t}/transcript?session=${encodeURIComponent(e)}&name=${encodeURIComponent(r)}&limit=${encodeURIComponent(String(s))}`,{body:l}=await n(i,{method:"GET",signal:a},"sidecar-unreachable");if(!l||"object"!=typeof l||"string"!=typeof l.sessionId||"string"!=typeof l.name||"number"!=typeof l.bytes||"boolean"!=typeof l.truncated||!Array.isArray(l.entries)||!l.entries.every(ir))throw new a9("invalid-response","Subagent 디스크 기록 응답이 올바르지 않습니다.");return{sessionId:l.sessionId,name:l.name,bytes:l.bytes,truncated:l.truncated,entries:l.entries}}}}let il=["feature","maintenance","diagnostic"],io=/^[\t ]*([A-Z_]+)[\t ]*:[\t ]*(.*?)[\t ]*$/;function ic(e){if("string"!=typeof e)return null;let t=e.split(/\r?\n/),n=t.findIndex(e=>/^\s*TASK_GUARD\s*:\s*$/.test(e));if(n<0)return null;for(let e=n+1;e<t.length;e+=1){let n=io.exec(t[e]);if(!n)break;if("WORK_CLASS"!==n[1])continue;let r=n[2].toLowerCase();return il.includes(r)?r:null}return null}let id={verdicts:new Map,runs:new Map,latestByAgent:new Map,spawnedAt:new Map,durations:new Map,parallelWith:new Map,runStartedAt:new Map};function iu(e){return Array.isArray(e)?e.filter(e=>"object"==typeof e&&null!==e):[]}function ih(e){return"string"==typeof e&&e.trim()?e:null}function ip(e){return"number"==typeof e.durationMs&&Number.isFinite(e.durationMs)&&e.durationMs>=0?e.durationMs:null}function im(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 ig(e){return"string"==typeof e?e:e.map(e=>"text"===e.type?e.text:"").join("\n")}function ix(e,t){if(t?.isError)return null;let n=iu(e.input.tasks),r=iu(t?.details?.progress),s=Math.max(n.length,r.length),a=[];for(let i=0;i<s;i++){let s=r.find(e=>e.index===i)??r[i],l=n[i],o=ih(s?.id)??ih(l?.name);o&&a.push({key:`${e.toolCallId}#${i}`,toolCallId:e.toolCallId,index:i,agentId:o,agent:ih(s?.agent)??ih(l?.agent),task:ih(s?.task)??ih(l?.task)??"",workClass:ic(l?.task)??ic(s?.task),spawned:!!t})}return a}let iv=/<task-result\b([^>]*)>/g,iy=/(\w+)="([^"]*)"/g;function ib(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 iw(e,t,n){var r;let s,a,i,l,o=ib(e,t,n),c=o?{key:e.key,identity:"live",live:o.assignment?o:{...o,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}},d=a3(c),u=n.runs.get(e.key),h=null;o&&"unknown"!==o.status?(s=o.status,h="live"):u&&"unknown"!==u.status?(s=u.status,h="record"):s=e.spawned?"unobserved":"dispatching";let p=n.verdicts.get(e.key),m=p&&p.length>0?p[p.length-1]:null,f=m?.at??null,g=null===f?null:(r=e.key,a=n.runStartedAt.get(r)??null,i=o?.progress?.durationMs,l=o&&("pending"===o.status||"running"===o.status)&&"number"==typeof i&&o.lastUpdate>0?o.lastUpdate-i:null,null===a?l:null===l?a:Math.max(a,l)),x=null!==f&&null!==g&&g>f;return{member:e,title:d.title,explicitTitle:d.explicitTitle,stage:o?d.stage:null,model:o?a7(c):null,run:s,runSource:h,verdict:x?null:m,priorVerdict:x?m:null,runTitle:x?a6(o?.progress?.task):null,observedParallelWith:n.parallelWith.get(e.key)}}function ik(e,t){return t.find(t=>t.parentToolCallId===e.toolCallId&&t.id===e.agentId)}function ij(e,t){let n=[...t.verdicts.get(e.key)??[]].sort((e,t)=>e.order-t.order),r=new Map,s=[];for(let e of n){let t={attempt:e.attempt,verdict:e.verdict,reason:e.reason};null===e.attempt?s.push(t):r.set(e.attempt,t)}return[...s,...[...r.values()].sort((e,t)=>(e.attempt??0)-(t.attempt??0))]}function iS(e){return"assistant"!==e.role?[]:e.content?.filter(e=>"toolCall"===e.type&&"task"===e.toolName)??[]}let iC=(0,s.createContext)({ledger:id,subagents:[],toolResults:new Map});n(21340);let iN={test:!0,tests:!0,__tests__:!0,__fixtures__:!0,fixtures:!0,__snapshots__:!0,node_modules:!0,coverage:!0},iT={html:0,document:1,image:2},iI=["investigate","edit","check","review","commit","ci","deploy"];function iM(e,t){let n="",r=t;for(;r<e.length&&'"'!==e[r];){let t=e[r];if("\\"===t&&r+1<e.length){let s=e[r+1];"\n"!==s&&(n+='$`"\\'.includes(s)?s:t+s),r+=2}else if("$"===t&&"("===e[r+1]){let t=iE(e,r+1);n+=e.slice(r,t),r=t}else if("`"===t){let t=i$(e,r+1);n+=e.slice(r,t),r=t}else n+=t,r+=1}return{text:n,end:Math.min(r+1,e.length)}}function iE(e,t){let n=e[t],r="{"===n?"}":")",s=0,a=t;for(;a<e.length;){let t=e[a];if("\\"===t)a+=2;else if("'"===t){let t=e.indexOf("'",a+1);a=t<0?e.length:t+1}else if('"'===t)a=iM(e,a+1).end;else if("`"===t)a=i$(e,a+1);else{if(t===n)s+=1;else if(t===r&&0==--s)return a+1;a+=1}}return e.length}function i$(e,t){let n=t;for(;n<e.length&&"`"!==e[n];)n+="\\"===e[n]?2:1;return Math.min(n+1,e.length)}function iR(e){let{tokens:t,groups:n,expandingHeredoc:r}=function(e){let t=[],n=[],r=!1,s=[],a=[],i="",l=-1,o=!1,c=e=>{if(l<0)return;let n={value:i,start:l,end:e,risky:o};for(let e of(t.push(n),a.splice(0)))e.at===t.length-1&&(e.owner=n);i="",l=-1,o=!1},d=0;for(;d<e.length;){let u=e[d];if("\\"===u)"\n"!==e[d+1]&&(l<0&&(l=d),i+=e[d+1]??""),d+=2;else if("'"===u){l<0&&(l=d);let t=e.indexOf("'",d+1),n=t<0?e.length:t;i+=e.slice(d+1,n),d=n+1}else if('"'===u){l<0&&(l=d);let t=iM(e,d+1);/\$[({]|`/.test(e.slice(d,t.end))&&(o=!0),i+=t.text,d=t.end}else if("$"===u&&("("===e[d+1]||"{"===e[d+1])){l<0&&(l=d);let t=iE(e,d+1);i+=e.slice(d,t),o=!0,d=t}else if("`"===u){l<0&&(l=d);let t=i$(e,d+1);i+=e.slice(d,t),o=!0,d=t}else if("#"===u&&l<0){let t=e.indexOf("\n",d);d=t<0?e.length:t}else if(" "===u||" "===u||"\r"===u)c(d),d+=1;else if("\n"===u){c(d);let n=t[t.length-1];for(let i of("&&"!==n&&"||"!==n&&"|"!==n&&t.push(";"),d+=1,a.length=0,s.splice(0)))for(;d<e.length;){let t=e.indexOf("\n",d),n=t<0?e.length:t,s=e.slice(d,n);if(d=n+1,(i.stripTabs?s.replace(/^\t+/,""):s)===i.delimiter)break;!i.quoted&&/\$[({]|`/.test(s)&&(i.owner?i.owner.risky=!0:r=!0)}}else if("<"===u&&"<"===e[d+1]&&"<"!==e[d+2]){c(d);let n=d+2,r="-"===e[n];for(r&&(n+=1);" "===e[n]||" "===e[n];)n+=1;let i="",l=!1;for(;n<e.length&&!/[\s;&|<>()]/.test(e[n]);){let t=e[n];if("'"===t||'"'===t){l=!0;let r=e.indexOf(t,n+1),s=r<0?e.length:r;i+=e.slice(n+1,s),n=s+1}else"\\"===t&&(l=!0),i+="\\"===t?e[n+1]??"":t,n+="\\"===t?2:1}if(i){let e=t[t.length-1],n={delimiter:i,stripTabs:r,quoted:l,owner:void 0!==e&&"string"!=typeof e?e:null,at:t.length};s.push(n),n.owner||a.push(n)}d=n}else";"===u?(c(d),t.push(";"),d+=";"===e[d+1]?2:1):"&"===u?"&"===e[d+1]?(c(d),t.push("&&"),d+=2):(">"===e[d+1]||/[<>]$/.test(i)?(l<0&&(l=d),i+=u):(c(d),t.push("&")),d+=1):"|"===u?"|"===e[d+1]?(c(d),t.push("||"),d+=2):i.endsWith(">")?(i+=u,d+=1):(c(d),t.push("|"),d+="&"===e[d+1]?2:1):("("===u||")"===u?(c(d),n.push(d)):(l<0&&(l=d),("{"===u||"}"===u||"!"===u)&&(o=!0),i+=u),d+=1)}return c(e.length),{tokens:t,groups:n,expandingHeredoc:r}}(e),s=[],a=[],i={pipelines:[],operators:[],background:!1},l={commands:[],negated:!1},o=[],c=()=>{let t=o.map(e=>e.value).filter(e=>"{"!==e&&"}"!==e);if(0===l.commands.length&&"!"===t[0]&&(l.negated=!0,t.shift()),t.length>0){let r=o[0].start,s=o[o.length-1].end,i=o.some(e=>e.risky)||n.some(e=>e>=r&&e<=s),c={words:t,text:e.slice(r,s),uncertain:i};l.commands.push(c),a.push(c)}o=[]},d=()=>{c(),l.commands.length>0&&i.pipelines.push(l),l={commands:[],negated:!1}},u=e=>{d(),i.pipelines.length>0&&s.push({...i,background:e}),i={pipelines:[],operators:[],background:!1}};for(let e of t)"string"!=typeof e?o.push(e):"|"===e?c():"&&"===e||"||"===e?(d(),i.operators.push(e)):u("&"===e);return u(!1),{lists:s,commands:a,uncertain:n.length>0||r||t.some(e=>"string"!=typeof e&&e.risky)}}function iL(e){return e.slice(e.lastIndexOf("/")+1)}let iP={bash:!0,sh:!0,zsh:!0,dash:!0},iA={sudo:!0,env:!0,command:!0,exec:!0,nice:!0,nohup:!0,time:!0,timeout:!0,setsid:!0,"systemd-run":!0},i_={"-u":!0,"--unit":!0,"-p":!0,"--property":!0,"-E":!0,"--setenv":!0,"--description":!0,"--slice":!0,"-M":!0,"--machine":!0,"-H":!0,"--host":!0,"--uid":!0,"--gid":!0,"--working-directory":!0,"-s":!0,"--signal":!0,"-k":!0,"--kill-after":!0},iF={"--wait":!0,"-W":!0,"--pipe":!0,"-P":!0,"--pty":!0,"-t":!0,"--scope":!0},iO={if:!0,then:!0,elif:!0,else:!0,do:!0,while:!0,until:!0};function iz(e){let t=iH(e);if(t>=0&&"eval"===e[t])return t+1<e.length?e.slice(t+1).join(" "):null;if(t<0||!Object.hasOwn(iP,iL(e[t]))||iD(e,t))return null;for(let n=t+1;n<e.length&&/^[-+]/.test(e[n]);n+=1){if(/^-[a-zA-Z]*c[a-zA-Z]*$/.test(e[n]))return e[n+1]??null;(/^[-+][a-zA-Z]*[oO]$/.test(e[n])||"--rcfile"===e[n]||"--init-file"===e[n])&&(n+=1)}return null}function iD(e,t){for(let n=t+1;n<e.length&&/^[-+]/.test(e[n]);n+=1){if(/^-[a-zA-Z]*n[a-zA-Z]*$/.test(e[n])||/^-[a-zA-Z]*o$/.test(e[n])&&"noexec"===e[n+1])return!0;(/^[-+][a-zA-Z]*[oO]$/.test(e[n])||"--rcfile"===e[n]||"--init-file"===e[n])&&(n+=1)}return!1}let iW={command:/^-[a-zA-Z]*[vV]/,sudo:/^(?:-[a-zA-Z]*[lvVhK]|--(?:list|validate|version|help|remove-timestamp)$)/};function iH(e){let t=!1,n="";for(let r=0;r<e.length;r+=1){let s=e[r];if(!(/^[A-Za-z_]\w*=/.test(s)||!t&&Object.hasOwn(iO,s))){if(t&&(s.startsWith("-")||/^\d+(?:\.\d+)?[smhd]?$/.test(s))){if(Object.hasOwn(iW,n)&&iW[n].test(s))return -1;"command"!==n&&Object.hasOwn(i_,s)&&(r+=1);continue}if(!Object.hasOwn(iA,iL(s)))return r;t=!0,n=iL(s)}}return -1}let iU=/(?:^|\/)wsl\/update\.sh$/;function iB(e,t=0){let n=iz(e);if(null!==n)return t<3&&iR(n).commands.some(e=>iB(e.words,t+1));let r=iH(e);if(r<0)return!1;if(iU.test(e[r]))return!0;if(!Object.hasOwn(iP,iL(e[r]))||iD(e,r))return!1;let s=e.slice(r+1).find(e=>!e.startsWith("-"));return void 0!==s&&iU.test(s)}function iq(e){let t=iH(e),n=t<0?e:e.slice(0,t),r=n.map(iL);return r.includes("systemd-run")?!n.some(e=>Object.hasOwn(iF,e)):!!(r.includes("sudo")&&n.some(e=>"--background"===e||/^-[a-zA-Z]*b[a-zA-Z]*$/.test(e)))||r.includes("setsid")&&!n.includes("-w")&&!n.includes("--wait")}function iV(e){let[t]=e.pipelines;return 1!==e.pipelines.length||1!==t.commands.length||t.negated?null:t.commands[0]}function iK(e){if(e.every(e=>/^[A-Za-z_]\w*=/.test(e)))return!0;let[t,...n]=e;return"cd"===t?n.length<=1:"export"===t?n.every(e=>/^[A-Za-z_]\w*=/.test(e)):"set"===t&&n.every(e=>/^[-+][a-zA-Z]+$/.test(e)&&!/^-[a-zA-Z]*n/.test(e)||"pipefail"===e)}let iJ={tail:!0,head:!0,cat:!0,tee:!0},iG=/(?:^|[^\w-])(?:tests?|typecheck|tsc|lint|eslint|vitest|jest|pytest|build|check|verify|smoke)(?![\w])/i,iY={bun:!0,bunx:!0,npm:!0,npx:!0,pnpm:!0,yarn:!0,node:!0,python:!0,python3:!0,deno:!0},iZ={"--help":!0,"-h":!0,"--version":!0},iQ=Object.fromEntries(["-C","-r","--allow-fs-read","--allow-fs-write","--build-snapshot-config","--conditions","--cpu-prof-dir","--debug-port","--inspect-port","--experimental-config-file","--experimental-default-config-file","--experimental-test-isolation","--test-isolation","--report-dir","--report-directory","--cpu-prof-interval","--cpu-prof-name","--diagnostic-dir","--disable-proto","--disable-warning","--dns-result-order","--env-file","--env-file-if-exists","--experimental-loader","--experimental-package-map","--experimental-sea-config","--experimental-test-tag-filter","--heap-prof-dir","--heap-prof-interval","--heap-prof-name","--heapsnapshot-near-heap-limit","--heapsnapshot-signal","--icu-data-dir","--import","--input-type","--inspect-publish-uid","--loader","--localstorage-file","--max-http-header-size","--max-old-space-size-percentage","--network-family-autoselection-attempt-timeout","--openssl-config","--redirect-warnings","--report-filename","--report-signal","--require","--run","--secure-heap","--secure-heap-min","--snapshot-blob","--test-concurrency","--test-coverage-branches","--test-coverage-exclude","--test-coverage-functions","--test-coverage-include","--test-coverage-lines","--test-global-setup","--test-name-pattern","--test-random-seed","--test-reporter","--test-reporter-destination","--test-rerun-failures","--test-shard","--test-skip-pattern","--test-timeout","--title","--tls-cipher-list","--tls-keylog","--trace-event-categories","--trace-event-file-pattern","--trace-require-module","--unhandled-rejections","--use-largepages","--v8-pool-size","--watch-kill-signal","--watch-path"].map(e=>[e,!0]));function iX(e){let t=iH(e);if(t<0)return!1;let n=iL(e[t]);if("test"===n||"["===n||e.slice(t+1).some(e=>Object.hasOwn(iZ,e)))return!1;if(iG.test(n))return!0;if(!Object.hasOwn(iY,n))return!1;if("node"===n&&function(e,t){for(let n=t;n<e.length;n+=1){let t=e[n];if("--test"===t)return!0;if("--"===t||!t.startsWith("-"))break;Object.hasOwn(iQ,t)&&(n+=1)}return!1}(e,t+1))return!0;let r=function(e,t){for(let n=t;n<e.length;n+=1){let t=e[n];if("-m"===t)return e[n+1];if(/^-[a-zA-Z]*[cep]/.test(t)||/^--(?:eval|print)(?:=|$)/.test(t))break;if(!t.startsWith("-")){if("run"===t||"exec"===t||"x"===t||"dlx"===t)return e.slice(n+1).find(e=>!e.startsWith("-"));return t}}}(e,t+1);return void 0!==r&&iG.test(r)}let i0={"-C":!0,"-c":!0,"--git-dir":!0,"--work-tree":!0,"--namespace":!0},i1={commit:{"--dry-run":!0,"-h":!0,"--help":!0},push:{"--dry-run":!0,"-n":!0,"-h":!0,"--help":!0,"--delete":!0,"-d":!0}};function i2(e){let t=iH(e);if(t<0||"git"!==iL(e[t]))return null;for(let n=t+1;n<e.length;n+=1)if(Object.hasOwn(i0,e[n]))n+=1;else if(!e[n].startsWith("-"))return{name:e[n],at:n};return null}function i4(e,t=0,n){let r=iz(e);if(null!==r)return t<3&&iR(r).commands.some(e=>i4(e.words,t+1,n));let s=i2(e);if(!s||"commit"!==s.name&&"push"!==s.name||void 0!==n&&s.name!==n)return!1;let a=i1[s.name];return!e.slice(s.at+1).some(e=>Object.hasOwn(a,e)||"push"===s.name&&/[nd]/.test(function(e){if(!/^-[a-zA-Z0-9]/.test(e))return"";let t="";for(let n of e.slice(1)){if("o".includes(n)||!/[a-zA-Z0-9]/.test(n))break;t+=n}return t}(e)))}function i8(e){return iK(e)||null!==i2(e)}let i5={check:({words:e})=>iX(e),commit:({words:e})=>i4(e),ci:({words:e})=>{let t=iH(e);return t>=0&&"gh"===iL(e[t])&&"run"===e[t+1]&&"watch"===e[t+2]&&e.includes("--exit-status")},deploy:e=>iB(e.words)},i6={test:"test",tests:"test",vitest:"test",jest:"test",pytest:"test",typecheck:"typecheck",tsc:"typecheck",lint:"lint",eslint:"lint",build:"build",check:"verify",verify:"verify",smoke:"smoke"};function i3(e){return!e||"object"!=typeof e||"bash"!==e.toolName||!e.input||"object"!=typeof e.input||Array.isArray(e.input)?null:("string"==typeof e.input.command?e.input.command.trim():"")||null}let i7={"$?":!1,"${PIPESTATUS[0]}":!0};function i9(e,t){let n=lu(t);if("notRun"===n)return[];let r=n?void 0:t,s=iR(e),a=[];if(s.commands.some(({words:e})=>(function e(t,n=0){let r=iz(t);return null!==r?n<3&&iR(r).commands.some(t=>e(t.words,n+1)):iX(t)})(e))&&a.push("check"),s.commands.some(({words:e})=>i4(e))&&a.push("commit"),s.commands.some(({words:e})=>(function e(t,n=0){let r=iz(t);if(null!==r)return n<3&&iR(r).commands.some(t=>e(t.words,n+1));let s=iH(t);return s>=0&&"gh"===iL(t[s])&&"run"===t[s+1]&&["watch","view","list"].includes(t[s+2])})(e))&&a.push("ci"),s.commands.some(i5.deploy)&&a.push("deploy"),0===a.length)return[];let i=r?ra(r):null,l=null===i?!!r?.isError:0!==i,o=a.length>1?{stages:a,failed:l}:void 0,c=r?lR(r):"";return a.map(e=>{var t;let a,d,u,h="commit"===e?i8:iK,p=function e(t,n,r=iK,s=0){let{lists:a}=t,i=[],l=t.uncertain,o=!1;return a.forEach((t,c)=>{for(let d of(t.pipelines.some(e=>e.commands.some(({words:e})=>e.some(e=>e.includes("pipefail"))))&&(o=!1),t.pipelines)){let u=!1;for(let h of d.commands){let p=s<3?iz(h.words):null,m=null===p?null:e(iR(p),n,r,s+1);if(m&&m.decisive.length>0)i.push(...m.decisive);else if(n(h))i.push(h);else{let e=iH(h.words);u&&o&&e>=0&&Object.hasOwn(iJ,iL(h.words[e]))||r(h.words)||function(e,t){if(t!==e.length-1||e[t].background)return!1;let n=iV(e[t])?.words;return n?.[0]==="exit"&&(1===n.length||2===n.length&&"$?"===n[1])}(a,c)||(l=!0);continue}u=!0,(m?.reach==="masked"||d.negated||d.commands.length>1&&!o||t.operators.includes("||")||t.background||iq(h.words)||!function(e,t){if(t===e.length-1)return!0;let n=e[e.length-1],r=iV(n)?.words;return!!r&&"exit"===r[0]&&!n.background&&t===e.length-2&&(1===r.length||2===r.length&&"$?"===r[1])}(a,c))&&(l=!0)}}let d=iV(t)?.words;!t.background&&d?.[0]==="set"&&3===d.length&&"pipefail"===d[2]&&(/^-[a-zA-Z]*o$/.test(d[1])?o=!0:/^\+[a-zA-Z]*o$/.test(d[1])&&(o=!1))}),{reach:0===i.length?"absent":l?"masked":"carried",decisive:i}}(s,i5[e],h),m="check"===e&&p.decisive.some(({words:e})=>e.includes("--if-present")),f=r?(t=i5[e],a=new Map,d=s.lists.map(e=>(function(e){let t=e&&!e.background?iV(e)?.words:void 0;if(!t||"echo"!==t[0]||t.length<2)return null;let n=t.slice(1);if(n.some(e=>e.startsWith("-")||/^(?:\d*[<>]|&>)/.test(e)))return null;let r=n.join(" ");for(let[e,t]of Object.entries(i7)){let n=r.indexOf(e);if(n<0||r.indexOf(e,n+1)>=0)continue;let s=r.slice(0,n),a=r.slice(n+e.length);if(/[$`\\]/.test(s+a)||!/[^\s\d]/.test(s))break;return{prefix:s,suffix:a,first:t}}return null})(e)),u=c.split("\n").map(e=>e.trimEnd()),s.lists.forEach((e,n)=>{let r=d[n+1];if(!r||e.background||e.operators.includes("||"))return;let s=e.pipelines[e.pipelines.length-1],i=e.pipelines.slice(0,-1);if(s.negated||i.some(e=>e.negated||1!==e.commands.length||!h(e.commands[0].words)))return;let l=r.first||1===s.commands.length?s.commands[0]:void 0;if(!l||!t(l)||iq(l.words)||l.uncertain)return;let o=d.filter(e=>e?.prefix===r.prefix&&e.suffix===r.suffix),c=RegExp(`^${r.prefix.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(-?\\d+)${r.suffix.trimEnd().replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}$`),p=u.flatMap(e=>{let t=c.exec(e);return t?[{code:Number(t[1]),line:e}]:[]});if(p.length!==o.length)return;let m=d.slice(0,n+2).filter(e=>o.includes(e)).length-1;a.set(l,p[m])}),a):new Map,g=p.decisive.flatMap(e=>f.get(e)??[]),x=g.length>0&&g.length===p.decisive.length?g.find(({code:e})=>0!==e)??g[0]:null,v=x?0!==x.code?"failed":m?"unverified":"passed":l?o?"unverified":"failed":null===i?"unobserved":"carried"!==p.reach||m?"unverified":"passed",y="unobserved"===v?"interrupted"===n?"interrupted":r?"noExit":"noResult":"unverified"!==v?null:m?"optional":l&&o?"compound":s.uncertain?"syntax":"masked";return{stage:e,state:v,exitCode:i,labels:"check"===e?function(e){let t=[];for(let{words:n}of e){let e=iH(n);n.forEach((n,r)=>{if(r!==e||"test"!==n)for(let e of n.replace(/^-+/,"").toLowerCase().split(":")){let n=Object.hasOwn(i6,e)?i6[e]:void 0;n&&!t.includes(n)&&t.push(n)}})}return t}(p.decisive):[],...o?{compound:o}:{},...x?{evidence:x.line}:{},...y?{reason:y}:{}}})}function le(e,t){let n=i3(e),r=null===n?void 0:i9(n,t).find(e=>"check"===e.stage);return null!==n&&r?{toolCallId:e.toolCallId,command:n,state:r.state,exitCode:r.exitCode,labels:r.labels,...r.compound?{compound:r.compound}:{},...r.reason?{reason:r.reason}:{}}:null}let lt=/\.(?:md|mdx|markdown|txt)$/i,ln=/^docs?$/i;function lr(e){return lt.test(e)||e.split(/[\\/]/).slice(0,-1).some(e=>ln.test(e))}let ls={read:!0,grep:!0,glob:!0,find:!0,ls:!0,skim:!0,web_search:!0,fetch:!0,ast_grep:!0,lsp:!0,recall:!0,reflect:!0},la={multiedit:!0,notebookedit:!0,draft:!0},li={rename:!0,rename_file:!0},ll={passed:"done",failed:"failed",unverified:"unverified",unobserved:"unobserved"};function lo(e){return e.split("\n")[0].trim()||void 0}let lc=/^\[[^\]\n]*? ([0-9a-f]{7,40})\] (.+)$/m,ld=/^\s*\+?[0-9a-f]{7,40}\.{2,3}([0-9a-f]{7,40})\s+\S+\s+->\s+\S+/m;function lu(e){let t=e?.details;return t&&"object"==typeof t?"__synthetic"in t&&!0===t.__synthetic&&"executed"in t&&!1===t.executed?"notRun":"__interrupted"in t&&!0===t.__interrupted?"interrupted":null:null}let lh=/\btool\.git_(?:finalize|integrate)\s*\(/,lp=/\b(?:Committed|Integrated \S+) and pushed ([0-9a-f]{40})\b|\bcommitSha["']?\s*:\s*["']([0-9a-f]{40})["']/,lm=/\bgit_(?:finalize|integrate) failed\b|\bok["']?\s*:\s*false\b|\bstage["']?\s*:\s*["'](?!complete["'])[\w-]+["']/,lf=/\bstage["']?\s*:\s*["'](?:up-to-date|aborted)["']/,lg=/["']?\bmessage["']?\s*:\s*(["'`])((?:\\[\s\S]|(?!\1)[^\\])*)\1/;function lx(e,t){if("string"==typeof t.commitSha&&""!==t.commitSha.trim())return t.commitSha.trim();let n=lp.exec(lR(e));return n?.[1]??n?.[2]??null}let lv=/^bg_\d+$/;function ly(e){let t=e.details,n=t&&"object"==typeof t&&"async"in t?t.async:null;if(n&&"object"==typeof n&&"jobId"in n&&"string"==typeof n.jobId&&lv.test(n.jobId))return n.jobId;let r=lR(e).trimStart();return r.startsWith("Backgrounded")?/\bBackgrounded as job (bg_\d+)\b/.exec(r)?.[1]??null:null}function lb(e,t){let n=/Command exited with code (-?\d+)\s*$/.exec(t.trimEnd());return{jobId:e,text:t,exitCode:n?Number(n[1]):null}}function lw(e){return"passed"===e||"failed"===e||"done"===e}function lk(e){let t=null;for(let n of e.values())"failed"===n.outcome&&(!t||n.order>t.order)&&(t=n);return t?.stage??null}function lj(e){return e.commandKey??JSON.stringify([e.cwd??"",e.command])}function lS(e){let t=new Map;for(let n of e){if("check"!==n.stage)continue;let e=lj(n),r=t.get(e);(r?.outcome!=="failed"||lw(n.outcome))&&t.set(e,n)}return[...t.values()]}function lC(e){return"compound"in e&&e.compound?.failed===!0}let lN={failed:6,running:5,unverified:4,unobserved:3,stale:2,passed:1,done:0};function lT(e){return"stale"!==e&&(lw(e)||"running"===e)}function lI(e){if("ci"!==e.stage)return null;let t=iR(e.command).commands.flatMap(({words:e})=>lP(e)).map(e=>"run"===e[0]&&("watch"===e[1]||"view"===e[1])?lO(e):null);return t.length>0&&t.every(e=>null!==e)?t:null}let lM={"publish public mirror":!0,"publish-public.yml":!0,".github/workflows/publish-public.yml":!0},lE={ci:!0,"ci.yml":!0,".github/workflows/ci.yml":!0},l$=/^[0-9a-f]{40}$/i;function lR(e){let t=e.content;return"string"==typeof t?t:Array.isArray(t)?t.map(e=>e&&"object"==typeof e&&"text"in e&&"string"==typeof e.text?e.text:"").join("\n"):""}function lL(e){let t=[];for(let n of e.split("\n")){let e,r=n.trim();if(r.startsWith("{")||r.startsWith("[")){try{e=JSON.parse(r)}catch{continue}for(let n of Array.isArray(e)?e:[e])n&&"object"==typeof n&&!Array.isArray(n)&&t.push(n)}}return t}function lP(e,t=0){let n=iz(e);if(null!==n)return t<3?iR(n).commands.flatMap(e=>lP(e.words,t+1)):[];let r=iH(e);return r>=0&&"gh"===iL(e[r])?[e.slice(r+1)]:[]}function lA(e,t){for(let n=0;n<e.length;n+=1)for(let r of t){if(e[n]===r)return e[n+1]??null;if(r.startsWith("--")&&e[n].startsWith(`${r}=`))return e[n].slice(r.length+1)}return null}let l_={"-R":!0,"--repo":!0,"-j":!0,"--job":!0,"--interval":!0,"-i":!0,"--json":!0,"-q":!0,"--jq":!0,"-t":!0,"--template":!0};function lF(e){for(let t=2;t<e.length;t+=1){if(Object.hasOwn(l_,e[t])){t+=1;continue}if(!e[t].startsWith("-"))return e[t]}return null}function lO(e){let t=lF(e);return null!==t&&/^\d+$/.test(t)?t:null}let lz=/^https:\/\/github\.com\/([^/\s]+\/[^/\s]+)\/actions\/runs\/\d+/i;function lD(e,t){if(!t||t.isError||!/\bgh\b/.test(e)||0!==ra(t))return[];let n=iR(e).commands.flatMap(({words:e})=>lP(e)).filter(e=>"run"===e[0]&&("list"===e[1]||"view"===e[1]));if(0===n.length)return[];let r=1===n.length?n[0]:null,s=r?.[1]==="list"?lA(r,["-c","--commit"])?.toLowerCase():void 0,a=s&&/^[0-9a-f]{7,40}$/.test(s)?s:null,i=lR(t);return a||i.includes("headSha")?lL(i).flatMap(e=>{let t="string"==typeof e.headSha?e.headSha.toLowerCase():a;if(null===t)return[];let n="string"==typeof e.url?lz.exec(e.url)?.[1]??null:null;return[{id:"number"==typeof e.databaseId||"string"==typeof e.databaseId?String(e.databaseId):r?.[1]==="view"?lO(r):null,repo:(n??(r?lA(r,["-R","--repo"]):null))?.toLowerCase()??null,sha:t,status:e.status,conclusion:e.conclusion,branch:"string"==typeof e.headBranch?e.headBranch:r?lA(r,["-b","--branch"]):null,workflow:("string"==typeof e.workflowName?e.workflowName:"string"==typeof e.name&&"databaseId"in e?e.name:r?lA(r,["-w","--workflow"]):null)?.toLowerCase()??null,title:"string"==typeof e.displayTitle?e.displayTitle:null}]}):[]}let lW=/\b\d{9,12}\b/g,lH=/\b(?=[0-9a-f]*[a-f])[0-9a-f]{7,40}\b/;function lU(e,t){if(e?.type!=="toolCall")return[];let n=i3(e);return null===n?[]:lD(n,t).flatMap(e=>e.repo&&e.sha&&e.branch&&e.workflow&&"completed"===e.status&&"success"===e.conclusion&&Object.hasOwn(lE,e.workflow)?[{repo:e.repo,sha:e.sha,branch:e.branch,workflow:e.workflow}]:[])}let lB="Public tree already matches; nothing to publish";function lq(e){let t=null===e?null:/^\$(?:\{([A-Za-z_]\w*)\}|([A-Za-z_]\w*))$/.exec(e);return t?t[1]??t[2]:null}function lV(e){let t="run"===e[0]&&"list"===e[1]?lA(e,["-w","--workflow"])?.toLowerCase():void 0;return void 0!==t&&Object.hasOwn(lM,t)}function lK(e,t){let n=new Map,r=[];for(let{words:s}of iR(e).commands){let e=s.map(e=>/^([A-Za-z_]\w*)=([\s\S]*)$/.exec(e));if(s.length>0&&e.every(e=>null!==e)){for(let t of e){if(!t)continue;let e=/^\$\(([\s\S]*)\)$/.exec(t[2])?.[1],r=void 0===e?[]:iR(e).commands.flatMap(e=>lP(e.words));n.set(t[1],1===r.length&&lV(r[0]))}continue}for(let e of lP(s)){if(lV(e)){r.push({args:e,publish:!0});continue}let s="run"===e[0]&&("watch"===e[1]||"view"===e[1])?lF(e):null,a=lq(s),i=null!==a?!0===n.get(a):null!==s&&/^\d+$/.test(s)&&t(s);r.push({args:e,publish:i})}}return r}function lJ(e,t){let n=lK(e,t);return n.length>0&&n.every(({publish:e})=>e)}function lG(e,t){if(!e||!t)return!1;let[n,r]=e.length<=t.length?[e.toLowerCase(),t.toLowerCase()]:[t.toLowerCase(),e.toLowerCase()];return n.length>=7&&/^[0-9a-f]+$/.test(r)&&r.startsWith(n)}function lY(e,t,n){if(lG(e.sha,t.step.commit))return!0;let{title:r}=t.step;return!!r&&!!e.title&&!!e.repo&&!(e.order<=t.order)&&!!e.workflow&&!!Object.hasOwn(lE,e.workflow)&&[...n.publishRuns.values()].some(n=>n.order>t.order&&null!==n.sha&&lG(n.sha,t.step.commit)&&null!==n.repo&&n.repo!==e.repo)&&function(e,t){if(e===t)return!0;let n=e.endsWith("…")?e.slice(0,-1):null;return null!==n&&n.length>=20&&t.startsWith(n)}(e.title,r)}let lZ={failure:!0,cancelled:!0,timed_out:!0,startup_failure:!0},lQ=/^(\d{4}-\d\d-\d\dT\d\d:\d\d:\d\dZ) READY ([0-9a-f]{7,40})\b/,lX=/^(\d{4}-\d\d-\d\dT\d\d:\d\d:\d\dZ) (ROLLED_BACK|ROLLBACK_FAILED|FAIL)\b/,l0=/^(\d{4}-\d\d-\d\dT\d\d:\d\d:\d\dZ) START old=\S* target=([0-9a-f]{7,40})\b/;function l1(e,t,n=!1,r=[],s,a=[]){let i,l,o=[],c=[],d=1,u=new Map,h=-1,p=-1,m=new Map,f={publishRuns:new Map,watched:[],heads:[],ciHeads:[],nothingToPublish:[],runs:[]},g=Array.isArray(e)?e:[],x=t instanceof Map?t:new Map,v=function(e,t,n=[]){let r=new Map,s=new Map,a=new Map;for(let e of n)null!==e.after&&a.set(e.after,[...a.get(e.after)??[],e]);let i=(e,t)=>{for(let n of e){let e=s.get(n.jobId);e&&(s.delete(n.jobId),r.set(e.toolCallId,{...e.result,isError:!1,content:[{type:"text",text:n.text}],details:{...null===n.exitCode?{}:{exitCode:n.exitCode},backgroundJob:{jobId:n.jobId,after:t}}}))}};for(let n of Array.isArray(e)?e:[]){if(!n||"toolCall"!==n.type)continue;let e=t.get(n.toolCallId);if(e){let t="bash"===n.toolName||"eval"===n.toolName?ly(e):null;t?s.set(t,{toolCallId:n.toolCallId,result:e}):r.set(n.toolCallId,e),"wait"===n.toolName&&i(function(e){let t=e.details,n=t&&"object"==typeof t&&"jobs"in t?t.jobs:null,r=(Array.isArray(n)?n:[]).flatMap(e=>{if(!e||"object"!=typeof e||!("id"in e)||!("status"in e)||!("resultText"in e)||"string"!=typeof e.id||!lv.test(e.id)||"completed"!==e.status&&"failed"!==e.status||"string"!=typeof e.resultText)return[];let t="exitCode"in e&&"number"==typeof e.exitCode?e.exitCode:null;return[{...lb(e.id,e.resultText),...null===t?{}:{exitCode:t}}]});if(r.length>0)return r;let s=lR(e),a=[...s.matchAll(/^### (bg_\d+) \[\w+\] — (?:completed|failed)$/gm)];return a.map((e,t)=>{let n=(e.index??0)+e[0].length,r=s.slice(n,t+1<a.length?a[t+1].index:s.length),i=r.indexOf("\n```\n"),l=r.lastIndexOf("\n```");return lb(e[1],i>=0&&l>i?r.slice(i+5,l):"")})}(e),n.toolCallId);let a="read"===n.toolName?function(e,t){let n=e.input.path,r="string"==typeof n?/^proc:\/\/(bg_\d+)$/.exec(n)?.[1]:void 0;if(!r)return null;let[s,...a]=lR(t).split("\n");return RegExp(`^1\\|${r} \\[\\w+\\] — (?:completed|failed)\\b`).test(s)?lb(r,a.map(e=>e.replace(/^\d+\|/,"")).join("\n")):null}(n,e):null;a&&i([a],n.toolCallId)}for(let e of a.get(n.toolCallId)??[])i(function(e){let t=e.replace(/^\s*<system-notice>\s*\n?/,"").replace(/\s*<\/system-notice>\s*$/,""),n=/^Background job (bg_\d+) has (?:completed|failed)\b[^\n]*(?:\n|$)/.exec(t);if(n)return[lb(n[1],t.slice(n[0].length))];let r=[...t.matchAll(/^── Job (\S+) .*──$/gm)];return r.flatMap((e,n)=>{if(!lv.test(e[1]))return[];let s=(e.index??0)+e[0].length;return[lb(e[1],t.slice(s,n+1<r.length?r[n+1].index:t.length).replace(/^\n/,""))]})}(e.text),n.toolCallId)}return r}(g,x,Array.isArray(a)?a:[]),y=[];g.forEach((e,t)=>{let r;if(!e||"toolCall"!==e.type)return;let a=v.get(e.toolCallId);for(let i of(!function(e,t,n,r){let s=i3(t);if(null===s||!s.includes("gh"))return;let a=(t,n)=>{let s=e.publishRuns.get(t);s&&(null===n.sha||null!==s.sha)||e.publishRuns.set(t,{...n,order:s?.order??r})};for(let t of lD(s,n))e.runs.push({...t,order:r}),t.id&&t.sha&&t.workflow&&Object.hasOwn(lM,t.workflow)&&a(t.id,{sha:t.sha,repo:t.repo});for(let e of function(e,t){if(!t||t.isError||0!==ra(t))return[];let n=iR(e).commands.flatMap(({words:e})=>lP(e)).filter(e=>"run"===e[0]&&"list"===e[1]);if(1!==n.length)return[];let r=lA(n[0],["-w","--workflow"])?.toLowerCase(),s=void 0!==r&&Object.hasOwn(lM,r),a=lA(n[0],["-R","--repo"])?.toLowerCase()??null;return lR(t).split("\n").flatMap(e=>{let t=e.trim();if(t.startsWith("{")||t.startsWith("["))return[];let n=t.toLowerCase();if(!s&&!Object.keys(lM).some(e=>n.includes(e)))return[];let r=t.match(lW)??[];return 1===r.length?[{id:r[0],sha:lH.exec(n)?.[0]??null,repo:a}]:[]})}(s,n))a(e.id,e);for(let s of lU(t,n))e.ciHeads.push({...s,order:r});for(let t of function(e,t){let n=iR(e),r=n.commands.flatMap(({words:e})=>lP(e)).filter(e=>"api"===e[0]),s=!n.uncertain&&1===n.commands.length&&1===r.length,a=t&&!t.isError&&0===ra(t)?lR(t).trim():"",i=[];for(let e of r){let t=e.slice(1).find(e=>/^\/?repos\//.test(e)),n=t?/^\/?repos\/([^/]+\/[^/]+)\/commits\/([^/?\s]+)$/.exec(t):null;if(!n)continue;let r=lA(e,["-q","--jq"]),l=null;if(s&&".sha"===r)l=a.split("\n")[0]?.trim();else if(s&&null===r&&a.startsWith("{"))try{l=JSON.parse(a.slice(0,a.lastIndexOf("}")+1)).sha}catch{}let o="string"==typeof l&&l$.test(l)?l.toLowerCase():null;i.push({repo:n[1].toLowerCase(),ref:n[2],sha:o})}return i}(s,n))e.heads.push({...t,order:r});let i=function(e,t){if(!t||t.isError||0!==ra(t)||2!==e.split(lB).length)return null;let{lists:n}=iR(e),r=0;for(;r<n.length&&["set","cd"].includes(iV(n[r])?.words[0]??"");)r+=1;let s=r<n.length-1?function(e){let t=iV(e)?.words,n=t?.length===1?/^([A-Za-z_]\w*)=\$\(([\s\S]*)\)$/.exec(t[0]):null;if(!n)return null;let r=iR(n[2]),s=1===r.lists.length?iV(r.lists[0]):null,a=s?.words[0]==="gh"?lP(s.words):[];if(1!==a.length||"run"!==a[0][0]||"list"!==a[0][1])return null;let i=lA(a[0],["-c","--commit"]),l=lA(a[0],["-w","--workflow"])?.toLowerCase();return i&&l$.test(i)&&l&&Object.hasOwn(lM,l)?{name:n[1],sha:i.toLowerCase()}:null}(n[r]):null;return s&&function(e,t){if(e.background||1!==e.pipelines.length)return!1;let[n]=e.pipelines,[r,s,...a]=n.commands;if(n.negated||!s||a.length>1||"gh"!==r.words[0])return!1;let i=lP(r.words);if(1!==i.length||"run"!==i[0][0]||"view"!==i[0][1]||!i[0].includes("--log"))return!1;let l=lF(i[0]);if(lq(l)!==t)return!1;for(let e=2;e<i[0].length;e+=1){let t=i[0][e];if("-R"===t||"--repo"===t)e+=1;else if(t!==l&&"--log"!==t&&!t.startsWith("--repo=")&&!/^2>/.test(t))return!1}let[o,...c]=s.words,d=c.filter(e=>e.startsWith("-")),u=c.filter(e=>!e.startsWith("-"));if("grep"!==o||!d.every(e=>/^-[oFas]+$/.test(e))||!d.some(e=>e.includes("o"))||1!==u.length||u[0]!==lB)return!1;let[h]=a;return!h||("head"===h.words[0]||"tail"===h.words[0])&&h.words.slice(1).every(e=>/^(?:-n?\d*|\d+)$/.test(e))}(n[n.length-1],s.name)&&n.slice(r+1,-1).flatMap(e=>e.pipelines.flatMap(({commands:e})=>e)).every(({words:e})=>(function(e,t){let[n,...r]=e;if("["===n||"[["===n||"test"===n||"exit"===n||"true"===n||":"===n||"sleep"===n)return!0;if("echo"===n||"printf"===n)return r.every(e=>!/`|\$\(/.test(e)&&!/public|tree|already|matches|nothing|publish/i.test(e)&&[...e.matchAll(/\$\{?([A-Za-z_]\w*|[?])/g)].every(e=>e[1]===t||"?"===e[1]));if("gh"!==n)return!1;let s=lP(e);return 1===s.length&&"run"===s[0][0]&&"watch"===s[0][1]&&lq(lF(s[0]))===t})(e,s.name))&&lR(t).split("\n").some(e=>e.trim()===lB)?s.sha:null}(s,n);i&&e.nothingToPublish.push({sha:i,order:r})}(f,e,a,t),Array.isArray(r=function(e,t,n,r){if(!e.input||"object"!=typeof e.input||Array.isArray(e.input)||"string"!=typeof e.toolName)return null;let s=lu(t);if("notRun"===s)return null;let a={toolCallId:e.toolCallId,attempt:0},i=n&&!s?"running":"unobserved",l=i3(e);if(null!==l){var o;let n,s,c=(o=t,(s=(n=o?.details)&&"object"==typeof n&&"backgroundJob"in n?n.backgroundJob:null)&&"object"==typeof s&&"jobId"in s&&"after"in s&&"string"==typeof s.jobId&&"string"==typeof s.after?{jobId:s.jobId,after:s.after}:null);return i9(l,t).map(n=>{var s,o,d,u;let h,p;if("commit"===n.stage){let e,r,o=t?"unobserved"===n.state&&function(e,t){if(t.isError)return!1;let{commands:n}=iR(e),r=lR(t),s=e=>n.some(({words:t})=>i4(t,0,e));return(!s("commit")||lc.test(r))&&(!s("push")||ld.test(r))}(l,t)?"done":ll[n.state]:i;return{...a,stage:"commit",..."done"===o?(e=(s=t)?lR(s):"",(r=lc.exec(e))?{commit:r[1],title:r[2].trim()}:{commit:ld.exec(e)?.[1]??null}):{commit:null},docsOnly:!1,outcome:o}}let m=n.evidence??(c&&null!==n.exitCode?`Command exited with code ${n.exitCode}`:void 0),f=m&&c?`${c.jobId} \xb7 ${m}`:m,g="ci"===n.stage&&"failed"===n.state&&t?function(e,t){let n=iR(e).commands.flatMap(({words:e})=>lP(e)),r=n.find(e=>"run"===e[0]&&"watch"===e[1]&&e.includes("--exit-status")),s=r?lF(r):null;if(null===s||!n.some(e=>"run"===e[0]&&"view"===e[1]&&e.includes("--json")&&lF(e)===s))return null;let a=lL(lR(t)).filter(e=>"completed"===e.status&&"string"==typeof e.conclusion),i=1===a.length?a[0].conclusion:null;return"string"!=typeof i||""===i||"success"===i||Object.hasOwn(lZ,i)?null:i}(l,t):null,x=g?"unverified":t?n.state:i,v="check"===n.stage&&x===n.state?n.reason:void 0;return{...a,stage:n.stage,command:l,..."check"===n.stage?{cwd:(o=e.input,d=r,u=e.toolCallId,h=d?tC(d)??d:void 0,(p="string"==typeof o.cwd?o.cwd:"")?tC(p,h)??(h?tC(`${h.replace(/\/+$/,"")}/${p}`):null)??`?${u}`:h??"")}:{},exitCode:n.exitCode,labels:n.labels,outcome:x,...n.compound?{compound:n.compound}:{},...f?{evidence:g?`${f} \xb7 ${g}`:f}:{},...g?{otherRun:{kind:"unjudged",conclusion:g}}:{},...v?{reason:v}:{}}})}let c=e.toolName.toLowerCase().split(/[.:/]/).pop()??"",d=s?void 0:t,u=d?.details&&"object"==typeof d.details?d.details:{};if("cross_review"===c){let t="resolve"===e.input.action?"resolve":"review";if(!d||d.isError)return{...a,stage:"review",action:t,findings:null,outcome:d?"failed":i};if("resolve"===t){if(!0===u.pass)return{...a,stage:"review",action:t,findings:0,outcome:"passed"};let e=Array.isArray(u.open)?u.open.length:null;return{...a,stage:"review",action:t,findings:e,outcome:!1===u.pass?"failed":"unobserved"}}let n=Array.isArray(u.findings)?u.findings.length:null;if(null!==n&&n>0)return{...a,stage:"review",action:t,findings:n,outcome:"failed"};let r=Array.isArray(u.reviewers)?u.reviewers:[];return!1===u.passable||r.some(e=>!e||"object"!=typeof e||!("status"in e)||"ok"!==e.status)?{...a,stage:"review",action:t,findings:n,outcome:"unverified",unusable:!0}:{...a,stage:"review",action:t,findings:n,outcome:null===n?"unobserved":"done"}}if("git_finalize"===c){let t="string"==typeof e.input.message?lo(e.input.message):void 0,n=t?{title:t}:{};if(!d)return{...a,stage:"commit",commit:null,docsOnly:!1,...n,outcome:i};let r=lx(d,u),s=d.isError||!1===u.ok,l=!s&&(!0===u.ok||null!==r),o=e.input.files,c=l&&Array.isArray(o)&&o.length>0&&o.every(e=>"string"==typeof e&&lr(e));return{...a,stage:"commit",commit:l?r:null,docsOnly:c,...n,outcome:l?"done":s?"failed":"unobserved"}}if("git_integrate"===c){if("abort"===e.input.action||"up-to-date"===u.stage)return null;if(!d)return{...a,stage:"commit",commit:null,docsOnly:!1,outcome:i};let t=lx(d,u),n=d.isError||!1===u.ok,r=!n&&null!==t,s=u.files,l=r&&Array.isArray(s)&&s.length>0&&s.every(e=>"string"==typeof e&&lr(e));return{...a,stage:"commit",commit:r?t:null,docsOnly:l,outcome:r?"done":n?"failed":"unobserved"}}if("eval"===c)return function(e,t,n){let r=function(e){if("string"==typeof e.code)return e.code;let t=e.cells;return Array.isArray(t)?t.map(e=>e&&"object"==typeof e&&"code"in e&&"string"==typeof e.code?e.code:"").join("\n"):""}(e.input);if(!lh.test(r))return null;let s=lg.exec(r)?.[2],a=void 0===s?void 0:lo(s.replace(/\\n/g,"\n").replace(/\\(["'`\\])/g,"$1")),i={toolCallId:e.toolCallId,attempt:0,stage:"commit",docsOnly:!1,...a?{title:a}:{}};if(!t)return{...i,commit:null,outcome:n};let l=lR(t),o=lp.exec(l),c=o?(o[1]??o[2]).toLowerCase():null;if(!c&&lf.test(l))return null;let d=lm.test(l);return c&&!d?{...i,commit:c,outcome:"done"}:{...i,commit:null,outcome:!c&&(d||t.isError)?"failed":"unobserved"}}(e,d,i);if(function(e,t){if("task"===t||Object.hasOwn(la,t))return!0;if("lsp"===t)return"string"==typeof e.input.action&&Object.hasOwn(li,e.input.action);if(!tN(e.toolName)&&!tT(e.toolName))return!1;let n=e.input.file_path??e.input.path;return"string"!=typeof n||/^[a-zA-Z]:[\\/]/.test(n)||!/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//.test(n)}(e,c))return!s&&t?.isError?null:(tN(e.toolName)||tT(e.toolName))&&tR(e.input,d,r)?{...a,stage:"investigate",outcome:s?"unobserved":t||!n?"done":"running"}:{...a,stage:"edit",outcome:d?"done":i,..."task"===c?{dispatch:!0}:{},...!function(e,t,n){if(!t||!(tN(e.toolName)||tT(e.toolName)))return!1;let r=t$(e.input,t);return r.length>0&&r.every(e=>(function(e,t){if(e.split(/[\\/]/).includes(".."))return!1;let n=t?tC(t)??t:void 0,r=tJ(tC(e,t)??e,n);if(/^[\\/]/.test(r)||/^[a-zA-Z]:[\\/]/.test(r))return!1;let s=r.split(/[\\/]/).filter(e=>""!==e&&"."!==e);return"HANDOFF.md"===s.at(-1)||"doc"===s[0]&&"history"===s[1]&&s.length>2})(e,n))}(e,d,r)?{}:{recordOnly:!0}};return Object.hasOwn(ls,c)?{...a,stage:"investigate",outcome:s?"unobserved":t||!n?"done":"running"}:null}(e,a,n,s))?r:r?[r]:[])){let n=a?void 0:x.get(e.toolCallId);"check"===i.stage&&"noResult"===i.reason&&n&&ly(n)&&(i.reason="noCompletion"),y.push({step:i,order:t})}}),i=null,l=!1,y.forEach((e,t)=>{let{step:n,order:r}=e;if("commit"===n.stage&&"done"===n.outcome&&n.commit&&(i={step:{...n,commit:n.commit},order:r},l=!1),"edit"!==n.stage||"done"!==n.outcome||n.dispatch||n.recordOnly||(l=!0),"ci"!==n.stage||!i)return;let s=i,a=iR(n.command).commands.flatMap(({words:e})=>lP(e)).find(e=>"run"===e[0]&&"watch"===e[1]);if(a){let e,i=lO(a),o=e=>(f.publishRuns.get(e)?.order??1/0)<=r;if((e=lK(n.command,o).filter(({args:e})=>"run"===e[0]&&"watch"===e[1])).length>0&&e.every(({publish:e})=>e)){lJ(n.command,o)||"passed"!==n.outcome&&"failed"!==n.outcome||(i&&"passed"===n.outcome&&f.watched.push({id:i,order:r}),y[t]={order:r,step:{...n,outcome:"unverified",evidence:void 0,otherRun:{kind:"publish",outcome:n.outcome}}});return}let c=i?f.runs.filter(e=>e.id===i):[],d=c.find(e=>null!==e.sha)?.sha;if(!d||c.some(e=>lY(e,s,f))){d&&l&&"passed"===n.outcome&&(y[t]={order:r,step:{...n,stale:!0}});return}if("passed"===n.outcome||"failed"===n.outcome){let e=d.slice(0,7);y[t]={order:r,step:{...n,outcome:"unverified",evidence:`run ${i} \xb7 ${e}`,otherRun:{kind:"commit",sha:e,outcome:n.outcome}}}}return}if("unverified"!==n.outcome)return;let o=f.runs.find(e=>e.order===r&&null!==e.workflow&&Object.hasOwn(lE,e.workflow)&&lY(e,s,f));if(!o||"completed"!==o.status||"string"!=typeof o.conclusion)return;let c="success"===o.conclusion?"passed":Object.hasOwn(lZ,o.conclusion)?"failed":null;c&&(y[t]={order:r,step:{...n,outcome:c,evidence:`run ${o.id??"?"} \xb7 ${o.status} ${o.conclusion}`,..."passed"===c&&l?{stale:!0}:{}}})}),y.forEach((e,t)=>{let{step:n,order:r}=e;if("deploy"!==n.stage||"unverified"!==n.outcome&&"unobserved"!==n.outcome)return;let s=function(e){let t=[],n=(e,r)=>{let s=iz(e);if(null!==s){if(r<3)for(let e of iR(s).commands)n(e.words,r+1);return}if(!iB(e))return;let a=iH(e),i=iU.test(e[a])?a:e.findIndex((e,t)=>t>a&&!e.startsWith("-")),l=e[i+1];t.push(void 0!==l&&/^[0-9a-f]{7,40}$/i.test(l)?l.toLowerCase():null)};for(let{words:t}of iR(e).commands)n(t,0);return 1===t.length?t[0]:null}(n.command),a=x.get(n.toolCallId);if("number"!=typeof a?.timestamp)return;let i=a.details,l=i&&"object"==typeof i&&"wallTimeMs"in i&&"number"==typeof i.wallTimeMs?i.wallTimeMs:0,o=1e3*Math.floor((a.timestamp-l)/1e3);for(let e=r;e<g.length;e+=1){let a=g[e],i=a?.type==="toolCall"?v.get(a.toolCallId):void 0;if(i)for(let e of lR(i).split("\n")){let a=e.trim().replace(/^\d+[:-](?=\d{4}-\d\d-\d\dT)/,"");if(null===s){let e=l0.exec(a);e&&Date.parse(e[1])>=o&&(s=e[2]);continue}let i=lQ.exec(a);if(i&&Date.parse(i[1])>=o&&lG(i[2],s)){y[t]={order:r,step:{...n,outcome:"passed",evidence:`${i[1]} READY ${i[2].slice(0,12)}`}};return}let l=lX.exec(a);if(l&&Date.parse(l[1])>=o){y[t]={order:r,step:{...n,outcome:"failed",evidence:a.length>120?`${a.slice(0,119)}…`:a}};return}}}});let b=(e,t)=>null!==e&&(f.publishRuns.get(e)?.order??1/0)<=t;for(let{step:e,order:t}of y){let n=e;if("ci"===n.stage){let e=iR(n.command).commands.flatMap(({words:e})=>lP(e)).find(e=>"run"===e[0]&&"watch"===e[1]),r=e?lO(e):null;r&&"passed"===n.outcome&&f.watched.push({id:r,order:t}),!n.compound&&lJ(n.command,e=>b(e,t))&&(n={toolCallId:n.toolCallId,attempt:n.attempt,stage:"investigate",outcome:"passed"===n.outcome||"unverified"===n.outcome?"done":n.outcome})}if("edit"!==n.stage||"done"!==n.outcome||n.dispatch){if("check"===n.stage||"review"===n.stage||"ci"===n.stage){let e="check"===n.stage?`check:${lj(n)}`:n.stage,t=u.get(e);(t?.outcome!=="failed"||lw(n.outcome))&&u.set(e,{stage:n.stage,outcome:n.outcome,order:o.length})}}else{let e=lk(u);e&&(c.push({from:e,attempt:d}),d+=1),u=new Map,h=o.length,n.recordOnly||(p=o.length)}n.attempt=d,m.set(n,t),o.push(n)}let w=!1;o.forEach((e,t)=>{t<("commit"===e.stage||w&&("ci"===e.stage||"deploy"===e.stage)?p:h)&&"investigate"!==e.stage&&"edit"!==e.stage&&("passed"===e.outcome||"done"===e.outcome)&&(e.stale=!0),"commit"===e.stage&&"done"===e.outcome&&(w=!0)});let k=o.filter(e=>"commit"===e.stage&&"done"===e.outcome&&e.attempt===d).at(-1),j=k?m.get(k)??-1:-1,S=k&&!k.stale&&k.commit&&l$.test(k.commit)?{sha:k.commit.toLowerCase(),order:j}:null,C=S?function(e,t,n){let r=e.watched.find(({id:n,order:r})=>{let s=e.publishRuns.get(n);return r>t.order&&s?.sha===t.sha&&s.order>t.order&&s.order<=r});if(!r)return null;let s=new Map;for(let t of e.heads)t.order>r.order&&s.set(`${t.repo}#${t.ref}`,t);let a=[...n,...e.ciHeads.filter(e=>e.order<t.order)];for(let e of s.values())if(null!==e.sha&&e.sha!==t.sha&&a.some(t=>t.repo===e.repo&&t.sha===e.sha&&t.branch===e.ref))return{kind:"publicHeadUnchanged",repo:e.repo,ref:e.ref,sha:e.sha,runId:r.id};return null}(f,S,r)??(f.nothingToPublish.some(({sha:e,order:t})=>e===S.sha&&t>S.order)?{kind:"nothingToPublish",commit:S.sha}:null):null;if(C?.kind==="nothingToPublish"){let e=C.commit;o.forEach((t,n)=>{var r;let s,a=m.get(t)??-1;if("ci"!==t.stage||"unverified"!==t.outcome||a<=j||!f.nothingToPublish.some(t=>t.order===a&&t.sha===e)&&(r=t.command,!((s=iR(r).commands.flatMap(({words:e})=>lP(e))).length>0&&s.every(t=>"run"===t[0]&&"list"===t[1]&&lA(t,["-c","--commit"])?.toLowerCase()===e))))return;let i={toolCallId:t.toolCallId,attempt:t.attempt,stage:"investigate",outcome:"done"};o[n]=i,m.set(i,a)})}let N=iI.map(e=>{let t=o.filter(t=>t.stage===e),n="investigate"===e?t:t.filter(e=>e.attempt===d);return{stage:e,status:function(e,t){if(0===t.length)return"waiting";if("check"!==e){let e=new Set,n=null;for(let r of t){let t=r.stale?"stale":r.outcome;if("failed"!==n||lw(r.outcome)){if(null!==n&&!("ci"!==r.stage||lT(t))&&!iR(r.command).commands.some(({words:e})=>lP(e).some(e=>"run"===e[0]&&"watch"===e[1]&&e.includes("--exit-status")))){let t="stale"===n&&(lI(r)?.every(t=>e.has(t))??!1);if(lT(n)||t)continue}if(n=t,"stale"===t||"passed"===r.outcome||"failed"===r.outcome)for(let t of lI(r)??[])e.add(t)}}return n??"waiting"}let n="done";for(let e of lS(t)){let t=e.stale?"stale":e.outcome;lN[t]>lN[n]&&(n=t)}return n}(e,n),steps:n,earlier:"investigate"===e?[]:t.filter(e=>e.attempt<d)}}),T=N[iI.indexOf("deploy")],I=o.some(e=>"commit"===e.stage&&"done"===e.outcome&&!e.docsOnly);!k?.docsOnly||k.stale||I||"waiting"!==T.status||(T.status="notNeeded");let M=N[iI.indexOf("ci")],E=M.steps.some(e=>(m.get(e)??1/0)>j);C&&("waiting"===M.status||("unverified"===M.status||"stale"===M.status)&&!E)?M.status="notNeeded":C=null;let $=-1;N.forEach((e,t)=>{"waiting"!==e.status&&"failed"!==e.status&&"skipped"!==e.status&&"notNeeded"!==e.status&&"stale"!==e.status&&e.steps.some(e=>!e.stale&&"failed"!==e.outcome&&!lC(e))&&($=t)});let R=null;if(n&&o.length>0)if(lk(u))R={stage:"edit",returning:!0};else if($<0)R={stage:N.find(e=>"waiting"!==e.status)?.stage??iI[0],returning:!1};else{let e=N[$].steps.at(-1);if(e?.stage==="review"&&e.unusable)R={stage:"review",returning:!1};else{let e=N.slice($+1).find(e=>"skipped"!==e.status&&"notNeeded"!==e.status);R=e?{stage:e.stage,returning:!1}:null}}if(N.forEach((e,t)=>{t<$&&"waiting"===e.status&&(e.status="skipped")}),!n&&o.length>0){let e=!I;for(let t of N)"waiting"===t.status&&(t.status=e&&("ci"===t.stage||"deploy"===t.stage)?"notNeeded":"skipped")}return{steps:o,attempt:d,loops:c,stages:N,current:function(e,t,n){let r=e.at(-1);if(!r)return null;if(!n||n.stale)return r.stage;let s=t.filter(e=>("commit"===e.stage||"ci"===e.stage||"deploy"===e.stage)&&e.steps.length>0&&"notNeeded"!==e.status&&"skipped"!==e.status),a=s.find(e=>"commit"!==e.stage&&Object.hasOwn(l2,e.status));return a?.stage??s.at(-1)?.stage??r.stage}(o,N,k),reached:$<0?null:iI[$],next:R,publication:C}}let l2={running:!0,unobserved:!0,unverified:!0,failed:!0,stale:!0},l4="끊기기 전에 바깥에 영향을 주는 행동(커밋\xb7push, `git_finalize`\xb7`git_integrate`, 배포\xb7`update.sh`, CI 재실행, 이슈\xb7PR 댓글, 메시지 전송)을 하던 중이었다면 다시 하기 전에 그 결과가 이미 반영됐는지 `git log`\xb7`git status`\xb7원격 브랜치, `gh run list`, 배포 로그, 해당 페이지로 먼저 확인하고, 반영됐으면 되풀이하지 않는다. ",l8="[자동 재개] CUELO 업데이트\xb7재시작 때문에 이 세션의 진행 중 작업이 중단(abort)됐다. 서버가 새 버전으로 다시 떴다. 중단 직전에 돌던 명령\xb7도구 결과는 사라졌을 수 있으니 파일\xb7프로세스 상태를 먼저 확인하고, 하던 작업을 이어서 진행한다. "+l4+"그때 돌던 SubAgent(task child)도 멈췄지만 기록은 남아 있다. 결과를 받지 못한 child에는 먼저 `write agent://<id>`로 이어서 하라고 보내 되살리고, 되살아나지 않으면(isolated 작업 공간 등) 남은 파일 상태를 확인한 뒤 새로 맡긴다.",l5="[자동 재개] CUELO 서버가 예기치 않게 종료돼 이 세션의 진행 중 작업이 중간에 끊겼다. 서버가 다시 떴다. 끊기기 직전에 돌던 명령\xb7도구 결과는 사라졌을 수 있다. 그 명령을 그대로 다시 실행하지 말고, 파일\xb7프로세스 상태를 먼저 확인한 뒤 하던 작업을 이어서 진행한다. "+l4+"그때 돌던 SubAgent(task child)도 멈췄지만 기록은 남아 있다. 결과를 받지 못한 child에는 먼저 `write agent://<id>`로 이어서 하라고 보내 되살리고, 되살아나지 않으면 남은 파일 상태를 확인한 뒤 새로 맡긴다.",l6="[자동 재개] CUELO 업데이트의 세션 정지 단계가 이 세션의 진행 중 작업을 중단(abort)했지만, 업데이트가 실패해 기존 서버가 그대로 돌고 있다(새 버전으로 바뀌지 않았다). 중단 직전에 돌던 명령\xb7도구 결과는 사라졌을 수 있으니 파일\xb7프로세스 상태를 먼저 확인하고, 하던 작업을 이어서 진행한다. "+l4+"그때 돌던 SubAgent(task child)도 멈췄지만 기록은 남아 있다. 결과를 받지 못한 child에는 먼저 `write agent://<id>`로 이어서 하라고 보내 되살리고, 되살아나지 않으면(isolated 작업 공간 등) 남은 파일 상태를 확인한 뒤 새로 맡긴다.",l3=new Set(["[자동 재개] CUELO 업데이트\xb7재시작 때문에 이 세션의 진행 중 작업이 중단(abort)됐다. 서버가 새 버전으로 다시 떴다. 중단 직전에 돌던 명령\xb7도구 결과는 사라졌을 수 있으니 파일\xb7프로세스 상태를 먼저 확인하고, 하던 작업을 이어서 진행한다. 그때 돌던 SubAgent(task child)도 멈췄지만 기록은 남아 있다. 결과를 받지 못한 child에는 먼저 `write agent://<id>`로 이어서 하라고 보내 되살리고, 되살아나지 않으면(isolated 작업 공간 등) 남은 파일 상태를 확인한 뒤 새로 맡긴다.","[자동 재개] CUELO 서버가 예기치 않게 종료돼 이 세션의 진행 중 작업이 중간에 끊겼다. 서버가 다시 떴다. 끊기기 직전에 돌던 명령\xb7도구 결과는 사라졌을 수 있다. 그 명령을 그대로 다시 실행하지 말고, 파일\xb7프로세스 상태를 먼저 확인한 뒤 하던 작업을 이어서 진행한다. 그때 돌던 SubAgent(task child)도 멈췄지만 기록은 남아 있다. 결과를 받지 못한 child에는 먼저 `write agent://<id>`로 이어서 하라고 보내 되살리고, 되살아나지 않으면 남은 파일 상태를 확인한 뒤 새로 맡긴다.","[자동 재개] CUELO 업데이트의 세션 정지 단계가 이 세션의 진행 중 작업을 중단(abort)했지만, 업데이트가 실패해 기존 서버가 그대로 돌고 있다(새 버전으로 바뀌지 않았다). 중단 직전에 돌던 명령\xb7도구 결과는 사라졌을 수 있으니 파일\xb7프로세스 상태를 먼저 확인하고, 하던 작업을 이어서 진행한다. 그때 돌던 SubAgent(task child)도 멈췄지만 기록은 남아 있다. 결과를 받지 못한 child에는 먼저 `write agent://<id>`로 이어서 하라고 보내 되살리고, 되살아나지 않으면(isolated 작업 공간 등) 남은 파일 상태를 확인한 뒤 새로 맡긴다."]),l7={sending:!0,accepted:!0,delivered:!1,unconfirmed:!1,failed:!1};function l9(e){return e.trim()}function oe(e){return l9(e.text)||(e.images>0?"[Image]":"")}function ot(e){let t=e.filter(e=>!l7[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 on(e,t){switch(t.type){case"submit":return ot([...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 ot(e.map(e=>e.id===t.id&&l7[e.stage]?{...e,stage:"failed",inQueue:!1}:e));case"queue":return function(e,t,n){let r=new Map,s=(e,t)=>{let n=`${e}\u0000${l9(t)}`;r.set(n,(r.get(n)??0)+1)};for(let e of t)s("steer",e);for(let e of n)s("followUp",e);let a=!1,i=e.map(e=>{if(!l7[e.stage])return e;let t=`${e.kind}\u0000${oe(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?i:e}(e,t.steering,t.followUp);case"user-message":{let n=l9(t.text);if(!n&&0===t.images)return e;let r=e.find(e=>(l7[e.stage]||"unconfirmed"===e.stage)&&e.kind===t.kind&&l9(e.text)===n&&e.images===t.images);if(!r)return e;return ot(e.map(e=>e===r?{...e,stage:"delivered",inQueue:!1}:e))}case"withdraw":{let n=e=>l7[e.stage]||"unconfirmed"===e.stage;if(void 0===t.text)return e.filter(e=>!n(e));let r=l9(t.text),s=e.find(e=>n(e)&&e.kind===t.kind&&(l9(e.text)===r||oe(e)===r));return s?e.filter(e=>e!==s):e}case"idle":{let t=e.filter(e=>e.inQueue);return t.length===e.length?e:t}case"reset":return 0===e.length?e:[]}}function or(e){return"user"!==e.role?"":"string"==typeof e.content?e.content:e.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n")}function os(e){return"steering"in e&&!0===e.steering?"steer":"followUp"}function oa(e){return e.flatMap(e=>e.tasks.flatMap(t=>"completed"===t.status||"abandoned"===t.status?[]:[{phase:e.name,content:t.content,status:t.status,blocker:t.blocker??null}]))}function oi(e,t,n){let r=[],s=[],a=null;for(let n of e){if("toolCall"!==n.type)continue;if("task"===n.toolName){s.push(n);continue}if(tW(n.toolName)){let e=tD(n,t.get(n.toolCallId));"authoritative"===e.kind&&(a=e.phases);continue}let e=le(n,t.get(n.toolCallId));e&&r.push(e)}return{checks:r,dispatchCalls:s,files:tF(e,t,n),remaining:a?oa(a):null}}function ol(e,t,n){let r=[];for(let s=Math.max(0,t);s<Math.min(e.length,n);s++){let t=e[s];"assistant"===t.role&&r.push(...t.content??[])}return r}function oo(e,t,n){let r=[],s=null;for(let a=Math.max(0,t);a<Math.min(e.length,n);a++){let t=e[a];if("assistant"===t.role)for(let e of t.content??[])"toolCall"===e.type&&(s=e.toolCallId);else if("custom"===t.role&&"async-result"===t.customType){let e="string"==typeof t.content?t.content:t.content.map(e=>"text"===e.type?e.text:"").join("\n");r.push({text:e,after:s})}}return r}function oc(e,t){var n;let r=t;for(;r>=0&&(n=e[r],n?.role==="custom"?"compaction"===n.customType:n?.role==="user"&&("steer"===os(n)||function(e){if(e===l8||e===l5||e===l6||l3.has(e))return!0;let[t,n]=e.split("\n",2);return("[하네스 통지] 이 세션이 시작한 CUELO 업데이트가 끝나 런타임이 새 버전으로 교체됐고, 이 세션이 그 위에서 재개됐습니다."===t||"[하네스 통지] 이 세션이 시작한 CUELO 업데이트가 실패했습니다."===t)&&void 0!==n&&n.startsWith("requestId=")}(or(n))));){let t=r-1;for(;t>=0&&"user"!==e[t].role;)t-=1;r=t}return r}function od(e,t,n,r){let s=Math.min(e.length,r),a=new Map;for(let t=Math.max(0,n);t<s;t++){let n=e[t];"toolResult"===n.role&&a.set(n.toolCallId,t)}let i=[];for(let r=Math.max(0,n-1);r<s;r++){let s=e[r];if(r>=n&&"assistant"===s.role)for(let e of s.content??[]){if("toolCall"!==e.type||!tW(e.toolName))continue;let n=tD(e,t.get(e.toolCallId));"authoritative"===n.kind&&i.push({at:a.get(e.toolCallId)??r,phases:n.phases})}for(let e of s.trackerTodos??[]){let t=tz(e);t&&i.push({at:r+.5,phases:t})}}let l=null;for(let e of i)(!l||e.at>=l.at)&&(l=e);return l?l.phases:null}function ou(e,t,n,r=0,s=[]){for(let a=Math.max(0,r);a<Math.min(e.length,n);a++){let n=e[a];if("assistant"===n.role)for(let e of n.content??[])"toolCall"===e.type&&s.push(...lU(e,t.get(e.toolCallId)))}return s}function oh(e,t,n){let r=null,s=null;for(let a=Math.max(0,t-1);a<Math.min(e.length,n);a++){let t=e[a];for(let e of[t.timestamp,"assistant"===t.role?t.completedAt:void 0])"number"==typeof e&&Number.isFinite(e)&&((null===r||e<r)&&(r=e),(null===s||e>s)&&(s=e))}return{startedAt:r,endedAt:s}}function op(e,t){if(0===e.length)return null;let n=[...e].sort((e,t)=>e-t),r=(n.length-1)*t,s=Math.floor(r),a=Math.ceil(r);return n[s]+(n[a]-n[s])*(r-s)}let om=["investigate","implement","verify","report"],of={edit:!0,write:!0,ast_edit:!0,multiedit:!0,notebookedit:!0},og={bash:!0,eval:!0};function ox(e){let t=[],n=new Map;for(let r of e)if("toolResult"===r.role&&n.set(r.toolCallId,r),"assistant"===r.role&&Array.isArray(r.content))for(let e of r.content)"toolCall"===e.type&&t.push(e);return{blocks:t,results:n}}function ov(e,t,n,r){return!0===of[t]&&!tR(e.input,n.get(e.toolCallId),r)}function oy(e){return(e.toolName??"").toLowerCase().split(/[.:/]/).pop()??""}function ob(e){return"yield"===oy(e)&&!Array.isArray(e.input?.type)}function ow(e,t){if(0===e.length)return null;let{blocks:n,results:r}=ox(e),s=-1;n.forEach((e,t)=>{ob(e)&&(s=t)});let a=s>=0&&s===n.length-1,i=a?n.findLastIndex((e,t)=>t<s&&ob(e))+1:s+1,l={calls:{investigate:0,implement:0,verify:0,report:0},phase:"investigate",ended:a,reedits:0,checks:{passed:0,failed:0,unknown:0},verifiedAfterEdit:!1},o=!1;for(let e of n.slice(i)){let n=oy(e);if(ov(e,n,r,t))"verify"===l.phase&&(l.reedits+=1),o=!0,l.phase="implement",l.verifiedAfterEdit=!1;else if(og[n]){if(l.phase=o?"verify":"investigate",o){l.verifiedAfterEdit=!0;let t=le(e,r.get(e.toolCallId));t?.state==="passed"?l.checks.passed+=1:t?.state==="failed"?l.checks.failed+=1:t&&(l.checks.unknown+=1)}}else"yield"===n&&(l.phase="report",o=!1);l.calls[l.phase]+=1}return l}function ok(e,t){if(!e)return{run:null,stations:om.map(e=>({phase:e,state:"unobserved",calls:0}))};let n=t&&e.ended?{calls:{investigate:0,implement:0,verify:0,report:0},phase:"investigate",ended:!1,reedits:0,checks:{passed:0,failed:0,unknown:0},verifiedAfterEdit:!1}:e,r=t?om.indexOf(n.phase):om.findLastIndex(e=>n.calls[e]>0),s=om.map((e,s)=>{let a,i=n.calls[e];return a=t&&e===n.phase?"active":i>0?"verify"!==e||n.verifiedAfterEdit?"done":"stale":s<r?"skipped":t?"waiting":"none",{phase:e,state:a,calls:i}});return{run:n,stations:s}}function oj(e){if(e<6e4)return null;let t=Math.round(e/6e4);return{hours:Math.floor(t/60),minutes:t%60}}function oS(e){if("assistant"!==e.role)return e;let t=e.content;if(!Array.isArray(t))return e;let n=t.map(e=>("object"!=typeof e||null===e||Array.isArray(e)||"toolCall"!==e.type?null:{type:"toolCall",toolCallId:"string"==typeof e.toolCallId?e.toolCallId:"string"==typeof e.id?e.id:"",toolName:"string"==typeof e.toolName?e.toolName:"string"==typeof e.name?e.name:"",input:"object"!=typeof e.input||null===e.input||Array.isArray(e.input)?"object"!=typeof e.arguments||null===e.arguments||Array.isArray(e.arguments)?{}:e.arguments:e.input})??e);return{...e,content:n}}function oC(e){return"pending"===e||"running"===e}let oN=new Map;function oT(e){return`${e.liveId??""}|${e.status??""}|${e.archiveName??""}`}function oI(e){return e instanceof a9&&("live-unreachable"===e.kind||"sidecar-unreachable"===e.kind)?{kind:"unreachable",message:e.message}:{kind:"error",message:e instanceof Error?e.message:String(e)}}function oM(e,{sessionId:t,client:n,enabled:r}){let[a,i]=(0,s.useState)(oN),l=(0,s.useRef)(new Map),o=(0,s.useRef)(e);o.current=e;let c=(0,s.useCallback)(()=>{let e=l.current;i(t=>{let n=!1,r=new Map;for(let[s,a]of e){let e=t.get(s),i=e&&e.entries===a.collected&&e.state===a.state?e:{state:a.state,entries:a.collected};i!==e&&(n=!0),r.set(s,i)}return r.size!==t.size&&(n=!0),n?r:t})},[]),d=e.map(e=>`${e.key}|${oT(e)}`).join("\n");return(0,s.useEffect)(()=>{if(!r)return;let e=!1,s=!1,a=null,i=l.current,d=new Set(o.current.map(e=>e.key));for(let e of[...i.keys()])d.has(e)||i.delete(e);for(let e of o.current){let t=oT(e);i.get(e.key)?.signature!==t&&i.set(e.key,{signature:t,nextByte:0,collected:[],state:{kind:"loading"}})}c();let u=async(r,s,a,i)=>{if(!r.archiveName){s.state={kind:"empty",source:"live",note:i};return}try{let l=await n.getArchiveTranscript(t,r.archiveName,400,a);if(e)return;0===s.collected.length&&(s.collected=l.entries.flatMap((e,t)=>{let n=`archive:${t}`;return e.message&&"assistant"===e.message.role?[{id:n,message:e.message}]:e.irc?[{id:n,irc:{from:e.irc.from||void 0,message:e.irc.message||void 0,truncated:!0===e.irc.truncated}}]:[]})),s.state=0===l.entries.length?{kind:"empty",source:"archive",note:i}:{kind:"ready-archive",entries:l.entries,truncated:l.truncated,note:i}}catch(n){if(e||a.aborted)return;let t=oI(n);s.state="unreachable"===t.kind?{kind:"unreachable",message:t.message}:{kind:"error",message:t.message}}},h=async(r,s)=>{let a=i.get(r.key);if(a){if(!r.liveId)return void await u(r,a,s);try{var l,o;let i=await n.getLiveTranscript(t,r.liveId,a.nextByte,s);if(e)return;let c=(l=i.entries,o=i.fromByte,l.flatMap((e,t)=>{let n=e.id??`${o}:${t}`;if("message"===e.type&&e.message)return[{id:n,message:oS(e.message)}];if("custom_message"===e.type&&"irc:incoming"===e.customType){let t=e.details;return!t||"object"!=typeof t||Array.isArray(t)?[]:[{id:n,irc:{from:"string"==typeof t.from?t.from:void 0,message:"string"==typeof t.message?t.message:void 0}}]}return[]}));i.reset||0===i.fromByte?a.collected=c:c.length>0&&(a.collected=[...a.collected,...c]),a.nextByte=i.nextByte,a.collected.length>0?("ready-live"!==a.state.kind||a.state.entries!==a.collected)&&(a.state={kind:"ready-live",entries:a.collected}):await u(r,a,s)}catch(t){if(e||s.aborted)return;if(r.archiveName){let e=oI(t);await u(r,a,s,`실시간 기록을 읽지 못해 디스크 기록을 표시합니다: ${e.message}`)}else{let e=oI(t);a.state="unreachable"===e.kind?{kind:"unreachable",message:e.message}:{kind:"error",message:e.message}}}}},p=async()=>{if(e||s||"u">typeof document&&"visible"!==document.visibilityState)return;s=!0;let t=new AbortController;a=t;try{for(let e of o.current)await h(e,t.signal)}finally{s=!1}e||c()};p();let m=o.current.some(e=>oC(e.status))?setInterval(()=>void p(),3e3):void 0,f=()=>{"visible"===document.visibilityState&&p()};return document.addEventListener("visibilitychange",f),()=>{e=!0,a?.abort(),clearInterval(m),document.removeEventListener("visibilitychange",f)}},[n,r,c,t,d]),a}let oE="omp-web:flow-motion",o$=new Set,oR=null;function oL(){if(null===oR)try{oR="paused"===window.localStorage.getItem(oE)}catch{oR=!1}return oR}function oP(e){return o$.add(e),()=>{o$.delete(e)}}function oA(){return(0,s.useSyncExternalStore)(oP,oL,()=>!1)}function o_({paused:e}){let{st:t}=sz();return(0,r.jsx)("button",{type:"button",className:"flow-graph-motion","aria-pressed":e,onClick:()=>(function(e){oR=e;try{e?window.localStorage.setItem(oE,"paused"):window.localStorage.removeItem(oE)}catch{}for(let e of o$)e()})(!e),children:t("graph.motion.pause")})}function oF(e,t,n){return n&&t.current===e.stage?"active":"waiting"===e.status?"deploy"===e.stage?"approval":"waiting":"skipped"===e.status||"notNeeded"===e.status?"skipped":"stale"===e.status?"stale":"done"===e.status||"passed"===e.status?"done":"failed"===e.status||"running"===e.status?e.status:"unverified"}function oO(e){return e.stale?"stale":e.outcome}let oz=(0,r.jsx)("svg",{className:"flow-chevron",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)("polyline",{points:"6 9 12 15 18 9"})});function oD({look:e}){return(0,r.jsxs)("span",{className:"flow-node","aria-hidden":"true",children:[("done"===e||"stale"===e)&&(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",strokeDasharray:"stale"===e?"3.5 2":void 0,children:(0,r.jsx)("polyline",{points:"5 12 10 17 19 7"})}),"unverified"===e&&(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",children:[(0,r.jsx)("line",{x1:"12",y1:"6",x2:"12",y2:"13"}),(0,r.jsx)("line",{x1:"12",y1:"18",x2:"12",y2:"18.5"})]}),"failed"===e&&(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",children:[(0,r.jsx)("line",{x1:"7",y1:"7",x2:"17",y2:"17"}),(0,r.jsx)("line",{x1:"17",y1:"7",x2:"7",y2:"17"})]}),"skipped"===e&&(0,r.jsx)("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",children:(0,r.jsx)("line",{x1:"6",y1:"12",x2:"18",y2:"12"})})]})}function oW({outcome:e}){let t={className:"flow-check-icon",width:16,height:16,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0};return"stale"===e?(0,r.jsxs)("svg",{...t,strokeWidth:2,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"}),(0,r.jsx)("path",{d:"M12 7v5l4 2"})]}):"passed"===e||"done"===e?(0,r.jsx)("svg",{...t,strokeWidth:2.5,children:(0,r.jsx)("polyline",{points:"5 12 10 17 19 7"})}):"failed"===e?(0,r.jsxs)("svg",{...t,strokeWidth:2.5,children:[(0,r.jsx)("line",{x1:"6",y1:"6",x2:"18",y2:"18"}),(0,r.jsx)("line",{x1:"18",y1:"6",x2:"6",y2:"18"})]}):"running"===e?(0,r.jsxs)("svg",{...t,strokeWidth:2,children:[(0,r.jsx)("path",{d:"M10.1 2.182a10 10 0 0 1 3.8 0"}),(0,r.jsx)("path",{d:"M13.9 21.818a10 10 0 0 1-3.8 0"}),(0,r.jsx)("path",{d:"M17.609 3.721a10 10 0 0 1 2.69 2.7"}),(0,r.jsx)("path",{d:"M2.182 13.9a10 10 0 0 1 0-3.8"}),(0,r.jsx)("path",{d:"M20.279 17.609a10 10 0 0 1-2.7 2.69"}),(0,r.jsx)("path",{d:"M21.818 10.1a10 10 0 0 1 0 3.8"}),(0,r.jsx)("path",{d:"M3.721 6.391a10 10 0 0 1 2.7-2.69"}),(0,r.jsx)("path",{d:"M6.391 20.279a10 10 0 0 1-2.69-2.7"})]}):(0,r.jsxs)("svg",{...t,strokeWidth:2,children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"10"}),(0,r.jsx)("line",{x1:"12",x2:"12",y1:"8",y2:"12"}),(0,r.jsx)("line",{x1:"12",x2:"12.01",y1:"16",y2:"16"})]})}function oH({step:e,st:t}){let n=t(`flow.state.${e.outcome}`);if(e.stale)n=t("passed"===e.outcome?"flow.state.stale":"flow.state.staleDone");else if("review"===e.stage&&"failed"===e.outcome&&null!==e.findings){let r=1===e.findings?"flow.state.findings.one":"flow.state.findings";n=t("resolve"===e.action?"flow.state.open":r,{count:e.findings})}else"review"===e.stage&&e.unusable?n=t("flow.state.reviewUnusable"):"review"===e.stage&&"done"===e.outcome&&(n=t("flow.state.noFindings"));return(0,r.jsxs)("span",{className:"flow-tone","data-tone":oO(e),children:[n,"commit"===e.stage&&e.commit&&(0,r.jsxs)(r.Fragment,{children:[" ",(0,r.jsxs)("span",{className:"flow-sha-tail",children:["\xb7\xa0",(0,r.jsx)("code",{className:"flow-sha",children:e.commit.slice(0,7)})]})]})]})}let oU={syntax:"flow.why.check.syntax",optional:"flow.why.check.optional",noExit:"flow.why.noExit",noResult:"flow.why.noResult",noCompletion:"flow.why.noCompletion",interrupted:"flow.why.interrupted"},oB={masked:"flow.next.rerun",syntax:"flow.next.rerun",optional:"flow.next.optional",compound:"flow.next.compound",noExit:"flow.next.again",noResult:"flow.next.again",noCompletion:"flow.next.again",interrupted:"flow.next.again"},oq=(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:"M6.5 3.5h7M6.5 8h7M6.5 12.5h7M2 5.5 4.5 8 2 10.5"})});function oV({toolCallId:e}){let t=(0,s.useContext)(tG),{t:n}=(0,F.s)();return t?(0,r.jsxs)(l.r,{className:"flow-reveal",variant:"ghost",size:"xsmall",layout:"withText",onClick:()=>t(e),style:{marginTop:6,marginInlineStart:-8},children:[(0,r.jsx)(c.In,{size:"14px",svg:oq}),n("processLog.revealInLog")]}):null}function oK({step:e,label:t,st:n}){let s=lC(e),a=e.compound?.stages.map(e=>n(`flow.stage.${e}`)).join("\xb7")??"",i=e.otherRun,l=e.reason?oU[e.reason]:void 0,o=s?n("flow.why.compoundConfirmed",{stages:a}):i?.kind==="unjudged"?n("flow.why.watched.unjudged",{conclusion:i.conclusion}):i?n(`flow.why.watched.${i.outcome}`):n("flow.why.exitZero"),c=s?n("flow.why.compoundMissing"):l?n(l,{label:t}):"check"===e.stage?n("flow.why.check",{label:t}):i?.kind==="commit"?n("flow.why.ciOtherRun",{sha:i.sha}):i?.kind==="publish"?n("flow.why.ciPublishRun"):i?.kind==="unjudged"?n("flow.why.ciUnjudged",{conclusion:i.conclusion}):n(`flow.why.${e.stage}`),d=e.reason?n(oB[e.reason]):s?n("flow.next.compound"):null,u="unverified"===e.outcome||"unobserved"===e.outcome&&void 0!==e.reason,h=null!==e.exitCode?n("flow.exit",{code:e.exitCode}):n("failed"===e.outcome?"flow.exit.error":"running"===e.outcome?"flow.state.running":"flow.exit.none");return(0,r.jsxs)("div",{className:"flow-raw",children:[u&&(0,r.jsxs)("p",{className:"flow-why",children:["unverified"===e.outcome&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("b",{children:n("flow.why.confirmed")})," ",o,(0,r.jsx)("br",{})]}),(0,r.jsx)("b",{children:n("flow.why.missing")})," ",c,d&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("br",{}),(0,r.jsx)("b",{children:n("flow.why.next")})," ",d]})]}),e.stale&&(0,r.jsx)("p",{className:"flow-why",children:n("flow.why.stale")}),void 0===e.commandKey?(0,r.jsx)("code",{className:"flow-raw-command",children:e.command}):(0,r.jsx)("p",{className:"flow-why",children:n("flow.commandOmitted")}),(0,r.jsx)("div",{className:"flow-exit",children:h}),e.evidence&&(0,r.jsxs)("div",{className:"flow-exit",children:[n("flow.evidence")," ",(0,r.jsx)("code",{className:"flow-evidence",children:e.evidence})]}),(0,r.jsx)(oV,{toolCallId:e.toolCallId})]})}function oJ({steps:e,st:t,attempts:n=!1}){return(0,r.jsx)("ul",{className:"flow-checks",children:e.map(e=>{let s="check"===e.stage?e.labels.map(e=>t(`flow.label.${e}`)).join("\xb7")||t("flow.label.check"):"review"===e.stage?t("resolve"===e.action?"flow.label.resolve":"flow.label.review"):"ci"===e.stage||"deploy"===e.stage||"commit"===e.stage?t(`flow.label.${e.stage}`):t(`flow.stage.${e.stage}`),a=oO(e),i=(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(oW,{outcome:a}),(0,r.jsx)(oH,{step:e,st:t}),(0,r.jsxs)("span",{className:"flow-check-label",children:[n?`${t("flow.attempt",{attempt:e.attempt})} \xb7 ${s}`:s,lC(e)&&(0,r.jsx)("span",{className:"flow-compound",children:t("flow.compound.failed")})]})]});return"check"!==e.stage&&"ci"!==e.stage&&"deploy"!==e.stage?(0,r.jsx)("li",{className:"flow-check","data-result":a,children:(0,r.jsx)("div",{className:"flow-check-head",children:i})},e.toolCallId):(0,r.jsx)("li",{className:"flow-check","data-result":a,children:(0,r.jsxs)("details",{children:[(0,r.jsxs)("summary",{className:"flow-check-head",children:[i,(0,r.jsxs)("span",{className:"flow-disclose",children:[t("flow.details"),oz]})]}),(0,r.jsx)(oK,{step:e,label:s,st:t})]})},`${e.toolCallId}#${e.stage}`)})})}function oG({steps:e,st:t}){return 0===e.length?null:(0,r.jsxs)("details",{className:"flow-earlier",children:[(0,r.jsxs)("summary",{className:"flow-earlier-toggle",children:[t("flow.earlier",{count:e.length}),oz]}),(0,r.jsx)(oJ,{steps:e,st:t,attempts:!0})]})}function oY({view:e,steps:t,st:n}){if(0===t.length)return null;if("check"!==e.stage)return(0,r.jsx)(oJ,{steps:t,st:n});let s=lS(t),a=e=>{let t=oZ.indexOf(oO(e));return t<0?oZ.length:t},i=[...s].sort((e,t)=>a(e)-a(t)),l=t.filter(e=>!s.includes(e));return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(oJ,{steps:i,st:n}),l.length>0&&(0,r.jsxs)("details",{className:"flow-earlier",children:[(0,r.jsxs)("summary",{className:"flow-earlier-toggle",children:[n("flow.repeats",{count:l.length}),oz]}),(0,r.jsx)(oJ,{steps:l,st:n})]})]})}let oZ=["failed","unverified","unobserved","stale","running","passed"];function oQ({view:e,flow:t,live:n,st:s,compact:a=!1}){if(n&&t.current===e.stage)return s("flow.state.running");if("waiting"===e.status)return s("flow.state.waiting");if("skipped"===e.status||"notNeeded"===e.status)return s(`flow.state.${e.status}`);let i=e.steps[e.steps.length-1];if("investigate"===e.stage)return s("running"===e.status?"flow.state.running":"flow.state.done");if("edit"===e.stage&&"done"===e.status)return s(t.attempt>1?"flow.state.redone":"flow.state.done");if("check"===e.stage&&!a){let t=new Map;for(let n of lS(e.steps))t.set(oO(n),(t.get(oO(n))??0)+1);return oZ.filter(e=>t.has(e)).map((e,n)=>(0,r.jsxs)("span",{children:[n>0&&" \xb7 ",(0,r.jsx)("span",{className:"flow-tone","data-tone":e,children:s(`flow.count.${e}`,{count:t.get(e)??0})})]},e))}return"check"===e.stage||"edit"===e.stage?(0,r.jsx)("span",{className:"flow-tone","data-tone":e.status,children:s(`flow.state.${e.status}`)}):(0,r.jsx)(oH,{step:i,st:s})}function oX({flow:e,live:t,st:n,id:s}){let a=e.loops[e.loops.length-1],i=a?e.steps.filter(e=>e.stage===a.from):[],l=n("flow.loop.badge",{attempt:e.attempt});return(0,r.jsxs)("div",{className:"flow-chain-panel",id:s,children:[(0,r.jsxs)("div",{className:"flow-chain-wrap","data-loop":a?"":void 0,style:a?{"--loop-from":iI.indexOf(a.from)}:void 0,children:[(0,r.jsx)("ol",{className:"flow-chain","aria-label":n("flow.aria"),children:e.stages.map(s=>{let a=oF(s,e,t);return(0,r.jsxs)("li",{className:"flow-link","data-state":a,"aria-current":"active"===a?"step":void 0,children:[(0,r.jsx)(oD,{look:a}),(0,r.jsx)("span",{className:"flow-link-name",children:n(`flow.stage.${s.stage}`)}),(0,r.jsx)("span",{className:"flow-link-state",children:(0,r.jsx)(oQ,{view:s,flow:e,live:t,st:n,compact:!0})})]},s.stage)})}),a&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("div",{className:"flow-loop","aria-hidden":"true",children:[(0,r.jsx)("svg",{width:"22",height:"15",viewBox:"0 0 22 15",children:(0,r.jsx)("polyline",{points:"3 12 11 3 19 12",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round"})}),(0,r.jsx)("span",{className:"flow-loop-count",children:l})]}),(0,r.jsxs)("p",{className:"flow-loop-caption",children:[(0,r.jsx)("span",{className:"flow-loop-caption-count",children:l}),n("review"===a.from?"flow.loop.findings":"flow.loop.failed",{stage:n(`flow.stage.${a.from}`),attempt:a.attempt})]})]})]}),i.length>0&&(0,r.jsx)("div",{className:"flow-chain-attempts",children:(0,r.jsx)(oJ,{steps:i,st:n,attempts:!0})})]})}function o0({sessionId:e,snapshots:t,client:n,enabled:r,transcripts:a=!0,cwd:i}){let l=(0,s.useMemo)(()=>t.filter(e=>oC(e.status)),[t]),o=r&&!!e&&l.length>0,c=oM((0,s.useMemo)(()=>l.map(e=>({key:e.id,liveId:e.id,status:e.status})),[l]),{sessionId:e??"",client:n,enabled:o&&a}),[d,u]=(0,s.useState)(null),h=l.map(e=>e.id).sort().join("\n");return(0,s.useEffect)(()=>{let t;if(!o||!e)return;let n=new AbortController,r=h.split("\n"),s=`/api/subagents/eta?sessionId=${encodeURIComponent(e)}`,a=!0,i=0;async function l(){try{let t=await fetch(s,{signal:AbortSignal.any([n.signal,AbortSignal.timeout(15e3)])}),i=t.ok?await t.json():null;!n.signal.aborted&&i&&i.sessionId===e&&i.histories&&"object"==typeof i.histories&&(u(i),a=r.some(e=>!i.histories[e]))}catch{}finally{if(!n.signal.aborted){let e=a&&i<3;e&&(i+=1),t=window.setTimeout(l,e?1e4:6e4)}}}return l(),()=>{n.abort(),window.clearTimeout(t)}},[h,o,e]),(0,s.useMemo)(()=>{let t=new Map;if(!o)return t;let n=d&&d.sessionId===e?d.histories:void 0;for(let e of l){let r=(a?c.get(e.id)?.entries??[]:[]).flatMap(e=>"message"in e?[e.message]:[]);t.set(e.id,{phase:function(e,t){if(0===e.length)return null;let{blocks:n,results:r}=ox(e),s="investigate",a=!1;for(let e of n){let n=oy(e);ov(e,n,r,t)?(a=!0,s="implement"):og[n]?s=a?"verify":"investigate":"yield"===n&&(s="report",a=!1)}return s}(r,i),trace:ow(r,i),todo:function(e){let t=new Map;for(let n of e)"toolResult"===n.role&&t.set(n.toolCallId,n);let n=tH([...e],t);if(!n)return null;let r=tB(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},[l,i,d,o,c,e,a])}function o1(e,t){let n=oj(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 o2(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}):o1(e,t)}function o4({phase:e}){let{st:t}=sz();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:om.map((n,s)=>(0,r.jsxs)("span",{children:[s>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))})]})}let o8={done:"done",stale:"stale",active:"active",waiting:"waiting",skipped:"skipped",none:"skipped",unobserved:"unverified"};function o5(e,t){let n=t.passed+t.failed+t.unknown,s=t.failed>0?"failed":t.unknown>0?"unverified":"passed";return(0,r.jsx)("span",{className:"flow-tone","data-tone":s,children:e("subflow.checks",{passed:t.passed,total:n})})}function o6({flow:e,live:t,verdict:n,attempts:s}){let{st:a}=sz(),i=oA(),l=e.stations.findIndex(e=>"active"===e.state),o=om.indexOf("implement"),c=s.filter(e=>"rework"===e.verdict).length,d=n?"accepted"===n.verdict?"done":"unverified":"waiting",u=n?`${a(`verdict.${n.verdict}`)}${null!==n.attempt&&n.attempt>1?` \xb7 ${a("verdict.attempt",{attempt:n.attempt})}`:""}`:a(t?"flow.state.waiting":"verdict.none");return(0,r.jsxs)("div",{className:"subagent-flow",children:[t&&l>=0&&(0,r.jsx)(o_,{paused:i}),(0,r.jsxs)("ol",{className:"flow-graph","aria-label":a("subflow.aria"),"data-live":t?"":void 0,"data-motion":i?"paused":void 0,children:[e.stations.map((t,n)=>{let s=o8[t.state];return(0,r.jsx)("li",{className:"flow-graph-station","data-stage":t.phase,"data-state":s,"data-loop":c>0&&n>=o?"":void 0,"aria-current":"active"===t.state?"step":void 0,style:{"--col":n+1},children:(0,r.jsxs)("div",{className:"flow-graph-stop",children:[(0,r.jsx)("span",{className:"flow-graph-stop-name",children:a(`phase.${t.phase}`)}),(0,r.jsxs)("span",{className:"flow-graph-stop-state",children:[(0,r.jsx)(oD,{look:s}),(0,r.jsx)("span",{className:"flow-graph-stop-word",children:function(e,t,n){let s="verify"===t.phase&&null!==n&&n.checks.passed+n.checks.failed+n.checks.unknown>0;switch(t.state){case"active":return s&&n?(0,r.jsxs)(r.Fragment,{children:[e("flow.state.running")," \xb7 ",o5(e,n.checks)]}):e("flow.state.running");case"waiting":return e("flow.state.waiting");case"skipped":return e("flow.state.skipped");case"none":return e("detail.stageNone");case"unobserved":return e("subflow.unobserved");case"stale":return e(n&&n.checks.passed>0?"flow.state.stale":"flow.state.staleDone");case"done":if("report"===t.phase)return e("subflow.reported");if(s&&n)return o5(e,n.checks);if("implement"===t.phase&&n&&n.reedits>0)return`${e("subflow.calls",{count:t.calls})} \xb7 ${e("subflow.reedits",{count:n.reedits})}`;return e("subflow.calls",{count:t.calls})}}(a,t,e.run)})]})]})},t.phase)}),(0,r.jsx)("li",{className:"flow-graph-station","data-stage":"verdict","data-state":d,style:{"--col":om.length+1},children:(0,r.jsxs)("div",{className:"flow-graph-stop",children:[(0,r.jsx)("span",{className:"flow-graph-stop-name",children:a("graph.join")}),(0,r.jsxs)("span",{className:"flow-graph-stop-state",children:[(0,r.jsx)(oD,{look:d}),(0,r.jsx)("span",{className:"flow-graph-stop-word",children:u})]})]})}),c>0&&(0,r.jsxs)("li",{className:"flow-graph-return",style:{"--from":o+1,"--to":om.length+1},children:[(0,r.jsx)("span",{className:"flow-graph-return-line","aria-hidden":"true",children:(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",children:(0,r.jsx)("polyline",{points:"5 12 12 5 19 12"})})}),(0,r.jsx)("span",{className:"flow-graph-return-text",children:a("subflow.rework",{count:c})})]})]})]})}function o3(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 o7({snapshot:e,view:t,id:n}){var s,a,i;let l,o,c,{st:d}=sz(),u=nG(5e3),h="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===h)return null;let p=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=op(n,.5)??0;return{kind:"remaining",p25Ms:op(n,.25)??0,medianMs:r,p75Ms:op(n,.75)??0,samples:n.length,percent:Math.round(t/(t+r)*100)}}(t.history,h),m=(s=t.todo,!s||null===h||0===s.completed||s.completed>=s.total?null:h*(s.total-s.completed)/s.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":p?.kind??(g?.rework?"rework":"none"),children:[(0,r.jsx)("span",{"data-elapsed":Math.floor(h/1e3),children:d("eta.elapsed",{duration:o2(d,h)})}),g?.rework&&(0,r.jsxs)(r.Fragment,{children:[" \xb7 ",(0,r.jsx)("span",{style:f,title:d("eta.reworkHint"),children:null!==x&&x>=0?d("eta.rework",{attempt:g.attempt,duration:o2(d,x)}):d("eta.reworkAttempt",{attempt:g.attempt})})]}),p?.kind==="remaining"&&(0,r.jsxs)(r.Fragment,{children:[" \xb7 ",(0,r.jsx)("span",{title:d("eta.hint"),children:d("eta.remaining",{range:(a=p.p25Ms,i=p.p75Ms,o=oj(a),c=oj(i),o&&c&&0===o.hours&&0===c.hours?o.minutes===c.minutes?d("duration.minutes",{minutes:o.minutes}):d("eta.rangeMinutes",{low:o.minutes,high:c.minutes}):d("eta.range",{low:o1(d,a),high:o1(d,i)})),samples:p.samples})})," \xb7 ",(0,r.jsx)("span",{style:f,children:d("eta.percent",{percent:p.percent})})]}),p?.kind==="overrun"&&(0,r.jsxs)(r.Fragment,{children:[" \xb7 ",(0,r.jsx)("span",{style:{color:"var(--warning)"},title:d("eta.hint"),children:0===p.longerRuns?d("eta.overrun",{longest:o1(d,p.longestMs)}):d("eta.sparseTail",{samples:p.samples,longerRuns:p.longerRuns})})]}),null!==m&&t.todo&&(0,r.jsxs)(r.Fragment,{children:[" \xb7 ",(0,r.jsx)("span",{style:f,title:d("eta.byTodoHint"),children:m<6e4?d("eta.byTodoSoon",{completed:t.todo.completed,total:t.todo.total}):d("eta.byTodo",{duration:o1(d,m),completed:t.todo.completed,total:t.todo.total})})]})]})}let o9={dispatching:"run.dispatching",pending:"run.pending",running:"run.running",completed:"run.completed",failed:"run.failed",aborted:"run.aborted",unobserved:"run.unobserved"},ce={accepted:"verdict.accepted",rework:"verdict.rework",held:"verdict.held",none:"verdict.none"};function ct({maker:e,st:t}){let n=e.verdict?.verdict??"none",s=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(o9[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(ce[n]),null!=s&&s>1?` \xb7 ${t("verdict.attempt",{attempt:s})}`:null]})]})}function cn(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 oi(n,r,t)}function cr(e){return e.sessionFile?.split(/[\\/]/).pop()?.replace(/\.jsonl$/i,"")||void 0}function cs(e,t){let n=e?.state;return n?.kind!=="ready-live"?null:ow(n.entries.flatMap(e=>"message"in e?[e.message]:[]),t)}function ca({maker:e,st:t}){let n=e.runTitle??e.title;return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{className:"answer-dispatch-name",title:n,children:n}),e.priorVerdict&&!e.runTitle&&(0,r.jsx)("span",{className:"answer-dispatch-title-note",children:t("subflow.firstTitle")})]})}function ci({calls:e}){let{ledger:t,subagents:n,toolResults:a,onOpenPanel:i,sessionId:l,cwd:o,onOpenMaker:c,selectedMaker:d}=(0,s.useContext)(iC),{st:u}=sz(),{t:h}=(0,F.s)(),[p,m]=(0,s.useState)(!1),f=(0,s.useId)(),g=(0,s.useMemo)(()=>ii(),[]),x=(0,s.useMemo)(()=>e.flatMap(e=>ix(e,a.get(e.toolCallId))??[]).map(e=>iw(e,n,t)),[e,a,n,t]),v=(0,s.useMemo)(()=>x.flatMap(e=>{if("pending"!==e.run&&"running"!==e.run)return[];let r=ib(e.member,n,t);return r?[r]:[]}),[x,n,t]),y=o0({sessionId:l,snapshots:v,client:g,enabled:!0,transcripts:p,cwd:o}),b=(0,s.useMemo)(()=>new Map(x.flatMap(e=>{let t=ik(e.member,n);return t?[[e.member.key,t]]:[]})),[x,n]),w=(0,s.useMemo)(()=>p?[...b].filter(([,e])=>!oC(e.status)).map(([e,t])=>({key:e,liveId:t.id,status:t.status,archiveName:cr(t)})):[],[b,p]),k=oM(w,{sessionId:l??"",client:g,enabled:p&&!!l&&w.length>0}),j=d?.origin?x.find(e=>e.member.key===d.origin):void 0,S=j?.run,C=j?.verdict??null;if((0,s.useEffect)(()=>{if(!d||!c||!S)return;let e=d.status;e&&e.run===S&&e.verdict?.order===C?.order||c({...d,status:{run:S,verdict:C}},!1)},[c,d,S,C]),0===x.length)return null;let N=0,T=0,I=0;for(let e of x)("dispatching"===e.run||"pending"===e.run||"running"===e.run)&&(N+=1),"completed"===e.run&&(T+=1),e.verdict?.verdict==="accepted"&&(I+=1);return(0,r.jsxs)("section",{className:"answer-dispatch","aria-label":u("dispatch.title",{count:x.length}),children:[(0,r.jsxs)("button",{type:"button",className:"answer-dispatch-toggle","aria-expanded":p,"aria-controls":f,title:u(p?"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:T,accepted:I})}),(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":p?h("dispatchLane.label"):void 0,children:x.map(e=>{var n;let s,a="pending"===e.run||"running"===e.run,i=a?v.find(t=>t.id===e.member.agentId):void 0,l=i?y.get(i.id):void 0,h=b.get(e.member.key),m=e.member.key===d?.origin,f=a&&"live"===e.runSource,g=p?ok(f?l?.trace??null:cs(k.get(e.member.key),o),f):null,x=p?ij(e.member,t):[];return(0,r.jsxs)("li",{className:"answer-dispatch-row","data-dispatch-key":e.member.key,"data-focused":m?"":void 0,children:[p?(0,r.jsx)(cl,{maker:e,phase:f&&g?.run?u(`phase.${g.run.phase}`):null,checks:function(e,t,n){if(!t)return{kind:"unobserved"};if(oC(t.status))return{kind:"running"};let r=e?.state;if(!r||"loading"===r.kind)return{kind:"loading"};if("ready-live"===r.kind){let{checks:e}=cn(r.entries,n);return{kind:"counted",passed:e.filter(e=>"passed"===e.state).length,total:e.length}}return"empty"===r.kind&&"live"===r.source?{kind:"counted",passed:0,total:0}:{kind:"unobserved"}}(k.get(e.member.key),h,o),onOpen:h&&c?()=>c({key:`live:${h.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)(ca,{maker:e,st:u}),(0,r.jsx)(ct,{maker:e,st:u})]}),g&&(0,r.jsx)(o6,{flow:g,live:f,verdict:e.verdict,attempts:x}),p&&(0,r.jsx)(cc,{attempts:x}),i&&l&&(0,r.jsxs)("div",{className:"answer-dispatch-progress",children:[l.todo?`${o3(u,l.todo)} \xb7 `:null,(0,r.jsx)(o7,{snapshot:i,view:l})]}),p&&(0,r.jsxs)("dl",{className:"answer-dispatch-detail",children:[a&&(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.priorVerdict&&(0,r.jsxs)("div",{children:[(0,r.jsx)("dt",{children:u("subflow.prior")}),(0,r.jsx)("dd",{children:(s=null!==(n=e.priorVerdict).attempt&&n.attempt>1?` \xb7 ${u("verdict.attempt",{attempt:n.attempt})}`:"",`${u(ce[n.verdict])}${s}${n.reason?` \xb7 ${n.reason}`:""}`)})]}),e.priorVerdict&&(0,r.jsxs)("div",{children:[(0,r.jsx)("dt",{children:u(e.runTitle?"subflow.firstTitle":"subflow.runTitle")}),(0,r.jsx)("dd",{children:e.runTitle?e.title:u("detail.stageNone")})]}),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)})}),p&&i&&(0,r.jsxs)("div",{className:"answer-dispatch-links",children:[(0,r.jsx)("button",{type:"button",className:"answer-link",onClick:()=>i("subagents"),children:u("detail.openSubagents")}),(0,r.jsx)("button",{type:"button",className:"answer-link",onClick:()=>i("process"),children:u("detail.openProcess")})]})]})}function cl({maker:e,phase:t,checks:n,onOpen:s}){let{st:a}=sz(),{t:i}=(0,F.s)(),l=e.verdict?.verdict??"none",o=a(o9[e.run]),c="running"===n.kind?null:"counted"===n.kind?i("dispatchLane.checks",{passed:n.passed,total:n.total}):i("loading"===n.kind?"dispatchLane.checksLoading":"dispatchLane.checksUnobserved");return(0,r.jsxs)("div",{className:"answer-dispatch-line is-lane",children:[(0,r.jsx)(ca,{maker:e,st:a}),(0,r.jsxs)("span",{className:"answer-status-pair",children:[(0,r.jsx)("span",{className:"answer-status-run","data-state":e.run,children:t?i("dispatchLane.runPhase",{run:o,phase:t}):o}),c&&(0,r.jsx)("span",{className:"answer-dispatch-checks","data-checks":"counted"===n.kind&&n.passed<n.total?"failed":n.kind,children:c}),(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(ce[l])})]}),s?(0,r.jsx)("button",{type:"button",className:"answer-link answer-dispatch-open","aria-label":i("dispatchLane.openLabel",{title:e.title}),onClick:s,children:i("dispatchLane.open")}):(0,r.jsx)("span",{className:"answer-dispatch-unavailable",title:i("makerDetail.unavailable"),children:i("dispatchLane.unavailable")})]})}function co({maker:e}){let{ledger:t,subagents:n,sessionId:a,cwd:i}=(0,s.useContext)(iC),l=(0,s.useMemo)(()=>ii(),[]),o="pending"===e.run||"running"===e.run,c=o&&"live"===e.runSource,d=o?ib(e.member,n,t):void 0,u=o0({sessionId:a,snapshots:(0,s.useMemo)(()=>d?[d]:[],[d]),client:l,enabled:!0,transcripts:!0,cwd:i}),h=ik(e.member,n),p=(0,s.useMemo)(()=>h&&!oC(h.status)?[{key:e.member.key,liveId:h.id,status:h.status,archiveName:cr(h)}]:[],[h,e.member.key]),m=oM(p,{sessionId:a??"",client:l,enabled:!!a&&p.length>0}),f=d?u.get(d.id):void 0,g=ok(c?f?.trace??null:cs(m.get(e.member.key),i),c),x=ij(e.member,t);return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(o6,{flow:g,live:c,verdict:e.verdict,attempts:x}),(0,r.jsx)(cc,{attempts:x})]})}function cc({attempts:e}){let{t}=(0,F.s)();return e.length<2?null:(0,r.jsx)("ol",{className:"answer-dispatch-attempts","aria-label":t("dispatchLane.label"),children:e.map((e,n)=>(0,r.jsxs)("li",{"data-verdict":e.verdict,title:e.reason??void 0,children:[n>0&&(0,r.jsx)("span",{className:"answer-status-arrow","aria-hidden":"true",children:"→ "}),null===e.attempt?t("dispatchLane.attemptUnknown"):t("dispatchLane.attempt",{attempt:e.attempt})," ",t(`dispatchLane.verdict.${e.verdict}`)]},`${e.attempt??"n"}-${n}`))})}let cd=/\.(?:md|mdx|markdown|txt)$/i;function cu(e){return`${(100*Math.min(1,Math.max(0,e))).toFixed(2)}%`}function ch(e,t,n){return"investigate"!==e.stage&&("edit"===e.stage?n>0||e.earlier.length>0:e.steps.length>0||e.earlier.length>0||"ci"===e.stage&&null!==t.publication)}function cp({entry:e,st:t}){let n="running"===e.maker.run||"pending"===e.maker.run||"dispatching"===e.maker.run;return e.bar&&null!==e.durationMs?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{className:"flow-graph-track","aria-hidden":"true",children:(0,r.jsx)("span",{className:"flow-graph-bar",style:{left:cu(e.bar.offset),width:cu(e.bar.width)}})}),(0,r.jsx)("span",{className:"flow-graph-time",children:o2(t,e.durationMs)})]}):(0,r.jsx)("span",{className:"flow-graph-time-missing",children:t(n?"summary.time.running":"summary.time.unobserved")})}function cm({entry:e,together:t,batch:n=!1,st:s}){let a=e.maker.member.workClass;return(0,r.jsxs)("span",{className:"flow-graph-maker-tags",children:[(0,r.jsx)("span",{className:"flow-graph-chip","data-unknown":a?void 0:"",children:s(`graph.kind.${a??"unknown"}`)}),n&&e.batchSize>1&&(0,r.jsx)("span",{className:"flow-graph-chip",children:s("graph.parallel.batch")}),t&&(0,r.jsx)("span",{className:"flow-graph-chip","data-unknown":"unknown"===e.concurrency?"":void 0,"data-concurrency":e.concurrency,children:s(`graph.concurrency.${e.concurrency}`)})]})}function cf({selectable:e,selected:t,detailId:n,onSelect:s,className:a,children:i,style:l}){return e?(0,r.jsx)("button",{type:"button",className:a,style:l,"aria-pressed":t,"aria-controls":n,onClick:s,children:i}):(0,r.jsx)("div",{className:a,style:l,children:i})}function cg({summary:e,makers:t,timings:n,live:a=!1,onOpenFile:i}){let l,o,c,{subagents:d,onOpenMaker:u}=(0,s.useContext)(iC),{st:h}=sz(),p=(0,s.useId)(),{flow:m}=e,f=(0,s.useMemo)(()=>(function(e,t,n,r){let s=function(e,t){let n=t.map(e=>null!==e.startedAt&&null!==e.durationMs?{start:e.startedAt,end:e.startedAt+e.durationMs}:null),r=e.startedAt,s=e.endedAt;for(let e of n)e&&((null===r||e.start<r)&&(r=e.start),(null===s||e.end>s)&&(s=e.end));let a=null!==r&&null!==s?s-r:0;return n.map(e=>e?a<=0||null===r?{offset:0,width:1}:{offset:(e.start-r)/a,width:(e.end-e.start)/a}:null)}(n,t),a=e.map(e=>"live"===e.runSource&&"running"===e.run),i=new Map;for(let t of e)i.set(t.member.toolCallId,(i.get(t.member.toolCallId)??0)+1);let l=e.map((n,r)=>{let l="unknown";for(let t=0;t<e.length;t+=1)if(t!==r&&(a[r]&&a[t]||n.observedParallelWith?.has(e[t].member.key))){l="overlapped";break}return{maker:n,bar:s[r],durationMs:t[r]?.durationMs??null,concurrency:l,batchSize:i.get(n.member.toolCallId)??1,liveRunning:a[r]}});return{makers:l,parallel:l.some(e=>"overlapped"===e.concurrency)?"observed":l.some(e=>e.batchSize>1)?"batch":"none",files:r.filter(e=>!cd.test(e.filePath)),docs:r.filter(e=>cd.test(e.filePath))}})(t,n,e.span,e.files),[t,n,e.span,e.files]),[g,x]=(0,s.useState)(void 0),v=oA(),y=e.files.length,b=a&&m.current?m.stages.find(e=>e.stage===m.current):void 0,w=void 0===g?b&&ch(b,m,y)?`stage:${b.stage}`:(l=m.stages.filter(e=>ch(e,m,y)),o=m.loops[m.loops.length-1],(c=(m.next?.returning&&o?l.find(e=>e.stage===o.from):void 0)??l.find(e=>"failed"===e.status)??l.find(e=>"unverified"===e.status||"stale"===e.status)??l.findLast(e=>"notNeeded"!==e.status&&"skipped"!==e.status)??l[l.length-1])?`stage:${c.stage}`:y>0?"files":null):g,k=m.loops[m.loops.length-1],j=k?iI.indexOf(k.from):-1,S=iI.indexOf("edit"),C=b?iI.indexOf(b.stage):-1,N=f.makers.some(e=>e.liveRunning),T=f.files.length>0||f.docs.length>0,I=(0,s.useMemo)(()=>a?[]:function(e,t,n,r){let s=iI.indexOf("edit"),a=e=>"waiting"!==e.status&&"skipped"!==e.status&&"notNeeded"!==e.status,i=[],l=n,o=e=>{let t=iI.indexOf(e.stage);l&&t>s&&(i.push("branch"),l=!1),i.push(e.stage),l&&t===s&&(i.push("branch"),l=!1)},c=t[t.length-1];if(c){let t=iI.indexOf(c.from);for(let n of e)iI.indexOf(n.stage)<=t&&(a(n)||n.earlier.length>0||n.stage===c.from)&&o(n);for(let t of(l&&(i.push("branch"),l=!1),i.push("return"),e))iI.indexOf(t.stage)>=s&&a(t)&&o(t)}else for(let t of e)a(t)&&o(t);return l&&i.push("branch"),r&&i.push("outputs"),i}(m.stages,m.loops,f.makers.length>0,T),[a,m.stages,m.loops,f.makers.length,T]),[M,E]=(0,s.useState)(null),$=null!==M&&M<I.length?M:null;(0,s.useEffect)(()=>{if(null===$)return;let e=window.setTimeout(()=>E($+1<I.length?$+1:null),800);return()=>window.clearTimeout(e)},[$,I.length]);let R=e=>{if(null!==$&&I.includes(e))return I[$]===e?"now":I.slice(0,$).includes(e)?"past":"ahead"},L=new Map;for(let e of f.makers){let t=e.maker.verdict?.verdict??"none";L.set(t,(L.get(t)??0)+1)}let P=1===L.size&&L.has("accepted"),A=m.stages[S+1],_=A?oF(A,m,a):"skipped",F=f.makers.length>0&&(0,r.jsxs)("li",{className:"flow-graph-branch","data-loop":k&&j>S?"":void 0,"data-merge":"skipped"===_||"waiting"===_||"approval"===_?"quiet":void 0,"data-beat":R("branch"),children:[(0,r.jsxs)("p",{className:"flow-graph-branch-head",children:[(0,r.jsx)("span",{children:h(1===f.makers.length?"graph.branch.one":"graph.branch",{count:f.makers.length})}),"none"!==f.parallel&&(0,r.jsx)("span",{className:"flow-graph-chip","data-parallel":f.parallel,children:h(`graph.parallel.${f.parallel}`)})]}),(0,r.jsx)("ul",{className:"flow-graph-lanes",children:f.makers.map(e=>{let t=`maker:${e.maker.member.key}`;return(0,r.jsx)("li",{className:"flow-graph-lane","data-run":e.maker.run,"data-live":e.liveRunning?"":void 0,children:(0,r.jsxs)(cf,{selectable:!0,selected:w===t,detailId:p,onSelect:()=>x(w===t?null:t),className:"flow-graph-maker",children:[(0,r.jsx)("span",{className:"flow-graph-maker-name",title:e.maker.title,children:e.maker.title}),(0,r.jsx)(cm,{entry:e,together:f.makers.length>1,st:h}),(0,r.jsx)("span",{className:"flow-graph-maker-time",children:(0,r.jsx)(cp,{entry:e,st:h})}),(0,r.jsx)(ct,{maker:e.maker,st:h})]})},e.maker.member.key)})}),(0,r.jsxs)("p",{className:"flow-graph-join","data-state":P?"done":"unverified",children:[(0,r.jsx)(oD,{look:P?"done":"unverified"}),(0,r.jsx)("span",{className:"flow-graph-join-label",children:h("graph.join")}),(0,r.jsx)("span",{className:"flow-graph-join-counts",children:["accepted","rework","held","none"].filter(e=>L.has(e)).map(e=>(0,r.jsxs)("span",{className:"answer-status-verdict","data-verdict":e,children:[h(ce[e])," ",L.get(e)]},e))})]})]},"branch"),O=k&&(0,r.jsxs)("li",{className:"flow-graph-return","data-beat":R("return"),style:{"--from":S+1,"--to":j+1},children:[(0,r.jsx)("span",{className:"flow-graph-return-line","aria-hidden":"true",children:(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",children:(0,r.jsx)("polyline",{points:"5 12 12 5 19 12"})})}),(0,r.jsxs)("span",{className:"flow-graph-return-text",children:[(0,r.jsx)("b",{children:h("flow.loop.badge",{attempt:m.attempt})})," ",h("review"===k.from?"flow.loop.findings":"flow.loop.failed",{stage:h(`flow.stage.${k.from}`),attempt:k.attempt})]})]},"return"),z=m.stages.map((e,t)=>{let n=oF(e,m,a),s=`stage:${e.stage}`,i=e.steps.some(lC);return(0,r.jsx)("li",{className:"flow-graph-station","data-stage":e.stage,"data-state":n,"data-again":e.earlier.length>0?"":void 0,"data-loop":k&&t>=S&&t<j?"":void 0,"data-beat":R(e.stage),"aria-current":"active"===n?"step":void 0,style:{"--col":t+1},children:(0,r.jsxs)(cf,{selectable:ch(e,m,y),selected:w===s,detailId:p,onSelect:()=>x(s),className:"flow-graph-stop",children:[(0,r.jsx)("span",{className:"flow-graph-stop-name",children:h(`flow.stage.${e.stage}`)}),(0,r.jsxs)("span",{className:"flow-graph-stop-state",children:[(0,r.jsx)(oD,{look:n}),(0,r.jsx)("span",{className:"flow-graph-stop-word",children:(0,r.jsx)(oQ,{view:e,flow:m,live:a,st:h})})]}),i&&(0,r.jsx)("span",{className:"flow-compound",children:h("flow.compound.failed")})]})},e.stage)}),D=[];z.forEach((e,t)=>{D.push(e),t===S&&F&&D.push(F),t===j&&O&&D.push(O)});let W=null;if(w?.startsWith("stage:")){let t=m.stages.find(e=>`stage:${e.stage}`===w);if(t){let n="ci"===t.stage&&null!==m.publication&&"notNeeded"===t.status,s="edit"===t.stage||n?[]:t.steps;W=(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("h5",{className:"flow-graph-detail-title",children:h(`flow.stage.${t.stage}`)}),"ci"===t.stage&&m.publication&&(0,r.jsx)("p",{className:"flow-graph-note",children:"nothingToPublish"===m.publication.kind?h("flow.ci.nothingToPublish",{sha:m.publication.commit.slice(0,7)}):h("flow.ci.notNeeded",{run:m.publication.runId,repo:m.publication.repo,ref:m.publication.ref,sha:m.publication.sha.slice(0,7)})}),"edit"===t.stage&&(0,r.jsx)(sZ,{files:e.files,onOpenFile:i}),(0,r.jsx)(oY,{view:t,steps:s,st:h}),(0,r.jsx)(oG,{steps:t.earlier,st:h})]})}}else if(w?.startsWith("maker:")){let e=f.makers.find(e=>`maker:${e.maker.member.key}`===w);if(e){let t=ik(e.maker.member,d);W=(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("h5",{className:"flow-graph-detail-title",children:e.maker.title}),(0,r.jsx)(cm,{entry:e,together:f.makers.length>1,batch:!0,st:h}),(0,r.jsx)("p",{className:"flow-graph-detail-line",children:(0,r.jsx)(ct,{maker:e.maker,st:h})}),(0,r.jsx)("div",{className:"flow-graph-maker-time",children:(0,r.jsx)(cp,{entry:e,st:h})}),(0,r.jsx)(co,{maker:e.maker}),t&&u?(0,r.jsx)("button",{type:"button",className:"flow-graph-open",onClick:()=>u({key:`live:${t.id}`,toolCallId:e.maker.member.toolCallId,origin:e.maker.member.key,status:{run:e.maker.run,verdict:e.maker.verdict}}),children:h("graph.maker.open")}):(0,r.jsx)("p",{className:"flow-graph-note",children:h("graph.maker.unavailable")})]})}}else("files"===w||"docs"===w)&&(W=(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("h5",{className:"flow-graph-detail-title",children:"files"===w?h(1===f.files.length?"graph.files.one":"graph.files",{count:f.files.length}):h(1===f.docs.length?"graph.docs.one":"graph.docs",{count:f.docs.length})}),(0,r.jsx)(sZ,{files:"files"===w?f.files:f.docs,onOpenFile:i})]}));return(0,r.jsxs)("section",{className:"flow-section",children:[(0,r.jsxs)("div",{className:"flow-graph-head",children:[(0,r.jsx)("h4",{className:"flow-heading",children:h("flow.heading")}),(C>=0||N)&&(0,r.jsx)(o_,{paused:v}),I.length>1&&(0,r.jsx)("button",{type:"button",className:"flow-graph-replay",onClick:()=>E(null===$?0:null),children:h(null===$?"graph.replay":"graph.replay.stop")})]}),(0,r.jsx)("div",{className:"flow-graph-frame",children:(0,r.jsxs)("ol",{className:"flow-graph","aria-label":h("flow.aria"),"data-live":a?"":void 0,"data-motion":v?"paused":void 0,"data-replay":null===$?void 0:"",children:[D,T&&(0,r.jsxs)("li",{className:"flow-graph-outputs","data-beat":R("outputs"),children:[(0,r.jsx)("span",{className:"flow-graph-outputs-label",children:h("graph.outputs")}),f.files.length>0&&(0,r.jsx)(cf,{selectable:!0,selected:"files"===w,detailId:p,onSelect:()=>x("files"),className:"flow-graph-output",children:h(1===f.files.length?"graph.files.one":"graph.files",{count:f.files.length})}),f.docs.length>0&&(0,r.jsx)(cf,{selectable:!0,selected:"docs"===w,detailId:p,onSelect:()=>x("docs"),className:"flow-graph-output",children:h(1===f.docs.length?"graph.docs.one":"graph.docs",{count:f.docs.length})})]})]})}),W&&(0,r.jsx)("div",{className:"flow-graph-detail",id:p,role:"region","aria-label":h("graph.detail.aria"),children:W})]})}function cx(e,t,n){let r=new URLSearchParams({type:t});return n&&r.set("sessionId",n),`/api/files/${tV(e)}?${r}`}function cv(e,t){let[n,r]=(0,s.useState)({kind:"loading"});return(0,s.useEffect)(()=>{let n=new AbortController;return r({kind:"loading"}),fetch(e,{method:"head"===t?"HEAD":"GET",cache:"no-store",signal:n.signal}).then(async e=>{if(!e.ok)return null;if("head"===t)return"";if("text"===t)return e.text();let n=await e.json();return"string"==typeof n.content?n.content:null}).then(e=>{n.signal.aborted||r(null===e?{kind:"failed"}:{kind:"ready",content:e})}).catch(()=>{n.signal.aborted||r({kind:"failed"})}),()=>n.abort()},[e,t]),n}function cy({messageKey:e}){let{st:t}=sz();return(0,r.jsx)("p",{className:"answer-result-fallback",role:"result.previewLoading"===e?"status":void 0,children:t(e)})}function cb({deliverable:e,sessionId:t,title:n}){let{filePath:s,kind:a}=e;if("image"===a){let e=cx(s,"read",t);return(0,r.jsx)(cS,{src:e,title:n},e)}if("html"===a){let e=cx(s,"read",t);return(0,r.jsx)(cw,{url:e,title:n},e)}if(s.toLowerCase().endsWith(".pdf")){let e=cx(s,"read",t);return(0,r.jsx)(ck,{url:e,title:n},e)}let i=cx(s,"preview",t);return(0,r.jsx)(cj,{url:i,title:n},i)}function cw({url:e,title:t}){let n=cv(e,"json");return"ready"!==n.kind?(0,r.jsx)(cy,{messageKey:"failed"===n.kind?"result.previewFailed":"result.previewLoading"}):(0,r.jsx)("iframe",{className:"answer-result-media",srcDoc:n.content,sandbox:"allow-scripts",title:t,scrolling:"no",inert:!0})}function ck({url:e,title:t}){let n=cv(e,"head");return"ready"!==n.kind?(0,r.jsx)(cy,{messageKey:"failed"===n.kind?"result.previewFailed":"result.previewLoading"}):(0,r.jsx)("iframe",{className:"answer-result-media",src:`${e}#toolbar=0&view=FitH`,title:t,inert:!0})}function cj({url:e,title:t}){let n=cv(e,"text");return"ready"!==n.kind?(0,r.jsx)(cy,{messageKey:"failed"===n.kind?"result.previewFailed":"result.previewLoading"}):(0,r.jsx)("iframe",{className:"answer-result-media",srcDoc:n.content,sandbox:"allow-same-origin",title:t,inert:!0})}function cS({src:e,title:t}){let[n,a]=(0,s.useState)("loading");return"failed"===n?(0,r.jsx)(cy,{messageKey:"result.previewFailed"}):(0,r.jsxs)(r.Fragment,{children:["loading"===n?(0,r.jsx)(cy,{messageKey:"result.previewLoading"}):null,(0,r.jsx)("img",{className:"answer-result-media","data-fit":"contain",src:e,alt:t,draggable:!1,hidden:"loading"===n,onLoad:()=>a("ready"),onError:()=>a("failed")})]})}function cC({deliverables:e,onOpenFile:t}){let{sessionId:n}=(0,s.useContext)(iC),{st:a}=sz(),[i,o]=function(){let e=(0,s.useRef)(null),[t,n]=(0,s.useState)(!1);return(0,s.useEffect)(()=>{let r=e.current;if(!r||t)return;if("u"<typeof IntersectionObserver)return void n(!0);let s=new IntersectionObserver(e=>{e.some(e=>e.isIntersecting)&&n(!0)},{rootMargin:"200px 0px"});return s.observe(r),()=>s.disconnect()},[t]),[e,t]}(),[c,...d]=e;if(!c)return null;let u=tK(c.filePath),h=a("result.previewTitle",{name:u}),p=t?()=>t(c.filePath):void 0;return(0,r.jsxs)("section",{className:"answer-result","aria-label":a("result.label"),children:[(0,r.jsxs)("div",{ref:i,className:"answer-result-frame","data-kind":c.kind,children:[o&&(0,r.jsx)(cb,{deliverable:c,sessionId:n,title:h}),p&&(0,r.jsx)("button",{type:"button",className:"answer-result-cover",tabIndex:-1,"aria-hidden":"true",onClick:p})]}),(0,r.jsxs)("div",{className:"answer-result-bar",children:[(0,r.jsxs)("span",{className:"answer-result-title",children:[(0,r.jsx)("span",{className:"answer-result-kind",children:a("html"===c.kind?"result.kind.html":"image"===c.kind?"result.kind.image":c.filePath.toLowerCase().endsWith(".pdf")?"result.kind.pdf":"result.kind.document")}),(0,r.jsx)("span",{className:"answer-result-name",title:c.filePath,children:u})]}),p&&(0,r.jsx)(l.r,{className:"answer-result-open",variant:"neutralSolid",size:"medium",onClick:p,"aria-label":a("result.openNamed",{name:u}),children:a("result.open")})]}),d.length>0&&(0,r.jsxs)("div",{className:"answer-result-more",children:[(0,r.jsx)("span",{className:"answer-result-more-label",children:a("result.more",{count:d.length})}),(0,r.jsx)(sZ,{files:d.map(({filePath:e})=>({filePath:e})),onOpenFile:t})]})]})}let cN=(0,s.createContext)({selected:null,shown:!1,select:()=>{}});function cT(e,t){let{ledger:n,subagents:r,toolResults:a}=(0,s.useContext)(iC),i=(0,s.useMemo)(()=>t?[]:function(e){let t=[];for(let n of e){if(function(e){let t=e.toLowerCase().replace(/\\/g,"/").split("/");for(let e=0;e<t.length;e+=1){let n=t[e];if(Object.hasOwn(iN,n)||n.startsWith(".next")||"doc"===n&&"history"===t[e+1])return!0}return!1}(n.filePath))continue;let e=function(e){let t=eQ(e);return"html"===t||"htm"===t?"html":e0(e)?"document":eX(e)?"image":null}(n.filePath);e&&t.push({filePath:n.filePath,kind:e})}return t.map((e,t)=>({deliverable:e,index:t})).sort((e,t)=>iT[e.deliverable.kind]-iT[t.deliverable.kind]||e.index-t.index).map(({deliverable:e})=>e)}(e.files),[t,e.files]),l=(0,s.useMemo)(()=>e.dispatchCalls.flatMap(e=>ix(e,a.get(e.toolCallId))??[]).map(e=>iw(e,r,n)),[e.dispatchCalls,a,r,n]),o=(0,s.useMemo)(()=>l.map(e=>({startedAt:n.spawnedAt.get(e.member.key)??null,durationMs:n.durations.get(e.member.key)??null})),[l,n]),c=lS(e.flow.steps),d=c.filter(e=>"failed"===e.outcome).length,u=c.filter(e=>"failed"===e.outcome||"unobserved"===e.outcome).length,h=c.filter(e=>e.compound?.failed).length,p=c.filter(e=>"unverified"===e.outcome&&!e.compound?.failed).length,m=c.filter(e=>e.stale).length,f=l.filter(e=>"failed"===e.run||"aborted"===e.run||"unobserved"===e.run||e.verdict?.verdict!=="accepted").length,g=t?0:u+f,x=0===e.flow.steps.length&&(t||0===e.files.length&&0===e.checks.length&&0===l.length&&!e.remaining?.length);return{deliverables:i,makers:l,timings:o,checks:c,failed:d,compoundFailed:h,verdictUnconfirmed:p,stale:m,unconfirmed:g,empty:x,attention:g>0||d>0||p>0||h>0||m>0}}function cI(e,t,n,r){let s=[r(1===e.files.length?"summary.files.one":"summary.files",{count:e.files.length}),r(1===t.checks.length?"summary.checks.one":"summary.checks",{count:t.checks.length})];return n&&s.unshift(r("summary.live")),t.failed>0&&s.push(r("summary.checksFailed",{count:t.failed})),t.compoundFailed>0&&s.push(r("summary.compoundFailed",{count:t.compoundFailed})),t.makers.length>0&&s.push(r(1===t.makers.length?"summary.makers.one":"summary.makers",{count:t.makers.length})),e.remaining&&s.push(r("summary.remaining",{count:e.remaining.length})),t.unconfirmed>0&&s.push(r("summary.unverified",{count:t.unconfirmed})),t.verdictUnconfirmed>0&&s.push(r(1===t.verdictUnconfirmed?"summary.verdictUnverified.one":"summary.verdictUnverified",{count:t.verdictUnconfirmed})),t.stale>0&&s.push(r("summary.stale",{count:t.stale})),s}function cM({summary:e,turnKey:t,live:n=!1}){let{st:a}=sz(),i=cT(e,n),{selected:l,shown:o,select:c}=(0,s.useContext)(cN);if(i.empty)return null;let d=l===t&&o;return(0,r.jsxs)("button",{type:"button",className:"turn-row","aria-pressed":d,"data-live":n?"":void 0,onClick:()=>c(t),children:[(0,r.jsx)(cL,{attention:i.attention,live:n}),(0,r.jsx)("span",{className:"turn-row-counts","data-attention":i.attention?"":void 0,children:cI(e,i,n,a).join(" \xb7 ")}),(0,r.jsxs)("span",{className:"turn-row-go",children:[(0,r.jsx)("span",{className:"turn-row-go-label",children:a(d?"turn.shown":"turn.show")}),(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m9 18 6-6-6-6"})})]})]})}function cE({summary:e,turnKey:t,live:n=!1}){let{shown:a}=(0,s.useContext)(cN);return a?(0,r.jsx)(cM,{summary:e,turnKey:t,live:n}):(0,r.jsx)(c$,{summary:e,turnKey:t,live:n})}function c$({summary:e,turnKey:t,live:n}){let{st:a,locale:i}=sz(),l=cT(e,n),{select:o,latestTurn:c,compactedCalls:d,onOpenFile:u}=(0,s.useContext)(cN),h="live"===t||t===c?d:void 0;return l.empty&&!h?.length?null:(0,r.jsxs)("section",{className:"turn-inline","data-live":n?"":void 0,children:[(0,r.jsx)(cF,{summary:e,live:n,folded:!1,compactedCalls:h,onOpenFile:u,st:a,locale:i}),(0,r.jsx)("div",{className:"turn-inline-actions",children:(0,r.jsxs)("button",{type:"button",className:"turn-inline-show",onClick:()=>o(t),children:[a("turn.show"),(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m9 18 6-6-6-6"})})]})})]})}function cR({summary:e,live:t=!1,onOpen:n}){let{st:s}=sz(),a=cT(e,t);return a.empty?null:(0,r.jsxs)("button",{type:"button",className:"turn-peek",onClick:n,children:[(0,r.jsx)(cL,{attention:a.attention,live:t}),(0,r.jsx)("span",{className:"turn-peek-counts",children:cI(e,a,t,s).join(" \xb7 ")}),(0,r.jsx)("span",{className:"turn-peek-open",children:s("turn.peek")}),(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m18 15-6-6-6 6"})})]})}function cL({attention:e,live:t}){return t?(0,r.jsx)("span",{className:"workbench-lamp","aria-hidden":"true"}):e?(0,r.jsxs)("svg",{className:"turn-state-icon","data-tone":"warning",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"10"}),(0,r.jsx)("line",{x1:"12",x2:"12",y1:"8",y2:"12"}),(0,r.jsx)("line",{x1:"12",x2:"12.01",y1:"16",y2:"16"})]}):(0,r.jsxs)("svg",{className:"turn-state-icon",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"10"}),(0,r.jsx)("path",{d:"m9 12 2 2 4-4"})]})}function cP({title:e,summaryLine:t,folded:n,open:s=!1,children:a}){return n?(0,r.jsxs)("details",{className:"turn-block","data-folded":"",open:s,children:[(0,r.jsxs)("summary",{className:"turn-block-summary",children:[(0,r.jsx)("span",{className:"turn-block-title",children:e}),t&&(0,r.jsx)("span",{className:"turn-block-line",children:t}),(0,r.jsx)("svg",{className:"turn-block-chevron",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m6 9 6 6 6-6"})})]}),(0,r.jsx)("div",{className:"turn-block-body",children:a})]}):(0,r.jsxs)("section",{className:"turn-block",children:[(0,r.jsx)("h4",{className:"turn-block-title",children:e}),a]})}function cA(e,t,n,r){let s=t+(e??[]).reduce((e,t)=>e+(ix(t,n.get(t.toolCallId))?.length??0),0);return r(1===s?"summary.makers.one":"summary.makers",{count:s})}function c_({summary:e,live:t=!1,folded:n=!1,compactedCalls:a,onOpenFile:i}){let{st:l,locale:o}=sz(),{toolResults:c}=(0,s.useContext)(iC);return e?(0,r.jsx)(cF,{summary:e,live:t,folded:n,compactedCalls:a,onOpenFile:i,st:l,locale:o}):a&&a.length>0?(0,r.jsx)("div",{className:"turn-inspector",children:(0,r.jsx)(cP,{title:l("turn.dispatches"),summaryLine:cA(a,0,c,l),folded:n,open:!0,children:(0,r.jsx)(ci,{calls:a})})}):(0,r.jsx)("p",{className:"inspector-empty",children:l("turn.none")})}function cF({summary:e,live:t,folded:n,compactedCalls:a,onOpenFile:i,st:l,locale:o}){let c=cT(e,t),{toolResults:d}=(0,s.useContext)(iC),u=e.span.endedAt??e.span.startedAt,h=t?l("turn.headingLive"):null!==u?l("turn.heading",{time:new Intl.DateTimeFormat(o,{hour:"numeric",minute:"2-digit"}).format(new Date(u))}):l("turn.headingUnknown"),p=[{key:"files",label:l("turn.metric.files"),value:e.files.length},{key:"checks",label:l("turn.metric.checks"),value:c.checks.length},{key:"remaining",label:l("turn.metric.remaining"),value:e.remaining?.length??0}];c.failed>0&&p.push({key:"failed",label:l("turn.metric.failed"),value:c.failed,tone:"danger"}),c.unconfirmed>0&&p.push({key:"unconfirmed",label:l("turn.metric.unverified"),value:c.unconfirmed,tone:"warning"}),c.verdictUnconfirmed>0&&p.push({key:"verdict",label:l("turn.metric.verdict"),value:c.verdictUnconfirmed,tone:"warning"}),c.stale>0&&p.push({key:"stale",label:l("turn.metric.stale"),value:c.stale});let m=e.remaining;return(0,r.jsxs)("div",{className:"turn-inspector","data-live":t?"":void 0,children:[(0,r.jsx)("div",{className:"turn-inspector-head",children:(0,r.jsx)("h3",{className:"turn-inspector-title",children:h})}),(0,r.jsx)("dl",{className:"turn-metrics","aria-label":l("turn.numbers"),children:p.map(e=>(0,r.jsxs)("div",{className:"turn-metric","data-tone":e.tone,children:[(0,r.jsx)("dd",{children:e.value}),(0,r.jsx)("dt",{children:e.label})]},e.key))}),c.deliverables.length>0&&(0,r.jsx)(cC,{deliverables:c.deliverables,onOpenFile:i}),c.empty&&!a?.length?(0,r.jsx)("p",{className:"inspector-empty",children:l("turn.empty")}):e.flow.steps.length>0&&(n?(0,r.jsx)(cP,{title:l("flow.heading"),summaryLine:cI(e,c,t,l).join(" \xb7 "),folded:!0,open:!0,children:(0,r.jsx)(cg,{summary:e,makers:c.makers,timings:c.timings,live:t,onOpenFile:i})}):(0,r.jsx)("section",{className:"turn-block",children:(0,r.jsx)(cg,{summary:e,makers:c.makers,timings:c.timings,live:t,onOpenFile:i})})),(e.dispatchCalls.length>0||(a?.length??0)>0)&&(0,r.jsxs)(cP,{title:l("turn.dispatches"),summaryLine:cA(a,c.makers.length,d,l),folded:n,children:[e.dispatchCalls.length>0&&(0,r.jsx)(ci,{calls:e.dispatchCalls}),a&&a.length>0&&(0,r.jsx)(ci,{calls:a})]}),m&&(0,r.jsx)(cP,{title:l("summary.heading.remaining"),summaryLine:0===m.length?l("summary.todo.none"):l("summary.remaining",{count:m.length}),folded:n,children:0===m.length?(0,r.jsx)("p",{className:"answer-summary-empty",children:l("summary.todo.none")}):(0,r.jsx)("ul",{className:"flow-remaining-list",children:m.map((e,t)=>(0,r.jsxs)("li",{className:"answer-remaining","data-status":e.status,title:e.phase||void 0,children:[(0,r.jsx)("span",{className:"answer-remaining-status",children:l(`summary.todo.${e.status}`)}),(0,r.jsx)("span",{className:"answer-remaining-text",children:e.content}),e.blocker&&(0,r.jsx)("span",{className:"answer-remaining-blocker",children:l("summary.todo.blocker",{blocker:e.blocker})})]},`${e.phase}#${t}`))})})]})}let cO="cuelo-chat-search",cz="cuelo-chat-search-active";function cD(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 cW({open:e,onClose:t,containerRef:n,index:a,renderedStart:i,renderedEnd:l,contentKey:o,onReveal:c,onProgrammaticScroll:d,focusRequest:u,t:h}){let p=(0,s.useRef)(null),[m,f]=(0,s.useState)(""),[g,x]=(0,s.useState)(null),[v,y]=(0,s.useState)({index:-1,total:0}),b=(0,s.useDeferredValue)(m),w=e?b.trim().toLowerCase():"",k=(0,s.useRef)(g);k.current=g;let j=(0,s.useRef)([]),S=(0,s.useRef)({key:null,needle:"",rendered:!1});(0,s.useEffect)(()=>{if(!e)return;let t=requestAnimationFrame(()=>p.current?.select());return()=>cancelAnimationFrame(t)},[e,u]),(0,s.useEffect)(()=>()=>{cD(cO,[]),cD(cz,[])},[]),(0,s.useLayoutEffect)(()=>{let t=n.current;if(!e||!w||!t){cD(cO,[]),cD(cz,[]),j.current=[],S.current={key:null,needle:"",rendered:!1},y(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]"),s=r?Number(r.dataset.chatItem):NaN;if(!Number.isInteger(s))continue;let a=(e.textContent??"").toLowerCase(),i=n.get(s);i||(i=[],n.set(s,i));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),i.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,s){let a=[];if(!t)return a;for(let i=0;i<e.length;i++){let l=i>=r&&i<s?n.get(i)??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[i],t);for(let e=0;e<l;e++)a.push({item:i,k:e})}return a}(a,w,n,i,l);j.current=r;let s=tb(r,k.current);y(e=>e.index===s&&e.total===r.length?e:{index:s,total:r.length});let o=[];for(let t of e.values())for(let e of t)o.push(e);if(cD(cO,o),s<0){cD(cz,[]),S.current={key:null,needle:w,rendered:!1};return}let u=r[s],h=k.current;h&&h.item===u.item&&h.k===u.k||x(u);let p=u.item>=i&&u.item<l,m=S.current,f=m.needle!==w||m.key?.item!==u.item||m.key?.k!==u.k||!m.rendered&&p;if(S.current={key:u,needle:w,rendered:p},!p){cD(cz,[]),f&&c(u.item);return}let g=e.get(u.item)?.[u.k];if(cD(cz,g?[g]:[]),f)if(d(),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,i,l,o,g,n,c,d]);let C=(0,s.useCallback)(e=>{let t=j.current;if(0===t.length)return;let n=tb(t,k.current);x(t[(n+e+t.length)%t.length])},[]);if(!e)return null;let N=m.trim().length>0?0===v.total?h("chat.searchNoResults"):h("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:p,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:h("chat.searchPlaceholder"),"aria-label":h("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":h("chat.searchPrevious"),title:`${h("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":h("chat.searchNext"),title:`${h("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":h("chat.searchClose"),title:`${h("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 cH({questions:e,containerRef:t,layoutKey:n,onJump:a,label:i}){let l=(0,s.useRef)(null),[o,c]=(0,s.useState)(-1),[d,u]=(0,s.useState)(!1);(0,s.useEffect)(()=>{let e=setTimeout(()=>u(!0),0);return()=>clearTimeout(e)},[]);let h=d&&e.length>=2;(0,s.useEffect)(()=>{let n=t.current;if(!n||!h)return;let r=0,s=null,a=()=>{r=0,s?.[0]?.isConnected||(s=n.querySelectorAll("[data-chat-item]"));let t=n.getBoundingClientRect().top+8,a=0,i=s.length-1,l=s.length-1;for(;a<=i;){let e=a+i>>1,n=s[e].firstElementChild?.getBoundingClientRect();n&&n.bottom>t?(l=e,i=e-1):a=e+1}let o=l>=0?Number(s[l].dataset.chatItem):-1,d=-1;for(let t of e){if(t.item>o)break;d=t.item}c(d)},i=()=>{r||(r=requestAnimationFrame(a))};return r=requestAnimationFrame(a),n.addEventListener("scroll",i,{passive:!0}),()=>{n.removeEventListener("scroll",i),r&&cancelAnimationFrame(r)}},[e,h,n,t]),(0,s.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 p=e.length,m=(0,s.useCallback)((e,t)=>{let n="ArrowUp"===e.key?t-1:"ArrowDown"===e.key?t+1:"Home"===e.key?0:"End"===e.key?p-1:null;if(null===n)return;e.preventDefault();let r=Math.max(0,Math.min(p-1,n));l.current?.querySelectorAll("button")[r]?.focus()},[p]);if(!h)return null;let f=e.some(e=>e.item===o)?o:e[0].item;return(0,r.jsx)("nav",{className:"question-rail","aria-label":i,children:(0,r.jsx)("div",{ref:l,className:"question-rail-list",children:e.map((e,t)=>(0,r.jsx)(cU,{question:e,position:t,count:p,active:e.item===o,focusable:e.item===f,onJump:a,onMoveFocus:m},e.item))})})}let cU=(0,s.memo)(function({question:e,position:t,count:n,active:s,focusable:a,onJump:i,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":s?"true":void 0,"aria-label":`${t+1}/${n} ${o}`,title:o,onClick:()=>i(e.item),onKeyDown:e=>l(e,t),children:(0,r.jsx)("span",{"aria-hidden":"true"})})});function cB({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 cq={manual:!0,threshold:!0,overflow:!0,idle:!0,incomplete:!0};function cV({compaction:e,t}){let[n,a]=(0,s.useState)(()=>Date.now());if((0,s.useEffect)(()=>{if(!e)return;a(Date.now());let t=setInterval(()=>a(Date.now()),1e3);return()=>clearInterval(t)},[e]),!e)return null;let i=Math.max(0,Math.floor((n-e.startedAt)/1e3)),l=e.reason&&!0===cq[e.reason]?t(`chat.compactionReason.${e.reason}`):null;return(0,r.jsxs)(cB,{label:t("chat.compactionLabel"),tone:"accent",children:[t("chat.compactionProgress",{seconds:i}),l?` \xb7 ${l}`:""]})}function cK({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 cJ=n(39092),cG=n.n(cJ);let cY=["01","02","03"];function cZ(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}function cQ(e,t,n){if(e&&"streaming"!==t){let r=r8(e);if(r){let e="failed"===t?"failed":"done",s=rL(r$(r4(r),r.id,e)?.stickers??[],null,()=>cZ(n));return s?{src:s,alt:rk[e]}:null}}if(!e||"streaming"===t||!ry.includes(e))return null;let r="failed"===t?"failed":"done",s=e.slice(0,e.indexOf("(")).toLowerCase(),a=rL(cY.map(e=>`/stickers/${s}/${r}/${e}.webp`),null,()=>cZ(n));return a?{src:a,alt:rk[r]}:null}let cX=new Map,c0=(0,s.createContext)(cX);function c1({utterances:e,children:t}){return(0,r.jsx)(c0.Provider,{value:e,children:t})}function c2({turnIndex:e,turnEntryId:t,sessionId:n,cwd:a,onOpenFile:i}){let l=(0,s.useContext)(c0).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)(c4,{utterance:e,sessionId:n,cwd:a,onOpenFile:i},e.key))}):null}function c4({utterance:e,sessionId:t,cwd:n,onOpenFile:a}){let i=s_(null===e.accountSessionId?void 0:e.accountSessionId??t,e.provider,e.credentialId,e.model),[l,o]=(0,s.useState)(!1),[c,d]=(0,s.useState)(!1),u=(0,s.useRef)(null);(0,s.useLayoutEffect)(()=>{let e=u.current;e&&!l&&d(e.scrollHeight>e.clientHeight+1)},[e.text,l]);let h=e.text.trim().length>0,p=e.label?.trim(),m=i?.alias??p??sa(e.provider),f=i?.alias.split("(",1)[0]?.trim(),g=i&&p&&p!==i.alias&&p!==f?`작업 \xb7 ${p}`:null,x=cQ(i?.alias,e.status,e.key),v="failed"===e.status?"중단됨":"streaming"===e.status&&h?"작업 중":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)",...i?{minHeight:40}:null},children:[i&&(0,r.jsx)(sD,{seed:i.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})]})]}),h?(0,r.jsx)("div",{ref:u,style:{fontSize:12.5,lineHeight:1.6,...l?null:{maxHeight:240,overflow:"hidden"}},children:(0,r.jsx)(nJ,{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?"발화 없이 중단되었습니다":"아직 발화가 없습니다"}),h&&(c||l)&&(0,r.jsx)("button",{type:"button",onClick:()=>o(e=>!e),"aria-expanded":l,style:{marginTop:4,padding:"3px 9px",height:22,border:0,borderRadius:"var(--radius-control)",background:"var(--bg-hover)",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-e0a9ca790f024efb inline-utterance-sticker"}),(0,r.jsx)(cG(),{id:"e0a9ca790f024efb",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 c8=/^\[character-summon alias="([^"\r\n]+)" model="([^"\r\n]+)"(?: oauth-position="\d+")?\]\r?$/mu;function c5(e,t,n,r){if("string"!=typeof n)return[];let s=c8.exec(n),a=s?.[1],i=s?.[2];return a&&i?[{toolCallId:e,...t?{name:t}:{},alias:a,model:i,batchSize:r}]:[]}function c6(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(...c5(n.toolCallId,"string"==typeof e.name?e.name:void 0,e.task,r)),Array.isArray(e.tasks))for(let s of e.tasks)!s||"object"!=typeof s||Array.isArray(s)||t.push(...c5(n.toolCallId,"name"in s&&"string"==typeof s.name?s.name:void 0,"task"in s?s.task:void 0,r))}return t}function c3(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 c7=/^agent:\/\/([^/?#]+)\/?$/i;function c9(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,s="string"==typeof e.path?c7.exec(e.path):null,a=s?.[1],i=e.content;if(!a||"string"!=typeof i)continue;let l=t?.get(r.toolCallId);n.push({toolCallId:r.toolCallId,to:a,message:i,...l?.from?{from:l.from}:{},...l?.receipts?{receipts:l.receipts}:{}})}return n}function de(e,t,n){for(let r of["string"==typeof e.progress?.resolvedModel?e.progress.resolvedModel.trim():"",t?.model.trim()??""]){let e=r.indexOf("/");if(e>0&&r.slice(0,e)===n)return r.slice(e+1).trim()||void 0}}let dt=["greeting","utterance","message","text"],dn=function(e){let t=(0,s.useMemo)(()=>ii(),[]),n=function(e,t){let[n,r]=(0,s.useState)(null);return(0,s.useEffect)(()=>{if(!t)return void r(null);let n=!1,s=new AbortController;return r(null),e.getArchive(t,s.signal).then(e=>{n||r(e)}).catch(()=>{}),()=>{n=!0,s.abort()}},[e,t]),n}(t,e.sessionId),r=(0,s.useMemo)(()=>{let t=new Set(e.subagents.map(e=>e.id)),r=[];if(n&&n.sessionId===e.sessionId){let s=e.turns.flatMap(e=>e.characterSummons);for(let a of n.subagents){if(t.has(a.name))continue;let n=[...s].reverse().find(e=>e.name===a.name);n&&r.push(function(e,t,n){let r=e.status??"unknown",s={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,i="string"==typeof e.errorMessage&&e.errorMessage.trim()?e.errorMessage.trim():void 0;return(void 0!==a||void 0!==i)&&(s.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!==i?{retryFailure:{attempt:0,errorMessage:i}}:{}}),s}(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 s=r.requests.filter(e=>e.name),a="string"==typeof t.task?c8.exec(t.task):null,i=a?.[1],l=a?.[2],o=s.find(e=>e.name===t.id)??(i&&l?r.requests.find(e=>e.alias===i&&e.model===l):void 0)??(1===r.requests.length&&1===r.requests[0].batchSize?r.requests[0]:void 0);if(!o)return[];let c=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:c}]})}(e.turns,[...e.subagents,...r])},[e.subagents,e.turns,e.sessionId,n]),a=(0,s.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]),i=oM(a,{sessionId:e.sessionId??"",client:t,enabled:!!e.sessionId&&a.length>0});return(0,s.useMemo)(()=>r.flatMap(t=>(function(e,t,n){var r;let{snapshot:s,summon:a}=e,i="completed"===(r=s.status)||"unknown"===r?"settled":"failed"===r||"aborted"===r?"failed":"streaming",l="failed"===i,o=a?.model.split("/",1)[0]?.trim()||void 0,c=l&&o?o:function(e,t,n){let r="string"==typeof e.progress?.resolvedModel?e.progress.resolvedModel.trim():"",s=r.indexOf("/");if(s>0)return r.slice(0,s);let a=t?.model.trim()??"",i=a.indexOf("/");return i>0?a.slice(0,i):n?.trim()||void 0}(s,a,n),d=s.id.trim()||void 0,u=`subagent:${s.id}`,h=[],p=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,s.id)&&a.send.from===n){p=a.turnIndex,m=t+1;break}}return}if("assistant"!==t.message.role)return;let g=t.message.provider||c;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",...dt]){let n=e[t];if("string"==typeof n&&n.trim().length>0){r=n;break}}let s=r.trim();s.length>0&&(t=s)}return t}(r))||(l?t.message.errorMessage?.trim()??"":"");if(0===x.length)return;let v=t.message.model||de(s,a,g);h.push({key:`${s.id}:${n}`,turnIndex:p,speakerId:u,provider:g,...v?{model:v}:{},credentialId:t.message.credentialId,accountSessionId:null,label:l&&a?a.alias:d,text:x,status:i})}),0===h.length&&"settled"!==i&&c){let e=l?s.progress?.retryFailure?.errorMessage?.trim():void 0,t=de(s,a,c);h.push({key:`${s.id}:pending`,turnIndex:p,speakerId:u,provider:c,...t?{model:t}:{},accountSessionId:null,label:l&&a?a.alias:d,text:e||"",status:i})}return h})(t,i.get(t.snapshot.id),e.sessionProvider)),[r,i,e.sessionProvider])},dr="web6",ds=[],da=[],di=function(e){let t=(0,s.useMemo)(()=>(function(e=(e,t)=>fetch(e,t),t="/api/web6/consults"){return{async listConsults(n,r){let s=n.trim();if(!s)throw Error("sessionId가 필요하다");let a=`${t}?sessionId=${encodeURIComponent(s)}`,i=await e(a,{signal:r});if(!i.ok)throw Error(`HTTP ${i.status}`);let l=await i.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 s="number"==typeof e.finishedAt&&Number.isFinite(e.finishedAt)?e.finishedAt:n,{conversationId:a,text:i,error:l}=e;return{sessionId:t,startedAt:n,finishedAt:s,elapsedMs:"number"==typeof e.elapsedMs&&Number.isFinite(e.elapsedMs)?e.elapsedMs:s-n,model:"string"==typeof e.model?e.model:"",status:r,conversationId:"string"==typeof a&&""!==a?a:void 0,text:"string"==typeof i&&""!==i?i:void 0,error:"string"==typeof l&&""!==l?l:void 0}}(e);return t?.sessionId===s?[t]:[]})}}})(),[]),[n,r]=(0,s.useState)(da),a=(0,s.useRef)(""),i=e.sessionId??"",l=i.length>0;return(0,s.useEffect)(()=>{if(!l){a.current="",r(da);return}let e=new AbortController,n=async()=>{if("u"<typeof document||"hidden"!==document.visibilityState)try{let n=await t.listConsults(i,e.signal),s=n.map(e=>`${e.startedAt}.${e.finishedAt}.${e.status}`).join("|");if(s===a.current)return;a.current=s,r(n)}catch{}};n();let s=setInterval(()=>void n(),5e3);return()=>{e.abort(),clearInterval(s)}},[t,l,i]),(0,s.useMemo)(()=>(function(e,t,n){if(0===e.length)return ds;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 s=r.timestamp;"number"==typeof s&&Number.isFinite(s)&&t.push({index:n,openedAt:s})}return t}(t);if(0===r.length)return ds;let s=[];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&&s.push({key:`${dr}:${t.startedAt}:${t.finishedAt}`,turnIndex:e,provider:"web6",speakerId:`${dr}:${t.conversationId??"unknown"}`,text:a,status:"failed"})}return s.length>0?s:ds})(n,e.messages,i),[n,e.messages,i])},dl="lab:";function dc(e){return e.startsWith(dl)?e.slice(dl.length).split(":",1)[0]||null:null}let dd={now:()=>Date.now(),setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e)};function du(e){return e.multi&&e.options.length>1}function dh(e){return"text"===e.kind?{kind:"text",text:e.value}:{kind:"choice",checked:e.options.flatMap((e,t)=>e.checked?[t]:[]),otherOn:!1,other:""}}function dp(e,t){let n={};for(let[t,r]of e.hidden)dx(n,t,r);return e.fields.forEach((e,r)=>{let s=t[r];if(!e.name||!s)return;let a=function(e,t){if("text"===e.kind){var n,r,s="text"===t.kind?t.text:"";if(("number"===e.type||"range"===e.type)&&""!==s.trim()){let e=Number(s);if(Number.isFinite(e))return e}return s}if("choice"===t.kind){let s,a;return n=new Set(t.checked),r=t.otherOn?t.other:void 0,s=e.other?r?.trim():void 0,a=e.options.flatMap((e,t)=>n.has(t)&&!e.disabled?[e.value]:[]),du(e)?s?[...a,s]:a:s||a[0]}}(e,s);void 0!==a&&dx(n,e.name,a)}),n}function dm(e,t){let n={};for(let r of e.fields){if(!r.name||dv(n,r.name))continue;let e=function(e,t){if("choice"===e.kind){let n=void 0===t||Array.isArray(t)&&0===t.length;if(!e.required||!n)return;return du(e)?{code:"selectAtLeastOne"}:{code:"required"}}let n=void 0===t?"":String(t);if(""===n.trim())return e.required?{code:"required"}:void 0;if("number"===e.type||"range"===e.type){let t=Number(n);if(!Number.isFinite(t))return{code:"enterNumber"};if(void 0!==e.min&&t<e.min)return{code:"min",value:e.min};if(void 0!==e.max&&t>e.max)return{code:"max",value:e.max}}return void 0!==e.minLength&&n.length<e.minLength?{code:"minLength",value:e.minLength}:void 0!==e.maxLength&&n.length>e.maxLength?{code:"maxLength",value:e.maxLength}:"email"!==e.type||/^[^\s@]+@[^\s@]+$/.test(n)?"url"!==e.type||URL.canParse(n)?e.pattern&&(function(e){try{return RegExp(`^(?:${e})$`,"v")}catch{return}})(e.pattern)?.test(n)===!1?{code:"pattern",pattern:e.pattern.length>40?`${e.pattern.slice(0,39)}…`:e.pattern}:void 0:{code:"url"}:{code:"email"}}(r,dv(t,r.name));e&&dx(n,r.name,e)}return n}function df(e){return e.map(e=>e.text).join("")}function dg(e,t,n){if(!e.multi)return{...t,checked:[n],otherOn:!1};let r=t.checked.includes(n)?t.checked.filter(e=>e!==n):[...t.checked,n].sort((e,t)=>e-t);return{...t,checked:r}}function dx(e,t,n){Object.defineProperty(e,t,{value:n,enumerable:!0,writable:!0,configurable:!0})}function dv(e,t){return Object.hasOwn(e,t)?e[t]:void 0}let dy={text:!0,search:!0,tel:!0,url:!0,email:!0,number:!0,password:!0,date:!0,time:!0,"datetime-local":!0,month:!0,week:!0,color:!0,range:!0},db={width:"100%",minWidth:0,padding:"0 10px",borderRadius:"var(--radius-control)",background:"var(--bg)",color:"var(--text)",fontFamily:"var(--seed-font-family)",fontSize:"var(--seed-font-size-t4-static)"},dw={minHeight:36,padding:"0 12px",borderRadius:"var(--radius-control)",background:"var(--bg)",color:"var(--text-muted)",cursor:"pointer"};function dk({spans:e}){return(0,r.jsx)(r.Fragment,{children:e.map((e,t)=>{let n=[];return(e.text.split("\n").forEach((e,t)=>{t>0&&n.push((0,r.jsx)("br",{},`br-${t}`)),n.push(e)}),"code"===e.style)?(0,r.jsx)("code",{style:{padding:"0 4px",borderRadius:4,background:"var(--bg)",fontFamily:"var(--font-mono)",fontSize:"0.92em"},children:n},t):"strong"===e.style?(0,r.jsx)("strong",{style:{fontWeight:600},children:n},t):"em"===e.style?(0,r.jsx)("em",{children:n},t):(0,r.jsx)("span",{children:n},t)})})}function dj({src:e,alt:t}){let{t:n}=(0,F.s)(),[a,i]=(0,s.useState)(!1);return!e||a?(0,r.jsx)("p",{style:{margin:0,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)",overflowWrap:"anywhere"},children:t||n("chat.formImageUnavailable")}):(0,r.jsx)("img",{src:e,alt:t,onError:()=>i(!0),style:{display:"block",maxWidth:"100%",maxHeight:320,height:"auto",objectFit:"contain",borderRadius:"var(--radius-control)"}})}function dS({block:e,id:t}){let n={margin:0,color:"var(--text)",fontSize:"var(--seed-font-size-t4-static)",lineHeight:1.55,overflowWrap:"anywhere"};switch(e.kind){case"text":return(0,r.jsx)("p",{id:t,style:{...n,fontWeight:e.heading?600:400},children:(0,r.jsx)(dk,{spans:e.spans})});case"list":{let t=e.ordered?"ol":"ul";return(0,r.jsx)(t,{style:{...n,paddingInlineStart:22},children:e.items.map((e,t)=>(0,r.jsx)("li",{children:(0,r.jsx)(dk,{spans:e})},t))})}case"pre":return(0,r.jsx)("pre",{tabIndex:0,style:{margin:0,padding:"8px 10px",overflowX:"auto",maxWidth:"100%",borderRadius:"var(--radius-control)",background:"var(--bg)",color:"var(--text)",fontFamily:"var(--font-mono)",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.5},children:e.text});case"table":return(0,r.jsx)("div",{tabIndex:0,style:{maxWidth:"100%",overflowX:"auto",borderRadius:"var(--radius-control)",background:"var(--bg)"},children:(0,r.jsx)("table",{style:{borderCollapse:"collapse",width:"100%",fontSize:"var(--seed-font-size-t3-static)",fontVariantNumeric:"tabular-nums"},children:(0,r.jsx)("tbody",{children:e.rows.map((t,n)=>(0,r.jsx)("tr",{children:t.map((t,s)=>{let a=n<e.headerRows?"th":"td";return(0,r.jsx)(a,{scope:n<e.headerRows?"col":void 0,style:{padding:"6px 10px",background:n<e.headerRows?"var(--bg-hover)":void 0,color:n<e.headerRows?"var(--text-muted)":"var(--text)",fontWeight:n<e.headerRows?600:400,textAlign:"left",verticalAlign:"top",minWidth:72},children:(0,r.jsx)(dk,{spans:t})},s)})},n))})})});case"image":return(0,r.jsx)(dj,{src:e.src,alt:e.alt})}}function dC({field:e,id:t,index:n,error:s,children:a,hasLabel:i}){let{t:l}=(0,F.s)();return(0,r.jsxs)("div",{"data-field":n,style:{display:"grid",gap:6,minWidth:0},children:[(i||e.required)&&(0,r.jsxs)("div",{style:{display:"flex",alignItems:"baseline",gap:8},children:[i&&(0,r.jsx)("label",{id:`${t}-label`,htmlFor:"text"===e.kind||e.select?t:void 0,style:{color:"var(--text)",fontSize:"var(--seed-font-size-t4-static)",fontWeight:600,lineHeight:1.5},children:(0,r.jsx)(dk,{spans:e.label})}),e.required&&(0,r.jsx)("span",{style:{marginLeft:i?0:"auto",color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontWeight:600},children:l("chat.formRequired")})]}),a,s&&(0,r.jsxs)("p",{id:`${t}-error`,style:{margin:0,display:"flex",alignItems:"flex-start",gap:6,color:"var(--danger)",fontSize:"var(--seed-font-size-t3-static)",fontWeight:500,lineHeight:1.45},children:[(0,r.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round","aria-hidden":"true",style:{flex:"none",marginTop:2},children:[(0,r.jsx)("circle",{cx:"7",cy:"7",r:"5.5"}),(0,r.jsx)("path",{d:"M7 4v3.4M7 9.6v.1"})]}),(0,r.jsx)("span",{children:function(e,t){switch(e.code){case"min":case"max":case"minLength":case"maxLength":return t(`chat.formError.${e.code}`,{value:e.value});case"pattern":return t("chat.formError.pattern",{pattern:e.pattern});default:return t(`chat.formError.${e.code}`)}}(s,l)})]})]})}function dN({field:e,id:t,index:n,state:a,error:i,captionId:l,fallbackName:o,onChange:c}){let{t:d}=(0,F.s)(),u=(0,s.useRef)(null);if("choice"!==a.kind)return null;let h=e.label.length>0,p={"aria-labelledby":h?`${t}-label`:l,"aria-label":h||l?void 0:o,"aria-required":e.required||void 0,"aria-invalid":!!i||void 0,"aria-describedby":i?`${t}-error`:void 0};if(e.select&&!e.multi)return(0,r.jsx)(dC,{field:e,id:t,index:n,error:i,hasLabel:h,children:(0,r.jsx)("select",{id:t,...p,value:String(a.checked[0]??""),onChange:t=>c(n,dg(e,a,Number(t.target.value))),style:{...db,height:36},children:e.options.map((e,t)=>(0,r.jsx)("option",{value:t,disabled:e.disabled,children:df(e.label)},t))})});let m=e.multi?"checkbox":"radio",f=(e,t)=>({display:"grid",gridTemplateColumns:"16px minmax(0, 1fr)",alignItems:"start",gap:9,minHeight:40,padding:"9px 10px",borderRadius:"var(--radius-control)",background:e?"var(--bg-selected)":"transparent",color:t?"var(--text-dim)":"var(--text)",cursor:t?"not-allowed":"pointer",fontSize:"var(--seed-font-size-t4-static)",lineHeight:1.5,overflowWrap:"anywhere"}),g={width:16,height:16,margin:"3px 0 0",accentColor:"var(--seed-color-fg-neutral)"},x=`${t}-choice`;return(0,r.jsx)(dC,{field:e,id:t,index:n,error:i,hasLabel:h,children:(0,r.jsxs)("div",{role:e.multi?"group":"radiogroup",...p,style:{display:"grid",gap:4},children:[e.options.map((t,s)=>{let i=a.checked.includes(s);return(0,r.jsxs)("label",{style:f(i,t.disabled),children:[(0,r.jsx)("input",{type:m,name:x,checked:i,disabled:t.disabled,"aria-required":!!e.required&&!e.multi||void 0,onChange:()=>c(n,dg(e,a,s)),style:g}),(0,r.jsx)("span",{children:(0,r.jsx)(dk,{spans:t.label})})]},s)}),e.other&&(0,r.jsxs)("div",{style:{display:"grid",gap:6},children:[(0,r.jsxs)("label",{style:f(a.otherOn,!1),children:[(0,r.jsx)("input",{type:m,name:x,checked:a.otherOn,onChange:()=>{c(n,e.multi?{...a,otherOn:!a.otherOn}:{...a,checked:[],otherOn:!0}),a.otherOn&&e.multi||u.current?.focus()},style:g}),(0,r.jsx)("span",{children:d("chat.formOther")})]}),(0,r.jsx)("input",{ref:u,type:"text",value:a.other,"aria-label":d("chat.formOther"),placeholder:d("chat.formOtherPlaceholder"),onChange:t=>{var r;let s;return c(n,(s=""!==(r=t.target.value).trim(),{...a,other:r,otherOn:!!s||a.otherOn,checked:s&&!e.multi?[]:a.checked}))},style:{...db,height:36,width:"calc(100% - 35px)",marginInlineStart:35}})]})]})})}function dT({field:e,id:t,index:n,state:s,error:a,captionId:i,fallbackName:l,onChange:o}){if("text"!==s.kind)return null;let c=e.label.length>0,d=Object.hasOwn(dy,e.type)?e.type:"text",u={id:t,value:s.text,placeholder:e.placeholder||void 0,"aria-labelledby":c?void 0:i,"aria-label":c||i?void 0:l,"aria-required":e.required||void 0,"aria-invalid":!!a||void 0,"aria-describedby":a?`${t}-error`:void 0},h=a?"color-mix(in srgb, var(--danger) 14%, var(--bg))":void 0;return(0,r.jsx)(dC,{field:e,id:t,index:n,error:a,hasLabel:c,children:e.multiline?(0,r.jsx)("textarea",{...u,rows:Math.max(2,e.rows),onChange:e=>o(n,{kind:"text",text:e.target.value}),style:{...db,padding:"8px 10px",...h?{background:h}:{},lineHeight:1.5,resize:"vertical"}}):(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10},children:[(0,r.jsx)("input",{...u,type:d,min:"number"===d||"range"===d?e.min:void 0,max:"number"===d||"range"===d?e.max:void 0,step:"number"===d?"any":void 0,onChange:e=>o(n,{kind:"text",text:e.target.value}),style:{...db,height:"color"===d?40:36,...h?{background:h}:{},..."range"===d?{padding:0}:{},fontVariantNumeric:"tabular-nums"}}),"range"===d&&(0,r.jsx)("output",{htmlFor:t,style:{minWidth:32,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)",fontVariantNumeric:"tabular-nums"},children:s.text})]})})}function dI({request:e,onRespond:t,onActivity:n,delivery:a}){let{t:i}=(0,F.s)(),l=(0,s.useId)(),o=e.form,[c,d]=(0,s.useState)(()=>o.fields.map(dh)),u=(0,s.useRef)(c),[h,p]=(0,s.useState)(!1),m=(0,s.useRef)(null),f=(0,s.useRef)(n);f.current=n;let g=(0,s.useRef)(e);g.current=e;let x=a?.status==="sending",v=(0,s.useRef)(null);if(null===v.current){let e=Array.from(crypto.getRandomValues(new Uint8Array(12)),e=>e.toString(16).padStart(2,"0")).join(""),t=0;v.current=function(e,t=dd){let n,r=-1/0,s=!1,a=()=>{s&&t.clearTimeout(n),s=!1,r=t.now(),e()};return{notify(){let e=1e3-(t.now()-r);e<=0?a():s||(s=!0,n=t.setTimeout(a,e))},cancel(){s&&t.clearTimeout(n),s=!1}}}(()=>{var n,r;let s=g.current;t+=1,f.current?.(s,(n=t,r=dp(s.form,u.current),`activity:form:v2:${e}:${n}:${JSON.stringify(r)}`))})}(0,s.useEffect)(()=>()=>v.current?.cancel(),[]);let y=(0,s.useCallback)((e,t)=>{let n=u.current.slice();n[e]=t,u.current=n,d(n),g.current.timeout&&f.current&&v.current?.notify()},[]),b=dp(o,c),w=h?dm(o,b):{},k=Object.keys(w).length>0,j=()=>{if(x)return;let n=dp(o,u.current),r=dm(o,n);if(Object.keys(r).length>0){p(!0);let e=o.fields.findIndex(e=>""!==e.name&&void 0!==dv(r,e.name));m.current?.querySelector(`[data-field="${e}"] input, [data-field="${e}"] select, [data-field="${e}"] textarea`)?.focus();return}t(e,{value:JSON.stringify(n)})};return(0,r.jsxs)("div",{"data-ask-form":"",style:{display:"flex",flexDirection:"column",minHeight:0},children:[(0,r.jsxs)("div",{style:{padding:"12px 16px"},children:[(0,r.jsx)("div",{style:{color:"var(--text)",fontSize:"var(--seed-font-size-t4-static)",fontWeight:600},children:i("chat.agentQuestion")}),(0,r.jsx)("div",{style:{marginTop:2,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)"},children:i("chat.agentFormHint")}),e.timeout?(0,r.jsx)("div",{style:{marginTop:2,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)"},children:i("chat.askFormAutoSubmitHint",{seconds:Math.round(e.timeout/1e3)})}):null]}),(0,r.jsx)("div",{ref:m,onKeyDown:e=>{(e.metaKey||e.ctrlKey)&&"Enter"===e.key&&j()},style:{flex:"1 1 auto",minHeight:0,overflowY:"auto",overscrollBehavior:"contain",padding:16},children:(0,r.jsx)("div",{style:{display:"grid",gap:24,minWidth:0},children:o.sections.map((e,t)=>{let n,s=df(e.title);return(0,r.jsxs)("section",{"aria-labelledby":s?`${l}-s${t}`:void 0,style:{display:"grid",gap:12,minWidth:0},children:[s&&(0,r.jsx)("h3",{id:`${l}-s${t}`,style:{margin:0,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)",fontWeight:600,lineHeight:1.4},children:(0,r.jsx)(dk,{spans:e.title})}),e.blocks.map((e,a)=>{var i;let d;if("field"!==e.kind){let s=`${l}-s${t}b${a}`;return n="text"===e.kind?s:void 0,(0,r.jsx)(dS,{block:e,id:s},a)}let u=o.fields[e.index],p=n;n=void 0;let m=(i=e.index,d=o.fields[i],{id:`${l}-f${i}`,index:i,state:c[i],error:h&&d.name?dv(w,d.name):void 0,captionId:p,fallbackName:s||d.name,onChange:y});return"choice"===u.kind?(0,r.jsx)(dN,{...m,field:u},a):(0,r.jsx)(dT,{...m,field:u},a)})]},t)})})}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",alignItems:"center",justifyContent:"flex-end",gap:8,padding:"12px 16px"},children:[k&&(0,r.jsx)("p",{role:"alert",style:{margin:0,marginRight:"auto",color:"var(--danger)",fontSize:"var(--seed-font-size-t3-static)"},children:i("chat.formInvalid")}),(0,r.jsx)("button",{type:"button",onClick:()=>t(e,{cancelled:!0}),style:dw,children:i("chat.cancel")}),(0,r.jsx)("button",{type:"button","aria-disabled":x||void 0,onClick:j,style:{minHeight:36,padding:"0 14px",borderRadius:"var(--radius-control)",background:x?"var(--seed-color-bg-disabled)":"var(--seed-color-bg-neutral-inverted)",color:x?"var(--seed-color-fg-disabled)":"var(--seed-color-fg-neutral-inverted)",cursor:x?"not-allowed":"pointer",fontWeight:600},children:i(x?"chat.responseSending":"chat.submitAnswer")})]})]})}let dM={steer:"delivery.kind.steer",followUp:"delivery.kind.followUp"},dE={sending:"delivery.stage.sending",accepted:"delivery.stage.accepted",delivered:"delivery.stage.delivered",unconfirmed:"delivery.stage.unconfirmed",failed:"delivery.stage.failed"};function d$({rows:e,removeLabel:t,onRemove:n}){let a,{st:i}=sz(),[l,o]=(0,s.useState)(!1),{rows:c,hidden:d}=(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,s.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?i("delivery.showRecent",{count:4}):i("delivery.showOlder",{count:d})}),(0,r.jsx)("ul",{className:"answer-delivery-list","aria-live":"polite",children:c.map(e=>{let s=ar(e.text),a=[s?[s.message,s.documents.map(e=>e.name).join(", ")].filter(Boolean).join(" \xb7 "):e.text.trim(),e.images>0?i(1===e.images?"delivery.images.one":"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:i(dM[e.kind])}),(0,r.jsx)("span",{className:"answer-delivery-text",title:a,children:a}),(0,r.jsx)("span",{className:"answer-delivery-stage",children:i(dE[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)})})]})}async function dR(e,t){let n=await fetch(e,{cache:"no-store",...t}),r=await n.json();if(!n.ok)throw Error(r.error||`HTTP ${n.status}`);return r}let dL=(0,s.forwardRef)(function({value:e,token:t,cwd:n,sessionTitle:a,style:i,maxHeight:l,onReplace:o,onClose:c},d){let{t:u}=(0,F.s)(),[h,p]=(0,s.useState)([]),[m,f]=(0,s.useState)(!0),[g,x]=(0,s.useState)(!1),[v,y]=(0,s.useState)(null),[b,w]=(0,s.useState)(null),[k,j]=(0,s.useState)(-1),S=(0,s.useRef)([]),C=t.query.toLowerCase(),N=h.filter(e=>`${e.title}
18
18
  ${e.body}`.toLowerCase().includes(C)),T=e.slice(0,t.start)+e.slice(t.end),I=!!T.trim(),M=N.length+ +!!I,E=(0,s.useCallback)(async()=>{p((await dR("/api/saved-prompts")).prompts)},[]);(0,s.useEffect)(()=>{let e=!1;return dR("/api/saved-prompts").then(t=>{e||p(t.prompts)}).catch(t=>{e||y(String(t.message??t))}).finally(()=>{e||f(!1)}),()=>{e=!0}},[]),(0,s.useEffect)(()=>{j(N.length>0?0:-1),w(null)},[C,h,N.length,I]),(0,s.useEffect)(()=>{S.current[k]?.scrollIntoView({block:"nearest"})},[k]);let $=r=>{var s,i;let l=new Date,c=`${l.getFullYear()}-${String(l.getMonth()+1).padStart(2,"0")}-${String(l.getDate()).padStart(2,"0")}`,d=(s=r.body,i={project_name:n?.replace(/[\\/]+$/,"").split(/[\\/]/).pop(),cwd:n,session_name:a,date:c},s.replace(/\{\{\s*([a-zA-Z_][\w]*)\s*\}\}/g,(e,t)=>(Object.hasOwn(i,t)?i[t]:void 0)||e));o(e,e.slice(0,t.start)+d+e.slice(t.end),t.start+d.length)},R=async()=>{if(!g&&I){x(!0),y(null);try{await dR("/api/saved-prompts",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({body:T})}),o(e,T,t.start,!0),await E()}catch(e){y(e instanceof Error?e.message:String(e))}finally{x(!1)}}},L=async e=>{if(!g){if(b!==e)return void w(e);x(!0),y(null);try{await dR(`/api/saved-prompts/${encodeURIComponent(e)}`,{method:"DELETE"}),p(t=>t.filter(t=>t.id!==e)),w(null),await E()}catch(e){y(e instanceof Error?e.message:String(e))}finally{x(!1)}}};(0,s.useImperativeHandle)(d,()=>({handleKeyDown(e){if("Escape"===e.key)return c(),e.preventDefault(),!0;if(("ArrowDown"===e.key||"ArrowUp"===e.key)&&M>0)return e.preventDefault(),j(t=>"ArrowDown"===e.key?Math.min(M-1,t+1):t<0?M-1:Math.max(0,t-1)),!0;if("Tab"===e.key||"Enter"===e.key&&!e.shiftKey){if(k>=0&&k<M)return e.preventDefault(),g||(N[k]?$(N[k]):R()),!0;"Enter"===e.key&&c()}return!1}}));let P=e=>({width:"100%",minWidth:0,minHeight:44,borderRadius:"var(--radius-control)",padding:"8px",background:e?"var(--bg-selected)":"none",color:"var(--text)",textAlign:"left",cursor:"pointer",fontSize:12});return(0,r.jsxs)("div",{id:"saved-prompt-menu",role:"region","aria-label":u("savedPrompts.title"),"data-saved-prompt-menu":"",onMouseDown:e=>e.preventDefault(),onKeyDown:e=>{"Escape"===e.key&&(e.stopPropagation(),c())},style:{position:"absolute",left:0,right:0,zIndex:120,background:"var(--bg)",borderRadius:"var(--radius-surface)",boxShadow:"var(--shadow-float)",display:"flex",flexDirection:"column",overflow:"hidden",maxHeight:l,...i},children:[(0,r.jsx)("div",{style:{padding:"8px 10px",fontSize:11,color:"var(--text-dim)",flexShrink:0},children:m?u("savedPrompts.loading"):u("savedPrompts.title")}),(0,r.jsxs)("div",{style:{overflowY:"auto",minHeight:0,padding:4},children:[!m&&0===N.length&&(0,r.jsx)("div",{style:{padding:8,fontSize:12,color:"var(--text-dim)"},children:u("savedPrompts.empty")}),N.map((e,t)=>(0,r.jsxs)("div",{style:{display:"flex",gap:4,alignItems:"center"},children:[(0,r.jsxs)("button",{type:"button",ref:e=>{S.current[t]=e},disabled:g,"data-saved-prompt-id":e.id,onClick:()=>$(e),onMouseEnter:()=>j(t),style:P(t===k),children:[(0,r.jsx)("span",{style:{display:"block",overflowWrap:"anywhere"},children:e.title}),(0,r.jsx)("span",{style:{display:"block",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-dim)",fontSize:11},children:e.body.replace(/\s+/g," ")})]}),(0,r.jsx)("button",{type:"button",disabled:g,"data-delete-prompt":e.id,"aria-label":`${u("savedPrompts.delete")}: ${e.title}`,onClick:()=>void L(e.id),style:{...P(!1),width:"auto",flexShrink:0,color:"var(--danger, var(--text))"},children:u(b===e.id?"savedPrompts.confirmDelete":"savedPrompts.delete")}),b===e.id&&(0,r.jsx)("button",{type:"button",onClick:()=>w(null),style:{...P(!1),width:"auto",flexShrink:0},children:u("savedPrompts.cancel")})]},e.id)),I&&(0,r.jsx)("button",{type:"button","data-save-current-prompt":"",disabled:g||m,ref:e=>{S.current[N.length]=e},onClick:()=>void R(),onMouseEnter:()=>j(N.length),style:P(k===N.length),children:u("savedPrompts.save")})]}),v&&(0,r.jsx)("div",{role:"alert",style:{padding:"6px 10px",fontSize:12,color:"var(--danger, var(--text))",overflowWrap:"anywhere"},children:u("savedPrompts.error",{error:v})}),(0,r.jsx)("div",{style:{padding:"6px 10px",fontSize:10,color:"var(--text-dim)",overflowWrap:"anywhere",overflowY:"auto",flexShrink:0,maxHeight:"40%"},children:u("savedPrompts.hint")})]})}),dP=(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"})]}),dA=(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 d_({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?dP:dA})})})}let dF=RegExp("^(?:아|어|음|응|네|자|그럼|이제|일단|그만|좀|알았어|알겠어|아니|그래)*(?:(?:통화|전화)(?:를|좀|그만)*)?(?:좀|그만)*(?:끊어|끊어봐|끊을게|끊자|끊겠습니다|끊으라고)(?:줘|주세요|요)?$|^(?:아|어|음|응|네|자|그럼|이제|일단|그만|좀|알았어|알겠어|아니|그래)*(?:통화|전화)(?:를|좀|그만)*(?:종료|종료해|종료해봐|종료할게|종료하자|종료하라고)(?:줘|주세요|요)?$","u"),dO=["normal","slow"],dz={idle:!0,connecting:!0,live:!0,working:!0,error:!0,closed:!0};function dD(e){if("complete"===e.iceGatheringState)return Promise.resolve();let{promise:t,resolve:n}=Promise.withResolvers(),r=()=>{clearTimeout(a),e.removeEventListener("icegatheringstatechange",s),n()},s=()=>{"complete"===e.iceGatheringState&&r()},a=setTimeout(r,3e3);return e.addEventListener("icegatheringstatechange",s),t}function dW(e,t){return 401===e||"live-auth"===t?"auth":502===e||"live-upstream"===t?"upstream":"failed"}let dH={unsupported:"chat.liveUnsupported","mic-denied":"chat.liveMicDenied","mic-unavailable":"chat.liveMicUnavailable",auth:"chat.liveAuthRequired",upstream:"chat.liveUpstreamFailed",failed:"chat.liveFailed"},dU=(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"})]}),dB=(0,r.jsx)(r.Fragment,{children:(0,r.jsx)("rect",{x:"4",y:"4",width:"16",height:"16",rx:"3"})});function dq({sessionId:e,onEnsureSession:t,onTranscriptPersisted:n}){let{t:a}=(0,F.s)(),i=function(e,t,n){let{locale:r}=(0,F.s)(),[a,i]=(0,s.useState)("idle"),[l,o]=(0,s.useState)(null),[c,d]=(0,s.useState)(null),[u,h]=(0,s.useState)(null),[p,m]=(0,s.useState)(null),[f,g]=(0,s.useState)(!1),x=(0,s.useRef)(null),v=(0,s.useRef)(null),y=(0,s.useRef)(null),b=(0,s.useRef)(null),w=(0,s.useRef)(null),k=(0,s.useRef)(0);(0,s.useEffect)(()=>{m("u">typeof RTCPeerConnection&&"u">typeof navigator&&"function"==typeof navigator.mediaDevices?.getUserMedia)},[]);let j=(0,s.useCallback)(e=>{k.current+=1;let t=w.current;for(let e of(w.current=null,b.current?.close(),b.current=null,x.current?.close(),x.current=null,v.current?.getTracks()??[]))e.stop();v.current=null;let n=y.current;y.current=null,n&&(n.srcObject=null,n.remove()),t&&fetch(`/api/live/call/${encodeURIComponent(t)}`,{method:"DELETE"}).catch(()=>{}),i(e),h(null),g(!1)},[]),S=(0,s.useCallback)((e,t)=>{o(e),d(t??null),j("error")},[j]),C=(0,s.useCallback)(async()=>{let s,a=k.current+1;k.current=a,o(null),d(null),g(!0),i("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{s=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 s.getTracks())e.stop();return}v.current=s;try{let e,t,o=new RTCPeerConnection;for(let e of(x.current=o,s.getTracks()))o.addTrack(e,s);let c=document.createElement("audio");if(c.autoplay=!0,y.current=c,o.ontrack=e=>{let[t]=e.streams;t&&(c.srcObject=t)},await o.setLocalDescription(await o.createOffer()),await dD(o),k.current!==a)return;let d=o.localDescription?.sdp;if(!d)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:d,locale:r})}),p=await u.json().catch(()=>({})),m="",f="";if(p&&"object"==typeof p&&("error"in p&&(e=p.error),"message"in p&&"string"==typeof p.message&&(t=p.message),"callId"in p&&"string"==typeof p.callId&&(m=p.callId),"sdp"in p&&"string"==typeof p.sdp&&(f=p.sdp)),!u.ok||!m||!f){k.current===a&&(g(!1),S(dW(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)}`);b.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!==dz[r]))return;"closed"===t.state?j("closed"):i(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;h({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&&dF.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")},i("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,s.useCallback)(()=>{if("idle"===a||"closed"===a||"error"===a){f||C();return}j("idle")},[f,a,C,j]);return(0,s.useEffect)(()=>()=>j("closed"),[j]),{state:a,failure:l,detail:c,transcript:u,supported:p,toggle:N}}(e,t,n),l="connecting"===i.state||"live"===i.state||"working"===i.state,o="connecting"===i.state?"chat.liveConnecting":"working"===i.state?"chat.liveWorking":"live"===i.state?"chat.liveOn":null,c=a(l?"chat.liveStop":"chat.liveStart"),d=!1===i.supported?dH.unsupported:i.failure?dH[i.failure]:null,u=!!(e||t),h=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:[d&&(0,r.jsx)("span",{role:"status",style:{fontSize:11,color:"var(--danger)",maxWidth:220,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:i.detail??void 0,children:a(d)}),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:i.toggle,disabled:!i.supported||!u,"aria-pressed":l,title:h?a(h):c,"aria-label":h?a(h):c,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?dB:dU})})]})}let dV={display:"inline-flex",alignItems:"center",flexShrink:0,height:32,padding:"0 10px",border:0,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 dK({sessionId:e}){let{t}=(0,F.s)(),[n,a]=(0,s.useState)(null);return((0,s.useEffect)(()=>{if(!e)return void a(null);let t=!1,n=0,r=!1,s=async()=>{if("visible"===document.visibilityState)try{let n=await fetch("/api/gpt6/handles",{cache:"no-store"});if(!n.ok)return;let s=await n.json();if(t)return;let i=Array.isArray(s.handles)?s.handles:[],l=i.find(t=>t.sessionId===e&&"active"===t.status)?.handle??null;r=null!==l,a(l)}catch{}},i=async()=>{await s(),t||(n=window.setTimeout(()=>void i(),r?5e3:3e4))};return i(),document.addEventListener("visibilitychange",s),()=>{t=!0,window.clearTimeout(n),document.removeEventListener("visibilitychange",s)}},[e]),n)?(0,r.jsx)("span",{style:dV,title:t("gpt6.boundBadgeHint",{handle:n}),children:t("gpt6.boundBadge",{handle:n})}):null}let dJ=new Map,dG="ompweb-drafts-for-reload-v1",dY=!1,dZ=new Map,dQ=new Map,dX="\0stale",d0=new Map,d1=0,d2=new Map,d4=new Map,d8=new Map,d5=new Map,d6=new Map,d3=(e,t,n)=>ad(e,t,n.length?{sentAttachmentIds:n}:{}),d7=null,d9=!1;function ue(){if(dY||"u"<typeof sessionStorage)return;dY=!0;let e=sessionStorage.getItem(dG);if(e){sessionStorage.removeItem(dG);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)&&(dJ.set(e[0],un(t)),"string"==typeof t.draftId&&t.draftId&&(dZ.set(e[0],t.draftId),dQ.set(t.draftId,dX)),uu(e[0]))}}catch{}}}function ut(){if("u"<typeof sessionStorage)return{ok:!1,error:"sessionStorage unavailable"};try{return sessionStorage.setItem(dG,JSON.stringify([...dJ.entries()].map(([e,t])=>{let n=dZ.get(e);return[e,n?{...un(t),draftId:n}:un(t)]}))),{ok:!0}}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}}function un(e){return{value:e.value,images:e.images.map(e=>({...e})),documents:e.documents.map(e=>({...e}))}}function ur(e){return!e.value&&0===e.images.length&&0===e.documents.length}function us(e){ue();let t=dJ.get(e);return t?un(t):null}function ua(e,t){ue(),ur(t)?dJ.delete(e):dJ.set(e,un(t)),uu(e)}function ui(e){dJ.delete(e),uu(e)}function ul(e,t,n,r,s,a=[]){let i=[...t??[],...r].filter(rs).slice(0,10).map(({data:e,mimeType:t})=>({data:e,mimeType:t})),l=ae([...s??[],...a]);return{value:e.trim()?n.trim()?`${e}
19
19
 
20
- ${n}`:e:n,images:i,documents:l}}function uo(e,t,n){if(e===t)return n?un(n):us(t);let r=us(e),s=n&&!ur(n)?un(n):r??(n?un(n):null),a=us(t),i=dZ.get(e);if(dZ.delete(e),i&&!dZ.has(t)&&dZ.set(t,i),ui(e),!s)return a;let l=a?ul(a.value,a.images,s.value,s.images,a.documents,s.documents):s;return ua(t,l),un(l)}function uc(e){let t=[];for(let n of e??[])n.attachmentId&&!t.includes(n.attachmentId)&&t.push(n.attachmentId);return t}function ud(e){ue();let t=dZ.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)}`}(),dZ.set(e,t)),t}function uu(e){let t=uc(dJ.get(e)?.documents),n=t.length?ud(e):dZ.get(e);for(let[e,n]of d4){for(let e of t)n.delete(e);0===n.size&&d4.delete(e)}let r=`${n??""}|${t.join(",")}`;d5.get(e)!==r&&(0!==t.length||n?d5.set(e,r):d5.delete(e),uv())}async function uh(e){let t=ud(e);d2.set(t,(d2.get(t)??0)+1),await d6.get(t);let n=!1;return{draftId:t,end(e){if(n)return;n=!0;let r=(d2.get(t)??1)-1;if(r>0?d2.set(t,r):d2.delete(t),e){let n=d4.get(t)??new Set;n.add(e),d4.set(t,n)}dQ.set(t,dX),uv()}}}function up(e,t){let n=d8.get(e);if(!n)return[];for(let e of t)n.delete(e);return 0===n.size&&d8.delete(e),[...n].sort()}async function um(){if(!d3)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 dZ)t(n,uc(dJ.get(e)?.documents));for(let{draftId:e,ids:n}of d0.values())t(e,n);for(let[e,n]of d4)t(e,n);for(let e of dQ.keys())t(e,[]);for(let e of d8.keys())t(e,[]);return new Map([...e].map(([e,t])=>[e,[...t].sort()]))}()].filter(([e,t])=>{if(d2.has(e))return!1;let n=dQ.get(e);return up(e,t).length>0||(0===t.length?void 0!==n:n!==t.join(","))}),t=d2.size>0,n=!1;for(let[r,s]of[...e.filter(([,e])=>e.length>0),...e.filter(([,e])=>0===e.length)]){if(0===s.length&&t)continue;let e=up(r,s),a=d3(r,s,e).then(()=>{0===s.length?dQ.delete(r):dQ.set(r,s.join(","));let t=d8.get(r);if(t){for(let n of e)t.delete(n);0===t.size&&d8.delete(r)}},()=>{n=!0,s.length>0&&(t=!0)});d6.set(r,a),await a,d6.get(r)===a&&d6.delete(r)}n?function(){if(ux)return;ux=!0;let e=setTimeout(()=>{ux=!1,uv()},ug);"object"==typeof e&&"unref"in e&&e.unref(),ug=Math.min(2*ug,6e4)}():ug=uf}let uf=5e3,ug=5e3,ux=!1;function uv(){if(d3){if(d7){d9=!0;return}d7=Promise.resolve().then(um).finally(()=>{d7=null,d9&&(d9=!1,uv())})}}let uy=Math.floor(Number.MAX_SAFE_INTEGER/1048576),ub=Object.freeze({uploadLimitMb:100,autoCleanupEnabled:!0,orphanGraceDays:7});function uw(e){return"number"==typeof e&&Number.isSafeInteger(e)&&e>=1&&e<=uy}async function uk(e){let t,n=await e.json().catch(()=>null);if(!e.ok||!n||!uw(n.uploadLimitMb)||"boolean"!=typeof n.autoCleanupEnabled)throw Error("string"==typeof n?.error?n.error:`HTTP ${e.status}`);return{uploadLimitMb:uw((t=n&&"object"==typeof n?n:{}).uploadLimitMb)?t.uploadLimitMb:ub.uploadLimitMb,autoCleanupEnabled:"boolean"==typeof t.autoCleanupEnabled?t.autoCleanupEnabled:ub.autoCleanupEnabled,orphanGraceDays:7}}async function uj(e={}){return uk(await fetch("/api/attachment-settings",{cache:"no-store",signal:e.signal}))}async function uS(e){return uk(await fetch("/api/attachment-settings",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}))}function uC(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 uN(e){let t=0;for(let n=0;n<e.length;n++)"/"===e[n]&&t++;return t}function uT(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}function uI(e,t){let n=t?`${e}/`:e;return n.includes(" ")?`@"${n}" `:`@${n} `}function uM(e,t,n){let r=Math.max(1,Math.min(t,n)),s=Math.max(1,Math.max(t,n)),a=e.includes(" ")?`@"${e}"`:`@${e}`,i=r===s?`:${r}`:`:${r}-${s}`;return`${a}${i} `}let uE="omp-web:model-picks";function u$(){try{let e=JSON.parse(window.localStorage.getItem(uE)??"{}");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 uR(e,t,n,r,s={}){let a=s.gap??8,i=s.margin??8,l=s.prefer??"above",o=Math.min(s.minHeight??120,Math.max(0,n-2*i)),c=Math.max(0,e-a-i),d=Math.max(0,n-t-a-i),u="above"===l?c:d,h="above"===l?d:c,p=u>=r||u>=h;return{side:p?l:"above"===l?"below":"above",maxHeight:Math.max(o,Math.min(r,p?u:h))}}function uL(e,t,n){return Math.min(e*t,n)}function uP(e,t,n){let{viewportFraction:r,cap:a,gap:i,margin:l,minHeight:o,prefer:c}=n,[d,u]=(0,s.useState)({side:c??"above",maxHeight:a}),h=(0,s.useCallback)(()=>{let t=e.current;if(!t)return;let n=window.visualViewport?.height??window.innerHeight,s=t.getBoundingClientRect(),d=uR(s.top,s.bottom,n,uL(n,r,a),{gap:i,margin:l,minHeight:o,prefer:c});u(e=>e.side===d.side&&e.maxHeight===d.maxHeight?e:d)},[e,a,i,l,o,c,r]);return(0,s.useEffect)(()=>{if(!t)return;h();let n=e.current,r=n?new ResizeObserver(h):null;return n&&r&&r.observe(n),window.addEventListener("resize",h),window.addEventListener("scroll",h,!0),window.visualViewport?.addEventListener("resize",h),window.visualViewport?.addEventListener("scroll",h),()=>{r?.disconnect(),window.removeEventListener("resize",h),window.removeEventListener("scroll",h,!0),window.visualViewport?.removeEventListener("resize",h),window.visualViewport?.removeEventListener("scroll",h)}},[e,h,t]),d}var uA=n(14755);let u_="omp-web:model-roles-expanded";async function uF(e,t,n,r,s,a,i){let l=e.slice(1).split(/\s/,1)[0];try{let o=t?.length?t:await i?.()??[],c=[...uZ,...o].find(e=>e.name===l||"aliases"in e&&e.aliases?.includes(l));if(a&&(!c||"builtin"===c.source))return s(`/${l} cannot run with attachments. Remove them and retry.`),!1;let d=await n?.(e);if(d?.handled){if(d.error)return!1;return d.prompt&&r(d.prompt),!0}if(c&&"builtin"!==c.source)return r(e),!0;return s(`/${l} is not available in this web session.`),!1}catch(e){return s(e instanceof Error?e.message:String(e)),!1}}function uO(e){let t=e.transcription?.state;return"planning"===t||"confirm"===t||"running"===t}let uz=["off","default","full"],uD={off:"none",default:"default",full:"full"},uW=uA.IN.join(" \xb7 "),uH=uA.C1.filter(e=>!uA.IN.includes(e)).join(" \xb7 ");function uU(e){return"above"===e?{bottom:"calc(100% + 8px)"}:{top:"calc(100% + 8px)"}}let uB=new Intl.Collator(void 0,{numeric:!0,sensitivity:"base"}),uq=0,uV={"text/markdown":"Markdown","text/plain":"Text","application/pdf":"PDF"};function uK(e,t){return uB.compare(e.name||e.modelId,t.name||t.modelId)||uB.compare(e.provider,t.provider)||uB.compare(e.modelId,t.modelId)}let uJ=["auto","off","minimal","low","medium","high","xhigh","max"],uG=["low","medium","high","xhigh"],uY={auto:"chat.thinkingAuto",off:"chat.thinkingOff",minimal:"chat.thinkingMinimal",low:"chat.thinkingLow",medium:"chat.thinkingMedium",high:"chat.thinkingHigh",xhigh:"chat.thinkingXhigh",max:"chat.thinkingMax"},uZ=[{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"}],uQ=["builtin","extension","custom","mcp_prompt","prompt","file","skill"],uX={builtin:"chat.builtIn",extension:"chat.extensions",custom:"chat.customCommands",mcp_prompt:"chat.mcpPrompts",prompt:"chat.prompts",file:"chat.fileCommands",skill:"chat.skills"},u0={builtin:0,extension:1,custom:2,mcp_prompt:3,prompt:4,file:5,skill:6};function u1(e,t,n){let r=e.name.toLowerCase(),s=u2(e,n).toLowerCase();return r===t?0:r.startsWith(t)?1:r.includes(t)?2:s.includes(t)?3:4}function u2(e,t){return"descriptionKey"in e?t(e.descriptionKey):e.description??""}function u4(e,t){return"skill"===e.source&&!!e.name.startsWith("skill:")&&!0===t[e.name.slice(6)]}function u8(e){return{data:e.data,mimeType:e.mimeType}}function u5(e){return{...e,previewUrl:`data:${e.mimeType};base64,${e.data}`}}function u6(e){return(e??[]).filter(rs).slice(0,10).map(u5)}let u3=/^File saved at: (.+)\n\(([^,\n]+), (\d+) bytes\)/,u7="\n\nTranscript of the audio ";function u9(e){return ae(e).map(e=>{let t=al(e),n="audio"===t&&e.attachmentId&&!e.text.includes(u7)?u3.exec(e.text):null;return{...e,id:++uq,status:"ready",..."audio"===t||"file"===t?{stored:t}:{},...n?{storedInfo:{path:n[1],mimeType:n[2],size:Number(n[3])}}:{}}})}function he({name:e,mimeType:t,size:n,text:r,attachmentId:s}){return s?{name:e,mimeType:t,size:n,text:r,attachmentId:s}:{name:e,mimeType:t,size:n,text:r}}function ht(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 hn extends Error{constructor(e,t,n,r){super(e),this.code=t,this.completedParts=n,this.parts=r}}let hr="composer:unkeyed";async function hs(e){let t=await e.json().catch(()=>null),n=t&&"object"==typeof t?{...t}:{};if(e.ok)return n;let r="number"==typeof n.completedParts?n.completedParts:null,s="number"==typeof n.parts?n.parts:null;throw new hn("string"==typeof n.error?n.error:`HTTP ${e.status}`,"string"==typeof n.code?n.code:null,r,s)}function ha(e){e.previewUrl.startsWith("blob:")&&URL.revokeObjectURL(e.previewUrl)}function hi({tone:e,title:t,body:n}){let s="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:0,borderRadius:"var(--radius-control)",background:`var(--${s}-soft)`,color:`var(--${s})`,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 hl({error:e}){return e?(0,r.jsx)(hi,{tone:"error",title:"Model error",body:e}):null}function ho({warnings:e}){return e&&0!==e.length?(0,r.jsx)(hi,{tone:"warning",title:e.length>1?"Model scope warnings":"Model scope warning",body:e.join("\n")}):null}let hc=(0,s.forwardRef)(function({onSend:e,onAbort:t,onSteer:n,onFollowUp:a,isStreaming:i,model:o,isAutoModelSelection:c,modelNames:d,modelList:u,modelError:h,modelScopeWarnings:p,onModelChange:m,onMainPresetChange:f,mainPresetActiveAlias:g,modelRoles:x,onRoleModelChange:v,modelSwitching:y,onCompact:b,onAbortCompaction:w,isCompacting:k,compactError:j,compactResult:S,toolPreset:C,onToolPresetChange:N,thinkingLevel:T,effectiveThinkingLevel:I,outputTokensPerSecond:M=null,outputSpeedLive:E=!1,thinkingCeiling:$,onThinkingLevelChange:R,availableThinkingLevels:L,thinkingLevelMap:P,fastMode:A=null,fastModeBusy:_=!1,onFastModeToggle:O,retryInfo:z,deliveryRows:D=[],inputHistory:W=[],onRecallQueue:H,onRemoveQueuedMessage:B,slashCommands:q,slashCommandsLoading:V,onLoadSlashCommands:K,onBuiltinCommand:J,soundEnabled:G,onSoundToggle:Y,onAudioUnlock:Z,onPromptWithStreamingBehavior:Q,draftKey:X,cwd:ee,sessionTitle:et,sessionId:en,onEnsureSession:er,onLiveTranscriptPersisted:es,startPlace:ea,notice:ei},el){let eo,ec,ed,eu,eh,ep,em,ef,eg,ex,{t:ev}=(0,F.s)();sF();let{st:ey}=sz(),eb=D.some(e=>e.removable),ew=U(),[ek,ej]=(0,s.useState)(()=>X?us(X)?.value??"":""),[eS,eC]=(0,s.useState)(!1),[eN,eT]=(0,s.useState)(null),[eI,eM]=(0,s.useState)(""),[eE,e$]=(0,s.useState)({});(0,s.useEffect)(()=>{eS&&e$(u$())},[eS]);let[eR,eL]=(0,s.useState)(!1);(0,s.useEffect)(()=>{if(eS)try{eL("1"===window.localStorage.getItem(u_))}catch{}},[eS]);let eP=()=>{eL(e=>{let t=!e;try{window.localStorage.setItem(u_,t?"1":"0")}catch{}return t})},[eA,e_]=(0,s.useState)(!1),[eF,eO]=(0,s.useState)(null),[ez,eD]=(0,s.useState)(!1),[eW,eH]=(0,s.useState)(!1),[eU,eB]=(0,s.useState)(null),[eq,eV]=(0,s.useState)(!1),[eK,eJ]=(0,s.useState)(()=>X?u6(us(X)?.images):[]),[eG,eY]=(0,s.useState)(()=>X?u9(us(X)?.documents):[]),[eZ,eQ]=(0,s.useState)(null),eX=(0,s.useMemo)(()=>eG.filter(e=>"ready"===e.status),[eG]),e0=eG.some(e=>"ready"!==e.status||uO(e)),e1=eG.filter(e=>"audio"===e.stored&&e.attachmentId&&e.storedInfo&&(void 0!==e.transcription||!e.text.includes(u7))),e2=ek.trimStart(),e4=0===eK.length&&0===eG.length&&e2.startsWith("!"),e8=e4&&e2.startsWith("!!"),[e5,e6]=(0,s.useState)(!1),[e3,e7]=(0,s.useState)(0),[e9,te]=(0,s.useState)(null),tt=e9?.value===ek&&e9.draftKey===X?e9.token:null,[tn,tr]=(0,s.useState)(!1),[ts,ta]=(0,s.useState)(!1),ti=(0,s.useRef)(null),[tl,to]=(0,s.useState)(null),[tc,td]=(0,s.useState)(!1),[tu,th]=(0,s.useState)(0),[tp,tm]=(0,s.useState)(!1),[tf,tg]=(0,s.useState)(0),[tx,tv]=(0,s.useState)(null),[ty,tb]=(0,s.useState)(!1),[tw,tk]=(0,s.useState)(null),[tj,tS]=(0,s.useState)(null),tC=ee&&tj?.cwd===ee?tj.values:{},tN=(0,s.useRef)(null),tT=(0,s.useRef)(null),tI=(0,s.useRef)(null),tM=(0,s.useRef)(null),tE=(0,s.useRef)(null),t$=(0,s.useRef)(null),tR=(0,s.useRef)(null),tL=(0,s.useRef)(null),tP=(0,s.useRef)(null),tA=(0,s.useRef)(null),t_=(0,s.useRef)(null),tF=(0,s.useRef)(!1),tO=(0,s.useRef)(0),tz=(0,s.useRef)(!1),tD=(0,s.useRef)([]),tW=(0,s.useRef)([]),tH=(0,s.useRef)([]),tU=(0,s.useRef)(null),tB=(0,s.useRef)(null),tq=(0,s.useRef)(X),tV=(0,s.useRef)(ek),tK=(0,s.useRef)(eK),tJ=(0,s.useRef)(0),tG=(0,s.useRef)(eG);tV.current=ek,tK.current=eK,tG.current=eG,(0,s.useImperativeHandle)(el,()=>({insertIfEmpty(e){let t=tN.current;(t?t.value:ek).trim()||(tV.current=e,ej(e),to(null),requestAnimationFrame(()=>{t&&(t.focus(),t.style.height="auto",t.style.height=`${Math.min(t.scrollHeight,200)}px`)}))},replaceMessage(e){let t,n,r=tN.current;if(!function(e,t,n,r=0){return!e.trim()&&0===t&&0===n&&0===r}(r?r.value:ek,tK.current.length,tJ.current,tG.current.length))return;let s=(t="string"==typeof e.content?e.content:e.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n"),ar(t)?.message??t),a=u6("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 rs(r)?[r]:[]})),i=u9((n="string"==typeof e.content?e.content:e.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n"),ar(n)?.documents??[]));tV.current=s,tK.current=a,tG.current=i,ej(s),to(null),tm(!1),eJ(e=>(e.forEach(ha),a)),eY(i),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(tq.current!==e)return void uo(e,t);let n={value:tV.current,images:tK.current.map(u8),documents:tG.current.filter(e=>"ready"===e.status).map(he)},r=uo(e,t,n)??{value:"",images:[],documents:[]},s=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(tq.current=t,s)return;let a=u6(r.images),i=ht(u9(r.documents),tG.current),l=r.value;tV.current=l,tK.current=a,tG.current=i,ej(l),eJ(e=>(e.forEach(ha),a)),eY(i),to(null),tm(!1)},restoreSubmission(e,t,n,r){if(!e.trim()&&!t?.length&&!n?.length)return;let s=tq.current,a=r??s,i=a===s,l=!i&&a?us(a):null,o=ul(e,t,i?tV.current:l?.value??"",i?tK.current.map(u8):l?.images??[],n,i?tG.current.filter(e=>"ready"===e.status).map(he):l?.documents??[]);if(a&&ua(a,o),!i)return;let c=t?.length?[...u6(t).slice(0,Math.max(0,10-tK.current.length)),...tK.current].slice(0,10):tK.current,d=ht(u9(o.documents),tG.current);tV.current=o.value,tK.current=c,tG.current=d,ej(o.value),to(null),tm(!1),t?.length&&eJ(e=>{let n=Math.max(0,10-e.length),r=u6(t).slice(0,n),s=r.length>0?[...r,...e]:e;return tK.current=s,s}),eY(d),requestAnimationFrame(()=>{let e=tN.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=tN.current;if(!t)return void ej(t=>t+(t?" ":"")+e);let n=t.selectionStart??t.value.length,r=t.selectionEnd??t.value.length,s=t.value.slice(0,n),a=t.value.slice(r),i=s.length>0&&!s.endsWith(" ")?" ":"",l=s+i+e+a;tV.current=l,ej(l),to(null),requestAnimationFrame(()=>{if(!t)return;let r=n+i.length+e.length;t.setSelectionRange(r,r),t.focus(),t.style.height="auto",t.style.height=`${Math.min(t.scrollHeight,200)}px`})},addAttachments(e){nt(e)}}));let tY=(0,s.useCallback)(async e=>{let t=Math.max(0,10-tK.current.length-tJ.current),n=e.filter(e=>e.size>0xa00000);n.length>0&&eQ(ev("chat.attachImageTooLarge",{name:n.map(e=>e.name).join(", "),limit:as(0xa00000)}));let r=e.filter(e=>e.size<=0xa00000),s=r.slice(0,t);if(s.length<r.length&&eQ(ev("chat.attachImageLimit",{count:10})),s.length){tJ.current+=s.length;try{let e=await Promise.all(s.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)})));eJ(t=>{let n=e.slice(0,Math.max(0,10-t.length));e.slice(n.length).forEach(ha);let r=[...t,...n];return tK.current=r,r})}finally{tJ.current-=s.length}}},[ev]),tZ=(0,s.useCallback)(async e=>{for(let t of e){let e=s6(t);if(!e)continue;if(tG.current.length>=3){eQ(ev("chat.attachLimit",{count:3}));continue}if(t.size>8388608){eQ(ev("chat.attachTooLarge",{name:t.name,limit:as(8388608)}));continue}if(tG.current.reduce((e,t)=>e+t.size,0)+t.size>0x1000000){eQ(ev("chat.attachTotalTooLarge",{limit:as(0x1000000)}));continue}let n={id:++uq,name:t.name,mimeType:s4[e],size:t.size,text:"",status:"extracting"},r=[...tG.current,n];tG.current=r,eY(r);try{let e=await at(t);if(tG.current.reduce((e,t)=>e+(t.id===n.id?0:t.text.length),0)+e.text.length>24e4)throw new s2("text_too_large","Total extracted text exceeds 240000 characters");let r=tG.current.map(t=>t.id===n.id?{...e,id:t.id,status:"ready"}:t);tG.current=r,eY(r)}catch(s){let e=tG.current.some(e=>e.id===n.id),r=tG.current.filter(e=>e.id!==n.id);if(tG.current=r,eY(r),!e)continue;s instanceof s2?"text_too_large"===s.code?eQ(ev("chat.attachTextTooLarge",{name:t.name,limit:12e4.toLocaleString()})):"too_many_pages"===s.code?eQ(ev("chat.attachTooManyPages",{name:t.name,limit:250})):"no_extractable_text"===s.code?eQ(ev("chat.attachNoPdfText",{name:t.name})):"password_protected"===s.code?eQ(ev("chat.attachPasswordProtected",{name:t.name})):eQ(ev("chat.attachExtractFailed",{name:t.name})):eQ(ev("chat.attachExtractFailed",{name:t.name}))}}},[ev]),tQ=(0,s.useCallback)((e,t)=>{if(!tG.current.some(t=>t.id===e))return!1;let n=t?tG.current.map(n=>n.id===e?t:n):tG.current.filter(t=>t.id!==e);return tG.current=n,eY(n),!0},[]),tX=(0,s.useCallback)((e,t)=>{if(!tG.current.some(t=>t.attachmentId===e))return!1;let n=tG.current.map(n=>n.attachmentId===e?t(n):n);return tG.current=n,eY(n),!0},[]),t0=(0,s.useCallback)((e,t,n)=>{if(!e||e===tq.current)return;let r=us(e);r?.documents.some(e=>e.attachmentId===t)&&ua(e,{...r,documents:u9(r.documents).map(e=>e.attachmentId===t?n(e):e).map(he)})},[]),t1=(0,s.useRef)(new Map),t2=(0,s.useRef)(new Map),t4=(0,s.useRef)(new Set),t8=(0,s.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)),s=ao({...e.storedInfo,transcript:t},r);return s.length>r?null:{...e,text:s,size:new TextEncoder().encode(s).byteLength,transcription:void 0}},[]),t5=(0,s.useCallback)(e=>e instanceof hn&&"media_tool_unavailable"===e.code?ev("chat.transcribeToolMissing"):e instanceof hn&&"transcription_failed"===e.code&&null!==e.completedParts&&null!==e.parts?ev("chat.transcribePartialFailed",{done:e.completedParts,total:e.parts}):e instanceof Error?e.message:String(e),[ev]),t6=(0,s.useCallback)(async(e,t)=>{let n=tq.current,r=tG.current.find(t=>t.attachmentId===e);if(!r?.storedInfo)return;let s=r.transcription?.state==="confirm"?r.transcription.plan:null;t2.current.get(e)?.abort();let a=new AbortController;t2.current.set(e,a),tX(e,e=>({...e,transcription:{state:"running",plan:s}}));try{let r=await hs(await fetch(`/api/attachments/${encodeURIComponent(e)}/transcription`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({confirmed:t}),signal:a.signal}));if("string"!=typeof r.transcript)throw new hn("Invalid transcription result",null,null,null);let s=r.transcript;tX(e,e=>t8(e,s,tG.current)??{...e,transcription:{state:"failed",error:ev("chat.transcribeTooLong")}})||t0(n,e,e=>t8(e,s,[])??e)}catch(n){if(a.signal.aborted)return void tX(e,e=>({...e,transcription:{state:"skipped"}}));if(n instanceof hn&&"confirmation_required"===n.code)return void t3.current?.(e);let t=t5(n);tX(e,e=>({...e,transcription:{state:"failed",error:t}}))}finally{t2.current.get(e)===a&&t2.current.delete(e)}},[ev,t5,tX,t0,t8]),t3=(0,s.useRef)(null),t7=(0,s.useCallback)(async e=>{let t;t2.current.get(e)?.abort();let n=new AbortController;t2.current.set(e,n),tX(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 hn("Invalid transcription plan",null,null,null);return{durationSeconds:e.durationSeconds,estimatedCalls:e.estimatedCalls,requiresConfirmation:e.requiresConfirmation,processing:e.processing,notice:e.notice}}(await hs(await fetch(`/api/attachments/${encodeURIComponent(e)}/transcription`,{cache:"no-store",signal:n.signal})))}catch(t){if(n.signal.aborted)tX(e,e=>({...e,transcription:{state:"skipped"}}));else{let n=t5(t);tX(e,e=>({...e,transcription:{state:"failed",error:n}}))}return}finally{t2.current.get(e)===n&&t2.current.delete(e)}t.requiresConfirmation?tX(e,e=>({...e,transcription:{state:"confirm",plan:t}})):await t6(e,!1)},[t6,t5,tX]);t3.current=t7;let t9=(0,s.useCallback)(e=>{let t=t2.current.get(e);t?t.abort():tX(e,e=>({...e,transcription:{state:"skipped"}}))},[tX]),ne=(0,s.useCallback)(async(e,t)=>{let n=null;for(let r of e){if(tG.current.length>=3){eQ(ev("chat.attachLimit",{count:3}));continue}let e="file"===t&&r.size<=8388608,s={id:++uq,name:r.name,mimeType:"text/plain",size:e?r.size:0,text:"",status:e?"extracting":"uploading",sourceSize:r.size},a=[...tG.current,s];tG.current=a,eY(a);let i=(e,t)=>{let n=tG.current.filter(e=>e.id!==s.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]?s9("utf-16le",t.subarray(2)):254===t[0]&&255===t[1]?s9("utf-16be",t.subarray(2)):t.includes(0)?null:s9("utf-8",t)??s9("euc-kr",t)},()=>null);if(null!==e&&i(e.length,r.size)){tQ(s.id,{...s,text:e,status:"ready"});continue}}if(null===n&&(n=1048576*(await uj().catch(()=>ub)).uploadLimitMb),r.size>n){tQ(s.id,null)&&eQ(ev("chat.attachStoredTooLarge",{name:r.name,limit:as(n)}));continue}let l={...s,stored:t,status:"uploading",size:0};if(!tQ(s.id,l))continue;let o=tq.current??hr,c=await uh(o),d=null,u=new AbortController;t1.current.set(s.id,u);try{if(t4.current.has(s.id))continue;let e=await ac(r,{sessionId:en,draftId:c.draftId,signal:u.signal}),n=tG.current.filter(e=>e.id!==s.id).reduce((e,t)=>e+t.text.length,0),a=ao({path:e.path,size:e.size,mimeType:e.mimeType},Math.min(12e4,24e4-n)),h=new TextEncoder().encode(a).byteLength;if(!i(a.length,h)){tQ(s.id,null)&&eQ(ev("chat.attachTotalTooLarge",{limit:as(0x1000000)}));continue}let p={...l,attachmentId:e.id,text:a,size:h,status:"ready",storedInfo:{path:e.path,size:e.size,mimeType:e.mimeType},..."audio"===t?{transcription:{state:"planning"}}:{}};if(tQ(s.id,p))d=e.id;else if(!t4.current.has(s.id)&&o!==tq.current){let t=us(o)??{value:"",images:[],documents:[]};ua(o,{...t,documents:[...t.documents,he(p)]}),d=e.id}}catch(e){if(u.signal.aborted)continue;tQ(s.id,null)&&eQ(ev("chat.attachUploadFailed",{name:r.name,error:e instanceof Error?e.message:String(e)}))}finally{t1.current.delete(s.id),c.end(d)}d&&"audio"===t&&tG.current.some(e=>e.attachmentId===d)&&t7(d)}},[tQ,t7,en,ev]),nt=(0,s.useCallback)(async e=>{eQ(null);let{images:t,documents:n,audio:r,files:s}=function(e){let t=[],n=[],r=[],s=[];for(let a of e)a.type.startsWith("image/")?t.push(a):null!==s6(a)?n.push(a):s7(a)?r.push(a):s.push(a);return{images:t,documents:n,audio:r,files:s}}(e),a=n.filter(e=>e.size>8388608);await Promise.all([tY(t),tZ(n.filter(e=>e.size<=8388608)),ne(r,"audio"),ne([...s,...a],"file")])},[tZ,ne,tY]),nn=(0,s.useCallback)(e=>{eJ(t=>{let n=[...t],[r]=n.splice(e,1);return r&&ha(r),tK.current=n,n})},[]),nr=(0,s.useCallback)(e=>{let t=tG.current.find(t=>t.id===e);if(t4.current.add(e),t1.current.get(e)?.abort(),t?.attachmentId){t2.current.get(t.attachmentId)?.abort();var n=t.attachmentId;for(let[e,t]of d4)t.delete(n)&&(0===t.size&&d4.delete(e),uv())}let r=tG.current.filter(t=>t.id!==e);tG.current=r,eY(r)},[]),ns=(0,s.useCallback)(()=>{tK.current=[],eJ(e=>(e.forEach(ha),[]))},[]),na=(0,s.useCallback)(()=>{tG.current=[],eY([])},[]),ni=(0,s.useCallback)(()=>{tV.current="",ej(""),to(null),te(null),tr(!1),tm(!1),X&&ui(X),tq.current&&tq.current!==X&&ui(tq.current),ns(),na(),eQ(null),tN.current&&(tN.current.style.height="auto")},[na,ns,X]);(0,s.useEffect)(()=>{X&&tq.current===X&&ua(X,{value:ek,images:eK.map(u8),documents:eX.map(he)})},[eK,X,eX,ek]),(0,s.useEffect)(()=>{let e=tq.current;if(e===X)return;e&&ua(e,{value:tV.current,images:tK.current.map(u8),documents:tG.current.filter(e=>"ready"===e.status).map(he)});let t=X?us(X):null;tq.current=X;let n=t?.value??"",r=u6(t?.images),s=u9(t?.documents);tV.current=n,tK.current=r,tG.current=s,ej(n),to(null),tm(!1),eJ(e=>(e.forEach(ha),r)),eY(s)},[X]),(0,s.useEffect)(()=>{let e=tN.current;e&&(e.style.height="auto",ek&&(e.style.height=`${Math.min(e.scrollHeight,200)}px`))},[ek]),(0,s.useEffect)(()=>()=>{tK.current.forEach(ha)},[]);let nl=(0,s.useCallback)((e,t)=>{let n=function(e,t){let n=uc(t);if(0===n.length)return()=>{};let r=++d1;return d0.set(r,{draftId:ud(e),ids:n}),e=>{if("accepted"!==e&&"returned"!==e)return;let t=d0.get(r);if(t){if(d0.delete(r),"accepted"===e){let e=d8.get(t.draftId)??new Set;for(let n of t.ids)e.add(n);d8.set(t.draftId,e)}uv()}}}(tq.current??hr,e);Promise.resolve(t()).then(e=>n("accepted"===e||"returned"===e?e:void 0),()=>void 0)},[]),no=(0,s.useCallback)(async()=>{let t=ek.trim(),n=e2.trim(),r=n.startsWith("/")||n.startsWith("!")?n:t;if(!r&&!eK.length&&!eX.length||i||e0)return;Z?.();let s=eK.length?eK:void 0,a=eX.length?eX:void 0;if(r.startsWith("/")){await uF(r,q,J,t=>nl(a,()=>e(t,s,a)),eQ,!!(s||a),K)&&ni();return}ni(),nl(a,()=>e(r,s,a))},[ek,e2,eK,eX,e0,i,J,q,K,e,ni,Z,nl]),nc=!e2.startsWith("/")||e2.startsWith("//")||/\s/.test(e2.slice(1))?null:e2.slice(1).toLowerCase(),nd=(()=>{if(null===nc)return[];let e=[...i?[]:uZ,...q??[]],t=new Set;return[...e].filter(e=>{let t=e.name.toLowerCase(),n=u2(e,ev).toLowerCase();return t.includes(nc)||n.includes(nc)}).sort((e,t)=>{let n=u1(e,nc,ev)-u1(t,nc,ev);return 0!==n?n:u0[e.source]-u0[t.source]||uB.compare(e.name,t.name)}).filter(e=>{let n=e.name.toLowerCase();return!t.has(n)&&(t.add(n),!0)})})(),{commands:nu,groups:nh}=(eo=0,{commands:(ec=uQ.map(e=>{let t=nd.filter(t=>t.source===e),n="skill"===e?[...t.filter(e=>!u4(e,tC)),...t.filter(e=>u4(e,tC))]:t;return{source:e,items:n.map(e=>({command:e,index:eo++}))}}).filter(e=>e.items.length>0)).flatMap(e=>e.items.map(({command:e})=>e)),groups:ec}),np=1===nd.length?ev(nc?"chat.match":"chat.command"):ev(nc?"chat.matches":"chat.commands",{count:nd.length}),nm=!!ek.trim(),nf=!e0&&(nm||eK.length>0||eX.length>0),ng=(0,s.useCallback)((e,t)=>{let n=function(e,t){let n=Math.max(0,Math.min(e.length,t)),r=/(?:^|\s)(\/\/[^\s]*)$/.exec(e.slice(0,n));if(!r)return null;let s=n-r[1].length,a=/^\S*/.exec(e.slice(n))[0];return{start:s,end:n+a.length,query:e.slice(s+2,n)}}(e,t??e.length);if(te(n?{value:e,draftKey:X,token:n}:null),ta(!1),!ee)return void to(null);let r=t??e.length;to(uC(e.slice(0,r)))},[ee,X]),nx=tl?.query??null,nv=s.useMemo(()=>null!==nx&&tx&&tx.cwd===ee?function(e,t,n=20){let r=t.toLowerCase();if(!r)return e.slice(0,n);let s=[];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:uT(t,n)&&(r=10);else{let e=n.lastIndexOf("/"),s=-1===e?n:n.slice(e+1);s===t?r=100:s.startsWith(t)?r=80:s.includes(t)?r=50:n.includes(t)?r=30:uT(t,n)&&(r=10)}return e.isDir&&r>0&&(r+=10),r}(t,r);e>0&&s.push({entry:t,score:e})}return s.sort((e,t)=>t.score-e.score||uN(e.entry.path)-uN(t.entry.path)||e.entry.path.localeCompare(t.entry.path)),s.slice(0,n).map(e=>e.entry)}(tx.entries,nx):[],[nx,tx,ee]),ny=!!(nx&&tx?.truncated&&tx.cwd===ee);(0,s.useEffect)(()=>{if(!ny||!ee||!nx)return;let e=setTimeout(()=>{fetch(`/api/file-index?cwd=${encodeURIComponent(ee)}&q=${encodeURIComponent(nx)}`).then(e=>{if(!e.ok)throw Error(`file search failed: ${e.status}`);return e.json()}).then(e=>tk({cwd:ee,query:nx,matches:e.matches??[]})).catch(()=>{})},150);return()=>clearTimeout(e)},[ny,nx,ee]);let nb=ny&&null!==tw&&tw.cwd===ee&&tw.query===nx,nw=nb?tw.matches:nv,nk=null===tl?null:`${tl.start}:${+!!tl.quoted}:${tl.query}`;(0,s.useEffect)(()=>{if(null===nk){td(!1),th(0);return}td(!0),th(0)},[nk]);let nj=null!==tl,nS=uP(tA,tp,{viewportFraction:.44,cap:360}),nC=uP(tA,e5,{viewportFraction:.56,cap:460}),nN=uP(tA,tc,{viewportFraction:.48,cap:400}),nT=uP(tA,tn,{viewportFraction:.48,cap:400}),nI=tt?`${tt.start}:${tt.end}:${tt.query}`:null;(0,s.useEffect)(()=>{tr(null!==nI)},[nI]);let nM=(0,s.useCallback)((e,t,n,r=!1)=>{tV.current===e&&tq.current===X&&(tV.current=t,ej(t),te(null),tr(!1),ta(r),requestAnimationFrame(()=>{let e=tN.current;e&&(e.focus(),e.setSelectionRange(n,n),e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)}))},[X]);(0,s.useEffect)(()=>{if(!nj||!ee)return;let e=tU.current;e&&e.cwd===ee&&Date.now()-e.fetchedAt<1e4||tB.current===ee||(tB.current=ee,tb(!0),fetch(`/api/file-index?cwd=${encodeURIComponent(ee)}`).then(e=>{if(!e.ok)throw Error(`file index failed: ${e.status}`);return e.json()}).then(e=>{tv({cwd:ee,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)=>uN(e.path)-uN(t.path)||e.path.localeCompare(t.path)),n}(e.files??[]),truncated:!!e.truncated}),tU.current={cwd:ee,fetchedAt:Date.now()}}).catch(()=>{tU.current=null}).finally(()=>{tB.current=null,tb(!1)}))},[nj,ee]);let nE=(0,s.useCallback)(e=>{if(!tl)return;let t=tN.current,n=t?.selectionStart??ek.length,r=ek.slice(0,tl.start),s=ek.slice(n);tl.quoted&&s.startsWith('"')&&(s=s.slice(1));let a=function(e,t,n=!1){let r=t?`${e}/`:e,s=n||r.includes(" ");if(t){let e=s?`@"${r}"`:`@${r}`;return{text:e,cursorOffset:s?e.length-1:e.length}}let a=s?`@"${r}" `:`@${r} `;return{text:a,cursorOffset:a.length}}(e.path,e.isDir,tl.quoted),i=r+a.text+s,l=r.length+a.cursorOffset;ej(i),to(uC(i.slice(0,l))),requestAnimationFrame(()=>{let e=tN.current;e&&(e.focus(),e.setSelectionRange(l,l),e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)})},[tl,ek]);(0,s.useEffect)(()=>{tu>=nw.length&&th(Math.max(0,nw.length-1))},[nw.length,tu]),(0,s.useEffect)(()=>{tW.current.length=nw.length},[nw.length]),(0,s.useEffect)(()=>{tc&&tW.current[tu]?.scrollIntoView({block:"nearest",inline:"nearest"})},[tu,tc]),(0,s.useEffect)(()=>{tf>=W.length&&tg(Math.max(0,W.length-1))},[W.length,tf]),(0,s.useEffect)(()=>{tH.current.length=W.length},[W.length]),(0,s.useEffect)(()=>{tp&&tH.current[tf]?.scrollIntoView({block:"nearest",inline:"nearest"})},[tf,tp]);let n$=(0,s.useCallback)(e=>{tV.current=e,ej(e),tm(!1),tg(0),to(null),requestAnimationFrame(()=>{let t=tN.current;t&&(t.focus(),t.setSelectionRange(e.length,e.length),t.style.height="auto",t.style.height=`${Math.min(t.scrollHeight,200)}px`)})},[]),nR=(0,s.useCallback)(e=>{let t=`/${e.name} `;tV.current=t,ej(t),e6(!1),e7(0),requestAnimationFrame(()=>{let e=tN.current;e&&(e.focus(),e.setSelectionRange(t.length,t.length),e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)})},[]),nL=(0,s.useCallback)(async e=>{let t=ek.trim(),r=e2.trim(),s=r.startsWith("/")||r.startsWith("!")?r:t,i=e0||!s&&0===eK.length&&0===eX.length?null:{message:s,images:eK.length?eK:void 0,documents:eX.length?eX:void 0};if(!i)return;Z?.();let l="steer"===e?"steer":"followUp";if(s.startsWith("/")){await uF(s,q,J,e=>{if(!Q)throw Error("Cannot queue this command while the session is busy.");nl(i.documents,()=>Q(e,l,i.images,i.documents))},eQ,!!(i.images?.length||i.documents?.length),K)&&ni();return}ni(),"steer"===e&&n?nl(i.documents,()=>n(i.message,i.images,i.documents)):"followup"===e&&a&&nl(i.documents,()=>a(i.message,i.images,i.documents))},[ek,e2,eK,eX,e0,q,K,J,Q,n,a,ni,Z,nl]),nP=(0,s.useCallback)(e=>{let t=nu.length-1;if(t<0)return 0;if("left"===e)return Math.max(0,e3-1);if("right"===e)return Math.min(t,e3+1);let n=tD.current[e3];if(!n)return"down"===e?Math.min(t,e3+1):Math.max(0,e3-1);let r=n.getBoundingClientRect(),s=r.left+r.width/2,a=r.top+r.height/2,i=-1,l=1/0;for(let n=0;n<=t;n+=1){if(n===e3)continue;let t=tD.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 c=1e3*Math.abs(o)+Math.abs(r.left+r.width/2-s);c<l&&(i=n,l=c)}return i>=0?i:"down"===e?Math.min(t,e3+1):Math.max(0,e3-1)},[nu.length,e3]),nA=(0,s.useCallback)(e=>{let r=e.nativeEvent,s=Date.now()-tO.current<100,l=tF.current||r.isComposing||229===r.keyCode;if("Enter"===e.key&&!e.shiftKey&&(l||s)){s&&e.preventDefault();return}if(tp&&!l){if("ArrowDown"===e.key){e.preventDefault(),tg(e=>Math.min(Math.max(0,W.length-1),e+1));return}if("ArrowUp"===e.key){e.preventDefault(),tg(e=>Math.max(0,e-1));return}if("Escape"===e.key){e.preventDefault(),tm(!1);return}if(("Tab"===e.key||"Enter"===e.key&&!e.shiftKey)&&W[tf]){e.preventDefault(),n$(W[tf]);return}}if(!(tn&&tt&&!l&&ti.current?.handleKeyDown(e))){if(e5&&null!==nc){if("ArrowDown"===e.key){e.preventDefault(),e7(nP("down"));return}if("ArrowUp"===e.key){e.preventDefault(),e7(nP("up"));return}if("ArrowRight"===e.key){e.preventDefault(),e7(nP("right"));return}if("ArrowLeft"===e.key){e.preventDefault(),e7(nP("left"));return}if("Escape"===e.key){e.preventDefault(),e6(!1);return}if(("Tab"===e.key||"Enter"===e.key&&!e.shiftKey)&&nu[e3]){e.preventDefault(),nR(nu[e3]);return}}if(tc&&null!==tl&&!l){if("ArrowDown"===e.key){e.preventDefault(),th(e=>Math.min(Math.max(0,nw.length-1),e+1));return}if("ArrowUp"===e.key){e.preventDefault(),th(e=>Math.max(0,e-1));return}if("Escape"===e.key){e.preventDefault(),td(!1);return}if(("Tab"===e.key||"Enter"===e.key&&!e.shiftKey)&&nw[tu]){e.preventDefault(),nE(nw[tu]);return}}if("ArrowUp"===e.key&&!l&&!i&&W.length>0&&0===ek.trim().length){e.preventDefault(),e6(!1),td(!1),tg(W.length-1),tm(!0);return}if("Escape"===e.key&&!l&&i&&t){e.preventDefault(),t();return}"Enter"!==e.key||e.shiftKey||(e.preventDefault(),i&&(n||a)?nL(n?"steer":"followup"):no())}},[i,n,a,t,e5,nc,nu,e3,nR,nL,no,nP,tc,tl,nw,tu,nE,tp,W,tf,n$,ek,tn,tt]),n_=(0,s.useCallback)(()=>{let e=tN.current;e&&(e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)},[]),nF=(0,s.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(),nt(t))},[nt]);(0,s.useEffect)(()=>{if(null===nc){e6(!1),e7(0),tz.current=!1;return}e6(!0),e7(0),!tz.current&&K&&(tz.current=!0,Promise.resolve(K()).catch(()=>{tz.current=!1}))},[nc,K]),(0,s.useEffect)(()=>{if(!e5||!ee)return;let e=!1;return tS({cwd:ee,values:{}}),fetch(`/api/skills?cwd=${encodeURIComponent(ee)}`).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;tS({cwd:ee,values:n})}).catch(()=>{e||tS({cwd:ee,values:{}})}),()=>{e=!0}},[e5,ee]),(0,s.useEffect)(()=>{e3>=nu.length&&e7(Math.max(0,nu.length-1))},[nu.length,e3]),(0,s.useEffect)(()=>{tD.current.length=nu.length},[nu.length]),(0,s.useEffect)(()=>{e5&&tD.current[e3]?.scrollIntoView({block:"nearest",inline:"nearest"})},[e3,e5]);let nO=u&&u.length>0?u.map(e=>({provider:e.provider,modelId:e.id,name:e.name})).sort(uK):Object.entries(d??{}).map(([e,t])=>({provider:o?.provider??"unknown",modelId:e,name:t})).sort(uK),nz=g??null,nD=rW.find(e=>e.alias===nz)?.provider??null,nW=nD?nO.filter(e=>e.provider===nD):nO,nH=(ed=eI.trim().toLocaleLowerCase())?nW.filter(e=>`${e.name} ${e.modelId}`.toLocaleLowerCase().includes(ed)):nW,nU=nW.length>8,nB=[];for(let e of nH){let t=nB.find(t=>t.provider===e.provider);t?t.options.push(e):nB.push({provider:e.provider,options:[e]})}let nq=nD?[]:(x??[]).filter(e=>!e.hidden&&e.resolved),nV=o?nq.find(e=>e.resolved?.provider===o.provider&&e.resolved?.modelId===o.modelId):void 0,nK=eI.trim()?[]:nW.map((e,t)=>{var n,r;return{option:e,order:t,count:eE[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})),nJ=(e,t,n)=>{let s=e.modelId===o?.modelId&&e.provider===o?.provider;return(0,r.jsxs)("button",{onClick:()=>{if(eC(!1),eM(""),!s||c){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}(u$(),(t=e.provider,n=e.modelId,`${t}/${n}`));try{window.localStorage.setItem(uE,JSON.stringify(r))}catch{}e$(r),m?.(e.provider,e.modelId)}},style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",background:s?"var(--bg-selected)":"none",border:"none",color:s?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left",fontWeight:s?600:400,whiteSpace:"nowrap"},onMouseEnter:e=>{s||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{s||(e.currentTarget.style.background="none")},children:[s?(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:ev("chat.modelPickCount",{count:n})})]},`${t}:${e.provider}:${e.modelId}`)},nG=o?nO.find(e=>e.modelId===o.modelId&&e.provider===o.provider)?.name??o.modelId:null,nY=S?Math.max(0,S.tokensBefore-S.estimatedTokensAfter):0,nZ=S?`${S.reason&&"manual"!==S.reason?`${S.reason[0].toUpperCase()}${S.reason.slice(1)} `:ev("chat.compacted")} ${ro(S.tokensBefore)} -> ${ro(S.estimatedTokensAfter)} tokens (${ev("chat.tokensSaved",{saved:ro(nY)})})`:null,nQ=e=>{let t=P?.[e];return null!=t&&t!==e?t:null},nX="auto"===(eu=T??"auto")?$?`auto ≤ ${nQ($)??$}`:"auto":P?P[eu]??eu:eu,n0=(T??"auto")==="auto"&&I&&"auto"!==I?P?.[I]??I:null,n1=R&&n0?ev("chat.currentReasoning",{level:n0}):null,n2=e=>!L||L.includes(e),n4=[{level:"auto",ceiling:null},...uG.filter(n2).map(e=>({level:"auto",ceiling:e})),...uJ.filter(e=>"auto"!==e&&n2(e)).map(e=>({level:e,ceiling:null}))],n8=Object.entries(uD).find(([,e])=>e===(C??"default"))?.[0]??"default";(0,s.useEffect)(()=>{let e=e=>{tT.current&&!tT.current.contains(e.target)&&tI.current&&!tI.current.contains(e.target)&&(eC(!1),eM("")),tM.current&&!tM.current.contains(e.target)&&tE.current&&!tE.current.contains(e.target)&&e_(!1),t$.current&&!t$.current.contains(e.target)&&eD(!1),tR.current&&!tR.current.contains(e.target)&&eH(!1),tL.current&&!tL.current.contains(e.target)&&eV(!1),!tP.current||tP.current.contains(e.target)||tN.current?.contains(e.target)||tm(!1)};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[]),(0,s.useEffect)(()=>{ew||eV(!1)},[ew]);let n5=(0,r.jsx)("button",{type:"button",className:`composer-icon-button${eK.length||eG.length?" is-active":""}`,onClick:()=>t_.current?.click(),title:ev("chat.attachFile"),"aria-label":ev("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:eK.length||eG.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=eK.length||eG.length?"var(--accent)":"var(--text)"},onMouseLeave:e=>{e.currentTarget.style.background="none",e.currentTarget.style.color=eK.length||eG.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"})]})}),n6=f&&rW.length>0?(0,r.jsxs)("div",{ref:tM,style:{position:"relative",flexShrink:+!!ew,minWidth:0},children:[(0,r.jsxs)("button",{className:`${ew?"composer-icon-button":"composer-chip"}${eA?" is-active":""}`,onClick:e=>{let t=e.currentTarget.getBoundingClientRect();eO({top:t.top,bottom:t.bottom,left:t.left,width:t.width}),eC(!1),eM(""),e_(e=>!e)},disabled:i||y,"aria-haspopup":"menu","aria-expanded":eA,onKeyDown:e=>{"Escape"===e.key&&eA&&(e.stopPropagation(),e_(!1))},style:{display:"flex",alignItems:"center",gap:6,maxWidth:"100%",padding:"4px 8px",background:eA?"var(--bg-hover)":"none",border:"none",borderRadius:"var(--radius-control)",color:"var(--text-muted)",cursor:i||y?"not-allowed":"pointer",fontSize:12,opacity:i?.5:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{i||y||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{e.currentTarget.style.background=eA?"var(--bg-hover)":"none",e.currentTarget.style.color="var(--text-muted)"},title:ev("chat.mainPreset"),"aria-label":ev("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"})}),ew?null:(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:ev("chat.mainPreset")})]}),eA&&eF&&(()=>{let e=window.visualViewport?.height??window.innerHeight,{side:t,maxHeight:n}=uR(eF.top,eF.bottom,e,uL(e,.6,460),{gap:6,prefer:"above"}),s="above"===t?{bottom:e-eF.top+6}:{top:eF.bottom+6},a=ew?{left:8,right:8,maxWidth:"calc(100vw - 16px)"}:{left:eF.left,width:"max-content",minWidth:eF.width};return(0,r.jsx)("div",{ref:tE,role:"menu","aria-label":ev("chat.mainPreset"),onKeyDown:e=>{"Escape"===e.key&&(e_(!1),tM.current?.querySelector("button")?.focus())},style:{position:"fixed",...s,...a,zIndex:500,background:"var(--bg-raised)",border:0,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:rW.map(e=>{let t=e.alias===nz;return(0,r.jsxs)("button",{role:"menuitemradio","aria-checked":t,onClick:()=>{e_(!1),f({alias:e.alias,provider:e.provider,modelId:e.model,...void 0!==e.oauthPosition?{oauthPosition:e.oauthPosition}:{}})},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:sr(e.seed),width:20,height:20,alt:"","aria-hidden":"true",draggable:!1}),(0,r.jsx)("span",{children:r5(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,n3=R?(0,r.jsxs)("div",{ref:tR,style:{position:"relative",flexShrink:0,minWidth:0},children:[(0,r.jsxs)("button",{type:"button",className:`${ew?"composer-icon-button":"composer-chip"}${eW?" is-active":""}`,onClick:e=>{let t=e.currentTarget.getBoundingClientRect();eB({top:t.top,bottom:t.bottom,left:t.left,width:t.width}),eC(!1),eM(""),e_(!1),eH(e=>!e)},disabled:i||y,"aria-haspopup":"menu","aria-expanded":eW,onKeyDown:e=>{"Escape"===e.key&&eW&&(e.stopPropagation(),eH(!1))},title:ev("chat.changeReasoning",{level:nX}),"aria-label":ev("chat.changeReasoning",{level:nX}),style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,padding:ew?0:"8px 12px",height:32,background:eW?"var(--bg-hover)":"none",border:"none",borderRadius:"var(--radius-control)",color:"var(--text-muted)",cursor:i||y?"not-allowed":"pointer",fontSize:12,opacity:i?.5:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{i||y||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{e.currentTarget.style.background=eW?"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"})]}),ew?null:(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:nX})]}),eW&&eU&&(()=>{let e=window.visualViewport?.height??window.innerHeight,{side:t,maxHeight:n}=uR(eU.top,eU.bottom,e,uL(e,.6,460),{gap:6,prefer:"above"}),s="above"===t?{bottom:e-eU.top+6}:{top:eU.bottom+6},a=ew?{left:8,right:8,maxWidth:"calc(100vw - 16px)"}:{left:eU.left,width:"max-content",minWidth:Math.max(180,eU.width)};return(0,r.jsx)("div",{role:"menu","aria-label":ev("chat.changeReasoningLabel"),onKeyDown:e=>{"Escape"===e.key&&(eH(!1),tR.current?.querySelector("button")?.focus())},style:{position:"fixed",...s,...a,zIndex:500,background:"var(--bg-raised)",border:0,borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s2)",overflowY:"auto",maxHeight:n},children:n4.map(({level:e,ceiling:t})=>{let n=(T??"auto")===e&&("auto"!==e||($??null)===t),s=t??e,a="auto"===e&&null===t?null:nQ(s),i=t?`auto ≤ ${a??t}`:a??e,l=t?ev("chat.thinkingAutoCapped",{level:a??t}):ev(uY[e]);return(0,r.jsxs)("button",{type:"button",role:"menuitemradio","aria-checked":n,onClick:()=>{eH(!1),R(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:[i,null!==a&&(0,r.jsxs)("span",{style:{fontSize:10,color:"var(--text-dim)",fontFamily:"var(--font-mono)",marginLeft:5},children:["(",s,")"]})]}),(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)",marginLeft:8},children:l})]},t?`auto-${t}`:e)})})})()]}):null,n7=O?(eh=_?ev("chat.fastModeBusy"):null===A?ev("chat.fastModeUnknown"):A.active?ev("chat.fastModeActive"):A.enabled?ev("chat.fastModeInactive"):ev("chat.fastModeOff"),ep=_||i||y,em=A?.enabled===!0,(0,r.jsx)("button",{type:"button",className:`composer-icon-button${A?.active?" is-active":""}`,onClick:O,disabled:ep,"aria-pressed":null===A?void 0:A.enabled,"aria-busy":_||void 0,title:eh,"aria-label":eh,style:{flexShrink:0,opacity:i?.5:1},children:(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:A?.active?"var(--accent)":"none",stroke:em?"var(--accent)":"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",strokeDasharray:null===A?"3 2":void 0,style:{opacity:em&&!A?.active?.6:1},"aria-hidden":"true",children:(0,r.jsx)("path",{d:"M13 2 4 14h7l-1 8 9-12h-7l1-8z"})})})):null,n9=(0,r.jsxs)(r.Fragment,{children:[n&&(0,r.jsxs)("button",{className:"composer-stream-action is-warning",onClick:()=>nL("steer"),disabled:!nf,title:e0?ev("chat.attachExtractingWait"):ev("chat.steerTitle"),style:{display:"flex",alignItems:"center",gap:5,padding:"7px 12px",background:nf?"var(--warning-soft)":"var(--bg-hover)",border:0,borderRadius:"var(--radius-control)",color:nf?"var(--warning)":"var(--text-dim)",cursor:nf?"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"})]}),ev("chat.steer")]}),a&&(0,r.jsxs)("button",{className:"composer-stream-action is-followup",onClick:()=>nL("followup"),disabled:!nf,title:e0?ev("chat.attachExtractingWait"):ev("chat.followUpTitle"),style:{display:"flex",alignItems:"center",gap:5,padding:"7px 12px",background:nf?"var(--bg-selected)":"var(--bg-hover)",border:0,borderRadius:"var(--radius-control)",color:nf?"var(--text)":"var(--text-dim)",cursor:nf?"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"})]}),ev("chat.followUp")]})]}),re=void 0!==Y?(0,r.jsx)(d_,{soundEnabled:G??!0,onToggle:Y}):null;return(0,r.jsxs)("div",{className:"chat-composer",style:{flexShrink:0,background:"transparent",padding:"0 16px 8px"},children:[(0,r.jsx)("input",{ref:t_,type:"file",multiple:!0,style:{display:"none"},onChange:e=>{nt(Array.from(e.target.files??[])),e.target.value=""}}),(0,r.jsxs)("div",{className:"chat-column-cap",style:{maxWidth:"var(--reading-measure)",margin:"0 auto"},children:[(0,r.jsx)(hl,{error:h}),(0,r.jsx)(ho,{warnings:p}),ei,D.length>0&&(0,r.jsxs)("div",{style:{marginBottom:8,border:0,borderRadius:"var(--radius-control)",background:"var(--bg-subtle)",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:12,fontWeight:600,color:"var(--text-muted)"},children:ey("delivery.title",{count:D.length})}),H&&eb&&(0,r.jsxs)("button",{onClick:H,title:ev("chat.recallTitle"),style:{display:"flex",alignItems:"center",gap:6,padding:"4px 12px",fontSize:12,color:"var(--text)",background:"var(--bg-hover)",border:0,borderRadius:"var(--radius-control)",cursor:"pointer",transition:"background 0.12s",whiteSpace:"nowrap"},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",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"})]}),ev("chat.recall")]})]}),(0,r.jsx)(d$,{rows:D,removeLabel:ev("chat.queueRemove"),onRemove:B?(e,t)=>B("steer"===e?"steering":"followUp",t):void 0})]}),z&&(0,r.jsxs)("div",{style:{marginBottom:8,padding:"5px 10px",background:"var(--warning-soft)",border:0,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"})]}),ev("chat.retrying",{attempt:z.attempt,max:z.maxAttempts}),z.errorMessage&&(0,r.jsxs)("span",{style:{opacity:.7,marginLeft:4},children:["— ",z.errorMessage]})]}),nZ&&(0,r.jsxs)("div",{style:{marginBottom:8,padding:"5px 10px",background:"var(--success-soft)",border:0,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"})}),nZ]}),j&&(0,r.jsx)("div",{role:"alert",style:{marginBottom:8,padding:"7px 10px",background:"var(--danger-soft)",border:0,borderRadius:"var(--radius-control)",color:"var(--danger)",fontFamily:"var(--font-mono)",fontSize:12,lineHeight:1.5,whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:j}),eZ&&(0,r.jsxs)("div",{role:"alert",style:{display:"flex",alignItems:"center",gap:8,marginBottom:8,padding:"7px 10px",background:"var(--danger-soft)",border:0,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:eZ}),(0,r.jsx)("button",{type:"button",onClick:()=>eQ(null),"aria-label":ev("i18n.close"),title:ev("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"})]})})]}),(eK.length>0||eG.length>0)&&(0,r.jsxs)("div",{role:"list","aria-label":ev("chat.attachments"),style:{display:"flex",alignItems:"center",gap:6,marginBottom:6,flexWrap:"wrap"},children:[eK.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)",display:"block"}}),(0,r.jsx)("button",{type:"button","aria-label":ev("chat.removeImage",{index:t+1}),onClick:()=>nn(t),style:{position:"absolute",top:-4,right:-4,width:16,height:16,borderRadius:"50%",background:"var(--bg-raised)",border:0,boxShadow:"var(--shadow-float)",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}`)),eG.map(e=>(0,r.jsxs)("div",{className:"composer-chip",role:"listitem","aria-busy":"ready"!==e.status||uO(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",className:"workbench-lamp",style:{animation:"lamp-breathe 1.2s ease-in-out infinite"}}):sY(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?ev("chat.attachKindAudio"):"file"===e.stored?ev("chat.attachKindFile"):uV[e.mimeType]," \xb7 ",as(e.sourceSize??e.size),"extracting"===e.status?` \xb7 ${ev("chat.attachExtracting")}`:"","uploading"===e.status?` \xb7 ${ev("chat.attachUploading")}`:"",e.transcription?.state==="planning"?` \xb7 ${ev("chat.transcribeChecking")}`:"",e.transcription?.state==="confirm"?` \xb7 ${ev("chat.attachTranscribePending")}`:"",e.transcription?.state==="running"?` \xb7 ${ev("chat.attachTranscribing")}`:"",e.transcription?.state==="failed"&&(0,r.jsx)("span",{style:{color:"var(--danger)"},children:` \xb7 ${ev("chat.attachTranscribeFailed")}`})]})]}),(0,r.jsx)("button",{type:"button",onClick:()=>nr(e.id),"aria-label":ev("chat.removeAttachment",{name:e.name}),title:ev("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))]}),e1.length>0&&(0,r.jsx)("div",{role:"group","aria-label":ev("chat.transcribeGroup"),"aria-live":"polite",style:{display:"flex",flexDirection:"column",gap:6,marginBottom:6},children:e1.map(e=>{let t,n,s,a,i=e.attachmentId,o=e.transcription,c=o?.state==="confirm"||o?.state==="running"?o.plan:null,d=c?ev("chat.transcribePlanSummary",{duration:null===c.durationSeconds?ev("chat.transcribeDurationUnknown"):(n=Math.floor((t=Math.round(c.durationSeconds))/3600),s=Math.floor(t%3600/60),a=String(t%60).padStart(2,"0"),n>0?`${n}:${String(s).padStart(2,"0")}:${a}`:`${s}:${a}`),calls:c.estimatedCalls}):null,u=o?.state==="confirm"?ev("chat.transcribeConfirmTitle",{name:e.name}):o?.state==="running"?ev("chat.transcribeRunning",{name:e.name}):o?.state==="planning"?`${e.name} \xb7 ${ev("chat.transcribeChecking")}`:o?.state==="failed"?ev("chat.transcribeFailedRow",{name:e.name,error:o.error}):ev("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:0,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}),d&&(0,r.jsx)("div",{style:{color:"var(--text-dim)",fontVariantNumeric:"tabular-nums"},children:d}),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:ev("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)(l.r,{type:"button",variant:"neutralSolid",size:"small",onClick:()=>void t6(i,!0),children:ev("chat.transcribeStart")}),(0,r.jsx)(l.r,{type:"button",variant:"neutralWeak",size:"small",onClick:()=>t9(i),children:ev("chat.transcribeSkip")})]}),(o?.state==="planning"||o?.state==="running")&&(0,r.jsx)(l.r,{type:"button",variant:"neutralWeak",size:"small",onClick:()=>t9(i),children:ev("chat.transcribeCancel")}),(void 0===o||"skipped"===o.state||"failed"===o.state)&&(0,r.jsx)(l.r,{type:"button",variant:"neutralWeak",size:"small",onClick:()=>void t7(i),children:ev(o?.state==="failed"?"chat.transcribeRetry":"chat.transcribeAction")})]})]},e.id)})}),(0,r.jsxs)("div",{ref:tA,style:{position:"relative",minWidth:0},children:[tp&&W.length>0&&(0,r.jsxs)("div",{ref:tP,style:{position:"absolute",left:0,right:0,...uU(nS.side),zIndex:120,background:"var(--bg-raised)",border:0,borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s3)",overflow:"hidden",maxHeight:nS.maxHeight},children:[(0,r.jsx)("div",{title:"Input history",style:{height:30,padding:"0 10px",background:"var(--bg-subtle)",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,nS.maxHeight-31),overflowY:"auto",padding:4},children:W.map((e,t)=>{let n=t===tf;return(0,r.jsxs)("button",{ref:e=>{tH.current[t]=e},type:"button",onMouseDown:t=>{t.preventDefault(),n$(e)},onMouseEnter:()=>tg(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}`)})})]}),ts&&(0,r.jsx)("div",{role:"status",style:{fontSize:12,color:"var(--text-dim)",padding:"4px 8px"},children:ev("savedPrompts.saved")}),tn&&tt&&(0,r.jsx)(dL,{ref:ti,value:ek,token:tt,cwd:ee,sessionTitle:et,style:uU(nT.side),maxHeight:nT.maxHeight,onReplace:nM,onClose:()=>tr(!1)}),e5&&null!==nc&&(0,r.jsxs)("div",{style:{position:"absolute",left:0,right:0,...uU(nC.side),zIndex:120,background:"var(--bg-raised)",border:0,borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s3)",overflow:"hidden",maxHeight:nC.maxHeight},children:[(0,r.jsxs)("div",{style:{padding:"8px 10px",background:"var(--bg-subtle)",display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,fontSize:11,color:"var(--text-dim)"},children:[(0,r.jsx)("span",{children:V?ev("chat.loadingCommands"):ev("chat.slashCommands",{label:np})}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},children:ev("chat.tabEnter")})]}),(0,r.jsx)("div",{style:{maxHeight:Math.max(0,nC.maxHeight-34),overflowY:"auto",padding:10},children:V||0!==nd.length?nh.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:ev(uX[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===e3,s=u4(e,tC);return(0,r.jsxs)("button",{ref:e=>{tD.current[t]=e},type:"button",onMouseDown:t=>{t.preventDefault(),nR(e)},onMouseEnter:()=>e7(t),style:{width:"100%",minWidth:0,minHeight:58,display:"flex",flexDirection:"column",gap:4,justifyContent:"center",padding:"9px 10px",border:0,borderRadius:"var(--radius-control)",background:n?"var(--bg-selected)":"var(--bg-subtle)",color:"var(--text)",cursor:"pointer",textAlign:"left"},children:[(0,r.jsxs)("span",{style:{fontSize:13,fontFamily:"var(--font-mono)",overflowWrap:"anywhere",wordBreak:"break-word",color:s?"var(--text-dim)":void 0},children:["/",e.name,s&&(0,r.jsx)("span",{style:{marginLeft:6,padding:"0 4px",background:"var(--bg-hover)",borderRadius:"var(--radius-control)",fontSize:9,color:"var(--text-dim)",whiteSpace:"nowrap"},children:ev("chat.dormant")})]}),u2(e,ev)&&(0,r.jsx)("span",{style:{display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:2,overflow:"hidden",fontSize:11,lineHeight:1.35,color:"var(--text-dim)"},children:u2(e,ev)})]},`${e.source}:${e.name}`)})})]},e.source)):(0,r.jsx)("div",{style:{padding:"2px 2px 4px",fontSize:12,color:"var(--text-dim)"},children:ev("chat.noCommands")})})]}),tc&&null!==tl&&(ef=ty&&(!tx||tx.cwd!==ee),eg=1===nw.length?ev("chat.match"):ev("chat.matches",{count:nw.length}),ex=tx?.truncated&&!nb?tl.query?ev("chat.searchingAll"):ev("chat.indexTruncated"):"",(0,r.jsxs)("div",{style:{position:"absolute",left:0,right:0,...uU(nN.side),zIndex:120,background:"var(--bg-raised)",border:0,borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s3)",overflow:"hidden",maxHeight:nN.maxHeight},children:[(0,r.jsxs)("div",{style:{padding:"8px 10px",background:"var(--bg-subtle)",display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,fontSize:11,color:"var(--text-dim)"},children:[(0,r.jsx)("span",{children:ef?ev("chat.loadingFiles"):ev("chat.files",{label:eg,hint:ex})}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},children:ev("chat.tabEnter")})]}),(0,r.jsx)("div",{style:{maxHeight:Math.max(0,nN.maxHeight-34),overflowY:"auto",padding:4},children:ef||0!==nw.length?nw.map((e,t)=>{let n=t===tu,s=e.path.split("/").pop()??e.path,a=e.path.slice(0,e.path.length-s.length);return(0,r.jsxs)("button",{ref:e=>{tW.current[t]=e},type:"button",onMouseDown:t=>{t.preventDefault(),nE(e)},onMouseEnter:()=>th(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)(sK,{size:14}):sY(s,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}),s,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:ny&&!nb?ev("chat.searching"):ev("chat.noMatchingFiles")})})]})),ea,(0,r.jsxs)("div",{className:`chat-composer-field${e4?" is-bash":""}${i?" is-streaming":""}`,style:{minWidth:0,display:"flex",gap:8,alignItems:"center",background:"var(--bg)",border:0,borderRadius:"var(--seed-radius-r3)",padding:"10px 10px 10px 14px",transition:"background 0.15s"},children:[(0,r.jsx)("textarea",{className:"chat-composer-textarea",ref:tN,"aria-controls":tn?"saved-prompt-menu":void 0,value:ek,onChange:e=>{tV.current=e.target.value,ej(e.target.value),tm(!1),ng(e.target.value,e.target.selectionStart)},onSelect:e=>{let t=e.currentTarget;ng(t.value,t.selectionStart)},onKeyDown:nA,onCompositionStart:()=>{tF.current=!0},onCompositionEnd:e=>{tF.current=!1,tO.current=Date.now();let t=e.currentTarget;ng(t.value,t.selectionStart)},onInput:n_,onPaste:nF,placeholder:i&&(n||a)?ev("chat.steerPlaceholder"):i?ev("chat.agentPlaceholder"):ev("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"}}),i?ew?null:(0,r.jsx)("div",{style:{display:"flex",alignItems:"center",gap:6,flexShrink:0,alignSelf:"flex-end"},children:n9}):(0,r.jsxs)("button",{className:"chat-composer-send",onClick:no,disabled:!nf,"aria-busy":e0||void 0,"aria-label":ew?ev("chat.send"):void 0,title:e0?ev("chat.attachExtractingWait"):void 0,style:{flexShrink:0,alignSelf:"flex-end",display:"flex",alignItems:"center",justifyContent:"center",gap:6,minWidth:ew?44:void 0,padding:ew?0:"7px 14px",background:nf?"var(--accent-soft)":"var(--bg-raised)",border:"none",borderRadius:"var(--radius-control)",color:nf?"var(--accent-hover)":"var(--text-dim)",cursor:nf?"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"})]}),ew?null:ev("chat.send")]})]})]}),e4&&(0,r.jsxs)("div",{className:"text-xs px-2 py-1",style:{color:e8?"var(--text-muted)":"var(--accent)",marginTop:4},children:[ev("chat.shell")," \xb7 ",e8?ev("chat.outputLocal"):ev("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:ew?"1 1 0%":"0 0 auto",minWidth:ew?"min-content":0,display:"flex",alignItems:"center",gap:2},children:[(!ew||!i)&&n5,!ew&&n6,!(ew&&i)&&(nO.length>0||nG||h)&&m&&(0,r.jsxs)("div",{ref:tT,style:{position:"relative",flex:ew?"1 1 0%":void 0,width:ew?0:void 0,minWidth:44*!!ew},children:[(0,r.jsxs)("button",{className:`composer-chip${eS?" is-active":""}`,onClick:e=>{let t=e.currentTarget.getBoundingClientRect();eT({top:t.top,bottom:t.bottom,left:t.left,width:t.width}),eC(e=>(e&&eM(""),!e))},disabled:i||y,"aria-busy":y||void 0,style:{display:"flex",alignItems:"center",gap:6,justifyContent:ew?"flex-start":void 0,padding:ew?"8px 10px":"8px 12px",height:32,width:ew?"100%":void 0,maxWidth:ew?"100%":220,overflow:"hidden",background:eS?"var(--bg-hover)":"none",border:"none",borderRadius:"var(--radius-control)",color:"var(--text-muted)",cursor:i||y?"not-allowed":"pointer",fontSize:12,opacity:i?.5:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{i||y||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{e.currentTarget.style.background=eS?"var(--bg-hover)":"none",e.currentTarget.style.color="var(--text-muted)"},title:y?"Switching model":nO.length>0?"Change model":"No available models",children:[y?(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:nG??(nO.length>0?"Select model":"No models")})]}),eS&&eN&&(()=>{let e=window.visualViewport?.height??window.innerHeight,{side:t,maxHeight:n}=uR(eN.top,eN.bottom,e,uL(e,.6,460),{gap:6,prefer:"above"}),s="above"===t?{bottom:e-eN.top+6}:{top:eN.bottom+6},a=ew?{left:8,right:8,maxWidth:"calc(100vw - 16px)"}:{left:eN.left,width:"max-content",minWidth:eN.width};return(0,r.jsxs)("div",{ref:tI,style:{position:"fixed",...s,...a,zIndex:500,background:"var(--bg-raised)",border:0,borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s2)",overflow:"hidden",maxHeight:n,display:"flex",flexDirection:"column"},children:[nU&&(0,r.jsx)("div",{style:{padding:"6px 8px",flexShrink:0},children:(0,r.jsx)("input",{value:eI,onChange:e=>eM(e.target.value),onKeyDown:e=>{"Escape"===e.key&&(eM(""),eC(!1))},placeholder:ev("chat.filterModels"),"aria-label":ev("chat.filterModels"),autoFocus:!0,autoComplete:"off",spellCheck:!1,style:{width:"100%",minWidth:220*!ew,fontSize:11,fontFamily:"var(--font-mono)",padding:"5px 8px",border:0,borderRadius:"var(--radius-control)",outline:"none",background:"var(--bg)",color:"var(--text)",boxSizing:"border-box"}})}),(0,r.jsxs)("div",{style:{minHeight:0,overflowY:"auto"},children:[nK.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:ev("chat.frequentModels")}),nK.map(({option:e,count:t})=>nJ(e,"frequent",t))]}),nq.length>0&&!eI.trim()&&v&&(0,r.jsxs)("div",{style:{marginTop:6*(nK.length>0)},children:[(0,r.jsxs)("button",{type:"button",className:"model-role-disclosure","aria-expanded":eR,"aria-controls":"model-role-rows",onClick:eP,style:{display:"flex",alignItems:"center",gap:6,width:"100%",minHeight:32,padding:"6px 12px 4px",background:"none",border:"none",cursor:"pointer",textAlign:"left",fontSize:10,fontWeight:600,color:"var(--text-dim)",letterSpacing:"0.07em",whiteSpace:"nowrap"},children:[(0,r.jsx)("svg",{width:"8",height:"8",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0,transform:eR?"rotate(90deg)":"none",transition:"transform 120ms"},children:(0,r.jsx)("polyline",{points:"3 1.5 7 5 3 8.5"})}),(0,r.jsx)("span",{style:{textTransform:"uppercase"},children:ev("chat.modelRoles")}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},children:nq.length}),nV&&(0,r.jsxs)("span",{style:{marginLeft:"auto",overflow:"hidden",textOverflow:"ellipsis",color:"var(--text-muted)",letterSpacing:0},children:[(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",color:"var(--accent)",marginRight:6},children:nV.tag??nV.role.toUpperCase()}),nV.name]})]}),(0,r.jsx)("div",{id:"model-role-rows",hidden:!eR,children:nq.map(e=>{let t=nV?.role===e.role,n=e.resolved?.name??e.resolved?.modelId??"";return(0,r.jsxs)("button",{onClick:()=>{eC(!1),eM(""),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:"var(--radius-control)",border:0,background:"var(--bg-hover)",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:11,fontWeight:600,color:"var(--text-muted)",marginTop:4},children:ev("chat.allModels")})]}),0===nB.length?(0,r.jsx)("div",{style:{padding:"8px 12px",color:"var(--text-dim)",fontSize:12,whiteSpace:"nowrap"},children:eI.trim()?ev("chat.noMatchingModels"):"No available models"}):nB.map((e,t)=>(0,r.jsxs)("div",{children:[nB.length>1&&(0,r.jsx)("div",{style:{padding:"6px 12px 4px",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em",marginTop:6*(t>0)},children:e.provider}),e.options.map(e=>nJ(e,"all"))]},e.provider))]})]})})()]}),ew&&i&&(0,r.jsx)("div",{style:{display:"flex",alignItems:"center",gap:6,minWidth:0},children:n9}),!ew&&n3,!ew&&n7,!ew&&n1&&(0,r.jsx)("span",{style:{flexShrink:0,padding:"0 6px",fontSize:12,color:"var(--text-muted)",whiteSpace:"nowrap"},children:n1}),!ew&&null!==M&&(0,r.jsx)("span",{title:ev(E?"chat.outputSpeedLiveTitle":"chat.outputSpeedTitle"),style:{flexShrink:0,padding:"0 6px",fontSize:12,color:"var(--text-muted)",whiteSpace:"nowrap",fontVariantNumeric:"tabular-nums"},children:ev(E?"chat.outputSpeedLive":"chat.outputSpeed",{rate:M>=10?Math.round(M):M.toFixed(1)})}),(0,r.jsx)(dK,{sessionId:en})]}),(0,r.jsxs)("div",{ref:tL,style:{flex:"0 1 auto",minWidth:0,display:"flex",alignItems:"center",justifyContent:"flex-end",position:"relative",marginLeft:"auto",gap:ew?4:2},children:[ew?(0,r.jsx)("button",{type:"button",className:`composer-icon-button${eq?" is-active":""}`,title:ev("chat.moreControls"),"aria-label":ev("chat.moreControls"),"aria-expanded":eq,onClick:()=>{eC(!1),eM(""),eV(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)(l.r,{type:"button",variant:"neutralWeak",size:"small",layout:"withText",title:eq?void 0:ev("chat.moreControls"),"aria-label":ev("chat.moreControls"),"aria-expanded":eq,onClick:()=>{eC(!1),eM(""),eV(e=>!e)},children:ev("chat.moreControls")}),(0,r.jsxs)("div",{className:"composer-run-options",role:"group","aria-label":ev("chat.moreControls"),style:{display:eq?ew?"grid":"flex":"none",gridTemplateColumns:ew?"repeat(3, minmax(0, max-content))":void 0,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:0,borderRadius:"var(--seed-radius-r2)",background:"var(--bg-raised)",boxShadow:"var(--seed-shadow-s2)"},children:[ew&&(0,r.jsxs)(r.Fragment,{children:[i&&n5,n6,n3,n7]}),!i&&N&&(0,r.jsxs)("div",{ref:t$,style:{position:"relative"},children:[(0,r.jsxs)("button",{className:`composer-chip${ez?" is-active":""}`,onClick:()=>!i&&eD(e=>!e),disabled:i,title:ev("chat.changeToolPreset")+`: ${n8}`,"aria-label":ev("chat.changeToolPreset"),style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,padding:"8px 12px",height:32,background:ez?"var(--bg-hover)":"none",border:"none",borderRadius:"var(--radius-control)",color:"var(--text-muted)",cursor:i?"not-allowed":"pointer",fontSize:12,opacity:i?.5:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{i||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{e.currentTarget.style.background=ez?"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:n8})]}),ez&&(0,r.jsx)("div",{style:{position:"absolute",bottom:"calc(100% + 6px)",right:0,zIndex:100,background:"var(--bg-raised)",border:0,borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s2)",overflow:"hidden",minWidth:120},children:uz.map(e=>{let t=uD[e],n=(C??"default")===t,s="off"===e?ev("chat.noTools"):"default"===e?ev("chat.builtInTools",{tools:uW}):ev("chat.allBuiltInTools",{tools:`${uW} + ${uH}`});return(0,r.jsxs)("button",{onClick:()=>{eD(!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:s})]},e)})})]}),!i&&b&&(0,r.jsx)("div",{children:(0,r.jsx)("button",{className:`composer-chip${k?" is-active is-danger":""}`,onClick:k?w:b,disabled:i&&!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:i&&!k?"not-allowed":"pointer",fontSize:12,opacity:i&&!k?.5:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{(!i||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?ev("chat.stopCompaction"):ev("chat.compactContext"),"aria-label":k?ev("chat.stopCompaction"):ev("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:ev("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:ev("chat.compact")})]})})}),ew&&re,eq&&!ew&&(0,r.jsx)("button",{className:"composer-icon-button is-active",type:"button",title:ev("chat.collapseControls"),"aria-label":ev("chat.collapseControls"),"aria-expanded":!0,onClick:()=>{eD(!1),eH(!1),eV(!1)},style:{display:"flex",alignItems:"center",justifyContent:"center",width:36,height:32,padding:0,marginLeft:0,background:"var(--bg-hover)",border:"none",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"})]})})]}),i&&(0,r.jsxs)("button",{className:"composer-chip is-danger is-active",onClick:t,title:ev("chat.stopAgent"),"aria-label":ew?ev("chat.stopAgent"):void 0,style:{display:"flex",alignItems:"center",justifyContent:"center",gap:6,minWidth:ew?44:void 0,padding:ew?0:"8px 14px",height:32,background:"var(--danger-soft)",border:0,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"})}),ew?null:ev("chat.stop")]}),(0,r.jsx)(dq,{sessionId:en,onEnsureSession:er,onTranscriptPersisted:es}),!ew&&re]})]})]})]})});function hd({cwd:e,projects:t,onChoose:n}){let{t:a}=(0,F.s)(),[i,l]=(0,s.useState)(null);(0,s.useEffect)(()=>{let t=new AbortController;return fetch(`/api/git/summary?cwd=${encodeURIComponent(e)}`,{signal:t.signal}).then(e=>e.ok?e.json():null).then(t=>{l({cwd:e,label:t?.isGitRepository===!0?!0===t.detached?a("projectOverview.detachedHead"):"string"==typeof t.branch?t.branch:null:null})}).catch(()=>{}),()=>t.abort()},[e,a]);let c=tK(e)||e,d=i?.cwd===e?i.label:null;return(0,r.jsxs)("div",{className:"composer-start-place",children:[(0,r.jsx)("span",{className:"composer-start-place-label",children:a("composer.startIn")}),(0,r.jsxs)(o.k.Root,{placement:"top-start",strategy:"fixed",children:[(0,r.jsx)(o.k.Trigger,{asChild:!0,children:(0,r.jsxs)("button",{type:"button",className:"composer-start-place-project",title:e,"aria-label":a("composer.chooseProject",{name:c}),children:[(0,r.jsx)("span",{children:c}),(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:(0,r.jsx)("path",{d:"m6 9 6 6 6-6"})})]})}),(0,r.jsx)(o.k.Positioner,{children:(0,r.jsx)(o.k.Content,{"aria-label":a("composer.startIn"),children:(0,r.jsx)(o.k.ScrollArea,{children:(0,r.jsx)(o.k.Group,{children:t.map(t=>(0,r.jsx)(o.k.Item,{role:"menuitemradio","aria-checked":t.path===e,onClick:()=>{t.path!==e&&n(t.path)},children:(0,r.jsxs)(o.k.ItemBody,{children:[(0,r.jsx)(o.k.ItemLabel,{children:t.name}),(0,r.jsx)(o.k.ItemDescription,{children:t.path})]})},t.path))})})})})]}),d&&(0,r.jsxs)("span",{className:"composer-start-place-branch",title:a("projectOverview.branch"),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)("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",{children:d})]})]})}function hu({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=eH(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",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:eK(t).map((e,t)=>(0,r.jsx)("span",{style:e.style,children:e.text},t))})})}function hh({phases:e,flow:t,busy:n}){let{t:a}=(0,F.s)(),{st:i}=sz(),[l,o]=(0,s.useState)(!1),[c,d]=(0,s.useState)(!1),[u,h]=(0,s.useState)(!1),p=(0,s.useId)(),m=e??[],{currentPhase:f,activeTask:g,remaining:x,completed:v,total:y,percent:b}=tB(m),w=m.some(e=>e.tasks.some(e=>e.dependsOn?.length)),k=t.steps.length>0,j=function(e,t,n){if(!t||!e.current)return null;let r=n("flow.strip.running",{stage:n(`flow.stage.${e.current}`)});return e.attempt>1?`${r} \xb7 ${n("flow.attempt",{attempt:e.attempt})}`:r}(t,n,i);if(0===y&&null===j)return null;let S=y>0&&0===x;return(0,r.jsxs)("div",{className:`todo-strip${S?" is-done":""}`,children:[(0,r.jsxs)("div",{className:"todo-strip-row",children:[(0,r.jsx)("span",{"aria-hidden":"true",className:"todo-strip-marker",children:S?"✓":"›"}),j&&(0,r.jsx)("span",{className:"todo-strip-lead",role:n?"status":void 0,children:j}),y>0&&(0,r.jsxs)("button",{type:"button",className:"todo-strip-summary","aria-expanded":l,onClick:()=>o(e=>!e),children:[!j&&f&&(0,r.jsx)("span",{className:"todo-strip-phase",children:f.name}),(0,r.jsx)("span",{className:"todo-strip-task",children:S?a("todo.allDone",{count:v}):g?.content??""}),(0,r.jsx)("span",{className:"todo-strip-count",children:S?a("todo.progressDone",{percent:b??0,completed:v,total:y}):a("todo.progress",{percent:b??0,completed:v,total:y,remaining:x})})]}),k&&(0,r.jsxs)("button",{type:"button",className:"todo-strip-flow-toggle","aria-expanded":c,"aria-controls":p,onClick:()=>d(e=>!e),children:[i("flow.toggle"),(0,r.jsx)("svg",{className:"flow-chevron",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)("polyline",{points:"6 9 12 15 18 9"})})]})]}),c&&k&&(0,r.jsx)(oX,{flow:t,live:n,st:i,id:p}),l&&y>0&&(0,r.jsxs)("div",{className:"todo-strip-body",children:[m.map((e,t)=>{let n=e.tasks.filter(e=>u||"completed"!==e.status);return 0===n.length?null:(0,r.jsxs)("div",{className:"todo-checklist-phase",role:"list",children:[m.length>1&&(0,r.jsx)("div",{className:"todo-checklist-phase-name",children:e.name}),n.map((e,t)=>(0,r.jsx)(sB,{task:e,phases:w?m:void 0},`${e.content}-${t}`))]},`${e.name}-${t}`)}),v>0&&(0,r.jsx)("button",{type:"button",className:"todo-strip-completed-toggle","aria-expanded":u,onClick:()=>h(e=>!e),children:a(u?"todo.hideCompleted":"todo.showCompleted",{count:v})})]})]})}function hp(e=document){return"visible"!==e.visibilityState||!e.hasFocus()}function hm(e){switch(e.method){case"select":case"confirm":case"input":case"editor":case"ask":case"form":case"plan_review":return!0;case"custom":return!0!==e.closed;default:return!1}}async function hf(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}}class hg extends Error{constructor(e,t,n,r){super(e),this.status=t,this.code=n,this.accepted=r,this.name="AgentCommandError"}}async function hx(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 hg(r.error??`HTTP ${n.status}`,n.status,r.code,r.accepted);return r.data}let hv="ompweb-update-client-id",hy="ompweb-update-resume-intent-v2",hb="ompweb-update-return-v1",hw="cuelo-restart-return-v1",hk="ompweb-update-failure-return-v1",hj="ompweb:update-wake";function hS(e){return null===e?2e4:"running"===e?null:"failed"===e?3e4:8e3}function hC(){let e=sessionStorage.getItem(hv);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(hv,t),t}function hN(){sessionStorage.removeItem(hy)}function hT(){let e=sessionStorage.getItem(hb);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 hI(e){let t=hT();if(!t||t.requestId!==e)return t;let n={...t,dismissed:!0};try{sessionStorage.setItem(hb,JSON.stringify(n))}catch{}return n}async function hM(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:hC(),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 hE(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=hT();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(hb,JSON.stringify(n))}catch{}}({requestId:e.requestId,stageHash:e.stageHash}),hN();let r=n?.wake;e.sessionId&&(r?.wake===!0||r?.reason==="already-claimed"||r?.reason==="user-already-active")&&window.dispatchEvent(new CustomEvent(hj,{detail:{sessionId:e.sessionId}}))}async function h$(e){let t=function(e){let t=sessionStorage.getItem(hk);if(!t)return null;sessionStorage.removeItem(hk);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?(hN(),t.wake&&e.sessionId&&window.dispatchEvent(new CustomEvent(hj,{detail:{sessionId:e.sessionId}})),"failed"):(await hE(e),"resumed")}function hR(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 hL(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 hP(e){return{steering:e?.steering??[],followUp:e?.followUp??[]}}function hA(e){if(e&&"boolean"==typeof e.fastModeEnabled)return{enabled:e.fastModeEnabled,active:!0===e.fastModeActive}}function h_(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 hF(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],s=t[n];if(!r||!s||r.name!==s.name||r.tasks.length!==s.tasks.length)return!1;for(let e=0;e<r.tasks.length;e+=1){let t=r.tasks[e],n=s.tasks[e];if(!t||!n||t.content!==n.content||t.status!==n.status||t.blocker!==n.blocker||(t.dependsOn?.length??0)!==(n.dependsOn?.length??0)||t.dependsOn?.some((e,t)=>e!==n.dependsOn?.[t]))return!1}}return!0}function hO(e){return"aborted"===e.stopReason?"aborted":"error"===e.stopReason||e.errorMessage?"failed":e.stopReason?"completed":"unknown"}function hz(e,t){for(let n=e.length-1;n>=0;n--){let r=t[n]??null;if(!tm(r??void 0))return{message:e[n],entryId:r}}return null}let hD=new Set(["ArrowUp","ArrowDown","PageUp","PageDown","Home","End"," ","Space","Spacebar"]);class hW 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 hH(){return"u">typeof crypto&&"function"==typeof crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2)}`}function hU(e){return new Promise(t=>setTimeout(t,e))}function hB(e){let t=e.findIndex(e=>!e.exiting);return -1===t?e:e.map((e,n)=>n===t?{...e,exiting:!0}:e)}function hq(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:hB(e.visible),pending:[...e.pending,t.notice]};return{...e,visible:[...e.visible,t.notice]};case"mark_oldest_exiting":return{...e,visible:hB(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=hB(n)),{visible:n,pending:r}}(e.visible.filter(e=>e.id!==t.id),e.pending);default:return e}}function hV(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 hK(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(hV).filter(Boolean)}):JSON.stringify({text:"",images:[]})}function hJ(e){return"user"===e.role?`user:${hK(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 hG(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 hY(e){return e?.map(({data:e,mimeType:t})=>({data:e,mimeType:t}))}function hZ(e){n1(e),e.clear()}function hQ(e,t,n){for(let r of n??[]){let n=n0(t,r);n&&e.add(n)}}function hX(){let e=document.activeElement;return e instanceof HTMLElement&&(e.isContentEditable||"INPUT"===e.tagName||"SELECT"===e.tagName||"TEXTAREA"===e.tagName)}let h0=!1,h1={width:0,height:0},h2=new Set,h4=null;function h8(){let e=window.visualViewport,t=hX();h1.width!==window.innerWidth?h1={width:window.innerWidth,height:window.innerHeight}:t||(h1.height=Math.max(h1.height,window.innerHeight));let n=function({hasFocusedEditable:e,innerHeight:t,viewportHeight:n,viewportScale:r,baselineHeight:s}){return!(!e||Math.abs(r-1)>=.01)&&(t-n>120||s-t>120)}({hasFocusedEditable:t,innerHeight:window.innerHeight,viewportHeight:e?.height??window.innerHeight,viewportScale:e?.scale??1,baselineHeight:h1.height});if(n!==h0)for(let e of(h0=n,h2))e()}function h5(e){if(h2.add(e),!h4){let e=null,t=()=>{null!==e&&window.cancelAnimationFrame(e),e=window.requestAnimationFrame(()=>{e=null,h8()})},n=window.visualViewport;n?.addEventListener("resize",t),window.addEventListener("resize",t),window.addEventListener("focusin",t),window.addEventListener("focusout",t),h8(),h4=()=>{n?.removeEventListener("resize",t),window.removeEventListener("resize",t),window.removeEventListener("focusin",t),window.removeEventListener("focusout",t),null!==e&&window.cancelAnimationFrame(e)}}return()=>{h2.delete(e),0===h2.size&&h4&&(h4(),h4=null)}}function h6(){return(0,s.useSyncExternalStore)(h5,()=>h0,()=>!1)}let h3={count:50,end:null};function h7(e,t){let n=Math.max(e,0),r=null===t.end?n:Math.min(Math.max(t.end,0),n),s=Math.min(Math.max(t.count,0),r),a=r-s;return{startIndex:a,endIndex:r,hasMore:a>0,hasLater:r<n}}function h9(e,t,n){let{startIndex:r,endIndex:s}=h7(e,n);if(t>=r&&t<s)return n;let a=Math.max(0,t-10),i=Math.max(t+1,a+50);return i>=e?{count:e-a,end:null}:{count:i-a,end:i}}function pe({sticker:e,text:t,tag:n,followRef:a}){let i=(0,s.useRef)(null);return((0,s.useEffect)(()=>{(!a||a.current)&&i.current?.scrollIntoView({block:"nearest",behavior:"smooth"})},[]),e||t)?(0,r.jsxs)("div",{ref:i,className:"cue-bubble-dock",role:"status","aria-live":"polite",children:[e&&(0,r.jsx)("img",{className:"cue-bubble-sticker",src:e,alt:rk[n]}),t&&(0,r.jsx)("p",{className:e?"cue-bubble":"cue-bubble cue-bubble--solo",children:t}),e&&(0,r.jsx)(cG(),{id:"71a4a7cebbc6c842",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 pt(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=(ar(t)?.message??t).trim();return n.length>0?n:null}function pn(e){return`omp-cues:${e}`}function pr(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(pn(e),JSON.stringify(n.slice(-200)))}catch{}}let ps=[];function pa(e){return`omp-web:interrupted-dismissed:${e}`}let pi=(0,s.memo)(function({messages:e,entryIds:t,toolResultsMap:n,modelNames:a,messageCwd:i,onOpenFile:l,sessionBusy:o,isNew:c,isStreaming:d,handleFork:u,forkingEntryId:h,handleNavigate:p,handleEditContent:m,sessionId:f,main:g,process:x,turnSummaries:v,startIndex:y,endIndex:b,sentinelRef:w,laterSentinelRef:k,flashItem:j,t:S,onProcessLogChange:C,cues:N,cueFollowRef:T}){(0,s.useEffect)(()=>{C({groups:x,messages:e,entryIds:t,toolResults:n,modelNames:a,cwd:i,sessionId:f})},[C,x,e,t,n,a,i,f]);let I=(0,s.useMemo)(()=>(function(e){let t=new Map;for(let n=0;n<e.length;n++){let r=th(e,n);r>=0&&t.set(r,function(e){let t="string"==typeof e.content?e.content:e.content.map(e=>"text"===e.type?e.text:"").join("\n");if(!t.startsWith("[interpreter] "))return t;let n=t.indexOf("\n\n");return n<0?t:t.slice(n+2)}(e[n]))}return t})(e),[e]),M=(0,s.useMemo)(()=>{let t=new Map;for(let[r,s]of function(e,t,n,r){let s=new Map;e.forEach((e,t)=>{"answer"===e.kind&&s.set(e.idx,t)});let a=new Map,i=new Map;for(let e of t){let t=i.get(e.anchorIdx);for(let l of(t||(t=new Set,i.set(e.anchorIdx,t)),e.entries)){let e=n[l.idx];if(e?.role!=="assistant")continue;let i=Math.max(0,(l.blocks?s.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 s=r.input??{};if("manage_skill"===r.toolName){let e=tv(s.action);if(!0===tx[e]){let t={kind:"skill",action:e,name:tv(s.name)};n(JSON.stringify(t),t)}continue}let a=tv(s.memory),i=s.skill,l=i?{action:tv(i.action),name:tv(i.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(i);n?n.push(t):a.set(i,[t])})}}return a}(g,x,e,n)){let e=s.map(e=>{if("skill"===e.kind)return S("chat.savedSkill",{action:e.action,name:e.name});let t=S("chat.savedLesson",{memory:e.memory});return e.skill?`${t} (${S("chat.savedSkill",e.skill)})`:t});t.set(r,{role:"custom",customType:td,content:[S("chat.lessonsSaved"),...e.map(e=>`- ${e}`)].join("\n"),display:!0})}return t},[g,x,e,n,S]),E=y>0,$=b<g.length,R=(s,g={})=>{let x=g.messageOverride??e[s],v=s-1;for(;v>=0&&tm(t[v]);)v-=1;let y="user"===x.role&&v>=0&&"assistant"===e[v].role?t[v]:void 0,b=g.keyPrefix??"message",w=!1;if("assistant"===x.role){w=!0;for(let t=s+1;t<e.length;t++){let n=e[t].role;if("user"===n)break;if("assistant"===n){w=!1;break}}w&&d&&s===e.length-1&&(w=!1)}return void 0!==g.showTimestamp&&(w=g.showTimestamp),(0,r.jsx)(aC,{message:x,toolResults:n,modelNames:a,cwd:i,onOpenFile:l,entryId:t[s],onFork:o||c||0===s&&"user"===x.role?void 0:u,forking:h===t[s],onNavigate:o?void 0:p,prevAssistantEntryId:o?void 0:y,onEditContent:m,showTimestamp:w,prevTimestamp:s>0?e[s-1].timestamp:void 0,sessionId:f,writtenFiles:g.writtenFiles,hasTurnSummary:void 0!==g.turnSummary,inputTranslation:"user"===x.role?I.get(s):void 0,recoveredError:e8(e,s)},`${b}-view-${s}`)},L=(t,n)=>{let s=g[t],a="message"===s.kind&&e[s.idx]?.role==="user";return(0,r.jsx)("div",{"data-chat-item":t,"data-chat-question":a?"":void 0,className:j===t?"chat-item chat-jump-flash":"chat-item",children:n})};return(0,r.jsxs)(r.Fragment,{children:[E&&(0,r.jsx)("div",{ref:w,className:"py-3 text-center text-xs text-text-muted",children:S("chat.loadEarlier",{count:y})}),g.slice(y,b).map((a,o)=>{let c=y+o,d="message"===a.kind?a.anchorIdx??a.idx:a.anchorIdx,u=g[c+1],h=u?"message"===u.kind?u.anchorIdx??u.idx:u.anchorIdx:null,p=u?u.idx:1/0,m=N.filter(n=>{let r=null!==n.anchorEntryId?t.indexOf(n.anchorEntryId):Math.min(n.liveIndex??-1,e.length-1);return r>=a.idx&&r<p}).map(e=>(0,r.jsx)(pe,{sticker:e.sticker,text:e.text,tag:e.tag,followRef:T},`cue-${e.id}`)),x=h!==d,b=M.get(c),w=b?(0,r.jsx)(aC,{message:b,cwd:i,onOpenFile:l},`saved-lessons-${c}`):null,k=x?(0,r.jsx)(c2,{turnIndex:d,turnEntryId:t[d],sessionId:f,cwd:i,onOpenFile:l}):null;if("message"===a.kind)return(0,r.jsxs)(s.Fragment,{children:[L(c,R(a.idx)),w,k,m]},`message-${a.idx}`);let j=tF(a.precedingBlocks,n,i),S=v.get(c);return(0,r.jsxs)(s.Fragment,{children:[L(c,R(a.idx,{keyPrefix:`answer-${a.runIndex}`,messageOverride:function(e,t){let n=e1(e,t);if(!e.replyTranslation)return n;let r=e.content.find(e=>"text"===e.type);return r&&t.includes(r)||(n.replyTranslation=void 0,"translated"===e.replyTranslation.kind&&(n.content=t.filter(e=>"text"!==e.type))),n}(e[a.idx],a.blocks),writtenFiles:j,turnSummary:S})),S&&(0,r.jsx)(cE,{summary:S,turnKey:c}),w,k,m]},`answer-${a.idx}-${a.runIndex}`)}),$&&(0,r.jsx)("div",{ref:k,className:"py-3 text-center text-xs text-text-muted",children:S("chat.loadLater",{count:g.length-b})})]})});function pl({session:e,newSessionCwd:t,newSessionAutoWorktree:i,initialSessionData:l,transitioning:o=!1,onAgentEnd:c,onAttentionNeeded:d,onSessionCreated:u,onSessionForked:h,modelsRefreshKey:p,chatInputRef:m,onBranchDataChange:f,onSystemPromptChange:g,onSessionStatsChange:v,onSessionStatsPanelOpen:y,onContextUsageChange:b,onSubagentsChange:w,onLabWidgetsChange:k,onOpenWorkspaceView:j,onOpenSessionList:S,onRevealToolCall:C,composerStartPlace:N,composerNotice:T,onBrowserUse:I,onOpenMaker:M,selectedMaker:E,onProcessLogChange:$,onOpenFile:R,transcriptReplacement:L,onComposerFocusChange:P,onSessionBusyChange:A,onWaitingChange:_,onAttentionChange:O,soundEnabled:z=!0,onSoundToggle:D,playCueSound:W=async()=>({sticker:null,text:null}),preloadCueSound:H,unlockAudio:B,jumpRequest:q=null,onJumpHandled:V,turnInspectorTarget:K=null,onShowTurnInspector:J,turnInspectorFolded:G=!1,shellConnected:Y=!0}){var Z,Q;let X,et,en,{t:er}=(0,F.s)(),es=h6(),ea=U(),el=es&&ea,eo=(0,s.useRef)(W);eo.current=W;let ec=(0,s.useRef)(null),ed=(0,s.useRef)(H);ed.current=H;let[eu,eh]=(0,s.useState)([]),ep=(0,s.useRef)(eu);ep.current=eu;let em=(0,s.useRef)(0),ef=(0,s.useRef)([]),eg=(0,s.useRef)([]),ex=(0,s.useRef)(null),ev=(0,s.useRef)(0),ey=(0,s.useRef)(-1),eb=(0,s.useRef)(-1),ew=(0,s.useCallback)(()=>{let e=ex.current?.current;return e?{sessionId:e,turn:ev.current}:null},[]),ek=(0,s.useCallback)(e=>ex.current?.current===e.sessionId&&ev.current===e.turn,[]),ej=(0,s.useCallback)((e,t,n,r)=>{if(!e.sticker&&!e.text)return;em.current=Math.max(em.current+1,Date.now());let s={id:em.current,sticker:e.sticker,text:e.text,tag:t,sessionId:n.sessionId},a="entry"===r.kind?{...s,anchorEntryId:r.entryId}:{...s,anchorEntryId:null,liveIndex:r.liveIndex,intent:r.intent};eh(e=>{let t=[...e,a];return null!==a.anchorEntryId&&pr(n.sessionId,t),t})},[]),eS=(0,s.useCallback)((e,t,n,r)=>{let s=()=>ek(n)&&("working"!==t||eb.current!==n.turn);s()&&eo.current(e,t,s).then(e=>{null!==t&&null!==r&&s()&&ej(e,t,n,r)}).catch(()=>{})},[ek,ej]),eC=(0,s.useCallback)(async(e,t,n,r)=>{let s=(await sA(e,t,n,r))?.alias??null;return s&&ed.current?.(s),s},[]),eN=(0,s.useCallback)((e,t,n,r,s)=>{let a=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 s=rP(e[n]),a=0;for(let t=r;t<=n;t++)rP(e[t])===s&&(a+=1);return{kind:"pending",liveIndex:n,intent:{baseEntryId:r>0?t[r-1]:null,identity:s,occurrence:a}}}(ef.current,eg.current);eC(t.sessionId,n,r,s).then(n=>{eS(n,e,t,a)})},[eS,eC]),[eT,eI]=(0,s.useState)(0),eM=(0,s.useRef)([]),eE=(0,s.useCallback)(e=>{if(ev.current+=1,null!==rN(e.outcome)){let t=e.sessionId;eM.current.push({completion:e,trigger:t?{sessionId:t,turn:ev.current}:null}),eI(e=>e+1)}c?.(e)},[c]);(0,s.useEffect)(()=>{for(let{completion:e,trigger:t}of eM.current.splice(0)){let n=rN(e.outcome),r="neutral"===n?null:n;t?eN(r,t,e.provider,e.credentialId,e.model):eo.current(null,r).catch(()=>{})}},[eT,eN]);let e$=(0,s.useCallback)(e=>{m?.current?.replaceMessage(e)},[m]),eR=(0,s.useRef)(-1),eL=(0,s.useCallback)(t=>{"ego_browser"===t&&e?.id&&I?.(e.id,eR.current)},[I,e?.id]),{loading:eP,error:eA,messages:e_,entryIds:eF,streamState:eO,agentRunning:ez,bashRunning:eD,pendingBash:eW,modelNames:eU,modelList:eB,modelError:eq,modelScopeWarnings:eV,modelThinkingLevels:eK,modelThinkingLevelMaps:eJ,modelRoles:eG,toolPreset:eY,thinkingLevel:eZ,effectiveThinkingLevel:eQ,thinkingCeiling:eX,fastMode:e0,fastModeBusy:e2,handleFastModeToggle:e3,retryInfo:e7,contextUsage:tt,forkingEntryId:tn,isCompacting:ts,compaction:ta,compactError:td,compactResult:tx,displayModel:tv,modelSwitching:tb,sessionStats:tw,runStateKnown:tk,compactedWork:tj,slashCommands:tS,slashCommandsLoading:tC,deliveryRows:tN,subagents:tT,todoPhases:tI,notices:tM,extensionDialog:tE,extensionResponse:t$,extensionCustomUi:tR,extensionStatuses:tL,extensionWidgets:tP,respondToExtensionUi:tA,sendExtensionCustomInput:t_,isAutoModelSelection:tF,agentPhase:tO,isNew:tz,autoFollowPaused:tD,resumeAutoFollow:tW,pauseAutoFollow:tU,goalStatus:tB,sessionIdRef:tq,messagesEndRef:tV,scrollContainerRef:tJ,handleSend:tY,handleAbort:tZ,handleFork:tQ,handleNavigate:tX,handleModelChange:t0,handleRoleModelChange:t1,handleMainPresetChange:t2,newSessionAccount:t4,handleCompact:t8,handleSteer:t5,handleFollowUp:t6,handlePromptWithStreamingBehavior:t3,handleAbortCompaction:t7,handleRecallQueue:t9,handleRemoveQueuedMessage:ne,handleBuiltinSlashCommand:nt,handleToolPresetChange:nn,handleThinkingLevelChange:nr,loadSlashCommands:ns,ensureNewSession:na,refreshLiveTranscript:ni}=function(e){let{session:t,newSessionCwd:r,initialData:a,onAgentEnd:i,onAttentionNeeded:l,onSessionCreated:o,onSessionForked:c,modelsRefreshKey:d,onBranchDataChange:u,onSystemPromptChange:h,onSessionStatsPanelOpen:p}=e,m=(0,s.useRef)(e.onToolStart);m.current=e.onToolStart;let f=null===t&&null!==r,g=a&&a.sessionId===t?.id?a:null,[x,v]=(0,s.useState)(g),[y,b]=(0,s.useState)(!f&&!g),[w,k]=(0,s.useState)(null),[j,S]=(0,s.useState)(g?.leafId??null),[C,N]=(0,s.useState)(g?.context.messages??[]),[T,I]=(0,s.useState)(g?.context.entryIds??[]),[M,E]=(0,s.useState)(g?.context.compactedWork??null),[$,R]=(0,s.useReducer)(hL,{isStreaming:!1,streamingMessage:null}),[L,P]=(0,s.useState)(!1),[A,_]=(0,s.useState)(!1),[F,O]=(0,s.useState)(null),[z,D]=(0,s.useState)({}),[W,H]=(0,s.useState)([]),[U,B]=(0,s.useState)(null),[q,V]=(0,s.useState)([]),[K,J]=(0,s.useState)({}),[G,Y]=(0,s.useState)({}),[Z,Q]=(0,s.useState)([]),[X,ee]=(0,s.useState)(null),[et,en]=(0,s.useState)(null),[er,es]=(0,s.useState)(null),[ea,el]=(0,s.useState)("default"),[eo,ec]=(0,s.useState)(()=>{let e=g?.context.thinkingLevel;return e&&"off"!==e?e:"auto"}),[ed,eu]=(0,s.useState)(),[eh,ep]=(0,s.useState)(null),[em,ef]=(0,s.useState)(null),[eg,ex]=(0,s.useState)(!1),ev=(0,s.useRef)(0),ey=(0,s.useRef)(0),eb=(0,s.useRef)(""),[ew,ek]=(0,s.useState)(null),[ej,eS]=(0,s.useState)(g?.contextUsage??null),[eC,eN]=(0,s.useState)(null),[eT,eI]=(0,s.useState)(null),[eM,eE]=(0,s.useState)(null),[e$,eR]=(0,s.useState)(null),[eL,eP]=(0,s.useState)(!1),[eA,e_]=(0,s.useState)(!1),[eF,eO]=(0,s.useState)(null),[ez,eD]=(0,s.useState)(null),[eW,eU]=(0,s.useState)(null),eB=(0,s.useRef)(null),[eq,eV]=(0,s.useState)(!1),[eK,eJ]=(0,s.useState)(null),[eG,eY]=(0,s.useState)([]),[eZ,eQ]=(0,s.useState)(!1),[eX,e0]=(0,s.useReducer)(hq,{visible:[],pending:[]}),[e1,e2]=(0,s.useState)(null),[e4,e8]=(0,s.useState)(null),e5=(0,s.useRef)(null),e6=(0,s.useRef)(null),[e3,e7]=(0,s.useState)(null),e9=(0,s.useRef)(null),[te,tt]=(0,s.useState)(null),[tn,tr]=(0,s.useState)([]),[ts,ta]=(0,s.useState)([]),[ti,tl]=(0,s.useState)({steering:[],followUp:[]}),[to,td]=(0,s.useState)([]),[tu,th]=(0,s.useReducer)(on,[]),tg=(0,s.useRef)(0);(0,s.useEffect)(()=>{th({type:"queue",steering:ti.steering,followUp:ti.followUp})},[ti]),(0,s.useEffect)(()=>{L||th({type:"idle"})},[L]),(0,s.useEffect)(()=>{th({type:"reset"})},[t?.id]);let tx=(0,s.useMemo)(()=>(function(e,t){let n=new Map;for(let t of e){if(!t.inQueue)continue;let e=`${t.kind}\u0000${oe(t)}`;n.set(e,(n.get(e)??0)+1)}let r=[],s=(e,t)=>{t.forEach((t,s)=>{let a=`${e}\u0000${l9(t)}`,i=n.get(a)??0;i>0?n.set(a,i-1):r.push({key:`queue-${e}-${s}`,kind:e,text:t,images:0,stage:"accepted",removable:!0})})};for(let n of(s("steer",t?.steering??[]),s("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})(tu,ti),[tu,ti]),[tv,ty]=(0,s.useState)(null),tb=(0,s.useRef)(null),tw=(0,s.useRef)(null),tk=(0,s.useRef)(null),tj=(0,s.useRef)(null),tS=(0,s.useRef)(null),tC=(0,s.useRef)(0),tN=(0,s.useRef)(!1),tT=(0,s.useRef)(t?.id??null),tI=(0,s.useRef)(g?.leafId??null),tM=(0,s.useRef)(C),tE=(0,s.useRef)(T);tM.current=C,tE.current=T;let t$=(0,s.useRef)({sessionId:t?.id??null,outputs:[],seq:0}),tR=(0,s.useRef)(!1),tL=(0,s.useRef)(new Set);(0,s.useEffect)(()=>()=>hZ(tL.current),[]);let tP=(0,s.useRef)(!1),tA=(0,s.useRef)(!1),t_=(0,s.useRef)(-1),tF=(0,s.useRef)("unknown"),tO=(0,s.useRef)(null),tz=(0,s.useRef)(null),tD=(0,s.useRef)(0),tW=(0,s.useRef)(!1),tH=(0,s.useRef)(0),tU=(0,s.useRef)(null),tB=(0,s.useRef)(null),tq=(0,s.useRef)(null),tV=(0,s.useRef)(!1),tK=(0,s.useRef)(!0),[tJ,tG]=(0,s.useState)(!1),[tY,tZ]=(0,s.useState)(null),tQ=(0,s.useRef)(void 0),tX=(0,s.useRef)(0),t0=(0,s.useRef)(null),t1=(0,s.useRef)(0),t2=(0,s.useRef)(()=>{}),t4=(0,s.useRef)(null),t8=(0,s.useRef)(null),t5=(0,s.useRef)(null),t6=(0,s.useRef)(null),t3=(0,s.useRef)(!1),t7=(0,s.useRef)(null),t9=(0,s.useRef)(null),ne=(0,s.useRef)(null),nt=(0,s.useRef)(null),nn=(0,s.useRef)(null),nr=(0,s.useRef)(0),ns=(0,s.useRef)(null),na=(0,s.useRef)(null),ni=(0,s.useRef)(!1);ni.current=e.transitioning??!1;let nl=(0,s.useRef)(Date.now()),no=(0,s.useRef)(0),nc=(0,s.useRef)(0),nd=(0,s.useRef)(null),nu=(0,s.useRef)(!1),nh=(0,s.useRef)(Promise.resolve()),np=e.setToolPreset??el,nm=eM??x?.context.model??e$??null,nf=f?X??er:nm,ng=(0,s.useMemo)(()=>{if(e1)return{...e1,totalActiveMs:x?.totalActiveMs};let e={input:0,output:0,cacheRead:0,cacheWrite:0,total:0},n=0,r=0,s=0,a=0,i=0;for(let t of C){if("user"===t.role&&(r+=1),"toolResult"===t.role&&(a+=1),"assistant"!==t.role)continue;s+=1;let l=t.usage;i+=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===C.length)?null:{sessionFile:x?.filePath||void 0,sessionId:tT.current??t?.id??"",sessionName:t?.name,userMessages:r,assistantMessages:s,toolCalls:i,toolResults:a,totalMessages:C.length,tokens:e,cost:n,totalActiveMs:x?.totalActiveMs,...ej?{contextUsage:ej}:{}}},[C,e1,ej,x?.filePath,x?.totalActiveMs,t?.id,t?.name]),nx=(0,s.useRef)(0),nv=(0,s.useCallback)((e,t)=>{e&&tT.current===e&&Array.isArray(t)&&(nx.current+=1,ty(n=>n?.sid===e&&hF(n.phases,t)?n:{sid:e,phases:t}))},[]),ny=(0,s.useCallback)((e,t,n)=>{tT.current===e&&nx.current===n&&Array.isArray(t)&&ty(n=>n?.sid===e&&hF(n.phases,t)?n:{sid:e,phases:t})},[]),nb=(0,s.useCallback)(e=>{let t="function"==typeof e?e(tM.current):e;tM.current=t,N(t)},[]),nw=(0,s.useCallback)(e=>{tE.current=e,I(e)},[]),nk=(0,s.useCallback)(async(e,t=!1,n=!1,r)=>{let s=!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&&(v(null),S(null),nb([]),E(null),k(null)),null;if(!r.ok)throw Error(`HTTP ${r.status}`);a=await r.json()}if(tT.current!==e)return null;v(a),S(a.leafId),tI.current=a.leafId??null;let i=tf(a.context.messages,a.context.entryIds??[],t$.current.sessionId===e?t$.current.outputs:[]);nb(i.messages),nw(i.entryIds),E(a.context.compactedWork??null),eS(a.contextUsage??null),eE(e=>nu.current?e:null),k(null);let l=!n&&nn.current===e;if(l||(ec(a.context.configuredThinkingLevel??a.context.thinkingLevel??"off"),eu(a.context.thinkingLevel)),ep(a.context.thinkingCeiling??null),s=!0,t&&b(!1),!n){if(l)try{let t=nr.current,n=await fetch(`/api/sessions/${encodeURIComponent(e)}/state`);if(n.ok&&tT.current===e){let r=await n.json();tT.current===e&&nr.current===t&&(r.state?.thinkingLevel!==void 0?(ec(r.state.configuredThinkingLevel??r.state.thinkingLevel),eu(r.state.thinkingLevel)):r.running||(nn.current=null,ec(a.context.configuredThinkingLevel??a.context.thinkingLevel??"off"),eu(a.context.thinkingLevel)))}}catch(e){console.error("Failed to refresh live thinking level:",e)}return null}try{let t=nx.current,n=await fetch(`/api/sessions/${encodeURIComponent(e)}/state`);if(!n.ok)throw Error(`HTTP ${n.status}`);let r=await n.json();if(tT.current!==e)return null;let s=r.state;return s?(void 0!==s.contextUsage&&eS(s.contextUsage??null),void 0!==s.systemPrompt&&eN(s.systemPrompt??null),void 0!==s.thinkingLevel&&(nn.current=e,ec(s.configuredThinkingLevel??s.thinkingLevel),eu(s.thinkingLevel)),void 0!==s.thinkingCeiling&&ep(s.thinkingCeiling??null),void 0!==s.extensionStatuses&&tr(s.extensionStatuses??[]),void 0!==s.extensionWidgets&&ta(s.extensionWidgets??[]),void 0!==s.queuedMessages&&tl(hP(s.queuedMessages)),void 0!==s.subagents&&td(e=>hR(e,s.subagents??[])),ny(e,s.todoPhases,t)):r.running||tl({steering:[],followUp:[]}),r}catch(e){return console.error("Failed to load agent state:",e),null}}catch(e){return k(String(e)),null}finally{t&&!s&&b(!1)}},[ny,nw,nb]),nj=(0,s.useCallback)(e=>{let t=nh.current.then(async()=>{tT.current===e&&await nk(e)});return nh.current=t.catch(()=>{}),t},[nk]),nS=(0,s.useCallback)(async(e,t)=>{let n=++ey.current;try{let r=new URLSearchParams({deferThinking:"1",deferMedia:"1"});t&&r.set("leafId",t);let s=`/api/sessions/${encodeURIComponent(e)}/context?${r}`,a=await fetch(s);if(!a.ok)throw Error(`HTTP ${a.status}`);let i=await a.json();if(ey.current!==n||tT.current!==e)return;tI.current=t;let l=tf(i.context.messages,i.context.entryIds??[],t$.current.sessionId===e?t$.current.outputs:[]);nb(l.messages),nw(l.entryIds),E(i.context.compactedWork??null),eS(i.contextUsage??null)}catch(e){console.error("Failed to load context:",e)}},[nw,nb]),nC=(0,s.useCallback)(async e=>{try{let t=await hx(e,{type:"get_tools"});if(t){let{getPresetFromTools:e}=await Promise.resolve().then(n.bind(n,14755));np(e(t))}}catch(e){console.error("Failed to load tools:",e)}},[np]),nN=(0,s.useCallback)((e=0,t="(no messages)")=>{let n=tT.current;if(!f||!r||!n||t3.current)return;let s=t7.current??r;t3.current=!0,o?.({id:n,path:"",cwd:s,...s!==r?{projectRoot:r}:{},name:void 0,created:new Date().toISOString(),modified:new Date().toISOString(),messageCount:e,firstMessage:t,transient:!0})},[f,r,o]),nT=(0,s.useCallback)(async()=>{if(t5.current)return t5.current;let t=tT.current;if(t&&na.current!==t||!t&&(!f||!r))return t;let n=(async()=>{let n=t;if(!n){let t=t9.current,s=nt.current,a=ne.current;t&&eR(t);let i={cwd:r,type:"ensure_session",toolNames:(0,uA.xG)(ea),...void 0!==e.newSessionAutoWorktree?{autoWorktree:e.newSessionAutoWorktree}:{},...t?{provider:t.provider,modelId:t.modelId}:{},...s?{thinkingLevel:s}:{},...t&&null!==a?{oauthPosition:a}:{}},l=JSON.stringify(i),o=t6.current,c=o?.body===l?o.createRequestId:hH();t6.current={body:l,createRequestId:c};let d=await fetch("/api/agent/new",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...i,createRequestId:c})});if(!d.ok)throw Error((await d.json().catch(()=>({}))).error??`HTTP ${d.status}`);let u=await d.json();t6.current=null,n=u.sessionId,tT.current=n,t7.current=u.cwd??r??null,t7.current&&ei(t7.current,u.worktree),null!==ns.current&&(na.current=n),u.model&&t9.current===t&&(eR(u.model),t||es(u.model)),u.thinkingLevel&&nt.current===s&&(ec(u.configuredThinkingLevel??u.thinkingLevel),eu(u.thinkingLevel))}for(;na.current===n;){let e=ns.current;await hx(n,{type:"set_thinking_ceiling",ceiling:e}),ns.current===e&&na.current===n&&(na.current=null)}return n})();t5.current=n;try{return await n}finally{t5.current=null}},[f,r,ea,e.newSessionAutoWorktree]),nI=(0,s.useCallback)(async()=>{let e=tT.current??await nT();if(!e)return eY([]),[];eQ(!0);try{let t=await hx(e,{type:"get_commands"}),n=t?.commands??[];return eY(n),n}catch(e){return console.error("Failed to load slash commands:",e),eY([]),[]}finally{eQ(!1)}},[nT]),nM=(0,s.useCallback)(()=>{tC.current+=1,tN.current=!1,tS.current&&(clearTimeout(tS.current),tS.current=null)},[]),nE=(0,s.useCallback)(()=>{tb.current?.close(),tb.current=null,tw.current=null,tk.current=null},[]),n$=(0,s.useCallback)(()=>{tj.current?.close(),tj.current=null},[]),nR=(0,s.useCallback)(e=>{n$();let t=new EventSource(`/api/agent/${encodeURIComponent(e)}/events?entries=1`);tj.current=t,t.onmessage=t=>{try{let n=JSON.parse(t.data);"session_snapshot"===n.type?tU.current?.(n):"agent_start"===n.type&&tB.current?.(e)}catch{}}},[n$]),nL=(0,s.useCallback)(e=>{nE();let t=new EventSource(`/api/agent/${encodeURIComponent(e)}/events`);tb.current=t,tw.current=e;let n=new Promise(n=>{let r=!1,s=e=>{r||(r=!0,clearTimeout(a),tk.current?.source===t&&(tk.current.pending=!1),n({status:e,source:t}))},a=setTimeout(()=>s("timeout"),5e3);t.onmessage=e=>{try{let n=JSON.parse(e.data);if("connected"===n.type&&s("connected"),tb.current!==t)return;"update_maintenance"===n.type&&window.dispatchEvent(new CustomEvent("ompweb:update-maintenance",{detail:n})),tU.current?.(n)}catch{}},t.onerror=()=>{if(t.readyState===EventSource.CLOSED&&(s("closed"),tb.current===t&&(tR.current||tN.current))){tb.current=null,tw.current=null,tk.current=null;let t=tC.current;setTimeout(()=>{t===tC.current&&!tb.current&&(tR.current||tN.current)&&nL(e)},1e3)}}});return tk.current={source:t,promise:n,pending:!0},n},[nE]),nP=(0,s.useCallback)(async e=>{let t=tb.current;if(t&&tw.current===e){if(t.readyState===EventSource.OPEN)return;let e=tk.current;if(e?.source===t&&e.pending&&(await e.promise,tb.current===t&&t.readyState===EventSource.OPEN))return}let n=await nL(e);if("connected"!==n.status&&n.source.readyState!==EventSource.OPEN)throw tb.current===n.source&&(tb.current=null),tw.current===e&&(tw.current=null),tk.current?.source===n.source&&(tk.current=null),n.source.close(),new hW(n.status)},[nL]),nA=(0,s.useCallback)(e=>{e5.current=e.id,e8(e),l?.(e)},[l]),n_=(0,s.useCallback)(e=>{if(e6.current?.id===e&&(e6.current=null),e5.current===e){let e=e6.current;e6.current=null,e?nA(e):(e5.current=null,e8(null))}e9.current?.id===e&&(e9.current=null,e7(null))},[nA]),nF=(0,s.useCallback)(async(e,t)=>{if(e5.current!==e.id)return;let n=e9.current;if(n?.id===e.id&&"sending"===n.status)return;let r=tT.current,s=e=>{e9.current=e,e7(e)};if(!r)return void s({id:e.id,status:"failed",error:"no session"});s({id:e.id,status:"sending"});try{await hx(r,{type:"extension_ui_response",id:e.id,...t})}catch(t){if(tT.current!==r||e5.current!==e.id)return;s({id:e.id,status:"failed",error:t instanceof Error?t.message:String(t)});return}tT.current===r&&n_(e.id)},[n_]),nO=(0,s.useCallback)(async(e,t)=>{let n=tT.current;if(n)try{await hx(n,{type:"extension_ui_input",id:e.id,data:t})}catch(e){console.error("Failed to send extension custom UI input:",e)}},[]),nz=(0,s.useCallback)(e=>{let t=e.message.trim();t&&e0({type:"add",notice:{id:e.id??hH(),message:t,type:e.type??"info"}})},[]),nD=(0,s.useCallback)(e=>{let t={role:"custom",customType:tc,content:eH(e).trim(),display:!0,timestamp:Date.now()},n=t$.current,r=tT.current;n.sessionId!==r&&(n.sessionId=r,n.outputs=[]);let s=tE.current.slice(0,tM.current.length),a=null;for(let e=s.length-1;e>=0;e--)if(!tm(s[e])){a=s[e];break}n.seq+=1,n.outputs.push({entryId:`${tp}${n.seq}`,baseEntryId:a,message:t});let i=tf(tM.current,tE.current,n.outputs);nb(i.messages),nw(i.entryIds)},[nb,nw]),nW=(0,s.useCallback)((t,n)=>{if("custom"!==t.method&&"closed"in t&&t.closed)return void n_(t.id);switch("custom"===t.method&&hm(t)&&l?.(t),t.method){case"select":case"confirm":case"input":case"editor":case"ask":case"form":case"plan_review":{let e=e5.current;if(e===t.id)break;if(null!==e&&n){e6.current=t;break}e6.current=null,null!==e&&n_(e),nA(t);break}case"notify":nz({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)}},[nz,n_,l,e.chatInputRef,nA]),nH=(0,s.useCallback)(()=>{let e=tR.current;return tR.current=!1,P(!1),eJ(null),hZ(tL.current),ek(null),R({type:"end"}),e},[]),nU=(0,s.useCallback)(()=>{tF.current="unknown",tO.current=null;let e=hz(tM.current,tE.current);tz.current=e?{entryId:e.entryId,key:hJ(e.message)}:null,tD.current+=1},[]),nB=(0,s.useCallback)(()=>{let e=tF.current,t=tO.current;if("unknown"===e){let n=hz(tM.current,tE.current),r=n?.message,s=tz.current;null!==n&&(null===s||(null!==n.entryId&&null!==s.entryId?n.entryId!==s.entryId:hJ(n.message)!==s.key))&&r?.role==="assistant"&&r.stopReason&&(e=hO(r),t??={provider:r.provider,...r.model?{model:r.model}:{},...void 0!==r.credentialId?{credentialId:r.credentialId}:{}})}return{outcome:e,sessionId:tT.current,...t?{provider:t.provider,...t.model?{model:t.model}:{},...void 0!==t.credentialId?{credentialId:t.credentialId}:{}}:{}}},[]),nq=(0,s.useCallback)(e=>{let t=nB();if("unknown"!==t.outcome||!e)return void i?.(t);let n=tD.current;e.catch(()=>void 0).then(()=>{let e=tT.current===t.sessionId&&tD.current===n;i?.(e?nB():t)})},[i,nB]),nV=(0,s.useCallback)((e,t)=>t_.current!==e&&(t_.current=e,nq(t),!0),[nq]),nK=(0,s.useCallback)(e=>{nM(),tN.current=!0;let t=tC.current,n=async()=>{if(t===tC.current&&tT.current===e&&tN.current)try{let r=nx.current,s=e5.current,a=e6.current,i=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(!i.ok)throw Error(`HTTP ${i.status}`);let l=await i.json();if(t!==tC.current||tT.current!==e||!tN.current)return;let o=l.state;if(td(e=>hR(e,o?.subagents??[])),ny(e,o?.todoPhases,r),l.running&&o&&(o.isStreaming||o.isPromptRunning||o.isHandoffRunning)){tN.current=!1,tS.current=null,tP.current=!!o?.isStreaming,tA.current=!!o?.isPromptRunning,tR.current=!0,P(!0),eJ(o?.isStreaming?{kind:"waiting_model"}:{kind:"running_command"});return}if(l.running&&o?.isCompacting){e_(!0),eU(h_(o)),tS.current=setTimeout(()=>void n(),600);return}if(l.running&&(o?.subagents?.length??0)>0){tS.current=setTimeout(()=>void n(),1e3);return}let c=!1===l.running?[]:o?.pendingExtensionUiIds;if(c&&s===e5.current&&a===e6.current&&(a&&!c.includes(a.id)&&(e6.current=null),null===s||c.includes(s)||n_(s)),null!==e5.current){tS.current=setTimeout(()=>void n(),3e4);return}tN.current=!1,tS.current=null,nE()}catch{if(t!==tC.current||tT.current!==e||!tN.current)return;tS.current=setTimeout(()=>void n(),600)}};tS.current=setTimeout(()=>void n(),3e4)},[ny,nM,n_,nE]),nJ=(0,s.useCallback)(async(e=tT.current,t=no.current)=>{if(no.current===t)try{e&&await nk(e)}finally{if(no.current!==t)return;let n=tA.current,r=tP.current;tA.current=!1,tP.current=!1,nd.current=null;let s=nH();n?nV(t):r&&s&&nq(),e&&nK(e)}},[nk,nq,nV,nK,nH]),nG=(0,s.useCallback)(async(e,t)=>{await hU(800);let n=Date.now();for(;tR.current&&Date.now()-n<2e4;){if(void 0!==t&&no.current!==t)return;try{let n=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(n.ok){let r=await n.json(),s=r.state;if(!r.running||!s||!s.isStreaming&&!s.isPromptRunning)return void await nJ(e,t)}}catch{}await hU(600)}},[nJ]),nZ=(0,s.useCallback)(async e=>{let t=tH.current+1;for(tH.current=t;tW.current&&tH.current===t&&tT.current===e;){await hU(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 nk(e),tH.current!==t||tT.current!==e)return;tW.current=!1,_(!1),O(null);return}catch{}}},[nk]),nX=(0,s.useCallback)(async e=>{if(!tR.current)return;let t=no.current;try{let n=nx.current,r=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(!r.ok)return;let s=await r.json();if(no.current!==t)return;let a=s.state;if(e_(a?.isCompacting??!1),eU(h_(a)),tl(hP(a?.queuedMessages)),a?.contextUsage!==void 0&&eS(a.contextUsage??null),td(e=>hR(e,a?.subagents??[])),ny(e,a?.todoPhases,n),s.running&&a&&(a.isStreaming||a.isPromptRunning||a.isCompacting||a.isHandoffRunning)||!tR.current)return;a&&(void 0!==a.systemPrompt&&eN(a.systemPrompt??null),void 0!==a.extensionStatuses&&tr(a.extensionStatuses??[]),void 0!==a.extensionWidgets&&ta(a.extensionWidgets??[])),await nJ(e,t)}catch{}},[ny,nJ]),n2=(0,s.useCallback)(async e=>{let t=await nk(e,!1,!0),n=t?.state;return!!t?.running&&!!n&&tT.current===e&&!tR.current&&!!(n.isStreaming||n.isPromptRunning||n.isHandoffRunning)&&(tP.current=!!n.isStreaming,tA.current=!!n.isPromptRunning,tR.current=!0,P(!0),eJ(n.isStreaming?{kind:"waiting_model"}:{kind:"running_command"}),R({type:"start"}),hQ(tL.current,e,n.pendingToolCalls),nL(e),!n.isStreaming&&n.isPromptRunning&&nG(e),!0)},[nL,nk,nG]),n4=(0,s.useCallback)(async(e,t=no.current)=>{let n=nc.current+1;nc.current=n;try{let r=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(!r.ok)return;let s=await r.json();if(n!==nc.current||tT.current!==e||no.current!==t)return;s.state?.contextUsage!==void 0&&eS(s.state.contextUsage??null)}catch{}},[]);(0,s.useEffect)(()=>{if(!eA){eB.current=null,eU(null);return}eU(e=>e??{startedAt:Date.now(),reason:eB.current})},[eA]),(0,s.useEffect)(()=>{if(!L&&!eA)return;let e=()=>{let e=tT.current;e&&n4(e)};e();let t=setInterval(e,1e3);return()=>clearInterval(t)},[L,eA,n4]),(0,s.useEffect)(()=>{if(!L)return;let e=()=>{let e=tT.current;e&&nX(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)}},[L,nX]),(0,s.useEffect)(()=>{if(L)return;let e=()=>{let e=tT.current;e&&!tR.current&&n2(e)},t=()=>{"visible"===document.visibilityState&&e()},n=e=>{let t=tT.current,n=e.detail?.sessionId;t&&n===t&&!tR.current&&n2(t).then(e=>{e||tT.current!==t||tR.current||nk(t)})};return document.addEventListener("visibilitychange",t),window.addEventListener("online",e),window.addEventListener(hj,n),()=>{document.removeEventListener("visibilitychange",t),window.removeEventListener("online",e),window.removeEventListener(hj,n)}},[L,n2,nk]),tB.current=e=>{if(tT.current!==e||tR.current||tb.current||tq.current)return;let t=n2(e).then(async t=>{t||tT.current!==e||tR.current||await nk(e)}).catch(()=>{}).finally(()=>{tq.current===t&&(tq.current=null)});tq.current=t},(0,s.useEffect)(()=>{tR.current=L},[L]),tU.current=(0,s.useCallback)(e=>{var t;switch(e.type){case"connected":{let t=e.pendingExtensionUiIds,n=e5.current;if(Array.isArray(t)){let e=e6.current;e&&!t.includes(e.id)&&(e6.current=null),null===n||t.includes(n)||n_(n)}break}case"extension_ui_closed":"string"==typeof e.id&&n_(e.id);break;case"session_snapshot":{let t=function(e,t,n,r,s){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,i=new Map;for(let e of a){let t=hJ(e);i.set(t,(i.get(t)??0)+1)}let l=Math.min(r.length,s.length);for(let e of r.slice(0,l)){let t=hJ(e),n=i.get(t)??0;n>0&&i.set(t,n-1)}let o=r.slice(l).filter(e=>{let t=hJ(e),n=i.get(t)??0;return 0===n||(i.set(t,n-1),!1)});return{entryId:e.entryId,messages:[...a,...o],entryIds:[...e.context.entryIds],compactedWork:e.context.compactedWork??null}}(e,tT.current,tI.current,tM.current,tE.current);if(!t)break;tI.current=t.entryId;let n=tf(t.messages,t.entryIds,t$.current.sessionId===tT.current?t$.current.outputs:[]);nb(n.messages),nw(n.entryIds),E(t.compactedWork);break}case"agent_start":{let e=!tR.current;nM(),e&&nU(),tP.current=!0,tR.current=!0,P(!0),eJ({kind:"waiting_model"}),R({type:"start"});break}case"agent_end":if(!tR.current)break;if(eJ(null),hZ(tL.current),ek(null),R({type:"end"}),tT.current){nk(tT.current);let e=nx.current;fetch(`/api/agent/${encodeURIComponent(tT.current)}`).then(e=>e.json()).then(t=>{t.state?.contextUsage!==void 0&&eS(t.state.contextUsage??null),t.state?.systemPrompt!==void 0&&eN(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=>hR(e,t.state?.subagents??[])),tT.current&&ny(tT.current,t.state?.todoPhases,e),t.state?.goal!==void 0&&tZ(t.state.goal??null),tl(hP(t.state?.queuedMessages))}).catch(()=>{})}break;case"goal_status":tZ(e.status??null);break;case"agent_settled":{let e=tP.current;if(tP.current=!1,!e||tA.current)break;let t=tT.current,n=nH();e_(!1);let r=t?nk(t):void 0;t&&nK(t),n&&nq(r);break}case"prompt_done":{let e=no.current,t=tA.current;tA.current=!1,nd.current=null;let n=t_.current!==e;if(!t&&!n)break;let r=tT.current;nV(e,r?nk(r):void 0),!tP.current&&(nH(),r&&nK(r))}break;case"prompt_error":tF.current="failed",nz({type:"error",message:e.errorMessage??"Command failed"});break;case"extension_error":tF.current="failed",nz({type:"error",message:e.error??"Extension command failed"});break;case"message_start":case"message_update":{if(!tR.current)break;let t=e.message;if(t?.role!=="assistant")break;t&&R({type:"update",message:oS(t)}),eJ(null);break}case"message_end":{if(!tR.current)break;let t=e.message;if(t?.role==="assistant"&&(tO.current={provider:t.provider,...t.model?{model:t.model}:{},...void 0!==t.credentialId?{credentialId:t.credentialId}:{}},tF.current=hO(t)),t&&"user"===t.role){let e=oS(t),n=hK(e),r=nd.current;nd.current=null,nb(t=>{let s=t[t.length-1];return r&&s?.role==="user"&&hK(s)===r?r===n?t:[...t.slice(0,-1),e]:[...t,e]}),r||th({type:"user-message",kind:os(e),text:or(e),images:"user"!==e.role||"string"==typeof e.content?0:e.content.filter(e=>"image"===e.type).length})}else t&&nb(e=>[...e,oS(t)]);let n=tT.current;n&&n4(n),R({type:"reset"}),eJ(e=>t?.role==="toolResult"&&e?.kind==="running_tools"?e:{kind:"waiting_model"});break}case"thinking_level_changed":{let t=tT.current,n=e.thinkingLevel;t&&void 0!==n&&(nn.current=t,nr.current+=1,ec(e.configured??n),eu(n));break}case"todo_changed":nv(tT.current,e.phases);break;case"tool_execution_start":{let t=e.toolCallId,n=e.toolName,r=e.args,s=n0(tT.current,t);s&&tL.current.add(s),eJ(e=>{let s=e?.kind==="running_tools"?[...e.tools]:[];return s.some(e=>e.id===t)||s.push({id:t,name:n,args:r}),{kind:"running_tools",tools:s}}),m.current?.(n);break}case"tool_execution_update":{let n=n0(tT.current,"string"==typeof e.toolCallId?e.toolCallId:null);n&&tL.current.has(n)&&"string"==typeof e.text&&(t=e.text,nY.get(n)!==t&&(nY.set(n,t),nQ()));break}case"tool_execution_end":{let t=e.toolCallId,n=n0(tT.current,t);n&&tL.current.delete(n)&&n1([n]),eJ(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 hR(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=>hR(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=>hR(e,[r]));break}case"queue_update":tl({steering:[...e.steering??[]],followUp:[...e.followUp??[]]});break;case"auto_retry_start":ek({attempt:e.attempt,maxAttempts:e.maxAttempts,errorMessage:e.errorMessage});break;case"auto_retry_end":ek(null);break;case"auto_compaction_start":case"compaction_start":if("string"==typeof e.reason){eB.current=e.reason;let t=e.reason;eU(e=>e?{...e,reason:t}:e)}e_(!0),eO(null),eD(null);break;case"auto_compaction_end":case"compaction_end":if(e_(!1),e.errorMessage)eO(e.errorMessage),eD(null);else if(!e.aborted){eD(hG(e.result,e.reason??"auto"));let t=tT.current;t&&(nk(t),n4(t))}break;case"extension_ui_request":nW(e,!0===e.replayed)}},[nz,nv,ny,nM,n_,nW,nk,nq,nV,n4,nU,nK,nH,nw,nb]);let n8=(0,s.useCallback)(async(n,s,a)=>{let i=n.trim();if(!i&&!s?.length&&!a?.length)return"returned";if(tR.current||tW.current||nu.current)return"unknown";let l=an(n,a??[]),o=!s?.length&&!a?.length&&i.startsWith("/");if(!s?.length&&!a?.length&&i.startsWith("!")){let e=i.startsWith("!!"),t=(e?i.slice(2):i.slice(1)).trim();return t?(await tQ.current?.(t,e),"accepted"):"unknown"}nU();let c=no.current+1;nM(),tA.current=!0;let d=s?.map(e=>({type:"image",source:{type:"base64",media_type:e.mimeType,data:e.data}})),u={role:"user",content:d?.length?[...l.trim()?[{type:"text",text:l}]:[],...d]:l,timestamp:Date.now()};nb(e=>[...e,u]),nd.current=hK(u),no.current=c,tR.current=!0,P(!0),eJ(o?{kind:"running_command"}:{kind:"waiting_model"}),R({type:"start"}),t2.current(!0);let h=s?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),p=null,m=!1,g="unknown";try{if(f&&r){let e=tT.current??await t5.current,t=await nT();t&&(p=t,X&&(eR(X),e&&await hx(t,{type:"set_model",provider:X.provider,modelId:X.modelId})),await nP(t),m=!0,await hx(t,{type:"prompt",message:l,...h?.length?{images:h}:{}}),nN(1,n),g="accepted")}else t&&(p=t.id,await nP(t.id),m=!0,await hx(t.id,{type:"prompt",message:l,...h?.length?{images:h}:{}}),g="accepted");return o&&p&&nG(p,c),g}catch(l){console.error("Failed to send message:",l);let r=l instanceof hg&&"update_draining"===l.code&&!1===l.accepted;if(!(!m||l instanceof hg&&"prompt_rejected"===l.code&&!1===l.accepted||r)&&p)return nG(p,c),"unknown";tA.current=!1,tR.current=!1,nE();let i=nd.current;return i&&nb(e=>{let t=e[e.length-1];return t?.role==="user"&&hK(t)===i?e.slice(0,-1):e}),nz({type:"error",message:l instanceof Error?l.message:String(l)}),e.chatInputRef?.current?.restoreSubmission?.(n,hY(s),a,t?.id??p??void 0),nd.current=null,P(!1),eJ(null),R({type:"end"}),"returned"}},[f,r,X,t,nT,nP,nN,nG,nz,nM,nE,e.chatInputRef,nU,nb]);tQ.current=(0,s.useCallback)(async(n,r)=>{if(tR.current||tW.current)return;let s=`${r?"!!":"!"}${n}`;tW.current=!0,t2.current(!0),O({command:n,excludeFromContext:r}),_(!0);try{let e=tT.current??t?.id??await nT();if(!e)throw Error("Unable to create a session for the shell command");await hx(e,{type:"bash",command:n,excludeFromContext:r}),await nk(e),nN(1,s)}catch(t){console.error("Failed to execute shell command:",t),nz({type:"error",message:t instanceof Error?t.message:String(t)}),e.chatInputRef?.current?.insertIfEmpty(s)}finally{tW.current=!1,O(null),_(!1)}},[nz,nT,nk,e.chatInputRef,nN,t]);let n5=(0,s.useCallback)(async()=>{let e=tT.current;if(e){if(tW.current){try{await hx(e,{type:"abort_bash"})}catch(e){console.error("Failed to abort bash:",e)}return}try{await hx(e,{type:"abort"}),tF.current="aborted"}catch(e){console.error("Failed to abort:",e)}}},[]),n6=(0,s.useCallback)(async e=>{if(tW.current)return{forked:!1,error:"Cannot fork while a shell command is running"};let t=tT.current;if(!t)return{forked:!1,error:"No active session to fork"};eI(e??null);try{let{cancelled:n,newSessionId:r}=await hx(t,{type:"fork",...e?{entryId:e}:{}})??{};if(!n&&r)return c?.(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)}},[c]),n3=(0,s.useCallback)(async e=>{if(tW.current)return;let t=tT.current;t&&(hx(t,{type:"navigate_tree",targetId:e}).catch(()=>{}),S(e),await nS(t,e))},[nS]),n7=(0,s.useCallback)(async e=>{if(tW.current)return;S(e);let t=tT.current;t&&(await nS(t,e),e&&hx(t,{type:"navigate_tree",targetId:e}).catch(()=>{}))},[nS]),n9=(0,s.useCallback)(async(e,t)=>{if(f){let n={provider:e,modelId:t},r=t9.current?.provider===e;t9.current=n,r||(ne.current=null,en(null)),ee(n),eR(n);let s=tT.current??await t5.current;if(!s)return;try{await hx(s,{type:"set_model",provider:e,modelId:t})}catch(e){console.error("Failed to set model:",e)}return}let n=tT.current;if(n&&!nu.current){nu.current=!0,eE({provider:e,modelId:t}),eP(!0);try{await hx(n,{type:"set_model",provider:e,modelId:t}),nu.current=!1,await nk(n)}catch(e){console.error("Failed to set model:",e),nu.current=!1,eE(eM),nz({type:"error",message:`Failed to switch model: ${e instanceof Error?e.message:String(e)}`}),await nk(n)}finally{nu.current=!1,eP(!1)}}},[nz,eM,f,nk,ee]),re=(0,s.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}:{}},s=t=>`${e.alias} preset was not applied: ${t instanceof Error?t.message:String(t)}`;if(f){if(nu.current)return!1;nu.current=!0,eP(!0);let e=t9.current,a=ne.current,i=nt.current;try{t9.current=t,ne.current=n??null,nt.current="auto";let e=tT.current??await t5.current;return e&&await hx(e,r),ee(t),en(n??null),eR(t),ec("auto"),eu(void 0),e&&await nk(e),!0}catch(n){console.error("Failed to apply Main preset:",n),t9.current=e,ne.current=a,nt.current=i,nz({type:"error",message:s(n)});let t=tT.current;return t&&await nk(t),!1}finally{nu.current=!1,eP(!1)}}let a=tT.current;if(!a||nu.current)return!1;nu.current=!0,eE(t),eP(!0);try{return await hx(a,r),await nk(a),!0}catch(e){return console.error("Failed to apply Main preset:",e),eE(eM),nz({type:"error",message:s(e)}),await nk(a),!1}finally{nu.current=!1,eP(!1)}},[nz,eM,ed,f,nk,ee,eo]),rt=(0,s.useCallback)(async e=>{let t=Z.find(t=>t.role===e),n=t?.resolved;if(!n)return;if(f){let e={provider:n.provider,modelId:n.modelId},t=n.thinkingLevel;nt.current=t??null,ec(t??"auto"),eu(void 0),t9.current=e,ne.current=null,en(null),ee(e),eR(e)}let r=tT.current??(f?await t5.current:null);if(r)try{await hx(r,{type:"set_role_model",role:e}),f||eE({provider:n.provider,modelId:n.modelId})}catch(e){console.error("Failed to set role model:",e)}},[f,Z,ee]),rn=(0,s.useCallback)(async()=>{let e=tT.current;if(e&&!eA){eB.current="manual",e_(!0),eO(null),eD(null);try{let t=await hx(e,{type:"compact"});eD(hG(t,"manual")),await nk(e,!0)}catch(e){eO(e instanceof Error?e.message:String(e)),eD(null)}finally{e_(!1)}}},[eA,nk]),rr=(0,s.useCallback)(async e=>{let n=r??t?.cwd??"",s=n?`/api/models?cwd=${encodeURIComponent(n)}`:"/api/models",a=await fetch(s,e?{signal:e}:void 0);if(!a.ok)throw Error(`HTTP ${a.status}`);let i=await a.json();D(i.models),B(i.modelError??null),V(i.modelScopeWarnings??[]),J(i.thinkingLevels??{}),Y(i.thinkingLevelMaps??{}),Q(i.roles??[]);let l=i.modelList??[];if(H(l),f&&!tT.current){let e=(i.defaultModel?l.find(e=>e.id===i.defaultModel?.modelId&&e.provider===i.defaultModel?.provider):void 0)??l[0];es(e?{provider:e.provider,modelId:e.id}:null);let t=e&&i.thinkingLevelPins?.[`${e.provider}/${e.id}`];null===nt.current&&ec(t??"auto")}},[f,r,t?.cwd]),rs=(0,s.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,s=r.trim(),a=await nT(),i=e=>(e.handled&&(e.error?nz({type:"error",message:e.error}):"openSessionStats"!==e.action&&nz({type:"success",message:e.message??"Command completed"})),e);try{switch(n){case"compact":{if(!a||eA)return i({handled:!0,error:"No active session to compact"});eB.current="manual",e_(!0),eO(null),eD(null);let e=await hx(a,{type:"compact",...s?{customInstructions:s}:{}});return eD(hG(e,"manual")),await nk(a,!0)&&nN(),i({handled:!0,message:"Compacted context"})}case"reload":if(!a)return i({handled:!0,error:"No active session to reload"});return await hx(a,{type:"reload"}),await Promise.all([nk(a,!1,!0),nC(a),nI(),rr()]),i({handled:!0,message:"Reloaded session resources"});case"name":if(!a)return i({handled:!0,error:"No active session to name"});if(!s)return i({handled:!0,error:"Usage: /name <name>"});return await hx(a,{type:"set_session_name",name:s}),await nk(a)&&nN(),i({handled:!0,message:`Session renamed to ${s}`});case"session":{if(!a)return i({handled:!0,error:"No active session"});let e=await hx(a,{type:"get_session_stats"});return e&&e2(e),p?.(),i({handled:!0,action:"openSessionStats"})}case"copy":{if(!a)return i({handled:!0,error:"No active session"});let e=await hx(a,{type:"get_last_assistant_text"}),t=e?.text??"";if(!t)return i({handled:!0,error:"No assistant message to copy"});return await navigator.clipboard.writeText(t),i({handled:!0,message:"Copied last assistant message"})}case"fork":{if(!a)return i({handled:!0,error:"No active session to fork"});let e=await n6();if(!e.forked)return i({handled:!0,error:e.error??"Fork failed"});return i({handled:!0,message:"Forked a new session"})}case"goal":{if(!a)return i({handled:!0,error:"No active session"});let e=await hx(a,{type:"goal",args:s});if(tZ(e?.status??null),e?.error)return i({handled:!0,error:e.error});if(e?.message&&e.message.includes("\n")){if(nD(e.message),e.prompt)return{handled:!0,prompt:e.prompt};return{handled:!0}}if(e?.prompt)return e.message&&nz({type:"success",message:e.message}),{handled:!0,prompt:e.prompt};return i({handled:!0,message:e?.message??"Command completed"})}case"handoff":if(!a)return i({handled:!0,error:"No active session"});if(tR.current||tW.current)return i({handled:!0,error:"Cannot hand off while the session is busy"});tR.current=!0,P(!0),eJ({kind:"running_command"});try{await nP(a);let e=await hx(a,{type:"handoff",...s?{customInstructions:s}:{}});if(!e||e.cancelled)return i({handled:!0,error:"Handoff cancelled"});return await nk(a,!0)&&nN(),i({handled:!0,message:"컨텍스트를 현재 세션에 압축했습니다"})}finally{tR.current=!1,P(!1),eJ(null),tT.current===a&&nK(a)}default:{if(!a)return i({handled:!0,error:"No active session"});let t=await hx(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&&nD(n),t.prompt)return{handled:!0,prompt:t.prompt};if(n)return{handled:!0};return i({handled:!0,message:"Command completed"})}}}catch(e){return i({handled:!0,error:e instanceof Error?e.message:String(e)})}finally{"compact"===n&&e_(!1)}},[nz,nD,nP,nT,n6,eA,rr,nk,nI,nC,nN,p,nK]),ra=(0,s.useCallback)(async(t,n,r)=>{let s=tT.current;if(!s)return nz({type:"error",message:"The session is not ready yet, so the message was returned to the composer."}),e.chatInputRef?.current?.restoreSubmission?.(t,hY(n),r),"returned";let a=an(t,r??[]),i=n?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),l=++tg.current;th({type:"submit",id:l,kind:"steer",text:a,images:i?.length??0});try{return await hx(s,{type:"steer",message:a,...i?.length?{images:i}:{}}),th({type:"ack",id:l}),"accepted"}catch(a){return th({type:"fail",id:l}),console.error("Failed to steer:",a),nz({type:"error",message:a instanceof Error?a.message:String(a)}),e.chatInputRef?.current?.restoreSubmission?.(t,hY(n),r,s),"returned"}},[nz,e.chatInputRef]),ri=(0,s.useCallback)(async(t,n,r,s)=>{let a=tT.current;if(!a)return nz({type:"error",message:"The session is not ready yet, so the message was returned to the composer."}),e.chatInputRef?.current?.restoreSubmission?.(t,hY(r),s),"returned";let i=an(t,s??[]),l=r?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),o=++tg.current;th({type:"submit",id:o,kind:n,text:i,images:l?.length??0});try{return await hx(a,{type:"prompt",message:i,streamingBehavior:n,...l?.length?{images:l}:{}}),th({type:"ack",id:o}),"accepted"}catch(n){return th({type:"fail",id:o}),console.error("Failed to queue prompt:",n),nz({type:"error",message:n instanceof Error?n.message:String(n)}),e.chatInputRef?.current?.restoreSubmission?.(t,hY(r),s,a),"returned"}},[nz,e.chatInputRef]),rl=(0,s.useCallback)(async(t,n,r)=>{let s=tT.current;if(!s)return nz({type:"error",message:"The session is not ready yet, so the message was returned to the composer."}),e.chatInputRef?.current?.restoreSubmission?.(t,hY(n),r),"returned";let a=an(t,r??[]),i=n?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),l=++tg.current;th({type:"submit",id:l,kind:"followUp",text:a,images:i?.length??0});try{return await hx(s,{type:"follow_up",message:a,...i?.length?{images:i}:{}}),th({type:"ack",id:l}),"accepted"}catch(a){return th({type:"fail",id:l}),console.error("Failed to follow up:",a),nz({type:"error",message:a instanceof Error?a.message:String(a)}),e.chatInputRef?.current?.restoreSubmission?.(t,hY(n),r,s),"returned"}},[nz,e.chatInputRef]),ro=(0,s.useCallback)(async()=>{let e=tT.current;if(e)try{await hx(e,{type:"abort_compaction"})}catch(e){console.error("Failed to abort compaction:",e)}},[]),rc=(0,s.useCallback)(async()=>{let t=tT.current;if(t)try{var n;let r=await hx(t,{type:"clear_queue"});th({type:"withdraw"}),tl({steering:[],followUp:[]});let s={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?.(s.text,s.images.length?s.images:void 0,void 0,t)}catch(e){console.error("Failed to recall queued messages:",e),nz({type:"error",message:"Failed to recall queued messages"})}},[e.chatInputRef,nz]),rd=(0,s.useCallback)(async(e,t)=>{let n=tT.current;if(n)try{let r=await hx(n,{type:"remove_queued_message",message:t,queue:e});if(!r?.removed)return;th({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),nz({type:"error",message:"Failed to remove queued message"})}},[nz]),ru=(0,s.useCallback)(async(e,t=null)=>{let n="auto"===e?t:null,r=n!==eh;ec(e),ep(n),f&&(!tT.current||na.current===tT.current)&&(nt.current=e,ns.current=n),eu(void 0);let s=tT.current??await t5.current;if(s)try{na.current===s?await nT():r&&await hx(s,{type:"set_thinking_ceiling",ceiling:n}),await hx(s,{type:"set_thinking_level",level:e}),await nk(s)}catch(e){console.error("Failed to set thinking level:",e),nz({type:"error",message:"Failed to set thinking level"}),await nk(s)}},[f,nk,nz,eh,nT]);eb.current=nf?`${nf.provider}/${nf.modelId}`:"";let rh=e=>e?`${e}|${eb.current}`:null,rp=t?.id??tT.current,rm=rh(rp),rf=em&&em.key===rm?em.value:null;(0,s.useEffect)(()=>{let e=++ev.current;rm&&rp&&!L&&!eL&&fetch(`/api/agent/${encodeURIComponent(rp)}`).then(e=>e.json()).then(t=>{ev.current===e&&rh(tT.current)===rm&&ef({key:rm,value:(t.running?hA(t.state):void 0)??null})}).catch(()=>{})},[rm,L,eL]);let rg=(0,s.useCallback)(async()=>{let e=tT.current??await nT(),t=rh(tT.current);if(!e||!t)return;let n=++ev.current,r=()=>ev.current===n&&rh(tT.current)===t,s=e=>{r()&&ef({key:t,value:e})};ex(!0);try{let n=em?.key===t?em.value?.enabled:void 0;if(void 0===n){let t=hA(await hx(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 hx(e,{type:"set_fast_mode",enabled:!n});s({enabled:a?.enabled===!0,active:a?.active===!0})}catch(t){if(!r())return;nz({type:"error",message:t instanceof Error?t.message:String(t)});try{s(hA(await hx(e,{type:"get_state"}))??null)}catch{s(null)}}finally{ex(!1)}},[nT,em,nz]),rx=(0,s.useCallback)(async e=>{let t=(0,uA.xG)(e);np(e);let n=tT.current??await t5.current;if(n)try{await hx(n,{type:"set_tools",toolNames:t})}catch(e){console.error("Failed to set tools:",e)}},[np]),rv=(0,s.useCallback)(e=>{tK.current=e,tG(t=>!e===t?t:!e)},[]);t2.current=e=>{t0.current=null,rv(e)};let ry=(0,s.useCallback)((e="smooth")=>{t1.current=Date.now()+700,t4.current?.scrollIntoView({behavior:e})},[]),rb=(0,s.useCallback)(()=>{tX.current=0,t0.current=null,rv(!0),ry("smooth")},[ry,rv]),rw=(0,s.useCallback)(()=>{tX.current=0,t0.current=null,rv(!1)},[rv]),rk=(0,s.useCallback)(()=>{if(!t0.current)return;t0.current=null;let e=t8.current;e&&rv(e.scrollHeight-e.scrollTop-e.clientHeight<=72)},[rv]),rj=(0,s.useCallback)(e=>{if(e instanceof PointerEvent&&"mouse"===e.pointerType&&1===e.button&&!(e.target instanceof Element&&e.target.closest("a[href], input, textarea"))&&!(e.target instanceof HTMLElement&&e.target.isContentEditable)){if(t0.current)return void rk();rw();let e=t8.current;return void(t0.current=e?{top:e.scrollTop,moved:!1,released:!1}:null)}rk(),e instanceof KeyboardEvent&&(!hD.has(e.key)||e.target instanceof Element&&e.target.closest("input, textarea, [contenteditable='true']"))||(tX.current=Date.now()+1200)},[rk,rw]),rS=(0,s.useCallback)(()=>{let e=t8.current;if(!e)return;let t=t0.current;if(null!==t){let n=t.top;t.moved||=e.scrollTop!==n,t.top=e.scrollTop;return}if(!tR.current&&!tW.current)return;let n=e.scrollHeight-e.scrollTop-e.clientHeight,r=Date.now()<=tX.current;if(!(!r&&Date.now()<t1.current)){if(n<=72)return void rv(!0);r&&rv(!1)}},[rv]);return(0,s.useEffect)(()=>(tT.current=t?.id??null,t$.current.sessionId!==tT.current&&(t$.current={sessionId:tT.current,outputs:[],seq:0}),t&&nk(t.id,!g,!0,g).then(e=>{if(tT.current!==t.id)return;nR(t.id),e?.running&&(nC(t.id),(e.state?.isStreaming||e.state?.isPromptRunning||e.state?.isHandoffRunning)&&(tP.current=!!e.state.isStreaming,tA.current=!!e.state.isPromptRunning,tR.current=!0,P(!0),eJ(e.state.isStreaming?{kind:"waiting_model"}:{kind:"running_command"}),R({type:"start"}),hQ(tL.current,t.id,e.state.pendingToolCalls),nL(t.id),!e.state.isStreaming&&e.state.isPromptRunning&&nG(t.id)),e.state?.isBashRunning&&(tW.current=!0,_(!0),nZ(t.id)),(e.state?.subagents?.length??0)>0&&nL(t.id));let n=e?.state;n&&(void 0!==n.isCompacting&&e_(n.isCompacting),eU(h_(n)),void 0!==n.contextUsage&&eS(n.contextUsage??null),void 0!==n.systemPrompt&&eN(n.systemPrompt??null),void 0!==n.thinkingLevel&&(nn.current=t.id,ec(n.configuredThinkingLevel??n.thinkingLevel),eu(n.thinkingLevel)),void 0!==n.thinkingCeiling&&ep(n.thinkingCeiling??null),void 0!==n.extensionStatuses&&tr(n.extensionStatuses??[]),void 0!==n.extensionWidgets&&ta(n.extensionWidgets??[]),void 0!==n.queuedMessages&&tl(hP(n.queuedMessages)),void 0!==n.subagents&&td(e=>hR(e,n.subagents??[])),void 0!==n.goal&&tZ(n.goal??null)),e&&eV(!0)}),()=>{tH.current+=1,nM(),e6.current=null,null!==e5.current&&n_(e5.current),nE(),n$()}),[t?.id]),(0,s.useEffect)(()=>{h?.(eC)},[eC,h]),(0,s.useEffect)(()=>{u&&u(x?.tree??[],j,n7)},[x?.tree,j,n7,u]),(0,s.useEffect)(()=>{let e=e=>{let t=t0.current;t&&(1!==e.button||t.released||t.moved||!(e.target instanceof Node&&t8.current?.contains(e.target))?rk():t.released=!0)};return window.addEventListener("pointerup",e,!0),window.addEventListener("keydown",rj),()=>{window.removeEventListener("pointerup",e,!0),window.removeEventListener("keydown",rj)}},[rk,rj]),(0,s.useEffect)(()=>{let e=t8.current;if(!e)return;let t=()=>{t0.current?.moved&&rk()};return e.addEventListener("pointerdown",rj,{passive:!0}),e.addEventListener("wheel",rj,{passive:!0}),e.addEventListener("touchstart",rj,{passive:!0}),e.addEventListener("scroll",rS,{passive:!0}),e.addEventListener("scrollend",t,{passive:!0}),()=>{e.removeEventListener("pointerdown",rj),e.removeEventListener("wheel",rj),e.removeEventListener("touchstart",rj),e.removeEventListener("scroll",rS),e.removeEventListener("scrollend",t)}},[C.length,y,rk,rS,rj]),(0,s.useEffect)(()=>{if(ni.current||!L&&!A||!tK.current)return;let e=t8.current;if(!e)return;let t=requestAnimationFrame(()=>{tK.current&&(t1.current=Date.now()+700,e.scrollTo({top:e.scrollHeight,behavior:"instant"}))});return()=>cancelAnimationFrame(t)},[L,A,C.length,$.streamingMessage,eK,F,e.transitioning]),(0,s.useLayoutEffect)(()=>{if(0!==C.length){if(!tV.current){tV.current=!0,ry("instant");return}if(!ni.current&&tK.current){let e=Date.now()-nl.current<1500;ry(tR.current||tW.current||e?"instant":"smooth")}}},[C.length,L,A,ry,e.transitioning]),(0,s.useEffect)(()=>{let e=new AbortController;return rr(e.signal).catch(e=>{if(e instanceof DOMException&&"AbortError"===e.name)return}),()=>e.abort()},[rr,d]),(0,s.useEffect)(()=>{if(!ez)return;let e=setTimeout(()=>eD(null),6e3);return()=>clearTimeout(e)},[ez]),(0,s.useEffect)(()=>{if(0===eX.visible.length)return;let e=eX.visible.find(e=>e.exiting);if(e){let t=setTimeout(()=>{e0({type:"remove",id:e.id})},180);return()=>clearTimeout(t)}if(!eX.visible[0])return;let t=setTimeout(()=>{e0({type:"mark_oldest_exiting"})},5e3);return()=>clearTimeout(t)},[eX.visible]),(0,s.useEffect)(()=>{e2(null)},[C.length,ej?.tokens,ej?.percent,ej?.contextWindow]),{data:x,loading:y,error:w,activeLeafId:j,messages:C,entryIds:T,streamState:$,agentRunning:L,modelNames:z,modelList:W,modelError:U,modelScopeWarnings:q,modelThinkingLevels:K,modelThinkingLevelMaps:G,modelRoles:Z,newSessionModel:X,toolPreset:ea,thinkingLevel:eo,effectiveThinkingLevel:ed,thinkingCeiling:eh,retryInfo:ew,contextUsage:ej,systemPrompt:eC,forkingEntryId:eT,isCompacting:eA,compaction:eW,compactError:eF,compactResult:ez,currentModel:nm,displayModel:nf,modelSwitching:eL,sessionStats:ng,runStateKnown:eq,slashCommands:eG,slashCommandsLoading:eZ,queuedMessages:ti,deliveryRows:tx,subagents:to,todoPhases:tv&&tv.sid===tT.current?tv.phases:null,compactedWork:M,notices:eX.visible,extensionDialog:e4,extensionResponse:e3,extensionCustomUi:te,extensionStatuses:tn,extensionWidgets:ts,respondToExtensionUi:nF,sendExtensionCustomInput:nO,isAutoModelSelection:f&&null===X,agentPhase:eK,isNew:f,autoFollowPaused:tJ,resumeAutoFollow:rb,pauseAutoFollow:rw,goalStatus:tY,sessionIdRef:tT,eventSourceRef:tb,messagesEndRef:t4,scrollContainerRef:t8,handleSend:n8,handleAbort:n5,handleFork:n6,handleNavigate:n3,handleModelChange:n9,handleRoleModelChange:rt,handleMainPresetChange:re,newSessionAccount:et,handleCompact:rn,handleSteer:ra,handleFollowUp:rl,handlePromptWithStreamingBehavior:ri,handleAbortCompaction:ro,handleRecallQueue:rc,handleRemoveQueuedMessage:rd,handleBuiltinSlashCommand:rs,handleToolPresetChange:rx,handleThinkingLevelChange:ru,fastMode:rf,fastModeBusy:eg,handleFastModeToggle:rg,loadTools:nC,loadSlashCommands:nI,ensureNewSession:nT,refreshLiveTranscript:nj,setActiveLeafId:S,setData:v,setMessages:N,dispatch:R,setAgentRunning:P,setForkingEntryId:eI,bashRunning:A,pendingBash:F,handleAgentEventRef:tU}}({session:e,newSessionCwd:t,initialData:l,transitioning:o,onAgentEnd:eE,onAttentionNeeded:d,onToolStart:eL,onSessionCreated:u,onSessionForked:h,newSessionAutoWorktree:i,modelsRefreshKey:p,chatInputRef:m,onBranchDataChange:f,onSystemPromptChange:g,onSessionStatsPanelOpen:y}),nl=(0,s.useMemo)(()=>(function(e){let t=null,n=new Map;for(let r=0;r<e.length;r++){let s=e[r],a=to(s);if(!a||"custom"!==s.role)continue;t??=[...e];let i=[];for(let t=0;t<r;t++){let r=e[t];if("assistant"!==r.role)continue;if(void 0===a.sourceHash){r.timestamp===a.sourceTimestamp&&i.push(t);continue}let s=n.get(t);void 0===s&&(s=function(e){let t=tl(e),n=5381;for(let e=0;e<t.length;e++)n=(n<<5)+n+t.charCodeAt(e)|0;return`${t.length}:${n}`}(r.content??[]),n.set(t,s)),s===a.sourceHash&&i.push(t)}i.length>1&&void 0!==a.sourceHash&&void 0!==a.sourceTimestamp&&(i=i.filter(t=>e[t].timestamp===a.sourceTimestamp));let l=1===i.length?t[i[0]]:null;if(l?.role!=="assistant"){t[r]={...s,details:void 0};continue}t[i[0]]={...l,replyTranslation:function(e,t){let n="string"==typeof e.content?e.content:e.content.map(e=>"text"===e.type?e.text:"").join("\n");return n.startsWith(ti)?{kind:"translated",text:n.slice(ti.length),original:t}:n.startsWith("[번역 생략]")?{kind:"skipped",text:n,original:t}:{kind:"failed",text:n,original:t}}(s,tl(l.content??[]))}}return t??e})(e_),[e_]),no=s_(e?.id,tv?.provider,void 0,tv?.modelId),nc=no?.alias;(0,s.useEffect)(()=>{nc&&ed.current?.(nc)},[nc]);let nd=(0,s.useMemo)(()=>{if(!tv)return null;let e=tz?t4:rW.find(e=>e.alias===no?.alias)?.oauthPosition;return rW.find(t=>t.provider===tv.provider&&(void 0===t.oauthPosition?null===no||no.seed===t.seed:t.oauthPosition===e))?.alias??null},[tv,tz,t4,no]),nu=ez||eD,nh=e?.id;ef.current=nl,eg.current=eF,ex.current=tq;let np=(0,s.useRef)(!0);np.current=!tD;let nm=(0,s.useRef)(!1);(0,s.useEffect)(()=>{ez&&!nm.current&&(ev.current+=1),nm.current=ez},[ez]),(0,s.useEffect)(()=>()=>{ev.current+=1},[]),(0,s.useEffect)(()=>{eh(e=>[...function(e){if(!e)return[];try{let t=JSON.parse(window.localStorage.getItem(pn(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[]}}(nh),...e.filter(e=>null===e.anchorEntryId&&e.sessionId===nh)])},[nh]),(0,s.useEffect)(()=>{let e=tq.current;e&&ep.current.some(t=>null===t.anchorEntryId&&t.sessionId===e)&&eh(t=>{let n=!1,r=[];for(let s of t){if(null!==s.anchorEntryId||!s.intent||s.sessionId!==e){r.push(s);continue}let a=function(e,t,n){let r=Math.min(t.length,n.length),s=0;if(null!==e.baseEntryId){let t=n.indexOf(e.baseEntryId);if(-1===t||t>=r)return{kind:"drop"};s=t+1}let a=0;for(let i=s;i<r;i++)if(rP(t[i])===e.identity&&(a+=1)===e.occurrence)return{kind:"entry",entryId:n[i]};return null}(s.intent,nl,eF);if(null===a){r.push(s);continue}n=!0,"drop"!==a.kind&&("working"===s.tag&&[...t,...r].some(e=>"working"===e.tag&&e.anchorEntryId===a.entryId)||r.push({id:s.id,anchorEntryId:a.entryId,sticker:s.sticker,text:s.text,tag:s.tag,sessionId:s.sessionId}))}return n?(pr(e,r),r):t})},[nl,eF,tq]);let nf=(0,s.useRef)(null);(0,s.useEffect)(()=>{let e=tq.current,t=nf.current;if(nf.current=e?{sessionId:e,entryIds:eF}: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=[],s=Math.min(n.length,t.length);for(let a=e.length;a<s;a++){let e=n[a];"assistant"===e.role&&"web6"===e.provider&&e.model===r_&&r.push(t[a])}return r}(t.entryIds,eF,nl),r=ew();if(0===n.length||!r)return;let s=sP(e,"web6",void 0)?.alias??null;for(let e of n)ep.current.some(t=>t.anchorEntryId===e)||eS(s,"done",r,{kind:"entry",entryId:e})},[eF,nl,tq,ew,eS]);let ng=ez&&tO?.kind==="running_tools"&&tO.tools.length>0&&tO.tools.every(e=>"wait"===e.name),nx=eP||o,{hideThinkingBlock:nv}=(Z=t??e?.cwd??null,X=rx(),(0,s.useEffect)(()=>{rg(Z).catch(()=>{})},[Z]),X),ny=(0,s.useMemo)(()=>({hideThinking:nv}),[nv]);(0,s.useEffect)(()=>{var e;if(!tE||ec.current===tE.id)return;ec.current=tE.id;let t=ew();if(!t)return;eb.current=t.turn;let n=eO.streamingMessage?.role==="assistant"?eO.streamingMessage:null,r=rA(ef.current,n,tv?.provider,tv?.modelId);eN("select"===(e=tE.method)||"ask"===e||"form"===e?"choice":"approval",t,r.provider,r.credentialId,r.model)},[tE,eO.streamingMessage,tv?.provider,tv?.modelId,ew,eN]),(0,s.useEffect)(()=>{if(Y)return x=nu?tZ:null,()=>void(x=null)},[Y,nu,tZ]),(0,s.useEffect)(()=>{A?.(nu)},[A,nu]),(0,s.useEffect)(()=>()=>A?.(!1),[A]),(0,s.useEffect)(()=>{_?.(ng)},[ng,_]),(0,s.useEffect)(()=>()=>_?.(!1),[_]),(0,s.useEffect)(()=>{O?.(null!==tE)},[O,tE]),(0,s.useEffect)(()=>()=>O?.(!1),[O]);let{main:nb,process:nw}=(0,s.useMemo)(()=>(function(e,t,n={}){let r=[],s=[],a=-1,i=null,l=(e,t,n)=>{if(0===t.length)return;let a=(i&&i.anchorIdx===e||(i={anchorIdx:e,entries:[],messageCount:0,toolCallCount:0},s.push(i)),i),l=r.length-1;for(let e of t)a.entries.push({...e,afterMainIndex:l});a.messageCount+=t.length,a.toolCallCount+=n},o=tr(e),c=new Map,d=(e,t)=>{let n=c.get(e)??0;c.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&&d(e.idx,e.blocks)};for(let s of t){if("answer"===s.kind){r.push(s);continue}if("process"===s.kind){l(s.anchorIdx,s.entries,s.toolCallCount);continue}let t=e[s.idx];if(!t)continue;if("user"===t.role){u(),a=s.idx,r.push(s);continue}if(tu(t)){r.push(void 0!==s.anchorIdx||a<0?s:{...s,anchorIdx:a});continue}if("assistant"!==t.role){"toolResult"!==t.role&&null===to(t)&&0>th(e,s.idx)&&l(a,[{idx:s.idx}],0);continue}let i=e5(t,n);if(e4(t,n)&&e8(e,s.idx)){let e=i.flatMap(e=>e.blocks);l(a,[{idx:s.idx}],e6(e)),o.collect(s.idx,e);continue}let c=!1;for(let e of i){if("answer"===e.kind){d(s.idx,e.blocks),c=!0;continue}l(a,[{idx:s.idx,blocks:e.blocks}],e6(e.blocks)),o.collect(s.idx,e.blocks)}!c&&e4(t,n)&&d(s.idx,[])}return u(),{main:r,process:s}})(nl,function(e,t={}){let n=-1;for(let t=e.length-1;t>=0;t--)if(tg(e[t])){n=t;break}let r=[];for(let s=0;s<e.length;){if(!tg(e[s])){r.push({kind:"message",idx:s}),s+=1;continue}let a=s,i=a+1;for(;i<e.length&&!tg(e[i]);)i+=1;if((t.sessionBusy||t.isStreaming)&&i===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,i)){for(let e=a;e<i;e++)r.push({kind:"message",idx:e});s=i;continue}for(let n of(r.push({kind:"message",idx:a}),function(e,t,n,r){let s=[],a=[],i=0,l=[],o=0,c=0,d=tr(e.slice(t+1,n)),u=()=>{0!==a.length&&(s.push({kind:"process",anchorIdx:t,idx:a[0].idx,groupIndex:c++,entries:a,messageCount:a.length,toolCallCount:i,turnHasAnswer:!1}),a=[],i=0)},h=(e,n)=>{u(),s.push({kind:"answer",anchorIdx:t,idx:e,runIndex:o++,blocks:d.attach(n),precedingBlocks:l}),l=[]};for(let o=t+1;o<n;o++){let n=e[o];if("assistant"!==n.role){if(null!==to(n)||th(e,o)>=0)continue;if(tu(n)){u(),s.push({kind:"message",idx:o,anchorIdx:t});continue}"toolResult"!==n.role&&a.push({idx:o});continue}let c=e5(n,r);if(e4(n,r)&&e8(e,o)){let e=c.flatMap(e=>e.blocks);for(let t of(a.push({idx:o}),i+=e6(e),d.collect(o,e),c))"process"===t.kind&&l.push(...t.blocks);continue}let p=c.reduce((e,t)=>"answer"===t.kind?e+1:e,0);for(let e of c){if("answer"===e.kind){h(o,e.blocks);continue}for(let t of(a.push(p>0?{idx:o,blocks:e.blocks}:{idx:o}),i+=e6(e.blocks),d.collect(o,e.blocks),e.blocks))l.push(t)}0===p&&e4(n,r)&&h(o,[])}u();let p=d.takeRemaining();p&&s.push({kind:"answer",anchorIdx:t,idx:p.idx,runIndex:o++,blocks:p.blocks,precedingBlocks:[]});let m=s.some(e=>"answer"===e.kind);for(let e of s)"process"===e.kind&&(e.turnHasAnswer=m);return s}(e,a,i,{hideThinking:t.hideThinking})))r.push(n);s=i}return r}(nl,{sessionBusy:nu,isStreaming:eO.isStreaming,hideThinking:ny.hideThinking}),ny),[nl,nu,eO.isStreaming,ny]),nk=(0,s.useMemo)(()=>(function(e,t,n=[]){let r,s,a,i,l,{atCompaction:o}=(r=-1,n.forEach((e,t)=>{"user"===e.role&&(r=t)}),s=n.slice(0,r+1).flatMap(iS),a=n.slice(r+1).flatMap(iS),i=t.findIndex(e=>"user"===e.role),-1===(l=0===a.length?-1:e.findIndex(e=>"answer"===e.kind&&(-1===i||e.idx<i)))?{continuing:null,atCompaction:[...s,...a]}:{continuing:{position:l,calls:a},atCompaction:s});if(0===o.length)return null;let c=-1;t.forEach((e,t)=>{"custom"===e.role&&"compaction"===e.customType&&(c=t)});let d=e.findIndex(e=>e.idx>c);return{position:-1===d?e.length:d,calls:o}})(nb,nl,tj?.messages),[nb,nl,tj]),[nj,nS]=(0,s.useState)(h3),{startIndex:nC,endIndex:nN,hasLater:nT}=h7(nb.length,nj),nI=null!==nj.end&&nT,nM=(0,s.useRef)(nb.length);nM.current=nb.length;let nE=(0,s.useRef)(null),n$=(0,s.useRef)(null),nR=(0,s.useRef)(null);(0,s.useEffect)(()=>{null!==nj.end&&nj.end>=nb.length&&nS(e=>({count:e.count,end:null}))},[nj.end,nb.length]),(0,s.useEffect)(()=>{let e=nE.current,t=tJ.current;if(!e||!t)return;let n=new IntersectionObserver(e=>{e[0]?.isIntersecting&&(nR.current=t.scrollHeight-t.scrollTop,nS(e=>(function(e,t=50){return{...e,count:e.count+t}})(e)))},{root:t,threshold:0});return n.observe(e),()=>n.disconnect()},[nj,nb.length,tJ]),(0,s.useEffect)(()=>{if(null==nR.current)return;let e=tJ.current;if(e){var t;t=e.scrollHeight,e.scrollTop=Math.max(0,t-nR.current),nR.current=null}},[nj.count,tJ]),(0,s.useEffect)(()=>{let e=n$.current,t=tJ.current;if(!e||!t)return;let n=new IntersectionObserver(e=>{e[0]?.isIntersecting&&nS(e=>(function(e,t,n=50){if(null===t.end)return t;let{startIndex:r,endIndex:s}=h7(e,t),a=s+n;return a>=e?{count:e-r,end:null}:{count:a-r,end:a}})(nM.current,e))},{root:t,threshold:0});return n.observe(e),()=>n.disconnect()},[nj,nb.length,tJ]);let[nL,nP]=(0,s.useState)(null),[nA,n_]=(0,s.useState)(0),nF=(0,s.useRef)(null),nz=(0,s.useCallback)(e=>{tU(),nF.current=e,nP(null),nS(t=>h9(nM.current,e,t)),n_(e=>e+1)},[tU]);(0,s.useLayoutEffect)(()=>{let e=nF.current,t=tJ.current;if(null===e||!t)return;let n=t.querySelector(`[data-chat-item="${e}"]`);if(!n)return;nF.current=null;let r=document.createRange();r.selectNodeContents(n),t.scrollTop+=r.getBoundingClientRect().top-t.getBoundingClientRect().top-24,nP(e)},[nA,nj,nb,tJ]),(0,s.useEffect)(()=>{if(null===nL)return;let e=setTimeout(()=>nP(null),1800);return()=>clearTimeout(e)},[nL]);let nD=(0,s.useCallback)(()=>{(0,a.flushSync)(()=>nS(h3));let e=tJ.current;e&&(e.scrollTop=e.scrollHeight)},[tJ]),nW=(0,s.useCallback)(()=>{nI&&nD(),tW()},[nI,nD,tW]),nH=(0,s.useRef)(null),[nU,nB]=(0,s.useState)(!1);(0,s.useEffect)(()=>{if(!q||nH.current===q.id||q.sessionId!==e?.id||eP||0===nl.length)return;nH.current=q.id,V?.(q.id);let t=eF.indexOf(q.entryId);if(t<0)return void nB(!0);let n=0;for(let e=0;e<nb.length;e++){let r=nb[e].idx;if(r>t||(n=e,r===t))break}nz(n)},[q,e?.id,eP,nl.length,eF,nb,nz,V]),(0,s.useEffect)(()=>{if(!nU)return;let e=setTimeout(()=>nB(!1),6e3);return()=>clearTimeout(e)},[nU]);let[nq,nV]=(0,s.useState)(!1),[nK,nJ]=(0,s.useState)(0),nG=(0,s.useMemo)(()=>nq?nb.map(e=>(function(e,t){if("answer"===e.kind)return ty(e.blocks);let n=t[e.idx];return n&&"content"in n?ty(n.content):""})(e,nl).toLowerCase()):ps,[nq,nb,nl]),nZ=(0,s.useCallback)(e=>{tU(),nS(t=>h9(nM.current,e,t))},[tU]),nX=(0,s.useCallback)(()=>nV(!1),[]);(0,s.useEffect)(()=>{if(!Y)return;let e=e=>{if(e.defaultPrevented||e.isComposing||e.altKey||e.shiftKey||!(e.ctrlKey||e.metaKey)||"f"!==e.key.toLowerCase())return;let t=tJ.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(),nV(!0),nJ(e=>e+1))};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[tJ,Y]);let n2=(0,s.useMemo)(()=>{let e=[];return nb.forEach((t,n)=>{if("message"!==t.kind)return;let r=pt(nl[t.idx]);null!==r&&e.push({item:n,text:r})}),e},[nb,nl]),n4=`${nC}:${nN}`,n8=eF.length>0?eF[eF.length-1]:null,[n5,n6]=(0,s.useState)(null),n3=(0,s.useRef)(!1);(0,s.useEffect)(()=>{n3.current||!tk||eP||!e?.id||(n3.current=!0,nu||!n8||!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}(nl)||function(e){try{return window.localStorage.getItem(pa(e))}catch{return null}}(e.id)!==n8&&n6(n8))},[tk,eP,e?.id,nu,n8,nl]);let n7=(0,s.useCallback)(()=>{e?.id&&n5&&function(e,t){try{window.localStorage.setItem(pa(e),t)}catch{}}(e.id,n5),n6(null)},[e?.id,n5]),n9=null!==n5&&n5===n8&&!nu&&!nI,re=tw?[tw.sessionId,tw.sessionFile??"",tw.sessionName??"",tw.userMessages,tw.assistantMessages,tw.toolCalls,tw.toolResults,tw.totalMessages,tw.tokens.input,tw.tokens.output,tw.tokens.cacheRead,tw.tokens.cacheWrite,tw.tokens.total,tw.cost??0,tw.totalActiveMs??0].join("|"):null,rt=(0,s.useRef)(tw);rt.current=tw,(0,s.useEffect)(()=>{v?.(rt.current)},[re,v]),(0,s.useEffect)(()=>()=>{v?.(null)},[v]);let rn=tt?`${tt.percent??"null"}|${tt.contextWindow}|${tt.tokens??"null"}`:null,rr=(0,s.useRef)(tt);rr.current=tt,(0,s.useEffect)(()=>{b?.(rr.current)},[rn,b]),(0,s.useEffect)(()=>()=>{b?.(null)},[b]),(0,s.useEffect)(()=>{w?.(tT)},[w,tT]),(0,s.useEffect)(()=>()=>{w?.([])},[w]);let{regular:rs,lab:ra}=(0,s.useMemo)(()=>(function(e){let t=[],n=[];for(let s of e){var r;((r=s.key).startsWith(dl)&&null!==dc(r)?n:t).push(s)}return{regular:t,lab:n}})(tP),[tP]),ri=e?.id??null;(0,s.useEffect)(()=>{k?.(ri,ra)},[k,ri,ra]),(0,s.useEffect)(()=>()=>{k?.(null,[])},[k]);let{isDragOver:rl,handleDragEnter:ro,handleDragOver:rc,handleDragLeave:rd,handleDrop:ru}=function(e){let[t,n]=(0,s.useState)(!1),r=(0,s.useRef)(0),a=(0,s.useCallback)(e=>{Array.from(e.dataTransfer.items).some(e=>"file"===e.kind)&&(e.preventDefault(),r.current+=1,n(!0))},[]),i=(0,s.useCallback)(e=>{Array.from(e.dataTransfer.items).some(e=>"file"===e.kind)&&e.preventDefault()},[]);return{isDragOver:t,handleDragEnter:a,handleDragOver:i,handleDragLeave:(0,s.useCallback)(()=>{r.current-=1,r.current<=0&&(r.current=0,n(!1))},[]),handleDrop:(0,s.useCallback)(t=>{t.preventDefault(),r.current=0,n(!1),e(Array.from(t.dataTransfer.files))},[e])}}((0,s.useCallback)(e=>{nu||m?.current?.addAttachments(e)},[nu,m])),rh=(0,s.useMemo)(()=>{var e;return e=tj?.messages,e&&e.length>0?[...e,...nl]:nl},[tj,nl]),rp=(0,s.useMemo)(()=>{let e=new Map;for(let t of rh)"toolResult"===t.role&&e.set(t.toolCallId,t);return e},[rh]),rm=(0,s.useMemo)(()=>{let e,t,n,r,s,a,i,l,o,c,d;return e=new Map,t=new Map,n=new Map,r=new Map,s=new Map,a=new Map,i=new Map,l=(e,r,s)=>{let a=n.get(e);a&&r&&t.set(a,{status:r,order:s})},o=new Set,c=(e,t)=>{let r=t?n.get(t):void 0,a=im(e.status);if(!r||o.has(r)||"completed"!==a&&"failed"!==a&&"aborted"!==a)return;o.add(r);let i=ip(e);null!==i&&s.set(r,i)},d=(e,t,r)=>{let s=t?n.get(t):void 0,a=ip(e);s&&"number"==typeof r&&null!==a&&"running"===im(e.status)&&i.set(s,Math.max(i.get(s)??-1/0,r-a))},rh.forEach((t,s)=>{if("assistant"===t.role){for(let e of t.content??[]){if("toolCall"!==e.type||"task"!==e.toolName)continue;let t=rp.get(e.toolCallId);if(t)for(let s of ix(e,t)??[])n.set(s.agentId,s.key),"number"==typeof t.timestamp&&r.set(s.key,t.timestamp)}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(ig(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=ih(t.assignmentId),s=r?.split("#")??[];if(s.length<3)return null;let a=s[s.length-1],i=s.slice(1,-1).join("#");return/^\d+$/.test(a)&&i?{key:`${i}#${a}`,record:{verdict:n,attempt:"number"==typeof t.attempt?t.attempt:null,reason:ih(t.reason)}}:null}(t);if(!n)return;let r=e.get(n.key)??[];r.push({...n.record,order:s,at:"number"==typeof t.timestamp?t.timestamp:null}),e.set(n.key,r);return}if("wait"===t.toolName){let e=new Set;for(let r of iu(t.details?.jobs)){if("task"!==r.type)continue;let a=ih(r.id);if(a&&l(a,im(r.status),s),c(r,a),d(r,a,t.timestamp),a&&"running"===im(r.status)){let t=n.get(a);t&&e.add(t)}}for(let t of e)for(let n of e){if(t===n)continue;let e=a.get(t);e||a.set(t,e=new Set),e.add(n)}}return}if("custom"===t.role&&"async-result"===t.customType){for(let e of ig(t.content).matchAll(iv)){let t=Object.fromEntries([...e[1].matchAll(iy)].map(e=>[e[1],e[2]]));t.id&&l(t.id,im(t.status),s)}for(let e of iu(t.details?.jobs))"task"===e.type&&c(e,ih(e.jobId))}}),{verdicts:e,runs:t,latestByAgent:n,spawnedAt:r,durations:s,parallelWith:a,runStartedAt:i}},[rh,rp]),rf=(0,s.useMemo)(()=>({ledger:rm,subagents:tT,toolResults:rp,onOpenPanel:j,sessionId:e?.id??null,cwd:e?.cwd??t??void 0,onOpenMaker:M,selectedMaker:E}),[rm,tT,rp,j,e?.id,e?.cwd,t,M,E]),rv=(0,s.useMemo)(()=>{let e=new Set,t=[];for(let n=nl.length-1;n>=0;n-=1){let r=pt(nl[n]);if(!(!r||e.has(r))&&(e.add(r),t.push(r),t.length>=50))break}return t.reverse()},[nl]),ry=(0,s.useMemo)(()=>tH(nl,rp,tI,tj?.todoPhases??null),[nl,rp,tI,tj]),rb=(0,s.useMemo)(()=>c3(eO.streamingMessage).join("|"),[eO.streamingMessage]),rw=(0,s.useMemo)(()=>JSON.stringify(c6(eO.streamingMessage)),[eO.streamingMessage]),rk=(0,s.useMemo)(()=>JSON.stringify(c9(eO.streamingMessage)),[eO.streamingMessage]),rj=(0,s.useMemo)(()=>(function(e,t,n=[],r=[],s=[]){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 s=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:s})}return t}(e),i=[],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 s=c3(r),c=c9(r,a);if(0===s.length&&0===c.length||o<0)continue;let d=c6(r),u=l.get(o);u||(u={index:o,entryId:t[o],taskToolCallIds:[],characterSummons:[],peerSends:[]},l.set(o,u),i.push(u)),u.taskToolCallIds=[...u.taskToolCallIds,...s],u.characterSummons=[...u.characterSummons,...d],u.peerSends=[...u.peerSends,...c]}if(n.length>0||s.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),i.push(e));let o=new Set(e.taskToolCallIds);e.taskToolCallIds=[...e.taskToolCallIds,...n.filter(e=>!o.has(e))];let c=new Set(e.characterSummons.map(e=>`${e.toolCallId} ${e.name??""}`));e.characterSummons=[...e.characterSummons,...r.filter(e=>!c.has(`${e.toolCallId} ${e.name??""}`))];let d=new Set(e.peerSends.map(e=>e.toolCallId));e.peerSends=[...e.peerSends,...s.filter(e=>!d.has(e.toolCallId))]}}return i.sort((e,t)=>e.index-t.index)})(nl,eF,rb.length>0?rb.split("|"):[],JSON.parse(rw),JSON.parse(rk)),[nl,eF,rb,rw,rk]),rS=e?.id??tq.current??void 0,rC=(et=dn(Q=(0,s.useMemo)(()=>({sessionId:rS,sessionProvider:tv?.provider,turns:rj,messages:nl,subagents:tT}),[rS,tv?.provider,rj,nl,tT])),en=di(Q),(0,s.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}([...et,...en])),[et,en])),rT=tz&&0===nl.length&&!eO.isStreaming&&!nu,rI=(0,s.useMemo)(()=>nl.filter(e=>"assistant"===e.role).length,[nl]),rM=function(e,t){let n=(0,s.useRef)(new Map),r=(0,s.useMemo)(()=>{if(!e)return n.current=new Map,0;let t=new Map,r=0;return(e.content??[]).forEach((e,s)=>{let a=e9(e);if(null===a)return;let i=te(n.current.get(s),a);t.set(s,{text:a,tokens:i}),r+=i}),n.current=t,r},[e]),a=(0,s.useRef)(r);a.current=r;let i=null!==e,l=e?.timestamp,[o,c]=(0,s.useState)(null);return(0,s.useEffect)(()=>{if(!i)return void c(null);let e=l??Date.now(),t=()=>{let t=(Date.now()-e)/1e3;c(t>=.5?a.current/t:0)};t();let n=setInterval(t,1e3);return()=>clearInterval(n)},[i,l,t]),i?o??0:null}(eO.streamingMessage?.role==="assistant"?eO.streamingMessage:null,rI),rE=(0,s.useMemo)(()=>(function(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if("assistant"!==n.role)continue;let{usage:r,timestamp:s,completedAt:a}=n,i=r?.output??0;if(!(i<=0)&&s&&a&&!(a<=s))return i/((a-s)/1e3)}return null})(nl),[nl]),r$=e?.cwd??t??void 0,rR=tv?eK[`${tv.provider}:${tv.modelId}`]??null:null,rL=tv?eJ[`${tv.provider}:${tv.modelId}`]??null:null,rF=(0,s.useRef)(null),rO=(0,s.useRef)(null),rz=(0,s.useCallback)(()=>{let e=rF.current?.querySelector("textarea");e&&(e.focus({preventScroll:!0}),e.setSelectionRange(e.value.length,e.value.length))},[]);(0,s.useEffect)(()=>(P?.(rz),()=>P?.(null)),[rz,P]),(0,s.useLayoutEffect)(()=>{let e=rO.current,t=e?.closest(".workspace-shell");if(!e||!t)return;let n=e.closest(".chat-pane"),r=tJ.current?.clientHeight??0,s=()=>{let s=Math.ceil(e.getBoundingClientRect().height);s>0&&(n?.style.setProperty("--omp-dock-h",`${s}px`),Y&&t.style.setProperty("--omp-dock-h",`${s}px`));let a=tJ.current;if(!a)return;let i=r-a.clientHeight;r=a.clientHeight,i<=0||a.scrollHeight-a.scrollTop-a.clientHeight-i<=1&&(a.scrollTop+=i)};s();let a=new ResizeObserver(s);return a.observe(e),()=>a.disconnect()},[eP,tJ,Y]);let rD=(0,s.useCallback)((...e)=>(null!==nj.end&&nD(),tY(...e)),[tY,nj.end,nD]),rH=(0,s.useCallback)(async e=>ez?await t6(e)==="accepted"?"followUp":"failed":await rD(e)==="accepted"?"prompt":"failed",[ez,t6,rD]),rU=(0,r.jsx)("div",{ref:rF,"data-chat-composer":"",style:{display:"contents"},children:(0,r.jsx)(hc,{ref:m,sessionId:e?.id??tq.current??void 0,onEnsureSession:tz&&t?na:void 0,onLiveTranscriptPersisted:ni,onSend:rD,onAbort:tZ,onSteer:ez?t5:void 0,onFollowUp:ez?t6:void 0,onPromptWithStreamingBehavior:ez?t3:void 0,isStreaming:nu,model:tv,isAutoModelSelection:tF,modelNames:eU,modelList:eB,modelError:eq,modelScopeWarnings:eV,onModelChange:t0,onMainPresetChange:e||tz?t2:void 0,mainPresetActiveAlias:nd,modelRoles:eG,onRoleModelChange:t1,modelSwitching:tb,onCompact:e||tz?t8:void 0,onAbortCompaction:t7,isCompacting:ts,compactError:td,compactResult:tx,toolPreset:eY,onToolPresetChange:e||tz?nn:void 0,thinkingLevel:eZ,effectiveThinkingLevel:eQ,outputTokensPerSecond:rM??rE,outputSpeedLive:null!==rM,thinkingCeiling:eX,onThinkingLevelChange:e||tz?nr:void 0,fastMode:e0,fastModeBusy:e2,onFastModeToggle:e||tz?e3:void 0,availableThinkingLevels:rR,thinkingLevelMap:rL,retryInfo:e7,deliveryRows:tN,inputHistory:rv,onRecallQueue:t9,onRemoveQueuedMessage:ne,slashCommands:tS,slashCommandsLoading:tC,onLoadSlashCommands:ns,onBuiltinCommand:nt,soundEnabled:z,onSoundToggle:D,onAudioUnlock:B,draftKey:e?.id??(t?`new:${t}`:void 0),cwd:e?.cwd??t,sessionTitle:e?.name,startPlace:rT&&!L?N:void 0,notice:T})}),rB=eO.streamingMessage,rq=(0,s.useMemo)(()=>rB?e5(rB,{isStreaming:!0}):[],[rB]),rV=(0,s.useMemo)(()=>rq.filter(e=>"answer"===e.kind).flatMap(e=>e.blocks),[rq]),rK=(0,s.useMemo)(()=>rq.filter(e=>"answer"!==e.kind).map(e=>e.blocks),[rq]),rJ=rB?.role==="assistant"?rB:null,rG=(0,s.useMemo)(()=>{let e=-1;for(let t=nl.length-1;t>=0;t-=1)if("user"===nl[t].role){e=t;break}let t=e<0?-1:oc(nl,e);return{start:t,blocks:ol(nl,t+1,nl.length),priorCiHeads:ou(nl,rp,t+1),jobNotices:oo(nl,t+1,nl.length)}},[nl,rp]);(0,s.useEffect)(()=>{eR.current=rG.start},[rG.start]);let rY=e?.id;(0,s.useEffect)(()=>{I&&rY&&tk&&!nu&&I(rY,null)},[rY,I,tk,nu]);let rZ=(0,s.useMemo)(()=>l1(rJ?[...rG.blocks,...rJ.content??[]]:rG.blocks,rp,nu,rG.priorCiHeads,r$,rG.jobNotices),[rG,rJ,rp,nu,r$]),rQ=(0,s.useMemo)(()=>nu?{...oi(rG.blocks,rp,r$),span:oh(nl,rG.start+1,nl.length)}:null,[nu,rG,rp,r$,nl]),rX=(0,s.useMemo)(()=>rQ?{...rQ,flow:rZ,latest:!0}:null,[rQ,rZ]),r0=(0,s.useMemo)(()=>{let e=null;if(nu)for(let t of nb)"message"===t.kind&&nl[t.idx]?.role==="user"&&(e=t.idx);return function(e,t,n,r,s,a,i=[]){let l=function(e,t,n){let r=new Map,s=e.filter(e=>"message"===e.kind&&t[e.idx]?.role==="user"&&oc(t,e.idx)===e.idx).map(e=>e.idx),a=null===n?null:oc(t,n),i=new Map;for(let[n,l]of(e.forEach((e,n)=>{"answer"===e.kind&&i.set(oc(t,e.anchorIdx),n)}),i)){if(n===a)continue;let e=s.find(e=>e>n);r.set(l,{from:n+1,to:e??t.length})}return r}(e,t,n),o=-1;for(let e of l.keys())e>o&&(o=e);let c=new Map,d=[],u=0;for(let[e,n]of[...l].sort((e,t)=>e[1].from-t[1].from)){if(ou(t,r,n.from,u,d),u=Math.max(u,n.from),0===n.from&&a){let s=n.to-1;for(;s>=n.from&&tm(i[s]);)s-=1;if(i[s]!==a.throughEntryId)continue;let l=ol(t,n.from,n.to).filter(e=>"toolCall"===e.type&&"task"===e.toolName),h=od(t,r,n.from,n.to);c.set(e,{...a.summary,...h?{remaining:oa(h)}:{},dispatchCalls:l,latest:e===o}),d.push(...a.ciHeads),u=n.to;continue}c.set(e,{...function(e,t,n,r,s,a=[]){let i=ol(e,n,r),l=od(e,t,n,r);return{...oi(i,t,s),remaining:l?oa(l):null,span:oh(e,n,r),flow:l1(i,t,!1,a,s,oo(e,n,r))}}(t,r,n.from,n.to,s,d),latest:e===o})}return c}(nb,nl,e,rp,r$,tj?.openRequest??null,eF)},[nb,nl,rp,r$,nu,tj,eF]),[r1,r2]=(0,s.useState)(null),r4=e?.id??null;(0,s.useEffect)(()=>{r2(null)},[r4]);let r8=null;for(let e of r0.keys())(null===r8||e>r8)&&(r8=e);let r5=("live"===r1?null!==rX:null!==r1&&r0.has(r1))?r1:rX?"live":r8,r6="live"===r5?rX:null===r5?null:r0.get(r5)??null,r3=null!==rX,r7=(0,s.useMemo)(()=>({selected:r5,shown:null!==K,select:e=>{r2(e),J?.()},latestTurn:r3?null:r8,compactedCalls:nk?.calls,onOpenFile:R}),[J,r5,K,r3,r8,nk,R]),r9=null===r5||"live"===r5||r5===r8,se=K&&(0,a.createPortal)((0,r.jsx)(tG.Provider,{value:C??null,children:(0,r.jsx)(iC.Provider,{value:rf,children:(0,r.jsx)(c_,{summary:r6,live:"live"===r5,folded:G,compactedCalls:r9?nk?.calls:void 0,onOpenFile:R})})}),K),st=ez&&(tO?.kind==="running_tools"||(rJ?.content??[]).some(e=>"text"===e.type&&/\S/.test(e.text)||"toolCall"===e.type)),sn=rA(nl,rJ,tv?.provider,tv?.modelId),sr=sn.provider,ss=sn.model,sa=sn.credentialId;(0,s.useEffect)(()=>{if(!st)return;let e=ew();e&&ey.current!==e.turn&&eb.current!==e.turn&&(ey.current=e.turn,eN("working",e,sr,sa,ss))},[st,sr,ss,sa,ew,eN]);let[si,sl]=(0,s.useState)(null),so=(0,s.useCallback)(e=>{sl(e)},[]),sc=(0,s.useMemo)(()=>eW?{role:"bashExecution",command:eW.command,output:"",excludeFromContext:eW.excludeFromContext}:null,[eW]),sd=(0,s.useMemo)(()=>{let e=[ez&&!rB&&tO?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}(tO,er):null,eD&&!eW?er("chat.runningCommand"):null].filter(e=>!!e);return e.length>0?e.join(" \xb7 "):null},[ez,rB,tO,eD,eW,er]);(0,s.useEffect)(()=>{if(!si)return void $?.(null);let e=[],t=[],n=0;if(rB&&rK.length>0){let r=si.messages.length+e.length;for(let s of(e.push(rB),rK))t.push({idx:r,blocks:s}),n+=e6(s)}if(sc&&(t.push({idx:si.messages.length+e.length}),e.push(sc)),0===t.length)return void $?.(sd?{...si,status:sd}:si);let r=-1;for(let e=si.messages.length-1;e>=0;e--)if(tg(si.messages[e])){r=e;break}let s=si.groups.slice(),a=s.length>0?s[s.length-1]:void 0;a&&a.anchorIdx===r?s[s.length-1]={...a,entries:[...a.entries,...t],messageCount:a.messageCount+t.length,toolCallCount:a.toolCallCount+n}:s.push({anchorIdx:r,entries:t,messageCount:t.length,toolCallCount:n}),$?.({...si,groups:s,messages:[...si.messages,...e],status:sd})},[si,rK,rB,sc,sd,$]),(0,s.useEffect)(()=>()=>$?.(null),[$]);let su=rs.filter(e=>"belowEditor"!==e.placement),sh=rs.filter(e=>"belowEditor"===e.placement);return eA?(0,r.jsx)("div",{className:"flex h-full items-center justify-center text-red-400",children:eA}):(0,r.jsxs)("div",{className:"chat-window relative flex h-full min-w-0 flex-col overflow-hidden","aria-busy":nx,"data-empty-start":rT&&!L?"true":void 0,style:{paddingBottom:"env(safe-area-inset-bottom)"},onDragEnter:ro,onDragOver:rc,onDragLeave:rd,onDrop:ru,children:[nx?(0,r.jsx)("div",{className:"absolute inset-0 z-40 cursor-wait",children:(0,r.jsx)("div",{className:"absolute right-3 top-3 bg-bg-raised px-3 py-2 text-sm text-text-muted shadow-sm",role:"status",children:er("chat.loadingSession")})}):null,rl&&!nu&&(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)"},children:(0,r.jsx)("span",{className:"px-3 py-1 text-sm font-medium",style:{background:"var(--bg-raised)",boxShadow:"var(--shadow-float)",borderRadius:"var(--radius-surface)",color:"var(--text)"},children:er("chat.attachFile")})}),tR&&(0,r.jsx)(pp,{request:tR,onInput:t_}),rT&&!L?(0,r.jsx)("div",{className:"flex flex-1 flex-col items-center overflow-y-auto px-4",children:(0,r.jsxs)("div",{className:"chat-empty-start my-auto w-full max-w-[var(--reading-measure)] 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)(ee,{})}),(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.355"]})]}),(0,r.jsxs)("span",{style:{fontSize:11,color:"var(--text-muted)"},children:["omp ",(0,r.jsxs)("span",{style:{color:"var(--text)"},children:["v","19.1.1"]})]})]})]}),r$&&!N&&(0,r.jsxs)("section",{className:"empty-workspace-context","aria-label":er("chat.emptyProjectLabel"),children:[(0,r.jsxs)("div",{className:"empty-workspace-context-text",children:[(0,r.jsx)("span",{className:"empty-workspace-context-kicker",children:er("chat.emptyProjectLabel")}),(0,r.jsx)("strong",{children:tK(r$)||r$}),(0,r.jsx)("code",{title:r$,children:r$}),(0,r.jsx)("p",{children:er("chat.emptyProjectHint")})]}),S&&(0,r.jsx)("button",{type:"button",className:"empty-workspace-context-action",onClick:S,children:er("chat.openSessionList")})]}),(0,r.jsx)(pd,{notices:tM,align:"right"})]})}):(0,r.jsxs)(r.Fragment,{children:[L&&(0,r.jsx)("div",{className:"min-h-0 min-w-0 flex-1 overflow-hidden",children:L}),(0,r.jsxs)("div",{className:"relative min-w-0 flex-1 overflow-hidden","aria-hidden":!!L,style:{display:L?"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:"var(--reading-measure)",margin:"0 auto",display:"flex",flexDirection:"column",alignItems:"flex-end",gap:8},children:[(0,r.jsx)(cW,{open:nq,onClose:nX,containerRef:tJ,index:nG,renderedStart:nC,renderedEnd:nN,contentKey:nl,onReveal:nZ,onProgrammaticScroll:tU,focusRequest:nK,t:er}),nU&&(0,r.jsx)("div",{className:"chat-jump-missing",role:"status",children:er("chat.jumpMissing")}),(0,r.jsx)(pd,{notices:tM,floating:!0,align:"right"})]})}),(0,r.jsx)("div",{ref:tJ,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:"var(--reading-measure)",margin:"0 auto"},children:[(0,r.jsx)(pc,{widgets:su}),(0,r.jsx)(nO,{sessionKey:e?.id??"new",messages:nl,onSend:rH,children:(0,r.jsx)(tG.Provider,{value:C??null,children:(0,r.jsx)(iC.Provider,{value:rf,children:(0,r.jsxs)(cN.Provider,{value:r7,children:[(0,r.jsx)(c1,{utterances:rC,children:(0,r.jsx)(pi,{messages:nl,entryIds:eF,toolResultsMap:rp,modelNames:eU,messageCwd:r$,onOpenFile:R,sessionBusy:nu,isNew:tz,isStreaming:eO.isStreaming,handleFork:tQ,forkingEntryId:tn,handleNavigate:tX,handleEditContent:e$,sessionId:e?.id??tq.current??void 0,main:nb,turnSummaries:r0,process:nw,startIndex:nC,endIndex:nN,sentinelRef:nE,laterSentinelRef:n$,flashItem:nL,t:er,cues:eu,cueFollowRef:np,onProcessLogChange:so})}),!nI&&eO.isStreaming&&eO.streamingMessage&&rV.length>0&&(0,r.jsx)(aC,{message:e1(eO.streamingMessage,rV),sessionId:e?.id??tq.current??void 0,isStreaming:!0,modelNames:eU,cwd:r$,onOpenFile:R}),!nI&&rX&&(0,r.jsx)(cE,{summary:rX,turnKey:"live",live:!0})]})})})}),n9&&(0,r.jsx)(cK,{onDismiss:n7,t:er}),(0,r.jsx)("div",{ref:tV})]})})}),(0,r.jsx)(cH,{questions:n2,containerRef:tJ,layoutKey:n4,onJump:nz,label:er("chat.questionRail")}),(nu&&tD||nI)&&(0,r.jsxs)("button",{type:"button",onClick:nW,"aria-label":er("chat.jumpToBottom"),title:er("chat.jumpToBottom"),style:{position:"absolute",bottom:16,left:"50%",transform:"translateX(-50%)",zIndex:40,display:"flex",alignItems:"center",gap:6,padding:"6px 12px",minHeight:ea?44:void 0,borderRadius:"var(--radius-control)",border:0,background:"var(--bg-raised)",boxShadow:"var(--shadow-float)",color:"var(--text-muted)",fontSize:12,cursor:"pointer"},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"})]}),er("chat.jumpToBottom")]})]})]}),(0,r.jsxs)("div",{ref:rO,className:"relative chat-composer-dock flex min-h-0 flex-col",children:[tE&&(0,r.jsx)("div",{style:{padding:"0 16px"},children:(0,r.jsx)("div",{className:"chat-column-cap",style:{maxWidth:"var(--reading-measure)",margin:"0 auto"},children:(0,r.jsx)(ph,{request:tE,onRespond:tA,onActivity:(e,t)=>void t_(e,t??"activity"),delivery:t$})})}),(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:"var(--reading-measure)",margin:"0 auto"},children:[(0,r.jsx)(cV,{compaction:ta,t:er}),(0,r.jsx)(po,{goal:tB,t:er}),(0,r.jsx)(pc,{widgets:sh}),(ry||rZ.steps.length>0)&&!el&&(0,r.jsx)(hh,{phases:ry,flow:rZ,busy:nu})]})}),G&&!K&&r6&&null!==r5&&!el&&(0,r.jsx)("div",{className:"turn-peek-dock",style:{padding:"0 16px"},children:(0,r.jsx)("div",{className:"chat-column-cap",children:(0,r.jsx)(iC.Provider,{value:rf,children:(0,r.jsx)(cR,{summary:r6,live:"live"===r5,onOpen:()=>r7.select(r5)})})})}),rU,(0,r.jsx)(hu,{statuses:tL})]}),se]})}function po({goal:e,t}){if(!e)return null;let n=!e.enabled,s=void 0!==e.tokenBudget?t("chat.goalBudgetLeft",{left:ro(Math.max(0,e.tokenBudget-e.tokensUsed))}):t("chat.goalTokensUsed",{used:ro(e.tokensUsed)});return(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:8,padding:"5px 10px",border:0,borderRadius:"var(--radius-control)",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:s})]})}function pc({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:0,borderRadius:"var(--radius-surface)",background:"var(--bg-panel)",overflow:"hidden"},children:[(0,r.jsx)("div",{style:{padding:"5px 9px",background:"var(--bg-hover)",color:"var(--text-muted)",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 pd({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,s)=>{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*(s!==e.length-1),overflow:"hidden",borderRadius:"var(--seed-radius-r3)",border:0,background:"var(--bg-subtle)",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 pu({focusKey:e,label:t,labelledBy:n,maxBlockSize:a="min(56dvh, 620px)",onCancel:i,delivery:l,children:o}){let{t:c}=(0,F.s)(),d=(0,s.useRef)(null),u=(0,s.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&&!d.current?.contains(t)?t:null}}return(0,s.useEffect)(()=>{let e=d.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:d,role:"dialog","aria-modal":"false","aria-label":t,"aria-labelledby":n,className:"chat-response-surface",tabIndex:-1,onKeyDown:i?e=>{"Escape"===e.key&&(e.stopPropagation(),i())}: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?c("chat.responseSending"):`${c("chat.responseFailed")}${l.error?` (${l.error})`:""}`}):null,o]})}function ph({request:e,onRespond:t,onActivity:n,delivery:a}){let{t:i}=(0,F.s)(),[l,o]=(0,s.useState)("editor"===e.method?e.prefill??"":""),[c,d]=(0,s.useState)({selected:{},custom:{}}),[u,h]=(0,s.useState)(""),p=(0,s.useRef)(0),m=(0,s.useCallback)(()=>{if("ask"!==e.method||!e.timeout||!n)return;let t=Date.now();t-p.current<1e3||(p.current=t,n(e))},[e,n]);(0,s.useEffect)(()=>{o("editor"===e.method?e.prefill??"":""),h(""),d("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("form"===e.method)return(0,r.jsx)(pu,{focusKey:e.id,label:i("chat.agentQuestion"),delivery:a,children:(0,r.jsx)(dI,{request:e,onRespond:t,onActivity:n,delivery:a},e.id)});if("ask"===e.method){var g;let n=(g=e.questions,g.every(e=>(c.selected[e.id]?.length??0)>0||(c.custom[e.id]?.trim().length??0)>0)),s=()=>{if(n){var r;t(e,{value:(r=e.questions,JSON.stringify({kind:"submit",results:r.map(e=>{let t=c.custom[e.id]?.trim();return{id:e.id,question:e.question,options:e.options.map(e=>e.label),multi:e.multi??!1,selectedOptions:(c.selected[e.id]??[]).map(t=>e.options[t]?.label).filter(e=>void 0!==e),...t?{customInput:t}:{}}})}))})}};return(0,r.jsx)(pu,{focusKey:e.id,label:i("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"},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:i("chat.agentQuestion")}),(0,r.jsx)("div",{style:{marginTop:2,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)"},children:i("chat.agentQuestionHint")}),e.timeout?(0,r.jsx)("div",{style:{marginTop:2,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)"},children:i("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=c.selected[t.id]??[];return(0,r.jsxs)("section",{style:{paddingTop:20*(0!==n)},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 s=a.includes(n),l=t.recommended===n;return(0,r.jsxs)("button",{type:"button",role:t.multi?"checkbox":"radio","aria-checked":s,onClick:()=>{m(),d(e=>(function(e,t,n){let r=e.selected[t.id]??[];if(t.multi){let s=r.includes(n)?r.filter(e=>e!==n):[...r,n];return{...e,selected:{...e.selected,[t.id]:s}}}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:0,borderRadius:"var(--radius-control)",background:s?"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:0,borderRadius:t.multi?"var(--radius-control)":"50%",background:s?"var(--seed-color-fg-neutral)":"var(--bg-selected)",color:"var(--seed-color-fg-neutral-inverted)",fontSize:"var(--seed-font-size-t2-static)",lineHeight:1},children:s&&(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:s?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}),s&&e.preview&&(0,r.jsx)("span",{style:{display:"block",marginTop:8,padding:"7px 8px",borderRadius:"var(--radius-control)",background:"var(--bg-hover)",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:i("chat.recommended")})]},`${t.id}:${n}`)})}),(0,r.jsx)("input",{value:c.custom[t.id]??"",onChange:e=>{m();let n=e.target.value;d(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&&s()},placeholder:i("chat.customAnswer"),"aria-label":i("chat.customAnswer"),style:{width:"100%",height:36,marginTop:9,padding:"0 10px",border:0,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"},children:[(0,r.jsx)("button",{type:"button",onClick:()=>t(e,{cancelled:!0}),style:{minHeight:36,padding:"0 12px",border:0,borderRadius:"var(--radius-control)",background:"var(--bg-hover)",color:"var(--text-muted)",cursor:"pointer"},children:i("chat.cancel")}),(0,r.jsx)("button",{type:"button",onClick:()=>t(e,{value:JSON.stringify({kind:"chat"})}),style:{minHeight:36,padding:"0 12px",border:0,borderRadius:"var(--radius-control)",background:"var(--bg-hover)",color:"var(--text)",cursor:"pointer"},children:i("chat.chatAboutThis")}),(0,r.jsx)("button",{type:"button",disabled:!n||a?.status==="sending",onClick:s,style:{minHeight:36,padding:"0 14px",border:0,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"?i("chat.responseSending"):i("chat.submitAnswer")})]})]})})}return"plan_review"===e.method?(0,r.jsx)(pu,{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"},children:[(0,r.jsx)("div",{style:{color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontWeight:600},children:i("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)(nJ,{children:e.planContent})}),(0,r.jsxs)("div",{style:{padding:"12px 16px"},children:[(0,r.jsx)("textarea",{value:u,onChange:e=>h(e.target.value),placeholder:i("chat.planFeedback"),"aria-label":i("chat.planFeedback"),style:{width:"100%",minHeight:64,maxHeight:150,padding:"9px 10px",border:0,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:0,borderRadius:"var(--radius-control)",background:"var(--bg-hover)",color:"var(--text)",cursor:"pointer"},children:i("chat.refinePlan")}),(0,r.jsx)("button",{type:"button",onClick:()=>t(e,{value:JSON.stringify({action:"approve"})}),style:{minHeight:36,padding:"0 14px",border:0,borderRadius:"var(--radius-control)",background:"var(--seed-color-bg-neutral-inverted)",color:"var(--seed-color-fg-neutral-inverted)",cursor:"pointer",fontWeight:600},children:i("chat.approvePlan")})]})]})]})}):(0,r.jsx)(pu,{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"},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:i("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:0,background:"var(--bg-hover)",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:0,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:0,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"},children:[(0,r.jsx)("button",{onClick:()=>t(e,{cancelled:!0}),style:{minHeight:36,padding:"0 12px",borderRadius:"var(--radius-control)",border:0,background:"var(--bg-hover)",color:"var(--text-muted)",cursor:"pointer"},children:i("chat.cancel")}),"confirm"===e.method?(0,r.jsx)("button",{onClick:f,style:{minHeight:36,padding:"0 14px",borderRadius:"var(--radius-control)",border:0,background:"var(--seed-color-bg-neutral-inverted)",color:"var(--seed-color-fg-neutral-inverted)",cursor:"pointer",fontWeight:600},children:i("chat.confirm")}):"select"!==e.method?(0,r.jsx)("button",{onClick:f,style:{minHeight:36,padding:"0 14px",borderRadius:"var(--radius-control)",border:0,background:"var(--seed-color-bg-neutral-inverted)",color:"var(--seed-color-fg-neutral-inverted)",cursor:"pointer",fontWeight:600},children:i("chat.submit")}):null]})]})})}function pp({request:e,onInput:t}){let{t:n}=(0,F.s)(),a=(0,s.useRef)(null),i=(0,s.useRef)(!1),l=eV(e.lines);return(0,s.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:0,borderRadius:"var(--radius-surface)",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(i.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=eG[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":" ":eJ[e.key]??null}(n);r&&(n.preventDefault(),n.stopPropagation(),t(e,r))},onInput:n=>{if(i.current||n.nativeEvent.isComposing)return;let r=n.currentTarget.value;n.currentTarget.value="",r&&t(e,r)},onCompositionStart:()=>{i.current=!0},onCompositionEnd:n=>{i.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",background:"var(--bg-panel)"},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:"var(--radius-control)",border:0,background:"var(--bg-hover)",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)(s.Fragment,{children:[(a=`line-${t}`,eK(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)})})]})})}var pm=n(40960),pf=n.n(pm);function pg({sessionId:e,refreshKey:t,compact:n}){let{t:a}=(0,F.s)(),[i,o]=(0,s.useState)(null),[c,d]=(0,s.useState)(!1),[u,h]=(0,s.useState)(null),p=(0,s.useRef)(e);p.current=e;let m=(0,s.useRef)(0);(0,s.useEffect)(()=>{if(!e)return;let t=!1,n=++m.current;return fetch(`/api/agent/${encodeURIComponent(e)}`).then(e=>e.json()).then(r=>{if(t||n!==m.current)return;let s=r.running?r.state?.computerTakeover:null;o(s?{sessionId:e,state:{enabled:!0===s.enabled,available:!0===s.available}}:null),h(null)}).catch(()=>{}),()=>{t=!0}},[e,t]);let f=(0,s.useCallback)(async e=>{let t=p.current;if(t){d(!0),h(null);try{let n=await fetch(`/api/agent/${encodeURIComponent(t)}/computer-takeover`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({enabled:e})}),r=await n.json();if(!n.ok)throw Error("shared_settings"===r.code?a("computerTakeover.shared"):r.error??n.statusText);p.current===t&&(m.current+=1,o({sessionId:t,state:{enabled:!0===r.enabled,available:!0!==r.enabled}}))}catch(e){p.current===t&&h(a("computerTakeover.failed",{error:e instanceof Error?e.message:String(e)}))}finally{d(!1)}}},[a]),g=i&&i.sessionId===e?i.state:null;if(!g||!g.enabled&&!g.available)return null;let x=g.enabled,v=x?a("computerTakeover.active"):a("computerTakeover.allow"),y=u??(x?a("computerTakeover.activeHint"):a("computerTakeover.allowHint"));return(0,r.jsxs)(l.r,{className:`workspace-header-action workspace-takeover${x?` ${pf().active}`:""}`,variant:x?"neutralWeak":"ghost",size:"small",type:"button",disabled:c,"aria-pressed":x,"aria-label":v,title:y,onClick:()=>void f(!x),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:"M5 3l14 7-6 2-2 6-6-15Z"})}),(x||!n)&&(0,r.jsx)("span",{children:v})]})}function px({onPick:e,t}){let[n,a]=(0,s.useState)(""),[i,l]=(0,s.useState)({kind:"idle"}),o=(0,s.useRef)(null),c=n.trim();(0,s.useEffect)(()=>{if(c.length<2)return void l({kind:"idle"});let e=new AbortController;l({kind:"loading"});let t=setTimeout(()=>{fetch(`/api/sessions/search?q=${encodeURIComponent(c)}`,{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()}},[c]);let d=e=>{let t=o.current?.querySelectorAll("button");t&&0!==t.length&&t[Math.max(0,Math.min(t.length-1,e))]?.focus()},u="done"===i.kind?i.data:null,h=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.jsxs)("div",{className:"palette-search-field",children:[(0,r.jsx)(ep,{name:"search"}),(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(),d(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}),(0,r.jsx)("kbd",{"aria-hidden":"true",children:"Ctrl K"})]}),c.length>=2&&(0,r.jsxs)("div",{className:"palette-search-results",role:"region","aria-label":t("palette.searchResults"),"aria-busy":"loading"===i.kind,children:[(0,r.jsxs)("p",{className:"palette-search-status","aria-live":"polite",children:["loading"===i.kind&&t("palette.searching"),"error"===i.kind&&t("palette.searchFailed"),u&&(0===u.hits.length?t("palette.searchEmpty"):t("palette.searchHits",{count:u.hits.length})),h?` \xb7 ${h}`:"",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,s)=>{let a=u.sessions[n.sessionId],i=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(),d(s+("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,i)}),n.snippet.slice(i)]})]},`${n.sessionId}:${n.entryId}`)})})]})]})}var pv=n(50640),py=n(73620);let pb=/^(?:\uFEFF)?---[ \t]*(?:\r\n|\n|\r)/;function pw(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 pk=["tags","categories","keywords","tag","category"];function pj({data:e}){var t;if(!e)return null;let n=Object.entries(e);if(0===n.length)return null;let s="string"==typeof(t=e.title)?t.trim()||null:"number"==typeof t||"boolean"==typeof t?String(t):null,a=pk.find(t=>Array.isArray(e[t])),i=a?e[a].map(pw).filter(Boolean):[],l=n.filter(([e])=>e!==a&&("title"!==e||!s));return(0,r.jsxs)("div",{className:"markdown-frontmatter",children:[s&&(0,r.jsx)("div",{className:"markdown-frontmatter-title",children:s}),i.length>0&&(0,r.jsx)("div",{className:"markdown-frontmatter-tags",children:i.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=pw(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 pS=n(8745);let pC=(0,s.createContext)(null),pN=(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"})}),pT=(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"})}),pI=(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"})}),pM=(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"})}),pE=(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 p$({back:e,title:t,titleTooltip:n,titleRef:s,titleAdornment:a,subtitle:i,subtitleKind:d="text",state:u,viewSwitch:h,actions:p=[],close:m}){let{t:f}=(0,F.s)();return(0,r.jsxs)("header",{className:"panel-header",children:[e&&(0,r.jsx)(l.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)(c.In,{size:"16px",svg:pI})}),(0,r.jsxs)("div",{className:"panel-header-heading",children:[(0,r.jsx)("h2",{className:"panel-header-title",title:n,ref:s,tabIndex:s?-1:void 0,children:t}),a,i&&("path"===d?(0,r.jsx)("span",{className:"panel-header-subtitle is-path",title:i,dir:"rtl",children:(0,r.jsx)("bdi",{dir:"ltr",children:i})}):(0,r.jsx)("span",{className:"panel-header-subtitle",title:i,children:i}))]}),u&&(0,r.jsx)("div",{className:"panel-header-state",children:u}),h&&h.options.length>1&&(0,r.jsxs)(pS.A.Root,{className:"panel-header-switch","aria-label":h.label,value:h.value,onValueChange:e=>h.onChange(e),children:[h.options.map(e=>(0,r.jsxs)(pS.A.Item,{value:e.value,title:e.title,children:[(0,r.jsx)(pS.A.ItemHiddenInput,{}),e.label]},e.value)),(0,r.jsx)(pS.A.Indicator,{})]}),p.length>0&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{className:"panel-header-actions",children:p.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)(l.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)(c.In,{size:"16px",svg:e.icon})},e.id))}),(0,r.jsxs)(o.k.Root,{placement:"bottom-end",strategy:"fixed",children:[(0,r.jsx)(o.k.Trigger,{asChild:!0,children:(0,r.jsx)(l.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)(c.In,{size:"16px",svg:pE})})}),(0,r.jsx)(o.k.Positioner,{children:(0,r.jsx)(o.k.Content,{"aria-label":f("panel.more"),children:(0,r.jsx)(o.k.ScrollArea,{children:(0,r.jsx)(o.k.Group,{children:p.map(e=>(0,r.jsx)(o.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)(o.k.ItemBody,{children:(0,r.jsx)(o.k.ItemLabel,{children:e.label})})},e.id))})})})})]})]}),(0,r.jsx)(pR,{}),m&&(0,r.jsx)(l.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)(c.In,{size:"16px",svg:pM})})]})}function pR({className:e="panel-header-button"}){let{t}=(0,F.s)(),n=(0,s.useContext)(pC);if(!n)return null;let a=t(n.expanded?"panel.restore":"panel.expand");return(0,r.jsx)(l.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)(c.In,{size:"16px",svg:n.expanded?pT:pN})})}let pL="cuelo-html-pick",pP="cuelo-html-pick-exit";function pA(e,t){return"string"==typeof e&&e.length<=t}function p_(e){return"number"==typeof e&&Number.isFinite(e)}function pF({content:e,title:t,picking:n,onExitPick:a,onRequestEdit:i}){let{t:o}=(0,F.s)(),c=(0,s.useRef)(null),d=(0,s.useMemo)(()=>{if(!n)return{nonce:"",srcDoc:e};let t=crypto.randomUUID();return{nonce:t,srcDoc:function(e,t){var n;let r=`<script>${(n=t,`(function(){
20
+ ${n}`:e:n,images:i,documents:l}}function uo(e,t,n){if(e===t)return n?un(n):us(t);let r=us(e),s=n&&!ur(n)?un(n):r??(n?un(n):null),a=us(t),i=dZ.get(e);if(dZ.delete(e),i&&!dZ.has(t)&&dZ.set(t,i),ui(e),!s)return a;let l=a?ul(a.value,a.images,s.value,s.images,a.documents,s.documents):s;return ua(t,l),un(l)}function uc(e){let t=[];for(let n of e??[])n.attachmentId&&!t.includes(n.attachmentId)&&t.push(n.attachmentId);return t}function ud(e){ue();let t=dZ.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)}`}(),dZ.set(e,t)),t}function uu(e){let t=uc(dJ.get(e)?.documents),n=t.length?ud(e):dZ.get(e);for(let[e,n]of d4){for(let e of t)n.delete(e);0===n.size&&d4.delete(e)}let r=`${n??""}|${t.join(",")}`;d5.get(e)!==r&&(0!==t.length||n?d5.set(e,r):d5.delete(e),uv())}async function uh(e){let t=ud(e);d2.set(t,(d2.get(t)??0)+1),await d6.get(t);let n=!1;return{draftId:t,end(e){if(n)return;n=!0;let r=(d2.get(t)??1)-1;if(r>0?d2.set(t,r):d2.delete(t),e){let n=d4.get(t)??new Set;n.add(e),d4.set(t,n)}dQ.set(t,dX),uv()}}}function up(e,t){let n=d8.get(e);if(!n)return[];for(let e of t)n.delete(e);return 0===n.size&&d8.delete(e),[...n].sort()}async function um(){if(!d3)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 dZ)t(n,uc(dJ.get(e)?.documents));for(let{draftId:e,ids:n}of d0.values())t(e,n);for(let[e,n]of d4)t(e,n);for(let e of dQ.keys())t(e,[]);for(let e of d8.keys())t(e,[]);return new Map([...e].map(([e,t])=>[e,[...t].sort()]))}()].filter(([e,t])=>{if(d2.has(e))return!1;let n=dQ.get(e);return up(e,t).length>0||(0===t.length?void 0!==n:n!==t.join(","))}),t=d2.size>0,n=!1;for(let[r,s]of[...e.filter(([,e])=>e.length>0),...e.filter(([,e])=>0===e.length)]){if(0===s.length&&t)continue;let e=up(r,s),a=d3(r,s,e).then(()=>{0===s.length?dQ.delete(r):dQ.set(r,s.join(","));let t=d8.get(r);if(t){for(let n of e)t.delete(n);0===t.size&&d8.delete(r)}},()=>{n=!0,s.length>0&&(t=!0)});d6.set(r,a),await a,d6.get(r)===a&&d6.delete(r)}n?function(){if(ux)return;ux=!0;let e=setTimeout(()=>{ux=!1,uv()},ug);"object"==typeof e&&"unref"in e&&e.unref(),ug=Math.min(2*ug,6e4)}():ug=uf}let uf=5e3,ug=5e3,ux=!1;function uv(){if(d3){if(d7){d9=!0;return}d7=Promise.resolve().then(um).finally(()=>{d7=null,d9&&(d9=!1,uv())})}}let uy=Math.floor(Number.MAX_SAFE_INTEGER/1048576),ub=Object.freeze({uploadLimitMb:100,autoCleanupEnabled:!0,orphanGraceDays:7});function uw(e){return"number"==typeof e&&Number.isSafeInteger(e)&&e>=1&&e<=uy}async function uk(e){let t,n=await e.json().catch(()=>null);if(!e.ok||!n||!uw(n.uploadLimitMb)||"boolean"!=typeof n.autoCleanupEnabled)throw Error("string"==typeof n?.error?n.error:`HTTP ${e.status}`);return{uploadLimitMb:uw((t=n&&"object"==typeof n?n:{}).uploadLimitMb)?t.uploadLimitMb:ub.uploadLimitMb,autoCleanupEnabled:"boolean"==typeof t.autoCleanupEnabled?t.autoCleanupEnabled:ub.autoCleanupEnabled,orphanGraceDays:7}}async function uj(e={}){return uk(await fetch("/api/attachment-settings",{cache:"no-store",signal:e.signal}))}async function uS(e){return uk(await fetch("/api/attachment-settings",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}))}function uC(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 uN(e){let t=0;for(let n=0;n<e.length;n++)"/"===e[n]&&t++;return t}function uT(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}function uI(e,t){let n=t?`${e}/`:e;return n.includes(" ")?`@"${n}" `:`@${n} `}function uM(e,t,n){let r=Math.max(1,Math.min(t,n)),s=Math.max(1,Math.max(t,n)),a=e.includes(" ")?`@"${e}"`:`@${e}`,i=r===s?`:${r}`:`:${r}-${s}`;return`${a}${i} `}let uE="omp-web:model-picks";function u$(){try{let e=JSON.parse(window.localStorage.getItem(uE)??"{}");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 uR(e,t,n,r,s={}){let a=s.gap??8,i=s.margin??8,l=s.prefer??"above",o=Math.min(s.minHeight??120,Math.max(0,n-2*i)),c=Math.max(0,e-a-i),d=Math.max(0,n-t-a-i),u="above"===l?c:d,h="above"===l?d:c,p=u>=r||u>=h;return{side:p?l:"above"===l?"below":"above",maxHeight:Math.max(o,Math.min(r,p?u:h))}}function uL(e,t,n){return Math.min(e*t,n)}function uP(e,t,n){let{viewportFraction:r,cap:a,gap:i,margin:l,minHeight:o,prefer:c}=n,[d,u]=(0,s.useState)({side:c??"above",maxHeight:a}),h=(0,s.useCallback)(()=>{let t=e.current;if(!t)return;let n=window.visualViewport?.height??window.innerHeight,s=t.getBoundingClientRect(),d=uR(s.top,s.bottom,n,uL(n,r,a),{gap:i,margin:l,minHeight:o,prefer:c});u(e=>e.side===d.side&&e.maxHeight===d.maxHeight?e:d)},[e,a,i,l,o,c,r]);return(0,s.useEffect)(()=>{if(!t)return;h();let n=e.current,r=n?new ResizeObserver(h):null;return n&&r&&r.observe(n),window.addEventListener("resize",h),window.addEventListener("scroll",h,!0),window.visualViewport?.addEventListener("resize",h),window.visualViewport?.addEventListener("scroll",h),()=>{r?.disconnect(),window.removeEventListener("resize",h),window.removeEventListener("scroll",h,!0),window.visualViewport?.removeEventListener("resize",h),window.visualViewport?.removeEventListener("scroll",h)}},[e,h,t]),d}var uA=n(14755);let u_="omp-web:model-roles-expanded";async function uF(e,t,n,r,s,a,i){let l=e.slice(1).split(/\s/,1)[0];try{let o=t?.length?t:await i?.()??[],c=[...uZ,...o].find(e=>e.name===l||"aliases"in e&&e.aliases?.includes(l));if(a&&(!c||"builtin"===c.source))return s(`/${l} cannot run with attachments. Remove them and retry.`),!1;let d=await n?.(e);if(d?.handled){if(d.error)return!1;return d.prompt&&r(d.prompt),!0}if(c&&"builtin"!==c.source)return r(e),!0;return s(`/${l} is not available in this web session.`),!1}catch(e){return s(e instanceof Error?e.message:String(e)),!1}}function uO(e){let t=e.transcription?.state;return"planning"===t||"confirm"===t||"running"===t}let uz=["off","default","full"],uD={off:"none",default:"default",full:"full"},uW=uA.IN.join(" \xb7 "),uH=uA.C1.filter(e=>!uA.IN.includes(e)).join(" \xb7 ");function uU(e){return"above"===e?{bottom:"calc(100% + 8px)"}:{top:"calc(100% + 8px)"}}let uB=new Intl.Collator(void 0,{numeric:!0,sensitivity:"base"}),uq=0,uV={"text/markdown":"Markdown","text/plain":"Text","application/pdf":"PDF"};function uK(e,t){return uB.compare(e.name||e.modelId,t.name||t.modelId)||uB.compare(e.provider,t.provider)||uB.compare(e.modelId,t.modelId)}let uJ=["auto","off","minimal","low","medium","high","xhigh","max"],uG=["low","medium","high","xhigh"],uY={auto:"chat.thinkingAuto",off:"chat.thinkingOff",minimal:"chat.thinkingMinimal",low:"chat.thinkingLow",medium:"chat.thinkingMedium",high:"chat.thinkingHigh",xhigh:"chat.thinkingXhigh",max:"chat.thinkingMax"},uZ=[{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"}],uQ=["builtin","extension","custom","mcp_prompt","prompt","file","skill"],uX={builtin:"chat.builtIn",extension:"chat.extensions",custom:"chat.customCommands",mcp_prompt:"chat.mcpPrompts",prompt:"chat.prompts",file:"chat.fileCommands",skill:"chat.skills"},u0={builtin:0,extension:1,custom:2,mcp_prompt:3,prompt:4,file:5,skill:6};function u1(e,t,n){let r=e.name.toLowerCase(),s=u2(e,n).toLowerCase();return r===t?0:r.startsWith(t)?1:r.includes(t)?2:s.includes(t)?3:4}function u2(e,t){return"descriptionKey"in e?t(e.descriptionKey):e.description??""}function u4(e,t){return"skill"===e.source&&!!e.name.startsWith("skill:")&&!0===t[e.name.slice(6)]}function u8(e){return{data:e.data,mimeType:e.mimeType}}function u5(e){return{...e,previewUrl:`data:${e.mimeType};base64,${e.data}`}}function u6(e){return(e??[]).filter(rs).slice(0,10).map(u5)}let u3=/^File saved at: (.+)\n\(([^,\n]+), (\d+) bytes\)/,u7="\n\nTranscript of the audio ";function u9(e){return ae(e).map(e=>{let t=al(e),n="audio"===t&&e.attachmentId&&!e.text.includes(u7)?u3.exec(e.text):null;return{...e,id:++uq,status:"ready",..."audio"===t||"file"===t?{stored:t}:{},...n?{storedInfo:{path:n[1],mimeType:n[2],size:Number(n[3])}}:{}}})}function he({name:e,mimeType:t,size:n,text:r,attachmentId:s}){return s?{name:e,mimeType:t,size:n,text:r,attachmentId:s}:{name:e,mimeType:t,size:n,text:r}}function ht(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 hn extends Error{constructor(e,t,n,r){super(e),this.code=t,this.completedParts=n,this.parts=r}}let hr="composer:unkeyed";async function hs(e){let t=await e.json().catch(()=>null),n=t&&"object"==typeof t?{...t}:{};if(e.ok)return n;let r="number"==typeof n.completedParts?n.completedParts:null,s="number"==typeof n.parts?n.parts:null;throw new hn("string"==typeof n.error?n.error:`HTTP ${e.status}`,"string"==typeof n.code?n.code:null,r,s)}function ha(e){e.previewUrl.startsWith("blob:")&&URL.revokeObjectURL(e.previewUrl)}function hi({tone:e,title:t,body:n}){let s="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:0,borderRadius:"var(--radius-control)",background:`var(--${s}-soft)`,color:`var(--${s})`,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 hl({error:e}){return e?(0,r.jsx)(hi,{tone:"error",title:"Model error",body:e}):null}function ho({warnings:e}){return e&&0!==e.length?(0,r.jsx)(hi,{tone:"warning",title:e.length>1?"Model scope warnings":"Model scope warning",body:e.join("\n")}):null}let hc=(0,s.forwardRef)(function({onSend:e,onAbort:t,onSteer:n,onFollowUp:a,isStreaming:i,model:o,isAutoModelSelection:c,modelNames:d,modelList:u,modelError:h,modelScopeWarnings:p,onModelChange:m,onMainPresetChange:f,mainPresetActiveAlias:g,modelRoles:x,onRoleModelChange:v,modelSwitching:y,onCompact:b,onAbortCompaction:w,isCompacting:k,compactError:j,compactResult:S,toolPreset:C,onToolPresetChange:N,thinkingLevel:T,effectiveThinkingLevel:I,outputTokensPerSecond:M=null,outputSpeedLive:E=!1,thinkingCeiling:$,onThinkingLevelChange:R,availableThinkingLevels:L,thinkingLevelMap:P,fastMode:A=null,fastModeBusy:_=!1,onFastModeToggle:O,retryInfo:z,deliveryRows:D=[],inputHistory:W=[],onRecallQueue:H,onRemoveQueuedMessage:B,slashCommands:q,slashCommandsLoading:V,onLoadSlashCommands:K,onBuiltinCommand:J,soundEnabled:G,onSoundToggle:Y,onAudioUnlock:Z,onPromptWithStreamingBehavior:Q,draftKey:X,cwd:ee,sessionTitle:et,sessionId:en,onEnsureSession:er,onLiveTranscriptPersisted:es,startPlace:ea,notice:ei},el){let eo,ec,ed,eu,eh,ep,em,ef,eg,ex,{t:ev}=(0,F.s)();sF();let{st:ey}=sz(),eb=D.some(e=>e.removable),ew=U(),[ek,ej]=(0,s.useState)(()=>X?us(X)?.value??"":""),[eS,eC]=(0,s.useState)(!1),[eN,eT]=(0,s.useState)(null),[eI,eM]=(0,s.useState)(""),[eE,e$]=(0,s.useState)({});(0,s.useEffect)(()=>{eS&&e$(u$())},[eS]);let[eR,eL]=(0,s.useState)(!1);(0,s.useEffect)(()=>{if(eS)try{eL("1"===window.localStorage.getItem(u_))}catch{}},[eS]);let eP=()=>{eL(e=>{let t=!e;try{window.localStorage.setItem(u_,t?"1":"0")}catch{}return t})},[eA,e_]=(0,s.useState)(!1),[eF,eO]=(0,s.useState)(null),[ez,eD]=(0,s.useState)(!1),[eW,eH]=(0,s.useState)(!1),[eU,eB]=(0,s.useState)(null),[eq,eV]=(0,s.useState)(!1),[eK,eJ]=(0,s.useState)(()=>X?u6(us(X)?.images):[]),[eG,eY]=(0,s.useState)(()=>X?u9(us(X)?.documents):[]),[eZ,eQ]=(0,s.useState)(null),eX=(0,s.useMemo)(()=>eG.filter(e=>"ready"===e.status),[eG]),e0=eG.some(e=>"ready"!==e.status||uO(e)),e1=eG.filter(e=>"audio"===e.stored&&e.attachmentId&&e.storedInfo&&(void 0!==e.transcription||!e.text.includes(u7))),e2=ek.trimStart(),e4=0===eK.length&&0===eG.length&&e2.startsWith("!"),e8=e4&&e2.startsWith("!!"),[e5,e6]=(0,s.useState)(!1),[e3,e7]=(0,s.useState)(0),[e9,te]=(0,s.useState)(null),tt=e9?.value===ek&&e9.draftKey===X?e9.token:null,[tn,tr]=(0,s.useState)(!1),[ts,ta]=(0,s.useState)(!1),ti=(0,s.useRef)(null),[tl,to]=(0,s.useState)(null),[tc,td]=(0,s.useState)(!1),[tu,th]=(0,s.useState)(0),[tp,tm]=(0,s.useState)(!1),[tf,tg]=(0,s.useState)(0),[tx,tv]=(0,s.useState)(null),[ty,tb]=(0,s.useState)(!1),[tw,tk]=(0,s.useState)(null),[tj,tS]=(0,s.useState)(null),tC=ee&&tj?.cwd===ee?tj.values:{},tN=(0,s.useRef)(null),tT=(0,s.useRef)(null),tI=(0,s.useRef)(null),tM=(0,s.useRef)(null),tE=(0,s.useRef)(null),t$=(0,s.useRef)(null),tR=(0,s.useRef)(null),tL=(0,s.useRef)(null),tP=(0,s.useRef)(null),tA=(0,s.useRef)(null),t_=(0,s.useRef)(null),tF=(0,s.useRef)(!1),tO=(0,s.useRef)(0),tz=(0,s.useRef)(!1),tD=(0,s.useRef)([]),tW=(0,s.useRef)([]),tH=(0,s.useRef)([]),tU=(0,s.useRef)(null),tB=(0,s.useRef)(null),tq=(0,s.useRef)(X),tV=(0,s.useRef)(ek),tK=(0,s.useRef)(eK),tJ=(0,s.useRef)(0),tG=(0,s.useRef)(eG);tV.current=ek,tK.current=eK,tG.current=eG,(0,s.useImperativeHandle)(el,()=>({insertIfEmpty(e){let t=tN.current;(t?t.value:ek).trim()||(tV.current=e,ej(e),to(null),requestAnimationFrame(()=>{t&&(t.focus(),t.style.height="auto",t.style.height=`${Math.min(t.scrollHeight,200)}px`)}))},replaceMessage(e){let t,n,r=tN.current;if(!function(e,t,n,r=0){return!e.trim()&&0===t&&0===n&&0===r}(r?r.value:ek,tK.current.length,tJ.current,tG.current.length))return;let s=(t="string"==typeof e.content?e.content:e.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n"),ar(t)?.message??t),a=u6("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 rs(r)?[r]:[]})),i=u9((n="string"==typeof e.content?e.content:e.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n"),ar(n)?.documents??[]));tV.current=s,tK.current=a,tG.current=i,ej(s),to(null),tm(!1),eJ(e=>(e.forEach(ha),a)),eY(i),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(tq.current!==e)return void uo(e,t);let n={value:tV.current,images:tK.current.map(u8),documents:tG.current.filter(e=>"ready"===e.status).map(he)},r=uo(e,t,n)??{value:"",images:[],documents:[]},s=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(tq.current=t,s)return;let a=u6(r.images),i=ht(u9(r.documents),tG.current),l=r.value;tV.current=l,tK.current=a,tG.current=i,ej(l),eJ(e=>(e.forEach(ha),a)),eY(i),to(null),tm(!1)},restoreSubmission(e,t,n,r){if(!e.trim()&&!t?.length&&!n?.length)return;let s=tq.current,a=r??s,i=a===s,l=!i&&a?us(a):null,o=ul(e,t,i?tV.current:l?.value??"",i?tK.current.map(u8):l?.images??[],n,i?tG.current.filter(e=>"ready"===e.status).map(he):l?.documents??[]);if(a&&ua(a,o),!i)return;let c=t?.length?[...u6(t).slice(0,Math.max(0,10-tK.current.length)),...tK.current].slice(0,10):tK.current,d=ht(u9(o.documents),tG.current);tV.current=o.value,tK.current=c,tG.current=d,ej(o.value),to(null),tm(!1),t?.length&&eJ(e=>{let n=Math.max(0,10-e.length),r=u6(t).slice(0,n),s=r.length>0?[...r,...e]:e;return tK.current=s,s}),eY(d),requestAnimationFrame(()=>{let e=tN.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=tN.current;if(!t)return void ej(t=>t+(t?" ":"")+e);let n=t.selectionStart??t.value.length,r=t.selectionEnd??t.value.length,s=t.value.slice(0,n),a=t.value.slice(r),i=s.length>0&&!s.endsWith(" ")?" ":"",l=s+i+e+a;tV.current=l,ej(l),to(null),requestAnimationFrame(()=>{if(!t)return;let r=n+i.length+e.length;t.setSelectionRange(r,r),t.focus(),t.style.height="auto",t.style.height=`${Math.min(t.scrollHeight,200)}px`})},addAttachments(e){nt(e)}}));let tY=(0,s.useCallback)(async e=>{let t=Math.max(0,10-tK.current.length-tJ.current),n=e.filter(e=>e.size>0xa00000);n.length>0&&eQ(ev("chat.attachImageTooLarge",{name:n.map(e=>e.name).join(", "),limit:as(0xa00000)}));let r=e.filter(e=>e.size<=0xa00000),s=r.slice(0,t);if(s.length<r.length&&eQ(ev("chat.attachImageLimit",{count:10})),s.length){tJ.current+=s.length;try{let e=await Promise.all(s.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)})));eJ(t=>{let n=e.slice(0,Math.max(0,10-t.length));e.slice(n.length).forEach(ha);let r=[...t,...n];return tK.current=r,r})}finally{tJ.current-=s.length}}},[ev]),tZ=(0,s.useCallback)(async e=>{for(let t of e){let e=s6(t);if(!e)continue;if(tG.current.length>=3){eQ(ev("chat.attachLimit",{count:3}));continue}if(t.size>8388608){eQ(ev("chat.attachTooLarge",{name:t.name,limit:as(8388608)}));continue}if(tG.current.reduce((e,t)=>e+t.size,0)+t.size>0x1000000){eQ(ev("chat.attachTotalTooLarge",{limit:as(0x1000000)}));continue}let n={id:++uq,name:t.name,mimeType:s4[e],size:t.size,text:"",status:"extracting"},r=[...tG.current,n];tG.current=r,eY(r);try{let e=await at(t);if(tG.current.reduce((e,t)=>e+(t.id===n.id?0:t.text.length),0)+e.text.length>24e4)throw new s2("text_too_large","Total extracted text exceeds 240000 characters");let r=tG.current.map(t=>t.id===n.id?{...e,id:t.id,status:"ready"}:t);tG.current=r,eY(r)}catch(s){let e=tG.current.some(e=>e.id===n.id),r=tG.current.filter(e=>e.id!==n.id);if(tG.current=r,eY(r),!e)continue;s instanceof s2?"text_too_large"===s.code?eQ(ev("chat.attachTextTooLarge",{name:t.name,limit:12e4.toLocaleString()})):"too_many_pages"===s.code?eQ(ev("chat.attachTooManyPages",{name:t.name,limit:250})):"no_extractable_text"===s.code?eQ(ev("chat.attachNoPdfText",{name:t.name})):"password_protected"===s.code?eQ(ev("chat.attachPasswordProtected",{name:t.name})):eQ(ev("chat.attachExtractFailed",{name:t.name})):eQ(ev("chat.attachExtractFailed",{name:t.name}))}}},[ev]),tQ=(0,s.useCallback)((e,t)=>{if(!tG.current.some(t=>t.id===e))return!1;let n=t?tG.current.map(n=>n.id===e?t:n):tG.current.filter(t=>t.id!==e);return tG.current=n,eY(n),!0},[]),tX=(0,s.useCallback)((e,t)=>{if(!tG.current.some(t=>t.attachmentId===e))return!1;let n=tG.current.map(n=>n.attachmentId===e?t(n):n);return tG.current=n,eY(n),!0},[]),t0=(0,s.useCallback)((e,t,n)=>{if(!e||e===tq.current)return;let r=us(e);r?.documents.some(e=>e.attachmentId===t)&&ua(e,{...r,documents:u9(r.documents).map(e=>e.attachmentId===t?n(e):e).map(he)})},[]),t1=(0,s.useRef)(new Map),t2=(0,s.useRef)(new Map),t4=(0,s.useRef)(new Set),t8=(0,s.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)),s=ao({...e.storedInfo,transcript:t},r);return s.length>r?null:{...e,text:s,size:new TextEncoder().encode(s).byteLength,transcription:void 0}},[]),t5=(0,s.useCallback)(e=>e instanceof hn&&"media_tool_unavailable"===e.code?ev("chat.transcribeToolMissing"):e instanceof hn&&"transcription_failed"===e.code&&null!==e.completedParts&&null!==e.parts?ev("chat.transcribePartialFailed",{done:e.completedParts,total:e.parts}):e instanceof Error?e.message:String(e),[ev]),t6=(0,s.useCallback)(async(e,t)=>{let n=tq.current,r=tG.current.find(t=>t.attachmentId===e);if(!r?.storedInfo)return;let s=r.transcription?.state==="confirm"?r.transcription.plan:null;t2.current.get(e)?.abort();let a=new AbortController;t2.current.set(e,a),tX(e,e=>({...e,transcription:{state:"running",plan:s}}));try{let r=await hs(await fetch(`/api/attachments/${encodeURIComponent(e)}/transcription`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({confirmed:t}),signal:a.signal}));if("string"!=typeof r.transcript)throw new hn("Invalid transcription result",null,null,null);let s=r.transcript;tX(e,e=>t8(e,s,tG.current)??{...e,transcription:{state:"failed",error:ev("chat.transcribeTooLong")}})||t0(n,e,e=>t8(e,s,[])??e)}catch(n){if(a.signal.aborted)return void tX(e,e=>({...e,transcription:{state:"skipped"}}));if(n instanceof hn&&"confirmation_required"===n.code)return void t3.current?.(e);let t=t5(n);tX(e,e=>({...e,transcription:{state:"failed",error:t}}))}finally{t2.current.get(e)===a&&t2.current.delete(e)}},[ev,t5,tX,t0,t8]),t3=(0,s.useRef)(null),t7=(0,s.useCallback)(async e=>{let t;t2.current.get(e)?.abort();let n=new AbortController;t2.current.set(e,n),tX(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 hn("Invalid transcription plan",null,null,null);return{durationSeconds:e.durationSeconds,estimatedCalls:e.estimatedCalls,requiresConfirmation:e.requiresConfirmation,processing:e.processing,notice:e.notice}}(await hs(await fetch(`/api/attachments/${encodeURIComponent(e)}/transcription`,{cache:"no-store",signal:n.signal})))}catch(t){if(n.signal.aborted)tX(e,e=>({...e,transcription:{state:"skipped"}}));else{let n=t5(t);tX(e,e=>({...e,transcription:{state:"failed",error:n}}))}return}finally{t2.current.get(e)===n&&t2.current.delete(e)}t.requiresConfirmation?tX(e,e=>({...e,transcription:{state:"confirm",plan:t}})):await t6(e,!1)},[t6,t5,tX]);t3.current=t7;let t9=(0,s.useCallback)(e=>{let t=t2.current.get(e);t?t.abort():tX(e,e=>({...e,transcription:{state:"skipped"}}))},[tX]),ne=(0,s.useCallback)(async(e,t)=>{let n=null;for(let r of e){if(tG.current.length>=3){eQ(ev("chat.attachLimit",{count:3}));continue}let e="file"===t&&r.size<=8388608,s={id:++uq,name:r.name,mimeType:"text/plain",size:e?r.size:0,text:"",status:e?"extracting":"uploading",sourceSize:r.size},a=[...tG.current,s];tG.current=a,eY(a);let i=(e,t)=>{let n=tG.current.filter(e=>e.id!==s.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]?s9("utf-16le",t.subarray(2)):254===t[0]&&255===t[1]?s9("utf-16be",t.subarray(2)):t.includes(0)?null:s9("utf-8",t)??s9("euc-kr",t)},()=>null);if(null!==e&&i(e.length,r.size)){tQ(s.id,{...s,text:e,status:"ready"});continue}}if(null===n&&(n=1048576*(await uj().catch(()=>ub)).uploadLimitMb),r.size>n){tQ(s.id,null)&&eQ(ev("chat.attachStoredTooLarge",{name:r.name,limit:as(n)}));continue}let l={...s,stored:t,status:"uploading",size:0};if(!tQ(s.id,l))continue;let o=tq.current??hr,c=await uh(o),d=null,u=new AbortController;t1.current.set(s.id,u);try{if(t4.current.has(s.id))continue;let e=await ac(r,{sessionId:en,draftId:c.draftId,signal:u.signal}),n=tG.current.filter(e=>e.id!==s.id).reduce((e,t)=>e+t.text.length,0),a=ao({path:e.path,size:e.size,mimeType:e.mimeType},Math.min(12e4,24e4-n)),h=new TextEncoder().encode(a).byteLength;if(!i(a.length,h)){tQ(s.id,null)&&eQ(ev("chat.attachTotalTooLarge",{limit:as(0x1000000)}));continue}let p={...l,attachmentId:e.id,text:a,size:h,status:"ready",storedInfo:{path:e.path,size:e.size,mimeType:e.mimeType},..."audio"===t?{transcription:{state:"planning"}}:{}};if(tQ(s.id,p))d=e.id;else if(!t4.current.has(s.id)&&o!==tq.current){let t=us(o)??{value:"",images:[],documents:[]};ua(o,{...t,documents:[...t.documents,he(p)]}),d=e.id}}catch(e){if(u.signal.aborted)continue;tQ(s.id,null)&&eQ(ev("chat.attachUploadFailed",{name:r.name,error:e instanceof Error?e.message:String(e)}))}finally{t1.current.delete(s.id),c.end(d)}d&&"audio"===t&&tG.current.some(e=>e.attachmentId===d)&&t7(d)}},[tQ,t7,en,ev]),nt=(0,s.useCallback)(async e=>{eQ(null);let{images:t,documents:n,audio:r,files:s}=function(e){let t=[],n=[],r=[],s=[];for(let a of e)a.type.startsWith("image/")?t.push(a):null!==s6(a)?n.push(a):s7(a)?r.push(a):s.push(a);return{images:t,documents:n,audio:r,files:s}}(e),a=n.filter(e=>e.size>8388608);await Promise.all([tY(t),tZ(n.filter(e=>e.size<=8388608)),ne(r,"audio"),ne([...s,...a],"file")])},[tZ,ne,tY]),nn=(0,s.useCallback)(e=>{eJ(t=>{let n=[...t],[r]=n.splice(e,1);return r&&ha(r),tK.current=n,n})},[]),nr=(0,s.useCallback)(e=>{let t=tG.current.find(t=>t.id===e);if(t4.current.add(e),t1.current.get(e)?.abort(),t?.attachmentId){t2.current.get(t.attachmentId)?.abort();var n=t.attachmentId;for(let[e,t]of d4)t.delete(n)&&(0===t.size&&d4.delete(e),uv())}let r=tG.current.filter(t=>t.id!==e);tG.current=r,eY(r)},[]),ns=(0,s.useCallback)(()=>{tK.current=[],eJ(e=>(e.forEach(ha),[]))},[]),na=(0,s.useCallback)(()=>{tG.current=[],eY([])},[]),ni=(0,s.useCallback)(()=>{tV.current="",ej(""),to(null),te(null),tr(!1),tm(!1),X&&ui(X),tq.current&&tq.current!==X&&ui(tq.current),ns(),na(),eQ(null),tN.current&&(tN.current.style.height="auto")},[na,ns,X]);(0,s.useEffect)(()=>{X&&tq.current===X&&ua(X,{value:ek,images:eK.map(u8),documents:eX.map(he)})},[eK,X,eX,ek]),(0,s.useEffect)(()=>{let e=tq.current;if(e===X)return;e&&ua(e,{value:tV.current,images:tK.current.map(u8),documents:tG.current.filter(e=>"ready"===e.status).map(he)});let t=X?us(X):null;tq.current=X;let n=t?.value??"",r=u6(t?.images),s=u9(t?.documents);tV.current=n,tK.current=r,tG.current=s,ej(n),to(null),tm(!1),eJ(e=>(e.forEach(ha),r)),eY(s)},[X]),(0,s.useEffect)(()=>{let e=tN.current;e&&(e.style.height="auto",ek&&(e.style.height=`${Math.min(e.scrollHeight,200)}px`))},[ek]),(0,s.useEffect)(()=>()=>{tK.current.forEach(ha)},[]);let nl=(0,s.useCallback)((e,t)=>{let n=function(e,t){let n=uc(t);if(0===n.length)return()=>{};let r=++d1;return d0.set(r,{draftId:ud(e),ids:n}),e=>{if("accepted"!==e&&"returned"!==e)return;let t=d0.get(r);if(t){if(d0.delete(r),"accepted"===e){let e=d8.get(t.draftId)??new Set;for(let n of t.ids)e.add(n);d8.set(t.draftId,e)}uv()}}}(tq.current??hr,e);Promise.resolve(t()).then(e=>n("accepted"===e||"returned"===e?e:void 0),()=>void 0)},[]),no=(0,s.useCallback)(async()=>{let t=ek.trim(),n=e2.trim(),r=n.startsWith("/")||n.startsWith("!")?n:t;if(!r&&!eK.length&&!eX.length||i||e0)return;Z?.();let s=eK.length?eK:void 0,a=eX.length?eX:void 0;if(r.startsWith("/")){await uF(r,q,J,t=>nl(a,()=>e(t,s,a)),eQ,!!(s||a),K)&&ni();return}ni(),nl(a,()=>e(r,s,a))},[ek,e2,eK,eX,e0,i,J,q,K,e,ni,Z,nl]),nc=!e2.startsWith("/")||e2.startsWith("//")||/\s/.test(e2.slice(1))?null:e2.slice(1).toLowerCase(),nd=(()=>{if(null===nc)return[];let e=[...i?[]:uZ,...q??[]],t=new Set;return[...e].filter(e=>{let t=e.name.toLowerCase(),n=u2(e,ev).toLowerCase();return t.includes(nc)||n.includes(nc)}).sort((e,t)=>{let n=u1(e,nc,ev)-u1(t,nc,ev);return 0!==n?n:u0[e.source]-u0[t.source]||uB.compare(e.name,t.name)}).filter(e=>{let n=e.name.toLowerCase();return!t.has(n)&&(t.add(n),!0)})})(),{commands:nu,groups:nh}=(eo=0,{commands:(ec=uQ.map(e=>{let t=nd.filter(t=>t.source===e),n="skill"===e?[...t.filter(e=>!u4(e,tC)),...t.filter(e=>u4(e,tC))]:t;return{source:e,items:n.map(e=>({command:e,index:eo++}))}}).filter(e=>e.items.length>0)).flatMap(e=>e.items.map(({command:e})=>e)),groups:ec}),np=1===nd.length?ev(nc?"chat.match":"chat.command"):ev(nc?"chat.matches":"chat.commands",{count:nd.length}),nm=!!ek.trim(),nf=!e0&&(nm||eK.length>0||eX.length>0),ng=(0,s.useCallback)((e,t)=>{let n=function(e,t){let n=Math.max(0,Math.min(e.length,t)),r=/(?:^|\s)(\/\/[^\s]*)$/.exec(e.slice(0,n));if(!r)return null;let s=n-r[1].length,a=/^\S*/.exec(e.slice(n))[0];return{start:s,end:n+a.length,query:e.slice(s+2,n)}}(e,t??e.length);if(te(n?{value:e,draftKey:X,token:n}:null),ta(!1),!ee)return void to(null);let r=t??e.length;to(uC(e.slice(0,r)))},[ee,X]),nx=tl?.query??null,nv=s.useMemo(()=>null!==nx&&tx&&tx.cwd===ee?function(e,t,n=20){let r=t.toLowerCase();if(!r)return e.slice(0,n);let s=[];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:uT(t,n)&&(r=10);else{let e=n.lastIndexOf("/"),s=-1===e?n:n.slice(e+1);s===t?r=100:s.startsWith(t)?r=80:s.includes(t)?r=50:n.includes(t)?r=30:uT(t,n)&&(r=10)}return e.isDir&&r>0&&(r+=10),r}(t,r);e>0&&s.push({entry:t,score:e})}return s.sort((e,t)=>t.score-e.score||uN(e.entry.path)-uN(t.entry.path)||e.entry.path.localeCompare(t.entry.path)),s.slice(0,n).map(e=>e.entry)}(tx.entries,nx):[],[nx,tx,ee]),ny=!!(nx&&tx?.truncated&&tx.cwd===ee);(0,s.useEffect)(()=>{if(!ny||!ee||!nx)return;let e=setTimeout(()=>{fetch(`/api/file-index?cwd=${encodeURIComponent(ee)}&q=${encodeURIComponent(nx)}`).then(e=>{if(!e.ok)throw Error(`file search failed: ${e.status}`);return e.json()}).then(e=>tk({cwd:ee,query:nx,matches:e.matches??[]})).catch(()=>{})},150);return()=>clearTimeout(e)},[ny,nx,ee]);let nb=ny&&null!==tw&&tw.cwd===ee&&tw.query===nx,nw=nb?tw.matches:nv,nk=null===tl?null:`${tl.start}:${+!!tl.quoted}:${tl.query}`;(0,s.useEffect)(()=>{if(null===nk){td(!1),th(0);return}td(!0),th(0)},[nk]);let nj=null!==tl,nS=uP(tA,tp,{viewportFraction:.44,cap:360}),nC=uP(tA,e5,{viewportFraction:.56,cap:460}),nN=uP(tA,tc,{viewportFraction:.48,cap:400}),nT=uP(tA,tn,{viewportFraction:.48,cap:400}),nI=tt?`${tt.start}:${tt.end}:${tt.query}`:null;(0,s.useEffect)(()=>{tr(null!==nI)},[nI]);let nM=(0,s.useCallback)((e,t,n,r=!1)=>{tV.current===e&&tq.current===X&&(tV.current=t,ej(t),te(null),tr(!1),ta(r),requestAnimationFrame(()=>{let e=tN.current;e&&(e.focus(),e.setSelectionRange(n,n),e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)}))},[X]);(0,s.useEffect)(()=>{if(!nj||!ee)return;let e=tU.current;e&&e.cwd===ee&&Date.now()-e.fetchedAt<1e4||tB.current===ee||(tB.current=ee,tb(!0),fetch(`/api/file-index?cwd=${encodeURIComponent(ee)}`).then(e=>{if(!e.ok)throw Error(`file index failed: ${e.status}`);return e.json()}).then(e=>{tv({cwd:ee,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)=>uN(e.path)-uN(t.path)||e.path.localeCompare(t.path)),n}(e.files??[]),truncated:!!e.truncated}),tU.current={cwd:ee,fetchedAt:Date.now()}}).catch(()=>{tU.current=null}).finally(()=>{tB.current=null,tb(!1)}))},[nj,ee]);let nE=(0,s.useCallback)(e=>{if(!tl)return;let t=tN.current,n=t?.selectionStart??ek.length,r=ek.slice(0,tl.start),s=ek.slice(n);tl.quoted&&s.startsWith('"')&&(s=s.slice(1));let a=function(e,t,n=!1){let r=t?`${e}/`:e,s=n||r.includes(" ");if(t){let e=s?`@"${r}"`:`@${r}`;return{text:e,cursorOffset:s?e.length-1:e.length}}let a=s?`@"${r}" `:`@${r} `;return{text:a,cursorOffset:a.length}}(e.path,e.isDir,tl.quoted),i=r+a.text+s,l=r.length+a.cursorOffset;ej(i),to(uC(i.slice(0,l))),requestAnimationFrame(()=>{let e=tN.current;e&&(e.focus(),e.setSelectionRange(l,l),e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)})},[tl,ek]);(0,s.useEffect)(()=>{tu>=nw.length&&th(Math.max(0,nw.length-1))},[nw.length,tu]),(0,s.useEffect)(()=>{tW.current.length=nw.length},[nw.length]),(0,s.useEffect)(()=>{tc&&tW.current[tu]?.scrollIntoView({block:"nearest",inline:"nearest"})},[tu,tc]),(0,s.useEffect)(()=>{tf>=W.length&&tg(Math.max(0,W.length-1))},[W.length,tf]),(0,s.useEffect)(()=>{tH.current.length=W.length},[W.length]),(0,s.useEffect)(()=>{tp&&tH.current[tf]?.scrollIntoView({block:"nearest",inline:"nearest"})},[tf,tp]);let n$=(0,s.useCallback)(e=>{tV.current=e,ej(e),tm(!1),tg(0),to(null),requestAnimationFrame(()=>{let t=tN.current;t&&(t.focus(),t.setSelectionRange(e.length,e.length),t.style.height="auto",t.style.height=`${Math.min(t.scrollHeight,200)}px`)})},[]),nR=(0,s.useCallback)(e=>{let t=`/${e.name} `;tV.current=t,ej(t),e6(!1),e7(0),requestAnimationFrame(()=>{let e=tN.current;e&&(e.focus(),e.setSelectionRange(t.length,t.length),e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)})},[]),nL=(0,s.useCallback)(async e=>{let t=ek.trim(),r=e2.trim(),s=r.startsWith("/")||r.startsWith("!")?r:t,i=e0||!s&&0===eK.length&&0===eX.length?null:{message:s,images:eK.length?eK:void 0,documents:eX.length?eX:void 0};if(!i)return;Z?.();let l="steer"===e?"steer":"followUp";if(s.startsWith("/")){await uF(s,q,J,e=>{if(!Q)throw Error("Cannot queue this command while the session is busy.");nl(i.documents,()=>Q(e,l,i.images,i.documents))},eQ,!!(i.images?.length||i.documents?.length),K)&&ni();return}ni(),"steer"===e&&n?nl(i.documents,()=>n(i.message,i.images,i.documents)):"followup"===e&&a&&nl(i.documents,()=>a(i.message,i.images,i.documents))},[ek,e2,eK,eX,e0,q,K,J,Q,n,a,ni,Z,nl]),nP=(0,s.useCallback)(e=>{let t=nu.length-1;if(t<0)return 0;if("left"===e)return Math.max(0,e3-1);if("right"===e)return Math.min(t,e3+1);let n=tD.current[e3];if(!n)return"down"===e?Math.min(t,e3+1):Math.max(0,e3-1);let r=n.getBoundingClientRect(),s=r.left+r.width/2,a=r.top+r.height/2,i=-1,l=1/0;for(let n=0;n<=t;n+=1){if(n===e3)continue;let t=tD.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 c=1e3*Math.abs(o)+Math.abs(r.left+r.width/2-s);c<l&&(i=n,l=c)}return i>=0?i:"down"===e?Math.min(t,e3+1):Math.max(0,e3-1)},[nu.length,e3]),nA=(0,s.useCallback)(e=>{let r=e.nativeEvent,s=Date.now()-tO.current<100,l=tF.current||r.isComposing||229===r.keyCode;if("Enter"===e.key&&!e.shiftKey&&(l||s)){s&&e.preventDefault();return}if(tp&&!l){if("ArrowDown"===e.key){e.preventDefault(),tg(e=>Math.min(Math.max(0,W.length-1),e+1));return}if("ArrowUp"===e.key){e.preventDefault(),tg(e=>Math.max(0,e-1));return}if("Escape"===e.key){e.preventDefault(),tm(!1);return}if(("Tab"===e.key||"Enter"===e.key&&!e.shiftKey)&&W[tf]){e.preventDefault(),n$(W[tf]);return}}if(!(tn&&tt&&!l&&ti.current?.handleKeyDown(e))){if(e5&&null!==nc){if("ArrowDown"===e.key){e.preventDefault(),e7(nP("down"));return}if("ArrowUp"===e.key){e.preventDefault(),e7(nP("up"));return}if("ArrowRight"===e.key){e.preventDefault(),e7(nP("right"));return}if("ArrowLeft"===e.key){e.preventDefault(),e7(nP("left"));return}if("Escape"===e.key){e.preventDefault(),e6(!1);return}if(("Tab"===e.key||"Enter"===e.key&&!e.shiftKey)&&nu[e3]){e.preventDefault(),nR(nu[e3]);return}}if(tc&&null!==tl&&!l){if("ArrowDown"===e.key){e.preventDefault(),th(e=>Math.min(Math.max(0,nw.length-1),e+1));return}if("ArrowUp"===e.key){e.preventDefault(),th(e=>Math.max(0,e-1));return}if("Escape"===e.key){e.preventDefault(),td(!1);return}if(("Tab"===e.key||"Enter"===e.key&&!e.shiftKey)&&nw[tu]){e.preventDefault(),nE(nw[tu]);return}}if("ArrowUp"===e.key&&!l&&!i&&W.length>0&&0===ek.trim().length){e.preventDefault(),e6(!1),td(!1),tg(W.length-1),tm(!0);return}if("Escape"===e.key&&!l&&i&&t){e.preventDefault(),t();return}"Enter"!==e.key||e.shiftKey||(e.preventDefault(),i&&(n||a)?nL(n?"steer":"followup"):no())}},[i,n,a,t,e5,nc,nu,e3,nR,nL,no,nP,tc,tl,nw,tu,nE,tp,W,tf,n$,ek,tn,tt]),n_=(0,s.useCallback)(()=>{let e=tN.current;e&&(e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)},[]),nF=(0,s.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(),nt(t))},[nt]);(0,s.useEffect)(()=>{if(null===nc){e6(!1),e7(0),tz.current=!1;return}e6(!0),e7(0),!tz.current&&K&&(tz.current=!0,Promise.resolve(K()).catch(()=>{tz.current=!1}))},[nc,K]),(0,s.useEffect)(()=>{if(!e5||!ee)return;let e=!1;return tS({cwd:ee,values:{}}),fetch(`/api/skills?cwd=${encodeURIComponent(ee)}`).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;tS({cwd:ee,values:n})}).catch(()=>{e||tS({cwd:ee,values:{}})}),()=>{e=!0}},[e5,ee]),(0,s.useEffect)(()=>{e3>=nu.length&&e7(Math.max(0,nu.length-1))},[nu.length,e3]),(0,s.useEffect)(()=>{tD.current.length=nu.length},[nu.length]),(0,s.useEffect)(()=>{e5&&tD.current[e3]?.scrollIntoView({block:"nearest",inline:"nearest"})},[e3,e5]);let nO=u&&u.length>0?u.map(e=>({provider:e.provider,modelId:e.id,name:e.name})).sort(uK):Object.entries(d??{}).map(([e,t])=>({provider:o?.provider??"unknown",modelId:e,name:t})).sort(uK),nz=g??null,nD=rW.find(e=>e.alias===nz)?.provider??null,nW=nD?nO.filter(e=>e.provider===nD):nO,nH=(ed=eI.trim().toLocaleLowerCase())?nW.filter(e=>`${e.name} ${e.modelId}`.toLocaleLowerCase().includes(ed)):nW,nU=nW.length>8,nB=[];for(let e of nH){let t=nB.find(t=>t.provider===e.provider);t?t.options.push(e):nB.push({provider:e.provider,options:[e]})}let nq=nD?[]:(x??[]).filter(e=>!e.hidden&&e.resolved),nV=o?nq.find(e=>e.resolved?.provider===o.provider&&e.resolved?.modelId===o.modelId):void 0,nK=eI.trim()?[]:nW.map((e,t)=>{var n,r;return{option:e,order:t,count:eE[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})),nJ=(e,t,n)=>{let s=e.modelId===o?.modelId&&e.provider===o?.provider;return(0,r.jsxs)("button",{onClick:()=>{if(eC(!1),eM(""),!s||c){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}(u$(),(t=e.provider,n=e.modelId,`${t}/${n}`));try{window.localStorage.setItem(uE,JSON.stringify(r))}catch{}e$(r),m?.(e.provider,e.modelId)}},style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"7px 12px",background:s?"var(--bg-selected)":"none",border:"none",color:s?"var(--text)":"var(--text-muted)",cursor:"pointer",fontSize:12,textAlign:"left",fontWeight:s?600:400,whiteSpace:"nowrap"},onMouseEnter:e=>{s||(e.currentTarget.style.background="var(--bg-hover)")},onMouseLeave:e=>{s||(e.currentTarget.style.background="none")},children:[s?(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:ev("chat.modelPickCount",{count:n})})]},`${t}:${e.provider}:${e.modelId}`)},nG=o?nO.find(e=>e.modelId===o.modelId&&e.provider===o.provider)?.name??o.modelId:null,nY=S?Math.max(0,S.tokensBefore-S.estimatedTokensAfter):0,nZ=S?`${S.reason&&"manual"!==S.reason?`${S.reason[0].toUpperCase()}${S.reason.slice(1)} `:ev("chat.compacted")} ${ro(S.tokensBefore)} -> ${ro(S.estimatedTokensAfter)} tokens (${ev("chat.tokensSaved",{saved:ro(nY)})})`:null,nQ=e=>{let t=P?.[e];return null!=t&&t!==e?t:null},nX="auto"===(eu=T??"auto")?$?`auto ≤ ${nQ($)??$}`:"auto":P?P[eu]??eu:eu,n0=(T??"auto")==="auto"&&I&&"auto"!==I?P?.[I]??I:null,n1=R&&n0?ev("chat.currentReasoning",{level:n0}):null,n2=e=>!L||L.includes(e),n4=[{level:"auto",ceiling:null},...uG.filter(n2).map(e=>({level:"auto",ceiling:e})),...uJ.filter(e=>"auto"!==e&&n2(e)).map(e=>({level:e,ceiling:null}))],n8=Object.entries(uD).find(([,e])=>e===(C??"default"))?.[0]??"default";(0,s.useEffect)(()=>{let e=e=>{tT.current&&!tT.current.contains(e.target)&&tI.current&&!tI.current.contains(e.target)&&(eC(!1),eM("")),tM.current&&!tM.current.contains(e.target)&&tE.current&&!tE.current.contains(e.target)&&e_(!1),t$.current&&!t$.current.contains(e.target)&&eD(!1),tR.current&&!tR.current.contains(e.target)&&eH(!1),tL.current&&!tL.current.contains(e.target)&&eV(!1),!tP.current||tP.current.contains(e.target)||tN.current?.contains(e.target)||tm(!1)};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[]),(0,s.useEffect)(()=>{ew||eV(!1)},[ew]);let n5=(0,r.jsx)("button",{type:"button",className:`composer-icon-button${eK.length||eG.length?" is-active":""}`,onClick:()=>t_.current?.click(),title:ev("chat.attachFile"),"aria-label":ev("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:eK.length||eG.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=eK.length||eG.length?"var(--accent)":"var(--text)"},onMouseLeave:e=>{e.currentTarget.style.background="none",e.currentTarget.style.color=eK.length||eG.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"})]})}),n6=f&&rW.length>0?(0,r.jsxs)("div",{ref:tM,style:{position:"relative",flexShrink:+!!ew,minWidth:0},children:[(0,r.jsxs)("button",{className:`${ew?"composer-icon-button":"composer-chip"}${eA?" is-active":""}`,onClick:e=>{let t=e.currentTarget.getBoundingClientRect();eO({top:t.top,bottom:t.bottom,left:t.left,width:t.width}),eC(!1),eM(""),e_(e=>!e)},disabled:i||y,"aria-haspopup":"menu","aria-expanded":eA,onKeyDown:e=>{"Escape"===e.key&&eA&&(e.stopPropagation(),e_(!1))},style:{display:"flex",alignItems:"center",gap:6,maxWidth:"100%",padding:"4px 8px",background:eA?"var(--bg-hover)":"none",border:"none",borderRadius:"var(--radius-control)",color:"var(--text-muted)",cursor:i||y?"not-allowed":"pointer",fontSize:12,opacity:i?.5:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{i||y||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{e.currentTarget.style.background=eA?"var(--bg-hover)":"none",e.currentTarget.style.color="var(--text-muted)"},title:ev("chat.mainPreset"),"aria-label":ev("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"})}),ew?null:(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:ev("chat.mainPreset")})]}),eA&&eF&&(()=>{let e=window.visualViewport?.height??window.innerHeight,{side:t,maxHeight:n}=uR(eF.top,eF.bottom,e,uL(e,.6,460),{gap:6,prefer:"above"}),s="above"===t?{bottom:e-eF.top+6}:{top:eF.bottom+6},a=ew?{left:8,right:8,maxWidth:"calc(100vw - 16px)"}:{left:eF.left,width:"max-content",minWidth:eF.width};return(0,r.jsx)("div",{ref:tE,role:"menu","aria-label":ev("chat.mainPreset"),onKeyDown:e=>{"Escape"===e.key&&(e_(!1),tM.current?.querySelector("button")?.focus())},style:{position:"fixed",...s,...a,zIndex:500,background:"var(--bg-raised)",border:0,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:rW.map(e=>{let t=e.alias===nz;return(0,r.jsxs)("button",{role:"menuitemradio","aria-checked":t,onClick:()=>{e_(!1),f({alias:e.alias,provider:e.provider,modelId:e.model,...void 0!==e.oauthPosition?{oauthPosition:e.oauthPosition}:{}})},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:sr(e.seed),width:20,height:20,alt:"","aria-hidden":"true",draggable:!1}),(0,r.jsx)("span",{children:r5(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,n3=R?(0,r.jsxs)("div",{ref:tR,style:{position:"relative",flexShrink:0,minWidth:0},children:[(0,r.jsxs)("button",{type:"button",className:`${ew?"composer-icon-button":"composer-chip"}${eW?" is-active":""}`,onClick:e=>{let t=e.currentTarget.getBoundingClientRect();eB({top:t.top,bottom:t.bottom,left:t.left,width:t.width}),eC(!1),eM(""),e_(!1),eH(e=>!e)},disabled:i||y,"aria-haspopup":"menu","aria-expanded":eW,onKeyDown:e=>{"Escape"===e.key&&eW&&(e.stopPropagation(),eH(!1))},title:ev("chat.changeReasoning",{level:nX}),"aria-label":ev("chat.changeReasoning",{level:nX}),style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,padding:ew?0:"8px 12px",height:32,background:eW?"var(--bg-hover)":"none",border:"none",borderRadius:"var(--radius-control)",color:"var(--text-muted)",cursor:i||y?"not-allowed":"pointer",fontSize:12,opacity:i?.5:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{i||y||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{e.currentTarget.style.background=eW?"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"})]}),ew?null:(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:nX})]}),eW&&eU&&(()=>{let e=window.visualViewport?.height??window.innerHeight,{side:t,maxHeight:n}=uR(eU.top,eU.bottom,e,uL(e,.6,460),{gap:6,prefer:"above"}),s="above"===t?{bottom:e-eU.top+6}:{top:eU.bottom+6},a=ew?{left:8,right:8,maxWidth:"calc(100vw - 16px)"}:{left:eU.left,width:"max-content",minWidth:Math.max(180,eU.width)};return(0,r.jsx)("div",{role:"menu","aria-label":ev("chat.changeReasoningLabel"),onKeyDown:e=>{"Escape"===e.key&&(eH(!1),tR.current?.querySelector("button")?.focus())},style:{position:"fixed",...s,...a,zIndex:500,background:"var(--bg-raised)",border:0,borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s2)",overflowY:"auto",maxHeight:n},children:n4.map(({level:e,ceiling:t})=>{let n=(T??"auto")===e&&("auto"!==e||($??null)===t),s=t??e,a="auto"===e&&null===t?null:nQ(s),i=t?`auto ≤ ${a??t}`:a??e,l=t?ev("chat.thinkingAutoCapped",{level:a??t}):ev(uY[e]);return(0,r.jsxs)("button",{type:"button",role:"menuitemradio","aria-checked":n,onClick:()=>{eH(!1),R(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:[i,null!==a&&(0,r.jsxs)("span",{style:{fontSize:10,color:"var(--text-dim)",fontFamily:"var(--font-mono)",marginLeft:5},children:["(",s,")"]})]}),(0,r.jsx)("span",{style:{fontSize:11,color:"var(--text-dim)",marginLeft:8},children:l})]},t?`auto-${t}`:e)})})})()]}):null,n7=O?(eh=_?ev("chat.fastModeBusy"):null===A?ev("chat.fastModeUnknown"):A.active?ev("chat.fastModeActive"):A.enabled?ev("chat.fastModeInactive"):ev("chat.fastModeOff"),ep=_||i||y,em=A?.enabled===!0,(0,r.jsx)("button",{type:"button",className:`composer-icon-button${A?.active?" is-active":""}`,onClick:O,disabled:ep,"aria-pressed":null===A?void 0:A.enabled,"aria-busy":_||void 0,title:eh,"aria-label":eh,style:{flexShrink:0,opacity:i?.5:1},children:(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:A?.active?"var(--accent)":"none",stroke:em?"var(--accent)":"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",strokeDasharray:null===A?"3 2":void 0,style:{opacity:em&&!A?.active?.6:1},"aria-hidden":"true",children:(0,r.jsx)("path",{d:"M13 2 4 14h7l-1 8 9-12h-7l1-8z"})})})):null,n9=(0,r.jsxs)(r.Fragment,{children:[n&&(0,r.jsxs)("button",{className:"composer-stream-action is-warning",onClick:()=>nL("steer"),disabled:!nf,title:e0?ev("chat.attachExtractingWait"):ev("chat.steerTitle"),style:{display:"flex",alignItems:"center",gap:5,padding:"7px 12px",background:nf?"var(--warning-soft)":"var(--bg-hover)",border:0,borderRadius:"var(--radius-control)",color:nf?"var(--warning)":"var(--text-dim)",cursor:nf?"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"})]}),ev("chat.steer")]}),a&&(0,r.jsxs)("button",{className:"composer-stream-action is-followup",onClick:()=>nL("followup"),disabled:!nf,title:e0?ev("chat.attachExtractingWait"):ev("chat.followUpTitle"),style:{display:"flex",alignItems:"center",gap:5,padding:"7px 12px",background:nf?"var(--bg-selected)":"var(--bg-hover)",border:0,borderRadius:"var(--radius-control)",color:nf?"var(--text)":"var(--text-dim)",cursor:nf?"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"})]}),ev("chat.followUp")]})]}),re=void 0!==Y?(0,r.jsx)(d_,{soundEnabled:G??!0,onToggle:Y}):null;return(0,r.jsxs)("div",{className:"chat-composer",style:{flexShrink:0,background:"transparent",padding:"0 16px 8px"},children:[(0,r.jsx)("input",{ref:t_,type:"file",multiple:!0,style:{display:"none"},onChange:e=>{nt(Array.from(e.target.files??[])),e.target.value=""}}),(0,r.jsxs)("div",{className:"chat-column-cap",style:{maxWidth:"var(--reading-measure)",margin:"0 auto"},children:[(0,r.jsx)(hl,{error:h}),(0,r.jsx)(ho,{warnings:p}),ei,D.length>0&&(0,r.jsxs)("div",{style:{marginBottom:8,border:0,borderRadius:"var(--radius-control)",background:"var(--bg-subtle)",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:12,fontWeight:600,color:"var(--text-muted)"},children:ey("delivery.title",{count:D.length})}),H&&eb&&(0,r.jsxs)("button",{onClick:H,title:ev("chat.recallTitle"),style:{display:"flex",alignItems:"center",gap:6,padding:"4px 12px",fontSize:12,color:"var(--text)",background:"var(--bg-hover)",border:0,borderRadius:"var(--radius-control)",cursor:"pointer",transition:"background 0.12s",whiteSpace:"nowrap"},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",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"})]}),ev("chat.recall")]})]}),(0,r.jsx)(d$,{rows:D,removeLabel:ev("chat.queueRemove"),onRemove:B?(e,t)=>B("steer"===e?"steering":"followUp",t):void 0})]}),z&&(0,r.jsxs)("div",{style:{marginBottom:8,padding:"5px 10px",background:"var(--warning-soft)",border:0,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"})]}),ev("chat.retrying",{attempt:z.attempt,max:z.maxAttempts}),z.errorMessage&&(0,r.jsxs)("span",{style:{opacity:.7,marginLeft:4},children:["— ",z.errorMessage]})]}),nZ&&(0,r.jsxs)("div",{style:{marginBottom:8,padding:"5px 10px",background:"var(--success-soft)",border:0,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"})}),nZ]}),j&&(0,r.jsx)("div",{role:"alert",style:{marginBottom:8,padding:"7px 10px",background:"var(--danger-soft)",border:0,borderRadius:"var(--radius-control)",color:"var(--danger)",fontFamily:"var(--font-mono)",fontSize:12,lineHeight:1.5,whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:j}),eZ&&(0,r.jsxs)("div",{role:"alert",style:{display:"flex",alignItems:"center",gap:8,marginBottom:8,padding:"7px 10px",background:"var(--danger-soft)",border:0,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:eZ}),(0,r.jsx)("button",{type:"button",onClick:()=>eQ(null),"aria-label":ev("i18n.close"),title:ev("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"})]})})]}),(eK.length>0||eG.length>0)&&(0,r.jsxs)("div",{role:"list","aria-label":ev("chat.attachments"),style:{display:"flex",alignItems:"center",gap:6,marginBottom:6,flexWrap:"wrap"},children:[eK.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)",display:"block"}}),(0,r.jsx)("button",{type:"button","aria-label":ev("chat.removeImage",{index:t+1}),onClick:()=>nn(t),style:{position:"absolute",top:-4,right:-4,width:16,height:16,borderRadius:"50%",background:"var(--bg-raised)",border:0,boxShadow:"var(--shadow-float)",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}`)),eG.map(e=>(0,r.jsxs)("div",{className:"composer-chip",role:"listitem","aria-busy":"ready"!==e.status||uO(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",className:"workbench-lamp",style:{animation:"lamp-breathe 1.2s ease-in-out infinite"}}):sY(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?ev("chat.attachKindAudio"):"file"===e.stored?ev("chat.attachKindFile"):uV[e.mimeType]," \xb7 ",as(e.sourceSize??e.size),"extracting"===e.status?` \xb7 ${ev("chat.attachExtracting")}`:"","uploading"===e.status?` \xb7 ${ev("chat.attachUploading")}`:"",e.transcription?.state==="planning"?` \xb7 ${ev("chat.transcribeChecking")}`:"",e.transcription?.state==="confirm"?` \xb7 ${ev("chat.attachTranscribePending")}`:"",e.transcription?.state==="running"?` \xb7 ${ev("chat.attachTranscribing")}`:"",e.transcription?.state==="failed"&&(0,r.jsx)("span",{style:{color:"var(--danger)"},children:` \xb7 ${ev("chat.attachTranscribeFailed")}`})]})]}),(0,r.jsx)("button",{type:"button",onClick:()=>nr(e.id),"aria-label":ev("chat.removeAttachment",{name:e.name}),title:ev("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))]}),e1.length>0&&(0,r.jsx)("div",{role:"group","aria-label":ev("chat.transcribeGroup"),"aria-live":"polite",style:{display:"flex",flexDirection:"column",gap:6,marginBottom:6},children:e1.map(e=>{let t,n,s,a,i=e.attachmentId,o=e.transcription,c=o?.state==="confirm"||o?.state==="running"?o.plan:null,d=c?ev("chat.transcribePlanSummary",{duration:null===c.durationSeconds?ev("chat.transcribeDurationUnknown"):(n=Math.floor((t=Math.round(c.durationSeconds))/3600),s=Math.floor(t%3600/60),a=String(t%60).padStart(2,"0"),n>0?`${n}:${String(s).padStart(2,"0")}:${a}`:`${s}:${a}`),calls:c.estimatedCalls}):null,u=o?.state==="confirm"?ev("chat.transcribeConfirmTitle",{name:e.name}):o?.state==="running"?ev("chat.transcribeRunning",{name:e.name}):o?.state==="planning"?`${e.name} \xb7 ${ev("chat.transcribeChecking")}`:o?.state==="failed"?ev("chat.transcribeFailedRow",{name:e.name,error:o.error}):ev("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:0,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}),d&&(0,r.jsx)("div",{style:{color:"var(--text-dim)",fontVariantNumeric:"tabular-nums"},children:d}),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:ev("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)(l.r,{type:"button",variant:"neutralSolid",size:"small",onClick:()=>void t6(i,!0),children:ev("chat.transcribeStart")}),(0,r.jsx)(l.r,{type:"button",variant:"neutralWeak",size:"small",onClick:()=>t9(i),children:ev("chat.transcribeSkip")})]}),(o?.state==="planning"||o?.state==="running")&&(0,r.jsx)(l.r,{type:"button",variant:"neutralWeak",size:"small",onClick:()=>t9(i),children:ev("chat.transcribeCancel")}),(void 0===o||"skipped"===o.state||"failed"===o.state)&&(0,r.jsx)(l.r,{type:"button",variant:"neutralWeak",size:"small",onClick:()=>void t7(i),children:ev(o?.state==="failed"?"chat.transcribeRetry":"chat.transcribeAction")})]})]},e.id)})}),(0,r.jsxs)("div",{ref:tA,style:{position:"relative",minWidth:0},children:[tp&&W.length>0&&(0,r.jsxs)("div",{ref:tP,style:{position:"absolute",left:0,right:0,...uU(nS.side),zIndex:120,background:"var(--bg-raised)",border:0,borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s3)",overflow:"hidden",maxHeight:nS.maxHeight},children:[(0,r.jsx)("div",{title:"Input history",style:{height:30,padding:"0 10px",background:"var(--bg-subtle)",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,nS.maxHeight-31),overflowY:"auto",padding:4},children:W.map((e,t)=>{let n=t===tf;return(0,r.jsxs)("button",{ref:e=>{tH.current[t]=e},type:"button",onMouseDown:t=>{t.preventDefault(),n$(e)},onMouseEnter:()=>tg(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}`)})})]}),ts&&(0,r.jsx)("div",{role:"status",style:{fontSize:12,color:"var(--text-dim)",padding:"4px 8px"},children:ev("savedPrompts.saved")}),tn&&tt&&(0,r.jsx)(dL,{ref:ti,value:ek,token:tt,cwd:ee,sessionTitle:et,style:uU(nT.side),maxHeight:nT.maxHeight,onReplace:nM,onClose:()=>tr(!1)}),e5&&null!==nc&&(0,r.jsxs)("div",{style:{position:"absolute",left:0,right:0,...uU(nC.side),zIndex:120,background:"var(--bg-raised)",border:0,borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s3)",overflow:"hidden",maxHeight:nC.maxHeight},children:[(0,r.jsxs)("div",{style:{padding:"8px 10px",background:"var(--bg-subtle)",display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,fontSize:11,color:"var(--text-dim)"},children:[(0,r.jsx)("span",{children:V?ev("chat.loadingCommands"):ev("chat.slashCommands",{label:np})}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},children:ev("chat.tabEnter")})]}),(0,r.jsx)("div",{style:{maxHeight:Math.max(0,nC.maxHeight-34),overflowY:"auto",padding:10},children:V||0!==nd.length?nh.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:ev(uX[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===e3,s=u4(e,tC);return(0,r.jsxs)("button",{ref:e=>{tD.current[t]=e},type:"button",onMouseDown:t=>{t.preventDefault(),nR(e)},onMouseEnter:()=>e7(t),style:{width:"100%",minWidth:0,minHeight:58,display:"flex",flexDirection:"column",gap:4,justifyContent:"center",padding:"9px 10px",border:0,borderRadius:"var(--radius-control)",background:n?"var(--bg-selected)":"var(--bg-subtle)",color:"var(--text)",cursor:"pointer",textAlign:"left"},children:[(0,r.jsxs)("span",{style:{fontSize:13,fontFamily:"var(--font-mono)",overflowWrap:"anywhere",wordBreak:"break-word",color:s?"var(--text-dim)":void 0},children:["/",e.name,s&&(0,r.jsx)("span",{style:{marginLeft:6,padding:"0 4px",background:"var(--bg-hover)",borderRadius:"var(--radius-control)",fontSize:9,color:"var(--text-dim)",whiteSpace:"nowrap"},children:ev("chat.dormant")})]}),u2(e,ev)&&(0,r.jsx)("span",{style:{display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:2,overflow:"hidden",fontSize:11,lineHeight:1.35,color:"var(--text-dim)"},children:u2(e,ev)})]},`${e.source}:${e.name}`)})})]},e.source)):(0,r.jsx)("div",{style:{padding:"2px 2px 4px",fontSize:12,color:"var(--text-dim)"},children:ev("chat.noCommands")})})]}),tc&&null!==tl&&(ef=ty&&(!tx||tx.cwd!==ee),eg=1===nw.length?ev("chat.match"):ev("chat.matches",{count:nw.length}),ex=tx?.truncated&&!nb?tl.query?ev("chat.searchingAll"):ev("chat.indexTruncated"):"",(0,r.jsxs)("div",{style:{position:"absolute",left:0,right:0,...uU(nN.side),zIndex:120,background:"var(--bg-raised)",border:0,borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s3)",overflow:"hidden",maxHeight:nN.maxHeight},children:[(0,r.jsxs)("div",{style:{padding:"8px 10px",background:"var(--bg-subtle)",display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,fontSize:11,color:"var(--text-dim)"},children:[(0,r.jsx)("span",{children:ef?ev("chat.loadingFiles"):ev("chat.files",{label:eg,hint:ex})}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},children:ev("chat.tabEnter")})]}),(0,r.jsx)("div",{style:{maxHeight:Math.max(0,nN.maxHeight-34),overflowY:"auto",padding:4},children:ef||0!==nw.length?nw.map((e,t)=>{let n=t===tu,s=e.path.split("/").pop()??e.path,a=e.path.slice(0,e.path.length-s.length);return(0,r.jsxs)("button",{ref:e=>{tW.current[t]=e},type:"button",onMouseDown:t=>{t.preventDefault(),nE(e)},onMouseEnter:()=>th(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)(sK,{size:14}):sY(s,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}),s,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:ny&&!nb?ev("chat.searching"):ev("chat.noMatchingFiles")})})]})),ea,(0,r.jsxs)("div",{className:`chat-composer-field${e4?" is-bash":""}${i?" is-streaming":""}`,style:{minWidth:0,display:"flex",gap:8,alignItems:"center",background:"var(--bg)",border:0,borderRadius:"var(--seed-radius-r3)",padding:"10px 10px 10px 14px",transition:"background 0.15s"},children:[(0,r.jsx)("textarea",{className:"chat-composer-textarea",ref:tN,"aria-controls":tn?"saved-prompt-menu":void 0,value:ek,onChange:e=>{tV.current=e.target.value,ej(e.target.value),tm(!1),ng(e.target.value,e.target.selectionStart)},onSelect:e=>{let t=e.currentTarget;ng(t.value,t.selectionStart)},onKeyDown:nA,onCompositionStart:()=>{tF.current=!0},onCompositionEnd:e=>{tF.current=!1,tO.current=Date.now();let t=e.currentTarget;ng(t.value,t.selectionStart)},onInput:n_,onPaste:nF,placeholder:i&&(n||a)?ev("chat.steerPlaceholder"):i?ev("chat.agentPlaceholder"):ev("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"}}),i?ew?null:(0,r.jsx)("div",{style:{display:"flex",alignItems:"center",gap:6,flexShrink:0,alignSelf:"flex-end"},children:n9}):(0,r.jsxs)("button",{className:"chat-composer-send",onClick:no,disabled:!nf,"aria-busy":e0||void 0,"aria-label":ew?ev("chat.send"):void 0,title:e0?ev("chat.attachExtractingWait"):void 0,style:{flexShrink:0,alignSelf:"flex-end",display:"flex",alignItems:"center",justifyContent:"center",gap:6,minWidth:ew?44:void 0,padding:ew?0:"7px 14px",background:nf?"var(--accent-soft)":"var(--bg-raised)",border:"none",borderRadius:"var(--radius-control)",color:nf?"var(--accent-hover)":"var(--text-dim)",cursor:nf?"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"})]}),ew?null:ev("chat.send")]})]})]}),e4&&(0,r.jsxs)("div",{className:"text-xs px-2 py-1",style:{color:e8?"var(--text-muted)":"var(--accent)",marginTop:4},children:[ev("chat.shell")," \xb7 ",e8?ev("chat.outputLocal"):ev("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:ew?"1 1 0%":"0 0 auto",minWidth:ew?"min-content":0,display:"flex",alignItems:"center",gap:2},children:[(!ew||!i)&&n5,!ew&&n6,!(ew&&i)&&(nO.length>0||nG||h)&&m&&(0,r.jsxs)("div",{ref:tT,style:{position:"relative",flex:ew?"1 1 0%":void 0,width:ew?0:void 0,minWidth:44*!!ew},children:[(0,r.jsxs)("button",{className:`composer-chip${eS?" is-active":""}`,onClick:e=>{let t=e.currentTarget.getBoundingClientRect();eT({top:t.top,bottom:t.bottom,left:t.left,width:t.width}),eC(e=>(e&&eM(""),!e))},disabled:i||y,"aria-busy":y||void 0,style:{display:"flex",alignItems:"center",gap:6,justifyContent:ew?"flex-start":void 0,padding:ew?"8px 10px":"8px 12px",height:32,width:ew?"100%":void 0,maxWidth:ew?"100%":220,overflow:"hidden",background:eS?"var(--bg-hover)":"none",border:"none",borderRadius:"var(--radius-control)",color:"var(--text-muted)",cursor:i||y?"not-allowed":"pointer",fontSize:12,opacity:i?.5:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{i||y||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{e.currentTarget.style.background=eS?"var(--bg-hover)":"none",e.currentTarget.style.color="var(--text-muted)"},title:y?"Switching model":nO.length>0?"Change model":"No available models",children:[y?(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:nG??(nO.length>0?"Select model":"No models")})]}),eS&&eN&&(()=>{let e=window.visualViewport?.height??window.innerHeight,{side:t,maxHeight:n}=uR(eN.top,eN.bottom,e,uL(e,.6,460),{gap:6,prefer:"above"}),s="above"===t?{bottom:e-eN.top+6}:{top:eN.bottom+6},a=ew?{left:8,right:8,maxWidth:"calc(100vw - 16px)"}:{left:eN.left,width:"max-content",minWidth:eN.width};return(0,r.jsxs)("div",{ref:tI,style:{position:"fixed",...s,...a,zIndex:500,background:"var(--bg-raised)",border:0,borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s2)",overflow:"hidden",maxHeight:n,display:"flex",flexDirection:"column"},children:[nU&&(0,r.jsx)("div",{style:{padding:"6px 8px",flexShrink:0},children:(0,r.jsx)("input",{value:eI,onChange:e=>eM(e.target.value),onKeyDown:e=>{"Escape"===e.key&&(eM(""),eC(!1))},placeholder:ev("chat.filterModels"),"aria-label":ev("chat.filterModels"),autoFocus:!0,autoComplete:"off",spellCheck:!1,style:{width:"100%",minWidth:220*!ew,fontSize:11,fontFamily:"var(--font-mono)",padding:"5px 8px",border:0,borderRadius:"var(--radius-control)",outline:"none",background:"var(--bg)",color:"var(--text)",boxSizing:"border-box"}})}),(0,r.jsxs)("div",{style:{minHeight:0,overflowY:"auto"},children:[nK.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:ev("chat.frequentModels")}),nK.map(({option:e,count:t})=>nJ(e,"frequent",t))]}),nq.length>0&&!eI.trim()&&v&&(0,r.jsxs)("div",{style:{marginTop:6*(nK.length>0)},children:[(0,r.jsxs)("button",{type:"button",className:"model-role-disclosure","aria-expanded":eR,"aria-controls":"model-role-rows",onClick:eP,style:{display:"flex",alignItems:"center",gap:6,width:"100%",minHeight:32,padding:"6px 12px 4px",background:"none",border:"none",cursor:"pointer",textAlign:"left",fontSize:10,fontWeight:600,color:"var(--text-dim)",letterSpacing:"0.07em",whiteSpace:"nowrap"},children:[(0,r.jsx)("svg",{width:"8",height:"8",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0,transform:eR?"rotate(90deg)":"none",transition:"transform 120ms"},children:(0,r.jsx)("polyline",{points:"3 1.5 7 5 3 8.5"})}),(0,r.jsx)("span",{style:{textTransform:"uppercase"},children:ev("chat.modelRoles")}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},children:nq.length}),nV&&(0,r.jsxs)("span",{style:{marginLeft:"auto",overflow:"hidden",textOverflow:"ellipsis",color:"var(--text-muted)",letterSpacing:0},children:[(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)",color:"var(--accent)",marginRight:6},children:nV.tag??nV.role.toUpperCase()}),nV.name]})]}),(0,r.jsx)("div",{id:"model-role-rows",hidden:!eR,children:nq.map(e=>{let t=nV?.role===e.role,n=e.resolved?.name??e.resolved?.modelId??"";return(0,r.jsxs)("button",{onClick:()=>{eC(!1),eM(""),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:"var(--radius-control)",border:0,background:"var(--bg-hover)",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:11,fontWeight:600,color:"var(--text-muted)",marginTop:4},children:ev("chat.allModels")})]}),0===nB.length?(0,r.jsx)("div",{style:{padding:"8px 12px",color:"var(--text-dim)",fontSize:12,whiteSpace:"nowrap"},children:eI.trim()?ev("chat.noMatchingModels"):"No available models"}):nB.map((e,t)=>(0,r.jsxs)("div",{children:[nB.length>1&&(0,r.jsx)("div",{style:{padding:"6px 12px 4px",fontSize:10,fontWeight:600,color:"var(--text-dim)",textTransform:"uppercase",letterSpacing:"0.07em",marginTop:6*(t>0)},children:e.provider}),e.options.map(e=>nJ(e,"all"))]},e.provider))]})]})})()]}),ew&&i&&(0,r.jsx)("div",{style:{display:"flex",alignItems:"center",gap:6,minWidth:0},children:n9}),!ew&&n3,!ew&&n7,!ew&&n1&&(0,r.jsx)("span",{style:{flexShrink:0,padding:"0 6px",fontSize:12,color:"var(--text-muted)",whiteSpace:"nowrap"},children:n1}),!ew&&null!==M&&(0,r.jsx)("span",{title:ev(E?"chat.outputSpeedLiveTitle":"chat.outputSpeedTitle"),style:{flexShrink:0,padding:"0 6px",fontSize:12,color:"var(--text-muted)",whiteSpace:"nowrap",fontVariantNumeric:"tabular-nums"},children:ev(E?"chat.outputSpeedLive":"chat.outputSpeed",{rate:M>=10?Math.round(M):M.toFixed(1)})}),(0,r.jsx)(dK,{sessionId:en})]}),(0,r.jsxs)("div",{ref:tL,style:{flex:"0 1 auto",minWidth:0,display:"flex",alignItems:"center",justifyContent:"flex-end",position:"relative",marginLeft:"auto",gap:ew?4:2},children:[ew?(0,r.jsx)("button",{type:"button",className:`composer-icon-button${eq?" is-active":""}`,title:ev("chat.moreControls"),"aria-label":ev("chat.moreControls"),"aria-expanded":eq,onClick:()=>{eC(!1),eM(""),eV(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)(l.r,{type:"button",variant:"neutralWeak",size:"small",layout:"withText",title:eq?void 0:ev("chat.moreControls"),"aria-label":ev("chat.moreControls"),"aria-expanded":eq,onClick:()=>{eC(!1),eM(""),eV(e=>!e)},children:ev("chat.moreControls")}),(0,r.jsxs)("div",{className:"composer-run-options",role:"group","aria-label":ev("chat.moreControls"),style:{display:eq?ew?"grid":"flex":"none",gridTemplateColumns:ew?"repeat(3, minmax(0, max-content))":void 0,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:0,borderRadius:"var(--seed-radius-r2)",background:"var(--bg-raised)",boxShadow:"var(--seed-shadow-s2)"},children:[ew&&(0,r.jsxs)(r.Fragment,{children:[i&&n5,n6,n3,n7]}),!i&&N&&(0,r.jsxs)("div",{ref:t$,style:{position:"relative"},children:[(0,r.jsxs)("button",{className:`composer-chip${ez?" is-active":""}`,onClick:()=>!i&&eD(e=>!e),disabled:i,title:ev("chat.changeToolPreset")+`: ${n8}`,"aria-label":ev("chat.changeToolPreset"),style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,padding:"8px 12px",height:32,background:ez?"var(--bg-hover)":"none",border:"none",borderRadius:"var(--radius-control)",color:"var(--text-muted)",cursor:i?"not-allowed":"pointer",fontSize:12,opacity:i?.5:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{i||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text)")},onMouseLeave:e=>{e.currentTarget.style.background=ez?"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:n8})]}),ez&&(0,r.jsx)("div",{style:{position:"absolute",bottom:"calc(100% + 6px)",right:0,zIndex:100,background:"var(--bg-raised)",border:0,borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s2)",overflow:"hidden",minWidth:120},children:uz.map(e=>{let t=uD[e],n=(C??"default")===t,s="off"===e?ev("chat.noTools"):"default"===e?ev("chat.builtInTools",{tools:uW}):ev("chat.allBuiltInTools",{tools:`${uW} + ${uH}`});return(0,r.jsxs)("button",{onClick:()=>{eD(!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:s})]},e)})})]}),!i&&b&&(0,r.jsx)("div",{children:(0,r.jsx)("button",{className:`composer-chip${k?" is-active is-danger":""}`,onClick:k?w:b,disabled:i&&!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:i&&!k?"not-allowed":"pointer",fontSize:12,opacity:i&&!k?.5:1,transition:"background 0.12s, color 0.12s"},onMouseEnter:e=>{(!i||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?ev("chat.stopCompaction"):ev("chat.compactContext"),"aria-label":k?ev("chat.stopCompaction"):ev("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:ev("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:ev("chat.compact")})]})})}),ew&&re,eq&&!ew&&(0,r.jsx)("button",{className:"composer-icon-button is-active",type:"button",title:ev("chat.collapseControls"),"aria-label":ev("chat.collapseControls"),"aria-expanded":!0,onClick:()=>{eD(!1),eH(!1),eV(!1)},style:{display:"flex",alignItems:"center",justifyContent:"center",width:36,height:32,padding:0,marginLeft:0,background:"var(--bg-hover)",border:"none",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"})]})})]}),i&&(0,r.jsxs)("button",{className:"composer-chip is-danger is-active",onClick:t,title:ev("chat.stopAgent"),"aria-label":ew?ev("chat.stopAgent"):void 0,style:{display:"flex",alignItems:"center",justifyContent:"center",gap:6,minWidth:ew?44:void 0,padding:ew?0:"8px 14px",height:32,background:"var(--danger-soft)",border:0,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"})}),ew?null:ev("chat.stop")]}),(0,r.jsx)(dq,{sessionId:en,onEnsureSession:er,onTranscriptPersisted:es}),!ew&&re]})]})]})]})});function hd({cwd:e,projects:t,onChoose:n}){let{t:a}=(0,F.s)(),[i,l]=(0,s.useState)(null);(0,s.useEffect)(()=>{let t=new AbortController;return fetch(`/api/git/summary?cwd=${encodeURIComponent(e)}`,{signal:t.signal}).then(e=>e.ok?e.json():null).then(t=>{l({cwd:e,label:t?.isGitRepository===!0?!0===t.detached?a("projectOverview.detachedHead"):"string"==typeof t.branch?t.branch:null:null})}).catch(()=>{}),()=>t.abort()},[e,a]);let c=tK(e)||e,d=i?.cwd===e?i.label:null;return(0,r.jsxs)("div",{className:"composer-start-place",children:[(0,r.jsx)("span",{className:"composer-start-place-label",children:a("composer.startIn")}),(0,r.jsxs)(o.k.Root,{placement:"top-start",strategy:"fixed",children:[(0,r.jsx)(o.k.Trigger,{asChild:!0,children:(0,r.jsxs)("button",{type:"button",className:"composer-start-place-project",title:e,"aria-label":a("composer.chooseProject",{name:c}),children:[(0,r.jsx)("span",{children:c}),(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:(0,r.jsx)("path",{d:"m6 9 6 6 6-6"})})]})}),(0,r.jsx)(o.k.Positioner,{children:(0,r.jsx)(o.k.Content,{"aria-label":a("composer.startIn"),children:(0,r.jsx)(o.k.ScrollArea,{children:(0,r.jsx)(o.k.Group,{children:t.map(t=>(0,r.jsx)(o.k.Item,{role:"menuitemradio","aria-checked":t.path===e,onClick:()=>{t.path!==e&&n(t.path)},children:(0,r.jsxs)(o.k.ItemBody,{children:[(0,r.jsx)(o.k.ItemLabel,{children:t.name}),(0,r.jsx)(o.k.ItemDescription,{children:t.path})]})},t.path))})})})})]}),d&&(0,r.jsxs)("span",{className:"composer-start-place-branch",title:a("projectOverview.branch"),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)("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",{children:d})]})]})}function hu({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=eH(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",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:eK(t).map((e,t)=>(0,r.jsx)("span",{style:e.style,children:e.text},t))})})}function hh({phases:e,flow:t,busy:n}){let{t:a}=(0,F.s)(),{st:i}=sz(),[l,o]=(0,s.useState)(!1),[c,d]=(0,s.useState)(!1),[u,h]=(0,s.useState)(!1),p=(0,s.useId)(),m=e??[],{currentPhase:f,activeTask:g,remaining:x,completed:v,total:y,percent:b}=tB(m),w=m.some(e=>e.tasks.some(e=>e.dependsOn?.length)),k=t.steps.length>0,j=function(e,t,n){if(!t||!e.current)return null;let r=n("flow.strip.running",{stage:n(`flow.stage.${e.current}`)});return e.attempt>1?`${r} \xb7 ${n("flow.attempt",{attempt:e.attempt})}`:r}(t,n,i);if(0===y&&null===j)return null;let S=y>0&&0===x;return(0,r.jsxs)("div",{className:`todo-strip${S?" is-done":""}`,children:[(0,r.jsxs)("div",{className:"todo-strip-row",children:[(0,r.jsx)("span",{"aria-hidden":"true",className:"todo-strip-marker",children:S?"✓":"›"}),j&&(0,r.jsx)("span",{className:"todo-strip-lead",role:n?"status":void 0,children:j}),y>0&&(0,r.jsxs)("button",{type:"button",className:"todo-strip-summary","aria-expanded":l,onClick:()=>o(e=>!e),children:[!j&&f&&(0,r.jsx)("span",{className:"todo-strip-phase",children:f.name}),(0,r.jsx)("span",{className:"todo-strip-task",children:S?a("todo.allDone",{count:v}):g?.content??""}),(0,r.jsx)("span",{className:"todo-strip-count",children:S?a("todo.progressDone",{percent:b??0,completed:v,total:y}):a("todo.progress",{percent:b??0,completed:v,total:y,remaining:x})})]}),k&&(0,r.jsxs)("button",{type:"button",className:"todo-strip-flow-toggle","aria-expanded":c,"aria-controls":p,onClick:()=>d(e=>!e),children:[i("flow.toggle"),(0,r.jsx)("svg",{className:"flow-chevron",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)("polyline",{points:"6 9 12 15 18 9"})})]})]}),c&&k&&(0,r.jsx)(oX,{flow:t,live:n,st:i,id:p}),l&&y>0&&(0,r.jsxs)("div",{className:"todo-strip-body",children:[m.map((e,t)=>{let n=e.tasks.filter(e=>u||"completed"!==e.status);return 0===n.length?null:(0,r.jsxs)("div",{className:"todo-checklist-phase",role:"list",children:[m.length>1&&(0,r.jsx)("div",{className:"todo-checklist-phase-name",children:e.name}),n.map((e,t)=>(0,r.jsx)(sB,{task:e,phases:w?m:void 0},`${e.content}-${t}`))]},`${e.name}-${t}`)}),v>0&&(0,r.jsx)("button",{type:"button",className:"todo-strip-completed-toggle","aria-expanded":u,onClick:()=>h(e=>!e),children:a(u?"todo.hideCompleted":"todo.showCompleted",{count:v})})]})]})}function hp(e=document){return"visible"!==e.visibilityState||!e.hasFocus()}function hm(e){switch(e.method){case"select":case"confirm":case"input":case"editor":case"ask":case"form":case"plan_review":return!0;case"custom":return!0!==e.closed;default:return!1}}async function hf(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}}class hg extends Error{constructor(e,t,n,r){super(e),this.status=t,this.code=n,this.accepted=r,this.name="AgentCommandError"}}async function hx(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 hg(r.error??`HTTP ${n.status}`,n.status,r.code,r.accepted);return r.data}let hv="ompweb-update-client-id",hy="ompweb-update-resume-intent-v2",hb="ompweb-update-return-v1",hw="cuelo-restart-return-v1",hk="ompweb-update-failure-return-v1",hj="ompweb:update-wake";function hS(e){return null===e?2e4:"running"===e?null:"failed"===e?3e4:8e3}function hC(){let e=sessionStorage.getItem(hv);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(hv,t),t}function hN(){sessionStorage.removeItem(hy)}function hT(){let e=sessionStorage.getItem(hb);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 hI(e){let t=hT();if(!t||t.requestId!==e)return t;let n={...t,dismissed:!0};try{sessionStorage.setItem(hb,JSON.stringify(n))}catch{}return n}async function hM(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:hC(),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 hE(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=hT();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(hb,JSON.stringify(n))}catch{}}({requestId:e.requestId,stageHash:e.stageHash}),hN();let r=n?.wake;e.sessionId&&(r?.wake===!0||r?.reason==="already-claimed"||r?.reason==="user-already-active")&&window.dispatchEvent(new CustomEvent(hj,{detail:{sessionId:e.sessionId}}))}async function h$(e){let t=function(e){let t=sessionStorage.getItem(hk);if(!t)return null;sessionStorage.removeItem(hk);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?(hN(),t.wake&&e.sessionId&&window.dispatchEvent(new CustomEvent(hj,{detail:{sessionId:e.sessionId}})),"failed"):(await hE(e),"resumed")}function hR(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 hL(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 hP(e){return{steering:e?.steering??[],followUp:e?.followUp??[]}}function hA(e){if(e&&"boolean"==typeof e.fastModeEnabled)return{enabled:e.fastModeEnabled,active:!0===e.fastModeActive}}function h_(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 hF(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],s=t[n];if(!r||!s||r.name!==s.name||r.tasks.length!==s.tasks.length)return!1;for(let e=0;e<r.tasks.length;e+=1){let t=r.tasks[e],n=s.tasks[e];if(!t||!n||t.content!==n.content||t.status!==n.status||t.blocker!==n.blocker||(t.dependsOn?.length??0)!==(n.dependsOn?.length??0)||t.dependsOn?.some((e,t)=>e!==n.dependsOn?.[t]))return!1}}return!0}function hO(e){return"aborted"===e.stopReason?"aborted":"error"===e.stopReason||e.errorMessage?"failed":e.stopReason?"completed":"unknown"}function hz(e,t){for(let n=e.length-1;n>=0;n--){let r=t[n]??null;if(!tm(r??void 0))return{message:e[n],entryId:r}}return null}let hD=new Set(["ArrowUp","ArrowDown","PageUp","PageDown","Home","End"," ","Space","Spacebar"]);class hW 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 hH(){return"u">typeof crypto&&"function"==typeof crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2)}`}function hU(e){return new Promise(t=>setTimeout(t,e))}function hB(e){let t=e.findIndex(e=>!e.exiting);return -1===t?e:e.map((e,n)=>n===t?{...e,exiting:!0}:e)}function hq(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:hB(e.visible),pending:[...e.pending,t.notice]};return{...e,visible:[...e.visible,t.notice]};case"mark_oldest_exiting":return{...e,visible:hB(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=hB(n)),{visible:n,pending:r}}(e.visible.filter(e=>e.id!==t.id),e.pending);default:return e}}function hV(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 hK(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(hV).filter(Boolean)}):JSON.stringify({text:"",images:[]})}function hJ(e){return"user"===e.role?`user:${hK(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 hG(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 hY(e){return e?.map(({data:e,mimeType:t})=>({data:e,mimeType:t}))}function hZ(e){n1(e),e.clear()}function hQ(e,t,n){for(let r of n??[]){let n=n0(t,r);n&&e.add(n)}}function hX(){let e=document.activeElement;return e instanceof HTMLElement&&(e.isContentEditable||"INPUT"===e.tagName||"SELECT"===e.tagName||"TEXTAREA"===e.tagName)}let h0=!1,h1={width:0,height:0},h2=new Set,h4=null;function h8(){let e=window.visualViewport,t=hX();h1.width!==window.innerWidth?h1={width:window.innerWidth,height:window.innerHeight}:t||(h1.height=Math.max(h1.height,window.innerHeight));let n=function({hasFocusedEditable:e,innerHeight:t,viewportHeight:n,viewportScale:r,baselineHeight:s}){return!(!e||Math.abs(r-1)>=.01)&&(t-n>120||s-t>120)}({hasFocusedEditable:t,innerHeight:window.innerHeight,viewportHeight:e?.height??window.innerHeight,viewportScale:e?.scale??1,baselineHeight:h1.height});if(n!==h0)for(let e of(h0=n,h2))e()}function h5(e){if(h2.add(e),!h4){let e=null,t=()=>{null!==e&&window.cancelAnimationFrame(e),e=window.requestAnimationFrame(()=>{e=null,h8()})},n=window.visualViewport;n?.addEventListener("resize",t),window.addEventListener("resize",t),window.addEventListener("focusin",t),window.addEventListener("focusout",t),h8(),h4=()=>{n?.removeEventListener("resize",t),window.removeEventListener("resize",t),window.removeEventListener("focusin",t),window.removeEventListener("focusout",t),null!==e&&window.cancelAnimationFrame(e)}}return()=>{h2.delete(e),0===h2.size&&h4&&(h4(),h4=null)}}function h6(){return(0,s.useSyncExternalStore)(h5,()=>h0,()=>!1)}let h3={count:50,end:null};function h7(e,t){let n=Math.max(e,0),r=null===t.end?n:Math.min(Math.max(t.end,0),n),s=Math.min(Math.max(t.count,0),r),a=r-s;return{startIndex:a,endIndex:r,hasMore:a>0,hasLater:r<n}}function h9(e,t,n){let{startIndex:r,endIndex:s}=h7(e,n);if(t>=r&&t<s)return n;let a=Math.max(0,t-10),i=Math.max(t+1,a+50);return i>=e?{count:e-a,end:null}:{count:i-a,end:i}}function pe({sticker:e,text:t,tag:n,followRef:a}){let i=(0,s.useRef)(null);return((0,s.useEffect)(()=>{(!a||a.current)&&i.current?.scrollIntoView({block:"nearest",behavior:"smooth"})},[]),e||t)?(0,r.jsxs)("div",{ref:i,className:"cue-bubble-dock",role:"status","aria-live":"polite",children:[e&&(0,r.jsx)("img",{className:"cue-bubble-sticker",src:e,alt:rk[n]}),t&&(0,r.jsx)("p",{className:e?"cue-bubble":"cue-bubble cue-bubble--solo",children:t}),e&&(0,r.jsx)(cG(),{id:"71a4a7cebbc6c842",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 pt(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=(ar(t)?.message??t).trim();return n.length>0?n:null}function pn(e){return`omp-cues:${e}`}function pr(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(pn(e),JSON.stringify(n.slice(-200)))}catch{}}let ps=[];function pa(e){return`omp-web:interrupted-dismissed:${e}`}let pi=(0,s.memo)(function({messages:e,entryIds:t,toolResultsMap:n,modelNames:a,messageCwd:i,onOpenFile:l,sessionBusy:o,isNew:c,isStreaming:d,handleFork:u,forkingEntryId:h,handleNavigate:p,handleEditContent:m,sessionId:f,main:g,process:x,turnSummaries:v,startIndex:y,endIndex:b,sentinelRef:w,laterSentinelRef:k,flashItem:j,t:S,onProcessLogChange:C,cues:N,cueFollowRef:T}){(0,s.useEffect)(()=>{C({groups:x,messages:e,entryIds:t,toolResults:n,modelNames:a,cwd:i,sessionId:f})},[C,x,e,t,n,a,i,f]);let I=(0,s.useMemo)(()=>(function(e){let t=new Map;for(let n=0;n<e.length;n++){let r=th(e,n);r>=0&&t.set(r,function(e){let t="string"==typeof e.content?e.content:e.content.map(e=>"text"===e.type?e.text:"").join("\n");if(!t.startsWith("[interpreter] "))return t;let n=t.indexOf("\n\n");return n<0?t:t.slice(n+2)}(e[n]))}return t})(e),[e]),M=(0,s.useMemo)(()=>{let t=new Map;for(let[r,s]of function(e,t,n,r){let s=new Map;e.forEach((e,t)=>{"answer"===e.kind&&s.set(e.idx,t)});let a=new Map,i=new Map;for(let e of t){let t=i.get(e.anchorIdx);for(let l of(t||(t=new Set,i.set(e.anchorIdx,t)),e.entries)){let e=n[l.idx];if(e?.role!=="assistant")continue;let i=Math.max(0,(l.blocks?s.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 s=r.input??{};if("manage_skill"===r.toolName){let e=tv(s.action);if(!0===tx[e]){let t={kind:"skill",action:e,name:tv(s.name)};n(JSON.stringify(t),t)}continue}let a=tv(s.memory),i=s.skill,l=i?{action:tv(i.action),name:tv(i.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(i);n?n.push(t):a.set(i,[t])})}}return a}(g,x,e,n)){let e=s.map(e=>{if("skill"===e.kind)return S("chat.savedSkill",{action:e.action,name:e.name});let t=S("chat.savedLesson",{memory:e.memory});return e.skill?`${t} (${S("chat.savedSkill",e.skill)})`:t});t.set(r,{role:"custom",customType:td,content:[S("chat.lessonsSaved"),...e.map(e=>`- ${e}`)].join("\n"),display:!0})}return t},[g,x,e,n,S]),E=y>0,$=b<g.length,R=(s,g={})=>{let x=g.messageOverride??e[s],v=s-1;for(;v>=0&&tm(t[v]);)v-=1;let y="user"===x.role&&v>=0&&"assistant"===e[v].role?t[v]:void 0,b=g.keyPrefix??"message",w=!1;if("assistant"===x.role){w=!0;for(let t=s+1;t<e.length;t++){let n=e[t].role;if("user"===n)break;if("assistant"===n){w=!1;break}}w&&d&&s===e.length-1&&(w=!1)}return void 0!==g.showTimestamp&&(w=g.showTimestamp),(0,r.jsx)(aC,{message:x,toolResults:n,modelNames:a,cwd:i,onOpenFile:l,entryId:t[s],onFork:o||c||0===s&&"user"===x.role?void 0:u,forking:h===t[s],onNavigate:o?void 0:p,prevAssistantEntryId:o?void 0:y,onEditContent:m,showTimestamp:w,prevTimestamp:s>0?e[s-1].timestamp:void 0,sessionId:f,writtenFiles:g.writtenFiles,hasTurnSummary:void 0!==g.turnSummary,inputTranslation:"user"===x.role?I.get(s):void 0,recoveredError:e8(e,s)},`${b}-view-${s}`)},L=(t,n)=>{let s=g[t],a="message"===s.kind&&e[s.idx]?.role==="user";return(0,r.jsx)("div",{"data-chat-item":t,"data-chat-question":a?"":void 0,className:j===t?"chat-item chat-jump-flash":"chat-item",children:n})};return(0,r.jsxs)(r.Fragment,{children:[E&&(0,r.jsx)("div",{ref:w,className:"py-3 text-center text-xs text-text-muted",children:S("chat.loadEarlier",{count:y})}),g.slice(y,b).map((a,o)=>{let c=y+o,d="message"===a.kind?a.anchorIdx??a.idx:a.anchorIdx,u=g[c+1],h=u?"message"===u.kind?u.anchorIdx??u.idx:u.anchorIdx:null,p=u?u.idx:1/0,m=N.filter(n=>{let r=null!==n.anchorEntryId?t.indexOf(n.anchorEntryId):Math.min(n.liveIndex??-1,e.length-1);return r>=a.idx&&r<p}).map(e=>(0,r.jsx)(pe,{sticker:e.sticker,text:e.text,tag:e.tag,followRef:T},`cue-${e.id}`)),x=h!==d,b=M.get(c),w=b?(0,r.jsx)(aC,{message:b,cwd:i,onOpenFile:l},`saved-lessons-${c}`):null,k=x?(0,r.jsx)(c2,{turnIndex:d,turnEntryId:t[d],sessionId:f,cwd:i,onOpenFile:l}):null;if("message"===a.kind)return(0,r.jsxs)(s.Fragment,{children:[L(c,R(a.idx)),w,k,m]},`message-${a.idx}`);let j=tF(a.precedingBlocks,n,i),S=v.get(c);return(0,r.jsxs)(s.Fragment,{children:[L(c,R(a.idx,{keyPrefix:`answer-${a.runIndex}`,messageOverride:function(e,t){let n=e1(e,t);if(!e.replyTranslation)return n;let r=e.content.find(e=>"text"===e.type);return r&&t.includes(r)||(n.replyTranslation=void 0,"translated"===e.replyTranslation.kind&&(n.content=t.filter(e=>"text"!==e.type))),n}(e[a.idx],a.blocks),writtenFiles:j,turnSummary:S})),S&&(0,r.jsx)(cE,{summary:S,turnKey:c}),w,k,m]},`answer-${a.idx}-${a.runIndex}`)}),$&&(0,r.jsx)("div",{ref:k,className:"py-3 text-center text-xs text-text-muted",children:S("chat.loadLater",{count:g.length-b})})]})});function pl({session:e,newSessionCwd:t,newSessionAutoWorktree:i,initialSessionData:l,transitioning:o=!1,onAgentEnd:c,onAttentionNeeded:d,onSessionCreated:u,onSessionForked:h,modelsRefreshKey:p,chatInputRef:m,onBranchDataChange:f,onSystemPromptChange:g,onSessionStatsChange:v,onSessionStatsPanelOpen:y,onContextUsageChange:b,onSubagentsChange:w,onLabWidgetsChange:k,onOpenWorkspaceView:j,onOpenSessionList:S,onRevealToolCall:C,composerStartPlace:N,composerNotice:T,onBrowserUse:I,onOpenMaker:M,selectedMaker:E,onProcessLogChange:$,onOpenFile:R,transcriptReplacement:L,onComposerFocusChange:P,onSessionBusyChange:A,onWaitingChange:_,onAttentionChange:O,soundEnabled:z=!0,onSoundToggle:D,playCueSound:W=async()=>({sticker:null,text:null}),preloadCueSound:H,unlockAudio:B,jumpRequest:q=null,onJumpHandled:V,turnInspectorTarget:K=null,onShowTurnInspector:J,turnInspectorFolded:G=!1,shellConnected:Y=!0}){var Z,Q;let X,et,en,{t:er}=(0,F.s)(),es=h6(),ea=U(),el=es&&ea,eo=(0,s.useRef)(W);eo.current=W;let ec=(0,s.useRef)(null),ed=(0,s.useRef)(H);ed.current=H;let[eu,eh]=(0,s.useState)([]),ep=(0,s.useRef)(eu);ep.current=eu;let em=(0,s.useRef)(0),ef=(0,s.useRef)([]),eg=(0,s.useRef)([]),ex=(0,s.useRef)(null),ev=(0,s.useRef)(0),ey=(0,s.useRef)(-1),eb=(0,s.useRef)(-1),ew=(0,s.useCallback)(()=>{let e=ex.current?.current;return e?{sessionId:e,turn:ev.current}:null},[]),ek=(0,s.useCallback)(e=>ex.current?.current===e.sessionId&&ev.current===e.turn,[]),ej=(0,s.useCallback)((e,t,n,r)=>{if(!e.sticker&&!e.text)return;em.current=Math.max(em.current+1,Date.now());let s={id:em.current,sticker:e.sticker,text:e.text,tag:t,sessionId:n.sessionId},a="entry"===r.kind?{...s,anchorEntryId:r.entryId}:{...s,anchorEntryId:null,liveIndex:r.liveIndex,intent:r.intent};eh(e=>{let t=[...e,a];return null!==a.anchorEntryId&&pr(n.sessionId,t),t})},[]),eS=(0,s.useCallback)((e,t,n,r)=>{let s=()=>ek(n)&&("working"!==t||eb.current!==n.turn);s()&&eo.current(e,t,s).then(e=>{null!==t&&null!==r&&s()&&ej(e,t,n,r)}).catch(()=>{})},[ek,ej]),eC=(0,s.useCallback)(async(e,t,n,r)=>{let s=(await sA(e,t,n,r))?.alias??null;return s&&ed.current?.(s),s},[]),eN=(0,s.useCallback)((e,t,n,r,s)=>{let a=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 s=rP(e[n]),a=0;for(let t=r;t<=n;t++)rP(e[t])===s&&(a+=1);return{kind:"pending",liveIndex:n,intent:{baseEntryId:r>0?t[r-1]:null,identity:s,occurrence:a}}}(ef.current,eg.current);eC(t.sessionId,n,r,s).then(n=>{eS(n,e,t,a)})},[eS,eC]),[eT,eI]=(0,s.useState)(0),eM=(0,s.useRef)([]),eE=(0,s.useCallback)(e=>{if(ev.current+=1,null!==rN(e.outcome)){let t=e.sessionId;eM.current.push({completion:e,trigger:t?{sessionId:t,turn:ev.current}:null}),eI(e=>e+1)}c?.(e)},[c]);(0,s.useEffect)(()=>{for(let{completion:e,trigger:t}of eM.current.splice(0)){let n=rN(e.outcome),r="neutral"===n?null:n;t?eN(r,t,e.provider,e.credentialId,e.model):eo.current(null,r).catch(()=>{})}},[eT,eN]);let e$=(0,s.useCallback)(e=>{m?.current?.replaceMessage(e)},[m]),eR=(0,s.useRef)(-1),eL=(0,s.useCallback)(t=>{"ego_browser"===t&&e?.id&&I?.(e.id,eR.current)},[I,e?.id]),{loading:eP,error:eA,messages:e_,entryIds:eF,streamState:eO,agentRunning:ez,bashRunning:eD,pendingBash:eW,modelNames:eU,modelList:eB,modelError:eq,modelScopeWarnings:eV,modelThinkingLevels:eK,modelThinkingLevelMaps:eJ,modelRoles:eG,toolPreset:eY,thinkingLevel:eZ,effectiveThinkingLevel:eQ,thinkingCeiling:eX,fastMode:e0,fastModeBusy:e2,handleFastModeToggle:e3,retryInfo:e7,contextUsage:tt,forkingEntryId:tn,isCompacting:ts,compaction:ta,compactError:td,compactResult:tx,displayModel:tv,modelSwitching:tb,sessionStats:tw,runStateKnown:tk,compactedWork:tj,slashCommands:tS,slashCommandsLoading:tC,deliveryRows:tN,subagents:tT,todoPhases:tI,notices:tM,extensionDialog:tE,extensionResponse:t$,extensionCustomUi:tR,extensionStatuses:tL,extensionWidgets:tP,respondToExtensionUi:tA,sendExtensionCustomInput:t_,isAutoModelSelection:tF,agentPhase:tO,isNew:tz,autoFollowPaused:tD,resumeAutoFollow:tW,pauseAutoFollow:tU,goalStatus:tB,sessionIdRef:tq,messagesEndRef:tV,scrollContainerRef:tJ,handleSend:tY,handleAbort:tZ,handleFork:tQ,handleNavigate:tX,handleModelChange:t0,handleRoleModelChange:t1,handleMainPresetChange:t2,newSessionAccount:t4,handleCompact:t8,handleSteer:t5,handleFollowUp:t6,handlePromptWithStreamingBehavior:t3,handleAbortCompaction:t7,handleRecallQueue:t9,handleRemoveQueuedMessage:ne,handleBuiltinSlashCommand:nt,handleToolPresetChange:nn,handleThinkingLevelChange:nr,loadSlashCommands:ns,ensureNewSession:na,refreshLiveTranscript:ni}=function(e){let{session:t,newSessionCwd:r,initialData:a,onAgentEnd:i,onAttentionNeeded:l,onSessionCreated:o,onSessionForked:c,modelsRefreshKey:d,onBranchDataChange:u,onSystemPromptChange:h,onSessionStatsPanelOpen:p}=e,m=(0,s.useRef)(e.onToolStart);m.current=e.onToolStart;let f=null===t&&null!==r,g=a&&a.sessionId===t?.id?a:null,[x,v]=(0,s.useState)(g),[y,b]=(0,s.useState)(!f&&!g),[w,k]=(0,s.useState)(null),[j,S]=(0,s.useState)(g?.leafId??null),[C,N]=(0,s.useState)(g?.context.messages??[]),[T,I]=(0,s.useState)(g?.context.entryIds??[]),[M,E]=(0,s.useState)(g?.context.compactedWork??null),[$,R]=(0,s.useReducer)(hL,{isStreaming:!1,streamingMessage:null}),[L,P]=(0,s.useState)(!1),[A,_]=(0,s.useState)(!1),[F,O]=(0,s.useState)(null),[z,D]=(0,s.useState)({}),[W,H]=(0,s.useState)([]),[U,B]=(0,s.useState)(null),[q,V]=(0,s.useState)([]),[K,J]=(0,s.useState)({}),[G,Y]=(0,s.useState)({}),[Z,Q]=(0,s.useState)([]),[X,ee]=(0,s.useState)(null),[et,en]=(0,s.useState)(null),[er,es]=(0,s.useState)(null),[ea,el]=(0,s.useState)("default"),[eo,ec]=(0,s.useState)(()=>{let e=g?.context.thinkingLevel;return e&&"off"!==e?e:"auto"}),[ed,eu]=(0,s.useState)(),[eh,ep]=(0,s.useState)(null),[em,ef]=(0,s.useState)(null),[eg,ex]=(0,s.useState)(!1),ev=(0,s.useRef)(0),ey=(0,s.useRef)(0),eb=(0,s.useRef)(""),[ew,ek]=(0,s.useState)(null),[ej,eS]=(0,s.useState)(g?.contextUsage??null),[eC,eN]=(0,s.useState)(null),[eT,eI]=(0,s.useState)(null),[eM,eE]=(0,s.useState)(null),[e$,eR]=(0,s.useState)(null),[eL,eP]=(0,s.useState)(!1),[eA,e_]=(0,s.useState)(!1),[eF,eO]=(0,s.useState)(null),[ez,eD]=(0,s.useState)(null),[eW,eU]=(0,s.useState)(null),eB=(0,s.useRef)(null),[eq,eV]=(0,s.useState)(!1),[eK,eJ]=(0,s.useState)(null),[eG,eY]=(0,s.useState)([]),[eZ,eQ]=(0,s.useState)(!1),[eX,e0]=(0,s.useReducer)(hq,{visible:[],pending:[]}),[e1,e2]=(0,s.useState)(null),[e4,e8]=(0,s.useState)(null),e5=(0,s.useRef)(null),e6=(0,s.useRef)(null),[e3,e7]=(0,s.useState)(null),e9=(0,s.useRef)(null),[te,tt]=(0,s.useState)(null),[tn,tr]=(0,s.useState)([]),[ts,ta]=(0,s.useState)([]),[ti,tl]=(0,s.useState)({steering:[],followUp:[]}),[to,td]=(0,s.useState)([]),[tu,th]=(0,s.useReducer)(on,[]),tg=(0,s.useRef)(0);(0,s.useEffect)(()=>{th({type:"queue",steering:ti.steering,followUp:ti.followUp})},[ti]),(0,s.useEffect)(()=>{L||th({type:"idle"})},[L]),(0,s.useEffect)(()=>{th({type:"reset"})},[t?.id]);let tx=(0,s.useMemo)(()=>(function(e,t){let n=new Map;for(let t of e){if(!t.inQueue)continue;let e=`${t.kind}\u0000${oe(t)}`;n.set(e,(n.get(e)??0)+1)}let r=[],s=(e,t)=>{t.forEach((t,s)=>{let a=`${e}\u0000${l9(t)}`,i=n.get(a)??0;i>0?n.set(a,i-1):r.push({key:`queue-${e}-${s}`,kind:e,text:t,images:0,stage:"accepted",removable:!0})})};for(let n of(s("steer",t?.steering??[]),s("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})(tu,ti),[tu,ti]),[tv,ty]=(0,s.useState)(null),tb=(0,s.useRef)(null),tw=(0,s.useRef)(null),tk=(0,s.useRef)(null),tj=(0,s.useRef)(null),tS=(0,s.useRef)(null),tC=(0,s.useRef)(0),tN=(0,s.useRef)(!1),tT=(0,s.useRef)(t?.id??null),tI=(0,s.useRef)(g?.leafId??null),tM=(0,s.useRef)(C),tE=(0,s.useRef)(T);tM.current=C,tE.current=T;let t$=(0,s.useRef)({sessionId:t?.id??null,outputs:[],seq:0}),tR=(0,s.useRef)(!1),tL=(0,s.useRef)(new Set);(0,s.useEffect)(()=>()=>hZ(tL.current),[]);let tP=(0,s.useRef)(!1),tA=(0,s.useRef)(!1),t_=(0,s.useRef)(-1),tF=(0,s.useRef)("unknown"),tO=(0,s.useRef)(null),tz=(0,s.useRef)(null),tD=(0,s.useRef)(0),tW=(0,s.useRef)(!1),tH=(0,s.useRef)(0),tU=(0,s.useRef)(null),tB=(0,s.useRef)(null),tq=(0,s.useRef)(null),tV=(0,s.useRef)(!1),tK=(0,s.useRef)(!0),[tJ,tG]=(0,s.useState)(!1),[tY,tZ]=(0,s.useState)(null),tQ=(0,s.useRef)(void 0),tX=(0,s.useRef)(0),t0=(0,s.useRef)(null),t1=(0,s.useRef)(0),t2=(0,s.useRef)(()=>{}),t4=(0,s.useRef)(null),t8=(0,s.useRef)(null),t5=(0,s.useRef)(null),t6=(0,s.useRef)(null),t3=(0,s.useRef)(!1),t7=(0,s.useRef)(null),t9=(0,s.useRef)(null),ne=(0,s.useRef)(null),nt=(0,s.useRef)(null),nn=(0,s.useRef)(null),nr=(0,s.useRef)(0),ns=(0,s.useRef)(null),na=(0,s.useRef)(null),ni=(0,s.useRef)(!1);ni.current=e.transitioning??!1;let nl=(0,s.useRef)(Date.now()),no=(0,s.useRef)(0),nc=(0,s.useRef)(0),nd=(0,s.useRef)(null),nu=(0,s.useRef)(!1),nh=(0,s.useRef)(Promise.resolve()),np=e.setToolPreset??el,nm=eM??x?.context.model??e$??null,nf=f?X??er:nm,ng=(0,s.useMemo)(()=>{if(e1)return{...e1,totalActiveMs:x?.totalActiveMs};let e={input:0,output:0,cacheRead:0,cacheWrite:0,total:0},n=0,r=0,s=0,a=0,i=0;for(let t of C){if("user"===t.role&&(r+=1),"toolResult"===t.role&&(a+=1),"assistant"!==t.role)continue;s+=1;let l=t.usage;i+=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===C.length)?null:{sessionFile:x?.filePath||void 0,sessionId:tT.current??t?.id??"",sessionName:t?.name,userMessages:r,assistantMessages:s,toolCalls:i,toolResults:a,totalMessages:C.length,tokens:e,cost:n,totalActiveMs:x?.totalActiveMs,...ej?{contextUsage:ej}:{}}},[C,e1,ej,x?.filePath,x?.totalActiveMs,t?.id,t?.name]),nx=(0,s.useRef)(0),nv=(0,s.useCallback)((e,t)=>{e&&tT.current===e&&Array.isArray(t)&&(nx.current+=1,ty(n=>n?.sid===e&&hF(n.phases,t)?n:{sid:e,phases:t}))},[]),ny=(0,s.useCallback)((e,t,n)=>{tT.current===e&&nx.current===n&&Array.isArray(t)&&ty(n=>n?.sid===e&&hF(n.phases,t)?n:{sid:e,phases:t})},[]),nb=(0,s.useCallback)(e=>{let t="function"==typeof e?e(tM.current):e;tM.current=t,N(t)},[]),nw=(0,s.useCallback)(e=>{tE.current=e,I(e)},[]),nk=(0,s.useCallback)(async(e,t=!1,n=!1,r)=>{let s=!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&&(v(null),S(null),nb([]),E(null),k(null)),null;if(!r.ok)throw Error(`HTTP ${r.status}`);a=await r.json()}if(tT.current!==e)return null;v(a),S(a.leafId),tI.current=a.leafId??null;let i=tf(a.context.messages,a.context.entryIds??[],t$.current.sessionId===e?t$.current.outputs:[]);nb(i.messages),nw(i.entryIds),E(a.context.compactedWork??null),eS(a.contextUsage??null),eE(e=>nu.current?e:null),k(null);let l=!n&&nn.current===e;if(l||(ec(a.context.configuredThinkingLevel??a.context.thinkingLevel??"off"),eu(a.context.thinkingLevel)),ep(a.context.thinkingCeiling??null),s=!0,t&&b(!1),!n){if(l)try{let t=nr.current,n=await fetch(`/api/sessions/${encodeURIComponent(e)}/state`);if(n.ok&&tT.current===e){let r=await n.json();tT.current===e&&nr.current===t&&(r.state?.thinkingLevel!==void 0?(ec(r.state.configuredThinkingLevel??r.state.thinkingLevel),eu(r.state.thinkingLevel)):r.running||(nn.current=null,ec(a.context.configuredThinkingLevel??a.context.thinkingLevel??"off"),eu(a.context.thinkingLevel)))}}catch(e){console.error("Failed to refresh live thinking level:",e)}return null}try{let t=nx.current,n=await fetch(`/api/sessions/${encodeURIComponent(e)}/state`);if(!n.ok)throw Error(`HTTP ${n.status}`);let r=await n.json();if(tT.current!==e)return null;let s=r.state;return s?(void 0!==s.contextUsage&&eS(s.contextUsage??null),void 0!==s.systemPrompt&&eN(s.systemPrompt??null),void 0!==s.thinkingLevel&&(nn.current=e,ec(s.configuredThinkingLevel??s.thinkingLevel),eu(s.thinkingLevel)),void 0!==s.thinkingCeiling&&ep(s.thinkingCeiling??null),void 0!==s.extensionStatuses&&tr(s.extensionStatuses??[]),void 0!==s.extensionWidgets&&ta(s.extensionWidgets??[]),void 0!==s.queuedMessages&&tl(hP(s.queuedMessages)),void 0!==s.subagents&&td(e=>hR(e,s.subagents??[])),ny(e,s.todoPhases,t)):r.running||tl({steering:[],followUp:[]}),r}catch(e){return console.error("Failed to load agent state:",e),null}}catch(e){return k(String(e)),null}finally{t&&!s&&b(!1)}},[ny,nw,nb]),nj=(0,s.useCallback)(e=>{let t=nh.current.then(async()=>{tT.current===e&&await nk(e)});return nh.current=t.catch(()=>{}),t},[nk]),nS=(0,s.useCallback)(async(e,t)=>{let n=++ey.current;try{let r=new URLSearchParams({deferThinking:"1",deferMedia:"1"});t&&r.set("leafId",t);let s=`/api/sessions/${encodeURIComponent(e)}/context?${r}`,a=await fetch(s);if(!a.ok)throw Error(`HTTP ${a.status}`);let i=await a.json();if(ey.current!==n||tT.current!==e)return;tI.current=t;let l=tf(i.context.messages,i.context.entryIds??[],t$.current.sessionId===e?t$.current.outputs:[]);nb(l.messages),nw(l.entryIds),E(i.context.compactedWork??null),eS(i.contextUsage??null)}catch(e){console.error("Failed to load context:",e)}},[nw,nb]),nC=(0,s.useCallback)(async e=>{try{let t=await hx(e,{type:"get_tools"});if(t){let{getPresetFromTools:e}=await Promise.resolve().then(n.bind(n,14755));np(e(t))}}catch(e){console.error("Failed to load tools:",e)}},[np]),nN=(0,s.useCallback)((e=0,t="(no messages)")=>{let n=tT.current;if(!f||!r||!n||t3.current)return;let s=t7.current??r;t3.current=!0,o?.({id:n,path:"",cwd:s,...s!==r?{projectRoot:r}:{},name:void 0,created:new Date().toISOString(),modified:new Date().toISOString(),messageCount:e,firstMessage:t,transient:!0})},[f,r,o]),nT=(0,s.useCallback)(async()=>{if(t5.current)return t5.current;let t=tT.current;if(t&&na.current!==t||!t&&(!f||!r))return t;let n=(async()=>{let n=t;if(!n){let t=t9.current,s=nt.current,a=ne.current;t&&eR(t);let i={cwd:r,type:"ensure_session",toolNames:(0,uA.xG)(ea),...void 0!==e.newSessionAutoWorktree?{autoWorktree:e.newSessionAutoWorktree}:{},...t?{provider:t.provider,modelId:t.modelId}:{},...s?{thinkingLevel:s}:{},...t&&null!==a?{oauthPosition:a}:{}},l=JSON.stringify(i),o=t6.current,c=o?.body===l?o.createRequestId:hH();t6.current={body:l,createRequestId:c};let d=await fetch("/api/agent/new",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...i,createRequestId:c})});if(!d.ok)throw Error((await d.json().catch(()=>({}))).error??`HTTP ${d.status}`);let u=await d.json();t6.current=null,n=u.sessionId,tT.current=n,t7.current=u.cwd??r??null,t7.current&&ei(t7.current,u.worktree),null!==ns.current&&(na.current=n),u.model&&t9.current===t&&(eR(u.model),t||es(u.model)),u.thinkingLevel&&nt.current===s&&(ec(u.configuredThinkingLevel??u.thinkingLevel),eu(u.thinkingLevel))}for(;na.current===n;){let e=ns.current;await hx(n,{type:"set_thinking_ceiling",ceiling:e}),ns.current===e&&na.current===n&&(na.current=null)}return n})();t5.current=n;try{return await n}finally{t5.current=null}},[f,r,ea,e.newSessionAutoWorktree]),nI=(0,s.useCallback)(async()=>{let e=tT.current??await nT();if(!e)return eY([]),[];eQ(!0);try{let t=await hx(e,{type:"get_commands"}),n=t?.commands??[];return eY(n),n}catch(e){return console.error("Failed to load slash commands:",e),eY([]),[]}finally{eQ(!1)}},[nT]),nM=(0,s.useCallback)(()=>{tC.current+=1,tN.current=!1,tS.current&&(clearTimeout(tS.current),tS.current=null)},[]),nE=(0,s.useCallback)(()=>{tb.current?.close(),tb.current=null,tw.current=null,tk.current=null},[]),n$=(0,s.useCallback)(()=>{tj.current?.close(),tj.current=null},[]),nR=(0,s.useCallback)(e=>{n$();let t=new EventSource(`/api/agent/${encodeURIComponent(e)}/events?entries=1`);tj.current=t,t.onmessage=t=>{try{let n=JSON.parse(t.data);"session_snapshot"===n.type?tU.current?.(n):"agent_start"===n.type&&tB.current?.(e)}catch{}}},[n$]),nL=(0,s.useCallback)(e=>{nE();let t=new EventSource(`/api/agent/${encodeURIComponent(e)}/events`);tb.current=t,tw.current=e;let n=new Promise(n=>{let r=!1,s=e=>{r||(r=!0,clearTimeout(a),tk.current?.source===t&&(tk.current.pending=!1),n({status:e,source:t}))},a=setTimeout(()=>s("timeout"),5e3);t.onmessage=e=>{try{let n=JSON.parse(e.data);if("connected"===n.type&&s("connected"),tb.current!==t)return;"update_maintenance"===n.type&&window.dispatchEvent(new CustomEvent("ompweb:update-maintenance",{detail:n})),tU.current?.(n)}catch{}},t.onerror=()=>{if(t.readyState===EventSource.CLOSED&&(s("closed"),tb.current===t&&(tR.current||tN.current))){tb.current=null,tw.current=null,tk.current=null;let t=tC.current;setTimeout(()=>{t===tC.current&&!tb.current&&(tR.current||tN.current)&&nL(e)},1e3)}}});return tk.current={source:t,promise:n,pending:!0},n},[nE]),nP=(0,s.useCallback)(async e=>{let t=tb.current;if(t&&tw.current===e){if(t.readyState===EventSource.OPEN)return;let e=tk.current;if(e?.source===t&&e.pending&&(await e.promise,tb.current===t&&t.readyState===EventSource.OPEN))return}let n=await nL(e);if("connected"!==n.status&&n.source.readyState!==EventSource.OPEN)throw tb.current===n.source&&(tb.current=null),tw.current===e&&(tw.current=null),tk.current?.source===n.source&&(tk.current=null),n.source.close(),new hW(n.status)},[nL]),nA=(0,s.useCallback)(e=>{e5.current=e.id,e8(e),l?.(e)},[l]),n_=(0,s.useCallback)(e=>{if(e6.current?.id===e&&(e6.current=null),e5.current===e){let e=e6.current;e6.current=null,e?nA(e):(e5.current=null,e8(null))}e9.current?.id===e&&(e9.current=null,e7(null))},[nA]),nF=(0,s.useCallback)(async(e,t)=>{if(e5.current!==e.id)return;let n=e9.current;if(n?.id===e.id&&"sending"===n.status)return;let r=tT.current,s=e=>{e9.current=e,e7(e)};if(!r)return void s({id:e.id,status:"failed",error:"no session"});s({id:e.id,status:"sending"});try{await hx(r,{type:"extension_ui_response",id:e.id,...t})}catch(t){if(tT.current!==r||e5.current!==e.id)return;s({id:e.id,status:"failed",error:t instanceof Error?t.message:String(t)});return}tT.current===r&&n_(e.id)},[n_]),nO=(0,s.useCallback)(async(e,t)=>{let n=tT.current;if(n)try{await hx(n,{type:"extension_ui_input",id:e.id,data:t})}catch(e){console.error("Failed to send extension custom UI input:",e)}},[]),nz=(0,s.useCallback)(e=>{let t=e.message.trim();t&&e0({type:"add",notice:{id:e.id??hH(),message:t,type:e.type??"info"}})},[]),nD=(0,s.useCallback)(e=>{let t={role:"custom",customType:tc,content:eH(e).trim(),display:!0,timestamp:Date.now()},n=t$.current,r=tT.current;n.sessionId!==r&&(n.sessionId=r,n.outputs=[]);let s=tE.current.slice(0,tM.current.length),a=null;for(let e=s.length-1;e>=0;e--)if(!tm(s[e])){a=s[e];break}n.seq+=1,n.outputs.push({entryId:`${tp}${n.seq}`,baseEntryId:a,message:t});let i=tf(tM.current,tE.current,n.outputs);nb(i.messages),nw(i.entryIds)},[nb,nw]),nW=(0,s.useCallback)((t,n)=>{if("custom"!==t.method&&"closed"in t&&t.closed)return void n_(t.id);switch("custom"===t.method&&hm(t)&&l?.(t),t.method){case"select":case"confirm":case"input":case"editor":case"ask":case"form":case"plan_review":{let e=e5.current;if(e===t.id)break;if(null!==e&&n){e6.current=t;break}e6.current=null,null!==e&&n_(e),nA(t);break}case"notify":nz({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)}},[nz,n_,l,e.chatInputRef,nA]),nH=(0,s.useCallback)(()=>{let e=tR.current;return tR.current=!1,P(!1),eJ(null),hZ(tL.current),ek(null),R({type:"end"}),e},[]),nU=(0,s.useCallback)(()=>{tF.current="unknown",tO.current=null;let e=hz(tM.current,tE.current);tz.current=e?{entryId:e.entryId,key:hJ(e.message)}:null,tD.current+=1},[]),nB=(0,s.useCallback)(()=>{let e=tF.current,t=tO.current;if("unknown"===e){let n=hz(tM.current,tE.current),r=n?.message,s=tz.current;null!==n&&(null===s||(null!==n.entryId&&null!==s.entryId?n.entryId!==s.entryId:hJ(n.message)!==s.key))&&r?.role==="assistant"&&r.stopReason&&(e=hO(r),t??={provider:r.provider,...r.model?{model:r.model}:{},...void 0!==r.credentialId?{credentialId:r.credentialId}:{}})}return{outcome:e,sessionId:tT.current,...t?{provider:t.provider,...t.model?{model:t.model}:{},...void 0!==t.credentialId?{credentialId:t.credentialId}:{}}:{}}},[]),nq=(0,s.useCallback)(e=>{let t=nB();if("unknown"!==t.outcome||!e)return void i?.(t);let n=tD.current;e.catch(()=>void 0).then(()=>{let e=tT.current===t.sessionId&&tD.current===n;i?.(e?nB():t)})},[i,nB]),nV=(0,s.useCallback)((e,t)=>t_.current!==e&&(t_.current=e,nq(t),!0),[nq]),nK=(0,s.useCallback)(e=>{nM(),tN.current=!0;let t=tC.current,n=async()=>{if(t===tC.current&&tT.current===e&&tN.current)try{let r=nx.current,s=e5.current,a=e6.current,i=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(!i.ok)throw Error(`HTTP ${i.status}`);let l=await i.json();if(t!==tC.current||tT.current!==e||!tN.current)return;let o=l.state;if(td(e=>hR(e,o?.subagents??[])),ny(e,o?.todoPhases,r),l.running&&o&&(o.isStreaming||o.isPromptRunning||o.isHandoffRunning)){tN.current=!1,tS.current=null,tP.current=!!o?.isStreaming,tA.current=!!o?.isPromptRunning,tR.current=!0,P(!0),eJ(o?.isStreaming?{kind:"waiting_model"}:{kind:"running_command"});return}if(l.running&&o?.isCompacting){e_(!0),eU(h_(o)),tS.current=setTimeout(()=>void n(),600);return}if(l.running&&(o?.subagents?.length??0)>0){tS.current=setTimeout(()=>void n(),1e3);return}let c=!1===l.running?[]:o?.pendingExtensionUiIds;if(c&&s===e5.current&&a===e6.current&&(a&&!c.includes(a.id)&&(e6.current=null),null===s||c.includes(s)||n_(s)),null!==e5.current){tS.current=setTimeout(()=>void n(),3e4);return}tN.current=!1,tS.current=null,nE()}catch{if(t!==tC.current||tT.current!==e||!tN.current)return;tS.current=setTimeout(()=>void n(),600)}};tS.current=setTimeout(()=>void n(),3e4)},[ny,nM,n_,nE]),nJ=(0,s.useCallback)(async(e=tT.current,t=no.current)=>{if(no.current===t)try{e&&await nk(e)}finally{if(no.current!==t)return;let n=tA.current,r=tP.current;tA.current=!1,tP.current=!1,nd.current=null;let s=nH();n?nV(t):r&&s&&nq(),e&&nK(e)}},[nk,nq,nV,nK,nH]),nG=(0,s.useCallback)(async(e,t)=>{await hU(800);let n=Date.now();for(;tR.current&&Date.now()-n<2e4;){if(void 0!==t&&no.current!==t)return;try{let n=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(n.ok){let r=await n.json(),s=r.state;if(!r.running||!s||!s.isStreaming&&!s.isPromptRunning)return void await nJ(e,t)}}catch{}await hU(600)}},[nJ]),nZ=(0,s.useCallback)(async e=>{let t=tH.current+1;for(tH.current=t;tW.current&&tH.current===t&&tT.current===e;){await hU(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 nk(e),tH.current!==t||tT.current!==e)return;tW.current=!1,_(!1),O(null);return}catch{}}},[nk]),nX=(0,s.useCallback)(async e=>{if(!tR.current)return;let t=no.current;try{let n=nx.current,r=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(!r.ok)return;let s=await r.json();if(no.current!==t)return;let a=s.state;if(e_(a?.isCompacting??!1),eU(h_(a)),tl(hP(a?.queuedMessages)),a?.contextUsage!==void 0&&eS(a.contextUsage??null),td(e=>hR(e,a?.subagents??[])),ny(e,a?.todoPhases,n),s.running&&a&&(a.isStreaming||a.isPromptRunning||a.isCompacting||a.isHandoffRunning)||!tR.current)return;a&&(void 0!==a.systemPrompt&&eN(a.systemPrompt??null),void 0!==a.extensionStatuses&&tr(a.extensionStatuses??[]),void 0!==a.extensionWidgets&&ta(a.extensionWidgets??[])),await nJ(e,t)}catch{}},[ny,nJ]),n2=(0,s.useCallback)(async e=>{let t=await nk(e,!1,!0),n=t?.state;return!!t?.running&&!!n&&tT.current===e&&!tR.current&&!!(n.isStreaming||n.isPromptRunning||n.isHandoffRunning)&&(tP.current=!!n.isStreaming,tA.current=!!n.isPromptRunning,tR.current=!0,P(!0),eJ(n.isStreaming?{kind:"waiting_model"}:{kind:"running_command"}),R({type:"start"}),hQ(tL.current,e,n.pendingToolCalls),nL(e),!n.isStreaming&&n.isPromptRunning&&nG(e),!0)},[nL,nk,nG]),n4=(0,s.useCallback)(async(e,t=no.current)=>{let n=nc.current+1;nc.current=n;try{let r=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(!r.ok)return;let s=await r.json();if(n!==nc.current||tT.current!==e||no.current!==t)return;s.state?.contextUsage!==void 0&&eS(s.state.contextUsage??null)}catch{}},[]);(0,s.useEffect)(()=>{if(!eA){eB.current=null,eU(null);return}eU(e=>e??{startedAt:Date.now(),reason:eB.current})},[eA]),(0,s.useEffect)(()=>{if(!L&&!eA)return;let e=()=>{let e=tT.current;e&&n4(e)};e();let t=setInterval(e,1e3);return()=>clearInterval(t)},[L,eA,n4]),(0,s.useEffect)(()=>{if(!L)return;let e=()=>{let e=tT.current;e&&nX(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)}},[L,nX]),(0,s.useEffect)(()=>{if(L)return;let e=()=>{let e=tT.current;e&&!tR.current&&n2(e)},t=()=>{"visible"===document.visibilityState&&e()},n=e=>{let t=tT.current,n=e.detail?.sessionId;t&&n===t&&!tR.current&&n2(t).then(e=>{e||tT.current!==t||tR.current||nk(t)})};return document.addEventListener("visibilitychange",t),window.addEventListener("online",e),window.addEventListener(hj,n),()=>{document.removeEventListener("visibilitychange",t),window.removeEventListener("online",e),window.removeEventListener(hj,n)}},[L,n2,nk]),tB.current=e=>{if(tT.current!==e||tR.current||tb.current||tq.current)return;let t=n2(e).then(async t=>{t||tT.current!==e||tR.current||await nk(e)}).catch(()=>{}).finally(()=>{tq.current===t&&(tq.current=null)});tq.current=t},(0,s.useEffect)(()=>{tR.current=L},[L]),tU.current=(0,s.useCallback)(e=>{var t;switch(e.type){case"connected":{let t=e.pendingExtensionUiIds,n=e5.current;if(Array.isArray(t)){let e=e6.current;e&&!t.includes(e.id)&&(e6.current=null),null===n||t.includes(n)||n_(n)}break}case"extension_ui_closed":"string"==typeof e.id&&n_(e.id);break;case"session_snapshot":{let t=function(e,t,n,r,s){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,i=new Map;for(let e of a){let t=hJ(e);i.set(t,(i.get(t)??0)+1)}let l=Math.min(r.length,s.length);for(let e of r.slice(0,l)){let t=hJ(e),n=i.get(t)??0;n>0&&i.set(t,n-1)}let o=r.slice(l).filter(e=>{let t=hJ(e),n=i.get(t)??0;return 0===n||(i.set(t,n-1),!1)});return{entryId:e.entryId,messages:[...a,...o],entryIds:[...e.context.entryIds],compactedWork:e.context.compactedWork??null}}(e,tT.current,tI.current,tM.current,tE.current);if(!t)break;tI.current=t.entryId;let n=tf(t.messages,t.entryIds,t$.current.sessionId===tT.current?t$.current.outputs:[]);nb(n.messages),nw(n.entryIds),E(t.compactedWork);break}case"agent_start":{let e=!tR.current;nM(),e&&nU(),tP.current=!0,tR.current=!0,P(!0),eJ({kind:"waiting_model"}),R({type:"start"});break}case"agent_end":if(!tR.current)break;if(eJ(null),hZ(tL.current),ek(null),R({type:"end"}),tT.current){nk(tT.current);let e=nx.current;fetch(`/api/agent/${encodeURIComponent(tT.current)}`).then(e=>e.json()).then(t=>{t.state?.contextUsage!==void 0&&eS(t.state.contextUsage??null),t.state?.systemPrompt!==void 0&&eN(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=>hR(e,t.state?.subagents??[])),tT.current&&ny(tT.current,t.state?.todoPhases,e),t.state?.goal!==void 0&&tZ(t.state.goal??null),tl(hP(t.state?.queuedMessages))}).catch(()=>{})}break;case"goal_status":tZ(e.status??null);break;case"agent_settled":{let e=tP.current;if(tP.current=!1,!e||tA.current)break;let t=tT.current,n=nH();e_(!1);let r=t?nk(t):void 0;t&&nK(t),n&&nq(r);break}case"prompt_done":{let e=no.current,t=tA.current;tA.current=!1,nd.current=null;let n=t_.current!==e;if(!t&&!n)break;let r=tT.current;nV(e,r?nk(r):void 0),!tP.current&&(nH(),r&&nK(r))}break;case"prompt_error":tF.current="failed",nz({type:"error",message:e.errorMessage??"Command failed"});break;case"extension_error":tF.current="failed",nz({type:"error",message:e.error??"Extension command failed"});break;case"message_start":case"message_update":{if(!tR.current)break;let t=e.message;if(t?.role!=="assistant")break;t&&R({type:"update",message:oS(t)}),eJ(null);break}case"message_end":{if(!tR.current)break;let t=e.message;if(t?.role==="assistant"&&(tO.current={provider:t.provider,...t.model?{model:t.model}:{},...void 0!==t.credentialId?{credentialId:t.credentialId}:{}},tF.current=hO(t)),t&&"user"===t.role){let e=oS(t),n=hK(e),r=nd.current;nd.current=null,nb(t=>{let s=t[t.length-1];return r&&s?.role==="user"&&hK(s)===r?r===n?t:[...t.slice(0,-1),e]:[...t,e]}),r||th({type:"user-message",kind:os(e),text:or(e),images:"user"!==e.role||"string"==typeof e.content?0:e.content.filter(e=>"image"===e.type).length})}else t&&nb(e=>[...e,oS(t)]);let n=tT.current;n&&n4(n),R({type:"reset"}),eJ(e=>t?.role==="toolResult"&&e?.kind==="running_tools"?e:{kind:"waiting_model"});break}case"thinking_level_changed":{let t=tT.current,n=e.thinkingLevel;t&&void 0!==n&&(nn.current=t,nr.current+=1,ec(e.configured??n),eu(n));break}case"todo_changed":nv(tT.current,e.phases);break;case"tool_execution_start":{let t=e.toolCallId,n=e.toolName,r=e.args,s=n0(tT.current,t);s&&tL.current.add(s),eJ(e=>{let s=e?.kind==="running_tools"?[...e.tools]:[];return s.some(e=>e.id===t)||s.push({id:t,name:n,args:r}),{kind:"running_tools",tools:s}}),m.current?.(n);break}case"tool_execution_update":{let n=n0(tT.current,"string"==typeof e.toolCallId?e.toolCallId:null);n&&tL.current.has(n)&&"string"==typeof e.text&&(t=e.text,nY.get(n)!==t&&(nY.set(n,t),nQ()));break}case"tool_execution_end":{let t=e.toolCallId,n=n0(tT.current,t);n&&tL.current.delete(n)&&n1([n]),eJ(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 hR(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=>hR(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=>hR(e,[r]));break}case"queue_update":tl({steering:[...e.steering??[]],followUp:[...e.followUp??[]]});break;case"auto_retry_start":ek({attempt:e.attempt,maxAttempts:e.maxAttempts,errorMessage:e.errorMessage});break;case"auto_retry_end":ek(null);break;case"auto_compaction_start":case"compaction_start":if("string"==typeof e.reason){eB.current=e.reason;let t=e.reason;eU(e=>e?{...e,reason:t}:e)}e_(!0),eO(null),eD(null);break;case"auto_compaction_end":case"compaction_end":if(e_(!1),e.errorMessage)eO(e.errorMessage),eD(null);else if(!e.aborted){eD(hG(e.result,e.reason??"auto"));let t=tT.current;t&&(nk(t),n4(t))}break;case"extension_ui_request":nW(e,!0===e.replayed)}},[nz,nv,ny,nM,n_,nW,nk,nq,nV,n4,nU,nK,nH,nw,nb]);let n8=(0,s.useCallback)(async(n,s,a)=>{let i=n.trim();if(!i&&!s?.length&&!a?.length)return"returned";if(tR.current||tW.current||nu.current)return"unknown";let l=an(n,a??[]),o=!s?.length&&!a?.length&&i.startsWith("/");if(!s?.length&&!a?.length&&i.startsWith("!")){let e=i.startsWith("!!"),t=(e?i.slice(2):i.slice(1)).trim();return t?(await tQ.current?.(t,e),"accepted"):"unknown"}nU();let c=no.current+1;nM(),tA.current=!0;let d=s?.map(e=>({type:"image",source:{type:"base64",media_type:e.mimeType,data:e.data}})),u={role:"user",content:d?.length?[...l.trim()?[{type:"text",text:l}]:[],...d]:l,timestamp:Date.now()};nb(e=>[...e,u]),nd.current=hK(u),no.current=c,tR.current=!0,P(!0),eJ(o?{kind:"running_command"}:{kind:"waiting_model"}),R({type:"start"}),t2.current(!0);let h=s?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),p=null,m=!1,g="unknown";try{if(f&&r){let e=tT.current??await t5.current,t=await nT();t&&(p=t,X&&(eR(X),e&&await hx(t,{type:"set_model",provider:X.provider,modelId:X.modelId})),await nP(t),m=!0,await hx(t,{type:"prompt",message:l,...h?.length?{images:h}:{}}),nN(1,n),g="accepted")}else t&&(p=t.id,await nP(t.id),m=!0,await hx(t.id,{type:"prompt",message:l,...h?.length?{images:h}:{}}),g="accepted");return o&&p&&nG(p,c),g}catch(l){console.error("Failed to send message:",l);let r=l instanceof hg&&"update_draining"===l.code&&!1===l.accepted;if(!(!m||l instanceof hg&&"prompt_rejected"===l.code&&!1===l.accepted||r)&&p)return nG(p,c),"unknown";tA.current=!1,tR.current=!1,nE();let i=nd.current;return i&&nb(e=>{let t=e[e.length-1];return t?.role==="user"&&hK(t)===i?e.slice(0,-1):e}),nz({type:"error",message:l instanceof Error?l.message:String(l)}),e.chatInputRef?.current?.restoreSubmission?.(n,hY(s),a,t?.id??p??void 0),nd.current=null,P(!1),eJ(null),R({type:"end"}),"returned"}},[f,r,X,t,nT,nP,nN,nG,nz,nM,nE,e.chatInputRef,nU,nb]);tQ.current=(0,s.useCallback)(async(n,r)=>{if(tR.current||tW.current)return;let s=`${r?"!!":"!"}${n}`;tW.current=!0,t2.current(!0),O({command:n,excludeFromContext:r}),_(!0);try{let e=tT.current??t?.id??await nT();if(!e)throw Error("Unable to create a session for the shell command");await hx(e,{type:"bash",command:n,excludeFromContext:r}),await nk(e),nN(1,s)}catch(t){console.error("Failed to execute shell command:",t),nz({type:"error",message:t instanceof Error?t.message:String(t)}),e.chatInputRef?.current?.insertIfEmpty(s)}finally{tW.current=!1,O(null),_(!1)}},[nz,nT,nk,e.chatInputRef,nN,t]);let n5=(0,s.useCallback)(async()=>{let e=tT.current;if(e){if(tW.current){try{await hx(e,{type:"abort_bash"})}catch(e){console.error("Failed to abort bash:",e)}return}try{await hx(e,{type:"abort"}),tF.current="aborted"}catch(e){console.error("Failed to abort:",e)}}},[]),n6=(0,s.useCallback)(async e=>{if(tW.current)return{forked:!1,error:"Cannot fork while a shell command is running"};let t=tT.current;if(!t)return{forked:!1,error:"No active session to fork"};eI(e??null);try{let{cancelled:n,newSessionId:r}=await hx(t,{type:"fork",...e?{entryId:e}:{}})??{};if(!n&&r)return c?.(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)}},[c]),n3=(0,s.useCallback)(async e=>{if(tW.current)return;let t=tT.current;t&&(hx(t,{type:"navigate_tree",targetId:e}).catch(()=>{}),S(e),await nS(t,e))},[nS]),n7=(0,s.useCallback)(async e=>{if(tW.current)return;S(e);let t=tT.current;t&&(await nS(t,e),e&&hx(t,{type:"navigate_tree",targetId:e}).catch(()=>{}))},[nS]),n9=(0,s.useCallback)(async(e,t)=>{if(f){let n={provider:e,modelId:t},r=t9.current?.provider===e;t9.current=n,r||(ne.current=null,en(null)),ee(n),eR(n);let s=tT.current??await t5.current;if(!s)return;try{await hx(s,{type:"set_model",provider:e,modelId:t})}catch(e){console.error("Failed to set model:",e)}return}let n=tT.current;if(n&&!nu.current){nu.current=!0,eE({provider:e,modelId:t}),eP(!0);try{await hx(n,{type:"set_model",provider:e,modelId:t}),nu.current=!1,await nk(n)}catch(e){console.error("Failed to set model:",e),nu.current=!1,eE(eM),nz({type:"error",message:`Failed to switch model: ${e instanceof Error?e.message:String(e)}`}),await nk(n)}finally{nu.current=!1,eP(!1)}}},[nz,eM,f,nk,ee]),re=(0,s.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}:{}},s=t=>`${e.alias} preset was not applied: ${t instanceof Error?t.message:String(t)}`;if(f){if(nu.current)return!1;nu.current=!0,eP(!0);let e=t9.current,a=ne.current,i=nt.current;try{t9.current=t,ne.current=n??null,nt.current="auto";let e=tT.current??await t5.current;return e&&await hx(e,r),ee(t),en(n??null),eR(t),ec("auto"),eu(void 0),e&&await nk(e),!0}catch(n){console.error("Failed to apply Main preset:",n),t9.current=e,ne.current=a,nt.current=i,nz({type:"error",message:s(n)});let t=tT.current;return t&&await nk(t),!1}finally{nu.current=!1,eP(!1)}}let a=tT.current;if(!a||nu.current)return!1;nu.current=!0,eE(t),eP(!0);try{return await hx(a,r),await nk(a),!0}catch(e){return console.error("Failed to apply Main preset:",e),eE(eM),nz({type:"error",message:s(e)}),await nk(a),!1}finally{nu.current=!1,eP(!1)}},[nz,eM,ed,f,nk,ee,eo]),rt=(0,s.useCallback)(async e=>{let t=Z.find(t=>t.role===e),n=t?.resolved;if(!n)return;if(f){let e={provider:n.provider,modelId:n.modelId},t=n.thinkingLevel;nt.current=t??null,ec(t??"auto"),eu(void 0),t9.current=e,ne.current=null,en(null),ee(e),eR(e)}let r=tT.current??(f?await t5.current:null);if(r)try{await hx(r,{type:"set_role_model",role:e}),f||eE({provider:n.provider,modelId:n.modelId})}catch(e){console.error("Failed to set role model:",e)}},[f,Z,ee]),rn=(0,s.useCallback)(async()=>{let e=tT.current;if(e&&!eA){eB.current="manual",e_(!0),eO(null),eD(null);try{let t=await hx(e,{type:"compact"});eD(hG(t,"manual")),await nk(e,!0)}catch(e){eO(e instanceof Error?e.message:String(e)),eD(null)}finally{e_(!1)}}},[eA,nk]),rr=(0,s.useCallback)(async e=>{let n=r??t?.cwd??"",s=n?`/api/models?cwd=${encodeURIComponent(n)}`:"/api/models",a=await fetch(s,e?{signal:e}:void 0);if(!a.ok)throw Error(`HTTP ${a.status}`);let i=await a.json();D(i.models),B(i.modelError??null),V(i.modelScopeWarnings??[]),J(i.thinkingLevels??{}),Y(i.thinkingLevelMaps??{}),Q(i.roles??[]);let l=i.modelList??[];if(H(l),f&&!tT.current){let e=(i.defaultModel?l.find(e=>e.id===i.defaultModel?.modelId&&e.provider===i.defaultModel?.provider):void 0)??l[0];es(e?{provider:e.provider,modelId:e.id}:null);let t=e&&i.thinkingLevelPins?.[`${e.provider}/${e.id}`];null===nt.current&&ec(t??"auto")}},[f,r,t?.cwd]),rs=(0,s.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,s=r.trim(),a=await nT(),i=e=>(e.handled&&(e.error?nz({type:"error",message:e.error}):"openSessionStats"!==e.action&&nz({type:"success",message:e.message??"Command completed"})),e);try{switch(n){case"compact":{if(!a||eA)return i({handled:!0,error:"No active session to compact"});eB.current="manual",e_(!0),eO(null),eD(null);let e=await hx(a,{type:"compact",...s?{customInstructions:s}:{}});return eD(hG(e,"manual")),await nk(a,!0)&&nN(),i({handled:!0,message:"Compacted context"})}case"reload":if(!a)return i({handled:!0,error:"No active session to reload"});return await hx(a,{type:"reload"}),await Promise.all([nk(a,!1,!0),nC(a),nI(),rr()]),i({handled:!0,message:"Reloaded session resources"});case"name":if(!a)return i({handled:!0,error:"No active session to name"});if(!s)return i({handled:!0,error:"Usage: /name <name>"});return await hx(a,{type:"set_session_name",name:s}),await nk(a)&&nN(),i({handled:!0,message:`Session renamed to ${s}`});case"session":{if(!a)return i({handled:!0,error:"No active session"});let e=await hx(a,{type:"get_session_stats"});return e&&e2(e),p?.(),i({handled:!0,action:"openSessionStats"})}case"copy":{if(!a)return i({handled:!0,error:"No active session"});let e=await hx(a,{type:"get_last_assistant_text"}),t=e?.text??"";if(!t)return i({handled:!0,error:"No assistant message to copy"});return await navigator.clipboard.writeText(t),i({handled:!0,message:"Copied last assistant message"})}case"fork":{if(!a)return i({handled:!0,error:"No active session to fork"});let e=await n6();if(!e.forked)return i({handled:!0,error:e.error??"Fork failed"});return i({handled:!0,message:"Forked a new session"})}case"goal":{if(!a)return i({handled:!0,error:"No active session"});let e=await hx(a,{type:"goal",args:s});if(tZ(e?.status??null),e?.error)return i({handled:!0,error:e.error});if(e?.message&&e.message.includes("\n")){if(nD(e.message),e.prompt)return{handled:!0,prompt:e.prompt};return{handled:!0}}if(e?.prompt)return e.message&&nz({type:"success",message:e.message}),{handled:!0,prompt:e.prompt};return i({handled:!0,message:e?.message??"Command completed"})}case"handoff":if(!a)return i({handled:!0,error:"No active session"});if(tR.current||tW.current)return i({handled:!0,error:"Cannot hand off while the session is busy"});tR.current=!0,P(!0),eJ({kind:"running_command"});try{await nP(a);let e=await hx(a,{type:"handoff",...s?{customInstructions:s}:{}});if(!e||e.cancelled)return i({handled:!0,error:"Handoff cancelled"});return await nk(a,!0)&&nN(),i({handled:!0,message:"컨텍스트를 현재 세션에 압축했습니다"})}finally{tR.current=!1,P(!1),eJ(null),tT.current===a&&nK(a)}default:{if(!a)return i({handled:!0,error:"No active session"});let t=await hx(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&&nD(n),t.prompt)return{handled:!0,prompt:t.prompt};if(n)return{handled:!0};return i({handled:!0,message:"Command completed"})}}}catch(e){return i({handled:!0,error:e instanceof Error?e.message:String(e)})}finally{"compact"===n&&e_(!1)}},[nz,nD,nP,nT,n6,eA,rr,nk,nI,nC,nN,p,nK]),ra=(0,s.useCallback)(async(t,n,r)=>{let s=tT.current;if(!s)return nz({type:"error",message:"The session is not ready yet, so the message was returned to the composer."}),e.chatInputRef?.current?.restoreSubmission?.(t,hY(n),r),"returned";let a=an(t,r??[]),i=n?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),l=++tg.current;th({type:"submit",id:l,kind:"steer",text:a,images:i?.length??0});try{return await hx(s,{type:"steer",message:a,...i?.length?{images:i}:{}}),th({type:"ack",id:l}),"accepted"}catch(a){return th({type:"fail",id:l}),console.error("Failed to steer:",a),nz({type:"error",message:a instanceof Error?a.message:String(a)}),e.chatInputRef?.current?.restoreSubmission?.(t,hY(n),r,s),"returned"}},[nz,e.chatInputRef]),ri=(0,s.useCallback)(async(t,n,r,s)=>{let a=tT.current;if(!a)return nz({type:"error",message:"The session is not ready yet, so the message was returned to the composer."}),e.chatInputRef?.current?.restoreSubmission?.(t,hY(r),s),"returned";let i=an(t,s??[]),l=r?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),o=++tg.current;th({type:"submit",id:o,kind:n,text:i,images:l?.length??0});try{return await hx(a,{type:"prompt",message:i,streamingBehavior:n,...l?.length?{images:l}:{}}),th({type:"ack",id:o}),"accepted"}catch(n){return th({type:"fail",id:o}),console.error("Failed to queue prompt:",n),nz({type:"error",message:n instanceof Error?n.message:String(n)}),e.chatInputRef?.current?.restoreSubmission?.(t,hY(r),s,a),"returned"}},[nz,e.chatInputRef]),rl=(0,s.useCallback)(async(t,n,r)=>{let s=tT.current;if(!s)return nz({type:"error",message:"The session is not ready yet, so the message was returned to the composer."}),e.chatInputRef?.current?.restoreSubmission?.(t,hY(n),r),"returned";let a=an(t,r??[]),i=n?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),l=++tg.current;th({type:"submit",id:l,kind:"followUp",text:a,images:i?.length??0});try{return await hx(s,{type:"follow_up",message:a,...i?.length?{images:i}:{}}),th({type:"ack",id:l}),"accepted"}catch(a){return th({type:"fail",id:l}),console.error("Failed to follow up:",a),nz({type:"error",message:a instanceof Error?a.message:String(a)}),e.chatInputRef?.current?.restoreSubmission?.(t,hY(n),r,s),"returned"}},[nz,e.chatInputRef]),ro=(0,s.useCallback)(async()=>{let e=tT.current;if(e)try{await hx(e,{type:"abort_compaction"})}catch(e){console.error("Failed to abort compaction:",e)}},[]),rc=(0,s.useCallback)(async()=>{let t=tT.current;if(t)try{var n;let r=await hx(t,{type:"clear_queue"});th({type:"withdraw"}),tl({steering:[],followUp:[]});let s={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?.(s.text,s.images.length?s.images:void 0,void 0,t)}catch(e){console.error("Failed to recall queued messages:",e),nz({type:"error",message:"Failed to recall queued messages"})}},[e.chatInputRef,nz]),rd=(0,s.useCallback)(async(e,t)=>{let n=tT.current;if(n)try{let r=await hx(n,{type:"remove_queued_message",message:t,queue:e});if(!r?.removed)return;th({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),nz({type:"error",message:"Failed to remove queued message"})}},[nz]),ru=(0,s.useCallback)(async(e,t=null)=>{let n="auto"===e?t:null,r=n!==eh;ec(e),ep(n),f&&(!tT.current||na.current===tT.current)&&(nt.current=e,ns.current=n),eu(void 0);let s=tT.current??await t5.current;if(s)try{na.current===s?await nT():r&&await hx(s,{type:"set_thinking_ceiling",ceiling:n}),await hx(s,{type:"set_thinking_level",level:e}),await nk(s)}catch(e){console.error("Failed to set thinking level:",e),nz({type:"error",message:"Failed to set thinking level"}),await nk(s)}},[f,nk,nz,eh,nT]);eb.current=nf?`${nf.provider}/${nf.modelId}`:"";let rh=e=>e?`${e}|${eb.current}`:null,rp=t?.id??tT.current,rm=rh(rp),rf=em&&em.key===rm?em.value:null;(0,s.useEffect)(()=>{let e=++ev.current;rm&&rp&&!L&&!eL&&fetch(`/api/agent/${encodeURIComponent(rp)}`).then(e=>e.json()).then(t=>{ev.current===e&&rh(tT.current)===rm&&ef({key:rm,value:(t.running?hA(t.state):void 0)??null})}).catch(()=>{})},[rm,L,eL]);let rg=(0,s.useCallback)(async()=>{let e=tT.current??await nT(),t=rh(tT.current);if(!e||!t)return;let n=++ev.current,r=()=>ev.current===n&&rh(tT.current)===t,s=e=>{r()&&ef({key:t,value:e})};ex(!0);try{let n=em?.key===t?em.value?.enabled:void 0;if(void 0===n){let t=hA(await hx(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 hx(e,{type:"set_fast_mode",enabled:!n});s({enabled:a?.enabled===!0,active:a?.active===!0})}catch(t){if(!r())return;nz({type:"error",message:t instanceof Error?t.message:String(t)});try{s(hA(await hx(e,{type:"get_state"}))??null)}catch{s(null)}}finally{ex(!1)}},[nT,em,nz]),rx=(0,s.useCallback)(async e=>{let t=(0,uA.xG)(e);np(e);let n=tT.current??await t5.current;if(n)try{await hx(n,{type:"set_tools",toolNames:t})}catch(e){console.error("Failed to set tools:",e)}},[np]),rv=(0,s.useCallback)(e=>{tK.current=e,tG(t=>!e===t?t:!e)},[]);t2.current=e=>{t0.current=null,rv(e)};let ry=(0,s.useCallback)((e="smooth")=>{t1.current=Date.now()+700,t4.current?.scrollIntoView({behavior:e})},[]),rb=(0,s.useCallback)(()=>{tX.current=0,t0.current=null,rv(!0),ry("smooth")},[ry,rv]),rw=(0,s.useCallback)(()=>{tX.current=0,t0.current=null,rv(!1)},[rv]),rk=(0,s.useCallback)(()=>{if(!t0.current)return;t0.current=null;let e=t8.current;e&&rv(e.scrollHeight-e.scrollTop-e.clientHeight<=72)},[rv]),rj=(0,s.useCallback)(e=>{if(e instanceof PointerEvent&&"mouse"===e.pointerType&&1===e.button&&!(e.target instanceof Element&&e.target.closest("a[href], input, textarea"))&&!(e.target instanceof HTMLElement&&e.target.isContentEditable)){if(t0.current)return void rk();rw();let e=t8.current;return void(t0.current=e?{top:e.scrollTop,moved:!1,released:!1}:null)}rk(),e instanceof KeyboardEvent&&(!hD.has(e.key)||e.target instanceof Element&&e.target.closest("input, textarea, [contenteditable='true']"))||(tX.current=Date.now()+1200)},[rk,rw]),rS=(0,s.useCallback)(()=>{let e=t8.current;if(!e)return;let t=t0.current;if(null!==t){let n=t.top;t.moved||=e.scrollTop!==n,t.top=e.scrollTop;return}if(!tR.current&&!tW.current)return;let n=e.scrollHeight-e.scrollTop-e.clientHeight,r=Date.now()<=tX.current;if(!(!r&&Date.now()<t1.current)){if(n<=72)return void rv(!0);r&&rv(!1)}},[rv]);return(0,s.useEffect)(()=>(tT.current=t?.id??null,t$.current.sessionId!==tT.current&&(t$.current={sessionId:tT.current,outputs:[],seq:0}),t&&nk(t.id,!g,!0,g).then(e=>{if(tT.current!==t.id)return;nR(t.id),e?.running&&(nC(t.id),(e.state?.isStreaming||e.state?.isPromptRunning||e.state?.isHandoffRunning)&&(tP.current=!!e.state.isStreaming,tA.current=!!e.state.isPromptRunning,tR.current=!0,P(!0),eJ(e.state.isStreaming?{kind:"waiting_model"}:{kind:"running_command"}),R({type:"start"}),hQ(tL.current,t.id,e.state.pendingToolCalls),nL(t.id),!e.state.isStreaming&&e.state.isPromptRunning&&nG(t.id)),e.state?.isBashRunning&&(tW.current=!0,_(!0),nZ(t.id)),(e.state?.subagents?.length??0)>0&&nL(t.id));let n=e?.state;n&&(void 0!==n.isCompacting&&e_(n.isCompacting),eU(h_(n)),void 0!==n.contextUsage&&eS(n.contextUsage??null),void 0!==n.systemPrompt&&eN(n.systemPrompt??null),void 0!==n.thinkingLevel&&(nn.current=t.id,ec(n.configuredThinkingLevel??n.thinkingLevel),eu(n.thinkingLevel)),void 0!==n.thinkingCeiling&&ep(n.thinkingCeiling??null),void 0!==n.extensionStatuses&&tr(n.extensionStatuses??[]),void 0!==n.extensionWidgets&&ta(n.extensionWidgets??[]),void 0!==n.queuedMessages&&tl(hP(n.queuedMessages)),void 0!==n.subagents&&td(e=>hR(e,n.subagents??[])),void 0!==n.goal&&tZ(n.goal??null)),e&&eV(!0)}),()=>{tH.current+=1,nM(),e6.current=null,null!==e5.current&&n_(e5.current),nE(),n$()}),[t?.id]),(0,s.useEffect)(()=>{h?.(eC)},[eC,h]),(0,s.useEffect)(()=>{u&&u(x?.tree??[],j,n7)},[x?.tree,j,n7,u]),(0,s.useEffect)(()=>{let e=e=>{let t=t0.current;t&&(1!==e.button||t.released||t.moved||!(e.target instanceof Node&&t8.current?.contains(e.target))?rk():t.released=!0)};return window.addEventListener("pointerup",e,!0),window.addEventListener("keydown",rj),()=>{window.removeEventListener("pointerup",e,!0),window.removeEventListener("keydown",rj)}},[rk,rj]),(0,s.useEffect)(()=>{let e=t8.current;if(!e)return;let t=()=>{t0.current?.moved&&rk()};return e.addEventListener("pointerdown",rj,{passive:!0}),e.addEventListener("wheel",rj,{passive:!0}),e.addEventListener("touchstart",rj,{passive:!0}),e.addEventListener("scroll",rS,{passive:!0}),e.addEventListener("scrollend",t,{passive:!0}),()=>{e.removeEventListener("pointerdown",rj),e.removeEventListener("wheel",rj),e.removeEventListener("touchstart",rj),e.removeEventListener("scroll",rS),e.removeEventListener("scrollend",t)}},[C.length,y,rk,rS,rj]),(0,s.useEffect)(()=>{if(ni.current||!L&&!A||!tK.current)return;let e=t8.current;if(!e)return;let t=requestAnimationFrame(()=>{tK.current&&(t1.current=Date.now()+700,e.scrollTo({top:e.scrollHeight,behavior:"instant"}))});return()=>cancelAnimationFrame(t)},[L,A,C.length,$.streamingMessage,eK,F,e.transitioning]),(0,s.useLayoutEffect)(()=>{if(0!==C.length){if(!tV.current){tV.current=!0,ry("instant");return}if(!ni.current&&tK.current){let e=Date.now()-nl.current<1500;ry(tR.current||tW.current||e?"instant":"smooth")}}},[C.length,L,A,ry,e.transitioning]),(0,s.useEffect)(()=>{let e=new AbortController;return rr(e.signal).catch(e=>{if(e instanceof DOMException&&"AbortError"===e.name)return}),()=>e.abort()},[rr,d]),(0,s.useEffect)(()=>{if(!ez)return;let e=setTimeout(()=>eD(null),6e3);return()=>clearTimeout(e)},[ez]),(0,s.useEffect)(()=>{if(0===eX.visible.length)return;let e=eX.visible.find(e=>e.exiting);if(e){let t=setTimeout(()=>{e0({type:"remove",id:e.id})},180);return()=>clearTimeout(t)}if(!eX.visible[0])return;let t=setTimeout(()=>{e0({type:"mark_oldest_exiting"})},5e3);return()=>clearTimeout(t)},[eX.visible]),(0,s.useEffect)(()=>{e2(null)},[C.length,ej?.tokens,ej?.percent,ej?.contextWindow]),{data:x,loading:y,error:w,activeLeafId:j,messages:C,entryIds:T,streamState:$,agentRunning:L,modelNames:z,modelList:W,modelError:U,modelScopeWarnings:q,modelThinkingLevels:K,modelThinkingLevelMaps:G,modelRoles:Z,newSessionModel:X,toolPreset:ea,thinkingLevel:eo,effectiveThinkingLevel:ed,thinkingCeiling:eh,retryInfo:ew,contextUsage:ej,systemPrompt:eC,forkingEntryId:eT,isCompacting:eA,compaction:eW,compactError:eF,compactResult:ez,currentModel:nm,displayModel:nf,modelSwitching:eL,sessionStats:ng,runStateKnown:eq,slashCommands:eG,slashCommandsLoading:eZ,queuedMessages:ti,deliveryRows:tx,subagents:to,todoPhases:tv&&tv.sid===tT.current?tv.phases:null,compactedWork:M,notices:eX.visible,extensionDialog:e4,extensionResponse:e3,extensionCustomUi:te,extensionStatuses:tn,extensionWidgets:ts,respondToExtensionUi:nF,sendExtensionCustomInput:nO,isAutoModelSelection:f&&null===X,agentPhase:eK,isNew:f,autoFollowPaused:tJ,resumeAutoFollow:rb,pauseAutoFollow:rw,goalStatus:tY,sessionIdRef:tT,eventSourceRef:tb,messagesEndRef:t4,scrollContainerRef:t8,handleSend:n8,handleAbort:n5,handleFork:n6,handleNavigate:n3,handleModelChange:n9,handleRoleModelChange:rt,handleMainPresetChange:re,newSessionAccount:et,handleCompact:rn,handleSteer:ra,handleFollowUp:rl,handlePromptWithStreamingBehavior:ri,handleAbortCompaction:ro,handleRecallQueue:rc,handleRemoveQueuedMessage:rd,handleBuiltinSlashCommand:rs,handleToolPresetChange:rx,handleThinkingLevelChange:ru,fastMode:rf,fastModeBusy:eg,handleFastModeToggle:rg,loadTools:nC,loadSlashCommands:nI,ensureNewSession:nT,refreshLiveTranscript:nj,setActiveLeafId:S,setData:v,setMessages:N,dispatch:R,setAgentRunning:P,setForkingEntryId:eI,bashRunning:A,pendingBash:F,handleAgentEventRef:tU}}({session:e,newSessionCwd:t,initialData:l,transitioning:o,onAgentEnd:eE,onAttentionNeeded:d,onToolStart:eL,onSessionCreated:u,onSessionForked:h,newSessionAutoWorktree:i,modelsRefreshKey:p,chatInputRef:m,onBranchDataChange:f,onSystemPromptChange:g,onSessionStatsPanelOpen:y}),nl=(0,s.useMemo)(()=>(function(e){let t=null,n=new Map;for(let r=0;r<e.length;r++){let s=e[r],a=to(s);if(!a||"custom"!==s.role)continue;t??=[...e];let i=[];for(let t=0;t<r;t++){let r=e[t];if("assistant"!==r.role)continue;if(void 0===a.sourceHash){r.timestamp===a.sourceTimestamp&&i.push(t);continue}let s=n.get(t);void 0===s&&(s=function(e){let t=tl(e),n=5381;for(let e=0;e<t.length;e++)n=(n<<5)+n+t.charCodeAt(e)|0;return`${t.length}:${n}`}(r.content??[]),n.set(t,s)),s===a.sourceHash&&i.push(t)}i.length>1&&void 0!==a.sourceHash&&void 0!==a.sourceTimestamp&&(i=i.filter(t=>e[t].timestamp===a.sourceTimestamp));let l=1===i.length?t[i[0]]:null;if(l?.role!=="assistant"){t[r]={...s,details:void 0};continue}t[i[0]]={...l,replyTranslation:function(e,t){let n="string"==typeof e.content?e.content:e.content.map(e=>"text"===e.type?e.text:"").join("\n");return n.startsWith(ti)?{kind:"translated",text:n.slice(ti.length),original:t}:n.startsWith("[번역 생략]")?{kind:"skipped",text:n,original:t}:{kind:"failed",text:n,original:t}}(s,tl(l.content??[]))}}return t??e})(e_),[e_]),no=s_(e?.id,tv?.provider,void 0,tv?.modelId),nc=no?.alias;(0,s.useEffect)(()=>{nc&&ed.current?.(nc)},[nc]);let nd=(0,s.useMemo)(()=>{if(!tv)return null;let e=tz?t4:rW.find(e=>e.alias===no?.alias)?.oauthPosition;return rW.find(t=>t.provider===tv.provider&&(void 0===t.oauthPosition?null===no||no.seed===t.seed:t.oauthPosition===e))?.alias??null},[tv,tz,t4,no]),nu=ez||eD,nh=e?.id;ef.current=nl,eg.current=eF,ex.current=tq;let np=(0,s.useRef)(!0);np.current=!tD;let nm=(0,s.useRef)(!1);(0,s.useEffect)(()=>{ez&&!nm.current&&(ev.current+=1),nm.current=ez},[ez]),(0,s.useEffect)(()=>()=>{ev.current+=1},[]),(0,s.useEffect)(()=>{eh(e=>[...function(e){if(!e)return[];try{let t=JSON.parse(window.localStorage.getItem(pn(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[]}}(nh),...e.filter(e=>null===e.anchorEntryId&&e.sessionId===nh)])},[nh]),(0,s.useEffect)(()=>{let e=tq.current;e&&ep.current.some(t=>null===t.anchorEntryId&&t.sessionId===e)&&eh(t=>{let n=!1,r=[];for(let s of t){if(null!==s.anchorEntryId||!s.intent||s.sessionId!==e){r.push(s);continue}let a=function(e,t,n){let r=Math.min(t.length,n.length),s=0;if(null!==e.baseEntryId){let t=n.indexOf(e.baseEntryId);if(-1===t||t>=r)return{kind:"drop"};s=t+1}let a=0;for(let i=s;i<r;i++)if(rP(t[i])===e.identity&&(a+=1)===e.occurrence)return{kind:"entry",entryId:n[i]};return null}(s.intent,nl,eF);if(null===a){r.push(s);continue}n=!0,"drop"!==a.kind&&("working"===s.tag&&[...t,...r].some(e=>"working"===e.tag&&e.anchorEntryId===a.entryId)||r.push({id:s.id,anchorEntryId:a.entryId,sticker:s.sticker,text:s.text,tag:s.tag,sessionId:s.sessionId}))}return n?(pr(e,r),r):t})},[nl,eF,tq]);let nf=(0,s.useRef)(null);(0,s.useEffect)(()=>{let e=tq.current,t=nf.current;if(nf.current=e?{sessionId:e,entryIds:eF}: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=[],s=Math.min(n.length,t.length);for(let a=e.length;a<s;a++){let e=n[a];"assistant"===e.role&&"web6"===e.provider&&e.model===r_&&r.push(t[a])}return r}(t.entryIds,eF,nl),r=ew();if(0===n.length||!r)return;let s=sP(e,"web6",void 0)?.alias??null;for(let e of n)ep.current.some(t=>t.anchorEntryId===e)||eS(s,"done",r,{kind:"entry",entryId:e})},[eF,nl,tq,ew,eS]);let ng=ez&&tO?.kind==="running_tools"&&tO.tools.length>0&&tO.tools.every(e=>"wait"===e.name),nx=eP||o,{hideThinkingBlock:nv}=(Z=t??e?.cwd??null,X=rx(),(0,s.useEffect)(()=>{rg(Z).catch(()=>{})},[Z]),X),ny=(0,s.useMemo)(()=>({hideThinking:nv}),[nv]);(0,s.useEffect)(()=>{var e;if(!tE||ec.current===tE.id)return;ec.current=tE.id;let t=ew();if(!t)return;eb.current=t.turn;let n=eO.streamingMessage?.role==="assistant"?eO.streamingMessage:null,r=rA(ef.current,n,tv?.provider,tv?.modelId);eN("select"===(e=tE.method)||"ask"===e||"form"===e?"choice":"approval",t,r.provider,r.credentialId,r.model)},[tE,eO.streamingMessage,tv?.provider,tv?.modelId,ew,eN]),(0,s.useEffect)(()=>{if(Y)return x=nu?tZ:null,()=>void(x=null)},[Y,nu,tZ]),(0,s.useEffect)(()=>{A?.(nu)},[A,nu]),(0,s.useEffect)(()=>()=>A?.(!1),[A]),(0,s.useEffect)(()=>{_?.(ng)},[ng,_]),(0,s.useEffect)(()=>()=>_?.(!1),[_]),(0,s.useEffect)(()=>{O?.(null!==tE)},[O,tE]),(0,s.useEffect)(()=>()=>O?.(!1),[O]);let{main:nb,process:nw}=(0,s.useMemo)(()=>(function(e,t,n={}){let r=[],s=[],a=-1,i=null,l=(e,t,n)=>{if(0===t.length)return;let a=(i&&i.anchorIdx===e||(i={anchorIdx:e,entries:[],messageCount:0,toolCallCount:0},s.push(i)),i),l=r.length-1;for(let e of t)a.entries.push({...e,afterMainIndex:l});a.messageCount+=t.length,a.toolCallCount+=n},o=tr(e),c=new Map,d=(e,t)=>{let n=c.get(e)??0;c.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&&d(e.idx,e.blocks)};for(let s of t){if("answer"===s.kind){r.push(s);continue}if("process"===s.kind){l(s.anchorIdx,s.entries,s.toolCallCount);continue}let t=e[s.idx];if(!t)continue;if("user"===t.role){u(),a=s.idx,r.push(s);continue}if(tu(t)){r.push(void 0!==s.anchorIdx||a<0?s:{...s,anchorIdx:a});continue}if("assistant"!==t.role){"toolResult"!==t.role&&null===to(t)&&0>th(e,s.idx)&&l(a,[{idx:s.idx}],0);continue}let i=e5(t,n);if(e4(t,n)&&e8(e,s.idx)){let e=i.flatMap(e=>e.blocks);l(a,[{idx:s.idx}],e6(e)),o.collect(s.idx,e);continue}let c=!1;for(let e of i){if("answer"===e.kind){d(s.idx,e.blocks),c=!0;continue}l(a,[{idx:s.idx,blocks:e.blocks}],e6(e.blocks)),o.collect(s.idx,e.blocks)}!c&&e4(t,n)&&d(s.idx,[])}return u(),{main:r,process:s}})(nl,function(e,t={}){let n=-1;for(let t=e.length-1;t>=0;t--)if(tg(e[t])){n=t;break}let r=[];for(let s=0;s<e.length;){if(!tg(e[s])){r.push({kind:"message",idx:s}),s+=1;continue}let a=s,i=a+1;for(;i<e.length&&!tg(e[i]);)i+=1;if((t.sessionBusy||t.isStreaming)&&i===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,i)){for(let e=a;e<i;e++)r.push({kind:"message",idx:e});s=i;continue}for(let n of(r.push({kind:"message",idx:a}),function(e,t,n,r){let s=[],a=[],i=0,l=[],o=0,c=0,d=tr(e.slice(t+1,n)),u=()=>{0!==a.length&&(s.push({kind:"process",anchorIdx:t,idx:a[0].idx,groupIndex:c++,entries:a,messageCount:a.length,toolCallCount:i,turnHasAnswer:!1}),a=[],i=0)},h=(e,n)=>{u(),s.push({kind:"answer",anchorIdx:t,idx:e,runIndex:o++,blocks:d.attach(n),precedingBlocks:l}),l=[]};for(let o=t+1;o<n;o++){let n=e[o];if("assistant"!==n.role){if(null!==to(n)||th(e,o)>=0)continue;if(tu(n)){u(),s.push({kind:"message",idx:o,anchorIdx:t});continue}"toolResult"!==n.role&&a.push({idx:o});continue}let c=e5(n,r);if(e4(n,r)&&e8(e,o)){let e=c.flatMap(e=>e.blocks);for(let t of(a.push({idx:o}),i+=e6(e),d.collect(o,e),c))"process"===t.kind&&l.push(...t.blocks);continue}let p=c.reduce((e,t)=>"answer"===t.kind?e+1:e,0);for(let e of c){if("answer"===e.kind){h(o,e.blocks);continue}for(let t of(a.push(p>0?{idx:o,blocks:e.blocks}:{idx:o}),i+=e6(e.blocks),d.collect(o,e.blocks),e.blocks))l.push(t)}0===p&&e4(n,r)&&h(o,[])}u();let p=d.takeRemaining();p&&s.push({kind:"answer",anchorIdx:t,idx:p.idx,runIndex:o++,blocks:p.blocks,precedingBlocks:[]});let m=s.some(e=>"answer"===e.kind);for(let e of s)"process"===e.kind&&(e.turnHasAnswer=m);return s}(e,a,i,{hideThinking:t.hideThinking})))r.push(n);s=i}return r}(nl,{sessionBusy:nu,isStreaming:eO.isStreaming,hideThinking:ny.hideThinking}),ny),[nl,nu,eO.isStreaming,ny]),nk=(0,s.useMemo)(()=>(function(e,t,n=[]){let r,s,a,i,l,{atCompaction:o}=(r=-1,n.forEach((e,t)=>{"user"===e.role&&(r=t)}),s=n.slice(0,r+1).flatMap(iS),a=n.slice(r+1).flatMap(iS),i=t.findIndex(e=>"user"===e.role),-1===(l=0===a.length?-1:e.findIndex(e=>"answer"===e.kind&&(-1===i||e.idx<i)))?{continuing:null,atCompaction:[...s,...a]}:{continuing:{position:l,calls:a},atCompaction:s});if(0===o.length)return null;let c=-1;t.forEach((e,t)=>{"custom"===e.role&&"compaction"===e.customType&&(c=t)});let d=e.findIndex(e=>e.idx>c);return{position:-1===d?e.length:d,calls:o}})(nb,nl,tj?.messages),[nb,nl,tj]),[nj,nS]=(0,s.useState)(h3),{startIndex:nC,endIndex:nN,hasLater:nT}=h7(nb.length,nj),nI=null!==nj.end&&nT,nM=(0,s.useRef)(nb.length);nM.current=nb.length;let nE=(0,s.useRef)(null),n$=(0,s.useRef)(null),nR=(0,s.useRef)(null);(0,s.useEffect)(()=>{null!==nj.end&&nj.end>=nb.length&&nS(e=>({count:e.count,end:null}))},[nj.end,nb.length]),(0,s.useEffect)(()=>{let e=nE.current,t=tJ.current;if(!e||!t)return;let n=new IntersectionObserver(e=>{e[0]?.isIntersecting&&(nR.current=t.scrollHeight-t.scrollTop,nS(e=>(function(e,t=50){return{...e,count:e.count+t}})(e)))},{root:t,threshold:0});return n.observe(e),()=>n.disconnect()},[nj,nb.length,tJ]),(0,s.useEffect)(()=>{if(null==nR.current)return;let e=tJ.current;if(e){var t;t=e.scrollHeight,e.scrollTop=Math.max(0,t-nR.current),nR.current=null}},[nj.count,tJ]),(0,s.useEffect)(()=>{let e=n$.current,t=tJ.current;if(!e||!t)return;let n=new IntersectionObserver(e=>{e[0]?.isIntersecting&&nS(e=>(function(e,t,n=50){if(null===t.end)return t;let{startIndex:r,endIndex:s}=h7(e,t),a=s+n;return a>=e?{count:e-r,end:null}:{count:a-r,end:a}})(nM.current,e))},{root:t,threshold:0});return n.observe(e),()=>n.disconnect()},[nj,nb.length,tJ]);let[nL,nP]=(0,s.useState)(null),[nA,n_]=(0,s.useState)(0),nF=(0,s.useRef)(null),nz=(0,s.useCallback)(e=>{tU(),nF.current=e,nP(null),nS(t=>h9(nM.current,e,t)),n_(e=>e+1)},[tU]);(0,s.useLayoutEffect)(()=>{let e=nF.current,t=tJ.current;if(null===e||!t)return;let n=t.querySelector(`[data-chat-item="${e}"]`);if(!n)return;nF.current=null;let r=document.createRange();r.selectNodeContents(n),t.scrollTop+=r.getBoundingClientRect().top-t.getBoundingClientRect().top-24,nP(e)},[nA,nj,nb,tJ]),(0,s.useEffect)(()=>{if(null===nL)return;let e=setTimeout(()=>nP(null),1800);return()=>clearTimeout(e)},[nL]);let nD=(0,s.useCallback)(()=>{(0,a.flushSync)(()=>nS(h3));let e=tJ.current;e&&(e.scrollTop=e.scrollHeight)},[tJ]),nW=(0,s.useCallback)(()=>{nI&&nD(),tW()},[nI,nD,tW]),nH=(0,s.useRef)(null),[nU,nB]=(0,s.useState)(!1);(0,s.useEffect)(()=>{if(!q||nH.current===q.id||q.sessionId!==e?.id||eP||0===nl.length)return;nH.current=q.id,V?.(q.id);let t=eF.indexOf(q.entryId);if(t<0)return void nB(!0);let n=0;for(let e=0;e<nb.length;e++){let r=nb[e].idx;if(r>t||(n=e,r===t))break}nz(n)},[q,e?.id,eP,nl.length,eF,nb,nz,V]),(0,s.useEffect)(()=>{if(!nU)return;let e=setTimeout(()=>nB(!1),6e3);return()=>clearTimeout(e)},[nU]);let[nq,nV]=(0,s.useState)(!1),[nK,nJ]=(0,s.useState)(0),nG=(0,s.useMemo)(()=>nq?nb.map(e=>(function(e,t){if("answer"===e.kind)return ty(e.blocks);let n=t[e.idx];return n&&"content"in n?ty(n.content):""})(e,nl).toLowerCase()):ps,[nq,nb,nl]),nZ=(0,s.useCallback)(e=>{tU(),nS(t=>h9(nM.current,e,t))},[tU]),nX=(0,s.useCallback)(()=>nV(!1),[]);(0,s.useEffect)(()=>{if(!Y)return;let e=e=>{if(e.defaultPrevented||e.isComposing||e.altKey||e.shiftKey||!(e.ctrlKey||e.metaKey)||"f"!==e.key.toLowerCase())return;let t=tJ.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(),nV(!0),nJ(e=>e+1))};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[tJ,Y]);let n2=(0,s.useMemo)(()=>{let e=[];return nb.forEach((t,n)=>{if("message"!==t.kind)return;let r=pt(nl[t.idx]);null!==r&&e.push({item:n,text:r})}),e},[nb,nl]),n4=`${nC}:${nN}`,n8=eF.length>0?eF[eF.length-1]:null,[n5,n6]=(0,s.useState)(null),n3=(0,s.useRef)(!1);(0,s.useEffect)(()=>{n3.current||!tk||eP||!e?.id||(n3.current=!0,nu||!n8||!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}(nl)||function(e){try{return window.localStorage.getItem(pa(e))}catch{return null}}(e.id)!==n8&&n6(n8))},[tk,eP,e?.id,nu,n8,nl]);let n7=(0,s.useCallback)(()=>{e?.id&&n5&&function(e,t){try{window.localStorage.setItem(pa(e),t)}catch{}}(e.id,n5),n6(null)},[e?.id,n5]),n9=null!==n5&&n5===n8&&!nu&&!nI,re=tw?[tw.sessionId,tw.sessionFile??"",tw.sessionName??"",tw.userMessages,tw.assistantMessages,tw.toolCalls,tw.toolResults,tw.totalMessages,tw.tokens.input,tw.tokens.output,tw.tokens.cacheRead,tw.tokens.cacheWrite,tw.tokens.total,tw.cost??0,tw.totalActiveMs??0].join("|"):null,rt=(0,s.useRef)(tw);rt.current=tw,(0,s.useEffect)(()=>{v?.(rt.current)},[re,v]),(0,s.useEffect)(()=>()=>{v?.(null)},[v]);let rn=tt?`${tt.percent??"null"}|${tt.contextWindow}|${tt.tokens??"null"}`:null,rr=(0,s.useRef)(tt);rr.current=tt,(0,s.useEffect)(()=>{b?.(rr.current)},[rn,b]),(0,s.useEffect)(()=>()=>{b?.(null)},[b]),(0,s.useEffect)(()=>{w?.(tT)},[w,tT]),(0,s.useEffect)(()=>()=>{w?.([])},[w]);let{regular:rs,lab:ra}=(0,s.useMemo)(()=>(function(e){let t=[],n=[];for(let s of e){var r;((r=s.key).startsWith(dl)&&null!==dc(r)?n:t).push(s)}return{regular:t,lab:n}})(tP),[tP]),ri=e?.id??null;(0,s.useEffect)(()=>{k?.(ri,ra)},[k,ri,ra]),(0,s.useEffect)(()=>()=>{k?.(null,[])},[k]);let{isDragOver:rl,handleDragEnter:ro,handleDragOver:rc,handleDragLeave:rd,handleDrop:ru}=function(e){let[t,n]=(0,s.useState)(!1),r=(0,s.useRef)(0),a=(0,s.useCallback)(e=>{Array.from(e.dataTransfer.items).some(e=>"file"===e.kind)&&(e.preventDefault(),r.current+=1,n(!0))},[]),i=(0,s.useCallback)(e=>{Array.from(e.dataTransfer.items).some(e=>"file"===e.kind)&&e.preventDefault()},[]);return{isDragOver:t,handleDragEnter:a,handleDragOver:i,handleDragLeave:(0,s.useCallback)(()=>{r.current-=1,r.current<=0&&(r.current=0,n(!1))},[]),handleDrop:(0,s.useCallback)(t=>{t.preventDefault(),r.current=0,n(!1),e(Array.from(t.dataTransfer.files))},[e])}}((0,s.useCallback)(e=>{nu||m?.current?.addAttachments(e)},[nu,m])),rh=(0,s.useMemo)(()=>{var e;return e=tj?.messages,e&&e.length>0?[...e,...nl]:nl},[tj,nl]),rp=(0,s.useMemo)(()=>{let e=new Map;for(let t of rh)"toolResult"===t.role&&e.set(t.toolCallId,t);return e},[rh]),rm=(0,s.useMemo)(()=>{let e,t,n,r,s,a,i,l,o,c,d;return e=new Map,t=new Map,n=new Map,r=new Map,s=new Map,a=new Map,i=new Map,l=(e,r,s)=>{let a=n.get(e);a&&r&&t.set(a,{status:r,order:s})},o=new Set,c=(e,t)=>{let r=t?n.get(t):void 0,a=im(e.status);if(!r||o.has(r)||"completed"!==a&&"failed"!==a&&"aborted"!==a)return;o.add(r);let i=ip(e);null!==i&&s.set(r,i)},d=(e,t,r)=>{let s=t?n.get(t):void 0,a=ip(e);s&&"number"==typeof r&&null!==a&&"running"===im(e.status)&&i.set(s,Math.max(i.get(s)??-1/0,r-a))},rh.forEach((t,s)=>{if("assistant"===t.role){for(let e of t.content??[]){if("toolCall"!==e.type||"task"!==e.toolName)continue;let t=rp.get(e.toolCallId);if(t)for(let s of ix(e,t)??[])n.set(s.agentId,s.key),"number"==typeof t.timestamp&&r.set(s.key,t.timestamp)}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(ig(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=ih(t.assignmentId),s=r?.split("#")??[];if(s.length<3)return null;let a=s[s.length-1],i=s.slice(1,-1).join("#");return/^\d+$/.test(a)&&i?{key:`${i}#${a}`,record:{verdict:n,attempt:"number"==typeof t.attempt?t.attempt:null,reason:ih(t.reason)}}:null}(t);if(!n)return;let r=e.get(n.key)??[];r.push({...n.record,order:s,at:"number"==typeof t.timestamp?t.timestamp:null}),e.set(n.key,r);return}if("wait"===t.toolName){let e=new Set;for(let r of iu(t.details?.jobs)){if("task"!==r.type)continue;let a=ih(r.id);if(a&&l(a,im(r.status),s),c(r,a),d(r,a,t.timestamp),a&&"running"===im(r.status)){let t=n.get(a);t&&e.add(t)}}for(let t of e)for(let n of e){if(t===n)continue;let e=a.get(t);e||a.set(t,e=new Set),e.add(n)}}return}if("custom"===t.role&&"async-result"===t.customType){for(let e of ig(t.content).matchAll(iv)){let t=Object.fromEntries([...e[1].matchAll(iy)].map(e=>[e[1],e[2]]));t.id&&l(t.id,im(t.status),s)}for(let e of iu(t.details?.jobs))"task"===e.type&&c(e,ih(e.jobId))}}),{verdicts:e,runs:t,latestByAgent:n,spawnedAt:r,durations:s,parallelWith:a,runStartedAt:i}},[rh,rp]),rf=(0,s.useMemo)(()=>({ledger:rm,subagents:tT,toolResults:rp,onOpenPanel:j,sessionId:e?.id??null,cwd:e?.cwd??t??void 0,onOpenMaker:M,selectedMaker:E}),[rm,tT,rp,j,e?.id,e?.cwd,t,M,E]),rv=(0,s.useMemo)(()=>{let e=new Set,t=[];for(let n=nl.length-1;n>=0;n-=1){let r=pt(nl[n]);if(!(!r||e.has(r))&&(e.add(r),t.push(r),t.length>=50))break}return t.reverse()},[nl]),ry=(0,s.useMemo)(()=>tH(nl,rp,tI,tj?.todoPhases??null),[nl,rp,tI,tj]),rb=(0,s.useMemo)(()=>c3(eO.streamingMessage).join("|"),[eO.streamingMessage]),rw=(0,s.useMemo)(()=>JSON.stringify(c6(eO.streamingMessage)),[eO.streamingMessage]),rk=(0,s.useMemo)(()=>JSON.stringify(c9(eO.streamingMessage)),[eO.streamingMessage]),rj=(0,s.useMemo)(()=>(function(e,t,n=[],r=[],s=[]){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 s=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:s})}return t}(e),i=[],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 s=c3(r),c=c9(r,a);if(0===s.length&&0===c.length||o<0)continue;let d=c6(r),u=l.get(o);u||(u={index:o,entryId:t[o],taskToolCallIds:[],characterSummons:[],peerSends:[]},l.set(o,u),i.push(u)),u.taskToolCallIds=[...u.taskToolCallIds,...s],u.characterSummons=[...u.characterSummons,...d],u.peerSends=[...u.peerSends,...c]}if(n.length>0||s.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),i.push(e));let o=new Set(e.taskToolCallIds);e.taskToolCallIds=[...e.taskToolCallIds,...n.filter(e=>!o.has(e))];let c=new Set(e.characterSummons.map(e=>`${e.toolCallId} ${e.name??""}`));e.characterSummons=[...e.characterSummons,...r.filter(e=>!c.has(`${e.toolCallId} ${e.name??""}`))];let d=new Set(e.peerSends.map(e=>e.toolCallId));e.peerSends=[...e.peerSends,...s.filter(e=>!d.has(e.toolCallId))]}}return i.sort((e,t)=>e.index-t.index)})(nl,eF,rb.length>0?rb.split("|"):[],JSON.parse(rw),JSON.parse(rk)),[nl,eF,rb,rw,rk]),rS=e?.id??tq.current??void 0,rC=(et=dn(Q=(0,s.useMemo)(()=>({sessionId:rS,sessionProvider:tv?.provider,turns:rj,messages:nl,subagents:tT}),[rS,tv?.provider,rj,nl,tT])),en=di(Q),(0,s.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}([...et,...en])),[et,en])),rT=tz&&0===nl.length&&!eO.isStreaming&&!nu,rI=(0,s.useMemo)(()=>nl.filter(e=>"assistant"===e.role).length,[nl]),rM=function(e,t){let n=(0,s.useRef)(new Map),r=(0,s.useMemo)(()=>{if(!e)return n.current=new Map,0;let t=new Map,r=0;return(e.content??[]).forEach((e,s)=>{let a=e9(e);if(null===a)return;let i=te(n.current.get(s),a);t.set(s,{text:a,tokens:i}),r+=i}),n.current=t,r},[e]),a=(0,s.useRef)(r);a.current=r;let i=null!==e,l=e?.timestamp,[o,c]=(0,s.useState)(null);return(0,s.useEffect)(()=>{if(!i)return void c(null);let e=l??Date.now(),t=()=>{let t=(Date.now()-e)/1e3;c(t>=.5?a.current/t:0)};t();let n=setInterval(t,1e3);return()=>clearInterval(n)},[i,l,t]),i?o??0:null}(eO.streamingMessage?.role==="assistant"?eO.streamingMessage:null,rI),rE=(0,s.useMemo)(()=>(function(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if("assistant"!==n.role)continue;let{usage:r,timestamp:s,completedAt:a}=n,i=r?.output??0;if(!(i<=0)&&s&&a&&!(a<=s))return i/((a-s)/1e3)}return null})(nl),[nl]),r$=e?.cwd??t??void 0,rR=tv?eK[`${tv.provider}:${tv.modelId}`]??null:null,rL=tv?eJ[`${tv.provider}:${tv.modelId}`]??null:null,rF=(0,s.useRef)(null),rO=(0,s.useRef)(null),rz=(0,s.useCallback)(()=>{let e=rF.current?.querySelector("textarea");e&&(e.focus({preventScroll:!0}),e.setSelectionRange(e.value.length,e.value.length))},[]);(0,s.useEffect)(()=>(P?.(rz),()=>P?.(null)),[rz,P]),(0,s.useLayoutEffect)(()=>{let e=rO.current,t=e?.closest(".workspace-shell");if(!e||!t)return;let n=e.closest(".chat-pane"),r=tJ.current?.clientHeight??0,s=()=>{let s=Math.ceil(e.getBoundingClientRect().height);s>0&&(n?.style.setProperty("--omp-dock-h",`${s}px`),Y&&t.style.setProperty("--omp-dock-h",`${s}px`));let a=tJ.current;if(!a)return;let i=r-a.clientHeight;r=a.clientHeight,i<=0||a.scrollHeight-a.scrollTop-a.clientHeight-i<=1&&(a.scrollTop+=i)};s();let a=new ResizeObserver(s);return a.observe(e),()=>a.disconnect()},[eP,tJ,Y]);let rD=(0,s.useCallback)((...e)=>(null!==nj.end&&nD(),tY(...e)),[tY,nj.end,nD]),rH=(0,s.useCallback)(async e=>ez?await t6(e)==="accepted"?"followUp":"failed":await rD(e)==="accepted"?"prompt":"failed",[ez,t6,rD]),rU=(0,r.jsx)("div",{ref:rF,"data-chat-composer":"",style:{display:"contents"},children:(0,r.jsx)(hc,{ref:m,sessionId:e?.id??tq.current??void 0,onEnsureSession:tz&&t?na:void 0,onLiveTranscriptPersisted:ni,onSend:rD,onAbort:tZ,onSteer:ez?t5:void 0,onFollowUp:ez?t6:void 0,onPromptWithStreamingBehavior:ez?t3:void 0,isStreaming:nu,model:tv,isAutoModelSelection:tF,modelNames:eU,modelList:eB,modelError:eq,modelScopeWarnings:eV,onModelChange:t0,onMainPresetChange:e||tz?t2:void 0,mainPresetActiveAlias:nd,modelRoles:eG,onRoleModelChange:t1,modelSwitching:tb,onCompact:e||tz?t8:void 0,onAbortCompaction:t7,isCompacting:ts,compactError:td,compactResult:tx,toolPreset:eY,onToolPresetChange:e||tz?nn:void 0,thinkingLevel:eZ,effectiveThinkingLevel:eQ,outputTokensPerSecond:rM??rE,outputSpeedLive:null!==rM,thinkingCeiling:eX,onThinkingLevelChange:e||tz?nr:void 0,fastMode:e0,fastModeBusy:e2,onFastModeToggle:e||tz?e3:void 0,availableThinkingLevels:rR,thinkingLevelMap:rL,retryInfo:e7,deliveryRows:tN,inputHistory:rv,onRecallQueue:t9,onRemoveQueuedMessage:ne,slashCommands:tS,slashCommandsLoading:tC,onLoadSlashCommands:ns,onBuiltinCommand:nt,soundEnabled:z,onSoundToggle:D,onAudioUnlock:B,draftKey:e?.id??(t?`new:${t}`:void 0),cwd:e?.cwd??t,sessionTitle:e?.name,startPlace:rT&&!L?N:void 0,notice:T})}),rB=eO.streamingMessage,rq=(0,s.useMemo)(()=>rB?e5(rB,{isStreaming:!0}):[],[rB]),rV=(0,s.useMemo)(()=>rq.filter(e=>"answer"===e.kind).flatMap(e=>e.blocks),[rq]),rK=(0,s.useMemo)(()=>rq.filter(e=>"answer"!==e.kind).map(e=>e.blocks),[rq]),rJ=rB?.role==="assistant"?rB:null,rG=(0,s.useMemo)(()=>{let e=-1;for(let t=nl.length-1;t>=0;t-=1)if("user"===nl[t].role){e=t;break}let t=e<0?-1:oc(nl,e);return{start:t,blocks:ol(nl,t+1,nl.length),priorCiHeads:ou(nl,rp,t+1),jobNotices:oo(nl,t+1,nl.length)}},[nl,rp]);(0,s.useEffect)(()=>{eR.current=rG.start},[rG.start]);let rY=e?.id;(0,s.useEffect)(()=>{I&&rY&&tk&&!nu&&I(rY,null)},[rY,I,tk,nu]);let rZ=(0,s.useMemo)(()=>l1(rJ?[...rG.blocks,...rJ.content??[]]:rG.blocks,rp,nu,rG.priorCiHeads,r$,rG.jobNotices),[rG,rJ,rp,nu,r$]),rQ=(0,s.useMemo)(()=>nu?{...oi(rG.blocks,rp,r$),span:oh(nl,rG.start+1,nl.length)}:null,[nu,rG,rp,r$,nl]),rX=(0,s.useMemo)(()=>rQ?{...rQ,flow:rZ,latest:!0}:null,[rQ,rZ]),r0=(0,s.useMemo)(()=>{let e=null;if(nu)for(let t of nb)"message"===t.kind&&nl[t.idx]?.role==="user"&&(e=t.idx);return function(e,t,n,r,s,a,i=[]){let l=function(e,t,n){let r=new Map,s=e.filter(e=>"message"===e.kind&&t[e.idx]?.role==="user"&&oc(t,e.idx)===e.idx).map(e=>e.idx),a=null===n?null:oc(t,n),i=new Map;for(let[n,l]of(e.forEach((e,n)=>{"answer"===e.kind&&i.set(oc(t,e.anchorIdx),n)}),i)){if(n===a)continue;let e=s.find(e=>e>n);r.set(l,{from:n+1,to:e??t.length})}return r}(e,t,n),o=-1;for(let e of l.keys())e>o&&(o=e);let c=new Map,d=[],u=0;for(let[e,n]of[...l].sort((e,t)=>e[1].from-t[1].from)){if(ou(t,r,n.from,u,d),u=Math.max(u,n.from),0===n.from&&a){let s=n.to-1;for(;s>=n.from&&tm(i[s]);)s-=1;if(i[s]!==a.throughEntryId)continue;let l=ol(t,n.from,n.to).filter(e=>"toolCall"===e.type&&"task"===e.toolName),h=od(t,r,n.from,n.to);c.set(e,{...a.summary,...h?{remaining:oa(h)}:{},dispatchCalls:l,latest:e===o}),d.push(...a.ciHeads),u=n.to;continue}c.set(e,{...function(e,t,n,r,s,a=[]){let i=ol(e,n,r),l=od(e,t,n,r);return{...oi(i,t,s),remaining:l?oa(l):null,span:oh(e,n,r),flow:l1(i,t,!1,a,s,oo(e,n,r))}}(t,r,n.from,n.to,s,d),latest:e===o})}return c}(nb,nl,e,rp,r$,tj?.openRequest??null,eF)},[nb,nl,rp,r$,nu,tj,eF]),[r1,r2]=(0,s.useState)(null),r4=e?.id??null;(0,s.useEffect)(()=>{r2(null)},[r4]);let r8=null;for(let e of r0.keys())(null===r8||e>r8)&&(r8=e);let r5=("live"===r1?null!==rX:null!==r1&&r0.has(r1))?r1:rX?"live":r8,r6="live"===r5?rX:null===r5?null:r0.get(r5)??null,r3=null!==rX,r7=(0,s.useMemo)(()=>({selected:r5,shown:null!==K,select:e=>{r2(e),J?.()},latestTurn:r3?null:r8,compactedCalls:nk?.calls,onOpenFile:R}),[J,r5,K,r3,r8,nk,R]),r9=null===r5||"live"===r5||r5===r8,se=K&&(0,a.createPortal)((0,r.jsx)(tG.Provider,{value:C??null,children:(0,r.jsx)(iC.Provider,{value:rf,children:(0,r.jsx)(c_,{summary:r6,live:"live"===r5,folded:G,compactedCalls:r9?nk?.calls:void 0,onOpenFile:R})})}),K),st=ez&&(tO?.kind==="running_tools"||(rJ?.content??[]).some(e=>"text"===e.type&&/\S/.test(e.text)||"toolCall"===e.type)),sn=rA(nl,rJ,tv?.provider,tv?.modelId),sr=sn.provider,ss=sn.model,sa=sn.credentialId;(0,s.useEffect)(()=>{if(!st)return;let e=ew();e&&ey.current!==e.turn&&eb.current!==e.turn&&(ey.current=e.turn,eN("working",e,sr,sa,ss))},[st,sr,ss,sa,ew,eN]);let[si,sl]=(0,s.useState)(null),so=(0,s.useCallback)(e=>{sl(e)},[]),sc=(0,s.useMemo)(()=>eW?{role:"bashExecution",command:eW.command,output:"",excludeFromContext:eW.excludeFromContext}:null,[eW]),sd=(0,s.useMemo)(()=>{let e=[ez&&!rB&&tO?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}(tO,er):null,eD&&!eW?er("chat.runningCommand"):null].filter(e=>!!e);return e.length>0?e.join(" \xb7 "):null},[ez,rB,tO,eD,eW,er]);(0,s.useEffect)(()=>{if(!si)return void $?.(null);let e=[],t=[],n=0;if(rB&&rK.length>0){let r=si.messages.length+e.length;for(let s of(e.push(rB),rK))t.push({idx:r,blocks:s}),n+=e6(s)}if(sc&&(t.push({idx:si.messages.length+e.length}),e.push(sc)),0===t.length)return void $?.(sd?{...si,status:sd}:si);let r=-1;for(let e=si.messages.length-1;e>=0;e--)if(tg(si.messages[e])){r=e;break}let s=si.groups.slice(),a=s.length>0?s[s.length-1]:void 0;a&&a.anchorIdx===r?s[s.length-1]={...a,entries:[...a.entries,...t],messageCount:a.messageCount+t.length,toolCallCount:a.toolCallCount+n}:s.push({anchorIdx:r,entries:t,messageCount:t.length,toolCallCount:n}),$?.({...si,groups:s,messages:[...si.messages,...e],status:sd})},[si,rK,rB,sc,sd,$]),(0,s.useEffect)(()=>()=>$?.(null),[$]);let su=rs.filter(e=>"belowEditor"!==e.placement),sh=rs.filter(e=>"belowEditor"===e.placement);return eA?(0,r.jsx)("div",{className:"flex h-full items-center justify-center text-red-400",children:eA}):(0,r.jsxs)("div",{className:"chat-window relative flex h-full min-w-0 flex-col overflow-hidden","aria-busy":nx,"data-empty-start":rT&&!L?"true":void 0,style:{paddingBottom:"env(safe-area-inset-bottom)"},onDragEnter:ro,onDragOver:rc,onDragLeave:rd,onDrop:ru,children:[nx?(0,r.jsx)("div",{className:"absolute inset-0 z-40 cursor-wait",children:(0,r.jsx)("div",{className:"absolute right-3 top-3 bg-bg-raised px-3 py-2 text-sm text-text-muted shadow-sm",role:"status",children:er("chat.loadingSession")})}):null,rl&&!nu&&(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)"},children:(0,r.jsx)("span",{className:"px-3 py-1 text-sm font-medium",style:{background:"var(--bg-raised)",boxShadow:"var(--shadow-float)",borderRadius:"var(--radius-surface)",color:"var(--text)"},children:er("chat.attachFile")})}),tR&&(0,r.jsx)(pp,{request:tR,onInput:t_}),rT&&!L?(0,r.jsx)("div",{className:"flex flex-1 flex-col items-center overflow-y-auto px-4",children:(0,r.jsxs)("div",{className:"chat-empty-start my-auto w-full max-w-[var(--reading-measure)] 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)(ee,{})}),(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.359"]})]}),(0,r.jsxs)("span",{style:{fontSize:11,color:"var(--text-muted)"},children:["omp ",(0,r.jsxs)("span",{style:{color:"var(--text)"},children:["v","19.1.1"]})]})]})]}),r$&&!N&&(0,r.jsxs)("section",{className:"empty-workspace-context","aria-label":er("chat.emptyProjectLabel"),children:[(0,r.jsxs)("div",{className:"empty-workspace-context-text",children:[(0,r.jsx)("span",{className:"empty-workspace-context-kicker",children:er("chat.emptyProjectLabel")}),(0,r.jsx)("strong",{children:tK(r$)||r$}),(0,r.jsx)("code",{title:r$,children:r$}),(0,r.jsx)("p",{children:er("chat.emptyProjectHint")})]}),S&&(0,r.jsx)("button",{type:"button",className:"empty-workspace-context-action",onClick:S,children:er("chat.openSessionList")})]}),(0,r.jsx)(pd,{notices:tM,align:"right"})]})}):(0,r.jsxs)(r.Fragment,{children:[L&&(0,r.jsx)("div",{className:"min-h-0 min-w-0 flex-1 overflow-hidden",children:L}),(0,r.jsxs)("div",{className:"relative min-w-0 flex-1 overflow-hidden","aria-hidden":!!L,style:{display:L?"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:"var(--reading-measure)",margin:"0 auto",display:"flex",flexDirection:"column",alignItems:"flex-end",gap:8},children:[(0,r.jsx)(cW,{open:nq,onClose:nX,containerRef:tJ,index:nG,renderedStart:nC,renderedEnd:nN,contentKey:nl,onReveal:nZ,onProgrammaticScroll:tU,focusRequest:nK,t:er}),nU&&(0,r.jsx)("div",{className:"chat-jump-missing",role:"status",children:er("chat.jumpMissing")}),(0,r.jsx)(pd,{notices:tM,floating:!0,align:"right"})]})}),(0,r.jsx)("div",{ref:tJ,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:"var(--reading-measure)",margin:"0 auto"},children:[(0,r.jsx)(pc,{widgets:su}),(0,r.jsx)(nO,{sessionKey:e?.id??"new",messages:nl,onSend:rH,children:(0,r.jsx)(tG.Provider,{value:C??null,children:(0,r.jsx)(iC.Provider,{value:rf,children:(0,r.jsxs)(cN.Provider,{value:r7,children:[(0,r.jsx)(c1,{utterances:rC,children:(0,r.jsx)(pi,{messages:nl,entryIds:eF,toolResultsMap:rp,modelNames:eU,messageCwd:r$,onOpenFile:R,sessionBusy:nu,isNew:tz,isStreaming:eO.isStreaming,handleFork:tQ,forkingEntryId:tn,handleNavigate:tX,handleEditContent:e$,sessionId:e?.id??tq.current??void 0,main:nb,turnSummaries:r0,process:nw,startIndex:nC,endIndex:nN,sentinelRef:nE,laterSentinelRef:n$,flashItem:nL,t:er,cues:eu,cueFollowRef:np,onProcessLogChange:so})}),!nI&&eO.isStreaming&&eO.streamingMessage&&rV.length>0&&(0,r.jsx)(aC,{message:e1(eO.streamingMessage,rV),sessionId:e?.id??tq.current??void 0,isStreaming:!0,modelNames:eU,cwd:r$,onOpenFile:R}),!nI&&rX&&(0,r.jsx)(cE,{summary:rX,turnKey:"live",live:!0})]})})})}),n9&&(0,r.jsx)(cK,{onDismiss:n7,t:er}),(0,r.jsx)("div",{ref:tV})]})})}),(0,r.jsx)(cH,{questions:n2,containerRef:tJ,layoutKey:n4,onJump:nz,label:er("chat.questionRail")}),(nu&&tD||nI)&&(0,r.jsxs)("button",{type:"button",onClick:nW,"aria-label":er("chat.jumpToBottom"),title:er("chat.jumpToBottom"),style:{position:"absolute",bottom:16,left:"50%",transform:"translateX(-50%)",zIndex:40,display:"flex",alignItems:"center",gap:6,padding:"6px 12px",minHeight:ea?44:void 0,borderRadius:"var(--radius-control)",border:0,background:"var(--bg-raised)",boxShadow:"var(--shadow-float)",color:"var(--text-muted)",fontSize:12,cursor:"pointer"},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"})]}),er("chat.jumpToBottom")]})]})]}),(0,r.jsxs)("div",{ref:rO,className:"relative chat-composer-dock flex min-h-0 flex-col",children:[tE&&(0,r.jsx)("div",{style:{padding:"0 16px"},children:(0,r.jsx)("div",{className:"chat-column-cap",style:{maxWidth:"var(--reading-measure)",margin:"0 auto"},children:(0,r.jsx)(ph,{request:tE,onRespond:tA,onActivity:(e,t)=>void t_(e,t??"activity"),delivery:t$})})}),(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:"var(--reading-measure)",margin:"0 auto"},children:[(0,r.jsx)(cV,{compaction:ta,t:er}),(0,r.jsx)(po,{goal:tB,t:er}),(0,r.jsx)(pc,{widgets:sh}),(ry||rZ.steps.length>0)&&!el&&(0,r.jsx)(hh,{phases:ry,flow:rZ,busy:nu})]})}),G&&!K&&r6&&null!==r5&&!el&&(0,r.jsx)("div",{className:"turn-peek-dock",style:{padding:"0 16px"},children:(0,r.jsx)("div",{className:"chat-column-cap",children:(0,r.jsx)(iC.Provider,{value:rf,children:(0,r.jsx)(cR,{summary:r6,live:"live"===r5,onOpen:()=>r7.select(r5)})})})}),rU,(0,r.jsx)(hu,{statuses:tL})]}),se]})}function po({goal:e,t}){if(!e)return null;let n=!e.enabled,s=void 0!==e.tokenBudget?t("chat.goalBudgetLeft",{left:ro(Math.max(0,e.tokenBudget-e.tokensUsed))}):t("chat.goalTokensUsed",{used:ro(e.tokensUsed)});return(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:8,padding:"5px 10px",border:0,borderRadius:"var(--radius-control)",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:s})]})}function pc({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:0,borderRadius:"var(--radius-surface)",background:"var(--bg-panel)",overflow:"hidden"},children:[(0,r.jsx)("div",{style:{padding:"5px 9px",background:"var(--bg-hover)",color:"var(--text-muted)",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 pd({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,s)=>{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*(s!==e.length-1),overflow:"hidden",borderRadius:"var(--seed-radius-r3)",border:0,background:"var(--bg-subtle)",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 pu({focusKey:e,label:t,labelledBy:n,maxBlockSize:a="min(56dvh, 620px)",onCancel:i,delivery:l,children:o}){let{t:c}=(0,F.s)(),d=(0,s.useRef)(null),u=(0,s.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&&!d.current?.contains(t)?t:null}}return(0,s.useEffect)(()=>{let e=d.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:d,role:"dialog","aria-modal":"false","aria-label":t,"aria-labelledby":n,className:"chat-response-surface",tabIndex:-1,onKeyDown:i?e=>{"Escape"===e.key&&(e.stopPropagation(),i())}: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?c("chat.responseSending"):`${c("chat.responseFailed")}${l.error?` (${l.error})`:""}`}):null,o]})}function ph({request:e,onRespond:t,onActivity:n,delivery:a}){let{t:i}=(0,F.s)(),[l,o]=(0,s.useState)("editor"===e.method?e.prefill??"":""),[c,d]=(0,s.useState)({selected:{},custom:{}}),[u,h]=(0,s.useState)(""),p=(0,s.useRef)(0),m=(0,s.useCallback)(()=>{if("ask"!==e.method||!e.timeout||!n)return;let t=Date.now();t-p.current<1e3||(p.current=t,n(e))},[e,n]);(0,s.useEffect)(()=>{o("editor"===e.method?e.prefill??"":""),h(""),d("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("form"===e.method)return(0,r.jsx)(pu,{focusKey:e.id,label:i("chat.agentQuestion"),delivery:a,children:(0,r.jsx)(dI,{request:e,onRespond:t,onActivity:n,delivery:a},e.id)});if("ask"===e.method){var g;let n=(g=e.questions,g.every(e=>(c.selected[e.id]?.length??0)>0||(c.custom[e.id]?.trim().length??0)>0)),s=()=>{if(n){var r;t(e,{value:(r=e.questions,JSON.stringify({kind:"submit",results:r.map(e=>{let t=c.custom[e.id]?.trim();return{id:e.id,question:e.question,options:e.options.map(e=>e.label),multi:e.multi??!1,selectedOptions:(c.selected[e.id]??[]).map(t=>e.options[t]?.label).filter(e=>void 0!==e),...t?{customInput:t}:{}}})}))})}};return(0,r.jsx)(pu,{focusKey:e.id,label:i("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"},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:i("chat.agentQuestion")}),(0,r.jsx)("div",{style:{marginTop:2,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)"},children:i("chat.agentQuestionHint")}),e.timeout?(0,r.jsx)("div",{style:{marginTop:2,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t3-static)"},children:i("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=c.selected[t.id]??[];return(0,r.jsxs)("section",{style:{paddingTop:20*(0!==n)},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 s=a.includes(n),l=t.recommended===n;return(0,r.jsxs)("button",{type:"button",role:t.multi?"checkbox":"radio","aria-checked":s,onClick:()=>{m(),d(e=>(function(e,t,n){let r=e.selected[t.id]??[];if(t.multi){let s=r.includes(n)?r.filter(e=>e!==n):[...r,n];return{...e,selected:{...e.selected,[t.id]:s}}}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:0,borderRadius:"var(--radius-control)",background:s?"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:0,borderRadius:t.multi?"var(--radius-control)":"50%",background:s?"var(--seed-color-fg-neutral)":"var(--bg-selected)",color:"var(--seed-color-fg-neutral-inverted)",fontSize:"var(--seed-font-size-t2-static)",lineHeight:1},children:s&&(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:s?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}),s&&e.preview&&(0,r.jsx)("span",{style:{display:"block",marginTop:8,padding:"7px 8px",borderRadius:"var(--radius-control)",background:"var(--bg-hover)",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:i("chat.recommended")})]},`${t.id}:${n}`)})}),(0,r.jsx)("input",{value:c.custom[t.id]??"",onChange:e=>{m();let n=e.target.value;d(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&&s()},placeholder:i("chat.customAnswer"),"aria-label":i("chat.customAnswer"),style:{width:"100%",height:36,marginTop:9,padding:"0 10px",border:0,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"},children:[(0,r.jsx)("button",{type:"button",onClick:()=>t(e,{cancelled:!0}),style:{minHeight:36,padding:"0 12px",border:0,borderRadius:"var(--radius-control)",background:"var(--bg-hover)",color:"var(--text-muted)",cursor:"pointer"},children:i("chat.cancel")}),(0,r.jsx)("button",{type:"button",onClick:()=>t(e,{value:JSON.stringify({kind:"chat"})}),style:{minHeight:36,padding:"0 12px",border:0,borderRadius:"var(--radius-control)",background:"var(--bg-hover)",color:"var(--text)",cursor:"pointer"},children:i("chat.chatAboutThis")}),(0,r.jsx)("button",{type:"button",disabled:!n||a?.status==="sending",onClick:s,style:{minHeight:36,padding:"0 14px",border:0,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"?i("chat.responseSending"):i("chat.submitAnswer")})]})]})})}return"plan_review"===e.method?(0,r.jsx)(pu,{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"},children:[(0,r.jsx)("div",{style:{color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontWeight:600},children:i("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)(nJ,{children:e.planContent})}),(0,r.jsxs)("div",{style:{padding:"12px 16px"},children:[(0,r.jsx)("textarea",{value:u,onChange:e=>h(e.target.value),placeholder:i("chat.planFeedback"),"aria-label":i("chat.planFeedback"),style:{width:"100%",minHeight:64,maxHeight:150,padding:"9px 10px",border:0,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:0,borderRadius:"var(--radius-control)",background:"var(--bg-hover)",color:"var(--text)",cursor:"pointer"},children:i("chat.refinePlan")}),(0,r.jsx)("button",{type:"button",onClick:()=>t(e,{value:JSON.stringify({action:"approve"})}),style:{minHeight:36,padding:"0 14px",border:0,borderRadius:"var(--radius-control)",background:"var(--seed-color-bg-neutral-inverted)",color:"var(--seed-color-fg-neutral-inverted)",cursor:"pointer",fontWeight:600},children:i("chat.approvePlan")})]})]})]})}):(0,r.jsx)(pu,{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"},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:i("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:0,background:"var(--bg-hover)",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:0,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:0,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"},children:[(0,r.jsx)("button",{onClick:()=>t(e,{cancelled:!0}),style:{minHeight:36,padding:"0 12px",borderRadius:"var(--radius-control)",border:0,background:"var(--bg-hover)",color:"var(--text-muted)",cursor:"pointer"},children:i("chat.cancel")}),"confirm"===e.method?(0,r.jsx)("button",{onClick:f,style:{minHeight:36,padding:"0 14px",borderRadius:"var(--radius-control)",border:0,background:"var(--seed-color-bg-neutral-inverted)",color:"var(--seed-color-fg-neutral-inverted)",cursor:"pointer",fontWeight:600},children:i("chat.confirm")}):"select"!==e.method?(0,r.jsx)("button",{onClick:f,style:{minHeight:36,padding:"0 14px",borderRadius:"var(--radius-control)",border:0,background:"var(--seed-color-bg-neutral-inverted)",color:"var(--seed-color-fg-neutral-inverted)",cursor:"pointer",fontWeight:600},children:i("chat.submit")}):null]})]})})}function pp({request:e,onInput:t}){let{t:n}=(0,F.s)(),a=(0,s.useRef)(null),i=(0,s.useRef)(!1),l=eV(e.lines);return(0,s.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:0,borderRadius:"var(--radius-surface)",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(i.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=eG[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":" ":eJ[e.key]??null}(n);r&&(n.preventDefault(),n.stopPropagation(),t(e,r))},onInput:n=>{if(i.current||n.nativeEvent.isComposing)return;let r=n.currentTarget.value;n.currentTarget.value="",r&&t(e,r)},onCompositionStart:()=>{i.current=!0},onCompositionEnd:n=>{i.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",background:"var(--bg-panel)"},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:"var(--radius-control)",border:0,background:"var(--bg-hover)",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)(s.Fragment,{children:[(a=`line-${t}`,eK(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)})})]})})}var pm=n(40960),pf=n.n(pm);function pg({sessionId:e,refreshKey:t,compact:n}){let{t:a}=(0,F.s)(),[i,o]=(0,s.useState)(null),[c,d]=(0,s.useState)(!1),[u,h]=(0,s.useState)(null),p=(0,s.useRef)(e);p.current=e;let m=(0,s.useRef)(0);(0,s.useEffect)(()=>{if(!e)return;let t=!1,n=++m.current;return fetch(`/api/agent/${encodeURIComponent(e)}`).then(e=>e.json()).then(r=>{if(t||n!==m.current)return;let s=r.running?r.state?.computerTakeover:null;o(s?{sessionId:e,state:{enabled:!0===s.enabled,available:!0===s.available}}:null),h(null)}).catch(()=>{}),()=>{t=!0}},[e,t]);let f=(0,s.useCallback)(async e=>{let t=p.current;if(t){d(!0),h(null);try{let n=await fetch(`/api/agent/${encodeURIComponent(t)}/computer-takeover`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({enabled:e})}),r=await n.json();if(!n.ok)throw Error("shared_settings"===r.code?a("computerTakeover.shared"):r.error??n.statusText);p.current===t&&(m.current+=1,o({sessionId:t,state:{enabled:!0===r.enabled,available:!0!==r.enabled}}))}catch(e){p.current===t&&h(a("computerTakeover.failed",{error:e instanceof Error?e.message:String(e)}))}finally{d(!1)}}},[a]),g=i&&i.sessionId===e?i.state:null;if(!g||!g.enabled&&!g.available)return null;let x=g.enabled,v=x?a("computerTakeover.active"):a("computerTakeover.allow"),y=u??(x?a("computerTakeover.activeHint"):a("computerTakeover.allowHint"));return(0,r.jsxs)(l.r,{className:`workspace-header-action workspace-takeover${x?` ${pf().active}`:""}`,variant:x?"neutralWeak":"ghost",size:"small",type:"button",disabled:c,"aria-pressed":x,"aria-label":v,title:y,onClick:()=>void f(!x),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:"M5 3l14 7-6 2-2 6-6-15Z"})}),(x||!n)&&(0,r.jsx)("span",{children:v})]})}function px({onPick:e,t}){let[n,a]=(0,s.useState)(""),[i,l]=(0,s.useState)({kind:"idle"}),o=(0,s.useRef)(null),c=n.trim();(0,s.useEffect)(()=>{if(c.length<2)return void l({kind:"idle"});let e=new AbortController;l({kind:"loading"});let t=setTimeout(()=>{fetch(`/api/sessions/search?q=${encodeURIComponent(c)}`,{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()}},[c]);let d=e=>{let t=o.current?.querySelectorAll("button");t&&0!==t.length&&t[Math.max(0,Math.min(t.length-1,e))]?.focus()},u="done"===i.kind?i.data:null,h=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.jsxs)("div",{className:"palette-search-field",children:[(0,r.jsx)(ep,{name:"search"}),(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(),d(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}),(0,r.jsx)("kbd",{"aria-hidden":"true",children:"Ctrl K"})]}),c.length>=2&&(0,r.jsxs)("div",{className:"palette-search-results",role:"region","aria-label":t("palette.searchResults"),"aria-busy":"loading"===i.kind,children:[(0,r.jsxs)("p",{className:"palette-search-status","aria-live":"polite",children:["loading"===i.kind&&t("palette.searching"),"error"===i.kind&&t("palette.searchFailed"),u&&(0===u.hits.length?t("palette.searchEmpty"):t("palette.searchHits",{count:u.hits.length})),h?` \xb7 ${h}`:"",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,s)=>{let a=u.sessions[n.sessionId],i=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(),d(s+("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,i)}),n.snippet.slice(i)]})]},`${n.sessionId}:${n.entryId}`)})})]})]})}var pv=n(50640),py=n(73620);let pb=/^(?:\uFEFF)?---[ \t]*(?:\r\n|\n|\r)/;function pw(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 pk=["tags","categories","keywords","tag","category"];function pj({data:e}){var t;if(!e)return null;let n=Object.entries(e);if(0===n.length)return null;let s="string"==typeof(t=e.title)?t.trim()||null:"number"==typeof t||"boolean"==typeof t?String(t):null,a=pk.find(t=>Array.isArray(e[t])),i=a?e[a].map(pw).filter(Boolean):[],l=n.filter(([e])=>e!==a&&("title"!==e||!s));return(0,r.jsxs)("div",{className:"markdown-frontmatter",children:[s&&(0,r.jsx)("div",{className:"markdown-frontmatter-title",children:s}),i.length>0&&(0,r.jsx)("div",{className:"markdown-frontmatter-tags",children:i.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=pw(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 pS=n(8745);let pC=(0,s.createContext)(null),pN=(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"})}),pT=(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"})}),pI=(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"})}),pM=(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"})}),pE=(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 p$({back:e,title:t,titleTooltip:n,titleRef:s,titleAdornment:a,subtitle:i,subtitleKind:d="text",state:u,viewSwitch:h,actions:p=[],close:m}){let{t:f}=(0,F.s)();return(0,r.jsxs)("header",{className:"panel-header",children:[e&&(0,r.jsx)(l.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)(c.In,{size:"16px",svg:pI})}),(0,r.jsxs)("div",{className:"panel-header-heading",children:[(0,r.jsx)("h2",{className:"panel-header-title",title:n,ref:s,tabIndex:s?-1:void 0,children:t}),a,i&&("path"===d?(0,r.jsx)("span",{className:"panel-header-subtitle is-path",title:i,dir:"rtl",children:(0,r.jsx)("bdi",{dir:"ltr",children:i})}):(0,r.jsx)("span",{className:"panel-header-subtitle",title:i,children:i}))]}),u&&(0,r.jsx)("div",{className:"panel-header-state",children:u}),h&&h.options.length>1&&(0,r.jsxs)(pS.A.Root,{className:"panel-header-switch","aria-label":h.label,value:h.value,onValueChange:e=>h.onChange(e),children:[h.options.map(e=>(0,r.jsxs)(pS.A.Item,{value:e.value,title:e.title,children:[(0,r.jsx)(pS.A.ItemHiddenInput,{}),e.label]},e.value)),(0,r.jsx)(pS.A.Indicator,{})]}),p.length>0&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{className:"panel-header-actions",children:p.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)(l.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)(c.In,{size:"16px",svg:e.icon})},e.id))}),(0,r.jsxs)(o.k.Root,{placement:"bottom-end",strategy:"fixed",children:[(0,r.jsx)(o.k.Trigger,{asChild:!0,children:(0,r.jsx)(l.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)(c.In,{size:"16px",svg:pE})})}),(0,r.jsx)(o.k.Positioner,{children:(0,r.jsx)(o.k.Content,{"aria-label":f("panel.more"),children:(0,r.jsx)(o.k.ScrollArea,{children:(0,r.jsx)(o.k.Group,{children:p.map(e=>(0,r.jsx)(o.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)(o.k.ItemBody,{children:(0,r.jsx)(o.k.ItemLabel,{children:e.label})})},e.id))})})})})]})]}),(0,r.jsx)(pR,{}),m&&(0,r.jsx)(l.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)(c.In,{size:"16px",svg:pM})})]})}function pR({className:e="panel-header-button"}){let{t}=(0,F.s)(),n=(0,s.useContext)(pC);if(!n)return null;let a=t(n.expanded?"panel.restore":"panel.expand");return(0,r.jsx)(l.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)(c.In,{size:"16px",svg:n.expanded?pT:pN})})}let pL="cuelo-html-pick",pP="cuelo-html-pick-exit";function pA(e,t){return"string"==typeof e&&e.length<=t}function p_(e){return"number"==typeof e&&Number.isFinite(e)}function pF({content:e,title:t,picking:n,onExitPick:a,onRequestEdit:i}){let{t:o}=(0,F.s)(),c=(0,s.useRef)(null),d=(0,s.useMemo)(()=>{if(!n)return{nonce:"",srcDoc:e};let t=crypto.randomUUID();return{nonce:t,srcDoc:function(e,t){var n;let r=`<script>${(n=t,`(function(){
21
21
  var NONCE=${JSON.stringify(n)},TYPE=${JSON.stringify(pL)},EXIT=${JSON.stringify(pP)};
22
22
  var host=window.parent;
23
23
  if(document.currentScript)document.currentScript.remove();
@@ -72,7 +72,7 @@ ${w.model??"모델 미확인"} \xb7 ${j}
72
72
  ${h.title}${m?`
73
73
  현재 단계: ${m}`:""}${g?`
74
74
  ${g}`:""}${x?`
75
- ${x}`:""}`,"aria-label":`${S} ${v}, 업무 ${h.title}${m?`, 현재 단계 ${m}`:""}${g?`, ${g}`:""}${x?`, ${x}`:""}, ${d?d.status:u?.status??"미확인"}, 모델 ${w.model??"미확인"}, 추론 ${j}`,"aria-describedby":f&&d?c:void 0,style:{display:"grid",gridTemplateColumns:"minmax(0, 1fr) auto",gap:"4px 8px",width:"100%",marginBottom:8,padding:12,borderRadius:"var(--seed-radius-r2)",background:"var(--bg)",color:"var(--text)",cursor:"pointer",textAlign:"left"},children:[(0,r.jsxs)("span",{style:{display:"flex",alignItems:"center",gap:6,minWidth:0},children:["known"===b.kind?(0,r.jsxs)("span",{className:"subagent-role","data-role-kind":"known","data-role":b.agent,title:`${b.agent} \xb7 ${f9[b.source]}`,children:[(0,r.jsx)("span",{className:"sr-only",children:"역할 "}),b.label]}):(0,r.jsx)("span",{className:"subagent-role","data-role-kind":"unknown",title:"역할 정보가 없는 기록입니다.",children:"역할 미확인"}),(0,r.jsx)("span",{className:"subagent-task-line",style:{minWidth:0},children:h.title})]}),d?(0,r.jsx)("span",{style:{color:f3(d),fontSize:"var(--seed-font-size-t2-static)",fontVariantNumeric:"tabular-nums"},children:d.status}):u?(0,r.jsx)("span",{style:{color:"failed"===u.status?"var(--danger)":"aborted"===u.status?"var(--warning)":"var(--seed-color-fg-neutral-subtle)",fontSize:"var(--seed-font-size-t2-static)",fontVariantNumeric:"tabular-nums"},children:u.status??"미확인"}):(0,r.jsx)("span",{"aria-hidden":"true"}),m&&(0,r.jsxs)("span",{className:"subagent-stage-line",title:`현재 단계: ${m}`,style:{gridColumn:"1 / -1",minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--seed-color-fg-neutral-subtle)",fontSize:"var(--seed-font-size-t2-static)"},children:[(0,r.jsx)("span",{style:{fontWeight:600},children:"현재 단계"})," \xb7 ",m]}),f?.phase&&(0,r.jsxs)("span",{className:"subagent-phase-line",style:{gridColumn:"1 / -1",minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:"var(--seed-font-size-t2-static)",fontVariantNumeric:"tabular-nums"},children:[(0,r.jsx)(o4,{phase:f.phase}),x&&(0,r.jsx)("span",{style:{color:"var(--seed-color-fg-neutral-subtle)"},title:x,children:` \xb7 ${x}`})]}),f&&d&&(0,r.jsx)("span",{className:"subagent-eta-line",style:{gridColumn:"1 / -1",minWidth:0,color:"var(--seed-color-fg-neutral)",fontSize:"var(--seed-font-size-t2-static)",fontVariantNumeric:"tabular-nums"},children:(0,r.jsx)(o7,{snapshot:d,view:f,id:c})}),(0,r.jsxs)("span",{className:"subagent-model-line","data-observed":w.model?w.effort?"both":"model":w.effort?"effort":"none","aria-hidden":"true",style:{gridColumn:"1 / -1"},children:[k,w.modelIsFallback&&(0,r.jsx)("span",{className:"subagent-effort",children:" (대체 모델)"}),(0,r.jsxs)("span",{className:"subagent-effort",children:[" \xb7 ",j]})]}),(0,r.jsxs)("span",{style:{gridColumn:"1 / -1",display:"flex",flexWrap:"wrap",gap:"4px 8px",minWidth:0,color:"var(--seed-color-fg-neutral-subtle)",fontFamily:"var(--font-mono)",fontSize:"var(--seed-font-size-t1-static)"},children:[(0,r.jsx)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:v}),(0,r.jsx)("span",{children:y})]}),(0,r.jsxs)("span",{style:{gridColumn:"1 / -1",display:"flex",flexWrap:"wrap",gap:"4px 10px",color:"var(--seed-color-fg-neutral-subtle)",fontFamily:"var(--font-mono)",fontSize:"var(--seed-font-size-t1-static)",fontVariantNumeric:"tabular-nums"},children:[d?.progress&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("span",{children:["도구 ",d.progress.toolCount]}),(0,r.jsxs)("span",{children:[d.progress.tokens.toLocaleString()," Token"]}),(0,r.jsx)("span",{children:function(e=0){let t=Math.max(0,Math.floor(e/1e3));if(t<60)return`${t}초`;let n=Math.floor(t/60);return n<60?`${n}분${t%60?` ${t%60}초`:""}`:`${Math.floor(n/60)}시간 ${n%60}분`}(d.progress.durationMs)})]}),u&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{children:null===u.messages?"메시지 수 미확인":`메시지 ${u.messages}`}),(0,r.jsxs)("span",{children:[(u.bytes/1024).toFixed(+(u.bytes<10240))," KB"]}),(0,r.jsx)("span",{children:function(e=0){let t=Math.max(0,Date.now()-e);return t<1e4?"방금 전":t<6e4?`${Math.floor(t/1e3)}초 전`:t<36e5?`${Math.floor(t/6e4)}분 전`:t<864e5?`${Math.floor(t/36e5)}시간 전`:`${Math.floor(t/864e5)}일 전`}(u.modified)})]})]})]})})}function gl({title:e,sessionId:t,sessionPath:n,sessionCwd:a,liveSubagents:i,client:l,visible:o=!0,onClose:c,onReturnFocus:d,selection:u,onSelectionChange:h,onReturnToOrigin:p,onOpenFile:m}){let{t:f}=(0,F.s)(),g=(0,s.useMemo)(()=>l??ii(),[l]),[x,v]=(0,s.useState)([]),[y,b]=(0,s.useState)({kind:"loading"}),[w,k]=(0,s.useState)({kind:"loading"}),[j,S]=(0,s.useState)(!1),[C,N]=(0,s.useState)(null),T=h?u??null:C,I=h??N,[M,E]=(0,s.useState)(0),$=(0,s.useRef)(null),R=(0,s.useRef)(null);(0,s.useEffect)(()=>{v([]),b({kind:"loading"}),k({kind:"loading"}),S(!1),N(null)},[t]),(0,s.useEffect)(()=>{if(!o||!t)return;let e=!1,n=!1,r=null,s=async()=>{if(e||n||"visible"!==document.visibilityState)return;n=!0,r=new AbortController;let[s,a]=await Promise.allSettled([g.getLiveSnapshots(t,r.signal),g.getArchive(t,r.signal)]);if(!e&&!r.signal.aborted){if("fulfilled"===s.status)v(s.value.subagents),b(s.value.subagents.length>0?{kind:"ready",data:s.value.subagents}:{kind:"empty",data:[]});else{let e=oI(s.reason);b("unreachable"===e.kind?{kind:"unreachable",message:e.message}:{kind:"error",message:e.message})}if("fulfilled"===a.status)S(!0===a.value.listTruncated),k(a.value.subagents.length>0?{kind:"ready",data:a.value.subagents}:{kind:"empty",data:[]});else{let e=oI(a.reason);k("unreachable"===e.kind?{kind:"unreachable",message:e.message}:{kind:"error",message:e.message})}n=!1}};s();let a=setInterval(()=>void s(),3e3),i=()=>{"visible"===document.visibilityState&&s()};return document.addEventListener("visibilitychange",i),()=>{e=!0,r?.abort(),clearInterval(a),document.removeEventListener("visibilitychange",i)}},[M,g,t,o]);let L=(0,s.useMemo)(()=>(function(e,t){let n=new Map,r=[];for(let s of[...e,...t]){let e=n.get(s.id);if(!e){r.push(s.id),n.set(s.id,s);continue}let[t,a]=ge(s)>=ge(e)?[s,e]:[e,s];n.set(s.id,{...t,assignment:t.assignment??a.assignment,description:t.description??a.description})}return r.flatMap(e=>{let t=n.get(e);return t?[t]:[]})})(i,x),[i,x]),P="ready"===w.kind||"empty"===w.kind?w.data:[],A=(0,s.useMemo)(()=>(function(e,t){let n=new Map(t.map(e=>[e.name,e])),r=new Set,s=e.map(e=>{let t=(function(e){let t=[];if(e.sessionFile){let n=e.sessionFile.split(/[\\/]/).pop()?.replace(/\.jsonl$/i,"");n&&t.push({name:n,match:"session-file"})}return t.some(t=>t.name===e.id)||t.push({name:e.id,match:"name"}),t})(e).find(e=>n.has(e.name)&&!r.has(e.name)),s=t?n.get(t.name):void 0;return s&&r.add(s.name),{key:`live:${e.id}`,identity:s?"live-archive":"live",live:e,...s&&t?{archive:s,archiveMatch:t.match}:{}}});for(let e of t)r.has(e.name)||s.push({key:`archive:${e.name}`,identity:"archive",archive:e});return s})(L,P),[P,L]),_=T?A.find(e=>e.key===T.key)??null:null,O=_&&T?.toolCallId&&_.live?.parentToolCallId!==T.toolCallId?null:_,z=o0({sessionId:t,snapshots:L,client:g,enabled:o&&!T,cwd:a??void 0});if((0,s.useEffect)(()=>{let e=R.current;if(T||!e)return;R.current=null;let t=[...$.current?.querySelectorAll("[data-subagent-key]")??[]].find(t=>t.dataset.subagentKey===e);t?.focus({preventScroll:!1})}),T&&t)return(0,r.jsx)(ga,{sessionId:t,sessionCwd:a,record:O,selection:T,client:g,visible:o,onOpenFile:m,onBack:()=>{I(null),T.origin&&p?p(T.origin):R.current=T.key}});let D=0===A.length&&"loading"===y.kind&&"loading"===w.kind,W=0===A.length&&("empty"===y.kind||0===i.length)&&"empty"===w.kind;return(0,r.jsxs)("section",{ref:$,"aria-label":"Subagent 기록","data-state":D?"loading":W?"empty":"ready",style:{display:"flex",flexDirection:"column",width:"100%",height:"100%",minWidth:0,minHeight:0,overflow:"hidden",background:"var(--bg-panel)",color:"var(--text)"},children:[(0,r.jsx)(p$,{title:e,titleTooltip:n??void 0,subtitle:D||!t?void 0:f("panel.subagentsCount",{count:A.length}),actions:[{id:"refresh",label:f("panel.refresh"),icon:gt,onClick:()=>E(e=>e+1)}],close:c?{label:f("panel.close"),onClick:()=>{c?.(),d?.()}}:void 0}),(0,r.jsxs)("div",{style:{flex:1,minHeight:0,overflowY:"auto",padding:"9px 10px 16px"},children:[t?D?(0,r.jsx)("div",{role:"status",style:{padding:24,color:"var(--text-muted)",textAlign:"center",fontSize:10.5},children:"Subagent 기록 불러오는 중…"}):W?(0,r.jsx)("div",{role:"status",style:{padding:24,color:"var(--text-muted)",textAlign:"center",fontSize:10.5,lineHeight:1.6},children:"이 세션은 아직 Subagent를 실행한 적이 없습니다."}):(0,r.jsx)("div",{role:"list","aria-label":"Subagent 실시간 및 디스크 기록",children:A.map(e=>(0,r.jsx)(gi,{record:e,view:e.live?z.get(e.live.id):void 0,onSelect:()=>I({key:e.key})},e.key))}):(0,r.jsx)("div",{role:"status",style:{padding:24,color:"var(--text-muted)",textAlign:"center",fontSize:10.5},children:"세션을 선택한 뒤 다시 시도하세요."}),!D&&"loading"===y.kind&&(0,r.jsx)("div",{role:"status",style:{marginTop:8,color:"var(--text-muted)",fontSize:9.5},children:"실시간 상태 불러오는 중…"}),!D&&"loading"===w.kind&&(0,r.jsx)("div",{role:"status",style:{marginTop:8,color:"var(--text-muted)",fontSize:9.5},children:"디스크 기록 불러오는 중…"}),"unreachable"===y.kind&&(0,r.jsx)("div",{role:"status",style:{marginTop:8,padding:"7px 9px",borderRadius:"var(--radius-surface)",background:"var(--bg)",color:"var(--text-muted)",fontSize:9.5},children:y.message}),"error"===y.kind&&(0,r.jsx)("div",{role:"alert",style:{marginTop:8,padding:"7px 9px",borderRadius:"var(--radius-surface)",background:"var(--danger-soft)",color:"var(--text)",fontSize:9.5},children:y.message}),"unreachable"===w.kind&&(0,r.jsx)("div",{role:"status",style:{marginTop:8,padding:"7px 9px",borderRadius:"var(--radius-surface)",background:"var(--bg)",color:"var(--text-muted)",fontSize:9.5},children:w.message}),"error"===w.kind&&(0,r.jsx)("div",{role:"alert",style:{marginTop:8,padding:"7px 9px",borderRadius:"var(--radius-surface)",background:"var(--danger-soft)",color:"var(--text)",fontSize:9.5},children:w.message}),j&&(0,r.jsx)("div",{role:"status",style:{marginTop:8,color:"var(--warning)",fontSize:9.5},children:"최근 디스크 기록 60개만 표시합니다."})]})]})}let go=["turn","process","subagents","files","browser"],gc=["efficiency","resource","sidechat","plugins","memory"],gd=new Set(["efficiency","sidechat","resource","browser"]);function gu({activeView:e,onViewChange:t,viewLabels:n,sessionId:s,sessionPath:a,sessionName:i,sessionCwd:d,liveSubagents:u,subagentClient:h,turnSlot:p,processSlot:m,fileSlot:f,browserSlot:g,sideChatSlot:x,resourceSlot:v,efficiencySlot:y,pluginsSlot:b,memorySlot:w,visible:k=!0,onClose:j,closeLabel:S,onReturnFocus:C,expand:N=null,selectedMaker:T,onSelectMaker:I,onReturnToDispatch:M,onOpenFile:E,fileOpen:$=!1,widthReadout:R=null}){let{t:L}=(0,F.s)(),P=gc.includes(e)?[...go,e]:go;return(0,r.jsx)(pC.Provider,{value:N,children:(0,r.jsx)("aside",{className:"auxiliary-deck","aria-label":L("inspector.label"),"data-auxiliary-view":e,"data-expanded":N?.expanded?"true":void 0,children:(0,r.jsxs)(f5.J.Root,{className:"auxiliary-deck-tabs",size:"small",contentLayout:"fill",triggerLayout:"hug",value:e,onValueChange:e=>t(e),children:[(0,r.jsxs)("div",{className:"auxiliary-deck-tabbar",children:[(0,r.jsx)(f5.J.List,{"aria-label":L("inspector.views"),children:P.map(e=>{let t="subagents"===e?u.filter(e=>"pending"===e.status||"running"===e.status).length:0;return(0,r.jsxs)(f5.J.Trigger,{value:e,"aria-label":t>0?`${n[e]} (${L("workbench.runningCount",{count:t})})`:void 0,children:[(0,r.jsx)("span",{className:"auxiliary-deck-tab-label",children:n[e]}),t>0&&(0,r.jsx)(n2.E,{size:"medium",variant:"weak",tone:"neutral","aria-hidden":"true",children:t})]},e)})}),(0,r.jsxs)(o.k.Root,{placement:"bottom-end",strategy:"fixed",children:[(0,r.jsx)(o.k.Trigger,{asChild:!0,children:(0,r.jsx)(l.r,{className:"auxiliary-deck-more",variant:"ghost",size:"small",layout:"iconOnly","aria-label":L("inspector.more"),title:L("inspector.more"),children:(0,r.jsx)(c.In,{size:"16px",svg:(0,r.jsxs)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"1"}),(0,r.jsx)("circle",{cx:"19",cy:"12",r:"1"}),(0,r.jsx)("circle",{cx:"5",cy:"12",r:"1"})]})})})}),(0,r.jsx)(o.k.Positioner,{children:(0,r.jsx)(o.k.Content,{"aria-label":L("inspector.more"),children:(0,r.jsx)(o.k.Group,{children:gc.map(s=>(0,r.jsx)(o.k.Item,{role:"menuitemradio","aria-checked":e===s,onClick:()=>t(s),children:(0,r.jsx)(o.k.ItemBody,{children:(0,r.jsx)(o.k.ItemLabel,{children:n[s]})})},s))})})})]}),(gd.has(e)||"files"===e&&!$)&&(0,r.jsx)(pR,{className:"auxiliary-deck-expand"}),j&&(0,r.jsx)(l.r,{className:"auxiliary-deck-close",variant:"ghost",size:"small",layout:"iconOnly",onClick:()=>{j?.(),C?.()},"aria-label":S??L("inspector.hide"),title:S??L("inspector.hide"),children:(0,r.jsx)(c.In,{size:"16px",svg:(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"})})})}),R]}),(0,r.jsx)(f5.J.Content,{value:"turn",className:"auxiliary-deck-panel",children:p}),(0,r.jsx)(f5.J.Content,{value:"process",className:"auxiliary-deck-panel",children:m}),(0,r.jsx)(f5.J.Content,{value:"efficiency",className:"auxiliary-deck-panel",children:y}),(0,r.jsx)(f5.J.Content,{value:"subagents",className:"auxiliary-deck-panel",children:(0,r.jsx)(gl,{title:n.subagents,sessionId:s,sessionPath:a,sessionCwd:d,liveSubagents:u,client:h,visible:k&&"subagents"===e,selection:T,onSelectionChange:I,onReturnToOrigin:M,onOpenFile:E})}),(0,r.jsx)(f5.J.Content,{value:"files",className:"auxiliary-deck-panel",children:f}),(0,r.jsx)(f5.J.Content,{value:"browser",className:"auxiliary-deck-panel",children:g}),(0,r.jsx)(f5.J.Content,{value:"sidechat",className:"auxiliary-deck-panel",children:x}),(0,r.jsx)(f5.J.Content,{value:"resource",className:"auxiliary-deck-panel",children:v}),(0,r.jsx)(f5.J.Content,{value:"plugins",className:"auxiliary-deck-panel",children:b}),(0,r.jsx)(f5.J.Content,{value:"memory",className:"auxiliary-deck-panel",children:w})]})})})}let gh={state:null,streamDown:!1,frameSize:null,frameTabId:null,hadView:!1};class gp{#e;#t;#n;#r;#s;#a;#i;#l;#o;#c;constructor(e,t){this.#n=new Set,this.#r=new Set,this.#s=gh,this.#a="",this.#i=!0,this.#l=null,this.#o=null,this.getSnapshot=()=>this.#s,this.subscribe=e=>(this.#n.add(e),1===this.#n.size&&(this.#d(),this.#u()),()=>{this.#n.delete(e)&&!(this.#n.size>0)&&(this.#o?.(),this.#o=null,this.#h(),this.#s=gh,this.#a="")}),this.#e=e,this.#t=t}get frameSrc(){return this.#a}watchFrames(e){return this.#r.add(e),this.#a&&e(this.#a),()=>{this.#r.delete(e)}}setVisible(e){e!==this.#i&&(this.#i=e,this.#u())}reconnect(){this.#u()}#d(){if("u"<typeof document)return;let e=()=>this.setVisible("visible"===document.visibilityState);document.addEventListener("visibilitychange",e),this.#o=()=>document.removeEventListener("visibilitychange",e),this.#i="visible"===document.visibilityState}#h(){clearTimeout(this.#c),this.#c=void 0,this.#l?.(),this.#l=null}#u(){this.#h(),this.#i&&0!==this.#n.size&&(this.#l=this.#t(this.#e,{open:()=>this.#p({streamDown:!1}),error:e=>{this.#p({streamDown:!0}),e&&(this.#c=setTimeout(()=>this.#u(),2e3))},message:e=>this.#m(e)}))}#m(e){let t;try{t=JSON.parse(e)}catch{return}if("state"===t.type)return void this.#p({state:t.state});for(let e of(this.#a=`data:image/jpeg;base64,${t.data}`,this.#r))e(this.#a);let{frameSize:n,frameTabId:r}=this.#s;(n?.width!==t.width||n.height!==t.height||r!==t.tabId)&&this.#p({frameSize:{width:t.width,height:t.height},frameTabId:t.tabId,hadView:!0})}#p(e){for(let t of(this.#s={...this.#s,...e},this.#n))t()}}let gm=(e,t)=>{let n=new EventSource(e);return n.onopen=t.open,n.onerror=()=>t.error(n.readyState===EventSource.CLOSED),n.onmessage=e=>t.message(e.data),()=>n.close()},gf=new Map,gg={state:null,streamDown:!1,frameSize:null,frameTabId:null,hadView:!1},gx=()=>gg,gv=["left","middle","right"];function gy(e){return!!e.altKey|2*!!e.ctrlKey|4*!!e.metaKey|8*!!e.shiftKey}function gb({sessionId:e,sessionTitle:t,chrome:n}){let{t:a}=(0,F.s)(),{status:i,state:l,hadView:o,frameSize:c,imageRef:d,bindImage:u,sendInput:h,returnControl:p,selectTab:m,reconnect:f}=function(e){let t,n=((t=gf.get(e))||(t=new gp(`/api/agent/${encodeURIComponent(e)}/browser/events`,gm),gf.set(e,t)),t),{state:r,streamDown:a,frameSize:i,frameTabId:l,hadView:o}=(0,s.useSyncExternalStore)(n.subscribe,n.getSnapshot,gx),c=(0,s.useRef)(null),d=(0,s.useCallback)(e=>{c.current=e,e&&n.frameSrc&&(e.src=n.frameSrc)},[n]);(0,s.useEffect)(()=>n.watchFrames(e=>{c.current&&(c.current.src=e)}),[n]);let u=(0,s.useRef)([]),h=(0,s.useRef)(!1),p=`/api/agent/${encodeURIComponent(e)}/browser`,m=(0,s.useRef)(!1);(0,s.useEffect)(()=>(m.current=!1,()=>{m.current=!0,u.current=[]}),[]),(0,s.useEffect)(()=>{u.current=[]},[l]);let f=(0,s.useCallback)(async()=>{if(!h.current){h.current=!0;try{for(;u.current.length>0&&!m.current;){let e=u.current,t=e[0].tabId,n=1;for(;n<e.length&&n<32&&e[n].tabId===t;)n+=1;let r=e.splice(0,n).map(e=>e.event),s=await fetch(`${p}/input`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tabId:t,events:r})}).catch(()=>null);(!s?.ok||m.current)&&(u.current=[])}}finally{h.current=!1}}},[p]),g=(0,s.useCallback)(e=>{let t=n.getSnapshot().frameTabId;if(!t)return;let r=u.current,s=r.at(-1);"mouse"===e.t&&"move"===e.type&&s?.tabId===t&&"mouse"===s.event.t&&"move"===s.event.type?r[r.length-1]={tabId:t,event:e}:r.push({tabId:t,event:e}),f()},[f,n]),x=(0,s.useCallback)(async()=>{u.current=[];try{let e=await fetch(p,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"return"})});return(await e.json()).result??"failed"}catch{return"failed"}},[p]),v=(0,s.useCallback)(e=>{fetch(p,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"tab",tabId:e})}).catch(()=>{})},[p]),y=(0,s.useCallback)(()=>n.reconnect(),[n]);return{status:a?o?"lost":"connecting":r?"off"===r.status?o?"lost":"off":"none"===r.status?"none":"lost"===r.status?o?"lost":"connecting":"live"===r.status&&l===r.tabId?"live":"connecting":"connecting",state:r,hadView:o,frameSize:i,imageRef:c,bindImage:d,sendInput:g,returnControl:x,selectTab:v,reconnect:y}}(e),[g,x]=(0,s.useState)(null),[v,y]=(0,s.useState)(!1),[b,w]=(0,s.useState)(null),[k,j]=(0,s.useState)(!1),S=(0,s.useRef)(null),C=(0,s.useRef)(!1),N=l?.ownership==="user",T=N&&"live"===i,I=l?.tabs.find(e=>e.id===l.tabId)??null,M="live"===i||"lost"===i||"connecting"===i&&o;(0,s.useEffect)(()=>{if(!g)return;let e=setTimeout(()=>x(null),4e3);return()=>clearTimeout(e)},[g]),(0,s.useEffect)(()=>{let e=d.current;if(!e||!c||c.width<=0)return;let t=new ResizeObserver(()=>w(Math.round(e.getBoundingClientRect().width/c.width*100)));return t.observe(e),()=>t.disconnect()},[c,M,d]);let E=(0,s.useCallback)((e,t)=>{let n=d.current;if(!n||!c)return null;let r=n.getBoundingClientRect();return r.width<=0||r.height<=0?null:{x:Math.min(Math.max((e-r.left)/r.width*c.width,0),c.width),y:Math.min(Math.max((t-r.top)/r.height*c.height,0),c.height)}},[c,d]);(0,s.useEffect)(()=>{let e=S.current;if(!e||!T)return;let t=e=>{let t=E(e.clientX,e.clientY);if(!t)return;e.preventDefault();let n=e.deltaMode===WheelEvent.DOM_DELTA_LINE?40:1;h({t:"wheel",...t,dx:e.deltaX*n,dy:e.deltaY*n,modifiers:gy(e)})};return e.addEventListener("wheel",t,{passive:!1}),()=>e.removeEventListener("wheel",t)},[T,E,h]);let $=(e,t)=>{let n=E(t.clientX,t.clientY);if(!n)return;let r=gy(t);if("move"===e)return void h({t:"mouse",type:e,...n,modifiers:r});let s=gv[t.button];s&&h({t:"mouse",type:e,...n,button:s,clickCount:Math.min(Math.max(t.detail,1),3),modifiers:r})},R=(e,t)=>{t.nativeEvent.isComposing||"Process"===t.key||"Tab"===t.key||(t.ctrlKey||t.metaKey)&&"v"===t.key.toLowerCase()||(t.preventDefault(),h({t:"key",type:e,key:t.key,modifiers:gy(t)}))},L=e=>{let t=e.length>4e5?null:[...e];if(!t||t.length>2e5)return void x("pasteTooLong");let n="";for(let e of t)n.length+e.length>2e3&&(h({t:"text",text:n}),n=""),n+=e;n&&h({t:"text",text:n})},P=async()=>{y(!0);let e=await p();y(!1),x("returned"===e?"returned":"failed"===e?"failed":null)},A="blocked"===g?a("browserPane.blocked"):"returned"===g?a("browserPane.returned"):"failed"===g?a("browserPane.returnFailed"):"pasteTooLong"===g?a("browserPane.pasteTooLong"):null;return(0,r.jsxs)("div",{className:n?"chat-pane browser-pane":"browser-pane is-inspector","data-turn":N?"user":"agent",onPointerDownCapture:n?.onUse,onFocusCapture:n?.onUse,children:[n&&(0,r.jsxs)("div",{className:"chat-pane-head",children:[(0,r.jsx)("span",{className:"chat-pane-title",title:t,children:a("browserPane.title",{title:t})}),n.onShowChat&&(0,r.jsx)("button",{type:"button",className:"browser-pane-button",onClick:n.onShowChat,children:a("workspace.toChat")}),(0,r.jsx)("button",{type:"button",className:"chat-pane-close",onClick:n.onClose,"aria-label":a("workspace.closePane"),title:a("workspace.closePane"),children:(0,r.jsx)(ep,{name:"x",size:14})})]}),n?.narrowNote&&(0,r.jsx)("p",{className:"browser-pane-narrow",children:n.narrowNote}),"none"===i&&(0,r.jsxs)("div",{className:"browser-pane-empty",children:[(0,r.jsx)("strong",{children:a("browserPane.noneTitle")}),(0,r.jsx)("p",{children:a("browserPane.noneHelp")})]}),"off"===i&&(0,r.jsxs)("div",{className:"browser-pane-empty",children:[(0,r.jsx)("strong",{children:a("browserPane.offTitle")}),(0,r.jsx)("p",{children:a("browserPane.offHelp")}),(0,r.jsx)("button",{type:"button",className:"browser-pane-button",onClick:f,children:a("browserPane.reconnect")})]}),"connecting"===i&&!M&&(0,r.jsx)("div",{className:"browser-pane-empty",role:"status",children:(0,r.jsx)("p",{children:a("browserPane.connecting")})}),M&&(0,r.jsxs)(r.Fragment,{children:["lost"!==i&&(0,r.jsxs)("div",{className:"browser-pane-band","data-turn":N?"user":"agent",children:[(0,r.jsx)("span",{className:"workbench-lamp","data-kind":N?"input":void 0,"aria-hidden":"true"}),(0,r.jsxs)("div",{className:"browser-pane-band-text",role:"status","aria-live":"polite",children:[(0,r.jsx)("strong",{children:N?a("browserPane.stateUser"):a("browserPane.stateAgent")}),(0,r.jsx)("span",{children:A??(N?a("browserPane.stateUserHelp"):a("browserPane.stateAgentHelp"))})]}),N&&(0,r.jsx)("button",{type:"button",className:"browser-pane-button is-primary",onClick:()=>void P(),disabled:v,children:v?a("browserPane.returning"):a("browserPane.return")})]}),(0,r.jsxs)("div",{className:"browser-pane-url",children:[(0,r.jsx)("span",{className:"browser-pane-url-text",title:I?.url,children:I?.url??""}),c&&null!==b&&(0,r.jsx)("span",{className:"browser-pane-scale",children:a("browserPane.scale",{percent:b})}),n&&(n.canSplit||n.enlarged)&&(0,r.jsxs)("button",{type:"button",className:"browser-pane-button is-quiet",onClick:n.onToggleEnlarge,children:[(0,r.jsx)(ep,{name:n.enlarged?"columns-2":"maximize-2",size:13}),n.enlarged?a("browserPane.shrink"):a("browserPane.enlarge")]})]}),"lost"===i&&(0,r.jsxs)("div",{className:"browser-pane-lost",role:"status",children:[(0,r.jsx)("span",{className:"workbench-lamp","data-kind":"off","aria-hidden":"true"}),(0,r.jsxs)("div",{className:"browser-pane-band-text",children:[(0,r.jsx)("strong",{children:a("browserPane.lostTitle")}),(0,r.jsx)("span",{children:a("browserPane.lostHelp")})]}),(0,r.jsx)("button",{type:"button",className:"browser-pane-button",onClick:f,children:a("browserPane.reconnect")})]}),(0,r.jsxs)("div",{className:"browser-pane-scroll",children:[(0,r.jsxs)("div",{className:`browser-pane-view${"lost"===i?" is-stale":""}${k?" is-keyboard-focus":""}`,children:[(0,r.jsx)("img",{ref:u,alt:"",draggable:!1}),(0,r.jsx)("textarea",{ref:S,className:"browser-pane-input","aria-label":a("browserPane.viewLabel",{title:I?.title||t}),readOnly:!T,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",spellCheck:!1,onInput:e=>{if(e.nativeEvent instanceof InputEvent&&e.nativeEvent.isComposing)return;let t=e.currentTarget.value;e.currentTarget.value="",T&&t&&L(t)},onMouseDown:e=>{if(C.current=!0,!T){"live"===i&&x("blocked");return}$("down",e)},onMouseUp:e=>{T&&$("up",e)},onMouseMove:e=>{T&&$("move",e)},onContextMenu:e=>{T&&e.preventDefault()},onKeyDown:e=>{T&&R("down",e)},onKeyUp:e=>{T&&R("up",e)},onCompositionEnd:e=>{T&&e.data&&L(e.data),e.currentTarget.value=""},onPaste:e=>{e.preventDefault();let t=e.clipboardData.getData("text/plain");T&&t&&L(t)},onFocus:()=>{j(!C.current),C.current=!1},onBlur:()=>{C.current=!1,j(!1)}})]}),l&&l.tabs.length>0&&(0,r.jsxs)("div",{className:"browser-pane-tabs",children:[(0,r.jsxs)("div",{className:"browser-pane-tabs-head",children:[(0,r.jsx)("span",{children:a("browserPane.tabs")}),(0,r.jsxs)("label",{className:"browser-pane-follow",children:[(0,r.jsx)("input",{type:"checkbox",checked:l.follow,onChange:e=>m(e.target.checked?null:l.tabId)}),a("browserPane.followTab")]})]}),(0,r.jsx)("ul",{children:l.tabs.map(e=>{let t=e.id===l.tabId,n=e.id===l.agentTabId;return(0,r.jsx)("li",{children:(0,r.jsxs)("button",{type:"button",className:`browser-pane-tab${t?" is-shown":""}`,"aria-current":t?"true":void 0,"aria-label":a("browserPane.tabPick",{title:e.title||e.url}),onClick:()=>m(e.id),children:[(0,r.jsx)("span",{className:"workbench-lamp","data-kind":n?N?"input":void 0:"off","aria-hidden":"true"}),(0,r.jsx)("span",{className:"browser-pane-tab-title",children:e.title||e.url}),(0,r.jsx)("span",{className:"browser-pane-tab-mark",children:[t?a("browserPane.tabViewing"):null,n&&!N?a("browserPane.tabAgent"):null].filter(Boolean).join(", ")})]})},e.id)})})]})]})]})]})}function gw({sessionId:e,inUse:t,onOpen:n}){let{t:a}=(0,F.s)(),[i,l]=(0,s.useState)(!1);return((0,s.useEffect)(()=>{let t,n=!1,r=async()=>{if(t=void 0,n)return;let s=3e3;if("visible"===document.visibilityState)try{let t=await fetch(`/api/agent/${encodeURIComponent(e)}/browser`,{cache:"no-store"}),r=t.ok?await t.json():{};if(n)return;l("user"===r.ownership),!0!==r.available&&(s=15e3)}catch{}n||(t=window.setTimeout(()=>void r(),s))};return r(),()=>{n=!0,clearTimeout(t)}},[e]),i||t)?(0,r.jsxs)("div",{className:"browser-handoff-notice","data-turn":i?"user":"agent",role:"status",children:[(0,r.jsx)("span",{className:"workbench-lamp","data-kind":i?"input":void 0,"aria-hidden":"true"}),(0,r.jsx)("span",{className:"browser-handoff-notice-text",children:a(i?"browserPane.handoffNotice":"browserPane.useNotice")}),(0,r.jsx)("button",{type:"button",className:`browser-pane-button${i?" is-primary":""}`,onClick:n,children:a(i?"browserPane.handoffAction":"browserPane.useAction")})]}):null}var gk=n(1682),gj=n.n(gk);let gS="omp-web:process-log-wrap",gC=new Set,gN=null;function gT(){if(gN)return gN;try{return"scroll"===window.localStorage.getItem(gS)?"scroll":"wrap"}catch{return"wrap"}}function gI(e){gC.add(e);let t=t=>{t.key===gS&&(gN=null,e())};return window.addEventListener("storage",t),()=>{gC.delete(e),window.removeEventListener("storage",t)}}function gM(e){try{window.localStorage.setItem(gS,e),gN=null}catch{gN=e}gC.forEach(e=>e())}function gE({title:e,data:t,onOpenFile:n,focusRequest:a}){let{t:i}=(0,F.s)(),o=t?.groups??[],[c,d]=(0,s.useState)(()=>new Set),u=(0,s.useSyncExternalStore)(gI,gT,()=>"wrap"),h=(0,s.useRef)(null),[p,m]=(0,s.useState)(null),[f,g]=(0,s.useState)(null),x=a&&a.nonce!==p&&t?function(e,t,n){for(let r of e)for(let e of r.entries){let s=t[e.idx];if(s){if("assistant"===s.role){if((e.blocks??s.content).some(e=>"toolCall"===e.type&&e.toolCallId===n))return r.anchorIdx}else if("bashExecution"===s.role&&`bash-${s.timestamp??""}`===n)return r.anchorIdx}}return null}(o,t.messages,a.toolCallId):null;return a&&null!==x&&(m(a.nonce),g(a),c.has(x)&&d(e=>{let t=new Set(e);return t.delete(x),t})),(0,s.useEffect)(()=>{if(!f)return;let e=h.current?.querySelector(`[data-tool-call-id="${CSS.escape(f.toolCallId)}"]`),t=window.matchMedia("(prefers-reduced-motion: reduce)").matches,n=e?.closest(".process-log-body"),r=e&&n&&e.offsetHeight>n.clientHeight?"start":"center";e?.scrollIntoView({block:r,behavior:t?"auto":"smooth"});let s=window.setTimeout(()=>{g(e=>e===f?null:e)},1600);return()=>window.clearTimeout(s)},[f]),(0,r.jsx)(tG.Provider,{value:null,children:(0,r.jsx)(tY.Provider,{value:f,children:(0,r.jsxs)("section",{ref:h,className:`process-log ${gj().root}`,"aria-label":e,"data-output-wrap":u,children:[(0,r.jsx)(p$,{title:`${o.length} ${i(1===o.length?"process.turn":"process.turns")}`,viewSwitch:{label:i("processLog.outputWrap"),value:u,options:[{value:"wrap",label:i("processLog.wrapLines")},{value:"scroll",label:i("processLog.scrollLines")}],onChange:gM}}),(0,r.jsxs)("div",{className:"process-log-body",children:[t?.status?(0,r.jsxs)("p",{className:"process-log-status",role:"status",children:[(0,r.jsx)("span",{className:"process-log-status-pulse","aria-hidden":"true"}),t.status]}):null,0===o.length?(0,r.jsx)("p",{className:"process-log-empty",children:i("process.empty")}):o.map((e,s)=>{let a=c.has(e.anchorIdx),o=function(e){if(!e||"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(" ")).replace(/\s+/g," ").trim();return 0===t.length?null:t.length>72?`${t.slice(0,72)}…`:t}(t?.messages[e.anchorIdx]),u=[`${e.messageCount} ${i(1===e.messageCount?"chat.message":"chat.messages")}`];return e.toolCallCount>0&&u.push(`${e.toolCallCount} ${i(1===e.toolCallCount?"chat.toolCall":"chat.toolCalls")}`),(0,r.jsxs)("article",{className:"process-log-turn","data-process-turn":e.anchorIdx,children:[(0,r.jsxs)(l.r,{className:"process-log-turn-toggle",variant:"ghost",size:"small",layout:"withText","aria-expanded":!a,onClick:()=>d(t=>{let n=new Set(t);return n.has(e.anchorIdx)?n.delete(e.anchorIdx):n.add(e.anchorIdx),n}),title:a?i("chat.expandProcess"):i("chat.collapseProcess"),children:[(0,r.jsx)("span",{className:"process-log-turn-title",children:o??i("chat.processDetails")}),(0,r.jsx)("span",{className:"process-log-turn-meta",children:u.join(" \xb7 ")})]}),!a&&(0,r.jsx)("div",{className:"process-log-entries",children:e.entries.map((s,a)=>{let i=t?.messages[s.idx];return i?(0,r.jsx)(aC,{message:s.blocks?e1(i,s.blocks,{omitUsage:!0}):i,toolResults:t?.toolResults,modelNames:t?.modelNames,cwd:t?.cwd,onOpenFile:n,entryId:t?.entryIds[s.idx],sessionId:t?.sessionId,showTimestamp:!1,recoveredError:e8(t?.messages??[],s.idx)},`process-${e.anchorIdx}-${a}`):null})})]},`turn-${e.anchorIdx}-${s}`)})]})]})})})}let g$=6,gR="omp-btw-log:",gL="omp-btw-log-index";function gP(e){return e.trim().toLowerCase()}function gA(e){return e.map(e=>({q:e.q,a:e.a,at:e.at}))}function g_(e){if(!Array.isArray(e))return[];let t=[],n=0;for(let r of e){if(!r||"object"!=typeof r||"string"!=typeof r.q||"string"!=typeof r.a)continue;let e={q:r.q,a:r.a,at:"number"==typeof r.at&&Number.isFinite(r.at)?r.at:0};t.push(e),n+=e.q.length+e.a.length}for(;t.length>40||n>12e4;){let e=t.shift();if(!e)break;n-=e.q.length+e.a.length}return t}function gF(e){return!!e&&"object"==typeof e&&("QuotaExceededError"===e.name||22===e.code||1014===e.code)}function gO(e,t={}){let n=t.now??Date.now,r=new Map,s=new Set,a=!1,i=[],l=t=>{if(e)try{e.removeItem(t)}catch{}},o=e=>{r.delete(e),s.delete(e),l(gR+e)},c=()=>{let e=new Set,t=[];for(let n of(i.sort((e,t)=>t.updatedAt-e.updatedAt),i))!n.id||e.has(n.id)||(e.add(n.id),t.length<20?t.push(n):o(n.id));i=t},d=()=>{if(!a){if(a=!0,e)try{let t=e.getItem(gL),n=t?JSON.parse(t):[];Array.isArray(n)&&(i=n.flatMap(e=>e&&"object"==typeof e&&"string"==typeof e.id&&e.id?[{id:gP(e.id),updatedAt:"number"==typeof e.updatedAt&&Number.isFinite(e.updatedAt)?e.updatedAt:0}]:[]))}catch{i=[]}c()}},u=e=>{d();for(let t=i.length-1;t>=0;t-=1){if(i[t].id===e)continue;let[n]=i.splice(t,1);return o(n.id),!0}return!1},h=t=>{if(e){try{e.setItem(gL,JSON.stringify(i));return}catch(e){if(!gF(e)||!u(t))return}try{e.setItem(gL,JSON.stringify(i))}catch{}}},p=t=>{let n=gP(t);if(!n)return[];if(s.has(n))return gA(r.get(n)??[]);if(e)try{let t=e.getItem(gR+n);if(t){let e=JSON.parse(t),s=g_(e?.entries);return r.set(n,s),gA(s)}}catch{}return gA(r.get(n)??[])},m=e=>{let t=gP(e);t&&(d(),i=i.filter(e=>e.id!==t),o(t),h(null))};return{read:p,append:(t,a)=>((t,a)=>{let l=gP(t);if(!l)return[];let o=g_(a),p=n();if(r.set(l,gA(o)),d(),(i=i.filter(e=>e.id!==l)).unshift({id:l,updatedAt:p}),c(),h(l),!e)return gA(o);let m=JSON.stringify({updatedAt:p,entries:o});try{return e.setItem(gR+l,m),s.delete(l),gA(o)}catch(e){if(!gF(e)||!u(l))return s.add(l),gA(o)}h(l);try{e.setItem(gR+l,m),s.delete(l)}catch{s.add(l)}return gA(o)})(t,[...p(t),a]),history:(e,t=g$)=>p(e).slice(-Math.max(0,t)).map(({q:e,a:t})=>({q:e,a:t})),clear:m,cleanup:(t,r)=>{if(!t.complete)return;d();let s=new Map;for(let e of t.sessions){if(!e||"string"!=typeof e.id||!e.id)continue;let t=gP(e.id),n="number"==typeof e.modified?e.modified:Date.parse(e.modified);s.set(t,Number.isFinite(n)?n:0)}let a=r?gP(r):null,o=n();for(let e of[...i])if(e.id!==a){if(!s.has(e.id)){m(e.id);continue}o-Math.max(s.get(e.id)??0,e.updatedAt)>6048e5&&m(e.id)}if(!e||"function"!=typeof e.key||"number"!=typeof e.length)return;let c=[];try{for(let t=0;t<e.length;t+=1){let n=e.key(t);if(!n?.startsWith(gR))continue;let r=gP(n.slice(gR.length));s.has(r)||r===a||c.push(n)}}catch{return}for(let e of c)l(e)}}}function gz(){let e=new Map,t=new Map,n=new Map,r=e=>{n.get(e)?.forEach(e=>{e()})};return{read(t){let n=e.get(t);return n?{...n.snapshot}:null},begin(t,n){if(e.has(t))return null;let s=new AbortController;return e.set(t,{snapshot:{sessionId:t,question:n,text:"",model:null},controller:s}),r(t),{controller:s}},ingest(t,n){let s=e.get(t);s&&("d"===n.t?s.snapshot.text+=n.v:"done"===n.t?s.snapshot.text=n.v||s.snapshot.text:"m"===n.t&&(s.snapshot.model=n.v),r(t))},abort(t){let n=e.get(t);return!!n&&(n.controller.abort(),!0)},finish(n,s){e.has(n)&&(e.delete(n),t.set(n,s),r(n))},takeOutcome(e){let n=t.get(e)??null;return n&&t.delete(e),n},subscribe(e,t){let r=n.get(e);return r||(r=new Set,n.set(e,r)),r.add(t),()=>{r.delete(t),0===r.size&&n.delete(e)}}}}class gD extends Error{constructor(e,t,n){super(t),this.kind=e,this.status=n,this.name="SideChatRequestError"}}function gW(e){let t;try{t=JSON.parse(e)}catch{throw new gD("stream","사이드채팅 스트림을 해석할 수 없습니다.")}if(!t||"object"!=typeof t)throw new gD("stream","사이드채팅 스트림 항목이 올바르지 않습니다.");let n=t;if("d"!==n.t&&"done"!==n.t&&"m"!==n.t&&"err"!==n.t||"string"!=typeof n.v)throw new gD("stream","사이드채팅 스트림 항목이 올바르지 않습니다.");return{t:n.t,v:n.v}}class gH{push(e){this.buffer+="string"==typeof e?e:this.decoder.decode(e,{stream:!0});let t=this.buffer.split("\n");return this.buffer=t.pop()??"",t.flatMap(e=>e.trim()?[gW(e)]:[])}finish(){this.buffer+=this.decoder.decode();let e=this.buffer.trim();return this.buffer="",e?[gW(e)]:[]}constructor(){this.decoder=new TextDecoder,this.buffer=""}}async function gU(e){let t=await e.text().catch(()=>"");if(!t)return`HTTP ${e.status}`;try{let e=JSON.parse(t);if("string"==typeof e.error&&e.error)return e.error}catch{}return t}function gB(e=!1){return{minHeight:30,padding:"4px 9px",borderRadius:"var(--radius-control)",background:"var(--bg-hover)",color:e?"var(--text-dim)":"var(--text-muted)",cursor:e?"default":"pointer",fontSize:"var(--seed-font-size-t2-static)",fontWeight:650}}function gq({children:e}){return(0,r.jsx)("div",{className:"side-chat-question",style:{alignSelf:"flex-end",maxWidth:"92%",padding:"8px 10px",color:"var(--text)",whiteSpace:"pre-wrap",overflowWrap:"anywhere",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.55},children:e})}function gV({children:e,streaming:t=!1}){return(0,r.jsxs)("div",{className:`side-chat-answer${t?" is-streaming":""}`,style:{alignSelf:"flex-start",maxWidth:"100%",padding:"8px 10px",color:"var(--text)",overflowWrap:"anywhere",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.58},children:[e?(0,r.jsx)(nJ,{isStreaming:t,children:e}):t?"응답을 기다리는 중…":null,t&&(0,r.jsx)("span",{"aria-hidden":"true",style:{marginLeft:2,color:"var(--accent)"},children:"▍"})]})}function gK({identity:e,status:t,utteranceKey:n,children:s}){let a=s_(e?.sessionId,e?.provider,e?.credentialId,e?.model),i=cQ(a?.alias,t,n);return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",alignItems:"flex-start",gap:5},children:[a&&e?.provider&&(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:9,minHeight:40,marginBottom:2},children:[(0,r.jsx)(sD,{seed:a.seed,size:40,provider:e.provider}),(0,r.jsx)("span",{style:{fontSize:15,fontWeight:600,color:"var(--text)"},children:a.alias})]}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"flex-start",gap:7,minWidth:0,maxWidth:"100%"},children:[s,i&&(0,r.jsx)("img",{src:i.src,alt:i.alt,width:52,height:52,style:{flex:"0 0 auto",objectFit:"contain"}})]})]})}function gJ({title:e,sessionId:t,sessionPath:n,sessionName:a,historyStore:i,flights:l,sessionCensus:o,client:c,visible:d=!0,onClose:u,onReturnFocus:h}){let p,m,f=(0,s.useMemo)(()=>c??function(e=(e,t)=>fetch(e,t),t="/api/sidecars/sidechat/ask"){return{async ask(n){let r;try{r=await e(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionPath:n.sessionPath,question:n.question,history:n.history.slice(-g$)}),signal:n.signal})}catch(e){if(n.signal?.aborted)throw e;throw new gD("unreachable","사이드채팅 사이드카(30143)에 연결할 수 없습니다.")}if(!r.ok)throw new gD("http",await gU(r),r.status);if(!r.body)throw new gD("stream","사이드채팅 스트림을 열 수 없습니다.");let s=r.body.getReader(),a=new gH,i="",l=null,o=e=>{for(let t of e)if(n.onEvent?.(t),"d"===t.t)i+=t.v;else if("done"===t.t)i=t.v||i;else if("m"===t.t)l=t.v;else throw new gD("server",t.v)};try{for(;;){let e=await s.read();if(e.done)break;o(a.push(e.value))}o(a.finish())}catch(e){if(n.signal?.aborted||e instanceof gD)throw e;throw new gD("stream",e instanceof Error?e.message:"사이드채팅 스트림이 중단되었습니다.")}finally{s.releaseLock()}if(!i)throw new gD("empty","사이드채팅이 빈 응답을 반환했습니다.");return{text:i,model:l}}}}(),[c]),g=t?.toLowerCase()??null,[x,v]=(0,s.useState)([]),[y,b]=(0,s.useState)({}),w=g??"",k=y[w]??"",j=(e,t)=>{b(n=>{if((n[e]??"")===t)return n;let r={...n};return t?r[e]=t:delete r[e],r})},[S,C]=(0,s.useState)(0),[N,T]=(0,s.useState)({}),[I,M]=(0,s.useState)({}),[E,$]=(0,s.useState)({}),[R,L]=(0,s.useState)(null),[P,A]=(0,s.useState)(null),[_,F]=(0,s.useState)({}),[O,z]=(0,s.useState)({}),[D,W]=(0,s.useState)({}),H=(0,s.useRef)((p=new Set,m=new Set,{claim:e=>!(!e||p.has(e)||m.has(e))&&(p.add(e),!0),markSent(e){p.delete(e),m.add(e)},release(e){p.delete(e)}})),U=(0,s.useRef)(!0),B=(0,s.useRef)(g),q=(0,s.useRef)(d),V=(0,s.useRef)(null),K=(0,s.useRef)(!1),J=(0,s.useRef)(0),G=(0,s.useRef)(null);B.current=g,q.current=d,(0,s.useEffect)(()=>(U.current=!0,()=>{U.current=!1}),[]),(0,s.useEffect)(()=>{v(g?i.read(g):[])},[i,g]);let Y=(0,s.useRef)(null);(0,s.useEffect)(()=>{L(null),Y.current=null},[g]),(0,s.useEffect)(()=>{if(!d||!g||Y.current===g)return;let e=!0;return fetch(`/api/sessions/${encodeURIComponent(g)}?deferThinking=1&deferMedia=1`,{cache:"no-store"}).then(async e=>{if(!e.ok)throw Error(`HTTP ${e.status}`);return function(e){if(!e||"object"!=typeof e||!("context"in e))return null;let t=e.context;if(!t||"object"!=typeof t||!("messages"in t))return null;let n=t.messages;if(!Array.isArray(n))return null;for(let e=n.length-1;e>=0;e-=1){let t=n[e];if(!t||"object"!=typeof t||!("role"in t)||"assistant"!==t.role)continue;if(!("provider"in t)||"string"!=typeof t.provider||!t.provider)break;let r="credentialId"in t?t.credentialId:void 0,s="model"in t?t.model:void 0;return{provider:t.provider,..."string"==typeof s&&s?{model:s}:{},..."number"==typeof r&&Number.isSafeInteger(r)&&r>0?{credentialId:r}:{}}}return null}(await e.json())}).then(t=>{e&&(Y.current=g,L(t?{...t,sessionId:g}:null))}).catch(()=>{e&&(Y.current=g,L(null))}),()=>{e=!1}},[g,d]),(0,s.useEffect)(()=>{if(!g)return;let e=()=>{if(!U.current||B.current!==g)return;let e=l.takeOutcome(g);if(e){if("aborted"===e.kind)M(t=>({...t,[g]:e.saved?"응답 생성을 중단했습니다. 받은 내용은 현재 세션 기록에 저장했습니다.":"응답 생성을 중단했습니다."}));else if("failed"===e.kind)T(t=>({...t,[g]:[...t[g]??[],{question:e.question,partialAnswer:e.partialAnswer,kind:e.errorKind,message:e.errorMessage}]})),b(t=>(t[g]??"").trim()?t:{...t,[g]:e.question});else if(e.model){let t=e.model;$(e=>({...e,[g]:t}))}v(i.read(g))}else null===l.read(g)&&v(i.read(g));C(e=>e+1)},t=l.subscribe(g,e);return e(),t},[l,i,g]),(0,s.useEffect)(()=>{o&&i.cleanup(o,g)},[i,g,o]),(0,s.useEffect)(()=>{d&&V.current?.focus()},[d,g]),(0,s.useEffect)(()=>{if(!d)return;let e=requestAnimationFrame(()=>{let e=G.current;e&&(e.scrollTop=e.scrollHeight)});return()=>cancelAnimationFrame(e)},[S,g,x.length,d]);let Z=async e=>{if(!g||!n){let e=g??"";M(t=>({...t,[e]:"세션 파일이 준비되지 않았습니다. 기록이 생성된 뒤 다시 시도하세요."}));return}let t=l.begin(g,e);if(!t)return;let{signal:r}=t.controller;M(e=>{let t={...e};return delete t[g],t});try{let t=await f.ask({sessionPath:n,question:e,history:i.history(g),signal:r,onEvent:e=>l.ingest(g,e)});i.append(g,{q:e,a:t.text,at:Date.now()}),l.finish(g,{kind:"done",model:t.model})}catch(n){let t=l.read(g)?.text??"";if(r.aborted){let n=!1;t&&(i.append(g,{q:e,a:t,at:Date.now()}),n=!0),l.finish(g,{kind:"aborted",saved:n})}else{let r=n instanceof gD?n.kind:"unknown",s=n instanceof Error?n.message:String(n);l.finish(g,{kind:"failed",question:e,partialAnswer:t,errorKind:r,errorMessage:s})}}finally{U.current&&q.current&&V.current?.focus()}},Q=async(e,t,n)=>{if(!g)return;let r=`${g}:${t}`;if(H.current.claim(r)){z(e=>({...e,[r]:"sending"})),W(e=>{let t={...e};return delete t[r],t});try{var s,a;let t,i=await fetch(`/api/agent/${encodeURIComponent(g)}`,{cache:"no-store"}),l=null;try{l=await i.json()}catch{}if(!i.ok){if(l&&"object"==typeof l&&"error"in l&&"string"==typeof l.error)throw Error(l.error);throw Error(`HTTP ${i.status}`)}let o=function(e){if(!e||"object"!=typeof e||!("running"in e)||"boolean"!=typeof e.running)return null;if(!e.running)return!1;if(!("state"in e)||!e.state||"object"!=typeof e.state)return null;let t=e.state;return"isStreaming"in t&&"boolean"==typeof t.isStreaming&&"isPromptRunning"in t&&"boolean"==typeof t.isPromptRunning&&"isBashRunning"in t&&"boolean"==typeof t.isBashRunning&&"isCompacting"in t&&"boolean"==typeof t.isCompacting&&"isHandoffRunning"in t&&"boolean"==typeof t.isHandoffRunning?t.isStreaming||t.isPromptRunning||t.isBashRunning||t.isCompacting||t.isHandoffRunning:null}(l);if(null===o)throw Error("메인 세션 실행 상태를 확인할 수 없습니다.");let c=(s=e.q,a=e.a,t=n.trim(),["사이드채팅 문답을 메인 대화에서 이어서 처리해 주세요.","","[사이드채팅 질문]",s,"","[사이드채팅 답변]",a,...t?["","[추가 지시]",t]:[]].join("\n"));await hx(g,{type:o?"steer":"prompt",message:c}),H.current.markSent(r),z(e=>({...e,[r]:"sent"}))}catch(e){H.current.release(r),z(e=>{let t={...e};return delete t[r],t}),W(t=>({...t,[r]:e instanceof Error?e.message:String(e)}))}}},X=()=>{if(g&&null!==l.read(g))return void l.abort(g);let e=k.trim();e&&(j(w,""),Z(e))},ee=N[g??""]??[],et=I[g??""],en=g?l.read(g):null,er=x.length>0||ee.length>0||null!==en,es=en?.model??E[g??""],ea=!g||!n,ei=null!==en,el=!ei&&!ea&&k.trim().length>0,eo=!g||ei,ec=R?.sessionId===g?R:null;return(0,r.jsxs)("section",{className:"side-chat-panel","aria-label":"사이드채팅","aria-busy":null!==en,"data-state":g&&n?en?"streaming":"ready":"unavailable",style:{display:"flex",flexDirection:"column",width:"100%",height:"100%",minWidth:0,minHeight:0,overflow:"hidden",background:"var(--bg-panel)",color:"var(--text)"},children:[(0,r.jsxs)("header",{style:{display:"flex",alignItems:"center",gap:8,minHeight:42,padding:"6px 10px",background:"var(--bg-panel)"},children:[(0,r.jsxs)("div",{style:{minWidth:0,flex:1},children:[(0,r.jsx)("div",{style:{fontSize:"var(--seed-font-size-t3-static)",fontWeight:600},children:e}),(0,r.jsxs)("div",{title:n??void 0,style:{marginTop:2,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-muted)",fontFamily:"var(--font-mono)",fontSize:"var(--seed-font-size-t2-static)"},children:[a||g?.slice(0,8)||"세션 없음",es?` \xb7 ${es}`:""]})]}),(0,r.jsx)("button",{type:"button",onClick:()=>{g&&null===l.read(g)&&(i.clear(g),v([]),T(e=>{let t={...e};return delete t[g],t}),M(e=>({...e,[g]:"현재 세션의 사이드채팅 기록을 비웠습니다."})))},disabled:eo,style:gB(eo),children:"Clear"}),u&&(0,r.jsx)("button",{type:"button",onClick:()=>{u?.(),h?.()},"aria-label":"사이드채팅 닫기",title:"닫기",style:{...gB(),width:32,padding:0},children:(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m4 4 8 8M12 4l-8 8"})})})]}),(0,r.jsxs)("div",{ref:G,"aria-live":"polite",style:{display:"flex",flex:1,minHeight:0,flexDirection:"column",gap:7,overflowY:"auto",padding:"11px 12px 18px"},children:[g&&n?(0,r.jsxs)(r.Fragment,{children:[x.map((e,t)=>{let n=`${e.at}:${t}`,s=`${g}:${n}`,a=O[s],i=P===s;return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:6,marginBottom:5},children:[(0,r.jsx)(gq,{children:e.q}),(0,r.jsx)(gK,{identity:ec,status:"settled",utteranceKey:n,children:(0,r.jsx)(gV,{children:e.a})}),"sent"===a?(0,r.jsx)("span",{role:"status",style:{color:"var(--text-muted)",fontSize:10.5},children:"보냄"}):(0,r.jsxs)(r.Fragment,{children:[!i&&(0,r.jsx)("button",{type:"button","aria-expanded":"false",onClick:()=>A(s),style:{...gB(),alignSelf:"flex-start"},children:"메인에 보내기"}),i&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",alignItems:"flex-start",gap:6},children:[(0,r.jsx)("label",{htmlFor:`side-chat-forward-${t}`,style:{color:"var(--text-muted)",fontSize:10.5},children:"메인에 덧붙일 지시 (선택)"}),(0,r.jsx)("textarea",{id:`side-chat-forward-${t}`,rows:2,value:_[s]??"",onChange:e=>F(t=>({...t,[s]:e.target.value})),style:{width:"100%",minWidth:0,boxSizing:"border-box",resize:"vertical",padding:"7px 8px",borderRadius:"var(--radius-control)",background:"var(--bg-hover)",color:"var(--text)",fontFamily:"var(--seed-font-family)",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.5}}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6},children:[(0,r.jsx)("button",{type:"button",onClick:()=>void Q(e,n,_[s]??""),disabled:"sending"===a,style:gB("sending"===a),children:"sending"===a?"보내는 중…":"메인으로 전송"}),"sending"!==a&&(0,r.jsx)("button",{type:"button",onClick:()=>A(null),style:gB(),children:"취소"})]})]}),D[s]&&(0,r.jsx)("div",{role:"alert",style:{color:"var(--danger)",fontSize:10.5,lineHeight:1.5,overflowWrap:"anywhere"},children:D[s]})]})]},n)}),ee.map((e,t)=>(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:6,marginBottom:5},children:[(0,r.jsx)(gq,{children:e.question}),(0,r.jsxs)(gK,{identity:ec,status:"failed",utteranceKey:`failed:${e.question}:${t}`,children:[e.partialAnswer&&(0,r.jsx)(gV,{children:e.partialAnswer}),(0,r.jsx)("div",{role:"alert","data-error-kind":e.kind,style:{padding:"7px 9px",borderRadius:"var(--radius-surface)",background:"var(--danger-soft)",color:"var(--text)",fontSize:10.5,lineHeight:1.5,overflowWrap:"anywhere"},children:e.message})]})]},`${e.question}:${t}`)),en&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:6,marginBottom:5},children:[(0,r.jsx)(gq,{children:en.question}),(0,r.jsx)(gK,{identity:ec,status:"streaming",utteranceKey:`stream:${en.question}`,children:(0,r.jsx)(gV,{streaming:!0,children:en.text})})]}),!er&&(0,r.jsxs)("div",{style:{margin:"auto 0",padding:16,color:"var(--text-muted)",textAlign:"center",fontSize:11,lineHeight:1.65},children:["현재 세션의 전체 맥락을 보고 답합니다.",(0,r.jsx)("br",{}),"사이드채팅 기록은 부모 세션별로 보관됩니다."]})]}):(0,r.jsxs)("div",{role:"status",style:{margin:"auto 0",padding:16,color:"var(--text-muted)",textAlign:"center",fontSize:11,lineHeight:1.6},children:["세션 기록을 준비하는 중입니다.",(0,r.jsx)("br",{}),"세션 파일이 생성되면 사이드채팅을 사용할 수 있습니다."]}),et&&(0,r.jsx)("div",{role:"status",style:{padding:"7px 9px",color:"var(--text-muted)",fontSize:10.5,lineHeight:1.5},children:et})]}),(0,r.jsxs)("form",{onSubmit:e=>{e.preventDefault(),X()},style:{display:"flex",flexDirection:"column",gap:6,padding:"9px 10px",background:"var(--bg-panel)"},children:[(0,r.jsx)("label",{htmlFor:"side-chat-question",style:{color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontWeight:600},children:"사이드채팅 질문"}),(0,r.jsx)("textarea",{ref:V,id:"side-chat-question",rows:4,value:k,onChange:e=>j(w,e.target.value),onCompositionStart:()=>{K.current=!0},onCompositionEnd:()=>{K.current=!1,J.current=Date.now()},onKeyDown:e=>{if("Enter"!==e.key||e.shiftKey)return;let t=e.nativeEvent,n=Date.now()-J.current<100;if(K.current||t.isComposing||229===t.keyCode||n){n&&e.preventDefault();return}ei||(e.preventDefault(),X())},disabled:ei||ea,placeholder:"질문 입력 — Enter 전송, Shift+Enter 줄바꿈",style:{width:"100%",minWidth:0,minHeight:88,maxHeight:240,boxSizing:"border-box",resize:"vertical",padding:"8px 9px",borderRadius:"var(--radius-control)",background:"var(--bg-hover)",color:"var(--text)",fontFamily:"var(--seed-font-family)",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.5}}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8},children:[(0,r.jsx)("span",{"aria-live":"polite",style:{flex:1,minWidth:0,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",lineHeight:1.4,overflowWrap:"anywhere"},children:ea?"세션 파일이 준비되면 질문할 수 있습니다.":ei?"응답을 받는 중입니다.":"Enter 전송 \xb7 Shift+Enter 줄바꿈"}),(0,r.jsx)("button",{type:"submit",disabled:!ei&&!el,style:gB(!ei&&!el),children:ei?"중단":"전송"})]})]})]})}let gG="min-h-9 bg-bg-hover px-3 text-xs font-medium text-text transition-colors hover:bg-bg-selected disabled:cursor-not-allowed disabled:opacity-50",gY="pointer-coarse:min-h-11 pointer-coarse:min-w-11 max-sm:min-h-11 max-sm:min-w-11",gZ="mx-3 mb-2 rounded-[var(--radius-surface)] bg-bg px-3 py-3",gQ="m-0 px-4 pb-1.5 pt-4 text-xs font-semibold text-text-muted",gX="mx-3 mb-2 rounded-[var(--radius-control)] bg-bg px-3 py-2 text-xs";function g0(...e){return e.filter(Boolean).join(" ")}function g1(e,t){let n=Math.floor((e-t)/6e4);if(n<=0)return"리셋됨";let r=Math.floor(n/1440),s=Math.floor(n%1440/60),a=n%60;return r>0?`${r}d ${s}h 후 리셋`:s>0?`${s}h ${a}m 후 리셋`:`${a}m 후 리셋`}function g2(e,t){if(!e)return null;let n=Date.parse(e);if(!Number.isFinite(n))return null;let r=Math.floor((n-t)/6e4);if(r<=0)return"만료됨";let s=Math.floor(r/1440),a=Math.floor(r%1440/60),i=r%60;return s>0?`${s}d ${a}h 후 만료`:a>0?`${a}h ${i}m 후 만료`:`${i}m 후 만료`}function g4(e){return"number"==typeof e&&Number.isFinite(e)?0===e?"$0":e>=100?`$${e.toFixed(0)}`:e>=1?`$${e.toFixed(2)}`:e>=.01?`$${e.toFixed(3)}`:`$${e.toFixed(4)}`:"—"}function g8(e,t){return!1!==t?g4(e):"number"==typeof e&&Number.isFinite(e)&&0!==e?`≥${g4(e)}`:"가격 미상"}function g5(e){return"number"==typeof e&&Number.isFinite(e)?Math.round(e).toLocaleString("en-US"):"—"}function g6(e){return"number"==typeof e&&Number.isFinite(e)?e>=1e9?`${(e/1e9).toFixed(1)}B`:e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${Math.round(e/1e3)}K`:String(Math.round(e)):"—"}function g3(e,t=0){return"number"==typeof e&&Number.isFinite(e)?`${(100*e).toFixed(t)}%`:"—"}function g7(e){return"number"==typeof e&&Number.isFinite(e)?`${(e/1e3).toFixed(1)}s`:"—"}function g9(e){let t=new Date(e);return`${t.getMonth()+1}/${t.getDate()}`}function xe({label:e,value:t}){return(0,r.jsxs)("div",{className:"flex min-w-0 items-baseline justify-between gap-3 py-1.5",children:[(0,r.jsx)("dt",{className:"text-xs text-text-muted",children:e}),(0,r.jsx)("dd",{className:"m-0 font-mono text-xs tabular-nums text-text",children:t})]})}function xt({state:e,loading:t,subject:n}){return t&&"idle"===e.status?(0,r.jsxs)("div",{className:"p-4 text-sm text-text-muted",role:"status",children:[n," 불러오는 중…"]}):"error"===e.status?(0,r.jsxs)("div",{className:"p-4 text-sm text-text",role:"alert",children:[(0,r.jsxs)("div",{className:"font-medium",children:[n,"을 불러오지 못했습니다."]}),(0,r.jsx)("div",{className:"mt-1 text-xs text-text-muted",children:e.error.message}),(0,r.jsx)("div",{className:"mt-2 text-xs text-text-dim",children:"사이드카(127.0.0.1:30142)가 실행 중인지 확인하세요."})]}):"stale"===e.status?(0,r.jsxs)("div",{className:g0(gX,"text-text-muted"),role:"status",children:["마지막 데이터를 표시합니다. 새로고침 실패: ",e.error.message]}):null}function xn(e){let t=new Date(e),n=String(t.getHours()).padStart(2,"0"),r=String(t.getMinutes()).padStart(2,"0");return`${t.getMonth()+1}/${t.getDate()} ${n}:${r}`}function xr({limit:e,now:t,detailed:n}){let s="number"==typeof e.amount?.usedFraction?e.amount.usedFraction:0,a=Math.max(0,Math.min(100,100*s)),i=Math.round(100*s),l=function(e,t){let n=e.window,r=e.amount?.usedFraction;if(!n?.resetsAt||"number"!=typeof r)return null;let s=Math.max(0,n.resetsAt-t),a=100*r,i=Math.max(0,100-a);if(!n.durationMs){let e=s/864e5;return{burnOnly:!0,unit:"하루",partial:e<1,burn:e>=1?i/e:i}}let l=Math.min(n.durationMs,Math.max(0,n.durationMs-s)),o=n.durationMs>432e5,c=o?864e5:36e5,d=n.durationMs/c,u=s/c,h=l/n.durationMs*100;return{burnOnly:!1,unit:o?"하루":"시간",partial:u<1,burn:u>=1?i/u:i,pacePct:h,deltaPct:a-h,nominal:100/d}}(e,t),o=e.daySlot,c=o?.usedPct==null||null==o.baselinePct?null:Math.max(0,Math.min(o.baselinePct,100)),d=null==c?null:Math.max(c,Math.min(100*s,100)),u=l?.pacePct==null?null:Math.min(l.pacePct,99.6),h=i>=90,p=l?.deltaPct!=null&&l.deltaPct>=.5?l.deltaPct:null,m=o?"unknown"===o.quality||null==o.usedPct?"구간 사용 — 기록 부족":"approx"===o.quality?`구간 사용 ≈${o.usedPct.toFixed(0)}% \xb7 추정`:"estimate"===o.quality?`구간 사용 ≥${o.usedPct.toFixed(0)}% \xb7 추정`:`구간 사용 ${o.usedPct.toFixed(1)}%`:null;return(0,r.jsxs)("div",{className:"usage-limit py-2",children:[(0,r.jsxs)("div",{className:"flex items-baseline justify-between gap-2",children:[(0,r.jsx)("span",{className:"min-w-0 flex-1 truncate text-[13px] text-text-muted",children:e.label||e.id}),s>=1?(0,r.jsx)("span",{className:"usage-chip","data-tone":"danger",children:s>1?"한도 초과":"한도 도달"}):null,null!=p?(0,r.jsx)("span",{className:"usage-chip","data-tone":"warning",children:`과속 +${p.toFixed(1)}%`}):null,(0,r.jsxs)("span",{className:g0("shrink-0 font-mono text-sm font-semibold tabular-nums",h?"text-danger":"text-text"),children:[i,"%"]})]}),(0,r.jsxs)("div",{className:"relative mt-1 h-3.5 bg-metric-track",role:"progressbar","aria-label":`${e.label||e.id} 사용량`,"aria-valuemin":0,"aria-valuemax":100,"aria-valuenow":i,children:[(0,r.jsx)("div",{className:g0("absolute inset-y-0 left-0",h?"bg-danger":"bg-metric"),style:{width:`${a}%`}}),null!=c&&null!=d&&d>c?(0,r.jsx)("div",{className:"absolute inset-y-0 bg-metric-recent",style:{left:`${c}%`,width:`${d-c}%`}}):null,null!=u?(0,r.jsx)("div",{className:"absolute -inset-y-1 w-0.5 bg-text",style:{left:`${u}%`},"aria-hidden":"true"}):null,s>1?(0,r.jsx)("div",{className:"absolute inset-y-0 right-0 w-1 bg-danger","aria-hidden":"true"}):null]}),m||e.window?.resetsAt?(0,r.jsxs)("div",{className:"mt-1 flex items-baseline justify-between gap-3 font-mono text-[11px] tabular-nums text-text-muted",children:[(0,r.jsx)("span",{className:"min-w-0 truncate",children:m??""}),e.window?.resetsAt?(0,r.jsx)("span",{className:"shrink-0",children:g1(e.window.resetsAt,t)}):null]}):null,n?(0,r.jsxs)("dl",{className:"m-0 mt-1.5",children:[l?.pacePct!=null?(0,r.jsx)(xe,{label:"페이스",value:`${l.pacePct.toFixed(1)}%`}):null,l?(0,r.jsx)(xe,{label:l.partial?"남은 한도":`앞으로 ${l.unit}`,value:`${l.burn.toFixed(1)}%`}):null,l?.nominal!=null?(0,r.jsx)(xe,{label:"균등 배분 기준",value:`${l.nominal.toFixed(1)}%/${"하루"===l.unit?"일":"시간"} \xb7 계산값`}):null,o?(0,r.jsx)(xe,{label:"구간",value:`${xn(o.slotStart)} ~ ${xn(o.slotEnd)} \xb7 ${o.slotIndex+1}/${o.slotCount}`}):null,o?(0,r.jsx)(xe,{label:"기록 품질",value:function(e){let t;if("unknown"===e.quality)return"기록 부족 \xb7 구간 시작 전 표본이 없습니다";if("estimate"===e.quality){let t=null==e.firstSeenAt?"?":xn(e.firstSeenAt);return`추정 \xb7 구간 시작 표본이 없어 ${t}부터 센 최소량${e.paceOver?" \xb7 주간 진도 초과":""}`}let n=null==e.gapMs||0===e.gapMs?null:(t=Math.round(e.gapMs/6e4))<60?`${t}분`:`${Math.floor(t/60)}시간 ${t%60}분`;return"exact"===e.quality?n?`실측 \xb7 경계 ${n} 전 표본`:"실측 \xb7 구간 시작이 창의 시작":`추정 \xb7 경계 ${n??"?"} 전 표본`}(o)}):null]}):null]})}function xs({confirmId:e,pending:t,primaryRef:n,summary:s,onConfirm:a,onCancel:i}){return(0,r.jsxs)("div",{className:"resource-reset resource-reset-confirm-group","data-reset-state":t?"pending":"confirming","data-dismissible-layer":!0,role:"group","aria-label":"리셋 사용 확인",onKeyDown:e=>{"Escape"===e.key&&(e.preventDefault(),e.stopPropagation(),i())},children:[(0,r.jsx)("p",{className:"m-0 text-xs leading-5 text-text-muted",children:s}),(0,r.jsx)("p",{id:e,className:"m-0 text-xs leading-5 text-text",children:"리셋 1개를 지금 사용합니다. 되돌릴 수 없습니다."}),(0,r.jsx)("p",{className:"m-0 mt-1 text-xs leading-5 text-text-muted",children:"이 계정의 차단 기록도 함께 지워집니다."}),(0,r.jsxs)("div",{className:"mt-2 flex flex-wrap justify-end gap-2",children:[(0,r.jsx)("button",{ref:n,type:"button",className:g0(gG,"resource-reset-confirm"),"aria-describedby":e,disabled:t,onClick:a,children:t?"사용 중…":"리셋 사용"}),(0,r.jsx)("button",{type:"button",className:gG,disabled:t,onClick:i,children:"취소"})]})]})}function xa({report:e,brokerOk:t,now:n,active:a,identity:i,recommendation:l,pendingAction:o,feedback:c,onToggle:d,onReset:u,t:h}){let p=e.metadata??{},m=i??si([e])[0],f=e.credentialId,g=Number.isSafeInteger(f)&&f>0,x=e.accountRole,v="usage-only"===x?"사용량":"control-only"===x?"계정 제어":p.planType,y=!0!==e.disabled&&"number"==typeof e.autoBlockedUntilMs&&e.autoBlockedUntilMs>n,b=a?"active":e.disabled?"off":y?"auto-blocked":"idle",w="toggle"===o?"전환 중…":"reset"===o?"리셋 사용 중…":g?a?"현재 사용 \xb7 이 세션":e.disabled?"꺼둠":y?`자동 차단 \xb7 ${g1(e.autoBlockedUntilMs,n)}`:"control-only"===x?"로그인 계정 \xb7 ON/OFF 제어":"대기":"usage-only"===x?"할당량 정보 \xb7 계정 연결 없음":"제어 불가 \xb7 credential id 없음",k=(0,s.useId)(),j=(0,s.useId)(),[S,C]=(0,s.useState)(!1),[N,T]=(0,s.useState)(!1),[I,M]=(0,s.useState)(null),E=(0,s.useRef)(null),$=(0,s.useRef)(null),R=(0,s.useRef)(!1),L=(0,s.useRef)(!1),P="openai-codex"===e.provider||"anthropic"===e.provider?e.savedReset:void 0,A="anthropic"===e.provider&&P?.state==="available"?P.credits:[],_=A.find(e=>e.id===P?.nextCreditId)??null,F="openai-codex"===e.provider?function(e){let t=e.savedReset?.credits??[],n=null;for(let e of t){if(!e.id)continue;let t=e.expiresAt?Date.parse(e.expiresAt):NaN,r=Number.isFinite(t)?t:null;(!n||null!=r&&(null==n.timestamp||r<n.timestamp))&&(n={id:e.id,expiresAt:e.expiresAt,timestamp:r})}return n?{id:n.id,expiresAt:n.expiresAt}:null}(e):null,O=F?.id??null,z=g2(F?.expiresAt??null,n),D=P?.availableCount,W=P&&"unavailable"!==P.state?"empty"===P.state||0===D?`없음${P.unconfirmed?" \xb7 확인 중":""}`:"anthropic"===e.provider?`${D??A.length}개${P.unconfirmed?" \xb7 확인 중":""}`:`${D??P.credits.length}개${z?` \xb7 ${z}`:""}`:"확인 불가",H=`저장된 리셋 ${W}`,U=function(e,t){if(!e)return null;if("blocked-account"===e.reason){if(e.scope)return`권고 — ${e.scope}가 소진됐습니다. 저장된 리셋권 사용을 검토하세요.`;let n="number"==typeof e.naturalResetAt?g1(e.naturalResetAt,t).replace(/ 후 리셋$/,""):null;return n?`권고 — 지금 쓸 수 있는 다른 계정이 없고 자연 리셋까지 ${n} 남았습니다.`:"권고 — 지금 쓸 수 있는 다른 계정이 없어 저장된 리셋 사용을 검토하세요."}let n=g2(e.expiresAt??null,t),r="number"==typeof e.usedFraction?` 현재 ${Math.round(100*e.usedFraction)}% 소모한 ${"weekly"===e.window?"주간":"5시간"} 한도를 초기화할 수 있습니다.`:"";return`권고 — 리셋 1개가 ${n&&"만료됨"!==n?n:"곧 만료"}됩니다.${r}`}(l,n),B="openai-codex"===e.provider&&t&&!0!==e.disabled&&P?.state==="available"&&0!==D&&null!=O;(0,s.useLayoutEffect)(()=>{if(I)return void $.current?.focus();if(R.current){var e;R.current=!1,e=E.current,e?.focus()}},[I]),(0,s.useEffect)(()=>{"reset"!==o&&(e.disabled||!t||P?.state!=="available")&&(R.current=!1,M(null))},[t,o,e.disabled,P?.state]);let q=async()=>{if(I&&!L.current){L.current=!0;try{await u(e,I.creditId)}finally{L.current=!1,R.current=!0,M(null)}}},V=(e.limits??[]).reduce((e,t)=>{let r=t.window?.resetsAt;return"number"!=typeof r||r<=n?e:null==e||r<e?r:e},null),K=o?"pending":a?"active":e.disabled?"off":y?"blocked":"idle";return(0,r.jsxs)("section",{className:g0("resource-account",gZ),"data-account-state":b,"aria-current":a?"true":void 0,children:[(0,r.jsxs)("div",{className:"resource-account-head flex min-w-0 items-start gap-2.5",children:[(0,r.jsx)(sD,{seed:m.seed,size:48,provider:e.provider}),(0,r.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,r.jsxs)("h3",{className:"m-0 flex min-w-0 flex-wrap items-baseline gap-x-1.5 text-sm font-semibold text-text",children:[(0,r.jsx)("span",{children:m.alias}),(0,r.jsx)("span",{className:"min-w-0 truncate text-xs font-normal text-text-muted",children:`${sa(e.provider)}${v?` \xb7 ${v}`:""}`})]}),(0,r.jsxs)("div",{className:"mt-1 flex flex-wrap items-center gap-1.5",children:[(0,r.jsx)("span",{className:"resource-account-state resource-account-badge","data-tone":K,role:o?"status":void 0,children:w}),null!=V&&V-n<=72e5?(0,r.jsx)("span",{className:"usage-chip",children:`곧 리셋 \xb7 ${g1(V,n).replace(/ 후 리셋$/,"")}`}):null]})]}),g?(0,r.jsxs)("span",{className:"resource-account-toggle",children:[(0,r.jsx)("span",{className:"resource-account-toggle-label",children:"사용 설정"}),(0,r.jsx)("button",{type:"button",role:"switch",className:g0(gG,"resource-account-switch min-w-[3.25rem]"),disabled:null!=o||!t,"aria-label":`${m.alias} 계정 사용 설정`,"aria-checked":!e.disabled,"aria-busy":null!=o||void 0,title:t?void 0:"제어 서버에 연결할 수 없습니다.",onClick:()=>{R.current=!1,M(null),d(e)},children:e.disabled?"OFF":"ON"})]}):null]}),e.disabled?(0,r.jsx)("div",{className:"mt-2 text-xs text-text-muted",children:"다른 계정이 있으면 이 계정을 사용하지 않습니다."}):y?(0,r.jsx)("div",{className:"mt-2 text-xs text-text-muted",children:(e.limits??[]).some(rO)?"한도를 다 써서 코어가 자동으로 차단했습니다.":"한도는 남아 있지만 토큰 갱신 실패나 일시 오류로 코어가 잠시 막았습니다. 해제 시각이 지나면 다시 씁니다."}):null,c?(0,r.jsx)("div",{className:"mt-2 text-xs text-text",role:"error"===c.tone?"alert":"status",children:c.message}):null,(0,r.jsxs)("div",{id:j,className:"resource-account-limits",children:[S?(0,r.jsxs)("div",{className:"flex items-baseline justify-between gap-3 py-2",children:[(0,r.jsx)("span",{className:"text-xs text-text-muted",children:"계정"}),(0,r.jsxs)("span",{className:"flex min-w-0 items-baseline gap-2",children:[(0,r.jsx)("span",{className:"min-w-0 truncate font-mono text-xs text-text",children:N?m.raw:m.masked||"—"}),m.raw?(0,r.jsx)("button",{type:"button",className:"resource-account-reveal","aria-pressed":N,onClick:()=>T(!N),children:N?"가리기":"이메일 보기"}):null]})]}):null,(e.limits??[]).map(e=>(0,r.jsx)(xr,{limit:e,now:n,detailed:S},e.id))]}),(e.limits??[]).length>0||m.raw?(0,r.jsx)("button",{type:"button",className:"resource-account-more","aria-expanded":S,"aria-controls":j,onClick:()=>{let e=!S;C(e),e||T(!1)},children:S?"간단히":"자세히"}):null,"openai-codex"===e.provider||"anthropic"===e.provider?I?(0,r.jsx)(xs,{confirmId:k,pending:"reset"===o,primaryRef:$,summary:I.summary,onConfirm:()=>{q()},onCancel:()=>{R.current=!0,M(null)}}):(0,r.jsxs)("div",{className:"resource-reset mt-3","data-reset-state":t?P&&"unavailable"!==P.state?"empty"===P.state||0===D?"empty":"reset"===o?"pending":"ready":"unavailable":"offline",children:[(0,r.jsxs)("div",{className:"flex flex-wrap items-baseline gap-x-3 gap-y-1.5",children:[(0,r.jsxs)("div",{className:"flex min-w-[10.5rem] flex-1 items-baseline justify-between gap-x-3",children:[(0,r.jsx)("span",{className:"text-xs text-text-muted",children:"저장된 리셋"}),(0,r.jsx)("span",{className:g0("font-mono text-xs tabular-nums text-text",l?.reason==="expiring-credit"&&"text-warning"),children:W})]}),B?(0,r.jsx)("button",{ref:E,type:"button",className:g0(gG,"ml-auto flex-none"),disabled:null!=o,onClick:()=>{O&&M({creditId:O,summary:H})},children:"리셋 사용"}):t&&e.disabled&&P?.state==="available"?(0,r.jsx)("span",{className:"ml-auto text-xs text-text-muted",children:"켠 뒤 사용 가능"}):null]}),A.length>0?(0,r.jsx)("ul",{className:"resource-reset-credits m-0 mt-1.5 list-none space-y-1 p-0","aria-label":"저장된 리셋 종류",children:A.map(s=>{let a,i,l,c=(i=(a=s.clears??[]).map(e=>{switch(e){case"anthropic:5h":return h("resource.reset.window.fiveHour");case"anthropic:7d":return h("resource.reset.window.weekly");case"anthropic:7d:fable":return h("resource.reset.includedOverage");case"anthropic:7d:opus":return`Opus ${h("resource.reset.window.weekly")}`;case"anthropic:7d:sonnet":return`Sonnet ${h("resource.reset.window.weekly")}`;default:return e}}),l=a.map(e=>/^anthropic:7d:(.+)$/.exec(e)?.[1]).find(e=>void 0!==e),{name:a.includes("anthropic:7d")?h("resource.reset.name.full"):a.includes("anthropic:7d:fable")?h("resource.reset.name.fable"):l?`${"opus"===l?"Opus":"sonnet"===l?"Sonnet":l} ${h("resource.reset.name.generic")}`:a.includes("anthropic:5h")?h("resource.reset.name.fiveHour"):h("resource.reset.name.generic"),covers:i.length?h("resource.reset.covers",{limits:[...new Set(i)].join(", ")}):null}),d=s.id===_?.id,u=g2(s.expiresAt,n),p=s.remainingCount??1,m=t&&g&&!0!==e.disabled&&P?.unconfirmed!==!0&&P?.eligible===!0&&!0===s.usable&&p>0;return(0,r.jsxs)("li",{className:"flex flex-wrap items-baseline gap-x-2 text-xs","data-reset-next":d?"true":void 0,children:[(0,r.jsx)("span",{className:g0("font-medium",d?"text-text":"text-text-muted"),children:p>1?`${c.name} ${p}개`:c.name}),d?(0,r.jsx)("span",{className:"usage-chip",children:h("resource.reset.chip.nextUse")}):null,(0,r.jsx)("span",{className:"min-w-0 text-text-muted",children:[c.covers,u].filter(Boolean).join(", ")}),m?(0,r.jsx)("button",{ref:e=>{e&&E.current?.dataset.creditId===s.id&&(E.current=e)},"data-credit-id":s.id,type:"button",className:g0(gG,"ml-auto flex-none"),disabled:null!=o,"aria-label":`${c.name}: ${h("resource.reset.use")}`,onClick:e=>{E.current=e.currentTarget,M({creditId:s.id,summary:[h("resource.reset.summary",{name:c.name}),c.covers,u].filter(Boolean).join(", ")})},children:h("resource.reset.use")}):(0,r.jsx)("span",{className:"ml-auto text-text-muted",children:P?.unconfirmed?"확인 중":h("resource.reset.unavailable")})]},s.id)})}):null,U?(0,r.jsx)("p",{className:"m-0 mt-1.5 text-xs leading-5 text-text-muted",children:U}):null]}):null]})}function xi({state:e,loading:t,accountState:n,pendingActions:s,feedbackByCredential:a,onToggle:i,onReset:l,t:o}){let c=nG(1e4);sF();let d=e.data,u=n?.state==="resolved"&&"session-pin"===n.source&&Number.isSafeInteger(n.credentialId)&&n.credentialId>0?n.credentialId:null,h=si(d?.reports??[]),p=null==u?-1:d?.reports.findIndex(e=>e.credentialId===u)??-1;return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(xt,{state:e,loading:t,subject:"사용량"}),d?.brokerOk===!1?(0,r.jsx)("div",{className:g0(gX,"text-text-muted"),role:"status",children:"제어 서버에 연결할 수 없어 계정 전환과 리셋 사용을 잠시 쓸 수 없습니다. 사용량 표시는 계속 갱신됩니다."}):null,(0,r.jsxs)("div",{className:"flex min-h-7 items-center gap-4 px-4 text-[11px] font-semibold text-text-muted","aria-label":"사용량 그래프 범례",children:[(0,r.jsxs)("span",{className:"inline-flex items-center gap-1.5",children:[(0,r.jsx)("span",{className:"size-2 bg-metric","aria-hidden":"true"}),"누적"]}),(0,r.jsxs)("span",{className:"inline-flex items-center gap-1.5",children:[(0,r.jsx)("span",{className:"size-2 bg-metric-recent","aria-hidden":"true"}),"이번 구간"]}),(0,r.jsxs)("span",{className:"inline-flex items-center gap-1.5",children:[(0,r.jsx)("span",{className:"h-3 w-0.5 bg-text","aria-hidden":"true"}),"페이스"]})]}),d&&0===d.reports.length?(0,r.jsx)("div",{className:"p-4 text-sm text-text-muted",children:"인증된 계정의 사용량 정보가 없습니다. `omp usage`로 확인하세요."}):null,d?.reports.map((e,t)=>{let u=e.credentialId;return(0,r.jsx)(xa,{report:e,brokerOk:!0===d.brokerOk,now:c,active:t===p,identity:h[t],recommendation:null==u?void 0:n?.resetRecommendations.find(e=>e.credentialId===u),pendingAction:null==u?null:s.get(u)??null,feedback:null==u?void 0:a.get(u),onToggle:i,onReset:l,t:o},`${e.provider}:${u??e.metadata?.accountId??e.metadata?.email??t}`)})]})}let xl={invalid_total:!0,invalid_start_date:!0,start_date_in_future:!0,session_scan_failed:!0,session_scan_partial:!0,internal:!0,settings_unreadable:!0,invalid_balance:!0,invalid_observed_at:!0,observed_at_in_future:!0,routes_unreadable:!0},xo={session:!0,memory:!0,"korean-reply-translation":!0};function xc(e,t,n=""){return t?Object.hasOwn(xl,t)?e(`credits.error.${t}`):n||t:n}function xd({face:e,provider:t="hive",title:n,model:s,cost:a,costMinimum:i=!1,detail:l,t:o}){return(0,r.jsxs)("li",{className:"flex min-w-0 items-start gap-2 py-1.5",children:[e?(0,r.jsx)(sD,{seed:e.seed,size:28,provider:t}):(0,r.jsx)("span",{className:"w-7 shrink-0","aria-hidden":"true"}),(0,r.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,r.jsxs)("div",{className:"flex min-w-0 items-baseline gap-1.5",children:[n?(0,r.jsx)("span",{className:"shrink-0 text-[13px] font-medium text-text",children:n}):null,(0,r.jsx)("span",{className:"min-w-0 flex-1 truncate font-mono text-[11px] text-text-dim",children:s}),(0,r.jsx)("span",{className:"shrink-0 font-mono text-xs tabular-nums text-text",children:null===a?o("credits.priceUnknown"):`${i?"≥":""}${g4(a)}`})]}),(0,r.jsx)("div",{className:"mt-0.5 whitespace-pre-line font-mono text-[11px] tabular-nums text-text-muted",children:l})]})]})}function xu({walletName:e,setting:t,onSave:n,onClose:a,t:i}){let l=(0,s.useId)(),[o,c]=(0,s.useState)(t?String(t.totalUsd):""),[d,u]=(0,s.useState)(t?.startDate??""),[h,p]=(0,s.useState)(!1),[m,f]=(0,s.useState)(null),g="min-h-8 w-full min-w-0 bg-bg-hover px-2 font-mono text-xs text-text",x=async e=>{p(!0),f(null);try{await n(e),a()}catch(e){f(i("credits.saveFailed",{reason:xc(i,e instanceof sl?e.code:void 0,e instanceof Error?e.message:String(e))}))}finally{p(!1)}};return(0,r.jsxs)("form",{className:"mt-2 grid gap-2","aria-label":i("credits.formLabel",{wallet:e}),onSubmit:e=>{var t;let n;e.preventDefault();let r=(n=Number((t={totalUsd:o,startDate:d}).totalUsd.replace(/[$,\s]/g,"")),t.totalUsd.trim()&&Number.isFinite(n)?{totalUsd:n,startDate:t.startDate.trim()}:null);r?x(r):f(i("credits.invalid.total"))},children:[(0,r.jsxs)("div",{className:"grid grid-cols-2 gap-2",children:[(0,r.jsxs)("label",{className:"grid gap-1 text-[11px] text-text-muted",htmlFor:`${l}-total`,children:[i("credits.totalUsd"),(0,r.jsx)("input",{id:`${l}-total`,className:g,inputMode:"decimal",value:o,onChange:e=>c(e.target.value),placeholder:"300",required:!0})]}),(0,r.jsxs)("label",{className:"grid gap-1 text-[11px] text-text-muted",htmlFor:`${l}-start`,children:[i("credits.startDate"),(0,r.jsx)("input",{id:`${l}-start`,className:g,type:"date",value:d,onChange:e=>u(e.target.value),required:!0})]})]}),m?(0,r.jsx)("div",{className:"text-xs text-danger",role:"alert",children:m}):null,(0,r.jsxs)("div",{className:"flex flex-wrap justify-end gap-1.5",children:[t?(0,r.jsx)("button",{type:"button",className:g0(gG,"me-auto"),disabled:h,onClick:()=>{x(null)},children:i("credits.clear")}):null,(0,r.jsx)("button",{type:"button",className:gG,disabled:h,onClick:a,children:i("credits.cancel")}),(0,r.jsx)("button",{type:"submit",className:gG,disabled:h,children:h?i("credits.saving"):i("credits.save")})]})]})}function xh({wallet:e,setting:t,balance:n,now:a,onSave:i,onSaveBalance:o,t:c}){let d=(0,s.useId)(),[u,h]=(0,s.useState)(!1),p=c("credits.wallet.hive"),m=function(e){if(null===e.totalUsd||e.totalUsd<=0)return{spentFraction:null,tone:"normal"};let t=e.spentUsd/e.totalUsd;return{spentFraction:Math.max(0,Math.min(1,t)),tone:t>=1?"danger":t>=.9?"warning":"normal"}}(e),f="start-date"===e.sinceSource?c("credits.since",{date:e.since}):c("credits.sinceDefault"),g=e.spentComplete||e.upperBoundRows?g4(e.spentUsd):`≥${g4(e.spentUsd)}`,x=null===e.remainingUsd?null:`${e.remainingUpperBound?"≤":""}${g4(Math.max(0,e.remainingUsd))}`,v=null===m.spentFraction||null===e.remainingUsd?null:Math.round(100*m.spentFraction);return(0,r.jsxs)("section",{className:gZ,"aria-labelledby":d,"data-credit-wallet":e.wallet,children:[(0,r.jsxs)("div",{className:"flex min-w-0 items-center gap-2",children:[(0,r.jsx)("h3",{id:d,className:"m-0 min-w-0 flex-1 text-sm font-semibold text-text",children:p}),u?null:(0,r.jsx)(l.r,{variant:"neutralWeak",size:"xsmall",onClick:()=>h(!0),children:t?c("credits.edit"):c("credits.enter")}),(0,r.jsx)(xf,{wallet:"hive",walletName:p,t:c})]}),n?(0,r.jsx)(xy,{balance:n,walletName:p,now:a,onSave:o,t:c}):null,(0,r.jsx)("div",{className:g0("text-xs text-text-muted",n?"mt-2":"mt-0.5"),children:`${c(`credits.scope.${e.wallet}`)} \xb7 ${f}`}),"error"===e.status?(0,r.jsx)("div",{className:"mt-1.5 text-xs text-text",role:"alert",children:c("credits.walletError",{reason:xc(c,e.error)})}):null,null!==v?(0,r.jsxs)("div",{className:"py-2",children:[(0,r.jsxs)("div",{className:"flex items-baseline justify-between gap-2",children:[(0,r.jsx)("span",{className:"text-[13px] text-text-muted",children:c("credits.remaining")}),(0,r.jsx)("span",{className:g0("font-mono text-sm font-semibold tabular-nums","danger"===m.tone?"text-danger":"text-text"),children:x})]}),(0,r.jsx)("div",{className:"relative mt-1 h-3.5 overflow-hidden bg-metric-track",role:"progressbar","aria-label":c("credits.meterLabel",{wallet:p}),"aria-valuemin":0,"aria-valuemax":100,"aria-valuenow":v,children:(0,r.jsx)("div",{className:g0("absolute inset-y-0 left-0","danger"===m.tone?"bg-danger":"bg-metric"),style:{width:`${v}%`}})}),(0,r.jsx)("div",{className:"mt-1 text-right text-[11px] text-text-muted tabular-nums",children:c("credits.usedPct",{pct:v})})]}):null,(0,r.jsxs)("dl",{className:"m-0 mt-1",children:[null!==e.totalUsd?(0,r.jsx)(xe,{label:c("credits.total"),value:g4(e.totalUsd)}):null,(0,r.jsx)(xe,{label:c("credits.spent"),value:g})]}),t||u?null:(0,r.jsx)("p",{className:"m-0 mt-1.5 text-xs text-text-muted",children:c("credits.enterPrompt")}),u?(0,r.jsx)(xu,{walletName:p,setting:t,onSave:e=>i("hive",e),onClose:()=>h(!1),t:c}):null,e.rows.length>0?(0,r.jsx)("ul",{className:"m-0 mt-1.5 list-none p-0",children:e.rows.map(e=>{let t=se("hive",e.model)??st("hive"),n=e.purposes.map(e=>{let t=Object.hasOwn(xo,e.purpose)?c(`credits.purpose.${e.purpose}`):e.purpose;return`${t} ${null===e.costUsd?c("credits.priceUnknown"):g4(e.costUsd)}`}),s=[c("credits.requests",{count:g5(e.requests)}),c("credits.tokens",{input:g6(e.inputTokens),output:g6(e.outputTokens)}),e.cacheReadTokens>0?c("credits.cacheTokens",{cache:g6(e.cacheReadTokens)}):null].filter(Boolean).join(" \xb7 ");return(0,r.jsx)(xd,{face:t,title:t?.alias??e.model,model:e.model,cost:e.costUsd,detail:n.length>0?`${s}
75
+ ${x}`:""}`,"aria-label":`${S} ${v}, 업무 ${h.title}${m?`, 현재 단계 ${m}`:""}${g?`, ${g}`:""}${x?`, ${x}`:""}, ${d?d.status:u?.status??"미확인"}, 모델 ${w.model??"미확인"}, 추론 ${j}`,"aria-describedby":f&&d?c:void 0,style:{display:"grid",gridTemplateColumns:"minmax(0, 1fr) auto",gap:"4px 8px",width:"100%",marginBottom:8,padding:12,borderRadius:"var(--seed-radius-r2)",background:"var(--bg)",color:"var(--text)",cursor:"pointer",textAlign:"left"},children:[(0,r.jsxs)("span",{style:{display:"flex",alignItems:"center",gap:6,minWidth:0},children:["known"===b.kind?(0,r.jsxs)("span",{className:"subagent-role","data-role-kind":"known","data-role":b.agent,title:`${b.agent} \xb7 ${f9[b.source]}`,children:[(0,r.jsx)("span",{className:"sr-only",children:"역할 "}),b.label]}):(0,r.jsx)("span",{className:"subagent-role","data-role-kind":"unknown",title:"역할 정보가 없는 기록입니다.",children:"역할 미확인"}),(0,r.jsx)("span",{className:"subagent-task-line",style:{minWidth:0},children:h.title})]}),d?(0,r.jsx)("span",{style:{color:f3(d),fontSize:"var(--seed-font-size-t2-static)",fontVariantNumeric:"tabular-nums"},children:d.status}):u?(0,r.jsx)("span",{style:{color:"failed"===u.status?"var(--danger)":"aborted"===u.status?"var(--warning)":"var(--seed-color-fg-neutral-subtle)",fontSize:"var(--seed-font-size-t2-static)",fontVariantNumeric:"tabular-nums"},children:u.status??"미확인"}):(0,r.jsx)("span",{"aria-hidden":"true"}),m&&(0,r.jsxs)("span",{className:"subagent-stage-line",title:`현재 단계: ${m}`,style:{gridColumn:"1 / -1",minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--seed-color-fg-neutral-subtle)",fontSize:"var(--seed-font-size-t2-static)"},children:[(0,r.jsx)("span",{style:{fontWeight:600},children:"현재 단계"})," \xb7 ",m]}),f?.phase&&(0,r.jsxs)("span",{className:"subagent-phase-line",style:{gridColumn:"1 / -1",minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:"var(--seed-font-size-t2-static)",fontVariantNumeric:"tabular-nums"},children:[(0,r.jsx)(o4,{phase:f.phase}),x&&(0,r.jsx)("span",{style:{color:"var(--seed-color-fg-neutral-subtle)"},title:x,children:` \xb7 ${x}`})]}),f&&d&&(0,r.jsx)("span",{className:"subagent-eta-line",style:{gridColumn:"1 / -1",minWidth:0,color:"var(--seed-color-fg-neutral)",fontSize:"var(--seed-font-size-t2-static)",fontVariantNumeric:"tabular-nums"},children:(0,r.jsx)(o7,{snapshot:d,view:f,id:c})}),(0,r.jsxs)("span",{className:"subagent-model-line","data-observed":w.model?w.effort?"both":"model":w.effort?"effort":"none","aria-hidden":"true",style:{gridColumn:"1 / -1"},children:[k,w.modelIsFallback&&(0,r.jsx)("span",{className:"subagent-effort",children:" (대체 모델)"}),(0,r.jsxs)("span",{className:"subagent-effort",children:[" \xb7 ",j]})]}),(0,r.jsxs)("span",{style:{gridColumn:"1 / -1",display:"flex",flexWrap:"wrap",gap:"4px 8px",minWidth:0,color:"var(--seed-color-fg-neutral-subtle)",fontFamily:"var(--font-mono)",fontSize:"var(--seed-font-size-t1-static)"},children:[(0,r.jsx)("span",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:v}),(0,r.jsx)("span",{children:y})]}),(0,r.jsxs)("span",{style:{gridColumn:"1 / -1",display:"flex",flexWrap:"wrap",gap:"4px 10px",color:"var(--seed-color-fg-neutral-subtle)",fontFamily:"var(--font-mono)",fontSize:"var(--seed-font-size-t1-static)",fontVariantNumeric:"tabular-nums"},children:[d?.progress&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("span",{children:["도구 ",d.progress.toolCount]}),(0,r.jsxs)("span",{children:[d.progress.tokens.toLocaleString()," Token"]}),(0,r.jsx)("span",{children:function(e=0){let t=Math.max(0,Math.floor(e/1e3));if(t<60)return`${t}초`;let n=Math.floor(t/60);return n<60?`${n}분${t%60?` ${t%60}초`:""}`:`${Math.floor(n/60)}시간 ${n%60}분`}(d.progress.durationMs)})]}),u&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{children:null===u.messages?"메시지 수 미확인":`메시지 ${u.messages}`}),(0,r.jsxs)("span",{children:[(u.bytes/1024).toFixed(+(u.bytes<10240))," KB"]}),(0,r.jsx)("span",{children:function(e=0){let t=Math.max(0,Date.now()-e);return t<1e4?"방금 전":t<6e4?`${Math.floor(t/1e3)}초 전`:t<36e5?`${Math.floor(t/6e4)}분 전`:t<864e5?`${Math.floor(t/36e5)}시간 전`:`${Math.floor(t/864e5)}일 전`}(u.modified)})]})]})]})})}function gl({title:e,sessionId:t,sessionPath:n,sessionCwd:a,liveSubagents:i,client:l,visible:o=!0,onClose:c,onReturnFocus:d,selection:u,onSelectionChange:h,onReturnToOrigin:p,onOpenFile:m}){let{t:f}=(0,F.s)(),g=(0,s.useMemo)(()=>l??ii(),[l]),[x,v]=(0,s.useState)([]),[y,b]=(0,s.useState)({kind:"loading"}),[w,k]=(0,s.useState)({kind:"loading"}),[j,S]=(0,s.useState)(!1),[C,N]=(0,s.useState)(null),T=h?u??null:C,I=h??N,[M,E]=(0,s.useState)(0),$=(0,s.useRef)(null),R=(0,s.useRef)(null);(0,s.useEffect)(()=>{v([]),b({kind:"loading"}),k({kind:"loading"}),S(!1),N(null)},[t]),(0,s.useEffect)(()=>{if(!o||!t)return;let e=!1,n=!1,r=null,s=async()=>{if(e||n||"visible"!==document.visibilityState)return;n=!0,r=new AbortController;let[s,a]=await Promise.allSettled([g.getLiveSnapshots(t,r.signal),g.getArchive(t,r.signal)]);if(!e&&!r.signal.aborted){if("fulfilled"===s.status)v(s.value.subagents),b(s.value.subagents.length>0?{kind:"ready",data:s.value.subagents}:{kind:"empty",data:[]});else{let e=oI(s.reason);b("unreachable"===e.kind?{kind:"unreachable",message:e.message}:{kind:"error",message:e.message})}if("fulfilled"===a.status)S(!0===a.value.listTruncated),k(a.value.subagents.length>0?{kind:"ready",data:a.value.subagents}:{kind:"empty",data:[]});else{let e=oI(a.reason);k("unreachable"===e.kind?{kind:"unreachable",message:e.message}:{kind:"error",message:e.message})}n=!1}};s();let a=setInterval(()=>void s(),3e3),i=()=>{"visible"===document.visibilityState&&s()};return document.addEventListener("visibilitychange",i),()=>{e=!0,r?.abort(),clearInterval(a),document.removeEventListener("visibilitychange",i)}},[M,g,t,o]);let L=(0,s.useMemo)(()=>(function(e,t){let n=new Map,r=[];for(let s of[...e,...t]){let e=n.get(s.id);if(!e){r.push(s.id),n.set(s.id,s);continue}let[t,a]=ge(s)>=ge(e)?[s,e]:[e,s];n.set(s.id,{...t,assignment:t.assignment??a.assignment,description:t.description??a.description})}return r.flatMap(e=>{let t=n.get(e);return t?[t]:[]})})(i,x),[i,x]),P="ready"===w.kind||"empty"===w.kind?w.data:[],A=(0,s.useMemo)(()=>(function(e,t){let n=new Map(t.map(e=>[e.name,e])),r=new Set,s=e.map(e=>{let t=(function(e){let t=[];if(e.sessionFile){let n=e.sessionFile.split(/[\\/]/).pop()?.replace(/\.jsonl$/i,"");n&&t.push({name:n,match:"session-file"})}return t.some(t=>t.name===e.id)||t.push({name:e.id,match:"name"}),t})(e).find(e=>n.has(e.name)&&!r.has(e.name)),s=t?n.get(t.name):void 0;return s&&r.add(s.name),{key:`live:${e.id}`,identity:s?"live-archive":"live",live:e,...s&&t?{archive:s,archiveMatch:t.match}:{}}});for(let e of t)r.has(e.name)||s.push({key:`archive:${e.name}`,identity:"archive",archive:e});return s})(L,P),[P,L]),_=T?A.find(e=>e.key===T.key)??null:null,O=_&&T?.toolCallId&&_.live?.parentToolCallId!==T.toolCallId?null:_,z=o0({sessionId:t,snapshots:L,client:g,enabled:o&&!T,cwd:a??void 0});if((0,s.useEffect)(()=>{let e=R.current;if(T||!e)return;R.current=null;let t=[...$.current?.querySelectorAll("[data-subagent-key]")??[]].find(t=>t.dataset.subagentKey===e);t?.focus({preventScroll:!1})}),T&&t)return(0,r.jsx)(ga,{sessionId:t,sessionCwd:a,record:O,selection:T,client:g,visible:o,onOpenFile:m,onBack:()=>{I(null),T.origin&&p?p(T.origin):R.current=T.key}});let D=0===A.length&&"loading"===y.kind&&"loading"===w.kind,W=0===A.length&&("empty"===y.kind||0===i.length)&&"empty"===w.kind;return(0,r.jsxs)("section",{ref:$,"aria-label":"Subagent 기록","data-state":D?"loading":W?"empty":"ready",style:{display:"flex",flexDirection:"column",width:"100%",height:"100%",minWidth:0,minHeight:0,overflow:"hidden",background:"var(--bg-panel)",color:"var(--text)"},children:[(0,r.jsx)(p$,{title:e,titleTooltip:n??void 0,subtitle:D||!t?void 0:f("panel.subagentsCount",{count:A.length}),actions:[{id:"refresh",label:f("panel.refresh"),icon:gt,onClick:()=>E(e=>e+1)}],close:c?{label:f("panel.close"),onClick:()=>{c?.(),d?.()}}:void 0}),(0,r.jsxs)("div",{style:{flex:1,minHeight:0,overflowY:"auto",padding:"9px 10px 16px"},children:[t?D?(0,r.jsx)("div",{role:"status",style:{padding:24,color:"var(--text-muted)",textAlign:"center",fontSize:10.5},children:"Subagent 기록 불러오는 중…"}):W?(0,r.jsx)("div",{role:"status",style:{padding:24,color:"var(--text-muted)",textAlign:"center",fontSize:10.5,lineHeight:1.6},children:"이 세션은 아직 Subagent를 실행한 적이 없습니다."}):(0,r.jsx)("div",{role:"list","aria-label":"Subagent 실시간 및 디스크 기록",children:A.map(e=>(0,r.jsx)(gi,{record:e,view:e.live?z.get(e.live.id):void 0,onSelect:()=>I({key:e.key})},e.key))}):(0,r.jsx)("div",{role:"status",style:{padding:24,color:"var(--text-muted)",textAlign:"center",fontSize:10.5},children:"세션을 선택한 뒤 다시 시도하세요."}),!D&&"loading"===y.kind&&(0,r.jsx)("div",{role:"status",style:{marginTop:8,color:"var(--text-muted)",fontSize:9.5},children:"실시간 상태 불러오는 중…"}),!D&&"loading"===w.kind&&(0,r.jsx)("div",{role:"status",style:{marginTop:8,color:"var(--text-muted)",fontSize:9.5},children:"디스크 기록 불러오는 중…"}),"unreachable"===y.kind&&(0,r.jsx)("div",{role:"status",style:{marginTop:8,padding:"7px 9px",borderRadius:"var(--radius-surface)",background:"var(--bg)",color:"var(--text-muted)",fontSize:9.5},children:y.message}),"error"===y.kind&&(0,r.jsx)("div",{role:"alert",style:{marginTop:8,padding:"7px 9px",borderRadius:"var(--radius-surface)",background:"var(--danger-soft)",color:"var(--text)",fontSize:9.5},children:y.message}),"unreachable"===w.kind&&(0,r.jsx)("div",{role:"status",style:{marginTop:8,padding:"7px 9px",borderRadius:"var(--radius-surface)",background:"var(--bg)",color:"var(--text-muted)",fontSize:9.5},children:w.message}),"error"===w.kind&&(0,r.jsx)("div",{role:"alert",style:{marginTop:8,padding:"7px 9px",borderRadius:"var(--radius-surface)",background:"var(--danger-soft)",color:"var(--text)",fontSize:9.5},children:w.message}),j&&(0,r.jsx)("div",{role:"status",style:{marginTop:8,color:"var(--warning)",fontSize:9.5},children:"최근 디스크 기록 60개만 표시합니다."})]})]})}let go=["turn","process","subagents","files","browser"],gc=["efficiency","resource","sidechat","plugins","memory"],gd=new Set(["efficiency","sidechat","resource","browser"]);function gu({activeView:e,onViewChange:t,viewLabels:n,sessionId:s,sessionPath:a,sessionName:i,sessionCwd:d,liveSubagents:u,subagentClient:h,turnSlot:p,processSlot:m,fileSlot:f,browserSlot:g,sideChatSlot:x,resourceSlot:v,efficiencySlot:y,pluginsSlot:b,memorySlot:w,visible:k=!0,onClose:j,closeLabel:S,onReturnFocus:C,expand:N=null,selectedMaker:T,onSelectMaker:I,onReturnToDispatch:M,onOpenFile:E,fileOpen:$=!1,widthReadout:R=null}){let{t:L}=(0,F.s)(),P=gc.includes(e)?[...go,e]:go;return(0,r.jsx)(pC.Provider,{value:N,children:(0,r.jsx)("aside",{className:"auxiliary-deck","aria-label":L("inspector.label"),"data-auxiliary-view":e,"data-expanded":N?.expanded?"true":void 0,children:(0,r.jsxs)(f5.J.Root,{className:"auxiliary-deck-tabs",size:"small",contentLayout:"fill",triggerLayout:"hug",value:e,onValueChange:e=>t(e),children:[(0,r.jsxs)("div",{className:"auxiliary-deck-tabbar",children:[(0,r.jsx)(f5.J.List,{"aria-label":L("inspector.views"),children:P.map(e=>{let t="subagents"===e?u.filter(e=>"pending"===e.status||"running"===e.status).length:0;return(0,r.jsxs)(f5.J.Trigger,{value:e,"aria-label":t>0?`${n[e]} (${L("workbench.runningCount",{count:t})})`:void 0,children:[(0,r.jsx)("span",{className:"auxiliary-deck-tab-label",children:n[e]}),t>0&&(0,r.jsx)(n2.E,{size:"medium",variant:"weak",tone:"neutral","aria-hidden":"true",children:t})]},e)})}),(0,r.jsxs)(o.k.Root,{placement:"bottom-end",strategy:"fixed",children:[(0,r.jsx)(o.k.Trigger,{asChild:!0,children:(0,r.jsx)(l.r,{className:"auxiliary-deck-more",variant:"ghost",size:"small",layout:"iconOnly","aria-label":L("inspector.more"),title:L("inspector.more"),children:(0,r.jsx)(c.In,{size:"16px",svg:(0,r.jsxs)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"12",cy:"12",r:"1"}),(0,r.jsx)("circle",{cx:"19",cy:"12",r:"1"}),(0,r.jsx)("circle",{cx:"5",cy:"12",r:"1"})]})})})}),(0,r.jsx)(o.k.Positioner,{children:(0,r.jsx)(o.k.Content,{"aria-label":L("inspector.more"),children:(0,r.jsx)(o.k.Group,{children:gc.map(s=>(0,r.jsx)(o.k.Item,{role:"menuitemradio","aria-checked":e===s,onClick:()=>t(s),children:(0,r.jsx)(o.k.ItemBody,{children:(0,r.jsx)(o.k.ItemLabel,{children:n[s]})})},s))})})})]}),(gd.has(e)||"files"===e&&!$)&&(0,r.jsx)(pR,{className:"auxiliary-deck-expand"}),j&&(0,r.jsx)(l.r,{className:"auxiliary-deck-close",variant:"ghost",size:"small",layout:"iconOnly",onClick:()=>{j?.(),C?.()},"aria-label":S??L("inspector.hide"),title:S??L("inspector.hide"),children:(0,r.jsx)(c.In,{size:"16px",svg:(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"})})})}),R]}),(0,r.jsx)(f5.J.Content,{value:"turn",className:"auxiliary-deck-panel",children:p}),(0,r.jsx)(f5.J.Content,{value:"process",className:"auxiliary-deck-panel",children:m}),(0,r.jsx)(f5.J.Content,{value:"efficiency",className:"auxiliary-deck-panel",children:y}),(0,r.jsx)(f5.J.Content,{value:"subagents",className:"auxiliary-deck-panel",children:(0,r.jsx)(gl,{title:n.subagents,sessionId:s,sessionPath:a,sessionCwd:d,liveSubagents:u,client:h,visible:k&&"subagents"===e,selection:T,onSelectionChange:I,onReturnToOrigin:M,onOpenFile:E})}),(0,r.jsx)(f5.J.Content,{value:"files",className:"auxiliary-deck-panel",children:f}),(0,r.jsx)(f5.J.Content,{value:"browser",className:"auxiliary-deck-panel",children:g}),(0,r.jsx)(f5.J.Content,{value:"sidechat",className:"auxiliary-deck-panel",children:x}),(0,r.jsx)(f5.J.Content,{value:"resource",className:"auxiliary-deck-panel",children:v}),(0,r.jsx)(f5.J.Content,{value:"plugins",className:"auxiliary-deck-panel",children:b}),(0,r.jsx)(f5.J.Content,{value:"memory",className:"auxiliary-deck-panel",children:w})]})})})}let gh={state:null,streamDown:!1,frameSize:null,frameTabId:null,hadView:!1};class gp{#e;#t;#n;#r;#s;#a;#i;#l;#o;#c;constructor(e,t){this.#n=new Set,this.#r=new Set,this.#s=gh,this.#a="",this.#i=!0,this.#l=null,this.#o=null,this.getSnapshot=()=>this.#s,this.subscribe=e=>(this.#n.add(e),1===this.#n.size&&(this.#d(),this.#u()),()=>{this.#n.delete(e)&&!(this.#n.size>0)&&(this.#o?.(),this.#o=null,this.#h(),this.#s=gh,this.#a="")}),this.#e=e,this.#t=t}get frameSrc(){return this.#a}watchFrames(e){return this.#r.add(e),this.#a&&e(this.#a),()=>{this.#r.delete(e)}}setVisible(e){e!==this.#i&&(this.#i=e,this.#u())}reconnect(){this.#u()}#d(){if("u"<typeof document)return;let e=()=>this.setVisible("visible"===document.visibilityState);document.addEventListener("visibilitychange",e),this.#o=()=>document.removeEventListener("visibilitychange",e),this.#i="visible"===document.visibilityState}#h(){clearTimeout(this.#c),this.#c=void 0,this.#l?.(),this.#l=null}#u(){this.#h(),this.#i&&0!==this.#n.size&&(this.#l=this.#t(this.#e,{open:()=>this.#p({streamDown:!1}),error:e=>{this.#p({streamDown:!0}),e&&(this.#c=setTimeout(()=>this.#u(),2e3))},message:e=>this.#m(e)}))}#m(e){let t;try{t=JSON.parse(e)}catch{return}if("state"===t.type)return void this.#p({state:t.state});for(let e of(this.#a=`data:image/jpeg;base64,${t.data}`,this.#r))e(this.#a);let{frameSize:n,frameTabId:r}=this.#s;(n?.width!==t.width||n.height!==t.height||r!==t.tabId)&&this.#p({frameSize:{width:t.width,height:t.height},frameTabId:t.tabId,hadView:!0})}#p(e){for(let t of(this.#s={...this.#s,...e},this.#n))t()}}let gm=(e,t)=>{let n=new EventSource(e);return n.onopen=t.open,n.onerror=()=>t.error(n.readyState===EventSource.CLOSED),n.onmessage=e=>t.message(e.data),()=>n.close()},gf=new Map,gg={state:null,streamDown:!1,frameSize:null,frameTabId:null,hadView:!1},gx=()=>gg,gv=["left","middle","right"];function gy(e){return!!e.altKey|2*!!e.ctrlKey|4*!!e.metaKey|8*!!e.shiftKey}function gb({sessionId:e,sessionTitle:t,chrome:n}){let{t:a}=(0,F.s)(),{status:i,state:l,hadView:o,frameSize:c,imageRef:d,bindImage:u,sendInput:h,returnControl:p,selectTab:m,reconnect:f,reportViewport:g}=function(e){let t,n=((t=gf.get(e))||(t=new gp(`/api/agent/${encodeURIComponent(e)}/browser/events`,gm),gf.set(e,t)),t),{state:r,streamDown:a,frameSize:i,frameTabId:l,hadView:o}=(0,s.useSyncExternalStore)(n.subscribe,n.getSnapshot,gx),c=(0,s.useRef)(null),d=(0,s.useCallback)(e=>{c.current=e,e&&n.frameSrc&&(e.src=n.frameSrc)},[n]);(0,s.useEffect)(()=>n.watchFrames(e=>{c.current&&(c.current.src=e)}),[n]);let u=(0,s.useRef)([]),h=(0,s.useRef)(!1),p=`/api/agent/${encodeURIComponent(e)}/browser`,m=(0,s.useRef)(!1);(0,s.useEffect)(()=>(m.current=!1,()=>{m.current=!0,u.current=[]}),[]),(0,s.useEffect)(()=>{u.current=[]},[l]);let f=(0,s.useCallback)(async()=>{if(!h.current){h.current=!0;try{for(;u.current.length>0&&!m.current;){let e=u.current,t=e[0].tabId,n=1;for(;n<e.length&&n<32&&e[n].tabId===t;)n+=1;let r=e.splice(0,n).map(e=>e.event),s=await fetch(`${p}/input`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tabId:t,events:r})}).catch(()=>null);(!s?.ok||m.current)&&(u.current=[])}}finally{h.current=!1}}},[p]),g=(0,s.useCallback)(e=>{let t=n.getSnapshot().frameTabId;if(!t)return;let r=u.current,s=r.at(-1);"mouse"===e.t&&"move"===e.type&&s?.tabId===t&&"mouse"===s.event.t&&"move"===s.event.type?r[r.length-1]={tabId:t,event:e}:r.push({tabId:t,event:e}),f()},[f,n]),x=(0,s.useCallback)(async()=>{u.current=[];try{let e=await fetch(p,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"return"})});return(await e.json()).result??"failed"}catch{return"failed"}},[p]),v=(0,s.useCallback)(e=>{fetch(p,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"tab",tabId:e})}).catch(()=>{})},[p]),y=(0,s.useCallback)(()=>n.reconnect(),[n]),b=(0,s.useRef)(null),w=(0,s.useRef)(!1),k=(0,s.useCallback)((e,t)=>{b.current={width:e,height:t},w.current||(w.current=!0,(async()=>{try{let e=0;for(;;){let t=b.current;if(!t||m.current)return;let n=await fetch(p,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"viewport",...t})}).then(e=>e.ok,()=>!1);if(b.current!==t){e=0;continue}if(n||++e>=3)return;let r=Promise.withResolvers();setTimeout(r.resolve,2e3),await r.promise}}finally{w.current=!1}})())},[p]);return{status:a?o?"lost":"connecting":r?"off"===r.status?o?"lost":"off":"none"===r.status?"none":"lost"===r.status?o?"lost":"connecting":"live"===r.status&&l===r.tabId?"live":"connecting":"connecting",state:r,hadView:o,frameSize:i,imageRef:c,bindImage:d,sendInput:g,returnControl:x,selectTab:v,reconnect:y,reportViewport:k}}(e),[x,v]=(0,s.useState)(null),[y,b]=(0,s.useState)(!1),[w,k]=(0,s.useState)(null),[j,S]=(0,s.useState)(!1),C=(0,s.useRef)(null),N=(0,s.useRef)(null),T=(0,s.useRef)(null),I=(0,s.useRef)(!1),M=l?.ownership==="user",E=M&&"live"===i,$=l?.tabs.find(e=>e.id===l.tabId)??null,R="live"===i||"lost"===i||"connecting"===i&&o;(0,s.useEffect)(()=>{if(!x)return;let e=setTimeout(()=>v(null),4e3);return()=>clearTimeout(e)},[x]),(0,s.useEffect)(()=>{let e=d.current;if(!e||!c||c.width<=0)return;let t=new ResizeObserver(()=>k(Math.round(e.getBoundingClientRect().width/c.width*100)));return t.observe(e),()=>t.disconnect()},[c,R,d]);let L="live"===i,P=(l?.tabs.length??0)>0;(0,s.useEffect)(()=>{let e,t=N.current;if(!t||!L)return;let n="",r=new ResizeObserver(()=>{let r=getComputedStyle(t),s=T.current,a=s?s.getBoundingClientRect().height+parseFloat(getComputedStyle(s).marginBlockStart):0,i=Math.round(t.clientWidth-parseFloat(r.paddingLeft)-parseFloat(r.paddingRight)),l=Math.round(t.clientHeight-parseFloat(r.paddingTop)-parseFloat(r.paddingBottom)-a),o=`${i}x${l}`;window.clearTimeout(e),i<100||l<100||o===n||(e=window.setTimeout(()=>{n=o,g(i,l)},250))});return r.observe(t),T.current&&r.observe(T.current),()=>{r.disconnect(),window.clearTimeout(e)}},[L,P,g]);let A=(0,s.useCallback)((e,t)=>{let n=d.current;if(!n||!c)return null;let r=n.getBoundingClientRect();return r.width<=0||r.height<=0?null:{x:Math.min(Math.max((e-r.left)/r.width*c.width,0),c.width),y:Math.min(Math.max((t-r.top)/r.height*c.height,0),c.height)}},[c,d]);(0,s.useEffect)(()=>{let e=C.current;if(!e||!E)return;let t=e=>{let t=A(e.clientX,e.clientY);if(!t)return;e.preventDefault();let n=e.deltaMode===WheelEvent.DOM_DELTA_LINE?40:1;h({t:"wheel",...t,dx:e.deltaX*n,dy:e.deltaY*n,modifiers:gy(e)})};return e.addEventListener("wheel",t,{passive:!1}),()=>e.removeEventListener("wheel",t)},[E,A,h]);let _=(e,t)=>{let n=A(t.clientX,t.clientY);if(!n)return;let r=gy(t);if("move"===e)return void h({t:"mouse",type:e,...n,modifiers:r});let s=gv[t.button];s&&h({t:"mouse",type:e,...n,button:s,clickCount:Math.min(Math.max(t.detail,1),3),modifiers:r})},O=(e,t)=>{t.nativeEvent.isComposing||"Process"===t.key||"Tab"===t.key||(t.ctrlKey||t.metaKey)&&"v"===t.key.toLowerCase()||(t.preventDefault(),h({t:"key",type:e,key:t.key,modifiers:gy(t)}))},z=e=>{let t=e.length>4e5?null:[...e];if(!t||t.length>2e5)return void v("pasteTooLong");let n="";for(let e of t)n.length+e.length>2e3&&(h({t:"text",text:n}),n=""),n+=e;n&&h({t:"text",text:n})},D=async()=>{b(!0);let e=await p();b(!1),v("returned"===e?"returned":"failed"===e?"failed":null)},W="blocked"===x?a("browserPane.blocked"):"returned"===x?a("browserPane.returned"):"failed"===x?a("browserPane.returnFailed"):"pasteTooLong"===x?a("browserPane.pasteTooLong"):null;return(0,r.jsxs)("div",{className:n?"chat-pane browser-pane":"browser-pane is-inspector","data-turn":M?"user":"agent",onPointerDownCapture:n?.onUse,onFocusCapture:n?.onUse,children:[n&&(0,r.jsxs)("div",{className:"chat-pane-head",children:[(0,r.jsx)("span",{className:"chat-pane-title",title:t,children:a("browserPane.title",{title:t})}),n.onShowChat&&(0,r.jsx)("button",{type:"button",className:"browser-pane-button",onClick:n.onShowChat,children:a("workspace.toChat")}),(0,r.jsx)("button",{type:"button",className:"chat-pane-close",onClick:n.onClose,"aria-label":a("workspace.closePane"),title:a("workspace.closePane"),children:(0,r.jsx)(ep,{name:"x",size:14})})]}),n?.narrowNote&&(0,r.jsx)("p",{className:"browser-pane-narrow",children:n.narrowNote}),"none"===i&&(0,r.jsxs)("div",{className:"browser-pane-empty",children:[(0,r.jsx)("strong",{children:a("browserPane.noneTitle")}),(0,r.jsx)("p",{children:a("browserPane.noneHelp")})]}),"off"===i&&(0,r.jsxs)("div",{className:"browser-pane-empty",children:[(0,r.jsx)("strong",{children:a("browserPane.offTitle")}),(0,r.jsx)("p",{children:a("browserPane.offHelp")}),(0,r.jsx)("button",{type:"button",className:"browser-pane-button",onClick:f,children:a("browserPane.reconnect")})]}),"connecting"===i&&!R&&(0,r.jsx)("div",{className:"browser-pane-empty",role:"status",children:(0,r.jsx)("p",{children:a("browserPane.connecting")})}),R&&(0,r.jsxs)(r.Fragment,{children:["lost"!==i&&(0,r.jsxs)("div",{className:"browser-pane-band","data-turn":M?"user":"agent",children:[(0,r.jsx)("span",{className:"workbench-lamp","data-kind":M?"input":void 0,"aria-hidden":"true"}),(0,r.jsxs)("div",{className:"browser-pane-band-text",role:"status","aria-live":"polite",children:[(0,r.jsx)("strong",{children:M?a("browserPane.stateUser"):a("browserPane.stateAgent")}),(0,r.jsx)("span",{children:W??(M?a("browserPane.stateUserHelp"):a("browserPane.stateAgentHelp"))})]}),M&&(0,r.jsx)("button",{type:"button",className:"browser-pane-button is-primary",onClick:()=>void D(),disabled:y,children:y?a("browserPane.returning"):a("browserPane.return")})]}),(0,r.jsxs)("div",{className:"browser-pane-url",children:[(0,r.jsx)("span",{className:"browser-pane-url-text",title:$?.url,children:$?.url??""}),c&&null!==w&&(0,r.jsx)("span",{className:"browser-pane-scale",children:a("browserPane.scale",{percent:w})}),n&&(n.canSplit||n.enlarged)&&(0,r.jsxs)("button",{type:"button",className:"browser-pane-button is-quiet",onClick:n.onToggleEnlarge,children:[(0,r.jsx)(ep,{name:n.enlarged?"columns-2":"maximize-2",size:13}),n.enlarged?a("browserPane.shrink"):a("browserPane.enlarge")]})]}),"lost"===i&&(0,r.jsxs)("div",{className:"browser-pane-lost",role:"status",children:[(0,r.jsx)("span",{className:"workbench-lamp","data-kind":"off","aria-hidden":"true"}),(0,r.jsxs)("div",{className:"browser-pane-band-text",children:[(0,r.jsx)("strong",{children:a("browserPane.lostTitle")}),(0,r.jsx)("span",{children:a("browserPane.lostHelp")})]}),(0,r.jsx)("button",{type:"button",className:"browser-pane-button",onClick:f,children:a("browserPane.reconnect")})]}),(0,r.jsxs)("div",{className:"browser-pane-scroll",ref:N,children:[(0,r.jsxs)("div",{className:`browser-pane-view${"lost"===i?" is-stale":""}${j?" is-keyboard-focus":""}`,children:[(0,r.jsx)("img",{ref:u,alt:"",draggable:!1}),(0,r.jsx)("textarea",{ref:C,className:"browser-pane-input","aria-label":a("browserPane.viewLabel",{title:$?.title||t}),readOnly:!E,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",spellCheck:!1,onInput:e=>{if(e.nativeEvent instanceof InputEvent&&e.nativeEvent.isComposing)return;let t=e.currentTarget.value;e.currentTarget.value="",E&&t&&z(t)},onMouseDown:e=>{if(I.current=!0,!E){"live"===i&&v("blocked");return}_("down",e)},onMouseUp:e=>{E&&_("up",e)},onMouseMove:e=>{E&&_("move",e)},onContextMenu:e=>{E&&e.preventDefault()},onKeyDown:e=>{E&&O("down",e)},onKeyUp:e=>{E&&O("up",e)},onCompositionEnd:e=>{E&&e.data&&z(e.data),e.currentTarget.value=""},onPaste:e=>{e.preventDefault();let t=e.clipboardData.getData("text/plain");E&&t&&z(t)},onFocus:()=>{S(!I.current),I.current=!1},onBlur:()=>{I.current=!1,S(!1)}})]}),l&&l.tabs.length>0&&(0,r.jsxs)("div",{className:"browser-pane-tabs",ref:T,children:[(0,r.jsxs)("div",{className:"browser-pane-tabs-head",children:[(0,r.jsx)("span",{children:a("browserPane.tabs")}),(0,r.jsxs)("label",{className:"browser-pane-follow",children:[(0,r.jsx)("input",{type:"checkbox",checked:l.follow,onChange:e=>m(e.target.checked?null:l.tabId)}),a("browserPane.followTab")]})]}),(0,r.jsx)("ul",{children:l.tabs.map(e=>{let t=e.id===l.tabId,n=e.id===l.agentTabId;return(0,r.jsx)("li",{children:(0,r.jsxs)("button",{type:"button",className:`browser-pane-tab${t?" is-shown":""}`,"aria-current":t?"true":void 0,"aria-label":a("browserPane.tabPick",{title:e.title||e.url}),onClick:()=>m(e.id),children:[(0,r.jsx)("span",{className:"workbench-lamp","data-kind":n?M?"input":void 0:"off","aria-hidden":"true"}),(0,r.jsx)("span",{className:"browser-pane-tab-title",children:e.title||e.url}),(0,r.jsx)("span",{className:"browser-pane-tab-mark",children:[t?a("browserPane.tabViewing"):null,n&&!M?a("browserPane.tabAgent"):null].filter(Boolean).join(", ")})]})},e.id)})})]})]})]})]})}function gw({sessionId:e,inUse:t,onOpen:n}){let{t:a}=(0,F.s)(),[i,l]=(0,s.useState)(!1);return((0,s.useEffect)(()=>{let t,n=!1,r=async()=>{if(t=void 0,n)return;let s=3e3;if("visible"===document.visibilityState)try{let t=await fetch(`/api/agent/${encodeURIComponent(e)}/browser`,{cache:"no-store"}),r=t.ok?await t.json():{};if(n)return;l("user"===r.ownership),!0!==r.available&&(s=15e3)}catch{}n||(t=window.setTimeout(()=>void r(),s))};return r(),()=>{n=!0,clearTimeout(t)}},[e]),i||t)?(0,r.jsxs)("div",{className:"browser-handoff-notice","data-turn":i?"user":"agent",role:"status",children:[(0,r.jsx)("span",{className:"workbench-lamp","data-kind":i?"input":void 0,"aria-hidden":"true"}),(0,r.jsx)("span",{className:"browser-handoff-notice-text",children:a(i?"browserPane.handoffNotice":"browserPane.useNotice")}),(0,r.jsx)("button",{type:"button",className:`browser-pane-button${i?" is-primary":""}`,onClick:n,children:a(i?"browserPane.handoffAction":"browserPane.useAction")})]}):null}var gk=n(1682),gj=n.n(gk);let gS="omp-web:process-log-wrap",gC=new Set,gN=null;function gT(){if(gN)return gN;try{return"scroll"===window.localStorage.getItem(gS)?"scroll":"wrap"}catch{return"wrap"}}function gI(e){gC.add(e);let t=t=>{t.key===gS&&(gN=null,e())};return window.addEventListener("storage",t),()=>{gC.delete(e),window.removeEventListener("storage",t)}}function gM(e){try{window.localStorage.setItem(gS,e),gN=null}catch{gN=e}gC.forEach(e=>e())}function gE({title:e,data:t,onOpenFile:n,focusRequest:a}){let{t:i}=(0,F.s)(),o=t?.groups??[],[c,d]=(0,s.useState)(()=>new Set),u=(0,s.useSyncExternalStore)(gI,gT,()=>"wrap"),h=(0,s.useRef)(null),[p,m]=(0,s.useState)(null),[f,g]=(0,s.useState)(null),x=a&&a.nonce!==p&&t?function(e,t,n){for(let r of e)for(let e of r.entries){let s=t[e.idx];if(s){if("assistant"===s.role){if((e.blocks??s.content).some(e=>"toolCall"===e.type&&e.toolCallId===n))return r.anchorIdx}else if("bashExecution"===s.role&&`bash-${s.timestamp??""}`===n)return r.anchorIdx}}return null}(o,t.messages,a.toolCallId):null;return a&&null!==x&&(m(a.nonce),g(a),c.has(x)&&d(e=>{let t=new Set(e);return t.delete(x),t})),(0,s.useEffect)(()=>{if(!f)return;let e=h.current?.querySelector(`[data-tool-call-id="${CSS.escape(f.toolCallId)}"]`),t=window.matchMedia("(prefers-reduced-motion: reduce)").matches,n=e?.closest(".process-log-body"),r=e&&n&&e.offsetHeight>n.clientHeight?"start":"center";e?.scrollIntoView({block:r,behavior:t?"auto":"smooth"});let s=window.setTimeout(()=>{g(e=>e===f?null:e)},1600);return()=>window.clearTimeout(s)},[f]),(0,r.jsx)(tG.Provider,{value:null,children:(0,r.jsx)(tY.Provider,{value:f,children:(0,r.jsxs)("section",{ref:h,className:`process-log ${gj().root}`,"aria-label":e,"data-output-wrap":u,children:[(0,r.jsx)(p$,{title:`${o.length} ${i(1===o.length?"process.turn":"process.turns")}`,viewSwitch:{label:i("processLog.outputWrap"),value:u,options:[{value:"wrap",label:i("processLog.wrapLines")},{value:"scroll",label:i("processLog.scrollLines")}],onChange:gM}}),(0,r.jsxs)("div",{className:"process-log-body",children:[t?.status?(0,r.jsxs)("p",{className:"process-log-status",role:"status",children:[(0,r.jsx)("span",{className:"process-log-status-pulse","aria-hidden":"true"}),t.status]}):null,0===o.length?(0,r.jsx)("p",{className:"process-log-empty",children:i("process.empty")}):o.map((e,s)=>{let a=c.has(e.anchorIdx),o=function(e){if(!e||"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(" ")).replace(/\s+/g," ").trim();return 0===t.length?null:t.length>72?`${t.slice(0,72)}…`:t}(t?.messages[e.anchorIdx]),u=[`${e.messageCount} ${i(1===e.messageCount?"chat.message":"chat.messages")}`];return e.toolCallCount>0&&u.push(`${e.toolCallCount} ${i(1===e.toolCallCount?"chat.toolCall":"chat.toolCalls")}`),(0,r.jsxs)("article",{className:"process-log-turn","data-process-turn":e.anchorIdx,children:[(0,r.jsxs)(l.r,{className:"process-log-turn-toggle",variant:"ghost",size:"small",layout:"withText","aria-expanded":!a,onClick:()=>d(t=>{let n=new Set(t);return n.has(e.anchorIdx)?n.delete(e.anchorIdx):n.add(e.anchorIdx),n}),title:a?i("chat.expandProcess"):i("chat.collapseProcess"),children:[(0,r.jsx)("span",{className:"process-log-turn-title",children:o??i("chat.processDetails")}),(0,r.jsx)("span",{className:"process-log-turn-meta",children:u.join(" \xb7 ")})]}),!a&&(0,r.jsx)("div",{className:"process-log-entries",children:e.entries.map((s,a)=>{let i=t?.messages[s.idx];return i?(0,r.jsx)(aC,{message:s.blocks?e1(i,s.blocks,{omitUsage:!0}):i,toolResults:t?.toolResults,modelNames:t?.modelNames,cwd:t?.cwd,onOpenFile:n,entryId:t?.entryIds[s.idx],sessionId:t?.sessionId,showTimestamp:!1,recoveredError:e8(t?.messages??[],s.idx)},`process-${e.anchorIdx}-${a}`):null})})]},`turn-${e.anchorIdx}-${s}`)})]})]})})})}let g$=6,gR="omp-btw-log:",gL="omp-btw-log-index";function gP(e){return e.trim().toLowerCase()}function gA(e){return e.map(e=>({q:e.q,a:e.a,at:e.at}))}function g_(e){if(!Array.isArray(e))return[];let t=[],n=0;for(let r of e){if(!r||"object"!=typeof r||"string"!=typeof r.q||"string"!=typeof r.a)continue;let e={q:r.q,a:r.a,at:"number"==typeof r.at&&Number.isFinite(r.at)?r.at:0};t.push(e),n+=e.q.length+e.a.length}for(;t.length>40||n>12e4;){let e=t.shift();if(!e)break;n-=e.q.length+e.a.length}return t}function gF(e){return!!e&&"object"==typeof e&&("QuotaExceededError"===e.name||22===e.code||1014===e.code)}function gO(e,t={}){let n=t.now??Date.now,r=new Map,s=new Set,a=!1,i=[],l=t=>{if(e)try{e.removeItem(t)}catch{}},o=e=>{r.delete(e),s.delete(e),l(gR+e)},c=()=>{let e=new Set,t=[];for(let n of(i.sort((e,t)=>t.updatedAt-e.updatedAt),i))!n.id||e.has(n.id)||(e.add(n.id),t.length<20?t.push(n):o(n.id));i=t},d=()=>{if(!a){if(a=!0,e)try{let t=e.getItem(gL),n=t?JSON.parse(t):[];Array.isArray(n)&&(i=n.flatMap(e=>e&&"object"==typeof e&&"string"==typeof e.id&&e.id?[{id:gP(e.id),updatedAt:"number"==typeof e.updatedAt&&Number.isFinite(e.updatedAt)?e.updatedAt:0}]:[]))}catch{i=[]}c()}},u=e=>{d();for(let t=i.length-1;t>=0;t-=1){if(i[t].id===e)continue;let[n]=i.splice(t,1);return o(n.id),!0}return!1},h=t=>{if(e){try{e.setItem(gL,JSON.stringify(i));return}catch(e){if(!gF(e)||!u(t))return}try{e.setItem(gL,JSON.stringify(i))}catch{}}},p=t=>{let n=gP(t);if(!n)return[];if(s.has(n))return gA(r.get(n)??[]);if(e)try{let t=e.getItem(gR+n);if(t){let e=JSON.parse(t),s=g_(e?.entries);return r.set(n,s),gA(s)}}catch{}return gA(r.get(n)??[])},m=e=>{let t=gP(e);t&&(d(),i=i.filter(e=>e.id!==t),o(t),h(null))};return{read:p,append:(t,a)=>((t,a)=>{let l=gP(t);if(!l)return[];let o=g_(a),p=n();if(r.set(l,gA(o)),d(),(i=i.filter(e=>e.id!==l)).unshift({id:l,updatedAt:p}),c(),h(l),!e)return gA(o);let m=JSON.stringify({updatedAt:p,entries:o});try{return e.setItem(gR+l,m),s.delete(l),gA(o)}catch(e){if(!gF(e)||!u(l))return s.add(l),gA(o)}h(l);try{e.setItem(gR+l,m),s.delete(l)}catch{s.add(l)}return gA(o)})(t,[...p(t),a]),history:(e,t=g$)=>p(e).slice(-Math.max(0,t)).map(({q:e,a:t})=>({q:e,a:t})),clear:m,cleanup:(t,r)=>{if(!t.complete)return;d();let s=new Map;for(let e of t.sessions){if(!e||"string"!=typeof e.id||!e.id)continue;let t=gP(e.id),n="number"==typeof e.modified?e.modified:Date.parse(e.modified);s.set(t,Number.isFinite(n)?n:0)}let a=r?gP(r):null,o=n();for(let e of[...i])if(e.id!==a){if(!s.has(e.id)){m(e.id);continue}o-Math.max(s.get(e.id)??0,e.updatedAt)>6048e5&&m(e.id)}if(!e||"function"!=typeof e.key||"number"!=typeof e.length)return;let c=[];try{for(let t=0;t<e.length;t+=1){let n=e.key(t);if(!n?.startsWith(gR))continue;let r=gP(n.slice(gR.length));s.has(r)||r===a||c.push(n)}}catch{return}for(let e of c)l(e)}}}function gz(){let e=new Map,t=new Map,n=new Map,r=e=>{n.get(e)?.forEach(e=>{e()})};return{read(t){let n=e.get(t);return n?{...n.snapshot}:null},begin(t,n){if(e.has(t))return null;let s=new AbortController;return e.set(t,{snapshot:{sessionId:t,question:n,text:"",model:null},controller:s}),r(t),{controller:s}},ingest(t,n){let s=e.get(t);s&&("d"===n.t?s.snapshot.text+=n.v:"done"===n.t?s.snapshot.text=n.v||s.snapshot.text:"m"===n.t&&(s.snapshot.model=n.v),r(t))},abort(t){let n=e.get(t);return!!n&&(n.controller.abort(),!0)},finish(n,s){e.has(n)&&(e.delete(n),t.set(n,s),r(n))},takeOutcome(e){let n=t.get(e)??null;return n&&t.delete(e),n},subscribe(e,t){let r=n.get(e);return r||(r=new Set,n.set(e,r)),r.add(t),()=>{r.delete(t),0===r.size&&n.delete(e)}}}}class gD extends Error{constructor(e,t,n){super(t),this.kind=e,this.status=n,this.name="SideChatRequestError"}}function gW(e){let t;try{t=JSON.parse(e)}catch{throw new gD("stream","사이드채팅 스트림을 해석할 수 없습니다.")}if(!t||"object"!=typeof t)throw new gD("stream","사이드채팅 스트림 항목이 올바르지 않습니다.");let n=t;if("d"!==n.t&&"done"!==n.t&&"m"!==n.t&&"err"!==n.t||"string"!=typeof n.v)throw new gD("stream","사이드채팅 스트림 항목이 올바르지 않습니다.");return{t:n.t,v:n.v}}class gH{push(e){this.buffer+="string"==typeof e?e:this.decoder.decode(e,{stream:!0});let t=this.buffer.split("\n");return this.buffer=t.pop()??"",t.flatMap(e=>e.trim()?[gW(e)]:[])}finish(){this.buffer+=this.decoder.decode();let e=this.buffer.trim();return this.buffer="",e?[gW(e)]:[]}constructor(){this.decoder=new TextDecoder,this.buffer=""}}async function gU(e){let t=await e.text().catch(()=>"");if(!t)return`HTTP ${e.status}`;try{let e=JSON.parse(t);if("string"==typeof e.error&&e.error)return e.error}catch{}return t}function gB(e=!1){return{minHeight:30,padding:"4px 9px",borderRadius:"var(--radius-control)",background:"var(--bg-hover)",color:e?"var(--text-dim)":"var(--text-muted)",cursor:e?"default":"pointer",fontSize:"var(--seed-font-size-t2-static)",fontWeight:650}}function gq({children:e}){return(0,r.jsx)("div",{className:"side-chat-question",style:{alignSelf:"flex-end",maxWidth:"92%",padding:"8px 10px",color:"var(--text)",whiteSpace:"pre-wrap",overflowWrap:"anywhere",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.55},children:e})}function gV({children:e,streaming:t=!1}){return(0,r.jsxs)("div",{className:`side-chat-answer${t?" is-streaming":""}`,style:{alignSelf:"flex-start",maxWidth:"100%",padding:"8px 10px",color:"var(--text)",overflowWrap:"anywhere",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.58},children:[e?(0,r.jsx)(nJ,{isStreaming:t,children:e}):t?"응답을 기다리는 중…":null,t&&(0,r.jsx)("span",{"aria-hidden":"true",style:{marginLeft:2,color:"var(--accent)"},children:"▍"})]})}function gK({identity:e,status:t,utteranceKey:n,children:s}){let a=s_(e?.sessionId,e?.provider,e?.credentialId,e?.model),i=cQ(a?.alias,t,n);return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",alignItems:"flex-start",gap:5},children:[a&&e?.provider&&(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:9,minHeight:40,marginBottom:2},children:[(0,r.jsx)(sD,{seed:a.seed,size:40,provider:e.provider}),(0,r.jsx)("span",{style:{fontSize:15,fontWeight:600,color:"var(--text)"},children:a.alias})]}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"flex-start",gap:7,minWidth:0,maxWidth:"100%"},children:[s,i&&(0,r.jsx)("img",{src:i.src,alt:i.alt,width:52,height:52,style:{flex:"0 0 auto",objectFit:"contain"}})]})]})}function gJ({title:e,sessionId:t,sessionPath:n,sessionName:a,historyStore:i,flights:l,sessionCensus:o,client:c,visible:d=!0,onClose:u,onReturnFocus:h}){let p,m,f=(0,s.useMemo)(()=>c??function(e=(e,t)=>fetch(e,t),t="/api/sidecars/sidechat/ask"){return{async ask(n){let r;try{r=await e(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionPath:n.sessionPath,question:n.question,history:n.history.slice(-g$)}),signal:n.signal})}catch(e){if(n.signal?.aborted)throw e;throw new gD("unreachable","사이드채팅 사이드카(30143)에 연결할 수 없습니다.")}if(!r.ok)throw new gD("http",await gU(r),r.status);if(!r.body)throw new gD("stream","사이드채팅 스트림을 열 수 없습니다.");let s=r.body.getReader(),a=new gH,i="",l=null,o=e=>{for(let t of e)if(n.onEvent?.(t),"d"===t.t)i+=t.v;else if("done"===t.t)i=t.v||i;else if("m"===t.t)l=t.v;else throw new gD("server",t.v)};try{for(;;){let e=await s.read();if(e.done)break;o(a.push(e.value))}o(a.finish())}catch(e){if(n.signal?.aborted||e instanceof gD)throw e;throw new gD("stream",e instanceof Error?e.message:"사이드채팅 스트림이 중단되었습니다.")}finally{s.releaseLock()}if(!i)throw new gD("empty","사이드채팅이 빈 응답을 반환했습니다.");return{text:i,model:l}}}}(),[c]),g=t?.toLowerCase()??null,[x,v]=(0,s.useState)([]),[y,b]=(0,s.useState)({}),w=g??"",k=y[w]??"",j=(e,t)=>{b(n=>{if((n[e]??"")===t)return n;let r={...n};return t?r[e]=t:delete r[e],r})},[S,C]=(0,s.useState)(0),[N,T]=(0,s.useState)({}),[I,M]=(0,s.useState)({}),[E,$]=(0,s.useState)({}),[R,L]=(0,s.useState)(null),[P,A]=(0,s.useState)(null),[_,F]=(0,s.useState)({}),[O,z]=(0,s.useState)({}),[D,W]=(0,s.useState)({}),H=(0,s.useRef)((p=new Set,m=new Set,{claim:e=>!(!e||p.has(e)||m.has(e))&&(p.add(e),!0),markSent(e){p.delete(e),m.add(e)},release(e){p.delete(e)}})),U=(0,s.useRef)(!0),B=(0,s.useRef)(g),q=(0,s.useRef)(d),V=(0,s.useRef)(null),K=(0,s.useRef)(!1),J=(0,s.useRef)(0),G=(0,s.useRef)(null);B.current=g,q.current=d,(0,s.useEffect)(()=>(U.current=!0,()=>{U.current=!1}),[]),(0,s.useEffect)(()=>{v(g?i.read(g):[])},[i,g]);let Y=(0,s.useRef)(null);(0,s.useEffect)(()=>{L(null),Y.current=null},[g]),(0,s.useEffect)(()=>{if(!d||!g||Y.current===g)return;let e=!0;return fetch(`/api/sessions/${encodeURIComponent(g)}?deferThinking=1&deferMedia=1`,{cache:"no-store"}).then(async e=>{if(!e.ok)throw Error(`HTTP ${e.status}`);return function(e){if(!e||"object"!=typeof e||!("context"in e))return null;let t=e.context;if(!t||"object"!=typeof t||!("messages"in t))return null;let n=t.messages;if(!Array.isArray(n))return null;for(let e=n.length-1;e>=0;e-=1){let t=n[e];if(!t||"object"!=typeof t||!("role"in t)||"assistant"!==t.role)continue;if(!("provider"in t)||"string"!=typeof t.provider||!t.provider)break;let r="credentialId"in t?t.credentialId:void 0,s="model"in t?t.model:void 0;return{provider:t.provider,..."string"==typeof s&&s?{model:s}:{},..."number"==typeof r&&Number.isSafeInteger(r)&&r>0?{credentialId:r}:{}}}return null}(await e.json())}).then(t=>{e&&(Y.current=g,L(t?{...t,sessionId:g}:null))}).catch(()=>{e&&(Y.current=g,L(null))}),()=>{e=!1}},[g,d]),(0,s.useEffect)(()=>{if(!g)return;let e=()=>{if(!U.current||B.current!==g)return;let e=l.takeOutcome(g);if(e){if("aborted"===e.kind)M(t=>({...t,[g]:e.saved?"응답 생성을 중단했습니다. 받은 내용은 현재 세션 기록에 저장했습니다.":"응답 생성을 중단했습니다."}));else if("failed"===e.kind)T(t=>({...t,[g]:[...t[g]??[],{question:e.question,partialAnswer:e.partialAnswer,kind:e.errorKind,message:e.errorMessage}]})),b(t=>(t[g]??"").trim()?t:{...t,[g]:e.question});else if(e.model){let t=e.model;$(e=>({...e,[g]:t}))}v(i.read(g))}else null===l.read(g)&&v(i.read(g));C(e=>e+1)},t=l.subscribe(g,e);return e(),t},[l,i,g]),(0,s.useEffect)(()=>{o&&i.cleanup(o,g)},[i,g,o]),(0,s.useEffect)(()=>{d&&V.current?.focus()},[d,g]),(0,s.useEffect)(()=>{if(!d)return;let e=requestAnimationFrame(()=>{let e=G.current;e&&(e.scrollTop=e.scrollHeight)});return()=>cancelAnimationFrame(e)},[S,g,x.length,d]);let Z=async e=>{if(!g||!n){let e=g??"";M(t=>({...t,[e]:"세션 파일이 준비되지 않았습니다. 기록이 생성된 뒤 다시 시도하세요."}));return}let t=l.begin(g,e);if(!t)return;let{signal:r}=t.controller;M(e=>{let t={...e};return delete t[g],t});try{let t=await f.ask({sessionPath:n,question:e,history:i.history(g),signal:r,onEvent:e=>l.ingest(g,e)});i.append(g,{q:e,a:t.text,at:Date.now()}),l.finish(g,{kind:"done",model:t.model})}catch(n){let t=l.read(g)?.text??"";if(r.aborted){let n=!1;t&&(i.append(g,{q:e,a:t,at:Date.now()}),n=!0),l.finish(g,{kind:"aborted",saved:n})}else{let r=n instanceof gD?n.kind:"unknown",s=n instanceof Error?n.message:String(n);l.finish(g,{kind:"failed",question:e,partialAnswer:t,errorKind:r,errorMessage:s})}}finally{U.current&&q.current&&V.current?.focus()}},Q=async(e,t,n)=>{if(!g)return;let r=`${g}:${t}`;if(H.current.claim(r)){z(e=>({...e,[r]:"sending"})),W(e=>{let t={...e};return delete t[r],t});try{var s,a;let t,i=await fetch(`/api/agent/${encodeURIComponent(g)}`,{cache:"no-store"}),l=null;try{l=await i.json()}catch{}if(!i.ok){if(l&&"object"==typeof l&&"error"in l&&"string"==typeof l.error)throw Error(l.error);throw Error(`HTTP ${i.status}`)}let o=function(e){if(!e||"object"!=typeof e||!("running"in e)||"boolean"!=typeof e.running)return null;if(!e.running)return!1;if(!("state"in e)||!e.state||"object"!=typeof e.state)return null;let t=e.state;return"isStreaming"in t&&"boolean"==typeof t.isStreaming&&"isPromptRunning"in t&&"boolean"==typeof t.isPromptRunning&&"isBashRunning"in t&&"boolean"==typeof t.isBashRunning&&"isCompacting"in t&&"boolean"==typeof t.isCompacting&&"isHandoffRunning"in t&&"boolean"==typeof t.isHandoffRunning?t.isStreaming||t.isPromptRunning||t.isBashRunning||t.isCompacting||t.isHandoffRunning:null}(l);if(null===o)throw Error("메인 세션 실행 상태를 확인할 수 없습니다.");let c=(s=e.q,a=e.a,t=n.trim(),["사이드채팅 문답을 메인 대화에서 이어서 처리해 주세요.","","[사이드채팅 질문]",s,"","[사이드채팅 답변]",a,...t?["","[추가 지시]",t]:[]].join("\n"));await hx(g,{type:o?"steer":"prompt",message:c}),H.current.markSent(r),z(e=>({...e,[r]:"sent"}))}catch(e){H.current.release(r),z(e=>{let t={...e};return delete t[r],t}),W(t=>({...t,[r]:e instanceof Error?e.message:String(e)}))}}},X=()=>{if(g&&null!==l.read(g))return void l.abort(g);let e=k.trim();e&&(j(w,""),Z(e))},ee=N[g??""]??[],et=I[g??""],en=g?l.read(g):null,er=x.length>0||ee.length>0||null!==en,es=en?.model??E[g??""],ea=!g||!n,ei=null!==en,el=!ei&&!ea&&k.trim().length>0,eo=!g||ei,ec=R?.sessionId===g?R:null;return(0,r.jsxs)("section",{className:"side-chat-panel","aria-label":"사이드채팅","aria-busy":null!==en,"data-state":g&&n?en?"streaming":"ready":"unavailable",style:{display:"flex",flexDirection:"column",width:"100%",height:"100%",minWidth:0,minHeight:0,overflow:"hidden",background:"var(--bg-panel)",color:"var(--text)"},children:[(0,r.jsxs)("header",{style:{display:"flex",alignItems:"center",gap:8,minHeight:42,padding:"6px 10px",background:"var(--bg-panel)"},children:[(0,r.jsxs)("div",{style:{minWidth:0,flex:1},children:[(0,r.jsx)("div",{style:{fontSize:"var(--seed-font-size-t3-static)",fontWeight:600},children:e}),(0,r.jsxs)("div",{title:n??void 0,style:{marginTop:2,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"var(--text-muted)",fontFamily:"var(--font-mono)",fontSize:"var(--seed-font-size-t2-static)"},children:[a||g?.slice(0,8)||"세션 없음",es?` \xb7 ${es}`:""]})]}),(0,r.jsx)("button",{type:"button",onClick:()=>{g&&null===l.read(g)&&(i.clear(g),v([]),T(e=>{let t={...e};return delete t[g],t}),M(e=>({...e,[g]:"현재 세션의 사이드채팅 기록을 비웠습니다."})))},disabled:eo,style:gB(eo),children:"Clear"}),u&&(0,r.jsx)("button",{type:"button",onClick:()=>{u?.(),h?.()},"aria-label":"사이드채팅 닫기",title:"닫기",style:{...gB(),width:32,padding:0},children:(0,r.jsx)("svg",{width:"13",height:"13",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"m4 4 8 8M12 4l-8 8"})})})]}),(0,r.jsxs)("div",{ref:G,"aria-live":"polite",style:{display:"flex",flex:1,minHeight:0,flexDirection:"column",gap:7,overflowY:"auto",padding:"11px 12px 18px"},children:[g&&n?(0,r.jsxs)(r.Fragment,{children:[x.map((e,t)=>{let n=`${e.at}:${t}`,s=`${g}:${n}`,a=O[s],i=P===s;return(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:6,marginBottom:5},children:[(0,r.jsx)(gq,{children:e.q}),(0,r.jsx)(gK,{identity:ec,status:"settled",utteranceKey:n,children:(0,r.jsx)(gV,{children:e.a})}),"sent"===a?(0,r.jsx)("span",{role:"status",style:{color:"var(--text-muted)",fontSize:10.5},children:"보냄"}):(0,r.jsxs)(r.Fragment,{children:[!i&&(0,r.jsx)("button",{type:"button","aria-expanded":"false",onClick:()=>A(s),style:{...gB(),alignSelf:"flex-start"},children:"메인에 보내기"}),i&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",alignItems:"flex-start",gap:6},children:[(0,r.jsx)("label",{htmlFor:`side-chat-forward-${t}`,style:{color:"var(--text-muted)",fontSize:10.5},children:"메인에 덧붙일 지시 (선택)"}),(0,r.jsx)("textarea",{id:`side-chat-forward-${t}`,rows:2,value:_[s]??"",onChange:e=>F(t=>({...t,[s]:e.target.value})),style:{width:"100%",minWidth:0,boxSizing:"border-box",resize:"vertical",padding:"7px 8px",borderRadius:"var(--radius-control)",background:"var(--bg-hover)",color:"var(--text)",fontFamily:"var(--seed-font-family)",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.5}}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:6},children:[(0,r.jsx)("button",{type:"button",onClick:()=>void Q(e,n,_[s]??""),disabled:"sending"===a,style:gB("sending"===a),children:"sending"===a?"보내는 중…":"메인으로 전송"}),"sending"!==a&&(0,r.jsx)("button",{type:"button",onClick:()=>A(null),style:gB(),children:"취소"})]})]}),D[s]&&(0,r.jsx)("div",{role:"alert",style:{color:"var(--danger)",fontSize:10.5,lineHeight:1.5,overflowWrap:"anywhere"},children:D[s]})]})]},n)}),ee.map((e,t)=>(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:6,marginBottom:5},children:[(0,r.jsx)(gq,{children:e.question}),(0,r.jsxs)(gK,{identity:ec,status:"failed",utteranceKey:`failed:${e.question}:${t}`,children:[e.partialAnswer&&(0,r.jsx)(gV,{children:e.partialAnswer}),(0,r.jsx)("div",{role:"alert","data-error-kind":e.kind,style:{padding:"7px 9px",borderRadius:"var(--radius-surface)",background:"var(--danger-soft)",color:"var(--text)",fontSize:10.5,lineHeight:1.5,overflowWrap:"anywhere"},children:e.message})]})]},`${e.question}:${t}`)),en&&(0,r.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:6,marginBottom:5},children:[(0,r.jsx)(gq,{children:en.question}),(0,r.jsx)(gK,{identity:ec,status:"streaming",utteranceKey:`stream:${en.question}`,children:(0,r.jsx)(gV,{streaming:!0,children:en.text})})]}),!er&&(0,r.jsxs)("div",{style:{margin:"auto 0",padding:16,color:"var(--text-muted)",textAlign:"center",fontSize:11,lineHeight:1.65},children:["현재 세션의 전체 맥락을 보고 답합니다.",(0,r.jsx)("br",{}),"사이드채팅 기록은 부모 세션별로 보관됩니다."]})]}):(0,r.jsxs)("div",{role:"status",style:{margin:"auto 0",padding:16,color:"var(--text-muted)",textAlign:"center",fontSize:11,lineHeight:1.6},children:["세션 기록을 준비하는 중입니다.",(0,r.jsx)("br",{}),"세션 파일이 생성되면 사이드채팅을 사용할 수 있습니다."]}),et&&(0,r.jsx)("div",{role:"status",style:{padding:"7px 9px",color:"var(--text-muted)",fontSize:10.5,lineHeight:1.5},children:et})]}),(0,r.jsxs)("form",{onSubmit:e=>{e.preventDefault(),X()},style:{display:"flex",flexDirection:"column",gap:6,padding:"9px 10px",background:"var(--bg-panel)"},children:[(0,r.jsx)("label",{htmlFor:"side-chat-question",style:{color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",fontWeight:600},children:"사이드채팅 질문"}),(0,r.jsx)("textarea",{ref:V,id:"side-chat-question",rows:4,value:k,onChange:e=>j(w,e.target.value),onCompositionStart:()=>{K.current=!0},onCompositionEnd:()=>{K.current=!1,J.current=Date.now()},onKeyDown:e=>{if("Enter"!==e.key||e.shiftKey)return;let t=e.nativeEvent,n=Date.now()-J.current<100;if(K.current||t.isComposing||229===t.keyCode||n){n&&e.preventDefault();return}ei||(e.preventDefault(),X())},disabled:ei||ea,placeholder:"질문 입력 — Enter 전송, Shift+Enter 줄바꿈",style:{width:"100%",minWidth:0,minHeight:88,maxHeight:240,boxSizing:"border-box",resize:"vertical",padding:"8px 9px",borderRadius:"var(--radius-control)",background:"var(--bg-hover)",color:"var(--text)",fontFamily:"var(--seed-font-family)",fontSize:"var(--seed-font-size-t3-static)",lineHeight:1.5}}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8},children:[(0,r.jsx)("span",{"aria-live":"polite",style:{flex:1,minWidth:0,color:"var(--text-muted)",fontSize:"var(--seed-font-size-t2-static)",lineHeight:1.4,overflowWrap:"anywhere"},children:ea?"세션 파일이 준비되면 질문할 수 있습니다.":ei?"응답을 받는 중입니다.":"Enter 전송 \xb7 Shift+Enter 줄바꿈"}),(0,r.jsx)("button",{type:"submit",disabled:!ei&&!el,style:gB(!ei&&!el),children:ei?"중단":"전송"})]})]})]})}let gG="min-h-9 bg-bg-hover px-3 text-xs font-medium text-text transition-colors hover:bg-bg-selected disabled:cursor-not-allowed disabled:opacity-50",gY="pointer-coarse:min-h-11 pointer-coarse:min-w-11 max-sm:min-h-11 max-sm:min-w-11",gZ="mx-3 mb-2 rounded-[var(--radius-surface)] bg-bg px-3 py-3",gQ="m-0 px-4 pb-1.5 pt-4 text-xs font-semibold text-text-muted",gX="mx-3 mb-2 rounded-[var(--radius-control)] bg-bg px-3 py-2 text-xs";function g0(...e){return e.filter(Boolean).join(" ")}function g1(e,t){let n=Math.floor((e-t)/6e4);if(n<=0)return"리셋됨";let r=Math.floor(n/1440),s=Math.floor(n%1440/60),a=n%60;return r>0?`${r}d ${s}h 후 리셋`:s>0?`${s}h ${a}m 후 리셋`:`${a}m 후 리셋`}function g2(e,t){if(!e)return null;let n=Date.parse(e);if(!Number.isFinite(n))return null;let r=Math.floor((n-t)/6e4);if(r<=0)return"만료됨";let s=Math.floor(r/1440),a=Math.floor(r%1440/60),i=r%60;return s>0?`${s}d ${a}h 후 만료`:a>0?`${a}h ${i}m 후 만료`:`${i}m 후 만료`}function g4(e){return"number"==typeof e&&Number.isFinite(e)?0===e?"$0":e>=100?`$${e.toFixed(0)}`:e>=1?`$${e.toFixed(2)}`:e>=.01?`$${e.toFixed(3)}`:`$${e.toFixed(4)}`:"—"}function g8(e,t){return!1!==t?g4(e):"number"==typeof e&&Number.isFinite(e)&&0!==e?`≥${g4(e)}`:"가격 미상"}function g5(e){return"number"==typeof e&&Number.isFinite(e)?Math.round(e).toLocaleString("en-US"):"—"}function g6(e){return"number"==typeof e&&Number.isFinite(e)?e>=1e9?`${(e/1e9).toFixed(1)}B`:e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${Math.round(e/1e3)}K`:String(Math.round(e)):"—"}function g3(e,t=0){return"number"==typeof e&&Number.isFinite(e)?`${(100*e).toFixed(t)}%`:"—"}function g7(e){return"number"==typeof e&&Number.isFinite(e)?`${(e/1e3).toFixed(1)}s`:"—"}function g9(e){let t=new Date(e);return`${t.getMonth()+1}/${t.getDate()}`}function xe({label:e,value:t}){return(0,r.jsxs)("div",{className:"flex min-w-0 items-baseline justify-between gap-3 py-1.5",children:[(0,r.jsx)("dt",{className:"text-xs text-text-muted",children:e}),(0,r.jsx)("dd",{className:"m-0 font-mono text-xs tabular-nums text-text",children:t})]})}function xt({state:e,loading:t,subject:n}){return t&&"idle"===e.status?(0,r.jsxs)("div",{className:"p-4 text-sm text-text-muted",role:"status",children:[n," 불러오는 중…"]}):"error"===e.status?(0,r.jsxs)("div",{className:"p-4 text-sm text-text",role:"alert",children:[(0,r.jsxs)("div",{className:"font-medium",children:[n,"을 불러오지 못했습니다."]}),(0,r.jsx)("div",{className:"mt-1 text-xs text-text-muted",children:e.error.message}),(0,r.jsx)("div",{className:"mt-2 text-xs text-text-dim",children:"사이드카(127.0.0.1:30142)가 실행 중인지 확인하세요."})]}):"stale"===e.status?(0,r.jsxs)("div",{className:g0(gX,"text-text-muted"),role:"status",children:["마지막 데이터를 표시합니다. 새로고침 실패: ",e.error.message]}):null}function xn(e){let t=new Date(e),n=String(t.getHours()).padStart(2,"0"),r=String(t.getMinutes()).padStart(2,"0");return`${t.getMonth()+1}/${t.getDate()} ${n}:${r}`}function xr({limit:e,now:t,detailed:n}){let s="number"==typeof e.amount?.usedFraction?e.amount.usedFraction:0,a=Math.max(0,Math.min(100,100*s)),i=Math.round(100*s),l=function(e,t){let n=e.window,r=e.amount?.usedFraction;if(!n?.resetsAt||"number"!=typeof r)return null;let s=Math.max(0,n.resetsAt-t),a=100*r,i=Math.max(0,100-a);if(!n.durationMs){let e=s/864e5;return{burnOnly:!0,unit:"하루",partial:e<1,burn:e>=1?i/e:i}}let l=Math.min(n.durationMs,Math.max(0,n.durationMs-s)),o=n.durationMs>432e5,c=o?864e5:36e5,d=n.durationMs/c,u=s/c,h=l/n.durationMs*100;return{burnOnly:!1,unit:o?"하루":"시간",partial:u<1,burn:u>=1?i/u:i,pacePct:h,deltaPct:a-h,nominal:100/d}}(e,t),o=e.daySlot,c=o?.usedPct==null||null==o.baselinePct?null:Math.max(0,Math.min(o.baselinePct,100)),d=null==c?null:Math.max(c,Math.min(100*s,100)),u=l?.pacePct==null?null:Math.min(l.pacePct,99.6),h=i>=90,p=l?.deltaPct!=null&&l.deltaPct>=.5?l.deltaPct:null,m=o?"unknown"===o.quality||null==o.usedPct?"구간 사용 — 기록 부족":"approx"===o.quality?`구간 사용 ≈${o.usedPct.toFixed(0)}% \xb7 추정`:"estimate"===o.quality?`구간 사용 ≥${o.usedPct.toFixed(0)}% \xb7 추정`:`구간 사용 ${o.usedPct.toFixed(1)}%`:null;return(0,r.jsxs)("div",{className:"usage-limit py-2",children:[(0,r.jsxs)("div",{className:"flex items-baseline justify-between gap-2",children:[(0,r.jsx)("span",{className:"min-w-0 flex-1 truncate text-[13px] text-text-muted",children:e.label||e.id}),s>=1?(0,r.jsx)("span",{className:"usage-chip","data-tone":"danger",children:s>1?"한도 초과":"한도 도달"}):null,null!=p?(0,r.jsx)("span",{className:"usage-chip","data-tone":"warning",children:`과속 +${p.toFixed(1)}%`}):null,(0,r.jsxs)("span",{className:g0("shrink-0 font-mono text-sm font-semibold tabular-nums",h?"text-danger":"text-text"),children:[i,"%"]})]}),(0,r.jsxs)("div",{className:"relative mt-1 h-3.5 bg-metric-track",role:"progressbar","aria-label":`${e.label||e.id} 사용량`,"aria-valuemin":0,"aria-valuemax":100,"aria-valuenow":i,children:[(0,r.jsx)("div",{className:g0("absolute inset-y-0 left-0",h?"bg-danger":"bg-metric"),style:{width:`${a}%`}}),null!=c&&null!=d&&d>c?(0,r.jsx)("div",{className:"absolute inset-y-0 bg-metric-recent",style:{left:`${c}%`,width:`${d-c}%`}}):null,null!=u?(0,r.jsx)("div",{className:"absolute -inset-y-1 w-0.5 bg-text",style:{left:`${u}%`},"aria-hidden":"true"}):null,s>1?(0,r.jsx)("div",{className:"absolute inset-y-0 right-0 w-1 bg-danger","aria-hidden":"true"}):null]}),m||e.window?.resetsAt?(0,r.jsxs)("div",{className:"mt-1 flex items-baseline justify-between gap-3 font-mono text-[11px] tabular-nums text-text-muted",children:[(0,r.jsx)("span",{className:"min-w-0 truncate",children:m??""}),e.window?.resetsAt?(0,r.jsx)("span",{className:"shrink-0",children:g1(e.window.resetsAt,t)}):null]}):null,n?(0,r.jsxs)("dl",{className:"m-0 mt-1.5",children:[l?.pacePct!=null?(0,r.jsx)(xe,{label:"페이스",value:`${l.pacePct.toFixed(1)}%`}):null,l?(0,r.jsx)(xe,{label:l.partial?"남은 한도":`앞으로 ${l.unit}`,value:`${l.burn.toFixed(1)}%`}):null,l?.nominal!=null?(0,r.jsx)(xe,{label:"균등 배분 기준",value:`${l.nominal.toFixed(1)}%/${"하루"===l.unit?"일":"시간"} \xb7 계산값`}):null,o?(0,r.jsx)(xe,{label:"구간",value:`${xn(o.slotStart)} ~ ${xn(o.slotEnd)} \xb7 ${o.slotIndex+1}/${o.slotCount}`}):null,o?(0,r.jsx)(xe,{label:"기록 품질",value:function(e){let t;if("unknown"===e.quality)return"기록 부족 \xb7 구간 시작 전 표본이 없습니다";if("estimate"===e.quality){let t=null==e.firstSeenAt?"?":xn(e.firstSeenAt);return`추정 \xb7 구간 시작 표본이 없어 ${t}부터 센 최소량${e.paceOver?" \xb7 주간 진도 초과":""}`}let n=null==e.gapMs||0===e.gapMs?null:(t=Math.round(e.gapMs/6e4))<60?`${t}분`:`${Math.floor(t/60)}시간 ${t%60}분`;return"exact"===e.quality?n?`실측 \xb7 경계 ${n} 전 표본`:"실측 \xb7 구간 시작이 창의 시작":`추정 \xb7 경계 ${n??"?"} 전 표본`}(o)}):null]}):null]})}function xs({confirmId:e,pending:t,primaryRef:n,summary:s,onConfirm:a,onCancel:i}){return(0,r.jsxs)("div",{className:"resource-reset resource-reset-confirm-group","data-reset-state":t?"pending":"confirming","data-dismissible-layer":!0,role:"group","aria-label":"리셋 사용 확인",onKeyDown:e=>{"Escape"===e.key&&(e.preventDefault(),e.stopPropagation(),i())},children:[(0,r.jsx)("p",{className:"m-0 text-xs leading-5 text-text-muted",children:s}),(0,r.jsx)("p",{id:e,className:"m-0 text-xs leading-5 text-text",children:"리셋 1개를 지금 사용합니다. 되돌릴 수 없습니다."}),(0,r.jsx)("p",{className:"m-0 mt-1 text-xs leading-5 text-text-muted",children:"이 계정의 차단 기록도 함께 지워집니다."}),(0,r.jsxs)("div",{className:"mt-2 flex flex-wrap justify-end gap-2",children:[(0,r.jsx)("button",{ref:n,type:"button",className:g0(gG,"resource-reset-confirm"),"aria-describedby":e,disabled:t,onClick:a,children:t?"사용 중…":"리셋 사용"}),(0,r.jsx)("button",{type:"button",className:gG,disabled:t,onClick:i,children:"취소"})]})]})}function xa({report:e,brokerOk:t,now:n,active:a,identity:i,recommendation:l,pendingAction:o,feedback:c,onToggle:d,onReset:u,t:h}){let p=e.metadata??{},m=i??si([e])[0],f=e.credentialId,g=Number.isSafeInteger(f)&&f>0,x=e.accountRole,v="usage-only"===x?"사용량":"control-only"===x?"계정 제어":p.planType,y=!0!==e.disabled&&"number"==typeof e.autoBlockedUntilMs&&e.autoBlockedUntilMs>n,b=a?"active":e.disabled?"off":y?"auto-blocked":"idle",w="toggle"===o?"전환 중…":"reset"===o?"리셋 사용 중…":g?a?"현재 사용 \xb7 이 세션":e.disabled?"꺼둠":y?`자동 차단 \xb7 ${g1(e.autoBlockedUntilMs,n)}`:"control-only"===x?"로그인 계정 \xb7 ON/OFF 제어":"대기":"usage-only"===x?"할당량 정보 \xb7 계정 연결 없음":"제어 불가 \xb7 credential id 없음",k=(0,s.useId)(),j=(0,s.useId)(),[S,C]=(0,s.useState)(!1),[N,T]=(0,s.useState)(!1),[I,M]=(0,s.useState)(null),E=(0,s.useRef)(null),$=(0,s.useRef)(null),R=(0,s.useRef)(!1),L=(0,s.useRef)(!1),P="openai-codex"===e.provider||"anthropic"===e.provider?e.savedReset:void 0,A="anthropic"===e.provider&&P?.state==="available"?P.credits:[],_=A.find(e=>e.id===P?.nextCreditId)??null,F="openai-codex"===e.provider?function(e){let t=e.savedReset?.credits??[],n=null;for(let e of t){if(!e.id)continue;let t=e.expiresAt?Date.parse(e.expiresAt):NaN,r=Number.isFinite(t)?t:null;(!n||null!=r&&(null==n.timestamp||r<n.timestamp))&&(n={id:e.id,expiresAt:e.expiresAt,timestamp:r})}return n?{id:n.id,expiresAt:n.expiresAt}:null}(e):null,O=F?.id??null,z=g2(F?.expiresAt??null,n),D=P?.availableCount,W=P&&"unavailable"!==P.state?"empty"===P.state||0===D?`없음${P.unconfirmed?" \xb7 확인 중":""}`:"anthropic"===e.provider?`${D??A.length}개${P.unconfirmed?" \xb7 확인 중":""}`:`${D??P.credits.length}개${z?` \xb7 ${z}`:""}`:"확인 불가",H=`저장된 리셋 ${W}`,U=function(e,t){if(!e)return null;if("blocked-account"===e.reason){if(e.scope)return`권고 — ${e.scope}가 소진됐습니다. 저장된 리셋권 사용을 검토하세요.`;let n="number"==typeof e.naturalResetAt?g1(e.naturalResetAt,t).replace(/ 후 리셋$/,""):null;return n?`권고 — 지금 쓸 수 있는 다른 계정이 없고 자연 리셋까지 ${n} 남았습니다.`:"권고 — 지금 쓸 수 있는 다른 계정이 없어 저장된 리셋 사용을 검토하세요."}let n=g2(e.expiresAt??null,t),r="number"==typeof e.usedFraction?` 현재 ${Math.round(100*e.usedFraction)}% 소모한 ${"weekly"===e.window?"주간":"5시간"} 한도를 초기화할 수 있습니다.`:"";return`권고 — 리셋 1개가 ${n&&"만료됨"!==n?n:"곧 만료"}됩니다.${r}`}(l,n),B="openai-codex"===e.provider&&t&&!0!==e.disabled&&P?.state==="available"&&0!==D&&null!=O;(0,s.useLayoutEffect)(()=>{if(I)return void $.current?.focus();if(R.current){var e;R.current=!1,e=E.current,e?.focus()}},[I]),(0,s.useEffect)(()=>{"reset"!==o&&(e.disabled||!t||P?.state!=="available")&&(R.current=!1,M(null))},[t,o,e.disabled,P?.state]);let q=async()=>{if(I&&!L.current){L.current=!0;try{await u(e,I.creditId)}finally{L.current=!1,R.current=!0,M(null)}}},V=(e.limits??[]).reduce((e,t)=>{let r=t.window?.resetsAt;return"number"!=typeof r||r<=n?e:null==e||r<e?r:e},null),K=o?"pending":a?"active":e.disabled?"off":y?"blocked":"idle";return(0,r.jsxs)("section",{className:g0("resource-account",gZ),"data-account-state":b,"aria-current":a?"true":void 0,children:[(0,r.jsxs)("div",{className:"resource-account-head flex min-w-0 items-start gap-2.5",children:[(0,r.jsx)(sD,{seed:m.seed,size:48,provider:e.provider}),(0,r.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,r.jsxs)("h3",{className:"m-0 flex min-w-0 flex-wrap items-baseline gap-x-1.5 text-sm font-semibold text-text",children:[(0,r.jsx)("span",{children:m.alias}),(0,r.jsx)("span",{className:"min-w-0 truncate text-xs font-normal text-text-muted",children:`${sa(e.provider)}${v?` \xb7 ${v}`:""}`})]}),(0,r.jsxs)("div",{className:"mt-1 flex flex-wrap items-center gap-1.5",children:[(0,r.jsx)("span",{className:"resource-account-state resource-account-badge","data-tone":K,role:o?"status":void 0,children:w}),null!=V&&V-n<=72e5?(0,r.jsx)("span",{className:"usage-chip",children:`곧 리셋 \xb7 ${g1(V,n).replace(/ 후 리셋$/,"")}`}):null]})]}),g?(0,r.jsxs)("span",{className:"resource-account-toggle",children:[(0,r.jsx)("span",{className:"resource-account-toggle-label",children:"사용 설정"}),(0,r.jsx)("button",{type:"button",role:"switch",className:g0(gG,"resource-account-switch min-w-[3.25rem]"),disabled:null!=o||!t,"aria-label":`${m.alias} 계정 사용 설정`,"aria-checked":!e.disabled,"aria-busy":null!=o||void 0,title:t?void 0:"제어 서버에 연결할 수 없습니다.",onClick:()=>{R.current=!1,M(null),d(e)},children:e.disabled?"OFF":"ON"})]}):null]}),e.disabled?(0,r.jsx)("div",{className:"mt-2 text-xs text-text-muted",children:"다른 계정이 있으면 이 계정을 사용하지 않습니다."}):y?(0,r.jsx)("div",{className:"mt-2 text-xs text-text-muted",children:(e.limits??[]).some(rO)?"한도를 다 써서 코어가 자동으로 차단했습니다.":"한도는 남아 있지만 토큰 갱신 실패나 일시 오류로 코어가 잠시 막았습니다. 해제 시각이 지나면 다시 씁니다."}):null,c?(0,r.jsx)("div",{className:"mt-2 text-xs text-text",role:"error"===c.tone?"alert":"status",children:c.message}):null,(0,r.jsxs)("div",{id:j,className:"resource-account-limits",children:[S?(0,r.jsxs)("div",{className:"flex items-baseline justify-between gap-3 py-2",children:[(0,r.jsx)("span",{className:"text-xs text-text-muted",children:"계정"}),(0,r.jsxs)("span",{className:"flex min-w-0 items-baseline gap-2",children:[(0,r.jsx)("span",{className:"min-w-0 truncate font-mono text-xs text-text",children:N?m.raw:m.masked||"—"}),m.raw?(0,r.jsx)("button",{type:"button",className:"resource-account-reveal","aria-pressed":N,onClick:()=>T(!N),children:N?"가리기":"이메일 보기"}):null]})]}):null,(e.limits??[]).map(e=>(0,r.jsx)(xr,{limit:e,now:n,detailed:S},e.id))]}),(e.limits??[]).length>0||m.raw?(0,r.jsx)("button",{type:"button",className:"resource-account-more","aria-expanded":S,"aria-controls":j,onClick:()=>{let e=!S;C(e),e||T(!1)},children:S?"간단히":"자세히"}):null,"openai-codex"===e.provider||"anthropic"===e.provider?I?(0,r.jsx)(xs,{confirmId:k,pending:"reset"===o,primaryRef:$,summary:I.summary,onConfirm:()=>{q()},onCancel:()=>{R.current=!0,M(null)}}):(0,r.jsxs)("div",{className:"resource-reset mt-3","data-reset-state":t?P&&"unavailable"!==P.state?"empty"===P.state||0===D?"empty":"reset"===o?"pending":"ready":"unavailable":"offline",children:[(0,r.jsxs)("div",{className:"flex flex-wrap items-baseline gap-x-3 gap-y-1.5",children:[(0,r.jsxs)("div",{className:"flex min-w-[10.5rem] flex-1 items-baseline justify-between gap-x-3",children:[(0,r.jsx)("span",{className:"text-xs text-text-muted",children:"저장된 리셋"}),(0,r.jsx)("span",{className:g0("font-mono text-xs tabular-nums text-text",l?.reason==="expiring-credit"&&"text-warning"),children:W})]}),B?(0,r.jsx)("button",{ref:E,type:"button",className:g0(gG,"ml-auto flex-none"),disabled:null!=o,onClick:()=>{O&&M({creditId:O,summary:H})},children:"리셋 사용"}):t&&e.disabled&&P?.state==="available"?(0,r.jsx)("span",{className:"ml-auto text-xs text-text-muted",children:"켠 뒤 사용 가능"}):null]}),A.length>0?(0,r.jsx)("ul",{className:"resource-reset-credits m-0 mt-1.5 list-none space-y-1 p-0","aria-label":"저장된 리셋 종류",children:A.map(s=>{let a,i,l,c=(i=(a=s.clears??[]).map(e=>{switch(e){case"anthropic:5h":return h("resource.reset.window.fiveHour");case"anthropic:7d":return h("resource.reset.window.weekly");case"anthropic:7d:fable":return h("resource.reset.includedOverage");case"anthropic:7d:opus":return`Opus ${h("resource.reset.window.weekly")}`;case"anthropic:7d:sonnet":return`Sonnet ${h("resource.reset.window.weekly")}`;default:return e}}),l=a.map(e=>/^anthropic:7d:(.+)$/.exec(e)?.[1]).find(e=>void 0!==e),{name:a.includes("anthropic:7d")?h("resource.reset.name.full"):a.includes("anthropic:7d:fable")?h("resource.reset.name.fable"):l?`${"opus"===l?"Opus":"sonnet"===l?"Sonnet":l} ${h("resource.reset.name.generic")}`:a.includes("anthropic:5h")?h("resource.reset.name.fiveHour"):h("resource.reset.name.generic"),covers:i.length?h("resource.reset.covers",{limits:[...new Set(i)].join(", ")}):null}),d=s.id===_?.id,u=g2(s.expiresAt,n),p=s.remainingCount??1,m=t&&g&&!0!==e.disabled&&P?.unconfirmed!==!0&&P?.eligible===!0&&!0===s.usable&&p>0;return(0,r.jsxs)("li",{className:"flex flex-wrap items-baseline gap-x-2 text-xs","data-reset-next":d?"true":void 0,children:[(0,r.jsx)("span",{className:g0("font-medium",d?"text-text":"text-text-muted"),children:p>1?`${c.name} ${p}개`:c.name}),d?(0,r.jsx)("span",{className:"usage-chip",children:h("resource.reset.chip.nextUse")}):null,(0,r.jsx)("span",{className:"min-w-0 text-text-muted",children:[c.covers,u].filter(Boolean).join(", ")}),m?(0,r.jsx)("button",{ref:e=>{e&&E.current?.dataset.creditId===s.id&&(E.current=e)},"data-credit-id":s.id,type:"button",className:g0(gG,"ml-auto flex-none"),disabled:null!=o,"aria-label":`${c.name}: ${h("resource.reset.use")}`,onClick:e=>{E.current=e.currentTarget,M({creditId:s.id,summary:[h("resource.reset.summary",{name:c.name}),c.covers,u].filter(Boolean).join(", ")})},children:h("resource.reset.use")}):(0,r.jsx)("span",{className:"ml-auto text-text-muted",children:P?.unconfirmed?"확인 중":h("resource.reset.unavailable")})]},s.id)})}):null,U?(0,r.jsx)("p",{className:"m-0 mt-1.5 text-xs leading-5 text-text-muted",children:U}):null]}):null]})}function xi({state:e,loading:t,accountState:n,pendingActions:s,feedbackByCredential:a,onToggle:i,onReset:l,t:o}){let c=nG(1e4);sF();let d=e.data,u=n?.state==="resolved"&&"session-pin"===n.source&&Number.isSafeInteger(n.credentialId)&&n.credentialId>0?n.credentialId:null,h=si(d?.reports??[]),p=null==u?-1:d?.reports.findIndex(e=>e.credentialId===u)??-1;return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(xt,{state:e,loading:t,subject:"사용량"}),d?.brokerOk===!1?(0,r.jsx)("div",{className:g0(gX,"text-text-muted"),role:"status",children:"제어 서버에 연결할 수 없어 계정 전환과 리셋 사용을 잠시 쓸 수 없습니다. 사용량 표시는 계속 갱신됩니다."}):null,(0,r.jsxs)("div",{className:"flex min-h-7 items-center gap-4 px-4 text-[11px] font-semibold text-text-muted","aria-label":"사용량 그래프 범례",children:[(0,r.jsxs)("span",{className:"inline-flex items-center gap-1.5",children:[(0,r.jsx)("span",{className:"size-2 bg-metric","aria-hidden":"true"}),"누적"]}),(0,r.jsxs)("span",{className:"inline-flex items-center gap-1.5",children:[(0,r.jsx)("span",{className:"size-2 bg-metric-recent","aria-hidden":"true"}),"이번 구간"]}),(0,r.jsxs)("span",{className:"inline-flex items-center gap-1.5",children:[(0,r.jsx)("span",{className:"h-3 w-0.5 bg-text","aria-hidden":"true"}),"페이스"]})]}),d&&0===d.reports.length?(0,r.jsx)("div",{className:"p-4 text-sm text-text-muted",children:"인증된 계정의 사용량 정보가 없습니다. `omp usage`로 확인하세요."}):null,d?.reports.map((e,t)=>{let u=e.credentialId;return(0,r.jsx)(xa,{report:e,brokerOk:!0===d.brokerOk,now:c,active:t===p,identity:h[t],recommendation:null==u?void 0:n?.resetRecommendations.find(e=>e.credentialId===u),pendingAction:null==u?null:s.get(u)??null,feedback:null==u?void 0:a.get(u),onToggle:i,onReset:l,t:o},`${e.provider}:${u??e.metadata?.accountId??e.metadata?.email??t}`)})]})}let xl={invalid_total:!0,invalid_start_date:!0,start_date_in_future:!0,session_scan_failed:!0,session_scan_partial:!0,internal:!0,settings_unreadable:!0,invalid_balance:!0,invalid_observed_at:!0,observed_at_in_future:!0,routes_unreadable:!0},xo={session:!0,memory:!0,"korean-reply-translation":!0};function xc(e,t,n=""){return t?Object.hasOwn(xl,t)?e(`credits.error.${t}`):n||t:n}function xd({face:e,provider:t="hive",title:n,model:s,cost:a,costMinimum:i=!1,detail:l,t:o}){return(0,r.jsxs)("li",{className:"flex min-w-0 items-start gap-2 py-1.5",children:[e?(0,r.jsx)(sD,{seed:e.seed,size:28,provider:t}):(0,r.jsx)("span",{className:"w-7 shrink-0","aria-hidden":"true"}),(0,r.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,r.jsxs)("div",{className:"flex min-w-0 items-baseline gap-1.5",children:[n?(0,r.jsx)("span",{className:"shrink-0 text-[13px] font-medium text-text",children:n}):null,(0,r.jsx)("span",{className:"min-w-0 flex-1 truncate font-mono text-[11px] text-text-dim",children:s}),(0,r.jsx)("span",{className:"shrink-0 font-mono text-xs tabular-nums text-text",children:null===a?o("credits.priceUnknown"):`${i?"≥":""}${g4(a)}`})]}),(0,r.jsx)("div",{className:"mt-0.5 whitespace-pre-line font-mono text-[11px] tabular-nums text-text-muted",children:l})]})]})}function xu({walletName:e,setting:t,onSave:n,onClose:a,t:i}){let l=(0,s.useId)(),[o,c]=(0,s.useState)(t?String(t.totalUsd):""),[d,u]=(0,s.useState)(t?.startDate??""),[h,p]=(0,s.useState)(!1),[m,f]=(0,s.useState)(null),g="min-h-8 w-full min-w-0 bg-bg-hover px-2 font-mono text-xs text-text",x=async e=>{p(!0),f(null);try{await n(e),a()}catch(e){f(i("credits.saveFailed",{reason:xc(i,e instanceof sl?e.code:void 0,e instanceof Error?e.message:String(e))}))}finally{p(!1)}};return(0,r.jsxs)("form",{className:"mt-2 grid gap-2","aria-label":i("credits.formLabel",{wallet:e}),onSubmit:e=>{var t;let n;e.preventDefault();let r=(n=Number((t={totalUsd:o,startDate:d}).totalUsd.replace(/[$,\s]/g,"")),t.totalUsd.trim()&&Number.isFinite(n)?{totalUsd:n,startDate:t.startDate.trim()}:null);r?x(r):f(i("credits.invalid.total"))},children:[(0,r.jsxs)("div",{className:"grid grid-cols-2 gap-2",children:[(0,r.jsxs)("label",{className:"grid gap-1 text-[11px] text-text-muted",htmlFor:`${l}-total`,children:[i("credits.totalUsd"),(0,r.jsx)("input",{id:`${l}-total`,className:g,inputMode:"decimal",value:o,onChange:e=>c(e.target.value),placeholder:"300",required:!0})]}),(0,r.jsxs)("label",{className:"grid gap-1 text-[11px] text-text-muted",htmlFor:`${l}-start`,children:[i("credits.startDate"),(0,r.jsx)("input",{id:`${l}-start`,className:g,type:"date",value:d,onChange:e=>u(e.target.value),required:!0})]})]}),m?(0,r.jsx)("div",{className:"text-xs text-danger",role:"alert",children:m}):null,(0,r.jsxs)("div",{className:"flex flex-wrap justify-end gap-1.5",children:[t?(0,r.jsx)("button",{type:"button",className:g0(gG,"me-auto"),disabled:h,onClick:()=>{x(null)},children:i("credits.clear")}):null,(0,r.jsx)("button",{type:"button",className:gG,disabled:h,onClick:a,children:i("credits.cancel")}),(0,r.jsx)("button",{type:"submit",className:gG,disabled:h,children:h?i("credits.saving"):i("credits.save")})]})]})}function xh({wallet:e,setting:t,balance:n,now:a,onSave:i,onSaveBalance:o,t:c}){let d=(0,s.useId)(),[u,h]=(0,s.useState)(!1),p=c("credits.wallet.hive"),m=function(e){if(null===e.totalUsd||e.totalUsd<=0)return{spentFraction:null,tone:"normal"};let t=e.spentUsd/e.totalUsd;return{spentFraction:Math.max(0,Math.min(1,t)),tone:t>=1?"danger":t>=.9?"warning":"normal"}}(e),f="start-date"===e.sinceSource?c("credits.since",{date:e.since}):c("credits.sinceDefault"),g=e.spentComplete||e.upperBoundRows?g4(e.spentUsd):`≥${g4(e.spentUsd)}`,x=null===e.remainingUsd?null:`${e.remainingUpperBound?"≤":""}${g4(Math.max(0,e.remainingUsd))}`,v=null===m.spentFraction||null===e.remainingUsd?null:Math.round(100*m.spentFraction);return(0,r.jsxs)("section",{className:gZ,"aria-labelledby":d,"data-credit-wallet":e.wallet,children:[(0,r.jsxs)("div",{className:"flex min-w-0 items-center gap-2",children:[(0,r.jsx)("h3",{id:d,className:"m-0 min-w-0 flex-1 text-sm font-semibold text-text",children:p}),u?null:(0,r.jsx)(l.r,{variant:"neutralWeak",size:"xsmall",onClick:()=>h(!0),children:t?c("credits.edit"):c("credits.enter")}),(0,r.jsx)(xf,{wallet:"hive",walletName:p,t:c})]}),n?(0,r.jsx)(xy,{balance:n,walletName:p,now:a,onSave:o,t:c}):null,(0,r.jsx)("div",{className:g0("text-xs text-text-muted",n?"mt-2":"mt-0.5"),children:`${c(`credits.scope.${e.wallet}`)} \xb7 ${f}`}),"error"===e.status?(0,r.jsx)("div",{className:"mt-1.5 text-xs text-text",role:"alert",children:c("credits.walletError",{reason:xc(c,e.error)})}):null,null!==v?(0,r.jsxs)("div",{className:"py-2",children:[(0,r.jsxs)("div",{className:"flex items-baseline justify-between gap-2",children:[(0,r.jsx)("span",{className:"text-[13px] text-text-muted",children:c("credits.remaining")}),(0,r.jsx)("span",{className:g0("font-mono text-sm font-semibold tabular-nums","danger"===m.tone?"text-danger":"text-text"),children:x})]}),(0,r.jsx)("div",{className:"relative mt-1 h-3.5 overflow-hidden bg-metric-track",role:"progressbar","aria-label":c("credits.meterLabel",{wallet:p}),"aria-valuemin":0,"aria-valuemax":100,"aria-valuenow":v,children:(0,r.jsx)("div",{className:g0("absolute inset-y-0 left-0","danger"===m.tone?"bg-danger":"bg-metric"),style:{width:`${v}%`}})}),(0,r.jsx)("div",{className:"mt-1 text-right text-[11px] text-text-muted tabular-nums",children:c("credits.usedPct",{pct:v})})]}):null,(0,r.jsxs)("dl",{className:"m-0 mt-1",children:[null!==e.totalUsd?(0,r.jsx)(xe,{label:c("credits.total"),value:g4(e.totalUsd)}):null,(0,r.jsx)(xe,{label:c("credits.spent"),value:g})]}),t||u?null:(0,r.jsx)("p",{className:"m-0 mt-1.5 text-xs text-text-muted",children:c("credits.enterPrompt")}),u?(0,r.jsx)(xu,{walletName:p,setting:t,onSave:e=>i("hive",e),onClose:()=>h(!1),t:c}):null,e.rows.length>0?(0,r.jsx)("ul",{className:"m-0 mt-1.5 list-none p-0",children:e.rows.map(e=>{let t=se("hive",e.model)??st("hive"),n=e.purposes.map(e=>{let t=Object.hasOwn(xo,e.purpose)?c(`credits.purpose.${e.purpose}`):e.purpose;return`${t} ${null===e.costUsd?c("credits.priceUnknown"):g4(e.costUsd)}`}),s=[c("credits.requests",{count:g5(e.requests)}),c("credits.tokens",{input:g6(e.inputTokens),output:g6(e.outputTokens)}),e.cacheReadTokens>0?c("credits.cacheTokens",{cache:g6(e.cacheReadTokens)}):null].filter(Boolean).join(" \xb7 ");return(0,r.jsx)(xd,{face:t,title:t?.alias??e.model,model:e.model,cost:e.costUsd,detail:n.length>0?`${s}
76
76
  ${n.join(" \xb7 ")}`:s,t:c},e.model)})}):null]})}let xp={input:"inputTokens",output:"outputTokens",cacheRead:"cacheReadTokens",cacheWrite:"cacheWriteTokens"},xm={hive:"https://portal.deploy.com/",exa:"https://dashboard.exa.ai/billing",typesafe:"https://console.typesafe.ai/billing",anthropic:"https://platform.claude.com/settings/billing"};function xf({wallet:e,walletName:t,t:n}){return(0,r.jsxs)("a",{href:xm[e],target:"_blank",rel:"noopener noreferrer",className:g0("inline-flex shrink-0 items-center text-xs text-accent underline-offset-2 hover:underline",gY),"aria-label":n("credits.billingLinkLabel",{wallet:t}),"data-billing-link":e,children:[n("credits.billingLink")," ↗"]})}function xg({wallet:e,balance:t,now:n,onSaveBalance:a,t:i}){let l,o=(0,s.useId)(),c="error"===e.status&&"session_scan_partial"!==e.error,d=null!==e.coverageSince,u=null===e.spentUsd?i("credits.priceUnknown"):`${e.spentComplete?"":"≥"}${g4(e.spentUsd)}`;return(0,r.jsxs)("section",{className:gZ,"aria-labelledby":o,"data-credit-wallet":"anthropic",children:[(0,r.jsxs)("div",{className:"flex min-w-0 items-center gap-2",children:[(0,r.jsx)("h3",{id:o,className:"m-0 min-w-0 flex-1 text-sm font-semibold text-text",children:i("credits.wallet.anthropic")}),(0,r.jsx)(xf,{wallet:"anthropic",walletName:i("credits.wallet.anthropic"),t:i})]}),t?(0,r.jsx)(xy,{balance:t,walletName:i("credits.wallet.anthropic"),now:n,onSave:a,t:i}):null,(0,r.jsx)("div",{className:g0("text-xs text-text-muted",t?"mt-2":"mt-0.5"),children:`${i("credits.scope.anthropic")} \xb7 ${i("credits.sinceDefault")}`}),(0,r.jsx)("p",{className:"m-0 mt-1 text-xs text-text-muted",children:i("credits.anthropic.note")}),"error"===e.status?(0,r.jsx)("div",{className:"mt-1.5 text-xs text-text",role:"alert",children:i("credits.walletError",{reason:xc(i,e.error)})}):null,c?null:(0,r.jsx)("p",{className:"m-0 mt-1.5 text-xs text-text","data-anthropic-coverage":d?"recorded":"none",children:d?i("credits.anthropic.coverageSince",{date:(l=new Date(e.coverageSince),`${l.getFullYear()}-${String(l.getMonth()+1).padStart(2,"0")}-${String(l.getDate()).padStart(2,"0")}`)}):i("credits.anthropic.noCoverage")}),c?null:(0,r.jsxs)("dl",{className:"m-0 mt-1",children:[d?(0,r.jsx)(xe,{label:i("credits.spent"),value:u}):null,(0,r.jsx)(xe,{label:i("credits.anthropic.oauthExcluded"),value:i("credits.requests",{count:g5(e.oauthRequests)})}),e.unattributedRequests>0?(0,r.jsx)(xe,{label:i("credits.anthropic.unattributedExcluded"),value:i("credits.requests",{count:g5(e.unattributedRequests)})}):null]}),d&&!c&&0===e.rows.length?(0,r.jsx)("p",{className:"m-0 mt-1.5 text-xs text-text-muted",children:i("credits.anthropic.none")}):null,e.rows.length>0?(0,r.jsx)("ul",{className:"m-0 mt-1.5 list-none p-0",children:e.rows.map(e=>{let t=t=>{let n=e.costs[t];return`${i(`credits.category.${t}`)} ${g6(e[xp[t]])} ${null===n?i("credits.priceUnknown"):g4(n)}`},n=e.purposes.map(e=>{let t=Object.hasOwn(xo,e.purpose)?i(`credits.purpose.${e.purpose}`):e.purpose,n=null===e.costUsd?i("credits.priceUnknown"):`${e.unpricedRequests>0?"≥":""}${g4(e.costUsd)}`;return`${t} ${n}`}),s=[[i("credits.requests",{count:g5(e.requests)}),t("input"),t("output")].join(" \xb7 "),[t("cacheRead"),t("cacheWrite")].join(" \xb7 "),n.length>0?n.join(" \xb7 "):null].filter(Boolean);return(0,r.jsx)(xd,{face:null,title:"",model:e.model,cost:e.costUsd,costMinimum:e.unpricedRequests>0,detail:s.join("\n"),t:i},e.model)})}):null]})}function xx(e){return rv(e).replace("T"," ")}function xv({walletName:e,recorded:t,onSave:n,onClose:a,t:i}){let l=(0,s.useId)(),[o,c]=(0,s.useState)(t?String(t.amountUsd):""),[d,u]=(0,s.useState)(()=>rv(t?.observedAt??Date.now())),[h,p]=(0,s.useState)(!1),[m,f]=(0,s.useState)({}),g="min-h-8 w-full min-w-0 bg-bg-hover px-2 font-mono text-xs text-text pointer-coarse:min-h-11 max-sm:min-h-11",x={amount:`${l}-amount`,observedAt:`${l}-observed`,hint:`${l}-hint`,amountError:`${l}-amount-error`,observedAtError:`${l}-observed-error`},v=async e=>{p(!0),f({});try{await n(e),a()}catch(r){let e=r instanceof sl?r.code:void 0,t=xc(i,e,r instanceof Error?r.message:String(r)),n="invalid_balance"===e?"amount":"invalid_observed_at"===e||"observed_at_in_future"===e?"observedAt":"form";f({[n]:"form"===n?i("credits.saveFailed",{reason:t}):t})}finally{p(!1)}};return(0,r.jsxs)("form",{className:"mt-2 grid gap-2","aria-label":i("credits.balance.formLabel",{wallet:e}),noValidate:!0,"data-dismissible-layer":!0,onKeyDown:e=>{"Escape"!==e.key||h||(e.preventDefault(),a())},onSubmit:e=>{e.preventDefault();let t=function(e){let t=Number(e.amountUsd.replace(/[$,\s]/g,""));if(!e.amountUsd.trim()||!Number.isFinite(t))return{error:"amount"};let n=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2})?$/.test(e.observedAt.trim())?new Date(e.observedAt.trim()).getTime():NaN;return Number.isFinite(n)?{value:{amountUsd:t,observedAt:n}}:{error:"observedAt"}}({amountUsd:o,observedAt:d});"error"in t?f({[t.error]:i("amount"===t.error?"credits.invalid.amount":"credits.invalid.observedAt")}):v(t.value)},children:[(0,r.jsxs)("div",{className:"grid gap-1",children:[(0,r.jsx)("label",{className:"text-[11px] text-text-muted",htmlFor:x.amount,children:i("credits.balance.amount")}),(0,r.jsx)("input",{id:x.amount,className:g,inputMode:"decimal",autoComplete:"off",value:o,onChange:e=>c(e.target.value),"aria-invalid":!!m.amount||void 0,"aria-describedby":m.amount?x.amountError:void 0,autoFocus:!0,required:!0}),m.amount?(0,r.jsx)("p",{id:x.amountError,className:"m-0 text-xs text-danger",role:"alert",children:m.amount}):null]}),(0,r.jsxs)("div",{className:"grid gap-1",children:[(0,r.jsx)("label",{className:"text-[11px] text-text-muted",htmlFor:x.observedAt,children:i("credits.balance.observedAt")}),(0,r.jsx)("input",{id:x.observedAt,className:g,type:"datetime-local",value:d,onChange:e=>u(e.target.value),"aria-invalid":!!m.observedAt||void 0,"aria-describedby":m.observedAt?x.observedAtError:x.hint,required:!0}),m.observedAt?(0,r.jsx)("p",{id:x.observedAtError,className:"m-0 text-xs text-danger",role:"alert",children:m.observedAt}):(0,r.jsx)("p",{id:x.hint,className:"m-0 text-[11px] text-text-muted",children:i("credits.balance.observedAtHint")})]}),m.form?(0,r.jsx)("div",{className:"text-xs text-danger",role:"alert",children:m.form}):null,(0,r.jsxs)("div",{className:"flex flex-wrap justify-end gap-1.5",children:[t?(0,r.jsx)("button",{type:"button",className:g0(gG,gY,"me-auto"),disabled:h,onClick:()=>{v(null)},children:i("credits.clear")}):null,(0,r.jsx)("button",{type:"button",className:g0(gG,gY),disabled:h,onClick:a,children:i("credits.cancel")}),(0,r.jsx)("button",{type:"submit",className:g0(gG,gY),disabled:h,children:h?i("credits.saving"):i("credits.save")})]})]})}function xy({balance:e,walletName:t,now:n,onSave:a,t:i}){let[o,c]=(0,s.useState)(!1),d=(0,s.useRef)(null),u=e.recorded,h=(0,s.useRef)(!1);(0,s.useLayoutEffect)(()=>{!o&&h.current&&(h.current=!1,d.current?.focus())},[o]);let p="unverified"===e.evidence?i("credits.evidence.unverified"):null!==e.lastPaidUseAt?i("credits.evidence.lastPaidUse",{time:xx(e.lastPaidUseAt)}):null;return(0,r.jsxs)("div",{"data-balance-source":e.source,"data-balance-state":u?"recorded":"unknown",children:[(0,r.jsxs)("p",{className:"m-0 mt-0.5 text-xs text-text-muted","data-balance-evidence":e.evidence,children:[i(`credits.route.${e.wallet}`),p?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("br",{}),p]}):null]}),(0,r.jsxs)("div",{className:"mt-2 flex min-w-0 items-baseline justify-between gap-2",children:[(0,r.jsxs)("span",{className:"min-w-0 text-[13px] text-text-muted",children:[i("credits.balance.label"),(0,r.jsx)("span",{className:"ms-1.5 rounded-[var(--radius-control)] bg-bg-hover px-1 text-[11px]",children:i("credits.balance.source")})]}),u?(0,r.jsx)("span",{className:"shrink-0 font-mono text-sm font-semibold tabular-nums text-text","data-balance-amount":!0,children:`$${u.amountUsd.toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2})}`}):(0,r.jsx)("span",{className:"shrink-0 text-xs text-text-muted",children:i("credits.balance.none")})]}),(0,r.jsxs)("div",{className:"mt-1 flex min-w-0 flex-wrap items-center justify-between gap-x-2 gap-y-1",children:[u?(0,r.jsx)("time",{className:"min-w-0 text-[11px] tabular-nums text-text-muted",dateTime:new Date(u.observedAt).toISOString(),children:`${i("credits.balance.observed",{time:xx(u.observedAt)})} \xb7 ${function(e,t,n){let r=Math.max(0,Math.floor((n-t)/6e4));if(r<1)return e("credits.balance.age.now");if(r<60)return e("credits.balance.age.minutes",{count:r});let s=Math.floor(r/60);return s<48?e("credits.balance.age.hours",{count:s}):e("credits.balance.age.days",{count:Math.floor(s/24)})}(i,u.observedAt,n)}`}):(0,r.jsx)("span",{}),o?null:(0,r.jsx)(l.r,{ref:d,variant:"neutralWeak",size:"xsmall",className:gY,onClick:()=>c(!0),"aria-label":`${t} ${i(u?"credits.balance.edit":"credits.balance.record")}`,children:i(u?"credits.balance.edit":"credits.balance.record")})]}),o?(0,r.jsx)(xv,{walletName:t,recorded:u,onSave:t=>a(e.wallet,t),onClose:()=>{h.current=!0,c(!1)},t:i}):null]})}function xb({balance:e,now:t,onSaveBalance:n,t:a}){let i=(0,s.useId)(),l=a(`credits.wallet.${e.wallet}`);return(0,r.jsxs)("section",{className:gZ,"aria-labelledby":i,"data-credit-wallet":e.wallet,children:[(0,r.jsxs)("div",{className:"flex min-w-0 items-center gap-2",children:[(0,r.jsx)("h3",{id:i,className:"m-0 min-w-0 flex-1 text-sm font-semibold text-text",children:l}),(0,r.jsx)(xf,{wallet:e.wallet,walletName:l,t:a})]}),(0,r.jsx)(xy,{balance:e,walletName:l,now:t,onSave:n,t:a})]})}function xw({state:e,loading:t,now:n,onSave:s,onSaveBalance:a,t:i}){let l=e.data,o=new Map((l?.balances&&!l.balancesError?l.balances:[]).map(e=>[e.wallet,e])),c=e=>{let t=o.get(e);return t?(0,r.jsx)(xb,{balance:t,now:n,onSaveBalance:a,t:i}):null},d=l?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(xh,{wallet:l.hive,setting:l.settings.hive,balance:o.get("hive")??null,now:n,onSave:s,onSaveBalance:a,t:i}),c("exa"),c("typesafe"),l.anthropic?(0,r.jsx)(xg,{wallet:l.anthropic,balance:o.get("anthropic")??null,now:n,onSaveBalance:a,t:i}):null]}):null;return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("h2",{className:"resource-group-heading",children:i("credits.heading")}),(0,r.jsx)("p",{className:g0("m-0",gX,"text-text-muted"),children:i("credits.estimateNote")}),t&&"idle"===e.status?(0,r.jsx)("div",{className:"p-4 text-sm text-text-muted",role:"status",children:i("credits.loading")}):null,"error"===e.status||"stale"===e.status?(0,r.jsx)("div",{className:g0(gX,"bg-[var(--danger-soft)] text-text"),role:"alert",children:i("credits.loadFailed",{reason:e.error.message})}):null,l?.settingsError?(0,r.jsx)("div",{className:g0(gX,"bg-[var(--danger-soft)] text-text"),role:"alert",children:i("credits.settingsError")}):null,l?.balancesError?(0,r.jsx)("div",{className:g0(gX,"bg-[var(--danger-soft)] text-text"),role:"alert",children:xc(i,l.balancesError)}):null,d]})}function xk({refreshToken:e}){let{t}=(0,F.s)(),[n,a]=(0,s.useState)({status:"idle",data:null,error:null}),[i,l]=(0,s.useState)(!1),o=(0,s.useRef)(n),c=(0,s.useRef)(null);o.current=n;let d=(0,s.useCallback)(async e=>{c.current?.abort();let t=new AbortController;c.current=t,l(!0);let n=await sf({refresh:e,previous:o.current.data,signal:t.signal});c.current!==t||t.signal.aborted||(a(n),l(!1))},[]);(0,s.useEffect)(()=>{d(e>0)},[d,e]),(0,s.useEffect)(()=>()=>c.current?.abort(),[]);let u=(0,s.useCallback)(async(e,t)=>{await sg(e,t),await d(!1)},[d]),h=(0,s.useCallback)(async(e,t)=>{await sx(e,t),await d(!1)},[d]),p=nG(6e4);return(0,r.jsx)(xw,{state:n,loading:i,now:p,onSave:u,onSaveBalance:h,t:t})}function xj({model:e}){var t,n;let s=Math.max(1,Math.min(100,100*e.costShare)),a="unpriced"!==e.pricing&&"partial"!==e.pricing,i="unpriced"===e.pricing?g8(0,!1):`${g8(e.cost,a)} \xb7 ${g3(e.costShare)}`;return(0,r.jsxs)("section",{className:gZ,children:[(0,r.jsxs)("div",{className:"flex items-baseline gap-2",children:[(0,r.jsx)("h3",{className:"m-0 min-w-0 flex-1 truncate text-sm font-semibold text-text",title:e.model,children:e.model}),(0,r.jsx)("span",{className:"text-xs text-text-muted",children:e.provider}),(0,r.jsx)("span",{className:"font-mono text-xs tabular-nums text-text",children:i})]}),(0,r.jsx)("div",{className:"my-2 h-1 overflow-hidden bg-metric-track","aria-hidden":"true",children:(0,r.jsx)("div",{className:"h-full bg-metric",style:{width:`${s}%`}})}),(0,r.jsxs)("dl",{className:"m-0 grid grid-cols-2 gap-x-4",children:[(0,r.jsx)(xe,{label:"요청",value:g5(e.requests)}),(0,r.jsx)(xe,{label:"요청당",value:g8(e.costPerRequest,a)}),(0,r.jsx)(xe,{label:"토큰/요청",value:g6(e.tokensPerRequest)}),(0,r.jsx)(xe,{label:"출력/요청",value:g6(e.outputPerRequest)}),(0,r.jsx)(xe,{label:"캐시율",value:(t=e.cacheRate,"not-reported"===(n=e.cacheStatus)?"미보고":"unknown"===n?"알 수 없음":g3(t,1))}),(0,r.jsx)(xe,{label:"TTFT",value:g7(e.avgTtft)})]})]})}function xS({agent:e}){let t={main:"메인",subagent:"SubAgent",advisor:"advisor"}[e.agentType]??e.agentType,n=Math.max(1,Math.min(100,100*e.costShare));return(0,r.jsxs)("section",{className:gZ,children:[(0,r.jsxs)("div",{className:"flex items-baseline justify-between gap-3",children:[(0,r.jsx)("h3",{className:"m-0 text-sm font-semibold text-text",children:t}),(0,r.jsxs)("span",{className:"font-mono text-xs tabular-nums text-text",children:[g8(e.cost,e.costComplete)," \xb7 ",g3(e.costShare)]})]}),(0,r.jsx)("div",{className:"my-2 h-1 overflow-hidden bg-metric-track","aria-hidden":"true",children:(0,r.jsx)("div",{className:"h-full bg-metric",style:{width:`${n}%`}})}),(0,r.jsxs)("dl",{className:"m-0 grid grid-cols-2 gap-x-4",children:[(0,r.jsx)(xe,{label:"요청",value:g5(e.requests)}),(0,r.jsx)(xe,{label:"요청당",value:g8(e.costPerRequest,e.costComplete)}),(0,r.jsx)(xe,{label:"토큰/요청",value:g6(e.tokensPerRequest)})]})]})}function xC({day:e}){let t=e.models.slice(0,3).map(e=>e.model).join(", ");return(0,r.jsxs)("div",{className:"grid grid-cols-[auto_minmax(0,1fr)_auto] items-baseline gap-3 px-3 py-1.5",children:[(0,r.jsx)("span",{className:"font-mono text-xs tabular-nums text-text-muted",children:g9(e.timestamp)}),(0,r.jsx)("span",{className:"truncate text-xs text-text-muted",title:t,children:t}),(0,r.jsx)("span",{className:"font-mono text-xs tabular-nums text-text",children:g8(e.cost,e.costComplete)})]})}function xN({state:e,loading:t}){let n=e.data,s=n?.overall.unpricedModels??0,a=n?.overall.cacheExcludedModels??0;return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(xt,{state:e,loading:t,subject:"모델 집계"}),n?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("section",{"aria-labelledby":"resource-overall-heading",children:[(0,r.jsx)("h2",{id:"resource-overall-heading",className:gQ,children:"전체"}),(0,r.jsxs)("dl",{className:g0("m-0 grid grid-cols-2 gap-x-4",gZ),children:[(0,r.jsx)(xe,{label:"요청",value:g5(n.overall.requests)}),(0,r.jsx)(xe,{label:"추정 비용",value:g8(n.overall.cost,n.overall.costComplete)}),(0,r.jsx)(xe,{label:"토큰",value:g6(n.overall.tokens)}),(0,r.jsx)(xe,{label:a>0?"캐시율(일부)":"캐시율",value:g3(n.overall.cacheRate,1)}),(0,r.jsx)(xe,{label:s>0?"캐시 절감(일부)":"캐시 절감",value:g3(n.overall.cacheSavings,1)}),(0,r.jsx)(xe,{label:"평균 TTFT",value:g7(n.overall.avgTtft)})]})]}),(0,r.jsxs)("section",{"aria-labelledby":"resource-models-heading",children:[(0,r.jsx)("h2",{id:"resource-models-heading",className:gQ,children:"모델별"}),n.models.length?n.models.map(e=>(0,r.jsx)(xj,{model:e},`${e.provider}:${e.model}`)):(0,r.jsx)("div",{className:"p-4 text-sm text-text-muted",children:"모델 기록이 없습니다."})]}),(0,r.jsxs)("section",{"aria-labelledby":"resource-agents-heading",children:[(0,r.jsx)("h2",{id:"resource-agents-heading",className:gQ,children:"에이전트 종류별"}),n.agents.length?n.agents.map(e=>(0,r.jsx)(xS,{agent:e},e.agentType)):(0,r.jsx)("div",{className:"p-4 text-sm text-text-muted",children:"기록이 없습니다."})]}),n.daily.length?(0,r.jsxs)("section",{"aria-labelledby":"resource-daily-heading",children:[(0,r.jsx)("h2",{id:"resource-daily-heading",className:gQ,children:"일별 추정 비용"}),(0,r.jsx)("div",{className:"mx-3 mb-2 rounded-[var(--radius-surface)] bg-bg py-1.5",children:n.daily.map(e=>(0,r.jsx)(xC,{day:e},e.timestamp))})]}):null,(0,r.jsxs)("p",{className:"m-0 px-4 py-3 text-xs leading-5 text-text-dim",children:["`omp stats` 기준 누적값입니다. 금액은 토큰 단가로 계산한 추정치이며 실제 청구액이나 구독 사용량이 아닙니다. 구독 한도 %는 계정 한도 탭에서 확인하세요.",s>0?` 가격을 다 매기지 못한 모델이 ${s}개 있어 추정 비용\xb7비중\xb7캐시 절감은 단가를 아는 사용량만 셉니다. ≥가 붙은 금액은 추정 비용의 최솟값입니다. 에이전트 종류별 집계는 모델을 나누지 않아 모든 행에 ≥를 붙입니다.`:null,a>0?` 캐시 사용량을 보고하지 않거나 보고 여부를 알 수 없는 모델 ${a}개는 캐시율 계산에서 뺐습니다.`:null]})]}):null]})}function xT({reports:e,providerConnections:t}){return sF(),(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("section",{className:"character-roster-intro","aria-labelledby":"character-roster-heading",children:[(0,r.jsx)("h2",{id:"character-roster-heading",children:"호출 가능한 캐릭터"}),(0,r.jsxs)("p",{children:[(0,r.jsx)("strong",{children:"호출\xb7불러\xb7소환"}),"은 캐릭터를 SubAgent로 이 대화에 부릅니다.",(0,r.jsx)("strong",{children:" 교체"}),"는 이 대화의 Main을 바꿉니다."]})]}),(0,r.jsx)("div",{className:"character-roster",role:"list","aria-label":"호출 가능한 캐릭터 목록",children:rV.map(n=>{let s=`character-roster-${n.seed}`,a=`character-roster-${n.seed}-status`,i=`${n.provider}/${n.model}`,l=!1,o=!1;if(e){for(let t of e)if(t.provider===n.provider&&(l=!0,!0!==t.disabled)){o=!0;break}}let c="web6"!==n.provider&&(t?.get(n.provider)===!1||l&&!o);return(0,r.jsxs)("article",{className:g0("character-roster-item",c&&"is-unavailable"),role:"listitem","aria-labelledby":s,"aria-describedby":c?a:void 0,children:[(0,r.jsxs)("div",{className:"character-roster-identity",children:[(0,r.jsx)(sD,{seed:n.seed,size:48,provider:n.provider}),(0,r.jsxs)("div",{children:[(0,r.jsx)("h3",{id:s,children:n.alias}),c?(0,r.jsx)("span",{id:a,className:"character-roster-availability",children:"연결 안 됨"}):null,(0,r.jsx)("p",{children:n.voice})]})]}),(0,r.jsxs)("dl",{className:"character-roster-model",children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("dt",{children:"모델"}),(0,r.jsx)("dd",{title:i,children:i})]}),void 0!==n.oauthPosition?(0,r.jsxs)("div",{children:[(0,r.jsx)("dt",{children:"계정"}),(0,r.jsxs)("dd",{children:["OAuth ",n.oauthPosition]})]}):null]}),(0,r.jsxs)("dl",{className:"character-roster-examples",children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("dt",{children:"호출"}),(0,r.jsxs)("dd",{children:[(0,r.jsx)("code",{children:n.summonExample}),(0,r.jsx)("span",{children:n.summonNote??"SubAgent로 이 대화에 부릅니다."})]})]}),(0,r.jsxs)("div",{children:[(0,r.jsx)("dt",{children:"Main 교체"}),(0,r.jsxs)("dd",{children:[n.switchExample?(0,r.jsx)("code",{children:n.switchExample}):(0,r.jsx)("strong",{children:"교체 불가"}),(0,r.jsx)("span",{children:n.switchNote??"이 대화의 Main을 바꿉니다."})]})]})]})]},n.alias)})})]})}function xI({open:e,sessionId:t,activeTab:n,onTabChange:a,usage:i,className:o}){let{t:c}=(0,F.s)(),d=(0,s.useId)(),u=i.state,h=i.loading,[p,m]=(0,s.useState)({status:"idle",data:null,error:null}),[f,g]=(0,s.useState)(null),[x,v]=(0,s.useState)(!1),[y,b]=(0,s.useState)(null),[w,k]=(0,s.useState)(()=>new Map),[j,S]=(0,s.useState)(()=>new Map),[C,N]=(0,s.useState)(0),T=(0,s.useRef)(p),I=(0,s.useRef)(null),M=(0,s.useRef)(null),E=(0,s.useRef)(new Set),$=(0,s.useRef)(new Set);T.current=p,(0,s.useEffect)(()=>{if(!e||"characters"!==n)return;let t=new AbortController;return b(null),Promise.all([fetch("/api/auth/all-providers",{signal:t.signal}).then(async e=>{if(!e.ok)throw Error(`HTTP ${e.status}`);return e.json()}),fetch("/api/auth/providers",{signal:t.signal}).then(async e=>{if(!e.ok)throw Error(`HTTP ${e.status}`);return e.json()})]).then(([e,n])=>{if(t.signal.aborted)return;let r=new Map(e.providers.map(e=>[e.id,e.configured]));for(let e of n.providers)r.set(e.id,!0===r.get(e.id)||e.loggedIn);b(r)}).catch(()=>{t.signal.aborted||b(null)}),()=>t.abort()},[n,e,u.data]),(0,s.useEffect)(()=>{var r;let s,a,i,l,o,c,d,u,h,p;if(g(null),!e||"usage"!==n||!t)return;let m=(a=(r={onClear(){g(null)},onResult(e){g("fresh"===e.status?e.data:null)}}).intervalMs??2500,i=r.setIntervalImpl??setInterval,l=r.clearIntervalImpl??clearInterval,o=null,c=null,d=0,u=!1,h=()=>{l(s),s=void 0},p=async e=>{c?.abort();let t=c=new AbortController,n=++d,s=await sp(e,{signal:t.signal,fetchImpl:r.fetchImpl});u||n!==d||o!==e||t.signal.aborted||r.onResult(s)},{setSessionId(e){u||e===o||(d+=1,c?.abort(),c=null,h(),o=e,r.onClear(e),e&&(p(e),s=i(()=>{o&&p(o)},a)))},stop(){u||(u=!0,d+=1,c?.abort(),c=null,h(),o=null)}});return I.current=m,m.setSessionId(t),()=>{m.stop(),I.current===m&&(I.current=null)}},[n,e,t]);let R=(0,s.useCallback)(async e=>{M.current?.abort();let t=new AbortController;M.current=t,v(!0);let n=await sm({refresh:e,previous:T.current.data,signal:t.signal});M.current!==t||t.signal.aborted||(m(n),v(!1))},[]);(0,s.useEffect)(()=>{e&&"models"===n&&("idle"===T.current.status||"error"===T.current.status)&&R(!1)},[n,e,R]),(0,s.useEffect)(()=>()=>{for(let e of(M.current?.abort(),E.current))e.abort()},[]);let L=(0,s.useCallback)(()=>{"models"===n?R(!0):(i.refresh(),N(e=>e+1))},[n,R,i]),P=(0,s.useCallback)(()=>i.refresh(),[i]),A=(0,s.useCallback)(async e=>{if(!Number.isSafeInteger(e.credentialId)||e.credentialId<=0)return;let t=e.credentialId,n=sw($.current,t);if(!n)return;let r=new AbortController;E.current.add(r),i.setPaused(!0),k(e=>new Map(e).set(t,"toggle")),S(e=>{let n=new Map(e);return n.delete(t),n});try{await sy(t,!0===e.disabled,{signal:r.signal});let n=await P();r.signal.aborted||S(r=>new Map(r).set(t,{tone:"status",message:"fresh"===n.status?`계정을 ${e.disabled?"켰습니다":"껐습니다"}.`:"계정 설정 저장됨 \xb7 표시 상태 새로고침 실패."}))}catch(e){if(!r.signal.aborted){let n=e instanceof sl&&("timeout"===e.kind||e.outcomeUnknown);S(r=>new Map(r).set(t,n?{tone:"error",message:"적용 여부 확인 필요 — 새로고침으로 계정 상태를 확인하세요."}:{tone:"error",message:`계정 전환 실패: ${e instanceof Error?e.message:String(e)}`}))}}finally{E.current.delete(r),n(),i.setPaused($.current.size>0),k(e=>{let n=new Map(e);return n.delete(t),n})}},[P,i]),_=(0,s.useCallback)(async(e,t)=>{if(!Number.isSafeInteger(e.credentialId)||e.credentialId<=0)return;let n=e.credentialId,r=sw($.current,n);if(!r)return;let s=new AbortController;E.current.add(s),i.setPaused(!0),k(e=>new Map(e).set(n,"reset")),S(e=>{let t=new Map(e);return t.delete(n),t});try{let r=await sb(n,t,{signal:s.signal}),a=function(e,t,n){if("anthropic"===n&&e.consumedCreditIds?.length)return{tone:"error",message:t("resource.reset.mismatch",{requested:e.creditId,consumed:e.consumedCreditIds.join(", ")})};switch(e.code){case"reset":return{tone:"status",message:"리셋 사용함"};case"no_credit":return{tone:"status",message:"사용할 수 있는 리셋이 없습니다."};case"already_redeemed":return{tone:"status",message:"이미 사용된 리셋입니다."};case"nothing_to_reset":return{tone:"status",message:"지금은 초기화할 한도가 없습니다."};case"ineligible":return{tone:"status",message:"지금은 이 리셋을 쓸 수 없습니다(한도 미도달 또는 자격 없음)."};case"cooldown":return{tone:"status",message:"리셋 재사용 대기 중입니다. 잠시 뒤 다시 시도하세요."};case"offer_changed":return{tone:"status",message:"리셋 목록이 바뀌었습니다. 새로고침 후 다시 시도하세요."};case"rate_limited":return{tone:"error",message:"리셋 사용 실패: 요청이 많아 잠시 막혔습니다."};case"reset_unconfirmed":return{tone:"error",message:"이전 리셋 요청 결과를 아직 확인하지 못했습니다. 잠시 뒤 확인하세요."};case"no_account":return{tone:"error",message:"리셋 사용 실패: 계정을 찾을 수 없습니다."};case"account_unavailable":return{tone:"error",message:"리셋 사용 실패: 계정에 연결할 수 없습니다."};case"credit_list_failed":return{tone:"error",message:"리셋 사용 실패: 저장된 리셋 목록을 확인하지 못했습니다."};default:return e.code.startsWith("http_")?{tone:"error",message:"anthropic"===n?t("resource.reset.rejection",{code:e.code,reason:e.reason??""}):`리셋 사용 실패: 서비스 응답 오류 (${e.code})`}:{tone:"error",message:`리셋 사용 실패: ${e.code}`}}}(r,c,e.provider),i=await P();if(r.ok&&!r.consumedCreditIds?.length){let e="fresh"===i.status?i.data.reports.find(e=>e.credentialId===n):void 0,t=e?.savedReset?.availableCount;a.message="number"==typeof t?`리셋 사용함 \xb7 남은 리셋 ${t}개`:"리셋 사용함 \xb7 남은 개수를 확인하지 못했습니다."}s.signal.aborted||S(e=>new Map(e).set(n,a))}catch(e){e instanceof sl&&(e.outcomeUnknown||"timeout"===e.kind)&&!s.signal.aborted&&await P(),s.signal.aborted||S(t=>new Map(t).set(n,function(e){if(e instanceof sl){if(e.outcomeUnknown||"timeout"===e.kind)return{tone:"error",message:"적용 여부 확인 필요 — 자동으로 다시 시도하지 않았습니다. 새로고침으로 남은 개수를 확인하세요."};switch(e.code){case"account_disabled":return{tone:"error",message:"리셋 사용 실패: 꺼둔 계정에서는 사용할 수 없습니다."};case"no_account":return{tone:"error",message:"리셋 사용 실패: 계정을 찾을 수 없습니다."};case"account_unavailable":return{tone:"error",message:"리셋 사용 실패: 계정에 연결할 수 없습니다."};case"rate_limited":return{tone:"error",message:"리셋 사용 실패: 리셋 목록 조회가 요청 한도에 걸렸습니다. 1분쯤 뒤 다시 시도하세요. 리셋은 쓰지 않았습니다."};case"credit_list_failed":return{tone:"error",message:"리셋 사용 실패: 저장된 리셋 목록을 확인하지 못했습니다."};default:return{tone:"error",message:`리셋 사용 실패: ${e.message}`}}}return{tone:"error",message:`리셋 사용 실패: ${e instanceof Error?e.message:String(e)}`}}(e)))}finally{E.current.delete(s),r(),i.setPaused($.current.size>0),k(e=>{let t=new Map(e);return t.delete(n),t})}},[P,i,c]);if(!e)return null;let O="models"===n?p.data?.generatedAt:u.data?.generatedAt,z="models"===n?p.data?.range:void 0,D=z?.from&&z.to?`${g9(z.from)}~${g9(z.to)}`:O?new Date(O).toLocaleTimeString():"",W="models"===n?x:"usage"===n&&h,H=W?"models"===n?"집계 중…":"불러오는 중…":"새로고침";return(0,r.jsxs)("section",{className:g0("resource-panel flex min-h-0 w-full flex-col overflow-hidden bg-bg-panel text-text",o),"aria-labelledby":d,"aria-busy":W,children:[(0,r.jsx)("h1",{id:d,className:"sr-only",children:"캐릭터"}),(0,r.jsxs)(f5.J.Root,{className:"resource-view-tabs",size:"small",contentLayout:"fill",triggerLayout:"fill",value:n,onValueChange:e=>a(e),children:[(0,r.jsxs)(f5.J.List,{"aria-label":"캐릭터와 사용량 보기",children:[(0,r.jsx)(f5.J.Trigger,{value:"characters",children:"캐릭터"}),(0,r.jsx)(f5.J.Trigger,{value:"usage",children:"계정 한도"}),(0,r.jsx)(f5.J.Trigger,{value:"models",children:"모델 통계"}),(0,r.jsx)(f5.J.Indicator,{})]}),(0,r.jsx)(f5.J.Content,{value:"characters",className:"resource-view-content",children:(0,r.jsx)(xT,{reports:u.data?.reports,providerConnections:y})}),(0,r.jsxs)(f5.J.Content,{value:"usage",className:"resource-view-content",children:[(0,r.jsxs)("div",{className:"resource-usage-toolbar",children:[(0,r.jsx)("span",{className:"min-w-0 flex-1 truncate font-mono text-[11px] tabular-nums text-text-dim",children:D}),(0,r.jsx)(l.r,{variant:"neutralWeak",size:"xsmall",onClick:L,disabled:W,children:H})]}),(0,r.jsx)("h2",{className:"resource-group-heading",children:"계정 한도"}),(0,r.jsx)(xi,{state:u,loading:h,accountState:f?.sessionId===t?f:null,pendingActions:w,feedbackByCredential:j,onToggle:e=>{A(e)},onReset:_,t:c}),(0,r.jsx)(xk,{refreshToken:C})]}),(0,r.jsxs)(f5.J.Content,{value:"models",className:"resource-view-content",children:[(0,r.jsxs)("div",{className:"resource-usage-toolbar",children:[(0,r.jsx)("span",{className:"min-w-0 flex-1 truncate font-mono text-[11px] tabular-nums text-text-dim",children:D}),(0,r.jsx)(l.r,{variant:"neutralWeak",size:"xsmall",onClick:L,disabled:W,children:H})]}),(0,r.jsx)(xN,{state:p,loading:x})]})]})]})}var xM=n(68890);let xE="unknown",x$="/api/runs";class xR extends Error{constructor(e,t,n=null){super(t),this.name="EfficiencyClientError",this.kind=e,this.status=n}}let xL=["completed","error","aborted","interrupted","running"],xP=["main","maker","checker","advisor","unattributed"],xA=["primary","rework","review"],x_=["wait-attribution","unpriced-cost","effort-unrecorded","role-unattributed","busy-unrecorded"],xF=["all","attributed"],xO=["single","unknown"],xz=["config","harness"];function xD(e){return"object"==typeof e&&null!==e}function xW(e){return Array.isArray(e)&&e.every(e=>"string"==typeof e)}function xH(e){return!!xD(e)&&"string"==typeof e.runId&&"string"==typeof e.sessionId&&"string"==typeof e.entryId&&"number"==typeof e.index&&Number.isFinite(e.index)&&(null===e.title||"string"==typeof e.title)&&"number"==typeof e.startedAt&&Number.isFinite(e.startedAt)&&(null===e.endedAt||"number"==typeof e.endedAt&&Number.isFinite(e.endedAt))&&"number"==typeof e.wallClockMs&&Number.isFinite(e.wallClockMs)&&"string"==typeof e.outcome&&xL.includes(e.outcome)&&"number"==typeof e.busyMs&&Number.isFinite(e.busyMs)&&"number"==typeof e.childCount&&Number.isFinite(e.childCount)&&"number"==typeof e.totalTokens&&Number.isFinite(e.totalTokens)&&"number"==typeof e.estimatedCostUsd&&Number.isFinite(e.estimatedCostUsd)&&"number"==typeof e.unpricedRequests&&Number.isFinite(e.unpricedRequests)&&"string"==typeof e.configSignature&&(null===e.harnessRevision||"string"==typeof e.harnessRevision)}function xU(e){return!!xD(e)&&"string"==typeof e.id&&"string"==typeof e.kind&&xP.includes(e.kind)&&(null===e.purpose||"string"==typeof e.purpose&&xA.includes(e.purpose))&&xW(e.models)&&xW(e.efforts)&&"number"==typeof e.requestCount&&Number.isFinite(e.requestCount)&&"number"==typeof e.busyMs&&Number.isFinite(e.busyMs)&&"number"==typeof e.spanMs&&Number.isFinite(e.spanMs)&&"number"==typeof e.startedAt&&Number.isFinite(e.startedAt)&&"number"==typeof e.endedAt&&Number.isFinite(e.endedAt)&&"number"==typeof e.inputTokens&&Number.isFinite(e.inputTokens)&&"number"==typeof e.outputTokens&&Number.isFinite(e.outputTokens)&&"number"==typeof e.cacheReadTokens&&Number.isFinite(e.cacheReadTokens)&&"number"==typeof e.cacheWriteTokens&&Number.isFinite(e.cacheWriteTokens)&&"number"==typeof e.totalTokens&&Number.isFinite(e.totalTokens)&&"number"==typeof e.estimatedCostUsd&&Number.isFinite(e.estimatedCostUsd)&&"number"==typeof e.unpricedRequests&&Number.isFinite(e.unpricedRequests)&&"number"==typeof e.untimedRequests&&Number.isFinite(e.untimedRequests)&&"number"==typeof e.errorCount&&Number.isFinite(e.errorCount)&&"number"==typeof e.abortedCount&&Number.isFinite(e.abortedCount)&&"number"==typeof e.toolCalls&&Number.isFinite(e.toolCalls)}function xB(e){return!!xD(e)&&("role-busy"===e.kind||"unmeasured-gap"===e.kind)&&"string"==typeof e.id&&"number"==typeof e.ms&&Number.isFinite(e.ms)&&"number"==typeof e.relative&&Number.isFinite(e.relative)}function xq(e){return!!xD(e)&&"string"==typeof e.toolName&&"number"==typeof e.calls&&Number.isFinite(e.calls)&&"number"==typeof e.failed&&Number.isFinite(e.failed)&&"number"==typeof e.noMatch&&Number.isFinite(e.noMatch)&&"number"==typeof e.cancelled&&Number.isFinite(e.cancelled)}function xV(e){return!!xD(e)&&"string"==typeof e.kind&&xP.includes(e.kind)&&"string"==typeof e.model&&(null===e.effort||"string"==typeof e.effort)&&"number"==typeof e.count&&Number.isFinite(e.count)&&xW(e.models)&&xW(e.efforts)&&xO.includes(e.pairing)}function xK(e){return!!xD(e)&&(null===e.revision||"string"==typeof e.revision)&&"number"==typeof e.runCount&&Number.isFinite(e.runCount)}function xJ(e){return!!xD(e)&&"string"==typeof e.signature&&Array.isArray(e.roles)&&e.roles.every(xV)&&"number"==typeof e.runCount&&Number.isFinite(e.runCount)&&"number"==typeof e.medianWallClockMs&&Number.isFinite(e.medianWallClockMs)&&"number"==typeof e.medianBusyMs&&Number.isFinite(e.medianBusyMs)&&"number"==typeof e.medianTotalTokens&&Number.isFinite(e.medianTotalTokens)&&"number"==typeof e.medianEstimatedCostUsd&&Number.isFinite(e.medianEstimatedCostUsd)&&"number"==typeof e.totalEstimatedCostUsd&&Number.isFinite(e.totalEstimatedCostUsd)&&"number"==typeof e.unpricedRuns&&Number.isFinite(e.unpricedRuns)&&"number"==typeof e.untimedRuns&&Number.isFinite(e.untimedRuns)&&"number"==typeof e.reworkRuns&&Number.isFinite(e.reworkRuns)&&"number"==typeof e.errorRuns&&Number.isFinite(e.errorRuns)&&"number"==typeof e.childRunsAvg&&Number.isFinite(e.childRunsAvg)&&"number"==typeof e.firstSeenAt&&Number.isFinite(e.firstSeenAt)&&"number"==typeof e.lastSeenAt&&Number.isFinite(e.lastSeenAt)&&Array.isArray(e.harnesses)&&e.harnesses.every(xK)}function xG(e){return Array.isArray(e)&&e.every(e=>"string"==typeof e&&x_.includes(e))}async function xY(e){try{return await e.json()}catch{throw new xR("invalid-response","효율 응답 JSON을 해석할 수 없습니다.",e.status)}}let xZ={groupBy:"config",harness:null};function xQ(e,t){return e instanceof xR||e instanceof Error?e.message:t}function xX(e){return"number"==typeof e&&Number.isFinite(e)?Math.round(e).toLocaleString("en-US"):"—"}function x0(e){return"number"==typeof e&&Number.isFinite(e)?e>=1e9?`${(e/1e9).toFixed(1)}B`:e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${Math.round(e/1e3)}K`:String(Math.round(e)):"—"}function x1(e){if("number"!=typeof e||!Number.isFinite(e))return"—";let t=Math.max(0,e);if(t<1e3)return`${Math.round(t)}ms`;let n=Math.round(t/1e3);if(n<60)return`${(t/1e3).toFixed(1)}s`;let r=Math.floor(n/60),s=n-60*r;return r<60?0===s?`${r}m`:`${r}m ${s}s`:`${Math.floor(r/60)}h ${r%60}m`}let x2={injection:"efficiency.sawKindInjection",developer:"efficiency.sawKindDeveloper",user:"efficiency.sawKindUser",compaction:"efficiency.sawKindCompaction",model:"efficiency.sawKindModel",effort:"efficiency.sawKindEffort",prompt:"efficiency.sawKindPrompt",rules:"efficiency.sawKindRules",memory:"efficiency.sawKindMemory"},x4={ok:"efficiency.sawToolOk",failed:"efficiency.sawToolFailed",noMatch:"efficiency.sawToolNoMatch",cancelled:"efficiency.sawToolCancelled",missing:"efficiency.sawToolMissing"},x8={failed:"critical",noMatch:"neutral",cancelled:"neutral",missing:"warning"};async function x5(e,t){let n,r=await fetch(e,{method:"GET",signal:t});try{n=await r.json()}catch{throw Error(`HTTP ${r.status}: invalid JSON`)}if(!r.ok)throw Error(n&&"object"==typeof n&&"error"in n&&"string"==typeof n.error?n.error:`HTTP ${r.status}`);if(null===n)throw Error(`HTTP ${r.status}: empty body`);return n}function x6(e,t,n){return`${x$}/${encodeURIComponent(e)}/${t}?${new URLSearchParams(n).toString()}`}function x3(e){return e>0?new Date(e).toLocaleTimeString(void 0,{hour12:!1}):"—"}function x7({runId:e,role:t,entryId:n,call:a,label:i,t:l}){let[o,c]=(0,s.useState)(!1),[d,u]=(0,s.useState)({status:"idle",value:null,error:null});return(0,r.jsxs)("div",{className:"run-saw-full-wrap",children:[(0,r.jsx)("button",{type:"button",className:"run-saw-link","aria-expanded":o,onClick:()=>{let r=!o;if(c(r),!r||"ready"===d.status||"loading"===d.status)return;u({status:"loading",value:null,error:null});let s={role:t,entry:n};a&&(s.call=a),x5(x6(e,"turns",s)).then(e=>u({status:"ready",value:e,error:null})).catch(e=>u({status:"error",value:null,error:e instanceof Error?e.message:String(e)}))},children:o?l("efficiency.sawHideFull"):i}),o?"ready"===d.status&&d.value?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("pre",{className:"run-saw-full",children:d.value.text}),d.value.truncated?(0,r.jsx)("p",{className:"run-saw-dim",children:l("efficiency.sawTruncated",{value:xX(d.value.text.length)})}):null]}):"error"===d.status?(0,r.jsx)("p",{className:"run-saw-dim",role:"alert",children:d.error}):(0,r.jsx)("p",{className:"run-saw-dim",role:"status",children:l("efficiency.sawLoading")}):null]})}function x9({event:e,runId:t,role:n,t:s}){let a=e.preview;if("compaction"===e.kind&&(null!=e.tokensBefore||null!=e.tokensAfter)){let t=s("efficiency.sawCompactionValue",{before:x0(e.tokensBefore??null),after:x0(e.tokensAfter??null)});a=a?`${t} \xb7 ${a}`:t}else void 0!==e.memoryIds&&(a=s("efficiency.sawMemoryIds",{value:e.memoryIds}));return(0,r.jsxs)("li",{className:"run-saw-event",children:[(0,r.jsxs)("div",{className:"run-saw-event-head",children:[(0,r.jsx)("span",{className:"run-saw-kind",children:s(x2[e.kind])}),(0,r.jsx)("span",{className:"run-saw-source",children:e.source}),(0,r.jsx)("span",{className:"run-saw-dim",children:x3(e.at)}),e.hiddenFromChat?(0,r.jsx)("span",{className:"run-saw-dim",children:s("efficiency.sawHiddenFromChat")}):null,e.sentToModel?null:(0,r.jsx)("span",{className:"run-saw-dim",children:s("efficiency.sawNotSent")})]}),a?(0,r.jsx)("p",{className:"run-saw-preview",children:a}):null,e.chars>e.preview.length?(0,r.jsx)(x7,{runId:t,role:n,entryId:e.entryId,call:null,label:s("efficiency.sawShowFull"),t:s}):null]})}function ve({call:e,runId:t,role:n,turnEntryId:s,t:a}){return(0,r.jsxs)("li",{className:"run-saw-tool",children:[(0,r.jsxs)("div",{className:"run-saw-tool-head",children:[(0,r.jsx)("span",{className:"run-saw-tool-name",children:e.name}),(0,r.jsx)("span",{className:"run-saw-num",children:x1(e.durationMs)}),null!==e.resultChars?(0,r.jsx)("span",{className:"run-saw-dim",children:a("efficiency.sawResultChars",{value:xX(e.resultChars)})}):null,"ok"!==e.status?(0,r.jsx)(n2.E,{tone:x8[e.status],variant:"weak",size:"medium",children:a(x4[e.status])}):null]}),(0,r.jsx)("code",{className:"run-saw-args",children:e.argsPreview}),(0,r.jsxs)("div",{className:"run-saw-tool-actions",children:[e.argsChars>e.argsPreview.length?(0,r.jsx)(x7,{runId:t,role:n,entryId:s,call:e.toolCallId,label:a("efficiency.sawShowArgs"),t:a}):null,e.resultEntryId?(0,r.jsx)(x7,{runId:t,role:n,entryId:e.resultEntryId,call:null,label:a("efficiency.sawShowResult"),t:a}):null]})]})}function vt({turn:e,runId:t,role:n,t:s}){let a=[e.model,x1(e.durationMs),e.usage?s("efficiency.sawUsage",{input:x0(e.usage.input),output:x0(e.usage.output),cacheRead:x0(e.usage.cacheRead)}):null,e.stopReason?s("efficiency.sawStop",{value:e.stopReason}):null].filter(Boolean).join(" \xb7 ");return(0,r.jsxs)("li",{className:"run-saw-turn",children:[(0,r.jsxs)("div",{className:"run-saw-turn-head",children:[(0,r.jsx)("span",{className:"run-saw-turn-label",children:s("efficiency.sawTurnLabel",{index:e.index})}),(0,r.jsx)("span",{className:"run-saw-dim",children:x3(e.at)})]}),(0,r.jsx)("p",{className:"run-saw-turn-meta",children:a}),e.toolsAdded.length>0||e.toolsRemoved.length>0?(0,r.jsx)("p",{className:"run-saw-dim",title:[...e.toolsAdded.map(e=>`+${e}`),...e.toolsRemoved.map(e=>`−${e}`)].join(" "),children:s("efficiency.sawToolsChanged",{added:e.toolsAdded.join(", ")||"0",removed:e.toolsRemoved.join(", ")||"0"})}):null,e.before.length>0?(0,r.jsxs)("div",{className:"run-saw-group",children:[(0,r.jsx)("p",{className:"run-saw-group-label",children:s("efficiency.sawBefore")}),(0,r.jsx)("ul",{className:"run-saw-events",children:e.before.map(e=>(0,r.jsx)(x9,{event:e,runId:t,role:n,t:s},e.entryId))})]}):null,e.toolCalls.length>0?(0,r.jsx)("ul",{className:"run-saw-tools",children:e.toolCalls.map(a=>(0,r.jsx)(ve,{call:a,runId:t,role:n,turnEntryId:e.entryId,t:s},a.toolCallId))}):null]})}function vn({runId:e,role:t,t:n}){let[a,i]=(0,s.useState)(null),[o,c]=(0,s.useState)(null),[d,u]=(0,s.useState)(!1);(0,s.useEffect)(()=>{let n=new AbortController;return i(null),c(null),x5(x6(e,"prelude",{role:t}),n.signal).then(i).catch(e=>{n.signal.aborted||c(e instanceof Error?e.message:String(e))}),()=>n.abort()},[e,t]);let h=a?.recorded.digests.at(-1)??null,p=a?.rebuilt;return(0,r.jsxs)("section",{className:"run-saw-prelude","aria-label":n("efficiency.sawPreludeTitle"),children:[(0,r.jsx)("h4",{className:"run-saw-subtitle",children:n("efficiency.sawPreludeTitle")}),o?(0,r.jsx)("p",{className:"run-saw-dim",role:"alert",children:o}):null,a||o?null:(0,r.jsx)("p",{className:"run-saw-dim",role:"status",children:n("efficiency.sawLoading")}),a?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("p",{className:"run-saw-group-label",children:n("efficiency.sawPreludeRecorded")}),(0,r.jsx)("p",{className:"run-saw-line",children:h?n("efficiency.sawPreludeDigest",{value:h.digest}):n("efficiency.sawPreludeDigestNone")}),a.recorded.activeTools?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("p",{className:"run-saw-line",children:n("efficiency.sawPreludeTools",{value:a.recorded.activeTools.length})}),(0,r.jsx)("p",{className:"run-saw-names",children:a.recorded.activeTools.join(" \xb7 ")})]}):null,a.recorded.memoryRecall?(0,r.jsxs)("div",{className:"run-saw-group",children:[(0,r.jsx)("p",{className:"run-saw-line",children:n("efficiency.sawPreludeMemory")}),(0,r.jsx)("p",{className:"run-saw-preview",children:a.recorded.memoryRecall.preview}),a.recorded.memoryRecall.chars>a.recorded.memoryRecall.preview.length?(0,r.jsx)(x7,{runId:e,role:t,entryId:a.recorded.memoryRecall.entryId,call:null,label:n("efficiency.sawShowFull"),t:n}):null]}):null,p?.status==="not-loaded"?(0,r.jsx)("p",{className:"run-saw-approx",children:n("efficiency.sawPreludeNotLoaded")}):p?.status==="available"?(0,r.jsx)("div",{className:"run-saw-actions",children:(0,r.jsx)(l.r,{variant:"neutralWeak",size:"xsmall",onClick:()=>{u(!0),x5(x6(e,"prelude",{role:t,rebuild:"1"})).then(i).catch(e=>c(e instanceof Error?e.message:String(e))).finally(()=>u(!1))},disabled:d,children:n(d?"efficiency.sawPreludeLoading":"efficiency.sawPreludeReconstruct")})}):p?.status==="rebuilt"?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("p",{className:"run-saw-approx",children:n("efficiency.sawPreludeApprox")}),null!==p.matchesRecorded?(0,r.jsx)("p",{className:"run-saw-line",children:n(p.matchesRecorded?"efficiency.sawPreludeMatch":"efficiency.sawPreludeMismatch")}):null,(0,r.jsx)("pre",{className:"run-saw-full",children:p.text}),p.truncated?(0,r.jsx)("p",{className:"run-saw-dim",children:n("efficiency.sawTruncated",{value:xX(p.text.length)})}):null]}):null]}):null]})}let vr={status:"idle",page:null,turns:[],loadingMore:!1,error:null};function vs({runId:e,t}){let[n,a]=(0,s.useState)(!1),[i,o]=(0,s.useState)("main"),[c,d]=(0,s.useState)(!1),[u,h]=(0,s.useState)(vr),p=(0,s.useRef)(null),m=(0,s.useCallback)(t=>{p.current?.abort();let n=new AbortController;p.current=n,h(e=>0===t?{...vr,status:"loading"}:{...e,loadingMore:!0});let r={role:i,offset:String(t),limit:String(30)};c&&(r.injectedOnly="1"),x5(x6(e,"turns",r),n.signal).then(e=>h(n=>({status:"ready",page:e,turns:0===t?e.turns:[...n.turns,...e.turns],loadingMore:!1,error:null}))).catch(e=>{n.signal.aborted||h(n=>({...n,status:0===t?"error":n.status,loadingMore:!1,error:e instanceof Error?e.message:String(e)}))})},[e,i,c]);(0,s.useEffect)(()=>{n&&m(0)},[n,m]),(0,s.useEffect)(()=>()=>p.current?.abort(),[]);let f=u.page,g=f?f.total-u.turns.length:0,x=f?Object.entries(f.counts.bySource).sort((e,t)=>t[1]-e[1]||e[0].localeCompare(t[0])):[];return(0,r.jsxs)("section",{className:"run-saw","aria-label":t("efficiency.sawSection"),children:[(0,r.jsx)("h3",{className:"efficiency-section-title",children:t("efficiency.sawSection")}),(0,r.jsx)("p",{className:"run-saw-approx",children:t("efficiency.sawApproxNote")}),n?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("div",{className:"run-saw-controls",children:[f&&f.roles.length>1?(0,r.jsxs)("label",{className:"run-saw-role",children:[(0,r.jsx)("span",{children:t("efficiency.sawRole")}),(0,r.jsx)("select",{className:"efficiency-folder-select",value:i,onChange:e=>o(e.target.value),children:f.roles.map(e=>(0,r.jsx)("option",{value:e,children:e},e))})]}):null,(0,r.jsx)(xM.f,{variant:"neutralWeak",size:"xsmall",pressed:c,onPressedChange:d,children:t("efficiency.sawOnlyInjected")})]}),"loading"===u.status||"idle"===u.status?(0,r.jsx)("p",{className:"efficiency-empty",role:"status",children:t("efficiency.sawLoading")}):"error"===u.status?(0,r.jsxs)("div",{className:"efficiency-empty",role:"alert",children:[(0,r.jsx)("div",{children:t("efficiency.sawError")}),(0,r.jsx)("div",{className:"run-saw-dim",children:u.error})]}):f?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("p",{className:"run-saw-summary",children:t("efficiency.sawSummary",{turns:f.counts.turns,injections:f.counts.injections,tools:f.counts.toolCalls,failed:f.counts.toolFailures})}),x.length>0?(0,r.jsx)("p",{className:"run-saw-names",children:x.map(([e,t])=>`${e} ${t}`).join(" \xb7 ")}):null,(0,r.jsx)("p",{className:"run-saw-dim run-saw-pad",children:t("efficiency.sawSecretsMasked")}),0===u.turns.length?(0,r.jsx)("p",{className:"efficiency-empty",children:t(c?"efficiency.sawFilterEmpty":"efficiency.sawEmpty")}):(0,r.jsx)("ol",{className:"run-saw-turns",children:u.turns.map(n=>(0,r.jsx)(vt,{turn:n,runId:e,role:f.role,t:t},n.entryId))}),f.trailing.length>0&&g<=0?(0,r.jsxs)("div",{className:"run-saw-group run-saw-trailing",children:[(0,r.jsx)("p",{className:"run-saw-group-label",children:t("efficiency.sawTrailing")}),(0,r.jsx)("ul",{className:"run-saw-events",children:f.trailing.map(n=>(0,r.jsx)(x9,{event:n,runId:e,role:f.role,t:t},n.entryId))})]}):null,(0,r.jsxs)("div",{className:"run-saw-actions",children:[(0,r.jsx)("span",{className:"run-saw-dim",children:t("efficiency.sawShown",{shown:u.turns.length,total:f.total})}),g>0?(0,r.jsx)(l.r,{variant:"neutralWeak",size:"xsmall",onClick:()=>m(u.turns.length),disabled:u.loadingMore,children:u.loadingMore?t("efficiency.sawLoading"):t("efficiency.sawMore",{value:Math.min(g,30)})}):null]}),u.error?(0,r.jsx)("p",{className:"run-saw-dim run-saw-pad",role:"alert",children:u.error}):null,(0,r.jsx)(vn,{runId:e,role:f.role,t:t})]}):null]}):(0,r.jsx)("div",{className:"run-saw-actions",children:(0,r.jsx)(l.r,{variant:"neutralWeak",size:"xsmall",onClick:()=>a(!0),children:t("efficiency.sawOpen")})})]})}let va={completed:"positive",error:"critical",aborted:"warning",interrupted:"warning",running:"informative"},vi={main:"informative",maker:"neutral",checker:"neutral",advisor:"neutral",unattributed:"warning"};function vl(...e){return e.filter(Boolean).join(" ")}function vo(e){return"number"==typeof e&&Number.isFinite(e)?0===e?"$0":e>=100?`$${e.toFixed(0)}`:e>=1?`$${e.toFixed(2)}`:e>=.01?`$${e.toFixed(3)}`:`$${e.toFixed(4)}`:"—"}function vc(e,t=0){return"number"==typeof e&&Number.isFinite(e)?`${(100*e).toFixed(t)}%`:"—"}function vd(e,t){return null===e?t("efficiency.harnessUnknown"):e.slice(0,7)}function vu({label:e,value:t}){return(0,r.jsxs)("div",{className:"flex min-w-0 items-baseline justify-between gap-3 py-1.5",children:[(0,r.jsx)("dt",{className:"min-w-0 flex-1 text-xs text-text-muted [overflow-wrap:anywhere]",children:e}),(0,r.jsx)("dd",{className:"m-0 flex-none text-right font-mono text-xs tabular-nums text-text",children:t})]})}function vh({share:e,label:t}){let n=Number.isFinite(e)?Math.max(1,Math.min(100,100*e)):1;return(0,r.jsxs)("div",{className:"efficiency-bar","aria-hidden":"true",children:[(0,r.jsx)("div",{className:"efficiency-bar-fill",style:{width:`${n}%`}}),(0,r.jsx)("span",{className:"efficiency-bar-value",children:t})]})}function vp({costUsd:e,unpriced:t,t:n}){return(0,r.jsxs)("span",{className:"font-mono tabular-nums",children:[n("efficiency.estimatedCostValue").replace("{value}",vo(e)),t>0?` \xb7 ${n("efficiency.unpricedLowerBound")}`:""]})}function vm({outcome:e,t}){return(0,r.jsx)(n2.E,{tone:va[e],variant:"weak",size:"medium",children:t({completed:"efficiency.outcomeCompleted",error:"efficiency.outcomeError",aborted:"efficiency.outcomeAborted",interrupted:"efficiency.outcomeInterrupted",running:"efficiency.outcomeRunning"}[e])})}function vf({purpose:e,t}){return null===e?(0,r.jsx)("span",{className:"efficiency-dim",children:t("efficiency.unmeasuredShort")}):(0,r.jsx)(n2.E,{tone:"rework"===e?"warning":"neutral",variant:"weak",size:"medium",children:t({primary:"efficiency.purposePrimary",rework:"efficiency.purposeRework",review:"efficiency.purposeReview"}[e]??"efficiency.unmeasuredShort")})}function vg({run:e,selected:t,onSelect:n,t:s}){let a=e.title&&e.title.trim().length>0?e.title:s("efficiency.noTitle");return(0,r.jsx)("li",{children:(0,r.jsxs)("button",{type:"button",onClick:n,"aria-current":t?"true":void 0,className:vl("efficiency-run-item",t&&"is-selected"),children:[(0,r.jsxs)("span",{className:"efficiency-run-top",children:[(0,r.jsxs)("span",{className:"efficiency-run-index",children:["#",e.index]}),(0,r.jsx)("span",{className:"efficiency-run-title",title:a,children:a}),(0,r.jsx)(vm,{outcome:e.outcome,t:s})]}),(0,r.jsxs)("span",{className:"efficiency-run-meta",children:[(0,r.jsx)("span",{className:"font-mono tabular-nums",children:s("efficiency.elapsedValue").replace("{value}",x1(e.wallClockMs))}),(0,r.jsx)(vp,{costUsd:e.estimatedCostUsd,unpriced:e.unpricedRequests,t:s}),(0,r.jsx)("span",{className:"font-mono tabular-nums",title:e.harnessRevision??s("efficiency.harnessUnknown"),children:s("efficiency.harnessValue").replace("{value}",vd(e.harnessRevision,s))})]})]})})}function vx({role:e,t}){let n=e.models.length>0?e.models.join(", "):t("efficiency.unmeasuredShort"),s=e.efforts.length>0?e.efforts.join(", "):t("efficiency.unmeasuredShort"),a=e.outputTokens-e.helpers.reduce((e,t)=>e+t.outputTokens,0),i=t(`efficiency.role${"main"===e.kind?"Main":"maker"===e.kind?"Maker":"checker"===e.kind?"Checker":"advisor"===e.kind?"Advisor":"Unattributed"}`);return(0,r.jsxs)("details",{className:"efficiency-role",children:[(0,r.jsxs)("summary",{className:"efficiency-role-summary",children:[(0,r.jsxs)("span",{className:"efficiency-role-head",children:[(0,r.jsx)("span",{className:"efficiency-role-id",children:e.id}),(0,r.jsx)(n2.E,{tone:vi[e.kind]??"neutral",variant:"weak",size:"medium",children:i}),(0,r.jsx)(vf,{purpose:e.purpose,t:t})]}),(0,r.jsx)("span",{className:"efficiency-model-line",title:n,children:n}),(0,r.jsxs)("span",{className:"efficiency-role-stats",children:[(0,r.jsxs)("span",{children:[t("efficiency.busyTime")," ",(0,r.jsx)("span",{className:"efficiency-role-stat-value",children:x1(e.busyMs)})]}),(0,r.jsxs)("span",{children:[t("efficiency.estimatedCost")," ",(0,r.jsx)("span",{className:"efficiency-role-stat-value",children:vo(e.estimatedCostUsd)})]}),(0,r.jsxs)("span",{children:[t("efficiency.tokens")," ",(0,r.jsx)("span",{className:"efficiency-role-stat-value",children:x0(e.totalTokens)})]})]})]}),(0,r.jsxs)("div",{className:"efficiency-role-body",children:[(0,r.jsxs)("p",{className:"efficiency-dim",children:[t("efficiency.effortLabel").replace("{value}",s),` \xb7 ${t("efficiency.requestsValue").replace("{value}",String(e.requestCount))}`,` \xb7 ${t("efficiency.toolCallsValue").replace("{value}",String(e.toolCalls))}`]}),(0,r.jsxs)("dl",{className:"efficiency-metrics",children:[(0,r.jsx)(vu,{label:t("efficiency.unpricedRequests"),value:xX(e.unpricedRequests)}),(0,r.jsx)(vu,{label:t("efficiency.firstTokenAvg"),value:null!==e.ttftMs&&e.ttftRequests>0?x1(e.ttftMs/e.ttftRequests):t("efficiency.unmeasuredShort")}),(0,r.jsx)(vu,{label:t("efficiency.outputTokens"),value:x0(a)})]}),e.ttftRequests>0&&e.ttftRequests<e.requestCount?(0,r.jsx)("p",{className:"efficiency-role-note",children:t("efficiency.firstTokenPartial",{recorded:e.ttftRequests,total:e.requestCount})}):null,e.untimedRequests>0?(0,r.jsx)("p",{className:"efficiency-role-note",children:t("efficiency.untimedLowerBound").replace("{value}",xX(e.untimedRequests))}):null,e.unpricedRequests>0?(0,r.jsx)("p",{className:"efficiency-role-note",children:t("efficiency.unpricedLowerBound")}):null,e.helpers.length>0?(0,r.jsxs)("section",{className:"efficiency-helpers","aria-label":t("efficiency.helpersTitle"),children:[(0,r.jsx)("h4",{className:"efficiency-helpers-title",children:t("efficiency.helpersTitle")}),(0,r.jsx)("ul",{className:"efficiency-helper-list",children:e.helpers.map(e=>(0,r.jsxs)("li",{className:"efficiency-helper",children:[(0,r.jsx)("span",{className:"efficiency-helper-name",children:`${e.purpose} \xb7 ${e.model}`}),(0,r.jsx)("span",{className:"efficiency-helper-value",children:t("efficiency.helperCallsValue",{count:e.requestCount,output:x0(e.outputTokens),tokens:x0(e.totalTokens),cost:vo(e.estimatedCostUsd)})})]},`${e.purpose}:${e.role??""}:${e.model}`))}),(0,r.jsx)("p",{className:"efficiency-role-note",children:t("efficiency.helpersIncludedNote")})]}):null]})]})}function vv({item:e,t}){let n="unmeasured-gap"===e.kind?t("efficiency.unmeasuredGap"):e.id;return(0,r.jsxs)("li",{className:"efficiency-bottleneck","data-kind":e.kind,children:[(0,r.jsx)("span",{className:"efficiency-bottleneck-label",children:n}),(0,r.jsx)("span",{className:"efficiency-meter","aria-hidden":"true",children:(0,r.jsx)("span",{className:"efficiency-meter-fill",style:{inlineSize:`${Number.isFinite(e.relative)?Math.max(1,Math.min(100,100*e.relative)):1}%`}})}),(0,r.jsx)("span",{className:"efficiency-bottleneck-value",children:x1(e.ms)})]})}function vy({detail:e,t}){return(0,r.jsxs)("div",{className:"efficiency-detail",children:[(0,r.jsxs)("section",{"aria-label":t("efficiency.summarySection"),children:[(0,r.jsx)("h3",{className:"efficiency-section-title",children:t("efficiency.summarySection")}),(0,r.jsxs)("div",{className:"efficiency-dual",children:[(0,r.jsxs)("div",{className:"efficiency-dual-cell",children:[(0,r.jsx)("span",{className:"efficiency-dual-label",children:t("efficiency.elapsed")}),(0,r.jsx)("span",{className:"efficiency-dual-value",children:x1(e.wallClockMs)})]}),(0,r.jsxs)("div",{className:"efficiency-dual-cell",children:[(0,r.jsx)("span",{className:"efficiency-dual-label",children:t("efficiency.busyTotal")}),(0,r.jsx)("span",{className:"efficiency-dual-value",children:x1(e.busyMs)})]})]}),(0,r.jsx)("p",{className:"efficiency-note",children:t("efficiency.noSumNote")}),(0,r.jsxs)("dl",{className:"efficiency-metrics",children:[(0,r.jsx)(vu,{label:t("efficiency.estimatedCost"),value:vo(e.estimatedCostUsd)}),(0,r.jsx)(vu,{label:t("efficiency.tokens"),value:x0(e.totalTokens)}),(0,r.jsx)(vu,{label:t("efficiency.harness"),value:vd(e.harnessRevision,t)})]}),e.unpricedRequests>0?(0,r.jsx)("p",{className:"efficiency-note",children:t("efficiency.unpricedLowerBound")}):null]}),(0,r.jsxs)("section",{"aria-label":t("efficiency.bottlenecksSection"),children:[(0,r.jsx)("h3",{className:"efficiency-section-title",children:t("efficiency.bottlenecksSection")}),(0,r.jsx)("p",{className:"efficiency-note",children:t("efficiency.bottleneckOrderNote")}),e.bottlenecks.length>0?(0,r.jsx)("ol",{className:"efficiency-bottlenecks",children:e.bottlenecks.map(e=>(0,r.jsx)(vv,{item:e,t:t},`${e.kind}:${e.id}`))}):(0,r.jsx)("p",{className:"efficiency-empty",children:t("efficiency.bottlenecksEmpty")}),e.unmeasuredMs>0?(0,r.jsx)("p",{className:"efficiency-note",children:t("efficiency.unmeasuredGapValue").replace("{value}",x1(e.unmeasuredMs))}):null]}),(0,r.jsxs)("section",{"aria-label":t("efficiency.rolesSection"),children:[(0,r.jsx)("h3",{className:"efficiency-section-title",children:t("efficiency.rolesSection")}),e.roles.length>0?(0,r.jsx)("div",{className:"efficiency-roles",children:e.roles.map(e=>(0,r.jsx)(vx,{role:e,t:t},e.id))},e.runId):(0,r.jsx)("p",{className:"efficiency-empty",children:t("efficiency.rolesEmpty")})]}),e.toolTotals.length>0?(0,r.jsxs)("section",{"aria-label":t("efficiency.toolsSection"),children:[(0,r.jsx)("h3",{className:"efficiency-section-title",children:t("efficiency.toolsSection")}),(0,r.jsx)("dl",{className:"efficiency-metrics",children:e.toolTotals.map(e=>(0,r.jsx)(vu,{label:[e.toolName,t("efficiency.toolFailedValue").replace("{value}",String(e.failed)),...e.noMatch>0?[t("efficiency.toolNoMatchValue").replace("{value}",String(e.noMatch))]:[],...e.cancelled>0?[t("efficiency.toolCancelledValue").replace("{value}",String(e.cancelled))]:[]].join(" \xb7 "),value:xX(e.calls)},e.toolName))})]}):null,(0,r.jsx)(vs,{runId:e.runId,t:t},e.runId)]})}function vb(e){return e.map(e=>{let t=e.effort??"–",n=e.count>1?` x${e.count}`:"";return`${e.kind} ${e.model}:${t}${n}`}).join(" \xb7 ")}function vw({response:e,t}){return(0,r.jsx)("section",{className:"efficiency-card",children:(0,r.jsxs)("dl",{className:"m-0 grid grid-cols-2 gap-x-4",children:[(0,r.jsx)(vu,{label:t("efficiency.scopeSessions"),value:xX(e.sessionCount)}),(0,r.jsx)(vu,{label:t("efficiency.scopeRuns"),value:xX(e.runCount)}),(0,r.jsx)(vu,{label:t("efficiency.scopeExcludedRuns"),value:xX(e.excludedRunCount)})]})})}function vk({config:e,baselineRuns:t,t:n}){let s=t>0?e.runCount/t:0,a=e.runCount>0?e.reworkRuns/e.runCount:0,i=e.runCount>0?e.errorRuns/e.runCount:0,l=function(e,t){if(1===e.length)return{text:vd(e[0].revision,t),full:e[0].revision??t("efficiency.harnessUnknown")};let n=e.map(e=>`${vd(e.revision,t)} \xd7${e.runCount}`),r=n.slice(0,4).join(" \xb7 ");return{text:n.length>4?`${r} \xb7 +${n.length-4}`:r,full:e.map(e=>`${e.revision??t("efficiency.harnessUnknown")} \xd7${e.runCount}`).join("\n")}}(e.harnesses,n);return(0,r.jsxs)("section",{className:"efficiency-card",children:[(0,r.jsx)("p",{className:"efficiency-model-line",title:vb(e.roles),children:vb(e.roles)}),(0,r.jsx)("p",{className:"efficiency-dim font-mono tabular-nums",title:l.full,children:n("efficiency.harnessValue").replace("{value}",l.text)}),e.roles.some(e=>"unknown"===e.pairing)?(0,r.jsx)("p",{className:"efficiency-note",children:n("efficiency.mixedPairingNote")}):null,(0,r.jsxs)("div",{className:"efficiency-bottleneck-top",children:[(0,r.jsx)("span",{className:"efficiency-dim",children:n("efficiency.runsValue").replace("{value}",String(e.runCount))}),(0,r.jsx)("span",{className:"font-mono text-xs tabular-nums text-text",children:vc(s)})]}),(0,r.jsx)(vh,{share:s,label:vc(s)}),(0,r.jsxs)("dl",{className:"m-0 grid grid-cols-2 gap-x-4",children:[(0,r.jsx)(vu,{label:n("efficiency.medianElapsed"),value:x1(e.medianWallClockMs)}),(0,r.jsx)(vu,{label:n("efficiency.medianBusy"),value:x1(e.medianBusyMs)}),(0,r.jsx)(vu,{label:n("efficiency.medianTokens"),value:x0(e.medianTotalTokens)}),(0,r.jsx)(vu,{label:n("efficiency.medianEstimatedCost"),value:vo(e.medianEstimatedCostUsd)}),(0,r.jsx)(vu,{label:n("efficiency.totalEstimatedCost"),value:vo(e.totalEstimatedCostUsd)}),(0,r.jsx)(vu,{label:n("efficiency.reworkRate"),value:vc(a,1)}),(0,r.jsx)(vu,{label:n("efficiency.errorRate"),value:vc(i,1)}),(0,r.jsx)(vu,{label:n("efficiency.unpricedRuns"),value:xX(e.unpricedRuns)}),(0,r.jsx)(vu,{label:n("efficiency.untimedRuns"),value:xX(e.untimedRuns)})]}),e.untimedRuns>0?(0,r.jsx)("p",{className:"efficiency-note",children:n("efficiency.untimedMedianLowerBound").replace("{value}",xX(e.untimedRuns))}):null,e.unpricedRuns>0?(0,r.jsx)("p",{className:"efficiency-note",children:n("efficiency.unpricedLowerBound")}):null]})}function vj({open:e,sessionId:t,activeTab:n,onTabChange:a,client:i,className:o}){let c=(0,s.useId)(),d=(0,s.useId)(),{t:u}=(0,F.s)(),h=function({sessionId:e,visible:t,activeTab:n,client:r}){let[a]=(0,s.useState)(()=>r??function(e=(e,t)=>fetch(e,t)){let t=async(t,n)=>{let r;try{r=await e(t,n)}catch(e){if(n.signal?.aborted)throw e;throw new xR("unreachable","효율 기록에 연결할 수 없습니다.")}let s=await xY(r);if(!r.ok){var a;throw new xR("http",(a=`HTTP ${r.status}`,null!==s&&"object"==typeof s&&"error"in s&&"string"==typeof s.error&&s.error?s.error:a),r.status)}return{response:r,body:s}};return{async listRuns(e,n,r){let{response:s,body:a}=await t(`${x$}?sessionId=${encodeURIComponent(e)}&limit=${encodeURIComponent(String(n))}`,{method:"GET",signal:r});return function(e,t,n=null){try{if(!xD(e)||!("string"==typeof e.sessionId&&Array.isArray(e.runs)&&e.runs.every(xH)&&xG(e.unmeasured)))throw new xR("invalid-response","실행 목록 응답이 올바르지 않습니다.");return e}catch{throw new xR("invalid-response",t,n)}}(a,"실행 목록 응답이 올바르지 않습니다.",s.status)},async getRun(e,n){let{response:r,body:s}=await t(`${x$}/${encodeURIComponent(e)}`,{method:"GET",signal:n});return function(e,t,n=null){try{if(!xH(e)||!(Array.isArray(e.roles)&&e.roles.every(xU)&&Array.isArray(e.bottlenecks)&&e.bottlenecks.every(xB)&&"number"==typeof e.unmeasuredMs&&Number.isFinite(e.unmeasuredMs)&&Array.isArray(e.toolTotals)&&e.toolTotals.every(xq)&&xG(e.unmeasured)))throw new xR("invalid-response","실행 상세 응답이 올바르지 않습니다.");return e}catch{throw new xR("invalid-response",t,n)}}(s,"실행 상세 응답이 올바르지 않습니다.",r.status)},async listExperiments(e,n,r,s,a){let i=new URLSearchParams;null!==e&&""!==e&&i.set("folder",e),i.set("sessions",String(n)),i.set("scope",r),a?.groupBy==="harness"&&i.set("groupBy","harness"),a?.harness&&i.set("harness",a.harness);let{response:l,body:o}=await t(`/api/experiments?${i.toString()}`,{method:"GET",signal:s});return function(e,t,n=null){try{if(!xD(e)||!((null===e.folder||"string"==typeof e.folder)&&xW(e.folders)&&"string"==typeof e.scope&&xF.includes(e.scope)&&Array.isArray(e.configs)&&e.configs.every(xJ)&&"number"==typeof e.runCount&&Number.isFinite(e.runCount)&&"number"==typeof e.sessionCount&&Number.isFinite(e.sessionCount)&&"number"==typeof e.excludedRunCount&&Number.isFinite(e.excludedRunCount)&&"string"==typeof e.groupBy&&xz.includes(e.groupBy)&&(null===e.harness||"string"==typeof e.harness)&&Array.isArray(e.harnesses)&&e.harnesses.every(xK)&&xG(e.unmeasured)))throw new xR("invalid-response","구성 비교 응답이 올바르지 않습니다.");return e}catch{throw new xR("invalid-response",t,n)}}(o,"구성 비교 응답이 올바르지 않습니다.",l.status)}}}()),[i,l]=(0,s.useState)({status:"idle",runs:[],error:null}),[o,c]=(0,s.useState)({status:"idle",runId:null,detail:null,error:null}),[d,u]=(0,s.useState)({status:"idle",response:null,error:null}),[h,p]=(0,s.useState)(null),[m,f]=(0,s.useState)(null),g=(0,s.useRef)(null),x=(0,s.useRef)(null),v=(0,s.useRef)(null),y=(0,s.useRef)(null);(0,s.useEffect)(()=>{x.current?.abort(),x.current=null,p(null),c({status:"idle",runId:null,detail:null,error:null}),l({status:"idle",runs:[],error:null})},[e]);let b=(0,s.useCallback)(()=>{if(!t||"governor"!==n||!e)return;g.current?.abort();let r=new AbortController;g.current=r,l(e=>({status:"loading",runs:"ready"===e.status||"empty"===e.status?e.runs:[],error:null})),a.listRuns(e,20,r.signal).then(e=>{if(!r.signal.aborted&&g.current===r){if(0===e.runs.length)return void l({status:"empty",runs:[],error:null});l({status:"ready",runs:e.runs,error:null})}}).catch(e=>{r.signal.aborted||g.current!==r||l({status:"error",runs:[],error:xQ(e,"실행 목록을 불러오지 못했습니다.")})})},[n,a,e,t]),w=(0,s.useCallback)(e=>{if(!t)return;x.current?.abort();let n=new AbortController;x.current=n,c({status:"loading",runId:e,detail:null,error:null}),a.getRun(e,n.signal).then(t=>{n.signal.aborted||x.current!==n||c({status:"ready",runId:e,detail:t,error:null})}).catch(t=>{n.signal.aborted||x.current!==n||c({status:"error",runId:e,detail:null,error:xQ(t,"실행 상세를 불러오지 못했습니다.")})})},[a,t]),k=(0,s.useCallback)((e,r="all",s=xZ)=>{if(!t||"lab"!==n)return;v.current?.abort();let i=new AbortController;v.current=i,u(e=>({status:"loading",response:"ready"===e.status||"empty"===e.status?e.response:null,error:null})),a.listExperiments(e,30,r,i.signal,s).then(e=>{if(!i.signal.aborted&&v.current===i){if(0===e.configs.length)return void u({status:"empty",response:e,error:null});u({status:"ready",response:e,error:null})}}).catch(e=>{i.signal.aborted||v.current!==i||u({status:"error",response:null,error:xQ(e,"구성 비교를 불러오지 못했습니다.")})})},[n,a,t]);(0,s.useEffect)(()=>{if(t&&"governor"===n)return b(),()=>{g.current?.abort(),g.current=null}},[n,b,e,t]),(0,s.useEffect)(()=>{if(t&&"lab"===n)return k(y.current),()=>{v.current?.abort(),v.current=null}},[n,k,t]),(0,s.useEffect)(()=>{if(t&&"governor"===n&&null!==h)return w(h),()=>{x.current?.abort(),x.current=null}},[n,w,h,t]),(0,s.useEffect)(()=>()=>{g.current?.abort(),x.current?.abort(),v.current?.abort()},[]);let j=(0,s.useCallback)(e=>{x.current?.abort(),x.current=null,p(e),null===e&&c({status:"idle",runId:null,detail:null,error:null})},[]);return{list:i,detail:o,experiments:d,selectedRunId:h,selectRun:j,refreshRuns:(0,s.useCallback)(()=>{b()},[b]),refreshExperiments:(0,s.useCallback)((e,t="all",n=xZ)=>{let r=void 0===e?y.current:e;void 0!==e&&(y.current=e,f(e)),k(r,t,n)},[k]),experimentFolder:m}}({sessionId:t,visible:e,activeTab:n,client:i}),[p,m]=(0,s.useState)(""),f=(0,s.useMemo)(()=>h.experiments.response?.folders??[],[h.experiments.response]),g=(0,s.useMemo)(()=>h.experiments.response?.configs.reduce((e,t)=>Math.max(e,t.runCount),0)??0,[h.experiments.response]),x=h.experimentFolder,v=h.experiments.response?.scope??"all",y={groupBy:h.experiments.response?.groupBy??"config",harness:h.experiments.response?.harness??null},b=h.experiments.response?.harnesses??[];if(!e)return null;let w="governor"===n&&"loading"===h.list.status||"lab"===n&&"loading"===h.experiments.status,k=w?u("efficiency.refreshing"):u("efficiency.refresh"),j="governor"===n?h.list.runs.length>0?u("efficiency.runsValue").replace("{value}",String(h.list.runs.length)):"":h.experiments.response?u("efficiency.runsValue").replace("{value}",String(h.experiments.response.runCount)):"";return(0,r.jsxs)("section",{className:vl("efficiency-panel flex min-h-0 w-full flex-col overflow-hidden bg-bg-panel text-text",o),"aria-labelledby":c,"aria-busy":w,children:[(0,r.jsxs)("header",{className:"flex min-h-12 items-center gap-3 px-3",children:[(0,r.jsx)("h1",{id:c,className:"m-0 text-sm font-semibold text-text",children:u("efficiency.title")}),(0,r.jsx)("span",{className:"min-w-0 flex-1 truncate text-right font-mono text-[11px] tabular-nums text-text-dim",children:j}),(0,r.jsx)(l.r,{variant:"neutralWeak",size:"xsmall",onClick:()=>{"governor"===n?h.refreshRuns():h.refreshExperiments(void 0,v,y)},disabled:w,children:k})]}),(0,r.jsx)("div",{className:"mx-3 mb-2 grid grid-cols-2 gap-0.5 rounded-[var(--radius-control)] bg-[var(--bg-rail)] p-0.5",role:"tablist","aria-label":u("efficiency.title"),children:["governor","lab"].map(e=>(0,r.jsx)("button",{type:"button",role:"tab","aria-selected":n===e,id:`${d}-${e}-tab`,"aria-controls":d,className:vl("min-h-10 rounded-[var(--radius-control)] px-4 text-sm text-text-muted hover:bg-bg-hover",n===e&&"bg-bg-raised font-semibold text-text hover:bg-bg-raised"),onClick:()=>a(e),children:"governor"===e?u("efficiency.governor"):u("efficiency.lab")},e))}),"lab"===n?(0,r.jsxs)("div",{className:"efficiency-folderbar",children:[(0,r.jsx)("label",{className:"efficiency-folder-label",htmlFor:`${d}-folder`,children:u("efficiency.folder")}),(0,r.jsxs)("select",{id:`${d}-folder`,className:"efficiency-folder-select",value:x??"",onChange:e=>{let t=""===e.target.value?null:e.target.value;m(t??""),h.refreshExperiments(t,v,y)},children:[(0,r.jsx)("option",{value:"",children:u("efficiency.folderAll")}),f.map(e=>(0,r.jsx)("option",{value:e,children:e},e)),x&&!f.includes(x)?(0,r.jsx)("option",{value:x,children:x}):null]}),(0,r.jsx)("input",{className:"efficiency-folder-input",value:p,placeholder:u("efficiency.folderPlaceholder"),"aria-label":u("efficiency.folder"),onChange:e=>m(e.target.value),onKeyDown:e=>{if("Enter"===e.key){let e=""===p.trim()?null:p.trim();h.refreshExperiments(e,v,y)}}}),(0,r.jsx)("label",{className:"efficiency-folder-label",htmlFor:`${d}-harness`,children:u("efficiency.harness")}),(0,r.jsxs)("select",{id:`${d}-harness`,className:"efficiency-folder-select font-mono",value:y.harness??"",onChange:e=>{let t=""===e.target.value?null:e.target.value;h.refreshExperiments(void 0,v,{groupBy:y.groupBy,harness:t})},children:[(0,r.jsx)("option",{value:"",children:u("efficiency.harnessAll")}),b.map(e=>(0,r.jsx)("option",{value:e.revision??xE,children:`${vd(e.revision,u)} (${e.runCount})`},e.revision??xE)),y.harness&&!b.some(e=>(e.revision??xE)===y.harness)?(0,r.jsx)("option",{value:y.harness,children:y.harness===xE?u("efficiency.harnessUnknown"):y.harness.slice(0,7)}):null]}),(0,r.jsxs)("div",{className:"col-span-full flex flex-col items-start gap-2",children:[(0,r.jsx)(xM.f,{variant:"neutralWeak",size:"xsmall",pressed:"attributed"===v,onPressedChange:e=>h.refreshExperiments(void 0,e?"attributed":"all",y),children:u("efficiency.scopeAttributed")}),(0,r.jsx)(n2.E,{tone:"attributed"===v?"informative":"neutral",variant:"weak",size:"medium",children:u("attributed"===v?"efficiency.scopeAttributed":"efficiency.scopeAll")}),(0,r.jsx)(xM.f,{variant:"neutralWeak",size:"xsmall",pressed:"harness"===y.groupBy,onPressedChange:e=>h.refreshExperiments(void 0,v,{groupBy:e?"harness":"config",harness:y.harness}),children:u("efficiency.groupByHarness")})]})]}):null,(0,r.jsx)("div",{id:d,className:"min-h-0 flex-1 overflow-y-auto overscroll-contain",role:"tabpanel","aria-labelledby":`${d}-${n}-tab`,children:"governor"===n?t?"idle"===h.list.status||"loading"===h.list.status?(0,r.jsx)("div",{className:"p-4 text-sm text-text-muted",role:"status",children:u("efficiency.loadingRuns")}):"error"===h.list.status?(0,r.jsxs)("div",{className:"p-4 text-sm text-text",role:"alert",children:[(0,r.jsx)("div",{className:"font-medium",children:u("efficiency.runsError")}),(0,r.jsx)("div",{className:"mt-1 text-xs text-text-muted",children:h.list.error})]}):"empty"===h.list.status?(0,r.jsx)("p",{className:"efficiency-empty",children:u("efficiency.runsEmpty")}):(0,r.jsxs)("div",{className:"efficiency-governor",children:[(0,r.jsx)("ul",{className:"efficiency-run-list",children:h.list.runs.map(e=>(0,r.jsx)(vg,{run:e,selected:h.selectedRunId===e.runId,onSelect:()=>h.selectRun(h.selectedRunId===e.runId?null:e.runId),t:u},e.runId))}),(0,r.jsx)("div",{className:"efficiency-detail-pane",children:null===h.selectedRunId||"idle"===h.detail.status?(0,r.jsx)("p",{className:"efficiency-empty",children:u("efficiency.selectRun")}):"loading"===h.detail.status?(0,r.jsx)("div",{className:"p-4 text-sm text-text-muted",role:"status",children:u("efficiency.loadingDetail")}):"error"===h.detail.status?(0,r.jsxs)("div",{className:"p-4 text-sm text-text",role:"alert",children:[(0,r.jsx)("div",{className:"font-medium",children:u("efficiency.detailError")}),(0,r.jsx)("div",{className:"mt-1 text-xs text-text-muted",children:h.detail.error})]}):h.detail.detail?(0,r.jsx)(vy,{detail:h.detail.detail,t:u}):null})]}):(0,r.jsx)("p",{className:"efficiency-empty",children:u("efficiency.noSession")}):(()=>{if("idle"===h.experiments.status||"loading"===h.experiments.status)return(0,r.jsx)("div",{className:"p-4 text-sm text-text-muted",role:"status",children:u("efficiency.loadingExperiments")});if("error"===h.experiments.status)return(0,r.jsxs)("div",{className:"p-4 text-sm text-text",role:"alert",children:[(0,r.jsx)("div",{className:"font-medium",children:u("efficiency.experimentsError")}),(0,r.jsx)("div",{className:"mt-1 text-xs text-text-muted",children:h.experiments.error})]});let e=h.experiments.response;return"empty"!==h.experiments.status&&e?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("p",{className:"efficiency-note",children:u("efficiency.difficultyNote")}),(0,r.jsx)("p",{className:"efficiency-note",children:u("efficiency.harnessNote")}),(0,r.jsxs)("div",{className:"efficiency-stack",children:[(0,r.jsx)(vw,{response:e,t:u}),e.configs.map(t=>(0,r.jsx)(vk,{config:t,baselineRuns:g,t:u},JSON.stringify([t.roles.map(e=>[e.kind,e.models,e.efforts,e.count]),"harness"===e.groupBy?t.harnesses[0]?.revision??null:null])))]})]}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("p",{className:"efficiency-empty",children:u("efficiency.experimentsEmpty")}),e?(0,r.jsx)("div",{className:"efficiency-stack",children:(0,r.jsx)(vw,{response:e,t:u})}):null,(0,r.jsx)("p",{className:"efficiency-note",children:u("efficiency.difficultyNote")}),(0,r.jsx)("p",{className:"efficiency-note",children:u("efficiency.harnessNote")})]})})()})]})}var vS=n(96607),vC=n(29213),vN=n.n(vC);let vT="cuelo-plugin-lab-open",vI="/api/plugin-lab",vM=(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 8a5 5 0 1 1-1.46-3.54M13 2.5v3h-3"})});async function vE(e){try{let t=await e.json();if("string"==typeof t.error&&t.error)return t.error}catch{}return`HTTP ${e.status}`}function v$(e){return e.hasPanel&&e.enabled}let vR=new Map;function vL({title:e,visible:t,sessionId:n,labWidgets:a,onInsertDraft:i}){let{t:o}=(0,F.s)(),[c,d]=(0,s.useState)({kind:"loading"}),[u,h]=(0,s.useState)(()=>new Set),[p,m]=(0,s.useState)({}),[f,g]=(0,s.useState)(null),x=(0,s.useRef)(0);(0,s.useEffect)(()=>{g(function(){try{return window.localStorage.getItem(vT)}catch{return null}}())},[]);let v=(0,s.useCallback)(async()=>{let e=++x.current;d(e=>"ready"===e.kind?e:{kind:"loading"});try{let t=await fetch(vI,{cache:"no-store"});if(!t.ok)throw Error(await vE(t));let n=await t.json();e===x.current&&d({kind:"ready",plugins:n.plugins??[]})}catch(t){e===x.current&&d({kind:"error",message:t instanceof Error?t.message:String(t)})}},[]);(0,s.useEffect)(()=>{t&&v()},[t,v]);let y=(0,s.useCallback)(async(e,t)=>{h(t=>new Set(t).add(e.id)),m(t=>({...t,[e.id]:null}));try{let n=await fetch(`${vI}/${encodeURIComponent(e.id)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({enabled:t})});if(!n.ok)throw Error(await vE(n));let r=await n.json();d(e=>"ready"===e.kind?{kind:"ready",plugins:e.plugins.map(e=>e.id===r.plugin.id?r.plugin:e)}:e),v()}catch(t){m(n=>({...n,[e.id]:t instanceof Error?t.message:String(t)}))}finally{h(t=>{let n=new Set(t);return n.delete(e.id),n})}},[v]),b=(0,s.useCallback)(e=>{g(e);try{e?window.localStorage.setItem(vT,e):window.localStorage.removeItem(vT)}catch{}},[]),w="ready"===c.kind?c.plugins:[],k=f?w.find(e=>e.id===f&&v$(e))??null:null;if(k)return(0,r.jsx)(vA,{plugin:k,sessionId:n,labWidgets:a,onInsertDraft:i,onBack:()=>b(null)});let j=w.some(e=>e.hasExtension);return(0,r.jsxs)("section",{className:vN().view,"aria-label":e,children:[(0,r.jsx)(p$,{title:e,subtitle:"ready"===c.kind?o("pluginLab.counts",{count:w.length}):void 0,actions:[{id:"refresh",label:o("pluginLab.refresh"),icon:vM,onClick:()=>void v()}]}),(0,r.jsxs)("div",{className:vN().toolbar,children:[(0,r.jsx)(l.r,{variant:"neutralWeak",size:"small",disabled:!i,onClick:()=>i?.(o("pluginLab.starter")),title:i?o("pluginLab.createHint"):o("pluginLab.noComposer"),children:o("pluginLab.create")}),j&&(0,r.jsx)("p",{className:vN().hint,children:o("pluginLab.applyHint")})]}),(0,r.jsxs)("div",{className:vN().body,children:["loading"===c.kind&&(0,r.jsx)("p",{className:vN().message,role:"status",children:o("pluginLab.loading")}),"error"===c.kind&&(0,r.jsxs)("div",{className:vN().message,role:"alert",children:[(0,r.jsx)("p",{className:vN().errorText,children:o("pluginLab.loadFailed",{error:c.message})}),(0,r.jsx)(l.r,{variant:"neutralWeak",size:"small",onClick:()=>void v(),children:o("pluginLab.retry")})]}),"ready"===c.kind&&0===w.length&&(0,r.jsx)("p",{className:vN().message,children:o("pluginLab.empty")}),"ready"===c.kind&&w.length>0&&(0,r.jsx)("ul",{className:vN().list,"aria-label":o("pluginLab.listLabel"),children:w.map(e=>(0,r.jsx)(vP,{plugin:e,busy:u.has(e.id),error:p[e.id]??null,onToggle:t=>void y(e,t),onOpen:()=>b(e.id)},e.id))})]})]})}function vP({plugin:e,busy:t,error:n,onToggle:a,onOpen:i}){let{t:o,locale:c}=(0,F.s)(),d=e.enabled,[u,h]=(0,s.useState)(!1),p=(0,s.useMemo)(()=>[...e.enhancements??[]].reverse(),[e.enhancements]);return(0,r.jsxs)("li",{className:vN().card,"data-enabled":d?"true":"false","aria-busy":t||void 0,children:[(0,r.jsxs)("div",{className:vN().cardHead,children:[(0,r.jsxs)("div",{className:vN().titleBlock,children:[(0,r.jsx)("div",{className:vN().titleLine,children:(0,r.jsx)("span",{className:vN().name,title:e.name,children:e.name})}),(0,r.jsx)("span",{className:vN().id,title:e.id,children:e.id})]}),(0,r.jsx)("div",{className:vN().control,children:(0,r.jsxs)(vS.h.Root,{className:vN().switch,size:"24",tone:"brand",checked:e.enabled,disabled:t,onCheckedChange:a,"aria-label":o("pluginLab.toggleLabel",{name:e.name}),children:[(0,r.jsx)(vS.h.HiddenInput,{}),(0,r.jsx)(vS.h.Label,{className:vN().switchLabel,children:t?o("pluginLab.saving"):e.enabled?o("pluginLab.on"):o("pluginLab.off")}),(0,r.jsx)(vS.h.Control,{children:(0,r.jsx)(vS.h.Thumb,{})})]})})]}),e.description&&(0,r.jsx)("p",{className:vN().description,children:e.description}),p.length>0&&(0,r.jsxs)("div",{className:vN().enhancement,children:[(0,r.jsx)("span",{className:vN().metaLabel,children:o("pluginLab.enhancements")}),p.slice(0,u?p.length:3).map((e,t)=>{var n;let s;return(0,r.jsxs)("div",{className:vN().enhancement,children:[(0,r.jsx)("p",{className:vN().enhancementHead,children:(0,r.jsx)("time",{className:vN().enhancementDate,dateTime:e.at,title:o("pluginLab.enhancementDateHint"),children:(n=e.at,(s=vR.get(c))||(s=new Intl.DateTimeFormat(c,{dateStyle:"medium"}),vR.set(c,s)),s.format(new Date(n)))})}),(0,r.jsx)("p",{className:vN().enhancementSummary,children:e.summary})]},`${e.at}-${t}`)}),p.length>3&&(0,r.jsx)("div",{className:vN().cardActions,children:(0,r.jsx)(l.r,{variant:"neutralWeak",size:"small","aria-expanded":u,onClick:()=>h(e=>!e),children:u?o("pluginLab.showFewerEnhancements"):o("pluginLab.showAllEnhancements",{count:p.length})})})]}),e.tools.length>0&&(0,r.jsxs)("div",{className:vN().tools,children:[(0,r.jsx)("span",{className:vN().metaLabel,children:o("pluginLab.tools")}),(0,r.jsx)("ul",{className:vN().toolList,"aria-label":o("pluginLab.tools"),children:e.tools.map(e=>(0,r.jsx)("li",{className:vN().tool,children:e},e))})]}),e.problem&&(0,r.jsxs)("p",{className:vN().problem,children:[(0,r.jsx)("span",{className:vN().problemLabel,children:o("pluginLab.problem")}),(0,r.jsx)("span",{children:e.problem})]}),n&&(0,r.jsx)("p",{className:vN().problem,role:"alert",children:o("pluginLab.toggleFailed",{error:n})}),v$(e)&&(0,r.jsx)("div",{className:vN().cardActions,children:(0,r.jsx)(l.r,{variant:"neutralWeak",size:"small",onClick:i,"aria-label":o("pluginLab.openPanelLabel",{name:e.name}),children:o("pluginLab.openPanel")})})]})}function vA({plugin:e,sessionId:t,labWidgets:n,onInsertDraft:a,onBack:i}){let{t:l}=(0,F.s)(),{theme:o}=nN(),c=(0,s.useRef)(null),d=(0,s.useMemo)(()=>{var r,s;return n.sessionId===t?(r=n.widgets,s=e.id,r.filter(e=>dc(e.key)===s).flatMap(e=>[...e.lines])):[]},[n,t,e.id]),u=(0,s.useRef)({sessionId:null,lines:[],theme:"light"}),h=(0,s.useRef)(a),[p,m]=(0,s.useState)(null);(0,s.useEffect)(()=>{h.current=a},[a]);let f=(0,s.useMemo)(()=>{var t;let n;return t={frame:()=>c.current?.contentWindow??null,state:()=>u.current,insertDraft:e=>{let t=h.current;return t?(t(e),m(l("pluginLab.draftInserted")),!0):(m(l("pluginLab.noComposer")),!1)},recordDraft:()=>{fetch(`${vI}/${encodeURIComponent(e.id)}/event`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({event:"draft"})}).then(e=>{e.ok||m(l("pluginLab.draftNotRecorded"))},()=>m(l("pluginLab.draftNotRecorded")))}},{publishState:n=()=>{let e=t.frame();if(!e)return;let{sessionId:n,lines:r,theme:s}=t.state();e.postMessage({type:"cuelo-lab:state",sessionId:n,lines:[...r],...s?{theme:s}:{}},"*")},handleMessage(e){let r=function(e,t){if(!t||e.source!==t||"null"!==e.origin||"object"!=typeof e.data||null===e.data||Array.isArray(e.data))return null;let n=e.data,r=Object.keys(n).sort().join(",");if("cuelo-lab:ready"===n.type)return"type"===r?{type:"cuelo-lab:ready"}:null;if("cuelo-lab:draft"!==n.type||"text,type"!==r||"string"!=typeof n.text)return null;let s=function(e){if(e.length<=4e3)return e;let t=e.slice(0,4e3),n=t.charCodeAt(t.length-1);return n>=55296&&n<=56319?t.slice(0,-1):t}(n.text);return s.trim()?{type:"cuelo-lab:draft",text:s}:null}(e,t.frame());if(r){if("cuelo-lab:ready"===r.type)return void n();t.insertDraft(r.text)&&t.recordDraft()}}}},[e.id,l]);return(0,s.useEffect)(()=>(window.addEventListener("message",f.handleMessage),()=>window.removeEventListener("message",f.handleMessage)),[f]),(0,s.useEffect)(()=>{u.current={sessionId:t,lines:d,theme:o},f.publishState()},[f,t,d,o]),(0,r.jsxs)("section",{className:vN().view,"aria-label":l("pluginLab.frameTitle",{name:e.name}),children:[(0,r.jsx)(p$,{back:{label:l("pluginLab.back"),onClick:i},title:e.name,subtitle:l("pluginLab.panelSubtitle",{id:e.id})}),(0,r.jsx)("div",{className:vN().stage,children:(0,r.jsx)("iframe",{ref:c,className:vN().frame,title:l("pluginLab.frameTitle",{name:e.name}),src:`${vI}/${encodeURIComponent(e.id)}/panel`,sandbox:"allow-scripts",referrerPolicy:"no-referrer"})}),(0,r.jsxs)("div",{className:vN().status,children:[(0,r.jsx)("span",{className:vN().lines,"data-live":d.length>0?"true":"false",children:d.length>0?l("pluginLab.lines",{count:d.length}):l("pluginLab.noLines")}),(0,r.jsx)("span",{role:"status",className:vN().notice,children:p})]})]})}function v_(e){return`request:${e}`}function vF(e){return`memory:${e}`}function vO(e){return`doc:${e}`}function vz(e){return`file:${e}`}var vD=n(2498),vW=n.n(vD);let vH="cuelo-memory-trace-scope",vU="cuelo-memory-trace-request:";function vB(e){return e.replace(/\b[\w.-]+=[0-9a-f]{12,}\b/gi,"").replace(/\b[0-9a-f]{16,}\b/gi,"").replace(/\s{2,}/g," ").trim()}function vq(e){return e.replace(/\[([^\]]+)\]\([^)]*\)/g,"$1").replace(/`+/g,"").replace(/\*\*|__/g,"").replace(/(^|\n)[ \t]*(?:#{1,6}|[-*+]|\d+[.)])[ \t]+/g,"$1").replace(/\s+/g," ").trim()}let vV=/^\[(하네스 통지|자동 재개)\]\s*/;function vK(e){let t=/^(\S+) · ([\s\S]*)$/.exec(e);return t?`${t[1]} \xb7 ${vq(t[2])}`:vq(e)}let vJ=(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 8a5 5 0 1 1-1.46-3.54M13 2.5v3h-3"})}),vG=["recall","jev","docmap","docs","lessons","saved"],vY={recall:"memoryTrace.stageRecall",jev:"memoryTrace.stageJev",docmap:"memoryTrace.stageDocmap",docs:"memoryTrace.stageDocs",lessons:"memoryTrace.stageLessons",saved:"memoryTrace.stageSaved"};function vZ(e,t){let n=e=>e.some(e=>vF(e.id)===t);return n(e.recalled)||e.explicit.some(e=>n(e.memories))?"recall":e.lessons.some(e=>vz(e.file)===t||vO(e.file)===t||n(e.memories))?"lessons":e.docs.some(e=>vO(e.path)===t)?"docs":e.candidates.some(e=>vO(e.path)===t)?"docmap":e.saved.some(e=>e.nodeId===t)?"saved":[...e.verdicts.keys()].some(e=>vF(e)===t)?"jev":null}async function vQ(e){try{let t=await e.json();if("string"==typeof t.error&&t.error)return t.error}catch{}return`HTTP ${e.status}`}function vX({title:e,visible:t,sessionId:n}){let a,{t:i,locale:o}=(0,F.s)(),[c,d]=(0,s.useState)({kind:"idle"}),[u,h]=(0,s.useState)(null),[p,m]=(0,s.useState)(null),[f,g]=(0,s.useState)(null),[x,v]=(0,s.useState)("request"),y=(0,s.useRef)(0),b=(0,s.useRef)(null),w=(0,s.useRef)(null);(0,s.useEffect)(()=>{v(function(){try{return"session"===window.localStorage.getItem(vH)?"session":"request"}catch{return"request"}}())},[]),(0,s.useEffect)(()=>{h(n?function(e){try{return window.sessionStorage.getItem(vU+e)}catch{return null}}(n):null),g(null)},[n]);let k=(0,s.useCallback)(async()=>{let e=++y.current;if(b.current?.abort(),!n)return void d({kind:"idle"});let t=new AbortController;b.current=t,d(e=>"ready"===e.kind&&e.trace.sessionId===n?e:{kind:"loading"});try{let r=await fetch(`/api/sessions/${encodeURIComponent(n)}/memory-trace`,{cache:"no-store",signal:t.signal});if(!r.ok)throw Error(await vQ(r));let s=await r.json();e===y.current&&d({kind:"ready",trace:s})}catch(n){if(t.signal.aborted)return;e===y.current&&d({kind:"error",message:n instanceof Error?n.message:String(n)})}},[n]);(0,s.useEffect)(()=>t?(k(),()=>b.current?.abort()):void 0,[t,k]);let j="ready"===c.kind&&c.trace.sessionId===n?c.trace:null,S=(0,s.useMemo)(()=>j?j.requests.map((e,t)=>{let n,r,s;return n={index:t+1,request:e,recalled:[],explicit:[],verdicts:new Map,jev:[],candidates:[],docs:[],lessons:[],saved:[],counts:{recall:0,jev:0,docmap:0,docs:0,lessons:0,saved:0},happened:{recall:!1,jev:!1,docmap:!1,docs:!1,lessons:!1,saved:!1}},r=new Map,s=new Set,e.steps.forEach((e,t)=>{switch(e.kind){case"recall":for(let t of e.memories)s.has(t.id)||(s.add(t.id),n.recalled.push(t));break;case"explicit-recall":for(let t of(n.explicit.push({target:e.target,query:e.query,memories:e.memories}),e.memories))s.add(t.id);break;case"jev":for(let t of(n.jev.push({buckets:e.buckets,unknown:e.unknownCount,unrelated:e.unrelatedCount}),e.buckets))for(let e of t.ids)n.verdicts.set(e,{short:t.shortLabel,label:t.label});break;case"docmap":for(let t of e.candidates)n.candidates.some(e=>e.path===t.path)||n.candidates.push(t);break;case"doc-read":{let t=r.get(e.path);t?e.selector&&!t.selectors.includes(e.selector)&&t.selectors.push(e.selector):r.set(e.path,{path:e.path,selectors:e.selector?[e.selector]:[],candidate:e.candidate});break}case"edit-lesson":n.lessons.push({file:e.file,memories:e.memories});break;case"saved":var a;n.saved.push({nodeId:(a=e.entryId,`saved:${a}:${t}`),source:e.source,text:e.text})}}),n.docs=[...r.values()],n.counts={recall:s.size,jev:n.jev.reduce((e,t)=>e+t.buckets.reduce((e,t)=>e+t.ids.length,0),0),docmap:n.candidates.length,docs:n.docs.length,lessons:n.lessons.reduce((e,t)=>e+t.memories.length,0),saved:n.saved.length},n.happened={recall:n.recalled.length>0||n.explicit.length>0,jev:n.jev.length>0,docmap:n.candidates.length>0,docs:n.docs.length>0,lessons:n.lessons.length>0,saved:n.saved.length>0},n}):[],[j]),C=(0,s.useMemo)(()=>S.filter(e=>e.request.steps.length>0),[S]),N=(0,s.useMemo)(()=>[...C].reverse(),[C]),T=C.find(e=>e.request.entryId===u)??N[0]??null;(0,s.useEffect)(()=>{T&&m(e=>e&&T.happened[e]?e:vG.find(e=>T.happened[e])??"recall")},[T]),(0,s.useEffect)(()=>{if(!f)return;let e=CSS.escape(f),t=w.current?.querySelector(`[data-node="${e}"], [data-alt-node="${e}"]`);t?.scrollIntoView({block:"nearest"})},[f,p,T]);let I=e=>{if(h(e),n)try{window.sessionStorage.setItem(vU+n,e)}catch{}},M=(0,s.useMemo)(()=>new Intl.DateTimeFormat(o,{hour:"2-digit",minute:"2-digit"}),[o]);return a=n?"error"===c.kind?(0,r.jsxs)("div",{className:vW().message,role:"alert",children:[(0,r.jsx)("p",{className:vW().errorText,children:i("memoryTrace.error",{error:c.message})}),(0,r.jsx)(l.r,{variant:"neutralOutline",size:"small",onClick:()=>void k(),children:i("memoryTrace.retry")})]}):j?0===C.length?(0,r.jsx)("p",{className:vW().message,children:i("memoryTrace.empty")}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("section",{className:vW().requests,"aria-label":i("memoryTrace.requestsLabel"),children:[(0,r.jsxs)("h3",{className:vW().sectionTitle,children:[i("memoryTrace.requestsLabel"),(0,r.jsx)("span",{className:vW().sectionCount,children:C.length})]}),(0,r.jsx)("div",{className:vW().requestScroller,children:(0,r.jsx)("ul",{className:vW().requestList,children:N.map(e=>{let t=e===T;return(0,r.jsx)("li",{children:(0,r.jsxs)("button",{type:"button",className:vW().requestRow,"aria-current":t?"true":void 0,onClick:()=>{I(e.request.entryId),g(null)},title:e.request.preview,children:[(0,r.jsxs)("span",{className:vW().requestIndex,children:["#",e.index]}),(0,r.jsx)("span",{className:vW().requestTime,children:e.request.at?M.format(e.request.at):""}),(0,r.jsx)(v1,{preview:e.request.preview,className:vW().requestPreview}),(0,r.jsx)("span",{className:vW().miniRail,"aria-hidden":"true",children:vG.map(t=>(0,r.jsx)("span",{"data-on":e.happened[t]?"true":"false"},t))})]})},e.request.entryId)})})})]}),T&&(0,r.jsxs)("section",{className:vW().flow,"aria-label":i("memoryTrace.flowLabel"),children:[(0,r.jsxs)("h3",{className:vW().sectionTitle,children:[(0,r.jsx)("span",{className:vW().titleText,children:i("memoryTrace.requestHeading",{index:T.index})}),(0,r.jsx)(v1,{preview:T.request.preview,className:vW().flowPreview})]}),(0,r.jsx)("ol",{className:vW().rail,children:vG.map((e,t)=>{let n=T.counts[e],s=p===e;return(0,r.jsx)("li",{className:vW().station,"data-filled":T.happened[e]?"true":"false","data-open":s?"true":void 0,children:(0,r.jsxs)("button",{type:"button",className:vW().stationButton,"aria-expanded":s,"aria-controls":"memory-trace-detail",onClick:()=>{m(e),g(null)},children:[(0,r.jsx)("span",{className:vW().stationStep,"aria-hidden":"true",children:t+1}),(0,r.jsx)("span",{className:vW().stationCount,children:n}),(0,r.jsx)("span",{className:vW().stationLabel,children:i(vY[e])}),"docmap"===e&&T.candidates.length>0&&(0,r.jsx)("span",{className:vW().stationNote,children:i("memoryTrace.openedSummary",{opened:T.candidates.filter(e=>e.opened).length,skipped:T.candidates.filter(e=>!e.opened).length})})]})},e)})}),(0,r.jsx)("div",{id:"memory-trace-detail",className:vW().detail,ref:w,role:"region","aria-label":p?i(vY[p]):void 0,children:p&&(0,r.jsx)(v4,{flow:T,stage:p,focusNode:f})})]}),j&&T&&(0,r.jsx)(v7,{trace:j,selected:T,scope:x,onScopeChange:e=>{v(e);try{window.localStorage.setItem(vH,e)}catch{}},focusNode:f,onSelectNode:e=>{if("request"===e.kind){I(e.id.slice(8)),g(null);return}let t=t=>e.edited?"lessons"===vZ(t,e.id):null!==vZ(t,e.id),n=(T&&t(T)?T:N.find(t))??(T&&vZ(T,e.id)?T:N.find(t=>null!==vZ(t,e.id)))??null;n&&(I(n.request.entryId),m(vZ(n,e.id)),g(e.id))}})]}):(0,r.jsx)("p",{className:vW().message,role:"status",children:i("memoryTrace.loading")}):(0,r.jsx)("p",{className:vW().message,children:i("memoryTrace.noSession")}),(0,r.jsxs)("section",{className:vW().view,"aria-label":e,children:[(0,r.jsx)(p$,{title:e,subtitle:j?i("memoryTrace.requests",{count:C.length}):void 0,actions:n?[{id:"refresh",label:i("memoryTrace.refresh"),icon:vJ,onClick:()=>void k(),disabled:"loading"===c.kind}]:[]}),(0,r.jsx)("div",{className:vW().body,"aria-busy":"loading"===c.kind?"true":void 0,children:a})]})}function v0({memory:e,verdict:t,focused:n}){let{t:s}=(0,F.s)();return(0,r.jsxs)("li",{className:vW().item,"data-node":vF(e.id),"data-focused":n?"true":void 0,children:[(0,r.jsxs)("div",{className:vW().itemHead,children:[(0,r.jsx)("code",{className:vW().memoryId,children:e.id}),e.date&&(0,r.jsx)("span",{className:vW().itemMeta,children:e.date}),t&&(0,r.jsx)(n2.E,{size:"medium",variant:"weak",tone:"neutral",title:t.label,children:t.short})]}),(0,r.jsx)("p",{className:vW().itemText,"data-empty":e.preview?void 0:"true",children:e.preview?vq(e.preview):s("memoryTrace.noMemoryText")})]})}function v1({preview:e,className:t}){let n,{t:s}=(0,F.s)(),{notice:a,text:i}=(n=vV.exec(e))?{notice:"자동 재개"===n[1]?"resume":"harness",text:e.slice(n[0].length)}:{notice:null,text:e},l=vB(i);return(0,r.jsxs)("span",{className:t,title:e,children:[a&&(0,r.jsx)("span",{className:vW().noticeChip,children:s("harness"===a?"memoryTrace.noticeHarness":"memoryTrace.noticeResume")}),l||(a?"":s("memoryTrace.noPreview"))]})}function v2({path:e}){return(0,r.jsx)("span",{className:vW().path,title:e,dir:"rtl",children:(0,r.jsx)("bdi",{dir:"ltr",children:e})})}function v4({flow:e,stage:t,focusNode:n}){let{t:s}=(0,F.s)();if(!e.happened[t])return(0,r.jsx)("p",{className:vW().stageEmpty,children:s("memoryTrace.stageEmpty")});switch(t){case"recall":return(0,r.jsxs)(r.Fragment,{children:[e.recalled.length>0&&(0,r.jsxs)("div",{className:vW().group,children:[(0,r.jsx)("h4",{className:vW().groupTitle,children:s("memoryTrace.autoRecall")}),(0,r.jsx)("ul",{className:vW().items,children:e.recalled.map(t=>(0,r.jsx)(v0,{memory:t,verdict:e.verdicts.get(t.id),focused:n===vF(t.id)},t.id))})]}),e.explicit.map((t,a)=>(0,r.jsxs)("div",{className:vW().group,children:[(0,r.jsxs)("h4",{className:vW().groupTitle,children:[s("memoryTrace.explicitRecall"),(0,r.jsx)("code",{className:vW().groupCode,children:t.target})]}),t.query&&(0,r.jsxs)("p",{className:vW().query,children:[s("memoryTrace.query")," \xb7 ",t.query]}),0===t.memories.length?(0,r.jsx)("p",{className:vW().itemMeta,children:s("memoryTrace.noResults")}):(0,r.jsx)("ul",{className:vW().items,children:t.memories.map(t=>(0,r.jsx)(v0,{memory:t,verdict:e.verdicts.get(t.id),focused:n===vF(t.id)},t.id))})]},`${t.target}-${a}`))]});case"jev":return(0,r.jsx)(r.Fragment,{children:e.jev.map((e,t)=>(0,r.jsxs)("div",{className:vW().group,children:[e.buckets.map(e=>(0,r.jsxs)("div",{className:vW().bucket,children:[(0,r.jsxs)("h4",{className:vW().groupTitle,title:e.label,children:[e.shortLabel,(0,r.jsx)("span",{className:vW().sectionCount,children:e.ids.length})]}),(0,r.jsx)("ul",{className:vW().idList,children:e.ids.map(e=>(0,r.jsx)("li",{"data-node":vF(e),"data-focused":n===vF(e)?"true":void 0,children:(0,r.jsx)("code",{className:vW().memoryId,children:e})},e))})]},e.label)),(0,r.jsxs)("p",{className:vW().itemMeta,children:[null!==e.unknown&&s("memoryTrace.jevUnknown",{count:e.unknown}),null!==e.unknown&&null!==e.unrelated&&" \xb7 ",null!==e.unrelated&&s("memoryTrace.jevUnrelated",{count:e.unrelated})]})]},t))});case"docmap":return(0,r.jsx)("ul",{className:vW().items,children:e.candidates.map(e=>(0,r.jsxs)("li",{className:vW().item,"data-node":vO(e.path),"data-focused":n===vO(e.path)?"true":void 0,"data-skipped":e.opened?void 0:"true",children:[(0,r.jsxs)("div",{className:vW().itemHead,children:[(0,r.jsx)(v2,{path:e.path}),(0,r.jsx)(n2.E,{size:"medium",variant:e.opened?"solid":"weak",tone:e.opened?"positive":"neutral",children:e.opened?s("memoryTrace.opened"):s("memoryTrace.candidateOnly")})]}),(e.status||e.map)&&(0,r.jsxs)("p",{className:vW().itemText,children:[e.status&&(0,r.jsxs)("span",{className:vW().itemMeta,children:["STATUS ",e.status]}),e.status&&e.map&&" \xb7 ",e.map]})]},e.path))});case"docs":return(0,r.jsx)("ul",{className:vW().items,children:e.docs.map(e=>(0,r.jsxs)("li",{className:vW().item,"data-node":vO(e.path),"data-focused":n===vO(e.path)?"true":void 0,children:[(0,r.jsxs)("div",{className:vW().itemHead,children:[(0,r.jsx)(v2,{path:e.path}),e.candidate&&(0,r.jsx)(n2.E,{size:"medium",variant:"weak",tone:"informative",children:s("memoryTrace.fromMap")})]}),e.selectors.length>0&&(0,r.jsx)("p",{className:vW().itemMeta,children:s("memoryTrace.lines",{lines:e.selectors.join(", ")})})]},e.path))});case"lessons":return(0,r.jsx)(r.Fragment,{children:e.lessons.map((e,t)=>(0,r.jsxs)("div",{className:vW().group,"data-node":vz(e.file),"data-alt-node":vO(e.file),"data-focused":n===vz(e.file)||n===vO(e.file)?"true":void 0,children:[(0,r.jsxs)("h4",{className:vW().groupTitle,children:[s("memoryTrace.lessonFor"),(0,r.jsx)(v2,{path:e.file})]}),(0,r.jsx)("ul",{className:vW().items,children:e.memories.map(e=>(0,r.jsx)(v0,{memory:e,focused:n===vF(e.id)},e.id))})]},`${e.file}-${t}`))});case"saved":return(0,r.jsx)("ul",{className:vW().items,children:e.saved.map(e=>(0,r.jsxs)("li",{className:vW().item,"data-node":e.nodeId,"data-focused":n===e.nodeId?"true":void 0,children:[(0,r.jsx)("div",{className:vW().itemHead,children:(0,r.jsx)(n2.E,{size:"medium",variant:"weak",tone:"neutral",children:"autolearn"===e.source?s("memoryTrace.savedAuto"):e.source})}),(0,r.jsx)("p",{className:vW().itemText,children:vq(e.text)})]},e.nodeId))})}}let v8=["apply","excepted","conflict","unconfirmed","unlisted"],v5={apply:"memoryTrace.verdictApply",excepted:"memoryTrace.verdictExcepted",conflict:"memoryTrace.verdictConflict",unconfirmed:"memoryTrace.verdictUnconfirmed",unlisted:"memoryTrace.verdictUnlisted"};function v6(e){return/[\u1100-\u11ff\u3000-\u9fff\uac00-\ud7af\uff00-\uffef]/.test(e)?12:6.8}function v3({kind:e}){switch(e){case"memory":return(0,r.jsx)("circle",{r:5});case"doc":return(0,r.jsx)("rect",{x:-5,y:-5,width:10,height:10,rx:1.5});case"file":return(0,r.jsx)("rect",{x:-5,y:-5,width:10,height:10,transform:"rotate(45)",rx:1});case"request":return(0,r.jsx)("rect",{x:-20,y:-9,width:40,height:18,rx:9})}}function v7({trace:e,selected:t,scope:n,onScopeChange:a,focusNode:i,onSelectNode:l}){let{t:o}=(0,F.s)(),c=(0,s.useRef)(null),[d,u]=(0,s.useState)(0),[h,p]=(0,s.useState)(280),[m,f]=(0,s.useState)(null),g=(0,s.useCallback)(()=>{let e=c.current,t=e?.closest(`.${vW().body}`);if(!e||!t)return;let n=e.getBoundingClientRect().top-t.getBoundingClientRect().top+t.scrollTop,r=Number.parseFloat(getComputedStyle(t).paddingBlockEnd)||0,s=Math.max(280,Math.floor(t.clientHeight-n-r-2));p(e=>Math.abs(e-s)>1?s:e)},[]);(0,s.useLayoutEffect)(g),(0,s.useEffect)(()=>{let e=c.current,t=e?.closest(`.${vW().body}`);if(!e)return;let n=new ResizeObserver(()=>{u(Math.round(e.getBoundingClientRect().width)-2),g()});return n.observe(e),t&&n.observe(t),()=>n.disconnect()},[g]);let x=(0,s.useMemo)(()=>new Map(e.requests.map((e,t)=>[v_(e.entryId),t+1])),[e]),v=(0,s.useMemo)(()=>{let t=new Map(e.nodes.filter(e=>"doc"===e.kind).map(e=>[e.title,e.id])),n=new Map;for(let r of e.nodes){let e="file"===r.kind?t.get(r.title):void 0;e&&n.set(r.id,e)}let r=new Set(n.values());return{nodes:e.nodes.filter(e=>!n.has(e.id)).map(e=>r.has(e.id)?{...e,edited:!0}:e),edges:e.edges.map(e=>({...e,from:n.get(e.from)??e.from,to:n.get(e.to)??e.to})),alias:n}},[e]),{nodes:y,edges:b}=(0,s.useMemo)(()=>{if("session"===n){let e=new Set(v.edges.flatMap(e=>[e.from,e.to]));return{nodes:v.nodes.filter(t=>e.has(t.id)),edges:v.edges}}let e=v_(t.request.entryId),r=new Set([e]),s=v.edges.filter(t=>t.from===e);for(let e of s)r.add(e.to);let a=new Set(t.lessons.flatMap(e=>e.memories.map(t=>{let n;return`${n=e.file,v.alias.get(vz(n))??vz(n)}\u0000${vF(t.id)}`}))),i=v.edges.filter(e=>"lesson"===e.kind&&a.has(`${e.from}\u0000${e.to}`));for(let e of i)r.add(e.to);return{nodes:v.nodes.filter(e=>r.has(e.id)),edges:[...s,...i]}},[v,n,t]),w=(0,s.useMemo)(()=>d>0?function(e,t,n,r,s){let a=e.filter(e=>"request"===e.kind).sort((e,t)=>(s.get(t.id)??0)-(s.get(e.id)??0)),i=new Map(a.map((e,t)=>[e.id,t])),l=new Map;for(let e of t)(l.get(e.from)??l.set(e.from,[]).get(e.from)).push(e.to),(l.get(e.to)??l.set(e.to,[]).get(e.to)).push(e.from);let o=new Map(e.map((e,t)=>[e.id,t])),c=e=>e.map(e=>({node:e,w:(e=>{let t=[];for(let n of l.get(e)??[]){let e=i.get(n);if(void 0!==e)t.push(e);else for(let e of l.get(n)??[]){let n=i.get(e);void 0!==n&&t.push(n)}}return t.length>0?t.reduce((e,t)=>e+t,0)/t.length:Number.MAX_SAFE_INTEGER})(e.id)})).sort((e,t)=>e.w-t.w||(o.get(e.node.id)??0)-(o.get(t.node.id)??0)).map(e=>e.node),d=[c(e.filter(e=>"memory"===e.kind)),a,[...c(e.filter(e=>"doc"===e.kind)),...c(e.filter(e=>"file"===e.kind))]],u=Math.max(1,...d.map(e=>e.length)),h=Math.min(60,Math.max(36,(r-30-16)/u)),p=Math.ceil(30+u*h+16),m=Math.min(160,Math.max(28,Math.round(.1*n))),f=Math.max(0,n-32-22-40-2*m),g=Math.round(.56*f),x=16+g+6+5,v=x+m+20,y=[x,v,v+20+m],b=new Map;return d.forEach((e,t)=>{let n=30+(u-e.length)*h/2+h/2;e.forEach((e,r)=>{b.set(e.id,{node:e,x:y[t],y:Math.round(n+r*h),column:t})})}),{placed:b,height:p,xs:y,neighbours:l,rowH:h,leftLabel:g,rightLabel:f-g}}(y,b,d,h,x):null,[y,b,d,h,x]),k=(0,s.useMemo)(()=>{let e=new Map;if(!t.happened.jev)return e;for(let n of t.recalled)e.set(vF(n.id),"unlisted");for(let[r,s]of t.verdicts){var n;e.set(vF(r),(n=s.label).includes("충돌")?"conflict":n.includes("불충족")||n.includes("예외")?"excepted":n.startsWith("적용")?"apply":"unconfirmed")}return e},[t]),j=(0,s.useMemo)(()=>{let e=new Set(y.flatMap(e=>k.get(e.id)??[]));return v8.filter(t=>e.has(t))},[y,k]),S=m??i,C=(0,s.useMemo)(()=>S&&w?new Set([S,...w.neighbours.get(S)??[]]):null,[S,w]),N=(0,s.useMemo)(()=>{if("request"===n||!w)return null;let e=S??v_(t.request.entryId),r=new Set([e]);for(let t of w.neighbours.get(e)??[])if(r.add(t),t.startsWith("file:")||t.startsWith("doc:"))for(let e of w.neighbours.get(t)??[])e.startsWith("memory:")&&r.add(e);return r},[n,w,S,t]),T={request:o("memoryTrace.legendRequest"),memory:o("memoryTrace.legendMemory"),doc:o("memoryTrace.legendDoc"),file:o("memoryTrace.legendFile")},I=e=>e.edited?`${T.doc} \xb7 ${T.file}`:T[e.kind],M=(0,s.useMemo)(()=>{let e=new Map;if(!w)return e;for(let t of b){let n=w.placed.get(t.from),r=w.placed.get(t.to);if(!n||!r)continue;let s=n.x<=r.x?`${t.from}|${t.to}`:`${t.to}|${t.from}`;(e.get(s)??e.set(s,[]).get(s)).push(t.kind)}return e},[b,w]),E=`memory-trace-arrow-${(0,s.useId)().replace(/[^a-zA-Z0-9_-]/g,"")}`,$=S&&w?w.placed.get(S)?.node??null:null,R=$?k.get($.id):void 0;return(0,r.jsxs)("section",{className:vW().graph,"aria-label":o("memoryTrace.graphLabel"),children:[(0,r.jsxs)("div",{className:vW().graphHead,children:[(0,r.jsx)("h3",{className:vW().sectionTitle,children:o("memoryTrace.graphLabel")}),(0,r.jsxs)(pS.A.Root,{className:vW().scopeSwitch,"aria-label":o("memoryTrace.graphScope"),value:n,onValueChange:e=>a(e),children:[["request","session"].map(e=>(0,r.jsxs)(pS.A.Item,{value:e,children:[(0,r.jsx)(pS.A.ItemHiddenInput,{}),"request"===e?o("memoryTrace.scopeRequest"):o("memoryTrace.scopeSession")]},e)),(0,r.jsx)(pS.A.Indicator,{})]})]}),(0,r.jsxs)("ul",{className:vW().legend,children:[["request","memory","doc","file"].map(e=>(0,r.jsxs)("li",{"data-kind":e,children:[(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"-7 -7 14 14","aria-hidden":"true",children:(0,r.jsx)("g",{className:vW().legendMark,children:"request"===e?(0,r.jsx)("rect",{x:-6,y:-4,width:12,height:8,rx:4}):(0,r.jsx)(v3,{kind:e})})}),T[e]]},e)),["recalled","opened","lesson","candidate"].map(e=>(0,r.jsxs)("li",{"data-kind":`edge-${e}`,children:[(0,r.jsx)("svg",{width:"20",height:"8","aria-hidden":"true",children:(0,r.jsx)("line",{x1:"1",y1:"4",x2:"19",y2:"4"})}),o("recalled"===e?"memoryTrace.edgeRecalled":"opened"===e?"memoryTrace.opened":"lesson"===e?"memoryTrace.edgeLesson":"memoryTrace.candidateOnly")]},e)),y.some(e=>e.edited)&&(0,r.jsxs)("li",{"data-kind":"edited",children:[(0,r.jsx)("svg",{width:"14",height:"14",viewBox:"-7 -7 14 14","aria-hidden":"true",children:(0,r.jsx)("g",{className:vW().legendMark,children:(0,r.jsx)(v3,{kind:"doc"})})}),o("memoryTrace.legendDocEdited")]})]}),j.length>0&&(0,r.jsxs)("ul",{className:vW().legend,"aria-label":o("memoryTrace.verdictLegend"),children:[(0,r.jsx)("li",{className:vW().legendTitle,children:o("memoryTrace.verdictLegend")}),j.map(e=>(0,r.jsxs)("li",{"data-verdict":e,children:[(0,r.jsxs)("svg",{width:"16",height:"16",viewBox:"-8 -8 16 16","aria-hidden":"true",children:[(0,r.jsx)("circle",{className:vW().ring,r:7.5}),(0,r.jsx)("circle",{className:vW().legendMemory,r:4})]}),o(v5[e])]},e))]}),(0,r.jsx)("p",{className:vW().graphCaption,"aria-live":"polite",children:$?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("span",{className:vW().captionKind,children:["request"===$.kind?`#${x.get($.id)??""}`:I($),R?` \xb7 ${o(v5[R])}`:""]}),"request"===$.kind?vB($.title):"memory"===$.kind?vK($.title):$.title]}):o("memoryTrace.graphHint")}),(0,r.jsx)("div",{className:vW().graphFrame,ref:c,children:y.length<=1?(0,r.jsx)("p",{className:vW().stageEmpty,children:o("memoryTrace.graphEmpty")}):w&&(0,r.jsxs)("svg",{className:vW().graphSvg,width:d,height:w.height,viewBox:`0 0 ${d} ${w.height}`,role:"group","aria-label":o("memoryTrace.graphLabel"),onPointerLeave:()=>f(null),children:[(0,r.jsx)("defs",{children:(0,r.jsx)("marker",{id:E,viewBox:"0 0 8 8",refX:"7",refY:"4",markerWidth:"7",markerHeight:"7",orient:"auto-start-reverse",children:(0,r.jsx)("path",{className:vW().arrow,d:"M0,0.5 L8,4 L0,7.5 z"})})}),(0,r.jsxs)("g",{className:vW().columnHeads,"aria-hidden":"true",children:[(0,r.jsx)("text",{x:w.xs[0],y:16,textAnchor:"end",children:T.memory}),(0,r.jsx)("text",{x:w.xs[1],y:16,textAnchor:"middle",children:T.request}),(0,r.jsxs)("text",{x:w.xs[2],y:16,textAnchor:"start",children:[T.doc," \xb7 ",T.file]})]}),(0,r.jsx)("g",{className:vW().edges,"aria-hidden":"true",children:b.map(e=>{let t=w.placed.get(e.from),n=w.placed.get(e.to);if(!t||!n)return null;let[s,a]=t.x<=n.x?[t,n]:[n,t],i=M.get(`${s.node.id}|${a.node.id}`)??[e.kind],l=(i.indexOf(e.kind)-(i.length-1)/2)*4,o=s.y+l,c=a.y+l,d=1===s.column?s.x+(s.x<a.x?20:-20):s.x+5,u=0===s.column&&2===a.column,h=1===a.column?a.x-20:a.x-5-3*!!u,p=(d+h)/2,m=u?d+Math.max(12,(w.xs[1]-20-d)*.4):null,f=u&&[...w.placed.values()].some(e=>1===e.column&&12>Math.abs(e.y-c)),g=c+(c+w.rowH/2>w.height-16?-1:1)*(w.rowH/2),x=w.xs[1]+20+8,v=null===m?`M${d},${o} C${p},${o} ${p},${c} ${h},${c}`:f?`M${d},${o} C${(d+m)/2},${o} ${(d+m)/2},${g} ${m},${g} L${x},${g} C${(x+h)/2},${g} ${(x+h)/2},${c} ${h},${c}`:`M${d},${o} C${(d+m)/2},${o} ${(d+m)/2},${c} ${m},${c} L${h},${c}`,y=null!==S&&(e.from===S||e.to===S),b=null!==N&&!(N.has(e.from)&&N.has(e.to));return(0,r.jsx)("path",{d:v,"data-kind":e.kind,"data-on":y?"true":void 0,"data-dim":b&&!y?"true":void 0,markerEnd:u?`url(#${E})`:void 0},`${e.from}|${e.to}|${e.kind}`)})}),(0,r.jsx)("g",{className:vW().nodes,children:[...w.placed.values()].map(({node:e,x:n,y:s,column:a})=>{let i=w.neighbours.get(e.id)?.length??0,c=0===a?w.leftLabel:w.rightLabel,d="request"===e.kind?[`#${x.get(e.id)??""}`]:"memory"===e.kind?function(e,t,n=2){if(t<24)return[];let r=[],s="",a=0;for(let i of e.trim()){let e=v6(i);if(a+e>t){if(r.length===n-1)return r.push(`${s.slice(0,-1).trimEnd()}…`),r;let e=s.lastIndexOf(" "),t=e>0?s.slice(0,e):s;r.push(t),a=[...s=s.slice(t.length).trimStart()].reduce((e,t)=>e+v6(t),0)}s+=i,a+=e}return s&&r.push(s),r}(vq(e.label),c):[function(e,t){let n=[...e];if(n.reduce((e,t)=>e+v6(t),0)<=t)return e;let r=v6("…"),s=n.length;for(;s>0&&r+v6(n[s-1])<=t;)s-=1,r+=v6(n[s]);return`…${n.slice(s).join("")}`}(e.title,c)],u=k.get(e.id),h=w.rowH-4,p=0===a?-11:11*(2===a);return(0,r.jsxs)("g",{className:vW().node,"data-kind":e.kind,"data-on":C?.has(e.id)?"true":void 0,"data-dim":N&&!N.has(e.id)?"true":void 0,"data-current":e.id===v_(t.request.entryId)?"true":void 0,"data-verdict":u,"data-edited":e.edited?"true":void 0,transform:`translate(${n},${s})`,tabIndex:0,role:"button","aria-label":o("memoryTrace.nodeLabel",{kind:I(e),label:"memory"===e.kind?vK(e.title):e.title,count:i}),onPointerEnter:()=>f(e.id),onFocus:()=>f(e.id),onBlur:()=>f(null),onClick:()=>l(e),onKeyDown:t=>{("Enter"===t.key||" "===t.key)&&(t.preventDefault(),l(e))},children:[(0,r.jsx)("title",{children:"request"===e.kind?vB(e.title):"memory"===e.kind?vK(e.title):e.title}),(0,r.jsx)("rect",{className:vW().hit,x:0===a?-11-c-4:1===a?-24:-9,y:-h/2,width:1===a?48:c+10+6+8,height:h}),u&&(0,r.jsx)("circle",{className:vW().ring,r:8}),(0,r.jsx)("g",{className:vW().mark,children:(0,r.jsx)(v3,{kind:e.kind})}),(0,r.jsx)("text",{className:vW().nodeText,x:p,y:4-(d.length-1)*14/2,textAnchor:0===a?"end":2===a?"start":"middle",children:d.map((e,t)=>(0,r.jsx)("tspan",{x:p,dy:14*(0!==t),children:e},t))})]},e.id)})})]})})]})}function v9({cwd:e,onOpenFile:t}){let n,{t:a}=(0,F.s)(),[i,l]=(0,s.useState)(null);(0,s.useEffect)(()=>{if(!e)return;let t=new AbortController;return fetch(`/api/project-docs?cwd=${encodeURIComponent(e)}`,{signal:t.signal}).then(async n=>{let r=await n.json();t.signal.aborted||(403===n.status?l({kind:"denied",cwd:e}):n.ok?l({kind:"ready",cwd:e,docs:r}):l({kind:"error",cwd:e,message:r.error??`HTTP ${n.status}`}))}).catch(n=>{t.signal.aborted||l({kind:"error",cwd:e,message:n instanceof Error?n.message:String(n)})}),()=>t.abort()},[e]);let o=e&&i?.cwd===e?i:null,c=(e,n,s)=>(0,r.jsx)("li",{className:"file-doc-shortcuts-item",children:"found"===s.state&&s.path?(0,r.jsxs)("button",{type:"button",className:"file-doc-shortcuts-link",title:s.path,"aria-label":`${e} — ${s.path}`,onClick:()=>t(s.path),children:[(0,r.jsx)("span",{className:"file-doc-shortcuts-label",children:e}),(0,r.jsx)("span",{className:"file-doc-shortcuts-file",children:n})]}):(0,r.jsxs)("div",{className:"file-doc-shortcuts-unavailable",title:s.path??void 0,children:[(0,r.jsx)("span",{className:"file-doc-shortcuts-label",children:e}),(0,r.jsx)("span",{className:"file-doc-shortcuts-file",children:"denied"===s.state?a("files.docs.denied",{file:n}):a("files.docs.missing",{file:n})})]})});if(e)if(o)if("denied"===o.kind)n=(0,r.jsx)("p",{className:"file-doc-shortcuts-status",children:a("files.docs.projectDenied")});else if("error"===o.kind)n=(0,r.jsx)("p",{className:"file-doc-shortcuts-status",role:"alert",children:a("files.docs.loadFailed",{error:o.message})});else{let{docs:e}=o,s="missing"===e.handoff.state&&"missing"===e.docMap.state&&"missing"===e.history.state;n=(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("p",{className:"file-doc-shortcuts-project",title:e.projectDir,children:a("files.docs.projectDir",{path:e.projectDir})}),s?(0,r.jsx)("p",{className:"file-doc-shortcuts-status",children:a("files.docs.noneFound")}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("ul",{className:"file-doc-shortcuts-list",children:[c(a("files.docs.current"),"HANDOFF.md",e.handoff),c(a("files.docs.map"),"doc/README.md",e.docMap)]}),(0,r.jsx)("h3",{className:"file-doc-shortcuts-heading",id:"file-doc-shortcuts-records",children:a("files.docs.records")}),e.history.records.length>0?(0,r.jsx)("ul",{className:"file-doc-shortcuts-list","aria-labelledby":"file-doc-shortcuts-records",children:e.history.records.map(e=>(0,r.jsx)("li",{className:"file-doc-shortcuts-item",children:(0,r.jsxs)("button",{type:"button",className:"file-doc-shortcuts-link",title:e.path,"aria-label":`${a("files.docs.records")} ${e.date} ${e.topic} — ${e.fileName}`,onClick:()=>t(e.path),children:[(0,r.jsx)("span",{className:"file-doc-shortcuts-date",children:e.date}),(0,r.jsxs)("span",{className:"file-doc-shortcuts-file",children:[e.topic,"main.md"===e.fileName?"":` \xb7 ${e.fileName}`]})]})},e.path))}):(0,r.jsx)("p",{className:"file-doc-shortcuts-status",children:"denied"===e.history.state?a("files.docs.denied",{file:"doc/history"}):a("files.docs.missing",{file:"doc/history"})})]})]})}else n=(0,r.jsx)("p",{className:"file-doc-shortcuts-status",role:"status",children:a("files.docs.loading")});else n=(0,r.jsx)("p",{className:"file-doc-shortcuts-status",children:a("files.docs.noProject")});return(0,r.jsxs)("section",{className:"file-doc-shortcuts","aria-labelledby":"file-doc-shortcuts-title",children:[(0,r.jsx)("h2",{className:"file-doc-shortcuts-title",id:"file-doc-shortcuts-title",children:a("files.noneOpen")}),n]})}var ye=n(58153),yt=n.n(ye);let yn={modified:yt().toneModified,added:yt().toneAdded,untracked:yt().toneAdded,deleted:yt().toneDeleted,conflict:yt().toneDeleted,renamed:yt().toneRenamed};async function yr(e,t){let n=await fetch(e,{signal:t,cache:"no-store"});if(!n.ok)throw Error(`${e} ${n.status}`);return await n.json()}function ys({value:e,className:t}){return(0,r.jsx)("span",{className:`${yt().pathText}${t?` ${t}`:""}`,dir:"rtl",title:e,children:(0,r.jsx)("bdi",{dir:"ltr",children:e})})}function ya({hidden:e,onShowAll:t}){return e<=0?null:(0,r.jsx)("li",{children:(0,r.jsxs)("button",{type:"button",className:`${yt().row} ${yt().rowButton} ${yt().more}`,"aria-expanded":!1,onClick:t,children:["+",e]})})}function yi({count:e}){return(0,r.jsx)("ul",{className:yt().list,"aria-hidden":"true",children:Array.from({length:e},(e,t)=>(0,r.jsx)("li",{className:yt().skeletonRow},t))})}function yl({cwd:e,onOpenFile:t}){let{t:n,locale:a}=(0,F.s)(),[i,l]=(0,s.useState)(null),[o,c]=(0,s.useState)(null),[d,u]=(0,s.useState)(null),h=d===e;(0,s.useEffect)(()=>{let t=null,n=encodeURIComponent(e),r=()=>{t?.abort();let r=new AbortController;t=r;let{signal:s}=r;Promise.all([yr(`/api/git/summary?cwd=${n}`,s),yr(`/api/git/status?cwd=${n}`,s)]).then(([t,n])=>{s.aborted||l({cwd:e,value:("object"==typeof t&&null!==t&&"isGitRepository"in t&&"boolean"==typeof t.isGitRepository&&"commits"in t&&Array.isArray(t.commits)&&"object"==typeof n&&null!==n&&"files"in n&&Array.isArray(n.files)?{summary:t,status:n}:null)??"failed"})},()=>{s.aborted||l({cwd:e,value:"failed"})}),yr(`/api/files/${tV(e)}?type=list`,s).then(t=>{s.aborted||c({cwd:e,value:("object"==typeof t&&null!==t&&"entries"in t&&Array.isArray(t.entries)?t.entries.flatMap(e=>"object"==typeof e&&null!==e&&"name"in e&&"string"==typeof e.name?[{name:e.name,isDir:"isDir"in e&&!0===e.isDir}]:[]):null)??"failed"})},()=>{s.aborted||c({cwd:e,value:"failed"})})};return r(),window.addEventListener("focus",r),()=>{window.removeEventListener("focus",r),t?.abort()}},[e]);let p=i?.cwd===e?i.value:null,m=o?.cwd===e?o.value:null,f=null===p||null===m;return(0,r.jsxs)("section",{className:yt().root,"aria-label":n("projectOverview.title"),"aria-busy":f||void 0,children:[(0,r.jsxs)("header",{className:yt().identity,children:[(0,r.jsx)("h2",{className:yt().name,children:tK(e)||e}),(0,r.jsx)(ys,{value:e,className:yt().cwd})]}),null===p?(0,r.jsx)("div",{className:yt().group,children:(0,r.jsx)(yi,{count:3})}):"failed"===p?(0,r.jsx)("p",{className:yt().note,role:"status",children:n("projectOverview.loadFailed")}):p.summary.isGitRepository?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(yo,{summary:p.summary}),(0,r.jsx)(yc,{cwd:e,files:p.status.files,onOpenFile:t},e),p.summary.commits.length>0&&(0,r.jsxs)("div",{className:yt().group,children:[(0,r.jsx)("h3",{className:yt().heading,children:n("projectOverview.recentCommits")}),(0,r.jsx)("ul",{className:`${yt().list} ${yt().commitList}`,children:p.summary.commits.map(e=>(0,r.jsxs)("li",{className:yt().commitRow,children:[(0,r.jsx)("span",{className:yt().hash,children:e.shortHash}),(0,r.jsx)("time",{className:yt().when,dateTime:e.committedAt,title:new Date(e.committedAt).toLocaleString(a),children:(0,et.fw)(e.committedAt,a)}),(0,r.jsx)("span",{className:yt().subject,title:e.subject,children:e.subject})]},e.hash))})]})]}):(0,r.jsx)("p",{className:yt().note,children:n("projectOverview.notGit")}),(0,r.jsxs)("div",{className:yt().group,children:[(0,r.jsx)("h3",{className:yt().heading,children:n("projectOverview.files")}),null===m?(0,r.jsx)(yi,{count:4}):"failed"===m?(0,r.jsx)("p",{className:yt().note,role:"status",children:n("projectOverview.loadFailed")}):(0,r.jsxs)("ul",{className:yt().list,children:[(h?m:m.slice(0,40)).map(n=>(0,r.jsx)("li",{children:n.isDir?(0,r.jsx)("span",{className:`${yt().row} ${yt().dirRow}`,children:(0,r.jsxs)("span",{className:yt().entryName,children:[n.name,"/"]})}):(0,r.jsx)("button",{type:"button",className:`${yt().row} ${yt().rowButton}`,onClick:()=>{var r;return t((r=n.name,`${tq(e).replace(/\/+$/,"")}/${r}`))},children:(0,r.jsx)("span",{className:yt().entryName,children:n.name})})},n.name)),!h&&(0,r.jsx)(ya,{hidden:m.length-40,onShowAll:()=>u(e)})]})]})]})}function yo({summary:e}){let{t}=(0,F.s)(),n=[];!e.detached&&(e.upstream?0===e.ahead&&0===e.behind?n.push(t("projectOverview.inSync")):(e.ahead&&n.push(t("projectOverview.ahead",{count:e.ahead})),e.behind&&n.push(t("projectOverview.behind",{count:e.behind}))):n.push(t("projectOverview.noUpstream")));let s=!!(e.ahead||e.behind);return(0,r.jsxs)("div",{className:yt().group,children:[(0,r.jsx)("h3",{className:yt().heading,children:t("projectOverview.branch")}),(0,r.jsxs)("p",{className:yt().branchLine,children:[(0,r.jsx)("span",{className:yt().branchName,children:e.detached?t("projectOverview.detachedHead"):e.branch}),e.upstream&&(0,r.jsx)("span",{className:yt().upstream,children:e.upstream})]}),n.length>0&&(0,r.jsx)("p",{className:`${yt().sync}${s?` ${yt().syncPending}`:""}`,children:n.map(e=>(0,r.jsx)("span",{children:e},e))})]})}function yc({cwd:e,files:t,onOpenFile:n}){let{t:a}=(0,F.s)(),[i,l]=(0,s.useState)(!1);return(0,r.jsxs)("div",{className:yt().group,children:[(0,r.jsxs)("h3",{className:yt().heading,children:[a("projectOverview.changes"),t.length>0&&(0,r.jsx)("span",{className:yt().count,children:t.length})]}),0===t.length?(0,r.jsx)("p",{className:yt().note,children:a("projectOverview.noChanges")}):(0,r.jsxs)("ul",{className:yt().list,children:[(i?t:t.slice(0,30)).map(t=>{var s;let a,i,l=(s=t.filePath,a=tq(e).replace(/\/+$/,""),(i=tq(s)).startsWith(`${a}/`)?i.slice(a.length+1):i),o=(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{className:`${yt().code} ${yn[t.status]}`,children:t.code}),(0,r.jsx)(ys,{value:l})]});return(0,r.jsx)("li",{children:"deleted"===t.status?(0,r.jsx)("span",{className:`${yt().row} ${yt().deletedRow}`,children:o}):(0,r.jsx)("button",{type:"button",className:`${yt().row} ${yt().rowButton}`,onClick:()=>n(t.filePath),children:o})},t.filePath)}),!i&&(0,r.jsx)(ya,{hidden:t.length-30,onShowAll:()=>l(!0)})]})]})}function yd(e){return"message"===e.type&&"message"in e}function yu(e){let t=e,n=t.branchPreview,r=yd(t.entry)?t.entry:null,s=t.compressedEntryIds?.length??0;for(;1===t.children.length;)t=t.children[0],n??=t.branchPreview,!r&&yd(t.entry)&&(r=t.entry),s+=1+(t.compressedEntryIds?.length??0);return{node:t,skipped:s,branchPreview:n,labelEntry:r??t.entry}}function yh({node:e,activePathIds:t,depth:n,isLast:s,parentLines:a,onSelect:i}){let{node:l,skipped:o,branchPreview:c,labelEntry:d}=yu(e),u=t.has(l.entry.id),h=t.has(e.entry.id)||t.has(l.entry.id),p=c?.text??function(e){if("message"===e.type&&"message"in e){let t=e.message,n=t.content,r="";if("string"==typeof n?r=n:Array.isArray(n)&&(r=n.filter(e=>"text"===e.type).map(e=>e.text).join(" ")),r.length>40&&(r=r.slice(0,40)+"…"),r)return r;if("assistant"===t.role)return"[assistant]"}return e.type}(d),m=c?c.role??null:yd(d)?d.message.role:null;return(0,r.jsxs)("div",{children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",height:24,cursor:"pointer"},onClick:()=>i(l.entry.id),children:[a.map((e,t)=>(0,r.jsx)("div",{style:{width:16,flexShrink:0}},t)),(0,r.jsx)("div",{style:{width:16,flexShrink:0}}),(0,r.jsx)("div",{style:{width:7,height:7,borderRadius:"50%",flexShrink:0,background:u?"var(--accent)":h?"var(--text-muted)":"var(--text-dim)",marginRight:6,transition:"background 0.12s"}}),m&&(0,r.jsx)("span",{style:{fontSize:9,fontFamily:"var(--font-mono)",color:"user"===m?"var(--accent)":"var(--text-dim)",background:"user"===m?"color-mix(in srgb, var(--accent) 16%, var(--bg-panel))":"var(--bg-hover)",borderRadius:"var(--radius-control)",padding:"0 4px",marginRight:5,flexShrink:0,lineHeight:"16px"},children:"user"===m?"U":"A"}),o>0&&(0,r.jsxs)("span",{style:{fontSize:10,color:"var(--text-dim)",marginRight:5,flexShrink:0},children:["+",o]}),(0,r.jsx)("span",{style:{fontSize:11,color:u?"var(--text)":h?"var(--text-muted)":"var(--text-dim)",fontWeight:u?500:400,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",flex:1,minWidth:0},children:p})]}),l.children.map((e,o)=>(0,r.jsx)(yh,{node:e,activePathIds:t,depth:n+1,isLast:o===l.children.length-1,parentLines:[...a,!s],onSelect:i},e.entry.id))]})}function yp({tree:e,activeLeafId:t,onLeafChange:n,hasSession:a}){let{t:i}=(0,F.s)(),l=(0,s.useMemo)(()=>t?new Set(function e(n,r){for(let s of n){let n=[...r,s.entry.id];if(s.entry.id===t||s.compressedEntryIds?.includes(t))return n;let a=e(s.children,n);if(a)return a}return null}(e,[])??[]):new Set,[e,t]),o=(0,s.useCallback)(e=>{n(e)},[n]),c=a?!function e(t){if(t.length>1)return!0;for(let n of t)if(n.children.length>1||e(n.children))return!0;return!1}(e)?i("i18n.noBranches"):null:i("i18n.noActiveSession"),d=function(e){if(e.length>1)return e;if(0===e.length)return[];let t=yu(e[0]).node;return t.children.length>1?t.children:[]}(e);return!c&&d.length>0?(0,r.jsx)("div",{className:"branch-navigator-tree",children:d.map((e,t)=>(0,r.jsx)(yh,{node:e,activePathIds:l,depth:0,isLast:t===d.length-1,parentLines:[],onSelect:o},e.entry.id))}):(0,r.jsx)("p",{className:"branch-navigator-empty",children:c??i("i18n.noBranches")})}function ym(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(0)}k`:String(e)}function yf(e,t,n){let r=Number.isFinite(e)?e:t,s=Math.max(t,n);return Math.round(Math.max(t,Math.min(s,r)))}function yg(e){return e>=1800?440:372}let yx=[80,100,120];function yv(e,t){return Math.ceil(e*t.charWidth+t.chrome-1e-6)}function yy(e){let t=getComputedStyle(e);return e.clientWidth-(Number.parseFloat(t.paddingLeft)||0)-(Number.parseFloat(t.paddingRight)||0)}function yb(e,t){try{window.localStorage.setItem(e,String(t))}catch{}}function yw(e){let{ariaLabel:t,cssVariable:n,defaultWidth:r,followDefault:a=!1,formatValueText:i,getDefaultWidth:l,getMaxWidth:o,growthDirection:c,maxWidth:d,minWidth:u,onLiveWidth:h,snapWidth:p,storageKey:m,widthRef:f}=e,g=(0,s.useRef)(null),x=(0,s.useRef)(null),v=(0,s.useRef)(!1),y=(0,s.useRef)(null),b=(0,s.useRef)(r),[w,k]=(0,s.useState)(r),[j,S]=(0,s.useState)(!1),C=(0,s.useCallback)(()=>Math.min(d,Math.max(u,o())),[o,d,u]),N=(0,s.useCallback)(e=>yf(e,u,C()),[C,u]),T=(0,s.useCallback)(e=>{f.current=e,g.current?.style.setProperty(n,`${e}px`),h?.(e)},[n,h,f]),I=(0,s.useCallback)((e,t={})=>{let{forcePersist:n=!1,persist:r=!0}=t,s=N(e),i=s!==f.current;return T(s),k(s),(a?r&&n:r&&(i||n))&&(yb(m,s),a&&(y.current=s)),b.current=y.current??s,s},[T,N,a,m,f]),M=(0,s.useCallback)(e=>{document.body.style.cursor=e.previousCursor,document.body.style.userSelect=e.previousUserSelect},[]),E=(0,s.useCallback)(e=>{let t=x.current;if(t&&t.pointerId===e){x.current=null,M(t),S(!1),I(f.current,{forcePersist:!a||f.current!==t.startWidth});try{t.target.hasPointerCapture(e)&&t.target.releasePointerCapture(e)}catch{}}},[I,a,M,f]),$=(0,s.useCallback)(e=>{if("mouse"===e.pointerType&&0!==e.button)return;e.preventDefault(),e.stopPropagation();let t=x.current;t&&E(t.pointerId);let n=e.currentTarget;n.focus({preventScroll:!0}),n.setPointerCapture(e.pointerId),x.current={pointerId:e.pointerId,startX:e.clientX,startWidth:f.current,target:n,previousCursor:document.body.style.cursor,previousUserSelect:document.body.style.userSelect},document.body.style.cursor="col-resize",document.body.style.userSelect="none",S(!0)},[E,f]),R=(0,s.useCallback)(e=>{let t=x.current;if(!t||t.pointerId!==e.pointerId)return;if("mouse"===e.pointerType&&0===e.buttons)return void E(e.pointerId);e.preventDefault();let n="right"===c?1:-1,r=N(t.startWidth+(e.clientX-t.startX)*n),s=p?N(p(r)):r;T(s),e.currentTarget.setAttribute("aria-valuenow",String(s)),e.currentTarget.setAttribute("aria-valuetext",i?.(s)??`${s} px`)},[T,N,E,i,c,p]),L=(0,s.useCallback)(e=>{E(e.pointerId)},[E]),P=(0,s.useCallback)(e=>{E(e.pointerId)},[E]),A=(0,s.useCallback)(e=>{E(e.pointerId)},[E]),_=(0,s.useCallback)(()=>{let e=l?.()??r;if(a){y.current=null;try{window.localStorage.removeItem(m)}catch{}I(e);return}I(e,{forcePersist:!0})},[I,r,a,l,m]),F=(0,s.useCallback)(()=>{a?I(y.current??l?.()??r):I(f.current)},[I,r,a,l,f]),O=(0,s.useCallback)(e=>{let t=e.shiftKey?32:12,n="right"===c?"ArrowRight":"ArrowLeft",r="right"===c?"ArrowLeft":"ArrowRight";e.key===n?(e.preventDefault(),I(f.current+t,{forcePersist:!0})):e.key===r?(e.preventDefault(),I(f.current-t,{forcePersist:!0})):"Home"===e.key?(e.preventDefault(),I(u,{forcePersist:!0})):"End"===e.key?(e.preventDefault(),I(C(),{forcePersist:!0})):"Enter"===e.key&&(e.preventDefault(),_())},[I,C,c,u,_,f]);return(0,s.useEffect)(()=>{if(v.current)return;v.current=!0;let e=function(e){try{let t=window.localStorage.getItem(e);if(null===t)return null;let n=Number.parseInt(t,10);return Number.isFinite(n)?n:null}catch{return null}}(m);a&&(y.current=e);let t=I(e??l?.()??r,{persist:!1});a||null!==e&&e!==t&&yb(m,t)},[I,r,a,l,m]),(0,s.useEffect)(()=>{if(v.current)return I(b.current),window.addEventListener("resize",F),()=>window.removeEventListener("resize",F)},[I,F]),(0,s.useEffect)(()=>{if(!j)return;let e=()=>{let e=x.current;e&&E(e.pointerId)},t=()=>{"visible"!==document.visibilityState&&e()};return window.addEventListener("blur",e),document.addEventListener("visibilitychange",t),()=>{window.removeEventListener("blur",e),document.removeEventListener("visibilitychange",t)}},[E,j]),(0,s.useEffect)(()=>()=>{let e=x.current;e&&(x.current=null,M(e))},[M]),{isResizing:j,panelRef:g,reclampWidth:F,resetWidth:_,setPanelWidth:I,separatorProps:{"aria-label":t,"aria-orientation":"vertical","aria-valuemax":C(),"aria-valuemin":u,"aria-valuenow":w,"aria-valuetext":i?.(w)??`${w} px`,onDoubleClick:_,onKeyDown:O,onLostPointerCapture:A,onPointerCancel:P,onPointerDown:$,onPointerMove:R,onPointerUp:L,role:"separator",tabIndex:0},width:w}}function yk(e){let t=e.currentTime;[523.25,659.25].forEach((n,r)=>{let s=e.createOscillator(),a=e.createGain();s.connect(a),a.connect(e.destination),s.type="sine",s.frequency.value=n;let i=t+.18*r;a.gain.setValueAtTime(0,i),a.gain.linearRampToValueAtTime(.18,i+.02),a.gain.exponentialRampToValueAtTime(.001,i+.45),s.start(i),s.stop(i+.45)})}async function yj(e){let t=await fetch(e);if(!t.ok)throw Error(`HTTP ${t.status}`);return t.arrayBuffer()}function yS(e){let t=e.window?.durationMs;if("number"==typeof t&&Number.isFinite(t)&&t>0)return t>=5184e5?"weekly":t<=432e5?"short":"other";let n=e.scope?.windowId,r=`${"string"==typeof n?n:""} ${e.id} ${e.label??""}`.toLowerCase();return/(^|[^0-9])7d\b|week|7 day|주간/.test(r)?"weekly":/(^|[^0-9])(5h|1h)\b|hour|시간/.test(r)?"short":"other"}let yC="omp-sidebar-usage-collapsed",yN="omp-sidebar-usage-order";function yT(e){let t=e.amount?.usedFraction;return"number"==typeof t&&Number.isFinite(t)?t:null}function yI({direction:e}){return(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",children:(0,r.jsx)("polyline",{points:"up"===e?"2.5 7.5 6 4 9.5 7.5":"2.5 4.5 6 8 9.5 4.5"})})}function yM({usage:e,onOpen:t,onRelogin:n}){var a;let i,l,o,c,{t:d}=(0,F.s)(),u=U(),[h,p]=(0,s.useState)(!1),[m,f]=(0,s.useState)(!1),[g,x]=(0,s.useState)([]),[v,y]=(0,s.useState)(""),[b,w]=(0,s.useState)(null),k=(0,s.useRef)(null),[j,S]=(0,s.useState)(!0);(0,s.useEffect)(()=>{try{S("0"!==window.localStorage.getItem(yC))}catch{}x(function(){try{let e=JSON.parse(window.localStorage.getItem(yN)??"[]");return Array.isArray(e)?e.filter(e=>"string"==typeof e):[]}catch{return[]}}())},[]);let C=e.state.data?.reports??[],N=nG(1e4),T=(i=si(C),l=[],o=[],C.forEach((e,t)=>{let n=e.authError;if(!0===e.disabled&&!n)return;let r=i[t],s="number"==typeof e.autoBlockedUntilMs&&e.autoBlockedUntilMs>N,a=!0===e.disabled?[]:e.limits??[],c=a.some(e=>e.scope?.shared===!0&&rO(e)),d=a.some(e=>null!==yT(e)&&"short"!==yS(e)),u=[];for(let e of a){let t=yT(e);null!==t&&(!d||"short"!==yS(e)||function(e){let t=e.amount?.usedFraction,n="number"==typeof t&&Number.isFinite(t)?Math.round(100*t):null;return rO(e)||"warning"===e.status||null!==n&&n>=90}(e))&&u.push({key:e.id,label:e.label||e.id,percent:Math.round(100*t),state:s?"blocked":c?"account-spent":rO(e)?"spent":"usable"})}if(0===u.length&&!n)return;let h=n?"auth":s?"blocked":c?"account-spent":"ok",p={orderKey:"string"==typeof e.accountKey&&e.accountKey.length>0?`${e.provider}:${e.accountKey}`:void 0!==e.credentialId?`${e.provider}:#${e.credentialId}`:`${e.provider}:@${t}`,provider:e.provider,alias:r.alias,seed:r.seed,masked:r.masked,..."string"==typeof e.accountKey?{accountKey:e.accountKey}:{},rows:u,state:h,...n?{authError:n}:{},usable:"ok"===h&&u.some(e=>"usable"===e.state)};(p.usable?l:o).push(p)}),a=[...l,...o],c=new Map(g.map((e,t)=>[e,t])),[...a.filter(e=>c.has(e.orderKey)).sort((e,t)=>c.get(e.orderKey)-c.get(t.orderKey)),...a.filter(e=>!c.has(e.orderKey))]);(0,s.useEffect)(()=>{if(null===b)return;let e=[...k.current?.querySelectorAll("[data-order-key]")??[]].find(e=>e.dataset.orderKey===b.orderKey),t=e?.querySelector(`[data-direction="${b.direction}"]`),n=e?.querySelector(`[data-direction="${"up"===b.direction?"down":"up"}"]`);(t&&!t.disabled?t:n)?.focus(),w(null)},[b]);let I=(e,t)=>{let n,r,s,a="up"===t?e-1:e+1;if(a<0||a>=T.length)return;let i=T.map(e=>e.orderKey);[i[e],i[a]]=[i[a],i[e]];let l=(n=new Set(i),r=[...g,...i.filter(e=>!g.includes(e))],s=0,r.map(e=>n.has(e)?i[s++]:e));x(l);try{window.localStorage.setItem(yN,JSON.stringify(l))}catch{}y(d("usage.moved",{account:T[e].alias,position:a+1})),w({orderKey:T[e].orderKey,direction:t})},M=e=>Math.max(1,e.rows.length),E=0,$=h||m?T:T.filter(e=>!(E>=2)&&(E+=M(e),!0)),R=T.slice($.length).reduce((e,t)=>e+M(t),0),L=T.filter(e=>"auth"===e.state).length,P=e=>"auth"===e.state?d(e.authError?.reloginRequired?"usage.authExpired":"usage.authUnavailable"):"blocked"===e.state?d("usage.accountBlocked"):"account-spent"===e.state?d("usage.accountSpent"):null,A=e=>"spent"===e.state?d("usage.limitSpent"):null,_=d("usage.open",{rows:[...$.flatMap(e=>{let t=P(e);return 0===e.rows.length?[`${e.alias} (${t??""}${e.authError?`: ${e.authError.message}`:""})`]:e.rows.map(n=>{let r=A(n)??t;return`${e.alias} ${n.label} ${n.percent}%${null===r?"":` (${r})`}`})})].join(", ")})+(R>0?d("usage.openMore",{count:R}):""),O=T[0],z=void 0===O?{label:d("usage.none"),value:"",danger:!1}:0===O.rows.length?{label:O.alias,value:P(O)??"",danger:!0}:{label:O.rows[0].label,value:`${O.rows[0].percent}%`,danger:O.rows[0].percent>=90},D=L>0?d("usage.authIssues",{count:L}):null,W=(0,r.jsxs)("div",{className:"navigator-usage",role:"group","aria-label":d("usage.title"),"data-editing":m?"":void 0,onClick:e=>{m||e.target instanceof Element&&e.target.closest("button, a")||t()},children:[(0,r.jsxs)("span",{className:"navigator-usage-header",children:[(0,r.jsx)("button",{type:"button",className:"navigator-usage-open","aria-label":_,onClick:t,children:d("usage.title")}),null===D?null:(0,r.jsx)("span",{className:"navigator-usage-alert",children:D}),T.length>1&&(0,r.jsx)("button",{type:"button",className:"navigator-usage-edit","data-active":m?"":void 0,onClick:()=>f(e=>!e),children:m?d("usage.reorderDone"):d("usage.reorder")})]}),(0,r.jsx)("div",{ref:k,role:m?"list":void 0,"aria-label":m?d("usage.reorderGroup"):void 0,className:"navigator-usage-groups",children:0===T.length?(0,r.jsx)("span",{className:"navigator-usage-empty",children:d("usage.none")}):$.map((e,t)=>{let s=P(e);return(0,r.jsxs)("div",{className:"navigator-usage-group","data-order-key":e.orderKey,role:m?"listitem":void 0,children:[(0,r.jsxs)("span",{className:"navigator-usage-account",children:[(0,r.jsx)(sD,{seed:e.seed,size:24,provider:e.provider}),(0,r.jsx)("span",{className:"navigator-usage-alias",children:e.alias}),null===s?null:(0,r.jsx)("span",{className:"navigator-usage-state","data-tone":"auth"===e.state?"danger":void 0,children:s}),m&&(0,r.jsxs)("span",{className:"navigator-usage-moves",children:[(0,r.jsx)("button",{type:"button",className:"navigator-usage-move","data-direction":"up","aria-label":d("usage.moveUp",{account:e.alias}),disabled:0===t,onClick:()=>I(t,"up"),children:(0,r.jsx)(yI,{direction:"up"})}),(0,r.jsx)("button",{type:"button",className:"navigator-usage-move","data-direction":"down","aria-label":d("usage.moveDown",{account:e.alias}),disabled:t===T.length-1,onClick:()=>I(t,"down"),children:(0,r.jsx)(yI,{direction:"down"})})]})]}),e.authError&&(0,r.jsxs)("span",{className:"navigator-usage-auth",children:[(0,r.jsx)("span",{className:"navigator-usage-reason",children:e.authError.message}),e.authError.reloginRequired&&n&&!m&&(0,r.jsx)("button",{type:"button",className:"navigator-usage-relogin","aria-label":d("usage.reloginFor",{account:e.alias}),onClick:()=>n({provider:e.provider,alias:e.alias,seed:e.seed,masked:e.masked,...e.accountKey?{accountKey:e.accountKey}:{},reason:e.authError?.message??""}),children:d("usage.relogin")})]}),e.rows.map(e=>{let t=A(e);return(0,r.jsxs)("span",{className:"navigator-usage-row",children:[(0,r.jsxs)("span",{className:"navigator-usage-head",children:[(0,r.jsx)("span",{className:"navigator-usage-label",children:e.label}),null===t?null:(0,r.jsx)("span",{className:"navigator-usage-state",children:t}),(0,r.jsxs)("span",{className:"navigator-usage-value",style:e.percent>=90?{color:"var(--danger)"}:void 0,children:[e.percent,"%"]})]}),(0,r.jsx)("span",{"aria-hidden":"true",className:"navigator-usage-track",children:(0,r.jsx)("span",{className:"navigator-usage-fill",style:{width:`${Math.max(0,Math.min(100,e.percent))}%`,background:e.percent>=90?"var(--danger)":"var(--metric)"}})})]},e.key)})]},e.orderKey)})}),!m&&(R>0||h)&&(0,r.jsx)("button",{type:"button",className:"navigator-usage-more","aria-expanded":h,onClick:()=>p(e=>!e),children:h?d("usage.showLess"):d("usage.showMore",{count:R})}),(0,r.jsx)("span",{className:"navigator-usage-live","aria-live":"polite",children:v})]});return u?(0,r.jsxs)("div",{className:"navigator-usage-shell",children:[(0,r.jsxs)("button",{type:"button",className:"navigator-usage-toggle","aria-expanded":!j,"aria-label":j?`${_}${null===D?"":`, ${D}`}`:d("usage.showLess"),onClick:()=>{let e=!j;S(e);try{window.localStorage.setItem(yC,e?"1":"0")}catch{}},children:[(0,r.jsx)("span",{className:"navigator-usage-label",children:j?z.label:d("usage.showLess")}),j&&(0,r.jsx)("span",{className:"navigator-usage-value",style:z.danger?{color:"var(--danger)"}:void 0,children:z.value}),j&&null!==D&&(0,r.jsx)("span",{className:"navigator-usage-alert",children:D}),(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:{flexShrink:0,transform:j?"rotate(0deg)":"rotate(180deg)"},children:(0,r.jsx)("polyline",{points:"2.5 4 6 7.5 9.5 4"})})]}),j?null:W]}):W}let yE=["casual","polite","formal","haggling","urgent"],y$=["male","female"],yR=["20s","30s","40s","50s","60s"],yL=["child","younger","older","parent","grandparent"],yP=["ja","th","vi"];function yA(e,t,n){if(!e||"object"!=typeof e)return{};let r=(e,t)=>"string"==typeof e&&e.trim()&&e.length<=t?e.replace(/\s+/g," ").trim():void 0,s={};if("theirs"===n){if(t.nuance){let t=r(e.nuance,240);t&&(s.nuance=t)}}else if(t.check){let t=r(e.warning,300),n=r(e.backTranslation,8e3);t&&(s.warning=t),n&&(s.backTranslation=n)}return s}let y_=(e,t)=>"string"==typeof t&&e.includes(t)?t:void 0;function yF(e){if(!e||"object"!=typeof e)return{};let t={},n=y_(yE,e.mood),r=y_(y$,e.gender),s=y_(yR,e.age),a=y_(y$,e.partnerGender),i=y_(yL,e.partnerAge);return n&&(t.mood=n),r&&(t.gender=r),s&&(t.age=s),a&&(t.partnerGender=a),i&&(t.partnerAge=i),t}let yO=[{code:"ko",tag:"ko-KR",englishName:"Korean",nativeName:"한국어"},{code:"en",tag:"en-US",englishName:"English",nativeName:"English"},{code:"vi",tag:"vi-VN",englishName:"Vietnamese",nativeName:"Tiếng Việt"},{code:"ja",tag:"ja-JP",englishName:"Japanese",nativeName:"日本語"},{code:"th",tag:"th-TH",englishName:"Thai",nativeName:"ไทย"},{code:"zh",tag:"zh-CN",englishName:"Chinese",nativeName:"中文"},{code:"zh-tw",tag:"zh-TW",englishName:"Traditional Chinese (Taiwan)",nativeName:"中文(台灣)"}];function yz(e){return"zh"===e||"zh-tw"===e}function yD(e){return"string"==typeof e?yO.find(t=>t.code===e):void 0}let yW={ko:{ko:"한국어",en:"영어",vi:"베트남어",ja:"일본어",th:"태국어",zh:"중국어","zh-tw":"중국어(대만 번체)"},en:{ko:"Korean",en:"English",vi:"Vietnamese",ja:"Japanese",th:"Thai",zh:"Chinese","zh-tw":"Traditional Chinese (Taiwan)"},vi:{ko:"tiếng H\xe0n",en:"tiếng Anh",vi:"tiếng Việt",ja:"tiếng Nhật",th:"tiếng Th\xe1i",zh:"tiếng Trung","zh-tw":"tiếng Trung phồn thể (Đ\xe0i Loan)"},ja:{ko:"韓国語",en:"英語",vi:"ベトナム語",ja:"日本語",th:"タイ語",zh:"中国語","zh-tw":"中国語(台湾・繁体字)"},th:{ko:"ภาษาเกาหลี",en:"ภาษาอังกฤษ",vi:"ภาษาเวียดนาม",ja:"ภาษาญี่ปุ่น",th:"ภาษาไทย",zh:"ภาษาจีน","zh-tw":"ภาษาจีนตัวเต็ม (ไต้หวัน)"},zh:{ko:"韩语",en:"英语",vi:"越南语",ja:"日语",th:"泰语",zh:"中文","zh-tw":"中文(台湾繁体)"},"zh-tw":{ko:"韓語",en:"英語",vi:"越南語",ja:"日語",th:"泰語",zh:"中文(簡體)","zh-tw":"中文(台灣)"}},yH={ko:e=>`말씀하시면 ${e}로 옮겨 드려요.`,en:e=>`Go ahead and speak. I'll interpret it into ${e} for you.`,vi:e=>`Bạn cứ n\xf3i, t\xf4i sẽ dịch sang ${e} cho bạn.`,ja:e=>`話しかけてください。${e}に通訳します。`,th:e=>`พูดได้เลย ระบบจะแปลเป็น${e}ให้`,zh:e=>`请直接说话,我会帮您翻译成${e}。`,"zh-tw":e=>`請直接說話,我會幫您翻譯成${e}。`},yU=/[ăâđêôơưàáạảãằắặẳẵầấậẩẫèéẹẻẽềếệểễìíịỉĩòóọỏõồốộổỗờớợởỡùúụủũừứựửữỳýỵỷỹ]/giu,yB=/[\u3040-\u30ff\u31f0-\u31ff\uff66-\uff9d]/u,yq={ko:/[\uac00-\ud7a3\u1100-\u11ff\u3130-\u318f]/gu,ja:/[\u3040-\u30ff\u31f0-\u31ff\uff66-\uff9d\u4e00-\u9fff]/gu,zh:/[\u4e00-\u9fff]/gu,"zh-tw":/[\u4e00-\u9fff]/gu,th:/[\u0e00-\u0e7f]/gu,vi:yU,en:/[a-z]/giu};function yV(e,t,n){let r=yq[t];return!r||"en"===t&&e.match(yU)||yz(t)&&yB.test(e)||"ja"===t&&yz(n)&&!yB.test(e)?0:e.match(r)?.length??0}function yK(e,t,n){let r=yV(e,t.code,n.code),s=yV(e,n.code,t.code);if(r!==s)return r>s?t:n}let yJ=String.raw`\d(?:[\d,.:/-]*\d)?`,yG=String.raw`(?:[kK](?![A-Za-z])|%|만|억|천|백)`,yY=String.raw`(?:원|동|위안|달러|엔|바트|đồng|nghìn|ngàn|triệu|tỷ|VND|[$€£¥₩₫]|개|명|시|분|번|층|년|월|일|(?:kg|km|cm|ml|g|m)(?![A-Za-z]))`,yZ=String.raw`[$€£¥₩₫]?`,yQ=RegExp(`${yZ}${yJ}(?:\\s?${yG})*(?:\\s?${yJ}(?:\\s?${yG})+)*(?:\\s?${yY}){0,2}`,"gu");function yX(e=[],t){return{turns:{},drafts:[],seen:e.filter(e=>"assistant"===e.role).map(e=>e.id),born:{},lastSegmentId:e.reduce((e,t)=>Math.max(e,t.id),-1),nextTurnId:t?.nextTurnId??0,nextDraftId:t?.nextDraftId??0}}let y0=e=>[...e.replace(/\s/gu,"")].slice(-24).join(""),y1=e=>e.match(/[\p{L}\p{N}]/gu)?.length??0,y2=e=>e.normalize("NFD").replace(/\p{M}/gu,"").toLowerCase().replace(/[^\p{L}\p{N}]/gu,"");function y4(e,t){let n=y2(e).slice(0,400),r=y2(t);if(n.length<8||r.length<8)return 0;let s=r.slice(0,Math.min(400,n.length+Math.ceil(.15*n.length)));return 1-function(e,t){let n=Array.from({length:t.length+1},(e,t)=>t);for(let r=1;r<=e.length;r+=1){let s=[r];for(let a=1;a<=t.length;a+=1)s[a]=Math.min(n[a]+1,s[a-1]+1,n[a-1]+ +(e[r-1]!==t[a-1]));n=s}return n[t.length]}(n,s)/Math.max(n.length,s.length)}function y8({mine:e,theirs:t}){return"en"===e.code&&"vi"===t.code||"vi"===e.code&&"en"===t.code||"ja"===e.code&&yz(t.code)||"ja"===t.code&&yz(e.code)}function y5(e,t,n){if(y8(e))return!1;let r=yK(t,e.mine,e.theirs),s=yK(n,e.mine,e.theirs);return void 0!==r&&void 0!==s&&r.code!==s.code}function y6(e,t,n){return yK(n.input,e.mine,e.theirs)?.code===t.code||y4(n.output,n.input)>=.8}function y3(e,t,n,r,s){let a=r.echo||y6(t,n,r);r.echo=a;let i=e.drafts.findIndex(e=>e.language.code===n.code&&e.turnId===r.id),l=r.output.trim();if(a||r.dead){if(i<0)return e;let t=e.drafts.flatMap((e,t)=>t!==i?[e]:null===e.matched?[]:[{...e,text:""}]);return{...e,drafts:t}}if(!l||i<0&&y9(r)&&s-r.outputSince<800)return e;if(i>=0)return e.drafts[i].text===l?e:{...e,drafts:e.drafts.map((e,t)=>t===i?{...e,text:l}:e)};let o={id:e.nextDraftId,language:n,pair:t,turnId:r.id,text:l,createdAt:s,after:e.lastSegmentId,matched:null};return{...e,drafts:[...e.drafts,o],nextDraftId:e.nextDraftId+1}}function y7(e,t,n){return{...e,turns:{...e.turns,[t.code]:n.slice(-12)}}}let y9=e=>void 0===yK(e.input,e.pair.mine,e.pair.theirs),be=(e,t)=>y9(t)&&!t.echo&&!t.dead&&""!==t.output.trim()&&!e.drafts.some(e=>e.turnId===t.id&&e.language.code===t.target.code);function bt(e,t,n){let r=function(e,t){let n=e;for(let r of Object.values(e.turns))for(let e of r)be(n,e)&&t-e.outputSince>=800&&(n=y3(n,e.pair,e.target,{...e},t));return n}(e,n),s=new Set(r.seen),a={...r.born},i=r.drafts.filter(e=>null===e.matched&&n-e.createdAt>2e4),l=r.drafts.filter(e=>!i.includes(e)),o=[...i],c=!1;for(let e of t){if("assistant"!==e.role||s.has(e.id)||y1(e.text)<(e.final?4:6))continue;let t=yK(y0(e.text),e.mine,e.theirs);if(t){a[e.id]?.code!==t.code&&(a[e.id]={at:n,code:t.code},c=!0);let r=()=>l.filter(n=>null===n.matched&&n.text&&n.language.code===t.code&&n.createdAt<=a[e.id].at);for(;r().length>1&&n-r()[0].createdAt>15e3;){let e=r()[0];o.push(e),l=l.filter(t=>t!==e)}let i=r()[0];if(i){l=l.map(t=>t===i?{...i,matched:e.id}:t),s.add(e.id),c=!0;continue}}e.final&&(s.add(e.id),c=!0)}let d=new Set(t.map(e=>e.id)),u=l.filter(e=>null===e.matched?n-e.createdAt>2e4:!d.has(e.matched));o.push(...u.filter(e=>null===e.matched)),l=l.filter(e=>!u.includes(e));let h=r.turns;if(o.length>0)for(let e of(h={...h},o))h[e.language.code]=(h[e.language.code]??[]).map(t=>t.id===e.turnId?{...t,dead:!0}:t);let p=t.reduce((e,t)=>Math.max(e,t.id),r.lastSegmentId);return c||0!==o.length||0!==u.length||p!==r.lastSegmentId?{...r,turns:h,drafts:l,seen:[...s],born:a,lastSegmentId:p}:r}class bn{constructor(e,t,n){this.pair=e,this.events=t,this.streams=new Map,this.nextId=0,this.voice=n}stream(e){let t=this.streams.get(e.code);return t||(t={turns:new Set},this.streams.set(e.code,t)),t}newTurn(e,t,n){let r={id:this.nextId++,startedAt:n,target:t,input:"",output:"",final:!1,inputAt:-1/0,outputAt:-1/0,echo:!1,shown:!1};return e.turns.add(r),r}input(e,t,n){if(!t)return;let r=this.stream(e),s=r.input;if(!s?.input&&r.output&&!r.output.input&&n-r.output.outputAt<=2700&&(s=r.output),!s||s.input&&(n-s.inputAt>1500||(n-s.inputAt>600||/[.!?。!?]\s*$/u.test(s.input))&&y5(this.pair,s.input,t))){if(!t.trim())return;s=this.newTurn(r,e,n)}r.input=s,s.input+=t,s.inputAt=n,s.source=yK(s.input,this.pair.mine,this.pair.theirs);let a=r.unattributed;a&&n-a.outputAt<=5400&&s.source?.code===e.code&&y4(a.output,s.input)>=.8&&(this.events.remove(a.id),r.unattributed=void 0),this.update(s,n);let i=r.audio;if(!i||i.blocked||n-i.at>1200){r.nextAudioInput=s;return}if(i.turn&&i.turn!==s&&(!s.source||i.turn.source?.code!==s.source.code)){r.nextAudioInput=s,i.blocked=!0,i.held.length=i.samples=0;return}if(i.turn=s,s.echo||s.source){if(!s.echo&&s.source?.code!==e.code)for(let e of i.held)n-e.at<=2700&&this.events.play(e.pcm,s.id);i.held.length=i.samples=0}}output(e,t,n){if(!t)return;let r=this.stream(e),s=r.output,a=r.input;(!s||n-s.outputAt>1200)&&(a&&n-a.inputAt<=2700?s=a:(!s||n-s.outputAt>2700)&&(s=this.newTurn(r,e,n))),s.output+=t,s.outputAt=n,r.output=s,this.update(s,n),r.audio?.blocked&&s===a&&(r.audio=void 0)}audio(e,t,n){if(!this.voice||!t.length||y8(this.pair))return;let r=this.stream(e),s=r.audio;if(!s||n-s.at>1200){let e=r.nextAudioInput;r.nextAudioInput=void 0;let t=e&&n-e.inputAt<=2700?e:void 0;r.audio=s={at:n,turn:t,blocked:!1,held:[],samples:0}}if(s.at=n,!(s.blocked||s.turn?.echo)){if(s.turn?.source){s.turn.source.code!==e.code&&this.events.play(t,s.turn.id);return}for(;s.held.length&&(s.samples+t.length>48e3||n-s.held[0].at>2700);)s.samples-=s.held.shift().pcm.length;t.length<=48e3&&(s.held.push({pcm:t,at:n}),s.samples+=t.length)}}update(e,t){(y8(this.pair)?y4(e.output,e.input)>=.8:y6(this.pair,e.target,e))&&!e.echo&&(e.echo=!0,this.events.cancel(e.id),e.shown&&this.events.remove(e.id)),!e.echo&&(e.source||e.output.trim()&&(e.final||t-e.startedAt>=800))&&(e.shown=!0,this.events.update({id:e.id,startedAt:e.startedAt,target:e.target,source:e.source,input:e.input,output:e.output,final:e.final}))}tick(e){for(let t of this.streams.values())for(let n of(t.audio&&e-t.audio.at>1200&&(t.audio=void 0),t.unattributed&&e-t.unattributed.outputAt>5400&&(t.unattributed=void 0),t.turns))e-Math.max(n.inputAt,n.outputAt)>2700?this.finalize(t,n,e):!n.shown&&n.output.trim()&&e-n.startedAt>=800&&this.update(n,e)}finalize(e,t,n){!e.audio||e.audio.turn?.source||e.audio.turn!==t&&(e.audio.turn||e.output!==t)||(e.audio.blocked=!0,e.audio.held.length=e.audio.samples=0),t.final=!0,this.update(t,n),t.source||!t.shown||t.echo||(e.unattributed=t),e.nextAudioInput===t&&(e.nextAudioInput=void 0),e.input===t&&(e.input=void 0),e.output===t&&(e.output=void 0),e.turns.delete(t)}stop(e){for(let t of this.streams.values())for(let n of(t.audio=void 0,t.turns))this.finalize(t,n,e)}clear(){this.streams.clear(),this.events.cancel()}setVoice(e){if(this.voice=e,!e){for(let e of this.streams.values())e.audio=void 0;this.events.cancel()}}}var br=n(56018),bs=n(1164),ba=n(68459),bi=n(2467);function bl(){return{segments:[],open:{user:null,assistant:null},nextId:0,call:0}}function bo(e){return{...e,open:{user:null,assistant:null},call:e.call+1}}function bc(e){return e.language?e.language:!e.utterance||e.side?yK(e.text,e.mine,e.theirs):void 0}function bd(e){if(e.utterance)return e.side;let t=bc(e);return t?bu(e,t):void 0}function bu(e,t){if(e.side)return e.side;let n=t.code===e.mine.code;return"user"===e.role===n?"me":"them"}function bh(e,t){return e.segments.filter(e=>!e.restored&&e.text.trim()).slice(-t).map(({id:e,role:t,text:n})=>({id:e,role:t,text:n}))}let bp={worklet:"/interpreter-noise/rnnoiseWorklet.js",wasm:"/interpreter-noise/rnnoise.wasm",simdWasm:"/interpreter-noise/rnnoise_simd.wasm"};async function bm(e,t,r,s=bp){if("function"!=typeof AudioContext||"function"!=typeof AudioWorkletNode||"object"!=typeof WebAssembly)throw Error("AudioWorklet or WebAssembly is not available");if(0===e.getAudioTracks().length)throw Error("the stream has no audio track");let a=Promise.withResolvers();a.promise.catch(()=>{});let i=()=>a.reject(Error("setup cancelled"));r?.aborted?i():r?.addEventListener("abort",i,{once:!0});let l=e=>Promise.race([e,a.promise]),o=null,c=!1,d=null,u=null,h=null,p=null,m=()=>{if(c)return;c=!0;let e=o;e&&(e.onstatechange=null,u&&(u.onprocessorerror=null,u.destroy(),u.disconnect()),d?.disconnect(),h?.disconnect(),p?.stop(),"closed"!==e.state&&e.close().catch(()=>{}))};r?.addEventListener("abort",m,{once:!0});try{let a;if(r?.aborted)throw Error("setup cancelled");let i=await l(n.e(5211).then(n.bind(n,55211)));if(r?.aborted)throw Error("setup cancelled");let{RnnoiseWorkletNode:m,loadRnnoise:f}=i,g=new AudioContext({sampleRate:48e3,latencyHint:"interactive"});o=g;let[x]=await Promise.all([l(f({url:s.wasm,simdUrl:s.simdWasm},r?{signal:r}:void 0)),l(g.audioWorklet.addModule(s.worklet))]);if(c)throw Error("setup cancelled");if(a=new Uint8Array(x,0,Math.min(4,x.byteLength)),4!==a.length||0!==a[0]||97!==a[1]||115!==a[2]||109!==a[3])throw Error("the RNNoise wasm did not load");if(48e3!==g.sampleRate)throw Error(`the browser ran the context at ${g.sampleRate} Hz`);if(await l(g.resume()),"running"!==g.state||c)throw Error(`the audio context is ${g.state}`);d=g.createMediaStreamSource(e),u=new m(g,{maxChannels:2,wasmBinary:x}),h=g.createGain();let v=g.createMediaStreamDestination();if(d.connect(u),u.connect(h),h.connect(v),!(p=v.stream.getAudioTracks()[0]??null))throw Error("the audio graph produced no track");u.onprocessorerror=()=>{c||t("the RNNoise processor failed")},g.onstatechange=()=>{c||"running"===g.state||t(`the audio context is ${g.state}`)}}catch(e){throw m(),e}finally{r?.removeEventListener("abort",m),r?.removeEventListener("abort",i)}let f=h,g=!1;return{track:p,setMuted:e=>{c||e===g||(g=e,f.gain.setTargetAtTime(+!e,o.currentTime,.005))},close:m}}class bf{#f;#g;constructor(e=500){this.#g=-1/0,this.#f=e}update(e,t){return e&&(this.#g=t),t-this.#g<this.#f}reset(){this.#g=-1/0}}let bg=e=>{fetch(`/api/live/call/${encodeURIComponent(e)}`,{method:"DELETE"}).catch(()=>{})};async function bx(e,t){let n=e?.getSettings().noiseSuppression;if(e&&"boolean"==typeof n&&n!==t)try{await e.applyConstraints({echoCancellation:!0,noiseSuppression:t,autoGainControl:!0})}catch(e){console.warn("[interpreter] cannot change the browser noise suppression:",e instanceof Error?e.message:String(e))}}let bv=({mine:e,theirs:t,profile:n})=>`${e.code}>${t.code}|${n.mood??""}|${n.gender??""}|${n.age??""}|${n.partnerGender??""}|${n.partnerAge??""}`;async function by(e,t,n){let r=await fetch("/api/live/draft-secret",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({mine:e.code,theirs:t.code}),signal:n});if(!r.ok)throw Error(401===r.status?"auth":"upstream");let s=await r.json(),a=s&&"object"==typeof s&&"sessions"in s&&Array.isArray(s.sessions)?s.sessions:[],i=[];for(let n of[e,t]){let e=a.find(e=>e&&"object"==typeof e&&"language"in e&&e.language===n.code),t=e&&"object"==typeof e&&"secret"in e?e.secret:void 0;if("string"!=typeof t||!t)throw Error("the secret answer was incomplete");i.push({language:n,secret:t})}return i}function bb(e){let t,n,r,s=new AbortController,a=[],i=null,l=null,o=null,c=null,d=0,u=!1,h=!1,p=null,m=new Map,f=0,g=!1,x=!1,v=!1,y=e=>{for(let[t,n]of m)(void 0===e||n.turn===e)&&(t.stop(),m.delete(t));for(let e of(f=0,m.values()))f=Math.max(f,e.ends)},b=()=>{for(let e of a.splice(0))e.onclose=null,e.onmessage=null,e.onerror=null,(e.readyState===WebSocket.OPEN||e.readyState===WebSocket.CONNECTING)&&e.close(1e3)},w=()=>{if(o?.disconnect(),o=null,i&&l&&c)try{(o=i.createMediaStreamSource(new MediaStream([c]))).connect(l),e.fast&&"live"!==c.readyState&&C("mic-unavailable")}catch{console.warn("[interpreter] draft captions cannot read the microphone"),e.fast&&C("mic-unavailable")}},k=()=>{h=!0,y(),p?.disconnect(),p=null,t?.(),t=void 0,o?.disconnect(),o=null,l&&(l.port.onmessage=null),l?.disconnect(),l=null,i&&"closed"!==i.state&&i.close().catch(()=>{}),i=null},j=()=>{if(e.fast)return void C("upstream");if(b(),!u&&void 0===n){if(d>=2){console.warn("[interpreter] draft captions stopped; the interpretation goes on without them"),k();return}d+=1,n=window.setTimeout(()=>{n=void 0,T()},2e3)}},S=()=>{u||(u=!0,s.abort(),window.clearTimeout(n),n=void 0,window.clearTimeout(r),b(),k())},C=t=>{u||(S(),e.fast?.onFailure(t))},N=()=>{e.fast&&!u&&!g&&o&&x&&(g=!0,window.clearTimeout(r),e.fast.onReady())},T=async()=>{if(!u){e.fast&&(r=window.setTimeout(()=>C("upstream"),15e3));try{let t=await by(e.mine,e.theirs,s.signal);if(u)return;let n=e=>void a.push(e);await Promise.all(t.map(t=>{var r;return r={onInput:e.onInput,onOutput:e.onOutput,fast:e.fast,onDown:j,register:n,signal:e.fast?s.signal:void 0},new Promise((e,n)=>{let s=new WebSocket("wss://api.openai.com/v1/realtime/translations?model=gpt-realtime-translate",["realtime",`openai-insecure-api-key.${t.secret}`]);r.register(s);let a=!1,i=!1,l=()=>n(Error("upstream"));r.signal?.addEventListener("abort",l,{once:!0}),s.onopen=()=>{a=!0,s.send(JSON.stringify({type:"session.update",session:{audio:{input:{transcription:{model:"gpt-realtime-whisper"},noise_reduction:r.fast?null:{type:"near_field"}},output:{language:t.language.code}}}})),r.fast||e(s)},s.onmessage=n=>{let a;try{a=JSON.parse(String(n.data))}catch{return}if(!a||"object"!=typeof a||!("type"in a))return;let o="delta"in a&&"string"==typeof a.delta?a.delta:"";"session.updated"===a.type&&r.fast&&!i?(i=!0,r.signal?.removeEventListener("abort",l),e(s)):"session.input_transcript.delta"===a.type?r.onInput(t.language,o):"session.output_transcript.delta"===a.type?r.onOutput(t.language,o):"session.output_audio.delta"===a.type&&o?r.fast?.onAudio(t.language,o):"error"===a.type&&(console.warn("[interpreter] a draft session reported an error"),r.onDown())},s.onerror=()=>{a||n(Error("the draft socket could not open")),r.fast&&r.onDown()},s.onclose=()=>{a||n(Error("the draft socket closed before it opened")),(a||r.fast)&&r.onDown()}})})),x=!0,u?b():N()}catch(t){if(e.fast)return void C(t instanceof Error&&"auth"===t.message?"auth":"upstream");j()}}};return(async()=>{if("function"!=typeof AudioContext||"function"!=typeof AudioWorkletNode){console.warn("[interpreter] draft captions need AudioWorklet"),e.fast?C("mic-unavailable"):S();return}try{let n=new AudioContext({sampleRate:24e3});i=n;let r=e.fast?n.resume():null;if(await Promise.all([n.audioWorklet.addModule("/interpreter-draft/capture.js"),r]),u||h||(r||await n.resume().catch(()=>{}),u||h))return;let s=new AudioWorkletNode(n,"interpreter-draft-capture",{numberOfOutputs:0,numberOfInputs:e.fast?2:1,processorOptions:{chunkSamples:2400,cancelPlayback:!!e.fast}});s.port.onmessage=t=>{if(e.fast&&!g||!a.some(e=>e.readyState===WebSocket.OPEN))return;let n=JSON.stringify({type:"session.input_audio_buffer.append",audio:function(e){let t="";for(let n=0;n<e.length;n+=32768)t+=String.fromCharCode(...e.subarray(n,n+32768));return btoa(t)}(new Uint8Array(t.data))});for(let e of a)e.readyState===WebSocket.OPEN&&e.send(n)},l=s,e.fast?((p=n.createGain()).connect(n.destination),p.connect(s,0,1),s.port.postMessage({guard:v})):(s.port.postMessage({muted:e.isBlocked()}),t=e.onBlockedChange(e=>s.port.postMessage({muted:e}))),w(),N()}catch{console.warn("[interpreter] draft captions cannot capture the microphone"),e.fast?C("mic-unavailable"):S()}})(),e.fast||T(),{setTrack:t=>{if(u)return;let n=e.fast&&t&&!c;c=t,w(),n&&!u&&T()},play:(e,t)=>{if(i?.state!=="running"||!p||!e.length)return!1;let n=i.createBuffer(1,e.length,24e3),r=n.getChannelData(0);for(let t=0;t<e.length;t++)r[t]=e[t]/32768;let s=i.createBufferSource();s.buffer=n,s.connect(p),s.onended=()=>{m.delete(s),s.disconnect()};let a=Math.max(f,i.currentTime);return f=a+n.duration,m.set(s,{turn:t,ends:f}),s.start(a),!0},cancelPlayback:y,setEchoGuard:t=>{v=t,e.fast&&l?.port.postMessage({guard:t})},close:()=>{S()}}}var bw=n(66592),bk=n.n(bw);async function*bj(e){let t=e.getReader(),n=new TextDecoder("utf-8",{fatal:!0}),r="";try{for(;;){let e,s=await t.read();for(r+=n.decode(s.value,{stream:!s.done});-1!==(e=r.indexOf("\n\n"));){let t=r.slice(0,e);if(r=r.slice(e+2),!t.startsWith("data: "))throw Error("Invalid interpreter stream frame");let n=JSON.parse(t.slice(6));if(!n||"delta"!==n.type&&"translation"!==n.type&&"done"!==n.type&&"error"!==n.type)throw Error("Invalid interpreter stream event");if("translation"===n.type&&("string"!=typeof n.text||!n.text.trim()||"string"!=typeof n.source||"string"!=typeof n.target))throw Error("Invalid interpreter translation");if("delta"===n.type&&"string"!=typeof n.text)throw Error("Invalid interpreter delta");if("done"===n.type&&("string"!=typeof n.text||!n.text.trim()||"string"!=typeof n.source||"string"!=typeof n.target||void 0!==n.reading&&"string"!=typeof n.reading))throw Error("Invalid interpreter completion");if("error"===n.type&&"live-auth"!==n.error&&"live-upstream"!==n.error)throw Error("Invalid interpreter failure");if(yield n,"done"===n.type||"error"===n.type)return}if(s.done)throw Error("Interpreter stream ended before completion")}}finally{await t.cancel().catch(()=>{}),t.releaseLock()}}var bS=n(56204);function bC(e,t){return JSON.stringify([JSON.stringify([e.id,e.mine,e.theirs,e.speaker,e.text,e.interpretation]),t.nuance,t.check])}function bN(e,t,n){let r=e[bC(t,{nuance:!1,check:!1})],s={nuance:n.nuance&&!r?.parts.nuance,check:n.check&&!r?.parts.check};return{result:yA(r?.result,n,t.speaker),missing:s,complete:!s.nuance&&!s.check}}function bT(e,t,n,r){let a=(0,s.useRef)(new Map),[i,l]=(0,s.useState)({}),o=(0,s.useRef)(n);o.current=n;let c=(0,s.useRef)(new Set);c.current=new Set(e.map(e=>bC(e,{nuance:!1,check:!1})));let d=r?e.map(e=>({line:e,parts:{nuance:"theirs"===e.speaker&&t.meaning,check:"mine"===e.speaker&&t.meaning&&!!e.interpretation}})).filter(({parts:e})=>e.nuance||e.check):[],u=JSON.stringify({wanted:d,ids:e.map(e=>e.id)});(0,s.useEffect)(()=>{let{wanted:e,ids:t}=JSON.parse(u),n=e.map(({line:e,parts:t})=>({line:e,parts:bN(i,e,t).missing})).filter(({parts:e})=>e.nuance||e.check),r=new Set(n.map(({line:e,parts:t})=>bC(e,t)));for(let[e,n]of a.current)t.includes(n.lineId)&&(r.has(e)||n.settled)||(n.controller.abort(),a.current.delete(e));for(let{line:e,parts:t}of n){let n=bC(e,t);if(a.current.has(n)||bN(i,e,t).complete)continue;let r=new AbortController,s={controller:r,lineId:e.id,settled:!1};a.current.set(n,s),(async()=>{let i=setTimeout(()=>r.abort(),28e3);try{let i=await fetch("/api/live/interpret/assist",{method:"POST",headers:{"Content-Type":"application/json"},signal:r.signal,body:JSON.stringify({...e,parts:t,context:{...o.current,history:o.current.history.slice(-24).map(e=>({...e,text:e.text.slice(0,8e3)}))}})});if(!i.ok)return;let d=yA(await i.json(),t,e.speaker);if(r.signal.aborted||a.current.get(n)!==s)return;let u=bC(e,{nuance:!1,check:!1});if(!c.current.has(u))return;l(e=>{let n=e[u],r=c.current;return{...Object.fromEntries(Object.entries(e).filter(([e])=>r.has(e))),[u]:{result:{...n?.result,...d},parts:{nuance:t.nuance||!!n?.parts.nuance,check:t.check||!!n?.parts.check}}}})}catch{}finally{clearTimeout(i),s.settled=!0}})()}},[u,i]),(0,s.useEffect)(()=>{let e=a.current;return()=>{for(let t of e.values())t.controller.abort();e.clear()}},[]);let h=new Map;for(let{line:e,parts:t}of d){let{result:n}=bN(i,e,t);Object.keys(n).length&&h.set(e.id,n)}return h}var bI=n(24371),bM=n(36201),bE=n(74643);let b$=new Map,bR={foreground:0,background:1,later:2},bL=new Map,bP=[],bA=!1;function b_(e,t,n,r="foreground"){if(b$.has(e))return Promise.resolve(b$.get(e)??null);let s=bL.get(e);if(s)return bR[r]<bR[s.priority]&&(s.priority=r),s.promise;let{promise:a,resolve:i}=Promise.withResolvers(),l={key:e,priority:r,promise:a,resolve:i,load:async()=>{try{let e=await fetch("/api/live/interpret/reading",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({text:t,language:n.code}),signal:AbortSignal.timeout(3e4)});if(!e.ok)return null;let r=await e.json();return r&&"object"==typeof r&&"reading"in r&&"string"==typeof r.reading&&r.reading.trim()?r.reading:null}catch{return null}}};return bL.set(e,l),bP.push(l),!function e(){if(bA||!bP.length)return;let t=bP.reduce((e,t,n)=>bR[t.priority]<bR[bP[e].priority]?n:e,0),[n]=bP.splice(t,1);bA=!0,n.load().then(t=>{b$.set(n.key,t),bL.delete(n.key),bA=!1,n.resolve(t),e()})}(),a}function bF(){return(0,r.jsxs)("svg",{width:"22",height:"22",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 9.5h3.5L12 5v14l-4.5-4.5H4z"}),(0,r.jsx)("path",{d:"M15.5 9a4 4 0 0 1 0 6M18 6.5a7.5 7.5 0 0 1 0 11"})]})}function bO({card:e,speech:t,onClose:n,renderText:a}){let{tt:i}=er(),l=(0,s.useRef)(null),o=(0,s.useRef)(null),c=(0,s.useRef)(null),d=`${e.language.code}\u0000${e.text}`,u=yP.includes(e.language.code),[h,p]=(0,s.useState)(null),m=u?e.reading??(h?.key===d?h.reading:b$.get(d)??void 0):void 0,f=(0,s.useRef)(e);f.current=e,(0,s.useEffect)(()=>{let{text:e,language:t,reading:n}=f.current;if(!yP.includes(t.code)||n)return;let r=b$.get(d);if(void 0!==r){r&&f.current.onReading?.(r);return}let s=!0,{onReading:a}=f.current;return b_(d,e,t).then(e=>{e&&(a?.(e),s&&p({key:d,reading:e}))}),()=>{s=!1}},[d]);let g=(0,s.useRef)(n);(0,s.useEffect)(()=>{g.current=n});let{cancel:x}=t;return(0,s.useEffect)(()=>{let e=document.activeElement instanceof HTMLElement?document.activeElement:null;l.current?.focus();let t=e=>{"Escape"===e.key&&(e.preventDefault(),e.stopPropagation(),g.current())};return document.addEventListener("keydown",t,!0),()=>{document.removeEventListener("keydown",t,!0),x(),e?.isConnected&&e.focus({preventScroll:!0})}},[x]),(0,s.useLayoutEffect)(()=>{let e=o.current,t=c.current;if(!e||!t)return;let n=()=>{delete e.dataset.overflow;let n=20,r=160;for(;r-n>1;){let s=Math.floor((n+r)/2);t.style.fontSize=`${s}px`,t.scrollHeight<=e.clientHeight&&t.scrollWidth<=e.clientWidth?n=s:r=s}t.style.fontSize=`${n}px`,t.scrollHeight>e.clientHeight||t.scrollWidth>e.clientWidth?e.dataset.overflow="true":delete e.dataset.overflow};n();let r=new ResizeObserver(n);return r.observe(e),()=>r.disconnect()},[e.text,m]),(0,r.jsxs)("div",{ref:l,className:"translator-card",role:"dialog","aria-modal":"true","aria-label":i("translator.cardTitle"),tabIndex:-1,"data-flipped":e.flipped?"true":void 0,onKeyDown:e=>{if("Tab"!==e.key)return;let t=Array.from(l.current?.querySelectorAll("button:not(:disabled)")??[]);if(0===t.length)return;let n=t[0],r=t[t.length-1];e.shiftKey&&(document.activeElement===n||document.activeElement===l.current)?(e.preventDefault(),r.focus()):e.shiftKey||document.activeElement!==r||(e.preventDefault(),n.focus())},children:[(0,r.jsx)("div",{ref:o,className:"translator-card-box",children:(0,r.jsxs)("div",{ref:c,className:"translator-card-content",children:[(0,r.jsx)("p",{className:"translator-card-text",lang:e.language.tag,children:a(e.text)}),m?(0,r.jsx)("p",{className:"translator-card-reading",lang:"ko",children:m}):null]})}),e.note?(0,r.jsx)("p",{className:"translator-card-note",lang:e.note.language.tag,children:e.note.text}):null,t.failed?(0,r.jsx)("p",{className:"translator-card-notice",role:"status",children:i("translator.speakFailed")}):null,(0,r.jsxs)("div",{className:"translator-card-actions",children:[(0,r.jsxs)("button",{type:"button",className:"translator-card-speak","data-focus-halo":!0,"aria-pressed":t.speaking,disabled:!t.supported,onClick:()=>t.speaking?t.cancel():t.speak(e.text,e.language),children:[(0,r.jsx)(bF,{}),i(t.speaking?"translator.speakStop":"translator.speak")]}),(0,r.jsx)("button",{type:"button",className:"translator-card-close",onClick:n,children:i("translator.cardClose")})]}),(0,r.jsx)("p",{className:"translator-volume-hint","aria-live":"polite",children:t.speaking?i("translator.volumeHint"):"\xa0"})]})}let bz={ko:{engineLabel:"통역 엔진",engineVoice:"음성 + 텍스트",engineCodex:"Codex Live",engineHint:"말하는 동안 원문이 표시되며, 등록된 목소리로 번역 방향을 고정합니다.",engineFast:"빠른 통역",fastHint:"말하는 동안 번역이 표시됩니다. 음성이 켜져 있고 통역 방향이 불분명하면 텍스트만 표시됩니다.",enrollTitle:"목소리 등록",enrollMe:"먼저 한 문장을 말해주세요.",enrollThem:"이제 상대방이 한 문장을 말해주세요.",enrollHint:"음성 샘플은 브라우저 메모리에만 남고 종료 시 삭제됩니다.",enrollRetry:"목소리가 또렷하게 들리지 않았습니다. 다른 한 문장을 다시 말씀해 주세요.",enrollNext:"다음",enrollDone:"완료",enrollSkip:"건너뛰기",enrollWaiting:"모델을 불러오는 중이지만 통역은 바로 시작됩니다.",modelLoading:"음성 모델 불러오는 중 {percent}%",modelFailed:"음성 구분을 사용할 수 없어 언어 규칙으로 동작합니다.",modelReady:"음성 모델 준비 완료",correctSpeaker:"말풍선을 눌러 화자를 수정하고 다시 번역하세요.",translationFailed:"번역 실패. 눌러서 다시 시도"},en:{engineLabel:"Engine",engineVoice:"Voice + text",engineCodex:"Codex Live",engineHint:"Originals appear while speaking. Registered voices lock translation direction.",engineFast:"Fast interpretation",fastHint:"Translations appear as people speak. When voice is on and the interpretation direction is unclear, only text is shown.",enrollTitle:"Voice setup",enrollMe:"Say a sentence first.",enrollThem:"Now have the other person say a sentence.",enrollHint:"Voice samples stay in browser memory and are discarded when you stop.",enrollRetry:"Your voice sample was not clear. Please say another sentence.",enrollNext:"Next",enrollDone:"Done",enrollSkip:"Skip",enrollWaiting:"Loading models, but interpreting now.",modelLoading:"Loading voice model {percent}%",modelFailed:"Voice matching unavailable; using language rules.",modelReady:"Voice model ready",correctSpeaker:"Tap a bubble to fix the speaker and retranslate.",translationFailed:"Translation failed. Tap to retry"}},bD={ko:"한 번에 한 명씩 말씀해 주세요. 겹쳐 말하면 모두 통역되지 않고 인식된 말만 순서대로 통역됩니다.",en:"Please speak one at a time. Overlapping speech is not fully captured; only recognized words are interpreted in order.",ja:"一度に一人ずつ話してください。声が重なるとすべては通訳されず、認識された言葉だけが順に訳されます。",vi:"Vui l\xf2ng n\xf3i từng người một. Nếu n\xf3i chồng l\xean nhau, chỉ những từ nhận diện được mới được dịch theo thứ tự.",zh:"请一次一个人说话。声音重叠时无法全部翻译,仅按顺序翻译识别到的内容。","zh-tw":"請一次一個人說話。聲音重疊時無法全部翻譯,僅按順序翻譯辨識到的內容。",th:"กรุณาพูดทีละคน หากพูดซ้อนกันระบบจะแปลเฉพาะคำที่จับได้ตามลำดับเท่านั้น"},bW={ko:"목소리를 등록할 수 있도록 한국어로 한 문장을 말해주세요.",en:"Please say one sentence in English to register your voice.",ja:"声を登録するため、日本語で一文話してください。",vi:"Vui l\xf2ng n\xf3i một c\xe2u bằng tiếng Việt để đăng k\xfd giọng n\xf3i.",zh:"请用中文说一句话以登记您的声音。","zh-tw":"請用中文說一句話以登記您的聲音。",th:"กรุณาพูดภาษาไทยหนึ่งประโยคเพื่อลงทะเบียนเสียงของคุณ"};function bH({line:e,className:t,only:n,priority:a,renderText:i,load:l}){let[o,c]=(0,s.useState)(null),d=(0,s.useRef)(null),u=e.language;(0,s.useEffect)(()=>{let t;if(!l||!e.loadReading||!e.final||!u||!yP.includes(u.code)||"u"<typeof IntersectionObserver)return;let n=!0,r=d.current;if(!r)return;let s=new IntersectionObserver(r=>{window.clearTimeout(t),r.at(-1)?.isIntersecting&&(t=window.setTimeout(()=>{s.disconnect(),b_(`${u.code}\u0000${e.text}`,e.text,u,a).then(t=>{n&&t&&c({text:e.text,reading:t})})},400))});return s.observe(r),()=>{n=!1,s.disconnect(),window.clearTimeout(t)}},[u,e.final,e.loadReading,e.text,l,a]);let h=e.reading??(o?.text===e.text?o.reading:void 0);return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("span",{ref:d,className:t,"data-only":n?"true":void 0,lang:u?.tag,children:i(e.text)}),h?(0,r.jsx)("span",{className:"translator-reading",lang:"ko",children:h}):null]})}function bU({turn:e,latest:t,visible:n,speech:s,onShow:a,onCorrect:i,renderText:l,children:o}){let{tt:c,locale:d}=er(),u=bz["ko"===d?"ko":"en"],h=e.translations.at(-1),p=h??e.originals.at(-1),m=p?.language??p?.fallbackLanguage,f=p&&m?{text:p.text,language:m,reading:p.reading}:null;return(0,r.jsxs)("article",{className:"translator-entry","data-side":e.side,"data-latest":t?"true":void 0,"data-speaker-start":e.speakerStart?"true":void 0,"aria-busy":e.pending||void 0,children:[e.speakerStart?(0,r.jsx)("span",{className:"translator-speaker",children:c("me"===e.side?"translator.me":"translator.them")}):null,(0,r.jsxs)("button",{type:"button",className:"translator-bubble",title:i?u.correctSpeaker:c("translator.cardTitle"),onClick:()=>{i?i():f&&a(f)},children:[(0,r.jsx)("span",{className:"sr-only",children:i?u.correctSpeaker:c("translator.cardTitle")}),e.translations.map(e=>(0,r.jsx)(bH,{line:e,className:"translator-translation",priority:"background",renderText:l,load:n},e.key)),e.originals.map(t=>(0,r.jsx)(bH,{line:t,className:"translator-original",only:!e.translations.length,priority:"later",renderText:l,load:n},t.key))]}),i&&e.voiceLines.some(e=>e.segment.translationError)?(0,r.jsx)("button",{type:"button",className:"translator-voice-retry",onClick:i,children:u.translationFailed}):null,o,(t||i)&&h&&f?(0,r.jsxs)("div",{className:"translator-bubble-controls",children:[(0,r.jsxs)("div",{className:"translator-bubble-actions",children:[(0,r.jsxs)("button",{type:"button",onClick:()=>a(f),children:[(0,r.jsx)(bI.A,{size:18,"aria-hidden":"true"}),c("translator.cardTitle")]}),(0,r.jsxs)("button",{type:"button",disabled:!s.supported,"aria-pressed":s.speaking,onClick:()=>s.speaking?s.cancel():s.speak(f.text,f.language),children:[s.speaking?(0,r.jsx)(bM.A,{size:16,"aria-hidden":"true"}):(0,r.jsx)(bE.A,{size:18,"aria-hidden":"true"}),c(s.speaking?"translator.speakStop":"translator.speak")]})]}),(0,r.jsx)("p",{className:"translator-volume-hint","aria-live":"polite",children:s.speaking?c("translator.volumeHint"):"\xa0"}),s.failed?(0,r.jsx)("p",{className:"translator-card-notice",role:"status",children:c("translator.speakFailed")}):null]}):null]})}let bB=e=>e.language??bc(e.segment),bq=e=>e.language?bu(e.segment,e.language):bd(e.segment),bV="cuelo-translator-conversation";function bK(e){let t,n=bl();if(!e)return n;try{t=JSON.parse(e)}catch{return n}if(!t||"object"!=typeof t||!("v"in t)||1!==t.v||!("segments"in t))return n;let r=t.segments;if(!Array.isArray(r))return n;let s=[];for(let e of r.slice(-200)){if(!e||"object"!=typeof e)continue;let{role:t,text:n,mine:r,theirs:a,at:i}=e,l=yD(r),o=yD(a);("user"===t||"assistant"===t)&&"string"==typeof n&&n.trim()&&l&&o&&s.push({id:s.length,role:t,text:n,final:!0,mine:l,theirs:o,call:0,at:"number"==typeof i&&Number.isFinite(i)?i:0,restored:!0,..."me"===e.side||"them"===e.side?{side:e.side}:{},...yD(e.language)?{language:yD(e.language)}:{},..."string"==typeof e.utterance&&e.utterance.length<=100?{utterance:e.utterance}:{}})}return{...n,segments:s,nextId:s.length}}let bJ="cueloTranslator";function bG(e,t){return{[bJ]:e,cueloTranslatorDepth:t}}function bY(e){if(!e||"object"!=typeof e)return 0;let t=e.cueloTranslatorDepth;return"string"==typeof e[bJ]&&"number"==typeof t&&Number.isInteger(t)&&t>0?t:0}let bZ={pushed:[],ignore:0,release:void 0,releasing:!1,listener:null,replaceGuard:!1};function bQ(){if(bZ.replaceGuard)return;bZ.replaceGuard=!0;let e=window.history.replaceState;window.history.replaceState=function(t,n,r){let s=null==r||new URL(r,window.location.href).href===window.location.href;return e.call(this,function(e,t,n){let r=bY(e);if(0===r||!n||bY(t)>0||null!=t&&("object"!=typeof t||Array.isArray(t)))return t;let s=e[bJ];return{...t??{},...bG(s,r)}}(window.history.state,t,s),n,r)}}function bX(e){if(bZ.ignore>0)return;let t=function(e,t){let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];)n+=1;return{back:e.length-n,push:t.slice(n)}}(bZ.pushed,e);if(t.back>0){if(bY(window.history.state)===bZ.pushed.length){bZ.ignore+=1,window.history.go(-t.back);return}bZ.pushed=bZ.pushed.slice(0,bZ.pushed.length-t.back)}for(let e of t.push)bZ.pushed=[...bZ.pushed,e],window.history.pushState({...window.history.state??{},...bG(e,bZ.pushed.length)},"")}function b0(){if(window.clearTimeout(bZ.release),bZ.release=void 0,bZ.ignore>0)return;let e=bY(window.history.state);if(bZ.pushed=[],e>0){bZ.ignore+=1,window.history.go(-e);return}bZ.listener&&window.removeEventListener("popstate",bZ.listener),bZ.listener=null,bZ.releasing=!1}bQ();let b1={posts:0,lastPostAt:null,queue:[],timer:void 0};function b2(){var e,t,n;b1.timer=void 0;let r=(e=b1.lastPostAt,t=b1.posts,n=Date.now(),t>=30?null:null===e?0:Math.max(0,e+1e4-n));if(null===r){b1.queue=[];return}if(r>0){b1.timer=window.setTimeout(b2,r);return}let s=b1.queue.splice(0,20);0!==s.length&&(b1.posts+=1,b1.lastPostAt=Date.now(),fetch("/api/live/stall",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({events:s}),keepalive:!0}).catch(()=>{}),b1.queue.length>0&&(b1.timer=window.setTimeout(b2,0)))}function b4(e){b1.queue.push(e),b1.queue.length>20&&b1.queue.splice(0,b1.queue.length-20),void 0===b1.timer&&(b1.timer=window.setTimeout(b2,0))}async function b8(e,t,n,r,s,a=!1){if(n.throwIfAborted(),a){let t=null;try{let a=r();t=b6(await b5(e,n,a,!0),a,n,s)}catch{}if(n.throwIfAborted(),t)return t}let i=window.speechSynthesis,l=i?.getVoices()??[],o=t.tag.toLowerCase(),c=l.find(e=>e.lang.toLowerCase().replaceAll("_","-")===o)??l.find(e=>e.lang.toLowerCase().split(/[-_]/)[0]===t.code);if(c){let r=Promise.withResolvers(),a=()=>{r.resolve(!0),i.cancel()},l=setTimeout(()=>{r.resolve(!1),i.cancel()},5e3);n.addEventListener("abort",a,{once:!0});try{let a=new SpeechSynthesisUtterance(e);if(a.lang=t.tag,a.voice=c,a.onstart=()=>{n.aborted||(clearTimeout(l),l=setTimeout(()=>{r.resolve(!0),i.cancel()},Math.max(15e3,500*e.length)),s?.())},a.onend=()=>r.resolve(!0),a.onerror=({error:e})=>r.resolve("canceled"===e||"interrupted"===e),i.speak(a),await r.promise)return}catch{}finally{clearTimeout(l),n.removeEventListener("abort",a)}}n.throwIfAborted();let d=r();await b6(await b5(e,n,d,!1),d,n,s)}async function b5(e,t,n,r){t.throwIfAborted();let s=Promise.withResolvers(),a=()=>s.reject(t.reason);t.addEventListener("abort",a,{once:!0});try{await Promise.race([n.resume(),s.promise])}finally{t.removeEventListener("abort",a)}let i=await fetch("/api/live/speech",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r?{text:e,engine:"elevenlabs"}:{text:e}),signal:t});if(!i.ok)throw Error("Speech unavailable");return n.decodeAudioData(await i.arrayBuffer())}function b6(e,t,n,r){n.throwIfAborted();let s=t.createBufferSource();s.buffer=e,s.connect(t.destination);let a=Promise.withResolvers();s.onended=()=>a.resolve();let i=()=>{s.stop(),a.resolve()};try{s.start()}catch(e){throw s.disconnect(),e}return n.addEventListener("abort",i,{once:!0}),r?.(),a.promise.finally(()=>{n.removeEventListener("abort",i),s.disconnect()})}let b3="cuelo-translator-phrases",b7={food:[{ko:"저는 땅콩 알레르기가 있어요.",en:"I'm allergic to peanuts."},{ko:"새우나 게 같은 갑각류는 못 먹어요.",en:"I can't eat shellfish like shrimp or crab."},{ko:"맵지 않게 해 주세요.",en:"Not spicy, please."},{ko:"고기는 빼 주실 수 있나요?",en:"Could you leave out the meat?"}],restroom:[{ko:"화장실이 어디에 있나요?",en:"Where is the restroom?"},{ko:"화장실을 써도 될까요?",en:"May I use the restroom?"},{ko:"화장지가 없어요.",en:"There's no toilet paper."}],payment:[{ko:"계산해 주세요.",en:"The bill, please."},{ko:"카드로 계산할 수 있나요?",en:"Can I pay by card?"},{ko:"영수증 주세요.",en:"Can I have a receipt?"},{ko:"따로 계산할게요.",en:"We'll pay separately."}],directions:[{ko:"여기에 어떻게 가나요?",en:"How do I get here?"},{ko:"가장 가까운 지하철역이 어디예요?",en:"Where is the nearest subway station?"},{ko:"걸어서 얼마나 걸려요?",en:"How long does it take on foot?"},{ko:"이 주소로 가 주세요.",en:"Please take me to this address."}],emergency:[{ko:"도와주세요!",en:"Help me, please!"},{ko:"구급차를 불러 주세요.",en:"Please call an ambulance."},{ko:"경찰을 불러 주세요.",en:"Please call the police."},{ko:"가장 가까운 병원이 어디예요?",en:"Where is the nearest hospital?"},{ko:"여권을 잃어버렸어요.",en:"I lost my passport."}]},b9=Object.keys(b7);function we(e,t,n){return`${t}>${n}\u0000${e.trim()}`}function wt(e){let t,n={custom:[],cache:{}};if(!e)return n;try{t=JSON.parse(e)}catch{return n}if(!t||"object"!=typeof t)return n;let r=[];if("custom"in t&&Array.isArray(t.custom))for(let e of t.custom.slice(0,50)){if(!e||"object"!=typeof e)continue;let{id:t,text:n,lang:s}=e;"string"==typeof t&&"string"==typeof n&&n.trim()&&"string"==typeof s&&r.push({id:t,text:n.slice(0,200),lang:s})}let s={};if("cache"in t&&t.cache&&"object"==typeof t.cache)for(let[e,n]of Object.entries(t.cache)){if("string"==typeof n){n.trim()&&(s[e]={translation:n});continue}if(!n||"object"!=typeof n||!("translation"in n)||"string"!=typeof n.translation||!n.translation.trim())continue;let t="reading"in n&&"string"==typeof n.reading&&n.reading.trim()?n.reading:void 0;s[e]=t?{translation:n.translation,reading:t}:{translation:n.translation}}return{custom:r,cache:wn(s)}}function wn(e){let t=Object.entries(e);return t.length<=400?e:Object.fromEntries(t.slice(-400))}async function wr(e,t,n,r){let s=await fetch("/api/live/interpret/text",{method:"POST",headers:{"Content-Type":"application/json"},signal:r,body:JSON.stringify({mine:t.code,theirs:n.code,source:t.code,text:e})});if(!s.ok||!s.body)throw Error(`translate ${s.status}`);for await(let e of bj(s.body)){if("error"===e.type)throw Error(e.error);if("done"===e.type){if(e.source!==t.code||e.target!==n.code)throw Error("translate: wrong direction");if(e.text.trim())return e.reading?{translation:e.text.trim(),reading:e.reading}:{translation:e.text.trim()}}}throw Error("translate: no result")}function ws(){try{return wt(window.localStorage.getItem(b3))}catch{return wt(null)}}function wa(){return(0,r.jsx)("svg",{width:"18",height:"18",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 6L6 18"})})}function wi({mine:e,theirs:t,onShow:n,onClose:a}){let i,l,{tt:o}=er(),[c,d]=(0,s.useState)(ws),[u,h]=(0,s.useState)(new Set),[p,m]=(0,s.useState)(new Set),[f,g]=(0,s.useState)(!1),[x,v]=(0,s.useState)(""),y=(0,s.useRef)(new AbortController),b=(0,s.useRef)(null),w=(0,s.useRef)((i=0,l=[],async function(e){if(i<2)i+=1;else{let{promise:e,resolve:t}=Promise.withResolvers();l.push(t),await e}try{return await e()}finally{let e=l.shift();e?e():i-=1}})),k=(0,s.useRef)(new Map),j=(0,s.useRef)(c);j.current=c;let S=(0,s.useRef)(a);(0,s.useEffect)(()=>{S.current=a}),(0,s.useEffect)(()=>{let e=new AbortController;y.current=e;let t=document.activeElement instanceof HTMLElement?document.activeElement:null;b.current?.focus();let n=e=>{"Escape"===e.key&&(e.preventDefault(),S.current())};return document.addEventListener("keydown",n),()=>{document.removeEventListener("keydown",n),e.abort(),t?.isConnected&&t.focus({preventScroll:!0})}},[]),(0,s.useEffect)(()=>{try{window.localStorage.setItem(b3,JSON.stringify(c))}catch{}},[c]);let C=(0,s.useMemo)(()=>b9.map(n=>({group:n,rows:b7[n].flatMap(n=>{var r;let s="ko"===(r=e.code)?n.ko:"en"===r?n.en:null;return s?[{key:we(s,e.code,t.code),text:s}]:[]})})).filter(({rows:e})=>e.length>0),[e.code,t.code]),N=(0,s.useMemo)(()=>c.custom.filter(t=>t.lang===e.code).map(n=>({key:we(n.text,e.code,t.code),text:n.text,customId:n.id})),[c.custom,e.code,t.code]),T=(0,s.useMemo)(()=>[...C.flatMap(({rows:e})=>e),...N],[N,C]).filter(e=>!c.cache[e.key]),I=n=>{let r=j.current.cache[n.key];if(r)return Promise.resolve(r);let s=k.current.get(n.key);if(s)return s;let a=y.current.signal;h(e=>new Set(e).add(n.key)),m(e=>{let t=new Set(e);return t.delete(n.key),t});let i=w.current(async()=>{try{let r=await wr(n.text,e,t,a);return d(e=>{var t;let s;return t=n.key,s={...e.cache},delete s[t],s[t]=r,{...e,cache:wn(s)}}),r}catch{return a.aborted||m(e=>new Set(e).add(n.key)),null}finally{k.current.delete(n.key),a.aborted||h(e=>{let t=new Set(e);return t.delete(n.key),t})}});return k.current.set(n.key,i),i},M=async()=>{g(!0);let e=new Set,t=T.filter(t=>!e.has(t.key)&&e.add(t.key));await Promise.all(t.map(I)),y.current.signal.aborted||g(!1)},E=s=>{let a=c.cache[s.key],i=u.has(s.key),l=a?void 0:i?"pending":p.has(s.key)?"failed":"uncached",h=s.customId;return(0,r.jsxs)("li",{className:"translator-phrase-item",children:[(0,r.jsxs)("button",{type:"button",className:"translator-phrase","data-state":l,"aria-busy":i||void 0,onClick:()=>{let r;(r=j.current.cache[s.key])?n({text:r.translation,reading:r.reading,language:t,note:{text:s.text,language:e},onReading:e=>d(t=>{var n;let r;return n=s.key,(r=t.cache[n])?{...t,cache:{...t.cache,[n]:{...r,reading:e}}}:t})}):I(s)},children:[(0,r.jsx)("span",{className:"translator-phrase-source",lang:e.tag,children:s.text}),(0,r.jsx)("span",{className:"translator-phrase-target",lang:a?t.tag:void 0,children:a?.translation??(i?o("translator.typePending"):p.has(s.key)?o("translator.phraseFailed"):o("translator.phraseNotCached"))}),a?.reading?(0,r.jsx)("span",{className:"translator-reading",lang:"ko",children:a.reading}):null]}),h?(0,r.jsx)("button",{type:"button",className:"translator-icon-button translator-phrase-delete","aria-label":o("translator.phraseDelete",{text:s.text}),title:o("translator.phraseDelete",{text:s.text}),onClick:()=>{d(e=>({...e,custom:e.custom.filter(e=>e.id!==h)}))},children:(0,r.jsx)(wa,{})}):null]},s.key)};return(0,r.jsxs)("div",{className:"translator-phrases",role:"dialog","aria-modal":"true","aria-labelledby":"translator-phrases-title",children:[(0,r.jsxs)("header",{className:"translator-phrases-head",children:[(0,r.jsx)("h2",{id:"translator-phrases-title",ref:b,tabIndex:-1,children:o("translator.phrases")}),(0,r.jsxs)("span",{className:"translator-phrases-pair",children:[(0,r.jsx)("span",{lang:e.tag,children:e.nativeName}),(0,r.jsx)("span",{"aria-hidden":"true",children:" → "}),(0,r.jsx)("span",{lang:t.tag,children:t.nativeName})]}),(0,r.jsx)("button",{type:"button",className:"translator-icon-button","aria-label":o("translator.phrasesClose"),title:o("translator.phrasesClose"),onClick:a,children:(0,r.jsx)(wa,{})})]}),(0,r.jsxs)("div",{className:"translator-phrases-body",children:[(0,r.jsxs)("div",{className:"translator-phrases-sync",children:[T.length>0?(0,r.jsx)("button",{type:"button",className:"translator-phrases-all","data-focus-halo":!0,disabled:f,"aria-busy":f||void 0,onClick:()=>void M(),children:f?o("translator.typePending"):o("translator.phrasesTranslateAll")}):null,(0,r.jsx)("p",{className:"translator-phrases-status",role:"status","aria-live":"polite",children:T.length>0?o("translator.phrasesRemaining",{count:String(T.length)}):o("translator.phrasesAllCached")})]}),0===C.length?(0,r.jsx)("p",{className:"translator-phrases-note",children:o("translator.phrasesNoBuiltIn")}):null,C.map(({group:e,rows:t})=>(0,r.jsxs)("section",{className:"translator-phrase-group","aria-labelledby":`translator-phrases-${e}`,children:[(0,r.jsx)("h3",{id:`translator-phrases-${e}`,children:o(`translator.phrases.${e}`)}),(0,r.jsx)("ul",{children:t.map(E)})]},e)),(0,r.jsxs)("section",{className:"translator-phrase-group","aria-labelledby":"translator-phrases-mine",children:[(0,r.jsx)("h3",{id:"translator-phrases-mine",children:o("translator.phrasesMine")}),N.length>0?(0,r.jsx)("ul",{children:N.map(E)}):null,(0,r.jsxs)("form",{className:"translator-phrase-add",onSubmit:t=>{t.preventDefault();let n=x.trim().slice(0,200);n&&(d(t=>t.custom.some(t=>t.lang===e.code&&t.text===n)?t:{...t,custom:[...t.custom,{id:`${Date.now().toString(36)}-${t.custom.length}`,text:n,lang:e.code}].slice(-50)}),v(""))},children:[(0,r.jsxs)("label",{children:[(0,r.jsx)("span",{className:"sr-only",children:o("translator.phraseAddLabel")}),(0,r.jsx)("input",{type:"text",value:x,lang:e.tag,maxLength:200,placeholder:o("translator.phraseAddPlaceholder"),onChange:e=>v(e.target.value)})]}),(0,r.jsx)("button",{type:"submit",disabled:!x.trim(),children:o("translator.phraseAdd")})]})]})]})]})}async function wl(e){let t=await createImageBitmap(e,{imageOrientation:"from-image"});try{let{width:e,height:n}=function(e,t,n=1600){let r=Math.min(1,n/Math.max(e,t));return{width:Math.max(1,Math.round(e*r)),height:Math.max(1,Math.round(t*r))}}(t.width,t.height),r=document.createElement("canvas");r.width=e,r.height=n;let s=r.getContext("2d");if(!s)throw Error("canvas unavailable");return s.fillStyle="#fff",s.fillRect(0,0,e,n),s.drawImage(t,0,0,e,n),r.toDataURL("image/jpeg",.85)}finally{t.close()}}let wo="cuelo-translator-scan-avoid";var wc=n(34292),wd=n.n(wc);let wu=[],wh=["title","close","takePhoto","pickAlbum","avoidLabel","avoidPlaceholder","avoidHint","pickHint","loading","error","authError","retry","empty","show","pick","avoidChanged","rescan","warning"];function wp(){return(0,r.jsxs)("svg",{width:"20",height:"20",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 8h3l1.6-2.4h6.8L17 8h3a1 1 0 0 1 1 1v9a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1V9a1 1 0 0 1 1-1Z"}),(0,r.jsx)("circle",{cx:"12",cy:"13",r:"3.6"})]})}function wm(){return(0,r.jsx)("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M6 6l12 12M18 6L6 18"})})}function wf({item:e,index:t,checked:n,copy:s,mine:a,theirs:i,onToggle:l,onShow:o}){return(0,r.jsxs)("li",{className:wd().row,"data-warn":e.warning?"true":void 0,children:[(0,r.jsx)("label",{className:wd().pick,title:s.pick,children:(0,r.jsx)("input",{type:"checkbox",checked:n,"aria-label":`${s.pick}: ${e.translation}`,onChange:()=>l(t)})}),(0,r.jsxs)("div",{className:wd().main,children:[(0,r.jsx)("span",{className:wd().translation,lang:a.tag,children:e.translation}),(0,r.jsx)("span",{className:wd().original,lang:i.tag,children:e.original}),e.description?(0,r.jsx)("p",{className:wd().description,lang:a.tag,children:e.description}):null,e.allergens?.length?(0,r.jsx)("ul",{className:wd().tags,lang:a.tag,children:e.allergens.map(e=>(0,r.jsx)("li",{children:e},e))}):null,e.warning?(0,r.jsxs)("p",{className:wd().warning,role:"note",lang:a.tag,children:[(0,r.jsxs)("span",{className:"sr-only",children:[s.warning,": "]}),e.warning]}):null]}),(0,r.jsxs)("div",{className:wd().side,children:[e.priceText||void 0!==e.price?(0,r.jsx)("span",{className:wd().price,children:e.priceText??e.price}):null,(0,r.jsx)("button",{type:"button",className:wd().show,onClick:()=>o(e),children:s.show})]})]})}function wg({mine:e,theirs:t,onShow:n,onClose:a}){let{tt:i}=er(),l=(0,s.useMemo)(()=>Object.fromEntries(wh.map(e=>[e,i(`translator.scan.${e}`)])),[i]),[o,c]=(0,s.useState)({name:"pick"}),[d,u]=(0,s.useState)(""),[h,p]=(0,s.useState)(new Set),m=(0,s.useRef)(null),f=(0,s.useRef)(null),g=(0,s.useRef)(!1),x=(0,s.useRef)(null),v=(0,s.useRef)(a);v.current=a,(0,s.useEffect)(()=>{g.current=!1,u(function(){try{let e=(void 0)??window.localStorage,t=e?.getItem(wo);return"string"==typeof t?t.slice(0,200):""}catch{return""}}());let e=document.activeElement instanceof HTMLElement?document.activeElement:null;x.current?.focus();let t=e=>{"Escape"===e.key&&(e.preventDefault(),v.current())};return document.addEventListener("keydown",t),()=>{g.current=!0,document.removeEventListener("keydown",t),f.current?.abort(),e?.isConnected&&e.focus({preventScroll:!0})}},[]);let y=async(n,r)=>{f.current?.abort();let s=new AbortController;f.current=s,c({name:"loading"}),p(new Set);try{let a=await fetch("/api/live/interpret/scan",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({image:n,mine:e.code,theirs:t.code,avoid:r.trim()}),signal:s.signal});if(!a.ok)return void c({name:"error",auth:401===a.status});c({name:"result",result:await a.json(),avoid:r})}catch{s.signal.aborted||c({name:"error",auth:!1})}},b=async e=>{let t=e.target.files?.[0];if(e.target.value="",t){m.current=null;try{m.current=await wl(t)}catch{g.current||c({name:"error",auth:!1});return}g.current||await y(m.current,d)}},w=e=>{p(t=>{let n=new Set(t);return n.delete(e)||n.add(e),n})},k=r=>n({text:r.original,language:t,note:{text:r.translation,language:e}}),j="result"===o.name?o.result.items:wu,S=(0,s.useMemo)(()=>{let e,t,n;return e=0,t=0,n=0,j.forEach((r,s)=>{h.has(s)&&("number"==typeof r.price&&Number.isFinite(r.price)?(e+=Math.round(100*r.price),t+=1):n+=1)}),{total:e/100,count:t,missing:n}},[j,h]),C=m.current;return(0,r.jsxs)("div",{className:"translator-phrases",role:"dialog","aria-modal":"true","aria-labelledby":"translator-scan-title",children:[(0,r.jsxs)("header",{className:"translator-phrases-head",children:[(0,r.jsx)("h2",{id:"translator-scan-title",ref:x,tabIndex:-1,children:l.title}),(0,r.jsx)("button",{type:"button",className:"translator-icon-button","aria-label":l.close,title:l.close,onClick:a,children:(0,r.jsx)(wm,{})})]}),(0,r.jsxs)("div",{className:wd().body,children:["pick"===o.name||"result"===o.name||"error"===o.name?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("div",{className:wd().pickers,children:[(0,r.jsxs)("label",{className:wd().primary,children:[(0,r.jsx)(wp,{}),l.takePhoto,(0,r.jsx)("input",{className:wd().hiddenInput,type:"file",accept:"image/*",capture:"environment",onChange:e=>void b(e)})]}),(0,r.jsxs)("label",{className:wd().secondary,children:[l.pickAlbum,(0,r.jsx)("input",{className:wd().hiddenInput,type:"file",accept:"image/*",onChange:e=>void b(e)})]})]}),(0,r.jsxs)("div",{className:wd().avoid,children:[(0,r.jsx)("label",{htmlFor:"translator-scan-avoid",children:l.avoidLabel}),(0,r.jsx)("input",{id:"translator-scan-avoid",type:"text",value:d,maxLength:200,placeholder:l.avoidPlaceholder,onChange:e=>(e=>{let t=e.slice(0,200);u(t);try{let e=(void 0)??window.localStorage,n=t.slice(0,200);n.trim()?e?.setItem(wo,n):e?.removeItem(wo)}catch{}})(e.target.value)}),(0,r.jsx)("p",{className:wd().hint,children:l.avoidHint})]})]}):null,"pick"===o.name?(0,r.jsx)("p",{className:wd().hint,children:l.pickHint}):null,"loading"===o.name?(0,r.jsx)("p",{className:wd().status,role:"status","aria-busy":"true",children:l.loading}):null,"error"===o.name?(0,r.jsxs)("div",{className:wd().error,role:"alert",children:[(0,r.jsx)("p",{children:o.auth?l.authError:l.error}),C?(0,r.jsx)("button",{type:"button",className:wd().secondary,onClick:()=>void y(C,d),children:l.retry}):null]}):null,"result"===o.name?(0,r.jsxs)(r.Fragment,{children:[o.avoid.trim()!==d.trim()&&C?(0,r.jsxs)("div",{className:wd().avoid,children:[(0,r.jsx)("p",{className:wd().hint,children:l.avoidChanged}),(0,r.jsx)("button",{type:"button",className:wd().rescan,onClick:()=>void y(C,d),children:l.rescan})]}):null,o.result.summary?(0,r.jsx)("p",{className:wd().summary,lang:e.tag,children:o.result.summary}):null,o.result.summary||0!==j.length?null:(0,r.jsx)("p",{className:wd().status,children:l.empty}),j.length>0?(0,r.jsx)("ul",{className:wd().list,children:j.map((n,s)=>(0,r.jsx)(wf,{item:n,index:s,checked:h.has(s),copy:l,mine:e,theirs:t,onToggle:w,onShow:k},`${s}:${n.original}`))}):null]}):null]}),"result"===o.name&&h.size>0?(0,r.jsxs)("div",{className:wd().footer,role:"status",children:[(0,r.jsxs)("span",{className:wd().footerLabel,children:[i("translator.scan.total",{count:S.count}),S.missing>0?`, ${i("translator.scan.missing",{count:S.missing})}`:""]}),(0,r.jsx)("span",{className:wd().footerTotal,children:function(e,t,n){let r=new Intl.NumberFormat(n,{maximumFractionDigits:2}).format(e);if(!t)return r;if(/^[A-Za-z]{3}$/.test(t))try{return new Intl.NumberFormat(n,{style:"currency",currency:t.toUpperCase(),maximumFractionDigits:2}).format(e)}catch{}return`${r} ${t}`}(S.total,o.result.currency,e.tag)})]}):null]})}function wx({result:e,numericMismatch:t=!1,meaning:n,mine:s}){let{tt:a}=er(),i=n?e?.warning||(t?a("translator.assistNumberWarning"):void 0):void 0,l=n?e?.nuance:void 0;return i||l?(0,r.jsxs)("div",{className:bk().assist,lang:s.tag,children:[l?(0,r.jsxs)("p",{className:bk().nuance,children:[(0,r.jsx)("span",{children:a("translator.assistNuance")})," ",l]}):null,i?(0,r.jsxs)("div",{className:bk().warning,role:"status",children:[(0,r.jsxs)("p",{children:[(0,r.jsx)("span",{children:a("translator.assistWarning")})," ",i]}),e?.backTranslation?(0,r.jsxs)("p",{className:bk().backTranslation,children:[(0,r.jsx)("span",{children:a("translator.assistBackTranslation")})," ",e.backTranslation]}):null]}):null]}):null}class wv{constructor(e){this.callbacks=e,this.pending=[],this.clock=0,this.nextId=0,this.sentUntil=0,this.silence=0,this.voiced=0,this.identified=!1,this.holdMs=0}get current(){return this.turn}get now(){return this.clock}push(e,t){let n=this.clock,r=e.length/24e3*1e3;this.clock+=r;let s=0;for(let t of e)s+=(t/32768)**2;let a=Math.sqrt(s/e.length)>=.012;if(!this.turn&&!a){this.continuation=void 0;return}if(!this.turn){let e=t??this.continuation;this.continuation=void 0,this.turn={id:this.nextId++,startMs:n,endMs:this.clock,side:e??this.previous},this.identified=void 0!==e,this.sentUntil=n,this.voiced=0,this.callbacks.open({...this.turn,side:e})}t&&!this.identified&&(this.turn.side=t,this.identified=!0),this.turn.endMs=this.clock,this.pending.push({samples:e,startMs:n,endMs:this.clock}),this.voiced+=a?r:0,this.silence=a?0:this.silence+r,this.silence>=700?this.finish():this.flush(this.clock-this.holdMs)}identify(e,t){if(!this.turn){this.previous=e;return}if(this.manualTurn===this.turn.id)return;if(!this.identified||!this.turn.side){this.turn.side=e,this.previous=e,this.identified=!0;return}if(this.turn.side===e)return;let n=Math.max(this.sentUntil,Math.min(t,this.clock));if(n-this.turn.startMs<100)return;this.flush(n);let r=this.turn;if(this.callbacks.commit({...r,endMs:n}),this.previous=e,!this.pending.length){this.turn=void 0,this.continuation=e,this.silence=0;return}this.turn={id:this.nextId++,startMs:n,endMs:this.clock,side:e},this.identified=!0,this.sentUntil=n,this.voiced=this.clock-n,this.callbacks.open(this.turn)}flush(e){if(this.turn)for(;this.pending.length&&this.pending[0].startMs<e;){let t=this.pending[0],n=Math.min(t.samples.length,Math.round((e-t.startMs)*24e3/1e3));if(n<=0)break;if(this.callbacks.append(t.samples.subarray(0,n),this.turn),this.sentUntil=t.startMs+n/24e3*1e3,n===t.samples.length)this.pending.shift();else{t.samples=t.samples.subarray(n),t.startMs=this.sentUntil;break}}}finish(){this.turn&&(this.flush(this.clock),this.previous=this.turn.side??this.previous,this.voiced>=100&&this.callbacks.commit({...this.turn,side:this.identified?this.turn.side:void 0,endMs:this.clock-this.silence}),this.turn=void 0,this.pending=[],this.silence=0)}releaseIdentity(){this.previous=void 0,this.continuation=void 0,this.turn&&this.manualTurn!==this.turn.id&&(this.turn.side=void 0,this.identified=!1)}correct(e,t){this.turn?.id===e&&(this.turn.side=t,this.identified=!0,this.manualTurn=e),this.turn?.id!==e&&(this.turn||e!==this.nextId-1)||(this.previous=t)}}function wy(e,t,n){let r=yK(e,t,n);return r?r.code===t.code?"me":"them":void 0}class wb{ready(e,t){this.values.set(e,t);let n=[];for(;this.values.has(this.next);)n.push(this.values.get(this.next)),this.values.delete(this.next++);return n}constructor(){this.next=0,this.values=new Map}}class ww{constructor(e){this.options=e,this.utterances=new Map,this.serverItems=new Map,this.revisions=new Map,this.manualSides=new Map,this.jobs=[],this.active=new Set,this.output=new wb,this.sequence=0,this.reservations=new Map,this.stopped=!1,this.idleResolvers=[]}open(e){this.utterances.set(e.id,{...e,text:"",closed:!1,translation:"",final:!1}),this.reservations.set(e.id,this.sequence++)}direction(e,t){let n=this.utterances.get(e);!n||n.closed||this.manualSides.has(e)||(n.side=t,this.options.onUpdate({...n}))}commit(e){let t=this.utterances.get(e.id);if(!t)return;t.startMs=e.startMs,t.endMs=e.endMs,void 0!==e.side&&(t.side=e.side);let n=this.manualSides.get(e.id);n&&(t.side=n)}bind(e){let t=this.serverItems.get(e);if(void 0===t){let n=new Set(this.serverItems.values());void 0!==(t=[...this.utterances.keys()].find(e=>!n.has(e)))&&this.serverItems.set(e,t)}return void 0===t?void 0:this.utterances.get(t)}committed(e){this.bind(e)}transcript(e,t,n){let r=this.bind(e);if(r&&!this.stopped&&!r.closed)return r.text=n?t:r.text+t,r.side??=wy(r.text,this.options.mine,this.options.theirs)??(n?this.previousSide(r.id):void 0),r.closed=n,this.options.onUpdate({...r}),n&&this.schedule(r),r}failed(e){let t=this.bind(e);return t&&!t.closed?this.transcript(e,t.text,!0):t}correct(e,t){let n=this.utterances.get(e);if(n&&!this.stopped){for(let n of(this.manualSides.set(e,t),this.revisions.set(e,(this.revisions.get(e)??0)+1),[...this.jobs,...this.active]))n.item.id===e&&n.abort.abort();n.closed&&this.reservations.set(e,this.sequence++),n.side=t,n.translation="",n.final=!1,n.translationError=!1,this.options.onUpdate({...n}),n.closed&&this.schedule(n)}}releaseDirection(e){if(void 0===e||this.manualSides.has(e))return;let t=this.utterances.get(e);t&&!t.closed&&(t.side=wy(t.text,this.options.mine,this.options.theirs),this.options.onUpdate({...t}))}schedule(e){e.side??=this.previousSide(e.id)??"me";let t={item:{...e},revision:this.revisions.get(e.id)??0,sequence:this.reservations.get(e.id),abort:new AbortController};this.jobs.push(t),this.pump()}previousSide(e){let t;for(let n of this.utterances.values())n.id<e&&n.side&&(t=n.side);return t}valid(e){return!this.stopped&&!e.abort.signal.aborted&&e.revision===(this.revisions.get(e.item.id)??0)}pump(){for(;!this.stopped&&this.active.size<2&&this.jobs.length;){let e=this.jobs.shift();this.active.add(e);let t="me"===e.item.side?this.options.mine:this.options.theirs,n="me"===e.item.side?this.options.theirs:this.options.mine,r=[...this.utterances.values()].filter(t=>t.id<e.item.id&&t.side===e.item.side&&t.closed&&t.text.trim()).slice(-1).map(e=>e.text);(this.valid(e)&&e.item.text.trim()?this.options.translate({text:e.item.text,source:t.code,target:n.code,previous:r,signal:e.abort.signal,onDelta:t=>{if(this.valid(e)){let n=this.utterances.get(e.item.id);n.translation=t,this.options.onUpdate({...n})}}}).then(t=>({job:e,text:t}),()=>({job:e,error:!0})):Promise.resolve({job:e,text:""})).then(t=>{for(let n of this.output.ready(e.sequence,t)){if(!this.valid(n.job))continue;let e=this.utterances.get(n.job.item.id);e.translation="text"in n?n.text??"":"",e.translationError="error"in n||!!e.text.trim()&&!e.translation.trim(),e.final=!0,this.options.onUpdate({...e}),this.options.onFinal({...e})}if(this.active.delete(e),this.pump(),!this.active.size&&!this.jobs.length)for(let e of this.idleResolvers.splice(0))e()})}}whenIdle(){if(!this.active.size&&!this.jobs.length)return Promise.resolve();let e=Promise.withResolvers();return this.idleResolvers.push(e.resolve),e.promise}completeInput(){if(!this.stopped)for(let e of this.utterances.values())e.closed||(e.closed=!0,this.options.onUpdate({...e}),this.schedule(e))}close(){for(let e of(this.stopped=!0,[...this.active,...this.jobs]))e.abort.abort();for(let e of(this.jobs=[],this.idleResolvers.splice(0)))e()}}function wk(e){let t=new Float32Array(Math.floor(2*e.length/3));for(let n=0;n<t.length;n++){let r=1.5*n,s=Math.floor(r),a=r-s;t[n]=((e[s]??0)*(1-a)+(e[s+1]??e[s]??0)*a)/32768}return t}class wj{constructor(e){this.options=e,this.abort=new AbortController,this.disposed=!1,this.stopping=!1,this.speakerReady=!1,this.workerBusy=!1,this.nextAnalysis=1e3,this.analysisRing=new Float32Array(24e3),this.analysisSize=0,this.identityEpoch=0,this.enrollment="me",this.enrollmentAudio=[],this.enrollmentSize=0,this.confirmedSides=new Set,this.enrollmentFailed=!1,this.audio=new Map,this.playbackQueue=Promise.resolve(),this.pendingFinals=new Set,this.finalWaiters=[],this.session=new ww({...e,translate:async({text:t,source:n,previous:r,signal:s,onDelta:a})=>{let i=await fetch("/api/live/interpret/text",{method:"POST",headers:{"Content-Type":"application/json"},signal:s,body:JSON.stringify({mine:e.mine.code,theirs:e.theirs.code,source:n,text:t,mode:"voice",profile:e.profile,history:r.map(e=>({role:"user",text:e}))})});if(!i.ok||!i.body)throw Error(401===i.status?"auth":"upstream");let l="";for await(let e of bj(i.body))if("delta"===e.type)a(l+=e.text);else if("done"===e.type)return e.text;else if("error"===e.type)throw Error(e.error);throw Error("Incomplete interpretation")},onFinal:t=>{let n=t.translation;if(!n||t.translationError||!e.playback().enabled)return;let r="me"===t.side?e.theirs:e.mine;this.playbackQueue=this.playbackQueue.then(async()=>{if(this.disposed||!e.playback().enabled||!this.context)return;let t=!1;try{await b8(n,r,this.abort.signal,()=>this.context,()=>{clearTimeout(this.guardTimer),t=e.playback().echoGuard,this.node?.port.postMessage({muted:t})},e.playback().natural)}catch{}finally{t&&!this.disposed&&(this.guardTimer=window.setTimeout(()=>this.node?.port.postMessage({muted:!1}),250))}})}}),this.turns=new wv({open:e=>{this.session.open(e),this.audio.set(e.id,{chunks:[],size:0}),this.audio.size>20&&this.audio.delete(this.audio.keys().next().value)},append:(e,t)=>{let n=this.audio.get(t.id);if(n&&n.size<72e3){let t=e.slice(0,72e3-n.size);n.chunks.push(t),n.size+=t.length}this.socket?.readyState===WebSocket.OPEN&&this.socket.send(JSON.stringify({type:"input_audio_buffer.append",audio:function(e){let t=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),n="";for(let e=0;e<t.length;e+=8192)n+=String.fromCharCode(...t.subarray(e,e+8192));return btoa(n)}(e)}))},commit:e=>{this.session.commit(e),this.pendingFinals.add(e.id),this.socket?.readyState===WebSocket.OPEN&&this.socket.send(JSON.stringify({type:"input_audio_buffer.commit"}))}})}async start(){this.options.onState("connecting"),this.options.onModels("loading",0),this.options.onEnrollment("me",0);try{this.worker=new Worker("/interpreter-voice/worker.mjs",{type:"module"}),this.worker.onmessage=({data:e})=>this.workerMessage(e),this.worker.onerror=()=>{this.workerMessage({type:"speaker-failed"}),this.workerBusy=!1},this.worker.postMessage({type:"init"})}catch{this.workerMessage({type:"speaker-failed"})}try{let e=new AudioContext({sampleRate:24e3});this.context=e;let t=e.resume(),n=navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0}}).catch(e=>{throw Error(e instanceof DOMException&&/NotAllowed|Security/.test(e.name)?"mic-denied":"mic-unavailable")}).then(e=>(this.stream=e,this.disposed&&e.getTracks().forEach(e=>e.stop()),e)),[r]=await Promise.all([n,t]);if(this.stopping||this.disposed)return;let s=await fetch("/api/live/transcribe-secret",{method:"POST",headers:{"Content-Type":"application/json"},signal:this.abort.signal,body:JSON.stringify({mine:this.options.mine.code,theirs:this.options.theirs.code})});if(this.stopping||this.disposed)return;if(!s.ok)throw Error(401===s.status?"auth":"upstream");let{secret:a}=await s.json();if(this.stopping||this.disposed||(await this.connect(a),await t,await e.audioWorklet.addModule("/interpreter-draft/capture.js"),this.stopping||this.disposed))return;this.node=new AudioWorkletNode(e,"interpreter-draft-capture",{numberOfOutputs:0,processorOptions:{chunkSamples:2400}}),this.node.port.onmessage=({data:e})=>this.capture(new Int16Array(e)),this.source=e.createMediaStreamSource(r),this.source.connect(this.node),this.options.onState("live")}catch(t){if(this.disposed||this.stopping)return;let e=t instanceof Error&&["auth","mic-denied","mic-unavailable"].includes(t.message)?t.message:"upstream";this.options.onState("error",e),this.dispose()}}async connect(e){let t=Promise.withResolvers(),n=new WebSocket("wss://api.openai.com/v1/realtime?intent=transcription",["realtime",`openai-insecure-api-key.${e}`]);this.socket=n;let r=setTimeout(()=>t.reject(Error("upstream")),15e3);n.onmessage=({data:e})=>{let n=JSON.parse(String(e));if("session.created"===n.type||"session.updated"===n.type)t.resolve();else if("input_audio_buffer.committed"===n.type)this.session.committed(n.item_id);else if("conversation.item.input_audio_transcription.delta"===n.type)this.session.transcript(n.item_id,n.delta??"",!1);else if("conversation.item.input_audio_transcription.completed"===n.type||"conversation.item.input_audio_transcription.failed"===n.type){let e=n.type.endsWith(".failed")?this.session.failed(n.item_id):this.session.transcript(n.item_id,n.transcript??"",!0);if(e&&this.pendingFinals.delete(e.id),!this.pendingFinals.size)for(let e of this.finalWaiters.splice(0))e()}else if("error"===n.type){for(let e of(t.reject(Error("upstream")),this.stopFailure="upstream",this.finalWaiters.splice(0)))e();this.disposed||this.stop("upstream")}},n.onerror=()=>{for(let e of(t.reject(Error("upstream")),this.stopFailure="upstream",this.finalWaiters.splice(0)))e();this.disposed||this.stop("upstream")},n.onclose=()=>{for(let e of(t.reject(Error("upstream")),this.finalWaiters.splice(0)))e();this.disposed||this.stopping||this.stop("upstream")};try{await t.promise}finally{clearTimeout(r)}}capture(e){var t,n;if(this.disposed||this.stopping||this.socket?.readyState!==WebSocket.OPEN)return;let r=wk(e),s=0;for(let e of r)s+=e*e;this.enrollment&&!this.pendingEnrollment&&s/r.length>=144e-6&&this.enrollmentSize<48e3&&(this.enrollmentAudio.push(r),this.enrollmentSize+=r.length,this.options.onEnrollment(this.enrollment,this.enrollmentSize/16e3,this.enrollmentFailed)),this.turns.push(e,this.speakerReady?this.enrollment??void 0:void 0);let a=this.turns.current;if(a&&(t=this.session.utterances.get(a.id)?.text??"",(n=this.turns.now-a.startMs)>=8e3&&t.trim().length>=40&&(/[.!?。!?]\s*$/u.test(t)||n>=15e3))&&this.turns.finish(),this.analysisRing.copyWithin(0,r.length),this.analysisRing.set(r,this.analysisRing.length-r.length),this.analysisSize=Math.min(this.analysisRing.length,this.analysisSize+r.length),this.turns.now>=this.nextAnalysis&&this.analysisSize>=16e3&&!this.workerBusy&&this.worker){this.nextAnalysis=this.turns.now+250,this.workerBusy=!0;let e=this.analysisRing.slice(this.analysisRing.length-this.analysisSize);this.worker.postMessage({type:"analyze",samples:e,endMs:this.turns.now,epoch:this.identityEpoch},[e.buffer])}}workerMessage(e){if(!this.disposed&&!this.stopping){if("progress"===e.type)this.options.onModels("loading",e.percent??0);else if("speaker-ready"===e.type)this.speakerReady=!0,this.turns.holdMs=1500,this.options.onModels("ready",100);else if("speaker-failed"===e.type)this.speakerReady=!1,this.turns.holdMs=0,this.options.onModels("failed",0),this.enrollment=null,this.pendingEnrollment=void 0,this.enrollmentAudio=[],this.enrollmentSize=0,this.options.onEnrollment(null,0);else if("enrolled"===e.type&&e.side){if(this.pendingEnrollment===e.side){if(this.pendingEnrollment=void 0,!e.ok){this.enrollmentFailed=!0,this.enrollmentAudio=[],this.enrollmentSize=0,this.options.onEnrollment(this.enrollment,0,!0);return}this.confirmedSides.add(e.side),this.enrollmentFailed=!1,this.enrollment="me"===e.side?"them":null,this.enrollmentAudio=[],this.enrollmentSize=0,this.options.onEnrollment(this.enrollment,0)}}else if("analysis"===e.type||"analysis-error"===e.type){if(this.workerBusy=!1,void 0!==e.epoch&&e.epoch!==this.identityEpoch||"analysis-error"===e.type)return;(e.overlapFrames??0)>=Math.max(2,.1*(e.speechFrames??0))&&this.options.onOverlap();let t={endMs:e.endMs??this.turns.now,matches:e.matches??[]},n=this.turns.current?(t.endMs-this.turns.current.startMs)/1e3:0,r=this.speakerReady?this.enrollment??function(e,t){if(t<1||!e.length)return;let n=[...e].sort((e,t)=>t.score-e.score);return n[0].score>=.45&&(!n[1]||n[0].score-n[1].score>=.12)?n[0].side:void 0}(t.matches,n)??function(e,t){if(1===e.length&&!(t<1)&&e[0].score<=.3)return"me"===e[0].side?"them":"me"}(t.matches,n):void 0;r&&this.turns.current&&t.endMs>=this.turns.current.startMs+500&&(this.turns.identify(r,function(e,t,n,r){if(!e||!n||n===r)return t.endMs-500;let s=e=>1===e.length?(e[0].side===n?1:-1)*(e[0].score-.45):(e.find(e=>e.side===n)?.score??0)-(e.find(e=>e.side===r)?.score??0),a=s(e.matches),i=s(t.matches);return(a>=0&&i<0?e.endMs+(t.endMs-e.endMs)*a/(a-i):t.endMs)-500}(this.lastAnalysis,t,this.turns.current?.side,r)),this.turns.current&&this.session.direction(this.turns.current.id,r)),r&&(this.lastAnalysis=t)}}}nextEnrollment(){if(!this.enrollment||this.pendingEnrollment||!this.speakerReady||this.enrollmentSize<16e3)return;this.enrollmentFailed=!1;let e=new Float32Array(this.enrollmentSize),t=0;for(let n of this.enrollmentAudio)e.set(n,t),t+=n.length;this.pendingEnrollment=this.enrollment,this.worker?.postMessage({type:"enroll",side:this.enrollment,samples:e},[e.buffer]),this.turns.finish(),this.enrollmentAudio=[],this.enrollmentSize=0,this.options.onEnrollment(this.enrollment,0)}skipEnrollment(){let e=this.turns.current?.id;this.identityEpoch++,this.lastAnalysis=void 0,this.confirmedSides.size?this.pendingEnrollment&&!this.confirmedSides.has(this.pendingEnrollment)&&this.worker?.postMessage({type:"remove",side:this.pendingEnrollment}):this.worker?.postMessage({type:"reset"}),this.turns.releaseIdentity(),this.session.releaseDirection(e),this.turns.finish(),this.enrollment=null,this.pendingEnrollment=void 0,this.enrollmentAudio=[],this.enrollmentSize=0,this.enrollmentFailed=!1,this.options.onEnrollment(null,0)}enrollAudio(e,t){let n=this.audio.get(e);if(!n||n.size<24e3)return;let r=new Int16Array(n.size),s=0;for(let e of n.chunks)r.set(e,s),s+=e.length;let a=wk(r);this.worker?.postMessage({type:"enroll",side:t,samples:a},[a.buffer])}correct(e,t){this.identityEpoch++,this.turns.correct(e,t),this.lastAnalysis=void 0,this.session.correct(e,t),this.enrollAudio(e,t)}async stop(e){if(!this.disposed&&!this.stopping){if(this.stopping=!0,this.stopFailure??=e,!this.socket){this.dispose(),this.options.onState(e?"error":"idle",e);return}if(this.stream?.getTracks().forEach(e=>e.stop()),this.source?.disconnect(),this.node?.disconnect(),this.turns.finish(),this.options.onEnrollment(null,0),this.options.onState(e?"error":"working",e),this.pendingFinals.size&&!e){let e=Promise.withResolvers();this.finalWaiters.push(e.resolve);let t=setTimeout(e.resolve,15e3);await e.promise,clearTimeout(t)}this.disposed||(this.socket&&(this.socket.onmessage=null),this.session.completeInput(),await this.session.whenIdle(),this.disposed||(this.stream?.getTracks().forEach(e=>e.stop()),this.source?.disconnect(),this.node?.disconnect(),this.playbackQueue.then(()=>{this.disposed||this.context?.close().catch(()=>{})}),this.socket?.close(1e3),this.worker?.terminate(),clearTimeout(this.guardTimer),this.audio.clear(),this.enrollmentAudio=[],this.analysisRing.fill(0),this.options.onState(this.stopFailure?"error":"idle",this.stopFailure)))}}dispose(){if(!this.disposed)for(let e of(this.disposed=!0,this.abort.abort(),this.session.close(),this.stream?.getTracks().forEach(e=>e.stop()),this.source?.disconnect(),this.node?.disconnect(),this.context?.close().catch(()=>{}),this.socket&&(this.socket.onmessage=null),this.socket?.close(1e3),this.worker?.terminate(),clearTimeout(this.guardTimer),this.audio.clear(),this.enrollmentAudio=[],this.analysisRing.fill(0),this.finalWaiters.splice(0)))e()}}function wS(e){window.clearInterval(e.clock),e.session?.close(),e.stream?.getTracks().forEach(e=>e.stop())}let wC=()=>()=>{},wN=()=>"function"==typeof WebSocket&&"function"==typeof AudioContext&&"function"==typeof AudioWorkletNode&&!!navigator.mediaDevices?.getUserMedia;function wT(e,t,n,r,s,a){let i=`${n}:${t.id}`,l="me"===t.side?r.mine:"them"===t.side?r.theirs:void 0,o=a??("me"===t.side?r.theirs:"them"===t.side?r.mine:void 0),c=[...e.segments],d=e.nextId,u=(n,a,l,o)=>{let u=c.findIndex(e=>e.utterance===i&&e.role===n);if(!a.trim()&&-1===u)return;let h={id:-1===u?d++:c[u].id,role:n,text:a,final:l,...r,call:e.call,at:s+t.startMs+.01*("assistant"===n),utterance:i,side:t.side,language:o,translationError:t.translationError};-1===u?c.push(h):c[u]=h};return u("user",t.text,t.closed,l),u("assistant",t.translation,t.final,o),c.sort((e,t)=>e.at-t.at||e.id-t.id),{...e,segments:c,nextId:d}}let wI="cuelo-translator",wM=[.85,1,1.3];function wE(e){return"codex"===e||"fast"===e?e:"voice"}function w$(){let e={mine:yO[0],theirs:yO[1],profile:{},face:!1,size:1,voice:!1,echoGuard:!0,naturalVoice:!1,noiseSuppression:!1,fastDrafts:!1,engine:"voice",assistMeaning:!0};try{let t=JSON.parse(window.localStorage.getItem(wI)??"null");if(!t||"object"!=typeof t)return e;let n=yD(t.mine)??e.mine,r=yD(t.theirs)??e.theirs,s=n.code===r.code?{mine:e.mine,theirs:e.theirs}:{mine:n,theirs:r},a="number"==typeof t.size&&Number.isInteger(t.size)&&t.size>=0&&t.size<wM.length?t.size:1;return{...s,profile:yF(t.profile),face:!0===t.face,size:a,voice:!0===t.voice,echoGuard:!1!==t.echoGuard,naturalVoice:!0===t.naturalVoice,noiseSuppression:!0===t.noiseSuppression,fastDrafts:!0===t.fastDrafts,engine:wE(t.engine),assistMeaning:!1!==t.assistMeaning}}catch{return e}}function wR(){try{return bK(window.localStorage.getItem(bV))}catch{return bK(null)}}function wL(e){try{if(e.some(e=>e.text.trim()))window.localStorage.setItem(bV,JSON.stringify({v:1,segments:e.filter(e=>e.text.trim()).slice(-200).map(({role:e,text:t,mine:n,theirs:r,at:s,side:a,language:i,utterance:l})=>({role:e,text:t,mine:n.code,theirs:r.code,at:s,...a?{side:a}:{},...i?{language:i.code}:{},...l?{utterance:l}:{}}))}));else window.localStorage.removeItem(bV)}catch{}}function wP(){return(0,r.jsxs)("svg",{width:"22",height:"22",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("rect",{x:"9",y:"3",width:"6",height:"11",rx:"3"}),(0,r.jsx)("path",{d:"M5 11a7 7 0 0 0 14 0M12 18v3"})]})}function wA(){return(0,r.jsx)("svg",{width:"22",height:"22",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",children:(0,r.jsx)("rect",{x:"6",y:"6",width:"12",height:"12",rx:"2.5"})})}function w_(){return(0,r.jsx)("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:(0,r.jsx)("path",{d:"M15 5l-7 7 7 7"})})}function wF(){return(0,r.jsxs)("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("rect",{x:"5",y:"2.5",width:"14",height:"19",rx:"2.5"}),(0,r.jsx)("path",{d:"M5 12h14M9 7.5h6M9 16.5h6M12 5.5v2M12 16.5v2"})]})}function wO(){return(0,r.jsx)("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:"M6 9l6 6 6-6"})})}function wz(){return(0,r.jsx)("svg",{width:"18",height:"18",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 6L6 18"})})}function wD(){return(0,r.jsxs)("svg",{width:"20",height:"20",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:"M12 15V4M8 8l4-4 4 4"}),(0,r.jsx)("path",{d:"M6 12v6.5A1.5 1.5 0 0 0 7.5 20h9a1.5 1.5 0 0 0 1.5-1.5V12"})]})}function wW(){return(0,r.jsxs)("svg",{width:"20",height:"20",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:"M5 4.5h14a1.5 1.5 0 0 1 1.5 1.5v9a1.5 1.5 0 0 1-1.5 1.5h-7l-4.5 3.5v-3.5H5A1.5 1.5 0 0 1 3.5 15V6A1.5 1.5 0 0 1 5 4.5z"}),(0,r.jsx)("path",{d:"M8 9h8M8 12.5h5"})]})}function wH({lines:e,language:t,unknownLabel:n,flipped:s,emptyHint:a,onShow:i,showLabel:l}){let o=e.map(e=>({line:e,known:e.language??bc(e.segment)})).filter(({known:e})=>void 0===e||e.code===t.code).slice(-3);return(0,r.jsxs)("div",{className:"translator-face-pane","data-flipped":s?"true":void 0,lang:t.tag,children:[(0,r.jsx)("p",{className:"translator-face-label",children:t.nativeName}),(0,r.jsxs)("div",{className:"translator-face-lines",children:[0===o.length&&a?(0,r.jsx)("p",{className:"translator-face-empty",children:a}):null,o.map(({line:e,known:a},c)=>(0,r.jsxs)("button",{type:"button",className:"translator-face-line",title:l,"data-latest":c===o.length-1?"true":void 0,"data-side":(e.language?bu(e.segment,e.language):bd(e.segment))??"them","data-draft":e.draft?"true":void 0,"data-language":a?void 0:"unknown",lang:a?void 0:"",onClick:()=>i({text:e.segment.text,language:a??t,flipped:s}),children:[a?null:(0,r.jsx)("span",{className:"translator-face-unknown",children:n}),(0,r.jsx)(wU,{text:e.segment.text})]},e.key))]})]})}function wU({text:e}){return(0,r.jsx)(r.Fragment,{children:(function(e){let t=[],n=0;for(let r of e.matchAll(yQ)){let s=r.index??0;s>n&&t.push({text:e.slice(n,s),number:!1}),t.push({text:r[0],number:!0}),n=s+r[0].length}return n<e.length&&t.push({text:e.slice(n),number:!1}),t})(e).map((e,t)=>e.number?(0,r.jsx)("span",{className:"translator-number",children:e.text},t):e.text)})}function wB({label:e,turns:t,visible:n,pending:a,jumpLabel:i,layoutKey:l,onShow:o,speech:c,renderAssist:d,onCorrect:u,correctionConnection:h}){let p=(0,s.useRef)(null),m=(0,s.useRef)(!0),[f,g]=(0,s.useState)(!1);return(0,s.useEffect)(()=>{let e=p.current;if(!e)return;let t=()=>{m.current&&(e.scrollTop=e.scrollHeight)};t();let n=new ResizeObserver(t);for(let t of e.children)n.observe(t);return()=>n.disconnect()},[t,a,l]),(0,r.jsxs)("section",{className:"translator-conversation","aria-label":e,children:[(0,r.jsxs)("div",{ref:p,className:"translator-log",role:"log","aria-label":e,onScroll:()=>{let e=p.current;e&&(m.current=e.scrollHeight-e.scrollTop-e.clientHeight<=32,g(!m.current))},children:[t.map((e,s)=>(0,r.jsx)(bU,{turn:e,latest:s===t.length-1,visible:n,speech:c,onShow:o,onCorrect:u&&e.voiceLines.some(e=>e.segment.utterance?.startsWith(`${h}:`)&&!e.segment.restored)?()=>u(e):void 0,renderText:e=>(0,r.jsx)(wU,{text:e}),children:d(e)},e.key)),a?(0,r.jsx)("p",{className:"translator-pending",children:a}):null]}),f?(0,r.jsx)("button",{type:"button",className:"translator-jump",onClick:()=>{let e=p.current;e&&(m.current=!0,g(!1),e.scrollTop=e.scrollHeight)},children:i}):null]})}function wq({visible:e=!0,onBack:t}){var n;let a,i,o,{tt:c,locale:d}=er(),[u,h]=(0,s.useState)(w$),[p,m]=(0,s.useState)(!1),{mine:f,theirs:g,profile:x,face:v,size:y,voice:b,echoGuard:w,naturalVoice:k,noiseSuppression:j,fastDrafts:S,assistMeaning:C,engine:N}=u,T=bz["ko"===d?"ko":"en"],I=function({mine:e,theirs:t,profile:n,visible:a,open:i,assistSettings:l}){let{tt:o}=er(),[c,d]=(0,s.useState)(e.code),[u,h]=(0,s.useState)(""),[p,m]=(0,s.useState)([]),[f,g]=(0,s.useState)(!1),[x,v]=(0,s.useState)(null),[y,b]=(0,s.useState)(null),w=(0,s.useRef)(null),k=(0,s.useRef)(new Set),j=(0,s.useRef)(0),S=(0,s.useRef)(!1),C=(0,s.useRef)(null),N=c===e.code?e:t,T=c===e.code?t:e,I=(n,r,s,a)=>{let i=r.code===e.code?"mine":"theirs";return{id:String(n),mine:e.code,theirs:t.code,speaker:i,text:s,..."mine"===i?{interpretation:a}:{}}},M=bT([...p.map(e=>I(e.id,e.source,e.original,e.translation)),...y&&y.source.code===t.code?[I(y.id,y.source,y.original)]:[]],l,{profile:n,history:p.flatMap(e=>[{role:"user",text:e.original},{role:"assistant",text:e.translation}]).slice(-24)},a);(0,s.useEffect)(()=>{let e=()=>{for(let e of k.current)e.abort();k.current.clear()};return a||(w.current?.abort(),w.current=null,e(),g(!1),b(null)),()=>{w.current?.abort(),w.current=null,e()}},[a]),(0,s.useEffect)(()=>{i&&C.current?.focus()},[i]);let E=(0,s.useCallback)(()=>{for(let e of(w.current?.abort(),w.current=null,k.current))e.abort();k.current.clear(),m([]),b(null),g(!1),v(null),h("")},[]);(0,s.useEffect)(()=>{E(),d(e.code)},[E,e.code,t.code]);let $=async r=>{if(r.preventDefault(),S.current||w.current||!u.trim())return;let s=new AbortController;w.current=s,g(!0),v(null);let a=u.trim(),i=Date.now();b({id:j.current,at:i,source:N,target:T,original:a,translation:""});let l=null;try{let r=await fetch("/api/live/interpret/text",{method:"POST",headers:{"Content-Type":"application/json"},signal:s.signal,body:JSON.stringify({mine:e.code,theirs:t.code,source:N.code,profile:n,text:a,history:p.flatMap(e=>[{role:"user",text:e.original},{role:"assistant",text:e.translation}]).slice(-24)})});if(!r.ok){let e=await r.json();w.current!==s||s.signal.aborted||v("live-auth"===e.error?"live-auth":"live-upstream");return}if(!r.body||!r.headers.get("Content-Type")?.includes("text/event-stream"))throw Error("Invalid translation response");for await(let e of bj(r.body)){if(s.signal.aborted||null===l&&w.current!==s)return;if("delta"===e.type)null===l&&b(t=>t?{...t,translation:t.translation+e.text}:null);else if("error"===e.type)null===l&&v(e.error);else{if(e.source!==N.code||e.target!==T.code)throw Error("Invalid translation direction");let t="done"===e.type?e.reading:void 0;if(null===l){let n=j.current++;l=n,m(r=>[...r,{id:n,at:i,source:N,target:T,original:a,translation:e.text,...t?{reading:t}:{}}].slice(-12)),b(null),h(""),k.current.add(s),w.current=null,g(!1),C.current?.focus()}else if(t){let e=l;m(n=>n.map(n=>n.id===e?{...n,reading:t}:n))}}}}catch{w.current!==s||s.signal.aborted||null!==l||v("live-upstream")}finally{k.current.delete(s),w.current===s&&(w.current=null,g(!1),b(null),C.current?.focus())}};return{turns:p,provisional:y,assists:M,composer:i?(0,r.jsxs)("form",{className:bk().composer,onSubmit:$,"aria-label":o("translator.keyboard"),children:[(0,r.jsx)("div",{className:bk().direction,children:(0,r.jsxs)("button",{type:"button","aria-label":o("translator.swapDirection"),onClick:()=>{var e;return e=T.code,void(w.current?.abort(),w.current=null,g(!1),b(null),v(null),d(e))},children:[(0,r.jsx)("span",{lang:N.tag,children:N.nativeName})," → ",(0,r.jsx)("span",{lang:T.tag,children:T.nativeName})]})}),(0,r.jsxs)("div",{className:bk().inputRow,children:[(0,r.jsxs)("label",{className:bk().field,children:[(0,r.jsx)("span",{className:"sr-only",children:o("translator.typeLabel")}),(0,r.jsx)("textarea",{ref:C,value:u,lang:N.tag,maxLength:2e3,rows:2,readOnly:f,"aria-busy":f,placeholder:o("translator.typePlaceholder"),onChange:e=>h(e.target.value),onCompositionStart:()=>{S.current=!0},onCompositionEnd:()=>{S.current=!1}})]}),(0,r.jsx)("button",{className:bk().submit,type:"submit","aria-label":o(f?"translator.typePending":"translator.typeSubmit"),disabled:f||!u.trim(),children:(0,r.jsx)(bS.A,{size:20,"aria-hidden":"true"})})]}),x?(0,r.jsx)("p",{className:bk().error,role:"alert",children:o("live-auth"===x?"translator.typeAuth":"translator.typeError")}):null]}):null,clear:E}}({mine:f,theirs:g,profile:x,visible:e,open:p,assistSettings:{meaning:C}}),M=(0,s.useRef)(null);(0,s.useEffect)(()=>{if(!e)return;let t=e=>{let t=M.current;t?.open&&e.target instanceof Node&&!t.contains(e.target)&&(t.open=!1)};return document.addEventListener("pointerdown",t,!0),()=>document.removeEventListener("pointerdown",t,!0)},[e]);let[E]=(0,s.useState)(wR),[$,R]=(0,s.useState)(E.segments),[L,P]=(0,s.useState)(!1),A=(0,s.useRef)(E),[_,F]=(0,s.useState)(0),O=(0,s.useRef)(u),[z,D]=(0,s.useState)(null),[W,H]=(0,s.useState)(!1),[U,B]=(0,s.useState)(!1),[q,V]=(0,s.useState)(null);(0,s.useEffect)(()=>{window.localStorage.setItem(wI,JSON.stringify({mine:f.code,theirs:g.code,profile:x,face:v,size:y,voice:b,echoGuard:w,naturalVoice:k,noiseSuppression:j,fastDrafts:S,engine:N,assistMeaning:C}))},[C,w,N,v,S,f,k,j,x,y,g,b]);let K=(0,s.useRef)(()=>{}),J=function({onTranscript:e,getHistory:t,onReconnect:n,muteMicWhilePlaying:r=!1,playVoice:a=!0,suppressNoise:i=!1}){let[l,o]=(0,s.useState)("idle"),[c,d]=(0,s.useState)(null),[u,h]=(0,s.useState)(null),[p,m]=(0,s.useState)(null),[f,g]=(0,s.useState)(!1),[x,v]=(0,s.useState)(null),[y,b]=(0,s.useState)(!1),[w,k]=(0,s.useState)(null),j=(0,s.useRef)(!1),S=(0,s.useRef)(new Set),C=(0,s.useCallback)(e=>{if(j.current!==e)for(let t of(j.current=e,S.current))t(e)},[]),N=(0,s.useRef)(null),T=(0,s.useRef)(null),I=(0,s.useRef)(null),M=(0,s.useRef)(null),E=(0,s.useRef)(null),$=(0,s.useRef)(null),R=(0,s.useRef)(null),L=(0,s.useRef)(null),P=(0,s.useRef)(null),A=(0,s.useRef)(!1),_=(0,s.useRef)(!1),F=(0,s.useRef)(!1),O=(0,s.useRef)(0),z=(0,s.useRef)([]),D=(0,s.useRef)(0),W=(0,s.useRef)(!1),H=(0,s.useRef)(void 0),U=(0,s.useRef)(void 0),B=(0,s.useRef)(0),q=(0,s.useRef)(e),V=(0,s.useRef)(t),K=(0,s.useRef)(n),J=(0,s.useRef)(r),G=(0,s.useRef)(a),Y=(0,s.useRef)(i),Z=(0,s.useRef)(null),Q=(0,s.useRef)(null),X=(0,s.useRef)(null),ee=(0,s.useRef)(Promise.resolve()),et=(0,s.useRef)(async()=>{});(0,s.useEffect)(()=>{q.current=e,V.current=t,K.current=n,J.current=r,G.current=a,E.current&&(E.current.muted=!a)},[t,r,n,e,a]),(0,s.useEffect)(()=>{m("u">typeof RTCPeerConnection&&"u">typeof navigator&&"function"==typeof navigator.mediaDevices?.getUserMedia)},[]);let en=(0,s.useCallback)(()=>{B.current+=1;let e=L.current;L.current=null,_.current=!1,F.current=!1,window.clearTimeout(U.current),U.current=void 0,window.clearTimeout(H.current),H.current=void 0,R.current?.close(),R.current=null,N.current?.close(),N.current=null,T.current=null,I.current=null,e&&bg(e)},[]),er=(0,s.useCallback)(()=>{let e=$.current;$.current=null,e&&(window.clearInterval(e.timer),e.source?.disconnect(),"closed"!==e.context.state&&e.context.close().catch(()=>{}))},[]),es=(0,s.useCallback)(()=>{let e=Z.current;Z.current=null,e?.close()},[]),ea=(0,s.useCallback)(()=>{let e=$.current,t=M.current?.getAudioTracks()[0];if(!e||!t)return;e.analyser.getFloatTimeDomainData(e.samples);let n=e.gate.update(function(e){if(0===e.length)return 0;let t=0;for(let n of e)t+=n*n;return Math.sqrt(t/e.length)}(e.samples)>=.01,performance.now()),r=J.current&&G.current&&n;t.enabled===r&&(t.enabled=!r),C(r),Z.current?.setMuted(r)},[C]),ei=(0,s.useCallback)(()=>{if(er(),"function"!=typeof window.AudioContext)return;let e=null;try{(e=new window.AudioContext).resume().catch(()=>{});let t=e.createAnalyser();t.fftSize=1024;let n=e.createGain();n.gain.value=0,t.connect(n),n.connect(e.destination),$.current={context:e,analyser:t,samples:new Float32Array(t.fftSize),source:null,remote:null,gate:new bf,timer:window.setInterval(ea,50)}}catch(t){e&&"closed"!==e.state&&e.close().catch(()=>{}),console.warn("[interpreter] echo guard unavailable:",t instanceof Error?t.message:String(t))}},[ea,er]),el=(0,s.useCallback)(()=>{for(let e of(en(),er(),X.current?.abort(),k(null),C(!1),es(),Q.current=null,P.current=null,A.current=!1,M.current?.getTracks()??[]))e.stop();M.current=null;let e=E.current;E.current=null,e&&(e.srcObject=null,e.remove())},[es,en,C,er]),eo=(0,s.useCallback)(e=>{el(),g(!1),b(!1),o(e)},[el]),ec=(0,s.useCallback)((e,t)=>{A.current?(d(e),h(t??null),eo("error")):el()},[el,eo]),ed=(0,s.useCallback)(()=>A.current&&_.current&&F.current,[]),eu=(0,s.useCallback)(e=>{B.current===e&&ed()&&(g(!1),W.current=!0,o("live"))},[ed]),eh=(0,s.useCallback)(()=>{let e=I.current;if(!e)return;let t=E.current;t&&t.srcObject!==e&&(t.srcObject=e);let n=$.current;if(n&&n.remote!==e){n.source?.disconnect(),n.source=null,n.remote=e;try{n.source=n.context.createMediaStreamSource(e),n.source.connect(n.analyser)}catch(e){console.warn("[interpreter] echo guard cannot read the interpreted voice:",e instanceof Error?e.message:String(e))}}},[]),ep=(0,s.useCallback)(async e=>{let t=e.getAudioTracks()[0]??null;if(!t)return null;if(Y.current&&!Z.current&&Q.current!==e){let t=new AbortController;X.current=t;let n=window.setTimeout(()=>t.abort(),3e3);try{Z.current=await bm(e,t=>{M.current===e&&(console.warn("[interpreter] noise suppression stopped, using the raw microphone:",t),Q.current=e,es(),et.current(B.current,e).catch(()=>{}))},t.signal)}catch(t){Y.current&&M.current===e&&(Q.current=e,console.warn("[interpreter] noise suppression unavailable, using the raw microphone:",t instanceof Error?t.message:String(t)))}finally{window.clearTimeout(n),X.current===t&&(X.current=null)}M.current!==e&&es()}return Y.current&&M.current===e&&Z.current?Z.current.track:t},[es]),em=(0,s.useCallback)((e,t)=>{let n=async()=>{let n=T.current;if(B.current!==e||!n)return;let r=await ep(t);if(B.current!==e||T.current!==n)return;let s=t.getAudioTracks()[0]??null;await bx(s,r===s);try{await n.replaceTrack(r)}catch(e){if(r===s)throw e;console.warn("[interpreter] the call refused the denoised track, using the raw microphone:",e instanceof Error?e.message:String(e)),Q.current=t,es(),await bx(s,!0),await n.replaceTrack(s),k(s);return}k(r),Z.current&&Z.current.track!==r&&es()},r=ee.current.then(n);return ee.current=r.catch(()=>{}),r},[ep,es]);(0,s.useEffect)(()=>{et.current=em},[em]),(0,s.useEffect)(()=>{Y.current=i,Q.current=null,i||X.current?.abort();let e=M.current;e&&T.current&&em(B.current,e).catch(e=>{console.warn("[interpreter] cannot switch the microphone track:",e instanceof Error?e.message:String(e))})},[em,i]);let ef=(0,s.useCallback)(async(e,t)=>{if(B.current===e&&T.current){try{await em(e,t)}catch(t){B.current===e&&ec("failed",t instanceof Error?t.message:String(t));return}B.current===e&&(F.current=!0,eh(),eu(e))}},[eh,ec,em,eu]),eg=(0,s.useRef)(()=>{}),ex=(0,s.useCallback)((e,t)=>{A.current&&W.current&&M.current&&"auth"!==e?eg.current({reason:e,message:t}):ec(e,t)},[ec]),ev=(0,s.useCallback)(async(e,t)=>{try{let n,r,s=new RTCPeerConnection;if(N.current=s,T.current=s.addTransceiver("audio",{direction:"sendrecv"}).sender,s.ontrack=t=>{B.current===e&&N.current===s&&(I.current=t.streams[0]??new MediaStream([t.track]),eh())},s.onconnectionstatechange=()=>{B.current===e&&"failed"===s.connectionState&&ex("failed","connection failed")},await s.setLocalDescription(await s.createOffer()),await dD(s),B.current!==e)return!1;let a=s.localDescription?.sdp;if(!a)throw Error("The browser produced no offer SDP.");let i=await fetch("/api/live/interpret",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sdp:a,mine:t.mine.code,theirs:t.theirs.code,context:{profile:t.profile,history:function(e,t){if(0===t.length)return e;let n=new Set(t.map(e=>e.id));return e.filter(e=>!n.has(e.id))}(V.current(),z.current)}})}),l=await i.json().catch(()=>({})),c="",d="";if(l&&"object"==typeof l&&("error"in l&&(n=l.error),"message"in l&&"string"==typeof l.message&&(r=l.message),"callId"in l&&"string"==typeof l.callId&&(c=l.callId),"sdp"in l&&"string"==typeof l.sdp&&(d=l.sdp)),!i.ok||!c||!d)return B.current===e&&ex(dW(i.status,n),r),!1;if(B.current!==e)return bg(c),!1;if(await s.setRemoteDescription({type:"answer",sdp:d}),B.current!==e)return s.close(),bg(c),!1;L.current=c;let u=new EventSource(`/api/live/events?callId=${encodeURIComponent(c)}`);return R.current=u,u.onmessage=t=>{let n;if(B.current===e){try{n=JSON.parse(t.data)}catch{return}if(n&&"object"==typeof n&&"type"in n){var r,s;if("state"===n.type&&"state"in n){if("string"!=typeof n.state||(r=n.state,!0!==dz[r]))return;"connecting"===n.state||"live"===n.state||"working"===n.state?ed()&&o(n.state):"error"===n.state?ex("upstream",n.state):A.current&&W.current&&M.current?eg.current():A.current?eo(n.state):el();return}if("transcript"===n.type&&"role"in n&&"text"in n&&"final"in n){A.current&&("user"===n.role||"assistant"===n.role)&&"string"==typeof n.text&&(n.text.trim()&&(O.current=0),"user"===n.role&&n.text.trim()&&(D.current=0),"assistant"===n.role&&n.text.trim()&&b(!1),q.current({role:n.role,text:n.text,final:!0===n.final}));return}if("generation-stopped"===n.type){let e;if(!A.current)return;b(!0),z.current.push(...(e=(s=V.current()).findLastIndex(e=>"user"===e.role))<0?[]:s.slice(e)),D.current+=1,D.current>2?ec("upstream","Codex stopped the interpretation repeatedly."):W.current&&M.current&&eg.current();return}"error"===n.type&&"message"in n&&"string"==typeof n.message&&ex("upstream",n.message)}}},u.onerror=()=>{B.current===e&&L.current&&ex("failed")},_.current=!0,eu(e),!0}catch(t){return B.current===e&&ex("failed",t instanceof Error?t.message:String(t)),!1}},[eh,ec,ed,ex,el,eu,eo]),ey=(0,s.useCallback)(e=>{let t=P.current,n=M.current;if(!A.current||!t||!n)return;if(O.current+=1,O.current>10)return void(e?ec(e.reason,e.message):(v("idle"),eo("idle")));en();let r=B.current;g(!0),o("connecting"),K.current();let s=()=>{B.current===r&&ev(r,t).then(e=>{e&&ef(r,n)})};e?H.current=window.setTimeout(s,2e3):s()},[ef,en,ec,ev,eo]);(0,s.useEffect)(()=>{eg.current=ey},[ey]);let eb=(0,s.useCallback)(async e=>{let t;try{t=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!Y.current,autoGainControl:!0}})}catch(n){let t=n instanceof DOMException?n.name:"";B.current===e&&ec("NotAllowedError"===t||"SecurityError"===t?"mic-denied":"mic-unavailable");return}if(B.current!==e||!T.current){for(let e of t.getTracks())e.stop();return}M.current=t,await ef(e,t)},[ef,ec]),ew=(0,s.useCallback)((e,t,n)=>{let r={mine:e,theirs:t,profile:n};if(P.current&&bv(P.current)===bv(r)||A.current)return;el(),P.current=r;let s=B.current;U.current=window.setTimeout(()=>{B.current!==s||A.current||el()},25e3),ev(s,r)},[ev,el]),ek=(0,s.useCallback)((e,t,n)=>{let r={mine:e,theirs:t,profile:n},s=null!==P.current&&bv(P.current)===bv(r)&&!A.current&&null!==N.current;s||(el(),P.current=r),window.clearTimeout(U.current),U.current=void 0,A.current=!0,O.current=0,z.current=[],D.current=0,W.current=!1;let a=B.current;d(null),h(null),v(null),g(!1),b(!1),o("connecting");let i=document.createElement("audio");i.autoplay=!0,i.muted=!G.current,E.current=i,ei(),eh(),s||ev(a,r),eb(a)},[eb,eh,ev,el,ei]),ej=(0,s.useCallback)(()=>eo("idle"),[eo]);return(0,s.useEffect)(()=>()=>el(),[el]),{state:l,failure:c,detail:u,supported:p,reconnecting:f,ended:x,skipped:y,sendTrack:w,isBlocked:(0,s.useCallback)(()=>j.current,[]),onBlockedChange:(0,s.useCallback)(e=>(S.current.add(e),()=>void S.current.delete(e)),[]),prepare:ew,start:ek,stop:ej}}({onTranscript:(0,s.useCallback)(e=>{A.current=function(e,t,n,r=Date.now()){let s=t.text.replace(/([.!?])(?=[\p{Lu}\p{Lo}])/gu,"$1 "),{segments:a,nextId:i}=e,l=e.open[t.role];if(null===l){if(!s.trim())return e;a=[...a,{id:l=i++,role:t.role,text:s,final:t.final,...n,call:e.call,at:r}]}else a=a.map(e=>e.id===l?{...e,text:s,final:t.final}:e);return{...e,segments:a,nextId:i,open:{...e.open,[t.role]:t.final?null:l}}}(A.current,e,O.current),R(A.current.segments),K.current(A.current.segments)},[]),getHistory:(0,s.useCallback)(()=>bh(A.current,24),[]),onReconnect:(0,s.useCallback)(()=>{A.current=bo(A.current),F(A.current.call)},[]),muteMicWhilePlaying:w,playVoice:b,suppressNoise:j}),G=function(e){let t=(0,s.useRef)(e);t.current=e;let n=(0,s.useRef)(null),[r,a]=(0,s.useState)("idle"),[i,l]=(0,s.useState)(""),[o,c]=(0,s.useState)(null),[d,u]=(0,s.useState)(null),[h,p]=(0,s.useState)({state:"loading",percent:0}),[m,f]=(0,s.useState)({side:null,seconds:0}),[g,x]=(0,s.useState)(!1),v=(0,s.useRef)(void 0);(0,s.useEffect)(()=>(u("function"==typeof WebSocket&&"function"==typeof AudioWorkletNode&&!!navigator.mediaDevices?.getUserMedia),()=>{n.current?.dispose(),window.clearTimeout(v.current)}),[]);let y=(0,s.useCallback)((e,r,s)=>{n.current?.dispose(),window.clearTimeout(v.current),x(!1),c(null);let i=crypto.randomUUID(),o=Date.now();l(i);let d=new wj({mine:e,theirs:r,profile:s,onUpdate:n=>t.current.onUtterance(n,i,o,{mine:e,theirs:r}),onState:(e,t)=>{a(e),t&&c(t)},onModels:(e,t)=>p({state:e,percent:t}),onEnrollment:(e,t,n)=>f({side:e,seconds:t,failed:n}),onOverlap:()=>{x(!0),window.clearTimeout(v.current),v.current=window.setTimeout(()=>x(!1),5e3)},playback:()=>({enabled:t.current.playVoice,echoGuard:t.current.echoGuard,natural:t.current.naturalVoice})});n.current=d,d.start()},[]),b=(0,s.useCallback)(()=>{n.current?.stop()},[]),w=(0,s.useCallback)(()=>{n.current?.dispose(),a("idle"),f({side:null,seconds:0}),x(!1),window.clearTimeout(v.current)},[]),k=(0,s.useCallback)((e,t)=>n.current?.correct(e,t),[]);return{state:r,failure:o,detail:null,supported:d,start:y,stop:b,shutdown:w,correct:k,models:h,enrollment:m,nextEnrollment:(0,s.useCallback)(()=>n.current?.nextEnrollment(),[]),skipEnrollment:(0,s.useCallback)(()=>n.current?.skipEnrollment(),[]),overlap:g,connectionId:i,reconnecting:!1,ended:null,skipped:!1,prepare:void 0}}({onUtterance:(0,s.useCallback)((e,t,n,r)=>{A.current=wT(A.current,e,t,r,n),R(A.current.segments)},[]),playVoice:b,echoGuard:w,naturalVoice:k}),Y=function(e){let t=(0,s.useRef)(e),n=(0,s.useRef)(null),[r,a]=(0,s.useState)("idle"),[i,l]=(0,s.useState)(null),o=(0,s.useSyncExternalStore)(wC,wN,()=>null);(0,s.useLayoutEffect)(()=>{t.current=e},[e]),(0,s.useEffect)(()=>()=>{let e=n.current;n.current=null,e&&wS(e)},[]);let c=(0,s.useCallback)(e=>{let t=n.current;t&&(n.current=null,t.turns.stop(performance.now()),wS(t),l(e??null),a(e?"error":"idle"))},[]),d=(0,s.useCallback)((e,r)=>{c(),l(null),a("connecting");let s={mine:e,theirs:r},i=`fast-${crypto.randomUUID()}`,o=Date.now()-performance.now(),d={turns:new bn(s,{update:e=>t.current.onTurn(e,i,o,s),remove:e=>t.current.onRemove(`${i}:${e}`),play:(e,n)=>{t.current.playVoice&&d.session?.play(e,n)},cancel:e=>d.session?.cancelPlayback(e)},t.current.playVoice)};n.current=d,d.session=bb({...s,onInput:(e,t)=>d.turns.input(e,t,performance.now()),onOutput:(e,t)=>d.turns.output(e,t,performance.now()),fast:{onAudio:(e,n)=>{if(!t.current.playVoice)return;let r=function(e){try{let t=atob(e);if(t.length%2)return;let n=new Int16Array(t.length/2);for(let e=0;e<n.length;e++)n[e]=t.charCodeAt(2*e)|t.charCodeAt(2*e+1)<<8;return n}catch{return}}(n);r&&d.turns.audio(e,r,performance.now())},onReady:()=>{n.current===d&&(a("live"),d.clock=window.setInterval(()=>d.turns.tick(performance.now()),250))},onFailure:e=>{n.current===d&&c(e)}}}),d.session.setEchoGuard(t.current.echoGuard),n.current===d&&navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0}}).then(e=>{if(n.current!==d)return void e.getTracks().forEach(e=>e.stop());d.stream=e;let t=e.getAudioTracks()[0];t&&"live"===t.readyState?(t.addEventListener("ended",()=>{n.current===d&&c("mic-unavailable")},{once:!0}),d.session?.setTrack(t)):c("mic-unavailable")}).catch(e=>{n.current===d&&c(e instanceof DOMException&&["NotAllowedError","SecurityError"].includes(e.name)?"mic-denied":"mic-unavailable")})},[c]);return(0,s.useLayoutEffect)(()=>{n.current?.turns.setVoice(e.playVoice)},[e.playVoice]),(0,s.useLayoutEffect)(()=>{n.current?.session?.setEchoGuard(e.echoGuard)},[e.echoGuard]),{state:r,failure:i,detail:null,supported:o,start:d,stop:(0,s.useCallback)(()=>c(),[c]),clear:(0,s.useCallback)(()=>n.current?.turns.clear(),[]),reconnecting:!1,ended:null,skipped:!1,prepare:void 0}}({playVoice:b,echoGuard:w,onTurn:(0,s.useCallback)((e,t,n,r)=>{let s=e.source?e.source.code===r.mine.code?"me":"them":void 0;A.current=wT(A.current,{id:e.id,text:e.input,startMs:e.startedAt,endMs:e.startedAt,side:s,translation:e.output,closed:e.final,final:e.final},t,r,n,e.target),R(A.current.segments)},[]),onRemove:(0,s.useCallback)(e=>{let t=A.current.segments.filter(t=>t.utterance!==e);A.current={...A.current,segments:t},R(t)},[])}),Z="codex"===N?J:"fast"===N?Y:G,Q="connecting"===Z.state||"live"===Z.state||"working"===Z.state,X=function({enabled:e,epoch:t,pairRef:n,segments:r,sendTrack:a,isBlocked:i,onBlockedChange:l}){let[o,c]=(0,s.useState)(()=>yX()),d=(0,s.useRef)(o),u=(0,s.useRef)(r),h=(0,s.useRef)(a),p=(0,s.useRef)(i),m=(0,s.useRef)(l),f=(0,s.useRef)(null),g=(0,s.useRef)(e),x=(0,s.useCallback)(e=>{d.current=e,c(e)},[]);(0,s.useEffect)(()=>{u.current=r,h.current=a,p.current=i,m.current=l,g.current=e});let v=(0,s.useCallback)(e=>{g.current&&x(bt(d.current,e,performance.now()))},[x]),y=(0,s.useCallback)(()=>{x(yX([],d.current))},[x]);(0,s.useEffect)(()=>{if(x(yX(u.current,d.current)),!e)return;let t=n.current,r=bb({mine:t.mine,theirs:t.theirs,isBlocked:()=>p.current(),onBlockedChange:e=>m.current(e),onInput:(e,n)=>x(function(e,t,n,r,s){let a;if(!r)return e;let i=(e.turns[n.code]??[]).map(e=>({...e})),l=i.at(-1),o=l?s-l.inputAt:1/0,c=void 0!==l&&o<=1500&&!(o>600&&y5(t,l.input,r)),d=e;return c&&l?(a=l,a.input+=r,a.inputAt=s):(a={id:d.nextTurnId,pair:t,target:n,input:r,output:"",inputAt:s,outputAt:-1/0,outputSince:s,echo:!1,dead:!1},d={...d,nextTurnId:d.nextTurnId+1},i.push(a)),y3(y7(d,n,i),t,n,a,s)}(d.current,t,e,n,performance.now())),onOutput:(e,n)=>x(function(e,t,n,r,s){if(!r)return e;let a=(e.turns[n.code]??[]).map(e=>({...e})),i=a.at(-1),l=[...a].reverse().find(e=>s-e.outputAt<=1200)??(i&&s-Math.max(i.inputAt,i.outputAt)<=1500?i:void 0),o=e;return l||(l={id:o.nextTurnId,pair:t,target:n,input:"",output:"",inputAt:s,outputAt:s,outputSince:s,echo:!1,dead:!1},o={...o,nextTurnId:o.nextTurnId+1},a.push(l)),l.output||(l.outputSince=s),l.output+=r,l.outputAt=s,y3(y7(o,n,a),t,n,l,s)}(d.current,t,e,n,performance.now()))});return f.current=r,r.setTrack(h.current),()=>{r.close(),f.current=null,x(yX(u.current,d.current))}},[x,e,t,n]),(0,s.useEffect)(()=>{f.current?.setTrack(a)},[a]);let b=o.drafts.length>0||Object.values(o.turns).some(e=>e.some(e=>be(o,e)));return(0,s.useEffect)(()=>{if(!b)return;let e=window.setInterval(()=>x(bt(d.current,u.current,performance.now())),250);return()=>window.clearInterval(e)},[x,b]),{state:o,reset:y,reconcile:v}}({enabled:"codex"===N&&S&&Q,epoch:_,pairRef:O,segments:$,sendTrack:J.sendTrack,isBlocked:J.isBlocked,onBlockedChange:J.onBlockedChange}),{reconcile:ee}=X;(0,s.useEffect)(()=>{K.current=ee},[ee]);let et=e=>{Y.stop(),O.current=e,A.current=bo(A.current),F(A.current.call),"codex"===e.engine?(G.shutdown(),J.start(e.mine,e.theirs,e.profile)):(J.stop(),"fast"===e.engine?(G.shutdown(),Y.start(e.mine,e.theirs)):G.start(e.mine,e.theirs,e.profile))},en=e=>{e.mine.code!==e.theirs.code&&(h(e),Q&&("fast"!==N||e.engine!==N||e.mine!==f||e.theirs!==g)&&et(e))},es=e=>{en({...u,profile:yF({...x,...e})})},{prepare:ea,supported:ei,stop:el}=Z,eo=(0,s.useRef)(el);(0,s.useEffect)(()=>{eo.current=el}),(0,s.useEffect)(()=>{e||eo.current()},[e]),(0,s.useEffect)(()=>{e||(D(null),H(!1),B(!1))},[e]);let ec=(0,s.useRef)($);ec.current=$,(0,s.useEffect)(()=>{let e=window.setTimeout(()=>wL($),800);return()=>window.clearTimeout(e)},[$]),(0,s.useEffect)(()=>{let e=()=>wL(ec.current),t=()=>{"hidden"===document.visibilityState&&e()};return window.addEventListener("pagehide",e),document.addEventListener("visibilitychange",t),()=>{window.removeEventListener("pagehide",e),document.removeEventListener("visibilitychange",t),e()}},[]),(0,s.useEffect)(()=>{if(!q)return;let e=window.setTimeout(()=>V(null),4e3);return()=>window.clearTimeout(e)},[q]),(0,s.useEffect)(()=>{"codex"===N&&e&&!Q&&!0===ei&&window.isSecureContext&&ea?.(f,g,x)},[Q,N,f,ea,x,ei,g,e]),(0,s.useEffect)(()=>{if(!Q||!("wakeLock"in navigator))return;let e=null,t=!1,n=()=>{"visible"===document.visibilityState&&(!e||e.released)&&navigator.wakeLock.request("screen").then(n=>{t?n.release():e=n}).catch(()=>{})};return n(),document.addEventListener("visibilitychange",n),()=>{t=!0,document.removeEventListener("visibilitychange",n),e?.release()}},[Q]);let ed=!1===Z.supported,eu=!window.isSecureContext,eh="error"===Z.state&&Z.failure?function(e,t,n){switch(t){case"mic-denied":return e("translator.micDenied");case"mic-unavailable":return e("translator.micUnavailable");case"auth":return e("translator.auth");case"upstream":return e("translator.upstream",{error:n??""});default:return e("translator.failed",{error:n??""})}}(c,Z.failure,Z.detail):Z.skipped&&Q?c("translator.generationSkipped"):"idle"!==Z.ended||Q?eu?c("translator.insecure"):ed?c("translator.unsupported"):null:c("translator.idleStopped"),ep=$.at(-1),em=Q&&("codex"===N?void 0!==ep&&ep.call===_&&"user"===ep.role:$.some(e=>e.call===_&&"user"===e.role&&("voice"===N?!e.translationError:!e.final)&&!$.some(t=>t.utterance===e.utterance&&"assistant"===t.role&&("fast"===N||t.final)))),ef="error"===Z.state?"error":Z.reconnecting?"reconnecting":"connecting"===Z.state?"connecting":"live"===Z.state||"working"===Z.state?em?"translating":"listening":"idle",eg="reconnecting"===ef?c("translator.reconnecting"):"connecting"===ef?c("translator.connecting"):"translating"===ef?c("translator.translating"):"listening"===ef?c("translator.live"):"error"===ef?c("translator.errorStatus"):"",ex={"--translator-scale":String(wM[y]??1)},ev="ko"===d?"가":"A",ey=Q||!(ed||eu||null===Z.supported),eb=(0,s.useMemo)(()=>(function(e,t){let n=new Map(t.drafts.filter(e=>null!==e.matched).map(e=>[e.matched,e])),r=[],s=t.drafts.some(e=>null===e.matched&&e.text);for(let a of e)!n.has(a.id)&&(s&&"assistant"===a.role&&!a.final&&!t.seen.includes(a.id)&&6>y1(a.text)||r.push({order:a.id,line:{key:`s${a.id}`,segment:a,draft:!1}}));for(let n of t.drafts){let t=n.after+.5+1e-6*n.id;if(null===n.matched){if(!n.text)continue;let e={id:-1-n.id,role:"assistant",text:n.text,final:!1,mine:n.pair.mine,theirs:n.pair.theirs,call:0};r.push({order:t,line:{key:`d${n.id}`,segment:e,draft:!0,language:n.language}});continue}let s=e.find(e=>e.id===n.matched);if(!s)continue;let a=""!==n.text&&!s.final&&s.text.trim().length<n.text.length;r.push({order:t,line:{key:`d${n.id}`,segment:a?{...s,text:n.text}:s,draft:a,language:n.language}})}return r.sort((e,t)=>e.order-t.order).map(e=>e.line)})($.filter(e=>e.text.trim()),X.state),[$,X.state]),ew=bT($.filter(e=>"user"===e.role&&e.text.trim()&&e.final&&!e.restored&&!e.utterance?.startsWith("fast-")&&"them"===bd(e)).slice(-24).map(e=>({id:String(e.id),mine:e.mine.code,theirs:e.theirs.code,speaker:"theirs",text:e.text})),{meaning:C},{profile:x,history:bh(A.current,24)},e&&!v),ek=(0,s.useMemo)(()=>(function(e,t,n,r=null){let s=[],a=new Map,i=new Map,l=r?[...t,r]:t;for(let t of function(e,t,n){let r=[];for(let s of e){let e=n(s),a=r.length;if("assistant"===t(s)&&e){for(;a>0&&"user"===t(r[a-1])&&n(r[a-1])===("me"===e?"them":"me");)a--;(0===a||n(r[a-1])!==e)&&(a=r.length)}r.splice(a,0,s)}return r}(e,e=>e.segment.role,bq)){let e=bq(t)??"them",n="assistant"===t.segment.role,r=t.segment.utterance,o=s.at(-1),c=r?a.get(r):void 0,d=o?.voiceLines[0]?.segment,u=r?c:d?.call!==t.segment.call||d.utterance?void 0:o;if(!r){let r=i.get(e);r&&r.call===t.segment.call||(r={call:t.segment.call,pending:0,ambiguous:!1,received:!1},i.set(e,r)),n?(r.ambiguous&&(u=void 0,r.received=!0),r.pending=Math.max(0,r.pending-1)):(r.received&&(u=void 0,r.ambiguous=r.pending>0,r.received=!1),!(u?.side===e&&u.translations.length&&!u.originals.length)&&r.pending++,r.pending>1&&(r.ambiguous=!0))}let h=u?.at,p=void 0!==h&&!n&&l.some(e=>e.at>h&&e.at<=t.segment.at),m=void 0!==u&&(n?u.translations:u.originals).length>0;if(!u||!c&&(u.side!==e||p||m)){let n=Number.isFinite(t.segment.at)?t.segment.at:h??0;u={key:`voice-${t.key}`,at:n,side:e,originals:[],translations:[],voiceLines:[]},s.push(u),r&&a.set(r,u)}u.voiceLines.push(t);let f={key:t.key,text:t.segment.text,language:bB(t),fallbackLanguage:t.segment.theirs,final:t.segment.final&&!t.draft,loadReading:!0};(n?u.translations:u.originals).push(f)}for(let e of l)s.push({key:`typed-${e.id}`,at:e.at,side:e.source.code===n.code?"me":"them",typed:e,originals:[{key:`original-${e.id}`,text:e.original,language:e.source,final:!0}],translations:e.translation?[{key:`translation-${e.id}`,text:e.translation,language:e.target,reading:e.reading,final:e!==r}]:[],voiceLines:[],pending:e===r});return s.sort((e,t)=>e.at-t.at),s.forEach((e,t)=>{e.speakerStart=0===t||s[t-1].side!==e.side}),s})(eb,I.turns,f,I.provisional),[eb,I.turns,f,I.provisional]),ej=`${y}|${p}|${Q}`,eS=function(e=!1){let t=(0,s.useRef)(e);t.current=e;let[n,r]=(0,s.useState)(!1),a=(0,s.useRef)(null),i=(0,s.useRef)(null),[l,o]=(0,s.useState)(!1),[c,d]=(0,s.useState)(!1);(0,s.useEffect)(()=>(window.speechSynthesis?.getVoices(),r(!!window.speechSynthesis||"function"==typeof AudioContext),()=>{a.current?.abort(),i.current?.close().catch(()=>{}),i.current=null}),[]);let u=(0,s.useCallback)(()=>{a.current?.abort(),a.current=null,o(!1),d(!1)},[]);return{supported:n,speaking:l,failed:c,speak:(0,s.useCallback)((e,n)=>{a.current?.abort();let r=new AbortController;if(a.current=r,d(!1),o(!0),"function"==typeof AudioContext)try{i.current??=new AudioContext,i.current.resume().catch(()=>{})}catch{}b8(e,n,r.signal,()=>i.current??=new AudioContext,void 0,t.current).catch(()=>{r.signal.aborted||d(!0)}).finally(()=>{r.signal.aborted||o(!1)})},[]),cancel:u}}(k),{recordFace:eC}=function({visible:e,phase:t,face:n,segmentCount:r}){let a=(0,s.useRef)({phase:t,face:n,segmentCount:r});return(0,s.useEffect)(()=>{a.current={phase:t,face:n,segmentCount:r}}),(0,s.useEffect)(()=>{if(!e||"u"<typeof PerformanceObserver||!PerformanceObserver.supportedEntryTypes?.includes("longtask"))return;let t=new PerformanceObserver(e=>{for(let t of e.getEntries())t.duration<500||b4({kind:"stall",durationMs:Math.round(t.duration),...a.current})});return t.observe({type:"longtask"}),()=>t.disconnect()},[e]),{recordFace:(0,s.useCallback)((e,t)=>{b4({kind:e?"face-on":"face-off",trigger:t,...a.current,face:e})},[])}}({visible:e,phase:ef,face:v,segmentCount:$.length}),eN=[];e&&(v&&eN.push("face"),W&&eN.push("phrases"),U&&eN.push("scan"),z&&eN.push("card")),n=e=>{"card"===e?D(null):"phrases"===e?H(!1):"scan"===e?B(!1):(h(e=>({...e,face:!1})),eC(!1,"back"))},a=(0,s.useRef)(eN),i=(0,s.useRef)(n),(0,s.useEffect)(()=>{a.current=eN,i.current=n}),(0,s.useEffect)(()=>{bQ(),window.clearTimeout(bZ.release),bZ.release=void 0,bZ.releasing=!1,bZ.listener&&window.removeEventListener("popstate",bZ.listener);let e=e=>{var t;let n,r=(t=bZ.pushed,(n=bY(e.state))>t.length?{pushed:[...t],closed:[],forward:n-t.length}:{pushed:t.slice(0,n),closed:t.slice(n).reverse(),forward:0});if(bZ.pushed=r.pushed,bZ.ignore>0)bZ.ignore-=1;else if(!bZ.releasing&&r.forward>0){bZ.ignore+=1,window.history.go(-r.forward);return}else if(!bZ.releasing){for(let e of r.closed)i.current(e);return}bZ.releasing?b0():bX(a.current)};if(bZ.listener=e,window.addEventListener("popstate",e),0===bZ.pushed.length&&0===bZ.ignore){let e=bY(window.history.state);e>0&&(bZ.ignore+=1,window.history.go(-e))}return()=>{bZ.releasing=!0,bZ.release=window.setTimeout(b0,0)}},[]),o=eN.join(">"),(0,s.useEffect)(()=>{bX(a.current)},[o]);let eT=(0,s.useRef)(v);eT.current=v,(0,s.useEffect)(()=>{e&&eT.current&&eC(!0,"restore")},[eC,e]);let eI=e=>{h({...u,face:e}),eC(e,"button")};(0,s.useEffect)(()=>{if(!e||!v||z)return;let t=e=>{"Escape"===e.key&&(e.preventDefault(),h(e=>({...e,face:!1})),eC(!1,"button"))};return document.addEventListener("keydown",t),()=>document.removeEventListener("keydown",t)},[z,v,eC,e]);let eM=()=>{var e;e=A.current,A.current={...bl(),call:e.call,nextId:e.nextId},R([]),X.reset(),Y.clear(),wL([]),I.clear()},eE=async()=>{var e,t;let n,r=(e={title:c("translator.shareTitle"),original:c("translator.original"),translation:c("translator.translation")},t=e=>new Date(e).toLocaleString(d,{month:"numeric",day:"numeric",hour:"2-digit",minute:"2-digit"}),n=$.filter(e=>e.text.trim()).map(n=>{let r=bc(n),s="assistant"===n.role?e.translation:e.original,a=r?`${s} (${r.nativeName})`:s,i=n.at>0?`[${t(n.at)}] `:"";return`${i}${a}: ${n.text.trim()}`}),[e.title,"",...n].join("\n"));if("function"==typeof navigator.share)try{await navigator.share({title:c("translator.shareTitle"),text:r});return}catch(e){if(e instanceof DOMException&&"AbortError"===e.name)return}try{await navigator.clipboard.writeText(r),V("copied")}catch{V("failed")}},e$=c("translator.cardTitle"),eR=z?(0,r.jsx)(bO,{card:z,speech:eS,onClose:()=>D(null),renderText:e=>(0,r.jsx)(wU,{text:e})}):null,eL=()=>{Q?Z.stop():(P(!1),et(u))},eP=e=>yO.map(t=>(0,r.jsx)("option",{value:t.code,disabled:t.code===e.code,children:t.nativeName},t.code)),eA=(0,r.jsxs)("p",{className:"translator-status","data-phase":ef,role:"status","aria-live":"polite",children:["idle"===ef?null:(0,r.jsx)("span",{className:"translator-status-dot","aria-hidden":"true"}),eg]}),e_="voice"===N&&Q?(0,r.jsxs)("div",{className:"translator-voice-status",children:["ready"!==G.models.state?(0,r.jsx)("p",{className:"translator-options-note",role:"status",children:"failed"===G.models.state?T.modelFailed:T.modelLoading.replace("{percent}",String(G.models.percent))}):null,G.enrollment.side?(0,r.jsxs)("section",{className:"translator-enrollment","aria-label":T.enrollTitle,children:[(0,r.jsx)("h3",{children:T.enrollTitle}),(0,r.jsx)("p",{children:"me"===G.enrollment.side?T.enrollMe:T.enrollThem}),(0,r.jsx)("p",{lang:("me"===G.enrollment.side?f:g).tag,children:bW[("me"===G.enrollment.side?f:g).code]}),(0,r.jsx)("p",{className:"translator-options-note",children:T.enrollHint}),G.enrollment.failed?(0,r.jsx)("p",{role:"status",children:T.enrollRetry}):null,"loading"===G.models.state?(0,r.jsx)("p",{className:"translator-options-note",children:T.enrollWaiting}):null,(0,r.jsxs)("div",{className:"translator-enrollment-actions",children:[(0,r.jsx)("button",{type:"button",onClick:G.skipEnrollment,children:T.enrollSkip}),(0,r.jsx)("button",{type:"button",disabled:"ready"!==G.models.state||G.enrollment.seconds<1,onClick:G.nextEnrollment,children:"me"===G.enrollment.side?T.enrollNext:T.enrollDone})]})]}):null,G.overlap?(0,r.jsxs)("div",{className:"translator-overlap",role:"alert",children:[(0,r.jsx)("p",{lang:f.tag,children:bD[f.code]}),(0,r.jsx)("p",{lang:g.tag,children:bD[g.code]})]}):null]}):null,eF=e=>(0,r.jsxs)("button",{type:"button",className:"translator-call-button","data-compact":e?"true":void 0,"data-focus-halo":!0,"aria-pressed":Q,disabled:!ey,onClick:eL,children:[Q?(0,r.jsx)(wA,{}):(0,r.jsx)(wP,{}),Q?c("translator.stop"):c("translator.start")]});if(v){let t;return(0,r.jsxs)("section",{className:"translator-view","data-face":"true","aria-label":c("translator.title"),hidden:!e,style:ex,children:[(0,r.jsx)("h2",{className:"sr-only",children:c("translator.title")}),(0,r.jsxs)("div",{className:"translator-face",role:"log","aria-label":c("translator.conversation"),children:[(0,r.jsx)(wH,{lines:eb,language:g,unknownLabel:c("translator.unknownLanguage"),flipped:!0,emptyHint:(t=yW[g.code]?.[f.code]??f.englishName,(yH[g.code]??yH.en)(t)),onShow:D,showLabel:e$}),(0,r.jsxs)("div",{className:"translator-face-bar",children:[eh?(0,r.jsx)("p",{className:"translator-face-notice","data-tone":"error"===Z.state?"danger":void 0,role:"error"===Z.state?"alert":"status",children:eh}):null,e_,"idle"===ef?null:eA,(0,r.jsxs)("div",{className:"translator-face-controls",children:[eF(!0),(0,r.jsxs)("button",{type:"button",className:"translator-face-exit",onClick:()=>eI(!1),children:[(0,r.jsx)(wz,{}),c("translator.faceExit")]})]})]}),(0,r.jsx)(wH,{lines:eb,language:f,unknownLabel:c("translator.unknownLanguage"),emptyHint:Q?void 0:c("translator.empty"),onShow:D,showLabel:e$})]}),eR]})}return(0,r.jsxs)("section",{className:"translator-view","data-active":Q?"true":void 0,"aria-label":c("translator.title"),hidden:!e,style:ex,children:[(0,r.jsxs)("header",{className:"translator-header",children:[(0,r.jsxs)("div",{className:"translator-bar",children:[t?(0,r.jsx)("button",{type:"button",className:"translator-icon-button","aria-label":c("translator.back"),title:c("translator.back"),onClick:t,children:(0,r.jsx)(w_,{})}):null,(0,r.jsx)("h2",{className:"sr-only",children:c("translator.title")}),(0,r.jsxs)("button",{type:"button",className:"translator-pair","aria-expanded":L,"aria-controls":"translator-setup","aria-label":`${c("translator.setup")}: ${f.nativeName} ⇄ ${g.nativeName}`,onClick:()=>P(e=>!e),children:[(0,r.jsxs)("span",{className:"translator-pair-text",children:[(0,r.jsx)("span",{lang:f.tag,children:f.nativeName}),(0,r.jsx)("span",{"aria-hidden":"true",children:" ⇄ "}),(0,r.jsx)("span",{lang:g.tag,children:g.nativeName})]}),(0,r.jsx)(wO,{})]}),(0,r.jsxs)("details",{className:"translator-more",ref:M,onKeyDown:e=>{"Escape"===e.key&&(e.preventDefault(),e.currentTarget.open=!1,e.currentTarget.querySelector("summary")?.focus())},onBlur:e=>{e.relatedTarget&&!e.currentTarget.contains(e.relatedTarget)&&(e.currentTarget.open=!1)},children:[(0,r.jsx)("summary",{className:"translator-icon-button","aria-label":c("translator.more"),children:(0,r.jsx)(br.A,{size:22,"aria-hidden":"true"})}),(0,r.jsxs)("div",{className:"translator-more-menu",children:[(0,r.jsxs)("div",{className:"translator-menu-size",children:[(0,r.jsxs)("button",{type:"button",disabled:y<=0,onClick:()=>h({...u,size:Math.max(0,y-1)}),children:[(0,r.jsxs)("span",{"aria-hidden":"true",children:[ev,"−"]}),c("translator.sizeDown")]}),(0,r.jsxs)("button",{type:"button",disabled:y>=wM.length-1,onClick:()=>h({...u,size:Math.min(wM.length-1,y+1)}),children:[(0,r.jsxs)("span",{"aria-hidden":"true",children:[ev,"+"]}),c("translator.sizeUp")]})]}),(0,r.jsxs)("button",{type:"button",onClick:()=>{M.current&&(M.current.open=!1),eI(!0)},children:[(0,r.jsx)(wF,{}),c("translator.face")]}),(0,r.jsxs)("button",{type:"button",disabled:!$.length,onClick:()=>{M.current&&(M.current.open=!1),eE()},children:[(0,r.jsx)(wD,{}),c("translator.share")]}),(0,r.jsxs)("button",{type:"button",onClick:()=>{M.current&&(M.current.open=!1),B(!0)},children:[(0,r.jsx)(wp,{}),c("translator.scan")]}),(0,r.jsxs)("button",{type:"button",onClick:()=>{M.current&&(M.current.open=!1),H(!0)},children:[(0,r.jsx)(wW,{}),c("translator.phrases")]}),(0,r.jsxs)("button",{type:"button",onClick:()=>{M.current&&(M.current.open=!1),P(!0)},children:[(0,r.jsx)(bs.A,{size:20,"aria-hidden":"true"}),c("translator.setup")]}),(0,r.jsxs)("button",{type:"button",disabled:!ek.length,onClick:()=>{eM(),M.current&&(M.current.open=!1)},children:[(0,r.jsx)(ba.A,{size:20,"aria-hidden":"true"}),c("translator.clear")]})]})]})]}),L?(0,r.jsxs)("div",{id:"translator-setup",className:"translator-setup",children:[(0,r.jsx)("button",{type:"button",className:"translator-setup-close translator-icon-button","aria-label":c("translator.cardClose"),onClick:()=>P(!1),children:(0,r.jsx)(wz,{})}),(0,r.jsxs)("label",{className:"translator-language",children:[(0,r.jsx)("span",{children:T.engineLabel}),(0,r.jsxs)("select",{value:N,"aria-describedby":"fast"===N?"translator-fast-hint":void 0,onChange:e=>en({...u,engine:wE(e.target.value)}),children:[(0,r.jsx)("option",{value:"voice",children:T.engineVoice}),(0,r.jsx)("option",{value:"codex",children:T.engineCodex}),(0,r.jsx)("option",{value:"fast",children:T.engineFast})]})]}),(0,r.jsx)("p",{className:"translator-options-note",id:"fast"===N?"translator-fast-hint":void 0,children:"fast"===N?T.fastHint:T.engineHint}),(0,r.jsxs)("div",{className:"translator-languages",children:[(0,r.jsxs)("label",{className:"translator-language",children:[(0,r.jsx)("span",{children:c("translator.me")}),(0,r.jsx)("select",{"aria-label":c("translator.myLanguage"),value:f.code,onChange:e=>{let t=yD(e.target.value);t&&en({...u,mine:t})},children:eP(g)})]}),(0,r.jsx)("button",{type:"button",className:"translator-swap","aria-label":c("translator.swap"),title:c("translator.swap"),onClick:()=>en({...u,mine:g,theirs:f}),children:"⇄"}),(0,r.jsxs)("label",{className:"translator-language",children:[(0,r.jsx)("span",{children:c("translator.them")}),(0,r.jsx)("select",{"aria-label":c("translator.theirLanguage"),value:g.code,onChange:e=>{let t=yD(e.target.value);t&&en({...u,theirs:t})},children:eP(f)})]})]}),(0,r.jsxs)("div",{className:"translator-context",children:[(0,r.jsxs)("label",{className:"translator-language",children:[(0,r.jsx)("span",{children:c("translator.mood")}),(0,r.jsxs)("select",{value:x.mood??"",onChange:e=>es({mood:e.target.value}),children:[(0,r.jsx)("option",{value:"",children:c("translator.notSet")}),yE.map(e=>(0,r.jsx)("option",{value:e,children:c(`translator.mood.${e}`)},e))]})]}),(0,r.jsxs)("label",{className:"translator-language",children:[(0,r.jsx)("span",{children:c("translator.gender")}),(0,r.jsxs)("select",{value:x.gender??"",onChange:e=>es({gender:e.target.value}),children:[(0,r.jsx)("option",{value:"",children:c("translator.notSet")}),y$.map(e=>(0,r.jsx)("option",{value:e,children:c(`translator.gender.${e}`)},e))]})]}),(0,r.jsxs)("label",{className:"translator-language",children:[(0,r.jsx)("span",{children:c("translator.age")}),(0,r.jsxs)("select",{value:x.age??"",onChange:e=>es({age:e.target.value}),children:[(0,r.jsx)("option",{value:"",children:c("translator.notSet")}),yR.map(e=>(0,r.jsx)("option",{value:e,children:c(`translator.age.${e}`)},e))]})]})]}),(0,r.jsxs)("div",{className:"translator-context",children:[(0,r.jsxs)("label",{className:"translator-language",children:[(0,r.jsx)("span",{children:c("translator.partnerGender")}),(0,r.jsxs)("select",{value:x.partnerGender??"",onChange:e=>es({partnerGender:e.target.value}),children:[(0,r.jsx)("option",{value:"",children:c("translator.notSet")}),y$.map(e=>(0,r.jsx)("option",{value:e,children:c(`translator.gender.${e}`)},e))]})]}),(0,r.jsxs)("label",{className:"translator-language",children:[(0,r.jsx)("span",{children:c("translator.partnerAge")}),(0,r.jsxs)("select",{value:x.partnerAge??"",onChange:e=>es({partnerAge:e.target.value}),children:[(0,r.jsx)("option",{value:"",children:c("translator.notSet")}),yL.map(e=>(0,r.jsx)("option",{value:e,children:c(`translator.partnerAge.${e}`)},e))]})]})]}),(0,r.jsxs)("div",{className:"translator-options",children:[(0,r.jsxs)("label",{className:"translator-toggle",children:[(0,r.jsx)("input",{type:"checkbox",checked:b,"aria-describedby":"fast"===N?"translator-fast-hint":"translator-voice-hint",onChange:e=>h({...u,voice:e.target.checked})}),(0,r.jsx)("span",{children:c("translator.voice")})]}),"fast"!==N?(0,r.jsx)("p",{id:"translator-voice-hint",className:"translator-options-note",children:c("translator.voiceHint")}):null,b?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("label",{className:"translator-toggle",children:[(0,r.jsx)("input",{type:"checkbox",checked:w,"aria-describedby":"translator-echo-guard-hint",onChange:e=>h({...u,echoGuard:e.target.checked})}),(0,r.jsx)("span",{children:c("translator.echoGuard")})]}),(0,r.jsx)("p",{id:"translator-echo-guard-hint",className:"translator-options-note",children:c("translator.echoGuardHint")})]}):null,(0,r.jsxs)("label",{className:"translator-toggle",children:[(0,r.jsx)("input",{type:"checkbox",checked:k,"aria-describedby":"translator-natural-voice-hint",onChange:e=>h({...u,naturalVoice:e.target.checked})}),(0,r.jsx)("span",{children:c("translator.naturalVoice")})]}),(0,r.jsx)("p",{id:"translator-natural-voice-hint",className:"translator-options-note",children:c("voice"===N?"translator.naturalVoiceHint":"translator.naturalVoiceButtonHint")}),"codex"===N?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("label",{className:"translator-toggle",children:[(0,r.jsx)("input",{type:"checkbox",checked:j,"aria-describedby":"translator-noise-suppression-hint",onChange:e=>h({...u,noiseSuppression:e.target.checked})}),(0,r.jsx)("span",{children:c("translator.noiseSuppression")})]}),(0,r.jsx)("p",{id:"translator-noise-suppression-hint",className:"translator-options-note",children:c("translator.noiseSuppressionHint")}),(0,r.jsxs)("label",{className:"translator-toggle",children:[(0,r.jsx)("input",{type:"checkbox",checked:S,"aria-describedby":"translator-fast-drafts-hint",onChange:e=>h({...u,fastDrafts:e.target.checked})}),(0,r.jsx)("span",{children:c("translator.fastDrafts")})]}),(0,r.jsx)("p",{id:"translator-fast-drafts-hint",className:"translator-options-note",children:c("translator.fastDraftsHint")})]}):null]}),(0,r.jsxs)("div",{className:"translator-options",children:[(0,r.jsxs)("label",{className:"translator-toggle",children:[(0,r.jsx)("input",{type:"checkbox",checked:C,"aria-describedby":"translator-assist-meaning-hint",onChange:e=>h({...u,assistMeaning:e.target.checked})}),(0,r.jsx)("span",{children:c("translator.assistMeaning")})]}),(0,r.jsx)("p",{id:"translator-assist-meaning-hint",className:"translator-options-note",children:c("translator.assistMeaningHint")})]}),ek.length>0?(0,r.jsx)(l.r,{variant:"ghost",size:"small",className:"translator-clear",onClick:eM,children:c("translator.clear")}):null]}):null]}),e_,eh?(0,r.jsx)("p",{className:"translator-banner","data-tone":"error"===Z.state?"danger":void 0,role:"error"===Z.state?"alert":"status",children:eh}):null,q?(0,r.jsx)("p",{className:"translator-banner","data-tone":"failed"===q?"danger":void 0,role:"status",children:c("copied"===q?"translator.shareCopied":"translator.shareFailed")}):null,0!==ek.length||Q?(0,r.jsx)(wB,{label:c("translator.conversation"),turns:ek,visible:e,pending:"translating"===ef?c("translator.translationPending"):null,jumpLabel:c("translator.jumpLatest"),layoutKey:ej,onShow:D,speech:eS,correctionConnection:G.connectionId,onCorrect:"voice"===N?e=>{let t=e.voiceLines.find(e=>e.segment.utterance?.startsWith(`${G.connectionId}:`))?.segment;t?.utterance&&G.correct(Number(t.utterance.split(":").at(-1)),t.translationError?e.side:"me"===e.side?"them":"me")}:void 0,renderAssist:e=>e.typed?(0,r.jsx)(wx,{result:I.assists.get(String(e.typed.id)),meaning:C,mine:f,numericMismatch:C&&!e.pending&&"me"===e.side&&function(e,t){let n={"\xa5":"yen",円:"yen",엔:"yen",JPY:"yen","₩":"won",원:"won",ウォン:"won",KRW:"won",$:"dollar",달러:"dollar",USD:"dollar",dollars:"dollar","€":"euro",유로:"euro",EUR:"euro",euros:"euro","₫":"dong",동:"dong",đồng:"dong",VND:"dong",개:"quantity",つ:"quantity",個:"quantity",pieces:"quantity",명:"people",人:"people"},r=[];for(let s of[e,t]){let e=s.normalize("NFKC");if(/\d[^\d\s]*\s*[-/〜~–—]\s*\d/u.test(e))return!1;let t=/^[\s\d.,+-]+$/.test(e),a=new Map;for(let r of e.matchAll(/([$€¥₩₫])?\s*([+-]?\d+(?:[.,]\d+)*)\s*(円|엔|JPY|원|ウォン|KRW|달러|USD|dollars|유로|EUR|euros|동|đồng|VND|개|つ|個|pieces|명|人)?/gu)){let s=r[2];if(!/^[+-]?(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d{1,2})?$/.test(s))return!1;let i=Number(s.replaceAll(",",""));if(!Number.isSafeInteger(Math.round(100*i)))return!1;let l=t?"digits":n[r[3]||r[1]];if(r[1]&&!r[3]&&/^\s*\p{L}/u.test(e.slice((r.index??0)+r[0].length))||!l)return!1;a.has(l)||a.set(l,new Set),a.get(l).add(i)}if(!a.size)return!1;r.push(a)}for(let[e,t]of r[0]){let n=r[1].get(e);if(n&&t.size===n.size&&[...t].some(e=>!n.has(e)))return!0}return!1}(e.typed.original,e.typed.translation)}):e.voiceLines.filter(e=>"user"===e.segment.role&&!e.draft&&e.segment.final).map(e=>(0,r.jsx)(wx,{result:ew.get(String(e.segment.id)),meaning:C,mine:e.segment.mine},e.key))}):(0,r.jsx)("div",{className:"translator-log",children:(0,r.jsx)("p",{className:"translator-empty",children:c("translator.empty")})}),I.composer,(0,r.jsxs)("div",{className:"translator-dock",children:["idle"!==ef?eA:null,(0,r.jsxs)("div",{className:"translator-dock-row",children:[(0,r.jsx)("button",{type:"button",className:"translator-keyboard","aria-label":c(p?"translator.keyboardClose":"translator.keyboard"),"aria-expanded":p,onClick:()=>m(e=>!e),children:(0,r.jsx)(bi.A,{size:24,"aria-hidden":"true"})}),eF(!0)]})]}),W?(0,r.jsx)(wi,{mine:f,theirs:g,onShow:D,onClose:()=>H(!1)}):null,U?(0,r.jsx)(wg,{mine:f,theirs:g,onShow:D,onClose:()=>B(!1)}):null,eR]})}function wV({onOpen:e}){let{tt:t}=er();return(0,r.jsxs)("div",{id:"navigator-translator-panel",className:"translator-panel",children:[(0,r.jsx)("p",{className:"translator-panel-hint",children:t("translator.panelHint")}),e?(0,r.jsx)("button",{type:"button",className:"translator-panel-open",onClick:e,children:t("translator.open")}):null]})}let wK="git pull --ff-only && node install.mjs setup",wJ={done:!0,"handed-off":!0,"restart-required":!0,failed:!0};function wG(e){return"unknown"===e?e:`v${e}`}function wY(){let{locale:e,t}=(0,F.s)(),n=U(),[i,l]=(0,s.useState)(null),[o,c]=(0,s.useState)(!1),[d,u]=(0,s.useState)(null),[h,p]=(0,s.useState)(null),m=(0,s.useRef)(null),f=(0,s.useRef)(null),g=(0,s.useRef)(null),x=(0,s.useRef)(null),[v,y]=(0,s.useState)(null),[b,w]=(0,s.useState)(null),[k,j]=(0,s.useState)(!1),[S,C]=(0,s.useState)(null),[N,T]=(0,s.useState)(!1),I=(0,s.useCallback)(()=>{let e=f.current?.getBoundingClientRect();if(!e)return;let t=window.visualViewport?.height??window.innerHeight,{side:n,maxHeight:r}=uR(e.top,e.bottom,t,uL(t,.72,620),{margin:12,minHeight:0}),s=Math.min(430,window.innerWidth-24),a=Math.max(12,window.innerWidth-s-12);y({left:Math.min(e.right+8,a),width:s,maxHeight:r,..."above"===n?{bottom:t-e.top+8}:{top:e.bottom+8}})},[]);(0,s.useEffect)(()=>o?(I(),window.addEventListener("resize",I),window.addEventListener("scroll",I,!0),window.visualViewport?.addEventListener("resize",I),window.visualViewport?.addEventListener("scroll",I),()=>{window.removeEventListener("resize",I),window.removeEventListener("scroll",I,!0),window.visualViewport?.removeEventListener("resize",I),window.visualViewport?.removeEventListener("scroll",I)}):void y(null),[o,I]),(0,s.useEffect)(()=>{let e,t=!1,n=null,r=0,s=()=>{clearTimeout(e),e=void 0},a=()=>{s(),t||"visible"!==document.visibilityState||(e=setTimeout(()=>void i(),36e5))},i=async()=>{if(t||n)return;let e=new AbortController;n=e,r=Date.now();try{let n=await fetch("/api/updates",{cache:"no-store",signal:e.signal});if(!n.ok)return;let r=await n.json();t||l(r)}catch{}finally{n===e&&(n=null),a()}},o=()=>{"visible"!==document.visibilityState?s():n||(Date.now()-r>=1e4?i():void 0===e&&a())};return i(),document.addEventListener("visibilitychange",o),window.addEventListener("focus",o),window.addEventListener("online",o),()=>{t=!0,s(),n?.abort(),document.removeEventListener("visibilitychange",o),window.removeEventListener("focus",o),window.removeEventListener("online",o)}},[]);let M=(0,s.useCallback)(async e=>{try{let t=await fetch("/api/updates/apply",{cache:"no-store",signal:e});if(!t.ok)return null;return await t.json()}catch{return null}},[]);(0,s.useEffect)(()=>{let e=new AbortController;return M(e.signal).then(t=>{t&&!e.signal.aborted&&(w(t),t.running&&t.job&&C(t.job.currentVersion))}),()=>e.abort()},[M]);let E=(0,s.useCallback)(async e=>{u(null);let n=0;try{let e=await fetch("/api/agent/running",{cache:"no-store"});if(e.ok){let t=await e.json();n=t.runningSessionIds?.length??0}}catch{n=0}let r=n>0?t("updates.applyConfirmBusy",{version:wG(e),count:n}):t("updates.applyConfirm",{version:wG(e)});if(window.confirm(r)){j(!0);try{let e=await fetch("/api/updates/apply",{method:"POST",headers:{"Content-Type":"application/json"},body:"{}"}),n=await e.json();if(!e.ok)return void u(n.error??t("updates.applyStartFailed",{reason:String(e.status)}));w(n),n.job&&C(n.job.currentVersion)}catch(e){u(t("updates.applyStartFailed",{reason:e instanceof Error?e.message:String(e)}))}finally{j(!1)}}},[t]);if((0,s.useEffect)(()=>{let e;if(!S)return;let t=!1,n=async()=>{let r=await M();if(!t){if(T(null===r),r){if(w(r),r.runningVersion!==S&&"unknown"!==r.runningVersion)return void window.location.reload();if(r.job&&wJ[r.job.phase]&&!r.running)return void C(null)}e=setTimeout(()=>void n(),r?2e3:5e3)}};return e=setTimeout(()=>void n(),2e3),()=>{t=!0,clearTimeout(e)}},[S,M]),(0,s.useEffect)(()=>()=>{clearTimeout(m.current??void 0),m.current=null},[]),(0,s.useEffect)(()=>{if(!o)return;let e=e=>{f.current?.contains(e.target)||g.current?.contains(e.target)||c(!1)},t=e=>{"Escape"===e.key&&(e.preventDefault(),c(!1),x.current?.focus({preventScroll:!0}))};return document.addEventListener("pointerdown",e),document.addEventListener("keydown",t),()=>{document.removeEventListener("pointerdown",e),document.removeEventListener("keydown",t)}},[o]),!i?.updateAvailable||!i.latestRelease)return null;let $=i.latestRelease,R=$.publishedAt?new Intl.DateTimeFormat(e,{dateStyle:"medium"}).format(new Date($.publishedAt)):null,L=$.body.trim()||$.name,P=b?.job??null,A=k||!!S||!!b?.running,_=async e=>{try{await nT(e),clearTimeout(m.current??void 0),p(e),m.current=setTimeout(()=>p(null),1600)}catch{u(t("updates.copyFailed"))}};return(0,r.jsxs)("div",{ref:f,"data-dismissible-layer":o?"":void 0,style:{position:"relative",width:"100%"},children:[(0,r.jsxs)("button",{ref:x,type:"button","aria-expanded":o,"aria-haspopup":"dialog",onClick:()=>{c(e=>!e),u(null)},title:t("updates.availableTitle",{version:wG($.version)}),style:{width:"100%",minHeight:n?44:34,display:"flex",alignItems:"center",justifyContent:"center",gap:8,padding:"7px 10px",borderRadius:"var(--radius-surface)",background:"color-mix(in srgb, var(--warning) 16%, var(--bg-panel))",color:"var(--warning)",cursor:"pointer",fontSize:11,fontFamily:"var(--font-mono)",transition:"background 0.12s"},onMouseEnter:e=>{e.currentTarget.style.background="color-mix(in srgb, var(--warning) 26%, var(--bg-panel))"},onMouseLeave:e=>{e.currentTarget.style.background="color-mix(in srgb, var(--warning) 16%, var(--bg-panel))"},children:[(0,r.jsx)("span",{"aria-hidden":"true",style:{width:6,height:6,borderRadius:"50%",background:"var(--warning)"}}),(0,r.jsx)("span",{children:t("updates.available")}),(0,r.jsx)("span",{style:{color:"var(--text)",fontVariantNumeric:"tabular-nums"},children:wG($.version)})]}),o&&v&&(0,a.createPortal)((0,r.jsxs)("div",{ref:g,"data-dismissible-layer":"",role:"dialog","aria-label":t("updates.dialogTitle"),style:{position:"fixed",left:v.left,top:v.top,bottom:v.bottom,zIndex:700,width:v.width,maxHeight:v.maxHeight,display:"flex",flexDirection:"column",overflow:"hidden",borderRadius:"var(--radius-surface)",background:"var(--bg)",boxShadow:"var(--shadow-float)"},children:[(0,r.jsxs)("div",{style:{padding:"13px 14px 11px",background:"color-mix(in srgb, var(--warning) 12%, var(--bg))"},children:[(0,r.jsxs)("div",{style:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:12},children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{style:{color:"var(--text-dim)",fontSize:10},children:t("updates.dialogEyebrow")}),(0,r.jsx)("div",{style:{marginTop:3,color:"var(--text)",fontSize:15,fontWeight:650},children:t("updates.dialogTitle")})]}),(0,r.jsx)("div",{style:{color:"var(--warning)",fontFamily:"var(--font-mono)",fontSize:12,fontVariantNumeric:"tabular-nums"},children:wG($.version)})]}),(0,r.jsxs)("div",{style:{display:"flex",flexWrap:"wrap",gap:"4px 14px",marginTop:9,color:"var(--text-muted)",fontSize:11,fontFamily:"var(--font-mono)"},children:[(0,r.jsx)("span",{children:t("updates.current",{version:wG(i.currentAppVersion)})}),R&&(0,r.jsx)("span",{children:R})]})]}),(0,r.jsxs)("div",{style:{flex:1,minHeight:0,overflowY:"auto",padding:"11px 14px 14px"},children:[(0,r.jsx)("div",{style:{marginBottom:7,color:"var(--text-dim)",fontSize:10},children:t("updates.changelog")}),(0,r.jsx)("div",{className:"update-changelog",style:{color:"var(--text-muted)",fontSize:11,lineHeight:1.5},children:(0,r.jsx)(nJ,{children:L})})]}),(0,r.jsxs)("div",{style:{flexShrink:0,padding:"10px 14px 12px",background:"var(--bg-panel)"},children:[(0,r.jsx)("div",{style:{display:"flex",alignItems:"center",gap:9,marginBottom:10},children:(0,r.jsx)("a",{href:$.htmlUrl,target:"_blank",rel:"noreferrer",style:{color:"var(--accent)",fontSize:11,textDecoration:"underline",textUnderlineOffset:3},children:t("updates.viewRelease")})}),b?.supported&&(0,r.jsxs)("div",{style:{marginBottom:11},children:[(0,r.jsx)("button",{type:"button",onClick:()=>void E($.version),disabled:A,style:{width:"100%",minHeight:n?44:32,padding:"6px 12px",borderRadius:"var(--radius-control)",background:"var(--accent)",color:"var(--accent-text)",fontSize:12,fontWeight:600,cursor:A?"not-allowed":"pointer",opacity:A?.65:1},children:A?t("updates.applyBusy"):t("updates.apply")}),P&&(0,r.jsxs)("div",{style:{marginTop:8,fontSize:11,lineHeight:1.45},children:[(0,r.jsxs)("div",{role:"status","aria-live":"polite",style:{color:"failed"===P.phase?"var(--danger)":"var(--text)",fontFamily:"var(--font-mono)"},children:[t(`updates.phase.${P.phase}`),P.targetRef?` \xb7 ${P.targetRef}`:""]}),"failed"===P.phase&&P.error&&(0,r.jsx)("div",{style:{marginTop:4,color:"var(--danger)",overflowWrap:"anywhere"},children:P.error}),"handed-off"===P.phase&&(0,r.jsx)("div",{style:{marginTop:4,color:"var(--text-muted)"},children:t("updates.handedOff")}),S&&(0,r.jsx)("div",{style:{marginTop:4,color:N?"var(--warning)":"var(--text-muted)"},children:t("updates.waitingForRestart")}),(0,r.jsx)("div",{style:{marginTop:4,color:"var(--text-dim)",overflowWrap:"anywhere",fontFamily:"var(--font-mono)"},children:t("updates.logPath",{path:P.logPath})})]})]}),b&&!b.supported&&b.reason&&(0,r.jsxs)("div",{style:{marginBottom:10,color:"var(--text-muted)",fontSize:11,lineHeight:1.45},children:[(0,r.jsx)("div",{children:t("updates.unsupported")}),(0,r.jsx)("div",{style:{marginTop:4,color:"var(--text-dim)",fontFamily:"var(--font-mono)",overflowWrap:"anywhere"},children:t("updates.unsupportedReason",{reason:b.reason})})]}),(0,r.jsxs)("div",{style:{color:"var(--text-muted)",fontSize:11,lineHeight:1.45},children:[(0,r.jsx)("div",{style:{marginBottom:7,color:"var(--text-dim)"},children:t("updates.manual")}),(0,r.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:7,minWidth:0,marginTop:6,padding:"6px 7px",borderRadius:"var(--radius-surface)",background:"var(--bg)",fontFamily:"var(--font-mono)"},children:[(0,r.jsx)("code",{style:{flex:1,minWidth:0,overflowWrap:"anywhere",color:"var(--text)"},children:wK}),(0,r.jsx)("button",{type:"button",onClick:()=>void _(wK),title:h===wK?t("updates.commandCopied"):t("updates.copyCommand"),"aria-label":h===wK?t("updates.commandCopied"):t("updates.copyCommand"),style:{flex:"0 0 auto",width:n?44:24,height:n?44:24,padding:0,borderRadius:"var(--radius-control)",background:"var(--bg-hover)",color:h===wK?"var(--accent)":"var(--text-dim)",cursor:"pointer"},children:h===wK?(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:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}):(0,r.jsxs)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"}),(0,r.jsx)("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]})})]})]}),d&&(0,r.jsx)("div",{role:"alert",style:{marginTop:9,color:"var(--danger)",fontSize:11,lineHeight:1.45},children:d})]})]}),document.body)]})}var wZ=n(34817),wQ=n.n(wZ);let wX={dirty:"작업 트리에 변경 사항 있음",diverged:"브랜치 이력 분기됨",ahead:"로컬 커밋이 원격보다 앞서 있음",detached:"분리된 HEAD 상태","other-branch":"기본 브랜치가 아님",untracked:"origin 브랜치를 추적하지 않음",busy:"세션 사용 중","unknown-idle":"유휴 상태 확인 불가","git-lock":"Git 잠금 파일 존재","fetch-error":"가져오기(fetch) 오류","ff-error":"빨리 감기(fast-forward) 병합 오류","server-auth":"서버 비밀번호 잠금으로 세션 확인 불가"};function w0(){let[e,t]=(0,s.useState)(null),[n,a]=(0,s.useState)(null),[i,l]=(0,s.useState)(!1),o=(0,s.useCallback)(async()=>{try{let e=await fetch("/api/repo-sync",{cache:"no-store"});e.ok&&t(await e.json())}catch{}},[]);async function c(e,n){a(e),l(!1);try{let r=await fetch("/api/repo-sync",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:e,action:n})});if(!r.ok)throw Error("Request failed");t(await r.json())}catch{l(!0)}finally{a(null),await o()}}if((0,s.useEffect)(()=>{o();let e=setInterval(()=>{document.hidden||o()},1e4);return()=>clearInterval(e)},[o]),!e)return null;let d=e.uncloned.filter(t=>"decline"!==e.decisions[t.name]),u=e.uncloned.filter(t=>"decline"===e.decisions[t.name]),h=e.results.filter(e=>"skipped"===e.outcome),p=Object.entries(e.clones).filter(([,e])=>"failed"===e.status),m=Object.entries(e.clones).filter(([,e])=>"running"===e.status),f="auth"===e.accountStatus||"error"===e.accountStatus;return d.length||u.length||h.length||f||p.length||m.length?(0,r.jsxs)("details",{className:wQ().notice,"data-repo-sync":!0,children:[(0,r.jsxs)("summary",{children:["저장소 동기화",d.length?` (${d.length})`:""]}),(0,r.jsxs)("div",{className:wQ().body,children:["auth"===e.accountStatus&&(0,r.jsx)("p",{role:"status",children:"이 PC에서 로그인 필요 (gh auth login)"}),"error"===e.accountStatus&&(0,r.jsx)("p",{role:"status",children:"계정 목록 조회 실패로 이전 목록 사용"}),i&&(0,r.jsx)("p",{role:"alert",children:"API 요청 실패"}),d.map(t=>(0,r.jsxs)("div",{className:wQ().repo,"data-repo-name":t.name,children:[(0,r.jsxs)("span",{children:[t.name,t.isFork?" (포크)":""]}),(0,r.jsxs)("div",{className:wQ().actions,children:[(0,r.jsx)("button",{type:"button",disabled:!!n||e.clones[t.name]?.status==="running",onClick:()=>void c(t.name,"clone"),children:"받기"}),(0,r.jsx)("button",{type:"button",disabled:!!n||e.clones[t.name]?.status==="running",onClick:()=>void c(t.name,"decline"),children:"이 PC에선 안 받기"})]})]},t.name)),m.map(([e])=>(0,r.jsxs)("p",{role:"status",children:[e,": 복제 진행 중"]},e)),p.map(([e,t])=>(0,r.jsxs)("p",{role:"status",children:[e,": ","auth"===t.error?"이 PC에서 로그인 필요 (gh auth login)":"복제 실패"]},e)),h.map(e=>(0,r.jsxs)("p",{title:e.path,children:[e.name,": ",e.reason?wX[e.reason]:"",e.skipCount>1&&(0,r.jsx)("small",{children:e.lastSuccess?`마지막 성공 동기화: ${Math.max(0,Math.floor((Date.now()-Date.parse(e.lastSuccess))/36e5))}시간 전`:"성공한 동기화 기록 없음"})]},e.path)),!!u.length&&(0,r.jsxs)("details",{children:[(0,r.jsxs)("summary",{children:["이 PC에서 받지 않을 저장소 (",u.length,")"]}),u.map(e=>(0,r.jsxs)("div",{className:wQ().repo,"data-repo-name":e.name,children:[(0,r.jsx)("span",{children:e.name}),(0,r.jsx)("button",{type:"button",disabled:!!n,onClick:()=>void c(e.name,"undecline"),children:"다시 묻기"})]},e.name))]})]})]}):null}let w1={ok:"정상",watch:"주의",problem:"문제",unknown:"미확인"};function w2(e){let t=Date.parse(e);return Number.isNaN(t)?null:new Date(t+324e5).toISOString()}function w4(e){return w2(e)?.slice(0,10)??e}function w8(e){let t=w2(e);return t?`${t.slice(0,10)} ${t.slice(11,16)}`:e}function w5(e){let t=Date.parse(e);return Number.isNaN(t)?e:w4(new Date(t-1).toISOString())}function w6(e){let{currentStart:t,currentEnd:n,previousStart:r}=e.window;return{current:`${w4(t)} ~ ${w5(n)}`,previous:`${w4(r)} ~ ${w5(t)}`}}function w3(e){let[t,n]=String(e).split("."),r=t.startsWith("-")?"-":"",s=(r?t.slice(1):t).replace(/\B(?=(\d{3})+(?!\d))/g,",");return`${r}${s}${n?`.${n}`:""}`}function w7(e,t){let n=10**t;return Math.round(e*n)/n}function w9(e,t){if(null===t)return"측정 불가";switch(e){case"count":return`${w3(w7(t,2))}건`;case"ratio":return`${(100*t).toFixed(1)}%`;case"usd":return`$${w3(w7(t,2))}`;case"ms":return t>=1e3?`${w3(w7(t/1e3,1))}초`:`${w3(w7(t,0))}ms`;case"tokens":return`${w3(Math.round(t))} 토큰`}}function ke(e,t=""){let{unit:n,current:r,previous:s}=e;if(null===r||null===s)return null;let a=r-s;if(0===a)return"없음";let i=a>0?"+":"-";if("ratio"===n)return`${i}${(100*Math.abs(a)).toFixed(1)}%p`;let l=w9(n,Math.abs(a)),o=0===s?"":` (${i}${w7(Math.abs(a)/Math.abs(s)*100,0)}%)`;return`${i}${l}${t}${o}`}function kt(e){return e<36e5?`${Math.max(0,Math.floor(e/6e4))}분`:e<864e5?`${Math.floor(e/36e5)}시간`:`${w7(e/864e5,1)}일`}let kn="관찰 중";function kr(e,t){let n=t.perDay?"/일":"",r=(e,n)=>null!==e&&t.perDay?n>0?e/(n/864e5):null:e,s=r(e.current,t.afterMs),a=r(t.before,t.beforeMs),i=t=>`${w9(e.unit,t)}${null===t?"":n}`;return{after:t.observing?kn:i(s),before:i(a),afterWindow:kt(t.afterMs),beforeWindow:kt(t.beforeMs),change:t.observing?kn:ke({unit:e.unit,current:s,previous:a},n)}}let ks={date:0,"after-deploy":0,condition:1,none:2};function ka(e){return[...e].sort((e,t)=>e.overdue!==t.overdue?e.overdue?-1:1:e.dueDate&&t.dueDate&&e.dueDate!==t.dueDate?e.dueDate<t.dueDate?-1:1:!!e.dueDate!=!!t.dueDate?e.dueDate?-1:1:ks[e.dueKind]-ks[t.dueKind])}function ki(e){if("condition"===e.dueKind)return"조건이 생기면 점검";if(!e.dueDate)return"점검일 미기재";let t="after-deploy"===e.dueKind?"배포일 기준 계산":"점검일";return`${t} ${e.dueDate}${e.overdue?" \xb7 기한 지남":""}`}function kl(e,t){let n=e.sections.find(e=>e.id===t);if(!n)throw Error(`upkeep section not found: ${t}`);return n}function ko(e){return e.metrics.filter(e=>"ok"!==e.status&&!e.check)}function kc(e){let t=e.filter(e=>e.check);return t.length?["",`점검 완료 표시한 지표 ${t.length}개는 뺐습니다: ${t.map(e=>e.label).join(", ")}`]:[]}function kd(e){let t=w6(e);return[`- 최근 7일: ${t.current}`,`- 비교 기간(직전 7일): ${t.previous}`,`- 보고서 생성: ${w8(e.generatedAt)} (세션 파일 ${w3(e.scannedFiles)}개를 읽음)`]}function ku(e,t){if(!t||!e.timestamp)return null;let n=Date.parse(t.markedAt);return Date.parse(e.timestamp)<n?"고침 전":e.since&&Date.parse(e.since)<n?"고침 전 사용 포함":null}function kh(e,t){return[`${t} (${e.path}, 「${e.title}」):`,"```text",e.text,"```"]}function kp(e){let{fix:t}=e,n=t?null:ke(e),r=t?kr(e,t):null,s=t&&r?[`- 고침 표시: ${w8(t.markedAt)}. 판정은 이 시각 이후 기록만으로 냈습니다.`,`- 고침 뒤 값(표시 뒤 ${r.afterWindow}): ${r.after}`,`- 고침 전 값(최근 7일 중 표시 전 ${r.beforeWindow}): ${r.before}${!t.observing&&r.change?` (고침 전 대비 변화 ${r.change})`:""}`]:[`- 최근 7일 값: ${w9(e.unit,e.current)}`];return s.push(`- 직전 7일 값: ${w9(e.unit,e.previous)}${n?` (변화 ${n})`:""}`,`- 판정: ${w1[e.status]}`,`- 판정 기준: ${e.criterion}`),e.note&&s.push(`- 해석 주의: ${e.note}`),e.check&&s.push(`- 점검 완료: ${w8(e.check.checkedAt)}${e.check.note?` \xb7 ${e.check.note}`:""}. 원인을 확인했지만 고친 게 아니라 행 판정은 그대로이고, 섹션 판정과 전체\xb7섹션 프롬프트에서는 빠집니다.`),s.push(`- 지표 id(${e.fixable?"고침\xb7점검 표시용":"점검 표시용"}): \`${e.id}\``),e.handoff&&s.push("",...kh(e.handoff,"이 기준을 적은 HANDOFF 항목")),s.push("","근거 사례:"),e.evidence.length?s.push(...e.evidence.map(e=>{let n,r;return n=[e.label],void 0!==e.count&&n.push(`${w3(e.count)}회`),e.sessionId&&n.push(`세션 ${e.sessionId}`),e.sessionPath&&n.push(e.sessionPath),e.timestamp&&n.push(w8(e.timestamp)),(r=ku(e,t))&&n.push(r),e.detail&&n.push(e.detail),`- ${n.join(" \xb7 ")}`})):s.push("- 보고서에 사례가 없습니다. 아래 요청 1번에서 직접 찾아야 합니다."),s}function km(e){return[`- 기한: ${ki(e)}`,`- 출처: ${e.ref.path}의 「${e.section}」 절`,"",...kh(e.ref,"HANDOFF 원문")]}function kf(e){return e.warnings.length?["","이 섹션을 만들 때 읽지 못한 자료:",...e.warnings.map(e=>`- ${e}`)]:[]}let kg=["요청:","1. 위 근거 사례의 세션 파일과 경로를 직접 열어, 이 판정이 나온 원인을 찾아 주세요. 근거가 부족하면 그 사실부터 알려 주세요.","2. 원인이 CUELO-private 저장소 범위 안이면 고치고, 고친 동작을 실제로 검증해 주세요.","3. HANDOFF.md와 작업 기록(doc/history)에 원인\xb7조치\xb7검증 결과를 남겨 주세요.","4. 사용자 결정이 필요한 일(기준 변경, 비용, 삭제, 상시 승인 범위 밖의 배포 등)이면 고치지 말고 멈춰서 저에게 물어봐 주세요. 이미 확인된 상시 승인 범위의 배포는 재승인을 요청하지 말고 해당 프로젝트의 검증, 커밋과 푸시, 배포 절차를 따라 주세요.",'5. 고쳐서 live 배포와 검증까지 끝난 지표만 고침 표시를 남겨 주세요. 이 CUELO 서버의 `POST /api/upkeep`에 JSON `{"metricId": "<지표 id>", "at": "<고친 동작이 live에 들어간 시각, ISO>"}`을 보내면 됩니다(최근 7일 안, 미래 불가). 원인은 확인했지만 사용자 결정에 따른 사용량처럼 고친 게 아닌 지표는 고침 표시 대신 점검 표시를 남겨 주세요: `POST /api/upkeep/check`에 JSON `{"metricId": "<지표 id>", "note": "<확인한 원인 한 줄>"}`(행 판정은 그대로 두고, 7일 동안 「점검 완료」로 붙어 섹션 판정과 전체\xb7섹션 프롬프트에서 빠집니다). 비밀번호 잠금 등으로 API를 부를 수 없으면 표시 대신 지표 id와 시각\xb7사유를 결과에 적어 주세요.'],kx=["요청:","1. 이 항목이 적어 둔 관찰\xb7점검을 지금 해 주세요. 판정은 원문에 적힌 조건과 기준으로만 내려 주세요.","2. 점검에서 결함이 나오고 CUELO-private 저장소 범위 안이면 고치고 검증해 주세요.","3. 결과에 맞게 HANDOFF.md 항목(끝났으면 정리, 남으면 다음 점검일)과 작업 기록(doc/history)을 고쳐 주세요.","4. 사용자 결정이 필요한 일이면 고치지 말고 멈춰서 저에게 물어봐 주세요."];function kv(e){let t=e.filter((t,n)=>""!==t||n>0&&""!==e[n-1]);for(;""===t[0];)t.shift();for(;""===t.at(-1);)t.pop();return t.join("\n")}let ky="보수 점검",kb=e=>`보고서를 읽지 못했습니다: ${e}`,kw=e=>`고침 표시를 바꾸지 못했습니다: ${e}`,kk=e=>`점검 표시를 바꾸지 못했습니다: ${e}`,kj="섹션",kS="상태",kC="점검",kN="근거",kT="항목",kI="기한",kM=(e,t)=>`${e} \xb7 ${t} 프롬프트`,kE=e=>`「${e}」`,k$="최근 7일",kR="직전 7일",kL="변화",kP="기준",kA="고침 표시",k_="고침 취소",kF=(e,t)=>`${e} \xb7 「${t}」`,kO=e=>`고침 ${e} 이후 기준`,kz="점검 완료 표시",kD="점검 취소",kW=e=>`점검 완료 ${e}`,kH="실제 문제",kU="오탐",kB="이 판정이",kq="고침 뒤",kV="고침 전",kK=(e,t)=>`${e} (${t})`,kJ="고침 전 대비",kG="알림 닫기",kY={problem:0,watch:1,unknown:2,ok:4},kZ=e=>e.check&&"ok"!==e.status?3:kY[e.status];function kQ({status:e,text:t}){return(0,r.jsx)("span",{className:"upkeep-status","data-status":e,children:t})}function kX(e){return e.split(/(\([^()]{1,24}\))/).map((e,t)=>t%2?(0,r.jsx)("span",{className:"upkeep-nowrap",children:e},t):e)}function k0({build:e,onStart:t,target:n,label:a="작업 프롬프트로 새 세션",primary:i=!1,children:l}){let[o,c]=(0,s.useState)("idle");(0,s.useEffect)(()=>{if("idle"===o)return;let e=window.setTimeout(()=>c("idle"),2e3);return()=>window.clearTimeout(e)},[o]);let d="copied"===o?"복사함":"failed"===o?"복사 실패":"복사";return(0,r.jsxs)("div",{className:"upkeep-actions",children:[(0,r.jsx)("button",{type:"button",className:"upkeep-button","data-variant":i?"primary":void 0,"aria-label":kM(a,n),onClick:()=>t(e()),children:a}),(0,r.jsx)("button",{type:"button",className:"upkeep-button","data-variant":"ghost","aria-label":kM(d,n),onClick:()=>{nT(e()).then(()=>c("copied"),()=>c("failed"))},children:(0,r.jsx)("span",{"aria-live":"polite",children:d})}),l]})}function k1({metric:e,selected:t,onSelect:n}){let s,{fix:a,check:i}=e,l=a?kr(e,a):null;return(0,r.jsxs)("tr",{className:"upkeep-row","data-status":e.status,"data-metric-row":e.id,"aria-selected":t,children:[(0,r.jsx)("td",{className:"upkeep-cell-status","data-label":kS,children:(0,r.jsx)(kQ,{status:e.status,text:w1[e.status]})}),(0,r.jsxs)("th",{scope:"row",className:"upkeep-cell-label",children:[(0,r.jsx)("button",{type:"button",className:"upkeep-row-select","aria-pressed":t,onClick:n,children:e.label}),a?(0,r.jsx)("span",{className:"upkeep-cell-sub",children:kO(w8(a.markedAt).slice(5))}):null]}),l?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("td",{className:"upkeep-cell-num","data-label":kq,children:[l.after,(0,r.jsx)("span",{className:"upkeep-cell-unit",children:kq})]}),(0,r.jsxs)("td",{className:"upkeep-cell-num","data-label":kV,children:[l.before,(0,r.jsx)("span",{className:"upkeep-cell-unit",children:kV})]}),(0,r.jsx)("td",{className:"upkeep-cell-num","data-label":kJ,children:l.change??"—"})]}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("td",{className:"upkeep-cell-num","data-label":k$,children:w9(e.unit,e.current)}),(0,r.jsx)("td",{className:"upkeep-cell-num","data-label":kR,children:w9(e.unit,e.previous)}),(0,r.jsx)("td",{className:"upkeep-cell-num","data-label":kL,children:ke(e)??"—"})]}),(0,r.jsx)("td",{className:"upkeep-cell-check","data-label":kC,children:i?(0,r.jsx)("span",{className:"upkeep-checked",children:kW(w8(i.checkedAt).slice(5))}):null}),(0,r.jsx)("td",{className:"upkeep-cell-num","data-label":kN,children:e.evidence.length?(s=e.evidence.length,`${s}건`):"—"})]})}function k2({report:e,section:t,metric:n,onStart:s,onMark:a,busy:i}){let l,o,{fix:c,check:d}=n,u=c||n.fixable&&("watch"===n.status||"problem"===n.status)?(0,r.jsx)("button",{type:"button",className:"upkeep-button","data-fix-metric":n.id,"aria-label":kF(c?k_:kA,n.label),disabled:i,onClick:()=>a("fix",n.id,!c,t.id),children:c?k_:kA}):null,h=d||"watch"===n.status||"problem"===n.status?(0,r.jsx)("button",{type:"button",className:"upkeep-button","data-check-metric":n.id,"aria-label":kF(d?kD:kz,n.label),disabled:i,onClick:()=>a("check",n.id,!d,t.id),children:d?kD:kz}):null,p=u||h?(0,r.jsxs)(r.Fragment,{children:[u,h]}):null,m=ke(n),f=c?kr(n,c):null;return(0,r.jsxs)("div",{className:"upkeep-detail","data-metric-detail":n.id,children:[(0,r.jsx)("h3",{className:"upkeep-detail-title",children:n.label}),f?(0,r.jsxs)("dl",{className:"upkeep-values",children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("dt",{children:kK(kq,f.afterWindow)}),(0,r.jsx)("dd",{children:f.after})]}),(0,r.jsxs)("div",{children:[(0,r.jsx)("dt",{children:kK(kV,f.beforeWindow)}),(0,r.jsx)("dd",{children:f.before})]}),(0,r.jsxs)("div",{"data-status":n.status,children:[(0,r.jsx)("dt",{children:kJ}),(0,r.jsx)("dd",{children:f.change??"—"})]}),(0,r.jsxs)("div",{children:[(0,r.jsx)("dt",{children:kR}),(0,r.jsx)("dd",{children:w9(n.unit,n.previous)})]})]}):(0,r.jsxs)("dl",{className:"upkeep-values",children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("dt",{children:k$}),(0,r.jsx)("dd",{children:w9(n.unit,n.current)})]}),(0,r.jsxs)("div",{children:[(0,r.jsx)("dt",{children:kR}),(0,r.jsx)("dd",{children:w9(n.unit,n.previous)})]}),(0,r.jsxs)("div",{"data-status":n.status,children:[(0,r.jsx)("dt",{children:kL}),(0,r.jsx)("dd",{children:m??"—"})]})]}),(0,r.jsxs)("p",{className:"upkeep-detail-state",children:[(0,r.jsx)(kQ,{status:n.status,text:w1[n.status]}),d?(0,r.jsx)("span",{className:"upkeep-checked",children:kW(w8(d.checkedAt).slice(5))}):null]}),c?(0,r.jsx)("p",{className:"upkeep-line",children:(0,r.jsx)("span",{className:"upkeep-line-label",children:kO(w8(c.markedAt).slice(5))})}):null,d?.note?(0,r.jsxs)("div",{className:"upkeep-block",children:[(0,r.jsx)("h4",{children:"점검 사유"}),(0,r.jsx)("p",{className:"upkeep-line",children:d.note})]}):null,n.criterionId?(0,r.jsxs)("p",{className:"upkeep-line upkeep-line-split",title:"실제 문제 / (실제 문제 + 오탐) 비율이며 판정 안 함은 제외합니다.",children:[(0,r.jsx)("span",{className:"upkeep-line-label",children:"규칙 정밀도 (최근 7일 점검)"}),(0,r.jsx)("span",{children:n.precision?(l=n.precision,`${null===l.precision?"—":`${Math.round(100*l.precision)}%`} (실제 문제 ${l.real}건, 오탐 ${l.falsePositive}건)`):"판정 없음"})]}):null,(0,r.jsxs)("div",{className:"upkeep-block",children:[(0,r.jsx)("h4",{children:kP}),(0,r.jsx)("p",{className:"upkeep-line",children:kX(n.criterion)})]}),n.handoff?(0,r.jsxs)("p",{className:"upkeep-line",children:[(0,r.jsx)("span",{className:"upkeep-line-label",children:"HANDOFF 기준"}),n.handoff.path," \xb7 「",n.handoff.title,"」"]}):null,n.note?(0,r.jsx)("p",{className:"upkeep-line upkeep-note",children:kX(n.note)}):null,n.evidence.length?(0,r.jsxs)("details",{className:"upkeep-details",children:[(0,r.jsx)("summary",{children:(o=n.evidence.length,`근거 사례 ${o}건`)}),(0,r.jsx)("ul",{className:"upkeep-evidence",children:n.evidence.map((e,t)=>(0,r.jsxs)("li",{children:[(0,r.jsxs)("span",{className:"upkeep-evidence-label",children:[e.label,void 0!==e.count?` \xb7 ${e.count}회`:"",e.timestamp?` \xb7 ${w8(e.timestamp)}`:"",ku(e,c)?` \xb7 ${ku(e,c)}`:""]}),e.detail?(0,r.jsx)("span",{className:"upkeep-evidence-detail",children:e.detail}):null,e.sessionId?(0,r.jsxs)("a",{className:"upkeep-evidence-link",href:`/?session=${encodeURIComponent(e.sessionId)}`,target:"_blank",rel:"noopener",title:e.sessionPath??e.sessionId,children:["세션 열기"," \xb7 ",e.sessionId]}):e.sessionPath?(0,r.jsx)("span",{className:"upkeep-evidence-detail",children:e.sessionPath}):null]},`${e.sessionId??e.label}-${t}`))})]}):null,"ok"!==n.status?(0,r.jsx)(k0,{build:()=>(function(e,t,n){let r=kl(e,t),s=r.metrics.find(e=>e.id===n);if(!s)throw Error(`upkeep metric not found: ${t}/${n}`);return kv([`CUELO 보수 점검: ${r.title} › ${s.label}`,"","점검 기간:",...kd(e),"",`「${s.label}」 지표 판정이 「${w1[s.status]}」입니다.`,...kp(s),"",...kg])})(e,t.id,n.id),onStart:s,target:kE(n.label),primary:!0,children:p}):p?(0,r.jsx)("div",{className:"upkeep-actions",children:p}):null,h?(0,r.jsxs)("div",{className:"upkeep-actions upkeep-verdict",role:"group","aria-label":kB,children:[(0,r.jsx)("span",{className:"upkeep-line-label","aria-hidden":"true",children:kB}),["real","false-positive"].map(e=>(0,r.jsx)("button",{type:"button",className:"upkeep-button","data-variant":d?.verdict===e?"chosen":void 0,"aria-label":kF("real"===e?kH:kU,n.label),"aria-pressed":d?.verdict===e,disabled:i,onClick:()=>a("check",n.id,!0,t.id,e),children:"real"===e?kH:kU},e))]}):null]})}let k4=e=>`${e.ref.path}-${e.ref.title}`;function k8({item:e,selected:t,onSelect:n}){let s=e.overdue?"problem":"unknown";return(0,r.jsxs)("tr",{className:"upkeep-row","data-status":s,"aria-selected":t,children:[(0,r.jsx)("td",{className:"upkeep-cell-status","data-label":kS,children:(0,r.jsx)(kQ,{status:s,text:w1[s]})}),(0,r.jsx)("th",{scope:"row",className:"upkeep-cell-label",children:(0,r.jsx)("button",{type:"button",className:"upkeep-row-select","aria-pressed":t,onClick:n,children:e.ref.title})}),(0,r.jsx)("td",{className:"upkeep-cell-due","data-label":kI,children:ki(e)})]})}function k5({report:e,item:t,onStart:n}){let s,a;return(0,r.jsxs)("div",{className:"upkeep-detail",children:[(0,r.jsx)("h3",{className:"upkeep-detail-title",children:t.ref.title}),(0,r.jsxs)("p",{className:"upkeep-detail-state",children:[(0,r.jsx)("span",{className:"upkeep-line",children:ki(t)}),(0,r.jsx)(kQ,{status:t.overdue?"problem":"unknown",text:w1[t.overdue?"problem":"unknown"]})]}),(0,r.jsx)("p",{className:"upkeep-line upkeep-note",children:(s=t.ref.path,a=t.section,`${s} \xb7 「${a}」`)}),(0,r.jsxs)("details",{className:"upkeep-details",open:!0,children:[(0,r.jsx)("summary",{children:"원문 보기"}),(0,r.jsx)("pre",{className:"upkeep-quote",children:t.ref.text})]}),(0,r.jsx)(k0,{build:()=>kv([`CUELO 보수 점검: HANDOFF 점검 기한 › ${t.ref.title}`,"","점검 기간:",...kd(e),"",t.overdue?"HANDOFF에 적힌 점검일이 지났습니다.":"HANDOFF에 남아 있는 점검 항목입니다.",...km(t),"",...kx]),onStart:n,target:kE(t.ref.title),primary:!0})]})}let k6="(max-width: 1231px)";function k3({open:e,onClose:t,onStartSession:n}){let a,i,l,o,c,[d,u]=(0,s.useState)(null),[h,p]=(0,s.useState)({phase:"idle"}),m=(0,s.useRef)(null),f=(0,s.useRef)(null),g=(0,s.useRef)(null),x=(0,s.useRef)(null),v=(0,s.useRef)(null),[y,b]=(0,s.useState)(!1),[w,k]=(0,s.useState)(null),[j,S]=(0,s.useState)(null),C=(0,s.useCallback)(async(e,t,n={})=>{x.current?.abort();let r=new AbortController;x.current=r,p({phase:"loading"});try{let t=await fetch(e,{cache:"no-store",...n,signal:r.signal}),s=await t.json().catch(()=>null);if(!t.ok||!s||!Array.isArray(s.sections))throw Error(s?.error??`HTTP ${t.status}`);u(s),p({phase:"ready"})}catch(e){if(r.signal.aborted)return;p({phase:"error",error:t(e instanceof Error?e.message:String(e))})}},[]),N=(0,s.useCallback)(e=>C(`/api/upkeep${e?"?refresh=1":""}`,kb),[C]),T=(0,s.useCallback)((e,t,n,r,s)=>{v.current={kind:e,metricId:t,sectionId:r},C("fix"===e?"/api/upkeep":"/api/upkeep/check","fix"===e?kw:kk,{method:n?"POST":"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({metricId:t,verdict:s})})},[C]);(0,s.useEffect)(()=>{let e=v.current,t=m.current;if(!e||!t||"loading"===h.phase)return;v.current=null;let n=CSS.escape(e.metricId),r=t.querySelector(`[data-${e.kind}-metric="${n}"]`)??t.querySelector(`[data-metric-detail="${n}"] :is(button:not([disabled]), summary)`)??t.querySelector(`[data-metric-row="${n}"] button`)??t.querySelector(`#upkeep-heading-${e.sectionId}`);r?.focus()},[d,h.phase]),(0,s.useEffect)(()=>()=>x.current?.abort(),[]),(0,s.useEffect)(()=>{e&&!d&&"idle"===h.phase&&N(!1)},[N,h.phase,e,d]),(0,s.useEffect)(()=>{let t=m.current;if(!e||!t)return;let n=()=>Array.from(t.querySelectorAll("a[href], button:not([disabled]), summary, [tabindex]:not([tabindex='-1'])")).filter(e=>e.getClientRects().length>0);(n()[0]??t).focus();let r=e=>{if("Tab"!==e.key)return;let r=n();if(!r.length)return;let s=document.activeElement,a=r[0],i=r[r.length-1];e.shiftKey&&(s===a||!t.contains(s))?(e.preventDefault(),i.focus()):e.shiftKey||s!==i&&t.contains(s)||(e.preventDefault(),a.focus())};return t.addEventListener("keydown",r),()=>t.removeEventListener("keydown",r)},[e]);let I=(0,s.useCallback)(e=>n(e,d?.repoCwd??null),[n,d?.repoCwd]),M=d?.sections??[],E=M.find(e=>e.id===w)??[...M].sort((e,t)=>kY[e.status]-kY[t.status])[0]??null,$=E?[...E.metrics].sort((e,t)=>kZ(e)-kZ(t)):[],R=E?ka(E.items??[]):[],L=$.find(e=>e.id===j)??null,P=L?null:R.find(e=>k4(e)===j)??null,A=L??(P?null:$[0]??null),_=A?null:P??R.find(e=>e.overdue||e.dueDate)??null,F=e=>{S(e),window.matchMedia(k6).matches&&window.requestAnimationFrame(()=>g.current?.scrollIntoView({block:"start",behavior:"smooth"}))},O="loading"===h.phase,z=d?w6(d):null,D=!!d&&d.sections.some(e=>ko(e).length>0||(e.items??[]).some(e=>e.overdue)||e.warnings.length>0),W=E?function(e){let t=new Map;for(let n of e)t.set(n.criterion,(t.get(n.criterion)??0)+1);let n=null;for(let[e,r]of t)(null===n||r>(t.get(n)??0))&&(n=e);return n}(E.metrics):null,H=R.filter(e=>e.overdue||e.dueDate),U=R.filter(e=>!e.overdue&&!e.dueDate),B=e=>(0,r.jsx)(k8,{item:e,selected:_===e,onSelect:()=>F(k4(e))},k4(e));return(0,r.jsxs)("section",{ref:m,className:"upkeep-view",role:"dialog","aria-modal":"true","aria-labelledby":"upkeep-title",tabIndex:-1,hidden:!e,onKeyDown:e=>{"Escape"!==e.key||e.nativeEvent.isComposing||(e.preventDefault(),e.stopPropagation(),t())},children:[(0,r.jsxs)("aside",{className:"upkeep-list","aria-label":ky,children:[(0,r.jsxs)("div",{className:"upkeep-list-bar",children:[(0,r.jsxs)("button",{type:"button",className:"upkeep-back",onClick:t,children:[(0,r.jsxs)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"m12 19-7-7 7-7"}),(0,r.jsx)("path",{d:"M19 12H5"})]}),"대화로"]}),(0,r.jsxs)("button",{type:"button",className:"upkeep-button","data-variant":"ghost",onClick:()=>void N(!0),disabled:O,"aria-busy":O,children:[(0,r.jsxs)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[(0,r.jsx)("path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8"}),(0,r.jsx)("path",{d:"M21 3v5h-5"}),(0,r.jsx)("path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16"}),(0,r.jsx)("path",{d:"M8 16H3v5"})]}),O?"읽는 중…":"다시 읽기"]})]}),(0,r.jsx)("h2",{id:"upkeep-title",children:ky}),d&&z?(0,r.jsxs)("dl",{className:"upkeep-meta",children:[(0,r.jsxs)("div",{children:[(0,r.jsx)("dt",{children:"최근 7일"}),(0,r.jsx)("dd",{children:z.current})]}),(0,r.jsxs)("div",{children:[(0,r.jsx)("dt",{children:"직전 7일"}),(0,r.jsx)("dd",{children:z.previous})]}),(0,r.jsxs)("div",{children:[(0,r.jsx)("dt",{children:"생성"}),(0,r.jsx)("dd",{children:w8(d.generatedAt)})]}),(0,r.jsxs)("div",{children:[(0,r.jsx)("dt",{children:"세션 파일"}),(0,r.jsx)("dd",{children:(a=d.scannedFiles.toLocaleString("ko-KR"),i=(d.scanMs/1e3).toFixed(1),`${a}개 \xb7 ${i}초`)})]})]}):null,d?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("nav",{className:"upkeep-sections","aria-label":"섹션별 상태",children:[(0,r.jsx)("h3",{className:"upkeep-group-title","aria-hidden":"true",children:kj}),M.map(e=>(0,r.jsxs)("button",{type:"button",className:"upkeep-section-item","data-status":e.status,"aria-pressed":e===E,onClick:()=>{var t;k(t=e.id),S(null),window.matchMedia(k6).matches&&f.current?.scrollIntoView({block:"start",behavior:"smooth"}),window.requestAnimationFrame(()=>m.current?.querySelector(`#upkeep-heading-${CSS.escape(t)}`)?.focus({preventScroll:!0}))},children:[(0,r.jsx)("span",{className:"upkeep-section-name",children:e.title}),(0,r.jsx)(kQ,{status:e.status,text:w1[e.status]})]},e.id))]}),(0,r.jsxs)("div",{className:"upkeep-full",children:[(0,r.jsx)("h3",{className:"upkeep-group-title",children:"전체 점검 프롬프트"}),D?(0,r.jsx)(k0,{build:()=>(function(e){let t=["CUELO 보수 전체 점검","","점검 기간:",...kd(e),"","보수 대시보드에서 정상이 아닌 지표, 점검일이 지난 HANDOFF 항목, 읽지 못한 자료만 모았습니다. 섹션 순서대로 처리하고, 항목마다 원인과 조치를 따로 적어 주세요.",...kc(e.sections.flatMap(e=>e.metrics))],n=0;for(let r of e.sections){let e=ko(r),s=ka(r.items??[]).filter(e=>e.overdue);if(e.length||s.length||r.warnings.length){for(let a of(n+=e.length+s.length,t.push("",`# ${r.title} (${w1[r.status]})`),e))t.push("",`## ${a.label}`,...kp(a));for(let e of s)t.push("",`## 점검일 지남: ${e.ref.title}`,...km(e));t.push(...kf(r))}}return n||t.push("","이번 보고서에는 정상이 아닌 지표와 기한 지난 항목이 없습니다."),t.push("",...kg,"6. 점검일이 지난 HANDOFF 항목은 원문에 적힌 조건과 기준으로 판정하고, 결과에 맞게 그 항목을 고쳐 주세요."),kv(t)})(d),onStart:I,target:"전체 점검",label:"새 세션"}):(0,r.jsx)("p",{className:"upkeep-note",children:"정상이 아닌 지표와 기한 지난 항목이 없습니다."})]})]}):null]}),(0,r.jsx)("div",{ref:f,className:"upkeep-main","aria-busy":O,children:d?(0,r.jsxs)(r.Fragment,{children:["error"===h.phase?(0,r.jsx)("p",{className:"upkeep-banner",role:"alert",children:h.error}):null,null===d.repoCwd?(0,r.jsx)("p",{className:"upkeep-banner",children:"CUELO 저장소 경로를 찾지 못했습니다. 「작업 프롬프트로 새 세션」은 프롬프트를 복사만 합니다."}):null,E?(0,r.jsxs)("section",{className:"upkeep-section",id:`upkeep-section-${E.id}`,"aria-labelledby":`upkeep-heading-${E.id}`,children:[(0,r.jsxs)("p",{className:"upkeep-crumb",children:[ky," / ",kj]}),(0,r.jsxs)("div",{className:"upkeep-section-head",children:[(0,r.jsxs)("div",{className:"upkeep-section-title",children:[(0,r.jsx)("h3",{id:`upkeep-heading-${E.id}`,tabIndex:-1,children:E.title}),(0,r.jsx)(kQ,{status:E.status,text:w1[E.status]})]}),(0,r.jsx)(k0,{build:()=>(function(e,t){let n=kl(e,t),r=ko(n),s=r.length?r:n.metrics.filter(e=>!e.check),a=ka(n.items??[]),i=a.filter(e=>e.overdue),l=i.length?i:a,o=[`CUELO 보수 점검: ${n.title} 섹션`,"","점검 기간:",...kd(e),"",`섹션 판정: ${w1[n.status]} \xb7 ${n.summary}`];for(let e of(s.length&&o.push(r.length?"아래는 이 섹션에서 정상이 아닌 지표입니다.":"이 섹션에서 점검 완료 표시가 없는 지표는 모두 정상으로 나왔습니다. 판정이 맞는지 근거로 확인해 주세요."),o.push(...kc(n.metrics)),s))o.push("",`## ${e.label}`,...kp(e));if(l.length)for(let e of(o.push("",i.length?"점검일이 지난 HANDOFF 항목:":"남아 있는 HANDOFF 점검 항목:"),l))o.push("",`## ${e.ref.title}`,...km(e));return o.push(...kf(n),"",...s.length?kg:kx),kv(o)})(d,E.id),onStart:I,target:(l=E.title,`${l} 섹션`),label:"섹션 프롬프트"})]}),(0,r.jsx)("p",{className:"upkeep-summary",children:E.summary}),W?(0,r.jsxs)("p",{className:"upkeep-line",children:[(0,r.jsx)("span",{className:"upkeep-line-label",children:kP}),kX(W)]}):null,E.warnings.length?(0,r.jsxs)("div",{className:"upkeep-warnings",children:[(0,r.jsx)("span",{className:"upkeep-line-label",children:"읽지 못한 자료"}),(0,r.jsx)("ul",{children:E.warnings.map(e=>(0,r.jsx)("li",{children:e},e))})]}):null,E.metrics.length?(0,r.jsxs)("table",{className:"upkeep-table",children:[(0,r.jsx)("thead",{children:(0,r.jsxs)("tr",{children:[(0,r.jsx)("th",{scope:"col",children:kS}),(0,r.jsx)("th",{scope:"col",children:"지표"}),(0,r.jsx)("th",{scope:"col",className:"upkeep-cell-num",children:k$}),(0,r.jsx)("th",{scope:"col",className:"upkeep-cell-num",children:kR}),(0,r.jsx)("th",{scope:"col",className:"upkeep-cell-num",children:kL}),(0,r.jsx)("th",{scope:"col",children:kC}),(0,r.jsx)("th",{scope:"col",className:"upkeep-cell-num",children:kN})]})}),(0,r.jsx)("tbody",{children:$.map(e=>(0,r.jsx)(k1,{metric:e,selected:e===A,onSelect:()=>F(e.id)},e.id))})]}):"ops"!==E.id?(0,r.jsx)("p",{className:"upkeep-note",children:"이 섹션에는 지표가 없습니다."}):null,"ops"===E.id?R.length?(0,r.jsxs)(r.Fragment,{children:[H.length?(0,r.jsxs)("table",{className:"upkeep-table","data-kind":"due",children:[(0,r.jsx)("thead",{children:(0,r.jsxs)("tr",{children:[(0,r.jsx)("th",{scope:"col",children:kS}),(0,r.jsx)("th",{scope:"col",children:kT}),(0,r.jsx)("th",{scope:"col",children:kI})]})}),(0,r.jsx)("tbody",{children:H.map(B)})]}):null,U.length?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("button",{type:"button",className:"upkeep-button upkeep-fold","data-variant":"ghost","aria-expanded":y,"aria-controls":"upkeep-due-folded",onClick:()=>b(e=>!e),children:y?(o=U.length,`조건부\xb7날짜 없음 ${o}건 접기`):(c=U.length,`조건부\xb7날짜 없음 ${c}건 보기`)}),(0,r.jsxs)("table",{id:"upkeep-due-folded",className:"upkeep-table","data-kind":"due",hidden:!y,children:[(0,r.jsx)("thead",{children:(0,r.jsxs)("tr",{children:[(0,r.jsx)("th",{scope:"col",children:kS}),(0,r.jsx)("th",{scope:"col",children:kT}),(0,r.jsx)("th",{scope:"col",children:kI})]})}),(0,r.jsx)("tbody",{children:U.map(B)})]})]}):null]}):(0,r.jsx)("p",{className:"upkeep-note",children:"HANDOFF에 남은 점검 항목이 없습니다."}):null]}):null]}):"error"===h.phase?(0,r.jsxs)("div",{className:"upkeep-empty",role:"alert",children:[(0,r.jsx)("p",{children:h.error}),(0,r.jsx)("button",{type:"button",className:"upkeep-button",onClick:()=>void N(!1),children:"다시 시도"})]}):(0,r.jsx)("p",{className:"upkeep-empty",role:"status",children:"세션 기록을 읽는 중입니다. 몇 초 걸립니다."})}),(0,r.jsx)("aside",{ref:g,className:"upkeep-inspector","aria-label":"고른 지표",children:d&&E&&A?(0,r.jsx)(k2,{report:d,section:E,metric:A,onStart:I,onMark:T,busy:O}):d&&_?(0,r.jsx)(k5,{report:d,item:_,onStart:I}):d?(0,r.jsx)("p",{className:"upkeep-note",children:"표에서 지표를 고르면 값과 근거가 여기에 나옵니다."}):null})]})}function k7({message:e,onDismiss:t}){return((0,s.useEffect)(()=>{if(!e)return;let n=window.setTimeout(t,8e3);return()=>window.clearTimeout(n)},[e,t]),e)?(0,r.jsxs)("div",{className:"upkeep-notice",role:"status",children:[(0,r.jsx)("p",{children:e}),(0,r.jsx)("button",{type:"button",onClick:t,"aria-label":kG,title:kG,children:"✕"})]}):null}let k9="pi-web:last-open-by-workspace";function je(){try{return window.localStorage}catch{return null}}function jt(e){let t=e.getItem(k9);if(!t)return{};try{let e=JSON.parse(t);return null===e||"object"!=typeof e||Array.isArray(e)?{}:e}catch{return{}}}function jn(e,t=je()){if(t)try{let n=jt(t);if(!(e in n))return;delete n[e],0===Object.keys(n).length?t.removeItem(k9):t.setItem(k9,JSON.stringify(n))}catch{}}let jr="button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex='-1'])",js="omp-web:wide-chat",ja="omp-web:inspector-open";function ji(e){return e.current+=1,e.current}let jl=[{id:"chat",label:"layout.presetChat",title:"layout.presetChatTitle"},{id:"log",label:"layout.presetLog",title:"layout.presetLogTitle"},{id:"preview",label:"layout.presetPreview",title:"layout.presetPreviewTitle"}];function jo(){try{return gO(window.localStorage)}catch{return gO(null)}}function jc(e){let t=document.querySelector(`[data-dispatch-key="${CSS.escape(e)}"]`);return t&&0!==t.getClientRects().length?t.querySelector(".answer-dispatch-open")??t.closest(".answer-dispatch")?.querySelector(".answer-dispatch-toggle")??null:null}let jd={chat:"message-square",process:"list-tree",subagents:"bot",files:"file-text",resource:"users",sidechat:"messages-square",efficiency:"gauge",plugins:"puzzle",memory:"brain",browser:"globe"};function ju(){let e=document.activeElement;return e instanceof HTMLElement&&e.closest("[data-top-panel-opener]")?e:document.querySelector(".workspace-header-more")}function jh({auxiliaryDeck:e,resourcePanel:t}={}){var n,u,p,m,S,C,N;let T,I,M,E,$,R,L,P,A,_,O,z,D,B,q,V,K,J,G,Y,Z,Q=(0,i.useRouter)(),X=(0,i.useSearchParams)(),[ee]=(0,s.useState)(()=>{let e;return{requestedCwd:e=X.get("cwd")?.trim()||null,sessionId:e?null:X.get("session")}}),{preference:et,toggleTheme:en}=nN(),{locale:es,setLocale:ea,t:ei,supportedLocales:ec}=(0,F.s)(),{tt:eu}=er(),eh=eu("translator.tab"),ef=function(){let[e,t]=(0,s.useState)(null),[n,r]=(0,s.useState)(!1),a=(0,s.useCallback)(()=>{t("Notification"in window?Notification.permission:null)},[]);return(0,s.useEffect)(()=>{try{r("1"===window.localStorage.getItem(f2))}catch{}return a(),window.addEventListener("focus",a),()=>window.removeEventListener("focus",a)},[a]),{permission:e,dismissed:n,request:(0,s.useCallback)(()=>{"Notification"in window&&"default"===Notification.permission?Notification.requestPermission().then(t,a):a()},[a]),dismiss:(0,s.useCallback)(()=>{r(!0);try{window.localStorage.setItem(f2,"1")}catch{}},[])}}(),eg=(0,s.useSyncExternalStore)(W.subscribe,W.getSnapshot,H);(0,s.useEffect)(()=>{let e=window.visualViewport;if(!e)return;let t=document.documentElement,n=null,r=()=>{n=null,function({hasFocusedEditable:e,innerHeight:t,viewportHeight:n,viewportScale:r}){let s=.01>Math.abs(r-1);return e&&s&&t-n>1}({hasFocusedEditable:hX(),innerHeight:window.innerHeight,viewportHeight:e.height,viewportScale:e.scale})?t.style.setProperty("--app-viewport-height",`${e.height}px`):t.style.removeProperty("--app-viewport-height");let r=0!==window.scrollX||0!==window.scrollY,s=.01>Math.abs(e.scale-1);r&&s&&window.scrollTo(0,0)},s=()=>{null!==n&&window.cancelAnimationFrame(n),n=window.requestAnimationFrame(r)};return s(),e.addEventListener("resize",s),e.addEventListener("scroll",s),window.addEventListener("resize",s),window.addEventListener("focusin",s),window.addEventListener("focusout",s),window.addEventListener("pageshow",s),()=>{e.removeEventListener("resize",s),e.removeEventListener("scroll",s),window.removeEventListener("resize",s),window.removeEventListener("focusin",s),window.removeEventListener("focusout",s),window.removeEventListener("pageshow",s),null!==n&&window.cancelAnimationFrame(n),t.style.removeProperty("--app-viewport-height")}},[]);let ex=h6(),ev=U(),{soundEnabled:ey,onSoundToggle:eb,playCueSound:ew,preloadCueSound:ek,unlockAudio:ej,soundEnabledRef:eS}=function(){let[e,t]=(0,s.useState)(()=>{let e=localStorage.getItem("omp-sound-enabled");return null===e||"true"===e}),n=(0,s.useRef)(e);(0,s.useEffect)(()=>{n.current=e},[e]);let r=(0,s.useRef)(null),a=(0,s.useRef)(null),i=(0,s.useRef)(0),l=(0,s.useRef)(new Map),o=(0,s.useRef)(new Map),c=(0,s.useRef)(new Map),d=(0,s.useRef)(null);sF();let u=(0,s.useRef)(new Map),h=(0,s.useRef)(new Map),p=(0,s.useRef)(new Map),m=(0,s.useCallback)(e=>{let t=h.current.get(e);return t||(t=yj(e).catch(t=>{throw h.current.delete(e),t}),h.current.set(e,t)),t},[]),f=(0,s.useCallback)(()=>{if(r.current&&"closed"!==r.current.state)return r.current;try{r.current=new AudioContext}catch{return null}return r.current},[]),g=(0,s.useCallback)(()=>(d.current??=rR(),d.current),[]);(0,s.useEffect)(()=>{g()},[g]);let x=(0,s.useCallback)(async e=>{if(!e)return;let t=await g(),r=r8(e);for(let s of rw){let a=r?r$(r4(r),r.id,s):rE(t,e,s);if(a){for(let e of a.stickers){if(p.current.has(e))continue;let t=new Image;t.decoding="async",t.src=e,p.current.set(e,t)}if(n.current)for(let e of a.voices)m(e).catch(()=>{})}}},[g,m]),v=(0,s.useCallback)(()=>{i.current+=1;let e=a.current;if(a.current=null,e)try{e.stop()}catch{}},[]),y=(0,s.useCallback)((e=!1)=>{if(!e&&!n.current)return;let t=f();t&&"suspended"===t.state&&t.resume().catch(()=>{})},[f]);(0,s.useEffect)(()=>{let e=()=>y(),t={capture:!0,passive:!0};return window.addEventListener("pointerdown",e,t),window.addEventListener("keydown",e,t),()=>{window.removeEventListener("pointerdown",e,t),window.removeEventListener("keydown",e,t)}},[y]);let b=(0,s.useCallback)(()=>{let e=!n.current;e?y(!0):v(),n.current=e,localStorage.setItem("omp-sound-enabled",String(e)),t(e)},[v,y]),w=(0,s.useCallback)(e=>{if(!n.current)return;let t=f();if(!t)return;v();let r=i.current,s=()=>{if(r===i.current&&n.current&&(!e||e()))try{yk(t)}catch{}};"suspended"===t.state?t.resume().then(s).catch(()=>{}):s()},[f,v]);return{soundEnabled:e,onSoundToggle:b,playCueSound:(0,s.useCallback)(async(e,t="done",r)=>{let s=await g(),d=r8(e),h=null===t?null:d?r$(r4(d),d.id,t):rE(s,e,t),p=`${d?.alias??e??""}\u0000${t??""}`,x=h?rL(h.stickers,o.current.get(p)??null):null;null!==x&&o.current.set(p,x);let y=h?rL(h.voices,l.current.get(p)??null):null,b=y?h?.lines.get(y)??null:null;!y&&h&&null!==(b=rL(h.captions,c.current.get(p)??null))&&c.current.set(p,b);let k={sticker:x,text:b};if(!n.current||r&&!r())return k;let j=f();if(!j)return k;if(!y)return null!==t&&rj[t]||w(r),k;v();let S=i.current,C=()=>S!==i.current||!n.current||void 0!==r&&!r();return(async()=>{if(!("suspended"===j.state&&(await j.resume().catch(()=>{}),C())))try{let e=u.current.get(y);e||(e=m(y).then(e=>j.decodeAudioData(e.slice(0))).catch(e=>{throw u.current.delete(y),e}),u.current.set(y,e));let t=await e;if(C())return;let n=j.createBufferSource(),r=j.createGain();n.buffer=t,n.connect(r),r.connect(j.destination),r.gain.setValueAtTime(.82,j.currentTime),n.onended=()=>{a.current===n&&(a.current=null)},a.current=n,n.start(),l.current.set(p,y)}catch{if(C()||null!==t&&rj[t])return;try{yk(j)}catch{}}})(),k},[f,w,v,g,m]),preloadCueSound:x,unlockAudio:y,soundEnabledRef:n}}(),eN=function(){let[e,t]=(0,s.useState)({status:"idle",data:null,error:null}),[n,r]=(0,s.useState)(!0),a=(0,s.useRef)(null);return(0,s.useEffect)(()=>{var e;let n,s,i,l,o,c,d,u,h,p,m=(s=(e={onResult(e){t(e),r(!1)}}).intervalMs??15e3,i=e.setIntervalImpl??setInterval,l=e.clearIntervalImpl??clearInterval,o=e.initialData??null,c=null,d=0,u=!1,h=!1,p=async t=>{c?.abort(),c=new AbortController;let n=++d,r=await sh({refresh:t,previous:o,signal:c.signal,fetchImpl:e.fetchImpl});return u&&n===d&&(r.data&&(o=r.data),e.onResult(r)),r},{start(){u||(u=!0,p(!1),n=i(()=>{h||p(!1)},s))},refresh:()=>u?p(!0):Promise.resolve(sd(o,new sl("사용량 폴링이 중지되었습니다.","aborted"))),setPaused(e){h=e},stop(){u=!1,d+=1,c?.abort(),c=null,l(n),n=void 0}});return a.current=m,m.start(),()=>{m.stop(),a.current===m&&(a.current=null)}},[]),{state:e,loading:n,refresh:(0,s.useCallback)(async()=>{let e=a.current;if(!e)return{status:"error",data:null,error:new sl("사용량 폴링이 시작되지 않았습니다.","aborted")};r(!0);let t=await e.refresh();return r(!1),t},[]),setPaused:(0,s.useCallback)(e=>{a.current?.setPaused(e)},[])}}();n=eN.state.data?.reports,(0,s.useEffect)(()=>{sL(n)},[n]);let[eT,eI]=(0,s.useState)(!1),[eM,eE]=(0,s.useState)(!1),[e$,eR]=(0,s.useState)(!1),[eL,eP]=(0,s.useState)(!1),[eA,e_]=(0,s.useState)(null),eF=(0,s.useCallback)(()=>e_(null),[]),eO=(0,s.useRef)(new Set),ez=(0,s.useCallback)(()=>{eS.current&&ew(null,"done")},[ew,eS]),[eD,eW]=(0,s.useState)(null),[eH,eU]=(0,s.useState)(null),[eB,eq]=(0,s.useState)(null),eV=(0,s.useRef)(0),eK=(0,s.useRef)(null),[eJ,eG]=(0,s.useState)(null),eY=(0,s.useRef)(0),eZ=(0,s.useCallback)(e=>{eG(t=>t?.id===e?null:t)},[]),[eQ,eX]=(0,s.useState)(!0);(0,s.useEffect)(()=>{try{eX("0"!==window.localStorage.getItem(js))}catch{}},[]);let e0=(0,s.useCallback)(()=>{eX(e=>{let t=!e;try{window.localStorage.setItem(js,t?"1":"0")}catch{}return t})},[]),[e1,e2]=(0,s.useState)(null),[e4,e8]=(0,s.useState)(),[e5,e6]=(0,s.useState)(()=>ee.requestedCwd?"validating":"idle"),[e3,e7]=(0,s.useState)(null),[e9,te]=(0,s.useState)(0),[tt,tn]=(0,s.useState)(0),tr=(0,s.useRef)(0),[ts,ta]=(0,s.useState)(null),[ti,tl]=(0,s.useState)(0),[to,tc]=(0,s.useState)(!0),[td,tu]=(0,s.useState)(0),[th,tp]=(0,s.useState)(!1),[tm,tf]=(0,s.useState)(!1),[tg,tx]=(0,s.useState)(!1),[tv,ty]=(0,s.useState)(!0),[tb,tw]=(0,s.useState)(null),tk=(0,s.useRef)(!1),tj=(0,s.useRef)(!1),tS=(0,s.useRef)(new Map),[tC,tN]=(0,s.useState)(new Set),tT=(0,s.useRef)(-1);tT.current=ts?ti:-1;let[tI,tM]=(0,s.useState)(0),[tE,t$]=(0,s.useState)(0),[tR,tL]=(0,s.useState)(!1),[tP,tA]=(0,s.useState)(null),[t_,tF]=(0,s.useState)(null),[tO]=(0,s.useState)(()=>{let e;return e=0,{reset(){e+=1,tF(null)},check(t,n){let r=++e;tF("checking"),t().then(t=>{r===e&&tF("fresh"===t.status?function(e,t){if(!t.accountKey)return"unknown";let n=e.filter(e=>e.provider===t.provider&&e.accountKey===t.accountKey);return n.some(e=>!0!==e.disabled&&!e.authError)?"recovered":n.length>0?"still-failing":"unknown"}(t.data.reports,n):"unknown")},()=>{r===e&&tF("unknown")})}}}),[tz,tD]=(0,s.useState)(null),[tW,tH]=(0,s.useState)(0),tU=(0,s.useRef)(null),tB=(0,s.useRef)(null),[tq,tV]=(0,s.useState)(!1),[tJ,tG]=(0,s.useState)(!1),[tY,tZ]=(0,s.useState)(null),[tQ,tX]=(0,s.useReducer)(f,h),[t0,t1]=(0,s.useState)("characters"),[t2,t4]=(0,s.useState)("governor"),[t8,t5]=(0,s.useState)({sessionId:null,widgets:[]}),[t6,t3]=(0,s.useState)(()=>g(0)),[t7,t9]=(0,s.useState)(!1),[ne]=(0,s.useState)(jo),[nt]=(0,s.useState)(gz),[nn,nr]=(0,s.useState)([]),[ns,na]=(0,s.useState)({sessions:[],complete:!1}),[ni,nl]=(0,s.useState)(!1),[no,nc]=(0,s.useState)(!1),[nd,nu]=(0,s.useState)(0),nh=(0,s.useRef)(null),np=(0,s.useRef)(null),nm=(0,s.useRef)(null),nf=(0,s.useCallback)(()=>{nu(e=>e+1)},[]),ng=(0,s.useCallback)(e=>{e&&eE(!0),eI(e),e||nf()},[nf]);(0,s.useEffect)(()=>{"translator"===new URL(window.location.href).searchParams.get("view")&&ng(!0)},[ng]);let nx=(0,s.useCallback)(e=>{e&&eP(!0),eR(e),e||nf()},[nf]);(0,s.useEffect)(()=>{"upkeep"===new URLSearchParams(window.location.search).get("view")&&nx(!0)},[nx]);let nv=(0,s.useCallback)(e=>{np.current=e},[]),ny=(0,s.useRef)(!1),[nb,nw]=(0,s.useState)(!1),nk=(0,s.useRef)(!1),nj=(0,s.useRef)(!1),nS=(0,s.useRef)(0),[nC,nI]=(0,s.useState)(!1),[nM,nE]=(0,s.useState)(!1),n$=(0,s.useRef)(null),[nR,nL]=(0,s.useState)(null),[nP,nA]=(0,s.useState)(null),n_=(0,s.useRef)(null),nF=(0,s.useRef)(!1);n_.current=nR,(0,s.useEffect)(()=>{nL(hT())},[]),(0,s.useEffect)(()=>{let e=!1,t=null,n=n=>{if(e||ny.current||"IDLE"===n.phase||!n.requestId||!n.stageHash)return;let r=`${window.location.pathname}${window.location.search}${window.location.hash}`,s=function(e){let t=ut();if(!t.ok)return{entered:!1,error:t.error};let n={schemaVersion:2,requestId:e.requestId,stageHash:e.stageHash,clientId:hC(),sessionId:e.sessionId,resumeUrl:e.resumeUrl};try{sessionStorage.setItem(hy,JSON.stringify(n))}catch(e){return{entered:!1,error:e instanceof Error?e.message:String(e)}}let r=new URLSearchParams({mode:"wait",requestId:n.requestId,stageHash:n.stageHash,clientId:n.clientId});return window.location.replace(`/api/update-maintenance?${r}`),{entered:!0}}({requestId:n.requestId,stageHash:n.stageHash,sessionId:eD?.id??null,resumeUrl:r});if(s.entered){ny.current=!0;return}t=s.error},r=async()=>{if(!e&&!ny.current)try{let l=nF.current?null:n_.current,o=await hM({sessionId:eD?.id??null,resumeUrl:`${window.location.pathname}${window.location.search}${window.location.hash}`,preservationError:t,update:l?{requestId:l.requestId,stageHash:l.stageHash}:null});nS.current=0;let c=(r=nk.current,s=n$.current,((a=o.serverBootId)&&s?a!==s:r)?"reload":r?"resume":"continue");if("reload"===c){var r,s,a,i=eD?.id??null;ut();try{sessionStorage.setItem(hw,JSON.stringify({schemaVersion:1,sessionId:i,at:Date.now()}))}catch{}window.location.reload();return}"resume"===c&&(nk.current=!1,nw(!1),nI(!1)),o.serverBootId&&(n$.current=o.serverBootId),nj.current=!0,!e&&o.update&&(nA(o.update),o.update.cleanup&&"running"!==o.update.cleanup.status&&(nF.current=!0)),n(o)}catch{nS.current+=1,!e&&nj.current&&nS.current>=2&&(nk.current=!0,nw(!0))}},s=e=>{n(e.detail??{}),t&&r()};window.addEventListener("ompweb:update-maintenance",s),r();let a=window.setInterval(()=>void r(),2e3);return()=>{e=!0,window.clearInterval(a),window.removeEventListener("ompweb:update-maintenance",s)}},[eD?.id]),(0,s.useEffect)(()=>{if(!nb)return;let e=window.setTimeout(()=>nI(!0),12e4);return()=>window.clearTimeout(e)},[nb]),(0,s.useEffect)(()=>{(function(e,t=Date.now()){let n,r=sessionStorage.getItem(hw);if(!r)return!1;try{n=JSON.parse(r)}catch{n=null}return!n||1!==n.schemaVersion||"number"!=typeof n.at||t-n.at>6e4||null!==n.sessionId&&"string"!=typeof n.sessionId?(sessionStorage.removeItem(hw),!1):n.sessionId===e&&(sessionStorage.removeItem(hw),!0)})(eD?.id??null)&&nE(!0)},[eD?.id]),(0,s.useEffect)(()=>{if(!nM)return;let e=window.setTimeout(()=>nE(!1),8e3);return()=>window.clearTimeout(e)},[nM]);let nO=nR?.requestId??null,nz=nR?.dismissed??!0,nD=nP?.requestId??null,nW=nP?.deploymentCompleted??!1,nH=nP?.cleanup?.status??null;(0,s.useEffect)(()=>{if(!nO||nz||nD!==nO||!nW)return;let e=hS(nH);if(null===e)return;let t=window.setTimeout(()=>{nL(hI(nO))},e);return()=>window.clearTimeout(t)},[nO,nz,nD,nW,nH]),(0,s.useEffect)(()=>{let e=function(){let e=sessionStorage.getItem(hy);if(!e)return null;try{let t=JSON.parse(e);if(2!==t.schemaVersion||"string"!=typeof t.requestId||!/^[0-9a-f]{32}$/.test(t.requestId)||"string"!=typeof t.stageHash||!/^[0-9a-f]{64}$/.test(t.stageHash)||"string"!=typeof t.clientId||"string"!=typeof t.resumeUrl||null!==t.sessionId&&"string"!=typeof t.sessionId)return null;return t}catch{return null}}();if(!e||e.sessionId&&eD?.id!==e.sessionId)return;let t=!1;return h$(e).then(e=>{t||"resumed"!==e||(nF.current=!1,nL(hT()),te(e=>e+1),tM(e=>e+1))}).catch(()=>{}),()=>{t=!0}},[eD?.id]);let nU=(0,s.useCallback)(e=>{if("ArrowDown"===e.key||"ArrowUp"===e.key){let t=nm.current,n=e.target;if(!t||e.nativeEvent.isComposing||document.activeElement!==n||n.closest(".palette-search-results"))return;let r=Array.from(t.querySelectorAll(".workspace-command-list button"));if(0===r.length)return;let s="ArrowDown"===e.key,a=r.indexOf(n);if(a<0&&!s)return;e.preventDefault(),a<0?r[0].focus():s||0!==a?r[(a+(s?1:-1))%r.length].focus():t.querySelector(".palette-search-field > input")?.focus();return}if("Tab"!==e.key)return;let t=nm.current;if(!t)return;let n=Array.from(t.querySelectorAll(jr));if(0===n.length)return;let r=e.shiftKey?n[0]:n[n.length-1],s=document.activeElement;s!==r&&t.contains(s)||(e.preventDefault(),(e.shiftKey?n[n.length-1]:n[0]).focus())},[]),[nB,nq]=(0,s.useState)(!0),[nV,nK]=(0,s.useState)(!1),[nJ,nG]=(0,s.useState)(!1),nY=(0,s.useRef)(nB),nZ=(0,s.useRef)(!1),nQ=(0,s.useRef)(!0),nX=(0,s.useRef)(null);nY.current=nB;let n0=(T=(u={clientPainted:nV,compactWorkspace:eg,requestedOpen:nB}).requestedOpen&&u.clientPainted,{laidOut:u.requestedOpen&&(!u.compactWorkspace||u.clientPainted),presented:T,drawer:T&&u.compactWorkspace}),n1=(0,s.useCallback)(e=>{nZ.current=e,nq(e),tX(e?{type:"open-layer",layer:"navigator-drawer"}:{type:"close-layer"})},[]),n2=(0,s.useRef)(null),n8=(0,s.useRef)(!1),n5=(0,s.useRef)(260),n6=(0,s.useCallback)(()=>(function(e){let{viewportWidth:t,rightPanelOpen:n,rightPanelWidth:r}=e;if(t<=640)return 480;let s=t<960;return Math.min(480,t-(s?320:420)-(!s&&n?r:0))})({viewportWidth:window.innerWidth,rightPanelOpen:!1,rightPanelWidth:0}),[]),n3=yw({ariaLabel:ei("layout.resizeSidebar"),cssVariable:"--sidebar-width",defaultWidth:260,getMaxWidth:n6,growthDirection:"right",maxWidth:480,minWidth:180,storageKey:"omp-sidebar-width",widthRef:n5}),n7=n3.reclampWidth,n9=(0,s.useRef)(372),re=(0,s.useCallback)(()=>{let e=nh.current;if(!e)return window.innerWidth;let t=getComputedStyle(e);return e.clientWidth-(Number.parseFloat(t.paddingLeft)||0)-(Number.parseFloat(t.paddingRight)||0)},[]),rt=(0,s.useCallback)(()=>yg(re()),[re]),rn=!eg&&n0.laidOut?n3.width:null,rr=(0,s.useCallback)(()=>{let e=nh.current,t=e&&Number.parseFloat(getComputedStyle(e).columnGap)||0;return function(e){let{shellContentWidth:t,navigatorWidth:n,zoneGap:r}=e,s=t-60-(null===n?0:Math.min(300,Math.max(240,n)))-560-r*((null===n?3:4)-1)-1;return Math.max(yg(t),Math.floor(s))}({shellContentWidth:re(),navigatorWidth:rn,zoneGap:t})},[rn,re]),[rs,ra]=(0,s.useState)(null),ri=(0,s.useCallback)(()=>{let e=function(e){if("u"<typeof document)return null;let t=document.createElement("div");t.setAttribute("aria-hidden","true"),t.style.cssText="position:fixed;left:-3000px;top:0;inline-size:1000px;visibility:hidden;pointer-events:none;contain:layout style;",t.innerHTML=`<div class="process-log-body" style="overflow:visible"><div class="tool-call-card"><div class="tool-call-body"><div class="shell-output-preview"><div class="shell-output-panel"><div class="shell-output-body" style="overflow:visible"><span class="shell-output-line" style="white-space:pre">${"0".repeat(100)}</span></div></div></div></div></div></div>`,document.body.appendChild(t);try{let n=t.querySelector(".shell-output-body"),r=t.querySelector(".shell-output-line");if(!n||!r)return null;let s=r.getBoundingClientRect().width/100;if(!(s>0))return null;let a=1e3-yy(n),i=e?[...e.querySelectorAll(".process-log .shell-output-body")].find(e=>e.getClientRects().length>0):void 0;return e&&i&&(a=e.getBoundingClientRect().width-yy(i)),{charWidth:s,chrome:a}}finally{t.remove()}}(document.getElementById("workspace-auxiliary-panel"));return ra(t=>t&&e&&t.charWidth===e.charWidth&&t.chrome===e.chrome?t:e),e},[]);(0,s.useEffect)(()=>{let e=!1;return document.fonts.ready.then(()=>{e||ri()}),()=>{e=!0}},[ri]);let rl=(0,s.useCallback)(e=>rs?ei("layout.inspectorReadout",{width:e,chars:rs.charWidth>0?Math.max(0,Math.floor((e-rs.chrome)/rs.charWidth+1e-6)):0}):`${e}px`,[rs,ei]),ro=(0,s.useRef)(null),rc=(0,s.useCallback)(e=>{let t=ro.current;t&&(t.textContent=rl(e))},[rl]),rd=(0,s.useCallback)(e=>(function(e,t){if(!t)return e;for(let n of yx){let r=yv(n,t);if(10>=Math.abs(e-r))return r}return e})(e,rs),[rs]),ru=yw({ariaLabel:ei("layout.resizeInspector"),cssVariable:"--w-inspector",defaultWidth:372,followDefault:!0,formatValueText:rl,getDefaultWidth:rt,getMaxWidth:rr,growthDirection:"left",maxWidth:1200,minWidth:320,onLiveWidth:rc,snapWidth:rd,storageKey:"omp-web:inspector-width",widthRef:n9}),rh=ru.panelRef,rp=(0,s.useCallback)(e=>{nh.current=e,rh.current=e},[rh]),[rm,rf]=(0,s.useState)(!1),rg=(0,s.useRef)(!1),rx=ru.isResizing||rm,rv=(0,s.useRef)(null),[ry,rb]=(0,s.useState)(!1);(0,s.useEffect)(()=>{let e=rv.current;if(!e)return;let t=new ResizeObserver(e=>{let t=e[0]?.contentRect.width;"number"==typeof t&&rb(t<880)});return t.observe(e),()=>t.disconnect()},[]),(0,s.useEffect)(()=>{let e=nX.current;if(e===eg)return;nG(!0),null!==e&&(e?nZ.current=nY.current:nQ.current=nY.current),nX.current=eg;let t=eg?nZ.current:nQ.current;eg?n1(t):nq(t);let n=0,r=requestAnimationFrame(()=>{n=requestAnimationFrame(()=>nG(!1))});return()=>{cancelAnimationFrame(r),n&&cancelAnimationFrame(n)}},[eg,n1]),(0,s.useEffect)(()=>{nK(!0)},[]),(0,s.useEffect)(()=>{let e=n8.current;if(n8.current=n0.drawer,n0.drawer){let e=n3.panelRef.current;if(!e||e.contains(document.activeElement))return;let t=requestAnimationFrame(()=>{e.querySelector(jr)?.focus()});return()=>cancelAnimationFrame(t)}if(!e)return;let t=0,n=requestAnimationFrame(()=>{t=requestAnimationFrame(()=>{let e=document.activeElement;e&&e!==document.body||n2.current?.focus()})});return()=>{cancelAnimationFrame(n),t&&cancelAnimationFrame(t)}},[n0.drawer,n3.panelRef]),(0,s.useEffect)(()=>{n7()},[n7,tQ.activeView]),(0,s.useEffect)(()=>{let e=nh.current;if(!e)return;let t=e=>{t3(t=>{let n=g(e);return t.navigator===n.navigator&&t.deck===n.deck?t:n}),t9(e>=1440)};t(e.getBoundingClientRect().width);let n=new ResizeObserver(e=>{let n=e[0]?.contentRect.width;"number"==typeof n&&t(n)});return n.observe(e),()=>n.disconnect()},[]),(0,s.useEffect)(()=>{if(!nd)return;let e=0,t=requestAnimationFrame(()=>{e=requestAnimationFrame(()=>np.current?.())});return()=>{cancelAnimationFrame(t),e&&cancelAnimationFrame(e)}},[nd]),(0,s.useEffect)(()=>{if("command-palette"!==tQ.transientLayer)return;let e=nm.current;if(!e)return;let t=requestAnimationFrame(()=>{e.querySelector(jr)?.focus()});return()=>cancelAnimationFrame(t)},[tQ.transientLayer]),(0,s.useEffect)(()=>{eg||"navigator-drawer"!==tQ.transientLayer||tX({type:"close-layer"})},[eg,tQ.transientLayer]),(0,s.useEffect)(()=>{let e=new AbortController;return na(e=>({...e,complete:!1})),fetch("/api/sessions",{cache:"no-store",signal:e.signal}).then(async e=>{if(!e.ok)throw Error(`HTTP ${e.status}`);let t=await e.json();if(!Array.isArray(t.sessions))throw Error("Invalid session census");nr(t.sessions),na({sessions:t.sessions.map(e=>({id:e.id,modified:e.modified})),complete:!0})}).catch(e=>{e instanceof DOMException&&"AbortError"===e.name||console.error("Failed to load the complete session census:",e)}),()=>e.abort()},[e9,eD?.id]);let rk=(0,s.useRef)(null),rS=(0,s.useRef)(null),[rC,rN]=(0,s.useState)({sessionId:null,tree:[],leafId:null,navigation:0}),rT=(0,s.useRef)(null),rI=(0,s.useCallback)((e,t,n)=>{rT.current=n,rN(n=>{let r=rJ.current;return n.sessionId!==r?{sessionId:r,tree:e,leafId:t,navigation:0}:{...n,tree:e,leafId:t}})},[]),rM=(0,s.useCallback)(e=>{rN(t=>t.leafId===e?t:{...t,navigation:t.navigation+1}),rT.current?.(e)},[]),[rP,rA]=(0,s.useState)(null),r_=(0,s.useCallback)(e=>{rA(e)},[]),[rF,rO]=(0,s.useState)(null),[rz,rD]=(0,s.useState)([]),[rW,rH]=(0,s.useState)(null),[rU,rB]=(0,s.useState)(!1);(0,s.useEffect)(()=>{let e=new AbortController;return fetch("/api/settings",{cache:"no-store",signal:e.signal}).then(async t=>{if(!t.ok)return;let n=await t.json(),r=n.fields?.find(e=>"task.maxConcurrency"===e.path),s=r?.value??r?.defaultValue,a="number"==typeof s?s:"string"==typeof s?Number.parseInt(s,10):NaN;!e.signal.aborted&&Number.isFinite(a)&&a>0&&rH(a)}).catch(()=>{}),()=>e.abort()},[]);let[rq,rV]=(0,s.useState)({kind:"idle"}),rK=(0,s.useRef)(null),rJ=(0,s.useRef)(eD?.id??null);rJ.current=eD?.id??null;let rG=(0,s.useCallback)(e=>{rO(e)},[]),[rY,rZ]=(0,s.useState)(null),rQ=(0,s.useRef)(null),r2=(0,s.useCallback)((e,t)=>{nT(t).then(()=>{rQ.current&&clearTimeout(rQ.current),rZ(e),rQ.current=setTimeout(()=>rZ(null),1400)})},[]);(0,s.useEffect)(()=>()=>{rQ.current&&clearTimeout(rQ.current),rK.current&&clearTimeout(rK.current)},[]),(0,s.useEffect)(()=>()=>eK.current?.abort(),[]);let[r5,r6]=(0,s.useState)(null),r3=(0,s.useCallback)(e=>{r6(e)},[]),[r7,r9]=(0,s.useState)(null),[se,st]=(0,s.useState)(null),[sn,sr]=(0,s.useState)(null),ss=(0,s.useRef)(null),sa=(0,s.useRef)(null),si=(0,s.useCallback)(()=>{let e=sa.current;sa.current=null,st(null),e?.isConnected&&window.requestAnimationFrame(()=>e.focus())},[]),[so,sc]=(0,s.useState)(!1),[su,sp]=(0,s.useState)(!0);(0,s.useEffect)(()=>{try{sp("0"!==window.localStorage.getItem(ja))}catch{}},[]);let sm=(0,s.useCallback)(e=>{sp(e);try{window.localStorage.setItem(ja,e?"1":"0")}catch{}},[]),[sf,sg]=(0,s.useState)(!1),[sx,sv]=(0,s.useState)(null),sy="pinned"===t6.deck,[sb,sw]=(0,s.useState)("projects");(0,s.useEffect)(()=>{try{sw(function(e,t){return"gpt6"===e?"projects":"string"==typeof e&&w.includes(e)?e:"1"===t?"priority":"projects"}(window.localStorage.getItem(k),window.localStorage.getItem(j)))}catch{}},[]);let sk=(0,s.useCallback)(e=>{sw(e);try{window.localStorage.setItem(k,e),window.localStorage.setItem(j,"priority"===e?"1":"0")}catch{}},[]),[sj,sS]=(0,s.useState)({running:0,waiting:[]}),sC=(0,s.useCallback)((e,t=!1)=>{tX({type:"select-view",view:e}),st(null),"chat"===e&&sg(!1),(t||"chat"===e)&&nf(),eg&&n1(!1)},[eg,nf,n1]),sN=(0,s.useRef)(!1),sT=(0,s.useCallback)(()=>{sN.current=!0,tX({type:"set-deck-expanded",expanded:!tQ.deckExpanded})},[tQ.deckExpanded]);(0,s.useEffect)(()=>{if(!sN.current)return;sN.current=!1;let e=requestAnimationFrame(()=>{[...document.querySelectorAll("#workspace-auxiliary-panel [data-panel-expand]")].find(e=>e.getClientRects().length>0)?.focus()});return()=>cancelAnimationFrame(e)},[tQ.deckExpanded]);let[sI,sM]=(0,s.useState)(null),sE=(0,s.useCallback)((e,t=!0)=>{sM(e),t&&sC("subagents")},[sC]),s$=eD?.id??null;(0,s.useEffect)(()=>{sM(null)},[s$]);let[sR,sP]=(0,s.useState)(null),sA=(0,s.useCallback)(e=>{jc(e)||(tQ.deckExpanded&&"pinned"===t6.deck?tX({type:"set-deck-expanded",expanded:!1}):tX({type:"select-view",view:"chat"})),sP(e)},[t6.deck,tQ.deckExpanded]);(0,s.useEffect)(()=>{if(!sR)return;let e=requestAnimationFrame(()=>{jc(sR)?.focus(),sP(null)});return()=>cancelAnimationFrame(e)},[sR]);let s_=(0,s.useCallback)(e=>{let t=tQ.transientLayer===e;st(null),eg&&"navigator-drawer"===tQ.transientLayer&&n1(!1),tX({type:"toggle-layer",layer:e}),t&&nf()},[eg,nf,n1,tQ.transientLayer]),sO=(0,s.useCallback)(()=>{let e="chat"!==tQ.activeView;if(sy)return void(su||e?(e&&sC("chat",!0),sm(!1)):sm(!0));if(e||sf){sg(!1),sC("chat",!0);return}sg(!0)},[su,sy,sC,sm,sf,tQ.activeView]),sz=(0,s.useCallback)(()=>{"chat"!==tQ.activeView&&tX({type:"select-view",view:"chat"}),sy?sm(!0):sg(!0)},[sy,sm,tQ.activeView]),sD=(0,s.useCallback)(e=>{"turn"!==e?sC(e):(tX({type:"select-view",view:"chat"}),st(null),sy?sm(!0):sg(!0))},[sy,sC,sm]),sW=(0,s.useCallback)(()=>{sy&&sm(!1),sg(!1),tX({type:"select-view",view:"chat"})},[sy,sm]),sH=(0,s.useCallback)(e=>{e?.focus({preventScroll:!0})},[]),sU=(0,s.useCallback)(e=>{st(null),tX({type:"close-layer"}),eg&&n1(!1),tO.reset(),tA(e)},[eg,tO,n1]),sB=(0,s.useCallback)(()=>{tO.reset(),tA(null),nf()},[tO,nf]),sq=eN.refresh,sV=(0,s.useCallback)(()=>{null!==tP&&tO.check(sq,tP)},[sq,tO,tP]),sK=(0,s.useCallback)(()=>tq?(tJ||(tV(!1),nf()),!0):null!==tP?(sB(),!0):tR?(tL(!1),nf(),!0):so?(sc(!1),nf(),!0):se?(si(),!0):tQ.transientLayer?("navigator-drawer"===tQ.transientLayer&&n1(!1),tX({type:"close-layer"}),nf(),!0):tQ.deckExpanded&&"pinned"===t6.deck&&document.activeElement?.closest("#workspace-auxiliary-panel")?(sN.current=!0,tX({type:"set-deck-expanded",expanded:!1}),!0):"chat"!==tQ.activeView&&(tX({type:"select-view",view:"chat"}),nf(),!0),[sB,so,tP,se,si,tJ,tq,nf,n1,tR,tQ.activeView,tQ.transientLayer,tQ.deckExpanded,t6.deck]),sJ=(0,s.useCallback)(e=>{tX({type:"close-layer"}),eg&&n1(!1),sa.current=ju(),st(t=>t===e?null:e)},[eg,n1]),sG=(0,s.useCallback)(()=>{tX({type:"close-layer"}),eg&&n1(!1),sa.current=ju(),st("session")},[eg,n1]),sY=(0,s.useCallback)(()=>{if(st(null),eg){let e="navigator-drawer"!==tQ.transientLayer;n1(e),e||nf();return}tX({type:"close-layer"}),nq(e=>{let t=!e;return nQ.current=t,t})},[eg,nf,n1,tQ.transientLayer]);(0,s.useEffect)(()=>{if(!se||!rS.current)return;let e=()=>{let e=rS.current.getBoundingClientRect();sr({top:e.bottom,left:e.left,width:e.width})};e();let t=new ResizeObserver(e);t.observe(rS.current);let n=e=>{let t=e.target;!(t instanceof Element)||ss.current?.contains(t)||t.closest("[data-top-panel-opener], [role='menu']")||(sa.current=null,st(null))};return document.addEventListener("pointerdown",n,!0),()=>{t.disconnect(),document.removeEventListener("pointerdown",n,!0)}},[se]);let[sZ,sQ]=(0,s.useState)([]),[sX,s0]=(0,s.useState)(null),s1=(0,s.useRef)(new Map),s2=(0,s.useCallback)(()=>{"view-stack"===t6.deck&&tX({type:"select-view",view:"chat"}),eg&&n1(!1),nf()},[eg,t6.deck,nf,n1]),s4=(0,s.useCallback)((e,t)=>{rk.current?.insertText(uI(e,t)),s2()},[s2]),s8=(0,s.useCallback)((e,t,n)=>{rk.current?.insertText(uM(e,t,n)),s2()},[s2]),s5=(0,s.useCallback)((e,t)=>{let n=rk.current;return!!n&&(n.addAttachments(e),t&&n.insertText(t),s2(),!0)},[s2]),s6=(0,s.useCallback)(e=>{rk.current?.insertText(e),s2()},[s2]),s3=(0,s.useCallback)((e,t)=>{t5({sessionId:e,widgets:t})},[]),s7=ee.sessionId,[s9,ae]=(0,s.useState)(null);nN({cwd:eD?.cwd??e1??s9,syncWithOmp:!0}),I=(0,s.useSyncExternalStore)(fW,fO,()=>!1),(0,s.useEffect)(()=>r0(()=>fD(rX().mode)),[]),(0,s.useEffect)(()=>{if(!I)return;let e=!0;return r1().then(t=>{e&&t&&fD(rX().mode)}),()=>{e=!1}},[I]);let at=(0,s.useRef)(null),[an,ar]=(0,s.useState)(()=>!s7),as=(0,s.useRef)(!1),aa=(0,s.useRef)(0),ai=(0,s.useCallback)(()=>{aa.current+=1},[]);(0,s.useEffect)(()=>{eD&&function(e,t,n=je()){if(n)try{let r=jt(n);r[e]=t,n.setItem(k9,JSON.stringify(r))}catch{}}(eD.projectRoot??at.current??eD.cwd,eD.id)},[eD]),(0,s.useEffect)(()=>{let e=ee.requestedCwd;if(!e)return;let t=new AbortController;return e6("validating"),e7(null),fetch("/api/cwd/validate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:e}),signal:t.signal}).then(async e=>{let t=await e.json().catch(()=>({}));if(!e.ok||!t.cwd)throw Error(t.error??`HTTP ${e.status}`);as.current=!0,e2(t.cwd),e8(void 0),e6("ready")}).catch(e=>{t.signal.aborted||(e7(e instanceof Error?e.message:String(e)),e6("error"))}),()=>t.abort()},[ee]);let al=(0,s.useCallback)(e=>{let t=++aa.current,n=function(e,t=je()){if(!t)return null;try{let n=jt(t)[e];return"string"==typeof n&&n.length>0?n:null}catch{return null}}(e);n&&fetch("/api/sessions").then(e=>e.ok?e.json():null).then(r=>{if(t!==aa.current)return;let s=r?.sessions.find(e=>e.id===n);if(!s){r&&jn(e);return}(s.projectRoot??s.cwd)!==e?jn(e):(eW(s),tn(ji(tr)),new URLSearchParams(window.location.search).get("session")!==s.id&&Q.replace(`?session=${encodeURIComponent(s.id)}`,{scroll:!1}))}).catch(()=>{})},[Q]),ao=(0,s.useCallback)((e,t)=>{if(ai(),ae(e),!e)return;let n=t??e,r=at.current??(eD?eD.projectRoot??eD.cwd:null);if(at.current=n,as.current){as.current=!1;return}r!==n&&(eV.current+=1,eK.current?.abort(),eK.current=null,eU(null),eq(null),eW(null),ta(null),tf(!1),tx(!1),e8(void 0),e2(t=>t&&t!==e?null:t),tn(ji(tr)),rN({sessionId:null,tree:[],leafId:null,navigation:0}),rA(null),st(null),sQ([]),s0(null),tX({type:"select-view",view:"chat"}),al(n),Q.replace("/",{scroll:!1}))},["/",Q,eD,ai,al]),ac=(0,s.useCallback)(e=>{ts&&!(tT.current<0)&&(void 0===e||e===tT.current)&&(tT.current=-1,at.current=ts.projectRoot??ts.cwd,ai(),eV.current+=1,eK.current?.abort(),eK.current=null,eU(null),e2(null),e8(void 0),eq(null),eW(ts),rN({sessionId:ts.id,tree:[],leafId:null,navigation:0}),rA(null),tn(ti),eD?(ta(eD),tl(tt),tc(e=>!e)):ta(null),Q.replace(`?session=${encodeURIComponent(ts.id)}`,{scroll:!1}))},[ti,ts,ai,Q,eD,tt]),ad=(0,s.useCallback)(e=>{e.id===eD?.id||(tf(!1),e.id!==ts?.id&&(ts||tc(!0),ta(e),tl(ji(tr))))},[ts,eD?.id]),au=(0,s.useCallback)(()=>ta(null),[]),ah=(0,s.useCallback)(()=>{ac(),ta(null)},[ac]),ap=(0,s.useCallback)(()=>{ts||tc(!0),tf(!0),ty(!0),tw(null)},[ts]),am=(0,s.useCallback)(()=>{sm(!0),tX({type:"select-view",view:"browser"})},[sm]),af=(0,s.useCallback)(e=>{tN(t=>{if(!t.has(e))return t;let n=new Set(t);return n.delete(e),n})},[]),ag=(0,s.useCallback)(()=>{eD&&af(eD.id),sy?am():ap()},[af,sy,eD,am,ap]),ax=(0,s.useCallback)((e,t)=>{if(null===t){tS.current.delete(e),af(e);return}e!==eD?.id||tS.current.get(e)===t||(tS.current.set(e,t),tj.current||(sy&&!document.activeElement?.closest(".auxiliary-deck-panel")?am():tN(t=>new Set(t).add(e))))},[af,sy,eD?.id,am]),av=(0,s.useCallback)(()=>{tf(!1),tx(!1),ta(null)},[]),ay=(0,s.useCallback)(()=>{te(e=>e+1),tM(e=>e+1)},[]),ab=(0,s.useRef)(null),aw=(0,s.useCallback)(e=>{if(ab.current?.disconnect(),ab.current=null,!e)return;let t=new ResizeObserver(([e])=>{e&&tu(Math.floor(e.contentRect.width))});t.observe(e),ab.current=t},[]),ak=(0,s.useCallback)((e,t,n)=>{e2(null),e8(void 0),eq(n),eW(e),rN({sessionId:e.id,tree:[],leafId:null,navigation:0}),tn(ji(tr)),ta(t=>t?.id===e.id?null:t),rA(null),ar(!0),eg&&!t&&(n1(!1),tX({type:"select-view",view:"chat"})),t&&(as.current=!0),t||Q.replace(`?session=${encodeURIComponent(e.id)}`,{scroll:!1})},[eg,Q,n1]),aj=(0,s.useCallback)((e,t=!1)=>{if(at.current=e.projectRoot??e.cwd,ai(),!t&&ts?.id===e.id&&tk.current)return void ac();if(!t&&eD){let t=(eD.projectRoot??eD.cwd)===(e.projectRoot??e.cwd);if(eD.id===e.id&&t){eV.current+=1,eK.current?.abort(),eK.current=null,eU(null),eg&&n1(!1);return}}if(!t&&eH?.id===e.id)return;eV.current+=1;let n=eV.current;if(eK.current?.abort(),t||!eD){eK.current=null,eU(null),ak(e,t,null);return}let r=new AbortController;eK.current=r,eU(e);let s=new URLSearchParams({deferThinking:"1",deferMedia:"1"});fetch(`/api/sessions/${encodeURIComponent(e.id)}?${s}`,{cache:"no-store",signal:r.signal}).then(async t=>{if(!t.ok)throw Error(`HTTP ${t.status}`);let r=await t.json();if(r.sessionId!==e.id)throw Error("Session preload returned the wrong session");eV.current===n&&ak(e,!1,r)}).catch(t=>{r.signal.aborted||eV.current!==n||(console.error("Failed to preload session before switching:",t),ak(e,!1,null))}).finally(()=>{eV.current===n&&(eK.current=null,eU(null))})},[ts?.id,ak,ai,eg,eH?.id,ac,eD,n1]),aS=(0,s.useCallback)(e=>{ap(),e.id!==eD?.id&&(tw(e.id),aj(e))},[aj,eD?.id,ap]),aC=(0,s.useCallback)((e,t,n)=>{eV.current+=1,eK.current?.abort(),eK.current=null,eU(null),eq(null),ai(),eW(null),e2(t),e8(n),tn(ji(tr)),rN({sessionId:null,tree:[],leafId:null,navigation:0}),rA(null),st(null),tX({type:"select-view",view:"chat"}),eg&&n1(!1),Q.replace("/",{scroll:!1})},["/",ai,eg,Q,n1]),aN=(0,s.useCallback)((e,t)=>{if(eR(!1),!t){nT(e).then(()=>e_("CUELO 저장소를 찾지 못해 프롬프트를 복사했습니다. 사이드바에서 폴더를 고른 뒤 새 세션 입력창에 붙여 넣으세요."),()=>e_("CUELO 저장소를 찾지 못했고 프롬프트 복사도 실패했습니다. 보수 화면의 「복사」를 다시 눌러 보세요.")),eg&&n1(!0);return}let n=`new:${t}`,r=us(n);ua(n,{value:r?.value.trim()?`${r.value.trimEnd()}
77
77
 
78
78
  ${e}`:e,images:r?.images??[],documents:r?.documents??[]}),aC(`upkeep-${Date.now()}`,t,!0),nf(),e_("프롬프트를 새 세션 입력창에 넣었습니다. 내용을 확인한 뒤 보내세요.")},[aC,eg,nf,n1]),aT=(0,s.useCallback)(e=>{let t=eD?.projectRoot??at.current??eD?.cwd??s9;if(!t||!eD)return;let n=nn.filter(e=>(e.projectRoot??e.cwd)===t),r=n.findIndex(e=>e.id===eD.id);if(r<0)return;let s=n[r+e];s&&(st(null),tX({type:"close-layer"}),aj(s),nf())},[s9,nn,aj,nf,eD]);p={onNewSession:e=>aC(`kb-${Date.now()}`,e),onToggleCommandPalette:()=>s_("command-palette"),onToggleNavigator:sY,onToggleResources:()=>sC("resource"===tQ.activeView?"chat":"resource",!0),onSelectView:e=>sC(e,!0),onCycleView:(0,s.useCallback)(e=>{let t=(d.indexOf(tQ.activeView)+e+d.length)%d.length;sC(d[t],!0)},[sC,tQ.activeView]),onNavigateSession:aT,onEscape:sK,enabled:!tR&&!tq&&null===tP,activeCwd:s9},(M=(0,s.useRef)(p)).current=p,(0,s.useEffect)(()=>{let e=e=>{!function(e,t){if(e.defaultPrevented)return;let n=t.now?.()??Date.now();if(v||e.isComposing||229===e.keyCode||n-y<100)return;let r=e.target,s="u">typeof Element&&r instanceof Element?r:null,a=!!s?.closest("input, textarea, select, [contenteditable='true']");if("Escape"===e.key)return!s?.closest("[data-dismissible-layer], [data-capture-keys], [role='listbox'], [role='menu'], [role='combobox'][aria-expanded='true'], [aria-haspopup][aria-expanded='true']")&&(t.onEscape?.()?(e.preventDefault(),e.stopPropagation()):!(a||s?.closest("[role='dialog']"))&&x&&(e.preventDefault(),x()));if(s?.closest("[data-capture-keys]")||!1===t.enabled)return;let i=e.key.toLowerCase(),l=(e.ctrlKey||e.metaKey)&&!e.altKey;if(l&&!e.shiftKey&&"k"===i)return t.onToggleCommandPalette&&(e.preventDefault(),t.onToggleCommandPalette());if(l&&!e.shiftKey&&"b"===i)return t.onToggleNavigator&&(e.preventDefault(),t.onToggleNavigator());if(l&&!e.shiftKey&&"u"===i)return t.onToggleResources&&(e.preventDefault(),t.onToggleResources());if(l&&!e.shiftKey&&/^[1-7]$/.test(i)){if(!t.onSelectView)return;let n=d[Number(i)-1];return n&&(e.preventDefault(),t.onSelectView(n))}l&&e.shiftKey&&("Period"===e.code||"Comma"===e.code)?t.onCycleView&&(e.preventDefault(),t.onCycleView("Period"===e.code?1:-1)):!e.altKey||e.ctrlKey||e.metaKey||"ArrowUp"!==e.key&&"ArrowDown"!==e.key?e.ctrlKey&&e.altKey&&!e.metaKey&&"n"===i&&t.activeCwd&&t.onNewSession&&(e.preventDefault(),t.onNewSession(t.activeCwd)):t.onNavigateSession&&(e.preventDefault(),t.onNavigateSession("ArrowUp"===e.key?-1:1))}(e,M.current)},t=()=>b(!0),n=()=>b(!1);return window.addEventListener("compositionstart",t,{capture:!0}),window.addEventListener("compositionend",n,{capture:!0}),window.addEventListener("keydown",e,{capture:!0}),()=>{window.removeEventListener("keydown",e,{capture:!0}),window.removeEventListener("compositionstart",t,{capture:!0}),window.removeEventListener("compositionend",n,{capture:!0})}},[]);let aI=(0,s.useCallback)(e=>{fetch("/api/sessions",{cache:"no-store"}).then(e=>e.ok?e.json():null).then(t=>{let n=t?.sessions.find(t=>t.id===e);n&&eW(t=>t?.id===e?{...t,...n,transient:n.transient??!1}:t)}).catch(()=>{})},[]),aM=(0,s.useCallback)(e=>{ai(),e2(null),e8(void 0),eW(e),te(e=>e+1),aI(e.id),Q.replace(`?session=${encodeURIComponent(e.id)}`,{scroll:!1})},[ai,Q,aI]),aE=(0,s.useCallback)(({targetSession:e,title:t,body:n,tag:r})=>{"Notification"in window&&"granted"===Notification.permission&&hf({title:t,body:n,sessionUrl:e?`/?session=${encodeURIComponent(e.id)}`:"/",tag:r,onClick:()=>{window.focus(),e&&aj(e)}})},[aj]),a$=(0,s.useCallback)(e=>{te(e=>e+1),tU.current?.pending&&tH(e=>e+1),tM(e=>e+1),eD&&aI(eD.id),"completed"===e.outcome&&hp()&&aE({targetSession:eD,title:eD?.name??ei("i18n.sessionComplete"),body:ei("i18n.taskFinished")})},[aE,aI,eD,ei]),aR=(0,s.useCallback)(e=>{var t;hp()&&(t=eO.current,!(!hm(e)||t.has(e.id))&&(t.add(e.id),1)&&aE({targetSession:eD,title:ei("i18n.attentionNeeded"),body:"custom"===e.method?ei("i18n.extensionInputNeeded"):"ask"===e.method?e.questions[0]?.question||ei("i18n.extensionInputNeeded"):"form"===e.method?function(e){for(let t of e.sections){let n=df(t.title),r="";for(let s of t.blocks){if("field"===s.kind){let t=e.fields[s.index],a=df(t.label),i="choice"===t.kind&&1===t.options.length?df(t.options[0].label):"";return(a||r||n||i||t.name).replace(/\s+/g," ").trim()}r="text"===s.kind?df(s.spans):""}}return""}(e.form)||ei("i18n.extensionInputNeeded"):e.title,tag:`pi-extension-ui:${e.id}`}))},[aE,eD,ei]),aL=(0,s.useCallback)(async()=>{let e=eD?.id;if(e&&"naming"!==rq.kind){rK.current&&clearTimeout(rK.current),st(null),rV({kind:"naming"});try{let t=await fetch(`/api/sessions/${encodeURIComponent(e)}/auto-name`,{method:"POST"}),n=await t.json().catch(()=>({}));if(!t.ok||!n.title)throw Error(n.error||`HTTP ${t.status}`);let r=n.title.trim();if(te(e=>e+1),rJ.current!==e)return;eW(t=>t?.id===e?{...t,name:r}:t),rO(t=>t?.sessionId===e?{...t,sessionName:r}:t),rV({kind:"success"}),rK.current=setTimeout(()=>rV({kind:"idle"}),1800)}catch(t){if(rJ.current!==e)return;rV({kind:"error",message:t instanceof Error?t.message:String(t)}),rK.current=setTimeout(()=>rV({kind:"idle"}),5e3)}}},[rq.kind,eD?.id]);(0,s.useEffect)(()=>{rK.current&&clearTimeout(rK.current),rV({kind:"idle"})},[eD?.id]);let aP=(0,s.useCallback)(e=>{ai(),te(e=>e+1),tn(ji(tr)),e2(null),e8(void 0),eW(t=>({...t??{path:"",cwd:"",created:"",modified:"",messageCount:0,firstMessage:""},id:e,transient:!1})),aI(e),Q.replace(`?session=${encodeURIComponent(e)}`,{scroll:!1})},[ai,Q,aI]),aA=(0,s.useCallback)(()=>{ar(!0)},[]),a_=(0,s.useCallback)(e=>{if(ai(),te(e=>e+1),ta(t=>t?.id===e?null:t),eD?.id===e){let e=eD.cwd;eW(null),e2(e??null),e8(void 0),tn(ji(tr)),rN({sessionId:null,tree:[],leafId:null,navigation:0}),rA(null),st(null),tX({type:"select-view",view:"chat"}),nf(),Q.replace("/",{scroll:!1})}},["/",ai,nf,eD,Q]),aF=(0,s.useCallback)((e,t,n)=>{let r=n?.sourceSessionId,s=n?.modeHint,a=`file:${e}`;s&&s1.current.delete(a),sQ(n=>{let i=n.find(e=>e.id===a);if(!i)return[...n,{id:a,label:t,filePath:e,sourceSessionId:r,initialDisplayMode:s}];let l=!r||i.sourceSessionId===r,o=!s||i.initialDisplayMode===s;return l&&o?n:n.map(e=>{if(e.id!==a)return e;let t={...e};return r&&(t.sourceSessionId=r),s&&(t.initialDisplayMode=s),t})}),s0(a),tX({type:"select-view",view:"files"}),st(null),eg&&n1(!1)},[eg,n1]),aO=(0,s.useCallback)(e=>{aF(e,tK(e),{sourceSessionId:eD?.id??null})},[aF,eD?.id]),az=(0,s.useCallback)(e=>{s1.current.delete(e);let t=sZ.filter(t=>t.id!==e);sQ(t),s0(n=>n!==e?n:t.length>0?t[t.length-1].id:null),0===t.length&&"files"===tQ.activeView&&sC("chat",!0)},[sZ,sC,tQ.activeView]),aD=(0,s.useCallback)(()=>{eD&&window.open(`/api/sessions/${encodeURIComponent(eD.id)}/export?inline=1`,"_blank","noopener,noreferrer")},[eD]),aW=e1??(null===eD&&s9?s9:null),aH=null!==eD||null!==aW,aU=eD?.cwd??aW,aB=(0,s.useMemo)(()=>{let e=new Set,t=[];for(let n of[...nn].sort((e,t)=>t.modified.localeCompare(e.modified))){let r=n.projectRoot??n.cwd;!r||e.has(r)||(e.add(r),t.push({path:r,name:tK(r)||r}))}return aW&&!e.has(aW)&&t.unshift({path:aW,name:tK(aW)||aW}),t},[aW,nn]),aq=(0,s.useCallback)(e=>{aC(`start-${Date.now()}`,e)},[aC]),aV=t7&&null===eD&&aW?(0,r.jsx)(hd,{cwd:aW,projects:aB,onChoose:aq}):void 0,aK=sy?su||"chat"!==tQ.activeView:"chat"!==tQ.activeView||sf,aJ=ev&&aK,aG="chat"===tQ.activeView?"turn":tQ.activeView,aY=eD?.cwd??aW,aZ=an&&!aH,aQ=(0,s.useCallback)((e,t)=>{tU.current=e,tD(e),tZ(e.error?ei("trust.applyFailed",{error:e.error}):null),null!==t&&null===e.pending&&(t.trusted!==e.trusted||"revoke"===t.pending)&&(e.trusted&&tV(!1),t$(e=>e+1),tn(ji(tr)))},[ei]);(0,s.useEffect)(()=>{let e=tB.current!==aY;if(tB.current=aY,e&&(tU.current=null,tD(null),tV(!1),tZ(null)),!aY)return;let t=tU.current,n=new AbortController;return fetch(`/api/project-trust?cwd=${encodeURIComponent(aY)}`,{signal:n.signal}).then(async e=>{let n=await e.json();if(!e.ok)throw Error(n.error??`HTTP ${e.status}`);aQ(n,t)}).catch(e=>{e instanceof DOMException&&"AbortError"===e.name||console.error("Failed to load project trust:",e)}),()=>n.abort()},[aQ,aY,tW]);let aX=(0,s.useCallback)(async e=>{if(aY&&!tJ){tG(!0),tZ(null);try{let t=await fetch("/api/project-trust",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cwd:aY,action:e})}),n=await t.json();if(!t.ok)throw Error(n.error??`HTTP ${t.status}`);let r=tU.current;aQ(n,r),(n.trusted||"cancel"===e)&&(tV(!1),nf())}catch(e){tZ(e instanceof Error?e.message:String(e))}finally{tG(!1)}}},[aQ,tJ,aY,nf]),a0=sZ.find(e=>e.id===sX)??null,a1=s9?tK(s9)||s9:null,a2=eD?.cwd??aW,a4=a2?tK(a2)||a2:null,a8=eD?.name?.trim()||eD?.firstMessage?.trim()||(aW?ei("i18n.newSession"):a1)||"CUELO",a5=a8.replace(/\s+/g," ").trim(),a6=a5.length>96?`${a5.slice(0,93)}…`:a5,a3=a1?`${a6} — ${a1} — CUELO`:`${a6} — CUELO`,a7=a1?`${a5} — ${a1}`:a5,a9=eD?.transient?`${a7} \xb7 ${ei("session.inMemory")}`:a7,ie=rz.filter(e=>"pending"===e.status||"running"===e.status).length,it=rU?ei("workspace.mainAttention"):no?ei("workspace.mainWaiting"):ni?ei("workspace.mainWorking"):ei("workspace.mainIdle"),ir=`${rU?"⚠":no?"○":ni?"●":"○"} Main ${it} \xb7 Sub ${ie}${rW?`/${rW}`:""}`,is=(0,s.useCallback)(e=>sC(e,!0),[sC]),[ia,ii]=(0,s.useState)(null);ia&&"process"!==tQ.activeView&&ii(null);let il=(0,s.useRef)(0),io=(0,s.useCallback)(e=>{ii({toolCallId:e,nonce:++il.current}),sC("process"),sy&&sm(!0)},[sy,sC,sm]),ic=($=(E=(m={deckVisible:aK,pinDecision:t6,deckExpanded:tQ.deckExpanded}).deckVisible&&"pinned"===m.pinDecision.deck)&&m.deckExpanded,{replacesTranscript:m.deckVisible&&("view-stack"===m.pinDecision.deck||$),expandable:E,expanded:$,staleExpansion:m.deckExpanded&&!E}),id=ic.replacesTranscript&&!aJ,iu=ic.expandable?{expanded:ic.expanded,onToggle:sT}:null,ih=rs?yf(yv(120,rs),320,ru.separatorProps["aria-valuemax"]):null,ip=aK?ic.expanded?"files"===tQ.activeView?"preview":null:"process"===tQ.activeView&&null!==ih&&1>=Math.abs(ru.width-ih)?"log":null:"chat",im=ru.setPanelWidth,ig=(0,s.useRef)(0),ix=(0,s.useCallback)(e=>{let t=++ig.current;if("chat"===e){sC("chat"),sm(!1);return}sm(!0),sC("log"===e?"process":"files"),tX({type:"set-deck-expanded",expanded:"preview"===e}),"log"===e&&document.fonts.ready.then(()=>{requestAnimationFrame(()=>{if(t!==ig.current)return;let e=ri();e&&im(yv(120,e),{forcePersist:!0})})})},[ri,sC,sm,im]),iv=ic.staleExpansion;(0,s.useEffect)(()=>{iv&&tX({type:"set-deck-expanded",expanded:!1})},[iv]),(0,s.useEffect)(()=>{let e=()=>{document.title!==a3&&(document.title=a3)};e();let t=new MutationObserver(e);return t.observe(document.head,{childList:!0,subtree:!0,characterData:!0}),()=>t.disconnect()},[a3]);let iy="ko"===es?{chat:"대화",process:"작업 과정",efficiency:"효율",subagents:"서브에이전트",files:"파일",resource:"캐릭터",sidechat:"사이드챗",plugins:"플러그인",memory:"기억 추적",browser:"브라우저"}:{chat:"Chat",process:"Process",efficiency:"Efficiency",subagents:"Subagents",files:"Files",resource:"캐릭터",sidechat:"Side Chat",plugins:"Plugins",memory:"Memory trace",browser:"Browser"},ib={...iy,turn:ei("inspector.turn")},iw=aK&&!ic.expanded,ik=(R=r5&&Number.isFinite(r5.contextWindow)&&r5.contextWindow>0?r5.contextWindow:null,L=r5&&"number"==typeof r5.tokens&&Number.isFinite(r5.tokens)?Math.max(0,r5.tokens):null,A=null===(P=r5&&"number"==typeof r5.percent&&Number.isFinite(r5.percent)?r5.percent:null!==L&&null!==R?L/R*100:null)?"normal":P>90?"critical":P>70?"warning":"normal",_=null===L?"?":ym(L),O=null===R?"?":ym(R),z=null===P?"?":`${P.toFixed(0)}%`,{level:A,percent:P,fillPercent:null===P?0:Math.min(100,Math.max(0,P)),readout:null===R?null:`${z} \xb7 ${_}/${O}`,usedLabel:_,limitLabel:O,percentLabel:z}),ij=ik.readout,iS=ij?ei("chat.contextUsageTitle",{used:ik.usedLabel,limit:ik.limitLabel,percent:ik.percentLabel}):null,iC="critical"===ik.level?ei("chat.contextUsageCritical"):"warning"===ik.level?ei("chat.contextUsageWarning"):null,iN=(S=rF?.userMessages,!eD||eD.transient?"unsaved":("number"==typeof S?S:0)>0||eD.messageCount>0?null:"no-messages"),iT="unsaved"===iN?ei("title.unsaved"):"no-messages"===iN?ei("title.noMessages"):null,iI=iT??("error"===rq.kind?rq.message:null),iM="naming"===rq.kind?ei("title.generating"):"success"===rq.kind?ei("title.updated"):"error"===rq.kind?ei("title.failed"):ei("title.generate"),iE=(0,r.jsxs)("div",{id:"workspace-file-view",className:"workspace-file-view",children:[(0,r.jsx)("div",{className:"workspace-file-tabs",children:(0,r.jsx)(p8,{tabs:sZ,activeTabId:sX??"",onSelectTab:s0,onCloseTab:az})}),(0,r.jsx)("div",{className:"workspace-file-content",children:a0?.filePath?(0,r.jsx)(p2,{filePath:a0.filePath,cwd:s9??void 0,sourceSessionId:a0.sourceSessionId,gitRefreshKey:tI,initialDisplayMode:a0.initialDisplayMode,viewStateStore:s1.current,viewStateKey:a0.id,onMentionLines:s8,onAtMention:s4,onInsertText:s6,onOpenFile:e=>aF(e,tK(e),{sourceSessionId:a0.sourceSessionId})},a0.id):(0,r.jsxs)("div",{className:"workspace-file-empty","data-overview":t7&&aU?"true":void 0,children:[t7&&aU&&(0,r.jsx)(yl,{cwd:aU,onOpenFile:aO}),(0,r.jsx)(v9,{cwd:eD?.cwd??s9,onOpenFile:aO})]})})]}),i$=(0,r.jsx)(xI,{open:"resource"===tQ.activeView,sessionId:eD?.id??null,activeTab:t0,onTabChange:t1,usage:eN}),iR=(0,r.jsx)(vj,{open:"efficiency"===tQ.activeView,sessionId:eD?.id??null,activeTab:t2,onTabChange:t4}),iL=(0,r.jsx)(vL,{title:iy.plugins,visible:"plugins"===tQ.activeView,sessionId:eD?.id??null,labWidgets:t8,onInsertDraft:aH?s6:void 0}),iP=(0,r.jsx)(vX,{title:iy.memory,visible:"memory"===tQ.activeView,sessionId:eD?.id??null}),iA=(0,r.jsx)(gE,{title:iy.process,data:r7,onOpenFile:aO,focusRequest:ia}),i_=eD?eD.path?eD.path:rF?.sessionId===eD.id&&rF.sessionFile?rF.sessionFile:null:null,iF=(0,r.jsx)(gJ,{title:iy.sidechat,sessionId:eD?.id??null,sessionPath:i_,sessionName:eD?.name,historyStore:ne,flights:nt,sessionCensus:ns,visible:"sidechat"===tQ.activeView}),iO=aH?(0,r.jsx)("div",{ref:sv,className:"turn-inspector-slot"}):(0,r.jsx)("p",{className:"inspector-empty",children:ei("inspector.noTurn")}),iz=aK&&"browser"===aG,iD=iz?eD?(0,r.jsx)(gb,{sessionId:eD.id,sessionTitle:a8,chrome:null},`inspector-browser-${eD.id}`):(0,r.jsx)("p",{className:"inspector-empty",children:ei("browserPane.noneTitle")}):null,iW=aK?(0,r.jsx)(gu,{activeView:aG,onViewChange:sD,viewLabels:ib,turnSlot:iO,sessionId:eD?.id??null,sessionPath:i_,sessionName:eD?.name,sessionCwd:eD?.cwd??aW??void 0,liveSubagents:rz,processSlot:iA,fileSlot:iE,browserSlot:iD,sideChatSlot:iF,resourceSlot:t??i$,efficiencySlot:iR,pluginsSlot:iL,memorySlot:iP,visible:!0,onClose:sW,closeLabel:sy?ei("inspector.hide"):ei("inspector.backToChat"),onReturnFocus:nf,expand:iu,widthReadout:sy&&rx&&!ic.expanded?(0,r.jsx)("span",{ref:ro,className:"inspector-width-readout","aria-hidden":"true",children:rl(ru.width)}):null,selectedMaker:sI,onSelectMaker:sM,onReturnToDispatch:sA,onOpenFile:aO,fileOpen:!!a0?.filePath}):null,iH=e??iW,iU=!eg&&!ev&&aH&&!id,iB=td>=1048,iq=null!==tb&&eD?.id!==tb&&null!==eH,iV=tm&&!iq&&aH&&!id&&null!==eD,iK=iV&&iU&&iB&&!tg,iJ=iV&&!iK&&tv,iG=iU&&iB&&null!==ts&&!iV&&!(tm&&iq),iY=iG||iK;tk.current=iG,tj.current=iK||iJ;let iZ=iB?null:ei(aK&&sy?"sidebar.openBesideNarrowDeck":"sidebar.openBesideNarrow"),iQ=(0,s.useMemo)(()=>iU?{besideSessionId:iG?ts?.id??null:null,blockedReason:iZ,openBeside:ad}:null,[iZ,iG,ts?.id,ad,iU]),iX=(e,t,n)=>(0,r.jsxs)("div",{className:"chat-pane-head",children:[(0,r.jsx)("span",{className:"chat-pane-title",title:e,children:e}),n,t&&(0,r.jsx)("button",{type:"button",className:"chat-pane-close",onClick:t,"aria-label":ei("workspace.closePane"),title:ei("workspace.closePane"),children:(0,r.jsx)(ep,{name:"x",size:14})})]}),i0=(0,r.jsx)("button",{type:"button",className:"browser-pane-button",onClick:ap,children:ei("workspace.toBrowser")}),i1=ts?nn.find(e=>e.id===ts.id)??ts:null,i2=i1?.name?.trim()||i1?.firstMessage?.trim()||i1?.id.slice(0,12)||"",i4=e=>{e.target instanceof Element&&e.target.closest(".chat-pane-head")||ac(ti)},i8=iG&&ts?(0,r.jsxs)("div",{className:"chat-pane is-idle",onPointerDownCapture:i4,onFocusCapture:i4,children:[iX(i2,au,eD?i0:void 0),(0,r.jsx)(pl,{session:ts,newSessionCwd:null,modelsRefreshKey:tE,onAgentEnd:ay,onOpenFile:aO,soundEnabled:ey,onSoundToggle:eb,playCueSound:ew,preloadCueSound:ek,unlockAudio:ej,turnInspectorFolded:ev,shellConnected:!1})]},`pane-${ti}`):null,i5=iV&&eD&&(iK||tv)?(0,r.jsx)(gb,{sessionId:eD.id,sessionTitle:a8,chrome:{canSplit:iU&&iB,enlarged:tg&&iU&&iB,onToggleEnlarge:()=>tx(e=>!e),onShowChat:iK?ts?()=>tf(!1):null:()=>ty(!1),onClose:av,onUse:()=>ty(!0),narrowNote:iU&&!iB?ei("workspace.foldedNarrow"):null}},`pane-browser-${eD.id}`):null,i6=(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(ed.Provider,{value:aS,children:(0,r.jsx)(eo.Provider,{value:iQ,children:(0,r.jsx)(eC,{selectedSessionId:eH?.id??eD?.id??null,optimisticSession:eH??eD,onSelectSession:aj,onNewSession:aC,initialSessionId:s7,skipInitialProjectSelection:null!==ee.requestedCwd,onInitialRestoreDone:aA,refreshKey:e9,onSessionDeleted:a_,selectedCwd:eD?.cwd??e1??null,onCwdChange:ao,onBackgroundTaskDone:ez,translatorPanel:(0,r.jsx)(wV,{onOpen:eg?()=>n1(!1):void 0}),translatorActive:eT,navigatorMode:sb,onActivityChange:sS})})}),(0,r.jsxs)("div",{className:"navigator-footer",children:[(0,r.jsx)(yM,{usage:eN,onOpen:()=>{t1("usage"),sC("resource",!1)},onRelogin:sU}),(0,r.jsx)(wY,{}),(0,r.jsx)(w0,{})]})]}),i3=e=>{sk(e),eT&&ng(!1),eg||nB||sY()},i7=(e,t,n,s,a,i)=>(0,r.jsxs)("button",{type:"button",className:"workspace-rail-item","aria-current":s?"page":void 0,title:n,onClick:a,children:[(0,r.jsx)(ep,{name:t}),(0,r.jsx)("span",{className:"workspace-rail-label",children:n}),i]},e),i9=(0,r.jsxs)("nav",{className:"workspace-rail","aria-label":ei("workbench.places"),children:[(0,r.jsx)("span",{className:"workspace-rail-logo",title:"CUELO",children:(0,r.jsx)(em,{size:30})}),i7("projects","folder",ei("sidebar.projects"),!eT&&"projects"===sb,()=>i3("projects")),i7("priority","list-ordered",ei("navigator.priority"),!eT&&"priority"===sb,()=>i3("priority"),sj.waiting.length>0?(0,r.jsx)("span",{className:"workspace-rail-badge","aria-label":ei("workbench.needsInputCount",{count:sj.waiting.length}),children:sj.waiting.length}):void 0),i7("translator","languages",eh,eT,()=>ng(!eT)),(0,r.jsx)("span",{className:"workspace-rail-spacer"}),i7("upkeep","activity","보수",e$,()=>{eg&&n1(!1),nx(!0)}),i7("settings","settings",ei("common.settings"),tR,()=>{st(null),tX({type:"close-layer"}),eg&&n1(!1),tL(!0)})]}),le=nR&&nP&&nP.requestId===nR.requestId&&nP.deploymentCompleted?nP:null,lt=le?.cleanup??null,ln=le&&!nR?.dismissed?function(e){if(!e)return{tone:"neutral",title:"업데이트 완료",detail:"임시 산출물 정리 상태를 확인하고 있습니다.",dismissible:!0,autoHideMs:hS(null)};let t=`${e.completedCount}/${e.totalCount} 완료`,n=`${Math.round(e.elapsedSeconds)}초 경과`;return"running"===e.status?{tone:"neutral",title:"업데이트 완료 \xb7 산출물 정리 중",detail:`${t} \xb7 ${n} \xb7 현재 ${e.currentTarget??"대상 선택 중"}`,dismissible:!1,autoHideMs:null}:"failed"===e.status?{tone:"warning",title:"업데이트 완료 \xb7 산출물 정리 실패",detail:`${t} \xb7 ${n} \xb7 보존 ${e.keptCount}건 \xb7 실패 ${e.failureCount}건. 업데이트 자체는 성공했고 실패 증거는 보존했습니다.`,dismissible:!0,autoHideMs:hS(e.status)}:"pending-approval"===e.status?{tone:"neutral",title:"업데이트 완료 \xb7 산출물 정리 승인 대기",detail:`${t} \xb7 ${n} \xb7 보존 ${e.keptCount}건. 삭제는 승인 후 실행합니다.`,dismissible:!0,autoHideMs:hS(e.status)}:"skipped"===e.status?{tone:"neutral",title:"업데이트 완료 \xb7 산출물 정리 건너뜀",detail:`${t} \xb7 ${n}`,dismissible:!0,autoHideMs:hS(e.status)}:{tone:"positive",title:"업데이트 완료 \xb7 산출물 정리 완료",detail:`${t} \xb7 ${n}`,dismissible:!0,autoHideMs:hS(e.status)}}(lt):null;return(0,r.jsxs)(n4.Provider,{value:s5,children:[nb?(0,r.jsx)("div",{className:"server-restart-overlay",role:"status","aria-live":"polite",children:(0,r.jsxs)("div",{className:"server-restart-card",children:[(0,r.jsx)("div",{className:"server-restart-spinner","aria-hidden":"true"}),(0,r.jsx)("strong",{children:ei("restart.title")}),(0,r.jsx)("span",{children:ei(nC?"restart.slow":"restart.body")})]})}):null,(0,r.jsxs)("div",{ref:rp,className:"workspace-shell","data-active-view":tQ.activeView,"data-deck-mode":t6.deck,"data-deck-visible":aK,"data-chat-wide":eQ?"true":"false",style:{"--w-inspector":`${ru.width}px`},children:[!eg&&i9,(0,r.jsx)("div",{"aria-hidden":"true",className:`sidebar-overlay-backdrop${n0.drawer?" is-open":""}${nV?"":" sidebar-mobile-pending"}${nJ?" sidebar-mode-shift":""}`,onClick:()=>{n1(!1),nf()}}),(0,r.jsxs)("div",{ref:n3.panelRef,id:"session-sidebar",className:`sidebar-container${n0.laidOut?" sidebar-open":" sidebar-closed"}${nV?"":" sidebar-mobile-pending"}${nJ?" sidebar-mode-shift":""}${n3.isResizing?" sidebar-resizing":""}`,"aria-hidden":eg&&!n0.presented,inert:eg&&!n0.presented,style:{"--sidebar-width":`${n3.width}px`},children:[eg&&i9,(0,r.jsx)("div",{className:"sidebar-list",children:i6})]}),n0.laidOut&&(0,r.jsx)("div",{...n3.separatorProps,"aria-controls":"session-sidebar",className:`panel-resize-handle sidebar-resize-handle${n3.isResizing?" is-resizing":""}`,"data-resize-handle":"sidebar",title:`${ei("layout.resizeSidebar")}: ${ei("layout.resizeHint")}`}),(0,r.jsxs)("div",{className:"workspace-session-region","data-active-view":tQ.activeView,"aria-hidden":n0.drawer,inert:n0.drawer,children:[(0,r.jsxs)("div",{ref:rS,className:"workspace-header-stack","data-soft-keyboard":ex&&ev?"open":void 0,children:[ln&&nR&&(0,r.jsxs)("div",{className:"workspace-update-banner","data-tone":ln.tone,role:"status","aria-live":"polite",children:[(0,r.jsx)("span",{className:"workspace-update-banner-title",children:ln.title}),(0,r.jsx)("span",{className:"workspace-update-banner-detail",children:ln.detail}),ln.dismissible&&(0,r.jsx)("button",{type:"button",className:"workspace-update-banner-dismiss",onClick:()=>nL(hI(nR.requestId)),"aria-label":"업데이트 상태 알림 닫기",children:"닫기"})]}),nM&&!(ln&&nR)&&(0,r.jsxs)("div",{className:"workspace-update-banner","data-tone":"positive",role:"status","aria-live":"polite",children:[(0,r.jsx)("span",{className:"workspace-update-banner-title",children:ei("restart.returnedTitle")}),(0,r.jsx)("span",{className:"workspace-update-banner-detail",children:ei("restart.returnedBody")}),(0,r.jsx)("button",{type:"button",className:"workspace-update-banner-dismiss",onClick:()=>nE(!1),"aria-label":ei("restart.returnedDismiss"),children:ei("i18n.close")})]}),(0,r.jsx)(f4,{variant:"banner",locale:es,...ef}),(0,r.jsxs)("header",{ref:rv,className:"workspace-header-seam",children:[(0,r.jsx)(l.r,{ref:n2,className:"workspace-header-nav-toggle",variant:"ghost",size:"small",layout:"iconOnly",type:"button",onClick:sY,"aria-controls":"session-sidebar","aria-expanded":n0.presented,title:n0.presented?ei("sidebar.hide"):ei("sidebar.show"),"aria-label":n0.presented?ei("sidebar.hide"):ei("sidebar.show"),children:(0,r.jsx)(ep,{name:eg?"menu":"panel-left"})}),(0,r.jsxs)("div",{className:"workspace-session-identity",title:a9,children:[(0,r.jsxs)("div",{className:"workspace-session-where",children:[a4&&(0,r.jsx)("span",{className:"workspace-session-project",children:a4}),sj.running>0&&(0,r.jsxs)("span",{className:"workspace-session-running",children:[(0,r.jsx)("span",{className:"workbench-lamp","aria-hidden":"true"}),ei("workbench.runningCount",{count:sj.running})]})]}),(0,r.jsx)("strong",{className:"workspace-session-title",children:a6})]}),(0,r.jsx)("span",{className:"workspace-session-status","aria-live":"polite",children:ir}),(0,r.jsx)("span",{className:"sr-only",role:"status",children:"error"===rq.kind?rq.message:""}),aH&&tz?.requiresTrust&&!tz.trusted&&(0,r.jsxs)(l.r,{className:"workspace-header-action",variant:"ghost",size:"small",color:"fg.warning",type:"button",onClick:()=>{tZ(tz.error?ei("trust.applyFailed",{error:tz.error}):null),st(null),tX({type:"close-layer"}),tV(!0),tz.pending&&tH(e=>e+1)},title:ei("grant"===tz.pending?"trust.pendingBadge":"trust.resourcesNotLoaded"),"aria-label":ei("grant"===tz.pending?"trust.pendingBadge":"trust.resourcesNotLoaded"),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:"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10Z"}),(0,r.jsx)("path",{d:"M12 8v4"}),(0,r.jsx)("path",{d:"M12 16h.01"})]}),!eg&&(0,r.jsx)("span",{children:ei("trust.resourcesNotLoaded")})]}),aH&&s$&&(0,r.jsx)(pg,{sessionId:s$,refreshKey:String(ni),compact:eg}),aH&&ij&&(0,r.jsxs)(l.r,{className:"workspace-context-usage",variant:"ghost",size:"small",type:"button",onClick:()=>sJ("session"),"data-top-panel-opener":"","aria-expanded":"session"===se,title:iS??ei("session.title"),"aria-label":iC?`${iS}. ${iC}`:iS??void 0,children:[(0,r.jsx)("span",{className:"workspace-context-meter","aria-hidden":"true",children:(0,r.jsx)("span",{className:"workspace-context-meter-fill","data-level":ik.level,style:{inlineSize:`${ik.fillPercent}%`}})}),(0,r.jsx)("span",{className:"workspace-context-readout","data-level":ik.level,children:ij})]}),aH&&t7&&sy&&(0,r.jsx)("div",{className:"workspace-layout-presets",role:"group","aria-label":ei("layout.presets"),children:jl.map(e=>(0,r.jsx)("button",{type:"button",className:"workspace-layout-preset","aria-pressed":ip===e.id,title:ei(e.title),onClick:()=>ix(e.id),children:ei(e.label)},e.id))}),aH&&t7&&(0,r.jsxs)(l.r,{className:"workspace-wide-toggle",variant:"ghost",size:"small",layout:ry?"iconOnly":"withText",type:"button",onClick:e0,"aria-pressed":eQ,title:ei("layout.wideTitle"),"aria-label":ei("layout.wide"),children:[(0,r.jsx)(ep,{name:"maximize-2"}),!ry&&(0,r.jsx)("span",{className:"workspace-wide-toggle-label",children:ei("layout.wide")})]}),aH&&(0,r.jsx)(l.r,{className:"workspace-panel-toggle",variant:"ghost",size:"small",layout:"iconOnly",type:"button",onClick:sO,"aria-controls":"workspace-auxiliary-panel","aria-pressed":aK,title:aK?ei("inspector.hide"):ei("inspector.show"),"aria-label":aK?ei("inspector.hide"):ei("inspector.show"),children:(0,r.jsx)(ep,{name:"panel-right"})}),(0,r.jsxs)(o.k.Root,{open:so,onOpenChange:e=>sc(e),placement:"bottom-end",strategy:"fixed",children:[(0,r.jsx)(o.k.Trigger,{asChild:!0,children:(0,r.jsx)(l.r,{className:"workspace-header-more",variant:"ghost",size:"small",layout:"iconOnly",type:"button",title:"ko"===es?"더 보기":"More","aria-label":"ko"===es?"더 보기":"More",children:(0,r.jsx)(c.In,{size:"16px",svg:(0,r.jsxs)("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round","aria-hidden":"true",children:[(0,r.jsx)("circle",{cx:"12",cy:"5",r:"1"}),(0,r.jsx)("circle",{cx:"12",cy:"12",r:"1"}),(0,r.jsx)("circle",{cx:"12",cy:"19",r:"1"})]})})})}),(0,r.jsx)(o.k.Positioner,{children:(0,r.jsx)(o.k.Content,{"aria-label":"ko"===es?"세션 및 환경 메뉴":"Session and environment menu",children:(0,r.jsxs)(o.k.ScrollArea,{children:[(0,r.jsxs)(o.k.Group,{children:[(0,r.jsx)(o.k.GroupLabel,{children:"ko"===es?"세션":"Session"}),aH&&(0,r.jsx)(o.k.Item,{onClick:sO,children:(0,r.jsx)(o.k.ItemBody,{children:(0,r.jsx)(o.k.ItemLabel,{children:aK?ei("inspector.hide"):ei("inspector.show")})})}),(0,r.jsx)(o.k.Item,{onClick:sG,children:(0,r.jsx)(o.k.ItemBody,{children:(0,r.jsx)(o.k.ItemLabel,{children:ei("session.title")})})}),(0,r.jsx)(o.k.Item,{onClick:aD,disabled:!eD,children:(0,r.jsxs)(o.k.ItemBody,{children:[(0,r.jsx)(o.k.ItemLabel,{children:ei("history.label")}),!eD&&(0,r.jsx)(o.k.ItemDescription,{children:ei("history.unsaved")})]})}),(0,r.jsx)(o.k.Item,{onClick:()=>void aL(),disabled:null!==iT||"naming"===rq.kind,children:(0,r.jsxs)(o.k.ItemBody,{children:[(0,r.jsx)(o.k.ItemLabel,{children:iM}),iI&&(0,r.jsx)(o.k.ItemDescription,{children:iI})]})}),(0,r.jsx)(o.k.Item,{onClick:()=>sJ("branches"),children:(0,r.jsx)(o.k.ItemBody,{children:(0,r.jsx)(o.k.ItemLabel,{children:ei("i18n.branches")})})}),(0,r.jsx)(o.k.Item,{onClick:()=>sJ("system"),children:(0,r.jsx)(o.k.ItemBody,{children:(0,r.jsx)(o.k.ItemLabel,{children:ei("system.label")})})})]}),(0,r.jsxs)(o.k.Group,{children:[(0,r.jsx)(o.k.GroupLabel,{children:"ko"===es?"환경":"Environment"}),(0,r.jsx)(f4,{variant:"menu",locale:es,...ef}),(0,r.jsx)(o.k.Item,{onClick:e=>{let t=e.currentTarget.getBoundingClientRect();en({x:t.left+t.width/2,y:t.top+t.height/2})},children:(0,r.jsx)(o.k.ItemBody,{children:(0,r.jsx)(o.k.ItemLabel,{children:ei("light"===et?"theme.light":"dark"===et?"theme.dark":"theme.auto")})})}),ec.map(e=>(0,r.jsx)(o.k.Item,{role:"menuitemradio","aria-checked":es===e.id,onClick:()=>ea(e.id),children:(0,r.jsx)(o.k.ItemBody,{children:(0,r.jsx)(o.k.ItemLabel,{children:e.label})})},e.id)),(0,r.jsx)(o.k.Item,{onClick:()=>{st(null),tX({type:"close-layer"}),eg&&n1(!1),tL(!0)},children:(0,r.jsx)(o.k.ItemBody,{children:(0,r.jsx)(o.k.ItemLabel,{children:ei("common.settings")})})})]})]})})})]})]}),se&&sn&&(0,a.createPortal)((0,r.jsxs)("div",{ref:ss,className:"workspace-top-layer",role:"dialog","aria-label":ei("branches"===se?"i18n.branches":"system"===se?"system.label":"session.title"),style:{top:sn.top,left:sn.left,width:sn.width,maxHeight:`calc(100dvh - ${sn.top}px - 8px)`},children:[(0,r.jsx)("button",{type:"button",className:"workspace-top-layer-close","aria-label":ei("chat.close"),title:ei("chat.close"),onClick:si,children:(0,r.jsx)(ep,{name:"x"})}),"branches"===se&&(0,r.jsx)("div",{className:"workspace-top-panel",children:(0,r.jsx)(yp,{tree:rC.sessionId===(eD?.id??null)?rC.tree:[],activeLeafId:rC.sessionId===(eD?.id??null)?rC.leafId:null,onLeafChange:rM,hasSession:!!eD})}),"system"===se&&(0,r.jsx)("div",{className:"workspace-top-panel",children:rP?(0,r.jsx)("div",{style:{color:"var(--text-muted)",fontSize:12,lineHeight:1.6,whiteSpace:"pre-wrap",overflowWrap:"anywhere",fontFamily:"var(--font-mono)"},children:rP}):(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text-muted)"},children:ei(""===rP?"system.empty":"system.load")})}),"session"===se&&(0,r.jsx)("div",{className:"workspace-top-panel session-info-popover",children:rF?(D=rF.totalActiveMs??0,B=[...rF.sessionName?[{label:ei("session.name"),value:rF.sessionName,copyField:null}]:[],{label:ei("session.file"),value:rF.sessionFile??ei("session.inMemory"),copyField:"file"},{label:ei("session.id"),value:rF.sessionId,copyField:"id"},...D>0?[{label:ei("session.totalActive"),value:(e=>{if(e<=0)return"0s";let t=Math.floor(e/1e3),n=Math.floor(t/3600),r=Math.floor(t%3600/60),s=t%60;return n>0?`${n}h ${r}m`:r>0?`${r}m ${s}s`:`${s}s`})(D),copyField:null}]:[]],q=[[ei("session.user"),rF.userMessages.toLocaleString(es)],[ei("session.assistant"),rF.assistantMessages.toLocaleString(es)],[ei("session.toolCalls"),rF.toolCalls.toLocaleString(es)],[ei("session.toolResults"),rF.toolResults.toLocaleString(es)],[ei("session.total"),rF.totalMessages.toLocaleString(es)]],V=[[ei("session.input"),rF.tokens.input.toLocaleString(es)],[ei("session.output"),rF.tokens.output.toLocaleString(es)],...rF.tokens.cacheRead>0?[[ei("session.cacheRead"),rF.tokens.cacheRead.toLocaleString(es)]]:[],...rF.tokens.cacheWrite>0?[[ei("session.cacheWrite"),rF.tokens.cacheWrite.toLocaleString(es)]]:[],[ei("session.total"),rF.tokens.total.toLocaleString(es)]],K=r5??rF.contextUsage,J=e=>e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(0)}k`:String(e),G=[...rF.cost>0?[[ei("session.cost"),`$${rF.cost.toFixed(4)}`]]:[],...K?.contextWindow?[[ei("session.context"),`${null!==K.tokens?J(K.tokens):"?"} / ${J(K.contextWindow)}${null!==K.percent?` \xb7 ${K.percent.toFixed(1)}%`:""}`]]:[],...rF.tokens.cacheRead+rF.tokens.cacheWrite>0&&rF.tokens.cacheRead+rF.tokens.cacheWrite+rF.tokens.input>0?[[ei("session.cacheHitRate"),`${(rF.tokens.cacheRead/(rF.tokens.cacheRead+rF.tokens.cacheWrite+rF.tokens.input)*100).toFixed(1)}%`]]:[]],Y=(e,t,n="left",s=!1)=>(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:11,fontWeight:700,color:"var(--text)",marginBottom:6},children:e}),(0,r.jsx)("div",{style:{display:"grid",gridTemplateColumns:s?"max-content max-content":"auto minmax(0, 1fr)",columnGap:s?14:12,rowGap:4,justifyContent:s?"start":void 0},children:t.map(([t,a])=>(0,r.jsxs)("div",{style:{display:"contents"},children:[(0,r.jsx)("div",{style:{color:"var(--text-dim)",whiteSpace:"nowrap"},children:t}),(0,r.jsx)("div",{style:{color:"var(--text-muted)",minWidth:0,overflowWrap:s?"normal":"anywhere",textAlign:n,whiteSpace:"right"===n?"nowrap":"normal"},children:a})]},`${e}:${t}`))})]}),Z=(0,r.jsxs)("div",{style:{minWidth:0},children:[(0,r.jsx)("div",{style:{fontSize:11,fontWeight:700,color:"var(--text)",marginBottom:6},children:ei("session.infoSection")}),(0,r.jsx)("div",{style:{display:"grid",gridTemplateColumns:"auto minmax(0, 1fr) auto",columnGap:12,rowGap:8,alignItems:"start"},children:B.map(e=>{var t,n;let s;return(0,r.jsxs)("div",{style:{display:"contents"},children:[(0,r.jsx)("div",{style:{color:"var(--text-dim)",whiteSpace:"nowrap"},children:e.label}),(0,r.jsx)("div",{style:{color:"var(--text-muted)",minWidth:0,overflowWrap:"anywhere",wordBreak:"break-word",whiteSpace:"normal"},children:e.value}),(0,r.jsx)("div",{children:e.copyField?(t=e.copyField,n=e.value,s=rY===t,(0,r.jsx)("button",{type:"button",title:s?ei("session.copied"):ei("file"===t?"session.copyFile":"session.copyId"),onClick:()=>r2(t,n),style:{alignSelf:"start",display:"inline-flex",alignItems:"center",justifyContent:"center",width:22,height:22,marginTop:-2,color:s?"var(--accent)":"var(--text-dim)",background:"transparent",border:0,borderRadius:"var(--radius-control)",cursor:"pointer",flex:"0 0 auto",transition:"color 0.12s, background 0.12s"},onMouseEnter:e=>{e.currentTarget.style.color="var(--accent)",e.currentTarget.style.background="var(--bg-hover)"},onMouseLeave:e=>{e.currentTarget.style.color=s?"var(--accent)":"var(--text-dim)",e.currentTarget.style.background="transparent"},children:s?(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:(0,r.jsx)("polyline",{points:"20 6 9 17 4 12"})}):(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)("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"}),(0,r.jsx)("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]})})):null})]},`session-info:${e.label}`)})})]}),(0,r.jsxs)("div",{className:"session-info-grid",children:[Z,Y(ei("session.messages"),q),Y(ei("session.tokens"),[...V,...G],"right",!0)]})):(0,r.jsx)("div",{style:{fontSize:12,color:"var(--text-muted)"},children:ei("session.load")})})]}),document.body)]}),(0,r.jsx)("div",{className:"chat-content-layout",children:(0,r.jsxs)("div",{id:"workspace-transcript",ref:aw,className:"chat-session-column","data-translator-open":eT?"true":void 0,onDragOver:e=>{iU&&e.dataTransfer.types.includes(el)&&(e.preventDefault(),e.dataTransfer.dropEffect=iB?"copy":"none",th||tp(!0))},onDragLeave:e=>{e.relatedTarget instanceof Node&&e.currentTarget.contains(e.relatedTarget)||tp(!1)},onDrop:e=>{if(!e.dataTransfer.types.includes(el)||(e.preventDefault(),tp(!1),!iU||!iB))return;let t=e.dataTransfer.getData(el).trim()||null,n=t?nn.find(e=>e.id===t):void 0;n&&ad(n)},children:[th&&(0,r.jsx)("div",{className:"chat-beside-drop","data-blocked":iB?void 0:"true","data-side":iY&&!to?"start":void 0,"aria-hidden":"true",children:(0,r.jsx)("span",{children:iB?ei("workspace.dropBeside"):iZ})}),aH?(0,r.jsx)("div",{className:`chat-split${iY?" is-split":""}`,children:(C=iV?i5:i8,N=(0,r.jsxs)("div",{className:`chat-pane is-active${iJ?" is-covered":""}`,onPointerDownCapture:iK?()=>ty(!1):void 0,onFocusCapture:iK?()=>ty(!1):void 0,children:[iY?iX(a8,iK?null:ah):iV&&!tv&&iX(a8,null,i0),(0,r.jsx)(pl,{session:eD,newSessionCwd:aW,newSessionAutoWorktree:e4,initialSessionData:eB,transitioning:null!==eH,onAgentEnd:a$,onAttentionNeeded:aR,onSessionCreated:aM,onSessionForked:aP,modelsRefreshKey:tE,chatInputRef:rk,onBranchDataChange:rI,onSystemPromptChange:r_,onSessionStatsChange:rG,onSessionStatsPanelOpen:sG,onContextUsageChange:r3,onSubagentsChange:rD,onLabWidgetsChange:s3,onOpenWorkspaceView:is,onOpenSessionList:n0.presented?void 0:sY,onRevealToolCall:io,composerStartPlace:aV,composerNotice:!eD||iK||iJ||iz?void 0:(0,r.jsx)(gw,{sessionId:eD.id,inUse:tC.has(eD.id),onOpen:ag},eD.id),onBrowserUse:ax,onOpenMaker:sE,selectedMaker:sI,onProcessLogChange:r9,onOpenFile:aO,transcriptReplacement:id?(0,r.jsx)("aside",{id:"workspace-auxiliary-panel",className:"workspace-auxiliary-deck-slot is-replacement","data-workspace-region":"deck",children:iH}):null,onComposerFocusChange:nv,onSessionBusyChange:nl,onWaitingChange:nc,onAttentionChange:rB,soundEnabled:ey,onSoundToggle:eb,playCueSound:ew,preloadCueSound:ek,unlockAudio:ej,jumpRequest:eJ,onJumpHandled:eZ,turnInspectorTarget:aK&&"turn"===aG?sx:null,onShowTurnInspector:sz,turnInspectorFolded:ev})]},`pane-${tt}`),C?to?[N,C]:[C,N]:[N])}):id?(0,r.jsx)("aside",{id:"workspace-auxiliary-panel",className:"workspace-auxiliary-deck-slot is-replacement","data-workspace-region":"deck",children:iH}):"validating"===e5?(0,r.jsxs)("div",{role:"status",style:{height:"100%",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:8,padding:24,color:"var(--text-muted)",textAlign:"center"},children:[(0,r.jsx)("div",{style:{fontSize:14,color:"var(--text)"},children:ei("workspace.opening")}),(0,r.jsx)("div",{style:{maxWidth:"min(720px, 100%)",overflowWrap:"anywhere",fontFamily:"var(--font-mono)",fontSize:12},children:ee.requestedCwd})]}):"error"===e5?(0,r.jsxs)("div",{role:"alert",style:{height:"100%",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:8,padding:24,color:"var(--text-muted)",textAlign:"center"},children:[(0,r.jsx)("div",{style:{fontSize:14,color:"var(--danger)"},children:ei("workspace.unable")}),(0,r.jsx)("div",{style:{maxWidth:"min(720px, 100%)",overflowWrap:"anywhere",fontFamily:"var(--font-mono)",fontSize:12},children:ee.requestedCwd}),(0,r.jsx)("div",{style:{maxWidth:720,fontSize:12},children:e3})]}):aZ?s9?(0,r.jsx)("div",{style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",color:"var(--text-muted)",fontSize:15},children:ei("workspace.selectSession")}):(0,r.jsxs)("div",{style:{position:"absolute",top:12,left:12,display:"flex",alignItems:"flex-start",gap:8,userSelect:"none",pointerEvents:"none"},children:[(0,r.jsxs)("svg",{width:"44",height:"44",viewBox:"0 0 24 24",fill:"none",stroke:"var(--accent)",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",style:{opacity:.7,flexShrink:0},children:[(0,r.jsx)("line",{x1:"20",y1:"12",x2:"4",y2:"12"}),(0,r.jsx)("polyline",{points:"10 6 4 12 10 18"})]}),(0,r.jsxs)("div",{children:[(0,r.jsx)("div",{style:{fontSize:18,fontWeight:600,color:"var(--text)",marginBottom:8},children:ei("workspace.getStarted")}),(0,r.jsxs)("div",{style:{fontSize:12,color:"var(--text-muted)",lineHeight:1.8},children:[(0,r.jsx)("span",{style:{color:"var(--text-dim)",marginRight:6},children:"1."}),ei("workspace.selectProject"),(0,r.jsx)("br",{}),(0,r.jsx)("span",{style:{color:"var(--text-dim)",marginRight:6},children:"2."}),ei("workspace.addModels")]})]})]}):null,eM?(0,r.jsx)(wq,{visible:eT,onBack:()=>ng(!1)}):null]})})]}),sy&&iw&&!eT&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{...ru.separatorProps,"aria-controls":"workspace-auxiliary-panel",className:`panel-resize-handle inspector-resize-handle${ru.isResizing?" is-resizing":""}`,"data-resize-handle":"inspector",title:`${ei("layout.resizeInspector")}: ${ei("layout.resizeHint")}`,onPointerDownCapture:()=>{rg.current=!0,ig.current+=1},onFocus:()=>{ri(),rf(!rg.current),rg.current=!1},onBlur:()=>{rg.current=!1,rf(!1)},onKeyDown:e=>{rf(!0),ig.current+=1,ru.separatorProps.onKeyDown(e)}}),(0,r.jsx)("aside",{id:"workspace-auxiliary-panel",className:"workspace-auxiliary-deck-slot is-pinned","data-workspace-region":"deck",children:iH})]}),aJ&&(0,r.jsxs)("div",{className:"inspector-sheet-layer",children:[(0,r.jsx)("div",{className:"inspector-sheet-scrim","aria-hidden":"true",onClick:sW}),(0,r.jsx)("aside",{id:"workspace-auxiliary-panel",className:"workspace-auxiliary-deck-slot is-sheet","data-workspace-region":"deck",role:"dialog","aria-modal":"true","aria-label":ei("inspector.label"),tabIndex:-1,ref:sH,onKeyDown:e=>{"Escape"===e.key&&(e.stopPropagation(),sW())},children:iH})]}),"command-palette"===tQ.transientLayer&&(0,r.jsx)("div",{className:"workspace-command-layer",onMouseDown:e=>{e.target===e.currentTarget&&(tX({type:"close-layer"}),nf())},children:(0,r.jsxs)("div",{ref:nm,className:"workspace-command-palette",role:"dialog","aria-modal":"true",onKeyDown:nU,"aria-label":"ko"===es?"명령 팔레트":"Command palette",children:[(0,r.jsx)(px,{t:ei,onPick:(e,t)=>{tX({type:"close-layer"}),sC("chat",!1),eY.current+=1,eG({id:eY.current,sessionId:e.id,entryId:t.entryId}),aj(e)}}),(0,r.jsxs)("div",{className:"workspace-command-list",children:[sj.waiting.length?(0,r.jsxs)("div",{className:"workspace-command-group",role:"group","aria-label":ei("workbench.needsInput"),children:[(0,r.jsx)("h3",{"aria-hidden":"true",children:ei("workbench.needsInput")}),sj.waiting.map(e=>(0,r.jsxs)("button",{type:"button",className:"workspace-command-waiting",onClick:()=>{tX({type:"close-layer"}),sC("chat",!0),aj(e)},children:[(0,r.jsxs)("span",{children:[(0,r.jsx)("span",{className:"workbench-lamp","data-kind":"input","aria-hidden":"true"}),e.name?.trim()||e.firstMessage?.trim()||e.id]}),(0,r.jsx)("small",{children:ei("workbench.needsInput")})]},`waiting-${e.id}`))]}):null,(0,r.jsxs)("div",{className:"workspace-command-group",role:"group","aria-label":ei("palette.groupViews"),children:[(0,r.jsxs)("h3",{"aria-hidden":"true",children:[ei("palette.groupViews")," ",(0,r.jsx)("small",{children:ei("palette.groupViewsHint")})]}),d.map(e=>(0,r.jsxs)("button",{type:"button","aria-current":tQ.activeView===e?"true":void 0,onClick:()=>{"resource"===e&&t1("characters"),sC(e,!0)},children:[(0,r.jsxs)("span",{children:[(0,r.jsx)(ep,{name:tQ.activeView===e?"check":jd[e]}),iy[e]]}),(0,r.jsx)("small",{children:tQ.activeView===e?"ko"===es?"현재 보기":"Current view":""})]},e))]}),(0,r.jsxs)("div",{className:"workspace-command-group",role:"group","aria-label":ei("palette.groupShortcuts"),children:[(0,r.jsx)("h3",{"aria-hidden":"true",children:ei("palette.groupShortcuts")}),["usage","models"].map(e=>(0,r.jsx)("button",{type:"button",onClick:()=>{t1(e),sC("resource",!1)},children:(0,r.jsxs)("span",{children:[(0,r.jsx)(ep,{name:"usage"===e?"user-round":"chart-column"}),"usage"===e?"계정 한도":"모델 통계"]})},e))]}),(0,r.jsxs)("div",{className:"workspace-command-group",role:"group","aria-label":ei("palette.groupScreen"),children:[(0,r.jsx)("h3",{"aria-hidden":"true",children:ei("palette.groupScreen")}),(0,r.jsxs)("button",{type:"button",onClick:sY,children:[(0,r.jsxs)("span",{children:[(0,r.jsx)(ep,{name:"panel-left"}),n0.presented?ei("sidebar.hide"):ei("sidebar.show")]}),(0,r.jsx)("kbd",{children:"Ctrl B"})]}),(0,r.jsx)("button",{type:"button",onClick:e0,children:(0,r.jsxs)("span",{children:[(0,r.jsx)(ep,{name:"maximize-2"}),ei(eQ?"palette.wideChatOff":"palette.wideChatOn")]})}),t7&&sy&&jl.map(e=>(0,r.jsx)("button",{type:"button",onClick:()=>ix(e.id),children:(0,r.jsxs)("span",{children:[(0,r.jsx)(ep,{name:"panel-right"}),ei("palette.layoutPreset",{name:ei(e.label)})]})},e.id)),(0,r.jsx)("button",{type:"button",onClick:()=>{tX({type:"close-layer"}),tL(!0)},children:(0,r.jsxs)("span",{children:[(0,r.jsx)(ep,{name:"settings"}),ei("common.settings")]})})]})]}),(0,r.jsxs)("footer",{className:"workspace-command-footer","aria-hidden":"true",children:[(0,r.jsxs)("span",{children:[(0,r.jsx)("kbd",{children:"↑↓"})," ",ei("palette.hintMove")]}),(0,r.jsxs)("span",{children:[(0,r.jsx)("kbd",{children:"Enter"})," ",ei("palette.hintOpen")]}),(0,r.jsxs)("span",{children:[(0,r.jsx)("kbd",{children:"Esc"})," ",ei("palette.hintClose")]})]})]})})]}),eL?(0,r.jsx)(k3,{open:e$,onClose:()=>nx(!1),onStartSession:aN}):null,(0,r.jsx)(k7,{message:eA,onDismiss:eF}),tR&&(0,r.jsx)(f0,{cwd:aY,sessionId:eD?.id??null,onClose:()=>{tL(!1),tH(e=>e+1),nf()},onModelsChanged:()=>t$(e=>e+1),onReloaded:()=>tn(ji(tr))}),null!==tP&&(0,r.jsx)(m7,{cwd:aY,onClose:sB,onModelsChanged:()=>t$(e=>e+1),relogin:{target:tP,outcome:t_,onLoginSucceeded:sV}}),tq&&aY&&(0,r.jsx)(f8,{cwd:aY,busy:tJ,scheduled:tz?.pending==="grant",error:tY,onCancel:()=>{tJ||(tV(!1),nf())},onConfirm:()=>void aX("grant"),onCancelSchedule:()=>void aX("cancel")})]})}},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",seg:"SettingsConfig_seg__XuRNt",panel:"SettingsConfig_panel__ZI0zy",btn:"SettingsConfig_btn__n6fBy",btnPrimary:"SettingsConfig_btnPrimary__iimPs",btnDanger:"SettingsConfig_btnDanger__1fFIU",btnQuiet:"SettingsConfig_btnQuiet__fNd0U",btnOk:"SettingsConfig_btnOk__EO_j1",field:"SettingsConfig_field__PVLX2",badge:"SettingsConfig_badge__8u4iQ",badgeWarn:"SettingsConfig_badgeWarn___hejU",badgeDanger:"SettingsConfig_badgeDanger__Ya7g_",badgeInfo:"SettingsConfig_badgeInfo__P8FR7",textDanger:"SettingsConfig_textDanger__5_0Vx",textOk:"SettingsConfig_textOk__XPaRs",textWarn:"SettingsConfig_textWarn__MxfZX",lamp:"SettingsConfig_lamp__spLQJ",lampOn:"SettingsConfig_lampOn__I5AtE",lampWarn:"SettingsConfig_lampWarn__gG1l4",lampDanger:"SettingsConfig_lampDanger__7BeCc",scrim:"SettingsConfig_scrim__i645I",sheet:"SettingsConfig_sheet__YV6De",listRowSel:"SettingsConfig_listRowSel__7RSLQ",bare:"SettingsConfig_bare__XoKXl",fieldBare:"SettingsConfig_fieldBare__jiy_X",navRow:"SettingsConfig_navRow__dSjxf"}},14755:(e,t,n)=>{"use strict";n.d(t,{C1:()=>a,IN:()=>s,getPresetFromTools:()=>l,xG:()=>o});let r=[],s=["read","bash","edit","write"],a=["read","bash","edit","write","grep","glob"],i=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===i[e]).sort().join(",");return n===[...s].sort().join(",")?"default":n===[...a].sort().join(",")?"full":"default"}function o(e){return"none"===e?[...r]:"full"===e?[...a]:[...s]}},21340:()=>{},21443:e=>{e.exports={dialog:"CloudProjectPicker_dialog__Dx2Dt",form:"CloudProjectPicker_form__MpEsn",header:"CloudProjectPicker_header__UcYbB",sources:"CloudProjectPicker_sources__6cl_0",activeSource:"CloudProjectPicker_activeSource__NptfQ",body:"CloudProjectPicker_body__vKMBC",account:"CloudProjectPicker_account__gb9Qo",repositories:"CloudProjectPicker_repositories__WSBt6",secondary:"CloudProjectPicker_secondary__hlaFU",primary:"CloudProjectPicker_primary__voWx5",loginLink:"CloudProjectPicker_loginLink__Gu5XC",login:"CloudProjectPicker_login__c0qSl",codeRow:"CloudProjectPicker_codeRow__jo8vy",repositoryInput:"CloudProjectPicker_repositoryInput__HWhvu",list:"CloudProjectPicker_list__0BSYU",repo:"CloudProjectPicker_repo__L4VaW",repoHeading:"CloudProjectPicker_repoHeading__3Pnq1",repoDescription:"CloudProjectPicker_repoDescription__YzPtB",error:"CloudProjectPicker_error__dAVsm",progress:"CloudProjectPicker_progress__OwvG9",footer:"CloudProjectPicker_footer__mmrGI"}},24568:(e,t,n)=>{"use strict";n.d(t,{$y:()=>l,Df:()=>m,Kn:()=>v,Oe:()=>h,U5:()=>y,_t:()=>b,aO:()=>a,di:()=>s,fG:()=>f,in:()=>u,sX:()=>w,v6:()=>g,vJ:()=>x});var r=n(1930);let s="a2ui",a="a2ui-action",i=/^( {0,3})(`{3,}|~{3,})(.*)$/;function l(e,t){if(!e.includes(t))return[];let n=e.split(/\r?\n/),r=[];for(let e=0;e<n.length;e+=1){let s=i.exec(n[e]);if(!s)continue;let[,a,l,o]=s;if("`"===l[0]&&o.includes("`"))continue;let c=l[0],d=RegExp(`^ {0,3}${"`"===c?"`":"~"}{${l.length},}[ \\t]*$`),u=[],h=e+1;for(;h<n.length&&!d.test(n[h]);h+=1)u.push(function(e,t){let n=0;for(;n<t&&" "===e[n];)n+=1;return e.slice(n)}(n[h],a.length));o.trim().split(/\s+/)[0]?.toLowerCase()===t&&r.push(u.join("\n")),e=h}return r}let o=r.g1(r.L5()),c=r.KC([r.YO(o).nonempty(),r.Ik({messages:r.YO(o).nonempty()}).transform(e=>e.messages),o.transform(e=>[e])]),d=r.Ik({surfaceId:r.Yj().min(1)}).passthrough();function u(e){let t,n=e.trim();if(!n)return{ok:!1,reason:"empty"};try{t=JSON.parse(n)}catch{let e=n.split("\n").map(e=>e.trim()).filter(Boolean);if(e.length<2)return{ok:!1,reason:"json"};let r=[];for(let t of e)try{r.push(JSON.parse(t))}catch{return{ok:!1,reason:"json"}}t=r}let r=c.safeParse(t);return r.success?{ok:!0,messages:r.data}:{ok:!1,reason:"shape"}}function h(e){let t={created:[],updated:[],deleted:[]},n={createSurface:t.created,updateComponents:t.updated,updateDataModel:t.updated,deleteSurface:t.deleted};for(let t of e)for(let[e,r]of Object.entries(n)){let n=d.safeParse(t[e]);n.success&&!r.includes(n.data.surfaceId)&&r.push(n.data.surfaceId)}return t}let p=r.Ik({version:r.eu("1.0"),action:r.Ik({name:r.Yj(),surfaceId:r.Yj(),sourceComponentId:r.Yj(),timestamp:r.Yj(),context:r.g1(r.L5())}).passthrough(),metadata:r.Ik({a2uiClientDataModel:r.Ik({version:r.eu("1.0"),surfaces:r.g1(r.L5())})}).optional()});function m(e,t){let n={version:"1.0",action:{name:e.name,surfaceId:e.surfaceId,sourceComponentId:e.sourceComponentId,timestamp:e.timestamp,context:e.context??{}}};return void 0!==t&&(n.metadata={a2uiClientDataModel:{version:"1.0",surfaces:{[e.surfaceId]:t}}}),n}function f(e){let t=JSON.stringify(e);return`카드 동작: ${e.action.name} (${e.action.surfaceId})