@seele00/seele-work 0.1.124 → 0.1.125

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 (68) hide show
  1. package/libexec/seele-server +0 -0
  2. package/libexec/seele-worker +0 -0
  3. package/libexec/seele-workspace-observe +0 -0
  4. package/package.json +1 -1
  5. package/release-manifest.json +125 -125
  6. package/web/dist/assets/{abnfDiagram-VRR7QNED-B_kH1nIm.js → abnfDiagram-VRR7QNED-D_yZSqrZ.js} +1 -1
  7. package/web/dist/assets/{arc-xa0iHFjk.js → arc-yK0OCbmk.js} +1 -1
  8. package/web/dist/assets/{architectureDiagram-ZJ3FMSHR-CzU_g4So.js → architectureDiagram-ZJ3FMSHR-CG3JpKId.js} +1 -1
  9. package/web/dist/assets/{blockDiagram-677ZJIJ3-CSC15fYc.js → blockDiagram-677ZJIJ3-C9QS5aze.js} +1 -1
  10. package/web/dist/assets/{c4Diagram-LMCZKHZV-B1DIXX6j.js → c4Diagram-LMCZKHZV-Gk0PO3p1.js} +1 -1
  11. package/web/dist/assets/channel-BwDPZHUy.js +1 -0
  12. package/web/dist/assets/{chunk-2Q5K7J3B-BFAdDgdu.js → chunk-2Q5K7J3B-J-hqh2gc.js} +1 -1
  13. package/web/dist/assets/{chunk-32BRIVSS-D0UwF4QZ.js → chunk-32BRIVSS-D9ZVaz8N.js} +1 -1
  14. package/web/dist/assets/{chunk-5VM5RSS4-B7D1rhlx.js → chunk-5VM5RSS4-CiPC7766.js} +1 -1
  15. package/web/dist/assets/{chunk-EX3LRPZG-Dng2T9Dy.js → chunk-EX3LRPZG-BhFqCCJl.js} +1 -1
  16. package/web/dist/assets/{chunk-JWPE2WC7-BHLKsg82.js → chunk-JWPE2WC7-K9j3Tpmq.js} +1 -1
  17. package/web/dist/assets/{chunk-MOJQB5TN-Bbq8g_7P.js → chunk-MOJQB5TN-ZZaTZvz9.js} +1 -1
  18. package/web/dist/assets/{chunk-RYQCIY6F-Dok8Mg9c.js → chunk-RYQCIY6F-CGATfeAL.js} +1 -1
  19. package/web/dist/assets/{chunk-V7JOEXUC-BA8n3gfC.js → chunk-V7JOEXUC-CcoXW_IA.js} +1 -1
  20. package/web/dist/assets/{chunk-VR4S4FIN-DPkZvuV1.js → chunk-VR4S4FIN-snrdRODA.js} +1 -1
  21. package/web/dist/assets/{chunk-XXDRQBXY-ZhJsKF0o.js → chunk-XXDRQBXY-YjruLOdm.js} +1 -1
  22. package/web/dist/assets/classDiagram-OUVF2IWQ-CqAh_8zE.js +1 -0
  23. package/web/dist/assets/classDiagram-v2-EOCWNBFH-CqAh_8zE.js +1 -0
  24. package/web/dist/assets/{core-0O0cuLx6.js → core-BEHJop_C.js} +1 -1
  25. package/web/dist/assets/{cose-bilkent-JH36ORCC-DQy3Yb5d.js → cose-bilkent-JH36ORCC-BBQFRLil.js} +1 -1
  26. package/web/dist/assets/{cynefin-VYW2F7L2-Bb63cxSQ.js → cynefin-VYW2F7L2-Dj6ehbQ4.js} +1 -1
  27. package/web/dist/assets/{cynefinDiagram-TSTJHNR4-DT0il-Hv.js → cynefinDiagram-TSTJHNR4-DHat9xn9.js} +1 -1
  28. package/web/dist/assets/{dagre-VKFMJZFB-Cbm5v8ii.js → dagre-VKFMJZFB-DUlnshF_.js} +1 -1
  29. package/web/dist/assets/{diagram-FQU43EPY-BYmehC-M.js → diagram-FQU43EPY-BlVn--_4.js} +1 -1
  30. package/web/dist/assets/{diagram-G47NLZAW-00YJ-fw3.js → diagram-G47NLZAW-CDqXu84J.js} +1 -1
  31. package/web/dist/assets/{diagram-NH7WQ7WH-CXX1aQw_.js → diagram-NH7WQ7WH-CZGxh6Wb.js} +1 -1
  32. package/web/dist/assets/{diagram-OA4YK3LP-BUaaV2d6.js → diagram-OA4YK3LP-DGKGdN5h.js} +1 -1
  33. package/web/dist/assets/{diagram-WEI45ONY-CCXemssm.js → diagram-WEI45ONY-BBPNpWlp.js} +1 -1
  34. package/web/dist/assets/{ebnfDiagram-CCIWWBDH-DKXmEp94.js → ebnfDiagram-CCIWWBDH-DyZJCJfa.js} +1 -1
  35. package/web/dist/assets/{erDiagram-Q63AITRT-qRlFwmjq.js → erDiagram-Q63AITRT-EnbKJfWu.js} +1 -1
  36. package/web/dist/assets/{flowDiagram-23GEKE2U-u85oZ5y3.js → flowDiagram-23GEKE2U-CfK6l3ok.js} +1 -1
  37. package/web/dist/assets/{ganttDiagram-NO4QXBWP-BTqL8gws.js → ganttDiagram-NO4QXBWP-puLwY_Xh.js} +1 -1
  38. package/web/dist/assets/{gitGraphDiagram-IHSO6WYX-BB78idDL.js → gitGraphDiagram-IHSO6WYX-xGzwnEXc.js} +1 -1
  39. package/web/dist/assets/{index-DaRSfH2B.js → index-U8EQQSnK.js} +36 -30
  40. package/web/dist/assets/{infoDiagram-FWYZ7A6U-RCDOO8-Y.js → infoDiagram-FWYZ7A6U-CeeBgxi4.js} +1 -1
  41. package/web/dist/assets/{ishikawaDiagram-FXEZZL3T-Cc5anuA2.js → ishikawaDiagram-FXEZZL3T-CqvX4Zh8.js} +1 -1
  42. package/web/dist/assets/{journeyDiagram-5HDEW3XC-DMfSxZkr.js → journeyDiagram-5HDEW3XC-DgwRNt8A.js} +1 -1
  43. package/web/dist/assets/{kanban-definition-HUTT4EX6-BKNNPh1_.js → kanban-definition-HUTT4EX6-BPKP590z.js} +1 -1
  44. package/web/dist/assets/{linear-CY1Ns8No.js → linear-CP3PnulA.js} +1 -1
  45. package/web/dist/assets/{mermaid.core-BjW4FHdg.js → mermaid.core-BeXu8ScT.js} +5 -5
  46. package/web/dist/assets/{mindmap-definition-LN4V7U3C-D4MLQkUJ.js → mindmap-definition-LN4V7U3C-DdqdtjeK.js} +1 -1
  47. package/web/dist/assets/{pegDiagram-2B236MQR-BhVIK92R.js → pegDiagram-2B236MQR-C78CRSoK.js} +1 -1
  48. package/web/dist/assets/{pieDiagram-ENE6RG2P-LsDzJ8Oi.js → pieDiagram-ENE6RG2P-qnahSUU_.js} +1 -1
  49. package/web/dist/assets/{quadrantDiagram-ABIIQ3AL-s6oqf7fB.js → quadrantDiagram-ABIIQ3AL-RVzjaWjT.js} +1 -1
  50. package/web/dist/assets/{railroadDiagram-RFXS5EU6-IG4o-XZB.js → railroadDiagram-RFXS5EU6-CT7x4nEl.js} +1 -1
  51. package/web/dist/assets/{requirementDiagram-TGXJPOKE-DvLbxvsb.js → requirementDiagram-TGXJPOKE-C7592sBZ.js} +1 -1
  52. package/web/dist/assets/{sankeyDiagram-HTMAVEWB-_7O_GQD4.js → sankeyDiagram-HTMAVEWB-ad-wZIN-.js} +1 -1
  53. package/web/dist/assets/{sequenceDiagram-DBY2YBRQ-BXW3IBO0.js → sequenceDiagram-DBY2YBRQ-DI10NXvR.js} +1 -1
  54. package/web/dist/assets/{sizeCapture-X5ZJPWSS-DAsC92Ze.js → sizeCapture-X5ZJPWSS-Ch_EaUOQ.js} +1 -1
  55. package/web/dist/assets/{stateDiagram-2N3HPSRC-ChyEmtfL.js → stateDiagram-2N3HPSRC-DKHt7m8k.js} +1 -1
  56. package/web/dist/assets/stateDiagram-v2-6OUMAXLB-zL7tBATR.js +1 -0
  57. package/web/dist/assets/{swimlanes-5IMT3BWC-De2ERjbQ.js → swimlanes-5IMT3BWC-BO4ZSIHp.js} +2 -2
  58. package/web/dist/assets/swimlanesDiagram-G3AALYLV-BV4-_c5_.js +8 -0
  59. package/web/dist/assets/{timeline-definition-FHXFAJF6-wqXKnO2p.js → timeline-definition-FHXFAJF6-CQGC6cYg.js} +1 -1
  60. package/web/dist/assets/{vennDiagram-L72KCM5P-ULwPLZpm.js → vennDiagram-L72KCM5P-xWiEWgt2.js} +1 -1
  61. package/web/dist/assets/{wardleyDiagram-EHGQE667-DVyXj8Yg.js → wardleyDiagram-EHGQE667-1wH74dTH.js} +1 -1
  62. package/web/dist/assets/{xychartDiagram-FW5EYKEG-CX-UN5E8.js → xychartDiagram-FW5EYKEG-Cp4wjH8Q.js} +1 -1
  63. package/web/dist/index.html +1 -1
  64. package/web/dist/assets/channel-6KggRmb9.js +0 -1
  65. package/web/dist/assets/classDiagram-OUVF2IWQ-bTPjN3A-.js +0 -1
  66. package/web/dist/assets/classDiagram-v2-EOCWNBFH-bTPjN3A-.js +0 -1
  67. package/web/dist/assets/stateDiagram-v2-6OUMAXLB-BYhqyZA9.js +0 -1
  68. package/web/dist/assets/swimlanesDiagram-G3AALYLV-Cc99IGaA.js +0 -8
@@ -335,59 +335,65 @@ l0,-`+(n+144)+`c-2,-159.3,-10,-310.7,-24,-454c-53.3,-528,-210,-949.7,
335
335
  |[ \r ]+
336
336
  ?)[ \r ]*`,Ip="[̀-ͯ]",zT=new RegExp(Ip+"+$"),DT="("+Tv+"+)|"+(MT+"|")+"([!-\\[\\]-‧‪-퟿豈-￿]"+(Ip+"*")+"|[\uD800-\uDBFF][\uDC00-\uDFFF]"+(Ip+"*")+"|\\\\verb\\*([^]).*?\\4|\\\\verb([^*a-zA-Z]).*?\\5"+("|"+NT)+("|"+ET+")");class p3{constructor(t,n){this.input=void 0,this.settings=void 0,this.tokenRegex=void 0,this.catcodes=void 0,this.input=t,this.settings=n,this.tokenRegex=new RegExp(DT,"g"),this.catcodes={"%":14,"~":13}}setCatcode(t,n){this.catcodes[t]=n}lex(){var t=this.input,n=this.tokenRegex.lastIndex;if(n===t.length)return new Or("EOF",new br(this,n,n));var i=this.tokenRegex.exec(t);if(i===null||i.index!==n)throw new je("Unexpected character: '"+t[n]+"'",new Or(t[n],new br(this,n,n+1)));var l=i[6]||i[3]||(i[2]?"\\ ":" ");if(this.catcodes[l]===14){var o=t.indexOf(`
337
337
  `,this.tokenRegex.lastIndex);return o===-1?(this.tokenRegex.lastIndex=t.length,this.settings.reportNonstrict("commentAtEnd","% comment has no terminating newline; LaTeX would fail because of commenting the end of math mode (e.g. $)")):this.tokenRegex.lastIndex=o+1,this.lex()}return new Or(l,new br(this,n,this.tokenRegex.lastIndex))}}class RT{constructor(t,n){t===void 0&&(t={}),n===void 0&&(n={}),this.current=void 0,this.builtins=void 0,this.undefStack=void 0,this.current=n,this.builtins=t,this.undefStack=[]}beginGroup(){this.undefStack.push({})}endGroup(){if(this.undefStack.length===0)throw new je("Unbalanced namespace destruction: attempt to pop global namespace; please report this as a bug");var t=this.undefStack.pop();for(var n in t)t.hasOwnProperty(n)&&(t[n]==null?delete this.current[n]:this.current[n]=t[n])}endGroups(){for(;this.undefStack.length>0;)this.endGroup()}has(t){return this.current.hasOwnProperty(t)||this.builtins.hasOwnProperty(t)}get(t){return this.current.hasOwnProperty(t)?this.current[t]:this.builtins[t]}set(t,n,i){if(i===void 0&&(i=!1),i){for(var l=0;l<this.undefStack.length;l++)delete this.undefStack[l][t];this.undefStack.length>0&&(this.undefStack[this.undefStack.length-1][t]=n)}else{var o=this.undefStack[this.undefStack.length-1];o&&!o.hasOwnProperty(t)&&(o[t]=this.current[t])}n==null?delete this.current[t]:this.current[t]=n}}var OT=pv;D("\\noexpand",function(e){var t=e.popToken();return e.isExpandable(t.text)&&(t.noexpand=!0,t.treatAsRelax=!0),{tokens:[t],numArgs:0}});D("\\expandafter",function(e){var t=e.popToken();return e.expandOnce(!0),{tokens:[t],numArgs:0}});D("\\@firstoftwo",function(e){var t=e.consumeArgs(2);return{tokens:t[0],numArgs:0}});D("\\@secondoftwo",function(e){var t=e.consumeArgs(2);return{tokens:t[1],numArgs:0}});D("\\@ifnextchar",function(e){var t=e.consumeArgs(3);e.consumeSpaces();var n=e.future();return t[0].length===1&&t[0][0].text===n.text?{tokens:t[1],numArgs:0}:{tokens:t[2],numArgs:0}});D("\\@ifstar","\\@ifnextchar *{\\@firstoftwo{#1}}");D("\\TextOrMath",function(e){var t=e.consumeArgs(2);return e.mode==="text"?{tokens:t[0],numArgs:0}:{tokens:t[1],numArgs:0}});var g3={0:0,1:1,2:2,3:3,4:4,5:5,6:6,7:7,8:8,9:9,a:10,A:10,b:11,B:11,c:12,C:12,d:13,D:13,e:14,E:14,f:15,F:15};D("\\char",function(e){var t=e.popToken(),n,i=0;if(t.text==="'")n=8,t=e.popToken();else if(t.text==='"')n=16,t=e.popToken();else if(t.text==="`")if(t=e.popToken(),t.text[0]==="\\")i=t.text.charCodeAt(1);else{if(t.text==="EOF")throw new je("\\char` missing argument");i=t.text.charCodeAt(0)}else n=10;if(n){if(i=g3[t.text],i==null||i>=n)throw new je("Invalid base-"+n+" digit "+t.text);for(var l;(l=g3[e.future().text])!=null&&l<n;)i*=n,i+=l,e.popToken()}return"\\@char{"+i+"}"});var z1=(e,t,n,i)=>{var l=e.consumeArg().tokens;if(l.length!==1)throw new je("\\newcommand's first argument must be a macro name");var o=l[0].text,c=e.isDefined(o);if(c&&!t)throw new je("\\newcommand{"+o+"} attempting to redefine "+(o+"; use \\renewcommand"));if(!c&&!n)throw new je("\\renewcommand{"+o+"} when command "+o+" does not yet exist; use \\newcommand");var f=0;if(l=e.consumeArg().tokens,l.length===1&&l[0].text==="["){for(var h="",m=e.expandNextToken();m.text!=="]"&&m.text!=="EOF";)h+=m.text,m=e.expandNextToken();if(!h.match(/^\s*[0-9]+\s*$/))throw new je("Invalid number of arguments: "+h);f=parseInt(h),l=e.consumeArg().tokens}return c&&i||e.macros.set(o,{tokens:l,numArgs:f}),""};D("\\newcommand",e=>z1(e,!1,!0,!1));D("\\renewcommand",e=>z1(e,!0,!1,!1));D("\\providecommand",e=>z1(e,!0,!0,!0));D("\\message",e=>{var t=e.consumeArgs(1)[0];return console.log(t.reverse().map(n=>n.text).join("")),""});D("\\errmessage",e=>{var t=e.consumeArgs(1)[0];return console.error(t.reverse().map(n=>n.text).join("")),""});D("\\show",e=>{var t=e.popToken(),n=t.text;return console.log(t,e.macros.get(n),Fl[n],Kt.math[n],Kt.text[n]),""});D("\\bgroup","{");D("\\egroup","}");D("~","\\nobreakspace");D("\\lq","`");D("\\rq","'");D("\\aa","\\r a");D("\\AA","\\r A");D("\\textcopyright","\\html@mathml{\\textcircled{c}}{\\char`©}");D("\\copyright","\\TextOrMath{\\textcopyright}{\\text{\\textcopyright}}");D("\\textregistered","\\html@mathml{\\textcircled{\\scriptsize R}}{\\char`®}");D("ℬ","\\mathscr{B}");D("ℰ","\\mathscr{E}");D("ℱ","\\mathscr{F}");D("ℋ","\\mathscr{H}");D("ℐ","\\mathscr{I}");D("ℒ","\\mathscr{L}");D("ℳ","\\mathscr{M}");D("ℛ","\\mathscr{R}");D("ℭ","\\mathfrak{C}");D("ℌ","\\mathfrak{H}");D("ℨ","\\mathfrak{Z}");D("\\Bbbk","\\Bbb{k}");D("\\llap","\\mathllap{\\textrm{#1}}");D("\\rlap","\\mathrlap{\\textrm{#1}}");D("\\clap","\\mathclap{\\textrm{#1}}");D("\\mathstrut","\\vphantom{(}");D("\\underbar","\\underline{\\text{#1}}");D("\\not",'\\html@mathml{\\mathrel{\\mathrlap\\@not}\\nobreak}{\\char"338}');D("\\neq","\\html@mathml{\\mathrel{\\not=}}{\\mathrel{\\char`≠}}");D("\\ne","\\neq");D("≠","\\neq");D("\\notin","\\html@mathml{\\mathrel{{\\in}\\mathllap{/\\mskip1mu}}}{\\mathrel{\\char`∉}}");D("∉","\\notin");D("≘","\\html@mathml{\\mathrel{=\\kern{-1em}\\raisebox{0.4em}{$\\scriptsize\\frown$}}}{\\mathrel{\\char`≘}}");D("≙","\\html@mathml{\\stackrel{\\tiny\\wedge}{=}}{\\mathrel{\\char`≘}}");D("≚","\\html@mathml{\\stackrel{\\tiny\\vee}{=}}{\\mathrel{\\char`≚}}");D("≛","\\html@mathml{\\stackrel{\\scriptsize\\star}{=}}{\\mathrel{\\char`≛}}");D("≝","\\html@mathml{\\stackrel{\\tiny\\mathrm{def}}{=}}{\\mathrel{\\char`≝}}");D("≞","\\html@mathml{\\stackrel{\\tiny\\mathrm{m}}{=}}{\\mathrel{\\char`≞}}");D("≟","\\html@mathml{\\stackrel{\\tiny?}{=}}{\\mathrel{\\char`≟}}");D("⟂","\\perp");D("‼","\\mathclose{!\\mkern-0.8mu!}");D("∌","\\notni");D("⌜","\\ulcorner");D("⌝","\\urcorner");D("⌞","\\llcorner");D("⌟","\\lrcorner");D("©","\\copyright");D("®","\\textregistered");D("\\ulcorner",'\\html@mathml{\\@ulcorner}{\\mathop{\\char"231c}}');D("\\urcorner",'\\html@mathml{\\@urcorner}{\\mathop{\\char"231d}}');D("\\llcorner",'\\html@mathml{\\@llcorner}{\\mathop{\\char"231e}}');D("\\lrcorner",'\\html@mathml{\\@lrcorner}{\\mathop{\\char"231f}}');D("\\vdots","{\\varvdots\\rule{0pt}{15pt}}");D("⋮","\\vdots");D("\\varGamma","\\mathit{\\Gamma}");D("\\varDelta","\\mathit{\\Delta}");D("\\varTheta","\\mathit{\\Theta}");D("\\varLambda","\\mathit{\\Lambda}");D("\\varXi","\\mathit{\\Xi}");D("\\varPi","\\mathit{\\Pi}");D("\\varSigma","\\mathit{\\Sigma}");D("\\varUpsilon","\\mathit{\\Upsilon}");D("\\varPhi","\\mathit{\\Phi}");D("\\varPsi","\\mathit{\\Psi}");D("\\varOmega","\\mathit{\\Omega}");D("\\substack","\\begin{subarray}{c}#1\\end{subarray}");D("\\colon","\\nobreak\\mskip2mu\\mathpunct{}\\mathchoice{\\mkern-3mu}{\\mkern-3mu}{}{}{:}\\mskip6mu\\relax");D("\\boxed","\\fbox{$\\displaystyle{#1}$}");D("\\iff","\\DOTSB\\;\\Longleftrightarrow\\;");D("\\implies","\\DOTSB\\;\\Longrightarrow\\;");D("\\impliedby","\\DOTSB\\;\\Longleftarrow\\;");D("\\dddot","{\\overset{\\raisebox{-0.1ex}{\\normalsize ...}}{#1}}");D("\\ddddot","{\\overset{\\raisebox{-0.1ex}{\\normalsize ....}}{#1}}");var y3={",":"\\dotsc","\\not":"\\dotsb","+":"\\dotsb","=":"\\dotsb","<":"\\dotsb",">":"\\dotsb","-":"\\dotsb","*":"\\dotsb",":":"\\dotsb","\\DOTSB":"\\dotsb","\\coprod":"\\dotsb","\\bigvee":"\\dotsb","\\bigwedge":"\\dotsb","\\biguplus":"\\dotsb","\\bigcap":"\\dotsb","\\bigcup":"\\dotsb","\\prod":"\\dotsb","\\sum":"\\dotsb","\\bigotimes":"\\dotsb","\\bigoplus":"\\dotsb","\\bigodot":"\\dotsb","\\bigsqcup":"\\dotsb","\\And":"\\dotsb","\\longrightarrow":"\\dotsb","\\Longrightarrow":"\\dotsb","\\longleftarrow":"\\dotsb","\\Longleftarrow":"\\dotsb","\\longleftrightarrow":"\\dotsb","\\Longleftrightarrow":"\\dotsb","\\mapsto":"\\dotsb","\\longmapsto":"\\dotsb","\\hookrightarrow":"\\dotsb","\\doteq":"\\dotsb","\\mathbin":"\\dotsb","\\mathrel":"\\dotsb","\\relbar":"\\dotsb","\\Relbar":"\\dotsb","\\xrightarrow":"\\dotsb","\\xleftarrow":"\\dotsb","\\DOTSI":"\\dotsi","\\int":"\\dotsi","\\oint":"\\dotsi","\\iint":"\\dotsi","\\iiint":"\\dotsi","\\iiiint":"\\dotsi","\\idotsint":"\\dotsi","\\DOTSX":"\\dotsx"},_T=new Set(["bin","rel"]);D("\\dots",function(e){var t="\\dotso",n=e.expandAfterFuture().text;return n in y3?t=y3[n]:(n.slice(0,4)==="\\not"||n in Kt.math&&_T.has(Kt.math[n].group))&&(t="\\dotsb"),t});var D1={")":!0,"]":!0,"\\rbrack":!0,"\\}":!0,"\\rbrace":!0,"\\rangle":!0,"\\rceil":!0,"\\rfloor":!0,"\\rgroup":!0,"\\rmoustache":!0,"\\right":!0,"\\bigr":!0,"\\biggr":!0,"\\Bigr":!0,"\\Biggr":!0,$:!0,";":!0,".":!0,",":!0};D("\\dotso",function(e){var t=e.future().text;return t in D1?"\\ldots\\,":"\\ldots"});D("\\dotsc",function(e){var t=e.future().text;return t in D1&&t!==","?"\\ldots\\,":"\\ldots"});D("\\cdots",function(e){var t=e.future().text;return t in D1?"\\@cdots\\,":"\\@cdots"});D("\\dotsb","\\cdots");D("\\dotsm","\\cdots");D("\\dotsi","\\!\\cdots");D("\\dotsx","\\ldots\\,");D("\\DOTSI","\\relax");D("\\DOTSB","\\relax");D("\\DOTSX","\\relax");D("\\tmspace","\\TextOrMath{\\kern#1#3}{\\mskip#1#2}\\relax");D("\\,","\\tmspace+{3mu}{.1667em}");D("\\thinspace","\\,");D("\\>","\\mskip{4mu}");D("\\:","\\tmspace+{4mu}{.2222em}");D("\\medspace","\\:");D("\\;","\\tmspace+{5mu}{.2777em}");D("\\thickspace","\\;");D("\\!","\\tmspace-{3mu}{.1667em}");D("\\negthinspace","\\!");D("\\negmedspace","\\tmspace-{4mu}{.2222em}");D("\\negthickspace","\\tmspace-{5mu}{.277em}");D("\\enspace","\\kern.5em ");D("\\enskip","\\hskip.5em\\relax");D("\\quad","\\hskip1em\\relax");D("\\qquad","\\hskip2em\\relax");D("\\tag","\\@ifstar\\tag@literal\\tag@paren");D("\\tag@paren","\\tag@literal{({#1})}");D("\\tag@literal",e=>{if(e.macros.get("\\df@tag"))throw new je("Multiple \\tag");return"\\gdef\\df@tag{\\text{#1}}"});D("\\bmod","\\mathchoice{\\mskip1mu}{\\mskip1mu}{\\mskip5mu}{\\mskip5mu}\\mathbin{\\rm mod}\\mathchoice{\\mskip1mu}{\\mskip1mu}{\\mskip5mu}{\\mskip5mu}");D("\\pod","\\allowbreak\\mathchoice{\\mkern18mu}{\\mkern8mu}{\\mkern8mu}{\\mkern8mu}(#1)");D("\\pmod","\\pod{{\\rm mod}\\mkern6mu#1}");D("\\mod","\\allowbreak\\mathchoice{\\mkern18mu}{\\mkern12mu}{\\mkern12mu}{\\mkern12mu}{\\rm mod}\\,\\,#1");D("\\newline","\\\\\\relax");D("\\TeX","\\textrm{\\html@mathml{T\\kern-.1667em\\raisebox{-.5ex}{E}\\kern-.125emX}{TeX}}");var Av=Me(Za["Main-Regular"][84][1]-.7*Za["Main-Regular"][65][1]);D("\\LaTeX","\\textrm{\\html@mathml{"+("L\\kern-.36em\\raisebox{"+Av+"}{\\scriptstyle A}")+"\\kern-.15em\\TeX}{LaTeX}}");D("\\KaTeX","\\textrm{\\html@mathml{"+("K\\kern-.17em\\raisebox{"+Av+"}{\\scriptstyle A}")+"\\kern-.15em\\TeX}{KaTeX}}");D("\\hspace","\\@ifstar\\@hspacer\\@hspace");D("\\@hspace","\\hskip #1\\relax");D("\\@hspacer","\\rule{0pt}{0pt}\\hskip #1\\relax");D("\\ordinarycolon",":");D("\\vcentcolon","\\mathrel{\\mathop\\ordinarycolon}");D("\\dblcolon",'\\html@mathml{\\mathrel{\\vcentcolon\\mathrel{\\mkern-.9mu}\\vcentcolon}}{\\mathop{\\char"2237}}');D("\\coloneqq",'\\html@mathml{\\mathrel{\\vcentcolon\\mathrel{\\mkern-1.2mu}=}}{\\mathop{\\char"2254}}');D("\\Coloneqq",'\\html@mathml{\\mathrel{\\dblcolon\\mathrel{\\mkern-1.2mu}=}}{\\mathop{\\char"2237\\char"3d}}');D("\\coloneq",'\\html@mathml{\\mathrel{\\vcentcolon\\mathrel{\\mkern-1.2mu}\\mathrel{-}}}{\\mathop{\\char"3a\\char"2212}}');D("\\Coloneq",'\\html@mathml{\\mathrel{\\dblcolon\\mathrel{\\mkern-1.2mu}\\mathrel{-}}}{\\mathop{\\char"2237\\char"2212}}');D("\\eqqcolon",'\\html@mathml{\\mathrel{=\\mathrel{\\mkern-1.2mu}\\vcentcolon}}{\\mathop{\\char"2255}}');D("\\Eqqcolon",'\\html@mathml{\\mathrel{=\\mathrel{\\mkern-1.2mu}\\dblcolon}}{\\mathop{\\char"3d\\char"2237}}');D("\\eqcolon",'\\html@mathml{\\mathrel{\\mathrel{-}\\mathrel{\\mkern-1.2mu}\\vcentcolon}}{\\mathop{\\char"2239}}');D("\\Eqcolon",'\\html@mathml{\\mathrel{\\mathrel{-}\\mathrel{\\mkern-1.2mu}\\dblcolon}}{\\mathop{\\char"2212\\char"2237}}');D("\\colonapprox",'\\html@mathml{\\mathrel{\\vcentcolon\\mathrel{\\mkern-1.2mu}\\approx}}{\\mathop{\\char"3a\\char"2248}}');D("\\Colonapprox",'\\html@mathml{\\mathrel{\\dblcolon\\mathrel{\\mkern-1.2mu}\\approx}}{\\mathop{\\char"2237\\char"2248}}');D("\\colonsim",'\\html@mathml{\\mathrel{\\vcentcolon\\mathrel{\\mkern-1.2mu}\\sim}}{\\mathop{\\char"3a\\char"223c}}');D("\\Colonsim",'\\html@mathml{\\mathrel{\\dblcolon\\mathrel{\\mkern-1.2mu}\\sim}}{\\mathop{\\char"2237\\char"223c}}');D("∷","\\dblcolon");D("∹","\\eqcolon");D("≔","\\coloneqq");D("≕","\\eqqcolon");D("⩴","\\Coloneqq");D("\\ratio","\\vcentcolon");D("\\coloncolon","\\dblcolon");D("\\colonequals","\\coloneqq");D("\\coloncolonequals","\\Coloneqq");D("\\equalscolon","\\eqqcolon");D("\\equalscoloncolon","\\Eqqcolon");D("\\colonminus","\\coloneq");D("\\coloncolonminus","\\Coloneq");D("\\minuscolon","\\eqcolon");D("\\minuscoloncolon","\\Eqcolon");D("\\coloncolonapprox","\\Colonapprox");D("\\coloncolonsim","\\Colonsim");D("\\simcolon","\\mathrel{\\sim\\mathrel{\\mkern-1.2mu}\\vcentcolon}");D("\\simcoloncolon","\\mathrel{\\sim\\mathrel{\\mkern-1.2mu}\\dblcolon}");D("\\approxcolon","\\mathrel{\\approx\\mathrel{\\mkern-1.2mu}\\vcentcolon}");D("\\approxcoloncolon","\\mathrel{\\approx\\mathrel{\\mkern-1.2mu}\\dblcolon}");D("\\notni","\\html@mathml{\\not\\ni}{\\mathrel{\\char`∌}}");D("\\limsup","\\DOTSB\\operatorname*{lim\\,sup}");D("\\liminf","\\DOTSB\\operatorname*{lim\\,inf}");D("\\injlim","\\DOTSB\\operatorname*{inj\\,lim}");D("\\projlim","\\DOTSB\\operatorname*{proj\\,lim}");D("\\varlimsup","\\DOTSB\\operatorname*{\\overline{lim}}");D("\\varliminf","\\DOTSB\\operatorname*{\\underline{lim}}");D("\\varinjlim","\\DOTSB\\operatorname*{\\underrightarrow{lim}}");D("\\varprojlim","\\DOTSB\\operatorname*{\\underleftarrow{lim}}");D("\\gvertneqq","\\html@mathml{\\@gvertneqq}{≩}");D("\\lvertneqq","\\html@mathml{\\@lvertneqq}{≨}");D("\\ngeqq","\\html@mathml{\\@ngeqq}{≱}");D("\\ngeqslant","\\html@mathml{\\@ngeqslant}{≱}");D("\\nleqq","\\html@mathml{\\@nleqq}{≰}");D("\\nleqslant","\\html@mathml{\\@nleqslant}{≰}");D("\\nshortmid","\\html@mathml{\\@nshortmid}{∤}");D("\\nshortparallel","\\html@mathml{\\@nshortparallel}{∦}");D("\\nsubseteqq","\\html@mathml{\\@nsubseteqq}{⊈}");D("\\nsupseteqq","\\html@mathml{\\@nsupseteqq}{⊉}");D("\\varsubsetneq","\\html@mathml{\\@varsubsetneq}{⊊}");D("\\varsubsetneqq","\\html@mathml{\\@varsubsetneqq}{⫋}");D("\\varsupsetneq","\\html@mathml{\\@varsupsetneq}{⊋}");D("\\varsupsetneqq","\\html@mathml{\\@varsupsetneqq}{⫌}");D("\\imath","\\html@mathml{\\@imath}{ı}");D("\\jmath","\\html@mathml{\\@jmath}{ȷ}");D("\\llbracket","\\html@mathml{\\mathopen{[\\mkern-3.2mu[}}{\\mathopen{\\char`⟦}}");D("\\rrbracket","\\html@mathml{\\mathclose{]\\mkern-3.2mu]}}{\\mathclose{\\char`⟧}}");D("⟦","\\llbracket");D("⟧","\\rrbracket");D("\\lBrace","\\html@mathml{\\mathopen{\\{\\mkern-3.2mu[}}{\\mathopen{\\char`⦃}}");D("\\rBrace","\\html@mathml{\\mathclose{]\\mkern-3.2mu\\}}}{\\mathclose{\\char`⦄}}");D("⦃","\\lBrace");D("⦄","\\rBrace");D("\\minuso","\\mathbin{\\html@mathml{{\\mathrlap{\\mathchoice{\\kern{0.145em}}{\\kern{0.145em}}{\\kern{0.1015em}}{\\kern{0.0725em}}\\circ}{-}}}{\\char`⦵}}");D("⦵","\\minuso");D("\\darr","\\downarrow");D("\\dArr","\\Downarrow");D("\\Darr","\\Downarrow");D("\\lang","\\langle");D("\\rang","\\rangle");D("\\uarr","\\uparrow");D("\\uArr","\\Uparrow");D("\\Uarr","\\Uparrow");D("\\N","\\mathbb{N}");D("\\R","\\mathbb{R}");D("\\Z","\\mathbb{Z}");D("\\alef","\\aleph");D("\\alefsym","\\aleph");D("\\Alpha","\\mathrm{A}");D("\\Beta","\\mathrm{B}");D("\\bull","\\bullet");D("\\Chi","\\mathrm{X}");D("\\clubs","\\clubsuit");D("\\cnums","\\mathbb{C}");D("\\Complex","\\mathbb{C}");D("\\Dagger","\\ddagger");D("\\diamonds","\\diamondsuit");D("\\empty","\\emptyset");D("\\Epsilon","\\mathrm{E}");D("\\Eta","\\mathrm{H}");D("\\exist","\\exists");D("\\harr","\\leftrightarrow");D("\\hArr","\\Leftrightarrow");D("\\Harr","\\Leftrightarrow");D("\\hearts","\\heartsuit");D("\\image","\\Im");D("\\infin","\\infty");D("\\Iota","\\mathrm{I}");D("\\isin","\\in");D("\\Kappa","\\mathrm{K}");D("\\larr","\\leftarrow");D("\\lArr","\\Leftarrow");D("\\Larr","\\Leftarrow");D("\\lrarr","\\leftrightarrow");D("\\lrArr","\\Leftrightarrow");D("\\Lrarr","\\Leftrightarrow");D("\\Mu","\\mathrm{M}");D("\\natnums","\\mathbb{N}");D("\\Nu","\\mathrm{N}");D("\\Omicron","\\mathrm{O}");D("\\plusmn","\\pm");D("\\rarr","\\rightarrow");D("\\rArr","\\Rightarrow");D("\\Rarr","\\Rightarrow");D("\\real","\\Re");D("\\reals","\\mathbb{R}");D("\\Reals","\\mathbb{R}");D("\\Rho","\\mathrm{P}");D("\\sdot","\\cdot");D("\\sect","\\S");D("\\spades","\\spadesuit");D("\\sub","\\subset");D("\\sube","\\subseteq");D("\\supe","\\supseteq");D("\\Tau","\\mathrm{T}");D("\\thetasym","\\vartheta");D("\\weierp","\\wp");D("\\Zeta","\\mathrm{Z}");D("\\argmin","\\DOTSB\\operatorname*{arg\\,min}");D("\\argmax","\\DOTSB\\operatorname*{arg\\,max}");D("\\plim","\\DOTSB\\mathop{\\operatorname{plim}}\\limits");D("\\bra","\\mathinner{\\langle{#1}|}");D("\\ket","\\mathinner{|{#1}\\rangle}");D("\\braket","\\mathinner{\\langle{#1}\\rangle}");D("\\Bra","\\left\\langle#1\\right|");D("\\Ket","\\left|#1\\right\\rangle");var Ev=e=>t=>{var n=t.consumeArg().tokens,i=t.consumeArg().tokens,l=t.consumeArg().tokens,o=t.consumeArg().tokens,c=t.macros.get("|"),f=t.macros.get("\\|");t.macros.beginGroup();var h=v=>k=>{e&&(k.macros.set("|",c),l.length&&k.macros.set("\\|",f));var w=v;if(!v&&l.length){var T=k.future();T.text==="|"&&(k.popToken(),w=!0)}return{tokens:w?l:i,numArgs:0}};t.macros.set("|",h(!1)),l.length&&t.macros.set("\\|",h(!0));var m=t.consumeArg().tokens,y=t.expandTokens([...o,...m,...n]);return t.macros.endGroup(),{tokens:y.reverse(),numArgs:0}};D("\\bra@ket",Ev(!1));D("\\bra@set",Ev(!0));D("\\Braket","\\bra@ket{\\left\\langle}{\\,\\middle\\vert\\,}{\\,\\middle\\vert\\,}{\\right\\rangle}");D("\\Set","\\bra@set{\\left\\{\\:}{\\;\\middle\\vert\\;}{\\;\\middle\\Vert\\;}{\\:\\right\\}}");D("\\set","\\bra@set{\\{\\,}{\\mid}{}{\\,\\}}");D("\\angln","{\\angl n}");D("\\blue","\\textcolor{##6495ed}{#1}");D("\\orange","\\textcolor{##ffa500}{#1}");D("\\pink","\\textcolor{##ff00af}{#1}");D("\\red","\\textcolor{##df0030}{#1}");D("\\green","\\textcolor{##28ae7b}{#1}");D("\\gray","\\textcolor{gray}{#1}");D("\\purple","\\textcolor{##9d38bd}{#1}");D("\\blueA","\\textcolor{##ccfaff}{#1}");D("\\blueB","\\textcolor{##80f6ff}{#1}");D("\\blueC","\\textcolor{##63d9ea}{#1}");D("\\blueD","\\textcolor{##11accd}{#1}");D("\\blueE","\\textcolor{##0c7f99}{#1}");D("\\tealA","\\textcolor{##94fff5}{#1}");D("\\tealB","\\textcolor{##26edd5}{#1}");D("\\tealC","\\textcolor{##01d1c1}{#1}");D("\\tealD","\\textcolor{##01a995}{#1}");D("\\tealE","\\textcolor{##208170}{#1}");D("\\greenA","\\textcolor{##b6ffb0}{#1}");D("\\greenB","\\textcolor{##8af281}{#1}");D("\\greenC","\\textcolor{##74cf70}{#1}");D("\\greenD","\\textcolor{##1fab54}{#1}");D("\\greenE","\\textcolor{##0d923f}{#1}");D("\\goldA","\\textcolor{##ffd0a9}{#1}");D("\\goldB","\\textcolor{##ffbb71}{#1}");D("\\goldC","\\textcolor{##ff9c39}{#1}");D("\\goldD","\\textcolor{##e07d10}{#1}");D("\\goldE","\\textcolor{##a75a05}{#1}");D("\\redA","\\textcolor{##fca9a9}{#1}");D("\\redB","\\textcolor{##ff8482}{#1}");D("\\redC","\\textcolor{##f9685d}{#1}");D("\\redD","\\textcolor{##e84d39}{#1}");D("\\redE","\\textcolor{##bc2612}{#1}");D("\\maroonA","\\textcolor{##ffbde0}{#1}");D("\\maroonB","\\textcolor{##ff92c6}{#1}");D("\\maroonC","\\textcolor{##ed5fa6}{#1}");D("\\maroonD","\\textcolor{##ca337c}{#1}");D("\\maroonE","\\textcolor{##9e034e}{#1}");D("\\purpleA","\\textcolor{##ddd7ff}{#1}");D("\\purpleB","\\textcolor{##c6b9fc}{#1}");D("\\purpleC","\\textcolor{##aa87ff}{#1}");D("\\purpleD","\\textcolor{##7854ab}{#1}");D("\\purpleE","\\textcolor{##543b78}{#1}");D("\\mintA","\\textcolor{##f5f9e8}{#1}");D("\\mintB","\\textcolor{##edf2df}{#1}");D("\\mintC","\\textcolor{##e0e5cc}{#1}");D("\\grayA","\\textcolor{##f6f7f7}{#1}");D("\\grayB","\\textcolor{##f0f1f2}{#1}");D("\\grayC","\\textcolor{##e3e5e6}{#1}");D("\\grayD","\\textcolor{##d6d8da}{#1}");D("\\grayE","\\textcolor{##babec2}{#1}");D("\\grayF","\\textcolor{##888d93}{#1}");D("\\grayG","\\textcolor{##626569}{#1}");D("\\grayH","\\textcolor{##3b3e40}{#1}");D("\\grayI","\\textcolor{##21242c}{#1}");D("\\kaBlue","\\textcolor{##314453}{#1}");D("\\kaGreen","\\textcolor{##71B307}{#1}");var Nv={"^":!0,_:!0,"\\limits":!0,"\\nolimits":!0};class BT{constructor(t,n,i){this.settings=void 0,this.expansionCount=void 0,this.lexer=void 0,this.macros=void 0,this.stack=void 0,this.mode=void 0,this.settings=n,this.expansionCount=0,this.feed(t),this.macros=new RT(OT,n.macros),this.mode=i,this.stack=[]}feed(t){this.lexer=new p3(t,this.settings)}switchMode(t){this.mode=t}beginGroup(){this.macros.beginGroup()}endGroup(){this.macros.endGroup()}endGroups(){this.macros.endGroups()}future(){return this.stack.length===0&&this.pushToken(this.lexer.lex()),this.stack[this.stack.length-1]}popToken(){return this.future(),this.stack.pop()}pushToken(t){this.stack.push(t)}pushTokens(t){this.stack.push(...t)}scanArgument(t){var n,i,l;if(t){if(this.consumeSpaces(),this.future().text!=="[")return null;n=this.popToken(),{tokens:l,end:i}=this.consumeArg(["]"])}else({tokens:l,start:n,end:i}=this.consumeArg());return this.pushToken(new Or("EOF",i.loc)),this.pushTokens(l),new Or("",br.range(n,i))}consumeSpaces(){for(;;){var t=this.future();if(t.text===" ")this.stack.pop();else break}}consumeArg(t){var n=[],i=t&&t.length>0;i||this.consumeSpaces();var l=this.future(),o,c=0,f=0;do{if(o=this.popToken(),n.push(o),o.text==="{")++c;else if(o.text==="}"){if(--c,c===-1)throw new je("Extra }",o)}else if(o.text==="EOF")throw new je("Unexpected end of input in a macro argument, expected '"+(t&&i?t[f]:"}")+"'",o);if(t&&i)if((c===0||c===1&&t[f]==="{")&&o.text===t[f]){if(++f,f===t.length){n.splice(-f,f);break}}else f=0}while(c!==0||i);return l.text==="{"&&n[n.length-1].text==="}"&&(n.pop(),n.shift()),n.reverse(),{tokens:n,start:l,end:o}}consumeArgs(t,n){if(n){if(n.length!==t+1)throw new je("The length of delimiters doesn't match the number of args!");for(var i=n[0],l=0;l<i.length;l++){var o=this.popToken();if(i[l]!==o.text)throw new je("Use of the macro doesn't match its definition",o)}}for(var c=[],f=0;f<t;f++)c.push(this.consumeArg(n&&n[f+1]).tokens);return c}countExpansion(t){if(this.expansionCount+=t,this.expansionCount>this.settings.maxExpand)throw new je("Too many expansions: infinite loop or need to increase maxExpand setting")}expandOnce(t){var n=this.popToken(),i=n.text,l=n.noexpand?null:this._getExpansion(i);if(l==null||t&&l.unexpandable){if(t&&l==null&&i[0]==="\\"&&!this.isDefined(i))throw new je("Undefined control sequence: "+i);return this.pushToken(n),!1}this.countExpansion(1);var o=l.tokens,c=this.consumeArgs(l.numArgs,l.delimiters);if(l.numArgs){o=o.slice();for(var f=o.length-1;f>=0;--f){var h=o[f];if(h.text==="#"){if(f===0)throw new je("Incomplete placeholder at end of macro body",h);if(h=o[--f],h.text==="#")o.splice(f+1,1);else if(/^[1-9]$/.test(h.text))o.splice(f,2,...c[+h.text-1]);else throw new je("Not a valid argument number",h)}}}return this.pushTokens(o),o.length}expandAfterFuture(){return this.expandOnce(),this.future()}expandNextToken(){for(;;)if(this.expandOnce()===!1){var t=this.stack.pop();return t.treatAsRelax&&(t.text="\\relax"),t}}expandMacro(t){return this.macros.has(t)?this.expandTokens([new Or(t)]):void 0}expandTokens(t){var n=[],i=this.stack.length;for(this.pushTokens(t);this.stack.length>i;)if(this.expandOnce(!0)===!1){var l=this.stack.pop();l.treatAsRelax&&(l.noexpand=!1,l.treatAsRelax=!1),n.push(l)}return this.countExpansion(n.length),n}expandMacroAsText(t){var n=this.expandMacro(t);return n&&n.map(i=>i.text).join("")}_getExpansion(t){var n=this.macros.get(t);if(n==null)return n;if(t.length===1){var i=this.lexer.catcodes[t];if(i!=null&&i!==13)return}var l=typeof n=="function"?n(this):n;if(typeof l=="string"){var o=0;if(l.includes("#"))for(var c=l.replace(/##/g,"");c.includes("#"+(o+1));)++o;for(var f=new p3(l,this.settings),h=[],m=f.lex();m.text!=="EOF";)h.push(m),m=f.lex();h.reverse();var y={tokens:h,numArgs:o};return y}return l}isDefined(t){return this.macros.has(t)||Fl.hasOwnProperty(t)||Kt.math.hasOwnProperty(t)||Kt.text.hasOwnProperty(t)||Nv.hasOwnProperty(t)}isExpandable(t){var n=this.macros.get(t);return n!=null?typeof n=="string"||typeof n=="function"||!n.unexpandable:Fl.hasOwnProperty(t)&&!Fl[t].primitive}}var v3=/^[₊₋₌₍₎₀₁₂₃₄₅₆₇₈₉ₐₑₕᵢⱼₖₗₘₙₒₚᵣₛₜᵤᵥₓᵦᵧᵨᵩᵪ]/,zd=Object.freeze({"₊":"+","₋":"-","₌":"=","₍":"(","₎":")","₀":"0","₁":"1","₂":"2","₃":"3","₄":"4","₅":"5","₆":"6","₇":"7","₈":"8","₉":"9","ₐ":"a","ₑ":"e","ₕ":"h","ᵢ":"i","ⱼ":"j","ₖ":"k","ₗ":"l","ₘ":"m","ₙ":"n","ₒ":"o","ₚ":"p","ᵣ":"r","ₛ":"s","ₜ":"t","ᵤ":"u","ᵥ":"v","ₓ":"x","ᵦ":"β","ᵧ":"γ","ᵨ":"ρ","ᵩ":"ϕ","ᵪ":"χ","⁺":"+","⁻":"-","⁼":"=","⁽":"(","⁾":")","⁰":"0","¹":"1","²":"2","³":"3","⁴":"4","⁵":"5","⁶":"6","⁷":"7","⁸":"8","⁹":"9","ᴬ":"A","ᴮ":"B","ᴰ":"D","ᴱ":"E","ᴳ":"G","ᴴ":"H","ᴵ":"I","ᴶ":"J","ᴷ":"K","ᴸ":"L","ᴹ":"M","ᴺ":"N","ᴼ":"O","ᴾ":"P","ᴿ":"R","ᵀ":"T","ᵁ":"U","ⱽ":"V","ᵂ":"W","ᵃ":"a","ᵇ":"b","ᶜ":"c","ᵈ":"d","ᵉ":"e","ᶠ":"f","ᵍ":"g",ʰ:"h","ⁱ":"i",ʲ:"j","ᵏ":"k",ˡ:"l","ᵐ":"m",ⁿ:"n","ᵒ":"o","ᵖ":"p",ʳ:"r",ˢ:"s","ᵗ":"t","ᵘ":"u","ᵛ":"v",ʷ:"w",ˣ:"x",ʸ:"y","ᶻ":"z","ᵝ":"β","ᵞ":"γ","ᵟ":"δ","ᵠ":"ϕ","ᵡ":"χ","ᶿ":"θ"}),Gm={"́":{text:"\\'",math:"\\acute"},"̀":{text:"\\`",math:"\\grave"},"̈":{text:'\\"',math:"\\ddot"},"̃":{text:"\\~",math:"\\tilde"},"̄":{text:"\\=",math:"\\bar"},"̆":{text:"\\u",math:"\\breve"},"̌":{text:"\\v",math:"\\check"},"̂":{text:"\\^",math:"\\hat"},"̇":{text:"\\.",math:"\\dot"},"̊":{text:"\\r",math:"\\mathring"},"̋":{text:"\\H"},"̧":{text:"\\c"}},x3={á:"á",à:"à",ä:"ä",ǟ:"ǟ",ã:"ã",ā:"ā",ă:"ă",ắ:"ắ",ằ:"ằ",ẵ:"ẵ",ǎ:"ǎ",â:"â",ấ:"ấ",ầ:"ầ",ẫ:"ẫ",ȧ:"ȧ",ǡ:"ǡ",å:"å",ǻ:"ǻ",ḃ:"ḃ",ć:"ć",ḉ:"ḉ",č:"č",ĉ:"ĉ",ċ:"ċ",ç:"ç",ď:"ď",ḋ:"ḋ",ḑ:"ḑ",é:"é",è:"è",ë:"ë",ẽ:"ẽ",ē:"ē",ḗ:"ḗ",ḕ:"ḕ",ĕ:"ĕ",ḝ:"ḝ",ě:"ě",ê:"ê",ế:"ế",ề:"ề",ễ:"ễ",ė:"ė",ȩ:"ȩ",ḟ:"ḟ",ǵ:"ǵ",ḡ:"ḡ",ğ:"ğ",ǧ:"ǧ",ĝ:"ĝ",ġ:"ġ",ģ:"ģ",ḧ:"ḧ",ȟ:"ȟ",ĥ:"ĥ",ḣ:"ḣ",ḩ:"ḩ",í:"í",ì:"ì",ï:"ï",ḯ:"ḯ",ĩ:"ĩ",ī:"ī",ĭ:"ĭ",ǐ:"ǐ",î:"î",ǰ:"ǰ",ĵ:"ĵ",ḱ:"ḱ",ǩ:"ǩ",ķ:"ķ",ĺ:"ĺ",ľ:"ľ",ļ:"ļ",ḿ:"ḿ",ṁ:"ṁ",ń:"ń",ǹ:"ǹ",ñ:"ñ",ň:"ň",ṅ:"ṅ",ņ:"ņ",ó:"ó",ò:"ò",ö:"ö",ȫ:"ȫ",õ:"õ",ṍ:"ṍ",ṏ:"ṏ",ȭ:"ȭ",ō:"ō",ṓ:"ṓ",ṑ:"ṑ",ŏ:"ŏ",ǒ:"ǒ",ô:"ô",ố:"ố",ồ:"ồ",ỗ:"ỗ",ȯ:"ȯ",ȱ:"ȱ",ő:"ő",ṕ:"ṕ",ṗ:"ṗ",ŕ:"ŕ",ř:"ř",ṙ:"ṙ",ŗ:"ŗ",ś:"ś",ṥ:"ṥ",š:"š",ṧ:"ṧ",ŝ:"ŝ",ṡ:"ṡ",ş:"ş",ẗ:"ẗ",ť:"ť",ṫ:"ṫ",ţ:"ţ",ú:"ú",ù:"ù",ü:"ü",ǘ:"ǘ",ǜ:"ǜ",ǖ:"ǖ",ǚ:"ǚ",ũ:"ũ",ṹ:"ṹ",ū:"ū",ṻ:"ṻ",ŭ:"ŭ",ǔ:"ǔ",û:"û",ů:"ů",ű:"ű",ṽ:"ṽ",ẃ:"ẃ",ẁ:"ẁ",ẅ:"ẅ",ŵ:"ŵ",ẇ:"ẇ",ẘ:"ẘ",ẍ:"ẍ",ẋ:"ẋ",ý:"ý",ỳ:"ỳ",ÿ:"ÿ",ỹ:"ỹ",ȳ:"ȳ",ŷ:"ŷ",ẏ:"ẏ",ẙ:"ẙ",ź:"ź",ž:"ž",ẑ:"ẑ",ż:"ż",Á:"Á",À:"À",Ä:"Ä",Ǟ:"Ǟ",Ã:"Ã",Ā:"Ā",Ă:"Ă",Ắ:"Ắ",Ằ:"Ằ",Ẵ:"Ẵ",Ǎ:"Ǎ",Â:"Â",Ấ:"Ấ",Ầ:"Ầ",Ẫ:"Ẫ",Ȧ:"Ȧ",Ǡ:"Ǡ",Å:"Å",Ǻ:"Ǻ",Ḃ:"Ḃ",Ć:"Ć",Ḉ:"Ḉ",Č:"Č",Ĉ:"Ĉ",Ċ:"Ċ",Ç:"Ç",Ď:"Ď",Ḋ:"Ḋ",Ḑ:"Ḑ",É:"É",È:"È",Ë:"Ë",Ẽ:"Ẽ",Ē:"Ē",Ḗ:"Ḗ",Ḕ:"Ḕ",Ĕ:"Ĕ",Ḝ:"Ḝ",Ě:"Ě",Ê:"Ê",Ế:"Ế",Ề:"Ề",Ễ:"Ễ",Ė:"Ė",Ȩ:"Ȩ",Ḟ:"Ḟ",Ǵ:"Ǵ",Ḡ:"Ḡ",Ğ:"Ğ",Ǧ:"Ǧ",Ĝ:"Ĝ",Ġ:"Ġ",Ģ:"Ģ",Ḧ:"Ḧ",Ȟ:"Ȟ",Ĥ:"Ĥ",Ḣ:"Ḣ",Ḩ:"Ḩ",Í:"Í",Ì:"Ì",Ï:"Ï",Ḯ:"Ḯ",Ĩ:"Ĩ",Ī:"Ī",Ĭ:"Ĭ",Ǐ:"Ǐ",Î:"Î",İ:"İ",Ĵ:"Ĵ",Ḱ:"Ḱ",Ǩ:"Ǩ",Ķ:"Ķ",Ĺ:"Ĺ",Ľ:"Ľ",Ļ:"Ļ",Ḿ:"Ḿ",Ṁ:"Ṁ",Ń:"Ń",Ǹ:"Ǹ",Ñ:"Ñ",Ň:"Ň",Ṅ:"Ṅ",Ņ:"Ņ",Ó:"Ó",Ò:"Ò",Ö:"Ö",Ȫ:"Ȫ",Õ:"Õ",Ṍ:"Ṍ",Ṏ:"Ṏ",Ȭ:"Ȭ",Ō:"Ō",Ṓ:"Ṓ",Ṑ:"Ṑ",Ŏ:"Ŏ",Ǒ:"Ǒ",Ô:"Ô",Ố:"Ố",Ồ:"Ồ",Ỗ:"Ỗ",Ȯ:"Ȯ",Ȱ:"Ȱ",Ő:"Ő",Ṕ:"Ṕ",Ṗ:"Ṗ",Ŕ:"Ŕ",Ř:"Ř",Ṙ:"Ṙ",Ŗ:"Ŗ",Ś:"Ś",Ṥ:"Ṥ",Š:"Š",Ṧ:"Ṧ",Ŝ:"Ŝ",Ṡ:"Ṡ",Ş:"Ş",Ť:"Ť",Ṫ:"Ṫ",Ţ:"Ţ",Ú:"Ú",Ù:"Ù",Ü:"Ü",Ǘ:"Ǘ",Ǜ:"Ǜ",Ǖ:"Ǖ",Ǚ:"Ǚ",Ũ:"Ũ",Ṹ:"Ṹ",Ū:"Ū",Ṻ:"Ṻ",Ŭ:"Ŭ",Ǔ:"Ǔ",Û:"Û",Ů:"Ů",Ű:"Ű",Ṽ:"Ṽ",Ẃ:"Ẃ",Ẁ:"Ẁ",Ẅ:"Ẅ",Ŵ:"Ŵ",Ẇ:"Ẇ",Ẍ:"Ẍ",Ẋ:"Ẋ",Ý:"Ý",Ỳ:"Ỳ",Ÿ:"Ÿ",Ỹ:"Ỹ",Ȳ:"Ȳ",Ŷ:"Ŷ",Ẏ:"Ẏ",Ź:"Ź",Ž:"Ž",Ẑ:"Ẑ",Ż:"Ż",ά:"ά",ὰ:"ὰ",ᾱ:"ᾱ",ᾰ:"ᾰ",έ:"έ",ὲ:"ὲ",ή:"ή",ὴ:"ὴ",ί:"ί",ὶ:"ὶ",ϊ:"ϊ",ΐ:"ΐ",ῒ:"ῒ",ῑ:"ῑ",ῐ:"ῐ",ό:"ό",ὸ:"ὸ",ύ:"ύ",ὺ:"ὺ",ϋ:"ϋ",ΰ:"ΰ",ῢ:"ῢ",ῡ:"ῡ",ῠ:"ῠ",ώ:"ώ",ὼ:"ὼ",Ύ:"Ύ",Ὺ:"Ὺ",Ϋ:"Ϋ",Ῡ:"Ῡ",Ῠ:"Ῠ",Ώ:"Ώ",Ὼ:"Ὼ"};class Tf{constructor(t,n){this.mode=void 0,this.gullet=void 0,this.settings=void 0,this.leftrightDepth=void 0,this.nextToken=void 0,this.mode="math",this.gullet=new BT(t,n,this.mode),this.settings=n,this.leftrightDepth=0,this.nextToken=null}expect(t,n){if(n===void 0&&(n=!0),this.fetch().text!==t)throw new je("Expected '"+t+"', got '"+this.fetch().text+"'",this.fetch());n&&this.consume()}consume(){this.nextToken=null}fetch(){return this.nextToken==null&&(this.nextToken=this.gullet.expandNextToken()),this.nextToken}switchMode(t){this.mode=t,this.gullet.switchMode(t)}parse(){this.settings.globalGroup||this.gullet.beginGroup(),this.settings.colorIsTextColor&&this.gullet.macros.set("\\color","\\textcolor");try{var t=this.parseExpression(!1);return this.expect("EOF"),this.settings.globalGroup||this.gullet.endGroup(),t}finally{this.gullet.endGroups()}}subparse(t){var n=this.nextToken;this.consume(),this.gullet.pushToken(new Or("}")),this.gullet.pushTokens(t);var i=this.parseExpression(!1);return this.expect("}"),this.nextToken=n,i}parseExpression(t,n){for(var i=[];;){this.mode==="math"&&this.consumeSpaces();var l=this.fetch();if(Tf.endOfExpression.has(l.text)||n&&l.text===n||t&&Fl[l.text]&&Fl[l.text].infix)break;var o=this.parseAtom(n);if(o){if(o.type==="internal")continue}else break;i.push(o)}return this.mode==="text"&&this.formLigatures(i),this.handleInfixNodes(i)}handleInfixNodes(t){for(var n=-1,i,l=0;l<t.length;l++){var o=t[l];if(o.type==="infix"){if(n!==-1)throw new je("only one infix operator per group",o.token);n=l,i=o.replaceWith}}if(n!==-1&&i){var c,f,h=t.slice(0,n),m=t.slice(n+1);h.length===1&&h[0].type==="ordgroup"?c=h[0]:c={type:"ordgroup",mode:this.mode,body:h},m.length===1&&m[0].type==="ordgroup"?f=m[0]:f={type:"ordgroup",mode:this.mode,body:m};var y;return i==="\\\\abovefrac"?y=this.callFunction(i,[c,t[n],f],[]):y=this.callFunction(i,[c,f],[]),[y]}else return t}handleSupSubscript(t){var n=this.fetch(),i=n.text;this.consume(),this.consumeSpaces();var l;do{var o;l=this.parseGroup(t)}while(((o=l)==null?void 0:o.type)==="internal");if(!l)throw new je("Expected group after '"+i+"'",n);return l}formatUnsupportedCmd(t){for(var n=[],i=0;i<t.length;i++)n.push({type:"textord",mode:"text",text:t[i]});var l={type:"text",mode:this.mode,body:n},o={type:"color",mode:this.mode,color:this.settings.errorColor,body:[l]};return o}parseAtom(t){var n=this.parseGroup("atom",t);if((n==null?void 0:n.type)==="internal"||this.mode==="text")return n;for(var i,l;;){this.consumeSpaces();var o=this.fetch();if(o.text==="\\limits"||o.text==="\\nolimits"){if(n&&n.type==="op"){var c=o.text==="\\limits";n.limits=c,n.alwaysHandleSupSub=!0}else if(n&&n.type==="operatorname")n.alwaysHandleSupSub&&(n.limits=o.text==="\\limits");else throw new je("Limit controls must follow a math operator",o);this.consume()}else if(o.text==="^"){if(i)throw new je("Double superscript",o);i=this.handleSupSubscript("superscript")}else if(o.text==="_"){if(l)throw new je("Double subscript",o);l=this.handleSupSubscript("subscript")}else if(o.text==="'"){if(i)throw new je("Double superscript",o);var f={type:"textord",mode:this.mode,text:"\\prime"},h=[f];for(this.consume();this.fetch().text==="'";)h.push(f),this.consume();this.fetch().text==="^"&&h.push(this.handleSupSubscript("superscript")),i={type:"ordgroup",mode:this.mode,body:h}}else if(zd[o.text]){var m=v3.test(o.text),y=[];for(y.push(new Or(zd[o.text])),this.consume();;){var v=this.fetch().text;if(!zd[v]||v3.test(v)!==m)break;y.unshift(new Or(zd[v])),this.consume()}var k=this.subparse(y);m?l={type:"ordgroup",mode:"math",body:k}:i={type:"ordgroup",mode:"math",body:k}}else break}return i||l?{type:"supsub",mode:this.mode,base:n,sup:i,sub:l}:n}parseFunction(t,n){var i=this.fetch(),l=i.text,o=Fl[l];if(!o)return null;if(this.consume(),n&&n!=="atom"&&!o.allowedInArgument)throw new je("Got function '"+l+"' with no arguments"+(n?" as "+n:""),i);if(this.mode==="text"&&!o.allowedInText)throw new je("Can't use function '"+l+"' in text mode",i);if(this.mode==="math"&&o.allowedInMath===!1)throw new je("Can't use function '"+l+"' in math mode",i);var{args:c,optArgs:f}=this.parseArguments(l,o);return this.callFunction(l,c,f,i,t)}callFunction(t,n,i,l,o){var c={funcName:t,parser:this,token:l,breakOnTokenText:o},f=Fl[t];if(f&&f.handler)return f.handler(c,n,i);throw new je("No function handler for "+t)}parseArguments(t,n){var i=n.numArgs+n.numOptionalArgs;if(i===0)return{args:[],optArgs:[]};for(var l=[],o=[],c=0;c<i;c++){var f=n.argTypes&&n.argTypes[c],h=c<n.numOptionalArgs;("primitive"in n&&n.primitive&&f==null||n.type==="sqrt"&&c===1&&o[0]==null)&&(f="primitive");var m=this.parseGroupOfType("argument to '"+t+"'",f,h);if(h)o.push(m);else if(m!=null)l.push(m);else throw new je("Null argument, please report this as a bug")}return{args:l,optArgs:o}}parseGroupOfType(t,n,i){switch(n){case"color":return this.parseColorGroup(i);case"size":return this.parseSizeGroup(i);case"url":return this.parseUrlGroup(i);case"math":case"text":return this.parseArgumentGroup(i,n);case"hbox":{var l=this.parseArgumentGroup(i,"text");return l!=null?{type:"styling",mode:l.mode,body:[l],style:"text",resetFont:!0}:null}case"raw":{var o=this.parseStringGroup("raw",i);return o!=null?{type:"raw",mode:"text",string:o.text}:null}case"primitive":{if(i)throw new je("A primitive argument cannot be optional");var c=this.parseGroup(t);if(c==null)throw new je("Expected group as "+t,this.fetch());return c}case"original":case null:case void 0:return this.parseArgumentGroup(i);default:throw new je("Unknown group type as "+t,this.fetch())}}consumeSpaces(){for(;this.fetch().text===" ";)this.consume()}parseStringGroup(t,n){var i=this.gullet.scanArgument(n);if(i==null)return null;for(var l="",o;(o=this.fetch()).text!=="EOF";)l+=o.text,this.consume();return this.consume(),i.text=l,i}parseRegexGroup(t,n){for(var i=this.fetch(),l=i,o="",c;(c=this.fetch()).text!=="EOF"&&t.test(o+c.text);)l=c,o+=l.text,this.consume();if(o==="")throw new je("Invalid "+n+": '"+i.text+"'",i);return i.range(l,o)}parseColorGroup(t){var n=this.parseStringGroup("color",t);if(n==null)return null;var i=/^(#[a-f0-9]{3,4}|#[a-f0-9]{6}|#[a-f0-9]{8}|[a-f0-9]{6}|[a-z]+)$/i.exec(n.text);if(!i)throw new je("Invalid color: '"+n.text+"'",n);var l=i[0];return/^[0-9a-f]{6}$/i.test(l)&&(l="#"+l),{type:"color-token",mode:this.mode,color:l}}parseSizeGroup(t){var n,i=!1;if(this.gullet.consumeSpaces(),!t&&this.gullet.future().text!=="{"?n=this.parseRegexGroup(/^[-+]? *(?:$|\d+|\d+\.\d*|\.\d*) *[a-z]{0,2} *$/,"size"):n=this.parseStringGroup("size",t),!n)return null;!t&&n.text.length===0&&(n.text="0pt",i=!0);var l=/([-+]?) *(\d+(?:\.\d*)?|\.\d+) *([a-z]{2})/.exec(n.text);if(!l)throw new je("Invalid size: '"+n.text+"'",n);var o={number:+(l[1]+l[2]),unit:l[3]};if(!B6(o))throw new je("Invalid unit: '"+o.unit+"'",n);return{type:"size",mode:this.mode,value:o,isBlank:i}}parseUrlGroup(t){this.gullet.lexer.setCatcode("%",13),this.gullet.lexer.setCatcode("~",12);var n=this.parseStringGroup("url",t);if(this.gullet.lexer.setCatcode("%",14),this.gullet.lexer.setCatcode("~",13),n==null)return null;var i=n.text.replace(/\\([#$%&~_^{}])/g,"$1");return{type:"url",mode:this.mode,url:i}}parseArgumentGroup(t,n){var i=this.gullet.scanArgument(t);if(i==null)return null;var l=this.mode;n&&this.switchMode(n),this.gullet.beginGroup();var o=this.parseExpression(!1,"EOF");this.expect("EOF"),this.gullet.endGroup();var c={type:"ordgroup",mode:this.mode,loc:i.loc,body:o};return n&&this.switchMode(l),c}parseGroup(t,n){var i=this.fetch(),l=i.text,o;if(l==="{"||l==="\\begingroup"){this.consume();var c=l==="{"?"}":"\\endgroup";this.gullet.beginGroup();var f=this.parseExpression(!1,c),h=this.fetch();this.expect(c),this.gullet.endGroup(),o={type:"ordgroup",mode:this.mode,loc:br.range(i,h),body:f,semisimple:l==="\\begingroup"||void 0}}else if(o=this.parseFunction(n,t)||this.parseSymbol(),o==null&&l[0]==="\\"&&!Nv.hasOwnProperty(l)){if(this.settings.throwOnError)throw new je("Undefined control sequence: "+l,i);o=this.formatUnsupportedCmd(l),this.consume()}return o}formLigatures(t){for(var n=t.length-1,i=0;i<n;++i){var l=t[i];if(l.type==="textord"){var o=l.text,c=t[i+1];if(!(!c||c.type!=="textord")){if(o==="-"&&c.text==="-"){var f=t[i+2];i+1<n&&f&&f.type==="textord"&&f.text==="-"?(t.splice(i,3,{type:"textord",mode:"text",loc:br.range(l,f),text:"---"}),n-=2):(t.splice(i,2,{type:"textord",mode:"text",loc:br.range(l,c),text:"--"}),n-=1)}(o==="'"||o==="`")&&c.text===o&&(t.splice(i,2,{type:"textord",mode:"text",loc:br.range(l,c),text:o+o}),n-=1)}}}}parseSymbol(){var t=this.fetch(),n=t.text;if(/^\\verb[^a-zA-Z]/.test(n)){this.consume();var i=n.slice(5),l=i.charAt(0)==="*";if(l&&(i=i.slice(1)),i.length<2||i.charAt(0)!==i.slice(-1))throw new je(`\\verb assertion failed --
338
- please report what input caused this bug`);return i=i.slice(1,-1),{type:"verb",mode:"text",body:i,star:l}}x3.hasOwnProperty(n[0])&&!Kt[this.mode][n[0]]&&(this.settings.strict&&this.mode==="math"&&this.settings.reportNonstrict("unicodeTextInMathMode",'Accented Unicode text character "'+n[0]+'" used in math mode',t),n=x3[n[0]]+n.slice(1));var o=zT.exec(n);o&&(n=n.substring(0,o.index),n==="i"?n="ı":n==="j"&&(n="ȷ"));var c;if(Kt[this.mode][n]){this.settings.strict&&this.mode==="math"&&Sp.includes(n)&&this.settings.reportNonstrict("unicodeTextInMathMode",'Latin-1/Unicode text character "'+n[0]+'" used in math mode',t);var f=Kt[this.mode][n].group,h=br.range(t),m;Zj(f)?m={type:"atom",mode:this.mode,family:f,loc:h,text:n}:m={type:f,mode:this.mode,loc:h,text:n},c=m}else if(n.charCodeAt(0)>=128)this.settings.strict&&(_6(n.charCodeAt(0))?this.mode==="math"&&this.settings.reportNonstrict("unicodeTextInMathMode",'Unicode text character "'+n[0]+'" used in math mode',t):this.settings.reportNonstrict("unknownSymbol",'Unrecognized Unicode character "'+n[0]+'"'+(" ("+n.charCodeAt(0)+")"),t)),c={type:"textord",mode:"text",loc:br.range(t),text:n};else return null;if(this.consume(),o)for(var y=0;y<o[0].length;y++){var v=o[0][y];if(!Gm[v])throw new je("Unknown accent ' "+v+"'",t);var k=Gm[v][this.mode]||Gm[v].text;if(!k)throw new je("Accent "+v+" unsupported in "+this.mode+" mode",t);c={type:"accent",mode:this.mode,loc:br.range(t),label:k,isStretchy:!1,isShifty:!0,base:c}}return c}}Tf.endOfExpression=new Set(["}","\\endgroup","\\end","\\right","&"]);var R1=function(t,n){if(!(typeof t=="string"||t instanceof String))throw new TypeError("KaTeX can only parse string typed expression");var i=new Tf(t,n);delete i.gullet.macros.current["\\df@tag"];var l=i.parse();if(delete i.gullet.macros.current["\\current@color"],delete i.gullet.macros.current["\\color"],i.gullet.macros.get("\\df@tag")){if(!n.displayMode)throw new je("\\tag works only in display equations");l=[{type:"tag",mode:"text",body:l,tag:i.subparse([new Or("\\df@tag")])}]}return l},O1=function(t,n,i){n.textContent="";var l=Af(t,i).toNode();n.appendChild(l)};typeof document<"u"&&document.compatMode!=="CSS1Compat"&&(typeof console<"u"&&console.warn("Warning: KaTeX doesn't work in quirks mode. Make sure your website has a suitable doctype."),O1=function(){throw new je("KaTeX doesn't work in quirks mode.")});var Mv=function(t,n){var i=Af(t,n).toMarkup();return i},zv=function(t,n){var i=new x1(n);return R1(t,i)},Dv=function(t,n,i){if(i.throwOnError||!(t instanceof je))throw t;var l=ke(["katex-error"],[new _r(n)]);return l.setAttribute("title",t.toString()),l.setAttribute("style","color:"+i.errorColor),l},Af=function(t,n){var i=new x1(n);try{var l=R1(t,i);return Gj(l,t,i)}catch(o){return Dv(o,t,i)}},Rv=function(t,n){var i=new x1(n);try{var l=R1(t,i);return Pj(l,t,i)}catch(o){return Dv(o,t,i)}},Ov="0.16.47",_v={Span:su,Anchor:mf,SymbolNode:_r,SvgNode:Ui,PathNode:Gl,LineNode:kp},Lp={version:Ov,render:O1,renderToString:Mv,ParseError:je,SETTINGS_SCHEMA:Zd,__parse:zv,__renderToDomTree:Af,__renderToHTMLTree:Rv,__setFontMetrics:U6,__defineSymbol:b,__defineFunction:Ie,__defineMacro:D,__domTree:_v};const jD=Object.freeze(Object.defineProperty({__proto__:null,ParseError:je,SETTINGS_SCHEMA:Zd,__defineFunction:Ie,__defineMacro:D,__defineSymbol:b,__domTree:_v,__parse:zv,__renderToDomTree:Af,__renderToHTMLTree:Rv,__setFontMetrics:U6,default:Lp,get render(){return O1},renderToString:Mv,version:Ov},Symbol.toStringTag,{value:"Module"})),IT={};function LT(e){const t=this,n=e||IT,i=t.data(),l=i.micromarkExtensions||(i.micromarkExtensions=[]),o=i.fromMarkdownExtensions||(i.fromMarkdownExtensions=[]),c=i.toMarkdownExtensions||(i.toMarkdownExtensions=[]);l.push(PC(n)),o.push(IC()),c.push(LC(n))}const b3=/[#.]/g;function qT(e,t){const n=e||"",i={};let l=0,o,c;for(;l<n.length;){b3.lastIndex=l;const f=b3.exec(n),h=n.slice(l,f?f.index:n.length);h&&(o?o==="#"?i.id=h:Array.isArray(i.className)?i.className.push(h):i.className=[h]:c=h,l+=h.length),f&&(o=f[0],l++)}return{type:"element",tagName:c||t||"div",properties:i,children:[]}}function Bv(e,t,n){const i=n?$T(n):void 0;function l(o,c,...f){let h;if(o==null){h={type:"root",children:[]};const m=c;f.unshift(m)}else{h=qT(o,t);const m=h.tagName.toLowerCase(),y=i?i.get(m):void 0;if(h.tagName=y||m,UT(c))f.unshift(c);else for(const[v,k]of Object.entries(c))HT(e,h.properties,v,k)}for(const m of f)qp(h.children,m);return h.type==="element"&&h.tagName==="template"&&(h.content={type:"root",children:h.children},h.children=[]),h}return l}function UT(e){if(e===null||typeof e!="object"||Array.isArray(e))return!0;if(typeof e.type!="string")return!1;const t=e,n=Object.keys(e);for(const i of n){const l=t[i];if(l&&typeof l=="object"){if(!Array.isArray(l))return!0;const o=l;for(const c of o)if(typeof c!="number"&&typeof c!="string")return!0}}return!!("children"in e&&Array.isArray(e.children))}function HT(e,t,n,i){const l=_5(e,n);let o;if(i!=null){if(typeof i=="number"){if(Number.isNaN(i))return;o=i}else typeof i=="boolean"?o=i:typeof i=="string"?l.spaceSeparated?o=X2(i):l.commaSeparated?o=G2(i):l.commaOrSpaceSeparated?o=X2(G2(i).join(" ")):o=w3(l,l.property,i):Array.isArray(i)?o=[...i]:o=l.property==="style"?FT(i):String(i);if(Array.isArray(o)){const c=[];for(const f of o)c.push(w3(l,l.property,f));o=c}l.property==="className"&&Array.isArray(t.className)&&(o=t.className.concat(o)),t[l.property]=o}}function qp(e,t){if(t!=null)if(typeof t=="number"||typeof t=="string")e.push({type:"text",value:String(t)});else if(Array.isArray(t))for(const n of t)qp(e,n);else if(typeof t=="object"&&"type"in t)t.type==="root"?qp(e,t.children):e.push(t);else throw new Error("Expected node, nodes, or string, got `"+t+"`")}function w3(e,t,n){if(typeof n=="string"){if(e.number&&n&&!Number.isNaN(Number(n)))return Number(n);if((e.boolean||e.overloadedBoolean)&&(n===""||qc(n)===qc(t)))return!0}return n}function FT(e){const t=[];for(const[n,i]of Object.entries(e))t.push([n,i].join(": "));return t.join("; ")}function $T(e){const t=new Map;for(const n of e)t.set(n.toLowerCase(),n);return t}const GT=["altGlyph","altGlyphDef","altGlyphItem","animateColor","animateMotion","animateTransform","clipPath","feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence","foreignObject","glyphRef","linearGradient","radialGradient","solidColor","textArea","textPath"],PT=Bv(B5,"div"),VT=Bv(uf,"g",GT),Pm={html:"http://www.w3.org/1999/xhtml",svg:"http://www.w3.org/2000/svg"};function YT(e,t){return Iv(e,{})||{type:"root",children:[]}}function Iv(e,t){const n=WT(e,t);return n&&t.afterTransform&&t.afterTransform(e,n),n}function WT(e,t){switch(e.nodeType){case 1:return ZT(e,t);case 3:return KT(e);case 8:return QT(e);case 9:return k3(e,t);case 10:return XT();case 11:return k3(e,t);default:return}}function k3(e,t){return{type:"root",children:Lv(e,t)}}function XT(){return{type:"doctype"}}function KT(e){return{type:"text",value:e.nodeValue||""}}function QT(e){return{type:"comment",value:e.nodeValue||""}}function ZT(e,t){const n=e.namespaceURI,i=n===Pm.svg?VT:PT,l=n===Pm.html?e.tagName.toLowerCase():e.tagName,o=n===Pm.html&&l==="template"?e.content:e,c=e.getAttributeNames(),f={};let h=-1;for(;++h<c.length;)f[c[h]]=e.getAttribute(c[h])||"";return i(l,f,Lv(o,t))}function Lv(e,t){const n=e.childNodes,i=[];let l=-1;for(;++l<n.length;){const o=Iv(n[l],t);o!==void 0&&i.push(o)}return i}new DOMParser;function JT(e,t){const n=eA(e);return YT(n)}function eA(e){const t=document.createElement("template");return t.innerHTML=e,t.content}const S3=(function(e,t,n){const i=Vc(n);if(!e||!e.type||!e.children)throw new Error("Expected parent node");if(typeof t=="number"){if(t<0||t===Number.POSITIVE_INFINITY)throw new Error("Expected positive finite number as index")}else if(t=e.children.indexOf(t),t<0)throw new Error("Expected child node or index");for(;++t<e.children.length;)if(i(e.children[t],t,e))return e.children[t]}),Ws=(function(e){if(e==null)return rA;if(typeof e=="string")return nA(e);if(typeof e=="object")return tA(e);if(typeof e=="function")return _1(e);throw new Error("Expected function, string, or array as `test`")});function tA(e){const t=[];let n=-1;for(;++n<e.length;)t[n]=Ws(e[n]);return _1(i);function i(...l){let o=-1;for(;++o<t.length;)if(t[o].apply(this,l))return!0;return!1}}function nA(e){return _1(t);function t(n){return n.tagName===e}}function _1(e){return t;function t(n,i,l){return!!(aA(n)&&e.call(this,n,typeof i=="number"?i:void 0,l||void 0))}}function rA(e){return!!(e&&typeof e=="object"&&"type"in e&&e.type==="element"&&"tagName"in e&&typeof e.tagName=="string")}function aA(e){return e!==null&&typeof e=="object"&&"type"in e&&"tagName"in e}const C3=/\n/g,j3=/[\t ]+/g,Up=Ws("br"),T3=Ws(fA),iA=Ws("p"),A3=Ws("tr"),lA=Ws(["datalist","head","noembed","noframes","noscript","rp","script","style","template","title",dA,hA]),qv=Ws(["address","article","aside","blockquote","body","caption","center","dd","dialog","dir","dl","dt","div","figure","figcaption","footer","form,","h1","h2","h3","h4","h5","h6","header","hgroup","hr","html","legend","li","listing","main","menu","nav","ol","p","plaintext","pre","section","ul","xmp"]);function sA(e,t){const n=t||{},i="children"in e?e.children:[],l=qv(e),o=Fv(e,{whitespace:n.whitespace||"normal"}),c=[];(e.type==="text"||e.type==="comment")&&c.push(...Hv(e,{breakBefore:!0,breakAfter:!0}));let f=-1;for(;++f<i.length;)c.push(...Uv(i[f],e,{whitespace:o,breakBefore:f?void 0:l,breakAfter:f<i.length-1?Up(i[f+1]):l}));const h=[];let m;for(f=-1;++f<c.length;){const y=c[f];typeof y=="number"?m!==void 0&&y>m&&(m=y):y&&(m!==void 0&&m>-1&&h.push(`
339
- `.repeat(m)||" "),m=-1,h.push(y))}return h.join("")}function Uv(e,t,n){return e.type==="element"?oA(e,t,n):e.type==="text"?n.whitespace==="normal"?Hv(e,n):uA(e):[]}function oA(e,t,n){const i=Fv(e,n),l=e.children||[];let o=-1,c=[];if(lA(e))return c;let f,h;for(Up(e)||A3(e)&&S3(t,e,A3)?h=`
340
- `:iA(e)?(f=2,h=2):qv(e)&&(f=1,h=1);++o<l.length;)c=c.concat(Uv(l[o],e,{whitespace:i,breakBefore:o?void 0:f,breakAfter:o<l.length-1?Up(l[o+1]):h}));return T3(e)&&S3(t,e,T3)&&c.push(" "),f&&c.unshift(f),h&&c.push(h),c}function Hv(e,t){const n=String(e.value),i=[],l=[];let o=0;for(;o<=n.length;){C3.lastIndex=o;const h=C3.exec(n),m=h&&"index"in h?h.index:n.length;i.push(cA(n.slice(o,m).replace(/[\u061C\u200E\u200F\u202A-\u202E\u2066-\u2069]/g,""),o===0?t.breakBefore:!0,m===n.length?t.breakAfter:!0)),o=m+1}let c=-1,f;for(;++c<i.length;)i[c].charCodeAt(i[c].length-1)===8203||c<i.length-1&&i[c+1].charCodeAt(0)===8203?(l.push(i[c]),f=void 0):i[c]?(typeof f=="number"&&l.push(f),l.push(i[c]),f=0):(c===0||c===i.length-1)&&l.push(0);return l}function uA(e){return[String(e.value)]}function cA(e,t,n){const i=[];let l=0,o;for(;l<e.length;){j3.lastIndex=l;const c=j3.exec(e);o=c?c.index:e.length,!l&&!o&&c&&!t&&i.push(""),l!==o&&i.push(e.slice(l,o)),l=c?o+c[0].length:o}return l!==o&&!n&&i.push(""),i.join(" ")}function Fv(e,t){if(e.type==="element"){const n=e.properties||{};switch(e.tagName){case"listing":case"plaintext":case"xmp":return"pre";case"nobr":return"nowrap";case"pre":return n.wrap?"pre-wrap":"pre";case"td":case"th":return n.noWrap?"nowrap":t.whitespace;case"textarea":return"pre-wrap"}}return t.whitespace}function dA(e){return!!(e.properties||{}).hidden}function fA(e){return e.tagName==="td"||e.tagName==="th"}function hA(e){return e.tagName==="dialog"&&!(e.properties||{}).open}const mA={},pA=[];function gA(e){const t=e||mA;return function(n,i){h1(n,"element",function(l,o){const c=Array.isArray(l.properties.className)?l.properties.className:pA,f=c.includes("language-math"),h=c.includes("math-display"),m=c.includes("math-inline");let y=h;if(!f&&!h&&!m)return;let v=o[o.length-1],k=l;if(l.tagName==="code"&&f&&v&&v.type==="element"&&v.tagName==="pre"&&(k=v,v=o[o.length-2],y=!0),!v)return;const w=sA(k,{whitespace:"pre"});let T;try{T=Lp.renderToString(w,{...t,displayMode:y,throwOnError:!0})}catch(q){const R=q,B=R.name.toLowerCase();i.message("Could not render math with KaTeX",{ancestors:[...o,l],cause:R,place:l.position,ruleId:B,source:"rehype-katex"});try{T=Lp.renderToString(w,{...t,displayMode:y,strict:"ignore",throwOnError:!1})}catch{T=[{type:"element",tagName:"span",properties:{className:["katex-error"],style:"color:"+(t.errorColor||"#cc0000"),title:String(q)},children:[{type:"text",value:w}]}]}}typeof T=="string"&&(T=JT(T).children);const E=v.children.indexOf(k);return v.children.splice(E,1,...T),u6})}}function yA(e){const t=new Map;for(const n of e){if(!n.turnId)continue;if(n.event==="server.wakeup.started"){t.set(n.turnId,"wakeup");continue}if(n.event!=="server.turn")continue;const i=xA(n.data);t.set(n.turnId,typeof i.source=="string"?i.source:"web")}return t}function Oc(e,t){return!!(t&&e.includes(t))}function vA(e){var n;if((e==null?void 0:e.status)!=="failed")return null;const t=(n=e.error)==null?void 0:n.trim();return t?{turnId:e.id,content:t,createdAt:e.finishedAt??e.startedAt}:null}function xA(e){return e&&typeof e=="object"?e:{}}const bA=["summary","message","status","instruction","description","reason","error","text"],E3=96,wA=new Set(["codex.dynamic_tool_request","codex.process_exited","codex.protocol_error"]),kA=new Set(["server.status","runtime.worker_stderr","codex.dynamic_tool_request"]),SA=new Set(["agentMessage","commandExecution","contextCompaction","fileChange","mcpToolCall","reasoning","userMessage","webSearch"]),$v=new Set(["item/commandExecution/terminalInteraction"]),CA=new Map([["server.wakeup.retry_scheduled","Wakeup retry scheduled"],["runtime.worker_exit","Runtime worker exited"]]);function jA(e){if(e.event!=="codex.notification")return!1;const t=Ja(e.data);return typeof t.method=="string"&&$v.has(t.method)}function TA(e){if(kA.has(e.event))return null;if(e.event.startsWith("server.")||e.event.startsWith("runtime.")||wA.has(e.event))return e.event;if(e.event!=="codex.notification")return null;const t=Ja(e.data),n=typeof t.method=="string"?t.method:"",i=Ja(t.params),l=Ja(i.item),o=typeof l.type=="string"?l.type:"";return!n.startsWith("item/")||$v.has(n)||n.endsWith("/delta")||n.endsWith("/outputDelta")||SA.has(o)?null:n}function Gv(e,t){const n=t.replace(/^input:/,""),i=(e==null?void 0:e.trim())??"";return!i||i===t||i===n?CA.get(n)??Pv(n):i}function $s(e,t=[]){const n=Ja(e),l=[...t,...bA.map(o=>_c(n[o]))].map(o=>(o==null?void 0:o.replace(/\s+/g," ").trim())??"").find(Boolean);return l?l.length<=E3?l:`${l.slice(0,E3-3)}...`:"查看详情"}function Hp(e,t=new Map){const n=Ja(e),i=typeof n.unreadCount=="number"&&n.unreadCount>0?Math.floor(n.unreadCount):0,o=(Array.isArray(n.senderWorkspaceIds)?Array.from(new Set(n.senderWorkspaceIds.filter(h=>typeof h=="string").map(h=>h.trim()).filter(Boolean))):[]).map(h=>t.get(h)??h),c="Messages",f=[i>0?String(i):"",o.length>0?`from ${o.join(", ")}`:""].filter(Boolean).join(" ");return{title:c,detail:$s({},[f])}}function AA(e){const t=Ja(e),n=Array.isArray(t.offers)?t.offers.map(Ja).filter(o=>Object.keys(o).length>0):[],i=n.map(o=>{var c;return(c=_c(o.previewText))==null?void 0:c.trim()}).filter(o=>!!o),l=n.length;return{title:l===1?"New input available":`${l} new inputs available`,detail:$s({},i.slice(0,2)),meta:l===1?"preview":`${l} previews`}}function EA(e){const t=Ja(e),n=_c(t.actionType)??"",i=Ja(t.payload);return n==="seele_wakeup"||n==="seele_workspace_schedule_wakeup"?{title:(_c(i.action)??"schedule")==="cancel"?"Wakeup cancellation requested":"Wakeup requested",detail:$s(i,[_c(i.instruction)]),meta:"after turn"}:{title:"Action requested",detail:$s(i,[Pv(n||"agent action")]),meta:"after turn"}}function Pv(e){const n=(e.split(/[./]/).filter(Boolean).pop()??e).replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/[_-]+/g," ").trim();return n?n.charAt(0).toUpperCase()+n.slice(1):"System event"}function _c(e){if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return String(e)}function Ja(e){return e&&typeof e=="object"?e:{}}function Fp(e){const t=$p(e);return(Array.isArray(t.changes)?t.changes:[]).flatMap(i=>{const l=$p(i);if(typeof l.path!="string"||!l.path.trim())return[];const o=DA(l.kind),c=typeof l.diff=="string"?l.diff:"",f=zA(c,o);return[{path:l.path,kind:o,additions:f.additions,deletions:f.deletions}]})}function Vv(e,t){const n=M3(e),i=M3(t??"").replace(/\/+$/,"");return i&&(n===i||n.startsWith(`${i}/`))?n.slice(i.length+1)||".":n}function NA(e,t){if(e.length===0)return"File changed";const n=Vv(e[0].path,t);return e.length===1?n:`${n} +${e.length-1}`}function MA(e){return e.reduce((t,n)=>({additions:t.additions+n.additions,deletions:t.deletions+n.deletions}),{additions:0,deletions:0})}function zA(e,t){if(!e)return{additions:0,deletions:0};if(t==="add")return{additions:N3(e),deletions:0};if(t==="delete")return{additions:0,deletions:N3(e)};let n=0,i=0;for(const l of e.split(`
338
+ please report what input caused this bug`);return i=i.slice(1,-1),{type:"verb",mode:"text",body:i,star:l}}x3.hasOwnProperty(n[0])&&!Kt[this.mode][n[0]]&&(this.settings.strict&&this.mode==="math"&&this.settings.reportNonstrict("unicodeTextInMathMode",'Accented Unicode text character "'+n[0]+'" used in math mode',t),n=x3[n[0]]+n.slice(1));var o=zT.exec(n);o&&(n=n.substring(0,o.index),n==="i"?n="ı":n==="j"&&(n="ȷ"));var c;if(Kt[this.mode][n]){this.settings.strict&&this.mode==="math"&&Sp.includes(n)&&this.settings.reportNonstrict("unicodeTextInMathMode",'Latin-1/Unicode text character "'+n[0]+'" used in math mode',t);var f=Kt[this.mode][n].group,h=br.range(t),m;Zj(f)?m={type:"atom",mode:this.mode,family:f,loc:h,text:n}:m={type:f,mode:this.mode,loc:h,text:n},c=m}else if(n.charCodeAt(0)>=128)this.settings.strict&&(_6(n.charCodeAt(0))?this.mode==="math"&&this.settings.reportNonstrict("unicodeTextInMathMode",'Unicode text character "'+n[0]+'" used in math mode',t):this.settings.reportNonstrict("unknownSymbol",'Unrecognized Unicode character "'+n[0]+'"'+(" ("+n.charCodeAt(0)+")"),t)),c={type:"textord",mode:"text",loc:br.range(t),text:n};else return null;if(this.consume(),o)for(var y=0;y<o[0].length;y++){var v=o[0][y];if(!Gm[v])throw new je("Unknown accent ' "+v+"'",t);var k=Gm[v][this.mode]||Gm[v].text;if(!k)throw new je("Accent "+v+" unsupported in "+this.mode+" mode",t);c={type:"accent",mode:this.mode,loc:br.range(t),label:k,isStretchy:!1,isShifty:!0,base:c}}return c}}Tf.endOfExpression=new Set(["}","\\endgroup","\\end","\\right","&"]);var R1=function(t,n){if(!(typeof t=="string"||t instanceof String))throw new TypeError("KaTeX can only parse string typed expression");var i=new Tf(t,n);delete i.gullet.macros.current["\\df@tag"];var l=i.parse();if(delete i.gullet.macros.current["\\current@color"],delete i.gullet.macros.current["\\color"],i.gullet.macros.get("\\df@tag")){if(!n.displayMode)throw new je("\\tag works only in display equations");l=[{type:"tag",mode:"text",body:l,tag:i.subparse([new Or("\\df@tag")])}]}return l},O1=function(t,n,i){n.textContent="";var l=Af(t,i).toNode();n.appendChild(l)};typeof document<"u"&&document.compatMode!=="CSS1Compat"&&(typeof console<"u"&&console.warn("Warning: KaTeX doesn't work in quirks mode. Make sure your website has a suitable doctype."),O1=function(){throw new je("KaTeX doesn't work in quirks mode.")});var Mv=function(t,n){var i=Af(t,n).toMarkup();return i},zv=function(t,n){var i=new x1(n);return R1(t,i)},Dv=function(t,n,i){if(i.throwOnError||!(t instanceof je))throw t;var l=ke(["katex-error"],[new _r(n)]);return l.setAttribute("title",t.toString()),l.setAttribute("style","color:"+i.errorColor),l},Af=function(t,n){var i=new x1(n);try{var l=R1(t,i);return Gj(l,t,i)}catch(o){return Dv(o,t,i)}},Rv=function(t,n){var i=new x1(n);try{var l=R1(t,i);return Pj(l,t,i)}catch(o){return Dv(o,t,i)}},Ov="0.16.47",_v={Span:su,Anchor:mf,SymbolNode:_r,SvgNode:Ui,PathNode:Gl,LineNode:kp},Lp={version:Ov,render:O1,renderToString:Mv,ParseError:je,SETTINGS_SCHEMA:Zd,__parse:zv,__renderToDomTree:Af,__renderToHTMLTree:Rv,__setFontMetrics:U6,__defineSymbol:b,__defineFunction:Ie,__defineMacro:D,__domTree:_v};const TD=Object.freeze(Object.defineProperty({__proto__:null,ParseError:je,SETTINGS_SCHEMA:Zd,__defineFunction:Ie,__defineMacro:D,__defineSymbol:b,__domTree:_v,__parse:zv,__renderToDomTree:Af,__renderToHTMLTree:Rv,__setFontMetrics:U6,default:Lp,get render(){return O1},renderToString:Mv,version:Ov},Symbol.toStringTag,{value:"Module"})),IT={};function LT(e){const t=this,n=e||IT,i=t.data(),l=i.micromarkExtensions||(i.micromarkExtensions=[]),o=i.fromMarkdownExtensions||(i.fromMarkdownExtensions=[]),c=i.toMarkdownExtensions||(i.toMarkdownExtensions=[]);l.push(PC(n)),o.push(IC()),c.push(LC(n))}function qT(e){return e.replace(/(^ {0,3}(`{3,}|~{3,})[^\n]*\n[\s\S]*?(?:^ {0,3}\2[^\n]*(?:\n|$)|(?![\s\S])))|(`+)([^`]|(?!\3)`)*?\3|\\\\|\\\(([\s\S]*?)\\\)|\\\[([\s\S]*?)\\\]/gm,(t,n,i,l,o,c,f)=>n||l||t==="\\\\"?t:c!==void 0?`$${c}$`:f!==void 0?`
339
+
340
+ $$
341
+ ${f.trim()}
342
+ $$
343
+
344
+ `:t)}const b3=/[#.]/g;function UT(e,t){const n=e||"",i={};let l=0,o,c;for(;l<n.length;){b3.lastIndex=l;const f=b3.exec(n),h=n.slice(l,f?f.index:n.length);h&&(o?o==="#"?i.id=h:Array.isArray(i.className)?i.className.push(h):i.className=[h]:c=h,l+=h.length),f&&(o=f[0],l++)}return{type:"element",tagName:c||t||"div",properties:i,children:[]}}function Bv(e,t,n){const i=n?GT(n):void 0;function l(o,c,...f){let h;if(o==null){h={type:"root",children:[]};const m=c;f.unshift(m)}else{h=UT(o,t);const m=h.tagName.toLowerCase(),y=i?i.get(m):void 0;if(h.tagName=y||m,HT(c))f.unshift(c);else for(const[v,k]of Object.entries(c))FT(e,h.properties,v,k)}for(const m of f)qp(h.children,m);return h.type==="element"&&h.tagName==="template"&&(h.content={type:"root",children:h.children},h.children=[]),h}return l}function HT(e){if(e===null||typeof e!="object"||Array.isArray(e))return!0;if(typeof e.type!="string")return!1;const t=e,n=Object.keys(e);for(const i of n){const l=t[i];if(l&&typeof l=="object"){if(!Array.isArray(l))return!0;const o=l;for(const c of o)if(typeof c!="number"&&typeof c!="string")return!0}}return!!("children"in e&&Array.isArray(e.children))}function FT(e,t,n,i){const l=_5(e,n);let o;if(i!=null){if(typeof i=="number"){if(Number.isNaN(i))return;o=i}else typeof i=="boolean"?o=i:typeof i=="string"?l.spaceSeparated?o=X2(i):l.commaSeparated?o=G2(i):l.commaOrSpaceSeparated?o=X2(G2(i).join(" ")):o=w3(l,l.property,i):Array.isArray(i)?o=[...i]:o=l.property==="style"?$T(i):String(i);if(Array.isArray(o)){const c=[];for(const f of o)c.push(w3(l,l.property,f));o=c}l.property==="className"&&Array.isArray(t.className)&&(o=t.className.concat(o)),t[l.property]=o}}function qp(e,t){if(t!=null)if(typeof t=="number"||typeof t=="string")e.push({type:"text",value:String(t)});else if(Array.isArray(t))for(const n of t)qp(e,n);else if(typeof t=="object"&&"type"in t)t.type==="root"?qp(e,t.children):e.push(t);else throw new Error("Expected node, nodes, or string, got `"+t+"`")}function w3(e,t,n){if(typeof n=="string"){if(e.number&&n&&!Number.isNaN(Number(n)))return Number(n);if((e.boolean||e.overloadedBoolean)&&(n===""||qc(n)===qc(t)))return!0}return n}function $T(e){const t=[];for(const[n,i]of Object.entries(e))t.push([n,i].join(": "));return t.join("; ")}function GT(e){const t=new Map;for(const n of e)t.set(n.toLowerCase(),n);return t}const PT=["altGlyph","altGlyphDef","altGlyphItem","animateColor","animateMotion","animateTransform","clipPath","feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence","foreignObject","glyphRef","linearGradient","radialGradient","solidColor","textArea","textPath"],VT=Bv(B5,"div"),YT=Bv(uf,"g",PT),Pm={html:"http://www.w3.org/1999/xhtml",svg:"http://www.w3.org/2000/svg"};function WT(e,t){return Iv(e,{})||{type:"root",children:[]}}function Iv(e,t){const n=XT(e,t);return n&&t.afterTransform&&t.afterTransform(e,n),n}function XT(e,t){switch(e.nodeType){case 1:return JT(e,t);case 3:return QT(e);case 8:return ZT(e);case 9:return k3(e,t);case 10:return KT();case 11:return k3(e,t);default:return}}function k3(e,t){return{type:"root",children:Lv(e,t)}}function KT(){return{type:"doctype"}}function QT(e){return{type:"text",value:e.nodeValue||""}}function ZT(e){return{type:"comment",value:e.nodeValue||""}}function JT(e,t){const n=e.namespaceURI,i=n===Pm.svg?YT:VT,l=n===Pm.html?e.tagName.toLowerCase():e.tagName,o=n===Pm.html&&l==="template"?e.content:e,c=e.getAttributeNames(),f={};let h=-1;for(;++h<c.length;)f[c[h]]=e.getAttribute(c[h])||"";return i(l,f,Lv(o,t))}function Lv(e,t){const n=e.childNodes,i=[];let l=-1;for(;++l<n.length;){const o=Iv(n[l],t);o!==void 0&&i.push(o)}return i}new DOMParser;function eA(e,t){const n=tA(e);return WT(n)}function tA(e){const t=document.createElement("template");return t.innerHTML=e,t.content}const S3=(function(e,t,n){const i=Vc(n);if(!e||!e.type||!e.children)throw new Error("Expected parent node");if(typeof t=="number"){if(t<0||t===Number.POSITIVE_INFINITY)throw new Error("Expected positive finite number as index")}else if(t=e.children.indexOf(t),t<0)throw new Error("Expected child node or index");for(;++t<e.children.length;)if(i(e.children[t],t,e))return e.children[t]}),Ws=(function(e){if(e==null)return aA;if(typeof e=="string")return rA(e);if(typeof e=="object")return nA(e);if(typeof e=="function")return _1(e);throw new Error("Expected function, string, or array as `test`")});function nA(e){const t=[];let n=-1;for(;++n<e.length;)t[n]=Ws(e[n]);return _1(i);function i(...l){let o=-1;for(;++o<t.length;)if(t[o].apply(this,l))return!0;return!1}}function rA(e){return _1(t);function t(n){return n.tagName===e}}function _1(e){return t;function t(n,i,l){return!!(iA(n)&&e.call(this,n,typeof i=="number"?i:void 0,l||void 0))}}function aA(e){return!!(e&&typeof e=="object"&&"type"in e&&e.type==="element"&&"tagName"in e&&typeof e.tagName=="string")}function iA(e){return e!==null&&typeof e=="object"&&"type"in e&&"tagName"in e}const C3=/\n/g,j3=/[\t ]+/g,Up=Ws("br"),T3=Ws(hA),lA=Ws("p"),A3=Ws("tr"),sA=Ws(["datalist","head","noembed","noframes","noscript","rp","script","style","template","title",fA,mA]),qv=Ws(["address","article","aside","blockquote","body","caption","center","dd","dialog","dir","dl","dt","div","figure","figcaption","footer","form,","h1","h2","h3","h4","h5","h6","header","hgroup","hr","html","legend","li","listing","main","menu","nav","ol","p","plaintext","pre","section","ul","xmp"]);function oA(e,t){const n=t||{},i="children"in e?e.children:[],l=qv(e),o=Fv(e,{whitespace:n.whitespace||"normal"}),c=[];(e.type==="text"||e.type==="comment")&&c.push(...Hv(e,{breakBefore:!0,breakAfter:!0}));let f=-1;for(;++f<i.length;)c.push(...Uv(i[f],e,{whitespace:o,breakBefore:f?void 0:l,breakAfter:f<i.length-1?Up(i[f+1]):l}));const h=[];let m;for(f=-1;++f<c.length;){const y=c[f];typeof y=="number"?m!==void 0&&y>m&&(m=y):y&&(m!==void 0&&m>-1&&h.push(`
345
+ `.repeat(m)||" "),m=-1,h.push(y))}return h.join("")}function Uv(e,t,n){return e.type==="element"?uA(e,t,n):e.type==="text"?n.whitespace==="normal"?Hv(e,n):cA(e):[]}function uA(e,t,n){const i=Fv(e,n),l=e.children||[];let o=-1,c=[];if(sA(e))return c;let f,h;for(Up(e)||A3(e)&&S3(t,e,A3)?h=`
346
+ `:lA(e)?(f=2,h=2):qv(e)&&(f=1,h=1);++o<l.length;)c=c.concat(Uv(l[o],e,{whitespace:i,breakBefore:o?void 0:f,breakAfter:o<l.length-1?Up(l[o+1]):h}));return T3(e)&&S3(t,e,T3)&&c.push(" "),f&&c.unshift(f),h&&c.push(h),c}function Hv(e,t){const n=String(e.value),i=[],l=[];let o=0;for(;o<=n.length;){C3.lastIndex=o;const h=C3.exec(n),m=h&&"index"in h?h.index:n.length;i.push(dA(n.slice(o,m).replace(/[\u061C\u200E\u200F\u202A-\u202E\u2066-\u2069]/g,""),o===0?t.breakBefore:!0,m===n.length?t.breakAfter:!0)),o=m+1}let c=-1,f;for(;++c<i.length;)i[c].charCodeAt(i[c].length-1)===8203||c<i.length-1&&i[c+1].charCodeAt(0)===8203?(l.push(i[c]),f=void 0):i[c]?(typeof f=="number"&&l.push(f),l.push(i[c]),f=0):(c===0||c===i.length-1)&&l.push(0);return l}function cA(e){return[String(e.value)]}function dA(e,t,n){const i=[];let l=0,o;for(;l<e.length;){j3.lastIndex=l;const c=j3.exec(e);o=c?c.index:e.length,!l&&!o&&c&&!t&&i.push(""),l!==o&&i.push(e.slice(l,o)),l=c?o+c[0].length:o}return l!==o&&!n&&i.push(""),i.join(" ")}function Fv(e,t){if(e.type==="element"){const n=e.properties||{};switch(e.tagName){case"listing":case"plaintext":case"xmp":return"pre";case"nobr":return"nowrap";case"pre":return n.wrap?"pre-wrap":"pre";case"td":case"th":return n.noWrap?"nowrap":t.whitespace;case"textarea":return"pre-wrap"}}return t.whitespace}function fA(e){return!!(e.properties||{}).hidden}function hA(e){return e.tagName==="td"||e.tagName==="th"}function mA(e){return e.tagName==="dialog"&&!(e.properties||{}).open}const pA={},gA=[];function yA(e){const t=e||pA;return function(n,i){h1(n,"element",function(l,o){const c=Array.isArray(l.properties.className)?l.properties.className:gA,f=c.includes("language-math"),h=c.includes("math-display"),m=c.includes("math-inline");let y=h;if(!f&&!h&&!m)return;let v=o[o.length-1],k=l;if(l.tagName==="code"&&f&&v&&v.type==="element"&&v.tagName==="pre"&&(k=v,v=o[o.length-2],y=!0),!v)return;const w=oA(k,{whitespace:"pre"});let T;try{T=Lp.renderToString(w,{...t,displayMode:y,throwOnError:!0})}catch(q){const R=q,B=R.name.toLowerCase();i.message("Could not render math with KaTeX",{ancestors:[...o,l],cause:R,place:l.position,ruleId:B,source:"rehype-katex"});try{T=Lp.renderToString(w,{...t,displayMode:y,strict:"ignore",throwOnError:!1})}catch{T=[{type:"element",tagName:"span",properties:{className:["katex-error"],style:"color:"+(t.errorColor||"#cc0000"),title:String(q)},children:[{type:"text",value:w}]}]}}typeof T=="string"&&(T=eA(T).children);const E=v.children.indexOf(k);return v.children.splice(E,1,...T),u6})}}function vA(e){const t=new Map;for(const n of e){if(!n.turnId)continue;if(n.event==="server.wakeup.started"){t.set(n.turnId,"wakeup");continue}if(n.event!=="server.turn")continue;const i=bA(n.data);t.set(n.turnId,typeof i.source=="string"?i.source:"web")}return t}function Oc(e,t){return!!(t&&e.includes(t))}function xA(e){var n;if((e==null?void 0:e.status)!=="failed")return null;const t=(n=e.error)==null?void 0:n.trim();return t?{turnId:e.id,content:t,createdAt:e.finishedAt??e.startedAt}:null}function bA(e){return e&&typeof e=="object"?e:{}}const wA=["summary","message","status","instruction","description","reason","error","text"],E3=96,kA=new Set(["codex.dynamic_tool_request","codex.process_exited","codex.protocol_error"]),SA=new Set(["server.status","runtime.worker_stderr","codex.dynamic_tool_request"]),CA=new Set(["agentMessage","commandExecution","contextCompaction","fileChange","mcpToolCall","reasoning","userMessage","webSearch"]),$v=new Set(["item/commandExecution/terminalInteraction"]),jA=new Map([["server.wakeup.retry_scheduled","Wakeup retry scheduled"],["runtime.worker_exit","Runtime worker exited"]]);function TA(e){if(e.event!=="codex.notification")return!1;const t=Ja(e.data);return typeof t.method=="string"&&$v.has(t.method)}function AA(e){if(SA.has(e.event))return null;if(e.event.startsWith("server.")||e.event.startsWith("runtime.")||kA.has(e.event))return e.event;if(e.event!=="codex.notification")return null;const t=Ja(e.data),n=typeof t.method=="string"?t.method:"",i=Ja(t.params),l=Ja(i.item),o=typeof l.type=="string"?l.type:"";return!n.startsWith("item/")||$v.has(n)||n.endsWith("/delta")||n.endsWith("/outputDelta")||CA.has(o)?null:n}function Gv(e,t){const n=t.replace(/^input:/,""),i=(e==null?void 0:e.trim())??"";return!i||i===t||i===n?jA.get(n)??Pv(n):i}function $s(e,t=[]){const n=Ja(e),l=[...t,...wA.map(o=>_c(n[o]))].map(o=>(o==null?void 0:o.replace(/\s+/g," ").trim())??"").find(Boolean);return l?l.length<=E3?l:`${l.slice(0,E3-3)}...`:"查看详情"}function Hp(e,t=new Map){const n=Ja(e),i=typeof n.unreadCount=="number"&&n.unreadCount>0?Math.floor(n.unreadCount):0,o=(Array.isArray(n.senderWorkspaceIds)?Array.from(new Set(n.senderWorkspaceIds.filter(h=>typeof h=="string").map(h=>h.trim()).filter(Boolean))):[]).map(h=>t.get(h)??h),c="Messages",f=[i>0?String(i):"",o.length>0?`from ${o.join(", ")}`:""].filter(Boolean).join(" ");return{title:c,detail:$s({},[f])}}function EA(e){const t=Ja(e),n=Array.isArray(t.offers)?t.offers.map(Ja).filter(o=>Object.keys(o).length>0):[],i=n.map(o=>{var c;return(c=_c(o.previewText))==null?void 0:c.trim()}).filter(o=>!!o),l=n.length;return{title:l===1?"New input available":`${l} new inputs available`,detail:$s({},i.slice(0,2)),meta:l===1?"preview":`${l} previews`}}function NA(e){const t=Ja(e),n=_c(t.actionType)??"",i=Ja(t.payload);return n==="seele_wakeup"||n==="seele_workspace_schedule_wakeup"?{title:(_c(i.action)??"schedule")==="cancel"?"Wakeup cancellation requested":"Wakeup requested",detail:$s(i,[_c(i.instruction)]),meta:"after turn"}:{title:"Action requested",detail:$s(i,[Pv(n||"agent action")]),meta:"after turn"}}function Pv(e){const n=(e.split(/[./]/).filter(Boolean).pop()??e).replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/[_-]+/g," ").trim();return n?n.charAt(0).toUpperCase()+n.slice(1):"System event"}function _c(e){if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return String(e)}function Ja(e){return e&&typeof e=="object"?e:{}}function Fp(e){const t=$p(e);return(Array.isArray(t.changes)?t.changes:[]).flatMap(i=>{const l=$p(i);if(typeof l.path!="string"||!l.path.trim())return[];const o=RA(l.kind),c=typeof l.diff=="string"?l.diff:"",f=DA(c,o);return[{path:l.path,kind:o,additions:f.additions,deletions:f.deletions}]})}function Vv(e,t){const n=M3(e),i=M3(t??"").replace(/\/+$/,"");return i&&(n===i||n.startsWith(`${i}/`))?n.slice(i.length+1)||".":n}function MA(e,t){if(e.length===0)return"File changed";const n=Vv(e[0].path,t);return e.length===1?n:`${n} +${e.length-1}`}function zA(e){return e.reduce((t,n)=>({additions:t.additions+n.additions,deletions:t.deletions+n.deletions}),{additions:0,deletions:0})}function DA(e,t){if(!e)return{additions:0,deletions:0};if(t==="add")return{additions:N3(e),deletions:0};if(t==="delete")return{additions:0,deletions:N3(e)};let n=0,i=0;for(const l of e.split(`
341
347
  `))l.startsWith("+")&&!l.startsWith("+++")?n+=1:l.startsWith("-")&&!l.startsWith("---")&&(i+=1);return{additions:n,deletions:i}}function N3(e){const t=e.split(`
342
348
  `).length;return e.endsWith(`
343
- `)?Math.max(0,t-1):t}function DA(e){const t=$p(e);return t.type==="add"?"add":t.type==="delete"?"delete":t.type==="move"||typeof t.move_path=="string"?"move":"update"}function M3(e){return e.replace(/\\/g,"/").replace(/\/+/g,"/")}function $p(e){return e&&typeof e=="object"?e:{}}const B1=["low","medium","high","xhigh"],RA=["none","minimal",...B1,"max"];function Qo(e){const t=e.trim();return t?{minimal:"Minimal",none:"None",low:"Low",medium:"Medium",high:"High",xhigh:"Extra high",max:"Max",ultra:"Ultra"}[t]??t:"Use model default"}function z3(e,t){const n=Gs(e),i=Gs(t==null?void 0:t.defaultReasoningEffort);return n?n===i?`${Qo(n)} (model default)`:Qo(n):i?`Auto (model default: ${Qo(i)})`:"Auto (follow model default)"}function OA(e,t=""){const n=Gs(e==null?void 0:e.defaultReasoningEffort),i=[];if(!e){i.push({value:"",label:"Use model default"});const f=Gs(t);return f&&Wv(f)&&i.push({value:f,label:`${Qo(f)} (configured)`}),i}const o=(Yv(e)??B1).filter(f=>!Gp(f));n&&!Gp(n)&&!o.includes(n)&&o.unshift(n),n&&o.includes(n)||i.push({value:"",label:"Use model default"});for(const f of o)i.push({value:f===n?"":f,label:f===n?`${Qo(f)} (model default)`:Qo(f)});return i}function D3(e,t){const n=Gs(e);if(!n||Gp(n))return"";const i=Gs(t==null?void 0:t.defaultReasoningEffort);if(i&&n===i)return"";if(!t)return Wv(n)?n:"";const l=Yv(t);return l!==null?l.includes(n)?n:"":B1.includes(n)?n:""}function _A(e,t,n){return n||e!==t?e:null}function Yv(e){if(!Array.isArray(e==null?void 0:e.supportedReasoningEfforts))return null;const t=[];for(const n of e.supportedReasoningEfforts){const i=Gs(n==null?void 0:n.reasoningEffort);i&&!t.includes(i)&&t.push(i)}return t}function Gs(e){return typeof e=="string"?e.trim():""}function Gp(e){return e.toLowerCase()==="ultra"}function Wv(e){return RA.includes(e)}function BA(e,t){return{textareaDisabled:!1,sendDisabled:t||!e.trim()}}function IA(e,t){return e.hasConversation?e.messageSubmitting?"blocked":e.hasActiveTurn||e.hasConfirmedCurrentTurn?t&&!e.complexTaskActive?"queue-turn":"steer-turn":"start-turn":"create-workspace"}function LA(e){return e.key!=="Enter"||!e.metaKey&&!e.ctrlKey||e.isComposing?null:{forceNewTurn:e.shiftKey}}function R3(e,t){return e.conversationId===t.conversationId&&e.version===t.version}function qA(e,t,n){return e===401&&!n&&t==="authentication_required"?"reauthenticate":"ignore"}const O3=15e3,_3=[1e3,2e3,5e3,1e4,15e3];function UA(e){return!e.workspaceRunning||e.streamLeaseActive||e.controllerActive?{kind:"none"}:e.currentTurnAbsent?e.retryAt!==null&&e.now>=e.retryAt?{kind:"probe",waitMs:O3}:{kind:"none"}:{kind:"probe",waitMs:O3}}function HA(e){const t=Math.min(Math.max(1,Math.floor(e))-1,_3.length-1);return _3[t]}function FA(e){const t=B3(e),n=B3(t.conversation),i=t.workspaceStatus??t.status??n.status;return i==="idle"||i==="error"||i==="done"||i==="initialization_failed"?i:"done"}function B3(e){return e&&typeof e=="object"?e:{}}function $A(e,t,n){return n?"running":e==="running"||e==="error"?e:t==="scheduled"?"waiting":e}function Lr(e,t){if(!e.deploymentId||!e.userId||!t)throw new Error("Browser storage requires deployment, user, and preference identities.");return["seele","v1",encodeURIComponent(e.deploymentId),encodeURIComponent(e.userId),encodeURIComponent(t)].join(":")}function I1(e,t){const n=[],i=new Set;for(const l of[...e,...t])i.has(l)||(i.add(l),n.push(l));return n}function I3(e,t,n){return I1([t,...e.filter(i=>i!==t)],n)}function GA(e,t){return e.filter(n=>n!==t)}function PA(e,t){const n=e.code==="ArrowUp"?-1:e.code==="ArrowDown"?1:null;return n!==null&&e.metaKey&&e.shiftKey&&e.leftShiftPressed&&!e.ctrlKey&&!e.altKey?{type:"move",direction:n}:t?e.key==="Escape"?{type:"cancel"}:e.code==="Space"&&!e.repeat?{type:"confirm"}:null:null}function Ls(e){return`${e.kind}:${e.id}`}function VA(e,t){return e.flatMap(n=>[{kind:"group",id:n.id},...t.has(n.id)?[]:n.conversations.map(i=>({kind:"workspace",id:i.id}))])}function YA(e,t,n,i){if(e.length===0)return null;const l=t?Ls(t):null;let o=l?e.findIndex(c=>Ls(c)===l):-1;return o<0&&n&&(o=e.findIndex(c=>c.kind==="workspace"&&c.id===n)),o<0?i>0?e[0]:e[e.length-1]:e[(o+i+e.length)%e.length]}function WA(e,t){return t??e}function XA(e,t){return e==="saved"||t==="accept"?"saved":"declined"}const KA=/^[a-z][a-z\d+.-]*:/i,QA=/^L([1-9]\d*)(?:C([1-9]\d*))?$/i;function ZA(e,t){const n=e.trim();if(!n||n.startsWith("#")||n.startsWith("?")||n.startsWith("/api/")||KA.test(n))return null;const i=n.indexOf("#"),l=i>=0?n.slice(0,i):n,o=i>=0?n.slice(i+1):"",c=l.indexOf("?"),f=c>=0?l.slice(0,c):l,h=JA(f);if(!h)return null;const m=o.match(QA);return{path:Xv(h,t),...m?{line:Number(m[1])}:{},...m!=null&&m[2]?{column:Number(m[2])}:{}}}function Xv(e,t){const n=e.replace(/\\/g,"/"),i=t.replace(/\\/g,"/").replace(/\/+$/,"");return n===i||!n.startsWith(`${i}/`)?n:n.slice(i.length+1)}function JA(e){const t=e.trim().replace(/^`+|`+$/g,"").replace(/^\.\//,"");return t||null}const Pp="seele:authentication-required",Vp="seele:deployment-status-required",Kv=12,eE=3e3,Qv="activeWorkspaceId",L1="workspaceOrder",Zv="workspaceGroupOrder",Jv="workspaceDrafts",e7="collapsedWorkspaceGroups",t7="sidebarWidth",L3=5,q3=275,tE=236,nE=420,U3="default",H3=300,rE=3,aE=10,iE=2,lE=13,sE=1.65,oE=20,uE=900;class Qa extends Error{constructor(n,i,l,o){super(n);xd(this,"detail");xd(this,"status");xd(this,"body");this.name="DetailedHttpError",this.detail=i,this.status=l,this.body=o}}const cE=[{value:"workspace-write",label:"Workspace"},{value:"danger-full-access",label:"System"}],bc={id:null,kind:"source",name:"",description:"",purpose:"",attention:"tracked",refreshPolicy:"manual",status:"draft",sourceCluesText:"",requiredEnvText:""};function q1(){var e;return((e=document.querySelector('meta[name="seele-public-base-path"]'))==null?void 0:e.content.replace(/\/?$/,"/"))??"/"}function Ne(e){return`${q1()}api/${e.replace(/^\/+/,"")}`}async function Fn(e,t){const n=await e.text().catch(()=>""),i=`Request failed with ${e.status}`,l=[`${t.method??"GET"} ${t.url}`,`HTTP ${e.status} ${e.statusText||""}`.trim(),n?`Response: ${n}`:"Response: <empty>"].join(`
344
- `);return new Qa(i,l,e.status,n)}function dt(e){return e instanceof Qa?{message:e.message,detail:e.detail}:e instanceof Error?{message:e.message}:{message:String(e)}}function _s(e){const t=dt(e);return t.detail?{message:t.message,detail:t.detail}:t.message}async function He(e,t){if(!e.ok)throw await Fn(e,t)}function dE(e){return e instanceof Qa&&e.status===410&&e.body.includes('"turn_not_active"')}function fE(e){return e instanceof Qa&&e.status===409&&e.body.includes('"turn_not_running"')}function hE(e){return e instanceof Qa&&e.status===409&&e.body.includes('"thread_capability_upgrade_required"')}function F3(e){return{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({message:e})}}async function mE(e){if(e.status!==409)return null;try{const t=await e.json();if(t.error==="turn_already_running"&&typeof t.turnId=="string")return t.turnId}catch{return null}return null}function U1(e){return Math.max(tE,Math.min(nE,Math.round(e)))}function pE(e){try{const t=window.localStorage.getItem(Lr(e,t7)),n=t?Number.parseInt(t,10):Number.NaN;return Number.isFinite(n)?U1(n):q3}catch{return q3}}function gE(e,t){try{window.localStorage.setItem(Lr(e,t7),String(U1(t)))}catch{}}function Vm(e){n7(e,()=>{e.scrollTop=Math.max(0,e.scrollHeight-e.clientHeight)})}function yE(e,t=48){return e.scrollHeight-e.scrollTop-e.clientHeight<=t}function vE(e){if(!e)return;const t=window.getComputedStyle(e),n=parseFloat(t.lineHeight)||24,i=parseFloat(t.paddingTop)||0,l=parseFloat(t.paddingBottom)||0,o=n*rE+i+l,c=n*aE+i+l;e.style.height="auto";const f=Math.min(Math.max(e.scrollHeight,o),c);e.style.height=`${f}px`,e.style.overflowY=e.scrollHeight>c?"auto":"hidden"}function xE(e){const t=e.split(/\r\n|\r|\n/).length;return Math.min(iE,Math.max(1,t+1))}function bE(e){return Math.ceil(xE(e)*lE*sE+oE)}function n7(e,t){const n=e.style.scrollBehavior;e.style.scrollBehavior="auto",t(),e.style.scrollBehavior=n}function wE(e){const t=e.getBoundingClientRect(),n=t.bottom-32,i=Array.from(e.querySelectorAll(".turn-group[data-turn-id]")),l=[...i].reverse().find(c=>{const f=c.getBoundingClientRect();return f.top<=n&&f.bottom>=t.top})??i[i.length-1]??null;if(!(l!=null&&l.dataset.turnId))return{anchorOffset:null,anchorTurnId:null};const o=l.getBoundingClientRect();return{anchorOffset:n-o.top,anchorTurnId:l.dataset.turnId}}function kE(e,t){return t?Array.from(e.querySelectorAll(".turn-group[data-turn-id]")).find(n=>n.dataset.turnId===t)??null:null}function $3(e,t){n7(e,()=>{const n=kE(e,t.anchorTurnId);if(n&&t.anchorOffset!==null){const l=e.getBoundingClientRect().bottom-32,c=n.getBoundingClientRect().top-(l-t.anchorOffset);Math.abs(c)>.5&&(e.scrollTop+=c);return}e.scrollTop=Math.max(0,e.scrollHeight-t.previousScrollHeight)})}function SE(e,t){let n=!1;const i=e.querySelector(".stream-inner")??e,l=typeof ResizeObserver>"u"?null:new ResizeObserver(()=>{n||$3(e,t)});$3(e,t),l==null||l.observe(i);const o=window.setTimeout(c,1200);function c(){n||(n=!0,l==null||l.disconnect(),window.clearTimeout(o))}return c}function CE(e){try{return window.localStorage.getItem(Lr(e,Qv))}catch{return null}}function Ym(e,t){const n=Lr(e,Qv);try{t?window.localStorage.setItem(n,t):window.localStorage.removeItem(n)}catch{}}function Wo(e){try{const t=window.localStorage.getItem(Lr(e,L1)),n=t?JSON.parse(t):[];return Array.isArray(n)?n.filter(i=>typeof i=="string"):[]}catch{return[]}}function r7(e){try{const t=window.localStorage.getItem(Lr(e,Zv)),n=t?JSON.parse(t):[];return Array.isArray(n)?n.filter(i=>typeof i=="string"):[]}catch{return[]}}function a7(e,t){try{window.localStorage.setItem(Lr(e,Zv),JSON.stringify(t))}catch{}}function Cc(e,t){try{window.localStorage.setItem(Lr(e,L1),JSON.stringify(t))}catch{}}function i7(e){try{const t=window.localStorage.getItem(Lr(e,Jv)),n=t?JSON.parse(t):{};return!n||typeof n!="object"||Array.isArray(n)?{}:Object.fromEntries(Object.entries(n).filter(i=>typeof i[0]=="string"&&typeof i[1]=="string"))}catch{return{}}}function jE(e,t){return t?i7(e)[t]??"":""}function Wm(e,t,n){if(t)try{const i=i7(e);n?i[t]=n:delete i[t],window.localStorage.setItem(Lr(e,Jv),JSON.stringify(i))}catch{}}function TE(e){try{const t=window.localStorage.getItem(Lr(e,e7)),n=t?JSON.parse(t):[];return new Set(Array.isArray(n)?n.filter(i=>typeof i=="string"):[])}catch{return new Set}}function Xm(e,t){try{window.localStorage.setItem(Lr(e,e7),JSON.stringify(Array.from(t)))}catch{}}function Ul(e,t){const n=Wo(e);if(n.length===0)return t;const i=new Map(n.map((l,o)=>[l,o]));return[...t].sort((l,o)=>{const c=i.get(l.id),f=i.get(o.id);return c!==void 0&&f!==void 0?c-f:c!==void 0?-1:f!==void 0?1:0})}function Dd(e,t){const n=r7(e);if(n.length===0)return t;const i=new Map(n.map((l,o)=>[l,o]));return[...t].sort((l,o)=>{const c=i.get(l.id),f=i.get(o.id);return c!==void 0&&f!==void 0?c-f:c!==void 0?-1:f!==void 0?1:l.createdAt.localeCompare(o.createdAt)})}function Rd(e,t){const n=Wo(e),i=I1(n,t.map(l=>l.id));JSON.stringify(i)!==JSON.stringify(n)&&Cc(e,i)}function Km(e,t){const n=new Set(t.map(o=>o.id)),i=r7(e).filter(o=>n.has(o)),l=t.map(o=>o.id).filter(o=>!i.includes(o));a7(e,[...i,...l])}function AE(e,t){const n=e.getBoundingClientRect(),i=n.top+n.height/2;return t<i?"before":"after"}function EE(e,t,n,i){if(t===n)return e;const l=e.findIndex(y=>y.id===t),o=e.findIndex(y=>y.id===n);if(l===-1||o===-1)return e;const c=[...e],[f]=c.splice(l,1),h=c.findIndex(y=>y.id===n),m=i==="before"?h:h+1;return c.splice(m,0,f),c}function NE(e,t,n){if(t===n)return e;const i=e.findIndex(h=>h.id===t),l=e.findIndex(h=>h.id===n);if(i===-1||l===-1)return e;const o=[...e],[c]=o.splice(i,1),f=o.findIndex(h=>h.id===n);return o.splice(f+1,0,c),o}function ME({authEnabled:e,currentUser:t,deploymentId:n,onLogout:i}){var $u,Ci,bl,Ts;const l=I.useMemo(()=>({deploymentId:n,userId:t.id}),[n,t.id]),[o,c]=I.useState(""),[f,h]=I.useState(new Set),[m,y]=I.useState([]),[v,k]=I.useState([]),[w,T]=I.useState(null),[E,q]=I.useState(null),[R,B]=I.useState("simple"),[F,Y]=I.useState(null),[te,_]=I.useState(null),[K,le]=I.useState(null),[J,G]=I.useState(!1),[ce,fe]=I.useState(!1),[Be,Ce]=I.useState({}),[ve,ee]=I.useState({}),[pe,De]=I.useState(null),[Ye,U]=I.useState([]),[O,Q]=I.useState(null),[z,de]=I.useState(!1),[Re,ne]=I.useState(null),[xe,oe]=I.useState("checking"),[Oe,st]=I.useState(null),[Ct,lt]=I.useState(!1),[Je,ut]=I.useState(null),[At,jn]=I.useState(!1),[Qe,Zt]=I.useState(null),[Pt,Wt]=I.useState(!1),[qr,Sr]=I.useState([]),[ua,Vt]=I.useState([]),[Ur,he]=I.useState({model:"",reasoningEffort:"",fastMode:!1,sandbox:"workspace-write"}),[we,Ue]=I.useState({profuseNotificationEnabled:!1,publicUrl:null}),[et,vt]=I.useState([]),[Tn,Hr]=I.useState(null),[zn,rn]=I.useState(null),[Dn,Dt]=I.useState(!1),[an,tr]=I.useState(null),[zf,Zl]=I.useState(!1),[Ks,Qs]=I.useState(null),[ai,Jl]=I.useState(!1),[Pi,cu]=I.useState({model:"",reasoningEffort:"",fastMode:!1,sandbox:"workspace-write"}),[nr,Na]=I.useState("global"),[Bt,es]=I.useState(null),[du,Vi]=I.useState(null),[fu,ii]=I.useState({model:"",reasoningEffort:"",fastMode:!1,sandbox:"workspace-write"}),[hu,mu]=I.useState({memory:"",items:[]}),[Kc,ca]=I.useState({memory:"",items:[]}),[An,Rn]=I.useState({memory:"",items:[]}),[Yi,li]=I.useState([]),[Wi,Xi]=I.useState(bc),[si,Fr]=I.useState({description:"",key:"",value:""}),[ts,da]=I.useState(null),[Ki,fa]=I.useState(()=>new Set),[Ma,ln]=I.useState(!1),[Zs,Js]=I.useState(!1),[oi,ui]=I.useState(!1),[za,eo]=I.useState(null),[pu,Df]=I.useState(!0),[to,ci]=I.useState(!1),[$r,Bn]=I.useState(!1),[Qc,Zc]=I.useState(!1),[Gr,Da]=I.useState(null),[no,Ra]=I.useState(null),[On,ro]=I.useState(null),[Pr,Cr]=I.useState(null),[rr,gu]=I.useState(null),[Qi,di]=I.useState(null),[ao,Jc]=I.useState(()=>new Set),[ns,fi]=I.useState(null),[yu,vu]=I.useState(null),[rs,ar]=I.useState(null),[ir,Vr]=I.useState(null),[Oa,Yr]=I.useState(null),[Zi,as]=I.useState(()=>TE(l)),[Jt,ha]=I.useState(null),[ma,is]=I.useState(()=>pE(l)),[Ji,_a]=I.useState(230),[pa,io]=I.useState(()=>Date.now()),[e0,lo]=I.useState(0),ls=I.useRef(null),ss=I.useRef(null),In=I.useRef(null),ga=I.useRef(null),ya=I.useRef(null),Ba=I.useRef(!0),t0=I.useRef(null),hi=I.useRef(null),os=I.useRef(null),mi=I.useRef(new Set),el=I.useRef(!1),so=I.useRef([]),us=I.useRef(null),n0=I.useRef(null),cs=I.useRef(new Map),pi=I.useRef(new Map),oo=I.useRef(new Set),uo=I.useRef(new Map),ds=I.useRef(new Map),tl=I.useRef(new Map),nl=I.useRef(new Set),va=I.useRef(null),lr=I.useRef(new Map),sr=I.useRef(new Map),rl=I.useRef(new Map),fs=I.useRef(new Set),al=I.useRef(null),co=I.useRef(null),xu=I.useRef(!1),bu=I.useRef(!1),hs=I.useRef(!1),We=m.find(x=>x.id===w),r0=(We==null?void 0:We.unreadTurnCount)??0,Wr=m.find(x=>x.id===za),dn=m.find(x=>x.id===Bt),wu=m.find(x=>x.id===ns),gi=I.useMemo(()=>{const j=Dd(l,v.length>0?v:[{id:"default",title:"Default",createdAt:"",updatedAt:""}]).map(V=>({id:V.id,title:V.title,conversations:[]})),N=new Map(j.map(V=>[V.id,V])),L=j[0];for(const V of m)(N.get(V.groupId)??L).conversations.push(V);return j.filter(V=>V.conversations.length>0||V.id!=="default")},[m,v]),fo=I.useMemo(()=>VA(gi,Zi),[Zi,gi]),Et=w!==null?Be[w]:null,il=(Et==null?void 0:Et.messages)??[],ll=(Et==null?void 0:Et.events)??[],xa=Yz(Vz(ll),w?ve[w]:null),ms=L7(xa),ho=(Et==null?void 0:Et.status)??(We==null?void 0:We.status)??"idle",Ia=Jp(We,ho),a0=za!==null?(($u=Be[za])==null?void 0:$u.status)??(Wr==null?void 0:Wr.status)??"idle":"idle",i0=Jp(Wr,a0),sl=w?sr.current.get(w)??null:null,yi=I.useMemo(()=>new Map(m.map(x=>[x.id,x.title])),[m]),ku=I.useMemo(()=>CN(il,ll,(Et==null?void 0:Et.turns)??[],(Et==null?void 0:Et.timelineNodes)??[],sl,yi),[sl,Et==null?void 0:Et.timelineNodes,Et==null?void 0:Et.turns,ll,il,yi]),Su=I.useMemo(()=>new Set(il.filter(x=>x.origin==="clone"&&x.turnId).map(x=>x.turnId)),[il]),mo=w!==null&&ao.has(w),l0=w!==null&&f.has(w),Cu=BA(o,l0),vi=sl?(Ci=ku.find(x=>Oc(x.turnIds,sl)))==null?void 0:Ci.activity:null,La=Ia==="running"||Ia==="initializing"||mo?vi&&!Rz(vi)?vi:{title:Ia==="initializing"?"Initializing clone":"Thinking",createdAt:new Date().toISOString(),tone:"running"}:null,Rf=!La&&Ia==="waiting"&&(We!=null&&We.nextWakeup)?{title:"Scheduled wakeup",detail:of(We.nextWakeup,pa),createdAt:We.nextWakeup.wakeAt,tone:"waiting"}:null,qa=La??Rf,s0=I.useMemo(()=>Pz(Object.values(Be)),[Be]),o0=v5(Re,s0);I.useEffect(()=>{Vn(),d0()},[]),I.useEffect(()=>()=>{ya.current!==null&&window.clearTimeout(ya.current)},[]),I.useEffect(()=>{ys(!1),ys(!0);const x=window.setInterval(()=>{ys(!0)},300*1e3);return()=>window.clearInterval(x)},[]),I.useEffect(()=>{const x=window.setInterval(()=>io(Date.now()),1e3);return()=>window.clearInterval(x)},[]),I.useEffect(()=>{fs.current=ao},[ao]),I.useEffect(()=>{us.current=w},[w]),I.useLayoutEffect(()=>{const x=n0.current;if(n0.current=w,!w||x===w)return;const j=window.requestAnimationFrame(()=>{const N=ga.current;N&&!N.disabled&&!document.querySelector('[aria-modal="true"]')&&N.focus({preventScroll:!0})});return()=>window.cancelAnimationFrame(j)},[w]),I.useEffect(()=>{so.current=m},[m]),I.useEffect(()=>{const x=Lr(l,L1),j=N=>{N.key===x&&y(L=>Ul(l,L))};return window.addEventListener("storage",j),()=>window.removeEventListener("storage",j)},[l]),I.useEffect(()=>{w&&Ym(l,w)},[w,l]),I.useLayoutEffect(()=>{if(!w||r0<=0)return;let x=!1;const j=async()=>{if(document.visibilityState==="visible"){y(L=>L.map(V=>V.id===w?{...V,unreadTurnCount:0}:V));try{await zM(w)}catch(L){x||console.error(L)}}},N=()=>void j();return j(),document.addEventListener("visibilitychange",N),()=>{x=!0,document.removeEventListener("visibilitychange",N)}},[w,r0]),I.useEffect(()=>{B("simple"),q(null),w&&(hn(w),xs(w))},[w]),I.useEffect(()=>{const x=window.setInterval(()=>void c0(),eE);return()=>window.clearInterval(x)},[]),I.useEffect(()=>{c(jE(l,w))},[w]),I.useEffect(()=>{if(!w)return;const x=UA({workspaceRunning:ho==="running",streamLeaseActive:mo,controllerActive:lr.current.has(w),currentTurnAbsent:oo.current.has(w),retryAt:ds.current.get(w)??null,now:Date.now()});x.kind==="probe"&&Hu(w,{waitMs:x.waitMs})},[w,mo,e0,ho]),I.useEffect(()=>()=>{for(const x of tl.current.values())window.clearTimeout(x);tl.current.clear()},[]),I.useEffect(()=>{if(!w)return;let x=!1;return rz(w).then(j=>{x||ee(N=>({...N,[w]:j}))}).catch(j=>console.error(j)),()=>{x=!0}},[w]),I.useEffect(()=>{!w&&nr==="workspace"&&Na("global")},[w,nr]),I.useEffect(()=>{var x;if(Pt){if(!Bt&&w){es(w);return}Bt&&!m.some(j=>j.id===Bt)&&es(w??((x=m[0])==null?void 0:x.id)??null)}},[w,m,Pt,Bt]),I.useEffect(()=>{if(!Pt||t.role!=="admin")return;const x=window.setInterval(()=>void ba(),5e3);return()=>window.clearInterval(x)},[t.role,Pt]),I.useEffect(()=>{!Pt||nr!=="workspace"||Rn({memory:(dn==null?void 0:dn.memory)??"",items:(dn==null?void 0:dn.memoryItems)??[]})},[nr,Pt,dn==null?void 0:dn.id,dn==null?void 0:dn.memory,dn==null?void 0:dn.memoryItems]),I.useEffect(()=>{if(!Ma)return;w&&Eu(w);const x=j=>{j.key==="Escape"&&ln(!1)};return window.addEventListener("keydown",x),()=>window.removeEventListener("keydown",x)},[w,Ma]),I.useEffect(()=>{if(!Pt)return;const x=j=>{j.key==="Escape"&&Wt(!1)};return window.addEventListener("keydown",x),()=>window.removeEventListener("keydown",x)},[Pt]),I.useEffect(()=>{var j;if(!Zs)return;if(za&&!m.some(N=>N.id===za)){eo(w??((j=m[0])==null?void 0:j.id)??null);return}const x=N=>{N.key==="Escape"&&(Gr?Da(null):Js(!1))};return window.addEventListener("keydown",x),()=>window.removeEventListener("keydown",x)},[w,Zs,Gr,za,m]),I.useEffect(()=>{if(!Pr)return;gu(null);const x=j=>{j.key==="Escape"&&Cr(null)};return window.addEventListener("keydown",x),()=>window.removeEventListener("keydown",x)},[Pr]),I.useEffect(()=>{const x=V=>{if(V.code==="ShiftLeft"){hs.current=!0;return}const ie=PA({code:V.code,key:V.key,metaKey:V.metaKey,shiftKey:V.shiftKey,ctrlKey:V.ctrlKey,altKey:V.altKey,leftShiftPressed:hs.current,repeat:V.repeat},Jt!==null);if((ie==null?void 0:ie.type)==="move"){V.preventDefault(),fe(!0),ha(Se=>YA(fo,Se,us.current,ie.direction));return}if((ie==null?void 0:ie.type)==="cancel"){ha(null);return}if(!((ie==null?void 0:ie.type)!=="confirm"||!Jt||Co(V.target))){if(V.preventDefault(),Jt.kind==="group"){js(Jt.id);return}$a(Jt.id),ha(null),fe(!1)}},j=V=>{V.code==="ShiftLeft"&&(hs.current=!1)},N=()=>{hs.current=!1},L=()=>ha(null);return window.addEventListener("keydown",x,!0),window.addEventListener("keyup",j,!0),window.addEventListener("blur",N),window.addEventListener("pointerdown",L),()=>{window.removeEventListener("keydown",x,!0),window.removeEventListener("keyup",j,!0),window.removeEventListener("blur",N),window.removeEventListener("pointerdown",L)}},[Jt,fo]),I.useEffect(()=>{Jt&&!fo.some(x=>Ls(x)===Ls(Jt))&&ha(null)},[Jt,fo]),I.useLayoutEffect(()=>{if(!Jt)return;const x=Ls(Jt),j=document.querySelector(`[data-keyboard-focus-key="${CSS.escape(x)}"]`);j==null||j.focus({preventScroll:!0}),j==null||j.scrollIntoView({block:"nearest"})},[Jt]),I.useLayoutEffect(()=>{vE(ga.current)},[o]),I.useLayoutEffect(()=>{const x=In.current;if(!x)return;const j=()=>{const L=x.getBoundingClientRect();_a(Math.ceil(L.height+44))};j();const N=typeof ResizeObserver>"u"?null:new ResizeObserver(j);return N==null||N.observe(x),window.addEventListener("resize",j),()=>{N==null||N.disconnect(),window.removeEventListener("resize",j)}},[]),I.useLayoutEffect(()=>{var ie,Se;const x=ss.current;if(!x)return;const j=t0.current!==w;t0.current=w,j&&((ie=va.current)==null||ie.call(va),va.current=null);const N=hi.current;if(N&&N.conversationId===w){(Se=va.current)==null||Se.call(va),va.current=SE(x,N),hi.current=null,Ba.current=!1;return}if(!j&&!Ba.current)return;Ba.current=!0,Vm(x);const L=requestAnimationFrame(()=>Vm(x)),V=window.setTimeout(()=>Vm(x),120);return()=>{cancelAnimationFrame(L),window.clearTimeout(V)}},[w,ll.length,il.length]);async function ju(){var j;const x=ss.current;x&&(Ba.current=yE(x),!(!w||!((j=Et==null?void 0:Et.history)!=null&&j.hasMoreBefore))&&(Et.loadingOlder||mi.current.has(w)||x.scrollTop>96||await ur(w)))}function ps(x){var N,L;if(x.history)return x.history;const j=((N=x.timelineNodes)==null?void 0:N.filter(V=>V.parentId===null).reduce((V,ie)=>V===null||ie.timelineAt<V.timelineAt||ie.timelineAt===V.timelineAt&&ie.sequence<V.sequence?ie:V,null))??null;return{hasMoreBefore:!1,oldestMessageCreatedAt:((L=x.messages[0])==null?void 0:L.createdAt)??null,oldestTimelineAt:(j==null?void 0:j.timelineAt)??null,oldestTimelineSequence:(j==null?void 0:j.sequence)??null,messageTotal:x.messages.length,eventTotal:x.events.length,loadedMessageCount:x.messages.length,loadedEventCount:x.events.length}}async function Ua(x){const j=new URL(x.url,window.location.href).toString();await navigator.clipboard.writeText(j),gu(x.url)}async function ol(x,j){await navigator.clipboard.writeText(j),di(x),ya.current!==null&&window.clearTimeout(ya.current),ya.current=window.setTimeout(()=>{di(null),ya.current=null},1800)}function Le(x,j,N){const L=Date.now();ro({id:L,tone:x,text:j,detail:N}),window.setTimeout(()=>{ro(V=>(V==null?void 0:V.id)===L?null:V)},N?8e3:2400)}function po(x){const j=tl.current.get(x);j!==void 0&&(window.clearTimeout(j),tl.current.delete(x))}function gs(x){oo.current.delete(x),uo.current.delete(x),ds.current.delete(x),nl.current.delete(x),po(x)}function u0(x){oo.current.add(x),uo.current.delete(x),ds.current.delete(x),nl.current.delete(x),po(x)}function Tu(x){oo.current.add(x),nl.current.delete(x);const j=(uo.current.get(x)??0)+1;uo.current.set(x,j);const N=HA(j);ds.current.set(x,Date.now()+N),po(x);const L=window.setTimeout(()=>{tl.current.delete(x),lo(V=>V+1)},N);tl.current.set(x,L)}function Au(x,j){j!=="running"&&gs(x)}async function Vn(){try{const[x,j]=await Promise.all([u5(),d5()]);oe("connected");const N=Dd(l,j);if(k(N),Km(l,N),x.length>0){const L=Ul(l,x),V=CE(l),ie=L.find(Se=>Se.id===V)??L[0];y(L),Rd(l,L),T(ie.id);return}y([]),Ym(l,null),T(null)}catch(x){console.error(x),oe("error")}}async function fn(){const[x,j]=await Promise.all([u5(),d5()]);for(const V of x)Au(V.id,V.status);const N=Ul(l,x),L=Dd(l,j);k(L),Km(l,L),y(N),Rd(l,N)}async function c0(){if(!el.current){el.current=!0;try{const x=await AM(),j=so.current,N=new Set(j.map(ze=>ze.id)),L=new Set(x.map(ze=>ze.id));if(N.size!==L.size||[...N].some(ze=>!L.has(ze))){await fn(),oe("connected");return}const V=us.current;for(const ze of x)Au(ze.id,ze.status);const ie=new Map(x.map(ze=>[ze.id,ze])),Se=V?ie.get(V)??null:null,Ge=Ul(l,j.map(ze=>{const _e=ie.get(ze.id);return _e?{...ze,status:_e.status,statusError:_e.statusError,nextWakeup:_e.nextWakeup,unreadTurnCount:_e.unreadTurnCount,updatedAt:_e.updatedAt}:ze}));y(Ge),Rd(l,Ge),oe("connected"),Se&&!fs.current.has(Se.id)&&kt(Se.id,ze=>({...ze,status:Se.status}))}catch(x){console.error(x),oe("error")}finally{el.current=!1}}}async function d0(){try{const x=await Sz();oe("connected"),De(x.version)}catch(x){console.error(x),oe("error")}}async function ys(x){try{const j=await Cz(x);j&&ne(N=>v5(N,j))}catch(j){console.error("runtime rate-limit refresh failed",j)}}async function f0(){try{const x=await _M();Sr(x),oe("connected")}catch(x){console.error(x),oe("error")}}async function go(x){try{const j=await BM(x);Vt(j),oe("connected")}catch(j){console.error(j),Vt([]),oe("error")}}async function Eu(x){try{const j=await IM(x);li(j),oe("connected")}catch(j){console.error(j),li([]),oe("error")}}async function ul(x){try{const j=await LM();he(j),cu(j),x||(Vi(null),ii(j)),oe("connected")}catch(j){console.error(j),oe("error")}}async function Nu(){if(t.role==="admin")try{Ue(await qM()),oe("connected")}catch(x){console.error(x),oe("error")}}async function Ha(x=!0){try{const j=await WM(x);vt(j.models),oe("connected"),j.refreshing&&window.setTimeout(()=>void Ha(!1),1e3)}catch(j){console.error(j),vt([]),oe("error")}}async function vs(){try{const x=await HM();Hr(x.codexVersion),rn(x.codexReleasedAt),oe("connected")}catch(x){console.error(x),Hr(null),rn(null),oe("error")}}async function yo(x=!1){x&&Jl(!0);try{const j=await XM(x);tr(j.job),Qs(j.latest),oe("connected"),j.job&&j.job.status!=="running"&&os.current===j.job.id&&(os.current=null,j.job.status==="succeeded"?(await Promise.all([Ha(),vs()]),Le("success",`Codex CLI updated to ${Mf(j.job.currentVersion)}`)):Le("error","Codex CLI update failed",j.job.error??void 0))}catch(j){console.error(j),oe("error")}finally{x&&Jl(!1)}}async function xi(){Zl(!0);try{const x=await KM();os.current=x.id,tr(x),oe("connected")}catch(x){console.error(x);const j=dt(x);Le("error","Unable to start Codex CLI update",j.detail??j.message)}finally{Zl(!1)}}I.useEffect(()=>{if(!Dn||(an==null?void 0:an.status)!=="running")return;const x=window.setInterval(()=>void yo(),1e3);return()=>window.clearInterval(x)},[Dn,an==null?void 0:an.id,an==null?void 0:an.status]);async function Fa(x){try{const j=await QM(x);Vi(j),ii(j.effective),oe("connected")}catch(j){console.error(j),Vi(null),oe("error")}}async function Mu(){try{const x=await ZM();mu(x),ca(x),oe("connected")}catch(x){console.error(x),oe("error")}}async function h0(){if(t.role!=="admin"){U([]);return}try{U(await xD()),oe("connected")}catch(x){console.error(x),oe("error")}}async function ba(){if(t.role!=="admin"){Q(null);return}de(!0);try{Q(await UM()),oe("connected")}catch(x){console.error(x),oe("error")}finally{de(!1)}}async function zu(x=Bt){const j=[f0(),ul(x),vs(),Ha(),Mu()];t.role==="admin"&&(j.push(h0()),j.push(ba()),j.push(Nu())),x&&(j.push(hn(x)),j.push(Fa(x)),j.push(go(x)),j.push(Eu(x))),await Promise.all(j)}function m0(){var j;const x=w??((j=m[0])==null?void 0:j.id)??null;fe(!1),es(x),Na(t.role==="admin"?"global":x?"workspace":"global"),Wt(!0),zu(x)}function p0(){var j;const x=w??((j=m[0])==null?void 0:j.id)??null;es(x),Na(x?"workspace":"global"),Wt(!0),zu(x)}function g0(){var j;fe(!1);const x=w??((j=m[0])==null?void 0:j.id)??null;eo(x),Ra(null),Da(null),Js(!0),x&&Of(x)}async function Of(x){try{const j=await C7(x);if(!j||j.status!=="running")return;ci(!0);const N=await j7(x,j);Ra(N),await hn(x),await fn(),N.warmupTurnId&&ks(x,N.warmupTurnId),Le("success","Full-history runtime reset completed")}catch(j){const N=dt(j);Le("error","Full-history runtime reset failed",N.message)}finally{ci(!1)}}function _f(x){es(x),Na("workspace"),hn(x),Fa(x),go(x),Eu(x),Xi(bc)}async function y0(x){x.preventDefault();try{if(nr==="workspace"&&Bt){const j=(dn==null?void 0:dn.status)==="running",N=await h5(Bt,lz(fu,Ur,du));Vi(N.settings),ii(N.settings.effective),hr(N.conversation),Le("success","Workspace settings saved",j?"The current turn keeps its existing settings. Changes apply from the next turn.":void 0)}else{const j=await JM(Pi);he(j),cu(j),Bt&&await Fa(Bt),Le("success","Global settings saved")}oe("connected")}catch(j){console.error(j),oe("error");const N=dt(j);Le("error","Failed to save runtime settings",N.detail??N.message)}}async function v0(x){try{const j=await ez(x);Ue(j),oe("connected"),Le("success","Deployment settings saved")}catch(j){console.error(j),oe("error");const N=dt(j);throw Le("error","Failed to save deployment settings",N.detail??N.message),j}}async function Du(){var N;const x=Wr;if(!x){Le("error","No workspace selected");return}const j=((N=Be[x.id])==null?void 0:N.status)??x.status;if(j==="running"||j==="initializing"){Le("error","Stop the running turn before resetting runtime");return}Zc(!0),Ra(null);try{const L=await p5(x.id);Da(L),oe("connected")}catch(L){console.error(L),oe("error");const V=dt(L);Le("error","Failed to preview runtime reset",V.detail??V.message)}finally{Zc(!1)}}async function jr(x){const j=Wr,N=Gr;if(!j||!N||N.conversationId!==j.id){Le("error","Reset preview is required");return}Bn(!0),Ra(null);try{const L=await m5(j.id,{warmup:pu,previewFingerprint:N.fingerprint,selectedEntryIds:x});Ra(L),Da(null),oe("connected"),await hn(j.id),await fn(),L.warmupTurnId&&ks(j.id,L.warmupTurnId),Le("success","Runtime thread reset")}catch(L){console.error(L),oe("error");const V=dt(L);Le("error","Failed to reset runtime thread",V.detail??V.message)}finally{Bn(!1)}}async function vo(){var L;const x=Wr;if(!x){Le("error","No workspace selected");return}const j=((L=Be[x.id])==null?void 0:L.status)??x.status;if(j==="running"||j==="initializing"){Le("error","Stop the running turn before clearing context");return}if(window.confirm(`Start "${x.title}" from a blank context?
349
+ `)?Math.max(0,t-1):t}function RA(e){const t=$p(e);return t.type==="add"?"add":t.type==="delete"?"delete":t.type==="move"||typeof t.move_path=="string"?"move":"update"}function M3(e){return e.replace(/\\/g,"/").replace(/\/+/g,"/")}function $p(e){return e&&typeof e=="object"?e:{}}const B1=["low","medium","high","xhigh"],OA=["none","minimal",...B1,"max"];function Qo(e){const t=e.trim();return t?{minimal:"Minimal",none:"None",low:"Low",medium:"Medium",high:"High",xhigh:"Extra high",max:"Max",ultra:"Ultra"}[t]??t:"Use model default"}function z3(e,t){const n=Gs(e),i=Gs(t==null?void 0:t.defaultReasoningEffort);return n?n===i?`${Qo(n)} (model default)`:Qo(n):i?`Auto (model default: ${Qo(i)})`:"Auto (follow model default)"}function _A(e,t=""){const n=Gs(e==null?void 0:e.defaultReasoningEffort),i=[];if(!e){i.push({value:"",label:"Use model default"});const f=Gs(t);return f&&Wv(f)&&i.push({value:f,label:`${Qo(f)} (configured)`}),i}const o=(Yv(e)??B1).filter(f=>!Gp(f));n&&!Gp(n)&&!o.includes(n)&&o.unshift(n),n&&o.includes(n)||i.push({value:"",label:"Use model default"});for(const f of o)i.push({value:f===n?"":f,label:f===n?`${Qo(f)} (model default)`:Qo(f)});return i}function D3(e,t){const n=Gs(e);if(!n||Gp(n))return"";const i=Gs(t==null?void 0:t.defaultReasoningEffort);if(i&&n===i)return"";if(!t)return Wv(n)?n:"";const l=Yv(t);return l!==null?l.includes(n)?n:"":B1.includes(n)?n:""}function BA(e,t,n){return n||e!==t?e:null}function Yv(e){if(!Array.isArray(e==null?void 0:e.supportedReasoningEfforts))return null;const t=[];for(const n of e.supportedReasoningEfforts){const i=Gs(n==null?void 0:n.reasoningEffort);i&&!t.includes(i)&&t.push(i)}return t}function Gs(e){return typeof e=="string"?e.trim():""}function Gp(e){return e.toLowerCase()==="ultra"}function Wv(e){return OA.includes(e)}function IA(e,t){return{textareaDisabled:!1,sendDisabled:t||!e.trim()}}function LA(e,t){return e.hasConversation?e.messageSubmitting?"blocked":e.hasActiveTurn||e.hasConfirmedCurrentTurn?t&&!e.complexTaskActive?"queue-turn":"steer-turn":"start-turn":"create-workspace"}function qA(e){return e.key!=="Enter"||!e.metaKey&&!e.ctrlKey||e.isComposing?null:{forceNewTurn:e.shiftKey}}function R3(e,t){return e.conversationId===t.conversationId&&e.version===t.version}function UA(e,t,n){return e===401&&!n&&t==="authentication_required"?"reauthenticate":"ignore"}const O3=15e3,_3=[1e3,2e3,5e3,1e4,15e3];function HA(e){return!e.workspaceRunning||e.streamLeaseActive||e.controllerActive?{kind:"none"}:e.currentTurnAbsent?e.retryAt!==null&&e.now>=e.retryAt?{kind:"probe",waitMs:O3}:{kind:"none"}:{kind:"probe",waitMs:O3}}function FA(e){const t=Math.min(Math.max(1,Math.floor(e))-1,_3.length-1);return _3[t]}function $A(e){const t=B3(e),n=B3(t.conversation),i=t.workspaceStatus??t.status??n.status;return i==="idle"||i==="error"||i==="done"||i==="initialization_failed"?i:"done"}function B3(e){return e&&typeof e=="object"?e:{}}function GA(e,t,n){return n?"running":e==="running"||e==="error"?e:t==="scheduled"?"waiting":e}function Lr(e,t){if(!e.deploymentId||!e.userId||!t)throw new Error("Browser storage requires deployment, user, and preference identities.");return["seele","v1",encodeURIComponent(e.deploymentId),encodeURIComponent(e.userId),encodeURIComponent(t)].join(":")}function I1(e,t){const n=[],i=new Set;for(const l of[...e,...t])i.has(l)||(i.add(l),n.push(l));return n}function I3(e,t,n){return I1([t,...e.filter(i=>i!==t)],n)}function PA(e,t){return e.filter(n=>n!==t)}function VA(e,t){const n=e.code==="ArrowUp"?-1:e.code==="ArrowDown"?1:null;return n!==null&&e.metaKey&&e.shiftKey&&e.leftShiftPressed&&!e.ctrlKey&&!e.altKey?{type:"move",direction:n}:t?e.key==="Escape"?{type:"cancel"}:e.code==="Space"&&!e.repeat?{type:"confirm"}:null:null}function Ls(e){return`${e.kind}:${e.id}`}function YA(e,t){return e.flatMap(n=>[{kind:"group",id:n.id},...t.has(n.id)?[]:n.conversations.map(i=>({kind:"workspace",id:i.id}))])}function WA(e,t,n,i){if(e.length===0)return null;const l=t?Ls(t):null;let o=l?e.findIndex(c=>Ls(c)===l):-1;return o<0&&n&&(o=e.findIndex(c=>c.kind==="workspace"&&c.id===n)),o<0?i>0?e[0]:e[e.length-1]:e[(o+i+e.length)%e.length]}function XA(e,t){return t??e}function KA(e,t){return e==="saved"||t==="accept"?"saved":"declined"}const QA=/^[a-z][a-z\d+.-]*:/i,ZA=/^L([1-9]\d*)(?:C([1-9]\d*))?$/i;function JA(e,t){const n=e.trim();if(!n||n.startsWith("#")||n.startsWith("?")||n.startsWith("/api/")||QA.test(n))return null;const i=n.indexOf("#"),l=i>=0?n.slice(0,i):n,o=i>=0?n.slice(i+1):"",c=l.indexOf("?"),f=c>=0?l.slice(0,c):l,h=eE(f);if(!h)return null;const m=o.match(ZA);return{path:Xv(h,t),...m?{line:Number(m[1])}:{},...m!=null&&m[2]?{column:Number(m[2])}:{}}}function Xv(e,t){const n=e.replace(/\\/g,"/"),i=t.replace(/\\/g,"/").replace(/\/+$/,"");return n===i||!n.startsWith(`${i}/`)?n:n.slice(i.length+1)}function eE(e){const t=e.trim().replace(/^`+|`+$/g,"").replace(/^\.\//,"");return t||null}const Pp="seele:authentication-required",Vp="seele:deployment-status-required",Kv=12,tE=3e3,Qv="activeWorkspaceId",L1="workspaceOrder",Zv="workspaceGroupOrder",Jv="workspaceDrafts",e7="collapsedWorkspaceGroups",t7="sidebarWidth",L3=5,q3=275,nE=236,rE=420,U3="default",H3=300,aE=3,iE=10,lE=2,sE=13,oE=1.65,uE=20,cE=900;class Qa extends Error{constructor(n,i,l,o){super(n);xd(this,"detail");xd(this,"status");xd(this,"body");this.name="DetailedHttpError",this.detail=i,this.status=l,this.body=o}}const dE=[{value:"workspace-write",label:"Workspace"},{value:"danger-full-access",label:"System"}],bc={id:null,kind:"source",name:"",description:"",purpose:"",attention:"tracked",refreshPolicy:"manual",status:"draft",sourceCluesText:"",requiredEnvText:""};function q1(){var e;return((e=document.querySelector('meta[name="seele-public-base-path"]'))==null?void 0:e.content.replace(/\/?$/,"/"))??"/"}function Ne(e){return`${q1()}api/${e.replace(/^\/+/,"")}`}async function Fn(e,t){const n=await e.text().catch(()=>""),i=`Request failed with ${e.status}`,l=[`${t.method??"GET"} ${t.url}`,`HTTP ${e.status} ${e.statusText||""}`.trim(),n?`Response: ${n}`:"Response: <empty>"].join(`
350
+ `);return new Qa(i,l,e.status,n)}function dt(e){return e instanceof Qa?{message:e.message,detail:e.detail}:e instanceof Error?{message:e.message}:{message:String(e)}}function _s(e){const t=dt(e);return t.detail?{message:t.message,detail:t.detail}:t.message}async function He(e,t){if(!e.ok)throw await Fn(e,t)}function fE(e){return e instanceof Qa&&e.status===410&&e.body.includes('"turn_not_active"')}function hE(e){return e instanceof Qa&&e.status===409&&e.body.includes('"turn_not_running"')}function mE(e){return e instanceof Qa&&e.status===409&&e.body.includes('"thread_capability_upgrade_required"')}function F3(e){return{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({message:e})}}async function pE(e){if(e.status!==409)return null;try{const t=await e.json();if(t.error==="turn_already_running"&&typeof t.turnId=="string")return t.turnId}catch{return null}return null}function U1(e){return Math.max(nE,Math.min(rE,Math.round(e)))}function gE(e){try{const t=window.localStorage.getItem(Lr(e,t7)),n=t?Number.parseInt(t,10):Number.NaN;return Number.isFinite(n)?U1(n):q3}catch{return q3}}function yE(e,t){try{window.localStorage.setItem(Lr(e,t7),String(U1(t)))}catch{}}function Vm(e){n7(e,()=>{e.scrollTop=Math.max(0,e.scrollHeight-e.clientHeight)})}function vE(e,t=48){return e.scrollHeight-e.scrollTop-e.clientHeight<=t}function xE(e){if(!e)return;const t=window.getComputedStyle(e),n=parseFloat(t.lineHeight)||24,i=parseFloat(t.paddingTop)||0,l=parseFloat(t.paddingBottom)||0,o=n*aE+i+l,c=n*iE+i+l;e.style.height="auto";const f=Math.min(Math.max(e.scrollHeight,o),c);e.style.height=`${f}px`,e.style.overflowY=e.scrollHeight>c?"auto":"hidden"}function bE(e){const t=e.split(/\r\n|\r|\n/).length;return Math.min(lE,Math.max(1,t+1))}function wE(e){return Math.ceil(bE(e)*sE*oE+uE)}function n7(e,t){const n=e.style.scrollBehavior;e.style.scrollBehavior="auto",t(),e.style.scrollBehavior=n}function kE(e){const t=e.getBoundingClientRect(),n=t.bottom-32,i=Array.from(e.querySelectorAll(".turn-group[data-turn-id]")),l=[...i].reverse().find(c=>{const f=c.getBoundingClientRect();return f.top<=n&&f.bottom>=t.top})??i[i.length-1]??null;if(!(l!=null&&l.dataset.turnId))return{anchorOffset:null,anchorTurnId:null};const o=l.getBoundingClientRect();return{anchorOffset:n-o.top,anchorTurnId:l.dataset.turnId}}function SE(e,t){return t?Array.from(e.querySelectorAll(".turn-group[data-turn-id]")).find(n=>n.dataset.turnId===t)??null:null}function $3(e,t){n7(e,()=>{const n=SE(e,t.anchorTurnId);if(n&&t.anchorOffset!==null){const l=e.getBoundingClientRect().bottom-32,c=n.getBoundingClientRect().top-(l-t.anchorOffset);Math.abs(c)>.5&&(e.scrollTop+=c);return}e.scrollTop=Math.max(0,e.scrollHeight-t.previousScrollHeight)})}function CE(e,t){let n=!1;const i=e.querySelector(".stream-inner")??e,l=typeof ResizeObserver>"u"?null:new ResizeObserver(()=>{n||$3(e,t)});$3(e,t),l==null||l.observe(i);const o=window.setTimeout(c,1200);function c(){n||(n=!0,l==null||l.disconnect(),window.clearTimeout(o))}return c}function jE(e){try{return window.localStorage.getItem(Lr(e,Qv))}catch{return null}}function Ym(e,t){const n=Lr(e,Qv);try{t?window.localStorage.setItem(n,t):window.localStorage.removeItem(n)}catch{}}function Wo(e){try{const t=window.localStorage.getItem(Lr(e,L1)),n=t?JSON.parse(t):[];return Array.isArray(n)?n.filter(i=>typeof i=="string"):[]}catch{return[]}}function r7(e){try{const t=window.localStorage.getItem(Lr(e,Zv)),n=t?JSON.parse(t):[];return Array.isArray(n)?n.filter(i=>typeof i=="string"):[]}catch{return[]}}function a7(e,t){try{window.localStorage.setItem(Lr(e,Zv),JSON.stringify(t))}catch{}}function Cc(e,t){try{window.localStorage.setItem(Lr(e,L1),JSON.stringify(t))}catch{}}function i7(e){try{const t=window.localStorage.getItem(Lr(e,Jv)),n=t?JSON.parse(t):{};return!n||typeof n!="object"||Array.isArray(n)?{}:Object.fromEntries(Object.entries(n).filter(i=>typeof i[0]=="string"&&typeof i[1]=="string"))}catch{return{}}}function TE(e,t){return t?i7(e)[t]??"":""}function Wm(e,t,n){if(t)try{const i=i7(e);n?i[t]=n:delete i[t],window.localStorage.setItem(Lr(e,Jv),JSON.stringify(i))}catch{}}function AE(e){try{const t=window.localStorage.getItem(Lr(e,e7)),n=t?JSON.parse(t):[];return new Set(Array.isArray(n)?n.filter(i=>typeof i=="string"):[])}catch{return new Set}}function Xm(e,t){try{window.localStorage.setItem(Lr(e,e7),JSON.stringify(Array.from(t)))}catch{}}function Ul(e,t){const n=Wo(e);if(n.length===0)return t;const i=new Map(n.map((l,o)=>[l,o]));return[...t].sort((l,o)=>{const c=i.get(l.id),f=i.get(o.id);return c!==void 0&&f!==void 0?c-f:c!==void 0?-1:f!==void 0?1:0})}function Dd(e,t){const n=r7(e);if(n.length===0)return t;const i=new Map(n.map((l,o)=>[l,o]));return[...t].sort((l,o)=>{const c=i.get(l.id),f=i.get(o.id);return c!==void 0&&f!==void 0?c-f:c!==void 0?-1:f!==void 0?1:l.createdAt.localeCompare(o.createdAt)})}function Rd(e,t){const n=Wo(e),i=I1(n,t.map(l=>l.id));JSON.stringify(i)!==JSON.stringify(n)&&Cc(e,i)}function Km(e,t){const n=new Set(t.map(o=>o.id)),i=r7(e).filter(o=>n.has(o)),l=t.map(o=>o.id).filter(o=>!i.includes(o));a7(e,[...i,...l])}function EE(e,t){const n=e.getBoundingClientRect(),i=n.top+n.height/2;return t<i?"before":"after"}function NE(e,t,n,i){if(t===n)return e;const l=e.findIndex(y=>y.id===t),o=e.findIndex(y=>y.id===n);if(l===-1||o===-1)return e;const c=[...e],[f]=c.splice(l,1),h=c.findIndex(y=>y.id===n),m=i==="before"?h:h+1;return c.splice(m,0,f),c}function ME(e,t,n){if(t===n)return e;const i=e.findIndex(h=>h.id===t),l=e.findIndex(h=>h.id===n);if(i===-1||l===-1)return e;const o=[...e],[c]=o.splice(i,1),f=o.findIndex(h=>h.id===n);return o.splice(f+1,0,c),o}function zE({authEnabled:e,currentUser:t,deploymentId:n,onLogout:i}){var $u,Ci,bl,Ts;const l=I.useMemo(()=>({deploymentId:n,userId:t.id}),[n,t.id]),[o,c]=I.useState(""),[f,h]=I.useState(new Set),[m,y]=I.useState([]),[v,k]=I.useState([]),[w,T]=I.useState(null),[E,q]=I.useState(null),[R,B]=I.useState("simple"),[F,Y]=I.useState(null),[te,_]=I.useState(null),[K,le]=I.useState(null),[J,G]=I.useState(!1),[ce,fe]=I.useState(!1),[Be,Ce]=I.useState({}),[ve,ee]=I.useState({}),[pe,De]=I.useState(null),[Ye,U]=I.useState([]),[O,Q]=I.useState(null),[z,de]=I.useState(!1),[Re,ne]=I.useState(null),[xe,oe]=I.useState("checking"),[Oe,st]=I.useState(null),[Ct,lt]=I.useState(!1),[Je,ut]=I.useState(null),[At,jn]=I.useState(!1),[Qe,Zt]=I.useState(null),[Pt,Wt]=I.useState(!1),[qr,Sr]=I.useState([]),[ua,Vt]=I.useState([]),[Ur,he]=I.useState({model:"",reasoningEffort:"",fastMode:!1,sandbox:"workspace-write"}),[we,Ue]=I.useState({profuseNotificationEnabled:!1,publicUrl:null}),[et,vt]=I.useState([]),[Tn,Hr]=I.useState(null),[zn,rn]=I.useState(null),[Dn,Dt]=I.useState(!1),[an,tr]=I.useState(null),[zf,Zl]=I.useState(!1),[Ks,Qs]=I.useState(null),[ai,Jl]=I.useState(!1),[Pi,cu]=I.useState({model:"",reasoningEffort:"",fastMode:!1,sandbox:"workspace-write"}),[nr,Na]=I.useState("global"),[Bt,es]=I.useState(null),[du,Vi]=I.useState(null),[fu,ii]=I.useState({model:"",reasoningEffort:"",fastMode:!1,sandbox:"workspace-write"}),[hu,mu]=I.useState({memory:"",items:[]}),[Kc,ca]=I.useState({memory:"",items:[]}),[An,Rn]=I.useState({memory:"",items:[]}),[Yi,li]=I.useState([]),[Wi,Xi]=I.useState(bc),[si,Fr]=I.useState({description:"",key:"",value:""}),[ts,da]=I.useState(null),[Ki,fa]=I.useState(()=>new Set),[Ma,ln]=I.useState(!1),[Zs,Js]=I.useState(!1),[oi,ui]=I.useState(!1),[za,eo]=I.useState(null),[pu,Df]=I.useState(!0),[to,ci]=I.useState(!1),[$r,Bn]=I.useState(!1),[Qc,Zc]=I.useState(!1),[Gr,Da]=I.useState(null),[no,Ra]=I.useState(null),[On,ro]=I.useState(null),[Pr,Cr]=I.useState(null),[rr,gu]=I.useState(null),[Qi,di]=I.useState(null),[ao,Jc]=I.useState(()=>new Set),[ns,fi]=I.useState(null),[yu,vu]=I.useState(null),[rs,ar]=I.useState(null),[ir,Vr]=I.useState(null),[Oa,Yr]=I.useState(null),[Zi,as]=I.useState(()=>AE(l)),[Jt,ha]=I.useState(null),[ma,is]=I.useState(()=>gE(l)),[Ji,_a]=I.useState(230),[pa,io]=I.useState(()=>Date.now()),[e0,lo]=I.useState(0),ls=I.useRef(null),ss=I.useRef(null),In=I.useRef(null),ga=I.useRef(null),ya=I.useRef(null),Ba=I.useRef(!0),t0=I.useRef(null),hi=I.useRef(null),os=I.useRef(null),mi=I.useRef(new Set),el=I.useRef(!1),so=I.useRef([]),us=I.useRef(null),n0=I.useRef(null),cs=I.useRef(new Map),pi=I.useRef(new Map),oo=I.useRef(new Set),uo=I.useRef(new Map),ds=I.useRef(new Map),tl=I.useRef(new Map),nl=I.useRef(new Set),va=I.useRef(null),lr=I.useRef(new Map),sr=I.useRef(new Map),rl=I.useRef(new Map),fs=I.useRef(new Set),al=I.useRef(null),co=I.useRef(null),xu=I.useRef(!1),bu=I.useRef(!1),hs=I.useRef(!1),We=m.find(x=>x.id===w),r0=(We==null?void 0:We.unreadTurnCount)??0,Wr=m.find(x=>x.id===za),dn=m.find(x=>x.id===Bt),wu=m.find(x=>x.id===ns),gi=I.useMemo(()=>{const j=Dd(l,v.length>0?v:[{id:"default",title:"Default",createdAt:"",updatedAt:""}]).map(V=>({id:V.id,title:V.title,conversations:[]})),N=new Map(j.map(V=>[V.id,V])),L=j[0];for(const V of m)(N.get(V.groupId)??L).conversations.push(V);return j.filter(V=>V.conversations.length>0||V.id!=="default")},[m,v]),fo=I.useMemo(()=>YA(gi,Zi),[Zi,gi]),Et=w!==null?Be[w]:null,il=(Et==null?void 0:Et.messages)??[],ll=(Et==null?void 0:Et.events)??[],xa=Wz(Yz(ll),w?ve[w]:null),ms=L7(xa),ho=(Et==null?void 0:Et.status)??(We==null?void 0:We.status)??"idle",Ia=Jp(We,ho),a0=za!==null?(($u=Be[za])==null?void 0:$u.status)??(Wr==null?void 0:Wr.status)??"idle":"idle",i0=Jp(Wr,a0),sl=w?sr.current.get(w)??null:null,yi=I.useMemo(()=>new Map(m.map(x=>[x.id,x.title])),[m]),ku=I.useMemo(()=>jN(il,ll,(Et==null?void 0:Et.turns)??[],(Et==null?void 0:Et.timelineNodes)??[],sl,yi),[sl,Et==null?void 0:Et.timelineNodes,Et==null?void 0:Et.turns,ll,il,yi]),Su=I.useMemo(()=>new Set(il.filter(x=>x.origin==="clone"&&x.turnId).map(x=>x.turnId)),[il]),mo=w!==null&&ao.has(w),l0=w!==null&&f.has(w),Cu=IA(o,l0),vi=sl?(Ci=ku.find(x=>Oc(x.turnIds,sl)))==null?void 0:Ci.activity:null,La=Ia==="running"||Ia==="initializing"||mo?vi&&!Oz(vi)?vi:{title:Ia==="initializing"?"Initializing clone":"Thinking",createdAt:new Date().toISOString(),tone:"running"}:null,Rf=!La&&Ia==="waiting"&&(We!=null&&We.nextWakeup)?{title:"Scheduled wakeup",detail:of(We.nextWakeup,pa),createdAt:We.nextWakeup.wakeAt,tone:"waiting"}:null,qa=La??Rf,s0=I.useMemo(()=>Vz(Object.values(Be)),[Be]),o0=v5(Re,s0);I.useEffect(()=>{Vn(),d0()},[]),I.useEffect(()=>()=>{ya.current!==null&&window.clearTimeout(ya.current)},[]),I.useEffect(()=>{ys(!1),ys(!0);const x=window.setInterval(()=>{ys(!0)},300*1e3);return()=>window.clearInterval(x)},[]),I.useEffect(()=>{const x=window.setInterval(()=>io(Date.now()),1e3);return()=>window.clearInterval(x)},[]),I.useEffect(()=>{fs.current=ao},[ao]),I.useEffect(()=>{us.current=w},[w]),I.useLayoutEffect(()=>{const x=n0.current;if(n0.current=w,!w||x===w)return;const j=window.requestAnimationFrame(()=>{const N=ga.current;N&&!N.disabled&&!document.querySelector('[aria-modal="true"]')&&N.focus({preventScroll:!0})});return()=>window.cancelAnimationFrame(j)},[w]),I.useEffect(()=>{so.current=m},[m]),I.useEffect(()=>{const x=Lr(l,L1),j=N=>{N.key===x&&y(L=>Ul(l,L))};return window.addEventListener("storage",j),()=>window.removeEventListener("storage",j)},[l]),I.useEffect(()=>{w&&Ym(l,w)},[w,l]),I.useLayoutEffect(()=>{if(!w||r0<=0)return;let x=!1;const j=async()=>{if(document.visibilityState==="visible"){y(L=>L.map(V=>V.id===w?{...V,unreadTurnCount:0}:V));try{await DM(w)}catch(L){x||console.error(L)}}},N=()=>void j();return j(),document.addEventListener("visibilitychange",N),()=>{x=!0,document.removeEventListener("visibilitychange",N)}},[w,r0]),I.useEffect(()=>{B("simple"),q(null),w&&(hn(w),xs(w))},[w]),I.useEffect(()=>{const x=window.setInterval(()=>void c0(),tE);return()=>window.clearInterval(x)},[]),I.useEffect(()=>{c(TE(l,w))},[w]),I.useEffect(()=>{if(!w)return;const x=HA({workspaceRunning:ho==="running",streamLeaseActive:mo,controllerActive:lr.current.has(w),currentTurnAbsent:oo.current.has(w),retryAt:ds.current.get(w)??null,now:Date.now()});x.kind==="probe"&&Hu(w,{waitMs:x.waitMs})},[w,mo,e0,ho]),I.useEffect(()=>()=>{for(const x of tl.current.values())window.clearTimeout(x);tl.current.clear()},[]),I.useEffect(()=>{if(!w)return;let x=!1;return az(w).then(j=>{x||ee(N=>({...N,[w]:j}))}).catch(j=>console.error(j)),()=>{x=!0}},[w]),I.useEffect(()=>{!w&&nr==="workspace"&&Na("global")},[w,nr]),I.useEffect(()=>{var x;if(Pt){if(!Bt&&w){es(w);return}Bt&&!m.some(j=>j.id===Bt)&&es(w??((x=m[0])==null?void 0:x.id)??null)}},[w,m,Pt,Bt]),I.useEffect(()=>{if(!Pt||t.role!=="admin")return;const x=window.setInterval(()=>void ba(),5e3);return()=>window.clearInterval(x)},[t.role,Pt]),I.useEffect(()=>{!Pt||nr!=="workspace"||Rn({memory:(dn==null?void 0:dn.memory)??"",items:(dn==null?void 0:dn.memoryItems)??[]})},[nr,Pt,dn==null?void 0:dn.id,dn==null?void 0:dn.memory,dn==null?void 0:dn.memoryItems]),I.useEffect(()=>{if(!Ma)return;w&&Eu(w);const x=j=>{j.key==="Escape"&&ln(!1)};return window.addEventListener("keydown",x),()=>window.removeEventListener("keydown",x)},[w,Ma]),I.useEffect(()=>{if(!Pt)return;const x=j=>{j.key==="Escape"&&Wt(!1)};return window.addEventListener("keydown",x),()=>window.removeEventListener("keydown",x)},[Pt]),I.useEffect(()=>{var j;if(!Zs)return;if(za&&!m.some(N=>N.id===za)){eo(w??((j=m[0])==null?void 0:j.id)??null);return}const x=N=>{N.key==="Escape"&&(Gr?Da(null):Js(!1))};return window.addEventListener("keydown",x),()=>window.removeEventListener("keydown",x)},[w,Zs,Gr,za,m]),I.useEffect(()=>{if(!Pr)return;gu(null);const x=j=>{j.key==="Escape"&&Cr(null)};return window.addEventListener("keydown",x),()=>window.removeEventListener("keydown",x)},[Pr]),I.useEffect(()=>{const x=V=>{if(V.code==="ShiftLeft"){hs.current=!0;return}const ie=VA({code:V.code,key:V.key,metaKey:V.metaKey,shiftKey:V.shiftKey,ctrlKey:V.ctrlKey,altKey:V.altKey,leftShiftPressed:hs.current,repeat:V.repeat},Jt!==null);if((ie==null?void 0:ie.type)==="move"){V.preventDefault(),fe(!0),ha(Se=>WA(fo,Se,us.current,ie.direction));return}if((ie==null?void 0:ie.type)==="cancel"){ha(null);return}if(!((ie==null?void 0:ie.type)!=="confirm"||!Jt||Co(V.target))){if(V.preventDefault(),Jt.kind==="group"){js(Jt.id);return}$a(Jt.id),ha(null),fe(!1)}},j=V=>{V.code==="ShiftLeft"&&(hs.current=!1)},N=()=>{hs.current=!1},L=()=>ha(null);return window.addEventListener("keydown",x,!0),window.addEventListener("keyup",j,!0),window.addEventListener("blur",N),window.addEventListener("pointerdown",L),()=>{window.removeEventListener("keydown",x,!0),window.removeEventListener("keyup",j,!0),window.removeEventListener("blur",N),window.removeEventListener("pointerdown",L)}},[Jt,fo]),I.useEffect(()=>{Jt&&!fo.some(x=>Ls(x)===Ls(Jt))&&ha(null)},[Jt,fo]),I.useLayoutEffect(()=>{if(!Jt)return;const x=Ls(Jt),j=document.querySelector(`[data-keyboard-focus-key="${CSS.escape(x)}"]`);j==null||j.focus({preventScroll:!0}),j==null||j.scrollIntoView({block:"nearest"})},[Jt]),I.useLayoutEffect(()=>{xE(ga.current)},[o]),I.useLayoutEffect(()=>{const x=In.current;if(!x)return;const j=()=>{const L=x.getBoundingClientRect();_a(Math.ceil(L.height+44))};j();const N=typeof ResizeObserver>"u"?null:new ResizeObserver(j);return N==null||N.observe(x),window.addEventListener("resize",j),()=>{N==null||N.disconnect(),window.removeEventListener("resize",j)}},[]),I.useLayoutEffect(()=>{var ie,Se;const x=ss.current;if(!x)return;const j=t0.current!==w;t0.current=w,j&&((ie=va.current)==null||ie.call(va),va.current=null);const N=hi.current;if(N&&N.conversationId===w){(Se=va.current)==null||Se.call(va),va.current=CE(x,N),hi.current=null,Ba.current=!1;return}if(!j&&!Ba.current)return;Ba.current=!0,Vm(x);const L=requestAnimationFrame(()=>Vm(x)),V=window.setTimeout(()=>Vm(x),120);return()=>{cancelAnimationFrame(L),window.clearTimeout(V)}},[w,ll.length,il.length]);async function ju(){var j;const x=ss.current;x&&(Ba.current=vE(x),!(!w||!((j=Et==null?void 0:Et.history)!=null&&j.hasMoreBefore))&&(Et.loadingOlder||mi.current.has(w)||x.scrollTop>96||await ur(w)))}function ps(x){var N,L;if(x.history)return x.history;const j=((N=x.timelineNodes)==null?void 0:N.filter(V=>V.parentId===null).reduce((V,ie)=>V===null||ie.timelineAt<V.timelineAt||ie.timelineAt===V.timelineAt&&ie.sequence<V.sequence?ie:V,null))??null;return{hasMoreBefore:!1,oldestMessageCreatedAt:((L=x.messages[0])==null?void 0:L.createdAt)??null,oldestTimelineAt:(j==null?void 0:j.timelineAt)??null,oldestTimelineSequence:(j==null?void 0:j.sequence)??null,messageTotal:x.messages.length,eventTotal:x.events.length,loadedMessageCount:x.messages.length,loadedEventCount:x.events.length}}async function Ua(x){const j=new URL(x.url,window.location.href).toString();await navigator.clipboard.writeText(j),gu(x.url)}async function ol(x,j){await navigator.clipboard.writeText(j),di(x),ya.current!==null&&window.clearTimeout(ya.current),ya.current=window.setTimeout(()=>{di(null),ya.current=null},1800)}function Le(x,j,N){const L=Date.now();ro({id:L,tone:x,text:j,detail:N}),window.setTimeout(()=>{ro(V=>(V==null?void 0:V.id)===L?null:V)},N?8e3:2400)}function po(x){const j=tl.current.get(x);j!==void 0&&(window.clearTimeout(j),tl.current.delete(x))}function gs(x){oo.current.delete(x),uo.current.delete(x),ds.current.delete(x),nl.current.delete(x),po(x)}function u0(x){oo.current.add(x),uo.current.delete(x),ds.current.delete(x),nl.current.delete(x),po(x)}function Tu(x){oo.current.add(x),nl.current.delete(x);const j=(uo.current.get(x)??0)+1;uo.current.set(x,j);const N=FA(j);ds.current.set(x,Date.now()+N),po(x);const L=window.setTimeout(()=>{tl.current.delete(x),lo(V=>V+1)},N);tl.current.set(x,L)}function Au(x,j){j!=="running"&&gs(x)}async function Vn(){try{const[x,j]=await Promise.all([u5(),d5()]);oe("connected");const N=Dd(l,j);if(k(N),Km(l,N),x.length>0){const L=Ul(l,x),V=jE(l),ie=L.find(Se=>Se.id===V)??L[0];y(L),Rd(l,L),T(ie.id);return}y([]),Ym(l,null),T(null)}catch(x){console.error(x),oe("error")}}async function fn(){const[x,j]=await Promise.all([u5(),d5()]);for(const V of x)Au(V.id,V.status);const N=Ul(l,x),L=Dd(l,j);k(L),Km(l,L),y(N),Rd(l,N)}async function c0(){if(!el.current){el.current=!0;try{const x=await EM(),j=so.current,N=new Set(j.map(ze=>ze.id)),L=new Set(x.map(ze=>ze.id));if(N.size!==L.size||[...N].some(ze=>!L.has(ze))){await fn(),oe("connected");return}const V=us.current;for(const ze of x)Au(ze.id,ze.status);const ie=new Map(x.map(ze=>[ze.id,ze])),Se=V?ie.get(V)??null:null,Ge=Ul(l,j.map(ze=>{const _e=ie.get(ze.id);return _e?{...ze,status:_e.status,statusError:_e.statusError,nextWakeup:_e.nextWakeup,unreadTurnCount:_e.unreadTurnCount,updatedAt:_e.updatedAt}:ze}));y(Ge),Rd(l,Ge),oe("connected"),Se&&!fs.current.has(Se.id)&&kt(Se.id,ze=>({...ze,status:Se.status}))}catch(x){console.error(x),oe("error")}finally{el.current=!1}}}async function d0(){try{const x=await Cz();oe("connected"),De(x.version)}catch(x){console.error(x),oe("error")}}async function ys(x){try{const j=await jz(x);j&&ne(N=>v5(N,j))}catch(j){console.error("runtime rate-limit refresh failed",j)}}async function f0(){try{const x=await BM();Sr(x),oe("connected")}catch(x){console.error(x),oe("error")}}async function go(x){try{const j=await IM(x);Vt(j),oe("connected")}catch(j){console.error(j),Vt([]),oe("error")}}async function Eu(x){try{const j=await LM(x);li(j),oe("connected")}catch(j){console.error(j),li([]),oe("error")}}async function ul(x){try{const j=await qM();he(j),cu(j),x||(Vi(null),ii(j)),oe("connected")}catch(j){console.error(j),oe("error")}}async function Nu(){if(t.role==="admin")try{Ue(await UM()),oe("connected")}catch(x){console.error(x),oe("error")}}async function Ha(x=!0){try{const j=await XM(x);vt(j.models),oe("connected"),j.refreshing&&window.setTimeout(()=>void Ha(!1),1e3)}catch(j){console.error(j),vt([]),oe("error")}}async function vs(){try{const x=await FM();Hr(x.codexVersion),rn(x.codexReleasedAt),oe("connected")}catch(x){console.error(x),Hr(null),rn(null),oe("error")}}async function yo(x=!1){x&&Jl(!0);try{const j=await KM(x);tr(j.job),Qs(j.latest),oe("connected"),j.job&&j.job.status!=="running"&&os.current===j.job.id&&(os.current=null,j.job.status==="succeeded"?(await Promise.all([Ha(),vs()]),Le("success",`Codex CLI updated to ${Mf(j.job.currentVersion)}`)):Le("error","Codex CLI update failed",j.job.error??void 0))}catch(j){console.error(j),oe("error")}finally{x&&Jl(!1)}}async function xi(){Zl(!0);try{const x=await QM();os.current=x.id,tr(x),oe("connected")}catch(x){console.error(x);const j=dt(x);Le("error","Unable to start Codex CLI update",j.detail??j.message)}finally{Zl(!1)}}I.useEffect(()=>{if(!Dn||(an==null?void 0:an.status)!=="running")return;const x=window.setInterval(()=>void yo(),1e3);return()=>window.clearInterval(x)},[Dn,an==null?void 0:an.id,an==null?void 0:an.status]);async function Fa(x){try{const j=await ZM(x);Vi(j),ii(j.effective),oe("connected")}catch(j){console.error(j),Vi(null),oe("error")}}async function Mu(){try{const x=await JM();mu(x),ca(x),oe("connected")}catch(x){console.error(x),oe("error")}}async function h0(){if(t.role!=="admin"){U([]);return}try{U(await bD()),oe("connected")}catch(x){console.error(x),oe("error")}}async function ba(){if(t.role!=="admin"){Q(null);return}de(!0);try{Q(await HM()),oe("connected")}catch(x){console.error(x),oe("error")}finally{de(!1)}}async function zu(x=Bt){const j=[f0(),ul(x),vs(),Ha(),Mu()];t.role==="admin"&&(j.push(h0()),j.push(ba()),j.push(Nu())),x&&(j.push(hn(x)),j.push(Fa(x)),j.push(go(x)),j.push(Eu(x))),await Promise.all(j)}function m0(){var j;const x=w??((j=m[0])==null?void 0:j.id)??null;fe(!1),es(x),Na(t.role==="admin"?"global":x?"workspace":"global"),Wt(!0),zu(x)}function p0(){var j;const x=w??((j=m[0])==null?void 0:j.id)??null;es(x),Na(x?"workspace":"global"),Wt(!0),zu(x)}function g0(){var j;fe(!1);const x=w??((j=m[0])==null?void 0:j.id)??null;eo(x),Ra(null),Da(null),Js(!0),x&&Of(x)}async function Of(x){try{const j=await C7(x);if(!j||j.status!=="running")return;ci(!0);const N=await j7(x,j);Ra(N),await hn(x),await fn(),N.warmupTurnId&&ks(x,N.warmupTurnId),Le("success","Full-history runtime reset completed")}catch(j){const N=dt(j);Le("error","Full-history runtime reset failed",N.message)}finally{ci(!1)}}function _f(x){es(x),Na("workspace"),hn(x),Fa(x),go(x),Eu(x),Xi(bc)}async function y0(x){x.preventDefault();try{if(nr==="workspace"&&Bt){const j=(dn==null?void 0:dn.status)==="running",N=await h5(Bt,sz(fu,Ur,du));Vi(N.settings),ii(N.settings.effective),hr(N.conversation),Le("success","Workspace settings saved",j?"The current turn keeps its existing settings. Changes apply from the next turn.":void 0)}else{const j=await ez(Pi);he(j),cu(j),Bt&&await Fa(Bt),Le("success","Global settings saved")}oe("connected")}catch(j){console.error(j),oe("error");const N=dt(j);Le("error","Failed to save runtime settings",N.detail??N.message)}}async function v0(x){try{const j=await tz(x);Ue(j),oe("connected"),Le("success","Deployment settings saved")}catch(j){console.error(j),oe("error");const N=dt(j);throw Le("error","Failed to save deployment settings",N.detail??N.message),j}}async function Du(){var N;const x=Wr;if(!x){Le("error","No workspace selected");return}const j=((N=Be[x.id])==null?void 0:N.status)??x.status;if(j==="running"||j==="initializing"){Le("error","Stop the running turn before resetting runtime");return}Zc(!0),Ra(null);try{const L=await p5(x.id);Da(L),oe("connected")}catch(L){console.error(L),oe("error");const V=dt(L);Le("error","Failed to preview runtime reset",V.detail??V.message)}finally{Zc(!1)}}async function jr(x){const j=Wr,N=Gr;if(!j||!N||N.conversationId!==j.id){Le("error","Reset preview is required");return}Bn(!0),Ra(null);try{const L=await m5(j.id,{warmup:pu,previewFingerprint:N.fingerprint,selectedEntryIds:x});Ra(L),Da(null),oe("connected"),await hn(j.id),await fn(),L.warmupTurnId&&ks(j.id,L.warmupTurnId),Le("success","Runtime thread reset")}catch(L){console.error(L),oe("error");const V=dt(L);Le("error","Failed to reset runtime thread",V.detail??V.message)}finally{Bn(!1)}}async function vo(){var L;const x=Wr;if(!x){Le("error","No workspace selected");return}const j=((L=Be[x.id])==null?void 0:L.status)??x.status;if(j==="running"||j==="initializing"){Le("error","Stop the running turn before clearing context");return}if(window.confirm(`Start "${x.title}" from a blank context?
345
351
 
346
- This clears Workspace Memory and creates a new Codex thread without restored history. Workspace files, Timeline, metadata, and Base Memory remain intact.`)){ci(!0),Ra(null);try{const V=await p5(x.id),ie=await m5(x.id,{warmup:!1,previewFingerprint:V.fingerprint,selectedEntryIds:[],clearWorkspaceMemory:!0,saveSelection:!1});Ra(ie),Da(null),Bt===x.id&&Rn({memory:"",items:[]}),oe("connected"),await hn(x.id),await fn(),Le("success","Workspace started from blank context")}catch(V){console.error(V),oe("error");const ie=dt(V);Le("error","Failed to clear workspace context",ie.detail??ie.message)}finally{ci(!1)}}}async function or(x){const j=Wr,N=Gr;if(!j||!N||N.conversationId!==j.id)throw new Error("Reset preview is no longer current.");try{await tz(j.id,{previewFingerprint:N.fingerprint,selectedEntryIds:x}),oe("connected")}catch(L){console.error(L),oe("error");const V=dt(L);throw Le("error","Failed to save reset defaults",V.detail??V.message),L}}async function cl(x,j){try{const N=await h5(x,{[j]:null});Vi(N.settings),ii(N.settings.effective),hr(N.conversation),oe("connected"),Le("success","Workspace override reset")}catch(N){console.error(N),oe("error"),Le("error","Failed to reset workspace override")}}async function Ru(x){try{const j=await hz({memory:fz(x),items:x});return mu(j),ca(j),oe("connected"),Le("success","Base memory saved"),j.items}catch(j){throw console.error(j),oe("error"),Le("error","Failed to save memory"),j}}async function xo(x,j){try{const N=await qd(x,{memoryItems:j});return hr(N),Rn({memory:N.memory,items:N.memoryItems}),oe("connected"),Le("success","Workspace memory saved"),N.memoryItems}catch(N){throw console.error(N),oe("error"),Le("error","Failed to save memory"),N}}async function bo(x){x.preventDefault();const j=si.key.trim();if(j)try{if(nr==="workspace"&&Bt){const N=await pz(Bt,j,si.value,si.description);Vt(L=>[...L.filter(V=>V.key!==N.variable.key),N.variable].sort((V,ie)=>V.key.localeCompare(ie.key))),hr(N.conversation)}else{const N=await mz(j,si.value,si.description);Sr(L=>[...L.filter(V=>V.key!==N.key),N].sort((V,ie)=>V.key.localeCompare(ie.key)))}Le("success",nr==="workspace"?"Workspace environment saved":"Base environment saved"),Fr({description:"",key:"",value:""}),da(null),fa(N=>{const L=new Set(N);return L.delete(j),L}),oe("connected")}catch(N){console.error(N),oe("error"),Le("error","Failed to save environment")}}async function Ou(x){try{if(nr==="workspace"&&Bt){const j=await xz(Bt,x);Vt(N=>N.filter(L=>L.key!==x)),hr(j)}else await vz(x),Sr(j=>j.filter(N=>N.key!==x));ts===x&&(Fr({description:"",key:"",value:""}),da(null),fa(j=>{const N=new Set(j);return N.delete(x),N})),oe("connected"),Le("success",nr==="workspace"?"Workspace environment deleted":"Base environment deleted")}catch(j){console.error(j),oe("error"),Le("error","Failed to delete environment")}}async function bi(x,j){if(j.preventDefault(),!Wi.name.trim()){Le("error","Knowledge name is required");return}const N=sz(Wi);try{const L=Wi.id?await wz(x,Wi.id,N):await bz(x,N);li(V=>[...V.filter(ie=>ie.id!==L.id),L].sort(g5)),Xi(bc),oe("connected"),Le("success","Workspace knowledge saved")}catch(L){console.error(L),oe("error"),Le("error","Failed to save workspace knowledge")}}async function x0(x,j){try{await kz(x,j),li(N=>N.filter(L=>L.id!==j)),Wi.id===j&&Xi(bc),oe("connected"),Le("success","Workspace knowledge deleted")}catch(N){console.error(N),oe("error"),Le("error","Failed to delete workspace knowledge")}}function wo(x){Na("workspace"),Xi(oz(x))}function dl(x){Fr({description:x.description,key:x.key,value:""}),da(x.key),fa(j=>{const N=new Set(j);return N.delete(x.key),N}),ko(x.key,{preserveTypedValue:!0})}function Bf(){const x=ts;Fr({description:"",key:"",value:""}),da(null),x&&fa(j=>{const N=new Set(j);return N.delete(x),N})}async function Yn(x){await ko(x)}async function ko(x,j={}){try{const N=nr==="workspace"&&Bt?await yz(Bt,x):await gz(x);Fr(L=>L.key===x&&(!j.preserveTypedValue||L.value.length===0)?{...L,value:N}:L),fa(L=>new Set(L).add(x)),oe("connected")}catch(N){console.error(N),oe("error")}}async function hn(x){const j=await sp(x);T0(j)}async function _u(x){try{const j=await sp(x);A0(j)}catch(j){console.warn("Failed to synchronize timeline before turn stream",j)}}async function xs(x){try{q(await Tz(x))}catch(j){console.error(j)}}async function Tr(x){if(w)try{const j=await Ez(w,x);q(x==="end"?null:j),x==="end"&&B("simple"),Le("success",x==="start"?"Complex task started":`Task ${x} accepted`),(x==="start"||x==="resume")&&Hu(w,{waitMs:15e3}),await fn()}catch(j){Le("error","Complex task control failed",dt(j).detail??dt(j).message)}}async function wa(x){if(w)try{Y(await Az(w,x))}catch(j){const N=dt(j);Le("error","Failed to load complex task",N.detail??N.message)}}function b0(){We&&le({sourceId:We.id,name:`${We.title} - Clone`,groupId:We.groupId})}async function Bu(x){if(x.preventDefault(),!(!K||!K.name.trim())){G(!0);try{const j=await Nz(K.sourceId,K.name.trim(),K.groupId);y(N=>{const L=[j.conversation,...N];return Cc(l,I3(Wo(l),j.conversation.id,L.map(V=>V.id))),Ul(l,L)}),T(j.conversation.id),le(null),fe(!1),Le(j.error?"error":"success",j.error?"Clone created, initialization failed":"Workspace cloned",j.error??void 0)}catch(j){Le("error","Clone failed",dt(j).detail??dt(j).message)}finally{G(!1)}}}async function w0(){if(We)try{const x=await Mz(We.id);hr(x.conversation),Le(x.error?"error":"success",x.error?"Clone retry failed":"Clone initialization restarted",x.error??void 0)}catch(x){Le("error","Clone retry failed",dt(x).detail??dt(x).message)}}async function ur(x,j={}){var ze,_e,Rt;const N=Be[x],L=(ze=N==null?void 0:N.history)==null?void 0:ze.oldestTimelineAt,V=(_e=N==null?void 0:N.history)==null?void 0:_e.oldestTimelineSequence,ie=L&&V!==null&&V!==void 0?`${L}|${V}`:V==null?(Rt=N==null?void 0:N.history)==null?void 0:Rt.oldestMessageCreatedAt:String(V),Se=ss.current;if(!ie||!Se)return;if(j.preserveAnchor??!0){const St=wE(Se);hi.current={anchorOffset:St.anchorOffset,conversationId:x,previousScrollHeight:Se.scrollHeight,anchorTurnId:St.anchorTurnId}}else hi.current=null;mi.current.add(x),kt(x,St=>({...St,loadingOlder:!0}));try{const St=await sp(x,{before:ie,limit:Kv});qf(St)}catch(St){console.error(St),hi.current=null}finally{mi.current.delete(x),kt(x,St=>({...St,loadingOlder:!1}))}}async function fl(x,j){const N=await jz(x,j||void 0);y(L=>{const V=[N,...L];return Cc(l,I3(Wo(l),N.id,V.map(ie=>ie.id))),Ul(l,V)}),T(N.id),fe(!1)}function $a(x){x!==us.current&&(Ce(j=>{if(!(x in j))return j;const N={...j};return delete N[x],N}),T(x))}function So(){fe(!1),Zt({mode:"create",groupId:null,title:""})}function hl(x){Zt({mode:"rename",groupId:x.id,title:x.title})}function Wn(){var x;fe(!1),st({mode:"create",conversationId:null,title:"",groupId:(We==null?void 0:We.groupId)??((x=v[0])==null?void 0:x.id)})}async function cr(x){var j;if(x.status!=="running"){jn(!0);try{await Dz(x.id),Ce(L=>{const V={...L};return delete V[x.id],V});const N=so.current.filter(L=>L.id!==x.id);if(Cc(l,GA(Wo(l),x.id)),Wm(l,x.id,""),y(N),w===x.id){const L=((j=N[0])==null?void 0:j.id)??null;Ym(l,L),T(L)}(Oe==null?void 0:Oe.conversationId)===x.id&&Ln(),ut(null),Le("success","Workspace moved to recycle")}catch(N){const L=dt(N);Le("error","Failed to move workspace to recycle",L.detail??L.message)}finally{jn(!1)}}}async function Ga(x){if(!(x.id===U3||!window.confirm(`Delete group "${x.title}"?
352
+ This clears Workspace Memory and creates a new Codex thread without restored history. Workspace files, Timeline, metadata, and Base Memory remain intact.`)){ci(!0),Ra(null);try{const V=await p5(x.id),ie=await m5(x.id,{warmup:!1,previewFingerprint:V.fingerprint,selectedEntryIds:[],clearWorkspaceMemory:!0,saveSelection:!1});Ra(ie),Da(null),Bt===x.id&&Rn({memory:"",items:[]}),oe("connected"),await hn(x.id),await fn(),Le("success","Workspace started from blank context")}catch(V){console.error(V),oe("error");const ie=dt(V);Le("error","Failed to clear workspace context",ie.detail??ie.message)}finally{ci(!1)}}}async function or(x){const j=Wr,N=Gr;if(!j||!N||N.conversationId!==j.id)throw new Error("Reset preview is no longer current.");try{await nz(j.id,{previewFingerprint:N.fingerprint,selectedEntryIds:x}),oe("connected")}catch(L){console.error(L),oe("error");const V=dt(L);throw Le("error","Failed to save reset defaults",V.detail??V.message),L}}async function cl(x,j){try{const N=await h5(x,{[j]:null});Vi(N.settings),ii(N.settings.effective),hr(N.conversation),oe("connected"),Le("success","Workspace override reset")}catch(N){console.error(N),oe("error"),Le("error","Failed to reset workspace override")}}async function Ru(x){try{const j=await mz({memory:hz(x),items:x});return mu(j),ca(j),oe("connected"),Le("success","Base memory saved"),j.items}catch(j){throw console.error(j),oe("error"),Le("error","Failed to save memory"),j}}async function xo(x,j){try{const N=await qd(x,{memoryItems:j});return hr(N),Rn({memory:N.memory,items:N.memoryItems}),oe("connected"),Le("success","Workspace memory saved"),N.memoryItems}catch(N){throw console.error(N),oe("error"),Le("error","Failed to save memory"),N}}async function bo(x){x.preventDefault();const j=si.key.trim();if(j)try{if(nr==="workspace"&&Bt){const N=await gz(Bt,j,si.value,si.description);Vt(L=>[...L.filter(V=>V.key!==N.variable.key),N.variable].sort((V,ie)=>V.key.localeCompare(ie.key))),hr(N.conversation)}else{const N=await pz(j,si.value,si.description);Sr(L=>[...L.filter(V=>V.key!==N.key),N].sort((V,ie)=>V.key.localeCompare(ie.key)))}Le("success",nr==="workspace"?"Workspace environment saved":"Base environment saved"),Fr({description:"",key:"",value:""}),da(null),fa(N=>{const L=new Set(N);return L.delete(j),L}),oe("connected")}catch(N){console.error(N),oe("error"),Le("error","Failed to save environment")}}async function Ou(x){try{if(nr==="workspace"&&Bt){const j=await bz(Bt,x);Vt(N=>N.filter(L=>L.key!==x)),hr(j)}else await xz(x),Sr(j=>j.filter(N=>N.key!==x));ts===x&&(Fr({description:"",key:"",value:""}),da(null),fa(j=>{const N=new Set(j);return N.delete(x),N})),oe("connected"),Le("success",nr==="workspace"?"Workspace environment deleted":"Base environment deleted")}catch(j){console.error(j),oe("error"),Le("error","Failed to delete environment")}}async function bi(x,j){if(j.preventDefault(),!Wi.name.trim()){Le("error","Knowledge name is required");return}const N=oz(Wi);try{const L=Wi.id?await kz(x,Wi.id,N):await wz(x,N);li(V=>[...V.filter(ie=>ie.id!==L.id),L].sort(g5)),Xi(bc),oe("connected"),Le("success","Workspace knowledge saved")}catch(L){console.error(L),oe("error"),Le("error","Failed to save workspace knowledge")}}async function x0(x,j){try{await Sz(x,j),li(N=>N.filter(L=>L.id!==j)),Wi.id===j&&Xi(bc),oe("connected"),Le("success","Workspace knowledge deleted")}catch(N){console.error(N),oe("error"),Le("error","Failed to delete workspace knowledge")}}function wo(x){Na("workspace"),Xi(uz(x))}function dl(x){Fr({description:x.description,key:x.key,value:""}),da(x.key),fa(j=>{const N=new Set(j);return N.delete(x.key),N}),ko(x.key,{preserveTypedValue:!0})}function Bf(){const x=ts;Fr({description:"",key:"",value:""}),da(null),x&&fa(j=>{const N=new Set(j);return N.delete(x),N})}async function Yn(x){await ko(x)}async function ko(x,j={}){try{const N=nr==="workspace"&&Bt?await vz(Bt,x):await yz(x);Fr(L=>L.key===x&&(!j.preserveTypedValue||L.value.length===0)?{...L,value:N}:L),fa(L=>new Set(L).add(x)),oe("connected")}catch(N){console.error(N),oe("error")}}async function hn(x){const j=await sp(x);T0(j)}async function _u(x){try{const j=await sp(x);A0(j)}catch(j){console.warn("Failed to synchronize timeline before turn stream",j)}}async function xs(x){try{q(await Az(x))}catch(j){console.error(j)}}async function Tr(x){if(w)try{const j=await Nz(w,x);q(x==="end"?null:j),x==="end"&&B("simple"),Le("success",x==="start"?"Complex task started":`Task ${x} accepted`),(x==="start"||x==="resume")&&Hu(w,{waitMs:15e3}),await fn()}catch(j){Le("error","Complex task control failed",dt(j).detail??dt(j).message)}}async function wa(x){if(w)try{Y(await Ez(w,x))}catch(j){const N=dt(j);Le("error","Failed to load complex task",N.detail??N.message)}}function b0(){We&&le({sourceId:We.id,name:`${We.title} - Clone`,groupId:We.groupId})}async function Bu(x){if(x.preventDefault(),!(!K||!K.name.trim())){G(!0);try{const j=await Mz(K.sourceId,K.name.trim(),K.groupId);y(N=>{const L=[j.conversation,...N];return Cc(l,I3(Wo(l),j.conversation.id,L.map(V=>V.id))),Ul(l,L)}),T(j.conversation.id),le(null),fe(!1),Le(j.error?"error":"success",j.error?"Clone created, initialization failed":"Workspace cloned",j.error??void 0)}catch(j){Le("error","Clone failed",dt(j).detail??dt(j).message)}finally{G(!1)}}}async function w0(){if(We)try{const x=await zz(We.id);hr(x.conversation),Le(x.error?"error":"success",x.error?"Clone retry failed":"Clone initialization restarted",x.error??void 0)}catch(x){Le("error","Clone retry failed",dt(x).detail??dt(x).message)}}async function ur(x,j={}){var ze,_e,Rt;const N=Be[x],L=(ze=N==null?void 0:N.history)==null?void 0:ze.oldestTimelineAt,V=(_e=N==null?void 0:N.history)==null?void 0:_e.oldestTimelineSequence,ie=L&&V!==null&&V!==void 0?`${L}|${V}`:V==null?(Rt=N==null?void 0:N.history)==null?void 0:Rt.oldestMessageCreatedAt:String(V),Se=ss.current;if(!ie||!Se)return;if(j.preserveAnchor??!0){const St=kE(Se);hi.current={anchorOffset:St.anchorOffset,conversationId:x,previousScrollHeight:Se.scrollHeight,anchorTurnId:St.anchorTurnId}}else hi.current=null;mi.current.add(x),kt(x,St=>({...St,loadingOlder:!0}));try{const St=await sp(x,{before:ie,limit:Kv});qf(St)}catch(St){console.error(St),hi.current=null}finally{mi.current.delete(x),kt(x,St=>({...St,loadingOlder:!1}))}}async function fl(x,j){const N=await Tz(x,j||void 0);y(L=>{const V=[N,...L];return Cc(l,I3(Wo(l),N.id,V.map(ie=>ie.id))),Ul(l,V)}),T(N.id),fe(!1)}function $a(x){x!==us.current&&(Ce(j=>{if(!(x in j))return j;const N={...j};return delete N[x],N}),T(x))}function So(){fe(!1),Zt({mode:"create",groupId:null,title:""})}function hl(x){Zt({mode:"rename",groupId:x.id,title:x.title})}function Wn(){var x;fe(!1),st({mode:"create",conversationId:null,title:"",groupId:(We==null?void 0:We.groupId)??((x=v[0])==null?void 0:x.id)})}async function cr(x){var j;if(x.status!=="running"){jn(!0);try{await Rz(x.id),Ce(L=>{const V={...L};return delete V[x.id],V});const N=so.current.filter(L=>L.id!==x.id);if(Cc(l,PA(Wo(l),x.id)),Wm(l,x.id,""),y(N),w===x.id){const L=((j=N[0])==null?void 0:j.id)??null;Ym(l,L),T(L)}(Oe==null?void 0:Oe.conversationId)===x.id&&Ln(),ut(null),Le("success","Workspace moved to recycle")}catch(N){const L=dt(N);Le("error","Failed to move workspace to recycle",L.detail??L.message)}finally{jn(!1)}}}async function Ga(x){if(!(x.id===U3||!window.confirm(`Delete group "${x.title}"?
347
353
 
348
- Workspaces in this group will move to Default.`)))try{const N=await OM(x.id),L=Dd(l,N.groups);k(L),Km(l,L);const V=Ul(l,N.conversations);y(V),Rd(l,V),as(ie=>{const Se=new Set(ie);return Se.delete(x.id),Xm(l,Se),Se})}catch(N){console.error(N)}}function Xr(x){st({mode:"rename",conversationId:x.id,title:x.title})}function Ln(){lt(!1),st(null)}function dr(){Zt(null)}async function k0(x,j){const N=j.trim(),L=m.find(ie=>ie.id===x);if(!L||!N||N===L.title){Ln();return}const V=await qd(x,{title:N});hr(V),Ln()}function Co(x){return x instanceof HTMLInputElement||x instanceof HTMLTextAreaElement}function jo(x){return x instanceof Element&&!!x.closest("input, button")}function S0(x,j){const N=document.elementFromPoint(x,j);return N instanceof HTMLElement?N.closest(".session-item[data-workspace-id]"):null}function gn(x,j){const N=document.elementFromPoint(x,j);return N instanceof HTMLElement?N.closest(".workspace-group[data-group-id]"):null}function Ut(x,j,N){const L=S0(j,N),V=L==null?void 0:L.dataset.workspaceId;if(L&&V&&V!==x){Vr({kind:"workspace",id:V,position:AE(L,N)});return}const ie=gn(j,N),Se=ie==null?void 0:ie.dataset.groupId;if(!Se){Vr(null);return}Vr({kind:"group",id:Se})}function mt(x,j){jo(x.target)||(x.currentTarget.setPointerCapture(x.pointerId),al.current={id:j,pointerId:x.pointerId,startX:x.clientX,startY:x.clientY})}function Pa(x,j){const N=al.current;if(!N||N.id!==j||N.pointerId!==x.pointerId)return;const L=Math.hypot(x.clientX-N.startX,x.clientY-N.startY);if(ns!==j){if(L<L3)return;fi(j),Vr(null)}x.preventDefault(),Yr({x:x.clientX,y:x.clientY}),Ut(j,x.clientX,x.clientY)}async function fr(x,j){var Se;x.preventDefault(),x.currentTarget.hasPointerCapture(x.pointerId)&&x.currentTarget.releasePointerCapture(x.pointerId),al.current=null;const N=ns===j;N&&(xu.current=!0);const L=ir;if(!N||!L){fi(null),Vr(null),Yr(null);return}const V=m.find(Ge=>Ge.id===j),ie=L.kind==="group"?L.id:(Se=m.find(Ge=>Ge.id===L.id))==null?void 0:Se.groupId;if(!V||!ie){fi(null),Vr(null),Yr(null);return}if(y(Ge=>{const ze=L.kind==="workspace"?EE(Ge.map(_e=>_e.id===j?{..._e,groupId:ie}:_e),j,L.id,L.position):[...Ge.filter(_e=>_e.id!==j),{...V,groupId:ie}];return Cc(l,I1(ze.map(_e=>_e.id),Wo(l))),ze}),V.groupId!==ie)try{const Ge=await qd(j,{groupId:ie});hr(Ge)}catch(Ge){console.error(Ge),await fn()}fi(null),Vr(null),Yr(null)}function Iu(x){x.currentTarget.hasPointerCapture(x.pointerId)&&x.currentTarget.releasePointerCapture(x.pointerId),al.current=null,fi(null),Vr(null),Yr(null)}function Va(x,j){x.currentTarget.setPointerCapture(x.pointerId),co.current={id:j,pointerId:x.pointerId,startX:x.clientX,startY:x.clientY}}function C0(x,j){const N=co.current;if(!N||N.id!==j||N.pointerId!==x.pointerId)return;const L=Math.hypot(x.clientX-N.startX,x.clientY-N.startY);if(yu!==j){if(L<L3)return;vu(j),ar(null)}x.preventDefault();const V=gn(x.clientX,x.clientY),ie=V==null?void 0:V.dataset.groupId;ar(ie&&ie!==j?ie:null)}function j0(x,j){x.currentTarget.hasPointerCapture(x.pointerId)&&x.currentTarget.releasePointerCapture(x.pointerId);const N=yu===j;N&&(x.preventDefault(),bu.current=!0);const L=rs;N&&L&&k(V=>{const ie=NE(V,j,L);return a7(l,ie.map(Se=>Se.id)),ie}),co.current=null,vu(null),ar(null)}function ml(x){x.currentTarget.hasPointerCapture(x.pointerId)&&x.currentTarget.releasePointerCapture(x.pointerId),co.current=null,vu(null),ar(null)}function wi(x){const j=x.target.value;st(N=>N&&{...N,title:j})}function Lu(x){const j=x.target.value;st(N=>N&&{...N,groupId:j})}function bs(x){const j=x.target.value;Zt(N=>N&&{...N,title:j})}async function qu(x){if(x.preventDefault(),!Oe)return;const j=Oe.title.trim();if(j){lt(!0);try{if(Oe.mode==="create"){await fl(j,Oe.groupId),Ln();return}Oe.conversationId&&await k0(Oe.conversationId,j)}catch(N){console.error(N);const L=dt(N);Le("error",Oe.mode==="create"?"Failed to create workspace":"Failed to rename workspace",L.detail??L.message)}finally{lt(!1)}}}function Kr(x){x.key==="Escape"&&(x.preventDefault(),x.stopPropagation(),Ln())}async function ka(x){if(x.preventDefault(),!Qe)return;const j=Qe.title.trim();if(j)try{if(Qe.mode==="rename"){if(!Qe.groupId)return;const L=await RM(Qe.groupId,{title:j});k(V=>V.map(ie=>ie.id===L.id?L:ie)),dr();return}const N=await DM(j);k(L=>[...L,N]),as(L=>{const V=new Set(L);return V.delete(N.id),Xm(l,V),V}),dr()}catch(N){console.error(N)}}function Qr(x){x.key==="Escape"&&(x.preventDefault(),x.stopPropagation(),dr())}async function Sa(x){x.preventDefault(),await yn()}function Uu(x){w&&cs.current.set(w,(cs.current.get(w)??0)+1),c(x),Wm(l,w,x)}function pl(x,j,N){const L={conversationId:x,version:N};if(!R3(L,{conversationId:x,version:cs.current.get(x)??0}))return;Wm(l,x,"");const V=us.current;V&&R3(L,{conversationId:V,version:cs.current.get(V)??0})&&c(ie=>ie.trim()===j?"":ie)}function gl(x){if(pi.current.has(x))return null;const j=Symbol(x);return pi.current.set(x,j),h(N=>{const L=new Set(N);return L.add(x),L}),j}function Ca(x,j){pi.current.get(x)===j&&(pi.current.delete(x),h(N=>{const L=new Set(N);return L.delete(x),L}))}function ja(x){const j=dt(x);Le("error","Message was not confirmed",`${j.message}. Your text is still in the composer and can be retried.`)}async function yn(x={}){const j=o.trim();if(!j)return;const N=w,L=IA({hasConversation:N!==null,messageSubmitting:N!==null&&pi.current.has(N),hasActiveTurn:N!==null&&sr.current.has(N),hasConfirmedCurrentTurn:N!==null&&nl.current.has(N),complexTaskActive:!!E},!!x.forceNewTurn);if(L==="create-workspace"){Wn();return}if(L==="blocked"||!N)return;const V=cs.current.get(N)??0,ie=gl(N);if(!ie)return;if(L==="queue-turn"){await If(N,j,V,ie);return}if(L==="steer-turn"){await Lf(N,j,V,ie);return}const Se=`local-${Date.now()}`;kt(N,ze=>({...ze,messages:[...ze.messages,{id:Se,role:"user",content:j,createdAt:new Date().toISOString()}],status:"running"})),ea(N,"running"),ta(N,!0);let Ge=!1;try{let ze=null;const _e=Ne(`conversations/${N}/turns`),Rt=await fetch(_e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({message:j,workMode:R})});if(Rt.ok){const St=await Rt.json();if(!St.turnId)throw new Error("Turn did not return a turn id");if(ze=St.turnId,(R==="complex"||E)&&(xs(N),B("simple")),!St.message)throw new Error("Turn did not return the persisted message");yl(N,Se,St.message,ze),Ge=!0,pl(N,j,V)}else{const St=await mE(Rt);if(St){ze=St;const As=await sn(N,St,j);if(!As.ok)throw await Fn(As,{method:"POST",url:Ne(`conversations/${N}/turns/${St}/steer`)});const wl=await As.json();if(!wl.message)throw new Error("Steer did not return the persisted message");yl(N,Se,wl.message,St),Ge=!0,pl(N,j,V)}else throw await Fn(Rt,{method:"POST",url:_e})}if(!ze)throw await Fn(Rt,{method:"POST",url:_e});ks(N,ze),Ca(N,ie)}catch(ze){Ge||ja(ze);const _e=hE(ze);_e&&Le("error","Reset thread required",E?"End the current complex task, then reset this workspace thread and try again.":"This thread does not support the required Seele tools. Reset this workspace thread and try again."),kt(N,Rt=>({...Rt,status:"error",messages:Ge?Rt.messages:Rt.messages.filter(St=>St.id!==Se),events:[...Rt.events,{id:Rt.events.length+1,event:"client.error",data:_e?{message:"Reset thread required",detail:E?"End the current complex task, then reset this workspace thread and try again.":"This thread does not support the required Seele tools. Reset this workspace thread and try again."}:_s(ze),createdAt:new Date().toISOString()}]})),ea(N,"error"),ta(N,!1),await fn()}finally{Ca(N,ie)}}async function ws(x){const j=rl.current.get(x)??[];if(j.length===0)return;const[N,...L]=j;rl.current.set(x,L),await ks(x,N)}async function Hu(x,j={}){if(fs.current.has(x)||lr.current.has(x))return;po(x),ds.current.delete(x);const N=new AbortController;lr.current.set(x,N),ta(x,!0);try{const L=j.waitMs?`?waitMs=${j.waitMs}`:"",V=Ne(`conversations/${x}/turns/current/events${L}`),ie=await fetch(V,{signal:N.signal});if(!ie.ok||!ie.body)throw await Fn(ie,{method:"GET",url:V});gs(x),nl.current.add(x),await _u(x),await k5(ie.body,Se=>{const Ge=n5(Se,`stream-${Date.now()}-${Math.random().toString(36).slice(2)}`);Ge.turnId&&!sr.current.has(x)&&sr.current.set(x,Ge.turnId),kt(x,_e=>({..._e,status:Ud(Ge)??_e.status,events:t5(_e.events,Ge)}));const ze=Ud(Ge);ze&&ea(x,ze)}),await hn(x),await fn()}catch(L){if(!a5(L)){if(fE(L)){lr.current.get(x)===N&&Tu(x);return}kt(x,V=>({...V,status:"error",events:[...V.events,{id:V.events.length+1,event:"client.error",data:_s(L),createdAt:new Date().toISOString()}]}))}}finally{lr.current.get(x)===N&&(nl.current.delete(x),sr.current.delete(x),lr.current.delete(x),ta(x,!1),await ws(x))}}async function ks(x,j,N={}){const L=sr.current.get(x);if(L===j)return;if(L||lr.current.has(x)){const ie=rl.current.get(x)??[];ie.includes(j)||rl.current.set(x,[...ie,j]);return}gs(x);const V=new AbortController;lr.current.set(x,V),sr.current.set(x,j),ta(x,!0);try{const ie=Ne(`conversations/${x}/turns/${j}/events`),Se=await fetch(ie,{signal:V.signal});if(!Se.ok||!Se.body)throw await Fn(Se,{method:"GET",url:ie});await _u(x),await k5(Se.body,Ge=>{const ze=n5(Ge,`stream-${Date.now()}-${Math.random().toString(36).slice(2)}`);kt(x,Rt=>({...Rt,status:Ud(ze)??Rt.status,events:t5(Rt.events,ze)}));const _e=Ud(ze);_e&&ea(x,_e)}),await hn(x),await fn()}catch(ie){if(!a5(ie)){if(N.recovered&&dE(ie)){await hn(x),await fn();return}kt(x,Se=>({...Se,status:"error",events:[...Se.events,{id:Se.events.length+1,event:"client.error",data:_s(ie),createdAt:new Date().toISOString()}]}))}}finally{lr.current.get(x)===V&&(sr.current.get(x)===j&&sr.current.delete(x),lr.current.delete(x),ta(x,!1),await ws(x))}}async function If(x,j,N,L){let V=!1;const ie=`local-queued-${Date.now()}`;kt(x,Se=>({...Se,messages:[...Se.messages,{id:ie,role:"user",content:j,createdAt:new Date().toISOString()}]}));try{const Se=Ne(`conversations/${x}/turns`),Ge=await fetch(Se,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({message:j,mode:"queue",workMode:R})});if(!Ge.ok)throw await Fn(Ge,{method:"POST",url:Se});const ze=await Ge.json();if(!ze.turnId)throw new Error("Queued turn did not return a turn id");if(!ze.message)throw new Error("Queued turn did not return the persisted message");yl(x,ie,ze.message,ze.turnId),V=!0,pl(x,j,N),ks(x,ze.turnId),Ca(x,L),await fn(),Le("success",ze.queuePosition?`Queued as next turn (${ze.queuePosition})`:"Started new turn")}catch(Se){V||ja(Se),kt(x,Ge=>({...Ge,messages:V?Ge.messages:Ge.messages.filter(ze=>ze.id!==ie),events:[...Ge.events,{id:Ge.events.length+1,event:"client.error",data:_s(Se),createdAt:new Date().toISOString()}]}))}finally{Ca(x,L)}}async function Lf(x,j,N,L){const V=sr.current.get(x);let ie=!1;const Se=`local-steer-${Date.now()}`;kt(x,Ge=>({...Ge,messages:[...Ge.messages,{id:Se,role:"user",content:j,createdAt:new Date().toISOString(),turnId:V??null}],status:"running"}));try{const Ge=Ne(V?`conversations/${x}/turns/${V}/steer`:`conversations/${x}/turns/steer`),ze=await fetch(Ge,F3(j));if(!ze.ok)throw await Fn(ze,{method:"POST",url:Ge});const _e=await ze.json();if(!_e.message)throw new Error("Steer did not return the persisted message");yl(x,Se,_e.message,V),ie=!0,pl(x,j,N),Ca(x,L)}catch(Ge){ja(Ge),kt(x,ze=>({...ze,messages:ie?ze.messages:ze.messages.filter(_e=>_e.id!==Se),events:[...ze.events,{id:ze.events.length+1,event:"client.error",data:_s(Ge),createdAt:new Date().toISOString()}]}))}finally{Ca(x,L)}}async function sn(x,j,N){return fetch(Ne(`conversations/${x}/turns/${j}/steer`),F3(N))}function yl(x,j,N,L){kt(x,V=>({...V,messages:Jm(V.messages.filter(ie=>ie.id!==j),[{...N,turnId:L??N.turnId??null}])}))}async function Ss(){var L;if(!w||Ia!=="running"&&Ia!=="initializing"&&!mo)return;const x=w,j=Ia,N=`client-stop-${Date.now()}`;u0(x),(L=lr.current.get(x))==null||L.abort(),sr.current.delete(x),rl.current.delete(x),ta(x,!1),kt(x,V=>({...V,status:"done",events:[...V.events,{id:N,event:"server.stop",data:{source:"client"},createdAt:new Date().toISOString()}]})),ea(x,"done");try{const V=await vl(x);gs(x),kt(x,ie=>({...ie,status:V})),ea(x,V),Promise.all([hn(x),fn()]).catch(ie=>{console.warn("Failed to refresh workspace after Stop",ie)})}catch(V){Tu(x),kt(x,Se=>({...Se,status:j==="initializing"?"initializing":"running",events:[...Se.events.filter(Ge=>Ge.id!==N),{id:Se.events.length+1,event:"client.error",data:_s(V),createdAt:new Date().toISOString()}]})),ea(x,j==="initializing"?"initializing":"running");const ie=dt(V);Le("error","Stop failed",ie.detail??ie.message);try{await fn()}catch(Se){console.warn("Failed to refresh workspace after Stop failed",Se)}}}async function vl(x){const j=Ne(`conversations/${x}/turns/interrupt`),N=await fetch(j,{method:"POST"});if(!N.ok)throw await Fn(N,{method:"POST",url:j});return FA(await N.json().catch(()=>null))}async function Fu(){var L;const x=Wr;if(!x){Le("error","No workspace selected");return}if(!window.confirm(`Force stop and repair "${x.title}"?
354
+ Workspaces in this group will move to Default.`)))try{const N=await _M(x.id),L=Dd(l,N.groups);k(L),Km(l,L);const V=Ul(l,N.conversations);y(V),Rd(l,V),as(ie=>{const Se=new Set(ie);return Se.delete(x.id),Xm(l,Se),Se})}catch(N){console.error(N)}}function Xr(x){st({mode:"rename",conversationId:x.id,title:x.title})}function Ln(){lt(!1),st(null)}function dr(){Zt(null)}async function k0(x,j){const N=j.trim(),L=m.find(ie=>ie.id===x);if(!L||!N||N===L.title){Ln();return}const V=await qd(x,{title:N});hr(V),Ln()}function Co(x){return x instanceof HTMLInputElement||x instanceof HTMLTextAreaElement}function jo(x){return x instanceof Element&&!!x.closest("input, button")}function S0(x,j){const N=document.elementFromPoint(x,j);return N instanceof HTMLElement?N.closest(".session-item[data-workspace-id]"):null}function gn(x,j){const N=document.elementFromPoint(x,j);return N instanceof HTMLElement?N.closest(".workspace-group[data-group-id]"):null}function Ut(x,j,N){const L=S0(j,N),V=L==null?void 0:L.dataset.workspaceId;if(L&&V&&V!==x){Vr({kind:"workspace",id:V,position:EE(L,N)});return}const ie=gn(j,N),Se=ie==null?void 0:ie.dataset.groupId;if(!Se){Vr(null);return}Vr({kind:"group",id:Se})}function mt(x,j){jo(x.target)||(x.currentTarget.setPointerCapture(x.pointerId),al.current={id:j,pointerId:x.pointerId,startX:x.clientX,startY:x.clientY})}function Pa(x,j){const N=al.current;if(!N||N.id!==j||N.pointerId!==x.pointerId)return;const L=Math.hypot(x.clientX-N.startX,x.clientY-N.startY);if(ns!==j){if(L<L3)return;fi(j),Vr(null)}x.preventDefault(),Yr({x:x.clientX,y:x.clientY}),Ut(j,x.clientX,x.clientY)}async function fr(x,j){var Se;x.preventDefault(),x.currentTarget.hasPointerCapture(x.pointerId)&&x.currentTarget.releasePointerCapture(x.pointerId),al.current=null;const N=ns===j;N&&(xu.current=!0);const L=ir;if(!N||!L){fi(null),Vr(null),Yr(null);return}const V=m.find(Ge=>Ge.id===j),ie=L.kind==="group"?L.id:(Se=m.find(Ge=>Ge.id===L.id))==null?void 0:Se.groupId;if(!V||!ie){fi(null),Vr(null),Yr(null);return}if(y(Ge=>{const ze=L.kind==="workspace"?NE(Ge.map(_e=>_e.id===j?{..._e,groupId:ie}:_e),j,L.id,L.position):[...Ge.filter(_e=>_e.id!==j),{...V,groupId:ie}];return Cc(l,I1(ze.map(_e=>_e.id),Wo(l))),ze}),V.groupId!==ie)try{const Ge=await qd(j,{groupId:ie});hr(Ge)}catch(Ge){console.error(Ge),await fn()}fi(null),Vr(null),Yr(null)}function Iu(x){x.currentTarget.hasPointerCapture(x.pointerId)&&x.currentTarget.releasePointerCapture(x.pointerId),al.current=null,fi(null),Vr(null),Yr(null)}function Va(x,j){x.currentTarget.setPointerCapture(x.pointerId),co.current={id:j,pointerId:x.pointerId,startX:x.clientX,startY:x.clientY}}function C0(x,j){const N=co.current;if(!N||N.id!==j||N.pointerId!==x.pointerId)return;const L=Math.hypot(x.clientX-N.startX,x.clientY-N.startY);if(yu!==j){if(L<L3)return;vu(j),ar(null)}x.preventDefault();const V=gn(x.clientX,x.clientY),ie=V==null?void 0:V.dataset.groupId;ar(ie&&ie!==j?ie:null)}function j0(x,j){x.currentTarget.hasPointerCapture(x.pointerId)&&x.currentTarget.releasePointerCapture(x.pointerId);const N=yu===j;N&&(x.preventDefault(),bu.current=!0);const L=rs;N&&L&&k(V=>{const ie=ME(V,j,L);return a7(l,ie.map(Se=>Se.id)),ie}),co.current=null,vu(null),ar(null)}function ml(x){x.currentTarget.hasPointerCapture(x.pointerId)&&x.currentTarget.releasePointerCapture(x.pointerId),co.current=null,vu(null),ar(null)}function wi(x){const j=x.target.value;st(N=>N&&{...N,title:j})}function Lu(x){const j=x.target.value;st(N=>N&&{...N,groupId:j})}function bs(x){const j=x.target.value;Zt(N=>N&&{...N,title:j})}async function qu(x){if(x.preventDefault(),!Oe)return;const j=Oe.title.trim();if(j){lt(!0);try{if(Oe.mode==="create"){await fl(j,Oe.groupId),Ln();return}Oe.conversationId&&await k0(Oe.conversationId,j)}catch(N){console.error(N);const L=dt(N);Le("error",Oe.mode==="create"?"Failed to create workspace":"Failed to rename workspace",L.detail??L.message)}finally{lt(!1)}}}function Kr(x){x.key==="Escape"&&(x.preventDefault(),x.stopPropagation(),Ln())}async function ka(x){if(x.preventDefault(),!Qe)return;const j=Qe.title.trim();if(j)try{if(Qe.mode==="rename"){if(!Qe.groupId)return;const L=await OM(Qe.groupId,{title:j});k(V=>V.map(ie=>ie.id===L.id?L:ie)),dr();return}const N=await RM(j);k(L=>[...L,N]),as(L=>{const V=new Set(L);return V.delete(N.id),Xm(l,V),V}),dr()}catch(N){console.error(N)}}function Qr(x){x.key==="Escape"&&(x.preventDefault(),x.stopPropagation(),dr())}async function Sa(x){x.preventDefault(),await yn()}function Uu(x){w&&cs.current.set(w,(cs.current.get(w)??0)+1),c(x),Wm(l,w,x)}function pl(x,j,N){const L={conversationId:x,version:N};if(!R3(L,{conversationId:x,version:cs.current.get(x)??0}))return;Wm(l,x,"");const V=us.current;V&&R3(L,{conversationId:V,version:cs.current.get(V)??0})&&c(ie=>ie.trim()===j?"":ie)}function gl(x){if(pi.current.has(x))return null;const j=Symbol(x);return pi.current.set(x,j),h(N=>{const L=new Set(N);return L.add(x),L}),j}function Ca(x,j){pi.current.get(x)===j&&(pi.current.delete(x),h(N=>{const L=new Set(N);return L.delete(x),L}))}function ja(x){const j=dt(x);Le("error","Message was not confirmed",`${j.message}. Your text is still in the composer and can be retried.`)}async function yn(x={}){const j=o.trim();if(!j)return;const N=w,L=LA({hasConversation:N!==null,messageSubmitting:N!==null&&pi.current.has(N),hasActiveTurn:N!==null&&sr.current.has(N),hasConfirmedCurrentTurn:N!==null&&nl.current.has(N),complexTaskActive:!!E},!!x.forceNewTurn);if(L==="create-workspace"){Wn();return}if(L==="blocked"||!N)return;const V=cs.current.get(N)??0,ie=gl(N);if(!ie)return;if(L==="queue-turn"){await If(N,j,V,ie);return}if(L==="steer-turn"){await Lf(N,j,V,ie);return}const Se=`local-${Date.now()}`;kt(N,ze=>({...ze,messages:[...ze.messages,{id:Se,role:"user",content:j,createdAt:new Date().toISOString()}],status:"running"})),ea(N,"running"),ta(N,!0);let Ge=!1;try{let ze=null;const _e=Ne(`conversations/${N}/turns`),Rt=await fetch(_e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({message:j,workMode:R})});if(Rt.ok){const St=await Rt.json();if(!St.turnId)throw new Error("Turn did not return a turn id");if(ze=St.turnId,(R==="complex"||E)&&(xs(N),B("simple")),!St.message)throw new Error("Turn did not return the persisted message");yl(N,Se,St.message,ze),Ge=!0,pl(N,j,V)}else{const St=await pE(Rt);if(St){ze=St;const As=await sn(N,St,j);if(!As.ok)throw await Fn(As,{method:"POST",url:Ne(`conversations/${N}/turns/${St}/steer`)});const wl=await As.json();if(!wl.message)throw new Error("Steer did not return the persisted message");yl(N,Se,wl.message,St),Ge=!0,pl(N,j,V)}else throw await Fn(Rt,{method:"POST",url:_e})}if(!ze)throw await Fn(Rt,{method:"POST",url:_e});ks(N,ze),Ca(N,ie)}catch(ze){Ge||ja(ze);const _e=mE(ze);_e&&Le("error","Reset thread required",E?"End the current complex task, then reset this workspace thread and try again.":"This thread does not support the required Seele tools. Reset this workspace thread and try again."),kt(N,Rt=>({...Rt,status:"error",messages:Ge?Rt.messages:Rt.messages.filter(St=>St.id!==Se),events:[...Rt.events,{id:Rt.events.length+1,event:"client.error",data:_e?{message:"Reset thread required",detail:E?"End the current complex task, then reset this workspace thread and try again.":"This thread does not support the required Seele tools. Reset this workspace thread and try again."}:_s(ze),createdAt:new Date().toISOString()}]})),ea(N,"error"),ta(N,!1),await fn()}finally{Ca(N,ie)}}async function ws(x){const j=rl.current.get(x)??[];if(j.length===0)return;const[N,...L]=j;rl.current.set(x,L),await ks(x,N)}async function Hu(x,j={}){if(fs.current.has(x)||lr.current.has(x))return;po(x),ds.current.delete(x);const N=new AbortController;lr.current.set(x,N),ta(x,!0);try{const L=j.waitMs?`?waitMs=${j.waitMs}`:"",V=Ne(`conversations/${x}/turns/current/events${L}`),ie=await fetch(V,{signal:N.signal});if(!ie.ok||!ie.body)throw await Fn(ie,{method:"GET",url:V});gs(x),nl.current.add(x),await _u(x),await k5(ie.body,Se=>{const Ge=n5(Se,`stream-${Date.now()}-${Math.random().toString(36).slice(2)}`);Ge.turnId&&!sr.current.has(x)&&sr.current.set(x,Ge.turnId),kt(x,_e=>({..._e,status:Ud(Ge)??_e.status,events:t5(_e.events,Ge)}));const ze=Ud(Ge);ze&&ea(x,ze)}),await hn(x),await fn()}catch(L){if(!a5(L)){if(hE(L)){lr.current.get(x)===N&&Tu(x);return}kt(x,V=>({...V,status:"error",events:[...V.events,{id:V.events.length+1,event:"client.error",data:_s(L),createdAt:new Date().toISOString()}]}))}}finally{lr.current.get(x)===N&&(nl.current.delete(x),sr.current.delete(x),lr.current.delete(x),ta(x,!1),await ws(x))}}async function ks(x,j,N={}){const L=sr.current.get(x);if(L===j)return;if(L||lr.current.has(x)){const ie=rl.current.get(x)??[];ie.includes(j)||rl.current.set(x,[...ie,j]);return}gs(x);const V=new AbortController;lr.current.set(x,V),sr.current.set(x,j),ta(x,!0);try{const ie=Ne(`conversations/${x}/turns/${j}/events`),Se=await fetch(ie,{signal:V.signal});if(!Se.ok||!Se.body)throw await Fn(Se,{method:"GET",url:ie});await _u(x),await k5(Se.body,Ge=>{const ze=n5(Ge,`stream-${Date.now()}-${Math.random().toString(36).slice(2)}`);kt(x,Rt=>({...Rt,status:Ud(ze)??Rt.status,events:t5(Rt.events,ze)}));const _e=Ud(ze);_e&&ea(x,_e)}),await hn(x),await fn()}catch(ie){if(!a5(ie)){if(N.recovered&&fE(ie)){await hn(x),await fn();return}kt(x,Se=>({...Se,status:"error",events:[...Se.events,{id:Se.events.length+1,event:"client.error",data:_s(ie),createdAt:new Date().toISOString()}]}))}}finally{lr.current.get(x)===V&&(sr.current.get(x)===j&&sr.current.delete(x),lr.current.delete(x),ta(x,!1),await ws(x))}}async function If(x,j,N,L){let V=!1;const ie=`local-queued-${Date.now()}`;kt(x,Se=>({...Se,messages:[...Se.messages,{id:ie,role:"user",content:j,createdAt:new Date().toISOString()}]}));try{const Se=Ne(`conversations/${x}/turns`),Ge=await fetch(Se,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({message:j,mode:"queue",workMode:R})});if(!Ge.ok)throw await Fn(Ge,{method:"POST",url:Se});const ze=await Ge.json();if(!ze.turnId)throw new Error("Queued turn did not return a turn id");if(!ze.message)throw new Error("Queued turn did not return the persisted message");yl(x,ie,ze.message,ze.turnId),V=!0,pl(x,j,N),ks(x,ze.turnId),Ca(x,L),await fn(),Le("success",ze.queuePosition?`Queued as next turn (${ze.queuePosition})`:"Started new turn")}catch(Se){V||ja(Se),kt(x,Ge=>({...Ge,messages:V?Ge.messages:Ge.messages.filter(ze=>ze.id!==ie),events:[...Ge.events,{id:Ge.events.length+1,event:"client.error",data:_s(Se),createdAt:new Date().toISOString()}]}))}finally{Ca(x,L)}}async function Lf(x,j,N,L){const V=sr.current.get(x);let ie=!1;const Se=`local-steer-${Date.now()}`;kt(x,Ge=>({...Ge,messages:[...Ge.messages,{id:Se,role:"user",content:j,createdAt:new Date().toISOString(),turnId:V??null}],status:"running"}));try{const Ge=Ne(V?`conversations/${x}/turns/${V}/steer`:`conversations/${x}/turns/steer`),ze=await fetch(Ge,F3(j));if(!ze.ok)throw await Fn(ze,{method:"POST",url:Ge});const _e=await ze.json();if(!_e.message)throw new Error("Steer did not return the persisted message");yl(x,Se,_e.message,V),ie=!0,pl(x,j,N),Ca(x,L)}catch(Ge){ja(Ge),kt(x,ze=>({...ze,messages:ie?ze.messages:ze.messages.filter(_e=>_e.id!==Se),events:[...ze.events,{id:ze.events.length+1,event:"client.error",data:_s(Ge),createdAt:new Date().toISOString()}]}))}finally{Ca(x,L)}}async function sn(x,j,N){return fetch(Ne(`conversations/${x}/turns/${j}/steer`),F3(N))}function yl(x,j,N,L){kt(x,V=>({...V,messages:Jm(V.messages.filter(ie=>ie.id!==j),[{...N,turnId:L??N.turnId??null}])}))}async function Ss(){var L;if(!w||Ia!=="running"&&Ia!=="initializing"&&!mo)return;const x=w,j=Ia,N=`client-stop-${Date.now()}`;u0(x),(L=lr.current.get(x))==null||L.abort(),sr.current.delete(x),rl.current.delete(x),ta(x,!1),kt(x,V=>({...V,status:"done",events:[...V.events,{id:N,event:"server.stop",data:{source:"client"},createdAt:new Date().toISOString()}]})),ea(x,"done");try{const V=await vl(x);gs(x),kt(x,ie=>({...ie,status:V})),ea(x,V),Promise.all([hn(x),fn()]).catch(ie=>{console.warn("Failed to refresh workspace after Stop",ie)})}catch(V){Tu(x),kt(x,Se=>({...Se,status:j==="initializing"?"initializing":"running",events:[...Se.events.filter(Ge=>Ge.id!==N),{id:Se.events.length+1,event:"client.error",data:_s(V),createdAt:new Date().toISOString()}]})),ea(x,j==="initializing"?"initializing":"running");const ie=dt(V);Le("error","Stop failed",ie.detail??ie.message);try{await fn()}catch(Se){console.warn("Failed to refresh workspace after Stop failed",Se)}}}async function vl(x){const j=Ne(`conversations/${x}/turns/interrupt`),N=await fetch(j,{method:"POST"});if(!N.ok)throw await Fn(N,{method:"POST",url:j});return $A(await N.json().catch(()=>null))}async function Fu(){var L;const x=Wr;if(!x){Le("error","No workspace selected");return}if(!window.confirm(`Force stop and repair "${x.title}"?
349
355
 
350
- This cancels every current or queued turn and the active complex task, kills its runtime, and repairs scheduler state. Future scheduled wakeups are preserved.`))return;const N=x.id;Bn(!0),u0(N),(L=lr.current.get(N))==null||L.abort(),sr.current.delete(N),rl.current.delete(N),ta(N,!1);try{const V=await vl(N);gs(N),kt(N,ie=>({...ie,status:V})),ea(N,V),await hn(N),await fn(),Le("success","Workspace stopped and repaired")}catch(V){Tu(N);const ie=dt(V);Le("error","Force stop failed",ie.detail??ie.message);try{await fn()}catch(Se){console.warn("Failed to refresh workspace after force Stop failed",Se)}}finally{Bn(!1)}}async function Zr(x,j){if(!w||!x.approvalTurnId||x.approvalRequestId===void 0)return;const N=w;try{const L=Ne(`conversations/${N}/turns/${x.approvalTurnId}/approvals/${encodeURIComponent(String(x.approvalRequestId))}`),V=await fetch(L,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({decision:j})});if(!V.ok)throw await Fn(V,{method:"POST",url:L});kt(N,ie=>({...ie,events:[...ie.events,{id:ie.events.length+1,event:"server.approval.decision",data:{requestId:x.approvalRequestId,decision:j,source:"client"},createdAt:new Date().toISOString()}]}))}catch(L){kt(N,ie=>({...ie,events:[...ie.events,{id:ie.events.length+1,event:"client.error",data:_s(L),createdAt:new Date().toISOString()}]}));const V=dt(L);Le("error","Failed to respond to approval",V.detail??V.message)}}async function Jr(x,j,N){const L=w,V=x.workspaceChangeProposalId??x.responsibilityProposalId;if(!L||!V)return!1;try{const ie=Ne(`conversations/${L}/workspace-change-proposals/${encodeURIComponent(V)}`),Se=await fetch(ie,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({decision:j,payload:j==="accept"?N??x.workspaceChangePayload:void 0})});if(!Se.ok)throw await Fn(Se,{method:"POST",url:ie});const Ge=await Se.json(),ze=WA(j,Ge.decision),_e=ze==="accept"?Ge.payload??N??x.workspaceChangePayload:null;return hr(Ge.conversation),kt(L,Rt=>({...Rt,events:[...Rt.events,{id:`${x.id}:${ze}`,event:"server.workspace_change.decision",data:{proposalId:V,changeType:x.workspaceChangeType??"responsibility",decision:ze,payload:_e},createdAt:new Date().toISOString()}]})),Le("success",ze==="accept"?"Workspace change applied":"Workspace change declined"),!0}catch(ie){console.error(ie);const Se=dt(ie);return Le("error","Failed to respond to workspace change proposal",Se.detail??Se.message),!1}}async function Cs(x,j,N){const L=w;if(!(!L||!x.knowledgeProposalId))try{let V;if(j==="accept")try{V=JSON.parse(N??x.body)}catch{Le("error","Knowledge proposal JSON is invalid");return}const ie=Ne(`conversations/${L}/knowledge-proposals/${encodeURIComponent(x.knowledgeProposalId)}`),Se=await fetch(ie,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({decision:j,knowledge:V})});if(!Se.ok)throw await Fn(Se,{method:"POST",url:ie});const Ge=await Se.json();li([...Ge.items??[]].sort(g5)),kt(L,ze=>({...ze,events:[...ze.events,{id:`${x.id}:${j}`,event:"server.knowledge.decision",data:{proposalId:x.knowledgeProposalId,decision:j,knowledge:j==="accept"?Ge.item:null},createdAt:new Date().toISOString()}]})),Le("success",j==="accept"?"Workspace knowledge saved":"Knowledge proposal declined")}catch(V){console.error(V);const ie=dt(V);Le("error","Failed to respond to knowledge proposal",ie.detail??ie.message)}}function T0(x){Au(x.id,x.status),To(x),Ce(j=>{const N=j[x.id],L=x.events.map(V=>({id:V.id,turnId:V.turnId,seq:V.seq,event:V.event,data:V.data,createdAt:V.createdAt}));return{...j,[x.id]:{messages:x.messages,events:Bd(L,(N==null?void 0:N.events)??[]),timelineNodes:tp(x.timelineNodes??[],(N==null?void 0:N.timelineNodes)??[]),turns:ep(x.turns??[],(N==null?void 0:N.turns)??[]),contextVersions:x.contextVersions??[],status:x.status,history:ps(x),loadingOlder:!1,fullEventTurnIds:(N==null?void 0:N.fullEventTurnIds)??new Set,loadingEventTurnIds:(N==null?void 0:N.loadingEventTurnIds)??new Set}}})}function qf(x){const j=ps(x);kt(x.id,N=>{var L,V,ie;return{...N,messages:Jm(x.messages,N.messages),timelineNodes:tp(x.timelineNodes??[],N.timelineNodes),turns:ep(x.turns??[],N.turns),events:Bd(x.events.map(Se=>({id:Se.id,turnId:Se.turnId,seq:Se.seq,event:Se.event,data:Se.data,createdAt:Se.createdAt})),N.events),contextVersions:(((L=x.contextVersions)==null?void 0:L.length)??0)>0?x.contextVersions??[]:N.contextVersions,history:{...j,loadedMessageCount:j.loadedMessageCount+(((V=N.history)==null?void 0:V.loadedMessageCount)??N.messages.length),loadedEventCount:j.loadedEventCount+(((ie=N.history)==null?void 0:ie.loadedEventCount)??N.events.length)},loadingOlder:!1}})}function A0(x){const j=ps(x),N=x.events.map(L=>({id:L.id,turnId:L.turnId,seq:L.seq,event:L.event,data:L.data,createdAt:L.createdAt}));kt(x.id,L=>{var V,ie,Se;return{...L,messages:Jm(L.messages,x.messages),timelineNodes:tp(L.timelineNodes,x.timelineNodes??[]),turns:ep(L.turns,x.turns??[]),events:Bd(N,L.events),contextVersions:(((V=x.contextVersions)==null?void 0:V.length)??0)>0?x.contextVersions??[]:L.contextVersions,status:x.status,history:{...L.history??j,messageTotal:j.messageTotal,eventTotal:j.eventTotal,loadedMessageCount:Math.max(((ie=L.history)==null?void 0:ie.loadedMessageCount)??L.messages.length,L.messages.length,x.messages.length),loadedEventCount:Math.max(((Se=L.history)==null?void 0:Se.loadedEventCount)??L.events.length,L.events.length,x.events.length)},loadingOlder:!1}})}function kt(x,j){Ce(N=>{const L=N[x]??{messages:[],events:[],timelineNodes:[],turns:[],contextVersions:[],status:"idle",history:null,loadingOlder:!1,fullEventTurnIds:new Set,loadingEventTurnIds:new Set};return{...N,[x]:j(L)}})}function ea(x,j){y(N=>N.map(L=>L.id===x?{...L,status:j,updatedAt:new Date().toISOString()}:L))}function To(x){hr(x)}function hr(x){y(j=>Ul(l,j.map(N=>N.id===x.id?{...N,...x}:N)))}async function xl(x,j){const N=j.filter(L=>{const V=Be[x];return V&&!V.fullEventTurnIds.has(L)&&!V.loadingEventTurnIds.has(L)});if(N.length!==0){kt(x,L=>{const V=new Set(L.loadingEventTurnIds);for(const ie of N)V.add(ie);return{...L,loadingEventTurnIds:V}});try{const L=await Promise.all(N.map(V=>zz(x,V)));kt(x,V=>{const ie=new Set(V.fullEventTurnIds),Se=new Set(V.loadingEventTurnIds),Ge=L.flatMap((ze,_e)=>{const Rt=N[_e];return ie.add(Rt),Se.delete(Rt),ze.map(St=>({id:St.id,turnId:St.turnId,seq:St.seq,event:St.event,data:St.data,createdAt:St.createdAt}))});return{...V,events:Bd(V.events,Ge),fullEventTurnIds:ie,loadingEventTurnIds:Se}})}catch(L){console.error(L),kt(x,V=>{const ie=new Set(V.loadingEventTurnIds);for(const Se of N)ie.delete(Se);return{...V,loadingEventTurnIds:ie}}),Le("error","Failed to load process details")}}}function ta(x,j){const N=new Set(fs.current);j?N.add(x):N.delete(x),fs.current=N,Jc(L=>{const V=new Set(L);return j?V.add(x):V.delete(x),V})}function Ao(x){const j=LA({key:x.key,metaKey:x.metaKey,ctrlKey:x.ctrlKey,shiftKey:x.shiftKey,isComposing:x.nativeEvent.isComposing});j&&(x.preventDefault(),yn({forceNewTurn:j.forceNewTurn}))}function js(x){as(j=>{const N=new Set(j);return N.has(x)?N.delete(x):N.add(x),Xm(l,N),N})}function E0(x){var j;return $A(x.status,(j=x.nextWakeup)==null?void 0:j.status,ao.has(x.id))}function Eo(x){var L;const j=(L=ls.current)==null?void 0:L.getBoundingClientRect(),N=j?x-j.left:x;return U1(N)}function ki(x){x.preventDefault(),x.currentTarget.setPointerCapture(x.pointerId),is(Eo(x.clientX))}function Si(x){x.currentTarget.hasPointerCapture(x.pointerId)&&(x.preventDefault(),is(Eo(x.clientX)))}function N0(x){x.currentTarget.hasPointerCapture(x.pointerId)&&x.currentTarget.releasePointerCapture(x.pointerId);const j=Eo(x.clientX);is(j),gE(l,j)}return u.jsxs("main",{className:`shell${ce?" mobile-sidebar-open":""}`,ref:ls,style:{"--sidebar-width":`${ma}px`},children:[u.jsxs("aside",{className:"sidebar",children:[u.jsxs("div",{className:"sidebar-header",children:[u.jsxs("div",{children:[u.jsxs("p",{className:"eyebrow brand-line",children:[u.jsx("span",{children:"Seele"}),pe?t.role==="admin"?u.jsxs("a",{"aria-label":`Open Seele Host control for Work v${pe}`,className:"work-version-link",href:`${q1()}admin/host`,title:"Open Seele Host control: versions, restart, and logs",children:["v",pe,u.jsx("span",{"aria-hidden":"true",children:"↗"})]}):u.jsxs("span",{children:["v",pe]}):null,u.jsx("span",{"aria-label":j5(xe),className:`backend-status ${xe}`,"data-label":j5(xe)})]}),u.jsxs("div",{className:"sidebar-title-row",children:[u.jsx("h2",{children:"Workspaces"}),e?u.jsx("button",{"aria-label":`Sign out ${t.username}`,className:"sign-out-button",onClick:i,title:`Sign out ${t.username}`,type:"button",children:"Sign out"}):null]})]}),u.jsxs("div",{className:"sidebar-header-actions",children:[u.jsx("button",{"aria-label":"Close workspace list",className:"mobile-sidebar-dismiss",onClick:()=>fe(!1),title:"Close workspace list",type:"button",children:"×"}),u.jsx("button",{"aria-label":"New workspace",className:"new-workspace-button",type:"button",onClick:Wn,children:"+"})]})]}),u.jsx("nav",{className:"session-list","aria-label":"Workspaces",children:gi.map(x=>u.jsxs("section",{className:["workspace-group",yu===x.id?"dragging":"",rs===x.id?"drop-after":"",(ir==null?void 0:ir.kind)==="group"&&ir.id===x.id?"drop-into":""].filter(Boolean).join(" "),"data-group-id":x.id,children:[u.jsxs("div",{className:"workspace-group-header",children:[u.jsxs("button",{"aria-expanded":!Zi.has(x.id),className:(Jt==null?void 0:Jt.kind)==="group"&&Jt.id===x.id?"workspace-group-toggle keyboard-focused":"workspace-group-toggle","data-keyboard-focus-key":Ls({kind:"group",id:x.id}),onClick:j=>{if(bu.current){j.preventDefault(),bu.current=!1;return}js(x.id)},onDoubleClick:j=>{j.preventDefault(),j.stopPropagation(),hl(x)},onPointerCancel:ml,onPointerDown:j=>Va(j,x.id),onPointerMove:j=>C0(j,x.id),onPointerUp:j=>j0(j,x.id),type:"button",children:[u.jsx("span",{className:Zi.has(x.id)?"workspace-group-caret collapsed":"workspace-group-caret","aria-hidden":"true",children:"▾"}),u.jsx("span",{onDoubleClick:j=>{j.preventDefault(),j.stopPropagation(),hl(x)},title:"Double-click to rename",children:x.title})]}),x.id!==U3?u.jsx("button",{"aria-label":`Delete group ${x.title}`,className:"workspace-group-delete",onClick:j=>{j.stopPropagation(),Ga(x)},title:"Delete group",type:"button",children:"×"}):null]}),Zi.has(x.id)?null:u.jsx("div",{className:"workspace-group-items",children:x.conversations.map(j=>{const N=E0(j);return u.jsxs("div",{className:["session-item",(Jt==null?void 0:Jt.kind)==="workspace"&&Jt.id===j.id?"keyboard-focused":"",j.id===w?"active":"",j.id===ns?"dragging":"",(ir==null?void 0:ir.kind)==="workspace"&&ir.id===j.id?`drop-${ir.position}`:""].filter(Boolean).join(" "),"data-keyboard-focus-key":Ls({kind:"workspace",id:j.id}),"data-workspace-id":j.id,onClick:L=>{if(xu.current){L.preventDefault(),xu.current=!1;return}$a(j.id),fe(!1)},onDoubleClick:L=>{jo(L.target)||(L.preventDefault(),Xr(j))},onKeyDown:L=>{Co(L.target)||L.key==="Enter"&&($a(j.id),fe(!1))},onPointerCancel:Iu,onPointerDown:L=>mt(L,j.id),onPointerMove:L=>Pa(L,j.id),onPointerUp:L=>fr(L,j.id),role:"button",tabIndex:0,children:[u.jsxs("span",{className:"session-heading",children:[u.jsx("span",{"aria-label":Yd(N,j.nextWakeup,pa),className:`session-status ${N}`,title:Yd(N,j.nextWakeup,pa)}),u.jsx("span",{className:"session-title",title:"Double-click to rename",children:j.title}),N==="waiting"&&j.nextWakeup?u.jsx("span",{className:"session-countdown",title:Yd(N,j.nextWakeup,pa),children:of(j.nextWakeup,pa)}):null,j.unreadTurnCount>0?u.jsx("span",{"aria-label":`${j.unreadTurnCount} unread turns`,className:"session-unread",title:`${j.unreadTurnCount} unread turns`,children:j.unreadTurnCount>99?"99+":j.unreadTurnCount}):null,N!=="running"?u.jsx("button",{"aria-label":`Delete ${j.title}`,className:"session-delete",onClick:L=>{L.stopPropagation(),ut(j)},title:"Move workspace to recycle",type:"button",children:"×"}):null]}),u.jsxs("span",{className:"session-workspace",title:j.workspacePath,children:["workspaces/",Zo(j.id)]})]},j.id)})})]},x.id))}),u.jsx("footer",{className:"sidebar-footer",children:u.jsxs("div",{className:"sidebar-actions","aria-label":"Workspace actions",children:[u.jsx("button",{"aria-label":"Settings",className:"sidebar-action-button",onClick:m0,type:"button",children:u.jsx(l5,{})}),u.jsx("button",{"aria-label":"New group",className:"sidebar-action-button",onClick:So,type:"button",children:u.jsx(xM,{})}),u.jsx("button",{"aria-label":"Collaboration topics",className:"sidebar-action-button",onClick:()=>{ui(!0),fe(!1)},type:"button",children:u.jsx(Gd,{})}),u.jsx("button",{"aria-label":"Console",className:"sidebar-action-button",onClick:g0,type:"button",children:u.jsx(bM,{})}),u.jsx(kN,{usage:o0})]})})]}),u.jsx("button",{"aria-label":"Close workspace list",className:"mobile-sidebar-backdrop",onClick:()=>fe(!1),tabIndex:ce?0:-1,type:"button"}),u.jsx("div",{"aria-label":"Resize sidebar",className:"sidebar-resizer",onPointerDown:ki,onPointerMove:Si,onPointerUp:N0,role:"separator",tabIndex:0}),wu&&Oa?u.jsxs("div",{className:"workspace-drag-preview",style:{transform:`translate3d(${Oa.x+12}px, ${Oa.y+10}px, 0)`},children:[u.jsx("span",{className:"workspace-drag-title",children:wu.title}),u.jsxs("span",{className:"workspace-drag-path",children:["workspaces/",Zo(wu.id)]})]}):null,Oe?u.jsx("div",{className:"workspace-editor-overlay",onKeyDown:Kr,role:"presentation",children:u.jsxs("form",{className:"workspace-editor",onKeyDown:Kr,onSubmit:x=>void qu(x),children:[u.jsx("label",{className:"workspace-editor-label",htmlFor:"workspace-title",children:"Workspace name"}),u.jsx("input",{autoFocus:!0,id:"workspace-title",onChange:wi,onKeyDown:Kr,value:Oe.title}),Oe.mode==="create"?u.jsxs(u.Fragment,{children:[u.jsx("label",{className:"workspace-editor-label",htmlFor:"workspace-group",children:"Group"}),u.jsx("select",{id:"workspace-group",onChange:Lu,onKeyDown:Kr,value:Oe.groupId??((bl=v[0])==null?void 0:bl.id)??"",children:v.map(x=>u.jsx("option",{value:x.id,children:x.title},x.id))})]}):null,u.jsxs("div",{className:"workspace-editor-actions",children:[u.jsx("button",{type:"button",onClick:Ln,children:"Cancel"}),u.jsx("button",{disabled:Ct,type:"submit",children:Ct?"Saving...":Oe.mode==="create"?"Create":"Save"})]})]})}):null,Qe?u.jsx("div",{className:"workspace-editor-overlay",onKeyDown:Qr,role:"presentation",children:u.jsxs("form",{className:"workspace-editor",onKeyDown:Qr,onSubmit:x=>void ka(x),children:[u.jsx("label",{className:"workspace-editor-label",htmlFor:"workspace-group-title",children:"Group name"}),u.jsx("input",{autoFocus:!0,id:"workspace-group-title",onChange:bs,onKeyDown:Qr,value:Qe.title}),u.jsxs("div",{className:"workspace-editor-actions",children:[u.jsx("button",{type:"button",onClick:dr,children:"Cancel"}),u.jsx("button",{type:"submit",children:Qe.mode==="create"?"Create":"Save"})]})]})}):null,Pt?u.jsx(BE,{currentUser:t,conversations:m,editingEnvironmentKey:ts,deploymentSettings:we,environmentDraft:si,globalEnvironment:qr,workspaceEnvironment:ua,memorySettings:hu,memorySettingsDraft:Kc,workspaceMemoryDraft:An,runtimeSettings:Ur,runtimeModels:et,runtimeCodexVersion:Tn,runtimeCodexReleasedAt:zn,runtimeCodexUpdating:(an==null?void 0:an.status)==="running",runtimeSettingsDraft:Pi,runtimeSettingsScope:nr,settingsWorkspace:dn,settingsWorkspaceId:Bt,systemDiagnostics:O,systemDiagnosticsLoading:z,workspaceGroups:gi,workspaceRuntimeSettings:du,workspaceRuntimeSettingsDraft:fu,managedUsers:Ye,onCancelEnvironmentEdit:Bf,onClose:()=>Wt(!1),onCreateUser:async x=>{const j=await bD(x);U(N=>[...N,j]),Le("success","User created")},onDeleteUser:async x=>{await kD(x),U(j=>j.filter(N=>N.id!==x)),Le("success","User deleted")},onSaveDeploymentSettings:v0,onDeleteEnvironment:x=>void Ou(x),onDraftChange:Fr,onEditEnvironment:dl,onRevealEnvironmentValue:x=>void Yn(x),onSaveBaseMemoryItems:x=>Ru(x),onSaveResponsibility:async(x,j)=>{try{const N=await qd(x,{responsibility:j});return hr(N),oe("connected"),Le("success","Workspace responsibility saved"),N.responsibility}catch(N){throw console.error(N),oe("error"),Le("error","Failed to save workspace responsibility"),N}},onSaveWorkspaceMemoryItems:x=>Bt?xo(Bt,x):Promise.reject(new Error("No workspace selected")),onRuntimeDraftChange:cu,onCodexAccountSwitched:async()=>{Le("success","Codex account switched"),(await G7()).codexAccountsReady&&await Promise.all([ys(!0),Ha(!0),vs()])},onUpdateCodexCli:()=>{Dt(!0),yo(!0)},onRuntimeScopeChange:Na,onSettingsWorkspaceChange:_f,onSubmitRuntimeSettings:x=>void y0(x),onWorkspaceRuntimeDraftChange:ii,onWorkspaceRuntimeReset:x=>Bt?void cl(Bt,x):void 0,revealedEnvironmentKeys:Ki,onSubmitEnvironment:x=>void bo(x),onRefreshSystemDiagnostics:()=>void ba(),onUpdateUser:async(x,j)=>{const N=await wD(x,j);U(L=>L.map(V=>V.id===N.id?N:V)),Le("success","User updated")}}):null,Dn?u.jsx(_E,{currentReleasedAt:zn,currentVersion:Tn,job:an,latest:Ks,latestChecking:ai,starting:zf,onClose:()=>Dt(!1),onRefresh:()=>void yo(),onStart:()=>void xi()}):null,Ma&&We?u.jsx(zE,{conversation:We,clockNow:pa,knowledgeDraft:Wi,workspaceKnowledge:Yi,tokenUsage:xa,onCancelKnowledgeEdit:()=>Xi(bc),onDeleteKnowledge:x=>void x0(We.id,x),onEditKnowledge:wo,onKnowledgeDraftChange:Xi,onSubmitKnowledge:x=>void bi(We.id,x),onClose:()=>ln(!1)}):null,oi?u.jsx(DE,{conversations:m,onClose:()=>ui(!1),workspaceGroups:gi}):null,Zs?u.jsx(RE,{busy:to||$r,conversation:Wr??null,conversationId:za,forceStopBusy:$r,preview:(Gr==null?void 0:Gr.conversationId)===za?Gr:null,previewLoading:Qc,result:no,status:i0,warmup:pu,workspaceGroups:gi,onClose:()=>Js(!1),onCancelResetPreview:()=>Da(null),onForceStop:()=>void Fu(),onPreviewReset:()=>void Du(),onStartBlankContext:()=>void vo(),onResetRuntime:x=>void jr(x),onSaveResetSelection:or,onWorkspaceChange:x=>{eo(x),Ra(null),Da(null)},onWarmupChange:Df}):null,K?u.jsx("div",{className:"dialog-backdrop",role:"presentation",onMouseDown:()=>!J&&le(null),children:u.jsxs("form",{className:"dialog-card clone-dialog",onSubmit:Bu,onMouseDown:x=>x.stopPropagation(),children:[u.jsxs("header",{children:[u.jsxs("div",{children:[u.jsx("h2",{children:"Clone workspace"}),u.jsx("p",{children:"Copy stable visible history and reusable workspace context into an independent workspace."})]}),u.jsx("button",{"aria-label":"Close",className:"icon-button",onClick:()=>le(null),type:"button",children:"×"})]}),u.jsxs("label",{children:[u.jsx("span",{children:"Name"}),u.jsx("input",{autoFocus:!0,value:K.name,onChange:x=>le(j=>j&&{...j,name:x.target.value})})]}),u.jsxs("label",{children:[u.jsx("span",{children:"Group"}),u.jsx("select",{value:K.groupId,onChange:x=>le(j=>j&&{...j,groupId:x.target.value}),children:gi.map(x=>u.jsx("option",{value:x.id,children:x.title},x.id))})]}),u.jsxs("footer",{children:[u.jsx("button",{className:"secondary",disabled:J,onClick:()=>le(null),type:"button",children:"Cancel"}),u.jsx("button",{disabled:J||!K.name.trim(),type:"submit",children:J?"Cloning...":"Clone"})]})]})}):null,F?u.jsx("div",{className:"dialog-backdrop",role:"presentation",onMouseDown:()=>Y(null),children:u.jsxs("section",{"aria-labelledby":"complex-task-detail-title","aria-modal":"true",className:"dialog-card task-detail-dialog",onMouseDown:x=>x.stopPropagation(),role:"dialog",children:[u.jsxs("header",{children:[u.jsxs("div",{children:[u.jsx("h2",{id:"complex-task-detail-title",children:F.title}),u.jsxs("p",{children:[C5(F.status),F.startedAt&&F.finishedAt?` · ${dD(F.startedAt,F.finishedAt)}`:""]})]}),u.jsx("button",{"aria-label":"Close",className:"icon-button",onClick:()=>Y(null),type:"button",children:"×"})]}),u.jsxs("div",{className:"complex-task-detail task-record-detail",children:[u.jsxs("div",{children:[u.jsx("small",{children:"Objective"}),u.jsx("p",{children:F.objective??"No objective recorded."})]}),u.jsxs("div",{children:[u.jsx("small",{children:F.status==="completed"?"Final plan":"Current plan"}),F.currentPlan?u.jsx("article",{className:"message assistant complex-task-plan-preview",children:u.jsx("div",{className:"message-main",children:u.jsx("div",{className:"message-body",children:Yl(F.currentPlan.planMarkdown,We)})})}):u.jsx("p",{children:"No plan recorded."})]}),u.jsxs("dl",{children:[u.jsxs("div",{children:[u.jsx("dt",{children:"Goal"}),u.jsx("dd",{children:F.codexGoalStatus??"not started"})]}),u.jsxs("div",{children:[u.jsx("dt",{children:"Plan versions"}),u.jsx("dd",{children:F.planVersions.length})]}),u.jsxs("div",{children:[u.jsx("dt",{children:"Started"}),u.jsx("dd",{children:F.startedAt?rt(F.startedAt):"—"})]}),u.jsxs("div",{children:[u.jsx("dt",{children:"Finished"}),u.jsx("dd",{children:F.finishedAt?rt(F.finishedAt):"—"})]})]})]}),u.jsx("footer",{children:u.jsx("button",{className:"secondary",onClick:()=>Y(null),type:"button",children:"Close"})})]})}):null,te?u.jsx("div",{className:"dialog-backdrop",role:"presentation",onMouseDown:()=>_(null),children:u.jsxs("section",{"aria-labelledby":"system-event-detail-title","aria-modal":"true",className:"dialog-card system-event-detail-dialog",onMouseDown:x=>x.stopPropagation(),role:"dialog",children:[u.jsxs("header",{children:[u.jsxs("div",{children:[u.jsx("h2",{id:"system-event-detail-title",children:te.title}),u.jsx("p",{children:rt(te.createdAt)})]}),u.jsx("button",{"aria-label":"Close",className:"icon-button",onClick:()=>_(null),type:"button",children:"×"})]}),u.jsx("div",{className:"system-event-detail-content",children:u.jsx(Ec,{content:te.fullDetail??te.detail??"No additional details.",conversation:We,streaming:!1,onPreviewArtifact:Cr,onCopyArtifactUrl:Ua,copiedArtifactUrl:rr})}),u.jsxs("footer",{children:[te.linkedTaskId?u.jsx("button",{onClick:()=>{const x=te.linkedTaskId;_(null),wa(x)},type:"button",children:"View task"}):null,u.jsx("button",{className:"secondary",onClick:()=>_(null),type:"button",children:"Close"})]})]})}):null,Je?u.jsx("div",{className:"memory-editor-overlay",onClick:()=>{At||ut(null)},role:"presentation",children:u.jsxs("section",{"aria-label":"Confirm workspace recycle","aria-modal":"true",className:"memory-delete-dialog workspace-delete-dialog",onClick:x=>x.stopPropagation(),role:"dialog",children:[u.jsxs("header",{children:[u.jsx("strong",{children:"Move Workspace to Recycle"}),u.jsx("button",{"aria-label":"Close workspace recycle confirmation",className:"memory-icon-button",disabled:At,onClick:()=>ut(null),title:"Close",type:"button",children:"×"})]}),u.jsxs("p",{children:["Move ",u.jsx("strong",{children:Je.title})," to recycle?"]}),u.jsx("code",{children:Je.workspacePath}),u.jsxs("div",{className:"memory-delete-actions",children:[u.jsx("button",{className:"memory-dialog-button",disabled:At,onClick:()=>ut(null),type:"button",children:"Cancel"}),u.jsx("button",{className:"memory-dialog-button danger",disabled:At,onClick:()=>void cr(Je),type:"button",children:At?"Moving...":"Move to recycle"})]})]})}):null,On?u.jsxs("div",{className:`app-toast ${On.tone}`,role:"status",children:[u.jsx("strong",{children:On.text}),On.detail?u.jsx("pre",{children:On.detail}):null]}):null,u.jsxs("section",{className:"conversation",children:[u.jsxs("header",{className:"topbar",children:[u.jsxs("div",{className:"topbar-main",children:[u.jsx("button",{"aria-label":"Show workspaces",className:"mobile-workspace-menu",onClick:()=>fe(!0),title:"Workspaces",type:"button",children:u.jsx(vM,{})}),u.jsxs("div",{className:"topbar-heading",children:[u.jsx("div",{className:"topbar-title-row",children:u.jsx("h1",{children:(We==null?void 0:We.title)??"New workspace"})}),We?u.jsxs("p",{className:"topbar-workspace",children:["workspaces/",Zo(We.id)]}):null]})]}),u.jsx("div",{className:"topbar-actions",children:We?u.jsxs(u.Fragment,{children:[We.threadUpgradeRequired?u.jsx("button",{"aria-label":"Reset required for latest thread tools",className:"topbar-icon-button thread-upgrade-button",onClick:g0,title:`当前 Thread 工具集已过期(${We.threadCapabilityVersion} / ${We.requiredThreadCapabilityVersion}),点击进行 Reset`,type:"button",children:u.jsx(S7,{})}):null,u.jsx("button",{"aria-label":"Clone workspace",className:"topbar-icon-button",onClick:b0,title:"Clone workspace",type:"button",children:u.jsx(yM,{})}),u.jsxs("button",{className:`context-button has-usage ${W1(ms??0)}`,onClick:()=>ln(!0),style:{"--context-usage":`${Nf(ms??0)}%`},title:xa&&ms!==null?`Context ${Math.round(ms)}% · ${wr(xa.totalTokens)} / ${Vd(xa.modelContextWindow)}`:"Context 0% · no usage recorded yet",type:"button",children:[u.jsx("span",{children:"Context"}),u.jsxs("strong",{children:[Math.round(ms??0),"%"]})]}),u.jsx("button",{"aria-label":"Workspace settings",className:"topbar-icon-button",onClick:p0,title:"Workspace settings",type:"button",children:u.jsx(l5,{})})]}):null})]}),E?u.jsxs("section",{className:`complex-task-bar ${E.status}`,children:[u.jsxs("button",{className:"complex-task-summary",onClick:()=>void wa(E.id),title:"View complex task details",type:"button",children:[u.jsx("span",{className:"complex-task-kicker",children:"Complex task"}),u.jsx("strong",{children:E.title}),u.jsx("span",{className:"complex-task-state",children:C5(E.status)}),u.jsx("span",{className:"complex-task-duration",children:cD(E,pa)})]}),u.jsxs("div",{className:"complex-task-actions",children:[up(E.status,"discussing","ready","replanning")?u.jsx("button",{disabled:!E.objective||!E.currentPlan,onClick:()=>void Tr("start"),title:E.objective&&E.currentPlan?"Start this complex task":"A complete candidate plan is required before starting",type:"button",children:"Start"}):null,E.status==="active"?u.jsx("button",{onClick:()=>void Tr("pause"),type:"button",children:"Pause"}):null,up(E.status,"paused","waiting","blocked")?u.jsx("button",{onClick:()=>void Tr("resume"),type:"button",children:"Resume"}):null,up(E.status,"active","paused","waiting","blocked")?u.jsx("button",{className:"secondary",onClick:()=>void Tr("replan"),type:"button",children:"Replan"}):null,u.jsx("button",{className:"quiet danger",onClick:()=>void Tr("end"),type:"button",children:"End task"})]})]}):null,(We==null?void 0:We.status)==="initialization_failed"&&We.cloneLineage?u.jsxs("div",{className:"clone-initialization-error",children:[u.jsxs("div",{children:[u.jsx("strong",{children:"Clone initialization failed"}),u.jsx("span",{children:We.cloneLineage.initializationError??"The runtime could not initialize this clone."})]}),u.jsx("button",{onClick:()=>void w0(),type:"button",children:"Retry with a clean thread"})]}):null,u.jsx("div",{className:"stream",onScroll:()=>void ju(),ref:ss,style:{scrollPaddingBottom:Ji},children:u.jsxs("div",{className:"stream-inner",style:{paddingBottom:Ji},children:[il.length===0?u.jsx("div",{className:"empty-state",children:u.jsx("h2",{children:"Start a workspace"})}):null,u.jsxs("section",{className:"message-log","aria-label":"Conversation messages",children:[We!=null&&We.cloneLineage&&Su.size>0?u.jsxs("div",{className:"clone-history-boundary clone-history-source",children:[u.jsxs("strong",{children:["Inherited from ",We.cloneLineage.sourceWorkspaceTitle]}),u.jsxs("span",{children:["through ",rt(We.cloneLineage.snapshotAt)," · ",We.cloneLineage.importedMessageCount," messages"]})]}):null,(Ts=Et==null?void 0:Et.history)!=null&&Ts.hasMoreBefore?u.jsx("div",{className:"history-loader",children:Et.loadingOlder?"Loading earlier messages...":"Scroll up for earlier messages"}):null,ku.map((x,j)=>{var Se,Ge,ze;const N=((Se=x.user)==null?void 0:Se.type)==="system",L=x.turnIds.some(_e=>Su.has(_e)),V=ku[j+1],ie=L&&(!V||!V.turnIds.some(_e=>Su.has(_e)));return u.jsxs(I.Fragment,{children:[u.jsxs("section",{className:`turn-group${L?" clone-history-turn":""}`,"data-turn-id":x.id,children:[x.user?u.jsxs("div",{className:`turn-panel ${N?"system-turn":"user-turn"}`,children:[jc(x.user,We,Cr,Ua,rr,Zr,Jr,Cs,wa,_),u.jsx(Tc,{copied:Qi===`${N?"system":"user"}-${x.id}-bottom`,content:Ac(x.user),id:`${N?"system":"user"}-${x.id}-bottom`,timestamp:x.user.createdAt,variant:"outside",onCopy:ol})]}):null,x.followupUsers.length>0?u.jsx("div",{className:"turn-followup-users","aria-label":"Additional turn input",children:x.followupUsers.map(_e=>u.jsxs("div",{className:"turn-panel user-turn followup-user-turn",children:[u.jsx("span",{className:"followup-user-label",children:"Added while running"}),jc(_e,We,Cr,Ua,rr,Zr,Jr,Cs,wa,_),u.jsx(Tc,{copied:Qi===`user-${_e.id}-bottom`,content:Ac(_e),id:`user-${_e.id}-bottom`,timestamp:_e.createdAt,variant:"outside",onCopy:ol})]},_e.id))}):null,(Ge=x.acceptedSystemInputs)==null?void 0:Ge.map(_e=>u.jsxs("div",{className:"turn-panel system-turn",children:[jc(_e,We,Cr,Ua,rr,Zr,Jr,Cs,wa,_),u.jsx(Tc,{copied:Qi===`system-${_e.id}-bottom`,content:Ac(_e),id:`system-${_e.id}-bottom`,timestamp:_e.createdAt,variant:"outside",onCopy:ol})]},_e.id)),x.agentItems.length>0?u.jsx(oN,{group:x,conversation:We,allowProcessView:!L,copiedFooter:Qi===`agent-${x.id}-bottom`,copiedArtifactUrl:rr,running:!L&&Oc(x.turnIds,sl),onCopyArtifactUrl:Ua,onCopyBubble:ol,onPreviewArtifact:Cr,onLoadProcessDetails:_e=>We&&!L?xl(We.id,_e):void 0,onRespondApproval:Zr,onRespondWorkspaceChangeProposal:Jr,onRespondKnowledgeProposal:Cs,onOpenComplexTask:wa,onOpenSystemEvent:_}):null,(ze=x.trailingSystemItems)==null?void 0:ze.map(_e=>u.jsxs("div",{className:"turn-panel system-turn",children:[jc(_e,We,Cr,Ua,rr,Zr,Jr,Cs,wa,_),u.jsx(Tc,{copied:Qi===`system-${_e.id}-bottom`,content:Ac(_e),id:`system-${_e.id}-bottom`,timestamp:_e.createdAt,variant:"outside",onCopy:ol})]},_e.id))]}),ie?u.jsx("div",{className:"clone-history-boundary clone-history-end",children:"Clone starts here"}):null]},x.id)})]})]})}),u.jsxs("form",{className:"composer",onSubmit:Sa,ref:In,children:[qa?u.jsxs("div",{className:`global-activity ${qa.tone??"running"}`,children:[La?u.jsx("button",{"aria-label":"Stop current workspace activity",className:"turn-stop activity-stop",onClick:()=>void Ss(),title:"Stop current workspace activity",type:"button",children:u.jsx(dN,{})}):u.jsx("span",{className:"activity-wait-dot","aria-hidden":"true"}),u.jsxs("div",{className:"global-activity-text",children:[u.jsx("span",{children:qa.title}),qa.detail?u.jsx("small",{children:qa.detail}):null]}),La?u.jsx("span",{className:"activity-spinner","aria-hidden":"true"}):null]}):null,u.jsxs("div",{className:"composer-panel",children:[u.jsxs("button",{"aria-label":E?"Complex task mode is locked while a task is in progress":"Toggle complex task mode","aria-pressed":!!E||R==="complex",className:`complex-mode-button ${E||R==="complex"?"active":""}`,disabled:!!E,onClick:()=>B(x=>x==="complex"?"simple":"complex"),title:E?"End the current complex task before switching back":R==="complex"?"Complex task mode on":"Complex task mode off",type:"button",children:[u.jsx(s7,{}),u.jsx("span",{className:"complex-mode-tooltip",role:"tooltip",children:E?"Complex task active":R==="complex"?"Complex task mode on":"Complex task mode off"})]}),u.jsx("textarea",{disabled:Cu.textareaDisabled,onChange:x=>Uu(x.target.value),onKeyDown:Ao,placeholder:"Cmd/Ctrl + Enter",ref:ga,value:o}),u.jsxs("button",{"aria-label":"Send message",className:"composer-send",disabled:Cu.sendDisabled,type:"submit",children:[u.jsx(fN,{}),u.jsxs("span",{className:"composer-send-tooltip",role:"tooltip",children:[u.jsxs("span",{children:[u.jsx("kbd",{children:"⌘ / Ctrl + Enter"})," Send or add to running turn"]}),u.jsxs("span",{children:[u.jsx("kbd",{children:"⇧ + ⌘ / Ctrl + Enter"})," New turn or queue"]})]})]})]})]}),Pr?u.jsx("div",{className:"artifact-lightbox",onClick:()=>Cr(null),role:"presentation",children:u.jsxs("figure",{className:"artifact-lightbox-card",onClick:x=>x.stopPropagation(),children:[u.jsx("button",{"aria-label":"Close preview",className:"artifact-lightbox-close",onClick:()=>Cr(null),type:"button",children:"×"}),u.jsx("img",{alt:Pr.name,src:Pr.url}),u.jsxs("figcaption",{children:[u.jsx("span",{children:Pr.name}),u.jsxs("div",{className:"artifact-lightbox-actions",children:[u.jsx("a",{href:Pr.url,rel:"noreferrer",target:"_blank",children:"Open in new tab"}),u.jsx("button",{onClick:()=>void Ua(Pr),type:"button",children:rr===Pr.url?"Copied":"Copy URL"})]})]})]})}):null]})]})}function zE({conversation:e,clockNow:t,knowledgeDraft:n,workspaceKnowledge:i,tokenUsage:l,onCancelKnowledgeEdit:o,onDeleteKnowledge:c,onEditKnowledge:f,onKnowledgeDraftChange:h,onSubmitKnowledge:m,onClose:y}){const[v,k]=I.useState("overview"),[w,T]=I.useState(!1),[E,q]=I.useState(!1),[R,B]=I.useState(null),[F,Y]=I.useState(null),[te,_]=I.useState(!1),[K,le]=I.useState(null),[J,G]=I.useState(null),[ce,fe]=I.useState(!1),[Be,Ce]=I.useState(null),[ve,ee]=I.useState(null),pe=L7(l),De=Jp(e,e.status),Ye=R?Qz(R):null;I.useEffect(()=>{T(!1),B(null),Y(null),le(null),G(null),Ce(null),ee(null)},[e.id]),I.useEffect(()=>{v==="additionalContext"&&!K&&O()},[v,K]),I.useEffect(()=>{v==="compactions"&&!Be&&Q()},[v,Be]);const U=()=>{T(!0),q(!0),Y(null),nz(e.id).then(z=>B(z)).catch(z=>{const de=dt(z);Y(de.detail?`${de.message}
351
- ${de.detail}`:de.message)}).finally(()=>q(!1))},O=()=>{_(!0),G(null),az(e.id).then(z=>le(z)).catch(z=>{const de=dt(z);G(de.detail?`${de.message}
352
- ${de.detail}`:de.message)}).finally(()=>_(!1))},Q=()=>{fe(!0),ee(null),iz(e.id).then(z=>Ce(z)).catch(z=>{const de=dt(z);ee(de.detail?`${de.message}
353
- ${de.detail}`:de.message)}).finally(()=>fe(!1))};return u.jsx("div",{className:"context-panel-overlay workspace-context-overlay",onClick:y,role:"presentation",children:u.jsxs("section",{"aria-label":"Workspace context",className:"context-panel workspace-context-panel",onClick:z=>z.stopPropagation(),children:[u.jsxs("header",{className:"context-panel-header workspace-context-header",children:[u.jsxs("div",{children:[u.jsx("h2",{children:"Workspace Context"}),u.jsx("p",{children:"Long-lived context assets and observable state for this workspace."})]}),u.jsx("button",{"aria-label":"Close context panel",onClick:y,type:"button",children:"×"})]}),u.jsxs("div",{className:"workspace-context-body",children:[u.jsxs("nav",{className:"settings-nav workspace-context-nav","aria-label":"Workspace context sections",children:[u.jsxs("button",{className:v==="overview"?"active":void 0,onClick:()=>k("overview"),type:"button",children:[u.jsx("span",{children:"Overview"}),u.jsx("small",{children:"Identity + state"})]}),u.jsxs("button",{className:v==="responsibility"?"active":void 0,onClick:()=>k("responsibility"),type:"button",children:[u.jsx("span",{children:"Responsibility"}),u.jsx("small",{children:"Long-lived role"})]}),u.jsxs("button",{className:v==="knowledge"?"active":void 0,onClick:()=>k("knowledge"),type:"button",children:[u.jsx("span",{children:"Knowledge"}),u.jsx("small",{children:"Sources + skills"})]}),u.jsxs("button",{className:v==="runtime"?"active":void 0,onClick:()=>k("runtime"),type:"button",children:[u.jsx("span",{children:"Runtime View"}),u.jsx("small",{children:"Thread + tokens"})]}),u.jsxs("button",{className:v==="compactions"?"active":void 0,onClick:()=>k("compactions"),type:"button",children:[u.jsx("span",{children:"Compactions"}),u.jsx("small",{children:"Context history"})]}),u.jsxs("button",{className:v==="additionalContext"?"active":void 0,onClick:()=>k("additionalContext"),type:"button",children:[u.jsx("span",{children:"Additional Context"}),u.jsx("small",{children:"Injected keys"})]})]}),u.jsx("div",{className:"workspace-context-content",children:v==="overview"?u.jsxs("div",{className:"workspace-context-grid",children:[u.jsxs("section",{className:`context-card wide workspace-status-detail ${De}`,children:[u.jsx("h3",{children:"Current Status"}),u.jsx(wt,{label:"Status",value:Yd(De,e.nextWakeup,t)}),e.nextWakeup?u.jsxs(u.Fragment,{children:[u.jsx(wt,{label:"Wakeup state",value:e.nextWakeup.status}),u.jsx(wt,{label:"Wake at",value:Lc(e.nextWakeup.wakeAt)}),e.nextWakeup.status==="scheduled"?u.jsx(wt,{label:"Remaining",value:of(e.nextWakeup,t)}):null,u.jsx(wt,{label:"Created by",value:e.nextWakeup.createdBy}),u.jsx(wt,{label:"Attempts",value:`${e.nextWakeup.attemptCount} / ${e.nextWakeup.maxAttempts}`,mono:!0}),u.jsxs("div",{className:"workspace-status-detail-text",children:[u.jsx("span",{children:"Wakeup instruction"}),u.jsx("pre",{children:e.nextWakeup.instruction})]}),e.nextWakeup.error?u.jsxs("div",{className:"workspace-status-detail-text error",children:[u.jsx("span",{children:"Wakeup error"}),u.jsx("pre",{children:e.nextWakeup.error})]}):null]}):null,e.statusError?u.jsxs("div",{className:"workspace-status-detail-text error",children:[u.jsx("span",{children:"Error"}),u.jsx("pre",{children:e.statusError})]}):e.status==="error"||e.status==="initialization_failed"?u.jsx("p",{className:"context-muted",children:"No persisted error detail is available for this status."}):null]}),u.jsxs("section",{className:"context-card",children:[u.jsx("h3",{children:"Workspace"}),u.jsx(wt,{label:"Name",value:e.title}),u.jsx(wt,{label:"ID",value:`workspaces/${Zo(e.id)}`,mono:!0}),u.jsx(wt,{label:"Path",value:e.workspacePath,mono:!0})]}),u.jsxs("section",{className:"context-card",children:[u.jsx("h3",{children:"Context Assets"}),u.jsx(wt,{label:"Responsibility",value:e.responsibility.trim()?"configured":"missing"}),u.jsx(wt,{label:"Memory",value:e.memory.trim()?"configured":"empty"}),u.jsx(wt,{label:"Knowledge",value:`${i.length} item${i.length===1?"":"s"}`})]}),u.jsxs("section",{className:"context-card wide",children:[u.jsx("h3",{children:"Current Responsibility"}),e.responsibility.trim()?u.jsx("div",{className:"context-markdown-preview",children:Yl(e.responsibility,e)}):u.jsx("p",{className:"context-muted",children:"No approved responsibility is configured yet."})]}),u.jsxs("section",{className:"context-card wide",children:[u.jsx("h3",{children:"Knowledge Index"}),u.jsx(l7,{items:i,onDelete:c,onEdit:z=>{f(z),k("knowledge")}})]})]}):v==="responsibility"?u.jsxs("section",{className:"context-tab-surface",children:[u.jsx("header",{className:"settings-section-header",children:u.jsxs("div",{children:[u.jsx("h3",{children:"Workspace Responsibility"}),u.jsx("p",{children:"User-approved long-lived role for this workspace. Edit it from Settings in workspace scope."})]})}),e.responsibility.trim()?u.jsx("div",{className:"context-card context-markdown-preview",children:Yl(e.responsibility,e)}):u.jsx("p",{className:"context-card context-muted",children:"No approved responsibility is configured yet."})]}):v==="knowledge"?u.jsx(ZE,{draft:n,items:i,scope:"workspace",workspaceName:e.title,onCancel:o,onDelete:c,onDraftChange:h,onEdit:f,onSubmit:m}):v==="runtime"?u.jsxs("div",{className:"workspace-context-grid",children:[u.jsxs("section",{className:"context-card",children:[u.jsx("h3",{children:"Runtime"}),u.jsx(wt,{label:"Runtime thread",value:e.codexThreadId??"not started",mono:!0}),u.jsxs("div",{className:"thread-read-actions",children:[u.jsx("button",{disabled:E,onClick:U,type:"button",children:E?"Reading...":"Read Codex thread"}),w?u.jsx("button",{disabled:E,onClick:()=>T(!1),type:"button",children:"Hide"}):null]})]}),u.jsxs("section",{className:"context-card",children:[u.jsx("h3",{children:"Token Window"}),l?u.jsxs(u.Fragment,{children:[u.jsx(wt,{label:"Used",value:pe===null?"unknown":`${Math.round(pe)}%`,mono:!0}),u.jsx(wt,{label:"Latest usage",value:l.modelContextWindow?`${wr(l.totalTokens)} / ${wr(l.modelContextWindow)}`:wr(l.totalTokens),mono:!0}),pe!==null?u.jsx("div",{className:`context-token-bar ${W1(pe)}`,children:u.jsx("span",{style:{width:`${Nf(pe)}%`}})}):null,u.jsx(wt,{label:"Input / output",value:`${Vd(l.inputTokens)} / ${Vd(l.outputTokens)}`,mono:!0}),u.jsx(wt,{label:"Reasoning",value:Vd(l.reasoningOutputTokens),mono:!0}),u.jsxs("p",{className:"context-muted",children:["Updated ",rt(l.createdAt),"."]})]}):u.jsx("p",{className:"context-muted",children:"No token usage event has been observed in the loaded event window yet."})]}),w?u.jsxs("section",{className:"context-card wide thread-read-panel",children:[u.jsx("h3",{children:"Runtime thread profile"}),u.jsx("p",{className:"context-muted",children:"One-time live thread/read response from Codex app-server. Seele does not persist this profile result."}),E?u.jsx("p",{className:"context-muted",children:"Reading Codex thread..."}):F?u.jsx("pre",{className:"thread-read-error",children:F}):R?u.jsxs(u.Fragment,{children:[Ye?u.jsx(iN,{summary:Ye}):null,u.jsxs("details",{className:"thread-read-raw",open:!0,children:[u.jsx("summary",{children:"Raw thread/read JSON"}),u.jsx("pre",{className:"thread-read-dump",children:JSON.stringify(R,null,2)})]})]}):u.jsx("p",{className:"context-muted",children:"No thread/read result loaded yet."})]}):null]}):v==="compactions"?u.jsxs("section",{className:"context-tab-surface",children:[u.jsxs("header",{className:"settings-section-header",children:[u.jsxs("div",{children:[u.jsx("h3",{children:"Context Compactions"}),u.jsx("p",{children:"Compaction history recorded for the current runtime thread."})]}),u.jsx("button",{className:"context-refresh-button",disabled:ce,onClick:Q,type:"button",children:ce?"Refreshing...":"Refresh"})]}),ve?u.jsx("pre",{className:"thread-read-error",children:ve}):ce&&!Be?u.jsx("p",{className:"context-card context-muted",children:"Loading compaction history..."}):Be!=null&&Be.length?u.jsx("div",{className:"context-compaction-list",children:Be.map(z=>u.jsxs("article",{className:"context-compaction-item",children:[u.jsxs("div",{className:"context-compaction-heading",children:[u.jsx("time",{children:rt(z.completedAt??z.usageObservedAt??z.startedAt??"")}),u.jsx("span",{className:`context-compaction-status ${z.status}`,children:z.status==="completed"?"Completed":"Running"})]}),u.jsx("dl",{className:"context-compaction-facts",children:Gz(z).map(de=>u.jsxs("div",{children:[u.jsx("dt",{children:de.label}),u.jsx("dd",{children:de.value})]},de.label))}),u.jsxs("small",{children:[Xl(z.id),z.turnId?` · turn ${Xl(z.turnId)}`:""]})]},z.id))}):u.jsx("p",{className:"context-card context-muted",children:"No compaction records yet."})]}):u.jsxs("section",{className:"context-tab-surface thread-read-panel",children:[u.jsx("header",{className:"settings-section-header",children:u.jsxs("div",{children:[u.jsx("h3",{children:"Additional Context"}),u.jsx("p",{children:"One-time live render of the application additionalContext for this workspace. Seele does not persist this preview result."})]})}),te?u.jsx("p",{className:"context-card context-muted",children:"Rendering additionalContext..."}):J?u.jsx("pre",{className:"thread-read-error",children:J}):K?u.jsx(rN,{preview:K,refreshing:te,onRefresh:O}):u.jsx("p",{className:"context-card context-muted",children:"No additionalContext preview loaded yet."})]})})]})]})})}function DE({conversations:e,onClose:t,workspaceGroups:n}){var U;const[i,l]=I.useState([]),[o,c]=I.useState("active"),[f,h]=I.useState(null),[m,y]=I.useState([]),[v,k]=I.useState(!0),[w,T]=I.useState(null),[E,q]=I.useState(null),[R,B]=I.useState(!1),[F,Y]=I.useState(!1),[te,_]=I.useState(new Set),[K,le]=I.useState({title:"",publicDescription:"",ownerWorkspaceId:((U=e[0])==null?void 0:U.id)??"",participantWorkspaceIds:[]}),J=i.find(O=>O.id===f)??null,G=I.useMemo(()=>new Map(e.map(O=>[O.id,O.title])),[e]),ce=i.filter(O=>o==="archived"?O.status==="archived":O.status!=="archived"),fe=n.map(O=>({...O,conversations:O.conversations.filter(Q=>Q.id!==K.ownerWorkspaceId)})).filter(O=>O.conversations.length>0),Be=()=>{var O;le({title:"",publicDescription:"",ownerWorkspaceId:((O=e[0])==null?void 0:O.id)??"",participantWorkspaceIds:[]}),_(new Set),q("create")},Ce=()=>{!J||J.status!=="active"||(le({title:J.title,publicDescription:J.publicDescription,ownerWorkspaceId:J.ownerWorkspaceId,participantWorkspaceIds:J.members.filter(O=>O.role==="participant"&&O.status==="active").map(O=>O.workspaceId)}),_(new Set),q("edit"))},ve=async(O,Q=o)=>{var z;k(!0),T(null);try{const de=await c5();l(de);const Re=de.filter(xe=>Q==="archived"?xe.status==="archived":xe.status!=="archived"),ne=(O&&Re.some(xe=>xe.id===O)?O:null)??(f&&Re.some(xe=>xe.id===f)?f:((z=Re[0])==null?void 0:z.id)??null);h(ne),y(ne?await Ld(ne):[])}catch(de){T(de instanceof Qa?de.detail:de instanceof Error?de.message:String(de))}finally{k(!1)}};I.useEffect(()=>{ve()},[]),I.useEffect(()=>{const O=window.setInterval(()=>{(async()=>{try{const Q=await c5();l(Q),f&&Q.some(z=>z.id===f)&&y(await Ld(f))}catch{}})()},1e4);return()=>window.clearInterval(O)},[f]);const ee=async O=>{h(O),T(null);try{y(await Ld(O))}catch(Q){T(Q instanceof Qa?Q.detail:Q instanceof Error?Q.message:String(Q))}},pe=async O=>{var z;if(O===o)return;c(O),T(null);const Q=((z=i.find(de=>O==="archived"?de.status==="archived":de.status!=="archived"))==null?void 0:z.id)??null;if(h(Q),!Q){y([]);return}try{y(await Ld(Q))}catch(de){T(de instanceof Qa?de.detail:de instanceof Error?de.message:String(de))}},De=async O=>{var Q;if(O.preventDefault(),!(!K.title.trim()||!K.ownerWorkspaceId)){Y(!0),T(null);try{const z=E==="edit"&&J?await NM(J.id,{expectedVersion:J.version,title:K.title.trim(),publicDescription:K.publicDescription.trim(),participantWorkspaceIds:K.participantWorkspaceIds}):await EM({...K,title:K.title.trim(),publicDescription:K.publicDescription.trim()});c("active"),q(null),le({title:"",publicDescription:"",ownerWorkspaceId:((Q=e[0])==null?void 0:Q.id)??"",participantWorkspaceIds:[]}),await ve(z.id,"active")}catch(z){T(z instanceof Qa?z.detail:z instanceof Error?z.message:String(z))}finally{Y(!1)}}},Ye=async()=>{if(!(!J||J.status!=="active")){Y(!0),T(null);try{const O=await MM(J.id,J.version);B(!1),c("active"),await ve(void 0,"active")}catch(O){T(O instanceof Qa?O.detail:O instanceof Error?O.message:String(O))}finally{Y(!1)}}};return u.jsx("div",{className:"context-panel-overlay settings-overlay",onClick:t,role:"presentation",children:u.jsxs("section",{"aria-label":"工作空间协作",className:"context-panel collaboration-panel",onClick:O=>O.stopPropagation(),children:[u.jsxs("header",{className:"context-panel-header collaboration-panel-header",children:[u.jsxs("div",{children:[u.jsx("h2",{children:"协作"}),u.jsx("p",{children:"在明确选择的工作空间之间建立持久、定向的 Topic 通信。"})]}),u.jsxs("div",{className:"collaboration-header-actions",children:[u.jsx("button",{"aria-label":"新建 Topic",className:"memory-icon-button collaboration-new-topic",onClick:Be,title:"新建 Topic",type:"button",children:"+"}),u.jsx("button",{"aria-label":"关闭协作",className:"icon-button",onClick:t,type:"button",children:"×"})]})]}),w?u.jsx("div",{className:"collaboration-error",children:w}):null,u.jsxs("div",{className:"collaboration-body",children:[u.jsxs("nav",{className:"collaboration-topic-list","aria-label":"协作 Topics",children:[u.jsxs("div",{className:"collaboration-topic-tabs",role:"tablist","aria-label":"Topic 列表范围",children:[u.jsx("button",{"aria-selected":o==="active",className:o==="active"?"active":void 0,onClick:()=>void pe("active"),role:"tab",type:"button",children:"当前"}),u.jsx("button",{"aria-selected":o==="archived",className:o==="archived"?"active":void 0,onClick:()=>void pe("archived"),role:"tab",type:"button",children:"已归档"})]}),v?u.jsx("p",{children:"正在加载..."}):ce.length===0?u.jsx("p",{children:o==="archived"?"还没有已归档 Topic。":"还没有当前 Topic。"}):ce.map(O=>u.jsxs("button",{className:`collaboration-topic-entry${O.id===f?" active":""}`,onClick:()=>void ee(O.id),type:"button",children:[u.jsx("span",{children:O.title}),u.jsxs("small",{children:[O.members.length," 个工作空间 · ",O.status]})]},O.id))]}),u.jsx("main",{className:"collaboration-topic-detail",children:J?u.jsxs(u.Fragment,{children:[u.jsxs("header",{children:[u.jsxs("div",{children:[u.jsx("h3",{children:J.title}),u.jsx("p",{children:J.publicDescription||"没有公开描述。"})]}),u.jsxs("div",{className:"collaboration-topic-actions",children:[u.jsx("span",{children:J.status}),J.status==="active"?u.jsxs(u.Fragment,{children:[u.jsx("button",{"aria-label":`编辑 Topic ${J.title}`,className:"memory-icon-button",onClick:Ce,title:"编辑",type:"button",children:u.jsx(Ef,{})}),u.jsx("button",{"aria-label":`归档 Topic ${J.title}`,className:"memory-icon-button",onClick:()=>B(!0),title:"归档",type:"button",children:u.jsx(wM,{})})]}):null]})]}),u.jsx("div",{className:"collaboration-members",children:J.members.filter(O=>O.status==="active").map(O=>u.jsxs("span",{children:[O.workspaceTitleSnapshot,u.jsx("small",{children:O.role})]},`${O.workspaceId}-${O.membershipVersion}`))}),u.jsx("div",{className:"collaboration-message-list",children:m.length===0?u.jsx("p",{children:"还没有消息。"}):m.map(O=>u.jsxs("article",{children:[u.jsxs("header",{children:[u.jsx("strong",{children:O.senderTitleSnapshot}),u.jsx("span",{children:O.recipientWorkspaceIds.includes("ALL")?"发给全部参与者":`发给 ${T7(O.recipientWorkspaceIds.map(Q=>G.get(Q)??Xl(Q)))}`}),u.jsx("time",{children:rt(O.createdAt)})]}),u.jsx("div",{className:"markdown-body",children:Yl(O.contentMarkdown,void 0)})]},O.id))})]}):u.jsx("div",{className:"collaboration-empty",children:"选择或新建一个 Topic。"})})]}),E?u.jsx("div",{className:"collaboration-create-overlay",role:"presentation",onClick:()=>!F&&q(null),children:u.jsxs("form",{className:"dialog-card collaboration-create-dialog",onClick:O=>O.stopPropagation(),onSubmit:De,children:[u.jsxs("header",{children:[u.jsxs("div",{children:[u.jsx("h3",{children:E==="edit"?"编辑 Topic":"新建 Topic"}),u.jsx("p",{children:E==="edit"?"调整公开信息与参与工作空间。":"明确选择本次通信的 owner 与参与者。"})]}),u.jsx("button",{"aria-label":"关闭 Topic 编辑",className:"icon-button",onClick:()=>q(null),type:"button",children:"×"})]}),u.jsxs("label",{children:["标题",u.jsx("input",{autoFocus:!0,placeholder:"填写 Topic 标题",value:K.title,onChange:O=>le(Q=>({...Q,title:O.target.value}))})]}),u.jsxs("label",{children:["公开描述",u.jsx("textarea",{placeholder:"填写所有参与工作空间可见的共享背景",value:K.publicDescription,onChange:O=>le(Q=>({...Q,publicDescription:O.target.value}))})]}),u.jsxs("label",{children:["Owner 工作空间",u.jsx("select",{disabled:E==="edit",value:K.ownerWorkspaceId,onChange:O=>le(Q=>({...Q,ownerWorkspaceId:O.target.value,participantWorkspaceIds:Q.participantWorkspaceIds.filter(z=>z!==O.target.value)})),children:n.map(O=>u.jsx("optgroup",{label:O.title,children:O.conversations.map(Q=>u.jsx("option",{value:Q.id,children:Q.title},Q.id))},O.id))})]}),u.jsxs("fieldset",{className:"collaboration-participant-groups",children:[u.jsx("legend",{children:"参与工作空间"}),u.jsxs("div",{className:"collaboration-participant-toolbar",children:[u.jsxs("span",{children:[K.participantWorkspaceIds.length," 个已选择"]}),u.jsxs("div",{children:[u.jsx("button",{onClick:()=>_(new Set),type:"button",children:"全部展开"}),u.jsx("button",{onClick:()=>_(new Set(fe.map(O=>O.id))),type:"button",children:"全部收起"})]})]}),fe.map(O=>{const Q=O.conversations,z=Q.filter(Re=>K.participantWorkspaceIds.includes(Re.id)).length,de=te.has(O.id);return u.jsxs("section",{className:"collaboration-participant-group",children:[u.jsxs("header",{children:[u.jsxs("button",{"aria-expanded":!de,className:"collaboration-group-toggle",onClick:()=>_(Re=>{const ne=new Set(Re);return ne.has(O.id)?ne.delete(O.id):ne.add(O.id),ne}),type:"button",children:[u.jsx("span",{"aria-hidden":"true",className:de?void 0:"expanded",children:"›"}),u.jsx("strong",{children:O.title}),u.jsxs("small",{children:[z,"/",Q.length]})]}),u.jsxs("label",{title:`选择 ${O.title} 全部工作空间`,children:[u.jsx("input",{checked:z===Q.length,onChange:()=>le(Re=>{const ne=Q.map(oe=>oe.id),xe=new Set(Re.participantWorkspaceIds);return ne.every(oe=>xe.has(oe))?ne.forEach(oe=>xe.delete(oe)):ne.forEach(oe=>xe.add(oe)),{...Re,participantWorkspaceIds:Array.from(xe)}}),type:"checkbox"}),u.jsx("span",{children:"全选"})]})]}),de?null:u.jsx("div",{children:Q.map(Re=>u.jsxs("label",{className:"collaboration-participant-option",children:[u.jsx("input",{checked:K.participantWorkspaceIds.includes(Re.id),onChange:ne=>le(xe=>({...xe,participantWorkspaceIds:ne.target.checked?[...xe.participantWorkspaceIds,Re.id]:xe.participantWorkspaceIds.filter(oe=>oe!==Re.id)})),type:"checkbox"}),u.jsx("span",{children:Re.title})]},Re.id))})]},O.id)})]}),u.jsxs("footer",{children:[u.jsx("button",{className:"secondary",disabled:F,onClick:()=>q(null),type:"button",children:"取消"}),u.jsx("button",{disabled:F||!K.title.trim()||!K.ownerWorkspaceId,type:"submit",children:F?"正在保存...":E==="edit"?"保存":"创建 Topic"})]})]})}):null,R&&J?u.jsx("div",{className:"collaboration-create-overlay",onClick:()=>!F&&B(!1),role:"presentation",children:u.jsxs("section",{"aria-label":"归档 Topic",className:"dialog-card collaboration-archive-dialog",onClick:O=>O.stopPropagation(),children:[u.jsxs("header",{children:[u.jsxs("div",{children:[u.jsx("h3",{children:"归档 Topic"}),u.jsx("p",{children:"归档后保留历史消息,但工作空间不能再向此 Topic 发送新消息。"})]}),u.jsx("button",{"aria-label":"关闭归档确认",className:"icon-button",onClick:()=>B(!1),type:"button",children:"×"})]}),u.jsx("strong",{children:J.title}),u.jsxs("footer",{children:[u.jsx("button",{className:"secondary",disabled:F,onClick:()=>B(!1),type:"button",children:"取消"}),u.jsx("button",{className:"danger",disabled:F,onClick:()=>void Ye(),type:"button",children:F?"正在归档...":"归档"})]})]})}):null]})})}function RE({busy:e,conversation:t,conversationId:n,forceStopBusy:i,preview:l,previewLoading:o,result:c,status:f,warmup:h,workspaceGroups:m,onCancelResetPreview:y,onClose:v,onForceStop:k,onPreviewReset:w,onStartBlankContext:T,onResetRuntime:E,onSaveResetSelection:q,onWorkspaceChange:R,onWarmupChange:B}){const F=!t||e||f==="running"||f==="initializing";return u.jsx("div",{className:"context-panel-overlay settings-overlay",onClick:v,role:"presentation",children:u.jsxs("section",{"aria-label":"Seele console",className:"context-panel console-panel",onClick:Y=>Y.stopPropagation(),children:[u.jsxs("header",{className:"context-panel-header console-panel-header",children:[u.jsxs("div",{children:[u.jsx("h2",{children:"Console"}),u.jsx("p",{children:"Control actions for the selected workspace runtime."})]}),u.jsxs("div",{className:"console-header-actions",children:[u.jsxs("label",{className:"console-workspace-picker",children:[u.jsx("span",{children:"Workspace"}),u.jsx("select",{disabled:e,onChange:Y=>R(Y.target.value),value:n??"",children:m.map(Y=>u.jsx("optgroup",{label:Y.title,children:Y.conversations.map(te=>u.jsxs("option",{value:te.id,children:[te.title," · workspaces/",Zo(te.id)]},te.id))},Y.id))})]}),u.jsx("button",{"aria-label":"Close console",onClick:v,type:"button",children:"×"})]})]}),u.jsx("div",{className:"console-body",children:u.jsxs("section",{className:"console-card",children:[u.jsxs("div",{className:"console-card-heading",children:[u.jsxs("div",{children:[u.jsx("h3",{children:"Workspace Runtime"}),u.jsx("p",{children:"Reset only replaces the Codex runtime thread. Seele workspace history, metadata, and files remain intact."})]}),u.jsx("span",{className:`console-status ${f}`,children:f})]}),u.jsxs("dl",{className:"console-facts",children:[u.jsxs("div",{children:[u.jsx("dt",{children:"Workspace"}),u.jsx("dd",{children:(t==null?void 0:t.title)??"No workspace selected"})]}),u.jsxs("div",{children:[u.jsx("dt",{children:"ID"}),u.jsx("dd",{children:t?`workspaces/${Zo(t.id)}`:"-"})]}),u.jsxs("div",{children:[u.jsx("dt",{children:"Thread"}),u.jsx("dd",{children:(t==null?void 0:t.codexThreadId)??"Not created"})]})]}),u.jsxs("label",{className:"console-toggle",children:[u.jsx("input",{checked:h,onChange:Y=>B(Y.target.checked),type:"checkbox"}),u.jsxs("span",{children:["Run a warmup turn after reset",u.jsx("small",{children:"The workspace will receive a system wakeup to re-orient itself after the thread is rebuilt."})]})]}),u.jsxs("div",{className:"console-actions",children:[u.jsx("button",{className:"danger",disabled:!t||i,onClick:k,title:"Kill the workspace runtime and repair every non-terminal scheduler state",type:"button",children:i?"Stopping & repairing...":"Force stop & repair"}),u.jsx("button",{className:"danger",disabled:F||o,onClick:w,type:"button",children:o?"Preparing preview...":"Preview runtime reset"}),u.jsx("button",{disabled:F||o,onClick:T,type:"button",children:"Clear memory & start blank"}),f==="running"||f==="initializing"?u.jsx("span",{children:"Force stop the active workspace operation before resetting."}):null]}),c?u.jsxs("div",{className:"console-result",children:[u.jsx("strong",{children:c.workspaceMemoryCleared?"Blank workspace context ready":"Runtime reset completed"}),u.jsxs("span",{children:[c.injectedItemCount," visible history items injected"]}),c.historyCompactionCount>0?u.jsxs("span",{children:["Full history processed in ",c.historyBatchCount," chronological batches with ",c.historyCompactionCount," native compactions"]}):null,c.workspaceMemoryCleared?u.jsx("span",{children:"Workspace Memory cleared; Base Memory retained"}):null,u.jsxs("span",{children:["New thread: ",c.newThreadId]}),c.warmupTurnId?u.jsxs("span",{children:["Warmup turn: ",c.warmupTurnId]}):null]}):null]})}),l?u.jsx(OE,{busy:e,preview:l,warmup:h,onCancel:y,onConfirm:E,onSaveSelection:q}):null]})})}function OE({busy:e,preview:t,warmup:n,onCancel:i,onConfirm:l,onSaveSelection:o}){const[c,f]=I.useState(()=>new Set(t.entries.filter(G=>G.includedByDefault).map(G=>G.id))),[h,m]=I.useState(!1),[y,v]=I.useState(!1),[k,w]=I.useState(null),T=I.useRef(null),E=t.entries.filter(G=>c.has(G.id)),q=E.filter(G=>G.role==="user").length,R=E.length-q,B=t.entries.filter(G=>G.topicRelation!==null).map(G=>G.id),F=B.filter(G=>c.has(G)).length,Y=t.entries.length>0&&c.size===t.entries.length;I.useEffect(()=>{T.current&&(T.current.indeterminate=c.size>0&&c.size<t.entries.length)},[t.entries.length,c.size]);const te=e||y;async function _(G){v(!0),w(null);try{await o(t.entries.filter(ce=>G.has(ce.id)).map(ce=>ce.id)),f(G)}catch(ce){w(dt(ce).message)}finally{v(!1)}}function K(G,ce){const fe=new Set(c);ce?fe.add(G):fe.delete(G),_(fe)}function le(){const G=new Set(c);B.forEach(ce=>G.add(ce)),_(G)}function J(){const G=new Set(c);B.forEach(ce=>{G.has(ce)?G.delete(ce):G.add(ce)}),_(G)}return u.jsx("div",{className:`reset-preview-overlay ${h?"expanded":""}`,onClick:te?void 0:i,role:"presentation",children:u.jsxs("section",{"aria-label":"Runtime reset preview","aria-modal":"true",className:`reset-preview-dialog ${h?"expanded":""}`,onClick:G=>G.stopPropagation(),role:"dialog",children:[u.jsxs("header",{className:"reset-preview-header",children:[u.jsxs("div",{children:[u.jsx("h3",{children:"Confirm runtime reset"}),u.jsx("p",{children:"The new thread will process the selected original messages in chronological batches. Each batch is compacted natively before the next batch is injected; the old thread context is never reused."})]}),u.jsxs("div",{className:"reset-preview-header-actions",children:[u.jsx("button",{"aria-label":h?"Restore reset preview size":"Expand reset preview",onClick:()=>m(G=>!G),title:h?"Restore size":"Expand",type:"button",children:h?"⊡":"⛶"}),u.jsx("button",{"aria-label":"Close reset preview",disabled:te,onClick:i,type:"button",children:"×"})]})]}),u.jsxs("div",{className:"reset-preview-summary",children:[u.jsxs("label",{className:"reset-preview-select-all",children:[u.jsx("input",{checked:Y,disabled:te||t.entries.length===0,onChange:G=>void _(G.target.checked?new Set(t.entries.map(ce=>ce.id)):new Set),ref:T,type:"checkbox"}),u.jsxs("span",{children:[c.size," of ",t.entries.length," selected"]})]}),u.jsxs("span",{children:[q," user"]}),u.jsxs("span",{children:[R," assistant"]}),B.length>0?u.jsxs("div",{className:"reset-preview-topic-actions",children:[u.jsxs("span",{children:[F," of ",B.length," Topic input + response"]}),u.jsx("button",{disabled:te||F===B.length,onClick:le,type:"button",children:"Select Topic turns"}),u.jsx("button",{disabled:te,onClick:J,type:"button",children:"Invert Topic turns"})]}):null,u.jsxs("span",{children:[t.historyBatchCount," planned batch",t.historyBatchCount===1?"":"es"]}),u.jsxs("span",{children:["~",t.estimatedTokenCount.toLocaleString()," source tokens"]}),u.jsx("span",{children:n?"Warmup enabled":"No warmup"}),y?u.jsx("span",{children:"Saving defaults..."}):null,k?u.jsx("span",{className:"reset-preview-selection-error",children:k}):null]}),u.jsx("div",{className:"reset-preview-list",children:t.entries.length>0?t.entries.map((G,ce)=>u.jsxs("article",{className:`reset-preview-item ${G.role} ${c.has(G.id)?"":"excluded"}`,children:[u.jsxs("header",{children:[u.jsxs("label",{children:[u.jsx("input",{"aria-label":`Include ${G.role} message ${ce+1}`,checked:c.has(G.id),disabled:te,onChange:fe=>K(G.id,fe.target.checked),type:"checkbox"}),u.jsx("span",{children:ce+1})]}),u.jsx("strong",{children:G.role}),G.topicRelation?u.jsxs("span",{className:"reset-preview-topic-badge",children:["Topic ",G.topicRelation]}):null,u.jsx("time",{dateTime:G.createdAt,children:rt(G.createdAt)})]}),u.jsx("pre",{children:G.content})]},G.id)):u.jsx("p",{className:"reset-preview-empty",children:"No visible history will be injected."})}),u.jsxs("footer",{className:"reset-preview-actions",children:[u.jsxs("small",{children:["Preview fingerprint: ",t.fingerprint.slice(0,12)]}),u.jsxs("div",{children:[u.jsx("button",{disabled:te,onClick:i,type:"button",children:"Cancel"}),u.jsx("button",{className:"danger",disabled:te,onClick:()=>l(t.entries.filter(G=>c.has(G.id)).map(G=>G.id)),type:"button",children:e?"Rebuilding and compacting...":"Confirm full-history reset"})]})]})]})})}function _E({currentReleasedAt:e,currentVersion:t,job:n,latest:i,latestChecking:l,starting:o,onClose:c,onRefresh:f,onStart:h}){const m=(n==null?void 0:n.currentVersion)??t,y=i!=null&&i.version&&aD(i.version,m)?rD(i.version):null;return I.useEffect(()=>{const v=k=>{k.key==="Escape"&&c()};return document.addEventListener("keydown",v),()=>document.removeEventListener("keydown",v)},[c]),u.jsx("div",{className:"codex-update-overlay",onClick:c,role:"presentation",children:u.jsxs("section",{"aria-label":"Codex CLI update",className:"codex-update-panel",onClick:v=>v.stopPropagation(),children:[u.jsxs("header",{children:[u.jsxs("div",{children:[u.jsx("h3",{children:"Codex CLI update"}),u.jsx("p",{children:"Managed by Seele in the instance runtime directory."})]}),u.jsx("button",{"aria-label":"Close Codex CLI update",onClick:c,type:"button",children:"×"})]}),u.jsxs("dl",{className:"codex-update-summary",children:[u.jsxs("div",{children:[u.jsx("dt",{children:"Status"}),u.jsx("dd",{className:n?`status-${n.status}`:void 0,children:(n==null?void 0:n.status)??"Not started"})]}),u.jsxs("div",{children:[u.jsx("dt",{children:"Current"}),u.jsx("dd",{children:Zp(m,(n==null?void 0:n.codexReleasedAt)??e)})]}),u.jsxs("div",{children:[u.jsx("dt",{children:"Latest"}),u.jsxs("dd",{title:(i==null?void 0:i.error)??void 0,children:[l?"Checking...":i!=null&&i.version?Zp(i.version,i.releasedAt):i!=null&&i.error?"Check failed":"Not checked",y?u.jsx("a",{className:"codex-release-notes-link",href:y,rel:"noreferrer",target:"_blank",children:"Release notes"}):null]})]}),n?u.jsxs("div",{children:[u.jsx("dt",{children:"Started"}),u.jsx("dd",{children:rt(n.startedAt)})]}):null]}),i!=null&&i.error?u.jsxs("p",{className:"codex-latest-error",children:["Latest version check: ",i.error]}):null,u.jsx("div",{className:"codex-update-log",role:"log","aria-live":"polite",children:n!=null&&n.logs.length?n.logs.map((v,k)=>u.jsxs("div",{className:`log-${v.stream}`,children:[u.jsx("time",{children:nD(v.at)}),u.jsx("span",{children:v.text})]},`${v.at}-${k}`)):u.jsx("p",{children:"No update logs yet."})}),u.jsxs("footer",{children:[u.jsx("button",{className:"secondary",onClick:f,type:"button",children:"Refresh"}),u.jsx("button",{disabled:o||(n==null?void 0:n.status)==="running",onClick:h,type:"button",children:o?"Starting...":(n==null?void 0:n.status)==="running"?"Updating...":n?"Run again":"Start update"})]})]})})}function BE({currentUser:e,conversations:t,deploymentSettings:n,editingEnvironmentKey:i,environmentDraft:l,globalEnvironment:o,workspaceEnvironment:c,memorySettings:f,memorySettingsDraft:h,managedUsers:m,workspaceMemoryDraft:y,runtimeSettings:v,runtimeModels:k,runtimeCodexVersion:w,runtimeCodexReleasedAt:T,runtimeCodexUpdating:E,runtimeSettingsDraft:q,runtimeSettingsScope:R,settingsWorkspace:B,settingsWorkspaceId:F,systemDiagnostics:Y,systemDiagnosticsLoading:te,workspaceGroups:_,workspaceRuntimeSettings:K,workspaceRuntimeSettingsDraft:le,onCancelEnvironmentEdit:J,onClose:G,onCreateUser:ce,onDeleteUser:fe,onDeleteEnvironment:Be,onDraftChange:Ce,onEditEnvironment:ve,onSaveBaseMemoryItems:ee,onSaveDeploymentSettings:pe,onSaveResponsibility:De,onSaveWorkspaceMemoryItems:Ye,onRevealEnvironmentValue:U,onRuntimeDraftChange:O,onCodexAccountSwitched:Q,onUpdateCodexCli:z,onRuntimeScopeChange:de,onSettingsWorkspaceChange:Re,onSubmitRuntimeSettings:ne,onSubmitEnvironment:xe,onRefreshSystemDiagnostics:oe,onUpdateUser:Oe,onWorkspaceRuntimeDraftChange:st,onWorkspaceRuntimeReset:Ct,revealedEnvironmentKeys:lt}){const[Je,ut]=I.useState("model"),[At,jn]=I.useState(!1),[Qe,Zt]=I.useState(null),[Pt,Wt]=I.useState(!1),[qr,Sr]=I.useState((B==null?void 0:B.responsibility)??""),[ua,Vt]=I.useState(!1),Ur=I.useRef(null),he=R==="workspace"?Object.values((K==null?void 0:K.sources)??{}).filter(we=>we==="workspace").length:0;return I.useEffect(()=>{R==="global"&&Wt(!1)},[R]),I.useEffect(()=>{Sr((B==null?void 0:B.responsibility)??"")},[B==null?void 0:B.id,B==null?void 0:B.responsibility]),I.useEffect(()=>{if(!Pt)return;const we=et=>{var Tn;const vt=et.target;vt instanceof Node&&((Tn=Ur.current)!=null&&Tn.contains(vt))||Wt(!1)},Ue=et=>{et.key==="Escape"&&Wt(!1)};return document.addEventListener("pointerdown",we,!0),document.addEventListener("keydown",Ue,!0),()=>{document.removeEventListener("pointerdown",we,!0),document.removeEventListener("keydown",Ue,!0)}},[Pt]),u.jsx("div",{className:"context-panel-overlay settings-overlay",onClick:G,role:"presentation",children:u.jsxs("section",{"aria-label":"Seele settings",className:"context-panel settings-panel",onClick:we=>we.stopPropagation(),children:[u.jsxs("header",{className:"context-panel-header settings-panel-header",children:[u.jsxs("div",{className:"settings-panel-title",children:[u.jsx("h2",{children:"Settings"}),Je!=="system"&&Je!=="users"&&Je!=="accounts"&&Je!=="deployment"?u.jsxs("div",{"aria-label":"Configuration scope",className:"settings-scope-segments",role:"radiogroup",children:[e.role==="admin"?u.jsx("button",{"aria-checked":R==="global",className:R==="global"?"active":void 0,onClick:()=>de("global"),role:"radio",type:"button",children:"Global"}):null,u.jsxs("div",{className:"settings-workspace-picker",ref:Ur,children:[u.jsx("button",{"aria-checked":R==="workspace","aria-expanded":R==="workspace"?Pt:void 0,"aria-label":R==="workspace"?"Settings workspace target":void 0,className:R==="workspace"?"active settings-scope-workspace-trigger":void 0,disabled:t.length===0,onClick:()=>{if(R!=="workspace"){de("workspace");return}Wt(we=>!we)},role:"radio",type:"button",children:R==="workspace"?u.jsxs(u.Fragment,{children:[u.jsxs("span",{children:["Workspace: ",(B==null?void 0:B.title)??"Select workspace"]}),u.jsx("span",{"aria-hidden":"true",children:"⌄"})]}):"Workspace"}),R==="workspace"&&Pt?u.jsx("div",{className:"settings-workspace-menu",role:"listbox",children:_.map(we=>u.jsxs("div",{className:"settings-workspace-menu-group",children:[u.jsx("div",{className:"settings-workspace-menu-heading",children:we.title}),we.conversations.map(Ue=>u.jsxs("button",{"aria-selected":Ue.id===F,className:Ue.id===F?"selected":void 0,onClick:()=>{Re(Ue.id),Wt(!1)},role:"option",type:"button",children:[u.jsx("span",{children:Ue.title}),u.jsxs("small",{children:["workspaces/",Ue.id]})]},Ue.id))]},we.id))}):null]})]}):null]}),u.jsx("div",{className:"settings-header-actions",children:u.jsx("button",{"aria-label":"Close settings panel",onClick:G,type:"button",children:"×"})})]}),u.jsxs("div",{className:"settings-body",children:[u.jsxs("nav",{className:"settings-nav","aria-label":"Settings sections",children:[u.jsxs("button",{className:Je==="model"?"active":void 0,onClick:()=>ut("model"),type:"button",children:[u.jsx("span",{children:"Runtime"}),u.jsx("small",{children:"Effective settings"})]}),u.jsxs("button",{className:Je==="responsibility"?"active":void 0,onClick:()=>ut("responsibility"),type:"button",children:[u.jsx("span",{children:"Responsibility"}),u.jsx("small",{children:"Workspace role"})]}),u.jsxs("button",{className:Je==="memory"?"active":void 0,onClick:()=>ut("memory"),type:"button",children:[u.jsx("span",{children:"Memory"}),u.jsx("small",{children:"Base + workspace context"})]}),u.jsxs("button",{className:Je==="environment"?"active":void 0,onClick:()=>ut("environment"),type:"button",children:[u.jsx("span",{children:"Environment"}),u.jsx("small",{children:"Base + workspace variables"})]}),e.role==="admin"?u.jsxs(u.Fragment,{children:[u.jsxs("button",{className:Je==="accounts"?"active":void 0,onClick:()=>ut("accounts"),type:"button",children:[u.jsx("span",{children:"Codex Accounts"}),u.jsx("small",{children:"Cloud login + active account"})]}),u.jsxs("button",{className:Je==="deployment"?"active":void 0,onClick:()=>ut("deployment"),type:"button",children:[u.jsx("span",{children:"Deployment"}),u.jsx("small",{children:"Local integrations"})]}),u.jsxs("button",{onClick:()=>{window.location.assign(`${q1()}admin/host`)},type:"button",children:[u.jsx("span",{children:"Work Operations"}),u.jsx("small",{children:"Versions, restart, logs"})]}),u.jsxs("button",{className:Je==="system"?"active":void 0,onClick:()=>ut("system"),type:"button",children:[u.jsx("span",{children:"System"}),u.jsx("small",{children:"Runtime + resources"})]}),u.jsxs("button",{className:Je==="users"?"active":void 0,onClick:()=>ut("users"),type:"button",children:[u.jsx("span",{children:"Users"}),u.jsx("small",{children:"Access + roles"})]})]}):null]}),u.jsxs("section",{className:"settings-content",children:[Je!=="system"&&Je!=="users"&&Je!=="accounts"&&Je!=="deployment"?u.jsxs("div",{className:`settings-scope-banner ${R==="workspace"?"workspace":"global"}`,children:[u.jsx("strong",{children:R==="workspace"?"Editing workspace custom settings":"Editing global settings"}),u.jsx("span",{children:R==="workspace"?`${(B==null?void 0:B.title)??"Selected workspace"} overrides global defaults.`:"These defaults apply to every workspace unless that workspace overrides them."})]}):null,Je==="system"?u.jsx(IE,{conversations:t,diagnostics:Y,loading:te,onRefresh:oe}):Je==="users"?u.jsx(PE,{currentUser:e,users:m,onCreate:ce,onDelete:fe,onUpdate:Oe}):Je==="accounts"?u.jsx(GE,{onSwitched:Q}):Je==="deployment"?u.jsx(VE,{settings:n,onSave:pe}):Je==="model"?u.jsx(YE,{draft:R==="workspace"?le:q,globalSettings:v,models:k,codexVersion:w,codexReleasedAt:T,codexUpdating:E,scope:R,workspaceOverrideCount:he,settings:R==="workspace"?(K==null?void 0:K.effective)??le:v,workspaceSettings:K,onDraftChange:R==="workspace"?st:O,onResetWorkspaceSetting:Ct,onSubmit:ne,onUpdateCodexCli:z}):Je==="responsibility"?u.jsx(UE,{draft:qr,saving:ua,scope:R,workspace:B,onDraftChange:Sr,onSubmit:we=>{we.preventDefault(),we.stopPropagation(),!(R!=="workspace"||!B)&&(Vt(!0),De(B.id,qr).then(Ue=>Sr(Ue)).finally(()=>Vt(!1)))}}):Je==="memory"?u.jsx(WE,{baseSettings:f,scope:R,workspaceSettings:y,workspaceName:B==null?void 0:B.title,onSaveBaseItems:ee,onSaveWorkspaceItems:Ye}):u.jsx(QE,{deleteConfirmKey:Qe,editingEnvironmentKey:i,environmentDraft:l,globalEnvironment:o,scope:R,workspaceEnvironment:c,valueVisible:At,onCancelEnvironmentEdit:J,onDeleteConfirmChange:Zt,onDeleteEnvironment:Be,onDraftChange:Ce,onEditEnvironment:ve,onRevealEnvironmentValue:U,onSubmitEnvironment:xe,onValueVisibleChange:jn,revealedEnvironmentKeys:lt})]})]})]})})}function IE({conversations:e,diagnostics:t,loading:n,onRefresh:i}){const l=(t==null?void 0:t.runtime.pool)??null,o=I.useMemo(()=>(t==null?void 0:t.systemLogs)??[],[t]),[c,f]=I.useState(!1),h=I.useMemo(()=>new Map(e.map(w=>[w.id,w.title])),[e]),m=I.useMemo(()=>t?JSON.stringify({generatedAt:t.generatedAt,app:t.app,systemLogs:o},null,2):"",[t,o]),y=async()=>{m&&(await navigator.clipboard.writeText(m),f(!0),window.setTimeout(()=>f(!1),1800))},v=()=>{if(!m||!t)return;const w=URL.createObjectURL(new Blob([m],{type:"application/json"})),T=document.createElement("a");T.href=w,T.download=`seele-system-log-${t.generatedAt.replaceAll(":","-").replaceAll(".","-")}.json`,T.click(),URL.revokeObjectURL(w)},k=()=>{if(!t||!o.length)return;const w=o[0],T=o.slice(0,5).map(F=>`- ${Lc(F.createdAt)} · ${F.level.toUpperCase()} · ${F.event} · ${F.summary}`).join(`
356
+ This cancels every current or queued turn and the active complex task, kills its runtime, and repairs scheduler state. Future scheduled wakeups are preserved.`))return;const N=x.id;Bn(!0),u0(N),(L=lr.current.get(N))==null||L.abort(),sr.current.delete(N),rl.current.delete(N),ta(N,!1);try{const V=await vl(N);gs(N),kt(N,ie=>({...ie,status:V})),ea(N,V),await hn(N),await fn(),Le("success","Workspace stopped and repaired")}catch(V){Tu(N);const ie=dt(V);Le("error","Force stop failed",ie.detail??ie.message);try{await fn()}catch(Se){console.warn("Failed to refresh workspace after force Stop failed",Se)}}finally{Bn(!1)}}async function Zr(x,j){if(!w||!x.approvalTurnId||x.approvalRequestId===void 0)return;const N=w;try{const L=Ne(`conversations/${N}/turns/${x.approvalTurnId}/approvals/${encodeURIComponent(String(x.approvalRequestId))}`),V=await fetch(L,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({decision:j})});if(!V.ok)throw await Fn(V,{method:"POST",url:L});kt(N,ie=>({...ie,events:[...ie.events,{id:ie.events.length+1,event:"server.approval.decision",data:{requestId:x.approvalRequestId,decision:j,source:"client"},createdAt:new Date().toISOString()}]}))}catch(L){kt(N,ie=>({...ie,events:[...ie.events,{id:ie.events.length+1,event:"client.error",data:_s(L),createdAt:new Date().toISOString()}]}));const V=dt(L);Le("error","Failed to respond to approval",V.detail??V.message)}}async function Jr(x,j,N){const L=w,V=x.workspaceChangeProposalId??x.responsibilityProposalId;if(!L||!V)return!1;try{const ie=Ne(`conversations/${L}/workspace-change-proposals/${encodeURIComponent(V)}`),Se=await fetch(ie,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({decision:j,payload:j==="accept"?N??x.workspaceChangePayload:void 0})});if(!Se.ok)throw await Fn(Se,{method:"POST",url:ie});const Ge=await Se.json(),ze=XA(j,Ge.decision),_e=ze==="accept"?Ge.payload??N??x.workspaceChangePayload:null;return hr(Ge.conversation),kt(L,Rt=>({...Rt,events:[...Rt.events,{id:`${x.id}:${ze}`,event:"server.workspace_change.decision",data:{proposalId:V,changeType:x.workspaceChangeType??"responsibility",decision:ze,payload:_e},createdAt:new Date().toISOString()}]})),Le("success",ze==="accept"?"Workspace change applied":"Workspace change declined"),!0}catch(ie){console.error(ie);const Se=dt(ie);return Le("error","Failed to respond to workspace change proposal",Se.detail??Se.message),!1}}async function Cs(x,j,N){const L=w;if(!(!L||!x.knowledgeProposalId))try{let V;if(j==="accept")try{V=JSON.parse(N??x.body)}catch{Le("error","Knowledge proposal JSON is invalid");return}const ie=Ne(`conversations/${L}/knowledge-proposals/${encodeURIComponent(x.knowledgeProposalId)}`),Se=await fetch(ie,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({decision:j,knowledge:V})});if(!Se.ok)throw await Fn(Se,{method:"POST",url:ie});const Ge=await Se.json();li([...Ge.items??[]].sort(g5)),kt(L,ze=>({...ze,events:[...ze.events,{id:`${x.id}:${j}`,event:"server.knowledge.decision",data:{proposalId:x.knowledgeProposalId,decision:j,knowledge:j==="accept"?Ge.item:null},createdAt:new Date().toISOString()}]})),Le("success",j==="accept"?"Workspace knowledge saved":"Knowledge proposal declined")}catch(V){console.error(V);const ie=dt(V);Le("error","Failed to respond to knowledge proposal",ie.detail??ie.message)}}function T0(x){Au(x.id,x.status),To(x),Ce(j=>{const N=j[x.id],L=x.events.map(V=>({id:V.id,turnId:V.turnId,seq:V.seq,event:V.event,data:V.data,createdAt:V.createdAt}));return{...j,[x.id]:{messages:x.messages,events:Bd(L,(N==null?void 0:N.events)??[]),timelineNodes:tp(x.timelineNodes??[],(N==null?void 0:N.timelineNodes)??[]),turns:ep(x.turns??[],(N==null?void 0:N.turns)??[]),contextVersions:x.contextVersions??[],status:x.status,history:ps(x),loadingOlder:!1,fullEventTurnIds:(N==null?void 0:N.fullEventTurnIds)??new Set,loadingEventTurnIds:(N==null?void 0:N.loadingEventTurnIds)??new Set}}})}function qf(x){const j=ps(x);kt(x.id,N=>{var L,V,ie;return{...N,messages:Jm(x.messages,N.messages),timelineNodes:tp(x.timelineNodes??[],N.timelineNodes),turns:ep(x.turns??[],N.turns),events:Bd(x.events.map(Se=>({id:Se.id,turnId:Se.turnId,seq:Se.seq,event:Se.event,data:Se.data,createdAt:Se.createdAt})),N.events),contextVersions:(((L=x.contextVersions)==null?void 0:L.length)??0)>0?x.contextVersions??[]:N.contextVersions,history:{...j,loadedMessageCount:j.loadedMessageCount+(((V=N.history)==null?void 0:V.loadedMessageCount)??N.messages.length),loadedEventCount:j.loadedEventCount+(((ie=N.history)==null?void 0:ie.loadedEventCount)??N.events.length)},loadingOlder:!1}})}function A0(x){const j=ps(x),N=x.events.map(L=>({id:L.id,turnId:L.turnId,seq:L.seq,event:L.event,data:L.data,createdAt:L.createdAt}));kt(x.id,L=>{var V,ie,Se;return{...L,messages:Jm(L.messages,x.messages),timelineNodes:tp(L.timelineNodes,x.timelineNodes??[]),turns:ep(L.turns,x.turns??[]),events:Bd(N,L.events),contextVersions:(((V=x.contextVersions)==null?void 0:V.length)??0)>0?x.contextVersions??[]:L.contextVersions,status:x.status,history:{...L.history??j,messageTotal:j.messageTotal,eventTotal:j.eventTotal,loadedMessageCount:Math.max(((ie=L.history)==null?void 0:ie.loadedMessageCount)??L.messages.length,L.messages.length,x.messages.length),loadedEventCount:Math.max(((Se=L.history)==null?void 0:Se.loadedEventCount)??L.events.length,L.events.length,x.events.length)},loadingOlder:!1}})}function kt(x,j){Ce(N=>{const L=N[x]??{messages:[],events:[],timelineNodes:[],turns:[],contextVersions:[],status:"idle",history:null,loadingOlder:!1,fullEventTurnIds:new Set,loadingEventTurnIds:new Set};return{...N,[x]:j(L)}})}function ea(x,j){y(N=>N.map(L=>L.id===x?{...L,status:j,updatedAt:new Date().toISOString()}:L))}function To(x){hr(x)}function hr(x){y(j=>Ul(l,j.map(N=>N.id===x.id?{...N,...x}:N)))}async function xl(x,j){const N=j.filter(L=>{const V=Be[x];return V&&!V.fullEventTurnIds.has(L)&&!V.loadingEventTurnIds.has(L)});if(N.length!==0){kt(x,L=>{const V=new Set(L.loadingEventTurnIds);for(const ie of N)V.add(ie);return{...L,loadingEventTurnIds:V}});try{const L=await Promise.all(N.map(V=>Dz(x,V)));kt(x,V=>{const ie=new Set(V.fullEventTurnIds),Se=new Set(V.loadingEventTurnIds),Ge=L.flatMap((ze,_e)=>{const Rt=N[_e];return ie.add(Rt),Se.delete(Rt),ze.map(St=>({id:St.id,turnId:St.turnId,seq:St.seq,event:St.event,data:St.data,createdAt:St.createdAt}))});return{...V,events:Bd(V.events,Ge),fullEventTurnIds:ie,loadingEventTurnIds:Se}})}catch(L){console.error(L),kt(x,V=>{const ie=new Set(V.loadingEventTurnIds);for(const Se of N)ie.delete(Se);return{...V,loadingEventTurnIds:ie}}),Le("error","Failed to load process details")}}}function ta(x,j){const N=new Set(fs.current);j?N.add(x):N.delete(x),fs.current=N,Jc(L=>{const V=new Set(L);return j?V.add(x):V.delete(x),V})}function Ao(x){const j=qA({key:x.key,metaKey:x.metaKey,ctrlKey:x.ctrlKey,shiftKey:x.shiftKey,isComposing:x.nativeEvent.isComposing});j&&(x.preventDefault(),yn({forceNewTurn:j.forceNewTurn}))}function js(x){as(j=>{const N=new Set(j);return N.has(x)?N.delete(x):N.add(x),Xm(l,N),N})}function E0(x){var j;return GA(x.status,(j=x.nextWakeup)==null?void 0:j.status,ao.has(x.id))}function Eo(x){var L;const j=(L=ls.current)==null?void 0:L.getBoundingClientRect(),N=j?x-j.left:x;return U1(N)}function ki(x){x.preventDefault(),x.currentTarget.setPointerCapture(x.pointerId),is(Eo(x.clientX))}function Si(x){x.currentTarget.hasPointerCapture(x.pointerId)&&(x.preventDefault(),is(Eo(x.clientX)))}function N0(x){x.currentTarget.hasPointerCapture(x.pointerId)&&x.currentTarget.releasePointerCapture(x.pointerId);const j=Eo(x.clientX);is(j),yE(l,j)}return u.jsxs("main",{className:`shell${ce?" mobile-sidebar-open":""}`,ref:ls,style:{"--sidebar-width":`${ma}px`},children:[u.jsxs("aside",{className:"sidebar",children:[u.jsxs("div",{className:"sidebar-header",children:[u.jsxs("div",{children:[u.jsxs("p",{className:"eyebrow brand-line",children:[u.jsx("span",{children:"Seele"}),pe?t.role==="admin"?u.jsxs("a",{"aria-label":`Open Seele Host control for Work v${pe}`,className:"work-version-link",href:`${q1()}admin/host`,title:"Open Seele Host control: versions, restart, and logs",children:["v",pe,u.jsx("span",{"aria-hidden":"true",children:"↗"})]}):u.jsxs("span",{children:["v",pe]}):null,u.jsx("span",{"aria-label":j5(xe),className:`backend-status ${xe}`,"data-label":j5(xe)})]}),u.jsxs("div",{className:"sidebar-title-row",children:[u.jsx("h2",{children:"Workspaces"}),e?u.jsx("button",{"aria-label":`Sign out ${t.username}`,className:"sign-out-button",onClick:i,title:`Sign out ${t.username}`,type:"button",children:"Sign out"}):null]})]}),u.jsxs("div",{className:"sidebar-header-actions",children:[u.jsx("button",{"aria-label":"Close workspace list",className:"mobile-sidebar-dismiss",onClick:()=>fe(!1),title:"Close workspace list",type:"button",children:"×"}),u.jsx("button",{"aria-label":"New workspace",className:"new-workspace-button",type:"button",onClick:Wn,children:"+"})]})]}),u.jsx("nav",{className:"session-list","aria-label":"Workspaces",children:gi.map(x=>u.jsxs("section",{className:["workspace-group",yu===x.id?"dragging":"",rs===x.id?"drop-after":"",(ir==null?void 0:ir.kind)==="group"&&ir.id===x.id?"drop-into":""].filter(Boolean).join(" "),"data-group-id":x.id,children:[u.jsxs("div",{className:"workspace-group-header",children:[u.jsxs("button",{"aria-expanded":!Zi.has(x.id),className:(Jt==null?void 0:Jt.kind)==="group"&&Jt.id===x.id?"workspace-group-toggle keyboard-focused":"workspace-group-toggle","data-keyboard-focus-key":Ls({kind:"group",id:x.id}),onClick:j=>{if(bu.current){j.preventDefault(),bu.current=!1;return}js(x.id)},onDoubleClick:j=>{j.preventDefault(),j.stopPropagation(),hl(x)},onPointerCancel:ml,onPointerDown:j=>Va(j,x.id),onPointerMove:j=>C0(j,x.id),onPointerUp:j=>j0(j,x.id),type:"button",children:[u.jsx("span",{className:Zi.has(x.id)?"workspace-group-caret collapsed":"workspace-group-caret","aria-hidden":"true",children:"▾"}),u.jsx("span",{onDoubleClick:j=>{j.preventDefault(),j.stopPropagation(),hl(x)},title:"Double-click to rename",children:x.title})]}),x.id!==U3?u.jsx("button",{"aria-label":`Delete group ${x.title}`,className:"workspace-group-delete",onClick:j=>{j.stopPropagation(),Ga(x)},title:"Delete group",type:"button",children:"×"}):null]}),Zi.has(x.id)?null:u.jsx("div",{className:"workspace-group-items",children:x.conversations.map(j=>{const N=E0(j);return u.jsxs("div",{className:["session-item",(Jt==null?void 0:Jt.kind)==="workspace"&&Jt.id===j.id?"keyboard-focused":"",j.id===w?"active":"",j.id===ns?"dragging":"",(ir==null?void 0:ir.kind)==="workspace"&&ir.id===j.id?`drop-${ir.position}`:""].filter(Boolean).join(" "),"data-keyboard-focus-key":Ls({kind:"workspace",id:j.id}),"data-workspace-id":j.id,onClick:L=>{if(xu.current){L.preventDefault(),xu.current=!1;return}$a(j.id),fe(!1)},onDoubleClick:L=>{jo(L.target)||(L.preventDefault(),Xr(j))},onKeyDown:L=>{Co(L.target)||L.key==="Enter"&&($a(j.id),fe(!1))},onPointerCancel:Iu,onPointerDown:L=>mt(L,j.id),onPointerMove:L=>Pa(L,j.id),onPointerUp:L=>fr(L,j.id),role:"button",tabIndex:0,children:[u.jsxs("span",{className:"session-heading",children:[u.jsx("span",{"aria-label":Yd(N,j.nextWakeup,pa),className:`session-status ${N}`,title:Yd(N,j.nextWakeup,pa)}),u.jsx("span",{className:"session-title",title:"Double-click to rename",children:j.title}),N==="waiting"&&j.nextWakeup?u.jsx("span",{className:"session-countdown",title:Yd(N,j.nextWakeup,pa),children:of(j.nextWakeup,pa)}):null,j.unreadTurnCount>0?u.jsx("span",{"aria-label":`${j.unreadTurnCount} unread turns`,className:"session-unread",title:`${j.unreadTurnCount} unread turns`,children:j.unreadTurnCount>99?"99+":j.unreadTurnCount}):null,N!=="running"?u.jsx("button",{"aria-label":`Delete ${j.title}`,className:"session-delete",onClick:L=>{L.stopPropagation(),ut(j)},title:"Move workspace to recycle",type:"button",children:"×"}):null]}),u.jsxs("span",{className:"session-workspace",title:j.workspacePath,children:["workspaces/",Zo(j.id)]})]},j.id)})})]},x.id))}),u.jsx("footer",{className:"sidebar-footer",children:u.jsxs("div",{className:"sidebar-actions","aria-label":"Workspace actions",children:[u.jsx("button",{"aria-label":"Settings",className:"sidebar-action-button",onClick:m0,type:"button",children:u.jsx(l5,{})}),u.jsx("button",{"aria-label":"New group",className:"sidebar-action-button",onClick:So,type:"button",children:u.jsx(bM,{})}),u.jsx("button",{"aria-label":"Collaboration topics",className:"sidebar-action-button",onClick:()=>{ui(!0),fe(!1)},type:"button",children:u.jsx(Gd,{})}),u.jsx("button",{"aria-label":"Console",className:"sidebar-action-button",onClick:g0,type:"button",children:u.jsx(wM,{})}),u.jsx(SN,{usage:o0})]})})]}),u.jsx("button",{"aria-label":"Close workspace list",className:"mobile-sidebar-backdrop",onClick:()=>fe(!1),tabIndex:ce?0:-1,type:"button"}),u.jsx("div",{"aria-label":"Resize sidebar",className:"sidebar-resizer",onPointerDown:ki,onPointerMove:Si,onPointerUp:N0,role:"separator",tabIndex:0}),wu&&Oa?u.jsxs("div",{className:"workspace-drag-preview",style:{transform:`translate3d(${Oa.x+12}px, ${Oa.y+10}px, 0)`},children:[u.jsx("span",{className:"workspace-drag-title",children:wu.title}),u.jsxs("span",{className:"workspace-drag-path",children:["workspaces/",Zo(wu.id)]})]}):null,Oe?u.jsx("div",{className:"workspace-editor-overlay",onKeyDown:Kr,role:"presentation",children:u.jsxs("form",{className:"workspace-editor",onKeyDown:Kr,onSubmit:x=>void qu(x),children:[u.jsx("label",{className:"workspace-editor-label",htmlFor:"workspace-title",children:"Workspace name"}),u.jsx("input",{autoFocus:!0,id:"workspace-title",onChange:wi,onKeyDown:Kr,value:Oe.title}),Oe.mode==="create"?u.jsxs(u.Fragment,{children:[u.jsx("label",{className:"workspace-editor-label",htmlFor:"workspace-group",children:"Group"}),u.jsx("select",{id:"workspace-group",onChange:Lu,onKeyDown:Kr,value:Oe.groupId??((bl=v[0])==null?void 0:bl.id)??"",children:v.map(x=>u.jsx("option",{value:x.id,children:x.title},x.id))})]}):null,u.jsxs("div",{className:"workspace-editor-actions",children:[u.jsx("button",{type:"button",onClick:Ln,children:"Cancel"}),u.jsx("button",{disabled:Ct,type:"submit",children:Ct?"Saving...":Oe.mode==="create"?"Create":"Save"})]})]})}):null,Qe?u.jsx("div",{className:"workspace-editor-overlay",onKeyDown:Qr,role:"presentation",children:u.jsxs("form",{className:"workspace-editor",onKeyDown:Qr,onSubmit:x=>void ka(x),children:[u.jsx("label",{className:"workspace-editor-label",htmlFor:"workspace-group-title",children:"Group name"}),u.jsx("input",{autoFocus:!0,id:"workspace-group-title",onChange:bs,onKeyDown:Qr,value:Qe.title}),u.jsxs("div",{className:"workspace-editor-actions",children:[u.jsx("button",{type:"button",onClick:dr,children:"Cancel"}),u.jsx("button",{type:"submit",children:Qe.mode==="create"?"Create":"Save"})]})]})}):null,Pt?u.jsx(IE,{currentUser:t,conversations:m,editingEnvironmentKey:ts,deploymentSettings:we,environmentDraft:si,globalEnvironment:qr,workspaceEnvironment:ua,memorySettings:hu,memorySettingsDraft:Kc,workspaceMemoryDraft:An,runtimeSettings:Ur,runtimeModels:et,runtimeCodexVersion:Tn,runtimeCodexReleasedAt:zn,runtimeCodexUpdating:(an==null?void 0:an.status)==="running",runtimeSettingsDraft:Pi,runtimeSettingsScope:nr,settingsWorkspace:dn,settingsWorkspaceId:Bt,systemDiagnostics:O,systemDiagnosticsLoading:z,workspaceGroups:gi,workspaceRuntimeSettings:du,workspaceRuntimeSettingsDraft:fu,managedUsers:Ye,onCancelEnvironmentEdit:Bf,onClose:()=>Wt(!1),onCreateUser:async x=>{const j=await wD(x);U(N=>[...N,j]),Le("success","User created")},onDeleteUser:async x=>{await SD(x),U(j=>j.filter(N=>N.id!==x)),Le("success","User deleted")},onSaveDeploymentSettings:v0,onDeleteEnvironment:x=>void Ou(x),onDraftChange:Fr,onEditEnvironment:dl,onRevealEnvironmentValue:x=>void Yn(x),onSaveBaseMemoryItems:x=>Ru(x),onSaveResponsibility:async(x,j)=>{try{const N=await qd(x,{responsibility:j});return hr(N),oe("connected"),Le("success","Workspace responsibility saved"),N.responsibility}catch(N){throw console.error(N),oe("error"),Le("error","Failed to save workspace responsibility"),N}},onSaveWorkspaceMemoryItems:x=>Bt?xo(Bt,x):Promise.reject(new Error("No workspace selected")),onRuntimeDraftChange:cu,onCodexAccountSwitched:async()=>{Le("success","Codex account switched"),(await G7()).codexAccountsReady&&await Promise.all([ys(!0),Ha(!0),vs()])},onUpdateCodexCli:()=>{Dt(!0),yo(!0)},onRuntimeScopeChange:Na,onSettingsWorkspaceChange:_f,onSubmitRuntimeSettings:x=>void y0(x),onWorkspaceRuntimeDraftChange:ii,onWorkspaceRuntimeReset:x=>Bt?void cl(Bt,x):void 0,revealedEnvironmentKeys:Ki,onSubmitEnvironment:x=>void bo(x),onRefreshSystemDiagnostics:()=>void ba(),onUpdateUser:async(x,j)=>{const N=await kD(x,j);U(L=>L.map(V=>V.id===N.id?N:V)),Le("success","User updated")}}):null,Dn?u.jsx(BE,{currentReleasedAt:zn,currentVersion:Tn,job:an,latest:Ks,latestChecking:ai,starting:zf,onClose:()=>Dt(!1),onRefresh:()=>void yo(),onStart:()=>void xi()}):null,Ma&&We?u.jsx(DE,{conversation:We,clockNow:pa,knowledgeDraft:Wi,workspaceKnowledge:Yi,tokenUsage:xa,onCancelKnowledgeEdit:()=>Xi(bc),onDeleteKnowledge:x=>void x0(We.id,x),onEditKnowledge:wo,onKnowledgeDraftChange:Xi,onSubmitKnowledge:x=>void bi(We.id,x),onClose:()=>ln(!1)}):null,oi?u.jsx(RE,{conversations:m,onClose:()=>ui(!1),workspaceGroups:gi}):null,Zs?u.jsx(OE,{busy:to||$r,conversation:Wr??null,conversationId:za,forceStopBusy:$r,preview:(Gr==null?void 0:Gr.conversationId)===za?Gr:null,previewLoading:Qc,result:no,status:i0,warmup:pu,workspaceGroups:gi,onClose:()=>Js(!1),onCancelResetPreview:()=>Da(null),onForceStop:()=>void Fu(),onPreviewReset:()=>void Du(),onStartBlankContext:()=>void vo(),onResetRuntime:x=>void jr(x),onSaveResetSelection:or,onWorkspaceChange:x=>{eo(x),Ra(null),Da(null)},onWarmupChange:Df}):null,K?u.jsx("div",{className:"dialog-backdrop",role:"presentation",onMouseDown:()=>!J&&le(null),children:u.jsxs("form",{className:"dialog-card clone-dialog",onSubmit:Bu,onMouseDown:x=>x.stopPropagation(),children:[u.jsxs("header",{children:[u.jsxs("div",{children:[u.jsx("h2",{children:"Clone workspace"}),u.jsx("p",{children:"Copy stable visible history and reusable workspace context into an independent workspace."})]}),u.jsx("button",{"aria-label":"Close",className:"icon-button",onClick:()=>le(null),type:"button",children:"×"})]}),u.jsxs("label",{children:[u.jsx("span",{children:"Name"}),u.jsx("input",{autoFocus:!0,value:K.name,onChange:x=>le(j=>j&&{...j,name:x.target.value})})]}),u.jsxs("label",{children:[u.jsx("span",{children:"Group"}),u.jsx("select",{value:K.groupId,onChange:x=>le(j=>j&&{...j,groupId:x.target.value}),children:gi.map(x=>u.jsx("option",{value:x.id,children:x.title},x.id))})]}),u.jsxs("footer",{children:[u.jsx("button",{className:"secondary",disabled:J,onClick:()=>le(null),type:"button",children:"Cancel"}),u.jsx("button",{disabled:J||!K.name.trim(),type:"submit",children:J?"Cloning...":"Clone"})]})]})}):null,F?u.jsx("div",{className:"dialog-backdrop",role:"presentation",onMouseDown:()=>Y(null),children:u.jsxs("section",{"aria-labelledby":"complex-task-detail-title","aria-modal":"true",className:"dialog-card task-detail-dialog",onMouseDown:x=>x.stopPropagation(),role:"dialog",children:[u.jsxs("header",{children:[u.jsxs("div",{children:[u.jsx("h2",{id:"complex-task-detail-title",children:F.title}),u.jsxs("p",{children:[C5(F.status),F.startedAt&&F.finishedAt?` · ${fD(F.startedAt,F.finishedAt)}`:""]})]}),u.jsx("button",{"aria-label":"Close",className:"icon-button",onClick:()=>Y(null),type:"button",children:"×"})]}),u.jsxs("div",{className:"complex-task-detail task-record-detail",children:[u.jsxs("div",{children:[u.jsx("small",{children:"Objective"}),u.jsx("p",{children:F.objective??"No objective recorded."})]}),u.jsxs("div",{children:[u.jsx("small",{children:F.status==="completed"?"Final plan":"Current plan"}),F.currentPlan?u.jsx("article",{className:"message assistant complex-task-plan-preview",children:u.jsx("div",{className:"message-main",children:u.jsx("div",{className:"message-body",children:Yl(F.currentPlan.planMarkdown,We)})})}):u.jsx("p",{children:"No plan recorded."})]}),u.jsxs("dl",{children:[u.jsxs("div",{children:[u.jsx("dt",{children:"Goal"}),u.jsx("dd",{children:F.codexGoalStatus??"not started"})]}),u.jsxs("div",{children:[u.jsx("dt",{children:"Plan versions"}),u.jsx("dd",{children:F.planVersions.length})]}),u.jsxs("div",{children:[u.jsx("dt",{children:"Started"}),u.jsx("dd",{children:F.startedAt?rt(F.startedAt):"—"})]}),u.jsxs("div",{children:[u.jsx("dt",{children:"Finished"}),u.jsx("dd",{children:F.finishedAt?rt(F.finishedAt):"—"})]})]})]}),u.jsx("footer",{children:u.jsx("button",{className:"secondary",onClick:()=>Y(null),type:"button",children:"Close"})})]})}):null,te?u.jsx("div",{className:"dialog-backdrop",role:"presentation",onMouseDown:()=>_(null),children:u.jsxs("section",{"aria-labelledby":"system-event-detail-title","aria-modal":"true",className:"dialog-card system-event-detail-dialog",onMouseDown:x=>x.stopPropagation(),role:"dialog",children:[u.jsxs("header",{children:[u.jsxs("div",{children:[u.jsx("h2",{id:"system-event-detail-title",children:te.title}),u.jsx("p",{children:rt(te.createdAt)})]}),u.jsx("button",{"aria-label":"Close",className:"icon-button",onClick:()=>_(null),type:"button",children:"×"})]}),u.jsx("div",{className:"system-event-detail-content",children:u.jsx(Ec,{content:te.fullDetail??te.detail??"No additional details.",conversation:We,streaming:!1,onPreviewArtifact:Cr,onCopyArtifactUrl:Ua,copiedArtifactUrl:rr})}),u.jsxs("footer",{children:[te.linkedTaskId?u.jsx("button",{onClick:()=>{const x=te.linkedTaskId;_(null),wa(x)},type:"button",children:"View task"}):null,u.jsx("button",{className:"secondary",onClick:()=>_(null),type:"button",children:"Close"})]})]})}):null,Je?u.jsx("div",{className:"memory-editor-overlay",onClick:()=>{At||ut(null)},role:"presentation",children:u.jsxs("section",{"aria-label":"Confirm workspace recycle","aria-modal":"true",className:"memory-delete-dialog workspace-delete-dialog",onClick:x=>x.stopPropagation(),role:"dialog",children:[u.jsxs("header",{children:[u.jsx("strong",{children:"Move Workspace to Recycle"}),u.jsx("button",{"aria-label":"Close workspace recycle confirmation",className:"memory-icon-button",disabled:At,onClick:()=>ut(null),title:"Close",type:"button",children:"×"})]}),u.jsxs("p",{children:["Move ",u.jsx("strong",{children:Je.title})," to recycle?"]}),u.jsx("code",{children:Je.workspacePath}),u.jsxs("div",{className:"memory-delete-actions",children:[u.jsx("button",{className:"memory-dialog-button",disabled:At,onClick:()=>ut(null),type:"button",children:"Cancel"}),u.jsx("button",{className:"memory-dialog-button danger",disabled:At,onClick:()=>void cr(Je),type:"button",children:At?"Moving...":"Move to recycle"})]})]})}):null,On?u.jsxs("div",{className:`app-toast ${On.tone}`,role:"status",children:[u.jsx("strong",{children:On.text}),On.detail?u.jsx("pre",{children:On.detail}):null]}):null,u.jsxs("section",{className:"conversation",children:[u.jsxs("header",{className:"topbar",children:[u.jsxs("div",{className:"topbar-main",children:[u.jsx("button",{"aria-label":"Show workspaces",className:"mobile-workspace-menu",onClick:()=>fe(!0),title:"Workspaces",type:"button",children:u.jsx(xM,{})}),u.jsxs("div",{className:"topbar-heading",children:[u.jsx("div",{className:"topbar-title-row",children:u.jsx("h1",{children:(We==null?void 0:We.title)??"New workspace"})}),We?u.jsxs("p",{className:"topbar-workspace",children:["workspaces/",Zo(We.id)]}):null]})]}),u.jsx("div",{className:"topbar-actions",children:We?u.jsxs(u.Fragment,{children:[We.threadUpgradeRequired?u.jsx("button",{"aria-label":"Reset required for latest thread tools",className:"topbar-icon-button thread-upgrade-button",onClick:g0,title:`当前 Thread 工具集已过期(${We.threadCapabilityVersion} / ${We.requiredThreadCapabilityVersion}),点击进行 Reset`,type:"button",children:u.jsx(S7,{})}):null,u.jsx("button",{"aria-label":"Clone workspace",className:"topbar-icon-button",onClick:b0,title:"Clone workspace",type:"button",children:u.jsx(vM,{})}),u.jsxs("button",{className:`context-button has-usage ${W1(ms??0)}`,onClick:()=>ln(!0),style:{"--context-usage":`${Nf(ms??0)}%`},title:xa&&ms!==null?`Context ${Math.round(ms)}% · ${wr(xa.totalTokens)} / ${Vd(xa.modelContextWindow)}`:"Context 0% · no usage recorded yet",type:"button",children:[u.jsx("span",{children:"Context"}),u.jsxs("strong",{children:[Math.round(ms??0),"%"]})]}),u.jsx("button",{"aria-label":"Workspace settings",className:"topbar-icon-button",onClick:p0,title:"Workspace settings",type:"button",children:u.jsx(l5,{})})]}):null})]}),E?u.jsxs("section",{className:`complex-task-bar ${E.status}`,children:[u.jsxs("button",{className:"complex-task-summary",onClick:()=>void wa(E.id),title:"View complex task details",type:"button",children:[u.jsx("span",{className:"complex-task-kicker",children:"Complex task"}),u.jsx("strong",{children:E.title}),u.jsx("span",{className:"complex-task-state",children:C5(E.status)}),u.jsx("span",{className:"complex-task-duration",children:dD(E,pa)})]}),u.jsxs("div",{className:"complex-task-actions",children:[up(E.status,"discussing","ready","replanning")?u.jsx("button",{disabled:!E.objective||!E.currentPlan,onClick:()=>void Tr("start"),title:E.objective&&E.currentPlan?"Start this complex task":"A complete candidate plan is required before starting",type:"button",children:"Start"}):null,E.status==="active"?u.jsx("button",{onClick:()=>void Tr("pause"),type:"button",children:"Pause"}):null,up(E.status,"paused","waiting","blocked")?u.jsx("button",{onClick:()=>void Tr("resume"),type:"button",children:"Resume"}):null,up(E.status,"active","paused","waiting","blocked")?u.jsx("button",{className:"secondary",onClick:()=>void Tr("replan"),type:"button",children:"Replan"}):null,u.jsx("button",{className:"quiet danger",onClick:()=>void Tr("end"),type:"button",children:"End task"})]})]}):null,(We==null?void 0:We.status)==="initialization_failed"&&We.cloneLineage?u.jsxs("div",{className:"clone-initialization-error",children:[u.jsxs("div",{children:[u.jsx("strong",{children:"Clone initialization failed"}),u.jsx("span",{children:We.cloneLineage.initializationError??"The runtime could not initialize this clone."})]}),u.jsx("button",{onClick:()=>void w0(),type:"button",children:"Retry with a clean thread"})]}):null,u.jsx("div",{className:"stream",onScroll:()=>void ju(),ref:ss,style:{scrollPaddingBottom:Ji},children:u.jsxs("div",{className:"stream-inner",style:{paddingBottom:Ji},children:[il.length===0?u.jsx("div",{className:"empty-state",children:u.jsx("h2",{children:"Start a workspace"})}):null,u.jsxs("section",{className:"message-log","aria-label":"Conversation messages",children:[We!=null&&We.cloneLineage&&Su.size>0?u.jsxs("div",{className:"clone-history-boundary clone-history-source",children:[u.jsxs("strong",{children:["Inherited from ",We.cloneLineage.sourceWorkspaceTitle]}),u.jsxs("span",{children:["through ",rt(We.cloneLineage.snapshotAt)," · ",We.cloneLineage.importedMessageCount," messages"]})]}):null,(Ts=Et==null?void 0:Et.history)!=null&&Ts.hasMoreBefore?u.jsx("div",{className:"history-loader",children:Et.loadingOlder?"Loading earlier messages...":"Scroll up for earlier messages"}):null,ku.map((x,j)=>{var Se,Ge,ze;const N=((Se=x.user)==null?void 0:Se.type)==="system",L=x.turnIds.some(_e=>Su.has(_e)),V=ku[j+1],ie=L&&(!V||!V.turnIds.some(_e=>Su.has(_e)));return u.jsxs(I.Fragment,{children:[u.jsxs("section",{className:`turn-group${L?" clone-history-turn":""}`,"data-turn-id":x.id,children:[x.user?u.jsxs("div",{className:`turn-panel ${N?"system-turn":"user-turn"}`,children:[jc(x.user,We,Cr,Ua,rr,Zr,Jr,Cs,wa,_),u.jsx(Tc,{copied:Qi===`${N?"system":"user"}-${x.id}-bottom`,content:Ac(x.user),id:`${N?"system":"user"}-${x.id}-bottom`,timestamp:x.user.createdAt,variant:"outside",onCopy:ol})]}):null,x.followupUsers.length>0?u.jsx("div",{className:"turn-followup-users","aria-label":"Additional turn input",children:x.followupUsers.map(_e=>u.jsxs("div",{className:"turn-panel user-turn followup-user-turn",children:[u.jsx("span",{className:"followup-user-label",children:"Added while running"}),jc(_e,We,Cr,Ua,rr,Zr,Jr,Cs,wa,_),u.jsx(Tc,{copied:Qi===`user-${_e.id}-bottom`,content:Ac(_e),id:`user-${_e.id}-bottom`,timestamp:_e.createdAt,variant:"outside",onCopy:ol})]},_e.id))}):null,(Ge=x.acceptedSystemInputs)==null?void 0:Ge.map(_e=>u.jsxs("div",{className:"turn-panel system-turn",children:[jc(_e,We,Cr,Ua,rr,Zr,Jr,Cs,wa,_),u.jsx(Tc,{copied:Qi===`system-${_e.id}-bottom`,content:Ac(_e),id:`system-${_e.id}-bottom`,timestamp:_e.createdAt,variant:"outside",onCopy:ol})]},_e.id)),x.agentItems.length>0?u.jsx(uN,{group:x,conversation:We,allowProcessView:!L,copiedFooter:Qi===`agent-${x.id}-bottom`,copiedArtifactUrl:rr,running:!L&&Oc(x.turnIds,sl),onCopyArtifactUrl:Ua,onCopyBubble:ol,onPreviewArtifact:Cr,onLoadProcessDetails:_e=>We&&!L?xl(We.id,_e):void 0,onRespondApproval:Zr,onRespondWorkspaceChangeProposal:Jr,onRespondKnowledgeProposal:Cs,onOpenComplexTask:wa,onOpenSystemEvent:_}):null,(ze=x.trailingSystemItems)==null?void 0:ze.map(_e=>u.jsxs("div",{className:"turn-panel system-turn",children:[jc(_e,We,Cr,Ua,rr,Zr,Jr,Cs,wa,_),u.jsx(Tc,{copied:Qi===`system-${_e.id}-bottom`,content:Ac(_e),id:`system-${_e.id}-bottom`,timestamp:_e.createdAt,variant:"outside",onCopy:ol})]},_e.id))]}),ie?u.jsx("div",{className:"clone-history-boundary clone-history-end",children:"Clone starts here"}):null]},x.id)})]})]})}),u.jsxs("form",{className:"composer",onSubmit:Sa,ref:In,children:[qa?u.jsxs("div",{className:`global-activity ${qa.tone??"running"}`,children:[La?u.jsx("button",{"aria-label":"Stop current workspace activity",className:"turn-stop activity-stop",onClick:()=>void Ss(),title:"Stop current workspace activity",type:"button",children:u.jsx(fN,{})}):u.jsx("span",{className:"activity-wait-dot","aria-hidden":"true"}),u.jsxs("div",{className:"global-activity-text",children:[u.jsx("span",{children:qa.title}),qa.detail?u.jsx("small",{children:qa.detail}):null]}),La?u.jsx("span",{className:"activity-spinner","aria-hidden":"true"}):null]}):null,u.jsxs("div",{className:"composer-panel",children:[u.jsxs("button",{"aria-label":E?"Complex task mode is locked while a task is in progress":"Toggle complex task mode","aria-pressed":!!E||R==="complex",className:`complex-mode-button ${E||R==="complex"?"active":""}`,disabled:!!E,onClick:()=>B(x=>x==="complex"?"simple":"complex"),title:E?"End the current complex task before switching back":R==="complex"?"Complex task mode on":"Complex task mode off",type:"button",children:[u.jsx(s7,{}),u.jsx("span",{className:"complex-mode-tooltip",role:"tooltip",children:E?"Complex task active":R==="complex"?"Complex task mode on":"Complex task mode off"})]}),u.jsx("textarea",{disabled:Cu.textareaDisabled,onChange:x=>Uu(x.target.value),onKeyDown:Ao,placeholder:"Cmd/Ctrl + Enter",ref:ga,value:o}),u.jsxs("button",{"aria-label":"Send message",className:"composer-send",disabled:Cu.sendDisabled,type:"submit",children:[u.jsx(hN,{}),u.jsxs("span",{className:"composer-send-tooltip",role:"tooltip",children:[u.jsxs("span",{children:[u.jsx("kbd",{children:"⌘ / Ctrl + Enter"})," Send or add to running turn"]}),u.jsxs("span",{children:[u.jsx("kbd",{children:"⇧ + ⌘ / Ctrl + Enter"})," New turn or queue"]})]})]})]})]}),Pr?u.jsx("div",{className:"artifact-lightbox",onClick:()=>Cr(null),role:"presentation",children:u.jsxs("figure",{className:"artifact-lightbox-card",onClick:x=>x.stopPropagation(),children:[u.jsx("button",{"aria-label":"Close preview",className:"artifact-lightbox-close",onClick:()=>Cr(null),type:"button",children:"×"}),u.jsx("img",{alt:Pr.name,src:Pr.url}),u.jsxs("figcaption",{children:[u.jsx("span",{children:Pr.name}),u.jsxs("div",{className:"artifact-lightbox-actions",children:[u.jsx("a",{href:Pr.url,rel:"noreferrer",target:"_blank",children:"Open in new tab"}),u.jsx("button",{onClick:()=>void Ua(Pr),type:"button",children:rr===Pr.url?"Copied":"Copy URL"})]})]})]})}):null]})]})}function DE({conversation:e,clockNow:t,knowledgeDraft:n,workspaceKnowledge:i,tokenUsage:l,onCancelKnowledgeEdit:o,onDeleteKnowledge:c,onEditKnowledge:f,onKnowledgeDraftChange:h,onSubmitKnowledge:m,onClose:y}){const[v,k]=I.useState("overview"),[w,T]=I.useState(!1),[E,q]=I.useState(!1),[R,B]=I.useState(null),[F,Y]=I.useState(null),[te,_]=I.useState(!1),[K,le]=I.useState(null),[J,G]=I.useState(null),[ce,fe]=I.useState(!1),[Be,Ce]=I.useState(null),[ve,ee]=I.useState(null),pe=L7(l),De=Jp(e,e.status),Ye=R?Zz(R):null;I.useEffect(()=>{T(!1),B(null),Y(null),le(null),G(null),Ce(null),ee(null)},[e.id]),I.useEffect(()=>{v==="additionalContext"&&!K&&O()},[v,K]),I.useEffect(()=>{v==="compactions"&&!Be&&Q()},[v,Be]);const U=()=>{T(!0),q(!0),Y(null),rz(e.id).then(z=>B(z)).catch(z=>{const de=dt(z);Y(de.detail?`${de.message}
357
+ ${de.detail}`:de.message)}).finally(()=>q(!1))},O=()=>{_(!0),G(null),iz(e.id).then(z=>le(z)).catch(z=>{const de=dt(z);G(de.detail?`${de.message}
358
+ ${de.detail}`:de.message)}).finally(()=>_(!1))},Q=()=>{fe(!0),ee(null),lz(e.id).then(z=>Ce(z)).catch(z=>{const de=dt(z);ee(de.detail?`${de.message}
359
+ ${de.detail}`:de.message)}).finally(()=>fe(!1))};return u.jsx("div",{className:"context-panel-overlay workspace-context-overlay",onClick:y,role:"presentation",children:u.jsxs("section",{"aria-label":"Workspace context",className:"context-panel workspace-context-panel",onClick:z=>z.stopPropagation(),children:[u.jsxs("header",{className:"context-panel-header workspace-context-header",children:[u.jsxs("div",{children:[u.jsx("h2",{children:"Workspace Context"}),u.jsx("p",{children:"Long-lived context assets and observable state for this workspace."})]}),u.jsx("button",{"aria-label":"Close context panel",onClick:y,type:"button",children:"×"})]}),u.jsxs("div",{className:"workspace-context-body",children:[u.jsxs("nav",{className:"settings-nav workspace-context-nav","aria-label":"Workspace context sections",children:[u.jsxs("button",{className:v==="overview"?"active":void 0,onClick:()=>k("overview"),type:"button",children:[u.jsx("span",{children:"Overview"}),u.jsx("small",{children:"Identity + state"})]}),u.jsxs("button",{className:v==="responsibility"?"active":void 0,onClick:()=>k("responsibility"),type:"button",children:[u.jsx("span",{children:"Responsibility"}),u.jsx("small",{children:"Long-lived role"})]}),u.jsxs("button",{className:v==="knowledge"?"active":void 0,onClick:()=>k("knowledge"),type:"button",children:[u.jsx("span",{children:"Knowledge"}),u.jsx("small",{children:"Sources + skills"})]}),u.jsxs("button",{className:v==="runtime"?"active":void 0,onClick:()=>k("runtime"),type:"button",children:[u.jsx("span",{children:"Runtime View"}),u.jsx("small",{children:"Thread + tokens"})]}),u.jsxs("button",{className:v==="compactions"?"active":void 0,onClick:()=>k("compactions"),type:"button",children:[u.jsx("span",{children:"Compactions"}),u.jsx("small",{children:"Context history"})]}),u.jsxs("button",{className:v==="additionalContext"?"active":void 0,onClick:()=>k("additionalContext"),type:"button",children:[u.jsx("span",{children:"Additional Context"}),u.jsx("small",{children:"Injected keys"})]})]}),u.jsx("div",{className:"workspace-context-content",children:v==="overview"?u.jsxs("div",{className:"workspace-context-grid",children:[u.jsxs("section",{className:`context-card wide workspace-status-detail ${De}`,children:[u.jsx("h3",{children:"Current Status"}),u.jsx(wt,{label:"Status",value:Yd(De,e.nextWakeup,t)}),e.nextWakeup?u.jsxs(u.Fragment,{children:[u.jsx(wt,{label:"Wakeup state",value:e.nextWakeup.status}),u.jsx(wt,{label:"Wake at",value:Lc(e.nextWakeup.wakeAt)}),e.nextWakeup.status==="scheduled"?u.jsx(wt,{label:"Remaining",value:of(e.nextWakeup,t)}):null,u.jsx(wt,{label:"Created by",value:e.nextWakeup.createdBy}),u.jsx(wt,{label:"Attempts",value:`${e.nextWakeup.attemptCount} / ${e.nextWakeup.maxAttempts}`,mono:!0}),u.jsxs("div",{className:"workspace-status-detail-text",children:[u.jsx("span",{children:"Wakeup instruction"}),u.jsx("pre",{children:e.nextWakeup.instruction})]}),e.nextWakeup.error?u.jsxs("div",{className:"workspace-status-detail-text error",children:[u.jsx("span",{children:"Wakeup error"}),u.jsx("pre",{children:e.nextWakeup.error})]}):null]}):null,e.statusError?u.jsxs("div",{className:"workspace-status-detail-text error",children:[u.jsx("span",{children:"Error"}),u.jsx("pre",{children:e.statusError})]}):e.status==="error"||e.status==="initialization_failed"?u.jsx("p",{className:"context-muted",children:"No persisted error detail is available for this status."}):null]}),u.jsxs("section",{className:"context-card",children:[u.jsx("h3",{children:"Workspace"}),u.jsx(wt,{label:"Name",value:e.title}),u.jsx(wt,{label:"ID",value:`workspaces/${Zo(e.id)}`,mono:!0}),u.jsx(wt,{label:"Path",value:e.workspacePath,mono:!0})]}),u.jsxs("section",{className:"context-card",children:[u.jsx("h3",{children:"Context Assets"}),u.jsx(wt,{label:"Responsibility",value:e.responsibility.trim()?"configured":"missing"}),u.jsx(wt,{label:"Memory",value:e.memory.trim()?"configured":"empty"}),u.jsx(wt,{label:"Knowledge",value:`${i.length} item${i.length===1?"":"s"}`})]}),u.jsxs("section",{className:"context-card wide",children:[u.jsx("h3",{children:"Current Responsibility"}),e.responsibility.trim()?u.jsx("div",{className:"context-markdown-preview",children:Yl(e.responsibility,e)}):u.jsx("p",{className:"context-muted",children:"No approved responsibility is configured yet."})]}),u.jsxs("section",{className:"context-card wide",children:[u.jsx("h3",{children:"Knowledge Index"}),u.jsx(l7,{items:i,onDelete:c,onEdit:z=>{f(z),k("knowledge")}})]})]}):v==="responsibility"?u.jsxs("section",{className:"context-tab-surface",children:[u.jsx("header",{className:"settings-section-header",children:u.jsxs("div",{children:[u.jsx("h3",{children:"Workspace Responsibility"}),u.jsx("p",{children:"User-approved long-lived role for this workspace. Edit it from Settings in workspace scope."})]})}),e.responsibility.trim()?u.jsx("div",{className:"context-card context-markdown-preview",children:Yl(e.responsibility,e)}):u.jsx("p",{className:"context-card context-muted",children:"No approved responsibility is configured yet."})]}):v==="knowledge"?u.jsx(JE,{draft:n,items:i,scope:"workspace",workspaceName:e.title,onCancel:o,onDelete:c,onDraftChange:h,onEdit:f,onSubmit:m}):v==="runtime"?u.jsxs("div",{className:"workspace-context-grid",children:[u.jsxs("section",{className:"context-card",children:[u.jsx("h3",{children:"Runtime"}),u.jsx(wt,{label:"Runtime thread",value:e.codexThreadId??"not started",mono:!0}),u.jsxs("div",{className:"thread-read-actions",children:[u.jsx("button",{disabled:E,onClick:U,type:"button",children:E?"Reading...":"Read Codex thread"}),w?u.jsx("button",{disabled:E,onClick:()=>T(!1),type:"button",children:"Hide"}):null]})]}),u.jsxs("section",{className:"context-card",children:[u.jsx("h3",{children:"Token Window"}),l?u.jsxs(u.Fragment,{children:[u.jsx(wt,{label:"Used",value:pe===null?"unknown":`${Math.round(pe)}%`,mono:!0}),u.jsx(wt,{label:"Latest usage",value:l.modelContextWindow?`${wr(l.totalTokens)} / ${wr(l.modelContextWindow)}`:wr(l.totalTokens),mono:!0}),pe!==null?u.jsx("div",{className:`context-token-bar ${W1(pe)}`,children:u.jsx("span",{style:{width:`${Nf(pe)}%`}})}):null,u.jsx(wt,{label:"Input / output",value:`${Vd(l.inputTokens)} / ${Vd(l.outputTokens)}`,mono:!0}),u.jsx(wt,{label:"Reasoning",value:Vd(l.reasoningOutputTokens),mono:!0}),u.jsxs("p",{className:"context-muted",children:["Updated ",rt(l.createdAt),"."]})]}):u.jsx("p",{className:"context-muted",children:"No token usage event has been observed in the loaded event window yet."})]}),w?u.jsxs("section",{className:"context-card wide thread-read-panel",children:[u.jsx("h3",{children:"Runtime thread profile"}),u.jsx("p",{className:"context-muted",children:"One-time live thread/read response from Codex app-server. Seele does not persist this profile result."}),E?u.jsx("p",{className:"context-muted",children:"Reading Codex thread..."}):F?u.jsx("pre",{className:"thread-read-error",children:F}):R?u.jsxs(u.Fragment,{children:[Ye?u.jsx(lN,{summary:Ye}):null,u.jsxs("details",{className:"thread-read-raw",open:!0,children:[u.jsx("summary",{children:"Raw thread/read JSON"}),u.jsx("pre",{className:"thread-read-dump",children:JSON.stringify(R,null,2)})]})]}):u.jsx("p",{className:"context-muted",children:"No thread/read result loaded yet."})]}):null]}):v==="compactions"?u.jsxs("section",{className:"context-tab-surface",children:[u.jsxs("header",{className:"settings-section-header",children:[u.jsxs("div",{children:[u.jsx("h3",{children:"Context Compactions"}),u.jsx("p",{children:"Compaction history recorded for the current runtime thread."})]}),u.jsx("button",{className:"context-refresh-button",disabled:ce,onClick:Q,type:"button",children:ce?"Refreshing...":"Refresh"})]}),ve?u.jsx("pre",{className:"thread-read-error",children:ve}):ce&&!Be?u.jsx("p",{className:"context-card context-muted",children:"Loading compaction history..."}):Be!=null&&Be.length?u.jsx("div",{className:"context-compaction-list",children:Be.map(z=>u.jsxs("article",{className:"context-compaction-item",children:[u.jsxs("div",{className:"context-compaction-heading",children:[u.jsx("time",{children:rt(z.completedAt??z.usageObservedAt??z.startedAt??"")}),u.jsx("span",{className:`context-compaction-status ${z.status}`,children:z.status==="completed"?"Completed":"Running"})]}),u.jsx("dl",{className:"context-compaction-facts",children:Pz(z).map(de=>u.jsxs("div",{children:[u.jsx("dt",{children:de.label}),u.jsx("dd",{children:de.value})]},de.label))}),u.jsxs("small",{children:[Xl(z.id),z.turnId?` · turn ${Xl(z.turnId)}`:""]})]},z.id))}):u.jsx("p",{className:"context-card context-muted",children:"No compaction records yet."})]}):u.jsxs("section",{className:"context-tab-surface thread-read-panel",children:[u.jsx("header",{className:"settings-section-header",children:u.jsxs("div",{children:[u.jsx("h3",{children:"Additional Context"}),u.jsx("p",{children:"One-time live render of the application additionalContext for this workspace. Seele does not persist this preview result."})]})}),te?u.jsx("p",{className:"context-card context-muted",children:"Rendering additionalContext..."}):J?u.jsx("pre",{className:"thread-read-error",children:J}):K?u.jsx(aN,{preview:K,refreshing:te,onRefresh:O}):u.jsx("p",{className:"context-card context-muted",children:"No additionalContext preview loaded yet."})]})})]})]})})}function RE({conversations:e,onClose:t,workspaceGroups:n}){var U;const[i,l]=I.useState([]),[o,c]=I.useState("active"),[f,h]=I.useState(null),[m,y]=I.useState([]),[v,k]=I.useState(!0),[w,T]=I.useState(null),[E,q]=I.useState(null),[R,B]=I.useState(!1),[F,Y]=I.useState(!1),[te,_]=I.useState(new Set),[K,le]=I.useState({title:"",publicDescription:"",ownerWorkspaceId:((U=e[0])==null?void 0:U.id)??"",participantWorkspaceIds:[]}),J=i.find(O=>O.id===f)??null,G=I.useMemo(()=>new Map(e.map(O=>[O.id,O.title])),[e]),ce=i.filter(O=>o==="archived"?O.status==="archived":O.status!=="archived"),fe=n.map(O=>({...O,conversations:O.conversations.filter(Q=>Q.id!==K.ownerWorkspaceId)})).filter(O=>O.conversations.length>0),Be=()=>{var O;le({title:"",publicDescription:"",ownerWorkspaceId:((O=e[0])==null?void 0:O.id)??"",participantWorkspaceIds:[]}),_(new Set),q("create")},Ce=()=>{!J||J.status!=="active"||(le({title:J.title,publicDescription:J.publicDescription,ownerWorkspaceId:J.ownerWorkspaceId,participantWorkspaceIds:J.members.filter(O=>O.role==="participant"&&O.status==="active").map(O=>O.workspaceId)}),_(new Set),q("edit"))},ve=async(O,Q=o)=>{var z;k(!0),T(null);try{const de=await c5();l(de);const Re=de.filter(xe=>Q==="archived"?xe.status==="archived":xe.status!=="archived"),ne=(O&&Re.some(xe=>xe.id===O)?O:null)??(f&&Re.some(xe=>xe.id===f)?f:((z=Re[0])==null?void 0:z.id)??null);h(ne),y(ne?await Ld(ne):[])}catch(de){T(de instanceof Qa?de.detail:de instanceof Error?de.message:String(de))}finally{k(!1)}};I.useEffect(()=>{ve()},[]),I.useEffect(()=>{const O=window.setInterval(()=>{(async()=>{try{const Q=await c5();l(Q),f&&Q.some(z=>z.id===f)&&y(await Ld(f))}catch{}})()},1e4);return()=>window.clearInterval(O)},[f]);const ee=async O=>{h(O),T(null);try{y(await Ld(O))}catch(Q){T(Q instanceof Qa?Q.detail:Q instanceof Error?Q.message:String(Q))}},pe=async O=>{var z;if(O===o)return;c(O),T(null);const Q=((z=i.find(de=>O==="archived"?de.status==="archived":de.status!=="archived"))==null?void 0:z.id)??null;if(h(Q),!Q){y([]);return}try{y(await Ld(Q))}catch(de){T(de instanceof Qa?de.detail:de instanceof Error?de.message:String(de))}},De=async O=>{var Q;if(O.preventDefault(),!(!K.title.trim()||!K.ownerWorkspaceId)){Y(!0),T(null);try{const z=E==="edit"&&J?await MM(J.id,{expectedVersion:J.version,title:K.title.trim(),publicDescription:K.publicDescription.trim(),participantWorkspaceIds:K.participantWorkspaceIds}):await NM({...K,title:K.title.trim(),publicDescription:K.publicDescription.trim()});c("active"),q(null),le({title:"",publicDescription:"",ownerWorkspaceId:((Q=e[0])==null?void 0:Q.id)??"",participantWorkspaceIds:[]}),await ve(z.id,"active")}catch(z){T(z instanceof Qa?z.detail:z instanceof Error?z.message:String(z))}finally{Y(!1)}}},Ye=async()=>{if(!(!J||J.status!=="active")){Y(!0),T(null);try{const O=await zM(J.id,J.version);B(!1),c("active"),await ve(void 0,"active")}catch(O){T(O instanceof Qa?O.detail:O instanceof Error?O.message:String(O))}finally{Y(!1)}}};return u.jsx("div",{className:"context-panel-overlay settings-overlay",onClick:t,role:"presentation",children:u.jsxs("section",{"aria-label":"工作空间协作",className:"context-panel collaboration-panel",onClick:O=>O.stopPropagation(),children:[u.jsxs("header",{className:"context-panel-header collaboration-panel-header",children:[u.jsxs("div",{children:[u.jsx("h2",{children:"协作"}),u.jsx("p",{children:"在明确选择的工作空间之间建立持久、定向的 Topic 通信。"})]}),u.jsxs("div",{className:"collaboration-header-actions",children:[u.jsx("button",{"aria-label":"新建 Topic",className:"memory-icon-button collaboration-new-topic",onClick:Be,title:"新建 Topic",type:"button",children:"+"}),u.jsx("button",{"aria-label":"关闭协作",className:"icon-button",onClick:t,type:"button",children:"×"})]})]}),w?u.jsx("div",{className:"collaboration-error",children:w}):null,u.jsxs("div",{className:"collaboration-body",children:[u.jsxs("nav",{className:"collaboration-topic-list","aria-label":"协作 Topics",children:[u.jsxs("div",{className:"collaboration-topic-tabs",role:"tablist","aria-label":"Topic 列表范围",children:[u.jsx("button",{"aria-selected":o==="active",className:o==="active"?"active":void 0,onClick:()=>void pe("active"),role:"tab",type:"button",children:"当前"}),u.jsx("button",{"aria-selected":o==="archived",className:o==="archived"?"active":void 0,onClick:()=>void pe("archived"),role:"tab",type:"button",children:"已归档"})]}),v?u.jsx("p",{children:"正在加载..."}):ce.length===0?u.jsx("p",{children:o==="archived"?"还没有已归档 Topic。":"还没有当前 Topic。"}):ce.map(O=>u.jsxs("button",{className:`collaboration-topic-entry${O.id===f?" active":""}`,onClick:()=>void ee(O.id),type:"button",children:[u.jsx("span",{children:O.title}),u.jsxs("small",{children:[O.members.length," 个工作空间 · ",O.status]})]},O.id))]}),u.jsx("main",{className:"collaboration-topic-detail",children:J?u.jsxs(u.Fragment,{children:[u.jsxs("header",{children:[u.jsxs("div",{children:[u.jsx("h3",{children:J.title}),u.jsx("p",{children:J.publicDescription||"没有公开描述。"})]}),u.jsxs("div",{className:"collaboration-topic-actions",children:[u.jsx("span",{children:J.status}),J.status==="active"?u.jsxs(u.Fragment,{children:[u.jsx("button",{"aria-label":`编辑 Topic ${J.title}`,className:"memory-icon-button",onClick:Ce,title:"编辑",type:"button",children:u.jsx(Ef,{})}),u.jsx("button",{"aria-label":`归档 Topic ${J.title}`,className:"memory-icon-button",onClick:()=>B(!0),title:"归档",type:"button",children:u.jsx(kM,{})})]}):null]})]}),u.jsx("div",{className:"collaboration-members",children:J.members.filter(O=>O.status==="active").map(O=>u.jsxs("span",{children:[O.workspaceTitleSnapshot,u.jsx("small",{children:O.role})]},`${O.workspaceId}-${O.membershipVersion}`))}),u.jsx("div",{className:"collaboration-message-list",children:m.length===0?u.jsx("p",{children:"还没有消息。"}):m.map(O=>u.jsxs("article",{children:[u.jsxs("header",{children:[u.jsx("strong",{children:O.senderTitleSnapshot}),u.jsx("span",{children:O.recipientWorkspaceIds.includes("ALL")?"发给全部参与者":`发给 ${T7(O.recipientWorkspaceIds.map(Q=>G.get(Q)??Xl(Q)))}`}),u.jsx("time",{children:rt(O.createdAt)})]}),u.jsx("div",{className:"markdown-body",children:Yl(O.contentMarkdown,void 0)})]},O.id))})]}):u.jsx("div",{className:"collaboration-empty",children:"选择或新建一个 Topic。"})})]}),E?u.jsx("div",{className:"collaboration-create-overlay",role:"presentation",onClick:()=>!F&&q(null),children:u.jsxs("form",{className:"dialog-card collaboration-create-dialog",onClick:O=>O.stopPropagation(),onSubmit:De,children:[u.jsxs("header",{children:[u.jsxs("div",{children:[u.jsx("h3",{children:E==="edit"?"编辑 Topic":"新建 Topic"}),u.jsx("p",{children:E==="edit"?"调整公开信息与参与工作空间。":"明确选择本次通信的 owner 与参与者。"})]}),u.jsx("button",{"aria-label":"关闭 Topic 编辑",className:"icon-button",onClick:()=>q(null),type:"button",children:"×"})]}),u.jsxs("label",{children:["标题",u.jsx("input",{autoFocus:!0,placeholder:"填写 Topic 标题",value:K.title,onChange:O=>le(Q=>({...Q,title:O.target.value}))})]}),u.jsxs("label",{children:["公开描述",u.jsx("textarea",{placeholder:"填写所有参与工作空间可见的共享背景",value:K.publicDescription,onChange:O=>le(Q=>({...Q,publicDescription:O.target.value}))})]}),u.jsxs("label",{children:["Owner 工作空间",u.jsx("select",{disabled:E==="edit",value:K.ownerWorkspaceId,onChange:O=>le(Q=>({...Q,ownerWorkspaceId:O.target.value,participantWorkspaceIds:Q.participantWorkspaceIds.filter(z=>z!==O.target.value)})),children:n.map(O=>u.jsx("optgroup",{label:O.title,children:O.conversations.map(Q=>u.jsx("option",{value:Q.id,children:Q.title},Q.id))},O.id))})]}),u.jsxs("fieldset",{className:"collaboration-participant-groups",children:[u.jsx("legend",{children:"参与工作空间"}),u.jsxs("div",{className:"collaboration-participant-toolbar",children:[u.jsxs("span",{children:[K.participantWorkspaceIds.length," 个已选择"]}),u.jsxs("div",{children:[u.jsx("button",{onClick:()=>_(new Set),type:"button",children:"全部展开"}),u.jsx("button",{onClick:()=>_(new Set(fe.map(O=>O.id))),type:"button",children:"全部收起"})]})]}),fe.map(O=>{const Q=O.conversations,z=Q.filter(Re=>K.participantWorkspaceIds.includes(Re.id)).length,de=te.has(O.id);return u.jsxs("section",{className:"collaboration-participant-group",children:[u.jsxs("header",{children:[u.jsxs("button",{"aria-expanded":!de,className:"collaboration-group-toggle",onClick:()=>_(Re=>{const ne=new Set(Re);return ne.has(O.id)?ne.delete(O.id):ne.add(O.id),ne}),type:"button",children:[u.jsx("span",{"aria-hidden":"true",className:de?void 0:"expanded",children:"›"}),u.jsx("strong",{children:O.title}),u.jsxs("small",{children:[z,"/",Q.length]})]}),u.jsxs("label",{title:`选择 ${O.title} 全部工作空间`,children:[u.jsx("input",{checked:z===Q.length,onChange:()=>le(Re=>{const ne=Q.map(oe=>oe.id),xe=new Set(Re.participantWorkspaceIds);return ne.every(oe=>xe.has(oe))?ne.forEach(oe=>xe.delete(oe)):ne.forEach(oe=>xe.add(oe)),{...Re,participantWorkspaceIds:Array.from(xe)}}),type:"checkbox"}),u.jsx("span",{children:"全选"})]})]}),de?null:u.jsx("div",{children:Q.map(Re=>u.jsxs("label",{className:"collaboration-participant-option",children:[u.jsx("input",{checked:K.participantWorkspaceIds.includes(Re.id),onChange:ne=>le(xe=>({...xe,participantWorkspaceIds:ne.target.checked?[...xe.participantWorkspaceIds,Re.id]:xe.participantWorkspaceIds.filter(oe=>oe!==Re.id)})),type:"checkbox"}),u.jsx("span",{children:Re.title})]},Re.id))})]},O.id)})]}),u.jsxs("footer",{children:[u.jsx("button",{className:"secondary",disabled:F,onClick:()=>q(null),type:"button",children:"取消"}),u.jsx("button",{disabled:F||!K.title.trim()||!K.ownerWorkspaceId,type:"submit",children:F?"正在保存...":E==="edit"?"保存":"创建 Topic"})]})]})}):null,R&&J?u.jsx("div",{className:"collaboration-create-overlay",onClick:()=>!F&&B(!1),role:"presentation",children:u.jsxs("section",{"aria-label":"归档 Topic",className:"dialog-card collaboration-archive-dialog",onClick:O=>O.stopPropagation(),children:[u.jsxs("header",{children:[u.jsxs("div",{children:[u.jsx("h3",{children:"归档 Topic"}),u.jsx("p",{children:"归档后保留历史消息,但工作空间不能再向此 Topic 发送新消息。"})]}),u.jsx("button",{"aria-label":"关闭归档确认",className:"icon-button",onClick:()=>B(!1),type:"button",children:"×"})]}),u.jsx("strong",{children:J.title}),u.jsxs("footer",{children:[u.jsx("button",{className:"secondary",disabled:F,onClick:()=>B(!1),type:"button",children:"取消"}),u.jsx("button",{className:"danger",disabled:F,onClick:()=>void Ye(),type:"button",children:F?"正在归档...":"归档"})]})]})}):null]})})}function OE({busy:e,conversation:t,conversationId:n,forceStopBusy:i,preview:l,previewLoading:o,result:c,status:f,warmup:h,workspaceGroups:m,onCancelResetPreview:y,onClose:v,onForceStop:k,onPreviewReset:w,onStartBlankContext:T,onResetRuntime:E,onSaveResetSelection:q,onWorkspaceChange:R,onWarmupChange:B}){const F=!t||e||f==="running"||f==="initializing";return u.jsx("div",{className:"context-panel-overlay settings-overlay",onClick:v,role:"presentation",children:u.jsxs("section",{"aria-label":"Seele console",className:"context-panel console-panel",onClick:Y=>Y.stopPropagation(),children:[u.jsxs("header",{className:"context-panel-header console-panel-header",children:[u.jsxs("div",{children:[u.jsx("h2",{children:"Console"}),u.jsx("p",{children:"Control actions for the selected workspace runtime."})]}),u.jsxs("div",{className:"console-header-actions",children:[u.jsxs("label",{className:"console-workspace-picker",children:[u.jsx("span",{children:"Workspace"}),u.jsx("select",{disabled:e,onChange:Y=>R(Y.target.value),value:n??"",children:m.map(Y=>u.jsx("optgroup",{label:Y.title,children:Y.conversations.map(te=>u.jsxs("option",{value:te.id,children:[te.title," · workspaces/",Zo(te.id)]},te.id))},Y.id))})]}),u.jsx("button",{"aria-label":"Close console",onClick:v,type:"button",children:"×"})]})]}),u.jsx("div",{className:"console-body",children:u.jsxs("section",{className:"console-card",children:[u.jsxs("div",{className:"console-card-heading",children:[u.jsxs("div",{children:[u.jsx("h3",{children:"Workspace Runtime"}),u.jsx("p",{children:"Reset only replaces the Codex runtime thread. Seele workspace history, metadata, and files remain intact."})]}),u.jsx("span",{className:`console-status ${f}`,children:f})]}),u.jsxs("dl",{className:"console-facts",children:[u.jsxs("div",{children:[u.jsx("dt",{children:"Workspace"}),u.jsx("dd",{children:(t==null?void 0:t.title)??"No workspace selected"})]}),u.jsxs("div",{children:[u.jsx("dt",{children:"ID"}),u.jsx("dd",{children:t?`workspaces/${Zo(t.id)}`:"-"})]}),u.jsxs("div",{children:[u.jsx("dt",{children:"Thread"}),u.jsx("dd",{children:(t==null?void 0:t.codexThreadId)??"Not created"})]})]}),u.jsxs("label",{className:"console-toggle",children:[u.jsx("input",{checked:h,onChange:Y=>B(Y.target.checked),type:"checkbox"}),u.jsxs("span",{children:["Run a warmup turn after reset",u.jsx("small",{children:"The workspace will receive a system wakeup to re-orient itself after the thread is rebuilt."})]})]}),u.jsxs("div",{className:"console-actions",children:[u.jsx("button",{className:"danger",disabled:!t||i,onClick:k,title:"Kill the workspace runtime and repair every non-terminal scheduler state",type:"button",children:i?"Stopping & repairing...":"Force stop & repair"}),u.jsx("button",{className:"danger",disabled:F||o,onClick:w,type:"button",children:o?"Preparing preview...":"Preview runtime reset"}),u.jsx("button",{disabled:F||o,onClick:T,type:"button",children:"Clear memory & start blank"}),f==="running"||f==="initializing"?u.jsx("span",{children:"Force stop the active workspace operation before resetting."}):null]}),c?u.jsxs("div",{className:"console-result",children:[u.jsx("strong",{children:c.workspaceMemoryCleared?"Blank workspace context ready":"Runtime reset completed"}),u.jsxs("span",{children:[c.injectedItemCount," visible history items injected"]}),c.historyCompactionCount>0?u.jsxs("span",{children:["Full history processed in ",c.historyBatchCount," chronological batches with ",c.historyCompactionCount," native compactions"]}):null,c.workspaceMemoryCleared?u.jsx("span",{children:"Workspace Memory cleared; Base Memory retained"}):null,u.jsxs("span",{children:["New thread: ",c.newThreadId]}),c.warmupTurnId?u.jsxs("span",{children:["Warmup turn: ",c.warmupTurnId]}):null]}):null]})}),l?u.jsx(_E,{busy:e,preview:l,warmup:h,onCancel:y,onConfirm:E,onSaveSelection:q}):null]})})}function _E({busy:e,preview:t,warmup:n,onCancel:i,onConfirm:l,onSaveSelection:o}){const[c,f]=I.useState(()=>new Set(t.entries.filter(G=>G.includedByDefault).map(G=>G.id))),[h,m]=I.useState(!1),[y,v]=I.useState(!1),[k,w]=I.useState(null),T=I.useRef(null),E=t.entries.filter(G=>c.has(G.id)),q=E.filter(G=>G.role==="user").length,R=E.length-q,B=t.entries.filter(G=>G.topicRelation!==null).map(G=>G.id),F=B.filter(G=>c.has(G)).length,Y=t.entries.length>0&&c.size===t.entries.length;I.useEffect(()=>{T.current&&(T.current.indeterminate=c.size>0&&c.size<t.entries.length)},[t.entries.length,c.size]);const te=e||y;async function _(G){v(!0),w(null);try{await o(t.entries.filter(ce=>G.has(ce.id)).map(ce=>ce.id)),f(G)}catch(ce){w(dt(ce).message)}finally{v(!1)}}function K(G,ce){const fe=new Set(c);ce?fe.add(G):fe.delete(G),_(fe)}function le(){const G=new Set(c);B.forEach(ce=>G.add(ce)),_(G)}function J(){const G=new Set(c);B.forEach(ce=>{G.has(ce)?G.delete(ce):G.add(ce)}),_(G)}return u.jsx("div",{className:`reset-preview-overlay ${h?"expanded":""}`,onClick:te?void 0:i,role:"presentation",children:u.jsxs("section",{"aria-label":"Runtime reset preview","aria-modal":"true",className:`reset-preview-dialog ${h?"expanded":""}`,onClick:G=>G.stopPropagation(),role:"dialog",children:[u.jsxs("header",{className:"reset-preview-header",children:[u.jsxs("div",{children:[u.jsx("h3",{children:"Confirm runtime reset"}),u.jsx("p",{children:"The new thread will process the selected original messages in chronological batches. Each batch is compacted natively before the next batch is injected; the old thread context is never reused."})]}),u.jsxs("div",{className:"reset-preview-header-actions",children:[u.jsx("button",{"aria-label":h?"Restore reset preview size":"Expand reset preview",onClick:()=>m(G=>!G),title:h?"Restore size":"Expand",type:"button",children:h?"⊡":"⛶"}),u.jsx("button",{"aria-label":"Close reset preview",disabled:te,onClick:i,type:"button",children:"×"})]})]}),u.jsxs("div",{className:"reset-preview-summary",children:[u.jsxs("label",{className:"reset-preview-select-all",children:[u.jsx("input",{checked:Y,disabled:te||t.entries.length===0,onChange:G=>void _(G.target.checked?new Set(t.entries.map(ce=>ce.id)):new Set),ref:T,type:"checkbox"}),u.jsxs("span",{children:[c.size," of ",t.entries.length," selected"]})]}),u.jsxs("span",{children:[q," user"]}),u.jsxs("span",{children:[R," assistant"]}),B.length>0?u.jsxs("div",{className:"reset-preview-topic-actions",children:[u.jsxs("span",{children:[F," of ",B.length," Topic input + response"]}),u.jsx("button",{disabled:te||F===B.length,onClick:le,type:"button",children:"Select Topic turns"}),u.jsx("button",{disabled:te,onClick:J,type:"button",children:"Invert Topic turns"})]}):null,u.jsxs("span",{children:[t.historyBatchCount," planned batch",t.historyBatchCount===1?"":"es"]}),u.jsxs("span",{children:["~",t.estimatedTokenCount.toLocaleString()," source tokens"]}),u.jsx("span",{children:n?"Warmup enabled":"No warmup"}),y?u.jsx("span",{children:"Saving defaults..."}):null,k?u.jsx("span",{className:"reset-preview-selection-error",children:k}):null]}),u.jsx("div",{className:"reset-preview-list",children:t.entries.length>0?t.entries.map((G,ce)=>u.jsxs("article",{className:`reset-preview-item ${G.role} ${c.has(G.id)?"":"excluded"}`,children:[u.jsxs("header",{children:[u.jsxs("label",{children:[u.jsx("input",{"aria-label":`Include ${G.role} message ${ce+1}`,checked:c.has(G.id),disabled:te,onChange:fe=>K(G.id,fe.target.checked),type:"checkbox"}),u.jsx("span",{children:ce+1})]}),u.jsx("strong",{children:G.role}),G.topicRelation?u.jsxs("span",{className:"reset-preview-topic-badge",children:["Topic ",G.topicRelation]}):null,u.jsx("time",{dateTime:G.createdAt,children:rt(G.createdAt)})]}),u.jsx("pre",{children:G.content})]},G.id)):u.jsx("p",{className:"reset-preview-empty",children:"No visible history will be injected."})}),u.jsxs("footer",{className:"reset-preview-actions",children:[u.jsxs("small",{children:["Preview fingerprint: ",t.fingerprint.slice(0,12)]}),u.jsxs("div",{children:[u.jsx("button",{disabled:te,onClick:i,type:"button",children:"Cancel"}),u.jsx("button",{className:"danger",disabled:te,onClick:()=>l(t.entries.filter(G=>c.has(G.id)).map(G=>G.id)),type:"button",children:e?"Rebuilding and compacting...":"Confirm full-history reset"})]})]})]})})}function BE({currentReleasedAt:e,currentVersion:t,job:n,latest:i,latestChecking:l,starting:o,onClose:c,onRefresh:f,onStart:h}){const m=(n==null?void 0:n.currentVersion)??t,y=i!=null&&i.version&&iD(i.version,m)?aD(i.version):null;return I.useEffect(()=>{const v=k=>{k.key==="Escape"&&c()};return document.addEventListener("keydown",v),()=>document.removeEventListener("keydown",v)},[c]),u.jsx("div",{className:"codex-update-overlay",onClick:c,role:"presentation",children:u.jsxs("section",{"aria-label":"Codex CLI update",className:"codex-update-panel",onClick:v=>v.stopPropagation(),children:[u.jsxs("header",{children:[u.jsxs("div",{children:[u.jsx("h3",{children:"Codex CLI update"}),u.jsx("p",{children:"Managed by Seele in the instance runtime directory."})]}),u.jsx("button",{"aria-label":"Close Codex CLI update",onClick:c,type:"button",children:"×"})]}),u.jsxs("dl",{className:"codex-update-summary",children:[u.jsxs("div",{children:[u.jsx("dt",{children:"Status"}),u.jsx("dd",{className:n?`status-${n.status}`:void 0,children:(n==null?void 0:n.status)??"Not started"})]}),u.jsxs("div",{children:[u.jsx("dt",{children:"Current"}),u.jsx("dd",{children:Zp(m,(n==null?void 0:n.codexReleasedAt)??e)})]}),u.jsxs("div",{children:[u.jsx("dt",{children:"Latest"}),u.jsxs("dd",{title:(i==null?void 0:i.error)??void 0,children:[l?"Checking...":i!=null&&i.version?Zp(i.version,i.releasedAt):i!=null&&i.error?"Check failed":"Not checked",y?u.jsx("a",{className:"codex-release-notes-link",href:y,rel:"noreferrer",target:"_blank",children:"Release notes"}):null]})]}),n?u.jsxs("div",{children:[u.jsx("dt",{children:"Started"}),u.jsx("dd",{children:rt(n.startedAt)})]}):null]}),i!=null&&i.error?u.jsxs("p",{className:"codex-latest-error",children:["Latest version check: ",i.error]}):null,u.jsx("div",{className:"codex-update-log",role:"log","aria-live":"polite",children:n!=null&&n.logs.length?n.logs.map((v,k)=>u.jsxs("div",{className:`log-${v.stream}`,children:[u.jsx("time",{children:rD(v.at)}),u.jsx("span",{children:v.text})]},`${v.at}-${k}`)):u.jsx("p",{children:"No update logs yet."})}),u.jsxs("footer",{children:[u.jsx("button",{className:"secondary",onClick:f,type:"button",children:"Refresh"}),u.jsx("button",{disabled:o||(n==null?void 0:n.status)==="running",onClick:h,type:"button",children:o?"Starting...":(n==null?void 0:n.status)==="running"?"Updating...":n?"Run again":"Start update"})]})]})})}function IE({currentUser:e,conversations:t,deploymentSettings:n,editingEnvironmentKey:i,environmentDraft:l,globalEnvironment:o,workspaceEnvironment:c,memorySettings:f,memorySettingsDraft:h,managedUsers:m,workspaceMemoryDraft:y,runtimeSettings:v,runtimeModels:k,runtimeCodexVersion:w,runtimeCodexReleasedAt:T,runtimeCodexUpdating:E,runtimeSettingsDraft:q,runtimeSettingsScope:R,settingsWorkspace:B,settingsWorkspaceId:F,systemDiagnostics:Y,systemDiagnosticsLoading:te,workspaceGroups:_,workspaceRuntimeSettings:K,workspaceRuntimeSettingsDraft:le,onCancelEnvironmentEdit:J,onClose:G,onCreateUser:ce,onDeleteUser:fe,onDeleteEnvironment:Be,onDraftChange:Ce,onEditEnvironment:ve,onSaveBaseMemoryItems:ee,onSaveDeploymentSettings:pe,onSaveResponsibility:De,onSaveWorkspaceMemoryItems:Ye,onRevealEnvironmentValue:U,onRuntimeDraftChange:O,onCodexAccountSwitched:Q,onUpdateCodexCli:z,onRuntimeScopeChange:de,onSettingsWorkspaceChange:Re,onSubmitRuntimeSettings:ne,onSubmitEnvironment:xe,onRefreshSystemDiagnostics:oe,onUpdateUser:Oe,onWorkspaceRuntimeDraftChange:st,onWorkspaceRuntimeReset:Ct,revealedEnvironmentKeys:lt}){const[Je,ut]=I.useState("model"),[At,jn]=I.useState(!1),[Qe,Zt]=I.useState(null),[Pt,Wt]=I.useState(!1),[qr,Sr]=I.useState((B==null?void 0:B.responsibility)??""),[ua,Vt]=I.useState(!1),Ur=I.useRef(null),he=R==="workspace"?Object.values((K==null?void 0:K.sources)??{}).filter(we=>we==="workspace").length:0;return I.useEffect(()=>{R==="global"&&Wt(!1)},[R]),I.useEffect(()=>{Sr((B==null?void 0:B.responsibility)??"")},[B==null?void 0:B.id,B==null?void 0:B.responsibility]),I.useEffect(()=>{if(!Pt)return;const we=et=>{var Tn;const vt=et.target;vt instanceof Node&&((Tn=Ur.current)!=null&&Tn.contains(vt))||Wt(!1)},Ue=et=>{et.key==="Escape"&&Wt(!1)};return document.addEventListener("pointerdown",we,!0),document.addEventListener("keydown",Ue,!0),()=>{document.removeEventListener("pointerdown",we,!0),document.removeEventListener("keydown",Ue,!0)}},[Pt]),u.jsx("div",{className:"context-panel-overlay settings-overlay",onClick:G,role:"presentation",children:u.jsxs("section",{"aria-label":"Seele settings",className:"context-panel settings-panel",onClick:we=>we.stopPropagation(),children:[u.jsxs("header",{className:"context-panel-header settings-panel-header",children:[u.jsxs("div",{className:"settings-panel-title",children:[u.jsx("h2",{children:"Settings"}),Je!=="system"&&Je!=="users"&&Je!=="accounts"&&Je!=="deployment"?u.jsxs("div",{"aria-label":"Configuration scope",className:"settings-scope-segments",role:"radiogroup",children:[e.role==="admin"?u.jsx("button",{"aria-checked":R==="global",className:R==="global"?"active":void 0,onClick:()=>de("global"),role:"radio",type:"button",children:"Global"}):null,u.jsxs("div",{className:"settings-workspace-picker",ref:Ur,children:[u.jsx("button",{"aria-checked":R==="workspace","aria-expanded":R==="workspace"?Pt:void 0,"aria-label":R==="workspace"?"Settings workspace target":void 0,className:R==="workspace"?"active settings-scope-workspace-trigger":void 0,disabled:t.length===0,onClick:()=>{if(R!=="workspace"){de("workspace");return}Wt(we=>!we)},role:"radio",type:"button",children:R==="workspace"?u.jsxs(u.Fragment,{children:[u.jsxs("span",{children:["Workspace: ",(B==null?void 0:B.title)??"Select workspace"]}),u.jsx("span",{"aria-hidden":"true",children:"⌄"})]}):"Workspace"}),R==="workspace"&&Pt?u.jsx("div",{className:"settings-workspace-menu",role:"listbox",children:_.map(we=>u.jsxs("div",{className:"settings-workspace-menu-group",children:[u.jsx("div",{className:"settings-workspace-menu-heading",children:we.title}),we.conversations.map(Ue=>u.jsxs("button",{"aria-selected":Ue.id===F,className:Ue.id===F?"selected":void 0,onClick:()=>{Re(Ue.id),Wt(!1)},role:"option",type:"button",children:[u.jsx("span",{children:Ue.title}),u.jsxs("small",{children:["workspaces/",Ue.id]})]},Ue.id))]},we.id))}):null]})]}):null]}),u.jsx("div",{className:"settings-header-actions",children:u.jsx("button",{"aria-label":"Close settings panel",onClick:G,type:"button",children:"×"})})]}),u.jsxs("div",{className:"settings-body",children:[u.jsxs("nav",{className:"settings-nav","aria-label":"Settings sections",children:[u.jsxs("button",{className:Je==="model"?"active":void 0,onClick:()=>ut("model"),type:"button",children:[u.jsx("span",{children:"Runtime"}),u.jsx("small",{children:"Effective settings"})]}),u.jsxs("button",{className:Je==="responsibility"?"active":void 0,onClick:()=>ut("responsibility"),type:"button",children:[u.jsx("span",{children:"Responsibility"}),u.jsx("small",{children:"Workspace role"})]}),u.jsxs("button",{className:Je==="memory"?"active":void 0,onClick:()=>ut("memory"),type:"button",children:[u.jsx("span",{children:"Memory"}),u.jsx("small",{children:"Base + workspace context"})]}),u.jsxs("button",{className:Je==="environment"?"active":void 0,onClick:()=>ut("environment"),type:"button",children:[u.jsx("span",{children:"Environment"}),u.jsx("small",{children:"Base + workspace variables"})]}),e.role==="admin"?u.jsxs(u.Fragment,{children:[u.jsxs("button",{className:Je==="accounts"?"active":void 0,onClick:()=>ut("accounts"),type:"button",children:[u.jsx("span",{children:"Codex Accounts"}),u.jsx("small",{children:"Cloud login + active account"})]}),u.jsxs("button",{className:Je==="deployment"?"active":void 0,onClick:()=>ut("deployment"),type:"button",children:[u.jsx("span",{children:"Deployment"}),u.jsx("small",{children:"Local integrations"})]}),u.jsxs("button",{onClick:()=>{window.location.assign(`${q1()}admin/host`)},type:"button",children:[u.jsx("span",{children:"Work Operations"}),u.jsx("small",{children:"Versions, restart, logs"})]}),u.jsxs("button",{className:Je==="system"?"active":void 0,onClick:()=>ut("system"),type:"button",children:[u.jsx("span",{children:"System"}),u.jsx("small",{children:"Runtime + resources"})]}),u.jsxs("button",{className:Je==="users"?"active":void 0,onClick:()=>ut("users"),type:"button",children:[u.jsx("span",{children:"Users"}),u.jsx("small",{children:"Access + roles"})]})]}):null]}),u.jsxs("section",{className:"settings-content",children:[Je!=="system"&&Je!=="users"&&Je!=="accounts"&&Je!=="deployment"?u.jsxs("div",{className:`settings-scope-banner ${R==="workspace"?"workspace":"global"}`,children:[u.jsx("strong",{children:R==="workspace"?"Editing workspace custom settings":"Editing global settings"}),u.jsx("span",{children:R==="workspace"?`${(B==null?void 0:B.title)??"Selected workspace"} overrides global defaults.`:"These defaults apply to every workspace unless that workspace overrides them."})]}):null,Je==="system"?u.jsx(LE,{conversations:t,diagnostics:Y,loading:te,onRefresh:oe}):Je==="users"?u.jsx(VE,{currentUser:e,users:m,onCreate:ce,onDelete:fe,onUpdate:Oe}):Je==="accounts"?u.jsx(PE,{onSwitched:Q}):Je==="deployment"?u.jsx(YE,{settings:n,onSave:pe}):Je==="model"?u.jsx(WE,{draft:R==="workspace"?le:q,globalSettings:v,models:k,codexVersion:w,codexReleasedAt:T,codexUpdating:E,scope:R,workspaceOverrideCount:he,settings:R==="workspace"?(K==null?void 0:K.effective)??le:v,workspaceSettings:K,onDraftChange:R==="workspace"?st:O,onResetWorkspaceSetting:Ct,onSubmit:ne,onUpdateCodexCli:z}):Je==="responsibility"?u.jsx(HE,{draft:qr,saving:ua,scope:R,workspace:B,onDraftChange:Sr,onSubmit:we=>{we.preventDefault(),we.stopPropagation(),!(R!=="workspace"||!B)&&(Vt(!0),De(B.id,qr).then(Ue=>Sr(Ue)).finally(()=>Vt(!1)))}}):Je==="memory"?u.jsx(XE,{baseSettings:f,scope:R,workspaceSettings:y,workspaceName:B==null?void 0:B.title,onSaveBaseItems:ee,onSaveWorkspaceItems:Ye}):u.jsx(ZE,{deleteConfirmKey:Qe,editingEnvironmentKey:i,environmentDraft:l,globalEnvironment:o,scope:R,workspaceEnvironment:c,valueVisible:At,onCancelEnvironmentEdit:J,onDeleteConfirmChange:Zt,onDeleteEnvironment:Be,onDraftChange:Ce,onEditEnvironment:ve,onRevealEnvironmentValue:U,onSubmitEnvironment:xe,onValueVisibleChange:jn,revealedEnvironmentKeys:lt})]})]})]})})}function LE({conversations:e,diagnostics:t,loading:n,onRefresh:i}){const l=(t==null?void 0:t.runtime.pool)??null,o=I.useMemo(()=>(t==null?void 0:t.systemLogs)??[],[t]),[c,f]=I.useState(!1),h=I.useMemo(()=>new Map(e.map(w=>[w.id,w.title])),[e]),m=I.useMemo(()=>t?JSON.stringify({generatedAt:t.generatedAt,app:t.app,systemLogs:o},null,2):"",[t,o]),y=async()=>{m&&(await navigator.clipboard.writeText(m),f(!0),window.setTimeout(()=>f(!1),1800))},v=()=>{if(!m||!t)return;const w=URL.createObjectURL(new Blob([m],{type:"application/json"})),T=document.createElement("a");T.href=w,T.download=`seele-system-log-${t.generatedAt.replaceAll(":","-").replaceAll(".","-")}.json`,T.click(),URL.revokeObjectURL(w)},k=()=>{if(!t||!o.length)return;const w=o[0],T=o.slice(0,5).map(F=>`- ${Lc(F.createdAt)} · ${F.level.toUpperCase()} · ${F.event} · ${F.summary}`).join(`
354
360
  `),E=JSON.stringify(w,null,2),q=["## Environment","",`- Seele: ${t.app.version}`,`- Runtime: ${t.app.runtime}`,`- Report generated: ${Lc(t.generatedAt)}`,"","## Latest incident","","```json",E.slice(0,2500),"```","","## Recent system log","",T,"","_Generated by Seele System Log. Attach the downloaded JSON report when more history is needed._"].join(`
355
- `),R=`[System Log] ${w.summary}`.slice(0,180),B=new URL("https://github.com/seele-labs/seele-work/issues/new");B.searchParams.set("title",R),B.searchParams.set("body",q),window.open(B.toString(),"_blank","noopener,noreferrer")};return u.jsxs("section",{className:"system-information-section",children:[u.jsxs("header",{className:"settings-section-header",children:[u.jsxs("div",{children:[u.jsx("h3",{children:"System"}),u.jsx("p",{children:"Read-only runtime and resource information managed by Seele."})]}),u.jsx("button",{className:"system-information-refresh",disabled:n,onClick:i,type:"button",children:n?"Refreshing...":"Refresh"})]}),l?u.jsxs(u.Fragment,{children:[u.jsxs("dl",{className:"system-information-summary",children:[u.jsxs("div",{children:[u.jsx("dt",{children:"LRU pool target"}),u.jsxs("dd",{children:[wr(l.maxRetainedRuntimes)," runtimes"]}),u.jsx("small",{children:l.capacitySource==="system_memory"?"Idle runtimes are released by least recent use":"Fallback target because system memory was unavailable"})]}),u.jsxs("div",{children:[u.jsx("dt",{children:"Retention policy"}),u.jsxs("dd",{children:["LRU · ",op(l.maxIdleSeconds*1e3)," max idle"]}),u.jsx("small",{children:"Only idle runtimes are eligible for eviction"})]}),u.jsxs("div",{children:[u.jsx("dt",{children:"Current pool"}),u.jsxs("dd",{children:[l.activeRuntimeCount," active · ",l.idleRuntimeCount," idle"]}),u.jsxs("small",{children:[l.retainedRuntimeCount," retained runtimes"]})]})]}),u.jsxs("section",{className:"system-runtime-list",children:[u.jsxs("header",{children:[u.jsxs("div",{children:[u.jsx("h4",{children:"Workspace runtimes"}),u.jsx("p",{children:"Active workspaces and idle runtimes currently retained for reuse."})]}),u.jsx("time",{dateTime:t==null?void 0:t.generatedAt,children:t?rt(t.generatedAt):""})]}),l.workspaces.length>0?u.jsxs("div",{className:"system-runtime-table",children:[u.jsxs("div",{className:"system-runtime-table-header",children:[u.jsx("span",{children:"Workspace"}),u.jsx("span",{children:"Status"}),u.jsx("span",{children:"Runtime"}),u.jsx("span",{children:"Age"})]}),l.workspaces.map(w=>u.jsxs("div",{className:"system-runtime-row",children:[u.jsxs("div",{children:[u.jsx("strong",{children:h.get(w.workspaceId)??w.workspaceId}),u.jsx("small",{children:w.workspaceId})]}),u.jsx("span",{className:`system-runtime-state ${w.turnId?"active":"idle"}`,children:w.lifecycle==="shutting_down"?"Shutting down":w.turnId?"Active":"Idle"}),u.jsxs("div",{children:[u.jsx("span",{children:w.turnId?w.state:"Retained"}),u.jsx("small",{children:w.pid===null?"PID unavailable":`PID ${w.pid}`})]}),u.jsx("span",{children:w.idleMs===null?op(w.uptimeMs):`${op(w.idleMs)} idle`})]},w.workspaceId))]}):u.jsx("div",{className:"system-runtime-empty",children:"No workspace runtimes are currently retained."})]}),u.jsxs("section",{className:"system-runtime-list system-log-list",children:[u.jsxs("header",{children:[u.jsxs("div",{children:[u.jsx("h4",{children:"System log"}),u.jsx("p",{children:"Recent persistent warnings and errors for external diagnostics."})]}),u.jsxs("div",{className:"system-log-actions",children:[u.jsx("button",{"aria-label":"Copy system log report",className:"icon-button",disabled:!o.length,onClick:()=>void y(),title:"Copy system log report",type:"button",children:u.jsx(P1,{})}),u.jsx("button",{"aria-label":"Download system log report",className:"icon-button",disabled:!o.length,onClick:v,title:"Download system log report",type:"button",children:u.jsx(LE,{})}),u.jsx("button",{"aria-label":"Report system log issue",className:"icon-button",disabled:!o.length,onClick:k,title:"Report issue to seele-labs/seele-work",type:"button",children:u.jsx(qE,{})}),c?u.jsx("small",{children:"Copied"}):null]})]}),o.length?u.jsx("div",{className:"system-log-entries",children:o.map(w=>u.jsxs("details",{className:`system-log-entry ${w.level}`,children:[u.jsxs("summary",{children:[u.jsx("span",{className:"system-log-level",children:w.level}),u.jsxs("span",{children:[u.jsx("strong",{children:w.summary}),u.jsxs("small",{children:[w.component," · ",Lc(w.createdAt)]})]})]}),u.jsxs("dl",{children:[u.jsxs("div",{children:[u.jsx("dt",{children:"Event"}),u.jsx("dd",{children:w.event})]}),w.workspaceId?u.jsxs("div",{children:[u.jsx("dt",{children:"Workspace"}),u.jsxs("dd",{children:[h.get(w.workspaceId)??w.workspaceId," · ",w.workspaceId]})]}):null,w.turnId?u.jsxs("div",{children:[u.jsx("dt",{children:"Turn"}),u.jsx("dd",{children:w.turnId})]}):null,w.runtimeId?u.jsxs("div",{children:[u.jsx("dt",{children:"Runtime"}),u.jsx("dd",{children:w.runtimeId})]}):null]}),u.jsx("pre",{children:JSON.stringify(w.detail,null,2)})]},w.id))}):u.jsx("div",{className:"system-runtime-empty",children:"No warnings or errors have been recorded."})]})]}):u.jsx("div",{className:"system-runtime-empty",children:n?"Loading system information...":"System information is unavailable."})]})}function LE(){return u.jsx("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",children:u.jsx("path",{d:"M12 3v12m0 0 4-4m-4 4-4-4M5 20h14"})})}function qE(){return u.jsxs("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",children:[u.jsx("circle",{cx:"12",cy:"12",r:"9"}),u.jsx("path",{d:"M12 7v6m0 4h.01"})]})}function UE({draft:e,saving:t,scope:n,workspace:i,onDraftChange:l,onSubmit:o}){const c=n==="workspace";return u.jsxs(u.Fragment,{children:[u.jsx("header",{className:"settings-section-header",children:u.jsxs("div",{children:[u.jsx("h3",{children:"Responsibility"}),u.jsx("p",{children:"Workspace-specific long-lived role. This is content context, so it is only editable in workspace scope."})]})}),c&&i?u.jsxs("form",{className:"settings-responsibility-form",onSubmit:o,children:[u.jsxs("label",{children:[u.jsx("span",{children:i.title}),u.jsx("textarea",{"aria-label":"Workspace responsibility",onChange:f=>l(f.target.value),placeholder:"Describe this workspace's durable role, scope, and long-term responsibilities.",rows:14,value:e})]}),u.jsx("div",{className:"settings-form-actions",children:u.jsx("button",{disabled:t,type:"submit",children:t?"Saving...":"Save responsibility"})})]}):u.jsx("section",{className:"settings-readonly-block",children:u.jsxs("div",{children:[u.jsx("strong",{children:"Workspace-only setting"}),u.jsx("span",{children:"Switch the header scope to Workspace and choose a workspace to edit its responsibility."})]})})]})}function HE({usage:e}){return u.jsx("div",{"aria-label":"Codex account usage",className:"codex-account-usage",children:[...e.windows].sort((t,n)=>t.windowDurationMins-n.windowDurationMins).map(t=>{const n=Nf(t.usedPercent),i=u7(t.windowDurationMins);return u.jsxs("div",{className:"codex-account-usage-window",children:[u.jsxs("div",{children:[u.jsxs("span",{children:[i," used"]}),u.jsx("strong",{children:H7(n)})]}),u.jsx("span",{"aria-hidden":"true",className:"codex-account-usage-track",children:u.jsx("span",{style:{width:`${n}%`}})}),u.jsxs("small",{children:["Resets ",F7(t.resetsAt)]})]},`${t.windowDurationMins}:${t.resetsAt}`)})})}function FE(e){if(!e)return null;const t=e.toLowerCase();return t==="chatgpt"?"ChatGPT":t==="apikey"||t==="api_key"?"API key":e}function $E(e){return e?e.split(/[_-]/).filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" "):null}function GE({onSwitched:e}){var Re;const[t,n]=I.useState(null),[i,l]=I.useState(!0),[o,c]=I.useState(!1),[f,h]=I.useState(!1),[m,y]=I.useState(""),[v,k]=I.useState(!1),[w,T]=I.useState(""),[E,q]=I.useState(null),[R,B]=I.useState(null),[F,Y]=I.useState(""),[te,_]=I.useState(null),[K,le]=I.useState(null),[J,G]=I.useState(!1),[ce,fe]=I.useState(""),Be=I.useRef(new Map);async function Ce(ne,xe){if(f||o||!window.confirm(`Use one reset credit for ${ne.name}? This consumes the credit if an eligible rate-limit window is reset.`))return;const oe=JSON.stringify([ne.id,xe.id]),Oe=Be.current.get(oe)??crypto.randomUUID();Be.current.set(oe,Oe),h(!0),y(""),fe("");try{const st=Ne(`settings/runtime/accounts/${encodeURIComponent(ne.id)}/reset-credits/consume`),Ct=await fetch(st,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({creditId:xe.id,idempotencyKey:Oe})});await He(Ct,{method:"POST",url:st});const lt=await Ct.json(),ut={reset:"Reset credit used. Eligible rate limits have been reset.",alreadyRedeemed:"This reset was already completed.",nothingToReset:"No rate-limit window needs a reset. No credit was used.",noCredit:"No reset credit is available for this account."}[lt.outcome];if(!ut)throw new Error("Reset outcome is unknown. Refresh details before trying again.");(lt.outcome==="nothingToReset"||lt.outcome==="noCredit")&&Be.current.delete(oe),fe(`${ne.name}: ${ut}`),n(At=>{if(!At)return At;const jn={...At.accountDetails};return delete jn[ne.id],{...At,accountDetails:jn}});try{n(await lp(!0))}catch{y("The result above is confirmed, but refreshing details failed. Please refresh details.")}}catch(st){y(`${dt(st).message} The outcome may be unknown; retrying this credit on this page reuses the same request ID.`)}finally{h(!1)}}async function ve(){var xe;const ne=await f5();n(ne),((xe=ne.login)==null?void 0:xe.status)==="pending"&&(q(ne.login),k(!0))}async function ee(ne){c(!0),y("");try{n(await lp(ne))}catch(xe){y(dt(xe).message)}finally{c(!1)}}I.useEffect(()=>{let ne=!1;return f5().then(xe=>{var oe;ne||(n(xe),((oe=xe.login)==null?void 0:oe.status)==="pending"&&(q(xe.login),k(!0)),xe.accounts.length>0&&(c(!0),lp(!1).then(Oe=>{ne||n(Oe)}).catch(Oe=>{ne||y(dt(Oe).message)}).finally(()=>{ne||c(!1)})))}).catch(xe=>{ne||y(dt(xe).message)}).finally(()=>{ne||l(!1)}),()=>{ne=!0}},[]),I.useEffect(()=>{if(!E||E.status!=="pending")return;let ne=!1;const xe=window.setInterval(()=>{$M(E.id).then(async oe=>{ne||(q(oe),oe.status!=="pending"&&(window.clearInterval(xe),oe.status==="succeeded"&&n(Oe=>{if(!Oe||!oe.account)return Oe;const st=Oe.accounts.some(Ct=>{var lt;return Ct.id===((lt=oe.account)==null?void 0:lt.id)})?Oe.accounts.map(Ct=>{var lt;return Ct.id===((lt=oe.account)==null?void 0:lt.id)?oe.account:Ct}):[...Oe.accounts,oe.account];return{...Oe,accounts:st}})))}).catch(oe=>{ne||y(dt(oe).message)})},1e3);return()=>{ne=!0,window.clearInterval(xe)}},[E==null?void 0:E.id,E==null?void 0:E.status]);function pe(){T(""),q(null),y(""),G(!1),k(!0)}async function De(ne){ne.preventDefault(),h(!0),y("");try{q(await FM(w.trim()))}catch(xe){y(dt(xe).message)}finally{h(!1)}}async function Ye(){if(!E||E.status!=="pending"){k(!1);return}h(!0),y("");try{const ne=await GM(E.id);q(ne),k(!1)}catch(ne){y(dt(ne).message)}finally{h(!1)}}function U(ne){B(ne),Y(ne.name),y("")}async function O(ne){if(ne.preventDefault(),!R)return;const xe=F.trim();if(!xe||xe===R.name){B(null);return}h(!0),y("");try{await PM(R.id,xe),await ve(),B(null)}catch(oe){y(dt(oe).message)}finally{h(!1)}}async function Q(){if(te){h(!0),y("");try{const ne=await YM(te.id);n(ne),_(null),await e()}catch(ne){const xe=dt(ne);y(xe.detail??xe.message)}finally{h(!1)}}}async function z(){if(K){h(!0),y("");try{await VM(K.id),await ve(),le(null)}catch(ne){y(dt(ne).detail??dt(ne).message)}finally{h(!1)}}}const de=(t==null?void 0:t.accounts)??[];return u.jsxs("section",{className:"settings-section codex-accounts-section",children:[u.jsxs("header",{className:"settings-section-header",children:[u.jsxs("div",{children:[u.jsx("h3",{children:"Codex Accounts"}),u.jsx("p",{children:"Manage the cloud-owned Codex logins. Every deployment uses the same globally active account; workspaces do not bind to accounts."})]}),u.jsxs("div",{className:"codex-account-toolbar",children:[u.jsx("button",{className:"codex-account-add",disabled:f||o||de.length===0,onClick:()=>void ee(!0),type:"button",children:o?"Refreshing...":"Refresh details"}),u.jsx("button",{className:"codex-account-add",disabled:f||o||(E==null?void 0:E.status)==="pending",onClick:pe,type:"button",children:"Add account"})]})]}),u.jsxs("div",{className:"codex-account-policy",children:[u.jsx("strong",{children:"Cloud-wide active account"}),u.jsx("span",{children:"Switching requires the cloud runtime to be idle. The cloud publishes the selected credential; members pause new work and apply it after any active turn finishes. There is no per-deployment selection."})]}),m?u.jsx("p",{className:"memory-editor-error",children:m}):null,i?u.jsx("p",{className:"settings-note",children:"Loading Codex accounts..."}):null,!i&&de.length===0?u.jsx("p",{className:"settings-note",children:"No persisted Codex account. Add one with the official device login flow."}):null,u.jsx("div",{className:"codex-account-list",children:de.map(ne=>{var Je,ut;const xe=(t==null?void 0:t.activeAccountId)===ne.id,oe=(Je=t==null?void 0:t.accountDetails)==null?void 0:Je[ne.id],Oe=((ut=t==null?void 0:t.accountIssues)==null?void 0:ut[ne.id])??[],st=Oe.length>0,Ct=Oe.some(At=>["missing_credential","invalid_credential","credential_unreadable"].includes(At.code)),lt=[ne.email,FE(ne.accountType),$E(ne.planType)].filter(At=>!!At);return u.jsxs("article",{className:`codex-account-card${xe?" active":""}${st?" issue":""}`,children:[u.jsxs("div",{className:"codex-account-main",children:[u.jsxs("div",{className:"codex-account-title",children:[u.jsx("strong",{children:ne.name}),xe?u.jsx("span",{className:"codex-account-active",children:"Active"}):null,st?u.jsx("span",{className:"codex-account-warning",children:"Needs attention"}):null]}),u.jsx("small",{children:lt.join(" · ")||`Added ${rt(ne.createdAt)}`}),st?u.jsx("div",{className:"codex-account-issues",role:"status",children:Oe.map(At=>u.jsx("span",{children:At.message},At.code))}):null,oe!=null&&oe.usage?u.jsx(HE,{usage:oe.usage}):u.jsx("span",{className:"codex-account-usage-empty",children:o?"Reading account usage...":"Usage unavailable"}),oe?u.jsx("small",{className:oe.error?"codex-account-detail-error":"codex-account-refreshed",children:oe.error?`Refresh issue: ${oe.error}`:`Updated ${rt(oe.refreshedAt)}`}):null]}),u.jsxs("div",{className:"codex-account-actions",children:[u.jsx("button",{disabled:f||o||Ct,onClick:()=>U(ne),title:Ct?"Sign in again or delete this account to replace its credential.":void 0,type:"button",children:st?"Repair & rename":"Rename"}),u.jsx("button",{disabled:f||o||xe||st,onClick:()=>{y(""),_(ne)},type:"button",children:xe?"In use":st?"Unavailable":"Switch"}),u.jsx("button",{className:"danger",disabled:f||o||xe,onClick:()=>{y(""),le(ne)},type:"button",children:"Delete"})]})]},ne.id)})}),!i&&de.length>0?u.jsxs("section",{className:"codex-reset-credits","aria-label":"Rate-limit reset credits",children:[u.jsx("h4",{children:"Rate-limit reset credits"}),ce?u.jsx("p",{className:"settings-note",role:"status",children:ce}):null,de.map(ne=>{var Oe,st,Ct;const xe=(Oe=t==null?void 0:t.accountDetails)==null?void 0:Oe[ne.id],oe=xe==null?void 0:xe.rateLimitResetCredits;return u.jsx("article",{className:"codex-account-card",children:u.jsxs("div",{className:"codex-account-main",children:[u.jsxs("div",{className:"codex-account-title",children:[u.jsx("strong",{children:ne.name}),u.jsx("span",{children:oe?`${oe.availableCount} available`:"Unavailable"})]}),oe?null:u.jsx("small",{children:o?"Reading reset credits...":"Reset credit information was not returned. Refresh details to try again."}),(st=oe==null?void 0:oe.credits)==null?void 0:st.map(lt=>{var Je,ut;return u.jsxs("div",{className:"codex-reset-credit",children:[u.jsxs("div",{className:"codex-account-title",children:[u.jsx("strong",{children:lt.title||"Rate-limit reset"}),u.jsx("button",{className:"codex-account-add",type:"button",disabled:f||o||lt.status!=="available"||lt.resetType!=="codexRateLimits"||lt.expiresAt!==null&&lt.expiresAt*1e3<=Date.now()||!!((ut=(Je=t==null?void 0:t.accountIssues)==null?void 0:Je[ne.id])!=null&&ut.length),onClick:()=>void Ce(ne,lt),children:f?"Please wait...":"Use"})]}),lt.description?u.jsx("span",{children:lt.description}):null,u.jsxs("small",{children:[lt.status," · Granted ",rt(new Date(lt.grantedAt*1e3).toISOString()),lt.expiresAt===null?" · No expiry":` · Expires ${rt(new Date(lt.expiresAt*1e3).toISOString())}`]})]},lt.id)}),oe&&oe.availableCount>(((Ct=oe.credits)==null?void 0:Ct.length)??0)?u.jsx("small",{children:oe.credits==null?"Only the available count was returned.":`Showing ${oe.credits.length} credit details; the available count includes all credits.`}):null,xe?u.jsx("small",{children:xe.error?`Refresh issue: ${xe.error}`:`Updated ${rt(xe.refreshedAt)}`}):null]})},ne.id)})]}):null,R?u.jsx("div",{className:"memory-editor-overlay",onClick:()=>!f&&B(null),role:"presentation",children:u.jsxs("form",{"aria-label":"Rename Codex account",className:"memory-editor-popover codex-account-login-dialog",onClick:ne=>ne.stopPropagation(),onSubmit:ne=>void O(ne),children:[u.jsxs("header",{children:[u.jsx("strong",{children:"Rename Codex Account"}),u.jsx("button",{"aria-label":"Close account rename",className:"memory-icon-button",disabled:f,onClick:()=>B(null),type:"button",children:"×"})]}),u.jsx("p",{className:"settings-note",children:"This name is only a Seele label. It does not change the Codex login or credential."}),u.jsxs("label",{children:[u.jsx("span",{children:"Account name"}),u.jsx("input",{"aria-label":"Codex account name",autoFocus:!0,maxLength:80,onChange:ne=>Y(ne.target.value),value:F})]}),m?u.jsx("p",{className:"memory-editor-error",children:m}):null,u.jsxs("div",{className:"memory-editor-actions",children:[u.jsx("button",{className:"memory-dialog-button",disabled:f,onClick:()=>B(null),type:"button",children:"Cancel"}),u.jsx("button",{className:"memory-dialog-button primary",disabled:f||!F.trim(),type:"submit",children:f?"Saving...":"Save"})]})]})}):null,v?u.jsx("div",{className:"memory-editor-overlay",onClick:()=>!f&&!E&&k(!1),role:"presentation",children:E?u.jsxs("section",{"aria-label":"Complete Codex account login",className:"memory-delete-dialog codex-account-login-dialog",onClick:ne=>ne.stopPropagation(),children:[u.jsxs("header",{children:[u.jsx("strong",{children:E.status==="succeeded"?"Account Added":"Complete Codex Login"}),u.jsx("button",{"aria-label":"Close account login",className:"memory-icon-button",disabled:f,onClick:()=>void Ye(),type:"button",children:"×"})]}),E.status==="pending"?u.jsxs(u.Fragment,{children:[u.jsx("p",{children:"Open the official Codex device page and enter this one-time code."}),u.jsxs("div",{className:"codex-device-code",children:[u.jsx("strong",{children:E.userCode}),u.jsx("button",{onClick:()=>{navigator.clipboard.writeText(E.userCode),G(!0),window.setTimeout(()=>G(!1),1500)},type:"button",children:J?"Copied":"Copy code"})]}),u.jsx("a",{href:E.verificationUrl,rel:"noreferrer",target:"_blank",children:"Open Codex device login"}),u.jsx("small",{className:"codex-login-waiting",children:"Waiting for Codex to confirm the login..."})]}):E.status==="succeeded"?u.jsxs("p",{children:[u.jsx("strong",{children:((Re=E.account)==null?void 0:Re.name)??E.accountName})," is persisted on the cloud and ready to synchronize. It was not activated automatically."]}):u.jsx("p",{className:"memory-editor-error",children:E.error??"Codex login was cancelled."}),u.jsx("div",{className:"memory-delete-actions",children:u.jsx("button",{className:"memory-dialog-button",disabled:f,onClick:()=>void Ye(),type:"button",children:E.status==="pending"?"Cancel login":"Close"})})]}):u.jsxs("form",{"aria-label":"Add Codex account",className:"memory-editor-popover codex-account-login-dialog",onClick:ne=>ne.stopPropagation(),onSubmit:ne=>void De(ne),children:[u.jsxs("header",{children:[u.jsx("strong",{children:"Add Codex Account"}),u.jsx("button",{"aria-label":"Close account login",className:"memory-icon-button",onClick:()=>k(!1),type:"button",children:"×"})]}),u.jsx("p",{className:"settings-note",children:"Seele creates the login profile on the cloud. Completing login shares it with every deployment but does not make it active."}),u.jsxs("label",{children:[u.jsx("span",{children:"Account name"}),u.jsx("input",{autoFocus:!0,maxLength:80,onChange:ne=>T(ne.target.value),placeholder:"For example: Codex backup",value:w})]}),m?u.jsx("p",{className:"memory-editor-error",children:m}):null,u.jsxs("div",{className:"memory-editor-actions",children:[u.jsx("button",{className:"memory-dialog-button",onClick:()=>k(!1),type:"button",children:"Cancel"}),u.jsx("button",{className:"memory-dialog-button primary",disabled:f||!w.trim(),type:"submit",children:f?"Starting...":"Continue"})]})]})}):null,te?u.jsx("div",{className:"memory-editor-overlay",onClick:()=>!f&&_(null),role:"presentation",children:u.jsxs("section",{"aria-label":"Switch Codex account",className:"memory-delete-dialog",onClick:ne=>ne.stopPropagation(),children:[u.jsxs("header",{children:[u.jsx("strong",{children:"Switch Codex Account"}),u.jsx("button",{"aria-label":"Close account switch",className:"memory-icon-button",disabled:f,onClick:()=>_(null),type:"button",children:"×"})]}),u.jsxs("p",{children:["Switch cloud-wide execution to ",u.jsx("strong",{children:te.name}),"? Active turns continue with the account they started with. New requests use this account after the switch; workspace threads and memory stay unchanged."]}),m?u.jsx("p",{className:"memory-editor-error",children:m}):null,u.jsxs("div",{className:"memory-delete-actions",children:[u.jsx("button",{className:"memory-dialog-button",disabled:f,onClick:()=>_(null),type:"button",children:"Cancel"}),u.jsx("button",{className:"memory-dialog-button primary",disabled:f,onClick:()=>void Q(),type:"button",children:f?"Switching...":"Switch account"})]})]})}):null,K?u.jsx("div",{className:"memory-editor-overlay",onClick:()=>!f&&le(null),role:"presentation",children:u.jsxs("section",{"aria-label":"Delete Codex account",className:"memory-delete-dialog",onClick:ne=>ne.stopPropagation(),children:[u.jsxs("header",{children:[u.jsx("strong",{children:"Delete Codex Account"}),u.jsx("button",{"aria-label":"Close account deletion",className:"memory-icon-button",disabled:f,onClick:()=>le(null),type:"button",children:"×"})]}),u.jsxs("p",{children:["Delete ",u.jsx("strong",{children:K.name})," and its persisted Codex credential from the cloud and every member mirror? This cannot be undone."]}),m?u.jsx("p",{className:"memory-editor-error",children:m}):null,u.jsxs("div",{className:"memory-delete-actions",children:[u.jsx("button",{className:"memory-dialog-button",disabled:f,onClick:()=>le(null),type:"button",children:"Cancel"}),u.jsx("button",{className:"memory-dialog-button danger",disabled:f,onClick:()=>void z(),type:"button",children:f?"Deleting...":"Delete"})]})]})}):null]})}function PE({currentUser:e,users:t,onCreate:n,onDelete:i,onUpdate:l}){const o={username:"",password:"",role:"user",active:!0},[c,f]=I.useState(null),[h,m]=I.useState(o),[y,v]=I.useState(!1),[k,w]=I.useState(null),[T,E]=I.useState("");function q(){m(o),E(""),f("new")}function R(Y){m({username:Y.username,password:"",role:Y.role,active:Y.active}),E(""),f(Y)}function B(){y||(f(null),E(""))}async function F(Y){if(Y.preventDefault(),!!c){v(!0),E("");try{c==="new"?await n({username:h.username.trim(),password:h.password,role:h.role}):await l(c.id,{username:h.username.trim(),password:h.password||void 0,role:h.role,active:h.active}),f(null)}catch(te){E(dt(te).message)}finally{v(!1)}}}return u.jsxs("section",{className:"settings-section user-management-section",children:[u.jsx("header",{className:"settings-section-header",children:u.jsxs("div",{children:[u.jsx("h3",{children:"Users"}),u.jsx("p",{children:"Manage sign-in access and Seele roles."})]})}),u.jsx("div",{className:"memory-items-editor-header actions-only",children:u.jsx("button",{"aria-label":"Add user",className:"memory-icon-button",onClick:q,title:"Add user",type:"button",children:"+"})}),u.jsxs("div",{className:"user-list",children:[t.map(Y=>u.jsxs("div",{className:"user-list-item",children:[u.jsxs("div",{className:"user-list-main",children:[u.jsxs("div",{children:[u.jsx("strong",{children:Y.username}),Y.id===e.id?u.jsx("span",{className:"user-current-badge",children:"Current"}):null]}),u.jsxs("small",{children:["Created ",rt(Y.createdAt)]})]}),u.jsx("span",{className:`user-role-badge role-${Y.role}`,children:Y.role}),u.jsx("span",{className:`user-status ${Y.active?"active":"disabled"}`,children:Y.active?"Active":"Disabled"}),u.jsxs("div",{className:"user-row-actions",children:[u.jsx("button",{"aria-label":`Edit user ${Y.username}`,className:"memory-icon-button",onClick:()=>R(Y),title:"Edit",type:"button",children:u.jsx(Ef,{})}),u.jsx("button",{"aria-label":`Delete user ${Y.username}`,className:"memory-icon-button memory-item-delete",disabled:Y.id===e.id,onClick:()=>{E(""),w(Y)},title:"Delete",type:"button",children:"×"})]})]},Y.id)),t.length===0?u.jsx("p",{className:"settings-note",children:"No users are configured."}):null]}),c?u.jsx("div",{className:"memory-editor-overlay",onClick:B,role:"presentation",children:u.jsxs("form",{"aria-label":c==="new"?"Add user":"Edit user",className:"memory-editor-popover user-editor-popover",onClick:Y=>Y.stopPropagation(),onSubmit:Y=>void F(Y),children:[u.jsxs("header",{children:[u.jsx("strong",{children:c==="new"?"Add User":"Edit User"}),u.jsx("button",{"aria-label":"Close user editor",className:"memory-icon-button",onClick:B,title:"Close",type:"button",children:"×"})]}),u.jsxs("label",{children:[u.jsx("span",{children:"Username"}),u.jsx("input",{autoComplete:"off",autoFocus:!0,onChange:Y=>m(te=>({...te,username:Y.target.value})),placeholder:"Sign-in username",value:h.username})]}),u.jsxs("label",{children:[u.jsx("span",{children:c==="new"?"Initial password":"New password"}),u.jsx("input",{autoComplete:"new-password",minLength:8,onChange:Y=>m(te=>({...te,password:Y.target.value})),placeholder:c==="new"?"At least 8 characters":"Leave blank to keep the current password",type:"password",value:h.password})]}),u.jsxs("label",{children:[u.jsx("span",{children:"Role"}),u.jsxs("select",{disabled:c!=="new"&&c.id===e.id,onChange:Y=>m(te=>({...te,role:Y.target.value==="admin"?"admin":"user"})),value:h.role,children:[u.jsx("option",{value:"user",children:"User"}),u.jsx("option",{value:"admin",children:"Admin"})]})]}),c!=="new"?u.jsxs("label",{className:"user-editor-active",children:[u.jsx("input",{checked:h.active,disabled:c.id===e.id,onChange:Y=>m(te=>({...te,active:Y.target.checked})),type:"checkbox"}),u.jsx("span",{children:"Account active"})]}):null,T?u.jsx("p",{className:"memory-editor-error",children:T}):null,u.jsxs("div",{className:"memory-editor-actions",children:[u.jsx("button",{className:"memory-dialog-button",onClick:B,type:"button",children:"Cancel"}),u.jsx("button",{className:"memory-dialog-button primary",disabled:y||!h.username.trim()||c==="new"&&h.password.length<8||c!=="new"&&h.password.length>0&&h.password.length<8,type:"submit",children:y?"Saving...":"Save"})]})]})}):null,k?u.jsx("div",{className:"memory-editor-overlay",onClick:()=>w(null),role:"presentation",children:u.jsxs("section",{"aria-label":"Delete user",className:"memory-delete-dialog",onClick:Y=>Y.stopPropagation(),children:[u.jsxs("header",{children:[u.jsx("strong",{children:"Delete User"}),u.jsx("button",{"aria-label":"Close delete user confirmation",className:"memory-icon-button",onClick:()=>w(null),title:"Close",type:"button",children:"×"})]}),u.jsxs("p",{children:["Delete ",u.jsx("strong",{children:k.username}),". Users that own workspaces must be disabled instead."]}),T?u.jsx("p",{className:"memory-editor-error",children:T}):null,u.jsxs("div",{className:"memory-delete-actions",children:[u.jsx("button",{className:"memory-dialog-button",onClick:()=>w(null),type:"button",children:"Cancel"}),u.jsx("button",{className:"memory-dialog-button danger",onClick:()=>{i(k.id).then(()=>w(null)).catch(Y=>E(dt(Y).message))},type:"button",children:"Delete"})]})]})}):null]})}function VE({settings:e,onSave:t}){const[n,i]=I.useState(e),[l,o]=I.useState(!1);return I.useEffect(()=>i(e),[e]),u.jsxs(u.Fragment,{children:[u.jsx("header",{className:"settings-section-header",children:u.jsxs("div",{children:[u.jsx("h3",{children:"Deployment"}),u.jsx("p",{children:"Settings stored only on this Seele instance. Cloud synchronization does not copy or overwrite them."})]})}),u.jsxs("form",{className:"settings-form",onSubmit:c=>{c.preventDefault(),o(!0),t(n).finally(()=>o(!1))},children:[u.jsxs("label",{className:"settings-field settings-field-wide",children:[u.jsxs("span",{children:[u.jsx("strong",{children:"Public URL"}),u.jsx("small",{children:"The externally reachable main URL of this deployment. Seele uses it when publishing callback links to external systems."})]}),u.jsx("input",{"aria-label":"Public URL of this deployment",onChange:c=>i({...n,publicUrl:c.target.value||null}),placeholder:"https://profuse.antgroup-inc.cn/codex/yishao-0/",type:"url",value:n.publicUrl||""})]}),u.jsxs("label",{className:"settings-toggle-field",children:[u.jsxs("span",{children:[u.jsx("strong",{children:"Profuse notification"}),u.jsx("small",{children:"Send DingTalk notifications from this deployment when a turn finishes or fails. Keep this off where the Profuse endpoint is unreachable."})]}),u.jsx("input",{"aria-label":"Enable Profuse notification on this deployment",checked:n.profuseNotificationEnabled,onChange:c=>i({...n,profuseNotificationEnabled:c.target.checked}),type:"checkbox"})]}),u.jsx("div",{className:"settings-form-actions",children:u.jsx("button",{disabled:l,type:"submit",children:l?"Saving...":"Save deployment settings"})})]})]})}function YE({codexReleasedAt:e,codexVersion:t,codexUpdating:n,draft:i,globalSettings:l,models:o,scope:c,settings:f,workspaceOverrideCount:h,workspaceSettings:m,onDraftChange:y,onResetWorkspaceSetting:v,onSubmit:k,onUpdateCodexCli:w}){var Y;const T=c==="workspace",E=Nc(i.model,o),q=Nc(l.model,o),R=Nc(f.model,o),B=D3(i.reasoningEffort,E),F=OA(E,i.reasoningEffort);return I.useEffect(()=>{E&&B!==i.reasoningEffort&&y({...i,reasoningEffort:B})},[i,E,B,y]),u.jsxs(u.Fragment,{children:[u.jsxs("header",{className:"settings-section-header",children:[u.jsxs("div",{children:[u.jsx("h3",{children:"Runtime"}),u.jsx("p",{children:"Configure global defaults or override them for the selected workspace. Running turns keep the settings they started with."})]}),T?u.jsx("span",{className:h>0?"section-override-count active":"section-override-count",children:h>0?`${h} custom`:"No custom runtime"}):null]}),u.jsxs("form",{className:"settings-form runtime-form",onSubmit:k,children:[u.jsxs("div",{className:_d(T,Hl(i.model,l.model,m==null?void 0:m.sources.model)),children:[u.jsx(Od,{globalValue:b5(l.model,o),isWorkspaceScope:T,label:"Model",settingKey:"model",source:Hl(i.model,l.model,m==null?void 0:m.sources.model),onReset:v}),u.jsx(Qm,{"aria-label":"Runtime model",onChange:te=>{const _=Nc(te,o);y({...i,model:te,reasoningEffort:D3(i.reasoningEffort,_)})},options:iD(o,i.model),value:i.model||((Y=o.find(te=>te.isDefault))==null?void 0:Y.model)||""})]}),u.jsxs("div",{className:_d(T,Hl(i.reasoningEffort,l.reasoningEffort,m==null?void 0:m.sources.reasoningEffort)),children:[u.jsx(Od,{globalValue:z3(l.reasoningEffort,q),isWorkspaceScope:T,label:"Reasoning effort",settingKey:"reasoningEffort",source:Hl(i.reasoningEffort,l.reasoningEffort,m==null?void 0:m.sources.reasoningEffort),onReset:v}),u.jsx(Qm,{"aria-label":"Runtime reasoning effort",onChange:te=>y({...i,reasoningEffort:te}),options:F,value:B})]}),u.jsxs("div",{className:_d(T,Hl(i.sandbox,l.sandbox,m==null?void 0:m.sources.sandbox)),children:[u.jsx(Od,{globalValue:S5(l.sandbox),isWorkspaceScope:T,label:"Permission mode",settingKey:"sandbox",source:Hl(i.sandbox,l.sandbox,m==null?void 0:m.sources.sandbox),onReset:v}),u.jsx(Qm,{"aria-label":"Permission mode",onChange:te=>y({...i,sandbox:te}),options:cE,value:i.sandbox})]}),u.jsxs("div",{className:_d(T,Hl(i.fastMode,l.fastMode,m==null?void 0:m.sources.fastMode),"settings-toggle-field"),children:[u.jsxs("span",{children:[u.jsx(Od,{globalValue:l.fastMode?"On":"Off",isWorkspaceScope:T,label:"Fast mode",settingKey:"fastMode",source:Hl(i.fastMode,l.fastMode,m==null?void 0:m.sources.fastMode),onReset:v}),u.jsx("small",{children:"1.5x speed with higher Codex credit consumption"})]}),u.jsx("input",{"aria-label":"Enable Fast mode",checked:i.fastMode,onChange:te=>y({...i,fastMode:te.target.checked}),type:"checkbox"})]}),u.jsxs("dl",{className:"runtime-summary",children:[u.jsxs("div",{children:[u.jsx("dt",{children:"Current"}),u.jsxs("dd",{children:["Model ",b5(f.model,o),", reasoning"," ",z3(f.reasoningEffort,R),", Fast mode"," ",f.fastMode?"on":"off",", permission"," ",S5(f.sandbox),"."]})]}),u.jsxs("div",{children:[u.jsx("dt",{children:"Codex CLI"}),u.jsxs("dd",{className:"runtime-version-value",children:[u.jsx("span",{children:Zp(t,e)}),u.jsx("button",{className:"runtime-update-button",disabled:n,onClick:w,type:"button",children:n?"Updating...":"Check update"})]})]})]}),u.jsx("div",{className:"settings-form-actions",children:u.jsx("button",{type:"submit",children:T?"Save workspace overrides":"Save global runtime"})})]})]})}function Od({globalValue:e,isWorkspaceScope:t,label:n,settingKey:i,source:l,onReset:o}){const c=t&&l==="workspace";return u.jsxs("span",{className:"runtime-field-label",children:[u.jsx("span",{children:n}),t?u.jsxs("span",{className:"runtime-field-meta",children:[u.jsx("span",{className:c?"override":"inherited",children:c?"Workspace override":`Inherited: ${e}`}),c?u.jsx("button",{type:"button",onClick:()=>o(i),children:"Reset"}):null]}):null]})}function Qm({"aria-label":e,onChange:t,options:n,value:i}){const[l,o]=I.useState(!1),c=I.useRef(null),f=n.find(h=>h.value===i)??n[0]??null;return I.useEffect(()=>{if(!l)return;function h(y){var v;(v=c.current)!=null&&v.contains(y.target)||o(!1)}function m(y){y.key==="Escape"&&o(!1)}return document.addEventListener("pointerdown",h,!0),document.addEventListener("keydown",m,!0),()=>{document.removeEventListener("pointerdown",h,!0),document.removeEventListener("keydown",m,!0)}},[l]),u.jsxs("div",{className:"runtime-select",ref:c,children:[u.jsxs("button",{"aria-expanded":l,"aria-label":e,className:"runtime-select-trigger",onClick:()=>o(h=>!h),type:"button",children:[u.jsx("span",{children:(f==null?void 0:f.label)??i}),u.jsx("span",{"aria-hidden":"true",children:"⌄"})]}),l?u.jsx("div",{className:"runtime-select-menu",role:"listbox",children:n.map(h=>u.jsx("button",{"aria-selected":h.value===i,className:h.value===i?"selected":void 0,onClick:()=>{t(h.value),o(!1)},role:"option",type:"button",children:h.label},h.value||"default"))}):null]})}function Hl(e,t,n){return e!==t?"workspace":n}function _d(e,t,n="settings-wide-field"){return[n,e?"workspace-scoped":"",e&&t==="workspace"?"workspace-overridden":""].filter(Boolean).join(" ")}function WE({baseSettings:e,scope:t,workspaceSettings:n,workspaceName:i,onSaveBaseItems:l,onSaveWorkspaceItems:o}){const c=t==="workspace",f=c?n.items:e.items,h=c?o:l;return u.jsxs(u.Fragment,{children:[u.jsx("header",{className:"settings-section-header",children:u.jsxs("div",{children:[u.jsx("h3",{children:c?"Workspace Memory":"Base Memory"}),u.jsx("p",{children:c?"Workspace memory applies only to the selected workspace. Use stable English keys; values may be Chinese, plain text, or Markdown.":"Base memory applies to every workspace. Use stable English keys; values may be Chinese, plain text, or Markdown."})]})}),c?u.jsxs("section",{className:"settings-readonly-block",children:[u.jsxs("div",{children:[u.jsx("strong",{children:"Base Memory"}),u.jsx("span",{children:"Read-only in workspace scope"})]}),u.jsx(KE,{emptyText:"No base memory is configured.",items:e.items,readonly:!0})]}):null,u.jsx("div",{className:"memory-manager-shell",children:u.jsx(XE,{ariaLabel:c?"Workspace memory":"Base memory",emptyText:"No memory items are configured.",items:f,onSaveItems:h,title:""})})]})}function XE({ariaLabel:e,emptyText:t,items:n,onSaveItems:i,title:l}){var K;const[o,c]=I.useState(Ic(n)),[f,h]=I.useState(null),[m,y]=I.useState({key:"",value:""}),[v,k]=I.useState(null),[w,T]=I.useState(null),[E,q]=I.useState(null);I.useEffect(()=>{c(Ic(n))},[n]),I.useEffect(()=>{if(f===null)return;const le=J=>{J.key==="Escape"&&(Y(),T(null))};return document.addEventListener("keydown",le),()=>document.removeEventListener("keydown",le)},[f]);async function R(le,J){q(J);try{const G=await i(le);return c(Ic(G)),G}finally{q(null)}}function B(){T(null),k(null),y({key:"",value:""}),h("new")}function F(le){const J=o[le];J&&(T(null),k(null),y({...J}),h(le))}function Y(){h(null),k(null),y({key:"",value:""})}async function te(le){const J=o[le],G=(J==null?void 0:J.key)||`${le}`;await R(o.filter((ce,fe)=>fe!==le),`delete:${G}`),T(null)}async function _(le){le.preventDefault(),le.stopPropagation();const J=m.key.trim(),G=dz(J);if(G){k(G);return}const ce=m.value.trim();if(!ce){k("Value is required.");return}const fe=f==="new"?-1:f;if(o.some((Ce,ve)=>ve!==fe&&Ce.key.trim()===J)){k(`Key "${J}" already exists. Each memory key must be unique.`);return}const Be={...m,key:J,value:ce};f==="new"?await R([...o,Be],"add"):typeof f=="number"&&await R(o.map((Ce,ve)=>ve===f?Be:Ce),`save:${f}`),Y()}return u.jsxs("section",{className:"memory-items-manager","aria-label":e,children:[u.jsxs("div",{className:l?"memory-items-editor-header":"memory-items-editor-header actions-only",children:[l?u.jsx("span",{children:l}):null,u.jsx("button",{"aria-label":"Add memory item",className:"memory-icon-button",title:"Add",type:"button",onClick:B,children:"+"})]}),o.length?u.jsx("div",{className:"memory-items-grid",children:o.map((le,J)=>u.jsxs("div",{className:"memory-item-display",children:[u.jsxs("pre",{"aria-label":`Memory item ${le.key}`,children:[u.jsx("span",{className:"memory-tag",children:`<${le.key}>`}),`
361
+ `),R=`[System Log] ${w.summary}`.slice(0,180),B=new URL("https://github.com/seele-labs/seele-work/issues/new");B.searchParams.set("title",R),B.searchParams.set("body",q),window.open(B.toString(),"_blank","noopener,noreferrer")};return u.jsxs("section",{className:"system-information-section",children:[u.jsxs("header",{className:"settings-section-header",children:[u.jsxs("div",{children:[u.jsx("h3",{children:"System"}),u.jsx("p",{children:"Read-only runtime and resource information managed by Seele."})]}),u.jsx("button",{className:"system-information-refresh",disabled:n,onClick:i,type:"button",children:n?"Refreshing...":"Refresh"})]}),l?u.jsxs(u.Fragment,{children:[u.jsxs("dl",{className:"system-information-summary",children:[u.jsxs("div",{children:[u.jsx("dt",{children:"LRU pool target"}),u.jsxs("dd",{children:[wr(l.maxRetainedRuntimes)," runtimes"]}),u.jsx("small",{children:l.capacitySource==="system_memory"?"Idle runtimes are released by least recent use":"Fallback target because system memory was unavailable"})]}),u.jsxs("div",{children:[u.jsx("dt",{children:"Retention policy"}),u.jsxs("dd",{children:["LRU · ",op(l.maxIdleSeconds*1e3)," max idle"]}),u.jsx("small",{children:"Only idle runtimes are eligible for eviction"})]}),u.jsxs("div",{children:[u.jsx("dt",{children:"Current pool"}),u.jsxs("dd",{children:[l.activeRuntimeCount," active · ",l.idleRuntimeCount," idle"]}),u.jsxs("small",{children:[l.retainedRuntimeCount," retained runtimes"]})]})]}),u.jsxs("section",{className:"system-runtime-list",children:[u.jsxs("header",{children:[u.jsxs("div",{children:[u.jsx("h4",{children:"Workspace runtimes"}),u.jsx("p",{children:"Active workspaces and idle runtimes currently retained for reuse."})]}),u.jsx("time",{dateTime:t==null?void 0:t.generatedAt,children:t?rt(t.generatedAt):""})]}),l.workspaces.length>0?u.jsxs("div",{className:"system-runtime-table",children:[u.jsxs("div",{className:"system-runtime-table-header",children:[u.jsx("span",{children:"Workspace"}),u.jsx("span",{children:"Status"}),u.jsx("span",{children:"Runtime"}),u.jsx("span",{children:"Age"})]}),l.workspaces.map(w=>u.jsxs("div",{className:"system-runtime-row",children:[u.jsxs("div",{children:[u.jsx("strong",{children:h.get(w.workspaceId)??w.workspaceId}),u.jsx("small",{children:w.workspaceId})]}),u.jsx("span",{className:`system-runtime-state ${w.turnId?"active":"idle"}`,children:w.lifecycle==="shutting_down"?"Shutting down":w.turnId?"Active":"Idle"}),u.jsxs("div",{children:[u.jsx("span",{children:w.turnId?w.state:"Retained"}),u.jsx("small",{children:w.pid===null?"PID unavailable":`PID ${w.pid}`})]}),u.jsx("span",{children:w.idleMs===null?op(w.uptimeMs):`${op(w.idleMs)} idle`})]},w.workspaceId))]}):u.jsx("div",{className:"system-runtime-empty",children:"No workspace runtimes are currently retained."})]}),u.jsxs("section",{className:"system-runtime-list system-log-list",children:[u.jsxs("header",{children:[u.jsxs("div",{children:[u.jsx("h4",{children:"System log"}),u.jsx("p",{children:"Recent persistent warnings and errors for external diagnostics."})]}),u.jsxs("div",{className:"system-log-actions",children:[u.jsx("button",{"aria-label":"Copy system log report",className:"icon-button",disabled:!o.length,onClick:()=>void y(),title:"Copy system log report",type:"button",children:u.jsx(P1,{})}),u.jsx("button",{"aria-label":"Download system log report",className:"icon-button",disabled:!o.length,onClick:v,title:"Download system log report",type:"button",children:u.jsx(qE,{})}),u.jsx("button",{"aria-label":"Report system log issue",className:"icon-button",disabled:!o.length,onClick:k,title:"Report issue to seele-labs/seele-work",type:"button",children:u.jsx(UE,{})}),c?u.jsx("small",{children:"Copied"}):null]})]}),o.length?u.jsx("div",{className:"system-log-entries",children:o.map(w=>u.jsxs("details",{className:`system-log-entry ${w.level}`,children:[u.jsxs("summary",{children:[u.jsx("span",{className:"system-log-level",children:w.level}),u.jsxs("span",{children:[u.jsx("strong",{children:w.summary}),u.jsxs("small",{children:[w.component," · ",Lc(w.createdAt)]})]})]}),u.jsxs("dl",{children:[u.jsxs("div",{children:[u.jsx("dt",{children:"Event"}),u.jsx("dd",{children:w.event})]}),w.workspaceId?u.jsxs("div",{children:[u.jsx("dt",{children:"Workspace"}),u.jsxs("dd",{children:[h.get(w.workspaceId)??w.workspaceId," · ",w.workspaceId]})]}):null,w.turnId?u.jsxs("div",{children:[u.jsx("dt",{children:"Turn"}),u.jsx("dd",{children:w.turnId})]}):null,w.runtimeId?u.jsxs("div",{children:[u.jsx("dt",{children:"Runtime"}),u.jsx("dd",{children:w.runtimeId})]}):null]}),u.jsx("pre",{children:JSON.stringify(w.detail,null,2)})]},w.id))}):u.jsx("div",{className:"system-runtime-empty",children:"No warnings or errors have been recorded."})]})]}):u.jsx("div",{className:"system-runtime-empty",children:n?"Loading system information...":"System information is unavailable."})]})}function qE(){return u.jsx("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",children:u.jsx("path",{d:"M12 3v12m0 0 4-4m-4 4-4-4M5 20h14"})})}function UE(){return u.jsxs("svg",{"aria-hidden":"true",viewBox:"0 0 24 24",children:[u.jsx("circle",{cx:"12",cy:"12",r:"9"}),u.jsx("path",{d:"M12 7v6m0 4h.01"})]})}function HE({draft:e,saving:t,scope:n,workspace:i,onDraftChange:l,onSubmit:o}){const c=n==="workspace";return u.jsxs(u.Fragment,{children:[u.jsx("header",{className:"settings-section-header",children:u.jsxs("div",{children:[u.jsx("h3",{children:"Responsibility"}),u.jsx("p",{children:"Workspace-specific long-lived role. This is content context, so it is only editable in workspace scope."})]})}),c&&i?u.jsxs("form",{className:"settings-responsibility-form",onSubmit:o,children:[u.jsxs("label",{children:[u.jsx("span",{children:i.title}),u.jsx("textarea",{"aria-label":"Workspace responsibility",onChange:f=>l(f.target.value),placeholder:"Describe this workspace's durable role, scope, and long-term responsibilities.",rows:14,value:e})]}),u.jsx("div",{className:"settings-form-actions",children:u.jsx("button",{disabled:t,type:"submit",children:t?"Saving...":"Save responsibility"})})]}):u.jsx("section",{className:"settings-readonly-block",children:u.jsxs("div",{children:[u.jsx("strong",{children:"Workspace-only setting"}),u.jsx("span",{children:"Switch the header scope to Workspace and choose a workspace to edit its responsibility."})]})})]})}function FE({usage:e}){return u.jsx("div",{"aria-label":"Codex account usage",className:"codex-account-usage",children:[...e.windows].sort((t,n)=>t.windowDurationMins-n.windowDurationMins).map(t=>{const n=Nf(t.usedPercent),i=u7(t.windowDurationMins);return u.jsxs("div",{className:"codex-account-usage-window",children:[u.jsxs("div",{children:[u.jsxs("span",{children:[i," used"]}),u.jsx("strong",{children:H7(n)})]}),u.jsx("span",{"aria-hidden":"true",className:"codex-account-usage-track",children:u.jsx("span",{style:{width:`${n}%`}})}),u.jsxs("small",{children:["Resets ",F7(t.resetsAt)]})]},`${t.windowDurationMins}:${t.resetsAt}`)})})}function $E(e){if(!e)return null;const t=e.toLowerCase();return t==="chatgpt"?"ChatGPT":t==="apikey"||t==="api_key"?"API key":e}function GE(e){return e?e.split(/[_-]/).filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" "):null}function PE({onSwitched:e}){var Re;const[t,n]=I.useState(null),[i,l]=I.useState(!0),[o,c]=I.useState(!1),[f,h]=I.useState(!1),[m,y]=I.useState(""),[v,k]=I.useState(!1),[w,T]=I.useState(""),[E,q]=I.useState(null),[R,B]=I.useState(null),[F,Y]=I.useState(""),[te,_]=I.useState(null),[K,le]=I.useState(null),[J,G]=I.useState(!1),[ce,fe]=I.useState(""),Be=I.useRef(new Map);async function Ce(ne,xe){if(f||o||!window.confirm(`Use one reset credit for ${ne.name}? This consumes the credit if an eligible rate-limit window is reset.`))return;const oe=JSON.stringify([ne.id,xe.id]),Oe=Be.current.get(oe)??crypto.randomUUID();Be.current.set(oe,Oe),h(!0),y(""),fe("");try{const st=Ne(`settings/runtime/accounts/${encodeURIComponent(ne.id)}/reset-credits/consume`),Ct=await fetch(st,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({creditId:xe.id,idempotencyKey:Oe})});await He(Ct,{method:"POST",url:st});const lt=await Ct.json(),ut={reset:"Reset credit used. Eligible rate limits have been reset.",alreadyRedeemed:"This reset was already completed.",nothingToReset:"No rate-limit window needs a reset. No credit was used.",noCredit:"No reset credit is available for this account."}[lt.outcome];if(!ut)throw new Error("Reset outcome is unknown. Refresh details before trying again.");(lt.outcome==="nothingToReset"||lt.outcome==="noCredit")&&Be.current.delete(oe),fe(`${ne.name}: ${ut}`),n(At=>{if(!At)return At;const jn={...At.accountDetails};return delete jn[ne.id],{...At,accountDetails:jn}});try{n(await lp(!0))}catch{y("The result above is confirmed, but refreshing details failed. Please refresh details.")}}catch(st){y(`${dt(st).message} The outcome may be unknown; retrying this credit on this page reuses the same request ID.`)}finally{h(!1)}}async function ve(){var xe;const ne=await f5();n(ne),((xe=ne.login)==null?void 0:xe.status)==="pending"&&(q(ne.login),k(!0))}async function ee(ne){c(!0),y("");try{n(await lp(ne))}catch(xe){y(dt(xe).message)}finally{c(!1)}}I.useEffect(()=>{let ne=!1;return f5().then(xe=>{var oe;ne||(n(xe),((oe=xe.login)==null?void 0:oe.status)==="pending"&&(q(xe.login),k(!0)),xe.accounts.length>0&&(c(!0),lp(!1).then(Oe=>{ne||n(Oe)}).catch(Oe=>{ne||y(dt(Oe).message)}).finally(()=>{ne||c(!1)})))}).catch(xe=>{ne||y(dt(xe).message)}).finally(()=>{ne||l(!1)}),()=>{ne=!0}},[]),I.useEffect(()=>{if(!E||E.status!=="pending")return;let ne=!1;const xe=window.setInterval(()=>{GM(E.id).then(async oe=>{ne||(q(oe),oe.status!=="pending"&&(window.clearInterval(xe),oe.status==="succeeded"&&n(Oe=>{if(!Oe||!oe.account)return Oe;const st=Oe.accounts.some(Ct=>{var lt;return Ct.id===((lt=oe.account)==null?void 0:lt.id)})?Oe.accounts.map(Ct=>{var lt;return Ct.id===((lt=oe.account)==null?void 0:lt.id)?oe.account:Ct}):[...Oe.accounts,oe.account];return{...Oe,accounts:st}})))}).catch(oe=>{ne||y(dt(oe).message)})},1e3);return()=>{ne=!0,window.clearInterval(xe)}},[E==null?void 0:E.id,E==null?void 0:E.status]);function pe(){T(""),q(null),y(""),G(!1),k(!0)}async function De(ne){ne.preventDefault(),h(!0),y("");try{q(await $M(w.trim()))}catch(xe){y(dt(xe).message)}finally{h(!1)}}async function Ye(){if(!E||E.status!=="pending"){k(!1);return}h(!0),y("");try{const ne=await PM(E.id);q(ne),k(!1)}catch(ne){y(dt(ne).message)}finally{h(!1)}}function U(ne){B(ne),Y(ne.name),y("")}async function O(ne){if(ne.preventDefault(),!R)return;const xe=F.trim();if(!xe||xe===R.name){B(null);return}h(!0),y("");try{await VM(R.id,xe),await ve(),B(null)}catch(oe){y(dt(oe).message)}finally{h(!1)}}async function Q(){if(te){h(!0),y("");try{const ne=await WM(te.id);n(ne),_(null),await e()}catch(ne){const xe=dt(ne);y(xe.detail??xe.message)}finally{h(!1)}}}async function z(){if(K){h(!0),y("");try{await YM(K.id),await ve(),le(null)}catch(ne){y(dt(ne).detail??dt(ne).message)}finally{h(!1)}}}const de=(t==null?void 0:t.accounts)??[];return u.jsxs("section",{className:"settings-section codex-accounts-section",children:[u.jsxs("header",{className:"settings-section-header",children:[u.jsxs("div",{children:[u.jsx("h3",{children:"Codex Accounts"}),u.jsx("p",{children:"Manage the cloud-owned Codex logins. Every deployment uses the same globally active account; workspaces do not bind to accounts."})]}),u.jsxs("div",{className:"codex-account-toolbar",children:[u.jsx("button",{className:"codex-account-add",disabled:f||o||de.length===0,onClick:()=>void ee(!0),type:"button",children:o?"Refreshing...":"Refresh details"}),u.jsx("button",{className:"codex-account-add",disabled:f||o||(E==null?void 0:E.status)==="pending",onClick:pe,type:"button",children:"Add account"})]})]}),u.jsxs("div",{className:"codex-account-policy",children:[u.jsx("strong",{children:"Cloud-wide active account"}),u.jsx("span",{children:"Switching requires the cloud runtime to be idle. The cloud publishes the selected credential; members pause new work and apply it after any active turn finishes. There is no per-deployment selection."})]}),m?u.jsx("p",{className:"memory-editor-error",children:m}):null,i?u.jsx("p",{className:"settings-note",children:"Loading Codex accounts..."}):null,!i&&de.length===0?u.jsx("p",{className:"settings-note",children:"No persisted Codex account. Add one with the official device login flow."}):null,u.jsx("div",{className:"codex-account-list",children:de.map(ne=>{var Je,ut;const xe=(t==null?void 0:t.activeAccountId)===ne.id,oe=(Je=t==null?void 0:t.accountDetails)==null?void 0:Je[ne.id],Oe=((ut=t==null?void 0:t.accountIssues)==null?void 0:ut[ne.id])??[],st=Oe.length>0,Ct=Oe.some(At=>["missing_credential","invalid_credential","credential_unreadable"].includes(At.code)),lt=[ne.email,$E(ne.accountType),GE(ne.planType)].filter(At=>!!At);return u.jsxs("article",{className:`codex-account-card${xe?" active":""}${st?" issue":""}`,children:[u.jsxs("div",{className:"codex-account-main",children:[u.jsxs("div",{className:"codex-account-title",children:[u.jsx("strong",{children:ne.name}),xe?u.jsx("span",{className:"codex-account-active",children:"Active"}):null,st?u.jsx("span",{className:"codex-account-warning",children:"Needs attention"}):null]}),u.jsx("small",{children:lt.join(" · ")||`Added ${rt(ne.createdAt)}`}),st?u.jsx("div",{className:"codex-account-issues",role:"status",children:Oe.map(At=>u.jsx("span",{children:At.message},At.code))}):null,oe!=null&&oe.usage?u.jsx(FE,{usage:oe.usage}):u.jsx("span",{className:"codex-account-usage-empty",children:o?"Reading account usage...":"Usage unavailable"}),oe?u.jsx("small",{className:oe.error?"codex-account-detail-error":"codex-account-refreshed",children:oe.error?`Refresh issue: ${oe.error}`:`Updated ${rt(oe.refreshedAt)}`}):null]}),u.jsxs("div",{className:"codex-account-actions",children:[u.jsx("button",{disabled:f||o||Ct,onClick:()=>U(ne),title:Ct?"Sign in again or delete this account to replace its credential.":void 0,type:"button",children:st?"Repair & rename":"Rename"}),u.jsx("button",{disabled:f||o||xe||st,onClick:()=>{y(""),_(ne)},type:"button",children:xe?"In use":st?"Unavailable":"Switch"}),u.jsx("button",{className:"danger",disabled:f||o||xe,onClick:()=>{y(""),le(ne)},type:"button",children:"Delete"})]})]},ne.id)})}),!i&&de.length>0?u.jsxs("section",{className:"codex-reset-credits","aria-label":"Rate-limit reset credits",children:[u.jsx("h4",{children:"Rate-limit reset credits"}),ce?u.jsx("p",{className:"settings-note",role:"status",children:ce}):null,de.map(ne=>{var Oe,st,Ct;const xe=(Oe=t==null?void 0:t.accountDetails)==null?void 0:Oe[ne.id],oe=xe==null?void 0:xe.rateLimitResetCredits;return u.jsx("article",{className:"codex-account-card",children:u.jsxs("div",{className:"codex-account-main",children:[u.jsxs("div",{className:"codex-account-title",children:[u.jsx("strong",{children:ne.name}),u.jsx("span",{children:oe?`${oe.availableCount} available`:"Unavailable"})]}),oe?null:u.jsx("small",{children:o?"Reading reset credits...":"Reset credit information was not returned. Refresh details to try again."}),(st=oe==null?void 0:oe.credits)==null?void 0:st.map(lt=>{var Je,ut;return u.jsxs("div",{className:"codex-reset-credit",children:[u.jsxs("div",{className:"codex-account-title",children:[u.jsx("strong",{children:lt.title||"Rate-limit reset"}),u.jsx("button",{className:"codex-account-add",type:"button",disabled:f||o||lt.status!=="available"||lt.resetType!=="codexRateLimits"||lt.expiresAt!==null&&lt.expiresAt*1e3<=Date.now()||!!((ut=(Je=t==null?void 0:t.accountIssues)==null?void 0:Je[ne.id])!=null&&ut.length),onClick:()=>void Ce(ne,lt),children:f?"Please wait...":"Use"})]}),lt.description?u.jsx("span",{children:lt.description}):null,u.jsxs("small",{children:[lt.status," · Granted ",rt(new Date(lt.grantedAt*1e3).toISOString()),lt.expiresAt===null?" · No expiry":` · Expires ${rt(new Date(lt.expiresAt*1e3).toISOString())}`]})]},lt.id)}),oe&&oe.availableCount>(((Ct=oe.credits)==null?void 0:Ct.length)??0)?u.jsx("small",{children:oe.credits==null?"Only the available count was returned.":`Showing ${oe.credits.length} credit details; the available count includes all credits.`}):null,xe?u.jsx("small",{children:xe.error?`Refresh issue: ${xe.error}`:`Updated ${rt(xe.refreshedAt)}`}):null]})},ne.id)})]}):null,R?u.jsx("div",{className:"memory-editor-overlay",onClick:()=>!f&&B(null),role:"presentation",children:u.jsxs("form",{"aria-label":"Rename Codex account",className:"memory-editor-popover codex-account-login-dialog",onClick:ne=>ne.stopPropagation(),onSubmit:ne=>void O(ne),children:[u.jsxs("header",{children:[u.jsx("strong",{children:"Rename Codex Account"}),u.jsx("button",{"aria-label":"Close account rename",className:"memory-icon-button",disabled:f,onClick:()=>B(null),type:"button",children:"×"})]}),u.jsx("p",{className:"settings-note",children:"This name is only a Seele label. It does not change the Codex login or credential."}),u.jsxs("label",{children:[u.jsx("span",{children:"Account name"}),u.jsx("input",{"aria-label":"Codex account name",autoFocus:!0,maxLength:80,onChange:ne=>Y(ne.target.value),value:F})]}),m?u.jsx("p",{className:"memory-editor-error",children:m}):null,u.jsxs("div",{className:"memory-editor-actions",children:[u.jsx("button",{className:"memory-dialog-button",disabled:f,onClick:()=>B(null),type:"button",children:"Cancel"}),u.jsx("button",{className:"memory-dialog-button primary",disabled:f||!F.trim(),type:"submit",children:f?"Saving...":"Save"})]})]})}):null,v?u.jsx("div",{className:"memory-editor-overlay",onClick:()=>!f&&!E&&k(!1),role:"presentation",children:E?u.jsxs("section",{"aria-label":"Complete Codex account login",className:"memory-delete-dialog codex-account-login-dialog",onClick:ne=>ne.stopPropagation(),children:[u.jsxs("header",{children:[u.jsx("strong",{children:E.status==="succeeded"?"Account Added":"Complete Codex Login"}),u.jsx("button",{"aria-label":"Close account login",className:"memory-icon-button",disabled:f,onClick:()=>void Ye(),type:"button",children:"×"})]}),E.status==="pending"?u.jsxs(u.Fragment,{children:[u.jsx("p",{children:"Open the official Codex device page and enter this one-time code."}),u.jsxs("div",{className:"codex-device-code",children:[u.jsx("strong",{children:E.userCode}),u.jsx("button",{onClick:()=>{navigator.clipboard.writeText(E.userCode),G(!0),window.setTimeout(()=>G(!1),1500)},type:"button",children:J?"Copied":"Copy code"})]}),u.jsx("a",{href:E.verificationUrl,rel:"noreferrer",target:"_blank",children:"Open Codex device login"}),u.jsx("small",{className:"codex-login-waiting",children:"Waiting for Codex to confirm the login..."})]}):E.status==="succeeded"?u.jsxs("p",{children:[u.jsx("strong",{children:((Re=E.account)==null?void 0:Re.name)??E.accountName})," is persisted on the cloud and ready to synchronize. It was not activated automatically."]}):u.jsx("p",{className:"memory-editor-error",children:E.error??"Codex login was cancelled."}),u.jsx("div",{className:"memory-delete-actions",children:u.jsx("button",{className:"memory-dialog-button",disabled:f,onClick:()=>void Ye(),type:"button",children:E.status==="pending"?"Cancel login":"Close"})})]}):u.jsxs("form",{"aria-label":"Add Codex account",className:"memory-editor-popover codex-account-login-dialog",onClick:ne=>ne.stopPropagation(),onSubmit:ne=>void De(ne),children:[u.jsxs("header",{children:[u.jsx("strong",{children:"Add Codex Account"}),u.jsx("button",{"aria-label":"Close account login",className:"memory-icon-button",onClick:()=>k(!1),type:"button",children:"×"})]}),u.jsx("p",{className:"settings-note",children:"Seele creates the login profile on the cloud. Completing login shares it with every deployment but does not make it active."}),u.jsxs("label",{children:[u.jsx("span",{children:"Account name"}),u.jsx("input",{autoFocus:!0,maxLength:80,onChange:ne=>T(ne.target.value),placeholder:"For example: Codex backup",value:w})]}),m?u.jsx("p",{className:"memory-editor-error",children:m}):null,u.jsxs("div",{className:"memory-editor-actions",children:[u.jsx("button",{className:"memory-dialog-button",onClick:()=>k(!1),type:"button",children:"Cancel"}),u.jsx("button",{className:"memory-dialog-button primary",disabled:f||!w.trim(),type:"submit",children:f?"Starting...":"Continue"})]})]})}):null,te?u.jsx("div",{className:"memory-editor-overlay",onClick:()=>!f&&_(null),role:"presentation",children:u.jsxs("section",{"aria-label":"Switch Codex account",className:"memory-delete-dialog",onClick:ne=>ne.stopPropagation(),children:[u.jsxs("header",{children:[u.jsx("strong",{children:"Switch Codex Account"}),u.jsx("button",{"aria-label":"Close account switch",className:"memory-icon-button",disabled:f,onClick:()=>_(null),type:"button",children:"×"})]}),u.jsxs("p",{children:["Switch cloud-wide execution to ",u.jsx("strong",{children:te.name}),"? Active turns continue with the account they started with. New requests use this account after the switch; workspace threads and memory stay unchanged."]}),m?u.jsx("p",{className:"memory-editor-error",children:m}):null,u.jsxs("div",{className:"memory-delete-actions",children:[u.jsx("button",{className:"memory-dialog-button",disabled:f,onClick:()=>_(null),type:"button",children:"Cancel"}),u.jsx("button",{className:"memory-dialog-button primary",disabled:f,onClick:()=>void Q(),type:"button",children:f?"Switching...":"Switch account"})]})]})}):null,K?u.jsx("div",{className:"memory-editor-overlay",onClick:()=>!f&&le(null),role:"presentation",children:u.jsxs("section",{"aria-label":"Delete Codex account",className:"memory-delete-dialog",onClick:ne=>ne.stopPropagation(),children:[u.jsxs("header",{children:[u.jsx("strong",{children:"Delete Codex Account"}),u.jsx("button",{"aria-label":"Close account deletion",className:"memory-icon-button",disabled:f,onClick:()=>le(null),type:"button",children:"×"})]}),u.jsxs("p",{children:["Delete ",u.jsx("strong",{children:K.name})," and its persisted Codex credential from the cloud and every member mirror? This cannot be undone."]}),m?u.jsx("p",{className:"memory-editor-error",children:m}):null,u.jsxs("div",{className:"memory-delete-actions",children:[u.jsx("button",{className:"memory-dialog-button",disabled:f,onClick:()=>le(null),type:"button",children:"Cancel"}),u.jsx("button",{className:"memory-dialog-button danger",disabled:f,onClick:()=>void z(),type:"button",children:f?"Deleting...":"Delete"})]})]})}):null]})}function VE({currentUser:e,users:t,onCreate:n,onDelete:i,onUpdate:l}){const o={username:"",password:"",role:"user",active:!0},[c,f]=I.useState(null),[h,m]=I.useState(o),[y,v]=I.useState(!1),[k,w]=I.useState(null),[T,E]=I.useState("");function q(){m(o),E(""),f("new")}function R(Y){m({username:Y.username,password:"",role:Y.role,active:Y.active}),E(""),f(Y)}function B(){y||(f(null),E(""))}async function F(Y){if(Y.preventDefault(),!!c){v(!0),E("");try{c==="new"?await n({username:h.username.trim(),password:h.password,role:h.role}):await l(c.id,{username:h.username.trim(),password:h.password||void 0,role:h.role,active:h.active}),f(null)}catch(te){E(dt(te).message)}finally{v(!1)}}}return u.jsxs("section",{className:"settings-section user-management-section",children:[u.jsx("header",{className:"settings-section-header",children:u.jsxs("div",{children:[u.jsx("h3",{children:"Users"}),u.jsx("p",{children:"Manage sign-in access and Seele roles."})]})}),u.jsx("div",{className:"memory-items-editor-header actions-only",children:u.jsx("button",{"aria-label":"Add user",className:"memory-icon-button",onClick:q,title:"Add user",type:"button",children:"+"})}),u.jsxs("div",{className:"user-list",children:[t.map(Y=>u.jsxs("div",{className:"user-list-item",children:[u.jsxs("div",{className:"user-list-main",children:[u.jsxs("div",{children:[u.jsx("strong",{children:Y.username}),Y.id===e.id?u.jsx("span",{className:"user-current-badge",children:"Current"}):null]}),u.jsxs("small",{children:["Created ",rt(Y.createdAt)]})]}),u.jsx("span",{className:`user-role-badge role-${Y.role}`,children:Y.role}),u.jsx("span",{className:`user-status ${Y.active?"active":"disabled"}`,children:Y.active?"Active":"Disabled"}),u.jsxs("div",{className:"user-row-actions",children:[u.jsx("button",{"aria-label":`Edit user ${Y.username}`,className:"memory-icon-button",onClick:()=>R(Y),title:"Edit",type:"button",children:u.jsx(Ef,{})}),u.jsx("button",{"aria-label":`Delete user ${Y.username}`,className:"memory-icon-button memory-item-delete",disabled:Y.id===e.id,onClick:()=>{E(""),w(Y)},title:"Delete",type:"button",children:"×"})]})]},Y.id)),t.length===0?u.jsx("p",{className:"settings-note",children:"No users are configured."}):null]}),c?u.jsx("div",{className:"memory-editor-overlay",onClick:B,role:"presentation",children:u.jsxs("form",{"aria-label":c==="new"?"Add user":"Edit user",className:"memory-editor-popover user-editor-popover",onClick:Y=>Y.stopPropagation(),onSubmit:Y=>void F(Y),children:[u.jsxs("header",{children:[u.jsx("strong",{children:c==="new"?"Add User":"Edit User"}),u.jsx("button",{"aria-label":"Close user editor",className:"memory-icon-button",onClick:B,title:"Close",type:"button",children:"×"})]}),u.jsxs("label",{children:[u.jsx("span",{children:"Username"}),u.jsx("input",{autoComplete:"off",autoFocus:!0,onChange:Y=>m(te=>({...te,username:Y.target.value})),placeholder:"Sign-in username",value:h.username})]}),u.jsxs("label",{children:[u.jsx("span",{children:c==="new"?"Initial password":"New password"}),u.jsx("input",{autoComplete:"new-password",minLength:8,onChange:Y=>m(te=>({...te,password:Y.target.value})),placeholder:c==="new"?"At least 8 characters":"Leave blank to keep the current password",type:"password",value:h.password})]}),u.jsxs("label",{children:[u.jsx("span",{children:"Role"}),u.jsxs("select",{disabled:c!=="new"&&c.id===e.id,onChange:Y=>m(te=>({...te,role:Y.target.value==="admin"?"admin":"user"})),value:h.role,children:[u.jsx("option",{value:"user",children:"User"}),u.jsx("option",{value:"admin",children:"Admin"})]})]}),c!=="new"?u.jsxs("label",{className:"user-editor-active",children:[u.jsx("input",{checked:h.active,disabled:c.id===e.id,onChange:Y=>m(te=>({...te,active:Y.target.checked})),type:"checkbox"}),u.jsx("span",{children:"Account active"})]}):null,T?u.jsx("p",{className:"memory-editor-error",children:T}):null,u.jsxs("div",{className:"memory-editor-actions",children:[u.jsx("button",{className:"memory-dialog-button",onClick:B,type:"button",children:"Cancel"}),u.jsx("button",{className:"memory-dialog-button primary",disabled:y||!h.username.trim()||c==="new"&&h.password.length<8||c!=="new"&&h.password.length>0&&h.password.length<8,type:"submit",children:y?"Saving...":"Save"})]})]})}):null,k?u.jsx("div",{className:"memory-editor-overlay",onClick:()=>w(null),role:"presentation",children:u.jsxs("section",{"aria-label":"Delete user",className:"memory-delete-dialog",onClick:Y=>Y.stopPropagation(),children:[u.jsxs("header",{children:[u.jsx("strong",{children:"Delete User"}),u.jsx("button",{"aria-label":"Close delete user confirmation",className:"memory-icon-button",onClick:()=>w(null),title:"Close",type:"button",children:"×"})]}),u.jsxs("p",{children:["Delete ",u.jsx("strong",{children:k.username}),". Users that own workspaces must be disabled instead."]}),T?u.jsx("p",{className:"memory-editor-error",children:T}):null,u.jsxs("div",{className:"memory-delete-actions",children:[u.jsx("button",{className:"memory-dialog-button",onClick:()=>w(null),type:"button",children:"Cancel"}),u.jsx("button",{className:"memory-dialog-button danger",onClick:()=>{i(k.id).then(()=>w(null)).catch(Y=>E(dt(Y).message))},type:"button",children:"Delete"})]})]})}):null]})}function YE({settings:e,onSave:t}){const[n,i]=I.useState(e),[l,o]=I.useState(!1);return I.useEffect(()=>i(e),[e]),u.jsxs(u.Fragment,{children:[u.jsx("header",{className:"settings-section-header",children:u.jsxs("div",{children:[u.jsx("h3",{children:"Deployment"}),u.jsx("p",{children:"Settings stored only on this Seele instance. Cloud synchronization does not copy or overwrite them."})]})}),u.jsxs("form",{className:"settings-form",onSubmit:c=>{c.preventDefault(),o(!0),t(n).finally(()=>o(!1))},children:[u.jsxs("label",{className:"settings-field settings-field-wide",children:[u.jsxs("span",{children:[u.jsx("strong",{children:"Public URL"}),u.jsx("small",{children:"The externally reachable main URL of this deployment. Seele uses it when publishing callback links to external systems."})]}),u.jsx("input",{"aria-label":"Public URL of this deployment",onChange:c=>i({...n,publicUrl:c.target.value||null}),placeholder:"https://profuse.antgroup-inc.cn/codex/yishao-0/",type:"url",value:n.publicUrl||""})]}),u.jsxs("label",{className:"settings-toggle-field",children:[u.jsxs("span",{children:[u.jsx("strong",{children:"Profuse notification"}),u.jsx("small",{children:"Send DingTalk notifications from this deployment when a turn finishes or fails. Keep this off where the Profuse endpoint is unreachable."})]}),u.jsx("input",{"aria-label":"Enable Profuse notification on this deployment",checked:n.profuseNotificationEnabled,onChange:c=>i({...n,profuseNotificationEnabled:c.target.checked}),type:"checkbox"})]}),u.jsx("div",{className:"settings-form-actions",children:u.jsx("button",{disabled:l,type:"submit",children:l?"Saving...":"Save deployment settings"})})]})]})}function WE({codexReleasedAt:e,codexVersion:t,codexUpdating:n,draft:i,globalSettings:l,models:o,scope:c,settings:f,workspaceOverrideCount:h,workspaceSettings:m,onDraftChange:y,onResetWorkspaceSetting:v,onSubmit:k,onUpdateCodexCli:w}){var Y;const T=c==="workspace",E=Nc(i.model,o),q=Nc(l.model,o),R=Nc(f.model,o),B=D3(i.reasoningEffort,E),F=_A(E,i.reasoningEffort);return I.useEffect(()=>{E&&B!==i.reasoningEffort&&y({...i,reasoningEffort:B})},[i,E,B,y]),u.jsxs(u.Fragment,{children:[u.jsxs("header",{className:"settings-section-header",children:[u.jsxs("div",{children:[u.jsx("h3",{children:"Runtime"}),u.jsx("p",{children:"Configure global defaults or override them for the selected workspace. Running turns keep the settings they started with."})]}),T?u.jsx("span",{className:h>0?"section-override-count active":"section-override-count",children:h>0?`${h} custom`:"No custom runtime"}):null]}),u.jsxs("form",{className:"settings-form runtime-form",onSubmit:k,children:[u.jsxs("div",{className:_d(T,Hl(i.model,l.model,m==null?void 0:m.sources.model)),children:[u.jsx(Od,{globalValue:b5(l.model,o),isWorkspaceScope:T,label:"Model",settingKey:"model",source:Hl(i.model,l.model,m==null?void 0:m.sources.model),onReset:v}),u.jsx(Qm,{"aria-label":"Runtime model",onChange:te=>{const _=Nc(te,o);y({...i,model:te,reasoningEffort:D3(i.reasoningEffort,_)})},options:lD(o,i.model),value:i.model||((Y=o.find(te=>te.isDefault))==null?void 0:Y.model)||""})]}),u.jsxs("div",{className:_d(T,Hl(i.reasoningEffort,l.reasoningEffort,m==null?void 0:m.sources.reasoningEffort)),children:[u.jsx(Od,{globalValue:z3(l.reasoningEffort,q),isWorkspaceScope:T,label:"Reasoning effort",settingKey:"reasoningEffort",source:Hl(i.reasoningEffort,l.reasoningEffort,m==null?void 0:m.sources.reasoningEffort),onReset:v}),u.jsx(Qm,{"aria-label":"Runtime reasoning effort",onChange:te=>y({...i,reasoningEffort:te}),options:F,value:B})]}),u.jsxs("div",{className:_d(T,Hl(i.sandbox,l.sandbox,m==null?void 0:m.sources.sandbox)),children:[u.jsx(Od,{globalValue:S5(l.sandbox),isWorkspaceScope:T,label:"Permission mode",settingKey:"sandbox",source:Hl(i.sandbox,l.sandbox,m==null?void 0:m.sources.sandbox),onReset:v}),u.jsx(Qm,{"aria-label":"Permission mode",onChange:te=>y({...i,sandbox:te}),options:dE,value:i.sandbox})]}),u.jsxs("div",{className:_d(T,Hl(i.fastMode,l.fastMode,m==null?void 0:m.sources.fastMode),"settings-toggle-field"),children:[u.jsxs("span",{children:[u.jsx(Od,{globalValue:l.fastMode?"On":"Off",isWorkspaceScope:T,label:"Fast mode",settingKey:"fastMode",source:Hl(i.fastMode,l.fastMode,m==null?void 0:m.sources.fastMode),onReset:v}),u.jsx("small",{children:"1.5x speed with higher Codex credit consumption"})]}),u.jsx("input",{"aria-label":"Enable Fast mode",checked:i.fastMode,onChange:te=>y({...i,fastMode:te.target.checked}),type:"checkbox"})]}),u.jsxs("dl",{className:"runtime-summary",children:[u.jsxs("div",{children:[u.jsx("dt",{children:"Current"}),u.jsxs("dd",{children:["Model ",b5(f.model,o),", reasoning"," ",z3(f.reasoningEffort,R),", Fast mode"," ",f.fastMode?"on":"off",", permission"," ",S5(f.sandbox),"."]})]}),u.jsxs("div",{children:[u.jsx("dt",{children:"Codex CLI"}),u.jsxs("dd",{className:"runtime-version-value",children:[u.jsx("span",{children:Zp(t,e)}),u.jsx("button",{className:"runtime-update-button",disabled:n,onClick:w,type:"button",children:n?"Updating...":"Check update"})]})]})]}),u.jsx("div",{className:"settings-form-actions",children:u.jsx("button",{type:"submit",children:T?"Save workspace overrides":"Save global runtime"})})]})]})}function Od({globalValue:e,isWorkspaceScope:t,label:n,settingKey:i,source:l,onReset:o}){const c=t&&l==="workspace";return u.jsxs("span",{className:"runtime-field-label",children:[u.jsx("span",{children:n}),t?u.jsxs("span",{className:"runtime-field-meta",children:[u.jsx("span",{className:c?"override":"inherited",children:c?"Workspace override":`Inherited: ${e}`}),c?u.jsx("button",{type:"button",onClick:()=>o(i),children:"Reset"}):null]}):null]})}function Qm({"aria-label":e,onChange:t,options:n,value:i}){const[l,o]=I.useState(!1),c=I.useRef(null),f=n.find(h=>h.value===i)??n[0]??null;return I.useEffect(()=>{if(!l)return;function h(y){var v;(v=c.current)!=null&&v.contains(y.target)||o(!1)}function m(y){y.key==="Escape"&&o(!1)}return document.addEventListener("pointerdown",h,!0),document.addEventListener("keydown",m,!0),()=>{document.removeEventListener("pointerdown",h,!0),document.removeEventListener("keydown",m,!0)}},[l]),u.jsxs("div",{className:"runtime-select",ref:c,children:[u.jsxs("button",{"aria-expanded":l,"aria-label":e,className:"runtime-select-trigger",onClick:()=>o(h=>!h),type:"button",children:[u.jsx("span",{children:(f==null?void 0:f.label)??i}),u.jsx("span",{"aria-hidden":"true",children:"⌄"})]}),l?u.jsx("div",{className:"runtime-select-menu",role:"listbox",children:n.map(h=>u.jsx("button",{"aria-selected":h.value===i,className:h.value===i?"selected":void 0,onClick:()=>{t(h.value),o(!1)},role:"option",type:"button",children:h.label},h.value||"default"))}):null]})}function Hl(e,t,n){return e!==t?"workspace":n}function _d(e,t,n="settings-wide-field"){return[n,e?"workspace-scoped":"",e&&t==="workspace"?"workspace-overridden":""].filter(Boolean).join(" ")}function XE({baseSettings:e,scope:t,workspaceSettings:n,workspaceName:i,onSaveBaseItems:l,onSaveWorkspaceItems:o}){const c=t==="workspace",f=c?n.items:e.items,h=c?o:l;return u.jsxs(u.Fragment,{children:[u.jsx("header",{className:"settings-section-header",children:u.jsxs("div",{children:[u.jsx("h3",{children:c?"Workspace Memory":"Base Memory"}),u.jsx("p",{children:c?"Workspace memory applies only to the selected workspace. Use stable English keys; values may be Chinese, plain text, or Markdown.":"Base memory applies to every workspace. Use stable English keys; values may be Chinese, plain text, or Markdown."})]})}),c?u.jsxs("section",{className:"settings-readonly-block",children:[u.jsxs("div",{children:[u.jsx("strong",{children:"Base Memory"}),u.jsx("span",{children:"Read-only in workspace scope"})]}),u.jsx(QE,{emptyText:"No base memory is configured.",items:e.items,readonly:!0})]}):null,u.jsx("div",{className:"memory-manager-shell",children:u.jsx(KE,{ariaLabel:c?"Workspace memory":"Base memory",emptyText:"No memory items are configured.",items:f,onSaveItems:h,title:""})})]})}function KE({ariaLabel:e,emptyText:t,items:n,onSaveItems:i,title:l}){var K;const[o,c]=I.useState(Ic(n)),[f,h]=I.useState(null),[m,y]=I.useState({key:"",value:""}),[v,k]=I.useState(null),[w,T]=I.useState(null),[E,q]=I.useState(null);I.useEffect(()=>{c(Ic(n))},[n]),I.useEffect(()=>{if(f===null)return;const le=J=>{J.key==="Escape"&&(Y(),T(null))};return document.addEventListener("keydown",le),()=>document.removeEventListener("keydown",le)},[f]);async function R(le,J){q(J);try{const G=await i(le);return c(Ic(G)),G}finally{q(null)}}function B(){T(null),k(null),y({key:"",value:""}),h("new")}function F(le){const J=o[le];J&&(T(null),k(null),y({...J}),h(le))}function Y(){h(null),k(null),y({key:"",value:""})}async function te(le){const J=o[le],G=(J==null?void 0:J.key)||`${le}`;await R(o.filter((ce,fe)=>fe!==le),`delete:${G}`),T(null)}async function _(le){le.preventDefault(),le.stopPropagation();const J=m.key.trim(),G=fz(J);if(G){k(G);return}const ce=m.value.trim();if(!ce){k("Value is required.");return}const fe=f==="new"?-1:f;if(o.some((Ce,ve)=>ve!==fe&&Ce.key.trim()===J)){k(`Key "${J}" already exists. Each memory key must be unique.`);return}const Be={...m,key:J,value:ce};f==="new"?await R([...o,Be],"add"):typeof f=="number"&&await R(o.map((Ce,ve)=>ve===f?Be:Ce),`save:${f}`),Y()}return u.jsxs("section",{className:"memory-items-manager","aria-label":e,children:[u.jsxs("div",{className:l?"memory-items-editor-header":"memory-items-editor-header actions-only",children:[l?u.jsx("span",{children:l}):null,u.jsx("button",{"aria-label":"Add memory item",className:"memory-icon-button",title:"Add",type:"button",onClick:B,children:"+"})]}),o.length?u.jsx("div",{className:"memory-items-grid",children:o.map((le,J)=>u.jsxs("div",{className:"memory-item-display",children:[u.jsxs("pre",{"aria-label":`Memory item ${le.key}`,children:[u.jsx("span",{className:"memory-tag",children:`<${le.key}>`}),`
356
362
  `,u.jsx("span",{children:le.value}),`
357
- `,u.jsx("span",{className:"memory-tag",children:`</${le.key}>`})]}),u.jsxs("div",{className:"memory-item-actions",children:[u.jsx("button",{"aria-label":`Edit memory item ${le.key||J+1}`,className:"memory-icon-button memory-item-edit",disabled:E!==null,title:"Edit",type:"button",onClick:()=>F(J),children:"✎"}),u.jsx("button",{"aria-label":`Delete memory item ${le.key||J+1}`,className:"memory-icon-button memory-item-delete",disabled:E!==null,title:"Delete",type:"button",onClick:()=>T(J),children:"×"})]})]},`${J}-${le.key}`))}):u.jsx("p",{className:"settings-note",children:t}),f!==null?u.jsx("div",{className:"memory-editor-overlay",onClick:Y,role:"presentation",children:u.jsxs("form",{"aria-label":f==="new"?"Add memory item":"Edit memory item",className:"memory-editor-popover",onClick:le=>le.stopPropagation(),onSubmit:le=>void _(le),children:[u.jsxs("header",{children:[u.jsx("strong",{children:f==="new"?"Add Memory":"Edit Memory"}),u.jsx("button",{"aria-label":"Close memory editor",className:"memory-icon-button",title:"Close",type:"button",onClick:Y,children:"×"})]}),u.jsxs("label",{children:[u.jsx("span",{children:"Key"}),u.jsx("input",{autoComplete:"off",autoFocus:!0,onChange:le=>y(J=>({...J,key:le.target.value})),placeholder:"Stable technical key used as the injected tag name",value:m.key})]}),u.jsxs("label",{children:[u.jsx("span",{children:"Value · up to 1000 tokens"}),u.jsx("textarea",{onChange:le=>y(J=>({...J,value:le.target.value})),placeholder:"Memory content injected under this key",rows:10,value:m.value})]}),v?u.jsx("p",{className:"memory-editor-error",children:v}):null,u.jsxs("div",{className:"memory-editor-actions",children:[u.jsx("button",{"aria-label":"Cancel memory edit",className:"memory-dialog-button",type:"button",onClick:Y,children:"Cancel"}),u.jsx("button",{"aria-label":"Save memory item",className:"memory-dialog-button primary",disabled:E!==null,type:"submit",children:E==="add"||E!=null&&E.startsWith("save:")?"Saving...":"Save"})]})]})}):null,w!==null?u.jsx("div",{className:"memory-editor-overlay",onClick:()=>T(null),role:"presentation",children:u.jsxs("section",{"aria-label":"Confirm delete memory item",className:"memory-delete-dialog",onClick:le=>le.stopPropagation(),children:[u.jsxs("header",{children:[u.jsx("strong",{children:"Delete Memory"}),u.jsx("button",{"aria-label":"Close delete confirmation",className:"memory-icon-button",title:"Close",type:"button",onClick:()=>T(null),children:"×"})]}),u.jsxs("p",{children:["Delete"," ",u.jsx("code",{children:((K=o[w])==null?void 0:K.key)||`item ${w+1}`}),"?"]}),u.jsxs("div",{className:"memory-delete-actions",children:[u.jsx("button",{"aria-label":"Cancel delete",className:"memory-dialog-button",disabled:E!==null,type:"button",onClick:()=>T(null),children:"Cancel"}),u.jsx("button",{"aria-label":"Confirm delete",className:"memory-dialog-button danger",disabled:E!==null,type:"button",onClick:()=>void te(w),children:"Delete"})]})]})}):null]})}function KE({emptyText:e,items:t}){const n=Ic(t);return n.length?u.jsx("div",{className:"memory-items-list",children:n.map(i=>u.jsx("div",{className:"memory-item-display memory-item-readonly",children:u.jsxs("pre",{"aria-label":`Memory item ${i.key}`,children:[u.jsx("span",{className:"memory-tag",children:`<${i.key}>`}),`
363
+ `,u.jsx("span",{className:"memory-tag",children:`</${le.key}>`})]}),u.jsxs("div",{className:"memory-item-actions",children:[u.jsx("button",{"aria-label":`Edit memory item ${le.key||J+1}`,className:"memory-icon-button memory-item-edit",disabled:E!==null,title:"Edit",type:"button",onClick:()=>F(J),children:"✎"}),u.jsx("button",{"aria-label":`Delete memory item ${le.key||J+1}`,className:"memory-icon-button memory-item-delete",disabled:E!==null,title:"Delete",type:"button",onClick:()=>T(J),children:"×"})]})]},`${J}-${le.key}`))}):u.jsx("p",{className:"settings-note",children:t}),f!==null?u.jsx("div",{className:"memory-editor-overlay",onClick:Y,role:"presentation",children:u.jsxs("form",{"aria-label":f==="new"?"Add memory item":"Edit memory item",className:"memory-editor-popover",onClick:le=>le.stopPropagation(),onSubmit:le=>void _(le),children:[u.jsxs("header",{children:[u.jsx("strong",{children:f==="new"?"Add Memory":"Edit Memory"}),u.jsx("button",{"aria-label":"Close memory editor",className:"memory-icon-button",title:"Close",type:"button",onClick:Y,children:"×"})]}),u.jsxs("label",{children:[u.jsx("span",{children:"Key"}),u.jsx("input",{autoComplete:"off",autoFocus:!0,onChange:le=>y(J=>({...J,key:le.target.value})),placeholder:"Stable technical key used as the injected tag name",value:m.key})]}),u.jsxs("label",{children:[u.jsx("span",{children:"Value · up to 1000 tokens"}),u.jsx("textarea",{onChange:le=>y(J=>({...J,value:le.target.value})),placeholder:"Memory content injected under this key",rows:10,value:m.value})]}),v?u.jsx("p",{className:"memory-editor-error",children:v}):null,u.jsxs("div",{className:"memory-editor-actions",children:[u.jsx("button",{"aria-label":"Cancel memory edit",className:"memory-dialog-button",type:"button",onClick:Y,children:"Cancel"}),u.jsx("button",{"aria-label":"Save memory item",className:"memory-dialog-button primary",disabled:E!==null,type:"submit",children:E==="add"||E!=null&&E.startsWith("save:")?"Saving...":"Save"})]})]})}):null,w!==null?u.jsx("div",{className:"memory-editor-overlay",onClick:()=>T(null),role:"presentation",children:u.jsxs("section",{"aria-label":"Confirm delete memory item",className:"memory-delete-dialog",onClick:le=>le.stopPropagation(),children:[u.jsxs("header",{children:[u.jsx("strong",{children:"Delete Memory"}),u.jsx("button",{"aria-label":"Close delete confirmation",className:"memory-icon-button",title:"Close",type:"button",onClick:()=>T(null),children:"×"})]}),u.jsxs("p",{children:["Delete"," ",u.jsx("code",{children:((K=o[w])==null?void 0:K.key)||`item ${w+1}`}),"?"]}),u.jsxs("div",{className:"memory-delete-actions",children:[u.jsx("button",{"aria-label":"Cancel delete",className:"memory-dialog-button",disabled:E!==null,type:"button",onClick:()=>T(null),children:"Cancel"}),u.jsx("button",{"aria-label":"Confirm delete",className:"memory-dialog-button danger",disabled:E!==null,type:"button",onClick:()=>void te(w),children:"Delete"})]})]})}):null]})}function QE({emptyText:e,items:t}){const n=Ic(t);return n.length?u.jsx("div",{className:"memory-items-list",children:n.map(i=>u.jsx("div",{className:"memory-item-display memory-item-readonly",children:u.jsxs("pre",{"aria-label":`Memory item ${i.key}`,children:[u.jsx("span",{className:"memory-tag",children:`<${i.key}>`}),`
358
364
  `,u.jsx("span",{children:i.value}),`
359
- `,u.jsx("span",{className:"memory-tag",children:`</${i.key}>`})]})},i.key))}):u.jsx("p",{className:"settings-note",children:e})}function QE({deleteConfirmKey:e,editingEnvironmentKey:t,environmentDraft:n,globalEnvironment:i,scope:l,workspaceEnvironment:o,valueVisible:c,onCancelEnvironmentEdit:f,onDeleteConfirmChange:h,onDeleteEnvironment:m,onDraftChange:y,onEditEnvironment:v,onRevealEnvironmentValue:k,onSubmitEnvironment:w,onValueVisibleChange:T,revealedEnvironmentKeys:E}){const q=t!==null&&E.has(t),R=l==="workspace",B=R?o:i,[F,Y]=I.useState(!1);function te(){f(),y({description:"",key:"",value:""}),T(!1),Y(!0)}function _(J){v(J),T(!1),Y(!0)}function K(){Y(!1),f(),T(!1)}function le(J){w(J),Y(!1)}return u.jsxs(u.Fragment,{children:[u.jsx("header",{className:"settings-section-header",children:u.jsxs("div",{children:[u.jsx("h3",{children:R?"Workspace Environment":"Base Environment"}),u.jsx("p",{children:R?"Workspace variables are stored in this workspace and are merged with base variables for new runs.":"Base variables are injected into every new workspace run. Existing runs keep the environment they started with."})]})}),R?u.jsxs("section",{className:"settings-readonly-block",children:[u.jsxs("div",{children:[u.jsx("strong",{children:"Base Environment"}),u.jsx("span",{children:"Read-only in workspace scope"})]}),u.jsx(G3,{emptyText:"No base environment variables are configured.",readonly:!0,variables:i})]}):null,u.jsxs("section",{className:"environment-manager",children:[u.jsx("div",{className:"memory-items-editor-header actions-only",children:u.jsx("button",{"aria-label":"Add environment variable",className:"memory-icon-button",title:"Add",type:"button",onClick:te,children:"+"})}),u.jsx(G3,{emptyText:R?"No workspace environment variables are configured.":"No base environment variables are configured.",onDelete:J=>h(J),onEdit:_,variables:B})]}),F?u.jsx("div",{className:"memory-editor-overlay",onClick:K,role:"presentation",children:u.jsxs("form",{"aria-label":t?"Edit environment variable":"Add environment variable",className:"memory-editor-popover environment-editor-popover",onClick:J=>J.stopPropagation(),onSubmit:le,children:[u.jsxs("header",{children:[u.jsx("strong",{children:t?"Edit Environment":"Add Environment"}),u.jsx("button",{"aria-label":"Close environment editor",className:"memory-icon-button",title:"Close",type:"button",onClick:K,children:"×"})]}),u.jsxs("label",{children:[u.jsx("span",{children:"Key"}),u.jsx("input",{"aria-label":"Environment variable key",autoComplete:"off",autoFocus:!0,disabled:t!==null,onChange:J=>y({...n,key:J.target.value}),placeholder:"Environment variable name",spellCheck:!1,value:n.key})]}),u.jsxs("label",{children:[u.jsx("span",{children:"Value"}),u.jsxs("span",{className:"environment-value-field",children:[u.jsx("input",{"aria-label":"Environment variable value",autoComplete:"off",onChange:J=>y({...n,value:J.target.value}),placeholder:"Environment variable value",spellCheck:!1,type:c?"text":"password",value:n.value}),u.jsx("button",{"aria-label":c?"Hide value":"Show value",onClick:()=>{if(t&&!q&&!n.value){k(t),T(!0);return}T(!c)},title:c?"Hide value":"Show value",type:"button",children:c?u.jsx(SM,{}):u.jsx(kM,{})})]})]}),u.jsxs("label",{children:[u.jsx("span",{children:"Description"}),u.jsx("input",{"aria-label":"Environment variable description",autoComplete:"off",onChange:J=>y({...n,description:J.target.value}),placeholder:"What this variable is for",spellCheck:!1,value:n.description})]}),u.jsxs("div",{className:"memory-editor-actions",children:[u.jsx("button",{className:"memory-dialog-button",type:"button",onClick:K,children:"Cancel"}),u.jsx("button",{className:"memory-dialog-button primary",disabled:!n.key.trim(),type:"submit",children:"Save"})]})]})}):null,e?u.jsx("div",{className:"memory-editor-overlay",onClick:()=>h(null),role:"presentation",children:u.jsxs("section",{"aria-label":"Confirm delete environment variable",className:"memory-delete-dialog",onClick:J=>J.stopPropagation(),children:[u.jsxs("header",{children:[u.jsx("strong",{children:"Delete Environment"}),u.jsx("button",{"aria-label":"Close delete confirmation",className:"memory-icon-button",title:"Close",type:"button",onClick:()=>h(null),children:"×"})]}),u.jsxs("p",{children:["Delete ",u.jsx("code",{children:e}),"?"]}),u.jsxs("div",{className:"memory-delete-actions",children:[u.jsx("button",{className:"memory-dialog-button",type:"button",onClick:()=>h(null),children:"Cancel"}),u.jsx("button",{className:"memory-dialog-button danger",type:"button",onClick:()=>{m(e),h(null)},children:"Delete"})]})]})}):null]})}function G3({emptyText:e,onDelete:t,onEdit:n,readonly:i=!1,variables:l}){return l.length===0?u.jsx("p",{className:"settings-note",children:e}):u.jsx("div",{className:i?"environment-list readonly":"environment-list",children:l.map(o=>u.jsxs("div",{className:i?"environment-row readonly":"environment-row",children:[u.jsxs("div",{className:"environment-row-main",children:[u.jsxs("pre",{"aria-label":`Environment variable ${o.key}`,children:[u.jsx("span",{className:"memory-tag",children:o.key}),"=",o.hasValue?"••••••":"",o.description?u.jsx("span",{className:"environment-comment",children:` # ${o.description}`}):null]}),u.jsxs("span",{children:[o.hasValue?"configured":"empty"," · updated"," ",rt(o.updatedAt)]})]}),i?u.jsx("span",{className:"environment-readonly-tag",children:"read-only"}):u.jsxs("div",{className:"environment-row-actions",children:[u.jsx("button",{"aria-label":`Edit ${o.key}`,className:"memory-icon-button memory-item-edit",onClick:()=>n==null?void 0:n(o),title:"Edit",type:"button",children:"✎"}),u.jsx("button",{"aria-label":`Delete ${o.key}`,className:"memory-icon-button memory-item-delete",onClick:()=>t==null?void 0:t(o.key),title:"Delete",type:"button",children:"×"})]})]},o.key))})}function l7({items:e,onDelete:t,onEdit:n}){const[i,l]=I.useState(null),[o,c]=I.useState(null);return e.length===0?u.jsxs("section",{className:"knowledge-empty",children:[u.jsx("h4",{children:"No knowledge registered"}),u.jsx("p",{children:"Give this workspace durable source material in chat. The workspace should decide whether to register it, create local copies, and produce digest or skill files."})]}):u.jsx("div",{className:"knowledge-list",children:e.map(f=>u.jsxs("article",{className:"knowledge-row",children:[u.jsxs("div",{className:"knowledge-row-main",children:[u.jsxs("header",{children:[u.jsx("strong",{children:f.name}),u.jsx("span",{children:JE(f.kind)}),u.jsx("span",{className:nN(f.status),children:eN(f.status)})]}),u.jsx("p",{children:f.purpose||f.description||"No purpose set."}),u.jsxs("div",{className:"knowledge-paths",children:[u.jsx("code",{children:f.digestPath}),u.jsx("code",{children:f.skillPath}),u.jsx("code",{children:f.fetch.scriptPath})]}),f.fetch.requiredEnv.length>0?u.jsx("div",{className:"knowledge-envs",children:f.fetch.requiredEnv.map(h=>u.jsx("span",{title:h.description||h.key,children:h.key},h.key))}):null,o===f.id?u.jsx("small",{className:"knowledge-row-notice",children:"Refresh/check is not automatic yet. Ask this workspace to review or refresh this knowledge source."}):null,u.jsxs("small",{children:[f.attention," · ",tN(f.refreshPolicy)," · updated ",rt(f.updatedAt)]})]}),u.jsx("div",{className:"environment-row-actions",children:i===f.id?u.jsxs(u.Fragment,{children:[u.jsx("button",{className:"danger",onClick:()=>{t(f.id),l(null)},type:"button",children:"Delete"}),u.jsx("button",{onClick:()=>l(null),type:"button",children:"Cancel"})]}):u.jsxs(u.Fragment,{children:[u.jsx("button",{"aria-label":`Check ${f.name}`,onClick:()=>c(f.id),title:"Check or refresh through workspace",type:"button",children:"↻"}),u.jsx("button",{"aria-label":`Edit ${f.name}`,onClick:()=>n(f),title:"Edit knowledge",type:"button",children:u.jsx(Ef,{})}),u.jsx("button",{"aria-label":`Delete ${f.name}`,onClick:()=>l(f.id),title:"Delete knowledge",type:"button",children:"×"})]})})]},f.id))})}function ZE({draft:e,items:t,scope:n,workspaceName:i,onCancel:l,onDelete:o,onDraftChange:c,onEdit:f,onSubmit:h}){return n==="workspace"?u.jsxs(u.Fragment,{children:[u.jsx("header",{className:"settings-section-header",children:u.jsxs("div",{children:[u.jsx("h3",{children:"Workspace Knowledge"}),u.jsxs("p",{children:["Long-lived source-backed material for ",i??"this workspace",". The workspace should create and maintain these assets itself when it digests external material. You mainly review status, delete stale items, or trigger a future refresh/check."]})]})}),u.jsx(l7,{items:t,onDelete:o,onEdit:f}),e.id?u.jsxs("form",{className:"settings-form knowledge-form",onSubmit:h,children:[u.jsxs("div",{className:"knowledge-form-header",children:[u.jsxs("div",{children:[u.jsx("strong",{children:"Edit metadata"}),u.jsx("span",{children:"This is mainly for correction. New knowledge should usually be created by the workspace while processing source material."})]}),u.jsx("button",{className:"secondary",onClick:l,type:"button",children:"Close"})]}),u.jsxs("div",{className:"knowledge-form-grid",children:[u.jsxs("label",{children:[u.jsx("span",{children:"Name"}),u.jsx("input",{"aria-label":"Knowledge name",onChange:y=>c({...e,name:y.target.value}),value:e.name})]}),u.jsxs("label",{children:[u.jsx("span",{children:"Kind"}),u.jsxs("select",{"aria-label":"Knowledge kind",onChange:y=>c({...e,kind:y.target.value}),value:e.kind,children:[u.jsx("option",{value:"source",children:"Source"}),u.jsx("option",{value:"skill",children:"Skill"}),u.jsx("option",{value:"reference",children:"Reference"})]})]}),u.jsxs("label",{children:[u.jsx("span",{children:"Status"}),u.jsxs("select",{"aria-label":"Knowledge status",onChange:y=>c({...e,status:y.target.value}),value:e.status,children:[u.jsx("option",{value:"draft",children:"Draft"}),u.jsx("option",{value:"needs_fetch_method",children:"Needs fetch method"}),u.jsx("option",{value:"needs_credentials",children:"Needs credentials"}),u.jsx("option",{value:"invalid_credentials",children:"Invalid credentials"}),u.jsx("option",{value:"ready",children:"Ready"}),u.jsx("option",{value:"stale_signal",children:"Stale signal"})]})]}),u.jsxs("label",{children:[u.jsx("span",{children:"Attention"}),u.jsxs("select",{"aria-label":"Knowledge attention",onChange:y=>c({...e,attention:y.target.value}),value:e.attention,children:[u.jsx("option",{value:"none",children:"None"}),u.jsx("option",{value:"tracked",children:"Tracked"}),u.jsx("option",{value:"watch",children:"Watch"})]})]}),u.jsxs("label",{children:[u.jsx("span",{children:"Refresh"}),u.jsxs("select",{"aria-label":"Knowledge refresh policy",onChange:y=>c({...e,refreshPolicy:y.target.value}),value:e.refreshPolicy,children:[u.jsx("option",{value:"manual",children:"Manual"}),u.jsx("option",{value:"low-frequency-check",children:"Low-frequency check"})]})]})]}),u.jsxs("label",{className:"settings-wide-field",children:[u.jsx("span",{children:"Purpose"}),u.jsx("textarea",{"aria-label":"Knowledge purpose",onChange:y=>c({...e,purpose:y.target.value}),rows:2,value:e.purpose})]}),u.jsxs("label",{className:"settings-wide-field",children:[u.jsx("span",{children:"Content"}),u.jsx("textarea",{"aria-label":"Knowledge content",onChange:y=>c({...e,description:y.target.value}),rows:2,value:e.description})]}),u.jsxs("label",{className:"settings-wide-field",children:[u.jsx("span",{children:"Source clues"}),u.jsx("textarea",{"aria-label":"Knowledge source clues",onChange:y=>c({...e,sourceCluesText:y.target.value}),rows:4,value:e.sourceCluesText})]}),u.jsxs("label",{className:"settings-wide-field",children:[u.jsx("span",{children:"Required environment"}),u.jsx("textarea",{"aria-label":"Knowledge required environment",onChange:y=>c({...e,requiredEnvText:y.target.value}),rows:3,value:e.requiredEnvText})]}),u.jsx("p",{className:"settings-note",children:"Metadata lives under `.seele/knowledge/<id>/item.json`. Source copies, digest, skill, and fetch script stay in the same folder."}),u.jsx("div",{className:"settings-form-actions",children:u.jsx("button",{disabled:!e.name.trim(),type:"submit",children:"Save metadata"})})]}):null]}):u.jsxs("section",{className:"settings-empty-section",children:[u.jsx("h3",{children:"Workspace Knowledge"}),u.jsx("p",{children:"Knowledge belongs to a specific workspace because source copies, digests, skills, and fetch scripts live under that workspace's `.seele/knowledge` directory. Switch to Workspace scope to manage it."})]})}function JE(e){return e==="skill"?"Skill":e==="reference"?"Reference":"Source"}function eN(e){return e.split("_").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function tN(e){return e==="low-frequency-check"?"low-frequency check":"manual refresh"}function nN(e){return e==="ready"?"knowledge-status ready":e==="needs_credentials"||e==="invalid_credentials"||e==="needs_fetch_method"?"knowledge-status warning":e==="stale_signal"?"knowledge-status stale":"knowledge-status"}function wt({label:e,value:t,mono:n=!1}){return u.jsxs("div",{className:"context-field",children:[u.jsx("span",{children:e}),u.jsx("strong",{className:n?"mono":void 0,title:t,children:t})]})}function rN({onRefresh:e,preview:t,refreshing:n}){const i=["workspace_identity","workspace_environment","rendering"],l=I.useMemo(()=>Object.entries(t.context).map(([c,f])=>[c,aN(f)]).sort(([c],[f])=>{const h=i.indexOf(c),m=i.indexOf(f);return h>=0||m>=0?(h>=0?h:Number.MAX_SAFE_INTEGER)-(m>=0?m:Number.MAX_SAFE_INTEGER):c.localeCompare(f)}),[t.context]),o=c=>{var f;(f=document.getElementById(P3(c)))==null||f.scrollIntoView({behavior:"smooth",block:"start"})};return u.jsxs("div",{className:"additional-context-preview",children:[u.jsx("div",{className:"additional-context-header",children:u.jsxs("div",{className:"additional-context-meta",children:[u.jsxs("span",{children:["Generated ",rt(t.generatedAt)]}),u.jsxs("span",{children:[wr(l.length)," keys"]}),u.jsx("button",{disabled:n,onClick:e,type:"button",children:n?"Rendering...":"Refresh"})]})}),u.jsxs("div",{className:"additional-context-toc",children:[u.jsx("button",{"aria-label":"Additional context outline",type:"button",children:"☰"}),u.jsx("div",{className:"additional-context-toc-menu",children:l.map(([c])=>u.jsx("button",{onClick:()=>o(c),type:"button",children:c},c))})]}),u.jsx("div",{className:"additional-context-list",children:l.map(([c,f])=>u.jsxs("section",{className:"additional-context-item",id:P3(c),children:[u.jsxs("header",{children:[u.jsxs("code",{children:["<",c,">"]}),u.jsxs("span",{children:[wr(f.length)," chars"]})]}),u.jsx("pre",{children:f})]},c))})]})}function P3(e){return`additional-context-${e.replace(/[^a-zA-Z0-9_-]/g,"-")}`}function aN(e){if(typeof e=="string")return e;if(e!==null&&typeof e=="object"&&"value"in e&&typeof e.value=="string")return e.value;if(e==null)return"";try{return JSON.stringify(e,null,2)}catch{return String(e)}}function iN({summary:e}){return u.jsxs("div",{className:"thread-read-summary",children:[u.jsxs("section",{className:"thread-read-summary-grid",children:[u.jsx(wt,{label:"Thread",value:e.id,mono:!0}),u.jsx(wt,{label:"Session",value:e.sessionId,mono:!0}),u.jsx(wt,{label:"Status",value:e.status}),u.jsx(wt,{label:"Source",value:e.source}),u.jsx(wt,{label:"Created",value:kc(e.createdAt)}),u.jsx(wt,{label:"Updated",value:kc(e.updatedAt)}),u.jsx(wt,{label:"Recency",value:kc(e.recencyAt)}),u.jsx(wt,{label:"Turns",value:wr(e.turnCount),mono:!0}),u.jsx(wt,{label:"Items",value:wr(e.itemCount),mono:!0}),u.jsx(wt,{label:"User / agent",value:`${wr(e.userMessageCount)} / ${wr(e.agentMessageCount)}`,mono:!0}),u.jsx(wt,{label:"Compactions",value:`${wr(e.compactionCount)} / ${wr(e.contextCompactionCount)} context`,mono:!0}),u.jsx(wt,{label:"CWD",value:e.cwd,mono:!0}),u.jsx(wt,{label:"Path",value:e.path,mono:!0})]}),e.preview?u.jsxs("details",{className:"thread-read-preview",children:[u.jsx("summary",{children:"Preview"}),u.jsx("p",{children:e.preview})]}):null,u.jsxs("section",{className:"thread-read-turns",children:[u.jsxs("div",{children:[u.jsx("strong",{children:"Turns"}),u.jsxs("span",{children:[e.turns.length," turn",e.turns.length===1?"":"s"]})]}),u.jsx("div",{className:"thread-read-turn-list",children:e.turns.map((t,n)=>u.jsxs("details",{className:"thread-read-turn",children:[u.jsxs("summary",{children:[u.jsxs("code",{children:["turn ",n+1]}),u.jsx("span",{title:t.id,children:t.id}),u.jsxs("small",{children:[t.status," · ",t.itemCount," item",t.itemCount===1?"":"s"]})]}),u.jsxs("div",{className:"thread-read-turn-detail",children:[u.jsxs("div",{className:"thread-read-turn-fields",children:[u.jsx(wt,{label:"Status",value:t.status}),u.jsx(wt,{label:"Items view",value:t.itemsView}),u.jsx(wt,{label:"Started",value:kc(t.startedAt)}),u.jsx(wt,{label:"Completed",value:kc(t.completedAt)}),u.jsx(wt,{label:"Duration",value:t.durationMs===null?"unknown":ru(t.durationMs)}),u.jsx(wt,{label:"Item types",value:t.itemTypes||"none"})]}),t.preview?u.jsx("p",{className:"thread-read-turn-preview",children:t.preview}):null,u.jsxs("details",{className:"thread-read-turn-raw",children:[u.jsx("summary",{children:"Turn raw JSON"}),u.jsx("pre",{children:JSON.stringify(t.raw,null,2)})]})]})]},t.id))})]})]})}function jc(e,t,n,i,l,o,c,f,h,m){var y,v,k,w;if(e.type==="assistantText")return u.jsx("article",{className:`message assistant${e.streaming?" streaming":""}`,"data-hover-time":rt(e.createdAt),children:u.jsxs("div",{className:"message-main",children:[u.jsxs("header",{className:"message-header",children:[u.jsx("span",{children:"Seele"}),u.jsx("time",{dateTime:e.createdAt,children:e.streaming?"streaming":rt(e.createdAt)})]}),u.jsx("div",{className:"message-body",children:u.jsx(Ec,{content:e.content,conversation:t,streaming:e.streaming,onPreviewArtifact:n,onCopyArtifactUrl:i,copiedArtifactUrl:l})})]})});if(e.type==="turnError")return u.jsxs("article",{className:"turn-error-result","data-hover-time":rt(e.createdAt),role:"alert",children:[u.jsx("strong",{children:"Task failed"}),u.jsx(r5,{content:e.content})]});if(e.type==="message")return u.jsx("article",{className:`message ${e.message.role}`,"data-hover-time":rt(e.message.createdAt),children:u.jsxs("div",{className:"message-main",children:[u.jsxs("header",{className:"message-header",children:[u.jsx("span",{children:hD(e.message.role)}),u.jsx("time",{dateTime:e.message.createdAt,children:rt(e.message.createdAt)})]}),u.jsx("div",{className:"message-body",children:e.message.role==="user"?u.jsx(r5,{content:e.message.content}):u.jsx(Ec,{content:e.message.content,conversation:t,streaming:!1,onPreviewArtifact:n,onCopyArtifactUrl:i,copiedArtifactUrl:l})})]})});if(e.type==="system"){if((y=e.topicMessages)!=null&&y.length)return u.jsx("div",{className:"topic-input-list",children:e.topicMessages.map(E=>u.jsx("article",{className:"message topic-input","data-hover-time":rt(E.createdAt),children:u.jsxs("div",{className:"topic-message-bubble topic-input-bubble",children:[u.jsxs("header",{className:"topic-input-header",children:[u.jsxs("span",{className:"topic-input-sender",children:["From ",E.senderName]}),u.jsx("time",{dateTime:E.createdAt,children:rt(E.createdAt)})]}),u.jsx("div",{className:"topic-input-content message-body",children:u.jsx(Ec,{content:E.contentMarkdown,conversation:t,streaming:!1,onPreviewArtifact:n,onCopyArtifactUrl:i,copiedArtifactUrl:l})})]})},E.id))});const T=$s({},[e.detail]);return u.jsx("article",{className:"message system","data-hover-time":rt(e.createdAt),children:u.jsx("div",{className:"message-main",children:u.jsxs("button",{className:`system-message-body system-message-link${e.visualKind?` ${e.visualKind}`:""}`,onClick:()=>m==null?void 0:m(e),type:"button",children:[e.visualKind==="topic"?u.jsx("span",{className:"system-message-icon",children:u.jsx(Gd,{})}):null,u.jsx("span",{className:"system-message-title",children:e.title}),u.jsx("small",{children:T})]})})})}return e.type==="steerMarker"?u.jsxs("div",{className:"turn-steer-marker","data-message-id":e.messageId,title:e.content,children:[u.jsx("span",{children:"Added while running"}),u.jsx("strong",{children:e.content})]}):e.tool.linkedTaskId&&h?u.jsx(o7,{description:e.tool.body,icon:u.jsx(s7,{}),onClick:()=>void h(e.tool.linkedTaskId),timestamp:e.tool.createdAt,title:"View complex task details",trailing:e.tool.meta,visibleTitle:e.tool.title}):e.tool.kind==="command"?u.jsx(yN,{tool:e.tool,onRespondApproval:o}):e.tool.kind==="file"&&((v=e.tool.fileChanges)!=null&&v.length)?u.jsx(pN,{conversation:t,tool:e.tool}):e.tool.kind==="responsibility"||e.tool.kind==="workspaceChange"?u.jsx(hN,{conversation:t,tool:e.tool,onRespond:c}):e.tool.kind==="knowledge"?u.jsx(mN,{tool:e.tool,onRespond:f}):e.tool.kind==="collaboration"&&e.tool.topicAction==="send"?u.jsxs("details",{className:"tool-card collaboration topic-output","data-hover-time":rt(e.tool.createdAt),title:rt(e.tool.createdAt),children:[u.jsxs("summary",{children:[u.jsxs("span",{className:"tool-card-summary-title",children:[u.jsx("span",{className:"tool-card-kind-icon",children:u.jsx(Gd,{})}),u.jsx("span",{children:e.tool.title})]}),e.tool.meta?u.jsx("small",{children:e.tool.meta}):null]}),u.jsxs("div",{className:"topic-message-bubble topic-output-bubble",children:[u.jsxs("header",{className:"topic-input-header",children:[u.jsxs("span",{className:"topic-input-sender",children:["To ",e.tool.topicRecipientLabel??"Topic"]}),u.jsx("time",{dateTime:e.tool.createdAt,children:rt(e.tool.createdAt)})]}),u.jsx("div",{className:"topic-input-content message-body",children:u.jsx(Ec,{content:e.tool.topicMessageContent??e.tool.output??"",conversation:t,streaming:!1,onPreviewArtifact:n,onCopyArtifactUrl:i,copiedArtifactUrl:l})})]}),(k=e.tool.rawEvents)!=null&&k.length?u.jsxs("details",{className:"tool-raw-details",children:[u.jsx("summary",{children:"Raw events"}),u.jsx("pre",{className:"tool-raw-json",children:JSON.stringify(e.tool.rawEvents,null,2)})]}):null]}):u.jsxs("details",{className:`tool-card ${e.tool.kind}`,"data-hover-time":rt(e.tool.createdAt),title:rt(e.tool.createdAt),children:[u.jsxs("summary",{children:[u.jsxs("span",{className:"tool-card-summary-title",children:[e.tool.kind==="collaboration"?u.jsx("span",{className:"tool-card-kind-icon",children:u.jsx(Gd,{})}):null,u.jsx("span",{children:e.tool.title})]}),e.tool.meta?u.jsx("small",{children:e.tool.meta}):null]}),u.jsx("code",{children:e.tool.body}),e.tool.output?u.jsx("pre",{children:e.tool.output}):null,(w=e.tool.rawEvents)!=null&&w.length?u.jsxs("details",{className:"tool-raw-details",children:[u.jsx("summary",{children:"Raw events"}),u.jsx("pre",{className:"tool-raw-json",children:JSON.stringify(e.tool.rawEvents,null,2)})]}):null]})}function V3(e){return e.type==="message"||e.type==="turnError"||e.type==="assistantText"&&e.pinnedToResult||e.type==="assistantText"&&e.phase==="final_answer"||e.type==="tool"&&lN(e.tool)}function lN(e){return e.kind==="responsibility"||e.kind==="workspaceChange"&&!!(e.workspaceChangeProposalId??e.responsibilityProposalId)||e.kind==="knowledge"||e.kind==="collaboration"&&e.topicAction==="send"||!!e.linkedTaskId||e.meta==="approval"}function sN(e){const t=[],n=[];for(const i of e)i.type==="tool"&&(i.tool.kind==="collaboration"&&i.tool.topicAction==="send"||i.tool.kind==="workspaceChange"||i.tool.kind==="responsibility")?n.push(i):t.push(i);return[...t,...n]}function oN({group:e,conversation:t,allowProcessView:n=!0,copiedFooter:i,copiedArtifactUrl:l,running:o,onCopyArtifactUrl:c,onCopyBubble:f,onLoadProcessDetails:h,onPreviewArtifact:m,onRespondApproval:y,onRespondWorkspaceChangeProposal:v,onRespondKnowledgeProposal:k,onOpenComplexTask:w,onOpenSystemEvent:T}){const E=sN(e.agentItems.filter(V3)),q=e.agentItems.some(ce=>!V3(ce)),R=n&&(q||e.turnIds.length>0),B=o?"process":"result",[F,Y]=I.useState(B),[te,_]=I.useState(!1),K=F==="result"?E:e.agentItems,le=bN(K);I.useEffect(()=>{te||Y(B)},[B,te]);const J=o||R||e.stopped,G=u.jsxs(u.Fragment,{children:[J?u.jsx("div",{className:"turn-panel-controls",children:o?u.jsx("span",{"aria-label":"Agent run in progress",className:"turn-view-spinner",title:"Agent run in progress"}):R?u.jsx("button",{"aria-label":F==="result"?"Show process":"Show result",className:"turn-view-toggle",title:F==="result"?"Show process":"Show result",type:"button",onClick:()=>{_(!0),Y(ce=>ce==="result"?(h(e.turnIds),"process"):"result")},children:F==="result"?u.jsx(uN,{}):u.jsx(cN,{})}):null}):null,K.map(ce=>u.jsx(I.Fragment,{children:jc(ce,t,m,c,l,y,v,k,w,T)},ce.id)),F==="result"&&K.length===0?u.jsx("div",{className:"turn-result-empty",children:e.stopped?"Run stopped by user":q?"No reliable final answer captured":"No result yet"}):null,u.jsx(Tc,{copied:i,content:le,id:`agent-${e.id}-bottom`,notice:e.notificationFailure,timestamp:wN(K),variant:"outside",onCopy:f})]});return e.stopped?u.jsxs("details",{className:"turn-panel agent-turn stopped","data-collapsed":"true",children:[u.jsxs("summary",{children:[u.jsx("span",{className:"turn-stopped-badge",children:"Stopped"}),u.jsx("span",{children:"Run stopped by user"})]}),u.jsx("div",{className:J?"stopped-turn-body has-controls":"stopped-turn-body",children:G})]}):u.jsx("div",{className:["turn-panel","agent-turn",e.stopped?"stopped":"",J?"has-controls":""].filter(Boolean).join(" "),children:G})}function uN(){return u.jsx("svg",{"aria-hidden":"true",fill:"none",height:"14",viewBox:"0 0 24 24",width:"14",children:u.jsx("path",{d:"M8 7h8M6 12h12M8 17h8",stroke:"currentColor",strokeLinecap:"round",strokeWidth:"2"})})}function cN(){return u.jsx("svg",{"aria-hidden":"true",fill:"none",height:"14",viewBox:"0 0 24 24",width:"14",children:u.jsx("path",{d:"m7 12 3 3 7-7",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2"})})}function dN(){return u.jsx("svg",{"aria-hidden":"true",fill:"none",height:"13",viewBox:"0 0 24 24",width:"13",children:u.jsx("rect",{fill:"currentColor",height:"12",rx:"2.6",width:"12",x:"6",y:"6"})})}function s7(){return u.jsxs("svg",{"aria-hidden":"true",fill:"none",height:"15",viewBox:"0 0 24 24",width:"15",children:[u.jsx("circle",{cx:"6",cy:"6",r:"2",stroke:"currentColor",strokeWidth:"1.8"}),u.jsx("circle",{cx:"18",cy:"7",r:"2",stroke:"currentColor",strokeWidth:"1.8"}),u.jsx("circle",{cx:"12",cy:"18",r:"2",stroke:"currentColor",strokeWidth:"1.8"}),u.jsx("path",{d:"m7.8 7 3.1 8.8M16.2 8.2l-3 7.8M8 6.2l8-.1",stroke:"currentColor",strokeLinecap:"round",strokeWidth:"1.8"})]})}function fN(){return u.jsx("svg",{"aria-hidden":"true",fill:"none",height:"16",viewBox:"0 0 24 24",width:"16",children:u.jsx("path",{d:"M12 19V5m-5 5 5-5 5 5",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2.1"})})}function o7({className:e="",description:t,icon:n,onClick:i,timestamp:l,title:o,trailing:c,visibleTitle:f}){return u.jsxs("button",{className:`tool-card file compact-timeline-link ${e}`.trim(),"data-hover-time":rt(l),onClick:i,title:o,type:"button",children:[u.jsx("span",{className:"compact-timeline-link-icon",children:n}),u.jsxs("span",{className:"compact-timeline-link-copy",children:[u.jsx("strong",{children:f}),u.jsx("small",{children:t})]}),c?u.jsx("span",{className:"compact-timeline-link-trailing",children:c}):null]})}function hN({conversation:e,tool:t,onRespond:n}){var q;const i=$e((q=t.workspaceChangePayload)==null?void 0:q.content)||t.body,[l,o]=I.useState(i),[c,f]=I.useState(null),[h,m]=I.useState("source"),[y,v]=I.useState(!1),k=!!(t.workspaceChangeProposalId??t.responsibilityProposalId),w=t.meta==="saved"||t.meta==="declined"?t.meta:k?"pending":"preparing",T=w==="pending";I.useEffect(()=>{o(i)},[i]);async function E(R){f(R);try{await n(t,R,R==="accept"?{content:l}:void 0)&&v(!1)}finally{f(null)}}return u.jsxs(u.Fragment,{children:[u.jsx(o7,{className:"responsibility-request-link",description:"Workspace responsibility",icon:u.jsx(Ef,{}),onClick:()=>v(!0),timestamp:t.createdAt,title:"View workspace change request",trailing:u.jsx("span",{className:`responsibility-request-status ${w}`,children:w}),visibleTitle:t.title}),y?u.jsx("div",{className:"dialog-backdrop",role:"presentation",onMouseDown:()=>!c&&v(!1),children:u.jsxs("section",{"aria-labelledby":`responsibility-proposal-${t.id}`,"aria-modal":"true",className:"dialog-card responsibility-proposal-dialog",onMouseDown:R=>R.stopPropagation(),role:"dialog",children:[u.jsxs("header",{children:[u.jsxs("div",{children:[u.jsx("h2",{id:`responsibility-proposal-${t.id}`,children:t.title}),u.jsxs("p",{children:["Workspace change · ",rt(t.createdAt)]})]}),u.jsx("button",{"aria-label":"Close",className:"icon-button",disabled:!!c,onClick:()=>v(!1),type:"button",children:"×"})]}),u.jsxs("div",{className:"responsibility-proposal-dialog-body",children:[u.jsxs("div",{className:"responsibility-proposal-header",children:[u.jsxs("div",{children:[u.jsx("strong",{children:"Proposed responsibility"}),u.jsx("p",{children:k?"Review or edit the Markdown before applying it to future turns.":"The proposal becomes actionable after the current turn completes."})]}),u.jsx("span",{children:w})]}),t.responsibilityReason?u.jsx("p",{className:"responsibility-proposal-reason",children:t.responsibilityReason}):null,T?u.jsxs("div",{className:"responsibility-proposal-editor",children:[u.jsxs("div",{className:"responsibility-proposal-tabs",role:"tablist",children:[u.jsx("button",{"aria-selected":h==="source",className:h==="source"?"active":"",role:"tab",type:"button",onClick:()=>m("source"),children:"Source"}),u.jsx("button",{"aria-selected":h==="preview",className:h==="preview"?"active":"",role:"tab",type:"button",onClick:()=>m("preview"),children:"Preview"})]}),h==="source"?u.jsx("textarea",{"aria-label":"Proposed workspace responsibility",className:"responsibility-proposal-body",disabled:!!c,onChange:R=>o(R.target.value),rows:12,value:l}):u.jsx("div",{className:"message-body responsibility-markdown-preview",children:Yl(l,e)})]}):u.jsx("div",{className:"message-body responsibility-markdown-preview saved",children:Yl(l,e)})]}),u.jsx("footer",{className:"responsibility-proposal-dialog-actions",children:T?u.jsxs(u.Fragment,{children:[u.jsx("button",{className:"secondary reject",disabled:!!c,type:"button",onClick:()=>void E("decline"),children:c==="decline"?"Rejecting...":"Reject"}),u.jsx("button",{className:"approve",disabled:!!c,type:"button",onClick:()=>void E("accept"),children:c==="accept"?"Saving...":"Save"})]}):u.jsx("button",{className:"secondary",onClick:()=>v(!1),type:"button",children:"Close"})})]})}):null]})}function mN({tool:e,onRespond:t}){const[n,i]=I.useState(e.body),[l,o]=I.useState(null),[c,f]=I.useState("source"),h=e.meta==="saved"||e.meta==="declined"?e.meta:"pending",m=h==="pending",y=Y3(n);return I.useEffect(()=>{i(e.body)},[e.body]),u.jsxs("article",{className:"tool-card responsibility knowledge-proposal","data-hover-time":rt(e.createdAt),title:rt(e.createdAt),children:[u.jsxs("div",{className:"responsibility-proposal-header",children:[u.jsxs("div",{children:[u.jsx("strong",{children:e.title}),u.jsx("p",{children:"Long-term knowledge changes require approval. Keep one item as a reusable source or skill, not a tiny note."})]}),u.jsx("span",{children:h})]}),m?u.jsxs("div",{className:"responsibility-proposal-editor",children:[u.jsxs("div",{className:"responsibility-proposal-tabs",role:"tablist",children:[u.jsx("button",{"aria-selected":c==="source",className:c==="source"?"active":"",role:"tab",type:"button",onClick:()=>f("source"),children:"JSON"}),u.jsx("button",{"aria-selected":c==="preview",className:c==="preview"?"active":"",role:"tab",type:"button",onClick:()=>f("preview"),children:"Preview"})]}),c==="source"?u.jsx("textarea",{"aria-label":"Proposed workspace knowledge",className:"responsibility-proposal-body",disabled:!!l,onChange:v=>i(v.target.value),rows:10,value:n}):y?u.jsx(W3,{value:y}):u.jsx("div",{className:"knowledge-proposal-invalid",children:"Invalid JSON. Fix the proposal before saving."})]}):y?u.jsx(W3,{value:y,saved:!0}):u.jsx("pre",{className:"knowledge-proposal-raw",children:n}),m?u.jsxs("div",{className:"tool-approval-actions responsibility-actions",children:[u.jsx("button",{className:"approve",disabled:!!l,type:"button",onClick:()=>{Y3(n)&&(o("accept"),Promise.resolve(t(e,"accept",n)).finally(()=>o(null)))},children:l==="accept"?"Saving...":"Save"}),u.jsx("button",{className:"reject",disabled:!!l,type:"button",onClick:()=>{o("decline"),Promise.resolve(t(e,"decline",n)).finally(()=>o(null))},children:l==="decline"?"Rejecting...":"Reject"})]}):null]})}function Y3(e){try{const t=JSON.parse(e);return!t||typeof t!="object"||Array.isArray(t)?null:t}catch{return null}}function Zm(e){return typeof e=="string"&&e.trim()?e.trim():typeof e=="number"||typeof e=="boolean"?String(e):"-"}function W3({value:e,saved:t}){return u.jsx("div",{className:`knowledge-proposal-preview${t?" saved":""}`,children:u.jsxs("dl",{children:[u.jsxs("div",{children:[u.jsx("dt",{children:"Name"}),u.jsx("dd",{children:Zm(e.name)})]}),u.jsxs("div",{children:[u.jsx("dt",{children:"Purpose"}),u.jsx("dd",{children:Zm(e.purpose)})]}),u.jsxs("div",{children:[u.jsx("dt",{children:"Content"}),u.jsx("dd",{children:Zm(e.content??e.description)})]})]})})}function pN({conversation:e,tool:t}){var c;const n=t.fileChanges??[],i=e==null?void 0:e.workspacePath,l=MA(n),o=t.meta==="started"||t.meta==="running";return u.jsxs("details",{className:`tool-card file${o?" running":" done"}`,"data-hover-time":rt(t.createdAt),title:rt(t.createdAt),children:[u.jsxs("summary",{children:[u.jsxs("span",{className:"tool-card-summary-title",children:[u.jsx("span",{className:"file-change-indicator","aria-hidden":"true"}),u.jsx("span",{className:"file-change-title",children:NA(n,i)})]}),u.jsx(X3,{additions:l.additions,deletions:l.deletions,running:o})]}),u.jsx("div",{className:"file-change-list",children:n.map((f,h)=>u.jsxs("div",{className:"file-change-row",children:[u.jsx("span",{className:"file-change-kind",children:gN(f.kind)}),u.jsx("code",{title:f.path,children:Vv(f.path,i)}),u.jsx(X3,{additions:f.additions,deletions:f.deletions})]},`${f.path}:${h}`))}),(c=t.rawEvents)!=null&&c.length?u.jsxs("details",{className:"tool-raw-details",children:[u.jsx("summary",{children:"Raw events"}),u.jsx("pre",{className:"tool-raw-json",children:JSON.stringify(t.rawEvents,null,2)})]}):null]})}function X3({additions:e,deletions:t,running:n=!1}){return u.jsxs("span",{className:"file-change-stats",children:[n?u.jsx("small",{children:"editing"}):null,e>0?u.jsxs("span",{className:"file-change-additions",children:["+",e]}):null,t>0?u.jsxs("span",{className:"file-change-deletions",children:["-",t]}):null]})}function gN(e){switch(e){case"add":return"A";case"delete":return"D";case"move":return"R";default:return"M"}}function yN({tool:e,onRespondApproval:t}){var k;const n=Lz(e),[i,l]=I.useState(!1),[o,c]=I.useState("script"),f=n==="approval"&&e.approvalRequestId!==void 0&&!!e.approvalTurnId,h=lf(e.body)?null:e.body,m=h?$z(h):null,y=m?`${vN(n)} · ${m}`:n==="running"?"Running script":n==="approval"?"Waiting for approval":"Command",v=qz(e,n);return u.jsxs("article",{className:`tool-card command ${n}`,"data-hover-time":rt(e.createdAt),title:rt(e.createdAt),children:[u.jsxs("div",{className:"tool-command-bar",children:[u.jsxs("button",{"aria-expanded":i,className:"tool-command-toggle",type:"button",onClick:()=>l(w=>!w),children:[u.jsx("span",{className:"tool-command-indicator","aria-hidden":"true"}),u.jsx("span",{children:y}),u.jsx("small",{className:"tool-command-badge",children:v})]}),i?u.jsxs("div",{className:"tool-command-tabs",role:"tablist","aria-label":"Command details",children:[u.jsx("button",{"aria-selected":o==="script",role:"tab",type:"button",onClick:()=>c("script"),children:"Script"}),u.jsx("button",{"aria-selected":o==="result",role:"tab",type:"button",onClick:()=>c("result"),children:"Result"}),(k=e.rawEvents)!=null&&k.length?u.jsx("button",{"aria-selected":o==="raw",role:"tab",type:"button",onClick:()=>c("raw"),children:"Raw"}):null]}):null,f?u.jsxs("div",{className:"tool-approval-actions",children:[u.jsx("button",{className:"approve",type:"button",onClick:()=>t(e,"accept"),children:"Approve"}),u.jsx("button",{className:"reject",type:"button",onClick:()=>t(e,"decline"),children:"Reject"})]}):null]}),i?o==="script"?u.jsx("div",{className:"tool-tab-panel",role:"tabpanel",children:h?u.jsx(K3,{content:h}):u.jsx("p",{className:"tool-output-pending",children:"Script unavailable"})}):o==="result"?u.jsxs("div",{className:"tool-tab-panel result",role:"tabpanel",children:[u.jsx("p",{className:"tool-command-result-meta",children:Uz(e,n)}),e.output?u.jsx(K3,{content:e.output}):u.jsx("p",{className:"tool-output-pending",children:n==="running"?"Waiting for output...":n==="approval"?"Waiting for approval before running.":e.meta??"No output"})]}):u.jsx(xN,{events:e.rawEvents??[]}):null]})}function vN(e){return e==="running"?"Running":e==="approval"?"Approval required":"Command"}function K3({content:e}){const[t,n]=I.useState(!1),i=Fz(e,H3);return u.jsxs("div",{className:"tool-content-block",children:[u.jsx("pre",{className:"tool-content-code",children:t?e:Hz(e,H3)}),i?u.jsx("button",{className:"tool-content-toggle",type:"button",onClick:()=>n(l=>!l),children:t?"Collapse":"Show all"}):null]})}function xN({events:e}){return u.jsx("div",{className:"tool-tab-panel raw",role:"tabpanel",children:u.jsx("pre",{className:"tool-raw-json",children:JSON.stringify(e,null,2)})})}function Tc({copied:e,content:t,id:n,notice:i,timestamp:l,variant:o,onCopy:c}){return t.trim()?u.jsxs("footer",{className:`turn-panel-footer ${o}${i?" has-notice":""}`,children:[i?u.jsx("span",{"aria-label":`Notification failed: ${i}`,className:"turn-panel-footer-notice",role:"img",title:i,children:u.jsx(S7,{})}):null,u.jsx("time",{dateTime:l,children:rt(l)}),u.jsx("button",{"aria-label":e?"Copied markdown":"Copy markdown",onClick:()=>c(n,t),title:e?"Copied":"Copy",type:"button",children:e?u.jsx("span",{"aria-hidden":"true",children:"Copied"}):u.jsxs("svg",{"aria-hidden":"true",fill:"none",height:"12",viewBox:"0 0 24 24",width:"12",children:[u.jsx("rect",{height:"14",rx:"2",stroke:"currentColor",strokeWidth:"2",width:"14",x:"8",y:"8"}),u.jsx("path",{d:"M4 16V6a2 2 0 0 1 2-2h10",stroke:"currentColor",strokeLinecap:"round",strokeWidth:"2"})]})})]}):null}function Ac(e){return e.type==="message"?e.message.role==="user"?e.message.content:Ps(e.message.content):e.type==="assistantText"?Ps(e.content):e.type==="turnError"?`Task failed
365
+ `,u.jsx("span",{className:"memory-tag",children:`</${i.key}>`})]})},i.key))}):u.jsx("p",{className:"settings-note",children:e})}function ZE({deleteConfirmKey:e,editingEnvironmentKey:t,environmentDraft:n,globalEnvironment:i,scope:l,workspaceEnvironment:o,valueVisible:c,onCancelEnvironmentEdit:f,onDeleteConfirmChange:h,onDeleteEnvironment:m,onDraftChange:y,onEditEnvironment:v,onRevealEnvironmentValue:k,onSubmitEnvironment:w,onValueVisibleChange:T,revealedEnvironmentKeys:E}){const q=t!==null&&E.has(t),R=l==="workspace",B=R?o:i,[F,Y]=I.useState(!1);function te(){f(),y({description:"",key:"",value:""}),T(!1),Y(!0)}function _(J){v(J),T(!1),Y(!0)}function K(){Y(!1),f(),T(!1)}function le(J){w(J),Y(!1)}return u.jsxs(u.Fragment,{children:[u.jsx("header",{className:"settings-section-header",children:u.jsxs("div",{children:[u.jsx("h3",{children:R?"Workspace Environment":"Base Environment"}),u.jsx("p",{children:R?"Workspace variables are stored in this workspace and are merged with base variables for new runs.":"Base variables are injected into every new workspace run. Existing runs keep the environment they started with."})]})}),R?u.jsxs("section",{className:"settings-readonly-block",children:[u.jsxs("div",{children:[u.jsx("strong",{children:"Base Environment"}),u.jsx("span",{children:"Read-only in workspace scope"})]}),u.jsx(G3,{emptyText:"No base environment variables are configured.",readonly:!0,variables:i})]}):null,u.jsxs("section",{className:"environment-manager",children:[u.jsx("div",{className:"memory-items-editor-header actions-only",children:u.jsx("button",{"aria-label":"Add environment variable",className:"memory-icon-button",title:"Add",type:"button",onClick:te,children:"+"})}),u.jsx(G3,{emptyText:R?"No workspace environment variables are configured.":"No base environment variables are configured.",onDelete:J=>h(J),onEdit:_,variables:B})]}),F?u.jsx("div",{className:"memory-editor-overlay",onClick:K,role:"presentation",children:u.jsxs("form",{"aria-label":t?"Edit environment variable":"Add environment variable",className:"memory-editor-popover environment-editor-popover",onClick:J=>J.stopPropagation(),onSubmit:le,children:[u.jsxs("header",{children:[u.jsx("strong",{children:t?"Edit Environment":"Add Environment"}),u.jsx("button",{"aria-label":"Close environment editor",className:"memory-icon-button",title:"Close",type:"button",onClick:K,children:"×"})]}),u.jsxs("label",{children:[u.jsx("span",{children:"Key"}),u.jsx("input",{"aria-label":"Environment variable key",autoComplete:"off",autoFocus:!0,disabled:t!==null,onChange:J=>y({...n,key:J.target.value}),placeholder:"Environment variable name",spellCheck:!1,value:n.key})]}),u.jsxs("label",{children:[u.jsx("span",{children:"Value"}),u.jsxs("span",{className:"environment-value-field",children:[u.jsx("input",{"aria-label":"Environment variable value",autoComplete:"off",onChange:J=>y({...n,value:J.target.value}),placeholder:"Environment variable value",spellCheck:!1,type:c?"text":"password",value:n.value}),u.jsx("button",{"aria-label":c?"Hide value":"Show value",onClick:()=>{if(t&&!q&&!n.value){k(t),T(!0);return}T(!c)},title:c?"Hide value":"Show value",type:"button",children:c?u.jsx(CM,{}):u.jsx(SM,{})})]})]}),u.jsxs("label",{children:[u.jsx("span",{children:"Description"}),u.jsx("input",{"aria-label":"Environment variable description",autoComplete:"off",onChange:J=>y({...n,description:J.target.value}),placeholder:"What this variable is for",spellCheck:!1,value:n.description})]}),u.jsxs("div",{className:"memory-editor-actions",children:[u.jsx("button",{className:"memory-dialog-button",type:"button",onClick:K,children:"Cancel"}),u.jsx("button",{className:"memory-dialog-button primary",disabled:!n.key.trim(),type:"submit",children:"Save"})]})]})}):null,e?u.jsx("div",{className:"memory-editor-overlay",onClick:()=>h(null),role:"presentation",children:u.jsxs("section",{"aria-label":"Confirm delete environment variable",className:"memory-delete-dialog",onClick:J=>J.stopPropagation(),children:[u.jsxs("header",{children:[u.jsx("strong",{children:"Delete Environment"}),u.jsx("button",{"aria-label":"Close delete confirmation",className:"memory-icon-button",title:"Close",type:"button",onClick:()=>h(null),children:"×"})]}),u.jsxs("p",{children:["Delete ",u.jsx("code",{children:e}),"?"]}),u.jsxs("div",{className:"memory-delete-actions",children:[u.jsx("button",{className:"memory-dialog-button",type:"button",onClick:()=>h(null),children:"Cancel"}),u.jsx("button",{className:"memory-dialog-button danger",type:"button",onClick:()=>{m(e),h(null)},children:"Delete"})]})]})}):null]})}function G3({emptyText:e,onDelete:t,onEdit:n,readonly:i=!1,variables:l}){return l.length===0?u.jsx("p",{className:"settings-note",children:e}):u.jsx("div",{className:i?"environment-list readonly":"environment-list",children:l.map(o=>u.jsxs("div",{className:i?"environment-row readonly":"environment-row",children:[u.jsxs("div",{className:"environment-row-main",children:[u.jsxs("pre",{"aria-label":`Environment variable ${o.key}`,children:[u.jsx("span",{className:"memory-tag",children:o.key}),"=",o.hasValue?"••••••":"",o.description?u.jsx("span",{className:"environment-comment",children:` # ${o.description}`}):null]}),u.jsxs("span",{children:[o.hasValue?"configured":"empty"," · updated"," ",rt(o.updatedAt)]})]}),i?u.jsx("span",{className:"environment-readonly-tag",children:"read-only"}):u.jsxs("div",{className:"environment-row-actions",children:[u.jsx("button",{"aria-label":`Edit ${o.key}`,className:"memory-icon-button memory-item-edit",onClick:()=>n==null?void 0:n(o),title:"Edit",type:"button",children:"✎"}),u.jsx("button",{"aria-label":`Delete ${o.key}`,className:"memory-icon-button memory-item-delete",onClick:()=>t==null?void 0:t(o.key),title:"Delete",type:"button",children:"×"})]})]},o.key))})}function l7({items:e,onDelete:t,onEdit:n}){const[i,l]=I.useState(null),[o,c]=I.useState(null);return e.length===0?u.jsxs("section",{className:"knowledge-empty",children:[u.jsx("h4",{children:"No knowledge registered"}),u.jsx("p",{children:"Give this workspace durable source material in chat. The workspace should decide whether to register it, create local copies, and produce digest or skill files."})]}):u.jsx("div",{className:"knowledge-list",children:e.map(f=>u.jsxs("article",{className:"knowledge-row",children:[u.jsxs("div",{className:"knowledge-row-main",children:[u.jsxs("header",{children:[u.jsx("strong",{children:f.name}),u.jsx("span",{children:eN(f.kind)}),u.jsx("span",{className:rN(f.status),children:tN(f.status)})]}),u.jsx("p",{children:f.purpose||f.description||"No purpose set."}),u.jsxs("div",{className:"knowledge-paths",children:[u.jsx("code",{children:f.digestPath}),u.jsx("code",{children:f.skillPath}),u.jsx("code",{children:f.fetch.scriptPath})]}),f.fetch.requiredEnv.length>0?u.jsx("div",{className:"knowledge-envs",children:f.fetch.requiredEnv.map(h=>u.jsx("span",{title:h.description||h.key,children:h.key},h.key))}):null,o===f.id?u.jsx("small",{className:"knowledge-row-notice",children:"Refresh/check is not automatic yet. Ask this workspace to review or refresh this knowledge source."}):null,u.jsxs("small",{children:[f.attention," · ",nN(f.refreshPolicy)," · updated ",rt(f.updatedAt)]})]}),u.jsx("div",{className:"environment-row-actions",children:i===f.id?u.jsxs(u.Fragment,{children:[u.jsx("button",{className:"danger",onClick:()=>{t(f.id),l(null)},type:"button",children:"Delete"}),u.jsx("button",{onClick:()=>l(null),type:"button",children:"Cancel"})]}):u.jsxs(u.Fragment,{children:[u.jsx("button",{"aria-label":`Check ${f.name}`,onClick:()=>c(f.id),title:"Check or refresh through workspace",type:"button",children:"↻"}),u.jsx("button",{"aria-label":`Edit ${f.name}`,onClick:()=>n(f),title:"Edit knowledge",type:"button",children:u.jsx(Ef,{})}),u.jsx("button",{"aria-label":`Delete ${f.name}`,onClick:()=>l(f.id),title:"Delete knowledge",type:"button",children:"×"})]})})]},f.id))})}function JE({draft:e,items:t,scope:n,workspaceName:i,onCancel:l,onDelete:o,onDraftChange:c,onEdit:f,onSubmit:h}){return n==="workspace"?u.jsxs(u.Fragment,{children:[u.jsx("header",{className:"settings-section-header",children:u.jsxs("div",{children:[u.jsx("h3",{children:"Workspace Knowledge"}),u.jsxs("p",{children:["Long-lived source-backed material for ",i??"this workspace",". The workspace should create and maintain these assets itself when it digests external material. You mainly review status, delete stale items, or trigger a future refresh/check."]})]})}),u.jsx(l7,{items:t,onDelete:o,onEdit:f}),e.id?u.jsxs("form",{className:"settings-form knowledge-form",onSubmit:h,children:[u.jsxs("div",{className:"knowledge-form-header",children:[u.jsxs("div",{children:[u.jsx("strong",{children:"Edit metadata"}),u.jsx("span",{children:"This is mainly for correction. New knowledge should usually be created by the workspace while processing source material."})]}),u.jsx("button",{className:"secondary",onClick:l,type:"button",children:"Close"})]}),u.jsxs("div",{className:"knowledge-form-grid",children:[u.jsxs("label",{children:[u.jsx("span",{children:"Name"}),u.jsx("input",{"aria-label":"Knowledge name",onChange:y=>c({...e,name:y.target.value}),value:e.name})]}),u.jsxs("label",{children:[u.jsx("span",{children:"Kind"}),u.jsxs("select",{"aria-label":"Knowledge kind",onChange:y=>c({...e,kind:y.target.value}),value:e.kind,children:[u.jsx("option",{value:"source",children:"Source"}),u.jsx("option",{value:"skill",children:"Skill"}),u.jsx("option",{value:"reference",children:"Reference"})]})]}),u.jsxs("label",{children:[u.jsx("span",{children:"Status"}),u.jsxs("select",{"aria-label":"Knowledge status",onChange:y=>c({...e,status:y.target.value}),value:e.status,children:[u.jsx("option",{value:"draft",children:"Draft"}),u.jsx("option",{value:"needs_fetch_method",children:"Needs fetch method"}),u.jsx("option",{value:"needs_credentials",children:"Needs credentials"}),u.jsx("option",{value:"invalid_credentials",children:"Invalid credentials"}),u.jsx("option",{value:"ready",children:"Ready"}),u.jsx("option",{value:"stale_signal",children:"Stale signal"})]})]}),u.jsxs("label",{children:[u.jsx("span",{children:"Attention"}),u.jsxs("select",{"aria-label":"Knowledge attention",onChange:y=>c({...e,attention:y.target.value}),value:e.attention,children:[u.jsx("option",{value:"none",children:"None"}),u.jsx("option",{value:"tracked",children:"Tracked"}),u.jsx("option",{value:"watch",children:"Watch"})]})]}),u.jsxs("label",{children:[u.jsx("span",{children:"Refresh"}),u.jsxs("select",{"aria-label":"Knowledge refresh policy",onChange:y=>c({...e,refreshPolicy:y.target.value}),value:e.refreshPolicy,children:[u.jsx("option",{value:"manual",children:"Manual"}),u.jsx("option",{value:"low-frequency-check",children:"Low-frequency check"})]})]})]}),u.jsxs("label",{className:"settings-wide-field",children:[u.jsx("span",{children:"Purpose"}),u.jsx("textarea",{"aria-label":"Knowledge purpose",onChange:y=>c({...e,purpose:y.target.value}),rows:2,value:e.purpose})]}),u.jsxs("label",{className:"settings-wide-field",children:[u.jsx("span",{children:"Content"}),u.jsx("textarea",{"aria-label":"Knowledge content",onChange:y=>c({...e,description:y.target.value}),rows:2,value:e.description})]}),u.jsxs("label",{className:"settings-wide-field",children:[u.jsx("span",{children:"Source clues"}),u.jsx("textarea",{"aria-label":"Knowledge source clues",onChange:y=>c({...e,sourceCluesText:y.target.value}),rows:4,value:e.sourceCluesText})]}),u.jsxs("label",{className:"settings-wide-field",children:[u.jsx("span",{children:"Required environment"}),u.jsx("textarea",{"aria-label":"Knowledge required environment",onChange:y=>c({...e,requiredEnvText:y.target.value}),rows:3,value:e.requiredEnvText})]}),u.jsx("p",{className:"settings-note",children:"Metadata lives under `.seele/knowledge/<id>/item.json`. Source copies, digest, skill, and fetch script stay in the same folder."}),u.jsx("div",{className:"settings-form-actions",children:u.jsx("button",{disabled:!e.name.trim(),type:"submit",children:"Save metadata"})})]}):null]}):u.jsxs("section",{className:"settings-empty-section",children:[u.jsx("h3",{children:"Workspace Knowledge"}),u.jsx("p",{children:"Knowledge belongs to a specific workspace because source copies, digests, skills, and fetch scripts live under that workspace's `.seele/knowledge` directory. Switch to Workspace scope to manage it."})]})}function eN(e){return e==="skill"?"Skill":e==="reference"?"Reference":"Source"}function tN(e){return e.split("_").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function nN(e){return e==="low-frequency-check"?"low-frequency check":"manual refresh"}function rN(e){return e==="ready"?"knowledge-status ready":e==="needs_credentials"||e==="invalid_credentials"||e==="needs_fetch_method"?"knowledge-status warning":e==="stale_signal"?"knowledge-status stale":"knowledge-status"}function wt({label:e,value:t,mono:n=!1}){return u.jsxs("div",{className:"context-field",children:[u.jsx("span",{children:e}),u.jsx("strong",{className:n?"mono":void 0,title:t,children:t})]})}function aN({onRefresh:e,preview:t,refreshing:n}){const i=["workspace_identity","workspace_environment","rendering"],l=I.useMemo(()=>Object.entries(t.context).map(([c,f])=>[c,iN(f)]).sort(([c],[f])=>{const h=i.indexOf(c),m=i.indexOf(f);return h>=0||m>=0?(h>=0?h:Number.MAX_SAFE_INTEGER)-(m>=0?m:Number.MAX_SAFE_INTEGER):c.localeCompare(f)}),[t.context]),o=c=>{var f;(f=document.getElementById(P3(c)))==null||f.scrollIntoView({behavior:"smooth",block:"start"})};return u.jsxs("div",{className:"additional-context-preview",children:[u.jsx("div",{className:"additional-context-header",children:u.jsxs("div",{className:"additional-context-meta",children:[u.jsxs("span",{children:["Generated ",rt(t.generatedAt)]}),u.jsxs("span",{children:[wr(l.length)," keys"]}),u.jsx("button",{disabled:n,onClick:e,type:"button",children:n?"Rendering...":"Refresh"})]})}),u.jsxs("div",{className:"additional-context-toc",children:[u.jsx("button",{"aria-label":"Additional context outline",type:"button",children:"☰"}),u.jsx("div",{className:"additional-context-toc-menu",children:l.map(([c])=>u.jsx("button",{onClick:()=>o(c),type:"button",children:c},c))})]}),u.jsx("div",{className:"additional-context-list",children:l.map(([c,f])=>u.jsxs("section",{className:"additional-context-item",id:P3(c),children:[u.jsxs("header",{children:[u.jsxs("code",{children:["<",c,">"]}),u.jsxs("span",{children:[wr(f.length)," chars"]})]}),u.jsx("pre",{children:f})]},c))})]})}function P3(e){return`additional-context-${e.replace(/[^a-zA-Z0-9_-]/g,"-")}`}function iN(e){if(typeof e=="string")return e;if(e!==null&&typeof e=="object"&&"value"in e&&typeof e.value=="string")return e.value;if(e==null)return"";try{return JSON.stringify(e,null,2)}catch{return String(e)}}function lN({summary:e}){return u.jsxs("div",{className:"thread-read-summary",children:[u.jsxs("section",{className:"thread-read-summary-grid",children:[u.jsx(wt,{label:"Thread",value:e.id,mono:!0}),u.jsx(wt,{label:"Session",value:e.sessionId,mono:!0}),u.jsx(wt,{label:"Status",value:e.status}),u.jsx(wt,{label:"Source",value:e.source}),u.jsx(wt,{label:"Created",value:kc(e.createdAt)}),u.jsx(wt,{label:"Updated",value:kc(e.updatedAt)}),u.jsx(wt,{label:"Recency",value:kc(e.recencyAt)}),u.jsx(wt,{label:"Turns",value:wr(e.turnCount),mono:!0}),u.jsx(wt,{label:"Items",value:wr(e.itemCount),mono:!0}),u.jsx(wt,{label:"User / agent",value:`${wr(e.userMessageCount)} / ${wr(e.agentMessageCount)}`,mono:!0}),u.jsx(wt,{label:"Compactions",value:`${wr(e.compactionCount)} / ${wr(e.contextCompactionCount)} context`,mono:!0}),u.jsx(wt,{label:"CWD",value:e.cwd,mono:!0}),u.jsx(wt,{label:"Path",value:e.path,mono:!0})]}),e.preview?u.jsxs("details",{className:"thread-read-preview",children:[u.jsx("summary",{children:"Preview"}),u.jsx("p",{children:e.preview})]}):null,u.jsxs("section",{className:"thread-read-turns",children:[u.jsxs("div",{children:[u.jsx("strong",{children:"Turns"}),u.jsxs("span",{children:[e.turns.length," turn",e.turns.length===1?"":"s"]})]}),u.jsx("div",{className:"thread-read-turn-list",children:e.turns.map((t,n)=>u.jsxs("details",{className:"thread-read-turn",children:[u.jsxs("summary",{children:[u.jsxs("code",{children:["turn ",n+1]}),u.jsx("span",{title:t.id,children:t.id}),u.jsxs("small",{children:[t.status," · ",t.itemCount," item",t.itemCount===1?"":"s"]})]}),u.jsxs("div",{className:"thread-read-turn-detail",children:[u.jsxs("div",{className:"thread-read-turn-fields",children:[u.jsx(wt,{label:"Status",value:t.status}),u.jsx(wt,{label:"Items view",value:t.itemsView}),u.jsx(wt,{label:"Started",value:kc(t.startedAt)}),u.jsx(wt,{label:"Completed",value:kc(t.completedAt)}),u.jsx(wt,{label:"Duration",value:t.durationMs===null?"unknown":ru(t.durationMs)}),u.jsx(wt,{label:"Item types",value:t.itemTypes||"none"})]}),t.preview?u.jsx("p",{className:"thread-read-turn-preview",children:t.preview}):null,u.jsxs("details",{className:"thread-read-turn-raw",children:[u.jsx("summary",{children:"Turn raw JSON"}),u.jsx("pre",{children:JSON.stringify(t.raw,null,2)})]})]})]},t.id))})]})]})}function jc(e,t,n,i,l,o,c,f,h,m){var y,v,k,w;if(e.type==="assistantText")return u.jsx("article",{className:`message assistant${e.streaming?" streaming":""}`,"data-hover-time":rt(e.createdAt),children:u.jsxs("div",{className:"message-main",children:[u.jsxs("header",{className:"message-header",children:[u.jsx("span",{children:"Seele"}),u.jsx("time",{dateTime:e.createdAt,children:e.streaming?"streaming":rt(e.createdAt)})]}),u.jsx("div",{className:"message-body",children:u.jsx(Ec,{content:e.content,conversation:t,streaming:e.streaming,onPreviewArtifact:n,onCopyArtifactUrl:i,copiedArtifactUrl:l})})]})});if(e.type==="turnError")return u.jsxs("article",{className:"turn-error-result","data-hover-time":rt(e.createdAt),role:"alert",children:[u.jsx("strong",{children:"Task failed"}),u.jsx(r5,{content:e.content})]});if(e.type==="message")return u.jsx("article",{className:`message ${e.message.role}`,"data-hover-time":rt(e.message.createdAt),children:u.jsxs("div",{className:"message-main",children:[u.jsxs("header",{className:"message-header",children:[u.jsx("span",{children:mD(e.message.role)}),u.jsx("time",{dateTime:e.message.createdAt,children:rt(e.message.createdAt)})]}),u.jsx("div",{className:"message-body",children:e.message.role==="user"?u.jsx(r5,{content:e.message.content}):u.jsx(Ec,{content:e.message.content,conversation:t,streaming:!1,onPreviewArtifact:n,onCopyArtifactUrl:i,copiedArtifactUrl:l})})]})});if(e.type==="system"){if((y=e.topicMessages)!=null&&y.length)return u.jsx("div",{className:"topic-input-list",children:e.topicMessages.map(E=>u.jsx("article",{className:"message topic-input","data-hover-time":rt(E.createdAt),children:u.jsxs("div",{className:"topic-message-bubble topic-input-bubble",children:[u.jsxs("header",{className:"topic-input-header",children:[u.jsxs("span",{className:"topic-input-sender",children:["From ",E.senderName]}),u.jsx("time",{dateTime:E.createdAt,children:rt(E.createdAt)})]}),u.jsx("div",{className:"topic-input-content message-body",children:u.jsx(Ec,{content:E.contentMarkdown,conversation:t,streaming:!1,onPreviewArtifact:n,onCopyArtifactUrl:i,copiedArtifactUrl:l})})]})},E.id))});const T=$s({},[e.detail]);return u.jsx("article",{className:"message system","data-hover-time":rt(e.createdAt),children:u.jsx("div",{className:"message-main",children:u.jsxs("button",{className:`system-message-body system-message-link${e.visualKind?` ${e.visualKind}`:""}`,onClick:()=>m==null?void 0:m(e),type:"button",children:[e.visualKind==="topic"?u.jsx("span",{className:"system-message-icon",children:u.jsx(Gd,{})}):null,u.jsx("span",{className:"system-message-title",children:e.title}),u.jsx("small",{children:T})]})})})}return e.type==="steerMarker"?u.jsxs("div",{className:"turn-steer-marker","data-message-id":e.messageId,title:e.content,children:[u.jsx("span",{children:"Added while running"}),u.jsx("strong",{children:e.content})]}):e.tool.linkedTaskId&&h?u.jsx(o7,{description:e.tool.body,icon:u.jsx(s7,{}),onClick:()=>void h(e.tool.linkedTaskId),timestamp:e.tool.createdAt,title:"View complex task details",trailing:e.tool.meta,visibleTitle:e.tool.title}):e.tool.kind==="command"?u.jsx(vN,{tool:e.tool,onRespondApproval:o}):e.tool.kind==="file"&&((v=e.tool.fileChanges)!=null&&v.length)?u.jsx(gN,{conversation:t,tool:e.tool}):e.tool.kind==="responsibility"||e.tool.kind==="workspaceChange"?u.jsx(mN,{conversation:t,tool:e.tool,onRespond:c}):e.tool.kind==="knowledge"?u.jsx(pN,{tool:e.tool,onRespond:f}):e.tool.kind==="collaboration"&&e.tool.topicAction==="send"?u.jsxs("details",{className:"tool-card collaboration topic-output","data-hover-time":rt(e.tool.createdAt),title:rt(e.tool.createdAt),children:[u.jsxs("summary",{children:[u.jsxs("span",{className:"tool-card-summary-title",children:[u.jsx("span",{className:"tool-card-kind-icon",children:u.jsx(Gd,{})}),u.jsx("span",{children:e.tool.title})]}),e.tool.meta?u.jsx("small",{children:e.tool.meta}):null]}),u.jsxs("div",{className:"topic-message-bubble topic-output-bubble",children:[u.jsxs("header",{className:"topic-input-header",children:[u.jsxs("span",{className:"topic-input-sender",children:["To ",e.tool.topicRecipientLabel??"Topic"]}),u.jsx("time",{dateTime:e.tool.createdAt,children:rt(e.tool.createdAt)})]}),u.jsx("div",{className:"topic-input-content message-body",children:u.jsx(Ec,{content:e.tool.topicMessageContent??e.tool.output??"",conversation:t,streaming:!1,onPreviewArtifact:n,onCopyArtifactUrl:i,copiedArtifactUrl:l})})]}),(k=e.tool.rawEvents)!=null&&k.length?u.jsxs("details",{className:"tool-raw-details",children:[u.jsx("summary",{children:"Raw events"}),u.jsx("pre",{className:"tool-raw-json",children:JSON.stringify(e.tool.rawEvents,null,2)})]}):null]}):u.jsxs("details",{className:`tool-card ${e.tool.kind}`,"data-hover-time":rt(e.tool.createdAt),title:rt(e.tool.createdAt),children:[u.jsxs("summary",{children:[u.jsxs("span",{className:"tool-card-summary-title",children:[e.tool.kind==="collaboration"?u.jsx("span",{className:"tool-card-kind-icon",children:u.jsx(Gd,{})}):null,u.jsx("span",{children:e.tool.title})]}),e.tool.meta?u.jsx("small",{children:e.tool.meta}):null]}),u.jsx("code",{children:e.tool.body}),e.tool.output?u.jsx("pre",{children:e.tool.output}):null,(w=e.tool.rawEvents)!=null&&w.length?u.jsxs("details",{className:"tool-raw-details",children:[u.jsx("summary",{children:"Raw events"}),u.jsx("pre",{className:"tool-raw-json",children:JSON.stringify(e.tool.rawEvents,null,2)})]}):null]})}function V3(e){return e.type==="message"||e.type==="turnError"||e.type==="assistantText"&&e.pinnedToResult||e.type==="assistantText"&&e.phase==="final_answer"||e.type==="tool"&&sN(e.tool)}function sN(e){return e.kind==="responsibility"||e.kind==="workspaceChange"&&!!(e.workspaceChangeProposalId??e.responsibilityProposalId)||e.kind==="knowledge"||e.kind==="collaboration"&&e.topicAction==="send"||!!e.linkedTaskId||e.meta==="approval"}function oN(e){const t=[],n=[];for(const i of e)i.type==="tool"&&(i.tool.kind==="collaboration"&&i.tool.topicAction==="send"||i.tool.kind==="workspaceChange"||i.tool.kind==="responsibility")?n.push(i):t.push(i);return[...t,...n]}function uN({group:e,conversation:t,allowProcessView:n=!0,copiedFooter:i,copiedArtifactUrl:l,running:o,onCopyArtifactUrl:c,onCopyBubble:f,onLoadProcessDetails:h,onPreviewArtifact:m,onRespondApproval:y,onRespondWorkspaceChangeProposal:v,onRespondKnowledgeProposal:k,onOpenComplexTask:w,onOpenSystemEvent:T}){const E=oN(e.agentItems.filter(V3)),q=e.agentItems.some(ce=>!V3(ce)),R=n&&(q||e.turnIds.length>0),B=o?"process":"result",[F,Y]=I.useState(B),[te,_]=I.useState(!1),K=F==="result"?E:e.agentItems,le=wN(K);I.useEffect(()=>{te||Y(B)},[B,te]);const J=o||R||e.stopped,G=u.jsxs(u.Fragment,{children:[J?u.jsx("div",{className:"turn-panel-controls",children:o?u.jsx("span",{"aria-label":"Agent run in progress",className:"turn-view-spinner",title:"Agent run in progress"}):R?u.jsx("button",{"aria-label":F==="result"?"Show process":"Show result",className:"turn-view-toggle",title:F==="result"?"Show process":"Show result",type:"button",onClick:()=>{_(!0),Y(ce=>ce==="result"?(h(e.turnIds),"process"):"result")},children:F==="result"?u.jsx(cN,{}):u.jsx(dN,{})}):null}):null,K.map(ce=>u.jsx(I.Fragment,{children:jc(ce,t,m,c,l,y,v,k,w,T)},ce.id)),F==="result"&&K.length===0?u.jsx("div",{className:"turn-result-empty",children:e.stopped?"Run stopped by user":q?"No reliable final answer captured":"No result yet"}):null,u.jsx(Tc,{copied:i,content:le,id:`agent-${e.id}-bottom`,notice:e.notificationFailure,timestamp:kN(K),variant:"outside",onCopy:f})]});return e.stopped?u.jsxs("details",{className:"turn-panel agent-turn stopped","data-collapsed":"true",children:[u.jsxs("summary",{children:[u.jsx("span",{className:"turn-stopped-badge",children:"Stopped"}),u.jsx("span",{children:"Run stopped by user"})]}),u.jsx("div",{className:J?"stopped-turn-body has-controls":"stopped-turn-body",children:G})]}):u.jsx("div",{className:["turn-panel","agent-turn",e.stopped?"stopped":"",J?"has-controls":""].filter(Boolean).join(" "),children:G})}function cN(){return u.jsx("svg",{"aria-hidden":"true",fill:"none",height:"14",viewBox:"0 0 24 24",width:"14",children:u.jsx("path",{d:"M8 7h8M6 12h12M8 17h8",stroke:"currentColor",strokeLinecap:"round",strokeWidth:"2"})})}function dN(){return u.jsx("svg",{"aria-hidden":"true",fill:"none",height:"14",viewBox:"0 0 24 24",width:"14",children:u.jsx("path",{d:"m7 12 3 3 7-7",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2"})})}function fN(){return u.jsx("svg",{"aria-hidden":"true",fill:"none",height:"13",viewBox:"0 0 24 24",width:"13",children:u.jsx("rect",{fill:"currentColor",height:"12",rx:"2.6",width:"12",x:"6",y:"6"})})}function s7(){return u.jsxs("svg",{"aria-hidden":"true",fill:"none",height:"15",viewBox:"0 0 24 24",width:"15",children:[u.jsx("circle",{cx:"6",cy:"6",r:"2",stroke:"currentColor",strokeWidth:"1.8"}),u.jsx("circle",{cx:"18",cy:"7",r:"2",stroke:"currentColor",strokeWidth:"1.8"}),u.jsx("circle",{cx:"12",cy:"18",r:"2",stroke:"currentColor",strokeWidth:"1.8"}),u.jsx("path",{d:"m7.8 7 3.1 8.8M16.2 8.2l-3 7.8M8 6.2l8-.1",stroke:"currentColor",strokeLinecap:"round",strokeWidth:"1.8"})]})}function hN(){return u.jsx("svg",{"aria-hidden":"true",fill:"none",height:"16",viewBox:"0 0 24 24",width:"16",children:u.jsx("path",{d:"M12 19V5m-5 5 5-5 5 5",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2.1"})})}function o7({className:e="",description:t,icon:n,onClick:i,timestamp:l,title:o,trailing:c,visibleTitle:f}){return u.jsxs("button",{className:`tool-card file compact-timeline-link ${e}`.trim(),"data-hover-time":rt(l),onClick:i,title:o,type:"button",children:[u.jsx("span",{className:"compact-timeline-link-icon",children:n}),u.jsxs("span",{className:"compact-timeline-link-copy",children:[u.jsx("strong",{children:f}),u.jsx("small",{children:t})]}),c?u.jsx("span",{className:"compact-timeline-link-trailing",children:c}):null]})}function mN({conversation:e,tool:t,onRespond:n}){var q;const i=$e((q=t.workspaceChangePayload)==null?void 0:q.content)||t.body,[l,o]=I.useState(i),[c,f]=I.useState(null),[h,m]=I.useState("source"),[y,v]=I.useState(!1),k=!!(t.workspaceChangeProposalId??t.responsibilityProposalId),w=t.meta==="saved"||t.meta==="declined"?t.meta:k?"pending":"preparing",T=w==="pending";I.useEffect(()=>{o(i)},[i]);async function E(R){f(R);try{await n(t,R,R==="accept"?{content:l}:void 0)&&v(!1)}finally{f(null)}}return u.jsxs(u.Fragment,{children:[u.jsx(o7,{className:"responsibility-request-link",description:"Workspace responsibility",icon:u.jsx(Ef,{}),onClick:()=>v(!0),timestamp:t.createdAt,title:"View workspace change request",trailing:u.jsx("span",{className:`responsibility-request-status ${w}`,children:w}),visibleTitle:t.title}),y?u.jsx("div",{className:"dialog-backdrop",role:"presentation",onMouseDown:()=>!c&&v(!1),children:u.jsxs("section",{"aria-labelledby":`responsibility-proposal-${t.id}`,"aria-modal":"true",className:"dialog-card responsibility-proposal-dialog",onMouseDown:R=>R.stopPropagation(),role:"dialog",children:[u.jsxs("header",{children:[u.jsxs("div",{children:[u.jsx("h2",{id:`responsibility-proposal-${t.id}`,children:t.title}),u.jsxs("p",{children:["Workspace change · ",rt(t.createdAt)]})]}),u.jsx("button",{"aria-label":"Close",className:"icon-button",disabled:!!c,onClick:()=>v(!1),type:"button",children:"×"})]}),u.jsxs("div",{className:"responsibility-proposal-dialog-body",children:[u.jsxs("div",{className:"responsibility-proposal-header",children:[u.jsxs("div",{children:[u.jsx("strong",{children:"Proposed responsibility"}),u.jsx("p",{children:k?"Review or edit the Markdown before applying it to future turns.":"The proposal becomes actionable after the current turn completes."})]}),u.jsx("span",{children:w})]}),t.responsibilityReason?u.jsx("p",{className:"responsibility-proposal-reason",children:t.responsibilityReason}):null,T?u.jsxs("div",{className:"responsibility-proposal-editor",children:[u.jsxs("div",{className:"responsibility-proposal-tabs",role:"tablist",children:[u.jsx("button",{"aria-selected":h==="source",className:h==="source"?"active":"",role:"tab",type:"button",onClick:()=>m("source"),children:"Source"}),u.jsx("button",{"aria-selected":h==="preview",className:h==="preview"?"active":"",role:"tab",type:"button",onClick:()=>m("preview"),children:"Preview"})]}),h==="source"?u.jsx("textarea",{"aria-label":"Proposed workspace responsibility",className:"responsibility-proposal-body",disabled:!!c,onChange:R=>o(R.target.value),rows:12,value:l}):u.jsx("div",{className:"message-body responsibility-markdown-preview",children:Yl(l,e)})]}):u.jsx("div",{className:"message-body responsibility-markdown-preview saved",children:Yl(l,e)})]}),u.jsx("footer",{className:"responsibility-proposal-dialog-actions",children:T?u.jsxs(u.Fragment,{children:[u.jsx("button",{className:"secondary reject",disabled:!!c,type:"button",onClick:()=>void E("decline"),children:c==="decline"?"Rejecting...":"Reject"}),u.jsx("button",{className:"approve",disabled:!!c,type:"button",onClick:()=>void E("accept"),children:c==="accept"?"Saving...":"Save"})]}):u.jsx("button",{className:"secondary",onClick:()=>v(!1),type:"button",children:"Close"})})]})}):null]})}function pN({tool:e,onRespond:t}){const[n,i]=I.useState(e.body),[l,o]=I.useState(null),[c,f]=I.useState("source"),h=e.meta==="saved"||e.meta==="declined"?e.meta:"pending",m=h==="pending",y=Y3(n);return I.useEffect(()=>{i(e.body)},[e.body]),u.jsxs("article",{className:"tool-card responsibility knowledge-proposal","data-hover-time":rt(e.createdAt),title:rt(e.createdAt),children:[u.jsxs("div",{className:"responsibility-proposal-header",children:[u.jsxs("div",{children:[u.jsx("strong",{children:e.title}),u.jsx("p",{children:"Long-term knowledge changes require approval. Keep one item as a reusable source or skill, not a tiny note."})]}),u.jsx("span",{children:h})]}),m?u.jsxs("div",{className:"responsibility-proposal-editor",children:[u.jsxs("div",{className:"responsibility-proposal-tabs",role:"tablist",children:[u.jsx("button",{"aria-selected":c==="source",className:c==="source"?"active":"",role:"tab",type:"button",onClick:()=>f("source"),children:"JSON"}),u.jsx("button",{"aria-selected":c==="preview",className:c==="preview"?"active":"",role:"tab",type:"button",onClick:()=>f("preview"),children:"Preview"})]}),c==="source"?u.jsx("textarea",{"aria-label":"Proposed workspace knowledge",className:"responsibility-proposal-body",disabled:!!l,onChange:v=>i(v.target.value),rows:10,value:n}):y?u.jsx(W3,{value:y}):u.jsx("div",{className:"knowledge-proposal-invalid",children:"Invalid JSON. Fix the proposal before saving."})]}):y?u.jsx(W3,{value:y,saved:!0}):u.jsx("pre",{className:"knowledge-proposal-raw",children:n}),m?u.jsxs("div",{className:"tool-approval-actions responsibility-actions",children:[u.jsx("button",{className:"approve",disabled:!!l,type:"button",onClick:()=>{Y3(n)&&(o("accept"),Promise.resolve(t(e,"accept",n)).finally(()=>o(null)))},children:l==="accept"?"Saving...":"Save"}),u.jsx("button",{className:"reject",disabled:!!l,type:"button",onClick:()=>{o("decline"),Promise.resolve(t(e,"decline",n)).finally(()=>o(null))},children:l==="decline"?"Rejecting...":"Reject"})]}):null]})}function Y3(e){try{const t=JSON.parse(e);return!t||typeof t!="object"||Array.isArray(t)?null:t}catch{return null}}function Zm(e){return typeof e=="string"&&e.trim()?e.trim():typeof e=="number"||typeof e=="boolean"?String(e):"-"}function W3({value:e,saved:t}){return u.jsx("div",{className:`knowledge-proposal-preview${t?" saved":""}`,children:u.jsxs("dl",{children:[u.jsxs("div",{children:[u.jsx("dt",{children:"Name"}),u.jsx("dd",{children:Zm(e.name)})]}),u.jsxs("div",{children:[u.jsx("dt",{children:"Purpose"}),u.jsx("dd",{children:Zm(e.purpose)})]}),u.jsxs("div",{children:[u.jsx("dt",{children:"Content"}),u.jsx("dd",{children:Zm(e.content??e.description)})]})]})})}function gN({conversation:e,tool:t}){var c;const n=t.fileChanges??[],i=e==null?void 0:e.workspacePath,l=zA(n),o=t.meta==="started"||t.meta==="running";return u.jsxs("details",{className:`tool-card file${o?" running":" done"}`,"data-hover-time":rt(t.createdAt),title:rt(t.createdAt),children:[u.jsxs("summary",{children:[u.jsxs("span",{className:"tool-card-summary-title",children:[u.jsx("span",{className:"file-change-indicator","aria-hidden":"true"}),u.jsx("span",{className:"file-change-title",children:MA(n,i)})]}),u.jsx(X3,{additions:l.additions,deletions:l.deletions,running:o})]}),u.jsx("div",{className:"file-change-list",children:n.map((f,h)=>u.jsxs("div",{className:"file-change-row",children:[u.jsx("span",{className:"file-change-kind",children:yN(f.kind)}),u.jsx("code",{title:f.path,children:Vv(f.path,i)}),u.jsx(X3,{additions:f.additions,deletions:f.deletions})]},`${f.path}:${h}`))}),(c=t.rawEvents)!=null&&c.length?u.jsxs("details",{className:"tool-raw-details",children:[u.jsx("summary",{children:"Raw events"}),u.jsx("pre",{className:"tool-raw-json",children:JSON.stringify(t.rawEvents,null,2)})]}):null]})}function X3({additions:e,deletions:t,running:n=!1}){return u.jsxs("span",{className:"file-change-stats",children:[n?u.jsx("small",{children:"editing"}):null,e>0?u.jsxs("span",{className:"file-change-additions",children:["+",e]}):null,t>0?u.jsxs("span",{className:"file-change-deletions",children:["-",t]}):null]})}function yN(e){switch(e){case"add":return"A";case"delete":return"D";case"move":return"R";default:return"M"}}function vN({tool:e,onRespondApproval:t}){var k;const n=qz(e),[i,l]=I.useState(!1),[o,c]=I.useState("script"),f=n==="approval"&&e.approvalRequestId!==void 0&&!!e.approvalTurnId,h=lf(e.body)?null:e.body,m=h?Gz(h):null,y=m?`${xN(n)} · ${m}`:n==="running"?"Running script":n==="approval"?"Waiting for approval":"Command",v=Uz(e,n);return u.jsxs("article",{className:`tool-card command ${n}`,"data-hover-time":rt(e.createdAt),title:rt(e.createdAt),children:[u.jsxs("div",{className:"tool-command-bar",children:[u.jsxs("button",{"aria-expanded":i,className:"tool-command-toggle",type:"button",onClick:()=>l(w=>!w),children:[u.jsx("span",{className:"tool-command-indicator","aria-hidden":"true"}),u.jsx("span",{children:y}),u.jsx("small",{className:"tool-command-badge",children:v})]}),i?u.jsxs("div",{className:"tool-command-tabs",role:"tablist","aria-label":"Command details",children:[u.jsx("button",{"aria-selected":o==="script",role:"tab",type:"button",onClick:()=>c("script"),children:"Script"}),u.jsx("button",{"aria-selected":o==="result",role:"tab",type:"button",onClick:()=>c("result"),children:"Result"}),(k=e.rawEvents)!=null&&k.length?u.jsx("button",{"aria-selected":o==="raw",role:"tab",type:"button",onClick:()=>c("raw"),children:"Raw"}):null]}):null,f?u.jsxs("div",{className:"tool-approval-actions",children:[u.jsx("button",{className:"approve",type:"button",onClick:()=>t(e,"accept"),children:"Approve"}),u.jsx("button",{className:"reject",type:"button",onClick:()=>t(e,"decline"),children:"Reject"})]}):null]}),i?o==="script"?u.jsx("div",{className:"tool-tab-panel",role:"tabpanel",children:h?u.jsx(K3,{content:h}):u.jsx("p",{className:"tool-output-pending",children:"Script unavailable"})}):o==="result"?u.jsxs("div",{className:"tool-tab-panel result",role:"tabpanel",children:[u.jsx("p",{className:"tool-command-result-meta",children:Hz(e,n)}),e.output?u.jsx(K3,{content:e.output}):u.jsx("p",{className:"tool-output-pending",children:n==="running"?"Waiting for output...":n==="approval"?"Waiting for approval before running.":e.meta??"No output"})]}):u.jsx(bN,{events:e.rawEvents??[]}):null]})}function xN(e){return e==="running"?"Running":e==="approval"?"Approval required":"Command"}function K3({content:e}){const[t,n]=I.useState(!1),i=$z(e,H3);return u.jsxs("div",{className:"tool-content-block",children:[u.jsx("pre",{className:"tool-content-code",children:t?e:Fz(e,H3)}),i?u.jsx("button",{className:"tool-content-toggle",type:"button",onClick:()=>n(l=>!l),children:t?"Collapse":"Show all"}):null]})}function bN({events:e}){return u.jsx("div",{className:"tool-tab-panel raw",role:"tabpanel",children:u.jsx("pre",{className:"tool-raw-json",children:JSON.stringify(e,null,2)})})}function Tc({copied:e,content:t,id:n,notice:i,timestamp:l,variant:o,onCopy:c}){return t.trim()?u.jsxs("footer",{className:`turn-panel-footer ${o}${i?" has-notice":""}`,children:[i?u.jsx("span",{"aria-label":`Notification failed: ${i}`,className:"turn-panel-footer-notice",role:"img",title:i,children:u.jsx(S7,{})}):null,u.jsx("time",{dateTime:l,children:rt(l)}),u.jsx("button",{"aria-label":e?"Copied markdown":"Copy markdown",onClick:()=>c(n,t),title:e?"Copied":"Copy",type:"button",children:e?u.jsx("span",{"aria-hidden":"true",children:"Copied"}):u.jsxs("svg",{"aria-hidden":"true",fill:"none",height:"12",viewBox:"0 0 24 24",width:"12",children:[u.jsx("rect",{height:"14",rx:"2",stroke:"currentColor",strokeWidth:"2",width:"14",x:"8",y:"8"}),u.jsx("path",{d:"M4 16V6a2 2 0 0 1 2-2h10",stroke:"currentColor",strokeLinecap:"round",strokeWidth:"2"})]})})]}):null}function Ac(e){return e.type==="message"?e.message.role==="user"?e.message.content:Ps(e.message.content):e.type==="assistantText"?Ps(e.content):e.type==="turnError"?`Task failed
360
366
 
361
367
  ${e.content}`:e.type==="system"?[e.title,e.fullDetail??e.detail].filter(t=>!!(t!=null&&t.trim())).join(`
362
368
 
363
- `):""}function bN(e){return e.map(Ac).filter(t=>t.trim()).join(`
369
+ `):""}function wN(e){return e.map(Ac).filter(t=>t.trim()).join(`
364
370
 
365
- `)}function wN(e){for(let t=e.length-1;t>=0;t-=1){const n=e[t];if(n.type!=="tool")return n.createdAt}return new Date().toISOString()}function kN({usage:e}){return e?u.jsx("div",{className:"usage-indicators","aria-label":"Seele usage",children:e.windows.map(t=>u.jsx(SN,{label:u7(t.windowDurationMins),window:t},`${t.windowDurationMins}:${t.resetsAt}`))}):u.jsx("span",{"aria-label":"Usage pending",className:"usage-indicator muted","data-tooltip":"Usage pending",role:"status",tabIndex:0,children:u.jsx("strong",{children:"--"})})}function u7(e){return e%10080===0?`${e/10080}w`:e%1440===0?`${e/1440}d`:e%60===0?`${e/60}h`:`${e}m`}function SN({label:e,window:t}){const n=Nf(t.usedPercent),i=W1(n),l=`${e} usage ${H7(n)} · resets ${F7(t.resetsAt)}`;return u.jsx("span",{"aria-label":l,className:`usage-indicator ${i}`,"data-tooltip":l,role:"status",style:{"--usage-level":`${n}%`},tabIndex:0,children:u.jsxs("strong",{children:[Math.round(n),"%"]})})}function CN(e,t,n,i,l,o){const c=[...e].sort(Bc),f=new Map(i.filter(_=>_.parentId===null&&_.nodeType==="agent_turn"&&_.turnId!==null).map(_=>[_.turnId,_.sequence])),h=new Map(i.filter(_=>_.parentId===null&&_.nodeType==="agent_turn"&&_.turnId!==null).map(_=>[_.turnId,_.timelineAt])),m=new Map(i.filter(_=>_.nodeType==="user_message"&&_.entityId!==null).map(_=>[_.entityId,_.sequence])),y=new Map(i.filter(_=>_.nodeType==="user_message"&&_.entityId!==null).map(_=>[_.entityId,_.timelineAt])),v=i.filter(_=>_.parentId===null&&_.nodeType==="system_event"),k=v.filter(_=>_.turnId!==null&&_.subtype.startsWith("input:")),w=v.filter(_=>!k.includes(_)),T=new Set(v.flatMap(_=>_.turnId?[_.turnId]:[])),E=yA(t),q=new Map(n.map(_=>[_.id,_])),R=i.filter(_=>_.parentId===null&&_.nodeType==="agent_turn"&&_.turnId!==null).map(_=>_.turnId),F=[...new Set(i.length>0?[...R,...l?[l]:[]]:[...n.map(_=>_.id),...c.flatMap(_=>_.turnId?[_.turnId]:[]),...t.flatMap(_=>_.turnId?[_.turnId]:[])])].map(_=>{var Je,ut,At,jn;const K=q.get(_),le=c.filter(Qe=>Qe.turnId===_),J=le.filter(Qe=>Qe.role==="user").sort((Qe,Zt)=>{const Pt=y.get(Qe.id)??Qe.createdAt,Wt=y.get(Zt.id)??Zt.createdAt;return Pt.localeCompare(Wt)||Bc(Qe,Zt)}),G=le.filter(Qe=>Qe.role==="assistant"),ce=t.filter(Qe=>Qe.turnId===_).sort(Bc),fe=`turn:${_}`,Be=i.filter(Qe=>Qe.parentId===fe).sort((Qe,Zt)=>Qe.sequence-Zt.sequence),Ce=(K==null?void 0:K.origin)??E.get(_),ve=k.filter(Qe=>Qe.turnId===_).sort((Qe,Zt)=>Qe.timelineAt.localeCompare(Zt.timelineAt)||Qe.sequence-Zt.sequence).map(Qe=>Q3(Qe,void 0,o)),ee=Ce==="timeline_event"?[]:i.length>0?RN(Be,ce,Oc([_],l),o):d7(ce,Oc([_],l),o),pe=G.map(wc),De=Be.find(Qe=>Qe.subtype==="server.complex_task.plan_updated"),Ye=ce.find(Qe=>Qe.event==="server.complex_task.plan_updated"),U=(De==null?void 0:De.detail)??(Ye==null?void 0:Ye.data),O=Ee(Ee(U).task),Q=Ee(O.currentPlan),z=$e(Q.planMarkdown),de=EN(DN(ee,pe),z),Re=vA(K);Re&&de.push({id:`turn-error-${Re.turnId}`,type:"turnError",createdAt:Re.createdAt,content:Re.content});const ne=ce.find(Qe=>Qe.event==="server.wakeup.started"),xe=Ee(ne==null?void 0:ne.data),oe=typeof xe.instruction=="string"?xe.instruction.trim():"",Oe=Ce==="timeline_event"?ce[0]:void 0,st=T.has(_)?null:Oe?c7(Oe,(K==null?void 0:K.startedAt)??new Date(0).toISOString()):NN(Ce)?{id:`system-${_}`,type:"system",createdAt:(K==null?void 0:K.startedAt)??((Je=ce[0])==null?void 0:Je.createdAt)??new Date(0).toISOString(),title:MN(Ce??"system"),detail:zN(Ce??"system",oe),fullDetail:oe||void 0}:null,Ct=YN(ce),lt=(J[0]?y.get(J[0].id):(ut=k.find(Qe=>Qe.turnId===_))==null?void 0:ut.timelineAt)??h.get(_)??(K==null?void 0:K.startedAt)??((At=le[0])==null?void 0:At.createdAt)??((jn=ce[0])==null?void 0:jn.createdAt)??new Date(0).toISOString();return{id:`turn-${_}`,turnIds:[_],user:st??(J[0]?wc(J[0]):null),followupUsers:J.slice(1).map(wc),acceptedSystemInputs:ve,agentItems:de,activity:Ct??(Oc([_],l)?{id:-1,title:de.some(Qe=>Qe.type==="assistantText"&&Qe.streaming)?"Writing response":"Working",createdAt:lt,tone:"running"}:null),notificationFailure:VN(ce),stopped:ce.some(h7),trailingSystemItems:[],sortAt:lt,sortSequence:f.get(_)??null}}),Y=c.filter(_=>!_.turnId);F.push(...Y.map(_=>({id:`message-${_.id}`,turnIds:[],user:_.role==="user"?wc(_):null,followupUsers:[],agentItems:_.role==="assistant"?[wc(_)]:[],activity:null,notificationFailure:null,stopped:!1,sortAt:y.get(_.id)??_.createdAt,sortSequence:m.get(_.id)??null})));const te=new Map(t.map(_=>[String(_.id),_]));return F.push(...w.map(_=>({id:_.id,turnIds:[],user:Q3(_,_.entityType==="event"&&_.entityId?te.get(_.entityId):void 0,o),followupUsers:[],agentItems:[],activity:null,notificationFailure:null,stopped:!1,trailingSystemItems:[],sortAt:_.timelineAt,sortSequence:_.sequence}))),F.sort((_,K)=>{const le=_.sortAt.localeCompare(K.sortAt);return le!==0?le:_.sortSequence!==null||K.sortSequence!==null?(_.sortSequence??Number.MAX_SAFE_INTEGER)-(K.sortSequence??Number.MAX_SAFE_INTEGER):0}).map(({sortAt:_,...K})=>K)}function Q3(e,t,n){var h,m;if(t||e.entityType==="event")return c7(t??Wp(e),e.createdAt);const i=Ee(e.detail);if(e.subtype==="input:collaboration_notice"||e.subtype==="input:topic_message"){const y=Hp(i,n),v=jN(i.messages,n),k=Array.isArray(i.senderWorkspaceIds)?i.senderWorkspaceIds.filter(T=>typeof T=="string"&&T.trim().length>0):[],w=typeof i.unreadCount=="number"?i.unreadCount:0;return{id:e.id,type:"system",createdAt:e.createdAt,title:y.title,detail:y.detail,visualKind:"topic",topicMessages:v,fullDetail:[`## ${y.title}`,"","**Unread**","",String(w),"","**From**","",k.length>0?k.map(T=>{const E=n.get(T)??T;return`${Us(E)} (\`${T}\`)`}).join(", "):"Unknown"].join(`
371
+ `)}function kN(e){for(let t=e.length-1;t>=0;t-=1){const n=e[t];if(n.type!=="tool")return n.createdAt}return new Date().toISOString()}function SN({usage:e}){return e?u.jsx("div",{className:"usage-indicators","aria-label":"Seele usage",children:e.windows.map(t=>u.jsx(CN,{label:u7(t.windowDurationMins),window:t},`${t.windowDurationMins}:${t.resetsAt}`))}):u.jsx("span",{"aria-label":"Usage pending",className:"usage-indicator muted","data-tooltip":"Usage pending",role:"status",tabIndex:0,children:u.jsx("strong",{children:"--"})})}function u7(e){return e%10080===0?`${e/10080}w`:e%1440===0?`${e/1440}d`:e%60===0?`${e/60}h`:`${e}m`}function CN({label:e,window:t}){const n=Nf(t.usedPercent),i=W1(n),l=`${e} usage ${H7(n)} · resets ${F7(t.resetsAt)}`;return u.jsx("span",{"aria-label":l,className:`usage-indicator ${i}`,"data-tooltip":l,role:"status",style:{"--usage-level":`${n}%`},tabIndex:0,children:u.jsxs("strong",{children:[Math.round(n),"%"]})})}function jN(e,t,n,i,l,o){const c=[...e].sort(Bc),f=new Map(i.filter(_=>_.parentId===null&&_.nodeType==="agent_turn"&&_.turnId!==null).map(_=>[_.turnId,_.sequence])),h=new Map(i.filter(_=>_.parentId===null&&_.nodeType==="agent_turn"&&_.turnId!==null).map(_=>[_.turnId,_.timelineAt])),m=new Map(i.filter(_=>_.nodeType==="user_message"&&_.entityId!==null).map(_=>[_.entityId,_.sequence])),y=new Map(i.filter(_=>_.nodeType==="user_message"&&_.entityId!==null).map(_=>[_.entityId,_.timelineAt])),v=i.filter(_=>_.parentId===null&&_.nodeType==="system_event"),k=v.filter(_=>_.turnId!==null&&_.subtype.startsWith("input:")),w=v.filter(_=>!k.includes(_)),T=new Set(v.flatMap(_=>_.turnId?[_.turnId]:[])),E=vA(t),q=new Map(n.map(_=>[_.id,_])),R=i.filter(_=>_.parentId===null&&_.nodeType==="agent_turn"&&_.turnId!==null).map(_=>_.turnId),F=[...new Set(i.length>0?[...R,...l?[l]:[]]:[...n.map(_=>_.id),...c.flatMap(_=>_.turnId?[_.turnId]:[]),...t.flatMap(_=>_.turnId?[_.turnId]:[])])].map(_=>{var Je,ut,At,jn;const K=q.get(_),le=c.filter(Qe=>Qe.turnId===_),J=le.filter(Qe=>Qe.role==="user").sort((Qe,Zt)=>{const Pt=y.get(Qe.id)??Qe.createdAt,Wt=y.get(Zt.id)??Zt.createdAt;return Pt.localeCompare(Wt)||Bc(Qe,Zt)}),G=le.filter(Qe=>Qe.role==="assistant"),ce=t.filter(Qe=>Qe.turnId===_).sort(Bc),fe=`turn:${_}`,Be=i.filter(Qe=>Qe.parentId===fe).sort((Qe,Zt)=>Qe.sequence-Zt.sequence),Ce=(K==null?void 0:K.origin)??E.get(_),ve=k.filter(Qe=>Qe.turnId===_).sort((Qe,Zt)=>Qe.timelineAt.localeCompare(Zt.timelineAt)||Qe.sequence-Zt.sequence).map(Qe=>Q3(Qe,void 0,o)),ee=Ce==="timeline_event"?[]:i.length>0?ON(Be,ce,Oc([_],l),o):d7(ce,Oc([_],l),o),pe=G.map(wc),De=Be.find(Qe=>Qe.subtype==="server.complex_task.plan_updated"),Ye=ce.find(Qe=>Qe.event==="server.complex_task.plan_updated"),U=(De==null?void 0:De.detail)??(Ye==null?void 0:Ye.data),O=Ee(Ee(U).task),Q=Ee(O.currentPlan),z=$e(Q.planMarkdown),de=NN(RN(ee,pe),z),Re=xA(K);Re&&de.push({id:`turn-error-${Re.turnId}`,type:"turnError",createdAt:Re.createdAt,content:Re.content});const ne=ce.find(Qe=>Qe.event==="server.wakeup.started"),xe=Ee(ne==null?void 0:ne.data),oe=typeof xe.instruction=="string"?xe.instruction.trim():"",Oe=Ce==="timeline_event"?ce[0]:void 0,st=T.has(_)?null:Oe?c7(Oe,(K==null?void 0:K.startedAt)??new Date(0).toISOString()):MN(Ce)?{id:`system-${_}`,type:"system",createdAt:(K==null?void 0:K.startedAt)??((Je=ce[0])==null?void 0:Je.createdAt)??new Date(0).toISOString(),title:zN(Ce??"system"),detail:DN(Ce??"system",oe),fullDetail:oe||void 0}:null,Ct=WN(ce),lt=(J[0]?y.get(J[0].id):(ut=k.find(Qe=>Qe.turnId===_))==null?void 0:ut.timelineAt)??h.get(_)??(K==null?void 0:K.startedAt)??((At=le[0])==null?void 0:At.createdAt)??((jn=ce[0])==null?void 0:jn.createdAt)??new Date(0).toISOString();return{id:`turn-${_}`,turnIds:[_],user:st??(J[0]?wc(J[0]):null),followupUsers:J.slice(1).map(wc),acceptedSystemInputs:ve,agentItems:de,activity:Ct??(Oc([_],l)?{id:-1,title:de.some(Qe=>Qe.type==="assistantText"&&Qe.streaming)?"Writing response":"Working",createdAt:lt,tone:"running"}:null),notificationFailure:YN(ce),stopped:ce.some(h7),trailingSystemItems:[],sortAt:lt,sortSequence:f.get(_)??null}}),Y=c.filter(_=>!_.turnId);F.push(...Y.map(_=>({id:`message-${_.id}`,turnIds:[],user:_.role==="user"?wc(_):null,followupUsers:[],agentItems:_.role==="assistant"?[wc(_)]:[],activity:null,notificationFailure:null,stopped:!1,sortAt:y.get(_.id)??_.createdAt,sortSequence:m.get(_.id)??null})));const te=new Map(t.map(_=>[String(_.id),_]));return F.push(...w.map(_=>({id:_.id,turnIds:[],user:Q3(_,_.entityType==="event"&&_.entityId?te.get(_.entityId):void 0,o),followupUsers:[],agentItems:[],activity:null,notificationFailure:null,stopped:!1,trailingSystemItems:[],sortAt:_.timelineAt,sortSequence:_.sequence}))),F.sort((_,K)=>{const le=_.sortAt.localeCompare(K.sortAt);return le!==0?le:_.sortSequence!==null||K.sortSequence!==null?(_.sortSequence??Number.MAX_SAFE_INTEGER)-(K.sortSequence??Number.MAX_SAFE_INTEGER):0}).map(({sortAt:_,...K})=>K)}function Q3(e,t,n){var h,m;if(t||e.entityType==="event")return c7(t??Wp(e),e.createdAt);const i=Ee(e.detail);if(e.subtype==="input:collaboration_notice"||e.subtype==="input:topic_message"){const y=Hp(i,n),v=TN(i.messages,n),k=Array.isArray(i.senderWorkspaceIds)?i.senderWorkspaceIds.filter(T=>typeof T=="string"&&T.trim().length>0):[],w=typeof i.unreadCount=="number"?i.unreadCount:0;return{id:e.id,type:"system",createdAt:e.createdAt,title:y.title,detail:y.detail,visualKind:"topic",topicMessages:v,fullDetail:[`## ${y.title}`,"","**Unread**","",String(w),"","**From**","",k.length>0?k.map(T=>{const E=n.get(T)??T;return`${Us(E)} (\`${T}\`)`}).join(", "):"Unknown"].join(`
366
372
  `)}}const l=$e(i.complexTaskId)||$e(Ee(i.task).id)||void 0,o=Gv(e.title,e.subtype),c=$s(i,[e.summary,e.contentMarkdown]),f=[`## ${Us(o)}`,"",((h=e.contentMarkdown)==null?void 0:h.trim())||((m=e.summary)==null?void 0:m.trim())||"",Object.keys(i).length>0?["","```json",JSON.stringify(i,null,2),"```"].join(`
367
373
  `):""].filter(Boolean).join(`
368
- `);return{id:e.id,type:"system",createdAt:e.createdAt,title:o,detail:c,fullDetail:f||void 0,linkedTaskId:l}}function jN(e,t){if(!Array.isArray(e))return[];const n=new Set,i=[];for(const l of e){const o=Ee(l),c=$e(o.id),f=$e(o.senderWorkspaceId),h=$e(o.contentMarkdown).trim(),m=$e(o.createdAt);!c||n.has(c)||!f||!h||!m||(n.add(c),i.push({id:c,senderWorkspaceId:f,senderName:t.get(f)??($e(o.senderTitleSnapshot)||f),contentMarkdown:h,createdAt:m}))}return i}function c7(e,t){return e.event==="server.collaboration.topic_created"?TN(e,t):AN(e,t)}function TN(e,t){const n=Ee(Ee(e.data).topic),i=$e(n.title).trim()||"Untitled Topic",l=$e(n.publicDescription).trim()||"未填写描述",o=Array.isArray(n.members)?n.members.map(Ee):[],c=$e(n.ownerWorkspaceId),f=o.find(v=>$e(v.role)==="owner"||$e(v.workspaceId)===c),h=$e(f==null?void 0:f.workspaceTitleSnapshot).trim()||"Unknown workspace",m=o.filter(v=>$e(v.role)!=="owner"&&$e(v.status)==="active"),y=m.length?m.map(v=>{const k=$e(v.workspaceTitleSnapshot).trim()||"Unknown workspace";return`- ${Us(k)} (\`${$e(v.workspaceId)}\`)`}):["无"];return{id:`collaboration-topic-created-${e.id}`,type:"system",createdAt:e.createdAt??t,title:"Created",detail:i,visualKind:"topic",fullDetail:["## Topic 已创建","","**名称**","",Us(i),"","**描述**","",Us(l),"","**Owner Workspace**","",`${Us(h)} (\`${c}\`)`,"","**协作 Workspace**","",...y].join(`
369
- `)}}function AN(e,t){const n=Ee(e.data),i=Yp(e.data),l=Gv(void 0,e.event);return{id:`system-event-${e.id}`,type:"system",createdAt:e.createdAt??t,title:l,detail:$s(n),visualKind:e.event.startsWith("server.collaboration.")?"topic":void 0,fullDetail:[`## ${Us(l)}`,"","**Event**","",`\`${e.event}\``,"","```json",JSON.stringify(i??null,null,2),"```"].join(`
370
- `)}}function Yp(e,t=""){return Array.isArray(e)?e.map(n=>Yp(n)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([n,i])=>[n,Yp(i,n)])):typeof e=="string"&&(t==="wakeAt"||t==="wake_at")&&Lc(e)||e}function EN(e,t){const n=t.trim();return n?e.filter(i=>i.type==="assistantText"?Ps(i.content).trim()!==n:i.type==="message"&&i.message.role==="assistant"?Ps(i.message.content).trim()!==n:!0):e}function NN(e){return e==="system"||e==="wakeup"||e==="runtime-reset"||e==="clone_initialization"}function MN(e){return e==="runtime-reset"?"Runtime reset":e==="clone_initialization"?"Clone initialization":e==="system"?"System action":"Scheduled wakeup"}function zN(e,t){return e==="runtime-reset"?"Thread rebuilt":e==="clone_initialization"?"Activating inherited context":e==="system"?"Workspace runtime action":t?O7(t,20):"Auto resumed"}function DN(e,t){if(e.some(l=>l.type==="assistantText"))return af(e);if(t.length===0)return e;const n=[...t],i=[];for(const l of e)l.type==="tool"&&$1(l.tool)&&F1(n,l.tool)||i.push(l);return af([...i,...n])}function RN(e,t,n,i){var h;const l=new Map(t.filter(m=>m.id!==void 0).map(m=>[String(m.id),m])),o=new Map,c=new Set;for(const m of e){const y=ON(m,t,l);y.length>0&&c.add(m.id);for(const v of y)o.set(qi(v),v)}if(n)for(const m of t)_N(e,m)||o.set(qi(m),m);else if(t.length>0&&!e.some(m=>m.phase==="process"))for(const m of t)o.set(qi(m),m);const f=d7([...o.values()].sort(Bc),n,i);for(const m of e)if(!c.has(m.id)){if(m.nodeType==="agent_text"&&m.subtype!=="final_answer"&&((h=m.contentMarkdown)!=null&&h.trim())){f.push({id:m.id,type:"assistantText",createdAt:m.createdAt,content:m.contentMarkdown,phase:BN(m),itemId:m.entityType==="codex_item"?m.entityId??void 0:void 0,streaming:n&&m.status==="running"});continue}m.nodeType==="operation"&&f.push({id:m.id,type:"tool",createdAt:m.createdAt,tool:IN(m,i)})}return af(f)}function ON(e,t,n){if(e.entityType==="event"&&e.entityId){const i=n.get(e.entityId);return i&&e.phase==="process"&&e.status==="running"?[i]:[Wp(e)]}if(e.entityType==="codex_item"&&e.entityId){const i=t.filter(l=>H1(l)===e.entityId);return i.length>0?i:[Wp(e)]}return[]}function Wp(e){const t=Ee(e.detail),n=e.subtype==="server.collaboration.message_staged"&&e.phase==="result"?e.status==="failed"?"server.collaboration.message_rejected":$e(t.messageId)?"server.collaboration.message_sent":e.subtype:e.subtype;return{id:e.entityId??e.id,turnId:e.turnId,seq:e.sequence,event:e.entityType==="codex_item"?"codex.notification":n,data:e.detail,createdAt:e.updatedAt||e.createdAt}}function _N(e,t){const n=t.id===void 0?null:String(t.id),i=H1(t);return e.some(l=>n!==null&&l.entityType==="event"&&l.entityId===n||i!==null&&l.entityType==="codex_item"&&l.entityId===i)}function H1(e){if(e.event!=="codex.notification")return null;const t=Ee(e.data),n=Ee(t.params),i=Ee(n.item);return $e(i.id)||$e(n.itemId)||null}function BN(e){return e.subtype==="final_answer"?"final_answer":e.phase==="process"?"commentary":"unknown"}function IN(e,t){var i,l;const n=Ee(e.detail);return{id:e.id,kind:e.status==="failed"?"error":"activity",title:e.subtype==="input:collaboration_notice"?Hp(n,t).title:e.title||_7(e.subtype),body:e.subtype==="input:collaboration_notice"?Hp(n,t).detail:((i=e.summary)==null?void 0:i.trim())||((l=e.contentMarkdown)==null?void 0:l.trim())||E7(n),createdAt:e.createdAt,itemId:e.entityType==="codex_item"?e.entityId??void 0:void 0,meta:e.status}}function d7(e,t,n){const i=[],l=new Map,o=new Map,c=new Map;for(const f of e){if(f.event==="server.workspace_change.decision"||f.event==="server.responsibility.decision"){UN(i,f);continue}if(f.event==="server.knowledge.decision"){HN(i,f);continue}if(h7(f)){PN(i);continue}if(f.event==="server.steer"){const T=Ee(f.data),E=typeof T.message=="string"?T.message.trim():"";i.push({id:`steer-${f.id}`,type:"steerMarker",createdAt:f.createdAt??new Date().toISOString(),content:E||"Additional input",messageId:typeof T.messageId=="string"?T.messageId:void 0});continue}const h=oD(f.data);h!=null&&h.itemId&&c.set(h.itemId,h.phase);const m=sD(f.data);if(m!=null&&m.text){const T=m.itemId?c.get(m.itemId)??m.phase:m.phase,E=m.itemId??`phase:${T}`,q=`${l.get(E)??""}${m.text}`,R=x7(q),B=o.get(E)??"",F=R.startsWith(B)?R.slice(B.length):R;if(l.set(E,q),o.set(E,R),F){const Y=i[i.length-1];(Y==null?void 0:Y.type)==="assistantText"&&$N(Y,m.itemId,T)?(Y.content+=F,Y.itemId=Y.itemId??m.itemId,Y.streamKey=Y.streamKey??E,Y.streaming=t):i.push({id:`assistant-event-${f.id}`,type:"assistantText",createdAt:f.createdAt??new Date().toISOString(),content:F,phase:T,itemId:m.itemId,streamKey:E,streaming:t})}continue}const y=uD(f.data);if(y!=null&&y.text){const T=Ps(y.text),E=y.itemId??`phase:${y.phase}`,q=GN(i,y.itemId,y.phase);if(q>=0){const R=i[q];R.type==="assistantText"&&(T?(R.content=T,R.phase=y.phase,R.itemId=R.itemId??y.itemId,R.streamKey=R.streamKey??E,R.streaming=!1,qN(i,q,y.itemId)):i.splice(q,1))}else T&&i.push({id:`assistant-completed-${f.id}`,type:"assistantText",createdAt:f.createdAt??new Date().toISOString(),content:T,phase:y.phase,itemId:y.itemId,streamKey:E,streaming:!1});continue}const v=Oz(f,n);if(v){v.rawEvents=[f];const T=J3(i,v);if(T>=0){e5(i[T],v);continue}if($1(v)&&F1(i,v)||v.kind==="command"&&v.meta==="running"&&lf(v.body))continue;i.push({id:`tool-${v.id}`,type:"tool",createdAt:v.createdAt,tool:v});continue}const k=_z(f);if(k){k.rawEvents=[f];const T=J3(i,k);if(T>=0){e5(i[T],k);continue}i.push({id:`tool-${k.id}`,type:"tool",createdAt:k.createdAt,tool:k});continue}if(jA(f)){LN(i,f);continue}const w=Bz(f);w&&(w.rawEvents=[f],i.push({id:`tool-${w.id}`,type:"tool",createdAt:w.createdAt,tool:w}))}return af(i)}function LN(e,t){const n=H1(t);if(n)for(let i=e.length-1;i>=0;i-=1){const l=e[i];if(!(l.type!=="tool"||l.tool.itemId!==n)){l.tool={...l.tool,rawEvents:m7(l.tool.rawEvents,[t])};return}}}function qN(e,t,n){if(n)for(let i=e.length-1;i>t;i-=1){const l=e[i];l.type==="assistantText"&&l.itemId===n&&e.splice(i,1)}}function UN(e,t){const n=Ee(t.data),i=typeof n.proposalId=="string"?n.proposalId:void 0,l=typeof n.decision=="string"?n.decision:void 0,o=Ee(n.payload),c=$e(o.content)||(typeof n.responsibility=="string"?n.responsibility:void 0);if(!(!i||l!=="accept"&&l!=="decline"))for(let f=e.length-1;f>=0;f-=1){const h=e[f];if(h.type==="tool"&&(h.tool.kind==="responsibility"||h.tool.kind==="workspaceChange")&&(h.tool.workspaceChangeProposalId===i||h.tool.responsibilityProposalId===i)){const m=XA(h.tool.meta,l);h.tool={...h.tool,title:m==="saved"?"Workspace change applied":"Workspace change declined",meta:m,body:m==="saved"?c??h.tool.body:h.tool.body,workspaceChangePayload:m==="saved"&&Object.keys(o).length>0?o:h.tool.workspaceChangePayload};return}}}function HN(e,t){const n=Ee(t.data),i=typeof n.proposalId=="string"?n.proposalId:void 0,l=typeof n.decision=="string"?n.decision:void 0,o=Ee(n.knowledge);if(!(!i||l!=="accept"&&l!=="decline"))for(let c=e.length-1;c>=0;c-=1){const f=e[c];if(f.type==="tool"&&f.tool.kind==="knowledge"&&f.tool.knowledgeProposalId===i){f.tool={...f.tool,title:l==="accept"?"Knowledge saved":"Knowledge proposal declined",meta:l==="accept"?"saved":"declined",body:l==="accept"&&Object.keys(o).length>0?JSON.stringify(o,null,2):f.tool.body};return}}}function F1(e,t){const n=f7(t);if(typeof n!="number")return!1;for(let o=0;o<e.length;o+=1){const c=e[o];if(c.type!=="assistantText"||!Z3(c,t))continue;const f=Ps(c.content);f!==c.content&&(e[o]={...c,content:f})}let i=0,l=-1;for(let o=0;o<e.length;o+=1){const c=e[o];if(c.type!=="assistantText"||!Z3(c,t))continue;l=o;const f=i,h=f+c.content.length;if(i=h,n>=h)continue;const m=Math.max(0,Math.min(c.content.length,n-f)),y=c.content.slice(0,m).trimEnd(),v=c.content.slice(m).trimStart(),k=[];return y&&k.push({...c,id:`${c.id}:before-tool-${t.id}`,content:y,pinnedToResult:!0}),k.push({id:`tool-${t.id}`,type:"tool",createdAt:t.createdAt,tool:t}),v&&k.push({...c,id:`${c.id}:after-tool-${t.id}`,content:v,pinnedToResult:!0}),e.splice(o,1,...k),!0}if(l>=0&&n>=i){const o=e[l];return(o==null?void 0:o.type)==="assistantText"&&(e[l]={...o,pinnedToResult:!0}),e.splice(l+1,0,{id:`tool-${t.id}`,type:"tool",createdAt:t.createdAt,tool:t}),!0}return!1}function Z3(e,t){return!t.anchorStreamKey||e.streamKey===t.anchorStreamKey}function af(e){const t=[],n=[];for(const o of e){if(o.type==="tool"&&$1(o.tool)){t.push(o.tool);continue}n.push(o)}const i=[...n],l=[];for(const o of t)F1(i,o)||l.push({id:`tool-${o.id}`,type:"tool",createdAt:o.createdAt,tool:o});return FN([...l,...i])}function $1(e){return typeof f7(e)=="number"}function f7(e){if(typeof e.anchorOffset=="number")return e.anchorOffset;if(e.kind==="responsibility")return e.responsibilityAnchorOffset;if(e.kind==="knowledge")return e.knowledgeAnchorOffset}function FN(e){const t=[];for(let n=0;n<e.length;n+=1){const i=e[n],l=e[n+1];if((i==null?void 0:i.type)==="tool"&&i.tool.kind==="responsibility"&&typeof i.tool.responsibilityAnchorOffset!="number"&&(l==null?void 0:l.type)==="assistantText"){t.push({...l,pinnedToResult:!0}),t.push(i),n+=1;continue}t.push(i)}return t}function $N(e,t,n){return e.type!=="assistantText"?!1:e.itemId&&t?e.itemId===t:e.itemId||t?!1:e.phase===n}function GN(e,t,n){if(t){const i=e.findIndex(l=>l.type==="assistantText"&&l.itemId===t);if(i>=0)return i}for(let i=e.length-1;i>=0;i-=1){const l=e[i];if(l.type==="assistantText"&&l.streaming&&(!t||!l.itemId)&&(l.phase===n||l.phase==="unknown"||n==="unknown"))return i}return-1}function h7(e){return e.event==="server.stop"||e.event==="server.stopped"}function PN(e){for(const t of e)t.type==="tool"&&t.tool.kind==="command"&&t.tool.meta==="running"&&(t.tool={...t.tool,title:"Command stopped",meta:"stopped"})}function VN(e){for(let t=e.length-1;t>=0;t-=1){const n=e[t];if(n.event!=="server.notification.failed")continue;const i=Ee(n.data);return typeof i.message=="string"?i.message:"Notification failed"}return null}function YN(e){for(let t=e.length-1;t>=0;t-=1){const n=B7(e[t]);if(n)return n}return null}function J3(e,t){for(let n=e.length-1;n>=0;n-=1){const i=e[n];if(i.type==="tool"&&i.tool.kind===t.kind&&(t.itemId&&i.tool.itemId===t.itemId||i.tool.body===t.body&&i.tool.meta==="running"))return n}return-1}function e5(e,t){if(e.type!=="tool")return;const n=e.tool.kind==="command"&&e.tool.meta!=="running"&&t.meta==="running",i=e.tool.kind==="command"&&t.kind==="command"&&lf(t.body)&&!lf(e.tool.body);e.tool={...e.tool,...t,id:e.tool.id,createdAt:e.tool.createdAt,title:n?e.tool.title:t.title,body:i?e.tool.body:t.body,meta:n?e.tool.meta:t.meta,output:Kz(e.tool.output,t.output),topicRecipientLabel:t.topicRecipientLabel??e.tool.topicRecipientLabel,topicMessageContent:t.topicMessageContent??e.tool.topicMessageContent,rawEvents:m7(e.tool.rawEvents,t.rawEvents)}}function m7(e,t){const n=[...e??[],...t??[]];if(n.length===0)return;const i=new Set;return n.filter(l=>{const o=qi(l);return i.has(o)?!1:(i.add(o),!0)})}function wc(e){return{id:`message-${e.id}`,type:"message",createdAt:e.createdAt,message:e}}function Jm(e,t){const n=new Set,i=[...e,...t].filter(l=>n.has(l.id)?!1:(n.add(l.id),!0));return i.filter(l=>p7(l)?!i.some(o=>WN(o,l)):!0)}function ep(e,t){const n=new Map;for(const i of[...e,...t])n.set(i.id,i);return[...n.values()].sort((i,l)=>Date.parse(i.startedAt)-Date.parse(l.startedAt))}function tp(e,t){const n=new Map;for(const i of[...e,...t])n.set(i.id,i);return[...n.values()].sort((i,l)=>i.timelineAt.localeCompare(l.timelineAt)||i.sequence-l.sequence)}function p7(e){return e.id.startsWith("local-")}function WN(e,t){if(p7(e)||e.role!==t.role||e.content.trim()!==t.content.trim())return!1;const n=Date.parse(e.createdAt),i=Date.parse(t.createdAt);return Number.isNaN(n)||Number.isNaN(i)?!1:Math.abs(n-i)<=12e4}function Bd(e,t){const n=new Map,i=new Map;for(const o of[...e,...t]){const c=qi(o);i.has(c)||i.set(c,i.size),n.set(c,o)}return[...n.values()].sort((o,c)=>{const f=g7(o,c);return f!==0?f:(i.get(qi(o))??0)-(i.get(qi(c))??0)})}function t5(e,t){const n=qi(t),i=e.findIndex(o=>qi(o)===n);if(i<0)return[...e,t];if(XN(e[i],t))return e;const l=[...e];return l[i]=t,l}function XN(e,t){return e.turnId===t.turnId&&e.event===t.event&&e.createdAt===t.createdAt&&e.seq===t.seq&&JSON.stringify(e.data)===JSON.stringify(t.data)}function qi(e){return e.id!==void 0?`${typeof e.id}:${e.id}`:`${e.event}:${e.createdAt??""}:${JSON.stringify(e.data)}`}function Bc(e,t){const n=g7(e,t);return n!==0?n:KN(e.id,t.id)}function g7(e,t){if(e.turnId&&t.turnId&&e.turnId===t.turnId&&typeof e.seq=="number"&&typeof t.seq=="number"&&e.seq!==t.seq)return e.seq-t.seq;const n=Date.parse(e.createdAt??""),i=Date.parse(t.createdAt??"");return!Number.isNaN(n)&&!Number.isNaN(i)&&n!==i?n-i:Number.isNaN(n)!==Number.isNaN(i)?Number.isNaN(n)?1:-1:0}function KN(e,t){return e===t?0:e===void 0?1:t===void 0?-1:typeof e=="number"&&typeof t=="number"?e-t:String(e).localeCompare(String(t))}function n5(e,t){const n=Ee(e.data);return typeof n.__seq=="number"&&typeof n.__createdAt=="string"&&Object.prototype.hasOwnProperty.call(n,"payload")?{id:typeof n.__eventId=="string"?n.__eventId:`stream:${n.__turnId??"unknown"}:${n.__seq}`,turnId:typeof n.__turnId=="string"?n.__turnId:null,seq:n.__seq,event:e.event,data:n.payload,createdAt:n.__createdAt}:{id:t,turnId:e.turnId??null,event:e.event,data:e.data,createdAt:e.createdAt??new Date().toISOString()}}const Ec=I.memo(function({content:t,conversation:n,streaming:i,onPreviewArtifact:l,onCopyArtifactUrl:o,copiedArtifactUrl:c}){const f=i?x7(t):Ps(t),h=n&&!i?aM(f,n):[];return u.jsxs(u.Fragment,{children:[i?u.jsx(JN,{content:f,conversation:n}):Yl(f,n),h.length>0?u.jsx("div",{className:"artifact-preview-list",children:h.map(m=>u.jsx(rM,{artifact:m,onPreview:l,onCopyUrl:o,copied:c===m.url},m.id))}):null]})},QN);function QN(e,t){var n,i,l,o;return e.content===t.content&&e.streaming===t.streaming&&e.copiedArtifactUrl===t.copiedArtifactUrl&&((n=e.conversation)==null?void 0:n.id)===((i=t.conversation)==null?void 0:i.id)&&((l=e.conversation)==null?void 0:l.workspacePath)===((o=t.conversation)==null?void 0:o.workspacePath)}function r5({content:e}){return u.jsx("div",{className:"plain-message-content",children:e})}const ZN=2;function JN({content:e,conversation:t}){const n=I.useRef(null),[i,l]=I.useState(null),{committedBlocks:o,activeBlock:c}=eM(e);return I.useLayoutEffect(()=>{const f=n.current;if(!f)return;const h=parseFloat(window.getComputedStyle(f).lineHeight)||28,m=f.scrollHeight;l(y=>{const v=h*ZN,k=Math.min(m,v);return y!==null&&k<=y?y:k})},[e]),u.jsxs("div",{className:"streaming-message-content",ref:n,style:i===null?void 0:{minHeight:i},children:[o.map((f,h)=>u.jsx(I.Fragment,{children:Yl(f,t)},`${h}:${f.length}`)),c?u.jsx("p",{className:"streaming-active-line",children:c}):null]})}function eM(e){const t=nM(e),n=t>0?e.slice(0,t):"",i=e.slice(t);return{committedBlocks:tM(n),activeBlock:i}}function tM(e){const t=[];let n=0,i=!1,l=!1;const o=e.match(/[^\n]*(?:\n|$)/g)??[];let c=0;for(const f of o){if(!f)continue;const h=f.trim(),m=c;if(c+=f.length,/^\s*(```|~~~)/.test(f)){i=!i,i||(Id(t,e.slice(n,c)),n=c);continue}if(i)continue;if(/^\s*\|.*\|\s*$/.test(f)||/^\s*:?-{3,}:?\s*(\|\s*:?-{3,}:?\s*)+\|?\s*$/.test(f)){l=!0;continue}l&&(Id(t,e.slice(n,m)),n=m,l=!1),h===""&&(Id(t,e.slice(n,c)),n=c)}return n<e.length&&Id(t,e.slice(n)),t}function Id(e,t){t.trim()&&e.push(t)}function nM(e){const t=e.lastIndexOf(`
374
+ `);return{id:e.id,type:"system",createdAt:e.createdAt,title:o,detail:c,fullDetail:f||void 0,linkedTaskId:l}}function TN(e,t){if(!Array.isArray(e))return[];const n=new Set,i=[];for(const l of e){const o=Ee(l),c=$e(o.id),f=$e(o.senderWorkspaceId),h=$e(o.contentMarkdown).trim(),m=$e(o.createdAt);!c||n.has(c)||!f||!h||!m||(n.add(c),i.push({id:c,senderWorkspaceId:f,senderName:t.get(f)??($e(o.senderTitleSnapshot)||f),contentMarkdown:h,createdAt:m}))}return i}function c7(e,t){return e.event==="server.collaboration.topic_created"?AN(e,t):EN(e,t)}function AN(e,t){const n=Ee(Ee(e.data).topic),i=$e(n.title).trim()||"Untitled Topic",l=$e(n.publicDescription).trim()||"未填写描述",o=Array.isArray(n.members)?n.members.map(Ee):[],c=$e(n.ownerWorkspaceId),f=o.find(v=>$e(v.role)==="owner"||$e(v.workspaceId)===c),h=$e(f==null?void 0:f.workspaceTitleSnapshot).trim()||"Unknown workspace",m=o.filter(v=>$e(v.role)!=="owner"&&$e(v.status)==="active"),y=m.length?m.map(v=>{const k=$e(v.workspaceTitleSnapshot).trim()||"Unknown workspace";return`- ${Us(k)} (\`${$e(v.workspaceId)}\`)`}):["无"];return{id:`collaboration-topic-created-${e.id}`,type:"system",createdAt:e.createdAt??t,title:"Created",detail:i,visualKind:"topic",fullDetail:["## Topic 已创建","","**名称**","",Us(i),"","**描述**","",Us(l),"","**Owner Workspace**","",`${Us(h)} (\`${c}\`)`,"","**协作 Workspace**","",...y].join(`
375
+ `)}}function EN(e,t){const n=Ee(e.data),i=Yp(e.data),l=Gv(void 0,e.event);return{id:`system-event-${e.id}`,type:"system",createdAt:e.createdAt??t,title:l,detail:$s(n),visualKind:e.event.startsWith("server.collaboration.")?"topic":void 0,fullDetail:[`## ${Us(l)}`,"","**Event**","",`\`${e.event}\``,"","```json",JSON.stringify(i??null,null,2),"```"].join(`
376
+ `)}}function Yp(e,t=""){return Array.isArray(e)?e.map(n=>Yp(n)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([n,i])=>[n,Yp(i,n)])):typeof e=="string"&&(t==="wakeAt"||t==="wake_at")&&Lc(e)||e}function NN(e,t){const n=t.trim();return n?e.filter(i=>i.type==="assistantText"?Ps(i.content).trim()!==n:i.type==="message"&&i.message.role==="assistant"?Ps(i.message.content).trim()!==n:!0):e}function MN(e){return e==="system"||e==="wakeup"||e==="runtime-reset"||e==="clone_initialization"}function zN(e){return e==="runtime-reset"?"Runtime reset":e==="clone_initialization"?"Clone initialization":e==="system"?"System action":"Scheduled wakeup"}function DN(e,t){return e==="runtime-reset"?"Thread rebuilt":e==="clone_initialization"?"Activating inherited context":e==="system"?"Workspace runtime action":t?O7(t,20):"Auto resumed"}function RN(e,t){if(e.some(l=>l.type==="assistantText"))return af(e);if(t.length===0)return e;const n=[...t],i=[];for(const l of e)l.type==="tool"&&$1(l.tool)&&F1(n,l.tool)||i.push(l);return af([...i,...n])}function ON(e,t,n,i){var h;const l=new Map(t.filter(m=>m.id!==void 0).map(m=>[String(m.id),m])),o=new Map,c=new Set;for(const m of e){const y=_N(m,t,l);y.length>0&&c.add(m.id);for(const v of y)o.set(qi(v),v)}if(n)for(const m of t)BN(e,m)||o.set(qi(m),m);else if(t.length>0&&!e.some(m=>m.phase==="process"))for(const m of t)o.set(qi(m),m);const f=d7([...o.values()].sort(Bc),n,i);for(const m of e)if(!c.has(m.id)){if(m.nodeType==="agent_text"&&m.subtype!=="final_answer"&&((h=m.contentMarkdown)!=null&&h.trim())){f.push({id:m.id,type:"assistantText",createdAt:m.createdAt,content:m.contentMarkdown,phase:IN(m),itemId:m.entityType==="codex_item"?m.entityId??void 0:void 0,streaming:n&&m.status==="running"});continue}m.nodeType==="operation"&&f.push({id:m.id,type:"tool",createdAt:m.createdAt,tool:LN(m,i)})}return af(f)}function _N(e,t,n){if(e.entityType==="event"&&e.entityId){const i=n.get(e.entityId);return i&&e.phase==="process"&&e.status==="running"?[i]:[Wp(e)]}if(e.entityType==="codex_item"&&e.entityId){const i=t.filter(l=>H1(l)===e.entityId);return i.length>0?i:[Wp(e)]}return[]}function Wp(e){const t=Ee(e.detail),n=e.subtype==="server.collaboration.message_staged"&&e.phase==="result"?e.status==="failed"?"server.collaboration.message_rejected":$e(t.messageId)?"server.collaboration.message_sent":e.subtype:e.subtype;return{id:e.entityId??e.id,turnId:e.turnId,seq:e.sequence,event:e.entityType==="codex_item"?"codex.notification":n,data:e.detail,createdAt:e.updatedAt||e.createdAt}}function BN(e,t){const n=t.id===void 0?null:String(t.id),i=H1(t);return e.some(l=>n!==null&&l.entityType==="event"&&l.entityId===n||i!==null&&l.entityType==="codex_item"&&l.entityId===i)}function H1(e){if(e.event!=="codex.notification")return null;const t=Ee(e.data),n=Ee(t.params),i=Ee(n.item);return $e(i.id)||$e(n.itemId)||null}function IN(e){return e.subtype==="final_answer"?"final_answer":e.phase==="process"?"commentary":"unknown"}function LN(e,t){var i,l;const n=Ee(e.detail);return{id:e.id,kind:e.status==="failed"?"error":"activity",title:e.subtype==="input:collaboration_notice"?Hp(n,t).title:e.title||_7(e.subtype),body:e.subtype==="input:collaboration_notice"?Hp(n,t).detail:((i=e.summary)==null?void 0:i.trim())||((l=e.contentMarkdown)==null?void 0:l.trim())||E7(n),createdAt:e.createdAt,itemId:e.entityType==="codex_item"?e.entityId??void 0:void 0,meta:e.status}}function d7(e,t,n){const i=[],l=new Map,o=new Map,c=new Map;for(const f of e){if(f.event==="server.workspace_change.decision"||f.event==="server.responsibility.decision"){HN(i,f);continue}if(f.event==="server.knowledge.decision"){FN(i,f);continue}if(h7(f)){VN(i);continue}if(f.event==="server.steer"){const T=Ee(f.data),E=typeof T.message=="string"?T.message.trim():"";i.push({id:`steer-${f.id}`,type:"steerMarker",createdAt:f.createdAt??new Date().toISOString(),content:E||"Additional input",messageId:typeof T.messageId=="string"?T.messageId:void 0});continue}const h=uD(f.data);h!=null&&h.itemId&&c.set(h.itemId,h.phase);const m=oD(f.data);if(m!=null&&m.text){const T=m.itemId?c.get(m.itemId)??m.phase:m.phase,E=m.itemId??`phase:${T}`,q=`${l.get(E)??""}${m.text}`,R=x7(q),B=o.get(E)??"",F=R.startsWith(B)?R.slice(B.length):R;if(l.set(E,q),o.set(E,R),F){const Y=i[i.length-1];(Y==null?void 0:Y.type)==="assistantText"&&GN(Y,m.itemId,T)?(Y.content+=F,Y.itemId=Y.itemId??m.itemId,Y.streamKey=Y.streamKey??E,Y.streaming=t):i.push({id:`assistant-event-${f.id}`,type:"assistantText",createdAt:f.createdAt??new Date().toISOString(),content:F,phase:T,itemId:m.itemId,streamKey:E,streaming:t})}continue}const y=cD(f.data);if(y!=null&&y.text){const T=Ps(y.text),E=y.itemId??`phase:${y.phase}`,q=PN(i,y.itemId,y.phase);if(q>=0){const R=i[q];R.type==="assistantText"&&(T?(R.content=T,R.phase=y.phase,R.itemId=R.itemId??y.itemId,R.streamKey=R.streamKey??E,R.streaming=!1,UN(i,q,y.itemId)):i.splice(q,1))}else T&&i.push({id:`assistant-completed-${f.id}`,type:"assistantText",createdAt:f.createdAt??new Date().toISOString(),content:T,phase:y.phase,itemId:y.itemId,streamKey:E,streaming:!1});continue}const v=_z(f,n);if(v){v.rawEvents=[f];const T=J3(i,v);if(T>=0){e5(i[T],v);continue}if($1(v)&&F1(i,v)||v.kind==="command"&&v.meta==="running"&&lf(v.body))continue;i.push({id:`tool-${v.id}`,type:"tool",createdAt:v.createdAt,tool:v});continue}const k=Bz(f);if(k){k.rawEvents=[f];const T=J3(i,k);if(T>=0){e5(i[T],k);continue}i.push({id:`tool-${k.id}`,type:"tool",createdAt:k.createdAt,tool:k});continue}if(TA(f)){qN(i,f);continue}const w=Iz(f);w&&(w.rawEvents=[f],i.push({id:`tool-${w.id}`,type:"tool",createdAt:w.createdAt,tool:w}))}return af(i)}function qN(e,t){const n=H1(t);if(n)for(let i=e.length-1;i>=0;i-=1){const l=e[i];if(!(l.type!=="tool"||l.tool.itemId!==n)){l.tool={...l.tool,rawEvents:m7(l.tool.rawEvents,[t])};return}}}function UN(e,t,n){if(n)for(let i=e.length-1;i>t;i-=1){const l=e[i];l.type==="assistantText"&&l.itemId===n&&e.splice(i,1)}}function HN(e,t){const n=Ee(t.data),i=typeof n.proposalId=="string"?n.proposalId:void 0,l=typeof n.decision=="string"?n.decision:void 0,o=Ee(n.payload),c=$e(o.content)||(typeof n.responsibility=="string"?n.responsibility:void 0);if(!(!i||l!=="accept"&&l!=="decline"))for(let f=e.length-1;f>=0;f-=1){const h=e[f];if(h.type==="tool"&&(h.tool.kind==="responsibility"||h.tool.kind==="workspaceChange")&&(h.tool.workspaceChangeProposalId===i||h.tool.responsibilityProposalId===i)){const m=KA(h.tool.meta,l);h.tool={...h.tool,title:m==="saved"?"Workspace change applied":"Workspace change declined",meta:m,body:m==="saved"?c??h.tool.body:h.tool.body,workspaceChangePayload:m==="saved"&&Object.keys(o).length>0?o:h.tool.workspaceChangePayload};return}}}function FN(e,t){const n=Ee(t.data),i=typeof n.proposalId=="string"?n.proposalId:void 0,l=typeof n.decision=="string"?n.decision:void 0,o=Ee(n.knowledge);if(!(!i||l!=="accept"&&l!=="decline"))for(let c=e.length-1;c>=0;c-=1){const f=e[c];if(f.type==="tool"&&f.tool.kind==="knowledge"&&f.tool.knowledgeProposalId===i){f.tool={...f.tool,title:l==="accept"?"Knowledge saved":"Knowledge proposal declined",meta:l==="accept"?"saved":"declined",body:l==="accept"&&Object.keys(o).length>0?JSON.stringify(o,null,2):f.tool.body};return}}}function F1(e,t){const n=f7(t);if(typeof n!="number")return!1;for(let o=0;o<e.length;o+=1){const c=e[o];if(c.type!=="assistantText"||!Z3(c,t))continue;const f=Ps(c.content);f!==c.content&&(e[o]={...c,content:f})}let i=0,l=-1;for(let o=0;o<e.length;o+=1){const c=e[o];if(c.type!=="assistantText"||!Z3(c,t))continue;l=o;const f=i,h=f+c.content.length;if(i=h,n>=h)continue;const m=Math.max(0,Math.min(c.content.length,n-f)),y=c.content.slice(0,m).trimEnd(),v=c.content.slice(m).trimStart(),k=[];return y&&k.push({...c,id:`${c.id}:before-tool-${t.id}`,content:y,pinnedToResult:!0}),k.push({id:`tool-${t.id}`,type:"tool",createdAt:t.createdAt,tool:t}),v&&k.push({...c,id:`${c.id}:after-tool-${t.id}`,content:v,pinnedToResult:!0}),e.splice(o,1,...k),!0}if(l>=0&&n>=i){const o=e[l];return(o==null?void 0:o.type)==="assistantText"&&(e[l]={...o,pinnedToResult:!0}),e.splice(l+1,0,{id:`tool-${t.id}`,type:"tool",createdAt:t.createdAt,tool:t}),!0}return!1}function Z3(e,t){return!t.anchorStreamKey||e.streamKey===t.anchorStreamKey}function af(e){const t=[],n=[];for(const o of e){if(o.type==="tool"&&$1(o.tool)){t.push(o.tool);continue}n.push(o)}const i=[...n],l=[];for(const o of t)F1(i,o)||l.push({id:`tool-${o.id}`,type:"tool",createdAt:o.createdAt,tool:o});return $N([...l,...i])}function $1(e){return typeof f7(e)=="number"}function f7(e){if(typeof e.anchorOffset=="number")return e.anchorOffset;if(e.kind==="responsibility")return e.responsibilityAnchorOffset;if(e.kind==="knowledge")return e.knowledgeAnchorOffset}function $N(e){const t=[];for(let n=0;n<e.length;n+=1){const i=e[n],l=e[n+1];if((i==null?void 0:i.type)==="tool"&&i.tool.kind==="responsibility"&&typeof i.tool.responsibilityAnchorOffset!="number"&&(l==null?void 0:l.type)==="assistantText"){t.push({...l,pinnedToResult:!0}),t.push(i),n+=1;continue}t.push(i)}return t}function GN(e,t,n){return e.type!=="assistantText"?!1:e.itemId&&t?e.itemId===t:e.itemId||t?!1:e.phase===n}function PN(e,t,n){if(t){const i=e.findIndex(l=>l.type==="assistantText"&&l.itemId===t);if(i>=0)return i}for(let i=e.length-1;i>=0;i-=1){const l=e[i];if(l.type==="assistantText"&&l.streaming&&(!t||!l.itemId)&&(l.phase===n||l.phase==="unknown"||n==="unknown"))return i}return-1}function h7(e){return e.event==="server.stop"||e.event==="server.stopped"}function VN(e){for(const t of e)t.type==="tool"&&t.tool.kind==="command"&&t.tool.meta==="running"&&(t.tool={...t.tool,title:"Command stopped",meta:"stopped"})}function YN(e){for(let t=e.length-1;t>=0;t-=1){const n=e[t];if(n.event!=="server.notification.failed")continue;const i=Ee(n.data);return typeof i.message=="string"?i.message:"Notification failed"}return null}function WN(e){for(let t=e.length-1;t>=0;t-=1){const n=B7(e[t]);if(n)return n}return null}function J3(e,t){for(let n=e.length-1;n>=0;n-=1){const i=e[n];if(i.type==="tool"&&i.tool.kind===t.kind&&(t.itemId&&i.tool.itemId===t.itemId||i.tool.body===t.body&&i.tool.meta==="running"))return n}return-1}function e5(e,t){if(e.type!=="tool")return;const n=e.tool.kind==="command"&&e.tool.meta!=="running"&&t.meta==="running",i=e.tool.kind==="command"&&t.kind==="command"&&lf(t.body)&&!lf(e.tool.body);e.tool={...e.tool,...t,id:e.tool.id,createdAt:e.tool.createdAt,title:n?e.tool.title:t.title,body:i?e.tool.body:t.body,meta:n?e.tool.meta:t.meta,output:Qz(e.tool.output,t.output),topicRecipientLabel:t.topicRecipientLabel??e.tool.topicRecipientLabel,topicMessageContent:t.topicMessageContent??e.tool.topicMessageContent,rawEvents:m7(e.tool.rawEvents,t.rawEvents)}}function m7(e,t){const n=[...e??[],...t??[]];if(n.length===0)return;const i=new Set;return n.filter(l=>{const o=qi(l);return i.has(o)?!1:(i.add(o),!0)})}function wc(e){return{id:`message-${e.id}`,type:"message",createdAt:e.createdAt,message:e}}function Jm(e,t){const n=new Set,i=[...e,...t].filter(l=>n.has(l.id)?!1:(n.add(l.id),!0));return i.filter(l=>p7(l)?!i.some(o=>XN(o,l)):!0)}function ep(e,t){const n=new Map;for(const i of[...e,...t])n.set(i.id,i);return[...n.values()].sort((i,l)=>Date.parse(i.startedAt)-Date.parse(l.startedAt))}function tp(e,t){const n=new Map;for(const i of[...e,...t])n.set(i.id,i);return[...n.values()].sort((i,l)=>i.timelineAt.localeCompare(l.timelineAt)||i.sequence-l.sequence)}function p7(e){return e.id.startsWith("local-")}function XN(e,t){if(p7(e)||e.role!==t.role||e.content.trim()!==t.content.trim())return!1;const n=Date.parse(e.createdAt),i=Date.parse(t.createdAt);return Number.isNaN(n)||Number.isNaN(i)?!1:Math.abs(n-i)<=12e4}function Bd(e,t){const n=new Map,i=new Map;for(const o of[...e,...t]){const c=qi(o);i.has(c)||i.set(c,i.size),n.set(c,o)}return[...n.values()].sort((o,c)=>{const f=g7(o,c);return f!==0?f:(i.get(qi(o))??0)-(i.get(qi(c))??0)})}function t5(e,t){const n=qi(t),i=e.findIndex(o=>qi(o)===n);if(i<0)return[...e,t];if(KN(e[i],t))return e;const l=[...e];return l[i]=t,l}function KN(e,t){return e.turnId===t.turnId&&e.event===t.event&&e.createdAt===t.createdAt&&e.seq===t.seq&&JSON.stringify(e.data)===JSON.stringify(t.data)}function qi(e){return e.id!==void 0?`${typeof e.id}:${e.id}`:`${e.event}:${e.createdAt??""}:${JSON.stringify(e.data)}`}function Bc(e,t){const n=g7(e,t);return n!==0?n:QN(e.id,t.id)}function g7(e,t){if(e.turnId&&t.turnId&&e.turnId===t.turnId&&typeof e.seq=="number"&&typeof t.seq=="number"&&e.seq!==t.seq)return e.seq-t.seq;const n=Date.parse(e.createdAt??""),i=Date.parse(t.createdAt??"");return!Number.isNaN(n)&&!Number.isNaN(i)&&n!==i?n-i:Number.isNaN(n)!==Number.isNaN(i)?Number.isNaN(n)?1:-1:0}function QN(e,t){return e===t?0:e===void 0?1:t===void 0?-1:typeof e=="number"&&typeof t=="number"?e-t:String(e).localeCompare(String(t))}function n5(e,t){const n=Ee(e.data);return typeof n.__seq=="number"&&typeof n.__createdAt=="string"&&Object.prototype.hasOwnProperty.call(n,"payload")?{id:typeof n.__eventId=="string"?n.__eventId:`stream:${n.__turnId??"unknown"}:${n.__seq}`,turnId:typeof n.__turnId=="string"?n.__turnId:null,seq:n.__seq,event:e.event,data:n.payload,createdAt:n.__createdAt}:{id:t,turnId:e.turnId??null,event:e.event,data:e.data,createdAt:e.createdAt??new Date().toISOString()}}const Ec=I.memo(function({content:t,conversation:n,streaming:i,onPreviewArtifact:l,onCopyArtifactUrl:o,copiedArtifactUrl:c}){const f=i?x7(t):Ps(t),h=n&&!i?iM(f,n):[];return u.jsxs(u.Fragment,{children:[i?u.jsx(eM,{content:f,conversation:n}):Yl(f,n),h.length>0?u.jsx("div",{className:"artifact-preview-list",children:h.map(m=>u.jsx(aM,{artifact:m,onPreview:l,onCopyUrl:o,copied:c===m.url},m.id))}):null]})},ZN);function ZN(e,t){var n,i,l,o;return e.content===t.content&&e.streaming===t.streaming&&e.copiedArtifactUrl===t.copiedArtifactUrl&&((n=e.conversation)==null?void 0:n.id)===((i=t.conversation)==null?void 0:i.id)&&((l=e.conversation)==null?void 0:l.workspacePath)===((o=t.conversation)==null?void 0:o.workspacePath)}function r5({content:e}){return u.jsx("div",{className:"plain-message-content",children:e})}const JN=2;function eM({content:e,conversation:t}){const n=I.useRef(null),[i,l]=I.useState(null),{committedBlocks:o,activeBlock:c}=tM(e);return I.useLayoutEffect(()=>{const f=n.current;if(!f)return;const h=parseFloat(window.getComputedStyle(f).lineHeight)||28,m=f.scrollHeight;l(y=>{const v=h*JN,k=Math.min(m,v);return y!==null&&k<=y?y:k})},[e]),u.jsxs("div",{className:"streaming-message-content",ref:n,style:i===null?void 0:{minHeight:i},children:[o.map((f,h)=>u.jsx(I.Fragment,{children:Yl(f,t)},`${h}:${f.length}`)),c?u.jsx("p",{className:"streaming-active-line",children:c}):null]})}function tM(e){const t=rM(e),n=t>0?e.slice(0,t):"",i=e.slice(t);return{committedBlocks:nM(n),activeBlock:i}}function nM(e){const t=[];let n=0,i=!1,l=!1;const o=e.match(/[^\n]*(?:\n|$)/g)??[];let c=0;for(const f of o){if(!f)continue;const h=f.trim(),m=c;if(c+=f.length,/^\s*(```|~~~)/.test(f)){i=!i,i||(Id(t,e.slice(n,c)),n=c);continue}if(i)continue;if(/^\s*\|.*\|\s*$/.test(f)||/^\s*:?-{3,}:?\s*(\|\s*:?-{3,}:?\s*)+\|?\s*$/.test(f)){l=!0;continue}l&&(Id(t,e.slice(n,m)),n=m,l=!1),h===""&&(Id(t,e.slice(n,c)),n=c)}return n<e.length&&Id(t,e.slice(n)),t}function Id(e,t){t.trim()&&e.push(t)}function rM(e){const t=e.lastIndexOf(`
371
377
  `);if(t<0)return 0;const n=[0];for(let l=0;l<e.length;l+=1)e[l]===`
372
378
  `&&l+1<e.length&&n.push(l+1);let i=-1;for(const l of n){const o=e.indexOf(`
373
- `,l),c=e.slice(l,o===-1?e.length:o);/^\s*(```|~~~)/.test(c)&&(i=i===-1?l:-1)}return i>=0?i:t+1}function rM({artifact:e,onPreview:t,onCopyUrl:n,copied:i}){return e?u.jsxs("figure",{className:"artifact-preview",children:[u.jsx("button",{className:"artifact-preview-media",onClick:()=>t(e),type:"button",children:u.jsx("img",{alt:e.name,src:e.url})}),u.jsxs("figcaption",{children:[u.jsx("span",{children:e.name}),u.jsxs("div",{className:"artifact-preview-actions",children:[u.jsx("button",{onClick:()=>t(e),type:"button",children:"Preview"}),u.jsx("a",{href:e.url,rel:"noreferrer",target:"_blank",children:"Open"}),u.jsx("button",{onClick:()=>n(e),type:"button",children:i?"Copied":"Copy"})]})]})]}):null}function aM(e,t){const n=new Map;for(const i of iM(e)){const l=y7(i);if(l){const o=v7(l).toLowerCase(),c=n.get(o);(!c||oM(l,c))&&n.set(o,l)}}return Array.from(n.values()).map(i=>lM(i,t)).filter(i=>i!==null)}function iM(e){const t=[],n=/!\[[^\]]*]\(([^)]+)\)/g,i=/\[[^\]]+]\(([^)]+)\)/g,l=/(?:artifact|preview|image|file)\s*:\s*(`?[^`\n]+?\.(?:svg|png|jpe?g|webp|gif)`?)/gim;for(const o of[n,i,l]){let c;for(;(c=o.exec(e))!==null;)t.push(c[1])}return t}function lM(e,t){const n=y7(e);if(!n||!sM(n))return null;const i=Xv(n,t.workspacePath);return{id:`${t.id}:${i}`,path:i,name:v7(i),url:Ne(`conversations/${t.id}/files?path=${encodeURIComponent(i)}`)}}function y7(e){const t=e.trim().replace(/^`+|`+$/g,"").replace(/[),.;:,。;:]+$/g,"");return t||null}function sM(e){return/\.(?:svg|png|jpe?g|webp|gif)$/i.test(e)}function v7(e){return e.replace(/\\/g,"/").split("/").filter(Boolean).pop()??e}function oM(e,t){return e.startsWith("/")&&!t.startsWith("/")?!0:e.length>t.length}function Ps(e){return e.trim()}function x7(e){return e.trim()}function a5(e){return e instanceof DOMException&&e.name==="AbortError"||e instanceof Error&&e.name==="AbortError"}function uM(e){return{a({children:t,href:n}){if(!n)return u.jsx(u.Fragment,{children:t});const i=/^[a-z][a-z\d+.-]*:/i.test(n),l=!i&&e?cM(n,e):null,o=l??n,c=i||!!l;return u.jsx("a",{className:"markdown-link",href:o,rel:c?"noreferrer":void 0,target:c?"_blank":void 0,children:t})},img(){return null},pre({children:t}){const n=fM(t);return n?G1(n.language)==="mermaid"?u.jsx(hM,{code:n.code}):u.jsx(gM,{code:n.code,language:n.language}):u.jsx("pre",{children:t})},table({children:t}){return u.jsx("div",{className:"markdown-table-wrap",children:u.jsx("table",{className:"markdown-table",children:t})})},td({align:t,children:n}){return u.jsx("td",{style:i5(t),children:n})},th({align:t,children:n}){return u.jsx("th",{style:i5(t),children:n})}}}function cM(e,t){if(!e||e.startsWith("#")||e.startsWith("/api/")||e.startsWith("?"))return null;const n=ZA(e,t.workspacePath);if(!n)return null;const i=n.line?`#L${n.line}${n.column?`C${n.column}`:""}`:"";return`${Ne(`conversations/${t.id}/files?path=${encodeURIComponent(n.path)}`)}${i}`}function i5(e){return e&&e!=="char"?{textAlign:e}:void 0}function Yl(e,t){const n=dM(e);return u.jsx(Ck,{components:uM(t),remarkPlugins:[BC,LT],rehypePlugins:[[gA,{trust:!1,strict:"ignore"}]],skipHtml:!0,children:n})}function dM(e){return e.replace(/([^\n])(```[^\n`]*(?:\r?\n|$))/g,`$1
374
- $2`)}function fM(e){var o;const t=I.Children.toArray(e),n=t.length===1&&I.isValidElement(t[0])?t[0]:null;if(!n||n.type!=="code")return null;const l=((o=(n.props.className??"").match(/(?:^|\s)language-([^\s]+)/))==null?void 0:o[1])??"";return{code:Xp(n.props.children).replace(/\n$/,""),language:l}}function Xp(e){return e==null||typeof e=="boolean"?"":typeof e=="string"||typeof e=="number"||typeof e=="bigint"?String(e):Array.isArray(e)?e.map(Xp).join(""):I.isValidElement(e)?Xp(e.props.children):""}const b7="github-light",np=new Map,rp=new Map;let ap=null,ip=null;const w7=new Set(["bash","css","diff","dockerfile","html","java","javascript","json","jsonc","jsx","markdown","python","shellscript","sql","toml","tsx","typescript","xml","yaml"]);function G1(e){const t=e.trim().toLowerCase().replace(/^\./,"");return{bash:"bash",cjs:"javascript",console:"shellscript",htm:"html",js:"javascript",jsx:"jsx",md:"markdown",mjs:"javascript",py:"python",rb:"ruby",shell:"bash",ts:"typescript",tsx:"tsx",yml:"yaml",zsh:"bash"}[t]??t}function k7(e){const t=G1(e);return!t||t==="text"||t==="txt"?"text":w7.has(t)?t:"text"}function hM({code:e}){const n=`seele-mermaid-${I.useId().replace(/[^a-zA-Z0-9_-]/g,"")}`,[i,l]=I.useState(!1),[o,c]=I.useState(()=>rp.get(e)??null),[f,h]=I.useState(null);I.useEffect(()=>{let y=!1,v;const k=rp.get(e);return k?(c(k),h(null),()=>{y=!0}):(h(null),c(null),mM(n,e).then(w=>{y||(v!==void 0&&window.clearTimeout(v),rp.set(e,w),c(w),h(null))},w=>{if(!y){const T=w instanceof Error?w.message:String(w);v=window.setTimeout(()=>{y||h(T)},uE)}}),()=>{y=!0,v!==void 0&&window.clearTimeout(v)})},[e,n]);async function m(){await navigator.clipboard.writeText(e),l(!0),window.setTimeout(()=>l(!1),1200)}return u.jsxs("figure",{className:`mermaid-block${f?" error":""}`,children:[u.jsx("span",{className:"code-block-kind",children:"mermaid"}),u.jsx("div",{className:"code-block-tools",children:u.jsx("button",{"aria-label":i?"Copied Mermaid source":"Copy Mermaid source",className:i?"copied":"",onClick:()=>void m(),title:i?"Copied":"Copy",type:"button",children:u.jsx(P1,{})})}),o?u.jsx("div",{className:"mermaid-diagram",dangerouslySetInnerHTML:{__html:o}}):f?u.jsxs("div",{className:"mermaid-error",children:[u.jsx("strong",{children:"Mermaid render failed"}),u.jsx("pre",{children:f}),u.jsx("code",{children:e})]}):u.jsx("div",{className:"mermaid-loading",children:"Rendering diagram..."})]})}async function mM(e,t){return(await(await pM()).render(e,t)).svg}function pM(){return ip||(ip=en(()=>import("./mermaid.core-BjW4FHdg.js").then(e=>e.bp),[],import.meta.url).then(e=>{const t=e.default;return t.initialize({startOnLoad:!1,securityLevel:"strict",theme:"base",themeVariables:{background:"#ffffff",primaryColor:"#f9fafa",primaryBorderColor:"#d8d9e8",primaryTextColor:"#0b0f16",lineColor:"#7a8294",secondaryColor:"#f5f5fb",tertiaryColor:"#ffffff",fontFamily:'Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif'}}),t})),ip}function gM({code:e,language:t,reserveHeight:n=!1}){const[i,l]=I.useState(!1),[o,c]=I.useState(()=>{if(!o5(t))return null;const m=s5(e,t);return np.get(m)??null}),f=n?{"--code-block-min-height":`${bE(e)}px`}:void 0;I.useEffect(()=>{let m=!1;if(!o5(t))return c(null),()=>{m=!0};const y=s5(e,t),v=np.get(y);return v?(c(v),()=>{m=!0}):(c(null),CM(e,t).then(k=>{np.set(y,k),m||c(k)}).catch(k=>{console.warn("Failed to highlight code block",k),m||c(null)}),()=>{m=!0})},[e,t]);async function h(){await navigator.clipboard.writeText(e),l(!0),window.setTimeout(()=>l(!1),1200)}return u.jsxs("figure",{className:"code-block",style:f,children:[t?u.jsx("span",{className:"code-block-kind",children:t}):null,u.jsx("div",{className:"code-block-tools",children:u.jsx("button",{"aria-label":i?"Copied code block":"Copy code block",className:i?"copied":"",onClick:()=>void h(),title:i?"Copied":"Copy",type:"button",children:u.jsx(P1,{})})}),o?u.jsx("div",{className:"code-block-shiki",dangerouslySetInnerHTML:{__html:o}}):u.jsx("pre",{children:u.jsx("code",{children:e})})]})}function P1(){return u.jsxs("svg",{"aria-hidden":"true",fill:"none",height:"13",viewBox:"0 0 24 24",width:"13",children:[u.jsx("rect",{height:"14",rx:"2",stroke:"currentColor",strokeWidth:"2",width:"14",x:"8",y:"8"}),u.jsx("path",{d:"M4 16V6a2 2 0 0 1 2-2h10",stroke:"currentColor",strokeLinecap:"round",strokeWidth:"2"})]})}function yM(){return u.jsxs("svg",{"aria-hidden":"true",fill:"none",height:"16",viewBox:"0 0 24 24",width:"16",children:[u.jsx("circle",{cx:"6",cy:"5",r:"2",stroke:"currentColor",strokeWidth:"2"}),u.jsx("circle",{cx:"18",cy:"5",r:"2",stroke:"currentColor",strokeWidth:"2"}),u.jsx("circle",{cx:"12",cy:"19",r:"2",stroke:"currentColor",strokeWidth:"2"}),u.jsx("path",{d:"M6 7v1a6 6 0 0 0 6 6v3M18 7v1a6 6 0 0 1-6 6",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2"})]})}function S7(){return u.jsxs("svg",{"aria-hidden":"true",fill:"none",height:"12",viewBox:"0 0 24 24",width:"12",children:[u.jsx("circle",{cx:"12",cy:"12",r:"9",stroke:"currentColor",strokeWidth:"2.2"}),u.jsx("path",{d:"M12 7v6",stroke:"currentColor",strokeLinecap:"round",strokeWidth:"2.4"}),u.jsx("circle",{cx:"12",cy:"17",fill:"currentColor",r:"1.25"})]})}function vM(){return u.jsx("svg",{"aria-hidden":"true",fill:"none",height:"18",viewBox:"0 0 24 24",width:"18",children:u.jsx("path",{d:"M4 7h16M4 12h16M4 17h16",stroke:"currentColor",strokeLinecap:"round",strokeWidth:"2"})})}function xM(){return u.jsxs("svg",{"aria-hidden":"true",fill:"none",height:"14",viewBox:"0 0 24 24",width:"14",children:[u.jsx("path",{d:"M7 7h10M7 12h10M7 17h10",stroke:"currentColor",strokeLinecap:"round",strokeWidth:"2"}),u.jsx("circle",{cx:"4",cy:"7",fill:"currentColor",r:"1.4"}),u.jsx("circle",{cx:"4",cy:"12",fill:"currentColor",r:"1.4"}),u.jsx("circle",{cx:"4",cy:"17",fill:"currentColor",r:"1.4"})]})}function l5(){return u.jsxs("svg",{"aria-hidden":"true",fill:"none",height:"14",viewBox:"0 0 24 24",width:"14",children:[u.jsx("circle",{cx:"12",cy:"12",r:"3",stroke:"currentColor",strokeWidth:"2"}),u.jsx("path",{d:"M19 12a7.8 7.8 0 0 0-.1-1l2-1.5-2-3.4-2.4 1a8 8 0 0 0-1.8-1l-.3-2.6h-4l-.3 2.6a8 8 0 0 0-1.8 1l-2.4-1-2 3.4 2 1.5a7.8 7.8 0 0 0 0 2l-2 1.5 2 3.4 2.4-1a8 8 0 0 0 1.8 1l.3 2.6h4l.3-2.6a8 8 0 0 0 1.8-1l2.4 1 2-3.4-2-1.5c.1-.3.1-.7.1-1Z",stroke:"currentColor",strokeLinejoin:"round",strokeWidth:"1.7"})]})}function bM(){return u.jsxs("svg",{"aria-hidden":"true",fill:"none",height:"14",viewBox:"0 0 24 24",width:"14",children:[u.jsx("rect",{height:"16",rx:"2.6",stroke:"currentColor",strokeWidth:"1.8",width:"18",x:"3",y:"4"}),u.jsx("path",{d:"m7 9 3 3-3 3M12.5 15h4.5",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"1.9"})]})}function Gd(){return u.jsxs("svg",{"aria-hidden":"true",fill:"none",height:"17",viewBox:"0 0 24 24",width:"17",children:[u.jsx("circle",{cx:"7",cy:"12",r:"2.4",stroke:"currentColor",strokeWidth:"1.8"}),u.jsx("circle",{cx:"17",cy:"7",r:"2.4",stroke:"currentColor",strokeWidth:"1.8"}),u.jsx("circle",{cx:"17",cy:"17",r:"2.4",stroke:"currentColor",strokeWidth:"1.8"}),u.jsx("path",{d:"m9.2 10.9 5.6-2.8M9.2 13.1l5.6 2.8",stroke:"currentColor",strokeLinecap:"round",strokeWidth:"1.8"})]})}function Ef(){return u.jsxs("svg",{"aria-hidden":"true",fill:"none",height:"13",viewBox:"0 0 24 24",width:"13",children:[u.jsx("path",{d:"m4 16-.8 4 4-.8L18.4 8 15.2 4.8 4 16Z",stroke:"currentColor",strokeLinejoin:"round",strokeWidth:"2"}),u.jsx("path",{d:"m13.8 6.2 3.2 3.2",stroke:"currentColor",strokeLinecap:"round",strokeWidth:"2"})]})}function wM(){return u.jsx("svg",{"aria-hidden":"true",fill:"none",height:"14",viewBox:"0 0 24 24",width:"14",children:u.jsx("path",{d:"M5 8v11h14V8M4 4h16v4H4zM9 12h6",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2"})})}function kM(){return u.jsxs("svg",{"aria-hidden":"true",fill:"none",height:"14",viewBox:"0 0 24 24",width:"14",children:[u.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",stroke:"currentColor",strokeLinejoin:"round",strokeWidth:"2"}),u.jsx("circle",{cx:"12",cy:"12",r:"3",stroke:"currentColor",strokeWidth:"2"})]})}function SM(){return u.jsxs("svg",{"aria-hidden":"true",fill:"none",height:"14",viewBox:"0 0 24 24",width:"14",children:[u.jsx("path",{d:"M3 3l18 18",stroke:"currentColor",strokeLinecap:"round",strokeWidth:"2"}),u.jsx("path",{d:"M9.9 5.4A9.8 9.8 0 0 1 12 5c6 0 9.5 7 9.5 7a15.5 15.5 0 0 1-3 3.8M6.2 6.8C3.8 8.4 2.5 12 2.5 12s3.5 7 9.5 7a9.7 9.7 0 0 0 4-.8",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2"})]})}function s5(e,t){return`${b7}:${k7(t)}:${e}`}function o5(e){const t=G1(e);return!!t&&w7.has(t)}async function CM(e,t){return(await jM()).codeToHtml(e,{lang:k7(t),theme:b7})}function jM(){return ap||(ap=TM()),ap}async function TM(){const[{createHighlighterCore:e},{createJavaScriptRegexEngine:t},{default:n},{default:i},{default:l},{default:o},{default:c},{default:f},{default:h},{default:m},{default:y},{default:v},{default:k},{default:w},{default:T},{default:E},{default:q},{default:R},{default:B},{default:F},{default:Y},{default:te}]=await Promise.all([en(()=>import("./core-0O0cuLx6.js"),[],import.meta.url),en(()=>import("./engine-javascript-DBd1bXLz.js"),[],import.meta.url),en(()=>import("./github-light-DAi9KRSo.js"),[],import.meta.url),en(()=>import("./bash-BELqPA7S.js").then(_=>_.b),[],import.meta.url),en(()=>import("./css-CLj8gQPS.js"),[],import.meta.url),en(()=>import("./diff-D97Zzqfu.js"),[],import.meta.url),en(()=>import("./dockerfile-BcOcwvcX.js"),[],import.meta.url),en(()=>import("./html-pp8916En.js"),__vite__mapDeps([0,1,2]),import.meta.url),en(()=>import("./java-CylS5w8V.js"),[],import.meta.url),en(()=>import("./javascript-wDzz0qaB.js"),[],import.meta.url),en(()=>import("./json-Cp-IABpG.js"),[],import.meta.url),en(()=>import("./jsonc-Des-eS-w.js"),[],import.meta.url),en(()=>import("./jsx-g9-lgVsj.js"),[],import.meta.url),en(()=>import("./markdown-Cvjx9yec.js"),[],import.meta.url),en(()=>import("./python-B6aJPvgy.js"),[],import.meta.url),en(()=>import("./bash-BELqPA7S.js").then(_=>_.s),[],import.meta.url),en(()=>import("./sql-CRqJ_cUM.js"),[],import.meta.url),en(()=>import("./toml-vGWfd6FD.js"),[],import.meta.url),en(()=>import("./tsx-COt5Ahok.js"),[],import.meta.url),en(()=>import("./typescript-BPQ3VLAy.js"),[],import.meta.url),en(()=>import("./xml-sdJ4AIDG.js"),__vite__mapDeps([3,4]),import.meta.url),en(()=>import("./yaml-Buea-lGh.js"),[],import.meta.url)]);return e({engine:t(),themes:[n],langs:[i,l,o,c,f,h,m,y,v,k,w,T,E,q,R,B,F,Y,te]})}async function u5(){const e=Ne("conversations"),t=await fetch(e);return await He(t,{url:e}),(await t.json()).conversations}async function AM(){const e=Ne("workspace-states"),t=await fetch(e);return await He(t,{url:e}),(await t.json()).workspaces}async function c5(){const e=Ne("collaboration/topics"),t=await fetch(e);return await He(t,{url:e}),(await t.json()).topics}async function Ld(e){const t=Ne(`collaboration/topics/${e}/messages?limit=100`),n=await fetch(t);return await He(n,{url:t}),(await n.json()).messages}async function EM(e){const t=Ne("collaboration/topics"),n=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});return await He(n,{method:"POST",url:t}),(await n.json()).topic}async function NM(e,t){const n=Ne(`collaboration/topics/${e}`),i=await fetch(n,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});return await He(i,{method:"PATCH",url:n}),(await i.json()).topic}async function MM(e,t){const n=Ne(`collaboration/topics/${e}/archive`),i=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({expectedVersion:t})});return await He(i,{method:"POST",url:n}),(await i.json()).topic}async function zM(e){const t=Ne(`conversations/${e}/read`),n=await fetch(t,{method:"POST"});await He(n,{method:"POST",url:t})}async function d5(){const e=Ne("workspace-groups"),t=await fetch(e);return await He(t,{url:e}),(await t.json()).groups}async function DM(e){const t=Ne("workspace-groups"),n=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:e})});return await He(n,{method:"POST",url:t}),(await n.json()).group}async function RM(e,t){const n=Ne(`workspace-groups/${e}`),i=await fetch(n,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});return await He(i,{method:"PATCH",url:n}),(await i.json()).group}async function OM(e){const t=Ne(`workspace-groups/${e}`),n=await fetch(t,{method:"DELETE"});return await He(n,{method:"DELETE",url:t}),await n.json()}async function _M(){const e=Ne("settings/environment"),t=await fetch(e);return await He(t,{url:e}),(await t.json()).variables}async function BM(e){const t=Ne(`conversations/${e}/settings/environment`),n=await fetch(t);return await He(n,{url:t}),(await n.json()).variables}async function IM(e){const t=Ne(`conversations/${e}/knowledge`),n=await fetch(t);return await He(n,{url:t}),(await n.json()).items}async function LM(){const e=Ne("settings/runtime"),t=await fetch(e);return await He(t,{url:e}),(await t.json()).settings}async function qM(){const e=Ne("settings/deployment"),t=await fetch(e);return await He(t,{url:e}),(await t.json()).settings}async function UM(){const e=Ne("diagnostics"),t=await fetch(e);return await He(t,{url:e}),await t.json()}async function HM(){const e=Ne("settings/runtime/codex"),t=await fetch(e);return await He(t,{url:e}),await t.json()}async function f5(){const e=Ne("settings/runtime/accounts"),t=await fetch(e);await He(t,{url:e});const n=await t.json();return Xs(),n}async function lp(e=!1){const t=Ne(`settings/runtime/accounts/refresh${e?"?force=1":""}`),n=await fetch(t,{method:"POST"});await He(n,{method:"POST",url:t});const i=await n.json();return Xs(),i}async function FM(e){const t=Ne("settings/runtime/accounts"),n=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:e})});await He(n,{method:"POST",url:t});const i=await n.json();return i.login.status==="succeeded"&&Xs(),i.login}async function $M(e){const t=Ne(`settings/runtime/accounts/login/${e}`),n=await fetch(t);return await He(n,{url:t}),(await n.json()).login}async function GM(e){const t=Ne(`settings/runtime/accounts/login/${e}/cancel`),n=await fetch(t,{method:"POST"});return await He(n,{method:"POST",url:t}),(await n.json()).login}async function PM(e,t){const n=Ne(`settings/runtime/accounts/${e}`),i=await fetch(n,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:t})});await He(i,{method:"PATCH",url:n});const l=await i.json();return Xs(),l.account}async function VM(e){const t=Ne(`settings/runtime/accounts/${e}`),n=await fetch(t,{method:"DELETE"});await He(n,{method:"DELETE",url:t}),Xs()}async function YM(e){const t=Ne(`settings/runtime/accounts/${e}/switch`),n=await fetch(t,{method:"POST"});await He(n,{method:"POST",url:t});const i=await n.json();return Xs(),i}async function WM(e=!0){const t=Ne(`settings/runtime/models?refresh=${e?"1":"0"}`),n=await fetch(t);return await He(n,{url:t}),await n.json()}async function XM(e=!1){const t=Ne(`settings/runtime/codex/update${e?"?refreshLatest=1":""}`),n=await fetch(t);return await He(n,{url:t}),await n.json()}async function KM(){const e=Ne("settings/runtime/codex/update"),t=await fetch(e,{method:"POST"});return await He(t,{method:"POST",url:e}),(await t.json()).job}async function QM(e){const t=Ne(`conversations/${e}/settings/runtime`),n=await fetch(t);return await He(n,{url:t}),(await n.json()).settings}async function ZM(){const e=Ne("settings/memory"),t=await fetch(e);return await He(t,{url:e}),await t.json()}async function JM(e){const t=Ne("settings/runtime"),n=await fetch(t,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});return await He(n,{method:"PUT",url:t}),(await n.json()).settings}async function ez(e){const t=Ne("settings/deployment"),n=await fetch(t,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});return await He(n,{method:"PUT",url:t}),(await n.json()).settings}async function h5(e,t){const n=Ne(`conversations/${e}/settings/runtime`),i=await fetch(n,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});return await He(i,{method:"PUT",url:n}),await i.json()}async function m5(e,t){const n=Ne(`conversations/${e}/runtime/reset`),i=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});await He(i,{method:"POST",url:n});const l=(await i.json()).job;return j7(e,l)}async function C7(e){const t=Ne(`conversations/${e}/runtime/reset`),n=await fetch(t);return await He(n,{url:t}),(await n.json()).job}async function j7(e,t){let n=t;const i=Date.now()+1800*1e3;for(;n.status==="running";){if(Date.now()>=i)throw new Error("Full-history reset is still running after 30 minutes. Reopen Console to check the workspace before retrying.");await new Promise(o=>window.setTimeout(o,1e3));const l=await C7(e);if(!l||l.id!==n.id)throw new Error("The runtime reset job is no longer available.");n=l}if(n.status==="failed"||n.status==="cancelled"||!n.result)throw new Error(n.error??"Full-history reset failed.");return n.result}async function p5(e){const t=Ne(`conversations/${e}/runtime/reset-preview`),n=await fetch(t);return await He(n,{url:t}),await n.json()}async function tz(e,t){const n=Ne(`conversations/${e}/runtime/reset-selection`),i=await fetch(n,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});await He(i,{method:"PUT",url:n})}async function nz(e){const t=Ne(`conversations/${e}/runtime/thread-read`),n=await fetch(t);return await He(n,{url:t}),(await n.json()).result}async function rz(e){const t=Ne(`conversations/${e}/runtime/token-usage`),n=await fetch(t);await He(n,{url:t});const i=await n.json();return i.event?I7(i.event):null}async function az(e){const t=Ne(`conversations/${e}/runtime/additional-context`),n=await fetch(t);return await He(n,{url:t}),await n.json()}async function iz(e){const t=Ne(`conversations/${e}/runtime/compactions`),n=await fetch(t);return await He(n,{url:t}),(await n.json()).compactions}function lz(e,t,n){return{model:e.model===t.model?null:e.model,reasoningEffort:_A(e.reasoningEffort,t.reasoningEffort,(n==null?void 0:n.sources.reasoningEffort)==="workspace"),fastMode:e.fastMode===t.fastMode?null:e.fastMode,sandbox:e.sandbox===t.sandbox?null:e.sandbox}}function sz(e){return{kind:e.kind,name:e.name,description:e.description,purpose:e.purpose,attention:e.attention,refreshPolicy:e.refreshPolicy,status:e.status,sourceClues:uz(e.sourceCluesText),requiredEnv:cz(e.requiredEnvText)}}function oz(e){return{id:e.id,kind:e.kind,name:e.name,description:e.description,purpose:e.purpose,attention:e.attention,refreshPolicy:e.refreshPolicy,status:e.status,sourceCluesText:e.sourceClues.map(t=>`${t.type}: ${t.value}`).join(`
379
+ `,l),c=e.slice(l,o===-1?e.length:o);/^\s*(```|~~~)/.test(c)&&(i=i===-1?l:-1)}return i>=0?i:t+1}function aM({artifact:e,onPreview:t,onCopyUrl:n,copied:i}){return e?u.jsxs("figure",{className:"artifact-preview",children:[u.jsx("button",{className:"artifact-preview-media",onClick:()=>t(e),type:"button",children:u.jsx("img",{alt:e.name,src:e.url})}),u.jsxs("figcaption",{children:[u.jsx("span",{children:e.name}),u.jsxs("div",{className:"artifact-preview-actions",children:[u.jsx("button",{onClick:()=>t(e),type:"button",children:"Preview"}),u.jsx("a",{href:e.url,rel:"noreferrer",target:"_blank",children:"Open"}),u.jsx("button",{onClick:()=>n(e),type:"button",children:i?"Copied":"Copy"})]})]})]}):null}function iM(e,t){const n=new Map;for(const i of lM(e)){const l=y7(i);if(l){const o=v7(l).toLowerCase(),c=n.get(o);(!c||uM(l,c))&&n.set(o,l)}}return Array.from(n.values()).map(i=>sM(i,t)).filter(i=>i!==null)}function lM(e){const t=[],n=/!\[[^\]]*]\(([^)]+)\)/g,i=/\[[^\]]+]\(([^)]+)\)/g,l=/(?:artifact|preview|image|file)\s*:\s*(`?[^`\n]+?\.(?:svg|png|jpe?g|webp|gif)`?)/gim;for(const o of[n,i,l]){let c;for(;(c=o.exec(e))!==null;)t.push(c[1])}return t}function sM(e,t){const n=y7(e);if(!n||!oM(n))return null;const i=Xv(n,t.workspacePath);return{id:`${t.id}:${i}`,path:i,name:v7(i),url:Ne(`conversations/${t.id}/files?path=${encodeURIComponent(i)}`)}}function y7(e){const t=e.trim().replace(/^`+|`+$/g,"").replace(/[),.;:,。;:]+$/g,"");return t||null}function oM(e){return/\.(?:svg|png|jpe?g|webp|gif)$/i.test(e)}function v7(e){return e.replace(/\\/g,"/").split("/").filter(Boolean).pop()??e}function uM(e,t){return e.startsWith("/")&&!t.startsWith("/")?!0:e.length>t.length}function Ps(e){return e.trim()}function x7(e){return e.trim()}function a5(e){return e instanceof DOMException&&e.name==="AbortError"||e instanceof Error&&e.name==="AbortError"}function cM(e){return{a({children:t,href:n}){if(!n)return u.jsx(u.Fragment,{children:t});const i=/^[a-z][a-z\d+.-]*:/i.test(n),l=!i&&e?dM(n,e):null,o=l??n,c=i||!!l;return u.jsx("a",{className:"markdown-link",href:o,rel:c?"noreferrer":void 0,target:c?"_blank":void 0,children:t})},img(){return null},pre({children:t}){const n=hM(t);return n?G1(n.language)==="mermaid"?u.jsx(mM,{code:n.code}):u.jsx(yM,{code:n.code,language:n.language}):u.jsx("pre",{children:t})},table({children:t}){return u.jsx("div",{className:"markdown-table-wrap",children:u.jsx("table",{className:"markdown-table",children:t})})},td({align:t,children:n}){return u.jsx("td",{style:i5(t),children:n})},th({align:t,children:n}){return u.jsx("th",{style:i5(t),children:n})}}}function dM(e,t){if(!e||e.startsWith("#")||e.startsWith("/api/")||e.startsWith("?"))return null;const n=JA(e,t.workspacePath);if(!n)return null;const i=n.line?`#L${n.line}${n.column?`C${n.column}`:""}`:"";return`${Ne(`conversations/${t.id}/files?path=${encodeURIComponent(n.path)}`)}${i}`}function i5(e){return e&&e!=="char"?{textAlign:e}:void 0}function Yl(e,t){const n=qT(fM(e));return u.jsx(Ck,{components:cM(t),remarkPlugins:[BC,LT],rehypePlugins:[[yA,{trust:!1,strict:"ignore"}]],skipHtml:!0,children:n})}function fM(e){return e.replace(/([^\n])(```[^\n`]*(?:\r?\n|$))/g,`$1
380
+ $2`)}function hM(e){var o;const t=I.Children.toArray(e),n=t.length===1&&I.isValidElement(t[0])?t[0]:null;if(!n||n.type!=="code")return null;const l=((o=(n.props.className??"").match(/(?:^|\s)language-([^\s]+)/))==null?void 0:o[1])??"";return{code:Xp(n.props.children).replace(/\n$/,""),language:l}}function Xp(e){return e==null||typeof e=="boolean"?"":typeof e=="string"||typeof e=="number"||typeof e=="bigint"?String(e):Array.isArray(e)?e.map(Xp).join(""):I.isValidElement(e)?Xp(e.props.children):""}const b7="github-light",np=new Map,rp=new Map;let ap=null,ip=null;const w7=new Set(["bash","css","diff","dockerfile","html","java","javascript","json","jsonc","jsx","markdown","python","shellscript","sql","toml","tsx","typescript","xml","yaml"]);function G1(e){const t=e.trim().toLowerCase().replace(/^\./,"");return{bash:"bash",cjs:"javascript",console:"shellscript",htm:"html",js:"javascript",jsx:"jsx",md:"markdown",mjs:"javascript",py:"python",rb:"ruby",shell:"bash",ts:"typescript",tsx:"tsx",yml:"yaml",zsh:"bash"}[t]??t}function k7(e){const t=G1(e);return!t||t==="text"||t==="txt"?"text":w7.has(t)?t:"text"}function mM({code:e}){const n=`seele-mermaid-${I.useId().replace(/[^a-zA-Z0-9_-]/g,"")}`,[i,l]=I.useState(!1),[o,c]=I.useState(()=>rp.get(e)??null),[f,h]=I.useState(null);I.useEffect(()=>{let y=!1,v;const k=rp.get(e);return k?(c(k),h(null),()=>{y=!0}):(h(null),c(null),pM(n,e).then(w=>{y||(v!==void 0&&window.clearTimeout(v),rp.set(e,w),c(w),h(null))},w=>{if(!y){const T=w instanceof Error?w.message:String(w);v=window.setTimeout(()=>{y||h(T)},cE)}}),()=>{y=!0,v!==void 0&&window.clearTimeout(v)})},[e,n]);async function m(){await navigator.clipboard.writeText(e),l(!0),window.setTimeout(()=>l(!1),1200)}return u.jsxs("figure",{className:`mermaid-block${f?" error":""}`,children:[u.jsx("span",{className:"code-block-kind",children:"mermaid"}),u.jsx("div",{className:"code-block-tools",children:u.jsx("button",{"aria-label":i?"Copied Mermaid source":"Copy Mermaid source",className:i?"copied":"",onClick:()=>void m(),title:i?"Copied":"Copy",type:"button",children:u.jsx(P1,{})})}),o?u.jsx("div",{className:"mermaid-diagram",dangerouslySetInnerHTML:{__html:o}}):f?u.jsxs("div",{className:"mermaid-error",children:[u.jsx("strong",{children:"Mermaid render failed"}),u.jsx("pre",{children:f}),u.jsx("code",{children:e})]}):u.jsx("div",{className:"mermaid-loading",children:"Rendering diagram..."})]})}async function pM(e,t){return(await(await gM()).render(e,t)).svg}function gM(){return ip||(ip=en(()=>import("./mermaid.core-BeXu8ScT.js").then(e=>e.bp),[],import.meta.url).then(e=>{const t=e.default;return t.initialize({startOnLoad:!1,securityLevel:"strict",theme:"base",themeVariables:{background:"#ffffff",primaryColor:"#f9fafa",primaryBorderColor:"#d8d9e8",primaryTextColor:"#0b0f16",lineColor:"#7a8294",secondaryColor:"#f5f5fb",tertiaryColor:"#ffffff",fontFamily:'Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif'}}),t})),ip}function yM({code:e,language:t,reserveHeight:n=!1}){const[i,l]=I.useState(!1),[o,c]=I.useState(()=>{if(!o5(t))return null;const m=s5(e,t);return np.get(m)??null}),f=n?{"--code-block-min-height":`${wE(e)}px`}:void 0;I.useEffect(()=>{let m=!1;if(!o5(t))return c(null),()=>{m=!0};const y=s5(e,t),v=np.get(y);return v?(c(v),()=>{m=!0}):(c(null),jM(e,t).then(k=>{np.set(y,k),m||c(k)}).catch(k=>{console.warn("Failed to highlight code block",k),m||c(null)}),()=>{m=!0})},[e,t]);async function h(){await navigator.clipboard.writeText(e),l(!0),window.setTimeout(()=>l(!1),1200)}return u.jsxs("figure",{className:"code-block",style:f,children:[t?u.jsx("span",{className:"code-block-kind",children:t}):null,u.jsx("div",{className:"code-block-tools",children:u.jsx("button",{"aria-label":i?"Copied code block":"Copy code block",className:i?"copied":"",onClick:()=>void h(),title:i?"Copied":"Copy",type:"button",children:u.jsx(P1,{})})}),o?u.jsx("div",{className:"code-block-shiki",dangerouslySetInnerHTML:{__html:o}}):u.jsx("pre",{children:u.jsx("code",{children:e})})]})}function P1(){return u.jsxs("svg",{"aria-hidden":"true",fill:"none",height:"13",viewBox:"0 0 24 24",width:"13",children:[u.jsx("rect",{height:"14",rx:"2",stroke:"currentColor",strokeWidth:"2",width:"14",x:"8",y:"8"}),u.jsx("path",{d:"M4 16V6a2 2 0 0 1 2-2h10",stroke:"currentColor",strokeLinecap:"round",strokeWidth:"2"})]})}function vM(){return u.jsxs("svg",{"aria-hidden":"true",fill:"none",height:"16",viewBox:"0 0 24 24",width:"16",children:[u.jsx("circle",{cx:"6",cy:"5",r:"2",stroke:"currentColor",strokeWidth:"2"}),u.jsx("circle",{cx:"18",cy:"5",r:"2",stroke:"currentColor",strokeWidth:"2"}),u.jsx("circle",{cx:"12",cy:"19",r:"2",stroke:"currentColor",strokeWidth:"2"}),u.jsx("path",{d:"M6 7v1a6 6 0 0 0 6 6v3M18 7v1a6 6 0 0 1-6 6",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2"})]})}function S7(){return u.jsxs("svg",{"aria-hidden":"true",fill:"none",height:"12",viewBox:"0 0 24 24",width:"12",children:[u.jsx("circle",{cx:"12",cy:"12",r:"9",stroke:"currentColor",strokeWidth:"2.2"}),u.jsx("path",{d:"M12 7v6",stroke:"currentColor",strokeLinecap:"round",strokeWidth:"2.4"}),u.jsx("circle",{cx:"12",cy:"17",fill:"currentColor",r:"1.25"})]})}function xM(){return u.jsx("svg",{"aria-hidden":"true",fill:"none",height:"18",viewBox:"0 0 24 24",width:"18",children:u.jsx("path",{d:"M4 7h16M4 12h16M4 17h16",stroke:"currentColor",strokeLinecap:"round",strokeWidth:"2"})})}function bM(){return u.jsxs("svg",{"aria-hidden":"true",fill:"none",height:"14",viewBox:"0 0 24 24",width:"14",children:[u.jsx("path",{d:"M7 7h10M7 12h10M7 17h10",stroke:"currentColor",strokeLinecap:"round",strokeWidth:"2"}),u.jsx("circle",{cx:"4",cy:"7",fill:"currentColor",r:"1.4"}),u.jsx("circle",{cx:"4",cy:"12",fill:"currentColor",r:"1.4"}),u.jsx("circle",{cx:"4",cy:"17",fill:"currentColor",r:"1.4"})]})}function l5(){return u.jsxs("svg",{"aria-hidden":"true",fill:"none",height:"14",viewBox:"0 0 24 24",width:"14",children:[u.jsx("circle",{cx:"12",cy:"12",r:"3",stroke:"currentColor",strokeWidth:"2"}),u.jsx("path",{d:"M19 12a7.8 7.8 0 0 0-.1-1l2-1.5-2-3.4-2.4 1a8 8 0 0 0-1.8-1l-.3-2.6h-4l-.3 2.6a8 8 0 0 0-1.8 1l-2.4-1-2 3.4 2 1.5a7.8 7.8 0 0 0 0 2l-2 1.5 2 3.4 2.4-1a8 8 0 0 0 1.8 1l.3 2.6h4l.3-2.6a8 8 0 0 0 1.8-1l2.4 1 2-3.4-2-1.5c.1-.3.1-.7.1-1Z",stroke:"currentColor",strokeLinejoin:"round",strokeWidth:"1.7"})]})}function wM(){return u.jsxs("svg",{"aria-hidden":"true",fill:"none",height:"14",viewBox:"0 0 24 24",width:"14",children:[u.jsx("rect",{height:"16",rx:"2.6",stroke:"currentColor",strokeWidth:"1.8",width:"18",x:"3",y:"4"}),u.jsx("path",{d:"m7 9 3 3-3 3M12.5 15h4.5",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"1.9"})]})}function Gd(){return u.jsxs("svg",{"aria-hidden":"true",fill:"none",height:"17",viewBox:"0 0 24 24",width:"17",children:[u.jsx("circle",{cx:"7",cy:"12",r:"2.4",stroke:"currentColor",strokeWidth:"1.8"}),u.jsx("circle",{cx:"17",cy:"7",r:"2.4",stroke:"currentColor",strokeWidth:"1.8"}),u.jsx("circle",{cx:"17",cy:"17",r:"2.4",stroke:"currentColor",strokeWidth:"1.8"}),u.jsx("path",{d:"m9.2 10.9 5.6-2.8M9.2 13.1l5.6 2.8",stroke:"currentColor",strokeLinecap:"round",strokeWidth:"1.8"})]})}function Ef(){return u.jsxs("svg",{"aria-hidden":"true",fill:"none",height:"13",viewBox:"0 0 24 24",width:"13",children:[u.jsx("path",{d:"m4 16-.8 4 4-.8L18.4 8 15.2 4.8 4 16Z",stroke:"currentColor",strokeLinejoin:"round",strokeWidth:"2"}),u.jsx("path",{d:"m13.8 6.2 3.2 3.2",stroke:"currentColor",strokeLinecap:"round",strokeWidth:"2"})]})}function kM(){return u.jsx("svg",{"aria-hidden":"true",fill:"none",height:"14",viewBox:"0 0 24 24",width:"14",children:u.jsx("path",{d:"M5 8v11h14V8M4 4h16v4H4zM9 12h6",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2"})})}function SM(){return u.jsxs("svg",{"aria-hidden":"true",fill:"none",height:"14",viewBox:"0 0 24 24",width:"14",children:[u.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",stroke:"currentColor",strokeLinejoin:"round",strokeWidth:"2"}),u.jsx("circle",{cx:"12",cy:"12",r:"3",stroke:"currentColor",strokeWidth:"2"})]})}function CM(){return u.jsxs("svg",{"aria-hidden":"true",fill:"none",height:"14",viewBox:"0 0 24 24",width:"14",children:[u.jsx("path",{d:"M3 3l18 18",stroke:"currentColor",strokeLinecap:"round",strokeWidth:"2"}),u.jsx("path",{d:"M9.9 5.4A9.8 9.8 0 0 1 12 5c6 0 9.5 7 9.5 7a15.5 15.5 0 0 1-3 3.8M6.2 6.8C3.8 8.4 2.5 12 2.5 12s3.5 7 9.5 7a9.7 9.7 0 0 0 4-.8",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2"})]})}function s5(e,t){return`${b7}:${k7(t)}:${e}`}function o5(e){const t=G1(e);return!!t&&w7.has(t)}async function jM(e,t){return(await TM()).codeToHtml(e,{lang:k7(t),theme:b7})}function TM(){return ap||(ap=AM()),ap}async function AM(){const[{createHighlighterCore:e},{createJavaScriptRegexEngine:t},{default:n},{default:i},{default:l},{default:o},{default:c},{default:f},{default:h},{default:m},{default:y},{default:v},{default:k},{default:w},{default:T},{default:E},{default:q},{default:R},{default:B},{default:F},{default:Y},{default:te}]=await Promise.all([en(()=>import("./core-BEHJop_C.js"),[],import.meta.url),en(()=>import("./engine-javascript-DBd1bXLz.js"),[],import.meta.url),en(()=>import("./github-light-DAi9KRSo.js"),[],import.meta.url),en(()=>import("./bash-BELqPA7S.js").then(_=>_.b),[],import.meta.url),en(()=>import("./css-CLj8gQPS.js"),[],import.meta.url),en(()=>import("./diff-D97Zzqfu.js"),[],import.meta.url),en(()=>import("./dockerfile-BcOcwvcX.js"),[],import.meta.url),en(()=>import("./html-pp8916En.js"),__vite__mapDeps([0,1,2]),import.meta.url),en(()=>import("./java-CylS5w8V.js"),[],import.meta.url),en(()=>import("./javascript-wDzz0qaB.js"),[],import.meta.url),en(()=>import("./json-Cp-IABpG.js"),[],import.meta.url),en(()=>import("./jsonc-Des-eS-w.js"),[],import.meta.url),en(()=>import("./jsx-g9-lgVsj.js"),[],import.meta.url),en(()=>import("./markdown-Cvjx9yec.js"),[],import.meta.url),en(()=>import("./python-B6aJPvgy.js"),[],import.meta.url),en(()=>import("./bash-BELqPA7S.js").then(_=>_.s),[],import.meta.url),en(()=>import("./sql-CRqJ_cUM.js"),[],import.meta.url),en(()=>import("./toml-vGWfd6FD.js"),[],import.meta.url),en(()=>import("./tsx-COt5Ahok.js"),[],import.meta.url),en(()=>import("./typescript-BPQ3VLAy.js"),[],import.meta.url),en(()=>import("./xml-sdJ4AIDG.js"),__vite__mapDeps([3,4]),import.meta.url),en(()=>import("./yaml-Buea-lGh.js"),[],import.meta.url)]);return e({engine:t(),themes:[n],langs:[i,l,o,c,f,h,m,y,v,k,w,T,E,q,R,B,F,Y,te]})}async function u5(){const e=Ne("conversations"),t=await fetch(e);return await He(t,{url:e}),(await t.json()).conversations}async function EM(){const e=Ne("workspace-states"),t=await fetch(e);return await He(t,{url:e}),(await t.json()).workspaces}async function c5(){const e=Ne("collaboration/topics"),t=await fetch(e);return await He(t,{url:e}),(await t.json()).topics}async function Ld(e){const t=Ne(`collaboration/topics/${e}/messages?limit=100`),n=await fetch(t);return await He(n,{url:t}),(await n.json()).messages}async function NM(e){const t=Ne("collaboration/topics"),n=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});return await He(n,{method:"POST",url:t}),(await n.json()).topic}async function MM(e,t){const n=Ne(`collaboration/topics/${e}`),i=await fetch(n,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});return await He(i,{method:"PATCH",url:n}),(await i.json()).topic}async function zM(e,t){const n=Ne(`collaboration/topics/${e}/archive`),i=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({expectedVersion:t})});return await He(i,{method:"POST",url:n}),(await i.json()).topic}async function DM(e){const t=Ne(`conversations/${e}/read`),n=await fetch(t,{method:"POST"});await He(n,{method:"POST",url:t})}async function d5(){const e=Ne("workspace-groups"),t=await fetch(e);return await He(t,{url:e}),(await t.json()).groups}async function RM(e){const t=Ne("workspace-groups"),n=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:e})});return await He(n,{method:"POST",url:t}),(await n.json()).group}async function OM(e,t){const n=Ne(`workspace-groups/${e}`),i=await fetch(n,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});return await He(i,{method:"PATCH",url:n}),(await i.json()).group}async function _M(e){const t=Ne(`workspace-groups/${e}`),n=await fetch(t,{method:"DELETE"});return await He(n,{method:"DELETE",url:t}),await n.json()}async function BM(){const e=Ne("settings/environment"),t=await fetch(e);return await He(t,{url:e}),(await t.json()).variables}async function IM(e){const t=Ne(`conversations/${e}/settings/environment`),n=await fetch(t);return await He(n,{url:t}),(await n.json()).variables}async function LM(e){const t=Ne(`conversations/${e}/knowledge`),n=await fetch(t);return await He(n,{url:t}),(await n.json()).items}async function qM(){const e=Ne("settings/runtime"),t=await fetch(e);return await He(t,{url:e}),(await t.json()).settings}async function UM(){const e=Ne("settings/deployment"),t=await fetch(e);return await He(t,{url:e}),(await t.json()).settings}async function HM(){const e=Ne("diagnostics"),t=await fetch(e);return await He(t,{url:e}),await t.json()}async function FM(){const e=Ne("settings/runtime/codex"),t=await fetch(e);return await He(t,{url:e}),await t.json()}async function f5(){const e=Ne("settings/runtime/accounts"),t=await fetch(e);await He(t,{url:e});const n=await t.json();return Xs(),n}async function lp(e=!1){const t=Ne(`settings/runtime/accounts/refresh${e?"?force=1":""}`),n=await fetch(t,{method:"POST"});await He(n,{method:"POST",url:t});const i=await n.json();return Xs(),i}async function $M(e){const t=Ne("settings/runtime/accounts"),n=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:e})});await He(n,{method:"POST",url:t});const i=await n.json();return i.login.status==="succeeded"&&Xs(),i.login}async function GM(e){const t=Ne(`settings/runtime/accounts/login/${e}`),n=await fetch(t);return await He(n,{url:t}),(await n.json()).login}async function PM(e){const t=Ne(`settings/runtime/accounts/login/${e}/cancel`),n=await fetch(t,{method:"POST"});return await He(n,{method:"POST",url:t}),(await n.json()).login}async function VM(e,t){const n=Ne(`settings/runtime/accounts/${e}`),i=await fetch(n,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:t})});await He(i,{method:"PATCH",url:n});const l=await i.json();return Xs(),l.account}async function YM(e){const t=Ne(`settings/runtime/accounts/${e}`),n=await fetch(t,{method:"DELETE"});await He(n,{method:"DELETE",url:t}),Xs()}async function WM(e){const t=Ne(`settings/runtime/accounts/${e}/switch`),n=await fetch(t,{method:"POST"});await He(n,{method:"POST",url:t});const i=await n.json();return Xs(),i}async function XM(e=!0){const t=Ne(`settings/runtime/models?refresh=${e?"1":"0"}`),n=await fetch(t);return await He(n,{url:t}),await n.json()}async function KM(e=!1){const t=Ne(`settings/runtime/codex/update${e?"?refreshLatest=1":""}`),n=await fetch(t);return await He(n,{url:t}),await n.json()}async function QM(){const e=Ne("settings/runtime/codex/update"),t=await fetch(e,{method:"POST"});return await He(t,{method:"POST",url:e}),(await t.json()).job}async function ZM(e){const t=Ne(`conversations/${e}/settings/runtime`),n=await fetch(t);return await He(n,{url:t}),(await n.json()).settings}async function JM(){const e=Ne("settings/memory"),t=await fetch(e);return await He(t,{url:e}),await t.json()}async function ez(e){const t=Ne("settings/runtime"),n=await fetch(t,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});return await He(n,{method:"PUT",url:t}),(await n.json()).settings}async function tz(e){const t=Ne("settings/deployment"),n=await fetch(t,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});return await He(n,{method:"PUT",url:t}),(await n.json()).settings}async function h5(e,t){const n=Ne(`conversations/${e}/settings/runtime`),i=await fetch(n,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});return await He(i,{method:"PUT",url:n}),await i.json()}async function m5(e,t){const n=Ne(`conversations/${e}/runtime/reset`),i=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});await He(i,{method:"POST",url:n});const l=(await i.json()).job;return j7(e,l)}async function C7(e){const t=Ne(`conversations/${e}/runtime/reset`),n=await fetch(t);return await He(n,{url:t}),(await n.json()).job}async function j7(e,t){let n=t;const i=Date.now()+1800*1e3;for(;n.status==="running";){if(Date.now()>=i)throw new Error("Full-history reset is still running after 30 minutes. Reopen Console to check the workspace before retrying.");await new Promise(o=>window.setTimeout(o,1e3));const l=await C7(e);if(!l||l.id!==n.id)throw new Error("The runtime reset job is no longer available.");n=l}if(n.status==="failed"||n.status==="cancelled"||!n.result)throw new Error(n.error??"Full-history reset failed.");return n.result}async function p5(e){const t=Ne(`conversations/${e}/runtime/reset-preview`),n=await fetch(t);return await He(n,{url:t}),await n.json()}async function nz(e,t){const n=Ne(`conversations/${e}/runtime/reset-selection`),i=await fetch(n,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});await He(i,{method:"PUT",url:n})}async function rz(e){const t=Ne(`conversations/${e}/runtime/thread-read`),n=await fetch(t);return await He(n,{url:t}),(await n.json()).result}async function az(e){const t=Ne(`conversations/${e}/runtime/token-usage`),n=await fetch(t);await He(n,{url:t});const i=await n.json();return i.event?I7(i.event):null}async function iz(e){const t=Ne(`conversations/${e}/runtime/additional-context`),n=await fetch(t);return await He(n,{url:t}),await n.json()}async function lz(e){const t=Ne(`conversations/${e}/runtime/compactions`),n=await fetch(t);return await He(n,{url:t}),(await n.json()).compactions}function sz(e,t,n){return{model:e.model===t.model?null:e.model,reasoningEffort:BA(e.reasoningEffort,t.reasoningEffort,(n==null?void 0:n.sources.reasoningEffort)==="workspace"),fastMode:e.fastMode===t.fastMode?null:e.fastMode,sandbox:e.sandbox===t.sandbox?null:e.sandbox}}function oz(e){return{kind:e.kind,name:e.name,description:e.description,purpose:e.purpose,attention:e.attention,refreshPolicy:e.refreshPolicy,status:e.status,sourceClues:cz(e.sourceCluesText),requiredEnv:dz(e.requiredEnvText)}}function uz(e){return{id:e.id,kind:e.kind,name:e.name,description:e.description,purpose:e.purpose,attention:e.attention,refreshPolicy:e.refreshPolicy,status:e.status,sourceCluesText:e.sourceClues.map(t=>`${t.type}: ${t.value}`).join(`
375
381
  `),requiredEnvText:e.fetch.requiredEnv.map(t=>t.description?`${t.key} - ${t.description}`:t.key).join(`
376
- `)}}function uz(e){const t=new Date().toISOString();return e.split(/\r?\n/).map(n=>n.trim()).filter(Boolean).map(n=>{const i=n.match(/^([a-zA-Z][\w-]{0,31})\s*:\s*(.+)$/);return{type:i?i[1].toLowerCase():"text",value:i?i[2].trim():n,providedBy:"user",providedAt:t}})}function cz(e){return e.split(/\r?\n/).map(t=>t.trim()).filter(Boolean).map(t=>{const[n,...i]=t.split(/\s+-\s+/);return{key:n.trim().toUpperCase(),description:i.join(" - ").trim()}}).filter(t=>/^[A-Z_][A-Z0-9_]*$/.test(t.key))}function g5(e,t){const n=y5(t.attention)-y5(e.attention);return n!==0?n:t.updatedAt.localeCompare(e.updatedAt)}function y5(e){return e==="watch"?2:e==="tracked"?1:0}function Ic(e){return e.map(t=>({key:t.key??"",value:t.value??"",updatedAt:t.updatedAt}))}function dz(e){return e?/^[a-z_][a-z0-9_.-]*$/.test(e)?null:"Key must start with a lowercase English letter or underscore, and may contain lowercase letters, numbers, dots, underscores, and hyphens.":"Key is required."}function fz(e){return Ic(e).filter(t=>t.key.trim()&&t.value.trim()).map(t=>`${t.key.trim()}: ${t.value.trim()}`).join(`
377
- `)}async function hz(e){const t=Ne("settings/memory"),n=await fetch(t,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});return await He(n,{method:"PUT",url:t}),await n.json()}async function mz(e,t,n){const i=Ne("settings/environment"),l=await fetch(i,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({description:n,key:e,value:t})});return await He(l,{method:"PUT",url:i}),(await l.json()).variable}async function pz(e,t,n,i){const l=Ne(`conversations/${e}/settings/environment`),o=await fetch(l,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({description:i,key:t,value:n})});return await He(o,{method:"PUT",url:l}),await o.json()}async function gz(e){const t=Ne(`settings/environment/${encodeURIComponent(e)}/reveal`),n=await fetch(t);return await He(n,{url:t}),(await n.json()).variable.value}async function yz(e,t){const n=Ne(`conversations/${e}/settings/environment/${encodeURIComponent(t)}/reveal`),i=await fetch(n);return await He(i,{url:n}),(await i.json()).variable.value}async function vz(e){const t=Ne(`settings/environment/${encodeURIComponent(e)}`),n=await fetch(t,{method:"DELETE"});await He(n,{method:"DELETE",url:t})}async function xz(e,t){const n=Ne(`conversations/${e}/settings/environment/${encodeURIComponent(t)}`),i=await fetch(n,{method:"DELETE"});return await He(i,{method:"DELETE",url:n}),(await i.json()).conversation}async function bz(e,t){const n=Ne(`conversations/${e}/knowledge`),i=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});return await He(i,{method:"POST",url:n}),(await i.json()).item}async function wz(e,t,n){const i=Ne(`conversations/${e}/knowledge/${encodeURIComponent(t)}`),l=await fetch(i,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});return await He(l,{method:"PATCH",url:i}),(await l.json()).item}async function kz(e,t){const n=Ne(`conversations/${e}/knowledge/${encodeURIComponent(t)}`),i=await fetch(n,{method:"DELETE"});await He(i,{method:"DELETE",url:n})}async function Sz(){const e=Ne("meta"),t=await fetch(e);return await He(t,{url:e}),await t.json()}async function Cz(e){const t=Ne(`settings/runtime/rate-limits?refresh=${e?"1":"0"}`),n=await fetch(t);return await He(n,{url:t}),(await n.json()).usage??null}async function jz(e,t){const n=Ne("conversations"),i=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:e,groupId:t})});return await He(i,{method:"POST",url:n}),(await i.json()).conversation}async function Tz(e){const t=Ne(`conversations/${e}/complex-task`),n=await fetch(t);return await He(n,{url:t}),(await n.json()).task}async function Az(e,t){const n=Ne(`conversations/${e}/complex-tasks/${encodeURIComponent(t)}`),i=await fetch(n);return await He(i,{url:n}),(await i.json()).task}async function Ez(e,t){const n=Ne(`conversations/${e}/complex-task/${t}`),i=await fetch(n,{method:"POST"});return await He(i,{method:"POST",url:n}),(await i.json()).task}async function Nz(e,t,n){const i=Ne(`conversations/${e}/clone`),l=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:t,groupId:n})});return await He(l,{method:"POST",url:i}),await l.json()}async function Mz(e){const t=Ne(`conversations/${e}/clone/retry`),n=await fetch(t,{method:"POST"});return await He(n,{method:"POST",url:t}),await n.json()}async function sp(e,t={}){const n=new URLSearchParams;n.set("limit",String(t.limit??Kv)),t.before&&n.set("before",t.before);const i=Ne(`conversations/${e}?${n}`),l=await fetch(i);return await He(l,{url:i}),(await l.json()).conversation}async function zz(e,t){const n=Ne(`conversations/${e}/turns/${t}/history-events`),i=await fetch(n);return await He(i,{url:n}),(await i.json()).events}async function qd(e,t){const n=Ne(`conversations/${e}`),i=await fetch(n,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});return await He(i,{method:"PATCH",url:n}),(await i.json()).conversation}async function Dz(e){const t=Ne(`conversations/${e}`),n=await fetch(t,{method:"DELETE"});await He(n,{method:"DELETE",url:t})}function Rz(e){return e.title==="Phase boundary recommended"||e.title==="Long run in progress"}function T7(e){return e.length<=3?e.join(", "):`${e.slice(0,3).join(", ")} +${e.length-3}`}function Oz(e,t){if(e.event==="server.error"||e.event==="client.error")return{id:e.id,kind:"error",title:"Error",body:tD(e.data),createdAt:e.createdAt??new Date().toISOString()};if(e.event==="server.collaboration.message_staged"||e.event==="server.collaboration.message_sent"||e.event==="server.collaboration.message_rejected"){const o=Ee(e.data),c=$e(o.toolCallId),f=typeof o.controlIndex=="number"?o.controlIndex:null;if(c||f!==null){const h=e.event==="server.collaboration.message_staged",m=e.event==="server.collaboration.message_sent",y=$e(o.audience),v=$e(o.recipientWorkspaceId),k=v?[v]:Array.isArray(o.recipientWorkspaceIds)?o.recipientWorkspaceIds.filter(q=>typeof q=="string"):Array.isArray(o.recipients)?o.recipients.filter(q=>typeof q=="string"):[],w=k.filter(q=>q!=="ALL").map(q=>t.get(q)).filter(q=>!!q);let T="Topic";w.length>0?T=T7(w):k.length===1?T=k[0]==="ALL"?"Topic participants":Xl(k[0]):k.length>1?T=`${k.length} workspaces`:y==="public"||y==="all"?T="Topic participants":y==="owner"&&(T="Topic owner");const E=$e(o.topicId);return{id:e.id,kind:"collaboration",title:`Send to ${T}`,body:E?`Topic ${Xl(E)}`:"Topic",createdAt:e.createdAt??new Date().toISOString(),itemId:c||`legacy-topic-message:${f}`,meta:h?"pending send":m?"done":"failed",output:h||m?$e(o.contentMarkdown)||void 0:$e(o.reason)||void 0,topicAction:"send",topicRecipientLabel:T,topicMessageContent:(h||m)&&$e(o.contentMarkdown)||void 0}}}if(e.event==="codex.input_request"||e.event==="codex.input_or_approval_request"){const o=Ee(e.data);if(e.event==="codex.input_request"||o.method==="item/tool/requestUserInput"){const c=Ee(o.params),h=(Array.isArray(c.questions)?c.questions:[]).map(m=>{const y=Ee(m),v=typeof y.question=="string"?y.question:"Please provide the missing information.",k=Array.isArray(y.options)?y.options.map(w=>{const T=Ee(w);return typeof T.label=="string"?`- ${T.label}${typeof T.description=="string"?`: ${T.description}`:""}`:""}).filter(Boolean).join(`
382
+ `)}}function cz(e){const t=new Date().toISOString();return e.split(/\r?\n/).map(n=>n.trim()).filter(Boolean).map(n=>{const i=n.match(/^([a-zA-Z][\w-]{0,31})\s*:\s*(.+)$/);return{type:i?i[1].toLowerCase():"text",value:i?i[2].trim():n,providedBy:"user",providedAt:t}})}function dz(e){return e.split(/\r?\n/).map(t=>t.trim()).filter(Boolean).map(t=>{const[n,...i]=t.split(/\s+-\s+/);return{key:n.trim().toUpperCase(),description:i.join(" - ").trim()}}).filter(t=>/^[A-Z_][A-Z0-9_]*$/.test(t.key))}function g5(e,t){const n=y5(t.attention)-y5(e.attention);return n!==0?n:t.updatedAt.localeCompare(e.updatedAt)}function y5(e){return e==="watch"?2:e==="tracked"?1:0}function Ic(e){return e.map(t=>({key:t.key??"",value:t.value??"",updatedAt:t.updatedAt}))}function fz(e){return e?/^[a-z_][a-z0-9_.-]*$/.test(e)?null:"Key must start with a lowercase English letter or underscore, and may contain lowercase letters, numbers, dots, underscores, and hyphens.":"Key is required."}function hz(e){return Ic(e).filter(t=>t.key.trim()&&t.value.trim()).map(t=>`${t.key.trim()}: ${t.value.trim()}`).join(`
383
+ `)}async function mz(e){const t=Ne("settings/memory"),n=await fetch(t,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});return await He(n,{method:"PUT",url:t}),await n.json()}async function pz(e,t,n){const i=Ne("settings/environment"),l=await fetch(i,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({description:n,key:e,value:t})});return await He(l,{method:"PUT",url:i}),(await l.json()).variable}async function gz(e,t,n,i){const l=Ne(`conversations/${e}/settings/environment`),o=await fetch(l,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({description:i,key:t,value:n})});return await He(o,{method:"PUT",url:l}),await o.json()}async function yz(e){const t=Ne(`settings/environment/${encodeURIComponent(e)}/reveal`),n=await fetch(t);return await He(n,{url:t}),(await n.json()).variable.value}async function vz(e,t){const n=Ne(`conversations/${e}/settings/environment/${encodeURIComponent(t)}/reveal`),i=await fetch(n);return await He(i,{url:n}),(await i.json()).variable.value}async function xz(e){const t=Ne(`settings/environment/${encodeURIComponent(e)}`),n=await fetch(t,{method:"DELETE"});await He(n,{method:"DELETE",url:t})}async function bz(e,t){const n=Ne(`conversations/${e}/settings/environment/${encodeURIComponent(t)}`),i=await fetch(n,{method:"DELETE"});return await He(i,{method:"DELETE",url:n}),(await i.json()).conversation}async function wz(e,t){const n=Ne(`conversations/${e}/knowledge`),i=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});return await He(i,{method:"POST",url:n}),(await i.json()).item}async function kz(e,t,n){const i=Ne(`conversations/${e}/knowledge/${encodeURIComponent(t)}`),l=await fetch(i,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});return await He(l,{method:"PATCH",url:i}),(await l.json()).item}async function Sz(e,t){const n=Ne(`conversations/${e}/knowledge/${encodeURIComponent(t)}`),i=await fetch(n,{method:"DELETE"});await He(i,{method:"DELETE",url:n})}async function Cz(){const e=Ne("meta"),t=await fetch(e);return await He(t,{url:e}),await t.json()}async function jz(e){const t=Ne(`settings/runtime/rate-limits?refresh=${e?"1":"0"}`),n=await fetch(t);return await He(n,{url:t}),(await n.json()).usage??null}async function Tz(e,t){const n=Ne("conversations"),i=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:e,groupId:t})});return await He(i,{method:"POST",url:n}),(await i.json()).conversation}async function Az(e){const t=Ne(`conversations/${e}/complex-task`),n=await fetch(t);return await He(n,{url:t}),(await n.json()).task}async function Ez(e,t){const n=Ne(`conversations/${e}/complex-tasks/${encodeURIComponent(t)}`),i=await fetch(n);return await He(i,{url:n}),(await i.json()).task}async function Nz(e,t){const n=Ne(`conversations/${e}/complex-task/${t}`),i=await fetch(n,{method:"POST"});return await He(i,{method:"POST",url:n}),(await i.json()).task}async function Mz(e,t,n){const i=Ne(`conversations/${e}/clone`),l=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:t,groupId:n})});return await He(l,{method:"POST",url:i}),await l.json()}async function zz(e){const t=Ne(`conversations/${e}/clone/retry`),n=await fetch(t,{method:"POST"});return await He(n,{method:"POST",url:t}),await n.json()}async function sp(e,t={}){const n=new URLSearchParams;n.set("limit",String(t.limit??Kv)),t.before&&n.set("before",t.before);const i=Ne(`conversations/${e}?${n}`),l=await fetch(i);return await He(l,{url:i}),(await l.json()).conversation}async function Dz(e,t){const n=Ne(`conversations/${e}/turns/${t}/history-events`),i=await fetch(n);return await He(i,{url:n}),(await i.json()).events}async function qd(e,t){const n=Ne(`conversations/${e}`),i=await fetch(n,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});return await He(i,{method:"PATCH",url:n}),(await i.json()).conversation}async function Rz(e){const t=Ne(`conversations/${e}`),n=await fetch(t,{method:"DELETE"});await He(n,{method:"DELETE",url:t})}function Oz(e){return e.title==="Phase boundary recommended"||e.title==="Long run in progress"}function T7(e){return e.length<=3?e.join(", "):`${e.slice(0,3).join(", ")} +${e.length-3}`}function _z(e,t){if(e.event==="server.error"||e.event==="client.error")return{id:e.id,kind:"error",title:"Error",body:nD(e.data),createdAt:e.createdAt??new Date().toISOString()};if(e.event==="server.collaboration.message_staged"||e.event==="server.collaboration.message_sent"||e.event==="server.collaboration.message_rejected"){const o=Ee(e.data),c=$e(o.toolCallId),f=typeof o.controlIndex=="number"?o.controlIndex:null;if(c||f!==null){const h=e.event==="server.collaboration.message_staged",m=e.event==="server.collaboration.message_sent",y=$e(o.audience),v=$e(o.recipientWorkspaceId),k=v?[v]:Array.isArray(o.recipientWorkspaceIds)?o.recipientWorkspaceIds.filter(q=>typeof q=="string"):Array.isArray(o.recipients)?o.recipients.filter(q=>typeof q=="string"):[],w=k.filter(q=>q!=="ALL").map(q=>t.get(q)).filter(q=>!!q);let T="Topic";w.length>0?T=T7(w):k.length===1?T=k[0]==="ALL"?"Topic participants":Xl(k[0]):k.length>1?T=`${k.length} workspaces`:y==="public"||y==="all"?T="Topic participants":y==="owner"&&(T="Topic owner");const E=$e(o.topicId);return{id:e.id,kind:"collaboration",title:`Send to ${T}`,body:E?`Topic ${Xl(E)}`:"Topic",createdAt:e.createdAt??new Date().toISOString(),itemId:c||`legacy-topic-message:${f}`,meta:h?"pending send":m?"done":"failed",output:h||m?$e(o.contentMarkdown)||void 0:$e(o.reason)||void 0,topicAction:"send",topicRecipientLabel:T,topicMessageContent:(h||m)&&$e(o.contentMarkdown)||void 0}}}if(e.event==="codex.input_request"||e.event==="codex.input_or_approval_request"){const o=Ee(e.data);if(e.event==="codex.input_request"||o.method==="item/tool/requestUserInput"){const c=Ee(o.params),h=(Array.isArray(c.questions)?c.questions:[]).map(m=>{const y=Ee(m),v=typeof y.question=="string"?y.question:"Please provide the missing information.",k=Array.isArray(y.options)?y.options.map(w=>{const T=Ee(w);return typeof T.label=="string"?`- ${T.label}${typeof T.description=="string"?`: ${T.description}`:""}`:""}).filter(Boolean).join(`
378
384
  `):"";return k?`${v}
379
385
 
380
386
  ${k}`:v}).join(`
381
387
 
382
- `);return{id:e.id,kind:"activity",title:"Seele needs input",body:h||"Please answer in the main input box to continue.",createdAt:e.createdAt??new Date().toISOString(),meta:"waiting for reply"}}}if(e.event==="server.agent_action.staged"){const o=Ee(e.data);if($e(o.actionType)==="seele_workspace_change"){const f=Ee(o.payload),h=Ee(f.payload),m=$e(f.type)||"workspace";return{id:e.id,kind:"workspaceChange",title:"Preparing workspace change",body:D7(m,h),createdAt:e.createdAt??new Date().toISOString(),itemId:$e(o.toolCallId)||void 0,meta:"pending turn",workspaceChangeType:m,workspaceChangePayload:h}}const c=EA(o);return{id:e.id,kind:"activity",title:c.title,body:c.detail,createdAt:e.createdAt??new Date().toISOString(),itemId:$e(o.toolCallId)||void 0,meta:c.meta}}if(e.event==="server.workspace_inbox.offered"){const o=AA(e.data);return{id:e.id,kind:"activity",title:o.title,body:o.detail,createdAt:e.createdAt??new Date().toISOString(),meta:o.meta}}if(e.event==="codex.dynamic_tool_request"){const o=Ee(e.data),c=Ee(o.params),f=$e(c.tool)||"dynamic tool",h=Ee(c.arguments);return{id:e.id,kind:f==="seele_topics"?"collaboration":f==="seele_workspace_change"?"workspaceChange":"activity",title:M7(f,!1,h),body:z7(f,h),createdAt:e.createdAt??new Date().toISOString(),itemId:$e(c.callId)||void 0,meta:"running",topicAction:f==="seele_topics"?A7(h.action):void 0,workspaceChangeType:f==="seele_workspace_change"&&$e(h.type)||void 0,workspaceChangePayload:f==="seele_workspace_change"?Ee(h.payload):void 0}}if(e.event==="server.workspace_change.proposed"||e.event==="server.responsibility.proposed"){const o=Ee(e.data),c=Ee(o.payload),f=$e(c.content)||$e(o.responsibility);return{id:e.id,kind:"workspaceChange",title:"Workspace change proposed",body:f,createdAt:e.createdAt??new Date().toISOString(),itemId:$e(o.toolCallId)||void 0,meta:"pending",responsibilityProposalId:String(e.id),workspaceChangeProposalId:String(e.id),responsibilityReason:typeof o.reason=="string"?o.reason:void 0,responsibilityAnchorOffset:typeof o.anchorOffset=="number"?o.anchorOffset:void 0,workspaceChangeType:$e(o.changeType)||"responsibility",workspaceChangePayload:Object.keys(c).length>0?c:{content:f}}}if(e.event==="server.knowledge.proposed"){const o=Ee(e.data),c=Ee(o.knowledge);return{id:e.id,kind:"knowledge",title:o.action==="update"?"Knowledge update proposed":"Knowledge creation proposed",body:JSON.stringify(c,null,2),createdAt:e.createdAt??new Date().toISOString(),meta:"pending",knowledgeProposalId:String(e.id),knowledgeAnchorOffset:typeof o.anchorOffset=="number"?o.anchorOffset:void 0}}if(e.event==="server.complex_task.plan_updated"){const o=Ee(e.data),c=Ee(o.task),f=Ee(c.currentPlan),h=Ee(o.update),m=$e(h.operation),y=typeof f.version=="number"?`v${f.version}`:"updated",v=typeof h.changeCount=="number"?h.changeCount:1;return{id:e.id,kind:"file",title:m==="edit"?"Plan updated":"Plan rewritten",body:`${v} change${v===1?"":"s"}`,createdAt:e.createdAt??new Date().toISOString(),linkedTaskId:$e(c.id)||void 0,meta:y}}if(e.event==="server.complex_task.plan_update_failed"){const o=Ee(e.data);return{id:e.id,kind:"error",title:"Plan update failed",body:$e(o.reason)||"The proposed Plan change could not be applied.",createdAt:e.createdAt??new Date().toISOString(),meta:"not applied"}}if(e.event==="runtime.command.started"||e.event==="runtime.command.completed"){const o=Ee(e.data),c=e.event==="runtime.command.completed",f=typeof o.exitCode=="number"?o.exitCode:null;return{id:e.id,kind:"command",title:c?f!==null&&f!==0?"Command failed":"Command completed":"Seele ran command",body:typeof o.command=="string"?Pd(o.command):"command",createdAt:e.createdAt??new Date().toISOString(),itemId:typeof o.itemId=="string"?o.itemId:void 0,meta:c?f!==null?`exit ${f}`:"done":"running",output:c&&typeof o.output=="string"&&o.output?o.output:void 0}}if(e.event==="runtime.compaction.started"||e.event==="runtime.compaction.completed"){const o=Ee(e.data),c=e.event==="runtime.compaction.completed";return{id:e.id,kind:"activity",title:c?"Context compacted":"Compacting context",body:Kp(o,c),createdAt:e.createdAt??new Date().toISOString(),itemId:typeof o.itemId=="string"?o.itemId:void 0,meta:c?"done":"running"}}if(e.event==="codex.server_request"){const o=Ee(e.data);if(o.method==="item/commandExecution/requestApproval"){const c=eD(o.requestId),f=Ee(o.params),h=typeof f.command=="string"?f.command:"command";return{id:e.id,kind:"command",title:"Command waiting for approval",body:h,createdAt:e.createdAt??new Date().toISOString(),itemId:typeof f.itemId=="string"?f.itemId:void 0,meta:"approval",approvalRequestId:c??void 0,approvalTurnId:typeof e.turnId=="string"?e.turnId:typeof f.turnId=="string"?f.turnId:void 0,approvalReason:typeof f.reason=="string"?f.reason:void 0}}}if(e.event!=="codex.notification")return null;const n=Ee(e.data),i=n.method,l=Ee(n.params);if(i==="item/started"){const o=Ee(l.item);if(o.type==="commandExecution"){const f=o.status==="inProgress"&&o.processId===null;return{id:e.id,kind:"command",title:f?"Command waiting for approval":"Seele ran command",body:Pd(o.command),createdAt:e.createdAt??new Date().toISOString(),itemId:typeof o.id=="string"?o.id:void 0,meta:f?"approval":"running"}}const c=Fp(o);if(c.length>0)return{id:e.id,kind:"file",title:"File change",body:c[0].path,createdAt:e.createdAt??new Date().toISOString(),itemId:$e(o.id)||void 0,meta:"started",fileChanges:c}}if(i==="item/completed"){const o=Ee(l.item);if(o.type==="commandExecution"){const f=typeof o.exitCode=="number"?o.exitCode:null;return{id:e.id,kind:"command",title:f!==null&&f!==0?"Command failed":"Command completed",body:Pd(o.command),createdAt:e.createdAt??new Date().toISOString(),itemId:typeof o.id=="string"?o.id:void 0,meta:f!==null?`exit ${f}`:"done",output:typeof o.aggregatedOutput=="string"&&o.aggregatedOutput?o.aggregatedOutput:void 0}}const c=Fp(o);if(c.length>0)return{id:e.id,kind:"file",title:"File changed",body:c[0].path,createdAt:e.createdAt??new Date().toISOString(),itemId:$e(o.id)||void 0,meta:"done",fileChanges:c}}return i==="item/commandExecution/outputDelta"?{id:e.id,kind:"command",title:"Command output",body:typeof l.itemId=="string"?l.itemId:"command",createdAt:e.createdAt??new Date().toISOString(),itemId:typeof l.itemId=="string"?l.itemId:void 0,meta:"running",output:typeof l.delta=="string"?l.delta:void 0}:null}function _z(e){if(e.event!=="codex.notification")return null;const t=Ee(e.data),n=t.method;if(n!=="item/started"&&n!=="item/completed")return null;const i=Ee(t.params),l=Ee(i.item),o=typeof l.type=="string"?l.type:"item";if(N7(o)||q7(l))return null;const c=n==="item/completed",f=Ee(l.arguments),h=o==="dynamicToolCall"&&typeof l.tool=="string"?l.tool:null;return{id:e.id,kind:h==="seele_topics"?"collaboration":h==="seele_workspace_change"?"workspaceChange":"activity",title:h?M7(h,c,f):c?`Finished ${Wl(o)}`:`Working on ${Wl(o)}`,body:h?z7(h,f):R7(l,o),createdAt:e.createdAt??new Date().toISOString(),itemId:typeof l.id=="string"?l.id:void 0,meta:h==="seele_wakeup"&&c?"after turn":c?Iz(l):"running",topicAction:h==="seele_topics"?A7(f.action):void 0,workspaceChangeType:h==="seele_workspace_change"&&$e(f.type)||void 0,workspaceChangePayload:h==="seele_workspace_change"?Ee(f.payload):void 0}}function A7(e){return e==="read"||e==="history"||e==="send"?e:void 0}function Bz(e){if(B7(e)||["server.turn","server.done","server.notification.sent","server.notification.failed","server.approval.decision","server.workspace_change.decision","server.responsibility.decision","server.knowledge.decision","server.collaboration.topic_created"].includes(e.event))return null;const t=TA(e);return t?{id:e.id,kind:"activity",title:_7(t),body:E7(e.data),createdAt:e.createdAt??new Date().toISOString(),meta:"event"}:null}function E7(e){const t=Ee(e);for(const n of["title","message","description","status","reason"])if(typeof t[n]=="string"&&t[n].trim())return O7(t[n].trim(),180);return"Event details are available"}function N7(e){return["agentMessage","assistantMessage","commandExecution","message","reasoning","plan","systemMessage","userMessage"].includes(e)}function Iz(e){return e.status==="failed"||e.status==="error"?"failed":e.status==="cancelled"||e.status==="canceled"?"stopped":"done"}function Wl(e){return e.replace(/([a-z])([A-Z])/g,"$1 $2").replace(/[-_]+/g," ").toLowerCase()}function M7(e,t,n){if(e==="seele_topics")switch($e(n.action)){case"read":return"Read messages";case"history":return"Review history";case"send":return"Send message";default:return t?"Operation completed":"Working"}if(e==="seele_wakeup"){const l=$e(n.action)==="cancel";return t?l?"Wakeup cancellation requested":"Wakeup requested":l?"Requesting wakeup cancellation":"Requesting wakeup"}if(e==="seele_workspace_change")return t?"Workspace change proposed":"Preparing workspace change";const i=Wl(e);return t?`Finished ${i}`:`Running ${i}`}function z7(e,t){if(e==="seele_topics"){const n=$e(t.topicId);return n?`Topic ${Xl(n)}`:"Topic"}if(e==="seele_wakeup")return $e(t.instruction)||($e(t.action)==="cancel"?"Cancel the current wakeup":"Schedule the current wakeup");if(e==="seele_workspace_change"){const n=$e(t.type)||"workspace";return D7(n,Ee(t.payload))}return Wl(e)}function D7(e,t){return e==="responsibility"?$e(t.content)||"Workspace responsibility":JSON.stringify(t,null,2)}function R7(e,t){for(const n of["title","name","description","text","summary"])if(typeof e[n]=="string"&&e[n].trim())return Xo(e[n].trim(),160);return typeof e.id=="string"?`${Wl(t)} ${Xl(e.id)}`:Wl(t)}function Lz(e){var n;if(e.meta==="running")return"running";if(e.meta==="approval")return"approval";if(e.meta==="stopped")return"stopped";const t=(n=e.meta)==null?void 0:n.match(/^exit\s+(-?\d+)$/);return t?Number(t[1])===0?"done":"failed":"done"}function qz(e,t){return t==="running"?"running":t==="approval"?"approval":t==="stopped"?"stopped":t==="failed"?e.meta??"failed":"ok"}function Uz(e,t){var i;if(t==="running")return"Command is still running.";if(t==="approval")return"Waiting for approval before running.";if(t==="stopped")return"Command was stopped.";const n=(i=e.meta)==null?void 0:i.match(/^exit\s+(-?\d+)$/);return n?`Exit code: ${n[1]}`:t==="failed"?"Command failed.":"Command completed."}function Hz(e,t){const n=e.split(/\r?\n/),l=n.slice(0,t).join(`
388
+ `);return{id:e.id,kind:"activity",title:"Seele needs input",body:h||"Please answer in the main input box to continue.",createdAt:e.createdAt??new Date().toISOString(),meta:"waiting for reply"}}}if(e.event==="server.agent_action.staged"){const o=Ee(e.data);if($e(o.actionType)==="seele_workspace_change"){const f=Ee(o.payload),h=Ee(f.payload),m=$e(f.type)||"workspace";return{id:e.id,kind:"workspaceChange",title:"Preparing workspace change",body:D7(m,h),createdAt:e.createdAt??new Date().toISOString(),itemId:$e(o.toolCallId)||void 0,meta:"pending turn",workspaceChangeType:m,workspaceChangePayload:h}}const c=NA(o);return{id:e.id,kind:"activity",title:c.title,body:c.detail,createdAt:e.createdAt??new Date().toISOString(),itemId:$e(o.toolCallId)||void 0,meta:c.meta}}if(e.event==="server.workspace_inbox.offered"){const o=EA(e.data);return{id:e.id,kind:"activity",title:o.title,body:o.detail,createdAt:e.createdAt??new Date().toISOString(),meta:o.meta}}if(e.event==="codex.dynamic_tool_request"){const o=Ee(e.data),c=Ee(o.params),f=$e(c.tool)||"dynamic tool",h=Ee(c.arguments);return{id:e.id,kind:f==="seele_topics"?"collaboration":f==="seele_workspace_change"?"workspaceChange":"activity",title:M7(f,!1,h),body:z7(f,h),createdAt:e.createdAt??new Date().toISOString(),itemId:$e(c.callId)||void 0,meta:"running",topicAction:f==="seele_topics"?A7(h.action):void 0,workspaceChangeType:f==="seele_workspace_change"&&$e(h.type)||void 0,workspaceChangePayload:f==="seele_workspace_change"?Ee(h.payload):void 0}}if(e.event==="server.workspace_change.proposed"||e.event==="server.responsibility.proposed"){const o=Ee(e.data),c=Ee(o.payload),f=$e(c.content)||$e(o.responsibility);return{id:e.id,kind:"workspaceChange",title:"Workspace change proposed",body:f,createdAt:e.createdAt??new Date().toISOString(),itemId:$e(o.toolCallId)||void 0,meta:"pending",responsibilityProposalId:String(e.id),workspaceChangeProposalId:String(e.id),responsibilityReason:typeof o.reason=="string"?o.reason:void 0,responsibilityAnchorOffset:typeof o.anchorOffset=="number"?o.anchorOffset:void 0,workspaceChangeType:$e(o.changeType)||"responsibility",workspaceChangePayload:Object.keys(c).length>0?c:{content:f}}}if(e.event==="server.knowledge.proposed"){const o=Ee(e.data),c=Ee(o.knowledge);return{id:e.id,kind:"knowledge",title:o.action==="update"?"Knowledge update proposed":"Knowledge creation proposed",body:JSON.stringify(c,null,2),createdAt:e.createdAt??new Date().toISOString(),meta:"pending",knowledgeProposalId:String(e.id),knowledgeAnchorOffset:typeof o.anchorOffset=="number"?o.anchorOffset:void 0}}if(e.event==="server.complex_task.plan_updated"){const o=Ee(e.data),c=Ee(o.task),f=Ee(c.currentPlan),h=Ee(o.update),m=$e(h.operation),y=typeof f.version=="number"?`v${f.version}`:"updated",v=typeof h.changeCount=="number"?h.changeCount:1;return{id:e.id,kind:"file",title:m==="edit"?"Plan updated":"Plan rewritten",body:`${v} change${v===1?"":"s"}`,createdAt:e.createdAt??new Date().toISOString(),linkedTaskId:$e(c.id)||void 0,meta:y}}if(e.event==="server.complex_task.plan_update_failed"){const o=Ee(e.data);return{id:e.id,kind:"error",title:"Plan update failed",body:$e(o.reason)||"The proposed Plan change could not be applied.",createdAt:e.createdAt??new Date().toISOString(),meta:"not applied"}}if(e.event==="runtime.command.started"||e.event==="runtime.command.completed"){const o=Ee(e.data),c=e.event==="runtime.command.completed",f=typeof o.exitCode=="number"?o.exitCode:null;return{id:e.id,kind:"command",title:c?f!==null&&f!==0?"Command failed":"Command completed":"Seele ran command",body:typeof o.command=="string"?Pd(o.command):"command",createdAt:e.createdAt??new Date().toISOString(),itemId:typeof o.itemId=="string"?o.itemId:void 0,meta:c?f!==null?`exit ${f}`:"done":"running",output:c&&typeof o.output=="string"&&o.output?o.output:void 0}}if(e.event==="runtime.compaction.started"||e.event==="runtime.compaction.completed"){const o=Ee(e.data),c=e.event==="runtime.compaction.completed";return{id:e.id,kind:"activity",title:c?"Context compacted":"Compacting context",body:Kp(o,c),createdAt:e.createdAt??new Date().toISOString(),itemId:typeof o.itemId=="string"?o.itemId:void 0,meta:c?"done":"running"}}if(e.event==="codex.server_request"){const o=Ee(e.data);if(o.method==="item/commandExecution/requestApproval"){const c=tD(o.requestId),f=Ee(o.params),h=typeof f.command=="string"?f.command:"command";return{id:e.id,kind:"command",title:"Command waiting for approval",body:h,createdAt:e.createdAt??new Date().toISOString(),itemId:typeof f.itemId=="string"?f.itemId:void 0,meta:"approval",approvalRequestId:c??void 0,approvalTurnId:typeof e.turnId=="string"?e.turnId:typeof f.turnId=="string"?f.turnId:void 0,approvalReason:typeof f.reason=="string"?f.reason:void 0}}}if(e.event!=="codex.notification")return null;const n=Ee(e.data),i=n.method,l=Ee(n.params);if(i==="item/started"){const o=Ee(l.item);if(o.type==="commandExecution"){const f=o.status==="inProgress"&&o.processId===null;return{id:e.id,kind:"command",title:f?"Command waiting for approval":"Seele ran command",body:Pd(o.command),createdAt:e.createdAt??new Date().toISOString(),itemId:typeof o.id=="string"?o.id:void 0,meta:f?"approval":"running"}}const c=Fp(o);if(c.length>0)return{id:e.id,kind:"file",title:"File change",body:c[0].path,createdAt:e.createdAt??new Date().toISOString(),itemId:$e(o.id)||void 0,meta:"started",fileChanges:c}}if(i==="item/completed"){const o=Ee(l.item);if(o.type==="commandExecution"){const f=typeof o.exitCode=="number"?o.exitCode:null;return{id:e.id,kind:"command",title:f!==null&&f!==0?"Command failed":"Command completed",body:Pd(o.command),createdAt:e.createdAt??new Date().toISOString(),itemId:typeof o.id=="string"?o.id:void 0,meta:f!==null?`exit ${f}`:"done",output:typeof o.aggregatedOutput=="string"&&o.aggregatedOutput?o.aggregatedOutput:void 0}}const c=Fp(o);if(c.length>0)return{id:e.id,kind:"file",title:"File changed",body:c[0].path,createdAt:e.createdAt??new Date().toISOString(),itemId:$e(o.id)||void 0,meta:"done",fileChanges:c}}return i==="item/commandExecution/outputDelta"?{id:e.id,kind:"command",title:"Command output",body:typeof l.itemId=="string"?l.itemId:"command",createdAt:e.createdAt??new Date().toISOString(),itemId:typeof l.itemId=="string"?l.itemId:void 0,meta:"running",output:typeof l.delta=="string"?l.delta:void 0}:null}function Bz(e){if(e.event!=="codex.notification")return null;const t=Ee(e.data),n=t.method;if(n!=="item/started"&&n!=="item/completed")return null;const i=Ee(t.params),l=Ee(i.item),o=typeof l.type=="string"?l.type:"item";if(N7(o)||q7(l))return null;const c=n==="item/completed",f=Ee(l.arguments),h=o==="dynamicToolCall"&&typeof l.tool=="string"?l.tool:null;return{id:e.id,kind:h==="seele_topics"?"collaboration":h==="seele_workspace_change"?"workspaceChange":"activity",title:h?M7(h,c,f):c?`Finished ${Wl(o)}`:`Working on ${Wl(o)}`,body:h?z7(h,f):R7(l,o),createdAt:e.createdAt??new Date().toISOString(),itemId:typeof l.id=="string"?l.id:void 0,meta:h==="seele_wakeup"&&c?"after turn":c?Lz(l):"running",topicAction:h==="seele_topics"?A7(f.action):void 0,workspaceChangeType:h==="seele_workspace_change"&&$e(f.type)||void 0,workspaceChangePayload:h==="seele_workspace_change"?Ee(f.payload):void 0}}function A7(e){return e==="read"||e==="history"||e==="send"?e:void 0}function Iz(e){if(B7(e)||["server.turn","server.done","server.notification.sent","server.notification.failed","server.approval.decision","server.workspace_change.decision","server.responsibility.decision","server.knowledge.decision","server.collaboration.topic_created"].includes(e.event))return null;const t=AA(e);return t?{id:e.id,kind:"activity",title:_7(t),body:E7(e.data),createdAt:e.createdAt??new Date().toISOString(),meta:"event"}:null}function E7(e){const t=Ee(e);for(const n of["title","message","description","status","reason"])if(typeof t[n]=="string"&&t[n].trim())return O7(t[n].trim(),180);return"Event details are available"}function N7(e){return["agentMessage","assistantMessage","commandExecution","message","reasoning","plan","systemMessage","userMessage"].includes(e)}function Lz(e){return e.status==="failed"||e.status==="error"?"failed":e.status==="cancelled"||e.status==="canceled"?"stopped":"done"}function Wl(e){return e.replace(/([a-z])([A-Z])/g,"$1 $2").replace(/[-_]+/g," ").toLowerCase()}function M7(e,t,n){if(e==="seele_topics")switch($e(n.action)){case"read":return"Read messages";case"history":return"Review history";case"send":return"Send message";default:return t?"Operation completed":"Working"}if(e==="seele_wakeup"){const l=$e(n.action)==="cancel";return t?l?"Wakeup cancellation requested":"Wakeup requested":l?"Requesting wakeup cancellation":"Requesting wakeup"}if(e==="seele_workspace_change")return t?"Workspace change proposed":"Preparing workspace change";const i=Wl(e);return t?`Finished ${i}`:`Running ${i}`}function z7(e,t){if(e==="seele_topics"){const n=$e(t.topicId);return n?`Topic ${Xl(n)}`:"Topic"}if(e==="seele_wakeup")return $e(t.instruction)||($e(t.action)==="cancel"?"Cancel the current wakeup":"Schedule the current wakeup");if(e==="seele_workspace_change"){const n=$e(t.type)||"workspace";return D7(n,Ee(t.payload))}return Wl(e)}function D7(e,t){return e==="responsibility"?$e(t.content)||"Workspace responsibility":JSON.stringify(t,null,2)}function R7(e,t){for(const n of["title","name","description","text","summary"])if(typeof e[n]=="string"&&e[n].trim())return Xo(e[n].trim(),160);return typeof e.id=="string"?`${Wl(t)} ${Xl(e.id)}`:Wl(t)}function qz(e){var n;if(e.meta==="running")return"running";if(e.meta==="approval")return"approval";if(e.meta==="stopped")return"stopped";const t=(n=e.meta)==null?void 0:n.match(/^exit\s+(-?\d+)$/);return t?Number(t[1])===0?"done":"failed":"done"}function Uz(e,t){return t==="running"?"running":t==="approval"?"approval":t==="stopped"?"stopped":t==="failed"?e.meta??"failed":"ok"}function Hz(e,t){var i;if(t==="running")return"Command is still running.";if(t==="approval")return"Waiting for approval before running.";if(t==="stopped")return"Command was stopped.";const n=(i=e.meta)==null?void 0:i.match(/^exit\s+(-?\d+)$/);return n?`Exit code: ${n[1]}`:t==="failed"?"Command failed.":"Command completed."}function Fz(e,t){const n=e.split(/\r?\n/),l=n.slice(0,t).join(`
383
389
  `);return n.length>t?`${l}
384
- ...`:l}function Fz(e,t){return e?e.split(/\r?\n/).filter(n=>n.trim()).length>t:!1}function lf(e){return/^call_[A-Za-z0-9]+$/.test(e)||e==="command"}function $z(e){const t=e.trim();return!t||t.includes(`
385
- `)?null:Xo(t,120)}function Xo(e,t){if(e.length<=t)return e;const n=Math.max(8,Math.floor((t-3)/2));return`${e.slice(0,n)}...${e.slice(-n)}`}function O7(e,t){return e.length<=t?e:`${e.slice(0,Math.max(1,t-3))}...`}function _7(e){const n=(e.split(/[./]/).filter(Boolean).pop()??e).replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/[_-]+/g," ").trim();return n?n.charAt(0).toUpperCase()+n.slice(1):"System event"}function B7(e){const t=e.createdAt??new Date().toISOString();if(e.event==="server.status"){const o=Ee(e.data);if(o.status==="initialized")return{id:e.id,title:"Connected to Seele runtime",createdAt:t,tone:"done"};if(o.status==="turn_started")return{id:e.id,title:"Turn started",createdAt:t,tone:"running"};if(o.status==="archived_thread_replaced")return{id:e.id,title:"Started a fresh runtime thread",detail:typeof o.archivedThreadId=="string"?`archived ${Xl(o.archivedThreadId)}`:void 0,createdAt:t,tone:"warning"}}if(e.event==="server.stopped"||e.event==="server.stop")return{id:e.id,title:"Stopped current run",createdAt:t,tone:"error"};if(e.event==="runtime.worker_stale")return{id:e.id,title:"Runtime appears stalled",detail:"No runtime signal for a while",createdAt:t,tone:"warning"};if(e.event==="runtime.worker_recovered")return{id:e.id,title:"Runtime resumed",createdAt:t,tone:"running"};if(e.event==="runtime.compaction.started"){const o=Ee(e.data);return{id:e.id,title:"Codex compacting context",detail:Kp(o,!1),createdAt:t,tone:"running"}}if(e.event==="runtime.compaction.completed"){const o=Ee(e.data);return{id:e.id,title:"Codex context compacted",detail:Kp(o,!0),createdAt:t,tone:"done"}}if(e.event==="server.turn.long_running")return{id:e.id,title:"Long run in progress",detail:"Consider splitting into a wakeup phase",createdAt:t,tone:"warning"};if(e.event==="server.turn.phase_boundary_recommended"){const o=Ee(e.data);return{id:e.id,title:"Phase boundary recommended",detail:typeof o.operationCount=="number"?`${o.operationCount} operations in this turn`:"Many operations in this turn",createdAt:t,tone:"warning"}}if(e.event==="server.wakeup.started"){const o=Ee(e.data);return{id:e.id,title:"Scheduled wakeup resumed",detail:typeof o.instruction=="string"?Xo(o.instruction,96):void 0,createdAt:t,tone:"running"}}if(e.event==="codex.server_request"){const o=Ee(e.data);if(o.method==="item/commandExecution/requestApproval"){const c=Ee(o.params);return{id:e.id,title:"Waiting for approval",detail:typeof c.command=="string"?Xo(c.command,96):"Command needs confirmation",createdAt:t,tone:"warning"}}}if(e.event!=="codex.notification")return null;const n=Ee(e.data),i=n.method,l=Ee(n.params);if(i==="item/started"||i==="item/completed"){const o=Ee(l.item),c=typeof o.type=="string"?o.type:"item",f=i==="item/completed";if(c==="commandExecution")return{id:e.id,title:f?"Command completed":"Running command",detail:Xo(Pd(o.command),96),createdAt:t,tone:f?"done":"running"};if(c==="contextCompaction")return{id:e.id,title:f?"Codex context compacted":"Codex compacting context",detail:f?void 0:"Current runtime thread is being compacted",createdAt:t,tone:f?"done":"running"};const h=q7(o);if(h)return{id:e.id,title:f?"File update finished":"Editing file",detail:Xo(h,96),createdAt:t,tone:f?"done":"running"};if(!N7(c))return{id:e.id,title:f?`Finished ${Wl(c)}`:`Working on ${Wl(c)}`,detail:R7(o,c),createdAt:t,tone:f?"done":"running"}}if(i==="thread/status/changed"){const o=Ee(l.status),c=Array.isArray(o.activeFlags)?o.activeFlags:[];if(o.type==="active"&&c.some(f=>f==="waitingOnApproval"))return{id:e.id,title:"Waiting for approval",detail:"Command needs confirmation",createdAt:t,tone:"warning"}}if(i==="turn/started")return{id:e.id,title:"Seele started working",createdAt:t,tone:"running"};if(i==="turn/completed"){const o=Ee(l.turn);return{id:e.id,title:"Turn completed",detail:typeof o.durationMs=="number"?ru(o.durationMs):void 0,createdAt:t,tone:"done"}}if(i==="hook/started"||i==="hook/completed"){const o=Ee(l.run),c=typeof o.eventName=="string"?o.eventName:"hook";return{id:e.id,title:i==="hook/started"?`Running ${x5(c)}`:`Finished ${x5(c)}`,detail:typeof o.durationMs=="number"?ru(o.durationMs):void 0,createdAt:t,tone:i==="hook/started"?"running":"done"}}return null}function Kp(e,t){const n=sf(e.before),i=sf(e.after),l=[];if(t){const o=typeof e.durationMs=="number"?e.durationMs:null;l.push(o===null?"Completed":`Completed in ${ru(o)}`)}else l.push("Codex triggered");if(n&&i){l.push(`context ${qs(n)} → ${qs(i)}`);const o=n.totalTokens-i.totalTokens;o>0&&l.push(`released ~${V1(o)} tokens`)}else n&&l.push(`context ${qs(n)}`);return l.join(" · ")}function Gz(e){const t=sf(e.before),n=sf(e.after),i=t&&n?t.totalTokens-n.totalTokens:null;let l="Unavailable";return t&&n?l=`${qs(t)} → ${qs(n)}`:t?l=`${qs(t)} → unavailable`:n&&(l=`unavailable → ${qs(n)}`),[{label:"Trigger",value:e.trigger==="codex"?"Codex automatic":e.trigger??"Unavailable"},{label:"Duration",value:e.durationMs===null?"Unavailable":ru(e.durationMs)},{label:"Context",value:l},{label:"Released",value:i===null?"Unavailable":i>0?`~${V1(i)} tokens`:"No decrease observed"}]}function sf(e){const t=Ee(e);return typeof t.totalTokens=="number"?{totalTokens:t.totalTokens,modelContextWindow:typeof t.modelContextWindow=="number"?t.modelContextWindow:null}:null}function qs(e){return e.modelContextWindow&&e.modelContextWindow>0?`${Math.round(e.totalTokens/e.modelContextWindow*100)}%`:`${V1(e.totalTokens)} tokens`}function V1(e){return new Intl.NumberFormat("en",{notation:"compact",maximumFractionDigits:1}).format(Math.max(0,e))}function Pz(e){let t=null;for(const n of e)for(const i of n.events){const l=Wz(i);l&&(!t||Date.parse(l.updatedAt)>Date.parse(t.updatedAt))&&(t=l)}return t}function v5(...e){return e.reduce((t,n)=>n&&(!t||Date.parse(n.updatedAt)>Date.parse(t.updatedAt))?n:t,null)}function Vz(e){let t=null;for(const n of e){const i=I7(n);i&&(!t||Bc(n,t)>0)&&(t=i)}return t}function I7(e){if(e.event!=="codex.notification")return null;const t=Ee(e.data);if(t.method!=="thread/tokenUsage/updated")return null;const n=Ee(t.params),i=Ee(n.tokenUsage),l=Ee(i.last),o=Ee(i.total),c=Object.keys(l).length>0?l:o,f=la(c.totalTokens);return f===null?null:{totalTokens:f,inputTokens:la(c.inputTokens),cachedInputTokens:la(c.cachedInputTokens),outputTokens:la(c.outputTokens),reasoningOutputTokens:la(c.reasoningOutputTokens),modelContextWindow:la(i.modelContextWindow),createdAt:e.createdAt??new Date().toISOString()}}function Yz(...e){return e.reduce((t,n)=>n&&(!t||Date.parse(n.createdAt)>Date.parse(t.createdAt))?n:t,null)}function L7(e){return e!=null&&e.modelContextWindow&&e.modelContextWindow>0?e.totalTokens/e.modelContextWindow*100:null}function Wz(e){if(e.event!=="codex.notification")return null;const t=Ee(e.data);if(t.method!=="account/rateLimits/updated")return null;const n=Ee(t.params),i=Ee(n.rateLimits),l=[i.primary,i.secondary].map(o=>Xz(o)).filter(o=>o!==null);return l.length===0?null:{windows:l,updatedAt:e.createdAt??new Date().toISOString()}}function Xz(e){const t=Ee(e);return typeof t.usedPercent!="number"||typeof t.resetsAt!="number"||typeof t.windowDurationMins!="number"?null:{usedPercent:t.usedPercent,resetsAt:t.resetsAt,windowDurationMins:t.windowDurationMins}}function Kz(e,t){return e?!t||e===t?e:t.startsWith(e)?t:`${e}${t}`:t}function Pd(e){return typeof e=="string"?e:Array.isArray(e)?e.map(t=>String(t)).join(" "):"command"}function q7(e){var n;const t=e.path??e.file??e.filename;return typeof t=="string"?t:((n=Fp(e)[0])==null?void 0:n.path)??null}function Ee(e){return e&&typeof e=="object"?e:{}}function la(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function $e(e){return typeof e=="string"?e:""}function Us(e){return e.replace(/([\\`*_[\]<>])/g,"\\$1")}function Qz(e){const t=Ee(e),n=Ee(t.thread);if(!Object.keys(n).length)return null;const i=Array.isArray(n.turns)?n.turns:[],l=[];let o=0,c=0,f=0,h=0,m=0;return i.forEach((y,v)=>{const k=Ee(y),w=$e(k.id)||`turn-${v+1}`,T=Array.isArray(k.items)?k.items:[];o+=T.length,l.push(Zz(k,w)),T.forEach(E=>{const q=Ee(E),R=$e(q.type);R==="userMessage"?c+=1:R==="agentMessage"?f+=1:R==="compaction"?h+=1:R==="contextCompaction"&&(m+=1)})}),{id:$e(n.id),sessionId:$e(n.sessionId),status:U7(n.status),source:Y1(n.source),cwd:$e(n.cwd),path:$e(n.path),preview:$e(n.preview),createdAt:la(n.createdAt),updatedAt:la(n.updatedAt),recencyAt:la(n.recencyAt),turnCount:i.length,itemCount:o,userMessageCount:c,agentMessageCount:f,compactionCount:h,contextCompactionCount:m,turns:l}}function Zz(e,t){const n=Array.isArray(e.items)?e.items:[],i=Array.from(new Set(n.map(o=>$e(Ee(o).type)).filter(o=>o.length>0))).join(", "),l=Jz(n.map(o=>Qp(o)).filter(Boolean).join(" "),220);return{id:t,status:U7(e.status),itemsView:$e(e.itemsView)||"unknown",itemCount:n.length,startedAt:la(e.startedAt),completedAt:la(e.completedAt),durationMs:la(e.durationMs),itemTypes:i,preview:l,raw:e}}function Qp(e){if(typeof e=="string")return e;if(Array.isArray(e))return e.map(Qp).filter(Boolean).join(`
390
+ ...`:l}function $z(e,t){return e?e.split(/\r?\n/).filter(n=>n.trim()).length>t:!1}function lf(e){return/^call_[A-Za-z0-9]+$/.test(e)||e==="command"}function Gz(e){const t=e.trim();return!t||t.includes(`
391
+ `)?null:Xo(t,120)}function Xo(e,t){if(e.length<=t)return e;const n=Math.max(8,Math.floor((t-3)/2));return`${e.slice(0,n)}...${e.slice(-n)}`}function O7(e,t){return e.length<=t?e:`${e.slice(0,Math.max(1,t-3))}...`}function _7(e){const n=(e.split(/[./]/).filter(Boolean).pop()??e).replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/[_-]+/g," ").trim();return n?n.charAt(0).toUpperCase()+n.slice(1):"System event"}function B7(e){const t=e.createdAt??new Date().toISOString();if(e.event==="server.status"){const o=Ee(e.data);if(o.status==="initialized")return{id:e.id,title:"Connected to Seele runtime",createdAt:t,tone:"done"};if(o.status==="turn_started")return{id:e.id,title:"Turn started",createdAt:t,tone:"running"};if(o.status==="archived_thread_replaced")return{id:e.id,title:"Started a fresh runtime thread",detail:typeof o.archivedThreadId=="string"?`archived ${Xl(o.archivedThreadId)}`:void 0,createdAt:t,tone:"warning"}}if(e.event==="server.stopped"||e.event==="server.stop")return{id:e.id,title:"Stopped current run",createdAt:t,tone:"error"};if(e.event==="runtime.worker_stale")return{id:e.id,title:"Runtime appears stalled",detail:"No runtime signal for a while",createdAt:t,tone:"warning"};if(e.event==="runtime.worker_recovered")return{id:e.id,title:"Runtime resumed",createdAt:t,tone:"running"};if(e.event==="runtime.compaction.started"){const o=Ee(e.data);return{id:e.id,title:"Codex compacting context",detail:Kp(o,!1),createdAt:t,tone:"running"}}if(e.event==="runtime.compaction.completed"){const o=Ee(e.data);return{id:e.id,title:"Codex context compacted",detail:Kp(o,!0),createdAt:t,tone:"done"}}if(e.event==="server.turn.long_running")return{id:e.id,title:"Long run in progress",detail:"Consider splitting into a wakeup phase",createdAt:t,tone:"warning"};if(e.event==="server.turn.phase_boundary_recommended"){const o=Ee(e.data);return{id:e.id,title:"Phase boundary recommended",detail:typeof o.operationCount=="number"?`${o.operationCount} operations in this turn`:"Many operations in this turn",createdAt:t,tone:"warning"}}if(e.event==="server.wakeup.started"){const o=Ee(e.data);return{id:e.id,title:"Scheduled wakeup resumed",detail:typeof o.instruction=="string"?Xo(o.instruction,96):void 0,createdAt:t,tone:"running"}}if(e.event==="codex.server_request"){const o=Ee(e.data);if(o.method==="item/commandExecution/requestApproval"){const c=Ee(o.params);return{id:e.id,title:"Waiting for approval",detail:typeof c.command=="string"?Xo(c.command,96):"Command needs confirmation",createdAt:t,tone:"warning"}}}if(e.event!=="codex.notification")return null;const n=Ee(e.data),i=n.method,l=Ee(n.params);if(i==="item/started"||i==="item/completed"){const o=Ee(l.item),c=typeof o.type=="string"?o.type:"item",f=i==="item/completed";if(c==="commandExecution")return{id:e.id,title:f?"Command completed":"Running command",detail:Xo(Pd(o.command),96),createdAt:t,tone:f?"done":"running"};if(c==="contextCompaction")return{id:e.id,title:f?"Codex context compacted":"Codex compacting context",detail:f?void 0:"Current runtime thread is being compacted",createdAt:t,tone:f?"done":"running"};const h=q7(o);if(h)return{id:e.id,title:f?"File update finished":"Editing file",detail:Xo(h,96),createdAt:t,tone:f?"done":"running"};if(!N7(c))return{id:e.id,title:f?`Finished ${Wl(c)}`:`Working on ${Wl(c)}`,detail:R7(o,c),createdAt:t,tone:f?"done":"running"}}if(i==="thread/status/changed"){const o=Ee(l.status),c=Array.isArray(o.activeFlags)?o.activeFlags:[];if(o.type==="active"&&c.some(f=>f==="waitingOnApproval"))return{id:e.id,title:"Waiting for approval",detail:"Command needs confirmation",createdAt:t,tone:"warning"}}if(i==="turn/started")return{id:e.id,title:"Seele started working",createdAt:t,tone:"running"};if(i==="turn/completed"){const o=Ee(l.turn);return{id:e.id,title:"Turn completed",detail:typeof o.durationMs=="number"?ru(o.durationMs):void 0,createdAt:t,tone:"done"}}if(i==="hook/started"||i==="hook/completed"){const o=Ee(l.run),c=typeof o.eventName=="string"?o.eventName:"hook";return{id:e.id,title:i==="hook/started"?`Running ${x5(c)}`:`Finished ${x5(c)}`,detail:typeof o.durationMs=="number"?ru(o.durationMs):void 0,createdAt:t,tone:i==="hook/started"?"running":"done"}}return null}function Kp(e,t){const n=sf(e.before),i=sf(e.after),l=[];if(t){const o=typeof e.durationMs=="number"?e.durationMs:null;l.push(o===null?"Completed":`Completed in ${ru(o)}`)}else l.push("Codex triggered");if(n&&i){l.push(`context ${qs(n)} → ${qs(i)}`);const o=n.totalTokens-i.totalTokens;o>0&&l.push(`released ~${V1(o)} tokens`)}else n&&l.push(`context ${qs(n)}`);return l.join(" · ")}function Pz(e){const t=sf(e.before),n=sf(e.after),i=t&&n?t.totalTokens-n.totalTokens:null;let l="Unavailable";return t&&n?l=`${qs(t)} → ${qs(n)}`:t?l=`${qs(t)} → unavailable`:n&&(l=`unavailable → ${qs(n)}`),[{label:"Trigger",value:e.trigger==="codex"?"Codex automatic":e.trigger??"Unavailable"},{label:"Duration",value:e.durationMs===null?"Unavailable":ru(e.durationMs)},{label:"Context",value:l},{label:"Released",value:i===null?"Unavailable":i>0?`~${V1(i)} tokens`:"No decrease observed"}]}function sf(e){const t=Ee(e);return typeof t.totalTokens=="number"?{totalTokens:t.totalTokens,modelContextWindow:typeof t.modelContextWindow=="number"?t.modelContextWindow:null}:null}function qs(e){return e.modelContextWindow&&e.modelContextWindow>0?`${Math.round(e.totalTokens/e.modelContextWindow*100)}%`:`${V1(e.totalTokens)} tokens`}function V1(e){return new Intl.NumberFormat("en",{notation:"compact",maximumFractionDigits:1}).format(Math.max(0,e))}function Vz(e){let t=null;for(const n of e)for(const i of n.events){const l=Xz(i);l&&(!t||Date.parse(l.updatedAt)>Date.parse(t.updatedAt))&&(t=l)}return t}function v5(...e){return e.reduce((t,n)=>n&&(!t||Date.parse(n.updatedAt)>Date.parse(t.updatedAt))?n:t,null)}function Yz(e){let t=null;for(const n of e){const i=I7(n);i&&(!t||Bc(n,t)>0)&&(t=i)}return t}function I7(e){if(e.event!=="codex.notification")return null;const t=Ee(e.data);if(t.method!=="thread/tokenUsage/updated")return null;const n=Ee(t.params),i=Ee(n.tokenUsage),l=Ee(i.last),o=Ee(i.total),c=Object.keys(l).length>0?l:o,f=la(c.totalTokens);return f===null?null:{totalTokens:f,inputTokens:la(c.inputTokens),cachedInputTokens:la(c.cachedInputTokens),outputTokens:la(c.outputTokens),reasoningOutputTokens:la(c.reasoningOutputTokens),modelContextWindow:la(i.modelContextWindow),createdAt:e.createdAt??new Date().toISOString()}}function Wz(...e){return e.reduce((t,n)=>n&&(!t||Date.parse(n.createdAt)>Date.parse(t.createdAt))?n:t,null)}function L7(e){return e!=null&&e.modelContextWindow&&e.modelContextWindow>0?e.totalTokens/e.modelContextWindow*100:null}function Xz(e){if(e.event!=="codex.notification")return null;const t=Ee(e.data);if(t.method!=="account/rateLimits/updated")return null;const n=Ee(t.params),i=Ee(n.rateLimits),l=[i.primary,i.secondary].map(o=>Kz(o)).filter(o=>o!==null);return l.length===0?null:{windows:l,updatedAt:e.createdAt??new Date().toISOString()}}function Kz(e){const t=Ee(e);return typeof t.usedPercent!="number"||typeof t.resetsAt!="number"||typeof t.windowDurationMins!="number"?null:{usedPercent:t.usedPercent,resetsAt:t.resetsAt,windowDurationMins:t.windowDurationMins}}function Qz(e,t){return e?!t||e===t?e:t.startsWith(e)?t:`${e}${t}`:t}function Pd(e){return typeof e=="string"?e:Array.isArray(e)?e.map(t=>String(t)).join(" "):"command"}function q7(e){var n;const t=e.path??e.file??e.filename;return typeof t=="string"?t:((n=Fp(e)[0])==null?void 0:n.path)??null}function Ee(e){return e&&typeof e=="object"?e:{}}function la(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function $e(e){return typeof e=="string"?e:""}function Us(e){return e.replace(/([\\`*_[\]<>])/g,"\\$1")}function Zz(e){const t=Ee(e),n=Ee(t.thread);if(!Object.keys(n).length)return null;const i=Array.isArray(n.turns)?n.turns:[],l=[];let o=0,c=0,f=0,h=0,m=0;return i.forEach((y,v)=>{const k=Ee(y),w=$e(k.id)||`turn-${v+1}`,T=Array.isArray(k.items)?k.items:[];o+=T.length,l.push(Jz(k,w)),T.forEach(E=>{const q=Ee(E),R=$e(q.type);R==="userMessage"?c+=1:R==="agentMessage"?f+=1:R==="compaction"?h+=1:R==="contextCompaction"&&(m+=1)})}),{id:$e(n.id),sessionId:$e(n.sessionId),status:U7(n.status),source:Y1(n.source),cwd:$e(n.cwd),path:$e(n.path),preview:$e(n.preview),createdAt:la(n.createdAt),updatedAt:la(n.updatedAt),recencyAt:la(n.recencyAt),turnCount:i.length,itemCount:o,userMessageCount:c,agentMessageCount:f,compactionCount:h,contextCompactionCount:m,turns:l}}function Jz(e,t){const n=Array.isArray(e.items)?e.items:[],i=Array.from(new Set(n.map(o=>$e(Ee(o).type)).filter(o=>o.length>0))).join(", "),l=eD(n.map(o=>Qp(o)).filter(Boolean).join(" "),220);return{id:t,status:U7(e.status),itemsView:$e(e.itemsView)||"unknown",itemCount:n.length,startedAt:la(e.startedAt),completedAt:la(e.completedAt),durationMs:la(e.durationMs),itemTypes:i,preview:l,raw:e}}function Qp(e){if(typeof e=="string")return e;if(Array.isArray(e))return e.map(Qp).filter(Boolean).join(`
386
392
  `);if(!e||typeof e!="object")return"";const t=e,n=$e(t.text),i=Qp(t.content);return[n,i].filter(Boolean).join(`
387
- `)}function U7(e){const t=Ee(e);return $e(t.type)||Y1(e)}function Jz(e,t){const n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t)}...`:n}function kc(e){return e===null?"unknown":rt(e*1e3)}function eD(e){return typeof e=="number"&&Number.isFinite(e)||typeof e=="string"&&e.trim()?e:null}function Y1(e){if(typeof e=="string")return e;const t=JSON.stringify(e);return t.length>180?`${t.slice(0,180)}...`:t}function tD(e){if(typeof e=="string")return e;const t=Ee(e),n=typeof t.message=="string"?t.message:null,i=typeof t.detail=="string"?t.detail:null;return n&&i?`${n}
393
+ `)}function U7(e){const t=Ee(e);return $e(t.type)||Y1(e)}function eD(e,t){const n=e.replace(/\s+/g," ").trim();return n.length>t?`${n.slice(0,t)}...`:n}function kc(e){return e===null?"unknown":rt(e*1e3)}function tD(e){return typeof e=="number"&&Number.isFinite(e)||typeof e=="string"&&e.trim()?e:null}function Y1(e){if(typeof e=="string")return e;const t=JSON.stringify(e);return t.length>180?`${t.slice(0,180)}...`:t}function nD(e){if(typeof e=="string")return e;const t=Ee(e),n=typeof t.message=="string"?t.message:null,i=typeof t.detail=="string"?t.detail:null;return n&&i?`${n}
388
394
 
389
- ${i}`:n||i||Y1(e)}function x5(e){return e.replace(/([a-z])([A-Z])/g,"$1 $2").replace(/[-_]+/g," ").toLowerCase()}function ru(e){return e<1e3?`${e}ms`:`${(e/1e3).toFixed(e<1e4?1:0)}s`}function op(e){if(e<6e4)return ru(e);const t=Math.floor(e/6e4);if(t<60)return`${t}m`;const n=Math.floor(t/60),i=t%60;return i===0?`${n}h`:`${n}h ${i}m`}function H7(e){return`${Math.round(e)}%`}function wr(e){return new Intl.NumberFormat("en-US").format(e)}function Vd(e){return e===null?"unknown":wr(e)}function Nf(e){return Math.max(0,Math.min(100,Math.round(e)))}function W1(e){return e>=100?"exhausted":e>=90?"danger":e>=75?"warning":"healthy"}function F7(e){return rt(e*1e3)}function rt(e){const t=typeof e=="number"?new Date(e):new Date(e);if(Number.isNaN(t.getTime()))return"";const n={timeZone:"Asia/Shanghai",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1},i=new Intl.DateTimeFormat("en-CA",n).formatToParts(t),l=o=>{var c;return((c=i.find(f=>f.type===o))==null?void 0:c.value)??""};return`${l("month")}/${l("day")} ${l("hour")}:${l("minute")}:${l("second")}`}function Lc(e){const t=rt(e);return t?`${t} UTC+08:00`:""}function nD(e){const t=new Date(e);return Number.isNaN(t.getTime())?"--:--:--":new Intl.DateTimeFormat("en-GB",{timeZone:"Asia/Shanghai",hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1}).format(t)}function b5(e,t){const n=Nc(e,t);return n?`${n.displayName}${n.isDefault?" (default)":""}`:e||"Unavailable"}function Nc(e,t){return e?t.find(n=>n.model===e)??null:t.find(n=>n.isDefault)??t[0]??null}function Mf(e){return e?e.replace(/^codex-cli\s+/i,""):"Unavailable"}function Zp(e,t){const n=Mf(e);return t?`${n} (${rt(t)})`:n}function rD(e){return`https://github.com/openai/codex/releases/tag/rust-v${encodeURIComponent(Mf(e))}`}function aD(e,t){const n=w5(e),i=w5(t);if(!n||!i)return!1;for(let l=0;l<n.core.length;l+=1)if(n.core[l]!==i.core[l])return n.core[l]>i.core[l];return n.prerelease===i.prerelease?!1:n.prerelease?i.prerelease?n.prerelease.localeCompare(i.prerelease,void 0,{numeric:!0})>0:!1:!0}function w5(e){if(!e)return null;const t=Mf(e).match(/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?$/);return t?{core:[Number(t[1]),Number(t[2]),Number(t[3])],prerelease:t[4]??null}:null}function iD(e,t){const n=e.map(i=>({value:i.model,label:`${i.displayName}${i.isDefault?" (default)":""}`}));return t&&!e.some(i=>i.model===t)&&n.push({value:t,label:`${t} (unavailable)`}),n.length===0&&n.push({value:"",label:"Models unavailable"}),n}async function k5(e,t){const n=e.getReader(),i=new TextDecoder;let l="";for(;;){const{done:o,value:c}=await n.read();if(o)break;l+=i.decode(c,{stream:!0});const f=l.split(`
395
+ ${i}`:n||i||Y1(e)}function x5(e){return e.replace(/([a-z])([A-Z])/g,"$1 $2").replace(/[-_]+/g," ").toLowerCase()}function ru(e){return e<1e3?`${e}ms`:`${(e/1e3).toFixed(e<1e4?1:0)}s`}function op(e){if(e<6e4)return ru(e);const t=Math.floor(e/6e4);if(t<60)return`${t}m`;const n=Math.floor(t/60),i=t%60;return i===0?`${n}h`:`${n}h ${i}m`}function H7(e){return`${Math.round(e)}%`}function wr(e){return new Intl.NumberFormat("en-US").format(e)}function Vd(e){return e===null?"unknown":wr(e)}function Nf(e){return Math.max(0,Math.min(100,Math.round(e)))}function W1(e){return e>=100?"exhausted":e>=90?"danger":e>=75?"warning":"healthy"}function F7(e){return rt(e*1e3)}function rt(e){const t=typeof e=="number"?new Date(e):new Date(e);if(Number.isNaN(t.getTime()))return"";const n={timeZone:"Asia/Shanghai",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1},i=new Intl.DateTimeFormat("en-CA",n).formatToParts(t),l=o=>{var c;return((c=i.find(f=>f.type===o))==null?void 0:c.value)??""};return`${l("month")}/${l("day")} ${l("hour")}:${l("minute")}:${l("second")}`}function Lc(e){const t=rt(e);return t?`${t} UTC+08:00`:""}function rD(e){const t=new Date(e);return Number.isNaN(t.getTime())?"--:--:--":new Intl.DateTimeFormat("en-GB",{timeZone:"Asia/Shanghai",hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1}).format(t)}function b5(e,t){const n=Nc(e,t);return n?`${n.displayName}${n.isDefault?" (default)":""}`:e||"Unavailable"}function Nc(e,t){return e?t.find(n=>n.model===e)??null:t.find(n=>n.isDefault)??t[0]??null}function Mf(e){return e?e.replace(/^codex-cli\s+/i,""):"Unavailable"}function Zp(e,t){const n=Mf(e);return t?`${n} (${rt(t)})`:n}function aD(e){return`https://github.com/openai/codex/releases/tag/rust-v${encodeURIComponent(Mf(e))}`}function iD(e,t){const n=w5(e),i=w5(t);if(!n||!i)return!1;for(let l=0;l<n.core.length;l+=1)if(n.core[l]!==i.core[l])return n.core[l]>i.core[l];return n.prerelease===i.prerelease?!1:n.prerelease?i.prerelease?n.prerelease.localeCompare(i.prerelease,void 0,{numeric:!0})>0:!1:!0}function w5(e){if(!e)return null;const t=Mf(e).match(/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?$/);return t?{core:[Number(t[1]),Number(t[2]),Number(t[3])],prerelease:t[4]??null}:null}function lD(e,t){const n=e.map(i=>({value:i.model,label:`${i.displayName}${i.isDefault?" (default)":""}`}));return t&&!e.some(i=>i.model===t)&&n.push({value:t,label:`${t} (unavailable)`}),n.length===0&&n.push({value:"",label:"Models unavailable"}),n}async function k5(e,t){const n=e.getReader(),i=new TextDecoder;let l="";for(;;){const{done:o,value:c}=await n.read();if(o)break;l+=i.decode(c,{stream:!0});const f=l.split(`
390
396
 
391
- `);l=f.pop()??"";for(const h of f){const m=lD(h);m&&t(m)}}}function lD(e){const t=e.split(`
397
+ `);l=f.pop()??"";for(const h of f){const m=sD(h);m&&t(m)}}}function sD(e){const t=e.split(`
392
398
  `),n=t.find(c=>c.startsWith("event: ")),i=t.filter(c=>c.startsWith("data: ")).map(c=>c.slice(6));if(!n||i.length===0)return null;const l=n.slice(7),o=i.join(`
393
- `);try{return{event:l,data:JSON.parse(o)}}catch{return{event:l,data:o}}}function sD(e){var i,l,o,c,f;if(!e||typeof e!="object")return null;const t=e;if(t.method!=="item/agentMessage/delta"&&t.method!=="item/plan/delta")return null;const n=((i=t.params)==null?void 0:i.delta)??((l=t.params)==null?void 0:l.text)??"";return n?{text:n,phase:t.method==="item/plan/delta"?"final_answer":((o=t.params)==null?void 0:o.phase)==="commentary"||((c=t.params)==null?void 0:c.phase)==="final_answer"?t.params.phase:"unknown",itemId:(f=t.params)==null?void 0:f.itemId}:null}function oD(e){var i;if(!e||typeof e!="object")return null;const t=e;if(t.method!=="item/started")return null;const n=(i=t.params)==null?void 0:i.item;return(n==null?void 0:n.type)!=="agentMessage"&&(n==null?void 0:n.type)!=="plan"?null:{itemId:n.id,phase:n.type==="plan"?"final_answer":n.phase==="commentary"||n.phase==="final_answer"?n.phase:"unknown"}}function uD(e){var i;if(!e||typeof e!="object")return null;const t=e;if(t.method!=="item/completed")return null;const n=(i=t.params)==null?void 0:i.item;return(n==null?void 0:n.type)!=="agentMessage"&&(n==null?void 0:n.type)!=="plan"||!n.text?null:{itemId:n.id,text:n.text,phase:n.type==="plan"?"final_answer":n.phase==="commentary"||n.phase==="final_answer"?n.phase:"unknown"}}function Ud(e){var n,i,l,o;if(e.event==="server.error"||e.event==="client.error")return"error";if(!e.data||typeof e.data!="object")return null;const t=e.data;return t.method==="thread/status/changed"&&((i=(n=t.params)==null?void 0:n.status)==null?void 0:i.type)==="idle"?"done":t.method==="turn/completed"?(o=(l=t.params)==null?void 0:l.turn)!=null&&o.error?"error":"done":null}function Zo(e){return e.length<=6?e:e.slice(0,6)}function Xl(e){return e.slice(0,8)}function S5(e){switch(e){case"danger-full-access":return"System";case"workspace-write":return"Workspace";case"read-only":return"Read only"}}function C5(e){return{discussing:"Planning",ready:"Planning",active:"Running",paused:"Paused",waiting:"Waiting",replanning:"Planning",blocked:"Blocked",completed:"Completed",cancelled:"Cancelled"}[e]}function up(e,...t){return t.includes(e)}function cD(e,t){const n=Date.parse(e.startedAt??e.createdAt),i=e.finishedAt?Date.parse(e.finishedAt):t;if(!Number.isFinite(n)||!Number.isFinite(i))return"";const l=Math.max(0,Math.floor((i-n)/1e3));if(l<60)return`${l}s`;const o=Math.floor(l/60);return o<60?`${o}m`:`${Math.floor(o/60)}h ${o%60}m`}function dD(e,t){const n=Date.parse(e),i=Date.parse(t);if(!Number.isFinite(n)||!Number.isFinite(i))return"Goal completed";const l=Math.max(0,Math.floor((i-n)/1e3));if(l<60)return`${l}s`;const o=Math.floor(l/60);return o<60?`${o}m`:`${Math.floor(o/60)}h ${o%60}m`}function Jp(e,t){var n;return t==="running"||t==="error"?t:((n=e==null?void 0:e.nextWakeup)==null?void 0:n.status)==="scheduled"?"waiting":t}function fD(e,t){return`waiting ${of(e,t)}`}function of(e,t){const n=Date.parse(e.wakeAt);if(Number.isNaN(n))return"waiting";const i=Math.max(0,Math.ceil((n-t)/1e3));if(i<60)return`${i}s`;const l=Math.ceil(i/60);if(l<60)return`${l}m`;const o=Math.ceil(l/60);return o<24?`${o}h`:`${Math.ceil(o/24)}d`}function Yd(e,t=null,n=Date.now()){if(e==="waiting")return t?fD(t,n):"waiting";switch(e){case"done":return"idle";case"running":return"running";case"error":return"error";case"initializing":return"initializing";case"initialization_failed":return"initialization failed";case"idle":return"idle"}}function j5(e){switch(e){case"checking":return"backend checking";case"connected":return"backend connected";case"error":return"backend unavailable"}}function hD(e){return e==="assistant"?"Seele":"You"}const mD=document.getElementById("root"),$7=window.__seeleCodexRoot??pb.createRoot(mD);window.__seeleCodexRoot=$7;SD();$7.render(u.jsx(I.StrictMode,{children:u.jsx(pD,{})}));function pD(){const[e,t]=I.useState(null),[n,i]=I.useState(null),[l,o]=I.useState(""),[c,f]=I.useState(""),[h,m]=I.useState("admin"),[y,v]=I.useState(""),[k,w]=I.useState(!1),[T,E]=I.useState("");I.useEffect(()=>{let B=!1,F=0;const Y=async()=>{try{const te=await T5();if(B)return;t(te),f("")}catch{if(B)return;f("Reconnecting to Seele..."),F=window.setTimeout(Y,2e3)}};return Y(),()=>{B=!0,window.clearTimeout(F)}},[]),I.useEffect(()=>{let B=!1,F=0;const Y=async()=>{try{const _=await G7();if(B)return;i(_),o(""),F=window.setTimeout(Y,_.status==="authorized"&&_.configurationReady&&_.codexAccountsReady?3e4:3e3)}catch{if(B)return;o("Unable to reach Seele."),F=window.setTimeout(Y,3e3)}},te=()=>{window.clearTimeout(F),Y()};return window.addEventListener(Vp,te),Y(),()=>{B=!0,window.clearTimeout(F),window.removeEventListener(Vp,te)}},[]),I.useEffect(()=>{const B=()=>{t({enabled:!0,authenticated:!1,user:null}),v(""),E("Your session has expired. Sign in again.")};return window.addEventListener(Pp,B),()=>window.removeEventListener(Pp,B)},[]);async function q(B){B.preventDefault(),w(!0),E("");try{const F=await fetch(Ne("auth/login"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:h,password:y})});if(!F.ok){E(F.status===401?"Incorrect username or password.":F.status===429?"Too many failed attempts. Try again later.":"Login failed.");return}v(""),t(await T5())}catch{E("Unable to reach Seele.")}finally{w(!1)}}async function R(){await fetch(Ne("auth/logout"),{method:"POST"}).catch(()=>{}),t({enabled:!0,authenticated:!1,user:null})}if(n&&(n.status!=="authorized"||!n.configurationReady||!n.codexAccountsReady))return u.jsx(gD,{authorization:n});if(!e||!n)return u.jsx("main",{className:"auth-shell",children:u.jsx("span",{className:"auth-loading",children:l||c||"Loading Seele..."})});if(!e.enabled||e.authenticated){const B=e.user??{id:"local-admin",username:"admin",role:"admin",active:!0,createdAt:"",updatedAt:""};return u.jsx(ME,{authEnabled:e.enabled,currentUser:B,deploymentId:n.deploymentId,onLogout:R},`${n.deploymentId}:${B.id}`)}return u.jsx("main",{className:"auth-shell",children:u.jsxs("section",{className:"auth-panel",children:[u.jsxs("header",{children:[u.jsx("p",{children:"Seele"}),u.jsx("h1",{children:"Sign in"})]}),u.jsxs("form",{onSubmit:q,children:[u.jsxs("label",{children:[u.jsx("span",{children:"Username"}),u.jsx("input",{autoComplete:"username",autoFocus:!0,onChange:B=>m(B.target.value),value:h})]}),u.jsxs("label",{children:[u.jsx("span",{children:"Password"}),u.jsx("input",{autoComplete:"current-password",onChange:B=>v(B.target.value),type:"password",value:y})]}),T?u.jsx("p",{className:"auth-error",role:"alert",children:T}):null,u.jsx("button",{disabled:k||!h||!y,type:"submit",children:k?"Signing in...":"Sign in"})]})]})})}function gD({authorization:e}){const t={starting:{title:"Checking deployment authorization",body:"Seele is contacting its configured cloud service."},pending:{title:"Waiting for cloud approval",body:"A cloud administrator must authorize this deployment before it can be used."},revoked:{title:"Deployment access revoked",body:"This deployment is disabled until a cloud administrator authorizes it again."},unavailable:{title:"Cloud authorization unavailable",body:"Seele will keep retrying. Business APIs and the runtime remain paused."},authorized:{title:"Deployment authorized",body:"Seele is ready."}},n=e.status==="authorized"&&!e.configurationReady?{title:"Synchronizing global configuration",body:"Seele is applying the current cloud configuration before the deployment becomes available."}:e.status==="authorized"&&!e.codexAccountsReady?{title:"Synchronizing Codex accounts",body:"Seele is installing the cloud account credentials before the deployment becomes available."}:t[e.status];return u.jsx("main",{className:"deployment-shell",children:u.jsxs("section",{className:"deployment-panel deployment-waiting-panel",children:[u.jsx("div",{className:`deployment-status-mark is-${e.status}`,"aria-hidden":"true"}),u.jsx("p",{className:"deployment-kicker",children:"Seele deployment"}),u.jsx("h1",{children:n.title}),u.jsx("p",{className:"deployment-lead",children:n.body}),u.jsxs("dl",{className:"deployment-facts",children:[u.jsxs("div",{children:[u.jsx("dt",{children:"Deployment ID"}),u.jsx("dd",{children:u.jsx("code",{children:e.deploymentId})})]}),u.jsxs("div",{children:[u.jsx("dt",{children:"Name"}),u.jsx("dd",{children:e.name})]}),u.jsxs("div",{children:[u.jsx("dt",{children:"Cloud"}),u.jsx("dd",{children:e.cloudUrl})]}),u.jsxs("div",{children:[u.jsx("dt",{children:"Last checked"}),u.jsx("dd",{children:e.lastCheckedAt?vD(e.lastCheckedAt):"Starting"})]}),u.jsxs("div",{children:[u.jsx("dt",{children:"Global revision"}),u.jsxs("dd",{children:[e.appliedGlobalRevision," / ",e.requiredGlobalRevision]})]}),u.jsxs("div",{children:[u.jsx("dt",{children:"Codex account revision"}),u.jsxs("dd",{children:[e.appliedCodexAccountRevision," / ",e.requiredCodexAccountRevision]})]})]}),e.lastError||e.configurationError||e.codexAccountError?u.jsx("p",{className:"deployment-error",role:"alert",children:e.lastError||e.configurationError||e.codexAccountError}):null,u.jsx("a",{className:"deployment-primary-link",href:yD(e.cloudUrl),children:"Open cloud deployment management"}),u.jsx("p",{className:"deployment-retry-note",children:"Authorization is checked automatically."})]})})}function yD(e){return`${e.replace(/\/+$/,"")}/admin/deployments`}function vD(e){const t=Date.parse(e);return Number.isNaN(t)?e:new Date(t).toLocaleString()}async function G7(){const e=await fetch(Ne("deployment/authorization"));if(!e.ok)throw new Error(`Deployment authorization request failed: ${e.status}`);return e.json()}async function T5(){const e=await fetch(Ne("auth/session"));if(!e.ok)throw new Error(`Auth session request failed: ${e.status}`);return e.json()}async function xD(){const e=Ne("admin/users"),t=await fetch(e);if(!t.ok)throw await Fn(t,{url:e});return(await t.json()).users}async function bD(e){const t=Ne("admin/users"),n=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!n.ok)throw await Fn(n,{method:"POST",url:t});return(await n.json()).user}async function wD(e,t){const n=Ne(`admin/users/${encodeURIComponent(e)}`),i=await fetch(n,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!i.ok)throw await Fn(i,{method:"PATCH",url:n});return(await i.json()).user}async function kD(e){const t=Ne(`admin/users/${encodeURIComponent(e)}`),n=await fetch(t,{method:"DELETE"});if(!n.ok)throw await Fn(n,{method:"DELETE",url:t})}function SD(){if(window.__seeleAuthFetchInstalled)return;const e=window.fetch.bind(window);window.fetch=async(...t)=>{const n=await e(...t),i=typeof t[0]=="string"?t[0]:t[0]instanceof URL?t[0].toString():t[0].url;if(n.status===401){const l=await n.clone().json().then(o=>o&&typeof o=="object"&&"error"in o?o.error:void 0).catch(()=>{});qA(n.status,l,i.includes("/api/auth/"))==="reauthenticate"&&window.dispatchEvent(new Event(Pp))}return n.status===503&&i.includes("/api/")&&Xs(),n},window.__seeleAuthFetchInstalled=!0}function Xs(){window.dispatchEvent(new Event(Vp))}export{en as _,gb as a,Mb as b,Ey as c,_5 as f,A5 as g,B5 as h,jD as k,uf as s,wb as w};
399
+ `);try{return{event:l,data:JSON.parse(o)}}catch{return{event:l,data:o}}}function oD(e){var i,l,o,c,f;if(!e||typeof e!="object")return null;const t=e;if(t.method!=="item/agentMessage/delta"&&t.method!=="item/plan/delta")return null;const n=((i=t.params)==null?void 0:i.delta)??((l=t.params)==null?void 0:l.text)??"";return n?{text:n,phase:t.method==="item/plan/delta"?"final_answer":((o=t.params)==null?void 0:o.phase)==="commentary"||((c=t.params)==null?void 0:c.phase)==="final_answer"?t.params.phase:"unknown",itemId:(f=t.params)==null?void 0:f.itemId}:null}function uD(e){var i;if(!e||typeof e!="object")return null;const t=e;if(t.method!=="item/started")return null;const n=(i=t.params)==null?void 0:i.item;return(n==null?void 0:n.type)!=="agentMessage"&&(n==null?void 0:n.type)!=="plan"?null:{itemId:n.id,phase:n.type==="plan"?"final_answer":n.phase==="commentary"||n.phase==="final_answer"?n.phase:"unknown"}}function cD(e){var i;if(!e||typeof e!="object")return null;const t=e;if(t.method!=="item/completed")return null;const n=(i=t.params)==null?void 0:i.item;return(n==null?void 0:n.type)!=="agentMessage"&&(n==null?void 0:n.type)!=="plan"||!n.text?null:{itemId:n.id,text:n.text,phase:n.type==="plan"?"final_answer":n.phase==="commentary"||n.phase==="final_answer"?n.phase:"unknown"}}function Ud(e){var n,i,l,o;if(e.event==="server.error"||e.event==="client.error")return"error";if(!e.data||typeof e.data!="object")return null;const t=e.data;return t.method==="thread/status/changed"&&((i=(n=t.params)==null?void 0:n.status)==null?void 0:i.type)==="idle"?"done":t.method==="turn/completed"?(o=(l=t.params)==null?void 0:l.turn)!=null&&o.error?"error":"done":null}function Zo(e){return e.length<=6?e:e.slice(0,6)}function Xl(e){return e.slice(0,8)}function S5(e){switch(e){case"danger-full-access":return"System";case"workspace-write":return"Workspace";case"read-only":return"Read only"}}function C5(e){return{discussing:"Planning",ready:"Planning",active:"Running",paused:"Paused",waiting:"Waiting",replanning:"Planning",blocked:"Blocked",completed:"Completed",cancelled:"Cancelled"}[e]}function up(e,...t){return t.includes(e)}function dD(e,t){const n=Date.parse(e.startedAt??e.createdAt),i=e.finishedAt?Date.parse(e.finishedAt):t;if(!Number.isFinite(n)||!Number.isFinite(i))return"";const l=Math.max(0,Math.floor((i-n)/1e3));if(l<60)return`${l}s`;const o=Math.floor(l/60);return o<60?`${o}m`:`${Math.floor(o/60)}h ${o%60}m`}function fD(e,t){const n=Date.parse(e),i=Date.parse(t);if(!Number.isFinite(n)||!Number.isFinite(i))return"Goal completed";const l=Math.max(0,Math.floor((i-n)/1e3));if(l<60)return`${l}s`;const o=Math.floor(l/60);return o<60?`${o}m`:`${Math.floor(o/60)}h ${o%60}m`}function Jp(e,t){var n;return t==="running"||t==="error"?t:((n=e==null?void 0:e.nextWakeup)==null?void 0:n.status)==="scheduled"?"waiting":t}function hD(e,t){return`waiting ${of(e,t)}`}function of(e,t){const n=Date.parse(e.wakeAt);if(Number.isNaN(n))return"waiting";const i=Math.max(0,Math.ceil((n-t)/1e3));if(i<60)return`${i}s`;const l=Math.ceil(i/60);if(l<60)return`${l}m`;const o=Math.ceil(l/60);return o<24?`${o}h`:`${Math.ceil(o/24)}d`}function Yd(e,t=null,n=Date.now()){if(e==="waiting")return t?hD(t,n):"waiting";switch(e){case"done":return"idle";case"running":return"running";case"error":return"error";case"initializing":return"initializing";case"initialization_failed":return"initialization failed";case"idle":return"idle"}}function j5(e){switch(e){case"checking":return"backend checking";case"connected":return"backend connected";case"error":return"backend unavailable"}}function mD(e){return e==="assistant"?"Seele":"You"}const pD=document.getElementById("root"),$7=window.__seeleCodexRoot??pb.createRoot(pD);window.__seeleCodexRoot=$7;CD();$7.render(u.jsx(I.StrictMode,{children:u.jsx(gD,{})}));function gD(){const[e,t]=I.useState(null),[n,i]=I.useState(null),[l,o]=I.useState(""),[c,f]=I.useState(""),[h,m]=I.useState("admin"),[y,v]=I.useState(""),[k,w]=I.useState(!1),[T,E]=I.useState("");I.useEffect(()=>{let B=!1,F=0;const Y=async()=>{try{const te=await T5();if(B)return;t(te),f("")}catch{if(B)return;f("Reconnecting to Seele..."),F=window.setTimeout(Y,2e3)}};return Y(),()=>{B=!0,window.clearTimeout(F)}},[]),I.useEffect(()=>{let B=!1,F=0;const Y=async()=>{try{const _=await G7();if(B)return;i(_),o(""),F=window.setTimeout(Y,_.status==="authorized"&&_.configurationReady&&_.codexAccountsReady?3e4:3e3)}catch{if(B)return;o("Unable to reach Seele."),F=window.setTimeout(Y,3e3)}},te=()=>{window.clearTimeout(F),Y()};return window.addEventListener(Vp,te),Y(),()=>{B=!0,window.clearTimeout(F),window.removeEventListener(Vp,te)}},[]),I.useEffect(()=>{const B=()=>{t({enabled:!0,authenticated:!1,user:null}),v(""),E("Your session has expired. Sign in again.")};return window.addEventListener(Pp,B),()=>window.removeEventListener(Pp,B)},[]);async function q(B){B.preventDefault(),w(!0),E("");try{const F=await fetch(Ne("auth/login"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:h,password:y})});if(!F.ok){E(F.status===401?"Incorrect username or password.":F.status===429?"Too many failed attempts. Try again later.":"Login failed.");return}v(""),t(await T5())}catch{E("Unable to reach Seele.")}finally{w(!1)}}async function R(){await fetch(Ne("auth/logout"),{method:"POST"}).catch(()=>{}),t({enabled:!0,authenticated:!1,user:null})}if(n&&(n.status!=="authorized"||!n.configurationReady||!n.codexAccountsReady))return u.jsx(yD,{authorization:n});if(!e||!n)return u.jsx("main",{className:"auth-shell",children:u.jsx("span",{className:"auth-loading",children:l||c||"Loading Seele..."})});if(!e.enabled||e.authenticated){const B=e.user??{id:"local-admin",username:"admin",role:"admin",active:!0,createdAt:"",updatedAt:""};return u.jsx(zE,{authEnabled:e.enabled,currentUser:B,deploymentId:n.deploymentId,onLogout:R},`${n.deploymentId}:${B.id}`)}return u.jsx("main",{className:"auth-shell",children:u.jsxs("section",{className:"auth-panel",children:[u.jsxs("header",{children:[u.jsx("p",{children:"Seele"}),u.jsx("h1",{children:"Sign in"})]}),u.jsxs("form",{onSubmit:q,children:[u.jsxs("label",{children:[u.jsx("span",{children:"Username"}),u.jsx("input",{autoComplete:"username",autoFocus:!0,onChange:B=>m(B.target.value),value:h})]}),u.jsxs("label",{children:[u.jsx("span",{children:"Password"}),u.jsx("input",{autoComplete:"current-password",onChange:B=>v(B.target.value),type:"password",value:y})]}),T?u.jsx("p",{className:"auth-error",role:"alert",children:T}):null,u.jsx("button",{disabled:k||!h||!y,type:"submit",children:k?"Signing in...":"Sign in"})]})]})})}function yD({authorization:e}){const t={starting:{title:"Checking deployment authorization",body:"Seele is contacting its configured cloud service."},pending:{title:"Waiting for cloud approval",body:"A cloud administrator must authorize this deployment before it can be used."},revoked:{title:"Deployment access revoked",body:"This deployment is disabled until a cloud administrator authorizes it again."},unavailable:{title:"Cloud authorization unavailable",body:"Seele will keep retrying. Business APIs and the runtime remain paused."},authorized:{title:"Deployment authorized",body:"Seele is ready."}},n=e.status==="authorized"&&!e.configurationReady?{title:"Synchronizing global configuration",body:"Seele is applying the current cloud configuration before the deployment becomes available."}:e.status==="authorized"&&!e.codexAccountsReady?{title:"Synchronizing Codex accounts",body:"Seele is installing the cloud account credentials before the deployment becomes available."}:t[e.status];return u.jsx("main",{className:"deployment-shell",children:u.jsxs("section",{className:"deployment-panel deployment-waiting-panel",children:[u.jsx("div",{className:`deployment-status-mark is-${e.status}`,"aria-hidden":"true"}),u.jsx("p",{className:"deployment-kicker",children:"Seele deployment"}),u.jsx("h1",{children:n.title}),u.jsx("p",{className:"deployment-lead",children:n.body}),u.jsxs("dl",{className:"deployment-facts",children:[u.jsxs("div",{children:[u.jsx("dt",{children:"Deployment ID"}),u.jsx("dd",{children:u.jsx("code",{children:e.deploymentId})})]}),u.jsxs("div",{children:[u.jsx("dt",{children:"Name"}),u.jsx("dd",{children:e.name})]}),u.jsxs("div",{children:[u.jsx("dt",{children:"Cloud"}),u.jsx("dd",{children:e.cloudUrl})]}),u.jsxs("div",{children:[u.jsx("dt",{children:"Last checked"}),u.jsx("dd",{children:e.lastCheckedAt?xD(e.lastCheckedAt):"Starting"})]}),u.jsxs("div",{children:[u.jsx("dt",{children:"Global revision"}),u.jsxs("dd",{children:[e.appliedGlobalRevision," / ",e.requiredGlobalRevision]})]}),u.jsxs("div",{children:[u.jsx("dt",{children:"Codex account revision"}),u.jsxs("dd",{children:[e.appliedCodexAccountRevision," / ",e.requiredCodexAccountRevision]})]})]}),e.lastError||e.configurationError||e.codexAccountError?u.jsx("p",{className:"deployment-error",role:"alert",children:e.lastError||e.configurationError||e.codexAccountError}):null,u.jsx("a",{className:"deployment-primary-link",href:vD(e.cloudUrl),children:"Open cloud deployment management"}),u.jsx("p",{className:"deployment-retry-note",children:"Authorization is checked automatically."})]})})}function vD(e){return`${e.replace(/\/+$/,"")}/admin/deployments`}function xD(e){const t=Date.parse(e);return Number.isNaN(t)?e:new Date(t).toLocaleString()}async function G7(){const e=await fetch(Ne("deployment/authorization"));if(!e.ok)throw new Error(`Deployment authorization request failed: ${e.status}`);return e.json()}async function T5(){const e=await fetch(Ne("auth/session"));if(!e.ok)throw new Error(`Auth session request failed: ${e.status}`);return e.json()}async function bD(){const e=Ne("admin/users"),t=await fetch(e);if(!t.ok)throw await Fn(t,{url:e});return(await t.json()).users}async function wD(e){const t=Ne("admin/users"),n=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!n.ok)throw await Fn(n,{method:"POST",url:t});return(await n.json()).user}async function kD(e,t){const n=Ne(`admin/users/${encodeURIComponent(e)}`),i=await fetch(n,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!i.ok)throw await Fn(i,{method:"PATCH",url:n});return(await i.json()).user}async function SD(e){const t=Ne(`admin/users/${encodeURIComponent(e)}`),n=await fetch(t,{method:"DELETE"});if(!n.ok)throw await Fn(n,{method:"DELETE",url:t})}function CD(){if(window.__seeleAuthFetchInstalled)return;const e=window.fetch.bind(window);window.fetch=async(...t)=>{const n=await e(...t),i=typeof t[0]=="string"?t[0]:t[0]instanceof URL?t[0].toString():t[0].url;if(n.status===401){const l=await n.clone().json().then(o=>o&&typeof o=="object"&&"error"in o?o.error:void 0).catch(()=>{});UA(n.status,l,i.includes("/api/auth/"))==="reauthenticate"&&window.dispatchEvent(new Event(Pp))}return n.status===503&&i.includes("/api/")&&Xs(),n},window.__seeleAuthFetchInstalled=!0}function Xs(){window.dispatchEvent(new Event(Vp))}export{en as _,gb as a,Mb as b,Ey as c,_5 as f,A5 as g,B5 as h,TD as k,uf as s,wb as w};