@youweichen/pi-harness 1.0.0 → 1.1.0

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 (84) hide show
  1. package/LICENSE +1 -1
  2. package/dist/server/agent-service.js +87 -7
  3. package/dist/server/control-socket.js +1 -0
  4. package/dist/server/extensions-worker.js +3 -2
  5. package/dist/server/files-service.js +8 -16
  6. package/dist/server/index.js +7 -3
  7. package/dist/server/node-agent.js +262 -0
  8. package/dist/server/node-workbench.js +62 -1
  9. package/dist/server/plan/extension.js +4 -4
  10. package/dist/server/plan/state.js +11 -1
  11. package/dist/server/slash-commands.js +6 -0
  12. package/dist/server/wiki-routes.js +8 -1
  13. package/dist/server/wiki-service.js +13 -0
  14. package/package.json +1 -1
  15. package/web/dist/assets/NodeWorkbench-BiP2ktQP.js +3 -0
  16. package/web/dist/assets/{TerminalPanel-CWh6vw_N.js → TerminalPanel-CKaSUsN-.js} +1 -1
  17. package/web/dist/assets/{abnfDiagram-VCTEODGH-D5Ti0Kpa.js → abnfDiagram-VCTEODGH-CnwRJDRL.js} +1 -1
  18. package/web/dist/assets/{arc-DKJilLd6.js → arc-CG4Q7-W_.js} +1 -1
  19. package/web/dist/assets/{architectureDiagram-5GKGNRK7-Cf0w38g-.js → architectureDiagram-5GKGNRK7-BrGqX_Rg.js} +1 -1
  20. package/web/dist/assets/{blockDiagram-I7D4REHJ-BOTLWLIL.js → blockDiagram-I7D4REHJ-C2t0PjZT.js} +1 -1
  21. package/web/dist/assets/{c4Diagram-7LVT6UL2-CLCCoJs3.js → c4Diagram-7LVT6UL2-CadrcgGL.js} +1 -1
  22. package/web/dist/assets/channel-C27Jizb6.js +1 -0
  23. package/web/dist/assets/{chunk-2Q5K7J3B-BHjga2Ge.js → chunk-2Q5K7J3B-CC3V2ITZ.js} +1 -1
  24. package/web/dist/assets/{chunk-5VM5RSS4-CQJ5VfDZ.js → chunk-5VM5RSS4-DqKSbGmE.js} +1 -1
  25. package/web/dist/assets/{chunk-F27PBJKO-C67qoPJH.js → chunk-F27PBJKO-_CDr3JbY.js} +1 -1
  26. package/web/dist/assets/{chunk-IMKFNOWR-CgXXGwI8.js → chunk-IMKFNOWR-BIR4H4fX.js} +1 -1
  27. package/web/dist/assets/{chunk-JWPE2WC7-D0RPyByP.js → chunk-JWPE2WC7-CrsdBGXT.js} +1 -1
  28. package/web/dist/assets/{chunk-POPQ4Y6H-BeYC9s9x.js → chunk-POPQ4Y6H-C6q9kQmf.js} +1 -1
  29. package/web/dist/assets/{chunk-SVP7TREG-eQPl4UBQ.js → chunk-SVP7TREG-l2XXTr2v.js} +1 -1
  30. package/web/dist/assets/{chunk-TICWLB2K-DT73arPU.js → chunk-TICWLB2K-29I_mZgB.js} +1 -1
  31. package/web/dist/assets/{chunk-XXDRQBXY-B4FwQcP-.js → chunk-XXDRQBXY-htV9FBqi.js} +1 -1
  32. package/web/dist/assets/classDiagram-ZZMXUADV-DYTBrAEP.js +1 -0
  33. package/web/dist/assets/classDiagram-v2-VYDZK3BY-DYTBrAEP.js +1 -0
  34. package/web/dist/assets/{cose-bilkent-JH36ORCC-Bnn5nlQN.js → cose-bilkent-JH36ORCC-Cop-ihyx.js} +1 -1
  35. package/web/dist/assets/{cynefin-OW5HDTMX-CStWX9kE.js → cynefin-OW5HDTMX-IEk8qBRq.js} +1 -1
  36. package/web/dist/assets/{cynefinDiagram-5FMLGOSQ-BMVHC03f.js → cynefinDiagram-5FMLGOSQ-Bmzt6Qb5.js} +1 -1
  37. package/web/dist/assets/{dagre-GXQ25YYZ-ClSaO4ml.js → dagre-GXQ25YYZ-DiXTJYYU.js} +1 -1
  38. package/web/dist/assets/{diagram-S7CK7UJ4-C43LL08C.js → diagram-S7CK7UJ4-BT7CLuNk.js} +1 -1
  39. package/web/dist/assets/{diagram-UQ7AKVKN-BPVn_ySW.js → diagram-UQ7AKVKN-BZZ3nTCO.js} +1 -1
  40. package/web/dist/assets/{diagram-VSXAHHWV-C34FFhRi.js → diagram-VSXAHHWV-Dal8LeZh.js} +1 -1
  41. package/web/dist/assets/{diagram-VX7I27RA-BRk4bncf.js → diagram-VX7I27RA-D6V9FfNA.js} +1 -1
  42. package/web/dist/assets/{diagram-Z3DM3KII-O5hYPLEd.js → diagram-Z3DM3KII-KUAIcFiD.js} +1 -1
  43. package/web/dist/assets/{ebnfDiagram-PWID7BFC-DVGEBm99.js → ebnfDiagram-PWID7BFC-s0FEPZrV.js} +1 -1
  44. package/web/dist/assets/{erDiagram-RLTQ6QDP-M-BLpTEV.js → erDiagram-RLTQ6QDP-CiIQPFCD.js} +1 -1
  45. package/web/dist/assets/{flowDiagram-HODETNUW-BwdLopEx.js → flowDiagram-HODETNUW-CvG4MYWn.js} +1 -1
  46. package/web/dist/assets/{ganttDiagram-EL5Y4UJY-DYxx2ppA.js → ganttDiagram-EL5Y4UJY-CUf115ii.js} +1 -1
  47. package/web/dist/assets/{gitGraphDiagram-WWUBYQGX-DUU0wMYB.js → gitGraphDiagram-WWUBYQGX-o3K1r6fL.js} +1 -1
  48. package/web/dist/assets/index-C3vDFSEV.css +10 -0
  49. package/web/dist/assets/index-C5or_GAq.js +276 -0
  50. package/web/dist/assets/{infoDiagram-27XIBGKW-CFaW5C0C.js → infoDiagram-27XIBGKW-BxiBeQ8E.js} +1 -1
  51. package/web/dist/assets/{ishikawaDiagram-5VMMS53U--ENP1MTB.js → ishikawaDiagram-5VMMS53U-B1ONuCkH.js} +1 -1
  52. package/web/dist/assets/{journeyDiagram-3NMN7TZE-DgnAzSTj.js → journeyDiagram-3NMN7TZE-DwmuoXcX.js} +1 -1
  53. package/web/dist/assets/{kanban-definition-UXKFOSKX-_STZN1vU.js → kanban-definition-UXKFOSKX-pMKHubxH.js} +1 -1
  54. package/web/dist/assets/{layout-CkUClkXt.js → layout-CEwfjQR0.js} +1 -1
  55. package/web/dist/assets/{linear-sYHiUOxa.js → linear-D22Gdbt1.js} +1 -1
  56. package/web/dist/assets/{markdown-vNTCZJ6d.js → markdown-BhJ_LInD.js} +1 -1
  57. package/web/dist/assets/{mermaid.core-B8fKGWsc.js → mermaid.core-CO2nrD04.js} +5 -5
  58. package/web/dist/assets/{mindmap-definition-YA3MSWOX-DP0BYOEx.js → mindmap-definition-YA3MSWOX-9MQn9ZAp.js} +1 -1
  59. package/web/dist/assets/{pegDiagram-XKGWAZYB-DkWTmZre.js → pegDiagram-XKGWAZYB-Dy6fLjM-.js} +1 -1
  60. package/web/dist/assets/{pieDiagram-E7YTZNPT-DfZgMV4u.js → pieDiagram-E7YTZNPT-EDLez6nA.js} +1 -1
  61. package/web/dist/assets/{quadrantDiagram-AXDQQJYC-Djl4TT7q.js → quadrantDiagram-AXDQQJYC-Cgcd9mvy.js} +1 -1
  62. package/web/dist/assets/{railroadDiagram-O6MQD6OU-DbKF6zXn.js → railroadDiagram-O6MQD6OU-B4Td0tjj.js} +1 -1
  63. package/web/dist/assets/{react-BNj3n7jX.js → react-BddUxV-9.js} +1 -1
  64. package/web/dist/assets/{requirementDiagram-BXWQKSXE-idola5qb.js → requirementDiagram-BXWQKSXE-aF2QNZ78.js} +1 -1
  65. package/web/dist/assets/{sankeyDiagram-P5KCCOFB-KA0hQOle.js → sankeyDiagram-P5KCCOFB-DgTYwYMa.js} +1 -1
  66. package/web/dist/assets/{sequenceDiagram-WJ2MYXX4-BXSKvxzP.js → sequenceDiagram-WJ2MYXX4-EUcddWUc.js} +1 -1
  67. package/web/dist/assets/{sizeCapture-INFHLROL-C_Ewv3S5.js → sizeCapture-INFHLROL-CXHOv9Sx.js} +1 -1
  68. package/web/dist/assets/{stateDiagram-D77RDMKH-DIf5X8oo.js → stateDiagram-D77RDMKH-B-xlgfaK.js} +1 -1
  69. package/web/dist/assets/stateDiagram-v2-MP3YSRHH-kwAwAlWX.js +1 -0
  70. package/web/dist/assets/{swimlanes-42K2YHIH-Cx_Rc8M2.js → swimlanes-42K2YHIH-BtFBOCDh.js} +1 -1
  71. package/web/dist/assets/swimlanesDiagram-VR7AAH4N-D5j5Cj3S.js +8 -0
  72. package/web/dist/assets/{timeline-definition-24CTP7MA-BRrDhWVz.js → timeline-definition-24CTP7MA-CZlQY6pb.js} +1 -1
  73. package/web/dist/assets/{vennDiagram-4TSXK5OY-Ad6G0YwD.js → vennDiagram-4TSXK5OY-Cn61dJvL.js} +1 -1
  74. package/web/dist/assets/{wardleyDiagram-VM6X3IG4-X6-ENpSi.js → wardleyDiagram-VM6X3IG4-fiMNrWpr.js} +1 -1
  75. package/web/dist/assets/{xychartDiagram-S5SC5T6Z-DhegNS6d.js → xychartDiagram-S5SC5T6Z-CuzM_sof.js} +1 -1
  76. package/web/dist/index.html +4 -4
  77. package/web/dist/assets/NodeWorkbench-C4U1PldE.js +0 -3
  78. package/web/dist/assets/channel-D8Hd7T4P.js +0 -1
  79. package/web/dist/assets/classDiagram-ZZMXUADV-B_btgYRB.js +0 -1
  80. package/web/dist/assets/classDiagram-v2-VYDZK3BY-B_btgYRB.js +0 -1
  81. package/web/dist/assets/index-CI2KfVSr.css +0 -10
  82. package/web/dist/assets/index-DQcpggFU.js +0 -275
  83. package/web/dist/assets/stateDiagram-v2-MP3YSRHH-DYwe_2mB.js +0 -1
  84. package/web/dist/assets/swimlanesDiagram-VR7AAH4N-52Y8tgRV.js +0 -8
@@ -0,0 +1,276 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/mermaid.core-CO2nrD04.js","assets/markdown-BhJ_LInD.js","assets/TerminalPanel-CKaSUsN-.js","assets/xterm-D1D2FVe3.js","assets/react-BddUxV-9.js","assets/xterm-6GBZ9nXN.css","assets/NodeWorkbench-BiP2ktQP.js"])))=>i.map(i=>d[i]);
2
+ var Yl=Object.defineProperty;var Xl=(t,n,s)=>n in t?Yl(t,n,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[n]=s;var $r=(t,n,s)=>Xl(t,typeof n!="symbol"?n+"":n,s);import{a as d,j as e,R as ks,u as Tr,c as Rr,b as Si,M as Ir,d as mo,H as Lt,e as Zl,f as ec,h as tc,i as nc,k as sc,l as rc,m as ic,n as ac,o as oc,p as lc,q as cc,s as dc,t as uc,v as pc,w as hc,x as mc,y as fc,z as gc,A as xc,B as vc,C as kc,D as yc,E as wc,F as bc,G as jc,I as Cc,J as Sc,r as fo}from"./markdown-BhJ_LInD.js";import{r as go}from"./react-BddUxV-9.js";(function(){const n=document.createElement("link").relList;if(n&&n.supports&&n.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))r(i);new MutationObserver(i=>{for(const a of i)if(a.type==="childList")for(const o of a.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&r(o)}).observe(document,{childList:!0,subtree:!0});function s(i){const a={};return i.integrity&&(a.integrity=i.integrity),i.referrerPolicy&&(a.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?a.credentials="include":i.crossOrigin==="anonymous"?a.credentials="omit":a.credentials="same-origin",a}function r(i){if(i.ep)return;i.ep=!0;const a=s(i);fetch(i.href,a)}})();const Nc="pi-harness:theme-change";function Mf(){const t=getComputedStyle(document.documentElement),n=s=>t.getPropertyValue(s).trim();return{background:n("--term-bg"),foreground:n("--term-fg"),cursor:n("--term-cursor"),cursorAccent:n("--term-cursor-accent"),selectionBackground:n("--term-selection"),black:n("--term-black"),red:n("--term-red"),green:n("--term-green"),yellow:n("--term-yellow"),blue:n("--term-blue"),magenta:n("--term-magenta"),cyan:n("--term-cyan"),white:n("--term-white"),brightBlack:n("--term-bright-black"),brightRed:n("--term-bright-red"),brightGreen:n("--term-bright-green"),brightYellow:n("--term-bright-yellow"),brightBlue:n("--term-bright-blue"),brightMagenta:n("--term-bright-magenta"),brightCyan:n("--term-bright-cyan"),brightWhite:n("--term-bright-white")}}const xo="pi-harness:appearance";function vo(){try{const t=localStorage.getItem(xo);return t==="dark"||t==="system"?t:"light"}catch{return"light"}}function Fr(t=vo()){document.documentElement.dataset.appearance=t==="system"?matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light":t,window.dispatchEvent(new Event(Nc))}function Ec(){Fr(),matchMedia("(prefers-color-scheme: dark)").addEventListener("change",()=>{vo()==="system"&&Fr()}),window.addEventListener("storage",t=>{(t.key===xo||t.key===null)&&Fr()})}var ir={},Zi;function Tc(){if(Zi)return ir;Zi=1;var t=go();return ir.createRoot=t.createRoot,ir.hydrateRoot=t.hydrateRoot,ir}var Rc=Tc();const Ic="modulepreload",Lc=function(t){return"/"+t},ea={},Lr=function(n,s,r){let i=Promise.resolve();if(s&&s.length>0){let o=function(p){return Promise.all(p.map(u=>Promise.resolve(u).then(f=>({status:"fulfilled",value:f}),f=>({status:"rejected",reason:f}))))};document.getElementsByTagName("link");const c=document.querySelector("meta[property=csp-nonce]"),l=(c==null?void 0:c.nonce)||(c==null?void 0:c.getAttribute("nonce"));i=o(s.map(p=>{if(p=Lc(p),p in ea)return;ea[p]=!0;const u=p.endsWith(".css"),f=u?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${p}"]${f}`))return;const k=document.createElement("link");if(k.rel=u?"stylesheet":Ic,u||(k.as="script"),k.crossOrigin="",k.href=p,l&&k.setAttribute("nonce",l),document.head.appendChild(k),u)return new Promise((j,R)=>{k.addEventListener("load",j),k.addEventListener("error",()=>R(new Error(`Unable to preload CSS for ${p}`)))})}))}function a(o){const c=new Event("vite:preloadError",{cancelable:!0});if(c.payload=o,window.dispatchEvent(c),!c.defaultPrevented)throw o}return i.then(o=>{for(const c of o||[])c.status==="rejected"&&a(c.reason);return n().catch(a)})};function Mc(t,n){const s=t.findIndex(r=>r.conversationId===n.conversationId&&r.level===n.level&&r.text===n.text);return s>=0?t.map((r,i)=>i===s?{...r,count:(r.count??1)+1}:r):[...t,n].slice(-6)}function Pc(t){return/^pi-mcp-adapter no longer reads [^\r\n]+[\\/]mcp\.json\. (?:Move it with:|Merge )/.test(t)}const ko=d.createContext(null),Mr=()=>d.useContext(ko),yo=d.createContext(!1),wo=d.createContext(null),Ac=()=>d.useContext(yo),Dc=()=>d.useContext(wo);function $c({conversationId:t,files:n,active:s,onOpenChange:r,children:i}){const a=`pi-harness:changes:${t}`,o=()=>{try{const M=JSON.parse(sessionStorage.getItem(a)??"null");if(M)return{open:M.open===!0,list:M.list===!0,scope:["branch","work"].includes(M.scope)?M.scope:"turn",selected:"",base:""}}catch{}return{open:!1,list:!1,scope:"turn",selected:"",base:""}},[c,l]=d.useState(a),[p,u]=d.useState(o),[f,k]=d.useState(null),[j,R]=d.useState(0);c!==a&&(l(a),u(o()),k(null),R(0)),d.useEffect(()=>{try{sessionStorage.setItem(a,JSON.stringify(p))}catch{}},[a,p]),d.useEffect(()=>(r(s&&p.open),()=>r(!1)),[s,p.open,r,t]),d.useEffect(()=>{const M=b=>{!s||!(b.metaKey||b.ctrlKey)||b.key.toLowerCase()!=="d"||(b.preventDefault(),u(F=>({...F,open:!F.open})))};return window.addEventListener("keydown",M),()=>window.removeEventListener("keydown",M)},[s]);const E=d.useCallback(M=>{M.scope==="turn"&&k(null),u(b=>({...b,...M}))},[]),A=d.useCallback((M,b)=>{k(M.length===n.length&&M.every((F,U)=>{var ce,ie;return F.path===n[U].path&&((ce=F.toolIds)==null?void 0:ce.join())===((ie=n[U].toolIds)==null?void 0:ie.join())})?null:M),u(F=>({...F,open:!0,scope:"turn",selected:b??""})),R(F=>F+1)},[n]),N=f??n,T=d.useMemo(()=>({...p,files:N,focusRequest:j,set:E,show:A}),[p,N,j,E,A]),y=d.useMemo(()=>({files:N,show:A}),[N,A]);return e.jsx(yo.Provider,{value:!0,children:e.jsx(wo.Provider,{value:y,children:e.jsx(ko.Provider,{value:T,children:i})})})}const Fc=/^\s*(?:(?:async\s+)?def\s+\w+|(?:export\s+)?(?:async\s+)?function\s+\w+|(?:public|private|protected)\s+\w+\s*\(|(?:async\s+)?\w+\s*\([^)]*\)\s*[:{])/;function Oc(t,n=2){var i;const s=[[]];let r=0;for(const a of t.replace(/\r\n/g,`
3
+ `).split(`
4
+ `)){if(/^\s*\.\.\.\s*$/.test(a)){(i=s.at(-1))!=null&&i.length&&s.push([]);continue}const o=/^([+\- ])\s*(\d+) (.*)$/.exec(a);if(!o)continue;const c=o[1],l=Number(o[2]),p=o[3];c==="+"?(s.at(-1).push({marker:c,newLine:l,text:p}),r++):c==="-"?(s.at(-1).push({marker:c,oldLine:l,text:p}),r--):s.at(-1).push({marker:c,oldLine:l,newLine:l+r,text:p})}return s.flatMap(a=>{const o=a.flatMap((l,p)=>l.marker===" "?[]:[p]);if(!o.length)return[];const c=[];for(const l of o){const p=c.at(-1);p&&l-p.last<=n*2+1?p.last=l:c.push({first:l,last:l})}return c.map(({first:l,last:p})=>{var k;const u=a.slice(Math.max(0,l-n),Math.min(a.length,p+n+1)),f=(k=[...a.slice(0,l)].reverse().find(j=>Fc.test(j.text)))==null?void 0:k.text.trim();return{line:a[l].newLine??a[l].oldLine??1,...f?{functionName:f}:{},lines:u}})})}function $s(t,n,s=2){var k;if(t.name!=="edit"&&t.name!=="write")return null;let r={};try{r=JSON.parse(t.argumentsText??"{}")}catch{}const i=typeof r.path=="string"?r.path:"",a=(n==null?void 0:n.content.filter(j=>j.type==="text").map(j=>j.text).join(`
5
+ `))??"",o=!!(n!=null&&n.isError);if(t.name==="write"){const j=typeof r.content=="string"?r.content:"",R=j?j.replace(/\r\n/g,`
6
+ `).replace(/\n$/,"").split(`
7
+ `):[];return{path:i,kind:"write",added:o?0:R.length,removed:0,firstChangedLine:1,hunks:R.length?[{line:1,lines:R.map((E,A)=>({marker:"+",newLine:A+1,text:E}))}]:[],error:o,errorText:o?a:"",output:a,empty:!R.length}}const c=n==null?void 0:n.details,l=!o&&typeof(c==null?void 0:c.diff)=="string"?c.diff:"";let p=Oc(l,s),u=!1;!o&&n&&p.length===0&&(p=(Array.isArray(r.edits)?r.edits:[r]).flatMap(R=>{if(!R||typeof R!="object")return[];const{oldText:E,newText:A}=R;if(typeof E!="string"||typeof A!="string"||E===A)return[];const N=E?E.replace(/\r\n/g,`
8
+ `).replace(/\n$/,"").split(`
9
+ `):[],T=A?A.replace(/\r\n/g,`
10
+ `).replace(/\n$/,"").split(`
11
+ `):[];let y=0;for(;y<N.length&&y<T.length&&N[y]===T[y];)y++;let M=0;for(;M<N.length-y&&M<T.length-y&&N[N.length-M-1]===T[T.length-M-1];)M++;const b=N.slice(Math.max(0,y-s),y).map(U=>({marker:" ",text:U})),F=N.slice(N.length-M,Math.min(N.length,N.length-M+s)).map(U=>({marker:" ",text:U}));return[{line:1,lines:[...b,...N.slice(y,N.length-M).map(U=>({marker:"-",text:U})),...T.slice(y,T.length-M).map(U=>({marker:"+",text:U})),...F]}]}),u=p.length>0);const f=p.flatMap(j=>j.lines);if(o){const E=(Array.isArray(r.edits)?r.edits:[r]).map(A=>typeof A=="object"&&A&&"oldText"in A&&typeof A.oldText=="string"?A.oldText:"").filter(Boolean).join(`
12
+
13
+ `);return{path:i,kind:"edit",added:0,removed:0,firstChangedLine:1,hunks:E?[{line:1,lines:E.replace(/\n$/,"").split(`
14
+ `).map(A=>({marker:" ",text:A}))}]:[],error:o,errorText:a,output:a,empty:!E}}return{path:i,kind:"edit",added:f.filter(j=>j.marker==="+").length,removed:f.filter(j=>j.marker==="-").length,firstChangedLine:typeof(c==null?void 0:c.firstChangedLine)=="number"?c.firstChangedLine:((k=p[0])==null?void 0:k.line)??1,hunks:p,error:o,errorText:"",output:a,empty:!p.length,fromArguments:u,diffTruncated:(c==null?void 0:c.diffTruncated)===!0}}function _c(t,n){var i;const s=new Map,r=new Set;for(const a of t)if(a.role==="assistant")for(const o of a.content){if(o.type!=="toolCall"||o.name!=="edit")continue;const c=o,l=n.get(c.id);if(!l)continue;const p=(i=$s(c,l))==null?void 0:i.path;if(p)if(l.isError)s.set(p,[...s.get(p)??[],c.id]);else{for(const u of s.get(p)??[])r.add(u);s.delete(p)}}return r}function bo(t,n){const s=a=>{const o=[];for(const c of a.replace(/\\/g,"/").split("/"))c!=="."&&(c===".."&&o.length&&o.at(-1)!==".."&&o.at(-1)!==""?o.pop():o.push(c));return o.join("/")},r=s(n).replace(/\/$/,""),i=s(t);return i.startsWith(`${r}/`)?i.slice(r.length+1):i}function jo(t,n,s){const r=new Map;if(!t)return[];const i=new Map(n.filter(c=>c.role==="toolResult").map(c=>[c.toolCallId,c])),a=new Map;for(const c of n)if(c.role==="assistant")for(const l of c.content)l.type==="toolCall"&&typeof l.id=="string"&&a.set(l.id,l);const o=new Set;for(const c of t.steps)for(const l of c.artifacts){if(o.has(l.toolCallId))continue;o.add(l.toolCallId);const p=i.get(l.toolCallId),u=a.get(l.toolCallId);if(!l.path||!["write","edit"].includes(l.kind)||!p||p.isError)continue;const f=bo(l.path,s),k=r.get(f)??{path:f,added:0,removed:0,counted:!1},j=u&&$s(u,p);(j==null?void 0:j.kind)==="edit"&&!j.error&&!j.diffTruncated&&!j.empty&&(k.added+=j.added,k.removed+=j.removed,k.counted=!0),r.set(f,k)}return[...r.values()]}function Co(t,n,s){const r=jo(t,n,s).map(c=>({...c,lines:[],toolIds:[],unlocated:!1,truncated:!1})),i=new Map(r.map(c=>[c.path,c])),a=new Set((t==null?void 0:t.steps.flatMap(c=>c.artifacts.map(l=>l.toolCallId)))??[]),o=new Map(n.filter(c=>c.role==="toolResult").map(c=>[c.toolCallId,c]));for(const c of n)if(c.role==="assistant")for(const l of c.content){if(l.type!=="toolCall"||!a.delete(String(l.id)))continue;const p=l,u=o.get(p.id);if(!u||u.isError)continue;const f=$s(p,u,3);if(!f)continue;const k=i.get(bo(f.path,s));k&&(k.lines.push(...f.hunks.flatMap(j=>j.lines)),k.toolIds.push(p.id),k.unlocated||(k.unlocated=!!f.fromArguments),k.truncated||(k.truncated=!!f.diffTruncated))}return r}function Cs(t,n=!0){let s=t.replace(/\t.*$/,"");if(s.startsWith('"'))try{s=JSON.parse(s)}catch{}return n?s.replace(/^[ab]\//,""):s}function Hc(t){const n=[];let s,r=0,i=0,a=0,o=0;for(const c of t.split(`
15
+ `)){if(c.startsWith("diff --git ")){s={path:"",added:0,removed:0,counted:!0,lines:[]},n.push(s),a=o=0;const p=/^diff --git ("(?:[^"\\]|\\.)*"|a\/.*?) ("(?:[^"\\]|\\.)*"|b\/.*)$/.exec(c);p&&(s.oldPath=Cs(p[1]),s.path=Cs(p[2]));continue}if(!s)continue;const l=/^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/.exec(c);if(l){r=+l[1],a=l[2]===void 0?1:+l[2],i=+l[3],o=l[4]===void 0?1:+l[4];continue}if(a||o){c.startsWith("+")?(s.lines.push({marker:"+",newLine:i++,text:c.slice(1)}),o--,s.added++):c.startsWith("-")?(s.lines.push({marker:"-",oldLine:r++,text:c.slice(1)}),a--,s.removed++):c.startsWith(" ")&&(s.lines.push({marker:" ",oldLine:r++,newLine:i++,text:c.slice(1)}),a--,o--);continue}c.startsWith("+++ ")&&c!=="+++ /dev/null"?s.path=Cs(c.slice(4)):c.startsWith("--- ")&&c!=="--- /dev/null"?s.oldPath=Cs(c.slice(4)):c.startsWith("rename from ")?s.oldPath=Cs(c.slice(12),!1):c.startsWith("rename to ")?s.path=Cs(c.slice(10),!1):c.startsWith("Binary files ")||c==="GIT binary patch"?s.binary=!0:c==="\\ Preview truncated"&&(s.truncated=!0)}return n.filter(c=>c.path)}function Bc(t,n){const s=t.match(/\s+|[\p{L}\p{N}_]+|[^\s\p{L}\p{N}_]/gu)??[],r=n.match(/\s+|[\p{L}\p{N}_]+|[^\s\p{L}\p{N}_]/gu)??[],i=new Set;if(s.length*r.length<=25e4){const o=r.length+1,c=new Uint32Array((s.length+1)*o);for(let l=s.length-1;l>=0;l--)for(let p=r.length-1;p>=0;p--)c[l*o+p]=s[l]===r[p]?c[(l+1)*o+p+1]+1:Math.max(c[(l+1)*o+p],c[l*o+p+1]);for(let l=0,p=0;l<s.length&&p<r.length;)s[l]===r[p]?(i.add(l++),p++):c[(l+1)*o+p]>=c[l*o+p+1]?l++:p++}else{let o=0,c=0;for(;o<s.length&&o<r.length&&s[o]===r[o];)i.add(o++);for(;c<s.length-o&&c<r.length-o&&s.at(-c-1)===r.at(-c-1);)i.add(s.length-c-1),c++}const a=[];return s.forEach((o,c)=>{const l=!i.has(c),p=a.at(-1);(p==null?void 0:p.changed)===l?p.text+=o:a.push({text:o,changed:l})}),a}function Uc(t){const n=[];for(let s=0;s<t.length;){if(t[s].marker!==" "){n.push({kind:"line",index:s++});continue}let r=s;for(;r<t.length&&t[r].marker===" ";)r++;const i=s===0?s:Math.min(s+3,r),a=r===t.length?r:Math.max(i,r-3);if(a-i>4){for(let o=s;o<i;o++)n.push({kind:"line",index:o});n.push({kind:"gap",start:i,end:a});for(let o=a;o<r;o++)n.push({kind:"line",index:o})}else for(let o=s;o<r;o++)n.push({kind:"line",index:o});s=r}return n}function Wc(t,n,s,r){const i=new Map,a=t.flatMap((o,c)=>o.role==="user"&&o.origin!=="auto-reminder"?[c]:[]);for(let o=0;o<a.length;o++){if(r&&o===a.length-1)continue;const c=t.slice(a[o],a[o+1]??t.length),l=c.findLast(f=>f.role==="assistant");if(!l)continue;const p=(n==null?void 0:n.sourceMessageId)===c[0].id?n:{id:c[0].id,sourceMessageId:c[0].id,steps:c.filter(f=>f.role==="assistant").map(f=>({id:f.id,messageId:f.id,title:"",status:"done",startedAt:0,artifacts:f.content.flatMap(k=>{if(k.type!=="toolCall")return[];const j=k,R=$s(j);return R?[{toolCallId:j.id,kind:R.kind,path:R.path,label:R.path}]:[]})}))},u=Co(p,n===p?t:c,s);u.length&&i.set(l.id,u)}return i}var So={color:void 0,size:void 0,className:void 0,style:void 0,attr:void 0},ta=ks.createContext&&ks.createContext(So),qc=["attr","size","title"];function zc(t,n){if(t==null)return{};var s,r,i=Vc(t,n);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(t);for(r=0;r<a.length;r++)s=a[r],n.indexOf(s)===-1&&{}.propertyIsEnumerable.call(t,s)&&(i[s]=t[s])}return i}function Vc(t,n){if(t==null)return{};var s={};for(var r in t)if({}.hasOwnProperty.call(t,r)){if(n.indexOf(r)!==-1)continue;s[r]=t[r]}return s}function ur(){return ur=Object.assign?Object.assign.bind():function(t){for(var n=1;n<arguments.length;n++){var s=arguments[n];for(var r in s)({}).hasOwnProperty.call(s,r)&&(t[r]=s[r])}return t},ur.apply(null,arguments)}function na(t,n){var s=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);n&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),s.push.apply(s,r)}return s}function pr(t){for(var n=1;n<arguments.length;n++){var s=arguments[n]!=null?arguments[n]:{};n%2?na(Object(s),!0).forEach(function(r){Kc(t,r,s[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(s)):na(Object(s)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(s,r))})}return t}function Kc(t,n,s){return(n=Gc(n))in t?Object.defineProperty(t,n,{value:s,enumerable:!0,configurable:!0,writable:!0}):t[n]=s,t}function Gc(t){var n=Jc(t,"string");return typeof n=="symbol"?n:n+""}function Jc(t,n){if(typeof t!="object"||!t)return t;var s=t[Symbol.toPrimitive];if(s!==void 0){var r=s.call(t,n);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(n==="string"?String:Number)(t)}function No(t){return t&&t.map((n,s)=>ks.createElement(n.tag,pr({key:s},n.attr),No(n.child)))}function it(t){return n=>ks.createElement(Qc,ur({attr:pr({},t.attr)},n),No(t.child))}function Qc(t){var n=s=>{var r=t.attr,i=t.size,a=t.title,o=zc(t,qc),c=i||s.size||"1em",l;return s.className&&(l=s.className),t.className&&(l=(l?l+" ":"")+t.className),ks.createElement("svg",ur({stroke:"currentColor",fill:"currentColor",strokeWidth:"0"},s.attr,r,o,{className:l,style:pr(pr({color:t.color||s.color},s.style),t.style),height:c,width:c,xmlns:"http://www.w3.org/2000/svg"}),a&&ks.createElement("title",null,a),t.children)};return ta!==void 0?ks.createElement(ta.Consumer,null,s=>n(s)):n(So)}function Yc(t){return it({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"circle",attr:{cx:"11",cy:"11",r:"8"},child:[]},{tag:"line",attr:{x1:"21",y1:"21",x2:"16.65",y2:"16.65"},child:[]},{tag:"line",attr:{x1:"8",y1:"11",x2:"14",y2:"11"},child:[]}]})(t)}function Xc(t){return it({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"circle",attr:{cx:"11",cy:"11",r:"8"},child:[]},{tag:"line",attr:{x1:"21",y1:"21",x2:"16.65",y2:"16.65"},child:[]},{tag:"line",attr:{x1:"11",y1:"8",x2:"11",y2:"14"},child:[]},{tag:"line",attr:{x1:"8",y1:"11",x2:"14",y2:"11"},child:[]}]})(t)}function Zc(t){return it({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polygon",attr:{points:"13 2 3 14 12 14 11 22 21 10 12 10 13 2"},child:[]}]})(t)}function Wt(t){return it({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"line",attr:{x1:"18",y1:"6",x2:"6",y2:"18"},child:[]},{tag:"line",attr:{x1:"6",y1:"6",x2:"18",y2:"18"},child:[]}]})(t)}function sa(t){return it({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polygon",attr:{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"},child:[]},{tag:"path",attr:{d:"M19.07 4.93a10 10 0 0 1 0 14.14M15.54 8.46a5 5 0 0 1 0 7.07"},child:[]}]})(t)}function _s(t){return it({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"4 7 4 4 20 4 20 7"},child:[]},{tag:"line",attr:{x1:"9",y1:"20",x2:"15",y2:"20"},child:[]},{tag:"line",attr:{x1:"12",y1:"4",x2:"12",y2:"20"},child:[]}]})(t)}function Or(t){return it({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"3 6 5 6 21 6"},child:[]},{tag:"path",attr:{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"},child:[]},{tag:"line",attr:{x1:"10",y1:"11",x2:"10",y2:"17"},child:[]},{tag:"line",attr:{x1:"14",y1:"11",x2:"14",y2:"17"},child:[]}]})(t)}function ra(t){return it({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"},child:[]}]})(t)}function Ni(t){return it({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"4 17 10 11 4 5"},child:[]},{tag:"line",attr:{x1:"12",y1:"19",x2:"20",y2:"19"},child:[]}]})(t)}function ia(t){return it({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M20.59 13.41l-7.17 7.17a2 2 0 0 1-2.83 0L2 12V2h10l8.59 8.59a2 2 0 0 1 0 2.82z"},child:[]},{tag:"line",attr:{x1:"7",y1:"7",x2:"7.01",y2:"7"},child:[]}]})(t)}function ms(t){return it({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"rect",attr:{x:"3",y:"3",width:"18",height:"18",rx:"2",ry:"2"},child:[]}]})(t)}function aa(t){return it({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"rect",attr:{x:"3",y:"3",width:"18",height:"18",rx:"2",ry:"2"},child:[]},{tag:"line",attr:{x1:"9",y1:"3",x2:"9",y2:"21"},child:[]}]})(t)}function qs(t){return it({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"circle",attr:{cx:"12",cy:"12",r:"3"},child:[]},{tag:"path",attr:{d:"M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1z"},child:[]}]})(t)}function as(t){return it({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"circle",attr:{cx:"11",cy:"11",r:"8"},child:[]},{tag:"line",attr:{x1:"21",y1:"21",x2:"16.65",y2:"16.65"},child:[]}]})(t)}function ed(t){return it({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z"},child:[]},{tag:"polyline",attr:{points:"17 21 17 13 7 13 7 21"},child:[]},{tag:"polyline",attr:{points:"7 3 7 8 15 8"},child:[]}]})(t)}function td(t){return it({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"23 4 23 10 17 10"},child:[]},{tag:"path",attr:{d:"M20.49 15a9 9 0 1 1-2.12-9.36L23 10"},child:[]}]})(t)}function nd(t){return it({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"1 4 1 10 7 10"},child:[]},{tag:"path",attr:{d:"M3.51 15a9 9 0 1 0 2.13-9.36L1 10"},child:[]}]})(t)}function ys(t){return it({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"23 4 23 10 17 10"},child:[]},{tag:"polyline",attr:{points:"1 20 1 14 7 14"},child:[]},{tag:"path",attr:{d:"M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"},child:[]}]})(t)}function ls(t){return it({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"line",attr:{x1:"12",y1:"5",x2:"12",y2:"19"},child:[]},{tag:"line",attr:{x1:"5",y1:"12",x2:"19",y2:"12"},child:[]}]})(t)}function Pf(t){return it({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polygon",attr:{points:"5 3 19 12 5 21 5 3"},child:[]}]})(t)}function oa(t){return it({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M21.44 11.05l-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48"},child:[]}]})(t)}function sd(t){return it({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"line",attr:{x1:"16.5",y1:"9.4",x2:"7.5",y2:"4.21"},child:[]},{tag:"path",attr:{d:"M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"},child:[]},{tag:"polyline",attr:{points:"3.27 6.96 12 12.01 20.73 6.96"},child:[]},{tag:"line",attr:{x1:"12",y1:"22.08",x2:"12",y2:"12"},child:[]}]})(t)}function Ms(t){return it({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"circle",attr:{cx:"12",cy:"12",r:"1"},child:[]},{tag:"circle",attr:{cx:"19",cy:"12",r:"1"},child:[]},{tag:"circle",attr:{cx:"5",cy:"12",r:"1"},child:[]}]})(t)}function ti(t){return it({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"line",attr:{x1:"5",y1:"12",x2:"19",y2:"12"},child:[]}]})(t)}function Eo(t){return it({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"},child:[]}]})(t)}function To(t){return it({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"line",attr:{x1:"3",y1:"12",x2:"21",y2:"12"},child:[]},{tag:"line",attr:{x1:"3",y1:"6",x2:"21",y2:"6"},child:[]},{tag:"line",attr:{x1:"3",y1:"18",x2:"21",y2:"18"},child:[]}]})(t)}function Ro(t){return it({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"15 3 21 3 21 9"},child:[]},{tag:"polyline",attr:{points:"9 21 3 21 3 15"},child:[]},{tag:"line",attr:{x1:"21",y1:"3",x2:"14",y2:"10"},child:[]},{tag:"line",attr:{x1:"3",y1:"21",x2:"10",y2:"14"},child:[]}]})(t)}function rd(t){return it({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"rect",attr:{x:"3",y:"11",width:"18",height:"11",rx:"2",ry:"2"},child:[]},{tag:"path",attr:{d:"M7 11V7a5 5 0 0 1 10 0v4"},child:[]}]})(t)}function id(t){return it({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"line",attr:{x1:"12",y1:"2",x2:"12",y2:"6"},child:[]},{tag:"line",attr:{x1:"12",y1:"18",x2:"12",y2:"22"},child:[]},{tag:"line",attr:{x1:"4.93",y1:"4.93",x2:"7.76",y2:"7.76"},child:[]},{tag:"line",attr:{x1:"16.24",y1:"16.24",x2:"19.07",y2:"19.07"},child:[]},{tag:"line",attr:{x1:"2",y1:"12",x2:"6",y2:"12"},child:[]},{tag:"line",attr:{x1:"18",y1:"12",x2:"22",y2:"12"},child:[]},{tag:"line",attr:{x1:"4.93",y1:"19.07",x2:"7.76",y2:"16.24"},child:[]},{tag:"line",attr:{x1:"16.24",y1:"7.76",x2:"19.07",y2:"4.93"},child:[]}]})(t)}function dr(t){return it({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"line",attr:{x1:"8",y1:"6",x2:"21",y2:"6"},child:[]},{tag:"line",attr:{x1:"8",y1:"12",x2:"21",y2:"12"},child:[]},{tag:"line",attr:{x1:"8",y1:"18",x2:"21",y2:"18"},child:[]},{tag:"line",attr:{x1:"3",y1:"6",x2:"3.01",y2:"6"},child:[]},{tag:"line",attr:{x1:"3",y1:"12",x2:"3.01",y2:"12"},child:[]},{tag:"line",attr:{x1:"3",y1:"18",x2:"3.01",y2:"18"},child:[]}]})(t)}function hr(t){return it({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"},child:[]},{tag:"path",attr:{d:"M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"},child:[]}]})(t)}function Es(t){return it({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polygon",attr:{points:"12 2 2 7 12 12 22 7 12 2"},child:[]},{tag:"polyline",attr:{points:"2 17 12 22 22 17"},child:[]},{tag:"polyline",attr:{points:"2 12 12 17 22 12"},child:[]}]})(t)}function ad(t){return it({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M21 2l-2 2m-7.61 7.61a5.5 5.5 0 1 1-7.778 7.778 5.5 5.5 0 0 1 7.777-7.777zm0 0L15.5 7.5m0 0l3 3L22 7l-3-3m-3.5 3.5L19 4"},child:[]}]})(t)}function la(t){return it({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"line",attr:{x1:"19",y1:"4",x2:"10",y2:"4"},child:[]},{tag:"line",attr:{x1:"14",y1:"20",x2:"5",y2:"20"},child:[]},{tag:"line",attr:{x1:"15",y1:"4",x2:"9",y2:"20"},child:[]}]})(t)}function od(t){return it({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"circle",attr:{cx:"12",cy:"12",r:"10"},child:[]},{tag:"line",attr:{x1:"12",y1:"16",x2:"12",y2:"12"},child:[]},{tag:"line",attr:{x1:"12",y1:"8",x2:"12.01",y2:"8"},child:[]}]})(t)}function Io(t){return it({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"rect",attr:{x:"3",y:"3",width:"18",height:"18",rx:"2",ry:"2"},child:[]},{tag:"circle",attr:{cx:"8.5",cy:"8.5",r:"1.5"},child:[]},{tag:"polyline",attr:{points:"21 15 16 10 5 21"},child:[]}]})(t)}function ld(t){return it({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"},child:[]},{tag:"polyline",attr:{points:"9 22 9 12 15 12 15 22"},child:[]}]})(t)}function cd(t){return it({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"line",attr:{x1:"22",y1:"12",x2:"2",y2:"12"},child:[]},{tag:"path",attr:{d:"M5.45 5.11L2 12v6a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6l-3.45-6.89A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z"},child:[]},{tag:"line",attr:{x1:"6",y1:"16",x2:"6.01",y2:"16"},child:[]},{tag:"line",attr:{x1:"10",y1:"16",x2:"10.01",y2:"16"},child:[]}]})(t)}function ca(t){return it({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"circle",attr:{cx:"12",cy:"12",r:"10"},child:[]},{tag:"line",attr:{x1:"2",y1:"12",x2:"22",y2:"12"},child:[]},{tag:"path",attr:{d:"M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"},child:[]}]})(t)}function hs(t){return it({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"line",attr:{x1:"6",y1:"3",x2:"6",y2:"15"},child:[]},{tag:"circle",attr:{cx:"18",cy:"6",r:"3"},child:[]},{tag:"circle",attr:{cx:"6",cy:"18",r:"3"},child:[]},{tag:"path",attr:{d:"M18 9a9 9 0 0 1-9 9"},child:[]}]})(t)}function Ks(t){return it({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"},child:[]}]})(t)}function Gs(t){return it({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M13 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V9z"},child:[]},{tag:"polyline",attr:{points:"13 2 13 9 20 9"},child:[]}]})(t)}function dd(t){return it({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"},child:[]},{tag:"polyline",attr:{points:"14 2 14 8 20 8"},child:[]},{tag:"line",attr:{x1:"16",y1:"13",x2:"8",y2:"13"},child:[]},{tag:"line",attr:{x1:"16",y1:"17",x2:"8",y2:"17"},child:[]},{tag:"polyline",attr:{points:"10 9 9 9 8 9"},child:[]}]})(t)}function Lo(t){return it({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"},child:[]},{tag:"polyline",attr:{points:"15 3 21 3 21 9"},child:[]},{tag:"line",attr:{x1:"10",y1:"14",x2:"21",y2:"3"},child:[]}]})(t)}function da(t){return it({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M12 20h9"},child:[]},{tag:"path",attr:{d:"M16.5 3.5a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4L16.5 3.5z"},child:[]}]})(t)}function ua(t){return it({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M17 3a2.828 2.828 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5L17 3z"},child:[]}]})(t)}function Pr(t){return it({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"},child:[]},{tag:"polyline",attr:{points:"7 10 12 15 17 10"},child:[]},{tag:"line",attr:{x1:"12",y1:"15",x2:"12",y2:"3"},child:[]}]})(t)}function Ei(t){return it({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"rect",attr:{x:"4",y:"4",width:"16",height:"16",rx:"2",ry:"2"},child:[]},{tag:"rect",attr:{x:"9",y:"9",width:"6",height:"6"},child:[]},{tag:"line",attr:{x1:"9",y1:"1",x2:"9",y2:"4"},child:[]},{tag:"line",attr:{x1:"15",y1:"1",x2:"15",y2:"4"},child:[]},{tag:"line",attr:{x1:"9",y1:"20",x2:"9",y2:"23"},child:[]},{tag:"line",attr:{x1:"15",y1:"20",x2:"15",y2:"23"},child:[]},{tag:"line",attr:{x1:"20",y1:"9",x2:"23",y2:"9"},child:[]},{tag:"line",attr:{x1:"20",y1:"14",x2:"23",y2:"14"},child:[]},{tag:"line",attr:{x1:"1",y1:"9",x2:"4",y2:"9"},child:[]},{tag:"line",attr:{x1:"1",y1:"14",x2:"4",y2:"14"},child:[]}]})(t)}function ud(t){return it({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"15 14 20 9 15 4"},child:[]},{tag:"path",attr:{d:"M4 20v-7a4 4 0 0 1 4-4h12"},child:[]}]})(t)}function Mo(t){return it({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"9 14 4 9 9 4"},child:[]},{tag:"path",attr:{d:"M20 20v-7a4 4 0 0 0-4-4H4"},child:[]}]})(t)}function pd(t){return it({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"14 9 9 4 4 9"},child:[]},{tag:"path",attr:{d:"M20 20h-7a4 4 0 0 1-4-4V4"},child:[]}]})(t)}function ws(t){return it({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"rect",attr:{x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"},child:[]},{tag:"path",attr:{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"},child:[]}]})(t)}function Po(t){return it({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"16 18 22 12 16 6"},child:[]},{tag:"polyline",attr:{points:"8 6 2 12 8 18"},child:[]}]})(t)}function pa(t){return it({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"circle",attr:{cx:"12",cy:"12",r:"10"},child:[]},{tag:"polyline",attr:{points:"12 6 12 12 16 14"},child:[]}]})(t)}function hd(t){return it({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"7 13 12 18 17 13"},child:[]},{tag:"polyline",attr:{points:"7 6 12 11 17 6"},child:[]}]})(t)}function Ao(t){return it({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"18 15 12 9 6 15"},child:[]}]})(t)}function _t(t){return it({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"9 18 15 12 9 6"},child:[]}]})(t)}function Qt(t){return it({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"6 9 12 15 18 9"},child:[]}]})(t)}function ts(t){return it({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"20 6 9 17 4 12"},child:[]}]})(t)}function md(t){return it({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"9 11 12 14 22 4"},child:[]},{tag:"path",attr:{d:"M21 12v7a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11"},child:[]}]})(t)}function Do(t){return it({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"rect",attr:{x:"3",y:"4",width:"18",height:"18",rx:"2",ry:"2"},child:[]},{tag:"line",attr:{x1:"16",y1:"2",x2:"16",y2:"6"},child:[]},{tag:"line",attr:{x1:"8",y1:"2",x2:"8",y2:"6"},child:[]},{tag:"line",attr:{x1:"3",y1:"10",x2:"21",y2:"10"},child:[]}]})(t)}function fd(t){return it({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"},child:[]},{tag:"polyline",attr:{points:"3.27 6.96 12 12.01 20.73 6.96"},child:[]},{tag:"line",attr:{x1:"12",y1:"22.08",x2:"12",y2:"12"},child:[]}]})(t)}function gd(t){return it({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M2 3h6a4 4 0 0 1 4 4v14a3 3 0 0 0-3-3H2z"},child:[]},{tag:"path",attr:{d:"M22 3h-6a4 4 0 0 0-4 4v14a3 3 0 0 1 3-3h7z"},child:[]}]})(t)}function ha(t){return it({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M6 4h8a4 4 0 0 1 4 4 4 4 0 0 1-4 4H6z"},child:[]},{tag:"path",attr:{d:"M6 12h9a4 4 0 0 1 4 4 4 4 0 0 1-4 4H6z"},child:[]}]})(t)}function mr(t){return it({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"line",attr:{x1:"12",y1:"19",x2:"12",y2:"5"},child:[]},{tag:"polyline",attr:{points:"5 12 12 5 19 12"},child:[]}]})(t)}function $o(t){return it({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"line",attr:{x1:"12",y1:"5",x2:"12",y2:"19"},child:[]},{tag:"polyline",attr:{points:"19 12 12 19 5 12"},child:[]}]})(t)}function ma(t){return it({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"21 8 21 21 3 21 3 8"},child:[]},{tag:"rect",attr:{x:"1",y:"3",width:"22",height:"5"},child:[]},{tag:"line",attr:{x1:"10",y1:"12",x2:"14",y2:"12"},child:[]}]})(t)}function Fo(t){return it({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"},child:[]},{tag:"line",attr:{x1:"12",y1:"9",x2:"12",y2:"13"},child:[]},{tag:"line",attr:{x1:"12",y1:"17",x2:"12.01",y2:"17"},child:[]}]})(t)}function xd(t){return it({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"circle",attr:{cx:"12",cy:"12",r:"10"},child:[]},{tag:"line",attr:{x1:"12",y1:"8",x2:"12",y2:"12"},child:[]},{tag:"line",attr:{x1:"12",y1:"16",x2:"12.01",y2:"16"},child:[]}]})(t)}const Oo="pi-harness:lang",vd={nodeAgentTitle:"Agent 工作台",nodeOpenWorkbench:"打开工作台",nodeAgentSend:"发送",nodeAgentRemote:"在远端节点运行",nodeAgentSetup:"使用节点上的 pi、模型凭据和原生工具,操作此节点的文件与进程。",nodeAgentInstall:"需要远端 Node ≥22.19.0 和 pi 1.0.4。未安装时,在终端执行以下命令,再运行 pi 配置模型。",nodeAgentStart:"启动远端 Agent",nodeAgentStarting:"正在启动远端 Agent…",nodeAgentOffline:"节点已断开,请重新连接。",nodeAgentNew:"新对话",nodeAgentClose:"关闭 Agent",nodeAgentYou:"我",nodeAgentThinking:"思考过程",nodeAgentWorking:"远端 Agent 正在工作…",nodeAgentSelect:"请选择",nodeAgentPrompt:"让 Agent 在此节点执行任务…",nodeAgentModel:"远端模型",nodeAgentQueue:"运行中发送方式",nodeAgentFollowUp:"排队",nodeAgentSteer:"纠正",nodeAgentTerminal:"终端与文件",toolParameters:"参数",toolOutputFileOnly:"完整结果可下载",mcpAdapterNoticeTitle:"旧 MCP 扩展需要选择配置方式",mcpAdapterNoticeNative:"pi 已内置 MCP,使用 mcp.json。如果你使用内置 MCP,请在 Extensions 中关闭 pi-mcp-adapter,再点击重载;保留 mcp.json。",mcpAdapterNoticeSeparate:"如果需要继续使用该扩展,请按扩展文档配置独立的 mcp-adapter.json,确认哪些服务交由扩展管理。不要直接移动正在供内置 MCP 使用的 mcp.json。",mcpAdapterNoticeOriginal:"查看扩展原始提示",changesTitle:"改动",changesRegenerate:"重新生成",changesTurn:"本轮",changesBranch:"整个分支",changesWork:"未提交",changesSummary:"改了 {n} 个文件",changesViewAll:"全部查看",changesMore:"还有 {n} 个文件",changesFiles:"{n} 个文件",changesList:"文件列表",changesBase:"基准分支",changesSearch:"在改动里搜索",changesExpand:"全部展开或收起",changesEmpty:"此范围没有改动",changesBinary:"二进制文件,无法显示差异",changesUnavailable:"没有可显示的文本差异",changesUnlocated:"行号不可用",changesLarge:"大文件 · 点击展开",changesUnchanged:"⇕ {n} 行未改动",changesTrailing:"显示后面 {n} 行",changesRecent:"刚刚改动",changesTruncated:"差异已截断",changesLoading:"正在读取改动…",changesReducedContext:"改动较大,只显示改动附近的上下文。",changesOmittedUntracked:"另有 {n} 个未跟踪文件未显示,可将它们加入 .gitignore。",changesCommands:"{n} 条命令",bashDurationUnknown:"耗时未记录",bashGroupCount:"运行了 {n} 条命令",bashGroupRunning:"正在运行 {n} 条命令",bashGroupFailed:"· {n} 条失败",bashGroupCwd:"在 {path}",bashGroupEarlier:"前面还有 {n} 条 · 展开全部",bashExtraLines:"+{n} 行",bashExitCode:"退出码 {n}",bashUnfinished:"未完成",bashRemainingLines:"展开其余 {n} 行",bashCopyCommand:"复制命令",bashCopyOutput:"复制输出",bashOpenTerminal:"在终端中打开",bashOpenTerminalHint:"在可见终端重新运行完整命令",bashCommandCount:"{n} 条命令",editBusy:"编辑重问暂不可用,请等待当前回复、压缩或切换完成。",editFailed:"编辑重问已取消或失败。",treeTitle:"会话树",treeFork:"派生新会话",treeForkAt:"从这里派生",treeFilter:"过滤节点",treeSearch:"搜索会话树",treeExternal:"会话文件已被外部修改,重新打开后才能继续写入。",treeReopen:"重新打开",treeTruncated:"结果超过 5000 个节点,请缩小过滤范围或搜索。",treeEmpty:"没有匹配的节点",treeFold:"折叠或展开分支",treeNavigate:"切换到这里",treeLabel:"设置书签",treeNodes:"个节点",treeClone:"复制当前分支",treePreviewCount:"将总结 {n} 条记录",treeSummary_none:"不生成摘要",treeSummary_default:"生成摘要",treeSummary_custom:"按自定义指令生成摘要",treeInstructions:"摘要指令",treeStopConfirm:"停止当前回复并切换,将排队消息放回输入框",treeLabelClear:"留空可清除书签",treeContent:"节点内容",treeDisconnected:"连接已断开,请重连后重试",treeBusy:"等待当前回复、压缩或切换完成",treeCancelled:"扩展取消了切换",treeAborted:"已取消分支摘要,保留原位置",treeFailed:"会话树操作失败",treeDraftConflict:"切换返回了文本,当前输入框已有草稿。请选择如何保留。",treeReturnedText:"查看返回的文本",treeReplaceDraft:"替换草稿",treeAppendDraft:"追加到草稿",treeKeepDraft:"保留当前草稿",treeEditOptions:"重问选项",treePrevious:"上一个分支",treeNext:"下一个分支",treeSummarizing:"正在总结离开的分支",treeEditNewSession:"编辑重问时新建会话",treeBranches:"{n} 个分叉点",treeDerived:"派生自 {name}",treeFilter_default:"默认","treeFilter_no-tools":"隐藏工具","treeFilter_user-only":"仅用户","treeFilter_labeled-only":"仅书签",treeFilter_all:"全部(CLI 规则)",treeKind_user:"用户",treeKind_assistant:"助手",treeKind_tool:"工具",treeKind_compaction:"压缩",treeKind_branchSummary:"分支摘要",treeKind_custom:"自定义",treeKind_model:"模型",treeKind_thinking:"思考档位",treeKind_info:"会话信息",treeKind_contextEdit:"上下文编辑",treeKind_label:"书签变更",wikiSaving:"保存中",wikiSaved:"已保存",wikiSaveFailedRetry:"保存失败 · 重试",wikiExternalChanged:"文件已在外部修改",wikiKeepMine:"保留我的版本",wikiMessageActions:"消息操作",wikiFullRequest:"查看完整发送内容",wikiResend:"重新发送",wikiReplyChanged:"修改了 {file}",wikiViewChange:"查看",richImage:"图片",richWikiLink:"文档链接",wikiLinkAddress:"输入链接,或 [[ 搜索文档",wikiInsertLinkAction:"插入链接",wikiInvalidLink:"请输入 http、https、mailto 或相对链接",wikiInsertParagraph:"普通正文段落",wikiInsertH1:"一级标题",wikiInsertH2:"二级标题",wikiInsertH3:"三级标题",wikiInsertList:"无序的项目列表",wikiInsertOrdered:"按顺序排列的列表",wikiInsertTask:"可勾选的待办事项",wikiInsertQuote:"引用一段文字",wikiInsertCode:"带语法高亮的代码",wikiInsertCallout:"强调提示或注意事项",wikiInsertTable:"插入 3 × 3 表格",wikiInsertDivider:"分隔不同内容",wikiInsertImage:"上传或粘贴图片",wikiInsertLink:"搜索并链接到文档",wikiNoInsertResults:"没有匹配项 · 按 Esc 关闭",wikiInsertKeys:"↑ ↓ 选择 ↵ 插入 Esc 关闭",v2PromptHint:"每次对话开头发给模型",v2IdentityHint:"告诉模型它是 Pi,该怎么工作",v2ToolsHint:"模型能调用的能力,随启用的工具和扩展变化",v2RulesHint:"工具的用法说明,由 Pi 自动去重",v2DocsHint:"只在你问到 Pi 本身时才读取",v2AppendHint:"写在默认内容之后的个人要求,例如回复语言",v2ContextHint:"当前目录和上级目录中的上下文,自动读取",v2CreateAgents:"新建 AGENTS.md",v2PiHint:"Desktop 内置的智能体引擎,随应用升级",v2ExtensionsIntro:"扩展为 Pi 增加工具和命令;扩展包还可以包含技能、提示词和主题。",v2ExtensionCount:"共 {n} 项",v2LastChecked:"上次检查 {time}",v2PackagesHint:"可检查更新",v2NoPackages:"还没有可管理的扩展包。浏览 pi.dev,找到需要的工具或技能。",v2FilesHint:"修改文件后重新加载生效",v2UpdatePolicy:"更新方式",v2AutoCheckHint:"打开管理页时检查,此后服务运行期间每 6 小时检查扩展包",v2InstallPolicy:"安装扩展更新",v2InstallHint:"由你确认更新;完成后重新加载或新建会话生效",v2ManualInstall:"手动安装",v2SkillsIntro:"技能是按需读取的操作指南。启用后仅名称和描述进入提示词,需要时才读取正文;关闭后不会被发现。",v2SkillCount:"共 {n} 项 · 已启用 {enabled} 项 · 约 {tokens} tokens",v2SkillSearch:"搜索技能名称或描述",v2SkillPackage:"扩展包",v2SkillAll:"全部",v2SkillsPaths:"技能目录",v2CopyPaths:"复制目录路径",v2OpenSkills:"打开技能目录",v2SkillsChanged:"已保存原生技能配置。重新加载或新建会话后生效。",v2ServersHint:"连接外部服务,让模型使用更多工具",v2ScopeHint:"全局对所有项目生效;项目只影响当前工作目录",v2CodemodeHint:"让模型写小段脚本批量调用工具,减少往返和上下文占用",v2ModeHint:"on:保留直接调用;only:工具通过脚本调用",v2BudgetHint:"直接放入上下文的工具声明预算;0 表示全部按需查找",v2AutoHint:"有 MCP 服务时自动启用 Codemode",v2EditMcp:"编辑 mcp.json",v2NoServersHint:"还没有配置服务。导入已有配置,或新建一个连接。",promptSavedShadowed:"已保存;当前会话仍使用优先级更高的同名文件。",promptDiscard:"放弃未保存的改动?",promptRestoreConfirm:"删除 {path}?Pi 将按原生优先级使用下一份 SYSTEM.md;没有其他文件时恢复默认提示词。",promptCopyFailed:"复制失败,请从原始文本中手动复制。",promptReplaceWarning:"SYSTEM.md 会替换默认身份、工具说明、规则和 Pi 文档段落。追加提示词、项目上下文、技能及工作目录仍由 Pi 管理。建议只需要补充指令时使用追加提示词。",promptContinueReplace:"继续替换",promptScope:"保存范围",promptUser:"个人 · 所有项目",promptProject:"当前项目",promptUntrusted:"未信任",promptContextHint:"编辑实际加载的上下文文件;上级目录或个人文件的修改也会影响使用它的其他项目。",promptEditor:"提示词文件内容",promptNativeSave:"保存到原生文件",promptReloadFile:"重新读取文件",promptSaving:"保存中…",promptSave:"保存",promptTokenHint:"粗略估算,包含技能和工作目录;实际 token 数取决于模型。",promptTokens:"约 {n} tokens",promptViewSections:"分段视图",promptViewRaw:"原始文本",promptCopied:"已复制",promptCopy:"复制全文",promptSavedPending:"文件已保存,等待会话空闲后重新加载。",promptSavedNext:"已重新加载;Pi 会在下一次请求中应用变化。",promptReloadFailed:"原生重新加载失败,文件已保存。",promptRetry:"重试加载",promptForced:"当前扩展强制设置了完整提示词,无法可靠拆分来源。仅显示原始文本,编辑已禁用。",promptOpaque:"当前提示词无法与 Pi 原生结构匹配,仅显示原始文本,编辑已禁用。",settingsLoaded:"已加载",settingsNoSkills:"暂无技能",settingsNoServers:"暂无服务器",settingsImportSave:"导入并保存",settingsRetrySave:"重试保存",settingsToolPresentation:"工具呈现",settingsDeclarationBudget:"声明预算",settingsAutoCodemode:"连接 MCP 时自动启用",settingsPackages:"包",settingsUpdates:"更新",settingsAutoCheck:"自动检查更新",settingsCheckNow:"立即检查",settingsBundled:"随应用更新",promptDefault:"身份",promptReplaced:"已由 SYSTEM.md 或运行时设置替换",promptBuiltinIdentity:"pi 默认",promptEdit:"编辑",promptRestore:"移除此替换",promptReplace:"替换",promptTools:"工具",promptInactive:"未包含说明",promptAutomatic:"自动生成",promptRules:"规则",promptRuleSummary:"{builtin} 条内置 · {tools} 条工具 · {extensions} 条扩展 / 运行时",promptCollapse:"收起",promptExpand:"展开",promptBuiltin:"内置",promptExtension:"扩展",promptRuntime:"运行时",promptDocs:"Pi 文档",promptDocsSummary:"按需阅读",promptAppend:"追加提示词",promptNotSet:"未设置",promptAdd:"添加",promptContext:"项目上下文",promptNoContext:"没有加载上下文文件",promptRuntimeSection:"原生运行时提供的额外段落",promptPriority:"受信任项目的 .pi 文件优先于个人目录同名文件;每类仅加载一份。技能和工作目录包含在全文中。",promptProjectNotTrusted:"当前项目尚未获得 Pi 信任,项目级替换与追加文件不可编辑。",promptDiskChanged:"磁盘内容与当前加载版本不同",connectionDisconnected:"连接已断开",downloadImage:"下载",extNew:"刚安装",extRetry:"重试",extEditFile:"编辑文件",extEditHint:"保存前请检查代码。变更将在重载后生效。",extDiscard:"放弃未保存的改动?",extSaveFile:"保存文件",extReleaseNotes:"版本说明",extNoNotes:"暂无可读取的版本说明。",extViewNotes:"查看完整版本说明",extSubtitle:"管理 Pi 原生扩展包与单文件扩展",extDetails:"查看详情",extPersonal:"个人",extProject:"项目",extUntrusted:"未信任 · 未加载",extPinned:"已锁定",extUpdate:"更新",extEnable:"启用",extOpen:"在文件管理器中显示",extCopyPath:"复制路径",extUnpin:"解除版本锁定",extMoveProject:"仅用于此项目",extMovePersonal:"移到个人范围",extRemoveReference:"移除引用",extUninstall:"卸载",extResources:"包含的资源",extResourceConfig:"资源单项开关由 pi config 管理,整包开关保留原有过滤规则。",extInstalled:"已安装",extBrowse:"浏览 pi.dev",extRefresh:"刷新",extRunning:"正在处理扩展包…",extDone:"操作完成",extFailed:"操作失败",extLog:"查看完整日志",extReloadHint:"变更在新会话生效;也可重载当前会话。",extReload:"重载当前会话",extLastChecked:"上次检查",extNotChecked:"尚未检查更新",extChecking:"检查中…",extCheck:"检查更新",extUpdatesAvailable:"个包可更新",extUpdateAll:"全部更新",extFilter:"筛选已安装扩展…",extScope:"安装范围",extInstallProject:"仅本项目",extAllScopes:"所有范围",extEmpty:"没有匹配的扩展包,浏览目录或从来源安装。",extSingleFiles:"单文件扩展 · 不检测版本更新",extAutoCheck:"打开页面时及每 6 小时自动检查更新",extTypeExtension:"扩展",extTypeSkill:"技能",extTypePrompt:"提示词",extTypeTheme:"主题",extLicenseUnknown:"未提供许可证",extCatalogPage:"pi.dev 页面",extCatalogOrigin:"来自 pi.dev · 带 pi-package 关键字的 npm 包 · 共 {count} 个",extCatalogOriginPage:"来自 pi.dev · 本页 {count} 个包",extInstallSource:"从 npm / git 安装",extUntrustedNotLoaded:"未信任,未加载",extWillLoad:"将加载的资源",extProjectUntrusted:"本项目尚未信任,暂不能安装到项目。",extNoneDeclared:"无",extInstalling:"安装中…",extSearch:"搜索 pi.dev 扩展包…",extSort:"排序",extPopular:"最多下载",extRecent:"最近更新",extAllTypes:"全部",extDownloads:"下载 / 月",extInstall:"安装",extNoResults:"没有找到匹配的扩展包。",extPrevious:"上一页",extNext:"下一页",extConfirm:"确认操作",extSource:"包来源",extReview:"查看安装信息",extResourcesUnknown:"该来源未声明资源清单;请先查看源代码。Git 来源在确认安装后才拉取。",extPinVersion:"锁定此版本",extSecurity:"扩展会在本机运行代码,技能可能让模型执行命令。不确定的话先看一下源码。",extViewSource:"查看源代码",extCancel:"取消",extRemoveHint:"移除这个包的配置及托管安装。对于本地路径,只移除引用,保留文件。",extMoveHint:"安装到目标范围,成功后移除原范围的声明,保留资源过滤规则。",extUnpinHint:"解除固定版本或 Git ref,下次检查可获取更新。",extUpdateHint:"更新可升级的包;锁定版本及本地路径保持不变。",cmCalls:"调用",cmScript:"脚本",cmWaitingCalls:"等待脚本调用…",cmNoCalls:"没有嵌套调用",cmMoreCalls:"前面还有 {n} 次调用 · 展开全部",cmCollapseCalls:"只显示最后 8 次调用",cmCancelled:"已取消",cmUnfinished:"未完成",cmLimitedCalls:"另有 {n} 次调用未在此显示",cmTruncated:"此预览已截断。",cmWaitingOutput:"输出将在脚本返回时显示。",cmNoOutput:"脚本没有文本输出。",cmFullOutput:"完整输出文件",cmFailureNote:"脚本失败前的工具调用已实际执行,不会自动撤销。错误及相似工具名建议见「输出」。",cmSaveImage:"保存到当前目录",cmAttachImage:"附加到下一条消息",cmAttached:"图片已添加到输入框",cmSaved:"已保存:{path}",cmModelCost:"模型调用费用",mcpDesignIntro:"管理原生 MCP 连接与 Codemode;设置直接保存到 pi 配置。",mcpServersTitle:"服务器",mcpAttentionFirst:"需要处理的连接优先显示,后台连接不会阻塞聊天输入。",mcpImport:"从其他客户端导入",mcpImportHelp:"粘贴 Claude、Cursor、VS Code 或 OpenCode 的 JSON 配置。重名服务器不会被覆盖;Codex TOML 请先转换为 mcpServers JSON。",mcpImportDraft:"导入到草稿",mcpEditorHelp:'填写原生服务器 JSON:本地使用 command / args / env,远程使用 url / headers / oauth。支持 clientRegistration: "cimd"。',mcpInvalidServer:"服务器配置必须是 JSON 对象",mcpDiscard:"放弃未保存的配置更改?",mcpNeedsAuth:"需要登录",mcpConnected:"已连接",mcpConnecting:"连接中",mcpDisabled:"已停用",mcpDisconnected:"已断开",mcpNotLoaded:"未加载",mcpFailed:"连接失败",mcpRuntime:"其他配置来源",mcpAuthHelp:"使用 pi 原生 OAuth 登录。服务器要求额外权限时,重新登录会保留已授予的权限。",mcpRemoteLogin:"浏览器在另一台机器上?登录后将跳转地址粘贴到原生登录输入框。",mcpAnnotations:"提示",mcpActualExposure:"实际暴露方式",mcpDestructive:"破坏性",mcpReadOnly:"只读",mcpInherit:"继承",mcpNoTools:"当前连接没有可展示的工具。",mcpExposureDraftHint:"* 为单工具覆盖。左侧是 SDK 实际暴露状态,codemode 在 SDK 中映射为 deferred;右侧修改配置草稿,保存后应用。",mcpEnableServer:"启用",mcpDisableServer:"停用",mcpEnableProject:"在本项目启用",mcpDisableProject:"在本项目停用",mcpRemoveConfirm:"从配置草稿中移除 {name}?保存后生效。",mcpUnsaved:"有未保存的更改",mcpSavedConfig:"配置已保存",mcpSaveApply:"保存并应用",mcpExposureGuide:"工具暴露方式说明",mcpExposure_codemode:"通过脚本或工具搜索按需发现,不直接声明。",mcpExposure_deferred:"tool_search 找到后加载,也可从脚本调用。",mcpExposure_direct:"直接声明给模型,同时支持脚本调用。",mcpExposure_hidden:"保留注册,但不可调用。",mcpEmpty:"尚未配置服务器。添加一个本地或远程 MCP 服务。",mcpCodemodeHelp:"只将脚本输出传给模型。工具调用遵循 pi 原生权限与生命周期。",mcpModeHelp:"on 保留直接工具;only 让模型统一通过脚本调用工具。",mcpBudgetHelp:"工具声明的估算 token 预算,默认 3000。0 仅列命名空间。",mcpBudgetSlider:"调整工具声明预算",mcpEffective:"当前会话生效值",mcpSaveCodemode:"保存 Codemode 设置",mcpAutoHelp:"codemode 暴露的 MCP 服务连接时自动启用。此项随 MCP 配置保存,不会关闭已启用的 codemode。",mcpAdvanced:"高级:原生 JSON 配置",wikiLoadMore:"加载更多文件",wikiOpenDefault:"用默认应用打开",wikiHiddenFolders:"隐藏文件夹 · {count}",wikiProperties:"文档属性",wikiIndexSkipped:"跳过 {count}",wikiIndexCounting:"统计中",wikiIndexStatus:"已索引 {indexed} / {total}",wikiIndexIssueCount:"{count} 项受限:{reason}",wikiIndexMultipleReasons:"{count} 种原因,点击查看",wikiIndexFileSize:"单个文件超过 2 MB",wikiIndexBudget:"总读取量超过 64 MB",wikiIndexEntries:"超过 20,000 项",wikiIndexDepth:"目录深度超过 32 层",wikiIndexUnreadable:"文件无法读取或路径不可访问",wikiIndexSubtree:"该目录还有未扫描内容",wikiIndexPartial:"扫描未覆盖整个工作区,仍有未统计的文件。下方按原因列出受限文件或未扫描目录。",wikiIndexHint:"部分内容未纳入索引。达到大小或预算限制的文件仍可按路径查找;无法访问的路径需要先解决访问问题。",wikiIndexComplete:"索引已完成,没有受限文件。",wikiUpdatedToday:"今天 {time} 更新",wikiUpdatedDate:"{date}更新",wikiReadingTime:"约 {minutes} 分钟读完",wikiCitations:"{count} 篇引用本文",wikiOnThisPage:"本页",wikiExpandComposer:"展开提问框",wikiCompactPlaceholder:"问 pi 关于这篇文档…",wikiCollapseComposer:"Esc 收起",wikiDocumentsOnly:"只改文档",wikiMayEditCode:"可改代码",wikiReferenceHint:"@ 引用",wikiSessionPreparing:"会话准备中",wikiRetrySession:"重试创建会话",wikiReferencesLoading:"引用加载中",wikiMode:"Wiki 模式",wikiRecent:"最近改动",wikiPreview:"渲染预览",wikiSource:"编辑源码",wikiSearchAll:"搜索全部文件",wikiFiles:"目录",wikiClear:"清除",wikiRefresh:"刷新文件",wikiUnread:"pi 修改后未查看",wikiNoFiles:"没有匹配的文件",wikiReload:"重新加载",wikiLimits:"部分文件未建立全文索引:单文件上限 2 MB,总量 64 MB,最多 20,000 项。目录仍可查看。",wikiBacklinks:"反向链接",wikiUnsaved:"有未保存修改",wikiCodeReadOnly:"代码只读 · 点击「编辑源码」可手动编辑",wikiEditingSource:"源码编辑 · ⌘/Ctrl S 保存",wikiPiAdded:"pi 新增",wikiDownloadOpen:"下载并用默认应用打开",wikiNoBacklinks:"还没有文档引用此文件",wikiWelcome:"和 pi 一起整理知识",wikiWelcomeHint:"从左侧打开文件,或搜索整个工作区。",wikiChangedFiles:"pi 修改了 {count} 个文件",wikiRedo:"重做",wikiUndo:"撤销",wikiChatPanel:"Wiki 对话面板",wikiFocus:"专注阅读",wikiTableSize:"表格尺寸",wikiTableDimensions:"{columns} 列 × {rows} 行",wikiTableHeader:"带表头",wikiSearchLanguage:"搜索语言…",wikiCodeAutomatic:"自动识别",wikiCodeAutomaticHint:"默认",wikiCodeShell:"命令行",wikiCodePython:"脚本",wikiCodeTypescript:"类型脚本",wikiCodeData:"结构化数据",wikiCodeConfig:"配置",wikiCodeQuery:"数据库查询",wikiCodeDiagram:"图表与源码",wikiMoreInsert:"更多插入",wikiMoreInsertHint:"更多插入 · 也可以输入 /",wikiStandardWidth:"标准宽度",wikiWideWidth:"宽版(隐藏两侧)",wikiMentionDate:"提及日期",wikiInsertDate:"插入今天的日期",wikiEmptyParagraph:"输入 / 插入内容,或直接写",wikiExitFocus:"退出专注阅读",wikiChatTitle:"对话",wikiCloseChat:"收起对话面板",wikiChatContext:"上下文 {percent}%",wikiNoModel:"未选择模型",wikiEarlierMessages:"查看更早的消息",wikiQuickSummary:"总结这篇文档",wikiQuickLinks:"找出失效链接",wikiQuickSections:"补全空的小节",wikiChatEmpty:"问 pi 关于这篇文档,或选中文字后提问。",wikiJumpSection:"跳到 §{section}",wikiToolInterrupted:"已中断",wikiWorking:"正在处理…",wikiLastAnswer:"最近一轮回复",wikiSelected:"选中内容",wikiAsk:"问 pi",wikiAskCode:"问 pi 关于 {file},比如「和文档一致吗」",wikiAskPlaceholder:"问 pi 关于这篇文档…",wikiScope:"范围",wikiCurrentScope:"范围 · 当前文档",wikiWholeScope:"范围 · 整个工作区",wikiReferencedScope:"范围 · 引用文件",wikiAllowCode:"允许修改代码",wikiPromptPreview:"查看发送内容",wikiStop:"停止",wikiSend:"发送",wikiRelatedChanges:"相关文档改动",wikiMe:"我",wikiFileCount:"{count} 个文件",wikiUndoAll:"全部撤销",wikiRedoAll:"全部重做",wikiViewDiff:"查看前后版本",wikiBinaryChange:"二进制文件改动,可恢复原始文件",wikiNewFile:"(新建文件)",wikiDeletedFile:"(已删除)",wikiUntracked:"以下文件未纳入撤销记录",wikiNoChanges:"Wiki 中的编辑和 pi 改动会显示在这里",wikiAskPi:"问 pi",wikiRewrite:"改写",wikiExplain:"解释",wikiAddLink:"加双链",wikiSearchHint:"搜索文档、代码和 PDF 内容…",wikiDocuments:"文档",wikiPdf:"PDF",wikiCode:"代码",wikiPage:"第 {page} 页",wikiNoResults:"没有找到结果",wikiSearchLimited:"结果有截断或部分文件无法搜索;PDF 最多搜索 8 个、每个 200 页。",wikiSearchKeys:"↑↓ 选择 ↵ 打开 ⌘/Ctrl ↵ 交给 pi Esc 关闭",wikiUnsavedHint:"先保存当前文件,再继续操作?",wikiDiscard:"放弃修改",wikiSaveContinue:"保存后继续",wikiSaveFirst:"请先保存或放弃当前草稿,再撤销文件改动。",wikiMissingLink:"找不到唯一对应文件:{path}",wikiDocumentsOnlyPrompt:"仅在用户明确要求修改时,将修改限制在此范围内的文档。代码文件默认只读,除非本条请求明确要求修改代码。",wikiSkipPrompt:"以上范围、引用与选区仅作为上下文,不代表用户要求分析或修改文档。请按用户本条消息的实际意图回复;问候或闲聊直接回应,不要因此读取、诊断或修改文件。只有用户明确要求修改时才编辑并保存,随后说明实际改动。",wikiRewritePrompt:"请改写选中内容,保持原意并保存。",wikiExplainPrompt:"请解释选中内容,不修改文件。",wikiLinkPrompt:"请为选中内容添加指向工作区已有文档的 [[双链]] 并保存,不要编造目标文件。",mcpArgs:"参数(JSON 数组)",mcpEnv:"环境变量(JSON 对象)",mcpHeaders:"HTTP headers(JSON 对象)",mcpProvider:"凭据服务商(仅全局)",mcpOauth:"OAuth 参数(JSON 对象,含 authServerMetadataUrl)",mcpEnabled:"启用",mcpExposure:"工具 exposure",mcpUpdateDraft:"更新配置草稿",mcpNew:"新建服务",mcpEdit:"编辑",nativeMcp:"MCP 与 Codemode",mcpScope:"配置范围",mcpGlobal:"全局",mcpProject:"当前项目",mcpExplanation:"原生 MCP 使用 Pi 配置与凭据。旧界面 MCP 桥仍使用应用 data-dir/mcp.json。",mcpUntrusted:"项目尚未信任,保存不会自动加载此配置。",mcpTrust:"信任当前项目",mcpPending:"等待当前任务结束后应用",mcpName:"服务名称",mcpCommand:"命令",mcpAdd:"加入配置草稿",mcpConfig:"MCP 配置 JSON",mcpJsonHelp:"JSON 可编辑 args、env、headers、auth.provider、oauth(含 authServerMetadataUrl)、enabled、exposure 及高级字段。•••••••• 保留原敏感值,替换为新值或删除字段以清除。删除 mcpServers 中的条目可移除服务。",mcpNameConflict:"名称为空或已存在",mcpRefresh:"刷新配置",mcpStatus:"官方连接状态",mcp_login:"登录",mcp_logout:"退出",mcp_reconnect:"重连",mcpTools:"可用工具",mcpConfigureRadius:"配置 Radius MCP",nonChatModelsPreserved:"此处仅编辑聊天模型。另有 {n} 个图片或分类模型,其配置会保留。",providerAuthChoose:"请选择",providerLogout:"退出账号",providerLogin:"登录账号",providerChatGPTLogin:"使用 ChatGPT 登录",providerAuthPending:"正在等待授权,请在浏览器中完成登录。",providerAuthSuccess:"登录成功,模型列表已更新。",providerAuthCancelled:"登录已取消。",providerAuthError:"登录失败。",providerAuthOpenBrowser:"打开授权页面",providerAuthDeviceCode:"授权码:",nodeConnectionTiming:"握手 {ms} ms · 已连接 {duration}",nodeRevealSource:"在本机定位配置",nodeSources:"节点来源",nodeSourceIntro:"连接已有的会话配置。在原工具中新增、修改节点,这里自动更新。",nodeDetect:"检测本机来源",nodeSyncKeep:"同步并保持更新",nodeImportOnce:"只导入一次",nodeChangePath:"选择其他路径",nodeSourcePath:"运行服务的机器上的配置路径",nodeSyncNow:"立即同步",nodeSyncPause:"暂停同步",nodeSyncResume:"恢复同步",nodeSyncInfo:"{n} 个节点 · {g} 个分组",nodeSyncTime:"上次同步:{time}",nodeSyncFields:"名称、分组、地址、端口、用户名及私钥路径",nodeSyncPassword:"暂不支持导入保存的密码,首次连接时补填",nodeSyncUnsupported:"跳板机、代理及其他不支持的选项会标记并阻止连接",nodeSearch:"搜索名称、地址",nodeMissingSecret:"缺密码",nodeSourceMissing:"来源已移除",nodeUnsupported:"暂不支持此配置",nodeFillSecret:"认证设置",nodeLocalAuthHint:"可切换密码或公钥认证。测试通过后保存在本机,不修改 Xshell 原配置,正常同步不会覆盖;来源的主机、用户或认证资料变化时重置。",nodeCredentialHint:"凭据单独保存,配置同步不会覆盖。Xshell 中修改密码后需在这里更新。",nodePersistSecret:"加密保存在运行服务的机器上",nodeGroupSecret:"同组且认证方式相同的节点使用此凭据",nodeGroupHint:"仅测试当前节点;同组其他节点在连接时验证。",nodeTestSave:"测试并保存",nodeTesting:"正在验证…",nodeCredentialsSaved:"凭据已验证,已应用到 {n} 个节点",nodeSourceReadonly:"来源字段只读,请在原工具中编辑",nodeSourceLocation:"来源文件",nodeLastConnected:"上次连接",nodeNever:"从未",nodeOpenTerminal:"打开终端",nodeBackList:"‹ 节点",nodeDetails:"节点详情",nodePolicy:"Agent 执行权限",nodePolicyReadonly:"只读自动 · 其余确认",nodePolicyConfirm:"每次执行需确认",nodePolicyAuto:"允许自动执行",nodePolicyOff:"停用 Agent",nodePolicyHint:"已识别的只读命令自动执行;写入、重启及无法确定的命令需确认。",nodeApproval:"需要确认",nodeAllow:"允许执行",nodeDeny:"不执行",nodeEditCommand:"改命令",nodeLocate:"定位 ↗",nodeRunOutput:"命令输出",nodeSendSelection:"发给 pi · {n} 行",nodeSelection:"终端选中 · {n} 行",nodeTerminalHint:"紫色标记为 pi 命令 · 选中输出可发给 pi",nodeCopy:"复制",nodeCopied:"已复制",nodeModel:"节点模型",nodeNoModel:"请先配置模型",nodeShowFiles:"文件",nodeCloseTab:"关闭终端",nodeAddSource:"添加来源",nodeNoSources:"未检测到默认来源,可手动指定 Xshell 会话目录或 SSH config 文件。",nodeWorkingHere:"在 {name} 上",nodeRunFailed:"执行失败",nodeSourceOpenHint:"复制路径,在 Xshell 或文本编辑器中打开原配置。",nodeQuoteRemove:"移除引用",currentFileLabel:"当前文件",currentFileUnsaved:"未保存",currentFileDraft:"当前文件 · 未保存草稿",currentFileUnavailable:"当前文件尚未就绪,请重新打开或移除标签",currentFileTooLarge:"当前文件快照超过 512 KiB,请缩减内容或移除标签",currentFileSaving:"当前文件正在保存,请稍候再发送",switchingProject:"正在同步项目…",retryProjectSwitch:"重试切换项目",directoryMissing:"目录已移动或删除",directoryDenied:"没有权限读取此目录",directoryNotFolder:"此路径已不是文件夹",directoryUnavailable:"暂时无法读取此目录",directoryChooseProject:"请重新选择项目目录,或恢复目录后刷新。",newWorkspaceFile:"新建文件",workspaceFilePath:"文件路径",workspaceFilePlaceholder:"例如 docs/笔记.md",createWorkspaceFile:"创建",refreshWorkspaceFiles:"刷新文件",cancel:"取消",ok:"确定",save:"保存",close:"关闭",widgetExpand:"点击放大查看完整输出",dragToResize:"拖拽调整宽度 · 双击复位",loading:"加载中…",connected:"已连接",connecting:"连接中…",reconnecting:"重连中…",language:"语言",langZh:"中文",langEn:"English",githubRepo:"GitHub 仓库(youweichen0208/pi-harness)",copy:"复制",viewSwitch:"视图切换",desktopWorkspace:"工作区",windowControls:"窗口操作",minimizeWindow:"最小化窗口",maximizeWindow:"最大化窗口",restoreWindow:"还原窗口",closeWindow:"关闭窗口(隐藏到托盘)",chat:"对话",terminal:"终端",nodes:"节点",nodeWorkbench:"SSH 节点",nodeAdd:"添加节点",nodeEdit:"编辑节点",nodeGroup:"分组",nodeName:"名称",nodeAddress:"地址",nodePort:"端口",nodeUsername:"用户名",nodeDefaultDir:"默认目录",nodeAuth:"认证方式",nodePassword:"密码",nodeKey:"公钥登录(私钥认证)",expandProjects:"展开项目栏",collapseProjects:"收起项目栏",nodePrivateKeyHint:"请选择运行 pi 的电脑上的 OpenSSH 私钥文件,不是 .pub 公钥。Xshell 密钥名称不能作为路径;可在 Xshell 用户密钥管理器中导出 OpenSSH 私钥。私钥口令可留空。",nodeAgentAuth:"SSH Agent",nodeKeyPath:"本机私钥路径",nodePassphrase:"私钥口令",nodeKeepSecret:"留空保留已存凭据",nodeImportLegacy:"导入 Remote-SSH 配置",nodeImportJson:"导入节点 JSON",nodeExport:"导出非机密资料",nodeEmpty:"选择或添加 SSH 节点",nodeAddHint:"添加节点,或导入已有 Remote-SSH 主机。",nodeConnected:"已连接",nodeDisconnected:"未连接",nodeConnect:"连接",nodeDisconnect:"断开",nodeTab:"终端 {n}",nodeTabClosed:"断开",nodeTabBusy:"Agent 执行中",nodeOpenHint:"连接后打开终端。Agent 将使用当前选中的终端。",nodeBrowse:"浏览文件",nodeChat:"节点 Agent",nodeChatPlaceholder:"向当前节点的 Agent 提问…",nodeSelectTerminal:"请先打开终端",nodeInterrupt:"中断终端",nodeStopAgent:"停止 Agent",nodeSend:"发送",nodeAgentWaiting:"pi 正在思考,等待响应…",nodeAgentExecuting:"pi 正在执行命令…",nodeAgentApproval:"等待你确认操作…",nodeDelete:"删除",nodeForgetHostKey:"清除主机密钥信任",nodeForgetHostKeyConfirm:"确认已核实 {name} 的新主机密钥?清除后下次连接会重新显示指纹。",nodeTrust:`首次连接 {name} ({host})
16
+ 主机密钥指纹:{fingerprint}
17
+ 确认信任?`,nodeDeleteConfirm:"删除 {name}?",nodeImported:"已导入 {n} 台节点(凭据请手动设置)",nodeInvalidJson:"节点 JSON 无效",selectModel:"选择模型",availableModels:"可用模型",noModels:"暂无可用模型(请先配置 API 密钥)",reasoning:"推理",vision:"识图",refreshModels:"刷新模型列表(保留手填,合并新增)",manageModels:"⚙ 管理模型(新增 / 修改)",manageModelsTitle:"管理模型",thinkingLevel:"思考强度",steerSend:"插话发送",activityReply:"正在生成回复…",activityTool:"正在运行 {name}…",activityReading:"正在读取 {name}…",waitingCommand:"等待命令完成…",onlyChanged:"只看改动",changedCount:"改动 {n}",yesterday:"昨天",noChangedFiles:"没有改动文件",goalEventSet:"目标已设定:{text}",cwdSwitchEvent:"工作目录切换到 {path}",goalEventComplete:"目标已完成:{text}",goalReviewDetails:"查看审查详情",thinkingDuration:"{n} 秒",thinkingUnrecorded:"耗时未记录",thinking:"思考",thinkingChip:"思考:{level}",sound:"声音",theme:"主题",themeDefault:"深色(默认)",newChat:"新对话",more:"更多",newChatTip:"新建对话(每个浏览器独立保存会话)","thinking.off":"关闭","thinking.minimal":"极简","thinking.low":"低","thinking.medium":"中","thinking.high":"高","thinking.xhigh":"极高","thinking.max":"最大",thinkingUnsupported:"当前模型不支持该级别,已按模型能力就近生效",context:"上下文",contextUsage:"上下文用量",usageContextTitle:"上下文窗口",usageCacheTitle:"缓存命中",usageCacheShort:"缓存",taskCurrentRound:"本轮",cumulativeCost:"累计成本",sessionMessages:"会话消息数",messages:"消息",pluginStatus:"插件状态",working:"工作中",queued:"排队",enterPath:"输入路径,Enter 切换",cwdTip:"工作目录:{path}(点击切换)",folderRef:"文件夹引用:{path}",refOnly:"仅引用:{path}",attachContent:"附加内容:{path}",attachLines:"附加选中行:{path}(第 {start}-{end} 行)",attachImage:"图片:{name}",attachFile:"文件:{name}",removeAttachment:"移除附件",attachHint:"将随下一条消息发送",uploadFile:"添加文件(图片/文本/任意文件,也可直接拖入或粘贴截图)",dropHereToAttach:"松开以添加文件",imageNotSupported:"当前模型不支持识图:图片将交给视觉桥转写(若未配置视觉模型则可能被忽略)",imageLoadFailed:"图片读取失败:{name}",fileLoadFailed:"文件读取失败:{name}",fileTooLarge:"文件过大已跳过(>{size}MB):{name}",foldersNotSupported:"不支持直接拖入文件夹,请展开后选择文件",placeholderStreaming:"继续输入,当前步骤结束后发送",stopTask:"停止任务",taskCommitting:"提交中",taskCompletionCriteria:"完成标准",taskOutlineChanged:"计划有变",taskOutlineAdded:"新增第 {n} 步「{title}」",taskOutlineRemoved:"移除「{title}」",taskOutlineUpdated:"调整第 {n} 步「{title}」",taskNoStepDetails:"尚无执行记录",otherDirectories:"其余 {n} 个目录",bashStatusFiles:"{n} 个文件",bashStatusAdded:"{n} 新增",bashStatusModified:"{n} 修改",bashStatusDeleted:"{n} 删除",bashStatusConflicts:"{n} 冲突",placeholderIdle:"给 pi 发送消息 — Enter 发送,/ 查看命令",placeholderConnecting:"正在连接服务器…",stopAgent:"停止智能体",stopQueuedAfterReconnect:"连接已中断;重连后将尝试停止当前对话。",stopUnavailable:"当前无法发送停止请求,请等待重新连接。",workDisconnected:"连接已中断,正在重连;运行状态待确认。",stop:"停止",bgTasks:"后台任务",bgTasksTip:"AI 在后台启动的服务(npm run dev & 等)——可逐个停止或全部关闭,对话结束后仍保留",bgTasksEmpty:"暂无后台任务",bgTasksDesc:"AI 运行中启动并仍在监听的进程(按监听端口检测)",bgTaskPort:"端口",bgTaskPid:"PID",bgTaskSince:"启动",bgTaskStop:"停止",bgTaskStopAll:"全部关闭",bgTaskRefresh:"刷新",bgTaskJustNow:"刚刚",bgTaskMinutes:"{n} 分钟前",bgTaskHours:"{n} 小时前",bgTaskDays:"{n} 天前",stopBash:"停止",stopBashTip:"停止正在运行的 bash 命令(对话继续)",supplement:"排队",supplementTip:"加入队列:AI 回答完全结束后才发送(不打断)",commandAttempts:"试了 {n} 次",queueSteerTag:"插话",pendingMessages:"{n} 条待发",recallQueueEdit:"全部撤回编辑",deliverySteerHint:"当前这一步结束后发送",deliveryFollowHint:"本轮结束后发送",placeholderStreamingModes:"继续输入,↵ {primary} · ⌥↵ {alternate}",queueFollowTag:"排队",sendTip:"发送(Enter)",slashCommands:"命令",slashMenuHint:"↑↓ 选择 · Enter/Tab 补全",slashHelpTitle:"pi 命令",slashHelpHint:"输入 / 随时打开命令列表",slashLoading:"命令列表加载中…(连接服务器后可用)",slashBuiltin:"内置",slashExtension:"扩展",slashPrompt:"模板",slashSkill:"技能",slashPlugin:"插件",slashCopied:"已复制上一条助手回复",slashCopyFailed:"复制失败,请手动复制",slashCopyEmpty:"还没有可复制的助手回复",mermaidRendering:"正在渲染图表…",mermaidRenderFailed:"图表渲染失败,已显示原始代码",recentProjects:"最近项目",workspaceFiles:"文件",showHiddenFiles:"显示隐藏项",taskProgress:"任务进度",taskProgressHeading:"进度",taskOutputsHeading:"输出",taskProgressEmpty:"较长任务的进度会显示在此处。",taskOutputsEmpty:"查看并打开在此任务期间创建或修改的文件。",taskPaused:"已暂停 · 等待继续",taskFailed:"任务失败",taskCompletedCount:"已完成 {n}",taskRunningCount:"进行中 {n}",taskSteps:"步",taskCompletedHidden:"已完成 {n} 步 · 展开",taskJumpToChat:"在对话中定位",builtinTaskList:"任务清单",componentUpdates:"更新",componentNewVersion:"有新版本",componentCurrent:"已是最新稳定版",componentPinned:"版本已固定,请手动调整安装来源",componentManual:"请按安装来源手动维护",componentUnknown:"无法确定已安装版本",componentCheckFailed:"检查失败,可重试",componentApp:"pi-harness 应用",componentDesktopUnsupported:"开发运行不支持自动安装,请使用已安装的桌面版。",componentAppHint:"检查并下载新版本,完成后可重启安装。",componentWebUpdateHint:"在终端更新全局 npm 包;完成后运行 pi-harness server restart 重启服务。",componentDownloading:"正在下载:{n}%",componentRestartInstall:"重启并安装",componentAutoUpdate:"自动更新",componentLocal:"本地文件扩展,请修改源文件后重新加载。",componentChecking:"正在检查…",componentCheck:"检查更新",componentUpdateIntro:"查看运行中的 pi Agent 与扩展安装版本。检查不会自动安装;用户扩展更新后需重启应用。",componentOffline:"连接恢复后可检查更新。",componentInstalling:"正在更新扩展,请等待完成…",componentRestart:"更新已安装,请重启应用以加载新版本。",componentBundled:"内置",componentBundledHint:"随应用版本升级,上游新版本不一定已被当前应用采用。",componentProject:"当前项目",componentUser:"用户安装",componentInstalled:"已安装",componentInstall:"更新扩展",taskTodoUpdate:"任务清单更新",planUnassignedRecords:"本轮执行记录 · 未归入计划",planEnabled:"原生计划工具(服务全局)",planEnabledHint:"默认开启,保留已保存的选择;所有客户端共用。运行中的会话在任务结束后应用。",planPending:"等待会话空闲或恢复可写后应用",planConflict:"当前会话存在第三方同名工具,开关不会修改它。",planMissing:"当前会话未加载原生计划扩展",planReplaced:"计划 {id}(版本 {revision})已被新计划替换并取消",planStatusChanged:"计划状态:{status}",planRecorded:"计划已记录",planActive:"未结束",planPrevious:"此前未完成计划",todoCounts:"{total} 项 · 已完成 {completed}",todoCreated:"已建立",todoPending:"待执行",todoRemoved:"已移除",todoView:"查看",todoChanges:"清单更新:{changes}",todoChangeSeparator:";",todoCleared:"任务清单已清空",todoItemAdded:"新增第 {n} 项",todoItemUpdated:"第 {n} 项已修改",todoItemPending:"第 {n} 项待执行",todoItemStarted:"第 {n} 项开始",todoItemCompleted:"第 {n} 项完成",todoItemDeleted:"第 {n} 项已移除",taskWaitingContinue:"等待继续",taskPlanSource:"任务清单",taskPlanSourceHint:"按 agent 创建的清单跟踪步骤",taskObservedSource:"执行记录 · 未创建计划",taskObservedSourceHint:"由实际工具调用归纳,不代表 agent 已创建任务清单",taskBlockedBy:"等待步骤 {steps} 完成",taskCancelled:"已停止",taskLongTool:"命令运行中",taskStepSilent:"暂时没有新数据,查看输入框上方的操作",taskPhases:"个阶段",taskDuration:"用时",taskResult:"结果",taskCommit:"提交",taskTests:"测试",taskChanges:"改动",taskPassed:"通过",taskFiles:"个文件",taskViewChanges:"查看改动",taskFinalReply:"定位到最终回复",taskProcess:"过程",taskOnlyResult:"只看结果",taskShowProcess:"展开过程",taskRawSteps:"原始 {n} 段",taskShowRaw:"查看原始 {n} 段",taskHideRaw:"收起原始段落",taskCopyMarkdown:"复制为 Markdown",taskArtifactRead:"读取",taskArtifactWrite:"写入",taskArtifactEdit:"修改",taskArtifactRun:"运行",taskLines:"行",taskExplicitPlan:"pi 计划",taskPlanSteps:"步",taskPlanPosition:"第 {current} / {total} 步",taskPlanChanged:"计划已调整",taskPlanAdded:"新增",taskPlanCard:"计划",taskUnderSecond:"<1 秒",taskReadCount:"读取 {n}",taskWriteCount:"写入 {n}",taskEditCount:"修改 {n}",taskCommandCount:"{n} 条命令",changeEdit:"编辑",changeWrite:"写入",changeOpen:"打开",changeRawArgs:"原始参数",changeRawOutput:"原始输出",changeAtLine:"第 {n} 行",changeWrittenLines:"写入 {n} 行",changeOriginal:"想替换的原文",changeAttemptedWrite:"尝试写入的内容",changeFailed:"修改失败",changeNoOriginal:"没有可显示的原文",changeNoDiff:"没有可显示的差异",changeReplacement:"替换内容(未返回文件差异)",changeRetried:"已重试",modelSilent:"{duration} 未收到模型响应",modelSilentShort:"模型未响应",toolSilentShort:"工具运行中 · 暂无新输出",placeholderModelSilent:"模型暂时没有响应,可停止、重试或继续等待…",placeholderToolSilent:"命令或工具仍在运行,输入的消息会排队…",toolSilent:"命令或工具已运行 {duration},暂时没有新输出",retrySilentUnavailable:"本轮已执行工具或包含附件,为避免重复执行,请停止后检查并手动重试",continueWaiting:"继续等待",actions:"操作",retry:"重试",writeVerb:"写入",expandRemainingLines:"展开其余 {n} 行",lines:"行",fileUsed:"涉及",thinkingDepthTip:"思考深度:越深越慢、越耗 token",readFiles:"读取 {n} 个文件",readVerb:"读取",modelReadOnly:"文件内容 · 仅供模型读取",readRaw:"原文",skillLabel:"技能",bashSteps:"步骤",bashRaw:"原始",bashRunning:"运行中",bashPartial:"部分失败 · {ok}/{total} 步成功",bashFailed:"失败",bashErrorCount:"{n} 个错误",bashExpandCommand:"展开完整命令 · {n} 步",bashExpandFullCommand:"展开完整命令",bashLikelyErrorLines:"疑似错误 {n} 行",bashHiddenLines:"省略 {n} 行",bashNoMatch:"无匹配",bashSkipped:"未执行",bashShowRaw:"查看原始输出",grepSearch:"搜索",grepInPath:"在 {path}",grepMatches:"{n} 处匹配",allDone:"全部完成",expandAllLines:"展开全部 · {n} 行",timeGapAt:"时间间隔,{time}",notGitRepoShort:"非 Git 仓库",toolWrap:"换行",copied:"已复制",toolLineCount:"{n} 行",toolRelativeTo:"相对于 {path}",toolMoreLines:"展开其余 {n} 行",workspaceBranch:"分支",workspacePath:"路径",workspaceProjects:"项目",composerPlaceholder:"给 pi 发送消息…",thinkingStandard:"标准",thinkingDeep:"深度",thinkingMinimalDescription:"几乎不思考,最快",thinkingStandardDescription:"速度和质量平衡",thinkingDeepDescription:"充分思考,适合复杂任务",workspaceModified:"有未提交改动",workspaceChanges:"{n} 项最近改动",runningConversations:"运行的对话",historySessions:"历史对话",openHistory:"历史对话",openFiles:"文件列表",streaming:"进行中…",noHistory:"还没有历史对话",current:"当前",messageCount:"{n} 条消息",tuiTip:"pi 终端(TUI)中的对话",deleteProject:"从最近项目移出",deleteProjectConfirm:"确认移出",deleteSession:"删除该对话记录(不可恢复)",deleteSessionConfirm:"确认删除",confirm:"确认",expandCode:"展开完整内容",collapseCode:"收起",zoomCode:"放大查看",closeZoom:"关闭",renameSession:"重命名该对话",renameSessionPlaceholder:"对话名称(留空则显示首条提问)",openFolder:"打开文件夹…",openFolderPlaceholder:"或直接粘贴绝对路径",openThisFolder:"打开当前文件夹",openTypedPath:"打开输入的路径",parentFolder:"上一级",home:"主目录",noSubfolders:"这里没有子文件夹",listTruncated:"目录过多,列表已截断",emptyChat:"空对话",editReask:"编辑重问",editReaskTip:"修改此问题,并从这里重新提问(会新建一个分支对话,原对话保留)",reaskFromHere:"从此处重新提问",editPlaceholder:"修改问题内容…",editHint:"⌘/Ctrl+Enter 提交 · Esc 取消",editAttachmentHint:"原附件已保留,可粘贴/拖入新图片或文件 · ⌘/Ctrl+Enter 提交 · Esc 取消",expandMsg:"展开",collapseMsg:"收起",toolCalls:"工具调用",bashRuns:"终端运行",images:"图片",update:"更新",updateTip:"检查并更新 pi-harness",currentVersion:"当前版本",latestVersion:"最新版本",checkingUpdate:"检查中…",checkUpdate:"检查更新",upToDate:"已是最新版本",updateAvailable:"发现新版本 v{version}",updateJustPublished:"v{version} 刚刚发布,npm 缓存可能尚未同步——若未检测到新版本,请稍后重新检查",updateNow:"在终端中更新",updateTabTitle:"更新 pi-harness",updateTerminalHint:"点击后会在可见终端中运行 npm i -g @youweichen/pi-harness@latest;完成后重启服务生效(pi-harness server restart)。",rootDir:"根目录",noFiles:"暂无文件",filesTruncated:"目录过大,列表已截断,仅显示前 2000 项",linkFolderTip:"链接文件夹路径到对话",attachInlineTip:"附加内容到对话",referenceTip:"仅引用路径(AI 按需读取)",richSourceBlock:"此段保留原文,可切换源码编辑",richFormatting:"文档格式",richEditMarkdown:"编辑 Markdown 文档",reloadRunning:"正在重新加载…",reloadDone:"已重新加载",reloadPartial:"已重新加载,{count} 项加载出错",reloadCounts:"扩展 {extensions} · 技能 {skills} · 提示模板 {prompts}",reloadDetails:"查看错误详情",reloadGeneralError:"重新加载",reloadExtensionList:"扩展:{names}",reloadSkillList:"技能:{names}",reloadPromptList:"提示模板:{names}",richFormatToolbar:"文档格式",richBold:"粗体",richItalic:"斜体",richHeading:"标题",richParagraph:"正文",richList:"列表",richOrderedList:"编号",richQuote:"引用",richUndo:"撤销",richRedo:"重做",richTable:"插入表格",dbViewer:"数据库预览",dbReadOnly:"只读",dbRefresh:"刷新",dbTable:"表 / 视图",dbView:"视图",dbRows:"表数据",dbNoTables:"数据库中没有可查看的表。",dbNoRows:"这张表暂无数据。",dbPrevious:"上一页",dbNext:"下一页",dbRowRange:"第 {start}–{end} 行",dbSchema:"查看表结构",dbCellLimit:"每页最多 50 行;长文本显示前 256 个字符,BLOB 显示字节数。",dbStructureLimited:"仅展示前 500 张表及每表前 64 个字段。",dbLoadFailed:"无法读取 SQLite 数据库:",dbUnavailable:"连接或工作区暂不可用。",richColumn:"列",richTableTools:"表格操作",richAddRow:"下方加行",richAddColumn:"右侧加列",richRemoveRow:"删除当前行",richRemoveColumn:"删除当前列",fileMoreActions:"更多文件操作",richCodeBlock:"代码块",richHighlightBlock:"高亮块",richTextHighlight:"背景标记",richHighlight_yellow:"黄色背景",richHighlight_green:"绿色背景",richHighlight_blue:"蓝色背景",richHighlight_pink:"粉色背景",richHighlight_purple:"紫色背景",richHighlightClear:"清除背景标记",richCodeLanguage:"代码语言",richPlainText:"纯文本",richImageUploading:"正在插入图片…",richImageFailed:"图片插入失败,请确认连接和文件状态后重新粘贴。",richImageTooLarge:"图片不能超过 5 MB。",richDivider:"分隔线",richTaskList:"任务列表",richInsertMenu:"插入元素",richTextGroup:"文字格式",richBlocksGroup:"基础元素",richNoElements:"没有匹配的元素",backToFiles:"返回文件列表",fileUnsaved:"未保存",fileSaving:"保存中",fileSaved:"已保存",fileViewMode:"文件视图",fileViewPreview:"预览",fileViewSource:"源码",fileViewChanges:"查看改动",fileChangesCount:"改动 {n}",fileEditMode:"编辑模式",fileReadOnly:"只读",fileEditShort:"编辑",fileReference:"引用",fileExternalChanged:"pi 修改了此文件",fileCompare:"对比",fileNoChanges:"没有可显示的改动",fileLocalDraft:"未保存草稿",fileDiskVersion:"磁盘最新版本",quoteSelection:"引用选中内容 @{name}:{start}-{end}",fileSaveFailed:"保存失败",fileOffline:"连接中断或请求超时,草稿已保留。请重试。",fileReload:"重新加载",fileOverwrite:"覆盖磁盘文件",fileOverwriteConfirm:"磁盘文件已改变,确定用当前草稿覆盖?",fileLeavePrompt:"当前文件有未保存的修改。",fileSaveContinue:"保存后继续",fileDiscard:"放弃修改",previewFile:"预览",downloadFile:"下载文件",downloadFailed:"下载失败:{error}",protocolMismatch:"页面版本与服务器不一致(应用刚更新过),请刷新页面以恢复全部功能。",selectLinesHint:"点击选择行;拖拽或 Shift+点击选择范围",enableWrap:"开启自动换行",disableWrap:"关闭自动换行",selectedRange:"已选 {n} 行(第 {start}-{end} 行)",fileLines:"{n} 行",selectAll:"全选",clearSelection:"清除",addToChat:"添加到对话",addedToChat:"已添加",previewTruncated:"⚠ 文件过大,仅预览前 512KB",previewLinesTruncated:"… 文件行数过多,仅显示前 {n} 行",binaryFile:"🔣 二进制文件,已显示前 4KB 十六进制",binaryHexTruncated:"(文件更大,可下载完整文件)",previewNotSupported:"该类型文件不支持预览(仅图片 / 视频 / 文本)",emptyFile:"(空文件)",editFile:"编辑文件",exitEditFile:"退出编辑",saveFile:"保存文件",discardFileChanges:"放弃未保存的修改?",fileEditTruncated:"文件过大,预览不完整,无法编辑",showMarkdownSource:"显示 Markdown 原文",showMarkdownPreview:"显示 Markdown 预览",fullscreen:"全屏",exitFullscreen:"退出全屏",zoomIn:"放大字号",zoomOut:"缩小字号",resetZoom:"重置缩放",pluginRequest:"插件请求",noOptions:"(无选项)",inputPlaceholder:"输入内容",soundHeader:"声音提示",enableSound:"启用声音",preview:"试听",volume:"音量","sound.question":"问卷弹出","sound.question.desc":"ask_user_question 出现时","sound.done":"回复结束","sound.done.desc":"智能体完成一轮回答时","sound.start":"回复开始","sound.start.desc":"智能体开始新一轮时","sound.error":"出错","sound.error.desc":"出现错误提示时",setupTitle:"未检测到 pi agent 配置",setupDesc:"pi-harness 需要 pi 的配置目录(~/.pi/agent)和至少一个 API 密钥才能运行智能体。pi 内置了 openai、anthropic、deepseek 等服务商——选一个填密钥即可,全程无需打开终端。",installFailed:"✖ pi agent 安装失败:",retryInstall:"重试安装",skip:"跳过",installDone:"✅ pi agent CLI 已安装。选择服务商并填入 API 密钥即可开始对话:",cliReadyHint:"✅ 本地已检测到 pi agent,选择服务商并填入 API 密钥即可开始对话:",provider:"服务商",configured:"已配置",providerKeyReady:"该服务商已配置密钥,可直接使用或更换新密钥。",apiKey:"API 密钥",saving:"保存中…",saveAndStart:"保存并开始使用",recheck:"重新检测",installing:"正在安装 pi agent CLI…",autoInstall:"自动安装 pi agent",attachment:"附件",plugin:"插件",unknown:"未知",thinkingWait:"正在思考",exitCode:"退出码 {code}",cancelled:"已取消",truncated:"… 内容过长,当前视图已截断",outputTruncated:"… 输出过长,当前视图已截断",refOnlyShort:"仅引用",folderRefShort:"文件夹 · 仅引用",inlineLines:"内联 · {n} 行",inlineLinesRange:"行 {start}-{end}",image:"🖼 图片",bridgedVision:"👁 已转写",bridgedVisionDetail:"图片已由视觉桥转写(当前模型不支持识图)",folderNotExpanded:"文件夹,未展开内容 —— 智能体会按需浏览目录",fileNotExpanded:"文件较大({size}),未展开内容 —— 智能体会按需读取","role.user":"你","role.assistant":"pi","role.tool":"工具","role.bash":"终端","role.branch":"分支摘要","role.compaction":"上下文已压缩",welcomeTitle:"pi 编码智能体",welcomeSub:"检查、编辑、运行 —— 随时待命",directory:"目录",clickToFill:"点击填入输入框",sending:"发送中",backToBottom:"回到底部",questionNavTitle:"问题列表",questionMarkerGroup:"附近 {n} 条消息",searchPlaceholder:"在对话中搜索…",searchNoResults:"无结果",searchModels:"搜索模型…",noModelMatches:"无匹配模型",searchGlobal:"搜索",searchGlobalTip:"全局搜索:对话 / 项目 / 文件(Ctrl+K)",gsPlaceholder:"搜索项目、历史对话、工作区文件…",gsHint:"输入关键词:同时搜索历史对话、最近项目与当前项目的文件名",gsSessions:"对话",gsProjects:"项目",gsFiles:"文件",gsNoResults:"无匹配结果",gsSearching:"正在搜索文件…",gsTruncated:"匹配过多,仅显示部分结果",gsCurrentProject:"当前",gsOpenPreview:"打开文件预览",gsNavigate:"选择",gsOpen:"打开",gsCloseHint:"关闭",bgTaskCommand:"命令行",searchPrev:"上一个(Shift+Enter)",searchNext:"下一个(Enter)",searchClose:"关闭(Esc)",questionNavTip:"本对话的全部问题,悬浮展开,点击跳转","ex.understand":"了解这个项目","ex.understand.prompt":"介绍一下这个项目:整体结构、主要模块和如何运行?","ex.debug":"排查一个问题","ex.debug.prompt":"帮我排查一个 bug,请先说明问题现象,我会补充细节。","ex.test":"编写测试","ex.test.prompt":"为项目的核心模块编写单元测试。","ex.review":"代码审查","ex.review.prompt":"审查最近改动的代码,指出潜在问题和改进建议。",error:"出错",done:"完成",running:"执行中…",toolQueued:"排队中",copyArgs:"复制参数",errorOutput:"错误输出",nestedToolCalls:"内部工具调用 · {n}",nestedToolCallsIncomplete:"部分调用记录或参数未完整保存。",recoveryCompacting:"正在压缩",recallQueue:"撤回全部待发消息",recallQueueShort:"撤回全部待发",treeVerifying:"正在校验会话文件…",compactionCompleted:"压缩完成",compactionAborted:"压缩已取消",compactionFailed:"压缩失败",compactionManual:"手动压缩",compactionThreshold:"上下文接近上限",compactionOverflow:"上下文超限",recoveryWaiting:"等待原生重试",recoveryRunning:"正在原生重试",recoverySummaryWaiting:"等待摘要重试",recoverySummaryRunning:"正在重试摘要",conversationRunSettings:"当前对话运行设置",conversationAutoCompaction:"自动压缩",conversationAutoRetry:"SDK 自动重试",commandAttachmentsRetained:"命令已执行,附件未发送,已保留在输入框。",toolOutputAuth:"下载认证失败,请重新连接。",toolOutputDenied:"无权访问此输出。",toolOutputError:"下载失败,请稍后重试。",toolOutputText:"完整文本",toolOutputDownload:"下载完整输出",toolOutputUnavailable:"完整输出不可用,文件可能已清理",toolResultImage:"工具返回的图片",output:"输出",waitingOutput:"等待输出…",toolDoneWaitingModel:"完成",waitUnderstanding:"Understanding your question",waitResults:"Reading command results",waitFile:"Reading files",waitThinking:"Thinking",waitTests:"Waiting for test results",waitBuild:"Waiting for build results",waitSteer:"Processing your direction",waitSeconds:"{n} sec",waitMinutes:"{m} min {s} sec",waitStop:"Stop",thinkingNow:"思考中",thinkingPreview:"思考:{preview}",leakedThinking:"模型附加内容",toolUnexecutedTitle:"工具调用未执行",toolUnexecutedAttempts:"自动提醒 {n} 次后停止",toolUnexecutedHint:"{model} 把工具指令写成了正文,自动提醒后仍没有调用工具,任务停在这里。前面的结果都已保留。",toolUnexecutedInline:"工具指令写成了正文,没有执行",toolAutoReminded:"已自动提醒",toolReminderEvent:"已自动提醒 pi 用工具调用重新发起",toolRecoverySwitch:"换个模型",toolRecoveryRaw:"查看原始输出",toolRecoveryRawHide:"收起原始输出",toolRecoveryFirst:"第 1 次",toolRecoveryAfterReminder:"自动提醒后",toolRecoveryNoCall:"没有工具调用",taskInterruptedHint:"工具调用未执行。在对话里点「重新发送」继续。",taskInterruptedTitle:"已中断",unexecutedToolHint:"{model} 将工具指令作为正文返回,未形成原生工具调用。前面的结果已保留。",unexecutedToolOriginal:"查看原始输出",toolStoppedTitle:"模型没有执行工具就结束了",toolStoppedHint:"已自动提醒 {model} 用工具调用继续,但它仍未调用任何工具,任务停在这里。可以重新发送,或换个模型继续。",toolRecoveryResend:"重新发送",toolRecoveryFailed:"未能确认重发请求,请检查连接与当前模型后重试。",toolRecoveryInterrupted:"中断",leakedThinkingHint:"正文中检测到思考标记,相关内容已折叠;不代表应用报错或数据泄露。点击查看原文。",commands:"命令",newCommand:"新建命令",newTerminal:"新建终端",name:"名称",command:"命令",cwdHint:"(${pwd} = 当前工作目录)",noCommands:"还没有命令,点 + 添加一个",clickToRun:"点击运行",edit:"编辑",delete:"删除",confirmQ:"确认?",builtinTerminal:"内置终端",termEmptySub:"点击左侧命令运行,或点右侧 + 新建终端",noTerminal:"暂无终端",exited:"(已退出{code})",closeTerminal:"关闭终端",rerun:"重新读取 .pi/commands.json",terminalTitle:"终端 {n}",exampleName:"例如:启动开发服务器",exampleCommand:"例如:npm run dev",scmTab:"Git",scmTitle:"源代码管理",scmRefreshTip:"重新查询 Git 状态与差异",scmCurrentBranch:"当前分支",scmUpstreamGone:"上游已删除",scmAheadBehind:"↑{ahead} ↓{behind}",scmDetached:"分离 HEAD",scmSelectBranch:"选择分支…",scmRemoteBranches:"远程分支",scmStageTip:"暂存 {path}",scmUnstageTip:"取消暂存 {path}",scmSwitch:"切换",scmSwitchBranch:"切换分支",scmSwitchBranchTip:"在终端中执行 git checkout {branch}",scmPush:"推送",scmPushTip:"在终端中执行 git push",scmPull:"拉取",scmPullTip:"在终端中执行 git pull",scmCommit:"提交",scmCommitTip:'在终端中执行 git add -A && git commit -m "…"(提交全部更改,含未跟踪)',scmCommitPlaceholder:"输入提交信息…",scmChanges:"更改",scmHistory:"提交树",scmCommitDetail:"提交详情",scmSelectCommitHint:"点击左侧提交查看详情",scmNoHistory:"暂无提交记录",scmNoChanges:"工作区干净,没有更改",scmNotGitRepo:"当前目录不是 Git 仓库",scmLoading:"查询中…",scmConnecting:"等待连接…",scmDiff:"差异",scmSelectFileHint:"点击左侧文件查看差异",scmNoDiff:"(无差异)",scmStaged:"已暂存",scmUnstaged:"未暂存",scmStagedUnstaged:"已暂存 + 未暂存",scmUntracked:"未跟踪",scmUntrackedBadge:"u",scmUntrackedBinary:"二进制文件无法在此预览",scmUntrackedDirectory:"目录无法在此预览,请选择其中的文件",scmEmptyFile:"空文件",scmPreviewTruncated:"仅显示前 512 KB",scmQueryFailed:"Git 查询失败:{error}",scmTooManyFailures:"Git 查询连续失败,请点击刷新重试",scmRunsInTerminal:"提交 / 切换分支 / 推送 / 拉取在终端中执行",scmViewTerminal:"去终端",editProvider:"编辑服务商",builtinProviders:"内置服务商",hintKeyOnly:"配置 API 密钥或登录支持的账号",configuredBadge:"✓ 已配置",keyReady:"密钥已就绪",replaceKey:"更换密钥",replaceKeyTitle:"替换已保存的密钥",clearKey:"清空",clearKeyTitle:"清除该服务商保存在 auth.json 的密钥,回到未配置状态(环境变量来源的无法在此清除)",clearKeyConfirm:"清空 {id} 已保存的密钥?其模型将从列表消失,直到重新配置。",cloneProvider:"复制为自定义",cloning:"复制中",cloneProviderTitle:"复制该内置供应商(baseUrl + 模型列表)为自定义供应商,填入另一个 API 密钥即可双 key 并存",pasteKey:"粘贴 API 密钥…",savingKey:"保存中",saveKey:"保存密钥",customProviders:"自定义服务商",customDesc:"用于 Ollama / vLLM / 兼容 OpenAI 的代理等,写入 pi 的 models.json,保存后热重载、立即生效。",noCustomProviders:"还没有自定义服务商",modelsCount:"{n} 个模型",addProvider:"新增服务商",providerId:"服务商 ID",providerIdHint:"(必填,如 ollama / my-proxy)",displayName:"显示名",displayNamePh:"我的代理",apiType:"API 类型",baseUrlHint:"(OpenAI 兼容端点)",apiKeyHint:"sk-…(留空保留已有密钥)",authHeader:"自动添加 Authorization 请求头",modelsTitle:"模型",modelIdReq:"模型 ID(必填)",text:"文本",textImage:"文本+图片",contextWindow:"上下文",maxOutput:"最大输出",removeModel:"移除模型",addModel:"添加模型",deleteProviderConfirm:"删除服务商 {id} 及其 {n} 个模型?",fetchModels:"自动获取模型列表",fetchModelsHint:"从 baseUrl 的 /models 接口自动拉取模型 ID(服务端请求,不受 CORS 限制)",fetchingModels:"获取中…",fetchModelsOk:"已获取 {n} 个模型",fetchModelsEmpty:"接口未返回任何模型",fetchModelsErr:"获取失败:{msg}",fetchModelsNeedBaseUrl:"请先填写 baseUrl 再获取",goalBarTitle:"目标",goalWizardCard:"目标调研",settings:"设置",nativeContextOnly:"使用 pi 原生上下文,WebUI 不追加提示词或注册自定义代理工具。",nativeResourcesManaged:"技能和扩展由 pi 原生配置管理,这里仅展示已加载的资源。",settingsTitle:"设置",allSettings:"所有设置",quickActions:"快捷操作",settingsAppearance:"外观",settingsCodeTheme:"代码文件配色",codeThemeLight:"浅色",codeThemeDark:"深色",codeThemeSystem:"跟随系统",settingsDesc:"修改立即生效:系统提示词、技能与插件开关会重建当前会话;审查提示词与审查技能只影响后续目标审查(回复进行中则主会话变更自动延迟)。",settingsSystemPrompt:"系统提示词",promptModeAppend:"追加",promptModeReplace:"替换",promptAppendHint:"追加模式:自定义内容拼接到默认系统提示词末尾(推荐,保留默认行为约束)。",promptReplaceHint:"替换模式:完全用自定义内容替换系统提示词(项目上下文与技能段仍会自动附加)。切换后输入框会显示原本的默认提示词,可直接修改;不改动失焦则仍使用默认。",promptPlaceholder:"输入自定义系统提示词…(失焦后自动应用)",settingsViewPrompt:"查看当前完整提示词",settingsViewPromptHint:"当前会话实际生效的完整系统提示词(含自定义追加/替换内容、项目上下文、技能说明与工具引导),只读。",settingsViewPromptEmpty:"会话尚未就绪,暂无系统提示词。",settingsSkills:"技能",settingsReview:"目标审查",settingsReviewDesc:"为独立的目标审查会话配置额外提示词和技能;不会改变主会话设置。",settingsReviewSkills:"审查可用技能",reviewPromptPlaceholder:"输入审查自定义提示词…(失焦后自动应用)",reviewPromptHint:"这些内容会追加到审查任务中;审查仍会强制要求输出 pass/fail JSON。技能开关仅对审查生效。",settingsVisionBridge:"视觉桥",settingsVisionBridgeDesc:"当前模型不支持识图时,把图片交给已配置的视觉模型转写为文字证据,再让模型回答",settingsTerminalTools:"终端工具",settingsTerminalToolsDesc:"让 AI 在交互式程序(REPL/vim)、长驻服务、需要持续观察输出或你要求在可见终端操作时,使用内置终端;普通命令仍走一次性 bash 工具",settingsMessageDisplay:"消息显示",thinkingWrap:"完整显示思考",thinkingWrapDesc:"开启:思考内容始终完整展开并自动换行(流式推理过程也实时可见);关闭:折叠成一行摘要,流式中一行实时显示最新文本",toolsWrap:"完整显示工具",toolsWrapDesc:"开启:工具调用始终完整展开显示参数和输出;关闭:默认折叠,点击展开",uninstallExt:"卸载",uninstallConfirm:"确认卸载?",uninstallConfirmHint:"再次点击确认,将在终端执行 pi remove",uninstallHint:"通过可见终端执行 pi remove 卸载此包,完成后自动刷新列表",uninstallTitle:"卸载",pluginUpdate:"更新",pluginUpdateHint:"从安装来源重新拉取并覆盖安装(保留 config.json 配置),完成后自动重载插件列表",pluginUninstallHint:"在可见终端执行 pi-harness uninstall 卸载此插件(再次点击确认),完成后自动刷新列表",settingsExtensions:"Extensions",settingsUiPlugins:"界面插件",noUiPlugins:"未安装界面组件(<dataDir>/plugins/)",uiPluginNoSource:"手工安装,无来源信息,无法在线更新",uiPluginPerms:"能力声明",pluginSettingsSave:"保存插件设置",pluginSettingsSaving:"保存中…",pluginSettingsReset:"恢复默认",settingsEnabled:"已启用",settingsDisabled:"已禁用",saveAsPreset:"保存为预设",applyPreset:"应用",deletePreset:"删除预设",noSkills:"暂无技能",noExtensions:"暂无插件",noPresets:"暂无预设(先调整上面的设置,再保存为预设组合)",loadingSession:"正在加载会话…",connectingServer:"正在连接 pi-harness 服务器…"},kd={nodeAgentTitle:"Agent workbench",nodeOpenWorkbench:"Open workbench",nodeAgentSend:"Send",nodeAgentRemote:"Runs on the remote node",nodeAgentSetup:"Use Pi, model credentials and native tools on this node to work with its files and processes.",nodeAgentInstall:"Requires remote Node ≥22.19.0 and Pi 1.0.4. If needed, run this in the terminal, then run pi to configure a model.",nodeAgentStart:"Start remote agent",nodeAgentStarting:"Starting remote agent…",nodeAgentOffline:"Node disconnected. Reconnect to continue.",nodeAgentNew:"New conversation",nodeAgentClose:"Close agent",nodeAgentYou:"You",nodeAgentThinking:"Thinking",nodeAgentWorking:"Remote agent is working…",nodeAgentSelect:"Select an option",nodeAgentPrompt:"Ask the agent to work on this node…",nodeAgentModel:"Remote model",nodeAgentQueue:"Send while running",nodeAgentFollowUp:"Follow up",nodeAgentSteer:"Steer",nodeAgentTerminal:"Terminal and files",toolParameters:"Parameters",toolOutputFileOnly:"Full result available to download",mcpAdapterNoticeTitle:"Choose how to configure the legacy MCP extension",mcpAdapterNoticeNative:"Pi includes native MCP using mcp.json. If you use native MCP, disable pi-mcp-adapter in Extensions and reload. Keep mcp.json in place.",mcpAdapterNoticeSeparate:"To keep using the adapter, follow its documentation to configure a separate mcp-adapter.json and choose which servers it manages. Do not move mcp.json while native MCP uses it.",mcpAdapterNoticeOriginal:"Show original extension notice",changesTitle:"Changes",changesRegenerate:"Regenerate",changesTurn:"This turn",changesBranch:"Branch",changesWork:"Uncommitted",changesSummary:"Changed {n} files",changesViewAll:"View all",changesMore:"{n} more files",changesFiles:"{n} files",changesList:"File list",changesBase:"Base branch",changesSearch:"Search changes",changesExpand:"Expand or collapse all",changesEmpty:"No changes in this scope",changesBinary:"Binary file; diff unavailable",changesUnavailable:"No text diff available",changesUnlocated:"Line numbers unavailable",changesLarge:"Large file · click to expand",changesUnchanged:"⇕ {n} unchanged lines",changesTrailing:"Show remaining {n} lines",changesRecent:"Just changed",changesTruncated:"Diff truncated",changesLoading:"Loading changes…",changesReducedContext:"Large diff: showing only the lines around each change.",changesOmittedUntracked:"{n} more untracked files are not shown; consider adding them to .gitignore.",changesCommands:"{n} commands",bashDurationUnknown:"Time unavailable",bashGroupCount:"Ran {n} commands",bashGroupRunning:"Running {n} commands",bashGroupFailed:"· {n} failed",bashGroupCwd:"In {path}",bashGroupEarlier:"{n} earlier commands · Show all",bashExtraLines:"+{n} lines",bashExitCode:"Exit code {n}",bashUnfinished:"Unfinished",bashRemainingLines:"Show remaining {n} lines",bashCopyCommand:"Copy command",bashCopyOutput:"Copy output",bashOpenTerminal:"Open in terminal",bashOpenTerminalHint:"Run the full command again in a visible terminal",bashCommandCount:"{n} commands",editBusy:"Wait for the current response, compaction or branch switch before editing.",editFailed:"Editing was cancelled or failed.",treeTitle:"Session tree",treeFork:"Fork session",treeForkAt:"Fork from here",treeFilter:"Filter nodes",treeSearch:"Search session tree",treeExternal:"This session changed externally. Reopen it before making changes.",treeReopen:"Reopen",treeTruncated:"More than 5,000 nodes. Narrow the filter or search.",treeEmpty:"No matching nodes",treeFold:"Collapse or expand branch",treeNavigate:"Switch here",treeLabel:"Set label",treeNodes:"nodes",treeClone:"Clone branch",treePreviewCount:"Summarize {n} entries",treeSummary_none:"Without summary",treeSummary_default:"Generate summary",treeSummary_custom:"Summarize with instructions",treeInstructions:"Summary instructions",treeStopConfirm:"Stop this response and switch; restore queued messages",treeLabelClear:"Leave blank to clear the label",treeContent:"Entry content",treeDisconnected:"Disconnected. Reconnect and retry.",treeBusy:"Wait for the current response, compaction or navigation",treeCancelled:"An extension cancelled navigation",treeAborted:"Branch summary cancelled; original position retained",treeFailed:"Session tree operation failed",treeDraftConflict:"Navigation returned text and the editor already contains a draft. Choose how to keep it.",treeReturnedText:"View returned text",treeReplaceDraft:"Replace draft",treeAppendDraft:"Append to draft",treeKeepDraft:"Keep current draft",treeEditOptions:"Resend options",treePrevious:"Previous branch",treeNext:"Next branch",treeSummarizing:"Summarizing the branch being left",treeEditNewSession:"Create a new session when editing and resending",treeBranches:"{n} branch points",treeDerived:"Forked from {name}",treeFilter_default:"Default","treeFilter_no-tools":"No tools","treeFilter_user-only":"Users only","treeFilter_labeled-only":"Labeled only",treeFilter_all:"All (CLI rules)",treeKind_user:"User",treeKind_assistant:"Assistant",treeKind_tool:"Tool",treeKind_compaction:"Compaction",treeKind_branchSummary:"Branch summary",treeKind_custom:"Custom",treeKind_model:"Model",treeKind_thinking:"Thinking",treeKind_info:"Session info",treeKind_contextEdit:"Context edit",treeKind_label:"Label change",wikiSaving:"Saving",wikiSaved:"Saved",wikiSaveFailedRetry:"Save failed · Retry",wikiExternalChanged:"File changed outside the editor",wikiKeepMine:"Keep my version",wikiMessageActions:"Message actions",wikiFullRequest:"View full sent message",wikiResend:"Resend",wikiReplyChanged:"Modified {file}",wikiViewChange:"View",richImage:"Image",richWikiLink:"Document link",wikiLinkAddress:"Enter a URL, or [[ to find a document",wikiInsertLinkAction:"Insert link",wikiInvalidLink:"Enter an http, https, mailto or relative URL",wikiInsertParagraph:"Plain text paragraph",wikiInsertH1:"Top-level heading",wikiInsertH2:"Section heading",wikiInsertH3:"Subsection heading",wikiInsertList:"Bulleted list",wikiInsertOrdered:"Numbered list",wikiInsertTask:"Checkable tasks",wikiInsertQuote:"Quote a passage",wikiInsertCode:"Code with syntax highlighting",wikiInsertCallout:"Highlight a note",wikiInsertTable:"Insert a 3 × 3 table",wikiInsertDivider:"Separate sections",wikiInsertImage:"Upload or paste an image",wikiInsertLink:"Find and link a document",wikiNoInsertResults:"No matches · Esc to close",wikiInsertKeys:"↑ ↓ Select ↵ Insert Esc Close",v2PromptHint:"Sent to the model at the start of each conversation",v2IdentityHint:"Tells the model it is Pi and how to work",v2ToolsHint:"Available capabilities, based on enabled tools and extensions",v2RulesHint:"Tool usage instructions, deduplicated by Pi",v2DocsHint:"Read only when you ask about Pi itself",v2AppendHint:"Extra instructions after the defaults, such as response language",v2ContextHint:"Context from this directory and its parents, loaded automatically",v2CreateAgents:"Create AGENTS.md",v2PiHint:"Built-in agent engine, updated with Desktop",v2ExtensionsIntro:"Extensions add tools and commands to Pi. Packages can also include skills, prompts, and themes.",v2ExtensionCount:"{n} installed",v2LastChecked:"Last checked {time}",v2PackagesHint:"Updates available through the package manager",v2NoPackages:"No managed packages yet. Browse pi.dev to find tools and skills.",v2FilesHint:"Reload after editing a file",v2UpdatePolicy:"Update policy",v2AutoCheckHint:"Check packages on opening management, then every 6 hours while the service runs",v2InstallPolicy:"Install package updates",v2InstallHint:"Update when you choose, then reload or start a new conversation",v2ManualInstall:"Manual",v2SkillsIntro:"Skills are instructions read on demand. Only enabled names and descriptions enter the prompt; full instructions are read when needed. Disabled skills are excluded.",v2SkillCount:"{n} skills · {enabled} enabled · about {tokens} tokens",v2SkillSearch:"Search skill names or descriptions",v2SkillPackage:"Package",v2SkillAll:"All",v2SkillsPaths:"Skill directories",v2CopyPaths:"Copy directory paths",v2OpenSkills:"Open skills directory",v2SkillsChanged:"Native skill settings saved. Reload or start a new conversation to apply.",v2ServersHint:"Connect external services to make more tools available",v2ScopeHint:"Global applies to all projects; project applies to this workspace",v2CodemodeHint:"Let the model batch tool calls in short scripts to reduce round trips and context use",v2ModeHint:"on: allow direct calls; only: call tools through scripts",v2BudgetHint:"Budget for inline tool declarations; 0 means discover all on demand",v2AutoHint:"Automatically enable Codemode when MCP servers are configured",v2EditMcp:"Edit mcp.json",v2NoServersHint:"No servers configured. Import an existing configuration or add a connection.",promptSavedShadowed:"Saved. This session still uses a higher-priority file of the same name.",promptDiscard:"Discard unsaved changes?",promptRestoreConfirm:"Delete {path}? Pi will use the next SYSTEM.md in native priority order, or its default prompt if none remains.",promptCopyFailed:"Copy failed. Copy manually from the raw text.",promptReplaceWarning:"SYSTEM.md replaces the default identity, tool descriptions, rules and Pi documentation. Pi still manages appended instructions, project context, skills and working directory. Use appended instructions for additions.",promptContinueReplace:"Continue with replacement",promptScope:"Save to",promptUser:"User · all projects",promptProject:"Current project",promptUntrusted:"Not trusted",promptContextHint:"Edits the loaded context file. Changes to a parent or user file also affect other projects that use it.",promptEditor:"Prompt file content",promptNativeSave:"Save to native file",promptReloadFile:"Reload file",promptSaving:"Saving…",promptSave:"Save",promptTokenHint:"Approximate count including skills and working directory; actual tokens depend on the model.",promptTokens:"~{n} tokens",promptViewSections:"Sections",promptViewRaw:"Raw text",promptCopied:"Copied",promptCopy:"Copy all",promptSavedPending:"File saved. Reload will run when the session is idle.",promptSavedNext:"Reloaded. Pi will apply the changes on the next request.",promptReloadFailed:"Native reload failed. The file was saved.",promptRetry:"Retry reload",promptForced:"An extension forced the entire prompt for this run. Its sources cannot be reliably separated. Raw text is read-only.",promptOpaque:"The current prompt cannot be matched to native Pi sections. Raw text is read-only.",settingsLoaded:"Loaded",settingsNoSkills:"No skills loaded",settingsNoServers:"No servers",settingsImportSave:"Import and save",settingsRetrySave:"Retry save",settingsToolPresentation:"Tool presentation",settingsDeclarationBudget:"Declaration budget",settingsAutoCodemode:"Enable when connecting MCP",settingsPackages:"Packages",settingsUpdates:"Updates",settingsAutoCheck:"Automatically check for updates",settingsCheckNow:"Check now",settingsBundled:"Updated with app",promptDefault:"Identity",promptReplaced:"Replaced by SYSTEM.md or runtime configuration",promptBuiltinIdentity:"Pi default",promptEdit:"Edit",promptRestore:"Remove replacement",promptReplace:"Replace",promptTools:"Tools",promptInactive:"Descriptions omitted",promptAutomatic:"Automatic",promptRules:"Rules",promptRuleSummary:"{builtin} built-in · {tools} tool · {extensions} extension / runtime",promptCollapse:"Collapse",promptExpand:"Expand",promptBuiltin:"Built-in",promptExtension:"Extension",promptRuntime:"Runtime",promptDocs:"Pi docs",promptDocsSummary:"Read on demand",promptAppend:"Append",promptNotSet:"Not set",promptAdd:"Add",promptContext:"Context",promptNoContext:"No context files loaded",promptRuntimeSection:"Additional native runtime section",promptPriority:"Trusted project .pi files take priority over user files of the same name; one file per type is loaded. Skills and working directory are included in the full text.",promptProjectNotTrusted:"Pi has not trusted this project. Project replacement and append files are read-only.",promptDiskChanged:"Disk content differs from the loaded version",connectionDisconnected:"Disconnected",downloadImage:"Download",extNew:"Just installed",extRetry:"Retry",extEditFile:"Edit file",extEditHint:"Review the code before saving. Changes take effect after reload.",extDiscard:"Discard unsaved changes?",extSaveFile:"Save file",extReleaseNotes:"Release notes",extNoNotes:"No release notes available.",extViewNotes:"View full release notes",extSubtitle:"Manage native Pi packages and standalone extensions",extDetails:"View details",extPersonal:"Personal",extProject:"Project",extUntrusted:"Untrusted · not loaded",extPinned:"Pinned",extUpdate:"Update",extEnable:"Enable",extOpen:"Show in file manager",extCopyPath:"Copy path",extUnpin:"Unpin version",extMoveProject:"Move to this project",extMovePersonal:"Move to personal scope",extRemoveReference:"Remove reference",extUninstall:"Uninstall",extResources:"Included resources",extResourceConfig:"Use pi config for individual resources. Package toggles preserve existing filters.",extInstalled:"Installed",extBrowse:"Browse pi.dev",extRefresh:"Refresh",extRunning:"Package operation in progress…",extDone:"Operation complete",extFailed:"Operation failed",extLog:"View full log",extReloadHint:"Changes apply to new sessions. You can also reload the current session.",extReload:"Reload current session",extLastChecked:"Last checked",extNotChecked:"Updates not checked yet",extChecking:"Checking…",extCheck:"Check updates",extUpdatesAvailable:"package updates available",extUpdateAll:"Update all",extFilter:"Filter installed packages…",extScope:"Install scope",extInstallProject:"This project only",extAllScopes:"All scopes",extEmpty:"No matching packages. Browse the catalog or install from a source.",extSingleFiles:"Standalone extensions · no version checks",extAutoCheck:"Check on opening and every 6 hours",extTypeExtension:"Extensions",extTypeSkill:"Skills",extTypePrompt:"Prompts",extTypeTheme:"Themes",extLicenseUnknown:"License not provided",extCatalogPage:"View on pi.dev",extCatalogOrigin:"From pi.dev · npm packages tagged pi-package · {count} total",extCatalogOriginPage:"From pi.dev · {count} packages on this page",extInstallSource:"Install from npm / git",extUntrustedNotLoaded:"Untrusted, not loaded",extWillLoad:"Resources to load",extProjectUntrusted:"This project is not trusted; project installation is unavailable.",extNoneDeclared:"None",extInstalling:"Installing…",extSearch:"Search pi.dev packages…",extSort:"Sort order",extPopular:"Most downloaded",extRecent:"Recently updated",extAllTypes:"All types",extDownloads:"downloads / month",extInstall:"Install",extNoResults:"No matching packages found.",extPrevious:"Previous",extNext:"Next",extConfirm:"Confirm action",extSource:"Package source",extReview:"Review installation",extResourcesUnknown:"No resource manifest available. Review the source first. Git sources are fetched only after confirmation.",extPinVersion:"Pin this version",extSecurity:"Extensions execute local code, and skills may instruct the model to run programs. Review the source before installing.",extViewSource:"View source",extCancel:"Cancel",extRemoveHint:"Remove this declaration and managed installation. Local paths are only unreferenced; their files remain.",extMoveHint:"Install in the destination scope, then remove the original declaration and preserve resource filters.",extUnpinHint:"Remove the fixed version or Git ref to allow future updates.",extUpdateHint:"Update eligible packages. Pinned versions and local paths stay unchanged.",cmCalls:"Calls",cmScript:"Script",cmWaitingCalls:"Waiting for script calls…",cmNoCalls:"No nested calls",cmMoreCalls:"{n} earlier calls · Show all",cmCollapseCalls:"Show last 8 calls",cmCancelled:"Cancelled",cmUnfinished:"Unfinished",cmLimitedCalls:"{n} additional calls omitted here",cmTruncated:"This preview has been truncated.",cmWaitingOutput:"Output appears when the script returns.",cmNoOutput:"The script returned no text.",cmFullOutput:"Full output file",cmFailureNote:"Calls made before the failure have already run and are not undone. See Output for the error and any similar tool names.",cmSaveImage:"Save to workspace",cmAttachImage:"Attach to next message",cmAttached:"Image added to composer",cmSaved:"Saved: {path}",cmModelCost:"Model call cost",mcpDesignIntro:"Manage native MCP connections and Codemode. Changes are saved to Pi configuration.",mcpServersTitle:"Servers",mcpAttentionFirst:"Connections needing attention appear first. Background connections do not block the composer.",mcpImport:"Import from another client",mcpImportHelp:"Paste Claude, Cursor, VS Code, or OpenCode JSON. Existing server names are preserved. Convert Codex TOML to mcpServers JSON first.",mcpImportDraft:"Import into draft",mcpEditorHelp:'Enter native server JSON: command / args / env for local servers; url / headers / oauth for remote servers. Supports clientRegistration: "cimd".',mcpInvalidServer:"Server configuration must be a JSON object",mcpDiscard:"Discard unsaved configuration changes?",mcpNeedsAuth:"Sign-in required",mcpConnected:"Connected",mcpConnecting:"Connecting",mcpDisabled:"Disabled",mcpDisconnected:"Disconnected",mcpNotLoaded:"Not loaded",mcpFailed:"Connection failed",mcpRuntime:"Another configuration source",mcpAuthHelp:"Sign in with Pi OAuth. When a server requests additional scopes, signing in again retains previously granted scopes.",mcpRemoteLogin:"Browser on another machine? Paste the redirected URL into the native sign-in dialog.",mcpAnnotations:"Hints",mcpActualExposure:"Actual exposure",mcpDestructive:"Destructive",mcpReadOnly:"Read-only",mcpInherit:"Inherited",mcpNoTools:"No tools available from this connection.",mcpExposureDraftHint:"* Per-tool override. Left: actual SDK exposure (codemode maps to deferred). Right: configuration draft. Save to apply.",mcpEnableServer:"Enable",mcpDisableServer:"Disable",mcpEnableProject:"Enable for this project",mcpDisableProject:"Disable for this project",mcpRemoveConfirm:"Remove {name} from the configuration draft? Save to apply.",mcpUnsaved:"Unsaved changes",mcpSavedConfig:"Configuration saved",mcpSaveApply:"Save and apply",mcpExposureGuide:"About tool exposure",mcpExposure_codemode:"Discovered through scripts or tool search; not declared directly.",mcpExposure_deferred:"Loaded by tool_search; also callable from scripts.",mcpExposure_direct:"Declared to the model and callable from scripts.",mcpExposure_hidden:"Registered but unreachable.",mcpEmpty:"No servers configured. Add a local or remote MCP server.",mcpCodemodeHelp:"Only script output reaches the model. Calls follow native Pi permissions and lifecycle.",mcpModeHelp:"on keeps direct tools; only routes tools through scripts.",mcpBudgetHelp:"Estimated token budget for tool declarations; default 3000. Zero lists only namespaces.",mcpBudgetSlider:"Adjust tool declaration budget",mcpEffective:"Current session values",mcpSaveCodemode:"Save Codemode settings",mcpAutoHelp:"Auto-enable when a codemode MCP server connects. Saved with MCP configuration; does not deactivate an already active codemode tool.",mcpAdvanced:"Advanced: native JSON configuration",wikiLoadMore:"Load more files",wikiOpenDefault:"Open in default app",wikiHiddenFolders:"Hidden folders · {count}",wikiProperties:"Document properties",wikiIndexSkipped:"Skipped {count}",wikiIndexCounting:"Counting",wikiIndexStatus:"Indexed {indexed} / {total}",wikiIndexIssueCount:"{count} limited: {reason}",wikiIndexMultipleReasons:"{count} reasons; click for details",wikiIndexFileSize:"File exceeds 2 MB",wikiIndexBudget:"Total read budget exceeds 64 MB",wikiIndexEntries:"More than 20,000 entries",wikiIndexDepth:"Directory depth exceeds 32",wikiIndexUnreadable:"File or path cannot be read",wikiIndexSubtree:"This directory contains unscanned content",wikiIndexPartial:"The scan did not cover the entire workspace. More files remain uncounted. Limited files and unscanned directories are listed below by reason.",wikiIndexHint:"Some content is not indexed. Files exceeding size or budget limits remain searchable by path; inaccessible paths require their access issue to be resolved first.",wikiIndexComplete:"Indexing is complete, with no limited files.",wikiUpdatedToday:"Updated today at {time}",wikiUpdatedDate:"Updated {date}",wikiReadingTime:"About {minutes} min read",wikiCitations:"{count} pages link here",wikiOnThisPage:"On this page",wikiExpandComposer:"Expand question composer",wikiCompactPlaceholder:"Ask pi about this document…",wikiCollapseComposer:"Esc Collapse",wikiDocumentsOnly:"Documents only",wikiMayEditCode:"Code edits allowed",wikiReferenceHint:"@ Reference",wikiSessionPreparing:"Preparing conversation",wikiRetrySession:"Retry conversation",wikiReferencesLoading:"Loading references",wikiMode:"Wiki mode",wikiRecent:"Recent changes",wikiPreview:"Preview",wikiSource:"Edit source",wikiSearchAll:"Search all files",wikiFiles:"Files",wikiClear:"Clear",wikiRefresh:"Refresh files",wikiUnread:"Unseen pi changes",wikiNoFiles:"No matching files",wikiReload:"Reload",wikiLimits:"Some files are not indexed: 2 MB per file, 64 MB total, 20,000 entries. Files remain browsable.",wikiBacklinks:"Backlinks",wikiUnsaved:"Unsaved changes",wikiCodeReadOnly:"Read-only code · Choose Edit source to edit manually",wikiEditingSource:"Source editor · ⌘/Ctrl S to save",wikiPiAdded:"Added by pi",wikiDownloadOpen:"Download and open in default app",wikiNoBacklinks:"No documents link to this file yet",wikiWelcome:"Explore your knowledge with pi",wikiWelcomeHint:"Open a file from the sidebar, or search your workspace.",wikiChangedFiles:"pi changed {count} files",wikiRedo:"Redo",wikiUndo:"Undo",wikiChatPanel:"Wiki conversation panel",wikiFocus:"Focus on document",wikiTableSize:"Table size",wikiTableDimensions:"{columns} columns × {rows} rows",wikiTableHeader:"With header",wikiSearchLanguage:"Search languages…",wikiCodeAutomatic:"Auto detect",wikiCodeAutomaticHint:"Default",wikiCodeShell:"Shell",wikiCodePython:"Script",wikiCodeTypescript:"Typed script",wikiCodeData:"Structured data",wikiCodeConfig:"Configuration",wikiCodeQuery:"Database query",wikiCodeDiagram:"Diagram and source",wikiMoreInsert:"More insertions",wikiMoreInsertHint:"More insertions · or type /",wikiStandardWidth:"Standard width",wikiWideWidth:"Wide document (hide both sides)",wikiMentionDate:"Mention date",wikiInsertDate:"Insert today’s date",wikiEmptyParagraph:"Type / to insert, or start writing",wikiExitFocus:"Exit focus mode",wikiChatTitle:"Chat",wikiCloseChat:"Close conversation panel",wikiChatContext:"Context {percent}%",wikiNoModel:"No model selected",wikiEarlierMessages:"Show earlier messages",wikiQuickSummary:"Summarize this document",wikiQuickLinks:"Find broken links",wikiQuickSections:"Fill empty sections",wikiChatEmpty:"Ask pi about this document, or select text to ask a question.",wikiJumpSection:"Jump to §{section}",wikiToolInterrupted:"Interrupted",wikiWorking:"Working…",wikiLastAnswer:"Latest reply",wikiSelected:"Selection",wikiAsk:"Ask pi",wikiAskCode:"Ask pi about {file}, e.g. “Does it match the docs?”",wikiAskPlaceholder:"Ask pi about this document…",wikiScope:"Scope",wikiCurrentScope:"Scope · Current document",wikiWholeScope:"Scope · Entire workspace",wikiReferencedScope:"Scope · Referenced files",wikiAllowCode:"Allow code changes",wikiPromptPreview:"Preview request",wikiStop:"Stop",wikiSend:"Send",wikiRelatedChanges:"Related changes",wikiMe:"Me",wikiFileCount:"{count} files",wikiUndoAll:"Undo all",wikiRedoAll:"Redo all",wikiViewDiff:"View before and after",wikiBinaryChange:"Binary change; original bytes can be restored",wikiNewFile:"(New file)",wikiDeletedFile:"(Deleted)",wikiUntracked:"Files excluded from undo history",wikiNoChanges:"Edits and pi changes made in Wiki appear here",wikiAskPi:"Ask pi",wikiRewrite:"Rewrite",wikiExplain:"Explain",wikiAddLink:"Add links",wikiSearchHint:"Search documents, code and PDFs…",wikiDocuments:"Documents",wikiPdf:"PDF",wikiCode:"Code",wikiPage:"Page {page}",wikiNoResults:"No results found",wikiSearchLimited:"Results are limited or some files could not be searched; up to 8 PDFs, 200 pages each.",wikiSearchKeys:"↑↓ Select ↵ Open ⌘/Ctrl ↵ Ask pi Esc Close",wikiUnsavedHint:"Save this file before continuing?",wikiDiscard:"Discard",wikiSaveContinue:"Save and continue",wikiSaveFirst:"Save or discard your draft before restoring files.",wikiMissingLink:"No unique matching file: {path}",wikiDocumentsOnlyPrompt:"Only when the user explicitly requests edits, limit changes to documents in this scope. Code files are read-only unless this request explicitly asks to change code.",wikiSkipPrompt:"The scope, references and selection are context only, not a request to analyze or edit documents. Respond to the actual intent of the user message; answer greetings or casual conversation directly without reading, diagnosing or modifying files on that basis. Only edit and save when the user explicitly requests changes, then describe the actual changes.",wikiRewritePrompt:"Rewrite the selection, preserve its meaning, and save.",wikiExplainPrompt:"Explain the selection without changing files.",wikiLinkPrompt:"Add [[wiki links]] to existing workspace documents in the selection and save. Do not invent target files.",mcpArgs:"Arguments (JSON array)",mcpEnv:"Environment (JSON object)",mcpHeaders:"HTTP headers (JSON object)",mcpProvider:"Credential provider (global only)",mcpOauth:"OAuth parameters (JSON object, including authServerMetadataUrl)",mcpEnabled:"Enabled",mcpExposure:"Tool exposure",mcpUpdateDraft:"Update draft",mcpNew:"New server",mcpEdit:"Edit",nativeMcp:"MCP & Codemode",mcpScope:"Configuration scope",mcpGlobal:"Global",mcpProject:"Current project",mcpExplanation:"Native MCP uses Pi configuration and credentials. The legacy UI bridge uses app data-dir/mcp.json.",mcpUntrusted:"Project is untrusted. Saving does not load this configuration.",mcpTrust:"Trust current project",mcpPending:"Applies after the current task settles",mcpName:"Server name",mcpCommand:"Command",mcpAdd:"Add to draft",mcpConfig:"MCP configuration JSON",mcpJsonHelp:"Edit args, env, headers, auth.provider, oauth (including authServerMetadataUrl), enabled, exposure and advanced fields. Keep •••••••• to preserve secrets; replace it or remove the field to clear. Remove an mcpServers entry to delete a server.",mcpNameConflict:"Name is empty or already exists",mcpRefresh:"Refresh configuration",mcpStatus:"Official connection status",mcp_login:"Sign in",mcp_logout:"Sign out",mcp_reconnect:"Reconnect",mcpTools:"Available tools",mcpConfigureRadius:"Configure Radius MCP",nonChatModelsPreserved:"This form edits chat models. Configuration for {n} image or classifier models is preserved.",providerAuthChoose:"Choose an option",providerLogout:"Sign out",providerLogin:"Sign in",providerChatGPTLogin:"Sign in with ChatGPT",providerAuthPending:"Waiting for authorization. Complete sign-in in your browser.",providerAuthSuccess:"Signed in. The model list has been updated.",providerAuthCancelled:"Sign-in cancelled.",providerAuthError:"Sign-in failed.",providerAuthOpenBrowser:"Open authorization page",providerAuthDeviceCode:"Authorization code:",nodeConnectionTiming:"Handshake {ms} ms · Connected {duration}",nodeRevealSource:"Reveal local configuration",nodeSources:"Node sources",nodeSourceIntro:"Connect existing sessions. Changes in the source update here automatically.",nodeDetect:"Detect local sources",nodeSyncKeep:"Sync and keep updated",nodeImportOnce:"Import once",nodeChangePath:"Use another path",nodeSourcePath:"Configuration path on the server machine",nodeSyncNow:"Sync now",nodeSyncPause:"Pause sync",nodeSyncResume:"Resume sync",nodeSyncInfo:"{n} nodes · {g} groups",nodeSyncTime:"Last synced: {time}",nodeSyncFields:"Names, groups, addresses, ports, usernames and key paths",nodeSyncPassword:"Saved passwords are not imported. Enter credentials before connecting.",nodeSyncUnsupported:"Jump hosts, proxies and unsupported options are flagged and blocked.",nodeSearch:"Search name or address",nodeMissingSecret:"Needs password",nodeSourceMissing:"Source removed",nodeUnsupported:"Unsupported configuration",nodeFillSecret:"Authentication settings",nodeLocalAuthHint:"Choose password or public-key authentication. Saved locally after a successful test; source files are unchanged. Normal sync preserves this choice; host, user or source authentication changes reset it.",nodeCredentialHint:"Credentials are stored separately. After changing a password in Xshell, update it here too.",nodePersistSecret:"Save encrypted on the server machine",nodeGroupSecret:"Apply to this group’s nodes using the same authentication method",nodeGroupHint:"Only this node is tested; other nodes are verified when connected.",nodeTestSave:"Test and save",nodeTesting:"Verifying…",nodeCredentialsSaved:"Credentials verified and applied to {n} nodes",nodeSourceReadonly:"Source fields are read-only. Edit them in the original tool.",nodeSourceLocation:"Source file",nodeLastConnected:"Last connected",nodeNever:"Never",nodeOpenTerminal:"Open terminal",nodeBackList:"‹ Nodes",nodeDetails:"Node details",nodePolicy:"Agent permissions",nodePolicyReadonly:"Read-only auto · confirm others",nodePolicyConfirm:"Confirm every command",nodePolicyAuto:"Allow automatic execution",nodePolicyOff:"Disable agent",nodePolicyHint:"Recognized read-only commands run automatically. Writes, restarts and unknown commands require confirmation.",nodeApproval:"Approval required",nodeAllow:"Allow",nodeDeny:"Deny",nodeEditCommand:"Edit command",nodeLocate:"Locate ↗",nodeRunOutput:"Command output",nodeSendSelection:"Send to pi · {n} lines",nodeSelection:"Terminal selection · {n} lines",nodeTerminalHint:"Purple marks pi commands · select output to send to pi",nodeCopy:"Copy",nodeCopied:"Copied",nodeModel:"Node model",nodeNoModel:"Configure a model first",nodeShowFiles:"Files",nodeCloseTab:"Close terminal",nodeAddSource:"Add source",nodeNoSources:"No default source found. Specify an Xshell sessions folder or SSH config file.",nodeWorkingHere:"On {name}",nodeRunFailed:"Failed",nodeSourceOpenHint:"Copy the path and open the original configuration in Xshell or a text editor.",nodeQuoteRemove:"Remove quote",currentFileLabel:"Current file",currentFileUnsaved:"Unsaved",currentFileDraft:"Current file · Unsaved draft",currentFileUnavailable:"Current file is unavailable. Reopen it or remove the tag.",currentFileTooLarge:"Current file exceeds 512 KiB. Reduce its content or remove the tag.",currentFileSaving:"Current file is still saving — send again in a moment.",switchingProject:"Syncing project…",retryProjectSwitch:"Retry project switch",directoryMissing:"Directory moved or deleted",directoryDenied:"Permission denied for this directory",directoryNotFolder:"This path is no longer a folder",directoryUnavailable:"Unable to read this directory",directoryChooseProject:"Choose the project directory again, or restore it and refresh.",newWorkspaceFile:"New file",workspaceFilePath:"File path",workspaceFilePlaceholder:"e.g. docs/notes.md",createWorkspaceFile:"Create",refreshWorkspaceFiles:"Refresh files",cancel:"Cancel",ok:"OK",save:"Save",close:"Close",widgetExpand:"Click to view full output",dragToResize:"Drag to resize · double-click to reset",loading:"Loading…",connected:"Connected",connecting:"Connecting…",reconnecting:"Reconnecting…",language:"Language",langZh:"中文",langEn:"English",githubRepo:"GitHub repository (youweichen0208/pi-harness)",copy:"Copy",viewSwitch:"Switch view",desktopWorkspace:"Workspace",windowControls:"Window controls",minimizeWindow:"Minimize window",maximizeWindow:"Maximize window",restoreWindow:"Restore window",closeWindow:"Close window (hide to tray)",chat:"Chat",terminal:"Terminal",nodes:"Nodes",nodeWorkbench:"SSH nodes",nodeAdd:"Add node",nodeEdit:"Edit node",nodeGroup:"Group",nodeName:"Name",nodeAddress:"Address",nodePort:"Port",nodeUsername:"Username",nodeDefaultDir:"Default directory",nodeAuth:"Authentication",nodePassword:"Password",nodeKey:"Public key (private key authentication)",expandProjects:"Expand projects",collapseProjects:"Collapse projects",nodePrivateKeyHint:"Enter the OpenSSH private key path on the computer running pi, not a .pub file. Xshell key names are not file paths; export an OpenSSH private key from its user key manager. Leave the passphrase empty for an unencrypted key.",nodeAgentAuth:"SSH Agent",nodeKeyPath:"Local private key path",nodePassphrase:"Key passphrase",nodeKeepSecret:"Leave blank to keep saved secret",nodeImportLegacy:"Import Remote-SSH hosts",nodeImportJson:"Import nodes JSON",nodeExport:"Export non-secret details",nodeEmpty:"Select or add an SSH node",nodeAddHint:"Add a node or import existing Remote-SSH hosts.",nodeConnected:"Connected",nodeDisconnected:"Disconnected",nodeConnect:"Connect",nodeDisconnect:"Disconnect",nodeTab:"Terminal {n}",nodeTabClosed:"disconnected",nodeTabBusy:"Agent running",nodeOpenHint:"Connect and open a terminal. The Agent uses the selected terminal.",nodeBrowse:"Browse files",nodeChat:"Node Agent",nodeChatPlaceholder:"Ask this node's Agent…",nodeSelectTerminal:"Open a terminal first",nodeInterrupt:"Interrupt terminal",nodeStopAgent:"Stop Agent",nodeSend:"Send",nodeAgentWaiting:"pi is thinking, waiting for a response…",nodeAgentExecuting:"pi is running a command…",nodeAgentApproval:"Waiting for your approval…",nodeDelete:"Delete",nodeForgetHostKey:"Forget trusted host key",nodeForgetHostKeyConfirm:"Have you verified the new host key for {name}? The fingerprint will appear again on the next connection.",nodeTrust:`First connection to {name} ({host})
18
+ Host key fingerprint: {fingerprint}
19
+ Trust this host?`,nodeDeleteConfirm:"Delete {name}?",nodeImported:"Imported {n} nodes (set credentials manually)",nodeInvalidJson:"Invalid nodes JSON",selectModel:"Select model",availableModels:"Available models",noModels:"No models available (configure an API key first)",reasoning:"reasoning",vision:"vision",refreshModels:"Refresh model list (keeps manual rows, merges new ones)",manageModels:"⚙ Manage models (add / edit)",manageModelsTitle:"Manage models",thinkingLevel:"Thinking level",steerSend:"Send now",activityReply:"Writing the reply…",activityTool:"Running {name}…",activityReading:"Reading {name}…",waitingCommand:"Waiting for command to finish…",onlyChanged:"Changed only",changedCount:"Changes {n}",yesterday:"Yesterday",noChangedFiles:"No changed files",goalEventSet:"Goal set: {text}",cwdSwitchEvent:"Workspace changed to {path}",goalEventComplete:"Goal completed: {text}",goalReviewDetails:"Review details",thinkingDuration:"{n}s",thinkingUnrecorded:"duration unavailable",thinking:"Thinking",thinkingChip:"Thinking: {level}",sound:"Sound",theme:"Theme",themeDefault:"Dark (default)",newChat:"New chat",more:"More",newChatTip:"New chat (sessions are saved per browser)","thinking.off":"Off","thinking.minimal":"Minimal","thinking.low":"Low","thinking.medium":"Medium","thinking.high":"High","thinking.xhigh":"Extra high","thinking.max":"Max",thinkingUnsupported:"Not supported by this model — snapped to the nearest supported level",context:"Context",contextUsage:"Context usage",usageContextTitle:"Context window",usageCacheTitle:"Cache hits",usageCacheShort:"Cache",taskCurrentRound:"This turn",cumulativeCost:"Cumulative cost",sessionMessages:"Session messages",messages:"messages",pluginStatus:"Plugin status",working:"Working",queued:"queued",enterPath:"Type a path, Enter to switch",cwdTip:"Working directory: {path} (click to switch)",folderRef:"Folder reference: {path}",refOnly:"Reference only: {path}",attachContent:"Attached content: {path}",attachLines:"Attached selected lines: {path} (lines {start}-{end})",attachImage:"Image: {name}",attachFile:"File: {name}",removeAttachment:"Remove attachment",attachHint:"Will be sent with the next message",uploadFile:"Add files (images / text / any file — or drag in / paste a screenshot)",dropHereToAttach:"Release to attach file",imageNotSupported:"The current model doesn't support vision — images will be transcribed by the vision bridge (may be ignored if no vision model is configured)",imageLoadFailed:"Couldn't read image: {name}",fileLoadFailed:"Couldn't read file: {name}",fileTooLarge:"File too large, skipped (> {size}MB): {name}",foldersNotSupported:"Folders can't be dropped directly — expand and pick files instead",placeholderStreaming:"Keep typing; send after the current step",stopTask:"Stop task",taskCommitting:"Committing",taskCompletionCriteria:"Done when",taskOutlineChanged:"Plan changed",taskOutlineAdded:"Added step {n}: {title}",taskOutlineRemoved:"Removed: {title}",taskOutlineUpdated:"Updated step {n}: {title}",taskNoStepDetails:"No execution records yet",otherDirectories:"{n} other folders",bashStatusFiles:"{n} files",bashStatusAdded:"{n} added",bashStatusModified:"{n} modified",bashStatusDeleted:"{n} deleted",bashStatusConflicts:"{n} conflicts",placeholderIdle:"Message pi — Enter to send, / for commands",placeholderConnecting:"Connecting to server…",stopAgent:"Stop agent",stopQueuedAfterReconnect:"Connection lost. The current conversation will be stopped after reconnecting.",stopUnavailable:"Cannot send a stop request yet. Wait for the connection to return.",workDisconnected:"Connection lost. Reconnecting; run status is unconfirmed.",stop:"Stop",bgTasks:"Background tasks",bgTasksTip:"Servers the AI started in the background (npm run dev & etc.) — stop them individually or all at once; they survive the conversation",bgTasksEmpty:"No background tasks",bgTasksDesc:"Processes the AI started that are still listening (detected by port)",bgTaskPort:"Port",bgTaskPid:"PID",bgTaskSince:"Started",bgTaskStop:"Stop",bgTaskStopAll:"Stop all",bgTaskRefresh:"Refresh",bgTaskJustNow:"just now",bgTaskMinutes:"{n} min ago",bgTaskHours:"{n} hr ago",bgTaskDays:"{n} days ago",stopBash:"Stop",stopBashTip:"Stop the running bash command (conversation continues)",supplement:"Queue",supplementTip:"Add to queue: sent only after the whole run finishes (no interruption)",commandAttempts:"{n} attempts",queueSteerTag:"Steer",pendingMessages:"{n} pending",recallQueueEdit:"Recall all to edit",deliverySteerHint:"Send after the current step",deliveryFollowHint:"Send after this turn",placeholderStreamingModes:"Keep typing, ↵ {primary} · Alt+↵ {alternate}",queueFollowTag:"Queued",sendTip:"Send (Enter)",slashCommands:"Commands",slashMenuHint:"↑↓ select · Enter/Tab complete",slashHelpTitle:"pi commands",slashHelpHint:"Type / anytime to open the command list",slashLoading:"Loading commands… (available once connected)",slashBuiltin:"Builtin",slashExtension:"Extension",slashPrompt:"Template",slashSkill:"Skill",slashPlugin:"Plugin",slashCopied:"Copied the last assistant reply",slashCopyFailed:"Copy failed — please copy manually",slashCopyEmpty:"No assistant reply to copy yet",mermaidRendering:"Rendering diagram…",mermaidRenderFailed:"Diagram failed to render — showing raw source",recentProjects:"Recent projects",workspaceFiles:"Files",showHiddenFiles:"Show hidden",taskProgress:"Task progress",taskProgressHeading:"Progress",taskOutputsHeading:"Outputs",taskProgressEmpty:"Progress for longer tasks will appear here.",taskOutputsEmpty:"View and open files created or modified during this task.",taskPaused:"Paused · waiting to continue",taskFailed:"Task failed",taskCompletedCount:"{n} completed",taskRunningCount:"{n} running",taskSteps:"steps",taskCompletedHidden:"{n} completed steps · Show",taskJumpToChat:"Find in chat",builtinTaskList:"Task list",componentUpdates:"Updates",componentNewVersion:"Update available",componentCurrent:"Latest stable version installed",componentPinned:"Pinned version; change the installation source manually",componentManual:"Maintain manually at the installation source",componentUnknown:"Installed version unknown",componentCheckFailed:"Check failed; retry available",componentApp:"pi-harness application",componentDesktopUnsupported:"Automatic installation is available in the installed desktop app, not development mode.",componentAppHint:"Check and download a new version, then restart to install.",componentWebUpdateHint:"Update the global npm package in the terminal, then run pi-harness server restart.",componentDownloading:"Downloading: {n}%",componentRestartInstall:"Restart and install",componentAutoUpdate:"Update automatically",componentLocal:"Local file extension; edit its source and reload.",componentChecking:"Checking…",componentCheck:"Check for updates",componentUpdateIntro:"Running pi Agent and installed extension versions. Checks never install updates. Restart the app after updating user extensions.",componentOffline:"Reconnect to check for updates.",componentInstalling:"Updating extension. Please wait…",componentRestart:"Update installed. Restart the app to load the new version.",componentBundled:"Bundled",componentBundledHint:"Updated with the app. An upstream release may not yet be included in this app.",componentProject:"Project",componentUser:"User-installed",componentInstalled:"Installed",componentInstall:"Update extension",taskTodoUpdate:"Task list update",planUnassignedRecords:"This turn’s execution records · outside the plan",planEnabled:"Native plan tool (whole service)",planEnabledHint:"On by default; saved preferences are preserved. Shared by all clients; running sessions apply changes after settling.",planPending:"Applies when the session is idle and writable",planConflict:"A third-party plan tool is present. This switch does not change it.",planMissing:"The native plan extension is unavailable in this session",planReplaced:"Plan {id} (revision {revision}) was replaced and cancelled",planStatusChanged:"Plan status: {status}",planRecorded:"Plan recorded",planActive:"Active",planPrevious:"Previous unfinished plan",todoCounts:"{total} items · {completed} completed",todoCreated:"Created",todoPending:"Pending",todoRemoved:"Removed",todoView:"View",todoChanges:"Checklist update: {changes}",todoChangeSeparator:"; ",todoCleared:"Task checklist cleared",todoItemAdded:"Item {n} added",todoItemUpdated:"Item {n} updated",todoItemPending:"Item {n} pending",todoItemStarted:"Item {n} started",todoItemCompleted:"Item {n} completed",todoItemDeleted:"Item {n} removed",taskWaitingContinue:"Waiting to continue",taskPlanSource:"Task checklist",taskPlanSourceHint:"Steps tracked from the checklist created by the agent",taskObservedSource:"Activity · No plan created",taskObservedSourceHint:"Summarized from tool calls; the agent has not created a task checklist",taskBlockedBy:"Waiting for steps {steps}",taskCancelled:"Stopped",taskLongTool:"Command running",taskStepSilent:"No new data; see actions above the composer",taskPhases:"phases",taskDuration:"Duration",taskResult:"Result",taskCommit:"Commit",taskTests:"Tests",taskChanges:"Changes",taskPassed:"passed",taskFiles:"files",taskViewChanges:"View changes",taskFinalReply:"Go to final reply",taskProcess:"Process",taskOnlyResult:"Only result",taskShowProcess:"Expand process",taskRawSteps:"{n} original steps",taskShowRaw:"Show {n} original steps",taskHideRaw:"Hide original steps",taskCopyMarkdown:"Copy as Markdown",taskArtifactRead:"Read",taskArtifactWrite:"Write",taskArtifactEdit:"Edit",taskArtifactRun:"Run",taskLines:"lines",taskExplicitPlan:"Pi plan",taskPlanSteps:"steps",taskPlanPosition:"Step {current} / {total}",taskPlanChanged:"Plan updated",taskPlanAdded:"Added",taskPlanCard:"Plan",taskUnderSecond:"<1s",taskReadCount:"{n} reads",taskWriteCount:"{n} writes",taskEditCount:"{n} edits",taskCommandCount:"{n} commands",changeEdit:"Edit",changeWrite:"Write",changeOpen:"Open",changeRawArgs:"Raw arguments",changeRawOutput:"Raw output",changeAtLine:"Line {n}",changeWrittenLines:"Wrote {n} lines",changeOriginal:"Original text sought",changeAttemptedWrite:"Content attempted",changeFailed:"Edit failed",changeNoOriginal:"No original text available",changeNoDiff:"No diff available",changeReplacement:"Replacement text (file diff unavailable)",changeRetried:"Retried",modelSilent:"No model response for {duration}",modelSilentShort:"Model unresponsive",toolSilentShort:"Tool running · no new output",placeholderModelSilent:"The model is quiet. Stop, retry, or keep waiting…",placeholderToolSilent:"A command or tool is still running. New messages will queue…",toolSilent:"Command or tool running for {duration} without new output",retrySilentUnavailable:"This turn used tools or attachments. Stop and review before retrying to avoid duplicate effects.",continueWaiting:"Keep waiting",actions:"Actions",retry:"Retry",writeVerb:"Write",expandRemainingLines:"Show {n} more lines",lines:"lines",fileUsed:"Used",thinkingDepthTip:"Thinking depth: deeper takes longer and uses more tokens",readFiles:"Read {n} files",readVerb:"Read",modelReadOnly:"File content · read by model only",readRaw:"Source",skillLabel:"Skill",bashSteps:"Steps",bashRaw:"Raw",bashRunning:"Running",bashPartial:"Partly failed · {ok}/{total} steps passed",bashFailed:"Failed",bashErrorCount:"{n} errors",bashExpandCommand:"Show full command · {n} steps",bashExpandFullCommand:"Show full command",bashLikelyErrorLines:"{n} likely error lines",bashHiddenLines:"{n} lines hidden",bashNoMatch:"No matches",bashSkipped:"Not run",bashShowRaw:"Show raw output",grepSearch:"Search",grepInPath:"in {path}",grepMatches:"{n} matches",allDone:"All done",expandAllLines:"Show all · {n} lines",timeGapAt:"Time gap, {time}",notGitRepoShort:"Not a Git repo",toolWrap:"Wrap",copied:"Copied",toolLineCount:"{n} lines",toolRelativeTo:"Relative to {path}",toolMoreLines:"Show remaining {n} lines",workspaceBranch:"Branch",workspacePath:"Path",workspaceProjects:"Projects",composerPlaceholder:"Message pi…",thinkingStandard:"Standard",thinkingDeep:"Deep",thinkingMinimalDescription:"Minimal reasoning, fastest",thinkingStandardDescription:"Balanced speed and quality",thinkingDeepDescription:"More reasoning for complex tasks",workspaceModified:"Uncommitted changes",workspaceChanges:"{n} recent changes",runningConversations:"Running chats",historySessions:"History",openHistory:"History",openFiles:"Files",streaming:"Streaming…",noHistory:"No previous chats",current:"Current",messageCount:"{n} messages",tuiTip:"Chat in the pi terminal (TUI)",deleteProject:"Remove from recent projects",deleteProjectConfirm:"Confirm remove",deleteSession:"Delete this chat transcript permanently",deleteSessionConfirm:"Confirm delete",confirm:"Confirm",expandCode:"Expand full content",collapseCode:"Collapse",zoomCode:"Open in a larger view",closeZoom:"Close",renameSession:"Rename this chat",renameSessionPlaceholder:"Chat name (empty falls back to first message)",openFolder:"Open folder…",openFolderPlaceholder:"Or paste an absolute path",openThisFolder:"Open this folder",openTypedPath:"Open typed path",parentFolder:"Parent folder",home:"Home",noSubfolders:"No subfolders here",listTruncated:"Too many folders — list truncated",emptyChat:"Empty chat",editReask:"Edit & re-ask",editReaskTip:"Edit this question and re-ask from here (forks a new conversation; the original is kept)",reaskFromHere:"Re-ask from here",editPlaceholder:"Edit the question…",editHint:"⌘/Ctrl+Enter to submit · Esc to cancel",editAttachmentHint:"Original attachments kept — paste/drop images or files · ⌘/Ctrl+Enter to submit · Esc to cancel",expandMsg:"Expand",collapseMsg:"Collapse",toolCalls:"tool calls",bashRuns:"bash runs",images:"images",update:"Update",updateTip:"Check & update pi-harness",currentVersion:"Current version",latestVersion:"Latest version",checkingUpdate:"Checking…",checkUpdate:"Check for updates",upToDate:"You're up to date",updateAvailable:"New version v{version} available",updateJustPublished:"v{version} was just published — npm cache may lag; if the new version isn't detected yet, re-check in a moment",updateNow:"Update in terminal",updateTabTitle:"Update pi-harness",updateTerminalHint:"Clicking runs npm i -g @youweichen/pi-harness@latest in a visible terminal; restart the service afterwards to take effect (pi-harness server restart).",rootDir:"Root",noFiles:"No files",filesTruncated:"Directory too large — list truncated (first 2000 shown)",linkFolderTip:"Link folder path to chat",attachInlineTip:"Attach content to chat",referenceTip:"Reference path only (AI reads on demand)",richSourceBlock:"Source preserved; switch to source to edit",richFormatting:"Document formatting",richEditMarkdown:"Edit Markdown document",reloadRunning:"Reloading…",reloadDone:"Reloaded",reloadPartial:"Reloaded with {count} loading error(s)",reloadCounts:"Extensions {extensions} · Skills {skills} · Prompts {prompts}",reloadDetails:"Show error details",reloadGeneralError:"Reload",reloadExtensionList:"Extensions: {names}",reloadSkillList:"Skills: {names}",reloadPromptList:"Prompts: {names}",richFormatToolbar:"Document formatting",richBold:"Bold",richItalic:"Italic",richHeading:"Heading",richParagraph:"Paragraph",richList:"List",richOrderedList:"Numbered list",richQuote:"Quote",richUndo:"Undo",richRedo:"Redo",richTable:"Insert table",dbViewer:"Database preview",dbReadOnly:"Read only",dbRefresh:"Refresh",dbTable:"Table / view",dbView:"View",dbRows:"Table data",dbNoTables:"This database has no tables to display.",dbNoRows:"This table has no rows.",dbPrevious:"Previous",dbNext:"Next",dbRowRange:"Rows {start}–{end}",dbSchema:"Show schema",dbCellLimit:"Up to 50 rows per page; text previews show 256 characters and BLOBs show byte counts.",dbStructureLimited:"Showing up to 500 tables and 64 columns per table.",dbLoadFailed:"Unable to read SQLite database:",dbUnavailable:"Connection or workspace is unavailable.",richColumn:"Column",richTableTools:"Table actions",richAddRow:"Add row below",richAddColumn:"Add column right",richRemoveRow:"Delete current row",richRemoveColumn:"Delete current column",fileMoreActions:"More file actions",richCodeBlock:"Code block",richHighlightBlock:"Highlight block",richTextHighlight:"Highlight",richHighlight_yellow:"Yellow highlight",richHighlight_green:"Green highlight",richHighlight_blue:"Blue highlight",richHighlight_pink:"Pink highlight",richHighlight_purple:"Purple highlight",richHighlightClear:"Clear highlight",richCodeLanguage:"Code language",richPlainText:"Plain text",richImageUploading:"Inserting image…",richImageFailed:"Image insertion failed. Check the connection and file state, then paste again.",richImageTooLarge:"Images must be at most 5 MB.",richDivider:"Divider",richTaskList:"Task list",richInsertMenu:"Insert element",richTextGroup:"Text formatting",richBlocksGroup:"Basic elements",richNoElements:"No matching elements",backToFiles:"Back to files",fileUnsaved:"Unsaved",fileSaving:"Saving",fileSaved:"Saved",fileViewMode:"File view",fileViewPreview:"Preview",fileViewSource:"Source",fileViewChanges:"View changes",fileChangesCount:"Changes {n}",fileEditMode:"Editing mode",fileReadOnly:"Read only",fileEditShort:"Edit",fileReference:"Reference",fileExternalChanged:"pi changed this file",fileCompare:"Compare",fileNoChanges:"No changes to show",fileLocalDraft:"Unsaved draft",fileDiskVersion:"Latest disk version",quoteSelection:"Quote selection @{name}:{start}-{end}",fileSaveFailed:"Save failed",fileOffline:"Disconnected or timed out. Your draft is retained. Please retry.",fileReload:"Reload",fileOverwrite:"Overwrite disk file",fileOverwriteConfirm:"The disk file has changed. Overwrite it with this draft?",fileLeavePrompt:"This file has unsaved changes.",fileSaveContinue:"Save and continue",fileDiscard:"Discard changes",previewFile:"Preview",downloadFile:"Download file",downloadFailed:"Download failed: {error}",protocolMismatch:"Page version differs from the server (the app was just updated). Refresh the page to restore full functionality.",selectLinesHint:"Click a line to select; drag or Shift+click for a range",enableWrap:"Enable line wrap",disableWrap:"Disable line wrap",selectedRange:"Selected {n} lines (lines {start}-{end})",fileLines:"{n} lines",selectAll:"Select all",clearSelection:"Clear",addToChat:"Add to chat",addedToChat:"Added",previewTruncated:"⚠ File too large — previewing the first 512KB",previewLinesTruncated:"… too many lines — showing the first {n}",binaryFile:"🔣 Binary file — first 4KB shown as hex",binaryHexTruncated:" (file larger — download for the full file)",previewNotSupported:"This file type can't be previewed (only images / videos / text)",emptyFile:"(empty file)",editFile:"Edit file",exitEditFile:"Exit editing",saveFile:"Save file",discardFileChanges:"Discard unsaved changes?",fileEditTruncated:"The preview is incomplete, so this file can't be edited",showMarkdownSource:"Show Markdown source",showMarkdownPreview:"Show Markdown preview",fullscreen:"Fullscreen",exitFullscreen:"Exit fullscreen",zoomIn:"Increase font size",zoomOut:"Decrease font size",resetZoom:"Reset zoom",pluginRequest:"Plugin request",noOptions:"(no options)",inputPlaceholder:"Enter content",soundHeader:"Sound notifications",enableSound:"Enable sound",preview:"Preview",volume:"Volume","sound.question":"Question popup","sound.question.desc":"When ask_user_question appears","sound.done":"Reply finished","sound.done.desc":"When the agent finishes a turn","sound.start":"Reply started","sound.start.desc":"When the agent starts a new turn","sound.error":"Error","sound.error.desc":"When an error notice appears",setupTitle:"pi agent config not detected",setupDesc:"pi-harness needs pi's config directory (~/.pi/agent) and at least one API key to run the agent. pi has built-in providers such as openai, anthropic, and deepseek — just pick one and enter a key, no terminal needed.",installFailed:"✖ pi agent installation failed:",retryInstall:"Retry install",skip:"Skip",installDone:"✅ pi agent CLI installed. Pick a provider and enter an API key to start chatting:",cliReadyHint:"✅ pi agent CLI already installed locally. Pick a provider and enter an API key to start chatting:",provider:"Provider",configured:"configured",providerKeyReady:"This provider already has a key — use it or replace it.",apiKey:"API key",saving:"Saving…",saveAndStart:"Save and start using",recheck:"Recheck",installing:"Installing pi agent CLI…",autoInstall:"Auto-install pi agent",attachment:"Attachment",plugin:"plugin",unknown:"unknown",thinkingWait:"Thinking",exitCode:"Exit code {code}",cancelled:"Cancelled",truncated:"… content too long, truncated in this view",outputTruncated:"… output too long, truncated in this view",refOnlyShort:"Reference only",folderRefShort:"Folder · reference only",inlineLines:"Inline · {n} lines",inlineLinesRange:"Lines {start}-{end}",image:"🖼 Image",bridgedVision:"👁 Transcribed",bridgedVisionDetail:"Image transcribed by the vision bridge (current model can't see images)",folderNotExpanded:"Folder — content not expanded, the agent will browse it as needed",fileNotExpanded:"Large file ({size}) — content not expanded, the agent will read it as needed","role.user":"You","role.assistant":"pi","role.tool":"Tool","role.bash":"Terminal","role.branch":"Branch summary","role.compaction":"Context compacted",welcomeTitle:"pi coding agent",welcomeSub:"Inspect, edit, run — always ready",directory:"Directory",clickToFill:"Click to fill input",sending:"Sending",backToBottom:"Back to bottom",questionNavTitle:"Questions",questionMarkerGroup:"{n} nearby questions",searchPlaceholder:"Search in conversation…",searchNoResults:"No results",searchModels:"Filter models…",noModelMatches:"No matching models",searchGlobal:"Search",searchGlobalTip:"Global search: sessions / projects / files (Ctrl+K)",gsPlaceholder:"Search projects, past conversations, workspace files…",gsHint:"Type to search session history, recent projects and file names in the current workspace at once",gsSessions:"Conversations",gsProjects:"Projects",gsFiles:"Files",gsNoResults:"No matches",gsSearching:"Searching files…",gsTruncated:"Too many matches — showing a subset",gsCurrentProject:"current",gsOpenPreview:"Open file preview",gsNavigate:"select",gsOpen:"open",gsCloseHint:"close",bgTaskCommand:"Command",searchPrev:"Previous (Shift+Enter)",searchNext:"Next (Enter)",searchClose:"Close (Esc)",questionNavTip:"All questions in this conversation — hover to expand, click to jump","ex.understand":"Understand this project","ex.understand.prompt":"Introduce this project: overall structure, main modules, and how to run it?","ex.debug":"Debug an issue","ex.debug.prompt":"Help me debug a bug — describe the symptom first, and I'll add details.","ex.test":"Write tests","ex.test.prompt":"Write unit tests for the core modules.","ex.review":"Code review","ex.review.prompt":"Review the recently changed code and point out potential issues and improvements.",error:"Error",done:"Done",running:"Running…",toolQueued:"Queued",copyArgs:"Copy args",errorOutput:"Error output",nestedToolCalls:"Nested tool calls · {n}",nestedToolCallsIncomplete:"Some call records or arguments were not fully retained.",recoveryCompacting:"Compacting",recallQueue:"Recall all queued messages",recallQueueShort:"Recall queued messages",treeVerifying:"Verifying session file…",compactionCompleted:"Compaction completed",compactionAborted:"Compaction cancelled",compactionFailed:"Compaction failed",compactionManual:"Manual",compactionThreshold:"Context near limit",compactionOverflow:"Context overflow",recoveryWaiting:"Waiting for native retry",recoveryRunning:"Retrying",recoverySummaryWaiting:"Waiting to retry summary",recoverySummaryRunning:"Retrying summary",conversationRunSettings:"Conversation run settings",conversationAutoCompaction:"Auto compaction",conversationAutoRetry:"SDK auto retry",commandAttachmentsRetained:"Command executed. Unsent attachments remain in the composer.",toolOutputAuth:"Download authentication failed. Please reconnect.",toolOutputDenied:"Access to this output was denied.",toolOutputError:"Download failed. Please try again.",toolOutputText:"Full text",toolOutputDownload:"Download full output",toolOutputUnavailable:"Full output unavailable or already cleaned up",toolResultImage:"Image returned by a tool",output:"Output",waitingOutput:"Waiting for output…",toolDoneWaitingModel:"Done",waitUnderstanding:"Understanding your question",waitResults:"Reading command results",waitFile:"Reading files",waitThinking:"Thinking",waitTests:"Waiting for test results",waitBuild:"Waiting for build results",waitSteer:"Processing your direction",waitSeconds:"{n} sec",waitMinutes:"{m} min {s} sec",waitStop:"Stop",thinkingNow:"Thinking",thinkingPreview:"Thinking: {preview}",leakedThinking:"Additional model content",toolUnexecutedTitle:"Tool call not executed",toolUnexecutedAttempts:"Stopped after {n} automatic reminder(s)",toolUnexecutedHint:"{model} wrote the tool instruction as text and still made no tool call after a reminder. Earlier results are preserved.",toolUnexecutedInline:"Tool instruction was written as text and not executed",toolAutoReminded:"Reminder sent",toolReminderEvent:"Asked pi to retry with a real tool call",toolRecoverySwitch:"Switch model",toolRecoveryRaw:"View original output",toolRecoveryRawHide:"Hide original output",toolRecoveryFirst:"First attempt",toolRecoveryAfterReminder:"After reminder",toolRecoveryNoCall:"No tool call",taskInterruptedHint:"Tool call not executed. Use Resend in the conversation to continue.",taskInterruptedTitle:"Interrupted",unexecutedToolHint:"{model} returned a tool instruction as text instead of a native tool call. Earlier results have been preserved.",unexecutedToolOriginal:"View original output",toolStoppedTitle:"The model stopped without running a tool",toolStoppedHint:"{model} was reminded to continue with a tool call but still did not call any tool, so the task stopped here. Resend, or continue with another model.",toolRecoveryResend:"Resend",toolRecoveryFailed:"Could not confirm the resend request. Check the connection and selected model before retrying.",toolRecoveryInterrupted:"Interrupted",leakedThinkingHint:"Reasoning markers were detected in the reply, so this content was collapsed. This does not indicate an application error or data disclosure. Click to view the original.",commands:"Commands",newCommand:"New command",newTerminal:"New terminal",name:"Name",command:"Command",cwdHint:"(${pwd} = current working directory)",noCommands:"No commands yet — click + to add one",clickToRun:"Click to run",edit:"Edit",delete:"Delete",confirmQ:"Confirm?",builtinTerminal:"Built-in terminal",termEmptySub:"Click a command on the left to run it, or + on the right for a new terminal",noTerminal:"No terminals",exited:"(exited{code})",closeTerminal:"Close terminal",rerun:"Reload .pi/commands.json",terminalTitle:"Terminal {n}",exampleName:"e.g. start dev server",exampleCommand:"e.g. npm run dev",scmTab:"Git",scmTitle:"Source Control",scmRefreshTip:"Re-query git status & diff",scmCurrentBranch:"Current branch",scmUpstreamGone:"Upstream deleted",scmAheadBehind:"↑{ahead} ↓{behind}",scmDetached:"Detached HEAD",scmSelectBranch:"Select branch…",scmRemoteBranches:"Remote branches",scmStageTip:"Stage {path}",scmUnstageTip:"Unstage {path}",scmSwitch:"Switch",scmSwitchBranch:"Switch branch",scmSwitchBranchTip:"Runs git checkout {branch} in the terminal",scmPush:"Push",scmPushTip:"Runs git push in the terminal",scmPull:"Pull",scmPullTip:"Runs git pull in the terminal",scmCommit:"Commit",scmCommitTip:'Runs git add -A && git commit -m "…" in the terminal (commits all changes incl. untracked)',scmCommitPlaceholder:"Type a commit message…",scmChanges:"Changes",scmHistory:"Commit tree",scmCommitDetail:"Commit details",scmSelectCommitHint:"Click a commit on the left to view its details",scmNoHistory:"No commits yet",scmNoChanges:"Working tree clean — no changes",scmNotGitRepo:"Current directory is not a Git repository",scmLoading:"Querying…",scmConnecting:"Waiting for connection…",scmDiff:"Diff",scmSelectFileHint:"Click a file on the left to view its diff",scmNoDiff:"(no diff)",scmStaged:"Staged",scmUnstaged:"Unstaged",scmStagedUnstaged:"Staged + unstaged",scmUntracked:"Untracked",scmUntrackedBadge:"u",scmUntrackedBinary:"Binary file cannot be previewed here",scmUntrackedDirectory:"Directory cannot be previewed here; select a file inside it",scmEmptyFile:"Empty file",scmPreviewTruncated:"Showing only the first 512 KB",scmQueryFailed:"Git query failed: {error}",scmTooManyFailures:"Git queries keep failing — click refresh to retry",scmRunsInTerminal:"Commit / branch switch / push / pull run in the terminal",scmViewTerminal:"Open terminal",editProvider:"Edit provider",builtinProviders:"Built-in providers",hintKeyOnly:"Configure an API key or sign in to a supported account",configuredBadge:"✓ Configured",keyReady:"Key ready",replaceKey:"Replace key",replaceKeyTitle:"Replace the saved key",clearKey:"Clear",clearKeyTitle:"Remove this provider's key stored in auth.json; it returns to unconfigured (env-var sourced keys can't be cleared here)",clearKeyConfirm:"Clear the stored key for {id}? Its models will leave the list until you configure it again.",cloneProvider:"Clone as custom",cloning:"Cloning",cloneProviderTitle:"Copy this built-in provider (baseUrl + model catalog) into a custom provider — paste another API key to run both keys side by side",pasteKey:"Paste API key…",savingKey:"Saving",saveKey:"Save key",customProviders:"Custom providers",customDesc:"For Ollama / vLLM / OpenAI-compatible proxies, etc. Written to pi's models.json — hot-reloaded immediately.",noCustomProviders:"No custom providers yet",modelsCount:"{n} models",addProvider:"Add provider",providerId:"Provider ID",providerIdHint:"(required, e.g. ollama / my-proxy)",displayName:"Display name",displayNamePh:"My proxy",apiType:"API type",baseUrlHint:"(OpenAI-compatible endpoint)",apiKeyHint:"sk-… (leave blank to keep the existing key)",authHeader:"Auto-add Authorization header",modelsTitle:"Models",modelIdReq:"Model ID (required)",text:"Text",textImage:"Text+image",contextWindow:"Context",maxOutput:"Max output",removeModel:"Remove model",addModel:"Add model",deleteProviderConfirm:"Delete provider {id} and its {n} models?",fetchModels:"Fetch model list",fetchModelsHint:"Pull model IDs from the baseUrl /models endpoint (server-side, no CORS)",fetchingModels:"Fetching…",fetchModelsOk:"Fetched {n} models",fetchModelsEmpty:"The endpoint returned no models",fetchModelsErr:"Fetch failed: {msg}",fetchModelsNeedBaseUrl:"Enter a baseUrl first",goalBarTitle:"Goal",goalWizardCard:"Goal survey",settings:"Settings",nativeContextOnly:"Uses the native pi context. WebUI does not append prompts or register custom agent tools.",nativeResourcesManaged:"Skills and extensions are managed by native pi configuration. Loaded resources are shown here.",settingsTitle:"Settings",allSettings:"All settings",quickActions:"Quick actions",settingsAppearance:"Appearance",settingsCodeTheme:"Code file colors",codeThemeLight:"Light",codeThemeDark:"Dark",codeThemeSystem:"Follow system",settingsDesc:"Changes apply immediately: system prompt, skill and extension toggles rebuild the current session; review instructions and review skills affect later goal reviews (main-session changes are deferred while streaming).",settingsSystemPrompt:"System prompt",promptModeAppend:"Append",promptModeReplace:"Replace",promptAppendHint:"Append mode: your text is appended to the end of the default system prompt (recommended — keeps the default behavior constraints).",promptReplaceHint:"Replace mode: your text fully replaces the system prompt (project context and skills are still appended automatically). After switching, the editor shows the built-in default prompt ready to edit; blurring without changes keeps the default.",promptPlaceholder:"Type a custom system prompt… (applied on blur)",settingsViewPrompt:"View the current full prompt",settingsViewPromptHint:"The full system prompt actually in effect for this conversation (custom append/replace text, project context, skills and tool guidance). Read-only.",settingsViewPromptEmpty:"Session not ready yet — no system prompt available.",settingsSkills:"Skills",settingsReview:"Goal review",settingsReviewDesc:"Configure extra instructions and skills for the isolated goal-review session; the main session is unaffected.",settingsReviewSkills:"Skills available to review",reviewPromptPlaceholder:"Type custom review instructions… (applied on blur)",reviewPromptHint:"These instructions are added to the review task; pass/fail JSON output is still enforced. Skill toggles apply only to review.",settingsVisionBridge:"Vision bridge",settingsVisionBridgeDesc:"When the current model can't see images, send them to a configured vision model and transcribe into text evidence first",settingsTerminalTools:"Terminal tools",settingsTerminalToolsDesc:"Let the AI use the built-in terminal for interactive programs (REPLs/vim), long-running servers, continuous output watching, or when you ask it to work in the visible terminal; ordinary commands still go through the one-shot bash tool",settingsMessageDisplay:"Message display",thinkingWrap:"Show full thinking",thinkingWrapDesc:"On: thinking always expands fully and wraps (live reasoning visible while streaming); Off: collapses to a one-line summary with the latest text shown live while streaming",toolsWrap:"Show full tools",toolsWrapDesc:"On: tool calls always expand fully showing arguments and output; Off: collapsed by default, click to expand",uninstallExt:"Uninstall",uninstallConfirm:"Confirm?",uninstallConfirmHint:"Click again to confirm — runs pi remove in the terminal",uninstallHint:"Runs pi remove in a visible terminal, then refreshes the list automatically",uninstallTitle:"Uninstall",pluginUpdate:"Update",pluginUpdateHint:"Re-installs from the recorded source (--force, keeps config.json), then refreshes the plugin list automatically",pluginUninstallHint:"Runs pi-harness uninstall in a visible terminal (click again to confirm), then refreshes the list automatically",settingsExtensions:"Extensions",settingsUiPlugins:"UI plugins",noUiPlugins:"No UI plugins installed (<dataDir>/plugins/)",uiPluginNoSource:"Installed manually — no recorded source, online update unavailable",uiPluginPerms:"Permissions",pluginSettingsSave:"Save plugin settings",pluginSettingsSaving:"Saving…",pluginSettingsReset:"Reset defaults",settingsEnabled:"Enabled",settingsDisabled:"Disabled",saveAsPreset:"Save as preset",applyPreset:"Apply",deletePreset:"Delete preset",noSkills:"No skills",noExtensions:"No extensions",noPresets:"No presets yet (tune the settings above, then save them as a preset)",loadingSession:"Loading session…",connectingServer:"Connecting to pi-harness server…"},_o=d.createContext(null);function yd(){try{const t=localStorage.getItem(Oo);if(t==="zh"||t==="en")return t}catch{}return"zh"}function wd({children:t}){const[n,s]=d.useState(yd),r=d.useCallback(o=>{s(o);try{localStorage.setItem(Oo,o)}catch{}},[]),i=d.useCallback((o,c)=>{let l=kd[o];if(n==="zh"&&(l=vd[o]),c)for(const[p,u]of Object.entries(c))l=l.replaceAll(`{${p}}`,String(u));return l},[n]);d.useEffect(()=>{document.documentElement.lang=n==="zh"?"zh-CN":"en"},[n]);const a=d.useMemo(()=>({locale:n,setLocale:r,t:i}),[n,r,i]);return e.jsx(_o.Provider,{value:a,children:t})}function ns(){const t=d.useContext(_o);if(!t)throw new Error("useI18n must be used within LanguageProvider");return t}function et(){return ns().t}function Ps({files:t}){if(!t.some(r=>r.counted))return null;const n=t.reduce((r,i)=>r+i.added,0),s=t.reduce((r,i)=>r+i.removed,0);return e.jsxs("span",{className:"change-counts",children:[e.jsxs("span",{className:"add",children:["+",n]}),e.jsxs("span",{className:"del",children:["−",s]})]})}function fa({files:t}){const n=et(),s=Mr(),[r,i]=d.useState(!1);return!t.length||!s?null:e.jsxs("section",{className:"change-summary",children:[e.jsxs("header",{children:[e.jsx("strong",{children:n("changesSummary",{n:t.length})}),e.jsx(Ps,{files:t}),e.jsx("button",{onClick:()=>s.show(t),children:n("changesViewAll")})]}),(r?t:t.slice(0,6)).map(a=>e.jsxs("button",{className:`change-summary-file ${s.open&&s.selected===a.path?"selected":""}`,onClick:()=>s.show(t,a.path),children:[e.jsx(Gs,{}),e.jsx("code",{children:a.path.split("/").at(-1)}),e.jsx("span",{className:"change-directory",children:a.path.split("/").slice(0,-1).join("/")}),e.jsx(Ps,{files:[a]}),e.jsx(_t,{})]},a.path)),!r&&t.length>6&&e.jsx("button",{className:"changes-more",onClick:()=>i(!0),children:n("changesMore",{n:t.length-6})})]})}let bd=-1e6;function jd({cwd:t,data:n,send:s,notRepo:r,branch:i,branches:a,defaultBase:o,dirty:c,ready:l}){const p=Mr(),u=et(),[f,k]=d.useState(),[j,R]=d.useState(!1),[E,A]=d.useState(""),[N,T]=d.useState({}),[y,M]=d.useState(new Set),b=d.useRef(0),F=d.useRef(null),U=d.useRef(null),ce=r?"turn":p.scope,ie=`${t}\0${ce}\0${p.base}`;d.useEffect(()=>{if(!p.open||ce==="turn"||!l)return;const L=()=>{const fe=--bd;s({type:"scm_diff",reqId:fe,scope:ce,base:p.base||void 0})&&(b.current=fe)};L();const q=setInterval(L,3e4);return()=>{clearInterval(q),b.current=0}},[p.open,ce,p.base,t,c,l,s]),d.useEffect(()=>{(n==null?void 0:n.type)!=="scm_data"||n.kind!=="diff"||n.reqId!==b.current||n.cwd!==t||k({key:ie,files:n.ok?Hc(n.text??""):[],error:n.error,base:n.base,omittedUntracked:n.omittedUntracked,reducedContext:n.reducedContext})},[n,ie,t]);const W=ce==="turn"?p.files:(f==null?void 0:f.key)===ie?f.files:[],ve=ce!=="turn"&&(f==null?void 0:f.key)!==ie,Se=d.useMemo(()=>E.trim()?W.filter(L=>L.path.toLowerCase().includes(E.toLowerCase())||L.lines.some(q=>q.text.toLowerCase().includes(E.toLowerCase()))):W,[W,E]),$=L=>N[L.path]??L.lines.filter(q=>q.marker!==" ").length>400,$e=L=>{p.set({selected:L}),T(q=>({...q,[L]:!1})),requestAnimationFrame(()=>{var q,fe;return(fe=Array.from(((q=F.current)==null?void 0:q.querySelectorAll("[data-change-file]"))??[]).find(je=>je.dataset.changeFile===L))==null?void 0:fe.scrollIntoView({block:"start"})})};return d.useEffect(()=>{p.open&&(A(""),p.selected?$e(p.selected):p.focusRequest>0&&(T(Object.fromEntries(W.map(L=>[L.path,!1]))),W[0]&&$e(W[0].path)))},[p.focusRequest,p.open]),d.useEffect(()=>{var L;j&&((L=U.current)==null||L.focus())},[j]),p.open?e.jsxs("aside",{className:"changes-panel","aria-label":u("changesTitle"),tabIndex:0,onKeyDown:L=>{var fe,je,ne;const q=L.target;if((L.metaKey||L.ctrlKey)&&L.key.toLowerCase()==="f")L.preventDefault(),L.stopPropagation(),R(!0);else if(L.key==="Escape")L.preventDefault(),L.stopPropagation(),j?(R(!1),A(""),L.currentTarget.focus()):(fe=document.querySelector(".inputbox textarea"))==null||fe.focus();else if(!q.closest("input,textarea,select")&&!L.metaKey&&!L.ctrlKey&&["j","k"].includes(L.key.toLowerCase())){L.preventDefault();const Pe=Array.from(((je=F.current)==null?void 0:je.querySelectorAll("[data-change-hunk]"))??[]),B=((ne=F.current)==null?void 0:ne.getBoundingClientRect().top)??0,re=(L.key.toLowerCase()==="j"?Pe:Pe.slice().reverse()).find(Ie=>L.key.toLowerCase()==="j"?Ie.getBoundingClientRect().top>B+45:Ie.getBoundingClientRect().top<B+35);re==null||re.scrollIntoView({block:"start"})}},children:[e.jsxs("header",{className:"changes-toolbar",children:[e.jsx("button",{title:u("changesList"),"aria-label":u("changesList"),"aria-pressed":p.list,onClick:()=>p.set({list:!p.list}),children:e.jsx(dr,{})}),!r&&e.jsxs("label",{className:"changes-branch",children:[e.jsxs("select",{"aria-label":u("changesBase"),value:p.base||(f==null?void 0:f.base)||o||"",onChange:L=>p.set({base:L.target.value}),children:[e.jsx("option",{value:"",children:u("changesBase")}),[...new Set([...a.map(L=>L.name),...f!=null&&f.base?[f.base]:[]])].map(L=>e.jsx("option",{children:L},L))]}),e.jsx("span",{children:"→"}),e.jsx("code",{title:i,children:i})]}),!r&&e.jsx("div",{className:"changes-scopes",children:["turn","branch","work"].map(L=>e.jsx("button",{"aria-pressed":ce===L,onClick:()=>{p.set({scope:L}),T({}),M(new Set)},children:u(L==="turn"?"changesTurn":L==="branch"?"changesBranch":"changesWork")},L))}),e.jsx("button",{title:u("changesSearch"),"aria-label":u("changesSearch"),onClick:()=>R(!j),children:e.jsx(as,{})}),e.jsx("button",{title:u("changesExpand"),"aria-label":u("changesExpand"),onClick:()=>{const L=W.some(q=>!$(q));T(Object.fromEntries(W.map(q=>[q.path,L])))},children:e.jsx(hd,{})}),e.jsx("button",{title:`${u("close")} (⌘D)`,"aria-label":u("close"),onClick:()=>p.set({open:!1}),children:e.jsx(Wt,{})})]}),j&&e.jsxs("div",{className:"changes-search",children:[e.jsx(as,{}),e.jsx("input",{ref:U,value:E,placeholder:u("changesSearch"),"aria-label":u("changesSearch"),onChange:L=>A(L.target.value)}),e.jsxs("span",{children:[Se.length," / ",W.length]})]}),e.jsxs("div",{className:"changes-content",children:[p.list&&e.jsxs("nav",{className:"changes-files","aria-label":u("changesList"),children:[e.jsxs("header",{children:[u("changesFiles",{n:W.length}),e.jsx(Ps,{files:W})]}),Se.map(L=>e.jsxs("button",{className:p.selected===L.path?"selected":"",onClick:()=>$e(L.path),children:[e.jsx("code",{children:L.path.split("/").at(-1)}),e.jsxs("span",{children:[e.jsx("span",{className:"change-directory",children:L.path.split("/").slice(0,-1).join("/")||"."}),e.jsx(Ps,{files:[L]})]})]},L.path))]}),e.jsxs("div",{className:"changes-diffs",ref:F,onScroll:()=>{var je;const L=F.current.getBoundingClientRect().top,fe=(je=Array.from(F.current.querySelectorAll("[data-change-file]")).find(ne=>ne.getBoundingClientRect().bottom>L+40))==null?void 0:je.dataset.changeFile;fe&&fe!==p.selected&&p.set({selected:fe})},children:[!ve&&(f==null?void 0:f.key)===ie&&ce!=="turn"&&(f.reducedContext||f.omittedUntracked)?e.jsx("p",{className:"changes-note",role:"status",children:[f.reducedContext?u("changesReducedContext"):"",f.omittedUntracked?u("changesOmittedUntracked",{n:f.omittedUntracked}):""].filter(Boolean).join(" ")}):null,ve?e.jsx("p",{className:"changes-empty",children:u("changesLoading")}):(f==null?void 0:f.key)===ie&&f.error&&ce!=="turn"?e.jsx("p",{className:"changes-empty",role:"alert",children:f.error}):!Se.length&&e.jsx("p",{className:"changes-empty",children:u("changesEmpty")}),Se.map(L=>e.jsx(Cd,{file:L,selected:p.selected===L.path,collapsed:$(L),toggle:()=>{p.set({selected:L.path}),T(q=>({...q,[L.path]:!$(L)}))},gaps:y,expandGap:q=>M(fe=>new Set([...fe,q])),query:E},L.path))]})]})]}):null}function Cd({file:t,selected:n,collapsed:s,toggle:r,gaps:i,expandGap:a,query:o}){var N,T;const c=et(),l=Mr(),p=()=>l==null?void 0:l.set({open:!1}),[u,f]=d.useState(!!((N=t.toolIds)!=null&&N.length));d.useEffect(()=>{const y=setTimeout(()=>f(!1),3e3);return()=>clearTimeout(y)},[]);const k=((T=t.toolIds)==null?void 0:T.join(","))??"",j=d.useRef(k);d.useEffect(()=>{if(j.current===k)return;j.current=k,f(!0);const y=setTimeout(()=>f(!1),3e3);return()=>clearTimeout(y)},[k]);const R=d.useMemo(()=>{var M,b;const y=new Map;for(let F=0;F<t.lines.length;){if(t.lines[F].marker!=="-"){F++;continue}const U=F;for(;((M=t.lines[F])==null?void 0:M.marker)==="-";)F++;const ce=F;for(;((b=t.lines[F])==null?void 0:b.marker)==="+";)F++;for(let ie=0;ie<Math.min(ce-U,F-ce);ie++)y.set(U+ie,t.lines[ce+ie].text),y.set(ce+ie,t.lines[U+ie].text)}return y},[t.lines]),E=y=>{const M=t.lines[y],b=M.marker==="+"?"add":M.marker==="-"?"del":"context",F=R.get(y),U=F===void 0?[{text:M.text,changed:!1}]:Bc(M.text,F);return e.jsxs("div",{className:`changes-line ${b}${o&&M.text.toLowerCase().includes(o.toLowerCase())?" search-match":""}`,"data-change-hunk":M.marker!==" "&&(y===0||t.lines[y-1].marker===" ")?"":void 0,children:[e.jsx("span",{className:"changes-line-number",children:M.newLine??M.oldLine}),e.jsx("span",{className:"changes-line-sign",children:M.marker}),e.jsx("code",{className:/^#{1,6} /.test(M.text)?"markdown-heading":"",children:U.map((ce,ie)=>ce.changed?e.jsx("mark",{children:ce.text},ie):ce.text)})]},y)},A=t.lines.find(y=>y.marker!==" ");return e.jsxs("section",{className:`changes-file ${n?"selected":""}`,"data-change-file":t.path,children:[e.jsxs("header",{className:"changes-file-head",children:[e.jsxs("button",{"aria-expanded":!s,onClick:r,children:[s?e.jsx(_t,{}):e.jsx(Qt,{}),e.jsx("code",{title:t.path,children:t.oldPath&&t.oldPath!==t.path?`${t.oldPath} → ${t.path}`:t.path.split("/").at(-1)}),e.jsx("span",{className:"change-directory",children:t.path.split("/").slice(0,-1).join("/")}),e.jsx(Ps,{files:[t]}),u&&e.jsx("span",{className:"changes-recent",title:c("changesRecent"),children:"●"})]}),e.jsxs("button",{className:"changes-open-file",title:c("changeOpen"),onClick:()=>{p(),window.dispatchEvent(new CustomEvent("pi-harness:open-tool-file",{detail:{path:t.path,line:(A==null?void 0:A.newLine)??(A==null?void 0:A.oldLine)??1}}))},children:[c("changeOpen")," ",e.jsx(Lo,{})]})]}),s&&t.lines.filter(y=>y.marker!==" ").length>400&&e.jsx("button",{className:"changes-gap",onClick:r,children:c("changesLarge")}),!s&&(t.binary?e.jsx("p",{className:"changes-empty",children:c("changesBinary")}):e.jsxs("div",{className:"changes-file-lines",children:[!t.lines.length&&e.jsx("p",{className:"changes-meta",children:c("changesUnavailable")}),t.unlocated&&e.jsx("p",{className:"changes-meta",children:c("changesUnlocated")}),Uc(t.lines).map(y=>y.kind==="line"?E(y.index):i.has(`${t.path}:${y.start}`)||o?Array.from({length:y.end-y.start},(M,b)=>E(y.start+b)):e.jsx("button",{className:"changes-gap",onClick:()=>a(`${t.path}:${y.start}`),children:c(y.end===t.lines.length?"changesTrailing":"changesUnchanged",{n:y.end-y.start})},`gap:${y.start}`)),t.truncated&&e.jsx("p",{className:"changes-meta",children:c("changesTruncated")})]}))]})}const Sd="你上一条回复里的工具调用是以普通文本输出的,没有被执行。请通过工具调用(不要写成文本)重新发起它,然后继续完成任务。";function ni(t){let n;return t.split(`
20
+ `).map(r=>{const i=/^ {0,3}(`{3,}|~{3,})(.*)$/.exec(r),a=!!n||!!i;return i&&(n?i[1][0]===n.marker&&i[1].length>=n.length&&!i[2].trim()&&(n=void 0):n={marker:i[1][0],length:i[1].length}),a?r.replace(/</g,"\0"):r}).join(`
21
+ `).replace(/(`+)([\s\S]*?)\1(?!`)/g,r=>r.replace(/</g,"\0"))}const es="(?:[||]DSML[||])?",Nd=new RegExp(`<${es}invoke\\s+name=["']([\\w.-]+)["']\\s*>`,"g"),Ho=`<${es}parameter\\s+name=["'][\\w.-]+["'][^>]*>[\\s\\S]*?<\\/${es}parameter>`,Bo=`(?:<\\/${es}(?:tool_calls|function_calls)>\\s*)?`,Ed=new RegExp(`(?:${Ho}\\s*)+<\\/${es}invoke>\\s*${Bo}$`),Td=new RegExp(`(?:<${es}(?:tool_calls|function_calls)>\\s*)?<${es}invoke\\s+name=["'][\\w.-]+["']\\s*>`);function Ti(t){var c;const n=ni(t),s=Td.exec(n);if(s){const l=n.slice(s.index),p=new RegExp(`<\\/${es}invoke>\\s*${Bo}$`).test(l),u=[...l.matchAll(new RegExp(`<${es}invoke\\s+name=["']([\\w.-]+)["']\\s*>([\\s\\S]*?)<\\/${es}invoke>`,"g"))];if(p&&u.length&&u.every(f=>new RegExp(Ho).test(f[2])))return{before:t.slice(0,s.index).trimEnd(),raw:t.slice(s.index).trim(),tools:[...new Set(u.map(f=>f[1]))]}}const r=Ed.exec(t);if(!r)return null;const i=[...t.matchAll(Nd)],a=((c=i.find(l=>l.index!==void 0&&l.index<r.index))==null?void 0:c.index)??r.index,o=Math.min(a,r.index);return{before:t.slice(0,o).trimEnd(),raw:t.slice(o).trim(),tools:[...new Set(i.map(l=>l[1]))]}}function Rd(t,n){const s=t[n],r=t[n-1];if((s==null?void 0:s.role)!=="user"||s.content.length!==1||s.content[0].type!=="text"||s.content[0].text!==Sd||(r==null?void 0:r.role)!=="assistant"||r.stopReason==="aborted"||r.stopReason==="error"||r.content.some(a=>a.type==="toolCall"))return!1;const i=r.content.map(a=>a.type==="text"?a.text:"").join(`
22
+ `);return!!Ti(i)}const ga=new WeakMap;function Id(t){const n=ga.get(t);if(n)return n;const s=t.content.map(i=>i.type==="text"?i.text:"").join(`
23
+ `),r={text:s,leak:Ti(s)};return ga.set(t,r),r}function Fs(t,n=!1){const s=[];let r,i,a=!1;for(const[o,c]of t.entries()){if(c.role==="user"){i&&Rd(t,o)?(i.reminders.push(c),i.state="reminding",a=!1):(r=c,i=void 0,a=!1);continue}if(c.role!=="assistant"||!r)continue;if(c.content.some(k=>k.type==="toolCall")){i&&(i.state="recovered"),a=!0;continue}const{text:p,leak:u}=Id(c),f=c.stopReason==="aborted"||c.stopReason==="error";u&&!f&&!i&&(i={incidentId:`tool-text:${r.entryId??r.id}:${c.entryId??c.id}`,user:r,first:c,last:c,reminders:[],leaks:[],outputs:[],state:"stopped"},s.push(i)),i&&(!u&&!i.reminders.length&&(i.state="recovered"),u&&i.leaks.push(c),(u||i.reminders.length&&!a)&&(i.last=c,i.outputs.push({message:c,raw:i.reminders.length?p:(u==null?void 0:u.raw)??p,attempt:i.reminders.length}),i.state=f?"recovered":"stopped"))}return i&&i.state!=="recovered"&&(i.state=n?"reminding":"stopped"),{incidents:s,current:i}}const xa=new WeakMap;function Ld(t){const n=new Map;for(const s of Fs(t).incidents){for(const r of s.outputs)n.set(r.message.id,{toolText:{incidentId:s.incidentId,attempt:r.attempt}});s.reminders.forEach((r,i)=>n.set(r.id,{origin:"auto-reminder",toolText:{incidentId:s.incidentId,attempt:i+1}}))}return t.map(s=>{const r=n.get(s.id);if(!r)return s;const i=JSON.stringify(r),a=xa.get(s);if((a==null?void 0:a.key)===i)return a.message;const o={...s,...r};return xa.set(s,{key:i,message:o}),o})}function Md(t,n=!1){const{current:s}=Fs(t,n);return!n&&(s==null?void 0:s.state)==="stopped"?{message:s.last,user:s.user}:null}function va(t,n,s){let r=!1;for(const i of n){const a=i;if(a.type!=="image"||typeof a.dataUrl!="string"||!a.dataUrl.startsWith("data:"))continue;const o=a.dataUrl.match(/^data:([^;]*);base64,(.+)$/);o&&(r=!0,t.push({path:"",imageData:o[2],mimeType:o[1]||"image/png",name:s??`image.${(o[1]||"image/png").split("/")[1]??"png"}`}))}return r}function Uo(t){var s;const n=new Map;for(let r=0;r<t.length;r++){const i=t[r];if(i.role!=="user"||!i.id)continue;const a=(i.userAttachments??[]).map(o=>({path:o.path,mode:o.mode,nativeRef:o.nativeRef}));va(a,i.content);for(let o=r+1;o<t.length&&t[o].role==="custom"&&t[o].customType==="file";o++){if((s=t[o].userAttachments)!=null&&s.length){a.push(...t[o].userAttachments.map(l=>({path:l.path,mode:l.mode,nativeRef:l.nativeRef})));continue}const c=t[o].details??{};if(!va(a,t[o].content,c.name)){if(c.upload&&c.path){a.push({path:"",uploadPath:c.path,name:c.name??c.path,size:c.size});continue}if(c.path&&c.mode){const l=c.mode==="inline"||c.mode==="lines"?c.mode:"reference",p={path:c.path,mode:l,...c.editorSnapshot?{editorSnapshot:c.editorSnapshot}:{}};c.mode==="lines"&&typeof c.startLine=="number"&&typeof c.endLine=="number"&&(p.lines={start:c.startLine,end:c.endLine}),a.push(p)}}}a.length>0&&n.set(i.id,a)}return n}const Pd=/^<skill name="([^"]+)" location="([^"]+)">\n([\s\S]*?)\n<\/skill>(?:\n\n([\s\S]+))?$/;function As(t){var s;const n=t.match(Pd);return n?{name:n[1],location:n[2],content:n[3],userMessage:((s=n[4])==null?void 0:s.trim())||void 0}:null}function fs(t){const n=As(t);return n?`skill:${n.name}`+(n.userMessage?` · ${n.userMessage.replace(/\s+/g," ").trim()}`:""):t.replace(/\s+/g," ").trim()}function ar(t){if(As(t))return fs(t);const n=/^<skill name="([^"]+)" location="[^"]+">\r?\n/.exec(t);return n&&!t.includes("</skill>")?`skill:${n[1]}`:t}function Gt(){if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return crypto.randomUUID();const t=new Uint8Array(16);if(typeof crypto<"u"&&typeof crypto.getRandomValues=="function")crypto.getRandomValues(t);else for(let s=0;s<16;s++)t[s]=Math.floor(Math.random()*256);t[6]=t[6]&15|64,t[8]=t[8]&63|128;const n=[...t].map(s=>s.toString(16).padStart(2,"0")).join("");return`${n.slice(0,8)}-${n.slice(8,12)}-${n.slice(12,16)}-${n.slice(16,20)}-${n.slice(20)}`}function Ad(t,n,s){var f,k,j,R;const r=((f=t.state)==null?void 0:f.conversationId)===t.activeConversationId?t.state:null,i=r&&Md(r.messages,r.isStreaming),a=d.useRef(null),[o,c]=d.useState(!1),l=!!r&&t.ready&&!r.isStreaming&&!((k=r.tree)!=null&&k.busy)&&!((j=r.tree)!=null&&j.verifying)&&!((R=r.tree)!=null&&R.externallyModified)&&!Object.values(r.recovery??{}).some(Boolean),p=d.useRef({state:r,failure:i,writable:l,send:n,onError:s});p.current={state:r,failure:i,writable:l,send:n,onError:s};const u=()=>{a.current=null,c(!1)};return d.useEffect(()=>{var A,N,T;const E=a.current;if(E){if(!t.ready||(r==null?void 0:r.conversationId)!==E.conversation||(r==null?void 0:r.sessionFile)!==E.session){u();return}if(((A=t.promptResult)==null?void 0:A.requestId)===E.requestId){u();return}if(!E.sent){if(!l||(i==null?void 0:i.user.id)!==E.source){u();return}E.modelId&&`${(N=r.model)==null?void 0:N.provider}/${(T=r.model)==null?void 0:T.id}`!==E.modelId||(E.sent=!0,n({type:"prompt",text:E.text,attachments:E.attachments,requestId:E.requestId})||(u(),s()))}}},[r,t.ready,t.promptResult,l,i,n,s]),d.useEffect(()=>{if(!o)return;const E=window.setTimeout(()=>{a.current&&(a.current=null,c(!1),p.current.onError())},3e4);return()=>window.clearTimeout(E)},[o]),{messageId:i==null?void 0:i.message.id,currentModelId:r!=null&&r.model?`${r.model.provider}/${r.model.id}`:void 0,disabled:!l||o,retry:E=>{var U,ce;const{state:A,failure:N,writable:T,send:y}=p.current;if(!A||!N||!T||a.current)return;const M=N.user.questionText??N.user.content.map(ie=>ie.type==="text"&&typeof ie.text=="string"?ie.text:"").join(`
24
+ `),b=As(M),F=b?`/skill:${b.name}${b.userMessage?` ${b.userMessage}`:""}`:M;F.trim()&&(a.current={conversation:A.conversationId,session:A.sessionFile,source:N.user.id,modelId:E,text:F,attachments:Uo(A.messages).get(N.user.id)??[],requestId:Gt(),sent:!1},c(!0),E&&`${(U=A.model)==null?void 0:U.provider}/${(ce=A.model)==null?void 0:ce.id}`!==E&&!y({type:"set_model",modelId:E})&&(u(),p.current.onError()))}}}const Wo="pi-harness:token";function Dd(){try{const t=new URL(window.location.href),n=t.searchParams.get("token");n&&(localStorage.setItem(Wo,n.trim()),t.searchParams.delete("token"),window.history.replaceState(null,"",t.toString()))}catch{}}function $d(){try{return localStorage.getItem(Wo)??""}catch{return""}}function Tn(t){const n=$d();return n?`${t}${t.includes("?")?"&":"?"}token=${encodeURIComponent(n)}`:t}function Js({url:t,compact:n=!1}){const s=et(),[r,i]=d.useState(!1),[a,o]=d.useState(),[c,l]=d.useState();d.useEffect(()=>{l(void 0),o(void 0)},[t]);const p=k=>{o(k)},u=async(k,j="tool-output.txt")=>{i(!0),o(void 0);try{const R=await fetch(Tn(t+(k?`&outputId=${encodeURIComponent(k)}`:"")));if(!R.ok){p(R.status);return}const E=R.headers.get("content-disposition")??"",A=E.match(/filename\*=UTF-8''([^;]+)/i),N=E.match(/filename="([^"]+)"/),T=A?decodeURIComponent(A[1]):(N==null?void 0:N[1])??j,y=URL.createObjectURL(await R.blob()),M=document.createElement("a");M.href=y,M.download=T,M.click(),setTimeout(()=>URL.revokeObjectURL(y),1e3)}catch{p(500)}finally{i(!1)}},f=async()=>{i(!0),o(void 0);try{const k=await fetch(Tn(t.replace("/api/tool-output?","/api/tool-output-list?")));if(!k.ok){p(k.status);return}const j=await k.json();j.length?j.length===1&&j[0].default?await u(j[0].id,j[0].name):l(j):await u()}catch{p(500)}finally{i(!1)}};return e.jsxs(e.Fragment,{children:[e.jsxs("button",{type:"button",className:n?"tool-output-download-link":"btn",disabled:r,onClick:()=>void f(),children:[n&&e.jsx(Pr,{"aria-hidden":"true"}),s("toolOutputDownload")]}),c&&e.jsxs("span",{className:"tool-output-files",children:[e.jsx("button",{disabled:r,onClick:()=>void u(),children:s("toolOutputText")}),c.map(k=>e.jsx("button",{disabled:r,onClick:()=>void u(k.id,k.name),children:k.name},k.id))]}),a&&e.jsx("span",{role:"alert",children:s(a===404?"toolOutputUnavailable":a===401?"toolOutputAuth":a===403?"toolOutputDenied":"toolOutputError")})]})}function ka(t,n=performance.now()){return t&&{...t,retry:t.retry?{...t.retry,deadline:n+Math.max(0,t.retry.remainingMs??0)}:void 0,summary:t.summary?{...t.summary,deadline:n+Math.max(0,t.summary.remainingMs??0)}:void 0}}function Fd(t){window.dispatchEvent(new CustomEvent("pi-tree-response",{detail:t}))}function ya(){window.dispatchEvent(new Event("pi-tree-open"))}function wa(t,n){window.dispatchEvent(new CustomEvent("pi-tree-navigate",{detail:{conversationId:t,targetId:n}}))}const Qs=new Map,Hs=new Set;function ba(t){var s;if(!t.text&&!((s=t.images)!=null&&s.length)||Hs.has(t.id))return;Hs.add(t.id),Hs.size>256&&Hs.delete(Hs.values().next().value);const n=Qs.get(t.conversationId)??[];n.some(r=>r.id===t.id)||n.push(t),Qs.set(t.conversationId,n),window.dispatchEvent(new Event("pi-tree-draft"))}function Od(t){var n;return(n=Qs.get(t))==null?void 0:n[0]}function ja(t,n){var r;const s=Qs.get(t);((r=s==null?void 0:s[0])==null?void 0:r.id)===n&&s.shift(),s!=null&&s.length||Qs.delete(t),window.dispatchEvent(new Event("pi-tree-draft"))}const fr=new Map,Ca=new Set;function _d(t){fr.delete(t)}function Hd(t){Ca.has(t.id)||(Ca.add(t.id),fr.set(t.conversationId,t),window.dispatchEvent(new Event("pi-extension-editor")))}function qo(t,n,s){d.useEffect(()=>{if(!n)return;const r=()=>{const i=fr.get(t);i&&(fr.delete(t),s(i.text))};return r(),window.addEventListener("pi-extension-editor",r),()=>window.removeEventListener("pi-extension-editor",r)},[t,n,s])}const _r=2e5;function Bd(t,n){const s=n.replace?n.delta:t+n.delta;return s.length>_r?`…[前 ${s.length-_r} 字符已省略]…
25
+ ${s.slice(-_r)}`:s}class Ud{constructor(n=3,s=32*1024*1024){$r(this,"entries",new Map);$r(this,"bytes",0);this.limit=n,this.budget=s}get(n){const s=this.entries.get(n);if(s)return this.entries.delete(n),this.entries.set(n,s),s.value}set(n,s){this.delete(n);const r=JSON.stringify(s).length*2;if(!(r>this.budget))for(this.entries.set(n,{value:s,bytes:r}),this.bytes+=r;this.entries.size>this.limit||this.bytes>this.budget;)this.delete(this.entries.keys().next().value)}delete(n){var s;this.bytes-=((s=this.entries.get(n))==null?void 0:s.bytes)??0,this.entries.delete(n)}}const kt=window.electronAPI,si=new Set;function Wd(t){return si.add(t),()=>{si.delete(t)}}async function qd(){return(await Promise.allSettled([...si].map(n=>n()))).every(n=>n.status==="fulfilled"&&n.value)}function zd(t,n){const s=n.assistantMessageEvent,r=t.stats.tokens,i=n.usage!==null?{...r,...n.usage}:r,a=i===r?t.stats:{...t.stats,tokens:i};if(s.type!=="text_delta"&&s.type!=="thinking_delta")return a===t.stats?t:{...t,stats:a};const o=s.delta??"";if(!o)return a===t.stats?t:{...t,stats:a};const c=t.streamingMessage??null,l=c&&c.id===n.messageId?c:{id:n.messageId,content:[]},p=[...l.content],u=s.type==="thinking_delta"?"thinking":"text",f=s.contentIndex??p.length-1;return f>=0&&f<p.length&&p[f].type===u?p[f]=u==="thinking"?{...p[f],type:"thinking",thinking:(p[f].thinking??"")+o}:{type:"text",text:(p[f].text??"")+o}:p.push(u==="thinking"?{type:"thinking",thinking:o}:{type:"text",text:o}),{...t,stats:a,streamingMessage:{...l,id:n.messageId,content:p}}}const ri="pi-harness:plugin-data";function Vd(t,n){window.dispatchEvent(new CustomEvent(ri,{detail:{pluginId:t,payload:n}}))}function Kd(t){const n=s=>{const r=s.detail;t(r.pluginId,r.payload)};return window.addEventListener(ri,n),()=>window.removeEventListener(ri,n)}const Ns=new Map,ii=new Set,Ss=new Set;let Sa=-1;function zo(){return[...Ns.values()]}function Gd(){const t=zo();for(const n of ii)n(t)}function Jd(t){return ii.add(t),t(zo()),()=>ii.delete(t)}async function Qd(t,n){n!==Sa&&(Sa=n,Ns.clear(),Ss.clear());const s=new Set(t.map(r=>r.id));for(const r of[...Ns.keys()])s.has(r)||Ns.delete(r);for(const r of[...Ss])s.has(r)||Ss.delete(r);await Promise.all(t.filter(r=>r.hasClient&&!r.error&&!Ns.has(r.id)&&!Ss.has(r.id)).map(async r=>{try{const a=(await Lr(()=>import(`/plugins/${encodeURIComponent(r.id)}/client/entry.mjs?e=${n}`),[])).default;a&&typeof a.mount=="function"?Ns.set(r.id,{info:r,module:a}):(Ss.add(r.id),console.error(`[plugin:${r.id}] entry.mjs 缺少 default.mount`))}catch(i){Ss.add(r.id),console.error(`[plugin:${r.id}] 客户端加载失败:`,i)}})),Gd()}function Yd(t,n){return{pluginId:t,send:s=>n({type:"plugin_message",pluginId:t,payload:s}),onData:s=>Kd((r,i)=>{r===t&&s(i)})}}const Xd=41,Vo="pi-harness:reload-events";function Zd(){try{const t=JSON.parse(sessionStorage.getItem(Vo)??"[]");return Array.isArray(t)?t.filter(n=>n&&typeof n=="object"&&n.type==="reload_status"&&typeof n.conversationId=="string"&&typeof n.requestId=="string"&&(n.phase==="running"||n.phase==="done")&&typeof n.timestamp=="number").slice(-40):[]}catch{return[]}}const eu=2e5;function tu(){const t=new Map,n=new Map,s=(r,i)=>`${r}:${i}`;return{write(r,i,a){const o=s(r,i),c=t.get(o);if(c&&c.size>0){for(const u of c)try{u.write(a)}catch{}return}const l=n.get(o)??"",p=l.length+a.length>eu?a:l+a;n.set(o,p)},register(r,i,a){const o=s(r,i);let c=t.get(o);c||(c=new Set,t.set(o,c)),c.add(a);const l=n.get(o);if(l){try{a.write(l)}catch{}n.delete(o)}return()=>{const p=t.get(o);p&&(p.delete(a),p.size===0&&t.delete(o)),n.delete(o)}},clear(){t.clear(),n.clear()}}}function Na(t,n){const s=new Set;for(const i of n.messages)i.role==="toolResult"&&i.toolCallId&&s.add(i.toolCallId),i.role==="bashExecution"&&s.add(`bash-${i.id}`);let r=!1;for(const i of t.keys())s.has(i)&&(t.delete(i),r=!0);return r?new Map(t):t}function Ea(t,n){var a;if(t.size===0)return t;const s=new Set;for(const o of n.messages)o.role==="toolResult"&&o.toolCallId&&s.add(o.toolCallId);const r=new Set(n.messages.flatMap(o=>o.content.flatMap(c=>c.type==="toolCall"&&typeof c.id=="string"?[c.id]:[])));for(const o of((a=n.streamingMessage)==null?void 0:a.content)??[])o.type==="toolCall"&&typeof o.id=="string"&&r.add(o.id);const i=new Map([...t].filter(([o,c])=>c.conversationId!==n.conversationId||c.parentToolCallId&&s.has(c.parentToolCallId)?!1:c.toolName==="bash"&&c.durationMs!==void 0?r.has(o):!s.has(o)));return i.size===t.size?t:i}function nu(t,n){var s,r,i,a,o,c,l,p;switch(n.type){case"status":return{...t,status:n.status,pendingDialogs:n.status==="closed"?[]:t.pendingDialogs,extensionUi:n.status==="closed"?{}:t.extensionUi,ready:n.status==="open"?t.ready:!1,agentSilence:n.status==="closed"?null:t.agentSilence,agentSilenceByConversation:n.status==="closed"?{}:t.agentSilenceByConversation,terminals:n.status==="closed"?[]:t.terminals};case"ready":return{...t,serverVersion:n.serverVersion,ready:!0,protocolMismatch:n.protocolVersion!==void 0&&n.protocolVersion!==Xd};case"snapshot":return{...t,ready:!0,state:n.state,...((s=t.state)==null?void 0:s.cwd)!==n.state.cwd?{sessions:[],files:null,conversationFilesChecked:null,fileContent:null,scmData:null,scmDiffData:null}:{},activeConversationId:n.state.conversationId,agentSilence:n.state.isStreaming?t.agentSilenceByConversation[n.state.conversationId]??null:null,liveOutputs:Na(t.liveOutputs,n.state),toolStatuses:Ea(t.toolStatuses,n.state),pendingEcho:null};case"snapshot_delta":{const u=t.state,f=n.msg;if(!u||u.conversationId!==f.conversationId||u.rev!==f.baseRev)return t;const k={...u,...f.state,messages:f.appended.length>0?[...u.messages,...f.appended]:u.messages};return{...t,ready:!0,state:k,agentSilence:k.isStreaming?t.agentSilenceByConversation[k.conversationId]??null:null,activeConversationId:k.conversationId,liveOutputs:Na(t.liveOutputs,k),toolStatuses:Ea(t.toolStatuses,k),pendingEcho:f.appended.length>0?null:t.pendingEcho}}case"tool_delta":{const u=t.liveOutputs.get(n.toolCallId),f=Bd((u==null?void 0:u.text)??"",n),k=new Map(t.liveOutputs);return k.set(n.toolCallId,{toolName:n.toolName,text:f,codemode:n.codemode??(u==null?void 0:u.codemode)}),{...t,liveOutputs:k}}case"message_delta":{const u=t.state;return!u||u.conversationId!==n.msg.conversationId?t:{...t,state:zd(u,n.msg)}}case"tool_status":return n.status.conversationId&&((r=t.state)==null?void 0:r.conversationId)!==n.status.conversationId?t:{...t,toolStatuses:new Map(t.toolStatuses).set(n.status.toolCallId,{...t.toolStatuses.get(n.status.toolCallId),...n.status})};case"notice":return{...t,notices:Mc(t.notices,n.notice)};case"agent_silence":{const u={...t.agentSilenceByConversation};return n.event.phase==="active"?delete u[n.event.conversationId]:u[n.event.conversationId]=n.event,{...t,agentSilenceByConversation:u,agentSilence:u[t.activeConversationId]??null}}case"reload_status":{const u=t.reloadEvents.findIndex(k=>k.requestId===n.event.requestId&&k.conversationId===n.event.conversationId),f=u<0?[...t.reloadEvents,n.event].slice(-40):t.reloadEvents.map((k,j)=>j===u?n.event:k);return{...t,reloadEvents:f}}case"dismiss_notice":return{...t,notices:t.notices.filter(u=>u.id!==n.id)};case"set_pending_echo":return{...t,pendingEcho:n.echo};case"clear_pending_echo":return{...t,pendingEcho:null};case"sessions":return{...t,sessions:n.sessions};case"conversations":return{...t,conversations:n.conversations,activeConversationId:n.activeId};case"projects":return{...t,projects:n.projects};case"dir_browse":return{...t,dirBrowse:n.dirBrowse};case"git_branch":return{...t,gitBranch:n.data};case"files":return{...t,files:n.files};case"conversation_files_checked":return{...t,conversationFilesChecked:n.result};case"file_changed":return{...t,fileChanged:{path:n.path}};case"prompt_result":return{...t,promptResult:n.result};case"file_result":return{...t,fileResult:n.result};case"file_content":return{...t,fileContent:n.content};case"models":return{...t,models:n.models,modelsLoading:n.loading};case"models_config":return{...t,modelsConfig:n.providers};case"provider_auth":return{...t,providerAuth:n.state};case"providers_status":return{...t,providers:n.providers};case"fetch_models_result":return{...t,fetchModelsResult:n.result};case"refresh_provider_result":return{...t,refreshProviderResult:n.result};case"clone_provider_result":return{...t,cloneProviderResult:n.result};case"install_result":return{...t,installResult:n.result};case"scm_data":return{...t,scmData:n.data,...n.data.type==="scm_data"&&n.data.kind==="diff"?{scmDiffData:n.data}:{}};case"file_search_result":return{...t,fileSearch:n.result};case"scm_changed":return{...t,scmDirty:t.scmDirty+1};case"path_completions":return{...t,pathCompletions:n.completions};case"component_updates_start":return{...t,componentUpdates:{type:"component_updates",requestId:n.requestId,cwd:n.cwd,phase:n.updating?"updating":"checking",items:n.updating&&((i=t.componentUpdates)==null?void 0:i.cwd)===n.cwd?t.componentUpdates.items:[]}};case"component_updates":return((a=t.componentUpdates)==null?void 0:a.requestId)!==n.result.requestId?t:{...t,componentUpdates:{...n.result,items:n.result.items.length?n.result.items:t.componentUpdates.items}};case"update_status":return{...t,update:n.status};case"extension_ui":{const u=n.message;return u.type==="dialog"?{...t,pendingDialogs:[...t.pendingDialogs.filter(f=>f.id!==u.id),u]}:u.type==="dialog_closed"?{...t,pendingDialogs:t.pendingDialogs.filter(f=>f.id!==u.id||f.conversationId!==u.conversationId)}:{...t,extensionUi:{...t.extensionUi,[u.conversationId]:{...t.extensionUi[u.conversationId],...u.type==="widgets"?{widgets:u.widgets}:u.type==="statuses"?{statuses:u.statuses}:{title:u.title}}}}}case"commands":return{...t,commands:n.commands,commandsPath:n.path};case"slash_commands":return{...t,slashCommands:n.commands};case"settings":return{...t,settings:n.settings};case"bg_servers":return{...t,bgServers:n.servers};case"plugins":return{...t,plugins:n.plugins,pluginsEpoch:n.epoch};case"terminal_add":return{...t,terminals:[...t.terminals,n.meta]};case"terminal_remove":return{...t,terminals:t.terminals.filter(u=>u.id!==n.id)};case"terminal_exit":return n.conversationId&&(t.activeConversationId||(o=t.state)!=null&&o.conversationId)&&n.conversationId!==(t.activeConversationId||((c=t.state)==null?void 0:c.conversationId))?t:{...t,terminals:t.terminals.map(u=>u.id===n.terminalId?{...u,running:!1,exitCode:n.exitCode}:u)};case"terminal_restart":return{...t,terminals:t.terminals.map(u=>u.id===n.terminalId?{...u,running:!0,exitCode:null}:u)};case"terminal_list":return n.conversationId&&(t.activeConversationId||(l=t.state)!=null&&l.conversationId)&&n.conversationId!==(t.activeConversationId||((p=t.state)==null?void 0:p.conversationId))?t:{...t,terminals:n.terminals.map(u=>{var f;return{...u,conversationId:n.conversationId??((f=t.state)==null?void 0:f.conversationId)??""}})};default:return t}}const Hr="pi-web-client-id";let Br=null;function fn(){if(Br)return Br;let t=(kt==null?void 0:kt.clientId)??null;try{t&&sessionStorage.setItem(Hr,t),t=t??sessionStorage.getItem(Hr),t||(t=Gt(),sessionStorage.setItem(Hr,t))}catch{t=t??Gt()}return Br=t,t}function su(){const t=location.protocol==="https:"?"wss:":"ws:";return Tn(`${t}//${location.host}/ws`)}function ru(){var le,O,ge,pe,Ae,ae,Te;const t=et(),n=d.useRef(t);n.current=t;const[s,r]=d.useReducer(nu,{status:"connecting",ready:!1,state:null,liveOutputs:new Map,toolStatuses:new Map,notices:[],agentSilence:null,agentSilenceByConversation:{},sessions:[],conversations:[],activeConversationId:"",projects:[],dirBrowse:null,files:null,conversationFilesChecked:null,gitBranch:null,fileChanged:null,fileContent:null,promptResult:null,fileResult:null,models:[],modelsLoading:!1,modelsConfig:[],providers:[],installResult:null,pathCompletions:[],update:null,componentUpdates:null,providerAuth:null,extensionUi:{},pendingDialogs:[],widgets:[],statuses:[],dialog:null,commands:[],commandsPath:"",slashCommands:[],terminals:[],bgServers:[],settings:null,fetchModelsResult:null,refreshProviderResult:null,cloneProviderResult:null,scmData:null,scmDiffData:null,fileSearch:null,scmDirty:0,plugins:[],pluginsEpoch:0,protocolMismatch:!1,pendingEcho:null,reloadEvents:Zd()});d.useEffect(()=>{try{sessionStorage.setItem(Vo,JSON.stringify(s.reloadEvents))}catch{}},[s.reloadEvents]);const i=d.useRef(s);i.current=s;const a=d.useRef(new Ud),[o,c]=d.useState(null),l=d.useRef(o),p=d.useRef(""),u=d.useRef(!1),[f,k]=d.useState(!1),j=d.useRef(null),[R,E]=d.useState(null);d.useEffect(()=>{var Z;o&&j.current===o.id&&((Z=s.state)==null?void 0:Z.cwd)===p.current&&(l.current=null,c(null))},[s.state,o]),d.useEffect(()=>{if(!(o!=null&&o.display))return;const Z=requestAnimationFrame(()=>{performance.clearMeasures("project-switch:cached-content"),performance.measure("project-switch:cached-content","project-switch:click")});return()=>cancelAnimationFrame(Z)},[o]);const A=d.useRef(null),N=d.useRef(tu()),T=d.useRef(0),y=d.useRef(null),M=d.useRef(!0),b=d.useRef(0),F=d.useRef(0),U=d.useRef(null),ce=d.useRef(new Map),ie=d.useRef(null),W=()=>{ie.current||(ie.current=setTimeout(()=>{ie.current=null;const Z=A.current;Z&&Z.readyState===WebSocket.OPEN&&Z.send(JSON.stringify({type:"get_state"}))},300))},ve=(Z,Fe)=>{var J;const z=ce.current,G=z.get(Z);if(G!==void 0&&Fe!==G+1){const Ee=i.current,V=Ee.activeConversationId||((J=Ee.state)==null?void 0:J.conversationId);Z===V&&W()}z.set(Z,Fe)},Se=d.useCallback((Z,Fe)=>{const z=++F.current;r({type:"notice",notice:{id:z,level:Z,text:Fe}})},[]),$=d.useCallback(Z=>{var z,G;const Fe=A.current;if(Z.type==="abort"&&(!Fe||Fe.readyState!==WebSocket.OPEN||!u.current)){const J=(z=i.current.state)==null?void 0:z.conversationId;return J?(U.current=J,!0):!1}if(Fe&&Fe.readyState===WebSocket.OPEN){if(!u.current&&Z.type!=="get_state")return!1;if((Z.type==="check_component_updates"||Z.type==="update_component")&&r({type:"component_updates_start",requestId:Z.requestId,cwd:((G=i.current.state)==null?void 0:G.cwd)??"",updating:Z.type==="update_component"}),Z.type==="set_cwd"){const J=i.current,Ee=a.current.get(Z.path);!l.current&&J.state&&a.current.set(J.state.cwd,{state:J.state,sessions:J.sessions,files:J.files}),E(null);const V=Gt(),Le={id:V,path:Z.path,display:Ee};l.current=Le,c(Le),performance.clearMarks("project-switch:click"),performance.mark("project-switch:click"),Z={...Z,requestId:V}}else if(l.current&&Z.type!=="get_state")return!1;return Fe.send(JSON.stringify(Z)),!0}return!1},[]),$e=d.useCallback(()=>{if(!M.current)return;r({type:"status",status:"connecting"});const Z=new WebSocket(su());A.current=Z,Z.onopen=()=>{A.current===Z&&(r({type:"status",status:"open"}),T.current=0,b.current=Date.now(),Z.send(JSON.stringify({type:"hello",clientId:fn()})))},Z.onmessage=Fe=>{var G,J,Ee,V,Le,xe;if(A.current!==Z)return;b.current=Date.now();let z;try{z=JSON.parse(Fe.data)}catch{return}switch(z.type){case"node_event":window.dispatchEvent(new CustomEvent("pi-node-event",{detail:z}));break;case"ready":r({type:"ready",serverVersion:z.serverVersion,protocolVersion:z.protocolVersion}),Z.send(JSON.stringify({type:"get_state"})),Z.send(JSON.stringify({type:"list_models"})),Z.send(JSON.stringify({type:"list_commands"})),Z.send(JSON.stringify({type:"get_commands"})),Z.send(JSON.stringify({type:"check_update"}));break;case"cwd_result":z.requestId===((G=l.current)==null?void 0:G.id)&&(p.current=z.cwd,j.current=z.requestId,z.ok||E(l.current.path),!z.ok||((J=i.current.state)==null?void 0:J.cwd)===z.cwd?(l.current=null,c(null)):Z.send(JSON.stringify({type:"get_state"})));break;case"snapshot":if(u.current=!0,k(!0),l.current||(p.current=z.state.cwd),l.current&&j.current===l.current.id&&p.current===z.state.cwd&&(l.current=null,c(null)),ce.current=new Map,r({type:"snapshot",state:{...z.state,recovery:ka(z.state.recovery)}}),U.current){const be=U.current===z.state.conversationId&&z.state.isStreaming;U.current=null,be&&Z.send(JSON.stringify({type:"abort"}))}break;case"snapshot_delta":{const be=i.current.state;(!be||be.conversationId!==z.conversationId||be.rev!==z.baseRev)&&W(),r({type:"snapshot_delta",msg:{...z,state:{...z.state,recovery:ka(z.state.recovery)}}});break}case"tool_delta":ve(z.conversationId,z.seq),r({type:"tool_delta",toolCallId:z.toolCallId,toolName:z.toolName,delta:z.delta,replace:z.replace,codemode:z.codemode});break;case"tool_status":r({type:"tool_status",status:z});break;case"message_delta":{ve(z.conversationId,z.seq),r({type:"message_delta",msg:z});break}case"notice":{(!z.conversationId||z.conversationId===i.current.activeConversationId)&&/MCP|mcp/i.test(z.text)&&window.dispatchEvent(new CustomEvent("pi-mcp-notice",{detail:z.text}));const be=++F.current;r({type:"notice",notice:{id:be,conversationId:z.conversationId,level:z.level,text:z.text}});break}case"agent_silence":r({type:"agent_silence",event:z});break;case"reload_status":r({type:"reload_status",event:z});break;case"sessions":if(z.cwd!==p.current)break;r({type:"sessions",sessions:z.sessions});break;case"conversations":((Ee=i.current.state)==null?void 0:Ee.conversationId)!==z.activeId&&W(),r({type:"conversations",conversations:z.conversations,activeId:z.activeId});break;case"projects":r({type:"projects",projects:z.projects});break;case"dir_browse":r({type:"dir_browse",dirBrowse:{path:z.path,parent:z.parent,dirs:z.dirs,truncated:z.truncated}});break;case"git_branch":if(z.cwd!==p.current||l.current)break;r({type:"git_branch",data:z});break;case"files":if(z.cwd!==p.current)break;r({type:"files",files:z});break;case"conversation_files_checked":if(z.cwd!==p.current)break;r({type:"conversation_files_checked",result:z});break;case"file_changed":r({type:"file_changed",path:z.path});break;case"prompt_result":r({type:"prompt_result",result:z});break;case"file_result":r({type:"file_result",result:z});break;case"file_content":if(z.cwd!==p.current||l.current)break;r({type:"file_content",content:z});break;case"models":r({type:"models",models:z.models,loading:!1});break;case"models_config":r({type:"models_config",providers:z.providers});break;case"native_mcp_result":window.dispatchEvent(new CustomEvent("pi-native-mcp-event",{detail:z}));break;case"provider_auth":r({type:"provider_auth",state:z.state});break;case"providers_status":r({type:"providers_status",providers:z.providers});break;case"fetch_models_result":r({type:"fetch_models_result",result:{reqId:z.reqId,ok:z.ok,models:z.models,error:z.error}});break;case"refresh_provider_result":r({type:"refresh_provider_result",result:{reqId:z.reqId,ok:z.ok,added:z.added,total:z.total,error:z.error}});break;case"clone_provider_result":r({type:"clone_provider_result",result:{reqId:z.reqId,ok:z.ok,config:z.config,error:z.error}});break;case"scm_data":if(z.cwd!==p.current||l.current)break;r({type:"scm_data",data:z});break;case"search_files_result":if(z.cwd!==p.current||l.current)break;r({type:"file_search_result",result:{reqId:z.reqId,ok:z.ok,results:z.results,truncated:z.truncated}});break;case"scm_changed":r({type:"scm_changed"});break;case"install_result":r({type:"install_result",result:z});break;case"path_completions":r({type:"path_completions",completions:z.completions});break;case"component_updates":r({type:"component_updates",result:z});break;case"update_status":r({type:"update_status",status:z});break;case"widgets":case"statuses":case"dialog":case"dialog_closed":case"extension_title":r({type:"extension_ui",message:z});break;case"extension_ui_reset":_d(z.conversationId);break;case"tree":case"tree_changed":case"tree_open":case"tree_content_result":case"tree_preview_result":case"tree_navigate_result":if(z.type==="tree_navigate_result"){z.reqId.startsWith("edit-")&&z.status!=="ok"&&r({type:"notice",notice:{id:++F.current,conversationId:z.conversationId,level:"warning",text:z.error??n.current(z.status==="busy"?"editBusy":"editFailed")}});const be=[...((V=z.restoredQueue)==null?void 0:V.steering)??[],...((Le=z.restoredQueue)==null?void 0:Le.followUp)??[]];z.editorText&&!z.reqId.startsWith("edit-")&&be.push(z.editorText),ba({id:z.reqId,conversationId:z.conversationId,text:be.join(`
26
+
27
+ `),images:(xe=z.restoredQueue)==null?void 0:xe.images})}Fd(z);break;case"queue_recalled":ba({id:z.requestId,conversationId:z.conversationId,text:z.text,images:z.images}),Z.send(JSON.stringify({type:"queue_recall_ack",conversationId:z.conversationId,requestId:z.requestId}));break;case"extension_editor":Hd(z);break;case"terminal_output":N.current.write(z.conversationId??i.current.activeConversationId,z.terminalId,z.data);break;case"terminal_exit":r({type:"terminal_exit",conversationId:z.conversationId,terminalId:z.terminalId,exitCode:z.exitCode});break;case"terminal_list":r({type:"terminal_list",conversationId:z.conversationId,terminals:z.terminals});break;case"commands":if(z.cwd!==p.current||l.current)break;r({type:"commands",commands:z.commands,path:z.path});break;case"slash_commands":r({type:"slash_commands",commands:z.commands});break;case"settings_state":r({type:"settings",settings:z.settings});break;case"bg_servers":r({type:"bg_servers",servers:z.servers});break;case"plugins":r({type:"plugins",plugins:z.plugins,epoch:z.epoch});break;case"plugin_data":Vd(z.pluginId,z.payload);break}},Z.onclose=()=>{if(A.current===Z&&(A.current=null),N.current.clear(),!M.current||A.current&&A.current!==Z)return;l.current=null,c(null),u.current=!1,k(!1),r({type:"status",status:"closed"});const Fe=Math.min(1e3*2**T.current,1e4);T.current+=1,y.current=setTimeout(()=>{y.current=null,$e()},Fe)},Z.onerror=()=>{}},[]);d.useEffect(()=>{M.current=!0,$e();const Z=setInterval(()=>{if(!M.current)return;const Fe=A.current;Fe&&Fe.readyState===WebSocket.OPEN&&Date.now()-b.current>3e4&&Fe.close()},5e3);return()=>{var Fe;M.current=!1,clearInterval(Z),ie.current&&(clearTimeout(ie.current),ie.current=null),y.current&&(clearTimeout(y.current),y.current=null),(Fe=A.current)==null||Fe.close(),A.current=null}},[$e]);const L=d.useCallback(Z=>r({type:"dismiss_notice",id:Z}),[]),q=d.useCallback((Z,Fe)=>r({type:"set_pending_echo",echo:{conversationId:Z,text:Fe,ts:Date.now()}}),[]),fe=d.useCallback(Z=>r({type:"terminal_add",meta:Z}),[]),je=d.useCallback(Z=>r({type:"terminal_remove",id:Z}),[]),ne=d.useCallback(Z=>r({type:"terminal_restart",terminalId:Z}),[]),Pe=d.useCallback((Z,Fe,z)=>N.current.register(Z,Fe,z),[]),B=d.useMemo(()=>({create:fe,close:je,register:Pe,restart:ne}),[fe,je,Pe,ne]),we=d.useRef({chat:s,send:$,pushNotice:Se,dismissNotice:L,setPendingEcho:q,terminal:B});we.current={chat:s,send:$,pushNotice:Se,dismissNotice:L,setPendingEcho:q,terminal:B};const re=s.extensionUi[s.activeConversationId];d.useEffect(()=>{document.title=(re==null?void 0:re.title)||"pi-harness"},[re==null?void 0:re.title]);const Ie={...s,notices:s.notices.filter(Z=>!Z.conversationId||Z.conversationId===s.activeConversationId),widgets:(re==null?void 0:re.widgets)??[],statuses:(re==null?void 0:re.statuses)??[],dialog:s.pendingDialogs.find(Z=>Z.conversationId===s.activeConversationId)??null},_=o?{...s,state:((le=o.display)==null?void 0:le.state)??null,sessions:((O=o.display)==null?void 0:O.sessions)??[],files:((ge=o.display)==null?void 0:ge.files)??null,activeConversationId:((Ae=(pe=o.display)==null?void 0:pe.state)==null?void 0:Ae.conversationId)??`pending:${o.path}`,ready:!1,liveOutputs:new Map,toolStatuses:new Map,dialog:null}:{...Ie,ready:s.ready&&f,files:s.files??((Te=a.current.get(((ae=s.state)==null?void 0:ae.cwd)??""))==null?void 0:Te.files)??null};return{...we.current,chat:_,switching:(o==null?void 0:o.path)??null,switchError:R}}function iu({state:t,connected:n,send:s}){var ae,Te,Z,Fe,z,G,J,Ee;const r=et(),[i,a]=d.useState(!1),[o,c]=d.useState("tree"),[l,p]=d.useState("default"),[u,f]=d.useState(""),[k,j]=d.useState([]),[R,E]=d.useState(!1),[A,N]=d.useState(new Set),[T,y]=d.useState(),[M,b]=d.useState(),[F,U]=d.useState(),[ce,ie]=d.useState(),[W,ve]=d.useState(),[Se,$]=d.useState(""),[$e,L]=d.useState(!1),[q,fe]=d.useState(!1),je=d.useRef(t);je.current=t;const ne=d.useRef(new Map),Pe=d.useRef(""),B=d.useRef(""),we=d.useRef(""),re=d.useCallback((V,Le=!1)=>{["tree_get","tree_preview","tree_content"].includes(V.type)||(we.current=V.reqId),ne.current.set(V.reqId,{type:V.type,targetId:"targetId"in V?V.targetId:"entryId"in V?V.entryId:void 0,copy:Le}),s(V)||(ne.current.delete(V.reqId),$(r("treeDisconnected")),L(!1),fe(!1))},[s,r]),Ie=d.useCallback(()=>{if(!(t!=null&&t.conversationId)||!n||!i)return;const V=Gt();Pe.current=V,fe(!0),re({type:"tree_get",conversationId:t.conversationId,reqId:V,filter:o==="fork"?"user-only":l,query:u})},[t==null?void 0:t.conversationId,n,i,l,u,o,re]);d.useEffect(()=>{const V=setTimeout(Ie,120);return()=>clearTimeout(V)},[Ie,(ae=t==null?void 0:t.tree)==null?void 0:ae.revision]),d.useEffect(()=>{var V,Le;ne.current.clear(),j([]),y(void 0),b(void 0),ie(void 0),ve(void 0),$(""),L(!1),N(new Set),p(((Le=(V=je.current)==null?void 0:V.tree)==null?void 0:Le.filterMode)??"default")},[t==null?void 0:t.conversationId]),d.useEffect(()=>{n||(ne.current.clear(),L(!1),fe(!1))},[n]);const _=d.useCallback(V=>{const Le=je.current;Le&&(L(!0),$(""),re({type:"tree_navigate",conversationId:Le.conversationId,reqId:Gt(),...V}))},[re]),le=d.useCallback((V,Le=!1)=>{var Ce,ye,ze;const xe=je.current;if(!xe||(Ce=xe.tree)!=null&&Ce.verifying||(ye=xe.tree)!=null&&ye.externallyModified)return;const be={targetId:V,summary:"none",customInstructions:"",abortRunning:!1};if((Le||(ze=xe.tree)!=null&&ze.skipSummaryPrompt)&&!xe.isStreaming){_(be);return}b(be),U(void 0),$("");const nt=Gt();B.current=nt,re({type:"tree_preview",conversationId:xe.conversationId,reqId:nt,targetId:V})},[re,_]);d.useEffect(()=>{const V=()=>{c("tree"),a(be=>!be)},Le=be=>{(be.ctrlKey||be.metaKey)&&be.shiftKey&&be.key.toLowerCase()==="t"&&(be.preventDefault(),V())},xe=be=>{var Ce;const nt=be.detail;((Ce=je.current)==null?void 0:Ce.conversationId)===nt.conversationId&&le(nt.targetId,!0)};return window.addEventListener("pi-tree-open",V),window.addEventListener("keydown",Le),window.addEventListener("pi-tree-navigate",xe),()=>{window.removeEventListener("pi-tree-open",V),window.removeEventListener("keydown",Le),window.removeEventListener("pi-tree-navigate",xe)}},[le]),d.useEffect(()=>{const V=Le=>{var nt;const xe=Le.detail;if(xe.conversationId!==((nt=je.current)==null?void 0:nt.conversationId))return;if(xe.type==="tree_open"){c(xe.mode),a(!0);return}if(xe.type==="tree_changed"){Ie();return}const be=ne.current.get(xe.reqId);ne.current.delete(xe.reqId),!((be==null?void 0:be.type)==="tree_get"&&xe.reqId!==Pe.current)&&((be==null?void 0:be.type)==="tree_preview"&&xe.reqId!==B.current||!be&&!xe.reqId.startsWith("command-")||(xe.type==="tree"&&xe.reqId===Pe.current&&(j(xe.nodes),E(xe.truncated),fe(!1)),xe.type==="tree_preview_result"&&xe.reqId===B.current&&U(xe.entryCount),xe.type==="tree_content_result"&&(be!=null&&be.copy?navigator.clipboard.writeText(xe.content).catch(()=>ve({id:xe.entryId,text:xe.content,toolCallId:xe.toolCallId})):ve({id:xe.entryId,text:xe.content,toolCallId:xe.toolCallId})),xe.type==="tree_navigate_result"&&(xe.reqId===we.current&&L(!1),xe.reqId===Pe.current&&fe(!1),xe.status==="ok"?((be==null?void 0:be.type)==="tree_navigate"&&(y(be.targetId),b(void 0)),(be==null?void 0:be.type)==="tree_label"&&ie(void 0),Ie()):$(xe.error??r(xe.status==="busy"?"treeBusy":xe.status==="cancelled"?"treeCancelled":xe.status==="aborted"?"treeAborted":"treeFailed")))))};return window.addEventListener("pi-tree-response",V),()=>window.removeEventListener("pi-tree-response",V)},[Ie,r]);const O=d.useMemo(()=>{const V=new Set;return k.filter(Le=>Le.visibleParentId&&(A.has(Le.visibleParentId)||V.has(Le.visibleParentId))?(V.add(Le.id),!1):!0)},[k,A]),ge=V=>{L(!0),$(""),re(V)},pe=!n||$e||((Te=t==null?void 0:t.tree)==null?void 0:Te.busy)||((Z=t==null?void 0:t.tree)==null?void 0:Z.verifying)||((Fe=t==null?void 0:t.tree)==null?void 0:Fe.externallyModified),Ae=()=>({conversationId:(t==null?void 0:t.conversationId)??"",reqId:Gt()});return e.jsxs(e.Fragment,{children:[i&&e.jsxs("aside",{className:"session-tree-panel","aria-label":r("treeTitle"),children:[e.jsxs("header",{children:[e.jsx(hs,{}),e.jsx("h2",{children:r(o==="fork"?"treeFork":"treeTitle")}),e.jsx("button",{onClick:()=>a(!1),"aria-label":r("close"),children:e.jsx(Wt,{})})]}),e.jsxs("div",{className:"session-tree-controls",children:[e.jsx("select",{"aria-label":r("treeFilter"),value:o==="fork"?"user-only":l,disabled:o==="fork",onChange:V=>p(V.target.value),children:["default","no-tools","user-only","labeled-only","all"].map(V=>e.jsx("option",{value:V,children:r(`treeFilter_${V}`)},V))}),e.jsx("input",{"aria-label":r("treeSearch"),placeholder:r("treeSearch"),value:u,onChange:V=>f(V.target.value)})]}),((z=t==null?void 0:t.tree)==null?void 0:z.verifying)&&e.jsx("div",{role:"status",children:r("treeVerifying")}),((G=t==null?void 0:t.tree)==null?void 0:G.externallyModified)&&e.jsxs("div",{className:"tree-warning",role:"alert",children:[e.jsx("p",{children:r("treeExternal")}),e.jsx("button",{disabled:!n||$e||t.isStreaming,onClick:()=>ge({type:"session_reopen",...Ae()}),children:r("treeReopen")})]}),Se&&e.jsx("p",{role:"alert",className:"tree-warning",children:Se}),R&&e.jsx("p",{className:"tree-warning",children:r("treeTruncated")}),e.jsxs("div",{className:"session-tree-list","aria-busy":q,children:[!k.length&&e.jsx("p",{className:"tree-empty",children:r(q?"loadingSession":"treeEmpty")}),O.map((V,Le)=>e.jsxs("section",{className:`tree-node${V.onActivePath?" active-path":""}${V.id===T?" selected":""}${Le===0||O[Le-1].rootId!==V.rootId?" root-start":""}`,style:{paddingLeft:`${12+Math.min(V.depth,18)*12}px`},"data-entry-id":V.id,children:[e.jsx("span",{className:"tree-connector","aria-hidden":"true",style:{width:`${Math.min(V.depth,18)*12}px`}}),e.jsxs("div",{className:"tree-node-heading",children:[e.jsx("button",{className:"tree-fold",disabled:!V.childCount,"aria-expanded":!A.has(V.id),"aria-label":r("treeFold"),onClick:()=>N(xe=>{const be=new Set(xe);return be.has(V.id)?be.delete(V.id):be.add(V.id),be}),children:V.childCount?A.has(V.id)?e.jsx(_t,{}):e.jsx(Qt,{}):e.jsx("span",{children:V.isLeaf?"●":"·"})}),e.jsxs("button",{className:"tree-node-preview",onClick:()=>re({type:"tree_content",...Ae(),entryId:V.id}),children:[e.jsxs("small",{children:[V.kind==="compaction"?e.jsx(ma,{}):V.kind==="branchSummary"?e.jsx(hs,{}):null,V.isLeaf?"● ":"",r(`treeKind_${V.kind}`),V.childCount>1?` · ${V.childCount}`:""]}),e.jsx("span",{children:V.preview||"…"})]}),V.label&&e.jsxs("span",{className:"tree-label",children:[e.jsx(ia,{}),V.label]})]}),e.jsxs("div",{className:"tree-node-actions",children:[e.jsx("button",{disabled:pe,onClick:()=>o==="fork"?ge({type:"session_fork",...Ae(),entryId:V.id,position:"before"}):le(V.id),children:r(o==="fork"?"treeFork":"treeNavigate")}),e.jsxs("button",{disabled:pe||(t==null?void 0:t.isStreaming),onClick:()=>ge({type:"session_fork",...Ae(),entryId:V.id,position:"at"}),children:[e.jsx(hs,{}),r("treeForkAt")]}),e.jsxs("button",{disabled:pe,onClick:()=>ie({id:V.id,value:V.label??""}),children:[e.jsx(ia,{}),r("treeLabel")]}),e.jsx("button",{disabled:!n,onClick:()=>re({type:"tree_content",...Ae(),entryId:V.id},!0),"aria-label":r("copy"),children:e.jsx(ws,{})})]})]},V.id))]}),e.jsxs("footer",{children:[e.jsxs("span",{children:[k.length," · ",r("treeNodes")]}),e.jsxs("button",{disabled:pe||(t==null?void 0:t.isStreaming),onClick:()=>ge({type:"session_clone",...Ae()}),children:[e.jsx(ma,{}),r("treeClone")]})]})]}),!i&&Se&&e.jsxs("div",{className:"tree-floating-error",role:"alert",children:[Se,e.jsx("button",{onClick:()=>$(""),"aria-label":r("close"),children:e.jsx(Wt,{})})]}),M&&!$e&&e.jsx("div",{className:"tree-modal-backdrop",children:e.jsxs("section",{className:"tree-dialog",role:"dialog","aria-modal":"true","aria-label":r("treeNavigate"),children:[e.jsx("h3",{children:r("treeNavigate")}),F!==void 0&&e.jsx("p",{children:r("treePreviewCount",{n:F})}),["none","default","custom"].map(V=>e.jsxs("label",{children:[e.jsx("input",{type:"radio",name:"tree-summary",value:V,checked:M.summary===V,disabled:$e,onChange:()=>b({...M,summary:V})}),r(`treeSummary_${V}`)]},V)),M.summary==="custom"&&e.jsx("textarea",{"aria-label":r("treeInstructions"),placeholder:r("treeInstructions"),value:M.customInstructions,onChange:V=>b({...M,customInstructions:V.target.value})}),(t==null?void 0:t.isStreaming)&&e.jsxs("label",{children:[e.jsx("input",{type:"checkbox",checked:M.abortRunning,onChange:V=>b({...M,abortRunning:V.target.checked})}),r("treeStopConfirm")]}),Se&&e.jsx("p",{role:"alert",children:Se}),e.jsxs("div",{className:"tree-dialog-actions",children:[e.jsx("button",{disabled:$e,onClick:()=>b(void 0),children:r("cancel")}),e.jsx("button",{className:"primary",disabled:pe||!!(t!=null&&t.isStreaming)&&!M.abortRunning,onClick:()=>_(M),children:r("treeNavigate")})]})]})}),ce&&e.jsx("div",{className:"tree-modal-backdrop",children:e.jsxs("form",{className:"tree-dialog",role:"dialog","aria-modal":"true","aria-label":r("treeLabel"),onSubmit:V=>{V.preventDefault(),ge({type:"tree_label",...Ae(),entryId:ce.id,label:ce.value.trim()||null})},children:[e.jsx("h3",{children:r("treeLabel")}),e.jsx("input",{autoFocus:!0,maxLength:200,"aria-label":r("treeLabel"),value:ce.value,onChange:V=>ie({...ce,value:V.target.value})}),e.jsx("p",{children:r("treeLabelClear")}),Se&&e.jsx("p",{role:"alert",children:Se}),e.jsxs("div",{className:"tree-dialog-actions",children:[e.jsx("button",{type:"button",onClick:()=>ie(void 0),children:r("cancel")}),e.jsx("button",{className:"primary",disabled:$e||!n||((J=t==null?void 0:t.tree)==null?void 0:J.verifying)||((Ee=t==null?void 0:t.tree)==null?void 0:Ee.externallyModified),children:r("save")})]})]})}),W&&e.jsx("div",{className:"tree-modal-backdrop",children:e.jsxs("section",{className:"tree-dialog tree-content-dialog",role:"dialog","aria-modal":"true","aria-label":r("treeContent"),children:[e.jsx("h3",{children:r("treeContent")}),e.jsx("pre",{children:W.text}),W.toolCallId&&t&&e.jsx(Js,{url:`/api/tool-output?${new URLSearchParams({clientId:fn(),conversationId:t.conversationId,toolCallId:W.toolCallId})}`}),e.jsx("button",{onClick:()=>ve(void 0),children:r("close")})]})})]})}function au({state:t,send:n,connected:s}){var A,N,T,y,M,b,F;const r=et(),[,i]=d.useState(0),[a,o]=d.useState(),c=performance.now(),l=t==null?void 0:t.recovery,p=(l==null?void 0:l.summary)??(l==null?void 0:l.retry)??(l==null?void 0:l.compaction)??(l==null?void 0:l.branch);if(d.useEffect(()=>{if(!p)return;const U=setInterval(()=>i(ce=>ce+1),250);return()=>clearInterval(U)},[p]),!t)return null;if((A=t.tree)!=null&&A.verifying)return e.jsx("div",{className:"agent-silence",role:"status",children:r("treeVerifying")});const u=(l==null?void 0:l.compaction)??(p||l==null?void 0:l.lastCompaction);if(!p&&!u)return null;const f=p||l==null?void 0:l.lastCompaction;if(f&&f.id===a)return null;const k=((N=l==null?void 0:l.summary)==null?void 0:N.deadline)??((T=l==null?void 0:l.retry)==null?void 0:T.deadline),j=((y=l==null?void 0:l.summary)==null?void 0:y.attempt)??((M=l==null?void 0:l.retry)==null?void 0:M.attempt),R=((b=l==null?void 0:l.summary)==null?void 0:b.maxAttempts)??((F=l==null?void 0:l.retry)==null?void 0:F.maxAttempts),E=l!=null&&l.summary?l.summary.phase==="waiting"?"recoverySummaryWaiting":"recoverySummaryRunning":l!=null&&l.retry?l.retry.phase==="running"||c>=(l.retry.deadline??1/0)?"recoveryRunning":"recoveryWaiting":l!=null&&l.branch?"treeSummarizing":"recoveryCompacting";return e.jsxs("div",{className:"agent-silence",role:"status",children:[e.jsxs("span",{children:[r(f?f.status==="completed"?"compactionCompleted":f.status==="aborted"?"compactionAborted":"compactionFailed":E),u&&` · ${r(u.reason==="manual"?"compactionManual":u.reason==="threshold"?"compactionThreshold":"compactionOverflow")}`,(u==null?void 0:u.tokensBefore)!==void 0&&` · ${u.tokensBefore.toLocaleString()} tokens`,(f==null?void 0:f.tokensAfter)!==void 0&&` → ≈${f.tokensAfter.toLocaleString()} tokens`,(f==null?void 0:f.error)&&` · ${f.error}`,s&&k!==void 0&&k>c&&` · ${Math.max(0,Math.ceil((k-c)/1e3))}s`,j!==void 0&&` · ${j}/${R}`]}),p&&e.jsx("button",{disabled:!s,onClick:()=>n({type:"cancel_recovery",conversationId:t.conversationId,operationId:p.id}),children:r("cancel")}),f&&e.jsx("button",{onClick:()=>o(f.id),children:r("close")})]})}function ai({text:t}){return e.jsx(e.Fragment,{children:t.split(/(https?:\/\/[^\s<>]+)/g).map((n,s)=>{try{const r=new URL(n);if(r.protocol==="https:"||r.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(r.hostname))return e.jsx("a",{href:n,target:"_blank",rel:"noreferrer",children:n},s)}catch{}return n})})}class Ko extends Error{constructor(n){super(n.error),this.detail=n}}async function En(t,n,s={},r){const i=await fetch(Tn("/api/wiki"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...s,clientId:fn(),cwd:t,action:n}),signal:r}),a=await i.json();if(!i.ok)throw new Ko({...a,error:a.error||i.statusText});return a}function Ur(t,n,s=!1){return Tn("/api/wiki-media?"+new URLSearchParams({clientId:fn(),cwd:t,path:n,...s?{download:"1"}:{}}))}const Go=/^(?:\*\*([\p{L}\p{N}_ -]{1,40})[::]\*\*|(?:\*\*)?([\p{L}\p{N}_ -]{1,40})(?:\*\*)?[::])\s*(.+)$/u,Jo=t=>t.replace(/(?:\\| {2,})$/,"").trim();function ou(t,n){var a;let s=!1,r=!1;const i=/[^\n]*(?:\n|$)/g;i.lastIndex=n;for(let o=i.exec(t);o&&o[0];o=i.exec(t)){const c=Jo(o[0]);if(c){if(!r&&!s&&/^# /.test(c)){s=!0;continue}if(r=!0,!Go.test(c)){const l=o.index+o[0].length,p=((a=t.slice(l).match(/^ {0,3}(?:=+|-+)[ \t]*(?:\r?\n|$)/))==null?void 0:a[0])??"",u=o[0].replace(/^[ \t]{4,}/," ");return t.slice(0,o.index)+u.slice(0,256).trimEnd()+`
28
+ `+p}}}return t}function Qo(t){var o,c;const n=((o=t.match(/^---\r?\n[\s\S]*?\r?\n(?:---|\.\.\.)(?:\r?\n|$)/))==null?void 0:o[0].length)??0,s=ou(t,n),r=Tr().use(Rr).parse(s).children.filter(l=>{var p;return(((p=l.position)==null?void 0:p.start.offset)??0)>=n});((c=r[0])==null?void 0:c.type)==="heading"&&r[0].depth===1&&r.shift();const i=[],a=[];for(const l of r){if(l.type!=="paragraph")break;const p=l.position.start.offset,u=l.position.end.offset,f=t.slice(p,u).split(/\r?\n/).map(k=>Go.exec(Jo(k)));if(f.some(k=>!k))break;for(const k of f)i.push({key:(k[1]??k[2]).trim(),value:k[3]});a.push({start:p,end:u})}return i.length>=2?{rows:i,ranges:a}:{rows:[],ranges:[]}}var mn=go();const lu=Tr().use(Rr);function oi(t){var n;return["code","html","definition"].includes(t.type)?"":t.value??((n=t.children)==null?void 0:n.map(oi).join(""))??""}function Yo(t,n){var s;n(t),["code","inlineCode","html","definition"].includes(t.type)||(s=t.children)==null||s.forEach(r=>Yo(r,n))}function Ta(t){const n=t.trim();if(n.startsWith('"')&&n.endsWith('"'))try{return JSON.parse(n)}catch{}return n.replace(/^(['"])([\s\S]*)\1$/,"$2").replaceAll("''","'")}function Xo(t){var E;const n=/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/.exec(t),s=n?t.slice(n[0].length):t,r=(n==null?void 0:n[1])??"",i=new Set,a=A=>{const N=Ta(A).replace(/^#/,"").trim();N&&!/^(?:[a-f0-9]{3}|[a-f0-9]{4}|[a-f0-9]{6}|[a-f0-9]{8})$/i.test(N)&&i.add(N)},o=/^tags?:[ \t]*(.*)$/m.exec(r);if(o!=null&&o[1].trim())for(const A of o[1].replace(/^\[|\]$/g,"").split(/[,\s]+/))a(A);if(o&&!o[1].trim())for(const A of r.slice(o.index+o[0].length).split(/\r?\n/)){if(!A.trim())continue;const N=/^\s*-\s+(.+)$/.exec(A);if(!N)break;a(N[1])}const c=lu.parse(s);let l;Yo(c,A=>{var N;if(!l&&A.type==="heading"&&A.depth===1&&(l=A),A.type==="text"&&((N=A.position)==null?void 0:N.start.offset)!==void 0&&A.position.end.offset!==void 0){const T=A.position.start.offset,y=s.slice(T,A.position.end.offset);for(const M of y.matchAll(/(?:^|\s)#([\p{L}\p{N}_/-]+)/gu))M.index===0&&y.startsWith("#")&&T>0&&!/\s/.test(s[T-1])||a(M[1])}});const p=l?oi(l).trim():void 0,u=Ta(((E=/^title:[ \t]*(.*)$/m.exec(r))==null?void 0:E[1])??"")||p;let f=s;if(u&&p===u.trim()&&(l!=null&&l.position)){const{start:A,end:N}=l.position;A.offset!==void 0&&N.offset!==void 0&&(f=s.slice(0,A.offset)+s.slice(N.offset))}const k=c.children.map(A=>oi(A)).join(" "),j=(k.match(new RegExp("\\p{Script=Han}","gu"))??[]).length,R=(k.replace(new RegExp("\\p{Script=Han}","gu")," ").match(/[\p{L}\p{N}]+(?:['’-][\p{L}\p{N}]+)*/gu)??[]).length;return{tags:[...i].slice(0,100),title:u,body:s,readingBody:f,minutes:Math.max(1,Math.ceil(j/400+R/200))}}const cu=t=>(t.split("/").at(-1)??"").replace(/\.(md|txt)$/i,"");function du(t){const n=new Map;for(const s of t){const r=cu(s),i=n.get(r);i?i.push(s):n.set(r,[s])}return{paths:new Set(t),byName:n}}function Ra(t,n,s){let r;try{r=decodeURIComponent(n.split("|")[0].split("#")[0]).replaceAll("\\","/")}catch{return}if(!r||/^(?:[a-z]+:|\/)/i.test(r))return;const i=l=>{const p=[];for(const u of l.split("/"))if(u===".."){if(!p.length)return"";p.pop()}else u&&u!=="."&&p.push(u);return p.join("/")},a=t.includes("/")?t.slice(0,t.lastIndexOf("/")+1):"",o=Array.isArray(s)?du(s):s;for(const l of[i(a+r),i(r)])for(const p of[l,l+".md",l+".txt"])if(o.paths.has(p))return p;const c=o.byName.get(r.replace(/\.(md|txt)$/i,""))??[];return c.length===1?c[0]:void 0}function uu(t){let n="";return t.split(`
29
+ `).map(s=>{const r=/^\s*(`{3,}|~{3,})/.exec(s);return r?(n?r[1][0]===n[0]&&r[1].length>=n.length&&(n=""):n=r[1],s):n?s:s.split(/(`+[^`]*`+)/g).map(i=>i.startsWith("`")?i:i.replace(/\[\[([^\]]+)\]\]/g,(a,o)=>`[${(o.split("|")[1]||o.split("|")[0]).replace(/[\[\]]/g,"")}](#wiki=${encodeURIComponent(o.split("|")[0])})`)).join("")}).join(`
30
+ `)}function Ia(t,n,s,r,i,a,o,c,l){const p=[...new Set([...n&&!i?[n]:[],...r,...a.filter(u=>i).map(u=>u.path)])];return`${t.trim()}
31
+
32
+ ${l.scope}: ${o?".":p.map(u=>JSON.stringify(u)).join(", ")}
33
+ ${c?"":l.documentsOnly+`
34
+ `}${l.skip}${s?`
35
+
36
+ ${l.selection} (${JSON.stringify(n)}):
37
+ ${s}`:""}`}const li={sidebar:250,chat:400},gr={sidebar:180,chat:280},xr={sidebar:480,chat:720},La=t=>`pi-wiki-${t}-width`;function Ma(t){const[n,s]=d.useState(()=>{try{const i=Number(localStorage.getItem(La(t)));if(i>=gr[t]&&i<=xr[t])return i}catch{}return li[t]});return[n,i=>{const a=Math.max(gr[t],Math.min(xr[t],Math.round(i)));s(a);try{localStorage.setItem(La(t),String(a))}catch{}}]}function Pa({side:t,width:n,onResize:s}){const r=et(),i=d.useRef(null);return e.jsx("div",{className:`wiki-resize-handle wiki-resize-${t}`,role:"separator",tabIndex:0,"aria-label":`${r(t==="sidebar"?"wikiFiles":"wikiChatPanel")} · ${r("dragToResize")}`,"aria-orientation":"vertical","aria-valuemin":gr[t],"aria-valuemax":xr[t],"aria-valuenow":n,title:r("dragToResize"),onDoubleClick:()=>s(li[t]),onKeyDown:a=>{a.key==="Home"&&(a.preventDefault(),s(li[t])),(a.key==="ArrowLeft"||a.key==="ArrowRight")&&(a.preventDefault(),s(n+(a.key==="ArrowRight"?10:-10)*(t==="sidebar"?1:-1)))},onPointerDown:a=>{var f;if(a.button!==0)return;a.preventDefault(),a.currentTarget.focus(),a.currentTarget.setPointerCapture(a.pointerId);const o=a.currentTarget.closest(".wiki-workbench"),c=o.getBoundingClientRect().width,l=window.matchMedia("(max-width: 1099px)").matches,p=((f=o.querySelector(t==="sidebar"?".wiki-chat-panel":".wiki-sidebar"))==null?void 0:f.getBoundingClientRect().width)??0,u=Math.max(gr[t],Math.min(xr[t],c-(l?t==="chat"?24:280:p+280)));i.current={x:a.clientX,width:a.currentTarget.parentElement.getBoundingClientRect().width,max:u}},onPointerMove:a=>{i.current&&s(Math.min(i.current.max,i.current.width+(a.clientX-i.current.x)*(t==="sidebar"?1:-1)))},onPointerUp:()=>{i.current=null},onPointerCancel:()=>{i.current=null},onLostPointerCapture:()=>{i.current=null}})}function Zo({cwd:t,conversationId:n,initialPath:s="",disabled:r,onCreated:i,onCancel:a}){const o=et(),[c,l]=d.useState(s),[p,u]=d.useState(""),[f,k]=d.useState(!1),j=d.useRef(null);return d.useEffect(()=>()=>{var R;(R=j.current)==null||R.abort()},[]),e.jsxs("form",{className:"create-file-form","aria-label":o("newWorkspaceFile"),onSubmit:async R=>{if(R.preventDefault(),f||r||!c.trim())return;const E=new AbortController;j.current=E,k(!0),u("");try{const A=await En(t,"create-file",{path:c,conversationId:n},E.signal);E.signal.aborted||i(A.path)}catch(A){E.signal.aborted||u(A.message)}finally{E.signal.aborted||k(!1)}},children:[e.jsxs("label",{children:[o("workspaceFilePath"),e.jsx("input",{autoFocus:!0,value:c,placeholder:o("workspaceFilePlaceholder"),disabled:f,onChange:R=>l(R.target.value),onKeyDown:R=>{R.key==="Escape"&&(R.stopPropagation(),f||a())}})]}),p&&e.jsx("p",{role:"alert",children:p}),e.jsxs("div",{children:[e.jsx("button",{type:"button",disabled:f,onClick:a,children:o("cancel")}),e.jsx("button",{type:"submit",disabled:f||r||!c.trim(),children:o(f?"saving":"createWorkspaceFile")})]})]})}const Ri=Tr().use(Rr),Ii=t=>"value"in t?t.value:"children"in t?t.children.map(Ii).join(""):"";function pu(t){var r,i;const n=[];let s=0;for(const a of Ri.parse(t).children){if(a.type!=="list"||!a.children.every(l=>{var p,u;return((p=l.children[0])==null?void 0:p.type)==="paragraph"&&((u=l.children[0].children[0])==null?void 0:u.type)==="strong"}))continue;const o=(r=a.position)==null?void 0:r.start.offset,c=(i=a.position)==null?void 0:i.end.offset;if(!(o===void 0||c===void 0)){o>s&&n.push({kind:"text",text:t.slice(s,o)});for(const l of a.children){const p=l.children[0];if(p.type!=="paragraph")continue;const u=p.children[0];if(u.type!=="strong")continue;const f=u.children.map(Ii).join(""),k=t.slice(u.position.end.offset,l.position.end.offset).trim().replace(/^[::—–]\s*/,""),j=/(?:§\s*(\d+)|第\s*(\d+)\s*节|\bsection\s+(\d+)\b)/i.exec(`${f}
38
+ ${k}`);n.push({kind:"card",title:f,text:k,section:j?Number(j[1]??j[2]??j[3]):null})}s=c}}return s<t.length&&n.push({kind:"text",text:t.slice(s)}),n}function Aa(t,n){const s=t.map(r=>{var i;return(i=/^\s*(?:第\s*)?(\d+)\s*(?:[.、.))]|节|\s)/.exec(r))==null?void 0:i[1]});return s.some(Boolean)?s.findIndex(r=>Number(r)===n):n>=1&&n<=t.length?n-1:-1}function hu(t){return Ri.parse(t).children.flatMap(n=>n.type==="heading"&&n.depth===2?[n.children.map(Ii).join("")]:[])}function mu(t){const n=t.replace(/^---\r?\n[\s\S]*?\r?\n---(?:\r?\n|$)/,""),s=Ri.parse(n).children;return s.some((r,i)=>{const a=s[i+1];return r.type==="heading"&&(!a||a.type==="heading"&&a.depth<=r.depth)})}function el({thinking:t,durationMs:n,streaming:s,wrap:r=!0}){const i=et(),[a,o]=d.useState(null),c=a??r;return s?t.trim()?c?e.jsx("div",{className:"thinking open live",children:e.jsx("div",{className:"thinking-body",children:t})}):e.jsx("div",{className:"thinking live",children:e.jsxs("button",{type:"button",className:"thinking-toggle",onClick:()=>o(!0),children:[e.jsx(_t,{}),e.jsx("span",{className:"thinking-label",children:i("thinking")}),e.jsx("span",{className:"thinking-live-label",children:t.trim().split(`
39
+ `).at(-1)})]})}):null:e.jsxs("div",{className:`thinking ${c?"open":""}`,children:[e.jsxs("button",{type:"button",className:"thinking-toggle",onClick:()=>o(!c),children:[c?e.jsx(Qt,{}):e.jsx(_t,{}),e.jsx("span",{className:"thinking-label",children:i("thinking")}),e.jsxs("span",{className:"thinking-duration",children:["· ",n!==void 0?i("thinkingDuration",{n:Math.max(1,Math.round(n/1e3))}):i("thinkingUnrecorded")]})]}),c&&e.jsx("div",{className:"thinking-body",children:t})]})}function Ys(t){try{const n=JSON.parse(t??"");return n&&typeof n=="object"&&"command"in n&&typeof n.command=="string"?n.command:null}catch{return null}}function tl(t){const n=[];let s=0,r="",i=null,a=!1,o=0;for(let c=0;c<t.length;c++){const l=t[c];if(a){a=!1;continue}if(l==="\\"&&i!=="'"){a=!0;continue}if(i){l===i&&(i=null);continue}if(l==="'"||l==='"'){i=l;continue}if(l==="("||l==="{"){o++;continue}if(l===")"||l==="}"){o=Math.max(0,o-1);continue}o===0&&(l===";"||l==="&"&&t[c+1]==="&")&&(n.push({text:t.slice(s,c).trim(),separator:r}),r=l===";"?";":"&&",s=c+r.length,c=s-1)}return n.push({text:t.slice(s).trim(),separator:r}),n.filter(c=>c.text)}function Li(t){return tl(t).map(n=>n.text)}function fu(t){var s;const n=/^echo\s+(["']?)===\s*(.+?)\s*===\1\s*$/.exec(t);return((s=n==null?void 0:n[2])==null?void 0:s.trim())??null}function nl(t){return t.replace(/\x1b\[[0-9;]*m/g,"").replace(/\r\n/g,`
40
+ `)}function gu(t){return t.split(`
41
+ `).filter(n=>n.trim().length>0).length}function xu(t,n,s,r,i){var N,T,y,M,b;const a=Ys(t);if(!a)return null;const o=tl(a),c=[];let l=null;for(const F of o){const U=fu(F.text);U?(l&&c.push({label:l.label,command:l.commands.map((ce,ie)=>`${ie?` ${ce.separator} `:""}${ce.text}`).join("")}),l={label:U,commands:[]}):l&&l.commands.push(F)}if(l&&c.push({label:l.label,command:l.commands.map((F,U)=>`${U?` ${F.separator} `:""}${F.text}`).join("")}),c.length<2||c.some(F=>!F.command)||new Set(c.map(F=>F.label)).size!==c.length)return null;const p=new Map;let u=null;for(const F of nl(n).split(`
42
+ `)){const U=(T=(N=/^===\s*(.+?)\s*===\s*$/.exec(F))==null?void 0:N[1])==null?void 0:T.trim();if(U&&c.some(ce=>ce.label===U)){if(p.has(U))return null;const ce=(y=c[p.size])==null?void 0:y.label;if(U!==ce)return null;u=U,p.set(U,[])}else if(u)(M=p.get(u))==null||M.push(F);else if(F.trim())return null}if(p.size===0)return null;const f=p.size-1,k=i??Number(((b=/(?:exited with code\s*|exit(?:ed)?\s+)(\d+)/i.exec(n))==null?void 0:b[1])??NaN),j=c.map((F,U)=>{const ce=(p.get(F.label)??[]).join(`
43
+ `).trimEnd();let ie="skipped";return U<f?ie="done":U===f&&(s?r?/^(?:grep|rg)\b/.test(F.command)&&k===1&&(!ce.replace(/(?:^|\n)Command exited with code 1\s*$/i,"").trim()||/^0\s*(?:\n|$)/.test(ce))?ie="no-match":ie="failed":ie="done":ie="running"),{label:F.label,command:F.command,output:ce,state:ie,lineCount:gu(ce)}}),R=j.filter(F=>F.state==="done").length,E=j.filter(F=>F.state==="failed").length,A=j.filter(F=>F.state==="no-match").length;return{command:a,steps:j,completed:R,failed:E,noMatch:A,exitCode:Number.isFinite(k)?k:void 0,status:s?E?R||A?"partial":"failed":A?"no-match":r?"failed":"done":"running"}}function vu(t){const n=[];for(const s of nl(t).split(`
44
+ `)){const r=s.trim(),i=/^(.+?\.(?:tsx?|jsx?|mjs|cjs|json|css|html|py|go|rs))(?::(\d+)(?::(\d+))?|\((\d+),(\d+)\)):\s*(?:error\s*(?:TS\d+)?\s*:?\s*)?(.+)$/i.exec(r);if(!i)continue;const a=Number(i[2]??i[4]);!Number.isInteger(a)||a<1||n.push({path:i[1],line:a,column:i[3]||i[5]?Number(i[3]??i[5]):void 0,message:i[6]})}return n.slice(0,20)}function ku(t){const n=new Map;let s;for(const r of t)if(r.role!=="toolResult"){if(r.role!=="assistant"){s=void 0;continue}s&&s.model===r.model&&n.set(r.id,s.id),s=r}return n}function yu(t,n){const s=new Set(t.filter(r=>r.role==="toolResult").map(r=>r.toolCallId));for(let r=t.length-1;r>=0;r--){const i=t[r];if(i.role==="user")break;for(const a of[...i.content].reverse())if(a.type==="toolCall"&&typeof a.id=="string"&&typeof a.name=="string"&&!s.has(a.id)&&!n.has(a.id))return a;if(i.role==="assistant"&&i.content.some(a=>a.type==="toolCall"))return}}function sl(t,n,s){const r=t.findLastIndex(c=>c.role==="user"),i=t.slice(r+1),a=yu(t,n);if(a){let c="";try{c=JSON.parse(a.argumentsText??"{}").command??""}catch{}if(a.name!=="bash"||typeof c!="string")return null;const l=Li(c),p=l.some(f=>/^(?:(?:npm|pnpm|yarn|bun) (?:run )?test(?:[:\s]|$)|(?:npx )?(?:vitest|pytest|jest)(?:\s|$)|python\d? -m pytest(?:\s|$))/.test(f)),u=l.some(f=>/^(?:(?:npm|pnpm|yarn|bun) (?:run )?build(?:[:\s]|$)|(?:npx )?(?:tsc|vite build|make|cargo build)(?:\s|$))/.test(f));return p||u?{key:a.id,label:p?"waitTests":"waitBuild",delay:4e3}:null}for(let c=i.length-1;c>=0;c--){const l=i[c];if(l.role==="toolResult")return{key:l.toolCallId??l.id,label:l.toolName==="read"?"waitFile":"waitResults",delay:300};if(l.role==="assistant")for(const p of[...l.content].reverse()){if(p.type==="toolCall"&&typeof p.id=="string")return n.has(p.id)?{key:p.id,label:p.name==="read"?"waitFile":"waitResults",delay:300}:null;if(p.type==="text"&&(typeof p.text=="string"&&p.text.trim()||p.truncated))return null;if(p.type==="thinking")return typeof p.thinking=="string"&&p.thinking.trim()||l.content.some(u=>u.type==="text"&&(typeof u.text=="string"&&u.text.trim()||u.truncated)||u.type==="thinking"&&typeof u.thinking=="string"&&u.thinking.trim())?null:{key:l.id,label:"waitThinking",delay:300}}}const o=t[r];return o?{key:o.id,label:o.id===s?"waitSteer":"waitUnderstanding",delay:300}:null}function wu({stage:t,onStop:n}){const s=et(),r=d.useRef(Date.now()),[i,a]=d.useState(0);if(d.useEffect(()=>{const c=()=>a(Date.now()-r.current),l=window.setTimeout(c,t.delay),p=window.setInterval(c,250);return()=>{window.clearTimeout(l),window.clearInterval(p)}},[t.delay]),i<t.delay)return null;const o=Math.floor(i/1e3);return e.jsxs("div",{className:"waiting-indicator",role:"status",children:[e.jsxs("span",{className:"waiting-brand","aria-hidden":"true",children:[e.jsx("i",{}),e.jsx("i",{}),e.jsx("i",{})]}),e.jsx("span",{className:"waiting-label",children:s(t.label)}),o>=4&&e.jsx("span",{className:"waiting-duration","aria-live":"off",children:o<60?s("waitSeconds",{n:o}):s("waitMinutes",{m:Math.floor(o/60),s:String(o%60).padStart(2,"0")})}),o>=60&&n&&e.jsxs("button",{className:"waiting-stop",onClick:n,children:["· ",s("waitStop")]})]})}function rl({state:t,connected:n,silenceNotified:s,toolStatuses:r,onStop:i}){const a=et(),o=t.messages.findLast(j=>j.role==="user"),c=d.useRef({conversation:t.conversationId,user:o==null?void 0:o.id,steering:[]}),[l,p]=d.useState();d.useEffect(()=>{var R;const j=c.current;if(j.conversation!==t.conversationId||!t.isStreaming)p(void 0);else if(o&&j.user!==o.id){const E=fs(o.questionText??o.content.filter(N=>N.type==="text").map(N=>N.type==="text"?N.text:"").join(`
45
+ `)),A=E.length>2e3?E.slice(0,2e3)+"…":E;p(j.steering.some(N=>fs(N)===A)?o.id:void 0)}c.current={conversation:t.conversationId,user:o==null?void 0:o.id,steering:((R=t.queue)==null?void 0:R.steering)??[]}},[t.conversationId,t.isStreaming,t.queue,o]);const u=new Map([...r].filter(([,j])=>!j.running&&(!j.conversationId||j.conversationId===t.conversationId))),f=t.streamingMessage?[...t.messages.filter(j=>{var R;return j.id!==((R=t.streamingMessage)==null?void 0:R.id)}),{...t.streamingMessage,role:"assistant"}]:t.messages,k=sl(f,u,l);return!t.isStreaming||s||t.recovery&&Object.values(t.recovery).some(Boolean)?null:n?k&&e.jsx(wu,{stage:k,onStop:i},`${t.conversationId}:${k.key}:${k.label}`):e.jsx("div",{className:"agent-working disconnected",role:"status",children:a("workDisconnected")})}function bu(t){const n=new Map;for(const s of t)n.set(s.reason,(n.get(s.reason)??0)+1);return[...n].map(([s,r])=>({reason:s,count:r})).sort((s,r)=>r.count-s.count)}function Mi({title:t,onClose:n,children:s}){const r=et(),i=d.useRef(null);return d.useEffect(()=>{var o,c,l;const a=document.activeElement;return(l=((o=i.current)==null?void 0:o.querySelector("input"))??((c=i.current)==null?void 0:c.querySelector("button")))==null||l.focus(),()=>{a!=null&&a.isConnected&&a.focus()}},[]),mn.createPortal(e.jsx("div",{className:"wiki-modal-backdrop",onMouseDown:a=>{a.target===a.currentTarget&&n()},children:e.jsxs("section",{ref:i,className:"wiki-reading-dialog",role:"dialog","aria-modal":"true","aria-label":t,onKeyDown:a=>{var c,l,p;if(a.key==="Escape"&&(a.stopPropagation(),n()),a.key!=="Tab")return;const o=[...((c=i.current)==null?void 0:c.querySelectorAll("button, input, [tabindex='0']"))??[]];a.shiftKey&&document.activeElement===o[0]?(a.preventDefault(),(l=o.at(-1))==null||l.focus()):!a.shiftKey&&document.activeElement===o.at(-1)&&(a.preventDefault(),(p=o[0])==null||p.focus())},children:[e.jsxs("header",{children:[e.jsx("h2",{children:t}),e.jsx("button",{"aria-label":r("close"),onClick:n,children:e.jsx(Wt,{})})]}),s]})}),document.body)}function ju({status:t}){const n=et(),{locale:s}=ns(),[r,i]=d.useState(!1),a={"file-size":"wikiIndexFileSize","byte-budget":"wikiIndexBudget","entry-limit":"wikiIndexEntries","depth-limit":"wikiIndexDepth",unreadable:"wikiIndexUnreadable"},o=u=>u.toLocaleString(s==="zh"?"zh-CN":"en-US"),c=t.issues.length,l=bu(t.issues),p=n("wikiIndexStatus",{indexed:o(t.indexed),total:t.totalIsLowerBound?n("wikiIndexCounting"):o(t.total)});return!r&&!c&&!t.totalIsLowerBound&&t.indexed===t.total?null:e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:`wiki-index-status ${c?"limited":""}`,onClick:()=>i(!0),title:[p,...l.map(u=>n("wikiIndexIssueCount",{count:o(u.count),reason:n(a[u.reason])}))].join(`
46
+ `),children:[c>0&&e.jsx("i",{}),e.jsx("span",{children:p}),c>0&&e.jsxs("span",{className:"wiki-index-reason",children:[" · ",n("wikiIndexSkipped",{count:o(c)})]})]}),r&&e.jsxs(Mi,{title:p,onClose:()=>i(!1),children:[e.jsx("p",{children:n(t.totalIsLowerBound?"wikiIndexPartial":c?"wikiIndexHint":"wikiIndexComplete")}),e.jsx("ul",{className:"wiki-index-summary",children:l.map(u=>e.jsx("li",{children:n("wikiIndexIssueCount",{count:o(u.count),reason:n(a[u.reason])})},u.reason))}),e.jsx("div",{className:"wiki-index-issues",children:t.issues.map((u,f)=>e.jsxs("div",{children:[e.jsx("code",{children:u.path}),e.jsx("span",{children:u.size===void 0?"—":`${(u.size/1024/1024).toFixed(2)} MB`}),e.jsxs("small",{children:[n(a[u.reason]),u.subtree?` · ${n("wikiIndexSubtree")}`:""]})]},`${u.path}:${f}`))})]})]})}function Cu(t){const n=[...new Set(t)].filter(Boolean).sort((s,r)=>r.length-s.length);return()=>s=>{const r=i=>{!i.children||["link","code","inlineCode"].includes(i.type)||(i.children=i.children.flatMap(a=>{if((a.type==="text"||a.type==="inlineCode")&&a.value){const o=a.value,c=[];let l=0;for(;l<o.length;){let p=-1,u="";for(const f of n){const k=o.indexOf(f,l);k<0||p>=0&&k>=p||k>0&&/[\w/.-]/.test(o[k-1])||/[\w/.-]/.test(o[k+f.length]??"")&&o[k+f.length]!=="."||(p=k,u=f)}if(p<0){c.push({...a,value:o.slice(l)});break}p>l&&c.push({...a,value:o.slice(l,p)}),c.push({type:"link",url:`#pi-change=${encodeURIComponent(u)}`,children:[{...a,value:u}]}),l=p+u.length}return c}return r(a),[a]}))};r(s)}}const ci=[{name:"yellow",hex:"#fff3a3",rgb:"rgb(255, 243, 163)"},{name:"green",hex:"#ccebc5",rgb:"rgb(204, 235, 197)"},{name:"blue",hex:"#c8e4ff",rgb:"rgb(200, 228, 255)"},{name:"pink",hex:"#ffd5e5",rgb:"rgb(255, 213, 229)"},{name:"purple",hex:"#e5d5ff",rgb:"rgb(229, 213, 255)"}];function di(t){return ci.find(n=>n.hex===t.toLowerCase()||n.rgb===t.toLowerCase())}function il(){return t=>{const n=s=>{for(let r=0;r<s.children.length;r++){const i=s.children[r];if(i.type==="html"){const o=/^<mark style="background-color: (#[0-9a-f]{6})">$/i.exec(i.value),c=o&&di(o[1]);if(!c)continue;let l=r+1;for(;l<s.children.length;){const u=s.children[l];if(u.type==="html"&&u.value==="</mark>")break;if(u.type==="html"){l=s.children.length;break}l++}if(l===s.children.length)continue;const p=s.children.slice(r+1,l);s.children.splice(r,l-r+1,{type:"emphasis",children:p,data:{hName:"span",hProperties:{style:`background-color: ${c.hex}`}}})}const a=s.children[r];"children"in a&&n(a)}};n(t)}}function al(){return t=>{const n=s=>{if(s.type==="blockquote"){const r=s.children[0],i=(r==null?void 0:r.type)==="paragraph"?r.children[0]:void 0;(i==null?void 0:i.type)==="text"&&/^\[!NOTE\](?:\r?\n|$)/.test(i.value)&&(i.value=i.value.replace(/^\[!NOTE\](?:\r?\n)?/,""),s.data={...s.data,hProperties:{className:["rich-highlight"],"data-rich-highlight":"note"}})}"children"in s&&s.children.forEach(r=>n(r))};n(t)}}const Su=/[ -〿＀-￯]/;function ol(t){const n=t.children;if(n)for(let s=0;s<n.length;s++){const r=n[s];if(ol(r),r.type!=="link"||typeof r.url!="string")continue;const i=Su.exec(r.url);if(!i||i.index===0)continue;const a=r.children&&r.children.length===1?r.children[0]:null;if(!a||a.type!=="text"||typeof a.value!="string")continue;const o=r.url.length-a.value.length;if(o<0||r.url.slice(o)!==a.value)continue;const c=i.index-o;if(c<=0)continue;const l=a.value.slice(c);a.value=a.value.slice(0,c),r.url=r.url.slice(0,i.index),n.splice(s+1,0,{type:"text",value:l}),s++}}function Nu(){return t=>{ol(t)}}const vr=d.memo(function({text:n,label:s=!1}){const r=et(),[i,a]=d.useState(!1);return n?e.jsxs("button",{type:"button",className:"copy-btn",title:r("copy"),onClick:()=>{navigator.clipboard.writeText(n).then(()=>{a(!0),setTimeout(()=>a(!1),1200)})},children:[i?e.jsx(ts,{}):e.jsx(ws,{}),s&&e.jsx("span",{children:r("copy")})]}):null});let Wr=null;function Eu(){return Wr||(Wr=Lr(()=>import("./mermaid.core-CO2nrD04.js").then(t=>t.cb),__vite__mapDeps([0,1])).then(t=>t.default)),Wr}let Tu=0,Da=Promise.resolve();function Ru(t,n){const s=Da.then(async()=>{const r=await Eu(),i=getComputedStyle(document.documentElement),a=document.createElement("canvas");a.width=a.height=1;const o=a.getContext("2d"),c=l=>{o.clearRect(0,0,1,1),o.fillStyle=i.getPropertyValue(l).trim(),o.fillRect(0,0,1,1);const[p,u,f]=o.getImageData(0,0,1,1).data;return`rgb(${p}, ${u}, ${f})`};return r.initialize({startOnLoad:!1,securityLevel:"strict",theme:"base",themeVariables:{background:c("--bg-elev"),primaryColor:c("--accent-soft"),primaryBorderColor:c("--accent"),primaryTextColor:c("--text"),textColor:c("--text"),lineColor:c("--text-dim"),secondaryColor:c("--bg-elev2"),tertiaryColor:c("--bg"),fontFamily:i.getPropertyValue("--mono").trim()}}),r.render(t,n)});return Da=s.catch(()=>{}),s}function ll({code:t}){const n=et(),s=d.useId().replace(/[^a-zA-Z0-9]/g,""),[r,i]=d.useState(null),[a,o]=d.useState(null),c=d.useRef(null),[l,p]=d.useState(document.documentElement.dataset.appearance);return d.useEffect(()=>{const u=new MutationObserver(()=>p(document.documentElement.dataset.appearance));return u.observe(document.documentElement,{attributes:!0,attributeFilter:["data-appearance"]}),()=>u.disconnect()},[]),d.useEffect(()=>{let u=!1;i(null),o(null);const f=`mermaid-${s}-${++Tu}`;return Ru(f,t).then(({svg:k})=>{u||i(k)}).catch(k=>{var j;u||o(k instanceof Error?k.message:String(k)),(j=document.getElementById(f))==null||j.remove()}),()=>{u=!0}},[t,s,l]),a?e.jsxs("div",{className:"mermaid-block mermaid-block-error",children:[e.jsx("div",{className:"mermaid-error-note",children:n("mermaidRenderFailed")}),e.jsxs("div",{className:"codeblock",children:[e.jsx(vr,{text:t}),e.jsx("pre",{children:e.jsx("code",{children:t})})]})]}):r?e.jsxs("div",{className:"mermaid-block",children:[e.jsx(vr,{text:t}),e.jsx("div",{ref:c,className:"mermaid-svg",dangerouslySetInnerHTML:{__html:r}})]}):e.jsx("div",{className:"mermaid-block mermaid-block-loading",children:e.jsx("div",{className:"mermaid-loading-note",children:n("mermaidRendering")})})}const ui=[Si,Nu,al,il],cl=[[mo,{detect:!0,ignoreMissing:!0}]],Iu={p:({node:t,...n})=>{var s,r;return e.jsx("p",{...n,"data-source-start":(s=t==null?void 0:t.position)==null?void 0:s.start.line,"data-source-end":(r=t==null?void 0:t.position)==null?void 0:r.end.line})},li:({node:t,...n})=>{var s,r;return e.jsx("li",{...n,"data-source-start":(s=t==null?void 0:t.position)==null?void 0:s.start.line,"data-source-end":(r=t==null?void 0:t.position)==null?void 0:r.end.line})},h1:({node:t,...n})=>{var s,r;return e.jsx("h1",{...n,"data-source-start":(s=t==null?void 0:t.position)==null?void 0:s.start.line,"data-source-end":(r=t==null?void 0:t.position)==null?void 0:r.end.line})},h2:({node:t,...n})=>{var s,r;return e.jsx("h2",{...n,"data-source-start":(s=t==null?void 0:t.position)==null?void 0:s.start.line,"data-source-end":(r=t==null?void 0:t.position)==null?void 0:r.end.line})},h3:({node:t,...n})=>{var s,r;return e.jsx("h3",{...n,"data-source-start":(s=t==null?void 0:t.position)==null?void 0:s.start.line,"data-source-end":(r=t==null?void 0:t.position)==null?void 0:r.end.line})},h4:({node:t,...n})=>{var s,r;return e.jsx("h4",{...n,"data-source-start":(s=t==null?void 0:t.position)==null?void 0:s.start.line,"data-source-end":(r=t==null?void 0:t.position)==null?void 0:r.end.line})},h5:({node:t,...n})=>{var s,r;return e.jsx("h5",{...n,"data-source-start":(s=t==null?void 0:t.position)==null?void 0:s.start.line,"data-source-end":(r=t==null?void 0:t.position)==null?void 0:r.end.line})},h6:({node:t,...n})=>{var s,r;return e.jsx("h6",{...n,"data-source-start":(s=t==null?void 0:t.position)==null?void 0:s.start.line,"data-source-end":(r=t==null?void 0:t.position)==null?void 0:r.end.line})}};function dl({text:t,imageSrc:n,sourceLines:s,fileLinks:r}){const i=Dc(),a=i&&!s?[...ui,Cu(i.files.map(o=>o.path))]:ui;return e.jsx(Ir,{remarkPlugins:a,rehypePlugins:cl,components:{pre:({children:o,...c})=>e.jsx(ul,{...c,fileLinks:r,children:o}),a:({node:o,href:c,children:l,...p})=>{const u=/^https?:\/\/github\.com\/[^/]+\/[^/]+\/pull\/(\d+)(?:[?#].*)?$/.exec(c??"");return e.jsx("a",{...p,href:c,className:u?"pr-reference":void 0,onClick:f=>{if(c!=null&&c.startsWith("#pi-change=")){f.preventDefault();const k=decodeURIComponent(c.slice(11));i==null||i.show(i.files,k)}else if(r&&(c!=null&&c.startsWith("#pi-file=")))f.preventDefault(),pl(c.slice(9));else if(i&&c&&!/^(?:[a-z]+:|#|\/\/)/i.test(c)&&/\.[a-z0-9]+(?:#L\d+)?$/i.test(c)){f.preventDefault();const[k,j]=c.split("#L"),R=i.files.find(E=>E.path===k);R?i.show(i.files,R.path):window.dispatchEvent(new CustomEvent("pi-harness:open-tool-file",{detail:{path:decodeURIComponent(k),line:Number(j)||1}}))}},children:u?`#${u[1]}`:l})},...s?Iu:{},...n?{img:({node:o,src:c,...l})=>e.jsx("img",{...l,src:n(c??"")})}:{}},children:t})}const On=d.memo(function({text:n,imageSrc:s,sourceLines:r,fileLinks:i}){return e.jsx("div",{className:"md",children:e.jsx(dl,{text:n,imageSrc:s,sourceLines:r,fileLinks:i})})});function ul({children:t,fileLinks:n,showLanguage:s,...r}){var l;if(Pu(t))return e.jsx(ll,{code:kr(t)});const i=n&&Lu(t),a=kr(t),o=Array.isArray(t)?t[0]:t,c=o&&typeof o=="object"&&"props"in o?(l=/language-([\w+-]+)/.exec(String(o.props.className??"")))==null?void 0:l[1]:void 0;return e.jsxs("div",{className:`codeblock${i?" ascii-table":""}`,children:[s?e.jsxs("div",{className:"codeblock-heading",children:[e.jsx("span",{children:c}),e.jsx(vr,{text:a,label:!0})]}):e.jsx(vr,{text:a}),e.jsx("pre",{...r,children:i?e.jsx("code",{children:Mu(a)}):t})]})}function Lu(t){var s;const n=Array.isArray(t)?t[0]:t;return!!n&&typeof n=="object"&&"props"in n&&/(^|\s)language-ascii-table(\s|$)/.test(String(((s=n.props)==null?void 0:s.className)??""))}function pl(t){const n=/^(.+):([1-9]\d*)$/.exec(t);if(n)try{window.dispatchEvent(new CustomEvent("pi-harness:open-tool-file",{detail:{path:decodeURIComponent(n[1]),line:Number(n[2])}}))}catch{}}function Mu(t){const n=/((?:[\w.-]+\/)+[\w.-]+\.[A-Za-z0-9]+):([1-9]\d*)/g,s=[];let r=0;for(const i of t.matchAll(n)){const a=i.index;a>r&&s.push(t.slice(r,a));const o=`${i[1]}:${i[2]}`;s.push(e.jsx("a",{href:`#pi-file=${encodeURIComponent(i[1])}:${i[2]}`,onClick:c=>{c.preventDefault(),pl(`${encodeURIComponent(i[1])}:${i[2]}`)},children:o},a)),r=a+i[0].length}return r<t.length&&s.push(t.slice(r)),s}function Pu(t){var r;const n=Array.isArray(t)?t[0]:t;if(!n||typeof n!="object"||!("props"in n))return!1;const s=(r=n.props)==null?void 0:r.className;return typeof s=="string"&&/(^|\s)language-mermaid(\s|$)/.test(s)}function kr(t){if(typeof t=="string")return t;if(Array.isArray(t))return t.map(kr).join("");if(t&&typeof t=="object"&&"props"in t){const n=t.props;return kr(n==null?void 0:n.children)}return""}function Au({resizeHandle:t,messages:n,live:s,streaming:r,toolStatuses:i,model:a,contextPercent:o,disabled:c,onNew:l,onClose:p,canJump:u,jump:f,composer:k,quickQuestions:j,onQuickQuestion:R,revisions:E,onViewChange:A,onUndo:N,onResend:T,error:y,conversationId:M,thinkingWrap:b,connected:F,silenceNotified:U,recovery:ce,onStop:ie}){const W=et(),ve=d.useRef(null),Se=d.useRef(!0),[$,$e]=d.useState(null),[L,q]=d.useState(""),[fe,je]=d.useState(60),ne=d.useMemo(()=>r&&s&&!n.some(_=>_.id===s.id)?[...n,{...s,role:"assistant"}]:n,[n,s,r]),Pe=d.useMemo(()=>new Map(n.filter(_=>_.role==="toolResult"&&_.toolCallId).map(_=>[_.toolCallId,_])),[n]);d.useEffect(()=>{Se.current&&ve.current&&(ve.current.scrollTop=ve.current.scrollHeight)},[n,s,r]);const B=d.useMemo(()=>{const _=ne.map(le=>le.role).lastIndexOf("user");return new Set(r?ne.slice(Math.max(0,_)).flatMap(le=>le.content.filter(O=>O.type==="toolCall").map(O=>O.type==="toolCall"?O.id:"")):[])},[ne,r]),[we,re]=d.useState(()=>window.matchMedia("(max-width: 1099px)").matches);d.useEffect(()=>{const _=window.matchMedia("(max-width: 1099px)"),le=()=>re(_.matches);return _.addEventListener("change",le),()=>_.removeEventListener("change",le)},[]);const Ie=_=>{const le=Pe.get(_.id),O=i.get(_.id),ge=(le==null?void 0:le.isError)||(O==null?void 0:O.isError),pe=B.has(_.id),Ae=!!le||!!O&&!O.running;let ae="";try{const Z=JSON.parse(_.argumentsText??"{}");ae=String(Z.path??Z.file_path??Z.command??"").split(`
47
+ `)[0]}catch{}const Te=le==null?void 0:le.content.filter(Z=>Z.type==="text").map(Z=>Z.type==="text"?String(Z.text??""):"").join(`
48
+ `);return e.jsxs("details",{className:`wiki-chat-tool ${ge?"error":Ae?"done":"pending"}`,children:[e.jsxs("summary",{children:[e.jsx("span",{children:ge?e.jsx(Wt,{}):Ae?e.jsx(ts,{}):pe?e.jsx(id,{}):"−"}),e.jsxs("code",{children:[_.name," ",ae]}),e.jsxs("small",{children:[W(ge?"error":Ae?"done":pe?"running":"wikiToolInterrupted"),(O==null?void 0:O.durationMs)!==void 0?` · ${(O.durationMs/1e3).toFixed(1)}s`:""]})]}),e.jsx("pre",{children:Te||_.argumentsText||_.name})]},_.id)};return e.jsxs("aside",{className:"wiki-chat-panel","aria-label":W("wikiChatPanel"),role:we?"dialog":void 0,"aria-modal":we||void 0,onKeyDown:_=>{var O,ge;if(!we||_.key!=="Tab")return;const le=[..._.currentTarget.querySelectorAll("button:not(:disabled), textarea, summary, a[href]")].filter(pe=>pe.getClientRects().length);_.shiftKey&&document.activeElement===le[0]?(_.preventDefault(),(O=le.at(-1))==null||O.focus()):!_.shiftKey&&document.activeElement===le.at(-1)&&(_.preventDefault(),(ge=le[0])==null||ge.focus())},children:[t,e.jsxs("header",{children:[e.jsx("img",{className:"wiki-chat-brand",src:"/icon/1a-mark.svg",alt:""}),e.jsx("strong",{children:W("wikiChatTitle")}),e.jsxs("span",{className:"wiki-chat-model",title:a==null?void 0:a.id,children:[(a==null?void 0:a.name)||(a==null?void 0:a.id)||W("wikiNoModel"),o!=null&&o>0?` · ${W("wikiChatContext",{percent:Math.round(o)})}`:""]}),e.jsx("button",{disabled:c,onClick:l,children:W("newChat")}),e.jsx("button",{"aria-label":W("wikiCloseChat"),onClick:p,children:e.jsx(Wt,{})})]}),y,e.jsxs("div",{className:`wiki-chat-messages${ne.length?"":" empty"}`,ref:ve,onScroll:_=>{const le=_.currentTarget;Se.current=le.scrollHeight-le.scrollTop-le.clientHeight<80},children:[ne.length>fe&&e.jsx("button",{className:"wiki-chat-earlier",onClick:()=>{Se.current=!1,je(_=>_+60)},children:W("wikiEarlierMessages")}),!ne.length&&e.jsxs("div",{className:"wiki-chat-empty",children:[e.jsx("p",{children:W("wikiChatEmpty")}),e.jsx("div",{className:"wiki-quick-questions",children:j.map(_=>e.jsx("button",{disabled:c||!F||r,onClick:()=>R(_),children:_},_))})]}),ne.slice(-fe).map(_=>{if(!["user","assistant"].includes(_.role))return null;const le=_.content.filter(O=>O.type==="text").map(O=>"text"in O?O.text:"").join(`
49
+ `);return e.jsxs("div",{className:`wiki-chat-message ${_.role}`,children:[_.content.map((O,ge)=>{if(O.type==="thinking"){const pe=O;return e.jsx(el,{thinking:pe.thinking,durationMs:pe.durationMs,streaming:r&&_.id===(s==null?void 0:s.id)&&ge===_.content.length-1,wrap:b},ge)}if(O.type==="toolCall")return Ie(O);if(O.type==="image"&&typeof O.dataUrl=="string")return e.jsx("img",{src:O.dataUrl,alt:W("attachment")},ge);if(O.type!=="text"||typeof O.text!="string"||!O.text.trim())return null;if(_.role==="user"){const pe=/\n\n(?:范围|Scope): /.exec(O.text);return e.jsx("div",{children:e.jsx(On,{text:pe?O.text.slice(0,pe.index):O.text})},ge)}return e.jsx("div",{className:"wiki-chat-answer",children:pu(O.text).map((pe,Ae)=>pe.kind==="text"?e.jsx(On,{text:pe.text},Ae):e.jsxs("section",{className:"wiki-suggestion",children:[e.jsxs("header",{children:[e.jsx("strong",{children:pe.title}),pe.section!==null&&u(pe.section)&&e.jsx("button",{onClick:()=>f(pe.section),children:W("wikiJumpSection",{section:pe.section})})]}),pe.text&&e.jsx(On,{text:pe.text})]},Ae))},ge)}),_.role==="user"&&e.jsxs("details",{className:"wiki-message-actions",children:[e.jsx("summary",{"aria-label":W("wikiMessageActions"),children:e.jsx(Ms,{})}),e.jsxs("div",{role:"menu",children:[e.jsx("button",{role:"menuitem",onClick:O=>{var ge;(ge=O.currentTarget.closest("details"))==null||ge.removeAttribute("open"),$e(le)},children:W("wikiFullRequest")}),e.jsx("button",{role:"menuitem",onClick:O=>{var ge;(ge=O.currentTarget.closest("details"))==null||ge.removeAttribute("open"),navigator.clipboard.writeText(le).catch(pe=>q(pe.message))},children:W("copy")}),e.jsx("button",{role:"menuitem",disabled:c||r,onClick:O=>{var ge;(ge=O.currentTarget.closest("details"))==null||ge.removeAttribute("open"),T(le)},children:W("wikiResend")})]})]}),_.role==="assistant"&&E.filter(O=>O.author==="pi"&&O.conversationId===M&&O.assistantTimestamp!==void 0&&O.assistantTimestamp===_.timestamp&&O.changes.length>0).map(O=>e.jsxs("div",{className:"wiki-reply-change",children:[e.jsx(ts,{}),e.jsxs("span",{children:[W("wikiReplyChanged",{file:O.changes.length===1?O.changes[0].path.split("/").at(-1):W("wikiFileCount",{count:O.changes.length})})," · ",e.jsxs("em",{children:["+",O.changes.reduce((ge,pe)=>ge+pe.additions,0)]})," ",e.jsxs("b",{children:["−",O.changes.reduce((ge,pe)=>ge+pe.deletions,0)]})]}),e.jsx("button",{onClick:()=>A(O),children:W("wikiViewChange")}),e.jsx("button",{disabled:c||r,onClick:()=>N(O),children:W(O.changes.every(ge=>ge.undone)?"wikiRedo":"wikiUndo")})]},O.id)),_.errorMessage&&e.jsx("p",{role:"alert",className:"wiki-chat-error",children:_.errorMessage})]},_.id)}),r&&e.jsx(rl,{onStop:ie,state:{recovery:ce,messages:n,streamingMessage:s,isStreaming:r,conversationId:M,model:a??null},connected:F,silenceNotified:U,toolStatuses:i})]}),L&&e.jsx("p",{role:"alert",children:L}),e.jsx("footer",{children:k}),$!==null&&e.jsx(Mi,{title:W("wikiFullRequest"),onClose:()=>$e(null),children:e.jsx("pre",{className:"wiki-full-request",children:$})})]})}function Du(){return e.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[e.jsx("rect",{x:"3",y:"4",width:"18",height:"16",rx:"2"}),e.jsx("path",{d:"M3 9h18M3 14h18M9 9v11M15 9v11"})]})}function $u(){return e.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round","aria-hidden":"true",children:e.jsx("path",{d:"M4 4v16M9 6h12M9 12h12M9 18h8"})})}function Fu(){return e.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:e.jsx("path",{d:"M3 12h18M7 8l-4 4 4 4M17 8l4 4-4 4"})})}function Ou(t){return it({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M4 12h8"},child:[]},{tag:"path",attr:{d:"M4 18V6"},child:[]},{tag:"path",attr:{d:"M12 18V6"},child:[]},{tag:"path",attr:{d:"M17.5 10.5c1.7-1 3.5 0 3.5 1.5a2 2 0 0 1-2 2"},child:[]},{tag:"path",attr:{d:"M17 17.5c2 1.5 4 .3 4-1.5a2 2 0 0 0-2-2"},child:[]}]})(t)}function _u(t){return it({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M4 12h8"},child:[]},{tag:"path",attr:{d:"M4 18V6"},child:[]},{tag:"path",attr:{d:"M12 18V6"},child:[]},{tag:"path",attr:{d:"M21 18h-4c0-4 4-3 4-6 0-1.5-2-2.5-4-1"},child:[]}]})(t)}function Hu({popup:t,onClose:n,children:s}){const r=d.useRef(null);return d.useLayoutEffect(()=>{var a;const i=r.current;i&&(i.style.left=`${Math.max(8,Math.min(t.x,innerWidth-i.offsetWidth-8))}px`,i.style.top=`${Math.max(8,Math.min(t.y,innerHeight-i.offsetHeight-8))}px`,(a=i.querySelector('input, [tabindex="0"], button'))==null||a.focus())},[t]),d.useEffect(()=>{const i=a=>{var o;(o=r.current)!=null&&o.contains(a.target)||n()};return window.addEventListener("pointerdown",i),window.addEventListener("resize",n),()=>{window.removeEventListener("pointerdown",i),window.removeEventListener("resize",n)}},[n]),mn.createPortal(e.jsx("div",{ref:r,className:`wiki-insert-popover wiki-${t.kind}-popover`,role:"dialog",onKeyDown:i=>{i.key==="Escape"&&(i.preventDefault(),i.stopPropagation(),n())},style:{left:t.x,top:t.y},children:s}),document.body)}function Bu({readOnly:t,focused:n,onWidth:s,items:r,popup:i,onPrepare:a,onSelect:o,onPopup:c}){const l=et(),p=[r.slice(0,3),r.slice(3,9),r.slice(9)],u=(f,k)=>{const j=k.getBoundingClientRect();c({kind:f,x:j.left,y:j.bottom+6})};return e.jsxs("div",{className:"wiki-insert-toolbar",role:"toolbar","aria-label":l("richInsertMenu"),children:[p.map((f,k)=>e.jsx("div",{className:"wiki-tool-group",children:f.map(j=>{const{id:R}=j,E=R==="bt2"?e.jsx(_u,{}):R==="bt3"?e.jsx(Ou,{}):j.icon,A=R==="bg"?"table":R==="dmk"?"code":void 0;return e.jsx("button",{type:"button",disabled:t,title:`${j.label} · ${j.help}${j.hint?` · ${j.hint}`:""}`,"aria-label":j.label,"aria-expanded":A?(i==null?void 0:i.kind)===A:void 0,onMouseDown:N=>{N.preventDefault(),a()},onClick:N=>A?u(A,N.currentTarget):o(R),children:E},R)})},k)),e.jsx("button",{type:"button",className:"wiki-width-toggle",title:l(n?"wikiStandardWidth":"wikiWideWidth"),"aria-label":l(n?"wikiStandardWidth":"wikiWideWidth"),"aria-pressed":n,onMouseDown:f=>f.preventDefault(),onClick:s,children:e.jsx(Fu,{})})]})}function Uu({onInsert:t}){const n=et(),[s,r]=d.useState({columns:3,rows:3});return e.jsxs("div",{className:"wiki-table-picker",tabIndex:0,role:"group","aria-label":n("wikiTableSize"),onKeyDown:i=>{i.key==="Enter"&&(i.preventDefault(),t(s.columns,s.rows)),i.key.startsWith("Arrow")&&(i.preventDefault(),r(a=>({columns:Math.max(1,Math.min(8,a.columns+(i.key==="ArrowRight"?1:i.key==="ArrowLeft"?-1:0))),rows:Math.max(1,Math.min(6,a.rows+(i.key==="ArrowDown"?1:i.key==="ArrowUp"?-1:0)))})))},children:[e.jsx("div",{className:"wiki-table-grid",children:Array.from({length:48},(i,a)=>{const o=a%8+1,c=Math.floor(a/8)+1;return e.jsx("button",{type:"button",tabIndex:-1,"aria-label":n("wikiTableDimensions",{columns:o,rows:c}),className:o<=s.columns&&c<=s.rows?"selected":"",onMouseEnter:()=>r({columns:o,rows:c}),onClick:()=>t(o,c)},a)})}),e.jsxs("footer",{children:[e.jsx("span",{"aria-live":"polite",children:n("wikiTableDimensions",s)}),e.jsx("small",{children:n("wikiTableHeader")})]})]})}const $a=["","bash","python","ts","json","yaml","sql","mermaid"];function Wu({onInsert:t}){const n=et(),[s,r]=d.useState(""),[i,a]=d.useState(-1),o=$a.filter(l=>(l||n("wikiCodeAutomatic")).toLowerCase().includes(s.toLowerCase())),c=["wikiCodeAutomaticHint","wikiCodeShell","wikiCodePython","wikiCodeTypescript","wikiCodeData","wikiCodeConfig","wikiCodeQuery","wikiCodeDiagram"];return e.jsxs("div",{className:"wiki-language-picker",onKeyDown:l=>{(l.key==="ArrowDown"||l.key==="ArrowUp")&&(l.preventDefault(),a(p=>o.length?(p+(l.key==="ArrowDown"?1:-1)+o.length)%o.length:-1)),l.key==="Enter"&&(l.preventDefault(),t(o[i]??""))},children:[e.jsx("input",{autoFocus:!0,placeholder:n("wikiSearchLanguage"),"aria-label":n("wikiSearchLanguage"),value:s,onChange:l=>{r(l.target.value),a(-1)},role:"combobox","aria-expanded":"true","aria-controls":"wiki-code-languages","aria-activedescendant":i>=0?`wiki-code-language-${i}`:void 0}),e.jsx("div",{id:"wiki-code-languages",role:"listbox",children:o.map((l,p)=>e.jsxs("button",{type:"button",role:"option","aria-selected":p===i,id:`wiki-code-language-${p}`,onMouseEnter:()=>a(p),onClick:()=>t(l),children:[e.jsx("code",{children:l||n("wikiCodeAutomatic")}),e.jsx("small",{children:n(c[$a.indexOf(l)])})]},l))})]})}function hl(t,n){if(!t||/^(?:[a-z]+:|\/\/|#)/i.test(t))return t;try{const s=n.path.replace(/\\/g,"/").split("/").slice(0,-1).map(encodeURIComponent).join("/"),r=decodeURIComponent(new URL(t,`https://workspace.invalid/${s?s+"/":""}`).pathname).slice(1);return Tn(`/api/file?clientId=${encodeURIComponent(fn())}&cwd=${encodeURIComponent(n.cwd)}&path=${encodeURIComponent(r)}`)}catch{return t}}function zs(t){const n=t.cloneNode(!0);return n.querySelectorAll("br").forEach(s=>s.replaceWith(`
50
+ `)),n.textContent??""}Lt.registerLanguage("bash",Zl);Lt.registerLanguage("c",ec);Lt.registerLanguage("cpp",tc);Lt.registerLanguage("csharp",nc);Lt.registerLanguage("css",sc);Lt.registerLanguage("diff",rc);Lt.registerLanguage("go",ic);Lt.registerLanguage("graphql",ac);Lt.registerLanguage("ini",oc);Lt.registerLanguage("java",lc);Lt.registerLanguage("javascript",cc);Lt.registerLanguage("json",dc);Lt.registerLanguage("kotlin",uc);Lt.registerLanguage("less",pc);Lt.registerLanguage("lua",hc);Lt.registerLanguage("makefile",mc);Lt.registerLanguage("php",fc);Lt.registerLanguage("python",gc);Lt.registerLanguage("r",xc);Lt.registerLanguage("ruby",vc);Lt.registerLanguage("rust",kc);Lt.registerLanguage("scss",yc);Lt.registerLanguage("sql",wc);Lt.registerLanguage("swift",bc);Lt.registerLanguage("typescript",jc);Lt.registerLanguage("xml",Cc);Lt.registerLanguage("yaml",Sc);function Rs(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function Zs(t,n){if(!n||!Lt.getLanguage(n))return Rs(t);try{return Lt.highlight(t,{language:n,ignoreIllegals:!0}).value}catch{return Rs(t)}}function qu(t,n){if(n&&n!=="plaintext")return Zs(t,n);try{return Lt.highlightAuto(t,["bash","python","typescript","json","yaml","sql"]).value}catch{return Rs(t)}}const zu={json:"json",jsonc:"json",ts:"typescript",mts:"typescript",cts:"typescript",tsx:"typescript",js:"javascript",mjs:"javascript",cjs:"javascript",jsx:"javascript",py:"python",rb:"ruby",go:"go",rs:"rust",java:"java",kt:"kotlin",kts:"kotlin",swift:"swift",c:"c",h:"c",cpp:"cpp",cc:"cpp",hpp:"cpp",cs:"csharp",php:"php",sql:"sql",css:"css",scss:"scss",less:"less",html:"xml",htm:"xml",xml:"xml",svg:"xml",yml:"yaml",yaml:"yaml",sh:"bash",bash:"bash",zsh:"bash",toml:"ini",ini:"ini",graphql:"graphql",gql:"graphql",lua:"lua",r:"r",makefile:"makefile",diff:"diff",patch:"diff"};function Os(t){var s,r;const n=(r=(s=t.split(/[\\/]/).pop())==null?void 0:s.split(".").pop())==null?void 0:r.toLowerCase();return n&&zu[n]||null}function ml(t,n){const s=t.split(`
51
+ `);if(!n||!Lt.getLanguage(n))return s.map(Rs);let r;try{r=Lt.highlight(t,{language:n,ignoreIllegals:!0}).value}catch{return s.map(Rs)}const i=[],a=[];let o="",c=0;for(;c<r.length;){if(r[c]==="<"){const f=r.indexOf(">",c);if(f===-1){o+=r.slice(c);break}const k=r.slice(c,f+1);k.startsWith("</")?a.pop():k.endsWith("/>")||a.push(k),o+=k,c=f+1;continue}const l=r.indexOf(`
52
+ `,c),p=r.indexOf("<",c),u=Math.min(l===-1?Number.POSITIVE_INFINITY:l,p===-1?Number.POSITIVE_INFINITY:p);if(u===Number.POSITIVE_INFINITY){o+=r.slice(c);break}o+=r.slice(c,u),u===l?(i.push(o+"</span>".repeat(a.length)),o=a.join(""),c=u+1):c=u}return i.push(o+"</span>".repeat(a.length)),i.length===s.length?i:s.map(Rs)}const Vu=t=>{if(["hljs-keyword","hljs-type","hljs-literal","hljs-selector-tag"].some(n=>t.contains(n)))return"keyword";if(["hljs-string","hljs-regexp","hljs-addition"].some(n=>t.contains(n)))return"string";if(["hljs-number","hljs-attr","hljs-symbol","hljs-bullet"].some(n=>t.contains(n)))return"number";if(["hljs-title","hljs-built_in","hljs-section"].some(n=>t.contains(n)))return"title";if(["hljs-comment","hljs-quote","hljs-meta","hljs-deletion"].some(n=>t.contains(n)))return"comment"};function Ku(t=!1){const n=CSS.highlights,s=window.Highlight,r=new Map,i=new Map,a=u=>{for(const{group:f,range:k}of r.get(u)??[]){const j=`rich-code-${f}`,R=n==null?void 0:n.get(j);R==null||R.delete(k),(R==null?void 0:R.size)===0&&(n==null||n.delete(j))}r.delete(u),i.delete(u)},o=new Set,c=new Set,l=t&&typeof IntersectionObserver<"u"?new IntersectionObserver(u=>{for(const f of u){const k=f.target;f.isIntersecting?(c.add(k),p.update(k)):c.delete(k)}},{rootMargin:"400px"}):null,p={observe(u){if(!l){p.update(u);return}for(const f of o)f.isConnected||(l.unobserve(f),o.delete(f),c.delete(f),a(f));o.has(u)?c.has(u)&&p.update(u):(o.add(u),l.observe(u))},update(u){var ce,ie,W,ve;if(!n||!s)return;for(const Se of r.keys())Se.isConnected||a(Se);const f=((ce=u.className.match(/language-([^\s]+)/))==null?void 0:ce[1])??"",k=u.innerHTML,j=i.get(u);if((j==null?void 0:j.html)===k&&j.language===f&&j.nodes.every(Se=>u.contains(Se)))return;a(u);const R=zs(u);if(!R)return;const E=document.createElement("template");E.innerHTML=(t?qu:Zs)(R,f==="toml"?"ini":f);const A=[],N=document.createTreeWalker(u,NodeFilter.SHOW_TEXT|NodeFilter.SHOW_ELEMENT);let T,y=0;for(;T=N.nextNode();){if(T.nodeName==="BR"){y++;continue}T.nodeType===Node.TEXT_NODE&&(A.push({node:T,start:y,end:y+(((ie=T.textContent)==null?void 0:ie.length)??0)}),y+=((W=T.textContent)==null?void 0:W.length)??0)}const M=[],b=(Se,$,$e)=>{if($===$e)return;let L=0,q=A.length;for(;L<q;){const we=L+q>>>1;A[we].end<=$?L=we+1:q=we}const fe=A[L];for(L=0,q=A.length;L<q;){const we=L+q>>>1;A[we].start<$e?L=we+1:q=we}const je=A[L-1];if(!fe||!je)return;const ne=document.createRange();ne.setStart(fe.node,Math.max(0,$-fe.start)),ne.setEnd(je.node,Math.min(je.node.length,$e-je.start));const Pe=`rich-code-${Se}`;let B=n.get(Pe);B||(B=new s,B.priority=Se==="plain"?0:1,n.set(Pe,B)),B.add(ne),M.push({group:Se,range:ne})};b("plain",0,((ve=A.at(-1))==null?void 0:ve.end)??0);let F=0;const U=(Se,$)=>{var L;if(Se.nodeType===Node.TEXT_NODE){const q=F+(((L=Se.textContent)==null?void 0:L.length)??0);$&&b($,F,q),F=q;return}const $e=Se instanceof Element?Vu(Se.classList)??$:$;Se.childNodes.forEach(q=>U(q,$e))};U(E.content),r.set(u,M),i.set(u,{html:k,language:f,nodes:A.map(Se=>Se.node)})},dispose(){l==null||l.disconnect(),o.clear(),c.clear();for(const u of r.keys())a(u)}};return p}var us={},vs={};/**
53
+ * @license React
54
+ * react-dom-server-legacy.browser.production.min.js
55
+ *
56
+ * Copyright (c) Facebook, Inc. and its affiliates.
57
+ *
58
+ * This source code is licensed under the MIT license found in the
59
+ * LICENSE file in the root directory of this source tree.
60
+ */var Fa;function Gu(){if(Fa)return vs;Fa=1;var t=fo();function n(h){for(var x="https://reactjs.org/docs/error-decoder.html?invariant="+h,S=1;S<arguments.length;S++)x+="&args[]="+encodeURIComponent(arguments[S]);return"Minified React error #"+h+"; visit "+x+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}var s=Object.prototype.hasOwnProperty,r=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,i={},a={};function o(h){return s.call(a,h)?!0:s.call(i,h)?!1:r.test(h)?a[h]=!0:(i[h]=!0,!1)}function c(h,x,S,P,de,oe,Ne){this.acceptsBooleans=x===2||x===3||x===4,this.attributeName=P,this.attributeNamespace=de,this.mustUseProperty=S,this.propertyName=h,this.type=x,this.sanitizeURL=oe,this.removeEmptyString=Ne}var l={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(h){l[h]=new c(h,0,!1,h,null,!1,!1)}),[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(h){var x=h[0];l[x]=new c(x,1,!1,h[1],null,!1,!1)}),["contentEditable","draggable","spellCheck","value"].forEach(function(h){l[h]=new c(h,2,!1,h.toLowerCase(),null,!1,!1)}),["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(h){l[h]=new c(h,2,!1,h,null,!1,!1)}),"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(h){l[h]=new c(h,3,!1,h.toLowerCase(),null,!1,!1)}),["checked","multiple","muted","selected"].forEach(function(h){l[h]=new c(h,3,!0,h,null,!1,!1)}),["capture","download"].forEach(function(h){l[h]=new c(h,4,!1,h,null,!1,!1)}),["cols","rows","size","span"].forEach(function(h){l[h]=new c(h,6,!1,h,null,!1,!1)}),["rowSpan","start"].forEach(function(h){l[h]=new c(h,5,!1,h.toLowerCase(),null,!1,!1)});var p=/[\-:]([a-z])/g;function u(h){return h[1].toUpperCase()}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(h){var x=h.replace(p,u);l[x]=new c(x,1,!1,h,null,!1,!1)}),"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(h){var x=h.replace(p,u);l[x]=new c(x,1,!1,h,"http://www.w3.org/1999/xlink",!1,!1)}),["xml:base","xml:lang","xml:space"].forEach(function(h){var x=h.replace(p,u);l[x]=new c(x,1,!1,h,"http://www.w3.org/XML/1998/namespace",!1,!1)}),["tabIndex","crossOrigin"].forEach(function(h){l[h]=new c(h,1,!1,h.toLowerCase(),null,!1,!1)}),l.xlinkHref=new c("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1),["src","href","action","formAction"].forEach(function(h){l[h]=new c(h,1,!1,h.toLowerCase(),null,!0,!0)});var f={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},k=["Webkit","ms","Moz","O"];Object.keys(f).forEach(function(h){k.forEach(function(x){x=x+h.charAt(0).toUpperCase()+h.substring(1),f[x]=f[h]})});var j=/["'&<>]/;function R(h){if(typeof h=="boolean"||typeof h=="number")return""+h;h=""+h;var x=j.exec(h);if(x){var S="",P,de=0;for(P=x.index;P<h.length;P++){switch(h.charCodeAt(P)){case 34:x="&quot;";break;case 38:x="&amp;";break;case 39:x="&#x27;";break;case 60:x="&lt;";break;case 62:x="&gt;";break;default:continue}de!==P&&(S+=h.substring(de,P)),de=P+1,S+=x}h=de!==P?S+h.substring(de,P):S}return h}var E=/([A-Z])/g,A=/^ms-/,N=Array.isArray;function T(h,x){return{insertionMode:h,selectedValue:x}}function y(h,x,S){switch(x){case"select":return T(1,S.value!=null?S.value:S.defaultValue);case"svg":return T(2,null);case"math":return T(3,null);case"foreignObject":return T(1,null);case"table":return T(4,null);case"thead":case"tbody":case"tfoot":return T(5,null);case"colgroup":return T(7,null);case"tr":return T(6,null)}return 4<=h.insertionMode||h.insertionMode===0?T(1,null):h}var M=new Map;function b(h,x,S){if(typeof S!="object")throw Error(n(62));x=!0;for(var P in S)if(s.call(S,P)){var de=S[P];if(de!=null&&typeof de!="boolean"&&de!==""){if(P.indexOf("--")===0){var oe=R(P);de=R((""+de).trim())}else{oe=P;var Ne=M.get(oe);Ne!==void 0||(Ne=R(oe.replace(E,"-$1").toLowerCase().replace(A,"-ms-")),M.set(oe,Ne)),oe=Ne,de=typeof de=="number"?de===0||s.call(f,P)?""+de:de+"px":R((""+de).trim())}x?(x=!1,h.push(' style="',oe,":",de)):h.push(";",oe,":",de)}}x||h.push('"')}function F(h,x,S,P){switch(S){case"style":b(h,x,P);return;case"defaultValue":case"defaultChecked":case"innerHTML":case"suppressContentEditableWarning":case"suppressHydrationWarning":return}if(!(2<S.length)||S[0]!=="o"&&S[0]!=="O"||S[1]!=="n"&&S[1]!=="N"){if(x=l.hasOwnProperty(S)?l[S]:null,x!==null){switch(typeof P){case"function":case"symbol":return;case"boolean":if(!x.acceptsBooleans)return}switch(S=x.attributeName,x.type){case 3:P&&h.push(" ",S,'=""');break;case 4:P===!0?h.push(" ",S,'=""'):P!==!1&&h.push(" ",S,'="',R(P),'"');break;case 5:isNaN(P)||h.push(" ",S,'="',R(P),'"');break;case 6:!isNaN(P)&&1<=P&&h.push(" ",S,'="',R(P),'"');break;default:x.sanitizeURL&&(P=""+P),h.push(" ",S,'="',R(P),'"')}}else if(o(S)){switch(typeof P){case"function":case"symbol":return;case"boolean":if(x=S.toLowerCase().slice(0,5),x!=="data-"&&x!=="aria-")return}h.push(" ",S,'="',R(P),'"')}}}function U(h,x,S){if(x!=null){if(S!=null)throw Error(n(60));if(typeof x!="object"||!("__html"in x))throw Error(n(61));x=x.__html,x!=null&&h.push(""+x)}}function ce(h){var x="";return t.Children.forEach(h,function(S){S!=null&&(x+=S)}),x}function ie(h,x,S,P){h.push(Se(S));var de=S=null,oe;for(oe in x)if(s.call(x,oe)){var Ne=x[oe];if(Ne!=null)switch(oe){case"children":S=Ne;break;case"dangerouslySetInnerHTML":de=Ne;break;default:F(h,P,oe,Ne)}}return h.push(">"),U(h,de,S),typeof S=="string"?(h.push(R(S)),null):S}var W=/^[a-zA-Z][a-zA-Z:_\.\-\d]*$/,ve=new Map;function Se(h){var x=ve.get(h);if(x===void 0){if(!W.test(h))throw Error(n(65,h));x="<"+h,ve.set(h,x)}return x}function $(h,x,S,P,de){switch(x){case"select":h.push(Se("select"));var oe=null,Ne=null;for(gt in S)if(s.call(S,gt)){var Ke=S[gt];if(Ke!=null)switch(gt){case"children":oe=Ke;break;case"dangerouslySetInnerHTML":Ne=Ke;break;case"defaultValue":case"value":break;default:F(h,P,gt,Ke)}}return h.push(">"),U(h,Ne,oe),oe;case"option":Ne=de.selectedValue,h.push(Se("option"));var ht=Ke=null,ut=null,gt=null;for(oe in S)if(s.call(S,oe)){var Rt=S[oe];if(Rt!=null)switch(oe){case"children":Ke=Rt;break;case"selected":ut=Rt;break;case"dangerouslySetInnerHTML":gt=Rt;break;case"value":ht=Rt;default:F(h,P,oe,Rt)}}if(Ne!=null)if(S=ht!==null?""+ht:ce(Ke),N(Ne)){for(P=0;P<Ne.length;P++)if(""+Ne[P]===S){h.push(' selected=""');break}}else""+Ne===S&&h.push(' selected=""');else ut&&h.push(' selected=""');return h.push(">"),U(h,gt,Ke),Ke;case"textarea":h.push(Se("textarea")),gt=Ne=oe=null;for(Ke in S)if(s.call(S,Ke)&&(ht=S[Ke],ht!=null))switch(Ke){case"children":gt=ht;break;case"value":oe=ht;break;case"defaultValue":Ne=ht;break;case"dangerouslySetInnerHTML":throw Error(n(91));default:F(h,P,Ke,ht)}if(oe===null&&Ne!==null&&(oe=Ne),h.push(">"),gt!=null){if(oe!=null)throw Error(n(92));if(N(gt)&&1<gt.length)throw Error(n(93));oe=""+gt}return typeof oe=="string"&&oe[0]===`
61
+ `&&h.push(`
62
+ `),oe!==null&&h.push(R(""+oe)),null;case"input":h.push(Se("input")),ht=gt=Ke=oe=null;for(Ne in S)if(s.call(S,Ne)&&(ut=S[Ne],ut!=null))switch(Ne){case"children":case"dangerouslySetInnerHTML":throw Error(n(399,"input"));case"defaultChecked":ht=ut;break;case"defaultValue":Ke=ut;break;case"checked":gt=ut;break;case"value":oe=ut;break;default:F(h,P,Ne,ut)}return gt!==null?F(h,P,"checked",gt):ht!==null&&F(h,P,"checked",ht),oe!==null?F(h,P,"value",oe):Ke!==null&&F(h,P,"value",Ke),h.push("/>"),null;case"menuitem":h.push(Se("menuitem"));for(var rn in S)if(s.call(S,rn)&&(oe=S[rn],oe!=null))switch(rn){case"children":case"dangerouslySetInnerHTML":throw Error(n(400));default:F(h,P,rn,oe)}return h.push(">"),null;case"title":h.push(Se("title")),oe=null;for(Rt in S)if(s.call(S,Rt)&&(Ne=S[Rt],Ne!=null))switch(Rt){case"children":oe=Ne;break;case"dangerouslySetInnerHTML":throw Error(n(434));default:F(h,P,Rt,Ne)}return h.push(">"),oe;case"listing":case"pre":h.push(Se(x)),Ne=oe=null;for(ht in S)if(s.call(S,ht)&&(Ke=S[ht],Ke!=null))switch(ht){case"children":oe=Ke;break;case"dangerouslySetInnerHTML":Ne=Ke;break;default:F(h,P,ht,Ke)}if(h.push(">"),Ne!=null){if(oe!=null)throw Error(n(60));if(typeof Ne!="object"||!("__html"in Ne))throw Error(n(61));S=Ne.__html,S!=null&&(typeof S=="string"&&0<S.length&&S[0]===`
63
+ `?h.push(`
64
+ `,S):h.push(""+S))}return typeof oe=="string"&&oe[0]===`
65
+ `&&h.push(`
66
+ `),oe;case"area":case"base":case"br":case"col":case"embed":case"hr":case"img":case"keygen":case"link":case"meta":case"param":case"source":case"track":case"wbr":h.push(Se(x));for(var pn in S)if(s.call(S,pn)&&(oe=S[pn],oe!=null))switch(pn){case"children":case"dangerouslySetInnerHTML":throw Error(n(399,x));default:F(h,P,pn,oe)}return h.push("/>"),null;case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return ie(h,S,x,P);case"html":return de.insertionMode===0&&h.push("<!DOCTYPE html>"),ie(h,S,x,P);default:if(x.indexOf("-")===-1&&typeof S.is!="string")return ie(h,S,x,P);h.push(Se(x)),Ne=oe=null;for(ut in S)if(s.call(S,ut)&&(Ke=S[ut],Ke!=null))switch(ut){case"children":oe=Ke;break;case"dangerouslySetInnerHTML":Ne=Ke;break;case"style":b(h,P,Ke);break;case"suppressContentEditableWarning":case"suppressHydrationWarning":break;default:o(ut)&&typeof Ke!="function"&&typeof Ke!="symbol"&&h.push(" ",ut,'="',R(Ke),'"')}return h.push(">"),U(h,Ne,oe),oe}}function $e(h,x,S){if(h.push('<!--$?--><template id="'),S===null)throw Error(n(395));return h.push(S),h.push('"></template>')}function L(h,x,S,P){switch(S.insertionMode){case 0:case 1:return h.push('<div hidden id="'),h.push(x.segmentPrefix),x=P.toString(16),h.push(x),h.push('">');case 2:return h.push('<svg aria-hidden="true" style="display:none" id="'),h.push(x.segmentPrefix),x=P.toString(16),h.push(x),h.push('">');case 3:return h.push('<math aria-hidden="true" style="display:none" id="'),h.push(x.segmentPrefix),x=P.toString(16),h.push(x),h.push('">');case 4:return h.push('<table hidden id="'),h.push(x.segmentPrefix),x=P.toString(16),h.push(x),h.push('">');case 5:return h.push('<table hidden><tbody id="'),h.push(x.segmentPrefix),x=P.toString(16),h.push(x),h.push('">');case 6:return h.push('<table hidden><tr id="'),h.push(x.segmentPrefix),x=P.toString(16),h.push(x),h.push('">');case 7:return h.push('<table hidden><colgroup id="'),h.push(x.segmentPrefix),x=P.toString(16),h.push(x),h.push('">');default:throw Error(n(397))}}function q(h,x){switch(x.insertionMode){case 0:case 1:return h.push("</div>");case 2:return h.push("</svg>");case 3:return h.push("</math>");case 4:return h.push("</table>");case 5:return h.push("</tbody></table>");case 6:return h.push("</tr></table>");case 7:return h.push("</colgroup></table>");default:throw Error(n(397))}}var fe=/[<\u2028\u2029]/g;function je(h){return JSON.stringify(h).replace(fe,function(x){switch(x){case"<":return"\\u003c";case"\u2028":return"\\u2028";case"\u2029":return"\\u2029";default:throw Error("escapeJSStringsForInstructionScripts encountered a match it does not know how to replace. this means the match regex and the replacement characters are no longer in sync. This is a bug in React")}})}function ne(h,x){return x=x===void 0?"":x,{bootstrapChunks:[],startInlineScript:"<script>",placeholderPrefix:x+"P:",segmentPrefix:x+"S:",boundaryPrefix:x+"B:",idPrefix:x,nextSuspenseID:0,sentCompleteSegmentFunction:!1,sentCompleteBoundaryFunction:!1,sentClientRenderFunction:!1,generateStaticMarkup:h}}function Pe(h,x,S,P){return S.generateStaticMarkup?(h.push(R(x)),!1):(x===""?h=P:(P&&h.push("<!-- -->"),h.push(R(x)),h=!0),h)}var B=Object.assign,we=Symbol.for("react.element"),re=Symbol.for("react.portal"),Ie=Symbol.for("react.fragment"),_=Symbol.for("react.strict_mode"),le=Symbol.for("react.profiler"),O=Symbol.for("react.provider"),ge=Symbol.for("react.context"),pe=Symbol.for("react.forward_ref"),Ae=Symbol.for("react.suspense"),ae=Symbol.for("react.suspense_list"),Te=Symbol.for("react.memo"),Z=Symbol.for("react.lazy"),Fe=Symbol.for("react.scope"),z=Symbol.for("react.debug_trace_mode"),G=Symbol.for("react.legacy_hidden"),J=Symbol.for("react.default_value"),Ee=Symbol.iterator;function V(h){if(h==null)return null;if(typeof h=="function")return h.displayName||h.name||null;if(typeof h=="string")return h;switch(h){case Ie:return"Fragment";case re:return"Portal";case le:return"Profiler";case _:return"StrictMode";case Ae:return"Suspense";case ae:return"SuspenseList"}if(typeof h=="object")switch(h.$$typeof){case ge:return(h.displayName||"Context")+".Consumer";case O:return(h._context.displayName||"Context")+".Provider";case pe:var x=h.render;return h=h.displayName,h||(h=x.displayName||x.name||"",h=h!==""?"ForwardRef("+h+")":"ForwardRef"),h;case Te:return x=h.displayName||null,x!==null?x:V(h.type)||"Memo";case Z:x=h._payload,h=h._init;try{return V(h(x))}catch{}}return null}var Le={};function xe(h,x){if(h=h.contextTypes,!h)return Le;var S={},P;for(P in h)S[P]=x[P];return S}var be=null;function nt(h,x){if(h!==x){h.context._currentValue2=h.parentValue,h=h.parent;var S=x.parent;if(h===null){if(S!==null)throw Error(n(401))}else{if(S===null)throw Error(n(401));nt(h,S)}x.context._currentValue2=x.value}}function Ce(h){h.context._currentValue2=h.parentValue,h=h.parent,h!==null&&Ce(h)}function ye(h){var x=h.parent;x!==null&&ye(x),h.context._currentValue2=h.value}function ze(h,x){if(h.context._currentValue2=h.parentValue,h=h.parent,h===null)throw Error(n(402));h.depth===x.depth?nt(h,x):ze(h,x)}function Ze(h,x){var S=x.parent;if(S===null)throw Error(n(402));h.depth===S.depth?nt(h,S):Ze(h,S),x.context._currentValue2=x.value}function Qe(h){var x=be;x!==h&&(x===null?ye(h):h===null?Ce(x):x.depth===h.depth?nt(x,h):x.depth>h.depth?ze(x,h):Ze(x,h),be=h)}var ct={isMounted:function(){return!1},enqueueSetState:function(h,x){h=h._reactInternals,h.queue!==null&&h.queue.push(x)},enqueueReplaceState:function(h,x){h=h._reactInternals,h.replace=!0,h.queue=[x]},enqueueForceUpdate:function(){}};function tt(h,x,S,P){var de=h.state!==void 0?h.state:null;h.updater=ct,h.props=S,h.state=de;var oe={queue:[],replace:!1};h._reactInternals=oe;var Ne=x.contextType;if(h.context=typeof Ne=="object"&&Ne!==null?Ne._currentValue2:P,Ne=x.getDerivedStateFromProps,typeof Ne=="function"&&(Ne=Ne(S,de),de=Ne==null?de:B({},de,Ne),h.state=de),typeof x.getDerivedStateFromProps!="function"&&typeof h.getSnapshotBeforeUpdate!="function"&&(typeof h.UNSAFE_componentWillMount=="function"||typeof h.componentWillMount=="function"))if(x=h.state,typeof h.componentWillMount=="function"&&h.componentWillMount(),typeof h.UNSAFE_componentWillMount=="function"&&h.UNSAFE_componentWillMount(),x!==h.state&&ct.enqueueReplaceState(h,h.state,null),oe.queue!==null&&0<oe.queue.length)if(x=oe.queue,Ne=oe.replace,oe.queue=null,oe.replace=!1,Ne&&x.length===1)h.state=x[0];else{for(oe=Ne?x[0]:h.state,de=!0,Ne=Ne?1:0;Ne<x.length;Ne++){var Ke=x[Ne];Ke=typeof Ke=="function"?Ke.call(h,oe,S,P):Ke,Ke!=null&&(de?(de=!1,oe=B({},oe,Ke)):B(oe,Ke))}h.state=oe}else oe.queue=null}var Oe={id:1,overflow:""};function ee(h,x,S){var P=h.id;h=h.overflow;var de=32-We(P)-1;P&=~(1<<de),S+=1;var oe=32-We(x)+de;if(30<oe){var Ne=de-de%5;return oe=(P&(1<<Ne)-1).toString(32),P>>=Ne,de-=Ne,{id:1<<32-We(x)+de|S<<de|P,overflow:oe+h}}return{id:1<<oe|S<<de|P,overflow:h}}var We=Math.clz32?Math.clz32:X,w=Math.log,H=Math.LN2;function X(h){return h>>>=0,h===0?32:31-(w(h)/H|0)|0}function ke(h,x){return h===x&&(h!==0||1/h===1/x)||h!==h&&x!==x}var De=typeof Object.is=="function"?Object.is:ke,He=null,ot=null,dt=null,g=null,se=!1,qe=!1,_e=0,at=null,mt=0;function Mt(){if(He===null)throw Error(n(321));return He}function Pt(){if(0<mt)throw Error(n(312));return{memoizedState:null,queue:null,next:null}}function $t(){return g===null?dt===null?(se=!1,dt=g=Pt()):(se=!0,g=dt):g.next===null?(se=!1,g=g.next=Pt()):(se=!0,g=g.next),g}function Ft(){ot=He=null,qe=!1,dt=null,mt=0,g=at=null}function Jt(h,x){return typeof x=="function"?x(h):x}function nn(h,x,S){if(He=Mt(),g=$t(),se){var P=g.queue;if(x=P.dispatch,at!==null&&(S=at.get(P),S!==void 0)){at.delete(P),P=g.memoizedState;do P=h(P,S.action),S=S.next;while(S!==null);return g.memoizedState=P,[P,x]}return[g.memoizedState,x]}return h=h===Jt?typeof x=="function"?x():x:S!==void 0?S(x):x,g.memoizedState=h,h=g.queue={last:null,dispatch:null},h=h.dispatch=Et.bind(null,He,h),[g.memoizedState,h]}function lt(h,x){if(He=Mt(),g=$t(),x=x===void 0?null:x,g!==null){var S=g.memoizedState;if(S!==null&&x!==null){var P=S[1];e:if(P===null)P=!1;else{for(var de=0;de<P.length&&de<x.length;de++)if(!De(x[de],P[de])){P=!1;break e}P=!0}if(P)return S[0]}}return h=h(),g.memoizedState=[h,x],h}function Et(h,x,S){if(25<=mt)throw Error(n(301));if(h===He)if(qe=!0,h={action:S,next:null},at===null&&(at=new Map),S=at.get(x),S===void 0)at.set(x,h);else{for(x=S;x.next!==null;)x=x.next;x.next=h}}function zt(){throw Error(n(394))}function Ht(){}var an={readContext:function(h){return h._currentValue2},useContext:function(h){return Mt(),h._currentValue2},useMemo:lt,useReducer:nn,useRef:function(h){He=Mt(),g=$t();var x=g.memoizedState;return x===null?(h={current:h},g.memoizedState=h):x},useState:function(h){return nn(Jt,h)},useInsertionEffect:Ht,useLayoutEffect:function(){},useCallback:function(h,x){return lt(function(){return h},x)},useImperativeHandle:Ht,useEffect:Ht,useDebugValue:Ht,useDeferredValue:function(h){return Mt(),h},useTransition:function(){return Mt(),[!1,zt]},useId:function(){var h=ot.treeContext,x=h.overflow;h=h.id,h=(h&~(1<<32-We(h)-1)).toString(32)+x;var S=At;if(S===null)throw Error(n(404));return x=_e++,h=":"+S.idPrefix+"R"+h,0<x&&(h+="H"+x.toString(32)),h+":"},useMutableSource:function(h,x){return Mt(),x(h._source)},useSyncExternalStore:function(h,x,S){if(S===void 0)throw Error(n(407));return S()}},At=null,Xt=t.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentDispatcher;function K(h){return console.error(h),null}function Y(){}function Je(h,x,S,P,de,oe,Ne,Ke,ht){var ut=[],gt=new Set;return x={destination:null,responseState:x,progressiveChunkSize:P===void 0?12800:P,status:0,fatalError:null,nextSegmentId:0,allPendingTasks:0,pendingRootTasks:0,completedRootSegment:null,abortableTasks:gt,pingedTasks:ut,clientRenderedBoundaries:[],completedBoundaries:[],partialBoundaries:[],onError:de===void 0?K:de,onAllReady:Y,onShellReady:Ne===void 0?Y:Ne,onShellError:Y,onFatalError:Y},S=te(x,0,null,S,!1,!1),S.parentFlushed=!0,h=Be(x,h,null,S,gt,Le,null,Oe),ut.push(h),x}function Be(h,x,S,P,de,oe,Ne,Ke){h.allPendingTasks++,S===null?h.pendingRootTasks++:S.pendingTasks++;var ht={node:x,ping:function(){var ut=h.pingedTasks;ut.push(ht),ut.length===1&&qn(h)},blockedBoundary:S,blockedSegment:P,abortSet:de,legacyContext:oe,context:Ne,treeContext:Ke};return de.add(ht),ht}function te(h,x,S,P,de,oe){return{status:0,id:-1,index:x,parentFlushed:!1,chunks:[],children:[],formatContext:P,boundary:S,lastPushedText:de,textEmbedded:oe}}function Ve(h,x){if(h=h.onError(x),h!=null&&typeof h!="string")throw Error('onError returned something with a type other than "string". onError should return a string and may return null or undefined but must not return anything else. It received something of type "'+typeof h+'" instead');return h}function Ue(h,x){var S=h.onShellError;S(x),S=h.onFatalError,S(x),h.destination!==null?(h.status=2,h.destination.destroy(x)):(h.status=1,h.fatalError=x)}function yt(h,x,S,P,de){for(He={},ot=x,_e=0,h=S(P,de);qe;)qe=!1,_e=0,mt+=1,g=null,h=S(P,de);return Ft(),h}function Bt(h,x,S,P){var de=S.render(),oe=P.childContextTypes;if(oe!=null){var Ne=x.legacyContext;if(typeof S.getChildContext!="function")P=Ne;else{S=S.getChildContext();for(var Ke in S)if(!(Ke in oe))throw Error(n(108,V(P)||"Unknown",Ke));P=B({},Ne,S)}x.legacyContext=P,St(h,x,de),x.legacyContext=Ne}else St(h,x,de)}function Zt(h,x){if(h&&h.defaultProps){x=B({},x),h=h.defaultProps;for(var S in h)x[S]===void 0&&(x[S]=h[S]);return x}return x}function qt(h,x,S,P,de){if(typeof S=="function")if(S.prototype&&S.prototype.isReactComponent){de=xe(S,x.legacyContext);var oe=S.contextType;oe=new S(P,typeof oe=="object"&&oe!==null?oe._currentValue2:de),tt(oe,S,P,de),Bt(h,x,oe,S)}else{oe=xe(S,x.legacyContext),de=yt(h,x,S,P,oe);var Ne=_e!==0;if(typeof de=="object"&&de!==null&&typeof de.render=="function"&&de.$$typeof===void 0)tt(de,S,P,oe),Bt(h,x,de,S);else if(Ne){P=x.treeContext,x.treeContext=ee(P,1,0);try{St(h,x,de)}finally{x.treeContext=P}}else St(h,x,de)}else if(typeof S=="string"){switch(de=x.blockedSegment,oe=$(de.chunks,S,P,h.responseState,de.formatContext),de.lastPushedText=!1,Ne=de.formatContext,de.formatContext=y(Ne,S,P),pt(h,x,oe),de.formatContext=Ne,S){case"area":case"base":case"br":case"col":case"embed":case"hr":case"img":case"input":case"keygen":case"link":case"meta":case"param":case"source":case"track":case"wbr":break;default:de.chunks.push("</",S,">")}de.lastPushedText=!1}else{switch(S){case G:case z:case _:case le:case Ie:St(h,x,P.children);return;case ae:St(h,x,P.children);return;case Fe:throw Error(n(343));case Ae:e:{S=x.blockedBoundary,de=x.blockedSegment,oe=P.fallback,P=P.children,Ne=new Set;var Ke={id:null,rootSegmentID:-1,parentFlushed:!1,pendingTasks:0,forceClientRender:!1,completedSegments:[],byteSize:0,fallbackAbortableTasks:Ne,errorDigest:null},ht=te(h,de.chunks.length,Ke,de.formatContext,!1,!1);de.children.push(ht),de.lastPushedText=!1;var ut=te(h,0,null,de.formatContext,!1,!1);ut.parentFlushed=!0,x.blockedBoundary=Ke,x.blockedSegment=ut;try{if(pt(h,x,P),h.responseState.generateStaticMarkup||ut.lastPushedText&&ut.textEmbedded&&ut.chunks.push("<!-- -->"),ut.status=1,Vt(Ke,ut),Ke.pendingTasks===0)break e}catch(gt){ut.status=4,Ke.forceClientRender=!0,Ke.errorDigest=Ve(h,gt)}finally{x.blockedBoundary=S,x.blockedSegment=de}x=Be(h,oe,S,ht,Ne,x.legacyContext,x.context,x.treeContext),h.pingedTasks.push(x)}return}if(typeof S=="object"&&S!==null)switch(S.$$typeof){case pe:if(P=yt(h,x,S.render,P,de),_e!==0){S=x.treeContext,x.treeContext=ee(S,1,0);try{St(h,x,P)}finally{x.treeContext=S}}else St(h,x,P);return;case Te:S=S.type,P=Zt(S,P),qt(h,x,S,P,de);return;case O:if(de=P.children,S=S._context,P=P.value,oe=S._currentValue2,S._currentValue2=P,Ne=be,be=P={parent:Ne,depth:Ne===null?0:Ne.depth+1,context:S,parentValue:oe,value:P},x.context=P,St(h,x,de),h=be,h===null)throw Error(n(403));P=h.parentValue,h.context._currentValue2=P===J?h.context._defaultValue:P,h=be=h.parent,x.context=h;return;case ge:P=P.children,P=P(S._currentValue2),St(h,x,P);return;case Z:de=S._init,S=de(S._payload),P=Zt(S,P),qt(h,x,S,P,void 0);return}throw Error(n(130,S==null?S:typeof S,""))}}function St(h,x,S){if(x.node=S,typeof S=="object"&&S!==null){switch(S.$$typeof){case we:qt(h,x,S.type,S.props,S.ref);return;case re:throw Error(n(257));case Z:var P=S._init;S=P(S._payload),St(h,x,S);return}if(N(S)){dn(h,x,S);return}if(S===null||typeof S!="object"?P=null:(P=Ee&&S[Ee]||S["@@iterator"],P=typeof P=="function"?P:null),P&&(P=P.call(S))){if(S=P.next(),!S.done){var de=[];do de.push(S.value),S=P.next();while(!S.done);dn(h,x,de)}return}throw h=Object.prototype.toString.call(S),Error(n(31,h==="[object Object]"?"object with keys {"+Object.keys(S).join(", ")+"}":h))}typeof S=="string"?(P=x.blockedSegment,P.lastPushedText=Pe(x.blockedSegment.chunks,S,h.responseState,P.lastPushedText)):typeof S=="number"&&(P=x.blockedSegment,P.lastPushedText=Pe(x.blockedSegment.chunks,""+S,h.responseState,P.lastPushedText))}function dn(h,x,S){for(var P=S.length,de=0;de<P;de++){var oe=x.treeContext;x.treeContext=ee(oe,P,de);try{pt(h,x,S[de])}finally{x.treeContext=oe}}}function pt(h,x,S){var P=x.blockedSegment.formatContext,de=x.legacyContext,oe=x.context;try{return St(h,x,S)}catch(ht){if(Ft(),typeof ht=="object"&&ht!==null&&typeof ht.then=="function"){S=ht;var Ne=x.blockedSegment,Ke=te(h,Ne.chunks.length,null,Ne.formatContext,Ne.lastPushedText,!0);Ne.children.push(Ke),Ne.lastPushedText=!1,h=Be(h,x.node,x.blockedBoundary,Ke,x.abortSet,x.legacyContext,x.context,x.treeContext).ping,S.then(h,h),x.blockedSegment.formatContext=P,x.legacyContext=de,x.context=oe,Qe(oe)}else throw x.blockedSegment.formatContext=P,x.legacyContext=de,x.context=oe,Qe(oe),ht}}function Dt(h){var x=h.blockedBoundary;h=h.blockedSegment,h.status=3,un(this,x,h)}function Yt(h,x,S){var P=h.blockedBoundary;h.blockedSegment.status=3,P===null?(x.allPendingTasks--,x.status!==2&&(x.status=2,x.destination!==null&&x.destination.push(null))):(P.pendingTasks--,P.forceClientRender||(P.forceClientRender=!0,h=S===void 0?Error(n(432)):S,P.errorDigest=x.onError(h),P.parentFlushed&&x.clientRenderedBoundaries.push(P)),P.fallbackAbortableTasks.forEach(function(de){return Yt(de,x,S)}),P.fallbackAbortableTasks.clear(),x.allPendingTasks--,x.allPendingTasks===0&&(P=x.onAllReady,P()))}function Vt(h,x){if(x.chunks.length===0&&x.children.length===1&&x.children[0].boundary===null){var S=x.children[0];S.id=x.id,S.parentFlushed=!0,S.status===1&&Vt(h,S)}else h.completedSegments.push(x)}function un(h,x,S){if(x===null){if(S.parentFlushed){if(h.completedRootSegment!==null)throw Error(n(389));h.completedRootSegment=S}h.pendingRootTasks--,h.pendingRootTasks===0&&(h.onShellError=Y,x=h.onShellReady,x())}else x.pendingTasks--,x.forceClientRender||(x.pendingTasks===0?(S.parentFlushed&&S.status===1&&Vt(x,S),x.parentFlushed&&h.completedBoundaries.push(x),x.fallbackAbortableTasks.forEach(Dt,h),x.fallbackAbortableTasks.clear()):S.parentFlushed&&S.status===1&&(Vt(x,S),x.completedSegments.length===1&&x.parentFlushed&&h.partialBoundaries.push(x)));h.allPendingTasks--,h.allPendingTasks===0&&(h=h.onAllReady,h())}function qn(h){if(h.status!==2){var x=be,S=Xt.current;Xt.current=an;var P=At;At=h.responseState;try{var de=h.pingedTasks,oe;for(oe=0;oe<de.length;oe++){var Ne=de[oe],Ke=h,ht=Ne.blockedSegment;if(ht.status===0){Qe(Ne.context);try{St(Ke,Ne,Ne.node),Ke.responseState.generateStaticMarkup||ht.lastPushedText&&ht.textEmbedded&&ht.chunks.push("<!-- -->"),Ne.abortSet.delete(Ne),ht.status=1,un(Ke,Ne.blockedBoundary,ht)}catch(en){if(Ft(),typeof en=="object"&&en!==null&&typeof en.then=="function"){var ut=Ne.ping;en.then(ut,ut)}else{Ne.abortSet.delete(Ne),ht.status=4;var gt=Ne.blockedBoundary,Rt=en,rn=Ve(Ke,Rt);if(gt===null?Ue(Ke,Rt):(gt.pendingTasks--,gt.forceClientRender||(gt.forceClientRender=!0,gt.errorDigest=rn,gt.parentFlushed&&Ke.clientRenderedBoundaries.push(gt))),Ke.allPendingTasks--,Ke.allPendingTasks===0){var pn=Ke.onAllReady;pn()}}}finally{}}}de.splice(0,oe),h.destination!==null&&Kt(h,h.destination)}catch(en){Ve(h,en),Ue(h,en)}finally{At=P,Xt.current=S,S===an&&Qe(x)}}}function wn(h,x,S){switch(S.parentFlushed=!0,S.status){case 0:var P=S.id=h.nextSegmentId++;return S.lastPushedText=!1,S.textEmbedded=!1,h=h.responseState,x.push('<template id="'),x.push(h.placeholderPrefix),h=P.toString(16),x.push(h),x.push('"></template>');case 1:S.status=2;var de=!0;P=S.chunks;var oe=0;S=S.children;for(var Ne=0;Ne<S.length;Ne++){for(de=S[Ne];oe<de.index;oe++)x.push(P[oe]);de=sn(h,x,de)}for(;oe<P.length-1;oe++)x.push(P[oe]);return oe<P.length&&(de=x.push(P[oe])),de;default:throw Error(n(390))}}function sn(h,x,S){var P=S.boundary;if(P===null)return wn(h,x,S);if(P.parentFlushed=!0,P.forceClientRender)return h.responseState.generateStaticMarkup||(P=P.errorDigest,x.push("<!--$!-->"),x.push("<template"),P&&(x.push(' data-dgst="'),P=R(P),x.push(P),x.push('"')),x.push("></template>")),wn(h,x,S),h=h.responseState.generateStaticMarkup?!0:x.push("<!--/$-->"),h;if(0<P.pendingTasks){P.rootSegmentID=h.nextSegmentId++,0<P.completedSegments.length&&h.partialBoundaries.push(P);var de=h.responseState,oe=de.nextSuspenseID++;return de=de.boundaryPrefix+oe.toString(16),P=P.id=de,$e(x,h.responseState,P),wn(h,x,S),x.push("<!--/$-->")}if(P.byteSize>h.progressiveChunkSize)return P.rootSegmentID=h.nextSegmentId++,h.completedBoundaries.push(P),$e(x,h.responseState,P.id),wn(h,x,S),x.push("<!--/$-->");if(h.responseState.generateStaticMarkup||x.push("<!--$-->"),S=P.completedSegments,S.length!==1)throw Error(n(391));return sn(h,x,S[0]),h=h.responseState.generateStaticMarkup?!0:x.push("<!--/$-->"),h}function bn(h,x,S){return L(x,h.responseState,S.formatContext,S.id),sn(h,x,S),q(x,S.formatContext)}function zn(h,x,S){for(var P=S.completedSegments,de=0;de<P.length;de++)Tt(h,x,S,P[de]);if(P.length=0,h=h.responseState,P=S.id,S=S.rootSegmentID,x.push(h.startInlineScript),h.sentCompleteBoundaryFunction?x.push('$RC("'):(h.sentCompleteBoundaryFunction=!0,x.push('function $RC(a,b){a=document.getElementById(a);b=document.getElementById(b);b.parentNode.removeChild(b);if(a){a=a.previousSibling;var f=a.parentNode,c=a.nextSibling,e=0;do{if(c&&8===c.nodeType){var d=c.data;if("/$"===d)if(0===e)break;else e--;else"$"!==d&&"$?"!==d&&"$!"!==d||e++}d=c.nextSibling;f.removeChild(c);c=d}while(c);for(;b.firstChild;)f.insertBefore(b.firstChild,c);a.data="$";a._reactRetry&&a._reactRetry()}};$RC("')),P===null)throw Error(n(395));return S=S.toString(16),x.push(P),x.push('","'),x.push(h.segmentPrefix),x.push(S),x.push('")<\/script>')}function Tt(h,x,S,P){if(P.status===2)return!0;var de=P.id;if(de===-1){if((P.id=S.rootSegmentID)===-1)throw Error(n(392));return bn(h,x,P)}return bn(h,x,P),h=h.responseState,x.push(h.startInlineScript),h.sentCompleteSegmentFunction?x.push('$RS("'):(h.sentCompleteSegmentFunction=!0,x.push('function $RS(a,b){a=document.getElementById(a);b=document.getElementById(b);for(a.parentNode.removeChild(a);a.firstChild;)b.parentNode.insertBefore(a.firstChild,b);b.parentNode.removeChild(b)};$RS("')),x.push(h.segmentPrefix),de=de.toString(16),x.push(de),x.push('","'),x.push(h.placeholderPrefix),x.push(de),x.push('")<\/script>')}function Kt(h,x){try{var S=h.completedRootSegment;if(S!==null&&h.pendingRootTasks===0){sn(h,x,S),h.completedRootSegment=null;var P=h.responseState.bootstrapChunks;for(S=0;S<P.length-1;S++)x.push(P[S]);S<P.length&&x.push(P[S])}var de=h.clientRenderedBoundaries,oe;for(oe=0;oe<de.length;oe++){var Ne=de[oe];P=x;var Ke=h.responseState,ht=Ne.id,ut=Ne.errorDigest,gt=Ne.errorMessage,Rt=Ne.errorComponentStack;if(P.push(Ke.startInlineScript),Ke.sentClientRenderFunction?P.push('$RX("'):(Ke.sentClientRenderFunction=!0,P.push('function $RX(b,c,d,e){var a=document.getElementById(b);a&&(b=a.previousSibling,b.data="$!",a=a.dataset,c&&(a.dgst=c),d&&(a.msg=d),e&&(a.stck=e),b._reactRetry&&b._reactRetry())};$RX("')),ht===null)throw Error(n(395));if(P.push(ht),P.push('"'),ut||gt||Rt){P.push(",");var rn=je(ut||"");P.push(rn)}if(gt||Rt){P.push(",");var pn=je(gt||"");P.push(pn)}if(Rt){P.push(",");var en=je(Rt);P.push(en)}if(!P.push(")<\/script>")){h.destination=null,oe++,de.splice(0,oe);return}}de.splice(0,oe);var jn=h.completedBoundaries;for(oe=0;oe<jn.length;oe++)if(!zn(h,x,jn[oe])){h.destination=null,oe++,jn.splice(0,oe);return}jn.splice(0,oe);var xn=h.partialBoundaries;for(oe=0;oe<xn.length;oe++){var Cn=xn[oe];e:{de=h,Ne=x;var tn=Cn.completedSegments;for(Ke=0;Ke<tn.length;Ke++)if(!Tt(de,Ne,Cn,tn[Ke])){Ke++,tn.splice(0,Ke);var Gn=!1;break e}tn.splice(0,Ke),Gn=!0}if(!Gn){h.destination=null,oe++,xn.splice(0,oe);return}}xn.splice(0,oe);var Rn=h.completedBoundaries;for(oe=0;oe<Rn.length;oe++)if(!zn(h,x,Rn[oe])){h.destination=null,oe++,Rn.splice(0,oe);return}Rn.splice(0,oe)}finally{h.allPendingTasks===0&&h.pingedTasks.length===0&&h.clientRenderedBoundaries.length===0&&h.completedBoundaries.length===0&&x.push(null)}}function _n(h,x){try{var S=h.abortableTasks;S.forEach(function(P){return Yt(P,h,x)}),S.clear(),h.destination!==null&&Kt(h,h.destination)}catch(P){Ve(h,P),Ue(h,P)}}function Vn(){}function Kn(h,x,S,P){var de=!1,oe=null,Ne="",Ke={push:function(ut){return ut!==null&&(Ne+=ut),!0},destroy:function(ut){de=!0,oe=ut}},ht=!1;if(h=Je(h,ne(S,x?x.identifierPrefix:void 0),{insertionMode:1,selectedValue:null},1/0,Vn,void 0,function(){ht=!0}),qn(h),_n(h,P),h.status===1)h.status=2,Ke.destroy(h.fatalError);else if(h.status!==2&&h.destination===null){h.destination=Ke;try{Kt(h,Ke)}catch(ut){Ve(h,ut),Ue(h,ut)}}if(de)throw oe;if(!ht)throw Error(n(426));return Ne}return vs.renderToNodeStream=function(){throw Error(n(207))},vs.renderToStaticMarkup=function(h,x){return Kn(h,x,!0,'The server used "renderToStaticMarkup" which does not support Suspense. If you intended to have the server wait for the suspended component please switch to "renderToReadableStream" which supports Suspense on the server')},vs.renderToStaticNodeStream=function(){throw Error(n(208))},vs.renderToString=function(h,x){return Kn(h,x,!1,'The server used "renderToString" which does not support Suspense. If you intended for this Suspense boundary to render the fallback content on the server consider throwing an Error somewhere within the Suspense boundary. If you intended to have the server wait for the suspended component please switch to "renderToReadableStream" which supports Suspense on the server')},vs.version="18.3.1",vs}var or={};/**
67
+ * @license React
68
+ * react-dom-server.browser.production.min.js
69
+ *
70
+ * Copyright (c) Facebook, Inc. and its affiliates.
71
+ *
72
+ * This source code is licensed under the MIT license found in the
73
+ * LICENSE file in the root directory of this source tree.
74
+ */var Oa;function Ju(){if(Oa)return or;Oa=1;var t=fo();function n(m){for(var v="https://reactjs.org/docs/error-decoder.html?invariant="+m,C=1;C<arguments.length;C++)v+="&args[]="+encodeURIComponent(arguments[C]);return"Minified React error #"+m+"; visit "+v+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}var s=null,r=0;function i(m,v){if(v.length!==0)if(512<v.length)0<r&&(m.enqueue(new Uint8Array(s.buffer,0,r)),s=new Uint8Array(512),r=0),m.enqueue(v);else{var C=s.length-r;C<v.length&&(C===0?m.enqueue(s):(s.set(v.subarray(0,C),r),m.enqueue(s),v=v.subarray(C)),s=new Uint8Array(512),r=0),s.set(v,r),r+=v.length}}function a(m,v){return i(m,v),!0}function o(m){s&&0<r&&(m.enqueue(new Uint8Array(s.buffer,0,r)),s=null,r=0)}var c=new TextEncoder;function l(m){return c.encode(m)}function p(m){return c.encode(m)}function u(m,v){typeof m.error=="function"?m.error(v):m.close()}var f=Object.prototype.hasOwnProperty,k=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,j={},R={};function E(m){return f.call(R,m)?!0:f.call(j,m)?!1:k.test(m)?R[m]=!0:(j[m]=!0,!1)}function A(m,v,C,D,he,ue,Me){this.acceptsBooleans=v===2||v===3||v===4,this.attributeName=D,this.attributeNamespace=he,this.mustUseProperty=C,this.propertyName=m,this.type=v,this.sanitizeURL=ue,this.removeEmptyString=Me}var N={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(m){N[m]=new A(m,0,!1,m,null,!1,!1)}),[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(m){var v=m[0];N[v]=new A(v,1,!1,m[1],null,!1,!1)}),["contentEditable","draggable","spellCheck","value"].forEach(function(m){N[m]=new A(m,2,!1,m.toLowerCase(),null,!1,!1)}),["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(m){N[m]=new A(m,2,!1,m,null,!1,!1)}),"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(m){N[m]=new A(m,3,!1,m.toLowerCase(),null,!1,!1)}),["checked","multiple","muted","selected"].forEach(function(m){N[m]=new A(m,3,!0,m,null,!1,!1)}),["capture","download"].forEach(function(m){N[m]=new A(m,4,!1,m,null,!1,!1)}),["cols","rows","size","span"].forEach(function(m){N[m]=new A(m,6,!1,m,null,!1,!1)}),["rowSpan","start"].forEach(function(m){N[m]=new A(m,5,!1,m.toLowerCase(),null,!1,!1)});var T=/[\-:]([a-z])/g;function y(m){return m[1].toUpperCase()}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(m){var v=m.replace(T,y);N[v]=new A(v,1,!1,m,null,!1,!1)}),"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(m){var v=m.replace(T,y);N[v]=new A(v,1,!1,m,"http://www.w3.org/1999/xlink",!1,!1)}),["xml:base","xml:lang","xml:space"].forEach(function(m){var v=m.replace(T,y);N[v]=new A(v,1,!1,m,"http://www.w3.org/XML/1998/namespace",!1,!1)}),["tabIndex","crossOrigin"].forEach(function(m){N[m]=new A(m,1,!1,m.toLowerCase(),null,!1,!1)}),N.xlinkHref=new A("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1),["src","href","action","formAction"].forEach(function(m){N[m]=new A(m,1,!1,m.toLowerCase(),null,!0,!0)});var M={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},b=["Webkit","ms","Moz","O"];Object.keys(M).forEach(function(m){b.forEach(function(v){v=v+m.charAt(0).toUpperCase()+m.substring(1),M[v]=M[m]})});var F=/["'&<>]/;function U(m){if(typeof m=="boolean"||typeof m=="number")return""+m;m=""+m;var v=F.exec(m);if(v){var C="",D,he=0;for(D=v.index;D<m.length;D++){switch(m.charCodeAt(D)){case 34:v="&quot;";break;case 38:v="&amp;";break;case 39:v="&#x27;";break;case 60:v="&lt;";break;case 62:v="&gt;";break;default:continue}he!==D&&(C+=m.substring(he,D)),he=D+1,C+=v}m=he!==D?C+m.substring(he,D):C}return m}var ce=/([A-Z])/g,ie=/^ms-/,W=Array.isArray,ve=p("<script>"),Se=p("<\/script>"),$=p('<script src="'),$e=p('<script type="module" src="'),L=p('" async=""><\/script>'),q=/(<\/|<)(s)(cript)/gi;function fe(m,v,C,D){return""+v+(C==="s"?"\\u0073":"\\u0053")+D}function je(m,v,C,D,he){m=m===void 0?"":m,v=v===void 0?ve:p('<script nonce="'+U(v)+'">');var ue=[];if(C!==void 0&&ue.push(v,l((""+C).replace(q,fe)),Se),D!==void 0)for(C=0;C<D.length;C++)ue.push($,l(U(D[C])),L);if(he!==void 0)for(D=0;D<he.length;D++)ue.push($e,l(U(he[D])),L);return{bootstrapChunks:ue,startInlineScript:v,placeholderPrefix:p(m+"P:"),segmentPrefix:p(m+"S:"),boundaryPrefix:m+"B:",idPrefix:m,nextSuspenseID:0,sentCompleteSegmentFunction:!1,sentCompleteBoundaryFunction:!1,sentClientRenderFunction:!1}}function ne(m,v){return{insertionMode:m,selectedValue:v}}function Pe(m){return ne(m==="http://www.w3.org/2000/svg"?2:m==="http://www.w3.org/1998/Math/MathML"?3:0,null)}function B(m,v,C){switch(v){case"select":return ne(1,C.value!=null?C.value:C.defaultValue);case"svg":return ne(2,null);case"math":return ne(3,null);case"foreignObject":return ne(1,null);case"table":return ne(4,null);case"thead":case"tbody":case"tfoot":return ne(5,null);case"colgroup":return ne(7,null);case"tr":return ne(6,null)}return 4<=m.insertionMode||m.insertionMode===0?ne(1,null):m}var we=p("<!-- -->");function re(m,v,C,D){return v===""?D:(D&&m.push(we),m.push(l(U(v))),!0)}var Ie=new Map,_=p(' style="'),le=p(":"),O=p(";");function ge(m,v,C){if(typeof C!="object")throw Error(n(62));v=!0;for(var D in C)if(f.call(C,D)){var he=C[D];if(he!=null&&typeof he!="boolean"&&he!==""){if(D.indexOf("--")===0){var ue=l(U(D));he=l(U((""+he).trim()))}else{ue=D;var Me=Ie.get(ue);Me!==void 0||(Me=p(U(ue.replace(ce,"-$1").toLowerCase().replace(ie,"-ms-"))),Ie.set(ue,Me)),ue=Me,he=typeof he=="number"?he===0||f.call(M,D)?l(""+he):l(he+"px"):l(U((""+he).trim()))}v?(v=!1,m.push(_,ue,le,he)):m.push(O,ue,le,he)}}v||m.push(ae)}var pe=p(" "),Ae=p('="'),ae=p('"'),Te=p('=""');function Z(m,v,C,D){switch(C){case"style":ge(m,v,D);return;case"defaultValue":case"defaultChecked":case"innerHTML":case"suppressContentEditableWarning":case"suppressHydrationWarning":return}if(!(2<C.length)||C[0]!=="o"&&C[0]!=="O"||C[1]!=="n"&&C[1]!=="N"){if(v=N.hasOwnProperty(C)?N[C]:null,v!==null){switch(typeof D){case"function":case"symbol":return;case"boolean":if(!v.acceptsBooleans)return}switch(C=l(v.attributeName),v.type){case 3:D&&m.push(pe,C,Te);break;case 4:D===!0?m.push(pe,C,Te):D!==!1&&m.push(pe,C,Ae,l(U(D)),ae);break;case 5:isNaN(D)||m.push(pe,C,Ae,l(U(D)),ae);break;case 6:!isNaN(D)&&1<=D&&m.push(pe,C,Ae,l(U(D)),ae);break;default:v.sanitizeURL&&(D=""+D),m.push(pe,C,Ae,l(U(D)),ae)}}else if(E(C)){switch(typeof D){case"function":case"symbol":return;case"boolean":if(v=C.toLowerCase().slice(0,5),v!=="data-"&&v!=="aria-")return}m.push(pe,l(C),Ae,l(U(D)),ae)}}}var Fe=p(">"),z=p("/>");function G(m,v,C){if(v!=null){if(C!=null)throw Error(n(60));if(typeof v!="object"||!("__html"in v))throw Error(n(61));v=v.__html,v!=null&&m.push(l(""+v))}}function J(m){var v="";return t.Children.forEach(m,function(C){C!=null&&(v+=C)}),v}var Ee=p(' selected=""');function V(m,v,C,D){m.push(nt(C));var he=C=null,ue;for(ue in v)if(f.call(v,ue)){var Me=v[ue];if(Me!=null)switch(ue){case"children":C=Me;break;case"dangerouslySetInnerHTML":he=Me;break;default:Z(m,D,ue,Me)}}return m.push(Fe),G(m,he,C),typeof C=="string"?(m.push(l(U(C))),null):C}var Le=p(`
75
+ `),xe=/^[a-zA-Z][a-zA-Z:_\.\-\d]*$/,be=new Map;function nt(m){var v=be.get(m);if(v===void 0){if(!xe.test(m))throw Error(n(65,m));v=p("<"+m),be.set(m,v)}return v}var Ce=p("<!DOCTYPE html>");function ye(m,v,C,D,he){switch(v){case"select":m.push(nt("select"));var ue=null,Me=null;for(bt in C)if(f.call(C,bt)){var Ge=C[bt];if(Ge!=null)switch(bt){case"children":ue=Ge;break;case"dangerouslySetInnerHTML":Me=Ge;break;case"defaultValue":case"value":break;default:Z(m,D,bt,Ge)}}return m.push(Fe),G(m,Me,ue),ue;case"option":Me=he.selectedValue,m.push(nt("option"));var xt=Ge=null,jt=null,bt=null;for(ue in C)if(f.call(C,ue)){var Ut=C[ue];if(Ut!=null)switch(ue){case"children":Ge=Ut;break;case"selected":jt=Ut;break;case"dangerouslySetInnerHTML":bt=Ut;break;case"value":xt=Ut;default:Z(m,D,ue,Ut)}}if(Me!=null)if(C=xt!==null?""+xt:J(Ge),W(Me)){for(D=0;D<Me.length;D++)if(""+Me[D]===C){m.push(Ee);break}}else""+Me===C&&m.push(Ee);else jt&&m.push(Ee);return m.push(Fe),G(m,bt,Ge),Ge;case"textarea":m.push(nt("textarea")),bt=Me=ue=null;for(Ge in C)if(f.call(C,Ge)&&(xt=C[Ge],xt!=null))switch(Ge){case"children":bt=xt;break;case"value":ue=xt;break;case"defaultValue":Me=xt;break;case"dangerouslySetInnerHTML":throw Error(n(91));default:Z(m,D,Ge,xt)}if(ue===null&&Me!==null&&(ue=Me),m.push(Fe),bt!=null){if(ue!=null)throw Error(n(92));if(W(bt)&&1<bt.length)throw Error(n(93));ue=""+bt}return typeof ue=="string"&&ue[0]===`
76
+ `&&m.push(Le),ue!==null&&m.push(l(U(""+ue))),null;case"input":m.push(nt("input")),xt=bt=Ge=ue=null;for(Me in C)if(f.call(C,Me)&&(jt=C[Me],jt!=null))switch(Me){case"children":case"dangerouslySetInnerHTML":throw Error(n(399,"input"));case"defaultChecked":xt=jt;break;case"defaultValue":Ge=jt;break;case"checked":bt=jt;break;case"value":ue=jt;break;default:Z(m,D,Me,jt)}return bt!==null?Z(m,D,"checked",bt):xt!==null&&Z(m,D,"checked",xt),ue!==null?Z(m,D,"value",ue):Ge!==null&&Z(m,D,"value",Ge),m.push(z),null;case"menuitem":m.push(nt("menuitem"));for(var Mn in C)if(f.call(C,Mn)&&(ue=C[Mn],ue!=null))switch(Mn){case"children":case"dangerouslySetInnerHTML":throw Error(n(400));default:Z(m,D,Mn,ue)}return m.push(Fe),null;case"title":m.push(nt("title")),ue=null;for(Ut in C)if(f.call(C,Ut)&&(Me=C[Ut],Me!=null))switch(Ut){case"children":ue=Me;break;case"dangerouslySetInnerHTML":throw Error(n(434));default:Z(m,D,Ut,Me)}return m.push(Fe),ue;case"listing":case"pre":m.push(nt(v)),Me=ue=null;for(xt in C)if(f.call(C,xt)&&(Ge=C[xt],Ge!=null))switch(xt){case"children":ue=Ge;break;case"dangerouslySetInnerHTML":Me=Ge;break;default:Z(m,D,xt,Ge)}if(m.push(Fe),Me!=null){if(ue!=null)throw Error(n(60));if(typeof Me!="object"||!("__html"in Me))throw Error(n(61));C=Me.__html,C!=null&&(typeof C=="string"&&0<C.length&&C[0]===`
77
+ `?m.push(Le,l(C)):m.push(l(""+C)))}return typeof ue=="string"&&ue[0]===`
78
+ `&&m.push(Le),ue;case"area":case"base":case"br":case"col":case"embed":case"hr":case"img":case"keygen":case"link":case"meta":case"param":case"source":case"track":case"wbr":m.push(nt(v));for(var Bn in C)if(f.call(C,Bn)&&(ue=C[Bn],ue!=null))switch(Bn){case"children":case"dangerouslySetInnerHTML":throw Error(n(399,v));default:Z(m,D,Bn,ue)}return m.push(z),null;case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return V(m,C,v,D);case"html":return he.insertionMode===0&&m.push(Ce),V(m,C,v,D);default:if(v.indexOf("-")===-1&&typeof C.is!="string")return V(m,C,v,D);m.push(nt(v)),Me=ue=null;for(jt in C)if(f.call(C,jt)&&(Ge=C[jt],Ge!=null))switch(jt){case"children":ue=Ge;break;case"dangerouslySetInnerHTML":Me=Ge;break;case"style":ge(m,D,Ge);break;case"suppressContentEditableWarning":case"suppressHydrationWarning":break;default:E(jt)&&typeof Ge!="function"&&typeof Ge!="symbol"&&m.push(pe,l(jt),Ae,l(U(Ge)),ae)}return m.push(Fe),G(m,Me,ue),ue}}var ze=p("</"),Ze=p(">"),Qe=p('<template id="'),ct=p('"></template>'),tt=p("<!--$-->"),Oe=p('<!--$?--><template id="'),ee=p('"></template>'),We=p("<!--$!-->"),w=p("<!--/$-->"),H=p("<template"),X=p('"'),ke=p(' data-dgst="');p(' data-msg="'),p(' data-stck="');var De=p("></template>");function He(m,v,C){if(i(m,Oe),C===null)throw Error(n(395));return i(m,C),a(m,ee)}var ot=p('<div hidden id="'),dt=p('">'),g=p("</div>"),se=p('<svg aria-hidden="true" style="display:none" id="'),qe=p('">'),_e=p("</svg>"),at=p('<math aria-hidden="true" style="display:none" id="'),mt=p('">'),Mt=p("</math>"),Pt=p('<table hidden id="'),$t=p('">'),Ft=p("</table>"),Jt=p('<table hidden><tbody id="'),nn=p('">'),lt=p("</tbody></table>"),Et=p('<table hidden><tr id="'),zt=p('">'),Ht=p("</tr></table>"),an=p('<table hidden><colgroup id="'),At=p('">'),Xt=p("</colgroup></table>");function K(m,v,C,D){switch(C.insertionMode){case 0:case 1:return i(m,ot),i(m,v.segmentPrefix),i(m,l(D.toString(16))),a(m,dt);case 2:return i(m,se),i(m,v.segmentPrefix),i(m,l(D.toString(16))),a(m,qe);case 3:return i(m,at),i(m,v.segmentPrefix),i(m,l(D.toString(16))),a(m,mt);case 4:return i(m,Pt),i(m,v.segmentPrefix),i(m,l(D.toString(16))),a(m,$t);case 5:return i(m,Jt),i(m,v.segmentPrefix),i(m,l(D.toString(16))),a(m,nn);case 6:return i(m,Et),i(m,v.segmentPrefix),i(m,l(D.toString(16))),a(m,zt);case 7:return i(m,an),i(m,v.segmentPrefix),i(m,l(D.toString(16))),a(m,At);default:throw Error(n(397))}}function Y(m,v){switch(v.insertionMode){case 0:case 1:return a(m,g);case 2:return a(m,_e);case 3:return a(m,Mt);case 4:return a(m,Ft);case 5:return a(m,lt);case 6:return a(m,Ht);case 7:return a(m,Xt);default:throw Error(n(397))}}var Je=p('function $RS(a,b){a=document.getElementById(a);b=document.getElementById(b);for(a.parentNode.removeChild(a);a.firstChild;)b.parentNode.insertBefore(a.firstChild,b);b.parentNode.removeChild(b)};$RS("'),Be=p('$RS("'),te=p('","'),Ve=p('")<\/script>'),Ue=p('function $RC(a,b){a=document.getElementById(a);b=document.getElementById(b);b.parentNode.removeChild(b);if(a){a=a.previousSibling;var f=a.parentNode,c=a.nextSibling,e=0;do{if(c&&8===c.nodeType){var d=c.data;if("/$"===d)if(0===e)break;else e--;else"$"!==d&&"$?"!==d&&"$!"!==d||e++}d=c.nextSibling;f.removeChild(c);c=d}while(c);for(;b.firstChild;)f.insertBefore(b.firstChild,c);a.data="$";a._reactRetry&&a._reactRetry()}};$RC("'),yt=p('$RC("'),Bt=p('","'),Zt=p('")<\/script>'),qt=p('function $RX(b,c,d,e){var a=document.getElementById(b);a&&(b=a.previousSibling,b.data="$!",a=a.dataset,c&&(a.dgst=c),d&&(a.msg=d),e&&(a.stck=e),b._reactRetry&&b._reactRetry())};$RX("'),St=p('$RX("'),dn=p('"'),pt=p(")<\/script>"),Dt=p(","),Yt=/[<\u2028\u2029]/g;function Vt(m){return JSON.stringify(m).replace(Yt,function(v){switch(v){case"<":return"\\u003c";case"\u2028":return"\\u2028";case"\u2029":return"\\u2029";default:throw Error("escapeJSStringsForInstructionScripts encountered a match it does not know how to replace. this means the match regex and the replacement characters are no longer in sync. This is a bug in React")}})}var un=Object.assign,qn=Symbol.for("react.element"),wn=Symbol.for("react.portal"),sn=Symbol.for("react.fragment"),bn=Symbol.for("react.strict_mode"),zn=Symbol.for("react.profiler"),Tt=Symbol.for("react.provider"),Kt=Symbol.for("react.context"),_n=Symbol.for("react.forward_ref"),Vn=Symbol.for("react.suspense"),Kn=Symbol.for("react.suspense_list"),h=Symbol.for("react.memo"),x=Symbol.for("react.lazy"),S=Symbol.for("react.scope"),P=Symbol.for("react.debug_trace_mode"),de=Symbol.for("react.legacy_hidden"),oe=Symbol.for("react.default_value"),Ne=Symbol.iterator;function Ke(m){if(m==null)return null;if(typeof m=="function")return m.displayName||m.name||null;if(typeof m=="string")return m;switch(m){case sn:return"Fragment";case wn:return"Portal";case zn:return"Profiler";case bn:return"StrictMode";case Vn:return"Suspense";case Kn:return"SuspenseList"}if(typeof m=="object")switch(m.$$typeof){case Kt:return(m.displayName||"Context")+".Consumer";case Tt:return(m._context.displayName||"Context")+".Provider";case _n:var v=m.render;return m=m.displayName,m||(m=v.displayName||v.name||"",m=m!==""?"ForwardRef("+m+")":"ForwardRef"),m;case h:return v=m.displayName||null,v!==null?v:Ke(m.type)||"Memo";case x:v=m._payload,m=m._init;try{return Ke(m(v))}catch{}}return null}var ht={};function ut(m,v){if(m=m.contextTypes,!m)return ht;var C={},D;for(D in m)C[D]=v[D];return C}var gt=null;function Rt(m,v){if(m!==v){m.context._currentValue=m.parentValue,m=m.parent;var C=v.parent;if(m===null){if(C!==null)throw Error(n(401))}else{if(C===null)throw Error(n(401));Rt(m,C)}v.context._currentValue=v.value}}function rn(m){m.context._currentValue=m.parentValue,m=m.parent,m!==null&&rn(m)}function pn(m){var v=m.parent;v!==null&&pn(v),m.context._currentValue=m.value}function en(m,v){if(m.context._currentValue=m.parentValue,m=m.parent,m===null)throw Error(n(402));m.depth===v.depth?Rt(m,v):en(m,v)}function jn(m,v){var C=v.parent;if(C===null)throw Error(n(402));m.depth===C.depth?Rt(m,C):jn(m,C),v.context._currentValue=v.value}function xn(m){var v=gt;v!==m&&(v===null?pn(m):m===null?rn(v):v.depth===m.depth?Rt(v,m):v.depth>m.depth?en(v,m):jn(v,m),gt=m)}var Cn={isMounted:function(){return!1},enqueueSetState:function(m,v){m=m._reactInternals,m.queue!==null&&m.queue.push(v)},enqueueReplaceState:function(m,v){m=m._reactInternals,m.replace=!0,m.queue=[v]},enqueueForceUpdate:function(){}};function tn(m,v,C,D){var he=m.state!==void 0?m.state:null;m.updater=Cn,m.props=C,m.state=he;var ue={queue:[],replace:!1};m._reactInternals=ue;var Me=v.contextType;if(m.context=typeof Me=="object"&&Me!==null?Me._currentValue:D,Me=v.getDerivedStateFromProps,typeof Me=="function"&&(Me=Me(C,he),he=Me==null?he:un({},he,Me),m.state=he),typeof v.getDerivedStateFromProps!="function"&&typeof m.getSnapshotBeforeUpdate!="function"&&(typeof m.UNSAFE_componentWillMount=="function"||typeof m.componentWillMount=="function"))if(v=m.state,typeof m.componentWillMount=="function"&&m.componentWillMount(),typeof m.UNSAFE_componentWillMount=="function"&&m.UNSAFE_componentWillMount(),v!==m.state&&Cn.enqueueReplaceState(m,m.state,null),ue.queue!==null&&0<ue.queue.length)if(v=ue.queue,Me=ue.replace,ue.queue=null,ue.replace=!1,Me&&v.length===1)m.state=v[0];else{for(ue=Me?v[0]:m.state,he=!0,Me=Me?1:0;Me<v.length;Me++){var Ge=v[Me];Ge=typeof Ge=="function"?Ge.call(m,ue,C,D):Ge,Ge!=null&&(he?(he=!1,ue=un({},ue,Ge)):un(ue,Ge))}m.state=ue}else ue.queue=null}var Gn={id:1,overflow:""};function Rn(m,v,C){var D=m.id;m=m.overflow;var he=32-Jn(D)-1;D&=~(1<<he),C+=1;var ue=32-Jn(v)+he;if(30<ue){var Me=he-he%5;return ue=(D&(1<<Me)-1).toString(32),D>>=Me,he-=Me,{id:1<<32-Jn(v)+he|C<<he|D,overflow:ue+m}}return{id:1<<ue|C<<he|D,overflow:m}}var Jn=Math.clz32?Math.clz32:vn,ss=Math.log,An=Math.LN2;function vn(m){return m>>>=0,m===0?32:31-(ss(m)/An|0)|0}function kn(m,v){return m===v&&(m!==0||1/m===1/v)||m!==m&&v!==v}var hn=typeof Object.is=="function"?Object.is:kn,on=null,yn=null,Qn=null,Nt=null,ln=!1,Dn=!1,In=0,Sn=null,Yn=0;function $n(){if(on===null)throw Error(n(321));return on}function gs(){if(0<Yn)throw Error(n(312));return{memoizedState:null,queue:null,next:null}}function rs(){return Nt===null?Qn===null?(ln=!1,Qn=Nt=gs()):(ln=!0,Nt=Qn):Nt.next===null?(ln=!1,Nt=Nt.next=gs()):(ln=!0,Nt=Nt.next),Nt}function Hn(){yn=on=null,Dn=!1,Qn=null,Yn=0,Nt=Sn=null}function cs(m,v){return typeof v=="function"?v(m):v}function Xn(m,v,C){if(on=$n(),Nt=rs(),ln){var D=Nt.queue;if(v=D.dispatch,Sn!==null&&(C=Sn.get(D),C!==void 0)){Sn.delete(D),D=Nt.memoizedState;do D=m(D,C.action),C=C.next;while(C!==null);return Nt.memoizedState=D,[D,v]}return[Nt.memoizedState,v]}return m=m===cs?typeof v=="function"?v():v:C!==void 0?C(v):v,Nt.memoizedState=m,m=Nt.queue={last:null,dispatch:null},m=m.dispatch=bs.bind(null,on,m),[Nt.memoizedState,m]}function ds(m,v){if(on=$n(),Nt=rs(),v=v===void 0?null:v,Nt!==null){var C=Nt.memoizedState;if(C!==null&&v!==null){var D=C[1];e:if(D===null)D=!1;else{for(var he=0;he<D.length&&he<v.length;he++)if(!hn(v[he],D[he])){D=!1;break e}D=!0}if(D)return C[0]}}return m=m(),Nt.memoizedState=[m,v],m}function bs(m,v,C){if(25<=Yn)throw Error(n(301));if(m===on)if(Dn=!0,m={action:C,next:null},Sn===null&&(Sn=new Map),C=Sn.get(v),C===void 0)Sn.set(v,m);else{for(v=C;v.next!==null;)v=v.next;v.next=m}}function xs(){throw Error(n(394))}function Q(){}var Re={readContext:function(m){return m._currentValue},useContext:function(m){return $n(),m._currentValue},useMemo:ds,useReducer:Xn,useRef:function(m){on=$n(),Nt=rs();var v=Nt.memoizedState;return v===null?(m={current:m},Nt.memoizedState=m):v},useState:function(m){return Xn(cs,m)},useInsertionEffect:Q,useLayoutEffect:function(){},useCallback:function(m,v){return ds(function(){return m},v)},useImperativeHandle:Q,useEffect:Q,useDebugValue:Q,useDeferredValue:function(m){return $n(),m},useTransition:function(){return $n(),[!1,xs]},useId:function(){var m=yn.treeContext,v=m.overflow;m=m.id,m=(m&~(1<<32-Jn(m)-1)).toString(32)+v;var C=Ye;if(C===null)throw Error(n(404));return v=In++,m=":"+C.idPrefix+"R"+m,0<v&&(m+="H"+v.toString(32)),m+":"},useMutableSource:function(m,v){return $n(),v(m._source)},useSyncExternalStore:function(m,v,C){if(C===void 0)throw Error(n(407));return C()}},Ye=null,ft=t.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentDispatcher;function wt(m){return console.error(m),null}function Ct(){}function It(m,v,C,D,he,ue,Me,Ge,xt){var jt=[],bt=new Set;return v={destination:null,responseState:v,progressiveChunkSize:D===void 0?12800:D,status:0,fatalError:null,nextSegmentId:0,allPendingTasks:0,pendingRootTasks:0,completedRootSegment:null,abortableTasks:bt,pingedTasks:jt,clientRenderedBoundaries:[],completedBoundaries:[],partialBoundaries:[],onError:he===void 0?wt:he,onAllReady:ue===void 0?Ct:ue,onShellReady:Me===void 0?Ct:Me,onShellError:Ge===void 0?Ct:Ge,onFatalError:xt===void 0?Ct:xt},C=Ln(v,0,null,C,!1,!1),C.parentFlushed=!0,m=Ot(v,m,null,C,bt,ht,null,Gn),jt.push(m),v}function Ot(m,v,C,D,he,ue,Me,Ge){m.allPendingTasks++,C===null?m.pendingRootTasks++:C.pendingTasks++;var xt={node:v,ping:function(){var jt=m.pingedTasks;jt.push(xt),jt.length===1&&Ki(m)},blockedBoundary:C,blockedSegment:D,abortSet:he,legacyContext:ue,context:Me,treeContext:Ge};return he.add(xt),xt}function Ln(m,v,C,D,he,ue){return{status:0,id:-1,index:v,parentFlushed:!1,chunks:[],children:[],formatContext:D,boundary:C,lastPushedText:he,textEmbedded:ue}}function Nn(m,v){if(m=m.onError(v),m!=null&&typeof m!="string")throw Error('onError returned something with a type other than "string". onError should return a string and may return null or undefined but must not return anything else. It received something of type "'+typeof m+'" instead');return m}function I(m,v){var C=m.onShellError;C(v),C=m.onFatalError,C(v),m.destination!==null?(m.status=2,u(m.destination,v)):(m.status=1,m.fatalError=v)}function me(m,v,C,D,he){for(on={},yn=v,In=0,m=C(D,he);Dn;)Dn=!1,In=0,Yn+=1,Nt=null,m=C(D,he);return Hn(),m}function Xe(m,v,C,D){var he=C.render(),ue=D.childContextTypes;if(ue!=null){var Me=v.legacyContext;if(typeof C.getChildContext!="function")D=Me;else{C=C.getChildContext();for(var Ge in C)if(!(Ge in ue))throw Error(n(108,Ke(D)||"Unknown",Ge));D=un({},Me,C)}v.legacyContext=D,vt(m,v,he),v.legacyContext=Me}else vt(m,v,he)}function st(m,v){if(m&&m.defaultProps){v=un({},v),m=m.defaultProps;for(var C in m)v[C]===void 0&&(v[C]=m[C]);return v}return v}function rt(m,v,C,D,he){if(typeof C=="function")if(C.prototype&&C.prototype.isReactComponent){he=ut(C,v.legacyContext);var ue=C.contextType;ue=new C(D,typeof ue=="object"&&ue!==null?ue._currentValue:he),tn(ue,C,D,he),Xe(m,v,ue,C)}else{ue=ut(C,v.legacyContext),he=me(m,v,C,D,ue);var Me=In!==0;if(typeof he=="object"&&he!==null&&typeof he.render=="function"&&he.$$typeof===void 0)tn(he,C,D,ue),Xe(m,v,he,C);else if(Me){D=v.treeContext,v.treeContext=Rn(D,1,0);try{vt(m,v,he)}finally{v.treeContext=D}}else vt(m,v,he)}else if(typeof C=="string"){switch(he=v.blockedSegment,ue=ye(he.chunks,C,D,m.responseState,he.formatContext),he.lastPushedText=!1,Me=he.formatContext,he.formatContext=B(Me,C,D),Fn(m,v,ue),he.formatContext=Me,C){case"area":case"base":case"br":case"col":case"embed":case"hr":case"img":case"input":case"keygen":case"link":case"meta":case"param":case"source":case"track":case"wbr":break;default:he.chunks.push(ze,l(C),Ze)}he.lastPushedText=!1}else{switch(C){case de:case P:case bn:case zn:case sn:vt(m,v,D.children);return;case Kn:vt(m,v,D.children);return;case S:throw Error(n(343));case Vn:e:{C=v.blockedBoundary,he=v.blockedSegment,ue=D.fallback,D=D.children,Me=new Set;var Ge={id:null,rootSegmentID:-1,parentFlushed:!1,pendingTasks:0,forceClientRender:!1,completedSegments:[],byteSize:0,fallbackAbortableTasks:Me,errorDigest:null},xt=Ln(m,he.chunks.length,Ge,he.formatContext,!1,!1);he.children.push(xt),he.lastPushedText=!1;var jt=Ln(m,0,null,he.formatContext,!1,!1);jt.parentFlushed=!0,v.blockedBoundary=Ge,v.blockedSegment=jt;try{if(Fn(m,v,D),jt.lastPushedText&&jt.textEmbedded&&jt.chunks.push(we),jt.status=1,tr(Ge,jt),Ge.pendingTasks===0)break e}catch(bt){jt.status=4,Ge.forceClientRender=!0,Ge.errorDigest=Nn(m,bt)}finally{v.blockedBoundary=C,v.blockedSegment=he}v=Ot(m,ue,C,xt,Me,v.legacyContext,v.context,v.treeContext),m.pingedTasks.push(v)}return}if(typeof C=="object"&&C!==null)switch(C.$$typeof){case _n:if(D=me(m,v,C.render,D,he),In!==0){C=v.treeContext,v.treeContext=Rn(C,1,0);try{vt(m,v,D)}finally{v.treeContext=C}}else vt(m,v,D);return;case h:C=C.type,D=st(C,D),rt(m,v,C,D,he);return;case Tt:if(he=D.children,C=C._context,D=D.value,ue=C._currentValue,C._currentValue=D,Me=gt,gt=D={parent:Me,depth:Me===null?0:Me.depth+1,context:C,parentValue:ue,value:D},v.context=D,vt(m,v,he),m=gt,m===null)throw Error(n(403));D=m.parentValue,m.context._currentValue=D===oe?m.context._defaultValue:D,m=gt=m.parent,v.context=m;return;case Kt:D=D.children,D=D(C._currentValue),vt(m,v,D);return;case x:he=C._init,C=he(C._payload),D=st(C,D),rt(m,v,C,D,void 0);return}throw Error(n(130,C==null?C:typeof C,""))}}function vt(m,v,C){if(v.node=C,typeof C=="object"&&C!==null){switch(C.$$typeof){case qn:rt(m,v,C.type,C.props,C.ref);return;case wn:throw Error(n(257));case x:var D=C._init;C=D(C._payload),vt(m,v,C);return}if(W(C)){cn(m,v,C);return}if(C===null||typeof C!="object"?D=null:(D=Ne&&C[Ne]||C["@@iterator"],D=typeof D=="function"?D:null),D&&(D=D.call(C))){if(C=D.next(),!C.done){var he=[];do he.push(C.value),C=D.next();while(!C.done);cn(m,v,he)}return}throw m=Object.prototype.toString.call(C),Error(n(31,m==="[object Object]"?"object with keys {"+Object.keys(C).join(", ")+"}":m))}typeof C=="string"?(D=v.blockedSegment,D.lastPushedText=re(v.blockedSegment.chunks,C,m.responseState,D.lastPushedText)):typeof C=="number"&&(D=v.blockedSegment,D.lastPushedText=re(v.blockedSegment.chunks,""+C,m.responseState,D.lastPushedText))}function cn(m,v,C){for(var D=C.length,he=0;he<D;he++){var ue=v.treeContext;v.treeContext=Rn(ue,D,he);try{Fn(m,v,C[he])}finally{v.treeContext=ue}}}function Fn(m,v,C){var D=v.blockedSegment.formatContext,he=v.legacyContext,ue=v.context;try{return vt(m,v,C)}catch(xt){if(Hn(),typeof xt=="object"&&xt!==null&&typeof xt.then=="function"){C=xt;var Me=v.blockedSegment,Ge=Ln(m,Me.chunks.length,null,Me.formatContext,Me.lastPushedText,!0);Me.children.push(Ge),Me.lastPushedText=!1,m=Ot(m,v.node,v.blockedBoundary,Ge,v.abortSet,v.legacyContext,v.context,v.treeContext).ping,C.then(m,m),v.blockedSegment.formatContext=D,v.legacyContext=he,v.context=ue,xn(ue)}else throw v.blockedSegment.formatContext=D,v.legacyContext=he,v.context=ue,xn(ue),xt}}function js(m){var v=m.blockedBoundary;m=m.blockedSegment,m.status=3,Vi(this,v,m)}function zi(m,v,C){var D=m.blockedBoundary;m.blockedSegment.status=3,D===null?(v.allPendingTasks--,v.status!==2&&(v.status=2,v.destination!==null&&v.destination.close())):(D.pendingTasks--,D.forceClientRender||(D.forceClientRender=!0,m=C===void 0?Error(n(432)):C,D.errorDigest=v.onError(m),D.parentFlushed&&v.clientRenderedBoundaries.push(D)),D.fallbackAbortableTasks.forEach(function(he){return zi(he,v,C)}),D.fallbackAbortableTasks.clear(),v.allPendingTasks--,v.allPendingTasks===0&&(D=v.onAllReady,D()))}function tr(m,v){if(v.chunks.length===0&&v.children.length===1&&v.children[0].boundary===null){var C=v.children[0];C.id=v.id,C.parentFlushed=!0,C.status===1&&tr(m,C)}else m.completedSegments.push(v)}function Vi(m,v,C){if(v===null){if(C.parentFlushed){if(m.completedRootSegment!==null)throw Error(n(389));m.completedRootSegment=C}m.pendingRootTasks--,m.pendingRootTasks===0&&(m.onShellError=Ct,v=m.onShellReady,v())}else v.pendingTasks--,v.forceClientRender||(v.pendingTasks===0?(C.parentFlushed&&C.status===1&&tr(v,C),v.parentFlushed&&m.completedBoundaries.push(v),v.fallbackAbortableTasks.forEach(js,m),v.fallbackAbortableTasks.clear()):C.parentFlushed&&C.status===1&&(tr(v,C),v.completedSegments.length===1&&v.parentFlushed&&m.partialBoundaries.push(v)));m.allPendingTasks--,m.allPendingTasks===0&&(m=m.onAllReady,m())}function Ki(m){if(m.status!==2){var v=gt,C=ft.current;ft.current=Re;var D=Ye;Ye=m.responseState;try{var he=m.pingedTasks,ue;for(ue=0;ue<he.length;ue++){var Me=he[ue],Ge=m,xt=Me.blockedSegment;if(xt.status===0){xn(Me.context);try{vt(Ge,Me,Me.node),xt.lastPushedText&&xt.textEmbedded&&xt.chunks.push(we),Me.abortSet.delete(Me),xt.status=1,Vi(Ge,Me.blockedBoundary,xt)}catch(Un){if(Hn(),typeof Un=="object"&&Un!==null&&typeof Un.then=="function"){var jt=Me.ping;Un.then(jt,jt)}else{Me.abortSet.delete(Me),xt.status=4;var bt=Me.blockedBoundary,Ut=Un,Mn=Nn(Ge,Ut);if(bt===null?I(Ge,Ut):(bt.pendingTasks--,bt.forceClientRender||(bt.forceClientRender=!0,bt.errorDigest=Mn,bt.parentFlushed&&Ge.clientRenderedBoundaries.push(bt))),Ge.allPendingTasks--,Ge.allPendingTasks===0){var Bn=Ge.onAllReady;Bn()}}}finally{}}}he.splice(0,ue),m.destination!==null&&Ar(m,m.destination)}catch(Un){Nn(m,Un),I(m,Un)}finally{Ye=D,ft.current=C,C===Re&&xn(v)}}}function nr(m,v,C){switch(C.parentFlushed=!0,C.status){case 0:var D=C.id=m.nextSegmentId++;return C.lastPushedText=!1,C.textEmbedded=!1,m=m.responseState,i(v,Qe),i(v,m.placeholderPrefix),m=l(D.toString(16)),i(v,m),a(v,ct);case 1:C.status=2;var he=!0;D=C.chunks;var ue=0;C=C.children;for(var Me=0;Me<C.length;Me++){for(he=C[Me];ue<he.index;ue++)i(v,D[ue]);he=sr(m,v,he)}for(;ue<D.length-1;ue++)i(v,D[ue]);return ue<D.length&&(he=a(v,D[ue])),he;default:throw Error(n(390))}}function sr(m,v,C){var D=C.boundary;if(D===null)return nr(m,v,C);if(D.parentFlushed=!0,D.forceClientRender)D=D.errorDigest,a(v,We),i(v,H),D&&(i(v,ke),i(v,l(U(D))),i(v,X)),a(v,De),nr(m,v,C);else if(0<D.pendingTasks){D.rootSegmentID=m.nextSegmentId++,0<D.completedSegments.length&&m.partialBoundaries.push(D);var he=m.responseState,ue=he.nextSuspenseID++;he=p(he.boundaryPrefix+ue.toString(16)),D=D.id=he,He(v,m.responseState,D),nr(m,v,C)}else if(D.byteSize>m.progressiveChunkSize)D.rootSegmentID=m.nextSegmentId++,m.completedBoundaries.push(D),He(v,m.responseState,D.id),nr(m,v,C);else{if(a(v,tt),C=D.completedSegments,C.length!==1)throw Error(n(391));sr(m,v,C[0])}return a(v,w)}function Gi(m,v,C){return K(v,m.responseState,C.formatContext,C.id),sr(m,v,C),Y(v,C.formatContext)}function Ji(m,v,C){for(var D=C.completedSegments,he=0;he<D.length;he++)Qi(m,v,C,D[he]);if(D.length=0,m=m.responseState,D=C.id,C=C.rootSegmentID,i(v,m.startInlineScript),m.sentCompleteBoundaryFunction?i(v,yt):(m.sentCompleteBoundaryFunction=!0,i(v,Ue)),D===null)throw Error(n(395));return C=l(C.toString(16)),i(v,D),i(v,Bt),i(v,m.segmentPrefix),i(v,C),a(v,Zt)}function Qi(m,v,C,D){if(D.status===2)return!0;var he=D.id;if(he===-1){if((D.id=C.rootSegmentID)===-1)throw Error(n(392));return Gi(m,v,D)}return Gi(m,v,D),m=m.responseState,i(v,m.startInlineScript),m.sentCompleteSegmentFunction?i(v,Be):(m.sentCompleteSegmentFunction=!0,i(v,Je)),i(v,m.segmentPrefix),he=l(he.toString(16)),i(v,he),i(v,te),i(v,m.placeholderPrefix),i(v,he),a(v,Ve)}function Ar(m,v){s=new Uint8Array(512),r=0;try{var C=m.completedRootSegment;if(C!==null&&m.pendingRootTasks===0){sr(m,v,C),m.completedRootSegment=null;var D=m.responseState.bootstrapChunks;for(C=0;C<D.length-1;C++)i(v,D[C]);C<D.length&&a(v,D[C])}var he=m.clientRenderedBoundaries,ue;for(ue=0;ue<he.length;ue++){var Me=he[ue];D=v;var Ge=m.responseState,xt=Me.id,jt=Me.errorDigest,bt=Me.errorMessage,Ut=Me.errorComponentStack;if(i(D,Ge.startInlineScript),Ge.sentClientRenderFunction?i(D,St):(Ge.sentClientRenderFunction=!0,i(D,qt)),xt===null)throw Error(n(395));i(D,xt),i(D,dn),(jt||bt||Ut)&&(i(D,Dt),i(D,l(Vt(jt||"")))),(bt||Ut)&&(i(D,Dt),i(D,l(Vt(bt||"")))),Ut&&(i(D,Dt),i(D,l(Vt(Ut)))),a(D,pt)}he.splice(0,ue);var Mn=m.completedBoundaries;for(ue=0;ue<Mn.length;ue++)Ji(m,v,Mn[ue]);Mn.splice(0,ue),o(v),s=new Uint8Array(512),r=0;var Bn=m.partialBoundaries;for(ue=0;ue<Bn.length;ue++){var Un=Bn[ue];e:{he=m,Me=v;var rr=Un.completedSegments;for(Ge=0;Ge<rr.length;Ge++)if(!Qi(he,Me,Un,rr[Ge])){Ge++,rr.splice(0,Ge);var Xi=!1;break e}rr.splice(0,Ge),Xi=!0}if(!Xi){m.destination=null,ue++,Bn.splice(0,ue);return}}Bn.splice(0,ue);var Dr=m.completedBoundaries;for(ue=0;ue<Dr.length;ue++)Ji(m,v,Dr[ue]);Dr.splice(0,ue)}finally{o(v),m.allPendingTasks===0&&m.pingedTasks.length===0&&m.clientRenderedBoundaries.length===0&&m.completedBoundaries.length===0&&v.close()}}function Yi(m,v){try{var C=m.abortableTasks;C.forEach(function(D){return zi(D,m,v)}),C.clear(),m.destination!==null&&Ar(m,m.destination)}catch(D){Nn(m,D),I(m,D)}}return or.renderToReadableStream=function(m,v){return new Promise(function(C,D){var he,ue,Me=new Promise(function(bt,Ut){ue=bt,he=Ut}),Ge=It(m,je(v?v.identifierPrefix:void 0,v?v.nonce:void 0,v?v.bootstrapScriptContent:void 0,v?v.bootstrapScripts:void 0,v?v.bootstrapModules:void 0),Pe(v?v.namespaceURI:void 0),v?v.progressiveChunkSize:void 0,v?v.onError:void 0,ue,function(){var bt=new ReadableStream({type:"bytes",pull:function(Ut){if(Ge.status===1)Ge.status=2,u(Ut,Ge.fatalError);else if(Ge.status!==2&&Ge.destination===null){Ge.destination=Ut;try{Ar(Ge,Ut)}catch(Mn){Nn(Ge,Mn),I(Ge,Mn)}}},cancel:function(){Yi(Ge)}},{highWaterMark:0});bt.allReady=Me,C(bt)},function(bt){Me.catch(function(){}),D(bt)},he);if(v&&v.signal){var xt=v.signal,jt=function(){Yi(Ge,xt.reason),xt.removeEventListener("abort",jt)};xt.addEventListener("abort",jt)}Ki(Ge)})},or.version="18.3.1",or}var _a;function Qu(){if(_a)return us;_a=1;var t,n;return t=Gu(),n=Ju(),us.version=t.version,us.renderToString=t.renderToString,us.renderToStaticMarkup=t.renderToStaticMarkup,us.renderToNodeStream=t.renderToNodeStream,us.renderToStaticNodeStream=t.renderToStaticNodeStream,us.renderToReadableStream=n.renderToReadableStream,us}var Yu=Qu();function Xu(t){for(var n=1;n<arguments.length;n++){var s=arguments[n];for(var r in s)Object.prototype.hasOwnProperty.call(s,r)&&(t[r]=s[r])}return t}function pi(t,n){return Array(n+1).join(t)}function fl(t){return t.replace(/^\n*/,"")}function gl(t){for(var n=t.length;n>0&&t[n-1]===`
79
+ `;)n--;return t.substring(0,n)}function xl(t){return gl(fl(t))}var Zu=["ADDRESS","ARTICLE","ASIDE","AUDIO","BLOCKQUOTE","BODY","CANVAS","CENTER","DD","DIR","DIV","DL","DT","FIELDSET","FIGCAPTION","FIGURE","FOOTER","FORM","FRAMESET","H1","H2","H3","H4","H5","H6","HEADER","HGROUP","HR","HTML","ISINDEX","LI","MAIN","MENU","NAV","NOFRAMES","NOSCRIPT","OL","OUTPUT","P","PRE","SECTION","TABLE","TBODY","TD","TFOOT","TH","THEAD","TR","UL"];function Pi(t){return Ai(t,Zu)}var vl=["AREA","BASE","BR","COL","COMMAND","EMBED","HR","IMG","INPUT","KEYGEN","LINK","META","PARAM","SOURCE","TRACK","WBR"];function kl(t){return Ai(t,vl)}function ep(t){return wl(t,vl)}var yl=["A","TABLE","THEAD","TBODY","TFOOT","TH","TD","IFRAME","SCRIPT","AUDIO","VIDEO"];function tp(t){return Ai(t,yl)}function np(t){return wl(t,yl)}function Ai(t,n){return n.indexOf(t.nodeName)>=0}function wl(t,n){return t.getElementsByTagName&&n.some(function(s){return t.getElementsByTagName(s).length})}var sp=[[/\\/g,"\\\\"],[/\*/g,"\\*"],[/^-/g,"\\-"],[/^\+ /g,"\\+ "],[/^(=+)/g,"\\$1"],[/^(#{1,6}) /g,"\\$1 "],[/`/g,"\\`"],[/^~~~/g,"\\~~~"],[/\[/g,"\\["],[/\]/g,"\\]"],[/^>/g,"\\>"],[/_/g,"\\_"],[/^(\d+)\. /g,"$1\\. "]];function bl(t){return sp.reduce(function(n,s){return n.replace(s[0],s[1])},t)}var gn={};gn.paragraph={filter:"p",replacement:function(t){return`
80
+
81
+ `+t+`
82
+
83
+ `}};gn.lineBreak={filter:"br",replacement:function(t,n,s){return s.br+`
84
+ `}};gn.heading={filter:["h1","h2","h3","h4","h5","h6"],replacement:function(t,n,s){var r=Number(n.nodeName.charAt(1));if(s.headingStyle==="setext"&&r<3){var i=pi(r===1?"=":"-",t.length);return`
85
+
86
+ `+t+`
87
+ `+i+`
88
+
89
+ `}else return`
90
+
91
+ `+pi("#",r)+" "+t+`
92
+
93
+ `}};gn.blockquote={filter:"blockquote",replacement:function(t){return t=xl(t).replace(/^/gm,"> "),`
94
+
95
+ `+t+`
96
+
97
+ `}};gn.list={filter:["ul","ol"],replacement:function(t,n){var s=n.parentNode;return s.nodeName==="LI"&&s.lastElementChild===n?`
98
+ `+t:`
99
+
100
+ `+t+`
101
+
102
+ `}};gn.listItem={filter:"li",replacement:function(t,n,s){var r=s.bulletListMarker+" ",i=n.parentNode;if(i.nodeName==="OL"){var a=i.getAttribute("start"),o=Array.prototype.indexOf.call(i.children,n);r=(a?Number(a)+o:o+1)+". "}var c=/\n$/.test(t);return t=xl(t)+(c?`
103
+ `:""),t=t.replace(/\n/gm,`
104
+ `+" ".repeat(r.length)),r+t+(n.nextSibling?`
105
+ `:"")}};gn.indentedCodeBlock={filter:function(t,n){return n.codeBlockStyle==="indented"&&t.nodeName==="PRE"&&t.firstChild&&t.firstChild.nodeName==="CODE"},replacement:function(t,n,s){return`
106
+
107
+ `+n.firstChild.textContent.replace(/\n/g,`
108
+ `)+`
109
+
110
+ `}};gn.fencedCodeBlock={filter:function(t,n){return n.codeBlockStyle==="fenced"&&t.nodeName==="PRE"&&t.firstChild&&t.firstChild.nodeName==="CODE"},replacement:function(t,n,s){for(var r=n.firstChild.getAttribute("class")||"",i=(r.match(/language-(\S+)/)||[null,""])[1],a=n.firstChild.textContent,o=s.fence.charAt(0),c=3,l=new RegExp("^"+o+"{3,}","gm"),p;p=l.exec(a);)p[0].length>=c&&(c=p[0].length+1);var u=pi(o,c);return`
111
+
112
+ `+u+i+`
113
+ `+a.replace(/\n$/,"")+`
114
+ `+u+`
115
+
116
+ `}};gn.horizontalRule={filter:"hr",replacement:function(t,n,s){return`
117
+
118
+ `+s.hr+`
119
+
120
+ `}};gn.inlineLink={filter:function(t,n){return n.linkStyle==="inlined"&&t.nodeName==="A"&&t.getAttribute("href")},replacement:function(t,n){var s=Di(n.getAttribute("href")),r=$i(yr(n.getAttribute("title"))),i=r?' "'+r+'"':"";return"["+t+"]("+s+i+")"}};gn.referenceLink={filter:function(t,n){return n.linkStyle==="referenced"&&t.nodeName==="A"&&t.getAttribute("href")},replacement:function(t,n,s){var r=Di(n.getAttribute("href")),i=yr(n.getAttribute("title"));i&&(i=' "'+$i(i)+'"');var a,o;switch(s.linkReferenceStyle){case"collapsed":a="["+t+"][]",o="["+t+"]: "+r+i;break;case"shortcut":a="["+t+"]",o="["+t+"]: "+r+i;break;default:var c=this.references.length+1;a="["+t+"]["+c+"]",o="["+c+"]: "+r+i}return this.references.push(o),a},references:[],append:function(t){var n="";return this.references.length&&(n=`
121
+
122
+ `+this.references.join(`
123
+ `)+`
124
+
125
+ `,this.references=[]),n}};gn.emphasis={filter:["em","i"],replacement:function(t,n,s){return t.trim()?s.emDelimiter+t+s.emDelimiter:""}};gn.strong={filter:["strong","b"],replacement:function(t,n,s){return t.trim()?s.strongDelimiter+t+s.strongDelimiter:""}};gn.code={filter:function(t){var n=t.previousSibling||t.nextSibling,s=t.parentNode.nodeName==="PRE"&&!n;return t.nodeName==="CODE"&&!s},replacement:function(t){if(!t)return"";t=t.replace(/\r?\n|\r/g," ");for(var n=/^`|^ .*?[^ ].* $|`$/.test(t)?" ":"",s="`",r=t.match(/`+/gm)||[];r.indexOf(s)!==-1;)s=s+"`";return s+n+t+n+s}};gn.image={filter:"img",replacement:function(t,n){var s=bl(yr(n.getAttribute("alt"))),r=Di(n.getAttribute("src")||""),i=yr(n.getAttribute("title")),a=i?' "'+$i(i)+'"':"";return r?"!["+s+"]("+r+a+")":""}};function yr(t){return t?t.replace(/(\n+\s*)+/g,`
126
+ `):""}function Di(t){var n=t.replace(/([<>()])/g,"\\$1");return n.indexOf(" ")>=0?"<"+n+">":n}function $i(t){return t.replace(/"/g,'\\"')}function jl(t){this.options=t,this._keep=[],this._remove=[],this.blankRule={replacement:t.blankReplacement},this.keepReplacement=t.keepReplacement,this.defaultRule={replacement:t.defaultReplacement},this.array=[];for(var n in t.rules)this.array.push(t.rules[n])}jl.prototype={add:function(t,n){this.array.unshift(n)},keep:function(t){this._keep.unshift({filter:t,replacement:this.keepReplacement})},remove:function(t){this._remove.unshift({filter:t,replacement:function(){return""}})},forNode:function(t){if(t.isBlank)return this.blankRule;var n;return(n=qr(this.array,t,this.options))||(n=qr(this._keep,t,this.options))||(n=qr(this._remove,t,this.options))?n:this.defaultRule},forEach:function(t){for(var n=0;n<this.array.length;n++)t(this.array[n],n)}};function qr(t,n,s){for(var r=0;r<t.length;r++){var i=t[r];if(rp(i,n,s))return i}}function rp(t,n,s){var r=t.filter;if(typeof r=="string"){if(r===n.nodeName.toLowerCase())return!0}else if(Array.isArray(r)){if(r.indexOf(n.nodeName.toLowerCase())>-1)return!0}else if(typeof r=="function"){if(r.call(t,n,s))return!0}else throw new TypeError("`filter` needs to be a string, array, or function")}function ip(t){var n=t.element,s=t.isBlock,r=t.isVoid,i=t.isPre||function(f){return f.nodeName==="PRE"};if(!(!n.firstChild||i(n))){for(var a=null,o=!1,c=null,l=Ha(c,n,i);l!==n;){if(l.nodeType===3||l.nodeType===4){var p=l.data.replace(/[ \r\n\t]+/g," ");if((!a||/ $/.test(a.data))&&!o&&p[0]===" "&&(p=p.substr(1)),!p){l=zr(l);continue}l.data=p,a=l}else if(l.nodeType===1)s(l)||l.nodeName==="BR"?(a&&(a.data=a.data.replace(/ $/,"")),a=null,o=!1):r(l)||i(l)?(a=null,o=!0):a&&(o=!1);else{l=zr(l);continue}var u=Ha(c,l,i);c=l,l=u}a&&(a.data=a.data.replace(/ $/,""),a.data||zr(a))}}function zr(t){var n=t.nextSibling||t.parentNode;return t.parentNode.removeChild(t),n}function Ha(t,n,s){return t&&t.parentNode===n||s(n)?n.nextSibling||n.parentNode:n.firstChild||n.nextSibling||n.parentNode}var Fi=typeof window<"u"?window:{};function ap(){var t=Fi.DOMParser,n=!1;try{new t().parseFromString("","text/html")&&(n=!0)}catch{}return n}function op(){var t=function(){};return lp()?t.prototype.parseFromString=function(n){var s=new window.ActiveXObject("htmlfile");return s.designMode="on",s.open(),s.write(n),s.close(),s}:t.prototype.parseFromString=function(n){var s=document.implementation.createHTMLDocument("");return s.open(),s.write(n),s.close(),s},t}function lp(){var t=!1;try{document.implementation.createHTMLDocument("").open()}catch{Fi.ActiveXObject&&(t=!0)}return t}var cp=ap()?Fi.DOMParser:op();function dp(t,n){var s;if(typeof t=="string"){var r=up().parseFromString('<x-turndown id="turndown-root">'+t+"</x-turndown>","text/html");s=r.getElementById("turndown-root")}else s=t.cloneNode(!0);return ip({element:s,isBlock:Pi,isVoid:kl,isPre:n.preformattedCode?pp:null}),s}var Vr;function up(){return Vr=Vr||new cp,Vr}function pp(t){return t.nodeName==="PRE"||t.nodeName==="CODE"}function hp(t,n){return t.isBlock=Pi(t),t.isCode=t.nodeName==="CODE"||t.parentNode.isCode,t.isBlank=mp(t),t.flankingWhitespace=fp(t,n),t}function mp(t){return!kl(t)&&!tp(t)&&/^\s*$/i.test(t.textContent)&&!ep(t)&&!np(t)}function fp(t,n){if(t.isBlock||n.preformattedCode&&t.isCode)return{leading:"",trailing:""};var s=gp(t.textContent);return s.leadingAscii&&Ba("left",t,n)&&(s.leading=s.leadingNonAscii),s.trailingAscii&&Ba("right",t,n)&&(s.trailing=s.trailingNonAscii),{leading:s.leading,trailing:s.trailing}}function gp(t){var n=t.match(/^(([ \t\r\n]*)(\s*))(?:(?=\S)[\s\S]*\S)?((\s*?)([ \t\r\n]*))$/);return{leading:n[1],leadingAscii:n[2],leadingNonAscii:n[3],trailing:n[4],trailingNonAscii:n[5],trailingAscii:n[6]}}function Ba(t,n,s){var r,i,a;return t==="left"?(r=n.previousSibling,i=/ $/):(r=n.nextSibling,i=/^ /),r&&(r.nodeType===3?a=i.test(r.nodeValue):s.preformattedCode&&r.nodeName==="CODE"?a=!1:r.nodeType===1&&!Pi(r)&&(a=i.test(r.textContent))),a}var xp=Array.prototype.reduce;function wr(t){if(!(this instanceof wr))return new wr(t);var n={rules:gn,headingStyle:"setext",hr:"* * *",bulletListMarker:"*",codeBlockStyle:"indented",fence:"```",emDelimiter:"_",strongDelimiter:"**",linkStyle:"inlined",linkReferenceStyle:"full",br:" ",preformattedCode:!1,blankReplacement:function(s,r){return r.isBlock?`
127
+
128
+ `:""},keepReplacement:function(s,r){return r.isBlock?`
129
+
130
+ `+r.outerHTML+`
131
+
132
+ `:r.outerHTML},defaultReplacement:function(s,r){return r.isBlock?`
133
+
134
+ `+s+`
135
+
136
+ `:s}};this.options=Xu({},n,t),this.rules=new jl(this.options)}wr.prototype={turndown:function(t){if(!yp(t))throw new TypeError(t+" is not a string, or an element/document/fragment node.");if(t==="")return"";var n=Cl.call(this,new dp(t,this.options));return vp.call(this,n)},use:function(t){if(Array.isArray(t))for(var n=0;n<t.length;n++)this.use(t[n]);else if(typeof t=="function")t(this);else throw new TypeError("plugin must be a Function or an Array of Functions");return this},addRule:function(t,n){return this.rules.add(t,n),this},keep:function(t){return this.rules.keep(t),this},remove:function(t){return this.rules.remove(t),this},escape:function(t){return bl(t)}};function Cl(t){var n=this;return xp.call(t.childNodes,function(s,r){r=new hp(r,n.options);var i="";return r.nodeType===3?i=r.isCode?r.nodeValue:n.escape(r.nodeValue):r.nodeType===1&&(i=kp.call(n,r)),Sl(s,i)},"")}function vp(t){var n=this;return this.rules.forEach(function(s){typeof s.append=="function"&&(t=Sl(t,s.append(n.options)))}),t.replace(/^[\t\r\n]+/,"").replace(/[\t\r\n\s]+$/,"")}function kp(t){var n=this.rules.forNode(t),s=Cl.call(this,t),r=t.flankingWhitespace;return(r.leading||r.trailing)&&(s=s.trim()),r.leading+n.replacement(s,t,this.options)+r.trailing}function Sl(t,n){var s=gl(t),r=fl(n),i=Math.max(t.length-s.length,n.length-r.length),a=`
137
+
138
+ `.substring(0,i);return s+a+r}function yp(t){return t!=null&&(typeof t=="string"||t.nodeType&&(t.nodeType===1||t.nodeType===9||t.nodeType===11))}var Ua=/highlight-(?:text|source)-([a-z0-9]+)/;function wp(t){t.addRule("highlightedCodeBlock",{filter:function(n){var s=n.firstChild;return n.nodeName==="DIV"&&Ua.test(n.className)&&s&&s.nodeName==="PRE"},replacement:function(n,s,r){var i=s.className||"",a=(i.match(Ua)||[null,""])[1];return`
139
+
140
+ `+r.fence+a+`
141
+ `+s.firstChild.textContent+`
142
+ `+r.fence+`
143
+
144
+ `}})}function bp(t){t.addRule("strikethrough",{filter:["del","s","strike"],replacement:function(n){return"~"+n+"~"}})}var jp=Array.prototype.indexOf,Cp=Array.prototype.every,Ds={};Ds.tableCell={filter:["th","td"],replacement:function(t,n){return Nl(t,n)}};Ds.tableRow={filter:"tr",replacement:function(t,n){var s="",r={left:":--",right:"--:",center:":-:"};if(Oi(n))for(var i=0;i<n.childNodes.length;i++){var a="---",o=(n.childNodes[i].getAttribute("align")||"").toLowerCase();o&&(a=r[o]||a),s+=Nl(a,n.childNodes[i])}return`
145
+ `+t+(s?`
146
+ `+s:"")}};Ds.table={filter:function(t){return t.nodeName==="TABLE"&&Oi(t.rows[0])},replacement:function(t){return t=t.replace(`
147
+
148
+ `,`
149
+ `),`
150
+
151
+ `+t+`
152
+
153
+ `}};Ds.tableSection={filter:["thead","tbody","tfoot"],replacement:function(t){return t}};function Oi(t){var n=t.parentNode;return n.nodeName==="THEAD"||n.firstChild===t&&(n.nodeName==="TABLE"||Sp(n))&&Cp.call(t.childNodes,function(s){return s.nodeName==="TH"})}function Sp(t){var n=t.previousSibling;return t.nodeName==="TBODY"&&(!n||n.nodeName==="THEAD"&&/^\s*$/i.test(n.textContent))}function Nl(t,n){var s=jp.call(n.parentNode.childNodes,n),r=" ";return s===0&&(r="| "),r+t+" |"}function Np(t){t.keep(function(s){return s.nodeName==="TABLE"&&!Oi(s.rows[0])});for(var n in Ds)t.addRule(n,Ds[n])}function Ep(t){t.addRule("taskListItems",{filter:function(n){return n.type==="checkbox"&&n.parentNode.nodeName==="LI"},replacement:function(n,s){return(s.checked?"[x]":"[ ]")+" "}})}function Tp(t){t.use([wp,bp,Np,Ep])}const Rp=Tr().use(Rr).use(Si);function hi(t){var o;const n=t.querySelector("code"),s=zs(n??t),r=((o=n==null?void 0:n.className.match(/language-([^\s]+)/))==null?void 0:o[1])??"",i=r==="plaintext"?"":r,a="`".repeat(Math.max(3,...Array.from(s.matchAll(/`+/g),c=>c[0].length+1)));return`
154
+
155
+ ${a}${i}
156
+ ${s.replace(/\n$/,"")}
157
+ ${a}
158
+
159
+ `}const Wn=new wr({headingStyle:"atx",codeBlockStyle:"fenced",bulletListMarker:"-",blankReplacement:(t,n)=>{if(n.nodeName==="BLOCKQUOTE"&&n.hasAttribute("data-rich-highlight"))return`
160
+
161
+ > [!NOTE]
162
+ >
163
+
164
+ `;if(n.nodeName==="PRE")return hi(n);const s=Array.from(n.querySelectorAll("pre"));return s.length?s.map(hi).join(`
165
+
166
+ `):"isBlock"in n&&n.isBlock?`
167
+
168
+ `:""}});Wn.use(Tp);Wn.addRule("textHighlight",{filter:t=>t.nodeName==="SPAN"&&!!di(t.style.backgroundColor),replacement:(t,n)=>`<mark style="background-color: ${di(n.style.backgroundColor).hex}">${t}</mark>`});Wn.addRule("highlightBlock",{filter:t=>t.nodeName==="BLOCKQUOTE"&&t.hasAttribute("data-rich-highlight"),replacement:t=>`
169
+
170
+ > [!NOTE]
171
+ `+t.trim().split(`
172
+ `).map(n=>"> "+n).join(`
173
+ `)+`
174
+
175
+ `});Wn.addRule("taskCheckbox",{filter:t=>t.nodeName==="INPUT"&&t.getAttribute("type")==="checkbox",replacement:(t,n)=>n.checked?"[x] ":"[ ] "});Wn.addRule("preservedSource",{filter:t=>t.hasAttribute("data-rich-source"),replacement:(t,n)=>`
176
+
177
+ `+n.getAttribute("data-rich-source")+`
178
+
179
+ `});Wn.addRule("preservedInlineSource",{filter:t=>t.hasAttribute("data-rich-inline"),replacement:(t,n)=>n.getAttribute("data-rich-inline")??""});Wn.addRule("wikiLink",{filter:t=>t.nodeName==="A"&&(t.getAttribute("href")??"").startsWith("#wiki="),replacement:(t,n)=>{let s;try{s=decodeURIComponent(n.getAttribute("href").slice(6))}catch{return t}return`[[${s}${t===s?"":"|"+t}]]`}});Wn.addRule("codeFence",{filter:"pre",replacement:(t,n)=>hi(n)});Wn.addRule("tableBreak",{filter:"br",replacement:(t,n)=>n.closest("td, th")?"<br>":`
180
+ `});Wn.addRule("tableCell",{filter:["th","td"],replacement:(t,n)=>{var r;return(Array.from(((r=n.parentNode)==null?void 0:r.childNodes)??[]).indexOf(n)===0?"| ":" ")+t.trim().replace(/\|/g,"\\|").replace(/\n/g,"<br>")+" |"}});function El(t,n=!1){return t.type==="html"?!n:["definition","footnoteDefinition","footnoteReference"].includes(t.type)?!0:"children"in t&&t.children.some(s=>El(s,!0))}function Ip(){return t=>{const n=s=>{if("children"in s)for(let r=0;r<s.children.length;r++){const i=s.children[r];i.type==="html"&&s.type!=="root"?/^<br\s*\/?>(?:\r?\n)?$/i.test(i.value)?s.children[r]={type:"break"}:s.children[r]={type:"text",value:i.value,data:{hName:"span",hProperties:{"data-rich-inline":i.value,contentEditable:"false"},hChildren:[{type:"text",value:i.value}]}}:n(i)}};n(t)}}function Lp(t,n=!1){var u,f,k;const s=[],r=Rp.parse(t).children,i=r.filter(j=>j.type==="definition").map(j=>{var R,E;return t.slice((R=j.position)==null?void 0:R.start.offset,(E=j.position)==null?void 0:E.end.offset)}).join(`
181
+ `),a=(u=t.match(/^---\r?\n[\s\S]*?\r?\n(?:---|\.\.\.)(?:\r?\n|$)/))==null?void 0:u[0],o=n?Xo(t):null,c=n?Qo(t).ranges:[];let l=!0,p=0;a&&(s.push({raw:a.trimEnd(),prefix:"",html:"",protected:!0,hidden:n}),p=a.trimEnd().length);for(const j of r){const R=(f=j.position)==null?void 0:f.start.offset,E=(k=j.position)==null?void 0:k.end.offset;if(R===void 0||E===void 0||R<p)continue;const A=t.slice(R,E),N=El(j),T=c.some(y=>y.start===R&&y.end===E)||!!o&&l&&j.type==="heading"&&j.depth===1&&o.readingBody!==o.body;j.type==="heading"&&j.depth===1&&(l=!1),s.push({raw:A,prefix:t.slice(p,R),protected:N,hidden:T,html:N?"":Yu.renderToStaticMarkup(e.jsx(Ir,{remarkPlugins:[Si,il,Ip,al],rehypePlugins:n?[]:[mo],children:(n?uu(A):A)+`
182
+
183
+ `+i}))}),p=E}return{source:t,blocks:s,suffix:t.slice(p)}}function Mp(t,n,s){t.replaceChildren();let r=1;n.blocks.forEach((i,a)=>{r+=i.prefix.split(`
184
+ `).length-1;const o=r,c=t.ownerDocument.createElement("div");if(c.dataset.richBlock=String(a),c.dataset.sourceStart=String(o),c.dataset.sourceEnd=String(o+i.raw.split(`
185
+ `).length-1),c.className="rich-block",c.hidden=!!i.hidden,i.protected){c.contentEditable="false",c.dataset.richSource=i.raw,c.classList.add("rich-source-block");const l=t.ownerDocument.createElement("small");l.textContent=s;const p=t.ownerDocument.createElement("pre");p.textContent=i.raw,c.append(l,p)}else c.innerHTML=i.html;c.querySelectorAll('input[type="checkbox"]').forEach(l=>{l.disabled=!1}),t.append(c),r+=i.raw.split(`
186
+ `).length-1,i.html=c.innerHTML}),n.blocks.length||(t.innerHTML="<p><br></p>")}function Wa(t,n){const s=n.ownerDocument.createElement("div");return s.append(t.cloneNode(!0)),s.querySelectorAll("th, td").forEach(r=>{const i=r.style.textAlign;["left","center","right"].includes(i)&&r.setAttribute("align",i)}),Wn.turndown(s)}function Pp(t,n){t=t.cloneNode(!0),t.querySelectorAll("[data-wiki-placeholder]").forEach(i=>i.removeAttribute("data-wiki-placeholder")),t.querySelectorAll("[data-rich-ui]").forEach(i=>i.remove()),t.querySelectorAll("img[data-rich-image-src]").forEach(i=>{i.setAttribute("src",i.dataset.richImageSrc),i.removeAttribute("data-rich-image-src")});for(let i=n.blocks.length-1;i>=0;i--){const a=n.blocks[i];if(!a.hidden||t.querySelector(`[data-rich-block="${i}"]`))continue;const o=t.ownerDocument.createElement("div");o.dataset.richBlock=String(i),o.innerHTML=a.html;const c=[...t.children].find(l=>Number(l.dataset.richBlock)>i);c?t.insertBefore(o,c):t.prepend(o)}const s=new Set,r=[];for(const i of Array.from(t.childNodes)){const a=i instanceof HTMLElement?i.dataset.richBlock:void 0,o=a===void 0?-1:Number(a),c=n.blocks[o];if(c&&!s.has(o)){s.add(o);const p=i instanceof HTMLElement&&i.tagName==="DIV"&&i.innerHTML===c.html||c.protected?c.raw:Wa(i,t);r.push((r.length?c.prefix||`
187
+
188
+ `:c.prefix)+p)}else{const l=Wa(i,t);l&&r.push((r.length?`
189
+
190
+ `:"")+l)}}return r.join("")+(r.length?n.suffix:"")}const Ap=["javascript","typescript","python","bash","json","yaml","html","css","sql","go","rust","java","c","cpp","csharp","ruby","php","swift","kotlin","markdown","xml","toml","diff","mermaid"],Tl=d.memo(function({value:n,readOnly:s,onChange:r,file:i,wiki:a}){const o=et(),[c,l]=d.useState(null),p=d.useRef(null),[u,f]=d.useState([]),k=d.useRef(!1),[j,R]=d.useState(!1),[E,A]=d.useState(""),N=d.useRef(null),T=d.useRef(s);T.current=s,d.useEffect(()=>()=>{var w;(w=N.current)==null||w.abort()},[]);const y=d.useRef(null),M=d.useRef(null);d.useEffect(()=>()=>{var w;(w=M.current)==null||w.dispose(),M.current=null},[]);const b=(w,H=!1)=>{M.current??(M.current=Ku(!!a)),H?M.current.observe(w):M.current.update(w)},F=()=>{var De;const w=window.getSelection(),H=w==null?void 0:w.anchorNode,X=H instanceof Element?H:H==null?void 0:H.parentElement,ke=X==null?void 0:X.closest("pre > code");return ke&&((De=y.current)!=null&&De.contains(ke))&&(w!=null&&w.focusNode)&&ke.contains(w.focusNode)?ke:null},[U,ce]=d.useState(null),[ie,W]=d.useState(null),ve=d.useRef(null),Se=d.useRef(null),$=d.useRef(null),$e=d.useRef(null),L=d.useRef(null),[q,fe]=d.useState(!1),je=()=>{var X;const w=window.getSelection();if(!(w!=null&&w.rangeCount)||w.isCollapsed||!((X=y.current)!=null&&X.contains(w.anchorNode))||!y.current.contains(w.focusNode))return null;const H=w.getRangeAt(0);return[...y.current.querySelectorAll("pre, code, [contenteditable=false]")].some(ke=>H.intersectsNode(ke))?null:H};d.useEffect(()=>{const w=()=>{var ot,dt,g,se,qe;const H=window.getSelection();H!=null&&H.rangeCount&&((ot=y.current)!=null&&ot.contains(H.anchorNode))&&y.current.contains(H.focusNode)&&(p.current=H.getRangeAt(0).cloneRange()),(dt=y.current)==null||dt.querySelectorAll("[data-wiki-placeholder]").forEach(_e=>_e.removeAttribute("data-wiki-placeholder"));const X=H==null?void 0:H.anchorNode,ke=(g=X instanceof Element?X:X==null?void 0:X.parentElement)==null?void 0:g.closest("p, div");a&&ke&&ke!==y.current&&((se=y.current)!=null&&se.contains(ke))&&!((qe=ke.textContent)!=null&&qe.trim())&&!ke.querySelector("img, code")&&ke.setAttribute("data-wiki-placeholder",o("wikiEmptyParagraph"));const De=je();if(fe(!!De),!De){ce(null);return}const He=De.getBoundingClientRect();if(He.bottom<0||He.top>window.innerHeight){ce(null);return}ce({x:Math.max(8,Math.min(He.left+He.width/2-160,window.innerWidth-328)),y:He.top>=50?He.top-46:Math.min(He.bottom+8,window.innerHeight-46)})};return document.addEventListener("selectionchange",w),window.addEventListener("scroll",w,!0),window.addEventListener("resize",w),()=>{document.removeEventListener("selectionchange",w),window.removeEventListener("scroll",w,!0),window.removeEventListener("resize",w)}},[]),d.useLayoutEffect(()=>{const w=L.current,H=je();if(!w||!H)return;const X=H.getBoundingClientRect();w.style.left=`${Math.max(8,Math.min(X.left+X.width/2-w.offsetWidth/2,window.innerWidth-w.offsetWidth-8))}px`,w.style.top=`${Math.max(8,X.top>=w.offsetHeight+8?X.top-w.offsetHeight-8:Math.min(X.bottom+8,window.innerHeight-w.offsetHeight-8))}px`},[U]);const ne=d.useRef(null),[Pe,B]=d.useState(null),[we,re]=d.useState(0),[Ie,_]=d.useState(null),le=d.useRef(null),O=()=>{le.current=null,B(null)},ge=d.useRef(null);d.useLayoutEffect(()=>{if(!y.current||n===ge.current)return;O(),_(null);const w=Lp(n,!!a);Mp(y.current,w,o("richSourceBlock")),a&&(y.current.querySelectorAll("pre:has(> code)").forEach(H=>H.classList.add("codeblock")),y.current.querySelectorAll("h2").forEach((H,X)=>{H.id=`wiki-heading-${X}`}),y.current.querySelectorAll("p").forEach(H=>{[...a.added].some(X=>{var ke;return X.trim()&&((ke=H.textContent)==null?void 0:ke.includes(X))})&&H.classList.add("wiki-added")}),y.current.querySelectorAll("code").forEach(H=>{if(H.closest("pre")||!a.resolveCode(H.textContent??""))return;const X=document.createElement("a");X.href=`#wiki=${encodeURIComponent(H.textContent??"")}`,X.textContent=H.textContent,H.replaceChildren(X)}),y.current.querySelectorAll("[data-rich-block]").forEach(H=>{w.blocks[Number(H.dataset.richBlock)].html=H.innerHTML})),ne.current=w,ge.current=n},[n,o]),d.useLayoutEffect(()=>{!a||!y.current||y.current.querySelectorAll("p").forEach(w=>w.classList.toggle("wiki-added",[...a.added].some(H=>{var X;return H.trim()&&((X=w.textContent)==null?void 0:X.includes(H))})))},[a==null?void 0:a.added,n]),d.useLayoutEffect(()=>{var w;s&&O(),(w=y.current)==null||w.querySelectorAll('input[type="checkbox"]').forEach(H=>{H.disabled=s})},[s,n]),d.useLayoutEffect(()=>{var w;(w=y.current)==null||w.querySelectorAll("pre > code").forEach(H=>{var ot;const X=H.parentElement;a&&X.classList.add("codeblock");let ke=X.querySelector("select[data-code-language]");if(!ke){const dt=document.createElement("span");if(dt.dataset.richUi="",dt.contentEditable="false",dt.className="fp-code-language",ke=document.createElement("select"),ke.dataset.codeLanguage="",dt.append(ke),a){const g=document.createElement("button");g.type="button",g.textContent=o("copy"),g.onmousedown=se=>se.preventDefault(),g.onclick=()=>{navigator.clipboard.writeText(zs(H))},dt.append(g)}X.prepend(dt)}const De=((ot=H.className.match(/language-([^\s]+)/))==null?void 0:ot[1])??"",He=De==="plaintext"?"":De;ke.replaceChildren();for(const dt of["",...new Set([...Ap,...He?[He]:[]])])ke.add(new Option(dt||o(a?"wikiCodeAutomatic":"richPlainText"),dt));ke.value=He,ke.disabled=s,ke.setAttribute("aria-label",o("richCodeLanguage")),b(H,!0)})},[n,s,o]),d.useLayoutEffect(()=>{var w;(w=y.current)==null||w.querySelectorAll("img").forEach(H=>{const X=H.dataset.richImageSrc??H.getAttribute("src")??"";!X||/^(?:[a-z]+:|\/\/|#)/i.test(X)||(H.dataset.richImageSrc=X,H.src=hl(X,i))})},[n,i.cwd,i.path]),d.useEffect(()=>{var H,X;if(!a||s||k.current||!y.current)return;k.current=!0,y.current.focus({preventScroll:!0});const w=document.createRange();w.selectNodeContents(y.current),w.collapse(!1),(H=window.getSelection())==null||H.removeAllRanges(),(X=window.getSelection())==null||X.addRange(w),p.current=w.cloneRange()},[s]),d.useLayoutEffect(()=>{if(!a||!y.current)return;const w=[];y.current.querySelectorAll("pre > code.language-mermaid").forEach(H=>{const X=H.parentElement;let ke=X.querySelector(".wiki-mermaid-preview");ke||(ke=document.createElement("div"),ke.dataset.richUi="",ke.contentEditable="false",ke.className="wiki-mermaid-preview",X.prepend(ke)),w.push({host:ke,code:zs(H)})}),y.current.querySelectorAll(".wiki-mermaid-preview").forEach(H=>{w.some(X=>X.host===H)||H.remove()}),f(w)},[n]);const pe=()=>{var ke,De;const w=(ke=window.getSelection())==null?void 0:ke.anchorNode,H=w instanceof Element?w:w==null?void 0:w.parentElement,X=(H==null?void 0:H.closest("th, td"))??null;return X&&((De=y.current)!=null&&De.contains(X))?X:null},Ae=w=>{var ke;(ke=y.current)==null||ke.focus();const H=document.createRange();H.selectNodeContents(w),H.collapse(!0);const X=window.getSelection();X==null||X.removeAllRanges(),X==null||X.addRange(H),_(w)},ae=(w,H=Ie)=>{var ot,dt;if(s||!H||!((ot=y.current)!=null&&ot.contains(H)))return;const X=H.closest("table"),ke=H.parentElement,De=H.cellIndex;let He=H;if(w==="row"){const g=document.createElement("tr");for(const se of Array.from(X.rows[0].cells)){const qe=g.insertCell();qe.style.textAlign=se.style.textAlign,qe.append(document.createElement("br"))}((dt=ke.parentElement)==null?void 0:dt.tagName)==="THEAD"?(X.tBodies[0]??X.createTBody()).prepend(g):ke.after(g),He=g.cells[0]}else if(w==="column")for(const g of Array.from(X.rows)){const se=document.createElement(g.cells[0].tagName==="TH"?"th":"td");se.style.textAlign=g.cells[De].style.textAlign,se.tagName==="TH"?se.textContent=o("richColumn"):se.append(document.createElement("br")),g.cells[De].after(se),g===ke&&(He=se)}else if(w==="removeRow"){if(ke.rowIndex===0||X.rows.length<=2)return;He=X.rows[ke.rowIndex-1].cells[De],ke.remove()}else{if(ke.cells.length<=1)return;He=ke.cells[De>0?De-1:1];for(const g of Array.from(X.rows))g.deleteCell(De)}Ae(He),Fe()},Te=async w=>{var De;if(T.current||N.current||!y.current)return;const H=window.getSelection();if(!(H!=null&&H.rangeCount)||!y.current.contains(H.anchorNode))return;const X=H.getRangeAt(0).cloneRange(),ke=new AbortController;N.current=ke,R(!0),A("");try{if(w.size>5*1024*1024)throw new Error(o("richImageTooLarge"));const He=await new Promise((se,qe)=>{const _e=new FileReader;_e.onload=()=>se(String(_e.result).split(",")[1]),_e.onerror=()=>qe(new Error(o("richImageFailed"))),_e.readAsDataURL(w)});if(ke.signal.aborted)return;const ot=await fetch(Tn("/api/markdown-image"),{method:"POST",headers:{"Content-Type":"application/json"},signal:ke.signal,body:JSON.stringify({clientId:fn(),cwd:i.cwd,path:i.path,data:He})});if(!ot.ok)throw new Error(o("richImageFailed"));const dt=await ot.json();if(typeof dt.path!="string")throw new Error(o("richImageFailed"));if(ke.signal.aborted)return;if(T.current||!((De=y.current)!=null&&De.contains(X.startContainer)))throw new Error(o("richImageFailed"));y.current.focus(),H.removeAllRanges(),H.addRange(X);const g=document.createElement("img");g.setAttribute("src",dt.path),g.setAttribute("alt",w.name||"screenshot"),document.execCommand("insertHTML",!1,g.outerHTML),Fe()}catch(He){ke.signal.aborted||A(He.message)}finally{ke.signal.aborted||R(!1),N.current===ke&&(N.current=null)}},Z=w=>{var ot;const H=w.closest("pre"),X=H==null?void 0:H.querySelector("code");if(s||!H||!X||!((ot=y.current)!=null&&ot.contains(H)))return;const ke=w.value;X.className=`hljs language-${ke||"plaintext"}`,X.innerHTML=Zs(zs(X),ke==="toml"?"ini":ke),X.textContent||X.append(document.createElement("br")),y.current.focus();const De=document.createRange();De.selectNodeContents(X),De.collapse(!1);const He=window.getSelection();He==null||He.removeAllRanges(),He==null||He.addRange(De),Fe()},Fe=()=>{if(s||!y.current||!ne.current)return;const w=Pp(y.current,ne.current);ge.current=w,r(w)},z=(w,H)=>{if(s||!y.current)return;const X=window.getSelection();(!(X!=null&&X.anchorNode)||!y.current.contains(X.anchorNode))&&y.current.focus(),document.execCommand(w,!1,H),Fe()},G=[...(a?[1,2,3]:[1,2,3,4,5,6]).map(w=>({label:"richHeading",keywords:`heading header title h${w} bt${w} biaoti${w} 标题${w}`,alias:`bt${w}`,action:"formatBlock",argument:`h${w}`})),{label:"richParagraph",alias:"zw",keywords:"paragraph text zw zhengwen 正文",action:"formatBlock",argument:"p"},{label:"richCodeBlock",alias:"dmk",keywords:"code fence dmk daimakuai 代码 代码块",action:"insertHTML",argument:"<pre><code data-slash-insert><br></code></pre><p><br></p>"},{label:"richHighlightBlock",alias:"glk",keywords:"highlight note callout glk gaoliangkuai ts tishi 高亮 提示",action:"insertHTML",argument:'<blockquote class="rich-highlight" data-rich-highlight="note"><p data-slash-insert><br></p></blockquote><p><br></p>'},{label:"richTable",alias:"bg",keywords:"table bg biaoge 表格",action:"insertHTML",argument:`<table><thead><tr><th data-slash-insert>${o("richColumn")} 1</th><th>${o("richColumn")} 2</th></tr></thead><tbody><tr><td>…</td><td>…</td></tr></tbody></table><p><br></p>`},{label:"richList",alias:"lb",keywords:"bullet list lb liebiao wxlb wuxuliebiao 列表 无序列表",action:"insertUnorderedList"},{label:"richOrderedList",alias:"bh",keywords:"number ordered bh bianhao yxlb youxuliebiao 编号 有序列表",action:"insertOrderedList"},{label:"richTaskList",alias:"rw",keywords:"task todo checkbox rw rwlb renwu renwuliebiao 任务",action:"insertHTML",argument:'<ul><li><input type="checkbox"><span data-slash-insert> </span></li></ul><p><br></p>'},{label:"richQuote",alias:"yy",keywords:"quote yy yinyong 引用",action:"formatBlock",argument:"blockquote"},{label:"richDivider",alias:"fgx",keywords:"divider horizontal rule fgx fengexian 分隔线",action:"insertHTML",argument:"<hr><p><br></p>"},{label:"richImage",alias:"tp",keywords:"image photo upload tp tupian 图片",action:"image"},{label:"richWikiLink",alias:"sl",keywords:"wiki link document sl shuanglian 链接 双链 文档",action:"wikiLink"},{label:"wikiMentionDate",alias:"date",keywords:"date mention riqi 日期",action:"insertText",get argument(){return new Date().toLocaleDateString("sv-SE")}}],J=["zw","bt2","bt3","lb","bg","tp","rw","yy","dmk","sl","date"],Ee=a?G.filter(w=>J.includes(w.alias)).sort((w,H)=>J.indexOf(w.alias)-J.indexOf(H.alias)):G.filter(w=>w.alias!=="date"),V={wikiMentionDate:e.jsx(Do,{}),richImage:e.jsx(Io,{}),richWikiLink:e.jsx(hr,{}),richHighlightBlock:e.jsx(ms,{}),richHeading:e.jsx(_s,{}),richParagraph:e.jsx(_s,{}),richCodeBlock:e.jsx(Po,{}),richTable:e.jsx(Du,{}),richList:e.jsx(dr,{}),richOrderedList:e.jsx(dr,{}),richTaskList:e.jsx(md,{}),richQuote:e.jsx($u,{}),richDivider:e.jsx(ti,{})},Le=w=>w.label==="richHeading"?`${o(w.label)} ${"argument"in w?w.argument.slice(1):""}`:o(w.label),xe=w=>w.action==="insertHTML",be={date:"@",zw:"",bt1:"#",bt2:"##",bt3:"###",lb:"-",bh:"1.",rw:"[]",yy:">",dmk:"```",glk:":::",bg:"3 × 3",fgx:"---",tp:"![]",sl:"[["},nt={date:"wikiInsertDate",zw:"wikiInsertParagraph",bt1:"wikiInsertH1",bt2:"wikiInsertH2",bt3:"wikiInsertH3",lb:"wikiInsertList",bh:"wikiInsertOrdered",rw:"wikiInsertTask",yy:"wikiInsertQuote",dmk:"wikiInsertCode",glk:"wikiInsertCallout",bg:"wikiInsertTable",fgx:"wikiInsertDivider",tp:"wikiInsertImage",sl:"wikiInsertLink"},Ce=Ee.filter(w=>a||!["image","wikiLink"].includes(w.action)).filter(w=>`${Le(w)} ${w.keywords}`.toLowerCase().includes((Pe==null?void 0:Pe.query.toLowerCase())??"")).sort((w,H)=>a?J.indexOf(w.alias)-J.indexOf(H.alias):Number(xe(w))-Number(xe(H))),ye=()=>{var H;const w=window.getSelection();w!=null&&w.rangeCount&&((H=y.current)!=null&&H.contains(w.anchorNode))&&(p.current=w.getRangeAt(0).cloneRange())},ze=()=>{if(!y.current||s)return!1;y.current.focus({preventScroll:!0});const w=p.current&&y.current.contains(p.current.startContainer)?p.current:document.createRange();(!p.current||!y.current.contains(w.startContainer))&&(w.selectNodeContents(y.current),w.collapse(!1));const H=window.getSelection();return H==null||H.removeAllRanges(),H==null||H.addRange(w),!0},Ze=(w,H,X,ke)=>{var qe,_e,at,mt,Mt,Pt,$t,Ft,Jt,nn;if(!ze())return;const De=(qe=window.getSelection())==null?void 0:qe.anchorNode,He=(_e=De instanceof Element?De:De==null?void 0:De.parentElement)==null?void 0:_e.closest("p,h1,h2,h3,h4,h5,h6"),ot=He==null?void 0:He.parentElement,dt=!((at=He==null?void 0:He.textContent)!=null&&at.trim());let g;if(w==="bg"&&!H||w==="dmk"&&X===void 0){const lt=ke??((mt=p.current)==null?void 0:mt.getBoundingClientRect());l({kind:w==="bg"?"table":"code",x:(c==null?void 0:c.x)??(lt==null?void 0:lt.left)??16,y:(c==null?void 0:c.y)??((lt==null?void 0:lt.bottom)??80)+6});return}if(l(null),w==="bg"&&H)z("insertHTML",`<table><thead><tr>${Array.from({length:H.columns},(lt,Et)=>`<th ${Et===0?"data-slash-insert":""}>${o("richColumn")} ${Et+1}</th>`).join("")}</tr></thead><tbody>${Array.from({length:H.rows-1},()=>`<tr>${"<td><br></td>".repeat(H.columns)}</tr>`).join("")}</tbody></table><p><br></p>`);else if(w==="dmk")z("insertHTML",`<pre><code data-slash-insert class="language-${X||"plaintext"}">${X==="mermaid"?`flowchart LR
191
+ A --> B`:"<br>"}</code></pre><p><br></p>`);else{const lt=Ee.find(Et=>Et.alias===w);if(!lt)return;if(lt.action==="image"){Se.current=((Mt=window.getSelection())==null?void 0:Mt.getRangeAt(0).cloneRange())??null,(Pt=$.current)==null||Pt.click();return}if(lt.action==="wikiLink"){z("insertText","[[");const Et=($t=window.getSelection())==null?void 0:$t.getRangeAt(0).cloneRange();Et&&Et.startOffset>=2&&Et.setStart(Et.startContainer,Et.startOffset-2),ve.current=Et??null,W("[[");return}lt.action==="formatBlock"&&(g=lt.argument),z(lt.action,"argument"in lt?lt.argument:void 0)}const se=((Ft=y.current)==null?void 0:Ft.querySelector("[data-slash-insert]"))??(dt&&g?ot==null?void 0:ot.querySelector(g):null);if(se){se.removeAttribute("data-slash-insert");const lt=document.createRange();lt.selectNodeContents(se),lt.collapse(!0),(Jt=window.getSelection())==null||Jt.removeAllRanges(),(nn=window.getSelection())==null||nn.addRange(lt),Fe()}ye()},Qe=(w=!0)=>{var qe,_e,at,mt;if(s)return O();const H=window.getSelection();if(!(H!=null&&H.isCollapsed)||!H.anchorNode||!((qe=y.current)!=null&&qe.contains(H.anchorNode)))return O();const X=H.anchorNode;if(X.nodeType!==Node.TEXT_NODE||(_e=X.parentElement)!=null&&_e.closest("pre, code, a, li, [contenteditable=false]"))return O();const ke=((at=X.textContent)==null?void 0:at.slice(0,H.anchorOffset))??"",De=(a?/\/([\p{L}\p{N}]{0,32})$/u:/\/([^\s/]{0,32})$/).exec(ke);if(!De)return O();const He=H.getRangeAt(0).cloneRange();He.setStart(X,H.anchorOffset-De[1].length-1);const ot=(mt=X.parentElement)==null?void 0:mt.closest("p, h1, h2, h3, h4, h5, h6, li, td, th, div");if(!ot||!y.current.contains(ot))return O();const dt=document.createRange();dt.selectNodeContents(ot),dt.setEnd(He.startContainer,He.startOffset);const g=dt.cloneContents();if((a?g.textContent&&!/\s$/.test(g.textContent):g.textContent)||g.querySelector("br, img, input, hr, video, audio"))return O();le.current=He;const se=He.getBoundingClientRect();B({query:De[1],x:Math.max(8,Math.min(se.left,window.innerWidth-(a?308:328))),y:se.bottom+6}),w&&re(0)};d.useEffect(()=>{if(!Pe)return;const w=H=>{var ke;if(H.target instanceof Element&&H.target.closest(".fp-slash-menu"))return;const X=(ke=le.current)==null?void 0:ke.getBoundingClientRect();a&&X&&X.bottom>=0&&X.top<=window.innerHeight?Qe(!1):O()};return window.addEventListener("scroll",w,!0),window.addEventListener("resize",O),()=>{window.removeEventListener("scroll",w,!0),window.removeEventListener("resize",O)}},[!!Pe]),d.useLayoutEffect(()=>{if(!Pe||!$e.current||!le.current)return;const w=le.current.getBoundingClientRect(),H=$e.current.offsetHeight;$e.current.style.top=`${Math.max(8,w.bottom+6+H<=window.innerHeight-8?w.bottom+6:w.top-H-6)}px`},[Pe]),d.useLayoutEffect(()=>{const w=document.getElementById(`fp-slash-option-${we}`),H=a?w==null?void 0:w.parentElement:w==null?void 0:w.closest(".fp-slash-menu");w&&H&&(w.offsetTop<H.scrollTop?H.scrollTop=w.offsetTop:w.offsetTop+w.offsetHeight>H.scrollTop+H.clientHeight&&(H.scrollTop=w.offsetTop+w.offsetHeight-H.clientHeight))},[we,Pe==null?void 0:Pe.query]);const ct=w=>{var dt,g,se,qe;const H=le.current,X=Ce[w];if(s||!X||!H||!((dt=y.current)!=null&&dt.contains(H.startContainer)))return O();const ke=(se=(g=H.startContainer.parentElement)==null?void 0:g.closest("p, h1, h2, h3, h4, h5, h6, td, th"))==null?void 0:se.parentElement;y.current.focus();const De=window.getSelection();De==null||De.removeAllRanges(),De==null||De.addRange(H);const He=H.getBoundingClientRect();if(O(),document.execCommand("delete"),a){ye(),Ze(X.alias,void 0,void 0,He);return}if(X.action==="image"){Se.current=(De==null?void 0:De.getRangeAt(0).cloneRange())??null,(qe=$.current)==null||qe.click(),Fe();return}if(X.action==="wikiLink"){ve.current=(De==null?void 0:De.getRangeAt(0).cloneRange())??null,W("[["),Fe();return}a&&X.alias==="bg"?z("insertHTML",`<table><thead><tr>${[1,2,3].map(_e=>`<th ${_e===1?"data-slash-insert":""}>${o("richColumn")} ${_e}</th>`).join("")}</tr></thead><tbody>${[1,2].map(()=>"<tr><td>…</td><td>…</td><td>…</td></tr>").join("")}</tbody></table><p><br></p>`):z(X.action,"argument"in X?X.argument:void 0);const ot=y.current.querySelector("[data-slash-insert]")??(X.action==="formatBlock"?ke==null?void 0:ke.querySelector(X.argument):null);if(ot){ot.removeAttribute("data-slash-insert");const _e=document.createRange();_e.selectNodeContents(ot),_e.collapse(!0),De==null||De.removeAllRanges(),De==null||De.addRange(_e),Fe()}},tt=w=>{const H=je();if(!H||!y.current)return;const X=document.createTreeWalker(y.current,NodeFilter.SHOW_TEXT),ke=[];let De;for(;De=X.nextNode();){if(!De.textContent||!H.intersectsNode(De)||H.endContainer===De&&H.endOffset===0||H.startContainer===De&&H.startOffset===De.textContent.length)continue;let He=De.parentElement,ot="";for(;He&&He!==y.current;){if(He.style.backgroundColor&&He.style.backgroundColor!=="transparent"){ot=He.style.backgroundColor;break}He=He.parentElement}ke.push(ot)}z("hiliteColor",ke.length&&ke.every(He=>He===w.rgb||He===w.hex)?"transparent":w.hex)},Oe=(w,H=!1)=>{var He;const X=ve.current;if(s||!X||!((He=y.current)!=null&&He.contains(X.startContainer)))return;if(!H&&!/^(https?:\/\/|mailto:|#|\.?\.?\/)/i.test(w)){A(o("wikiInvalidLink"));return}const ke=document.createElement("a");ke.setAttribute("href",H?`#wiki=${encodeURIComponent(w)}`:w),ke.textContent=X.toString()&&X.toString()!=="[["?X.toString():w,y.current.focus();const De=window.getSelection();De==null||De.removeAllRanges(),De==null||De.addRange(X),z("insertHTML",ke.outerHTML),W(null)},ee=()=>{var g,se,qe;if(!a||s)return!1;const w=window.getSelection(),H=w==null?void 0:w.anchorNode;if(!(w!=null&&w.isCollapsed)||!H||!((g=y.current)!=null&&g.contains(H))||(se=H.parentElement)!=null&&se.closest("pre, code, a, [contenteditable=false]"))return!1;const X=(qe=H.parentElement)==null?void 0:qe.closest("p, div");if(!X||X===y.current)return!1;const ke=w.getRangeAt(0).cloneRange();ke.setStart(X,0);const De=ke.toString(),He=/^(#{1,6})$/.exec(De),ot=G.find(_e=>_e.alias==={"-":"lb","*":"lb","1.":"bh","[]":"rw","[ ]":"rw",">":"yy","```":"dmk","---":"fgx",":::":"glk"}[De]);if(!He&&!ot)return!1;if(w.removeAllRanges(),w.addRange(ke),document.execCommand("delete"),He){const _e=X.parentElement,at=`h${He[1].length}`;z("formatBlock",at);const mt=_e==null?void 0:_e.querySelector(at);mt&&!mt.textContent&&(ke.selectNodeContents(mt),ke.collapse(!0),w.removeAllRanges(),w.addRange(ke))}else ot&&z(ot.action,"argument"in ot?ot.argument:void 0);const dt=y.current.querySelector("[data-slash-insert]");return dt&&(dt.removeAttribute("data-slash-insert"),ke.selectNodeContents(dt),ke.collapse(!0),w.removeAllRanges(),w.addRange(ke)),O(),Fe(),!0},We=[{label:o("richUndo"),icon:e.jsx(nd,{}),action:"undo"},{label:o("richRedo"),icon:e.jsx(td,{}),action:"redo"},{label:o("richParagraph"),icon:e.jsx(_s,{}),action:"formatBlock",argument:"p",separator:!0},{label:`${o("richHeading")} 1`,icon:e.jsx("span",{children:"H₁"}),action:"formatBlock",argument:"h1"},{label:`${o("richHeading")} 2`,icon:e.jsx("span",{children:"H₂"}),action:"formatBlock",argument:"h2"},{label:o("richBold"),icon:e.jsx(ha,{}),action:"bold",separator:!0},{label:o("richItalic"),icon:e.jsx(la,{}),action:"italic"},{label:o("richList"),icon:e.jsx(dr,{}),action:"insertUnorderedList",separator:!0},{label:o("richOrderedList"),icon:e.jsx("span",{children:"1."}),action:"insertOrderedList"}];return e.jsxs("div",{className:"fp-rich-editor",onScrollCapture:w=>{w.target.closest(".fp-slash-menu")||Pe&&Qe(!1)},children:[(a==null?void 0:a.toolbarHost)&&mn.createPortal(e.jsx(Bu,{readOnly:s,focused:!!a.focused,onWidth:a.onWidth??(()=>{}),items:Ee.map(w=>({id:w.alias,label:Le(w),hint:be[w.alias]??"",help:o(nt[w.alias]),icon:V[w.label]})),popup:c,onPrepare:ye,onSelect:w=>Ze(w),onPopup:l}),a.toolbarHost),u.map(({host:w,code:H},X)=>mn.createPortal(e.jsx(ll,{code:H}),w,String(X))),c&&!s&&e.jsx(Hu,{popup:c,onClose:()=>{l(null),ze()},children:c.kind==="table"?e.jsx(Uu,{onInsert:(w,H)=>Ze("bg",{columns:w,rows:H})}):e.jsx(Wu,{onInsert:w=>Ze("dmk",void 0,w)})}),!a&&e.jsxs("div",{className:"fp-rich-toolbar",role:"toolbar","aria-label":o("richFormatToolbar"),children:[We.map(w=>e.jsxs(d.Fragment,{children:[w.separator&&e.jsx("span",{className:"fp-rich-toolbar-separator","aria-hidden":"true"}),e.jsx("button",{type:"button",title:w.label,"aria-label":w.label,disabled:s,onMouseDown:H=>H.preventDefault(),onClick:()=>z(w.action,w.argument),children:w.icon})]},w.label)),e.jsx("span",{className:"fp-rich-toolbar-separator","aria-hidden":"true"}),e.jsx("span",{className:"fp-highlight-label",children:o("richTextHighlight")}),ci.map(w=>e.jsx("button",{type:"button",className:`fp-highlight-swatch fp-highlight-${w.name}`,title:o(`richHighlight_${w.name}`),"aria-label":o(`richHighlight_${w.name}`),disabled:s||!q,onMouseDown:H=>H.preventDefault(),onClick:()=>{je()&&z("hiliteColor",w.hex)},children:e.jsx("span",{})},w.name)),e.jsx("button",{type:"button",title:o("richHighlightClear"),"aria-label":o("richHighlightClear"),disabled:s||!q,onMouseDown:w=>w.preventDefault(),onClick:()=>{je()&&z("hiliteColor","transparent")},children:e.jsx(ti,{})})]}),(Ie==null?void 0:Ie.isConnected)&&!s&&e.jsxs("div",{className:"fp-table-tools",role:"toolbar","aria-label":o("richTableTools"),children:[e.jsx("button",{type:"button",onMouseDown:w=>w.preventDefault(),onClick:()=>ae("row"),children:o("richAddRow")}),e.jsx("button",{type:"button",onMouseDown:w=>w.preventDefault(),onClick:()=>ae("column"),children:o("richAddColumn")}),e.jsx("button",{type:"button",disabled:Ie.parentElement.rowIndex===0||Ie.closest("table").rows.length<=2,onMouseDown:w=>w.preventDefault(),onClick:()=>ae("removeRow"),children:o("richRemoveRow")}),e.jsx("button",{type:"button",disabled:Ie.parentElement.cells.length<=1,onMouseDown:w=>w.preventDefault(),onClick:()=>ae("removeColumn"),children:o("richRemoveColumn")})]}),j&&e.jsx("div",{className:"fp-notice",role:"status",children:o("richImageUploading")}),E&&e.jsx("div",{className:"fp-notice",role:"alert",children:E}),a&&U&&ie===null&&mn.createPortal(e.jsxs("div",{ref:L,className:"wiki-format-popover",role:"toolbar","aria-label":o("richFormatToolbar"),style:{left:U.x,top:U.y},onMouseDown:w=>w.preventDefault(),children:[[{label:o("richBold"),action:"bold",icon:e.jsx(ha,{})},{label:o("richItalic"),action:"italic",icon:e.jsx(la,{})},{label:`${o("richHeading")} 2`,action:"formatBlock",argument:"h2",icon:e.jsx(_s,{})},{label:`${o("richHeading")} 3`,action:"formatBlock",argument:"h3",icon:e.jsx(_s,{})}].map(w=>e.jsx("button",{"aria-label":w.label,title:w.label,disabled:s,onClick:()=>z(w.action,w.argument),children:w.icon},w.label)),e.jsx("button",{"aria-label":o("wikiAddLink"),title:o("wikiAddLink"),disabled:s,onClick:()=>{var w;ve.current=((w=je())==null?void 0:w.cloneRange())??null,W("")},children:e.jsx(hr,{})}),e.jsx("i",{}),ci.slice(0,2).map(w=>e.jsx("button",{className:`fp-highlight-swatch fp-highlight-${w.name}`,"aria-label":o(`richHighlight_${w.name}`),title:o(`richHighlight_${w.name}`),disabled:s,onClick:()=>tt(w),children:e.jsx("span",{})},w.name)),e.jsx("i",{}),e.jsx("button",{className:"wiki-ask-selection",onClick:()=>{var w;a.ask(((w=window.getSelection())==null?void 0:w.toString())??""),ce(null)},children:o("wikiAskPi")})]}),document.body),e.jsx("input",{ref:$,type:"file",accept:"image/*",hidden:!0,onChange:w=>{var ke,De;const H=(ke=w.target.files)==null?void 0:ke[0],X=Se.current;if(H&&X&&((De=y.current)!=null&&De.contains(X.startContainer))){y.current.focus();const He=window.getSelection();He==null||He.removeAllRanges(),He==null||He.addRange(X),Te(H)}w.target.value=""}}),ie!==null&&e.jsxs(Mi,{title:o("wikiAddLink"),onClose:()=>W(null),children:[e.jsxs("form",{className:"wiki-link-form",onSubmit:w=>{w.preventDefault(),Oe(ie)},children:[e.jsx("input",{"aria-label":o("wikiLinkAddress"),placeholder:o("wikiLinkAddress"),value:ie,onChange:w=>W(w.target.value)}),e.jsx("button",{type:"submit",disabled:!ie.trim()||ie.startsWith("[["),children:o("wikiInsertLinkAction")})]}),ie.startsWith("[[")&&e.jsx("div",{className:"wiki-link-results",children:a==null?void 0:a.paths.filter(w=>/\.(md|markdown|mdown)$/i.test(w)&&w.toLowerCase().includes(ie.slice(2).toLowerCase())).slice(0,30).map(w=>e.jsx("button",{onClick:()=>Oe(w,!0),children:w},w))})]}),Pe&&!s&&mn.createPortal(e.jsxs("div",{ref:$e,className:`fp-slash-menu ${a?"wiki-slash-menu":""}`,style:{left:Pe.x,top:Pe.y},children:[e.jsx("div",{className:"fp-slash-options",role:"listbox","aria-label":o("richInsertMenu"),children:Ce.length?Ce.map((w,H)=>e.jsxs(d.Fragment,{children:[!a&&(H===0||xe(w)!==xe(Ce[H-1]))&&e.jsx("div",{className:"fp-slash-group",role:"presentation",children:o(xe(w)?"richBlocksGroup":"richTextGroup")}),e.jsxs("button",{type:"button",role:"option","aria-label":Le(w),"aria-selected":H===we,id:`fp-slash-option-${H}`,onMouseDown:X=>X.preventDefault(),onMouseEnter:()=>re(H),onClick:()=>ct(H),children:[e.jsx("span",{className:"fp-slash-icon","aria-hidden":"true",children:V[w.label]}),e.jsxs("span",{className:"fp-slash-label",children:[Le(w),a&&e.jsx("small",{children:o(nt[w.alias])})]}),e.jsx("kbd",{"aria-hidden":"true",children:a?be[w.alias]:`/${w.alias}`})]})]},w.alias)):e.jsx("span",{className:"wiki-slash-empty",children:o(a?"wikiNoInsertResults":"richNoElements")})}),a&&e.jsx("footer",{children:o("wikiInsertKeys")})]}),document.body),e.jsx("div",{className:"fp-markdown msg-text",children:e.jsx("div",{className:"fp-markdown-zoom",children:e.jsx("div",{ref:y,className:"md fp-rich-document",role:"textbox","aria-label":o("richEditMarkdown"),"aria-multiline":"true",contentEditable:!s,suppressContentEditableWarning:!0,spellCheck:!1,"aria-expanded":!!Pe,"aria-autocomplete":"list","aria-activedescendant":Pe&&Ce.length?`fp-slash-option-${we}`:void 0,onBlur:O,onCompositionStart:O,onCompositionEnd:()=>{const w=F();w&&b(w),Fe(),Qe()},onKeyUp:()=>_(pe()),onKeyDown:w=>{if(w.key===" "&&!w.nativeEvent.isComposing&&ee()){w.preventDefault();return}if(w.key==="Enter"&&!s&&!w.nativeEvent.isComposing&&F()){w.preventDefault(),z("insertLineBreak");return}if(w.key==="Tab"&&!s&&!w.nativeEvent.isComposing){const H=pe();if(H){const X=Array.from(H.closest("table").querySelectorAll("th, td")),ke=X.indexOf(H);if(!w.shiftKey||ke>0){w.preventDefault(),!w.shiftKey&&ke===X.length-1?ae("row",H):Ae(X[ke+(w.shiftKey?-1:1)]);return}}}!Pe||w.nativeEvent.isComposing||(w.key==="Escape"?(w.preventDefault(),w.stopPropagation(),O()):w.key==="ArrowDown"||w.key==="ArrowUp"?(w.preventDefault(),re(H=>Ce.length?(H+(w.key==="ArrowDown"?1:-1)+Ce.length)%Ce.length:0)):w.key==="Enter"&&Ce.length?(w.preventDefault(),ct(we)):(w.key==="ArrowLeft"||w.key==="ArrowRight"||w.key==="Home"||w.key==="End")&&O())},onInput:w=>{var X,ke;if(w.target instanceof HTMLSelectElement&&w.target.hasAttribute("data-code-language")){Z(w.target);return}const H=w.target;if(H.type==="checkbox"&&H.toggleAttribute("checked",H.checked),Fe(),!w.nativeEvent.isComposing){Qe();const De=window.getSelection(),He=De==null?void 0:De.anchorNode;if(a&&(De!=null&&De.isCollapsed)&&(He==null?void 0:He.nodeType)===Node.TEXT_NODE&&!((X=He.parentElement)!=null&&X.closest("pre, code, a"))&&((ke=He.textContent)!=null&&ke.slice(0,De.anchorOffset).endsWith("[["))){const ot=De.getRangeAt(0).cloneRange();ot.setStart(He,De.anchorOffset-2),ve.current=ot,W("[[")}}},onClick:w=>{_(pe()),O();const H=w.target.closest("a");if(H){w.preventDefault();const X=H.getAttribute("href");a&&X&&(/^(https?:|mailto:)/i.test(X)?window.open(X,"_blank","noopener,noreferrer"):a.followLink(X))}},onChange:w=>{const H=w.target;H.type==="checkbox"&&(H.toggleAttribute("checked",H.checked),Fe())},onPaste:w=>{w.preventDefault();const H=Array.from(w.clipboardData.files).find(X=>X.type.startsWith("image/"));if(H){Te(H);return}s||z("insertText",w.clipboardData.getData("text/plain"))},onDrop:w=>{w.preventDefault(),w.stopPropagation()}})})})]})}),Rl=d.memo(function({value:n,name:s,readOnly:r,wrap:i,markers:a,onChange:o,onSelectLines:c}){const l=et(),p=d.useRef(null),[u,f]=d.useState(0),k=d.useMemo(()=>ml(n,Os(s)),[n,s]);return e.jsxs("div",{className:`fp-code-editor ${i?"":"no-wrap"}`,children:[e.jsx("div",{className:"fp-code-paint",ref:p,"aria-hidden":"true",children:e.jsx("div",{className:"fp-code-ink hljs",children:k.map((j,R)=>e.jsxs("div",{className:`fp-edit-line ${R+1===u?"current":""}`,"data-line":R+1,children:[e.jsx("span",{className:`fp-edit-marker ${(a==null?void 0:a.get(R+1))??""}`}),e.jsx("span",{className:"fp-edit-number",children:R+1}),e.jsx("span",{className:"fp-edit-text",dangerouslySetInnerHTML:{__html:j||"​"}})]},R))})}),e.jsx("textarea",{className:"fp-editor","aria-label":l("editFile"),value:n,readOnly:r,onChange:j=>o(j.target.value),onClick:j=>f(n.slice(0,j.currentTarget.selectionStart).split(`
192
+ `).length),onKeyUp:j=>f(n.slice(0,j.currentTarget.selectionStart).split(`
193
+ `).length),onSelect:j=>{const R=j.currentTarget;if(R.selectionStart===R.selectionEnd)return;const E=n.slice(0,R.selectionStart).split(`
194
+ `).length,A=n.slice(0,Math.max(R.selectionStart,R.selectionEnd-1)).split(`
195
+ `).length;c==null||c(E,A)},onScroll:j=>{p.current&&(p.current.scrollTop=j.currentTarget.scrollTop,p.current.scrollLeft=j.currentTarget.scrollLeft)},onKeyDown:j=>{j.key!=="Tab"||r||j.nativeEvent.isComposing||(j.preventDefault(),document.execCommand("insertText",!1," "))},wrap:i?"soft":"off",spellCheck:!1,autoCapitalize:"off",autoCorrect:"off"})]})});function Dp(t,n,s,r,i,a){const o=d.useRef({doc:n,draft:s,blocked:r,accept:i,refreshed:a});o.current={doc:n,draft:s,blocked:r,accept:i,refreshed:a};const c=d.useRef(!0),l=d.useRef(null),[p,u]=d.useState(!1),[f,k]=d.useState(""),[j,R]=d.useState(!1),E=d.useRef(!1);d.useEffect(()=>(c.current=!0,()=>{c.current=!1}),[]),d.useEffect(()=>{k(""),R(!1),E.current=!1},[n==null?void 0:n.entry.path]);const A=d.useCallback(()=>{if(l.current)return l.current;const M=o.current.doc;if(!(M!=null&&M.editable)||M.text===void 0||M.text===o.current.draft)return Promise.resolve(!0);if(E.current||o.current.blocked)return Promise.resolve(!1);u(!0),k("");const b=async()=>{var U,ce,ie;let F=M;try{for(;c.current&&((U=o.current.doc)==null?void 0:U.entry.path)===M.entry.path;){const W=o.current.draft;if(W===F.text)return!0;if(o.current.blocked)return!1;const ve=await En(t,"write",{path:M.entry.path,text:W,version:F.version});if(!c.current||((ce=o.current.doc)==null?void 0:ce.entry.path)!==M.entry.path)return!1;F={...ve,backlinks:o.current.doc.backlinks},o.current.doc=F,o.current.accept(F),o.current.refreshed()}return!1}catch(W){return c.current&&((ie=o.current.doc)==null?void 0:ie.entry.path)===M.entry.path&&(k(W.message),W instanceof Ko&&W.detail.code==="version_conflict"&&(E.current=!0,R(!0))),!1}};return l.current=b().finally(()=>{l.current=null,c.current&&u(!1)}),l.current},[t]);d.useEffect(()=>{(n==null?void 0:n.text)===s&&(k(""),R(!1),E.current=!1)},[n==null?void 0:n.version,s]);const N=!!(n!=null&&n.editable)&&n.text!==void 0&&n.text!==s;d.useEffect(()=>{if(!N||r||j||f)return;const M=setTimeout(()=>void A(),800);return()=>clearTimeout(M)},[s,N,r,j,f,A]);const T=async()=>{var b;const M=o.current.doc;if(!M||o.current.blocked)return!1;try{const F=await En(t,"document-content",{path:M.entry.path});if(!c.current||((b=o.current.doc)==null?void 0:b.entry.path)!==M.entry.path||o.current.doc.version!==M.version)return!1;const U={...F,backlinks:M.backlinks};return o.current.doc=U,o.current.accept(U),E.current=!1,R(!1),k(""),await A()}catch(F){return c.current&&k(F.message),!1}},y=d.useCallback(()=>{E.current=!0,R(!0),k("File changed on disk; reload before saving")},[]);return{save:A,saving:p,failure:f,conflict:j,keepMine:T,noteExternalChange:y}}const $p={entries:[],tags:[],revisions:[],running:!1,limited:!1};function Fp({cwd:t,conversationId:n,messages:s,streaming:r,live:i,model:a,contextPercent:o,toolStatuses:c,active:l,ready:p,send:u,guard:f,fileRequest:k,openDocument:j,thinkingWrap:R,connected:E,silenceNotified:A,sessionError:N,writingBlocked:T,onContentRequested:y,recovery:M}){const b=et(),{locale:F}=ns(),[U,ce]=d.useState($p),[ie,W]=d.useState({}),[ve,Se]=d.useState({}),[$,$e]=d.useState(()=>(k==null?void 0:k.path)??localStorage.getItem(`pi-wiki-file:${t}`)??""),[L,q]=d.useState(!1),[fe,je]=d.useState(100),[ne,Pe]=d.useState(null),[B,we]=d.useState(""),[re,Ie]=d.useState(!1),[_,le]=d.useState(!1),[O,ge]=d.useState(!1),[pe,Ae]=d.useState(""),[ae,Te]=d.useState(null),[Z,Fe]=d.useState(()=>new Set),[z,G]=d.useState(()=>localStorage.getItem(`pi-wiki-hidden:${t}`)==="true"),[J,Ee]=d.useState(!0),[V,Le]=Ma("sidebar"),[xe,be]=Ma("chat"),[nt,Ce]=d.useState(!1),[ye,ze]=d.useState(null);d.useEffect(()=>Ce(!1),[$]);const Ze=I=>{Ee(I),Oe(!1),I&&(qe(null),Ce(!1))},[Qe,ct]=d.useState(!1),[tt,Oe]=d.useState(!1),[ee,We]=d.useState(null),w=d.useRef(null),H=d.useRef(null),[X,ke]=d.useState(0),De=()=>{ct(!0)};d.useEffect(()=>{var I;(Qe||J)&&((I=sn.current)==null||I.focus())},[Qe,J]),d.useEffect(()=>{const I=H.current;if(!I)return;const me=new ResizeObserver(()=>ke(I.getBoundingClientRect().height));return me.observe(I),()=>me.disconnect()},[J]);const[He,ot]=d.useState(!1);d.useEffect(()=>ot(!1),[l,n]);const[dt,g]=d.useState(!1),[se,qe]=d.useState(null),[_e,at]=d.useState(!1),[mt,Mt]=d.useState(""),[Pt,$t]=d.useState([]),[Ft,Jt]=d.useState(!1),[nn,lt]=d.useState(!1),[Et,zt]=d.useState(0),[Ht,an]=d.useState(0),[At,Xt]=d.useState(""),[K,Y]=d.useState([]),[Je,Be]=d.useState("");qo(n,l&&p,Xt);const[te,Ve]=d.useState(null),[Ue,yt]=d.useState(!1),[Bt,Zt]=d.useState(!1),[qt,St]=d.useState(!1),[dn,pt]=d.useState(!1),[Dt,Yt]=d.useState(()=>{try{return JSON.parse(localStorage.getItem(`pi-wiki-viewed:${t}`)??"{}")}catch{return{}}}),[Vt,un]=d.useState(Date.now()),[qn,wn]=d.useState(null),sn=d.useRef(null),bn=d.useRef(null),zn=d.useRef(k);zn.current=k;const Tt=d.useRef(!0),Kt=d.useRef(0),_n=d.useRef(0),Vn=d.useRef(0),Kn=d.useRef(U.entries),h=d.useRef(U.revisions),x=d.useRef(void 0);h.current=U.revisions;const S=d.useRef(ne),P=!!(ne!=null&&ne.editable)&&ne.text!==void 0&&B!==ne.text;S.current=ne;const de=qt||O||_||U.running||T||!!ne&&ne.entry.path!==$,oe=de||!p,[Ne,Ke]=d.useState(null),ht=new Set(U.revisions.filter(I=>I.author==="pi").flatMap(I=>I.changes.filter(me=>!me.undone&&(Dt[me.path]??0)<I.at).map(me=>me.path))),ut=d.useMemo(()=>{const I=new Map(U.entries.map(me=>[me.path,me]));for(const me of Object.values(ie)){const Xe=!U.entries.length||U.limited||U.entries.some(st=>st.symlink&&me.path.startsWith(st.path));for(const st of me.entries)!I.has(st.path)&&Xe&&I.set(st.path,st)}return[...I.values()].sort((me,Xe)=>{const st=me.path.split("/"),rt=Xe.path.split("/");for(let vt=0;vt<Math.min(st.length,rt.length);vt++){if(st[vt]===rt[vt])continue;const cn=vt<st.length-1||me.kind==="directory",Fn=vt<rt.length-1||Xe.kind==="directory";return Number(Fn)-Number(cn)||st[vt].localeCompare(rt[vt])}return st.length-rt.length})},[U.entries,U.limited,ie]),gt=d.useMemo(()=>ut.filter(I=>I.kind!=="directory").map(I=>I.path),[ut]),Rt=d.useMemo(()=>new Set(ut.filter(I=>I.kind==="directory"&&!I.path.includes("/")&&I.name.startsWith(".")).map(I=>I.path)),[ut]),rn=d.useMemo(()=>ut.filter(I=>(z||!Rt.has(I.path.split("/")[0]))&&I.path.split("/").slice(0,-1).every((me,Xe,st)=>Z.has(st.slice(0,Xe+1).join("/")))),[ut,Z,z,Rt]),[pn,en]=d.useState(0),jn=Math.max(0,Math.floor(pn/30)-10),xn=jn+70,Cn=/(?:^|\s)(@)([^\s]*)$/.exec(At),tn=Cn?gt.filter(I=>I.toLocaleLowerCase().includes(Cn[2].toLocaleLowerCase())).slice(0,8):[],Gn=I=>{var me;Cn&&(Y(Xe=>[...new Set([...Xe,I])]),Xt(At.slice(0,Cn.index).trimEnd()+" "),an(0),(me=sn.current)==null||me.focus())},Rn=d.useMemo(()=>(ne==null?void 0:ne.entry.kind)==="document"&&ne.text!==void 0?[b("wikiQuickSummary"),b("wikiQuickLinks"),...mu(B)?[b("wikiQuickSections")]:[]]:[],[ne==null?void 0:ne.entry.kind,ne==null?void 0:ne.text,B,b]),Jn=Ia(At,$,Je,K,"",ut,Ue,Bt,{scope:b("wikiScope"),selection:b("wikiSelected"),documentsOnly:b("wikiDocumentsOnlyPrompt"),skip:b("wikiSkipPrompt")});d.useEffect(()=>(Tt.current=!0,()=>{Tt.current=!1,Kt.current++,_n.current++}),[]),d.useEffect(()=>{wn(document.getElementById("wiki-toolbar-slot")),We(document.getElementById("wiki-status-slot"))},[l]);const ss=d.useCallback(async(I,me=0)=>{try{const Xe=await En(t,"directory",{path:I,offset:me});Tt.current&&W(st=>{var rt;return{...st,[I]:{...Xe,entries:me?[...((rt=st[I])==null?void 0:rt.entries)??[],...Xe.entries]:Xe.entries}}})}catch(Xe){Tt.current&&Ae(Xe.message)}},[t]);d.useEffect(()=>{var I;k&&(((I=S.current)==null?void 0:I.entry.path)===k.path&&y(k.token),Ce(!1),Ee(!0),qe(null),$e(k.path),Ie(!1),at(!1),g(!1),Be(""),Ve(null))},[k,y,ne==null?void 0:ne.entry.path]),d.useEffect(()=>{l&&ss("")},[l,ss]),d.useEffect(()=>{l&&$&&!k&&j($)},[l,$,k,j]);const An=d.useCallback(async(I=!1)=>{const me=++_n.current;try{const Xe=await En(t,I?"refresh":"state");Tt.current&&me===_n.current&&ce(Xe)}catch(Xe){Tt.current&&me===_n.current&&Ae(Xe.message)}},[t]),vn=Dp(t,ne,B,_||O||U.running||T||(ne==null?void 0:ne.entry.path)!==$,Pe,()=>void An(!0)),{save:kn,saving:hn}=vn;d.useEffect(()=>Wd(async()=>{const I=await kn();return I||Ze(!1),I}),[kn]),d.useEffect(()=>{if(!l)return;An();const I=setInterval(()=>{un(Date.now()),An()},r||U.running?1e3:3e4);return()=>clearInterval(I)},[l,r,U.running,An]),d.useEffect(()=>{$&&Fe(I=>{const me=new Set(I),Xe=$.split("/");for(let st=1;st<Xe.length;st++)me.add(Xe.slice(0,st).join("/"));return me})},[$]),d.useEffect(()=>{if($||!U.entries.length)return;const I=U.entries.find(me=>/^(readme|index)\.md$/i.test(me.path))??U.entries.find(me=>me.kind==="document");I&&$e(I.path)},[U.entries,$]);const on=d.useCallback(async(I,me)=>{const Xe=++Vn.current;try{const st=await En(t,"document-references",{path:I});if(!Tt.current||me!==Kt.current||Xe!==Vn.current)return;Pe(rt=>(rt==null?void 0:rt.entry.path)===I?{...rt,...st}:rt),q(!0)}catch(st){Tt.current&&me===Kt.current&&Xe===Vn.current&&Ae(st.message)}},[t]),yn=d.useCallback(async(I,me=!1)=>{var st;const Xe=++Kt.current;le(!0),q(!1),je(100),Ae("");try{const rt=En(t,"document-content",{path:I}),vt=zn.current;(vt==null?void 0:vt.path)===I&&y(vt.token);const cn=await rt;if(!Tt.current||Xe!==Kt.current)return;x.current=(st=h.current.find(Fn=>Fn.author==="pi"&&Fn.changes.some(js=>js.path===I)))==null?void 0:st.id,Pe({...cn,backlinks:[]}),we(cn.text??""),Be(""),Ve(null),on(I,Xe),localStorage.setItem(`pi-wiki-file:${t}`,I),me&&Yt(Fn=>{const js={...Fn,[I]:Date.now()};return localStorage.setItem(`pi-wiki-viewed:${t}`,JSON.stringify(js)),js})}catch(rt){Tt.current&&Xe===Kt.current&&(Pe(null),Ae(rt.message))}finally{Tt.current&&Xe===Kt.current&&le(!1)}},[t,y,on]);d.useEffect(()=>{var I;return $&&l&&((I=S.current)==null?void 0:I.entry.path)!==$&&yn($,!0),()=>{Kt.current++}},[$,l,yn]),d.useEffect(()=>{var I;l&&((I=S.current)==null?void 0:I.entry.path)===$&&U.entries.length&&on($,Kt.current)},[U.entries,l,$,on]),d.useEffect(()=>{if(!ne||P||hn||_||r||U.running||!l||Kn.current===U.entries)return;Kn.current=U.entries;const I=U.entries.find(rt=>rt.path===$),me=U.revisions.find(rt=>rt.author==="pi"&&rt.changes.some(vt=>vt.path===$));if(!I||I.modified===ne.entry.modified){x.current=me==null?void 0:me.id;return}if(!ne.editable||(me==null?void 0:me.id)!==x.current){yn($);return}const Xe=ne,st=Kt.current;En(t,"document-content",{path:$}).then(rt=>{var vt;!Tt.current||st!==Kt.current||((vt=S.current)==null?void 0:vt.version)!==Xe.version||(rt.version!==Xe.version?vn.noteExternalChange():Pe(cn=>cn&&{...cn,entry:rt.entry}))}).catch(rt=>{Tt.current&&st===Kt.current&&Ae(rt.message)})},[U.entries,ne,P,hn,_,l,$,yn,t,U.revisions,U.running,r,vn.noteExternalChange]);const Qn=d.useRef(0),Nt=d.useCallback(I=>{const me=++Qn.current;P||hn?kn().then(Xe=>{!Tt.current||me!==Qn.current||(Xe?I():Te(()=>I))}):I()},[P,hn,kn]);d.useEffect(()=>(f.current=P||hn?Nt:null,()=>{f.current=null}),[f,Nt,P,hn]),d.useEffect(()=>{const I=me=>{P&&(kn(),me.preventDefault(),me.returnValue="")};return window.addEventListener("beforeunload",I),()=>window.removeEventListener("beforeunload",I)},[P,kn]);const ln=I=>Nt(()=>{if(I!==$){j(I);return}Ze(!0),$e(I),Ie(!1),at(!1),g(!1),Ve(null),Fe(me=>{const Xe=new Set(me),st=I.split("/");for(let rt=1;rt<st.length;rt++)Xe.add(st.slice(0,rt).join("/"));return Xe}),I===$&&yn(I,!0)});d.useEffect(()=>{if(!l)return;const I=me=>{var Xe;if(me.key==="/"&&!me.metaKey&&!me.ctrlKey&&!me.altKey&&!me.isComposing&&!(me.target instanceof HTMLElement&&me.target.closest("input,textarea,select,[contenteditable=true],[role=dialog]"))&&(me.preventDefault(),De()),me.key==="Tab"&&(_e||ae)){const st=[...document.querySelectorAll(".wiki-modal-backdrop [role=dialog]")].at(-1),rt=[...(st==null?void 0:st.querySelectorAll("button:not(:disabled), input, textarea, select, [tabindex='0']"))??[]];rt.length&&me.shiftKey&&document.activeElement===rt[0]?(me.preventDefault(),(Xe=rt.at(-1))==null||Xe.focus()):rt.length&&!me.shiftKey&&document.activeElement===rt.at(-1)&&(me.preventDefault(),rt[0].focus())}(me.metaKey||me.ctrlKey)&&me.key.toLowerCase()==="j"&&!me.isComposing&&!_e&&!ae&&(me.preventDefault(),Ze(!J)),(me.metaKey||me.ctrlKey)&&me.key.toLowerCase()==="k"&&(me.preventDefault(),at(st=>!st)),(me.metaKey||me.ctrlKey)&&me.key.toLowerCase()==="s"&&(me.preventDefault(),de||kn()),me.key==="Escape"&&(!_e&&!ae&&!se&&!te&&!tt&&Ze(!1),ct(!1),Oe(!1),pt(!1),Te(null),at(!1),Ve(null),qe(null),g(!1))};return window.addEventListener("keydown",I),()=>window.removeEventListener("keydown",I)}),d.useEffect(()=>{if(!_e||!mt.trim()){$t([]),Jt(!1);return}const I=new AbortController;Jt(!0),$t([]),lt(!1),zt(0);const me=setTimeout(()=>{En(t,"search",{query:mt},I.signal).then(Xe=>{I.signal.aborted||($t(Xe.results.sort((st,rt)=>["document","code","pdf","image","other"].indexOf(st.kind)-["document","code","pdf","image","other"].indexOf(rt.kind))),lt(Xe.limited))}).catch(Xe=>{I.signal.aborted||Ae(Xe.message)}).finally(()=>{I.signal.aborted||Jt(!1)})},250);return()=>{clearTimeout(me),I.abort()}},[t,mt,_e]),d.useEffect(()=>{var I;_e&&((I=document.querySelector(".wiki-search-results button.selected"))==null||I.scrollIntoView({block:"nearest"}))},[_e,Et]);const Dn=async(I,me,Xe)=>{if(P){Ae(b("wikiSaveFirst"));return}ge(!0),Ae("");try{const st=await En(t,"restore",{id:I.id,undo:me,path:Xe});Tt.current&&(ce(st),$&&await yn($))}catch(st){Tt.current&&Ae(st.message)}finally{Tt.current&&ge(!1)}},In=async I=>{if(!(!(I??At).trim()||oe||!$&&!Ue&&!K.length)){St(!0),Ae("");try{if(P&&!await kn())return;await En(t,"prompt",{text:I??Jn,requestId:Gt(),conversationId:n}),Tt.current&&(I||(Xt(""),Be(""),Y([])),pt(!1),Oe(!1),ct(!1),Ze(!0),An())}catch(me){Tt.current&&Ae(me.message)}finally{Tt.current&&St(!1)}}},Sn=I=>{var me;Y(Xe=>[...new Set([...Xe,I.path])]),at(!1),De(),(me=sn.current)==null||me.focus()},Yn=()=>{var st,rt;const I=window.getSelection();if(!I||I.isCollapsed||!((st=bn.current)!=null&&st.contains(I.anchorNode))||!((rt=bn.current)!=null&&rt.contains(I.focusNode))){Ve(null);return}const me=I.toString().trim().slice(0,12e3),Xe=I.getRangeAt(0).getBoundingClientRect();me&&Ve({text:me,x:Math.max(8,Math.min(Xe.left,window.innerWidth-300)),y:Math.min(Xe.bottom+8,window.innerHeight-50)})},$n=I=>{var me;te&&(Be(te.text),Ve(null),Ze(!0),I!=="ask"&&Xt(b(I==="rewrite"?"wikiRewritePrompt":I==="explain"?"wikiExplainPrompt":"wikiLinkPrompt")),De(),(me=sn.current)==null||me.focus())},gs=I=>{let me=I;try{I.startsWith("#wiki=")&&(me=decodeURIComponent(I.slice(6)))}catch{return}const Xe=Ra($,me,gt);Xe?ln(Xe):Ae(b("wikiMissingLink",{path:me}))},rs=d.useMemo(()=>Qo(B).rows,[B]),Hn=d.useMemo(()=>Xo(B),[B]),cs=Hn.readingBody,Xn=new Date((ne==null?void 0:ne.entry.modified)??0),ds=new Date(Vt),bs=Xn.toDateString()===ds.toDateString()?b("wikiUpdatedToday",{time:Xn.toLocaleTimeString(F==="zh"?"zh-CN":"en-US",{hour:"2-digit",minute:"2-digit",hour12:!1})}):b("wikiUpdatedDate",{date:Xn.toLocaleDateString(F==="zh"?"zh-CN":"en-US",{month:"long",day:"numeric",...Xn.getFullYear()!==ds.getFullYear()?{year:"numeric"}:{}})}),xs=new Set(ne==null?void 0:ne.backlinks.map(I=>I.path)).size,Q=d.useMemo(()=>Ne&&Ne.path===$&&!Ne.undone?new Set((Ne.after??"").split(`
196
+ `).filter(I=>!(Ne.before??"").split(`
197
+ `).includes(I))):new Set,[Ne,$]),Re=async I=>{const me=Kt.current,Xe=I.changes.find(st=>st.path===$)??I.changes[0];if(Xe)try{const st=await En(t,"change",{id:I.id,path:Xe.path});if(!Tt.current||me!==Kt.current)return;Ke(st),Xe.path!==$?ln(Xe.path):requestAnimationFrame(()=>{var rt,vt;return(vt=(rt=bn.current)==null?void 0:rt.querySelector(".wiki-added"))==null?void 0:vt.scrollIntoView({block:"center",behavior:"smooth"})})}catch(st){Ae(st.message)}},Ye=d.useMemo(()=>hu(cs),[cs]),ft=I=>{var Xe;const me=[...((Xe=bn.current)==null?void 0:Xe.querySelectorAll(".wiki-prose h2"))??[]];return me[Aa(me.map(st=>st.textContent??""),I)]},wt=I=>{const me=ft(I);me&&(window.matchMedia("(max-width: 1099px)").matches&&Ze(!1),me.scrollIntoView({behavior:window.matchMedia("(prefers-reduced-motion: reduce)").matches?"instant":"smooth",block:"start"}),me.animate([{backgroundColor:"transparent"},{backgroundColor:getComputedStyle(me).getPropertyValue("--accent-soft").trim(),offset:.15},{backgroundColor:"transparent"}],{duration:1500}))},Ct=(pe||N)&&e.jsxs("div",{className:"wiki-error",role:"alert",children:[e.jsx("span",{children:pe||N}),N&&e.jsx("button",{onClick:()=>void j($),children:b("wikiRetrySession")}),e.jsx("button",{onClick:()=>Ae(""),"aria-label":b("close"),children:e.jsx(Wt,{})}),ne&&e.jsx("button",{onClick:()=>Nt(()=>void yn($)),children:b("wikiReload")})]}),It=e.jsxs("div",{ref:H,className:`wiki-composer-area ${Qe||J?"expanded":"compact"}`,children:[!J&&!Qe&&e.jsxs("div",{className:"wiki-composer-pill",children:[e.jsxs("button",{className:"wiki-expand-composer",onClick:De,"aria-label":b("wikiExpandComposer"),children:[e.jsx("span",{className:"wiki-pill-file",children:$.split("/").at(-1)||b("wikiMode")}),e.jsx("span",{children:At.trim()||b("wikiCompactPlaceholder")}),e.jsx("kbd",{children:"/"})]}),r?e.jsx("button",{className:"wiki-pill-send stop","aria-label":b("wikiStop"),onClick:()=>u({type:"abort"}),children:e.jsx(ms,{})}):e.jsx("button",{className:"wiki-pill-send","aria-label":b("wikiSend"),disabled:!0,children:e.jsx(mr,{})})]}),e.jsxs("div",{className:`wiki-composer${At.trim()?" has-draft":""}`,hidden:!Qe&&!J,children:[(Je||K.length>0)&&e.jsxs("div",{className:"wiki-context-chips",children:[Je&&e.jsxs("button",{className:"wiki-quoted-selection",onClick:()=>Be(""),title:b("wikiSelected"),children:[e.jsx("b",{children:b("wikiSelected")}),e.jsx("span",{children:Je}),e.jsx(Wt,{})]}),K.map(I=>e.jsxs("button",{onClick:()=>Y(me=>me.filter(Xe=>Xe!==I)),children:["@",I,e.jsx(Wt,{})]},I))]}),tn.length>0&&e.jsx("div",{className:"wiki-mentions",children:tn.map(I=>e.jsxs("button",{className:tn[Ht]===I?"selected":"",onClick:()=>Gn(I),children:[Cn[1],I]},I))}),e.jsx("textarea",{ref:sn,"aria-label":b("wikiAsk"),placeholder:(ne==null?void 0:ne.entry.kind)==="code"?b("wikiAskCode",{file:ne.entry.name}):b("wikiAskPlaceholder"),value:At,onChange:I=>{Xt(I.target.value),an(0)},onKeyDown:I=>{if(tn.length&&!I.nativeEvent.isComposing){if(I.key==="ArrowDown"||I.key==="ArrowUp"){I.preventDefault(),an(me=>(me+(I.key==="ArrowDown"?1:tn.length-1))%tn.length);return}if(I.key==="Enter"||I.key==="Tab"){I.preventDefault(),Gn(tn[Ht]??tn[0]);return}}I.key==="Enter"&&!I.shiftKey&&!I.nativeEvent.isComposing&&(I.preventDefault(),In())}}),e.jsxs("div",{className:"wiki-composer-controls",children:[e.jsxs("div",{className:"wiki-scope-control",children:[e.jsxs("button",{"aria-label":b("wikiScope"),"aria-expanded":tt,onClick:()=>Oe(I=>!I),children:[Ue?b("wikiWholeScope"):K.length?b("wikiReferencedScope"):(ne==null?void 0:ne.entry.name)||b("wikiCurrentScope")," ",e.jsx(Qt,{})]}),tt&&e.jsxs("div",{className:"wiki-scope-menu",children:[e.jsx("button",{"aria-pressed":!Ue,onClick:()=>{yt(!1),Oe(!1)},children:b("wikiCurrentScope")}),e.jsx("button",{"aria-pressed":Ue,onClick:()=>{yt(!0),Oe(!1)},children:b("wikiWholeScope")}),e.jsx("button",{onClick:()=>{pt(I=>!I),Oe(!1)},children:b("wikiPromptPreview")})]})]}),e.jsx("button",{"aria-pressed":Bt,onClick:()=>Zt(I=>!I),children:b(Bt?"wikiMayEditCode":"wikiDocumentsOnly")}),e.jsx("span",{className:"wiki-mention-hints",children:e.jsx("button",{onClick:()=>{var I;Xt(me=>me+" @"),(I=sn.current)==null||I.focus()},children:b("wikiReferenceHint")})}),!J&&e.jsx("button",{className:"wiki-collapse-composer",onClick:()=>{ct(!1),Oe(!1)},children:b("wikiCollapseComposer")}),r?e.jsx("button",{className:"wiki-send stopping","aria-label":b("wikiStop"),onClick:()=>u({type:"abort"}),children:e.jsx(ms,{})}):e.jsxs("button",{className:"wiki-send","aria-label":b(p?qt?"sending":"wikiSend":"wikiSessionPreparing"),title:b(p?qt?"sending":"wikiSend":"wikiSessionPreparing"),disabled:oe||!At.trim()||!$&&!Ue&&!K.length,onClick:()=>void In(),children:[(!p||qt)&&e.jsx("span",{children:b(p?"sending":"wikiSessionPreparing")}),e.jsx(mr,{})]})]}),dn&&e.jsx("pre",{className:"wiki-prompt-preview",children:Jn})]})]}),Ot=(ne==null?void 0:ne.editable)&&e.jsxs("button",{className:`wiki-save-status ${vn.failure?"failed":hn||P?"saving":"saved"}`,onClick:()=>void kn(),title:vn.failure||void 0,disabled:!vn.failure||vn.conflict,"aria-live":"polite",children:[e.jsx("i",{}),b(vn.failure?"wikiSaveFailedRetry":hn||P?"wikiSaving":"wikiSaved")]}),Ln=e.jsxs("button",{disabled:!(ne!=null&&ne.editable)||_||ne.entry.path!==$,"aria-pressed":re,onClick:()=>Ie(I=>!I),children:[e.jsx(Po,{}),b(re?"wikiPreview":"wikiSource")]}),Nn=e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"wiki-breadcrumb",title:`${t}/${$}`,children:[e.jsx("span",{className:"wiki-path-parent",children:$.includes("/")&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"wiki-path-segment",children:$.split("/").slice(0,-2).map(I=>`${I} / `).join("")}),e.jsxs("span",{className:"wiki-path-tail",children:[$.split("/").at(-2)," / "]})]})}),e.jsx("b",{children:$.split("/").at(-1)||b("wikiMode")}),Ot]}),e.jsxs("div",{className:"wiki-toolbar-actions",children:[e.jsxs("button",{onClick:()=>{Ce(!1),Ze(!1),qe(se==="recent"?null:"recent")},className:se==="recent"?"active":"",children:[e.jsx(pa,{}),b("wikiRecent")]}),e.jsxs("button",{className:`wiki-chat-toggle ${J?"active":""}`,"aria-label":b("wikiChatPanel"),"aria-expanded":J,onClick:()=>Ze(!J),children:[e.jsx("span",{children:"π"}),b("wikiChatTitle"),e.jsx("kbd",{children:navigator.platform.includes("Mac")?"⌘J":"Ctrl+J"})]})]})]});return e.jsxs("section",{className:`wiki-workbench ${nt?"is-focused":""} ${se?"with-drawer":""} ${J?"with-chat":""}`,"aria-label":b("wikiMode"),style:{"--wiki-sidebar-width":`${V}px`,"--wiki-chat-width":`${xe}px`},children:[l&&qn&&mn.createPortal(Nn,qn),l&&ee&&U.index&&mn.createPortal(e.jsx(ju,{status:U.index}),ee),e.jsxs("aside",{className:`wiki-sidebar ${dt?"open":""}`,children:[e.jsx(Pa,{side:"sidebar",width:V,onResize:Le}),e.jsxs("button",{className:"wiki-search-trigger",onClick:()=>at(!0),children:[e.jsx(as,{}),e.jsx("span",{children:b("wikiSearchAll")}),e.jsx("kbd",{children:"⌘K"})]}),e.jsxs("div",{className:"wiki-tree-label",children:[e.jsx("span",{children:b("wikiFiles")}),e.jsx("button",{"aria-label":b("newWorkspaceFile"),title:b("newWorkspaceFile"),disabled:T||!E||U.running,onClick:()=>ot(I=>!I),children:e.jsx(ls,{})}),e.jsx("button",{"aria-label":b("wikiRefresh"),onClick:()=>void An(!0),children:e.jsx(ys,{})})]}),He&&e.jsx(Zo,{cwd:t,conversationId:n,initialPath:$.includes("/")?$.slice(0,$.lastIndexOf("/")+1):"",disabled:T||!E||U.running,onCancel:()=>ot(!1),onCreated:I=>{ot(!1),An(!0),ln(I)}},`${t}:${n}`),e.jsxs("div",{className:"wiki-tree",role:"tree","aria-label":b("wikiFiles"),onScroll:I=>en(I.currentTarget.scrollTop),children:[Rt.size>0&&e.jsxs("button",{className:"wiki-tree-row wiki-hidden-folders",role:"treeitem","aria-expanded":z,onClick:()=>{const I=!z;G(I),localStorage.setItem(`pi-wiki-hidden:${t}`,String(I)),en(0)},children:[z?e.jsx(Qt,{}):e.jsx(_t,{}),e.jsx("span",{children:b("wikiHiddenFolders",{count:Rt.size})})]}),e.jsx("div",{style:{height:jn*30}}),rn.slice(jn,xn).map(I=>e.jsxs("button",{role:"treeitem","aria-selected":I.path===$,"aria-expanded":I.kind==="directory"?Z.has(I.path):void 0,className:`wiki-tree-row ${I.path===$?"selected":""}`,style:{paddingLeft:12+(I.path.split("/").length-1)*16},title:I.path,onClick:()=>I.kind==="directory"?Fe(me=>{const Xe=new Set(me);return Xe.has(I.path)?Xe.delete(I.path):(Xe.add(I.path),ss(I.path)),Xe}):ln(I.path),children:[I.kind==="directory"?Z.has(I.path)?e.jsx(Qt,{}):e.jsx(_t,{}):e.jsx("i",{className:"wiki-tree-spacer"}),e.jsx("span",{children:I.name}),ht.has(I.path)&&e.jsx("i",{className:"wiki-unread","aria-label":b("wikiUnread")})]},I.path)),e.jsx("div",{style:{height:Math.max(0,rn.length-xn)*30}}),Object.values(ie).filter(I=>I.nextOffset!==void 0&&(U.limited||ut.some(me=>me.symlink&&I.path.startsWith(me.path)))&&(!I.path||Z.has(I.path))).map(I=>e.jsxs("button",{className:"wiki-load-more",onClick:()=>void ss(I.path,I.nextOffset),children:[b("wikiLoadMore")," · ",I.path||"/"]},I.path)),!rn.length&&e.jsx("p",{className:"wiki-muted",children:b("wikiNoFiles")})]})]}),dt&&e.jsx("button",{className:"wiki-sidebar-scrim","aria-label":b("close"),onClick:()=>g(!1)}),e.jsxs("div",{className:"wiki-main",children:[e.jsxs("div",{className:"wiki-document-toolbar",children:[e.jsxs("div",{className:"wiki-mobile-tools",children:[e.jsx("button",{"aria-label":b("wikiFiles"),onClick:()=>{Ce(!1),g(I=>!I)},children:e.jsx(To,{})}),e.jsx("button",{"aria-label":b("wikiSearchAll"),onClick:()=>at(!0),children:e.jsx(as,{})})]}),e.jsx("div",{className:"wiki-editor-toolbar-slot",ref:ze}),(ne==null?void 0:ne.entry.kind)==="code"&&e.jsx("div",{className:"wiki-toolbar-actions",children:Ln})]}),!J&&Ct,vn.conflict&&e.jsxs("div",{className:"wiki-conflict",role:"alert",children:[e.jsx("span",{children:b("wikiExternalChanged")}),e.jsx("button",{disabled:de,onClick:()=>void yn($),children:b("wikiReload")}),e.jsx("button",{disabled:de||hn,onClick:()=>void vn.keepMine(),children:b("wikiKeepMine")})]}),e.jsx("div",{className:"wiki-scroll",ref:w,style:{paddingBottom:J?0:Math.max(0,X-120)},onScroll:()=>Ve(null),children:_?e.jsx("div",{className:"wiki-empty",children:b("loading")}):ne?e.jsxs("article",{className:`wiki-document ${re||ne.entry.kind==="code"?"is-source":""}`,ref:bn,onMouseUp:re?Yn:void 0,onKeyUp:re?Yn:void 0,children:[e.jsxs("header",{className:"wiki-document-heading",children:[e.jsx("h1",{children:Hn.title||ne.entry.name.replace(/\.(md|txt)$/i,"")}),e.jsxs("div",{className:"wiki-document-meta",children:[e.jsxs("span",{className:"wiki-meta-chip",children:[e.jsx(Do,{}),bs]}),ne.text!==void 0&&e.jsxs("span",{className:"wiki-meta-chip",children:[e.jsx(pa,{}),b("wikiReadingTime",{minutes:Hn.minutes})]}),Hn.tags.map(I=>e.jsxs("span",{className:"wiki-meta-chip wiki-meta-tag",children:["#",I]},I)),(!L||xs>0)&&e.jsx("button",{onClick:()=>{var I,me;return(me=(I=bn.current)==null?void 0:I.querySelector(".wiki-backlinks"))==null?void 0:me.scrollIntoView({behavior:"smooth"})},children:L?b("wikiCitations",{count:xs}):b("wikiReferencesLoading")})]}),(ne==null?void 0:ne.entry.kind)==="document"&&rs.length>0&&e.jsxs("details",{className:"wiki-properties",open:!0,children:[e.jsx("summary",{children:b("wikiProperties")}),e.jsx("dl",{children:rs.map((I,me)=>e.jsxs("div",{children:[e.jsx("dt",{children:I.key}),e.jsx("dd",{children:e.jsx(Ir,{children:I.value})})]},me))})]})]}),ne.text!==void 0?re||ne.entry.kind==="code"?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"wiki-code-hint",children:ne.entry.kind==="code"&&!re?b("wikiCodeReadOnly"):b("wikiEditingSource")}),e.jsx(Rl,{value:B,name:$,readOnly:de||!ne.editable||!re&&ne.entry.kind==="code",wrap:!1,onChange:we,onSelectLines:(I,me)=>Be(B.split(`
198
+ `).slice(I-1,me).join(`
199
+ `))})]}):e.jsx("div",{className:"wiki-prose md",children:e.jsx(Tl,{file:{cwd:t,path:$},value:B,readOnly:de||!ne.editable,onChange:we,wiki:{toolbarHost:ye,focused:nt,onWidth:()=>{Ce(!nt),Ze(!1),ct(!1),qe(null),g(!1)},paths:gt,ask:I=>{var me;Be(I.slice(0,12e3)),Ze(!0),De(),(me=sn.current)==null||me.focus()},followLink:gs,resolveCode:I=>Ra($,I,gt),added:Q}},`${t}:${$}`)}):ne.entry.kind==="image"?e.jsx("img",{className:"wiki-image",src:Ur(t,$),alt:ne.entry.name}):ne.entry.kind==="pdf"?e.jsx("iframe",{className:"wiki-pdf",title:ne.entry.name,src:Ur(t,$)}):e.jsxs("div",{className:"wiki-empty",children:[e.jsx(Gs,{}),e.jsxs("p",{children:[ne.entry.name," · ",Math.ceil(ne.entry.size/1024)," KB"]}),kt!=null&&kt.openWikiFile?e.jsx("button",{onClick:()=>void kt.openWikiFile({clientId:fn(),cwd:t,path:$}).catch(I=>Ae(I.message)),children:b("wikiOpenDefault")}):e.jsx("a",{href:Ur(t,$,!0),download:!0,children:b("wikiDownloadOpen")})]}),(!L||ne.backlinks.length>0)&&e.jsxs("section",{className:"wiki-backlinks",children:[e.jsxs("h2",{children:[e.jsx(hr,{}),b("wikiBacklinks")," ",e.jsx("span",{children:L?ne.backlinks.length:b("loading")})]}),ne.backlinks.slice(0,fe).map((I,me)=>e.jsxs("button",{onClick:()=>ln(I.path),children:[e.jsx("strong",{children:I.path}),e.jsx("span",{children:I.snippet})]},`${I.path}:${me}`)),ne.backlinks.length>fe&&e.jsx("button",{onClick:()=>je(I=>I+100),children:b("wikiLoadMore")}),!L&&e.jsx("p",{children:b("wikiReferencesLoading")}),L&&!ne.backlinks.length&&e.jsx("p",{children:b("wikiNoBacklinks")})]})]}):e.jsxs("div",{className:"wiki-empty",children:[e.jsx(gd,{}),e.jsx("h1",{children:b("wikiWelcome")}),e.jsx("p",{children:b("wikiWelcomeHint")}),e.jsx("button",{onClick:()=>at(!0),children:b("wikiSearchAll")})]})}),!J&&It]}),J&&e.jsxs(e.Fragment,{children:[e.jsx("button",{className:"wiki-chat-scrim","aria-label":b("wikiCloseChat"),onClick:()=>Ze(!1)}),e.jsx(Au,{resizeHandle:e.jsx(Pa,{side:"chat",width:xe,onResize:be}),onStop:()=>u({type:"abort"}),recovery:M,conversationId:n,thinkingWrap:R,connected:E,silenceNotified:A,messages:s,live:i,streaming:r,toolStatuses:c,model:a??void 0,contextPercent:o,disabled:oe,onNew:()=>Nt(()=>void j($)),onClose:()=>Ze(!1),canJump:I=>!re&&Aa(Ye,I)>=0,jump:wt,composer:It,quickQuestions:Rn,onQuickQuestion:I=>void In(Ia(I,$,"",[],"",[],!1,!1,{scope:b("wikiScope"),selection:b("wikiSelected"),documentsOnly:b("wikiDocumentsOnlyPrompt"),skip:b("wikiSkipPrompt")})),revisions:U.revisions,onViewChange:I=>void Re(I),onUndo:I=>void Dn(I,!I.changes.every(me=>me.undone)),onResend:I=>void In(I),error:Ct})]}),se&&e.jsxs("aside",{className:"wiki-changes",children:[e.jsxs("header",{children:[e.jsxs("div",{children:[e.jsx("h2",{children:b(se==="recent"?"wikiRecent":"wikiRelatedChanges")}),e.jsx("span",{children:t.split(/[\\/]/).at(-1)})]}),e.jsx("button",{"aria-label":b("close"),onClick:()=>qe(null),children:e.jsx(Wt,{})})]}),e.jsxs("div",{className:"wiki-changes-scroll",children:[U.revisions.filter(I=>se==="recent"||I.id===se).map((I,me,Xe)=>e.jsxs("div",{className:"wiki-revision",children:[(me===0||new Date(Xe[me-1].at).toDateString()!==new Date(I.at).toDateString())&&e.jsx("time",{children:new Date(I.at).toLocaleDateString(F==="zh"?"zh-CN":"en-US")}),e.jsxs("div",{className:"wiki-revision-title",children:[e.jsx("span",{className:`wiki-avatar ${I.author}`,children:I.author==="pi"?e.jsx("img",{src:"/icon/1a-mark.svg",alt:"pi"}):b("wikiMe")}),e.jsxs("div",{children:[e.jsx("strong",{children:I.title.split(`
200
+ `)[0]}),e.jsxs("small",{children:[new Date(I.at).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})," · ",b("wikiFileCount",{count:I.changes.length})]})]})]}),e.jsxs("div",{className:"wiki-revision-actions",children:[e.jsxs("button",{disabled:oe||I.changes.every(st=>st.undone),onClick:()=>void Dn(I,!0),children:[e.jsx(Mo,{}),b("wikiUndoAll")]}),e.jsxs("button",{disabled:oe||I.changes.every(st=>!st.undone),onClick:()=>void Dn(I,!1),children:[e.jsx(ud,{}),b("wikiRedoAll")]})]}),I.changes.map(st=>{const rt={...st,...ve[`${I.id}:${st.path}`]??{},undone:st.undone};return e.jsxs("div",{className:`wiki-file-change ${rt.undone?"undone":""}`,children:[e.jsxs("div",{children:[e.jsx("button",{title:rt.path,onClick:()=>ln(rt.path),children:rt.path}),e.jsx("button",{disabled:oe,onClick:()=>void Dn(I,!rt.undone,rt.path),children:b(rt.undone?"wikiRedo":"wikiUndo")})]}),e.jsxs("small",{children:[e.jsxs("em",{children:["+",rt.additions]})," ",e.jsxs("b",{children:["−",rt.deletions]})]}),e.jsxs("details",{onToggle:vt=>{vt.currentTarget.open&&rt.truncated&&En(t,"change",{id:I.id,path:rt.path}).then(cn=>{Tt.current&&Se(Fn=>({...Fn,[`${I.id}:${rt.path}`]:cn}))}).catch(cn=>Ae(cn.message))},children:[e.jsx("summary",{children:b("wikiViewDiff")}),rt.binary?e.jsx("p",{children:b("wikiBinaryChange")}):e.jsxs(e.Fragment,{children:[e.jsx("pre",{className:"wiki-diff-before",children:rt.before??b("wikiNewFile")}),e.jsx("pre",{className:"wiki-diff-after",children:rt.after??b("wikiDeletedFile")})]})]})]},rt.path)}),I.skipped.length>0&&e.jsxs("p",{className:"wiki-skipped",children:[b("wikiUntracked"),": ",I.skipped.join(", ")]})]},I.id)),!U.revisions.length&&e.jsx("p",{className:"wiki-muted",children:b("wikiNoChanges")})]})]}),te&&mn.createPortal(e.jsx("div",{className:"wiki-selection-menu",style:{left:te.x,top:te.y},onMouseDown:I=>I.preventDefault(),children:["ask","rewrite","explain","link"].map(I=>e.jsx("button",{onClick:()=>$n(I),children:b(I==="ask"?"wikiAskPi":I==="rewrite"?"wikiRewrite":I==="explain"?"wikiExplain":"wikiAddLink")},I))}),document.body),_e&&e.jsx("div",{className:"wiki-modal-backdrop",onMouseDown:I=>{I.target===I.currentTarget&&at(!1)},children:e.jsxs("section",{className:"wiki-search-modal",role:"dialog","aria-modal":"true","aria-label":b("wikiSearchAll"),children:[e.jsxs("div",{children:[e.jsx(as,{}),e.jsx("input",{autoFocus:!0,"aria-label":b("wikiSearchAll"),placeholder:b("wikiSearchHint"),value:mt,onChange:I=>Mt(I.target.value),onKeyDown:I=>{(I.key==="ArrowDown"||I.key==="ArrowUp")&&(I.preventDefault(),zt(me=>Math.max(0,Math.min(Pt.length-1,me+(I.key==="ArrowDown"?1:-1))))),I.key==="Enter"&&Pt[Et]&&(I.preventDefault(),I.metaKey||I.ctrlKey?Sn(Pt[Et]):ln(Pt[Et].path))}}),e.jsx("button",{"aria-label":b("close"),onClick:()=>at(!1),children:e.jsx(Wt,{})})]}),e.jsxs("div",{className:"wiki-search-results",children:[Ft&&e.jsx("p",{role:"status",children:b("loading")}),Pt.map((I,me)=>e.jsxs("div",{children:[(me===0||Pt[me-1].kind!==I.kind)&&e.jsx("h3",{children:b(I.kind==="document"?"wikiDocuments":I.kind==="pdf"?"wikiPdf":I.kind==="code"?"wikiCode":"wikiFiles")}),e.jsxs("button",{className:Et===me?"selected":"",onMouseEnter:()=>zt(me),onClick:Xe=>Xe.metaKey||Xe.ctrlKey?Sn(I):ln(I.path),children:[e.jsxs("strong",{children:[I.path,I.page?` · ${b("wikiPage",{page:I.page})}`:""]}),e.jsx("span",{children:I.snippet})]})]},`${I.path}:${I.line}:${me}`)),mt&&!Ft&&!Pt.length&&e.jsx("p",{children:b("wikiNoResults")}),nn&&e.jsx("p",{children:b("wikiSearchLimited")})]}),e.jsx("footer",{children:b("wikiSearchKeys")})]})}),ae&&e.jsx("div",{className:"wiki-modal-backdrop",children:e.jsxs("section",{className:"wiki-confirm",role:"dialog","aria-modal":"true","aria-label":b("wikiUnsaved"),children:[e.jsx("h2",{children:b("wikiUnsaved")}),e.jsx("p",{children:b("wikiUnsavedHint")}),e.jsxs("div",{children:[e.jsx("button",{disabled:hn,onClick:()=>Te(null),children:b("cancel")}),e.jsx("button",{disabled:hn,onClick:()=>{const I=ae;we((ne==null?void 0:ne.text)??""),Te(null),I()},children:b("wikiDiscard")}),e.jsx("button",{disabled:oe,onClick:()=>void(async()=>{if(await kn()){const I=ae;Te(null),I()}})(),children:b("wikiSaveContinue")})]})]})})]})}function Op({state:t,send:n}){var p,u;const s=et(),[r,i]=d.useState(""),[a,o]=d.useState(null);if(d.useEffect(()=>{i("")},[t==null?void 0:t.requestId,(p=t==null?void 0:t.prompt)==null?void 0:p.id]),d.useEffect(()=>{if(!t||a===t.requestId)return;const f=k=>{k.key==="Escape"&&(k.preventDefault(),t.phase==="pending"&&n({type:"cancel_provider_login",requestId:t.requestId}),o(t.requestId))};return window.addEventListener("keydown",f),()=>window.removeEventListener("keydown",f)},[t,a,n]),!t||a===t.requestId)return null;let c;try{const f=new URL(t.url??"");(f.protocol==="https:"||f.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(f.hostname))&&(c=f.href)}catch{}const l=()=>{t.phase==="pending"&&n({type:"cancel_provider_login",requestId:t.requestId}),o(t.requestId)};return e.jsx("div",{className:"modal-backdrop provider-auth-backdrop",children:e.jsxs("section",{className:"modal provider-auth-modal",role:"dialog","aria-modal":"true","aria-labelledby":"provider-auth-title",children:[e.jsxs("div",{className:"modal-head",children:[e.jsxs("h2",{id:"provider-auth-title",children:[s("providerLogin")," · ",t.provider]}),e.jsx("button",{className:"iconbtn",onClick:l,"aria-label":s("close"),children:"×"})]}),e.jsxs("div",{className:"modal-body",children:[e.jsx("p",{children:s(t.phase==="pending"?"providerAuthPending":t.phase==="success"?"providerAuthSuccess":t.phase==="cancelled"?"providerAuthCancelled":"providerAuthError")}),t.message&&e.jsx("p",{className:"provider-auth-message",children:t.message}),c&&e.jsx("a",{className:"btn",href:c,target:"_blank",rel:"noreferrer",children:s("providerAuthOpenBrowser")}),t.phase==="success"&&t.provider==="radius"&&e.jsx("button",{className:"btn",onClick:()=>window.dispatchEvent(new Event("pi-configure-radius")),children:s("mcpConfigureRadius")}),t.code&&e.jsxs("p",{children:[s("providerAuthDeviceCode")," ",e.jsx("code",{children:t.code})]}),t.prompt&&e.jsxs("form",{onSubmit:f=>{f.preventDefault(),t.prompt&&n({type:"provider_auth_response",requestId:t.requestId,promptId:t.prompt.id,value:r}),i("")},children:[e.jsxs("label",{children:[t.prompt.message,t.prompt.kind==="select"?e.jsxs("select",{value:r,onChange:f=>i(f.target.value),children:[e.jsx("option",{value:"",children:s("providerAuthChoose")}),(u=t.prompt.options)==null?void 0:u.map(f=>e.jsx("option",{value:f.id,children:f.label},f.id))]}):e.jsx("input",{autoFocus:!0,type:t.prompt.kind==="secret"?"password":"text",value:r,onChange:f=>i(f.target.value),placeholder:t.prompt.placeholder,autoComplete:"off"})]}),e.jsx("button",{type:"submit",className:"btn",disabled:!r,children:s("confirm")})]},t.prompt.id)]}),e.jsx("div",{className:"modal-actions",children:e.jsx("button",{className:"btn",onClick:l,children:s(t.phase==="pending"?"cancel":"close")})})]})})}const er=d.createContext("");let _p=-100;const Hp=[];function Bp(t,n,s,r,i){const a=d.useRef(0),[o,c]=d.useState(null);return d.useEffect(()=>{if(!n||!t)return;const l=()=>{document.visibilityState!=="hidden"&&(a.current=--_p,i({type:"scm_status",reqId:a.current}))};return l(),window.addEventListener("focus",l),document.addEventListener("visibilitychange",l),()=>{a.current=0,window.removeEventListener("focus",l),document.removeEventListener("visibilitychange",l)}},[t,n,s,i]),d.useEffect(()=>{(r==null?void 0:r.type)!=="scm_data"||r.kind!=="status"||r.reqId!==a.current||r.cwd!==t||c({cwd:t,files:r.ok?(r.files??[]).map(l=>({...l,path:l.path.replaceAll("\\","/")})):[],base:r.base??"",branch:r.branch??"",branches:r.branches??[],notRepo:!!r.notRepo})},[r,t]),(o==null?void 0:o.cwd)===t?o:{cwd:t,files:Hp,notRepo:!1,base:"",branch:"",branches:[]}}function Is({trigger:t,open:n,onOpenChange:s,children:r,align:i="right",fit:a=!1,direction:o="down",menuClassName:c}){const l=d.useRef(null);return d.useEffect(()=>{if(!n)return;const p=f=>{l.current&&!l.current.contains(f.target)&&s(!1)},u=f=>{f.key==="Escape"&&s(!1)};return document.addEventListener("mousedown",p),document.addEventListener("keydown",u),()=>{document.removeEventListener("mousedown",p),document.removeEventListener("keydown",u)}},[n,s]),e.jsxs("div",{className:`dropdown ${i} ${a?"fit":""} ${o==="up"?"dd-up":""}`,ref:l,children:[e.jsxs("button",{type:"button",className:"chip",onClick:()=>s(!n),"aria-expanded":n,children:[t,e.jsx(Qt,{className:`dd-caret ${n?"up":""}`})]}),n&&e.jsx("div",{className:`dd-menu ${c??""}`,children:r})]})}function Zn({active:t,disabled:n=!1,title:s,onClick:r,children:i}){return e.jsx("button",{type:"button",className:`dd-item ${t?"active":""}`,disabled:n,title:s,onClick:r,children:i})}const Up=["off","minimal","low","medium","high","xhigh","max"],Il=d.memo(function({state:n,models:s,modelsLoading:r,send:i,onManageModels:a,compact:o=!1,segmented:c=!1}){const l=et(),p=n==null?void 0:n.model,u=p?`${p.provider}/${p.id}`:null,[f,k]=d.useState(!1),[j,R]=d.useState(!1),[E,A]=d.useState("");d.useEffect(()=>{f||A("")},[f]);const N=d.useMemo(()=>{const W=E.trim().toLowerCase();return W?s.filter(ve=>ve.name.toLowerCase().includes(W)||ve.provider.toLowerCase().includes(W)||ve.id.toLowerCase().includes(W)):s},[s,E]),[T,y]=d.useState(!1),M=n!=null&&n.availableThinkingLevels&&n.availableThinkingLevels.length>0?new Set(n.availableThinkingLevels):null,b=Up.map(W=>({value:W,label:l(`thinking.${W}`),supported:M?M.has(W):!0})),F=[{label:l("thinking.minimal"),description:l("thinkingMinimalDescription"),values:["minimal","low","off"]},{label:l("thinkingStandard"),description:l("thinkingStandardDescription"),values:["medium"]},{label:l("thinkingDeep"),description:l("thinkingDeepDescription"),values:["high","xhigh","max"]}],U=F.find(W=>W.values.includes((n==null?void 0:n.thinkingLevel)??"off"))??F[0],ce=W=>{var ve;return((ve=b.find(Se=>Se.value===W))==null?void 0:ve.label)??W},ie=(n==null?void 0:n.runSettings)&&e.jsx("div",{className:"thinking-run-settings",children:["autoCompaction","autoRetry"].map(W=>e.jsxs("label",{children:[e.jsx("input",{type:"checkbox",checked:n.runSettings[W],onChange:ve=>i({type:"set_run_settings",conversationId:n.conversationId,[W]:ve.target.checked})}),l(W==="autoCompaction"?"conversationAutoCompaction":"conversationAutoRetry")]},W))});return d.useEffect(()=>{f&&s.length===0&&!T&&!r&&(y(!0),i({type:"list_models"}))},[f,s.length,T,r,i]),d.useEffect(()=>{s.length>0&&y(!1)},[s.length]),e.jsxs(e.Fragment,{children:[e.jsxs(Is,{trigger:e.jsxs(e.Fragment,{children:[e.jsx(Ei,{}),e.jsxs("span",{className:"chip-model",children:[p?p.name:l("selectModel"),(n==null?void 0:n.routedModel)&&e.jsxs("span",{className:"chip-routed-model",title:`${n.routedModel.provider}/${n.routedModel.id}${n.routedModel.thinkingLevel?` · ${n.routedModel.thinkingLevel}`:""}`,children:[" → ",n.routedModel.name]})]}),!o&&(p==null?void 0:p.vision)&&e.jsx("span",{className:"chip-vision",title:l("vision"),children:"🖼"}),!o&&p&&e.jsx("span",{className:"chip-sub",children:p.provider})]}),open:f,onOpenChange:k,menuClassName:"dd-menu-model",children:[e.jsx("div",{className:"dd-header",children:l("availableModels")}),e.jsxs("div",{className:"dd-search-row",children:[e.jsx(as,{}),e.jsx("input",{className:"dd-search",type:"text",placeholder:l("searchModels"),value:E,onChange:W=>A(W.target.value)})]}),e.jsxs("div",{className:"dd-model-scroll",children:[(T||r)&&e.jsx("div",{className:"dd-loading",children:l("loading")}),s.length===0&&!T&&!r&&e.jsx("div",{className:"dd-loading",children:l("noModels")}),N.length===0&&s.length>0&&e.jsx("div",{className:"dd-loading",children:l("noModelMatches")}),N.map(W=>e.jsx(Zn,{active:u===W.id,onClick:()=>{u!==W.id&&i({type:"set_model",modelId:W.id}),k(!1)},children:e.jsxs("span",{className:"dd-model-cell",children:[e.jsx("span",{className:"dd-model-name",children:W.name}),e.jsxs("span",{className:"dd-model-meta",children:[e.jsx("span",{className:"dd-model-provider",children:W.provider}),(W.reasoning||W.vision)&&e.jsxs("span",{className:"dd-model-badges",children:[W.reasoning&&e.jsx("span",{className:"dd-model-badge",children:l("reasoning")}),W.vision&&e.jsx("span",{className:"dd-model-badge",children:l("vision")})]})]})]})},W.id))]}),c&&e.jsxs("div",{className:"dd-thinking-levels",children:[e.jsx("span",{children:l("thinkingLevel")}),b.filter(W=>W.supported).map(W=>e.jsx("button",{type:"button","aria-pressed":(n==null?void 0:n.thinkingLevel)===W.value,onClick:()=>i({type:"set_thinking",level:W.value}),children:W.label},W.value))]}),e.jsxs("div",{className:"dd-footer",children:[e.jsx("button",{type:"button",className:"dd-refresh",onClick:()=>i({type:"list_models"}),children:l("refreshModels")}),e.jsx("button",{type:"button",className:"dd-refresh",onClick:()=>{k(!1),a()},children:l("manageModels")})]})]}),c?e.jsx("div",{className:"thinking-control",children:e.jsxs(Is,{trigger:e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"thinking-trigger-prefix",children:[l("thinking")," · "]}),e.jsx("span",{children:U.label})]}),open:j,onOpenChange:R,align:"left",menuClassName:"dd-menu-thinking",children:[e.jsx("div",{className:"dd-header",children:l("thinkingLevel")}),F.map(W=>{const ve=W.values.find(Se=>!M||M.has(Se));return e.jsx(Zn,{active:W===U,disabled:!ve,title:ve?void 0:l("thinkingUnsupported"),onClick:()=>{ve&&(n==null?void 0:n.thinkingLevel)!==ve&&i({type:"set_thinking",level:ve}),R(!1)},children:e.jsxs("span",{className:"thinking-mode-option",children:[e.jsx("strong",{children:W.label}),e.jsx("small",{children:W.description})]})},W.label)}),ie]})}):e.jsxs(Is,{trigger:e.jsxs(e.Fragment,{children:[e.jsx(Zc,{}),e.jsx("span",{className:"chip-sub",children:l("thinkingChip",{level:n?ce(n.thinkingLevel):"—"})})]}),open:j,onOpenChange:R,children:[e.jsx("div",{className:"dd-header",children:l("thinkingLevel")}),b.map(W=>e.jsx(Zn,{active:(n==null?void 0:n.thinkingLevel)===W.value,disabled:!W.supported,title:W.supported?void 0:l("thinkingUnsupported"),onClick:()=>{(n==null?void 0:n.thinkingLevel)!==W.value&&i({type:"set_thinking",level:W.value}),R(!1)},children:W.label},W.value)),ie]})]})}),Wp=[{kind:"question",labelKey:"sound.question",descKey:"sound.question.desc"},{kind:"done",labelKey:"sound.done",descKey:"sound.done.desc"},{kind:"start",labelKey:"sound.start",descKey:"sound.start.desc"},{kind:"error",labelKey:"sound.error",descKey:"sound.error.desc"}];function qp({settings:t,onChange:n,onPreview:s}){const r=et(),i=a=>n({...t,...a});return e.jsxs("details",{className:"sound-menu",children:[e.jsxs("summary",{className:"sound-menu-summary",children:[e.jsx(sa,{"aria-hidden":"true"}),e.jsx("span",{children:r("soundHeader")}),e.jsx(Qt,{className:"sound-menu-caret","aria-hidden":"true"})]}),e.jsxs("div",{className:"sound-menu-options",children:[e.jsxs("label",{className:"sound-row sound-master",children:[e.jsxs("span",{className:"sound-label",children:[e.jsx(sa,{className:"sound-icon"}),e.jsx("span",{children:r("enableSound")})]}),e.jsx("input",{type:"checkbox",checked:t.enabled,onChange:a=>i({enabled:a.target.checked})})]}),Wp.map(({kind:a,labelKey:o,descKey:c})=>e.jsxs("label",{className:`sound-row ${t.enabled?"":"disabled"}`,children:[e.jsxs("span",{className:"sound-label",children:[e.jsx("span",{className:"sound-name",children:r(o)}),e.jsx("span",{className:"sound-desc",children:r(c)})]}),e.jsxs("span",{className:"sound-right",children:[e.jsx("button",{type:"button",className:"sound-preview",title:r("preview"),disabled:!t.enabled,onClick:l=>{l.preventDefault(),s(a)},children:r("preview")}),e.jsx("input",{type:"checkbox",checked:t[a],disabled:!t.enabled,onChange:l=>i({[a]:l.target.checked})})]})]},a)),e.jsxs("div",{className:`sound-volume ${t.enabled?"":"disabled"}`,children:[e.jsx("span",{className:"sound-name",children:r("volume")}),e.jsx("input",{type:"range",min:0,max:100,step:5,value:t.volume,disabled:!t.enabled,onChange:a=>i({volume:Number(a.target.value)})}),e.jsxs("span",{className:"sound-vol-num",children:[t.volume,"%"]})]})]})]})}function br(t,n,s,r,i,a){if(s!=null&&s.trim())return s;const o=(n||t).trim();if(r>1&&/^(?:hi|hello|hey|你好|您好|嗨|哈喽)[\s!!??.。~~]*$/iu.test(o)){const c=a==null?void 0:a.filter(l=>l.role==="user").map(l=>l.content.filter(p=>p.type==="text").map(p=>p.type==="text"?p.text:"").join(" ").trim()).find(l=>l&&!/^(?:hi|hello|hey|你好|您好|嗨|哈喽)[\s!!??.。~~]*$/iu.test(l)&&!l.startsWith("【目标已设定】")&&!l.startsWith("✅ 目标已达成"));if(c)return Array.from(c).slice(0,24).join("")+(Array.from(c).length>24?"…":"");if(i==="zh")return"打招呼"}return t}function zp({leftCollapsed:t=!1,gitChangeCount:n,onOpenTask:s,chat:r,send:i,terminal:a,view:o,plugins:c,onViewChange:l,onOpenPanel:p,onManageModels:u,onOpenSettings:f,onOpenBgTasks:k,onOpenGlobalSearch:j,sound:R,onSoundChange:E,onSoundPreview:A}){var ge,pe,Ae,ae,Te,Z,Fe,z,G,J,Ee,V,Le,xe,be,nt;const{locale:N,setLocale:T,t:y}=ns(),M=Mr(),[b,F]=d.useState(!1),[U,ce]=d.useState(!1),[ie,W]=d.useState(null);d.useEffect(()=>{W(t?null:document.getElementById("sidebar-settings-slot")),o==="nodes"&&ce(!1)},[o,t]);const[ve,Se]=d.useState({maximized:!1,fullscreen:!1});d.useEffect(()=>kt==null?void 0:kt.onWindowState(Se),[]);const $=(pe=(ge=r.state)==null?void 0:ge.cwd)==null?void 0:pe.split(/[\\/]/).filter(Boolean).at(-1),$e=((Ae=r.gitBranch)==null?void 0:Ae.cwd)===((ae=r.state)==null?void 0:ae.cwd)&&!!((Te=r.gitBranch)!=null&&Te.notRepo),L=((Z=r.state)==null?void 0:Z.conversationId)===r.activeConversationId?Fs(r.state.streamingMessage?[...r.state.messages,r.state.streamingMessage]:r.state.messages,r.state.isStreaming).current:void 0,q=(L==null?void 0:L.state)==="stopped",fe=(L==null?void 0:L.state)==="reminding",je=((Fe=r.state)==null?void 0:Fe.conversationId)===r.activeConversationId?(z=r.state)==null?void 0:z.taskProgress:null,ne=(je==null?void 0:je.status)==="running"||(je==null?void 0:je.status)==="waiting"?((G=je.plan)==null?void 0:G.items.filter(Ce=>Ce.status!=="removed"))??[]:[],Pe=ne.findIndex(Ce=>Ce.status==="running"),B=r.sessions.find(Ce=>{var ye;return Ce.path===((ye=r.state)==null?void 0:ye.sessionFile)}),we=r.conversations.find(Ce=>Ce.id===r.activeConversationId),re=br((we==null?void 0:we.title)||fs((B==null?void 0:B.firstMessage)??"")||y("newChat"),B==null?void 0:B.firstMessage,B==null?void 0:B.name,Math.max((B==null?void 0:B.messageCount)??0,(we==null?void 0:we.messageCount)??0,((J=r.state)==null?void 0:J.messages.length)??0),N,(Ee=r.state)==null?void 0:Ee.messages),Ie=[{value:"zh",label:y("langZh")},{value:"en",label:y("langEn")}],_=r.ready?y("connected"):r.status==="closed"?y("reconnecting"):y("connecting"),le=r.ready?"ok":"busy",O=e.jsx("div",{className:"topbar-more",children:e.jsxs(Is,{trigger:e.jsxs(e.Fragment,{children:[e.jsx(qs,{"aria-hidden":"true"}),e.jsx("span",{className:"chip-sub",children:y("settings")})]}),open:U,onOpenChange:ce,menuClassName:"workspace-settings-menu",children:[e.jsxs(Zn,{onClick:()=>{ce(!1),f()},children:[e.jsx(qs,{"aria-hidden":"true"}),e.jsx("span",{className:"workspace-menu-label",children:y("allSettings")})]}),e.jsx("div",{className:"dd-header workspace-menu-section",children:y("quickActions")}),e.jsxs(Zn,{onClick:()=>{ce(!1),ya()},children:[e.jsx(hs,{"aria-hidden":"true"}),e.jsx("span",{className:"workspace-menu-label",children:y("treeTitle")})]}),e.jsxs(Zn,{onClick:()=>{ce(!1),j()},children:[e.jsx(as,{"aria-hidden":"true"}),e.jsx("span",{className:"workspace-menu-label",children:y("searchGlobal")})]}),e.jsxs(Zn,{onClick:()=>{ce(!1),k()},children:[e.jsx(Es,{"aria-hidden":"true"}),e.jsx("span",{className:"workspace-menu-label",children:y("bgTasks")}),r.bgServers.length>0&&e.jsx("em",{className:"bg-task-badge",children:r.bgServers.length})]}),e.jsx(qp,{settings:R,onChange:E,onPreview:A}),e.jsx("div",{className:"dd-header",children:y("language")}),Ie.map(Ce=>e.jsx(Zn,{active:N===Ce.value,onClick:()=>T(Ce.value),children:Ce.label},Ce.value))]})});return e.jsxs("header",{className:"topbar",children:[e.jsxs("div",{className:"brand",children:[e.jsx("button",{type:"button",className:"panel-toggle",title:y("openHistory"),onClick:()=>p("left"),children:e.jsx(To,{})}),e.jsx("img",{className:"brand-logo",src:"/icon/1a-mark.svg",alt:""}),e.jsx("span",{className:"brand-name",children:"pi-harness"}),kt&&e.jsxs("span",{className:"desktop-window-title",title:((V=r.state)==null?void 0:V.cwd)??"",children:["pi-harness ",e.jsx("span",{className:"desktop-title-separator",children:"/"})," ",$||y("desktopWorkspace")]}),e.jsx("span",{className:`conn-dot ${le}`,title:_}),e.jsx("span",{className:"conn-label",children:_})]}),o!=="nodes"&&e.jsx("button",{type:"button",className:"project-panel-toggle",title:y(t?"expandProjects":"collapseProjects"),"aria-label":y(t?"expandProjects":"collapseProjects"),"aria-expanded":!t,onClick:()=>p("left"),children:e.jsx(aa,{})}),e.jsx("div",{id:"wiki-toolbar-slot"}),e.jsxs("div",{className:"header-location",children:[e.jsx("span",{title:(Le=r.state)==null?void 0:Le.cwd,children:$||y("desktopWorkspace")}),e.jsx("i",{children:"/"}),e.jsxs("button",{className:"conversation-title-button",title:y("treeTitle"),onClick:()=>ya(),children:[e.jsx("strong",{title:re,children:re}),e.jsx("span",{"aria-hidden":"true",children:"⌄"})]}),o==="chat"&&((xe=r.gitBranch)==null?void 0:xe.branch)&&e.jsx("code",{className:"changes-current-branch",children:r.gitBranch.branch}),(q||fe||Pe>=0||!!((be=je==null?void 0:je.plan)!=null&&be.awaitingConfirmation))&&e.jsxs("button",{type:"button",className:`header-task-progress${q?" interrupted":fe?" reminding":""}`,title:y("taskProgress"),onClick:s,children:[e.jsx("span",{"aria-hidden":"true",children:"●"}),q?y("toolRecoveryInterrupted"):fe?y("working"):(nt=je==null?void 0:je.plan)!=null&&nt.awaitingConfirmation?y("taskProgress"):y("taskPlanPosition",{current:Pe+1,total:ne.length})]})]}),e.jsxs("div",{className:"topbar-actions",children:[o==="chat"&&M&&(M.files.length>0||n>0||M.open)&&e.jsxs("button",{className:"changes-toggle","aria-pressed":M.open,title:"⌘D",onClick:()=>M.set({open:!M.open}),children:[e.jsx(Es,{"aria-hidden":"true"}),y("changesTitle")," ",e.jsx(Ps,{files:M.files})]}),e.jsxs("div",{className:"view-switch",role:"tablist","aria-label":y("viewSwitch"),children:[e.jsxs("button",{type:"button",role:"tab","aria-label":y("chat"),title:y("chat"),"aria-selected":o==="chat",className:o==="chat"?"active":"",onClick:()=>l("chat"),children:[e.jsx(Eo,{}),e.jsx("span",{children:y("chat")})]}),o==="wiki"&&e.jsx("button",{type:"button",role:"tab","aria-selected":"true",className:"active wiki-view-tab",children:e.jsx("span",{children:"Wiki"})}),e.jsxs("button",{type:"button",role:"tab","aria-label":y("terminal"),title:y("terminal"),"aria-selected":o==="terminal",className:o==="terminal"?"active":"",onClick:()=>l("terminal"),children:[e.jsx(Ni,{}),e.jsx("span",{children:y("terminal")})]}),e.jsxs("button",{type:"button",role:"tab","aria-label":y("nodes"),title:y("nodes"),"aria-selected":o==="nodes",className:o==="nodes"?"active":"",onClick:()=>l("nodes"),children:[e.jsx(ca,{}),e.jsx("span",{children:y("nodes")})]}),e.jsxs("button",{type:"button",role:"tab","aria-label":y("scmTab"),title:y($e?"notGitRepoShort":"scmTab"),"aria-disabled":$e,className:o==="git"?"active":void 0,"aria-selected":o==="git",onClick:()=>{$e||l("git")},children:[e.jsx(hs,{}),e.jsx("span",{children:y("scmTab")}),!$e&&n>0&&e.jsx("em",{className:"tab-change-count",children:n})]}),e.jsxs("button",{type:"button",className:"workspace-jobs",onClick:k,title:y("bgTasksTip"),children:[e.jsx(Es,{}),e.jsx("span",{children:y("bgTasks")}),r.bgServers.length>0&&e.jsx("em",{className:"bg-task-badge",children:r.bgServers.length})]}),c.map(Ce=>{const ye=Ce.error?`${Ce.name}: ${Ce.error}`:Ce.description?`${Ce.name} — ${Ce.description}`:Ce.name;return e.jsxs("button",{type:"button",role:"tab","aria-selected":o===`plugin:${Ce.id}`,className:`plugin-tab${o===`plugin:${Ce.id}`?" active":""}${Ce.error?" broken":""}`,title:ye,onClick:()=>l(`plugin:${Ce.id}`),children:[Ce.icon?e.jsx("span",{"aria-hidden":!0,children:Ce.icon}):null,e.jsx("span",{children:Ce.name})]},Ce.id)})]}),e.jsxs("div",{className:"topbar-desktop",children:[e.jsxs("button",{type:"button",className:"chip bg-task-chip","data-tip":y("bgTasksTip"),onClick:k,children:[e.jsx(Es,{}),e.jsx("span",{className:"chip-sub",children:y("bgTasks")}),r.bgServers.length>0&&e.jsx("span",{className:"bg-task-badge",children:r.bgServers.length})]}),e.jsx(Il,{state:r.state?{conversationId:r.state.conversationId,runSettings:r.state.runSettings,model:r.state.model,routedModel:r.state.routedModel,thinkingLevel:r.state.thinkingLevel,availableThinkingLevels:r.state.availableThinkingLevels}:null,models:r.models,modelsLoading:r.modelsLoading,send:i,onManageModels:u}),e.jsxs("button",{type:"button",className:"chip",title:y("settingsTitle"),onClick:f,children:[e.jsx(qs,{}),e.jsx("span",{className:"chip-sub",children:y("settings")})]}),e.jsxs(Is,{trigger:e.jsxs(e.Fragment,{children:[e.jsx(ca,{}),e.jsx("span",{className:"chip-sub",children:N==="zh"?y("langZh"):"EN"})]}),open:b,onOpenChange:F,children:[e.jsx("div",{className:"dd-header",children:y("language")}),Ie.map(Ce=>e.jsx(Zn,{active:N===Ce.value,onClick:()=>{T(Ce.value),F(!1)},children:Ce.label},Ce.value))]})]}),e.jsxs("button",{type:"button",className:"chip newchat","data-tip":y("newChatTip"),onClick:()=>i({type:"new_chat"}),children:[e.jsx(ls,{}),e.jsx("span",{children:y("newChat")})]}),o!=="nodes"&&(ie?mn.createPortal(O,ie):O),e.jsx("button",{type:"button",className:"panel-toggle",title:y("openFiles"),onClick:()=>p("right"),children:e.jsx(aa,{})})]}),kt&&kt.platform!=="darwin"&&e.jsxs("div",{className:"desktop-window-controls","aria-label":y("windowControls"),children:[e.jsx("button",{type:"button",title:y("minimizeWindow"),"aria-label":y("minimizeWindow"),onClick:()=>kt==null?void 0:kt.windowAction("minimize"),children:e.jsx(ti,{})}),e.jsx("button",{type:"button",title:ve.maximized||ve.fullscreen?y("restoreWindow"):y("maximizeWindow"),"aria-label":ve.maximized||ve.fullscreen?y("restoreWindow"):y("maximizeWindow"),onClick:()=>kt==null?void 0:kt.windowAction("toggle-maximize"),children:ve.maximized||ve.fullscreen?e.jsx(ws,{}):e.jsx(ms,{})}),e.jsx("button",{type:"button",className:"desktop-window-close",title:y("closeWindow"),"aria-label":y("closeWindow"),onClick:()=>kt==null?void 0:kt.windowAction("close"),children:e.jsx(Wt,{})})]})]})}function Vp({dirBrowse:t,onBrowse:n,onPick:s,onClose:r}){const i=et(),[a,o]=d.useState("");d.useEffect(()=>{n(void 0)},[]),d.useEffect(()=>{const f=k=>{k.key==="Escape"&&r()};return window.addEventListener("keydown",f),()=>window.removeEventListener("keydown",f)},[r]);const c=(t==null?void 0:t.path)??"",l=c.includes("\\")&&!c.includes("/")?"\\":"/",p=f=>c.endsWith(l)?`${c}${f}`:`${c}${l}${f}`,u=(t==null?void 0:t.drives)??[];return e.jsx("div",{className:"modal-backdrop",onClick:r,children:e.jsxs("div",{className:"fpk-modal",role:"dialog","aria-modal":"true",onClick:f=>f.stopPropagation(),children:[e.jsxs("div",{className:"fpk-modal-head",children:[e.jsx(Ks,{className:"modal-head-icon"}),e.jsx("h2",{children:i("openFolder")}),e.jsx("span",{className:"toolcall-spacer"}),e.jsx("button",{type:"button",className:"toolcall-zoom-close",title:i("cancel"),onClick:r,children:e.jsx(Wt,{})})]}),e.jsxs("div",{className:"fpk-modal-bar",children:[e.jsx("button",{type:"button",className:"fpk-nav-btn",title:i("home"),onClick:()=>n(void 0),children:e.jsx(ld,{})}),e.jsx("button",{type:"button",className:"fpk-nav-btn",title:i("parentFolder"),disabled:!(t!=null&&t.parent),onClick:()=>(t==null?void 0:t.parent)&&n(t.parent),children:e.jsx(pd,{})}),e.jsx("code",{className:"fpk-path",title:c,children:c||"…"})]}),u.length>0&&e.jsx("div",{className:"fpk-drives",children:u.map(f=>e.jsxs("button",{type:"button",className:`fpk-drive ${c.toUpperCase().startsWith(f.toUpperCase())?"active":""}`,onClick:()=>n(f),children:[e.jsx(cd,{}),e.jsx("span",{children:f.replace(/\\$/,"")})]},f))}),e.jsxs("div",{className:"fpk-list",children:[t&&t.dirs.length===0&&e.jsx("div",{className:"panel-empty",children:i("noSubfolders")}),t==null?void 0:t.dirs.map(f=>e.jsxs("button",{type:"button",className:"fpk-item",onClick:()=>n(p(f)),children:[e.jsx(Ks,{className:"fpk-item-icon"}),e.jsx("span",{className:"fpk-item-name",children:f}),e.jsx(_t,{className:"fpk-item-go"})]},f)),(t==null?void 0:t.truncated)&&e.jsx("div",{className:"panel-empty",children:i("listTruncated")})]}),e.jsxs("form",{className:"fpk-modal-foot",onSubmit:f=>{f.preventDefault();const k=a.trim()||c;k&&s(k)},children:[e.jsx("input",{className:"lp-inline-input",placeholder:i("openFolderPlaceholder"),value:a,onChange:f=>o(f.target.value)}),e.jsxs("button",{type:"submit",className:"fpk-open-btn",disabled:!c&&!a.trim(),children:[e.jsx(ts,{}),e.jsx("span",{children:a.trim()?i("openTypedPath"):i("openThisFolder")})]})]})]})})}function Kr(t,n){const s=new Date(t),r=new Date;if(s.toDateString()===r.toDateString())return`${String(s.getHours()).padStart(2,"0")}:${String(s.getMinutes()).padStart(2,"0")}`;const a=new Date(r.getFullYear(),r.getMonth(),r.getDate()-1);return s.toDateString()===a.toDateString()?n:`${s.getMonth()+1}/${s.getDate()}`}const Kp=d.memo(function({incidentState:n,onOpenSettings:s,onNewChat:r,ready:i,status:a,cwd:o,sessionFile:c,conversations:l,sessions:p,projects:u,dirBrowse:f,activeConversationId:k,send:j,active:R}){const{t:E,locale:A}=ns(),N=c,T=o,[y,M]=d.useState(null),[b,F]=d.useState(null),[U,ce]=d.useState(""),[ie,W]=d.useState(null),[ve,Se]=d.useState(!1);d.useEffect(()=>Se(!1),[o]),d.useEffect(()=>{if(!ie)return;const _=O=>{const ge=O.target instanceof Element?O.target.closest(".lp-menu-zone"):null;(ge==null?void 0:ge.dataset.menuKey)!==ie&&W(null)},le=O=>{O.key==="Escape"&&W(null)};return document.addEventListener("pointerdown",_),document.addEventListener("keydown",le),()=>{document.removeEventListener("pointerdown",_),document.removeEventListener("keydown",le)}},[ie]);const[$,$e]=d.useState(!1),[L,q]=d.useState(null);d.useEffect(()=>{L&&o===L&&q(null)},[o,L]),d.useEffect(()=>{if(!L)return;const _=setTimeout(()=>q(null),15e3);return()=>clearTimeout(_)},[L]),d.useEffect(()=>{!R||!i||a!=="open"||o&&(j({type:"list_sessions"}),j({type:"list_projects"}))},[R,i,a,o,j]);const fe=_=>{var O;const le=_.name||((O=je.get(_.path))==null?void 0:O.title)||fs(_.firstMessage);return br(le.length>0?le:E("emptyChat"),_.firstMessage,_.name,_.messageCount,A)},je=new Map;for(const _ of l)_.sessionFile&&je.set(_.sessionFile,_);const ne=new Set(p.map(_=>_.path)),Pe=l.filter(_=>!_.sessionFile||!ne.has(_.sessionFile)),B=_=>{const le=_.replace(/\\/g,"/").replace(/\/$/,"")||"/";return le==="/"||/^[A-Za-z]:$/.test(le)?E("rootDir"):/^(?:\/Users\/[^/]+|\/home\/[^/]+|[A-Za-z]:\/Users\/[^/]+)$/.test(le)?"~":le.split("/").at(-1)||le},we=_=>Math.max(_.lastUsed,_.lastConversationAt??0,_.path===T&&p.length?Math.max(...p.map(le=>le.modified)):0),re=[...u].sort((_,le)=>+(le.path===T)-+(_.path===T)||we(le)-we(_)||_.path.localeCompare(le.path)),Ie=e.jsxs("div",{className:"panel-sessions",children:[e.jsx("div",{className:"panel-section-title",children:E("historySessions")}),e.jsxs("div",{className:"sessions-scroll",children:[p.length===0&&Pe.length===0&&e.jsx("div",{className:"panel-empty",children:E("noHistory")}),Pe.map(_=>{var O;const le=k===_.id;return e.jsxs("button",{type:"button",className:`session-item ${le?"active":""}`,title:`${_.title}
201
+ ${le?E("current"):E("messageCount",{n:_.messageCount})}`,onClick:()=>{le||j({type:"switch_conversation",id:_.id})},children:[e.jsx("span",{className:`session-dot${_.id===k&&n==="stopped"?" interrupted":_.id===k&&n==="reminding"||_.isStreaming?" streaming":""}`,title:_.isStreaming?E("streaming"):void 0}),e.jsxs("span",{className:"session-info",children:[e.jsx("span",{className:"session-title",children:br(_.title,void 0,void 0,_.messageCount,A)}),!!_.branchPoints&&e.jsx("small",{children:E("treeBranches",{n:_.branchPoints})}),_.parentSessionPath&&e.jsx("small",{title:_.parentSessionPath,children:E("treeDerived",{name:((O=p.find(ge=>ge.path===_.parentSessionPath))==null?void 0:O.name)||_.parentSessionPath.split(/[\\/]/).pop()||""})})]}),e.jsx("span",{className:"session-time",children:Kr(_.createdAt??Date.now(),E("yesterday"))})]},_.id)}),p.map(_=>{var ge;const le=je.get(_.path),O=le?k===le.id:N===_.path;return b===_.path?e.jsxs("form",{className:"lp-inline-form",onSubmit:pe=>{pe.preventDefault(),j({type:"rename_session",path:_.path,name:U.trim()}),F(null)},children:[e.jsx("input",{autoFocus:!0,className:"lp-inline-input",placeholder:E("renameSessionPlaceholder"),value:U,onChange:pe=>ce(pe.target.value),onKeyDown:pe=>{pe.key==="Escape"&&F(null)}}),e.jsx("button",{type:"submit",className:"lp-inline-ok",title:E("confirm"),children:e.jsx(ts,{})}),e.jsx("button",{type:"button",className:"lp-inline-cancel",title:E("cancel"),onClick:()=>F(null),children:e.jsx(Wt,{})})]},_.path):e.jsxs("div",{className:"lp-row",onMouseLeave:()=>M(pe=>pe===`sess:${_.path}`?null:pe),children:[e.jsxs("button",{type:"button",className:`session-item ${O?"active":""}`,title:`${_.path}
202
+ ${O?E("current"):E("messageCount",{n:_.messageCount})}`,onClick:()=>{O||j(le?{type:"switch_conversation",id:le.id}:{type:"switch_session",path:_.path})},children:[e.jsx("span",{className:`session-dot${(le==null?void 0:le.id)===k&&n==="stopped"?" interrupted":(le==null?void 0:le.id)===k&&n==="reminding"||le!=null&&le.isStreaming?" streaming":""}`,title:le!=null&&le.isStreaming?E("streaming"):void 0}),e.jsxs("span",{className:"session-info",children:[e.jsx("span",{className:"session-title",children:fe(_)}),!!((le==null?void 0:le.branchPoints)??_.branchPoints)&&e.jsx("small",{children:E("treeBranches",{n:(le==null?void 0:le.branchPoints)??_.branchPoints??0})}),_.parentSessionPath&&e.jsx("small",{title:_.parentSessionPath,children:E("treeDerived",{name:((ge=p.find(pe=>pe.path===_.parentSessionPath))==null?void 0:ge.name)||_.parentSessionPath.split(/[\\/]/).pop()||""})})]}),_.source==="tui"&&e.jsx("span",{className:"session-src",title:E("tuiTip"),children:"TUI"}),e.jsx("span",{className:"session-time",children:Kr(_.modified,E("yesterday"))})]}),e.jsxs("div",{className:`lp-menu-zone${ie===`sess:${_.path}`?" is-open":""}`,"data-menu-key":`sess:${_.path}`,children:[e.jsx("button",{type:"button",className:"lp-menu-trigger","aria-label":`${fe(_)} · ${E("more")}`,"aria-haspopup":"menu","aria-expanded":ie===`sess:${_.path}`,onClick:()=>W(pe=>pe===`sess:${_.path}`?null:`sess:${_.path}`),children:e.jsx(Ms,{})}),ie===`sess:${_.path}`&&e.jsxs("div",{className:"lp-menu-popover",role:"menu",children:[e.jsx("button",{type:"button",role:"menuitem",onClick:()=>{ce(_.name??fe(_)),F(_.path),W(null)},children:E("renameSession")}),e.jsx("button",{type:"button",role:"menuitem",className:y===`sess:${_.path}`?"danger":"",onClick:()=>{y===`sess:${_.path}`?(j({type:"delete_session",path:_.path}),M(null),W(null)):M(`sess:${_.path}`)},children:y===`sess:${_.path}`?E("deleteSessionConfirm"):E("deleteSession")})]})]})]},_.path)})]})]});return e.jsxs("aside",{className:"panel panel-left",children:[e.jsxs("div",{className:"sidebar-brand",children:[e.jsx("span",{className:"sidebar-logo",children:e.jsx("img",{src:"/icon/1a-mark.svg",alt:""})}),e.jsx("strong",{children:"pi-harness"})]}),e.jsx("div",{className:"sidebar-new",children:e.jsxs("button",{type:"button",onClick:r,children:[e.jsxs("span",{children:[e.jsx(ls,{}),E("newChat")]}),e.jsxs("kbd",{children:[navigator.platform.includes("Mac")?"⌘":"Ctrl+","N"]})]})}),e.jsxs("div",{className:"panel-projects",children:[e.jsxs("div",{className:"panel-section-title",children:[e.jsx("span",{children:E("workspaceProjects")}),e.jsx("button",{type:"button",className:"lp-add-project",title:E("openFolder"),"aria-label":E("openFolder"),onClick:()=>$e(!0),children:e.jsx(ls,{})})]}),e.jsx("div",{className:"projects-scroll",children:re.map(_=>{const le=T===_.path,O=!le&&L===_.path,ge=le&&!ve,pe=le?Math.max(_.conversationCount??0,p.length+Pe.length):_.conversationCount??0;return e.jsxs("div",{className:"lp-row",onMouseLeave:()=>M(Ae=>Ae===`proj:${_.path}`?null:Ae),children:[e.jsxs("button",{type:"button",className:`project-item ${le?"active":""} ${O?"pending":""}`,title:_.path,onClick:()=>{le?Se(Ae=>!Ae):(Se(!1),q(_.path),j({type:"set_cwd",path:_.path,source:"ui"}))},children:[ge?e.jsx(Qt,{className:"project-chevron"}):e.jsx(_t,{className:"project-chevron"}),e.jsxs("span",{className:"project-info",children:[e.jsx("span",{className:"project-name",children:B(_.path)}),e.jsxs("span",{className:"project-count",children:["· ",pe]})]}),O?e.jsx("span",{className:"thinking-spinner project-spinner","aria-hidden":"true"}):e.jsx("span",{className:"project-time",children:Kr(we(_),E("yesterday"))})]}),e.jsxs("div",{className:`lp-menu-zone${ie===`proj:${_.path}`?" is-open":""}`,"data-menu-key":`proj:${_.path}`,children:[e.jsx("button",{type:"button",className:"lp-menu-trigger","aria-label":`${B(_.path)} · ${E("more")}`,"aria-haspopup":"menu","aria-expanded":ie===`proj:${_.path}`,onClick:()=>W(Ae=>Ae===`proj:${_.path}`?null:`proj:${_.path}`),children:e.jsx(Ms,{})}),ie===`proj:${_.path}`&&e.jsx("div",{className:"lp-menu-popover",role:"menu",children:e.jsx("button",{type:"button",role:"menuitem",className:y===`proj:${_.path}`?"danger":"",onClick:()=>{y===`proj:${_.path}`?(j({type:"remove_project",path:_.path}),M(null),W(null)):M(`proj:${_.path}`)},children:y===`proj:${_.path}`?E("deleteProjectConfirm"):E("deleteProject")})})]}),ge&&Ie]},_.path)})})]}),!u.some(_=>_.path===T)&&Ie,e.jsxs("div",{className:"sidebar-footer",children:[e.jsxs("span",{className:"sidebar-connection",children:[e.jsx("i",{className:i?"ok":"busy"}),E(i?"connected":"connecting")]}),e.jsx("span",{id:"sidebar-settings-slot",children:e.jsxs("button",{type:"button",onClick:s,children:[e.jsx(qs,{"aria-hidden":"true"})," ",E("settings")]})})]}),$&&e.jsx(Vp,{dirBrowse:f,onBrowse:_=>j({type:"browse_dirs",path:_}),onPick:_=>{q(_),j({type:"set_cwd",path:_,source:"ui"}),$e(!1)},onClose:()=>$e(!1)})]})}),Gp=200*1024*1024,Jp=/windows/i.test(navigator.userAgent),Qp=/[<>:"/\\|?*\u0000-\u001f]/g,Yp=/[. ]+$/,Xp=/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\..*)?$/i;function Zp(t){const n=t.replace(Qp,"_").replace(Yp,"");return n?Xp.test(n)?`_${n}`:n:"_"}function qa(t,n=!0){const s=new URLSearchParams({clientId:fn(),path:t,...n?{download:"1"}:{}});return Tn(`/api/file?${s}`)}async function Ll(t,n){const s=Jp?Zp(n):n;try{const r=await fetch(qa(t));if(!r.ok)return{ok:!1,cancelled:!1,error:await r.text().catch(()=>"")||(r.status===404?"文件不存在":`HTTP ${r.status}`)};if(Number(r.headers.get("content-length")??"0")>Gp)return window.location.assign(qa(t)),{ok:!0};const a=await r.blob();return window.showSaveFilePicker&&window.isSecureContext?eh(a,s):mi(a,s)}catch(r){return{ok:!1,cancelled:!1,error:r instanceof Error?r.message:String(r)}}}async function eh(t,n){let s;const r=window.showSaveFilePicker;if(!r)return mi(t,n);try{s=await r({suggestedName:n})}catch(i){return i instanceof DOMException&&i.name==="AbortError"?{ok:!1,cancelled:!0}:mi(t,n)}try{const i=await s.createWritable();return await i.write(t),await i.close(),{ok:!0}}catch(i){return{ok:!1,cancelled:!1,error:i instanceof Error?i.message:String(i)}}}function mi(t,n){const s=URL.createObjectURL(t),r=document.createElement("a");return r.href=s,r.download=n,document.body.appendChild(r),r.click(),r.remove(),setTimeout(()=>URL.revokeObjectURL(s),1e4),{ok:!0}}function th(t){const n=new Set;for(const s of t)for(const r of s.content){if(r.type!=="toolCall"||r.name!=="bash"||typeof r.argumentsText!="string")continue;let i;try{i=JSON.parse(r.argumentsText??"{}").command??""}catch{continue}for(const a of i.matchAll(/(?:^|[\s'"=/])(\.[A-Za-z][\w.-]*)(?=\/|[\s'";&|]|$)/g))n.add(a[1])}return n}function nh(t,n){var i;const s=n.toolCallIds?new Set(n.toolCallIds):null,r=(i=t.plan)==null?void 0:i.items.filter(a=>a.startedAt&&a.startedAt>(n.startedAt??1/0)).map(a=>a.startedAt).sort((a,o)=>a-o)[0];return t.steps.flatMap(a=>a.artifacts.filter(o=>s?s.has(o.toolCallId):!!n.startedAt&&a.startedAt>=n.startedAt&&a.startedAt<(n.endedAt??r??1/0)).map(o=>({messageId:a.messageId,artifact:o})))}function sh({task:t,silence:n,cwd:s,messages:r,onPreview:i,streaming:a,live:o}){var Se,$,$e;const c=et(),l=Fs(o?[...r,o]:r,a??(t==null?void 0:t.status)==="running").current,p=(l==null?void 0:l.state)==="stopped",u=(l==null?void 0:l.state)==="reminding",[f,k]=d.useState(0);d.useEffect(()=>{var je;if(!u)return;const L=((je=l==null?void 0:l.reminders.at(-1))==null?void 0:je.timestamp)??Date.now(),q=()=>k(Math.max(0,Math.floor((Date.now()-L)/1e3)));q();const fe=window.setInterval(q,1e3);return()=>window.clearInterval(fe)},[u,l==null?void 0:l.incidentId]);const j=sl(r,new Map),[R,E]=d.useState(!0),[A,N]=d.useState(!0),[T,y]=d.useState(null),M=d.useRef(null),b=((Se=t==null?void 0:t.plan)==null?void 0:Se.items.filter(L=>L.status!=="removed"))??[],F=($=b.find(L=>L.status==="running"))==null?void 0:$.id;d.useEffect(()=>{if(!R||!F)return;const L=M.current,q=L==null?void 0:L.querySelector(".task-plan-step.running");if(!L||!q)return;const fe=q.getBoundingClientRect().top-L.getBoundingClientRect().top+L.scrollTop;L.scrollTop=Math.max(0,fe-L.clientHeight/3)},[F,t==null?void 0:t.id,R]);const U=L=>{const q=L.startsWith(`${s}/`)?L.slice(s.length+1):L;i(q,q.replace(/\\/g,"/").split("/").at(-1)??q)},ce=jo(t,r,s),ie=r.find(L=>{var q,fe;return L.role==="toolResult"&&((q=L.planSnapshot)==null?void 0:q.planId)===((fe=t==null?void 0:t.plan)==null?void 0:fe.origin)}),W=ie&&r.find(L=>L.role==="assistant"&&L.content.some(q=>q.type==="toolCall"&&q.id===ie.toolCallId)),ve=p?c("toolRecoveryInterrupted"):u?`${c("working")} · ${c("waitSeconds",{n:f})}`:(t==null?void 0:t.status)==="failed"?c("taskFailed"):(t==null?void 0:t.status)==="cancelled"?c("taskCancelled"):($e=t==null?void 0:t.plan)!=null&&$e.awaitingConfirmation?c("planPrevious"):(t==null?void 0:t.status)==="waiting"?c("taskPaused"):n&&t&&n.conversationId===t.conversationId?c((j==null?void 0:j.label)??"working"):"";return e.jsx("div",{className:`task-progress task-sections ${p?"interrupted":u?"reminding":(t==null?void 0:t.status)??"empty"}`,tabIndex:-1,"aria-label":c("taskProgress"),children:e.jsxs("div",{className:"task-sections-scroll",ref:M,children:[e.jsxs("section",{className:"task-section",children:[e.jsxs("button",{type:"button",className:"task-section-heading","aria-expanded":R,onClick:()=>E(L=>!L),children:[e.jsx(_t,{className:R?"open":""}),c("taskProgressHeading")]}),R&&e.jsxs("div",{className:"task-section-content",children:[ve&&(!p||!!(t!=null&&t.plan))&&e.jsxs("p",{className:`task-progress-status task-progress-source ${p?"interrupted":u?"reminding":t==null?void 0:t.status}`,role:"status",children:[u&&e.jsx("i",{"aria-hidden":"true"}),ve]}),t!=null&&t.plan&&b.length?e.jsxs(e.Fragment,{children:[t.plan.completionCriteria&&e.jsxs("p",{className:"task-outline-criteria",children:[c("taskCompletionCriteria"),":",t.plan.completionCriteria]}),e.jsx("div",{className:"task-plan-list",children:b.map(L=>{var q;return e.jsxs("div",{className:`task-plan-step ${p&&L.status==="running"?"interrupted":L.status}${T===L.id?" expanded":""}`,children:[e.jsxs("button",{type:"button",className:"task-plan-step-head","aria-expanded":T===L.id,onClick:()=>y(fe=>fe===L.id?null:L.id),children:[e.jsx("span",{className:"task-plan-mark","aria-hidden":"true",children:p&&L.status==="running"?"×":L.status==="done"?"✓":L.status==="running"?"●":""}),e.jsx("span",{className:"task-plan-step-title",children:L.title}),e.jsx(_t,{className:T===L.id?"open":""})]}),T===L.id&&e.jsxs("div",{className:"task-plan-step-detail",children:[L.detail&&e.jsx("p",{children:L.detail}),!!((q=L.blockedBy)!=null&&q.length)&&e.jsx("p",{children:c("taskBlockedBy",{steps:L.blockedBy.join(", ")})}),nh(t,L).map(({artifact:fe,messageId:je})=>e.jsxs("div",{className:"task-artifact-row",children:[fe.path&&e.jsx("button",{type:"button",title:fe.path,onClick:()=>U(fe.path),children:fe.path}),e.jsx("button",{type:"button",title:c("taskJumpToChat"),onClick:()=>window.dispatchEvent(new CustomEvent("pi:jump-tool",{detail:{messageId:je,toolCallId:fe.toolCallId}})),children:fe.path?"↗":fe.label})]},fe.toolCallId)),e.jsxs("button",{type:"button",className:"task-step-jump",onClick:()=>window.dispatchEvent(new CustomEvent("pi:jump-message",{detail:{messageId:(W==null?void 0:W.id)??t.sourceMessageId}})),children:[c("taskJumpToChat")," →"]})]})]},L.id)})})]}):p?e.jsxs("div",{className:"task-interrupted-hint",children:[e.jsxs("strong",{children:["● ",c("taskInterruptedTitle")]}),e.jsx("p",{children:c("taskInterruptedHint")})]}):u?null:e.jsxs("div",{className:"task-section-empty",children:[e.jsxs("div",{className:"task-empty-circles","aria-hidden":"true",children:[e.jsx("i",{}),e.jsx("i",{}),e.jsx("i",{})]}),e.jsx("p",{children:c("taskProgressEmpty")})]})]})]}),e.jsxs("section",{className:"task-section",children:[e.jsxs("button",{type:"button",className:"task-section-heading","aria-expanded":A,onClick:()=>N(L=>!L),children:[e.jsx(_t,{className:A?"open":""}),c("taskOutputsHeading")]}),A&&e.jsx("div",{className:"task-section-content",children:ce.length?e.jsx("div",{className:"task-file-results",children:ce.map(L=>e.jsxs("div",{className:"task-file-result",children:[e.jsx(Gs,{"aria-hidden":"true"}),e.jsxs("button",{type:"button",title:L.path,onClick:()=>U(L.path),children:[e.jsx("span",{children:L.path.split("/").at(-1)}),L.path.includes("/")&&e.jsx("small",{children:L.path})]}),L.counted&&e.jsxs("span",{className:"task-file-counts",children:[e.jsxs("span",{children:["+",L.added]})," ",e.jsxs("span",{children:["−",L.removed]})]})]},L.path))}):e.jsxs("div",{className:"task-section-empty",children:[e.jsx(Gs,{className:"task-empty-file","aria-hidden":"true"}),e.jsx("p",{children:c("taskOutputsEmpty")})]})})]})]})})}const rh=d.memo(function({active:n,files:s,fileChanged:r,changed:i,notRepo:a,widgets:o,messages:c,streamingMessage:l,isStreaming:p,taskProgress:u,conversationId:f,agentSilence:k,cwd:j,send:R,onAttach:E,onPreview:A,onNotice:N}){const T=et(),[y,M]=d.useState(!1);d.useEffect(()=>M(!1),[j,f,n]);const[b,F]=d.useState(null),[U,ce]=d.useState({}),[ie,W]=d.useState(new Set),[ve,Se]=d.useState(!1),[$,$e]=d.useState(!1);d.useEffect(()=>$e(!1),[j,u==null?void 0:u.id]);const L=(u==null?void 0:u.status)==="running"&&!a&&i.length>0&&!$,[q,fe]=d.useState(!0),[je,ne]=d.useState(!1),Pe=d.useRef(null);d.useEffect(()=>{if(!je)return;const G=Ee=>{var V;(V=Pe.current)!=null&&V.contains(Ee.target)||ne(!1)},J=Ee=>{Ee.key==="Escape"&&ne(!1)};return document.addEventListener("pointerdown",G,!0),document.addEventListener("keydown",J),()=>{document.removeEventListener("pointerdown",G,!0),document.removeEventListener("keydown",J)}},[je]);const B=l?[...c,l]:c,we=th(B),re=d.useRef(j),Ie=d.useRef(null),_=d.useRef([]),le=d.useRef(null),O=d.useRef(ie);O.current=ie;const ge=d.useCallback(()=>{if(!n||le.current!==null)return;const G=_.current.shift();G!==void 0&&(le.current=G,R({type:"list_files",path:G||void 0})||(le.current=null))},[n,R]),pe=d.useCallback(G=>{le.current!==G&&!_.current.includes(G)&&_.current.push(G),ge()},[ge]);d.useEffect(()=>{if(re.current!==j&&(re.current=j,Ie.current=s,_.current=[],le.current=null,ce({}),W(new Set),Se(!1)),!n||!j)return;pe("");const G=setInterval(()=>{if(document.visibilityState!=="hidden"){le.current=null,pe("");for(const J of O.current)pe(J)}},1e4);return()=>clearInterval(G)},[n,j,pe]),d.useEffect(()=>{!s||s===Ie.current||re.current!==j||(Ie.current=s,ce(G=>({...G,[s.path]:s})),le.current===s.path&&(le.current=null),ge())},[s,j,ge]),d.useEffect(()=>{n&&r&&pe(r.path)},[n,r,pe]),d.useEffect(()=>{(a||!i.length)&&Se(!1)},[a,i]);const Ae=()=>{le.current=null,pe("");for(const G of O.current)pe(G)},ae=G=>{W(J=>{const Ee=new Set(J);return Ee.has(G)?Ee.delete(G):Ee.add(G),Ee}),ie.has(G)||pe(G)},Te=G=>{var V;const J=(((V=U[G])==null?void 0:V.entries)??[]).map(Le=>({entry:Le,virtual:!1})),Ee=new Set(J.map(({entry:Le})=>Le.name));for(const Le of i){if(Le.x!=="D"&&Le.y!=="D")continue;const xe=G?Le.path.startsWith(`${G}/`)?Le.path.slice(G.length+1):"":Le.path;if(!xe)continue;const be=xe.split("/")[0];Ee.has(be)||(Ee.add(be),J.push({entry:{name:be,path:G?`${G}/${be}`:be,type:xe.includes("/")?"dir":"file"},virtual:!0}))}return J.sort((Le,xe)=>Le.entry.type===xe.entry.type?Le.entry.name.localeCompare(xe.entry.name):Le.entry.type==="dir"?-1:1)},Z=(G,J,Ee)=>{const V=G.type==="dir",Le=ie.has(G.path),xe=i.filter(ye=>ye.path===G.path||V&&ye.path.startsWith(`${G.path}/`)).length,be=V?void 0:i.find(ye=>ye.path===G.path),nt=be?be.x==="D"||be.y==="D"?"D":be.x==="A"||be.y==="A"||be.x==="?"?"A":"M":null;if(L&&J===0&&V&&xe===0)return null;const Ce=V&&G.name.startsWith(".")&&we.has(G.name);return(!q&&G.name.startsWith(".")||ve&&!xe)&&!Ce?null:e.jsxs("div",{role:"treeitem","aria-expanded":V?Le:void 0,children:[e.jsxs("div",{className:`file-item ${V?"dir":"file"}`,style:{paddingLeft:6+J*16},children:[e.jsxs("button",{type:"button","data-tree-node":G.path,className:V?"file-dir-main":"file-name",title:G.path,disabled:Ee&&!V,onClick:()=>V?Ee?W(ye=>{const ze=new Set(ye);return ze.has(G.path)?ze.delete(G.path):ze.add(G.path),ze}):ae(G.path):A(G.path,G.name),children:[e.jsx("span",{className:`tree-caret ${Le?"open":""}`,children:V&&e.jsx(_t,{})}),e.jsx("span",{className:V?"file-name":"file-name-text",children:G.name})]}),V&&xe>0&&e.jsx("span",{className:"tree-modified-count",title:T("workspaceChanges",{n:xe}),children:xe}),nt&&e.jsx("span",{className:`tree-change-badge ${nt.toLowerCase()}`,title:nt==="A"?"Added":nt==="D"?"Deleted":"Modified",children:nt}),!V&&!Ee&&e.jsx("button",{type:"button",className:"file-attach download",title:T("downloadFile"),onClick:()=>void Ll(G.path,G.name).then(ye=>{!ye.ok&&!ye.cancelled&&N("error",T("downloadFailed",{error:ye.error}))}),children:e.jsx(Pr,{})}),!V&&!Ee&&e.jsx("button",{type:"button",className:"file-attach inline",title:T("attachInlineTip"),onClick:()=>E(G.path,G.name,"inline"),children:e.jsx(ls,{})}),!Ee&&e.jsx("button",{type:"button",className:"file-attach ref",title:T(V?"linkFolderTip":"referenceTip"),onClick:()=>E(G.path,G.name,"reference",V),children:e.jsx(hr,{})})]}),V&&Le&&e.jsx("div",{role:"group",children:U[G.path]||Ee?Fe(G.path,J+1):e.jsx("div",{className:"tree-loading",children:T("loading")})})]},G.path)},Fe=(G,J)=>{var Ee,V,Le,xe,be,nt;return e.jsxs(e.Fragment,{children:[(Ee=U[G])!=null&&Ee.error?e.jsxs("div",{className:"tree-directory-error",role:"status",title:(V=U[G].error)==null?void 0:V.message,children:[e.jsx("span",{children:T(((Le=U[G].error)==null?void 0:Le.code)==="missing"?"directoryMissing":((xe=U[G].error)==null?void 0:xe.code)==="denied"?"directoryDenied":((be=U[G].error)==null?void 0:be.code)==="not_directory"?"directoryNotFolder":"directoryUnavailable")}),!G&&e.jsx("span",{children:T("directoryChooseProject")}),e.jsx("button",{type:"button",onClick:()=>pe(G),children:T("refreshWorkspaceFiles")})]}):Te(G).map(({entry:Ce,virtual:ye})=>Z(Ce,J,ye)),((nt=U[G])==null?void 0:nt.truncated)&&e.jsx("div",{className:"panel-empty files-truncated",children:T("filesTruncated")})]})},z=Te("").filter(({entry:G})=>G.type==="dir"&&!i.some(J=>J.path===G.path||J.path.startsWith(`${G.path}/`))&&(q||!G.name.startsWith("."))).length;return e.jsxs("aside",{className:"panel panel-right has-task-progress",children:[e.jsxs("div",{className:"panel-title",children:[e.jsx("span",{children:T("workspaceFiles")}),!a&&i.length>0&&e.jsx("button",{type:"button",className:"tree-filter","aria-pressed":ve,onClick:()=>Se(G=>!G),children:T("changedCount",{n:i.length})}),e.jsx("button",{type:"button",className:"tree-menu-trigger","aria-label":T("newWorkspaceFile"),title:T("newWorkspaceFile"),disabled:p||!j,onClick:()=>M(G=>!G),children:e.jsx(ls,{})}),e.jsx("button",{type:"button",className:"tree-menu-trigger","aria-label":T("refreshWorkspaceFiles"),title:T("refreshWorkspaceFiles"),onClick:Ae,children:e.jsx(ys,{})}),e.jsxs("div",{className:"tree-controls",ref:Pe,children:[e.jsx("button",{type:"button",className:"tree-menu-trigger","aria-label":T("more"),"aria-expanded":je,onClick:()=>ne(G=>!G),children:e.jsx(Ms,{})}),je&&e.jsx("div",{className:"tree-controls-menu",children:e.jsxs("button",{type:"button",className:"tree-hidden-toggle",role:"switch","aria-checked":q,onClick:()=>fe(G=>!G),children:[e.jsx("span",{children:T("showHiddenFiles")}),e.jsx("span",{className:"tree-switch-track"})]})})]})]}),y&&e.jsx(Zo,{cwd:j,conversationId:f,disabled:p,onCancel:()=>M(!1),onCreated:G=>{M(!1),Ae(),A(G,G.split("/").at(-1))}},`${j}:${f}`),e.jsxs("div",{className:"panel-body",role:"tree","aria-label":T("workspaceFiles"),onKeyDown:G=>{var Le,xe;const J=G.target.closest("button[data-tree-node]");if(!J)return;const Ee=J.dataset.treeNode,V=J.classList.contains("file-dir-main");if(G.key==="ArrowRight"&&V&&!ie.has(Ee)&&(G.preventDefault(),ae(Ee)),G.key==="ArrowLeft")if(G.preventDefault(),V&&ie.has(Ee))ae(Ee);else{const be=Ee.slice(0,Ee.lastIndexOf("/"));(Le=Array.from(G.currentTarget.querySelectorAll("button[data-tree-node]")).find(nt=>nt.dataset.treeNode===be))==null||Le.focus()}if(G.key==="ArrowDown"||G.key==="ArrowUp"){G.preventDefault();const be=Array.from(G.currentTarget.querySelectorAll("button[data-tree-node]"));(xe=be[be.indexOf(J)+(G.key==="ArrowDown"?1:-1)])==null||xe.focus()}},children:[ve&&i.length===0?e.jsx("div",{className:"panel-empty",children:T("noChangedFiles")}):U[""]?Fe("",0):e.jsx("div",{className:"panel-empty",children:T("loading")}),L&&!ve&&z>0&&e.jsx("button",{type:"button",className:"tree-other-directories",onClick:()=>$e(!0),children:T("otherDirectories",{n:z})})]}),e.jsx("div",{className:"panel-lower",children:e.jsx(sh,{task:u,streaming:p,live:l,silence:k??null,cwd:j,messages:c,onPreview:A},f)}),o.filter(G=>G.lines.length>0).length>0&&e.jsx("div",{className:"panel-widgets",children:o.filter(G=>G.lines.length>0).map(G=>e.jsxs("div",{className:"widget",children:[e.jsxs("button",{type:"button",className:"widget-title widget-title-btn",title:T("widgetExpand"),onClick:()=>F(G.key),children:[e.jsx("span",{children:G.key}),e.jsx(Ro,{})]}),e.jsx("pre",{className:"widget-lines",children:G.lines.join(`
203
+ `)})]},G.key))}),b&&(()=>{const G=o.find(J=>J.key===b);return G?e.jsx("div",{className:"modal-backdrop",onClick:()=>F(null),children:e.jsxs("div",{className:"widget-expand",onClick:J=>J.stopPropagation(),children:[e.jsxs("div",{className:"widget-expand-head",children:[e.jsx("span",{className:"widget-expand-title",children:G.key}),e.jsx("button",{type:"button",className:"btn",title:T("close"),onClick:()=>F(null),children:e.jsx(Wt,{})})]}),e.jsx("pre",{className:"widget-expand-lines",children:G.lines.join(`
204
+ `)})]})}):null})()]})});function ih(t,n,s=!1){const r=s==="mixed"?/^([^:\s]+):(\d+):\s*(.*)$/.exec(t):s?/^(?:([^:\s]+):)?(\d+):\s*(.*)$/.exec(t):null;return r?{number:r[2],text:r[1]?`${r[1]}: ${r[3]}`:r[3]}:{number:String(n+1),text:t}}function Xs(t){return/^(?:stderr\b|fatal:|error:|[^:\n]+:\s.*(?:No such file or directory|Permission denied|command not found|not found|cannot access|failed|error))/i.test(t.trim())}function ah(t,n){if(n||t.length<=8)return t.map((r,i)=>i);const s=new Set;for(let r=0;r<Math.min(5,t.length);r++)s.add(r);for(let r=Math.max(0,t.length-3);r<t.length;r++)s.add(r);for(let r=0;r<t.length;r++)Xs(t[r])&&s.add(r);return[...s].sort((r,i)=>r-i)}function Vs(t,n){var r;const s=(r=/^\/(?:Users|home)\/[^/]+/.exec(n))==null?void 0:r[0];return s?t.replaceAll(s,"~"):t}function oh(t){try{const n=JSON.parse(t??"{}").command;return typeof n!="string"||!/(?:^|[;&|(\s])(?:grep|rg)\s+(?:-[\w-]*n[\w-]*\s+|--line-number\s+)/.test(n)?"none":/^\s*(?:grep|rg)\b/.test(n)&&!/[;&|]/.test(n)?"standalone":"mixed"}catch{return"none"}}function fi(t,n){var s,r;try{const i=JSON.parse(t??"{}"),a=typeof i.cwd=="string"?i.cwd:typeof i.command=="string"?(s=/^\s*cd\s+(?:"([^"$`]+)"|'([^']+)'|([^\s;&|$`]+))\s*&&/.exec(i.command))==null?void 0:s.slice(1).find(Boolean):void 0;if(!a||/[$`*?]/.test(a))return null;const o=(r=/^(\/(?:Users|home)\/[^/]+)/.exec(n))==null?void 0:r[1],c=a.startsWith("~/")&&o?o+a.slice(1):a.startsWith("/")?a:`${n}/${a}`,l=[];for(const u of c.split("/"))u===".."?l.pop():u&&u!=="."&&l.push(u);const p="/"+l.join("/");return p===n.replace(/\/$/,"")?null:o&&(p===o||p.startsWith(o+"/"))?"~"+p.slice(o.length):p}catch{return null}}function jr(t,n){const s=/^\s*cd\s+(?:"([^"$`\\]+)"|'([^']+)'|([^\s;&|$`\\*?(){}<>]+))\s*&&\s*/.exec(t);if(!s||!n.startsWith("/"))return{command:Vs(t,n),directory:null};const r=s.slice(1).find(Boolean);return/[$`*?\\]/.test(r)||(s[1]||s[2])&&r.startsWith("~")||r==="-"||r.startsWith("~")&&!r.startsWith("~/")?{command:Vs(t,n),directory:null}:{command:Vs(t.slice(s[0].length),n),directory:fi(JSON.stringify({command:t}),n)}}function Ml(t){const n=/^([ MADRCUT?!]{2}) (.+)$/.exec(t);if(!n||!n[1].trim())return null;const s=n[1].trim(),r=s.includes("U")||s==="AA"||s==="DD"?"conflict":s==="??"?"untracked":s.includes("D")?"deleted":s.includes("A")?"added":"modified";return{status:s,path:n[2],kind:r}}function lh(t,n){if(!Li(t).some(r=>/^git\s+status\b/.test(r))||!n.length)return null;const s=n.map(Ml);return s.some(r=>!r)?null:{files:s.length,added:s.filter(r=>r.kind==="added"||r.kind==="untracked").length,modified:s.filter(r=>r.kind==="modified").length,deleted:s.filter(r=>r.kind==="deleted").length,conflicts:s.filter(r=>r.kind==="conflict").length}}function ch(t){const n=t.split(/\r?\n/,1)[0],s=/\s+2>\s*\/dev\/null\s*$/.exec(n);if(!s)return n;const r=n.slice(0,s.index);return/['"`\\;&|<>$]/.test(r)?n:r}function gi(t){const n=ch(t).replace(/(?:[~.]?\/|[A-Za-z]:\\)(?:[\w.@-]+[\/\\]){2,}([\w.@-]+)/g,(s,r,i,a)=>`${s.startsWith("/")&&i>0&&/[\w.@-]/.test(a[i-1])?"/":""}…/${r}`);return n.length>80?`${n.slice(0,28)}…${n.slice(-48)}`:n}function dh(t){return t<100?"<0.1s":`${(t/1e3).toFixed(1)}s`}function xi(t,n=!1){const s=/^\s*echo\s+(["'])===\s*(.+?)\s*===\1\s*&&\s*([\s\S]+)$/.exec(t),r=s?s[3]:t,i=Li(r)[0]??r,a=/^sed\s+-n\s+['"]?(\d+),(\d+)p['"]?\s+(['"]?)([^\s'";&|<>$`]+)\3(?:\s+2>\s*\/dev\/null)?\s*$/.exec(i),o=/^(?:cat|head|tail)\s+(?:-n\s+\d+\s+)?(['"]?)([^\s'";&|<>$`]+)\1(?:\s+2>\s*\/dev\/null)?\s*$/.exec(i),c=/^git\s+show\s+[^\s:'"`;$&|<>]+:([^\s'"`;$&|<>]+)(?:\s+2>\s*\/dev\/null)?\s*$/.exec(i),l=(a==null?void 0:a[4])??(o==null?void 0:o[2])??(c==null?void 0:c[1]),p=l==null?void 0:l.split(/[\\/]/).at(-1);return{title:(s==null?void 0:s[2].trim())||(a?`${p} ${a[1]}–${a[2]}${n?" lines":" 行"}`:p)||gi(t),command:r,path:l}}function uh(t,n){const s=[];for(const r of t){const i=s.at(-1);i&&n(i[0])===n(r)?i.push(r):s.push([r])}return s}function Pl(t){const n=t.trim();return[...n].length<40&&!/[\n#*]|(?:完成|通过|失败|结论|发现|结果|问题是|已修复)/.test(n)&&/^(?:(?:我|我们)(?:会|将|要)?|接下来|下一步|然后|现在|先|再|继续|让我|I'll|I will|Next,?\s|Let me)/i.test(n)&&/(?:检查|查看|读取|确认|验证|修改|修复|测试|实现|更新|定位|对照|check|read|inspect|test|update|verify)/i.test(n)}function ph({message:t,last:n,regenerate:s}){const r=et(),[i,a]=d.useState(!1),o=t.content.map(c=>c.type==="text"?c.text:"").join(`
205
+ `);return!o.trim()||t.content.some(c=>c.type==="toolCall")||!n&&Pl(o)?null:e.jsxs("div",{className:`reply-actions ${n?"last":""}`,children:[e.jsxs("button",{onClick:()=>{navigator.clipboard.writeText(o).then(()=>a(!0)).catch(()=>a(!1))},children:[e.jsx(ws,{}),r(i?"copied":"copy")]}),s&&e.jsxs("button",{onClick:s,children:[e.jsx(ys,{}),r("changesRegenerate")]}),t.timestamp&&e.jsx("time",{dateTime:new Date(t.timestamp).toISOString(),children:new Date(t.timestamp).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})})]})}function hh(t,n=0,s=new Set){const r=new Map,i=new Map,a=new Map;let o;for(let c=n;c<t.length;c++){const l=t[c];for(const f of l.content)f.type==="toolCall"&&typeof f.id=="string"&&a.set(f.id,l.id);if(s.has(c)&&(o=void 0),l.role==="toolResult")continue;if(!(l.role==="assistant"&&l.content.length>0&&l.content.every(f=>f.type==="toolCall"&&f.name==="bash"))){const f=l.content.at(-1);o=l.role==="assistant"&&(f==null?void 0:f.type)==="toolCall"&&f.name==="bash"?l:void 0;continue}if(!o){o=l;continue}const u=r.get(o.id)??o;r.set(o.id,{...u,content:[...u.content,...l.content]}),i.set(l.id,o.id)}return{projected:r,owners:i,sources:a}}function _i(t){var s;if(t.role!=="user"||t.content.some(r=>r.type!=="text"))return null;const n=t.content.map(r=>r.type==="text"?r.text:"").join(`
206
+ `);return((s=/^【目标已设定】\n\n([\s\S]+)\n\n请现在开始实现这个目标。$/.exec(n))==null?void 0:s[1].trim())||null}function Hi(t){var s;if(t.role!=="user"||t.content.some(r=>r.type!=="text"))return null;const n=t.content.map(r=>r.type==="text"?r.text:"").join(`
207
+ `);return((s=/^✅ 目标已达成并通过审查(第 \d+ 轮)。\n\n目标:(.+)\n\n[\s\S]+\n\n(目标模式已解除,接下来按你的普通指令响应。)$/.exec(n))==null?void 0:s[1].trim())||null}function mh(t){const n=new Map,s=new Set;let r;for(const i of t){const a=_i(i),o=a??Hi(i);if(!o){r=void 0;continue}const c=a?"set":"complete";c==="set"&&(r==null?void 0:r.text)===o&&r.kind===c?(r.ids.push(i.id),s.add(i.id)):(r={text:o,kind:c,ids:[i.id]},n.set(i.id,r))}return{groups:n,absorbed:s}}function fh({recovery:t}){const n=et(),[s,r]=d.useState(!1),[i,a]=d.useState({left:0,top:0,maxHeight:300}),o=d.useRef(null),c=d.useRef(null),l=()=>{var p;r(!1),(p=o.current)==null||p.focus()};return d.useEffect(()=>{t.disabled&&r(!1)},[t.disabled]),d.useLayoutEffect(()=>{if(!s)return;const p=()=>{var k,j;const u=(k=o.current)==null?void 0:k.getBoundingClientRect();if(!u)return;const f=Math.min(300,window.innerHeight-24,((j=c.current)==null?void 0:j.scrollHeight)||100);a({left:Math.max(12,Math.min(u.left,window.innerWidth-272)),top:u.bottom+f+8<=window.innerHeight?u.bottom+6:Math.max(12,u.top-f-6),maxHeight:f})};return p(),window.addEventListener("resize",p),window.addEventListener("scroll",p,!0),()=>{window.removeEventListener("resize",p),window.removeEventListener("scroll",p,!0)}},[s,t.models]),d.useEffect(()=>{var u,f;if(!s)return;(f=((u=c.current)==null?void 0:u.querySelector('[aria-checked="true"], button'))??c.current)==null||f.focus();const p=k=>{var j,R;!((j=c.current)!=null&&j.contains(k.target))&&!((R=o.current)!=null&&R.contains(k.target))&&r(!1)};return document.addEventListener("pointerdown",p),()=>document.removeEventListener("pointerdown",p)},[s,t.models]),e.jsxs(e.Fragment,{children:[e.jsxs("button",{ref:o,type:"button",disabled:t.disabled,"aria-haspopup":"menu","aria-expanded":s,onClick:()=>{s||t.onLoadModels(),r(!s)},onKeyDown:p=>{(p.key==="ArrowDown"||p.key==="ArrowUp")&&(p.preventDefault(),t.onLoadModels(),r(!0))},children:[n("toolRecoverySwitch")," ",e.jsx(Qt,{className:s?"up":""})]}),s&&mn.createPortal(e.jsx("div",{ref:c,className:"tool-model-menu dd-menu",role:"menu","aria-label":n("toolRecoverySwitch"),tabIndex:-1,style:i,onKeyDown:p=>{var u,f;if(p.key==="Escape"&&(p.preventDefault(),l()),p.key==="Tab"&&r(!1),["ArrowDown","ArrowUp","Home","End"].includes(p.key)){p.preventDefault();const k=Array.from(((u=c.current)==null?void 0:u.querySelectorAll("button"))??[]),j=k.indexOf(document.activeElement),R=p.key==="Home"?0:p.key==="End"?k.length-1:(j+(p.key==="ArrowDown"?1:-1)+k.length)%k.length;(f=k[R])==null||f.focus()}},children:t.models.length?t.models.map(p=>e.jsxs("button",{type:"button",role:"menuitemradio","aria-checked":p.id===t.currentModelId,className:`dd-item ${p.id===t.currentModelId?"active":""}`,onClick:()=>{l(),t.retry(p.id)},children:[e.jsx("span",{className:"dd-model-name",children:p.name}),e.jsx("span",{className:"dd-model-provider",children:p.provider})]},p.id)):e.jsx("span",{className:"tool-model-empty",children:n("loading")})}),document.body)]})}function gh({incident:t,model:n,recovery:s}){const r=et(),[i,a]=d.useState(!1);return e.jsxs("div",{className:"unexecuted-tool",role:"status","data-incident-id":t.incidentId,children:[e.jsxs("header",{children:[e.jsxs("strong",{children:["✗ ",r("toolUnexecutedTitle")]}),e.jsx("span",{children:r("toolUnexecutedAttempts",{n:t.reminders.length})})]}),e.jsxs("div",{className:"tool-recovery-body",children:[e.jsx("p",{children:r(t.reminders.length?"toolUnexecutedHint":"unexecutedToolHint",{model:n})}),e.jsxs("div",{className:"tool-recovery-actions",children:[s&&e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button",className:"tool-recovery-primary",disabled:s.disabled,onClick:()=>s.retry(),children:r("toolRecoveryResend")}),e.jsx(fh,{recovery:s})]}),e.jsx("button",{type:"button",className:"tool-recovery-raw","aria-expanded":i,onClick:()=>a(o=>!o),children:r(i?"toolRecoveryRawHide":"toolRecoveryRaw")})]}),i&&e.jsx("div",{className:"tool-recovery-outputs",children:t.outputs.map(({message:o,raw:c,attempt:l})=>e.jsxs("section",{children:[e.jsxs("div",{children:[r(l?"toolRecoveryAfterReminder":"toolRecoveryFirst"),o.timestamp?` · ${new Date(o.timestamp).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}`:"",l>0&&` · ${r("toolRecoveryNoCall")}`]}),e.jsx("pre",{children:c})]},o.id))})]})]})}function xh({text:t}){const n=et(),[s,r]=d.useState(!1);return e.jsxs("div",{className:`thinking leaked ${s?"open":""}`,children:[e.jsxs("button",{type:"button",className:"thinking-toggle","aria-expanded":s,title:n("leakedThinkingHint"),onClick:()=>r(!s),children:[s?e.jsx(Qt,{}):e.jsx(_t,{}),e.jsx(Fo,{className:"thinking-icon"}),e.jsx("span",{className:"thinking-label",children:n("leakedThinking")})]}),s&&e.jsx("div",{className:"thinking-body",children:t})]})}const vh=/^\s{0,3}(`{3,}|~{3,})/,kh=/^\s{0,3}(?:[-*+]|\d{1,9}[.)])\s/;function Gr(t){return t.trim()===""}function za(t){const n=vh.exec(t);return n?n[1]:null}function yh(t){const n=t.split(`
208
+ `),s=[];let r=[],i=null;for(let a=0;a<n.length;a++){const o=n[a];if(i!==null){const l=za(o);l&&l[0]===i[0]&&l.length>=i.length&&(i=null),r.push(o);continue}const c=za(o);if(c&&!Gr(o)){i=c,r.push(o);continue}if(Gr(o)){let l=a;for(;l<n.length&&Gr(n[l]);)l++;if(!(l<n.length&&kh.test(n[l]))&&r.length>0){s.push(r.join(`
209
+ `)),r=[];continue}r.push(o);continue}r.push(o)}return{frozen:s,active:r.join(`
210
+ `),inFence:i!==null}}const wh=d.memo(function({text:n}){return e.jsx(Ir,{remarkPlugins:ui,rehypePlugins:cl,components:{pre:ul},children:n})}),Va=200;function bh({text:t,inFence:n}){const[s,r]=d.useState(t),i=d.useRef(0),a=d.useRef(null);return d.useEffect(()=>{if(n)return;const o=Date.now()-i.current,c=()=>{i.current=Date.now(),r(t)};if(o>=Va){c();return}return a.current=setTimeout(c,Va-o),()=>{a.current&&clearTimeout(a.current)}},[t,n]),n?e.jsx("div",{className:"codeblock",children:e.jsx("pre",{children:e.jsx("code",{children:t})})}):e.jsx(dl,{text:s})}const jh=d.memo(function({text:n}){const{frozen:s,active:r,inFence:i}=d.useMemo(()=>yh(n),[n]);return e.jsxs("div",{className:"md",children:[s.map((a,o)=>e.jsx(wh,{text:a},o)),r.length>0&&e.jsx(bh,{text:r,inFence:i},s.length)]})});function Ch(t){if(!t)return"";try{const n=JSON.parse(t);if(typeof n=="string")return n;if(typeof(n==null?void 0:n.code)=="string")return n.code}catch{}return t}function Sh(t){const n=/^\s*\/\/\s*@options:\s*(\{[^\n]*\})/.exec(t);if(!n)return{};try{const s=JSON.parse(n[1]);return Object.fromEntries(["max_output_tokens","timeout_ms"].filter(r=>typeof s[r]=="number"&&Number.isFinite(s[r])&&s[r]>=0).map(r=>[r,s[r]]))}catch{return{}}}function Nh({block:t,view:n,wrap:s=!0}){var q,fe,je,ne,Pe,B,we,re,Ie,_,le;const r=et(),i=d.useContext(er),[a,o]=d.useState(s),[c,l]=d.useState("calls"),[p,u]=d.useState(!1),[f,k]=d.useState(""),[j,R]=d.useState(!1),E=((q=n.result)==null?void 0:q.codemode)??n.codemode,A=(E==null?void 0:E.calls)??((je=((fe=n.result)==null?void 0:fe.nestedCalls)??n.nestedCalls)==null?void 0:je.calls.map(O=>({...O,args:O.argumentsText??"",status:O.status==="unfinished"?"running":O.status,cost:void 0})))??[],N=(E==null?void 0:E.totalCalls)??A.length,T=!!n.result||!!n.status&&!n.status.running,y=!T&&n.streaming,M=((ne=n.result)==null?void 0:ne.isError)??((Pe=n.status)==null?void 0:Pe.isError),b=M?"error":T?"done":y?"running":"toolQueued",F=((B=n.result)==null?void 0:B.content.map(O=>O.type==="text"?O.text:"").join(`
211
+ `))??n.liveOutput??"",U=Ch(t.argumentsText),ce=Sh(U),ie=((we=n.result)==null?void 0:we.content.flatMap(O=>O.type==="image"&&typeof O.dataUrl=="string"&&/^data:image\/(png|jpeg|gif|webp);base64,/.test(O.dataUrl)?[O.dataUrl]:[]))??[],W=new Map;for(const O of A)W.set(O.name,(W.get(O.name)??0)+1);const ve=A.filter(O=>O.cost!==void 0),Se=ve.reduce((O,ge)=>O+(ge.cost??0),0),$=((re=n.status)==null?void 0:re.durationMs)!==void 0?`${(n.status.durationMs/1e3).toFixed(1)}s`:(Ie=/Wall time:?\s*([^\n]+)/i.exec(F))==null?void 0:Ie[1],$e=async O=>{try{await navigator.clipboard.writeText(O),k(r("copied"))}catch(ge){k(String(ge))}},L=async(O,ge,pe)=>{R(!0),k("");try{if(ge){const Ae=await(await fetch(O)).blob();if(!await new Promise(Te=>window.dispatchEvent(new CustomEvent("pi-codemode-attach",{detail:{cwd:i,complete:Te,file:new File([Ae],`codemode-${pe}.${Ae.type.split("/")[1]}`,{type:Ae.type})}}))))throw new Error(r("imageLoadFailed",{name:`codemode-${pe}`}));k(r("cmAttached"))}else{const Ae=await fetch(Tn("/api/codemode-image"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({clientId:fn(),cwd:i,dataUrl:O})}),ae=await Ae.json();if(!Ae.ok)throw new Error(ae.error??`HTTP ${Ae.status}`);k(r("cmSaved",{path:ae.path}))}}catch(Ae){k(Ae.message)}finally{R(!1)}};return e.jsxs("section",{className:`codemode-card ${M?"err":y?"run":""}`,"data-tool-call-id":t.id,children:[e.jsxs("button",{className:"codemode-head","aria-expanded":a,onClick:()=>o(!a),children:[e.jsx("span",{"aria-hidden":"true",children:a?"⌄":"›"}),e.jsx("span",{className:"codemode-mark",children:"{ }"}),e.jsx("strong",{children:"codemode"}),e.jsx("span",{className:"codemode-state",children:r(b)}),$&&e.jsx("small",{children:$}),ve.length>0&&e.jsxs("small",{children:["$",Se.toFixed(4)]})]}),a&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"codemode-summary",children:[[...W].map(([O,ge])=>e.jsxs("span",{children:[e.jsx("code",{children:O})," × ",ge]},O)),!A.length&&e.jsx("span",{children:r(y?"cmWaitingCalls":"cmNoCalls")})]}),e.jsxs("div",{className:"codemode-tabs",role:"tablist","aria-label":"Codemode",children:[["calls","script","output"].map(O=>e.jsxs("button",{id:`${t.id}-${O}`,role:"tab","aria-selected":c===O,"aria-controls":`${t.id}-panel`,tabIndex:c===O?0:-1,onKeyDown:ge=>{var pe;if(ge.key==="ArrowRight"||ge.key==="ArrowLeft"){ge.preventDefault();const Ae=["calls","script","output"],ae=Ae[(Ae.indexOf(O)+(ge.key==="ArrowRight"?1:2))%3];l(ae),(pe=document.getElementById(`${t.id}-${ae}`))==null||pe.focus()}},onClick:()=>l(O),children:[r(O==="calls"?"cmCalls":O==="script"?"cmScript":"output"),O==="calls"&&` · ${N}`]},O)),e.jsx("span",{}),c!=="calls"&&e.jsx("button",{className:"codemode-copy",onClick:()=>void $e(c==="script"?U:F),children:r("copy")})]}),e.jsxs("div",{className:"codemode-body",id:`${t.id}-panel`,role:"tabpanel","aria-labelledby":`${t.id}-${c}`,children:[c==="calls"&&e.jsxs(e.Fragment,{children:[A.length>8&&e.jsx("button",{className:"codemode-expand",onClick:()=>u(!p),children:r(p?"cmCollapseCalls":"cmMoreCalls",{n:A.length-8})}),(p?A:A.slice(-8)).map(O=>e.jsxs("details",{className:`codemode-call ${O.status}`,children:[e.jsxs("summary",{children:[e.jsx("span",{className:"codemode-call-dot","aria-label":r(O.status==="ok"?"done":O.status==="cancelled"?"cmCancelled":O.status==="running"?T?"cmUnfinished":"running":"error"),children:O.status==="ok"?"✓":O.status==="error"?"×":O.status==="cancelled"||T&&O.status==="running"?"−":"•"}),e.jsx("code",{children:O.name}),e.jsx("span",{className:"codemode-args",children:O.args}),O.cost!==void 0&&e.jsxs("small",{children:["$",O.cost.toFixed(4)]}),O.durationMs!==void 0&&e.jsx("small",{children:O.durationMs<1e3?`${Math.round(O.durationMs)}ms`:`${(O.durationMs/1e3).toFixed(1)}s`})]}),e.jsx("pre",{children:O.args}),O.error&&e.jsx("pre",{className:"err",children:O.error})]},O.id)),N>A.length&&e.jsx("p",{children:r("cmLimitedCalls",{n:N-A.length})}),!A.length&&e.jsx("p",{className:"codemode-empty",children:r("cmNoCalls")})]}),c==="script"&&e.jsxs(e.Fragment,{children:[e.jsx(On,{text:`\`\`\`\`javascript
212
+ ${U}
213
+ \`\`\`\``}),t.argumentsTruncated&&e.jsx("p",{children:r("cmTruncated")})]}),c==="output"&&e.jsxs(e.Fragment,{children:[((_=n.result)==null?void 0:_.toolOutputUrl)&&e.jsx(Js,{url:n.result.toolOutputUrl}),e.jsx("pre",{children:F||r(y?"cmWaitingOutput":"cmNoOutput")}),((le=n.result)==null?void 0:le.content.some(O=>O.type==="text"&&O.truncated))&&e.jsx("p",{children:r("cmTruncated")}),(E==null?void 0:E.fullOutputPath)&&e.jsxs("div",{className:"codemode-full-output",children:[r("cmFullOutput")," ",e.jsx("code",{children:E.fullOutputPath}),e.jsx("button",{onClick:()=>void $e(E.fullOutputPath),children:r("copy")})]})]})]}),M&&e.jsx("p",{className:"codemode-error-note",children:r("cmFailureNote")}),ie.length>0&&e.jsx("div",{className:"codemode-images",children:ie.map((O,ge)=>e.jsxs("figure",{children:[e.jsx("a",{href:O,target:"_blank",rel:"noreferrer",children:e.jsx("img",{src:O,alt:r("toolResultImage"),loading:"lazy"})}),e.jsxs("figcaption",{children:[e.jsx("button",{disabled:j,onClick:()=>void L(O,!1,ge),children:r("cmSaveImage")}),e.jsx("button",{disabled:j,onClick:()=>void L(O,!0,ge),children:r("cmAttachImage")})]})]},ge))}),e.jsxs("footer",{className:"codemode-footer",children:[e.jsxs("span",{children:["max_output_tokens ",ce.max_output_tokens??1e4]}),ce.timeout_ms!==void 0&&e.jsxs("span",{children:["timeout ",ce.timeout_ms/1e3,"s"]}),e.jsx("span",{children:"QuickJS · 256 MB"}),ve.length>0&&e.jsxs("span",{children:[r("cmModelCost"),": $",Se.toFixed(4)]})]}),f&&e.jsx("p",{className:"codemode-feedback",role:"status",children:f})]})]})}function Bi(t){if(!t)return null;try{const n=JSON.parse(t);return!n||typeof n!="object"||!("path"in n)?null:typeof n.path=="string"?n.path:null}catch{return null}}function Ui(t){var s;const n=(s=t.match(/^\/(?:Users|home)\/[^/]+(?=\/|$)/))==null?void 0:s[0];return n?`~${t.slice(n.length)}`:t}function Al(t){var i;const n=t.replace(/\r\n/g,`
214
+ `).split(`
215
+ `);if(((i=n[0])==null?void 0:i.trim())!=="---")return{fields:[],body:t};const s=n.findIndex((a,o)=>o>0&&o<50&&a.trim()==="---");if(s<0)return{fields:[],body:t};const r=[];for(const a of n.slice(1,s)){const o=/^([\w-]+):\s*(.*)$/.exec(a);o?r.push({name:o[1],value:o[2].replace(/^['"]|['"]$/g,"")}):/^\s+\S/.test(a)&&r.length&&(r[r.length-1].value+=` ${a.trim()}`)}return{fields:r,body:n.slice(s+1).join(`
216
+ `).trimStart()}}function Dl(t,n){const s=[...n.values()].filter(r=>r.parentToolCallId===t).slice(0,256).map(r=>({id:r.toolCallId,name:r.toolName,argumentsText:r.argumentsText,status:r.running?"unfinished":r.isError?"error":"ok",durationMs:r.durationMs}));return s.length?{calls:s,complete:!1}:void 0}function Cr(t){window.dispatchEvent(new CustomEvent("pi:tool-hover",{detail:{toolCallId:t}}))}function Eh({items:t,wrap:n}){const s=et(),[r,i]=d.useState(!1),a=t.map(({block:u})=>Bi(u.argumentsText)??u.name),o=t.some(({view:u})=>u.streaming&&!u.result&&!u.status),c=t.every(({view:u})=>u.result||u.status),l=t.some(({view:u})=>{var f,k;return((f=u.result)==null?void 0:f.isError)||((k=u.status)==null?void 0:k.isError)}),p=t.reduce((u,{view:f})=>{var k;return u+(((k=f.status)==null?void 0:k.durationMs)??0)},0);return e.jsxs("div",{className:`read-group ${l?"err":o?"run":c?"ok":"idle"}`,children:[e.jsxs("button",{type:"button",className:"read-group-head","aria-expanded":r,onClick:()=>i(u=>!u),children:[e.jsx("span",{"aria-hidden":"true",children:r?"⌄":"›"}),e.jsx("span",{"aria-hidden":"true",children:"📄"}),e.jsx("strong",{children:s("readFiles",{n:t.length})}),e.jsx("span",{className:"read-group-paths",title:a.join(`
217
+ `),children:a.map(u=>u.split("/").slice(-2).join("/")).join(", ")}),e.jsx("span",{className:"read-group-status",children:l?s("error"):o?s("running"):c?`${s("done")}${p?` · ${Sr(p)}`:""}`:s("toolQueued")})]}),r&&e.jsx("div",{className:"read-group-items",children:t.map(({block:u,view:f})=>e.jsx(Th,{block:u,view:f,wrap:n},u.id))})]})}function Th({block:t,view:n,wrap:s}){var p,u,f;const r=et(),[i,a]=d.useState(!1),o=Bi(t.argumentsText)??t.name,c=((p=n.result)==null?void 0:p.content.map(k=>k.type==="text"&&typeof k.text=="string"?k.text:"").join(""))??n.liveOutput??"",l=c?c.replace(/\r\n/g,`
218
+ `).replace(/\n$/,"").split(`
219
+ `).length:0;return e.jsxs("div",{className:"read-file-row",onMouseEnter:()=>Cr(t.id),onMouseLeave:()=>Cr(null),children:[e.jsxs("button",{type:"button",className:"read-file-head",title:o,"aria-expanded":i,onClick:()=>a(k=>!k),children:[e.jsx(_t,{className:i?"open":""}),e.jsx("span",{children:r("readVerb")}),e.jsx("code",{children:Ui(o)}),l>0&&e.jsx("span",{children:r("toolLineCount",{n:l})}),e.jsx("i",{className:(u=n.result)!=null&&u.isError||(f=n.status)!=null&&f.isError?"error":n.result||n.status?"done":"pending"})]}),i&&e.jsx(Wi,{block:t,view:n,wrap:s})]})}function Rh({block:t,view:n,wrap:s}){var k,j;const r=et(),[i,a]=d.useState(!1);let o="",c="";try{const R=JSON.parse(t.argumentsText??"{}");typeof R.pattern=="string"&&(o=R.pattern),typeof R.path=="string"?c=R.path:typeof R.glob=="string"&&(c=R.glob)}catch{}const l=((k=n.result)==null?void 0:k.content.map(R=>R.type==="text"&&typeof R.text=="string"?R.text:"").join(""))??n.liveOutput??"",p=/^\s*(?:No matches|没有匹配)/i.test(l),u=l.split(`
220
+ `).filter(R=>/^\S+?:\d+[:-]/.test(R)).length,f=((j=n.status)==null?void 0:j.durationMs)!==void 0?Sr(n.status.durationMs):"";return e.jsxs("div",{className:"grep-summary",children:[e.jsxs("button",{type:"button",className:"grep-summary-head","aria-expanded":i,onClick:()=>a(R=>!R),children:[e.jsx(_t,{className:i?"open":""}),e.jsx("strong",{children:r("grepSearch")}),e.jsx("code",{title:o,children:o||t.name}),c&&e.jsx("span",{title:c,children:r("grepInPath",{path:Ui(c)})}),n.result&&!n.result.isError&&e.jsx("span",{children:u||p?r("grepMatches",{n:u}):r("toolLineCount",{n:l.split(`
221
+ `).filter(Boolean).length})}),f&&e.jsx("span",{className:"grep-summary-time",children:f})]}),i&&e.jsx("div",{className:"grep-summary-body",children:e.jsx(Wi,{block:t,view:n,wrap:s})})]})}const $l={bash:"$",read:"📄",write:"W",edit:"✏️",grep:"🔍",find:"🧭",ls:"📂"};function Ka(t){return $l[t]??"🛠"}function Ih({text:t}){const n=et();let s;try{const r=JSON.parse(t);if(r&&typeof r=="object"&&!Array.isArray(r)){const i=Object.entries(r);i.length>0&&i.length<=8&&i.every(([,a])=>a===null||typeof a=="number"||typeof a=="boolean"||typeof a=="string"&&a.length<=160)&&(s=i)}}catch{}return e.jsxs("div",{className:"toolcall-parameters",children:[e.jsx("span",{className:"toolcall-section-label",children:n("toolParameters")}),s?e.jsx("dl",{children:s.map(([r,i])=>e.jsxs("div",{children:[e.jsx("dt",{children:r}),e.jsx("dd",{children:i===null?"null":String(i)})]},r))}):e.jsx("pre",{children:t})]})}function Lh(t){if(t.name!=="read"||!t.argumentsText)return!1;try{const n=JSON.parse(t.argumentsText);return typeof n.path=="string"&&/\.(md|markdown)$/i.test(n.path)}catch{return!1}}function Mh(t){if(t.name!=="read"||!t.argumentsText)return null;try{const n=JSON.parse(t.argumentsText);return typeof n.path=="string"?Os(n.path):null}catch{return null}}function Ph(t){if(t.name!=="write"||!t.argumentsText)return null;try{const n=JSON.parse(t.argumentsText);return typeof n.content!="string"?null:{lang:typeof n.path=="string"?Os(n.path):null,content:n.content}}catch{return null}}function Ah(t){if(t.name!=="edit"||!t.argumentsText)return null;try{const n=JSON.parse(t.argumentsText);return typeof n.path=="string"?Os(n.path):null}catch{return null}}function Dh(t,n){if(t.name!=="edit"||!n.result||n.result.isError)return null;const s=n.result.details;return typeof(s==null?void 0:s.diff)=="string"?s.diff:null}const $h=/^([+\- ])(\s*\d+) (.*)$/;function Fh(t){return t.split(`
222
+ `).map(n=>{const s=$h.exec(n);return s?{marker:s[1],lineNum:s[2],code:s[3]}:{marker:" ",lineNum:"",code:n}})}function Oh({diff:t,lang:n,path:s}){const r=Fh(t),i=r.filter(o=>o.marker==="+").length,a=r.filter(o=>o.marker==="-").length;return e.jsxs("div",{className:"toolcall-diff",children:[e.jsxs("div",{className:"toolcall-diff-header",children:[e.jsx("span",{title:s,children:s}),e.jsxs("span",{children:["+",i," −",a]})]}),e.jsx("div",{className:"toolcall-diff-lines",children:r.map((o,c)=>e.jsxs("div",{className:`toolcall-diff-line ${o.marker==="+"?"add":o.marker==="-"?"del":"ctx"}`,children:[e.jsxs("span",{className:"toolcall-diff-gutter",children:[o.marker,o.lineNum]}),e.jsx("code",{className:"toolcall-diff-code hljs",dangerouslySetInnerHTML:{__html:Zs(o.code,n)||"​"}})]},c))})]})}function Ga(t,n){var a;const s=((a=t.match(/`+/g))==null?void 0:a.map(o=>o.length))??[],r=s.length?Math.max(...s):0,i="`".repeat(Math.max(3,r+1));return`${i}${n}
223
+ ${t.replace(/\n$/,"")}
224
+ ${i}`}const Wi=d.memo(function(n){return n.block.name==="codemode"?e.jsx(Nh,{...n}):n.block.name==="task_plan"?e.jsx(_h,{block:n.block,view:n.view}):e.jsx(Bh,{...n})});function _h({block:t,view:n}){var l,p,u,f,k;const s=et();let r=[];try{const j=JSON.parse(t.argumentsText??"{}");Array.isArray(j.steps)&&(r=j.steps.filter(R=>typeof R=="object"&&R!==null&&typeof R.title=="string"))}catch{}const[i,a]=d.useState(!n.result);d.useEffect(()=>{n.result&&a(!1)},[n.result]);const o=((l=n.result)==null?void 0:l.content.filter(j=>j.type==="text").map(j=>j.text).join(" "))??"",c=Number(((p=/Plan revision (\d+)/.exec(o))==null?void 0:p[1])??0)>1;return e.jsxs("div",{className:`task-plan-card${(u=n.result)!=null&&u.isError?" err":""}`,children:[e.jsxs("button",{type:"button",className:"task-plan-card-head","aria-expanded":i,onClick:()=>a(j=>!j),children:[e.jsx(_t,{className:i?"open":""}),e.jsxs("span",{children:[s(c?"taskPlanChanged":"taskPlanCard")," · ",r.length," ",s("taskPlanSteps")]}),e.jsx("span",{className:"task-plan-card-state",children:(f=n.result)!=null&&f.isError?s("error"):n.result?s("done"):s("running")})]}),i&&e.jsx("ol",{children:r.map(j=>e.jsx("li",{children:j.title},j.id))}),((k=n.result)==null?void 0:k.isError)&&e.jsx("div",{className:"task-plan-card-error",children:o})]})}function Hh({command:t,original:n,directory:s,running:r,elapsed:i,status:a,full:o,onFull:c,onKill:l,children:p}){const u=et(),f=/^git\s+commit\s+(?:-q\s+)?-m\s+(?:"([^"$`]+)"|'([^']+)')\s*$/.exec(t),k=d.useRef(null),[j,R]=d.useState(!1);return d.useEffect(()=>{const E=k.current;if(!E)return;const A=()=>R(E.scrollWidth>E.clientWidth+1||t.includes(`
225
+ `)),N=new ResizeObserver(A);return N.observe(E),A(),()=>N.disconnect()},[t]),e.jsxs("div",{className:"toolcall-head bash-command-head",children:[r&&e.jsx("span",{className:"bash-running-dot","aria-label":u("running")}),e.jsxs("button",{type:"button",className:"bash-head-command",title:n,disabled:!j&&!o,"aria-expanded":o,"aria-label":o?u("collapseCode"):j?u("bashExpandFullCommand"):t,onClick:c,children:[e.jsx("span",{className:"bash-prompt",children:"$"}),f&&e.jsx("span",{className:"bash-command-verb",children:"git commit"}),e.jsx("span",{ref:k,className:`bash-command-text${f?" bash-commit-subject":""}`,children:f?f[1]??f[2]:t}),(j||o)&&e.jsx(Qt,{className:o?"open":""})]}),s&&e.jsx("span",{className:"bash-directory",title:s,children:s}),e.jsx("span",{className:"toolcall-status",children:r?`${Math.floor(i/60)}:${String(i%60).padStart(2,"0")}`:a}),r&&l&&e.jsx("button",{type:"button",className:"toolcall-kill",title:u("stopBashTip"),onClick:l,children:u("stopBash")}),e.jsxs("details",{className:"bash-card-more",children:[e.jsx("summary",{"aria-label":u("more"),children:"⋯"}),e.jsx("div",{children:p})]})]})}function Bh({block:t,view:n,onKillBash:s,wrap:r=!0}){var Le,xe,be,nt,Ce,ye,ze,Ze,Qe,ct,tt;const i=((Le=n.result)==null?void 0:Le.nestedCalls)??n.nestedCalls,a=et(),[o,c]=d.useState(r),[l,p]=d.useState(!1),[u,f]=d.useState(!1),[k,j]=d.useState("steps"),[R,E]=d.useState(!1),[A,N]=d.useState(0),T=d.useContext(er),[y,M]=d.useState(!0),[b,F]=d.useState(!1),[U,ce]=d.useState(!1);d.useEffect(()=>{if(!U)return;const Oe=ee=>{ee.key==="Escape"&&ce(!1)};return window.addEventListener("keydown",Oe),()=>window.removeEventListener("keydown",Oe)},[U]);const ie=!n.result&&n.streaming&&!n.status;d.useEffect(()=>{if(!ie)return;const Oe=Date.now(),ee=window.setInterval(()=>N(Math.floor((Date.now()-Oe)/1e3)),1e3);return()=>window.clearInterval(ee)},[ie]);const W=t.name==="bash"&&ie,ve=n.result!==void 0,Se=!n.result&&!!n.status,$=((xe=n.result)==null?void 0:xe.isError)??((be=n.status)==null?void 0:be.isError)??!1,$e=Lh(t),L=!$e&&!$?Mh(t):null,q=Ph(t),fe=Dh(t,n),je=fe?Ah(t):null;let ne="";if(fe)try{ne=JSON.parse(t.argumentsText??"").path??""}catch{}const Pe=!Object.hasOwn($l,t.name),B=n.result?n.result.content.map(Oe=>Oe.type==="text"?Oe.text:"").join(""):n.liveOutput??"",we=((Ce=(nt=n.result)==null?void 0:nt.details)==null?void 0:Ce.exitCode)??((ye=n.status)==null?void 0:ye.exitCode),re=t.name==="bash"?xu(t.argumentsText,B,ve||Se,$,we):null,Ie=t.name==="bash"&&$&&!re?vu(B):[],_=we??Number(((ze=/(?:exited with code\s*|exit(?:ed)?\s+)(\d+)/i.exec(B))==null?void 0:ze[1])??NaN),le=B.replace(/\r\n/g,`
226
+ `).split(`
227
+ `);le.at(-1)===""&&le.pop();const O=t.name==="bash"?Ys(t.argumentsText):null,ge=!!O,pe=O?jr(O,T):null,ae=t.name!=="bash"&&le.length>10&&!b&&!U?le.slice(0,10).join(`
228
+ `):B,Te=$e&&y&&!$?Al(ae):null,Z=t.name==="read"?Bi(t.argumentsText):null,Fe=(re==null?void 0:re.status)==="partial"?"partial":(re==null?void 0:re.status)==="no-match"?"idle":$?"err":ve||Se?"ok":ie?"run":"idle";let z=a($?"error":ve?"done":ie?"running":Se?"done":"toolQueued");const G=((Ze=n.status)==null?void 0:Ze.durationMs)!==void 0?Sr(n.status.durationMs):"";G&&(z=`${z} · ${G}`),re?z=re.status==="partial"?a("bashPartial",{ok:re.completed,total:re.steps.length}):re.status==="failed"?a("bashFailed"):re.status==="no-match"?a("bashNoMatch"):re.status==="running"?`${a("bashRunning")}${A?` · ${A}s`:""}`:`${a("done")}${G?` · ${G}`:""}`:t.name==="bash"&&$&&(z=`${a("bashFailed")}${Number.isFinite(_)?` · exit ${_}`:""}${Ie.length?` · ${a("bashErrorCount",{n:Ie.length})}`:""}`);const J=we!==void 0?`exit ${we}`:"",Ee=()=>{if(t.argumentsText){let Oe=t.argumentsText;try{t.name==="bash"&&(Oe=JSON.parse(Oe).command??Oe)}catch{}navigator.clipboard.writeText(Oe),p(!0),setTimeout(()=>p(!1),1200)}},V=e.jsxs(e.Fragment,{children:[t.argumentsText&&(!ge||R||U)&&e.jsx("div",{className:"toolcall-args",children:Pe?e.jsx(Ih,{text:t.argumentsText}):Z?e.jsx("button",{type:"button",className:"toolcall-read-path",title:Z,onClick:()=>ce(!0),children:Ui(Z)}):t.name==="bash"&&t.argumentsText.startsWith("{")?e.jsx("div",{className:"bash-command-preview",children:e.jsx(Uh,{args:t.argumentsText,cwd:T})}):q?q.lang?e.jsx("div",{className:"toolcall-code",children:e.jsx(On,{text:Ga(q.content,q.lang)})}):e.jsx("pre",{children:q.content}):e.jsx("pre",{children:t.argumentsText})}),i&&e.jsxs("details",{className:"tool-nested-calls",open:!0,children:[e.jsx("summary",{children:a("nestedToolCalls",{n:i.calls.length})}),i.calls.map(Oe=>e.jsxs("details",{className:"tool-nested-call",children:[e.jsxs("summary",{children:[e.jsx("code",{children:Oe.name}),e.jsxs("span",{className:Oe.status==="error"?"err":"",children:[a(Oe.status==="ok"?"done":Oe.status==="error"?"error":"running"),Oe.durationMs!==void 0?` · ${Sr(Oe.durationMs)}`:""]})]}),Oe.argumentsText&&e.jsx("pre",{children:Oe.argumentsText}),Oe.error&&e.jsx("pre",{className:"err",children:Oe.error})]},Oe.id)),n.result&&!i.complete&&e.jsx("p",{children:a("nestedToolCallsIncomplete")})]}),!Pe&&((Qe=n.result)==null?void 0:Qe.toolOutputUrl)&&e.jsx(Js,{url:n.result.toolOutputUrl}),(ct=n.result)==null?void 0:ct.content.flatMap(Oe=>Oe.type==="image"&&"dataUrl"in Oe&&typeof Oe.dataUrl=="string"?[Oe.dataUrl]:[]).map((Oe,ee)=>e.jsxs("div",{children:[e.jsx("a",{href:Oe,target:"_blank",rel:"noreferrer",className:"tool-result-image",children:e.jsx("img",{src:Oe,alt:a("toolResultImage"),loading:"lazy"})}),e.jsx("a",{href:Oe,download:`generated-${ee}.png`,children:a("downloadImage")})]},ee)),B.length>0&&(t.name==="bash"?re&&k==="steps"?e.jsx(Wh,{run:re,wrap:u}):Ie.length>0?e.jsx(qh,{diagnostics:Ie,output:B,wrap:u}):e.jsx(zh,{output:B,wrap:u,cwd:fi(t.argumentsText,T)??"",searchOutput:oh(t.argumentsText),command:(pe==null?void 0:pe.command)??""}):e.jsxs("div",{className:"toolcall-output",children:[e.jsxs("div",{className:"toolcall-output-label",children:[$?a("errorOutput"):t.name==="read"?a("modelReadOnly"):a("output"),ie&&e.jsx("span",{className:"thinking-spinner","aria-hidden":"true"}),e.jsx("span",{className:"toolcall-output-spacer"}),$e&&!$&&e.jsx("button",{type:"button",className:"toolcall-md-toggle",title:a(y?"showMarkdownSource":"showMarkdownPreview"),onClick:()=>M(Oe=>!Oe),children:a(y?"readRaw":"showMarkdownPreview")})]}),fe?e.jsx(Oh,{diff:fe,lang:je,path:ne}):$e&&y&&!$?e.jsxs("div",{className:"toolcall-markdown",children:[Te&&Te.fields.length>0&&e.jsx("dl",{className:"toolcall-frontmatter",children:Te.fields.map(({name:Oe,value:ee})=>e.jsxs("div",{children:[e.jsx("dt",{children:Oe}),e.jsx("dd",{children:ee})]},Oe))}),e.jsx(On,{text:(Te==null?void 0:Te.body)??ae})]}):L?e.jsx("div",{className:"toolcall-code",children:e.jsx(On,{text:Ga(ae,L)})}):e.jsx("pre",{children:ae}),t.name!=="bash"&&le.length>10&&e.jsx("button",{type:"button",className:"toolcall-output-more",onClick:()=>F(Oe=>!Oe),children:b||U?a("collapseCode"):a("expandAllLines",{n:le.length})})]})),Pe&&((tt=n.result)==null?void 0:tt.toolOutputUrl)&&e.jsxs("div",{className:"toolcall-result-actions",children:[!B&&e.jsx("span",{children:a("toolOutputFileOnly")}),e.jsx(Js,{url:n.result.toolOutputUrl,compact:!0})]})]});return e.jsxs("div",{className:`toolcall ${Pe?"toolcall-generic":""} ${Fe} ${t.name==="bash"?"toolcall-bash":""} ${re?"toolcall-steps":""} ${Ie.length?"toolcall-diagnostics":""}`,onMouseEnter:()=>Cr(t.id),onMouseLeave:()=>Cr(null),children:[pe?e.jsxs(Hh,{command:pe.command,original:O,directory:pe.directory??fi(t.argumentsText,T),running:W,elapsed:A,status:z,full:R,onFull:()=>{E(Oe=>!Oe),c(!0)},onKill:s,children:[re&&e.jsxs("span",{className:"bash-view-switch",children:[e.jsx("button",{type:"button",className:k==="steps"?"active":"",onClick:()=>j("steps"),children:a("bashSteps")}),e.jsx("button",{type:"button",className:k==="raw"?"active":"",onClick:()=>j("raw"),children:a("bashRaw")})]}),e.jsx("button",{type:"button",className:"toolcall-wrap","aria-pressed":u,onClick:()=>f(Oe=>!Oe),children:a("toolWrap")}),e.jsx("button",{type:"button",className:"toolcall-expand",onClick:()=>F(Oe=>!Oe),children:a(b?"collapseCode":"expandCode")}),e.jsx("button",{type:"button",className:"toolcall-expand",onClick:()=>ce(!0),children:a("zoomCode")}),e.jsx("button",{type:"button",className:"toolcall-copy",onClick:Ee,children:a(l?"copied":"copy")}),e.jsx("button",{type:"button",className:"toolcall-toggle",onClick:()=>c(Oe=>!Oe),children:a(o?"collapseCode":"expandCode")})]}):e.jsxs("div",{className:"toolcall-head",children:[e.jsx("span",{className:"toolcall-icon",children:Pe?e.jsx(ra,{"aria-hidden":"true"}):Ka(t.name)}),ge?e.jsxs("code",{className:"bash-head-command",title:O??"",children:["$ ",Vs(O,T)]}):Pe?e.jsx("button",{type:"button",className:"toolcall-name toolcall-name-toggle",title:t.name,"aria-expanded":o,onClick:()=>c(Oe=>!Oe),children:t.name}):e.jsx("span",{className:"toolcall-name",children:t.name}),ge&&B&&e.jsx("span",{className:"bash-head-count",children:a("toolLineCount",{n:le.length})}),e.jsxs("span",{className:"toolcall-status",children:[z,ie&&t.name==="bash"&&e.jsxs("span",{className:"working-dots","aria-hidden":"true",children:[e.jsx("i",{}),e.jsx("i",{}),e.jsx("i",{})]}),J&&e.jsx("em",{className:"toolcall-exit",children:J})]}),e.jsx("span",{className:"toolcall-spacer"}),re&&e.jsxs("span",{className:"bash-view-switch",children:[e.jsx("button",{type:"button",className:k==="steps"?"active":"",onClick:()=>j("steps"),children:a("bashSteps")}),e.jsx("button",{type:"button",className:k==="raw"?"active":"",onClick:()=>j("raw"),children:a("bashRaw")})]}),t.name==="bash"&&!re&&!Ie.length&&e.jsx("button",{type:"button",className:"toolcall-wrap","aria-pressed":u,onClick:()=>f(Oe=>!Oe),children:a("toolWrap")}),W&&s&&e.jsxs("button",{type:"button",className:"toolcall-kill",title:a("stopBashTip"),onClick:s,children:[e.jsx(ms,{}),e.jsx("span",{children:a("stopBash")})]}),!Pe&&t.name!=="read"&&!re&&!Ie.length&&e.jsx("button",{type:"button",disabled:!o,className:"toolcall-expand",title:a(b?"collapseCode":"expandCode"),onClick:()=>F(Oe=>!Oe),children:a(b?"collapseCode":"expandCode")}),!re&&!Ie.length&&e.jsx("button",{type:"button",className:"toolcall-expand",title:a("zoomCode"),"aria-label":a("zoomCode"),onClick:()=>ce(!0),children:Pe?e.jsx(Ro,{}):a("zoomCode")}),e.jsx("button",{type:"button",className:"toolcall-copy",title:a("copyArgs"),"aria-label":a(l?"copied":"copyArgs"),onClick:Ee,children:Pe?l?e.jsx(ts,{}):e.jsx(ws,{}):a(l?"copied":"copy")}),(re||Ie.length>0)&&e.jsxs("details",{className:"bash-card-more",children:[e.jsx("summary",{"aria-label":a("more"),children:"⋯"}),e.jsxs("div",{children:[e.jsx("button",{type:"button",onClick:()=>f(Oe=>!Oe),children:a("toolWrap")}),e.jsx("button",{type:"button",onClick:()=>ce(!0),children:a("zoomCode")}),e.jsx("button",{type:"button",onClick:()=>c(Oe=>!Oe),children:a(o?"collapseCode":"expandCode")})]})]}),!re&&!Ie.length&&e.jsx("button",{type:"button",className:"toolcall-toggle","aria-label":a(o?"collapseCode":"expandCode"),onClick:()=>c(Oe=>!Oe),children:o?e.jsx(Qt,{}):e.jsx(_t,{})})]}),o&&e.jsx("div",{className:`toolcall-body ${b?"expanded":""}`,children:V}),U&&e.jsx("div",{className:"modal-backdrop",onClick:()=>ce(!1),children:e.jsxs("div",{className:"toolcall-zoom",role:"dialog","aria-modal":"true",onClick:Oe=>Oe.stopPropagation(),children:[e.jsxs("div",{className:"toolcall-zoom-head",children:[e.jsx("span",{className:"toolcall-icon",children:Pe?e.jsx(ra,{"aria-hidden":"true"}):Ka(t.name)}),e.jsx("span",{className:"toolcall-name",children:t.name}),e.jsx("span",{className:"toolcall-spacer"}),e.jsx("button",{type:"button",className:"toolcall-zoom-close",title:a("closeZoom"),onClick:()=>ce(!1),children:e.jsx(Wt,{})})]}),e.jsx("div",{className:"toolcall-body toolcall-zoom-body",children:V})]})})]})}function Uh({args:t,cwd:n}){let s=null;try{s=JSON.parse(t)}catch{return e.jsx("pre",{children:t})}return typeof s.command!="string"?e.jsx("pre",{children:t}):e.jsxs("div",{className:"termline",children:[e.jsx("span",{className:"termline-icon",children:"$"}),e.jsx("code",{title:s.command,children:Vs(s.command,n)}),typeof s.timeout=="number"&&e.jsxs("span",{className:"termline-timeout",children:["⏱ ",s.timeout,"s"]})]})}function Sr(t){if(t===void 0)return"";const n=t/1e3;if(n<.1)return"<0.1s";if(n<60)return`${n.toFixed(1)}s`;const s=Math.floor(n/60),r=Math.round(n%60);return`${s}m ${String(r).padStart(2,"0")}s`}function Wh({run:t,wrap:n}){const s=et(),[r,i]=d.useState(()=>t.steps.findIndex(a=>a.state==="failed"));return e.jsx("div",{className:"bash-steps",children:t.steps.map((a,o)=>{const c=r===o,l=a.state==="done"?"✓":a.state==="failed"?"×":a.state==="running"?"⋯":"–";return e.jsxs("div",{className:`bash-step ${a.state}`,children:[e.jsxs("button",{type:"button",className:"bash-step-head","aria-expanded":c,onClick:()=>i(c?null:o),children:[e.jsx("span",{className:"bash-step-index",children:o+1}),e.jsx("span",{className:"bash-step-icon",children:l}),e.jsx("strong",{children:a.label}),e.jsx("code",{title:a.command,children:a.command}),e.jsx("span",{className:"bash-step-count",children:a.state==="no-match"?s("bashNoMatch"):a.state==="skipped"?s("bashSkipped"):a.state==="failed"?t.exitCode!==void 0?`exit ${t.exitCode}`:s("bashFailed"):a.state==="running"?s("running"):s("toolLineCount",{n:a.lineCount})}),e.jsx(_t,{className:c?"open":""})]}),c&&e.jsxs("div",{className:`bash-step-detail ${n?"wrap":""}`,children:[e.jsxs("div",{className:"bash-step-command",children:["$ ",a.command]}),e.jsx("pre",{children:a.output?a.output.split(`
229
+ `).map((p,u,f)=>e.jsxs("span",{className:Xs(p)?"error":"",children:[p,u<f.length-1?`
230
+ `:""]},u)):s(a.state==="no-match"?"bashNoMatch":"waitingOutput")})]})]},`${a.label}-${o}`)})})}function qh({diagnostics:t,output:n,wrap:s}){const r=et(),[i,a]=d.useState(!1);return e.jsxs("div",{className:"bash-failure",children:[e.jsx("div",{className:"bash-failure-list",children:t.map((o,c)=>e.jsxs("div",{className:"bash-failure-line",children:[e.jsxs("button",{type:"button",onClick:()=>window.dispatchEvent(new CustomEvent("pi-harness:open-tool-file",{detail:o})),children:[o.path,":",o.line,o.column?`:${o.column}`:""]}),e.jsx("span",{children:o.message})]},`${o.path}:${o.line}:${c}`))}),e.jsx("button",{type:"button",className:"bash-failure-toggle",onClick:()=>a(o=>!o),children:r(i?"collapseCode":"bashShowRaw")}),i&&e.jsx("pre",{className:s?"wrap":"",children:n})]})}function zh({output:t,wrap:n,cwd:s,searchOutput:r,compact:i=!1,command:a=""}){const o=et(),[c,l]=d.useState(!1),p=d.useRef(null),[u,f]=d.useState(!1);d.useEffect(()=>{const N=p.current;if(!N)return;const T=()=>f(!n&&N.scrollWidth-N.clientWidth-N.scrollLeft>1),y=new ResizeObserver(T);return y.observe(N),N.addEventListener("scroll",T),T(),()=>{y.disconnect(),N.removeEventListener("scroll",T)}},[t,c,n]);const k=t.replace(/\r\n/g,`
231
+ `).split(`
232
+ `);k.at(-1)===""&&k.pop();const j=lh(a,k),R=j&&!c&&k.length>6?[0,1,2,k.length-3,k.length-2,k.length-1]:ah(k,c),E=k.filter(Xs).length,A=R.some((N,T)=>T>0&&N>R[T-1]+1);return e.jsxs("div",{className:"bash-output",children:[j?e.jsxs("div",{className:"bash-output-label bash-git-summary",children:[e.jsxs("span",{children:["git status · ",o("bashStatusFiles",{n:j.files})]}),j.added>0&&e.jsxs("span",{className:"git-added",children:["· ",o("bashStatusAdded",{n:j.added})]}),j.modified>0&&e.jsxs("span",{className:"git-modified",children:["· ",o("bashStatusModified",{n:j.modified})]}),j.deleted>0&&e.jsxs("span",{className:"git-deleted",children:["· ",o("bashStatusDeleted",{n:j.deleted})]}),j.conflicts>0&&e.jsxs("span",{className:"git-deleted",children:["· ",o("bashStatusConflicts",{n:j.conflicts})]})]}):!i&&e.jsxs("div",{className:"bash-output-label",children:[e.jsxs("span",{children:[o("output")," · ",o("toolLineCount",{n:k.length}),E>0?` · ${o("bashLikelyErrorLines",{n:E})}`:""]}),s&&e.jsx("span",{title:s,children:o("toolRelativeTo",{path:s})})]}),e.jsx("div",{ref:p,className:`bash-output-lines ${n?"wrap":""} ${u?"has-overflow":""}`,children:R.map((N,T)=>{const y=k[N],{number:M,text:b}=ih(y,N,r==="mixed"?"mixed":r==="standalone"),F=/^(?:[.~/\w-]+\/)*[.\w-]+(?:\.[\w-]+)$/.test(b),U=F?b.lastIndexOf("/")+1:0,ce=j?Ml(b):null;return e.jsxs(d.Fragment,{children:[T>0&&N>R[T-1]+1&&e.jsxs("button",{type:"button",className:"bash-output-gap bash-output-gap-button",onClick:()=>l(!0),children:["⋯ ",o("toolMoreLines",{n:N-R[T-1]-1})]}),e.jsxs("div",{className:`bash-output-line${ce?" git-row":""}${Xs(y)?" error":""}`,children:[e.jsx("span",{className:"bash-line-number",children:M}),ce?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:`bash-git-status git-${ce.kind}`,children:ce.status}),e.jsx("span",{className:"bash-line-text",children:ce.path})]}):e.jsx("span",{className:"bash-line-text",children:F?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"bash-path-dir",children:b.slice(0,U)}),e.jsx("span",{className:U?"bash-path-file":"bash-root-file",children:b.slice(U)})]}):b||" "})]})]},N)})}),k.length>(j?6:8)&&(c||!A)&&e.jsx("button",{type:"button",className:"bash-output-more",onClick:()=>l(N=>!N),children:c?o("collapseCode"):o("toolMoreLines",{n:k.length-R.length})})]})}function vi(t){var s,r;return((s=t.view.result)==null?void 0:s.isError)||((r=t.view.status)==null?void 0:r.isError)?"err":t.view.result||t.view.status?"done":t.view.streaming?"running":"pending"}function Vh({lines:t,path:n}){const s=Os(n);return e.jsx("div",{className:"change-lines",children:t.map((r,i)=>e.jsxs("div",{className:`change-line ${r.marker==="+"?"add":r.marker==="-"?"del":"context"}`,children:[e.jsx("span",{className:"change-old",children:r.oldLine??""}),e.jsx("span",{className:"change-new",children:r.newLine??""}),e.jsx("span",{className:"change-marker",children:r.marker==="-"?"−":r.marker}),e.jsx("code",{className:"hljs",dangerouslySetInnerHTML:{__html:Zs(r.text,s)||"&#8203;"}})]},i))})}function Kh({change:t}){const n=et(),[s,r]=d.useState(!1),i=t.hunks.reduce((o,c)=>o+c.lines.length,0);let a=s?1/0:12;return e.jsxs("div",{className:"change-card-body",children:[t.error&&e.jsx("div",{className:"change-error",children:t.errorText.split(`
233
+ `).find(o=>o.trim())||n("changeFailed")}),t.empty?e.jsx("div",{className:"change-empty",children:t.error?n("changeNoOriginal"):t.kind==="write"?`${n("emptyFile")} (${t.path.split("/").at(-1)})`:n("changeNoDiff")}):t.hunks.map((o,c)=>{if(a<=0)return null;const l=o.lines.slice(0,a);return a-=l.length,e.jsxs("div",{className:"change-hunk",children:[e.jsxs("div",{className:"change-hunk-head",children:[t.error?t.kind==="write"?n("changeAttemptedWrite"):n("changeOriginal"):t.kind==="write"?n("changeWrittenLines",{n:t.added}):t.fromArguments?n("changeReplacement"):n("changeAtLine",{n:o.line}),o.functionName&&e.jsxs("span",{children:[" · ",o.functionName]})]}),e.jsx(Vh,{lines:l,path:t.path})]},c)}),t.diffTruncated&&e.jsx("div",{className:"change-empty",children:n("truncated")}),i>12&&e.jsx("button",{type:"button",className:"change-more",onClick:()=>r(o=>!o),children:s?n("collapseCode"):n("expandRemainingLines",{n:i-12})})]})}function Fl({item:t,compact:n=!1,retried:s=!1}){const r=et(),i=d.useMemo(()=>$s(t.block,t.view.result),[t.block,t.view.result]),[a,o]=d.useState(!n&&!s);if(d.useEffect(()=>{s&&o(!1)},[s]),d.useEffect(()=>{(i==null?void 0:i.kind)==="edit"&&i.empty&&!i.error&&t.view.result&&o(!1)},[i,t.view.result]),d.useEffect(()=>{const f=k=>{var j;((j=k.detail)==null?void 0:j.toolCallId)===t.block.id&&o(!0)};return window.addEventListener("pi:jump-tool",f),()=>window.removeEventListener("pi:jump-tool",f)},[t.block.id]),!i)return null;const c=s?"retried":vi(t),l=i.kind==="edit"&&i.empty&&!i.error&&c==="done",p=i.path||t.block.name,u=()=>window.dispatchEvent(new CustomEvent("pi-harness:open-tool-file",{detail:{path:i.path,...i.fromArguments?{}:{line:i.firstChangedLine}}}));return e.jsxs("div",{className:`change-card ${c}`,"data-tool-call-id":t.block.id,onMouseEnter:()=>window.dispatchEvent(new CustomEvent("pi:tool-hover",{detail:{toolCallId:t.block.id}})),onMouseLeave:()=>window.dispatchEvent(new CustomEvent("pi:tool-hover",{detail:{toolCallId:null}})),children:[e.jsxs("div",{className:"change-card-head",children:[e.jsxs("button",{type:"button",className:"change-card-toggle","aria-expanded":a&&!l,disabled:l,onClick:()=>o(f=>!f),children:[!l&&e.jsx(_t,{className:a?"open":""}),e.jsx("span",{className:"change-verb",children:t.block.name==="edit"?r("changeEdit"):r("changeWrite")}),e.jsx("code",{title:p,children:p})]}),e.jsx("span",{className:"change-counts",children:!i.error&&e.jsxs(e.Fragment,{children:[i.added>0&&e.jsxs("span",{className:"add",children:["+",i.added]}),i.removed>0&&e.jsxs("span",{className:"del",children:["−",i.removed]})]})}),e.jsxs("span",{className:`change-state ${c}`,children:[e.jsx("i",{}),r(s?"changeRetried":c==="err"?"error":c==="done"?"done":c==="running"?"running":"toolQueued")]}),i.path&&e.jsx("button",{type:"button",className:"change-open",onClick:u,children:r("changeOpen")}),e.jsxs("details",{className:"change-raw",children:[e.jsx("summary",{"aria-label":r("more"),children:e.jsx(Ms,{})}),e.jsxs("div",{children:[e.jsx("strong",{children:r("changeRawArgs")}),e.jsx("pre",{children:t.block.argumentsText}),i.output&&e.jsxs(e.Fragment,{children:[e.jsx("strong",{children:r("changeRawOutput")}),e.jsx("pre",{children:i.output})]})]})]})]}),a&&!l&&e.jsx(Kh,{change:i})]})}function Gh({items:t,retriedIds:n}){const s=et(),[r,i]=d.useState(!0);d.useEffect(()=>{const f=k=>{var R;const j=(R=k.detail)==null?void 0:R.toolCallId;j&&t.some(E=>E.block.id===j)&&i(!0)};return window.addEventListener("pi:jump-tool",f),()=>window.removeEventListener("pi:jump-tool",f)},[t]);const a=t.map(({block:f,view:k})=>$s(f,k.result)),o=a.reduce((f,k)=>f+((k==null?void 0:k.added)??0),0),c=a.reduce((f,k)=>f+((k==null?void 0:k.removed)??0),0),l=t.some(f=>vi(f)==="err"&&!(n!=null&&n.has(f.block.id))),p=t.every(f=>["done","err"].includes(vi(f))),u=t.every(f=>f.block.name==="edit")?s("changeEdit"):t.every(f=>f.block.name==="write")?s("changeWrite"):s("taskChanges");return e.jsxs("div",{className:`change-group ${l?"err":p?"done":"running"}`,children:[e.jsxs("button",{type:"button",className:"change-group-head","aria-expanded":r,onClick:()=>i(f=>!f),children:[e.jsx(_t,{className:r?"open":""}),e.jsxs("strong",{children:[u," ",t.length," ",s("taskFiles")]}),e.jsxs("span",{className:"change-counts",children:[o>0&&e.jsxs("span",{className:"add",children:["+",o]}),c>0&&e.jsxs("span",{className:"del",children:["−",c]})]}),e.jsx("span",{className:"change-state",children:s(l?"error":p?"done":"running")})]}),r&&e.jsx("div",{className:"change-group-items",children:t.map(f=>e.jsx(Fl,{item:f,compact:!0,retried:n==null?void 0:n.has(f.block.id)},f.block.id))})]})}const Jh=/<\/(?:ant)?think(?:ing)?>/gi,Qh=/(?:\s*<\/?(?:ant)?think(?:ing)?>\s*)+$/i;function Ja(t){let n=-1;for(const s of t.matchAll(Jh))n=s.index+s[0].length;return n}const Yh=/(?:\s*<\/(?:[||]DSML[||])?(?:parameter|invoke|tool_calls)>)+\s*$/i,Xh=/<\/?(?:ant)?think(?:ing)?>/gi;function Ol(t){let n=ni(t);const s=n.match(Yh),r=!!s&&/[||]DSML[||]/i.test(s[0]);r&&(t=t.slice(0,s.index).trimEnd(),n=n.slice(0,s.index).trimEnd());const i=n.match(Qh),a=i!=null&&Ja(n.slice(0,i.index))!==-1,o=a?t.slice(i.index).trim():"",c=a?t.slice(0,i.index):t,l=Ja(a?n.slice(0,i.index):n);if(l===-1)return r?{leaked:"",visible:t.trim()}:null;const p=[c.slice(0,l).trim(),o].filter(Boolean).join(`
234
+ `);return{leaked:ni(p).replace(Xh,"").trim().length>0?p:"",visible:c.slice(l).trim()}}const Zh="#ffffff",em=1568,tm=2*1024*1024;function os(t){return t.startsWith("image/")&&t!=="image/svg+xml"&&t!=="image/svg"}async function ki(t){if(!t.type.startsWith("image/"))return null;let n;try{n=await createImageBitmap(t,{imageOrientation:"from-image"})}catch{return null}try{const s=Math.min(1,em/Math.max(n.width,n.height)),r=Math.max(1,Math.round(n.width*s)),i=Math.max(1,Math.round(n.height*s)),a=t.type==="image/jpeg"||t.type==="image/jpg"?[["image/jpeg",.85],["image/jpeg",.6],["image/webp",.8]]:[["image/png",1],["image/jpeg",.85],["image/jpeg",.6]];let o=null;for(const[c,l]of a){const p=document.createElement("canvas");p.width=r,p.height=i;const u=p.getContext("2d");if(!u)continue;c!=="image/png"&&(u.fillStyle=Zh,u.fillRect(0,0,r,i)),u.drawImage(n,0,0,r,i);const f=p.toDataURL(c,l),k=f.match(/^data:([^;]+);base64,/),j=k?k[1]:c,R=f.replace(/^data:[^;]*;base64,/,""),E=Math.floor(R.length*3/4);if(o={data:R,mimeType:j,name:t.name,size:E},E<=tm)return o}return o}finally{n.close()}}function _l(t){return t.trim().replace(/^\d+[.)、.]\s*/,"").replace(/\s+/g," ")}function nm(t,n,s=32){const r=[];for(const i of[...t].sort((a,o)=>a.position-o.position)){const a=r.at(-1);a&&(i.position-a.positions.at(-1))*n<s?(a.ids.push(i.id),a.positions.push(i.position)):r.push({ids:[i.id],positions:[i.position]})}return r.map(({ids:i,positions:a})=>({ids:i,position:a.reduce((o,c)=>o+c,0)/a.length}))}function Nr(t){const n=t.split(`
235
+ `),s=[];let r=!1;for(let i=0;i<n.length;){const a=n[i];if(/^\s*(```|~~~)/.test(a)){r=!r,s.push(a),i++;continue}if(!r&&sm(n,i)){for(s.push("```ascii-table");i<n.length&&n[i].trim();)s.push(n[i++]);s.push("```");continue}if(!r&&/^\s*[│ ]*[├└]─{1,2}/.test(a)){const o=s.at(-1),c=o&&o.trim()&&o.length<100&&!/^\s*(?:[-*#>]|\d+[.)])\s/.test(o)?s.pop():void 0;for(s.push("```text"),c!==void 0&&s.push(c);i<n.length&&/^\s*[│ ]*[├└]─{1,2}/.test(n[i]);)s.push(n[i++]);s.push("```");continue}s.push(r?a:rm(a)),i++}return s.join(`
236
+ `)}function sm(t,n){var r;if(!((r=t[n])!=null&&r.trim())||!Qa(t[n+1]??""))return!1;let s=0;for(let i=n+1;i<t.length&&i<n+20&&t[i].trim();i++)Qa(t[i])&&s++;return s>=2}function Qa(t){var s;const n=t.replace(/\s/g,"");return n.length>=20&&/[─━═╌┄┈┉]/.test(n)&&(((s=n.match(/[─━═╌┄┈┉│┃┌┐└┘├┤┼┬┴╭╮╰╯]/g))==null?void 0:s.length)??0)/n.length>=.7}function rm(t){return t.includes("](")?t:t.split(/(`[^`]*`)/g).map(n=>n.startsWith("`")?n:n.replace(/(^|[\s(])((?:[\w.-]+\/)+[\w.-]+\.[A-Za-z0-9]+):([1-9]\d*)/g,(s,r,i,a)=>`${r}[${i}:${a}](#pi-file=${encodeURIComponent(i)}:${a})`)).join("")}const Er=t=>t<1e3?"":dh(t);function yi(t){return t.result?t.result.isError?"err":"ok":t.status&&!t.status.running?t.status.isError?"err":"ok":t.streaming?"run":"err"}function im({items:t,onKill:n,active:s=!1,title:r}){const i=et(),a=d.useContext(er),o=uh(t,y=>xi(jr(Ys(y.block.argumentsText)??"",a).command).title),[c,l]=d.useState(s);d.useEffect(()=>l(s),[s]);const[p,u]=d.useState(!1),[f,k]=d.useState(),j=o.map(y=>y[y.length-1]),R=j.filter(({view:y})=>yi(y)==="err").length,E=j.some(({view:y})=>yi(y)==="run"),A=R?"err":E?"run":"ok",N=t.map(({view:y})=>{var M;return(M=y.status)==null?void 0:M.durationMs}),T=N.every(y=>y!==void 0);return d.useEffect(()=>{const y=M=>{var F;const b=(F=M.detail)==null?void 0:F.toolCallId;t.some(({block:U})=>U.id===b)&&(l(!0),u(!0),k(b))};return window.addEventListener("pi:reveal-tool",y),()=>window.removeEventListener("pi:reveal-tool",y)},[t]),e.jsxs("section",{className:`bash-group ${A} ${c?"":"historical-step"}`,children:[(!s||t.length>1)&&e.jsxs("button",{type:"button",className:"bash-group-head","aria-expanded":c,onClick:()=>l(!c),children:[e.jsx("span",{className:`bash-state ${A}`,"aria-label":i(R?"error":E?"running":"done"),children:R?"✗":E?"●":"✓"}),e.jsx("strong",{children:c?i(E?"bashGroupRunning":"bashGroupCount",{n:t.length}):r||xi(jr(Ys(t[0].block.argumentsText)??"",a).command).title}),!c&&e.jsxs("span",{children:[" · ",i("changesCommands",{n:t.length})]}),R>0&&e.jsx("span",{className:"bash-state err",children:i("bashGroupFailed",{n:R})}),T&&Er(N.reduce((y,M)=>y+(M??0),0))&&e.jsx("span",{className:"bash-group-duration",children:Er(N.reduce((y,M)=>y+(M??0),0))}),c?e.jsx(Qt,{}):e.jsx(_t,{})]}),(c||s&&t.length===1)&&e.jsxs("div",{className:"bash-group-items",children:[!p&&o.length>8&&e.jsx("button",{type:"button",className:"bash-group-more",onClick:()=>u(!0),children:i("bashGroupEarlier",{n:o.length-8})}),(p?o:o.slice(-8)).map(y=>y.length===1?e.jsx(Jr,{...y[0],onKill:n,revealed:f===y[0].block.id},y[0].block.id):e.jsx(Jr,{...y[y.length-1],onKill:n,revealed:y.some(M=>M.block.id===f),attempts:y.length,history:e.jsx("div",{className:"bash-attempt-history",children:y.slice(0,-1).map(M=>e.jsx(Jr,{...M,revealed:M.block.id===f,historical:!0},M.block.id))})},y[0].block.id))]})]})}function Jr({block:t,view:n,onKill:s,revealed:r,messageId:i,attempts:a,historical:o,history:c}){var $,$e,L,q,fe,je,ne,Pe;const l=et(),p=d.useContext(er),u=o&&!n.result?"empty":yi(n),{locale:f}=ns(),[k,j]=d.useState(u==="err"),[R,E]=d.useState(!1),[A,N]=d.useState(null),T=d.useRef();d.useEffect(()=>()=>clearTimeout(T.current),[]),d.useEffect(()=>{(u==="err"||r)&&j(!0)},[u,r]),d.useEffect(()=>{const B=we=>{var re,Ie;((re=we.detail)==null?void 0:re.toolCallId)===t.id&&(j(!0),(Ie=we.detail)!=null&&Ie.search&&E(!0))};return window.addEventListener("pi:reveal-tool",B),()=>window.removeEventListener("pi:reveal-tool",B)},[t.id]);const y=Ys(t.argumentsText)??t.argumentsText??"bash",M=jr(y,p),b=xi(M.command,f==="en"),F=M.command.trimEnd().split(/\r?\n/),U=(($=n.result)==null?void 0:$.content.map(B=>B.type==="text"&&typeof B.text=="string"?B.text:"").join(""))??n.liveOutput??"",ce=U?U.replace(/\r\n/g,`
237
+ `).replace(/\n$/,"").split(`
238
+ `):[],ie=($e=n.result)==null?void 0:$e.details,W=(ie==null?void 0:ie.exitCode)??((L=n.status)==null?void 0:L.exitCode),ve=(ie==null?void 0:ie.fullOutputPath)||((q=ie==null?void 0:ie.truncation)==null?void 0:q.truncated)||((fe=n.result)==null?void 0:fe.content.some(B=>B.type==="text"&&B.truncated)),Se=async B=>{try{await navigator.clipboard.writeText(B==="command"?y:U),N(B),clearTimeout(T.current),T.current=setTimeout(()=>N(null),1500)}catch{N(null)}};return e.jsxs("div",{className:`bash-row ${u}`,"data-tool-call-id":t.id,"data-msg-id":i,onMouseEnter:()=>window.dispatchEvent(new CustomEvent("pi:tool-hover",{detail:{toolCallId:t.id}})),onMouseLeave:()=>window.dispatchEvent(new CustomEvent("pi:tool-hover",{detail:{toolCallId:null}})),children:[e.jsxs("button",{type:"button",className:"bash-row-head",title:y,"aria-expanded":k,onClick:()=>j(!k),children:[e.jsx("span",{className:`bash-state ${u}`,"aria-label":l(u==="run"?"running":u==="err"?"error":"done"),children:u==="run"?"●":u==="err"?"✗":u==="empty"?"−":"✓"}),e.jsx("span",{className:"bash-readable-title",children:b.title}),a&&e.jsx("span",{className:"bash-attempt-count",children:l("commandAttempts",{n:a})}),b.title!==gi(b.command)&&e.jsx("code",{className:"bash-command-secondary",children:b.command}),F.length>1&&e.jsx("span",{className:"bash-extra-lines",children:l("bashExtraLines",{n:F.length-1})}),e.jsxs("span",{className:"bash-row-stats",children:[u==="run"?l("running"):W!==void 0&&u==="err"?l("bashExitCode",{n:W}):l("toolLineCount",{n:ce.length}),((je=n.status)==null?void 0:je.durationMs)!==void 0&&Er(n.status.durationMs)?` · ${Er(n.status.durationMs)}`:""]}),k?e.jsx(Qt,{}):e.jsx(_t,{})]}),k&&e.jsxs("div",{className:"bash-row-body",children:[M.directory&&e.jsx("div",{className:"bash-row-directory",children:l("bashGroupCwd",{path:M.directory})}),e.jsx("pre",{className:"bash-full-command",children:y}),ce.length>0&&e.jsx("div",{className:"bash-numbered-output","data-msg-id":(ne=n.result)==null?void 0:ne.id,children:(R?ce:ce.slice(0,6)).map((B,we)=>e.jsxs("div",{className:`bash-numbered-line${Xs(B)?" error":/(?:\bPASS\b|\bpassed\b|\bsummary\b)/i.test(B)?" important":""}`,children:[e.jsx("span",{"aria-hidden":"true",children:we+1}),e.jsx("code",{children:B||" "})]},we))}),ce.length>6&&e.jsx("button",{type:"button",className:"bash-group-more",onClick:()=>E(!R),children:R?l("collapseCode"):l("bashRemainingLines",{n:ce.length-6})}),e.jsxs("div",{className:"bash-row-actions",children:[e.jsx("button",{type:"button",onClick:()=>void Se("command"),children:l(A==="command"?"copied":"bashCopyCommand")}),e.jsx("button",{type:"button",disabled:!U,onClick:()=>void Se("output"),children:l(A==="output"?"copied":"bashCopyOutput")}),ve&&((Pe=n.result)==null?void 0:Pe.toolOutputUrl)&&e.jsx(Js,{url:n.result.toolOutputUrl}),e.jsx("button",{type:"button",title:l("bashOpenTerminalHint"),onClick:()=>window.dispatchEvent(new CustomEvent("pi-harness:plugin-run-command",{detail:{title:gi(F[0]),command:y}})),children:l("bashOpenTerminal")}),u==="run"&&s&&e.jsx("button",{type:"button",onClick:s,children:l("stopBash")})]}),c]})]})}function am(t,n){if(t.kind==="replaced")return n("planReplaced",{id:t.planId,revision:t.revision});if(t.kind==="status")return n("planStatusChanged",{status:n(t.status==="active"?"running":t.status==="completed"?"done":t.status==="failed"?"error":"cancelled")});const s={added:"todoItemAdded",updated:"todoItemUpdated",pending:"todoItemPending",started:"todoItemStarted",completed:"todoItemCompleted",removed:"todoItemDeleted"};return t.position?n(s[t.kind],{n:t.position}):`${n("todoRemoved")}: ${t.title}`}function om({view:t,toolCallId:n}){const s=et(),r=t.changes.map(a=>am(a,s)).join(s("todoChangeSeparator"));if(t.kind==="update")return e.jsxs("div",{className:"todo-update","data-tool-call-id":n,children:[e.jsx("span",{className:"todo-update-dot","aria-hidden":"true"}),e.jsx("span",{children:r||s("planRecorded")}),e.jsx("button",{type:"button",onClick:()=>window.dispatchEvent(new CustomEvent("pi:jump-tool",{detail:{...t.target,todoItemIds:t.changes.flatMap(a=>"stepId"in a?[a.stepId]:[])}})),children:s("todoView")})]});const i=t.snapshot;return e.jsxs("section",{className:"todo-checklist","data-tool-call-id":n,"aria-label":s("taskPlanSource"),children:[e.jsxs("header",{className:"todo-checklist-head",children:[e.jsx("strong",{children:i.title}),e.jsx("span",{children:s("todoCounts",{total:i.steps.length,completed:i.completedStepIds.length})}),e.jsx("span",{className:"todo-checklist-state",children:s(i.status==="active"?"planActive":i.status==="completed"?"done":i.status==="failed"?"error":"cancelled")})]}),e.jsx("ol",{className:"todo-checklist-items",children:i.steps.map(a=>{const o=i.completedStepIds.includes(a.id)?"completed":i.currentStepId===a.id?"in_progress":"pending";return e.jsxs("li",{className:`todo-checklist-item ${o}`,"data-todo-item-id":a.id,tabIndex:-1,children:[e.jsx("span",{className:"todo-checklist-mark","aria-hidden":"true",children:o==="completed"?"✓":""}),e.jsx("div",{children:a.detail?e.jsxs("details",{children:[e.jsx("summary",{children:a.title}),e.jsx("p",{children:a.detail})]}):a.title})]},a.id)})}),e.jsxs("p",{className:"task-outline-criteria",children:[s("taskCompletionCriteria"),":",i.completionCriteria]}),r&&e.jsx("p",{className:"todo-update",children:r})]})}const lm=20*1024*1024;function Ls(t){return t.type==="text"&&typeof t.text=="string"?t:null}function Hl(t){return t.type==="thinking"&&typeof t.thinking=="string"?t:null}function Ts(t){return t.type==="toolCall"&&typeof t.id=="string"&&typeof t.name=="string"?t:null}function Bl(t){return t.type==="image"&&typeof t.dataUrl=="string"?t:null}function Ul(t){return t.type==="bash"&&typeof t.command=="string"?t:null}function cm(t){return t.imageData?"image":t.uploadPath?"upload":t.fileData?"file":"path"}function dm(t,n){if(t.editorSnapshot)return`${t.path} · ${n(t.editorSnapshot.dirty?"currentFileDraft":"currentFileLabel")}`;if(t.imageData)return n("attachImage",{name:t.name??"image"});if(t.uploadPath)return n("attachFile",{name:t.name??t.uploadPath});if(t.fileData)return n("attachFile",{name:t.name??"file"});const s=t.path.split("/").pop()??t.path;return t.mode==="lines"&&t.lines?n("attachLines",{path:s,start:t.lines.start,end:t.lines.end}):t.mode==="reference"?n("refOnly",{path:s}):n("attachContent",{path:s})}const Qr=d.memo(function({incident:n,recovery:s,toolsRunning:r,bashActive:i,bashTitle:a,toolMessageIds:o,planViews:c,continuation:l,conversationId:p,message:u,toolResults:f,retriedEditIds:k,liveOutputs:j,toolStatuses:R,streaming:E,isLast:A,onEdit:N,onKillBash:T,onCollapse:y,questionAttachments:M,qnIndex:b,qnActive:F,onJump:U,thinkingWrap:ce,toolsWrap:ie}){var Ce;const W=et(),ve=Ac(),[Se,$]=d.useState(!1),[$e,L]=d.useState(""),[q,fe]=d.useState([]),[je,ne]=d.useState(!1),[Pe,B]=d.useState(null),we=u.role==="user"&&u.content.length>0&&u.content.every(ye=>ye.type==="text"),re=d.useRef(null),[Ie,_]=d.useState(!1),[le,O]=d.useState(!1),[ge,pe]=d.useState(0);d.useLayoutEffect(()=>{if(!we||Se||Ie)return;const ye=re.current;if(!ye)return;const ze=()=>{O(ye.scrollHeight>ye.clientHeight+2);const ct=u.content.map(Oe=>{var ee;return((ee=Ls(Oe))==null?void 0:ee.text)??""}).filter(Boolean).join(`
239
+ `).split(/\r?\n/).length,tt=parseFloat(getComputedStyle(ye).lineHeight)||22;pe(Math.max(ct,Math.ceil(ye.scrollHeight/tt)))},Ze=new ResizeObserver(ze);return Ze.observe(ye),ze(),()=>Ze.disconnect()},[we,u.content,Se,Ie]);const Ae=ye=>{B(ye),window.setTimeout(()=>B(ze=>ze===ye?null:ze),4e3)};if(u.role==="toolResult")return null;if(u.origin==="auto-reminder")return e.jsx("div",{className:"tool-reminder-event","data-msg-id":u.id,title:u.content.map(ye=>ye.type==="text"?ye.text:"").join(`
240
+ `),children:e.jsxs("span",{children:["↻ ",W("toolReminderEvent"),u.timestamp?` · ${Za(u.timestamp)}`:""]})});if(u.role==="system"&&!u.content.some(ye=>ye.type==="text"?typeof ye.text=="string"&&ye.text.trim():ye.type!=="thinking"))return null;const ae=u.role==="custom"&&u.customType==="file",Te=u.questionText??u.content.map(ye=>{var ze;return((ze=Ls(ye))==null?void 0:ze.text)??""}).filter(Boolean).join(`
241
+ `),Z=u.role==="user"?As(Te):null,Fe=_l(Z?Z.userMessage??`skill:${Z.name}`:Te),z=u.role==="user"&&!E&&!!N,G=async ye=>{const ze=[];for(const Ze of ye){if(!os(Ze.type))continue;const Qe=await ki(Ze);Qe&&ze.push({path:"",imageData:Qe.data,mimeType:Qe.mimeType,name:Qe.name})}ze.length>0&&fe(Ze=>[...Ze,...ze])},J=async ye=>{if(ye.size>lm){Ae(W("fileTooLarge",{name:ye.name,size:20}));return}let ze;try{ze=(await new Promise((Qe,ct)=>{const tt=new FileReader;tt.onload=()=>Qe(tt.result),tt.onerror=()=>ct(tt.error??new Error("read failed")),tt.readAsDataURL(ye)})).replace(/^data:[^;]*;base64,/,"")}catch{Ae(W("fileLoadFailed",{name:ye.name}));return}fe(Ze=>[...Ze,{path:"",fileData:ze,name:ye.name,size:ye.size,mimeType:ye.type||void 0}])},Ee=async ye=>{const ze=[];for(const Ze of ye)os(Ze.type)?ze.push(Ze):J(Ze);ze.length>0&&await G(ze)},V=()=>{L(Z?`/skill:${Z.name}${Z.userMessage?` ${Z.userMessage}`:""}`:u.questionText??u.content.map(ye=>{var ze;return((ze=Ls(ye))==null?void 0:ze.text)??""}).filter(Boolean).join(`
242
+ `)),fe(M??[]),$(!0)},Le=ye=>{const ze=$e.trim();ze&&(N==null||N(u.id,ze,q.length>0?q:void 0,{entryId:u.entryId,newSession:ye}),$(!1))},xe=u.role==="custom"&&(u.customType==="goal-review"||u.customType==="goal-wizard"),be=u.role==="custom"&&u.customType==="goal-wizard",nt=ye=>{const ze=[],Ze=Qe=>{var ct,tt;return{result:f.get(Qe.id),nestedCalls:Dl(Qe.id,R),liveOutput:(ct=j.get(Qe.id))==null?void 0:ct.text,codemode:(tt=j.get(Qe.id))==null?void 0:tt.codemode,status:R.get(Qe.id),streaming:E}};for(let Qe=0;Qe<u.content.length;Qe++){const ct=u.content[Qe];if(ye&&ct.type==="text")continue;const tt=Ts(ct),Oe=tt&&(c==null?void 0:c.get(tt.id));if(tt&&Oe){ze.push(e.jsx(om,{toolCallId:tt.id,view:Oe},tt.id));continue}if((tt==null?void 0:tt.name)==="write"||(tt==null?void 0:tt.name)==="edit"){const ee=[tt];for(;Qe+1<u.content.length;){const w=Ts(u.content[Qe+1]);if((w==null?void 0:w.name)!=="write"&&(w==null?void 0:w.name)!=="edit")break;ee.push(w),Qe++}const We=ve?ee.filter(w=>{var H;return!f.get(w.id)||((H=f.get(w.id))==null?void 0:H.isError)}):ee;We.length>=3?ze.push(e.jsx(Gh,{items:We.map(w=>({block:w,view:Ze(w)})),retriedIds:k},`${u.id}-${tt.id}`)):ze.push(...We.map(w=>e.jsx(Fl,{item:{block:w,view:Ze(w)},retried:k==null?void 0:k.has(w.id)},`${u.id}-${w.id}`)));continue}if((tt==null?void 0:tt.name)==="bash"){const ee=[tt];for(;Qe+1<u.content.length;){const We=Ts(u.content[Qe+1]);if((We==null?void 0:We.name)!=="bash")break;ee.push(We),Qe++}ze.push(e.jsx(im,{active:i??r??E,title:a,items:ee.map(We=>({block:We,view:{...Ze(We),streaming:r??E},messageId:(o==null?void 0:o.get(We.id))??u.id})),onKill:T},tt.id));continue}if((tt==null?void 0:tt.name)==="read"){const ee=[tt];for(;Qe+1<u.content.length;){const We=Ts(u.content[Qe+1]);if((We==null?void 0:We.name)!=="read")break;ee.push(We),Qe++}ze.push(e.jsx(Eh,{items:ee.map(We=>({block:We,view:Ze(We)})),wrap:ie},`${u.id}-${tt.id}`));continue}if((tt==null?void 0:tt.name)==="grep"){ze.push(e.jsx(Rh,{block:tt,view:Ze(tt),wrap:ie},`${u.id}-${tt.id}`));continue}ze.push(e.jsx(Xa,{suppressLeak:!!n,block:ct,user:u.role==="user",toolResults:f,liveOutputs:j,toolStatuses:R,streaming:E,isLast:A&&Qe===u.content.length-1,onKillBash:T,toolsWrap:ie,thinkingWrap:ce},`${u.id}-${Qe}`))}return ze};return e.jsxs("div",{className:`msg msg-${u.role}${xe?" msg-goal-review":""}${l?" msg-continuation":""}`,"data-role":u.role,"data-msg-id":u.id,children:[e.jsxs("div",{className:"msg-meta",children:[e.jsx("span",{className:"msg-role",children:u.role==="custom"?be?W("goalWizardCard"):xe?W("goalBarTitle"):u.customType==="file"?W("attachment"):`${W("plugin")} · ${u.customType??W("unknown")}`:Wl(u.role,W)}),u.model&&e.jsx("span",{className:"msg-model",children:u.model}),u.timestamp&&e.jsx("span",{className:"msg-time",title:new Date(u.timestamp).toLocaleString(),children:Za(u.timestamp)}),y&&e.jsxs("button",{type:"button",className:"msg-collapse-btn",title:W("collapseMsg"),onClick:()=>y(u.id),children:[e.jsx(Qt,{})," ",W("collapseMsg")]}),b!==void 0&&U&&e.jsxs("button",{type:"button",className:`qn-tag ${F?"active":""}`,title:`${b+1}. ${Fe}`,"aria-label":`${b+1}. ${Fe}`,onClick:()=>U(u.id),children:[e.jsx("span",{className:"qn-tag-bar"}),e.jsx("span",{className:"qn-tag-idx",children:b+1})]})]}),(u.label||u.siblings)&&e.jsxs("div",{className:"message-tree-controls",children:[u.label&&e.jsx("span",{className:"tree-label",children:u.label}),u.siblings&&p&&e.jsxs("span",{className:"tree-siblings",children:[e.jsx("button",{"aria-label":W("treePrevious"),disabled:!u.siblings.prevTarget||E,onClick:()=>wa(p,u.siblings.prevTarget),children:"‹"}),e.jsxs("span",{children:[u.siblings.index," / ",u.siblings.count]}),e.jsx("button",{"aria-label":W("treeNext"),disabled:!u.siblings.nextTarget||E,onClick:()=>wa(p,u.siblings.nextTarget),children:"›"})]})]}),e.jsx("div",{className:"msg-body",children:Se?e.jsxs("div",{className:`msg-editor${je?" drag-over":""}`,onDragOver:ye=>{ye.preventDefault(),ye.stopPropagation(),ne(!0)},onDragLeave:ye=>{ye.currentTarget.contains(ye.relatedTarget)||ne(!1)},onDrop:ye=>{var ze;ye.preventDefault(),ye.stopPropagation(),ne(!1),Ee(Array.from(((ze=ye.dataTransfer)==null?void 0:ze.files)??[]))},children:[q.length>0&&e.jsx("div",{className:"msg-editor-images",children:q.map((ye,ze)=>{var Qe;const Ze=cm(ye);return e.jsxs("span",{className:`msg-editor-img ${Ze==="image"?"":"file-chip"}`,title:dm(ye,W),children:[Ze==="image"?e.jsx("img",{src:`data:${ye.mimeType??"image/png"};base64,${ye.imageData}`,alt:ye.name}):e.jsxs("span",{className:"msg-editor-file",children:[e.jsx("span",{className:"msg-editor-file-icon",children:Ze==="path"?ye.mode==="reference"?"🔗":"📎":"📄"}),e.jsx("span",{className:"msg-editor-file-name",children:ye.name??((Qe=ye.path)==null?void 0:Qe.split("/").pop())})]}),e.jsx("button",{type:"button",className:"msg-editor-img-remove",title:W("removeAttachment"),onClick:()=>fe(ct=>ct.filter((tt,Oe)=>Oe!==ze)),children:e.jsx(Wt,{})})]},`${ye.name??ye.path??"att"}-${ze}`)})}),Pe&&e.jsx("div",{className:"msg-editor-notice",children:Pe}),e.jsx("textarea",{className:"msg-editor-input",value:$e,autoFocus:!0,placeholder:W("editPlaceholder"),rows:Math.max(2,Math.min(10,$e.split(`
243
+ `).length+1)),onChange:ye=>L(ye.target.value),onPaste:ye=>{var Ze;const ze=[];for(const Qe of((Ze=ye.clipboardData)==null?void 0:Ze.items)??[])if(Qe.kind==="file"&&os(Qe.type)){const ct=Qe.getAsFile();ct&&ze.push(ct)}ze.length!==0&&(ye.preventDefault(),G(ze))},onKeyDown:ye=>{ye.key==="Enter"&&(ye.metaKey||ye.ctrlKey)?(ye.preventDefault(),Le()):ye.key==="Escape"&&$(!1)}}),e.jsxs("div",{className:"msg-editor-actions",children:[e.jsxs("details",{className:"tree-edit-menu",children:[e.jsx("summary",{children:W("treeEditOptions")}),e.jsx("button",{disabled:!$e.trim(),onClick:()=>Le(!0),children:W("treeFork")})]}),e.jsxs("span",{className:"msg-editor-hint",children:[e.jsx(Io,{})," ",W("editAttachmentHint")]}),e.jsx("button",{type:"button",className:"chip",onClick:()=>$(!1),children:W("cancel")}),e.jsxs("button",{type:"button",className:"chip primary",disabled:!$e.trim(),title:W("reaskFromHere"),onClick:()=>Le(),children:[e.jsx(da,{})," ",W("reaskFromHere")]})]})]}):e.jsxs(e.Fragment,{children:[u.errorMessage&&e.jsx("div",{className:"msg-error",children:u.errorMessage}),ae?e.jsx(um,{message:u}):Z?e.jsxs(e.Fragment,{children:[e.jsx(hm,{block:Z}),Z.userMessage&&e.jsx("div",{className:"msg-text",children:e.jsx(On,{text:Nr(Z.userMessage),fileLinks:!0})}),nt(!0)]}):u.role==="user"?e.jsx("div",{ref:re,className:`user-message-content${we&&!Ie?" collapsed":""}`,children:u.questionText!==void 0?e.jsxs(e.Fragment,{children:[e.jsx(On,{text:Nr(u.questionText),fileLinks:!0}),u.content.filter(ye=>ye.type==="image").map((ye,ze)=>e.jsx(Xa,{block:ye,user:!0,toolResults:f,liveOutputs:j,toolStatuses:R,streaming:E,isLast:!1},ze))]}):nt(!1)}):nt(!1),n&&n.last.id===u.id&&n.state==="stopped"?e.jsx(gh,{incident:n,model:u.model||n.first.model||W("unknown"),recovery:(s==null?void 0:s.messageId)===u.id?s:void 0}):(n==null?void 0:n.leaks.some(ye=>ye.id===u.id))&&e.jsxs("div",{className:"tool-unexecuted-inline",children:[e.jsx("span",{children:"✗"})," ",W("toolUnexecutedInline"),n.reminders.length>0&&e.jsxs("small",{children:[" · ",W("toolAutoReminded")]})]}),u.role==="user"&&((Ce=u.userAttachments)==null?void 0:Ce.map((ye,ze)=>e.jsxs("details",{className:"user-attachment-card",children:[e.jsx("summary",{children:ye.path}),e.jsx("pre",{children:ye.preview})]},ze))),we&&le&&!Se&&!Z&&e.jsx("button",{type:"button",className:"user-message-expand",onClick:()=>_(ye=>!ye),children:Ie?W("collapseCode"):W("expandAllLines",{n:ge})})]})}),z&&!Se&&e.jsx("div",{className:"msg-actions",children:e.jsxs("button",{type:"button",className:"msg-action",title:W("editReaskTip"),onClick:V,children:[e.jsx(da,{})," ",W("editReask")]})})]})});function um({message:t}){var j;const n=et(),[s,r]=d.useState(!1),i=t.details??{},a=i.name??i.path??n("attachment"),o=i.type==="folder",c=i.mode==="reference",l=i.mode==="bridged",p=t.content.filter(R=>R.type==="text").map(R=>R.text).join(`
244
+ `),u=((j=i.editorSnapshot)==null?void 0:j.text)??pm(p),f=t.content.find(R=>R.type==="image"),k=u.split(`
245
+ `).length;return e.jsxs("div",{className:`attachcard ${c?"reference":""}`,children:[e.jsxs("button",{type:"button",className:"attachcard-head",onClick:()=>r(R=>!R),children:[e.jsx("span",{className:"attachcard-icon",children:o?"📁":"📎"}),e.jsx("span",{className:"attachcard-name",children:a}),i.editorSnapshot&&e.jsx("span",{className:"attachcard-mode",children:n(i.editorSnapshot.dirty?"currentFileDraft":"currentFileLabel")}),i.path&&e.jsx("span",{className:"attachcard-path",children:i.path}),e.jsx("span",{className:`attachcard-mode ${i.mode==="lines"?"lines":c?"ref":l?"bridged":"inline"}`,children:c?o?n("folderRefShort"):`${n("refOnlyShort")} · ${Ya(i.size)}`:l?n("bridgedVision"):f?n("image"):i.mode==="lines"?n("inlineLinesRange",{start:i.startLine??1,end:i.endLine??i.lines??1}):n("inlineLines",{n:i.lines??k})}),!c&&(s?e.jsx(Qt,{}):e.jsx(_t,{}))]}),!c&&s&&(l?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"attachcard-bridgenote",children:n("bridgedVisionDetail")}),(f==null?void 0:f.dataUrl)&&e.jsx("div",{className:"attachcard-image",children:e.jsx("img",{src:f.dataUrl,alt:a})}),u&&e.jsx("pre",{className:"attachcard-content",children:u})]}):f!=null&&f.dataUrl?e.jsx("div",{className:"attachcard-image",children:e.jsx("img",{src:f.dataUrl,alt:a})}):e.jsx("pre",{className:"attachcard-content",children:u})),c&&e.jsx("div",{className:"attachcard-refnote",children:o?n("folderNotExpanded"):n("fileNotExpanded",{size:Ya(i.size)})})]})}function Ya(t){return t===void 0?"":t>=1024*1024?`${(t/(1024*1024)).toFixed(1)} MB`:t>=1024?`${Math.round(t/1024)} KB`:`${t} B`}function pm(t){const n=t.match(/^\s*<file path="[^"]*"(?:\s+lines="[^"]*")?>\s*```\s*\n?([\s\S]*?)\n?```\s*<\/file>\s*$/);if(n)return n[1].trim();const s=t.match(/^\s*<vision-bridge>\s*([\s\S]*?)\s*<\/vision-bridge>\s*$/);return s?s[1].trim():t.trim()}function hm({block:t}){const n=et(),[s,r]=d.useState(!1),i=Al(t.content);return e.jsxs("div",{className:`skillcard${s?" expanded":""}`,children:[e.jsxs("button",{type:"button",className:"skillcard-head",onClick:()=>r(a=>!a),title:t.location,children:[e.jsx("span",{className:"skillcard-icon","aria-hidden":"true",children:"◆"}),e.jsxs("span",{className:"skillcard-name",children:[n("skillLabel")," · ",t.name]}),s&&e.jsx("span",{className:"skillcard-path",children:t.location}),e.jsxs("span",{className:"skillcard-action",children:[s?e.jsx(Ao,{}):e.jsx(Qt,{}),n(s?"collapseMsg":"expandMsg")]})]}),s&&e.jsxs("div",{className:"skillcard-body",children:[i.fields.length>0&&e.jsx("dl",{className:"toolcall-frontmatter",children:i.fields.map(({name:a,value:o})=>e.jsxs("div",{children:[e.jsx("dt",{children:a}),e.jsx("dd",{children:o})]},a))}),e.jsx(On,{text:i.body})]})]})}function Xa({suppressLeak:t,block:n,user:s,toolResults:r,liveOutputs:i,toolStatuses:a,streaming:o,isLast:c,onKillBash:l,thinkingWrap:p,toolsWrap:u}){const f=et(),k=Ls(n);if(k){const N=o&&c,T=!s&&(!o||t)?Ti(k.text):null,y=T?T.before:k.text,M=s?null:Ol(y),b=M?M.visible:y;return!b.trim()&&!(M!=null&&M.leaked.trim())&&!T&&!k.truncated?null:e.jsxs("div",{className:`msg-text${!s&&!c&&Pl(b)?" process-narration":""}`,children:[(M==null?void 0:M.leaked)&&!t&&e.jsx(xh,{text:M.leaked}),b&&(N?e.jsx(jh,{text:s?Nr(b):b}):e.jsx(On,{text:s?Nr(b):b,fileLinks:s})),k.truncated&&e.jsx("div",{className:"trunc-note",children:f("truncated")})]})}const j=Hl(n);if(j)return j.thinking.trim()?e.jsx(el,{thinking:j.thinking,durationMs:j.durationMs,streaming:o&&c,wrap:p}):null;const R=Ts(n);if(R){const N=r.get(R.id),T=i.get(R.id),y={nestedCalls:Dl(R.id,a),result:N,liveOutput:T==null?void 0:T.text,codemode:T==null?void 0:T.codemode,streaming:o,status:a.get(R.id)};return e.jsx(Wi,{block:R,view:y,onKillBash:l,wrap:u})}const E=Bl(n);if(E&&E.dataUrl)return e.jsx("div",{className:"msg-image",children:e.jsx("img",{src:E.dataUrl,alt:"attachment"})});const A=Ul(n);return A?e.jsxs("div",{className:"bashblock",children:[e.jsxs("div",{className:"bashblock-command",children:[e.jsx("span",{className:"bashblock-prompt",children:"$"}),e.jsx("code",{children:A.command}),A.exitCode!==void 0&&e.jsx("span",{className:`bashblock-exit ${A.exitCode===0?"ok":"err"}`,children:f("exitCode",{code:A.exitCode})}),A.cancelled&&e.jsx("span",{className:"bashblock-exit err",children:f("cancelled")})]}),A.output&&e.jsx("pre",{className:"bashblock-output",children:A.output}),A.truncated&&e.jsx("div",{className:"trunc-note",children:f("outputTruncated")})]}):null}function Wl(t,n){switch(t){case"user":return n("role.user");case"assistant":return n("role.assistant");case"toolResult":return n("role.tool");case"bashExecution":return n("role.bash");case"branchSummary":return n("role.branch");case"compactionSummary":return n("role.compaction");default:return t}}function Za(t){const n=new Date(t),s=String(n.getHours()).padStart(2,"0"),r=String(n.getMinutes()).padStart(2,"0");return`${s}:${r}`}function mm(t,n,s){const r=new Map,i=new Map;for(const a of t)if(a.role==="assistant")for(const o of a.content){if(o.type!=="toolCall"||o.name!=="plan"||typeof o.id!="string")continue;const c=n.get(o.id),l=c==null?void 0:c.planSnapshot;if(!l||c!=null&&c.isError)continue;for(const u of l.changes)if(u.kind==="replaced"){const f=i.get(`${s}:${u.planId}`);f&&(f.snapshot={...f.snapshot,status:"cancelled",currentStepId:null})}let p=i.get(`${s}:${l.planId}`);p?(p.snapshot=l,r.set(o.id,{kind:"update",target:p.target,changes:l.changes})):(p={kind:"card",target:{messageId:a.id,toolCallId:o.id},snapshot:l,changes:l.changes.filter(u=>u.kind==="replaced")},i.set(`${s}:${l.planId}`,p),r.set(o.id,p))}return r}function fm(t,n=!0){var r;const s=n?((r=Ol(t))==null?void 0:r.visible)??t:t;return fs(s).replace(/`+([^`]+)`+/g,"$1").replace(/\[([^\]]+)\]\([^)]*\)/g,"$1").replace(/\*\*([^*]+)\*\*|__([^_]+)__/g,(i,a,o)=>a??o).replace(/\*([^*]+)\*/g,"$1").replace(/^#{1,6}\s+/,"")}function gm(t,n,s,r=new Set,i=new Set){const a=new Map,o=new Set;let c=-1,l=[];const p=()=>{c>=0&&l.length>0&&a.set(c,l),c=-1,l=[]},u=Math.min(n,t.length);for(let f=0;f<u;f++){const k=t[f];if(k.role==="toolResult"||k.origin==="auto-reminder"||i.has(k.id)){o.add(f);continue}if(r.has(f)&&p(),s.has(k.id)||_i(k)||Hi(k)){p();continue}c>=0&&l[0].role===k.role?(l.push(k),o.add(f)):(p(),c=f,l=[k])}return p(),{groupAt:a,absorbed:o}}const xm=1800*1e3;function vm(t){const n=new Map;let s;for(let r=0;r<t.length;r++){const i=t[r];if(i.role==="toolResult"||!i.timestamp)continue;const a=i.timestamp;if(s!==void 0&&a-s>xm){const o=new Date(a);n.set(r,`${String(o.getHours()).padStart(2,"0")}:${String(o.getMinutes()).padStart(2,"0")}`)}s=a}return n}const Yr=4,km=d.memo(function({messages:n,onExpand:s}){const r=et(),i=n[0];let a="";e:for(const R of n)for(const E of R.content){const A=Ls(E);if(A&&A.text.trim()&&(a=fm(A.text,R.role==="assistant"),a))break e}if(!a&&i.role==="custom"&&i.customType==="file"){const R=i.details??{};a=R.name??R.path??""}a.length>90&&(a=`${a.slice(0,90)}…`);const o=new Map;let c=0,l=0,p=0;for(const R of n)for(const E of R.content){const A=Ts(E);if(A){o.set(A.name,(o.get(A.name)??0)+1);continue}Hl(E)?c++:Ul(E)?l++:Bl(E)&&p++}const u=[...o.entries()].sort((R,E)=>E[1]-R[1]||R[0].localeCompare(E[0])),f=[];for(const[R,E]of u.slice(0,Yr))f.push({key:`t:${R}`,label:lr(R,E),kind:"tool"});u.length>Yr&&f.push({key:"t:more",label:`+${u.length-Yr}`,kind:"tool"}),c&&f.push({key:"thinking",label:lr(r("thinking"),c),kind:"meta"}),l&&f.push({key:"bash",label:lr(r("bashRuns"),l),kind:"meta"}),p&&f.push({key:"images",label:lr(r("images"),p),kind:"meta"});const k=i.role==="custom"&&i.customType==="file"?r("attachment"):Wl(i.role,r),j=n.map(R=>R.id);return e.jsxs("button",{type:"button",className:"msg-collapsed","data-msg-id":i.id,title:`${r("expandMsg")} · ${a||f.map(R=>R.label).join(" · ")||i.role}`,onClick:()=>s(j),children:[e.jsx("span",{className:`msg-collapsed-role role-${i.role}`,children:k}),e.jsxs("span",{className:"msg-collapsed-body",children:[a&&e.jsx("span",{className:"msg-collapsed-preview",children:a}),f.length>0&&e.jsx("span",{className:"msg-collapsed-chips",children:f.map(R=>e.jsx("span",{className:`msg-collapsed-chip is-${R.kind}`,children:R.label},R.key))})]}),i.timestamp?e.jsx("span",{className:"msg-collapsed-time",children:ym(i.timestamp)}):null,e.jsx("span",{className:"msg-collapsed-action","aria-hidden":"true",children:e.jsx(_t,{})})]})});function lr(t,n){return n>1?`${t} ×${n}`:t}function ym(t){const n=new Date(t),s=String(n.getHours()).padStart(2,"0"),r=String(n.getMinutes()).padStart(2,"0");return`${s}:${r}`}const eo=d.memo(function({id:n,show:s,height:r,containerRef:i,onMeasured:a,lazyRef:o,children:c}){const l=d.useRef(null),p=d.useRef(null);return d.useLayoutEffect(()=>{const u=p.current;if(p.current=s,!s||u!==!1)return;const f=l.current,k=i.current;if(!f||!k)return;const j=f.offsetHeight;a==null||a(n,j);const R=j-r;if(R!==0){const E=f.parentElement;E&&E.getBoundingClientRect().bottom<=k.getBoundingClientRect().top&&(k.scrollTop+=R)}},[s]),s?e.jsx("div",{ref:o,"data-lazy-id":n,children:e.jsx("div",{ref:l,children:c})}):e.jsx("div",{ref:o,className:"msg-lazy-ph","data-msg-id":n,"data-lazy-id":n,style:{height:r},"aria-hidden":"true"})});function wm(t,n,s,r){const i=[],a=[];let o=0;for(const c of t){if(s.has(c.id))continue;c.top<n.bottom&&c.bottom>n.top?r.has(c.id)&&i.push(c.id):r.has(c.id)||(a.push(c.id),c.bottom<=n.top&&(o+=c.bottom-c.top))}return{show:i,hide:a,shrinkAbove:o}}function bm(t,n){if(n.show.length===0&&n.hide.length===0)return t;const s=new Set(t);for(const r of n.show)s.delete(r);for(const r of n.hide)s.add(r);return s}function jm(t,n,s){const r=new Set;let i=0;for(let a=t.length-1;a>=0&&!(a<t.length-1&&i>=s);a--){const o=t[a];r.add(o.id),i+=n.get(o.id)??ql(o.role,o.customType)}return r}function ql(t,n){switch(t){case"user":return 72;case"assistant":return 280;case"toolResult":return 8;case"custom":return n==="file"?96:72;default:return 60}}function Cm(t){if(t.role==="toolResult")return"";const n=[];for(const s of t.content)Sm(s,n);return t.errorMessage&&n.push(t.errorMessage),n.join(`
246
+ `)}function Sm(t,n){if(typeof t.text=="string"){n.push(t.text);return}switch(t.type){case"thinking":typeof t.thinking=="string"&&n.push(t.thinking);break;case"toolCall":{typeof t.name=="string"&&n.push(t.name),typeof t.argumentsText=="string"&&n.push(t.argumentsText);break}case"bash":typeof t.command=="string"&&n.push(t.command),typeof t.output=="string"&&n.push(t.output);break}}function Nm(t,n){const s=n.trim().toLowerCase();if(!s)return 0;const r=t.toLowerCase();let i=0,a=r.indexOf(s);for(;a!==-1;)i++,a=r.indexOf(s,a+s.length);return i}function Em(t,n){const s=n.trim().toLowerCase();if(!s)return[];const r=[];for(const i of t){const a=Cm(i);if(!a)continue;const o=Nm(a,s);for(let c=0;c<o;c++)r.push({messageId:i.id,occurrence:c})}return r}function Tm(t,n){var o;const s=new Map,r=[],i=n.toLowerCase();if(!i)return{byMsg:s,all:r};const a=document.createTreeWalker(t,NodeFilter.SHOW_TEXT,{acceptNode(c){const l=c.parentElement;return!l||l.closest(".search-bar")?NodeFilter.FILTER_REJECT:(c.textContent??"").toLowerCase().includes(i)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(let c=a.nextNode();c;c=a.nextNode()){const l=(c.textContent??"").toLowerCase(),p=(o=c.parentElement)==null?void 0:o.closest("[data-msg-id]");if(!p)continue;const u=p.getAttribute("data-msg-id")??"";let f=l.indexOf(i);for(;f!==-1;){const k=document.createRange();k.setStart(c,f),k.setEnd(c,f+i.length),r.push(k);const j=s.get(u);j?j.push(k):s.set(u,[k]),f=l.indexOf(i,f+i.length)}}return{byMsg:s,all:r}}function ps(t,n){const s=CSS;if(!s.highlights)return;if(n.length===0){s.highlights.delete(t);return}const r=window.Highlight;r&&s.highlights.set(t,new r(...n))}function Rm({containerRef:t,messages:n,open:s,onClose:r,onEnsureExpanded:i}){const a=et(),o=d.useRef(null),[c,l]=d.useState(""),[p,u]=d.useState(0),f=d.useDeferredValue(c),k=s?f.trim():"",j=d.useMemo(()=>s?Em(n,k):[],[n,k,s]),R=d.useRef(j);R.current=j;const E=d.useRef(p);E.current=p,d.useEffect(()=>{s&&(u(0),requestAnimationFrame(()=>{var y;return(y=o.current)==null?void 0:y.select()}))},[s]),d.useEffect(()=>{if(!s)return;const y=M=>{M.key==="Escape"&&(M.preventDefault(),M.stopPropagation(),r())};return window.addEventListener("keydown",y,!0),()=>window.removeEventListener("keydown",y,!0)},[s,r]),d.useEffect(()=>(s||(ps("msg-search",[]),ps("msg-search-active",[])),()=>{ps("msg-search",[]),ps("msg-search-active",[])}),[s]);const A=d.useCallback(y=>{const M=t.current;if(!M)return;const b=M.querySelector(`[data-msg-id="${y}"]`);b&&(b.classList.remove("msg-flash"),b.offsetWidth,b.classList.add("msg-flash"))},[t]);d.useLayoutEffect(()=>{if(!s||!k)return;const y=t.current;if(!y)return;let M=!1,b=0;return b=requestAnimationFrame(()=>{var ve;if(M)return;const F=R.current,U=F[Math.min(E.current,F.length-1)];if(!U){ps("msg-search",[]),ps("msg-search-active",[]);return}i(U.messageId);const{byMsg:ce,all:ie}=Tm(y,k);ps("msg-search",ie);const W=(ve=ce.get(U.messageId))==null?void 0:ve[U.occurrence];if(W){ps("msg-search-active",[W]);const Se=W.startContainer.parentElement??y.querySelector(`[data-msg-id="${U.messageId}"]`);Se==null||Se.scrollIntoView({block:"center"})}else A(U.messageId)}),()=>{M=!0,cancelAnimationFrame(b)}},[s,k,j,t,A,i]);const N=d.useCallback(y=>{const M=R.current;if(M.length===0)return;const b=(E.current+y+M.length)%M.length;u(b),i(M[b].messageId)},[i]);if(!s)return null;const T=j.length;return e.jsxs("div",{className:"search-bar",role:"search",children:[e.jsx("input",{ref:o,className:"search-input",type:"text",value:c,placeholder:a("searchPlaceholder"),onChange:y=>{l(y.target.value),u(0)},onKeyDown:y=>{y.key==="Enter"&&(y.preventDefault(),N(y.shiftKey?-1:1))}}),e.jsx("span",{className:`search-count ${T===0?"empty":""}`,children:T===0?a("searchNoResults"):`${Math.min(p+1,T)}/${T}`}),e.jsx("button",{type:"button",className:"search-btn",title:a("searchPrev"),disabled:T===0,onClick:()=>N(-1),children:e.jsx(Ao,{})}),e.jsx("button",{type:"button",className:"search-btn",title:a("searchNext"),disabled:T===0,onClick:()=>N(1),children:e.jsx(Qt,{})}),e.jsx("button",{type:"button",className:"search-btn",title:a("searchClose"),onClick:r,children:e.jsx(Wt,{})})]})}const Xr=new Map,Im=15,to=30,no=1200,Lm=1600;function so(t){return t.content.some(n=>n.type==="toolCall")}const Mm=[{key:"ex.understand",icon:"🔍"},{key:"ex.debug",icon:"🐛"},{key:"ex.test",icon:"🧪"},{key:"ex.review",icon:"🧹"}];function Pm(t){return Mm.map(({key:n,icon:s})=>({icon:s,text:t(n),prompt:t(`${n}.prompt`)}))}const is=new Map;function Am({event:t}){const n=et(),s=t.errors??[],r=t.phase==="done"&&s.length>0,i=t.phase==="running"?n("reloadRunning"):r?n("reloadPartial",{count:s.length}):n("reloadDone"),a=t.extensions===void 0?"":n("reloadCounts",{extensions:t.extensions,skills:t.skills??0,prompts:t.prompts??0}),o=t.durationMs===void 0?"":` · ${(t.durationMs/1e3).toFixed(1)}s`,c=p=>p.length>8?`${p.slice(0,8).join(", ")} +${p.length-8}`:p.join(", "),l=t.resources?[n("reloadExtensionList",{names:c(t.resources.extensions)||"—"}),n("reloadSkillList",{names:c(t.resources.skills)||"—"}),n("reloadPromptList",{names:c(t.resources.prompts)||"—"})].join(`
247
+ `):"";return e.jsxs("div",{className:`reload-event${r?" failed":""}`,role:"status",title:a?`${a}${o}
248
+ ${l}`:void 0,children:[e.jsx("div",{className:"reload-command",children:e.jsx("code",{children:"/reload"})}),e.jsxs("div",{className:"reload-event-line",children:[e.jsx("span",{className:t.phase==="running"?"reload-dots":"reload-mark","aria-hidden":"true",children:t.phase==="running"?e.jsxs(e.Fragment,{children:[e.jsx("i",{}),e.jsx("i",{}),e.jsx("i",{})]}):r?"!":"✓"}),e.jsxs("span",{children:[i,t.phase==="done"&&a?` · ${a}${o}`:o]})]}),r&&e.jsxs("details",{className:"reload-errors",children:[e.jsx("summary",{children:n("reloadDetails")}),e.jsx("ul",{children:s.map((p,u)=>e.jsxs("li",{children:[e.jsx("strong",{children:p.path||n("reloadGeneralError")}),e.jsx("span",{children:p.message})]},`${p.path}-${u}`))})]})]})}const Dm=d.memo(function({recovery:n,state:s,connected:r=!0,silenceNotified:i=!1,liveOutputs:a,toolStatuses:o,onEdit:c,onKillBash:l,onStop:p,thinkingWrap:u,toolsWrap:f,pendingEcho:k,reloadEvents:j=[]}){var Ht,an,At,Xt;const R=et(),E=d.useMemo(()=>Ld(s.messages),[s.messages]);s={...s,messages:E};const A=d.useMemo(()=>Fs(s.streamingMessage?[...s.messages,s.streamingMessage]:s.messages,s.isStreaming),[s.messages,s.streamingMessage,s.isStreaming]),N=new Map(A.incidents.flatMap(K=>[...K.leaks,K.last].map(Y=>[Y.id,K]))),T=d.useMemo(()=>{const K=[...j.filter(Be=>Be.conversationId===s.conversationId).map(Be=>({kind:"reload",event:Be})),...s.cwdEvents.filter(Be=>Be.cwd===s.cwd).map(Be=>({kind:"cwd",event:Be}))].sort((Be,te)=>Be.event.timestamp-te.event.timestamp),Y=[];let Je=0;for(s.messages.forEach((Be,te)=>{for(;Je<K.length&&K[Je].event.timestamp<=(Be.timestamp??0);)Y.push(K[Je++]);Y.push({kind:"message",message:Be,index:te})});Je<K.length;)Y.push(K[Je++]);return Y},[s.messages,s.conversationId,s.cwd,s.cwdEvents,j]),y=d.useRef(null),[M,b]=d.useState(!0),[F,U]=d.useState(!1),ce=d.useRef(!0),ie=d.useRef(0),W=d.useRef(!1);d.useLayoutEffect(()=>{const K=y.current,Y=is.get(s.conversationId);return K&&Y&&(ce.current=Y.bottom,W.current=!Y.bottom,b(Y.bottom),K.scrollTop=Y.bottom?K.scrollHeight:Y.top),()=>{K&&(is.delete(s.conversationId),is.set(s.conversationId,{top:K.scrollTop,bottom:ce.current,hidden:xe.current,expanded:$.current,heights:J.current}),is.size>24&&is.delete(is.keys().next().value))}},[s.conversationId]);const[ve,Se]=d.useState(()=>{var K;return((K=is.get(s.conversationId))==null?void 0:K.expanded)??new Set}),$=d.useRef(ve);$.current=ve;const[$e,L]=d.useState(!1),q=s.streamingMessage?[...s.messages,s.streamingMessage]:s.messages,fe=d.useMemo(()=>{const K=new Map;for(const Y of s.messages)Y.role==="toolResult"&&Y.toolCallId&&K.set(Y.toolCallId,Y);return K},[s.messages]),je=d.useMemo(()=>_c(s.messages,fe),[s.messages,fe]),ne=(Ht=s.streamingMessage)!=null&&Ht.content.some(K=>{var Y;return K.type==="toolCall"&&typeof K.id=="string"&&((Y=fe.get(K.id))==null?void 0:Y.planSnapshot)})?s.streamingMessage:null,Pe=d.useMemo(()=>mm(ne?[...s.messages,ne]:s.messages,fe,s.conversationId),[s.messages,ne,fe,s.conversationId]),B=d.useMemo(()=>Uo(s.messages),[s.messages]),we=d.useMemo(()=>mh(s.messages),[s.messages]),re=d.useMemo(()=>vm(s.messages),[s.messages]),Ie=ku(q),_=((an=s.streamingMessage)==null?void 0:an.content.some(K=>K.type==="text"?typeof K.text=="string"&&!!K.text.trim()||!!K.truncated:K.type==="thinking"?typeof K.thinking=="string"&&!!K.thinking.trim():!0))??!1,le=d.useMemo(()=>Wc(s.messages,s.taskProgress,s.cwd,s.isStreaming),[s.messages,s.taskProgress,s.cwd,s.isStreaming]),O=s.messages.findLastIndex(K=>K.role==="user"),ge=q.length>0?q[q.length-1].id:null,pe=s.messages.length>to?Math.max(0,s.messages.length-Im):0,Ae=(At=s.streamingMessage)!=null&&At.content.length&&s.streamingMessage.content.every(K=>K.type==="toolCall"&&K.name==="bash")?s.streamingMessage:null,ae=d.useMemo(()=>hh(Ae?[...s.messages,Ae]:s.messages,pe,new Set(re.keys())),[s.messages,Ae,pe,re]),Te=d.useMemo(()=>gm(s.messages,pe,ve,new Set(re.keys())),[s.messages,pe,ve,re]),[Z,Fe]=d.useState(()=>{var K;return((K=is.get(s.conversationId))==null?void 0:K.hidden)??new Set}),[z,G]=d.useState(()=>new Set),J=d.useRef(((Xt=is.get(s.conversationId))==null?void 0:Xt.heights)??new Map),Ee=d.useMemo(()=>{const K=new Set(Z);for(const Y of s.messages.slice(0,pe))J.current.has(Y.id)||K.add(Y.id);return K},[Z,s.messages,pe]),V=d.useRef(new Map),Le=d.useRef(0),xe=d.useRef(Ee);xe.current=Ee;const be=s.messages.length>to&&!$e,nt=d.useRef(be);nt.current=be;const Ce=jm(s.messages,J.current,Lm),ye=d.useRef(Ce);ye.current=Ce;const ze=d.useCallback(()=>{const K=y.current;if(!K)return;if(!nt.current){Fe(Ve=>Ve.size?new Set:Ve);return}const Y=K.getBoundingClientRect(),Je={top:Y.top-no,bottom:Y.bottom+no},Be=[];for(const[Ve,Ue]of V.current){const yt=Ue.getBoundingClientRect();Be.push({id:Ve,top:yt.top,bottom:yt.bottom}),J.current.set(Ve,yt.bottom-yt.top)}const te=wm(Be,Je,ye.current,xe.current);for(const Ve of te.hide){const Ue=V.current.get(Ve);Ue&&J.current.set(Ve,Ue.offsetHeight)}Fe(()=>bm(xe.current,te))},[]),Ze=d.useCallback(()=>{Le.current||(Le.current=requestAnimationFrame(()=>{Le.current=0,ze()}))},[ze]);d.useLayoutEffect(()=>{ze()},[ze,s.messages,ve]);const Qe=d.useRef($e);d.useLayoutEffect(()=>{Qe.current&&!$e&&ze(),Qe.current=$e},[$e,ze]);const ct=d.useCallback((K,Y)=>{J.current.set(K,Y)},[]),tt=d.useCallback(K=>{K&&V.current.set(K.dataset.lazyId??"",K)},[]);d.useEffect(()=>{const K=new Set(s.messages.map(Y=>Y.id));for(const[Y,Je]of V.current)K.has(Y)||(V.current.delete(Y),J.current.delete(Y));Fe(Y=>{let Je=!1;const Be=new Set;for(const te of Y)K.has(te)?Be.add(te):Je=!0;return Je?Be:Y})},[s.messages,ve]),d.useEffect(()=>()=>cancelAnimationFrame(Le.current),[]);const Oe=d.useMemo(()=>{const K=[];for(const Y of s.messages){if(Y.role!=="user"||Y.origin==="auto-reminder"||_i(Y)||Hi(Y))continue;const Je=Y.content.map(Ve=>{var Ue;return((Ue=Ls(Ve))==null?void 0:Ue.text)??""}).filter(Boolean).join(" "),Be=As(Je),te=_l(Be?Be.userMessage??`skill:${Be.name}`:Je);te&&K.push({id:Y.id,text:te})}return K},[s.messages]),ee=d.useMemo(()=>{const K=new Map;return Oe.forEach((Y,Je)=>K.set(Y.id,Je)),K},[Oe]),[We,w]=d.useState(-1),H=d.useRef(-1),X=d.useRef(Oe);d.useEffect(()=>{X.current=Oe},[Oe]);const[ke,De]=d.useState({}),He=d.useCallback(()=>{const K=y.current;if(!K)return;const Y=K.getBoundingClientRect().top,Je=Math.max(K.scrollHeight,1),Be={},te=new Map(Array.from(K.querySelectorAll("[data-msg-id]"),Ve=>[Ve.dataset.msgId,Ve]));for(const Ve of X.current){const Ue=te.get(Ve.id);Ue&&(Be[Ve.id]=Math.max(.02,Math.min(.98,(Ue.getBoundingClientRect().top-Y+K.scrollTop)/Je)))}De(Ve=>Object.keys(Be).length===Object.keys(Ve).length&&Object.keys(Be).every(Ue=>Math.abs(Be[Ue]-Ve[Ue])<.002)?Ve:Be)},[]);d.useLayoutEffect(()=>{const K=y.current;if(!K)return;let Y=requestAnimationFrame(He);const Je=()=>{cancelAnimationFrame(Y),Y=requestAnimationFrame(He)},Be=new MutationObserver(Je);return Be.observe(K,{childList:!0,subtree:!0}),window.addEventListener("resize",Je),()=>{cancelAnimationFrame(Y),Be.disconnect(),window.removeEventListener("resize",Je)}},[Oe,He]);const ot=d.useCallback(()=>{const K=y.current,Y=X.current;if(!K||Y.length===0)return;const Je=K.getBoundingClientRect().top,Be=140;let te=-1;const Ve=new Map(Array.from(K.querySelectorAll("[data-msg-id]"),Ue=>[Ue.dataset.msgId,Ue]));for(let Ue=0;Ue<Y.length;Ue++){const yt=Ve.get(Y[Ue].id);if(yt)if(yt.getBoundingClientRect().top<=Je+Be)te=Ue;else break}te!==H.current&&(H.current=te,w(te))},[]);d.useEffect(()=>{ot()},[Oe,ot]);const dt=d.useCallback(K=>{Se(Y=>Y.has(K)?Y:new Set(Y).add(K))},[]),g=d.useCallback(K=>{Se(Y=>{if(K.every(Be=>Y.has(Be)))return Y;const Je=new Set(Y);for(const Be of K)Je.add(Be);return Je})},[]),se=d.useCallback(K=>{const Y=s.messages.find(Ue=>Ue.id===K),Je=(Y==null?void 0:Y.role)==="toolResult"&&Y.toolCallId?ae.sources.get(Y.toolCallId)??K:K,Be=ae.owners.get(Je)??Je,te=s.messages.findIndex(Ue=>Ue.id===Be);mn.flushSync(()=>{te>=0&&te<pe&&!ve.has(Be)&&dt(Be),G(Ue=>Ue.has(Be)?Ue:new Set(Ue).add(Be))});const Ve=Y!=null&&Y.toolCallId?[Y.toolCallId]:(Y==null?void 0:Y.content.flatMap(Ue=>Ue.type==="toolCall"&&Ue.name==="bash"&&typeof Ue.id=="string"?[Ue.id]:[]))??[];for(const Ue of Ve)mn.flushSync(()=>window.dispatchEvent(new CustomEvent("pi:reveal-tool",{detail:{toolCallId:Ue,search:!0}})))},[s.messages,pe,ve,dt,ae]);d.useEffect(()=>{const K=Y=>{if(!(Y.ctrlKey||Y.metaKey)||Y.key.toLowerCase()!=="f")return;const Je=Y.target;Je&&(Je.tagName==="INPUT"||Je.tagName==="TEXTAREA"||Je.isContentEditable)||(Y.preventDefault(),L(!0))};return window.addEventListener("keydown",K),()=>window.removeEventListener("keydown",K)},[]);const qe=d.useCallback(K=>{Se(Y=>{if(!Y.has(K))return Y;const Je=new Set(Y);return Je.delete(K),Je})},[]),_e=d.useCallback(K=>{K=ae.owners.get(K)??K;const Y=s.messages.findIndex(Be=>Be.id===K);mn.flushSync(()=>{Y>=0&&Y<pe&&!ve.has(K)&&dt(K),G(Be=>Be.has(K)?Be:new Set(Be).add(K))});const Je=X.current.findIndex(Be=>Be.id===K);H.current=Je,w(Je),requestAnimationFrame(()=>{var te,Ve,Ue;const Be=(te=y.current)==null?void 0:te.querySelector(`[data-msg-id="${K}"]`);Be&&((Ve=y.current)==null||Ve.querySelectorAll(".msg-flash").forEach(yt=>yt.classList.remove("msg-flash")),Be.scrollIntoView({block:"start"}),Be.classList.remove("msg-flash"),Be.offsetWidth,Be.classList.add("msg-flash"),Be!==((Ue=y.current)==null?void 0:Ue.lastElementChild)&&(W.current=!0))})},[s.messages,pe,ve,dt,ae]);d.useEffect(()=>{const K=Je=>{var te;const Be=(te=Je.detail)==null?void 0:te.messageId;Be&&q.some(Ve=>Ve.id===Be)&&_e(Be)},Y=Je=>{let{messageId:Be,toolCallId:te,todoItemIds:Ve}=Je.detail??{};const Ue=te?Pe.get(te):void 0;Ue!=null&&Ue.target&&({messageId:Be,toolCallId:te}=Ue.target),!(!Be||!te||!q.some(yt=>yt.id===Be))&&(_e(Be),requestAnimationFrame(()=>{mn.flushSync(()=>window.dispatchEvent(new CustomEvent("pi:reveal-tool",{detail:{toolCallId:te}}))),requestAnimationFrame(()=>{var Bt,Zt;const yt=(Bt=y.current)==null?void 0:Bt.querySelector(`[data-tool-call-id="${CSS.escape(te)}"]`);if(yt){if(Ve!=null&&Ve.length){(Zt=y.current)==null||Zt.querySelectorAll(".todo-item-flash").forEach(St=>St.classList.remove("todo-item-flash"));const qt=Array.from(yt.querySelectorAll("[data-todo-item-id]")).filter(St=>Ve.includes(St.dataset.todoItemId??""));if(qt.length){qt[0].focus({preventScroll:!0}),qt[0].scrollIntoView({block:"center"});for(const St of qt)St.offsetWidth,St.classList.add("todo-item-flash");window.setTimeout(()=>qt.forEach(St=>St.classList.remove("todo-item-flash")),1800);return}}yt.scrollIntoView({block:"center"}),yt.classList.remove("change-card-flash"),yt.offsetWidth,yt.classList.add("change-card-flash"),window.setTimeout(()=>yt.classList.remove("change-card-flash"),1800)}})}))};return window.addEventListener("pi:jump-message",K),window.addEventListener("pi:jump-tool",Y),()=>{window.removeEventListener("pi:jump-message",K),window.removeEventListener("pi:jump-tool",Y)}},[_e,q,Pe]);const at=d.useCallback(()=>{const K=y.current;if(!K)return;const Y=K.scrollTop-ie.current;ie.current=K.scrollTop;const Je=K.scrollHeight-K.scrollTop-K.clientHeight;U(Je>K.clientHeight);const Be=Je<80;Y<-4&&Y>-500?W.current=!0:Be&&Y>=0&&(W.current=!1),ce.current=Be&&!W.current,b(ce.current),ot(),He(),Ze()},[ot,He,Ze]),mt=d.useRef(!1);d.useEffect(()=>{const K=mt.current;if(mt.current=!!s.isStreaming,K&&!s.isStreaming&&!W.current){const Y=()=>{const Be=y.current;Be&&!W.current&&(Be.scrollTop=Be.scrollHeight,ce.current=!0,b(!0))};requestAnimationFrame(()=>requestAnimationFrame(Y));const Je=setTimeout(Y,180);return()=>clearTimeout(Je)}},[s.isStreaming]),d.useEffect(()=>{const K=y.current;K&&ce.current&&(K.scrollTop=K.scrollHeight),K&&U(K.scrollHeight-K.scrollTop-K.clientHeight>K.clientHeight)},[q,s.isStreaming,a]);const Mt=d.useCallback(()=>{const K=y.current;K&&(K.scrollTop=K.scrollHeight),ce.current=!0,W.current=!1,b(!0)},[]),Pt=d.useRef(null),[$t,Ft]=d.useState(!1);d.useEffect(()=>{if(!$t)return;const K=Je=>{var Be;(Be=Pt.current)!=null&&Be.contains(Je.target)||Ft(!1)},Y=Je=>{Je.key==="Escape"&&Ft(!1)};return document.addEventListener("pointerdown",K,!0),document.addEventListener("keydown",Y),()=>{document.removeEventListener("pointerdown",K,!0),document.removeEventListener("keydown",Y)}},[$t]),d.useEffect(()=>{const K=Pt.current,Y=y.current;if(!K||!Y)return;const Je=Be=>{Be.preventDefault();const te=K.querySelector(".qn-list");if(te&&te.contains(Be.target)&&te.scrollHeight>te.clientHeight){te.scrollTop+=Be.deltaY;return}Y.scrollTop+=Be.deltaY};return K.addEventListener("wheel",Je,{passive:!1}),()=>K.removeEventListener("wheel",Je)},[]);const[Jt,nn]=d.useState(0);d.useEffect(()=>{const K=()=>{var Y;nn(((Y=y.current)==null?void 0:Y.clientHeight)??0),Ze()};return K(),window.addEventListener("resize",K),()=>window.removeEventListener("resize",K)},[Ze]);const lt=Oe.filter(K=>ke[K.id]!==void 0),Et=nm(lt.map(K=>({id:K.id,position:ke[K.id]})),Jt),zt=Et.some(K=>K.ids.length>1);return e.jsxs("div",{className:"messages-wrap",children:[e.jsxs("div",{className:"messages",ref:y,onScroll:at,children:[T.length===0&&!s.streamingMessage&&e.jsxs("div",{className:"empty-state",children:[e.jsx("div",{className:"empty-logo-wrap",children:e.jsx("img",{className:"empty-logo",src:"/icon/1a-mark.svg",alt:""})}),e.jsx("h2",{className:"empty-title",children:R("welcomeTitle")}),e.jsx("p",{className:"empty-sub",children:R("welcomeSub")}),e.jsxs("div",{className:"empty-cwd",children:[e.jsx("span",{className:"empty-cwd-label",children:R("directory")}),e.jsx("span",{className:"empty-cwd-path",children:s.cwd})]}),e.jsx("div",{className:"empty-examples",children:Pm(R).map(K=>e.jsxs("button",{type:"button",className:"empty-example",title:R("clickToFill"),onClick:()=>window.dispatchEvent(new CustomEvent("pi-web:fill",{detail:K.prompt})),children:[e.jsx("span",{className:"empty-example-icon",children:K.icon}),e.jsx("span",{className:"empty-example-text",children:K.text})]},K.prompt))})]}),T.map(K=>{var Zt,qt,St,dn;if(K.kind==="reload")return e.jsx(Am,{event:K.event},`reload-${K.event.requestId}`);if(K.kind==="cwd")return e.jsxs("div",{className:"goal-event cwd-event",role:"status",children:[e.jsx("span",{"aria-hidden":"true",children:"↪"}),e.jsx("span",{children:R("cwdSwitchEvent",{path:K.event.cwd.replace(/^\/(?:Users|home)\/[^/]+(?=\/|$)/,"~")})})]},`cwd-${K.event.timestamp}`);const{message:Y,index:Je}=K;if(we.absorbed.has(Y.id))return null;if(Y.origin==="auto-reminder")return e.jsx(Qr,{message:Y,toolResults:fe,liveOutputs:Xr,toolStatuses:o,streaming:!1,isLast:!1},Y.id);const Be=pt=>{const Dt=re.get(Je);return Dt?e.jsxs(d.Fragment,{children:[e.jsx("div",{className:"time-gap","aria-label":R("timeGapAt",{time:Dt}),title:Y.timestamp?new Date(Y.timestamp).toLocaleString():void 0,children:e.jsx("span",{children:Dt})}),pt]},Y.id):pt},te=we.groups.get(Y.id);if(te)return Be(e.jsxs("div",{className:`goal-event ${te.kind}`,"data-msg-id":Y.id,children:[e.jsx("span",{"aria-hidden":"true",children:te.kind==="complete"?"✓":"◎"}),e.jsx("span",{children:R(te.kind==="complete"?"goalEventComplete":"goalEventSet",{text:te.text})}),te.ids.length>1&&e.jsxs("span",{className:"goal-event-count",children:["×",te.ids.length]}),te.kind==="complete"&&e.jsxs("details",{className:"goal-event-details",children:[e.jsx("summary",{children:R("goalReviewDetails")}),e.jsx("pre",{children:Y.content.map(pt=>pt.type==="text"?pt.text:"").join(`
249
+ `)})]}),te.ids.slice(1).map(pt=>e.jsx("span",{"data-msg-id":pt},pt))]},Y.id));const Ve=Je<pe,Ue=Ve&&ve.has(Y.id);if(Ve&&!Ue){if(Te.absorbed.has(Je))return null;const pt=Te.groupAt.get(Je);return pt?Be(e.jsx(eo,{id:Y.id,show:!be||Ce.has(Y.id)||z.has(Y.id)||!Ee.has(Y.id),height:J.current.get(Y.id)??30,containerRef:y,onMeasured:ct,lazyRef:tt,children:e.jsx(km,{messages:pt,onExpand:g})},Y.id)):null}if(ae.owners.has(Y.id))return le.has(Y.id)?e.jsx(fa,{files:le.get(Y.id)},Y.id):null;const yt=Y.role==="user"?ee.get(Y.id):void 0,Bt=!be||Ce.has(Y.id)||z.has(Y.id)||!Ee.has(Y.id);return Be(e.jsxs(eo,{id:Y.id,show:Bt,height:J.current.get(Y.id)??ql(Y.role,Y.customType),containerRef:y,onMeasured:ct,lazyRef:tt,children:[e.jsx(Qr,{recovery:n,incident:N.get(Y.id),message:ae.projected.get(Y.id)??Y,toolMessageIds:ae.sources,continuation:!!Ie.get(Y.id)&&!Ee.has(Ie.get(Y.id))&&!(Je<pe&&!ve.has(Ie.get(Y.id))),qnIndex:yt,qnActive:yt!==void 0?yt===We:void 0,onJump:_e,toolResults:fe,planViews:Pe,retriedEditIds:je,liveOutputs:so(Y)?a:Xr,toolStatuses:o,streaming:s.isStreaming&&r&&Je>O,toolsRunning:s.isStreaming&&Je>O,bashActive:s.isStreaming&&Je>O&&!s.messages.slice(Je+1).some(pt=>pt.role==="assistant"&&pt.content.some(Dt=>Dt.type==="text"&&typeof Dt.text=="string"&&Dt.text.trim()))&&!((Zt=s.streamingMessage)!=null&&Zt.content.some(pt=>pt.type==="text"&&typeof pt.text=="string"&&pt.text.trim())),bashTitle:(qt=s.messages.slice(O<Je?O:0,Je+1).findLast(pt=>pt.role==="assistant"&&pt.content.some(Dt=>Dt.type==="text"&&typeof Dt.text=="string"&&Dt.text.trim())))==null?void 0:qt.content.filter(pt=>pt.type==="text").map(pt=>pt.type==="text"&&typeof pt.text=="string"?pt.text:"").join(" ").slice(0,80),onKillBash:l,toolsWrap:f,thinkingWrap:u,isLast:Y.id===ge,onEdit:c,conversationId:s.conversationId,questionAttachments:B.get(Y.id),onCollapse:Ue?qe:void 0},Y.id),le.has(Y.id)&&e.jsx(fa,{files:le.get(Y.id)}),Y.role==="assistant"&&e.jsx(ph,{message:Y,last:Y.id===((St=s.messages.findLast(pt=>pt.role==="assistant"))==null?void 0:St.id),regenerate:!s.isStreaming&&r&&!((dn=s.tree)!=null&&dn.verifying)&&c?()=>{const pt=s.messages.slice(0,Je).findLast(Vt=>Vt.role==="user"&&Vt.origin!=="auto-reminder");if(!pt)return;const Dt=pt.questionText??pt.content.map(Vt=>Vt.type==="text"?Vt.text:"").join(`
250
+ `),Yt=As(Dt);c(pt.id,Yt?`/skill:${Yt.name}${Yt.userMessage?` ${Yt.userMessage}`:""}`:Dt,B.get(pt.id),{entryId:pt.entryId})}:void 0})]},Y.id))}),s.streamingMessage&&_&&!ae.owners.has(s.streamingMessage.id)&&e.jsx(Qr,{recovery:n,incident:N.get(s.streamingMessage.id),message:s.streamingMessage,continuation:!!Ie.get(s.streamingMessage.id),toolResults:fe,planViews:Pe,retriedEditIds:je,liveOutputs:so(s.streamingMessage)?a:Xr,toolStatuses:o,streaming:r,toolsRunning:s.isStreaming,isLast:!0,onEdit:c,conversationId:s.conversationId,onKillBash:l,toolsWrap:f,thinkingWrap:u},s.streamingMessage.id),e.jsx("div",{className:"trailing-working",children:e.jsx(rl,{onStop:p,state:s,connected:r,silenceNotified:i,toolStatuses:o})}),k&&k.conversationId===s.conversationId&&e.jsxs("div",{className:"msg msg-user pending-echo","data-role":"user",children:[e.jsxs("div",{className:"msg-meta",children:[e.jsx("span",{className:"msg-role",children:R("role.user")}),e.jsxs("span",{className:"pending-echo-tag",children:[e.jsx("span",{className:"thinking-spinner","aria-hidden":"true"}),R("sending")]})]}),e.jsx("div",{className:"msg-body",children:e.jsx("div",{className:"msg-text",children:k.text})})]})]}),!M&&F&&(()=>{const K=e.jsxs("button",{type:"button",className:"scroll-bottom",onClick:Mt,children:[e.jsx($o,{})," ",R("backToBottom")]}),Y=document.querySelector(".design-workspace .view-pane:not(.hidden) .main > .inputbar");return Y?mn.createPortal(K,Y):K})(),e.jsx(Rm,{containerRef:y,messages:q,open:$e,onClose:()=>L(!1),onEnsureExpanded:se}),Oe.length>0&&e.jsxs("div",{className:`qn-rail ${zt?"many":""} ${$t?"open":""}`,ref:Pt,"aria-label":R("questionNavTitle"),onPointerEnter:()=>Ft(!0),onPointerLeave:()=>Ft(!1),onFocusCapture:()=>Ft(!0),children:[Et.map(K=>{var Je;const Y=lt.find(Be=>Be.id===K.ids[0]);return e.jsx("button",{type:"button",className:`qn-bar ${K.ids.length>1?"cluster":""} ${K.ids.includes(((Je=Oe[We])==null?void 0:Je.id)??"")?"active":""}`,style:{top:`${K.position*100}%`},"aria-label":K.ids.length>1?R("questionMarkerGroup",{n:K.ids.length}):`${Oe.indexOf(Y)+1}. ${Y.text}`,onClick:()=>{_e(Y.id),Ft(!1)},children:e.jsxs("span",{className:"qn-bar-text",children:[Oe.indexOf(Y)+1,". ",Y.text]})},K.ids.join(":"))}),zt&&e.jsx("div",{className:"qn-list",children:Oe.map((K,Y)=>e.jsxs("button",{type:"button",className:`qn-list-item ${Y===We?"active":""}`,"aria-label":`${Y+1}. ${K.text}`,onClick:()=>{_e(K.id),Ft(!1)},children:[e.jsx("span",{className:"qn-list-idx",children:Y+1}),e.jsx("span",{className:"qn-list-text",children:K.text})]},K.id))})]})]})},(t,n)=>t.active===!1&&n.active===!1&&t.state.conversationId===n.state.conversationId?!0:Object.keys(n).every(s=>t[s]===n[s]));function $m({conversationId:t,active:n,text:s,replace:r,restoreImages:i}){const a=et(),[o,c]=d.useState();if(d.useEffect(()=>{const p=()=>c(n?Od(t):void 0);return p(),window.addEventListener("pi-tree-draft",p),()=>window.removeEventListener("pi-tree-draft",p)},[t,n]),d.useEffect(()=>{var p;o&&o.conversationId===t&&n&&!s.trim()&&(r(o.text),(p=o.images)!=null&&p.length&&(i==null||i(o.images)),ja(t,o.id))},[o,t,n,s,r,i]),!o||o.conversationId!==t||!n||!s.trim())return null;const l=p=>{var u;p!==void 0&&(r(p),(u=o.images)!=null&&u.length&&(i==null||i(o.images))),ja(t,o.id)};return e.jsxs("section",{className:"tree-draft-restore",role:"alert",children:[e.jsx("p",{children:a("treeDraftConflict")}),e.jsxs("details",{children:[e.jsx("summary",{children:a("treeReturnedText")}),e.jsx("pre",{children:o.text})]}),e.jsx("button",{onClick:()=>l(o.text),children:a("treeReplaceDraft")}),e.jsx("button",{onClick:()=>l(`${s}
251
+
252
+ ${o.text}`),children:a("treeAppendDraft")}),e.jsx("button",{onClick:()=>l(),children:a("treeKeepDraft")})]})}function Fm(t,n){const s=r=>{var c;const i=r.replace(/\\/g,"/"),a=/^(?:\/|[A-Za-z]:\/)/.test(i)?i:`${((c=n.editorSnapshot)==null?void 0:c.cwd)??""}/${i}`,o=[];for(const l of a.split("/"))l===".."?o.pop():l&&l!=="."&&o.push(l);return o.join("/")};return[...t.filter(r=>r.nativeRef||r.mode==="lines"||r.imageData||r.fileData||r.uploadPath||s(r.path)!==s(n.path)),n]}function Om(t){const n=t.input+t.cacheRead+t.cacheWrite;return n>0?Math.round(t.cacheRead/n*100):null}const ro=t=>new Intl.NumberFormat("en",{notation:"compact",maximumFractionDigits:1}).format(t);function _m({stats:t}){const n=et(),s=d.useRef(null),[r,i]=d.useState(!1),a=d.useRef(!1);d.useEffect(()=>{if(!r)return;const u=k=>{var j;(j=s.current)!=null&&j.contains(k.target)||(i(!1),a.current=!1)},f=k=>{k.key==="Escape"&&(i(!1),a.current=!1)};return document.addEventListener("pointerdown",u,!0),document.addEventListener("keydown",f),()=>{document.removeEventListener("pointerdown",u,!0),document.removeEventListener("keydown",f)}},[r]);const o=t==null?void 0:t.contextUsage,c=(o==null?void 0:o.percent)===null||(o==null?void 0:o.percent)===void 0?null:Math.round(o.percent),l=c===null?0:Math.max(0,Math.min(100,c)),p=t?Om(t.tokens):null;return!(c!==null&&c>0)&&!(p!==null&&p>0)?null:e.jsxs("div",{className:"usage-control",ref:s,onPointerEnter:()=>i(!0),onPointerLeave:()=>{a.current||i(!1)},children:[e.jsxs("button",{type:"button",className:`usage-trigger${c!==null&&c>=80?" warn":""}`,title:`${n("usageContextTitle")} · ${n("usageCacheTitle")}`,"aria-label":`${n("usageContextTitle")} ${c??"—"}%`,"aria-expanded":r,onPointerDown:()=>{a.current=!a.current,i(a.current)},onClick:u=>{u.detail===0&&(a.current=!a.current,i(a.current))},children:[c!==null&&c>0&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"usage-context-label",children:n("context")}),e.jsxs("span",{className:"usage-percent",children:[c,"%"]})]}),p!==null&&p>0&&e.jsxs("span",{className:"usage-cache-short",children:[c!==null&&c>0?"· ":"",n("usageCacheShort")," ",e.jsxs("strong",{className:p<50?"warn":"",children:[p,"%"]})]})]}),r&&e.jsxs("div",{className:"usage-popover",role:"dialog","aria-label":n("usageContextTitle"),children:[e.jsxs("div",{className:"usage-head",children:[e.jsx("strong",{children:n("usageContextTitle")}),e.jsxs("span",{children:[(o==null?void 0:o.tokens)===null||(o==null?void 0:o.tokens)===void 0?"—":ro(o.tokens)," / ",o!=null&&o.contextWindow?ro(o.contextWindow):"—"]})]}),e.jsx("div",{className:"usage-progress",role:"img","aria-label":`${n("usageContextTitle")} ${c??"—"}%`,children:e.jsx("span",{className:c!==null&&c>=80?"warn":"",style:{width:`${l}%`}})}),e.jsxs("div",{className:"usage-head usage-cache-section",children:[e.jsx("strong",{children:n("usageCacheTitle")}),e.jsx("span",{className:p!==null&&p<50?"warn":"",children:p===null?"—":`${p}%`})]})]})]})}const Hm=d.memo(function({active:n=!0,currentFile:s,contextReader:r,contextSaver:i,stats:a,ready:o,promptResult:c,verifying:l,pendingCount:p=0,queue:u,workingStatus:f,streaming:k,silentActivity:j,messages:R,slashCommands:E,modelState:A,models:N,modelsLoading:T,send:y,activeConversationId:M,setPendingEcho:b,attachments:F,onRemoveAttachment:U,onAddImageFiles:ce,onAddLocalFiles:ie,onNotice:W,onSent:ve,onManageModels:Se}){var De,He,ot,dt;const $=et(),[$e,L]=d.useState({}),q=s&&$e[M]!==s.id?s:null,fe=d.useRef(null),{locale:je}=ns(),ne=g=>je==="en"&&g.descriptionEn?g.descriptionEn:g.description??"",Pe=g=>je==="en"&&g.argumentHintEn?g.argumentHintEn:g.argumentHint??"",B=d.useRef(new Map),we=d.useRef(M),[re,Ie]=d.useState(""),[_,le]=d.useState("steer"),[O,ge]=d.useState(!1),[pe,Ae]=d.useState(!1);d.useEffect(()=>{le("steer"),ge(!1),Ae(!1)},[M,k]);const ae=()=>y({type:"recall_queue",conversationId:M,requestId:Gt()}),Te=()=>{const g=y({type:"abort"});We||W(g?"warning":"error",$(g?"stopQueuedAfterReconnect":"stopUnavailable"))},Z=u?[...u.steering.map(g=>({text:g,steer:!0})),...u.followUp.map(g=>({text:g,steer:!1}))]:[];d.useLayoutEffect(()=>{we.current!==M&&(re?B.current.set(we.current,re):B.current.delete(we.current),we.current=M,Ie(B.current.get(M)??""),B.current.delete(M))},[M,re]),qo(M,n,Ie),d.useEffect(()=>{const g=fe.current;!g||(c==null?void 0:c.requestId)!==g.id||(fe.current=null,c.ok&&(c.attachmentsConsumed!==!1&&ve(g.conversation,g.attachments),g.conversation===M?(Ie(se=>se===g.text?"":se),!g.queued&&!c.commandExecuted&&g.text.trim()!=="/reload"&&b(M,g.text.trim())):B.current.get(g.conversation)===g.text&&B.current.delete(g.conversation)))},[c,M,ve,b]),d.useEffect(()=>{o||(fe.current=null)},[o]);const[Fe,z]=d.useState(!1),[G,J]=d.useState(null),[Ee,V]=d.useState(0),[Le,xe]=d.useState(!1),[be,nt]=d.useState(void 0),Ce=d.useRef(null),ye=d.useRef(null),ze=d.useRef(null),Ze={builtin:$("slashBuiltin"),extension:$("slashExtension"),prompt:$("slashPrompt"),skill:$("slashSkill"),plugin:$("slashPlugin")},Qe=g=>{const se=g.match(/^\/([^\s]*)$/);if(se&&o){const qe=se[1].toLowerCase(),_e=E.filter(at=>{const mt=at.name.toLowerCase();if(mt.startsWith(qe))return!0;const Mt=mt.indexOf(":");return Mt>=0&&mt.slice(Mt+1).startsWith(qe)});J(_e.length>0?_e:null),V(0)}else J(null)};d.useEffect(()=>{var se;const g=(se=ze.current)==null?void 0:se.querySelector(".slash-item.active");g==null||g.scrollIntoView({block:"nearest"})},[Ee,G]);const ct=g=>{var mt;const se=G??[],qe=g??se[Ee%Math.max(se.length,1)];if(!qe){J(null);return}const _e=re.match(/^\/([^\s]*)([\s\S]*)$/),at=_e?_e[2]:"";Ie(`/${qe.name} ${at}`),J(null),(mt=Ce.current)==null||mt.focus()},tt=async()=>{const se=[...R].reverse().find(_e=>_e.role==="assistant"&&_e.content.some(at=>at.type==="text"&&at.text)),qe=se==null?void 0:se.content.filter(_e=>_e.type==="text").map(_e=>_e.text).join(`
253
+ `);if(!qe){W("warning",$("slashCopyEmpty"));return}try{await navigator.clipboard.writeText(qe),W("info",$("slashCopied"))}catch{W("error",$("slashCopyFailed"))}},Oe=g=>{if(!g||g.length===0){W("warning",$("foldersNotSupported"));return}const se=Array.from(g).filter(_e=>os(_e.type)),qe=Array.from(g).filter(_e=>!os(_e.type));se.length>0&&ce(se),qe.length>0&&ie(qe)},ee=g=>{var _e;const se=(_e=g.clipboardData)==null?void 0:_e.items;if(!se)return;const qe=[];for(const at of se)if(at.kind==="file"&&os(at.type)){const mt=at.getAsFile();mt&&qe.push(mt)}qe.length!==0&&(g.preventDefault(),ce(qe))},We=o,w=d.useRef(re);d.useEffect(()=>{w.current=re},[re]),d.useEffect(()=>{Qe(w.current)},[E]),d.useEffect(()=>{const g=se=>{var _e;const qe=se.detail;Ie(qe),(_e=Ce.current)==null||_e.focus()};return window.addEventListener("pi-web:fill",g),()=>window.removeEventListener("pi-web:fill",g)},[]),d.useEffect(()=>{if(!Le)return;const g=se=>{se.key==="Escape"&&xe(!1)};return window.addEventListener("keydown",g),()=>window.removeEventListener("keydown",g)},[Le]),d.useEffect(()=>{const g=Ce.current;if(!g)return;g.style.height="auto";const se=g.scrollHeight>220;g.style.height=`${Math.min(g.scrollHeight,220)}px`,g.style.overflowY=se?"auto":"hidden"},[re]);const H=(g=!1)=>{var mt,Mt,Pt,$t,Ft,Jt,nn;if(l){W("info",$("treeVerifying"));return}const se=re.trim(),qe=E.some(lt=>lt.source==="extension"&&lt.name===se.slice(1).split(" ",1)[0])&&se.startsWith("/"),_e=F.some(lt=>lt.imageData||lt.fileData);if(fe.current||!We||!se&&!_e)return;if(se==="/help"){const lt=(Mt=(mt=Ce.current)==null?void 0:mt.closest(".inputbox"))==null?void 0:Mt.getBoundingClientRect();nt(lt==null?void 0:lt.width),xe(!0),Ie(""),(Pt=Ce.current)==null||Pt.focus();return}if(se==="/copy"){Ie(""),($t=Ce.current)==null||$t.focus(),tt();return}const at=()=>{var zt;let lt=F.map(({key:Ht,isDir:an,...At})=>At);if(q&&!qe){const Ht=(zt=r.current)==null?void 0:zt.call(r,q.id);if(!(Ht!=null&&Ht.editorSnapshot)||Ht.path!==q.path||Ht.editorSnapshot.cwd!==q.cwd){W("error",$("currentFileUnavailable"));return}if(new TextEncoder().encode(Ht.editorSnapshot.text).length>512*1024){W("error",$("currentFileTooLarge"));return}lt=Fm(lt,Ht)}const Et=Gt();y({type:"prompt",text:se,queue:g,requestId:Et,attachments:lt})&&(fe.current={id:Et,conversation:M,text:re,queued:k,attachments:F})};if(q&&!qe){const lt=(Ft=r.current)==null?void 0:Ft.call(r,q.id);if(lt!=null&&lt.editorSnapshot&&new TextEncoder().encode(lt.editorSnapshot.text).length>512*1024){W("error",$("currentFileTooLarge"));return}if((Jt=lt==null?void 0:lt.editorSnapshot)!=null&&Jt.dirty){if(!((nn=i.current)==null?void 0:nn.call(i,q.id,at))){W("error",$("currentFileSaving"));return}return}}at()},X=g=>{if(!g.nativeEvent.isComposing){if(G&&G.length>0)switch(g.key){case"ArrowDown":g.preventDefault(),V(se=>(se+1)%G.length);return;case"ArrowUp":g.preventDefault(),V(se=>(se-1+G.length)%G.length);return;case"Tab":case"Enter":g.preventDefault(),ct();return;case"Escape":g.preventDefault(),J(null);return}if(g.key==="Escape"){g.preventDefault(),g.stopPropagation(),O?ge(!1):re?Ie(""):k&&Te();return}if(g.key==="ArrowUp"&&!re&&p===1){g.preventDefault(),ae();return}g.key==="Enter"&&!g.shiftKey&&(g.preventDefault(),H(k&&(g.altKey?_!=="followUp":_==="followUp")))}},ke=()=>e.jsxs("div",{className:"inputbox-actions",children:[k&&e.jsx("button",{type:"button",className:"btn composer-action stop",title:`${$("stopTask")} · Esc`,"aria-label":$("stopTask"),onClick:Te,children:e.jsx(ms,{"aria-hidden":"true"})}),e.jsx("button",{type:"button",className:"btn composer-action send",title:$("sendTip"),"aria-label":$("sendTip"),disabled:!We||l||!re.trim()&&!F.some(g=>g.imageData||g.fileData),onClick:()=>H(k&&_==="followUp"),children:e.jsx(mr,{"aria-hidden":"true"})})]});return e.jsxs("div",{className:`inputbar${Fe?" drop-active":""}`,onDragOver:g=>{g.preventDefault(),g.stopPropagation(),z(!0)},onDragLeave:g=>{g.currentTarget.contains(g.relatedTarget)||z(!1)},onDrop:g=>{var se;g.preventDefault(),g.stopPropagation(),z(!1),Oe(((se=g.dataTransfer)==null?void 0:se.files)??null)},children:[Fe&&e.jsx("div",{className:"drop-overlay",children:e.jsxs("span",{children:["📎 ",$("dropHereToAttach")]})}),G&&G.length>0&&e.jsxs("div",{className:"slash-menu",role:"listbox",ref:ze,"aria-label":$("slashCommands"),children:[e.jsxs("div",{className:"slash-menu-hint",children:[e.jsx("span",{children:$("slashMenuHint")}),e.jsx("span",{className:"slash-menu-close",onClick:()=>J(null),children:"Esc"})]}),G.map((g,se)=>e.jsxs("button",{type:"button",className:`slash-item${se===Ee?" active":""}`,onMouseEnter:()=>V(se),onClick:()=>ct(g),children:[e.jsxs("span",{className:"slash-name",children:["/",g.name]}),e.jsx("span",{className:`slash-source ${g.source}`,children:Ze[g.source]}),e.jsxs("span",{className:"slash-desc",children:[ne(g),g.argumentHint&&e.jsx("span",{className:"slash-hint",children:Pe(g)})]})]},g.name))]}),Le&&e.jsx("div",{className:"modal-backdrop",onClick:()=>xe(!1),children:e.jsxs("div",{className:"slash-help",style:be?{width:be}:void 0,onClick:g=>g.stopPropagation(),children:[e.jsxs("div",{className:"slash-help-head",children:[e.jsxs("span",{children:["⚡ ",$("slashHelpTitle")]}),e.jsx("button",{type:"button",className:"btn",onClick:()=>xe(!1),children:$("close")})]}),e.jsx("div",{className:"slash-help-body",children:E.length===0?e.jsx("div",{className:"slash-help-empty",children:$("slashLoading")}):E.map(g=>e.jsxs("div",{className:"slash-help-row",children:[e.jsxs("span",{className:"slash-help-cmd",children:["/",g.name]}),e.jsx("span",{className:`slash-source ${g.source}`,children:Ze[g.source]}),e.jsxs("span",{className:"slash-help-desc",children:[ne(g),g.argumentHint&&e.jsx("span",{className:"slash-hint",children:Pe(g)})]})]},g.name))})]})}),e.jsx($m,{conversationId:M,active:n,text:re,replace:Ie,restoreImages:g=>ce(g.map((se,qe)=>{const _e=Uint8Array.from(atob(se.data),at=>at.charCodeAt(0));return new File([_e],`recalled-${qe}.${se.mimeType.split("/")[1]??"png"}`,{type:se.mimeType})}))}),f&&e.jsx("div",{className:"composer-working",children:f}),p>0&&e.jsxs("div",{className:"composer-queue",children:[e.jsxs("div",{className:"composer-queue-head",children:[p>1?e.jsxs("button",{type:"button",className:"queue-toggle","aria-expanded":pe,onClick:()=>Ae(!pe),children:[$("pendingMessages",{n:p})," ",pe?"▴":"▾"]}):e.jsxs("span",{className:"queue-single",children:[e.jsx("span",{className:"queue-badge",children:$((De=Z[0])!=null&&De.steer?"queueSteerTag":"queueFollowTag")}),e.jsx("span",{className:"queued-text",title:ar(((He=Z[0])==null?void 0:He.text)??""),children:ar(((ot=Z[0])==null?void 0:ot.text)??"")})]}),p===1&&e.jsx("span",{className:"queue-when",children:$((dt=Z[0])!=null&&dt.steer?"deliverySteerHint":"deliveryFollowHint")}),e.jsxs("button",{type:"button",className:"recall-queue",title:$("recallQueue"),disabled:!We,onClick:ae,children:[e.jsx(Mo,{"aria-hidden":"true"}),$("recallQueueEdit")]})]}),pe&&p>1&&e.jsx("div",{className:"composer-queue-list",children:Z.map((g,se)=>e.jsxs("div",{className:"composer-queue-item",children:[e.jsx("span",{className:"queue-badge",children:$(g.steer?"queueSteerTag":"queueFollowTag")}),e.jsx("span",{className:"queued-text",title:ar(g.text),children:ar(g.text)}),e.jsx("span",{className:"queue-when",children:$(g.steer?"deliverySteerHint":"deliveryFollowHint")})]},se))})]}),e.jsxs("div",{className:`inputbox${re.length>0?" has-draft":""}`,children:[(c==null?void 0:c.commandExecuted)&&c.conversationId===M&&F.length>0&&e.jsx("div",{role:"status",children:$("commandAttachmentsRetained")}),(F.length>0||q)&&e.jsxs("div",{className:"attach-row",children:[q&&e.jsxs("span",{className:"attach-chip current-file",title:`${q.cwd}/${q.path}`,children:["@",q.name,q.dirty?` · ${$("currentFileUnsaved")}`:"",e.jsx("button",{type:"button",className:"attach-remove",title:$("removeAttachment"),onClick:()=>L(g=>({...g,[M]:q.id})),children:"×"})]}),F.map(g=>e.jsxs("span",{className:`attach-chip ${g.imageData?"image":g.fileData?"file":g.mode}`,title:g.imageData?$("attachImage",{name:g.name}):g.fileData?$("attachFile",{name:g.name}):g.isDir?$("folderRef",{path:g.path}):g.mode==="reference"?$("refOnly",{path:g.path}):g.mode==="lines"&&g.lines?$("attachLines",{path:g.path,start:g.lines.start,end:g.lines.end}):$("attachContent",{path:g.path}),children:[g.imageData?"🖼":g.fileData?"📄":g.isDir?"📁":g.mode==="reference"?"🔗":"📎"," ",g.name,g.mode==="lines"&&g.lines&&e.jsxs("span",{className:"attach-range",children:["L",g.lines.start,"-",g.lines.end]}),e.jsx("button",{type:"button",className:"attach-remove",title:$("removeAttachment"),onClick:()=>U(g.key??g.path),children:"×"})]},g.key??`${g.path}|${g.mode}|${g.lines?`${g.lines.start}-${g.lines.end}`:""}`)),e.jsx("span",{className:"attach-hint",children:$("attachHint")})]}),e.jsx("input",{ref:ye,type:"file",multiple:!0,hidden:!0,onChange:g=>{Oe(g.target.files),g.target.value=""}}),e.jsxs("div",{className:"inputbox-row",children:[e.jsx("button",{type:"button",className:"btn attach-img",title:$("uploadFile"),disabled:!We,onClick:()=>{var g;return(g=ye.current)==null?void 0:g.click()},children:e.jsx(oa,{})}),e.jsx("textarea",{ref:Ce,value:re,rows:1,placeholder:We?k?j?$(j==="model"?"placeholderModelSilent":"placeholderToolSilent"):$("placeholderStreamingModes",{primary:$(_==="steer"?"queueSteerTag":"queueFollowTag"),alternate:$(_==="steer"?"queueFollowTag":"queueSteerTag")}):$("composerPlaceholder"):$("placeholderConnecting"),disabled:!We,onChange:g=>{Ie(g.target.value),Qe(g.target.value)},onKeyDown:X,onPaste:ee})]}),e.jsxs("div",{className:"input-tools",children:[e.jsxs("div",{className:"input-tools-left",children:[e.jsx("button",{type:"button",className:"btn composer-attach",title:$("uploadFile"),disabled:!We,onClick:()=>{var g;return(g=ye.current)==null?void 0:g.click()},children:e.jsx(ls,{})}),e.jsx(Il,{state:A,models:N,modelsLoading:T,send:y,onManageModels:Se,compact:!0,segmented:!0}),k&&e.jsx("div",{className:"delivery-control",children:e.jsx(Is,{direction:"up",open:O,onOpenChange:ge,trigger:$(_==="steer"?"queueSteerTag":"queueFollowTag"),children:["steer","followUp"].map(g=>e.jsx(Zn,{active:_===g,onClick:()=>{var se;le(g),ge(!1),(se=Ce.current)==null||se.focus()},children:e.jsxs("span",{className:"delivery-option",children:[e.jsx("strong",{children:$(g==="steer"?"queueSteerTag":"queueFollowTag")}),e.jsx("small",{children:$(g==="steer"?"deliverySteerHint":"deliveryFollowHint")})]})},g))})})]}),e.jsxs("div",{className:"input-tools-right",children:[e.jsx(_m,{stats:a}),e.jsx("button",{type:"button",className:"btn attach-img",title:$("uploadFile"),disabled:!We,onClick:()=>{var g;return(g=ye.current)==null?void 0:g.click()},children:e.jsx(oa,{})}),ke()]})]})]})]})});function Bm({chat:t,send:n}){var A,N;const s=et(),r=t.agentSilence,[i,a]=d.useState(Date.now()),[o,c]=d.useState(!1);if(d.useEffect(()=>{c(!1)},[r==null?void 0:r.since,r==null?void 0:r.conversationId]),d.useEffect(()=>{if(!r)return;const T=window.setInterval(()=>a(Date.now()),1e3);return()=>window.clearInterval(T)},[r]),(A=t.state)!=null&&A.recovery&&Object.values(t.state.recovery).some(Boolean)||!t.ready||!r||r.conversationId!==t.activeConversationId||!((N=t.state)!=null&&N.isStreaming))return null;const l=Math.max(0,Math.floor((i-r.since)/1e3)),p=`${Math.floor(l/60)}:${String(l%60).padStart(2,"0")}`,u=t.state.messages,f=u.findLastIndex(T=>T.role==="user"),k=u[f],j=(k==null?void 0:k.content.map(T=>T.type==="text"&&typeof T.text=="string"?T.text:"").filter(Boolean).join(`
254
+ `).trim())??"",R=u.slice(f+1).some(T=>T.content.some(y=>y.type==="toolCall")),E=r.activity==="model"&&!!j&&!R&&(k==null?void 0:k.content.every(T=>T.type==="text"));return e.jsxs("div",{className:`agent-silence ${r.activity}`,role:"status",children:[e.jsxs("span",{className:"agent-silence-label",children:["⚠ ",r.activity==="tool"?s("toolSilent",{duration:p}):s("modelSilent",{duration:p})]}),o?e.jsx("button",{type:"button",onClick:()=>c(!1),children:s("actions")}):e.jsxs("span",{className:"agent-silence-actions",children:[e.jsx("button",{type:"button",onClick:()=>n({type:"abort"}),children:s("stop")}),e.jsx("button",{type:"button",disabled:!E,title:E?void 0:s("retrySilentUnavailable"),onClick:()=>{E&&n({type:"retry_silent_prompt",conversationId:r.conversationId,text:j})},children:s("retry")}),e.jsx("button",{type:"button",onClick:()=>c(!0),children:s("continueWaiting")})]})]})}function Um(t){const s=t.replaceAll("\\","/").replace(/^(?:\/(?:Users|home)\/[^/]+|[a-zA-Z]:\/Users\/[^/]+)(?=\/|$)/,"~"),r=s.split("/");return r.length>3?`${r.slice(0,2).join("/")}/…/${r.at(-1)}`:s}function Wm({chat:t,send:n}){var M;const s=et(),r=t.state,[i,a]=d.useState(!1),[o,c]=d.useState(""),[l,p]=d.useState(0),u=d.useRef(null),f=t.pathCompletions;if(d.useEffect(()=>{!t.ready||!(r!=null&&r.cwd)||n({type:"get_git_branch"})},[t.ready,r==null?void 0:r.cwd,t.scmDirty,n]),d.useEffect(()=>{const b=()=>{t.ready&&n({type:"get_git_branch"})};return window.addEventListener("focus",b),()=>window.removeEventListener("focus",b)},[t.ready,n]),d.useEffect(()=>{if(!i)return;const b=setTimeout(()=>{n({type:"complete_path",path:o})},150);return()=>clearTimeout(b)},[o,i,n]),d.useEffect(()=>p(0),[f]),d.useEffect(()=>{const b=document.querySelector(`.status-completions .pc-item[data-idx="${l}"]`);b==null||b.scrollIntoView({block:"nearest"})},[l]),!r)return null;const k=((M=t.gitBranch)==null?void 0:M.cwd)===r.cwd?t.gitBranch:null,j=k!=null&&k.notRepo?s("notGitRepoShort"):k!=null&&k.branch?k.detached?`${s("scmDetached")} · ${k.branch}`:k.branch:"—",R=t.ready?"ok":"busy",E=t.ready?s("connected"):s("connecting"),A=()=>{c(r.cwd),a(!0)},N=(b,F)=>{var ce;const U=b.includes("\\")?"\\":"/";c(F?`${b}${U}`:b),p(0),(ce=u.current)==null||ce.focus()},T=b=>{const F=b.trim();F&&F!==r.cwd&&n({type:"set_cwd",path:F,source:"ui"}),a(!1)},y=b=>{if(b.key==="ArrowDown")b.preventDefault(),p(F=>Math.min(F+1,f.length-1));else if(b.key==="ArrowUp")b.preventDefault(),p(F=>Math.max(F-1,0));else if(b.key==="Tab"&&f.length>0){b.preventDefault();const F=f[Math.min(l,f.length-1)];N(F.path,F.type==="dir")}else if(b.key==="Enter"&&!b.nativeEvent.isComposing){const F=o.trim();if(F.endsWith("/")||F.endsWith("\\"))T(F);else if(f.some(U=>U.path===F))T(F);else if(f.length>0&&f[l]){b.preventDefault();const U=f[l];N(U.path,U.type==="dir")}else T(F)}else b.key==="Escape"&&(f.length>0?(b.stopPropagation(),n({type:"complete_path",path:""})):a(!1))};return e.jsxs("footer",{className:"statusbar",children:[e.jsx("span",{className:`status-dot ${R}`,title:E}),e.jsx("span",{className:"status-item status-connection",children:E}),t.serverVersion&&e.jsxs("span",{className:"status-item status-version",title:`pi-harness v${t.serverVersion}`,children:["v",t.serverVersion]}),e.jsx("span",{className:"status-sep",children:"·"}),e.jsxs("span",{className:"status-item status-branch",title:k!=null&&k.notRepo?j:`${s("scmCurrentBranch")}: ${j}`,children:[!(k!=null&&k.notRepo)&&e.jsx("span",{className:"workspace-stat-label",children:s("workspaceBranch")}),e.jsx("span",{className:"status-branch-name",children:j})]}),t.statuses.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"status-sep",children:"·"}),e.jsx("span",{className:"status-item ext-status",title:s("pluginStatus"),children:t.statuses.map(b=>b.text).join(" · ")})]}),e.jsx("span",{id:"wiki-status-slot"}),i?e.jsxs("div",{className:"status-cwd-wrap",children:[e.jsx("input",{ref:u,className:"status-cwd-input",value:o,autoFocus:!0,placeholder:s("enterPath"),onChange:b=>c(b.target.value),onKeyDown:y,onBlur:()=>a(!1)}),f.length>0&&e.jsx("ul",{className:"status-completions",onMouseDown:b=>b.preventDefault(),children:f.map((b,F)=>e.jsx("li",{children:e.jsxs("button",{type:"button","data-idx":F,className:`pc-item ${F===l?"sel":""}`,onMouseEnter:()=>p(F),onClick:()=>N(b.path,b.type==="dir"),children:[e.jsx("span",{className:"pc-icon",children:b.type==="dir"?e.jsx(Ks,{}):e.jsx(Gs,{})}),e.jsxs("span",{className:"pc-body",children:[e.jsx("span",{className:"pc-name",children:b.name}),e.jsx("span",{className:"pc-path",children:b.path})]})]})},b.path))})]}):e.jsxs("button",{type:"button",className:"status-item status-cwd",title:s("cwdTip",{path:r.cwd}),onClick:A,children:[e.jsx("span",{className:"workspace-stat-label",children:s("workspacePath")}),e.jsx("span",{className:"workspace-stat-path",children:Um(r.cwd)})]})]})}function wi({dialog:t,send:n}){const s=et(),[r,i]=d.useState(""),[a,o]=d.useState(0),c=u=>{n({type:"dialog_response",conversationId:t.conversationId,id:t.id,value:u})};d.useEffect(()=>{i(t.kind==="editor"?String(t.args[0]??""):""),o(0);const u=f=>{f.key==="Escape"&&c(null)};return document.addEventListener("keydown",u),()=>document.removeEventListener("keydown",u)},[t.id]);const l=Array.isArray(t.args[0])?t.args[0]:[],p=typeof t.args[0]=="string"?t.args[0]:"";return e.jsxs("div",{className:"dialog-inline","data-dialog-kind":t.kind,children:[e.jsxs("div",{className:"dialog-head",children:[e.jsx("span",{className:"dialog-badge",children:s("pluginRequest")}),t.title&&t.title!==s("pluginRequest")&&e.jsx("span",{className:"dialog-title",children:t.title}),e.jsx("button",{type:"button",className:"dialog-dismiss",title:s("cancel"),onClick:()=>c(null),children:"✕"})]}),t.kind==="select"&&e.jsxs("div",{className:"dialog-options",children:[l.map((u,f)=>e.jsx("button",{type:"button",className:`dialog-option ${f===a?"sel":""}`,onMouseEnter:()=>o(f),onClick:()=>c(u),children:u},f)),l.length===0&&e.jsx("div",{className:"dialog-hint",children:s("noOptions")})]}),t.kind==="confirm"&&e.jsxs("div",{className:"dialog-body",children:[e.jsx("p",{children:p}),e.jsxs("div",{className:"dialog-actions",children:[e.jsx("button",{type:"button",className:"btn",onClick:()=>c(!1),children:s("cancel")}),e.jsx("button",{type:"button",className:"btn primary",onClick:()=>c(!0),children:s("ok")})]})]}),(t.kind==="input"||t.kind==="editor")&&e.jsxs("div",{className:"dialog-body",children:[t.kind==="editor"?e.jsx("textarea",{className:"dialog-input",rows:8,value:r,autoFocus:!0,onChange:u=>i(u.target.value)}):e.jsx("input",{className:"dialog-input",value:r,placeholder:p||s("inputPlaceholder"),autoFocus:!0,onChange:u=>i(u.target.value),onKeyDown:u=>{u.key==="Enter"&&!u.nativeEvent.isComposing&&c(r)}}),e.jsxs("div",{className:"dialog-actions",children:[e.jsx("button",{type:"button",className:"btn",onClick:()=>c(null),children:s("cancel")}),e.jsx("button",{type:"button",className:"btn primary",onClick:()=>c(r),children:s("ok")})]})]})]})}function qm(t){if(t.x==="?"&&t.y==="?")return"untracked";const n=t.x!==" "&&t.x!=="?",s=t.y!==" "&&t.y!=="?";return n&&s?"both":n?"staged":"unstaged"}function zm({chat:t,send:n,terminal:s,active:r,commitToShow:i,onSwitchToTerminal:a}){var tt,Oe;const o=et(),[c,l]=d.useState(null),[p,u]=d.useState([]),[f,k]=d.useState(""),[j,R]=d.useState(new Map),[E,A]=d.useState("changes"),[N,T]=d.useState([]),[y,M]=d.useState(null),[b,F]=d.useState(""),[U,ce]=d.useState(!1),[ie,W]=d.useState(null),[ve,Se]=d.useState(null),[$,$e]=d.useState(!1),[L,q]=d.useState(!1),[fe,je]=d.useState(!1),[ne,Pe]=d.useState(null),[B,we]=d.useState(!1),[re,Ie]=d.useState(""),_=d.useRef(0),le=d.useRef(-1),O=d.useRef(-1),ge=d.useRef(-1),pe=d.useRef(-1),Ae=d.useRef(void 0),ae=d.useRef(null),Te=d.useRef([]),Z=d.useCallback(ee=>{if(ee.reqId===le.current){if(le.current=-1,q(!1),Pe(null),!ee.ok){Pe(ee.error??"查询失败");return}if(ee.notRepo){we(!0),l(null),u([]),R(new Map),T([]),M(null),F(""),Se(null);return}we(!1);const We={branch:ee.branch??"",detached:!!ee.detached,upstream:ee.upstream??null,ahead:ee.ahead??0,behind:ee.behind??0,upstreamGone:!!ee.upstreamGone,files:(ee.files??[]).map(X=>({...X}))},w=(ee.branches??[]).map(X=>({...X})),H=new Map;for(const[X,ke]of Object.entries(ee.stats??{}))H.set(X,{add:ke[0],del:ke[1]});l(We),u(w),R(H),k(X=>{var ke;return We.detached?X||"":We.branch&&w.some(De=>De.name===We.branch)?We.branch:X&&w.some(De=>De.name===X)?X:((ke=w[0])==null?void 0:ke.name)??""}),Se(X=>X&&!We.files.some(ke=>ke.path===X.file.path)?null:X)}else if(ee.reqId===O.current){if(O.current=-1,$e(!1),!ee.ok){Pe(ee.error??"查询失败");return}const We=ae.current;if(!We)return;Se({file:We,staged:ee.stagedText??"",worktree:ee.worktreeText??"",untracked:!!ee.untracked,untrackedText:ee.untrackedText,untrackedKind:ee.untrackedKind,untrackedTruncated:ee.untrackedTruncated})}else if(ee.reqId===pe.current){if(pe.current=-1,je(!1),!ee.ok){Pe(ee.error??"查询失败");return}T((ee.history??[]).map(We=>({...We})))}else if(ee.reqId===ge.current){if(ge.current=-1,ce(!1),!ee.ok){Pe(ee.error??"查询失败");return}F(ee.text??"")}},[]);d.useEffect(()=>{const ee=t.scmData;ee&&ee.type==="scm_data"&&Z(ee)},[t.scmData,Z]);const Fe=d.useCallback((ee,We)=>{if(!t.ready||t.status!=="open")return!1;const w=++_.current;return n({...ee,reqId:w})?(We.current=w,!0):(_.current-=1,!1)},[t.ready,t.status,n]),z=d.useCallback((ee=!1,We=!1)=>{var w;!t.ready||t.status!=="open"||(w=t.state)!=null&&w.cwd&&(Ae.current!==void 0&&Ae.current!==t.state.cwd&&(l(null),u([]),R(new Map),T([]),je(!1),pe.current=-1,M(null),F(""),Se(null),W(null)),Ae.current=t.state.cwd,Pe(null),Fe({type:"scm_status"},le)&&(We||q(!0)))},[t.ready,(tt=t.state)==null?void 0:tt.cwd,t.status,Fe]),G=d.useCallback(ee=>{W(ee),M(null),ae.current=ee,Se(null),$e(!0),Pe(null),Fe({type:"scm_filediff",path:ee.path},O)||($e(!1),Pe(o("scmConnecting")))},[Fe,o]),J=d.useCallback(ee=>{M(ee),W(null),Se(null),F(""),ce(!0),Pe(null),Fe({type:"scm_commit",hash:ee.hash},ge)||ce(!1)},[Fe]),Ee=d.useCallback((ee,We)=>{var X,ke;if(!t.ready)return;const w={name:ee,command:We,cwd:"${pwd}"},H=t.terminals.find(De=>De.title===ee);if(H)s.restart(H.id),n({type:"run_command",terminalId:H.id,conversationId:H.conversationId,command:w,cols:80,rows:24});else{const De=Gt();s.create({id:De,conversationId:t.activeConversationId||((X=t.state)==null?void 0:X.conversationId)||"",title:ee,cwd:((ke=t.state)==null?void 0:ke.cwd)??"",cols:80,rows:24,running:!0,exitCode:null,command:w})}a()},[t.ready,(Oe=t.state)==null?void 0:Oe.cwd,t.terminals,a,n,s]),V=d.useCallback(()=>{const ee=re.trim();if(!ee||B)return;const We=ee.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/`/g,"\\`").replace(/\$/g,"\\$");Ee("git commit",`git add -A && git commit -m "${We}"`),Ie("")},[re,B,Ee]),Le=ee=>`'${ee.replace(/'/g,"'\\''")}`,xe=d.useCallback(ee=>{B||Ee("git add",`git add -- ${Le(ee.path)}`)},[B,Ee]),be=d.useCallback(ee=>{B||Ee("git reset",`git reset HEAD -- ${Le(ee.path)}`)},[B,Ee]),nt=d.useCallback(()=>{if(!f||B)return;const ee=p.find(We=>We.name===f);if(ee!=null&&ee.remote&&typeof ee.remote=="string"){const We=f.slice(ee.remote.length+1);Ee("git checkout",`git checkout -b ${We} ${f} || git checkout ${f}`)}else Ee("git checkout",`git checkout ${f}`)},[f,p,B,Ee]),Ce=d.useCallback(()=>Ee("git push","git push"),[Ee]),ye=d.useCallback(()=>Ee("git pull","git pull"),[Ee]),ze=d.useCallback(()=>{Fe({type:"scm_history"},pe)||(pe.current=-1)},[Fe]);d.useEffect(()=>{r&&z()},[r,z]),d.useEffect(()=>{E==="history"&&c&&ze()},[E,c,ze]);const Ze=d.useRef(null);d.useEffect(()=>{!r||!t.ready||t.status!=="open"||!i||Ze.current===i.token||(Ze.current=i.token,A("history"),J({hash:i.hash,shortHash:i.hash,subject:"",author:"",date:"",decorations:"",graph:""}))},[r,t.ready,t.status,i,J]),d.useEffect(()=>{t.scmDirty>0&&r&&z(!1,!0)},[t.scmDirty]),d.useEffect(()=>{if(!r||!t.ready||t.status!=="open")return;const ee=setInterval(()=>{document.visibilityState!=="hidden"&&z(!1,!0)},3e4);return()=>clearInterval(ee)},[r,t.ready,t.status,z]),d.useEffect(()=>{const ee=Te.current;if(Te.current=t.terminals,!r)return;t.terminals.some(w=>{var X;return w.running!==!1?!1:((X=ee.find(ke=>ke.id===w.id))==null?void 0:X.running)===!0&&/^git /.test(w.title)})&&t.ready&&t.status==="open"&&(z(!1,!0),E==="history"&&c&&ze())},[t.terminals,r,t.ready,t.status,z,E,c,ze]);const Qe={staged:o("scmStaged"),unstaged:o("scmUnstaged"),untracked:o("scmUntracked"),both:o("scmStagedUnstaged")},ct=ee=>{const We=ee.split(`
255
+ `);return e.jsx("pre",{className:"scm-diff-pre",children:We.map((w,H)=>{let X="";return w.startsWith("diff --git")||w.startsWith("index ")||w.startsWith("new file")||w.startsWith("deleted file")||w.startsWith("old mode")||w.startsWith("new mode")||w.startsWith("similarity index")||w.startsWith("rename ")||w.startsWith("copy ")||w.startsWith("Binary files")||w.startsWith("---")||w.startsWith("+++")?X="hdr":w.startsWith("@@")?X="hunk":w.startsWith("+")?X="add":w.startsWith("-")&&(X="del"),e.jsx("div",{className:`scm-diff-line ${X}`,children:w||" "},H)})})};return e.jsxs("div",{className:"scm-view",children:[e.jsxs("div",{className:"scm-header",children:[e.jsxs("div",{className:"scm-title-row",children:[e.jsxs("span",{className:"scm-title",children:[e.jsx(hs,{}),o("scmTitle")]}),e.jsxs("div",{className:"scm-view-tabs",role:"tablist",children:[e.jsx("button",{type:"button",role:"tab","aria-selected":E==="changes",className:E==="changes"?"active":"",onClick:()=>{A("changes"),Pe(null)},children:o("scmChanges")}),e.jsx("button",{type:"button",role:"tab","aria-selected":E==="history",className:E==="history"?"active":"",onClick:()=>{A("history"),Pe(null)},children:o("scmHistory")})]}),e.jsx("button",{type:"button",className:"panel-refresh",title:o("scmRefreshTip"),disabled:L,onClick:()=>z(!0),children:e.jsx(ys,{className:L?"scm-spin":""})})]}),e.jsxs("div",{className:"scm-row",children:[e.jsxs("span",{className:"scm-branch-current",title:o("scmCurrentBranch"),children:[e.jsx(hs,{}),c?c.detached?o("scmDetached"):c.branch:"…",(c==null?void 0:c.upstream)&&e.jsx("span",{className:"scm-upstream",children:c.upstreamGone?o("scmUpstreamGone"):c.ahead>0||c.behind>0?o("scmAheadBehind",{ahead:c.ahead,behind:c.behind}):c.upstream})]}),e.jsxs("select",{className:"scm-select",value:f,disabled:B||p.length===0,title:o("scmSwitchBranch"),onChange:ee=>k(ee.target.value),children:[e.jsx("option",{value:"",disabled:!0,children:o("scmSelectBranch")}),p.filter(ee=>!ee.remote).map(ee=>e.jsx("option",{value:ee.name,children:ee.current?`* ${ee.name}`:ee.name},ee.name)),p.some(ee=>ee.remote)&&e.jsx("optgroup",{label:o("scmRemoteBranches"),children:p.filter(ee=>ee.remote).map(ee=>e.jsx("option",{value:ee.name,children:ee.name},ee.name))})]}),e.jsxs("button",{type:"button",className:"btn",disabled:!f||f===(c==null?void 0:c.branch)||B,title:o("scmSwitchBranchTip",{branch:f}),onClick:nt,children:[e.jsx(hs,{}),o("scmSwitch")]}),e.jsxs("button",{type:"button",className:"btn",disabled:!c||c.detached||B,title:o("scmPushTip"),onClick:Ce,children:[e.jsx(mr,{}),o("scmPush")]}),e.jsxs("button",{type:"button",className:"btn",disabled:!c||c.detached||B,title:o("scmPullTip"),onClick:ye,children:[e.jsx($o,{}),o("scmPull")]}),e.jsx("input",{className:"scm-commit-input",value:re,placeholder:o("scmCommitPlaceholder"),disabled:B,onChange:ee=>Ie(ee.target.value),onKeyDown:ee=>{ee.key==="Enter"&&!ee.nativeEvent.isComposing&&V()}}),e.jsxs("button",{type:"button",className:"btn primary",disabled:!re.trim()||B,title:o("scmCommitTip"),onClick:V,children:[e.jsx(ts,{}),o("scmCommit")]})]})]}),e.jsxs("div",{className:"scm-body",children:[E==="history"?e.jsxs("div",{className:"scm-history",children:[e.jsxs("div",{className:"scm-files-header",children:[e.jsx("span",{children:o("scmHistory")}),N.length>0&&e.jsx("span",{className:"scm-files-count",children:N.length})]}),e.jsx("div",{className:"scm-history-list",children:B?e.jsx("div",{className:"scm-empty",children:o("scmNotGitRepo")}):!c||fe?e.jsx("div",{className:"scm-empty",children:t.status==="open"?o("scmLoading"):o("scmConnecting")}):N.length===0?e.jsx("div",{className:"scm-empty",children:o("scmNoHistory")}):N.map(ee=>e.jsxs("button",{type:"button",className:`scm-commit ${(y==null?void 0:y.hash)===ee.hash?"active":""}`,onClick:()=>J(ee),title:ee.hash,children:[e.jsx("span",{className:"scm-commit-graph","aria-hidden":"true",children:ee.graph||"* "}),e.jsxs("span",{className:"scm-commit-info",children:[e.jsx("span",{className:"scm-commit-subject",children:ee.subject}),e.jsxs("span",{className:"scm-commit-meta",children:[ee.shortHash," · ",ee.author," · ",ee.date]}),ee.decorations&&e.jsx("span",{className:"scm-commit-refs",children:ee.decorations})]})]},ee.hash))})]}):e.jsxs("div",{className:"scm-files",children:[e.jsxs("div",{className:"scm-files-header",children:[e.jsx("span",{children:o("scmChanges")}),c&&c.files.length>0&&e.jsx("span",{className:"scm-files-count",children:c.files.length})]}),e.jsx("div",{className:"scm-files-list",children:B?e.jsx("div",{className:"scm-empty",children:o("scmNotGitRepo")}):c?c.files.length===0?e.jsx("div",{className:"scm-empty",children:o("scmNoChanges")}):c.files.map(ee=>{const We=qm(ee),w=j.get(ee.path);return e.jsxs("div",{className:`scm-file ${(ie==null?void 0:ie.path)===ee.path?"active":""}`,title:Qe[We],onClick:()=>G(ee),children:[e.jsx("span",{className:"scm-file-xy x",children:We==="untracked"?" ":ee.x!==" "?ee.x:" "}),e.jsx("span",{className:`scm-file-xy y${We==="untracked"?" untracked":""}`,"aria-label":We==="untracked"?o("scmUntracked"):void 0,children:We==="untracked"?o("scmUntrackedBadge"):ee.y!==" "?ee.y:" "}),e.jsx("span",{className:"scm-file-path",children:ee.path}),w&&(w.add>0||w.del>0)&&e.jsxs("span",{className:"scm-file-stat",children:[w.add>0&&e.jsxs("span",{className:"add",children:["+",w.add]}),w.del>0&&e.jsxs("span",{className:"del",children:["-",w.del]})]}),e.jsxs("span",{className:"scm-file-actions",children:[(ee.y!==" "||We==="untracked")&&e.jsx("button",{type:"button",className:"scm-act",title:o("scmStageTip",{path:ee.path}),onClick:H=>{H.stopPropagation(),xe(ee)},children:"+"}),We==="staged"||We==="both"?e.jsx("button",{type:"button",className:"scm-act",title:o("scmUnstageTip",{path:ee.path}),onClick:H=>{H.stopPropagation(),be(ee)},children:"−"}):null]})]},ee.path)}):e.jsx("div",{className:"scm-empty",children:t.status==="open"?o("scmLoading"):o("scmConnecting")})})]}),e.jsxs("div",{className:"scm-diff",children:[e.jsxs("div",{className:"scm-diff-header",children:[e.jsx("span",{children:E==="history"?y?`${y.shortHash} ${y.subject}`:o("scmCommitDetail"):ie?ie.path:o("scmDiff")}),(E==="history"?U:$)&&e.jsx("span",{className:"scm-diff-loading",children:o("scmLoading")})]}),e.jsx("div",{className:"scm-diff-body",children:E==="history"?e.jsxs(e.Fragment,{children:[ne&&e.jsx("div",{className:"scm-error",children:ne}),!y&&!ne&&e.jsx("div",{className:"scm-empty",children:o("scmSelectCommitHint")}),y&&U&&!ne&&e.jsx("div",{className:"scm-empty",children:o("scmLoading")}),y&&!U&&!ne&&b?ct(b):null]}):e.jsxs(e.Fragment,{children:[ne&&e.jsx("div",{className:"scm-error",children:ne}),!ie&&!ne&&e.jsx("div",{className:"scm-empty",children:o("scmSelectFileHint")}),ie&&!ve&&!ne&&e.jsx("div",{className:"scm-empty",children:o("scmLoading")}),ie&&ve&&ve.untracked&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"scm-diff-section",children:o("scmUntracked")}),ve.untrackedKind==="text"?ve.untrackedText?e.jsx("pre",{className:"scm-diff-pre scm-untracked-content",children:ve.untrackedText}):e.jsx("div",{className:"scm-empty",children:o("scmEmptyFile")}):e.jsx("div",{className:"scm-empty",children:o(ve.untrackedKind==="directory"?"scmUntrackedDirectory":"scmUntrackedBinary")}),ve.untrackedTruncated&&e.jsx("div",{className:"scm-empty",children:o("scmPreviewTruncated")})]}),ie&&ve&&!ve.untracked&&e.jsxs(e.Fragment,{children:[ve.staged&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"scm-diff-section",children:o("scmStaged")}),ct(ve.staged)]}),ve.worktree&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"scm-diff-section",children:o("scmUnstaged")}),ct(ve.worktree)]}),!ve.staged&&!ve.worktree&&e.jsx("div",{className:"scm-empty",children:o("scmNoDiff")})]})]})})]})]}),e.jsxs("div",{className:"scm-hint",children:[e.jsx(Ni,{}),e.jsx("span",{children:o("scmRunsInTerminal")}),e.jsx("button",{type:"button",className:"scm-goto-term",onClick:a,children:o("scmViewTerminal")})]})]})}function Vm({entry:t,send:n}){const s=d.useRef(null);return d.useEffect(()=>{const r=s.current;if(!r)return;let i;try{i=t.module.mount(r,Yd(t.info.id,a=>n(a)))}catch(a){console.error(`[plugin:${t.info.id}] mount failed:`,a),r.textContent=`插件 ${t.info.name} 挂载失败`}return()=>{if(typeof i=="function")try{i()}catch(a){console.error(`[plugin:${t.info.id}] cleanup failed:`,a)}r.textContent=""}},[t,n]),e.jsx("div",{className:"plugin-view",ref:s})}function Km({send:t,piConfigured:n,piAgentInstalled:s,providers:r,installResult:i,onClose:a}){const o=et(),[c,l]=d.useState(!1),[p,u]=d.useState(""),[f,k]=d.useState(""),[j,R]=d.useState(!1);d.useEffect(()=>{t({type:"list_providers"})},[t]),d.useEffect(()=>{n&&a()},[n,a]),d.useEffect(()=>{i&&l(!1)},[i]),d.useEffect(()=>{var M;!p&&r.length>0&&u(((M=r.find(b=>!b.configured))==null?void 0:M.id)??r[0].id)},[r,p]);const E=()=>{c||(l(!0),t({type:"install_pi_agent"}))},A=()=>{!f.trim()||j||(R(!0),t({type:"set_provider_api_key",provider:p.trim(),apiKey:f.trim()}),setTimeout(()=>R(!1),3e3))},N=()=>{t({type:"get_state"}),t({type:"list_providers"})},T=r.find(M=>M.id===p),y=i!==null&&!i.ok;return e.jsx("div",{className:"modal-backdrop",children:e.jsxs("div",{className:"modal setup-modal",children:[e.jsx("button",{type:"button",className:"modal-close","aria-label":o("close"),onClick:a,children:e.jsx(Wt,{})}),e.jsxs("div",{className:"modal-head",children:[e.jsx(Ei,{className:"modal-head-icon"}),e.jsx("h2",{children:o("setupTitle")})]}),e.jsx("p",{className:"modal-desc",children:o("setupDesc")}),y?e.jsxs("div",{className:"setup-failed",children:[e.jsx("div",{className:"setup-done",children:o("installFailed")}),e.jsx("pre",{className:"setup-detail",children:i.detail}),e.jsxs("div",{className:"setup-actions",children:[e.jsx("button",{type:"button",className:"btn primary",disabled:c,onClick:E,children:o("retryInstall")}),e.jsx("button",{type:"button",className:"btn",onClick:a,children:o("skip")})]})]}):s||i!=null&&i.ok?e.jsxs("div",{className:"setup-key-form",children:[e.jsx("div",{className:"setup-done",children:i!=null&&i.ok?o("installDone"):o("cliReadyHint")}),e.jsxs("label",{className:"field",children:[e.jsx("span",{className:"field-label",children:o("provider")}),e.jsxs("select",{value:p,onChange:M=>u(M.target.value),children:[r.length===0&&e.jsx("option",{value:"",children:o("loading")}),r.map(M=>e.jsxs("option",{value:M.id,children:[M.name,"(",M.id,")",M.configured?` · ${o("configured")}`:""]},M.id))]}),(T==null?void 0:T.configured)&&e.jsx("div",{className:"field-hint",children:o("providerKeyReady")})]}),e.jsxs("label",{className:"field",children:[e.jsx("span",{className:"field-label",children:o("apiKey")}),e.jsx("input",{type:"password",value:f,onChange:M=>k(M.target.value),placeholder:"sk-…"})]}),e.jsxs("div",{className:"setup-actions",children:[e.jsx("button",{type:"button",className:"btn primary",disabled:!f.trim()||j||!p,onClick:A,children:o(j?"saving":"saveAndStart")}),e.jsxs("button",{type:"button",className:"btn",onClick:N,children:[e.jsx(ys,{})," ",o("recheck")]})]})]}):e.jsxs("div",{className:"setup-actions",children:[e.jsx("button",{type:"button",className:"btn primary",disabled:c,onClick:E,children:o(c?"installing":"autoInstall")}),e.jsx("button",{type:"button",className:"btn",onClick:a,children:o("skip")})]})]})})}const Gm=["openai-completions","openai-responses","anthropic-messages","google-generative-ai"],qi=()=>({id:"",name:"",reasoning:!1,input:"text",contextWindow:"",maxTokens:""}),Jm=()=>({providerId:"",name:"",api:"openai-completions",baseUrl:"",apiKey:"",authHeader:!0,models:[qi()]});function io(t){return{providerId:t.providerId,nonChatModelCount:t.nonChatModelCount,name:t.name??"",api:t.api??"openai-completions",baseUrl:t.baseUrl??"",apiKey:t.apiKey??"",authHeader:t.authHeader??!1,models:(t.models.length?t.models:[qi()]).map(n=>{var s;return{id:n.id,name:n.name??"",reasoning:n.reasoning??!1,input:(s=n.input)!=null&&s.includes("image")?"text-image":"text",contextWindow:n.contextWindow?String(n.contextWindow):"",maxTokens:n.maxTokens?String(n.maxTokens):""}})}}function Qm({send:t,providers:n,providerStatus:s,fetchModelsResult:r,refreshProviderResult:i,cloneProviderResult:a,onClose:o}){const c=et(),[l,p]=d.useState(null),[u,f]=d.useState({}),[k,j]=d.useState(null),[R,E]=d.useState({}),[A,N]=d.useState(!1),[T,y]=d.useState(0),[M,b]=d.useState(null),F=d.useRef(0),[U,ce]=d.useState({});d.useRef(0);const ie=d.useRef(0),[W,ve]=d.useState(null),Se=d.useRef(0),$=d.useRef(0);d.useEffect(()=>{t({type:"list_models_config"}),t({type:"list_providers"})},[t]);const $e=()=>{if(!l)return;const B=l.baseUrl.trim();if(!B){b({ok:!1,text:c("fetchModelsNeedBaseUrl")});return}if(A)return;N(!0),b(null);const we=T+1;y(we),t({type:"fetch_models",reqId:we,baseUrl:B,apiKey:l.apiKey.trim()||void 0,authHeader:l.authHeader,api:l.api})};d.useEffect(()=>{var B;if(!(!r||r.reqId===F.current))if(F.current=r.reqId,N(!1),r.ok&&((B=r.models)!=null&&B.length)){const we=r.models;p(re=>{if(!re)return re;const Ie=re.models.map(ge=>{var ae;if(!ge.id.trim())return ge;const pe=we.find(Te=>Te.id===ge.id.trim());if(!pe)return ge;const Ae={...ge};return!Ae.name&&pe.name&&(Ae.name=pe.name),!Ae.contextWindow&&pe.contextWindow&&(Ae.contextWindow=String(pe.contextWindow)),!Ae.maxTokens&&pe.maxTokens&&(Ae.maxTokens=String(pe.maxTokens)),Ae.input==="text"&&((ae=pe.input)!=null&&ae.includes("image"))&&(Ae.input="text-image"),!Ae.reasoning&&pe.reasoning&&(Ae.reasoning=!0),Ae}),_=new Set(Ie.map(ge=>ge.id.trim()).filter(Boolean)),le=we.filter(ge=>!_.has(ge.id)).map(ge=>{var pe;return{id:ge.id,name:ge.name??"",reasoning:ge.reasoning??!1,input:(pe=ge.input)!=null&&pe.includes("image")?"text-image":"text",contextWindow:ge.contextWindow?String(ge.contextWindow):"",maxTokens:ge.maxTokens?String(ge.maxTokens):""}}),O=[...Ie,...le];return O.some(ge=>ge.id.trim())?{...re,models:O.filter(ge=>ge.id.trim())}:re}),b({ok:!0,text:c("fetchModelsOk",{n:we.length})})}else b({ok:!1,text:r.error||c("fetchModelsEmpty")})},[r]);const L=B=>{const we=(u[B.id]??"").trim();!we||k||(j(B.id),t({type:"set_provider_api_key",provider:B.id,apiKey:we}),setTimeout(()=>{j(null),f(re=>({...re,[B.id]:""})),E(re=>({...re,[B.id]:!1})),t({type:"list_providers"})},1500))},q=()=>{if(!l)return;const B=l.providerId.trim(),we=l.models.filter(Ie=>Ie.id.trim()).map(Ie=>({id:Ie.id.trim(),name:Ie.name.trim()||void 0,reasoning:Ie.reasoning||void 0,input:Ie.input==="text-image"?["text","image"]:void 0,contextWindow:Ie.contextWindow?Number(Ie.contextWindow):void 0,maxTokens:Ie.maxTokens?Number(Ie.maxTokens):void 0})),re={providerId:B,name:l.name.trim()||void 0,api:l.api.trim()||void 0,baseUrl:l.baseUrl.trim()||void 0,apiKey:l.apiKey.trim()||void 0,authHeader:l.authHeader||void 0,models:we};t({type:"save_model_config",providerId:B,config:re}),o()};d.useEffect(()=>{!i||i.reqId===ie.current||(ie.current=i.reqId,ce({}))},[i]);const fe=B=>{if(W)return;ve(B.id);const we=++Se.current+Date.now();t({type:"clone_provider",provider:B.id,reqId:we})};d.useEffect(()=>{!a||a.reqId===$.current||($.current=a.reqId,ve(null),a.ok&&a.config&&p(io({...a.config,apiKey:""})))},[a]);const je=B=>{window.confirm(c("clearKeyConfirm",{id:B}))&&t({type:"clear_provider_api_key",provider:B})},ne=B=>{window.confirm(c("deleteProviderConfirm",{id:B.providerId,n:B.models.length}))&&t({type:"delete_model_config",providerId:B.providerId})},Pe=(B,we)=>{l&&p({...l,models:l.models.map((re,Ie)=>Ie===B?{...re,...we}:re)})};return e.jsx("div",{className:"modal-backdrop",onClick:o,children:e.jsxs("div",{className:"modal model-modal",onClick:B=>B.stopPropagation(),children:[e.jsx("button",{type:"button",className:"modal-close","aria-label":c("close"),onClick:o,children:e.jsx(Wt,{})}),e.jsx("div",{className:"modal-head",children:e.jsx("h2",{children:c(l?"editProvider":"manageModelsTitle")})}),l?e.jsxs("div",{className:"provider-form",children:[e.jsxs("div",{className:"form-grid",children:[e.jsxs("label",{className:"field",children:[e.jsxs("span",{className:"field-label",children:[c("providerId")," ",e.jsx("em",{children:c("providerIdHint")})]}),e.jsx("input",{type:"text",value:l.providerId,disabled:n.some(B=>B.providerId===l.providerId),onChange:B=>p({...l,providerId:B.target.value}),placeholder:"my-proxy"})]}),e.jsxs("label",{className:"field",children:[e.jsx("span",{className:"field-label",children:c("displayName")}),e.jsx("input",{type:"text",value:l.name,onChange:B=>p({...l,name:B.target.value}),placeholder:c("displayNamePh")})]}),e.jsxs("label",{className:"field",children:[e.jsx("span",{className:"field-label",children:c("apiType")}),e.jsx("select",{value:l.api,onChange:B=>p({...l,api:B.target.value}),children:Gm.map(B=>e.jsx("option",{value:B,children:B},B))})]}),e.jsxs("label",{className:"field",children:[e.jsxs("span",{className:"field-label",children:["baseUrl ",e.jsx("em",{children:c("baseUrlHint")})]}),e.jsx("input",{type:"text",value:l.baseUrl,onChange:B=>p({...l,baseUrl:B.target.value}),placeholder:"http://localhost:11434/v1"})]}),e.jsxs("label",{className:"field",children:[e.jsx("span",{className:"field-label",children:c("apiKey")}),e.jsx("input",{type:"password",value:l.apiKey,onChange:B=>p({...l,apiKey:B.target.value}),placeholder:c("apiKeyHint")})]}),e.jsxs("label",{className:"field check",children:[e.jsx("input",{type:"checkbox",checked:l.authHeader,onChange:B=>p({...l,authHeader:B.target.checked})}),e.jsx("span",{children:c("authHeader")})]})]}),!!l.nonChatModelCount&&e.jsx("p",{className:"hint",children:c("nonChatModelsPreserved",{n:l.nonChatModelCount})}),e.jsxs("div",{className:"model-section-head",children:[e.jsx("span",{className:"form-section-title",children:c("modelsTitle")}),e.jsxs("span",{className:"model-section-actions",children:[M&&e.jsx("span",{className:`fetch-msg ${M.ok?"ok":"err"}`,title:M.text,children:M.text}),e.jsxs("button",{type:"button",className:"btn sm",disabled:A||!l.baseUrl.trim(),title:c("fetchModelsHint"),onClick:$e,children:[e.jsx(Pr,{})," ",c(A?"fetchingModels":"fetchModels")]})]})]}),l.models.map((B,we)=>e.jsxs("div",{className:"model-row",children:[e.jsx("input",{type:"text",value:B.id,onChange:re=>Pe(we,{id:re.target.value}),placeholder:c("modelIdReq")}),e.jsx("input",{type:"text",value:B.name,onChange:re=>Pe(we,{name:re.target.value}),placeholder:c("displayName")}),e.jsxs("select",{value:B.input,onChange:re=>Pe(we,{input:re.target.value}),children:[e.jsx("option",{value:"text",children:c("text")}),e.jsx("option",{value:"text-image",children:c("textImage")})]}),e.jsxs("label",{className:"check",children:[e.jsx("input",{type:"checkbox",checked:B.reasoning,onChange:re=>Pe(we,{reasoning:re.target.checked})}),e.jsx("span",{children:c("reasoning")})]}),e.jsx("input",{type:"number",value:B.contextWindow,onChange:re=>Pe(we,{contextWindow:re.target.value}),placeholder:c("contextWindow"),title:"contextWindow"}),e.jsx("input",{type:"number",value:B.maxTokens,onChange:re=>Pe(we,{maxTokens:re.target.value}),placeholder:c("maxOutput"),title:"maxTokens"}),e.jsx("button",{type:"button",className:"iconbtn danger",title:c("removeModel"),onClick:()=>p({...l,models:l.models.filter((re,Ie)=>Ie!==we)}),children:e.jsx(Or,{})})]},we)),e.jsxs("button",{type:"button",className:"btn",onClick:()=>p({...l,models:[...l.models,qi()]}),children:[e.jsx(ls,{})," ",c("addModel")]}),e.jsxs("div",{className:"modal-actions",children:[e.jsx("button",{type:"button",className:"btn",onClick:()=>p(null),children:c("cancel")}),e.jsx("button",{type:"button",className:"btn primary",disabled:!l.providerId.trim()||!l.models.some(B=>B.id.trim()),onClick:q,children:c("save")})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"form-section-title",children:[c("builtinProviders")," ",e.jsx("em",{className:"section-hint",children:c("hintKeyOnly")})]}),e.jsxs("div",{className:"provider-list",children:[s.length===0&&e.jsx("div",{className:"dd-loading",children:c("loading")}),s.map(B=>e.jsxs("div",{className:"provider-row",children:[e.jsxs("div",{className:"provider-info",children:[e.jsx("span",{className:"provider-name",children:B.name}),e.jsxs("span",{className:"provider-sub",children:[B.id,B.configured&&e.jsx("span",{className:"auth-badge",children:c("configuredBadge")}),B.source&&!B.configured&&e.jsx("span",{className:"auth-badge dim",children:B.source})]})]}),e.jsxs("div",{className:"provider-actions",children:[B.oauth&&e.jsxs(e.Fragment,{children:[e.jsx("button",{className:"btn sm",type:"button",onClick:()=>t({type:"login_provider",provider:B.id}),children:B.id==="openai"?c("providerChatGPTLogin"):c("providerLogin")}),B.configured&&B.source==="stored"&&e.jsx("button",{className:"btn sm",type:"button",onClick:()=>t({type:"logout_provider",provider:B.id}),children:c("providerLogout")})]}),B.configured&&!R[B.id]?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"auth-badge",children:c("keyReady")}),e.jsxs("button",{type:"button",className:"btn sm",title:c("replaceKeyTitle"),onClick:()=>E(we=>({...we,[B.id]:!0})),children:[e.jsx(ua,{})," ",c("replaceKey")]}),B.source==="stored"&&e.jsxs("button",{type:"button",className:"btn sm danger",title:c("clearKeyTitle"),onClick:()=>je(B.id),children:[e.jsx(Or,{})," ",c("clearKey")]})]}):e.jsxs(e.Fragment,{children:[e.jsx("input",{type:"password",className:"key-input",placeholder:c("pasteKey"),value:u[B.id]??"",onChange:we=>f(re=>({...re,[B.id]:we.target.value}))}),e.jsxs("button",{type:"button",className:"btn primary sm",disabled:!(u[B.id]??"").trim()||k===B.id,onClick:()=>L(B),children:[e.jsx(ad,{})," ",k===B.id?c("savingKey"):c("saveKey")]})]}),e.jsxs("button",{type:"button",className:"btn sm",disabled:W!==null,title:c("cloneProviderTitle"),onClick:()=>fe(B),children:[e.jsx(ws,{})," ",W===B.id?c("cloning"):c("cloneProvider")]})]})]},B.id))]}),e.jsx("div",{className:"form-section-title",children:c("customProviders")}),e.jsx("p",{className:"modal-desc",children:c("customDesc")}),n.length===0&&e.jsx("div",{className:"dd-loading",children:c("noCustomProviders")}),e.jsx("div",{className:"provider-list",children:n.map(B=>e.jsxs("div",{className:"provider-row",children:[e.jsxs("div",{className:"provider-info",children:[e.jsx("span",{className:"provider-name",children:B.providerId}),e.jsxs("span",{className:"provider-sub",children:[B.api??"—",B.baseUrl?` · ${B.baseUrl}`:"",B.models.length>0&&` · ${c("modelsCount",{n:B.models.length})}`]})]}),e.jsxs("div",{className:"provider-actions",children:[e.jsx("button",{type:"button",className:"iconbtn",title:c("edit"),onClick:()=>p(io(B)),children:e.jsx(ua,{})}),e.jsx("button",{type:"button",className:"iconbtn danger",title:c("delete"),onClick:()=>ne(B),children:e.jsx(Or,{})})]})]},B.providerId))}),e.jsx("div",{className:"modal-actions",children:e.jsxs("button",{type:"button",className:"btn primary",onClick:()=>p(Jm()),children:[e.jsx(ls,{})," ",c("addProvider")]})})]})]})})}function zl(t,n){return t===void 0||!Number.isFinite(t)?"—":n==="zh"?t>=1e4?`${Number((t/1e4).toFixed(t>=1e5?0:1))} 万 / 月`:`${t.toLocaleString("zh-CN")} / 月`:`${new Intl.NumberFormat("en",{notation:"compact",maximumFractionDigits:1}).format(t)} / mo`}function Ym(t,n,s=Date.now()){if(!t||!Number.isFinite(t))return"";const r=new Date(t),i=new Date(s),a=Math.max(0,Math.round((Date.UTC(i.getFullYear(),i.getMonth(),i.getDate())-Date.UTC(r.getFullYear(),r.getMonth(),r.getDate()))/864e5));if(a<=1)return n==="zh"?a?"昨天":"今天":a?"Yesterday":"Today";if(a<7)return n==="zh"?`${a} 天前`:`${a} days ago`;if(a<=30){const o=Math.floor(a/7);return n==="zh"?`${o} 周前`:`${o} ${o===1?"week":"weeks"} ago`}return r.toLocaleDateString(n==="zh"?"zh-CN":"en-US")}function Xm(t,n){const s=t.filter(r=>r.kind==="npm"&&r.name===n);return s.find(r=>r.update&&r.trusted&&!r.protected&&!r.pinned)??s[0]}const bi={extensions:"extTypeExtension",skills:"extTypeSkill",prompts:"extTypePrompt",themes:"extTypeTheme"};function Zm({catalog:t,packages:n,working:s,inspect:r,update:i,details:a}){const o=et(),{locale:c}=ns(),[l,p]=d.useState(),[u,f]=d.useState(),[k,j]=d.useState(""),[R,E]=d.useState(0);d.useEffect(()=>{if(f(void 0),j(""),!l)return;const N=new AbortController;return a(`npm:${l}`,N.signal).then(T=>{N.signal.aborted||f(T)}).catch(T=>{N.signal.aborted||j(T.message)}),()=>N.abort()},[l,R,a]);const A=N=>[N.author,N.version&&`v${N.version}`,zl(N.downloads,c),Ym(N.date,c)].filter(Boolean).join(" · ");return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"ext-catalog-list",children:t==null?void 0:t.items.map(N=>{const T=Xm(n,N.name),y=l===N.name,M=!!(T!=null&&T.update)&&T.trusted&&!T.protected&&!T.pinned,b=c==="zh"&&N.descriptionZh?N.descriptionZh:N.description;return e.jsxs("article",{className:`ext-catalog-row ${y?"expanded":""}`,children:[e.jsxs("div",{className:"ext-catalog-line",children:[e.jsxs("button",{className:"ext-catalog-expand","aria-expanded":y,"aria-label":`${o("extDetails")} ${N.name}`,onClick:()=>p(y?void 0:N.name),children:[e.jsxs("span",{className:"ext-catalog-identity",children:[e.jsx("strong",{title:N.name,children:N.name}),e.jsx("small",{title:A(N),children:A(N)})]}),e.jsx("span",{className:"ext-catalog-summary",title:b,children:b})]}),e.jsx("button",{className:`ext-catalog-action ${M?"update":T?"installed":"install"}`,disabled:s||!!T&&!M,onClick:()=>M?i(T):r(`npm:${N.name}`),children:o(T?M?"extUpdate":"extInstalled":"extInstall")})]}),y&&e.jsxs("div",{className:"ext-catalog-detail",children:[e.jsxs("div",{children:[e.jsx("p",{children:(u==null?void 0:u.description)||N.description}),u?e.jsxs("div",{className:"ext-resource-counts",children:[Object.entries(bi).filter(([F])=>{var U;return(U=u.resources[F])==null?void 0:U.length}).map(([F,U])=>e.jsxs("span",{children:[o(U)," ",u.resources[F].length]},F)),!Object.values(u.resources).some(F=>F.length)&&e.jsx("span",{children:o("extResourcesUnknown")})]}):k?e.jsxs("p",{role:"alert",children:[k," ",e.jsx("button",{onClick:()=>E(F=>F+1),children:o("extRetry")})]}):e.jsx("small",{role:"status",children:o("loading")})]}),e.jsxs("aside",{children:[e.jsxs("code",{children:["npm:",N.name]}),e.jsx("span",{children:(u==null?void 0:u.license)||(u?o("extLicenseUnknown"):"")}),((u==null?void 0:u.repository)||N.repository)&&e.jsxs("a",{href:(u==null?void 0:u.repository)||N.repository,target:"_blank",rel:"noreferrer",children:[o("extViewSource")," ↗"]}),e.jsxs("a",{href:N.url,target:"_blank",rel:"noreferrer",children:[o("extCatalogPage")," ↗"]})]})]})]},N.name)})}),t&&e.jsx("p",{className:"ext-catalog-origin",children:o(t.total===void 0?"extCatalogOriginPage":"extCatalogOrigin",{count:(t.total??t.items.length).toLocaleString(c==="zh"?"zh-CN":"en-US")})})]})}async function Pn(t,n,s={},r){const i=await fetch(Tn("/api/extensions"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...s,clientId:fn(),cwd:t,action:n}),signal:r}),a=await i.json();if(!i.ok)throw Error(a.error??i.statusText);return a}function Vl({cwd:t,reload:n,onUpdateCount:s,mode:r="manage",children:i}){var ot,dt;const a=et(),{locale:o}=ns(),c=d.useCallback((g,se)=>Pn(t,"details",{source:g},se),[t]),[l,p]=d.useState(),[u,f]=d.useState("installed"),[k,j]=d.useState(""),[R,E]=d.useState(""),[A,N]=d.useState("downloads"),[T,y]=d.useState(1),[M,b]=d.useState(),[F,U]=d.useState(),ce=d.useRef(),[ie,W]=d.useState(),[ve,Se]=d.useState(),[$,$e]=d.useState(),[L,q]=d.useState(""),[fe,je]=d.useState(!1),[ne,Pe]=d.useState(!1),[B,we]=d.useState(!1),[re,Ie]=d.useState(""),[_,le]=d.useState(!1),[O,ge]=d.useState(),[pe,Ae]=d.useState("user"),[ae,Te]=d.useState(!1),[Z,Fe]=d.useState(),z=d.useRef(),[G,J]=d.useState(),[Ee,V]=d.useState(!1),[Le,xe]=d.useState(!1),[be,nt]=d.useState(()=>localStorage.getItem("pi-extensions-autocheck")!=="false"),Ce=d.useRef(!0),ye=d.useRef(0);d.useEffect(()=>{if(!$||$.content===$.original)return;const g=se=>{se.preventDefault(),se.returnValue=""};return window.addEventListener("beforeunload",g),()=>window.removeEventListener("beforeunload",g)},[$]);const ze=d.useRef(null);d.useEffect(()=>{var at;if(!_&&!Z)return;const g=document.activeElement,se=ze.current,qe=()=>Array.from((se==null?void 0:se.querySelectorAll('button:not(:disabled), input:not(:disabled), select:not(:disabled), a[href], [tabindex="0"]'))??[]);(at=qe()[0])==null||at.focus();const _e=mt=>{if(mt.key!=="Tab")return;const Mt=qe(),Pt=Mt[0],$t=Mt.at(-1);mt.shiftKey&&(document.activeElement===Pt||!(se!=null&&se.contains(document.activeElement)))?(mt.preventDefault(),$t==null||$t.focus()):!mt.shiftKey&&(document.activeElement===$t||!(se!=null&&se.contains(document.activeElement)))&&(mt.preventDefault(),Pt==null||Pt.focus())};return document.addEventListener("keydown",_e),()=>{document.removeEventListener("keydown",_e),g instanceof HTMLElement&&g.isConnected&&g.focus()}},[_,!!Z]);const Ze=`pi-extensions-job:${t}`;async function Qe(g=!1){const se=++ye.current;g&&we(!0);try{const qe=await Pn(t,g?"check":"list");if(Ce.current&&se===ye.current){p(qe);const _e=ce.current&&qe.packages.find(at=>at.name===ce.current);_e&&(U(_e.id),W(_e.id),ce.current=void 0),qe.autoCheck!==void 0&&nt(qe.autoCheck),q("")}}catch(qe){Ce.current&&q(qe.message)}finally{Ce.current&&we(!1)}}d.useEffect(()=>{Ce.current=!0,Qe();const g=sessionStorage.getItem(Ze);return g&&Pn(t,"job",{id:g}).then(J).catch(()=>sessionStorage.removeItem(Ze)),()=>{Ce.current=!1}},[t]),d.useEffect(()=>{if(!be||!l||(G==null?void 0:G.phase)==="running")return;const g=Math.max(0,(l.checkedAt??0)+360*60*1e3-Date.now()),se=setTimeout(()=>void Qe(!0),g);return()=>clearTimeout(se)},[be,l==null?void 0:l.checkedAt,!!l,G==null?void 0:G.phase]),d.useEffect(()=>{if(u!=="browse")return;const g=new AbortController;Pe(!0),b(void 0);const se=setTimeout(()=>void Pn(t,"search",{query:k,type:R,sort:A,page:T},g.signal).then(qe=>{b(qe),q("")}).catch(qe=>{g.signal.aborted||q(qe.message)}).finally(()=>{g.signal.aborted||Pe(!1)}),300);return()=>{clearTimeout(se),g.abort()}},[t,u,k,R,A,T]),d.useEffect(()=>{if((G==null?void 0:G.phase)!=="running")return;let g=!1;const se=setInterval(()=>void Pn(t,"job",{id:G.id}).then(qe=>{var _e;g||(J(qe),qe.phase!=="running"&&(sessionStorage.removeItem(Ze),xe(!0),qe.phase==="done"&&((_e=z.current)==null?void 0:_e.action)==="install"&&(le(!1),ge(void 0),f("installed"),j("")),Qe()))}).catch(qe=>{g||q(qe.message)}),800);return()=>{g=!0,clearInterval(se)}},[G==null?void 0:G.id,G==null?void 0:G.phase,t]);async function ct(g,se=l==null?void 0:l.version){if(se){z.current=g,g.action==="install"&&(ce.current=O==null?void 0:O.name),je(!0),q("");try{const qe=await Pn(t,"start",{operation:g,version:se});if(!Ce.current)return;J(qe),sessionStorage.setItem(Ze,qe.id),Fe(void 0),g.action!=="install"&&(le(!1),ge(void 0))}catch(qe){q(qe.message)}finally{je(!1)}}}async function tt(g){je(!0),q("");try{const se=await Pn(t,"preview",{source:g});if(!Ce.current)return;ge(se),J(void 0),Ie(g),le(!0),Te(!1)}catch(se){q(se.message)}finally{je(!1)}}async function Oe(g){try{kt!=null&&kt.openExtensionPath?await kt.openExtensionPath({clientId:fn(),cwd:t,id:g.id}):await navigator.clipboard.writeText(g.path??g.source)}catch(se){q(se.message)}}const ee=fe||(G==null?void 0:G.phase)==="running",We=(l==null?void 0:l.packages.filter(g=>g.update&&!g.protected))??[];d.useEffect(()=>s==null?void 0:s(We.length),[We.length,s]);const w=(l==null?void 0:l.packages.filter(g=>(r!=="updates"||g.kind!=="file"&&!g.protected)&&`${g.name} ${g.source}`.toLowerCase().includes(k.toLowerCase())))??[];d.useEffect(()=>{if(!F)return;let g=!1;return Se(void 0),Pn(t,"notes",{id:F}).then(se=>{g||Se(se)}).catch(()=>{}),()=>{g=!0}},[F,t]);async function H(g){try{const se=await Pn(t,"file",{id:g.id});$e({...se,original:se.content,id:g.id,name:g.name})}catch(se){q(se.message)}}async function X(){if($){je(!0);try{await Pn(t,"save-file",{id:$.id,version:$.version,content:$.content}),$e(void 0),xe(!0)}catch(g){q(g.message)}finally{je(!1)}}}const ke=g=>g in bi?a(bi[g]):g,De=g=>Object.entries(g.resources).filter(([,se])=>se.length).map(([se,qe])=>e.jsxs("span",{children:[ke(se)," ",qe.length]},se));function He(g){var qe;const se=F===g.id;return e.jsxs("article",{className:`ext-row${g.enabled?"":" ext-disabled"}`,"data-extension-id":g.id,children:[e.jsxs("div",{className:"ext-row-main",children:[e.jsx("button",{className:"ext-expand","aria-label":`${a("extDetails")} ${g.name}`,"aria-expanded":se,onClick:()=>U(se?void 0:g.id),children:se?e.jsx(Qt,{}):e.jsx(_t,{})}),e.jsxs("div",{className:"ext-row-info",children:[e.jsxs("div",{className:"ext-name",children:[e.jsx("strong",{children:g.name}),ie===g.id&&e.jsx("span",{className:"ext-new",children:a("extNew")})]}),e.jsxs("div",{className:"ext-meta",children:[g.kind==="file"?e.jsx("code",{title:g.path,children:(qe=g.path)==null?void 0:qe.replace(/^\/Users\/[^/]+|^\/home\/[^/]+/,"~")}):e.jsxs("span",{children:[g.kind," · ",a(g.scope==="user"?"extPersonal":"extProject")]}),!g.trusted&&e.jsx("span",{className:"ext-pin",children:a("extUntrustedNotLoaded")})]})]}),g.kind!=="file"&&e.jsx("div",{className:"ext-resource-counts",children:De(g)}),r==="manage"&&g.kind==="file"&&e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:()=>void Oe(g),children:a(kt!=null&&kt.openExtensionPath?"extOpen":"extCopyPath")}),e.jsx("button",{disabled:ee,onClick:n,children:a("extReload")})]}),e.jsxs("div",{className:"ext-version",children:[r==="manage"&&g.update&&!g.protected&&g.trusted&&!g.pinned?e.jsxs("button",{className:"ext-version-update",disabled:ee||B,onClick:()=>void ct({action:"update",id:g.id}),children:[g.version,g.latest&&` → ${g.latest}`," · ",a("extUpdate")]}):e.jsxs(e.Fragment,{children:[g.version??(g.kind==="git"?"git":""),g.latest&&g.update&&e.jsxs("span",{children:[" → ",g.latest]})]}),g.pinned&&e.jsxs("span",{className:"ext-pin",children:[e.jsx(rd,{}),a("extPinned")]})]}),r==="updates"&&g.update&&!g.protected&&e.jsx("button",{className:"ext-update",disabled:ee||B,onClick:()=>void ct({action:"update",id:g.id}),children:a("extUpdate")}),r!=="updates"&&e.jsx("input",{className:"ext-switch",role:"switch",type:"checkbox","aria-label":`${a("extEnable")} ${g.name}`,checked:g.enabled,disabled:ee||B||!g.trusted||g.protected,onChange:_e=>void ct({action:"toggle",id:g.id,enabled:_e.target.checked})})]}),se&&e.jsxs("div",{className:"ext-details",children:[e.jsx("p",{children:g.description??g.source}),e.jsx("code",{className:"ext-source",children:g.source}),e.jsxs("div",{className:"ext-actions",children:[g.kind==="file"&&e.jsx("button",{disabled:ee||!g.trusted,onClick:()=>void H(g),children:a("extEditFile")}),g.kind==="npm"&&e.jsxs("a",{href:`https://pi.dev/packages/${g.name}`,target:"_blank",rel:"noreferrer",children:[e.jsx(Lo,{}),"pi.dev"]}),g.path&&e.jsxs("button",{onClick:()=>void Oe(g),children:[e.jsx(Ks,{}),a(kt!=null&&kt.openExtensionPath?"extOpen":"extCopyPath")]}),g.pinned&&e.jsx("button",{disabled:ee||B||!g.trusted||g.protected,onClick:()=>Fe({operation:{action:"unpin",id:g.id},name:g.name}),children:a("extUnpin")}),g.kind!=="file"&&e.jsxs(e.Fragment,{children:[e.jsx("button",{disabled:ee||B||!(l!=null&&l.trusted)||g.protected,onClick:()=>Fe({operation:{action:"move",id:g.id},name:g.name}),children:a(g.scope==="user"?"extMoveProject":"extMovePersonal")}),e.jsx("button",{className:"ext-danger",disabled:ee||B||!g.trusted||g.protected,onClick:()=>Fe({operation:{action:"remove",id:g.id},name:g.name}),children:a(g.kind==="local"?"extRemoveReference":"extUninstall")})]})]}),ve&&e.jsxs("div",{className:"ext-release-notes",children:[e.jsxs("strong",{children:[a("extReleaseNotes")," ",ve.title]}),ve.notes.length?e.jsx("ul",{children:ve.notes.map((_e,at)=>e.jsx("li",{children:_e},at))}):e.jsx("p",{children:a("extNoNotes")}),ve.url&&e.jsxs("a",{href:ve.url,target:"_blank",rel:"noreferrer",children:[a("extViewNotes")," ↗"]})]}),Object.entries(g.resources).some(([,_e])=>_e.length>0)&&e.jsxs("details",{children:[e.jsx("summary",{children:a("extResources")}),Object.entries(g.resources).filter(([,_e])=>_e.length).map(([_e,at])=>e.jsxs("div",{children:[e.jsx("strong",{children:ke(_e)}),e.jsx("pre",{children:at.join(`
256
+ `)})]},_e))]}),e.jsx("p",{className:"ext-muted",children:a("extResourceConfig")})]})]},g.id)}return e.jsxs("section",{className:`extensions-panel ${r==="manage"?"extensions-v3":""}`,children:[e.jsxs("header",{className:"ext-header",children:[e.jsx("h2",{children:r==="updates"?a("componentUpdates"):"Extensions"}),r==="updates"&&e.jsx("span",{className:"settings-count",children:l!=null&&l.checkedAt?a("v2LastChecked",{time:new Date(l.checkedAt).toLocaleDateString()===new Date().toLocaleDateString()?new Date(l.checkedAt).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):new Date(l.checkedAt).toLocaleDateString([],{month:"short",day:"numeric"})}):a("extNotChecked")}),e.jsx("div",{className:"settings-heading-actions",children:r==="updates"?e.jsx("button",{disabled:B||ee,onClick:()=>void Qe(!0),children:a(B?"extChecking":"settingsCheckNow")}):e.jsx("button",{disabled:ee,onClick:()=>{Ie(""),ge(void 0),J(void 0),q(""),le(!0)},children:a("extInstallSource")})})]}),r==="manage"&&e.jsx("div",{className:"ext-v3-tabs",role:"tablist","aria-label":"Extensions",children:["installed","browse"].map(g=>e.jsx("button",{role:"tab",tabIndex:u===g?0:-1,onKeyDown:se=>{var qe,_e;if(["ArrowLeft","ArrowRight","Home","End"].includes(se.key)){se.preventDefault();const at=se.key==="Home"?"installed":se.key==="End"||g==="installed"?"browse":"installed";f(at),j(""),y(1),(_e=(qe=se.currentTarget.parentElement)==null?void 0:qe.querySelectorAll('[role="tab"]')[at==="installed"?0:1])==null||_e.focus()}},"aria-selected":u===g,onClick:()=>{f(g),j(""),y(1)},children:g==="installed"?`${a("extInstalled")} · ${(l==null?void 0:l.packages.filter(se=>se.kind!=="file").length)??0}`:a("extBrowse")},g))}),i,L&&!_&&e.jsxs("div",{className:"ext-error",role:"alert",children:[L,e.jsx("button",{onClick:()=>void Qe(),children:a("extRefresh")})]}),G&&!_&&e.jsxs("div",{className:`ext-job ${G.phase==="error"?"ext-error":""}`,role:"status",children:[e.jsxs("div",{children:[e.jsx("strong",{children:a(G.phase==="running"?"extRunning":G.phase==="done"?"extDone":"extFailed")}),e.jsx("button",{onClick:()=>V(!Ee),children:a("extLog")})]}),G.error&&e.jsx("p",{children:G.error}),G.phase==="error"&&z.current&&e.jsx("button",{disabled:ee,onClick:()=>{var g;return((g=z.current)==null?void 0:g.action)==="install"?void tt(re):void ct(z.current)},children:a("extRetry")}),e.jsx("pre",{children:Ee?G.log:G.log.split(`
257
+ `).filter(Boolean).slice(-3).join(`
258
+ `)})]}),Le&&e.jsxs("div",{className:"ext-notice",children:[a("extReloadHint")," ",e.jsx("button",{disabled:ee,onClick:()=>{n(),xe(!1)},children:a("extReload")})]}),u==="installed"?e.jsxs(e.Fragment,{children:[r==="updates"&&We.length>0&&e.jsxs("div",{className:"ext-update-banner",children:[e.jsx(Pr,{}),e.jsxs("div",{children:[e.jsxs("strong",{children:[We.length," ",a("extUpdatesAvailable")]}),e.jsx("p",{children:We.map(g=>g.name).join(" · ")})]}),e.jsx("button",{className:"ext-primary",disabled:ee||B,onClick:()=>Fe({operation:{action:"update-all"},name:We.map(g=>g.name).join(", ")}),children:a("extUpdateAll")})]}),l?e.jsxs(e.Fragment,{children:[e.jsxs("h3",{className:"settings-group-title",children:[a("settingsPackages"),e.jsx("small",{children:a("v2PackagesHint")})]}),e.jsxs("div",{className:"ext-list",children:[w.filter(g=>g.kind!=="file").map(He),!w.some(g=>g.kind!=="file")&&e.jsxs("div",{className:"settings-empty",children:[e.jsx("p",{children:a("v2NoPackages")}),r==="manage"&&e.jsx("button",{onClick:()=>f("browse"),children:a("extBrowse")})]})]}),r==="manage"&&w.some(g=>g.kind==="file")&&e.jsxs(e.Fragment,{children:[e.jsxs("h3",{className:"ext-group-title",children:[a("extSingleFiles"),e.jsx("small",{children:a("v2FilesHint")})]}),e.jsx("div",{className:"ext-list",children:w.filter(g=>g.kind==="file").map(He)})]})]}):e.jsx("p",{className:"ext-empty",children:a("loading")}),r==="updates"&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"settings-group-title",children:a("v2UpdatePolicy")}),e.jsxs("div",{className:"settings-group",children:[e.jsxs("label",{className:"settings-list-row",children:[e.jsxs("span",{children:[a("settingsAutoCheck"),e.jsx("small",{className:"settings-description",children:a("v2AutoCheckHint")})]}),e.jsx("input",{className:"settings-switch",role:"switch",type:"checkbox","aria-label":a("settingsAutoCheck"),disabled:!l||ee,checked:be,onChange:g=>{const se=g.target.checked;nt(se),Pn(t,"preferences",{enabled:se}).catch(qe=>{nt(!se),q(qe.message)})}})]}),e.jsxs("div",{className:"settings-list-row",children:[e.jsxs("span",{children:[a("v2InstallPolicy"),e.jsx("small",{className:"settings-description",children:a("v2InstallHint")})]}),e.jsx("span",{className:"settings-readonly",children:a("v2ManualInstall")})]})]})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"ext-filters",children:[e.jsxs("label",{className:"ext-search",children:[e.jsx(as,{}),e.jsx("input",{type:"search",value:k,onChange:g=>{j(g.target.value),y(1)},placeholder:a("extSearch"),"aria-label":a("extSearch")})]}),e.jsx("div",{className:"ext-type-filters",children:["","extension","skill","prompt","theme"].map(g=>e.jsx("button",{"aria-pressed":R===g,onClick:()=>{E(g),y(1)},children:g?ke(`${g}s`):a("extAllTypes")},g))}),e.jsxs("select",{"aria-label":a("extSort"),value:A,onChange:g=>{N(g.target.value),y(1)},children:[e.jsx("option",{value:"downloads",children:a("extPopular")}),e.jsx("option",{value:"recent",children:a("extRecent")})]})]}),ne?e.jsx("p",{className:"ext-empty",role:"status",children:a("loading")}):e.jsx(Zm,{catalog:M,packages:(l==null?void 0:l.packages)??[],working:ee||B||!l,inspect:g=>void tt(g),update:g=>void ct({action:"update",id:g.id}),details:c}),M&&!M.items.length&&e.jsx("p",{className:"ext-empty",children:a("extNoResults")}),M&&e.jsxs("div",{className:"ext-pagination",children:[e.jsx("button",{disabled:T<=1,onClick:()=>y(T-1),children:a("extPrevious")}),e.jsxs("span",{children:[T," / ",M.pages]}),e.jsx("button",{disabled:T>=M.pages,onClick:()=>y(T+1),children:a("extNext")})]})]}),$&&e.jsx("div",{className:"ext-dialog-backdrop",children:e.jsxs("div",{className:"ext-dialog ext-editor","data-dirty":$.content!==$.original,role:"dialog","aria-modal":"true","aria-label":a("extEditFile"),onKeyDown:g=>{g.key==="Escape"&&g.stopPropagation()},children:[e.jsx("header",{children:e.jsx("h3",{children:$.name})}),e.jsx("textarea",{"aria-label":a("extEditFile"),value:$.content,onChange:g=>$e({...$,content:g.target.value}),spellCheck:!1}),e.jsx("p",{children:a("extEditHint")}),L&&e.jsx("p",{role:"alert",className:"ext-error",children:L}),e.jsxs("footer",{children:[e.jsx("button",{disabled:fe,onClick:()=>{($.content===$.original||window.confirm(a("extDiscard")))&&$e(void 0)},children:a("extCancel")}),e.jsx("button",{className:"ext-primary",disabled:fe,onClick:()=>void X(),children:a("extSaveFile")})]})]})}),(_||Z)&&e.jsx("div",{className:"ext-dialog-backdrop",onClick:()=>{fe||(le(!1),Fe(void 0))},children:e.jsxs("div",{ref:ze,className:"ext-dialog",role:"dialog","aria-modal":"true","aria-label":a(_?"extInstall":"extConfirm"),onClick:g=>g.stopPropagation(),onKeyDown:g=>{g.key==="Escape"&&(g.stopPropagation(),le(!1),Fe(void 0))},children:[e.jsxs("header",{children:[e.jsxs("h3",{children:[a(_?"extInstall":"extConfirm"),_&&O&&e.jsxs(e.Fragment,{children:[" ",e.jsx("code",{children:O.name})]})]}),e.jsx("button",{"aria-label":a("close"),onClick:()=>{le(!1),Fe(void 0)},children:e.jsx(Wt,{})})]}),_?e.jsx(e.Fragment,{children:O?e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"ext-install-meta",children:[O.author,O.version&&`v${O.version}`,((ot=M==null?void 0:M.items.find(g=>g.name===O.name))==null?void 0:ot.downloads)!==void 0?zl((dt=M.items.find(g=>g.name===O.name))==null?void 0:dt.downloads,o):void 0].filter(Boolean).join(" · ")}),e.jsxs("div",{className:"ext-preview-resources",children:[e.jsx("strong",{children:a("extWillLoad")}),Object.keys(O.resources).length?Object.entries(O.resources).map(([g,se])=>e.jsxs("p",{children:[e.jsx("span",{children:ke(g)}),e.jsx("code",{children:se.join(", ")||a("extNoneDeclared")})]},g)):e.jsx("p",{children:a("extResourcesUnknown")})]}),e.jsxs("div",{className:"ext-install-scope",children:[e.jsx("strong",{children:a("extScope")}),e.jsx("div",{className:"ext-scope-segments",children:["user","project"].map(g=>e.jsx("button",{"aria-pressed":pe===g,disabled:ee||g==="project"&&!(l!=null&&l.trusted),onClick:()=>Ae(g),children:a(g==="user"?"extPersonal":"extInstallProject")},g))}),e.jsx("code",{children:pe==="user"?"~/.pi/agent/settings.json":".pi/settings.json"}),!(l!=null&&l.trusted)&&e.jsx("small",{children:a("extProjectUntrusted")})]}),O.canPin&&e.jsxs("label",{className:"ext-auto",children:[e.jsx("input",{type:"checkbox",checked:ae,disabled:ee,onChange:g=>Te(g.target.checked)}),a("extPinVersion")," ",O.version]}),e.jsx("p",{className:"ext-security",children:a("extSecurity")}),e.jsxs("code",{className:"ext-command",children:["pi install ",ae&&O.canPin?`${O.source.replace(/^(npm:(?:@[^/]+\/)?[^@]+)(?:@.*)?$/,"$1")}@${O.version}`:O.source,pe==="project"?" --local":""]}),e.jsxs("footer",{children:[O.repository&&e.jsxs("a",{href:O.repository,target:"_blank",rel:"noreferrer",children:[a("extViewSource")," ↗"]}),e.jsx("button",{onClick:()=>le(!1),children:a("extCancel")}),e.jsx("button",{className:"ext-primary",disabled:ee||B,onClick:()=>void(async()=>{if((G==null?void 0:G.phase)==="error"||L){je(!0);try{const[g,se]=await Promise.all([Pn(t,"preview",{source:O.source}),Pn(t,"list")]);if(!Ce.current)return;ge(g),p(se),await ct({action:"install",ticket:g.ticket,scope:pe,pin:ae},se.version)}catch(g){q(g.message)}finally{je(!1)}}else await ct({action:"install",ticket:O.ticket,scope:pe,pin:ae})})(),children:a((G==null?void 0:G.phase)==="running"?"extInstalling":(G==null?void 0:G.phase)==="error"||L?"extRetry":"extInstall")})]})]}):e.jsxs("form",{onSubmit:g=>{g.preventDefault(),tt(re)},children:[e.jsxs("label",{children:[a("extSource"),e.jsx("input",{autoFocus:!0,value:re,onChange:g=>Ie(g.target.value),placeholder:"npm:@scope/name · git:github.com/owner/repo · ./local-path"})]}),e.jsx("button",{className:"ext-primary",disabled:fe||!re.trim(),type:"submit",children:a("extReview")})]})}):e.jsxs(e.Fragment,{children:[e.jsx("p",{children:Z==null?void 0:Z.name}),e.jsx("p",{children:a((Z==null?void 0:Z.operation.action)==="remove"?"extRemoveHint":(Z==null?void 0:Z.operation.action)==="move"?"extMoveHint":(Z==null?void 0:Z.operation.action)==="unpin"?"extUnpinHint":"extUpdateHint")}),e.jsxs("footer",{children:[e.jsx("button",{onClick:()=>Fe(void 0),children:a("extCancel")}),e.jsx("button",{className:"ext-primary",disabled:fe||B,onClick:()=>Z&&void ct(Z.operation),children:a("extConfirm")})]})]}),(G==null?void 0:G.phase)==="error"&&_&&e.jsx("pre",{className:"ext-install-error",role:"alert",children:[G.error,G.log.split(`
259
+ `).filter(Boolean).slice(-3).join(`
260
+ `)].filter(Boolean).join(`
261
+ `)}),L&&e.jsx("p",{className:"ext-error",role:"alert",children:L})]})})]})}function ef({cwd:t,updates:n,reload:s,onUpdateCount:r}){const i=et();return e.jsx(Vl,{cwd:t,mode:"updates",reload:s,onUpdateCount:r,children:e.jsx("div",{className:"settings-group",children:n==null?void 0:n.items.filter(a=>a.id==="builtin:agent").map(a=>e.jsxs("div",{className:"settings-list-row",children:[e.jsxs("span",{children:["Pi",e.jsx("small",{className:"settings-description",children:i("v2PiHint")})]}),e.jsx("span",{className:"component-version",children:a.current??"—"}),e.jsx("span",{className:"settings-readonly",children:i("settingsBundled")})]},a.id))})},t)}function tf({cwd:t,conversationId:n}){const s=et(),[r,i]=d.useState(),[a,o]=d.useState(""),[c,l]=d.useState(),[p,u]=d.useState(!1),[f,k]=d.useState(!1),[j,R]=d.useState(!1),[E,A]=d.useState(!1),[N,T]=d.useState(),[y,M]=d.useState(!1),[b,F]=d.useState(!1),[U,ce]=d.useState(!1),ie=d.useRef(!0),W=d.useRef(0),ve=d.useRef(!1),Se=!!c&&c.text!==c.initial;async function $(ae,Te={}){const Z=await fetch(Tn("/api/system-prompt"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({clientId:fn(),cwd:t,conversationId:n,action:ae,...Te})}),Fe=await Z.json();if(!Z.ok)throw Error(Fe.error??Z.statusText);return Fe}async function $e(){if(ve.current)return;const ae=++W.current;try{const Te=await $("get");ie.current&&W.current===ae&&i(Te)}catch(Te){ie.current&&W.current===ae&&o(Te.message)}}d.useEffect(()=>{ie.current=!0,$e();const ae=setInterval(()=>void $e(),2e3);return()=>{ie.current=!1,clearInterval(ae)}},[t,n]),d.useEffect(()=>{if(!Se)return;const ae=Te=>{Te.preventDefault(),Te.returnValue=""};return window.addEventListener("beforeunload",ae),()=>window.removeEventListener("beforeunload",ae)},[Se]);const L=()=>!Se||window.confirm(s("promptDiscard"));function q(ae,Te=!1){if(!L())return;const Z=Te&&!ae.exists?(r==null?void 0:r.defaultPreamble)??"":ae.content;l({file:ae,text:Z,initial:Z,confirmed:!Te}),F(!1),o("")}async function fe(ae,Te){if(!(ae==="restore"&&(!L()||!window.confirm(s("promptRestoreConfirm",{path:(Te==null?void 0:Te.path)??""}))))){ve.current=!0,M(!0),o(""),++W.current;try{const Z=await $(ae,Te?{id:Te.id,version:Te.version,...ae==="save"?{content:c==null?void 0:c.text}:{}}:{});ie.current&&(i(Z),ae!=="retry"&&l(void 0),T(Te==null?void 0:Te.id),F(!0))}catch(Z){ie.current&&o(Z.message)}finally{ve.current=!1,ie.current&&M(!1)}}}async function je(){if(L())try{const ae=await $("get");if(!ie.current)return;i(ae);const Te=ae.files.find(Z=>Z.id===(c==null?void 0:c.file.id));Te&&l({file:Te,text:Te.content,initial:Te.content,confirmed:!0}),o("")}catch(ae){o(ae.message)}}async function ne(){try{await navigator.clipboard.writeText((r==null?void 0:r.raw)??""),ce(!0)}catch{o(s("promptCopyFailed"))}}function Pe(ae){return!c||c.file.kind!==ae?null:e.jsxs("div",{className:"prompt-editor","data-dirty":Se,children:[ae==="system"&&e.jsx("div",{className:"prompt-warning",children:s("promptReplaceWarning")}),c.confirmed?e.jsxs(e.Fragment,{children:[ae!=="context"&&e.jsxs("label",{className:"prompt-scope",children:[s("promptScope"),e.jsx("select",{disabled:y,value:c.file.id,onChange:Te=>{const Z=r==null?void 0:r.files.find(Fe=>Fe.id===Te.target.value);if(Z&&L()){const Fe=ae==="system"&&!Z.exists?(r==null?void 0:r.defaultPreamble)??"":Z.content;l({file:Z,text:Fe,initial:Fe,confirmed:!0})}},children:r==null?void 0:r.files.filter(Te=>Te.kind===ae).map(Te=>e.jsxs("option",{value:Te.id,disabled:!Te.editable,children:[s(Te.scope==="user"?"promptUser":"promptProject"),Te.editable?"":` · ${s("promptUntrusted")}`]},Te.id))})]}),e.jsx("code",{className:"prompt-editor-path",children:c.file.path}),ae==="context"&&e.jsx("p",{className:"prompt-muted",children:s("promptContextHint")}),e.jsx("textarea",{autoFocus:!0,value:c.text,onChange:Te=>l({...c,text:Te.target.value}),spellCheck:!1,"aria-label":s("promptEditor"),disabled:y}),e.jsxs("div",{className:"prompt-editor-actions",children:[e.jsx("span",{children:s("promptNativeSave")}),e.jsx("button",{disabled:y,onClick:()=>void je(),children:s("promptReloadFile")}),e.jsx("button",{disabled:y,onClick:()=>{L()&&l(void 0)},children:s("cancel")}),e.jsx("button",{className:"prompt-primary",disabled:y||!c.file.editable||(r==null?void 0:r.opaque),onClick:()=>void fe("save",c.file),children:s(y?"promptSaving":"promptSave")})]})]}):e.jsxs("div",{className:"prompt-editor-actions",children:[e.jsx("button",{onClick:()=>l(void 0),children:s("cancel")}),e.jsx("button",{className:"prompt-primary",onClick:()=>l({...c,confirmed:!0}),children:s("promptContinueReplace")})]})]})}if(!r)return e.jsxs("section",{className:"system-prompt-panel",children:[e.jsx("p",{children:s("loading")}),a&&e.jsx("p",{role:"alert",children:a})]});const B=ae=>{var Te;return(Te=r.sections.find(Z=>Z.name===ae))==null?void 0:Te.text},we=r.files.find(ae=>ae.kind==="system"&&ae.active),re=r.files.filter(ae=>ae.kind==="append"&&ae.active),Ie=r.files.filter(ae=>ae.kind==="context"&&ae.exists),_=r.files.find(ae=>ae.kind==="context"&&!ae.exists&&ae.editable),le=new Map;for(const ae of r.rules){const Te=`${ae.kind}:${ae.name??""}:${ae.path??""}`;le.set(Te,[...le.get(Te)??[],ae])}const O=ae=>r.files.find(Te=>Te.kind===ae&&Te.scope===(r.trusted?"project":"user")),ge=ae=>r.rules.filter(Te=>Te.kind===ae).length,pe=r.files.some(ae=>ae.id===N&&ae.exists&&!ae.active),Ae=r.custom?" prompt-inactive":"";return e.jsxs("section",{className:"system-prompt-panel","aria-label":s("settingsSystemPrompt"),children:[e.jsxs("header",{className:"prompt-heading",children:[e.jsx("h2",{children:s("settingsSystemPrompt")}),e.jsxs("span",{className:"prompt-token",title:s("promptTokenHint"),children:[s("promptTokens",{n:r.tokens.toLocaleString()})," · ",s("v2PromptHint")]}),e.jsxs("div",{className:"prompt-heading-actions",children:[e.jsx("button",{className:"prompt-link",disabled:!!c,onClick:()=>u(!p),children:s(p?"promptViewSections":"promptViewRaw")}),e.jsxs("button",{onClick:()=>void ne(),children:[U?e.jsx(ts,{}):e.jsx(ws,{}),s(U?"promptCopied":"promptCopy")]})]})]}),(b||r.pending)&&!r.reloadError&&e.jsxs("p",{className:"prompt-save-status",role:"status",children:[e.jsx(ts,{}),s(r.pending?"promptSavedPending":pe?"promptSavedShadowed":"promptSavedNext")]}),a&&e.jsx("p",{className:"prompt-error",role:"alert",children:a}),r.reloadError&&e.jsxs("div",{className:"prompt-error",role:"alert",children:[s("promptReloadFailed")," ",r.reloadError,e.jsx("button",{disabled:y,onClick:()=>void fe("retry"),children:s("promptRetry")})]}),r.opaque?e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"prompt-warning",children:s(r.forced?"promptForced":"promptOpaque")}),e.jsx("pre",{className:"prompt-raw",children:r.raw})]}):p?e.jsx("pre",{className:"prompt-raw",children:r.raw}):e.jsxs("div",{className:"prompt-sections",children:[e.jsxs("div",{className:`prompt-section${(c==null?void 0:c.file.kind)==="system"?" prompt-editing":""}`,children:[e.jsxs("div",{className:"prompt-section-line",children:[e.jsxs("span",{className:"prompt-label",children:[s("promptDefault"),e.jsx("small",{className:"settings-description",children:s("v2IdentityHint")})]}),e.jsxs("div",{className:"prompt-summary",children:[e.jsx("button",{className:"prompt-text-button","aria-expanded":j,onClick:()=>R(!j),children:r.custom?s("promptReplaced"):s("promptBuiltinIdentity")}),r.custom&&we&&e.jsx("code",{className:"prompt-file-path",children:we.path})]}),e.jsx("div",{className:"prompt-row-actions",children:r.custom&&we?e.jsxs(e.Fragment,{children:[e.jsx("button",{disabled:y||!we.editable,onClick:()=>q(we),children:s("promptEdit")}),e.jsx("button",{disabled:y||!we.editable,onClick:()=>void fe("restore",we),children:s("promptRestore")})]}):e.jsx("button",{disabled:y,onClick:()=>q(O("system"),!0),children:s("promptReplace")})})]}),j&&e.jsx("pre",{className:"prompt-section-text",children:B("preamble")}),Pe("system")]}),e.jsx("div",{className:`prompt-section${Ae}`,children:e.jsxs("div",{className:"prompt-section-line",children:[e.jsxs("span",{className:"prompt-label",children:[s("promptTools")," · ",r.tools.length,e.jsx("small",{className:"settings-description",children:s("v2ToolsHint")})]}),e.jsx("div",{className:"prompt-tool-list",children:r.tools.map(ae=>e.jsx("code",{className:ae.custom?"prompt-custom-tool":"",title:ae.path,children:ae.name},ae.name))}),e.jsx("span",{className:"prompt-auto",children:s(r.custom?"promptInactive":"promptAutomatic")})]})}),e.jsxs("div",{className:`prompt-section${Ae}`,children:[e.jsxs("div",{className:"prompt-section-line",children:[e.jsxs("span",{className:"prompt-label",children:[s("promptRules")," · ",r.rules.length,e.jsx("small",{className:"settings-description",children:s("v2RulesHint")})]}),e.jsx("div",{className:"prompt-summary",children:s("promptRuleSummary",{builtin:ge("builtin"),tools:ge("tool"),extensions:ge("extension")+ge("unknown")})}),e.jsxs("button",{className:"prompt-link","aria-expanded":f,onClick:()=>k(!f),children:[f?e.jsx(Qt,{}):e.jsx(_t,{}),s(f?"promptCollapse":"promptExpand")]})]}),f&&e.jsx("div",{className:"prompt-rule-groups",children:[...le].map(([ae,Te])=>e.jsxs("div",{className:"prompt-rule-group",children:[e.jsxs("span",{title:Te[0].path,children:[Te[0].name??s(Te[0].kind==="builtin"?"promptBuiltin":Te[0].kind==="extension"?"promptExtension":"promptRuntime")," · ",Te.length]}),e.jsx("ul",{children:Te.map((Z,Fe)=>e.jsx("li",{children:Z.text},Fe))})]},ae))})]}),e.jsxs("div",{className:`prompt-section${Ae}`,children:[e.jsxs("div",{className:"prompt-section-line",children:[e.jsxs("span",{className:"prompt-label",children:[s("promptDocs"),e.jsx("small",{className:"settings-description",children:s("v2DocsHint")})]}),e.jsx("button",{className:"prompt-text-button prompt-summary","aria-expanded":E,onClick:()=>A(!E),children:s("promptDocsSummary")}),e.jsx("span",{className:"prompt-auto",children:s(r.custom?"promptInactive":"promptAutomatic")})]}),E&&B("docs")&&e.jsx("pre",{className:"prompt-section-text",children:B("docs")})]}),e.jsxs("div",{className:`prompt-section${(c==null?void 0:c.file.kind)==="append"?" prompt-editing":""}`,children:[e.jsxs("div",{className:"prompt-section-line",children:[e.jsxs("span",{className:"prompt-label",children:[s("promptAppend"),e.jsx("small",{className:"settings-description",children:s("v2AppendHint")})]}),e.jsx("div",{className:"prompt-summary",children:re.length?re.map(ae=>e.jsx("code",{className:"prompt-file-path",children:ae.path},ae.id)):e.jsx("span",{className:"prompt-muted",children:B("addendum")?s("promptRuntime"):s("promptNotSet")})}),e.jsx("div",{className:"prompt-row-actions",children:e.jsx("button",{disabled:y||!(re[0]??O("append")).editable,onClick:()=>q(re[0]??O("append")),children:s(re.length?"promptEdit":"promptAdd")})})]}),Pe("append")]}),e.jsxs("div",{className:`prompt-section${(c==null?void 0:c.file.kind)==="context"?" prompt-editing":""}`,children:[e.jsxs("div",{className:"prompt-section-line prompt-context-line",children:[e.jsxs("span",{className:"prompt-label",children:[s("promptContext"),e.jsx("small",{className:"settings-description",children:s("v2ContextHint")})]}),e.jsx("div",{className:"prompt-context-files",children:Ie.length?Ie.map(ae=>e.jsxs("div",{className:"prompt-context-file",children:[e.jsx("code",{title:ae.path,children:ae.path.split(/[\\/]/).pop()}),e.jsxs("span",{className:"prompt-token",title:ae.changedOnDisk?s("promptDiskChanged"):s("promptTokenHint"),children:[ae.tokens.toLocaleString()," tok",ae.changedOnDisk?" *":""]}),e.jsx("button",{className:"prompt-link",disabled:y||!ae.editable,title:ae.error,onClick:()=>q(ae),children:s("promptEdit")})]},ae.id)):e.jsx("span",{className:"prompt-muted",children:s("promptNoContext")})}),_&&e.jsx("button",{className:"prompt-link",disabled:y,onClick:()=>q(_),children:s("v2CreateAgents")})]}),Pe("context")]}),r.sections.filter(ae=>!["preamble","tools","rules","docs","addendum","project_context","skills","cwd"].includes(ae.name)).map(ae=>e.jsxs("div",{className:"prompt-section",children:[e.jsxs("div",{className:"prompt-section-line",children:[e.jsx("span",{className:"prompt-label",children:ae.name}),e.jsx("span",{className:"prompt-summary",children:s("promptRuntimeSection")}),e.jsx("span",{className:"prompt-auto",children:s("promptAutomatic")})]}),e.jsx("pre",{className:"prompt-section-text",children:ae.text})]},ae.name))]})]})}const ao=["codemode","deferred","direct","hidden"];function nf(t,n){const s=t.toolExposure&&typeof t.toolExposure=="object"?t.toolExposure:{},r=s[n],i=Object.entries(s).find(([o])=>new RegExp(`^${o.split("*").map(c=>c.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join(".*")}$`).test(n)),a=r??(i==null?void 0:i[1])??String(t.exposure??"codemode");return{value:a==="codemode-deferred"?"codemode":a,override:r!==void 0||i!==void 0}}function sf(t,n){const s=JSON.parse(t),r=s.mcpServers??s.servers??s.mcp;if(!r||typeof r!="object"||Array.isArray(r))throw new Error("Expected mcpServers, servers, or mcp");const i={...n.mcpServers??{}};for(const[a,o]of Object.entries(r)){if(Object.hasOwn(i,a))throw new Error(`Server already exists: ${a}`);if(!o||typeof o!="object"||Array.isArray(o))throw new Error(`Invalid server: ${a}`);const c={...o};if(c.type==="local"){if(c.type="stdio",Array.isArray(c.command)){const[p,...u]=c.command;c.command=p,c.args=u}c.environment&&(c.env=c.environment,delete c.environment)}c.type==="remote"&&(c.type="http");const l=JSON.stringify(c).replace(/\{env:([A-Za-z_][A-Za-z0-9_]*)\}/g,"${$1}");if(/\$\{input:/.test(l))throw new Error("Replace ${input:...} with ${ENV_NAME} before importing");i[a]=JSON.parse(l)}return{...n,mcpServers:i}}function rf({cwd:t,send:n,dialog:s}){const r=et(),[i,a]=d.useState("global"),[o,c]=d.useState(),[l,p]=d.useState(),[u,f]=d.useState("on"),[k,j]=d.useState(3e3),[R,E]=d.useState(""),[A,N]=d.useState(""),[T,y]=d.useState(""),[M,b]=d.useState(!1),[F,U]=d.useState(!1),[ce,ie]=d.useState([]),[W,ve]=d.useState(""),[Se,$]=d.useState([]),[$e,L]=d.useState(),[q,fe]=d.useState(),[je,ne]=d.useState(),[Pe,B]=d.useState(),[we,re]=d.useState(!1),Ie=!!o&&R!==JSON.stringify(o.document,null,2),_=d.useRef(!1),le=d.useRef(new Map),O=(J,Ee={},V=!1)=>{if(J!=="get"&&_.current)return;J!=="get"&&(_.current=!0);const Le=Gt();le.current.set(Le,{action:J,preserve:V}),J!=="get"&&U(!0),n({type:"native_mcp_request",requestId:Le,cwd:t,scope:i,action:J,...Ee})||(le.current.delete(Le),_.current=!1,U(!1),N(r("connectionDisconnected")))};d.useEffect(()=>{le.current.clear(),_.current=!1,c(void 0),p(void 0),E(""),N(""),y(""),ie([]),$([]),U(!1),fe(void 0),ne(void 0),B(void 0),L(void 0);const J=Le=>{const xe=Le.detail,be=le.current.get(xe.requestId);if(!(!be||xe.cwd!==t||xe.state&&xe.state.scope!==i)){if(le.current.delete(xe.requestId),be.action!=="get"&&(_.current=!1,U(!1)),xe.error){N(xe.error),be.action==="codemode"&&xe.codemode&&(p(xe.codemode),f(xe.codemode.mode),j(xe.codemode.inlineBudget));return}be.preserve||N(""),b(!!xe.pending),xe.state&&!be.preserve&&(c(xe.state),E(JSON.stringify(xe.state.document,null,2))),xe.codemode&&(!be.preserve||be.action==="codemode")&&(p(xe.codemode),f(xe.codemode.mode),j(xe.codemode.inlineBudget)),xe.codemode&&be.preserve&&be.action!=="codemode"&&p(nt=>nt?{...nt,effectiveMode:xe.codemode.effectiveMode,effectiveInlineBudget:xe.codemode.effectiveInlineBudget}:xe.codemode),xe.servers&&ie(xe.servers),xe.statusText!==void 0&&ve(xe.statusText),xe.toolInfo&&$(xe.toolInfo),xe.log!==void 0&&B(xe.log)}},Ee=Le=>y(Le.detail);window.addEventListener("pi-native-mcp-event",J),window.addEventListener("pi-mcp-notice",Ee),O("get");const V=setInterval(()=>{le.current.size||O("get",{},!0)},3e3);return()=>{clearInterval(V),window.removeEventListener("pi-native-mcp-event",J),window.removeEventListener("pi-mcp-notice",Ee)}},[t,i,n]),d.useEffect(()=>{if(!Ie&&!F&&!q&&je===void 0)return;const J=Ee=>{Ee.preventDefault(),Ee.returnValue=""};return window.addEventListener("beforeunload",J),()=>window.removeEventListener("beforeunload",J)},[Ie,F,q,je]);const ge=J=>{try{const Ee=JSON.parse(R);J(Ee),E(JSON.stringify(Ee,null,2)),N(""),O("save",{version:o==null?void 0:o.version,document:Ee})}catch(Ee){N(Ee.message)}},pe=()=>{try{O("save",{version:o==null?void 0:o.version,document:JSON.parse(R)})}catch(J){N(J.message)}};let Ae={};try{const J=JSON.parse(R);J&&typeof J=="object"&&!Array.isArray(J)&&(Ae=J)}catch{}const ae=Ae.mcpServers??{},Te=ae&&typeof ae=="object"&&!Array.isArray(ae)?ae:{},Z=J=>{var V;const Ee=(V=ce.find(Le=>Le.name===J))==null?void 0:V.state;return Ee==="needs-auth"||Ee==="failed"||Ee==="error"?0:Ee==="starting"||Ee==="connecting"||Ee==="disconnected"?1:2},Fe=[...new Set([...Object.keys(Te),...ce.map(J=>J.name)])].sort((J,Ee)=>Z(J)-Z(Ee)||J.localeCompare(Ee)),z=(J,Ee)=>ge(V=>{const Le={...V.mcpServers??{}};Ee===null?delete Le[J]:Le[J]=Ee,V.mcpServers=Le}),G=()=>{if(q)try{if(!/^[\w-]+$/.test(q.name)||!q.original&&Object.hasOwn(Te,q.name))throw new Error(r("mcpNameConflict"));const J=JSON.parse(q.json);if(!J||typeof J!="object"||Array.isArray(J))throw new Error(r("mcpInvalidServer"));z(q.name,J),fe(void 0)}catch(J){N(J.message)}};return e.jsxs("section",{className:"native-mcp-panel mcp-workbench","data-dirty":Ie||F||!!q||je!==void 0,children:[e.jsxs("header",{className:"mcp-page-head",children:[e.jsx("h3",{children:r("nativeMcp")}),e.jsxs("div",{className:"settings-heading-actions",children:[e.jsx("button",{disabled:!o||F,onClick:()=>re(!0),children:r("v2EditMcp")}),e.jsx("button",{disabled:F,onClick:()=>O("log",{},!0),children:r("extLog")})]})]}),s&&e.jsx(wi,{dialog:s,send:n}),T&&e.jsx("div",{className:"mcp-notice",children:e.jsx(ai,{text:T})}),e.jsxs("h4",{className:"settings-group-title",children:[r("mcpServersTitle"),e.jsx("small",{children:r("v2ServersHint")})]}),e.jsxs("div",{className:"mcp-scope-row",children:[e.jsxs("span",{title:o==null?void 0:o.path,children:[r("mcpScope"),e.jsx("small",{className:"settings-description",children:r("v2ScopeHint")})]}),e.jsx("div",{className:"settings-segment",role:"group","aria-label":r("mcpScope"),children:["global","project"].map(J=>e.jsx("button",{disabled:F,"aria-pressed":i===J,onClick:()=>{(!Ie&&!q&&je===void 0||window.confirm(r("mcpDiscard")))&&a(J)},children:r(J==="global"?"mcpGlobal":"mcpProject")},J))})]}),i==="project"&&!(o!=null&&o.trusted)&&e.jsxs("p",{className:"mcp-warning",children:[r("mcpUntrusted")," ",e.jsx("button",{disabled:F,onClick:()=>O("trust"),children:r("mcpTrust")})]}),M&&e.jsx("p",{className:"mcp-warning",role:"status",children:r("mcpPending")}),A&&e.jsxs("p",{className:"mcp-error",role:"alert",children:[A," ",e.jsx("button",{disabled:F,onClick:()=>{(!Ie||window.confirm(r("mcpDiscard")))&&O("get")},children:r("promptReloadFile")})]}),e.jsxs("div",{className:"mcp-section-head",children:[e.jsx("span",{children:Fe.length?"":r("v2NoServersHint")}),e.jsx("button",{disabled:!o||F,onClick:()=>ne(""),children:r("mcpImport")}),e.jsxs("button",{disabled:!o||F,onClick:()=>fe({name:"",json:`{
262
+ "url": "https://example.com/mcp",
263
+ "exposure": "codemode"
264
+ }`}),children:["+ ",r("mcpNew")]})]}),je!==void 0&&e.jsxs("div",{className:"mcp-editor",children:[e.jsx("h4",{children:r("mcpImport")}),e.jsx("p",{children:r("mcpImportHelp")}),e.jsx("textarea",{"aria-label":r("mcpImport"),rows:8,value:je,onChange:J=>ne(J.target.value)}),e.jsx("button",{onClick:()=>{try{const J=sf(je,JSON.parse(R));E(JSON.stringify(J,null,2)),O("save",{version:o==null?void 0:o.version,document:J}),ne(void 0),N("")}catch(J){N(J.message)}},children:r("settingsImportSave")}),e.jsx("button",{onClick:()=>ne(void 0),children:r("cancel")})]}),q&&e.jsxs("div",{className:"mcp-editor",children:[e.jsxs("label",{children:[r("mcpName"),e.jsx("input",{disabled:!!q.original,value:q.name,onChange:J=>fe({...q,name:J.target.value})})]}),e.jsx("p",{children:r("mcpEditorHelp")}),e.jsx("textarea",{"aria-label":r("mcpConfig"),rows:10,value:q.json,onChange:J=>fe({...q,json:J.target.value}),spellCheck:!1}),e.jsx("button",{disabled:F,onClick:G,children:r("save")}),e.jsx("button",{onClick:()=>fe(void 0),children:r("cancel")})]}),e.jsx("div",{className:"mcp-server-list",children:Fe.map(J=>{const Ee=Te[J],V=Ee&&typeof Ee=="object"?Ee:void 0,Le=ce.find(Ce=>Ce.name===J),xe=Se.filter(Ce=>Ce.name.startsWith(`mcp__${J.replace(/-/g,"_")}__`)),be=(Le==null?void 0:Le.state)??((V==null?void 0:V.enabled)===!1?"disabled":W?"unknown":"connecting"),nt=be==="needs-auth"?"mcpNeedsAuth":be==="connected"?"mcpConnected":be==="connecting"||be==="starting"?"mcpConnecting":be==="disabled"?"mcpDisabled":be==="disconnected"?"mcpDisconnected":be==="unknown"?"mcpNotLoaded":"mcpFailed";return e.jsxs("article",{className:`mcp-server ${be}`,children:[e.jsxs("div",{className:"mcp-server-head",children:[e.jsxs("button",{className:"mcp-server-toggle","aria-expanded":$e===J,onClick:()=>L($e===J?void 0:J),children:[e.jsx("span",{"aria-hidden":"true",children:$e===J?"⌄":"›"}),e.jsx("i",{className:"mcp-state-dot"}),e.jsx("strong",{children:J}),e.jsx("small",{children:V!=null&&V.url?"http":V!=null&&V.command?"stdio":r("mcpRuntime")})]}),e.jsxs("span",{className:"mcp-server-state",children:[r(nt),be==="connected"&&` · ${(Le==null?void 0:Le.toolCount)??xe.length}`]}),V&&e.jsx("select",{"aria-label":`${J} ${r("mcpExposure")}`,value:String(V.exposure??"codemode").replace("codemode-deferred","codemode"),disabled:F,onChange:Ce=>z(J,{...V,exposure:Ce.target.value}),children:ao.map(Ce=>e.jsx("option",{children:Ce},Ce))})]}),$e===J&&e.jsxs("div",{className:"mcp-server-body",children:[e.jsx("p",{className:"mcp-endpoint",children:V!=null&&V.description?String(V.description):""}),e.jsx("code",{className:"mcp-endpoint",children:V!=null&&V.url?(()=>{try{const Ce=new URL(String(V.url));return Ce.username="",Ce.password="",Ce.search="",Ce.href}catch{return"HTTP"}})():String((V==null?void 0:V.command)??"")}),be==="needs-auth"&&e.jsxs("div",{className:"mcp-warning",children:[e.jsx("p",{children:r("mcpAuthHelp")}),e.jsx("button",{disabled:F,onClick:()=>O("command",{command:"login",name:J},!0),children:r("mcp_login")}),e.jsx("p",{children:r("mcpRemoteLogin")})]}),Le&&be!=="connected"&&be!=="needs-auth"&&e.jsx("pre",{className:"mcp-diagnostic",children:Le.detail}),e.jsxs("div",{className:"mcp-tool-table",children:[e.jsxs("div",{className:"mcp-tool-heading",children:[e.jsx("span",{children:r("mcpTools")}),e.jsx("span",{children:r("mcpAnnotations")}),e.jsx("span",{children:r("mcpActualExposure")})]}),xe.map(Ce=>{var Ze;const ye=Ce.name.split("__").slice(2).join("__"),ze=nf(V??{},ye);return e.jsxs("div",{children:[e.jsx("code",{title:Ce.description,children:ye}),e.jsx("span",{children:Ce.destructive?r("mcpDestructive"):Ce.readOnly?r("mcpReadOnly"):"—"}),V?e.jsxs("span",{className:"mcp-exposure-control",children:[e.jsx("small",{children:Ce.exposure}),e.jsxs("select",{"aria-label":`${ye} ${r("mcpActualExposure")}`,title:`${r("mcpActualExposure")}: ${Ce.exposure}`,value:((Ze=V.toolExposure)==null?void 0:Ze[ye])??"inherit",disabled:F,onChange:Qe=>{const ct={...V.toolExposure??{}};Qe.target.value==="inherit"?delete ct[ye]:ct[ye]=Qe.target.value,z(J,{...V,toolExposure:ct})},children:[e.jsxs("option",{value:"inherit",children:[r("mcpInherit")," · ",ze.value]}),ao.map(Qe=>e.jsxs("option",{value:Qe,children:[Qe," *"]},Qe))]})]}):e.jsx("code",{children:Ce.exposure})]},Ce.name)}),!xe.length&&e.jsx("p",{children:r("mcpNoTools")})]}),e.jsxs("div",{className:"mcp-server-actions",children:[i==="project"&&!V&&e.jsx("button",{disabled:F,onClick:()=>z(J,{enabled:be==="disabled"}),children:r(be==="disabled"?"mcpEnableProject":"mcpDisableProject")}),["reconnect","login","logout"].map(Ce=>e.jsx("button",{disabled:F||!Le||be==="disabled",onClick:()=>O("command",{command:Ce,name:J},!0),children:r(`mcp_${Ce}`)},Ce)),V&&e.jsxs(e.Fragment,{children:[e.jsx("button",{disabled:F,onClick:()=>z(J,{...V,enabled:V.enabled===!1}),children:r(V.enabled===!1?"mcpEnableServer":"mcpDisableServer")}),e.jsx("button",{disabled:F,onClick:()=>fe({original:J,name:J,json:JSON.stringify(V,null,2)}),children:r("mcpEdit")}),e.jsx("button",{disabled:F,onClick:()=>{window.confirm(r("mcpRemoveConfirm",{name:J}))&&z(J,null)},children:r("delete")})]})]})]})]},J)})}),Ie&&!F&&e.jsxs("div",{className:"mcp-save-row",role:"status",children:[e.jsx("span",{children:r("mcpUnsaved")}),e.jsx("button",{onClick:pe,children:r("settingsRetrySave")}),e.jsx("button",{onClick:()=>{window.confirm(r("mcpDiscard"))&&O("get")},children:r("promptReloadFile")})]}),e.jsxs("h4",{className:"settings-group-title",children:["Codemode",e.jsx("small",{children:r("v2CodemodeHint")})]}),e.jsxs("div",{className:"settings-group",children:[e.jsxs("div",{className:"mcp-setting-row",children:[e.jsxs("span",{title:r("mcpModeHelp"),children:[r("settingsToolPresentation"),e.jsx("small",{className:"settings-description",children:r("v2ModeHint")})]}),e.jsx("div",{className:"settings-segment",role:"group","aria-label":"codemode.mode",children:["on","only"].map(J=>e.jsx("button",{"aria-pressed":u===J,disabled:!l||F,onClick:()=>O("codemode",{version:l==null?void 0:l.version,codemode:{mode:J,inlineBudget:k}},!0),children:J},J))})]}),e.jsxs("div",{className:"mcp-setting-row",children:[e.jsxs("span",{title:r("mcpBudgetHelp"),children:[r("settingsDeclarationBudget"),e.jsx("small",{className:"settings-description",children:r("v2BudgetHint")})]}),e.jsx("div",{className:"settings-segment",role:"group","aria-label":"codemode.inlineBudget",children:[...new Set([0,3e3,8e3,k])].sort((J,Ee)=>J-Ee).map(J=>e.jsx("button",{"aria-pressed":k===J,disabled:!l||F,onClick:()=>O("codemode",{version:l==null?void 0:l.version,codemode:{mode:u,inlineBudget:J}},!0),children:J},J))})]}),e.jsxs("label",{className:"mcp-setting-row",children:[e.jsxs("span",{title:r("mcpAutoHelp"),children:[r("settingsAutoCodemode"),e.jsx("small",{className:"settings-description",children:r("v2AutoHint")})]}),e.jsx("input",{className:"settings-switch",type:"checkbox",role:"switch","aria-label":"autoEnableCodemode",disabled:!o||F,checked:typeof Ae.autoEnableCodemode=="boolean"?Ae.autoEnableCodemode:(o==null?void 0:o.inheritedAutoEnableCodemode)??!0,onChange:J=>ge(Ee=>{Ee.autoEnableCodemode=J.target.checked})})]})]}),e.jsx("footer",{className:"settings-paths",children:o!=null&&o.paths?e.jsxs(e.Fragment,{children:[e.jsxs("code",{children:[r("mcpGlobal")," · ",o.paths.global]}),e.jsxs("code",{children:[r("mcpProject")," · ",o.paths.project]})]}):e.jsx("code",{children:o==null?void 0:o.path})}),we&&e.jsx("div",{className:"ext-dialog-backdrop",children:e.jsxs("div",{className:"ext-dialog mcp-json-dialog",role:"dialog","aria-modal":"true","aria-label":r("v2EditMcp"),onKeyDown:J=>{J.key==="Escape"&&J.stopPropagation()},children:[e.jsx("header",{children:e.jsx("h3",{children:r("v2EditMcp")})}),e.jsx("p",{children:r("mcpJsonHelp")}),e.jsx("code",{children:o==null?void 0:o.path}),e.jsx("textarea",{"aria-label":r("mcpConfig"),rows:15,value:R,disabled:F,onChange:J=>E(J.target.value),spellCheck:!1}),A&&e.jsx("p",{className:"mcp-error",role:"alert",children:A}),e.jsxs("footer",{children:[e.jsx("button",{disabled:F,onClick:()=>{(!Ie||window.confirm(r("mcpDiscard")))&&(E(JSON.stringify(o==null?void 0:o.document,null,2)),re(!1))},children:r("close")}),e.jsx("button",{disabled:F||!Ie,onClick:pe,children:r("save")})]})]})}),Pe!==void 0&&e.jsxs("details",{className:"mcp-advanced",open:!0,children:[e.jsx("summary",{children:"mcp.log"}),e.jsx("pre",{children:Pe}),e.jsx("button",{onClick:()=>B(void 0),children:r("close")})]})]})}function af({cwd:t,reload:n}){const s=et(),[r,i]=d.useState(),[a,o]=d.useState(""),[c,l]=d.useState("all"),[p,u]=d.useState(!1),[f,k]=d.useState(!1),[j,R]=d.useState(""),E=d.useRef(!0);async function A(b,F={}){u(!0),R("");try{const U=await fetch(Tn("/api/extensions"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({clientId:fn(),cwd:t,action:b,...F})}),ce=await U.json();if(!U.ok)throw Error(ce.error??U.statusText);E.current&&(i(ce),b==="skills-toggle"&&k(!0))}catch(U){E.current&&R(U.message)}finally{E.current&&u(!1)}}d.useEffect(()=>(E.current=!0,A("skills-list"),()=>{E.current=!1}),[t]);const N=(r==null?void 0:r.skills)??[],T=N.filter(b=>(c==="all"||b.source===c)&&`${b.name} ${b.description}`.toLowerCase().includes(a.toLowerCase())),y=N.filter(b=>b.enabled),M=Math.ceil(y.filter(b=>b.promptVisible).reduce((b,F)=>b+F.name.length+F.description.length,0)/4);return e.jsxs("section",{className:"settings-skills",children:[e.jsxs("header",{className:"settings-page-heading",children:[e.jsx("h2",{className:"settings-page-title",children:s("settingsSkills")}),e.jsx("span",{className:"settings-count",children:s("v2SkillCount",{n:N.length,enabled:y.length,tokens:M})}),e.jsx("button",{disabled:!r,onClick:()=>void(kt!=null&&kt.openExtensionPath?kt.openExtensionPath({clientId:fn(),cwd:t,id:"skills:user"}):navigator.clipboard.writeText((r==null?void 0:r.paths.join(`
265
+ `))??"")).catch(b=>R(b.message)),children:s(kt!=null&&kt.openExtensionPath?"v2OpenSkills":"v2CopyPaths")})]}),e.jsx("p",{className:"settings-intro",children:s("v2SkillsIntro")}),j&&e.jsxs("p",{className:"settings-error",role:"alert",children:[j," ",e.jsx("button",{disabled:p,onClick:()=>void A("skills-list"),children:s("extRefresh")})]}),f&&e.jsxs("p",{className:"ext-notice",role:"status",children:[s("v2SkillsChanged")," ",e.jsx("button",{disabled:p,onClick:()=>{n(),k(!1)},children:s("extReload")})]}),e.jsxs("div",{className:"skills-filters",children:[e.jsx("input",{type:"search",value:a,onChange:b=>o(b.target.value),placeholder:s("v2SkillSearch"),"aria-label":s("v2SkillSearch")}),e.jsx("div",{className:"settings-segment",role:"group","aria-label":s("extScope"),children:["all","user","project","package"].map(b=>e.jsx("button",{"aria-pressed":c===b,onClick:()=>l(b),children:s(b==="all"?"v2SkillAll":b==="user"?"extPersonal":b==="project"?"extProject":"v2SkillPackage")},b))})]}),e.jsxs("div",{className:"settings-group",children:[T.map(b=>e.jsxs("label",{className:`settings-skill-row${b.enabled?"":" disabled"}`,children:[e.jsxs("span",{className:"settings-skill-info",children:[e.jsx("code",{children:b.name}),e.jsx("small",{title:b.description,children:b.description})]}),e.jsx("span",{className:"settings-readonly",title:b.path,children:s(b.source==="package"?"v2SkillPackage":b.scope==="project"?"extProject":"extPersonal")}),e.jsx("input",{type:"checkbox",role:"switch",className:"settings-switch","aria-label":`${s("extEnable")} ${b.name}`,checked:b.enabled,disabled:p||!b.canToggle,onChange:F=>void A("skills-toggle",{id:b.id,enabled:F.target.checked,version:r==null?void 0:r.version})})]},b.id)),!T.length&&e.jsx("p",{className:"settings-empty",children:s(r?"extNoResults":"loading")})]}),e.jsxs("footer",{className:"settings-paths",children:[s("v2SkillsPaths"),r==null?void 0:r.paths.map(b=>e.jsx("code",{children:b},b))]})]})}function of({chat:t,send:n,onClose:s,initialTab:r="prompt"}){var R,E,A,N,T,y,M;const i=et(),[a,o]=d.useState(0),c=()=>!document.querySelector('.ext-editor[data-dirty="true"], .prompt-editor[data-dirty="true"], .mcp-workbench[data-dirty="true"]')||window.confirm(i("extDiscard")),l=()=>{c()&&s()};d.useEffect(()=>{const b=F=>{F.key==="Escape"&&!F.defaultPrevented&&l()};return window.addEventListener("keydown",b),()=>window.removeEventListener("keydown",b)},[s]);const[p,u]=d.useState(r),f=t.settings;d.useEffect(()=>{p==="updates"&&t.ready&&n({type:"check_component_updates",requestId:Gt()})},[p,t.ready,(R=t.state)==null?void 0:R.cwd,n]);const k=[{id:"prompt",label:i("settingsSystemPrompt"),icon:e.jsx(qs,{})},{id:"skills",label:i("settingsSkills"),icon:e.jsx(Ei,{})},{id:"extensions",label:i("settingsExtensions"),icon:e.jsx(sd,{})},{id:"native-mcp",label:i("nativeMcp"),icon:e.jsx(fd,{})},{id:"updates",label:i("componentUpdates"),icon:e.jsx(ys,{})}],j=((E=t.componentUpdates)==null?void 0:E.cwd)===((A=t.state)==null?void 0:A.cwd)?t.componentUpdates:null;return e.jsx("div",{className:"modal-backdrop",onClick:l,children:e.jsxs("div",{className:"modal settings-modal",role:"dialog","aria-modal":"true","aria-label":i("settingsTitle"),onClick:b=>b.stopPropagation(),children:[e.jsx("div",{className:"modal-head",children:e.jsx("button",{className:"icon-btn","aria-label":i("close"),onClick:l,children:e.jsx(Wt,{})})}),e.jsxs("div",{className:"settings-layout",children:[e.jsxs("nav",{className:"settings-rail","aria-label":i("settingsTitle"),children:[e.jsx("h2",{children:i("settingsTitle")}),k.map(b=>e.jsxs("button",{title:b.label,className:`settings-tab${p===b.id?" active":""}`,onClick:()=>{c()&&u(b.id)},children:[e.jsx("span",{className:"settings-tab-icon",children:b.icon}),e.jsxs("span",{className:"settings-tab-label",children:[b.label,b.id==="updates"&&a>0&&e.jsx("span",{className:"ext-rail-badge",children:a})]})]},b.id))]}),e.jsx("div",{className:"modal-body",children:e.jsx("div",{className:"set-section",children:f?e.jsxs(e.Fragment,{children:[e.jsxs("label",{className:"tree-edit-preference",children:[e.jsx("input",{type:"checkbox",checked:f.editResendNewSession??!1,onChange:b=>n({type:"set_settings",editResendNewSession:b.target.checked})}),i("treeEditNewSession")]}),((N=t.state)==null?void 0:N.planSettings)&&e.jsxs("div",{className:"plan-settings",children:[e.jsxs("label",{children:[e.jsx("input",{type:"checkbox",checked:t.state.planSettings.enabled,disabled:!t.ready,onChange:b=>n({type:"set_plan_enabled",conversationId:t.state.conversationId,enabled:b.target.checked})}),i("planEnabled")]}),e.jsx("p",{children:i("planEnabledHint")}),t.state.planSettings.available?t.state.planSettings.pending?e.jsx("p",{children:i("planPending")}):null:e.jsx("p",{children:i(t.state.planSettings.reason==="conflict"?"planConflict":"planMissing")})]}),p==="prompt"&&t.state&&e.jsx(tf,{cwd:t.state.cwd,conversationId:t.state.conversationId},`${t.state.cwd}:${t.state.conversationId}`),p==="skills"&&t.state&&e.jsx(af,{cwd:t.state.cwd,reload:()=>n({type:"extensions_reload"})},t.state.cwd),p==="extensions"&&((T=t.state)==null?void 0:T.cwd)&&e.jsx(Vl,{cwd:t.state.cwd,onUpdateCount:o,reload:()=>n({type:"extensions_reload"})},t.state.cwd),p==="native-mcp"&&((y=t.state)==null?void 0:y.cwd)&&e.jsx(rf,{cwd:t.state.cwd,send:n,dialog:t.dialog},`${t.state.cwd}:${t.state.conversationId}`),p==="updates"&&e.jsx(ef,{cwd:((M=t.state)==null?void 0:M.cwd)??"",updates:j,onUpdateCount:o,reload:()=>n({type:"extensions_reload"})})]}):e.jsx("p",{children:i("loading")})})})]})]})})}function lf(t,n){const s=Math.max(0,Date.now()-t),r=Math.floor(s/6e4);if(r<1)return n("bgTaskJustNow");if(r<60)return n("bgTaskMinutes",{n:r});const i=Math.floor(r/60);return i<24?n("bgTaskHours",{n:i}):n("bgTaskDays",{n:Math.floor(i/24)})}function cf({servers:t,send:n,onClose:s}){const r=et(),[i,a]=d.useState(new Set),o=c=>a(l=>{const p=new Set(l);return p.has(c)?p.delete(c):p.add(c),p});return d.useEffect(()=>{n({type:"list_bg_servers"})},[]),e.jsx("div",{className:"modal-backdrop",onClick:s,children:e.jsxs("div",{className:"bg-task-modal",onClick:c=>c.stopPropagation(),children:[e.jsxs("div",{className:"bg-task-head",children:[e.jsxs("span",{className:"bg-task-title",children:[e.jsx(Es,{})," ",r("bgTasks"),t.length>0&&e.jsx("em",{className:"bg-task-count",children:t.length})]}),e.jsx("button",{type:"button",className:"btn",title:r("close"),onClick:s,children:e.jsx(Wt,{})})]}),t.length===0?e.jsxs("div",{className:"bg-task-empty",children:[e.jsx(Es,{}),e.jsx("span",{children:r("bgTasksEmpty")}),e.jsx("small",{children:r("bgTasksDesc")})]}):e.jsx("ul",{className:"bg-task-list",children:t.map(c=>{const l=!!c.taskId,p=c.taskId??String(c.port);return e.jsxs("li",{className:"bg-task-item",children:[e.jsx("span",{className:"bg-task-icon",title:l?c.plugin:r("bgTaskPort")}),e.jsxs("div",{className:"bg-task-info",children:[e.jsxs("div",{className:"bg-task-line1",children:[l?e.jsxs("span",{className:"bg-task-port",title:c.taskId,children:["🧩 ",c.plugin]}):e.jsxs("span",{className:"bg-task-port",children:[":",c.port]}),c.name&&e.jsx("span",{className:"bg-task-name",children:c.name})]}),e.jsxs("div",{className:"bg-task-line2",children:[!l&&e.jsxs("span",{children:[r("bgTaskPid")," ",c.pid]}),e.jsxs("span",{children:[r("bgTaskSince")," ",lf(c.since,r)]}),l&&c.status&&e.jsx("span",{className:"bg-task-status",children:c.status})]}),c.command&&e.jsxs("button",{type:"button",className:`bg-task-cmd ${i.has(p)?"open":""}`,title:`${r("bgTaskCommand")}: ${c.command}`,onClick:()=>o(p),children:[e.jsx(Ni,{}),e.jsx("code",{children:c.command})]})]}),e.jsxs("button",{type:"button",className:"btn bg-task-stop",title:r("bgTaskStop"),onClick:()=>n(l?{type:"kill_background_server",taskId:c.taskId}:{type:"kill_background_server",port:c.port}),children:[e.jsx(ms,{}),e.jsx("span",{children:r("bgTaskStop")})]})]},p)})}),e.jsxs("div",{className:"bg-task-foot",children:[e.jsxs("button",{type:"button",className:"btn",title:r("bgTaskRefresh"),onClick:()=>n({type:"list_bg_servers"}),children:[e.jsx(ys,{}),e.jsx("span",{children:r("bgTaskRefresh")})]}),e.jsxs("button",{type:"button",className:"btn bg-task-stopall",disabled:t.length===0,title:r("bgTaskStopAll"),onClick:()=>n({type:"kill_background_servers"}),children:[e.jsx(ms,{}),e.jsx("span",{children:r("bgTaskStopAll")})]})]})]})})}function cr(t,n){return t.toLowerCase().includes(n)}function df({send:t,sessions:n,projects:s,cwd:r,fileSearch:i,onClose:a,onSwitchSession:o,onSwitchProject:c,onPreviewFile:l}){const p=et(),u=d.useRef(null),[f,k]=d.useState(""),j=d.useDeferredValue(f),[R,E]=d.useState(0),A=d.useRef(1),N=d.useRef(0),T=d.useRef(null);d.useEffect(()=>{t({type:"list_sessions"}),t({type:"list_projects"}),requestAnimationFrame(()=>{var L;return(L=u.current)==null?void 0:L.focus()})},[]);const[y,M]=d.useState(!1);d.useEffect(()=>{T.current&&clearTimeout(T.current);const L=j.trim();if(L)return T.current=setTimeout(()=>{const q=++A.current;N.current=q,M(!0),t({type:"search_files",reqId:q,query:L})},300),()=>{T.current&&clearTimeout(T.current)}},[j]);const b=j.trim().toLowerCase(),F=d.useMemo(()=>b?n.filter(L=>cr(L.firstMessage??"",b)||cr(L.name??"",b)||cr(L.path.split(/[\\/]/).pop()??"",b)).slice(0,20):[],[n,b]),U=d.useMemo(()=>b?s.filter(L=>cr(L.path,b)).slice(0,10):[],[s,b]),ce=d.useMemo(()=>!b||!i||i.reqId!==N.current||!i.ok?[]:i.results,[i,b]);d.useEffect(()=>{i&&i.reqId===N.current&&N.current!==0&&M(!1)},[i]);const ie=!!i&&i.ok&&i.truncated,W=d.useMemo(()=>[...F.map(L=>({kind:"session",path:L.path})),...U.map(L=>({kind:"project",path:L.path})),...ce.filter(L=>L.type==="file").map(L=>({kind:"file",path:L.path,name:L.name}))],[F,U,ce]);d.useEffect(()=>{E(0)},[j]);const ve=d.useCallback(L=>{L&&(L.kind==="session"?o(L.path):L.kind==="project"?c(L.path):l(L.path,L.name),a())},[o,c,l,a]);d.useEffect(()=>{const L=q=>{q.key==="Escape"?(q.preventDefault(),q.stopPropagation(),a()):q.key==="ArrowDown"?(q.preventDefault(),E(fe=>Math.min(fe+1,W.length-1))):q.key==="ArrowUp"?(q.preventDefault(),E(fe=>Math.max(fe-1,0))):q.key==="Enter"&&(q.preventDefault(),ve(W[R]))};return window.addEventListener("keydown",L,!0),()=>window.removeEventListener("keydown",L,!0)},[W,R,ve,a]);const Se=F.length+U.length+ce.length,$=(L,q,fe)=>e.jsxs("div",{className:"gs-section-head",children:[fe,e.jsx("span",{children:L}),e.jsx("em",{children:q})]});let $e=-1;return e.jsx("div",{className:"modal-backdrop gs-backdrop",onClick:a,children:e.jsxs("div",{className:"gs-modal",onClick:L=>L.stopPropagation(),children:[e.jsxs("div",{className:"gs-input-row",children:[e.jsx(as,{}),e.jsx("input",{ref:u,type:"text",value:f,placeholder:p("gsPlaceholder"),onChange:L=>k(L.target.value)}),e.jsx("button",{type:"button",className:"gs-close",title:p("close"),onClick:a,children:e.jsx(Wt,{})})]}),e.jsxs("div",{className:"gs-results",children:[!b&&e.jsx("div",{className:"gs-empty",children:p("gsHint")}),b&&Se===0&&!ie&&e.jsx("div",{className:"gs-empty",children:p(y?"gsSearching":"gsNoResults")}),F.length>0&&e.jsxs("div",{className:"gs-section",children:[$(p("gsSessions"),F.length,e.jsx(Eo,{})),F.map(L=>{$e++;const q=$e;return e.jsxs("button",{type:"button",className:q===R?"gs-item active":"gs-item",onMouseEnter:()=>E(q),onClick:()=>ve({kind:"session",path:L.path}),children:[e.jsxs("span",{className:"gs-item-title",children:[L.name||L.path.split(/[\\/]/).pop(),e.jsx("em",{className:"gs-item-meta",children:L.messageCount})]}),e.jsx("span",{className:"gs-item-sub",children:fs(L.firstMessage)})]},L.path)})]}),U.length>0&&e.jsxs("div",{className:"gs-section",children:[$(p("gsProjects"),U.length,e.jsx(Ks,{})),U.map(L=>{$e++;const q=$e,fe=r&&L.path===r;return e.jsxs("button",{type:"button",className:q===R?"gs-item active":"gs-item",onMouseEnter:()=>E(q),onClick:()=>ve({kind:"project",path:L.path}),children:[e.jsxs("span",{className:"gs-item-title",children:[L.path.split(/[\\/]/).pop(),fe&&e.jsx("em",{className:"gs-item-meta",children:p("gsCurrentProject")})]}),e.jsx("span",{className:"gs-item-sub",children:L.path})]},L.path)})]}),(ce.length>0||b&&ie)&&e.jsxs("div",{className:"gs-section",children:[$(p("gsFiles"),ce.length,e.jsx(dd,{})),ce.map(L=>{$e++;const q=$e;return e.jsxs("button",{type:"button",className:q===R?"gs-item active":"gs-item",disabled:L.type==="dir",title:L.type==="dir"?void 0:p("gsOpenPreview"),onMouseEnter:()=>E(q),onClick:()=>{L.type==="file"&&ve({kind:"file",path:L.path,name:L.name})},children:[e.jsx("span",{className:"gs-item-title",children:L.name}),e.jsx("span",{className:"gs-item-sub",children:L.path})]},`${L.type}:${L.path}`)}),ie&&e.jsx("div",{className:"gs-truncated",children:p("gsTruncated")})]})]}),e.jsxs("div",{className:"gs-foot",children:[e.jsxs("span",{children:["↑↓ ",p("gsNavigate")]}),e.jsxs("span",{children:["Enter ",p("gsOpen")]}),e.jsxs("span",{children:["Esc ",p("gsCloseHint")]})]})]})})}const uf=d.memo(function({file:n,disabled:s}){const r=et(),[i,a]=d.useState({offset:0}),[o,c]=d.useState(0),[l,p]=d.useState(null),[u,f]=d.useState(!1),[k,j]=d.useState("");d.useEffect(()=>{if(s){f(!1);return}const E=new AbortController,A=Gt();f(!0),j(""),p(null);const N=new URLSearchParams({clientId:fn(),cwd:n.cwd,path:n.path,requestId:A,offset:String(i.offset)});return i.table!==void 0&&N.set("table",i.table),(async()=>{try{const T=await fetch(Tn("/api/sqlite?"+N),{signal:E.signal}),y=await T.json();if(E.signal.aborted)return;if(!T.ok||y.error)throw new Error(y.error||r("dbLoadFailed"));if(y.requestId!==A||y.cwd!==n.cwd||y.path!==n.path||!y.data)throw new Error(r("dbLoadFailed"));p(y.data)}catch(T){E.signal.aborted||j(T.message)}finally{E.signal.aborted||f(!1)}})(),()=>E.abort()},[n.cwd,n.path,i.table,i.offset,o,s,r]);const R=u||s;return e.jsxs("section",{className:"sqlite-preview","aria-label":r("dbViewer"),children:[e.jsxs("div",{className:"sqlite-toolbar",children:[e.jsxs("span",{className:"sqlite-label",children:["SQLite · ",r("dbReadOnly")]}),e.jsx("button",{type:"button",className:"btn",disabled:R,onClick:()=>{a({offset:0}),c(E=>E+1)},children:r("dbRefresh")})]}),s&&e.jsx("div",{className:"fp-notice",children:r("dbUnavailable")}),u&&e.jsx("div",{className:"fp-empty",role:"status",children:r("loading")}),k&&e.jsxs("div",{className:"fp-notice",role:"alert",children:[r("dbLoadFailed")," ",k]}),l&&e.jsxs(e.Fragment,{children:[l.tables.length?e.jsxs("label",{className:"sqlite-table-picker",children:[e.jsx("span",{children:r("dbTable")}),e.jsx("select",{"aria-label":r("dbTable"),disabled:R,value:l.table??"",onChange:E=>a({table:E.target.value,offset:0}),children:l.tables.map(E=>e.jsxs("option",{value:E.name,children:[E.name,E.type==="view"?" · "+r("dbView"):""]},E.name))})]}):e.jsx("div",{className:"fp-empty",children:r("dbNoTables")}),(l.columnsTruncated||l.tablesTruncated)&&e.jsx("div",{className:"fp-notice",children:r("dbStructureLimited")}),l.queryError&&e.jsxs("div",{className:"fp-notice",role:"alert",children:[r("dbLoadFailed")," ",l.queryError]}),l.table!==null&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"sqlite-grid-wrap",tabIndex:0,"aria-label":r("dbRows"),children:[e.jsxs("table",{className:"sqlite-grid",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{scope:"col",children:"#"}),l.columns.map(E=>e.jsxs("th",{scope:"col",children:[e.jsxs("span",{children:[E.name,E.primaryKey?" 🔑":""]}),e.jsx("small",{children:E.type||"—"})]},E.name))]})}),e.jsx("tbody",{children:l.rows.map((E,A)=>e.jsxs("tr",{children:[e.jsx("th",{scope:"row",children:l.offset+A+1}),E.map((N,T)=>e.jsx("td",{className:N.kind==="null"||N.kind==="blob"?"sqlite-special":"",children:e.jsxs("span",{title:N.kind==="text"?N.value:void 0,children:[N.kind==="null"?"NULL":N.kind==="blob"?`BLOB · ${N.value} B`:N.value,N.truncated?"…":""]})},T))]},l.offset+A))})]}),!l.rows.length&&e.jsx("div",{className:"fp-empty",children:r("dbNoRows")})]}),e.jsxs("div",{className:"sqlite-pagination",children:[e.jsx("button",{className:"btn",disabled:R||l.offset===0,onClick:()=>a({table:l.table,offset:Math.max(0,l.offset-l.pageSize)}),children:r("dbPrevious")}),e.jsx("span",{children:r("dbRowRange",{start:l.rows.length?l.offset+1:0,end:l.offset+l.rows.length})}),e.jsx("button",{className:"btn",disabled:R||!l.hasMore,onClick:()=>a({table:l.table,offset:l.offset+l.pageSize}),children:r("dbNext")})]}),e.jsx("div",{className:"sqlite-hint",children:r("dbCellLimit")}),e.jsxs("details",{className:"sqlite-schema",children:[e.jsx("summary",{children:r("dbSchema")}),e.jsx("pre",{children:l.schema})]})]})]})]})}),pf="pi-harness:code-theme",oo="pi-harness:code-theme";function lo(){try{const t=localStorage.getItem(pf);return t==="dark"||t==="system"?t:"light"}catch{return"light"}}function hf(t){const n=new Map;let s=0,r=!1,i=0;const a=()=>{i&&s>0&&!n.has(s)&&n.set(s,"deleted"),i=0};for(const o of t.split(`
266
+ `)){const c=/^@@ -\d+(?:,\d+)? \+(\d+)(?:,\d+)? @@/.exec(o);if(c){a(),s=Number(c[1]),r=!0;continue}if(o.startsWith("diff --git ")||o.startsWith("--- ")||o.startsWith("+++ ")){a(),r=!1;continue}if(r){if(o.startsWith("-")){i++;continue}if(o.startsWith("+")){n.set(s,i>0?"changed":"added"),i>0&&i--,s++;continue}a(),o.startsWith(" ")&&s++}}return a(),n}const Zr=5e3;let ei=-5e3;const mf=d.memo(function({result:n,guard:s,disabled:r,connected:i,contextReader:a,contextSaver:o,onContextChange:c,file:l,content:p,send:u,onAddLines:f,onAttach:k,onClose:j,fileChanged:R,scmData:E,scmDirty:A}){const N=et(),[T,y]=d.useState(null),M=d.useRef(null),[b,F]=d.useState(!1),[U,ce]=d.useState(null),[ie,W]=d.useState(!1),[ve,Se]=d.useState(!1),[$,$e]=d.useState(!0),[L,q]=d.useState(""),fe=d.useRef(""),je=te=>{fe.current=te,q(te)},ne=d.useRef(Gt()),[Pe,B]=d.useState(!0),[we,re]=d.useState(null),[Ie,_]=d.useState(!1),[le,O]=d.useState(""),[ge,pe]=d.useState(!1),[Ae,ae]=d.useState(!1),[Te,Z]=d.useState(!1),[Fe,z]=d.useState(null),[G,J]=d.useState(()=>new Date),[Ee,V]=d.useState(null),[Le,xe]=d.useState(!1),[be,nt]=d.useState(lo);d.useEffect(()=>{const te=()=>nt(lo());return window.addEventListener(oo,te),()=>window.removeEventListener(oo,te)},[]);const[Ce,ye]=d.useState(100),ze=d.useRef(0),Ze=d.useRef(!1),Qe=d.useRef(null),ct=d.useRef(""),tt=d.useRef(""),Oe=d.useRef(0),ee=d.useRef(0),We=d.useRef(null),[w,H]=d.useState("saved"),[X,ke]=d.useState(""),[De,He]=d.useState(!1),[ot,dt]=d.useState(null),g=T!==null&&L!==T.text,se=()=>{r||(ct.current=Gt(),F(!0),ke(""),u({type:"read_file",path:l.path,cwd:l.cwd,requestId:ct.current})||(F(!1),ke(N("fileOffline"))))};d.useEffect(()=>{se()},[l.path,l.cwd]),d.useEffect(()=>{(p==null?void 0:p.requestId)!==ct.current||(p==null?void 0:p.cwd)!==l.cwd||(p==null?void 0:p.path)!==l.path||(ct.current="",M.current=p,y(p),ce(null),je(p.text),$e(p.kind==="text"&&!p.binary&&!p.truncated),B(!0),F(!1),He(!1),H("saved"),J(new Date),Z(!1),z(null),re(null))},[p,l.path,l.cwd]),d.useEffect(()=>{!p||p.requestId!==tt.current||p.path!==l.path||p.cwd!==l.cwd||(tt.current="",T&&p.version!==T.version&&(g?(z(p.text),Z(!0)):(M.current=p,y(p),je(p.text))))},[p,T,g,l.path,l.cwd]),d.useEffect(()=>{!R||!T||We.current||r||(tt.current=Gt(),u({type:"read_file",path:l.path,cwd:l.cwd,requestId:tt.current}))},[R,l.path,l.cwd,T,g,r,u]),d.useEffect(()=>{r||!i||(Oe.current=--ei,u({type:"scm_status",reqId:Oe.current}))},[l.path,l.cwd,A,R,r,i,u]),d.useEffect(()=>{var te;if((E==null?void 0:E.cwd)===l.cwd)if(E.kind==="status"&&E.reqId===Oe.current){const Ve=!!E.ok&&!!((te=E.files)!=null&&te.some(Ue=>Ue.path.replaceAll("\\","/")===l.path));_(Ve),Ve||(O(""),pe(!1))}else E.kind==="filediff"&&E.reqId===ee.current&&(ae(!1),pe(!!E.ok&&!!E.untracked&&E.untrackedKind==="text"),O(E.ok?[E.stagedText,E.worktreeText,E.untrackedText].filter(Boolean).join(`
267
+ `):E.error??""))},[E,l.cwd,l.path]),d.useEffect(()=>{!Ie||r||!i||!T||T.kind!=="text"||(ee.current=--ei,u({type:"scm_filediff",reqId:ee.current,path:l.path}))},[Ie,A,R,T==null?void 0:T.version,r,i,l.path,u]);const qe=d.useMemo(()=>ge?new Map(((T==null?void 0:T.text.split(`
268
+ `))??[]).map((te,Ve)=>[Ve+1,"added"])):hf(le),[le,ge,T==null?void 0:T.text]);d.useEffect(()=>{var Ve,Ue;if(!n||n.cwd!==l.cwd||n.path!==l.path||(n.operation==="read"&&n.requestId===ct.current&&(ct.current="",F(!1),ke(n.error??N("fileSaveFailed"))),n.operation!=="write"||n.requestId!==((Ve=We.current)==null?void 0:Ve.id)))return;const te=We.current;if(te)if(We.current=null,n.ok){const yt=M.current;if(yt){const Bt={...yt,text:te.text,version:n.version,size:new TextEncoder().encode(te.text).length,lines:te.text?te.text.split(`
269
+ `).length-(te.text.endsWith(`
270
+ `)?1:0):0};M.current=Bt,y(Bt)}H("saved"),J(new Date),ce(null),He(!1),ke(""),(Ue=te.next)==null||Ue.call(te)}else H("failed"),He(!!n.conflict),ke(n.error??N("fileSaveFailed"))},[n,l.cwd,l.path,N]),d.useEffect(()=>{if(!b)return;const te=()=>{ct.current="",F(!1),ke(N("fileOffline"))};if(!i){te();return}const Ve=setTimeout(te,15e3);return()=>clearTimeout(Ve)},[b,i,N]),d.useEffect(()=>{if(w!=="saving")return;const te=()=>{We.current=null,H("failed"),ke(N("fileOffline"))};if(!i){te();return}const Ve=setTimeout(te,15e3);return()=>clearTimeout(Ve)},[w,i,N]),d.useLayoutEffect(()=>(s.current=te=>{We.current||(g?dt({action:te}):te())},()=>{s.current=null}),[g,s]),d.useEffect(()=>{if(!g)return;const te=Ve=>{Ve.preventDefault(),Ve.returnValue=""};return window.addEventListener("beforeunload",te),()=>window.removeEventListener("beforeunload",te)},[g]);const _e=!!T&&T.kind==="text"&&!T.binary&&!T.truncated&&!b&&!r;d.useLayoutEffect(()=>{if(a)return a.current=te=>{var Ve,Ue;return _e&&T&&te===ne.current?{path:l.path,mode:"inline",editorSnapshot:{cwd:l.cwd,text:fe.current,dirty:fe.current!==((Ve=M.current)==null?void 0:Ve.text),version:(Ue=M.current)==null?void 0:Ue.version}}:null},()=>{a.current=null}},[a,_e,T,l.path,l.cwd]),d.useLayoutEffect(()=>{c==null||c(_e?{...l,id:ne.current,dirty:g}:null)},[_e,g,l,c]),d.useLayoutEffect(()=>()=>c==null?void 0:c(null),[c]),d.useLayoutEffect(()=>{if(o)return o.current=(te,Ve)=>{const Ue=M.current;return!_e||!Ue||te!==ne.current?!1:fe.current===Ue.text?(Ve(),!0):b||r||We.current?!1:(zt(!1,Ve),!0)},()=>{o.current=null}},[o,_e,b,r,L,l.path,l.cwd]),d.useEffect(()=>{const te=()=>{Ze.current=!1,W(!1)};return window.addEventListener("mouseup",te),()=>{window.removeEventListener("mouseup",te),Qe.current&&clearTimeout(Qe.current)}},[]);const at=d.useMemo(()=>{if(!T)return[];const te=T.text.split(`
271
+ `);return te.length>0&&te[te.length-1]===""&&te.pop(),te.slice(0,Zr)},[T]),mt=d.useMemo(()=>{const te=Os(l.name);return!te||at.length===0?null:ml(at.join(`
272
+ `),te)},[at,l.name]),Pt=((T==null?void 0:T.lines)??0)>Zr,$t=(te,Ve)=>{if(Ve){const Ue=ze.current>0?ze.current:te;ce({start:Math.min(Ue,te),end:Math.max(Ue,te)})}else ze.current=te,ce({start:te,end:te})},Ft=()=>{U&&(f(l.path,l.name,U.start,U.end),Se(!0),Qe.current&&clearTimeout(Qe.current),Qe.current=setTimeout(()=>Se(!1),1400))},Jt=()=>{!Ie||r||(re("git"),ae(!0),ee.current=--ei,u({type:"scm_filediff",reqId:ee.current,path:l.path})||ae(!1))},nn=(te,Ve)=>{if(!(te instanceof Element)||!te.closest(".fp-markdown"))return;const Ue=window.getSelection();if(!Ue||Ue.isCollapsed||!Ue.anchorNode||!Ve.contains(Ue.anchorNode))return;const yt=pt=>{const Dt=pt instanceof Element?pt:pt==null?void 0:pt.parentElement,Yt=Dt==null?void 0:Dt.closest("[data-source-start]"),Vt=Number(Yt==null?void 0:Yt.dataset.sourceStart),un=Number(Yt==null?void 0:Yt.dataset.sourceEnd);return Vt>0&&un>=Vt?{start:Vt,end:un}:null},Bt=yt(Ue.anchorNode),Zt=yt(Ue.focusNode),qt=Bt&&Zt?{start:Math.min(Bt.start,Zt.start),end:Math.max(Bt.end,Zt.end)}:gf(L,Ue.toString());if(!qt)return;ce(qt);const St=Ue.getRangeAt(0).getBoundingClientRect(),dn=Ve.getBoundingClientRect();V({x:Math.max(12,Math.min(dn.width-260,St.left-dn.left)),y:Math.max(54,Math.min(dn.height-42,St.bottom-dn.top+8))})},lt=T!==null&&T.kind==="text"&&!T.binary&&!T.truncated,Et=()=>{lt&&($e(te=>!te),ce(null))},zt=(te=!1,Ve)=>{if(!T||!lt||b||r||We.current)return;const Ue=Gt();We.current={id:Ue,text:L,next:Ve},H("saving"),ke(""),u({type:"write_file",path:l.path,cwd:l.cwd,text:L,requestId:Ue,expectedVersion:T.version,force:te})||(We.current=null,H("failed"),ke(N("fileOffline")))},Ht=()=>{var te;return(te=s.current)==null?void 0:te.call(s,j)},an=te=>{ye(Math.min(200,Math.max(50,te)))};U&&U.end-U.start+1;const At=(T==null?void 0:T.binary)??!1,Xt=(T==null?void 0:T.truncated)??!1,K=(T==null?void 0:T.kind)??"text",Y=ff(l.name),Je=Y&&Pe&&K==="text"&&!At,Be=te=>Tn(`/api/file?clientId=${encodeURIComponent(fn())}&path=${encodeURIComponent(te)}`);return e.jsx("div",{className:"fp-embedded","data-code-theme":be,onKeyDown:te=>{!te.nativeEvent.isComposing&&(te.metaKey||te.ctrlKey)&&te.key.toLowerCase()==="s"&&(te.preventDefault(),te.stopPropagation(),zt())},children:e.jsxs("div",{className:`fp ${we?"show-diff":""}`,style:{"--fp-zoom":Ce/100},onMouseUp:te=>nn(te.target,te.currentTarget),children:[e.jsxs("div",{className:"fp-title-row",children:[e.jsx("button",{className:"fp-back","aria-label":N("backToFiles"),title:N("backToFiles"),onClick:Ht,disabled:w==="saving",children:"←"}),e.jsxs("span",{className:"fp-file-path",title:`${l.cwd}/${l.path}`,children:[e.jsx("span",{className:"fp-project-name",children:l.cwd.split(/[\\/]/).filter(Boolean).at(-1)}),e.jsx("span",{className:"fp-path-separator",children:" / "}),l.path.split(/[\\/]/).join(" / ")]}),e.jsxs("span",{className:"fp-header-status",role:"status",children:[w==="saving"?N("fileSaving"):w==="failed"?N("fileSaveFailed"):g?N("fileUnsaved"):T?N("fileSaved"):"",T&&!g&&w==="saved"&&e.jsxs("time",{children:[" · ",G.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"})]})]}),e.jsxs("div",{className:"fp-header-actions",children:[Y&&K==="text"&&e.jsxs("div",{className:"fp-view-switch",role:"group","aria-label":N("fileViewMode"),children:[e.jsx("button",{type:"button","aria-pressed":!we&&Pe,onClick:()=>{re(null),B(!0),$e(!0),ce(null)},children:N("fileViewPreview")}),e.jsx("button",{type:"button","aria-pressed":!we&&!Pe,disabled:!lt,onClick:()=>{re(null),B(!1),$e(!0),ce(null)},children:N("fileViewSource")})]}),!Y&&lt&&e.jsxs("div",{className:"fp-view-switch",role:"group","aria-label":N("fileEditMode"),children:[e.jsx("button",{type:"button","aria-pressed":!$,onClick:()=>{re(null),$e(!1)},children:N("fileReadOnly")}),e.jsx("button",{type:"button","aria-pressed":$,onClick:()=>{re(null),$e(!0)},children:N("fileEditShort")})]}),Ie&&e.jsx("button",{type:"button",className:"fp-header-action","aria-pressed":we==="git",onClick:()=>we==="git"?re(null):Jt(),children:N("fileChangesCount",{n:1})}),e.jsxs("button",{type:"button",className:"fp-header-action fp-reference",disabled:r,onClick:()=>k(l.path,l.name,"reference"),children:["@",N("fileReference")]}),e.jsxs("details",{className:"fp-more",children:[e.jsx("summary",{"aria-label":N("fileMoreActions"),children:e.jsx(Ms,{})}),e.jsxs("div",{className:"fp-more-actions",onClick:te=>{var Ve;te.target instanceof Element&&te.target.closest("button")&&((Ve=te.currentTarget.closest("details"))==null||Ve.removeAttribute("open"))},children:[e.jsx("button",{className:"btn",disabled:r,onClick:()=>{Ll(l.path,l.name).then(te=>{!te.ok&&!te.cancelled&&ke(te.error)})},children:N("downloadFile")}),Y&&lt&&e.jsx("button",{className:"btn",onClick:()=>{re(null),B(!0),$e(!0)},children:N("editFile")}),!Y&&lt&&e.jsx("button",{className:"btn",onClick:Et,children:N($?"exitEditFile":"editFile")}),K==="text"&&e.jsx("button",{className:"btn",onClick:()=>xe(te=>!te),children:N(Le?"disableWrap":"enableWrap")}),K==="text"&&e.jsxs("button",{className:"btn",onClick:()=>an(Ce-10),disabled:Ce<=50,children:[e.jsx(Yc,{})," ",N("zoomOut")]}),K==="text"&&e.jsxs("button",{className:"btn",onClick:()=>an(Ce+10),disabled:Ce>=200,children:[e.jsx(Xc,{})," ",N("zoomIn")]}),K!=="video"&&K!=="none"&&K!=="sqlite"&&e.jsx("button",{className:"btn",onClick:()=>k(l.path,l.name,"inline"),children:N("attachInlineTip")})]})]}),lt&&g&&w!=="saving"&&e.jsxs("button",{className:"btn primary fp-header-save",disabled:r,onClick:()=>zt(),children:[e.jsx(ed,{})," ",N("saveFile")]})]})]}),Te&&g&&e.jsxs("div",{className:"fp-external-banner",role:"alert",children:[N("fileExternalChanged"),e.jsx("button",{type:"button",onClick:()=>{var te;return(te=s.current)==null?void 0:te.call(s,se)},children:N("fileReload")}),e.jsx("button",{type:"button",disabled:Fe===null,onClick:()=>re("external"),children:N("fileCompare")})]}),Xt&&K==="text"&&!At&&e.jsx("div",{className:"fp-notice",children:N("previewTruncated")}),X&&e.jsxs("div",{className:"fp-notice",role:"alert",children:[X,e.jsx("button",{className:"btn",disabled:r||w==="saving",onClick:()=>{var te;return(te=s.current)==null?void 0:te.call(s,se)},children:N("fileReload")}),De&&e.jsx("button",{className:"btn",disabled:r,onClick:()=>{window.confirm(N("fileOverwriteConfirm"))&&zt(!0)},children:N("fileOverwrite")})]}),ot&&e.jsxs("div",{className:"fp-leave",role:"alertdialog","aria-label":N("fileUnsaved"),children:[e.jsx("p",{children:N("fileLeavePrompt")}),e.jsx("button",{className:"btn primary",disabled:r,onClick:()=>{const te=ot.action;dt(null),zt(!1,te)},children:N("fileSaveContinue")}),e.jsx("button",{className:"btn",onClick:()=>{const te=ot.action;dt(null),te()},children:N("fileDiscard")}),e.jsx("button",{className:"btn",onClick:()=>dt(null),children:N("cancel")})]}),b&&!T&&e.jsx("div",{className:"fp-empty",children:N("loading")}),!b&&K==="none"&&!At&&e.jsx("div",{className:"fp-empty",children:N("previewNotSupported")}),!b&&K==="sqlite"&&e.jsx(uf,{file:l,disabled:r||!i}),!b&&K==="image"&&e.jsx("div",{className:"fp-media-wrap",children:e.jsx("img",{className:"fp-media",src:Be(l.path),alt:l.name})}),!b&&K==="video"&&e.jsx("div",{className:"fp-media-wrap",children:e.jsx("video",{className:"fp-media",src:Be(l.path),controls:!0,preload:"metadata"})}),!b&&Je&&T&&($&&lt?e.jsx(Tl,{file:l,value:L,readOnly:r||w==="saving",onChange:je}):e.jsx("div",{className:"fp-markdown msg-text",children:e.jsx("div",{className:"fp-markdown-zoom",children:e.jsx(On,{text:lt?L:T.text,imageSrc:te=>hl(te,l),sourceLines:!0})})})),!b&&At&&K!=="image"&&K!=="sqlite"&&K!=="video"&&T&&e.jsxs("div",{className:"fp-hex-wrap",children:[e.jsxs("div",{className:"fp-notice",children:[N("binaryFile"),T.truncated&&N("binaryHexTruncated")]}),e.jsx("pre",{className:"fp-hex",children:T.text})]}),!b&&$&&!Je&&K==="text"&&!At&&T&&e.jsx(Rl,{name:l.name,value:L,readOnly:r||w==="saving",onChange:je,onSelectLines:(te,Ve)=>{ce({start:te,end:Ve}),V(null)},wrap:Le,markers:g?void 0:qe}),!b&&!Je&&!$&&K==="text"&&!At&&T&&at.length===0&&e.jsx("div",{className:"fp-empty",children:N("emptyFile")}),!b&&!Je&&!$&&K==="text"&&!At&&at.length>0&&e.jsxs("div",{className:`fp-code ${ie?"dragging":""} ${Le?"":"no-wrap"}`,onMouseDown:te=>{te.button===0&&te.preventDefault()},children:[at.map((te,Ve)=>{const Ue=Ve+1,yt=U!==null&&Ue>=U.start&&Ue<=U.end;return e.jsxs("div",{"data-line":Ue,className:`fp-line ${yt?"sel":""}`,onMouseDown:Bt=>{Bt.button===0&&($t(Ue,Bt.shiftKey),Ze.current=!0,W(!0))},onMouseEnter:()=>{Ze.current&&$t(Ue,!0)},children:[e.jsx("span",{className:`fp-num ${g?"":qe.get(Ue)??""}`,children:Ue}),mt?e.jsx("span",{className:"fp-code-text hljs",dangerouslySetInnerHTML:{__html:mt[Ve]||"​"}}):e.jsx("span",{className:"fp-code-text",children:te})]},Ue)}),Pt&&e.jsx("div",{className:"fp-lines-note",children:N("previewLinesTruncated",{n:Zr})})]}),U&&!we&&e.jsxs("button",{type:"button",className:`fp-quote-selection${Ee?" at-selection":""}`,style:Ee?{left:Ee.x,top:Ee.y}:void 0,disabled:r,onMouseDown:te=>te.preventDefault(),onClick:Ft,children:[ve?e.jsx(ts,{}):null,ve?N("addedToChat"):N("quoteSelection",{name:l.name,start:U.start,end:U.end})]}),we==="git"&&e.jsx("div",{className:"fp-diff-view",role:"region","aria-label":N("fileViewChanges"),children:Ae?e.jsx("span",{className:"fp-empty",children:N("loading")}):le?e.jsx("pre",{children:le.split(`
273
+ `).map((te,Ve)=>e.jsxs("span",{className:te.startsWith("+")&&!te.startsWith("+++")?"add":te.startsWith("-")&&!te.startsWith("---")?"del":te.startsWith("@@")?"hunk":"",children:[te,`
274
+ `]},Ve))}):e.jsx("div",{className:"fp-empty",children:N("fileNoChanges")})}),we==="external"&&e.jsxs("div",{className:"fp-diff-view fp-external-comparison",role:"region","aria-label":N("fileCompare"),children:[e.jsxs("section",{children:[e.jsx("h3",{children:N("fileLocalDraft")}),e.jsx("pre",{children:L})]}),e.jsxs("section",{children:[e.jsx("h3",{children:N("fileDiskVersion")}),e.jsx("pre",{children:Fe})]})]})]})})});function ff(t){const n=t.toLowerCase();return n.endsWith(".md")||n.endsWith(".markdown")}function gf(t,n){const s=n.trim();if(!s)return null;let r=t.indexOf(s),i=r+s.length;if(r<0){let a="";const o=[];for(let p=0;p<t.length;p++){const u=t[p];if(/\s/.test(u)){if(a.endsWith(" "))continue;a+=" "}else a+=u;o.push(p)}const c=s.replace(/\s+/g," "),l=a.indexOf(c);if(l<0)return null;r=o[l],i=o[l+c.length-1]+1}return{start:t.slice(0,r).split(`
275
+ `).length,end:t.slice(0,i).split(`
276
+ `).length}}function co(t){return t.filter(n=>n.nativeRef||n.mode==="lines"||n.isDir||n.imageData||n.fileData||!n.path)}const Kl="pi-web-sounds",Bs={enabled:!0,question:!0,done:!0,start:!1,error:!0,volume:100};function Gl(){try{const t=localStorage.getItem(Kl);if(!t)return{...Bs};const n=JSON.parse(t),s={...Bs,...n};for(const r of["enabled","question","done","start","error"])typeof s[r]!="boolean"&&(s[r]=Bs[r]);return typeof s.volume!="number"||!Number.isFinite(s.volume)?s.volume=Bs.volume:s.volume=Math.round(Math.max(0,Math.min(100,s.volume))/5)*5,s}catch{return{...Bs}}}function xf(t){try{localStorage.setItem(Kl,JSON.stringify(t))}catch{}}let Us=null;function vf(){try{if(!Us){const t=window.AudioContext??window.webkitAudioContext;if(!t)return null;Us=new t}return Us.state==="suspended"&&Us.resume(),Us}catch{return null}}const kf=[{type:"sine",freq:587.33,start:0,dur:.13,peak:.5},{type:"sine",freq:880,start:.11,dur:.24,peak:.5}],yf=[{type:"sine",freq:880,start:0,dur:.15,peak:.35},{type:"sine",freq:587.33,start:.15,dur:.32,peak:.35}],wf=[{type:"triangle",freq:660,start:0,dur:.08,peak:.22}],bf=[{type:"square",freq:220,start:0,dur:.16,peak:.18},{type:"square",freq:174.61,start:.18,dur:.26,peak:.18}],jf={question:kf,done:yf,start:wf,error:bf};function Cf(t,n,s){const r=t.createOscillator(),i=t.createGain();r.type=n.type,r.frequency.value=n.freq;const a=t.currentTime+n.start,o=Math.max(1e-4,n.peak*s);i.gain.setValueAtTime(1e-4,a),i.gain.exponentialRampToValueAtTime(o,a+.012),i.gain.exponentialRampToValueAtTime(1e-4,a+n.dur),r.connect(i),i.connect(t.destination),r.start(a),r.stop(a+n.dur+.05)}function Ws(t,n=Gl()){if(!n.enabled||!n[t])return;const s=vf();if(!s)return;const r=Math.max(0,Math.min(1,n.volume/100));for(const i of jf[t])Cf(s,i,r)}const Sf=d.lazy(()=>Lr(()=>import("./TerminalPanel-CKaSUsN-.js"),__vite__mapDeps([2,1,3,4,5])).then(t=>({default:t.TerminalPanel}))),Nf=d.lazy(()=>Lr(()=>import("./NodeWorkbench-BiP2ktQP.js"),__vite__mapDeps([6,1,3,4,5])).then(t=>({default:t.NodeWorkbench})));function uo({notice:t,onDismiss:n,onOpenExtensions:s}){const r=et(),[i,a]=d.useState(!1);d.useEffect(()=>{if(i||t.level!=="info")return;const c=setTimeout(()=>n(t.id),3e3);return()=>clearTimeout(c)},[i,t.id,t.level,t.count,n]);const o=t.level==="error"?xd:t.level==="warning"?Fo:od;return e.jsxs("div",{className:`notice notice-${t.level}${i?" paused":""}`,role:"status",onMouseEnter:()=>a(!0),onMouseLeave:()=>a(!1),children:[e.jsx(o,{className:"notice-icon"}),e.jsx("span",{className:"notice-text",children:Pc(t.text)?e.jsxs(e.Fragment,{children:[e.jsx("strong",{children:r("mcpAdapterNoticeTitle")}),e.jsx("p",{children:r("mcpAdapterNoticeNative")}),e.jsx("p",{children:r("mcpAdapterNoticeSeparate")}),e.jsx("button",{onClick:s,children:r("settingsExtensions")}),e.jsxs("details",{children:[e.jsx("summary",{children:r("mcpAdapterNoticeOriginal")}),e.jsx(ai,{text:t.text})]})]}):e.jsx(ai,{text:t.text})}),(t.count??1)>1&&e.jsxs("span",{className:"notice-count",children:["×",t.count]}),e.jsx("button",{type:"button",className:"notice-close",title:r("close"),onClick:()=>n(t.id),children:e.jsx(Wt,{})})]})}const Ef=[],ji=180,Jl=520,Ql=240,Ci=t=>`pi-harness:${t}-panel-width`;function po(t){const n=Number(localStorage.getItem(Ci(t)));return Number.isFinite(n)&&n>=ji&&n<=Jl?n:t==="editor"?480:t==="right"?300:Ql}function ho({side:t,width:n,onResize:s,onReset:r}){const i=et(),a=d.useCallback(o=>{var j,R;o.preventDefault();const c=o.clientX,l=t==="editor"?((j=o.currentTarget.nextElementSibling)==null?void 0:j.getBoundingClientRect().width)??n:n,p=t==="editor"?Math.max(ji,l+(((R=o.currentTarget.previousElementSibling)==null?void 0:R.getBoundingClientRect().width)??0)-180):Jl;let u=l;const f=E=>{const A=t==="left"?E.clientX-c:c-E.clientX;u=Math.min(p,Math.max(ji,Math.round(l+A))),s(u)},k=()=>{window.removeEventListener("pointermove",f),window.removeEventListener("pointerup",k),document.body.classList.remove("panel-resizing"),localStorage.setItem(Ci(t),String(u))};window.addEventListener("pointermove",f),window.addEventListener("pointerup",k),document.body.classList.add("panel-resizing")},[t,n,s]);return e.jsx("div",{className:`resize-handle resize-${t==="editor"?"right":t}`,title:i("dragToResize"),onPointerDown:a,onDoubleClick:()=>{if(r){r();return}const o=t==="editor"?480:t==="right"?300:Ql;s(o),localStorage.setItem(Ci(t),String(o))}})}function Tf(){var gt,Rt,rn,pn,en,jn,xn,Cn,tn,Gn,Rn,Jn,ss,An,vn,kn,hn,on,yn,Qn,Nt,ln,Dn,In,Sn,Yn,$n,gs,rs,Hn,cs,Xn,ds,bs,xs;d.useEffect(()=>{var Q;return(Q=kt==null?void 0:kt.onBeforeClose)==null?void 0:Q.call(kt,qd)},[]);const t=et(),{locale:n}=ns(),{chat:s,send:r,dismissNotice:i,pushNotice:a,setPendingEcho:o,terminal:c,switching:l,switchError:p}=ru(),u=((gt=s.state)==null?void 0:gt.conversationId)===s.activeConversationId?s.state:null,f=Bp(((Rt=s.state)==null?void 0:Rt.cwd)??"",s.ready&&!l,s.scmDirty,s.scmData,r),k=s.conversations.find(Q=>Q.id===s.activeConversationId),j=s.sessions.find(Q=>Q.path===(u==null?void 0:u.sessionFile));br((k==null?void 0:k.title)||fs((j==null?void 0:j.firstMessage)??"")||t("newChat"),j==null?void 0:j.firstMessage,j==null?void 0:j.name,Math.max((j==null?void 0:j.messageCount)??0,(k==null?void 0:k.messageCount)??0,(u==null?void 0:u.messages.length)??0),n,u==null?void 0:u.messages);const[R,E]=d.useState([]),A=d.useRef(new Map),N=d.useRef(s.activeConversationId);d.useLayoutEffect(()=>{N.current!==s.activeConversationId&&(R.length?A.current.set(N.current,R):A.current.delete(N.current),N.current=s.activeConversationId,E(A.current.get(s.activeConversationId)??[]),A.current.delete(s.activeConversationId))},[s.activeConversationId,R]);const[T,y]=d.useState(null),M=d.useRef(null);d.useLayoutEffect(()=>{const Q=M.current;if(Q&&(Q.cwd!==(T==null?void 0:T.cwd)||Q.path!==(T==null?void 0:T.path))){E(co);for(const[Re,Ye]of A.current)A.current.set(Re,co(Ye))}M.current=T},[T]);const b=d.useRef(null),F=d.useRef(null),[U,ce]=d.useState(null);d.useEffect(()=>{var Q;!l&&((Q=s.state)!=null&&Q.cwd)&&T&&T.cwd!==s.state.cwd&&y(null)},[l,(rn=s.state)==null?void 0:rn.cwd,T]);const ie=d.useRef(null),W=d.useRef(null),ve=d.useRef(!1),Se=d.useRef(null),$=d.useCallback(Q=>{const Re=Q.type==="switch_conversation"||Q.type==="new_chat"||Q.type==="set_cwd"||Q.type==="switch_session"||Q.type==="prompt"&&/^\/cwd(?:\s|$)/.test(Q.text);return Re&&(ve.current||Se.current)?!1:Re&&W.current?(W.current(()=>{r(Q)}),!1):Re&&ie.current?(fe("chat"),g("right"),ie.current(()=>{r(Q)&&Q.type!=="switch_session"&&y(null)}),!1):r(Q)},[r]),[$e,L]=d.useState(!1);d.useEffect(()=>{const Q=()=>L(!1),Re=Ye=>{Ye.key==="Escape"&&Q()};return window.addEventListener("drop",Q,!0),window.addEventListener("dragend",Q,!0),window.addEventListener("blur",Q),window.addEventListener("keydown",Re,!0),()=>{window.removeEventListener("drop",Q,!0),window.removeEventListener("dragend",Q,!0),window.removeEventListener("blur",Q),window.removeEventListener("keydown",Re,!0)}},[]),d.useEffect(()=>{const Q=()=>{var Re;(Re=s.state)!=null&&Re.cwd&&$({type:"native_mcp_request",action:"radius",scope:"global",cwd:s.state.cwd,requestId:Gt()})};return window.addEventListener("pi-configure-radius",Q),()=>window.removeEventListener("pi-configure-radius",Q)},[(pn=s.state)==null?void 0:pn.cwd,$]);const[q,fe]=d.useState("chat"),[je,ne]=d.useState(null),[Pe,B]=d.useState(null),[we,re]=d.useState(!1),[Ie,_]=d.useState(null),[le,O]=d.useState(null),[ge,pe]=d.useState(""),Ae=d.useRef(null),ae=d.useRef(je==null?void 0:je.token);ae.current=je==null?void 0:je.token;const Te=d.useRef({cwd:(en=s.state)==null?void 0:en.cwd,conversationId:s.activeConversationId,epoch:0});Te.current.cwd!==((jn=s.state)==null?void 0:jn.cwd)&&(Te.current.epoch++,Se.current=null),Te.current={...Te.current,cwd:(xn=s.state)==null?void 0:xn.cwd,conversationId:s.activeConversationId};const Z=d.useCallback(async Q=>{const Re=Te.current;Re.cwd&&(pe(""),ne({cwd:Re.cwd,path:Q,token:Gt()}),y(null),fe("wiki"),g(null))},[]);d.useEffect(()=>{var ft,wt;if(Se.current){if(Se.current!==((ft=s.state)==null?void 0:ft.conversationId)||Se.current!==s.activeConversationId)return;Se.current=null}const Q=je;if(!Q||Pe!==Q.token||Q.cwd!==((wt=s.state)==null?void 0:wt.cwd)||ve.current||Ae.current===Q.token||!s.ready||l)return;Ae.current=Q.token,ve.current=!0,re(!0),pe("");const Re=s.activeConversationId,Ye=Te.current.epoch;En(Q.cwd,"new-conversation",{path:Q.path,conversationId:Re}).then(Ct=>{Te.current.cwd!==Q.cwd||Te.current.epoch!==Ye||(Se.current=Ct.conversationId,_(Ct.conversationId),O(Q.token))}).catch(Ct=>{Te.current.cwd===Q.cwd&&Te.current.epoch===Ye&&ae.current===Q.token&&pe(Ct.message)}).finally(()=>{ve.current=!1,re(!1)})},[je,Pe,(Cn=s.state)==null?void 0:Cn.cwd,(tn=s.state)==null?void 0:tn.conversationId,s.activeConversationId,s.ready,l,we]);const Fe=le===(je==null?void 0:je.token)&&Ie===s.activeConversationId&&Ie===((Gn=s.state)==null?void 0:Gn.conversationId),z=s.ready&&!l&&!we&&Fe,G=d.useRef(null);d.useEffect(()=>{q!=="chat"||!z||G.current===s.activeConversationId||r({type:"new_chat"})&&(G.current=s.activeConversationId)},[q,z,s.activeConversationId,r]),d.useEffect(()=>{var Q;q==="wiki"&&s.ready&&!l&&!we&&!Se.current&&je&&je.cwd===((Q=s.state)==null?void 0:Q.cwd)&&le===je.token&&Ie&&Ie!==s.activeConversationId&&Z(je.path)},[q,s.ready,l,we,je,(Rn=s.state)==null?void 0:Rn.cwd,s.activeConversationId,le,Ie,Z]);const[J,Ee]=d.useState(null),V=d.useRef(new Set(["chat"]));V.current.add(q);const Le=d.useMemo(()=>s.plugins.filter(Q=>{var Re,Ye;return!((Ye=(Re=s.settings)==null?void 0:Re.disabledPlugins)!=null&&Ye.includes(Q.id))}),[s.plugins,(Jn=s.settings)==null?void 0:Jn.disabledPlugins]),[xe,be]=d.useState([]);d.useEffect(()=>Jd(be),[]),d.useEffect(()=>{Qd(Le,s.pluginsEpoch)},[Le,s.pluginsEpoch]);const[nt,Ce]=d.useState(()=>localStorage.getItem("pi-left-collapsed")==="true"),[ye,ze]=d.useState(!1),Ze=d.useRef(null),Qe=d.useCallback(Q=>{ze(Q),Q?Ce(Re=>(Ze.current=Re,!0)):Ze.current!==null&&(Ce(Ze.current),Ze.current=null)},[]),ct=d.useMemo(()=>Co(u==null?void 0:u.taskProgress,(u==null?void 0:u.messages)??[],(u==null?void 0:u.cwd)??""),[u==null?void 0:u.taskProgress,u==null?void 0:u.messages,u==null?void 0:u.cwd]),[tt,Oe]=d.useState(()=>po("left")),[ee,We]=d.useState(()=>po("right")),w=d.useCallback(Q=>Oe(Q),[]),[H,X]=d.useState(()=>{const Q=Number(localStorage.getItem("pi-harness:editor-share"));return Number.isFinite(Q)&&Q>=.15&&Q<=.85?Q:.45}),ke=d.useCallback(Q=>We(Q),[]),De=d.useCallback(Q=>{const Re=document.querySelector(".view-pane.preview-open:not(.hidden)"),Ye=Re==null?void 0:Re.querySelector(".main"),ft=Re==null?void 0:Re.querySelector(".drawer-right"),wt=((Ye==null?void 0:Ye.getBoundingClientRect().width)??0)+((ft==null?void 0:ft.getBoundingClientRect().width)??0);if(wt>0){const Ct=Math.min(.85,Math.max(.15,Q/wt));X(Ct),localStorage.setItem("pi-harness:editor-share",String(Ct))}},[]),[He,ot]=d.useState(!1),[dt,g]=d.useState(null),[se,qe]=d.useState(()=>window.matchMedia("(max-width: 768px)").matches),[_e,at]=d.useState(()=>window.matchMedia("(max-width: 1100px)").matches);d.useEffect(()=>{const Q=window.matchMedia("(max-width: 1100px)"),Re=Ye=>{at(Ye.matches),g(null)};return Q.addEventListener("change",Re),()=>Q.removeEventListener("change",Re)},[]),d.useEffect(()=>{const Q=window.matchMedia("(max-width: 768px)"),Re=Ye=>qe(Ye.matches);return Q.addEventListener("change",Re),()=>Q.removeEventListener("change",Re)},[]);const mt=d.useCallback((Q,Re,Ye,ft=!1,wt)=>{const Ct=`${Q}|${Ye}|${wt?`${wt.start}-${wt.end}`:""}`;E(It=>It.some(Ot=>`${Ot.path}|${Ot.mode}|${Ot.lines?`${Ot.lines.start}-${Ot.lines.end}`:""}`===Ct)?It:[...It,{path:Q,name:Re,mode:Ye,isDir:ft,...wt?{lines:wt}:{}}])},[]),Mt=d.useCallback((Q,Re)=>{var wt;if(l||!((wt=s.state)!=null&&wt.cwd))return;const Ye=s.state.cwd,ft=()=>{/\.(md|markdown)$/i.test(Q)?Z(Q):(fe("chat"),g("right"),y({path:Q,name:Re,cwd:Ye}))};if(W.current){W.current(ft);return}ie.current?(fe("chat"),g("right"),ie.current(ft)):ft()},[l,(ss=s.state)==null?void 0:ss.cwd,Z]);d.useEffect(()=>{const Q=Re=>{var Nn,I;const Ye=Re.detail,ft=(I=(Nn=s.state)==null?void 0:Nn.cwd)==null?void 0:I.replaceAll("\\","/").replace(/\/$/,"");if(!ft||typeof(Ye==null?void 0:Ye.path)!="string")return;const wt=Ye.path.replaceAll("\\","/"),Ct=wt.startsWith(`${ft}/`)?wt.slice(ft.length+1):wt;if(Ct.startsWith("/")||/^[A-Za-z]:\//.test(Ct)||Ct.split("/").includes(".."))return;Mt(Ct,Ct.split("/").at(-1)??Ct);const It=Ye.line;if(!Number.isInteger(It)||!It||It<1)return;let Ot=0;const Ln=()=>{var st,rt;if(((st=document.querySelector(".fp-file-path"))==null?void 0:st.title.replaceAll("\\","/"))!==`${ft}/${Ct}`){++Ot<40&&window.setTimeout(Ln,100);return}const Xe=document.querySelector(`.fp-line[data-line="${It}"], .fp-edit-line[data-line="${It}"], .fp-markdown [data-source-start="${It}"]`)??Array.from(document.querySelectorAll(".fp-markdown [data-source-start][data-source-end]")).find(vt=>Number(vt.dataset.sourceStart)<=It&&Number(vt.dataset.sourceEnd)>=It);if(Xe){const vt=(rt=Xe.closest(".fp-code-editor"))==null?void 0:rt.querySelector(".fp-editor");if(vt){const cn=Number.parseFloat(getComputedStyle(vt).lineHeight)||22;vt.scrollTop=Math.max(0,(It-1)*cn-vt.clientHeight/2),vt.dispatchEvent(new Event("scroll",{bubbles:!0}))}else Xe.scrollIntoView({block:"center"});Xe.classList.add("from-tool"),window.setTimeout(()=>Xe.classList.remove("from-tool"),2e3)}else++Ot<40&&window.setTimeout(Ln,100)};window.setTimeout(Ln,100)};return window.addEventListener("pi-harness:open-tool-file",Q),()=>window.removeEventListener("pi-harness:open-tool-file",Q)},[Mt,(An=s.state)==null?void 0:An.cwd]);const[Pt,$t]=d.useState(!1),[Ft,Jt]=d.useState(!1),[nn,lt]=d.useState(!1),[Et,zt]=d.useState("prompt"),Ht=()=>{zt("extensions"),lt(!0)},[an,At]=d.useState(!1),[Xt,K]=d.useState(!1);d.useEffect(()=>{const Q=Re=>{var Ot,Ln;const Ye=Re.detail,ft=(Ye==null?void 0:Ye.title)||"插件命令",wt=Ye==null?void 0:Ye.command;if(!wt||!s.ready)return;const Ct={name:ft,command:wt,cwd:"${pwd}"},It=s.terminals.find(Nn=>Nn.title===ft);if(It)c.restart(It.id),$({type:"run_command",terminalId:It.id,conversationId:It.conversationId,command:Ct,cols:80,rows:24});else{const Nn=Gt();c.create({id:Nn,conversationId:s.activeConversationId||((Ot=s.state)==null?void 0:Ot.conversationId)||"",title:ft,cwd:((Ln=s.state)==null?void 0:Ln.cwd)??"",cols:80,rows:24,running:!0,exitCode:null,command:Ct})}fe("terminal")};return window.addEventListener("pi-harness:plugin-run-command",Q),()=>window.removeEventListener("pi-harness:plugin-run-command",Q)},[s,c,$]),d.useEffect(()=>{const Q=Re=>{q==="wiki"||!(Re.ctrlKey||Re.metaKey)||Re.key.toLowerCase()!=="k"||(Re.preventDefault(),K(Ye=>!Ye))};return window.addEventListener("keydown",Q),()=>window.removeEventListener("keydown",Q)},[q]);const[Y,Je]=d.useState(Gl),Be=d.useRef(null),te=d.useRef(null),Ve=d.useRef(0),Ue=d.useRef(!1),yt=d.useRef(s.terminals);d.useEffect(()=>{xf(Y)},[Y]),d.useEffect(()=>{var Re;const Q=yt.current;yt.current=s.terminals;for(const Ye of s.terminals){const ft=((Re=Ye.command)==null?void 0:Re.command)??"",wt=Q.find(Ct=>Ct.id===Ye.id);!(wt!=null&&wt.running)||Ye.running||(ft.startsWith("pi remove ")?$({type:"extensions_reload"}):(ft.startsWith("pi-harness install ")||ft.startsWith("pi-harness uninstall "))&&$({type:"plugins_reload"}))}},[s.terminals,$]),d.useEffect(()=>{var Ye;const Q=((Ye=s.state)==null?void 0:Ye.isStreaming)??!1,Re=Be.current;Be.current=Q,Re!==null&&(!Re&&Q?Ws("start",Y):Re&&!Q&&Ws("done",Y))},[(vn=s.state)==null?void 0:vn.isStreaming,Y]),d.useEffect(()=>{var Re;const Q=((Re=s.dialog)==null?void 0:Re.id)??null;Q!==null&&Q!==te.current&&Ws("question",Y),te.current=Q},[s.dialog,Y]),d.useEffect(()=>{const Q=[...s.notices].reverse().find(Re=>Re.level==="error");Q&&Q.id!==Ve.current&&(Ve.current=Q.id,Ws("error",Y))},[s.notices,Y]);const Bt=d.useCallback(()=>y(null),[]),[Zt,qt]=d.useState(0),St=()=>{const Q=()=>{y(null),fe("chat"),ot(!1),g(se||_e?"right":null),qt(Re=>Re+1)};ie.current?ie.current(Q):Q()};d.useEffect(()=>{var Re;if(!Zt)return;const Q=document.querySelector(".view-pane:not(.hidden) .task-progress");Q==null||Q.focus({preventScroll:!0}),(Re=Q==null?void 0:Q.querySelector(".task-plan-step.running"))==null||Re.scrollIntoView({block:"nearest"})},[Zt]);const dn=d.useCallback((Q,Re,Ye,ft)=>{mt(Q,Re,"lines",!1,{start:Ye,end:ft})},[mt]),pt=Q=>E(Re=>Re.filter(Ye=>Ye.key?Ye.key!==Q:Ye.path!==Q)),Dt=d.useCallback(Q=>(!Q.type.startsWith("list_")&&!Q.type.startsWith("get_")&&g(null),$(Q)),[$]);d.useEffect(()=>{const Q=Re=>{if((Re.metaKey||Re.ctrlKey)&&!Re.shiftKey&&Re.key.toLowerCase()==="n"){if(Re.preventDefault(),W.current){W.current(()=>{fe("chat"),r({type:"new_chat"})});return}fe("chat"),Dt({type:"new_chat"})}};return window.addEventListener("keydown",Q),()=>window.removeEventListener("keydown",Q)},[Dt,r]);const Yt=d.useRef(0),Vt=d.useRef(0),un=(Q,Re)=>{Re===N.current?E(Ye=>[...Ye,Q]):A.current.set(Re,[...A.current.get(Re)??[],Q])},qn=(Q,Re)=>{var wt;const Ye=Date.now();(wt=s.state)!=null&&wt.model&&!s.state.model.vision&&Ye-Vt.current>1e4&&(Vt.current=Ye,a("warning",t("imageNotSupported")));const ft=`paste-${++Yt.current}`;un({path:"",key:ft,name:Q.name,mode:"inline",imageData:Q.data,mimeType:Q.mimeType},Re)},wn=async(Q,Re=N.current)=>{for(const Ye of Q){const ft=await ki(Ye);if(!ft){a("error",t("imageLoadFailed",{name:Ye.name}));continue}qn(ft,Re)}},sn=20*1024*1024,bn=d.useRef(0),zn=async(Q,Re)=>{if(Q.size>sn){a("warning",t("fileTooLarge",{name:Q.name,size:sn/1024/1024}));return}let Ye;try{Ye=(await new Promise((Ct,It)=>{const Ot=new FileReader;Ot.onload=()=>Ct(Ot.result),Ot.onerror=()=>It(Ot.error??new Error("read failed")),Ot.readAsDataURL(Q)})).replace(/^data:[^;]*;base64,/,"")}catch{a("error",t("fileLoadFailed",{name:Q.name}));return}const ft=`upload-${++bn.current}`;un({path:"",key:ft,name:Q.name,mode:"inline",fileData:Ye,size:Q.size,mimeType:Q.type||void 0},Re)},Tt=async Q=>{const Re=N.current;for(const Ye of Q)os(Ye.type)?await wn([Ye],Re):await zn(Ye,Re)},Kt=Ad(s,$,()=>a("error",t("toolRecoveryFailed"))),_n=d.useCallback((Q,Re,Ye,ft)=>{$({type:"edit_message",conversationId:s.activeConversationId,messageId:Q,text:Re,attachments:Ye,...ft})},[$,s.activeConversationId]),Vn=d.useCallback(()=>Jt(!0),[]),Kn=d.useCallback((Q,Re)=>{const Ye=ft=>ft.filter(wt=>!Re.includes(wt));N.current===Q?E(Ye):A.current.set(Q,Ye(A.current.get(Q)??[]))},[]),h=d.useCallback(pt,[]),x=d.useCallback(wn,[wn]),S=d.useCallback(Tt,[Tt]);d.useEffect(()=>{const Q=Re=>{var It;const{cwd:Ye,file:ft,complete:wt}=Re.detail;if(Ye!==((It=s.state)==null?void 0:It.cwd)||!(ft instanceof File)){wt(!1);return}const Ct=s.activeConversationId;ki(ft).then(Ot=>{Ot&&qn(Ot,Ct),wt(!!Ot)}).catch(()=>wt(!1))};return window.addEventListener("pi-codemode-attach",Q),()=>window.removeEventListener("pi-codemode-attach",Q)},[(kn=s.state)==null?void 0:kn.cwd,s.activeConversationId,x]);const P=(hn=s.state)==null?void 0:hn.model,de=(on=s.state)==null?void 0:on.thinkingLevel,oe=(yn=s.state)==null?void 0:yn.availableThinkingLevels,Ne=d.useMemo(()=>u?{model:P??null,conversationId:u.conversationId,runSettings:u.runSettings,routedModel:u==null?void 0:u.routedModel,thinkingLevel:de??"off",availableThinkingLevels:oe??[]}:null,[P,de,oe,u==null?void 0:u.routedModel,u==null?void 0:u.conversationId,(Qn=u==null?void 0:u.runSettings)==null?void 0:Qn.autoCompaction,(Nt=u==null?void 0:u.runSettings)==null?void 0:Nt.autoRetry]),Ke=u==null?void 0:u.conversationId,ht=u==null?void 0:u.cwd,ut=d.useCallback(()=>!s.ready||!Ke||s.terminals.length!==0?!1:(c.create({id:Gt(),conversationId:Ke,title:t("terminalTitle",{n:1}),cwd:ht??"",cols:80,rows:24,running:!0,exitCode:null}),!0),[s.ready,Ke,ht,s.terminals.length,t,c]);return d.useEffect(()=>{if(Ue.current){if(q!=="terminal"||s.terminals.length!==0){Ue.current=!1;return}ut()&&(Ue.current=!1)}},[s.terminals.length,ut,q]),e.jsx($c,{conversationId:(u==null?void 0:u.conversationId)??"",files:ct,active:q==="chat",onOpenChange:Qe,children:e.jsxs("div",{className:`app design-workspace ${ye&&q==="chat"?"changes-open":""} ${q==="wiki"?"wiki-mode":""} ${nt?"left-collapsed":""} ${T&&q==="chat"?"document-open":""}`,style:{"--left-w":`${tt}px`,"--right-w":`${ee}px`},onDragOver:Q=>{var Re;Array.from(((Re=Q.dataTransfer)==null?void 0:Re.types)??[]).includes("Files")&&(Q.preventDefault(),L(!0))},onDragLeave:Q=>{Q.currentTarget.contains(Q.relatedTarget)||L(!1)},onDrop:Q=>{var wt,Ct;if(L(!1),!Array.from(((wt=Q.dataTransfer)==null?void 0:wt.types)??[]).includes("Files"))return;Q.preventDefault();const Re=Array.from(((Ct=Q.dataTransfer)==null?void 0:Ct.files)??[]);if(Re.length===0){a("warning",t("foldersNotSupported"));return}const Ye=Re.filter(It=>os(It.type)),ft=Re.filter(It=>!os(It.type));Ye.length>0&&wn(Ye),ft.length>0&&Tt(ft)},children:[$e&&e.jsx("div",{className:"app-drop-overlay","aria-hidden":!0,children:e.jsxs("span",{children:["📎 ",t("dropHereToAttach")]})}),q!=="nodes"&&q!=="wiki"&&e.jsx("div",{className:`panel-drawer drawer-left ${dt==="left"?"open":""}`,children:e.jsx(Kp,{incidentState:u?(ln=Fs(u.streamingMessage?[...u.messages,u.streamingMessage]:u.messages,u.isStreaming).current)==null?void 0:ln.state:void 0,onOpenSettings:()=>{zt("prompt"),lt(!0)},onNewChat:()=>{fe("chat"),Dt({type:"new_chat"})},send:Dt,active:!se||dt==="left",ready:s.ready&&!!u,status:s.status,cwd:((Dn=s.state)==null?void 0:Dn.cwd)??"",sessionFile:(u==null?void 0:u.sessionFile)??null,conversations:s.conversations,sessions:s.sessions,projects:s.projects,dirBrowse:s.dirBrowse,activeConversationId:s.activeConversationId})}),q!=="nodes"&&q!=="wiki"&&!se&&!nt&&e.jsx(ho,{side:"left",width:tt,onResize:w}),e.jsxs("div",{className:"workspace-column",children:[e.jsx(zp,{leftCollapsed:nt,gitChangeCount:f.files.length,onOpenTask:St,chat:s,send:$,terminal:c,view:q,plugins:Le,onViewChange:Q=>{Ue.current=Q==="terminal"&&s.terminals.length===0,Ue.current&&ut()&&(Ue.current=!1);const Re=()=>{fe(Q),g(null)};q==="wiki"&&W.current?W.current(Re):Q==="wiki"&&ie.current?ie.current(Re):Re()},onOpenPanel:Q=>{Q==="left"&&!se?(g(null),Ze.current=null,Ce(Re=>(localStorage.setItem("pi-left-collapsed",String(!Re)),!Re))):Q==="right"&&!se&&!_e&&!T?ot(Re=>!Re):(Q==="right"&&ot(!1),g(Re=>Re===Q?null:Q))},onManageModels:()=>Jt(!0),onOpenSettings:()=>{zt("prompt"),lt(!0)},onOpenBgTasks:()=>At(!0),onOpenGlobalSearch:()=>K(!0),sound:Y,onSoundChange:Je,onSoundPreview:Q=>Ws(Q,Y)}),e.jsx(au,{state:u,send:$,connected:s.ready}),s.pendingDialogs.filter(Q=>Q.conversationId!==s.activeConversationId).map(Q=>e.jsxs("button",{className:"protocol-banner",onClick:()=>{if(ve.current||Se.current)return;const Re=()=>{r({type:"switch_conversation",id:Q.conversationId})&&fe("chat")};W.current?W.current(Re):ie.current?ie.current(Re):Re()},children:[t("pluginRequest")," · ",Q.source," · ",Q.title]},Q.id)),q==="wiki"&&s.dialog&&e.jsx(wi,{dialog:s.dialog,send:$}),p&&e.jsxs("div",{className:"protocol-banner",role:"alert",children:[e.jsx("button",{onClick:()=>$({type:"set_cwd",path:p,source:"ui"}),children:t("retryProjectSwitch")})," ",p]}),l&&e.jsxs("div",{className:"protocol-banner",role:"status",children:[t("switchingProject")," ",l]}),s.protocolMismatch&&e.jsxs("div",{className:"protocol-banner",children:["⚠ ",t("protocolMismatch")]}),q!=="chat"&&s.notices.length>0&&e.jsx("div",{className:"notices notices-overlay",children:s.notices.map(Q=>e.jsx(uo,{notice:Q,onDismiss:i,onOpenExtensions:Ht},Q.id))}),e.jsxs("div",{className:"layout",style:{"--left-w":`${tt}px`,"--right-w":`${ee}px`,"--editor-share":H},children:[dt&&(se||_e&&!T||dt==="left"&&!!T)&&e.jsx("div",{className:"drawer-backdrop",onClick:()=>g(null)}),e.jsxs("div",{className:`view-pane ${T?"preview-open":""} ${q==="chat"?"":"hidden"}`,children:[e.jsxs("main",{className:"main",children:[u?e.jsx(er.Provider,{value:u.cwd,children:e.jsx(Dm,{recovery:{...Kt,models:s.models,onLoadModels:()=>{!s.models.length&&!s.modelsLoading&&$({type:"list_models"})}},active:q==="chat",connected:s.ready,silenceNotified:((In=s.agentSilence)==null?void 0:In.conversationId)===u.conversationId&&s.agentSilence.phase==="silent",state:u,liveOutputs:s.liveOutputs,toolStatuses:s.toolStatuses,onEdit:_n,onStop:()=>$({type:"abort"}),thinkingWrap:((Sn=s.settings)==null?void 0:Sn.thinkingWrap)??!1,toolsWrap:((Yn=s.settings)==null?void 0:Yn.toolsWrap)??!0,pendingEcho:s.pendingEcho,reloadEvents:s.reloadEvents},u.conversationId)}):e.jsx("div",{className:"boot-wait",children:s.ready?t("loadingSession"):t("connectingServer")}),e.jsx(Bm,{chat:s,send:$}),s.dialog&&e.jsx(wi,{dialog:s.dialog,send:$}),s.notices.length>0&&e.jsx("div",{className:"notices",children:s.notices.map(Q=>e.jsx(uo,{notice:Q,onDismiss:i,onOpenExtensions:Ht},Q.id))}),e.jsx(Hm,{active:q==="chat"&&!Fe,currentFile:!l&&(U==null?void 0:U.cwd)===(($n=s.state)==null?void 0:$n.cwd)?U:null,contextReader:b,contextSaver:F,stats:u==null?void 0:u.stats,promptResult:s.promptResult,verifying:(gs=u==null?void 0:u.tree)==null?void 0:gs.verifying,queue:u==null?void 0:u.queue,pendingCount:((u==null?void 0:u.queue.steering.length)??0)+((u==null?void 0:u.queue.followUp.length)??0),send:$,ready:s.ready&&!!u&&!(q==="chat"&&(we||Fe)),streaming:(u==null?void 0:u.isStreaming)??!1,silentActivity:((rs=s.agentSilence)==null?void 0:rs.conversationId)===s.activeConversationId?s.agentSilence.activity:null,messages:(u==null?void 0:u.messages)??Ef,slashCommands:s.slashCommands,modelState:Ne,models:s.models,modelsLoading:s.modelsLoading,activeConversationId:s.activeConversationId,setPendingEcho:o,attachments:R,onRemoveAttachment:h,onAddImageFiles:x,onAddLocalFiles:S,onNotice:a,onManageModels:Vn,onSent:Kn})]}),e.jsx(jd,{cwd:(u==null?void 0:u.cwd)??"",data:s.scmDiffData,send:$,ready:s.ready&&!l,notRepo:f.notRepo,branch:f.branch,defaultBase:f.base,branches:f.branches,dirty:s.scmDirty},(u==null?void 0:u.conversationId)??""),!se&&(!_e||!!T)&&(!He||!!T)&&e.jsx(ho,{side:T?"editor":"right",width:T?480:ee,onResize:T?De:ke,onReset:T?()=>{X(.45),localStorage.setItem("pi-harness:editor-share","0.45")}:void 0}),e.jsxs("div",{className:`panel-drawer drawer-right ${He&&!T?"files-collapsed":""} ${dt==="right"?"open":""}`,children:[e.jsx("div",{className:"file-list-host",hidden:!!T,children:e.jsx(rh,{active:!He&&!T&&!l&&q==="chat"&&(!se&&!_e||dt==="right"),send:$,files:s.files,changed:f.files,notRepo:f.notRepo,fileChanged:s.fileChanged,widgets:s.widgets,messages:(u==null?void 0:u.messages)??[],streamingMessage:(u==null?void 0:u.streamingMessage)??null,taskProgress:u==null?void 0:u.taskProgress,isStreaming:u==null?void 0:u.isStreaming,conversationId:s.activeConversationId,agentSilence:s.agentSilence,cwd:((Hn=s.state)==null?void 0:Hn.cwd)??"",onAttach:(Q,Re,Ye,ft)=>{g(null),mt(Q,Re,Ye,ft)},onPreview:Mt,onNotice:(Q,Re)=>a(Q,Re)})}),T&&e.jsx(mf,{file:T,contextReader:b,contextSaver:F,onContextChange:ce,guard:ie,result:s.fileResult,disabled:!!l||T.cwd!==((cs=s.state)==null?void 0:cs.cwd),connected:s.status==="open",content:s.fileContent,fileChanged:s.fileChanged,scmData:((Xn=s.scmData)==null?void 0:Xn.type)==="scm_data"?s.scmData:null,scmDirty:s.scmDirty,send:$,onAddLines:dn,onAttach:mt,onClose:Bt},`${T.cwd}:${T.path}`)]})]}),e.jsx("div",{className:`view-pane ${q==="wiki"?"":"hidden"}`,children:V.current.has("wiki")&&s.state&&e.jsx(Fp,{recovery:u==null?void 0:u.recovery,cwd:s.state.cwd,conversationId:s.activeConversationId,fileRequest:(je==null?void 0:je.cwd)===s.state.cwd?je:null,messages:Fe?s.state.messages:[],streaming:z&&s.state.isStreaming,live:z?s.state.streamingMessage:null,model:s.state.model,contextPercent:s.state.stats.contextUsage.percent,toolStatuses:s.toolStatuses,active:q==="wiki",ready:z,onContentRequested:B,sessionError:ge,writingBlocked:!!l||s.state.isStreaming,openDocument:Z,thinkingWrap:((ds=s.settings)==null?void 0:ds.thinkingWrap)??!1,connected:s.ready,silenceNotified:((bs=s.agentSilence)==null?void 0:bs.conversationId)===s.state.conversationId&&s.agentSilence.phase==="silent",send:$,guard:W},s.state.cwd)}),e.jsx("div",{className:`view-pane ${q==="terminal"?"":"hidden"}`,children:e.jsx(d.Suspense,{fallback:null,children:V.current.has("terminal")&&e.jsx(Sf,{active:q==="terminal"&&!l,chat:s,send:$,terminal:c})})}),e.jsx("div",{className:`view-pane ${q==="nodes"?"":"hidden"}`,children:e.jsx(d.Suspense,{fallback:null,children:V.current.has("nodes")&&e.jsx(Nf,{active:q==="nodes",send:$})})}),e.jsx("div",{className:`view-pane ${q==="git"?"":"hidden"}`,children:V.current.has("git")&&e.jsx(zm,{chat:s,send:$,terminal:c,active:q==="git",commitToShow:J,onSwitchToTerminal:()=>fe("terminal")})}),xe.map(Q=>{const Re=`plugin:${Q.info.id}`;return e.jsx("div",{className:`view-pane ${q===Re?"":"hidden"}`,children:V.current.has(Re)&&e.jsx(Vm,{entry:Q,send:$})},Q.info.id)})]})]}),e.jsx(Wm,{chat:s,send:$}),s.ready&&s.state&&s.state.piConfigured===!1&&!Pt&&!Ft&&e.jsx(Km,{send:$,piConfigured:s.state.piConfigured,piAgentInstalled:s.state.piAgentInstalled,providers:s.providers,installResult:s.installResult,onClose:()=>$t(!0)}),e.jsx(Op,{state:s.providerAuth,send:$}),Ft&&e.jsx(Qm,{send:$,providers:s.modelsConfig,providerStatus:s.providers,fetchModelsResult:s.fetchModelsResult,refreshProviderResult:s.refreshProviderResult,cloneProviderResult:s.cloneProviderResult,onClose:()=>Jt(!1)}),e.jsx(iu,{state:u,connected:s.ready,send:$}),nn&&e.jsx(of,{initialTab:Et,chat:s,send:$,onClose:()=>lt(!1)}),an&&e.jsx(cf,{servers:s.bgServers,send:$,onClose:()=>At(!1)}),Xt&&e.jsx(df,{send:$,sessions:s.sessions,projects:s.projects,cwd:((xs=s.state)==null?void 0:xs.cwd)??"",fileSearch:s.fileSearch,onClose:()=>K(!1),onSwitchSession:Q=>{$({type:"switch_session",path:Q})},onSwitchProject:Q=>{$({type:"set_cwd",path:Q,source:"ui"})},onPreviewFile:Mt})]})})}kt&&document.documentElement.classList.add("pi-desktop",`pi-desktop-${kt.platform}`);Dd();Ec();Rc.createRoot(document.getElementById("root")).render(e.jsx(d.StrictMode,{children:e.jsx(wd,{children:e.jsx(Tf,{})})}));export{ys as F,Nc as T,Lr as _,ls as a,Mf as b,Pf as c,ua as d,Or as e,Wt as f,To as g,Ni as h,Gt as r,et as u};