cuelo 0.10.340 → 0.10.341

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 (116) hide show
  1. package/.next/BUILD_ID +1 -1
  2. package/.next/app-path-routes-manifest.json +53 -53
  3. package/.next/build-manifest.json +2 -2
  4. package/.next/prerender-manifest.json +3 -3
  5. package/.next/required-server-files.js +1 -1
  6. package/.next/required-server-files.json +1 -1
  7. package/.next/server/app/_global-error/page_client-reference-manifest.js +1 -1
  8. package/.next/server/app/_global-error.html +1 -1
  9. package/.next/server/app/_global-error.rsc +1 -1
  10. package/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
  11. package/.next/server/app/_global-error.segments/_global-error/__PAGE__.segment.rsc +1 -1
  12. package/.next/server/app/_global-error.segments/_global-error.segment.rsc +1 -1
  13. package/.next/server/app/_global-error.segments/_head.segment.rsc +1 -1
  14. package/.next/server/app/_global-error.segments/_index.segment.rsc +1 -1
  15. package/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
  16. package/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
  17. package/.next/server/app/_not-found.html +1 -1
  18. package/.next/server/app/_not-found.rsc +2 -2
  19. package/.next/server/app/_not-found.segments/_full.segment.rsc +2 -2
  20. package/.next/server/app/_not-found.segments/_head.segment.rsc +1 -1
  21. package/.next/server/app/_not-found.segments/_index.segment.rsc +2 -2
  22. package/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +1 -1
  23. package/.next/server/app/_not-found.segments/_not-found.segment.rsc +1 -1
  24. package/.next/server/app/_not-found.segments/_tree.segment.rsc +1 -1
  25. package/.next/server/app/api/agent/[id]/account/route.js +1 -1
  26. package/.next/server/app/api/agent/[id]/computer-takeover/route.js +1 -1
  27. package/.next/server/app/api/agent/[id]/events/route.js +1 -1
  28. package/.next/server/app/api/agent/[id]/route.js +1 -1
  29. package/.next/server/app/api/agent/new/route.js +1 -1
  30. package/.next/server/app/api/agent/running/route.js +1 -1
  31. package/.next/server/app/api/gpt6/handles/route.js +1 -1
  32. package/.next/server/app/api/gpt6/reply/route.js +1 -1
  33. package/.next/server/app/api/gpt6/token/route.js +1 -1
  34. package/.next/server/app/api/gpt6/web6-session/route.js +1 -1
  35. package/.next/server/app/api/live/call/[callId]/route.js +1 -1
  36. package/.next/server/app/api/live/draft-secret/route.js +1 -1
  37. package/.next/server/app/api/live/events/route.js +1 -1
  38. package/.next/server/app/api/live/interpret/assist/route.js +1 -1
  39. package/.next/server/app/api/live/interpret/reading/route.js +1 -1
  40. package/.next/server/app/api/live/interpret/route.js +1 -1
  41. package/.next/server/app/api/live/interpret/scan/route.js +1 -1
  42. package/.next/server/app/api/live/interpret/text/route.js +1 -1
  43. package/.next/server/app/api/live/offer/route.js +1 -1
  44. package/.next/server/app/api/live/voices/route.js +1 -1
  45. package/.next/server/app/api/project-trust/route.js +1 -1
  46. package/.next/server/app/api/runs/[runId]/prelude/route.js +1 -1
  47. package/.next/server/app/api/sessions/[id]/auto-name/route.js +1 -1
  48. package/.next/server/app/api/sessions/[id]/context/route.js +1 -1
  49. package/.next/server/app/api/sessions/[id]/route.js +1 -1
  50. package/.next/server/app/api/sessions/[id]/state/route.js +1 -1
  51. package/.next/server/app/api/sessions/route.js +1 -1
  52. package/.next/server/app/api/skills/check/route.js +1 -1
  53. package/.next/server/app/api/skills/install/route.js +1 -1
  54. package/.next/server/app/api/skills/install/route.js.nft.json +1 -1
  55. package/.next/server/app/api/skills/route.js +1 -1
  56. package/.next/server/app/api/skills/update/route.js +1 -1
  57. package/.next/server/app/api/tool-image/route.js +1 -1
  58. package/.next/server/app/api/update-maintenance/route.js +1 -1
  59. package/.next/server/app/api/updates/apply/route.js +2 -2
  60. package/.next/server/app/api/updates/route.js +1 -1
  61. package/.next/server/app/api/upkeep/check/route.js +1 -1
  62. package/.next/server/app/api/upkeep/morning/route.js +1 -1
  63. package/.next/server/app/api/upkeep/nightly/export/route.js +1 -1
  64. package/.next/server/app/api/upkeep/nightly/result/route.js +1 -1
  65. package/.next/server/app/api/upkeep/nightly/route.js +1 -1
  66. package/.next/server/app/api/upkeep/route.js +1 -1
  67. package/.next/server/app/api/worktrees/route.js +1 -1
  68. package/.next/server/app/index.html +1 -1
  69. package/.next/server/app/index.rsc +4 -4
  70. package/.next/server/app/index.segments/__PAGE__.segment.rsc +3 -3
  71. package/.next/server/app/index.segments/_full.segment.rsc +4 -4
  72. package/.next/server/app/index.segments/_head.segment.rsc +1 -1
  73. package/.next/server/app/index.segments/_index.segment.rsc +2 -2
  74. package/.next/server/app/index.segments/_tree.segment.rsc +1 -1
  75. package/.next/server/app/page.js +2 -2
  76. package/.next/server/app/page_client-reference-manifest.js +1 -1
  77. package/.next/server/app/recover/page_client-reference-manifest.js +1 -1
  78. package/.next/server/app/recover.html +1 -1
  79. package/.next/server/app/recover.rsc +2 -2
  80. package/.next/server/app/recover.segments/_full.segment.rsc +2 -2
  81. package/.next/server/app/recover.segments/_head.segment.rsc +1 -1
  82. package/.next/server/app/recover.segments/_index.segment.rsc +2 -2
  83. package/.next/server/app/recover.segments/_tree.segment.rsc +1 -1
  84. package/.next/server/app/recover.segments/recover/__PAGE__.segment.rsc +1 -1
  85. package/.next/server/app/recover.segments/recover.segment.rsc +1 -1
  86. package/.next/server/app-paths-manifest.json +53 -53
  87. package/.next/server/chunks/2235.js +2 -2
  88. package/.next/server/chunks/5228.js +1 -1
  89. package/.next/server/chunks/8685.js +4 -4
  90. package/.next/server/chunks/9467.js +2 -2
  91. package/.next/server/middleware-build-manifest.js +1 -1
  92. package/.next/server/pages/404.html +1 -1
  93. package/.next/server/pages/500.html +1 -1
  94. package/.next/server/server-reference-manifest.json +1 -1
  95. package/.next/static/chunks/app/{layout-21f6af530e431195.js → layout-6ee169c5af9a4d8e.js} +1 -1
  96. package/.next/static/chunks/app/{page-1b8437381ed0a136.js → page-6b7ae42a86e2c837.js} +2 -2
  97. package/.next/trace +113 -113
  98. package/.next/trace-build +1 -1
  99. package/Tools/CUELO_Setup/files/native-runtime-patch.js +1 -1
  100. package/Tools/OMP_Global_Config/agent/extensions/consult.ts +7 -7
  101. package/Tools/OMP_Global_Config/agent/extensions/cross-review.ts +6 -7
  102. package/Tools/OMP_Global_Config/agent/extensions/lib/cross-review.ts +31 -23
  103. package/Tools/OMP_Global_Config/agent/extensions/lib/finalize-checks.ts +213 -40
  104. package/Tools/OMP_Global_Config/agent/extensions/lib/helper-usage.ts +55 -0
  105. package/Tools/OMP_Global_Config/agent/extensions/lib/interpreter.ts +5 -6
  106. package/Tools/OMP_Global_Config/agent/extensions/lib/preflight-check.ts +44 -12
  107. package/Tools/OMP_Global_Config/agent/extensions/skim.ts +22 -24
  108. package/Tools/OMP_Global_Config/agent/rules/cross-review-procedure.md +3 -1
  109. package/Tools/OMP_Global_Config/agent/rules/subagent.md +1 -1
  110. package/Tools/OMP_Global_Config/agent/tools/git-finalizer/finalizer.ps1 +14 -0
  111. package/Tools/OMP_Global_Config/agent/tools/git-finalizer/index.ts +9 -9
  112. package/Tools/OMP_Global_Config/patches/apply-core-patch.mjs +4 -3
  113. package/bin/ci-local.mjs +4 -1
  114. package/package.json +1 -1
  115. /package/.next/static/{4XtQSNswpweUHnrOc9NYK → T48PfNOAbH9vZjSnZ4tXV}/_buildManifest.js +0 -0
  116. /package/.next/static/{4XtQSNswpweUHnrOc9NYK → T48PfNOAbH9vZjSnZ4tXV}/_ssgManifest.js +0 -0
@@ -1,4 +1,4 @@
1
- (self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[8974],{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)}n.d(t,{u0:()=>r})},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"}},29213:e=>{e.exports={view:"PluginLabPanel_view__Sot51",toolbar:"PluginLabPanel_toolbar__co_Uq",hint:"PluginLabPanel_hint__kb7Hq",body:"PluginLabPanel_body__T_QMu",message:"PluginLabPanel_message__QbEDh",errorText:"PluginLabPanel_errorText__EI47_",list:"PluginLabPanel_list__BnAn6",card:"PluginLabPanel_card__5479R",cardHead:"PluginLabPanel_cardHead__SCiZ3",titleBlock:"PluginLabPanel_titleBlock__zfcvo",titleLine:"PluginLabPanel_titleLine__OmG7U",name:"PluginLabPanel_name__t4Ea0",id:"PluginLabPanel_id__osclH",control:"PluginLabPanel_control___gzgN",switch:"PluginLabPanel_switch__m3agg",switchLabel:"PluginLabPanel_switchLabel__DGX6y",description:"PluginLabPanel_description__PfruO",enhancement:"PluginLabPanel_enhancement__TOHjM",enhancementHead:"PluginLabPanel_enhancementHead__sgewN",enhancementDate:"PluginLabPanel_enhancementDate__4YWB1",enhancementSummary:"PluginLabPanel_enhancementSummary__srTnj",tools:"PluginLabPanel_tools__raR8s",metaLabel:"PluginLabPanel_metaLabel__LY5ak",toolList:"PluginLabPanel_toolList___rd6_",tool:"PluginLabPanel_tool___AjRR",problem:"PluginLabPanel_problem__Sx4aQ",problemLabel:"PluginLabPanel_problemLabel__rBSUT",cardActions:"PluginLabPanel_cardActions__GI_Bb",stage:"PluginLabPanel_stage__1l0FR",frame:"PluginLabPanel_frame__sP_V0",status:"PluginLabPanel_status__BYiAs",lines:"PluginLabPanel_lines__ONctT",notice:"PluginLabPanel_notice__mn_vu"}},34292:e=>{e.exports={body:"MenuScan_body__N1gSP",pickers:"MenuScan_pickers__K7rHv",primary:"MenuScan_primary__aMEtr",secondary:"MenuScan_secondary__nV23S",hiddenInput:"MenuScan_hiddenInput__qx7P_",avoid:"MenuScan_avoid__iazt8",hint:"MenuScan_hint__Jz4C9",status:"MenuScan_status__CnA_N",error:"MenuScan_error__CgwsP",summary:"MenuScan_summary__b1ZtT",signLine:"MenuScan_signLine__f_kUU",rescan:"MenuScan_rescan__Cdw4T",list:"MenuScan_list__sLZlP",row:"MenuScan_row__Hh2pX",warning:"MenuScan_warning__0eyVj",pick:"MenuScan_pick__wMRMv",main:"MenuScan_main__P3_Xp",translation:"MenuScan_translation__KT9aS",original:"MenuScan_original__yKqtc",description:"MenuScan_description__ZPvqQ",tags:"MenuScan_tags__VjkJ7",side:"MenuScan_side__zxLGs",price:"MenuScan_price__EzjRO",show:"MenuScan_show__fE8b0",footer:"MenuScan_footer__x2A7y",footerLabel:"MenuScan_footerLabel__2dbF_",footerTotal:"MenuScan_footerTotal__pWpMt"}},34817:e=>{e.exports={notice:"RepoSyncIndicator_notice__6q27O",body:"RepoSyncIndicator_body___uZUj",repo:"RepoSyncIndicator_repo__U0mga",actions:"RepoSyncIndicator_actions__OgFJN"}},40960:e=>{e.exports={active:"ComputerTakeoverControl_active__7430b"}},44440:(e,t,n)=>{"use strict";n.d(t,{AppShell:()=>ke});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"];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 A(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 P=/^<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(P);if(!t)return null;let[,n,,,r]=t;return r?`/skill:${n} ${r}`:`/skill:${n}`}var F=n(84183);let z=`(max-width: ${u.navigator-1}px)`;function W(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 O=W("(max-width: 640px)"),D=W(z);function H(){return!1}function U(){return(0,s.useSyncExternalStore)(O.subscribe,O.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 Z=n(21443),Y=n.n(Z);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",A=n||C,P=(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 z(e){if(e.preventDefault(),y.trim()&&!A){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),P()},[P]),(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 P();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,P]),!c)return null;if(u)return(0,r.jsx)(G,{onCancel:()=>h(!1),onSelect:t,busy:n,error:i});let W=f.filter(e=>`${e.fullName} ${e.description??""}`.toLowerCase().includes(x.toLowerCase())),O=T??i??p?.device?.error;return(0,a.createPortal)((0,r.jsx)("dialog",{ref:o,className:Y().dialog,"aria-labelledby":"cloud-project-title",onCancel:t=>{t.preventDefault(),A||e()},children:(0,r.jsxs)("form",{onSubmit:z,className:Y().form,children:[(0,r.jsxs)("header",{className:Y().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:Y().sources,children:[(0,r.jsx)("span",{className:Y().activeSource,children:l("cloudProjects.github")}),(0,r.jsx)("button",{type:"button",onClick:()=>h(!0),disabled:A,children:l("cloudProjects.serverFolder")})]}),(0,r.jsxs)("div",{className:Y().body,children:[(0,r.jsxs)("section",{className:Y().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:Y().secondary,onClick:()=>void P(),disabled:w||A,children:l("cloudProjects.refresh")}):(0,r.jsx)("button",{type:"button",className:Y().secondary,onClick:()=>void _(),disabled:w||j||L||A,children:j||L?l("cloudProjects.waiting"):l("cloudProjects.connect")})]}),L&&(0,r.jsxs)("div",{className:Y().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:Y().codeRow,children:[(0,r.jsx)("code",{children:p.device.code}),(0,r.jsx)("button",{type:"button",className:Y().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:Y().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:Y().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:A}),w?(0,r.jsx)("p",{role:"status",children:l("cloudProjects.loading")}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("ul",{className:Y().list,children:W.slice(0,$).map(e=>(0,r.jsx)("li",{children:(0,r.jsxs)("button",{type:"button",className:Y().repo,"aria-pressed":y===e.fullName,disabled:A,onClick:()=>b(e.fullName),children:[(0,r.jsxs)("span",{className:Y().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:Y().repoDescription,children:e.description})]})},e.fullName))}),!W.length&&(0,r.jsx)("p",{children:l("cloudProjects.empty")}),W.length>$&&(0,r.jsx)("button",{type:"button",className:Y().secondary,onClick:()=>R(e=>e+50),children:l("cloudProjects.more")})]})]}),(0,r.jsxs)("div",{className:Y().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:A,"aria-describedby":"cloud-repo-help"}),(0,r.jsx)("small",{id:"cloud-repo-help",children:l("cloudProjects.publicHelp")})]}),O&&(0,r.jsxs)("div",{className:Y().error,role:"alert",children:[(0,r.jsx)("strong",{children:l("cloudProjects.error")}),(0,r.jsx)("p",{children:O}),(0,r.jsx)("button",{type:"button",className:Y().secondary,onClick:()=>void P(),disabled:A,children:l("cloudProjects.refresh")})]}),C&&(0,r.jsx)("p",{role:"status",className:Y().progress,children:l("cloudProjects.openingHelp")})]}),(0,r.jsxs)("footer",{className:Y().footer,children:[(0,r.jsx)("button",{type:"button",className:Y().secondary,onClick:e,disabled:A,children:l("i18n.cancel")}),(0,r.jsx)("button",{type:"submit",className:Y().primary,disabled:A||!y.trim(),children:A?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.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.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":"This phone couldn't read it aloud. Check the phone's text-to-speech settings.","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="omp-web:unread-session-ids",eo="omp-web:pinned-session-ids",ec="omp-web:removed-projects";function ed(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 eu(e,t){return t&&e.startsWith(t)?"~"+e.slice(t.length):e}function eh({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 ep({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 em="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*";function ef(){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:em[Math.floor(Math.random()*em.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.340/19.1.0":"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 eg(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 ex({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,P]=(0,s.useState)([]),_=(0,s.useMemo)(()=>t&&!j.some(e=>e.id===t.id)?[t,...j]:j,[j,t]),[z,W]=(0,s.useState)(!0),[O,D]=(0,s.useState)(null),[H,B]=(0,s.useState)(null),[q,V]=(0,s.useState)(""),[K,J]=(0,s.useState)(!1),[Z,Y]=(0,s.useState)(""),[Q,ee]=(0,s.useState)(()=>new Set),[et,en]=(0,s.useState)(()=>new Set),[em,ey]=(0,s.useState)(null),[ej,eS]=(0,s.useState)(null),[eC,eT]=(0,s.useState)({version:1,projects:[]}),[eI,eM]=(0,s.useState)(!1),[eE,e$]=(0,s.useState)(!1),[eR,eL]=(0,s.useState)(!1),[eA,eP]=(0,s.useState)(null),[e_,eF]=(0,s.useState)(""),[ez,eW]=(0,s.useState)(!1),[eO,eD]=(0,s.useState)(null),[eH,eU]=(0,s.useState)(""),[eB,eq]=(0,s.useState)(!1),[eV,eK]=(0,s.useState)(null),[eJ,eG]=(0,s.useState)(!1),[eZ,eY]=(0,s.useState)(null),[eQ,eX]=(0,s.useState)(!1),[e0,e1]=(0,s.useState)(!1),[e2,e4]=(0,s.useState)(""),[e8,e5]=(0,s.useState)(null),[e6,e3]=(0,s.useState)(""),[e7,e9]=(0,s.useState)(!1),[te,tt]=(0,s.useState)(null),tn=(0,s.useRef)(null),[tr,ts]=(0,s.useState)(!1),[ta,ti]=(0,s.useState)(null),tl=(0,s.useRef)(null),to=(0,s.useRef)(null),tc=(0,s.useRef)(null),td=(0,s.useRef)(!1),tu=(0,s.useRef)(!1),[th,tp]=(0,s.useState)(!1),[tm,tf]=(0,s.useState)(()=>new Set),[tg,tx]=(0,s.useState)(()=>new Set),[tv,ty]=(0,s.useState)(()=>(function(){try{let e=window.localStorage.getItem(el);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}})()),[tb,tw]=(0,s.useState)(()=>new Set),[tk,tj]=(0,s.useState)(null),[tS,tC]=(0,s.useState)(!1),tN=(0,s.useRef)(new Set),tT=(0,s.useRef)(!1),tI=(0,s.useRef)(null);(0,s.useEffect)(()=>{tw(function(){try{let e=window.localStorage.getItem(eo);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{}tj(N(e,Date.now()));let t=e=>{if(e.key!==C||null===e.newValue)return;let t=N(e.newValue,Date.now());tj(e=>e?T(e,t):e)};return window.addEventListener("storage",t),()=>window.removeEventListener("storage",t)},[]);let tM=(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}`);eT(await e.json())}catch{eT({version:1,projects:[]})}finally{eM(!0)}},[]);(0,s.useEffect)(()=>{tM()},[tM,c]),(0,s.useEffect)(()=>{let e=null;try{e=window.localStorage.getItem(ec)}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 eg(n.map(e=>({key:R(e),path:e,hidden:!0})))}}catch{return}try{window.localStorage.removeItem(ec)}catch{}await tM()})()},[tM]);let tE=(0,s.useCallback)(async e=>{if(tu.current)throw Error("Project update in progress");tu.current=!0,eW(!0);try{await eg(e),await tM()}finally{tu.current=!1,eW(!1)}},[tM]);(0,s.useEffect)(()=>{eA&&tc.current?.select()},[eA]);let t$=(0,s.useCallback)(async(e=!1,t=!1)=>{try{e&&W(!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();P(r.sessions),tT.current||tf(new Set(r.runningSessionIds??[])),D(null),e||(tp(!0),tI.current&&clearTimeout(tI.current),tI.current=setTimeout(()=>tp(!1),2e3))}catch(e){D(String(e))}finally{e&&W(!1)}},[]),tR=(0,s.useCallback)(e=>{ty(t=>{if(!t.has(e))return t;let n=new Set(t);return n.delete(e),n}),tw(t=>{if(!t.has(e))return t;let n=new Set(t);return n.delete(e),n}),tj(t=>t&&$(t,[e])),d?.(e),t$()},[t$,d]),[tL,tA]=(0,s.useState)(null),[tP,t_]=(0,s.useState)(!1),[tF,tz]=(0,s.useState)(null),tW=(0,s.useCallback)(()=>{tP||(tA(null),tz(null))},[tP]),tO=(0,s.useCallback)(async e=>{t_(!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&&(tT.current=!0,tf(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(ty(n),tw(n),tj(e=>e&&$(e,t)),t))d?.(e)}(await t$(),t_(!1),r.length>0)?tz(b("sidebar.clearSessionsFailed",{count:r.length,names:r.join(", ")})):n.length>0||tA(null)},[t$,d,b]),[tD,tH]=(0,s.useState)(0),tU=(0,s.useCallback)(()=>{tH(e=>e+1),t$()},[t$]),tB=(0,s.useRef)(!1);(0,s.useEffect)(()=>{let e=!tB.current;tB.current=!0,t$(e,!e)},[t$,c]),(0,s.useEffect)(()=>{if("priority"!==g)return;let e=()=>{"visible"===document.visibilityState&&t$(!1,!0)};e();let t=window.setInterval(e,15e3);return()=>window.clearInterval(t)},[t$,g]),(0,s.useEffect)(()=>{x?.({running:tm.size,waiting:j.filter(e=>tg.has(e.id))})},[j,x,tm,tg]),(0,s.useEffect)(()=>{try{0===tv.size?window.localStorage.removeItem(el):window.localStorage.setItem(el,JSON.stringify([...tv]))}catch{}},[tv]),(0,s.useEffect)(()=>{try{0===tb.size?window.localStorage.removeItem(eo):window.localStorage.setItem(eo,JSON.stringify([...tb]))}catch{}},[tb]),(0,s.useEffect)(()=>{if(tk)try{var e,t,n;let r=window.localStorage;r.setItem(C,(e=r.getItem(C),t=Date.now(),JSON.stringify({since:(n=T(tk,N(e,t))).since,opened:n.opened})))}catch{}},[tk]);let tq=(0,s.useCallback)(e=>{tw(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;tT.current=!0,tf(new Set(r.runningSessionIds??[])),tx(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)}},[]),(0,s.useEffect)(()=>{let t=tN.current,n=[...t].filter(t=>!tm.has(t)&&t!==e),r=[...tm].filter(e=>!t.has(e));(n.length>0||r.length>0)&&ty(e=>{let t=new Set(e);return tm.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)&&t$(!1,!0),n.length>0&&p?.(),tN.current=tm},[tm,e,j,t$,p]),(0,s.useEffect)(()=>{e&&ty(t=>{if(!t.has(e))return t;let n=new Set(t);return n.delete(e),n})},[e]);let tV=e?_.find(t=>t.id===e):void 0,tK=tV?.conversationModified??tV?.modified,tJ=null!==tk;(0,s.useEffect)(()=>{e&&void 0!==tK&&tJ&&tj(t=>t&&M(t,{id:e,modified:tK},Date.now()))},[e,tK,tJ]),(0,s.useEffect)(()=>{fetch("/api/home").then(e=>e.json()).then(e=>{e.home&&V(e.home),J(!0===e.cloudProjects)}).catch(()=>{})},[]);let tG=(0,s.useRef)(!1),tZ=(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,_]),tY=(0,s.useRef)(null);(0,s.useEffect)(()=>{tY.current!==H&&(tY.current=H,h?.(H,tZ(H)))},[H,h,tZ]);let tQ=(0,s.useRef)(null);(0,s.useEffect)(()=>{u&&u!==tQ.current&&(tQ.current=u,B(u))},[u]);let[tX,t0]=(0,s.useState)(0);(0,s.useLayoutEffect)(()=>{if(!H)return void eY(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 eY(null);eY({forCwd:H,projectRoot:t.projectRoot,isGit:t.isGit??!1,isTopLevel:t.isTopLevel??!1,worktrees:t.worktrees??[]})}}).catch(()=>{e||eY(null)}),()=>{e=!0}},[H,tX,c]),(0,s.useEffect)(()=>{if(0!==j.length&&!l&&null===H){if(i&&!tG.current){tG.current=!0;let e=j.find(e=>e.id===i);if(e){B(e.cwd),n(e,!0);return}o?.()}if(!eI)return;let e=new Map(eC.projects.map(e=>[e.key,e])),t=A(j.length>0?L(j):[],eC.projects).filter(t=>!e.get(R(t))?.hidden);t.length>0&&B(t[0])}},[j,H,i,l,n,o,eC,eI]);let t1=(0,s.useCallback)(async e=>{let t=e.trim();if(t&&!eJ){eG(!0),eK(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 eK(n.error??b("workspace.unable"));let r=n.cwd??t,s=R(r),a=eC.projects.find(e=>e.key===s);if(a?.hidden===!0)try{await tE([{key:s,path:r,hidden:!1}])}catch{}B(r),eq(!1)}catch{eK(b("workspace.unable"))}finally{eG(!1)}}},[tE,eJ,eC.projects,b]),t2=(0,s.useCallback)(()=>{eq(!0),eK(null)},[]),t4=(0,s.useCallback)(async()=>{let e=e2.trim();if(e&&!tr&&eZ){ts(!0),e5(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 e5(n.error??`HTTP ${t.status}`);e1(!1),e4(""),eX(!1),eY(t=>t?{...t,forCwd:n.path,worktrees:[...t.worktrees,{path:n.path,branch:e,isMain:!1}]}:t),B(n.path),t0(e=>e+1)}catch(e){e5(e instanceof Error?e.message:String(e))}finally{ts(!1)}}},[e2,tr,eZ]),t8=(0,s.useCallback)(async(e,t)=>{if(eZ&&!tr){ts(!0),e5(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 ti(e);e5(r.error??`HTTP ${n.status}`);return}ti(null),H===e&&B(eZ.projectRoot),t0(e=>e+1)}catch(e){e5(e instanceof Error?e.message:String(e))}finally{ts(!1)}}},[eZ,tr,H]);(0,s.useEffect)(()=>{let e=e=>{tl.current&&!tl.current.contains(e.target)&&(eS(null),eX(!1),e1(!1),e4(""),e5(null),ti(null),eU(""),ey(null))};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[]);let t5=(0,s.useCallback)(e=>{e.cwd&&B(e.cwd),n(e)},[n]),t6=(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]),t3=(0,s.useCallback)(async()=>{let e=eZ?.projectRoot,t=e6.trim();if(!e||!t||e7)return;e9(!0),tt(null);let r=tn.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)}`;tn.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),tn.current=null,e3(""),B(a.cwd),t0(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){tt(e instanceof Error?e.message:String(e))}finally{e9(!1)}},[eZ,e6,e7,n]),[t7,t9]=(0,s.useState)(!1),[ne,nt]=(0,s.useState)(null),nn=(0,s.useCallback)(async()=>{t9(!0),nt(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}`);t6(t.cwd)}catch(e){nt(b("sidebar.newScratchSessionFailed",{error:e instanceof Error?e.message:String(e)}))}finally{t9(!1)}},[t6,b]),nr=(0,s.useCallback)(e=>{en(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]),ns=tZ(H),na=null===ns?null:R(ns),ni=(0,s.useMemo)(()=>new Map(eC.projects.map(e=>[e.key,e])),[eC.projects]),nl=L(_);if(null!==ns){let e=R(ns);nl.some(t=>R(t)===e)||nl.unshift(ns)}let no=A(nl,eC.projects),nc=no.filter(e=>eE||!ni.get(R(e))?.hidden),nd=no.some(e=>ni.get(R(e))?.hidden),nu=()=>{eS(null),eX(!1),e1(!1),e4(""),e5(null),ti(null),eU("")},nh=async(e,t)=>{nu();try{await tE([{key:R(e),path:e,hidden:t}]),t&&na&&na===R(e)&&B(null),t||no.some(t=>R(t)!==R(e)&&ni.get(R(t))?.hidden)||e$(!1)}catch{}},np=async e=>{if(td.current){td.current=!1,eP(null);return}let t=e_.trim();if(t===(ni.get(R(e))?.alias??""))return void eP(null);eD(null);try{await tE([{key:R(e),path:e,alias:t||null}]),eP(null)}catch{eD(b("sidebar.projectUpdateFailed"))}},nm=async(e,t)=>{if(Z)return;let n=nc.indexOf(e),r=n+t;if(n<0||r<0||r>=nc.length)return;let s=new Set(nc),a=no.map((e,t)=>s.has(e)?t:-1).filter(e=>e>=0),i=[...no],l=a[n],o=a[r];[i[l],i[o]]=[i[o],i[l]],nu();try{await tE(i.map((e,t)=>({key:R(e),path:e,order:t})))}catch{}},nf=new Map;for(let e of _){let t=e.projectRoot??e.cwd;if(!t)continue;let n=R(t),r=nf.get(n);r?r.push(e):nf.set(n,[e])}let ng=(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)),tm.has(t.id)&&s.running++,tv.has(t.id)&&s.unread++}return e},[_,tm,tv]),nx=Z.trim().toLowerCase(),nv=Z.length>0,ny=nc.flatMap(e=>{let t=e.replace(/[\\/]+$/,"").split(/[\\/]/).at(-1)||e,n=R(e),r=ni.get(n),s=r?.alias??t,a=(nf.get(n)??[]).slice().sort((e,t)=>{let n=Number(tb.has(t.id))-Number(tb.has(e.id));return 0!==n?n:t.modified.localeCompare(e.modified)});if(!nx)return[{project:e,key:n,name:s,sessions:a,hidden:r?.hidden===!0}];let i=s.toLowerCase().includes(nx)||t.toLowerCase().includes(nx),l=a.filter(e=>(e.name||e.firstMessage.slice(0,50)||e.id.slice(0,12)).toLowerCase().includes(nx));return i||0!==l.length?[{project:e,key:n,name:s,sessions:i?a:l,hidden:r?.hidden===!0}]:[]}),nb=[],nw=[];for(let e of ny){let t=e.key===na||(ng.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?nw.push(e):nb.push(e)}let nk={running:0,unread:0};for(let e of nw){let t=ng.get(e.key);t&&(nk.running+=t.running,nk.unread+=t.unread)}let nj=nv||eR,nS=[...nb.map(e=>({kind:"project",group:e})),...nw.length>0?[{kind:"temporary"}]:[],...nj?nw.map(e=>({kind:"project",group:e})):[]],nC=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))}(nS.flatMap(e=>"project"===e.kind?[e.group.name]:[])),nN=(0,s.useMemo)(()=>tk?_.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,tm,tk,tg)):[],[tk,tm,_,tg]),nT=tS&&null!==tk,[nI,nM]=(0,s.useState)(null),nE=(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})(nT?_.filter(e=>e.id===nI&&!tm.has(e.id)||nN.includes(e)):_,tm,new Date,w,b("navigator.priority"),tb,b("sidebar.pinned"),nT?1/0:void 0),[nI,w,tb,nN,nT,tm,_,b]),n$=(0,s.useMemo)(()=>{let e=new Set(nN.map(e=>e.id)),t=[],n=[],r=[],s=null,a=[];for(let i of nE)if("pinned"===i.key){let a=i.sessions.filter(s=>{if(tg.has(s.id))t.push(s);else if(tm.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)(tg.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},[nE,nN,tm,b,tg]),nR=(0,s.useCallback)(e=>{nM(e.id),t5(e)},[t5]),nL=!!(eZ?.isGit&&eZ.isTopLevel&&H&&ns===eZ.projectRoot),nA=eZ?.worktrees.find(e=>e.path===H)??eZ?.worktrees.find(e=>e.isMain),nP=(eZ?.worktrees.length??0)>=8,n_=nP&&eH.trim()?(eZ?.worktrees??[]).filter(e=>(e.branch??eu(e.path,q)).toLowerCase().includes(eH.trim().toLowerCase())):eZ?.worktrees??[],nF=es[w.startsWith("ko")?"ko":w.startsWith("zh")?"zh":"en"],nz=function(e){if(e&&"u">typeof sessionStorage)try{return JSON.parse(sessionStorage.getItem(`cuelo:worktree:${e}`)??"null")??void 0}catch{return}}(H),nW=(()=>{if(!tL)return[];let e="project"===tL.kind?nf.get(R(tL.project))??[]:nE.flatMap(e=>e.sessions),t=new Set;return e.filter(e=>!(e.transient||t.has(e.id))&&(t.add(e.id),!0))})(),nO=nW.filter(e=>!tm.has(e.id)),nD=e=>{let t=new Set;for(let n of e)n.transient||tm.has(n.id)||t.has(n.id)||t.add(n.id);return t.size},nH=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:[eB&&(0,r.jsx)(K?X:G,{busy:eJ,error:eV,onCancel:()=>{eq(!1),eK(null)},onSelect:e=>void t1(e)}),tL&&(0,r.jsx)(ev,{scope:tL,eligible:nO.length,runningExcluded:nW.length-nO.length,busy:tP,error:tF,onCancel:tW,onConfirm:()=>void tO(nO)}),(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)(ef,{}),(0,r.jsxs)("div",{style:{display:"flex",gap:12},children:[(0,r.jsx)("button",{className:"navigator-icon-action",onClick:()=>t6(),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${th?" is-success":""}`,onClick:()=>t$(!1,!0),style:{display:"flex",alignItems:"center",justifyContent:"center",background:th?"var(--success-soft)":"var(--bg-hover)",border:0,color:th?"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=>{th||(e.currentTarget.style.background="var(--bg-selected)",e.currentTarget.style.color="var(--accent)")},onMouseLeave:e=>{th||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text-muted)")},title:b("sidebar.refresh"),children:th?(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"})]})})]})]}),nL&&(0,r.jsxs)("form",{onSubmit:e=>{e.preventDefault(),t3()},style:{marginTop:8},children:[(0,r.jsx)("label",{htmlFor:"session-issue",style:{display:"block",fontSize:12,color:"var(--text-muted)"},children:nF.issueLabel}),(0,r.jsxs)("div",{style:{display:"flex",gap:4,marginTop:4},children:[(0,r.jsx)("input",{id:"session-issue",value:e6,disabled:e7,onChange:e=>{e3(e.target.value),tt(null)},placeholder:nF.issuePlaceholder,"aria-describedby":te?"session-issue-error":void 0,"aria-invalid":!!te,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:e7||!e6.trim(),title:nF.issueStart,"aria-label":nF.issueStart,style:{minWidth:32,padding:"4px 8px",border:0,borderRadius:"var(--radius-control)",background:"var(--bg-hover)",color:"var(--text)",cursor:e7?"wait":"pointer"},children:e7?"…":"↵"})]}),e7&&(0,r.jsx)("div",{role:"status",style:{fontSize:12},children:nF.issueBusy}),te&&(0,r.jsx)("div",{id:"session-issue-error",role:"alert",style:{fontSize:12,color:"var(--danger)",overflowWrap:"anywhere"},children:te})]}),(nz||nA&&!nA.isMain)&&(0,r.jsxs)("div",{role:"status",title:H??void 0,style:{marginTop:4,fontSize:12,color:"var(--text-muted)",overflowWrap:"anywhere"},children:[nz?.branch??nA?.branch,nz?.fallback&&(0,r.jsx)("div",{children:nF.fallbackBase.replace("{branch}",nz.base)}),nz?.missingSubdirectory&&(0,r.jsx)("div",{children:ea[w.startsWith("ko")?"ko":w.startsWith("zh")?"zh":"en"].replace("{path}",nz.missingSubdirectory)})]})]}),K&&!nH&&(0,r.jsx)("button",{type:"button",className:"navigator-cloud-project",onClick:t2,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:nH?y("translator.tab"):"projects"===g?b("sidebar.projects"):b("navigator.priority")}),(0,r.jsx)("span",{className:"navigator-mode-spacer"}),!nH&&"projects"===g&&(0,r.jsx)("button",{type:"button",onClick:()=>e$(e=>!e),disabled:!nd,title:b("sidebar.projectShowHidden"),"aria-label":b("sidebar.projectShowHidden"),"aria-pressed":eE,style:{display:"flex",alignItems:"center",justifyContent:"center",width:26,height:26,padding:0,border:"none",borderRadius:"var(--radius-control)",background:eE?"var(--bg-selected)":"transparent",color:eE?"var(--accent)":"var(--text-dim)",cursor:nd?"pointer":"default",opacity:nd?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"}),!eE&&(0,r.jsx)("path",{d:"m4 4 16 16"})]})}),!nH&&"projects"===g&&(0,r.jsx)("button",{className:"navigator-add-project",type:"button",onClick:t2,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"})]})})]}),nH&&m,!nH&&"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:Z,onChange:e=>Y(e.target.value),onKeyDown:e=>{"Escape"===e.key&&(e.preventDefault(),Y(""),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}})]}),!nH&&"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:[(z||!eI)&&(0,r.jsx)("div",{style:{padding:"12px 8px",color:"var(--text-muted)",fontSize:12},children:b("sidebar.loading")}),O&&(0,r.jsx)("div",{style:{padding:"10px 8px",color:"var(--danger)",fontSize:12},children:O}),eO&&(0,r.jsx)("div",{style:{padding:"10px 8px",color:"var(--danger)",fontSize:12},children:eO}),!z&&eI&&!O&&0===ny.length&&(0,r.jsx)("div",{style:{padding:"12px 8px",color:"var(--text-muted)",fontSize:12},children:nx?b("sidebar.noMatchingProjects"):b("sidebar.noSessions")}),!z&&eI&&!O&&nS.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":nj,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:nj?"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:nw.length}),eN(nk,b)]})},"navigator-temporary-projects");let{project:i,key:l,name:o,sessions:c,hidden:d}=t.group,u=l===na,h=nC.has(o.toLowerCase())&&eu((s=Math.max((n=i.trim().replace(/[\\/]+$/,"")).lastIndexOf("\\"),n.lastIndexOf("/")))<=0?"":n.slice(0,s),q)||null,p=!et.has(i)&&!nx,m=Q.has(i),f=eA===i,g=nc.indexOf(i),x=ez||nv||g<=0,v=ez||nv||g>=nc.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:ej===i?tl:void 0,onMouseEnter:()=>ey(i),onMouseLeave:()=>ey(e=>e===i&&ej!==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:()=>nr(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:tc,value:e_,onChange:e=>eF(e.target.value),onBlur:()=>void np(i),onKeyDown:e=>{"Enter"===e.key?(e.preventDefault(),e.currentTarget.blur()):"Escape"===e.key&&(e.preventDefault(),td.current=!0,eP(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}),eN(ng.get(l),b)]}),!k&&(0,r.jsx)("button",{type:"button",onClick:()=>t6(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:+(em===i),pointerEvents:em===i?"auto":"none",transition:"opacity 0.12s, background 0.12s, color 0.12s",flexShrink:0},onFocus:()=>ey(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:()=>{eS(ej===i?null:i),eX(!1),e1(!1),e5(null),u||B(i)},title:b("sidebar.projectActions"),"aria-label":b("sidebar.projectActions"),"aria-expanded":ej===i,style:{display:"flex",alignItems:"center",justifyContent:"center",width:26,height:26,marginRight:3,padding:0,border:"none",borderRadius:"var(--radius-control)",background:ej===i?"var(--bg-selected)":"transparent",color:u&&nA&&!nA.isMain?"var(--accent)":"var(--text-dim)",cursor:"pointer",opacity:k||em===i||ej===i?1:0,pointerEvents:k||em===i||ej===i?"auto":"none",transition:"opacity 0.12s, background 0.12s, color 0.12s"},onFocus:()=>ey(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)(ep,{open:ej===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:()=>{eS(null),t6(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")]}),nL&&eZ&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("button",{type:"button",onClick:()=>eX(e=>!e),title:nA?b("sidebar.switchWorktreeTitle",{path:nA.path}):b("sidebar.switchWorktree"),"aria-label":b("sidebar.worktrees"),"aria-expanded":eQ,style:{display:"flex",alignItems:"center",gap:8,width:"100%",minHeight:34,padding:"0 10px",border:"none",background:eQ?"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)(ep,{open:eQ,style:{position:"static",width:"auto",zIndex:100,background:"var(--bg)",border:"none",borderRadius:0,boxShadow:"none",boxSizing:"border-box",overflow:"hidden"},children:[nP&&(0,r.jsx)("div",{style:{padding:"6px 8px"},children:(0,r.jsx)("input",{value:eH,onChange:e=>eU(e.target.value),onKeyDown:e=>{"Escape"===e.key&&(eU(""),eX(!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:[n_.map(e=>{let t=e.path===H||e.isMain&&!eZ.worktrees.some(e=>e.path===H);return ta===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 t8(e.path,!0),disabled:tr,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:()=>ti(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),eX(!1),e5(null),eU("")},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)(eh,{text:e.branch??eu(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 t8(e.path,!1),disabled:tr,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)}),nP&&0===n_.length&&eH.trim()&&(0,r.jsx)("div",{style:{padding:"8px 10px",fontSize:11,color:"var(--text-dim)"},children:b("sidebar.noMatchingWorktrees")})]}),e0?(0,r.jsxs)("div",{style:{padding:"6px 8px"},children:[(0,r.jsx)("input",{ref:to,value:e2,onChange:e=>{e4(e.target.value),e5(null)},onKeyDown:e=>{"Enter"===e.key&&(e.preventDefault(),t4()),"Escape"===e.key&&(e1(!1),e4(""),e5(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 t4(),disabled:tr||!e2.trim(),style:{flex:1,padding:"4px 0",background:"var(--accent)",border:"none",borderRadius:"var(--radius-control)",color:"var(--bg)",fontSize:11,fontWeight:600,cursor:tr||!e2.trim()?"not-allowed":"pointer",opacity:tr||!e2.trim()?.65:1},children:tr?b("sidebar.creating"):b("sidebar.create")}),(0,r.jsx)("button",{onClick:()=>{e1(!1),e4(""),e5(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(),e1(!0),e5(null),setTimeout(()=>to.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")})]}),e8&&(0,r.jsx)("div",{style:{padding:"5px 10px 8px",color:"var(--danger)",fontSize:11,lineHeight:1.35,overflowWrap:"anywhere"},children:e8})]})]}),(0,r.jsxs)("button",{type:"button",disabled:ez,onClick:()=>{let e;return e=ni.get(R(i))?.alias??"",void(td.current=!1,eD(null),eF(e),eP(i),nu())},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(ni.get(R(i))?.alias?"sidebar.projectAliasEdit":"sidebar.projectAlias")]}),(0,r.jsxs)("button",{type:"button",disabled:x,title:nv?b("sidebar.projectMoveDisabledWhileFiltering"):void 0,onClick:()=>void nm(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:nv?b("sidebar.projectMoveDisabledWhileFiltering"):void 0,onClick:()=>void nm(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 nh(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===nD(nf.get(l)??[])||tP,(0,r.jsxs)("button",{type:"button",disabled:a,onClick:()=>{nu(),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)(ek,{node:t,selectedSessionId:e,runningSessionIds:tm,unreadSessionIds:tv,pinnedSessionIds:tb,onSelectSession:t5,onTogglePinnedSession:tq,onRenamed:t$,onSessionDeleted:tR,onSessionArchived:tU,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)})]}),!nH&&(0,r.jsx)(ew,{refreshKey:tD,selectedSessionId:e,onSelectSession:t5,onRestored:tU}),!nH&&"priority"===g&&(0,r.jsxs)("div",{id:"navigator-priority-panel",style:{flex:"1 1 auto",minHeight:80,overflowY:"auto",padding:"0 6px 10px"},children:[z&&(0,r.jsx)("div",{style:{padding:"12px 8px",color:"var(--text-muted)",fontSize:12},children:b("sidebar.loading")}),O&&(0,r.jsx)("div",{role:"alert",style:{padding:"10px 8px",color:"var(--danger)",fontSize:12},children:O}),!z&&!O&&(v=nD(nE.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:t7,onClick:()=>void nn(),title:b("sidebar.newScratchSessionTitle"),style:ed(t7,k),children:b("sidebar.newScratchSession")}),nE.length>0&&!nT&&(0,r.jsx)("button",{type:"button",disabled:0===v||tP,onClick:()=>{tz(null),tA({kind:"priority"})},style:ed(0===v||tP,k),children:b("sidebar.clearPriorityList")})]})),!z&&!O&&tk&&(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":nT,"aria-label":b("navigator.resultsToCheckCount",{count:nN.length}),title:b("navigator.resultsToCheckHint"),onClick:()=>{nM(null),tC(e=>!e)},style:{...ed(!1,k),display:"inline-flex",alignItems:"center",gap:6,background:nT?"var(--bg-selected)":"var(--bg-hover)",color:nT||nN.length>0?"var(--text)":"var(--text-muted)",fontWeight:nT?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:nN.length>0?"var(--seed-color-bg-neutral-inverted)":"var(--bg-subtle)",color:nN.length>0?"var(--seed-color-fg-neutral-inverted)":"var(--text-muted)",fontSize:11,fontVariantNumeric:"tabular-nums",lineHeight:"18px",textAlign:"center"},children:nN.length})]}),nN.some(e=>!tg.has(e.id))&&(0,r.jsx)("button",{type:"button",title:b("navigator.acknowledgeResultsHint"),onClick:()=>{nM(null),tj(e=>e&&function(e,t,n){let r=e;for(let e of t)r=M(r,e,n);return r}(e,nN,Date.now()))},style:ed(!1,k),children:b("navigator.acknowledgeResults")})]}),ne&&(0,r.jsx)("div",{role:"alert",style:{padding:"6px 8px",color:"var(--danger)",fontSize:12},children:ne}),!z&&!O&&0===nE.length&&(0,r.jsx)("div",{style:{padding:"12px 8px",color:"var(--text-muted)",fontSize:12},children:nT?b("navigator.resultsToCheckEmpty"):b("sidebar.noSessions")}),!z&&!O&&n$.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)(eb,{session:t,selected:t.id===e,running:tm.has(t.id),waiting:tg.has(t.id),unread:tv.has(t.id),pinned:tb.has(t.id),onSelect:nT?nR:t5,onTogglePin:tq},t.id))]},t.key))]})]})}function ev({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 ey({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 eb({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],{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)}n.d(t,{u0:()=>r})},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"}},29213:e=>{e.exports={view:"PluginLabPanel_view__Sot51",toolbar:"PluginLabPanel_toolbar__co_Uq",hint:"PluginLabPanel_hint__kb7Hq",body:"PluginLabPanel_body__T_QMu",message:"PluginLabPanel_message__QbEDh",errorText:"PluginLabPanel_errorText__EI47_",list:"PluginLabPanel_list__BnAn6",card:"PluginLabPanel_card__5479R",cardHead:"PluginLabPanel_cardHead__SCiZ3",titleBlock:"PluginLabPanel_titleBlock__zfcvo",titleLine:"PluginLabPanel_titleLine__OmG7U",name:"PluginLabPanel_name__t4Ea0",id:"PluginLabPanel_id__osclH",control:"PluginLabPanel_control___gzgN",switch:"PluginLabPanel_switch__m3agg",switchLabel:"PluginLabPanel_switchLabel__DGX6y",description:"PluginLabPanel_description__PfruO",enhancement:"PluginLabPanel_enhancement__TOHjM",enhancementHead:"PluginLabPanel_enhancementHead__sgewN",enhancementDate:"PluginLabPanel_enhancementDate__4YWB1",enhancementSummary:"PluginLabPanel_enhancementSummary__srTnj",tools:"PluginLabPanel_tools__raR8s",metaLabel:"PluginLabPanel_metaLabel__LY5ak",toolList:"PluginLabPanel_toolList___rd6_",tool:"PluginLabPanel_tool___AjRR",problem:"PluginLabPanel_problem__Sx4aQ",problemLabel:"PluginLabPanel_problemLabel__rBSUT",cardActions:"PluginLabPanel_cardActions__GI_Bb",stage:"PluginLabPanel_stage__1l0FR",frame:"PluginLabPanel_frame__sP_V0",status:"PluginLabPanel_status__BYiAs",lines:"PluginLabPanel_lines__ONctT",notice:"PluginLabPanel_notice__mn_vu"}},34292:e=>{e.exports={body:"MenuScan_body__N1gSP",pickers:"MenuScan_pickers__K7rHv",primary:"MenuScan_primary__aMEtr",secondary:"MenuScan_secondary__nV23S",hiddenInput:"MenuScan_hiddenInput__qx7P_",avoid:"MenuScan_avoid__iazt8",hint:"MenuScan_hint__Jz4C9",status:"MenuScan_status__CnA_N",error:"MenuScan_error__CgwsP",summary:"MenuScan_summary__b1ZtT",signLine:"MenuScan_signLine__f_kUU",rescan:"MenuScan_rescan__Cdw4T",list:"MenuScan_list__sLZlP",row:"MenuScan_row__Hh2pX",warning:"MenuScan_warning__0eyVj",pick:"MenuScan_pick__wMRMv",main:"MenuScan_main__P3_Xp",translation:"MenuScan_translation__KT9aS",original:"MenuScan_original__yKqtc",description:"MenuScan_description__ZPvqQ",tags:"MenuScan_tags__VjkJ7",side:"MenuScan_side__zxLGs",price:"MenuScan_price__EzjRO",show:"MenuScan_show__fE8b0",footer:"MenuScan_footer__x2A7y",footerLabel:"MenuScan_footerLabel__2dbF_",footerTotal:"MenuScan_footerTotal__pWpMt"}},34817:e=>{e.exports={notice:"RepoSyncIndicator_notice__6q27O",body:"RepoSyncIndicator_body___uZUj",repo:"RepoSyncIndicator_repo__U0mga",actions:"RepoSyncIndicator_actions__OgFJN"}},40960:e=>{e.exports={active:"ComputerTakeoverControl_active__7430b"}},44440:(e,t,n)=>{"use strict";n.d(t,{AppShell:()=>ke});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"];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 A(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 P=/^<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(P);if(!t)return null;let[,n,,,r]=t;return r?`/skill:${n} ${r}`:`/skill:${n}`}var F=n(84183);let z=`(max-width: ${u.navigator-1}px)`;function W(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 O=W("(max-width: 640px)"),D=W(z);function H(){return!1}function U(){return(0,s.useSyncExternalStore)(O.subscribe,O.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 Z=n(21443),Y=n.n(Z);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",A=n||C,P=(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 z(e){if(e.preventDefault(),y.trim()&&!A){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),P()},[P]),(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 P();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,P]),!c)return null;if(u)return(0,r.jsx)(G,{onCancel:()=>h(!1),onSelect:t,busy:n,error:i});let W=f.filter(e=>`${e.fullName} ${e.description??""}`.toLowerCase().includes(x.toLowerCase())),O=T??i??p?.device?.error;return(0,a.createPortal)((0,r.jsx)("dialog",{ref:o,className:Y().dialog,"aria-labelledby":"cloud-project-title",onCancel:t=>{t.preventDefault(),A||e()},children:(0,r.jsxs)("form",{onSubmit:z,className:Y().form,children:[(0,r.jsxs)("header",{className:Y().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:Y().sources,children:[(0,r.jsx)("span",{className:Y().activeSource,children:l("cloudProjects.github")}),(0,r.jsx)("button",{type:"button",onClick:()=>h(!0),disabled:A,children:l("cloudProjects.serverFolder")})]}),(0,r.jsxs)("div",{className:Y().body,children:[(0,r.jsxs)("section",{className:Y().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:Y().secondary,onClick:()=>void P(),disabled:w||A,children:l("cloudProjects.refresh")}):(0,r.jsx)("button",{type:"button",className:Y().secondary,onClick:()=>void _(),disabled:w||j||L||A,children:j||L?l("cloudProjects.waiting"):l("cloudProjects.connect")})]}),L&&(0,r.jsxs)("div",{className:Y().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:Y().codeRow,children:[(0,r.jsx)("code",{children:p.device.code}),(0,r.jsx)("button",{type:"button",className:Y().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:Y().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:Y().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:A}),w?(0,r.jsx)("p",{role:"status",children:l("cloudProjects.loading")}):(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("ul",{className:Y().list,children:W.slice(0,$).map(e=>(0,r.jsx)("li",{children:(0,r.jsxs)("button",{type:"button",className:Y().repo,"aria-pressed":y===e.fullName,disabled:A,onClick:()=>b(e.fullName),children:[(0,r.jsxs)("span",{className:Y().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:Y().repoDescription,children:e.description})]})},e.fullName))}),!W.length&&(0,r.jsx)("p",{children:l("cloudProjects.empty")}),W.length>$&&(0,r.jsx)("button",{type:"button",className:Y().secondary,onClick:()=>R(e=>e+50),children:l("cloudProjects.more")})]})]}),(0,r.jsxs)("div",{className:Y().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:A,"aria-describedby":"cloud-repo-help"}),(0,r.jsx)("small",{id:"cloud-repo-help",children:l("cloudProjects.publicHelp")})]}),O&&(0,r.jsxs)("div",{className:Y().error,role:"alert",children:[(0,r.jsx)("strong",{children:l("cloudProjects.error")}),(0,r.jsx)("p",{children:O}),(0,r.jsx)("button",{type:"button",className:Y().secondary,onClick:()=>void P(),disabled:A,children:l("cloudProjects.refresh")})]}),C&&(0,r.jsx)("p",{role:"status",className:Y().progress,children:l("cloudProjects.openingHelp")})]}),(0,r.jsxs)("footer",{className:Y().footer,children:[(0,r.jsx)("button",{type:"button",className:Y().secondary,onClick:e,disabled:A,children:l("i18n.cancel")}),(0,r.jsx)("button",{type:"submit",className:Y().primary,disabled:A||!y.trim(),children:A?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.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.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":"This phone couldn't read it aloud. Check the phone's text-to-speech settings.","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="omp-web:unread-session-ids",eo="omp-web:pinned-session-ids",ec="omp-web:removed-projects";function ed(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 eu(e,t){return t&&e.startsWith(t)?"~"+e.slice(t.length):e}function eh({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 ep({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 em="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*";function ef(){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:em[Math.floor(Math.random()*em.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.341/19.1.0":"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 eg(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 ex({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,P]=(0,s.useState)([]),_=(0,s.useMemo)(()=>t&&!j.some(e=>e.id===t.id)?[t,...j]:j,[j,t]),[z,W]=(0,s.useState)(!0),[O,D]=(0,s.useState)(null),[H,B]=(0,s.useState)(null),[q,V]=(0,s.useState)(""),[K,J]=(0,s.useState)(!1),[Z,Y]=(0,s.useState)(""),[Q,ee]=(0,s.useState)(()=>new Set),[et,en]=(0,s.useState)(()=>new Set),[em,ey]=(0,s.useState)(null),[ej,eS]=(0,s.useState)(null),[eC,eT]=(0,s.useState)({version:1,projects:[]}),[eI,eM]=(0,s.useState)(!1),[eE,e$]=(0,s.useState)(!1),[eR,eL]=(0,s.useState)(!1),[eA,eP]=(0,s.useState)(null),[e_,eF]=(0,s.useState)(""),[ez,eW]=(0,s.useState)(!1),[eO,eD]=(0,s.useState)(null),[eH,eU]=(0,s.useState)(""),[eB,eq]=(0,s.useState)(!1),[eV,eK]=(0,s.useState)(null),[eJ,eG]=(0,s.useState)(!1),[eZ,eY]=(0,s.useState)(null),[eQ,eX]=(0,s.useState)(!1),[e0,e1]=(0,s.useState)(!1),[e2,e4]=(0,s.useState)(""),[e8,e5]=(0,s.useState)(null),[e6,e3]=(0,s.useState)(""),[e7,e9]=(0,s.useState)(!1),[te,tt]=(0,s.useState)(null),tn=(0,s.useRef)(null),[tr,ts]=(0,s.useState)(!1),[ta,ti]=(0,s.useState)(null),tl=(0,s.useRef)(null),to=(0,s.useRef)(null),tc=(0,s.useRef)(null),td=(0,s.useRef)(!1),tu=(0,s.useRef)(!1),[th,tp]=(0,s.useState)(!1),[tm,tf]=(0,s.useState)(()=>new Set),[tg,tx]=(0,s.useState)(()=>new Set),[tv,ty]=(0,s.useState)(()=>(function(){try{let e=window.localStorage.getItem(el);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}})()),[tb,tw]=(0,s.useState)(()=>new Set),[tk,tj]=(0,s.useState)(null),[tS,tC]=(0,s.useState)(!1),tN=(0,s.useRef)(new Set),tT=(0,s.useRef)(!1),tI=(0,s.useRef)(null);(0,s.useEffect)(()=>{tw(function(){try{let e=window.localStorage.getItem(eo);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{}tj(N(e,Date.now()));let t=e=>{if(e.key!==C||null===e.newValue)return;let t=N(e.newValue,Date.now());tj(e=>e?T(e,t):e)};return window.addEventListener("storage",t),()=>window.removeEventListener("storage",t)},[]);let tM=(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}`);eT(await e.json())}catch{eT({version:1,projects:[]})}finally{eM(!0)}},[]);(0,s.useEffect)(()=>{tM()},[tM,c]),(0,s.useEffect)(()=>{let e=null;try{e=window.localStorage.getItem(ec)}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 eg(n.map(e=>({key:R(e),path:e,hidden:!0})))}}catch{return}try{window.localStorage.removeItem(ec)}catch{}await tM()})()},[tM]);let tE=(0,s.useCallback)(async e=>{if(tu.current)throw Error("Project update in progress");tu.current=!0,eW(!0);try{await eg(e),await tM()}finally{tu.current=!1,eW(!1)}},[tM]);(0,s.useEffect)(()=>{eA&&tc.current?.select()},[eA]);let t$=(0,s.useCallback)(async(e=!1,t=!1)=>{try{e&&W(!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();P(r.sessions),tT.current||tf(new Set(r.runningSessionIds??[])),D(null),e||(tp(!0),tI.current&&clearTimeout(tI.current),tI.current=setTimeout(()=>tp(!1),2e3))}catch(e){D(String(e))}finally{e&&W(!1)}},[]),tR=(0,s.useCallback)(e=>{ty(t=>{if(!t.has(e))return t;let n=new Set(t);return n.delete(e),n}),tw(t=>{if(!t.has(e))return t;let n=new Set(t);return n.delete(e),n}),tj(t=>t&&$(t,[e])),d?.(e),t$()},[t$,d]),[tL,tA]=(0,s.useState)(null),[tP,t_]=(0,s.useState)(!1),[tF,tz]=(0,s.useState)(null),tW=(0,s.useCallback)(()=>{tP||(tA(null),tz(null))},[tP]),tO=(0,s.useCallback)(async e=>{t_(!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&&(tT.current=!0,tf(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(ty(n),tw(n),tj(e=>e&&$(e,t)),t))d?.(e)}(await t$(),t_(!1),r.length>0)?tz(b("sidebar.clearSessionsFailed",{count:r.length,names:r.join(", ")})):n.length>0||tA(null)},[t$,d,b]),[tD,tH]=(0,s.useState)(0),tU=(0,s.useCallback)(()=>{tH(e=>e+1),t$()},[t$]),tB=(0,s.useRef)(!1);(0,s.useEffect)(()=>{let e=!tB.current;tB.current=!0,t$(e,!e)},[t$,c]),(0,s.useEffect)(()=>{if("priority"!==g)return;let e=()=>{"visible"===document.visibilityState&&t$(!1,!0)};e();let t=window.setInterval(e,15e3);return()=>window.clearInterval(t)},[t$,g]),(0,s.useEffect)(()=>{x?.({running:tm.size,waiting:j.filter(e=>tg.has(e.id))})},[j,x,tm,tg]),(0,s.useEffect)(()=>{try{0===tv.size?window.localStorage.removeItem(el):window.localStorage.setItem(el,JSON.stringify([...tv]))}catch{}},[tv]),(0,s.useEffect)(()=>{try{0===tb.size?window.localStorage.removeItem(eo):window.localStorage.setItem(eo,JSON.stringify([...tb]))}catch{}},[tb]),(0,s.useEffect)(()=>{if(tk)try{var e,t,n;let r=window.localStorage;r.setItem(C,(e=r.getItem(C),t=Date.now(),JSON.stringify({since:(n=T(tk,N(e,t))).since,opened:n.opened})))}catch{}},[tk]);let tq=(0,s.useCallback)(e=>{tw(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;tT.current=!0,tf(new Set(r.runningSessionIds??[])),tx(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)}},[]),(0,s.useEffect)(()=>{let t=tN.current,n=[...t].filter(t=>!tm.has(t)&&t!==e),r=[...tm].filter(e=>!t.has(e));(n.length>0||r.length>0)&&ty(e=>{let t=new Set(e);return tm.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)&&t$(!1,!0),n.length>0&&p?.(),tN.current=tm},[tm,e,j,t$,p]),(0,s.useEffect)(()=>{e&&ty(t=>{if(!t.has(e))return t;let n=new Set(t);return n.delete(e),n})},[e]);let tV=e?_.find(t=>t.id===e):void 0,tK=tV?.conversationModified??tV?.modified,tJ=null!==tk;(0,s.useEffect)(()=>{e&&void 0!==tK&&tJ&&tj(t=>t&&M(t,{id:e,modified:tK},Date.now()))},[e,tK,tJ]),(0,s.useEffect)(()=>{fetch("/api/home").then(e=>e.json()).then(e=>{e.home&&V(e.home),J(!0===e.cloudProjects)}).catch(()=>{})},[]);let tG=(0,s.useRef)(!1),tZ=(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,_]),tY=(0,s.useRef)(null);(0,s.useEffect)(()=>{tY.current!==H&&(tY.current=H,h?.(H,tZ(H)))},[H,h,tZ]);let tQ=(0,s.useRef)(null);(0,s.useEffect)(()=>{u&&u!==tQ.current&&(tQ.current=u,B(u))},[u]);let[tX,t0]=(0,s.useState)(0);(0,s.useLayoutEffect)(()=>{if(!H)return void eY(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 eY(null);eY({forCwd:H,projectRoot:t.projectRoot,isGit:t.isGit??!1,isTopLevel:t.isTopLevel??!1,worktrees:t.worktrees??[]})}}).catch(()=>{e||eY(null)}),()=>{e=!0}},[H,tX,c]),(0,s.useEffect)(()=>{if(0!==j.length&&!l&&null===H){if(i&&!tG.current){tG.current=!0;let e=j.find(e=>e.id===i);if(e){B(e.cwd),n(e,!0);return}o?.()}if(!eI)return;let e=new Map(eC.projects.map(e=>[e.key,e])),t=A(j.length>0?L(j):[],eC.projects).filter(t=>!e.get(R(t))?.hidden);t.length>0&&B(t[0])}},[j,H,i,l,n,o,eC,eI]);let t1=(0,s.useCallback)(async e=>{let t=e.trim();if(t&&!eJ){eG(!0),eK(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 eK(n.error??b("workspace.unable"));let r=n.cwd??t,s=R(r),a=eC.projects.find(e=>e.key===s);if(a?.hidden===!0)try{await tE([{key:s,path:r,hidden:!1}])}catch{}B(r),eq(!1)}catch{eK(b("workspace.unable"))}finally{eG(!1)}}},[tE,eJ,eC.projects,b]),t2=(0,s.useCallback)(()=>{eq(!0),eK(null)},[]),t4=(0,s.useCallback)(async()=>{let e=e2.trim();if(e&&!tr&&eZ){ts(!0),e5(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 e5(n.error??`HTTP ${t.status}`);e1(!1),e4(""),eX(!1),eY(t=>t?{...t,forCwd:n.path,worktrees:[...t.worktrees,{path:n.path,branch:e,isMain:!1}]}:t),B(n.path),t0(e=>e+1)}catch(e){e5(e instanceof Error?e.message:String(e))}finally{ts(!1)}}},[e2,tr,eZ]),t8=(0,s.useCallback)(async(e,t)=>{if(eZ&&!tr){ts(!0),e5(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 ti(e);e5(r.error??`HTTP ${n.status}`);return}ti(null),H===e&&B(eZ.projectRoot),t0(e=>e+1)}catch(e){e5(e instanceof Error?e.message:String(e))}finally{ts(!1)}}},[eZ,tr,H]);(0,s.useEffect)(()=>{let e=e=>{tl.current&&!tl.current.contains(e.target)&&(eS(null),eX(!1),e1(!1),e4(""),e5(null),ti(null),eU(""),ey(null))};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[]);let t5=(0,s.useCallback)(e=>{e.cwd&&B(e.cwd),n(e)},[n]),t6=(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]),t3=(0,s.useCallback)(async()=>{let e=eZ?.projectRoot,t=e6.trim();if(!e||!t||e7)return;e9(!0),tt(null);let r=tn.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)}`;tn.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),tn.current=null,e3(""),B(a.cwd),t0(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){tt(e instanceof Error?e.message:String(e))}finally{e9(!1)}},[eZ,e6,e7,n]),[t7,t9]=(0,s.useState)(!1),[ne,nt]=(0,s.useState)(null),nn=(0,s.useCallback)(async()=>{t9(!0),nt(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}`);t6(t.cwd)}catch(e){nt(b("sidebar.newScratchSessionFailed",{error:e instanceof Error?e.message:String(e)}))}finally{t9(!1)}},[t6,b]),nr=(0,s.useCallback)(e=>{en(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]),ns=tZ(H),na=null===ns?null:R(ns),ni=(0,s.useMemo)(()=>new Map(eC.projects.map(e=>[e.key,e])),[eC.projects]),nl=L(_);if(null!==ns){let e=R(ns);nl.some(t=>R(t)===e)||nl.unshift(ns)}let no=A(nl,eC.projects),nc=no.filter(e=>eE||!ni.get(R(e))?.hidden),nd=no.some(e=>ni.get(R(e))?.hidden),nu=()=>{eS(null),eX(!1),e1(!1),e4(""),e5(null),ti(null),eU("")},nh=async(e,t)=>{nu();try{await tE([{key:R(e),path:e,hidden:t}]),t&&na&&na===R(e)&&B(null),t||no.some(t=>R(t)!==R(e)&&ni.get(R(t))?.hidden)||e$(!1)}catch{}},np=async e=>{if(td.current){td.current=!1,eP(null);return}let t=e_.trim();if(t===(ni.get(R(e))?.alias??""))return void eP(null);eD(null);try{await tE([{key:R(e),path:e,alias:t||null}]),eP(null)}catch{eD(b("sidebar.projectUpdateFailed"))}},nm=async(e,t)=>{if(Z)return;let n=nc.indexOf(e),r=n+t;if(n<0||r<0||r>=nc.length)return;let s=new Set(nc),a=no.map((e,t)=>s.has(e)?t:-1).filter(e=>e>=0),i=[...no],l=a[n],o=a[r];[i[l],i[o]]=[i[o],i[l]],nu();try{await tE(i.map((e,t)=>({key:R(e),path:e,order:t})))}catch{}},nf=new Map;for(let e of _){let t=e.projectRoot??e.cwd;if(!t)continue;let n=R(t),r=nf.get(n);r?r.push(e):nf.set(n,[e])}let ng=(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)),tm.has(t.id)&&s.running++,tv.has(t.id)&&s.unread++}return e},[_,tm,tv]),nx=Z.trim().toLowerCase(),nv=Z.length>0,ny=nc.flatMap(e=>{let t=e.replace(/[\\/]+$/,"").split(/[\\/]/).at(-1)||e,n=R(e),r=ni.get(n),s=r?.alias??t,a=(nf.get(n)??[]).slice().sort((e,t)=>{let n=Number(tb.has(t.id))-Number(tb.has(e.id));return 0!==n?n:t.modified.localeCompare(e.modified)});if(!nx)return[{project:e,key:n,name:s,sessions:a,hidden:r?.hidden===!0}];let i=s.toLowerCase().includes(nx)||t.toLowerCase().includes(nx),l=a.filter(e=>(e.name||e.firstMessage.slice(0,50)||e.id.slice(0,12)).toLowerCase().includes(nx));return i||0!==l.length?[{project:e,key:n,name:s,sessions:i?a:l,hidden:r?.hidden===!0}]:[]}),nb=[],nw=[];for(let e of ny){let t=e.key===na||(ng.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?nw.push(e):nb.push(e)}let nk={running:0,unread:0};for(let e of nw){let t=ng.get(e.key);t&&(nk.running+=t.running,nk.unread+=t.unread)}let nj=nv||eR,nS=[...nb.map(e=>({kind:"project",group:e})),...nw.length>0?[{kind:"temporary"}]:[],...nj?nw.map(e=>({kind:"project",group:e})):[]],nC=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))}(nS.flatMap(e=>"project"===e.kind?[e.group.name]:[])),nN=(0,s.useMemo)(()=>tk?_.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,tm,tk,tg)):[],[tk,tm,_,tg]),nT=tS&&null!==tk,[nI,nM]=(0,s.useState)(null),nE=(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})(nT?_.filter(e=>e.id===nI&&!tm.has(e.id)||nN.includes(e)):_,tm,new Date,w,b("navigator.priority"),tb,b("sidebar.pinned"),nT?1/0:void 0),[nI,w,tb,nN,nT,tm,_,b]),n$=(0,s.useMemo)(()=>{let e=new Set(nN.map(e=>e.id)),t=[],n=[],r=[],s=null,a=[];for(let i of nE)if("pinned"===i.key){let a=i.sessions.filter(s=>{if(tg.has(s.id))t.push(s);else if(tm.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)(tg.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},[nE,nN,tm,b,tg]),nR=(0,s.useCallback)(e=>{nM(e.id),t5(e)},[t5]),nL=!!(eZ?.isGit&&eZ.isTopLevel&&H&&ns===eZ.projectRoot),nA=eZ?.worktrees.find(e=>e.path===H)??eZ?.worktrees.find(e=>e.isMain),nP=(eZ?.worktrees.length??0)>=8,n_=nP&&eH.trim()?(eZ?.worktrees??[]).filter(e=>(e.branch??eu(e.path,q)).toLowerCase().includes(eH.trim().toLowerCase())):eZ?.worktrees??[],nF=es[w.startsWith("ko")?"ko":w.startsWith("zh")?"zh":"en"],nz=function(e){if(e&&"u">typeof sessionStorage)try{return JSON.parse(sessionStorage.getItem(`cuelo:worktree:${e}`)??"null")??void 0}catch{return}}(H),nW=(()=>{if(!tL)return[];let e="project"===tL.kind?nf.get(R(tL.project))??[]:nE.flatMap(e=>e.sessions),t=new Set;return e.filter(e=>!(e.transient||t.has(e.id))&&(t.add(e.id),!0))})(),nO=nW.filter(e=>!tm.has(e.id)),nD=e=>{let t=new Set;for(let n of e)n.transient||tm.has(n.id)||t.has(n.id)||t.add(n.id);return t.size},nH=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:[eB&&(0,r.jsx)(K?X:G,{busy:eJ,error:eV,onCancel:()=>{eq(!1),eK(null)},onSelect:e=>void t1(e)}),tL&&(0,r.jsx)(ev,{scope:tL,eligible:nO.length,runningExcluded:nW.length-nO.length,busy:tP,error:tF,onCancel:tW,onConfirm:()=>void tO(nO)}),(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)(ef,{}),(0,r.jsxs)("div",{style:{display:"flex",gap:12},children:[(0,r.jsx)("button",{className:"navigator-icon-action",onClick:()=>t6(),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${th?" is-success":""}`,onClick:()=>t$(!1,!0),style:{display:"flex",alignItems:"center",justifyContent:"center",background:th?"var(--success-soft)":"var(--bg-hover)",border:0,color:th?"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=>{th||(e.currentTarget.style.background="var(--bg-selected)",e.currentTarget.style.color="var(--accent)")},onMouseLeave:e=>{th||(e.currentTarget.style.background="var(--bg-hover)",e.currentTarget.style.color="var(--text-muted)")},title:b("sidebar.refresh"),children:th?(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"})]})})]})]}),nL&&(0,r.jsxs)("form",{onSubmit:e=>{e.preventDefault(),t3()},style:{marginTop:8},children:[(0,r.jsx)("label",{htmlFor:"session-issue",style:{display:"block",fontSize:12,color:"var(--text-muted)"},children:nF.issueLabel}),(0,r.jsxs)("div",{style:{display:"flex",gap:4,marginTop:4},children:[(0,r.jsx)("input",{id:"session-issue",value:e6,disabled:e7,onChange:e=>{e3(e.target.value),tt(null)},placeholder:nF.issuePlaceholder,"aria-describedby":te?"session-issue-error":void 0,"aria-invalid":!!te,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:e7||!e6.trim(),title:nF.issueStart,"aria-label":nF.issueStart,style:{minWidth:32,padding:"4px 8px",border:0,borderRadius:"var(--radius-control)",background:"var(--bg-hover)",color:"var(--text)",cursor:e7?"wait":"pointer"},children:e7?"…":"↵"})]}),e7&&(0,r.jsx)("div",{role:"status",style:{fontSize:12},children:nF.issueBusy}),te&&(0,r.jsx)("div",{id:"session-issue-error",role:"alert",style:{fontSize:12,color:"var(--danger)",overflowWrap:"anywhere"},children:te})]}),(nz||nA&&!nA.isMain)&&(0,r.jsxs)("div",{role:"status",title:H??void 0,style:{marginTop:4,fontSize:12,color:"var(--text-muted)",overflowWrap:"anywhere"},children:[nz?.branch??nA?.branch,nz?.fallback&&(0,r.jsx)("div",{children:nF.fallbackBase.replace("{branch}",nz.base)}),nz?.missingSubdirectory&&(0,r.jsx)("div",{children:ea[w.startsWith("ko")?"ko":w.startsWith("zh")?"zh":"en"].replace("{path}",nz.missingSubdirectory)})]})]}),K&&!nH&&(0,r.jsx)("button",{type:"button",className:"navigator-cloud-project",onClick:t2,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:nH?y("translator.tab"):"projects"===g?b("sidebar.projects"):b("navigator.priority")}),(0,r.jsx)("span",{className:"navigator-mode-spacer"}),!nH&&"projects"===g&&(0,r.jsx)("button",{type:"button",onClick:()=>e$(e=>!e),disabled:!nd,title:b("sidebar.projectShowHidden"),"aria-label":b("sidebar.projectShowHidden"),"aria-pressed":eE,style:{display:"flex",alignItems:"center",justifyContent:"center",width:26,height:26,padding:0,border:"none",borderRadius:"var(--radius-control)",background:eE?"var(--bg-selected)":"transparent",color:eE?"var(--accent)":"var(--text-dim)",cursor:nd?"pointer":"default",opacity:nd?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"}),!eE&&(0,r.jsx)("path",{d:"m4 4 16 16"})]})}),!nH&&"projects"===g&&(0,r.jsx)("button",{className:"navigator-add-project",type:"button",onClick:t2,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"})]})})]}),nH&&m,!nH&&"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:Z,onChange:e=>Y(e.target.value),onKeyDown:e=>{"Escape"===e.key&&(e.preventDefault(),Y(""),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}})]}),!nH&&"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:[(z||!eI)&&(0,r.jsx)("div",{style:{padding:"12px 8px",color:"var(--text-muted)",fontSize:12},children:b("sidebar.loading")}),O&&(0,r.jsx)("div",{style:{padding:"10px 8px",color:"var(--danger)",fontSize:12},children:O}),eO&&(0,r.jsx)("div",{style:{padding:"10px 8px",color:"var(--danger)",fontSize:12},children:eO}),!z&&eI&&!O&&0===ny.length&&(0,r.jsx)("div",{style:{padding:"12px 8px",color:"var(--text-muted)",fontSize:12},children:nx?b("sidebar.noMatchingProjects"):b("sidebar.noSessions")}),!z&&eI&&!O&&nS.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":nj,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:nj?"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:nw.length}),eN(nk,b)]})},"navigator-temporary-projects");let{project:i,key:l,name:o,sessions:c,hidden:d}=t.group,u=l===na,h=nC.has(o.toLowerCase())&&eu((s=Math.max((n=i.trim().replace(/[\\/]+$/,"")).lastIndexOf("\\"),n.lastIndexOf("/")))<=0?"":n.slice(0,s),q)||null,p=!et.has(i)&&!nx,m=Q.has(i),f=eA===i,g=nc.indexOf(i),x=ez||nv||g<=0,v=ez||nv||g>=nc.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:ej===i?tl:void 0,onMouseEnter:()=>ey(i),onMouseLeave:()=>ey(e=>e===i&&ej!==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:()=>nr(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:tc,value:e_,onChange:e=>eF(e.target.value),onBlur:()=>void np(i),onKeyDown:e=>{"Enter"===e.key?(e.preventDefault(),e.currentTarget.blur()):"Escape"===e.key&&(e.preventDefault(),td.current=!0,eP(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}),eN(ng.get(l),b)]}),!k&&(0,r.jsx)("button",{type:"button",onClick:()=>t6(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:+(em===i),pointerEvents:em===i?"auto":"none",transition:"opacity 0.12s, background 0.12s, color 0.12s",flexShrink:0},onFocus:()=>ey(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:()=>{eS(ej===i?null:i),eX(!1),e1(!1),e5(null),u||B(i)},title:b("sidebar.projectActions"),"aria-label":b("sidebar.projectActions"),"aria-expanded":ej===i,style:{display:"flex",alignItems:"center",justifyContent:"center",width:26,height:26,marginRight:3,padding:0,border:"none",borderRadius:"var(--radius-control)",background:ej===i?"var(--bg-selected)":"transparent",color:u&&nA&&!nA.isMain?"var(--accent)":"var(--text-dim)",cursor:"pointer",opacity:k||em===i||ej===i?1:0,pointerEvents:k||em===i||ej===i?"auto":"none",transition:"opacity 0.12s, background 0.12s, color 0.12s"},onFocus:()=>ey(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)(ep,{open:ej===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:()=>{eS(null),t6(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")]}),nL&&eZ&&(0,r.jsxs)(r.Fragment,{children:[(0,r.jsxs)("button",{type:"button",onClick:()=>eX(e=>!e),title:nA?b("sidebar.switchWorktreeTitle",{path:nA.path}):b("sidebar.switchWorktree"),"aria-label":b("sidebar.worktrees"),"aria-expanded":eQ,style:{display:"flex",alignItems:"center",gap:8,width:"100%",minHeight:34,padding:"0 10px",border:"none",background:eQ?"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)(ep,{open:eQ,style:{position:"static",width:"auto",zIndex:100,background:"var(--bg)",border:"none",borderRadius:0,boxShadow:"none",boxSizing:"border-box",overflow:"hidden"},children:[nP&&(0,r.jsx)("div",{style:{padding:"6px 8px"},children:(0,r.jsx)("input",{value:eH,onChange:e=>eU(e.target.value),onKeyDown:e=>{"Escape"===e.key&&(eU(""),eX(!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:[n_.map(e=>{let t=e.path===H||e.isMain&&!eZ.worktrees.some(e=>e.path===H);return ta===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 t8(e.path,!0),disabled:tr,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:()=>ti(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),eX(!1),e5(null),eU("")},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)(eh,{text:e.branch??eu(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 t8(e.path,!1),disabled:tr,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)}),nP&&0===n_.length&&eH.trim()&&(0,r.jsx)("div",{style:{padding:"8px 10px",fontSize:11,color:"var(--text-dim)"},children:b("sidebar.noMatchingWorktrees")})]}),e0?(0,r.jsxs)("div",{style:{padding:"6px 8px"},children:[(0,r.jsx)("input",{ref:to,value:e2,onChange:e=>{e4(e.target.value),e5(null)},onKeyDown:e=>{"Enter"===e.key&&(e.preventDefault(),t4()),"Escape"===e.key&&(e1(!1),e4(""),e5(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 t4(),disabled:tr||!e2.trim(),style:{flex:1,padding:"4px 0",background:"var(--accent)",border:"none",borderRadius:"var(--radius-control)",color:"var(--bg)",fontSize:11,fontWeight:600,cursor:tr||!e2.trim()?"not-allowed":"pointer",opacity:tr||!e2.trim()?.65:1},children:tr?b("sidebar.creating"):b("sidebar.create")}),(0,r.jsx)("button",{onClick:()=>{e1(!1),e4(""),e5(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(),e1(!0),e5(null),setTimeout(()=>to.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")})]}),e8&&(0,r.jsx)("div",{style:{padding:"5px 10px 8px",color:"var(--danger)",fontSize:11,lineHeight:1.35,overflowWrap:"anywhere"},children:e8})]})]}),(0,r.jsxs)("button",{type:"button",disabled:ez,onClick:()=>{let e;return e=ni.get(R(i))?.alias??"",void(td.current=!1,eD(null),eF(e),eP(i),nu())},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(ni.get(R(i))?.alias?"sidebar.projectAliasEdit":"sidebar.projectAlias")]}),(0,r.jsxs)("button",{type:"button",disabled:x,title:nv?b("sidebar.projectMoveDisabledWhileFiltering"):void 0,onClick:()=>void nm(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:nv?b("sidebar.projectMoveDisabledWhileFiltering"):void 0,onClick:()=>void nm(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 nh(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===nD(nf.get(l)??[])||tP,(0,r.jsxs)("button",{type:"button",disabled:a,onClick:()=>{nu(),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)(ek,{node:t,selectedSessionId:e,runningSessionIds:tm,unreadSessionIds:tv,pinnedSessionIds:tb,onSelectSession:t5,onTogglePinnedSession:tq,onRenamed:t$,onSessionDeleted:tR,onSessionArchived:tU,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)})]}),!nH&&(0,r.jsx)(ew,{refreshKey:tD,selectedSessionId:e,onSelectSession:t5,onRestored:tU}),!nH&&"priority"===g&&(0,r.jsxs)("div",{id:"navigator-priority-panel",style:{flex:"1 1 auto",minHeight:80,overflowY:"auto",padding:"0 6px 10px"},children:[z&&(0,r.jsx)("div",{style:{padding:"12px 8px",color:"var(--text-muted)",fontSize:12},children:b("sidebar.loading")}),O&&(0,r.jsx)("div",{role:"alert",style:{padding:"10px 8px",color:"var(--danger)",fontSize:12},children:O}),!z&&!O&&(v=nD(nE.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:t7,onClick:()=>void nn(),title:b("sidebar.newScratchSessionTitle"),style:ed(t7,k),children:b("sidebar.newScratchSession")}),nE.length>0&&!nT&&(0,r.jsx)("button",{type:"button",disabled:0===v||tP,onClick:()=>{tz(null),tA({kind:"priority"})},style:ed(0===v||tP,k),children:b("sidebar.clearPriorityList")})]})),!z&&!O&&tk&&(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":nT,"aria-label":b("navigator.resultsToCheckCount",{count:nN.length}),title:b("navigator.resultsToCheckHint"),onClick:()=>{nM(null),tC(e=>!e)},style:{...ed(!1,k),display:"inline-flex",alignItems:"center",gap:6,background:nT?"var(--bg-selected)":"var(--bg-hover)",color:nT||nN.length>0?"var(--text)":"var(--text-muted)",fontWeight:nT?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:nN.length>0?"var(--seed-color-bg-neutral-inverted)":"var(--bg-subtle)",color:nN.length>0?"var(--seed-color-fg-neutral-inverted)":"var(--text-muted)",fontSize:11,fontVariantNumeric:"tabular-nums",lineHeight:"18px",textAlign:"center"},children:nN.length})]}),nN.some(e=>!tg.has(e.id))&&(0,r.jsx)("button",{type:"button",title:b("navigator.acknowledgeResultsHint"),onClick:()=>{nM(null),tj(e=>e&&function(e,t,n){let r=e;for(let e of t)r=M(r,e,n);return r}(e,nN,Date.now()))},style:ed(!1,k),children:b("navigator.acknowledgeResults")})]}),ne&&(0,r.jsx)("div",{role:"alert",style:{padding:"6px 8px",color:"var(--danger)",fontSize:12},children:ne}),!z&&!O&&0===nE.length&&(0,r.jsx)("div",{style:{padding:"12px 8px",color:"var(--text-muted)",fontSize:12},children:nT?b("navigator.resultsToCheckEmpty"):b("sidebar.noSessions")}),!z&&!O&&n$.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)(eb,{session:t,selected:t.id===e,running:tm.has(t.id),waiting:tg.has(t.id),unread:tv.has(t.id),pinned:tb.has(t.id),onSelect:nT?nR:t5,onTogglePin:tq},t.id))]},t.key))]})]})}function ev({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 ey({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 eb({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)(ej,{}),n&&!s&&(0,r.jsx)(eS,{}),!n&&a&&(0,r.jsx)(eC,{})]}),(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)(ey,{filled:i})})]})}function ew({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 ek({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)(eT,{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)(ek,{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 ej(){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 eS(){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 eC(){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 eN(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 eT({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,b]=(0,s.useState)(!1),[w,k]=(0,s.useState)(""),[j,S]=(0,s.useState)(!1),[C,N]=(0,s.useState)(!1),T=(0,s.useRef)(null);(0,s.useEffect)(()=>{if(y){let e=requestAnimationFrame(()=>T.current?.select());return()=>cancelAnimationFrame(e)}},[y]);let I=_(e.firstMessage)??e.firstMessage,M=e.name||I.slice(0,50)||e.id.slice(0,12),E=(0,s.useCallback)(t=>{t.stopPropagation(),e.transient||(k(e.name||I.slice(0,50)||e.id.slice(0,12)),b(!0))},[e.name,e.transient,I,e.id]),$=(0,s.useCallback)(async()=>{let t=w.trim();if(b(!1),w!==M&&t!==(e.name??""))try{await fetch(`/api/sessions/${encodeURIComponent(e.id)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:t})}),c?.()}catch{}},[w,e.id,e.name,c,M]),R=(0,s.useCallback)(async()=>{if(!e.transient){S(!1),N(!0);try{await fetch(`/api/sessions/${encodeURIComponent(e.id)}`,{method:"DELETE"}),d?.(e.id)}catch{N(!1)}}},[e.id,e.transient,d]),L=(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]),A=(0,s.useCallback)(e=>{e.stopPropagation(),e.shiftKey?R():S(!0)},[R]),P=(0,s.useCallback)(e=>{e.stopPropagation(),R()},[R]),z=(0,s.useCallback)(e=>{e.stopPropagation(),S(!1)},[]),W=(0,s.useCallback)(t=>{(function(e,t=window){let n=new CustomEvent("pi-web:session-row-contextmenu",{cancelable:!0,detail:e});return!t.dispatchEvent(n)})({id:e.id,path:e.path,cwd:e.cwd,name:e.name,clientX:t.clientX,clientY:t.clientY,refresh:()=>{c?.()}})&&(t.preventDefault(),t.stopPropagation())},[c,e.cwd,e.id,e.name,e.path]);return(0,r.jsx)("div",{className:`navigator-session-row${t?" is-selected":""}${n?" is-running":""}${a?" is-unread":""}${j?" is-confirming":""}`,onClick:j||y?void 0:l,onContextMenu:j||y?void 0:W,onMouseEnter:()=>v(!0),onMouseLeave:()=>{v(!1)},style:{height:40,display:"flex",alignItems:"center",paddingLeft:h>0?10*h+8:8,paddingRight:4,cursor:j||y?"default":"pointer",background:t?"var(--bg-selected)":x?"var(--bg-hover)":"transparent",transition:"background 0.1s",opacity:C?.5:1,gap:4,overflow:"hidden"},children:j?(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("div",{style:{flex:1,minWidth:0,fontSize:12,color:"var(--text)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:g("sidebar.deleteSession",{title:M.slice(0,22)+(M.length>22?"…":"")})}),(0,r.jsxs)("div",{style:{display:"flex",gap:5,flexShrink:0},children:[(0,r.jsxs)("button",{onClick:P,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:z,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")})]})]}):y?(0,r.jsx)("input",{ref:T,value:w,onChange:e=>k(e.target.value),onBlur:$,onKeyDown:e=>{"Enter"===e.key&&$(),"Escape"===e.key&&b(!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:M,style:{display:"flex",alignItems:"center",gap:6,flex:1,minWidth:0,color:"var(--text)",fontSize:12.5,fontWeight:t?500:400,lineHeight:1.35,padding:0,border:"none",background:"transparent",fontFamily:"inherit",textAlign:"left",cursor:"pointer"},children:[(0,r.jsx)("span",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:M}),n&&(0,r.jsx)(eS,{}),!n&&a&&(0,r.jsx)(eC,{}),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"})})}),!e.transient&&(0,r.jsxs)("div",{style:{display:"flex",gap:4,flexShrink:0},children:[(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)(ey,{filled:i})}),(0,r.jsx)("button",{className:"navigator-session-action",onClick:E,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:L,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:A,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"})]})})]})]})})}let eI=/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~]|\][^\x07]*(?:\x07|\x1B\\))/g,eM=/^\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~]|\][^\x07]*(?:\x07|\x1B\\))/,eE=/\x1B\[([0-9;]*)m/g,e$=/\x1B_pi:c\x07/g,eR=["#1f2937","#dc2626","#16a34a","#d97706","#2563eb","#9333ea","#0891b2","#6b7280"],eL=["#9ca3af","#ef4444","#22c55e","#f59e0b","#3b82f6","#a855f7","#06b6d4","#e5e7eb"];function eA(e){return e.replace(e$,"").replace(eI,"")}function eP(e){let t=[],n=0;for(;n<e.length;){if(27===e.charCodeAt(n)){let t=e.slice(n).match(eM);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 e_(e,t){let n=eP(e)[t];return n?e.slice(0,n.start)+e.slice(n.end):e}function eF(e){return eP(e)[0]?.char}function ez(e){let t=/^[┌├└╭╰][─┬┴┼]+[┐┤┘╮╯]$/,n=[];for(let r of e){let e=r.replace(e$,""),s=eA(e).trimEnd();if(t.test(s))continue;let a=e,i=eF(a);("│"===i||"┃"===i)&&" "===eF(a=e_(a,0))&&(a=e_(a,0));let l=function(e){let t=eP(e);for(let e=t.length-1;e>=0;e--)if(""!==t[e].char.trim())return e;return -1}(a),o=l>=0?eP(a)[l]?.char:void 0;("│"===o||"┃"===o)&&(a=e_(a,l)),n.push(function(e){let t=e;for(;;){let e=eP(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&&""===eA(n[0]).trim();)n.shift();for(;n.length>0&&""===eA(n[n.length-1]).trim();)n.pop();return n.length?n:e}function eW(e){let t,n=[],r={},s=0;for(eE.lastIndex=0;null!==(t=eE.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=eR[r-30];else if(r>=90&&r<=97)n.color=eL[r-90];else if(r>=40&&r<=47)n.backgroundColor=eR[r-40];else if(r>=100&&r<=107)n.backgroundColor=eL[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 eR[e];if(e>=8&&e<16)return eL[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 eO={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:""},eD={ArrowLeft:"\x1bb",ArrowRight:"\x1bf",ArrowUp:"\x1bp",ArrowDown:"\x1bn"},eH={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"},eU={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 eB(e){return(e.replace(/\\/g,"/").split("/").pop()??"").toLowerCase().split(".").pop()??""}function eq(e){return null!==(eH[eB(e)]??null)}function eV(e){let t;return null!==("pdf"===(t=eB(e))||"docx"===t?t:null)}function eK(e,t,n={}){let r={...e,content:t};return n.omitUsage&&(r.usage=void 0),r}function eJ(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 eG(e,t={}){return t.isStreaming||"error"!==e.stopReason?null:e.errorMessage?.trim()||"Unknown provider error"}function eZ(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 eY(e,t={}){let n=[];for(let r of function(e,t={}){return(e.content??[]).filter(e=>!eJ(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 eQ(e){return e.filter(e=>"toolCall"===e.type).length}let eX=/[\u3000-\u30ff\u3400-\u9fff\uf900-\ufaff\u{20000}-\u{2fa1f}\uac00-\ud7af]/u;function e0(e){let t=0,n=0;for(let r of e)eX.test(r)?t++:n++;return t+n/4}function e1(e){return"text"===e.type?e.text:"thinking"===e.type?e.thinking:"toolCall"===e.type?JSON.stringify(e.input??{})??"":null}function e2(e,t){if(!e)return e0(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-e0(e.text.slice(r))+e0(t.slice(r))}function e4(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 e8=/^\[[1-9]\d* tool result images? omitted from initial history payload(?:: [^\]\n]*)?, ~\d+ bytes\]$/;function e5(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"&&e8.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&&eq(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 e6=new Map,e3=new Map,e7="[한국어 번역]\n";function e9(e){return e.filter(e=>"text"===e.type&&"string"==typeof e.text).map(e=>e.text).join("\n")}function te(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 tt="command",tn="autolearn-saved";function tr(e){return"custom"===e.role&&(e.customType===tt||e.customType===tn&&!1!==e.display)}function ts(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 ta="local-command:";function ti(e){return e?.startsWith(ta)===!0}function tl(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&&ti(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 to(e){return"user"===e.role||"custom"===e.role&&"compaction"===e.customType}let tc={create:!0,update:!0};function td(e){return"string"==typeof e?e.replace(/\s+/g," ").trim():""}function tu(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 th(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 tp(e){try{return decodeURIComponent(e)}catch{return e}}function tm(e){return/^[a-zA-Z]:[\\/]/.test(e)||e.startsWith("\\\\")?e.replace(/\\/g,"/"):e}function tf(e){let t=tm(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 tg(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=tp(o),h=u.startsWith("\\\\"),p=tm(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=tp(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=`${tm(t).replace(/\/+$/,"")}/${p}`,d="relative"),!c)return null;let f=tf(c).replace(/:\d+(?::\d+)?$/,"");return"relative"===d&&n&&(r=tf(f).replace(/\/+$/,""),s=tf(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 tx(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 tf(n)}function tv(e){let t=e.toLowerCase();return"write"===t||t.startsWith("write_")||t.endsWith(".write")||t.endsWith("_write")}function ty(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 tb(e){if(!e)return null;let t=e.file_path??e.path;return"string"==typeof t&&t.length>0?t:null}function tw(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 tk(e,t,n=!1){let r=t.details,s=tb(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=>tw(e,n)).filter(e=>null!==e);let a=tw(r,n);return a?[a]:[]}function tj(e,t){let n=tb(e);return(t?tk(e,t,!0):n?[n]:[]).filter(tI)}function tS(e,t,n){let r=tj(e,t);return r.length>0&&r.every(e=>tT(e,n))}let tC=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])),tN=[/^\/(?: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 tT(e,t){let n=tx(e,t),r=t?tx(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=tC.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&&tN.some(e=>e.test(s))}function tI(e){return!!/^[a-zA-Z]:[\\/]/.test(e)||!/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//.test(e)}function tM(e,t,n){let r=new Set,s=[];for(let i of e){var a;if("toolCall"!==i.type||!(tv(a=i.toolName)||ty(a)))continue;let e=t?.get(i.toolCallId);if(e&&!e.isError)for(let t of tk(i.input,e)){if(!tI(t))continue;let e=tx(t,n);!(!e||tT(t,n))&&(r.has(e)||(r.add(e),s.push({filePath:e})))}}return s}function tE(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 t$(e){if(!Array.isArray(e))return null;let{phases:t,malformed:n}=tE(e);return n?null:t}function tR(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}=tE(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 tL(e){if(!e)return!1;let t=e.toLowerCase();return"todo"===t||t.endsWith(".todo")||t.endsWith("_todo")}function tA(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=t$(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||!tL(n.toolName))continue;let r=tR(n,t.get(n.toolCallId));if("unknown"!==r.kind)return r.phases}}return null}(e,t)??r)}function tP(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 t_(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,tP(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 tF(e){return/^[a-zA-Z]:[\\/]/.test(e)||e.startsWith("\\\\")?e.replace(/\\/g,"/"):e}function tz(e){return tF(e).split("/").filter(Boolean).map(encodeURIComponent).join("/")}function tW(e){let t=tF(e).replace(/\/+$/,"");return t.split("/").pop()??t}function tO(e,t){if(!t)return e;let n=tF(e),r=tF(t).replace(/\/$/,"");return n.startsWith(r+"/")?n.slice(r.length+1):e}var tD=n(65063),tH=n(7644),tU=n(32316),tB=n(88374),tq=n(63280),tV=n(94764),tK=n(63835),tJ=n(54152),tG=n(84678),tZ=n(98164);let tY={...tV.j,attributes:{...tV.j.attributes,code:[["className",/^language-./,"math-inline","math-display"]]},strip:[...tV.j.strip||[],"iframe","object","style","form"]};function tQ(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=>t0(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=tX(n,e+1,t,l);if(a){r.push(`${t}$$`,`${t}${s}`);for(let s=e+1;s<a.index;s++)r.push(t0(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=tX(n,e+1,t,l);if(s&&(s.glued||""!==t)){r.push(`${t}$$`);for(let a=e+1;a<s.index;a++)r.push(t0(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 tX(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 t0(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 t1={singleTilde:!1},t2=[[tJ.A,["yaml"]],[tG.A,t1],tZ.A],t4=[[tJ.A,["yaml"]],[tG.A,t1],tZ.A],t8=[tq.A,[tK.A,tY],[tB.A,{throwOnError:!1,strict:!1}]],t5=[tq.A,[tK.A,tY],[tB.A,{throwOnError:!1,strict:!1}]],t6="pi-theme",t3=["light","dark","auto"],t7={preference:"auto",theme:"light"},t9="omp-theme",ne=null,nt=0,nn=new Set,nr=null,ns=!1;function na(){return window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}function ni(e){return"auto"===e?na():e}let nl="--omp-md-";function no(e){let t=document.documentElement,n=ne?.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(nl)&&t.style.removeProperty(n)}if(n){for(let[e,r]of Object.entries(n.variables))e.startsWith(nl)&&t.style.setProperty(e,r);t.dataset.ompThemeName=n.name}try{localStorage.setItem(t9,e)}catch{}}function nc(){if(nr)return nr;let e=function(){try{let e=localStorage.getItem(t6);if("light"===e||"dark"===e||"auto"===e)return e;let t=localStorage.getItem(t9);if("light"===t||"dark"===t)return t}catch{}return"auto"}(),t=ni(e);return no(t),nr={preference:e,theme:t}}function nd(e,t,n){if(no(t),n)try{localStorage.setItem(t6,e)}catch{}nr={preference:e,theme:t},nn.forEach(e=>e())}function nu(){let e=nc();if("auto"!==e.preference)return;let t=na();t!==e.theme&&nd("auto",t,!1)}function nh(e){return nn.add(e),nc(),ns||!window.matchMedia||(window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change",nu),window.addEventListener("focus",nu),document.addEventListener("visibilitychange",()=>{"visible"===document.visibilityState&&nu()}),ns=!0),nu(),()=>{nn.delete(e)}}function np(){return nc()}function nm(){return t7}async function nf(e){let t=++nt,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===nt){ne=s;try{localStorage.setItem("omp-theme-config",JSON.stringify(ne))}catch{}no(nc().theme)}}function ng(e){let t=(0,s.useSyncExternalStore)(nh,np,nm);(0,s.useEffect)(()=>{e?.syncWithOmp&&nf(e.cwd).catch(()=>{})},[e?.cwd,e?.syncWithOmp]);let n=(0,s.useCallback)((e,t)=>{let n=ni(e),r=()=>{nd(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=nc().preference,r=t3.indexOf(t),t3[(r+1)%t3.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 nx(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 nv={...tH.vs,...Object.fromEntries(["url","symbol","number","boolean","variable","constant","inserted"].map(e=>[e,{...tH.vs[e],color:"var(--seed-color-palette-green-800)"}]))};function ny({code:e,isStreaming:t}){let{isDark:a}=ng(),{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)(nw,{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)(nb,{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 nb({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 nw=(0,s.memo)(function({code:e,lang:t,headerAction:n,isStreaming:a}){let{isDark:i}=ng(),{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:()=>{nx(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)(tD.A,{language:t||"text",style:i?tH.xJ:nv,showLineNumbers:!0,lineNumberStyle:{color:"var(--text-muted)",fontStyle:"normal"},customStyle:{margin:0,padding:"11px 13px",fontSize:12.5,lineHeight:1.62,borderRadius:0,background:"color-mix(in srgb, var(--bg) 92%, var(--bg-panel))"},codeTagProps:{style:{fontFamily:"var(--font-mono)"}},children:e})]})});function nk({children:e,className:t,isStreaming:n,cwd:a,onOpenFile:i}){let l=(0,s.useMemo)(()=>tQ(e),[e]),o=(0,s.useMemo)(()=>({code({className:e,children:t,...s}){let a=e?.replace("language-","").toLowerCase()??"",i=String(t);return e?.includes("language-")||i.includes("\n")?"mermaid"===a?(0,r.jsx)(ny,{code:i.replace(/\n$/,""),isStreaming:n}):(0,r.jsx)(nw,{code:i.replace(/\n$/,""),lang:a,isStreaming:n}):(0,r.jsx)("code",{className:"markdown-inline-code",...s,children:t})},pre:({children:e})=>(0,r.jsx)(r.Fragment,{children:e}),a({href:e,children:t,...n}){delete n.node;let s=i?tg(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?tg(e,a):null,i=s?`/api/files/${tz(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)(tU.oz,{remarkPlugins:t2,rehypePlugins:t8,components:o,children:l})})}function nj(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 nS=new Map,nC=new Set;function nN(){nC.forEach(e=>e())}function nT(e){return nC.add(e),()=>{nC.delete(e)}}function nI(e,t){return e&&t?`${e}\u0000${t}`:null}function nM(e){let t=!1;for(let n of e)t=nS.delete(n)||t;t&&nN()}var nE=n(54265);let n$=(0,s.createContext)(null);function nR(e,t,n){return Math.min(n,Math.max(t,e))}function nL(e,t,n){let r=t.width>0?n.width/t.width:0,s=t.height>0?n.height/t.height:0;return{x:nR((e.x-t.left)*r,0,n.width),y:nR((e.y-t.top)*s,0,n.height)}}function nA(e){let t=nR(Math.round(.004*Math.max(e.width,e.height)),2,12);return{inner:t,outer:2*t}}let nP="#e5191f",n_="#ffffff";function nF(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 nz(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 nW(e,t){let n=await createImageBitmap(e);try{let e={width:n.width,height:n.height},{inner:r,outer:s}=nA(e),a=Math.max(14,7*nA(e).inner),[i,l]=nz(e.width,e.height);l.drawImage(n,0,0),t.forEach((t,n)=>{let i=function(e,t){let{inner:n,outer:r}=nA(t),s=(n,r)=>{let s=nR(e.x-n,r,t.width-r),a=nR(e.y-n,r,t.height-r),i=nR(e.x+e.w+n,r,t.width-r);return{x:s,y:a,w:Math.max(0,i-s),h:Math.max(0,nR(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=n_,l.lineWidth=s,l.strokeRect(i.outer.x,i.outer.y,i.outer.w,i.outer.h),l.strokeStyle=nP,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=n_,l.fillRect(h-1,m-1,d+2,u+2),l.fillStyle=nP,l.fillRect(h,m,d,u),l.fillStyle=n_,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=nR(e.x-r,0,t.width),i=nR(e.y-s,0,t.height),l=nR(e.x+e.w+r,0,t.width);return{x:a,y:i,w:l-a,h:nR(e.y+e.h+s,0,t.height)-i}}(t,e),[s,a]=nz(r.w,r.h);return a.drawImage(n,r.x,r.y,r.w,r.h,0,0,r.w,r.h),nF(s)}));return{marked:await nF(i),crops:o}}finally{n.close()}}function nO({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=nR(Math.min(e.x,t.x),n.left,n.left+n.width),a=nR(Math.max(e.x,t.x),n.left,n.left+n.width),i=nR(Math.min(e.y,t.y),n.top,n.top+n.height),l=nR(Math.max(e.y,t.y),n.top,n.top+n.height);if(a-s<6||l-i<6)return null;let o=nL({x:s,y:i},n,r),c=nL({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)(nD,{region:e,natural:c,label:String(t+1),title:l(t+1)},`${t}-${e.x}-${e.y}`)),c&&h&&(0,r.jsx)(nD,{region:h,natural:c})]})}function nD({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 nH(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 nU(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 nB=/<(read-files|modified-files)>\s*([\s\S]*?)\s*<\/\1>/g,nq=/(?:\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 nV(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${Math.round(e/1e3)}k`:e.toLocaleString()}let nK={hideThinkingBlock:!1},nJ=new Set,nG=nK,nZ=0;function nY(e){return nJ.add(e),()=>{nJ.delete(e)}}function nQ(){return nG}function nX(){return nK}async function n0(e){let t=++nZ,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!==nZ||s.hideThinkingBlock!==nG.hideThinkingBlock&&(nG={hideThinkingBlock:!0===s.hideThinkingBlock},nJ.forEach(e=>e()))}function n1(){return(0,s.useSyncExternalStore)(nY,nQ,nX)}function n2(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 n4=["YUKI(유키)","ISANA(이사나)","MIO(미오)","RIN(린)","MITSU(미츠)","SHION(시온)"],n8={"YUKI(유키)":"yuki","ISANA(이사나)":"isana","MIO(미오)":"mio","RIN(린)":"rin","MITSU(미츠)":"mitsu","SHION(시온)":"shion"},n5=["approval","choice","done","failed","blocked","working"],n6={approval:"부름",choice:"물음",done:"기쁨",failed:"사과",blocked:"난처",working:"시작"},n3={approval:!1,choice:!1,done:!1,failed:!1,blocked:!1,working:!0},n7="/api/office-characters/",n9={voice:"/audio/completion/",sticker:"/stickers/"};function re(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(n6,e)?e:null}function rn(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 rr(e,t=n9){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=rn(s,t.voice),o=rn(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 n5){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 rs(e,t,n){let r=t&&Object.hasOwn(n8,t)?n8[t]:null;return r?e.get(r)?.get(n)??null:null}function ra(e,t,n){return e.get(t)?.get(n)??null}async function ri(e=fetch){try{let t=await e("/audio/completion/voices.json");if(!t.ok)return new Map;return rr(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 ro(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 rc(e,t,n,r){if(t&&("web6"!==t.provider||t.model!==rd))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!==rd))return{provider:n.provider,model:n.model,credentialId:n.credentialId}}return{provider:n,model:r,credentialId:void 0}}let rd="ChatGPT 6PRO",ru="/api/sidecars/resource";function rh(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 rp=[{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"}],rm=[{seed:3,alias:rp[3].alias,provider:"openai-codex",model:"gpt-6.2-astra",voice:"빠른 판단\xb7선명한 결론\xb7영리한 장난기",summonExample:"유키 불러와",switchExample:"유키로 교체해"},{seed:4,alias:rp[4].alias,provider:"hive",model:"deepseek-ai/deepseek-v4.1-flash-1017",voice:"호기심과 실행력\xb7생기 있는 관찰\xb7솔직함",summonExample:"이사나 불러와",switchExample:"이사나로 교체해"},{seed:0,alias:rp[0].alias,provider:"anthropic",model:"claude-opus-5-5",oauthPosition:0,voice:"조용한 집중\xb7날카로운 분석\xb7건조한 유머",summonExample:"린 불러와",switchExample:"린으로 교체해"},{seed:1,alias:rp[1].alias,provider:"anthropic",model:"claude-opus-5-5",oauthPosition:1,voice:"따뜻하고 세심함\xb7부드럽고 안정적인 설명",summonExample:"미오 불러와",switchExample:"미오로 교체해"},{seed:2,alias:rp[2].alias,provider:"hive",model:"zai-org/glm-5.3-flash",voice:"부지런한 배달\xb7통통 튀는 보고\xb7끈질긴 재도전",summonExample:"미츠 불러와",switchExample:"미츠로 교체해"},{seed:5,alias:rp[5].alias,provider:"web6",model:"gpt-6-pro",voice:"우아한 전략\xb7넓은 시야\xb7은근한 장난기",summonExample:"시온 불러와",switchExample:null,summonNote:"WEB6 상담으로 호출합니다.",switchNote:"SHION은 WEB6 상담 전용이라 Main으로 교체할 수 없습니다."}],rf=rm.filter(e=>null!==e.switchExample),rg={mode:"default",rosterAvailable:!1,seats:[]},rx=rg,rv=new Map,ry=new Map,rb=rm,rw=new Set,rk=null,rj=0,rS=null,rC=!1;function rN(e){let t="office"===e.mode?e.seats.filter(e=>rp.some(t=>t.alias===e.seat)&&!rp.some(t=>t.alias===e.alias)&&"MITSU(미츠)"!==e.seat):[];rj+=1;let n=JSON.stringify([e.mode,e.rosterAvailable,t]);if(n!==rS)for(let r of(rS=n,rx={...e,seats:t},ry=new Map([...rv=new Map(t.flatMap(e=>{let t=rp.findIndex(t=>t.alias===e.seat);return t>=0?[[t,e]]:[]}))].flatMap(([e,t])=>{let n=rp[e];return"provider"in n&&!("model"in n)?[[n.provider,{seed:e,alias:t.alias}]]:[]})),rb=0===rv.size?rm:rm.map(e=>{let t,n,r,s=rv.get(rp.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}),rw))r()}function rT(){return rx}function rI(e){return rw.add(e),()=>{rw.delete(e)}}async function rM(e=fetch){let t=rj;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!==rj)return!0;let{mode:s,rosterAvailable:a,seats:i}=r;return rN({mode:"office"===s?"office":"default",rosterAvailable:!0===a,seats:Array.isArray(i)?i:[]}),!0}catch{return!1}}let rE=new WeakMap;function r$(e){let t=rE.get(e);return t||(t=rr(e.manifest,{voice:n7,sticker:n7}),rE.set(e,t)),t}function rR(e){return e?rx.seats.find(t=>t.seat===e||t.alias===e)??null:null}function rL(e){return rx.seats.find(t=>t.seat===e)?.alias??e}let rA=rp.filter(e=>!("provider"in e)).length,rP=new Map(rp.flatMap((e,t)=>"provider"in e&&!("model"in e)?[[e.provider,t]]:[])),r_=new Map(rp.flatMap((e,t)=>"model"in e?[[`${e.provider}/${e.model}`,{seed:t,alias:e.alias}]]:[])),rF=new Map([...rP].map(([e,t])=>[e,{seed:t,alias:rp[t].alias}]));function rz(e,t){return void 0===t?null:r_.get(`${e}/${t}`)??null}function rW(e){return ry.get(e)??rF.get(e)??null}function rO(e){let t=e%rp.length;return rv.get(t)?.alias??rp[t].alias}function rD(e){let t=e%rp.length;return rv.get(t)?.faceUrl??`/avatars/${rp[t].file}`}function rH(e){return 0===e.length?"":1===e.length?"•••":2===e.length?`${e[0]}•••`:`${e[0]}•••${e[e.length-1]}`}function rU(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 rB(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 rH(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`${rH(e.slice(0,t))}@${0===s.length?"":`${s[0]}•••`}${a}`}(a):"",l=(n=e.provider,rP.get(n)??-1);if(l>=0)return{seed:l,alias:rO(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%rA,d=o<rA?rO(c):`${rO(c)}${o+1}`;return{seed:c,alias:d,masked:i,raw:a}})}class rq 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 rV(e,t){return`${ru}${e}${t?"?refresh=1":""}`}function rK(e,t,n=!1){return e instanceof rq?e:t?new rq("요청 시간이 초과되었습니다.","timeout",void 0,{cause:e}):n||e instanceof DOMException&&"AbortError"===e.name?new rq("요청이 취소되었습니다.","aborted",void 0,{cause:e}):new rq(e instanceof Error?e.message:String(e),"network",void 0,{cause:e})}function rJ(e,t){return null==e?{status:"error",data:null,error:t}:{status:"stale",data:e,error:t}}async function rG(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 rq("리소스 서버 응답이 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 rq(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 rK(e,a,s.signal.aborted)}finally{clearTimeout(n),t.signal?.removeEventListener("abort",i)}}async function rZ(e={}){try{let t=await rG(rV("/usage",!0===e.refresh),e);if(!t||!Array.isArray(t.reports))throw new rq("사용량 응답 형식이 올바르지 않습니다.","invalid-response");return{status:"fresh",data:t,error:null}}catch(t){return rJ(e.previous,rK(t,!1))}}async function rY(e,t={}){if(!e)return rJ(void 0,new rq("세션 id가 올바르지 않습니다.","invalid-response"));try{let n=await rG(`/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 rq("현재 계정 응답 형식이 올바르지 않습니다.","invalid-response");return{status:"fresh",data:n,error:null}}catch(e){return rJ(void 0,rK(e,!1))}}async function rQ(e={}){try{let t=await rG(rV("/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 rq("모델 집계 응답 형식이 올바르지 않습니다.","invalid-response");return{status:"fresh",data:t,error:null}}catch(t){return rJ(e.previous,rK(t,!1))}}async function rX(e={}){try{let t=await rG(`${ru}/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 rq("API 크레딧 응답 형식이 올바르지 않습니다.","invalid-response");return{status:"fresh",data:t,error:null}}catch(t){return rJ(e.previous,rK(t,!1))}}async function r0(e,t,n={}){await r2({wallet:e,value:t},n)}async function r1(e,t,n={}){await r2({kind:"balance",wallet:e,value:t},n)}async function r2(e,t){await rG(`${ru}/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 r4(e,t,n={}){if(!Number.isSafeInteger(e)||e<=0)throw new rq("credential id가 올바르지 않습니다.","invalid-response");let r=await rG(`${ru}/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 rq("계정 전환 응답 형식이 올바르지 않습니다.","invalid-response");return r}async function r8(e,t,n={}){if(!Number.isSafeInteger(e)||e<=0)throw new rq("credential id가 올바르지 않습니다.","invalid-response");if(!t)throw new rq("credit id가 올바르지 않습니다.","invalid-response");let r=await rG(`${ru}/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 rq("리셋 사용 응답 형식이 올바르지 않습니다.","invalid-response");return r}function r5(e,t){if(e.has(t))return null;e.add(t);let n=!1;return()=>{n||(n=!0,e.delete(t))}}let r6={faces:new Map,pins:new Map},r3=[],r7=r6,r9=null,se=r3,st=new Map,sn=new Set;function sr(e){let t=(sn.add(e),()=>{sn.delete(e)}),n=rI(e);return()=>{t(),n()}}function ss(e){r7=e,sn.forEach(e=>e())}function sa(e){return Number.isSafeInteger(e)&&e>0}function si(e,t){return`${e}:${t}`}function sl(e){let t=e??r3;se=t;let n=t.map(e=>[e.provider,e.credentialId??"",e.oauthPosition??"",e.metadata?.accountId??"",e.metadata?.email??""].join("\0")).join("|");if(n===r9)return;r9=n;let r=rB(t),s=new Map;t.forEach((e,t)=>{let n=e.credentialId;if(!sa(n))return;let a=si(e.provider,n);s.has(a)||s.set(a,{seed:r[t].seed,alias:r[t].alias})}),ss({faces:s,pins:r7.pins})}function so(e,t,n,r){if(!t)return null;let s=rz(t,r);if(s)return s;if(sa(n)){let e=r7.faces.get(si(t,n));if(e)return e}let a=e?r7.pins.get(e):void 0;if(a&&a.provider===t){let e=r7.faces.get(si(t,a.credentialId));if(e)return e}return rW(t)??("anthropic"!==t||sa(n)||a?.provider===t?null:rb.find(e=>e.provider===t&&0===e.oauthPosition)??null)}async function sc(e,t,n,r){if(!t||sa(n)||rW(t))return so(e,t,n,r);try{let{data:n}=await rY(e);if(n?.state==="resolved"&&n.provider===t&&sa(n.credentialId)){let r=new Map(r7.pins);r.set(e,{provider:t,credentialId:n.credentialId,observedAt:Date.now()}),ss({faces:r7.faces,pins:r})}}catch{}return so(e,t,void 0,r)}function sd(e,t,n,r){let a=!!t&&!sa(n)&&!!e;return(0,s.useEffect)(()=>{a&&e&&t&&function(e,t){let n=Date.now(),r=r7.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),rY(e).then(t=>{let n=t.data;if(!n||"resolved"!==n.state)return;let{provider:r,credentialId:s}=n;if("string"!=typeof r||""===r||!sa(s))return;let a=new Map(r7.pins);a.set(e,{provider:r,credentialId:s,observedAt:Date.now()}),ss({faces:r7.faces,pins:a})}).catch(()=>{}))}(e,t)},[a,e,t]),(0,s.useSyncExternalStore)(sr,()=>so(e,t,n,r),()=>null)}function su(){return(0,s.useEffect)(()=>{if(!rC){rC=!0;let e=()=>{"visible"===document.visibilityState&&rM()};window.addEventListener("focus",e),document.addEventListener("visibilitychange",e)}null===rk&&(rk=rM().then(e=>{e||(rk=null)}))},[]),(0,s.useSyncExternalStore)(rI,rT,()=>rg)}rI(()=>{r9=null,sl(se)});let sh={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 sp(){let{locale:e}=(0,F.s)();return{st:(0,s.useCallback)((t,n)=>(0,et.u0)(e,t,sh,n),[e]),locale:e}}function sm({seed:e,size:t,provider:n}){su();let a=rD(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:rO(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":rO(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)(sf,{seed:e,provider:n,onClose:()=>d(!1)})]})}function sf({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=rO(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:rD(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:rU(t)}):null]}),(0,r.jsx)("button",{type:"button",className:"account-avatar-close",onClick:n,children:i("i18n.close")})]}),document.body)}function sg(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=sx(d.slice(4));continue}if(d.startsWith("+++ ")){u(),r={oldPath:t,newPath:sx(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 sx(e){return e.split(" ")[0].trim()}function sv({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?[]:tP(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 sy="/icons/catppuccin";function sb({name:e,size:t=14}){let n={width:t,height:t,"--catppuccin-icon-light":`url(${sy}/latte/${e}.svg)`,"--catppuccin-icon-dark":`url(${sy}/mocha/${e}.svg)`};return(0,r.jsx)("span",{"aria-hidden":"true",className:"catppuccin-file-icon",style:n})}function sw({size:e=14,open:t=!1}){return(0,r.jsx)(sb,{name:t?"_folder_open":"_folder",size:e})}function sk({size:e=14}){return(0,r.jsx)(sb,{name:"_file",size:e})}let sj={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 sS(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)(sb,{name:s,size:t});let a=sj[n.split(".").pop()??""];return a?(0,r.jsx)(sb,{name:a,size:t}):(0,r.jsx)(sk,{size:t})}function sC({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=tW(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:[sS(s,12),(0,r.jsx)("span",{children:s})]},e)})})}let sN=/^att_[0-9a-f]{32}$/,sT=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function sI(e){return"string"==typeof e&&sN.test(e)}function sM(e){return"string"==typeof e&&sT.test(e)}class sE extends Error{constructor(e,t){super(t),this.code=e,this.name="DocumentAttachmentError"}}let s$={markdown:"text/markdown",text:"text/plain",pdf:"application/pdf"},sR={".txt":!0,".csv":!0,".tsv":!0,".json":!0,".log":!0},sL={"text/plain":!0,"text/csv":!0,"text/tab-separated-values":!0,"application/json":!0,"text/json":!0};function sA(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&&sR[t.slice(n)])return"text";let r=e.type.toLocaleLowerCase().split(";",1)[0]?.trim();return"text/markdown"===r?"markdown":"application/pdf"===r?"pdf":r&&sL[r]?"text":null}let sP={".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 s_(e){let t=e.name.toLocaleLowerCase(),n=t.lastIndexOf("."),r=n>0?sP[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 sF(e,t){try{let n=new TextDecoder(e,{fatal:!0}).decode(t);return n.includes("\0")?null:n}catch{return null}}function sz(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,...sI(s.attachmentId)?{attachmentId:s.attachmentId}:{}}),n+=s.size,r+=s.text.length))}}return t}async function sW(e){let t,n=sA(e);if(!n)throw new sE("unsupported",`Unsupported document type: ${e.name}`);if(e.size>8388608)throw new sE("file_too_large",`${e.name} exceeds the document size limit`);if("pdf"===n)t=await sG(e);else{try{t=await e.text()}catch(e){throw new sE("read_failed",e instanceof Error?e.message:String(e))}sZ(t)}return{name:e.name,mimeType:s$[n],size:e.size,text:t}}function sO(e,t){let n=sz(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=`${sY}${JSON.stringify(r)}${sQ}
@@ -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=e6.get(n);if(void 0!==r)return Promise.resolve(r);let s=e3.get(n);if(s)return s;let a=fetch(e4(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 e6.set(n,r),r}).catch(()=>0).finally(()=>e3.delete(n));return e3.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:e4(e,t,s),alt:"",loading:"lazy",draggable:!1,onError:()=>d(e=>new Set(e).add(s))})},s)),null!==l&&(0,r.jsx)(ao,{src:e4(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 ao({src:e,fileName:t,onClose:n}){let{t:i}=(0,F.s)(),o=(0,s.useContext)(n$),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 nW(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)(nO,{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 ac({block:e,isStreaming:t,cwd:n,onOpenFile:s}){return(0,r.jsx)(s8,{isStreaming:t,cwd:n,onOpenFile:s,children:e.text})}function ad({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=s4.get(r);if(s)return s4.delete(r),s4.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 s4.delete(r),e});if(s4.set(r,a),s4.size>100){let e=s4.keys().next().value;e&&s4.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)(nk,{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 au({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=(l=t?null:nI(i,e.toolCallId),(0,s.useSyncExternalStore)(nT,()=>l?nS.get(l)??null:null,()=>null)),f=e.toolName.toLowerCase(),g=JSON.stringify(e.input,null,2),x="todo"===f||f.endsWith(".todo")||f.endsWith("_todo"),v="bash"===f||f.startsWith("bash ")||f.endsWith(".bash")||f.endsWith("_bash"),y=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,b=x?"unknown"===(o=tR(e,t)).kind||0===o.phases.length?null:o.phases:null,w=y?y.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,k=t?t.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n"):null,j=null!==k&&("(no output)"===k.trim()||""===k.trim()),S=t?nU(t):null,C=t?t.isError||null!==S&&0!==S?"failed":"done":"running",N="failed"===C,T=h??N;if(x&&b)return(0,r.jsx)(av,{phases:b});let I=v&&"string"==typeof e.input.command?e.input.command:"",M=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),E=null!==M&&M.rows.length>0?M:null,$=!!(b||y||E),R=v?I.split(/\r?\n/,1)[0]??"":M?.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,b),L=!v&&/^\S+$/.test(R)&&/[\\/]/.test(R),A=w?c("toolRun.diffStats",{added:w.added,removed:w.removed}):"";return(0,r.jsxs)("div",{className:`tool-call-card ${N?"is-error":"running"===C?"is-running":"is-done"}${v?" is-shell":""}`,"aria-busy":"running"===C||void 0,style:{overflow:"hidden",fontSize:12},children:[(0,r.jsxs)("button",{type:"button",className:"tool-call-header",onClick:()=>p(!T),"aria-expanded":T,"aria-controls":T?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)(ag,{toolName:e.toolName}),(0,r.jsx)("span",{className:"tool-call-name",children:v?"bash":e.toolName}),v&&f.includes("(local)")&&(0,r.jsx)("span",{className:"shell-local-label",children:"local"}),(0,r.jsx)("span",{className:`tool-call-target${L?" is-path":""}`,title:v?I:R,children:L?(0,r.jsx)("bdi",{dir:"ltr",children:R}):R}),w&&(0,r.jsxs)("span",{className:"tool-call-diffstats",title:A,"aria-label":A,children:[(0,r.jsxs)("span",{style:{color:"var(--success)"},children:["+",w.added]}),(0,r.jsxs)("span",{style:{color:"var(--danger)"},children:["−",w.removed]})]}),(0,r.jsx)(ap,{state:C,duration:n,exitCode:S,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:T?"rotate(180deg)":"none",transition:"transform 0.15s"},children:(0,r.jsx)("polyline",{points:"2 3.5 5 6.5 8 3.5"})})]}),"running"===C&&m&&(0,r.jsx)("div",{className:"tool-call-progress",title:m,style:{padding:"0 10px 6px 29px",color:"var(--text-dim)",fontSize:11,lineHeight:1.4,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:m}),T&&(0,r.jsx)("div",{id:d,className:"tool-call-body",children:v?(0,r.jsx)(ay,{command:I,output:k??"",pending:!t,isError:N}):(0,r.jsxs)(r.Fragment,{children:[y&&(0,r.jsx)("div",{style:{maxHeight:560,overflowY:"auto",overflowX:"hidden"},children:(0,r.jsx)(ab,{diff:y})}),t&&N&&(0,r.jsx)(aC,{text:k??"",isEmpty:j,isError:!0}),E&&!N&&(0,r.jsx)(ah,{summary:E}),!$&&(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:g}),t&&!$&&!N&&(0,r.jsx)(aC,{text:k??"",isEmpty:j,isError:!1})]})})]})}function ah({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 ap({state:e,duration:t,exitCode:n,startedAt:s}){let{t:a}=(0,F.s)();return"running"===e?(0,r.jsx)(am,{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)(nE.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 am({startedAt:e}){let{t}=(0,F.s)(),n=nj(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 af(e,t){let n=e.trim().toLowerCase();return n===t||n.endsWith(`.${t}`)||n.endsWith(`_${t}`)||n.split(/[.\s:_-]+/).includes(t)}function ag({toolName:e}){let t,n=(t=e.trim().toLowerCase()).includes("str_replace")||t.includes("replace_editor")||af(t,"edit")?"edit":af(t,"read")||af(t,"cat")?"read":af(t,"write")||af(t,"save")?"write":af(t,"glob")||af(t,"find")?"glob":af(t,"grep")||af(t,"search")?"grep":af(t,"bash")||af(t,"shell")||af(t,"exec")?"bash":af(t,"todo")?"todo":af(t,"eval")?"eval":af(t,"task")||af(t,"agent")?"task":af(t,"browser")||af(t,"web_search")||af(t,"fetch")?"browser":af(t,"image")||af(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)(ax,{kind:n})})})}function ax({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 av({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)(sv,{task:e},`${e.content}-${t}`))]},`${t.name}-${n}`))})]})}function ay({command:e,output:t,pending:n,isError:s}){let{isDark:a}=ng(),{t:i}=(0,F.s)(),l=ez(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)(tD.A,{className:"shell-command-code",language:"bash",style:a?tH.xJ:tH.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=eA(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:[eW(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 ab({diff:e}){return(0,r.jsx)("div",{style:{background:"var(--bg)"},children:(0,r.jsx)(aw,{text:e.text})})}function aw({text:e}){let{t}=(0,F.s)(),n=(0,s.useMemo)(()=>sg(e),[e]);if(!n)return(0,r.jsx)(aS,{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)(ak,{title:e.oldPath||t("i18n.before"),side:"left"}),(0,r.jsx)(ak,{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)(aj,{cell:e.left,side:"left"}),(0,r.jsx)(aj,{cell:e.right,side:"right"})]},t))})]},n))})}function ak({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 aj({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 aS({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 aC({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 aN({message:e}){let{t}=(0,F.s)(),n=aE(e.content),a=(0,s.useMemo)(()=>{let e,t,r,s,a;return e=[],t=[],r=n.match(nq),s=r?.[1]??"",a=r?.index===void 0?n:n.slice(0,r.index),s.replace(nB,(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=s7(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:nV(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)(nk,{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)(aT,{readFiles:a.readFiles,modifiedFiles:a.modifiedFiles})]})]})})}function aT({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)(aI,{title:n("i18n.modifiedFiles"),files:t}),e.length>0&&(0,r.jsx)(aI,{title:n("i18n.readFiles"),files:e})]})}function aI({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 aM({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=aE(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=s7(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=a$(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)(nk,{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:()=>{nx(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 aE(e){return"string"==typeof e?e:e.filter(e=>"text"===e.type).map(e=>e.text).join("\n")}function a$(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 aR({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)(au,{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 aL=/^[\t ]*(?:WORK_CLASS|PURPOSE|BLOCKS_PRIMARY|PRIMARY_DELIVERABLE|OWNED_PATHS|FINDING_ID)[\t ]*:[^\r\n]*$/i;function aA(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(!aL.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 aP(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(aA).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 a_(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 aF extends Error{constructor(e,t,n){super(t),this.kind=e,this.status=n,this.name="SubagentClientError"}}async function az(e){try{return await e.json()}catch{throw new aF("invalid-response","응답 JSON을 해석할 수 없습니다.",e.status)}}function aW(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 aO(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 aD(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 aH(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 aU(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 aF(r,"sidecar-unreachable"===r?"Subagent 기록 사이드카(30144)에 연결할 수 없습니다.":"실시간 Subagent 상태에 연결할 수 없습니다.")}let a=await az(s);if(!s.ok)throw new aF("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 aF("invalid-response","실시간 Subagent 응답이 올바르지 않습니다.");if("string"==typeof r.error&&r.error)throw new aF("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(aD)))throw new aF("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 aF("invalid-response","실시간 Subagent 기록 응답이 올바르지 않습니다.");if("string"==typeof a.error&&a.error)throw new aF("http",a.error);if(!0!==a.success||!a.data||"object"!=typeof a.data)throw new aF("invalid-response","실시간 Subagent 기록 응답이 올바르지 않습니다.");let i=a.data;if(!Array.isArray(i.entries)||!i.entries.every(aH)||"number"!=typeof i.fromByte||"number"!=typeof i.nextByte||"boolean"!=typeof i.reset)throw new aF("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(aW))throw new aF("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(aO))throw new aF("invalid-response","Subagent 디스크 기록 응답이 올바르지 않습니다.");return{sessionId:l.sessionId,name:l.name,bytes:l.bytes,truncated:l.truncated,entries:l.entries}}}}let aB=["feature","maintenance","diagnostic"],aq=/^[\t ]*([A-Z_]+)[\t ]*:[\t ]*(.*?)[\t ]*$/;function aV(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=aq.exec(t[e]);if(!n)break;if("WORK_CLASS"!==n[1])continue;let r=n[2].toLowerCase();return aB.includes(r)?r:null}return null}let aK={verdicts:new Map,runs:new Map,latestByAgent:new Map,spawnedAt:new Map,durations:new Map,parallelWith:new Map,runStartedAt:new Map};function aJ(e){return Array.isArray(e)?e.filter(e=>"object"==typeof e&&null!==e):[]}function aG(e){return"string"==typeof e&&e.trim()?e:null}function aZ(e){return"number"==typeof e.durationMs&&Number.isFinite(e.durationMs)&&e.durationMs>=0?e.durationMs:null}function aY(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 aQ(e){return"string"==typeof e?e:e.map(e=>"text"===e.type?e.text:"").join("\n")}function aX(e,t){if(t?.isError)return null;let n=aJ(e.input.tasks),r=aJ(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=aG(s?.id)??aG(l?.name);o&&a.push({key:`${e.toolCallId}#${i}`,toolCallId:e.toolCallId,index:i,agentId:o,agent:aG(s?.agent)??aG(l?.agent),task:aG(s?.task)??aG(l?.task)??"",workClass:aV(l?.task)??aV(s?.task),spawned:!!t})}return a}let a0=/<task-result\b([^>]*)>/g,a1=/(\w+)="([^"]*)"/g;function a2(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 a4(e,t,n){var r;let s,a,i,l,o=a2(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=aP(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?a_(c):null,run:s,runSource:h,verdict:x?null:m,priorVerdict:x?m:null,runTitle:x?aA(o?.progress?.task):null,observedParallelWith:n.parallelWith.get(e.key)}}function a8(e,t){return t.find(t=>t.parentToolCallId===e.toolCallId&&t.id===e.agentId)}function a5(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 a6(e){return"assistant"!==e.role?[]:e.content?.filter(e=>"toolCall"===e.type&&"task"===e.toolName)??[]}let a3=(0,s.createContext)({ledger:aK,subagents:[],toolResults:new Map});n(21340);let a7={test:!0,tests:!0,__tests__:!0,__fixtures__:!0,fixtures:!0,__snapshots__:!0,node_modules:!0,coverage:!0},a9={html:0,document:1,image:2},ie=["investigate","edit","check","review","commit","ci","deploy"];function it(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=ir(e,r+1);n+=e.slice(r,t),r=t}else if("`"===t){let t=is(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 ir(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=it(e,a+1).end;else if("`"===t)a=is(e,a+1);else{if(t===n)s+=1;else if(t===r&&0==--s)return a+1;a+=1}}return e.length}function is(e,t){let n=t;for(;n<e.length&&"`"!==e[n];)n+="\\"===e[n]?2:1;return Math.min(n+1,e.length)}function ia(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=it(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=ir(e,d+1);i+=e.slice(d,t),o=!0,d=t}else if("`"===u){l<0&&(l=d);let t=is(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 ii(e){return e.slice(e.lastIndexOf("/")+1)}let il={bash:!0,sh:!0,zsh:!0,dash:!0},io={sudo:!0,env:!0,command:!0,exec:!0,nice:!0,nohup:!0,time:!0,timeout:!0,setsid:!0,"systemd-run":!0},ic={"-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},id={"--wait":!0,"-W":!0,"--pipe":!0,"-P":!0,"--pty":!0,"-t":!0,"--scope":!0},iu={if:!0,then:!0,elif:!0,else:!0,do:!0,while:!0,until:!0};function ih(e){let t=ig(e);if(t>=0&&"eval"===e[t])return t+1<e.length?e.slice(t+1).join(" "):null;if(t<0||!Object.hasOwn(il,ii(e[t]))||ip(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 ip(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 im={command:/^-[a-zA-Z]*[vV]/,sudo:/^(?:-[a-zA-Z]*[lvVhK]|--(?:list|validate|version|help|remove-timestamp)$)/};function ig(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(iu,s))){if(t&&(s.startsWith("-")||/^\d+(?:\.\d+)?[smhd]?$/.test(s))){if(Object.hasOwn(im,n)&&im[n].test(s))return -1;"command"!==n&&Object.hasOwn(ic,s)&&(r+=1);continue}if(!Object.hasOwn(io,ii(s)))return r;t=!0,n=ii(s)}}return -1}let ix=/(?:^|\/)wsl\/update\.sh$/;function iv(e,t=0){let n=ih(e);if(null!==n)return t<3&&ia(n).commands.some(e=>iv(e.words,t+1));let r=ig(e);if(r<0)return!1;if(ix.test(e[r]))return!0;if(!Object.hasOwn(il,ii(e[r]))||ip(e,r))return!1;let s=e.slice(r+1).find(e=>!e.startsWith("-"));return void 0!==s&&ix.test(s)}function iy(e){let t=ig(e),n=t<0?e:e.slice(0,t),r=n.map(ii);return r.includes("systemd-run")?!n.some(e=>Object.hasOwn(id,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 ib(e){let[t]=e.pipelines;return 1!==e.pipelines.length||1!==t.commands.length||t.negated?null:t.commands[0]}function iw(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 ik={tail:!0,head:!0,cat:!0,tee:!0},ij=/(?:^|[^\w-])(?:tests?|typecheck|tsc|lint|eslint|vitest|jest|pytest|build|check|verify|smoke)(?![\w])/i,iS={bun:!0,bunx:!0,npm:!0,npx:!0,pnpm:!0,yarn:!0,node:!0,python:!0,python3:!0,deno:!0},iC={"--help":!0,"-h":!0,"--version":!0},iN=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 iT(e){let t=ig(e);if(t<0)return!1;let n=ii(e[t]);if("test"===n||"["===n||e.slice(t+1).some(e=>Object.hasOwn(iC,e)))return!1;if(ij.test(n))return!0;if(!Object.hasOwn(iS,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(iN,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&&ij.test(r)}let iI={"-C":!0,"-c":!0,"--git-dir":!0,"--work-tree":!0,"--namespace":!0},iM={commit:{"--dry-run":!0,"-h":!0,"--help":!0},push:{"--dry-run":!0,"-n":!0,"-h":!0,"--help":!0,"--delete":!0,"-d":!0}};function iE(e){let t=ig(e);if(t<0||"git"!==ii(e[t]))return null;for(let n=t+1;n<e.length;n+=1)if(Object.hasOwn(iI,e[n]))n+=1;else if(!e[n].startsWith("-"))return{name:e[n],at:n};return null}function i$(e,t=0,n){let r=ih(e);if(null!==r)return t<3&&ia(r).commands.some(e=>i$(e.words,t+1,n));let s=iE(e);if(!s||"commit"!==s.name&&"push"!==s.name||void 0!==n&&s.name!==n)return!1;let a=iM[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 iR(e){return iw(e)||null!==iE(e)}let iL={check:({words:e})=>iT(e),commit:({words:e})=>i$(e),ci:({words:e})=>{let t=ig(e);return t>=0&&"gh"===ii(e[t])&&"run"===e[t+1]&&"watch"===e[t+2]&&e.includes("--exit-status")},deploy:e=>iv(e.words)},iA={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 iP(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 i_={"$?":!1,"${PIPESTATUS[0]}":!0};function iF(e,t){let n=iG(t);if("notRun"===n)return[];let r=n?void 0:t,s=ia(e),a=[];if(s.commands.some(({words:e})=>(function e(t,n=0){let r=ih(t);return null!==r?n<3&&ia(r).commands.some(t=>e(t.words,n+1)):iT(t)})(e))&&a.push("check"),s.commands.some(({words:e})=>i$(e))&&a.push("commit"),s.commands.some(({words:e})=>(function e(t,n=0){let r=ih(t);if(null!==r)return n<3&&ia(r).commands.some(t=>e(t.words,n+1));let s=ig(t);return s>=0&&"gh"===ii(t[s])&&"run"===t[s+1]&&["watch","view","list"].includes(t[s+2])})(e))&&a.push("ci"),s.commands.some(iL.deploy)&&a.push("deploy"),0===a.length)return[];let i=r?nU(r):null,l=null===i?!!r?.isError:0!==i,o=a.length>1?{stages:a,failed:l}:void 0,c=r?li(r):"";return a.map(e=>{var t;let a,d,u,h="commit"===e?iR:iw,p=function e(t,n,r=iw,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?ih(h.words):null,m=null===p?null:e(ia(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=ig(h.words);u&&o&&e>=0&&Object.hasOwn(ik,ii(h.words[e]))||r(h.words)||function(e,t){if(t!==e.length-1||e[t].background)return!1;let n=ib(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||iy(h.words)||!function(e,t){if(t===e.length-1)return!0;let n=e[e.length-1],r=ib(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=ib(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,iL[e],h),m="check"===e&&p.decisive.some(({words:e})=>e.includes("--if-present")),f=r?(t=iL[e],a=new Map,d=s.lists.map(e=>(function(e){let t=e&&!e.background?ib(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(i_)){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)||iy(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=ig(n);n.forEach((n,r)=>{if(r!==e||"test"!==n)for(let e of n.replace(/^-+/,"").toLowerCase().split(":")){let n=Object.hasOwn(iA,e)?iA[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 iz(e,t){let n=iP(e),r=null===n?void 0:iF(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 iW=/\.(?:md|mdx|markdown|txt)$/i,iO=/^docs?$/i;function iD(e){return iW.test(e)||e.split(/[\\/]/).slice(0,-1).some(e=>iO.test(e))}let iH={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},iU={multiedit:!0,notebookedit:!0,draft:!0},iB={rename:!0,rename_file:!0},iq={passed:"done",failed:"failed",unverified:"unverified",unobserved:"unobserved"};function iV(e){return e.split("\n")[0].trim()||void 0}let iK=/^\[[^\]\n]*? ([0-9a-f]{7,40})\] (.+)$/m,iJ=/^\s*\+?[0-9a-f]{7,40}\.{2,3}([0-9a-f]{7,40})\s+\S+\s+->\s+\S+/m;function iG(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 iZ=/\btool\.git_(?:finalize|integrate)\s*\(/,iY=/\b(?:Committed|Integrated \S+) and pushed ([0-9a-f]{40})\b|\bcommitSha["']?\s*:\s*["']([0-9a-f]{40})["']/,iQ=/\bgit_(?:finalize|integrate) failed\b|\bok["']?\s*:\s*false\b|\bstage["']?\s*:\s*["'](?!complete["'])[\w-]+["']/,iX=/\bstage["']?\s*:\s*["'](?:up-to-date|aborted)["']/,i0=/["']?\bmessage["']?\s*:\s*(["'`])((?:\\[\s\S]|(?!\1)[^\\])*)\1/;function i1(e,t){if("string"==typeof t.commitSha&&""!==t.commitSha.trim())return t.commitSha.trim();let n=iY.exec(li(e));return n?.[1]??n?.[2]??null}let i2=/^bg_\d+$/;function i4(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&&i2.test(n.jobId))return n.jobId;let r=li(e).trimStart();return r.startsWith("Backgrounded")?/\bBackgrounded as job (bg_\d+)\b/.exec(r)?.[1]??null:null}function i8(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 i5(e){return"passed"===e||"failed"===e||"done"===e}function i6(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 i3(e){return e.commandKey??JSON.stringify([e.cwd??"",e.command])}function i7(e){let t=new Map;for(let n of e){if("check"!==n.stage)continue;let e=i3(n),r=t.get(e);(r?.outcome!=="failed"||i5(n.outcome))&&t.set(e,n)}return[...t.values()]}function i9(e){return"compound"in e&&e.compound?.failed===!0}let le={failed:6,running:5,unverified:4,unobserved:3,stale:2,passed:1,done:0};function lt(e){return"stale"!==e&&(i5(e)||"running"===e)}function ln(e){if("ci"!==e.stage)return null;let t=ia(e.command).commands.flatMap(({words:e})=>lo(e)).map(e=>"run"===e[0]&&("watch"===e[1]||"view"===e[1])?lh(e):null);return t.length>0&&t.every(e=>null!==e)?t:null}let lr={"publish public mirror":!0,"publish-public.yml":!0,".github/workflows/publish-public.yml":!0},ls={ci:!0,"ci.yml":!0,".github/workflows/ci.yml":!0},la=/^[0-9a-f]{40}$/i;function li(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 lo(e,t=0){let n=ih(e);if(null!==n)return t<3?ia(n).commands.flatMap(e=>lo(e.words,t+1)):[];let r=ig(e);return r>=0&&"gh"===ii(e[r])?[e.slice(r+1)]:[]}function lc(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 ld={"-R":!0,"--repo":!0,"-j":!0,"--job":!0,"--interval":!0,"-i":!0,"--json":!0,"-q":!0,"--jq":!0,"-t":!0,"--template":!0};function lu(e){for(let t=2;t<e.length;t+=1){if(Object.hasOwn(ld,e[t])){t+=1;continue}if(!e[t].startsWith("-"))return e[t]}return null}function lh(e){let t=lu(e);return null!==t&&/^\d+$/.test(t)?t:null}let lp=/^https:\/\/github\.com\/([^/\s]+\/[^/\s]+)\/actions\/runs\/\d+/i;function lm(e,t){if(!t||t.isError||!/\bgh\b/.test(e)||0!==nU(t))return[];let n=ia(e).commands.flatMap(({words:e})=>lo(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"?lc(r,["-c","--commit"])?.toLowerCase():void 0,a=s&&/^[0-9a-f]{7,40}$/.test(s)?s:null,i=li(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?lp.exec(e.url)?.[1]??null:null;return[{id:"number"==typeof e.databaseId||"string"==typeof e.databaseId?String(e.databaseId):r?.[1]==="view"?lh(r):null,repo:(n??(r?lc(r,["-R","--repo"]):null))?.toLowerCase()??null,sha:t,status:e.status,conclusion:e.conclusion,branch:"string"==typeof e.headBranch?e.headBranch:r?lc(r,["-b","--branch"]):null,workflow:("string"==typeof e.workflowName?e.workflowName:"string"==typeof e.name&&"databaseId"in e?e.name:r?lc(r,["-w","--workflow"]):null)?.toLowerCase()??null,title:"string"==typeof e.displayTitle?e.displayTitle:null}]}):[]}let lf=/\b\d{9,12}\b/g,lg=/\b(?=[0-9a-f]*[a-f])[0-9a-f]{7,40}\b/;function lx(e,t){if(e?.type!=="toolCall")return[];let n=iP(e);return null===n?[]:lm(n,t).flatMap(e=>e.repo&&e.sha&&e.branch&&e.workflow&&"completed"===e.status&&"success"===e.conclusion&&Object.hasOwn(ls,e.workflow)?[{repo:e.repo,sha:e.sha,branch:e.branch,workflow:e.workflow}]:[])}let lv="Public tree already matches; nothing to publish";function ly(e){let t=null===e?null:/^\$(?:\{([A-Za-z_]\w*)\}|([A-Za-z_]\w*))$/.exec(e);return t?t[1]??t[2]:null}function lb(e){let t="run"===e[0]&&"list"===e[1]?lc(e,["-w","--workflow"])?.toLowerCase():void 0;return void 0!==t&&Object.hasOwn(lr,t)}function lw(e,t){let n=new Map,r=[];for(let{words:s}of ia(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?[]:ia(e).commands.flatMap(e=>lo(e.words));n.set(t[1],1===r.length&&lb(r[0]))}continue}for(let e of lo(s)){if(lb(e)){r.push({args:e,publish:!0});continue}let s="run"===e[0]&&("watch"===e[1]||"view"===e[1])?lu(e):null,a=ly(s),i=null!==a?!0===n.get(a):null!==s&&/^\d+$/.test(s)&&t(s);r.push({args:e,publish:i})}}return r}function lk(e,t){let n=lw(e,t);return n.length>0&&n.every(({publish:e})=>e)}function lj(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 lS(e,t,n){if(lj(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(ls,e.workflow)&&[...n.publishRuns.values()].some(n=>n.order>t.order&&null!==n.sha&&lj(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 lC={failure:!0,cancelled:!0,timed_out:!0,startup_failure:!0},lN=/^(\d{4}-\d\d-\d\dT\d\d:\d\d:\d\dZ) READY ([0-9a-f]{7,40})\b/,lT=/^(\d{4}-\d\d-\d\dT\d\d:\d\d:\d\dZ) (ROLLED_BACK|ROLLBACK_FAILED|FAIL)\b/,lI=/^(\d{4}-\d\d-\d\dT\d\d:\d\d:\d\dZ) START old=\S* target=([0-9a-f]{7,40})\b/;function lM(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?i4(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||!i2.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[{...i8(e.id,e.resultText),...null===t?{}:{exitCode:t}}]});if(r.length>0)return r;let s=li(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 i8(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]=li(t).split("\n");return RegExp(`^1\\|${r} \\[\\w+\\] — (?:completed|failed)\\b`).test(s)?i8(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[i8(n[1],t.slice(n[0].length))];let r=[...t.matchAll(/^── Job (\S+) .*──$/gm)];return r.flatMap((e,n)=>{if(!i2.test(e[1]))return[];let s=(e.index??0)+e[0].length;return[i8(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=iP(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 lm(s,n))e.runs.push({...t,order:r}),t.id&&t.sha&&t.workflow&&Object.hasOwn(lr,t.workflow)&&a(t.id,{sha:t.sha,repo:t.repo});for(let e of function(e,t){if(!t||t.isError||0!==nU(t))return[];let n=ia(e).commands.flatMap(({words:e})=>lo(e)).filter(e=>"run"===e[0]&&"list"===e[1]);if(1!==n.length)return[];let r=lc(n[0],["-w","--workflow"])?.toLowerCase(),s=void 0!==r&&Object.hasOwn(lr,r),a=lc(n[0],["-R","--repo"])?.toLowerCase()??null;return li(t).split("\n").flatMap(e=>{let t=e.trim();if(t.startsWith("{")||t.startsWith("["))return[];let n=t.toLowerCase();if(!s&&!Object.keys(lr).some(e=>n.includes(e)))return[];let r=t.match(lf)??[];return 1===r.length?[{id:r[0],sha:lg.exec(n)?.[0]??null,repo:a}]:[]})}(s,n))a(e.id,e);for(let s of lx(t,n))e.ciHeads.push({...s,order:r});for(let t of function(e,t){let n=ia(e),r=n.commands.flatMap(({words:e})=>lo(e)).filter(e=>"api"===e[0]),s=!n.uncertain&&1===n.commands.length&&1===r.length,a=t&&!t.isError&&0===nU(t)?li(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=lc(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&&la.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!==nU(t)||2!==e.split(lv).length)return null;let{lists:n}=ia(e),r=0;for(;r<n.length&&["set","cd"].includes(ib(n[r])?.words[0]??"");)r+=1;let s=r<n.length-1?function(e){let t=ib(e)?.words,n=t?.length===1?/^([A-Za-z_]\w*)=\$\(([\s\S]*)\)$/.exec(t[0]):null;if(!n)return null;let r=ia(n[2]),s=1===r.lists.length?ib(r.lists[0]):null,a=s?.words[0]==="gh"?lo(s.words):[];if(1!==a.length||"run"!==a[0][0]||"list"!==a[0][1])return null;let i=lc(a[0],["-c","--commit"]),l=lc(a[0],["-w","--workflow"])?.toLowerCase();return i&&la.test(i)&&l&&Object.hasOwn(lr,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=lo(r.words);if(1!==i.length||"run"!==i[0][0]||"view"!==i[0][1]||!i[0].includes("--log"))return!1;let l=lu(i[0]);if(ly(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]!==lv)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=lo(e);return 1===s.length&&"run"===s[0][0]&&"watch"===s[0][1]&&ly(lu(s[0]))===t})(e,s.name))&&li(t).split("\n").some(e=>e.trim()===lv)?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=iG(t);if("notRun"===s)return null;let a={toolCallId:e.toolCallId,attempt:0},i=n&&!s?"running":"unobserved",l=iP(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 iF(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}=ia(e),r=li(t),s=e=>n.some(({words:t})=>i$(t,0,e));return(!s("commit")||iK.test(r))&&(!s("push")||iJ.test(r))}(l,t)?"done":iq[n.state]:i;return{...a,stage:"commit",..."done"===o?(e=(s=t)?li(s):"",(r=iK.exec(e))?{commit:r[1],title:r[2].trim()}:{commit:iJ.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=ia(e).commands.flatMap(({words:e})=>lo(e)),r=n.find(e=>"run"===e[0]&&"watch"===e[1]&&e.includes("--exit-status")),s=r?lu(r):null;if(null===s||!n.some(e=>"run"===e[0]&&"view"===e[1]&&e.includes("--json")&&lu(e)===s))return null;let a=ll(li(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(lC,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?tx(d)??d:void 0,(p="string"==typeof o.cwd?o.cwd:"")?tx(p,h)??(h?tx(`${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?iV(e.input.message):void 0,n=t?{title:t}:{};if(!d)return{...a,stage:"commit",commit:null,docsOnly:!1,...n,outcome:i};let r=i1(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&&iD(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=i1(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&&iD(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(!iZ.test(r))return null;let s=i0.exec(r)?.[2],a=void 0===s?void 0:iV(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=li(t),o=iY.exec(l),c=o?(o[1]??o[2]).toLowerCase():null;if(!c&&iX.test(l))return null;let d=iQ.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(iU,t))return!0;if("lsp"===t)return"string"==typeof e.input.action&&Object.hasOwn(iB,e.input.action);if(!tv(e.toolName)&&!ty(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:(tv(e.toolName)||ty(e.toolName))&&tS(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||!(tv(e.toolName)||ty(e.toolName)))return!1;let r=tj(e.input,t);return r.length>0&&r.every(e=>(function(e,t){if(e.split(/[\\/]/).includes(".."))return!1;let n=t?tx(t)??t:void 0,r=tO(tx(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(iH,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&&i4(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=ia(n.command).commands.flatMap(({words:e})=>lo(e)).find(e=>"run"===e[0]&&"watch"===e[1]);if(a){let e,i=lh(a),o=e=>(f.publishRuns.get(e)?.order??1/0)<=r;if((e=lw(n.command,o).filter(({args:e})=>"run"===e[0]&&"watch"===e[1])).length>0&&e.every(({publish:e})=>e)){lk(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=>lS(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(ls,e.workflow)&&lS(e,s,f));if(!o||"completed"!==o.status||"string"!=typeof o.conclusion)return;let c="success"===o.conclusion?"passed":Object.hasOwn(lC,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=ih(e);if(null!==s){if(r<3)for(let e of ia(s).commands)n(e.words,r+1);return}if(!iv(e))return;let a=ig(e),i=ix.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 ia(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 li(i).split("\n")){let a=e.trim().replace(/^\d+[:-](?=\d{4}-\d\d-\d\dT)/,"");if(null===s){let e=lI.exec(a);e&&Date.parse(e[1])>=o&&(s=e[2]);continue}let i=lN.exec(a);if(i&&Date.parse(i[1])>=o&&lj(i[2],s)){y[t]={order:r,step:{...n,outcome:"passed",evidence:`${i[1]} READY ${i[2].slice(0,12)}`}};return}let l=lT.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=ia(n.command).commands.flatMap(({words:e})=>lo(e)).find(e=>"run"===e[0]&&"watch"===e[1]),r=e?lh(e):null;r&&"passed"===n.outcome&&f.watched.push({id:r,order:t}),!n.compound&&lk(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:${i3(n)}`:n.stage,t=u.get(e);(t?.outcome!=="failed"||i5(n.outcome))&&u.set(e,{stage:n.stage,outcome:n.outcome,order:o.length})}}else{let e=i6(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&&la.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=ia(r).commands.flatMap(({words:e})=>lo(e))).length>0&&s.every(t=>"run"===t[0]&&"list"===t[1]&&lc(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=ie.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||i5(r.outcome)){if(null!==n&&!("ci"!==r.stage||lt(t))&&!ia(r.command).commands.some(({words:e})=>lo(e).some(e=>"run"===e[0]&&"watch"===e[1]&&e.includes("--exit-status")))){let t="stale"===n&&(ln(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 ln(r)??[])e.add(t)}}return n??"waiting"}let n="done";for(let e of i7(t)){let t=e.stale?"stale":e.outcome;le[t]>le[n]&&(n=t)}return n}(e,n),steps:n,earlier:"investigate"===e?[]:t.filter(e=>e.attempt<d)}}),T=N[ie.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[ie.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&&!i9(e))&&($=t)});let R=null;if(n&&o.length>0)if(i6(u))R={stage:"edit",returning:!0};else if($<0)R={stage:N.find(e=>"waiting"!==e.status)?.stage??ie[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(lE,e.status));return a?.stage??s.at(-1)?.stage??r.stage}(o,N,k),reached:$<0?null:ie[$],next:R,publication:C}}let lE={running:!0,unobserved:!0,unverified:!0,failed:!0,stale:!0},l$="끊기기 전에 바깥에 영향을 주는 행동(커밋\xb7push, `git_finalize`\xb7`git_integrate`, 배포\xb7`update.sh`, CI 재실행, 이슈\xb7PR 댓글, 메시지 전송)을 하던 중이었다면 다시 하기 전에 그 결과가 이미 반영됐는지 `git log`\xb7`git status`\xb7원격 브랜치, `gh run list`, 배포 로그, 해당 페이지로 먼저 확인하고, 반영됐으면 되풀이하지 않는다. ",lR="[자동 재개] CUELO 업데이트\xb7재시작 때문에 이 세션의 진행 중 작업이 중단(abort)됐다. 서버가 새 버전으로 다시 떴다. 중단 직전에 돌던 명령\xb7도구 결과는 사라졌을 수 있으니 파일\xb7프로세스 상태를 먼저 확인하고, 하던 작업을 이어서 진행한다. "+l$+"그때 돌던 SubAgent(task child)도 멈췄지만 기록은 남아 있다. 결과를 받지 못한 child에는 먼저 `write agent://<id>`로 이어서 하라고 보내 되살리고, 되살아나지 않으면(isolated 작업 공간 등) 남은 파일 상태를 확인한 뒤 새로 맡긴다.",lL="[자동 재개] CUELO 서버가 예기치 않게 종료돼 이 세션의 진행 중 작업이 중간에 끊겼다. 서버가 다시 떴다. 끊기기 직전에 돌던 명령\xb7도구 결과는 사라졌을 수 있다. 그 명령을 그대로 다시 실행하지 말고, 파일\xb7프로세스 상태를 먼저 확인한 뒤 하던 작업을 이어서 진행한다. "+l$+"그때 돌던 SubAgent(task child)도 멈췄지만 기록은 남아 있다. 결과를 받지 못한 child에는 먼저 `write agent://<id>`로 이어서 하라고 보내 되살리고, 되살아나지 않으면 남은 파일 상태를 확인한 뒤 새로 맡긴다.",lA="[자동 재개] CUELO 업데이트의 세션 정지 단계가 이 세션의 진행 중 작업을 중단(abort)했지만, 업데이트가 실패해 기존 서버가 그대로 돌고 있다(새 버전으로 바뀌지 않았다). 중단 직전에 돌던 명령\xb7도구 결과는 사라졌을 수 있으니 파일\xb7프로세스 상태를 먼저 확인하고, 하던 작업을 이어서 진행한다. "+l$+"그때 돌던 SubAgent(task child)도 멈췄지만 기록은 남아 있다. 결과를 받지 못한 child에는 먼저 `write agent://<id>`로 이어서 하라고 보내 되살리고, 되살아나지 않으면(isolated 작업 공간 등) 남은 파일 상태를 확인한 뒤 새로 맡긴다.",lP=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 작업 공간 등) 남은 파일 상태를 확인한 뒤 새로 맡긴다."]),l_={sending:!0,accepted:!0,delivered:!1,unconfirmed:!1,failed:!1};function lF(e){return e.trim()}function lz(e){return lF(e.text)||(e.images>0?"[Image]":"")}function lW(e){let t=e.filter(e=>!l_[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 lO(e,t){switch(t.type){case"submit":return lW([...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 lW(e.map(e=>e.id===t.id&&l_[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${lF(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(!l_[e.stage])return e;let t=`${e.kind}\u0000${lz(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=lF(t.text);if(!n&&0===t.images)return e;let r=e.find(e=>(l_[e.stage]||"unconfirmed"===e.stage)&&e.kind===t.kind&&lF(e.text)===n&&e.images===t.images);if(!r)return e;return lW(e.map(e=>e===r?{...e,stage:"delivered",inQueue:!1}:e))}case"withdraw":{let n=e=>l_[e.stage]||"unconfirmed"===e.stage;if(void 0===t.text)return e.filter(e=>!n(e));let r=lF(t.text),s=e.find(e=>n(e)&&e.kind===t.kind&&(lF(e.text)===r||lz(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 lD(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 lH(e){return"steering"in e&&!0===e.steering?"steer":"followUp"}function lU(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 lB(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(tL(n.toolName)){let e=tR(n,t.get(n.toolCallId));"authoritative"===e.kind&&(a=e.phases);continue}let e=iz(n,t.get(n.toolCallId));e&&r.push(e)}return{checks:r,dispatchCalls:s,files:tM(e,t,n),remaining:a?lU(a):null}}function lq(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 lV(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 lK(e,t){var n;let r=t;for(;r>=0&&(n=e[r],n?.role==="custom"?"compaction"===n.customType:n?.role==="user"&&("steer"===lH(n)||function(e){if(e===lR||e===lL||e===lA||lP.has(e))return!0;let[t,n]=e.split("\n",2);return("[하네스 통지] 이 세션이 시작한 CUELO 업데이트가 끝나 런타임이 새 버전으로 교체됐고, 이 세션이 그 위에서 재개됐습니다."===t||"[하네스 통지] 이 세션이 시작한 CUELO 업데이트가 실패했습니다."===t)&&void 0!==n&&n.startsWith("requestId=")}(lD(n))));){let t=r-1;for(;t>=0&&"user"!==e[t].role;)t-=1;r=t}return r}function lJ(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||!tL(e.toolName))continue;let n=tR(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=t$(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 lG(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(...lx(e,t.get(e.toolCallId)))}return s}function lZ(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 lY(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 lQ=["investigate","implement","verify","report"],lX={edit:!0,write:!0,ast_edit:!0,multiedit:!0,notebookedit:!0},l0={bash:!0,eval:!0};function l1(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 l2(e,t,n,r){return!0===lX[t]&&!tS(e.input,n.get(e.toolCallId),r)}function l4(e){return(e.toolName??"").toLowerCase().split(/[.:/]/).pop()??""}function l8(e){return"yield"===l4(e)&&!Array.isArray(e.input?.type)}function l5(e,t){if(0===e.length)return null;let{blocks:n,results:r}=l1(e),s=-1;n.forEach((e,t)=>{l8(e)&&(s=t)});let a=s>=0&&s===n.length-1,i=a?n.findLastIndex((e,t)=>t<s&&l8(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=l4(e);if(l2(e,n,r,t))"verify"===l.phase&&(l.reedits+=1),o=!0,l.phase="implement",l.verifiedAfterEdit=!1;else if(l0[n]){if(l.phase=o?"verify":"investigate",o){l.verifiedAfterEdit=!0;let t=iz(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 l6(e,t){if(!e)return{run:null,stations:lQ.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?lQ.indexOf(n.phase):lQ.findLastIndex(e=>n.calls[e]>0),s=lQ.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 l3(e){if(e<6e4)return null;let t=Math.round(e/6e4);return{hours:Math.floor(t/60),minutes:t%60}}function l7(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 l9(e){return"pending"===e||"running"===e}let oe=new Map;function ot(e){return`${e.liveId??""}|${e.status??""}|${e.archiveName??""}`}function on(e){return e instanceof aF&&("live-unreachable"===e.kind||"sidecar-unreachable"===e.kind)?{kind:"unreachable",message:e.message}:{kind:"error",message:e instanceof Error?e.message:String(e)}}function or(e,{sessionId:t,client:n,enabled:r}){let[a,i]=(0,s.useState)(oe),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=on(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:l7(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=on(t);await u(r,a,s,`실시간 기록을 읽지 못해 디스크 기록을 표시합니다: ${e.message}`)}else{let e=on(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=>l9(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 os="omp-web:flow-motion",oa=new Set,oi=null;function ol(){if(null===oi)try{oi="paused"===window.localStorage.getItem(os)}catch{oi=!1}return oi}function oo(e){return oa.add(e),()=>{oa.delete(e)}}function oc(){return(0,s.useSyncExternalStore)(oo,ol,()=>!1)}function od({paused:e}){let{st:t}=sp();return(0,r.jsx)("button",{type:"button",className:"flow-graph-motion","aria-pressed":e,onClick:()=>(function(e){oi=e;try{e?window.localStorage.setItem(os,"paused"):window.localStorage.removeItem(os)}catch{}for(let e of oa)e()})(!e),children:t("graph.motion.pause")})}function ou(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 oh(e){return e.stale?"stale":e.outcome}let op=(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 om({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 of({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 og({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":oh(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 ox={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"},ov={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"};function oy({step:e,label:t,st:n}){let s=i9(e),a=e.compound?.stages.map(e=>n(`flow.stage.${e}`)).join("\xb7")??"",i=e.otherRun,l=e.reason?ox[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(ov[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})]})]})}function ob({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=oh(e),i=(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(of,{outcome:a}),(0,r.jsx)(og,{step:e,st:t}),(0,r.jsxs)("span",{className:"flow-check-label",children:[n?`${t("flow.attempt",{attempt:e.attempt})} \xb7 ${s}`:s,i9(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"),op]})]}),(0,r.jsx)(oy,{step:e,label:s,st:t})]})},`${e.toolCallId}#${e.stage}`)})})}function ow({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}),op]}),(0,r.jsx)(ob,{steps:e,st:t,attempts:!0})]})}function ok({view:e,steps:t,st:n}){if(0===t.length)return null;if("check"!==e.stage)return(0,r.jsx)(ob,{steps:t,st:n});let s=i7(t),a=e=>{let t=oj.indexOf(oh(e));return t<0?oj.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)(ob,{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}),op]}),(0,r.jsx)(ob,{steps:l,st:n})]})]})}let oj=["failed","unverified","unobserved","stale","running","passed"];function oS({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 i7(e.steps))t.set(oh(n),(t.get(oh(n))??0)+1);return oj.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)(og,{step:i,st:s})}function oC({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":ie.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=ou(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)(om,{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)(oS,{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)(ob,{steps:i,st:n,attempts:!0})})]})}function oN({sessionId:e,snapshots:t,client:n,enabled:r,transcripts:a=!0,cwd:i}){let l=(0,s.useMemo)(()=>t.filter(e=>l9(e.status)),[t]),o=r&&!!e&&l.length>0,c=or((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}=l1(e),s="investigate",a=!1;for(let e of n){let n=l4(e);l2(e,n,r,t)?(a=!0,s="implement"):l0[n]?s=a?"verify":"investigate":"yield"===n&&(s="report",a=!1)}return s}(r,i),trace:l5(r,i),todo:function(e){let t=new Map;for(let n of e)"toolResult"===n.role&&t.set(n.toolCallId,n);let n=tA([...e],t);if(!n)return null;let r=t_(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 oT(e,t){let n=l3(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 oI(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}):oT(e,t)}function oM({phase:e}){let{st:t}=sp();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:lQ.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 oE={done:"done",stale:"stale",active:"active",waiting:"waiting",skipped:"skipped",none:"skipped",unobserved:"unverified"};function o$(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 oR({flow:e,live:t,verdict:n,attempts:s}){let{st:a}=sp(),i=oc(),l=e.stations.findIndex(e=>"active"===e.state),o=lQ.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)(od,{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=oE[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)(om,{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 ",o$(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 o$(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":lQ.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)(om,{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":lQ.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 oL(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 oA({snapshot:e,view:t,id:n}){var s,a,i;let l,o,c,{st:d}=sp(),u=nj(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=lY(n,.5)??0;return{kind:"remaining",p25Ms:lY(n,.25)??0,medianMs:r,p75Ms:lY(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:oI(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:oI(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=l3(a),c=l3(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:oT(d,a),high:oT(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:oT(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:oT(d,m),completed:t.todo.completed,total:t.todo.total})})]})]})}let oP={dispatching:"run.dispatching",pending:"run.pending",running:"run.running",completed:"run.completed",failed:"run.failed",aborted:"run.aborted",unobserved:"run.unobserved"},o_={accepted:"verdict.accepted",rework:"verdict.rework",held:"verdict.held",none:"verdict.none"};function oF({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(oP[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(o_[n]),null!=s&&s>1?` \xb7 ${t("verdict.attempt",{attempt:s})}`:null]})]})}function oz(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 lB(n,r,t)}function oW(e){return e.sessionFile?.split(/[\\/]/).pop()?.replace(/\.jsonl$/i,"")||void 0}function oO(e,t){let n=e?.state;return n?.kind!=="ready-live"?null:l5(n.entries.flatMap(e=>"message"in e?[e.message]:[]),t)}function oD({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 oH({calls:e}){let{ledger:t,subagents:n,toolResults:a,onOpenPanel:i,sessionId:l,cwd:o,onOpenMaker:c,selectedMaker:d}=(0,s.useContext)(a3),{st:u}=sp(),{t:h}=(0,F.s)(),[p,m]=(0,s.useState)(!1),f=(0,s.useId)(),g=(0,s.useMemo)(()=>aU(),[]),x=(0,s.useMemo)(()=>e.flatMap(e=>aX(e,a.get(e.toolCallId))??[]).map(e=>a4(e,n,t)),[e,a,n,t]),v=(0,s.useMemo)(()=>x.flatMap(e=>{if("pending"!==e.run&&"running"!==e.run)return[];let r=a2(e.member,n,t);return r?[r]:[]}),[x,n,t]),y=oN({sessionId:l,snapshots:v,client:g,enabled:!0,transcripts:p,cwd:o}),b=(0,s.useMemo)(()=>new Map(x.flatMap(e=>{let t=a8(e.member,n);return t?[[e.member.key,t]]:[]})),[x,n]),w=(0,s.useMemo)(()=>p?[...b].filter(([,e])=>!l9(e.status)).map(([e,t])=>({key:e,liveId:t.id,status:t.status,archiveName:oW(t)})):[],[b,p]),k=or(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?l6(f?l?.trace??null:oO(k.get(e.member.key),o),f):null,x=p?a5(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)(oU,{maker:e,phase:f&&g?.run?u(`phase.${g.run.phase}`):null,checks:function(e,t,n){if(!t)return{kind:"unobserved"};if(l9(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}=oz(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)(oD,{maker:e,st:u}),(0,r.jsx)(oF,{maker:e,st:u})]}),g&&(0,r.jsx)(oR,{flow:g,live:f,verdict:e.verdict,attempts:x}),p&&(0,r.jsx)(oq,{attempts:x}),i&&l&&(0,r.jsxs)("div",{className:"answer-dispatch-progress",children:[l.todo?`${oL(u,l.todo)} \xb7 `:null,(0,r.jsx)(oA,{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(o_[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 oU({maker:e,phase:t,checks:n,onOpen:s}){let{st:a}=sp(),{t:i}=(0,F.s)(),l=e.verdict?.verdict??"none",o=a(oP[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)(oD,{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(o_[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 oB({maker:e}){let{ledger:t,subagents:n,sessionId:a,cwd:i}=(0,s.useContext)(a3),l=(0,s.useMemo)(()=>aU(),[]),o="pending"===e.run||"running"===e.run,c=o&&"live"===e.runSource,d=o?a2(e.member,n,t):void 0,u=oN({sessionId:a,snapshots:(0,s.useMemo)(()=>d?[d]:[],[d]),client:l,enabled:!0,transcripts:!0,cwd:i}),h=a8(e.member,n),p=(0,s.useMemo)(()=>h&&!l9(h.status)?[{key:e.member.key,liveId:h.id,status:h.status,archiveName:oW(h)}]:[],[h,e.member.key]),m=or(p,{sessionId:a??"",client:l,enabled:!!a&&p.length>0}),f=d?u.get(d.id):void 0,g=l6(c?f?.trace??null:oO(m.get(e.member.key),i),c),x=a5(e.member,t);return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(oR,{flow:g,live:c,verdict:e.verdict,attempts:x}),(0,r.jsx)(oq,{attempts:x})]})}function oq({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 oV=/\.(?:md|mdx|markdown|txt)$/i;function oK(e){return`${(100*Math.min(1,Math.max(0,e))).toFixed(2)}%`}function oJ(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 oG({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:oK(e.bar.offset),width:oK(e.bar.width)}})}),(0,r.jsx)("span",{className:"flow-graph-time",children:oI(t,e.durationMs)})]}):(0,r.jsx)("span",{className:"flow-graph-time-missing",children:t(n?"summary.time.running":"summary.time.unobserved")})}function oZ({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 oY({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 oQ({summary:e,makers:t,timings:n,live:a=!1,onOpenFile:i}){let l,o,c,{subagents:d,onOpenMaker:u}=(0,s.useContext)(a3),{st:h}=sp(),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=>!oV.test(e.filePath)),docs:r.filter(e=>oV.test(e.filePath))}})(t,n,e.span,e.files),[t,n,e.span,e.files]),[g,x]=(0,s.useState)(void 0),v=oc(),y=e.files.length,b=a&&m.current?m.stages.find(e=>e.stage===m.current):void 0,w=void 0===g?b&&oJ(b,m,y)?`stage:${b.stage}`:(l=m.stages.filter(e=>oJ(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?ie.indexOf(k.from):-1,S=ie.indexOf("edit"),C=b?ie.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=ie.indexOf("edit"),a=e=>"waiting"!==e.status&&"skipped"!==e.status&&"notNeeded"!==e.status,i=[],l=n,o=e=>{let t=ie.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=ie.indexOf(c.from);for(let n of e)ie.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))ie.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 A=1===L.size&&L.has("accepted"),P=m.stages[S+1],_=P?ou(P,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)(oY,{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)(oZ,{entry:e,together:f.makers.length>1,st:h}),(0,r.jsx)("span",{className:"flow-graph-maker-time",children:(0,r.jsx)(oG,{entry:e,st:h})}),(0,r.jsx)(oF,{maker:e.maker,st:h})]})},e.maker.member.key)})}),(0,r.jsxs)("p",{className:"flow-graph-join","data-state":A?"done":"unverified",children:[(0,r.jsx)(om,{look:A?"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(o_[e])," ",L.get(e)]},e))})]})]},"branch"),z=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"),W=m.stages.map((e,t)=>{let n=ou(e,m,a),s=`stage:${e.stage}`,i=e.steps.some(i9);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)(oY,{selectable:oJ(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)(om,{look:n}),(0,r.jsx)("span",{className:"flow-graph-stop-word",children:(0,r.jsx)(oS,{view:e,flow:m,live:a,st:h})})]}),i&&(0,r.jsx)("span",{className:"flow-compound",children:h("flow.compound.failed")})]})},e.stage)}),O=[];W.forEach((e,t)=>{O.push(e),t===S&&F&&O.push(F),t===j&&z&&O.push(z)});let D=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;D=(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)(sC,{files:e.files,onOpenFile:i}),(0,r.jsx)(ok,{view:t,steps:s,st:h}),(0,r.jsx)(ow,{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=a8(e.maker.member,d);D=(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)("h5",{className:"flow-graph-detail-title",children:e.maker.title}),(0,r.jsx)(oZ,{entry:e,together:f.makers.length>1,batch:!0,st:h}),(0,r.jsx)("p",{className:"flow-graph-detail-line",children:(0,r.jsx)(oF,{maker:e.maker,st:h})}),(0,r.jsx)("div",{className:"flow-graph-maker-time",children:(0,r.jsx)(oG,{entry:e,st:h})}),(0,r.jsx)(oB,{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)&&(D=(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)(sC,{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)(od,{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:[O,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)(oY,{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)(oY,{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})})]})]})}),D&&(0,r.jsx)("div",{className:"flow-graph-detail",id:p,role:"region","aria-label":h("graph.detail.aria"),children:D})]})}function oX(e,t,n){let r=new URLSearchParams({type:t});return n&&r.set("sessionId",n),`/api/files/${tz(e)}?${r}`}function o0(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 o1({messageKey:e}){let{st:t}=sp();return(0,r.jsx)("p",{className:"answer-result-fallback",role:"result.previewLoading"===e?"status":void 0,children:t(e)})}function o2({deliverable:e,sessionId:t,title:n}){let{filePath:s,kind:a}=e;if("image"===a){let e=oX(s,"read",t);return(0,r.jsx)(o6,{src:e,title:n},e)}if("html"===a){let e=oX(s,"read",t);return(0,r.jsx)(o4,{url:e,title:n},e)}if(s.toLowerCase().endsWith(".pdf")){let e=oX(s,"read",t);return(0,r.jsx)(o8,{url:e,title:n},e)}let i=oX(s,"preview",t);return(0,r.jsx)(o5,{url:i,title:n},i)}function o4({url:e,title:t}){let n=o0(e,"json");return"ready"!==n.kind?(0,r.jsx)(o1,{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 o8({url:e,title:t}){let n=o0(e,"head");return"ready"!==n.kind?(0,r.jsx)(o1,{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 o5({url:e,title:t}){let n=o0(e,"text");return"ready"!==n.kind?(0,r.jsx)(o1,{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 o6({src:e,title:t}){let[n,a]=(0,s.useState)("loading");return"failed"===n?(0,r.jsx)(o1,{messageKey:"result.previewFailed"}):(0,r.jsxs)(r.Fragment,{children:["loading"===n?(0,r.jsx)(o1,{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 o3({deliverables:e,onOpenFile:t}){let{sessionId:n}=(0,s.useContext)(a3),{st:a}=sp(),[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=tW(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)(o2,{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)(sC,{files:d.map(({filePath:e})=>({filePath:e})),onOpenFile:t})]})]})}let o7=(0,s.createContext)({selected:null,shown:!1,select:()=>{}});function o9(e,t){let{ledger:n,subagents:r,toolResults:a}=(0,s.useContext)(a3),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(a7,n)||n.startsWith(".next")||"doc"===n&&"history"===t[e+1])return!0}return!1}(n.filePath))continue;let e=function(e){let t=eB(e);return"html"===t||"htm"===t?"html":eV(e)?"document":eq(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)=>a9[e.deliverable.kind]-a9[t.deliverable.kind]||e.index-t.index).map(({deliverable:e})=>e)}(e.files),[t,e.files]),l=(0,s.useMemo)(()=>e.dispatchCalls.flatMap(e=>aX(e,a.get(e.toolCallId))??[]).map(e=>a4(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=i7(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 ce(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 ct({summary:e,turnKey:t,live:n=!1}){let{st:a}=sp(),i=o9(e,n),{selected:l,shown:o,select:c}=(0,s.useContext)(o7);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)(ca,{attention:i.attention,live:n}),(0,r.jsx)("span",{className:"turn-row-counts","data-attention":i.attention?"":void 0,children:ce(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 cn({summary:e,turnKey:t,live:n=!1}){let{shown:a}=(0,s.useContext)(o7);return a?(0,r.jsx)(ct,{summary:e,turnKey:t,live:n}):(0,r.jsx)(cr,{summary:e,turnKey:t,live:n})}function cr({summary:e,turnKey:t,live:n}){let{st:a,locale:i}=sp(),l=o9(e,n),{select:o,latestTurn:c,compactedCalls:d,onOpenFile:u}=(0,s.useContext)(o7),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)(cc,{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 cs({summary:e,live:t=!1,onOpen:n}){let{st:s}=sp(),a=o9(e,t);return a.empty?null:(0,r.jsxs)("button",{type:"button",className:"turn-peek",onClick:n,children:[(0,r.jsx)(ca,{attention:a.attention,live:t}),(0,r.jsx)("span",{className:"turn-peek-counts",children:ce(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 ca({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 ci({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 cl(e,t,n,r){let s=t+(e??[]).reduce((e,t)=>e+(aX(t,n.get(t.toolCallId))?.length??0),0);return r(1===s?"summary.makers.one":"summary.makers",{count:s})}function co({summary:e,live:t=!1,folded:n=!1,compactedCalls:a,onOpenFile:i}){let{st:l,locale:o}=sp(),{toolResults:c}=(0,s.useContext)(a3);return e?(0,r.jsx)(cc,{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)(ci,{title:l("turn.dispatches"),summaryLine:cl(a,0,c,l),folded:n,open:!0,children:(0,r.jsx)(oH,{calls:a})})}):(0,r.jsx)("p",{className:"inspector-empty",children:l("turn.none")})}function cc({summary:e,live:t,folded:n,compactedCalls:a,onOpenFile:i,st:l,locale:o}){let c=o9(e,t),{toolResults:d}=(0,s.useContext)(a3),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)(o3,{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)(ci,{title:l("flow.heading"),summaryLine:ce(e,c,t,l).join(" \xb7 "),folded:!0,open:!0,children:(0,r.jsx)(oQ,{summary:e,makers:c.makers,timings:c.timings,live:t,onOpenFile:i})}):(0,r.jsx)("section",{className:"turn-block",children:(0,r.jsx)(oQ,{summary:e,makers:c.makers,timings:c.timings,live:t,onOpenFile:i})})),(e.dispatchCalls.length>0||(a?.length??0)>0)&&(0,r.jsxs)(ci,{title:l("turn.dispatches"),summaryLine:cl(a,c.makers.length,d,l),folded:n,children:[e.dispatchCalls.length>0&&(0,r.jsx)(oH,{calls:e.dispatchCalls}),a&&a.length>0&&(0,r.jsx)(oH,{calls:a})]}),m&&(0,r.jsx)(ci,{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 cd="cuelo-chat-search",cu="cuelo-chat-search-active";function ch(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 cp({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)(()=>()=>{ch(cd,[]),ch(cu,[])},[]),(0,s.useLayoutEffect)(()=>{let t=n.current;if(!e||!w||!t){ch(cd,[]),ch(cu,[]),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=th(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(ch(cd,o),s<0){ch(cu,[]),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){ch(cu,[]),f&&c(u.item);return}let g=e.get(u.item)?.[u.k];if(ch(cu,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=th(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 cm({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)(cf,{question:e,position:t,count:p,active:e.item===o,focusable:e.item===f,onJump:a,onMoveFocus:m},e.item))})})}let cf=(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 cg({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 cx={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===cx[e.reason]?t(`chat.compactionReason.${e.reason}`):null;return(0,r.jsxs)(cg,{label:t("chat.compactionLabel"),tone:"accent",children:[t("chat.compactionProgress",{seconds:i}),l?` \xb7 ${l}`:""]})}function cy({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 cb=n(39092),cw=n.n(cb);let ck=["01","02","03"];function cj(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 cS(e,t,n){if(e&&"streaming"!==t){let r=rR(e);if(r){let e="failed"===t?"failed":"done",s=rl(ra(r$(r),r.id,e)?.stickers??[],null,()=>cj(n));return s?{src:s,alt:n6[e]}:null}}if(!e||"streaming"===t||!n4.includes(e))return null;let r="failed"===t?"failed":"done",s=e.slice(0,e.indexOf("(")).toLowerCase(),a=rl(ck.map(e=>`/stickers/${s}/${r}/${e}.webp`),null,()=>cj(n));return a?{src:a,alt:n6[r]}:null}let cC=new Map,cN=(0,s.createContext)(cC);function cT({utterances:e,children:t}){return(0,r.jsx)(cN.Provider,{value:e,children:t})}function cI({turnIndex:e,turnEntryId:t,sessionId:n,cwd:a,onOpenFile:i}){let l=(0,s.useContext)(cN).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)(cM,{utterance:e,sessionId:n,cwd:a,onOpenFile:i},e.key))}):null}function cM({utterance:e,sessionId:t,cwd:n,onOpenFile:a}){let i=sd(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??rU(e.provider),f=i?.alias.split("(",1)[0]?.trim(),g=i&&p&&p!==i.alias&&p!==f?`작업 \xb7 ${p}`:null,x=cS(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)(sm,{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)(nk,{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)(cw(),{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 cE=/^\[character-summon alias="([^"\r\n]+)" model="([^"\r\n]+)"(?: oauth-position="\d+")?\]\r?$/mu;function c$(e,t,n,r){if("string"!=typeof n)return[];let s=cE.exec(n),a=s?.[1],i=s?.[2];return a&&i?[{toolCallId:e,...t?{name:t}:{},alias:a,model:i,batchSize:r}]:[]}function cR(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(...c$(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(...c$(n.toolCallId,"name"in s&&"string"==typeof s.name?s.name:void 0,"task"in s?s.task:void 0,r))}return t}function cL(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 cA=/^agent:\/\/([^/?#]+)\/?$/i;function cP(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?cA.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 c_(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 cF=["greeting","utterance","message","text"],cz=function(e){let t=(0,s.useMemo)(()=>aU(),[]),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?cE.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=or(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",...cF]){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||c_(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=c_(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])},cW="web6",cO=[],cD=[],cH=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)(cD),a=(0,s.useRef)(""),i=e.sessionId??"",l=i.length>0;return(0,s.useEffect)(()=>{if(!l){a.current="",r(cD);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 cO;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 cO;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:`${cW}:${t.startedAt}:${t.finishedAt}`,turnIndex:e,provider:"web6",speakerId:`${cW}:${t.conversationId??"unknown"}`,text:a,status:"failed"})}return s.length>0?s:cO})(n,e.messages,i),[n,e.messages,i])},cU="lab:";function cB(e){return e.startsWith(cU)?e.slice(cU.length).split(":",1)[0]||null:null}let cq={now:()=>Date.now(),setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e)};function cV(e){return e.multi&&e.options.length>1}function cK(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 cJ(e,t){let n={};for(let[t,r]of e.hidden)cQ(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]:[]),cV(e)?s?[...a,s]:a:s||a[0]}}(e,s);void 0!==a&&cQ(n,e.name,a)}),n}function cG(e,t){let n={};for(let r of e.fields){if(!r.name||cX(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 cV(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,cX(t,r.name));e&&cQ(n,r.name,e)}return n}function cZ(e){return e.map(e=>e.text).join("")}function cY(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 cQ(e,t,n){Object.defineProperty(e,t,{value:n,enumerable:!0,writable:!0,configurable:!0})}function cX(e,t){return Object.hasOwn(e,t)?e[t]:void 0}let c0={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},c1={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)"},c2={minHeight:36,padding:"0 12px",borderRadius:"var(--radius-control)",background:"var(--bg)",color:"var(--text-muted)",cursor:"pointer"};function c4({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 c8({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 c5({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)(c4,{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)(c4,{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)(c4,{spans:t})},s)})},n))})})});case"image":return(0,r.jsx)(c8,{src:e.src,alt:e.alt})}}function c6({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)(c4,{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 c3({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)(c6,{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,cY(e,a,Number(t.target.value))),style:{...c1,height:36},children:e.options.map((e,t)=>(0,r.jsx)("option",{value:t,disabled:e.disabled,children:cZ(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)(c6,{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,cY(e,a,s)),style:g}),(0,r.jsx)("span",{children:(0,r.jsx)(c4,{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:{...c1,height:36,width:"calc(100% - 35px)",marginInlineStart:35}})]})]})})}function c7({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(c0,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)(c6,{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:{...c1,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:{...c1,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 c9({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(cK)),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=cq){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=cJ(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=cJ(o,c),w=h?cG(o,b):{},k=Object.keys(w).length>0,j=()=>{if(x)return;let n=cJ(o,u.current),r=cG(o,n);if(Object.keys(r).length>0){p(!0);let e=o.fields.findIndex(e=>""!==e.name&&void 0!==cX(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=cZ(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)(c4,{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)(c5,{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?cX(w,d.name):void 0,captionId:p,fallbackName:s||d.name,onChange:y});return"choice"===u.kind?(0,r.jsx)(c3,{...m,field:u},a):(0,r.jsx)(c7,{...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:c2,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 de={steer:"delivery.kind.steer",followUp:"delivery.kind.followUp"},dt={sending:"delivery.stage.sending",accepted:"delivery.stage.accepted",delivered:"delivery.stage.delivered",unconfirmed:"delivery.stage.unconfirmed",failed:"delivery.stage.failed"};function dn({rows:e,removeLabel:t,onRemove:n}){let a,{st:i}=sp(),[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=sD(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(de[e.kind])}),(0,r.jsx)("span",{className:"answer-delivery-text",title:a,children:a}),(0,r.jsx)("span",{className:"answer-delivery-stage",children:i(dt[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 ds=(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 A=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:A(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:{...A(!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:{...A(!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:A(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")})]})}),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:"M15.54 8.46a5 5 0 0 1 0 7.07"})]}),di=(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 dl({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?da:di})})})}let dc=RegExp("^(?:아|어|음|응|네|자|그럼|이제|일단|그만|좀|알았어|알겠어|아니|그래)*(?:(?:통화|전화)(?:를|좀|그만)*)?(?:좀|그만)*(?:끊어|끊어봐|끊을게|끊자|끊겠습니다|끊으라고)(?:줘|주세요|요)?$|^(?:아|어|음|응|네|자|그럼|이제|일단|그만|좀|알았어|알겠어|아니|그래)*(?:통화|전화)(?:를|좀|그만)*(?:종료|종료해|종료해봐|종료할게|종료하자|종료하라고)(?:줘|주세요|요)?$","u"),dd=["normal","slow"],du={idle:!0,connecting:!0,live:!0,working:!0,error:!0,closed:!0};function dh(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 dp(e,t){return 401===e||"live-auth"===t?"auth":502===e||"live-upstream"===t?"upstream":"failed"}let dm={unsupported:"chat.liveUnsupported","mic-denied":"chat.liveMicDenied","mic-unavailable":"chat.liveMicUnavailable",auth:"chat.liveAuthRequired",upstream:"chat.liveUpstreamFailed",failed:"chat.liveFailed"},df=(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"})]}),dg=(0,r.jsx)(r.Fragment,{children:(0,r.jsx)("rect",{x:"4",y:"4",width:"16",height:"16",rx:"3"})});function dx({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 dh(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(dp(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!==du[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&&dc.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?dm.unsupported:i.failure?dm[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?dg:df})})]})}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 dy({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 db=new Map,dw="ompweb-drafts-for-reload-v1",dk=!1,dj=new Map,dS=new Map,dC="\0stale",dN=new Map,dT=0,dI=new Map,dM=new Map,dE=new Map,d$=new Map,dR=new Map,dL=(e,t,n)=>sJ(e,t,n.length?{sentAttachmentIds:n}:{}),dA=null,dP=!1;function d_(){if(dk||"u"<typeof sessionStorage)return;dk=!0;let e=sessionStorage.getItem(dw);if(e){sessionStorage.removeItem(dw);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)&&(db.set(e[0],dz(t)),"string"==typeof t.draftId&&t.draftId&&(dj.set(e[0],t.draftId),dS.set(t.draftId,dC)),dK(e[0]))}}catch{}}}function dF(){if("u"<typeof sessionStorage)return{ok:!1,error:"sessionStorage unavailable"};try{return sessionStorage.setItem(dw,JSON.stringify([...db.entries()].map(([e,t])=>{let n=dj.get(e);return[e,n?{...dz(t),draftId:n}:dz(t)]}))),{ok:!0}}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}}function dz(e){return{value:e.value,images:e.images.map(e=>({...e})),documents:e.documents.map(e=>({...e}))}}function dW(e){return!e.value&&0===e.images.length&&0===e.documents.length}function dO(e){d_();let t=db.get(e);return t?dz(t):null}function dD(e,t){d_(),dW(t)?db.delete(e):db.set(e,dz(t)),dK(e)}function dH(e){db.delete(e),dK(e)}function dU(e,t,n,r,s,a=[]){let i=[...t??[],...r].filter(nH).slice(0,10).map(({data:e,mimeType:t})=>({data:e,mimeType:t})),l=sz([...s??[],...a]);return{value:e.trim()?n.trim()?`${e}
19
19
 
20
- ${n}`:e:n,images:i,documents:l}}function dB(e,t,n){if(e===t)return n?dz(n):dO(t);let r=dO(e),s=n&&!dW(n)?dz(n):r??(n?dz(n):null),a=dO(t),i=dj.get(e);if(dj.delete(e),i&&!dj.has(t)&&dj.set(t,i),dH(e),!s)return a;let l=a?dU(a.value,a.images,s.value,s.images,a.documents,s.documents):s;return dD(t,l),dz(l)}function dq(e){let t=[];for(let n of e??[])n.attachmentId&&!t.includes(n.attachmentId)&&t.push(n.attachmentId);return t}function dV(e){d_();let t=dj.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)}`}(),dj.set(e,t)),t}function dK(e){let t=dq(db.get(e)?.documents),n=t.length?dV(e):dj.get(e);for(let[e,n]of dM){for(let e of t)n.delete(e);0===n.size&&dM.delete(e)}let r=`${n??""}|${t.join(",")}`;d$.get(e)!==r&&(0!==t.length||n?d$.set(e,r):d$.delete(e),d0())}async function dJ(e){let t=dV(e);dI.set(t,(dI.get(t)??0)+1),await dR.get(t);let n=!1;return{draftId:t,end(e){if(n)return;n=!0;let r=(dI.get(t)??1)-1;if(r>0?dI.set(t,r):dI.delete(t),e){let n=dM.get(t)??new Set;n.add(e),dM.set(t,n)}dS.set(t,dC),d0()}}}function dG(e,t){let n=dE.get(e);if(!n)return[];for(let e of t)n.delete(e);return 0===n.size&&dE.delete(e),[...n].sort()}async function dZ(){if(!dL)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 dj)t(n,dq(db.get(e)?.documents));for(let{draftId:e,ids:n}of dN.values())t(e,n);for(let[e,n]of dM)t(e,n);for(let e of dS.keys())t(e,[]);for(let e of dE.keys())t(e,[]);return new Map([...e].map(([e,t])=>[e,[...t].sort()]))}()].filter(([e,t])=>{if(dI.has(e))return!1;let n=dS.get(e);return dG(e,t).length>0||(0===t.length?void 0!==n:n!==t.join(","))}),t=dI.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=dG(r,s),a=dL(r,s,e).then(()=>{0===s.length?dS.delete(r):dS.set(r,s.join(","));let t=dE.get(r);if(t){for(let n of e)t.delete(n);0===t.size&&dE.delete(r)}},()=>{n=!0,s.length>0&&(t=!0)});dR.set(r,a),await a,dR.get(r)===a&&dR.delete(r)}n?function(){if(dX)return;dX=!0;let e=setTimeout(()=>{dX=!1,d0()},dQ);"object"==typeof e&&"unref"in e&&e.unref(),dQ=Math.min(2*dQ,6e4)}():dQ=dY}let dY=5e3,dQ=5e3,dX=!1;function d0(){if(dL){if(dA){dP=!0;return}dA=Promise.resolve().then(dZ).finally(()=>{dA=null,dP&&(dP=!1,d0())})}}let d1=Math.floor(Number.MAX_SAFE_INTEGER/1048576),d2=Object.freeze({uploadLimitMb:100,autoCleanupEnabled:!0,orphanGraceDays:7});function d4(e){return"number"==typeof e&&Number.isSafeInteger(e)&&e>=1&&e<=d1}async function d8(e){let t,n=await e.json().catch(()=>null);if(!e.ok||!n||!d4(n.uploadLimitMb)||"boolean"!=typeof n.autoCleanupEnabled)throw Error("string"==typeof n?.error?n.error:`HTTP ${e.status}`);return{uploadLimitMb:d4((t=n&&"object"==typeof n?n:{}).uploadLimitMb)?t.uploadLimitMb:d2.uploadLimitMb,autoCleanupEnabled:"boolean"==typeof t.autoCleanupEnabled?t.autoCleanupEnabled:d2.autoCleanupEnabled,orphanGraceDays:7}}async function d5(e={}){return d8(await fetch("/api/attachment-settings",{cache:"no-store",signal:e.signal}))}async function d6(e){return d8(await fetch("/api/attachment-settings",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}))}function d3(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 d7(e){let t=0;for(let n=0;n<e.length;n++)"/"===e[n]&&t++;return t}function d9(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 ue(e,t){let n=t?`${e}/`:e;return n.includes(" ")?`@"${n}" `:`@${n} `}function ut(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 un="omp-web:model-picks";function ur(){try{let e=JSON.parse(window.localStorage.getItem(un)??"{}");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 us(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 ua(e,t,n){return Math.min(e*t,n)}function ui(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=us(s.top,s.bottom,n,ua(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 ul=n(14755);let uo="omp-web:model-roles-expanded";async function uc(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=[...uj,...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 ud(e){let t=e.transcription?.state;return"planning"===t||"confirm"===t||"running"===t}let uu=["off","default","full"],uh={off:"none",default:"default",full:"full"},up=ul.IN.join(" \xb7 "),um=ul.C1.filter(e=>!ul.IN.includes(e)).join(" \xb7 ");function uf(e){return"above"===e?{bottom:"calc(100% + 8px)"}:{top:"calc(100% + 8px)"}}let ug=new Intl.Collator(void 0,{numeric:!0,sensitivity:"base"}),ux=0,uv={"text/markdown":"Markdown","text/plain":"Text","application/pdf":"PDF"};function uy(e,t){return ug.compare(e.name||e.modelId,t.name||t.modelId)||ug.compare(e.provider,t.provider)||ug.compare(e.modelId,t.modelId)}let ub=["auto","off","minimal","low","medium","high","xhigh","max"],uw=["low","medium","high","xhigh"],uk={auto:"chat.thinkingAuto",off:"chat.thinkingOff",minimal:"chat.thinkingMinimal",low:"chat.thinkingLow",medium:"chat.thinkingMedium",high:"chat.thinkingHigh",xhigh:"chat.thinkingXhigh",max:"chat.thinkingMax"},uj=[{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"}],uS=["builtin","extension","custom","mcp_prompt","prompt","file","skill"],uC={builtin:"chat.builtIn",extension:"chat.extensions",custom:"chat.customCommands",mcp_prompt:"chat.mcpPrompts",prompt:"chat.prompts",file:"chat.fileCommands",skill:"chat.skills"},uN={builtin:0,extension:1,custom:2,mcp_prompt:3,prompt:4,file:5,skill:6};function uT(e,t,n){let r=e.name.toLowerCase(),s=uI(e,n).toLowerCase();return r===t?0:r.startsWith(t)?1:r.includes(t)?2:s.includes(t)?3:4}function uI(e,t){return"descriptionKey"in e?t(e.descriptionKey):e.description??""}function uM(e,t){return"skill"===e.source&&!!e.name.startsWith("skill:")&&!0===t[e.name.slice(6)]}function uE(e){return{data:e.data,mimeType:e.mimeType}}function u$(e){return{...e,previewUrl:`data:${e.mimeType};base64,${e.data}`}}function uR(e){return(e??[]).filter(nH).slice(0,10).map(u$)}let uL=/^File saved at: (.+)\n\(([^,\n]+), (\d+) bytes\)/,uA="\n\nTranscript of the audio ";function uP(e){return sz(e).map(e=>{let t=sq(e),n="audio"===t&&e.attachmentId&&!e.text.includes(uA)?uL.exec(e.text):null;return{...e,id:++ux,status:"ready",..."audio"===t||"file"===t?{stored:t}:{},...n?{storedInfo:{path:n[1],mimeType:n[2],size:Number(n[3])}}:{}}})}function u_({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 uF(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 uz extends Error{constructor(e,t,n,r){super(e),this.code=t,this.completedParts=n,this.parts=r}}let uW="composer:unkeyed";async function uO(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 uz("string"==typeof n.error?n.error:`HTTP ${e.status}`,"string"==typeof n.code?n.code:null,r,s)}function uD(e){e.previewUrl.startsWith("blob:")&&URL.revokeObjectURL(e.previewUrl)}function uH({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 uU({error:e}){return e?(0,r.jsx)(uH,{tone:"error",title:"Model error",body:e}):null}function uB({warnings:e}){return e&&0!==e.length?(0,r.jsx)(uH,{tone:"warning",title:e.length>1?"Model scope warnings":"Model scope warning",body:e.join("\n")}):null}let uq=(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:A,fastMode:P=null,fastModeBusy:_=!1,onFastModeToggle:z,retryInfo:W,deliveryRows:O=[],inputHistory:D=[],onRecallQueue:H,onRemoveQueuedMessage:B,slashCommands:q,slashCommandsLoading:V,onLoadSlashCommands:K,onBuiltinCommand:J,soundEnabled:G,onSoundToggle:Z,onAudioUnlock:Y,onPromptWithStreamingBehavior:Q,draftKey:X,cwd:ee,sessionTitle:et,sessionId:en,onEnsureSession:er,onLiveTranscriptPersisted:es},ea){let ei,el,eo,ec,ed,eu,eh,ep,em,ef,{t:eg}=(0,F.s)();su();let{st:ex}=sp(),ev=O.some(e=>e.removable),ey=U(),[eb,ew]=(0,s.useState)(()=>X?dO(X)?.value??"":""),[ek,ej]=(0,s.useState)(!1),[eS,eC]=(0,s.useState)(null),[eN,eT]=(0,s.useState)(""),[eI,eM]=(0,s.useState)({});(0,s.useEffect)(()=>{ek&&eM(ur())},[ek]);let[eE,e$]=(0,s.useState)(!1);(0,s.useEffect)(()=>{if(ek)try{e$("1"===window.localStorage.getItem(uo))}catch{}},[ek]);let eR=()=>{e$(e=>{let t=!e;try{window.localStorage.setItem(uo,t?"1":"0")}catch{}return t})},[eL,eA]=(0,s.useState)(!1),[eP,e_]=(0,s.useState)(null),[eF,ez]=(0,s.useState)(!1),[eW,eO]=(0,s.useState)(!1),[eD,eH]=(0,s.useState)(null),[eU,eB]=(0,s.useState)(!1),[eq,eV]=(0,s.useState)(()=>X?uR(dO(X)?.images):[]),[eK,eJ]=(0,s.useState)(()=>X?uP(dO(X)?.documents):[]),[eG,eZ]=(0,s.useState)(null),eY=(0,s.useMemo)(()=>eK.filter(e=>"ready"===e.status),[eK]),eQ=eK.some(e=>"ready"!==e.status||ud(e)),eX=eK.filter(e=>"audio"===e.stored&&e.attachmentId&&e.storedInfo&&(void 0!==e.transcription||!e.text.includes(uA))),e0=eb.trimStart(),e1=0===eq.length&&0===eK.length&&e0.startsWith("!"),e2=e1&&e0.startsWith("!!"),[e4,e8]=(0,s.useState)(!1),[e5,e6]=(0,s.useState)(0),[e3,e7]=(0,s.useState)(null),e9=e3?.value===eb&&e3.draftKey===X?e3.token:null,[te,tt]=(0,s.useState)(!1),[tn,tr]=(0,s.useState)(!1),ts=(0,s.useRef)(null),[ta,ti]=(0,s.useState)(null),[tl,to]=(0,s.useState)(!1),[tc,td]=(0,s.useState)(0),[tu,th]=(0,s.useState)(!1),[tp,tm]=(0,s.useState)(0),[tf,tg]=(0,s.useState)(null),[tx,tv]=(0,s.useState)(!1),[ty,tb]=(0,s.useState)(null),[tw,tk]=(0,s.useState)(null),tj=ee&&tw?.cwd===ee?tw.values:{},tS=(0,s.useRef)(null),tC=(0,s.useRef)(null),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),tA=(0,s.useRef)(null),tP=(0,s.useRef)(!1),t_=(0,s.useRef)(0),tF=(0,s.useRef)(!1),tz=(0,s.useRef)([]),tW=(0,s.useRef)([]),tO=(0,s.useRef)([]),tD=(0,s.useRef)(null),tH=(0,s.useRef)(null),tU=(0,s.useRef)(X),tB=(0,s.useRef)(eb),tq=(0,s.useRef)(eq),tV=(0,s.useRef)(0),tK=(0,s.useRef)(eK);tB.current=eb,tq.current=eq,tK.current=eK,(0,s.useImperativeHandle)(ea,()=>({insertIfEmpty(e){let t=tS.current;(t?t.value:eb).trim()||(tB.current=e,ew(e),ti(null),requestAnimationFrame(()=>{t&&(t.focus(),t.style.height="auto",t.style.height=`${Math.min(t.scrollHeight,200)}px`)}))},replaceMessage(e){let t,n,r=tS.current;if(!function(e,t,n,r=0){return!e.trim()&&0===t&&0===n&&0===r}(r?r.value:eb,tq.current.length,tV.current,tK.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"),sD(t)?.message??t),a=uR("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 nH(r)?[r]:[]})),i=uP((n="string"==typeof e.content?e.content:e.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n"),sD(n)?.documents??[]));tB.current=s,tq.current=a,tK.current=i,ew(s),ti(null),th(!1),eV(e=>(e.forEach(uD),a)),eJ(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(tU.current!==e)return void dB(e,t);let n={value:tB.current,images:tq.current.map(uE),documents:tK.current.filter(e=>"ready"===e.status).map(u_)},r=dB(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(tU.current=t,s)return;let a=uR(r.images),i=uF(uP(r.documents),tK.current),l=r.value;tB.current=l,tq.current=a,tK.current=i,ew(l),eV(e=>(e.forEach(uD),a)),eJ(i),ti(null),th(!1)},restoreSubmission(e,t,n,r){if(!e.trim()&&!t?.length&&!n?.length)return;let s=tU.current,a=r??s,i=a===s,l=!i&&a?dO(a):null,o=dU(e,t,i?tB.current:l?.value??"",i?tq.current.map(uE):l?.images??[],n,i?tK.current.filter(e=>"ready"===e.status).map(u_):l?.documents??[]);if(a&&dD(a,o),!i)return;let c=t?.length?[...uR(t).slice(0,Math.max(0,10-tq.current.length)),...tq.current].slice(0,10):tq.current,d=uF(uP(o.documents),tK.current);tB.current=o.value,tq.current=c,tK.current=d,ew(o.value),ti(null),th(!1),t?.length&&eV(e=>{let n=Math.max(0,10-e.length),r=uR(t).slice(0,n),s=r.length>0?[...r,...e]:e;return tq.current=s,s}),eJ(d),requestAnimationFrame(()=>{let e=tS.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=tS.current;if(!t)return void ew(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;tB.current=l,ew(l),ti(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){t9(e)}}));let tJ=(0,s.useCallback)(async e=>{let t=Math.max(0,10-tq.current.length-tV.current),n=e.filter(e=>e.size>0xa00000);n.length>0&&eZ(eg("chat.attachImageTooLarge",{name:n.map(e=>e.name).join(", "),limit:sH(0xa00000)}));let r=e.filter(e=>e.size<=0xa00000),s=r.slice(0,t);if(s.length<r.length&&eZ(eg("chat.attachImageLimit",{count:10})),s.length){tV.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)})));eV(t=>{let n=e.slice(0,Math.max(0,10-t.length));e.slice(n.length).forEach(uD);let r=[...t,...n];return tq.current=r,r})}finally{tV.current-=s.length}}},[eg]),tG=(0,s.useCallback)(async e=>{for(let t of e){let e=sA(t);if(!e)continue;if(tK.current.length>=3){eZ(eg("chat.attachLimit",{count:3}));continue}if(t.size>8388608){eZ(eg("chat.attachTooLarge",{name:t.name,limit:sH(8388608)}));continue}if(tK.current.reduce((e,t)=>e+t.size,0)+t.size>0x1000000){eZ(eg("chat.attachTotalTooLarge",{limit:sH(0x1000000)}));continue}let n={id:++ux,name:t.name,mimeType:s$[e],size:t.size,text:"",status:"extracting"},r=[...tK.current,n];tK.current=r,eJ(r);try{let e=await sW(t);if(tK.current.reduce((e,t)=>e+(t.id===n.id?0:t.text.length),0)+e.text.length>24e4)throw new sE("text_too_large","Total extracted text exceeds 240000 characters");let r=tK.current.map(t=>t.id===n.id?{...e,id:t.id,status:"ready"}:t);tK.current=r,eJ(r)}catch(s){let e=tK.current.some(e=>e.id===n.id),r=tK.current.filter(e=>e.id!==n.id);if(tK.current=r,eJ(r),!e)continue;s instanceof sE?"text_too_large"===s.code?eZ(eg("chat.attachTextTooLarge",{name:t.name,limit:12e4.toLocaleString()})):"too_many_pages"===s.code?eZ(eg("chat.attachTooManyPages",{name:t.name,limit:250})):"no_extractable_text"===s.code?eZ(eg("chat.attachNoPdfText",{name:t.name})):"password_protected"===s.code?eZ(eg("chat.attachPasswordProtected",{name:t.name})):eZ(eg("chat.attachExtractFailed",{name:t.name})):eZ(eg("chat.attachExtractFailed",{name:t.name}))}}},[eg]),tZ=(0,s.useCallback)((e,t)=>{if(!tK.current.some(t=>t.id===e))return!1;let n=t?tK.current.map(n=>n.id===e?t:n):tK.current.filter(t=>t.id!==e);return tK.current=n,eJ(n),!0},[]),tY=(0,s.useCallback)((e,t)=>{if(!tK.current.some(t=>t.attachmentId===e))return!1;let n=tK.current.map(n=>n.attachmentId===e?t(n):n);return tK.current=n,eJ(n),!0},[]),tQ=(0,s.useCallback)((e,t,n)=>{if(!e||e===tU.current)return;let r=dO(e);r?.documents.some(e=>e.attachmentId===t)&&dD(e,{...r,documents:uP(r.documents).map(e=>e.attachmentId===t?n(e):e).map(u_)})},[]),tX=(0,s.useRef)(new Map),t0=(0,s.useRef)(new Map),t1=(0,s.useRef)(new Set),t2=(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=sV({...e.storedInfo,transcript:t},r);return s.length>r?null:{...e,text:s,size:new TextEncoder().encode(s).byteLength,transcription:void 0}},[]),t4=(0,s.useCallback)(e=>e instanceof uz&&"media_tool_unavailable"===e.code?eg("chat.transcribeToolMissing"):e instanceof uz&&"transcription_failed"===e.code&&null!==e.completedParts&&null!==e.parts?eg("chat.transcribePartialFailed",{done:e.completedParts,total:e.parts}):e instanceof Error?e.message:String(e),[eg]),t8=(0,s.useCallback)(async(e,t)=>{let n=tU.current,r=tK.current.find(t=>t.attachmentId===e);if(!r?.storedInfo)return;let s=r.transcription?.state==="confirm"?r.transcription.plan:null;t0.current.get(e)?.abort();let a=new AbortController;t0.current.set(e,a),tY(e,e=>({...e,transcription:{state:"running",plan:s}}));try{let r=await uO(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 uz("Invalid transcription result",null,null,null);let s=r.transcript;tY(e,e=>t2(e,s,tK.current)??{...e,transcription:{state:"failed",error:eg("chat.transcribeTooLong")}})||tQ(n,e,e=>t2(e,s,[])??e)}catch(n){if(a.signal.aborted)return void tY(e,e=>({...e,transcription:{state:"skipped"}}));if(n instanceof uz&&"confirmation_required"===n.code)return void t5.current?.(e);let t=t4(n);tY(e,e=>({...e,transcription:{state:"failed",error:t}}))}finally{t0.current.get(e)===a&&t0.current.delete(e)}},[eg,t4,tY,tQ,t2]),t5=(0,s.useRef)(null),t6=(0,s.useCallback)(async e=>{let t;t0.current.get(e)?.abort();let n=new AbortController;t0.current.set(e,n),tY(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 uz("Invalid transcription plan",null,null,null);return{durationSeconds:e.durationSeconds,estimatedCalls:e.estimatedCalls,requiresConfirmation:e.requiresConfirmation,processing:e.processing,notice:e.notice}}(await uO(await fetch(`/api/attachments/${encodeURIComponent(e)}/transcription`,{cache:"no-store",signal:n.signal})))}catch(t){if(n.signal.aborted)tY(e,e=>({...e,transcription:{state:"skipped"}}));else{let n=t4(t);tY(e,e=>({...e,transcription:{state:"failed",error:n}}))}return}finally{t0.current.get(e)===n&&t0.current.delete(e)}t.requiresConfirmation?tY(e,e=>({...e,transcription:{state:"confirm",plan:t}})):await t8(e,!1)},[t8,t4,tY]);t5.current=t6;let t3=(0,s.useCallback)(e=>{let t=t0.current.get(e);t?t.abort():tY(e,e=>({...e,transcription:{state:"skipped"}}))},[tY]),t7=(0,s.useCallback)(async(e,t)=>{let n=null;for(let r of e){if(tK.current.length>=3){eZ(eg("chat.attachLimit",{count:3}));continue}let e="file"===t&&r.size<=8388608,s={id:++ux,name:r.name,mimeType:"text/plain",size:e?r.size:0,text:"",status:e?"extracting":"uploading",sourceSize:r.size},a=[...tK.current,s];tK.current=a,eJ(a);let i=(e,t)=>{let n=tK.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]?sF("utf-16le",t.subarray(2)):254===t[0]&&255===t[1]?sF("utf-16be",t.subarray(2)):t.includes(0)?null:sF("utf-8",t)??sF("euc-kr",t)},()=>null);if(null!==e&&i(e.length,r.size)){tZ(s.id,{...s,text:e,status:"ready"});continue}}if(null===n&&(n=1048576*(await d5().catch(()=>d2)).uploadLimitMb),r.size>n){tZ(s.id,null)&&eZ(eg("chat.attachStoredTooLarge",{name:r.name,limit:sH(n)}));continue}let l={...s,stored:t,status:"uploading",size:0};if(!tZ(s.id,l))continue;let o=tU.current??uW,c=await dJ(o),d=null,u=new AbortController;tX.current.set(s.id,u);try{if(t1.current.has(s.id))continue;let e=await sK(r,{sessionId:en,draftId:c.draftId,signal:u.signal}),n=tK.current.filter(e=>e.id!==s.id).reduce((e,t)=>e+t.text.length,0),a=sV({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)){tZ(s.id,null)&&eZ(eg("chat.attachTotalTooLarge",{limit:sH(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(tZ(s.id,p))d=e.id;else if(!t1.current.has(s.id)&&o!==tU.current){let t=dO(o)??{value:"",images:[],documents:[]};dD(o,{...t,documents:[...t.documents,u_(p)]}),d=e.id}}catch(e){if(u.signal.aborted)continue;tZ(s.id,null)&&eZ(eg("chat.attachUploadFailed",{name:r.name,error:e instanceof Error?e.message:String(e)}))}finally{tX.current.delete(s.id),c.end(d)}d&&"audio"===t&&tK.current.some(e=>e.attachmentId===d)&&t6(d)}},[tZ,t6,en,eg]),t9=(0,s.useCallback)(async e=>{eZ(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!==sA(a)?n.push(a):s_(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([tJ(t),tG(n.filter(e=>e.size<=8388608)),t7(r,"audio"),t7([...s,...a],"file")])},[tG,t7,tJ]),ne=(0,s.useCallback)(e=>{eV(t=>{let n=[...t],[r]=n.splice(e,1);return r&&uD(r),tq.current=n,n})},[]),nt=(0,s.useCallback)(e=>{let t=tK.current.find(t=>t.id===e);if(t1.current.add(e),tX.current.get(e)?.abort(),t?.attachmentId){t0.current.get(t.attachmentId)?.abort();var n=t.attachmentId;for(let[e,t]of dM)t.delete(n)&&(0===t.size&&dM.delete(e),d0())}let r=tK.current.filter(t=>t.id!==e);tK.current=r,eJ(r)},[]),nn=(0,s.useCallback)(()=>{tq.current=[],eV(e=>(e.forEach(uD),[]))},[]),nr=(0,s.useCallback)(()=>{tK.current=[],eJ([])},[]),ns=(0,s.useCallback)(()=>{tB.current="",ew(""),ti(null),e7(null),tt(!1),th(!1),X&&dH(X),tU.current&&tU.current!==X&&dH(tU.current),nn(),nr(),eZ(null),tS.current&&(tS.current.style.height="auto")},[nr,nn,X]);(0,s.useEffect)(()=>{X&&tU.current===X&&dD(X,{value:eb,images:eq.map(uE),documents:eY.map(u_)})},[eq,X,eY,eb]),(0,s.useEffect)(()=>{let e=tU.current;if(e===X)return;e&&dD(e,{value:tB.current,images:tq.current.map(uE),documents:tK.current.filter(e=>"ready"===e.status).map(u_)});let t=X?dO(X):null;tU.current=X;let n=t?.value??"",r=uR(t?.images),s=uP(t?.documents);tB.current=n,tq.current=r,tK.current=s,ew(n),ti(null),th(!1),eV(e=>(e.forEach(uD),r)),eJ(s)},[X]),(0,s.useEffect)(()=>{let e=tS.current;e&&(e.style.height="auto",eb&&(e.style.height=`${Math.min(e.scrollHeight,200)}px`))},[eb]),(0,s.useEffect)(()=>()=>{tq.current.forEach(uD)},[]);let na=(0,s.useCallback)((e,t)=>{let n=function(e,t){let n=dq(t);if(0===n.length)return()=>{};let r=++dT;return dN.set(r,{draftId:dV(e),ids:n}),e=>{if("accepted"!==e&&"returned"!==e)return;let t=dN.get(r);if(t){if(dN.delete(r),"accepted"===e){let e=dE.get(t.draftId)??new Set;for(let n of t.ids)e.add(n);dE.set(t.draftId,e)}d0()}}}(tU.current??uW,e);Promise.resolve(t()).then(e=>n("accepted"===e||"returned"===e?e:void 0),()=>void 0)},[]),ni=(0,s.useCallback)(async()=>{let t=eb.trim(),n=e0.trim(),r=n.startsWith("/")||n.startsWith("!")?n:t;if(!r&&!eq.length&&!eY.length||i||eQ)return;Y?.();let s=eq.length?eq:void 0,a=eY.length?eY:void 0;if(r.startsWith("/")){await uc(r,q,J,t=>na(a,()=>e(t,s,a)),eZ,!!(s||a),K)&&ns();return}ns(),na(a,()=>e(r,s,a))},[eb,e0,eq,eY,eQ,i,J,q,K,e,ns,Y,na]),nl=!e0.startsWith("/")||e0.startsWith("//")||/\s/.test(e0.slice(1))?null:e0.slice(1).toLowerCase(),no=(()=>{if(null===nl)return[];let e=[...i?[]:uj,...q??[]],t=new Set;return[...e].filter(e=>{let t=e.name.toLowerCase(),n=uI(e,eg).toLowerCase();return t.includes(nl)||n.includes(nl)}).sort((e,t)=>{let n=uT(e,nl,eg)-uT(t,nl,eg);return 0!==n?n:uN[e.source]-uN[t.source]||ug.compare(e.name,t.name)}).filter(e=>{let n=e.name.toLowerCase();return!t.has(n)&&(t.add(n),!0)})})(),{commands:nc,groups:nd}=(ei=0,{commands:(el=uS.map(e=>{let t=no.filter(t=>t.source===e),n="skill"===e?[...t.filter(e=>!uM(e,tj)),...t.filter(e=>uM(e,tj))]:t;return{source:e,items:n.map(e=>({command:e,index:ei++}))}}).filter(e=>e.items.length>0)).flatMap(e=>e.items.map(({command:e})=>e)),groups:el}),nu=1===no.length?eg(nl?"chat.match":"chat.command"):eg(nl?"chat.matches":"chat.commands",{count:no.length}),nh=!!eb.trim(),np=!eQ&&(nh||eq.length>0||eY.length>0),nm=(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(e7(n?{value:e,draftKey:X,token:n}:null),tr(!1),!ee)return void ti(null);let r=t??e.length;ti(d3(e.slice(0,r)))},[ee,X]),nf=ta?.query??null,ng=s.useMemo(()=>null!==nf&&tf&&tf.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:d9(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:d9(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||d7(e.entry.path)-d7(t.entry.path)||e.entry.path.localeCompare(t.entry.path)),s.slice(0,n).map(e=>e.entry)}(tf.entries,nf):[],[nf,tf,ee]),nx=!!(nf&&tf?.truncated&&tf.cwd===ee);(0,s.useEffect)(()=>{if(!nx||!ee||!nf)return;let e=setTimeout(()=>{fetch(`/api/file-index?cwd=${encodeURIComponent(ee)}&q=${encodeURIComponent(nf)}`).then(e=>{if(!e.ok)throw Error(`file search failed: ${e.status}`);return e.json()}).then(e=>tb({cwd:ee,query:nf,matches:e.matches??[]})).catch(()=>{})},150);return()=>clearTimeout(e)},[nx,nf,ee]);let nv=nx&&null!==ty&&ty.cwd===ee&&ty.query===nf,ny=nv?ty.matches:ng,nb=null===ta?null:`${ta.start}:${+!!ta.quoted}:${ta.query}`;(0,s.useEffect)(()=>{if(null===nb){to(!1),td(0);return}to(!0),td(0)},[nb]);let nw=null!==ta,nk=ui(tL,tu,{viewportFraction:.44,cap:360}),nj=ui(tL,e4,{viewportFraction:.56,cap:460}),nS=ui(tL,tl,{viewportFraction:.48,cap:400}),nC=ui(tL,te,{viewportFraction:.48,cap:400}),nN=e9?`${e9.start}:${e9.end}:${e9.query}`:null;(0,s.useEffect)(()=>{tt(null!==nN)},[nN]);let nT=(0,s.useCallback)((e,t,n,r=!1)=>{tB.current===e&&tU.current===X&&(tB.current=t,ew(t),e7(null),tt(!1),tr(r),requestAnimationFrame(()=>{let e=tS.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(!nw||!ee)return;let e=tD.current;e&&e.cwd===ee&&Date.now()-e.fetchedAt<1e4||tH.current===ee||(tH.current=ee,tv(!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=>{tg({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)=>d7(e.path)-d7(t.path)||e.path.localeCompare(t.path)),n}(e.files??[]),truncated:!!e.truncated}),tD.current={cwd:ee,fetchedAt:Date.now()}}).catch(()=>{tD.current=null}).finally(()=>{tH.current=null,tv(!1)}))},[nw,ee]);let nI=(0,s.useCallback)(e=>{if(!ta)return;let t=tS.current,n=t?.selectionStart??eb.length,r=eb.slice(0,ta.start),s=eb.slice(n);ta.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,ta.quoted),i=r+a.text+s,l=r.length+a.cursorOffset;ew(i),ti(d3(i.slice(0,l))),requestAnimationFrame(()=>{let e=tS.current;e&&(e.focus(),e.setSelectionRange(l,l),e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)})},[ta,eb]);(0,s.useEffect)(()=>{tc>=ny.length&&td(Math.max(0,ny.length-1))},[ny.length,tc]),(0,s.useEffect)(()=>{tW.current.length=ny.length},[ny.length]),(0,s.useEffect)(()=>{tl&&tW.current[tc]?.scrollIntoView({block:"nearest",inline:"nearest"})},[tc,tl]),(0,s.useEffect)(()=>{tp>=D.length&&tm(Math.max(0,D.length-1))},[D.length,tp]),(0,s.useEffect)(()=>{tO.current.length=D.length},[D.length]),(0,s.useEffect)(()=>{tu&&tO.current[tp]?.scrollIntoView({block:"nearest",inline:"nearest"})},[tp,tu]);let nM=(0,s.useCallback)(e=>{tB.current=e,ew(e),th(!1),tm(0),ti(null),requestAnimationFrame(()=>{let t=tS.current;t&&(t.focus(),t.setSelectionRange(e.length,e.length),t.style.height="auto",t.style.height=`${Math.min(t.scrollHeight,200)}px`)})},[]),nE=(0,s.useCallback)(e=>{let t=`/${e.name} `;tB.current=t,ew(t),e8(!1),e6(0),requestAnimationFrame(()=>{let e=tS.current;e&&(e.focus(),e.setSelectionRange(t.length,t.length),e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)})},[]),n$=(0,s.useCallback)(async e=>{let t=eb.trim(),r=e0.trim(),s=r.startsWith("/")||r.startsWith("!")?r:t,i=eQ||!s&&0===eq.length&&0===eY.length?null:{message:s,images:eq.length?eq:void 0,documents:eY.length?eY:void 0};if(!i)return;Y?.();let l="steer"===e?"steer":"followUp";if(s.startsWith("/")){await uc(s,q,J,e=>{if(!Q)throw Error("Cannot queue this command while the session is busy.");na(i.documents,()=>Q(e,l,i.images,i.documents))},eZ,!!(i.images?.length||i.documents?.length),K)&&ns();return}ns(),"steer"===e&&n?na(i.documents,()=>n(i.message,i.images,i.documents)):"followup"===e&&a&&na(i.documents,()=>a(i.message,i.images,i.documents))},[eb,e0,eq,eY,eQ,q,K,J,Q,n,a,ns,Y,na]),nR=(0,s.useCallback)(e=>{let t=nc.length-1;if(t<0)return 0;if("left"===e)return Math.max(0,e5-1);if("right"===e)return Math.min(t,e5+1);let n=tz.current[e5];if(!n)return"down"===e?Math.min(t,e5+1):Math.max(0,e5-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===e5)continue;let t=tz.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,e5+1):Math.max(0,e5-1)},[nc.length,e5]),nL=(0,s.useCallback)(e=>{let r=e.nativeEvent,s=Date.now()-t_.current<100,l=tP.current||r.isComposing||229===r.keyCode;if("Enter"===e.key&&!e.shiftKey&&(l||s)){s&&e.preventDefault();return}if(tu&&!l){if("ArrowDown"===e.key){e.preventDefault(),tm(e=>Math.min(Math.max(0,D.length-1),e+1));return}if("ArrowUp"===e.key){e.preventDefault(),tm(e=>Math.max(0,e-1));return}if("Escape"===e.key){e.preventDefault(),th(!1);return}if(("Tab"===e.key||"Enter"===e.key&&!e.shiftKey)&&D[tp]){e.preventDefault(),nM(D[tp]);return}}if(!(te&&e9&&!l&&ts.current?.handleKeyDown(e))){if(e4&&null!==nl){if("ArrowDown"===e.key){e.preventDefault(),e6(nR("down"));return}if("ArrowUp"===e.key){e.preventDefault(),e6(nR("up"));return}if("ArrowRight"===e.key){e.preventDefault(),e6(nR("right"));return}if("ArrowLeft"===e.key){e.preventDefault(),e6(nR("left"));return}if("Escape"===e.key){e.preventDefault(),e8(!1);return}if(("Tab"===e.key||"Enter"===e.key&&!e.shiftKey)&&nc[e5]){e.preventDefault(),nE(nc[e5]);return}}if(tl&&null!==ta&&!l){if("ArrowDown"===e.key){e.preventDefault(),td(e=>Math.min(Math.max(0,ny.length-1),e+1));return}if("ArrowUp"===e.key){e.preventDefault(),td(e=>Math.max(0,e-1));return}if("Escape"===e.key){e.preventDefault(),to(!1);return}if(("Tab"===e.key||"Enter"===e.key&&!e.shiftKey)&&ny[tc]){e.preventDefault(),nI(ny[tc]);return}}if("ArrowUp"===e.key&&!l&&!i&&D.length>0&&0===eb.trim().length){e.preventDefault(),e8(!1),to(!1),tm(D.length-1),th(!0);return}if("Escape"===e.key&&!l&&i&&t){e.preventDefault(),t();return}"Enter"!==e.key||e.shiftKey||(e.preventDefault(),i&&(n||a)?n$(n?"steer":"followup"):ni())}},[i,n,a,t,e4,nl,nc,e5,nE,n$,ni,nR,tl,ta,ny,tc,nI,tu,D,tp,nM,eb,te,e9]),nA=(0,s.useCallback)(()=>{let e=tS.current;e&&(e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)},[]),nP=(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(),t9(t))},[t9]);(0,s.useEffect)(()=>{if(null===nl){e8(!1),e6(0),tF.current=!1;return}e8(!0),e6(0),!tF.current&&K&&(tF.current=!0,Promise.resolve(K()).catch(()=>{tF.current=!1}))},[nl,K]),(0,s.useEffect)(()=>{if(!e4||!ee)return;let e=!1;return tk({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;tk({cwd:ee,values:n})}).catch(()=>{e||tk({cwd:ee,values:{}})}),()=>{e=!0}},[e4,ee]),(0,s.useEffect)(()=>{e5>=nc.length&&e6(Math.max(0,nc.length-1))},[nc.length,e5]),(0,s.useEffect)(()=>{tz.current.length=nc.length},[nc.length]),(0,s.useEffect)(()=>{e4&&tz.current[e5]?.scrollIntoView({block:"nearest",inline:"nearest"})},[e5,e4]);let n_=u&&u.length>0?u.map(e=>({provider:e.provider,modelId:e.id,name:e.name})).sort(uy):Object.entries(d??{}).map(([e,t])=>({provider:o?.provider??"unknown",modelId:e,name:t})).sort(uy),nF=g??null,nz=rf.find(e=>e.alias===nF)?.provider??null,nW=nz?n_.filter(e=>e.provider===nz):n_,nO=(eo=eN.trim().toLocaleLowerCase())?nW.filter(e=>`${e.name} ${e.modelId}`.toLocaleLowerCase().includes(eo)):nW,nD=nW.length>8,nU=[];for(let e of nO){let t=nU.find(t=>t.provider===e.provider);t?t.options.push(e):nU.push({provider:e.provider,options:[e]})}let nB=nz?[]:(x??[]).filter(e=>!e.hidden&&e.resolved),nq=o?nB.find(e=>e.resolved?.provider===o.provider&&e.resolved?.modelId===o.modelId):void 0,nK=eN.trim()?[]:nW.map((e,t)=>{var n,r;return{option:e,order:t,count:eI[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(ej(!1),eT(""),!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}(ur(),(t=e.provider,n=e.modelId,`${t}/${n}`));try{window.localStorage.setItem(un,JSON.stringify(r))}catch{}eM(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:eg("chat.modelPickCount",{count:n})})]},`${t}:${e.provider}:${e.modelId}`)},nG=o?n_.find(e=>e.modelId===o.modelId&&e.provider===o.provider)?.name??o.modelId:null,nZ=S?Math.max(0,S.tokensBefore-S.estimatedTokensAfter):0,nY=S?`${S.reason&&"manual"!==S.reason?`${S.reason[0].toUpperCase()}${S.reason.slice(1)} `:eg("chat.compacted")} ${nV(S.tokensBefore)} -> ${nV(S.estimatedTokensAfter)} tokens (${eg("chat.tokensSaved",{saved:nV(nZ)})})`:null,nQ=e=>{let t=A?.[e];return null!=t&&t!==e?t:null},nX="auto"===(ec=T??"auto")?$?`auto ≤ ${nQ($)??$}`:"auto":A?A[ec]??ec:ec,n0=(T??"auto")==="auto"&&I&&"auto"!==I?A?.[I]??I:null,n1=R&&n0?eg("chat.currentReasoning",{level:n0}):null,n2=e=>!L||L.includes(e),n4=[{level:"auto",ceiling:null},...uw.filter(n2).map(e=>({level:"auto",ceiling:e})),...ub.filter(e=>"auto"!==e&&n2(e)).map(e=>({level:e,ceiling:null}))],n8=Object.entries(uh).find(([,e])=>e===(C??"default"))?.[0]??"default";(0,s.useEffect)(()=>{let e=e=>{tC.current&&!tC.current.contains(e.target)&&tN.current&&!tN.current.contains(e.target)&&(ej(!1),eT("")),tT.current&&!tT.current.contains(e.target)&&tI.current&&!tI.current.contains(e.target)&&eA(!1),tM.current&&!tM.current.contains(e.target)&&ez(!1),tE.current&&!tE.current.contains(e.target)&&eO(!1),t$.current&&!t$.current.contains(e.target)&&eB(!1),!tR.current||tR.current.contains(e.target)||tS.current?.contains(e.target)||th(!1)};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[]),(0,s.useEffect)(()=>{ey||eB(!1)},[ey]);let n5=(0,r.jsx)("button",{type:"button",className:`composer-icon-button${eq.length||eK.length?" is-active":""}`,onClick:()=>tA.current?.click(),title:eg("chat.attachFile"),"aria-label":eg("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:eq.length||eK.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=eq.length||eK.length?"var(--accent)":"var(--text)"},onMouseLeave:e=>{e.currentTarget.style.background="none",e.currentTarget.style.color=eq.length||eK.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&&rf.length>0?(0,r.jsxs)("div",{ref:tT,style:{position:"relative",flexShrink:+!!ey,minWidth:0},children:[(0,r.jsxs)("button",{className:`${ey?"composer-icon-button":"composer-chip"}${eL?" is-active":""}`,onClick:e=>{let t=e.currentTarget.getBoundingClientRect();e_({top:t.top,bottom:t.bottom,left:t.left,width:t.width}),ej(!1),eT(""),eA(e=>!e)},disabled:i||y,"aria-haspopup":"menu","aria-expanded":eL,onKeyDown:e=>{"Escape"===e.key&&eL&&(e.stopPropagation(),eA(!1))},style:{display:"flex",alignItems:"center",gap:6,maxWidth:"100%",padding:"4px 8px",background:eL?"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=eL?"var(--bg-hover)":"none",e.currentTarget.style.color="var(--text-muted)"},title:eg("chat.mainPreset"),"aria-label":eg("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"})}),ey?null:(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:eg("chat.mainPreset")})]}),eL&&eP&&(()=>{let e=window.visualViewport?.height??window.innerHeight,{side:t,maxHeight:n}=us(eP.top,eP.bottom,e,ua(e,.6,460),{gap:6,prefer:"above"}),s="above"===t?{bottom:e-eP.top+6}:{top:eP.bottom+6},a=ey?{left:8,right:8,maxWidth:"calc(100vw - 16px)"}:{left:eP.left,width:"max-content",minWidth:eP.width};return(0,r.jsx)("div",{ref:tI,role:"menu","aria-label":eg("chat.mainPreset"),onKeyDown:e=>{"Escape"===e.key&&(eA(!1),tT.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:rf.map(e=>{let t=e.alias===nF;return(0,r.jsxs)("button",{role:"menuitemradio","aria-checked":t,onClick:()=>{eA(!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:rD(e.seed),width:20,height:20,alt:"","aria-hidden":"true",draggable:!1}),(0,r.jsx)("span",{children:rL(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:tE,style:{position:"relative",flexShrink:0,minWidth:0},children:[(0,r.jsxs)("button",{type:"button",className:`${ey?"composer-icon-button":"composer-chip"}${eW?" is-active":""}`,onClick:e=>{let t=e.currentTarget.getBoundingClientRect();eH({top:t.top,bottom:t.bottom,left:t.left,width:t.width}),ej(!1),eT(""),eA(!1),eO(e=>!e)},disabled:i||y,"aria-haspopup":"menu","aria-expanded":eW,onKeyDown:e=>{"Escape"===e.key&&eW&&(e.stopPropagation(),eO(!1))},title:eg("chat.changeReasoning",{level:nX}),"aria-label":eg("chat.changeReasoning",{level:nX}),style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,padding:ey?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"})]}),ey?null:(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:nX})]}),eW&&eD&&(()=>{let e=window.visualViewport?.height??window.innerHeight,{side:t,maxHeight:n}=us(eD.top,eD.bottom,e,ua(e,.6,460),{gap:6,prefer:"above"}),s="above"===t?{bottom:e-eD.top+6}:{top:eD.bottom+6},a=ey?{left:8,right:8,maxWidth:"calc(100vw - 16px)"}:{left:eD.left,width:"max-content",minWidth:Math.max(180,eD.width)};return(0,r.jsx)("div",{role:"menu","aria-label":eg("chat.changeReasoningLabel"),onKeyDown:e=>{"Escape"===e.key&&(eO(!1),tE.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?eg("chat.thinkingAutoCapped",{level:a??t}):eg(uk[e]);return(0,r.jsxs)("button",{type:"button",role:"menuitemradio","aria-checked":n,onClick:()=>{eO(!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=z?(ed=_?eg("chat.fastModeBusy"):null===P?eg("chat.fastModeUnknown"):P.active?eg("chat.fastModeActive"):P.enabled?eg("chat.fastModeInactive"):eg("chat.fastModeOff"),eu=_||i||y,eh=P?.enabled===!0,(0,r.jsx)("button",{type:"button",className:`composer-icon-button${P?.active?" is-active":""}`,onClick:z,disabled:eu,"aria-pressed":null===P?void 0:P.enabled,"aria-busy":_||void 0,title:ed,"aria-label":ed,style:{flexShrink:0,opacity:i?.5:1},children:(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:P?.active?"var(--accent)":"none",stroke:eh?"var(--accent)":"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",strokeDasharray:null===P?"3 2":void 0,style:{opacity:eh&&!P?.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:()=>n$("steer"),disabled:!np,title:eQ?eg("chat.attachExtractingWait"):eg("chat.steerTitle"),style:{display:"flex",alignItems:"center",gap:5,padding:"7px 12px",background:np?"var(--warning-soft)":"var(--bg-hover)",border:0,borderRadius:"var(--radius-control)",color:np?"var(--warning)":"var(--text-dim)",cursor:np?"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"})]}),eg("chat.steer")]}),a&&(0,r.jsxs)("button",{className:"composer-stream-action is-followup",onClick:()=>n$("followup"),disabled:!np,title:eQ?eg("chat.attachExtractingWait"):eg("chat.followUpTitle"),style:{display:"flex",alignItems:"center",gap:5,padding:"7px 12px",background:np?"var(--bg-selected)":"var(--bg-hover)",border:0,borderRadius:"var(--radius-control)",color:np?"var(--text)":"var(--text-dim)",cursor:np?"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"})]}),eg("chat.followUp")]})]}),re=void 0!==Z?(0,r.jsx)(dl,{soundEnabled:G??!0,onToggle:Z}):null;return(0,r.jsxs)("div",{className:"chat-composer",style:{flexShrink:0,background:"transparent",padding:"0 16px 8px"},children:[(0,r.jsx)("input",{ref:tA,type:"file",multiple:!0,style:{display:"none"},onChange:e=>{t9(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)(uU,{error:h}),(0,r.jsx)(uB,{warnings:p}),O.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:ex("delivery.title",{count:O.length})}),H&&ev&&(0,r.jsxs)("button",{onClick:H,title:eg("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"})]}),eg("chat.recall")]})]}),(0,r.jsx)(dn,{rows:O,removeLabel:eg("chat.queueRemove"),onRemove:B?(e,t)=>B("steer"===e?"steering":"followUp",t):void 0})]}),W&&(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"})]}),eg("chat.retrying",{attempt:W.attempt,max:W.maxAttempts}),W.errorMessage&&(0,r.jsxs)("span",{style:{opacity:.7,marginLeft:4},children:["— ",W.errorMessage]})]}),nY&&(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"})}),nY]}),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}),eG&&(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:eG}),(0,r.jsx)("button",{type:"button",onClick:()=>eZ(null),"aria-label":eg("i18n.close"),title:eg("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"})]})})]}),(eq.length>0||eK.length>0)&&(0,r.jsxs)("div",{role:"list","aria-label":eg("chat.attachments"),style:{display:"flex",alignItems:"center",gap:6,marginBottom:6,flexWrap:"wrap"},children:[eq.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":eg("chat.removeImage",{index:t+1}),onClick:()=>ne(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}`)),eK.map(e=>(0,r.jsxs)("div",{className:"composer-chip",role:"listitem","aria-busy":"ready"!==e.status||ud(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"}}):sS(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?eg("chat.attachKindAudio"):"file"===e.stored?eg("chat.attachKindFile"):uv[e.mimeType]," \xb7 ",sH(e.sourceSize??e.size),"extracting"===e.status?` \xb7 ${eg("chat.attachExtracting")}`:"","uploading"===e.status?` \xb7 ${eg("chat.attachUploading")}`:"",e.transcription?.state==="planning"?` \xb7 ${eg("chat.transcribeChecking")}`:"",e.transcription?.state==="confirm"?` \xb7 ${eg("chat.attachTranscribePending")}`:"",e.transcription?.state==="running"?` \xb7 ${eg("chat.attachTranscribing")}`:"",e.transcription?.state==="failed"&&(0,r.jsx)("span",{style:{color:"var(--danger)"},children:` \xb7 ${eg("chat.attachTranscribeFailed")}`})]})]}),(0,r.jsx)("button",{type:"button",onClick:()=>nt(e.id),"aria-label":eg("chat.removeAttachment",{name:e.name}),title:eg("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))]}),eX.length>0&&(0,r.jsx)("div",{role:"group","aria-label":eg("chat.transcribeGroup"),"aria-live":"polite",style:{display:"flex",flexDirection:"column",gap:6,marginBottom:6},children:eX.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?eg("chat.transcribePlanSummary",{duration:null===c.durationSeconds?eg("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"?eg("chat.transcribeConfirmTitle",{name:e.name}):o?.state==="running"?eg("chat.transcribeRunning",{name:e.name}):o?.state==="planning"?`${e.name} \xb7 ${eg("chat.transcribeChecking")}`:o?.state==="failed"?eg("chat.transcribeFailedRow",{name:e.name,error:o.error}):eg("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:eg("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 t8(i,!0),children:eg("chat.transcribeStart")}),(0,r.jsx)(l.r,{type:"button",variant:"neutralWeak",size:"small",onClick:()=>t3(i),children:eg("chat.transcribeSkip")})]}),(o?.state==="planning"||o?.state==="running")&&(0,r.jsx)(l.r,{type:"button",variant:"neutralWeak",size:"small",onClick:()=>t3(i),children:eg("chat.transcribeCancel")}),(void 0===o||"skipped"===o.state||"failed"===o.state)&&(0,r.jsx)(l.r,{type:"button",variant:"neutralWeak",size:"small",onClick:()=>void t6(i),children:eg(o?.state==="failed"?"chat.transcribeRetry":"chat.transcribeAction")})]})]},e.id)})}),(0,r.jsxs)("div",{ref:tL,style:{position:"relative",minWidth:0},children:[tu&&D.length>0&&(0,r.jsxs)("div",{ref:tR,style:{position:"absolute",left:0,right:0,...uf(nk.side),zIndex:120,background:"var(--bg-raised)",border:0,borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s3)",overflow:"hidden",maxHeight:nk.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,nk.maxHeight-31),overflowY:"auto",padding:4},children:D.map((e,t)=>{let n=t===tp;return(0,r.jsxs)("button",{ref:e=>{tO.current[t]=e},type:"button",onMouseDown:t=>{t.preventDefault(),nM(e)},onMouseEnter:()=>tm(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}`)})})]}),tn&&(0,r.jsx)("div",{role:"status",style:{fontSize:12,color:"var(--text-dim)",padding:"4px 8px"},children:eg("savedPrompts.saved")}),te&&e9&&(0,r.jsx)(ds,{ref:ts,value:eb,token:e9,cwd:ee,sessionTitle:et,style:uf(nC.side),maxHeight:nC.maxHeight,onReplace:nT,onClose:()=>tt(!1)}),e4&&null!==nl&&(0,r.jsxs)("div",{style:{position:"absolute",left:0,right:0,...uf(nj.side),zIndex:120,background:"var(--bg-raised)",border:0,borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s3)",overflow:"hidden",maxHeight:nj.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?eg("chat.loadingCommands"):eg("chat.slashCommands",{label:nu})}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},children:eg("chat.tabEnter")})]}),(0,r.jsx)("div",{style:{maxHeight:Math.max(0,nj.maxHeight-34),overflowY:"auto",padding:10},children:V||0!==no.length?nd.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:eg(uC[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===e5,s=uM(e,tj);return(0,r.jsxs)("button",{ref:e=>{tz.current[t]=e},type:"button",onMouseDown:t=>{t.preventDefault(),nE(e)},onMouseEnter:()=>e6(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:eg("chat.dormant")})]}),uI(e,eg)&&(0,r.jsx)("span",{style:{display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:2,overflow:"hidden",fontSize:11,lineHeight:1.35,color:"var(--text-dim)"},children:uI(e,eg)})]},`${e.source}:${e.name}`)})})]},e.source)):(0,r.jsx)("div",{style:{padding:"2px 2px 4px",fontSize:12,color:"var(--text-dim)"},children:eg("chat.noCommands")})})]}),tl&&null!==ta&&(ep=tx&&(!tf||tf.cwd!==ee),em=1===ny.length?eg("chat.match"):eg("chat.matches",{count:ny.length}),ef=tf?.truncated&&!nv?ta.query?eg("chat.searchingAll"):eg("chat.indexTruncated"):"",(0,r.jsxs)("div",{style:{position:"absolute",left:0,right:0,...uf(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.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:ep?eg("chat.loadingFiles"):eg("chat.files",{label:em,hint:ef})}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},children:eg("chat.tabEnter")})]}),(0,r.jsx)("div",{style:{maxHeight:Math.max(0,nS.maxHeight-34),overflowY:"auto",padding:4},children:ep||0!==ny.length?ny.map((e,t)=>{let n=t===tc,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(),nI(e)},onMouseEnter:()=>td(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)(sw,{size:14}):sS(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:nx&&!nv?eg("chat.searching"):eg("chat.noMatchingFiles")})})]})),(0,r.jsxs)("div",{className:`chat-composer-field${e1?" 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:tS,"aria-controls":te?"saved-prompt-menu":void 0,value:eb,onChange:e=>{tB.current=e.target.value,ew(e.target.value),th(!1),nm(e.target.value,e.target.selectionStart)},onSelect:e=>{let t=e.currentTarget;nm(t.value,t.selectionStart)},onKeyDown:nL,onCompositionStart:()=>{tP.current=!0},onCompositionEnd:e=>{tP.current=!1,t_.current=Date.now();let t=e.currentTarget;nm(t.value,t.selectionStart)},onInput:nA,onPaste:nP,placeholder:i&&(n||a)?eg("chat.steerPlaceholder"):i?eg("chat.agentPlaceholder"):eg("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?ey?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:ni,disabled:!np,"aria-busy":eQ||void 0,"aria-label":ey?eg("chat.send"):void 0,title:eQ?eg("chat.attachExtractingWait"):void 0,style:{flexShrink:0,alignSelf:"flex-end",display:"flex",alignItems:"center",justifyContent:"center",gap:6,minWidth:ey?44:void 0,padding:ey?0:"7px 14px",background:np?"var(--accent-soft)":"var(--bg-raised)",border:"none",borderRadius:"var(--radius-control)",color:np?"var(--accent-hover)":"var(--text-dim)",cursor:np?"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"})]}),ey?null:eg("chat.send")]})]})]}),e1&&(0,r.jsxs)("div",{className:"text-xs px-2 py-1",style:{color:e2?"var(--text-muted)":"var(--accent)",marginTop:4},children:[eg("chat.shell")," \xb7 ",e2?eg("chat.outputLocal"):eg("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:ey?"1 1 0%":"0 0 auto",minWidth:ey?"min-content":0,display:"flex",alignItems:"center",gap:2},children:[(!ey||!i)&&n5,!ey&&n6,!(ey&&i)&&(n_.length>0||nG||h)&&m&&(0,r.jsxs)("div",{ref:tC,style:{position:"relative",flex:ey?"1 1 0%":void 0,width:ey?0:void 0,minWidth:44*!!ey},children:[(0,r.jsxs)("button",{className:`composer-chip${ek?" is-active":""}`,onClick:e=>{let t=e.currentTarget.getBoundingClientRect();eC({top:t.top,bottom:t.bottom,left:t.left,width:t.width}),ej(e=>(e&&eT(""),!e))},disabled:i||y,"aria-busy":y||void 0,style:{display:"flex",alignItems:"center",gap:6,justifyContent:ey?"flex-start":void 0,padding:ey?"8px 10px":"8px 12px",height:32,width:ey?"100%":void 0,maxWidth:ey?"100%":220,overflow:"hidden",background:ek?"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=ek?"var(--bg-hover)":"none",e.currentTarget.style.color="var(--text-muted)"},title:y?"Switching model":n_.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??(n_.length>0?"Select model":"No models")})]}),ek&&eS&&(()=>{let e=window.visualViewport?.height??window.innerHeight,{side:t,maxHeight:n}=us(eS.top,eS.bottom,e,ua(e,.6,460),{gap:6,prefer:"above"}),s="above"===t?{bottom:e-eS.top+6}:{top:eS.bottom+6},a=ey?{left:8,right:8,maxWidth:"calc(100vw - 16px)"}:{left:eS.left,width:"max-content",minWidth:eS.width};return(0,r.jsxs)("div",{ref:tN,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:[nD&&(0,r.jsx)("div",{style:{padding:"6px 8px",flexShrink:0},children:(0,r.jsx)("input",{value:eN,onChange:e=>eT(e.target.value),onKeyDown:e=>{"Escape"===e.key&&(eT(""),ej(!1))},placeholder:eg("chat.filterModels"),"aria-label":eg("chat.filterModels"),autoFocus:!0,autoComplete:"off",spellCheck:!1,style:{width:"100%",minWidth:220*!ey,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:eg("chat.frequentModels")}),nK.map(({option:e,count:t})=>nJ(e,"frequent",t))]}),nB.length>0&&!eN.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":eE,"aria-controls":"model-role-rows",onClick:eR,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:eE?"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:eg("chat.modelRoles")}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},children:nB.length}),nq&&(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:nq.tag??nq.role.toUpperCase()}),nq.name]})]}),(0,r.jsx)("div",{id:"model-role-rows",hidden:!eE,children:nB.map(e=>{let t=nq?.role===e.role,n=e.resolved?.name??e.resolved?.modelId??"";return(0,r.jsxs)("button",{onClick:()=>{ej(!1),eT(""),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:eg("chat.allModels")})]}),0===nU.length?(0,r.jsx)("div",{style:{padding:"8px 12px",color:"var(--text-dim)",fontSize:12,whiteSpace:"nowrap"},children:eN.trim()?eg("chat.noMatchingModels"):"No available models"}):nU.map((e,t)=>(0,r.jsxs)("div",{children:[nU.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))]})]})})()]}),ey&&i&&(0,r.jsx)("div",{style:{display:"flex",alignItems:"center",gap:6,minWidth:0},children:n9}),!ey&&n3,!ey&&n7,!ey&&n1&&(0,r.jsx)("span",{style:{flexShrink:0,padding:"0 6px",fontSize:12,color:"var(--text-muted)",whiteSpace:"nowrap"},children:n1}),!ey&&null!==M&&(0,r.jsx)("span",{title:eg(E?"chat.outputSpeedLiveTitle":"chat.outputSpeedTitle"),style:{flexShrink:0,padding:"0 6px",fontSize:12,color:"var(--text-muted)",whiteSpace:"nowrap",fontVariantNumeric:"tabular-nums"},children:eg(E?"chat.outputSpeedLive":"chat.outputSpeed",{rate:M>=10?Math.round(M):M.toFixed(1)})}),(0,r.jsx)(dy,{sessionId:en})]}),(0,r.jsxs)("div",{ref:t$,style:{flex:"0 1 auto",minWidth:0,display:"flex",alignItems:"center",justifyContent:"flex-end",position:"relative",marginLeft:"auto",gap:ey?4:2},children:[ey?(0,r.jsx)("button",{type:"button",className:`composer-icon-button${eU?" is-active":""}`,title:eg("chat.moreControls"),"aria-label":eg("chat.moreControls"),"aria-expanded":eU,onClick:()=>{ej(!1),eT(""),eB(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:eU?void 0:eg("chat.moreControls"),"aria-label":eg("chat.moreControls"),"aria-expanded":eU,onClick:()=>{ej(!1),eT(""),eB(e=>!e)},children:eg("chat.moreControls")}),(0,r.jsxs)("div",{className:"composer-run-options",role:"group","aria-label":eg("chat.moreControls"),style:{display:eU?ey?"grid":"flex":"none",gridTemplateColumns:ey?"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:[ey&&(0,r.jsxs)(r.Fragment,{children:[i&&n5,n6,n3,n7]}),!i&&N&&(0,r.jsxs)("div",{ref:tM,style:{position:"relative"},children:[(0,r.jsxs)("button",{className:`composer-chip${eF?" is-active":""}`,onClick:()=>!i&&ez(e=>!e),disabled:i,title:eg("chat.changeToolPreset")+`: ${n8}`,"aria-label":eg("chat.changeToolPreset"),style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,padding:"8px 12px",height:32,background:eF?"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=eF?"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})]}),eF&&(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:uu.map(e=>{let t=uh[e],n=(C??"default")===t,s="off"===e?eg("chat.noTools"):"default"===e?eg("chat.builtInTools",{tools:up}):eg("chat.allBuiltInTools",{tools:`${up} + ${um}`});return(0,r.jsxs)("button",{onClick:()=>{ez(!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?eg("chat.stopCompaction"):eg("chat.compactContext"),"aria-label":k?eg("chat.stopCompaction"):eg("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:eg("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:eg("chat.compact")})]})})}),ey&&re,eU&&!ey&&(0,r.jsx)("button",{className:"composer-icon-button is-active",type:"button",title:eg("chat.collapseControls"),"aria-label":eg("chat.collapseControls"),"aria-expanded":!0,onClick:()=>{ez(!1),eO(!1),eB(!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:eg("chat.stopAgent"),"aria-label":ey?eg("chat.stopAgent"):void 0,style:{display:"flex",alignItems:"center",justifyContent:"center",gap:6,minWidth:ey?44:void 0,padding:ey?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"})}),ey?null:eg("chat.stop")]}),(0,r.jsx)(dx,{sessionId:en,onEnsureSession:er,onTranscriptPersisted:es}),!ey&&re]})]})]})]})});function uV({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=eA(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:eW(t).map((e,t)=>(0,r.jsx)("span",{style:e.style,children:e.text},t))})})}function uK({phases:e,flow:t,busy:n}){let{t:a}=(0,F.s)(),{st:i}=sp(),[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}=t_(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)(oC,{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)(sv,{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 uJ(e=document){return"visible"!==e.visibilityState||!e.hasFocus()}function uG(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 uZ(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 uY extends Error{constructor(e,t,n,r){super(e),this.status=t,this.code=n,this.accepted=r,this.name="AgentCommandError"}}async function uQ(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 uY(r.error??`HTTP ${n.status}`,n.status,r.code,r.accepted);return r.data}let uX="ompweb-update-client-id",u0="ompweb-update-resume-intent-v2",u1="ompweb-update-return-v1",u2="cuelo-restart-return-v1",u4="ompweb-update-failure-return-v1",u8="ompweb:update-wake";function u5(e){return null===e?2e4:"running"===e?null:"failed"===e?3e4:8e3}function u6(){let e=sessionStorage.getItem(uX);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(uX,t),t}function u3(){sessionStorage.removeItem(u0)}function u7(){let e=sessionStorage.getItem(u1);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 u9(e){let t=u7();if(!t||t.requestId!==e)return t;let n={...t,dismissed:!0};try{sessionStorage.setItem(u1,JSON.stringify(n))}catch{}return n}async function he(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:u6(),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 ht(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=u7();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(u1,JSON.stringify(n))}catch{}}({requestId:e.requestId,stageHash:e.stageHash}),u3();let r=n?.wake;e.sessionId&&(r?.wake===!0||r?.reason==="already-claimed"||r?.reason==="user-already-active")&&window.dispatchEvent(new CustomEvent(u8,{detail:{sessionId:e.sessionId}}))}async function hn(e){let t=function(e){let t=sessionStorage.getItem(u4);if(!t)return null;sessionStorage.removeItem(u4);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?(u3(),t.wake&&e.sessionId&&window.dispatchEvent(new CustomEvent(u8,{detail:{sessionId:e.sessionId}})),"failed"):(await ht(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 hs(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 ha(e){return{steering:e?.steering??[],followUp:e?.followUp??[]}}function hi(e){if(e&&"boolean"==typeof e.fastModeEnabled)return{enabled:e.fastModeEnabled,active:!0===e.fastModeActive}}function hl(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 ho(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 hc(e){return"aborted"===e.stopReason?"aborted":"error"===e.stopReason||e.errorMessage?"failed":e.stopReason?"completed":"unknown"}function hd(e,t){for(let n=e.length-1;n>=0;n--){let r=t[n]??null;if(!ti(r??void 0))return{message:e[n],entryId:r}}return null}let hu=new Set(["ArrowUp","ArrowDown","PageUp","PageDown","Home","End"," ","Space","Spacebar"]);class hh 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 hp(){return"u">typeof crypto&&"function"==typeof crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2)}`}function hm(e){return new Promise(t=>setTimeout(t,e))}function hf(e){let t=e.findIndex(e=>!e.exiting);return -1===t?e:e.map((e,n)=>n===t?{...e,exiting:!0}:e)}function hg(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:hf(e.visible),pending:[...e.pending,t.notice]};return{...e,visible:[...e.visible,t.notice]};case"mark_oldest_exiting":return{...e,visible:hf(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=hf(n)),{visible:n,pending:r}}(e.visible.filter(e=>e.id!==t.id),e.pending);default:return e}}function hx(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 hv(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(hx).filter(Boolean)}):JSON.stringify({text:"",images:[]})}function hy(e){return"user"===e.role?`user:${hv(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 hb(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 hw(e){return e?.map(({data:e,mimeType:t})=>({data:e,mimeType:t}))}function hk(e){nM(e),e.clear()}function hj(e,t,n){for(let r of n??[]){let n=nI(t,r);n&&e.add(n)}}function hS(){let e=document.activeElement;return e instanceof HTMLElement&&(e.isContentEditable||"INPUT"===e.tagName||"SELECT"===e.tagName||"TEXTAREA"===e.tagName)}let hC=!1,hN={width:0,height:0},hT=new Set,hI=null;function hM(){let e=window.visualViewport,t=hS();hN.width!==window.innerWidth?hN={width:window.innerWidth,height:window.innerHeight}:t||(hN.height=Math.max(hN.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:hN.height});if(n!==hC)for(let e of(hC=n,hT))e()}function hE(e){if(hT.add(e),!hI){let e=null,t=()=>{null!==e&&window.cancelAnimationFrame(e),e=window.requestAnimationFrame(()=>{e=null,hM()})},n=window.visualViewport;n?.addEventListener("resize",t),window.addEventListener("resize",t),window.addEventListener("focusin",t),window.addEventListener("focusout",t),hM(),hI=()=>{n?.removeEventListener("resize",t),window.removeEventListener("resize",t),window.removeEventListener("focusin",t),window.removeEventListener("focusout",t),null!==e&&window.cancelAnimationFrame(e)}}return()=>{hT.delete(e),0===hT.size&&hI&&(hI(),hI=null)}}function h$(){return(0,s.useSyncExternalStore)(hE,()=>hC,()=>!1)}let hR={count:50,end:null};function hL(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 hA(e,t,n){let{startIndex:r,endIndex:s}=hL(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 hP({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:n6[n]}),t&&(0,r.jsx)("p",{className:e?"cue-bubble":"cue-bubble cue-bubble--solo",children:t}),e&&(0,r.jsx)(cw(),{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 h_(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=(sD(t)?.message??t).trim();return n.length>0?n:null}function hF(e){return`omp-cues:${e}`}function hz(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(hF(e),JSON.stringify(n.slice(-200)))}catch{}}let hW=[];function hO(e){return`omp-web:interrupted-dismissed:${e}`}let hD=(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=ts(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=td(s.action);if(!0===tc[e]){let t={kind:"skill",action:e,name:td(s.name)};n(JSON.stringify(t),t)}continue}let a=td(s.memory),i=s.skill,l=i?{action:td(i.action),name:td(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:tn,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&&ti(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)(s9,{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:eZ(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)(hP,{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)(s9,{message:b,cwd:i,onOpenFile:l},`saved-lessons-${c}`):null,k=x?(0,r.jsx)(cI,{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=tM(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=eK(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)(cn,{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 hH({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,onOpenMaker:C,selectedMaker:N,onProcessLogChange:T,onOpenFile:I,transcriptReplacement:M,onComposerFocusChange:E,onSessionBusyChange:$,onWaitingChange:R,onAttentionChange:L,soundEnabled:A=!0,onSoundToggle:P,playCueSound:_=async()=>({sticker:null,text:null}),preloadCueSound:z,unlockAudio:W,jumpRequest:O=null,onJumpHandled:D,turnInspectorTarget:H=null,onShowTurnInspector:B,turnInspectorFolded:q=!1}){var V,K;let J,G,Z,{t:Y}=(0,F.s)(),Q=h$(),X=U(),et=Q&&X,en=(0,s.useRef)(_);en.current=_;let er=(0,s.useRef)(null),es=(0,s.useRef)(z);es.current=z;let[ea,el]=(0,s.useState)([]),eo=(0,s.useRef)(ea);eo.current=ea;let ec=(0,s.useRef)(0),ed=(0,s.useRef)([]),eu=(0,s.useRef)([]),eh=(0,s.useRef)(null),ep=(0,s.useRef)(0),em=(0,s.useRef)(-1),ef=(0,s.useRef)(-1),eg=(0,s.useCallback)(()=>{let e=eh.current?.current;return e?{sessionId:e,turn:ep.current}:null},[]),ex=(0,s.useCallback)(e=>eh.current?.current===e.sessionId&&ep.current===e.turn,[]),ev=(0,s.useCallback)((e,t,n,r)=>{if(!e.sticker&&!e.text)return;ec.current=Math.max(ec.current+1,Date.now());let s={id:ec.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};el(e=>{let t=[...e,a];return null!==a.anchorEntryId&&hz(n.sessionId,t),t})},[]),ey=(0,s.useCallback)((e,t,n,r)=>{let s=()=>ex(n)&&("working"!==t||ef.current!==n.turn);s()&&en.current(e,t,s).then(e=>{null!==t&&null!==r&&s()&&ev(e,t,n,r)}).catch(()=>{})},[ex,ev]),eb=(0,s.useCallback)(async(e,t,n,r)=>{let s=(await sc(e,t,n,r))?.alias??null;return s&&es.current?.(s),s},[]),ew=(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=ro(e[n]),a=0;for(let t=r;t<=n;t++)ro(e[t])===s&&(a+=1);return{kind:"pending",liveIndex:n,intent:{baseEntryId:r>0?t[r-1]:null,identity:s,occurrence:a}}}(ed.current,eu.current);eb(t.sessionId,n,r,s).then(n=>{ey(n,e,t,a)})},[ey,eb]),[ek,ej]=(0,s.useState)(0),eS=(0,s.useRef)([]),eC=(0,s.useCallback)(e=>{if(ep.current+=1,null!==re(e.outcome)){let t=e.sessionId;eS.current.push({completion:e,trigger:t?{sessionId:t,turn:ep.current}:null}),ej(e=>e+1)}c?.(e)},[c]);(0,s.useEffect)(()=>{for(let{completion:e,trigger:t}of eS.current.splice(0)){let n=re(e.outcome),r="neutral"===n?null:n;t?ew(r,t,e.provider,e.credentialId,e.model):en.current(null,r).catch(()=>{})}},[ek,ew]);let eN=(0,s.useCallback)(e=>{m?.current?.replaceMessage(e)},[m]),{loading:eT,error:eI,messages:eM,entryIds:eE,streamState:e$,agentRunning:eR,bashRunning:eL,pendingBash:eP,modelNames:e_,modelList:eF,modelError:ez,modelScopeWarnings:eW,modelThinkingLevels:eO,modelThinkingLevelMaps:eD,modelRoles:eH,toolPreset:eU,thinkingLevel:eB,effectiveThinkingLevel:eq,thinkingCeiling:eV,fastMode:eJ,fastModeBusy:eX,handleFastModeToggle:e0,retryInfo:e4,contextUsage:e8,forkingEntryId:e6,isCompacting:e3,compaction:tn,compactError:tc,compactResult:td,displayModel:th,modelSwitching:tp,sessionStats:tm,runStateKnown:tf,compactedWork:tg,slashCommands:tx,slashCommandsLoading:tv,deliveryRows:ty,subagents:tb,todoPhases:tw,notices:tk,extensionDialog:tj,extensionResponse:tS,extensionCustomUi:tC,extensionStatuses:tN,extensionWidgets:tT,respondToExtensionUi:tI,sendExtensionCustomInput:tM,isAutoModelSelection:tE,agentPhase:t$,isNew:tR,autoFollowPaused:tL,resumeAutoFollow:tP,pauseAutoFollow:t_,goalStatus:tF,sessionIdRef:tz,messagesEndRef:tO,scrollContainerRef:tD,handleSend:tH,handleAbort:tU,handleFork:tB,handleNavigate:tq,handleModelChange:tV,handleRoleModelChange:tK,handleMainPresetChange:tJ,newSessionAccount:tG,handleCompact:tZ,handleSteer:tY,handleFollowUp:tQ,handlePromptWithStreamingBehavior:tX,handleAbortCompaction:t0,handleRecallQueue:t1,handleRemoveQueuedMessage:t2,handleBuiltinSlashCommand:t4,handleToolPresetChange:t8,handleThinkingLevelChange:t5,loadSlashCommands:t6,ensureNewSession:t3,refreshLiveTranscript:t7}=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=null===t&&null!==r,f=a&&a.sessionId===t?.id?a:null,[g,x]=(0,s.useState)(f),[v,y]=(0,s.useState)(!m&&!f),[b,w]=(0,s.useState)(null),[k,j]=(0,s.useState)(f?.leafId??null),[S,C]=(0,s.useState)(f?.context.messages??[]),[N,T]=(0,s.useState)(f?.context.entryIds??[]),[I,M]=(0,s.useState)(f?.context.compactedWork??null),[E,$]=(0,s.useReducer)(hs,{isStreaming:!1,streamingMessage:null}),[R,L]=(0,s.useState)(!1),[A,P]=(0,s.useState)(!1),[_,F]=(0,s.useState)(null),[z,W]=(0,s.useState)({}),[O,D]=(0,s.useState)([]),[H,U]=(0,s.useState)(null),[B,q]=(0,s.useState)([]),[V,K]=(0,s.useState)({}),[J,G]=(0,s.useState)({}),[Z,Y]=(0,s.useState)([]),[Q,X]=(0,s.useState)(null),[ee,et]=(0,s.useState)(null),[en,er]=(0,s.useState)(null),[es,ea]=(0,s.useState)("default"),[el,eo]=(0,s.useState)(()=>{let e=f?.context.thinkingLevel;return e&&"off"!==e?e:"auto"}),[ec,ed]=(0,s.useState)(),[eu,eh]=(0,s.useState)(null),[ep,em]=(0,s.useState)(null),[ef,eg]=(0,s.useState)(!1),ex=(0,s.useRef)(0),ev=(0,s.useRef)(0),ey=(0,s.useRef)(""),[eb,ew]=(0,s.useState)(null),[ek,ej]=(0,s.useState)(f?.contextUsage??null),[eS,eC]=(0,s.useState)(null),[eN,eT]=(0,s.useState)(null),[eI,eM]=(0,s.useState)(null),[eE,e$]=(0,s.useState)(null),[eR,eL]=(0,s.useState)(!1),[eP,e_]=(0,s.useState)(!1),[eF,ez]=(0,s.useState)(null),[eW,eO]=(0,s.useState)(null),[eD,eH]=(0,s.useState)(null),eU=(0,s.useRef)(null),[eB,eq]=(0,s.useState)(!1),[eV,eK]=(0,s.useState)(null),[eJ,eG]=(0,s.useState)([]),[eZ,eY]=(0,s.useState)(!1),[eQ,eX]=(0,s.useReducer)(hg,{visible:[],pending:[]}),[e0,e1]=(0,s.useState)(null),[e2,e4]=(0,s.useState)(null),e8=(0,s.useRef)(null),e5=(0,s.useRef)(null),[e6,e3]=(0,s.useState)(null),e7=(0,s.useRef)(null),[e9,te]=(0,s.useState)(null),[tn,tr]=(0,s.useState)([]),[ts,to]=(0,s.useState)([]),[tc,td]=(0,s.useState)({steering:[],followUp:[]}),[tu,th]=(0,s.useState)([]),[tp,tm]=(0,s.useReducer)(lO,[]),tf=(0,s.useRef)(0);(0,s.useEffect)(()=>{tm({type:"queue",steering:tc.steering,followUp:tc.followUp})},[tc]),(0,s.useEffect)(()=>{R||tm({type:"idle"})},[R]),(0,s.useEffect)(()=>{tm({type:"reset"})},[t?.id]);let tg=(0,s.useMemo)(()=>(function(e,t){let n=new Map;for(let t of e){if(!t.inQueue)continue;let e=`${t.kind}\u0000${lz(t)}`;n.set(e,(n.get(e)??0)+1)}let r=[],s=(e,t)=>{t.forEach((t,s)=>{let a=`${e}\u0000${lF(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})(tp,tc),[tp,tc]),[tx,tv]=(0,s.useState)(null),ty=(0,s.useRef)(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)(0),tC=(0,s.useRef)(!1),tN=(0,s.useRef)(t?.id??null),tT=(0,s.useRef)(f?.leafId??null),tI=(0,s.useRef)(S),tM=(0,s.useRef)(N);tI.current=S,tM.current=N;let tE=(0,s.useRef)({sessionId:t?.id??null,outputs:[],seq:0}),t$=(0,s.useRef)(!1),tR=(0,s.useRef)(new Set);(0,s.useEffect)(()=>()=>hk(tR.current),[]);let tL=(0,s.useRef)(!1),tA=(0,s.useRef)(!1),tP=(0,s.useRef)(-1),t_=(0,s.useRef)("unknown"),tF=(0,s.useRef)(null),tz=(0,s.useRef)(null),tW=(0,s.useRef)(0),tO=(0,s.useRef)(!1),tD=(0,s.useRef)(0),tH=(0,s.useRef)(null),tU=(0,s.useRef)(null),tB=(0,s.useRef)(null),tq=(0,s.useRef)(!1),tV=(0,s.useRef)(!0),[tK,tJ]=(0,s.useState)(!1),[tG,tZ]=(0,s.useState)(null),tY=(0,s.useRef)(void 0),tQ=(0,s.useRef)(0),tX=(0,s.useRef)(null),t0=(0,s.useRef)(0),t1=(0,s.useRef)(()=>{}),t2=(0,s.useRef)(null),t4=(0,s.useRef)(null),t8=(0,s.useRef)(null),t5=(0,s.useRef)(null),t6=(0,s.useRef)(!1),t3=(0,s.useRef)(null),t7=(0,s.useRef)(null),t9=(0,s.useRef)(null),ne=(0,s.useRef)(null),nt=(0,s.useRef)(null),nn=(0,s.useRef)(0),nr=(0,s.useRef)(null),ns=(0,s.useRef)(null),na=(0,s.useRef)(!1);na.current=e.transitioning??!1;let ni=(0,s.useRef)(Date.now()),nl=(0,s.useRef)(0),no=(0,s.useRef)(0),nc=(0,s.useRef)(null),nd=(0,s.useRef)(!1),nu=(0,s.useRef)(Promise.resolve()),nh=e.setToolPreset??ea,np=eI??g?.context.model??eE??null,nm=m?Q??en:np,nf=(0,s.useMemo)(()=>{if(e0)return{...e0,totalActiveMs:g?.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 S){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===S.length)?null:{sessionFile:g?.filePath||void 0,sessionId:tN.current??t?.id??"",sessionName:t?.name,userMessages:r,assistantMessages:s,toolCalls:i,toolResults:a,totalMessages:S.length,tokens:e,cost:n,totalActiveMs:g?.totalActiveMs,...ek?{contextUsage:ek}:{}}},[S,e0,ek,g?.filePath,g?.totalActiveMs,t?.id,t?.name]),ng=(0,s.useRef)(0),nx=(0,s.useCallback)((e,t)=>{e&&tN.current===e&&Array.isArray(t)&&(ng.current+=1,tv(n=>n?.sid===e&&ho(n.phases,t)?n:{sid:e,phases:t}))},[]),nv=(0,s.useCallback)((e,t,n)=>{tN.current===e&&ng.current===n&&Array.isArray(t)&&tv(n=>n?.sid===e&&ho(n.phases,t)?n:{sid:e,phases:t})},[]),ny=(0,s.useCallback)(e=>{let t="function"==typeof e?e(tI.current):e;tI.current=t,C(t)},[]),nb=(0,s.useCallback)(e=>{tM.current=e,T(e)},[]),nw=(0,s.useCallback)(async(e,t=!1,n=!1,r)=>{let s=!1;try{t&&y(!0);let a=r??null;if(!a){let n=new URLSearchParams({deferThinking:"1",deferMedia:"1"}),r=await fetch(`/api/sessions/${encodeURIComponent(e)}?${n}`);if(404===r.status)return t&&(x(null),j(null),ny([]),M(null),w(null)),null;if(!r.ok)throw Error(`HTTP ${r.status}`);a=await r.json()}if(tN.current!==e)return null;x(a),j(a.leafId),tT.current=a.leafId??null;let i=tl(a.context.messages,a.context.entryIds??[],tE.current.sessionId===e?tE.current.outputs:[]);ny(i.messages),nb(i.entryIds),M(a.context.compactedWork??null),ej(a.contextUsage??null),eM(e=>nd.current?e:null),w(null);let l=!n&&nt.current===e;if(l||(eo(a.context.configuredThinkingLevel??a.context.thinkingLevel??"off"),ed(a.context.thinkingLevel)),eh(a.context.thinkingCeiling??null),s=!0,t&&y(!1),!n){if(l)try{let t=nn.current,n=await fetch(`/api/sessions/${encodeURIComponent(e)}/state`);if(n.ok&&tN.current===e){let r=await n.json();tN.current===e&&nn.current===t&&(r.state?.thinkingLevel!==void 0?(eo(r.state.configuredThinkingLevel??r.state.thinkingLevel),ed(r.state.thinkingLevel)):r.running||(nt.current=null,eo(a.context.configuredThinkingLevel??a.context.thinkingLevel??"off"),ed(a.context.thinkingLevel)))}}catch(e){console.error("Failed to refresh live thinking level:",e)}return null}try{let t=ng.current,n=await fetch(`/api/sessions/${encodeURIComponent(e)}/state`);if(!n.ok)throw Error(`HTTP ${n.status}`);let r=await n.json();if(tN.current!==e)return null;let s=r.state;return s?(void 0!==s.contextUsage&&ej(s.contextUsage??null),void 0!==s.systemPrompt&&eC(s.systemPrompt??null),void 0!==s.thinkingLevel&&(nt.current=e,eo(s.configuredThinkingLevel??s.thinkingLevel),ed(s.thinkingLevel)),void 0!==s.thinkingCeiling&&eh(s.thinkingCeiling??null),void 0!==s.extensionStatuses&&tr(s.extensionStatuses??[]),void 0!==s.extensionWidgets&&to(s.extensionWidgets??[]),void 0!==s.queuedMessages&&td(ha(s.queuedMessages)),void 0!==s.subagents&&th(e=>hr(e,s.subagents??[])),nv(e,s.todoPhases,t)):r.running||td({steering:[],followUp:[]}),r}catch(e){return console.error("Failed to load agent state:",e),null}}catch(e){return w(String(e)),null}finally{t&&!s&&y(!1)}},[nv,nb,ny]),nk=(0,s.useCallback)(e=>{let t=nu.current.then(async()=>{tN.current===e&&await nw(e)});return nu.current=t.catch(()=>{}),t},[nw]),nj=(0,s.useCallback)(async(e,t)=>{let n=++ev.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(ev.current!==n||tN.current!==e)return;tT.current=t;let l=tl(i.context.messages,i.context.entryIds??[],tE.current.sessionId===e?tE.current.outputs:[]);ny(l.messages),nb(l.entryIds),M(i.context.compactedWork??null),ej(i.contextUsage??null)}catch(e){console.error("Failed to load context:",e)}},[nb,ny]),nC=(0,s.useCallback)(async e=>{try{let t=await uQ(e,{type:"get_tools"});if(t){let{getPresetFromTools:e}=await Promise.resolve().then(n.bind(n,14755));nh(e(t))}}catch(e){console.error("Failed to load tools:",e)}},[nh]),nT=(0,s.useCallback)((e=0,t="(no messages)")=>{let n=tN.current;if(!m||!r||!n||t6.current)return;let s=t3.current??r;t6.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})},[m,r,o]),nE=(0,s.useCallback)(async()=>{if(t8.current)return t8.current;let t=tN.current;if(t&&ns.current!==t||!t&&(!m||!r))return t;let n=(async()=>{let n=t;if(!n){let t=t7.current,s=ne.current,a=t9.current;t&&e$(t);let i={cwd:r,type:"ensure_session",toolNames:(0,ul.xG)(es),...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=t5.current,c=o?.body===l?o.createRequestId:hp();t5.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();t5.current=null,n=u.sessionId,tN.current=n,t3.current=u.cwd??r??null,t3.current&&ei(t3.current,u.worktree),null!==nr.current&&(ns.current=n),u.model&&t7.current===t&&(e$(u.model),t||er(u.model)),u.thinkingLevel&&ne.current===s&&(eo(u.configuredThinkingLevel??u.thinkingLevel),ed(u.thinkingLevel))}for(;ns.current===n;){let e=nr.current;await uQ(n,{type:"set_thinking_ceiling",ceiling:e}),nr.current===e&&ns.current===n&&(ns.current=null)}return n})();t8.current=n;try{return await n}finally{t8.current=null}},[m,r,es,e.newSessionAutoWorktree]),n$=(0,s.useCallback)(async()=>{let e=tN.current??await nE();if(!e)return eG([]),[];eY(!0);try{let t=await uQ(e,{type:"get_commands"}),n=t?.commands??[];return eG(n),n}catch(e){return console.error("Failed to load slash commands:",e),eG([]),[]}finally{eY(!1)}},[nE]),nR=(0,s.useCallback)(()=>{tS.current+=1,tC.current=!1,tj.current&&(clearTimeout(tj.current),tj.current=null)},[]),nL=(0,s.useCallback)(()=>{ty.current?.close(),ty.current=null,tb.current=null,tw.current=null},[]),nA=(0,s.useCallback)(()=>{tk.current?.close(),tk.current=null},[]),nP=(0,s.useCallback)(e=>{nA();let t=new EventSource(`/api/agent/${encodeURIComponent(e)}/events?entries=1`);tk.current=t,t.onmessage=t=>{try{let n=JSON.parse(t.data);"session_snapshot"===n.type?tH.current?.(n):"agent_start"===n.type&&tU.current?.(e)}catch{}}},[nA]),n_=(0,s.useCallback)(e=>{nL();let t=new EventSource(`/api/agent/${encodeURIComponent(e)}/events`);ty.current=t,tb.current=e;let n=new Promise(n=>{let r=!1,s=e=>{r||(r=!0,clearTimeout(a),tw.current?.source===t&&(tw.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"),ty.current!==t)return;"update_maintenance"===n.type&&window.dispatchEvent(new CustomEvent("ompweb:update-maintenance",{detail:n})),tH.current?.(n)}catch{}},t.onerror=()=>{if(t.readyState===EventSource.CLOSED&&(s("closed"),ty.current===t&&(t$.current||tC.current))){ty.current=null,tb.current=null,tw.current=null;let t=tS.current;setTimeout(()=>{t===tS.current&&!ty.current&&(t$.current||tC.current)&&n_(e)},1e3)}}});return tw.current={source:t,promise:n,pending:!0},n},[nL]),nF=(0,s.useCallback)(async e=>{let t=ty.current;if(t&&tb.current===e){if(t.readyState===EventSource.OPEN)return;let e=tw.current;if(e?.source===t&&e.pending&&(await e.promise,ty.current===t&&t.readyState===EventSource.OPEN))return}let n=await n_(e);if("connected"!==n.status&&n.source.readyState!==EventSource.OPEN)throw ty.current===n.source&&(ty.current=null),tb.current===e&&(tb.current=null),tw.current?.source===n.source&&(tw.current=null),n.source.close(),new hh(n.status)},[n_]),nz=(0,s.useCallback)(e=>{e8.current=e.id,e4(e),l?.(e)},[l]),nW=(0,s.useCallback)(e=>{if(e5.current?.id===e&&(e5.current=null),e8.current===e){let e=e5.current;e5.current=null,e?nz(e):(e8.current=null,e4(null))}e7.current?.id===e&&(e7.current=null,e3(null))},[nz]),nO=(0,s.useCallback)(async(e,t)=>{if(e8.current!==e.id)return;let n=e7.current;if(n?.id===e.id&&"sending"===n.status)return;let r=tN.current,s=e=>{e7.current=e,e3(e)};if(!r)return void s({id:e.id,status:"failed",error:"no session"});s({id:e.id,status:"sending"});try{await uQ(r,{type:"extension_ui_response",id:e.id,...t})}catch(t){if(tN.current!==r||e8.current!==e.id)return;s({id:e.id,status:"failed",error:t instanceof Error?t.message:String(t)});return}tN.current===r&&nW(e.id)},[nW]),nD=(0,s.useCallback)(async(e,t)=>{let n=tN.current;if(n)try{await uQ(n,{type:"extension_ui_input",id:e.id,data:t})}catch(e){console.error("Failed to send extension custom UI input:",e)}},[]),nH=(0,s.useCallback)(e=>{let t=e.message.trim();t&&eX({type:"add",notice:{id:e.id??hp(),message:t,type:e.type??"info"}})},[]),nU=(0,s.useCallback)(e=>{let t={role:"custom",customType:tt,content:eA(e).trim(),display:!0,timestamp:Date.now()},n=tE.current,r=tN.current;n.sessionId!==r&&(n.sessionId=r,n.outputs=[]);let s=tM.current.slice(0,tI.current.length),a=null;for(let e=s.length-1;e>=0;e--)if(!ti(s[e])){a=s[e];break}n.seq+=1,n.outputs.push({entryId:`${ta}${n.seq}`,baseEntryId:a,message:t});let i=tl(tI.current,tM.current,n.outputs);ny(i.messages),nb(i.entryIds)},[ny,nb]),nB=(0,s.useCallback)((t,n)=>{if("custom"!==t.method&&"closed"in t&&t.closed)return void nW(t.id);switch("custom"===t.method&&uG(t)&&l?.(t),t.method){case"select":case"confirm":case"input":case"editor":case"ask":case"form":case"plan_review":{let e=e8.current;if(e===t.id)break;if(null!==e&&n){e5.current=t;break}e5.current=null,null!==e&&nW(e),nz(t);break}case"notify":nH({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":to(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":te(e=>t.closed?e?.id===t.id?null:e:t)}},[nH,nW,l,e.chatInputRef,nz]),nq=(0,s.useCallback)(()=>{let e=t$.current;return t$.current=!1,L(!1),eK(null),hk(tR.current),ew(null),$({type:"end"}),e},[]),nV=(0,s.useCallback)(()=>{t_.current="unknown",tF.current=null;let e=hd(tI.current,tM.current);tz.current=e?{entryId:e.entryId,key:hy(e.message)}:null,tW.current+=1},[]),nK=(0,s.useCallback)(()=>{let e=t_.current,t=tF.current;if("unknown"===e){let n=hd(tI.current,tM.current),r=n?.message,s=tz.current;null!==n&&(null===s||(null!==n.entryId&&null!==s.entryId?n.entryId!==s.entryId:hy(n.message)!==s.key))&&r?.role==="assistant"&&r.stopReason&&(e=hc(r),t??={provider:r.provider,...r.model?{model:r.model}:{},...void 0!==r.credentialId?{credentialId:r.credentialId}:{}})}return{outcome:e,sessionId:tN.current,...t?{provider:t.provider,...t.model?{model:t.model}:{},...void 0!==t.credentialId?{credentialId:t.credentialId}:{}}:{}}},[]),nJ=(0,s.useCallback)(e=>{let t=nK();if("unknown"!==t.outcome||!e)return void i?.(t);let n=tW.current;e.catch(()=>void 0).then(()=>{let e=tN.current===t.sessionId&&tW.current===n;i?.(e?nK():t)})},[i,nK]),nG=(0,s.useCallback)((e,t)=>tP.current!==e&&(tP.current=e,nJ(t),!0),[nJ]),nZ=(0,s.useCallback)(e=>{nR(),tC.current=!0;let t=tS.current,n=async()=>{if(t===tS.current&&tN.current===e&&tC.current)try{let r=ng.current,s=e8.current,a=e5.current,i=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(!i.ok)throw Error(`HTTP ${i.status}`);let l=await i.json();if(t!==tS.current||tN.current!==e||!tC.current)return;let o=l.state;if(th(e=>hr(e,o?.subagents??[])),nv(e,o?.todoPhases,r),l.running&&o&&(o.isStreaming||o.isPromptRunning||o.isHandoffRunning)){tC.current=!1,tj.current=null,tL.current=!!o?.isStreaming,tA.current=!!o?.isPromptRunning,t$.current=!0,L(!0),eK(o?.isStreaming?{kind:"waiting_model"}:{kind:"running_command"});return}if(l.running&&o?.isCompacting){e_(!0),eH(hl(o)),tj.current=setTimeout(()=>void n(),600);return}if(l.running&&(o?.subagents?.length??0)>0){tj.current=setTimeout(()=>void n(),1e3);return}let c=!1===l.running?[]:o?.pendingExtensionUiIds;if(c&&s===e8.current&&a===e5.current&&(a&&!c.includes(a.id)&&(e5.current=null),null===s||c.includes(s)||nW(s)),null!==e8.current){tj.current=setTimeout(()=>void n(),3e4);return}tC.current=!1,tj.current=null,nL()}catch{if(t!==tS.current||tN.current!==e||!tC.current)return;tj.current=setTimeout(()=>void n(),600)}};tj.current=setTimeout(()=>void n(),3e4)},[nv,nR,nW,nL]),nY=(0,s.useCallback)(async(e=tN.current,t=nl.current)=>{if(nl.current===t)try{e&&await nw(e)}finally{if(nl.current!==t)return;let n=tA.current,r=tL.current;tA.current=!1,tL.current=!1,nc.current=null;let s=nq();n?nG(t):r&&s&&nJ(),e&&nZ(e)}},[nw,nJ,nG,nZ,nq]),nQ=(0,s.useCallback)(async(e,t)=>{await hm(800);let n=Date.now();for(;t$.current&&Date.now()-n<2e4;){if(void 0!==t&&nl.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 nY(e,t)}}catch{}await hm(600)}},[nY]),nX=(0,s.useCallback)(async e=>{let t=tD.current+1;for(tD.current=t;tO.current&&tD.current===t&&tN.current===e;){await hm(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 nw(e),tD.current!==t||tN.current!==e)return;tO.current=!1,P(!1),F(null);return}catch{}}},[nw]),n0=(0,s.useCallback)(async e=>{if(!t$.current)return;let t=nl.current;try{let n=ng.current,r=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(!r.ok)return;let s=await r.json();if(nl.current!==t)return;let a=s.state;if(e_(a?.isCompacting??!1),eH(hl(a)),td(ha(a?.queuedMessages)),a?.contextUsage!==void 0&&ej(a.contextUsage??null),th(e=>hr(e,a?.subagents??[])),nv(e,a?.todoPhases,n),s.running&&a&&(a.isStreaming||a.isPromptRunning||a.isCompacting||a.isHandoffRunning)||!t$.current)return;a&&(void 0!==a.systemPrompt&&eC(a.systemPrompt??null),void 0!==a.extensionStatuses&&tr(a.extensionStatuses??[]),void 0!==a.extensionWidgets&&to(a.extensionWidgets??[])),await nY(e,t)}catch{}},[nv,nY]),n1=(0,s.useCallback)(async e=>{let t=await nw(e,!1,!0),n=t?.state;return!!t?.running&&!!n&&tN.current===e&&!t$.current&&!!(n.isStreaming||n.isPromptRunning||n.isHandoffRunning)&&(tL.current=!!n.isStreaming,tA.current=!!n.isPromptRunning,t$.current=!0,L(!0),eK(n.isStreaming?{kind:"waiting_model"}:{kind:"running_command"}),$({type:"start"}),hj(tR.current,e,n.pendingToolCalls),n_(e),!n.isStreaming&&n.isPromptRunning&&nQ(e),!0)},[n_,nw,nQ]),n2=(0,s.useCallback)(async(e,t=nl.current)=>{let n=no.current+1;no.current=n;try{let r=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(!r.ok)return;let s=await r.json();if(n!==no.current||tN.current!==e||nl.current!==t)return;s.state?.contextUsage!==void 0&&ej(s.state.contextUsage??null)}catch{}},[]);(0,s.useEffect)(()=>{if(!eP){eU.current=null,eH(null);return}eH(e=>e??{startedAt:Date.now(),reason:eU.current})},[eP]),(0,s.useEffect)(()=>{if(!R&&!eP)return;let e=()=>{let e=tN.current;e&&n2(e)};e();let t=setInterval(e,1e3);return()=>clearInterval(t)},[R,eP,n2]),(0,s.useEffect)(()=>{if(!R)return;let e=()=>{let e=tN.current;e&&n0(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)}},[R,n0]),(0,s.useEffect)(()=>{if(R)return;let e=()=>{let e=tN.current;e&&!t$.current&&n1(e)},t=()=>{"visible"===document.visibilityState&&e()},n=e=>{let t=tN.current,n=e.detail?.sessionId;t&&n===t&&!t$.current&&n1(t).then(e=>{e||tN.current!==t||t$.current||nw(t)})};return document.addEventListener("visibilitychange",t),window.addEventListener("online",e),window.addEventListener(u8,n),()=>{document.removeEventListener("visibilitychange",t),window.removeEventListener("online",e),window.removeEventListener(u8,n)}},[R,n1,nw]),tU.current=e=>{if(tN.current!==e||t$.current||ty.current||tB.current)return;let t=n1(e).then(async t=>{t||tN.current!==e||t$.current||await nw(e)}).catch(()=>{}).finally(()=>{tB.current===t&&(tB.current=null)});tB.current=t},(0,s.useEffect)(()=>{t$.current=R},[R]),tH.current=(0,s.useCallback)(e=>{var t;switch(e.type){case"connected":{let t=e.pendingExtensionUiIds,n=e8.current;if(Array.isArray(t)){let e=e5.current;e&&!t.includes(e.id)&&(e5.current=null),null===n||t.includes(n)||nW(n)}break}case"extension_ui_closed":"string"==typeof e.id&&nW(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=hy(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=hy(e),n=i.get(t)??0;n>0&&i.set(t,n-1)}let o=r.slice(l).filter(e=>{let t=hy(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,tN.current,tT.current,tI.current,tM.current);if(!t)break;tT.current=t.entryId;let n=tl(t.messages,t.entryIds,tE.current.sessionId===tN.current?tE.current.outputs:[]);ny(n.messages),nb(n.entryIds),M(t.compactedWork);break}case"agent_start":{let e=!t$.current;nR(),e&&nV(),tL.current=!0,t$.current=!0,L(!0),eK({kind:"waiting_model"}),$({type:"start"});break}case"agent_end":if(!t$.current)break;if(eK(null),hk(tR.current),ew(null),$({type:"end"}),tN.current){nw(tN.current);let e=ng.current;fetch(`/api/agent/${encodeURIComponent(tN.current)}`).then(e=>e.json()).then(t=>{t.state?.contextUsage!==void 0&&ej(t.state.contextUsage??null),t.state?.systemPrompt!==void 0&&eC(t.state.systemPrompt??null),t.state?.extensionStatuses!==void 0&&tr(t.state.extensionStatuses??[]),t.state?.extensionWidgets!==void 0&&to(t.state.extensionWidgets??[]),t.state?.subagents!==void 0&&th(e=>hr(e,t.state?.subagents??[])),tN.current&&nv(tN.current,t.state?.todoPhases,e),t.state?.goal!==void 0&&tZ(t.state.goal??null),td(ha(t.state?.queuedMessages))}).catch(()=>{})}break;case"goal_status":tZ(e.status??null);break;case"agent_settled":{let e=tL.current;if(tL.current=!1,!e||tA.current)break;let t=tN.current,n=nq();e_(!1);let r=t?nw(t):void 0;t&&nZ(t),n&&nJ(r);break}case"prompt_done":{let e=nl.current,t=tA.current;tA.current=!1,nc.current=null;let n=tP.current!==e;if(!t&&!n)break;let r=tN.current;nG(e,r?nw(r):void 0),!tL.current&&(nq(),r&&nZ(r))}break;case"prompt_error":t_.current="failed",nH({type:"error",message:e.errorMessage??"Command failed"});break;case"extension_error":t_.current="failed",nH({type:"error",message:e.error??"Extension command failed"});break;case"message_start":case"message_update":{if(!t$.current)break;let t=e.message;if(t?.role!=="assistant")break;t&&$({type:"update",message:l7(t)}),eK(null);break}case"message_end":{if(!t$.current)break;let t=e.message;if(t?.role==="assistant"&&(tF.current={provider:t.provider,...t.model?{model:t.model}:{},...void 0!==t.credentialId?{credentialId:t.credentialId}:{}},t_.current=hc(t)),t&&"user"===t.role){let e=l7(t),n=hv(e),r=nc.current;nc.current=null,ny(t=>{let s=t[t.length-1];return r&&s?.role==="user"&&hv(s)===r?r===n?t:[...t.slice(0,-1),e]:[...t,e]}),r||tm({type:"user-message",kind:lH(e),text:lD(e),images:"user"!==e.role||"string"==typeof e.content?0:e.content.filter(e=>"image"===e.type).length})}else t&&ny(e=>[...e,l7(t)]);let n=tN.current;n&&n2(n),$({type:"reset"}),eK(e=>t?.role==="toolResult"&&e?.kind==="running_tools"?e:{kind:"waiting_model"});break}case"thinking_level_changed":{let t=tN.current,n=e.thinkingLevel;t&&void 0!==n&&(nt.current=t,nn.current+=1,eo(e.configured??n),ed(n));break}case"todo_changed":nx(tN.current,e.phases);break;case"tool_execution_start":{let t=e.toolCallId,n=e.toolName,r=e.args,s=nI(tN.current,t);s&&tR.current.add(s),eK(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}});break}case"tool_execution_update":{let n=nI(tN.current,"string"==typeof e.toolCallId?e.toolCallId:null);n&&tR.current.has(n)&&"string"==typeof e.text&&(t=e.text,nS.get(n)!==t&&(nS.set(n,t),nN()));break}case"tool_execution_end":{let t=e.toolCallId,n=nI(tN.current,t);n&&tR.current.delete(n)&&nM([n]),eK(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";th(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()};th(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};th(e=>hr(e,[r]));break}case"queue_update":td({steering:[...e.steering??[]],followUp:[...e.followUp??[]]});break;case"auto_retry_start":ew({attempt:e.attempt,maxAttempts:e.maxAttempts,errorMessage:e.errorMessage});break;case"auto_retry_end":ew(null);break;case"auto_compaction_start":case"compaction_start":if("string"==typeof e.reason){eU.current=e.reason;let t=e.reason;eH(e=>e?{...e,reason:t}:e)}e_(!0),ez(null),eO(null);break;case"auto_compaction_end":case"compaction_end":if(e_(!1),e.errorMessage)ez(e.errorMessage),eO(null);else if(!e.aborted){eO(hb(e.result,e.reason??"auto"));let t=tN.current;t&&(nw(t),n2(t))}break;case"extension_ui_request":nB(e,!0===e.replayed)}},[nH,nx,nv,nR,nW,nB,nw,nJ,nG,n2,nV,nZ,nq,nb,ny]);let n4=(0,s.useCallback)(async(n,s,a)=>{let i=n.trim();if(!i&&!s?.length&&!a?.length)return"returned";if(t$.current||tO.current||nd.current)return"unknown";let l=sO(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 tY.current?.(t,e),"accepted"):"unknown"}nV();let c=nl.current+1;nR(),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()};ny(e=>[...e,u]),nc.current=hv(u),nl.current=c,t$.current=!0,L(!0),eK(o?{kind:"running_command"}:{kind:"waiting_model"}),$({type:"start"}),t1.current(!0);let h=s?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),p=null,f=!1,g="unknown";try{if(m&&r){let e=tN.current??await t8.current,t=await nE();t&&(p=t,Q&&(e$(Q),e&&await uQ(t,{type:"set_model",provider:Q.provider,modelId:Q.modelId})),await nF(t),f=!0,await uQ(t,{type:"prompt",message:l,...h?.length?{images:h}:{}}),nT(1,n),g="accepted")}else t&&(p=t.id,await nF(t.id),f=!0,await uQ(t.id,{type:"prompt",message:l,...h?.length?{images:h}:{}}),g="accepted");return o&&p&&nQ(p,c),g}catch(l){console.error("Failed to send message:",l);let r=l instanceof uY&&"update_draining"===l.code&&!1===l.accepted;if(!(!f||l instanceof uY&&"prompt_rejected"===l.code&&!1===l.accepted||r)&&p)return nQ(p,c),"unknown";tA.current=!1,t$.current=!1,nL();let i=nc.current;return i&&ny(e=>{let t=e[e.length-1];return t?.role==="user"&&hv(t)===i?e.slice(0,-1):e}),nH({type:"error",message:l instanceof Error?l.message:String(l)}),e.chatInputRef?.current?.restoreSubmission?.(n,hw(s),a,t?.id??p??void 0),nc.current=null,L(!1),eK(null),$({type:"end"}),"returned"}},[m,r,Q,t,nE,nF,nT,nQ,nH,nR,nL,e.chatInputRef,nV,ny]);tY.current=(0,s.useCallback)(async(n,r)=>{if(t$.current||tO.current)return;let s=`${r?"!!":"!"}${n}`;tO.current=!0,t1.current(!0),F({command:n,excludeFromContext:r}),P(!0);try{let e=tN.current??t?.id??await nE();if(!e)throw Error("Unable to create a session for the shell command");await uQ(e,{type:"bash",command:n,excludeFromContext:r}),await nw(e),nT(1,s)}catch(t){console.error("Failed to execute shell command:",t),nH({type:"error",message:t instanceof Error?t.message:String(t)}),e.chatInputRef?.current?.insertIfEmpty(s)}finally{tO.current=!1,F(null),P(!1)}},[nH,nE,nw,e.chatInputRef,nT,t]);let n8=(0,s.useCallback)(async()=>{let e=tN.current;if(e){if(tO.current){try{await uQ(e,{type:"abort_bash"})}catch(e){console.error("Failed to abort bash:",e)}return}try{await uQ(e,{type:"abort"}),t_.current="aborted"}catch(e){console.error("Failed to abort:",e)}}},[]),n5=(0,s.useCallback)(async e=>{if(tO.current)return{forked:!1,error:"Cannot fork while a shell command is running"};let t=tN.current;if(!t)return{forked:!1,error:"No active session to fork"};eT(e??null);try{let{cancelled:n,newSessionId:r}=await uQ(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{eT(null)}},[c]),n6=(0,s.useCallback)(async e=>{if(tO.current)return;let t=tN.current;t&&(uQ(t,{type:"navigate_tree",targetId:e}).catch(()=>{}),j(e),await nj(t,e))},[nj]),n3=(0,s.useCallback)(async e=>{if(tO.current)return;j(e);let t=tN.current;t&&(await nj(t,e),e&&uQ(t,{type:"navigate_tree",targetId:e}).catch(()=>{}))},[nj]),n7=(0,s.useCallback)(async(e,t)=>{if(m){let n={provider:e,modelId:t},r=t7.current?.provider===e;t7.current=n,r||(t9.current=null,et(null)),X(n),e$(n);let s=tN.current??await t8.current;if(!s)return;try{await uQ(s,{type:"set_model",provider:e,modelId:t})}catch(e){console.error("Failed to set model:",e)}return}let n=tN.current;if(n&&!nd.current){nd.current=!0,eM({provider:e,modelId:t}),eL(!0);try{await uQ(n,{type:"set_model",provider:e,modelId:t}),nd.current=!1,await nw(n)}catch(e){console.error("Failed to set model:",e),nd.current=!1,eM(eI),nH({type:"error",message:`Failed to switch model: ${e instanceof Error?e.message:String(e)}`}),await nw(n)}finally{nd.current=!1,eL(!1)}}},[nH,eI,m,nw,X]),n9=(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(m){if(nd.current)return!1;nd.current=!0,eL(!0);let e=t7.current,a=t9.current,i=ne.current;try{t7.current=t,t9.current=n??null,ne.current="auto";let e=tN.current??await t8.current;return e&&await uQ(e,r),X(t),et(n??null),e$(t),eo("auto"),ed(void 0),e&&await nw(e),!0}catch(n){console.error("Failed to apply Main preset:",n),t7.current=e,t9.current=a,ne.current=i,nH({type:"error",message:s(n)});let t=tN.current;return t&&await nw(t),!1}finally{nd.current=!1,eL(!1)}}let a=tN.current;if(!a||nd.current)return!1;nd.current=!0,eM(t),eL(!0);try{return await uQ(a,r),await nw(a),!0}catch(e){return console.error("Failed to apply Main preset:",e),eM(eI),nH({type:"error",message:s(e)}),await nw(a),!1}finally{nd.current=!1,eL(!1)}},[nH,eI,ec,m,nw,X,el]),re=(0,s.useCallback)(async e=>{let t=Z.find(t=>t.role===e),n=t?.resolved;if(!n)return;if(m){let e={provider:n.provider,modelId:n.modelId},t=n.thinkingLevel;ne.current=t??null,eo(t??"auto"),ed(void 0),t7.current=e,t9.current=null,et(null),X(e),e$(e)}let r=tN.current??(m?await t8.current:null);if(r)try{await uQ(r,{type:"set_role_model",role:e}),m||eM({provider:n.provider,modelId:n.modelId})}catch(e){console.error("Failed to set role model:",e)}},[m,Z,X]),rt=(0,s.useCallback)(async()=>{let e=tN.current;if(e&&!eP){eU.current="manual",e_(!0),ez(null),eO(null);try{let t=await uQ(e,{type:"compact"});eO(hb(t,"manual")),await nw(e,!0)}catch(e){ez(e instanceof Error?e.message:String(e)),eO(null)}finally{e_(!1)}}},[eP,nw]),rn=(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();W(i.models),U(i.modelError??null),q(i.modelScopeWarnings??[]),K(i.thinkingLevels??{}),G(i.thinkingLevelMaps??{}),Y(i.roles??[]);let l=i.modelList??[];if(D(l),m&&!tN.current){let e=(i.defaultModel?l.find(e=>e.id===i.defaultModel?.modelId&&e.provider===i.defaultModel?.provider):void 0)??l[0];er(e?{provider:e.provider,modelId:e.id}:null);let t=e&&i.thinkingLevelPins?.[`${e.provider}/${e.id}`];null===ne.current&&eo(t??"auto")}},[m,r,t?.cwd]),rr=(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 nE(),i=e=>(e.handled&&(e.error?nH({type:"error",message:e.error}):"openSessionStats"!==e.action&&nH({type:"success",message:e.message??"Command completed"})),e);try{switch(n){case"compact":{if(!a||eP)return i({handled:!0,error:"No active session to compact"});eU.current="manual",e_(!0),ez(null),eO(null);let e=await uQ(a,{type:"compact",...s?{customInstructions:s}:{}});return eO(hb(e,"manual")),await nw(a,!0)&&nT(),i({handled:!0,message:"Compacted context"})}case"reload":if(!a)return i({handled:!0,error:"No active session to reload"});return await uQ(a,{type:"reload"}),await Promise.all([nw(a,!1,!0),nC(a),n$(),rn()]),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 uQ(a,{type:"set_session_name",name:s}),await nw(a)&&nT(),i({handled:!0,message:`Session renamed to ${s}`});case"session":{if(!a)return i({handled:!0,error:"No active session"});let e=await uQ(a,{type:"get_session_stats"});return e&&e1(e),p?.(),i({handled:!0,action:"openSessionStats"})}case"copy":{if(!a)return i({handled:!0,error:"No active session"});let e=await uQ(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 n5();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 uQ(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(nU(e.message),e.prompt)return{handled:!0,prompt:e.prompt};return{handled:!0}}if(e?.prompt)return e.message&&nH({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(t$.current||tO.current)return i({handled:!0,error:"Cannot hand off while the session is busy"});t$.current=!0,L(!0),eK({kind:"running_command"});try{await nF(a);let e=await uQ(a,{type:"handoff",...s?{customInstructions:s}:{}});if(!e||e.cancelled)return i({handled:!0,error:"Handoff cancelled"});return await nw(a,!0)&&nT(),i({handled:!0,message:"컨텍스트를 현재 세션에 압축했습니다"})}finally{t$.current=!1,L(!1),eK(null),tN.current===a&&nZ(a)}default:{if(!a)return i({handled:!0,error:"No active session"});let t=await uQ(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&&nU(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)}},[nH,nU,nF,nE,n5,eP,rn,nw,n$,nC,nT,p,nZ]),rs=(0,s.useCallback)(async(t,n,r)=>{let s=tN.current;if(!s)return nH({type:"error",message:"The session is not ready yet, so the message was returned to the composer."}),e.chatInputRef?.current?.restoreSubmission?.(t,hw(n),r),"returned";let a=sO(t,r??[]),i=n?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),l=++tf.current;tm({type:"submit",id:l,kind:"steer",text:a,images:i?.length??0});try{return await uQ(s,{type:"steer",message:a,...i?.length?{images:i}:{}}),tm({type:"ack",id:l}),"accepted"}catch(a){return tm({type:"fail",id:l}),console.error("Failed to steer:",a),nH({type:"error",message:a instanceof Error?a.message:String(a)}),e.chatInputRef?.current?.restoreSubmission?.(t,hw(n),r,s),"returned"}},[nH,e.chatInputRef]),ra=(0,s.useCallback)(async(t,n,r,s)=>{let a=tN.current;if(!a)return nH({type:"error",message:"The session is not ready yet, so the message was returned to the composer."}),e.chatInputRef?.current?.restoreSubmission?.(t,hw(r),s),"returned";let i=sO(t,s??[]),l=r?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),o=++tf.current;tm({type:"submit",id:o,kind:n,text:i,images:l?.length??0});try{return await uQ(a,{type:"prompt",message:i,streamingBehavior:n,...l?.length?{images:l}:{}}),tm({type:"ack",id:o}),"accepted"}catch(n){return tm({type:"fail",id:o}),console.error("Failed to queue prompt:",n),nH({type:"error",message:n instanceof Error?n.message:String(n)}),e.chatInputRef?.current?.restoreSubmission?.(t,hw(r),s,a),"returned"}},[nH,e.chatInputRef]),ri=(0,s.useCallback)(async(t,n,r)=>{let s=tN.current;if(!s)return nH({type:"error",message:"The session is not ready yet, so the message was returned to the composer."}),e.chatInputRef?.current?.restoreSubmission?.(t,hw(n),r),"returned";let a=sO(t,r??[]),i=n?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),l=++tf.current;tm({type:"submit",id:l,kind:"followUp",text:a,images:i?.length??0});try{return await uQ(s,{type:"follow_up",message:a,...i?.length?{images:i}:{}}),tm({type:"ack",id:l}),"accepted"}catch(a){return tm({type:"fail",id:l}),console.error("Failed to follow up:",a),nH({type:"error",message:a instanceof Error?a.message:String(a)}),e.chatInputRef?.current?.restoreSubmission?.(t,hw(n),r,s),"returned"}},[nH,e.chatInputRef]),rl=(0,s.useCallback)(async()=>{let e=tN.current;if(e)try{await uQ(e,{type:"abort_compaction"})}catch(e){console.error("Failed to abort compaction:",e)}},[]),ro=(0,s.useCallback)(async()=>{let t=tN.current;if(t)try{var n;let r=await uQ(t,{type:"clear_queue"});tm({type:"withdraw"}),td({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),nH({type:"error",message:"Failed to recall queued messages"})}},[e.chatInputRef,nH]),rc=(0,s.useCallback)(async(e,t)=>{let n=tN.current;if(n)try{let r=await uQ(n,{type:"remove_queued_message",message:t,queue:e});if(!r?.removed)return;tm({type:"withdraw",kind:"steering"===e?"steer":"followUp",text:t}),td(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),nH({type:"error",message:"Failed to remove queued message"})}},[nH]),rd=(0,s.useCallback)(async(e,t=null)=>{let n="auto"===e?t:null,r=n!==eu;eo(e),eh(n),m&&(!tN.current||ns.current===tN.current)&&(ne.current=e,nr.current=n),ed(void 0);let s=tN.current??await t8.current;if(s)try{ns.current===s?await nE():r&&await uQ(s,{type:"set_thinking_ceiling",ceiling:n}),await uQ(s,{type:"set_thinking_level",level:e}),await nw(s)}catch(e){console.error("Failed to set thinking level:",e),nH({type:"error",message:"Failed to set thinking level"}),await nw(s)}},[m,nw,nH,eu,nE]);ey.current=nm?`${nm.provider}/${nm.modelId}`:"";let ru=e=>e?`${e}|${ey.current}`:null,rh=t?.id??tN.current,rp=ru(rh),rm=ep&&ep.key===rp?ep.value:null;(0,s.useEffect)(()=>{let e=++ex.current;rp&&rh&&!R&&!eR&&fetch(`/api/agent/${encodeURIComponent(rh)}`).then(e=>e.json()).then(t=>{ex.current===e&&ru(tN.current)===rp&&em({key:rp,value:(t.running?hi(t.state):void 0)??null})}).catch(()=>{})},[rp,R,eR]);let rf=(0,s.useCallback)(async()=>{let e=tN.current??await nE(),t=ru(tN.current);if(!e||!t)return;let n=++ex.current,r=()=>ex.current===n&&ru(tN.current)===t,s=e=>{r()&&em({key:t,value:e})};eg(!0);try{let n=ep?.key===t?ep.value?.enabled:void 0;if(void 0===n){let t=hi(await uQ(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 uQ(e,{type:"set_fast_mode",enabled:!n});s({enabled:a?.enabled===!0,active:a?.active===!0})}catch(t){if(!r())return;nH({type:"error",message:t instanceof Error?t.message:String(t)});try{s(hi(await uQ(e,{type:"get_state"}))??null)}catch{s(null)}}finally{eg(!1)}},[nE,ep,nH]),rg=(0,s.useCallback)(async e=>{let t=(0,ul.xG)(e);nh(e);let n=tN.current??await t8.current;if(n)try{await uQ(n,{type:"set_tools",toolNames:t})}catch(e){console.error("Failed to set tools:",e)}},[nh]),rx=(0,s.useCallback)(e=>{tV.current=e,tJ(t=>!e===t?t:!e)},[]);t1.current=e=>{tX.current=null,rx(e)};let rv=(0,s.useCallback)((e="smooth")=>{t0.current=Date.now()+700,t2.current?.scrollIntoView({behavior:e})},[]),ry=(0,s.useCallback)(()=>{tQ.current=0,tX.current=null,rx(!0),rv("smooth")},[rv,rx]),rb=(0,s.useCallback)(()=>{tQ.current=0,tX.current=null,rx(!1)},[rx]),rw=(0,s.useCallback)(()=>{if(!tX.current)return;tX.current=null;let e=t4.current;e&&rx(e.scrollHeight-e.scrollTop-e.clientHeight<=72)},[rx]),rk=(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(tX.current)return void rw();rb();let e=t4.current;return void(tX.current=e?{top:e.scrollTop,moved:!1,released:!1}:null)}rw(),e instanceof KeyboardEvent&&(!hu.has(e.key)||e.target instanceof Element&&e.target.closest("input, textarea, [contenteditable='true']"))||(tQ.current=Date.now()+1200)},[rw,rb]),rj=(0,s.useCallback)(()=>{let e=t4.current;if(!e)return;let t=tX.current;if(null!==t){let n=t.top;t.moved||=e.scrollTop!==n,t.top=e.scrollTop;return}if(!t$.current&&!tO.current)return;let n=e.scrollHeight-e.scrollTop-e.clientHeight,r=Date.now()<=tQ.current;if(!(!r&&Date.now()<t0.current)){if(n<=72)return void rx(!0);r&&rx(!1)}},[rx]);return(0,s.useEffect)(()=>(tN.current=t?.id??null,tE.current.sessionId!==tN.current&&(tE.current={sessionId:tN.current,outputs:[],seq:0}),t&&nw(t.id,!f,!0,f).then(e=>{if(tN.current!==t.id)return;nP(t.id),e?.running&&(nC(t.id),(e.state?.isStreaming||e.state?.isPromptRunning||e.state?.isHandoffRunning)&&(tL.current=!!e.state.isStreaming,tA.current=!!e.state.isPromptRunning,t$.current=!0,L(!0),eK(e.state.isStreaming?{kind:"waiting_model"}:{kind:"running_command"}),$({type:"start"}),hj(tR.current,t.id,e.state.pendingToolCalls),n_(t.id),!e.state.isStreaming&&e.state.isPromptRunning&&nQ(t.id)),e.state?.isBashRunning&&(tO.current=!0,P(!0),nX(t.id)),(e.state?.subagents?.length??0)>0&&n_(t.id));let n=e?.state;n&&(void 0!==n.isCompacting&&e_(n.isCompacting),eH(hl(n)),void 0!==n.contextUsage&&ej(n.contextUsage??null),void 0!==n.systemPrompt&&eC(n.systemPrompt??null),void 0!==n.thinkingLevel&&(nt.current=t.id,eo(n.configuredThinkingLevel??n.thinkingLevel),ed(n.thinkingLevel)),void 0!==n.thinkingCeiling&&eh(n.thinkingCeiling??null),void 0!==n.extensionStatuses&&tr(n.extensionStatuses??[]),void 0!==n.extensionWidgets&&to(n.extensionWidgets??[]),void 0!==n.queuedMessages&&td(ha(n.queuedMessages)),void 0!==n.subagents&&th(e=>hr(e,n.subagents??[])),void 0!==n.goal&&tZ(n.goal??null)),e&&eq(!0)}),()=>{tD.current+=1,nR(),e5.current=null,null!==e8.current&&nW(e8.current),nL(),nA()}),[t?.id]),(0,s.useEffect)(()=>{h?.(eS)},[eS,h]),(0,s.useEffect)(()=>{u&&u(g?.tree??[],k,n3)},[g?.tree,k,n3,u]),(0,s.useEffect)(()=>{let e=e=>{let t=tX.current;t&&(1!==e.button||t.released||t.moved||!(e.target instanceof Node&&t4.current?.contains(e.target))?rw():t.released=!0)};return window.addEventListener("pointerup",e,!0),window.addEventListener("keydown",rk),()=>{window.removeEventListener("pointerup",e,!0),window.removeEventListener("keydown",rk)}},[rw,rk]),(0,s.useEffect)(()=>{let e=t4.current;if(!e)return;let t=()=>{tX.current?.moved&&rw()};return e.addEventListener("pointerdown",rk,{passive:!0}),e.addEventListener("wheel",rk,{passive:!0}),e.addEventListener("touchstart",rk,{passive:!0}),e.addEventListener("scroll",rj,{passive:!0}),e.addEventListener("scrollend",t,{passive:!0}),()=>{e.removeEventListener("pointerdown",rk),e.removeEventListener("wheel",rk),e.removeEventListener("touchstart",rk),e.removeEventListener("scroll",rj),e.removeEventListener("scrollend",t)}},[S.length,v,rw,rj,rk]),(0,s.useEffect)(()=>{if(na.current||!R&&!A||!tV.current)return;let e=t4.current;if(!e)return;let t=requestAnimationFrame(()=>{tV.current&&(t0.current=Date.now()+700,e.scrollTo({top:e.scrollHeight,behavior:"instant"}))});return()=>cancelAnimationFrame(t)},[R,A,S.length,E.streamingMessage,eV,_,e.transitioning]),(0,s.useLayoutEffect)(()=>{if(0!==S.length){if(!tq.current){tq.current=!0,rv("instant");return}if(!na.current&&tV.current){let e=Date.now()-ni.current<1500;rv(t$.current||tO.current||e?"instant":"smooth")}}},[S.length,R,A,rv,e.transitioning]),(0,s.useEffect)(()=>{let e=new AbortController;return rn(e.signal).catch(e=>{if(e instanceof DOMException&&"AbortError"===e.name)return}),()=>e.abort()},[rn,d]),(0,s.useEffect)(()=>{if(!eW)return;let e=setTimeout(()=>eO(null),6e3);return()=>clearTimeout(e)},[eW]),(0,s.useEffect)(()=>{if(0===eQ.visible.length)return;let e=eQ.visible.find(e=>e.exiting);if(e){let t=setTimeout(()=>{eX({type:"remove",id:e.id})},180);return()=>clearTimeout(t)}if(!eQ.visible[0])return;let t=setTimeout(()=>{eX({type:"mark_oldest_exiting"})},5e3);return()=>clearTimeout(t)},[eQ.visible]),(0,s.useEffect)(()=>{e1(null)},[S.length,ek?.tokens,ek?.percent,ek?.contextWindow]),{data:g,loading:v,error:b,activeLeafId:k,messages:S,entryIds:N,streamState:E,agentRunning:R,modelNames:z,modelList:O,modelError:H,modelScopeWarnings:B,modelThinkingLevels:V,modelThinkingLevelMaps:J,modelRoles:Z,newSessionModel:Q,toolPreset:es,thinkingLevel:el,effectiveThinkingLevel:ec,thinkingCeiling:eu,retryInfo:eb,contextUsage:ek,systemPrompt:eS,forkingEntryId:eN,isCompacting:eP,compaction:eD,compactError:eF,compactResult:eW,currentModel:np,displayModel:nm,modelSwitching:eR,sessionStats:nf,runStateKnown:eB,slashCommands:eJ,slashCommandsLoading:eZ,queuedMessages:tc,deliveryRows:tg,subagents:tu,todoPhases:tx&&tx.sid===tN.current?tx.phases:null,compactedWork:I,notices:eQ.visible,extensionDialog:e2,extensionResponse:e6,extensionCustomUi:e9,extensionStatuses:tn,extensionWidgets:ts,respondToExtensionUi:nO,sendExtensionCustomInput:nD,isAutoModelSelection:m&&null===Q,agentPhase:eV,isNew:m,autoFollowPaused:tK,resumeAutoFollow:ry,pauseAutoFollow:rb,goalStatus:tG,sessionIdRef:tN,eventSourceRef:ty,messagesEndRef:t2,scrollContainerRef:t4,handleSend:n4,handleAbort:n8,handleFork:n5,handleNavigate:n6,handleModelChange:n7,handleRoleModelChange:re,handleMainPresetChange:n9,newSessionAccount:ee,handleCompact:rt,handleSteer:rs,handleFollowUp:ri,handlePromptWithStreamingBehavior:ra,handleAbortCompaction:rl,handleRecallQueue:ro,handleRemoveQueuedMessage:rc,handleBuiltinSlashCommand:rr,handleToolPresetChange:rg,handleThinkingLevelChange:rd,fastMode:rm,fastModeBusy:ef,handleFastModeToggle:rf,loadTools:nC,loadSlashCommands:n$,ensureNewSession:nE,refreshLiveTranscript:nk,setActiveLeafId:j,setData:x,setMessages:C,dispatch:$,setAgentRunning:L,setForkingEntryId:eT,bashRunning:A,pendingBash:_,handleAgentEventRef:tH}}({session:e,newSessionCwd:t,initialData:l,transitioning:o,onAgentEnd:eC,onAttentionNeeded:d,onSessionCreated:u,onSessionForked:h,newSessionAutoWorktree:i,modelsRefreshKey:p,chatInputRef:m,onBranchDataChange:f,onSystemPromptChange:g,onSessionStatsPanelOpen:y}),t9=(0,s.useMemo)(()=>(function(e){let t=null,n=new Map;for(let r=0;r<e.length;r++){let s=e[r],a=te(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=e9(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(e7)?{kind:"translated",text:n.slice(e7.length),original:t}:n.startsWith("[번역 생략]")?{kind:"skipped",text:n,original:t}:{kind:"failed",text:n,original:t}}(s,e9(l.content??[]))}}return t??e})(eM),[eM]),ne=sd(e?.id,th?.provider,void 0,th?.modelId),nt=ne?.alias;(0,s.useEffect)(()=>{nt&&es.current?.(nt)},[nt]);let nn=(0,s.useMemo)(()=>{if(!th)return null;let e=tR?tG:rf.find(e=>e.alias===ne?.alias)?.oauthPosition;return rf.find(t=>t.provider===th.provider&&(void 0===t.oauthPosition?null===ne||ne.seed===t.seed:t.oauthPosition===e))?.alias??null},[th,tR,tG,ne]),nr=eR||eL,ns=e?.id;ed.current=t9,eu.current=eE,eh.current=tz;let na=(0,s.useRef)(!0);na.current=!tL;let ni=(0,s.useRef)(!1);(0,s.useEffect)(()=>{eR&&!ni.current&&(ep.current+=1),ni.current=eR},[eR]),(0,s.useEffect)(()=>()=>{ep.current+=1},[]),(0,s.useEffect)(()=>{el(e=>[...function(e){if(!e)return[];try{let t=JSON.parse(window.localStorage.getItem(hF(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[]}}(ns),...e.filter(e=>null===e.anchorEntryId&&e.sessionId===ns)])},[ns]),(0,s.useEffect)(()=>{let e=tz.current;e&&eo.current.some(t=>null===t.anchorEntryId&&t.sessionId===e)&&el(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(ro(t[i])===e.identity&&(a+=1)===e.occurrence)return{kind:"entry",entryId:n[i]};return null}(s.intent,t9,eE);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?(hz(e,r),r):t})},[t9,eE,tz]);let nl=(0,s.useRef)(null);(0,s.useEffect)(()=>{let e=tz.current,t=nl.current;if(nl.current=e?{sessionId:e,entryIds:eE}: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===rd&&r.push(t[a])}return r}(t.entryIds,eE,t9),r=eg();if(0===n.length||!r)return;let s=so(e,"web6",void 0)?.alias??null;for(let e of n)eo.current.some(t=>t.anchorEntryId===e)||ey(s,"done",r,{kind:"entry",entryId:e})},[eE,t9,tz,eg,ey]);let no=eR&&t$?.kind==="running_tools"&&t$.tools.length>0&&t$.tools.every(e=>"wait"===e.name),nc=eT||o,{hideThinkingBlock:nd}=(V=t??e?.cwd??null,J=n1(),(0,s.useEffect)(()=>{n0(V).catch(()=>{})},[V]),J),nu=(0,s.useMemo)(()=>({hideThinking:nd}),[nd]);(0,s.useEffect)(()=>{var e;if(!tj||er.current===tj.id)return;er.current=tj.id;let t=eg();if(!t)return;ef.current=t.turn;let n=e$.streamingMessage?.role==="assistant"?e$.streamingMessage:null,r=rc(ed.current,n,th?.provider,th?.modelId);ew("select"===(e=tj.method)||"ask"===e||"form"===e?"choice":"approval",t,r.provider,r.credentialId,r.model)},[tj,e$.streamingMessage,th?.provider,th?.modelId,eg,ew]),(0,s.useEffect)(()=>(x=nr?tU:null,()=>void(x=null)),[nr,tU]),(0,s.useEffect)(()=>{$?.(nr)},[$,nr]),(0,s.useEffect)(()=>()=>$?.(!1),[$]),(0,s.useEffect)(()=>{R?.(no)},[no,R]),(0,s.useEffect)(()=>()=>R?.(!1),[R]),(0,s.useEffect)(()=>{L?.(null!==tj)},[L,tj]),(0,s.useEffect)(()=>()=>L?.(!1),[L]);let{main:nh,process:np}=(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=e5(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(tr(t)){r.push(void 0!==s.anchorIdx||a<0?s:{...s,anchorIdx:a});continue}if("assistant"!==t.role){"toolResult"!==t.role&&null===te(t)&&0>ts(e,s.idx)&&l(a,[{idx:s.idx}],0);continue}let i=eY(t,n);if(eG(t,n)&&eZ(e,s.idx)){let e=i.flatMap(e=>e.blocks);l(a,[{idx:s.idx}],eQ(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}],eQ(e.blocks)),o.collect(s.idx,e.blocks)}!c&&eG(t,n)&&d(s.idx,[])}return u(),{main:r,process:s}})(t9,function(e,t={}){let n=-1;for(let t=e.length-1;t>=0;t--)if(to(e[t])){n=t;break}let r=[];for(let s=0;s<e.length;){if(!to(e[s])){r.push({kind:"message",idx:s}),s+=1;continue}let a=s,i=a+1;for(;i<e.length&&!to(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=e5(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!==te(n)||ts(e,o)>=0)continue;if(tr(n)){u(),s.push({kind:"message",idx:o,anchorIdx:t});continue}"toolResult"!==n.role&&a.push({idx:o});continue}let c=eY(n,r);if(eG(n,r)&&eZ(e,o)){let e=c.flatMap(e=>e.blocks);for(let t of(a.push({idx:o}),i+=eQ(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+=eQ(e.blocks),d.collect(o,e.blocks),e.blocks))l.push(t)}0===p&&eG(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}(t9,{sessionBusy:nr,isStreaming:e$.isStreaming,hideThinking:nu.hideThinking}),nu),[t9,nr,e$.isStreaming,nu]),nm=(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(a6),a=n.slice(r+1).flatMap(a6),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}})(nh,t9,tg?.messages),[nh,t9,tg]),[nf,ng]=(0,s.useState)(hR),{startIndex:nx,endIndex:nv,hasLater:ny}=hL(nh.length,nf),nb=null!==nf.end&&ny,nw=(0,s.useRef)(nh.length);nw.current=nh.length;let nk=(0,s.useRef)(null),nj=(0,s.useRef)(null),nC=(0,s.useRef)(null);(0,s.useEffect)(()=>{null!==nf.end&&nf.end>=nh.length&&ng(e=>({count:e.count,end:null}))},[nf.end,nh.length]),(0,s.useEffect)(()=>{let e=nk.current,t=tD.current;if(!e||!t)return;let n=new IntersectionObserver(e=>{e[0]?.isIntersecting&&(nC.current=t.scrollHeight-t.scrollTop,ng(e=>(function(e,t=50){return{...e,count:e.count+t}})(e)))},{root:t,threshold:0});return n.observe(e),()=>n.disconnect()},[nf,nh.length,tD]),(0,s.useEffect)(()=>{if(null==nC.current)return;let e=tD.current;if(e){var t;t=e.scrollHeight,e.scrollTop=Math.max(0,t-nC.current),nC.current=null}},[nf.count,tD]),(0,s.useEffect)(()=>{let e=nj.current,t=tD.current;if(!e||!t)return;let n=new IntersectionObserver(e=>{e[0]?.isIntersecting&&ng(e=>(function(e,t,n=50){if(null===t.end)return t;let{startIndex:r,endIndex:s}=hL(e,t),a=s+n;return a>=e?{count:e-r,end:null}:{count:a-r,end:a}})(nw.current,e))},{root:t,threshold:0});return n.observe(e),()=>n.disconnect()},[nf,nh.length,tD]);let[nT,nE]=(0,s.useState)(null),[n$,nR]=(0,s.useState)(0),nL=(0,s.useRef)(null),nA=(0,s.useCallback)(e=>{t_(),nL.current=e,nE(null),ng(t=>hA(nw.current,e,t)),nR(e=>e+1)},[t_]);(0,s.useLayoutEffect)(()=>{let e=nL.current,t=tD.current;if(null===e||!t)return;let n=t.querySelector(`[data-chat-item="${e}"]`);if(!n)return;nL.current=null;let r=document.createRange();r.selectNodeContents(n),t.scrollTop+=r.getBoundingClientRect().top-t.getBoundingClientRect().top-24,nE(e)},[n$,nf,nh,tD]),(0,s.useEffect)(()=>{if(null===nT)return;let e=setTimeout(()=>nE(null),1800);return()=>clearTimeout(e)},[nT]);let nP=(0,s.useCallback)(()=>{(0,a.flushSync)(()=>ng(hR));let e=tD.current;e&&(e.scrollTop=e.scrollHeight)},[tD]),n_=(0,s.useCallback)(()=>{nb&&nP(),tP()},[nb,nP,tP]),nF=(0,s.useRef)(null),[nz,nW]=(0,s.useState)(!1);(0,s.useEffect)(()=>{if(!O||nF.current===O.id||O.sessionId!==e?.id||eT||0===t9.length)return;nF.current=O.id,D?.(O.id);let t=eE.indexOf(O.entryId);if(t<0)return void nW(!0);let n=0;for(let e=0;e<nh.length;e++){let r=nh[e].idx;if(r>t||(n=e,r===t))break}nA(n)},[O,e?.id,eT,t9.length,eE,nh,nA,D]),(0,s.useEffect)(()=>{if(!nz)return;let e=setTimeout(()=>nW(!1),6e3);return()=>clearTimeout(e)},[nz]);let[nO,nD]=(0,s.useState)(!1),[nH,nU]=(0,s.useState)(0),nB=(0,s.useMemo)(()=>nO?nh.map(e=>(function(e,t){if("answer"===e.kind)return tu(e.blocks);let n=t[e.idx];return n&&"content"in n?tu(n.content):""})(e,t9).toLowerCase()):hW,[nO,nh,t9]),nq=(0,s.useCallback)(e=>{t_(),ng(t=>hA(nw.current,e,t))},[t_]),nV=(0,s.useCallback)(()=>nD(!1),[]);(0,s.useEffect)(()=>{let e=e=>{if(e.defaultPrevented||e.isComposing||e.altKey||e.shiftKey||!(e.ctrlKey||e.metaKey)||"f"!==e.key.toLowerCase())return;let t=tD.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(),nD(!0),nU(e=>e+1))};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[tD]);let nK=(0,s.useMemo)(()=>{let e=[];return nh.forEach((t,n)=>{if("message"!==t.kind)return;let r=h_(t9[t.idx]);null!==r&&e.push({item:n,text:r})}),e},[nh,t9]),nJ=`${nx}:${nv}`,nG=eE.length>0?eE[eE.length-1]:null,[nZ,nY]=(0,s.useState)(null),nQ=(0,s.useRef)(!1);(0,s.useEffect)(()=>{nQ.current||!tf||eT||!e?.id||(nQ.current=!0,nr||!nG||!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}(t9)||function(e){try{return window.localStorage.getItem(hO(e))}catch{return null}}(e.id)!==nG&&nY(nG))},[tf,eT,e?.id,nr,nG,t9]);let nX=(0,s.useCallback)(()=>{e?.id&&nZ&&function(e,t){try{window.localStorage.setItem(hO(e),t)}catch{}}(e.id,nZ),nY(null)},[e?.id,nZ]),n2=null!==nZ&&nZ===nG&&!nr&&!nb,n4=tm?[tm.sessionId,tm.sessionFile??"",tm.sessionName??"",tm.userMessages,tm.assistantMessages,tm.toolCalls,tm.toolResults,tm.totalMessages,tm.tokens.input,tm.tokens.output,tm.tokens.cacheRead,tm.tokens.cacheWrite,tm.tokens.total,tm.cost??0,tm.totalActiveMs??0].join("|"):null,n8=(0,s.useRef)(tm);n8.current=tm,(0,s.useEffect)(()=>{v?.(n8.current)},[n4,v]),(0,s.useEffect)(()=>()=>{v?.(null)},[v]);let n5=e8?`${e8.percent??"null"}|${e8.contextWindow}|${e8.tokens??"null"}`:null,n6=(0,s.useRef)(e8);n6.current=e8,(0,s.useEffect)(()=>{b?.(n6.current)},[n5,b]),(0,s.useEffect)(()=>()=>{b?.(null)},[b]),(0,s.useEffect)(()=>{w?.(tb)},[w,tb]),(0,s.useEffect)(()=>()=>{w?.([])},[w]);let{regular:n3,lab:n7}=(0,s.useMemo)(()=>(function(e){let t=[],n=[];for(let s of e){var r;((r=s.key).startsWith(cU)&&null!==cB(r)?n:t).push(s)}return{regular:t,lab:n}})(tT),[tT]),n9=e?.id??null;(0,s.useEffect)(()=>{k?.(n9,n7)},[k,n9,n7]),(0,s.useEffect)(()=>()=>{k?.(null,[])},[k]);let{isDragOver:rt,handleDragEnter:rn,handleDragOver:rr,handleDragLeave:rs,handleDrop:ra}=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=>{nr||m?.current?.addAttachments(e)},[nr,m])),ri=(0,s.useMemo)(()=>{var e;return e=tg?.messages,e&&e.length>0?[...e,...t9]:t9},[tg,t9]),rl=(0,s.useMemo)(()=>{let e=new Map;for(let t of ri)"toolResult"===t.role&&e.set(t.toolCallId,t);return e},[ri]),ru=(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=aY(e.status);if(!r||o.has(r)||"completed"!==a&&"failed"!==a&&"aborted"!==a)return;o.add(r);let i=aZ(e);null!==i&&s.set(r,i)},d=(e,t,r)=>{let s=t?n.get(t):void 0,a=aZ(e);s&&"number"==typeof r&&null!==a&&"running"===aY(e.status)&&i.set(s,Math.max(i.get(s)??-1/0,r-a))},ri.forEach((t,s)=>{if("assistant"===t.role){for(let e of t.content??[]){if("toolCall"!==e.type||"task"!==e.toolName)continue;let t=rl.get(e.toolCallId);if(t)for(let s of aX(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(aQ(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=aG(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:aG(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 aJ(t.details?.jobs)){if("task"!==r.type)continue;let a=aG(r.id);if(a&&l(a,aY(r.status),s),c(r,a),d(r,a,t.timestamp),a&&"running"===aY(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 aQ(t.content).matchAll(a0)){let t=Object.fromEntries([...e[1].matchAll(a1)].map(e=>[e[1],e[2]]));t.id&&l(t.id,aY(t.status),s)}for(let e of aJ(t.details?.jobs))"task"===e.type&&c(e,aG(e.jobId))}}),{verdicts:e,runs:t,latestByAgent:n,spawnedAt:r,durations:s,parallelWith:a,runStartedAt:i}},[ri,rl]),rh=(0,s.useMemo)(()=>({ledger:ru,subagents:tb,toolResults:rl,onOpenPanel:j,sessionId:e?.id??null,cwd:e?.cwd??t??void 0,onOpenMaker:C,selectedMaker:N}),[ru,tb,rl,j,e?.id,e?.cwd,t,C,N]),rp=(0,s.useMemo)(()=>{let e=new Set,t=[];for(let n=t9.length-1;n>=0;n-=1){let r=h_(t9[n]);if(!(!r||e.has(r))&&(e.add(r),t.push(r),t.length>=50))break}return t.reverse()},[t9]),rm=(0,s.useMemo)(()=>tA(t9,rl,tw,tg?.todoPhases??null),[t9,rl,tw,tg]),rg=(0,s.useMemo)(()=>cL(e$.streamingMessage).join("|"),[e$.streamingMessage]),rx=(0,s.useMemo)(()=>JSON.stringify(cR(e$.streamingMessage)),[e$.streamingMessage]),rv=(0,s.useMemo)(()=>JSON.stringify(cP(e$.streamingMessage)),[e$.streamingMessage]),ry=(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=cL(r),c=cP(r,a);if(0===s.length&&0===c.length||o<0)continue;let d=cR(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)})(t9,eE,rg.length>0?rg.split("|"):[],JSON.parse(rx),JSON.parse(rv)),[t9,eE,rg,rx,rv]),rb=e?.id??tz.current??void 0,rw=(G=cz(K=(0,s.useMemo)(()=>({sessionId:rb,sessionProvider:th?.provider,turns:ry,messages:t9,subagents:tb}),[rb,th?.provider,ry,t9,tb])),Z=cH(K),(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}([...G,...Z])),[G,Z])),rk=tR&&0===t9.length&&!e$.isStreaming&&!nr,rj=(0,s.useMemo)(()=>t9.filter(e=>"assistant"===e.role).length,[t9]),rS=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=e1(e);if(null===a)return;let i=e2(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}(e$.streamingMessage?.role==="assistant"?e$.streamingMessage:null,rj),rC=(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})(t9),[t9]),rN=e?.cwd??t??void 0,rT=th?eO[`${th.provider}:${th.modelId}`]??null:null,rI=th?eD[`${th.provider}:${th.modelId}`]??null:null,rM=(0,s.useRef)(null),rE=(0,s.useRef)(null),r$=(0,s.useCallback)(()=>{let e=rM.current?.querySelector("textarea");e&&(e.focus({preventScroll:!0}),e.setSelectionRange(e.value.length,e.value.length))},[]);(0,s.useEffect)(()=>(E?.(r$),()=>E?.(null)),[r$,E]),(0,s.useLayoutEffect)(()=>{let e=rE.current,t=e?.closest(".workspace-shell");if(!e||!t)return;let n=tD.current?.clientHeight??0,r=()=>{let r=Math.ceil(e.getBoundingClientRect().height);r>0&&t.style.setProperty("--omp-dock-h",`${r}px`);let s=tD.current;if(!s)return;let a=n-s.clientHeight;n=s.clientHeight,a<=0||s.scrollHeight-s.scrollTop-s.clientHeight-a<=1&&(s.scrollTop+=a)};r();let s=new ResizeObserver(r);return s.observe(e),()=>s.disconnect()},[eT,tD]);let rR=(0,s.useCallback)((...e)=>(null!==nf.end&&nP(),tH(...e)),[tH,nf.end,nP]),rL=(0,r.jsx)("div",{ref:rM,"data-chat-composer":"",style:{display:"contents"},children:(0,r.jsx)(uq,{ref:m,sessionId:e?.id??tz.current??void 0,onEnsureSession:tR&&t?t3:void 0,onLiveTranscriptPersisted:t7,onSend:rR,onAbort:tU,onSteer:eR?tY:void 0,onFollowUp:eR?tQ:void 0,onPromptWithStreamingBehavior:eR?tX:void 0,isStreaming:nr,model:th,isAutoModelSelection:tE,modelNames:e_,modelList:eF,modelError:ez,modelScopeWarnings:eW,onModelChange:tV,onMainPresetChange:e||tR?tJ:void 0,mainPresetActiveAlias:nn,modelRoles:eH,onRoleModelChange:tK,modelSwitching:tp,onCompact:e||tR?tZ:void 0,onAbortCompaction:t0,isCompacting:e3,compactError:tc,compactResult:td,toolPreset:eU,onToolPresetChange:e||tR?t8:void 0,thinkingLevel:eB,effectiveThinkingLevel:eq,outputTokensPerSecond:rS??rC,outputSpeedLive:null!==rS,thinkingCeiling:eV,onThinkingLevelChange:e||tR?t5:void 0,fastMode:eJ,fastModeBusy:eX,onFastModeToggle:e||tR?e0:void 0,availableThinkingLevels:rT,thinkingLevelMap:rI,retryInfo:e4,deliveryRows:ty,inputHistory:rp,onRecallQueue:t1,onRemoveQueuedMessage:t2,slashCommands:tx,slashCommandsLoading:tv,onLoadSlashCommands:t6,onBuiltinCommand:t4,soundEnabled:A,onSoundToggle:P,onAudioUnlock:W,draftKey:e?.id??(t?`new:${t}`:void 0),cwd:e?.cwd??t,sessionTitle:e?.name})}),rA=e$.streamingMessage,rP=(0,s.useMemo)(()=>rA?eY(rA,{isStreaming:!0}):[],[rA]),r_=(0,s.useMemo)(()=>rP.filter(e=>"answer"===e.kind).flatMap(e=>e.blocks),[rP]),rF=(0,s.useMemo)(()=>rP.filter(e=>"answer"!==e.kind).map(e=>e.blocks),[rP]),rz=rA?.role==="assistant"?rA:null,rW=(0,s.useMemo)(()=>{let e=-1;for(let t=t9.length-1;t>=0;t-=1)if("user"===t9[t].role){e=t;break}let t=e<0?-1:lK(t9,e);return{start:t,blocks:lq(t9,t+1,t9.length),priorCiHeads:lG(t9,rl,t+1),jobNotices:lV(t9,t+1,t9.length)}},[t9,rl]),rO=(0,s.useMemo)(()=>lM(rz?[...rW.blocks,...rz.content??[]]:rW.blocks,rl,nr,rW.priorCiHeads,rN,rW.jobNotices),[rW,rz,rl,nr,rN]),rD=(0,s.useMemo)(()=>nr?{...lB(rW.blocks,rl,rN),span:lZ(t9,rW.start+1,t9.length)}:null,[nr,rW,rl,rN,t9]),rH=(0,s.useMemo)(()=>rD?{...rD,flow:rO,latest:!0}:null,[rD,rO]),rU=(0,s.useMemo)(()=>{let e=null;if(nr)for(let t of nh)"message"===t.kind&&t9[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"&&lK(t,e.idx)===e.idx).map(e=>e.idx),a=null===n?null:lK(t,n),i=new Map;for(let[n,l]of(e.forEach((e,n)=>{"answer"===e.kind&&i.set(lK(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(lG(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&&ti(i[s]);)s-=1;if(i[s]!==a.throughEntryId)continue;let l=lq(t,n.from,n.to).filter(e=>"toolCall"===e.type&&"task"===e.toolName),h=lJ(t,r,n.from,n.to);c.set(e,{...a.summary,...h?{remaining:lU(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=lq(e,n,r),l=lJ(e,t,n,r);return{...lB(i,t,s),remaining:l?lU(l):null,span:lZ(e,n,r),flow:lM(i,t,!1,a,s,lV(e,n,r))}}(t,r,n.from,n.to,s,d),latest:e===o})}return c}(nh,t9,e,rl,rN,tg?.openRequest??null,eE)},[nh,t9,rl,rN,nr,tg,eE]),[rB,rq]=(0,s.useState)(null),rV=e?.id??null;(0,s.useEffect)(()=>{rq(null)},[rV]);let rK=null;for(let e of rU.keys())(null===rK||e>rK)&&(rK=e);let rJ=("live"===rB?null!==rH:null!==rB&&rU.has(rB))?rB:rH?"live":rK,rG="live"===rJ?rH:null===rJ?null:rU.get(rJ)??null,rZ=null!==rH,rY=(0,s.useMemo)(()=>({selected:rJ,shown:null!==H,select:e=>{rq(e),B?.()},latestTurn:rZ?null:rK,compactedCalls:nm?.calls,onOpenFile:I}),[B,rJ,H,rZ,rK,nm,I]),rQ=null===rJ||"live"===rJ||rJ===rK,rX=H&&(0,a.createPortal)((0,r.jsx)(a3.Provider,{value:rh,children:(0,r.jsx)(co,{summary:rG,live:"live"===rJ,folded:q,compactedCalls:rQ?nm?.calls:void 0,onOpenFile:I})}),H),r0=eR&&(t$?.kind==="running_tools"||(rz?.content??[]).some(e=>"text"===e.type&&/\S/.test(e.text)||"toolCall"===e.type)),r1=rc(t9,rz,th?.provider,th?.modelId),r2=r1.provider,r4=r1.model,r8=r1.credentialId;(0,s.useEffect)(()=>{if(!r0)return;let e=eg();e&&em.current!==e.turn&&ef.current!==e.turn&&(em.current=e.turn,ew("working",e,r2,r8,r4))},[r0,r2,r4,r8,eg,ew]);let[r5,r6]=(0,s.useState)(null),r3=(0,s.useCallback)(e=>{r6(e)},[]),r7=(0,s.useMemo)(()=>eP?{role:"bashExecution",command:eP.command,output:"",excludeFromContext:eP.excludeFromContext}:null,[eP]),r9=(0,s.useMemo)(()=>{let e=[eR&&!rA&&t$?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}(t$,Y):null,eL&&!eP?Y("chat.runningCommand"):null].filter(e=>!!e);return e.length>0?e.join(" \xb7 "):null},[eR,rA,t$,eL,eP,Y]);(0,s.useEffect)(()=>{if(!r5)return void T?.(null);let e=[],t=[],n=0;if(rA&&rF.length>0){let r=r5.messages.length+e.length;for(let s of(e.push(rA),rF))t.push({idx:r,blocks:s}),n+=eQ(s)}if(r7&&(t.push({idx:r5.messages.length+e.length}),e.push(r7)),0===t.length)return void T?.(r9?{...r5,status:r9}:r5);let r=-1;for(let e=r5.messages.length-1;e>=0;e--)if(to(r5.messages[e])){r=e;break}let s=r5.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}),T?.({...r5,groups:s,messages:[...r5.messages,...e],status:r9})},[r5,rF,rA,r7,r9,T]),(0,s.useEffect)(()=>()=>T?.(null),[T]);let se=n3.filter(e=>"belowEditor"!==e.placement),st=n3.filter(e=>"belowEditor"===e.placement);return eI?(0,r.jsx)("div",{className:"flex h-full items-center justify-center text-red-400",children:eI}):(0,r.jsxs)("div",{className:"chat-window relative flex h-full min-w-0 flex-col overflow-hidden","aria-busy":nc,"data-empty-start":rk&&!M?"true":void 0,style:{paddingBottom:"env(safe-area-inset-bottom)"},onDragEnter:rn,onDragOver:rr,onDragLeave:rs,onDrop:ra,children:[nc?(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:Y("chat.loadingSession")})}):null,rt&&!nr&&(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:Y("chat.attachFile")})}),tC&&(0,r.jsx)(hJ,{request:tC,onInput:tM}),rk&&!M?(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.340"]})]}),(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.0"]})]})]})]}),rN&&(0,r.jsxs)("section",{className:"empty-workspace-context","aria-label":Y("chat.emptyProjectLabel"),children:[(0,r.jsxs)("div",{className:"empty-workspace-context-text",children:[(0,r.jsx)("span",{className:"empty-workspace-context-kicker",children:Y("chat.emptyProjectLabel")}),(0,r.jsx)("strong",{children:tW(rN)||rN}),(0,r.jsx)("code",{title:rN,children:rN}),(0,r.jsx)("p",{children:Y("chat.emptyProjectHint")})]}),S&&(0,r.jsx)("button",{type:"button",className:"empty-workspace-context-action",onClick:S,children:Y("chat.openSessionList")})]}),(0,r.jsx)(hq,{notices:tk,align:"right"})]})}):(0,r.jsxs)(r.Fragment,{children:[M&&(0,r.jsx)("div",{className:"min-h-0 min-w-0 flex-1 overflow-hidden",children:M}),(0,r.jsxs)("div",{className:"relative min-w-0 flex-1 overflow-hidden","aria-hidden":!!M,style:{display:M?"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)(cp,{open:nO,onClose:nV,containerRef:tD,index:nB,renderedStart:nx,renderedEnd:nv,contentKey:t9,onReveal:nq,onProgrammaticScroll:t_,focusRequest:nH,t:Y}),nz&&(0,r.jsx)("div",{className:"chat-jump-missing",role:"status",children:Y("chat.jumpMissing")}),(0,r.jsx)(hq,{notices:tk,floating:!0,align:"right"})]})}),(0,r.jsx)("div",{ref:tD,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)(hB,{widgets:se}),(0,r.jsx)(a3.Provider,{value:rh,children:(0,r.jsxs)(o7.Provider,{value:rY,children:[(0,r.jsx)(cT,{utterances:rw,children:(0,r.jsx)(hD,{messages:t9,entryIds:eE,toolResultsMap:rl,modelNames:e_,messageCwd:rN,onOpenFile:I,sessionBusy:nr,isNew:tR,isStreaming:e$.isStreaming,handleFork:tB,forkingEntryId:e6,handleNavigate:tq,handleEditContent:eN,sessionId:e?.id??tz.current??void 0,main:nh,turnSummaries:rU,process:np,startIndex:nx,endIndex:nv,sentinelRef:nk,laterSentinelRef:nj,flashItem:nT,t:Y,cues:ea,cueFollowRef:na,onProcessLogChange:r3})}),!nb&&e$.isStreaming&&e$.streamingMessage&&r_.length>0&&(0,r.jsx)(s9,{message:eK(e$.streamingMessage,r_),sessionId:e?.id??tz.current??void 0,isStreaming:!0,modelNames:e_,cwd:rN,onOpenFile:I}),!nb&&rH&&(0,r.jsx)(cn,{summary:rH,turnKey:"live",live:!0})]})}),n2&&(0,r.jsx)(cy,{onDismiss:nX,t:Y}),(0,r.jsx)("div",{ref:tO})]})})}),(0,r.jsx)(cm,{questions:nK,containerRef:tD,layoutKey:nJ,onJump:nA,label:Y("chat.questionRail")}),(nr&&tL||nb)&&(0,r.jsxs)("button",{type:"button",onClick:n_,"aria-label":Y("chat.jumpToBottom"),title:Y("chat.jumpToBottom"),style:{position:"absolute",bottom:16,left:"50%",transform:"translateX(-50%)",zIndex:40,display:"flex",alignItems:"center",gap:6,padding:"6px 12px",minHeight:X?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"})]}),Y("chat.jumpToBottom")]})]})]}),(0,r.jsxs)("div",{ref:rE,className:"relative chat-composer-dock flex min-h-0 flex-col",children:[tj&&(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)(hK,{request:tj,onRespond:tI,onActivity:(e,t)=>void tM(e,t??"activity"),delivery:tS})})}),(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:tn,t:Y}),(0,r.jsx)(hU,{goal:tF,t:Y}),(0,r.jsx)(hB,{widgets:st}),(rm||rO.steps.length>0)&&!et&&(0,r.jsx)(uK,{phases:rm,flow:rO,busy:nr})]})}),q&&!H&&rG&&null!==rJ&&!et&&(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)(a3.Provider,{value:rh,children:(0,r.jsx)(cs,{summary:rG,live:"live"===rJ,onOpen:()=>rY.select(rJ)})})})}),rL,(0,r.jsx)(uV,{statuses:tN})]}),rX]})}function hU({goal:e,t}){if(!e)return null;let n=!e.enabled,s=void 0!==e.tokenBudget?t("chat.goalBudgetLeft",{left:nV(Math.max(0,e.tokenBudget-e.tokensUsed))}):t("chat.goalTokensUsed",{used:nV(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 hB({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 hq({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 hV({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 hK({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)(hV,{focusKey:e.id,label:i("chat.agentQuestion"),delivery:a,children:(0,r.jsx)(c9,{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)(hV,{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)(hV,{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)(nk,{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)(hV,{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 hJ({request:e,onInput:t}){let{t:n}=(0,F.s)(),a=(0,s.useRef)(null),i=(0,s.useRef)(!1),l=ez(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=eD[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":" ":eO[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}`,eW(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 hG=n(40960),hZ=n.n(hG);function hY({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?` ${hZ().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})]})}let hQ={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"})]}),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 hX({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:hQ[e]})}function h0({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)"})]})})}function h1({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)(hX,{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 h2=n(50640),h4=n(73620);let h8=/^(?:\uFEFF)?---[ \t]*(?:\r\n|\n|\r)/;function h5(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 h6=["tags","categories","keywords","tag","category"];function h3({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=h6.find(t=>Array.isArray(e[t])),i=a?e[a].map(h5).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=h5(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 h7=n(8745);let h9=(0,s.createContext)(null),pe=(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"})}),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:"m10 3-5 5 5 5"})}),pr=(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"})}),ps=(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 pa({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:pn})}),(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)(h7.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)(h7.A.Item,{value:e.value,title:e.title,children:[(0,r.jsx)(h7.A.ItemHiddenInput,{}),e.label]},e.value)),(0,r.jsx)(h7.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:ps})})}),(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)(pi,{}),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:pr})})]})}function pi({className:e="panel-header-button"}){let{t}=(0,F.s)(),n=(0,s.useContext)(h9);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:pe})})}let pl="cuelo-html-pick",po="cuelo-html-pick-exit";function pc(e,t){return"string"==typeof e&&e.length<=t}function pd(e){return"number"==typeof e&&Number.isFinite(e)}function pu({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 dB(e,t,n){if(e===t)return n?dz(n):dO(t);let r=dO(e),s=n&&!dW(n)?dz(n):r??(n?dz(n):null),a=dO(t),i=dj.get(e);if(dj.delete(e),i&&!dj.has(t)&&dj.set(t,i),dH(e),!s)return a;let l=a?dU(a.value,a.images,s.value,s.images,a.documents,s.documents):s;return dD(t,l),dz(l)}function dq(e){let t=[];for(let n of e??[])n.attachmentId&&!t.includes(n.attachmentId)&&t.push(n.attachmentId);return t}function dV(e){d_();let t=dj.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)}`}(),dj.set(e,t)),t}function dK(e){let t=dq(db.get(e)?.documents),n=t.length?dV(e):dj.get(e);for(let[e,n]of dM){for(let e of t)n.delete(e);0===n.size&&dM.delete(e)}let r=`${n??""}|${t.join(",")}`;d$.get(e)!==r&&(0!==t.length||n?d$.set(e,r):d$.delete(e),d0())}async function dJ(e){let t=dV(e);dI.set(t,(dI.get(t)??0)+1),await dR.get(t);let n=!1;return{draftId:t,end(e){if(n)return;n=!0;let r=(dI.get(t)??1)-1;if(r>0?dI.set(t,r):dI.delete(t),e){let n=dM.get(t)??new Set;n.add(e),dM.set(t,n)}dS.set(t,dC),d0()}}}function dG(e,t){let n=dE.get(e);if(!n)return[];for(let e of t)n.delete(e);return 0===n.size&&dE.delete(e),[...n].sort()}async function dZ(){if(!dL)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 dj)t(n,dq(db.get(e)?.documents));for(let{draftId:e,ids:n}of dN.values())t(e,n);for(let[e,n]of dM)t(e,n);for(let e of dS.keys())t(e,[]);for(let e of dE.keys())t(e,[]);return new Map([...e].map(([e,t])=>[e,[...t].sort()]))}()].filter(([e,t])=>{if(dI.has(e))return!1;let n=dS.get(e);return dG(e,t).length>0||(0===t.length?void 0!==n:n!==t.join(","))}),t=dI.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=dG(r,s),a=dL(r,s,e).then(()=>{0===s.length?dS.delete(r):dS.set(r,s.join(","));let t=dE.get(r);if(t){for(let n of e)t.delete(n);0===t.size&&dE.delete(r)}},()=>{n=!0,s.length>0&&(t=!0)});dR.set(r,a),await a,dR.get(r)===a&&dR.delete(r)}n?function(){if(dX)return;dX=!0;let e=setTimeout(()=>{dX=!1,d0()},dQ);"object"==typeof e&&"unref"in e&&e.unref(),dQ=Math.min(2*dQ,6e4)}():dQ=dY}let dY=5e3,dQ=5e3,dX=!1;function d0(){if(dL){if(dA){dP=!0;return}dA=Promise.resolve().then(dZ).finally(()=>{dA=null,dP&&(dP=!1,d0())})}}let d1=Math.floor(Number.MAX_SAFE_INTEGER/1048576),d2=Object.freeze({uploadLimitMb:100,autoCleanupEnabled:!0,orphanGraceDays:7});function d4(e){return"number"==typeof e&&Number.isSafeInteger(e)&&e>=1&&e<=d1}async function d8(e){let t,n=await e.json().catch(()=>null);if(!e.ok||!n||!d4(n.uploadLimitMb)||"boolean"!=typeof n.autoCleanupEnabled)throw Error("string"==typeof n?.error?n.error:`HTTP ${e.status}`);return{uploadLimitMb:d4((t=n&&"object"==typeof n?n:{}).uploadLimitMb)?t.uploadLimitMb:d2.uploadLimitMb,autoCleanupEnabled:"boolean"==typeof t.autoCleanupEnabled?t.autoCleanupEnabled:d2.autoCleanupEnabled,orphanGraceDays:7}}async function d5(e={}){return d8(await fetch("/api/attachment-settings",{cache:"no-store",signal:e.signal}))}async function d6(e){return d8(await fetch("/api/attachment-settings",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}))}function d3(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 d7(e){let t=0;for(let n=0;n<e.length;n++)"/"===e[n]&&t++;return t}function d9(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 ue(e,t){let n=t?`${e}/`:e;return n.includes(" ")?`@"${n}" `:`@${n} `}function ut(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 un="omp-web:model-picks";function ur(){try{let e=JSON.parse(window.localStorage.getItem(un)??"{}");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 us(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 ua(e,t,n){return Math.min(e*t,n)}function ui(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=us(s.top,s.bottom,n,ua(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 ul=n(14755);let uo="omp-web:model-roles-expanded";async function uc(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=[...uj,...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 ud(e){let t=e.transcription?.state;return"planning"===t||"confirm"===t||"running"===t}let uu=["off","default","full"],uh={off:"none",default:"default",full:"full"},up=ul.IN.join(" \xb7 "),um=ul.C1.filter(e=>!ul.IN.includes(e)).join(" \xb7 ");function uf(e){return"above"===e?{bottom:"calc(100% + 8px)"}:{top:"calc(100% + 8px)"}}let ug=new Intl.Collator(void 0,{numeric:!0,sensitivity:"base"}),ux=0,uv={"text/markdown":"Markdown","text/plain":"Text","application/pdf":"PDF"};function uy(e,t){return ug.compare(e.name||e.modelId,t.name||t.modelId)||ug.compare(e.provider,t.provider)||ug.compare(e.modelId,t.modelId)}let ub=["auto","off","minimal","low","medium","high","xhigh","max"],uw=["low","medium","high","xhigh"],uk={auto:"chat.thinkingAuto",off:"chat.thinkingOff",minimal:"chat.thinkingMinimal",low:"chat.thinkingLow",medium:"chat.thinkingMedium",high:"chat.thinkingHigh",xhigh:"chat.thinkingXhigh",max:"chat.thinkingMax"},uj=[{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"}],uS=["builtin","extension","custom","mcp_prompt","prompt","file","skill"],uC={builtin:"chat.builtIn",extension:"chat.extensions",custom:"chat.customCommands",mcp_prompt:"chat.mcpPrompts",prompt:"chat.prompts",file:"chat.fileCommands",skill:"chat.skills"},uN={builtin:0,extension:1,custom:2,mcp_prompt:3,prompt:4,file:5,skill:6};function uT(e,t,n){let r=e.name.toLowerCase(),s=uI(e,n).toLowerCase();return r===t?0:r.startsWith(t)?1:r.includes(t)?2:s.includes(t)?3:4}function uI(e,t){return"descriptionKey"in e?t(e.descriptionKey):e.description??""}function uM(e,t){return"skill"===e.source&&!!e.name.startsWith("skill:")&&!0===t[e.name.slice(6)]}function uE(e){return{data:e.data,mimeType:e.mimeType}}function u$(e){return{...e,previewUrl:`data:${e.mimeType};base64,${e.data}`}}function uR(e){return(e??[]).filter(nH).slice(0,10).map(u$)}let uL=/^File saved at: (.+)\n\(([^,\n]+), (\d+) bytes\)/,uA="\n\nTranscript of the audio ";function uP(e){return sz(e).map(e=>{let t=sq(e),n="audio"===t&&e.attachmentId&&!e.text.includes(uA)?uL.exec(e.text):null;return{...e,id:++ux,status:"ready",..."audio"===t||"file"===t?{stored:t}:{},...n?{storedInfo:{path:n[1],mimeType:n[2],size:Number(n[3])}}:{}}})}function u_({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 uF(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 uz extends Error{constructor(e,t,n,r){super(e),this.code=t,this.completedParts=n,this.parts=r}}let uW="composer:unkeyed";async function uO(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 uz("string"==typeof n.error?n.error:`HTTP ${e.status}`,"string"==typeof n.code?n.code:null,r,s)}function uD(e){e.previewUrl.startsWith("blob:")&&URL.revokeObjectURL(e.previewUrl)}function uH({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 uU({error:e}){return e?(0,r.jsx)(uH,{tone:"error",title:"Model error",body:e}):null}function uB({warnings:e}){return e&&0!==e.length?(0,r.jsx)(uH,{tone:"warning",title:e.length>1?"Model scope warnings":"Model scope warning",body:e.join("\n")}):null}let uq=(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:A,fastMode:P=null,fastModeBusy:_=!1,onFastModeToggle:z,retryInfo:W,deliveryRows:O=[],inputHistory:D=[],onRecallQueue:H,onRemoveQueuedMessage:B,slashCommands:q,slashCommandsLoading:V,onLoadSlashCommands:K,onBuiltinCommand:J,soundEnabled:G,onSoundToggle:Z,onAudioUnlock:Y,onPromptWithStreamingBehavior:Q,draftKey:X,cwd:ee,sessionTitle:et,sessionId:en,onEnsureSession:er,onLiveTranscriptPersisted:es},ea){let ei,el,eo,ec,ed,eu,eh,ep,em,ef,{t:eg}=(0,F.s)();su();let{st:ex}=sp(),ev=O.some(e=>e.removable),ey=U(),[eb,ew]=(0,s.useState)(()=>X?dO(X)?.value??"":""),[ek,ej]=(0,s.useState)(!1),[eS,eC]=(0,s.useState)(null),[eN,eT]=(0,s.useState)(""),[eI,eM]=(0,s.useState)({});(0,s.useEffect)(()=>{ek&&eM(ur())},[ek]);let[eE,e$]=(0,s.useState)(!1);(0,s.useEffect)(()=>{if(ek)try{e$("1"===window.localStorage.getItem(uo))}catch{}},[ek]);let eR=()=>{e$(e=>{let t=!e;try{window.localStorage.setItem(uo,t?"1":"0")}catch{}return t})},[eL,eA]=(0,s.useState)(!1),[eP,e_]=(0,s.useState)(null),[eF,ez]=(0,s.useState)(!1),[eW,eO]=(0,s.useState)(!1),[eD,eH]=(0,s.useState)(null),[eU,eB]=(0,s.useState)(!1),[eq,eV]=(0,s.useState)(()=>X?uR(dO(X)?.images):[]),[eK,eJ]=(0,s.useState)(()=>X?uP(dO(X)?.documents):[]),[eG,eZ]=(0,s.useState)(null),eY=(0,s.useMemo)(()=>eK.filter(e=>"ready"===e.status),[eK]),eQ=eK.some(e=>"ready"!==e.status||ud(e)),eX=eK.filter(e=>"audio"===e.stored&&e.attachmentId&&e.storedInfo&&(void 0!==e.transcription||!e.text.includes(uA))),e0=eb.trimStart(),e1=0===eq.length&&0===eK.length&&e0.startsWith("!"),e2=e1&&e0.startsWith("!!"),[e4,e8]=(0,s.useState)(!1),[e5,e6]=(0,s.useState)(0),[e3,e7]=(0,s.useState)(null),e9=e3?.value===eb&&e3.draftKey===X?e3.token:null,[te,tt]=(0,s.useState)(!1),[tn,tr]=(0,s.useState)(!1),ts=(0,s.useRef)(null),[ta,ti]=(0,s.useState)(null),[tl,to]=(0,s.useState)(!1),[tc,td]=(0,s.useState)(0),[tu,th]=(0,s.useState)(!1),[tp,tm]=(0,s.useState)(0),[tf,tg]=(0,s.useState)(null),[tx,tv]=(0,s.useState)(!1),[ty,tb]=(0,s.useState)(null),[tw,tk]=(0,s.useState)(null),tj=ee&&tw?.cwd===ee?tw.values:{},tS=(0,s.useRef)(null),tC=(0,s.useRef)(null),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),tA=(0,s.useRef)(null),tP=(0,s.useRef)(!1),t_=(0,s.useRef)(0),tF=(0,s.useRef)(!1),tz=(0,s.useRef)([]),tW=(0,s.useRef)([]),tO=(0,s.useRef)([]),tD=(0,s.useRef)(null),tH=(0,s.useRef)(null),tU=(0,s.useRef)(X),tB=(0,s.useRef)(eb),tq=(0,s.useRef)(eq),tV=(0,s.useRef)(0),tK=(0,s.useRef)(eK);tB.current=eb,tq.current=eq,tK.current=eK,(0,s.useImperativeHandle)(ea,()=>({insertIfEmpty(e){let t=tS.current;(t?t.value:eb).trim()||(tB.current=e,ew(e),ti(null),requestAnimationFrame(()=>{t&&(t.focus(),t.style.height="auto",t.style.height=`${Math.min(t.scrollHeight,200)}px`)}))},replaceMessage(e){let t,n,r=tS.current;if(!function(e,t,n,r=0){return!e.trim()&&0===t&&0===n&&0===r}(r?r.value:eb,tq.current.length,tV.current,tK.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"),sD(t)?.message??t),a=uR("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 nH(r)?[r]:[]})),i=uP((n="string"==typeof e.content?e.content:e.content.filter(e=>"text"===e.type).map(e=>e.text).join("\n"),sD(n)?.documents??[]));tB.current=s,tq.current=a,tK.current=i,ew(s),ti(null),th(!1),eV(e=>(e.forEach(uD),a)),eJ(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(tU.current!==e)return void dB(e,t);let n={value:tB.current,images:tq.current.map(uE),documents:tK.current.filter(e=>"ready"===e.status).map(u_)},r=dB(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(tU.current=t,s)return;let a=uR(r.images),i=uF(uP(r.documents),tK.current),l=r.value;tB.current=l,tq.current=a,tK.current=i,ew(l),eV(e=>(e.forEach(uD),a)),eJ(i),ti(null),th(!1)},restoreSubmission(e,t,n,r){if(!e.trim()&&!t?.length&&!n?.length)return;let s=tU.current,a=r??s,i=a===s,l=!i&&a?dO(a):null,o=dU(e,t,i?tB.current:l?.value??"",i?tq.current.map(uE):l?.images??[],n,i?tK.current.filter(e=>"ready"===e.status).map(u_):l?.documents??[]);if(a&&dD(a,o),!i)return;let c=t?.length?[...uR(t).slice(0,Math.max(0,10-tq.current.length)),...tq.current].slice(0,10):tq.current,d=uF(uP(o.documents),tK.current);tB.current=o.value,tq.current=c,tK.current=d,ew(o.value),ti(null),th(!1),t?.length&&eV(e=>{let n=Math.max(0,10-e.length),r=uR(t).slice(0,n),s=r.length>0?[...r,...e]:e;return tq.current=s,s}),eJ(d),requestAnimationFrame(()=>{let e=tS.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=tS.current;if(!t)return void ew(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;tB.current=l,ew(l),ti(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){t9(e)}}));let tJ=(0,s.useCallback)(async e=>{let t=Math.max(0,10-tq.current.length-tV.current),n=e.filter(e=>e.size>0xa00000);n.length>0&&eZ(eg("chat.attachImageTooLarge",{name:n.map(e=>e.name).join(", "),limit:sH(0xa00000)}));let r=e.filter(e=>e.size<=0xa00000),s=r.slice(0,t);if(s.length<r.length&&eZ(eg("chat.attachImageLimit",{count:10})),s.length){tV.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)})));eV(t=>{let n=e.slice(0,Math.max(0,10-t.length));e.slice(n.length).forEach(uD);let r=[...t,...n];return tq.current=r,r})}finally{tV.current-=s.length}}},[eg]),tG=(0,s.useCallback)(async e=>{for(let t of e){let e=sA(t);if(!e)continue;if(tK.current.length>=3){eZ(eg("chat.attachLimit",{count:3}));continue}if(t.size>8388608){eZ(eg("chat.attachTooLarge",{name:t.name,limit:sH(8388608)}));continue}if(tK.current.reduce((e,t)=>e+t.size,0)+t.size>0x1000000){eZ(eg("chat.attachTotalTooLarge",{limit:sH(0x1000000)}));continue}let n={id:++ux,name:t.name,mimeType:s$[e],size:t.size,text:"",status:"extracting"},r=[...tK.current,n];tK.current=r,eJ(r);try{let e=await sW(t);if(tK.current.reduce((e,t)=>e+(t.id===n.id?0:t.text.length),0)+e.text.length>24e4)throw new sE("text_too_large","Total extracted text exceeds 240000 characters");let r=tK.current.map(t=>t.id===n.id?{...e,id:t.id,status:"ready"}:t);tK.current=r,eJ(r)}catch(s){let e=tK.current.some(e=>e.id===n.id),r=tK.current.filter(e=>e.id!==n.id);if(tK.current=r,eJ(r),!e)continue;s instanceof sE?"text_too_large"===s.code?eZ(eg("chat.attachTextTooLarge",{name:t.name,limit:12e4.toLocaleString()})):"too_many_pages"===s.code?eZ(eg("chat.attachTooManyPages",{name:t.name,limit:250})):"no_extractable_text"===s.code?eZ(eg("chat.attachNoPdfText",{name:t.name})):"password_protected"===s.code?eZ(eg("chat.attachPasswordProtected",{name:t.name})):eZ(eg("chat.attachExtractFailed",{name:t.name})):eZ(eg("chat.attachExtractFailed",{name:t.name}))}}},[eg]),tZ=(0,s.useCallback)((e,t)=>{if(!tK.current.some(t=>t.id===e))return!1;let n=t?tK.current.map(n=>n.id===e?t:n):tK.current.filter(t=>t.id!==e);return tK.current=n,eJ(n),!0},[]),tY=(0,s.useCallback)((e,t)=>{if(!tK.current.some(t=>t.attachmentId===e))return!1;let n=tK.current.map(n=>n.attachmentId===e?t(n):n);return tK.current=n,eJ(n),!0},[]),tQ=(0,s.useCallback)((e,t,n)=>{if(!e||e===tU.current)return;let r=dO(e);r?.documents.some(e=>e.attachmentId===t)&&dD(e,{...r,documents:uP(r.documents).map(e=>e.attachmentId===t?n(e):e).map(u_)})},[]),tX=(0,s.useRef)(new Map),t0=(0,s.useRef)(new Map),t1=(0,s.useRef)(new Set),t2=(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=sV({...e.storedInfo,transcript:t},r);return s.length>r?null:{...e,text:s,size:new TextEncoder().encode(s).byteLength,transcription:void 0}},[]),t4=(0,s.useCallback)(e=>e instanceof uz&&"media_tool_unavailable"===e.code?eg("chat.transcribeToolMissing"):e instanceof uz&&"transcription_failed"===e.code&&null!==e.completedParts&&null!==e.parts?eg("chat.transcribePartialFailed",{done:e.completedParts,total:e.parts}):e instanceof Error?e.message:String(e),[eg]),t8=(0,s.useCallback)(async(e,t)=>{let n=tU.current,r=tK.current.find(t=>t.attachmentId===e);if(!r?.storedInfo)return;let s=r.transcription?.state==="confirm"?r.transcription.plan:null;t0.current.get(e)?.abort();let a=new AbortController;t0.current.set(e,a),tY(e,e=>({...e,transcription:{state:"running",plan:s}}));try{let r=await uO(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 uz("Invalid transcription result",null,null,null);let s=r.transcript;tY(e,e=>t2(e,s,tK.current)??{...e,transcription:{state:"failed",error:eg("chat.transcribeTooLong")}})||tQ(n,e,e=>t2(e,s,[])??e)}catch(n){if(a.signal.aborted)return void tY(e,e=>({...e,transcription:{state:"skipped"}}));if(n instanceof uz&&"confirmation_required"===n.code)return void t5.current?.(e);let t=t4(n);tY(e,e=>({...e,transcription:{state:"failed",error:t}}))}finally{t0.current.get(e)===a&&t0.current.delete(e)}},[eg,t4,tY,tQ,t2]),t5=(0,s.useRef)(null),t6=(0,s.useCallback)(async e=>{let t;t0.current.get(e)?.abort();let n=new AbortController;t0.current.set(e,n),tY(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 uz("Invalid transcription plan",null,null,null);return{durationSeconds:e.durationSeconds,estimatedCalls:e.estimatedCalls,requiresConfirmation:e.requiresConfirmation,processing:e.processing,notice:e.notice}}(await uO(await fetch(`/api/attachments/${encodeURIComponent(e)}/transcription`,{cache:"no-store",signal:n.signal})))}catch(t){if(n.signal.aborted)tY(e,e=>({...e,transcription:{state:"skipped"}}));else{let n=t4(t);tY(e,e=>({...e,transcription:{state:"failed",error:n}}))}return}finally{t0.current.get(e)===n&&t0.current.delete(e)}t.requiresConfirmation?tY(e,e=>({...e,transcription:{state:"confirm",plan:t}})):await t8(e,!1)},[t8,t4,tY]);t5.current=t6;let t3=(0,s.useCallback)(e=>{let t=t0.current.get(e);t?t.abort():tY(e,e=>({...e,transcription:{state:"skipped"}}))},[tY]),t7=(0,s.useCallback)(async(e,t)=>{let n=null;for(let r of e){if(tK.current.length>=3){eZ(eg("chat.attachLimit",{count:3}));continue}let e="file"===t&&r.size<=8388608,s={id:++ux,name:r.name,mimeType:"text/plain",size:e?r.size:0,text:"",status:e?"extracting":"uploading",sourceSize:r.size},a=[...tK.current,s];tK.current=a,eJ(a);let i=(e,t)=>{let n=tK.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]?sF("utf-16le",t.subarray(2)):254===t[0]&&255===t[1]?sF("utf-16be",t.subarray(2)):t.includes(0)?null:sF("utf-8",t)??sF("euc-kr",t)},()=>null);if(null!==e&&i(e.length,r.size)){tZ(s.id,{...s,text:e,status:"ready"});continue}}if(null===n&&(n=1048576*(await d5().catch(()=>d2)).uploadLimitMb),r.size>n){tZ(s.id,null)&&eZ(eg("chat.attachStoredTooLarge",{name:r.name,limit:sH(n)}));continue}let l={...s,stored:t,status:"uploading",size:0};if(!tZ(s.id,l))continue;let o=tU.current??uW,c=await dJ(o),d=null,u=new AbortController;tX.current.set(s.id,u);try{if(t1.current.has(s.id))continue;let e=await sK(r,{sessionId:en,draftId:c.draftId,signal:u.signal}),n=tK.current.filter(e=>e.id!==s.id).reduce((e,t)=>e+t.text.length,0),a=sV({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)){tZ(s.id,null)&&eZ(eg("chat.attachTotalTooLarge",{limit:sH(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(tZ(s.id,p))d=e.id;else if(!t1.current.has(s.id)&&o!==tU.current){let t=dO(o)??{value:"",images:[],documents:[]};dD(o,{...t,documents:[...t.documents,u_(p)]}),d=e.id}}catch(e){if(u.signal.aborted)continue;tZ(s.id,null)&&eZ(eg("chat.attachUploadFailed",{name:r.name,error:e instanceof Error?e.message:String(e)}))}finally{tX.current.delete(s.id),c.end(d)}d&&"audio"===t&&tK.current.some(e=>e.attachmentId===d)&&t6(d)}},[tZ,t6,en,eg]),t9=(0,s.useCallback)(async e=>{eZ(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!==sA(a)?n.push(a):s_(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([tJ(t),tG(n.filter(e=>e.size<=8388608)),t7(r,"audio"),t7([...s,...a],"file")])},[tG,t7,tJ]),ne=(0,s.useCallback)(e=>{eV(t=>{let n=[...t],[r]=n.splice(e,1);return r&&uD(r),tq.current=n,n})},[]),nt=(0,s.useCallback)(e=>{let t=tK.current.find(t=>t.id===e);if(t1.current.add(e),tX.current.get(e)?.abort(),t?.attachmentId){t0.current.get(t.attachmentId)?.abort();var n=t.attachmentId;for(let[e,t]of dM)t.delete(n)&&(0===t.size&&dM.delete(e),d0())}let r=tK.current.filter(t=>t.id!==e);tK.current=r,eJ(r)},[]),nn=(0,s.useCallback)(()=>{tq.current=[],eV(e=>(e.forEach(uD),[]))},[]),nr=(0,s.useCallback)(()=>{tK.current=[],eJ([])},[]),ns=(0,s.useCallback)(()=>{tB.current="",ew(""),ti(null),e7(null),tt(!1),th(!1),X&&dH(X),tU.current&&tU.current!==X&&dH(tU.current),nn(),nr(),eZ(null),tS.current&&(tS.current.style.height="auto")},[nr,nn,X]);(0,s.useEffect)(()=>{X&&tU.current===X&&dD(X,{value:eb,images:eq.map(uE),documents:eY.map(u_)})},[eq,X,eY,eb]),(0,s.useEffect)(()=>{let e=tU.current;if(e===X)return;e&&dD(e,{value:tB.current,images:tq.current.map(uE),documents:tK.current.filter(e=>"ready"===e.status).map(u_)});let t=X?dO(X):null;tU.current=X;let n=t?.value??"",r=uR(t?.images),s=uP(t?.documents);tB.current=n,tq.current=r,tK.current=s,ew(n),ti(null),th(!1),eV(e=>(e.forEach(uD),r)),eJ(s)},[X]),(0,s.useEffect)(()=>{let e=tS.current;e&&(e.style.height="auto",eb&&(e.style.height=`${Math.min(e.scrollHeight,200)}px`))},[eb]),(0,s.useEffect)(()=>()=>{tq.current.forEach(uD)},[]);let na=(0,s.useCallback)((e,t)=>{let n=function(e,t){let n=dq(t);if(0===n.length)return()=>{};let r=++dT;return dN.set(r,{draftId:dV(e),ids:n}),e=>{if("accepted"!==e&&"returned"!==e)return;let t=dN.get(r);if(t){if(dN.delete(r),"accepted"===e){let e=dE.get(t.draftId)??new Set;for(let n of t.ids)e.add(n);dE.set(t.draftId,e)}d0()}}}(tU.current??uW,e);Promise.resolve(t()).then(e=>n("accepted"===e||"returned"===e?e:void 0),()=>void 0)},[]),ni=(0,s.useCallback)(async()=>{let t=eb.trim(),n=e0.trim(),r=n.startsWith("/")||n.startsWith("!")?n:t;if(!r&&!eq.length&&!eY.length||i||eQ)return;Y?.();let s=eq.length?eq:void 0,a=eY.length?eY:void 0;if(r.startsWith("/")){await uc(r,q,J,t=>na(a,()=>e(t,s,a)),eZ,!!(s||a),K)&&ns();return}ns(),na(a,()=>e(r,s,a))},[eb,e0,eq,eY,eQ,i,J,q,K,e,ns,Y,na]),nl=!e0.startsWith("/")||e0.startsWith("//")||/\s/.test(e0.slice(1))?null:e0.slice(1).toLowerCase(),no=(()=>{if(null===nl)return[];let e=[...i?[]:uj,...q??[]],t=new Set;return[...e].filter(e=>{let t=e.name.toLowerCase(),n=uI(e,eg).toLowerCase();return t.includes(nl)||n.includes(nl)}).sort((e,t)=>{let n=uT(e,nl,eg)-uT(t,nl,eg);return 0!==n?n:uN[e.source]-uN[t.source]||ug.compare(e.name,t.name)}).filter(e=>{let n=e.name.toLowerCase();return!t.has(n)&&(t.add(n),!0)})})(),{commands:nc,groups:nd}=(ei=0,{commands:(el=uS.map(e=>{let t=no.filter(t=>t.source===e),n="skill"===e?[...t.filter(e=>!uM(e,tj)),...t.filter(e=>uM(e,tj))]:t;return{source:e,items:n.map(e=>({command:e,index:ei++}))}}).filter(e=>e.items.length>0)).flatMap(e=>e.items.map(({command:e})=>e)),groups:el}),nu=1===no.length?eg(nl?"chat.match":"chat.command"):eg(nl?"chat.matches":"chat.commands",{count:no.length}),nh=!!eb.trim(),np=!eQ&&(nh||eq.length>0||eY.length>0),nm=(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(e7(n?{value:e,draftKey:X,token:n}:null),tr(!1),!ee)return void ti(null);let r=t??e.length;ti(d3(e.slice(0,r)))},[ee,X]),nf=ta?.query??null,ng=s.useMemo(()=>null!==nf&&tf&&tf.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:d9(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:d9(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||d7(e.entry.path)-d7(t.entry.path)||e.entry.path.localeCompare(t.entry.path)),s.slice(0,n).map(e=>e.entry)}(tf.entries,nf):[],[nf,tf,ee]),nx=!!(nf&&tf?.truncated&&tf.cwd===ee);(0,s.useEffect)(()=>{if(!nx||!ee||!nf)return;let e=setTimeout(()=>{fetch(`/api/file-index?cwd=${encodeURIComponent(ee)}&q=${encodeURIComponent(nf)}`).then(e=>{if(!e.ok)throw Error(`file search failed: ${e.status}`);return e.json()}).then(e=>tb({cwd:ee,query:nf,matches:e.matches??[]})).catch(()=>{})},150);return()=>clearTimeout(e)},[nx,nf,ee]);let nv=nx&&null!==ty&&ty.cwd===ee&&ty.query===nf,ny=nv?ty.matches:ng,nb=null===ta?null:`${ta.start}:${+!!ta.quoted}:${ta.query}`;(0,s.useEffect)(()=>{if(null===nb){to(!1),td(0);return}to(!0),td(0)},[nb]);let nw=null!==ta,nk=ui(tL,tu,{viewportFraction:.44,cap:360}),nj=ui(tL,e4,{viewportFraction:.56,cap:460}),nS=ui(tL,tl,{viewportFraction:.48,cap:400}),nC=ui(tL,te,{viewportFraction:.48,cap:400}),nN=e9?`${e9.start}:${e9.end}:${e9.query}`:null;(0,s.useEffect)(()=>{tt(null!==nN)},[nN]);let nT=(0,s.useCallback)((e,t,n,r=!1)=>{tB.current===e&&tU.current===X&&(tB.current=t,ew(t),e7(null),tt(!1),tr(r),requestAnimationFrame(()=>{let e=tS.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(!nw||!ee)return;let e=tD.current;e&&e.cwd===ee&&Date.now()-e.fetchedAt<1e4||tH.current===ee||(tH.current=ee,tv(!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=>{tg({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)=>d7(e.path)-d7(t.path)||e.path.localeCompare(t.path)),n}(e.files??[]),truncated:!!e.truncated}),tD.current={cwd:ee,fetchedAt:Date.now()}}).catch(()=>{tD.current=null}).finally(()=>{tH.current=null,tv(!1)}))},[nw,ee]);let nI=(0,s.useCallback)(e=>{if(!ta)return;let t=tS.current,n=t?.selectionStart??eb.length,r=eb.slice(0,ta.start),s=eb.slice(n);ta.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,ta.quoted),i=r+a.text+s,l=r.length+a.cursorOffset;ew(i),ti(d3(i.slice(0,l))),requestAnimationFrame(()=>{let e=tS.current;e&&(e.focus(),e.setSelectionRange(l,l),e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)})},[ta,eb]);(0,s.useEffect)(()=>{tc>=ny.length&&td(Math.max(0,ny.length-1))},[ny.length,tc]),(0,s.useEffect)(()=>{tW.current.length=ny.length},[ny.length]),(0,s.useEffect)(()=>{tl&&tW.current[tc]?.scrollIntoView({block:"nearest",inline:"nearest"})},[tc,tl]),(0,s.useEffect)(()=>{tp>=D.length&&tm(Math.max(0,D.length-1))},[D.length,tp]),(0,s.useEffect)(()=>{tO.current.length=D.length},[D.length]),(0,s.useEffect)(()=>{tu&&tO.current[tp]?.scrollIntoView({block:"nearest",inline:"nearest"})},[tp,tu]);let nM=(0,s.useCallback)(e=>{tB.current=e,ew(e),th(!1),tm(0),ti(null),requestAnimationFrame(()=>{let t=tS.current;t&&(t.focus(),t.setSelectionRange(e.length,e.length),t.style.height="auto",t.style.height=`${Math.min(t.scrollHeight,200)}px`)})},[]),nE=(0,s.useCallback)(e=>{let t=`/${e.name} `;tB.current=t,ew(t),e8(!1),e6(0),requestAnimationFrame(()=>{let e=tS.current;e&&(e.focus(),e.setSelectionRange(t.length,t.length),e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)})},[]),n$=(0,s.useCallback)(async e=>{let t=eb.trim(),r=e0.trim(),s=r.startsWith("/")||r.startsWith("!")?r:t,i=eQ||!s&&0===eq.length&&0===eY.length?null:{message:s,images:eq.length?eq:void 0,documents:eY.length?eY:void 0};if(!i)return;Y?.();let l="steer"===e?"steer":"followUp";if(s.startsWith("/")){await uc(s,q,J,e=>{if(!Q)throw Error("Cannot queue this command while the session is busy.");na(i.documents,()=>Q(e,l,i.images,i.documents))},eZ,!!(i.images?.length||i.documents?.length),K)&&ns();return}ns(),"steer"===e&&n?na(i.documents,()=>n(i.message,i.images,i.documents)):"followup"===e&&a&&na(i.documents,()=>a(i.message,i.images,i.documents))},[eb,e0,eq,eY,eQ,q,K,J,Q,n,a,ns,Y,na]),nR=(0,s.useCallback)(e=>{let t=nc.length-1;if(t<0)return 0;if("left"===e)return Math.max(0,e5-1);if("right"===e)return Math.min(t,e5+1);let n=tz.current[e5];if(!n)return"down"===e?Math.min(t,e5+1):Math.max(0,e5-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===e5)continue;let t=tz.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,e5+1):Math.max(0,e5-1)},[nc.length,e5]),nL=(0,s.useCallback)(e=>{let r=e.nativeEvent,s=Date.now()-t_.current<100,l=tP.current||r.isComposing||229===r.keyCode;if("Enter"===e.key&&!e.shiftKey&&(l||s)){s&&e.preventDefault();return}if(tu&&!l){if("ArrowDown"===e.key){e.preventDefault(),tm(e=>Math.min(Math.max(0,D.length-1),e+1));return}if("ArrowUp"===e.key){e.preventDefault(),tm(e=>Math.max(0,e-1));return}if("Escape"===e.key){e.preventDefault(),th(!1);return}if(("Tab"===e.key||"Enter"===e.key&&!e.shiftKey)&&D[tp]){e.preventDefault(),nM(D[tp]);return}}if(!(te&&e9&&!l&&ts.current?.handleKeyDown(e))){if(e4&&null!==nl){if("ArrowDown"===e.key){e.preventDefault(),e6(nR("down"));return}if("ArrowUp"===e.key){e.preventDefault(),e6(nR("up"));return}if("ArrowRight"===e.key){e.preventDefault(),e6(nR("right"));return}if("ArrowLeft"===e.key){e.preventDefault(),e6(nR("left"));return}if("Escape"===e.key){e.preventDefault(),e8(!1);return}if(("Tab"===e.key||"Enter"===e.key&&!e.shiftKey)&&nc[e5]){e.preventDefault(),nE(nc[e5]);return}}if(tl&&null!==ta&&!l){if("ArrowDown"===e.key){e.preventDefault(),td(e=>Math.min(Math.max(0,ny.length-1),e+1));return}if("ArrowUp"===e.key){e.preventDefault(),td(e=>Math.max(0,e-1));return}if("Escape"===e.key){e.preventDefault(),to(!1);return}if(("Tab"===e.key||"Enter"===e.key&&!e.shiftKey)&&ny[tc]){e.preventDefault(),nI(ny[tc]);return}}if("ArrowUp"===e.key&&!l&&!i&&D.length>0&&0===eb.trim().length){e.preventDefault(),e8(!1),to(!1),tm(D.length-1),th(!0);return}if("Escape"===e.key&&!l&&i&&t){e.preventDefault(),t();return}"Enter"!==e.key||e.shiftKey||(e.preventDefault(),i&&(n||a)?n$(n?"steer":"followup"):ni())}},[i,n,a,t,e4,nl,nc,e5,nE,n$,ni,nR,tl,ta,ny,tc,nI,tu,D,tp,nM,eb,te,e9]),nA=(0,s.useCallback)(()=>{let e=tS.current;e&&(e.style.height="auto",e.style.height=`${Math.min(e.scrollHeight,200)}px`)},[]),nP=(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(),t9(t))},[t9]);(0,s.useEffect)(()=>{if(null===nl){e8(!1),e6(0),tF.current=!1;return}e8(!0),e6(0),!tF.current&&K&&(tF.current=!0,Promise.resolve(K()).catch(()=>{tF.current=!1}))},[nl,K]),(0,s.useEffect)(()=>{if(!e4||!ee)return;let e=!1;return tk({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;tk({cwd:ee,values:n})}).catch(()=>{e||tk({cwd:ee,values:{}})}),()=>{e=!0}},[e4,ee]),(0,s.useEffect)(()=>{e5>=nc.length&&e6(Math.max(0,nc.length-1))},[nc.length,e5]),(0,s.useEffect)(()=>{tz.current.length=nc.length},[nc.length]),(0,s.useEffect)(()=>{e4&&tz.current[e5]?.scrollIntoView({block:"nearest",inline:"nearest"})},[e5,e4]);let n_=u&&u.length>0?u.map(e=>({provider:e.provider,modelId:e.id,name:e.name})).sort(uy):Object.entries(d??{}).map(([e,t])=>({provider:o?.provider??"unknown",modelId:e,name:t})).sort(uy),nF=g??null,nz=rf.find(e=>e.alias===nF)?.provider??null,nW=nz?n_.filter(e=>e.provider===nz):n_,nO=(eo=eN.trim().toLocaleLowerCase())?nW.filter(e=>`${e.name} ${e.modelId}`.toLocaleLowerCase().includes(eo)):nW,nD=nW.length>8,nU=[];for(let e of nO){let t=nU.find(t=>t.provider===e.provider);t?t.options.push(e):nU.push({provider:e.provider,options:[e]})}let nB=nz?[]:(x??[]).filter(e=>!e.hidden&&e.resolved),nq=o?nB.find(e=>e.resolved?.provider===o.provider&&e.resolved?.modelId===o.modelId):void 0,nK=eN.trim()?[]:nW.map((e,t)=>{var n,r;return{option:e,order:t,count:eI[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(ej(!1),eT(""),!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}(ur(),(t=e.provider,n=e.modelId,`${t}/${n}`));try{window.localStorage.setItem(un,JSON.stringify(r))}catch{}eM(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:eg("chat.modelPickCount",{count:n})})]},`${t}:${e.provider}:${e.modelId}`)},nG=o?n_.find(e=>e.modelId===o.modelId&&e.provider===o.provider)?.name??o.modelId:null,nZ=S?Math.max(0,S.tokensBefore-S.estimatedTokensAfter):0,nY=S?`${S.reason&&"manual"!==S.reason?`${S.reason[0].toUpperCase()}${S.reason.slice(1)} `:eg("chat.compacted")} ${nV(S.tokensBefore)} -> ${nV(S.estimatedTokensAfter)} tokens (${eg("chat.tokensSaved",{saved:nV(nZ)})})`:null,nQ=e=>{let t=A?.[e];return null!=t&&t!==e?t:null},nX="auto"===(ec=T??"auto")?$?`auto ≤ ${nQ($)??$}`:"auto":A?A[ec]??ec:ec,n0=(T??"auto")==="auto"&&I&&"auto"!==I?A?.[I]??I:null,n1=R&&n0?eg("chat.currentReasoning",{level:n0}):null,n2=e=>!L||L.includes(e),n4=[{level:"auto",ceiling:null},...uw.filter(n2).map(e=>({level:"auto",ceiling:e})),...ub.filter(e=>"auto"!==e&&n2(e)).map(e=>({level:e,ceiling:null}))],n8=Object.entries(uh).find(([,e])=>e===(C??"default"))?.[0]??"default";(0,s.useEffect)(()=>{let e=e=>{tC.current&&!tC.current.contains(e.target)&&tN.current&&!tN.current.contains(e.target)&&(ej(!1),eT("")),tT.current&&!tT.current.contains(e.target)&&tI.current&&!tI.current.contains(e.target)&&eA(!1),tM.current&&!tM.current.contains(e.target)&&ez(!1),tE.current&&!tE.current.contains(e.target)&&eO(!1),t$.current&&!t$.current.contains(e.target)&&eB(!1),!tR.current||tR.current.contains(e.target)||tS.current?.contains(e.target)||th(!1)};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[]),(0,s.useEffect)(()=>{ey||eB(!1)},[ey]);let n5=(0,r.jsx)("button",{type:"button",className:`composer-icon-button${eq.length||eK.length?" is-active":""}`,onClick:()=>tA.current?.click(),title:eg("chat.attachFile"),"aria-label":eg("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:eq.length||eK.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=eq.length||eK.length?"var(--accent)":"var(--text)"},onMouseLeave:e=>{e.currentTarget.style.background="none",e.currentTarget.style.color=eq.length||eK.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&&rf.length>0?(0,r.jsxs)("div",{ref:tT,style:{position:"relative",flexShrink:+!!ey,minWidth:0},children:[(0,r.jsxs)("button",{className:`${ey?"composer-icon-button":"composer-chip"}${eL?" is-active":""}`,onClick:e=>{let t=e.currentTarget.getBoundingClientRect();e_({top:t.top,bottom:t.bottom,left:t.left,width:t.width}),ej(!1),eT(""),eA(e=>!e)},disabled:i||y,"aria-haspopup":"menu","aria-expanded":eL,onKeyDown:e=>{"Escape"===e.key&&eL&&(e.stopPropagation(),eA(!1))},style:{display:"flex",alignItems:"center",gap:6,maxWidth:"100%",padding:"4px 8px",background:eL?"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=eL?"var(--bg-hover)":"none",e.currentTarget.style.color="var(--text-muted)"},title:eg("chat.mainPreset"),"aria-label":eg("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"})}),ey?null:(0,r.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",minWidth:0},children:eg("chat.mainPreset")})]}),eL&&eP&&(()=>{let e=window.visualViewport?.height??window.innerHeight,{side:t,maxHeight:n}=us(eP.top,eP.bottom,e,ua(e,.6,460),{gap:6,prefer:"above"}),s="above"===t?{bottom:e-eP.top+6}:{top:eP.bottom+6},a=ey?{left:8,right:8,maxWidth:"calc(100vw - 16px)"}:{left:eP.left,width:"max-content",minWidth:eP.width};return(0,r.jsx)("div",{ref:tI,role:"menu","aria-label":eg("chat.mainPreset"),onKeyDown:e=>{"Escape"===e.key&&(eA(!1),tT.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:rf.map(e=>{let t=e.alias===nF;return(0,r.jsxs)("button",{role:"menuitemradio","aria-checked":t,onClick:()=>{eA(!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:rD(e.seed),width:20,height:20,alt:"","aria-hidden":"true",draggable:!1}),(0,r.jsx)("span",{children:rL(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:tE,style:{position:"relative",flexShrink:0,minWidth:0},children:[(0,r.jsxs)("button",{type:"button",className:`${ey?"composer-icon-button":"composer-chip"}${eW?" is-active":""}`,onClick:e=>{let t=e.currentTarget.getBoundingClientRect();eH({top:t.top,bottom:t.bottom,left:t.left,width:t.width}),ej(!1),eT(""),eA(!1),eO(e=>!e)},disabled:i||y,"aria-haspopup":"menu","aria-expanded":eW,onKeyDown:e=>{"Escape"===e.key&&eW&&(e.stopPropagation(),eO(!1))},title:eg("chat.changeReasoning",{level:nX}),"aria-label":eg("chat.changeReasoning",{level:nX}),style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,padding:ey?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"})]}),ey?null:(0,r.jsx)("span",{style:{whiteSpace:"nowrap"},children:nX})]}),eW&&eD&&(()=>{let e=window.visualViewport?.height??window.innerHeight,{side:t,maxHeight:n}=us(eD.top,eD.bottom,e,ua(e,.6,460),{gap:6,prefer:"above"}),s="above"===t?{bottom:e-eD.top+6}:{top:eD.bottom+6},a=ey?{left:8,right:8,maxWidth:"calc(100vw - 16px)"}:{left:eD.left,width:"max-content",minWidth:Math.max(180,eD.width)};return(0,r.jsx)("div",{role:"menu","aria-label":eg("chat.changeReasoningLabel"),onKeyDown:e=>{"Escape"===e.key&&(eO(!1),tE.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?eg("chat.thinkingAutoCapped",{level:a??t}):eg(uk[e]);return(0,r.jsxs)("button",{type:"button",role:"menuitemradio","aria-checked":n,onClick:()=>{eO(!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=z?(ed=_?eg("chat.fastModeBusy"):null===P?eg("chat.fastModeUnknown"):P.active?eg("chat.fastModeActive"):P.enabled?eg("chat.fastModeInactive"):eg("chat.fastModeOff"),eu=_||i||y,eh=P?.enabled===!0,(0,r.jsx)("button",{type:"button",className:`composer-icon-button${P?.active?" is-active":""}`,onClick:z,disabled:eu,"aria-pressed":null===P?void 0:P.enabled,"aria-busy":_||void 0,title:ed,"aria-label":ed,style:{flexShrink:0,opacity:i?.5:1},children:(0,r.jsx)("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:P?.active?"var(--accent)":"none",stroke:eh?"var(--accent)":"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",strokeDasharray:null===P?"3 2":void 0,style:{opacity:eh&&!P?.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:()=>n$("steer"),disabled:!np,title:eQ?eg("chat.attachExtractingWait"):eg("chat.steerTitle"),style:{display:"flex",alignItems:"center",gap:5,padding:"7px 12px",background:np?"var(--warning-soft)":"var(--bg-hover)",border:0,borderRadius:"var(--radius-control)",color:np?"var(--warning)":"var(--text-dim)",cursor:np?"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"})]}),eg("chat.steer")]}),a&&(0,r.jsxs)("button",{className:"composer-stream-action is-followup",onClick:()=>n$("followup"),disabled:!np,title:eQ?eg("chat.attachExtractingWait"):eg("chat.followUpTitle"),style:{display:"flex",alignItems:"center",gap:5,padding:"7px 12px",background:np?"var(--bg-selected)":"var(--bg-hover)",border:0,borderRadius:"var(--radius-control)",color:np?"var(--text)":"var(--text-dim)",cursor:np?"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"})]}),eg("chat.followUp")]})]}),re=void 0!==Z?(0,r.jsx)(dl,{soundEnabled:G??!0,onToggle:Z}):null;return(0,r.jsxs)("div",{className:"chat-composer",style:{flexShrink:0,background:"transparent",padding:"0 16px 8px"},children:[(0,r.jsx)("input",{ref:tA,type:"file",multiple:!0,style:{display:"none"},onChange:e=>{t9(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)(uU,{error:h}),(0,r.jsx)(uB,{warnings:p}),O.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:ex("delivery.title",{count:O.length})}),H&&ev&&(0,r.jsxs)("button",{onClick:H,title:eg("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"})]}),eg("chat.recall")]})]}),(0,r.jsx)(dn,{rows:O,removeLabel:eg("chat.queueRemove"),onRemove:B?(e,t)=>B("steer"===e?"steering":"followUp",t):void 0})]}),W&&(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"})]}),eg("chat.retrying",{attempt:W.attempt,max:W.maxAttempts}),W.errorMessage&&(0,r.jsxs)("span",{style:{opacity:.7,marginLeft:4},children:["— ",W.errorMessage]})]}),nY&&(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"})}),nY]}),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}),eG&&(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:eG}),(0,r.jsx)("button",{type:"button",onClick:()=>eZ(null),"aria-label":eg("i18n.close"),title:eg("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"})]})})]}),(eq.length>0||eK.length>0)&&(0,r.jsxs)("div",{role:"list","aria-label":eg("chat.attachments"),style:{display:"flex",alignItems:"center",gap:6,marginBottom:6,flexWrap:"wrap"},children:[eq.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":eg("chat.removeImage",{index:t+1}),onClick:()=>ne(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}`)),eK.map(e=>(0,r.jsxs)("div",{className:"composer-chip",role:"listitem","aria-busy":"ready"!==e.status||ud(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"}}):sS(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?eg("chat.attachKindAudio"):"file"===e.stored?eg("chat.attachKindFile"):uv[e.mimeType]," \xb7 ",sH(e.sourceSize??e.size),"extracting"===e.status?` \xb7 ${eg("chat.attachExtracting")}`:"","uploading"===e.status?` \xb7 ${eg("chat.attachUploading")}`:"",e.transcription?.state==="planning"?` \xb7 ${eg("chat.transcribeChecking")}`:"",e.transcription?.state==="confirm"?` \xb7 ${eg("chat.attachTranscribePending")}`:"",e.transcription?.state==="running"?` \xb7 ${eg("chat.attachTranscribing")}`:"",e.transcription?.state==="failed"&&(0,r.jsx)("span",{style:{color:"var(--danger)"},children:` \xb7 ${eg("chat.attachTranscribeFailed")}`})]})]}),(0,r.jsx)("button",{type:"button",onClick:()=>nt(e.id),"aria-label":eg("chat.removeAttachment",{name:e.name}),title:eg("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))]}),eX.length>0&&(0,r.jsx)("div",{role:"group","aria-label":eg("chat.transcribeGroup"),"aria-live":"polite",style:{display:"flex",flexDirection:"column",gap:6,marginBottom:6},children:eX.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?eg("chat.transcribePlanSummary",{duration:null===c.durationSeconds?eg("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"?eg("chat.transcribeConfirmTitle",{name:e.name}):o?.state==="running"?eg("chat.transcribeRunning",{name:e.name}):o?.state==="planning"?`${e.name} \xb7 ${eg("chat.transcribeChecking")}`:o?.state==="failed"?eg("chat.transcribeFailedRow",{name:e.name,error:o.error}):eg("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:eg("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 t8(i,!0),children:eg("chat.transcribeStart")}),(0,r.jsx)(l.r,{type:"button",variant:"neutralWeak",size:"small",onClick:()=>t3(i),children:eg("chat.transcribeSkip")})]}),(o?.state==="planning"||o?.state==="running")&&(0,r.jsx)(l.r,{type:"button",variant:"neutralWeak",size:"small",onClick:()=>t3(i),children:eg("chat.transcribeCancel")}),(void 0===o||"skipped"===o.state||"failed"===o.state)&&(0,r.jsx)(l.r,{type:"button",variant:"neutralWeak",size:"small",onClick:()=>void t6(i),children:eg(o?.state==="failed"?"chat.transcribeRetry":"chat.transcribeAction")})]})]},e.id)})}),(0,r.jsxs)("div",{ref:tL,style:{position:"relative",minWidth:0},children:[tu&&D.length>0&&(0,r.jsxs)("div",{ref:tR,style:{position:"absolute",left:0,right:0,...uf(nk.side),zIndex:120,background:"var(--bg-raised)",border:0,borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s3)",overflow:"hidden",maxHeight:nk.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,nk.maxHeight-31),overflowY:"auto",padding:4},children:D.map((e,t)=>{let n=t===tp;return(0,r.jsxs)("button",{ref:e=>{tO.current[t]=e},type:"button",onMouseDown:t=>{t.preventDefault(),nM(e)},onMouseEnter:()=>tm(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}`)})})]}),tn&&(0,r.jsx)("div",{role:"status",style:{fontSize:12,color:"var(--text-dim)",padding:"4px 8px"},children:eg("savedPrompts.saved")}),te&&e9&&(0,r.jsx)(ds,{ref:ts,value:eb,token:e9,cwd:ee,sessionTitle:et,style:uf(nC.side),maxHeight:nC.maxHeight,onReplace:nT,onClose:()=>tt(!1)}),e4&&null!==nl&&(0,r.jsxs)("div",{style:{position:"absolute",left:0,right:0,...uf(nj.side),zIndex:120,background:"var(--bg-raised)",border:0,borderRadius:"var(--radius-surface)",boxShadow:"var(--seed-shadow-s3)",overflow:"hidden",maxHeight:nj.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?eg("chat.loadingCommands"):eg("chat.slashCommands",{label:nu})}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},children:eg("chat.tabEnter")})]}),(0,r.jsx)("div",{style:{maxHeight:Math.max(0,nj.maxHeight-34),overflowY:"auto",padding:10},children:V||0!==no.length?nd.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:eg(uC[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===e5,s=uM(e,tj);return(0,r.jsxs)("button",{ref:e=>{tz.current[t]=e},type:"button",onMouseDown:t=>{t.preventDefault(),nE(e)},onMouseEnter:()=>e6(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:eg("chat.dormant")})]}),uI(e,eg)&&(0,r.jsx)("span",{style:{display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:2,overflow:"hidden",fontSize:11,lineHeight:1.35,color:"var(--text-dim)"},children:uI(e,eg)})]},`${e.source}:${e.name}`)})})]},e.source)):(0,r.jsx)("div",{style:{padding:"2px 2px 4px",fontSize:12,color:"var(--text-dim)"},children:eg("chat.noCommands")})})]}),tl&&null!==ta&&(ep=tx&&(!tf||tf.cwd!==ee),em=1===ny.length?eg("chat.match"):eg("chat.matches",{count:ny.length}),ef=tf?.truncated&&!nv?ta.query?eg("chat.searchingAll"):eg("chat.indexTruncated"):"",(0,r.jsxs)("div",{style:{position:"absolute",left:0,right:0,...uf(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.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:ep?eg("chat.loadingFiles"):eg("chat.files",{label:em,hint:ef})}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},children:eg("chat.tabEnter")})]}),(0,r.jsx)("div",{style:{maxHeight:Math.max(0,nS.maxHeight-34),overflowY:"auto",padding:4},children:ep||0!==ny.length?ny.map((e,t)=>{let n=t===tc,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(),nI(e)},onMouseEnter:()=>td(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)(sw,{size:14}):sS(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:nx&&!nv?eg("chat.searching"):eg("chat.noMatchingFiles")})})]})),(0,r.jsxs)("div",{className:`chat-composer-field${e1?" 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:tS,"aria-controls":te?"saved-prompt-menu":void 0,value:eb,onChange:e=>{tB.current=e.target.value,ew(e.target.value),th(!1),nm(e.target.value,e.target.selectionStart)},onSelect:e=>{let t=e.currentTarget;nm(t.value,t.selectionStart)},onKeyDown:nL,onCompositionStart:()=>{tP.current=!0},onCompositionEnd:e=>{tP.current=!1,t_.current=Date.now();let t=e.currentTarget;nm(t.value,t.selectionStart)},onInput:nA,onPaste:nP,placeholder:i&&(n||a)?eg("chat.steerPlaceholder"):i?eg("chat.agentPlaceholder"):eg("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?ey?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:ni,disabled:!np,"aria-busy":eQ||void 0,"aria-label":ey?eg("chat.send"):void 0,title:eQ?eg("chat.attachExtractingWait"):void 0,style:{flexShrink:0,alignSelf:"flex-end",display:"flex",alignItems:"center",justifyContent:"center",gap:6,minWidth:ey?44:void 0,padding:ey?0:"7px 14px",background:np?"var(--accent-soft)":"var(--bg-raised)",border:"none",borderRadius:"var(--radius-control)",color:np?"var(--accent-hover)":"var(--text-dim)",cursor:np?"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"})]}),ey?null:eg("chat.send")]})]})]}),e1&&(0,r.jsxs)("div",{className:"text-xs px-2 py-1",style:{color:e2?"var(--text-muted)":"var(--accent)",marginTop:4},children:[eg("chat.shell")," \xb7 ",e2?eg("chat.outputLocal"):eg("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:ey?"1 1 0%":"0 0 auto",minWidth:ey?"min-content":0,display:"flex",alignItems:"center",gap:2},children:[(!ey||!i)&&n5,!ey&&n6,!(ey&&i)&&(n_.length>0||nG||h)&&m&&(0,r.jsxs)("div",{ref:tC,style:{position:"relative",flex:ey?"1 1 0%":void 0,width:ey?0:void 0,minWidth:44*!!ey},children:[(0,r.jsxs)("button",{className:`composer-chip${ek?" is-active":""}`,onClick:e=>{let t=e.currentTarget.getBoundingClientRect();eC({top:t.top,bottom:t.bottom,left:t.left,width:t.width}),ej(e=>(e&&eT(""),!e))},disabled:i||y,"aria-busy":y||void 0,style:{display:"flex",alignItems:"center",gap:6,justifyContent:ey?"flex-start":void 0,padding:ey?"8px 10px":"8px 12px",height:32,width:ey?"100%":void 0,maxWidth:ey?"100%":220,overflow:"hidden",background:ek?"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=ek?"var(--bg-hover)":"none",e.currentTarget.style.color="var(--text-muted)"},title:y?"Switching model":n_.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??(n_.length>0?"Select model":"No models")})]}),ek&&eS&&(()=>{let e=window.visualViewport?.height??window.innerHeight,{side:t,maxHeight:n}=us(eS.top,eS.bottom,e,ua(e,.6,460),{gap:6,prefer:"above"}),s="above"===t?{bottom:e-eS.top+6}:{top:eS.bottom+6},a=ey?{left:8,right:8,maxWidth:"calc(100vw - 16px)"}:{left:eS.left,width:"max-content",minWidth:eS.width};return(0,r.jsxs)("div",{ref:tN,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:[nD&&(0,r.jsx)("div",{style:{padding:"6px 8px",flexShrink:0},children:(0,r.jsx)("input",{value:eN,onChange:e=>eT(e.target.value),onKeyDown:e=>{"Escape"===e.key&&(eT(""),ej(!1))},placeholder:eg("chat.filterModels"),"aria-label":eg("chat.filterModels"),autoFocus:!0,autoComplete:"off",spellCheck:!1,style:{width:"100%",minWidth:220*!ey,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:eg("chat.frequentModels")}),nK.map(({option:e,count:t})=>nJ(e,"frequent",t))]}),nB.length>0&&!eN.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":eE,"aria-controls":"model-role-rows",onClick:eR,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:eE?"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:eg("chat.modelRoles")}),(0,r.jsx)("span",{style:{fontFamily:"var(--font-mono)"},children:nB.length}),nq&&(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:nq.tag??nq.role.toUpperCase()}),nq.name]})]}),(0,r.jsx)("div",{id:"model-role-rows",hidden:!eE,children:nB.map(e=>{let t=nq?.role===e.role,n=e.resolved?.name??e.resolved?.modelId??"";return(0,r.jsxs)("button",{onClick:()=>{ej(!1),eT(""),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:eg("chat.allModels")})]}),0===nU.length?(0,r.jsx)("div",{style:{padding:"8px 12px",color:"var(--text-dim)",fontSize:12,whiteSpace:"nowrap"},children:eN.trim()?eg("chat.noMatchingModels"):"No available models"}):nU.map((e,t)=>(0,r.jsxs)("div",{children:[nU.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))]})]})})()]}),ey&&i&&(0,r.jsx)("div",{style:{display:"flex",alignItems:"center",gap:6,minWidth:0},children:n9}),!ey&&n3,!ey&&n7,!ey&&n1&&(0,r.jsx)("span",{style:{flexShrink:0,padding:"0 6px",fontSize:12,color:"var(--text-muted)",whiteSpace:"nowrap"},children:n1}),!ey&&null!==M&&(0,r.jsx)("span",{title:eg(E?"chat.outputSpeedLiveTitle":"chat.outputSpeedTitle"),style:{flexShrink:0,padding:"0 6px",fontSize:12,color:"var(--text-muted)",whiteSpace:"nowrap",fontVariantNumeric:"tabular-nums"},children:eg(E?"chat.outputSpeedLive":"chat.outputSpeed",{rate:M>=10?Math.round(M):M.toFixed(1)})}),(0,r.jsx)(dy,{sessionId:en})]}),(0,r.jsxs)("div",{ref:t$,style:{flex:"0 1 auto",minWidth:0,display:"flex",alignItems:"center",justifyContent:"flex-end",position:"relative",marginLeft:"auto",gap:ey?4:2},children:[ey?(0,r.jsx)("button",{type:"button",className:`composer-icon-button${eU?" is-active":""}`,title:eg("chat.moreControls"),"aria-label":eg("chat.moreControls"),"aria-expanded":eU,onClick:()=>{ej(!1),eT(""),eB(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:eU?void 0:eg("chat.moreControls"),"aria-label":eg("chat.moreControls"),"aria-expanded":eU,onClick:()=>{ej(!1),eT(""),eB(e=>!e)},children:eg("chat.moreControls")}),(0,r.jsxs)("div",{className:"composer-run-options",role:"group","aria-label":eg("chat.moreControls"),style:{display:eU?ey?"grid":"flex":"none",gridTemplateColumns:ey?"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:[ey&&(0,r.jsxs)(r.Fragment,{children:[i&&n5,n6,n3,n7]}),!i&&N&&(0,r.jsxs)("div",{ref:tM,style:{position:"relative"},children:[(0,r.jsxs)("button",{className:`composer-chip${eF?" is-active":""}`,onClick:()=>!i&&ez(e=>!e),disabled:i,title:eg("chat.changeToolPreset")+`: ${n8}`,"aria-label":eg("chat.changeToolPreset"),style:{display:"flex",alignItems:"center",justifyContent:"center",gap:5,padding:"8px 12px",height:32,background:eF?"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=eF?"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})]}),eF&&(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:uu.map(e=>{let t=uh[e],n=(C??"default")===t,s="off"===e?eg("chat.noTools"):"default"===e?eg("chat.builtInTools",{tools:up}):eg("chat.allBuiltInTools",{tools:`${up} + ${um}`});return(0,r.jsxs)("button",{onClick:()=>{ez(!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?eg("chat.stopCompaction"):eg("chat.compactContext"),"aria-label":k?eg("chat.stopCompaction"):eg("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:eg("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:eg("chat.compact")})]})})}),ey&&re,eU&&!ey&&(0,r.jsx)("button",{className:"composer-icon-button is-active",type:"button",title:eg("chat.collapseControls"),"aria-label":eg("chat.collapseControls"),"aria-expanded":!0,onClick:()=>{ez(!1),eO(!1),eB(!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:eg("chat.stopAgent"),"aria-label":ey?eg("chat.stopAgent"):void 0,style:{display:"flex",alignItems:"center",justifyContent:"center",gap:6,minWidth:ey?44:void 0,padding:ey?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"})}),ey?null:eg("chat.stop")]}),(0,r.jsx)(dx,{sessionId:en,onEnsureSession:er,onTranscriptPersisted:es}),!ey&&re]})]})]})]})});function uV({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=eA(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:eW(t).map((e,t)=>(0,r.jsx)("span",{style:e.style,children:e.text},t))})})}function uK({phases:e,flow:t,busy:n}){let{t:a}=(0,F.s)(),{st:i}=sp(),[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}=t_(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)(oC,{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)(sv,{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 uJ(e=document){return"visible"!==e.visibilityState||!e.hasFocus()}function uG(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 uZ(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 uY extends Error{constructor(e,t,n,r){super(e),this.status=t,this.code=n,this.accepted=r,this.name="AgentCommandError"}}async function uQ(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 uY(r.error??`HTTP ${n.status}`,n.status,r.code,r.accepted);return r.data}let uX="ompweb-update-client-id",u0="ompweb-update-resume-intent-v2",u1="ompweb-update-return-v1",u2="cuelo-restart-return-v1",u4="ompweb-update-failure-return-v1",u8="ompweb:update-wake";function u5(e){return null===e?2e4:"running"===e?null:"failed"===e?3e4:8e3}function u6(){let e=sessionStorage.getItem(uX);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(uX,t),t}function u3(){sessionStorage.removeItem(u0)}function u7(){let e=sessionStorage.getItem(u1);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 u9(e){let t=u7();if(!t||t.requestId!==e)return t;let n={...t,dismissed:!0};try{sessionStorage.setItem(u1,JSON.stringify(n))}catch{}return n}async function he(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:u6(),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 ht(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=u7();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(u1,JSON.stringify(n))}catch{}}({requestId:e.requestId,stageHash:e.stageHash}),u3();let r=n?.wake;e.sessionId&&(r?.wake===!0||r?.reason==="already-claimed"||r?.reason==="user-already-active")&&window.dispatchEvent(new CustomEvent(u8,{detail:{sessionId:e.sessionId}}))}async function hn(e){let t=function(e){let t=sessionStorage.getItem(u4);if(!t)return null;sessionStorage.removeItem(u4);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?(u3(),t.wake&&e.sessionId&&window.dispatchEvent(new CustomEvent(u8,{detail:{sessionId:e.sessionId}})),"failed"):(await ht(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 hs(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 ha(e){return{steering:e?.steering??[],followUp:e?.followUp??[]}}function hi(e){if(e&&"boolean"==typeof e.fastModeEnabled)return{enabled:e.fastModeEnabled,active:!0===e.fastModeActive}}function hl(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 ho(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 hc(e){return"aborted"===e.stopReason?"aborted":"error"===e.stopReason||e.errorMessage?"failed":e.stopReason?"completed":"unknown"}function hd(e,t){for(let n=e.length-1;n>=0;n--){let r=t[n]??null;if(!ti(r??void 0))return{message:e[n],entryId:r}}return null}let hu=new Set(["ArrowUp","ArrowDown","PageUp","PageDown","Home","End"," ","Space","Spacebar"]);class hh 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 hp(){return"u">typeof crypto&&"function"==typeof crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2)}`}function hm(e){return new Promise(t=>setTimeout(t,e))}function hf(e){let t=e.findIndex(e=>!e.exiting);return -1===t?e:e.map((e,n)=>n===t?{...e,exiting:!0}:e)}function hg(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:hf(e.visible),pending:[...e.pending,t.notice]};return{...e,visible:[...e.visible,t.notice]};case"mark_oldest_exiting":return{...e,visible:hf(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=hf(n)),{visible:n,pending:r}}(e.visible.filter(e=>e.id!==t.id),e.pending);default:return e}}function hx(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 hv(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(hx).filter(Boolean)}):JSON.stringify({text:"",images:[]})}function hy(e){return"user"===e.role?`user:${hv(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 hb(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 hw(e){return e?.map(({data:e,mimeType:t})=>({data:e,mimeType:t}))}function hk(e){nM(e),e.clear()}function hj(e,t,n){for(let r of n??[]){let n=nI(t,r);n&&e.add(n)}}function hS(){let e=document.activeElement;return e instanceof HTMLElement&&(e.isContentEditable||"INPUT"===e.tagName||"SELECT"===e.tagName||"TEXTAREA"===e.tagName)}let hC=!1,hN={width:0,height:0},hT=new Set,hI=null;function hM(){let e=window.visualViewport,t=hS();hN.width!==window.innerWidth?hN={width:window.innerWidth,height:window.innerHeight}:t||(hN.height=Math.max(hN.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:hN.height});if(n!==hC)for(let e of(hC=n,hT))e()}function hE(e){if(hT.add(e),!hI){let e=null,t=()=>{null!==e&&window.cancelAnimationFrame(e),e=window.requestAnimationFrame(()=>{e=null,hM()})},n=window.visualViewport;n?.addEventListener("resize",t),window.addEventListener("resize",t),window.addEventListener("focusin",t),window.addEventListener("focusout",t),hM(),hI=()=>{n?.removeEventListener("resize",t),window.removeEventListener("resize",t),window.removeEventListener("focusin",t),window.removeEventListener("focusout",t),null!==e&&window.cancelAnimationFrame(e)}}return()=>{hT.delete(e),0===hT.size&&hI&&(hI(),hI=null)}}function h$(){return(0,s.useSyncExternalStore)(hE,()=>hC,()=>!1)}let hR={count:50,end:null};function hL(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 hA(e,t,n){let{startIndex:r,endIndex:s}=hL(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 hP({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:n6[n]}),t&&(0,r.jsx)("p",{className:e?"cue-bubble":"cue-bubble cue-bubble--solo",children:t}),e&&(0,r.jsx)(cw(),{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 h_(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=(sD(t)?.message??t).trim();return n.length>0?n:null}function hF(e){return`omp-cues:${e}`}function hz(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(hF(e),JSON.stringify(n.slice(-200)))}catch{}}let hW=[];function hO(e){return`omp-web:interrupted-dismissed:${e}`}let hD=(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=ts(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=td(s.action);if(!0===tc[e]){let t={kind:"skill",action:e,name:td(s.name)};n(JSON.stringify(t),t)}continue}let a=td(s.memory),i=s.skill,l=i?{action:td(i.action),name:td(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:tn,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&&ti(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)(s9,{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:eZ(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)(hP,{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)(s9,{message:b,cwd:i,onOpenFile:l},`saved-lessons-${c}`):null,k=x?(0,r.jsx)(cI,{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=tM(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=eK(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)(cn,{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 hH({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,onOpenMaker:C,selectedMaker:N,onProcessLogChange:T,onOpenFile:I,transcriptReplacement:M,onComposerFocusChange:E,onSessionBusyChange:$,onWaitingChange:R,onAttentionChange:L,soundEnabled:A=!0,onSoundToggle:P,playCueSound:_=async()=>({sticker:null,text:null}),preloadCueSound:z,unlockAudio:W,jumpRequest:O=null,onJumpHandled:D,turnInspectorTarget:H=null,onShowTurnInspector:B,turnInspectorFolded:q=!1}){var V,K;let J,G,Z,{t:Y}=(0,F.s)(),Q=h$(),X=U(),et=Q&&X,en=(0,s.useRef)(_);en.current=_;let er=(0,s.useRef)(null),es=(0,s.useRef)(z);es.current=z;let[ea,el]=(0,s.useState)([]),eo=(0,s.useRef)(ea);eo.current=ea;let ec=(0,s.useRef)(0),ed=(0,s.useRef)([]),eu=(0,s.useRef)([]),eh=(0,s.useRef)(null),ep=(0,s.useRef)(0),em=(0,s.useRef)(-1),ef=(0,s.useRef)(-1),eg=(0,s.useCallback)(()=>{let e=eh.current?.current;return e?{sessionId:e,turn:ep.current}:null},[]),ex=(0,s.useCallback)(e=>eh.current?.current===e.sessionId&&ep.current===e.turn,[]),ev=(0,s.useCallback)((e,t,n,r)=>{if(!e.sticker&&!e.text)return;ec.current=Math.max(ec.current+1,Date.now());let s={id:ec.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};el(e=>{let t=[...e,a];return null!==a.anchorEntryId&&hz(n.sessionId,t),t})},[]),ey=(0,s.useCallback)((e,t,n,r)=>{let s=()=>ex(n)&&("working"!==t||ef.current!==n.turn);s()&&en.current(e,t,s).then(e=>{null!==t&&null!==r&&s()&&ev(e,t,n,r)}).catch(()=>{})},[ex,ev]),eb=(0,s.useCallback)(async(e,t,n,r)=>{let s=(await sc(e,t,n,r))?.alias??null;return s&&es.current?.(s),s},[]),ew=(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=ro(e[n]),a=0;for(let t=r;t<=n;t++)ro(e[t])===s&&(a+=1);return{kind:"pending",liveIndex:n,intent:{baseEntryId:r>0?t[r-1]:null,identity:s,occurrence:a}}}(ed.current,eu.current);eb(t.sessionId,n,r,s).then(n=>{ey(n,e,t,a)})},[ey,eb]),[ek,ej]=(0,s.useState)(0),eS=(0,s.useRef)([]),eC=(0,s.useCallback)(e=>{if(ep.current+=1,null!==re(e.outcome)){let t=e.sessionId;eS.current.push({completion:e,trigger:t?{sessionId:t,turn:ep.current}:null}),ej(e=>e+1)}c?.(e)},[c]);(0,s.useEffect)(()=>{for(let{completion:e,trigger:t}of eS.current.splice(0)){let n=re(e.outcome),r="neutral"===n?null:n;t?ew(r,t,e.provider,e.credentialId,e.model):en.current(null,r).catch(()=>{})}},[ek,ew]);let eN=(0,s.useCallback)(e=>{m?.current?.replaceMessage(e)},[m]),{loading:eT,error:eI,messages:eM,entryIds:eE,streamState:e$,agentRunning:eR,bashRunning:eL,pendingBash:eP,modelNames:e_,modelList:eF,modelError:ez,modelScopeWarnings:eW,modelThinkingLevels:eO,modelThinkingLevelMaps:eD,modelRoles:eH,toolPreset:eU,thinkingLevel:eB,effectiveThinkingLevel:eq,thinkingCeiling:eV,fastMode:eJ,fastModeBusy:eX,handleFastModeToggle:e0,retryInfo:e4,contextUsage:e8,forkingEntryId:e6,isCompacting:e3,compaction:tn,compactError:tc,compactResult:td,displayModel:th,modelSwitching:tp,sessionStats:tm,runStateKnown:tf,compactedWork:tg,slashCommands:tx,slashCommandsLoading:tv,deliveryRows:ty,subagents:tb,todoPhases:tw,notices:tk,extensionDialog:tj,extensionResponse:tS,extensionCustomUi:tC,extensionStatuses:tN,extensionWidgets:tT,respondToExtensionUi:tI,sendExtensionCustomInput:tM,isAutoModelSelection:tE,agentPhase:t$,isNew:tR,autoFollowPaused:tL,resumeAutoFollow:tP,pauseAutoFollow:t_,goalStatus:tF,sessionIdRef:tz,messagesEndRef:tO,scrollContainerRef:tD,handleSend:tH,handleAbort:tU,handleFork:tB,handleNavigate:tq,handleModelChange:tV,handleRoleModelChange:tK,handleMainPresetChange:tJ,newSessionAccount:tG,handleCompact:tZ,handleSteer:tY,handleFollowUp:tQ,handlePromptWithStreamingBehavior:tX,handleAbortCompaction:t0,handleRecallQueue:t1,handleRemoveQueuedMessage:t2,handleBuiltinSlashCommand:t4,handleToolPresetChange:t8,handleThinkingLevelChange:t5,loadSlashCommands:t6,ensureNewSession:t3,refreshLiveTranscript:t7}=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=null===t&&null!==r,f=a&&a.sessionId===t?.id?a:null,[g,x]=(0,s.useState)(f),[v,y]=(0,s.useState)(!m&&!f),[b,w]=(0,s.useState)(null),[k,j]=(0,s.useState)(f?.leafId??null),[S,C]=(0,s.useState)(f?.context.messages??[]),[N,T]=(0,s.useState)(f?.context.entryIds??[]),[I,M]=(0,s.useState)(f?.context.compactedWork??null),[E,$]=(0,s.useReducer)(hs,{isStreaming:!1,streamingMessage:null}),[R,L]=(0,s.useState)(!1),[A,P]=(0,s.useState)(!1),[_,F]=(0,s.useState)(null),[z,W]=(0,s.useState)({}),[O,D]=(0,s.useState)([]),[H,U]=(0,s.useState)(null),[B,q]=(0,s.useState)([]),[V,K]=(0,s.useState)({}),[J,G]=(0,s.useState)({}),[Z,Y]=(0,s.useState)([]),[Q,X]=(0,s.useState)(null),[ee,et]=(0,s.useState)(null),[en,er]=(0,s.useState)(null),[es,ea]=(0,s.useState)("default"),[el,eo]=(0,s.useState)(()=>{let e=f?.context.thinkingLevel;return e&&"off"!==e?e:"auto"}),[ec,ed]=(0,s.useState)(),[eu,eh]=(0,s.useState)(null),[ep,em]=(0,s.useState)(null),[ef,eg]=(0,s.useState)(!1),ex=(0,s.useRef)(0),ev=(0,s.useRef)(0),ey=(0,s.useRef)(""),[eb,ew]=(0,s.useState)(null),[ek,ej]=(0,s.useState)(f?.contextUsage??null),[eS,eC]=(0,s.useState)(null),[eN,eT]=(0,s.useState)(null),[eI,eM]=(0,s.useState)(null),[eE,e$]=(0,s.useState)(null),[eR,eL]=(0,s.useState)(!1),[eP,e_]=(0,s.useState)(!1),[eF,ez]=(0,s.useState)(null),[eW,eO]=(0,s.useState)(null),[eD,eH]=(0,s.useState)(null),eU=(0,s.useRef)(null),[eB,eq]=(0,s.useState)(!1),[eV,eK]=(0,s.useState)(null),[eJ,eG]=(0,s.useState)([]),[eZ,eY]=(0,s.useState)(!1),[eQ,eX]=(0,s.useReducer)(hg,{visible:[],pending:[]}),[e0,e1]=(0,s.useState)(null),[e2,e4]=(0,s.useState)(null),e8=(0,s.useRef)(null),e5=(0,s.useRef)(null),[e6,e3]=(0,s.useState)(null),e7=(0,s.useRef)(null),[e9,te]=(0,s.useState)(null),[tn,tr]=(0,s.useState)([]),[ts,to]=(0,s.useState)([]),[tc,td]=(0,s.useState)({steering:[],followUp:[]}),[tu,th]=(0,s.useState)([]),[tp,tm]=(0,s.useReducer)(lO,[]),tf=(0,s.useRef)(0);(0,s.useEffect)(()=>{tm({type:"queue",steering:tc.steering,followUp:tc.followUp})},[tc]),(0,s.useEffect)(()=>{R||tm({type:"idle"})},[R]),(0,s.useEffect)(()=>{tm({type:"reset"})},[t?.id]);let tg=(0,s.useMemo)(()=>(function(e,t){let n=new Map;for(let t of e){if(!t.inQueue)continue;let e=`${t.kind}\u0000${lz(t)}`;n.set(e,(n.get(e)??0)+1)}let r=[],s=(e,t)=>{t.forEach((t,s)=>{let a=`${e}\u0000${lF(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})(tp,tc),[tp,tc]),[tx,tv]=(0,s.useState)(null),ty=(0,s.useRef)(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)(0),tC=(0,s.useRef)(!1),tN=(0,s.useRef)(t?.id??null),tT=(0,s.useRef)(f?.leafId??null),tI=(0,s.useRef)(S),tM=(0,s.useRef)(N);tI.current=S,tM.current=N;let tE=(0,s.useRef)({sessionId:t?.id??null,outputs:[],seq:0}),t$=(0,s.useRef)(!1),tR=(0,s.useRef)(new Set);(0,s.useEffect)(()=>()=>hk(tR.current),[]);let tL=(0,s.useRef)(!1),tA=(0,s.useRef)(!1),tP=(0,s.useRef)(-1),t_=(0,s.useRef)("unknown"),tF=(0,s.useRef)(null),tz=(0,s.useRef)(null),tW=(0,s.useRef)(0),tO=(0,s.useRef)(!1),tD=(0,s.useRef)(0),tH=(0,s.useRef)(null),tU=(0,s.useRef)(null),tB=(0,s.useRef)(null),tq=(0,s.useRef)(!1),tV=(0,s.useRef)(!0),[tK,tJ]=(0,s.useState)(!1),[tG,tZ]=(0,s.useState)(null),tY=(0,s.useRef)(void 0),tQ=(0,s.useRef)(0),tX=(0,s.useRef)(null),t0=(0,s.useRef)(0),t1=(0,s.useRef)(()=>{}),t2=(0,s.useRef)(null),t4=(0,s.useRef)(null),t8=(0,s.useRef)(null),t5=(0,s.useRef)(null),t6=(0,s.useRef)(!1),t3=(0,s.useRef)(null),t7=(0,s.useRef)(null),t9=(0,s.useRef)(null),ne=(0,s.useRef)(null),nt=(0,s.useRef)(null),nn=(0,s.useRef)(0),nr=(0,s.useRef)(null),ns=(0,s.useRef)(null),na=(0,s.useRef)(!1);na.current=e.transitioning??!1;let ni=(0,s.useRef)(Date.now()),nl=(0,s.useRef)(0),no=(0,s.useRef)(0),nc=(0,s.useRef)(null),nd=(0,s.useRef)(!1),nu=(0,s.useRef)(Promise.resolve()),nh=e.setToolPreset??ea,np=eI??g?.context.model??eE??null,nm=m?Q??en:np,nf=(0,s.useMemo)(()=>{if(e0)return{...e0,totalActiveMs:g?.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 S){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===S.length)?null:{sessionFile:g?.filePath||void 0,sessionId:tN.current??t?.id??"",sessionName:t?.name,userMessages:r,assistantMessages:s,toolCalls:i,toolResults:a,totalMessages:S.length,tokens:e,cost:n,totalActiveMs:g?.totalActiveMs,...ek?{contextUsage:ek}:{}}},[S,e0,ek,g?.filePath,g?.totalActiveMs,t?.id,t?.name]),ng=(0,s.useRef)(0),nx=(0,s.useCallback)((e,t)=>{e&&tN.current===e&&Array.isArray(t)&&(ng.current+=1,tv(n=>n?.sid===e&&ho(n.phases,t)?n:{sid:e,phases:t}))},[]),nv=(0,s.useCallback)((e,t,n)=>{tN.current===e&&ng.current===n&&Array.isArray(t)&&tv(n=>n?.sid===e&&ho(n.phases,t)?n:{sid:e,phases:t})},[]),ny=(0,s.useCallback)(e=>{let t="function"==typeof e?e(tI.current):e;tI.current=t,C(t)},[]),nb=(0,s.useCallback)(e=>{tM.current=e,T(e)},[]),nw=(0,s.useCallback)(async(e,t=!1,n=!1,r)=>{let s=!1;try{t&&y(!0);let a=r??null;if(!a){let n=new URLSearchParams({deferThinking:"1",deferMedia:"1"}),r=await fetch(`/api/sessions/${encodeURIComponent(e)}?${n}`);if(404===r.status)return t&&(x(null),j(null),ny([]),M(null),w(null)),null;if(!r.ok)throw Error(`HTTP ${r.status}`);a=await r.json()}if(tN.current!==e)return null;x(a),j(a.leafId),tT.current=a.leafId??null;let i=tl(a.context.messages,a.context.entryIds??[],tE.current.sessionId===e?tE.current.outputs:[]);ny(i.messages),nb(i.entryIds),M(a.context.compactedWork??null),ej(a.contextUsage??null),eM(e=>nd.current?e:null),w(null);let l=!n&&nt.current===e;if(l||(eo(a.context.configuredThinkingLevel??a.context.thinkingLevel??"off"),ed(a.context.thinkingLevel)),eh(a.context.thinkingCeiling??null),s=!0,t&&y(!1),!n){if(l)try{let t=nn.current,n=await fetch(`/api/sessions/${encodeURIComponent(e)}/state`);if(n.ok&&tN.current===e){let r=await n.json();tN.current===e&&nn.current===t&&(r.state?.thinkingLevel!==void 0?(eo(r.state.configuredThinkingLevel??r.state.thinkingLevel),ed(r.state.thinkingLevel)):r.running||(nt.current=null,eo(a.context.configuredThinkingLevel??a.context.thinkingLevel??"off"),ed(a.context.thinkingLevel)))}}catch(e){console.error("Failed to refresh live thinking level:",e)}return null}try{let t=ng.current,n=await fetch(`/api/sessions/${encodeURIComponent(e)}/state`);if(!n.ok)throw Error(`HTTP ${n.status}`);let r=await n.json();if(tN.current!==e)return null;let s=r.state;return s?(void 0!==s.contextUsage&&ej(s.contextUsage??null),void 0!==s.systemPrompt&&eC(s.systemPrompt??null),void 0!==s.thinkingLevel&&(nt.current=e,eo(s.configuredThinkingLevel??s.thinkingLevel),ed(s.thinkingLevel)),void 0!==s.thinkingCeiling&&eh(s.thinkingCeiling??null),void 0!==s.extensionStatuses&&tr(s.extensionStatuses??[]),void 0!==s.extensionWidgets&&to(s.extensionWidgets??[]),void 0!==s.queuedMessages&&td(ha(s.queuedMessages)),void 0!==s.subagents&&th(e=>hr(e,s.subagents??[])),nv(e,s.todoPhases,t)):r.running||td({steering:[],followUp:[]}),r}catch(e){return console.error("Failed to load agent state:",e),null}}catch(e){return w(String(e)),null}finally{t&&!s&&y(!1)}},[nv,nb,ny]),nk=(0,s.useCallback)(e=>{let t=nu.current.then(async()=>{tN.current===e&&await nw(e)});return nu.current=t.catch(()=>{}),t},[nw]),nj=(0,s.useCallback)(async(e,t)=>{let n=++ev.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(ev.current!==n||tN.current!==e)return;tT.current=t;let l=tl(i.context.messages,i.context.entryIds??[],tE.current.sessionId===e?tE.current.outputs:[]);ny(l.messages),nb(l.entryIds),M(i.context.compactedWork??null),ej(i.contextUsage??null)}catch(e){console.error("Failed to load context:",e)}},[nb,ny]),nC=(0,s.useCallback)(async e=>{try{let t=await uQ(e,{type:"get_tools"});if(t){let{getPresetFromTools:e}=await Promise.resolve().then(n.bind(n,14755));nh(e(t))}}catch(e){console.error("Failed to load tools:",e)}},[nh]),nT=(0,s.useCallback)((e=0,t="(no messages)")=>{let n=tN.current;if(!m||!r||!n||t6.current)return;let s=t3.current??r;t6.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})},[m,r,o]),nE=(0,s.useCallback)(async()=>{if(t8.current)return t8.current;let t=tN.current;if(t&&ns.current!==t||!t&&(!m||!r))return t;let n=(async()=>{let n=t;if(!n){let t=t7.current,s=ne.current,a=t9.current;t&&e$(t);let i={cwd:r,type:"ensure_session",toolNames:(0,ul.xG)(es),...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=t5.current,c=o?.body===l?o.createRequestId:hp();t5.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();t5.current=null,n=u.sessionId,tN.current=n,t3.current=u.cwd??r??null,t3.current&&ei(t3.current,u.worktree),null!==nr.current&&(ns.current=n),u.model&&t7.current===t&&(e$(u.model),t||er(u.model)),u.thinkingLevel&&ne.current===s&&(eo(u.configuredThinkingLevel??u.thinkingLevel),ed(u.thinkingLevel))}for(;ns.current===n;){let e=nr.current;await uQ(n,{type:"set_thinking_ceiling",ceiling:e}),nr.current===e&&ns.current===n&&(ns.current=null)}return n})();t8.current=n;try{return await n}finally{t8.current=null}},[m,r,es,e.newSessionAutoWorktree]),n$=(0,s.useCallback)(async()=>{let e=tN.current??await nE();if(!e)return eG([]),[];eY(!0);try{let t=await uQ(e,{type:"get_commands"}),n=t?.commands??[];return eG(n),n}catch(e){return console.error("Failed to load slash commands:",e),eG([]),[]}finally{eY(!1)}},[nE]),nR=(0,s.useCallback)(()=>{tS.current+=1,tC.current=!1,tj.current&&(clearTimeout(tj.current),tj.current=null)},[]),nL=(0,s.useCallback)(()=>{ty.current?.close(),ty.current=null,tb.current=null,tw.current=null},[]),nA=(0,s.useCallback)(()=>{tk.current?.close(),tk.current=null},[]),nP=(0,s.useCallback)(e=>{nA();let t=new EventSource(`/api/agent/${encodeURIComponent(e)}/events?entries=1`);tk.current=t,t.onmessage=t=>{try{let n=JSON.parse(t.data);"session_snapshot"===n.type?tH.current?.(n):"agent_start"===n.type&&tU.current?.(e)}catch{}}},[nA]),n_=(0,s.useCallback)(e=>{nL();let t=new EventSource(`/api/agent/${encodeURIComponent(e)}/events`);ty.current=t,tb.current=e;let n=new Promise(n=>{let r=!1,s=e=>{r||(r=!0,clearTimeout(a),tw.current?.source===t&&(tw.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"),ty.current!==t)return;"update_maintenance"===n.type&&window.dispatchEvent(new CustomEvent("ompweb:update-maintenance",{detail:n})),tH.current?.(n)}catch{}},t.onerror=()=>{if(t.readyState===EventSource.CLOSED&&(s("closed"),ty.current===t&&(t$.current||tC.current))){ty.current=null,tb.current=null,tw.current=null;let t=tS.current;setTimeout(()=>{t===tS.current&&!ty.current&&(t$.current||tC.current)&&n_(e)},1e3)}}});return tw.current={source:t,promise:n,pending:!0},n},[nL]),nF=(0,s.useCallback)(async e=>{let t=ty.current;if(t&&tb.current===e){if(t.readyState===EventSource.OPEN)return;let e=tw.current;if(e?.source===t&&e.pending&&(await e.promise,ty.current===t&&t.readyState===EventSource.OPEN))return}let n=await n_(e);if("connected"!==n.status&&n.source.readyState!==EventSource.OPEN)throw ty.current===n.source&&(ty.current=null),tb.current===e&&(tb.current=null),tw.current?.source===n.source&&(tw.current=null),n.source.close(),new hh(n.status)},[n_]),nz=(0,s.useCallback)(e=>{e8.current=e.id,e4(e),l?.(e)},[l]),nW=(0,s.useCallback)(e=>{if(e5.current?.id===e&&(e5.current=null),e8.current===e){let e=e5.current;e5.current=null,e?nz(e):(e8.current=null,e4(null))}e7.current?.id===e&&(e7.current=null,e3(null))},[nz]),nO=(0,s.useCallback)(async(e,t)=>{if(e8.current!==e.id)return;let n=e7.current;if(n?.id===e.id&&"sending"===n.status)return;let r=tN.current,s=e=>{e7.current=e,e3(e)};if(!r)return void s({id:e.id,status:"failed",error:"no session"});s({id:e.id,status:"sending"});try{await uQ(r,{type:"extension_ui_response",id:e.id,...t})}catch(t){if(tN.current!==r||e8.current!==e.id)return;s({id:e.id,status:"failed",error:t instanceof Error?t.message:String(t)});return}tN.current===r&&nW(e.id)},[nW]),nD=(0,s.useCallback)(async(e,t)=>{let n=tN.current;if(n)try{await uQ(n,{type:"extension_ui_input",id:e.id,data:t})}catch(e){console.error("Failed to send extension custom UI input:",e)}},[]),nH=(0,s.useCallback)(e=>{let t=e.message.trim();t&&eX({type:"add",notice:{id:e.id??hp(),message:t,type:e.type??"info"}})},[]),nU=(0,s.useCallback)(e=>{let t={role:"custom",customType:tt,content:eA(e).trim(),display:!0,timestamp:Date.now()},n=tE.current,r=tN.current;n.sessionId!==r&&(n.sessionId=r,n.outputs=[]);let s=tM.current.slice(0,tI.current.length),a=null;for(let e=s.length-1;e>=0;e--)if(!ti(s[e])){a=s[e];break}n.seq+=1,n.outputs.push({entryId:`${ta}${n.seq}`,baseEntryId:a,message:t});let i=tl(tI.current,tM.current,n.outputs);ny(i.messages),nb(i.entryIds)},[ny,nb]),nB=(0,s.useCallback)((t,n)=>{if("custom"!==t.method&&"closed"in t&&t.closed)return void nW(t.id);switch("custom"===t.method&&uG(t)&&l?.(t),t.method){case"select":case"confirm":case"input":case"editor":case"ask":case"form":case"plan_review":{let e=e8.current;if(e===t.id)break;if(null!==e&&n){e5.current=t;break}e5.current=null,null!==e&&nW(e),nz(t);break}case"notify":nH({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":to(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":te(e=>t.closed?e?.id===t.id?null:e:t)}},[nH,nW,l,e.chatInputRef,nz]),nq=(0,s.useCallback)(()=>{let e=t$.current;return t$.current=!1,L(!1),eK(null),hk(tR.current),ew(null),$({type:"end"}),e},[]),nV=(0,s.useCallback)(()=>{t_.current="unknown",tF.current=null;let e=hd(tI.current,tM.current);tz.current=e?{entryId:e.entryId,key:hy(e.message)}:null,tW.current+=1},[]),nK=(0,s.useCallback)(()=>{let e=t_.current,t=tF.current;if("unknown"===e){let n=hd(tI.current,tM.current),r=n?.message,s=tz.current;null!==n&&(null===s||(null!==n.entryId&&null!==s.entryId?n.entryId!==s.entryId:hy(n.message)!==s.key))&&r?.role==="assistant"&&r.stopReason&&(e=hc(r),t??={provider:r.provider,...r.model?{model:r.model}:{},...void 0!==r.credentialId?{credentialId:r.credentialId}:{}})}return{outcome:e,sessionId:tN.current,...t?{provider:t.provider,...t.model?{model:t.model}:{},...void 0!==t.credentialId?{credentialId:t.credentialId}:{}}:{}}},[]),nJ=(0,s.useCallback)(e=>{let t=nK();if("unknown"!==t.outcome||!e)return void i?.(t);let n=tW.current;e.catch(()=>void 0).then(()=>{let e=tN.current===t.sessionId&&tW.current===n;i?.(e?nK():t)})},[i,nK]),nG=(0,s.useCallback)((e,t)=>tP.current!==e&&(tP.current=e,nJ(t),!0),[nJ]),nZ=(0,s.useCallback)(e=>{nR(),tC.current=!0;let t=tS.current,n=async()=>{if(t===tS.current&&tN.current===e&&tC.current)try{let r=ng.current,s=e8.current,a=e5.current,i=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(!i.ok)throw Error(`HTTP ${i.status}`);let l=await i.json();if(t!==tS.current||tN.current!==e||!tC.current)return;let o=l.state;if(th(e=>hr(e,o?.subagents??[])),nv(e,o?.todoPhases,r),l.running&&o&&(o.isStreaming||o.isPromptRunning||o.isHandoffRunning)){tC.current=!1,tj.current=null,tL.current=!!o?.isStreaming,tA.current=!!o?.isPromptRunning,t$.current=!0,L(!0),eK(o?.isStreaming?{kind:"waiting_model"}:{kind:"running_command"});return}if(l.running&&o?.isCompacting){e_(!0),eH(hl(o)),tj.current=setTimeout(()=>void n(),600);return}if(l.running&&(o?.subagents?.length??0)>0){tj.current=setTimeout(()=>void n(),1e3);return}let c=!1===l.running?[]:o?.pendingExtensionUiIds;if(c&&s===e8.current&&a===e5.current&&(a&&!c.includes(a.id)&&(e5.current=null),null===s||c.includes(s)||nW(s)),null!==e8.current){tj.current=setTimeout(()=>void n(),3e4);return}tC.current=!1,tj.current=null,nL()}catch{if(t!==tS.current||tN.current!==e||!tC.current)return;tj.current=setTimeout(()=>void n(),600)}};tj.current=setTimeout(()=>void n(),3e4)},[nv,nR,nW,nL]),nY=(0,s.useCallback)(async(e=tN.current,t=nl.current)=>{if(nl.current===t)try{e&&await nw(e)}finally{if(nl.current!==t)return;let n=tA.current,r=tL.current;tA.current=!1,tL.current=!1,nc.current=null;let s=nq();n?nG(t):r&&s&&nJ(),e&&nZ(e)}},[nw,nJ,nG,nZ,nq]),nQ=(0,s.useCallback)(async(e,t)=>{await hm(800);let n=Date.now();for(;t$.current&&Date.now()-n<2e4;){if(void 0!==t&&nl.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 nY(e,t)}}catch{}await hm(600)}},[nY]),nX=(0,s.useCallback)(async e=>{let t=tD.current+1;for(tD.current=t;tO.current&&tD.current===t&&tN.current===e;){await hm(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 nw(e),tD.current!==t||tN.current!==e)return;tO.current=!1,P(!1),F(null);return}catch{}}},[nw]),n0=(0,s.useCallback)(async e=>{if(!t$.current)return;let t=nl.current;try{let n=ng.current,r=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(!r.ok)return;let s=await r.json();if(nl.current!==t)return;let a=s.state;if(e_(a?.isCompacting??!1),eH(hl(a)),td(ha(a?.queuedMessages)),a?.contextUsage!==void 0&&ej(a.contextUsage??null),th(e=>hr(e,a?.subagents??[])),nv(e,a?.todoPhases,n),s.running&&a&&(a.isStreaming||a.isPromptRunning||a.isCompacting||a.isHandoffRunning)||!t$.current)return;a&&(void 0!==a.systemPrompt&&eC(a.systemPrompt??null),void 0!==a.extensionStatuses&&tr(a.extensionStatuses??[]),void 0!==a.extensionWidgets&&to(a.extensionWidgets??[])),await nY(e,t)}catch{}},[nv,nY]),n1=(0,s.useCallback)(async e=>{let t=await nw(e,!1,!0),n=t?.state;return!!t?.running&&!!n&&tN.current===e&&!t$.current&&!!(n.isStreaming||n.isPromptRunning||n.isHandoffRunning)&&(tL.current=!!n.isStreaming,tA.current=!!n.isPromptRunning,t$.current=!0,L(!0),eK(n.isStreaming?{kind:"waiting_model"}:{kind:"running_command"}),$({type:"start"}),hj(tR.current,e,n.pendingToolCalls),n_(e),!n.isStreaming&&n.isPromptRunning&&nQ(e),!0)},[n_,nw,nQ]),n2=(0,s.useCallback)(async(e,t=nl.current)=>{let n=no.current+1;no.current=n;try{let r=await fetch(`/api/agent/${encodeURIComponent(e)}`);if(!r.ok)return;let s=await r.json();if(n!==no.current||tN.current!==e||nl.current!==t)return;s.state?.contextUsage!==void 0&&ej(s.state.contextUsage??null)}catch{}},[]);(0,s.useEffect)(()=>{if(!eP){eU.current=null,eH(null);return}eH(e=>e??{startedAt:Date.now(),reason:eU.current})},[eP]),(0,s.useEffect)(()=>{if(!R&&!eP)return;let e=()=>{let e=tN.current;e&&n2(e)};e();let t=setInterval(e,1e3);return()=>clearInterval(t)},[R,eP,n2]),(0,s.useEffect)(()=>{if(!R)return;let e=()=>{let e=tN.current;e&&n0(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)}},[R,n0]),(0,s.useEffect)(()=>{if(R)return;let e=()=>{let e=tN.current;e&&!t$.current&&n1(e)},t=()=>{"visible"===document.visibilityState&&e()},n=e=>{let t=tN.current,n=e.detail?.sessionId;t&&n===t&&!t$.current&&n1(t).then(e=>{e||tN.current!==t||t$.current||nw(t)})};return document.addEventListener("visibilitychange",t),window.addEventListener("online",e),window.addEventListener(u8,n),()=>{document.removeEventListener("visibilitychange",t),window.removeEventListener("online",e),window.removeEventListener(u8,n)}},[R,n1,nw]),tU.current=e=>{if(tN.current!==e||t$.current||ty.current||tB.current)return;let t=n1(e).then(async t=>{t||tN.current!==e||t$.current||await nw(e)}).catch(()=>{}).finally(()=>{tB.current===t&&(tB.current=null)});tB.current=t},(0,s.useEffect)(()=>{t$.current=R},[R]),tH.current=(0,s.useCallback)(e=>{var t;switch(e.type){case"connected":{let t=e.pendingExtensionUiIds,n=e8.current;if(Array.isArray(t)){let e=e5.current;e&&!t.includes(e.id)&&(e5.current=null),null===n||t.includes(n)||nW(n)}break}case"extension_ui_closed":"string"==typeof e.id&&nW(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=hy(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=hy(e),n=i.get(t)??0;n>0&&i.set(t,n-1)}let o=r.slice(l).filter(e=>{let t=hy(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,tN.current,tT.current,tI.current,tM.current);if(!t)break;tT.current=t.entryId;let n=tl(t.messages,t.entryIds,tE.current.sessionId===tN.current?tE.current.outputs:[]);ny(n.messages),nb(n.entryIds),M(t.compactedWork);break}case"agent_start":{let e=!t$.current;nR(),e&&nV(),tL.current=!0,t$.current=!0,L(!0),eK({kind:"waiting_model"}),$({type:"start"});break}case"agent_end":if(!t$.current)break;if(eK(null),hk(tR.current),ew(null),$({type:"end"}),tN.current){nw(tN.current);let e=ng.current;fetch(`/api/agent/${encodeURIComponent(tN.current)}`).then(e=>e.json()).then(t=>{t.state?.contextUsage!==void 0&&ej(t.state.contextUsage??null),t.state?.systemPrompt!==void 0&&eC(t.state.systemPrompt??null),t.state?.extensionStatuses!==void 0&&tr(t.state.extensionStatuses??[]),t.state?.extensionWidgets!==void 0&&to(t.state.extensionWidgets??[]),t.state?.subagents!==void 0&&th(e=>hr(e,t.state?.subagents??[])),tN.current&&nv(tN.current,t.state?.todoPhases,e),t.state?.goal!==void 0&&tZ(t.state.goal??null),td(ha(t.state?.queuedMessages))}).catch(()=>{})}break;case"goal_status":tZ(e.status??null);break;case"agent_settled":{let e=tL.current;if(tL.current=!1,!e||tA.current)break;let t=tN.current,n=nq();e_(!1);let r=t?nw(t):void 0;t&&nZ(t),n&&nJ(r);break}case"prompt_done":{let e=nl.current,t=tA.current;tA.current=!1,nc.current=null;let n=tP.current!==e;if(!t&&!n)break;let r=tN.current;nG(e,r?nw(r):void 0),!tL.current&&(nq(),r&&nZ(r))}break;case"prompt_error":t_.current="failed",nH({type:"error",message:e.errorMessage??"Command failed"});break;case"extension_error":t_.current="failed",nH({type:"error",message:e.error??"Extension command failed"});break;case"message_start":case"message_update":{if(!t$.current)break;let t=e.message;if(t?.role!=="assistant")break;t&&$({type:"update",message:l7(t)}),eK(null);break}case"message_end":{if(!t$.current)break;let t=e.message;if(t?.role==="assistant"&&(tF.current={provider:t.provider,...t.model?{model:t.model}:{},...void 0!==t.credentialId?{credentialId:t.credentialId}:{}},t_.current=hc(t)),t&&"user"===t.role){let e=l7(t),n=hv(e),r=nc.current;nc.current=null,ny(t=>{let s=t[t.length-1];return r&&s?.role==="user"&&hv(s)===r?r===n?t:[...t.slice(0,-1),e]:[...t,e]}),r||tm({type:"user-message",kind:lH(e),text:lD(e),images:"user"!==e.role||"string"==typeof e.content?0:e.content.filter(e=>"image"===e.type).length})}else t&&ny(e=>[...e,l7(t)]);let n=tN.current;n&&n2(n),$({type:"reset"}),eK(e=>t?.role==="toolResult"&&e?.kind==="running_tools"?e:{kind:"waiting_model"});break}case"thinking_level_changed":{let t=tN.current,n=e.thinkingLevel;t&&void 0!==n&&(nt.current=t,nn.current+=1,eo(e.configured??n),ed(n));break}case"todo_changed":nx(tN.current,e.phases);break;case"tool_execution_start":{let t=e.toolCallId,n=e.toolName,r=e.args,s=nI(tN.current,t);s&&tR.current.add(s),eK(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}});break}case"tool_execution_update":{let n=nI(tN.current,"string"==typeof e.toolCallId?e.toolCallId:null);n&&tR.current.has(n)&&"string"==typeof e.text&&(t=e.text,nS.get(n)!==t&&(nS.set(n,t),nN()));break}case"tool_execution_end":{let t=e.toolCallId,n=nI(tN.current,t);n&&tR.current.delete(n)&&nM([n]),eK(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";th(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()};th(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};th(e=>hr(e,[r]));break}case"queue_update":td({steering:[...e.steering??[]],followUp:[...e.followUp??[]]});break;case"auto_retry_start":ew({attempt:e.attempt,maxAttempts:e.maxAttempts,errorMessage:e.errorMessage});break;case"auto_retry_end":ew(null);break;case"auto_compaction_start":case"compaction_start":if("string"==typeof e.reason){eU.current=e.reason;let t=e.reason;eH(e=>e?{...e,reason:t}:e)}e_(!0),ez(null),eO(null);break;case"auto_compaction_end":case"compaction_end":if(e_(!1),e.errorMessage)ez(e.errorMessage),eO(null);else if(!e.aborted){eO(hb(e.result,e.reason??"auto"));let t=tN.current;t&&(nw(t),n2(t))}break;case"extension_ui_request":nB(e,!0===e.replayed)}},[nH,nx,nv,nR,nW,nB,nw,nJ,nG,n2,nV,nZ,nq,nb,ny]);let n4=(0,s.useCallback)(async(n,s,a)=>{let i=n.trim();if(!i&&!s?.length&&!a?.length)return"returned";if(t$.current||tO.current||nd.current)return"unknown";let l=sO(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 tY.current?.(t,e),"accepted"):"unknown"}nV();let c=nl.current+1;nR(),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()};ny(e=>[...e,u]),nc.current=hv(u),nl.current=c,t$.current=!0,L(!0),eK(o?{kind:"running_command"}:{kind:"waiting_model"}),$({type:"start"}),t1.current(!0);let h=s?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),p=null,f=!1,g="unknown";try{if(m&&r){let e=tN.current??await t8.current,t=await nE();t&&(p=t,Q&&(e$(Q),e&&await uQ(t,{type:"set_model",provider:Q.provider,modelId:Q.modelId})),await nF(t),f=!0,await uQ(t,{type:"prompt",message:l,...h?.length?{images:h}:{}}),nT(1,n),g="accepted")}else t&&(p=t.id,await nF(t.id),f=!0,await uQ(t.id,{type:"prompt",message:l,...h?.length?{images:h}:{}}),g="accepted");return o&&p&&nQ(p,c),g}catch(l){console.error("Failed to send message:",l);let r=l instanceof uY&&"update_draining"===l.code&&!1===l.accepted;if(!(!f||l instanceof uY&&"prompt_rejected"===l.code&&!1===l.accepted||r)&&p)return nQ(p,c),"unknown";tA.current=!1,t$.current=!1,nL();let i=nc.current;return i&&ny(e=>{let t=e[e.length-1];return t?.role==="user"&&hv(t)===i?e.slice(0,-1):e}),nH({type:"error",message:l instanceof Error?l.message:String(l)}),e.chatInputRef?.current?.restoreSubmission?.(n,hw(s),a,t?.id??p??void 0),nc.current=null,L(!1),eK(null),$({type:"end"}),"returned"}},[m,r,Q,t,nE,nF,nT,nQ,nH,nR,nL,e.chatInputRef,nV,ny]);tY.current=(0,s.useCallback)(async(n,r)=>{if(t$.current||tO.current)return;let s=`${r?"!!":"!"}${n}`;tO.current=!0,t1.current(!0),F({command:n,excludeFromContext:r}),P(!0);try{let e=tN.current??t?.id??await nE();if(!e)throw Error("Unable to create a session for the shell command");await uQ(e,{type:"bash",command:n,excludeFromContext:r}),await nw(e),nT(1,s)}catch(t){console.error("Failed to execute shell command:",t),nH({type:"error",message:t instanceof Error?t.message:String(t)}),e.chatInputRef?.current?.insertIfEmpty(s)}finally{tO.current=!1,F(null),P(!1)}},[nH,nE,nw,e.chatInputRef,nT,t]);let n8=(0,s.useCallback)(async()=>{let e=tN.current;if(e){if(tO.current){try{await uQ(e,{type:"abort_bash"})}catch(e){console.error("Failed to abort bash:",e)}return}try{await uQ(e,{type:"abort"}),t_.current="aborted"}catch(e){console.error("Failed to abort:",e)}}},[]),n5=(0,s.useCallback)(async e=>{if(tO.current)return{forked:!1,error:"Cannot fork while a shell command is running"};let t=tN.current;if(!t)return{forked:!1,error:"No active session to fork"};eT(e??null);try{let{cancelled:n,newSessionId:r}=await uQ(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{eT(null)}},[c]),n6=(0,s.useCallback)(async e=>{if(tO.current)return;let t=tN.current;t&&(uQ(t,{type:"navigate_tree",targetId:e}).catch(()=>{}),j(e),await nj(t,e))},[nj]),n3=(0,s.useCallback)(async e=>{if(tO.current)return;j(e);let t=tN.current;t&&(await nj(t,e),e&&uQ(t,{type:"navigate_tree",targetId:e}).catch(()=>{}))},[nj]),n7=(0,s.useCallback)(async(e,t)=>{if(m){let n={provider:e,modelId:t},r=t7.current?.provider===e;t7.current=n,r||(t9.current=null,et(null)),X(n),e$(n);let s=tN.current??await t8.current;if(!s)return;try{await uQ(s,{type:"set_model",provider:e,modelId:t})}catch(e){console.error("Failed to set model:",e)}return}let n=tN.current;if(n&&!nd.current){nd.current=!0,eM({provider:e,modelId:t}),eL(!0);try{await uQ(n,{type:"set_model",provider:e,modelId:t}),nd.current=!1,await nw(n)}catch(e){console.error("Failed to set model:",e),nd.current=!1,eM(eI),nH({type:"error",message:`Failed to switch model: ${e instanceof Error?e.message:String(e)}`}),await nw(n)}finally{nd.current=!1,eL(!1)}}},[nH,eI,m,nw,X]),n9=(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(m){if(nd.current)return!1;nd.current=!0,eL(!0);let e=t7.current,a=t9.current,i=ne.current;try{t7.current=t,t9.current=n??null,ne.current="auto";let e=tN.current??await t8.current;return e&&await uQ(e,r),X(t),et(n??null),e$(t),eo("auto"),ed(void 0),e&&await nw(e),!0}catch(n){console.error("Failed to apply Main preset:",n),t7.current=e,t9.current=a,ne.current=i,nH({type:"error",message:s(n)});let t=tN.current;return t&&await nw(t),!1}finally{nd.current=!1,eL(!1)}}let a=tN.current;if(!a||nd.current)return!1;nd.current=!0,eM(t),eL(!0);try{return await uQ(a,r),await nw(a),!0}catch(e){return console.error("Failed to apply Main preset:",e),eM(eI),nH({type:"error",message:s(e)}),await nw(a),!1}finally{nd.current=!1,eL(!1)}},[nH,eI,ec,m,nw,X,el]),re=(0,s.useCallback)(async e=>{let t=Z.find(t=>t.role===e),n=t?.resolved;if(!n)return;if(m){let e={provider:n.provider,modelId:n.modelId},t=n.thinkingLevel;ne.current=t??null,eo(t??"auto"),ed(void 0),t7.current=e,t9.current=null,et(null),X(e),e$(e)}let r=tN.current??(m?await t8.current:null);if(r)try{await uQ(r,{type:"set_role_model",role:e}),m||eM({provider:n.provider,modelId:n.modelId})}catch(e){console.error("Failed to set role model:",e)}},[m,Z,X]),rt=(0,s.useCallback)(async()=>{let e=tN.current;if(e&&!eP){eU.current="manual",e_(!0),ez(null),eO(null);try{let t=await uQ(e,{type:"compact"});eO(hb(t,"manual")),await nw(e,!0)}catch(e){ez(e instanceof Error?e.message:String(e)),eO(null)}finally{e_(!1)}}},[eP,nw]),rn=(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();W(i.models),U(i.modelError??null),q(i.modelScopeWarnings??[]),K(i.thinkingLevels??{}),G(i.thinkingLevelMaps??{}),Y(i.roles??[]);let l=i.modelList??[];if(D(l),m&&!tN.current){let e=(i.defaultModel?l.find(e=>e.id===i.defaultModel?.modelId&&e.provider===i.defaultModel?.provider):void 0)??l[0];er(e?{provider:e.provider,modelId:e.id}:null);let t=e&&i.thinkingLevelPins?.[`${e.provider}/${e.id}`];null===ne.current&&eo(t??"auto")}},[m,r,t?.cwd]),rr=(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 nE(),i=e=>(e.handled&&(e.error?nH({type:"error",message:e.error}):"openSessionStats"!==e.action&&nH({type:"success",message:e.message??"Command completed"})),e);try{switch(n){case"compact":{if(!a||eP)return i({handled:!0,error:"No active session to compact"});eU.current="manual",e_(!0),ez(null),eO(null);let e=await uQ(a,{type:"compact",...s?{customInstructions:s}:{}});return eO(hb(e,"manual")),await nw(a,!0)&&nT(),i({handled:!0,message:"Compacted context"})}case"reload":if(!a)return i({handled:!0,error:"No active session to reload"});return await uQ(a,{type:"reload"}),await Promise.all([nw(a,!1,!0),nC(a),n$(),rn()]),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 uQ(a,{type:"set_session_name",name:s}),await nw(a)&&nT(),i({handled:!0,message:`Session renamed to ${s}`});case"session":{if(!a)return i({handled:!0,error:"No active session"});let e=await uQ(a,{type:"get_session_stats"});return e&&e1(e),p?.(),i({handled:!0,action:"openSessionStats"})}case"copy":{if(!a)return i({handled:!0,error:"No active session"});let e=await uQ(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 n5();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 uQ(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(nU(e.message),e.prompt)return{handled:!0,prompt:e.prompt};return{handled:!0}}if(e?.prompt)return e.message&&nH({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(t$.current||tO.current)return i({handled:!0,error:"Cannot hand off while the session is busy"});t$.current=!0,L(!0),eK({kind:"running_command"});try{await nF(a);let e=await uQ(a,{type:"handoff",...s?{customInstructions:s}:{}});if(!e||e.cancelled)return i({handled:!0,error:"Handoff cancelled"});return await nw(a,!0)&&nT(),i({handled:!0,message:"컨텍스트를 현재 세션에 압축했습니다"})}finally{t$.current=!1,L(!1),eK(null),tN.current===a&&nZ(a)}default:{if(!a)return i({handled:!0,error:"No active session"});let t=await uQ(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&&nU(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)}},[nH,nU,nF,nE,n5,eP,rn,nw,n$,nC,nT,p,nZ]),rs=(0,s.useCallback)(async(t,n,r)=>{let s=tN.current;if(!s)return nH({type:"error",message:"The session is not ready yet, so the message was returned to the composer."}),e.chatInputRef?.current?.restoreSubmission?.(t,hw(n),r),"returned";let a=sO(t,r??[]),i=n?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),l=++tf.current;tm({type:"submit",id:l,kind:"steer",text:a,images:i?.length??0});try{return await uQ(s,{type:"steer",message:a,...i?.length?{images:i}:{}}),tm({type:"ack",id:l}),"accepted"}catch(a){return tm({type:"fail",id:l}),console.error("Failed to steer:",a),nH({type:"error",message:a instanceof Error?a.message:String(a)}),e.chatInputRef?.current?.restoreSubmission?.(t,hw(n),r,s),"returned"}},[nH,e.chatInputRef]),ra=(0,s.useCallback)(async(t,n,r,s)=>{let a=tN.current;if(!a)return nH({type:"error",message:"The session is not ready yet, so the message was returned to the composer."}),e.chatInputRef?.current?.restoreSubmission?.(t,hw(r),s),"returned";let i=sO(t,s??[]),l=r?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),o=++tf.current;tm({type:"submit",id:o,kind:n,text:i,images:l?.length??0});try{return await uQ(a,{type:"prompt",message:i,streamingBehavior:n,...l?.length?{images:l}:{}}),tm({type:"ack",id:o}),"accepted"}catch(n){return tm({type:"fail",id:o}),console.error("Failed to queue prompt:",n),nH({type:"error",message:n instanceof Error?n.message:String(n)}),e.chatInputRef?.current?.restoreSubmission?.(t,hw(r),s,a),"returned"}},[nH,e.chatInputRef]),ri=(0,s.useCallback)(async(t,n,r)=>{let s=tN.current;if(!s)return nH({type:"error",message:"The session is not ready yet, so the message was returned to the composer."}),e.chatInputRef?.current?.restoreSubmission?.(t,hw(n),r),"returned";let a=sO(t,r??[]),i=n?.map(e=>({type:"image",data:e.data,mimeType:e.mimeType})),l=++tf.current;tm({type:"submit",id:l,kind:"followUp",text:a,images:i?.length??0});try{return await uQ(s,{type:"follow_up",message:a,...i?.length?{images:i}:{}}),tm({type:"ack",id:l}),"accepted"}catch(a){return tm({type:"fail",id:l}),console.error("Failed to follow up:",a),nH({type:"error",message:a instanceof Error?a.message:String(a)}),e.chatInputRef?.current?.restoreSubmission?.(t,hw(n),r,s),"returned"}},[nH,e.chatInputRef]),rl=(0,s.useCallback)(async()=>{let e=tN.current;if(e)try{await uQ(e,{type:"abort_compaction"})}catch(e){console.error("Failed to abort compaction:",e)}},[]),ro=(0,s.useCallback)(async()=>{let t=tN.current;if(t)try{var n;let r=await uQ(t,{type:"clear_queue"});tm({type:"withdraw"}),td({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),nH({type:"error",message:"Failed to recall queued messages"})}},[e.chatInputRef,nH]),rc=(0,s.useCallback)(async(e,t)=>{let n=tN.current;if(n)try{let r=await uQ(n,{type:"remove_queued_message",message:t,queue:e});if(!r?.removed)return;tm({type:"withdraw",kind:"steering"===e?"steer":"followUp",text:t}),td(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),nH({type:"error",message:"Failed to remove queued message"})}},[nH]),rd=(0,s.useCallback)(async(e,t=null)=>{let n="auto"===e?t:null,r=n!==eu;eo(e),eh(n),m&&(!tN.current||ns.current===tN.current)&&(ne.current=e,nr.current=n),ed(void 0);let s=tN.current??await t8.current;if(s)try{ns.current===s?await nE():r&&await uQ(s,{type:"set_thinking_ceiling",ceiling:n}),await uQ(s,{type:"set_thinking_level",level:e}),await nw(s)}catch(e){console.error("Failed to set thinking level:",e),nH({type:"error",message:"Failed to set thinking level"}),await nw(s)}},[m,nw,nH,eu,nE]);ey.current=nm?`${nm.provider}/${nm.modelId}`:"";let ru=e=>e?`${e}|${ey.current}`:null,rh=t?.id??tN.current,rp=ru(rh),rm=ep&&ep.key===rp?ep.value:null;(0,s.useEffect)(()=>{let e=++ex.current;rp&&rh&&!R&&!eR&&fetch(`/api/agent/${encodeURIComponent(rh)}`).then(e=>e.json()).then(t=>{ex.current===e&&ru(tN.current)===rp&&em({key:rp,value:(t.running?hi(t.state):void 0)??null})}).catch(()=>{})},[rp,R,eR]);let rf=(0,s.useCallback)(async()=>{let e=tN.current??await nE(),t=ru(tN.current);if(!e||!t)return;let n=++ex.current,r=()=>ex.current===n&&ru(tN.current)===t,s=e=>{r()&&em({key:t,value:e})};eg(!0);try{let n=ep?.key===t?ep.value?.enabled:void 0;if(void 0===n){let t=hi(await uQ(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 uQ(e,{type:"set_fast_mode",enabled:!n});s({enabled:a?.enabled===!0,active:a?.active===!0})}catch(t){if(!r())return;nH({type:"error",message:t instanceof Error?t.message:String(t)});try{s(hi(await uQ(e,{type:"get_state"}))??null)}catch{s(null)}}finally{eg(!1)}},[nE,ep,nH]),rg=(0,s.useCallback)(async e=>{let t=(0,ul.xG)(e);nh(e);let n=tN.current??await t8.current;if(n)try{await uQ(n,{type:"set_tools",toolNames:t})}catch(e){console.error("Failed to set tools:",e)}},[nh]),rx=(0,s.useCallback)(e=>{tV.current=e,tJ(t=>!e===t?t:!e)},[]);t1.current=e=>{tX.current=null,rx(e)};let rv=(0,s.useCallback)((e="smooth")=>{t0.current=Date.now()+700,t2.current?.scrollIntoView({behavior:e})},[]),ry=(0,s.useCallback)(()=>{tQ.current=0,tX.current=null,rx(!0),rv("smooth")},[rv,rx]),rb=(0,s.useCallback)(()=>{tQ.current=0,tX.current=null,rx(!1)},[rx]),rw=(0,s.useCallback)(()=>{if(!tX.current)return;tX.current=null;let e=t4.current;e&&rx(e.scrollHeight-e.scrollTop-e.clientHeight<=72)},[rx]),rk=(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(tX.current)return void rw();rb();let e=t4.current;return void(tX.current=e?{top:e.scrollTop,moved:!1,released:!1}:null)}rw(),e instanceof KeyboardEvent&&(!hu.has(e.key)||e.target instanceof Element&&e.target.closest("input, textarea, [contenteditable='true']"))||(tQ.current=Date.now()+1200)},[rw,rb]),rj=(0,s.useCallback)(()=>{let e=t4.current;if(!e)return;let t=tX.current;if(null!==t){let n=t.top;t.moved||=e.scrollTop!==n,t.top=e.scrollTop;return}if(!t$.current&&!tO.current)return;let n=e.scrollHeight-e.scrollTop-e.clientHeight,r=Date.now()<=tQ.current;if(!(!r&&Date.now()<t0.current)){if(n<=72)return void rx(!0);r&&rx(!1)}},[rx]);return(0,s.useEffect)(()=>(tN.current=t?.id??null,tE.current.sessionId!==tN.current&&(tE.current={sessionId:tN.current,outputs:[],seq:0}),t&&nw(t.id,!f,!0,f).then(e=>{if(tN.current!==t.id)return;nP(t.id),e?.running&&(nC(t.id),(e.state?.isStreaming||e.state?.isPromptRunning||e.state?.isHandoffRunning)&&(tL.current=!!e.state.isStreaming,tA.current=!!e.state.isPromptRunning,t$.current=!0,L(!0),eK(e.state.isStreaming?{kind:"waiting_model"}:{kind:"running_command"}),$({type:"start"}),hj(tR.current,t.id,e.state.pendingToolCalls),n_(t.id),!e.state.isStreaming&&e.state.isPromptRunning&&nQ(t.id)),e.state?.isBashRunning&&(tO.current=!0,P(!0),nX(t.id)),(e.state?.subagents?.length??0)>0&&n_(t.id));let n=e?.state;n&&(void 0!==n.isCompacting&&e_(n.isCompacting),eH(hl(n)),void 0!==n.contextUsage&&ej(n.contextUsage??null),void 0!==n.systemPrompt&&eC(n.systemPrompt??null),void 0!==n.thinkingLevel&&(nt.current=t.id,eo(n.configuredThinkingLevel??n.thinkingLevel),ed(n.thinkingLevel)),void 0!==n.thinkingCeiling&&eh(n.thinkingCeiling??null),void 0!==n.extensionStatuses&&tr(n.extensionStatuses??[]),void 0!==n.extensionWidgets&&to(n.extensionWidgets??[]),void 0!==n.queuedMessages&&td(ha(n.queuedMessages)),void 0!==n.subagents&&th(e=>hr(e,n.subagents??[])),void 0!==n.goal&&tZ(n.goal??null)),e&&eq(!0)}),()=>{tD.current+=1,nR(),e5.current=null,null!==e8.current&&nW(e8.current),nL(),nA()}),[t?.id]),(0,s.useEffect)(()=>{h?.(eS)},[eS,h]),(0,s.useEffect)(()=>{u&&u(g?.tree??[],k,n3)},[g?.tree,k,n3,u]),(0,s.useEffect)(()=>{let e=e=>{let t=tX.current;t&&(1!==e.button||t.released||t.moved||!(e.target instanceof Node&&t4.current?.contains(e.target))?rw():t.released=!0)};return window.addEventListener("pointerup",e,!0),window.addEventListener("keydown",rk),()=>{window.removeEventListener("pointerup",e,!0),window.removeEventListener("keydown",rk)}},[rw,rk]),(0,s.useEffect)(()=>{let e=t4.current;if(!e)return;let t=()=>{tX.current?.moved&&rw()};return e.addEventListener("pointerdown",rk,{passive:!0}),e.addEventListener("wheel",rk,{passive:!0}),e.addEventListener("touchstart",rk,{passive:!0}),e.addEventListener("scroll",rj,{passive:!0}),e.addEventListener("scrollend",t,{passive:!0}),()=>{e.removeEventListener("pointerdown",rk),e.removeEventListener("wheel",rk),e.removeEventListener("touchstart",rk),e.removeEventListener("scroll",rj),e.removeEventListener("scrollend",t)}},[S.length,v,rw,rj,rk]),(0,s.useEffect)(()=>{if(na.current||!R&&!A||!tV.current)return;let e=t4.current;if(!e)return;let t=requestAnimationFrame(()=>{tV.current&&(t0.current=Date.now()+700,e.scrollTo({top:e.scrollHeight,behavior:"instant"}))});return()=>cancelAnimationFrame(t)},[R,A,S.length,E.streamingMessage,eV,_,e.transitioning]),(0,s.useLayoutEffect)(()=>{if(0!==S.length){if(!tq.current){tq.current=!0,rv("instant");return}if(!na.current&&tV.current){let e=Date.now()-ni.current<1500;rv(t$.current||tO.current||e?"instant":"smooth")}}},[S.length,R,A,rv,e.transitioning]),(0,s.useEffect)(()=>{let e=new AbortController;return rn(e.signal).catch(e=>{if(e instanceof DOMException&&"AbortError"===e.name)return}),()=>e.abort()},[rn,d]),(0,s.useEffect)(()=>{if(!eW)return;let e=setTimeout(()=>eO(null),6e3);return()=>clearTimeout(e)},[eW]),(0,s.useEffect)(()=>{if(0===eQ.visible.length)return;let e=eQ.visible.find(e=>e.exiting);if(e){let t=setTimeout(()=>{eX({type:"remove",id:e.id})},180);return()=>clearTimeout(t)}if(!eQ.visible[0])return;let t=setTimeout(()=>{eX({type:"mark_oldest_exiting"})},5e3);return()=>clearTimeout(t)},[eQ.visible]),(0,s.useEffect)(()=>{e1(null)},[S.length,ek?.tokens,ek?.percent,ek?.contextWindow]),{data:g,loading:v,error:b,activeLeafId:k,messages:S,entryIds:N,streamState:E,agentRunning:R,modelNames:z,modelList:O,modelError:H,modelScopeWarnings:B,modelThinkingLevels:V,modelThinkingLevelMaps:J,modelRoles:Z,newSessionModel:Q,toolPreset:es,thinkingLevel:el,effectiveThinkingLevel:ec,thinkingCeiling:eu,retryInfo:eb,contextUsage:ek,systemPrompt:eS,forkingEntryId:eN,isCompacting:eP,compaction:eD,compactError:eF,compactResult:eW,currentModel:np,displayModel:nm,modelSwitching:eR,sessionStats:nf,runStateKnown:eB,slashCommands:eJ,slashCommandsLoading:eZ,queuedMessages:tc,deliveryRows:tg,subagents:tu,todoPhases:tx&&tx.sid===tN.current?tx.phases:null,compactedWork:I,notices:eQ.visible,extensionDialog:e2,extensionResponse:e6,extensionCustomUi:e9,extensionStatuses:tn,extensionWidgets:ts,respondToExtensionUi:nO,sendExtensionCustomInput:nD,isAutoModelSelection:m&&null===Q,agentPhase:eV,isNew:m,autoFollowPaused:tK,resumeAutoFollow:ry,pauseAutoFollow:rb,goalStatus:tG,sessionIdRef:tN,eventSourceRef:ty,messagesEndRef:t2,scrollContainerRef:t4,handleSend:n4,handleAbort:n8,handleFork:n5,handleNavigate:n6,handleModelChange:n7,handleRoleModelChange:re,handleMainPresetChange:n9,newSessionAccount:ee,handleCompact:rt,handleSteer:rs,handleFollowUp:ri,handlePromptWithStreamingBehavior:ra,handleAbortCompaction:rl,handleRecallQueue:ro,handleRemoveQueuedMessage:rc,handleBuiltinSlashCommand:rr,handleToolPresetChange:rg,handleThinkingLevelChange:rd,fastMode:rm,fastModeBusy:ef,handleFastModeToggle:rf,loadTools:nC,loadSlashCommands:n$,ensureNewSession:nE,refreshLiveTranscript:nk,setActiveLeafId:j,setData:x,setMessages:C,dispatch:$,setAgentRunning:L,setForkingEntryId:eT,bashRunning:A,pendingBash:_,handleAgentEventRef:tH}}({session:e,newSessionCwd:t,initialData:l,transitioning:o,onAgentEnd:eC,onAttentionNeeded:d,onSessionCreated:u,onSessionForked:h,newSessionAutoWorktree:i,modelsRefreshKey:p,chatInputRef:m,onBranchDataChange:f,onSystemPromptChange:g,onSessionStatsPanelOpen:y}),t9=(0,s.useMemo)(()=>(function(e){let t=null,n=new Map;for(let r=0;r<e.length;r++){let s=e[r],a=te(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=e9(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(e7)?{kind:"translated",text:n.slice(e7.length),original:t}:n.startsWith("[번역 생략]")?{kind:"skipped",text:n,original:t}:{kind:"failed",text:n,original:t}}(s,e9(l.content??[]))}}return t??e})(eM),[eM]),ne=sd(e?.id,th?.provider,void 0,th?.modelId),nt=ne?.alias;(0,s.useEffect)(()=>{nt&&es.current?.(nt)},[nt]);let nn=(0,s.useMemo)(()=>{if(!th)return null;let e=tR?tG:rf.find(e=>e.alias===ne?.alias)?.oauthPosition;return rf.find(t=>t.provider===th.provider&&(void 0===t.oauthPosition?null===ne||ne.seed===t.seed:t.oauthPosition===e))?.alias??null},[th,tR,tG,ne]),nr=eR||eL,ns=e?.id;ed.current=t9,eu.current=eE,eh.current=tz;let na=(0,s.useRef)(!0);na.current=!tL;let ni=(0,s.useRef)(!1);(0,s.useEffect)(()=>{eR&&!ni.current&&(ep.current+=1),ni.current=eR},[eR]),(0,s.useEffect)(()=>()=>{ep.current+=1},[]),(0,s.useEffect)(()=>{el(e=>[...function(e){if(!e)return[];try{let t=JSON.parse(window.localStorage.getItem(hF(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[]}}(ns),...e.filter(e=>null===e.anchorEntryId&&e.sessionId===ns)])},[ns]),(0,s.useEffect)(()=>{let e=tz.current;e&&eo.current.some(t=>null===t.anchorEntryId&&t.sessionId===e)&&el(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(ro(t[i])===e.identity&&(a+=1)===e.occurrence)return{kind:"entry",entryId:n[i]};return null}(s.intent,t9,eE);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?(hz(e,r),r):t})},[t9,eE,tz]);let nl=(0,s.useRef)(null);(0,s.useEffect)(()=>{let e=tz.current,t=nl.current;if(nl.current=e?{sessionId:e,entryIds:eE}: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===rd&&r.push(t[a])}return r}(t.entryIds,eE,t9),r=eg();if(0===n.length||!r)return;let s=so(e,"web6",void 0)?.alias??null;for(let e of n)eo.current.some(t=>t.anchorEntryId===e)||ey(s,"done",r,{kind:"entry",entryId:e})},[eE,t9,tz,eg,ey]);let no=eR&&t$?.kind==="running_tools"&&t$.tools.length>0&&t$.tools.every(e=>"wait"===e.name),nc=eT||o,{hideThinkingBlock:nd}=(V=t??e?.cwd??null,J=n1(),(0,s.useEffect)(()=>{n0(V).catch(()=>{})},[V]),J),nu=(0,s.useMemo)(()=>({hideThinking:nd}),[nd]);(0,s.useEffect)(()=>{var e;if(!tj||er.current===tj.id)return;er.current=tj.id;let t=eg();if(!t)return;ef.current=t.turn;let n=e$.streamingMessage?.role==="assistant"?e$.streamingMessage:null,r=rc(ed.current,n,th?.provider,th?.modelId);ew("select"===(e=tj.method)||"ask"===e||"form"===e?"choice":"approval",t,r.provider,r.credentialId,r.model)},[tj,e$.streamingMessage,th?.provider,th?.modelId,eg,ew]),(0,s.useEffect)(()=>(x=nr?tU:null,()=>void(x=null)),[nr,tU]),(0,s.useEffect)(()=>{$?.(nr)},[$,nr]),(0,s.useEffect)(()=>()=>$?.(!1),[$]),(0,s.useEffect)(()=>{R?.(no)},[no,R]),(0,s.useEffect)(()=>()=>R?.(!1),[R]),(0,s.useEffect)(()=>{L?.(null!==tj)},[L,tj]),(0,s.useEffect)(()=>()=>L?.(!1),[L]);let{main:nh,process:np}=(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=e5(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(tr(t)){r.push(void 0!==s.anchorIdx||a<0?s:{...s,anchorIdx:a});continue}if("assistant"!==t.role){"toolResult"!==t.role&&null===te(t)&&0>ts(e,s.idx)&&l(a,[{idx:s.idx}],0);continue}let i=eY(t,n);if(eG(t,n)&&eZ(e,s.idx)){let e=i.flatMap(e=>e.blocks);l(a,[{idx:s.idx}],eQ(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}],eQ(e.blocks)),o.collect(s.idx,e.blocks)}!c&&eG(t,n)&&d(s.idx,[])}return u(),{main:r,process:s}})(t9,function(e,t={}){let n=-1;for(let t=e.length-1;t>=0;t--)if(to(e[t])){n=t;break}let r=[];for(let s=0;s<e.length;){if(!to(e[s])){r.push({kind:"message",idx:s}),s+=1;continue}let a=s,i=a+1;for(;i<e.length&&!to(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=e5(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!==te(n)||ts(e,o)>=0)continue;if(tr(n)){u(),s.push({kind:"message",idx:o,anchorIdx:t});continue}"toolResult"!==n.role&&a.push({idx:o});continue}let c=eY(n,r);if(eG(n,r)&&eZ(e,o)){let e=c.flatMap(e=>e.blocks);for(let t of(a.push({idx:o}),i+=eQ(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+=eQ(e.blocks),d.collect(o,e.blocks),e.blocks))l.push(t)}0===p&&eG(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}(t9,{sessionBusy:nr,isStreaming:e$.isStreaming,hideThinking:nu.hideThinking}),nu),[t9,nr,e$.isStreaming,nu]),nm=(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(a6),a=n.slice(r+1).flatMap(a6),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}})(nh,t9,tg?.messages),[nh,t9,tg]),[nf,ng]=(0,s.useState)(hR),{startIndex:nx,endIndex:nv,hasLater:ny}=hL(nh.length,nf),nb=null!==nf.end&&ny,nw=(0,s.useRef)(nh.length);nw.current=nh.length;let nk=(0,s.useRef)(null),nj=(0,s.useRef)(null),nC=(0,s.useRef)(null);(0,s.useEffect)(()=>{null!==nf.end&&nf.end>=nh.length&&ng(e=>({count:e.count,end:null}))},[nf.end,nh.length]),(0,s.useEffect)(()=>{let e=nk.current,t=tD.current;if(!e||!t)return;let n=new IntersectionObserver(e=>{e[0]?.isIntersecting&&(nC.current=t.scrollHeight-t.scrollTop,ng(e=>(function(e,t=50){return{...e,count:e.count+t}})(e)))},{root:t,threshold:0});return n.observe(e),()=>n.disconnect()},[nf,nh.length,tD]),(0,s.useEffect)(()=>{if(null==nC.current)return;let e=tD.current;if(e){var t;t=e.scrollHeight,e.scrollTop=Math.max(0,t-nC.current),nC.current=null}},[nf.count,tD]),(0,s.useEffect)(()=>{let e=nj.current,t=tD.current;if(!e||!t)return;let n=new IntersectionObserver(e=>{e[0]?.isIntersecting&&ng(e=>(function(e,t,n=50){if(null===t.end)return t;let{startIndex:r,endIndex:s}=hL(e,t),a=s+n;return a>=e?{count:e-r,end:null}:{count:a-r,end:a}})(nw.current,e))},{root:t,threshold:0});return n.observe(e),()=>n.disconnect()},[nf,nh.length,tD]);let[nT,nE]=(0,s.useState)(null),[n$,nR]=(0,s.useState)(0),nL=(0,s.useRef)(null),nA=(0,s.useCallback)(e=>{t_(),nL.current=e,nE(null),ng(t=>hA(nw.current,e,t)),nR(e=>e+1)},[t_]);(0,s.useLayoutEffect)(()=>{let e=nL.current,t=tD.current;if(null===e||!t)return;let n=t.querySelector(`[data-chat-item="${e}"]`);if(!n)return;nL.current=null;let r=document.createRange();r.selectNodeContents(n),t.scrollTop+=r.getBoundingClientRect().top-t.getBoundingClientRect().top-24,nE(e)},[n$,nf,nh,tD]),(0,s.useEffect)(()=>{if(null===nT)return;let e=setTimeout(()=>nE(null),1800);return()=>clearTimeout(e)},[nT]);let nP=(0,s.useCallback)(()=>{(0,a.flushSync)(()=>ng(hR));let e=tD.current;e&&(e.scrollTop=e.scrollHeight)},[tD]),n_=(0,s.useCallback)(()=>{nb&&nP(),tP()},[nb,nP,tP]),nF=(0,s.useRef)(null),[nz,nW]=(0,s.useState)(!1);(0,s.useEffect)(()=>{if(!O||nF.current===O.id||O.sessionId!==e?.id||eT||0===t9.length)return;nF.current=O.id,D?.(O.id);let t=eE.indexOf(O.entryId);if(t<0)return void nW(!0);let n=0;for(let e=0;e<nh.length;e++){let r=nh[e].idx;if(r>t||(n=e,r===t))break}nA(n)},[O,e?.id,eT,t9.length,eE,nh,nA,D]),(0,s.useEffect)(()=>{if(!nz)return;let e=setTimeout(()=>nW(!1),6e3);return()=>clearTimeout(e)},[nz]);let[nO,nD]=(0,s.useState)(!1),[nH,nU]=(0,s.useState)(0),nB=(0,s.useMemo)(()=>nO?nh.map(e=>(function(e,t){if("answer"===e.kind)return tu(e.blocks);let n=t[e.idx];return n&&"content"in n?tu(n.content):""})(e,t9).toLowerCase()):hW,[nO,nh,t9]),nq=(0,s.useCallback)(e=>{t_(),ng(t=>hA(nw.current,e,t))},[t_]),nV=(0,s.useCallback)(()=>nD(!1),[]);(0,s.useEffect)(()=>{let e=e=>{if(e.defaultPrevented||e.isComposing||e.altKey||e.shiftKey||!(e.ctrlKey||e.metaKey)||"f"!==e.key.toLowerCase())return;let t=tD.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(),nD(!0),nU(e=>e+1))};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[tD]);let nK=(0,s.useMemo)(()=>{let e=[];return nh.forEach((t,n)=>{if("message"!==t.kind)return;let r=h_(t9[t.idx]);null!==r&&e.push({item:n,text:r})}),e},[nh,t9]),nJ=`${nx}:${nv}`,nG=eE.length>0?eE[eE.length-1]:null,[nZ,nY]=(0,s.useState)(null),nQ=(0,s.useRef)(!1);(0,s.useEffect)(()=>{nQ.current||!tf||eT||!e?.id||(nQ.current=!0,nr||!nG||!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}(t9)||function(e){try{return window.localStorage.getItem(hO(e))}catch{return null}}(e.id)!==nG&&nY(nG))},[tf,eT,e?.id,nr,nG,t9]);let nX=(0,s.useCallback)(()=>{e?.id&&nZ&&function(e,t){try{window.localStorage.setItem(hO(e),t)}catch{}}(e.id,nZ),nY(null)},[e?.id,nZ]),n2=null!==nZ&&nZ===nG&&!nr&&!nb,n4=tm?[tm.sessionId,tm.sessionFile??"",tm.sessionName??"",tm.userMessages,tm.assistantMessages,tm.toolCalls,tm.toolResults,tm.totalMessages,tm.tokens.input,tm.tokens.output,tm.tokens.cacheRead,tm.tokens.cacheWrite,tm.tokens.total,tm.cost??0,tm.totalActiveMs??0].join("|"):null,n8=(0,s.useRef)(tm);n8.current=tm,(0,s.useEffect)(()=>{v?.(n8.current)},[n4,v]),(0,s.useEffect)(()=>()=>{v?.(null)},[v]);let n5=e8?`${e8.percent??"null"}|${e8.contextWindow}|${e8.tokens??"null"}`:null,n6=(0,s.useRef)(e8);n6.current=e8,(0,s.useEffect)(()=>{b?.(n6.current)},[n5,b]),(0,s.useEffect)(()=>()=>{b?.(null)},[b]),(0,s.useEffect)(()=>{w?.(tb)},[w,tb]),(0,s.useEffect)(()=>()=>{w?.([])},[w]);let{regular:n3,lab:n7}=(0,s.useMemo)(()=>(function(e){let t=[],n=[];for(let s of e){var r;((r=s.key).startsWith(cU)&&null!==cB(r)?n:t).push(s)}return{regular:t,lab:n}})(tT),[tT]),n9=e?.id??null;(0,s.useEffect)(()=>{k?.(n9,n7)},[k,n9,n7]),(0,s.useEffect)(()=>()=>{k?.(null,[])},[k]);let{isDragOver:rt,handleDragEnter:rn,handleDragOver:rr,handleDragLeave:rs,handleDrop:ra}=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=>{nr||m?.current?.addAttachments(e)},[nr,m])),ri=(0,s.useMemo)(()=>{var e;return e=tg?.messages,e&&e.length>0?[...e,...t9]:t9},[tg,t9]),rl=(0,s.useMemo)(()=>{let e=new Map;for(let t of ri)"toolResult"===t.role&&e.set(t.toolCallId,t);return e},[ri]),ru=(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=aY(e.status);if(!r||o.has(r)||"completed"!==a&&"failed"!==a&&"aborted"!==a)return;o.add(r);let i=aZ(e);null!==i&&s.set(r,i)},d=(e,t,r)=>{let s=t?n.get(t):void 0,a=aZ(e);s&&"number"==typeof r&&null!==a&&"running"===aY(e.status)&&i.set(s,Math.max(i.get(s)??-1/0,r-a))},ri.forEach((t,s)=>{if("assistant"===t.role){for(let e of t.content??[]){if("toolCall"!==e.type||"task"!==e.toolName)continue;let t=rl.get(e.toolCallId);if(t)for(let s of aX(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(aQ(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=aG(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:aG(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 aJ(t.details?.jobs)){if("task"!==r.type)continue;let a=aG(r.id);if(a&&l(a,aY(r.status),s),c(r,a),d(r,a,t.timestamp),a&&"running"===aY(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 aQ(t.content).matchAll(a0)){let t=Object.fromEntries([...e[1].matchAll(a1)].map(e=>[e[1],e[2]]));t.id&&l(t.id,aY(t.status),s)}for(let e of aJ(t.details?.jobs))"task"===e.type&&c(e,aG(e.jobId))}}),{verdicts:e,runs:t,latestByAgent:n,spawnedAt:r,durations:s,parallelWith:a,runStartedAt:i}},[ri,rl]),rh=(0,s.useMemo)(()=>({ledger:ru,subagents:tb,toolResults:rl,onOpenPanel:j,sessionId:e?.id??null,cwd:e?.cwd??t??void 0,onOpenMaker:C,selectedMaker:N}),[ru,tb,rl,j,e?.id,e?.cwd,t,C,N]),rp=(0,s.useMemo)(()=>{let e=new Set,t=[];for(let n=t9.length-1;n>=0;n-=1){let r=h_(t9[n]);if(!(!r||e.has(r))&&(e.add(r),t.push(r),t.length>=50))break}return t.reverse()},[t9]),rm=(0,s.useMemo)(()=>tA(t9,rl,tw,tg?.todoPhases??null),[t9,rl,tw,tg]),rg=(0,s.useMemo)(()=>cL(e$.streamingMessage).join("|"),[e$.streamingMessage]),rx=(0,s.useMemo)(()=>JSON.stringify(cR(e$.streamingMessage)),[e$.streamingMessage]),rv=(0,s.useMemo)(()=>JSON.stringify(cP(e$.streamingMessage)),[e$.streamingMessage]),ry=(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=cL(r),c=cP(r,a);if(0===s.length&&0===c.length||o<0)continue;let d=cR(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)})(t9,eE,rg.length>0?rg.split("|"):[],JSON.parse(rx),JSON.parse(rv)),[t9,eE,rg,rx,rv]),rb=e?.id??tz.current??void 0,rw=(G=cz(K=(0,s.useMemo)(()=>({sessionId:rb,sessionProvider:th?.provider,turns:ry,messages:t9,subagents:tb}),[rb,th?.provider,ry,t9,tb])),Z=cH(K),(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}([...G,...Z])),[G,Z])),rk=tR&&0===t9.length&&!e$.isStreaming&&!nr,rj=(0,s.useMemo)(()=>t9.filter(e=>"assistant"===e.role).length,[t9]),rS=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=e1(e);if(null===a)return;let i=e2(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}(e$.streamingMessage?.role==="assistant"?e$.streamingMessage:null,rj),rC=(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})(t9),[t9]),rN=e?.cwd??t??void 0,rT=th?eO[`${th.provider}:${th.modelId}`]??null:null,rI=th?eD[`${th.provider}:${th.modelId}`]??null:null,rM=(0,s.useRef)(null),rE=(0,s.useRef)(null),r$=(0,s.useCallback)(()=>{let e=rM.current?.querySelector("textarea");e&&(e.focus({preventScroll:!0}),e.setSelectionRange(e.value.length,e.value.length))},[]);(0,s.useEffect)(()=>(E?.(r$),()=>E?.(null)),[r$,E]),(0,s.useLayoutEffect)(()=>{let e=rE.current,t=e?.closest(".workspace-shell");if(!e||!t)return;let n=tD.current?.clientHeight??0,r=()=>{let r=Math.ceil(e.getBoundingClientRect().height);r>0&&t.style.setProperty("--omp-dock-h",`${r}px`);let s=tD.current;if(!s)return;let a=n-s.clientHeight;n=s.clientHeight,a<=0||s.scrollHeight-s.scrollTop-s.clientHeight-a<=1&&(s.scrollTop+=a)};r();let s=new ResizeObserver(r);return s.observe(e),()=>s.disconnect()},[eT,tD]);let rR=(0,s.useCallback)((...e)=>(null!==nf.end&&nP(),tH(...e)),[tH,nf.end,nP]),rL=(0,r.jsx)("div",{ref:rM,"data-chat-composer":"",style:{display:"contents"},children:(0,r.jsx)(uq,{ref:m,sessionId:e?.id??tz.current??void 0,onEnsureSession:tR&&t?t3:void 0,onLiveTranscriptPersisted:t7,onSend:rR,onAbort:tU,onSteer:eR?tY:void 0,onFollowUp:eR?tQ:void 0,onPromptWithStreamingBehavior:eR?tX:void 0,isStreaming:nr,model:th,isAutoModelSelection:tE,modelNames:e_,modelList:eF,modelError:ez,modelScopeWarnings:eW,onModelChange:tV,onMainPresetChange:e||tR?tJ:void 0,mainPresetActiveAlias:nn,modelRoles:eH,onRoleModelChange:tK,modelSwitching:tp,onCompact:e||tR?tZ:void 0,onAbortCompaction:t0,isCompacting:e3,compactError:tc,compactResult:td,toolPreset:eU,onToolPresetChange:e||tR?t8:void 0,thinkingLevel:eB,effectiveThinkingLevel:eq,outputTokensPerSecond:rS??rC,outputSpeedLive:null!==rS,thinkingCeiling:eV,onThinkingLevelChange:e||tR?t5:void 0,fastMode:eJ,fastModeBusy:eX,onFastModeToggle:e||tR?e0:void 0,availableThinkingLevels:rT,thinkingLevelMap:rI,retryInfo:e4,deliveryRows:ty,inputHistory:rp,onRecallQueue:t1,onRemoveQueuedMessage:t2,slashCommands:tx,slashCommandsLoading:tv,onLoadSlashCommands:t6,onBuiltinCommand:t4,soundEnabled:A,onSoundToggle:P,onAudioUnlock:W,draftKey:e?.id??(t?`new:${t}`:void 0),cwd:e?.cwd??t,sessionTitle:e?.name})}),rA=e$.streamingMessage,rP=(0,s.useMemo)(()=>rA?eY(rA,{isStreaming:!0}):[],[rA]),r_=(0,s.useMemo)(()=>rP.filter(e=>"answer"===e.kind).flatMap(e=>e.blocks),[rP]),rF=(0,s.useMemo)(()=>rP.filter(e=>"answer"!==e.kind).map(e=>e.blocks),[rP]),rz=rA?.role==="assistant"?rA:null,rW=(0,s.useMemo)(()=>{let e=-1;for(let t=t9.length-1;t>=0;t-=1)if("user"===t9[t].role){e=t;break}let t=e<0?-1:lK(t9,e);return{start:t,blocks:lq(t9,t+1,t9.length),priorCiHeads:lG(t9,rl,t+1),jobNotices:lV(t9,t+1,t9.length)}},[t9,rl]),rO=(0,s.useMemo)(()=>lM(rz?[...rW.blocks,...rz.content??[]]:rW.blocks,rl,nr,rW.priorCiHeads,rN,rW.jobNotices),[rW,rz,rl,nr,rN]),rD=(0,s.useMemo)(()=>nr?{...lB(rW.blocks,rl,rN),span:lZ(t9,rW.start+1,t9.length)}:null,[nr,rW,rl,rN,t9]),rH=(0,s.useMemo)(()=>rD?{...rD,flow:rO,latest:!0}:null,[rD,rO]),rU=(0,s.useMemo)(()=>{let e=null;if(nr)for(let t of nh)"message"===t.kind&&t9[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"&&lK(t,e.idx)===e.idx).map(e=>e.idx),a=null===n?null:lK(t,n),i=new Map;for(let[n,l]of(e.forEach((e,n)=>{"answer"===e.kind&&i.set(lK(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(lG(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&&ti(i[s]);)s-=1;if(i[s]!==a.throughEntryId)continue;let l=lq(t,n.from,n.to).filter(e=>"toolCall"===e.type&&"task"===e.toolName),h=lJ(t,r,n.from,n.to);c.set(e,{...a.summary,...h?{remaining:lU(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=lq(e,n,r),l=lJ(e,t,n,r);return{...lB(i,t,s),remaining:l?lU(l):null,span:lZ(e,n,r),flow:lM(i,t,!1,a,s,lV(e,n,r))}}(t,r,n.from,n.to,s,d),latest:e===o})}return c}(nh,t9,e,rl,rN,tg?.openRequest??null,eE)},[nh,t9,rl,rN,nr,tg,eE]),[rB,rq]=(0,s.useState)(null),rV=e?.id??null;(0,s.useEffect)(()=>{rq(null)},[rV]);let rK=null;for(let e of rU.keys())(null===rK||e>rK)&&(rK=e);let rJ=("live"===rB?null!==rH:null!==rB&&rU.has(rB))?rB:rH?"live":rK,rG="live"===rJ?rH:null===rJ?null:rU.get(rJ)??null,rZ=null!==rH,rY=(0,s.useMemo)(()=>({selected:rJ,shown:null!==H,select:e=>{rq(e),B?.()},latestTurn:rZ?null:rK,compactedCalls:nm?.calls,onOpenFile:I}),[B,rJ,H,rZ,rK,nm,I]),rQ=null===rJ||"live"===rJ||rJ===rK,rX=H&&(0,a.createPortal)((0,r.jsx)(a3.Provider,{value:rh,children:(0,r.jsx)(co,{summary:rG,live:"live"===rJ,folded:q,compactedCalls:rQ?nm?.calls:void 0,onOpenFile:I})}),H),r0=eR&&(t$?.kind==="running_tools"||(rz?.content??[]).some(e=>"text"===e.type&&/\S/.test(e.text)||"toolCall"===e.type)),r1=rc(t9,rz,th?.provider,th?.modelId),r2=r1.provider,r4=r1.model,r8=r1.credentialId;(0,s.useEffect)(()=>{if(!r0)return;let e=eg();e&&em.current!==e.turn&&ef.current!==e.turn&&(em.current=e.turn,ew("working",e,r2,r8,r4))},[r0,r2,r4,r8,eg,ew]);let[r5,r6]=(0,s.useState)(null),r3=(0,s.useCallback)(e=>{r6(e)},[]),r7=(0,s.useMemo)(()=>eP?{role:"bashExecution",command:eP.command,output:"",excludeFromContext:eP.excludeFromContext}:null,[eP]),r9=(0,s.useMemo)(()=>{let e=[eR&&!rA&&t$?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}(t$,Y):null,eL&&!eP?Y("chat.runningCommand"):null].filter(e=>!!e);return e.length>0?e.join(" \xb7 "):null},[eR,rA,t$,eL,eP,Y]);(0,s.useEffect)(()=>{if(!r5)return void T?.(null);let e=[],t=[],n=0;if(rA&&rF.length>0){let r=r5.messages.length+e.length;for(let s of(e.push(rA),rF))t.push({idx:r,blocks:s}),n+=eQ(s)}if(r7&&(t.push({idx:r5.messages.length+e.length}),e.push(r7)),0===t.length)return void T?.(r9?{...r5,status:r9}:r5);let r=-1;for(let e=r5.messages.length-1;e>=0;e--)if(to(r5.messages[e])){r=e;break}let s=r5.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}),T?.({...r5,groups:s,messages:[...r5.messages,...e],status:r9})},[r5,rF,rA,r7,r9,T]),(0,s.useEffect)(()=>()=>T?.(null),[T]);let se=n3.filter(e=>"belowEditor"!==e.placement),st=n3.filter(e=>"belowEditor"===e.placement);return eI?(0,r.jsx)("div",{className:"flex h-full items-center justify-center text-red-400",children:eI}):(0,r.jsxs)("div",{className:"chat-window relative flex h-full min-w-0 flex-col overflow-hidden","aria-busy":nc,"data-empty-start":rk&&!M?"true":void 0,style:{paddingBottom:"env(safe-area-inset-bottom)"},onDragEnter:rn,onDragOver:rr,onDragLeave:rs,onDrop:ra,children:[nc?(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:Y("chat.loadingSession")})}):null,rt&&!nr&&(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:Y("chat.attachFile")})}),tC&&(0,r.jsx)(hJ,{request:tC,onInput:tM}),rk&&!M?(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.341"]})]}),(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.0"]})]})]})]}),rN&&(0,r.jsxs)("section",{className:"empty-workspace-context","aria-label":Y("chat.emptyProjectLabel"),children:[(0,r.jsxs)("div",{className:"empty-workspace-context-text",children:[(0,r.jsx)("span",{className:"empty-workspace-context-kicker",children:Y("chat.emptyProjectLabel")}),(0,r.jsx)("strong",{children:tW(rN)||rN}),(0,r.jsx)("code",{title:rN,children:rN}),(0,r.jsx)("p",{children:Y("chat.emptyProjectHint")})]}),S&&(0,r.jsx)("button",{type:"button",className:"empty-workspace-context-action",onClick:S,children:Y("chat.openSessionList")})]}),(0,r.jsx)(hq,{notices:tk,align:"right"})]})}):(0,r.jsxs)(r.Fragment,{children:[M&&(0,r.jsx)("div",{className:"min-h-0 min-w-0 flex-1 overflow-hidden",children:M}),(0,r.jsxs)("div",{className:"relative min-w-0 flex-1 overflow-hidden","aria-hidden":!!M,style:{display:M?"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)(cp,{open:nO,onClose:nV,containerRef:tD,index:nB,renderedStart:nx,renderedEnd:nv,contentKey:t9,onReveal:nq,onProgrammaticScroll:t_,focusRequest:nH,t:Y}),nz&&(0,r.jsx)("div",{className:"chat-jump-missing",role:"status",children:Y("chat.jumpMissing")}),(0,r.jsx)(hq,{notices:tk,floating:!0,align:"right"})]})}),(0,r.jsx)("div",{ref:tD,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)(hB,{widgets:se}),(0,r.jsx)(a3.Provider,{value:rh,children:(0,r.jsxs)(o7.Provider,{value:rY,children:[(0,r.jsx)(cT,{utterances:rw,children:(0,r.jsx)(hD,{messages:t9,entryIds:eE,toolResultsMap:rl,modelNames:e_,messageCwd:rN,onOpenFile:I,sessionBusy:nr,isNew:tR,isStreaming:e$.isStreaming,handleFork:tB,forkingEntryId:e6,handleNavigate:tq,handleEditContent:eN,sessionId:e?.id??tz.current??void 0,main:nh,turnSummaries:rU,process:np,startIndex:nx,endIndex:nv,sentinelRef:nk,laterSentinelRef:nj,flashItem:nT,t:Y,cues:ea,cueFollowRef:na,onProcessLogChange:r3})}),!nb&&e$.isStreaming&&e$.streamingMessage&&r_.length>0&&(0,r.jsx)(s9,{message:eK(e$.streamingMessage,r_),sessionId:e?.id??tz.current??void 0,isStreaming:!0,modelNames:e_,cwd:rN,onOpenFile:I}),!nb&&rH&&(0,r.jsx)(cn,{summary:rH,turnKey:"live",live:!0})]})}),n2&&(0,r.jsx)(cy,{onDismiss:nX,t:Y}),(0,r.jsx)("div",{ref:tO})]})})}),(0,r.jsx)(cm,{questions:nK,containerRef:tD,layoutKey:nJ,onJump:nA,label:Y("chat.questionRail")}),(nr&&tL||nb)&&(0,r.jsxs)("button",{type:"button",onClick:n_,"aria-label":Y("chat.jumpToBottom"),title:Y("chat.jumpToBottom"),style:{position:"absolute",bottom:16,left:"50%",transform:"translateX(-50%)",zIndex:40,display:"flex",alignItems:"center",gap:6,padding:"6px 12px",minHeight:X?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"})]}),Y("chat.jumpToBottom")]})]})]}),(0,r.jsxs)("div",{ref:rE,className:"relative chat-composer-dock flex min-h-0 flex-col",children:[tj&&(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)(hK,{request:tj,onRespond:tI,onActivity:(e,t)=>void tM(e,t??"activity"),delivery:tS})})}),(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:tn,t:Y}),(0,r.jsx)(hU,{goal:tF,t:Y}),(0,r.jsx)(hB,{widgets:st}),(rm||rO.steps.length>0)&&!et&&(0,r.jsx)(uK,{phases:rm,flow:rO,busy:nr})]})}),q&&!H&&rG&&null!==rJ&&!et&&(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)(a3.Provider,{value:rh,children:(0,r.jsx)(cs,{summary:rG,live:"live"===rJ,onOpen:()=>rY.select(rJ)})})})}),rL,(0,r.jsx)(uV,{statuses:tN})]}),rX]})}function hU({goal:e,t}){if(!e)return null;let n=!e.enabled,s=void 0!==e.tokenBudget?t("chat.goalBudgetLeft",{left:nV(Math.max(0,e.tokenBudget-e.tokensUsed))}):t("chat.goalTokensUsed",{used:nV(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 hB({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 hq({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 hV({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 hK({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)(hV,{focusKey:e.id,label:i("chat.agentQuestion"),delivery:a,children:(0,r.jsx)(c9,{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)(hV,{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)(hV,{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)(nk,{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)(hV,{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 hJ({request:e,onInput:t}){let{t:n}=(0,F.s)(),a=(0,s.useRef)(null),i=(0,s.useRef)(!1),l=ez(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=eD[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":" ":eO[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}`,eW(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 hG=n(40960),hZ=n.n(hG);function hY({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?` ${hZ().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})]})}let hQ={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"})]}),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 hX({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:hQ[e]})}function h0({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)"})]})})}function h1({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)(hX,{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 h2=n(50640),h4=n(73620);let h8=/^(?:\uFEFF)?---[ \t]*(?:\r\n|\n|\r)/;function h5(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 h6=["tags","categories","keywords","tag","category"];function h3({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=h6.find(t=>Array.isArray(e[t])),i=a?e[a].map(h5).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=h5(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 h7=n(8745);let h9=(0,s.createContext)(null),pe=(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"})}),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:"m10 3-5 5 5 5"})}),pr=(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"})}),ps=(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 pa({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:pn})}),(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)(h7.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)(h7.A.Item,{value:e.value,title:e.title,children:[(0,r.jsx)(h7.A.ItemHiddenInput,{}),e.label]},e.value)),(0,r.jsx)(h7.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:ps})})}),(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)(pi,{}),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:pr})})]})}function pi({className:e="panel-header-button"}){let{t}=(0,F.s)(),n=(0,s.useContext)(h9);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:pe})})}let pl="cuelo-html-pick",po="cuelo-html-pick-exit";function pc(e,t){return"string"==typeof e&&e.length<=t}function pd(e){return"number"==typeof e&&Number.isFinite(e)}function pu({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(po)};
22
22
  var host=window.parent;
23
23
  if(document.currentScript)document.currentScript.remove();