@intent-hq/web 2.392.3 → 2.393.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 (147) hide show
  1. package/package.json +1 -1
  2. package/web/app/immutable/chunks/{Ct1r6efw.js → 0IudVN8T.js} +2 -2
  3. package/web/app/immutable/chunks/{edaGtK2z.js → 0Pskylmi.js} +1 -1
  4. package/web/app/immutable/chunks/{CnDy2OA4.js → 0biFhMxb.js} +1 -1
  5. package/web/app/immutable/chunks/{BH56GSiy.js → 3Z-66JFK.js} +1 -1
  6. package/web/app/immutable/chunks/{DlbHdfKY.js → 3eHuEsL0.js} +1 -1
  7. package/web/app/immutable/chunks/{CnDbx_Wj.js → 7Ovc5F1W.js} +1 -1
  8. package/web/app/immutable/chunks/{Cp9hDo50.js → 7bKjKvMj.js} +1 -1
  9. package/web/app/immutable/chunks/{DWurigib.js → 8ysnd5N8.js} +4 -4
  10. package/web/app/immutable/chunks/{DimbKbDZ.js → 9gZxSRYR.js} +2 -2
  11. package/web/app/immutable/chunks/{DQxnu3QZ.js → AJU0I4QP.js} +1 -1
  12. package/web/app/immutable/chunks/{BZNRCsEn.js → B1jwNspC.js} +1 -1
  13. package/web/app/immutable/chunks/{DUbqvr_K.js → B2NCDWQj.js} +1 -1
  14. package/web/app/immutable/chunks/{4Rh5tdzC.js → B3M7htfw.js} +1 -1
  15. package/web/app/immutable/chunks/{Cks1DUg1.js → BABLhp9e.js} +1 -1
  16. package/web/app/immutable/chunks/{CyUokemm.js → BAWHRd64.js} +1 -1
  17. package/web/app/immutable/chunks/{BhD6TCSq.js → BAlN6xXV.js} +2 -2
  18. package/web/app/immutable/chunks/{DxZIPHU6.js → BDY2Kajf.js} +1 -1
  19. package/web/app/immutable/chunks/{BLNxuTdw.js → BDYqZy5l.js} +1 -1
  20. package/web/app/immutable/chunks/{DJDA_1H4.js → BEeu6Jyo.js} +1 -1
  21. package/web/app/immutable/chunks/{BipAYtG2.js → BGIAis8Q.js} +3 -3
  22. package/web/app/immutable/chunks/{q9gf_Sso.js → BHFbn3A9.js} +1 -1
  23. package/web/app/immutable/chunks/{D__LL1n8.js → BI6MUuoX.js} +1 -1
  24. package/web/app/immutable/chunks/{DEykPUjl.js → BI9u_QTd.js} +1 -1
  25. package/web/app/immutable/chunks/{n1INJGMs.js → BK7FmI7K.js} +1 -1
  26. package/web/app/immutable/chunks/{BC7-67A3.js → BKFA3yUf.js} +1 -1
  27. package/web/app/immutable/chunks/{CNKJ8_Xr.js → BMHxxfP4.js} +1 -1
  28. package/web/app/immutable/chunks/{B87xP_ZF.js → BOpa3JL5.js} +1 -1
  29. package/web/app/immutable/chunks/{DqQqeuqi.js → BVRxvAzz.js} +1 -1
  30. package/web/app/immutable/chunks/{CE7ZckmT.js → BVab-LI7.js} +1 -1
  31. package/web/app/immutable/chunks/{uQRHnH1Z.js → BZ5plXZy.js} +1 -1
  32. package/web/app/immutable/chunks/{Cf5NbMeL.js → B_dB55pf.js} +3 -3
  33. package/web/app/immutable/chunks/{BtOGFmaT.js → Bb6_ZpFm.js} +1 -1
  34. package/web/app/immutable/chunks/{DGMKnMeG.js → BezqW82L.js} +2 -2
  35. package/web/app/immutable/chunks/{BHYEUr70.js → BgKsHej9.js} +2 -2
  36. package/web/app/immutable/chunks/{BRtw-FGJ.js → BieWjGd7.js} +1 -1
  37. package/web/app/immutable/chunks/{_aw8AL2s.js → BroDUcjq.js} +1 -1
  38. package/web/app/immutable/chunks/{BptF1xOU.js → Bt1-7rTQ.js} +1 -1
  39. package/web/app/immutable/chunks/{CVG625sB.js → Bttih9ri.js} +1 -1
  40. package/web/app/immutable/chunks/{DDhuJH-4.js → Bu0K6ujo.js} +1 -1
  41. package/web/app/immutable/chunks/{By6WkvE9.js → Bxf_-54V.js} +1 -1
  42. package/web/app/immutable/chunks/{BrLVGrLO.js → BxpgiWm2.js} +1 -1
  43. package/web/app/immutable/chunks/{gdhW58MB.js → C-86kNuI.js} +3 -3
  44. package/web/app/immutable/chunks/{CTGxPVh7.js → C35-tQAa.js} +1 -1
  45. package/web/app/immutable/chunks/{Cs3vMbTn.js → CBKDJPOp.js} +1 -1
  46. package/web/app/immutable/chunks/{CDUwgFl9.js → CEfljVcs.js} +1 -1
  47. package/web/app/immutable/chunks/{Cy5LTcPz.js → CF6Vxctv.js} +1 -1
  48. package/web/app/immutable/chunks/{DIHHBzYi.js → CJL-iSZe.js} +2 -2
  49. package/web/app/immutable/chunks/{FTRClsUK.js → CJvysCNo.js} +1 -1
  50. package/web/app/immutable/chunks/{ERz1iYnn.js → CKOT06_N.js} +1 -1
  51. package/web/app/immutable/chunks/{BrCVQoPE.js → CPsAdpQg.js} +1 -1
  52. package/web/app/immutable/chunks/{2ZBNrUZy.js → CUllgFqe.js} +1 -1
  53. package/web/app/immutable/chunks/{DtqJUfJC.js → CXnXrUsE.js} +1 -1
  54. package/web/app/immutable/chunks/{7n-O-xn5.js → Cad-FQZw.js} +1 -1
  55. package/web/app/immutable/chunks/{8ItTOum-.js → CbBvi-vT.js} +2 -2
  56. package/web/app/immutable/chunks/{u-Z99Ptk.js → Cev7VHoN.js} +1 -1
  57. package/web/app/immutable/chunks/{BFMw_Rsu.js → CippTVu3.js} +1 -1
  58. package/web/app/immutable/chunks/{C2KrJl1V.js → CkbdUYUB.js} +1 -1
  59. package/web/app/immutable/chunks/{BafkB9h2.js → Ct8a2yek.js} +1 -1
  60. package/web/app/immutable/chunks/{CKa70XGN.js → CtX9AjBD.js} +1 -1
  61. package/web/app/immutable/chunks/{DgzWQmDb.js → Cxm3e0CO.js} +1 -1
  62. package/web/app/immutable/chunks/{DIUdGij-.js → CzoSrhdL.js} +2 -2
  63. package/web/app/immutable/chunks/{D1Tekuc4.js → D1nkWdsN.js} +1 -1
  64. package/web/app/immutable/chunks/{QnRBGtVu.js → D2Q6mppm.js} +1 -1
  65. package/web/app/immutable/chunks/{nUY7GyaZ.js → D6eyCbi1.js} +1 -1
  66. package/web/app/immutable/chunks/{DVSwhvvP.js → DCgY039R.js} +7 -7
  67. package/web/app/immutable/chunks/{CcUDp4zq.js → DCzxlgBs.js} +1 -1
  68. package/web/app/immutable/chunks/{CVCwKAMk.js → DDa6EINl.js} +1 -1
  69. package/web/app/immutable/chunks/{YClu3XTz.js → DF6LaFyj.js} +2 -2
  70. package/web/app/immutable/chunks/{Bz-Q0sJs.js → DGGucQxs.js} +2 -2
  71. package/web/app/immutable/chunks/{BtmdpA7S.js → DHwN0lRn.js} +1 -1
  72. package/web/app/immutable/chunks/{Bsnum5pm.js → DLGucGdD.js} +3 -3
  73. package/web/app/immutable/chunks/{BzZzhsx0.js → DM5kqQ1V.js} +1 -1
  74. package/web/app/immutable/chunks/{CCMvmg57.js → DM_PIf-5.js} +1 -1
  75. package/web/app/immutable/chunks/{D80ng7VB.js → DO2zAKv0.js} +3 -3
  76. package/web/app/immutable/chunks/{O8yKLCWC.js → DOK_g7vV.js} +1 -1
  77. package/web/app/immutable/chunks/{DyrDaCZi.js → DSXyr_Fr.js} +1 -1
  78. package/web/app/immutable/chunks/{BSsSTp5c.js → DT_y9FGD.js} +1 -1
  79. package/web/app/immutable/chunks/{Bhk2u-_3.js → DU4Vhr-0.js} +1 -1
  80. package/web/app/immutable/chunks/{Dz-57yVz.js → DU59Vdu3.js} +1 -1
  81. package/web/app/immutable/chunks/{DthJR85Z.js → DVhkgoDW.js} +1 -1
  82. package/web/app/immutable/chunks/{PZ5MSUIU.js → DXBE2Tld.js} +1 -1
  83. package/web/app/immutable/chunks/{D9OezaF9.js → DZlDxCgn.js} +1 -1
  84. package/web/app/immutable/chunks/{C3L7kk5u.js → D_EFP2qU.js} +1 -1
  85. package/web/app/immutable/chunks/{DWOcsYbU.js → D_YdQJM4.js} +1 -1
  86. package/web/app/immutable/chunks/{Bex9L_jH.js → DabFMHr_.js} +4 -4
  87. package/web/app/immutable/chunks/{D2Jd8tc3.js → DcGK_0d9.js} +1 -1
  88. package/web/app/immutable/chunks/{DvXSJM4q.js → DcJ9XwiY.js} +1 -1
  89. package/web/app/immutable/chunks/{B3sgdO-M.js → DfApjOPM.js} +1 -1
  90. package/web/app/immutable/chunks/{CfOrhDjV.js → DhBBsVaP.js} +1 -1
  91. package/web/app/immutable/chunks/{DccCxKmZ.js → DjD2npnM.js} +1 -1
  92. package/web/app/immutable/chunks/{9AeivJQm.js → Ds7d6UPo.js} +4 -4
  93. package/web/app/immutable/chunks/{DdpYiyRs.js → DuiDeolO.js} +1 -1
  94. package/web/app/immutable/chunks/{PAEJNClQ.js → DujlAAuA.js} +1 -1
  95. package/web/app/immutable/chunks/{2bueaerM.js → DzeUh63h.js} +1 -1
  96. package/web/app/immutable/chunks/{BezBXtqG.js → FXLHv4s7.js} +1 -1
  97. package/web/app/immutable/chunks/{Ce2Qo9vu.js → FzsqLvWW.js} +1 -1
  98. package/web/app/immutable/chunks/{Ce20e-vK.js → GCJgqmLv.js} +1 -1
  99. package/web/app/immutable/chunks/{L9YD-wcw.js → GFF7xfJq.js} +1 -1
  100. package/web/app/immutable/chunks/{C6O8IM8T.js → HcCqNlKh.js} +1 -1
  101. package/web/app/immutable/chunks/{Egi6fNpS.js → IGNO0qoE.js} +1 -1
  102. package/web/app/immutable/chunks/{B3ZeLze4.js → OrDYwyck.js} +1 -1
  103. package/web/app/immutable/chunks/{DjyYYXwz.js → PWNFccPv.js} +1 -1
  104. package/web/app/immutable/chunks/{CO-JfYA5.js → Pc52abky.js} +1 -1
  105. package/web/app/immutable/chunks/{C8XfkHlI.js → QEpqKBee.js} +1 -1
  106. package/web/app/immutable/chunks/{CQmOm-Tm.js → RsYrgUiV.js} +1 -1
  107. package/web/app/immutable/chunks/{B5V_Igzh.js → W0kxgN1W.js} +1 -1
  108. package/web/app/immutable/chunks/{wsIl6ydR.js → X66bh60j.js} +1 -1
  109. package/web/app/immutable/chunks/{DEuuzjmM.js → XSkFT3M0.js} +1 -1
  110. package/web/app/immutable/chunks/{CKzjrq__.js → YWPnOD4T.js} +1 -1
  111. package/web/app/immutable/chunks/{DeJMgdsa.js → YnYoZ2NK.js} +1 -1
  112. package/web/app/immutable/chunks/{B26epB4C.js → aQkb4saz.js} +1 -1
  113. package/web/app/immutable/chunks/{BC2ymm4x.js → b45PQ8TG.js} +1 -1
  114. package/web/app/immutable/chunks/{CPgSaaZt.js → bX4FGmNr.js} +1 -1
  115. package/web/app/immutable/chunks/{BOnAZ0Bh.js → dEp87wve.js} +1 -1
  116. package/web/app/immutable/chunks/{A9FjQ4ig.js → fr4AMTgg.js} +1 -1
  117. package/web/app/immutable/chunks/{yus24-dF.js → l_KiA0-X.js} +1 -1
  118. package/web/app/immutable/chunks/{C1UoJPr2.js → ng4mcU_-.js} +1 -1
  119. package/web/app/immutable/chunks/{BAbB1JR3.js → nnHDE1dd.js} +1 -1
  120. package/web/app/immutable/chunks/{B5OK1c9R.js → nrSh0aC8.js} +1 -1
  121. package/web/app/immutable/chunks/{ZspDMNEv.js → oHufBZXQ.js} +1 -1
  122. package/web/app/immutable/chunks/{-xPMI1SM.js → r0vRtx-T.js} +1 -1
  123. package/web/app/immutable/chunks/{BQLNg--d.js → u2ZzqP0a.js} +1 -1
  124. package/web/app/immutable/chunks/{VeOG7xIg.js → uzIA17NN.js} +3 -3
  125. package/web/app/immutable/chunks/{CN7DE5jB.js → v7NJYdhp.js} +1 -1
  126. package/web/app/immutable/chunks/{B0dqY8Yd.js → vA_m-Yoy.js} +1 -1
  127. package/web/app/immutable/chunks/{g2j4hm88.js → w6C2OuF7.js} +1 -1
  128. package/web/app/immutable/chunks/{DVqhJMup.js → yKdlMKAe.js} +2 -2
  129. package/web/app/immutable/entry/{app.DBKLYfDG.js → app.CiyeQuxv.js} +2 -2
  130. package/web/app/immutable/entry/start.D87x7VCJ.js +1 -0
  131. package/web/app/immutable/nodes/{0.Dr_KMFP9.js → 0.CRbxkcM2.js} +1 -1
  132. package/web/app/immutable/nodes/{1.B4UC5y6C.js → 1.DqX6QaPm.js} +1 -1
  133. package/web/app/immutable/nodes/{10.D-SXaVii.js → 10.BCKuK60u.js} +1 -1
  134. package/web/app/immutable/nodes/{11.CD0ZMPB_.js → 11.DfT5UkBP.js} +1 -1
  135. package/web/app/immutable/nodes/{15.CWhAy0IL.js → 15.D7dZwhi4.js} +1 -1
  136. package/web/app/immutable/nodes/{19.Cl4NIDR3.js → 19.Bp3Vf5X-.js} +2 -2
  137. package/web/app/immutable/nodes/{2.DgYKd6eT.js → 2.COUI43GN.js} +1 -1
  138. package/web/app/immutable/nodes/{3.Cz3D2Kq7.js → 3.Ch8C_wLR.js} +1 -1
  139. package/web/app/immutable/nodes/{4.CjaUjxEb.js → 4.DNtyFj6E.js} +1 -1
  140. package/web/app/immutable/nodes/{5.COJH7IAv.js → 5.DibkYULx.js} +1 -1
  141. package/web/app/immutable/nodes/{6.Da5DOHiE.js → 6.Cpj-A029.js} +1 -1
  142. package/web/app/immutable/nodes/{7.dcDATK47.js → 7.CecRnFtb.js} +1 -1
  143. package/web/app/immutable/nodes/{8.C2qio8n9.js → 8.BbuGaD-H.js} +1 -1
  144. package/web/app/immutable/nodes/{9.CjfzK0IK.js → 9.BMl85hfy.js} +2 -2
  145. package/web/app/version.json +1 -1
  146. package/web/index.html +9 -9
  147. package/web/app/immutable/entry/start.DyzI50m5.js +0 -1
@@ -1 +1 @@
1
- var De=Object.defineProperty;var Ce=(i,s,e)=>s in i?De(i,s,{enumerable:!0,configurable:!0,writable:!0,value:e}):i[s]=e;var E=(i,s,e)=>Ce(i,typeof s!="symbol"?s+"":s,e);import{K as Le,P as ce,a6 as le,as as z,aC as ve}from"./DWurigib.js";import{b_ as we,c$ as ue,cr as de,cq as be}from"./CNKJ8_Xr.js";import{JH as p,Cg as Fe,bJ as ke,i as Ge,LM as me,ir as Ee,bV as Pe,Ec as H,CF as xe,fl as Ve,AL as Ue,e3 as fe,fh as _e,e2 as he,Be,Lq as $e,wy as Xe}from"./D0qhIm1r.js";import{aO as Se,dX as ge,A as K,P as Re,aK as Q}from"./cD292w1o.js";import{h as qe}from"./BAtAwQ72.js";import{c as W}from"./ChTqQfQN.js";import{a as We}from"./BdWqymET.js";import{m as j}from"./DkQdSPDN.js";import"./3SdAC2_C.js";import{bm as n}from"./Fcr7AvC-.js";import"./BRCr02in.js";import"./CWfjuhY2.js";import"./DRMe5Ypb.js";import{R as pe}from"./B5aYN90J.js";import{L as Ye}from"./CSiaiLHL.js";function ze(i,s){return i.some(e=>e.id===s.id)?i.map(e=>e.id===s.id?{...s,...s.author==null&&e.author!==void 0?{author:e.author}:{}}:e):[...i,s]}const Te="confirmUnslothModelSwitch";function He(i){if(!i||typeof i!="object")return!1;const{agentId:s,agentName:e,workspaceId:t,workspaceTitle:r}=i;return typeof s=="string"&&typeof e=="string"&&typeof t=="string"&&(r===null||typeof r=="string")}function Ke(i){for(let s=i,e=0;s&&e<4;e++){const t=s.data;if(t&&typeof t=="object"){const{code:r,currentModel:a,requestedModel:l,agents:o}=t;if(r==="unsloth-model-switch-confirmation-required"&&typeof a=="string"&&typeof l=="string"&&Array.isArray(o)&&o.every(He))return{currentModel:a,requestedModel:l,agents:o}}s=s.cause}}function bt(i){if(!i||!(Te in i))return i;const{[Te]:s,...e}=i;return Object.keys(e).length>0?e:void 0}const Z=typeof performance<"u"?performance:{now:()=>Date.now()},V=new We("PerformanceOptimizer"),w=class w{constructor(){E(this,"metricsBuffer");E(this,"metricsIndex",0);E(this,"metricsCount",0);E(this,"MAX_METRICS",500);E(this,"TARGET_RESPONSE_TIME",100);E(this,"memoCache",new Map);E(this,"MEMO_TTL",6e4);E(this,"MAX_CACHE_SIZE",100);E(this,"cacheHits",0);E(this,"cacheMisses",0);E(this,"pendingRequests",new Map);E(this,"requestQueue",[]);E(this,"cleanupInterval",null);this.metricsBuffer=new Array(this.MAX_METRICS).fill(null),this.startCacheCleanup(),V.info("PerformanceOptimizer initialized")}static getInstance(){return w.instance||(w.instance=new w),w.instance}reset(){this.metricsBuffer=new Array(this.MAX_METRICS).fill(null),this.metricsIndex=0,this.metricsCount=0,this.memoCache.clear(),this.pendingRequests.clear(),this.requestQueue=[],this.cacheHits=0,this.cacheMisses=0}clearCache(){this.memoCache.clear(),this.cacheHits=0,this.cacheMisses=0}async processBatch(s,e,t={}){const{batchSize:r=10,concurrency:a=4}=t,l=[];for(let o=0;o<s.length;o+=r){const _=s.slice(o,o+r).map((c,R)=>{const g=Math.floor(R/a)*10;return new Promise(d=>{setTimeout(async()=>{const k=await e(c);d(k)},g)})}),u=await Promise.all(_);l.push(...u)}return l}startCacheCleanup(){this.cleanupInterval=setInterval(()=>{this.cleanupCache()},3e4)}stopCacheCleanup(){this.cleanupInterval&&(clearInterval(this.cleanupInterval),this.cleanupInterval=null)}cleanupCache(){const s=Date.now(),e=[];this.memoCache.forEach((t,r)=>{s-t.timestamp>this.MEMO_TTL&&e.push(r)}),e.forEach(t=>this.memoCache.delete(t)),this.memoCache.size>this.MAX_CACHE_SIZE&&Array.from(this.memoCache.entries()).sort((a,l)=>a[1].hits-l[1].hits||a[1].timestamp-l[1].timestamp).slice(0,this.memoCache.size-this.MAX_CACHE_SIZE).forEach(([a])=>this.memoCache.delete(a))}async track(s,e,t={}){const r=Z.now();try{const a=t.cacheKey||s;if(t.memoize){const _=this.getMemoized(a);if(_!==void 0)return this.cacheHits++,V.debug("Memoized result used",{operation:s,cacheKey:a,hits:this.cacheHits}),_;this.cacheMisses++}if(t.coalesce){const _=this.pendingRequests.get(s);if(_)return V.debug("Request coalesced",{operation:s}),_}let l;t.coalesce?(l=t.timeout?this.withTimeout(e(),t.timeout):e(),this.pendingRequests.set(s,l)):l=t.timeout?this.withTimeout(e(),t.timeout):e();const o=await l;t.memoize&&this.memoize(a,o);const f=Z.now()-r;return this.recordMetric(s,f,!0,{strategy:t.priority||"normal",memoized:t.memoize||!1,coalesced:t.coalesce||!1}),f>this.TARGET_RESPONSE_TIME&&V.warn("Operation exceeded target time",{operation:s,duration:Math.round(f),target:this.TARGET_RESPONSE_TIME}),o}catch(a){const l=Z.now()-r;throw this.recordMetric(s,l,!1,{error:a instanceof Error?a.message:"Unknown error"}),a}finally{t.coalesce&&this.pendingRequests.delete(s)}}getStats(){if(this.metricsCount===0)return{avgResponseTime:0,p95ResponseTime:0,p99ResponseTime:0,successRate:100,slowOperations:[]};const s=[],e=this.metricsCount<this.MAX_METRICS?0:this.metricsIndex;for(let u=0;u<this.metricsCount;u++){const c=this.metricsBuffer[(e+u)%this.MAX_METRICS];c&&s.push(c)}if(s.length===0)return{avgResponseTime:0,p95ResponseTime:0,p99ResponseTime:0,successRate:100,slowOperations:[]};const t=s.sort((u,c)=>u.duration-c.duration);let r=0,a=0;const l=new Set;for(const u of s)a+=u.duration,u.success&&r++,u.duration>this.TARGET_RESPONSE_TIME&&l.add(u.operation);const o=a/s.length,f=Math.floor(t.length*.95),_=Math.floor(t.length*.99);return{avgResponseTime:Math.round(o),p95ResponseTime:Math.round(t[f]?.duration||0),p99ResponseTime:Math.round(t[_]?.duration||0),successRate:r/s.length*100,slowOperations:Array.from(l)}}getCacheStats(){const s=this.cacheHits+this.cacheMisses;return{size:this.memoCache.size,hitRate:s>0?this.cacheHits/s*100:0,hits:this.cacheHits,misses:this.cacheMisses}}getMemoized(s){const e=this.memoCache.get(s);if(e){if(Date.now()-e.timestamp>this.MEMO_TTL){this.memoCache.delete(s);return}return e.hits++,e.value}}memoize(s,e){const t=JSON.stringify(e).length;this.memoCache.set(s,{value:e,timestamp:Date.now(),hits:0,size:t}),this.memoCache.size>this.MAX_CACHE_SIZE&&this.cleanupCache()}async withTimeout(s,e){return Promise.race([s,new Promise((t,r)=>setTimeout(()=>r(new Error(`Operation timed out after ${e}ms`)),e))])}recordMetric(s,e,t,r){this.metricsBuffer[this.metricsIndex]={operation:s,duration:e,timestamp:Date.now(),success:t,metadata:r},this.metricsIndex=(this.metricsIndex+1)%this.MAX_METRICS,this.metricsCount<this.MAX_METRICS&&this.metricsCount++,e>this.TARGET_RESPONSE_TIME&&V.warn("Slow operation detected",{operation:s,duration:`${e.toFixed(2)}ms`,target:`${this.TARGET_RESPONSE_TIME}ms`,metadata:r})}};E(w,"instance");let te=w;const Qe=te.getInstance(),Ae={AGENT_CREATION:"https://docs.example.com/agent-creation",STREAMING:"https://docs.example.com/streaming-issues",STORAGE:"https://docs.example.com/storage-troubleshooting",MEMORY:"https://docs.example.com/memory-management",PROVIDER:"https://docs.example.com/provider-setup",GENERAL:"https://docs.example.com/help"},J={get AGENT_CREATION_FAILED(){return n.errors_catalog_agentCreationFailed_template({agentName:"{agentName}",details:"{details}"})},get AGENT_ALREADY_EXISTS(){return n.errors_catalog_agentAlreadyExists_template({agentName:"{agentName}"})},get INVALID_AGENT_CONFIG(){return n.errors_catalog_invalidAgentConfig_template({details:"{details}"})},get INVALID_CONFIG(){return n.errors_catalog_invalidConfig_template({details:"{details}"})},get SESSION_NOT_FOUND(){return n.errors_catalog_sessionNotFound_template({sessionId:"{sessionId}"})},get SESSION_ALREADY_ACTIVE(){return n.errors_catalog_sessionAlreadyActive_template()},get SESSION_INITIALIZATION_FAILED(){return n.errors_catalog_sessionInitializationFailed_template({details:"{details}"})},get STREAM_CONNECTION_FAILED(){return n.errors_catalog_streamConnectionFailed_template({details:"{details}"})},get STREAM_TIMEOUT(){return n.errors_catalog_streamTimeout_template({timeout:"{timeout}"})},get STREAM_INTERRUPTED(){return n.errors_catalog_streamInterrupted_template({attempt:"{attempt}",maxAttempts:"{maxAttempts}"})},get STREAM_RECOVERY_FAILED(){return n.errors_catalog_streamRecoveryFailed_template({attempts:"{attempts}"})},get MESSAGE_SEND_FAILED(){return n.errors_catalog_messageSendFailed_template({details:"{details}"})},get MESSAGE_VALIDATION_FAILED(){return n.errors_catalog_messageValidationFailed_template({details:"{details}"})},get MESSAGE_TOO_LONG(){return n.errors_catalog_messageTooLong_template({maxLength:"{maxLength}",currentLength:"{currentLength}"})},get PROVIDER_NOT_FOUND(){return n.errors_catalog_providerNotFound_template({provider:"{provider}"})},get PROVIDER_CONNECTION_FAILED(){return n.errors_catalog_providerConnectionFailed_template({provider:"{provider}",details:"{details}"})},get PROVIDER_PROCESS_DIED(){return n.errors_catalog_providerProcessDied_template({provider:"{provider}"})},get STORAGE_READ_FAILED(){return n.errors_catalog_storageReadFailed_template({details:"{details}"})},get STORAGE_WRITE_FAILED(){return n.errors_catalog_storageWriteFailed_template({details:"{details}"})},get STORAGE_CORRUPTED(){return n.errors_catalog_storageCorrupted_template({lastBackup:"{lastBackup}"})},get MEMORY_LIMIT_EXCEEDED(){return n.errors_catalog_memoryLimitExceeded_template({currentUsage:"{currentUsage}",limit:"{limit}"})},get RATE_LIMIT_EXCEEDED(){return n.errors_catalog_rateLimitExceeded_template({count:"{count}",window:"{window}"})},get CONCURRENT_LIMIT_EXCEEDED(){return n.errors_catalog_concurrentLimitExceeded_template({current:"{current}",max:"{max}"})}},je={get AGENT_CREATION_FAILED(){return n.errors_catalog_agentCreationFailed_friendly()},get AGENT_ALREADY_EXISTS(){return n.errors_catalog_agentAlreadyExists_friendly()},get INVALID_AGENT_CONFIG(){return n.errors_catalog_invalidAgentConfig_friendly()},get INVALID_CONFIG(){return n.errors_catalog_invalidConfig_friendly()},get SESSION_NOT_FOUND(){return n.errors_catalog_sessionNotFound_friendly()},get SESSION_ALREADY_ACTIVE(){return n.errors_catalog_sessionAlreadyActive_friendly()},get SESSION_INITIALIZATION_FAILED(){return n.errors_catalog_sessionInitializationFailed_friendly()},get STREAM_CONNECTION_FAILED(){return n.errors_catalog_streamConnectionFailed_friendly()},get STREAM_TIMEOUT(){return n.errors_catalog_streamTimeout_friendly()},get STREAM_INTERRUPTED(){return n.errors_catalog_streamInterrupted_friendly()},get STREAM_RECOVERY_FAILED(){return n.errors_catalog_streamRecoveryFailed_friendly()},get MESSAGE_SEND_FAILED(){return n.errors_catalog_messageSendFailed_friendly()},get MESSAGE_VALIDATION_FAILED(){return n.errors_catalog_messageValidationFailed_friendly()},get MESSAGE_TOO_LONG(){return n.errors_catalog_messageTooLong_friendly()},get PROVIDER_NOT_FOUND(){return n.errors_catalog_providerNotFound_friendly()},get PROVIDER_CONNECTION_FAILED(){return n.errors_catalog_providerConnectionFailed_friendly()},get PROVIDER_PROCESS_DIED(){return n.errors_catalog_providerProcessDied_friendly()},get STORAGE_READ_FAILED(){return n.errors_catalog_storageReadFailed_friendly()},get STORAGE_WRITE_FAILED(){return n.errors_catalog_storageWriteFailed_friendly()},get STORAGE_CORRUPTED(){return n.errors_catalog_storageCorrupted_friendly()},get MEMORY_LIMIT_EXCEEDED(){return n.errors_catalog_memoryLimitExceeded_friendly()},get RATE_LIMIT_EXCEEDED(){return n.errors_catalog_rateLimitExceeded_friendly()},get CONCURRENT_LIMIT_EXCEEDED(){return n.errors_catalog_concurrentLimitExceeded_friendly()}};function Ze(i){return(i.match(/{(\w+)}/g)||[]).map(e=>e.slice(1,-1))}function Je(i,s){return Ze(i).every(t=>t in s)}function Oe(i,s={}){return i.replace(/{(\w+)}/g,(e,t)=>String(s[t]??e))}function ee(i){const s=n.errors_cleanMessage_fallback_error();if(!i)return s;let e=i;return e=e.replace(/^.*?failed(?:\s+to\s+.*?)?\s+after\s+\d+\s+attempts:\s*/i,""),e=e.replace(/^Error invoking remote method '[^']+':(\s*Error:)?\s*/i,""),e=e.replace(/^(Error:\s*)+/i,""),e=e.replace(/\n\s*at .+/g,""),e=e.replace(/\s+/g," ").trim(),e||s}function et(i,s){return s&&J[i]&&Je(J[i],s)?Oe(J[i],s):je[i]||n.errors_userFriendly_fallback_error()}function tt(i){const e={AGENT_CREATION_FAILED:"AGENT_CREATION",AGENT_ALREADY_EXISTS:"AGENT_CREATION",INVALID_AGENT_CONFIG:"AGENT_CREATION",STREAM_CONNECTION_FAILED:"STREAMING",STREAM_TIMEOUT:"STREAMING",STREAM_INTERRUPTED:"STREAMING",STREAM_RECOVERY_FAILED:"STREAMING",STORAGE_READ_FAILED:"STORAGE",STORAGE_WRITE_FAILED:"STORAGE",STORAGE_CORRUPTED:"STORAGE",MEMORY_LIMIT_EXCEEDED:"MEMORY",RATE_LIMIT_EXCEEDED:"MEMORY",CONCURRENT_LIMIT_EXCEEDED:"MEMORY",PROVIDER_NOT_FOUND:"PROVIDER",PROVIDER_CONNECTION_FAILED:"PROVIDER",PROVIDER_PROCESS_DIED:"PROVIDER"}[i];return e?Ae[e]:Ae.GENERAL}const st={AGENT_CREATION_FAILED:[{action:"retry",description:"Try creating the agent again",automatic:!1,priority:"high"},{action:"check-config",description:"Verify agent configuration in settings",automatic:!1,priority:"high"},{action:"check-resources",description:"Ensure sufficient memory and disk space",automatic:!1,priority:"medium"}],AGENT_ALREADY_EXISTS:[{action:"rename",description:"Choose a different name for the agent",automatic:!1,priority:"high"},{action:"delete-existing",description:"Delete the existing agent first",automatic:!1,priority:"medium"}],INVALID_AGENT_CONFIG:[{action:"review-config",description:"Review and correct the configuration",automatic:!1,priority:"high"},{action:"use-defaults",description:"Reset to default configuration",automatic:!1,priority:"medium"}],INVALID_CONFIG:[{action:"review-config",description:"Review and correct the configuration",automatic:!1,priority:"high"},{action:"use-defaults",description:"Reset to default configuration",automatic:!1,priority:"medium"}],SESSION_NOT_FOUND:[{action:"start-new",description:"Start a new agent session",automatic:!1,priority:"high"},{action:"check-history",description:"Check session history for recent sessions",automatic:!1,priority:"medium"}],SESSION_ALREADY_ACTIVE:[{action:"wait",description:"Wait for the current session to complete",automatic:!1,priority:"high"},{action:"cancel",description:"Cancel the active session first",automatic:!1,priority:"high"}],SESSION_INITIALIZATION_FAILED:[{action:"retry",description:"Try initializing the session again",automatic:!1,priority:"high"},{action:"check-resources",description:"Ensure sufficient resources are available",automatic:!1,priority:"medium"}],MESSAGE_SEND_FAILED:[{action:"retry",description:"Try sending the message again",automatic:!1,priority:"high"},{action:"check-connection",description:"Check your network connection",automatic:!1,priority:"high"}],MESSAGE_VALIDATION_FAILED:[{action:"review-config",description:"Review and correct the message format",automatic:!1,priority:"high"},{action:"check-config",description:"Check configuration for valid message format",automatic:!1,priority:"medium"}],MESSAGE_TOO_LONG:[{action:"retry",description:"Shorten the message and try again",automatic:!1,priority:"high"},{action:"batch",description:"Split the message into multiple parts",automatic:!1,priority:"medium"}],PROVIDER_NOT_FOUND:[{action:"check-config",description:"Verify provider is properly configured",automatic:!1,priority:"high"},{action:"recreate",description:"Install or reinstall the provider",automatic:!1,priority:"high"}],PROVIDER_CONNECTION_FAILED:[{action:"retry",description:"Try connecting to the provider again",automatic:!1,priority:"high"},{action:"check-config",description:"Verify provider configuration",automatic:!1,priority:"high"}],STORAGE_READ_FAILED:[{action:"retry",description:"Try reading the data again",automatic:!1,priority:"high"},{action:"restore",description:"Restore from a recent backup",automatic:!1,priority:"medium"}],STORAGE_WRITE_FAILED:[{action:"retry",description:"Try saving again",automatic:!1,priority:"high"},{action:"check-resources",description:"Check available disk space",automatic:!1,priority:"high"}],STREAM_CONNECTION_FAILED:[{action:"retry",description:"Try connecting again",automatic:!1,priority:"high"},{action:"check-connection",description:"Check your network connection",automatic:!1,priority:"high"}],STREAM_RECOVERY_FAILED:[{action:"restart",description:"Restart the agent",automatic:!1,priority:"high"},{action:"check-config",description:"Check error logs for more details",automatic:!1,priority:"medium"}],STREAM_INTERRUPTED:[{action:"reconnect",description:"Attempting automatic reconnection",automatic:!0,priority:"high"},{action:"retry",description:"Retry sending the message",automatic:!1,priority:"high"},{action:"check-connection",description:"Check your internet connection",automatic:!1,priority:"medium"}],STREAM_TIMEOUT:[{action:"wait",description:"Wait for agent to complete processing",automatic:!1,priority:"high"},{action:"cancel",description:"Cancel current operation",automatic:!1,priority:"medium"},{action:"increase-timeout",description:"Increase timeout in settings",automatic:!1,priority:"low"}],PROVIDER_PROCESS_DIED:[{action:"restart",description:"Restart agent process",automatic:!0,priority:"high"},{action:"recreate",description:"Create new agent session",automatic:!1,priority:"high"}],STORAGE_CORRUPTED:[{action:"restore",description:"Restore from backup",automatic:!1,priority:"high"},{action:"reset",description:"Reset agent data",automatic:!1,priority:"medium"}],MEMORY_LIMIT_EXCEEDED:[{action:"cleanup",description:"Close unused agents",automatic:!1,priority:"high"},{action:"increase-limit",description:"Increase memory limit in settings",automatic:!1,priority:"medium"}],RATE_LIMIT_EXCEEDED:[{action:"wait",description:"Wait before making more requests",automatic:!1,priority:"high"},{action:"batch",description:"Batch requests together",automatic:!1,priority:"medium"}],CONCURRENT_LIMIT_EXCEEDED:[{action:"close-agents",description:"Close some running agents",automatic:!1,priority:"high"},{action:"queue",description:"Queue operation for later",automatic:!1,priority:"medium"}]};function it(i){return st[i]||[{action:"retry",description:"Try the operation again",automatic:!1,priority:"high"}]}var N=(i=>(i.AGENT_CREATION_FAILED="AGENT_CREATION_FAILED",i.AGENT_ALREADY_EXISTS="AGENT_ALREADY_EXISTS",i.INVALID_AGENT_CONFIG="INVALID_AGENT_CONFIG",i.INVALID_CONFIG="INVALID_CONFIG",i.SESSION_NOT_FOUND="SESSION_NOT_FOUND",i.SESSION_ALREADY_ACTIVE="SESSION_ALREADY_ACTIVE",i.SESSION_INITIALIZATION_FAILED="SESSION_INITIALIZATION_FAILED",i.STREAM_CONNECTION_FAILED="STREAM_CONNECTION_FAILED",i.STREAM_TIMEOUT="STREAM_TIMEOUT",i.STREAM_INTERRUPTED="STREAM_INTERRUPTED",i.STREAM_RECOVERY_FAILED="STREAM_RECOVERY_FAILED",i.MESSAGE_SEND_FAILED="MESSAGE_SEND_FAILED",i.MESSAGE_VALIDATION_FAILED="MESSAGE_VALIDATION_FAILED",i.MESSAGE_TOO_LONG="MESSAGE_TOO_LONG",i.PROVIDER_NOT_FOUND="PROVIDER_NOT_FOUND",i.PROVIDER_CONNECTION_FAILED="PROVIDER_CONNECTION_FAILED",i.PROVIDER_PROCESS_DIED="PROVIDER_PROCESS_DIED",i.PROVIDER_UNAVAILABLE="PROVIDER_UNAVAILABLE",i.PROVIDER_ERROR="PROVIDER_ERROR",i.STORAGE_READ_FAILED="STORAGE_READ_FAILED",i.STORAGE_WRITE_FAILED="STORAGE_WRITE_FAILED",i.STORAGE_CORRUPTED="STORAGE_CORRUPTED",i.STORAGE_ERROR="STORAGE_ERROR",i.STORAGE_QUOTA_EXCEEDED="STORAGE_QUOTA_EXCEEDED",i.MEMORY_LIMIT_EXCEEDED="MEMORY_LIMIT_EXCEEDED",i.RATE_LIMIT_EXCEEDED="RATE_LIMIT_EXCEEDED",i.CONCURRENT_LIMIT_EXCEEDED="CONCURRENT_LIMIT_EXCEEDED",i.RESOURCE_NOT_FOUND="RESOURCE_NOT_FOUND",i.RESOURCE_EXHAUSTED="RESOURCE_EXHAUSTED",i.NETWORK_ERROR="NETWORK_ERROR",i.PERMISSION_DENIED="PERMISSION_DENIED",i.OPERATION_FAILED="OPERATION_FAILED",i.VALIDATION_ERROR="VALIDATION_ERROR",i.INVALID_RESPONSE="INVALID_RESPONSE",i.STATE_CORRUPTION="STATE_CORRUPTION",i.CONTEXT_OVERFLOW="CONTEXT_OVERFLOW",i))(N||{});class q extends Error{constructor(e,t,r={},a){super(e);E(this,"code");E(this,"context");E(this,"recoverySuggestions");E(this,"userMessage");E(this,"isRecoverable");E(this,"cause");this.name="AgentError",this.code=t,this.context={...r,timestamp:new Date,stackTrace:this.stack},this.userMessage=a?.userMessage||this.getDefaultUserMessage(t),this.recoverySuggestions=a?.recoverySuggestions||this.getDefaultRecoverySuggestions(t),this.isRecoverable=a?.isRecoverable??this.isErrorRecoverable(t),a?.cause&&(this.cause=a.cause)}getDefaultUserMessage(e){return et(e,this.context)}getDefaultRecoverySuggestions(e){return it(e)}isErrorRecoverable(e){return["STREAM_INTERRUPTED","STREAM_TIMEOUT","MESSAGE_SEND_FAILED","PROVIDER_PROCESS_DIED","STORAGE_READ_FAILED","STORAGE_WRITE_FAILED"].includes(e)}getHelpLink(){return tt(this.code)}formatMessage(e){return Oe(e,this.context)}toJSON(){return{name:this.name,code:this.code,message:this.message,userMessage:this.userMessage,context:this.context,recoverySuggestions:this.recoverySuggestions,isRecoverable:this.isRecoverable,helpLink:this.getHelpLink(),stack:this.stack}}}const rt={NON_RETRYABLE_ERRORS:["EACCES","EPERM","ENOSPC","EMFILE","permission","memory","fatal","process died","not available on your current plan","agent binary","rate limit","too many requests","hit your limit","you've hit your limit","quota exceeded"]};function re(i){const s=i.toLowerCase();for(const e of rt.NON_RETRYABLE_ERRORS)if(s.includes(e.toLowerCase()))return!0;return!1}const at="Agent already has an in-flight prompt. Message was not delivered.",v=W("ErrorBoundary"),b=class b{constructor(){}static getInstance(){return b.instance||(b.instance=new b),b.instance}async wrap(s,e,t={}){const{retries:r=pe.DEFAULT_ATTEMPTS,retryDelay:a=pe.BASE_DELAY,exponentialBackoff:l=!0,notify:o=!1,notifyOnRetry:f=!1,context:_={},onError:u,onRetry:c,shouldRetry:R=this.defaultShouldRetry}=t;let g=null,d=0;for(d=1;d<=r+1;d++)try{v.debug(`[${e}] Attempt ${d}/${r+1}`);const C=await s();return d>1&&v.info(`[${e}] Succeeded after ${d} attempts`),C}catch(C){if(g=C,v.error(`[${e}] Attempt ${d} failed`,{error:g.message,attempt:d,maxAttempts:r+1,context:_}),u?.(g,d),d<=r&&R(g)){const h=l?a*Math.pow(2,d-1):a;f&&j.warning(n.agent_errorBoundary_retrying_message({seconds:h/1e3})),c?.(d),v.info(`[${e}] Retrying in ${h}ms`),await this.sleep(h)}else break}const k=`${e} failed after ${d} attempt${d===1?"":"s"}: ${g?.message}`,P=ee(g?.message||n.agent_errorBoundary_generic_error()),D=g?.message?.toLowerCase()||"",$=D.includes("no available models")||D.includes("all models exhausted")||D.includes("all models unavailable");throw o&&!$&&j.error(P),new q(P,N.OPERATION_FAILED,{originalError:g?.message,detailedMessage:k,attempts:d,context:_})}async wrapVoid(s,e,t={}){await this.wrap(s,e,t)}wrapSync(s,e,t={}){try{return s()}catch(r){const a=r;throw v.error(`[${e}] Failed`,{error:a.message,context:t.context}),t.notify&&j.error(ee(a.message)),new q(ee(a.message),N.OPERATION_FAILED,t.context)}}defaultShouldRetry(s){const e=s.message.toLowerCase();return re(s.message)?!1:e.includes("network")||e.includes("timeout")?!0:s instanceof q?[N.NETWORK_ERROR,N.STREAM_TIMEOUT,N.STREAM_CONNECTION_FAILED,N.PROVIDER_CONNECTION_FAILED,N.PROVIDER_UNAVAILABLE].includes(s.code):!(e.includes("invalid")||e.includes("interrupted")||e.includes("cancel")||e.includes("not found")||e.includes("not available")||e.includes("404")||e.includes("no available models")||e.includes("all models exhausted")||e.includes("all models unavailable")||e.includes("413")||e.includes("too long for the agent")||e.includes("request entity too large")||e.includes("payload too large")||e.includes("content too large")||e.includes("body too large")||e.includes("unauthorized")||e.includes("forbidden")||e.includes("401")||e.includes("403"))}sleep(s){return new Promise(e=>setTimeout(e,s))}async withTimeout(s,e,t){return Promise.race([s(),new Promise((r,a)=>setTimeout(()=>a(new q(`${t} timed out after ${e}ms`,N.STREAM_TIMEOUT)),e))])}async batchOperations(s,e,t={}){const{concurrency:r=5,continueOnError:a=!0,operationName:l="batch operation"}=t,o=[],f=[];for(let _=0;_<s.length;_+=r){const u=s.slice(_,_+r);(await Promise.allSettled(u.map(R=>e(R)))).forEach((R,g)=>{if(R.status==="fulfilled")o.push(R.value);else{const d=R.reason;if(f.push({item:u[g],error:d}),v.error(`[${l}] Batch item failed`,{item:u[g],error:d.message}),!a)throw d}})}return f.length>0&&v.warn(`[${l}] Completed with ${f.length} errors`),{results:o,errors:f}}};E(b,"instance");let se=b;const nt=se.getInstance(),ie=W("browser/index"),F=new Map,B=new Map;let U;function ot(i,s,e){for(const t of s)try{t(e)}catch(r){ie.error("Error in agent subscriber callback",{agentId:i,error:r})}}function ct(){if(U)return;let i=!1;U=p.createSelector(e=>e.agentSessions)().subscribe(()=>{if(!i){i=!0;return}if(F.size===0)return;const e=p.state;for(const[t,r]of F){const a=Se.select(e,t);B.get(t)!==a&&(B.set(t,a),ot(t,r,a))}})}function lt(){F.size>0||!U||(U(),U=void 0,B.clear())}function Ft(i,s,e){let t=F.get(i);const r=!t;t||(t=new Set,F.set(i,t)),t.add(s),ct();const a=p.state,l=Se.select(a,i);return r&&B.set(i,l),l?ie.debug("[subscribeToAgent] Initial callback data",{agentId:i,workspaceId:e??"current",hasSession:!0}):ie.debug("[subscribeToAgent] No session found",{agentId:i,workspaceId:e??"current"}),s(l),()=>{const o=F.get(i);o&&(o.delete(s),o.size===0&&(F.delete(i),B.delete(i))),lt()}}const y=W("ErrorRecovery"),ye={network:{maxRetries:3,initialBackoffMs:1e3,maxBackoffMs:1e4,backoffMultiplier:2,shouldRetry:i=>{const s=i.message.toLowerCase();return s.includes("network")||s.includes("fetch")||s.includes("connection")||s.includes("timeout")}},streaming:{maxRetries:5,initialBackoffMs:500,maxBackoffMs:5e3,backoffMultiplier:1.5,shouldRetry:(i,s)=>{if(s>=5)return!1;const e=i.message.toLowerCase();return e.includes("no available models")||e.includes("all models exhausted")||e.includes("all models unavailable")||re(i.message)?!1:e.includes("stream")||e.includes("chunk")||e.includes("incomplete")}},persistence:{maxRetries:2,initialBackoffMs:100,maxBackoffMs:1e3,backoffMultiplier:2,shouldRetry:i=>{const s=i.message.toLowerCase();return s.includes("save")||s.includes("write")||s.includes("persist")}},rateLimit:{maxRetries:3,initialBackoffMs:5e3,maxBackoffMs:3e4,backoffMultiplier:2,shouldRetry:i=>{const s=i.message.toLowerCase();return s.includes("rate")||s.includes("limit")||s.includes("429")}}};class ut{constructor(){E(this,"listeners",new Map)}on(s,e){let t=this.listeners.get(s);t||(t=new Set,this.listeners.set(s,t)),t.add(e)}off(s,e){this.listeners.get(s)?.delete(e)}emit(s,...e){this.listeners.get(s)?.forEach(t=>{try{t(...e)}catch(r){y.error(`Error in event listener for ${s}:`,r)}})}removeAllListeners(){this.listeners.clear()}}class dt extends ut{constructor(){super(...arguments);E(this,"activeRecoveries",new Map);E(this,"recoveryStats",new Map)}async executeWithRecovery(e,t=ye.network,r){const a=Date.now(),l=new AbortController;r&&(this.cancelRecovery(r),this.activeRecoveries.set(r,l));let o,f=t.initialBackoffMs,_=0;for(let u=1;u<=t.maxRetries;u++){if(_=u,l.signal.aborted){y.info(`Recovery cancelled for operation ${r}`);break}try{y.debug(`Attempting operation (attempt ${u}/${t.maxRetries})`,{operationId:r});const c=await e();return this.updateStats(r,!0),this.emit("recovery:success",{operationId:r,attempt:u,duration:Date.now()-a}),r&&this.activeRecoveries.delete(r),{success:!0,data:c,attempts:u,totalTime:Date.now()-a}}catch(c){o=c,y.warn(`Operation failed (attempt ${u}/${t.maxRetries})`,{operationId:r,error:o.message});const R=o.message.toLowerCase();if(R.includes("interrupted")||R.includes("cancelled")||R.includes("canceled")){y.debug("User-initiated interruption/cancellation, not retrying",{operationId:r,error:o.message});break}if(R.includes("no available models")||R.includes("all models exhausted")||R.includes("all models unavailable")){y.debug("All models exhausted, not retrying",{operationId:r,error:o.message});break}if(re(o.message)){y.debug("Fatal error detected, not retrying",{operationId:r,error:o.message});break}if(!t.shouldRetry(o,u)){y.debug("Error not retryable, stopping recovery",{operationId:r,error:o.message});break}if(u<t.maxRetries){const g=Math.random()*.2*f,d=Math.min(f+g,t.maxBackoffMs);t.onRetry?.(u,d),this.emit("recovery:retry",{operationId:r,attempt:u,delay:d,error:o.message}),await this.delay(d,l.signal),f=Math.min(f*t.backoffMultiplier,t.maxBackoffMs)}}}return this.updateStats(r,!1),t.onFailure?.(o,_),this.emit("recovery:failure",{operationId:r,attempts:_,duration:Date.now()-a,error:o?.message}),r&&this.activeRecoveries.delete(r),{success:!1,error:o,attempts:_,totalTime:Date.now()-a}}cancelRecovery(e){const t=this.activeRecoveries.get(e);t&&(t.abort(),this.activeRecoveries.delete(e),y.info(`Cancelled recovery for operation ${e}`))}cancelAllRecoveries(){for(const[e,t]of this.activeRecoveries)t.abort(),y.info(`Cancelled recovery for operation ${e}`);this.activeRecoveries.clear()}getStats(e){if(e)return this.recoveryStats.get(e)||{successes:0,failures:0};const t={};for(const[r,a]of this.recoveryStats)t[r]=a;return t}clearStats(e){e?this.recoveryStats.delete(e):this.recoveryStats.clear()}isRetryable(e,t){const r=e.message.toLowerCase();if(t)switch(t){case"NETWORK":return r.includes("network")||r.includes("fetch");case"TIMEOUT":return r.includes("timeout")||r.includes("timed out");case"RATE_LIMIT":return r.includes("rate")||r.includes("limit")||r.includes("429");case"TEMPORARY":return r.includes("temporary")||r.includes("transient");case"CONFLICT":return r.includes("conflict")||r.includes("concurrent");default:return!1}return this.isRetryable(e,"NETWORK")||this.isRetryable(e,"TIMEOUT")||this.isRetryable(e,"RATE_LIMIT")||this.isRetryable(e,"TEMPORARY")||this.isRetryable(e,"CONFLICT")}delay(e,t){return new Promise((r,a)=>{const l=setTimeout(r,e);if(t){const o=()=>{clearTimeout(l),a(new Error("Delay aborted"))};t.addEventListener("abort",o);const f=r;r=()=>{t.removeEventListener("abort",o),f()}}})}updateStats(e,t){if(!e)return;const r=this.recoveryStats.get(e)||{successes:0,failures:0};t?r.successes++:r.failures++,this.recoveryStats.set(e,r)}dispose(){this.cancelAllRecoveries(),this.recoveryStats.clear(),this.removeAllListeners()}}const mt=new dt,O=new Ye({category:"WorkspaceMetrics"}),Et=100;class ft{constructor(){E(this,"metrics",new Map);E(this,"operations",new Map)}startWorkspaceCreation(s){const e=Date.now();for(this.metrics.delete(s),this.metrics.set(s,{workspaceId:s,creationStarted:e});this.metrics.size>Et;){const t=this.metrics.keys().next().value;if(t===void 0)break;this.metrics.delete(t)}O.info("Started tracking workspace creation",{workspaceId:s})}recordMilestone(s,e){const t=this.metrics.get(s);if(!t){O.warn("No metrics found for workspace",{workspaceId:s,milestone:e});return}const r=Date.now();switch(e){case"optimisticNavigation":t.optimisticNavigation=r;break;case"realWorkspaceCreated":t.realWorkspaceCreated=r;break;case"agentCreated":t.agentCreated=r;break;case"agentReady":t.agentReady=r;break;case"firstMessageSent":t.firstMessageSent=r;break;case"firstResponseReceived":t.firstResponseReceived=r;break;case"firstChunkReceived":t.firstChunkReceived=r;break;case"totalDuration":t.totalDuration=r;break;case"workspaceId":case"creationStarted":O.warn("Cannot update milestone",{milestone:e});return}const a=r-t.creationStarted;O.info(`Milestone: ${e}`,{workspaceId:s,elapsed:`${a}ms`,timestamp:r}),e==="firstResponseReceived"&&(t.totalDuration=r-t.creationStarted,this.logSummary(s))}startOperation(s,e){this.operations.set(s,{startTime:Date.now(),metadata:e})}endOperation(s,e){const t=this.operations.get(s);if(!t)return O.warn("Operation not found",{operationId:s}),null;const r=Date.now();return t.endTime=r,t.duration=r-t.startTime,e&&(t.metadata={...t.metadata,...e}),O.info("Operation completed",{operationId:s,duration:`${t.duration}ms`,metadata:t.metadata}),this.operations.delete(s),t.duration}getMetrics(s){return this.metrics.get(s)}logSummary(s){const e=this.metrics.get(s);if(!e)return;const t={workspaceId:s,totalDuration:`${e.totalDuration}ms`,stages:{optimisticNavigation:e.optimisticNavigation?`${e.optimisticNavigation-e.creationStarted}ms`:"N/A",realWorkspaceCreation:e.realWorkspaceCreated?`${e.realWorkspaceCreated-e.creationStarted}ms`:"N/A",agentCreation:e.agentCreated?`${e.agentCreated-e.creationStarted}ms`:"N/A",agentReady:e.agentReady?`${e.agentReady-e.creationStarted}ms`:"N/A",firstMessage:e.firstMessageSent?`${e.firstMessageSent-e.creationStarted}ms`:"N/A",firstResponse:e.firstResponseReceived?`${e.firstResponseReceived-e.creationStarted}ms`:"N/A"}};O.info("=== Workspace Creation Metrics Summary ===",t),O.info("Workspace Creation Metrics:",t)}clearMetrics(s){this.metrics.delete(s)}incrementAgentCreated(s){const e=this.metrics.get(s);e&&(e.agentCreated=Date.now(),O.info("Agent created",{workspaceId:s}))}incrementMessageSent(s){const e=this.metrics.get(s);e&&!e.firstMessageSent&&(e.firstMessageSent=Date.now(),O.info("First message sent",{workspaceId:s}))}}const _t=new ft,M=W("AgentSend");function A(i){p.dispatch(i)}function Ie(i){return typeof i=="object"&&i!==null&&!Array.isArray(i)}function ht(i){const s=Ie(i)&&i.success===!0&&"data"in i?i.data:i;return!Ie(s)||s.success!==!1?!1:typeof s.error=="string"&&s.error.includes(at)}async function kt(i,s,e,t={}){const r=ge.select(p.state,e.id);if(!r)return;const a=Le(i,e.id),l=t.submission,o=!!l&&we.select(p.state,l.scope)?.supported===!0,f=(c,R,g=!1)=>{l&&A(Xe(l.scope,l.id,c,Date.now(),R,g))};let _=!1;const u=()=>(!l||_||be.select(p.state,l))&&r===ge.select(p.state,e.id)&&a.isCurrent(p.state.agentSessions?.byAgentId[i]?.workspaceId);return Qe.track(`sendMessage:${a.key}:${i}:${l?.id??"legacy"}`,async()=>{if(!u())return;M.debug(`Sending message to agent ${i}`,{contentLength:s.length,hasContextReferences:!!t.contextReferences?.length,model:t.model});let c=await p.dispatch(Fe(e.id,i));if(u()){if(!c)throw new Error(n.agent_streamLifecycle_sessionNotFound_error({agentId:i}));c={...c,isStreaming:c.isStreaming??!1};{if(c&&(c.status==="pending"||!c.id)&&!c.backendSessionId&&c.activationState!==K.ACTIVE&&c.activationState!==K.ACTIVATING){const h=e.id.startsWith("optimistic-"),Y=e.worktreePath||e.repositoryPath||e.path;if(!h&&Y){M.info("Activating pending session in sendMessage",{agentId:i,status:c.status,activationState:c.activationState,hasBackendSessionId:!!c.backendSessionId});const x=await p.dispatch(ke(e.id,i));if(!u())return;x&&(c=x)}else throw M.warn("Cannot activate agent - workspace not ready",{agentId:i,workspaceId:e.id,isOptimistic:h,hasWorktreePath:!!e.worktreePath,hasRepositoryPath:!!e.repositoryPath,hasPath:!!e.path}),new Error(n.agent_streamLifecycle_spaceNotReady_error())}else c&&c.status==="pending"&&c.backendSessionId&&(M.info("Fixing status for already-activated session",{agentId:i,backendSessionId:c.backendSessionId,activationState:c.activationState}),c={...c,status:Ge.Active,activationState:K.ACTIVE},A(me({...c,workspaceId:e.id})));if(!c)throw new Error(`Failed to get or create session for agent ${i}`);A(me({...c,workspaceId:e.id}));const g=[{type:"text",text:s}];if(t.imageBlocks)for(const h of t.imageBlocks)g.push({type:"image",...h.data!==void 0?{data:h.data}:{},...h.mimeType!==void 0?{mimeType:h.mimeType}:{},...h.attachmentId!==void 0?{attachmentId:h.attachmentId}:{}});if(t.fileBlocks)for(const h of t.fileBlocks)g.push({type:"file",attachmentId:h.attachmentId,fileName:h.fileName,...h.mimeType!==void 0?{mimeType:h.mimeType}:{},...h.size!==void 0?{size:h.size}:{}});const d=t.userAppMessageId??ce(),k=t.messageMetadata?.[Re],P={...t.contextReferences?.length?{contextReferences:t.contextReferences}:{},...k!==void 0?{[Re]:k}:{}},D={id:Ee(ue()),appMessageId:d,role:"user",contentBlocks:g,timestamp:new Date().toISOString(),metadata:{...P,...t.messageMetadata??{}}};o||(l&&(f("rejected"),_=!0),A(Pe(c.id,D))),A(H(c.id,!0));let $=!1,C;try{o||await p.dispatch(xe(e.id,i,!0,{allowTruncation:t.resetHistory}));const h=Ee(`msg_${ue()}`),Y=ce(),x=async()=>nt.wrap(async()=>{if(!u())return;M.info("Agent Service: Sending message to backend with image and file blocks",{agentId:i,sessionId:c.id,hasImageBlocks:!!t.imageBlocks,imageBlocksCount:t.imageBlocks?.length||0,imageBlockDetails:t.imageBlocks?.map(m=>({type:m.type,mimeType:m.mimeType,dataLength:m.data?.length||0}))||[],hasFileBlocks:!!t.fileBlocks,fileBlocksCount:t.fileBlocks?.length||0,fileBlockDetails:t.fileBlocks?.map(m=>({type:m.type,fileName:m.fileName,mimeType:m.mimeType,attachmentId:m.attachmentId,size:m.size}))||[]});const Me=t.model??t.modelId??c.model??void 0;A(Ve(i));const Ne=le(i,e.id),ne=p.state.chatState?.byAgentId[i]?.attemptGeneration??0,T=await qe("agent.sendMessage",{agentId:i,...o&&l?{messageId:l.id}:{},workspaceId:e.id,content:s,model:Me,contextReferences:t.contextReferences,imageBlocks:t.imageBlocks,fileBlocks:t.fileBlocks,noteIds:t.noteIds,stdinContext:t.stdinContext,assistantMessageId:h,userAppMessageId:d,assistantAppMessageId:Y,priority:t.priority,...t.messageMetadata?{messageMetadata:t.messageMetadata}:{}}).catch(m=>{if(u())throw Ke(m)&&(C=m),m});if(u()){if(ht(T)){M.info("Backend dropped duplicate in-flight prompt",{agentId:i,sessionId:c.id}),f("rejected");return}if(T&&typeof T=="object"&&"success"in T){if(!T.success){const m=T.error,I=typeof m=="string"?m:m?.message;throw $=!0,new Error(I||n.agent_streamLifecycle_sendToBackendFailed_error())}if("queued"in T&&T.queued===!0){if(M.info("sendMessage auto-queued by daemon (mid-turn or turn-startup race)",{agentId:i,sessionId:c.id,queuedMessageId:T.queuedMessage?.id}),(!o||!l||!de.select(p.state,l))&&A(H(c.id,!1)),o||A(Ue(c.id,D.id)),o){const I=T.queuedMessage,G=T.turnId,L=typeof G=="string"?G:I?.turnId;if(I&&typeof L=="string"){const S=fe(s,t),X=Q.select(p.state,i,e.id).find(oe=>oe.id===I.id||oe.turnId===L);A(_e(i,I.id,S,L,he(X??I,S),!X&&!!l&&de.select(p.state,l),ne))}f("accepted",I,!0),z(i,e.id);return}const m=T.queuedMessage;if(m){const I=T.turnId,G=typeof I=="string"?I:m.turnId;let L=m;if(u()&&le(i,e.id)===Ne){const S=Q.select(p.state,i,e.id),X=ze(S,m);A(Be(i,X,e.id))}else u()&&(M.debug("queued-response queue seed superseded by an authoritative snapshot; reconciling via hydrate",{agentId:i,queuedMessageId:m.id}),await z(i,e.id).catch(()=>{}),L=Q.select(p.state,i,e.id).find(S=>S.id===m.id||S.turnId===G));if(u()&&typeof G=="string"){const S=fe(s,t);A(_e(i,m.id,S,G,he(L??m,S),!L,ne))}else u()&&M.warn("auto-queued sendMessage response carried no turnId; retry record not parked",{agentId:i,queuedMessageId:m.id})}return}}o&&(f("accepted"),z(i,e.id),ve(i,e.id)),_t.incrementMessageSent(e.id)}},"send message",{retries:o?0:2,notify:!1,context:{agentId:i,workspace:e.id}}),ae=o?await x().then(()=>({success:!0,error:void 0})):await mt.executeWithRecovery(x,ye.streaming,`send-message-${i}`);if(!ae.success)throw ae.error||new Error(n.agent_streamLifecycle_sendFailed_error())}catch(h){if(!u())return;throw A(H(c.id,!1)),!o&&t.messageMetadata&&A($e(c.id,D.id,{metadata:P})),o&&f($||C?"rejected":"uncertain"),C??h}}}},{memoize:!1,coalesce:!0,priority:"high"})}export{Te as U,Ft as a,ee as c,ze as r,kt as s,Ke as u,bt as w};
1
+ var De=Object.defineProperty;var Ce=(i,s,e)=>s in i?De(i,s,{enumerable:!0,configurable:!0,writable:!0,value:e}):i[s]=e;var E=(i,s,e)=>Ce(i,typeof s!="symbol"?s+"":s,e);import{K as Le,P as ce,a6 as le,as as z,aC as ve}from"./8ysnd5N8.js";import{b_ as we,c$ as ue,cr as de,cq as be}from"./BMHxxfP4.js";import{JH as p,Cg as Fe,bJ as ke,i as Ge,LM as me,ir as Ee,bV as Pe,Ec as H,CF as xe,fl as Ve,AL as Ue,e3 as fe,fh as _e,e2 as he,Be,Lq as $e,wy as Xe}from"./D0qhIm1r.js";import{aO as Se,dX as ge,A as K,P as Re,aK as Q}from"./cD292w1o.js";import{h as qe}from"./BAtAwQ72.js";import{c as W}from"./ChTqQfQN.js";import{a as We}from"./BdWqymET.js";import{m as j}from"./DkQdSPDN.js";import"./3SdAC2_C.js";import{bm as n}from"./Fcr7AvC-.js";import"./BRCr02in.js";import"./CWfjuhY2.js";import"./DRMe5Ypb.js";import{R as pe}from"./B5aYN90J.js";import{L as Ye}from"./CSiaiLHL.js";function ze(i,s){return i.some(e=>e.id===s.id)?i.map(e=>e.id===s.id?{...s,...s.author==null&&e.author!==void 0?{author:e.author}:{}}:e):[...i,s]}const Te="confirmUnslothModelSwitch";function He(i){if(!i||typeof i!="object")return!1;const{agentId:s,agentName:e,workspaceId:t,workspaceTitle:r}=i;return typeof s=="string"&&typeof e=="string"&&typeof t=="string"&&(r===null||typeof r=="string")}function Ke(i){for(let s=i,e=0;s&&e<4;e++){const t=s.data;if(t&&typeof t=="object"){const{code:r,currentModel:a,requestedModel:l,agents:o}=t;if(r==="unsloth-model-switch-confirmation-required"&&typeof a=="string"&&typeof l=="string"&&Array.isArray(o)&&o.every(He))return{currentModel:a,requestedModel:l,agents:o}}s=s.cause}}function bt(i){if(!i||!(Te in i))return i;const{[Te]:s,...e}=i;return Object.keys(e).length>0?e:void 0}const Z=typeof performance<"u"?performance:{now:()=>Date.now()},V=new We("PerformanceOptimizer"),w=class w{constructor(){E(this,"metricsBuffer");E(this,"metricsIndex",0);E(this,"metricsCount",0);E(this,"MAX_METRICS",500);E(this,"TARGET_RESPONSE_TIME",100);E(this,"memoCache",new Map);E(this,"MEMO_TTL",6e4);E(this,"MAX_CACHE_SIZE",100);E(this,"cacheHits",0);E(this,"cacheMisses",0);E(this,"pendingRequests",new Map);E(this,"requestQueue",[]);E(this,"cleanupInterval",null);this.metricsBuffer=new Array(this.MAX_METRICS).fill(null),this.startCacheCleanup(),V.info("PerformanceOptimizer initialized")}static getInstance(){return w.instance||(w.instance=new w),w.instance}reset(){this.metricsBuffer=new Array(this.MAX_METRICS).fill(null),this.metricsIndex=0,this.metricsCount=0,this.memoCache.clear(),this.pendingRequests.clear(),this.requestQueue=[],this.cacheHits=0,this.cacheMisses=0}clearCache(){this.memoCache.clear(),this.cacheHits=0,this.cacheMisses=0}async processBatch(s,e,t={}){const{batchSize:r=10,concurrency:a=4}=t,l=[];for(let o=0;o<s.length;o+=r){const _=s.slice(o,o+r).map((c,R)=>{const g=Math.floor(R/a)*10;return new Promise(d=>{setTimeout(async()=>{const k=await e(c);d(k)},g)})}),u=await Promise.all(_);l.push(...u)}return l}startCacheCleanup(){this.cleanupInterval=setInterval(()=>{this.cleanupCache()},3e4)}stopCacheCleanup(){this.cleanupInterval&&(clearInterval(this.cleanupInterval),this.cleanupInterval=null)}cleanupCache(){const s=Date.now(),e=[];this.memoCache.forEach((t,r)=>{s-t.timestamp>this.MEMO_TTL&&e.push(r)}),e.forEach(t=>this.memoCache.delete(t)),this.memoCache.size>this.MAX_CACHE_SIZE&&Array.from(this.memoCache.entries()).sort((a,l)=>a[1].hits-l[1].hits||a[1].timestamp-l[1].timestamp).slice(0,this.memoCache.size-this.MAX_CACHE_SIZE).forEach(([a])=>this.memoCache.delete(a))}async track(s,e,t={}){const r=Z.now();try{const a=t.cacheKey||s;if(t.memoize){const _=this.getMemoized(a);if(_!==void 0)return this.cacheHits++,V.debug("Memoized result used",{operation:s,cacheKey:a,hits:this.cacheHits}),_;this.cacheMisses++}if(t.coalesce){const _=this.pendingRequests.get(s);if(_)return V.debug("Request coalesced",{operation:s}),_}let l;t.coalesce?(l=t.timeout?this.withTimeout(e(),t.timeout):e(),this.pendingRequests.set(s,l)):l=t.timeout?this.withTimeout(e(),t.timeout):e();const o=await l;t.memoize&&this.memoize(a,o);const f=Z.now()-r;return this.recordMetric(s,f,!0,{strategy:t.priority||"normal",memoized:t.memoize||!1,coalesced:t.coalesce||!1}),f>this.TARGET_RESPONSE_TIME&&V.warn("Operation exceeded target time",{operation:s,duration:Math.round(f),target:this.TARGET_RESPONSE_TIME}),o}catch(a){const l=Z.now()-r;throw this.recordMetric(s,l,!1,{error:a instanceof Error?a.message:"Unknown error"}),a}finally{t.coalesce&&this.pendingRequests.delete(s)}}getStats(){if(this.metricsCount===0)return{avgResponseTime:0,p95ResponseTime:0,p99ResponseTime:0,successRate:100,slowOperations:[]};const s=[],e=this.metricsCount<this.MAX_METRICS?0:this.metricsIndex;for(let u=0;u<this.metricsCount;u++){const c=this.metricsBuffer[(e+u)%this.MAX_METRICS];c&&s.push(c)}if(s.length===0)return{avgResponseTime:0,p95ResponseTime:0,p99ResponseTime:0,successRate:100,slowOperations:[]};const t=s.sort((u,c)=>u.duration-c.duration);let r=0,a=0;const l=new Set;for(const u of s)a+=u.duration,u.success&&r++,u.duration>this.TARGET_RESPONSE_TIME&&l.add(u.operation);const o=a/s.length,f=Math.floor(t.length*.95),_=Math.floor(t.length*.99);return{avgResponseTime:Math.round(o),p95ResponseTime:Math.round(t[f]?.duration||0),p99ResponseTime:Math.round(t[_]?.duration||0),successRate:r/s.length*100,slowOperations:Array.from(l)}}getCacheStats(){const s=this.cacheHits+this.cacheMisses;return{size:this.memoCache.size,hitRate:s>0?this.cacheHits/s*100:0,hits:this.cacheHits,misses:this.cacheMisses}}getMemoized(s){const e=this.memoCache.get(s);if(e){if(Date.now()-e.timestamp>this.MEMO_TTL){this.memoCache.delete(s);return}return e.hits++,e.value}}memoize(s,e){const t=JSON.stringify(e).length;this.memoCache.set(s,{value:e,timestamp:Date.now(),hits:0,size:t}),this.memoCache.size>this.MAX_CACHE_SIZE&&this.cleanupCache()}async withTimeout(s,e){return Promise.race([s,new Promise((t,r)=>setTimeout(()=>r(new Error(`Operation timed out after ${e}ms`)),e))])}recordMetric(s,e,t,r){this.metricsBuffer[this.metricsIndex]={operation:s,duration:e,timestamp:Date.now(),success:t,metadata:r},this.metricsIndex=(this.metricsIndex+1)%this.MAX_METRICS,this.metricsCount<this.MAX_METRICS&&this.metricsCount++,e>this.TARGET_RESPONSE_TIME&&V.warn("Slow operation detected",{operation:s,duration:`${e.toFixed(2)}ms`,target:`${this.TARGET_RESPONSE_TIME}ms`,metadata:r})}};E(w,"instance");let te=w;const Qe=te.getInstance(),Ae={AGENT_CREATION:"https://docs.example.com/agent-creation",STREAMING:"https://docs.example.com/streaming-issues",STORAGE:"https://docs.example.com/storage-troubleshooting",MEMORY:"https://docs.example.com/memory-management",PROVIDER:"https://docs.example.com/provider-setup",GENERAL:"https://docs.example.com/help"},J={get AGENT_CREATION_FAILED(){return n.errors_catalog_agentCreationFailed_template({agentName:"{agentName}",details:"{details}"})},get AGENT_ALREADY_EXISTS(){return n.errors_catalog_agentAlreadyExists_template({agentName:"{agentName}"})},get INVALID_AGENT_CONFIG(){return n.errors_catalog_invalidAgentConfig_template({details:"{details}"})},get INVALID_CONFIG(){return n.errors_catalog_invalidConfig_template({details:"{details}"})},get SESSION_NOT_FOUND(){return n.errors_catalog_sessionNotFound_template({sessionId:"{sessionId}"})},get SESSION_ALREADY_ACTIVE(){return n.errors_catalog_sessionAlreadyActive_template()},get SESSION_INITIALIZATION_FAILED(){return n.errors_catalog_sessionInitializationFailed_template({details:"{details}"})},get STREAM_CONNECTION_FAILED(){return n.errors_catalog_streamConnectionFailed_template({details:"{details}"})},get STREAM_TIMEOUT(){return n.errors_catalog_streamTimeout_template({timeout:"{timeout}"})},get STREAM_INTERRUPTED(){return n.errors_catalog_streamInterrupted_template({attempt:"{attempt}",maxAttempts:"{maxAttempts}"})},get STREAM_RECOVERY_FAILED(){return n.errors_catalog_streamRecoveryFailed_template({attempts:"{attempts}"})},get MESSAGE_SEND_FAILED(){return n.errors_catalog_messageSendFailed_template({details:"{details}"})},get MESSAGE_VALIDATION_FAILED(){return n.errors_catalog_messageValidationFailed_template({details:"{details}"})},get MESSAGE_TOO_LONG(){return n.errors_catalog_messageTooLong_template({maxLength:"{maxLength}",currentLength:"{currentLength}"})},get PROVIDER_NOT_FOUND(){return n.errors_catalog_providerNotFound_template({provider:"{provider}"})},get PROVIDER_CONNECTION_FAILED(){return n.errors_catalog_providerConnectionFailed_template({provider:"{provider}",details:"{details}"})},get PROVIDER_PROCESS_DIED(){return n.errors_catalog_providerProcessDied_template({provider:"{provider}"})},get STORAGE_READ_FAILED(){return n.errors_catalog_storageReadFailed_template({details:"{details}"})},get STORAGE_WRITE_FAILED(){return n.errors_catalog_storageWriteFailed_template({details:"{details}"})},get STORAGE_CORRUPTED(){return n.errors_catalog_storageCorrupted_template({lastBackup:"{lastBackup}"})},get MEMORY_LIMIT_EXCEEDED(){return n.errors_catalog_memoryLimitExceeded_template({currentUsage:"{currentUsage}",limit:"{limit}"})},get RATE_LIMIT_EXCEEDED(){return n.errors_catalog_rateLimitExceeded_template({count:"{count}",window:"{window}"})},get CONCURRENT_LIMIT_EXCEEDED(){return n.errors_catalog_concurrentLimitExceeded_template({current:"{current}",max:"{max}"})}},je={get AGENT_CREATION_FAILED(){return n.errors_catalog_agentCreationFailed_friendly()},get AGENT_ALREADY_EXISTS(){return n.errors_catalog_agentAlreadyExists_friendly()},get INVALID_AGENT_CONFIG(){return n.errors_catalog_invalidAgentConfig_friendly()},get INVALID_CONFIG(){return n.errors_catalog_invalidConfig_friendly()},get SESSION_NOT_FOUND(){return n.errors_catalog_sessionNotFound_friendly()},get SESSION_ALREADY_ACTIVE(){return n.errors_catalog_sessionAlreadyActive_friendly()},get SESSION_INITIALIZATION_FAILED(){return n.errors_catalog_sessionInitializationFailed_friendly()},get STREAM_CONNECTION_FAILED(){return n.errors_catalog_streamConnectionFailed_friendly()},get STREAM_TIMEOUT(){return n.errors_catalog_streamTimeout_friendly()},get STREAM_INTERRUPTED(){return n.errors_catalog_streamInterrupted_friendly()},get STREAM_RECOVERY_FAILED(){return n.errors_catalog_streamRecoveryFailed_friendly()},get MESSAGE_SEND_FAILED(){return n.errors_catalog_messageSendFailed_friendly()},get MESSAGE_VALIDATION_FAILED(){return n.errors_catalog_messageValidationFailed_friendly()},get MESSAGE_TOO_LONG(){return n.errors_catalog_messageTooLong_friendly()},get PROVIDER_NOT_FOUND(){return n.errors_catalog_providerNotFound_friendly()},get PROVIDER_CONNECTION_FAILED(){return n.errors_catalog_providerConnectionFailed_friendly()},get PROVIDER_PROCESS_DIED(){return n.errors_catalog_providerProcessDied_friendly()},get STORAGE_READ_FAILED(){return n.errors_catalog_storageReadFailed_friendly()},get STORAGE_WRITE_FAILED(){return n.errors_catalog_storageWriteFailed_friendly()},get STORAGE_CORRUPTED(){return n.errors_catalog_storageCorrupted_friendly()},get MEMORY_LIMIT_EXCEEDED(){return n.errors_catalog_memoryLimitExceeded_friendly()},get RATE_LIMIT_EXCEEDED(){return n.errors_catalog_rateLimitExceeded_friendly()},get CONCURRENT_LIMIT_EXCEEDED(){return n.errors_catalog_concurrentLimitExceeded_friendly()}};function Ze(i){return(i.match(/{(\w+)}/g)||[]).map(e=>e.slice(1,-1))}function Je(i,s){return Ze(i).every(t=>t in s)}function Oe(i,s={}){return i.replace(/{(\w+)}/g,(e,t)=>String(s[t]??e))}function ee(i){const s=n.errors_cleanMessage_fallback_error();if(!i)return s;let e=i;return e=e.replace(/^.*?failed(?:\s+to\s+.*?)?\s+after\s+\d+\s+attempts:\s*/i,""),e=e.replace(/^Error invoking remote method '[^']+':(\s*Error:)?\s*/i,""),e=e.replace(/^(Error:\s*)+/i,""),e=e.replace(/\n\s*at .+/g,""),e=e.replace(/\s+/g," ").trim(),e||s}function et(i,s){return s&&J[i]&&Je(J[i],s)?Oe(J[i],s):je[i]||n.errors_userFriendly_fallback_error()}function tt(i){const e={AGENT_CREATION_FAILED:"AGENT_CREATION",AGENT_ALREADY_EXISTS:"AGENT_CREATION",INVALID_AGENT_CONFIG:"AGENT_CREATION",STREAM_CONNECTION_FAILED:"STREAMING",STREAM_TIMEOUT:"STREAMING",STREAM_INTERRUPTED:"STREAMING",STREAM_RECOVERY_FAILED:"STREAMING",STORAGE_READ_FAILED:"STORAGE",STORAGE_WRITE_FAILED:"STORAGE",STORAGE_CORRUPTED:"STORAGE",MEMORY_LIMIT_EXCEEDED:"MEMORY",RATE_LIMIT_EXCEEDED:"MEMORY",CONCURRENT_LIMIT_EXCEEDED:"MEMORY",PROVIDER_NOT_FOUND:"PROVIDER",PROVIDER_CONNECTION_FAILED:"PROVIDER",PROVIDER_PROCESS_DIED:"PROVIDER"}[i];return e?Ae[e]:Ae.GENERAL}const st={AGENT_CREATION_FAILED:[{action:"retry",description:"Try creating the agent again",automatic:!1,priority:"high"},{action:"check-config",description:"Verify agent configuration in settings",automatic:!1,priority:"high"},{action:"check-resources",description:"Ensure sufficient memory and disk space",automatic:!1,priority:"medium"}],AGENT_ALREADY_EXISTS:[{action:"rename",description:"Choose a different name for the agent",automatic:!1,priority:"high"},{action:"delete-existing",description:"Delete the existing agent first",automatic:!1,priority:"medium"}],INVALID_AGENT_CONFIG:[{action:"review-config",description:"Review and correct the configuration",automatic:!1,priority:"high"},{action:"use-defaults",description:"Reset to default configuration",automatic:!1,priority:"medium"}],INVALID_CONFIG:[{action:"review-config",description:"Review and correct the configuration",automatic:!1,priority:"high"},{action:"use-defaults",description:"Reset to default configuration",automatic:!1,priority:"medium"}],SESSION_NOT_FOUND:[{action:"start-new",description:"Start a new agent session",automatic:!1,priority:"high"},{action:"check-history",description:"Check session history for recent sessions",automatic:!1,priority:"medium"}],SESSION_ALREADY_ACTIVE:[{action:"wait",description:"Wait for the current session to complete",automatic:!1,priority:"high"},{action:"cancel",description:"Cancel the active session first",automatic:!1,priority:"high"}],SESSION_INITIALIZATION_FAILED:[{action:"retry",description:"Try initializing the session again",automatic:!1,priority:"high"},{action:"check-resources",description:"Ensure sufficient resources are available",automatic:!1,priority:"medium"}],MESSAGE_SEND_FAILED:[{action:"retry",description:"Try sending the message again",automatic:!1,priority:"high"},{action:"check-connection",description:"Check your network connection",automatic:!1,priority:"high"}],MESSAGE_VALIDATION_FAILED:[{action:"review-config",description:"Review and correct the message format",automatic:!1,priority:"high"},{action:"check-config",description:"Check configuration for valid message format",automatic:!1,priority:"medium"}],MESSAGE_TOO_LONG:[{action:"retry",description:"Shorten the message and try again",automatic:!1,priority:"high"},{action:"batch",description:"Split the message into multiple parts",automatic:!1,priority:"medium"}],PROVIDER_NOT_FOUND:[{action:"check-config",description:"Verify provider is properly configured",automatic:!1,priority:"high"},{action:"recreate",description:"Install or reinstall the provider",automatic:!1,priority:"high"}],PROVIDER_CONNECTION_FAILED:[{action:"retry",description:"Try connecting to the provider again",automatic:!1,priority:"high"},{action:"check-config",description:"Verify provider configuration",automatic:!1,priority:"high"}],STORAGE_READ_FAILED:[{action:"retry",description:"Try reading the data again",automatic:!1,priority:"high"},{action:"restore",description:"Restore from a recent backup",automatic:!1,priority:"medium"}],STORAGE_WRITE_FAILED:[{action:"retry",description:"Try saving again",automatic:!1,priority:"high"},{action:"check-resources",description:"Check available disk space",automatic:!1,priority:"high"}],STREAM_CONNECTION_FAILED:[{action:"retry",description:"Try connecting again",automatic:!1,priority:"high"},{action:"check-connection",description:"Check your network connection",automatic:!1,priority:"high"}],STREAM_RECOVERY_FAILED:[{action:"restart",description:"Restart the agent",automatic:!1,priority:"high"},{action:"check-config",description:"Check error logs for more details",automatic:!1,priority:"medium"}],STREAM_INTERRUPTED:[{action:"reconnect",description:"Attempting automatic reconnection",automatic:!0,priority:"high"},{action:"retry",description:"Retry sending the message",automatic:!1,priority:"high"},{action:"check-connection",description:"Check your internet connection",automatic:!1,priority:"medium"}],STREAM_TIMEOUT:[{action:"wait",description:"Wait for agent to complete processing",automatic:!1,priority:"high"},{action:"cancel",description:"Cancel current operation",automatic:!1,priority:"medium"},{action:"increase-timeout",description:"Increase timeout in settings",automatic:!1,priority:"low"}],PROVIDER_PROCESS_DIED:[{action:"restart",description:"Restart agent process",automatic:!0,priority:"high"},{action:"recreate",description:"Create new agent session",automatic:!1,priority:"high"}],STORAGE_CORRUPTED:[{action:"restore",description:"Restore from backup",automatic:!1,priority:"high"},{action:"reset",description:"Reset agent data",automatic:!1,priority:"medium"}],MEMORY_LIMIT_EXCEEDED:[{action:"cleanup",description:"Close unused agents",automatic:!1,priority:"high"},{action:"increase-limit",description:"Increase memory limit in settings",automatic:!1,priority:"medium"}],RATE_LIMIT_EXCEEDED:[{action:"wait",description:"Wait before making more requests",automatic:!1,priority:"high"},{action:"batch",description:"Batch requests together",automatic:!1,priority:"medium"}],CONCURRENT_LIMIT_EXCEEDED:[{action:"close-agents",description:"Close some running agents",automatic:!1,priority:"high"},{action:"queue",description:"Queue operation for later",automatic:!1,priority:"medium"}]};function it(i){return st[i]||[{action:"retry",description:"Try the operation again",automatic:!1,priority:"high"}]}var N=(i=>(i.AGENT_CREATION_FAILED="AGENT_CREATION_FAILED",i.AGENT_ALREADY_EXISTS="AGENT_ALREADY_EXISTS",i.INVALID_AGENT_CONFIG="INVALID_AGENT_CONFIG",i.INVALID_CONFIG="INVALID_CONFIG",i.SESSION_NOT_FOUND="SESSION_NOT_FOUND",i.SESSION_ALREADY_ACTIVE="SESSION_ALREADY_ACTIVE",i.SESSION_INITIALIZATION_FAILED="SESSION_INITIALIZATION_FAILED",i.STREAM_CONNECTION_FAILED="STREAM_CONNECTION_FAILED",i.STREAM_TIMEOUT="STREAM_TIMEOUT",i.STREAM_INTERRUPTED="STREAM_INTERRUPTED",i.STREAM_RECOVERY_FAILED="STREAM_RECOVERY_FAILED",i.MESSAGE_SEND_FAILED="MESSAGE_SEND_FAILED",i.MESSAGE_VALIDATION_FAILED="MESSAGE_VALIDATION_FAILED",i.MESSAGE_TOO_LONG="MESSAGE_TOO_LONG",i.PROVIDER_NOT_FOUND="PROVIDER_NOT_FOUND",i.PROVIDER_CONNECTION_FAILED="PROVIDER_CONNECTION_FAILED",i.PROVIDER_PROCESS_DIED="PROVIDER_PROCESS_DIED",i.PROVIDER_UNAVAILABLE="PROVIDER_UNAVAILABLE",i.PROVIDER_ERROR="PROVIDER_ERROR",i.STORAGE_READ_FAILED="STORAGE_READ_FAILED",i.STORAGE_WRITE_FAILED="STORAGE_WRITE_FAILED",i.STORAGE_CORRUPTED="STORAGE_CORRUPTED",i.STORAGE_ERROR="STORAGE_ERROR",i.STORAGE_QUOTA_EXCEEDED="STORAGE_QUOTA_EXCEEDED",i.MEMORY_LIMIT_EXCEEDED="MEMORY_LIMIT_EXCEEDED",i.RATE_LIMIT_EXCEEDED="RATE_LIMIT_EXCEEDED",i.CONCURRENT_LIMIT_EXCEEDED="CONCURRENT_LIMIT_EXCEEDED",i.RESOURCE_NOT_FOUND="RESOURCE_NOT_FOUND",i.RESOURCE_EXHAUSTED="RESOURCE_EXHAUSTED",i.NETWORK_ERROR="NETWORK_ERROR",i.PERMISSION_DENIED="PERMISSION_DENIED",i.OPERATION_FAILED="OPERATION_FAILED",i.VALIDATION_ERROR="VALIDATION_ERROR",i.INVALID_RESPONSE="INVALID_RESPONSE",i.STATE_CORRUPTION="STATE_CORRUPTION",i.CONTEXT_OVERFLOW="CONTEXT_OVERFLOW",i))(N||{});class q extends Error{constructor(e,t,r={},a){super(e);E(this,"code");E(this,"context");E(this,"recoverySuggestions");E(this,"userMessage");E(this,"isRecoverable");E(this,"cause");this.name="AgentError",this.code=t,this.context={...r,timestamp:new Date,stackTrace:this.stack},this.userMessage=a?.userMessage||this.getDefaultUserMessage(t),this.recoverySuggestions=a?.recoverySuggestions||this.getDefaultRecoverySuggestions(t),this.isRecoverable=a?.isRecoverable??this.isErrorRecoverable(t),a?.cause&&(this.cause=a.cause)}getDefaultUserMessage(e){return et(e,this.context)}getDefaultRecoverySuggestions(e){return it(e)}isErrorRecoverable(e){return["STREAM_INTERRUPTED","STREAM_TIMEOUT","MESSAGE_SEND_FAILED","PROVIDER_PROCESS_DIED","STORAGE_READ_FAILED","STORAGE_WRITE_FAILED"].includes(e)}getHelpLink(){return tt(this.code)}formatMessage(e){return Oe(e,this.context)}toJSON(){return{name:this.name,code:this.code,message:this.message,userMessage:this.userMessage,context:this.context,recoverySuggestions:this.recoverySuggestions,isRecoverable:this.isRecoverable,helpLink:this.getHelpLink(),stack:this.stack}}}const rt={NON_RETRYABLE_ERRORS:["EACCES","EPERM","ENOSPC","EMFILE","permission","memory","fatal","process died","not available on your current plan","agent binary","rate limit","too many requests","hit your limit","you've hit your limit","quota exceeded"]};function re(i){const s=i.toLowerCase();for(const e of rt.NON_RETRYABLE_ERRORS)if(s.includes(e.toLowerCase()))return!0;return!1}const at="Agent already has an in-flight prompt. Message was not delivered.",v=W("ErrorBoundary"),b=class b{constructor(){}static getInstance(){return b.instance||(b.instance=new b),b.instance}async wrap(s,e,t={}){const{retries:r=pe.DEFAULT_ATTEMPTS,retryDelay:a=pe.BASE_DELAY,exponentialBackoff:l=!0,notify:o=!1,notifyOnRetry:f=!1,context:_={},onError:u,onRetry:c,shouldRetry:R=this.defaultShouldRetry}=t;let g=null,d=0;for(d=1;d<=r+1;d++)try{v.debug(`[${e}] Attempt ${d}/${r+1}`);const C=await s();return d>1&&v.info(`[${e}] Succeeded after ${d} attempts`),C}catch(C){if(g=C,v.error(`[${e}] Attempt ${d} failed`,{error:g.message,attempt:d,maxAttempts:r+1,context:_}),u?.(g,d),d<=r&&R(g)){const h=l?a*Math.pow(2,d-1):a;f&&j.warning(n.agent_errorBoundary_retrying_message({seconds:h/1e3})),c?.(d),v.info(`[${e}] Retrying in ${h}ms`),await this.sleep(h)}else break}const k=`${e} failed after ${d} attempt${d===1?"":"s"}: ${g?.message}`,P=ee(g?.message||n.agent_errorBoundary_generic_error()),D=g?.message?.toLowerCase()||"",$=D.includes("no available models")||D.includes("all models exhausted")||D.includes("all models unavailable");throw o&&!$&&j.error(P),new q(P,N.OPERATION_FAILED,{originalError:g?.message,detailedMessage:k,attempts:d,context:_})}async wrapVoid(s,e,t={}){await this.wrap(s,e,t)}wrapSync(s,e,t={}){try{return s()}catch(r){const a=r;throw v.error(`[${e}] Failed`,{error:a.message,context:t.context}),t.notify&&j.error(ee(a.message)),new q(ee(a.message),N.OPERATION_FAILED,t.context)}}defaultShouldRetry(s){const e=s.message.toLowerCase();return re(s.message)?!1:e.includes("network")||e.includes("timeout")?!0:s instanceof q?[N.NETWORK_ERROR,N.STREAM_TIMEOUT,N.STREAM_CONNECTION_FAILED,N.PROVIDER_CONNECTION_FAILED,N.PROVIDER_UNAVAILABLE].includes(s.code):!(e.includes("invalid")||e.includes("interrupted")||e.includes("cancel")||e.includes("not found")||e.includes("not available")||e.includes("404")||e.includes("no available models")||e.includes("all models exhausted")||e.includes("all models unavailable")||e.includes("413")||e.includes("too long for the agent")||e.includes("request entity too large")||e.includes("payload too large")||e.includes("content too large")||e.includes("body too large")||e.includes("unauthorized")||e.includes("forbidden")||e.includes("401")||e.includes("403"))}sleep(s){return new Promise(e=>setTimeout(e,s))}async withTimeout(s,e,t){return Promise.race([s(),new Promise((r,a)=>setTimeout(()=>a(new q(`${t} timed out after ${e}ms`,N.STREAM_TIMEOUT)),e))])}async batchOperations(s,e,t={}){const{concurrency:r=5,continueOnError:a=!0,operationName:l="batch operation"}=t,o=[],f=[];for(let _=0;_<s.length;_+=r){const u=s.slice(_,_+r);(await Promise.allSettled(u.map(R=>e(R)))).forEach((R,g)=>{if(R.status==="fulfilled")o.push(R.value);else{const d=R.reason;if(f.push({item:u[g],error:d}),v.error(`[${l}] Batch item failed`,{item:u[g],error:d.message}),!a)throw d}})}return f.length>0&&v.warn(`[${l}] Completed with ${f.length} errors`),{results:o,errors:f}}};E(b,"instance");let se=b;const nt=se.getInstance(),ie=W("browser/index"),F=new Map,B=new Map;let U;function ot(i,s,e){for(const t of s)try{t(e)}catch(r){ie.error("Error in agent subscriber callback",{agentId:i,error:r})}}function ct(){if(U)return;let i=!1;U=p.createSelector(e=>e.agentSessions)().subscribe(()=>{if(!i){i=!0;return}if(F.size===0)return;const e=p.state;for(const[t,r]of F){const a=Se.select(e,t);B.get(t)!==a&&(B.set(t,a),ot(t,r,a))}})}function lt(){F.size>0||!U||(U(),U=void 0,B.clear())}function Ft(i,s,e){let t=F.get(i);const r=!t;t||(t=new Set,F.set(i,t)),t.add(s),ct();const a=p.state,l=Se.select(a,i);return r&&B.set(i,l),l?ie.debug("[subscribeToAgent] Initial callback data",{agentId:i,workspaceId:e??"current",hasSession:!0}):ie.debug("[subscribeToAgent] No session found",{agentId:i,workspaceId:e??"current"}),s(l),()=>{const o=F.get(i);o&&(o.delete(s),o.size===0&&(F.delete(i),B.delete(i))),lt()}}const y=W("ErrorRecovery"),ye={network:{maxRetries:3,initialBackoffMs:1e3,maxBackoffMs:1e4,backoffMultiplier:2,shouldRetry:i=>{const s=i.message.toLowerCase();return s.includes("network")||s.includes("fetch")||s.includes("connection")||s.includes("timeout")}},streaming:{maxRetries:5,initialBackoffMs:500,maxBackoffMs:5e3,backoffMultiplier:1.5,shouldRetry:(i,s)=>{if(s>=5)return!1;const e=i.message.toLowerCase();return e.includes("no available models")||e.includes("all models exhausted")||e.includes("all models unavailable")||re(i.message)?!1:e.includes("stream")||e.includes("chunk")||e.includes("incomplete")}},persistence:{maxRetries:2,initialBackoffMs:100,maxBackoffMs:1e3,backoffMultiplier:2,shouldRetry:i=>{const s=i.message.toLowerCase();return s.includes("save")||s.includes("write")||s.includes("persist")}},rateLimit:{maxRetries:3,initialBackoffMs:5e3,maxBackoffMs:3e4,backoffMultiplier:2,shouldRetry:i=>{const s=i.message.toLowerCase();return s.includes("rate")||s.includes("limit")||s.includes("429")}}};class ut{constructor(){E(this,"listeners",new Map)}on(s,e){let t=this.listeners.get(s);t||(t=new Set,this.listeners.set(s,t)),t.add(e)}off(s,e){this.listeners.get(s)?.delete(e)}emit(s,...e){this.listeners.get(s)?.forEach(t=>{try{t(...e)}catch(r){y.error(`Error in event listener for ${s}:`,r)}})}removeAllListeners(){this.listeners.clear()}}class dt extends ut{constructor(){super(...arguments);E(this,"activeRecoveries",new Map);E(this,"recoveryStats",new Map)}async executeWithRecovery(e,t=ye.network,r){const a=Date.now(),l=new AbortController;r&&(this.cancelRecovery(r),this.activeRecoveries.set(r,l));let o,f=t.initialBackoffMs,_=0;for(let u=1;u<=t.maxRetries;u++){if(_=u,l.signal.aborted){y.info(`Recovery cancelled for operation ${r}`);break}try{y.debug(`Attempting operation (attempt ${u}/${t.maxRetries})`,{operationId:r});const c=await e();return this.updateStats(r,!0),this.emit("recovery:success",{operationId:r,attempt:u,duration:Date.now()-a}),r&&this.activeRecoveries.delete(r),{success:!0,data:c,attempts:u,totalTime:Date.now()-a}}catch(c){o=c,y.warn(`Operation failed (attempt ${u}/${t.maxRetries})`,{operationId:r,error:o.message});const R=o.message.toLowerCase();if(R.includes("interrupted")||R.includes("cancelled")||R.includes("canceled")){y.debug("User-initiated interruption/cancellation, not retrying",{operationId:r,error:o.message});break}if(R.includes("no available models")||R.includes("all models exhausted")||R.includes("all models unavailable")){y.debug("All models exhausted, not retrying",{operationId:r,error:o.message});break}if(re(o.message)){y.debug("Fatal error detected, not retrying",{operationId:r,error:o.message});break}if(!t.shouldRetry(o,u)){y.debug("Error not retryable, stopping recovery",{operationId:r,error:o.message});break}if(u<t.maxRetries){const g=Math.random()*.2*f,d=Math.min(f+g,t.maxBackoffMs);t.onRetry?.(u,d),this.emit("recovery:retry",{operationId:r,attempt:u,delay:d,error:o.message}),await this.delay(d,l.signal),f=Math.min(f*t.backoffMultiplier,t.maxBackoffMs)}}}return this.updateStats(r,!1),t.onFailure?.(o,_),this.emit("recovery:failure",{operationId:r,attempts:_,duration:Date.now()-a,error:o?.message}),r&&this.activeRecoveries.delete(r),{success:!1,error:o,attempts:_,totalTime:Date.now()-a}}cancelRecovery(e){const t=this.activeRecoveries.get(e);t&&(t.abort(),this.activeRecoveries.delete(e),y.info(`Cancelled recovery for operation ${e}`))}cancelAllRecoveries(){for(const[e,t]of this.activeRecoveries)t.abort(),y.info(`Cancelled recovery for operation ${e}`);this.activeRecoveries.clear()}getStats(e){if(e)return this.recoveryStats.get(e)||{successes:0,failures:0};const t={};for(const[r,a]of this.recoveryStats)t[r]=a;return t}clearStats(e){e?this.recoveryStats.delete(e):this.recoveryStats.clear()}isRetryable(e,t){const r=e.message.toLowerCase();if(t)switch(t){case"NETWORK":return r.includes("network")||r.includes("fetch");case"TIMEOUT":return r.includes("timeout")||r.includes("timed out");case"RATE_LIMIT":return r.includes("rate")||r.includes("limit")||r.includes("429");case"TEMPORARY":return r.includes("temporary")||r.includes("transient");case"CONFLICT":return r.includes("conflict")||r.includes("concurrent");default:return!1}return this.isRetryable(e,"NETWORK")||this.isRetryable(e,"TIMEOUT")||this.isRetryable(e,"RATE_LIMIT")||this.isRetryable(e,"TEMPORARY")||this.isRetryable(e,"CONFLICT")}delay(e,t){return new Promise((r,a)=>{const l=setTimeout(r,e);if(t){const o=()=>{clearTimeout(l),a(new Error("Delay aborted"))};t.addEventListener("abort",o);const f=r;r=()=>{t.removeEventListener("abort",o),f()}}})}updateStats(e,t){if(!e)return;const r=this.recoveryStats.get(e)||{successes:0,failures:0};t?r.successes++:r.failures++,this.recoveryStats.set(e,r)}dispose(){this.cancelAllRecoveries(),this.recoveryStats.clear(),this.removeAllListeners()}}const mt=new dt,O=new Ye({category:"WorkspaceMetrics"}),Et=100;class ft{constructor(){E(this,"metrics",new Map);E(this,"operations",new Map)}startWorkspaceCreation(s){const e=Date.now();for(this.metrics.delete(s),this.metrics.set(s,{workspaceId:s,creationStarted:e});this.metrics.size>Et;){const t=this.metrics.keys().next().value;if(t===void 0)break;this.metrics.delete(t)}O.info("Started tracking workspace creation",{workspaceId:s})}recordMilestone(s,e){const t=this.metrics.get(s);if(!t){O.warn("No metrics found for workspace",{workspaceId:s,milestone:e});return}const r=Date.now();switch(e){case"optimisticNavigation":t.optimisticNavigation=r;break;case"realWorkspaceCreated":t.realWorkspaceCreated=r;break;case"agentCreated":t.agentCreated=r;break;case"agentReady":t.agentReady=r;break;case"firstMessageSent":t.firstMessageSent=r;break;case"firstResponseReceived":t.firstResponseReceived=r;break;case"firstChunkReceived":t.firstChunkReceived=r;break;case"totalDuration":t.totalDuration=r;break;case"workspaceId":case"creationStarted":O.warn("Cannot update milestone",{milestone:e});return}const a=r-t.creationStarted;O.info(`Milestone: ${e}`,{workspaceId:s,elapsed:`${a}ms`,timestamp:r}),e==="firstResponseReceived"&&(t.totalDuration=r-t.creationStarted,this.logSummary(s))}startOperation(s,e){this.operations.set(s,{startTime:Date.now(),metadata:e})}endOperation(s,e){const t=this.operations.get(s);if(!t)return O.warn("Operation not found",{operationId:s}),null;const r=Date.now();return t.endTime=r,t.duration=r-t.startTime,e&&(t.metadata={...t.metadata,...e}),O.info("Operation completed",{operationId:s,duration:`${t.duration}ms`,metadata:t.metadata}),this.operations.delete(s),t.duration}getMetrics(s){return this.metrics.get(s)}logSummary(s){const e=this.metrics.get(s);if(!e)return;const t={workspaceId:s,totalDuration:`${e.totalDuration}ms`,stages:{optimisticNavigation:e.optimisticNavigation?`${e.optimisticNavigation-e.creationStarted}ms`:"N/A",realWorkspaceCreation:e.realWorkspaceCreated?`${e.realWorkspaceCreated-e.creationStarted}ms`:"N/A",agentCreation:e.agentCreated?`${e.agentCreated-e.creationStarted}ms`:"N/A",agentReady:e.agentReady?`${e.agentReady-e.creationStarted}ms`:"N/A",firstMessage:e.firstMessageSent?`${e.firstMessageSent-e.creationStarted}ms`:"N/A",firstResponse:e.firstResponseReceived?`${e.firstResponseReceived-e.creationStarted}ms`:"N/A"}};O.info("=== Workspace Creation Metrics Summary ===",t),O.info("Workspace Creation Metrics:",t)}clearMetrics(s){this.metrics.delete(s)}incrementAgentCreated(s){const e=this.metrics.get(s);e&&(e.agentCreated=Date.now(),O.info("Agent created",{workspaceId:s}))}incrementMessageSent(s){const e=this.metrics.get(s);e&&!e.firstMessageSent&&(e.firstMessageSent=Date.now(),O.info("First message sent",{workspaceId:s}))}}const _t=new ft,M=W("AgentSend");function A(i){p.dispatch(i)}function Ie(i){return typeof i=="object"&&i!==null&&!Array.isArray(i)}function ht(i){const s=Ie(i)&&i.success===!0&&"data"in i?i.data:i;return!Ie(s)||s.success!==!1?!1:typeof s.error=="string"&&s.error.includes(at)}async function kt(i,s,e,t={}){const r=ge.select(p.state,e.id);if(!r)return;const a=Le(i,e.id),l=t.submission,o=!!l&&we.select(p.state,l.scope)?.supported===!0,f=(c,R,g=!1)=>{l&&A(Xe(l.scope,l.id,c,Date.now(),R,g))};let _=!1;const u=()=>(!l||_||be.select(p.state,l))&&r===ge.select(p.state,e.id)&&a.isCurrent(p.state.agentSessions?.byAgentId[i]?.workspaceId);return Qe.track(`sendMessage:${a.key}:${i}:${l?.id??"legacy"}`,async()=>{if(!u())return;M.debug(`Sending message to agent ${i}`,{contentLength:s.length,hasContextReferences:!!t.contextReferences?.length,model:t.model});let c=await p.dispatch(Fe(e.id,i));if(u()){if(!c)throw new Error(n.agent_streamLifecycle_sessionNotFound_error({agentId:i}));c={...c,isStreaming:c.isStreaming??!1};{if(c&&(c.status==="pending"||!c.id)&&!c.backendSessionId&&c.activationState!==K.ACTIVE&&c.activationState!==K.ACTIVATING){const h=e.id.startsWith("optimistic-"),Y=e.worktreePath||e.repositoryPath||e.path;if(!h&&Y){M.info("Activating pending session in sendMessage",{agentId:i,status:c.status,activationState:c.activationState,hasBackendSessionId:!!c.backendSessionId});const x=await p.dispatch(ke(e.id,i));if(!u())return;x&&(c=x)}else throw M.warn("Cannot activate agent - workspace not ready",{agentId:i,workspaceId:e.id,isOptimistic:h,hasWorktreePath:!!e.worktreePath,hasRepositoryPath:!!e.repositoryPath,hasPath:!!e.path}),new Error(n.agent_streamLifecycle_spaceNotReady_error())}else c&&c.status==="pending"&&c.backendSessionId&&(M.info("Fixing status for already-activated session",{agentId:i,backendSessionId:c.backendSessionId,activationState:c.activationState}),c={...c,status:Ge.Active,activationState:K.ACTIVE},A(me({...c,workspaceId:e.id})));if(!c)throw new Error(`Failed to get or create session for agent ${i}`);A(me({...c,workspaceId:e.id}));const g=[{type:"text",text:s}];if(t.imageBlocks)for(const h of t.imageBlocks)g.push({type:"image",...h.data!==void 0?{data:h.data}:{},...h.mimeType!==void 0?{mimeType:h.mimeType}:{},...h.attachmentId!==void 0?{attachmentId:h.attachmentId}:{}});if(t.fileBlocks)for(const h of t.fileBlocks)g.push({type:"file",attachmentId:h.attachmentId,fileName:h.fileName,...h.mimeType!==void 0?{mimeType:h.mimeType}:{},...h.size!==void 0?{size:h.size}:{}});const d=t.userAppMessageId??ce(),k=t.messageMetadata?.[Re],P={...t.contextReferences?.length?{contextReferences:t.contextReferences}:{},...k!==void 0?{[Re]:k}:{}},D={id:Ee(ue()),appMessageId:d,role:"user",contentBlocks:g,timestamp:new Date().toISOString(),metadata:{...P,...t.messageMetadata??{}}};o||(l&&(f("rejected"),_=!0),A(Pe(c.id,D))),A(H(c.id,!0));let $=!1,C;try{o||await p.dispatch(xe(e.id,i,!0,{allowTruncation:t.resetHistory}));const h=Ee(`msg_${ue()}`),Y=ce(),x=async()=>nt.wrap(async()=>{if(!u())return;M.info("Agent Service: Sending message to backend with image and file blocks",{agentId:i,sessionId:c.id,hasImageBlocks:!!t.imageBlocks,imageBlocksCount:t.imageBlocks?.length||0,imageBlockDetails:t.imageBlocks?.map(m=>({type:m.type,mimeType:m.mimeType,dataLength:m.data?.length||0}))||[],hasFileBlocks:!!t.fileBlocks,fileBlocksCount:t.fileBlocks?.length||0,fileBlockDetails:t.fileBlocks?.map(m=>({type:m.type,fileName:m.fileName,mimeType:m.mimeType,attachmentId:m.attachmentId,size:m.size}))||[]});const Me=t.model??t.modelId??c.model??void 0;A(Ve(i));const Ne=le(i,e.id),ne=p.state.chatState?.byAgentId[i]?.attemptGeneration??0,T=await qe("agent.sendMessage",{agentId:i,...o&&l?{messageId:l.id}:{},workspaceId:e.id,content:s,model:Me,contextReferences:t.contextReferences,imageBlocks:t.imageBlocks,fileBlocks:t.fileBlocks,noteIds:t.noteIds,stdinContext:t.stdinContext,assistantMessageId:h,userAppMessageId:d,assistantAppMessageId:Y,priority:t.priority,...t.messageMetadata?{messageMetadata:t.messageMetadata}:{}}).catch(m=>{if(u())throw Ke(m)&&(C=m),m});if(u()){if(ht(T)){M.info("Backend dropped duplicate in-flight prompt",{agentId:i,sessionId:c.id}),f("rejected");return}if(T&&typeof T=="object"&&"success"in T){if(!T.success){const m=T.error,I=typeof m=="string"?m:m?.message;throw $=!0,new Error(I||n.agent_streamLifecycle_sendToBackendFailed_error())}if("queued"in T&&T.queued===!0){if(M.info("sendMessage auto-queued by daemon (mid-turn or turn-startup race)",{agentId:i,sessionId:c.id,queuedMessageId:T.queuedMessage?.id}),(!o||!l||!de.select(p.state,l))&&A(H(c.id,!1)),o||A(Ue(c.id,D.id)),o){const I=T.queuedMessage,G=T.turnId,L=typeof G=="string"?G:I?.turnId;if(I&&typeof L=="string"){const S=fe(s,t),X=Q.select(p.state,i,e.id).find(oe=>oe.id===I.id||oe.turnId===L);A(_e(i,I.id,S,L,he(X??I,S),!X&&!!l&&de.select(p.state,l),ne))}f("accepted",I,!0),z(i,e.id);return}const m=T.queuedMessage;if(m){const I=T.turnId,G=typeof I=="string"?I:m.turnId;let L=m;if(u()&&le(i,e.id)===Ne){const S=Q.select(p.state,i,e.id),X=ze(S,m);A(Be(i,X,e.id))}else u()&&(M.debug("queued-response queue seed superseded by an authoritative snapshot; reconciling via hydrate",{agentId:i,queuedMessageId:m.id}),await z(i,e.id).catch(()=>{}),L=Q.select(p.state,i,e.id).find(S=>S.id===m.id||S.turnId===G));if(u()&&typeof G=="string"){const S=fe(s,t);A(_e(i,m.id,S,G,he(L??m,S),!L,ne))}else u()&&M.warn("auto-queued sendMessage response carried no turnId; retry record not parked",{agentId:i,queuedMessageId:m.id})}return}}o&&(f("accepted"),z(i,e.id),ve(i,e.id)),_t.incrementMessageSent(e.id)}},"send message",{retries:o?0:2,notify:!1,context:{agentId:i,workspace:e.id}}),ae=o?await x().then(()=>({success:!0,error:void 0})):await mt.executeWithRecovery(x,ye.streaming,`send-message-${i}`);if(!ae.success)throw ae.error||new Error(n.agent_streamLifecycle_sendFailed_error())}catch(h){if(!u())return;throw A(H(c.id,!1)),!o&&t.messageMetadata&&A($e(c.id,D.id,{metadata:P})),o&&f($||C?"rejected":"uncertain"),C??h}}}},{memoize:!1,coalesce:!0,priority:"high"})}export{Te as U,Ft as a,ee as c,ze as r,kt as s,Ke as u,bt as w};
@@ -1,4 +1,4 @@
1
- import{b as e}from"./Bex9L_jH.js";var l=e(()=>`
1
+ import{b as e}from"./DabFMHr_.js";var l=e(()=>`
2
2
  /* Font Awesome icon styling - consolidated */
3
3
  .label-icon {
4
4
  display: inline-block;
@@ -1 +1 @@
1
- import{t as Qe,bo as h,bw as Ye,b as $e,bq as nt,bm as w,bs as Ve}from"./Fcr7AvC-.js";import{bo as st,bs as et,a7 as J,ay as y,aD as e,bS as L,W as c,a5 as Pe,bA as De,bH as V,bl as _e,b_ as oe,bO as de,bn as tt,bf as je,bV as Ee,aA as v,c9 as k,aB as U,be as it,b$ as lt,bj as dt,cd as ct,ca as He,bk as ut}from"./3SdAC2_C.js";import{i as G}from"./CL3a4Hm1.js";import{JH as Je,ni as pt,vh as ft}from"./D0qhIm1r.js";import{aM as ht}from"./B3ZeLze4.js";import{cB as vt}from"./cD292w1o.js";import{c as gt}from"./ChTqQfQN.js";import{i as Le,t as Ue}from"./H2jLkRRS.js";import{w as _t}from"./Bqd7fdCF.js";import{d as mt}from"./B0Z-1lwJ.js";import{F as Re,aw as bt,ax as wt,cV as Xe,aZ as qe,bg as kt,ao as yt,an as At,cS as Ge}from"./ChHRVjww.js";import{m as K,w as Ft}from"./DkQdSPDN.js";import{s as Ne,f as xe,c as Wt}from"./BRCr02in.js";import{t as Ct}from"./CWfjuhY2.js";import{w as xt}from"./BAtAwQ72.js";import"./DRMe5Ypb.js";import{i as M}from"./BhYXv0ZM.js";import{g as It,e as Te}from"./CA6H1-bp.js";import{c as Z}from"./2z64ELW5.js";import{a as Pt,r as Dt}from"./DUbqvr_K.js";import{f as Mt,aa as Et}from"./Beq_QLuz.js";import{t as Be}from"./DAsc1V4f.js";import{h as Ke,k as Ot,j as St,R as Rt,i as Nt,g as Tt,c as Bt,e as zt}from"./D7KhILhs.js";import{M as Vt}from"./C2RnxEnO.js";import{m as ze}from"./Cz3WzTlQ.js";var jt=U('<img alt="" class="size-4"/>'),Ht=U('<span class="min-w-0 flex-1 text-left"><span class="block truncate"> </span> <span class="block text-muted-foreground" aria-hidden="true" data-menu-action-reason=""> </span></span>'),Jt=U("<span> </span>"),Lt=U('<span data-menu-action-detail=""> </span>'),Ut=U('<span aria-hidden="true"><!></span>'),Ze=U("<!> <!> <!>",1),Xt=U('<div class="my-1 h-px bg-border" role="separator"></div>'),Me=U("<!> <!>",1),qt=U('<!> <p data-menu-action-note=""> </p>',1),Gt=U('<span class="flex size-4 shrink-0 items-center justify-center" aria-hidden="true"><!></span> <!> <!>',1),Kt=U('<p data-menu-action-note=""> </p>'),Zt=U('<div class="pl-4"><!> <!></div>'),Qt=U('<span class="sr-only"> </span>');function me(be,d){const we=st();if(new.target)return Qe({component:me,...be});et(d,!0);const Ie=(p,r=je)=>{var O=J(),S=y(O);{var j=W=>{const x=k(()=>Pt(r().editor));var H=J(),m=y(H);{var f=s=>{var i=jt();oe(()=>Ne(i,"src",`data:image/png;base64,${r().editor.iconBase64??""}`)),c(s,i)},o=s=>{var i=J(),b=y(i);Z(b,()=>e(x),(T,ae)=>{ae(T,{size:16})}),c(s,i)},N=s=>{{let i=k(()=>Dt(r().editor.category));Re(s,{get icon(){return e(i)},size:16})}};M(m,s=>{r().editor.iconBase64?s(f):e(x)?s(o,1):s(N,-1)})}c(W,H)},R=W=>{var x=J(),H=y(x);Ct(H,()=>r().iconSnippet),c(W,x)},q=W=>{{let x=k(()=>r().variant==="destructive"?"text-current":"text-muted-foreground");Re(W,{get icon(){return r().icon},get weight(){return X()},size:16,get class(){return e(x)}})}};M(S,W=>{r().editor?W(j):r().iconSnippet?W(R,1):r().icon&&W(q,2)})}c(p,O)},ne=(p,r=je)=>{var O=Ze(),S=y(O);{var j=m=>{var f=Ht(),o=Pe(f),N=_e(o,!0);Te(o,(b,T)=>Be?.(b,T),()=>r().label);var s=L(o,2),i=_e(s,!0);De(f),oe(()=>{de(N,r().label),de(i,r().disabledReason)}),c(m,f)},R=m=>{var f=Jt(),o=_e(f,!0);Te(f,(N,s)=>Be?.(N,s),()=>r().label),oe(()=>{xe(f,1,`min-w-0 truncate text-left ${r().detail?"flex-[1_0_auto]":"flex-1"}`),de(o,r().label)}),c(m,f)};M(S,m=>{r().disabledReason?m(j):m(R,-1)})}var q=L(S,2);{var W=m=>{var f=Lt(),o=_e(f,!0);Te(f,(N,s)=>Be?.(N,s),()=>r().detail),oe(()=>{xe(f,1,`ml-4 min-w-0 truncate ${(r().detailTone==="danger"?"text-danger":ze)??""}`),de(o,r().detail)}),c(m,f)};M(q,m=>{r().detail&&m(W)})}var x=L(q,2);{var H=m=>{var f=Ut(),o=Pe(f);Et(o,{children:(N,s)=>{it();var i=lt();oe(b=>de(i,b),[()=>xt(r().shortcut)]),c(N,i)},$$slots:{default:!0}}),De(f),oe(()=>xe(f,1,Wt(E()?"ml-4 flex h-lh shrink-0 items-center":"ml-4"))),c(m,f)};M(x,m=>{r().shortcut&&m(H)})}c(p,O)};let ke=h(d,"actions",7),E=h(d,"menu",7),X=h(d,"iconWeight",7),u=h(d,"onClose",7),A=h(d,"selection",7),F=Ee(null);function Q(p){p.disabled||p.disabledReason!==void 0||(p.onClick(),u()?.())}var ce={get actions(){return ke()},set actions(p){ke(p),v()},get menu(){return E()},set menu(p){E(p),v()},get iconWeight(){return X()},set iconWeight(p){X(p),v()},get onClose(){return u()},set onClose(p){u(p),v()},get selection(){return A()},set selection(p){A(p),v()},$set:Ye,$on:(p,r)=>$e(d,p,r)},se=J(),ie=y(se);return It(ie,17,ke,p=>p.id,(p,r)=>{const O=i=>{Ie(i,()=>e(r))},S=k(()=>!!(e(r).editor||e(r).iconSnippet||e(r).icon)),j=k(()=>e(r).disabled||e(r).disabledReason!==void 0),R=k(()=>e(r).disabledReason?`${we}-${e(r).id}-reason`:void 0);var q=Ze(),W=y(q);{var x=i=>{var b=J(),T=y(b);{var ae=a=>{var n=J(),g=y(n);Z(g,()=>Ke,(C,P)=>{P(C,{})}),c(a,n)},ue=a=>{var n=Xt();c(a,n)};M(T,a=>{E()?a(ae):a(ue,-1)})}c(i,b)};M(W,i=>{e(r).dividerBefore&&i(x)})}var H=L(W,2);{var m=i=>{var b=J(),T=y(b);{var ae=g=>{var C=J(),P=y(C);Z(P,()=>Nt,(I,D)=>{D(I,{children:(B,Y)=>{var $=Me(),pe=y($);{let te=k(()=>e(S)?O:void 0);Z(pe,()=>Ot,(fe,he)=>{he(fe,{get leading(){return e(te)},get disabled(){return e(j)},get"aria-describedby"(){return e(R)},get"data-action-id"(){return e(r).id},children:(ve,ye)=>{ne(ve,()=>e(r))},$$slots:{default:!0}})})}var ee=L(pe,2);{let te=k(()=>e(r).note?`${we}-${e(r).id}-note`:void 0);Z(ee,()=>St,(fe,he)=>{he(fe,{class:"w-60",get"aria-describedby"(){return e(te)},children:(ve,ye)=>{var t=Me(),l=y(t);{var _=re=>{var Ae=Me(),Fe=y(Ae);{let Ce=k(()=>e(r).submenu.find(ge=>ge.checked)?.id??"");Z(Fe,()=>Rt,(ge,Se)=>{Se(ge,{get value(){return e(Ce)},get"aria-label"(){return e(r).label},children:(rt,$t)=>{{let at=k(()=>e(r).submenu.filter(ot=>ot.checked!==void 0));me(rt,{get actions(){return e(at)},selection:"single",get menu(){return E()},get iconWeight(){return X()},get onClose(){return u()}})}},$$slots:{default:!0}})})}var We=L(Fe,2);{let Ce=k(()=>e(r).submenu.filter(ge=>ge.checked===void 0));me(We,{get actions(){return e(Ce)},get menu(){return E()},get iconWeight(){return X()},get onClose(){return u()}})}c(re,Ae)},z=re=>{me(re,{get actions(){return e(r).submenu},get menu(){return E()},get iconWeight(){return X()},get onClose(){return u()}})};M(l,re=>{e(r).selection==="single"?re(_):re(z,-1)})}var le=L(l,2);{var Oe=re=>{var Ae=qt(),Fe=y(Ae);Z(Fe,()=>Ke,(ge,Se)=>{Se(ge,{})});var We=L(Fe,2),Ce=_e(We,!0);oe(()=>{Ne(We,"id",`${we}-${e(r).id}-note`),xe(We,1,`type-caption px-2 py-1 ${ze}`),de(Ce,e(r).note)}),c(re,Ae)};M(le,re=>{e(r).note&&re(Oe)})}c(ve,t)},$$slots:{default:!0}})})}c(B,$)},$$slots:{default:!0}})}),c(g,C)},ue=g=>{var C=J(),P=y(C);{let I=k(()=>e(S)?O:void 0);Z(P,()=>Tt,(D,B)=>{B(D,{get leading(){return e(I)},get value(){return e(r).id},get disabled(){return e(j)},get"aria-describedby"(){return e(R)},closeOnSelect:!0,onSelect:()=>Q(e(r)),get"data-action-id"(){return e(r).id},children:(Y,$)=>{ne(Y,()=>e(r))},$$slots:{default:!0}})})}c(g,C)},a=g=>{var C=J(),P=y(C);{let I=k(()=>e(S)?O:void 0);Z(P,()=>Bt,(D,B)=>{B(D,{get leading(){return e(I)},get checked(){return e(r).checked},get disabled(){return e(j)},get"aria-describedby"(){return e(R)},closeOnSelect:!0,onSelect:()=>Q(e(r)),get"data-action-id"(){return e(r).id},children:(Y,$)=>{ne(Y,()=>e(r))},$$slots:{default:!0}})})}c(g,C)},n=g=>{var C=J(),P=y(C);{let I=k(()=>e(S)?O:void 0),D=k(()=>e(r).variant==="destructive");Z(P,()=>zt,(B,Y)=>{Y(B,{get leading(){return e(I)},get destructive(){return e(D)},get disabled(){return e(j)},get"aria-describedby"(){return e(R)},onSelect:()=>Q(e(r)),get"data-action-id"(){return e(r).id},children:($,pe)=>{ne($,()=>e(r))},$$slots:{default:!0}})})}c(g,C)};M(T,g=>{e(r).submenu?g(ae):A()==="single"&&e(r).checked!==void 0?g(ue,1):e(r).checked!==void 0?g(a,2):g(n,-1)})}c(i,b)},f=i=>{me(i,{get actions(){return e(r).submenu},get menu(){return E()},get iconWeight(){return X()},get onClose(){return u()}})},o=i=>{var b=Me(),T=y(b);{let a=k(()=>e(r).variant==="destructive"?"text-danger hover:text-danger":""),n=k(()=>e(r).submenu?e(F)===e(r).id:void 0);Mt(T,{variant:"ghost",size:"sm",get class(){return`w-full justify-start gap-2 ${e(a)??""}`},get disabled(){return e(j)},get"aria-describedby"(){return e(R)},get"aria-expanded"(){return e(n)},onclick:()=>e(r).submenu?V(F,e(F)===e(r).id?null:e(r).id,!0):Q(e(r)),children:(g,C)=>{var P=Gt(),I=y(P),D=Pe(I);Ie(D,()=>e(r)),De(I);var B=L(I,2);ne(B,()=>e(r));var Y=L(B,2);{var $=ee=>{{let te=k(()=>e(F)===e(r).id?bt:wt);Re(ee,{get icon(){return e(te)},size:12})}},pe=ee=>{var te=J(),fe=y(te);{let he=k(()=>e(r).checked?"checked":"empty");Z(fe,()=>Vt,(ve,ye)=>{ye(ve,{get state(){return e(he)}})})}c(ee,te)};M(Y,ee=>{e(r).submenu?ee($):e(r).checked!==void 0&&ee(pe,1)})}c(g,P)},$$slots:{default:!0}})}var ae=L(T,2);{var ue=a=>{var n=Zt(),g=Pe(n);me(g,{get actions(){return e(r).submenu},get menu(){return E()},get iconWeight(){return X()},get onClose(){return u()}});var C=L(g,2);{var P=I=>{var D=Kt(),B=_e(D,!0);oe(()=>{xe(D,1,`type-caption px-2 py-1 ${ze}`),de(B,e(r).note)}),c(I,D)};M(C,I=>{e(r).note&&I(P)})}De(n),c(a,n)};M(ae,a=>{e(r).submenu&&e(F)===e(r).id&&a(ue)})}c(i,b)};M(H,i=>{E()?i(m):e(r).id==="open-in"&&e(r).submenu?i(f,1):i(o,-1)})}var N=L(H,2);{var s=i=>{var b=Qt(),T=_e(b,!0);oe(()=>{Ne(b,"id",e(R)),de(T,e(r).disabledReason)}),c(i,b)};M(N,i=>{e(r).disabledReason&&i(s)})}c(p,q)}),c(be,se),tt(ce)}function Yt(be,d){if(new.target)return Qe({component:Yt,...be});et(d,!0);const we=()=>Ve(T,"$installedEditors$",ne),Ie=()=>Ve(ue,"$isWorkspaceHostLocal$",ne),[ne,ke]=nt();let E=h(d,"layout",7,"list"),X=h(d,"iconWeight",7),u=h(d,"filePath",7,""),A=h(d,"workspaceId",7,""),F=h(d,"isDirectory",7,!0),Q=h(d,"onDelete",7,void 0),ce=h(d,"onArchive",7,void 0),se=h(d,"onUnarchive",7,void 0),ie=h(d,"isArchived",7,!1),p=h(d,"onClose",7,void 0),r=h(d,"showDeleteOption",7,!0),O=h(d,"showArchiveOption",7,!1),S=h(d,"showPathCopy",7,!0),j=h(d,"showFileNameCopy",7,!1),R=h(d,"showFileActions",7,!0),q=h(d,"workspaceFolderPath",7,""),W=h(d,"isDiff",7,!1),x=h(d,"isWorkspaceRoot",7,!1),H=h(d,"additionalActions",23,()=>[]),m=h(d,"showDeleteFileOption",7,!1),f=h(d,"onFileDeleted",7,void 0);const o=gt("WorkspaceActionsMenu");let N=!1;dt(()=>{N=!0});function s(){N||p()?.()}const i=_t("externalEditors"),b=ct(A());He(()=>{b.set(A())});const T=ht(b),ae=k(we),ue=vt(b);let a=Ee(""),n=Ee(""),g=Ee(!1);ut(()=>{Je.dispatch(pt())}),He(()=>{u()&&A()?G("workspace:get",{id:A()}).then(t=>{if(t&&t.success&&t.data){const l=t.data,_=l.worktreePath||l.repositoryPath||l.path,z=q()==="__WORKSPACE_ROOT__"?_:q()||_;if(z){const le=z.replace(/\\/g,"/");x()?V(a,le,!0):Le(u())?V(a,u().replace(/\\/g,"/"),!0):V(a,`${le}/${u()}`.replace(/\/+/g,"/"),!0),V(n,le,!0),o.info("[WorkspaceActionsMenu] Resolved file path:",{filePath:u(),workspacePath:z,resolvedPath:e(a)})}else V(a,u()),V(n,""),l.status!=="archived"&&l.status!=="deleted"&&o.warn("[WorkspaceActionsMenu] No workspace path found:",l)}else V(a,u()),V(n,""),t?.error&&!t.error.includes("not found")&&o.warn("[WorkspaceActionsMenu] Workspace not available:",t)}).catch(t=>{V(a,u()),V(n,""),t?.message?.includes("not found")||o.error("[WorkspaceActionsMenu] Failed to resolve path:",t)}):(V(a,u()),o.info("[WorkspaceActionsMenu] Using filePath directly:",{filePath:u(),workspaceId:A()}))});async function C(){if(!e(a)){o.warn("[WorkspaceActionsMenu] No resolved path for VSCode");return}try{if(W()&&!F()){o.info("[WorkspaceActionsMenu] Opening diff in VSCode:",{resolvedPath:e(a)}),await G("vscode:open-git-diff",{filePath:e(a),workspacePath:e(n)||void 0}),s();return}let t=e(a);if(e(n))!F()&&!x()?t={folder:e(n),file:e(a)}:t=e(n);else if(!F()){const l=e(a).includes("\\")?"\\":"/",_=e(a).split(l);_.length>1&&(t={folder:_.slice(0,-1).join(l),file:e(a)})}await G("vscode:open",t),s()}catch(t){o.error("Failed to open in VSCode:",t),K.error(t instanceof Error?t.message:w.ui_workspaceActions_openFailed_error({name:"VS Code"}))}}async function P(){if(!e(a)){o.warn("[WorkspaceActionsMenu] No resolved path for JetBrains");return}try{let t=e(a);e(n)&&!F()?t={folder:e(n),file:e(a)}:e(n)&&(t=e(n)),await G("jetbrains:open",t),s()}catch(t){o.error("Failed to open in JetBrains:",t),K.error(t instanceof Error?t.message:w.ui_workspaceActions_openFailed_error({name:"JetBrains"}))}}async function I(){if(!e(a)){o.warn("[WorkspaceActionsMenu] No resolved path for Xcode");return}try{if(A()&&e(n)){Je.dispatch(ft(A(),e(n),F()?void 0:e(a))),s();return}let t=e(a);e(n)&&!F()?t={folder:e(n),file:e(a)}:e(n)&&(t={folder:e(n)}),await G("xcode:open",t),s()}catch(t){o.error("Failed to open in Xcode:",t),K.error(t instanceof Error?t.message:w.ui_workspaceActions_openFailed_error({name:"Xcode"}))}}async function D(t){if(o.info("[WorkspaceActionsMenu] openInEditor called",{editorId:t.id,appName:t.appName,handlerType:t.handlerType,resolvedPath:e(a),isDirectory:F()}),!e(a)){o.warn("[WorkspaceActionsMenu] openInEditor: No resolved path, aborting");return}const l=F()?e(a):e(a).substring(0,e(a).lastIndexOf("/"));o.info(`[WorkspaceActionsMenu] openInEditor: targetPath=${l}, handlerType=${t.handlerType}`);try{switch(t.handlerType){case"finder":o.info("[WorkspaceActionsMenu] openInEditor: Invoking shell:showItemInFolder"),await G("shell:showItemInFolder",{path:l});break;case"vscode":o.info("[WorkspaceActionsMenu] openInEditor: Delegating to openInVSCode"),await C();return;case"jetbrains":o.info("[WorkspaceActionsMenu] openInEditor: Delegating to openInJetBrains"),await P();return;case"xcode":o.info("[WorkspaceActionsMenu] openInEditor: Delegating to openInXcode"),await I();return;case"generic":default:{o.info(`[WorkspaceActionsMenu] openInEditor: Invoking external-editors:open for ${t.id}`);const _=await G("external-editors:open",{editorId:t.id,path:l});o.info("[WorkspaceActionsMenu] openInEditor: external-editors:open result",_);break}}s()}catch(_){o.error(`[WorkspaceActionsMenu] Failed to open in ${t.appName}:`,_),K.error(_ instanceof Error?_.message:w.ui_workspaceActions_openFailed_error({name:t.appName}))}}async function B(){if(!e(a)){o.warn("No resolved path for openWithOther");return}try{let t=e(a);F()&&e(n)&&(t=e(n));const l=await G("external-editors:open-with-other",{path:t});if(!l?.success){l?.error!=="No application selected"&&(o.error("Failed to open with other app:",l?.error),K.error(l?.error||w.ui_workspaceActions_openOtherFailed_error()));return}s()}catch(t){o.error("Failed to open with other app:",t),K.error(t instanceof Error?t.message:w.ui_workspaceActions_openOtherFailed_error())}}async function Y(){if(e(a))try{await navigator.clipboard.writeText(Ue(e(a))),s()}catch(t){o.error("Failed to copy path:",t)}}async function $(){if(u())try{let t=u().replace(/\\/g,"/");if(Le(u())&&e(n)){const l=e(n).endsWith("/")?e(n):e(n)+"/";t.startsWith(l)&&(t=t.slice(l.length))}await navigator.clipboard.writeText(Ue(t)),s()}catch(t){o.error("Failed to copy workspace path:",t)}}async function pe(){if(u())try{const t=u().split(/[/\\]/).pop()||"";await navigator.clipboard.writeText(t),s()}catch(t){o.error("Failed to copy file name:",t)}}function ee(){Q()&&(Q()(),s())}async function te(){if(!(!A()||!e(a)||e(g))){V(g,!0);try{const t=u().split(/[/\\]/).pop()||"file",l=e(a);let _="";try{_=(await G("file:read",{path:l,workspaceId:A()}))?.data?.content??""}catch{}const z=await G("file:delete",{path:l,workspaceId:A()});if(z?.success){f()?.(),s();const le=K.warning(w.ui_workspaceActions_deletedFile_label({name:t}),Ft({duration:15e3,action:{label:w.ui_workspaceActions_undo_label(),onClick:async()=>{try{await G("file:write",{path:l,content:_,workspaceId:A()}),mt("file:changed",{workspaceId:A(),type:"create",filePath:l}),K.dismiss(le)}catch(Oe){o.error("[WorkspaceActionsMenu] Failed to restore file",Oe),K.error(w.ui_workspaceActions_restoreFileFailed_error())}}}}))}else K.error(w.ui_workspaceActions_deleteFileFailedDetail_error({error:z?.error||w.ui_workspaceActions_unknown_error()}))}catch(t){o.error("[WorkspaceActionsMenu] Error deleting file",t),K.error(w.ui_workspaceActions_deleteFileFailed_error())}finally{V(g,!1)}}}function fe(){ie()&&se()?(se()(),s()):!ie()&&ce()&&(ce()(),s())}const he=k(()=>{const t=[];R()&&(i&&Ie()&&t.push({id:"open-in",label:w.ui_openCombo_openInApp_tooltip(),icon:Xe,onClick:()=>{},submenu:[...e(ae).map(_=>({id:`editor:${_.id}`,label:w.ui_workspaceActions_openIn_label({name:_.name}),editor:_,onClick:()=>{D(_)}})),{id:"choose-app",label:w.ui_workspaceActions_chooseApp_label(),icon:Xe,onClick:()=>{B()}}]}),S()&&t.push({id:"copy-absolute-path",label:w.ui_workspaceActions_copyAbsolutePath_label(),icon:qe,disabled:!e(a),dividerBefore:t.length>0,onClick:()=>{Y()}}),S()&&!x()&&t.push({id:"copy-relative-path",label:w.ui_workspaceActions_copyRelativePath_label(),icon:qe,disabled:!u(),onClick:()=>{$()}}),j()&&!F()&&t.push({id:"copy-file-name",label:w.ui_workspaceActions_copyFileName_label(),icon:kt,disabled:!u(),onClick:()=>{pe()}}));const l=_=>_.map(z=>({...z,submenu:z.submenu?l(z.submenu):void 0,onClick:()=>{z.onClick(),s()}}));return t.push(...l(H())),O()&&(ce()||se())&&t.push({id:"archive-workspace",label:ie()?w.ui_workspaceActions_unarchiveSpace_label():w.ui_workspaceActions_archiveSpace_label(),icon:ie()?yt:At,dividerBefore:t.length>0,onClick:fe}),r()&&Q()&&t.push({id:"delete-workspace",label:w.ui_workspaceActions_deleteSpace_label(),icon:Ge,variant:"destructive",dividerBefore:t.length>0&&t.at(-1)?.id!=="archive-workspace",onClick:ee}),m()&&!F()&&t.push({id:"delete-file",label:w.ui_workspaceActions_deleteFile_label(),icon:Ge,variant:"destructive",disabled:e(g)||!e(a)||!A(),dividerBefore:t.length>0,onClick:()=>{te()}}),t});var ve={get layout(){return E()},set layout(t="list"){E(t),v()},get iconWeight(){return X()},set iconWeight(t){X(t),v()},get filePath(){return u()},set filePath(t=""){u(t),v()},get workspaceId(){return A()},set workspaceId(t=""){A(t),v()},get isDirectory(){return F()},set isDirectory(t=!0){F(t),v()},get onDelete(){return Q()},set onDelete(t=void 0){Q(t),v()},get onArchive(){return ce()},set onArchive(t=void 0){ce(t),v()},get onUnarchive(){return se()},set onUnarchive(t=void 0){se(t),v()},get isArchived(){return ie()},set isArchived(t=!1){ie(t),v()},get onClose(){return p()},set onClose(t=void 0){p(t),v()},get showDeleteOption(){return r()},set showDeleteOption(t=!0){r(t),v()},get showArchiveOption(){return O()},set showArchiveOption(t=!1){O(t),v()},get showPathCopy(){return S()},set showPathCopy(t=!0){S(t),v()},get showFileNameCopy(){return j()},set showFileNameCopy(t=!1){j(t),v()},get showFileActions(){return R()},set showFileActions(t=!0){R(t),v()},get workspaceFolderPath(){return q()},set workspaceFolderPath(t=""){q(t),v()},get isDiff(){return W()},set isDiff(t=!1){W(t),v()},get isWorkspaceRoot(){return x()},set isWorkspaceRoot(t=!1){x(t),v()},get additionalActions(){return H()},set additionalActions(t=[]){H(t),v()},get showDeleteFileOption(){return m()},set showDeleteFileOption(t=!1){m(t),v()},get onFileDeleted(){return f()},set onFileDeleted(t=void 0){f(t),v()},$set:Ye,$on:(t,l)=>$e(d,t,l)};{let t=k(()=>E()!=="list");me(be,{get actions(){return e(he)},get menu(){return e(t)},get iconWeight(){return X()}})}var ye=tt(ve);return ke(),ye}export{Yt as default};
1
+ import{t as Qe,bo as h,bw as Ye,b as $e,bq as nt,bm as w,bs as Ve}from"./Fcr7AvC-.js";import{bo as st,bs as et,a7 as J,ay as y,aD as e,bS as L,W as c,a5 as Pe,bA as De,bH as V,bl as _e,b_ as oe,bO as de,bn as tt,bf as je,bV as Ee,aA as v,c9 as k,aB as U,be as it,b$ as lt,bj as dt,cd as ct,ca as He,bk as ut}from"./3SdAC2_C.js";import{i as G}from"./CL3a4Hm1.js";import{JH as Je,ni as pt,vh as ft}from"./D0qhIm1r.js";import{aM as ht}from"./OrDYwyck.js";import{cB as vt}from"./cD292w1o.js";import{c as gt}from"./ChTqQfQN.js";import{i as Le,t as Ue}from"./H2jLkRRS.js";import{w as _t}from"./Bqd7fdCF.js";import{d as mt}from"./B0Z-1lwJ.js";import{F as Re,aw as bt,ax as wt,cV as Xe,aZ as qe,bg as kt,ao as yt,an as At,cS as Ge}from"./ChHRVjww.js";import{m as K,w as Ft}from"./DkQdSPDN.js";import{s as Ne,f as xe,c as Wt}from"./BRCr02in.js";import{t as Ct}from"./CWfjuhY2.js";import{w as xt}from"./BAtAwQ72.js";import"./DRMe5Ypb.js";import{i as M}from"./BhYXv0ZM.js";import{g as It,e as Te}from"./CA6H1-bp.js";import{c as Z}from"./2z64ELW5.js";import{a as Pt,r as Dt}from"./B2NCDWQj.js";import{f as Mt,aa as Et}from"./Beq_QLuz.js";import{t as Be}from"./DAsc1V4f.js";import{h as Ke,k as Ot,j as St,R as Rt,i as Nt,g as Tt,c as Bt,e as zt}from"./D7KhILhs.js";import{M as Vt}from"./C2RnxEnO.js";import{m as ze}from"./Cz3WzTlQ.js";var jt=U('<img alt="" class="size-4"/>'),Ht=U('<span class="min-w-0 flex-1 text-left"><span class="block truncate"> </span> <span class="block text-muted-foreground" aria-hidden="true" data-menu-action-reason=""> </span></span>'),Jt=U("<span> </span>"),Lt=U('<span data-menu-action-detail=""> </span>'),Ut=U('<span aria-hidden="true"><!></span>'),Ze=U("<!> <!> <!>",1),Xt=U('<div class="my-1 h-px bg-border" role="separator"></div>'),Me=U("<!> <!>",1),qt=U('<!> <p data-menu-action-note=""> </p>',1),Gt=U('<span class="flex size-4 shrink-0 items-center justify-center" aria-hidden="true"><!></span> <!> <!>',1),Kt=U('<p data-menu-action-note=""> </p>'),Zt=U('<div class="pl-4"><!> <!></div>'),Qt=U('<span class="sr-only"> </span>');function me(be,d){const we=st();if(new.target)return Qe({component:me,...be});et(d,!0);const Ie=(p,r=je)=>{var O=J(),S=y(O);{var j=W=>{const x=k(()=>Pt(r().editor));var H=J(),m=y(H);{var f=s=>{var i=jt();oe(()=>Ne(i,"src",`data:image/png;base64,${r().editor.iconBase64??""}`)),c(s,i)},o=s=>{var i=J(),b=y(i);Z(b,()=>e(x),(T,ae)=>{ae(T,{size:16})}),c(s,i)},N=s=>{{let i=k(()=>Dt(r().editor.category));Re(s,{get icon(){return e(i)},size:16})}};M(m,s=>{r().editor.iconBase64?s(f):e(x)?s(o,1):s(N,-1)})}c(W,H)},R=W=>{var x=J(),H=y(x);Ct(H,()=>r().iconSnippet),c(W,x)},q=W=>{{let x=k(()=>r().variant==="destructive"?"text-current":"text-muted-foreground");Re(W,{get icon(){return r().icon},get weight(){return X()},size:16,get class(){return e(x)}})}};M(S,W=>{r().editor?W(j):r().iconSnippet?W(R,1):r().icon&&W(q,2)})}c(p,O)},ne=(p,r=je)=>{var O=Ze(),S=y(O);{var j=m=>{var f=Ht(),o=Pe(f),N=_e(o,!0);Te(o,(b,T)=>Be?.(b,T),()=>r().label);var s=L(o,2),i=_e(s,!0);De(f),oe(()=>{de(N,r().label),de(i,r().disabledReason)}),c(m,f)},R=m=>{var f=Jt(),o=_e(f,!0);Te(f,(N,s)=>Be?.(N,s),()=>r().label),oe(()=>{xe(f,1,`min-w-0 truncate text-left ${r().detail?"flex-[1_0_auto]":"flex-1"}`),de(o,r().label)}),c(m,f)};M(S,m=>{r().disabledReason?m(j):m(R,-1)})}var q=L(S,2);{var W=m=>{var f=Lt(),o=_e(f,!0);Te(f,(N,s)=>Be?.(N,s),()=>r().detail),oe(()=>{xe(f,1,`ml-4 min-w-0 truncate ${(r().detailTone==="danger"?"text-danger":ze)??""}`),de(o,r().detail)}),c(m,f)};M(q,m=>{r().detail&&m(W)})}var x=L(q,2);{var H=m=>{var f=Ut(),o=Pe(f);Et(o,{children:(N,s)=>{it();var i=lt();oe(b=>de(i,b),[()=>xt(r().shortcut)]),c(N,i)},$$slots:{default:!0}}),De(f),oe(()=>xe(f,1,Wt(E()?"ml-4 flex h-lh shrink-0 items-center":"ml-4"))),c(m,f)};M(x,m=>{r().shortcut&&m(H)})}c(p,O)};let ke=h(d,"actions",7),E=h(d,"menu",7),X=h(d,"iconWeight",7),u=h(d,"onClose",7),A=h(d,"selection",7),F=Ee(null);function Q(p){p.disabled||p.disabledReason!==void 0||(p.onClick(),u()?.())}var ce={get actions(){return ke()},set actions(p){ke(p),v()},get menu(){return E()},set menu(p){E(p),v()},get iconWeight(){return X()},set iconWeight(p){X(p),v()},get onClose(){return u()},set onClose(p){u(p),v()},get selection(){return A()},set selection(p){A(p),v()},$set:Ye,$on:(p,r)=>$e(d,p,r)},se=J(),ie=y(se);return It(ie,17,ke,p=>p.id,(p,r)=>{const O=i=>{Ie(i,()=>e(r))},S=k(()=>!!(e(r).editor||e(r).iconSnippet||e(r).icon)),j=k(()=>e(r).disabled||e(r).disabledReason!==void 0),R=k(()=>e(r).disabledReason?`${we}-${e(r).id}-reason`:void 0);var q=Ze(),W=y(q);{var x=i=>{var b=J(),T=y(b);{var ae=a=>{var n=J(),g=y(n);Z(g,()=>Ke,(C,P)=>{P(C,{})}),c(a,n)},ue=a=>{var n=Xt();c(a,n)};M(T,a=>{E()?a(ae):a(ue,-1)})}c(i,b)};M(W,i=>{e(r).dividerBefore&&i(x)})}var H=L(W,2);{var m=i=>{var b=J(),T=y(b);{var ae=g=>{var C=J(),P=y(C);Z(P,()=>Nt,(I,D)=>{D(I,{children:(B,Y)=>{var $=Me(),pe=y($);{let te=k(()=>e(S)?O:void 0);Z(pe,()=>Ot,(fe,he)=>{he(fe,{get leading(){return e(te)},get disabled(){return e(j)},get"aria-describedby"(){return e(R)},get"data-action-id"(){return e(r).id},children:(ve,ye)=>{ne(ve,()=>e(r))},$$slots:{default:!0}})})}var ee=L(pe,2);{let te=k(()=>e(r).note?`${we}-${e(r).id}-note`:void 0);Z(ee,()=>St,(fe,he)=>{he(fe,{class:"w-60",get"aria-describedby"(){return e(te)},children:(ve,ye)=>{var t=Me(),l=y(t);{var _=re=>{var Ae=Me(),Fe=y(Ae);{let Ce=k(()=>e(r).submenu.find(ge=>ge.checked)?.id??"");Z(Fe,()=>Rt,(ge,Se)=>{Se(ge,{get value(){return e(Ce)},get"aria-label"(){return e(r).label},children:(rt,$t)=>{{let at=k(()=>e(r).submenu.filter(ot=>ot.checked!==void 0));me(rt,{get actions(){return e(at)},selection:"single",get menu(){return E()},get iconWeight(){return X()},get onClose(){return u()}})}},$$slots:{default:!0}})})}var We=L(Fe,2);{let Ce=k(()=>e(r).submenu.filter(ge=>ge.checked===void 0));me(We,{get actions(){return e(Ce)},get menu(){return E()},get iconWeight(){return X()},get onClose(){return u()}})}c(re,Ae)},z=re=>{me(re,{get actions(){return e(r).submenu},get menu(){return E()},get iconWeight(){return X()},get onClose(){return u()}})};M(l,re=>{e(r).selection==="single"?re(_):re(z,-1)})}var le=L(l,2);{var Oe=re=>{var Ae=qt(),Fe=y(Ae);Z(Fe,()=>Ke,(ge,Se)=>{Se(ge,{})});var We=L(Fe,2),Ce=_e(We,!0);oe(()=>{Ne(We,"id",`${we}-${e(r).id}-note`),xe(We,1,`type-caption px-2 py-1 ${ze}`),de(Ce,e(r).note)}),c(re,Ae)};M(le,re=>{e(r).note&&re(Oe)})}c(ve,t)},$$slots:{default:!0}})})}c(B,$)},$$slots:{default:!0}})}),c(g,C)},ue=g=>{var C=J(),P=y(C);{let I=k(()=>e(S)?O:void 0);Z(P,()=>Tt,(D,B)=>{B(D,{get leading(){return e(I)},get value(){return e(r).id},get disabled(){return e(j)},get"aria-describedby"(){return e(R)},closeOnSelect:!0,onSelect:()=>Q(e(r)),get"data-action-id"(){return e(r).id},children:(Y,$)=>{ne(Y,()=>e(r))},$$slots:{default:!0}})})}c(g,C)},a=g=>{var C=J(),P=y(C);{let I=k(()=>e(S)?O:void 0);Z(P,()=>Bt,(D,B)=>{B(D,{get leading(){return e(I)},get checked(){return e(r).checked},get disabled(){return e(j)},get"aria-describedby"(){return e(R)},closeOnSelect:!0,onSelect:()=>Q(e(r)),get"data-action-id"(){return e(r).id},children:(Y,$)=>{ne(Y,()=>e(r))},$$slots:{default:!0}})})}c(g,C)},n=g=>{var C=J(),P=y(C);{let I=k(()=>e(S)?O:void 0),D=k(()=>e(r).variant==="destructive");Z(P,()=>zt,(B,Y)=>{Y(B,{get leading(){return e(I)},get destructive(){return e(D)},get disabled(){return e(j)},get"aria-describedby"(){return e(R)},onSelect:()=>Q(e(r)),get"data-action-id"(){return e(r).id},children:($,pe)=>{ne($,()=>e(r))},$$slots:{default:!0}})})}c(g,C)};M(T,g=>{e(r).submenu?g(ae):A()==="single"&&e(r).checked!==void 0?g(ue,1):e(r).checked!==void 0?g(a,2):g(n,-1)})}c(i,b)},f=i=>{me(i,{get actions(){return e(r).submenu},get menu(){return E()},get iconWeight(){return X()},get onClose(){return u()}})},o=i=>{var b=Me(),T=y(b);{let a=k(()=>e(r).variant==="destructive"?"text-danger hover:text-danger":""),n=k(()=>e(r).submenu?e(F)===e(r).id:void 0);Mt(T,{variant:"ghost",size:"sm",get class(){return`w-full justify-start gap-2 ${e(a)??""}`},get disabled(){return e(j)},get"aria-describedby"(){return e(R)},get"aria-expanded"(){return e(n)},onclick:()=>e(r).submenu?V(F,e(F)===e(r).id?null:e(r).id,!0):Q(e(r)),children:(g,C)=>{var P=Gt(),I=y(P),D=Pe(I);Ie(D,()=>e(r)),De(I);var B=L(I,2);ne(B,()=>e(r));var Y=L(B,2);{var $=ee=>{{let te=k(()=>e(F)===e(r).id?bt:wt);Re(ee,{get icon(){return e(te)},size:12})}},pe=ee=>{var te=J(),fe=y(te);{let he=k(()=>e(r).checked?"checked":"empty");Z(fe,()=>Vt,(ve,ye)=>{ye(ve,{get state(){return e(he)}})})}c(ee,te)};M(Y,ee=>{e(r).submenu?ee($):e(r).checked!==void 0&&ee(pe,1)})}c(g,P)},$$slots:{default:!0}})}var ae=L(T,2);{var ue=a=>{var n=Zt(),g=Pe(n);me(g,{get actions(){return e(r).submenu},get menu(){return E()},get iconWeight(){return X()},get onClose(){return u()}});var C=L(g,2);{var P=I=>{var D=Kt(),B=_e(D,!0);oe(()=>{xe(D,1,`type-caption px-2 py-1 ${ze}`),de(B,e(r).note)}),c(I,D)};M(C,I=>{e(r).note&&I(P)})}De(n),c(a,n)};M(ae,a=>{e(r).submenu&&e(F)===e(r).id&&a(ue)})}c(i,b)};M(H,i=>{E()?i(m):e(r).id==="open-in"&&e(r).submenu?i(f,1):i(o,-1)})}var N=L(H,2);{var s=i=>{var b=Qt(),T=_e(b,!0);oe(()=>{Ne(b,"id",e(R)),de(T,e(r).disabledReason)}),c(i,b)};M(N,i=>{e(r).disabledReason&&i(s)})}c(p,q)}),c(be,se),tt(ce)}function Yt(be,d){if(new.target)return Qe({component:Yt,...be});et(d,!0);const we=()=>Ve(T,"$installedEditors$",ne),Ie=()=>Ve(ue,"$isWorkspaceHostLocal$",ne),[ne,ke]=nt();let E=h(d,"layout",7,"list"),X=h(d,"iconWeight",7),u=h(d,"filePath",7,""),A=h(d,"workspaceId",7,""),F=h(d,"isDirectory",7,!0),Q=h(d,"onDelete",7,void 0),ce=h(d,"onArchive",7,void 0),se=h(d,"onUnarchive",7,void 0),ie=h(d,"isArchived",7,!1),p=h(d,"onClose",7,void 0),r=h(d,"showDeleteOption",7,!0),O=h(d,"showArchiveOption",7,!1),S=h(d,"showPathCopy",7,!0),j=h(d,"showFileNameCopy",7,!1),R=h(d,"showFileActions",7,!0),q=h(d,"workspaceFolderPath",7,""),W=h(d,"isDiff",7,!1),x=h(d,"isWorkspaceRoot",7,!1),H=h(d,"additionalActions",23,()=>[]),m=h(d,"showDeleteFileOption",7,!1),f=h(d,"onFileDeleted",7,void 0);const o=gt("WorkspaceActionsMenu");let N=!1;dt(()=>{N=!0});function s(){N||p()?.()}const i=_t("externalEditors"),b=ct(A());He(()=>{b.set(A())});const T=ht(b),ae=k(we),ue=vt(b);let a=Ee(""),n=Ee(""),g=Ee(!1);ut(()=>{Je.dispatch(pt())}),He(()=>{u()&&A()?G("workspace:get",{id:A()}).then(t=>{if(t&&t.success&&t.data){const l=t.data,_=l.worktreePath||l.repositoryPath||l.path,z=q()==="__WORKSPACE_ROOT__"?_:q()||_;if(z){const le=z.replace(/\\/g,"/");x()?V(a,le,!0):Le(u())?V(a,u().replace(/\\/g,"/"),!0):V(a,`${le}/${u()}`.replace(/\/+/g,"/"),!0),V(n,le,!0),o.info("[WorkspaceActionsMenu] Resolved file path:",{filePath:u(),workspacePath:z,resolvedPath:e(a)})}else V(a,u()),V(n,""),l.status!=="archived"&&l.status!=="deleted"&&o.warn("[WorkspaceActionsMenu] No workspace path found:",l)}else V(a,u()),V(n,""),t?.error&&!t.error.includes("not found")&&o.warn("[WorkspaceActionsMenu] Workspace not available:",t)}).catch(t=>{V(a,u()),V(n,""),t?.message?.includes("not found")||o.error("[WorkspaceActionsMenu] Failed to resolve path:",t)}):(V(a,u()),o.info("[WorkspaceActionsMenu] Using filePath directly:",{filePath:u(),workspaceId:A()}))});async function C(){if(!e(a)){o.warn("[WorkspaceActionsMenu] No resolved path for VSCode");return}try{if(W()&&!F()){o.info("[WorkspaceActionsMenu] Opening diff in VSCode:",{resolvedPath:e(a)}),await G("vscode:open-git-diff",{filePath:e(a),workspacePath:e(n)||void 0}),s();return}let t=e(a);if(e(n))!F()&&!x()?t={folder:e(n),file:e(a)}:t=e(n);else if(!F()){const l=e(a).includes("\\")?"\\":"/",_=e(a).split(l);_.length>1&&(t={folder:_.slice(0,-1).join(l),file:e(a)})}await G("vscode:open",t),s()}catch(t){o.error("Failed to open in VSCode:",t),K.error(t instanceof Error?t.message:w.ui_workspaceActions_openFailed_error({name:"VS Code"}))}}async function P(){if(!e(a)){o.warn("[WorkspaceActionsMenu] No resolved path for JetBrains");return}try{let t=e(a);e(n)&&!F()?t={folder:e(n),file:e(a)}:e(n)&&(t=e(n)),await G("jetbrains:open",t),s()}catch(t){o.error("Failed to open in JetBrains:",t),K.error(t instanceof Error?t.message:w.ui_workspaceActions_openFailed_error({name:"JetBrains"}))}}async function I(){if(!e(a)){o.warn("[WorkspaceActionsMenu] No resolved path for Xcode");return}try{if(A()&&e(n)){Je.dispatch(ft(A(),e(n),F()?void 0:e(a))),s();return}let t=e(a);e(n)&&!F()?t={folder:e(n),file:e(a)}:e(n)&&(t={folder:e(n)}),await G("xcode:open",t),s()}catch(t){o.error("Failed to open in Xcode:",t),K.error(t instanceof Error?t.message:w.ui_workspaceActions_openFailed_error({name:"Xcode"}))}}async function D(t){if(o.info("[WorkspaceActionsMenu] openInEditor called",{editorId:t.id,appName:t.appName,handlerType:t.handlerType,resolvedPath:e(a),isDirectory:F()}),!e(a)){o.warn("[WorkspaceActionsMenu] openInEditor: No resolved path, aborting");return}const l=F()?e(a):e(a).substring(0,e(a).lastIndexOf("/"));o.info(`[WorkspaceActionsMenu] openInEditor: targetPath=${l}, handlerType=${t.handlerType}`);try{switch(t.handlerType){case"finder":o.info("[WorkspaceActionsMenu] openInEditor: Invoking shell:showItemInFolder"),await G("shell:showItemInFolder",{path:l});break;case"vscode":o.info("[WorkspaceActionsMenu] openInEditor: Delegating to openInVSCode"),await C();return;case"jetbrains":o.info("[WorkspaceActionsMenu] openInEditor: Delegating to openInJetBrains"),await P();return;case"xcode":o.info("[WorkspaceActionsMenu] openInEditor: Delegating to openInXcode"),await I();return;case"generic":default:{o.info(`[WorkspaceActionsMenu] openInEditor: Invoking external-editors:open for ${t.id}`);const _=await G("external-editors:open",{editorId:t.id,path:l});o.info("[WorkspaceActionsMenu] openInEditor: external-editors:open result",_);break}}s()}catch(_){o.error(`[WorkspaceActionsMenu] Failed to open in ${t.appName}:`,_),K.error(_ instanceof Error?_.message:w.ui_workspaceActions_openFailed_error({name:t.appName}))}}async function B(){if(!e(a)){o.warn("No resolved path for openWithOther");return}try{let t=e(a);F()&&e(n)&&(t=e(n));const l=await G("external-editors:open-with-other",{path:t});if(!l?.success){l?.error!=="No application selected"&&(o.error("Failed to open with other app:",l?.error),K.error(l?.error||w.ui_workspaceActions_openOtherFailed_error()));return}s()}catch(t){o.error("Failed to open with other app:",t),K.error(t instanceof Error?t.message:w.ui_workspaceActions_openOtherFailed_error())}}async function Y(){if(e(a))try{await navigator.clipboard.writeText(Ue(e(a))),s()}catch(t){o.error("Failed to copy path:",t)}}async function $(){if(u())try{let t=u().replace(/\\/g,"/");if(Le(u())&&e(n)){const l=e(n).endsWith("/")?e(n):e(n)+"/";t.startsWith(l)&&(t=t.slice(l.length))}await navigator.clipboard.writeText(Ue(t)),s()}catch(t){o.error("Failed to copy workspace path:",t)}}async function pe(){if(u())try{const t=u().split(/[/\\]/).pop()||"";await navigator.clipboard.writeText(t),s()}catch(t){o.error("Failed to copy file name:",t)}}function ee(){Q()&&(Q()(),s())}async function te(){if(!(!A()||!e(a)||e(g))){V(g,!0);try{const t=u().split(/[/\\]/).pop()||"file",l=e(a);let _="";try{_=(await G("file:read",{path:l,workspaceId:A()}))?.data?.content??""}catch{}const z=await G("file:delete",{path:l,workspaceId:A()});if(z?.success){f()?.(),s();const le=K.warning(w.ui_workspaceActions_deletedFile_label({name:t}),Ft({duration:15e3,action:{label:w.ui_workspaceActions_undo_label(),onClick:async()=>{try{await G("file:write",{path:l,content:_,workspaceId:A()}),mt("file:changed",{workspaceId:A(),type:"create",filePath:l}),K.dismiss(le)}catch(Oe){o.error("[WorkspaceActionsMenu] Failed to restore file",Oe),K.error(w.ui_workspaceActions_restoreFileFailed_error())}}}}))}else K.error(w.ui_workspaceActions_deleteFileFailedDetail_error({error:z?.error||w.ui_workspaceActions_unknown_error()}))}catch(t){o.error("[WorkspaceActionsMenu] Error deleting file",t),K.error(w.ui_workspaceActions_deleteFileFailed_error())}finally{V(g,!1)}}}function fe(){ie()&&se()?(se()(),s()):!ie()&&ce()&&(ce()(),s())}const he=k(()=>{const t=[];R()&&(i&&Ie()&&t.push({id:"open-in",label:w.ui_openCombo_openInApp_tooltip(),icon:Xe,onClick:()=>{},submenu:[...e(ae).map(_=>({id:`editor:${_.id}`,label:w.ui_workspaceActions_openIn_label({name:_.name}),editor:_,onClick:()=>{D(_)}})),{id:"choose-app",label:w.ui_workspaceActions_chooseApp_label(),icon:Xe,onClick:()=>{B()}}]}),S()&&t.push({id:"copy-absolute-path",label:w.ui_workspaceActions_copyAbsolutePath_label(),icon:qe,disabled:!e(a),dividerBefore:t.length>0,onClick:()=>{Y()}}),S()&&!x()&&t.push({id:"copy-relative-path",label:w.ui_workspaceActions_copyRelativePath_label(),icon:qe,disabled:!u(),onClick:()=>{$()}}),j()&&!F()&&t.push({id:"copy-file-name",label:w.ui_workspaceActions_copyFileName_label(),icon:kt,disabled:!u(),onClick:()=>{pe()}}));const l=_=>_.map(z=>({...z,submenu:z.submenu?l(z.submenu):void 0,onClick:()=>{z.onClick(),s()}}));return t.push(...l(H())),O()&&(ce()||se())&&t.push({id:"archive-workspace",label:ie()?w.ui_workspaceActions_unarchiveSpace_label():w.ui_workspaceActions_archiveSpace_label(),icon:ie()?yt:At,dividerBefore:t.length>0,onClick:fe}),r()&&Q()&&t.push({id:"delete-workspace",label:w.ui_workspaceActions_deleteSpace_label(),icon:Ge,variant:"destructive",dividerBefore:t.length>0&&t.at(-1)?.id!=="archive-workspace",onClick:ee}),m()&&!F()&&t.push({id:"delete-file",label:w.ui_workspaceActions_deleteFile_label(),icon:Ge,variant:"destructive",disabled:e(g)||!e(a)||!A(),dividerBefore:t.length>0,onClick:()=>{te()}}),t});var ve={get layout(){return E()},set layout(t="list"){E(t),v()},get iconWeight(){return X()},set iconWeight(t){X(t),v()},get filePath(){return u()},set filePath(t=""){u(t),v()},get workspaceId(){return A()},set workspaceId(t=""){A(t),v()},get isDirectory(){return F()},set isDirectory(t=!0){F(t),v()},get onDelete(){return Q()},set onDelete(t=void 0){Q(t),v()},get onArchive(){return ce()},set onArchive(t=void 0){ce(t),v()},get onUnarchive(){return se()},set onUnarchive(t=void 0){se(t),v()},get isArchived(){return ie()},set isArchived(t=!1){ie(t),v()},get onClose(){return p()},set onClose(t=void 0){p(t),v()},get showDeleteOption(){return r()},set showDeleteOption(t=!0){r(t),v()},get showArchiveOption(){return O()},set showArchiveOption(t=!1){O(t),v()},get showPathCopy(){return S()},set showPathCopy(t=!0){S(t),v()},get showFileNameCopy(){return j()},set showFileNameCopy(t=!1){j(t),v()},get showFileActions(){return R()},set showFileActions(t=!0){R(t),v()},get workspaceFolderPath(){return q()},set workspaceFolderPath(t=""){q(t),v()},get isDiff(){return W()},set isDiff(t=!1){W(t),v()},get isWorkspaceRoot(){return x()},set isWorkspaceRoot(t=!1){x(t),v()},get additionalActions(){return H()},set additionalActions(t=[]){H(t),v()},get showDeleteFileOption(){return m()},set showDeleteFileOption(t=!1){m(t),v()},get onFileDeleted(){return f()},set onFileDeleted(t=void 0){f(t),v()},$set:Ye,$on:(t,l)=>$e(d,t,l)};{let t=k(()=>E()!=="list");me(be,{get actions(){return e(he)},get menu(){return e(t)},get iconWeight(){return X()}})}var ye=tt(ve);return ke(),ye}export{Yt as default};
@@ -1,4 +1,4 @@
1
- var z1=Object.defineProperty;var js=t=>{throw TypeError(t)};var R1=(t,e,r)=>e in t?z1(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r;var le=(t,e,r)=>R1(t,typeof e!="symbol"?e+"":e,r),D1=(t,e,r)=>e.has(t)||js("Cannot "+r);var Vs=(t,e,r)=>e.has(t)?js("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r);var tn=(t,e,r)=>(D1(t,e,"access private method"),r);import{cR as Vt,b4 as N1,dJ as Xl,a7 as _n,a5 as Ia,a6 as P1,a4 as _1,aa as L1,am as O1,a1 as $1,ea as B1,X as q1,bn as Yl,cU as qr,dI as Zl,b3 as F1,b8 as H1,cC as U1,cS as W1,cn as G1,dD as si,e2 as j1,dX as V1,aK as X0,ax as K1,aF as _i,dH as Ql,ee as Jl,dV as X1,ed as Y1}from"./cD292w1o.js";import{D as Ks,b3 as Z1,bd as Q1,aB as J1}from"./B3ZeLze4.js";import{M as eh,G as hn,I as th}from"./Bqd7fdCF.js";import{zz as y0,JH as E,n_ as ve,nZ as xe,aU as rh,m as ec,I as De,br as gn,kf as Li,mf as w0,ar as Xt,me as Xs,mo as Ys,ml as Zs,jO as tc,gA as oi,I2 as nh,tK as ah,B1 as ih,p1 as sh,n3 as k0,CB as oh,iO as lh,my as ch,m9 as uh}from"./D0qhIm1r.js";import{bm as ie}from"./Fcr7AvC-.js";import{l as rt}from"./C7b3vXLD.js";import{m as hh,f as Tr}from"./B0SSzYpD.js";import{a as vn}from"./BdWqymET.js";import{o as pe,r as Kt,e as bn,s as V,_ as Je,l as yn,g as dh,n as Le,c as dr,b as Ve,u as ph,d as mh}from"./CIyUrgF0.js";import{j as rc}from"./uXuxG9cN.js";import{u as fh}from"./BwweojP5.js";import{selectActiveWorkspaceIds as gh}from"./_IjN0Lbt.js";import{i as je}from"./CL3a4Hm1.js";import{l as za,c as Oi}from"./ChTqQfQN.js";import"./CDCAMh6o.js";import{e as vh,h as Er}from"./DONrLvvt.js";import{h as wn}from"./BAtAwQ72.js";import{i as Qs}from"./BBWuirRW.js";import{f as $i,o as nc,p as ac,h as bh,m as ic,i as yh,k as wh}from"./BeZe2Rt-.js";const Ze=[];for(let t=0;t<256;++t)Ze.push((t+256).toString(16).slice(1));function kh(t,e=0){return(Ze[t[e+0]]+Ze[t[e+1]]+Ze[t[e+2]]+Ze[t[e+3]]+"-"+Ze[t[e+4]]+Ze[t[e+5]]+"-"+Ze[t[e+6]]+Ze[t[e+7]]+"-"+Ze[t[e+8]]+Ze[t[e+9]]+"-"+Ze[t[e+10]]+Ze[t[e+11]]+Ze[t[e+12]]+Ze[t[e+13]]+Ze[t[e+14]]+Ze[t[e+15]]).toLowerCase()}const xh=new Uint8Array(16);function Sh(){return crypto.getRandomValues(xh)}function Bi(t,e,r){return crypto.randomUUID?crypto.randomUUID():Ah(t)}function Ah(t,e,r){t=t||{};const n=t.random??t.rng?.()??Sh();if(n.length<16)throw new Error("Random bytes length must be >= 16");return n[6]=n[6]&15|64,n[8]=n[8]&63|128,kh(n)}function qi(t,e){if(t.repositoryIdentity===null)return null;if(t.repositoryIdentity){const{provider:a,instanceBaseUrl:i,projectPath:s}=t.repositoryIdentity,o=qi({...t,repositoryIdentity:void 0,githubUrl:`${i}/${s}`},a==="gitlab"?i:void 0);return o?.provider===a?o:null}const r=t.githubUrl;if(!r)return null;const n=/^(?:https:\/\/github\.com\/|git@github\.com:)([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+?)(?:\.git)?\/?$/i.exec(r);return n&&!n.slice(1).some(a=>a==="."||a==="..")?{provider:"github",instanceBaseUrl:"https://github.com",projectPath:`${n[1]}/${n[2]}`}:e?eh(r.replace(/\.git\/?$/,""),e):null}function f3(t,e){return t.type==="local"?t.plainFolder?"folder":"local":qi(t,e)?.provider==="gitlab"?"gitlab":"github"}function sc(t){const e=t.split(/[\\/]/).filter(Boolean);return e[e.length-1]??""}function g3(t){if(t.type!=="local")return{ownerPrefix:t.owner,primary:t.name};const e=sc(t.path)||t.name,r=t.owner?`${t.owner}/${t.name}`:void 0;return{primary:e,suffix:r}}function v3(t){return t.type==="local"&&t.path?t.path:void 0}const Th=["/.clones/","/.repo-cache/"];function b3(t){const e=t.replaceAll("\\","/");return Th.some(r=>e.includes(r))}function y3(t){const e=new Set;for(const r of t){const{repositoryPath:n,worktreePath:a}=r;n&&a&&n===a&&e.add(n)}return e}function Eh(t){return t.includes("\\")||t.includes(":")||t.startsWith("/")?void 0:/^([^/]+)\/[^/]+$/.exec(t)?.[1]}function w3(t,e){const{selectedValue:r,selectedRepoType:n,confirmedGithubUrl:a}=t;if(!(n!=="github"||!r)){if(a){const i=e(a)?.owner;if(i)return i}return e(r)?.owner??Eh(r)}}function k3(t,e){const r=e.trim().toLowerCase();return r===""?!0:[t.name,t.path,sc(t.path),t.owner,t.owner?`${t.owner}/${t.name}`:void 0].some(a=>a?.toLowerCase().includes(r)??!1)}const Ch="known-repos",Mh=6e4;function Ih({saved:t,source:e,dismissed:r,mode:n}){if(!e)return[...t];const a=new Map;if(n==="all")for(const s of[...e.repos,...t]){const o=y0(s);a.has(o)||a.set(o,s)}else{for(const s of t)a.set(y0(s),s);for(const s of e.repos)a.set(y0(s),s)}const i=[...a.values()].filter(s=>!r[y0(s)]);return n==="all"?i:i.slice(0,9)}function x3(t){const e=t.lastUsedAt?Date.parse(t.lastUsedAt):NaN;return Number.isFinite(e)?e:0}function S3({visible:t,admission:e,entry:r,readyAt:n,now:a}){return!t||!e?"skip":!r||r.admission!==e?"load":r.status==="pending"?"reuse":r.status==="ready"&&n?.requestId===r.requestId&&a-n.at<Mh?"skip":"load"}function A3(t,e){if(t.type==="local")return t.plainFolder?{repoPath:t.path,plainFolder:!0}:{repoPath:t.path};const r=qi(t,e);return r?.provider==="gitlab"?{repositoryCheckoutDraft:{instanceBaseUrl:r.instanceBaseUrl,projectPath:r.projectPath}}:r?{githubUrl:`https://github.com/${r.projectPath}`,exactRemote:!0}:{githubUrl:t.githubUrl||`https://github.com/${t.path}`,exactRemote:!0}}function zh({compactFormState:t,lastSubmittedAgent:e,specialists:r,orchestratorId:n}){if(t?.isTeamMode??e?.isTeamMode??!1)return n;const i=o=>r.some(c=>c.id===o),s=t?.selectedSpecialist!==void 0?t.selectedSpecialist:e?.selectedSpecialist!==void 0?e.selectedSpecialist:i(Ks)?Ks:null;return s===null||!i(s)?null:s}const T3=E.createSelector(t=>t.workspaceInitializer.hydrated),E3=E.createSelector(t=>t.workspaceInitializer.compactFormState),C3=E.createSelector(t=>t.workspaceInitializer.onboardingFormState),M3=E.createSelector(t=>t.workspaceInitializer.lastSelectedRepo),I3=E.createSelector(t=>t.workspaceInitializer.branchByRepo),z3=E.createSelector(t=>t.workspaceInitializer.defaultParentPath),R3=E.createSelector(t=>ve(t.workspaceInitializer.recentRepos)),D3=E.createSelector((t,e)=>xe(t.workspaceInitializer.recentRepoRefreshes,e)),N3=E.createSelector((t,e)=>xe(t.workspaceInitializer.directoryStatusChecks,e)),P3=E.createSelector(t=>t.workspaceInitializer.dismissedRecentRepoKeys),_3=E.createSelector(t=>ve(t.workspaceInitializer.remoteSetups)),L3=E.createSelector(t=>t.workspaceInitializer.lastSubmittedAgent),O3=E.createSelector(t=>t.workspaceInitializer.agentByRepo),$3=E.createSelector(t=>t.workspaceInitializer.recentSpecialistIds),B3=E.createSelector((t,e)=>t.workspaceInitializer.agentByRepo[e]??null),q3=E.createSelector(t=>t.workspaceInitializer.pendingGitHubPrefill),F3=E.createSelector((t,e)=>({restore:xe(t.workspaceInitializer.draftRestores,e),clear:xe(t.workspaceInitializer.draftClears,e)})),H3=E.createSelector((t,e,r)=>{const n=xe(t.workspaceInitializer.initializationOutcomes,e);return n?.resourceId===r?n:void 0}),U3=E.createSelector((t,e)=>xe(t.workspaceInitializer.initializationOutcomes,e)),W3=E.createSelector((t,e)=>xe(t.workspaceInitializer.initializationResumes,e)),G3=E.createSelector(t=>zh({compactFormState:t.workspaceInitializer.compactFormState,lastSubmittedAgent:t.workspaceInitializer.lastSubmittedAgent,specialists:Q1.select(t),orchestratorId:Z1.select(t)?.id??null})),Rh=E.createSelector(t=>{const e=t.workspaceInitializer.gitCheckRequest,r=Vt.select(t);return e&&r&&N1.select(t)?JSON.stringify([r,e]):null}),j3=E.createSelector(t=>{const e=Rh.select(t),r=t.workspaceInitializer.gitCheck;return e&&r?.context===e?r.available:null}),Dh=E.createSelector(t=>{const e=xe(t.workspaceInitializer.recentRepoRefreshes,Ch),r=Vt.select(t);return Ih({saved:ve(t.workspaceInitializer.recentRepos),source:e&&r&&e.admission===r?e:null,dismissed:t.workspaceInitializer.dismissedRecentRepoKeys,mode:"all"})}),V3=E.createSelector(t=>Xl.select(t)?Dh.select(t):[]),K3=E.createSelector(t=>J1.select(t)||void 0),Js="workspace-debug-flags",x0={enableCreationAnimation:!0,animationDuration:300,enablePageTransitions:!0,enableComponentTransitions:!0,showDebugInfo:!1,showPerformanceMetrics:!1,logStateChanges:!1,enableAutofocus:!0,enableBranchCaching:!0,enableFormPersistence:!0,simulateSlowNetwork:!1,simulateErrors:!1,networkDelay:0};class Nh{constructor(){le(this,"flags");le(this,"listeners",new Set);this.flags=this.loadFlags()}loadFlags(){if(typeof localStorage>"u")return x0;try{const e=localStorage.getItem(Js);if(e)return{...x0,...JSON.parse(e)}}catch(e){za.error("Failed to load debug flags:",e)}return x0}saveFlags(){if(!(typeof localStorage>"u")){try{localStorage.setItem(Js,JSON.stringify(this.flags))}catch(e){za.error("Failed to save debug flags:",e)}this.listeners.forEach(e=>e(this.flags))}}get(e){return this.flags[e]}set(e,r){this.flags[e]=r,this.saveFlags()}toggle(e){typeof this.flags[e]=="boolean"&&(this.flags[e]=!this.flags[e],this.saveFlags())}reset(){this.flags={...x0},this.saveFlags()}getAll(){return{...this.flags}}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}toggleDebugPanel(){this.toggle("showDebugInfo"),za.info("Debug panel:",this.flags.showDebugInfo?"ON":"OFF")}async simulateDelay(e){return this.flags.simulateSlowNetwork&&this.flags.networkDelay>0&&await new Promise(r=>setTimeout(r,this.flags.networkDelay)),e}}const Ra=new Nh;function X3(t){if(!t)return"";let e=t;return e=e.replace(/\*\*(.+?)\*\*/g,"$1"),e=e.replace(/__(.+?)__/g,"$1"),e=e.replace(/(?<!\*)\*(?!\*)(.+?)(?<!\*)\*(?!\*)/g,"$1"),e=e.replace(/(?<!_)_(?!_)(.+?)(?<!_)_(?!_)/g,"$1"),e=e.replace(/~~(.+?)~~/g,"$1"),e=e.replace(/`([^`]+)`/g,"$1"),e=e.replace(/\[([^\]]+)\]\([^)]+\)/g,"$1"),e=e.replace(/^#{1,6}\s+/gm,""),e=e.replace(/^\*+\s*/gm,""),e=e.replace(/\s*\*+$/gm,""),e.trim()}function Ph(t){return t.charAt(0).toUpperCase()+t.slice(1)}function Y3(t){if(!t||t.trim().length===0)return ie.workspace_sidebarHeader_branchEmpty_error();if(/[\s~^:\\?*\[\\]/.test(t))return ie.workspace_sidebarHeader_branchInvalidChars_error();if(t.includes("@{"))return ie.workspace_sidebarChanges_branchAtBrace_error({seq:"@{"});if(t==="@")return ie.workspace_sidebarChanges_branchAt_error({symbol:"@"});if(t.startsWith("."))return ie.workspace_sidebarHeader_branchStartsDot_error();if(t.endsWith(".lock"))return ie.workspace_sidebarHeader_branchEndsLock_error();if(t.includes(".."))return ie.workspace_sidebarHeader_branchDoubleDot_error();if(t.startsWith("/")||t.endsWith("/"))return ie.workspace_sidebarHeader_branchSlashEnds_error();if(t.includes("//"))return ie.workspace_sidebarHeader_branchDoubleSlash_error();if(t.startsWith("-"))return ie.workspace_sidebarHeader_branchStartsDash_error();if(t.endsWith("."))return ie.workspace_sidebarChanges_branchEndsPeriod_error();const e=t.split("/");for(const r of e){if(r.startsWith("."))return ie.workspace_sidebarChanges_branchComponentStartsDot_error();if(r.endsWith(".lock"))return ie.workspace_sidebarChanges_branchComponentEndsLock_error()}if(t.length>250)return ie.workspace_sidebarHeader_branchTooLong_error()}function Z3(t,e,r,n){return e&&r?`https://github.com/${e}/${r}/pull/${t}`:n||""}function li(t){return t==="Open"?"open":t==="Merged"?"merged":t==="Draft"?"draft":"closed"}function Q3(t,e){return`${e}:${t.agentId??"manual"}`}function _h(t,e){if(t.length===0||e>=t.length)return 0;const r=Math.max(0,e);let n=0;for(let a=r;a<t.length;a++)t[a].isPushed||n++;return n}function Lh(t,e){if(t.length===0||e<0)return 0;const r=Math.min(e,t.length-1);let n=0;for(let a=0;a<=r;a++)t[a].isPushed&&n++;return n}function Oh(t,e){if(t.length===0||e<0)return 0;const r=Math.min(e,t.length-1);let n=0;for(let a=0;a<=r;a++)t[a].isPushed||n++;return n}function J3(t,e,r,n){const a=_h(t,e),i=n?` (origin/${n})`:"";return r?a===1?ie.workspace_sidebarChanges_addToPr_one({suffix:i}):ie.workspace_sidebarChanges_addToPr_many({count:rt(a),suffix:i}):a===1?ie.workspace_sidebarChanges_pushToRemote_one({suffix:i}):ie.workspace_sidebarChanges_pushToRemote_many({count:rt(a),suffix:i})}function e6(t,e,r){const n=Lh(t,e),a=r?` (origin/${r})`:"";return n===1?ie.workspace_sidebarChanges_undoPush_one({suffix:a}):ie.workspace_sidebarChanges_undoPush_many({count:rt(n),suffix:a})}function t6(t,e){const r=Oh(t,e);return r===1?ie.workspace_sidebarChanges_undoCommit_one():ie.workspace_sidebarChanges_undoCommit_many({count:rt(r)})}function r6(t,e){return e===0&&t.length>0}function n6(t,e,r,n){return!r||n==null?!1:t===r&&e===n}function a6(t,e,r){const n=`${e?"staged":"unstaged"}:${t}`;return r.has(n)}function i6(t,e,r){return r?.path===t&&r?.staged===e}function s6(t){if(t.length===0)return[];const e=new Map,r=[...t].sort((n,a)=>n.timestamp-a.timestamp);for(const n of r)for(const a of n.files??[]){const i=e.get(a.path);i?e.set(a.path,{additions:i.additions+(a.additions||0),deletions:i.deletions+(a.deletions||0)}):e.set(a.path,{additions:a.additions||0,deletions:a.deletions||0})}return Array.from(e.entries()).map(([n,a])=>({path:n,additions:a.additions,deletions:a.deletions,staged:!1}))}function o6(t,e,r){const n=new Set;let a=0,i=0;for(const s of t)n.add(s.relativePath),a+=s.stats?.additions||0,i+=s.stats?.deletions||0;for(const s of e)n.add(s.relativePath),a+=s.stats?.additions||0,i+=s.stats?.deletions||0;for(const s of r)for(const o of s.files||[])n.add(o.path),a+=o.additions||0,i+=o.deletions||0;return{totalFilesChanged:n.size,totalAdditions:a,totalDeletions:i}}function $h(t){const e=t?.match(/^https?:\/\/github\.com\/([^/]+)\/([^/]+)\/pull\/\d+/i);return e?`${e[1]}/${e[2]}`:void 0}function l6(t,e,r,n,a){if(t&&t.length>0){const i=a?.split("/")[0];return t.map(s=>{const o=s.url||r(s.number),c=$h(s.url),h=c!==void 0&&c.toLowerCase()!==a?.toLowerCase()?c:void 0;return{number:s.number,title:n(s),url:o,htmlUrl:o,status:li(s.status),createdAt:s.createdAt,updatedAt:s.updatedAt,isInMergeQueue:s.isDraft?void 0:s.isInMergeQueue,crossRepo:h,crossRepoDisplay:h?Fi(h,i):void 0}})}return e?[{number:e.number,title:n(e),url:r(e.number,e.url),htmlUrl:r(e.number,e.url),status:li(e.status),createdAt:e.createdAt,updatedAt:e.updatedAt,isInMergeQueue:e.isDraft?void 0:e.isInMergeQueue}]:[]}function c6(t){const{prNumber:e,prUrl:r}=t;return e==null||!r?null:{id:`legacy-pr-${e}`,number:e,url:r,title:"",status:t.prStatus??rh.Open,createdAt:t.updatedAt,updatedAt:t.updatedAt}}function Bh(t){const e=t.lastSnapshot?.state?.toLowerCase();return e==="merged"?"merged":e==="closed"?"closed":t.lastSnapshot?.isDraft?"draft":t.state==="completed"?"closed":"open"}function Da(t,e,r){if(e.length===0)return t;const n=r?.split("/")[0],a=t.map(i=>({...i}));for(const i of e){const s=!i.resource&&!i.monitorAvailability&&(!r||i.repo===r),o=_n(i),c=o.toLowerCase(),h=a.find(d=>!!o&&d.url.toLowerCase()===c||(i.resource||i.monitorAvailability?d.monitorIdentity===Ia(i):!d.resource&&!d.monitorAvailability&&(s?!d.crossRepo&&d.number===i.prNumber:d.crossRepo===i.repo&&d.number===i.prNumber)));if(h){h.monitorAgentId=i.agentId,h.resource=i.resource,h.monitorAvailability=i.monitorAvailability,h.monitorIdentity=i.resource||i.monitorAvailability?Ia(i):void 0,h.monitorSnapshot=i.lastSnapshot??h.monitorSnapshot;continue}a.push({number:i.prNumber,title:i.title??`${i.repo}${P1(i,i.prNumber)}`,resource:i.resource,monitorAvailability:i.monitorAvailability,monitorIdentity:i.resource||i.monitorAvailability?Ia(i):void 0,url:o,htmlUrl:o,status:Bh(i),createdAt:i.createdAt,updatedAt:i.updatedAt,monitorAgentId:i.agentId,crossRepo:s?void 0:i.repo,crossRepoDisplay:s?void 0:Fi(i.repo,n),monitorSnapshot:i.lastSnapshot,monitorOnly:!0})}return a}function Fi(t,e){return e&&t.toLowerCase().startsWith(`${e.toLowerCase()}/`)?t.slice(e.length+1):t}function u6(t,e,r,n,a){const i=r?.toLowerCase(),s=new Set;for(const k of n)k.repoOwner&&k.repoName&&s.add(`${k.repoOwner}/${k.repoName}`.toLowerCase());let o=t;const c=[],h=[];if(t.some(k=>k.crossRepo)){o=[];for(const k of t)k.crossRepo?s.has(k.crossRepo.toLowerCase())?c.push(k):h.push(k):o.push(k)}const d=[],v=[],m=[];for(const k of e){const I=k.repo.toLowerCase();_n(k)&&o.some(R=>R.url===_n(k))||!k.resource&&!k.monitorAvailability&&(!i||I===i)?d.push(k):_n(k)&&c.some(R=>R.url===_n(k))||!k.resource&&!k.monitorAvailability&&s.has(I)?v.push(k):m.push(k)}const w=Da(o,d,r),A=r?.split("/")[0],C=new Set([...w,...c,...h].map(k=>`${(k.crossRepo??r??"").toLowerCase()}#${k.number}`)),M=[...c];for(const k of n){if(!k.repoOwner||!k.repoName)continue;const I=`${k.repoOwner}/${k.repoName}`;for(const R of k.pullRequests??[]){const Z=`${I.toLowerCase()}#${R.number}`;if(C.has(Z))continue;C.add(Z);const K=R.url||`https://github.com/${I}/pull/${R.number}`,ee=i!==void 0&&I.toLowerCase()===i;M.push({number:R.number,title:a(R),url:K,htmlUrl:K,status:li(R.status),createdAt:R.createdAt,updatedAt:R.updatedAt,crossRepo:ee?void 0:I,crossRepoDisplay:ee?void 0:Fi(I,A)})}}return{own:w,otherRoots:Da(M,v,r),otherTracked:Da(h,m,r)}}function eo(t){return t.status!=="open"?!1:t.monitorSnapshot?t.monitorSnapshot.isInMergeQueue===!0:t.isInMergeQueue===!0}function h6(t){const e=t.status==="merged"?ie.workspace_prSection_merged_label():t.status==="closed"?ie.workspace_prSection_closed_label():t.status==="draft"?ie.workspace_prSection_statusDraft_label():eo(t)?ie.workspace_prSection_statusQueued_label():ie.workspace_prSection_statusOpen_label(),r=[_1(t)??e],n=eo(t)?hh(t.monitorSnapshot?.mergeQueue):null;n&&r.push(n);const a=t.status==="merged"||t.status==="closed"?void 0:t.monitorSnapshot;return a&&(a.checks.total===null||a.checks.passed===null||a.checks.failed===null||a.checks.pending===null||a.availability&&a.availability.checks!=="available"?r.push(ie.chat_monitoredPrs_hover_checksUnknown_label()):a.checks.total>0&&r.push(ie.workspace_prSection_statusChecks_tooltip({passed:rt(a.checks.passed),failed:rt(a.checks.failed),pending:rt(a.checks.pending)})),r.push(a.approvals.have===null||a.availability&&a.availability.approvals!=="available"?ie.chat_monitoredPrs_hover_approvalsUnknown_label():a.approvals.needed!=null?ie.workspace_prSection_statusApprovalsOfNeeded_tooltip({count:rt(a.approvals.have),needed:rt(a.approvals.needed)}):ie.workspace_prSection_statusApprovals_tooltip({count:rt(a.approvals.have)})),a.approvals.changesRequested!==null&&a.approvals.changesRequested>0&&r.push(ie.workspace_prSection_statusChangesRequested_tooltip({count:rt(a.approvals.changesRequested)})),a.availability&&a.availability.discussions!=="available"?r.push(ie.workspace_prSection_statusUnresolvedThreadsUnknown_tooltip()):typeof a.threads.unresolved=="number"?a.threads.unresolved>0&&r.push(ie.workspace_prSection_statusUnresolvedThreads_tooltip({count:rt(a.threads.unresolved)})):a.threads.resolutionRequired&&r.push(ie.workspace_prSection_statusUnresolvedThreadsUnknown_tooltip()),a.mergeBlockedReason&&r.push(Ph(a.mergeBlockedReason))),r.join(`
1
+ var z1=Object.defineProperty;var js=t=>{throw TypeError(t)};var R1=(t,e,r)=>e in t?z1(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r;var le=(t,e,r)=>R1(t,typeof e!="symbol"?e+"":e,r),D1=(t,e,r)=>e.has(t)||js("Cannot "+r);var Vs=(t,e,r)=>e.has(t)?js("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r);var tn=(t,e,r)=>(D1(t,e,"access private method"),r);import{cR as Vt,b4 as N1,dJ as Xl,a7 as _n,a5 as Ia,a6 as P1,a4 as _1,aa as L1,am as O1,a1 as $1,ea as B1,X as q1,bn as Yl,cU as qr,dI as Zl,b3 as F1,b8 as H1,cC as U1,cS as W1,cn as G1,dD as si,e2 as j1,dX as V1,aK as X0,ax as K1,aF as _i,dH as Ql,ee as Jl,dV as X1,ed as Y1}from"./cD292w1o.js";import{D as Ks,b3 as Z1,bd as Q1,aB as J1}from"./OrDYwyck.js";import{M as eh,G as hn,I as th}from"./Bqd7fdCF.js";import{zz as y0,JH as E,n_ as ve,nZ as xe,aU as rh,m as ec,I as De,br as gn,kf as Li,mf as w0,ar as Xt,me as Xs,mo as Ys,ml as Zs,jO as tc,gA as oi,I2 as nh,tK as ah,B1 as ih,p1 as sh,n3 as k0,CB as oh,iO as lh,my as ch,m9 as uh}from"./D0qhIm1r.js";import{bm as ie}from"./Fcr7AvC-.js";import{l as rt}from"./C7b3vXLD.js";import{m as hh,f as Tr}from"./B0SSzYpD.js";import{a as vn}from"./BdWqymET.js";import{o as pe,r as Kt,e as bn,s as V,_ as Je,l as yn,g as dh,n as Le,c as dr,b as Ve,u as ph,d as mh}from"./CIyUrgF0.js";import{j as rc}from"./uXuxG9cN.js";import{u as fh}from"./BwweojP5.js";import{selectActiveWorkspaceIds as gh}from"./_IjN0Lbt.js";import{i as je}from"./CL3a4Hm1.js";import{l as za,c as Oi}from"./ChTqQfQN.js";import"./CDCAMh6o.js";import{e as vh,h as Er}from"./DONrLvvt.js";import{h as wn}from"./BAtAwQ72.js";import{i as Qs}from"./BBWuirRW.js";import{f as $i,o as nc,p as ac,h as bh,m as ic,i as yh,k as wh}from"./BeZe2Rt-.js";const Ze=[];for(let t=0;t<256;++t)Ze.push((t+256).toString(16).slice(1));function kh(t,e=0){return(Ze[t[e+0]]+Ze[t[e+1]]+Ze[t[e+2]]+Ze[t[e+3]]+"-"+Ze[t[e+4]]+Ze[t[e+5]]+"-"+Ze[t[e+6]]+Ze[t[e+7]]+"-"+Ze[t[e+8]]+Ze[t[e+9]]+"-"+Ze[t[e+10]]+Ze[t[e+11]]+Ze[t[e+12]]+Ze[t[e+13]]+Ze[t[e+14]]+Ze[t[e+15]]).toLowerCase()}const xh=new Uint8Array(16);function Sh(){return crypto.getRandomValues(xh)}function Bi(t,e,r){return crypto.randomUUID?crypto.randomUUID():Ah(t)}function Ah(t,e,r){t=t||{};const n=t.random??t.rng?.()??Sh();if(n.length<16)throw new Error("Random bytes length must be >= 16");return n[6]=n[6]&15|64,n[8]=n[8]&63|128,kh(n)}function qi(t,e){if(t.repositoryIdentity===null)return null;if(t.repositoryIdentity){const{provider:a,instanceBaseUrl:i,projectPath:s}=t.repositoryIdentity,o=qi({...t,repositoryIdentity:void 0,githubUrl:`${i}/${s}`},a==="gitlab"?i:void 0);return o?.provider===a?o:null}const r=t.githubUrl;if(!r)return null;const n=/^(?:https:\/\/github\.com\/|git@github\.com:)([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+?)(?:\.git)?\/?$/i.exec(r);return n&&!n.slice(1).some(a=>a==="."||a==="..")?{provider:"github",instanceBaseUrl:"https://github.com",projectPath:`${n[1]}/${n[2]}`}:e?eh(r.replace(/\.git\/?$/,""),e):null}function f3(t,e){return t.type==="local"?t.plainFolder?"folder":"local":qi(t,e)?.provider==="gitlab"?"gitlab":"github"}function sc(t){const e=t.split(/[\\/]/).filter(Boolean);return e[e.length-1]??""}function g3(t){if(t.type!=="local")return{ownerPrefix:t.owner,primary:t.name};const e=sc(t.path)||t.name,r=t.owner?`${t.owner}/${t.name}`:void 0;return{primary:e,suffix:r}}function v3(t){return t.type==="local"&&t.path?t.path:void 0}const Th=["/.clones/","/.repo-cache/"];function b3(t){const e=t.replaceAll("\\","/");return Th.some(r=>e.includes(r))}function y3(t){const e=new Set;for(const r of t){const{repositoryPath:n,worktreePath:a}=r;n&&a&&n===a&&e.add(n)}return e}function Eh(t){return t.includes("\\")||t.includes(":")||t.startsWith("/")?void 0:/^([^/]+)\/[^/]+$/.exec(t)?.[1]}function w3(t,e){const{selectedValue:r,selectedRepoType:n,confirmedGithubUrl:a}=t;if(!(n!=="github"||!r)){if(a){const i=e(a)?.owner;if(i)return i}return e(r)?.owner??Eh(r)}}function k3(t,e){const r=e.trim().toLowerCase();return r===""?!0:[t.name,t.path,sc(t.path),t.owner,t.owner?`${t.owner}/${t.name}`:void 0].some(a=>a?.toLowerCase().includes(r)??!1)}const Ch="known-repos",Mh=6e4;function Ih({saved:t,source:e,dismissed:r,mode:n}){if(!e)return[...t];const a=new Map;if(n==="all")for(const s of[...e.repos,...t]){const o=y0(s);a.has(o)||a.set(o,s)}else{for(const s of t)a.set(y0(s),s);for(const s of e.repos)a.set(y0(s),s)}const i=[...a.values()].filter(s=>!r[y0(s)]);return n==="all"?i:i.slice(0,9)}function x3(t){const e=t.lastUsedAt?Date.parse(t.lastUsedAt):NaN;return Number.isFinite(e)?e:0}function S3({visible:t,admission:e,entry:r,readyAt:n,now:a}){return!t||!e?"skip":!r||r.admission!==e?"load":r.status==="pending"?"reuse":r.status==="ready"&&n?.requestId===r.requestId&&a-n.at<Mh?"skip":"load"}function A3(t,e){if(t.type==="local")return t.plainFolder?{repoPath:t.path,plainFolder:!0}:{repoPath:t.path};const r=qi(t,e);return r?.provider==="gitlab"?{repositoryCheckoutDraft:{instanceBaseUrl:r.instanceBaseUrl,projectPath:r.projectPath}}:r?{githubUrl:`https://github.com/${r.projectPath}`,exactRemote:!0}:{githubUrl:t.githubUrl||`https://github.com/${t.path}`,exactRemote:!0}}function zh({compactFormState:t,lastSubmittedAgent:e,specialists:r,orchestratorId:n}){if(t?.isTeamMode??e?.isTeamMode??!1)return n;const i=o=>r.some(c=>c.id===o),s=t?.selectedSpecialist!==void 0?t.selectedSpecialist:e?.selectedSpecialist!==void 0?e.selectedSpecialist:i(Ks)?Ks:null;return s===null||!i(s)?null:s}const T3=E.createSelector(t=>t.workspaceInitializer.hydrated),E3=E.createSelector(t=>t.workspaceInitializer.compactFormState),C3=E.createSelector(t=>t.workspaceInitializer.onboardingFormState),M3=E.createSelector(t=>t.workspaceInitializer.lastSelectedRepo),I3=E.createSelector(t=>t.workspaceInitializer.branchByRepo),z3=E.createSelector(t=>t.workspaceInitializer.defaultParentPath),R3=E.createSelector(t=>ve(t.workspaceInitializer.recentRepos)),D3=E.createSelector((t,e)=>xe(t.workspaceInitializer.recentRepoRefreshes,e)),N3=E.createSelector((t,e)=>xe(t.workspaceInitializer.directoryStatusChecks,e)),P3=E.createSelector(t=>t.workspaceInitializer.dismissedRecentRepoKeys),_3=E.createSelector(t=>ve(t.workspaceInitializer.remoteSetups)),L3=E.createSelector(t=>t.workspaceInitializer.lastSubmittedAgent),O3=E.createSelector(t=>t.workspaceInitializer.agentByRepo),$3=E.createSelector(t=>t.workspaceInitializer.recentSpecialistIds),B3=E.createSelector((t,e)=>t.workspaceInitializer.agentByRepo[e]??null),q3=E.createSelector(t=>t.workspaceInitializer.pendingGitHubPrefill),F3=E.createSelector((t,e)=>({restore:xe(t.workspaceInitializer.draftRestores,e),clear:xe(t.workspaceInitializer.draftClears,e)})),H3=E.createSelector((t,e,r)=>{const n=xe(t.workspaceInitializer.initializationOutcomes,e);return n?.resourceId===r?n:void 0}),U3=E.createSelector((t,e)=>xe(t.workspaceInitializer.initializationOutcomes,e)),W3=E.createSelector((t,e)=>xe(t.workspaceInitializer.initializationResumes,e)),G3=E.createSelector(t=>zh({compactFormState:t.workspaceInitializer.compactFormState,lastSubmittedAgent:t.workspaceInitializer.lastSubmittedAgent,specialists:Q1.select(t),orchestratorId:Z1.select(t)?.id??null})),Rh=E.createSelector(t=>{const e=t.workspaceInitializer.gitCheckRequest,r=Vt.select(t);return e&&r&&N1.select(t)?JSON.stringify([r,e]):null}),j3=E.createSelector(t=>{const e=Rh.select(t),r=t.workspaceInitializer.gitCheck;return e&&r?.context===e?r.available:null}),Dh=E.createSelector(t=>{const e=xe(t.workspaceInitializer.recentRepoRefreshes,Ch),r=Vt.select(t);return Ih({saved:ve(t.workspaceInitializer.recentRepos),source:e&&r&&e.admission===r?e:null,dismissed:t.workspaceInitializer.dismissedRecentRepoKeys,mode:"all"})}),V3=E.createSelector(t=>Xl.select(t)?Dh.select(t):[]),K3=E.createSelector(t=>J1.select(t)||void 0),Js="workspace-debug-flags",x0={enableCreationAnimation:!0,animationDuration:300,enablePageTransitions:!0,enableComponentTransitions:!0,showDebugInfo:!1,showPerformanceMetrics:!1,logStateChanges:!1,enableAutofocus:!0,enableBranchCaching:!0,enableFormPersistence:!0,simulateSlowNetwork:!1,simulateErrors:!1,networkDelay:0};class Nh{constructor(){le(this,"flags");le(this,"listeners",new Set);this.flags=this.loadFlags()}loadFlags(){if(typeof localStorage>"u")return x0;try{const e=localStorage.getItem(Js);if(e)return{...x0,...JSON.parse(e)}}catch(e){za.error("Failed to load debug flags:",e)}return x0}saveFlags(){if(!(typeof localStorage>"u")){try{localStorage.setItem(Js,JSON.stringify(this.flags))}catch(e){za.error("Failed to save debug flags:",e)}this.listeners.forEach(e=>e(this.flags))}}get(e){return this.flags[e]}set(e,r){this.flags[e]=r,this.saveFlags()}toggle(e){typeof this.flags[e]=="boolean"&&(this.flags[e]=!this.flags[e],this.saveFlags())}reset(){this.flags={...x0},this.saveFlags()}getAll(){return{...this.flags}}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}toggleDebugPanel(){this.toggle("showDebugInfo"),za.info("Debug panel:",this.flags.showDebugInfo?"ON":"OFF")}async simulateDelay(e){return this.flags.simulateSlowNetwork&&this.flags.networkDelay>0&&await new Promise(r=>setTimeout(r,this.flags.networkDelay)),e}}const Ra=new Nh;function X3(t){if(!t)return"";let e=t;return e=e.replace(/\*\*(.+?)\*\*/g,"$1"),e=e.replace(/__(.+?)__/g,"$1"),e=e.replace(/(?<!\*)\*(?!\*)(.+?)(?<!\*)\*(?!\*)/g,"$1"),e=e.replace(/(?<!_)_(?!_)(.+?)(?<!_)_(?!_)/g,"$1"),e=e.replace(/~~(.+?)~~/g,"$1"),e=e.replace(/`([^`]+)`/g,"$1"),e=e.replace(/\[([^\]]+)\]\([^)]+\)/g,"$1"),e=e.replace(/^#{1,6}\s+/gm,""),e=e.replace(/^\*+\s*/gm,""),e=e.replace(/\s*\*+$/gm,""),e.trim()}function Ph(t){return t.charAt(0).toUpperCase()+t.slice(1)}function Y3(t){if(!t||t.trim().length===0)return ie.workspace_sidebarHeader_branchEmpty_error();if(/[\s~^:\\?*\[\\]/.test(t))return ie.workspace_sidebarHeader_branchInvalidChars_error();if(t.includes("@{"))return ie.workspace_sidebarChanges_branchAtBrace_error({seq:"@{"});if(t==="@")return ie.workspace_sidebarChanges_branchAt_error({symbol:"@"});if(t.startsWith("."))return ie.workspace_sidebarHeader_branchStartsDot_error();if(t.endsWith(".lock"))return ie.workspace_sidebarHeader_branchEndsLock_error();if(t.includes(".."))return ie.workspace_sidebarHeader_branchDoubleDot_error();if(t.startsWith("/")||t.endsWith("/"))return ie.workspace_sidebarHeader_branchSlashEnds_error();if(t.includes("//"))return ie.workspace_sidebarHeader_branchDoubleSlash_error();if(t.startsWith("-"))return ie.workspace_sidebarHeader_branchStartsDash_error();if(t.endsWith("."))return ie.workspace_sidebarChanges_branchEndsPeriod_error();const e=t.split("/");for(const r of e){if(r.startsWith("."))return ie.workspace_sidebarChanges_branchComponentStartsDot_error();if(r.endsWith(".lock"))return ie.workspace_sidebarChanges_branchComponentEndsLock_error()}if(t.length>250)return ie.workspace_sidebarHeader_branchTooLong_error()}function Z3(t,e,r,n){return e&&r?`https://github.com/${e}/${r}/pull/${t}`:n||""}function li(t){return t==="Open"?"open":t==="Merged"?"merged":t==="Draft"?"draft":"closed"}function Q3(t,e){return`${e}:${t.agentId??"manual"}`}function _h(t,e){if(t.length===0||e>=t.length)return 0;const r=Math.max(0,e);let n=0;for(let a=r;a<t.length;a++)t[a].isPushed||n++;return n}function Lh(t,e){if(t.length===0||e<0)return 0;const r=Math.min(e,t.length-1);let n=0;for(let a=0;a<=r;a++)t[a].isPushed&&n++;return n}function Oh(t,e){if(t.length===0||e<0)return 0;const r=Math.min(e,t.length-1);let n=0;for(let a=0;a<=r;a++)t[a].isPushed||n++;return n}function J3(t,e,r,n){const a=_h(t,e),i=n?` (origin/${n})`:"";return r?a===1?ie.workspace_sidebarChanges_addToPr_one({suffix:i}):ie.workspace_sidebarChanges_addToPr_many({count:rt(a),suffix:i}):a===1?ie.workspace_sidebarChanges_pushToRemote_one({suffix:i}):ie.workspace_sidebarChanges_pushToRemote_many({count:rt(a),suffix:i})}function e6(t,e,r){const n=Lh(t,e),a=r?` (origin/${r})`:"";return n===1?ie.workspace_sidebarChanges_undoPush_one({suffix:a}):ie.workspace_sidebarChanges_undoPush_many({count:rt(n),suffix:a})}function t6(t,e){const r=Oh(t,e);return r===1?ie.workspace_sidebarChanges_undoCommit_one():ie.workspace_sidebarChanges_undoCommit_many({count:rt(r)})}function r6(t,e){return e===0&&t.length>0}function n6(t,e,r,n){return!r||n==null?!1:t===r&&e===n}function a6(t,e,r){const n=`${e?"staged":"unstaged"}:${t}`;return r.has(n)}function i6(t,e,r){return r?.path===t&&r?.staged===e}function s6(t){if(t.length===0)return[];const e=new Map,r=[...t].sort((n,a)=>n.timestamp-a.timestamp);for(const n of r)for(const a of n.files??[]){const i=e.get(a.path);i?e.set(a.path,{additions:i.additions+(a.additions||0),deletions:i.deletions+(a.deletions||0)}):e.set(a.path,{additions:a.additions||0,deletions:a.deletions||0})}return Array.from(e.entries()).map(([n,a])=>({path:n,additions:a.additions,deletions:a.deletions,staged:!1}))}function o6(t,e,r){const n=new Set;let a=0,i=0;for(const s of t)n.add(s.relativePath),a+=s.stats?.additions||0,i+=s.stats?.deletions||0;for(const s of e)n.add(s.relativePath),a+=s.stats?.additions||0,i+=s.stats?.deletions||0;for(const s of r)for(const o of s.files||[])n.add(o.path),a+=o.additions||0,i+=o.deletions||0;return{totalFilesChanged:n.size,totalAdditions:a,totalDeletions:i}}function $h(t){const e=t?.match(/^https?:\/\/github\.com\/([^/]+)\/([^/]+)\/pull\/\d+/i);return e?`${e[1]}/${e[2]}`:void 0}function l6(t,e,r,n,a){if(t&&t.length>0){const i=a?.split("/")[0];return t.map(s=>{const o=s.url||r(s.number),c=$h(s.url),h=c!==void 0&&c.toLowerCase()!==a?.toLowerCase()?c:void 0;return{number:s.number,title:n(s),url:o,htmlUrl:o,status:li(s.status),createdAt:s.createdAt,updatedAt:s.updatedAt,isInMergeQueue:s.isDraft?void 0:s.isInMergeQueue,crossRepo:h,crossRepoDisplay:h?Fi(h,i):void 0}})}return e?[{number:e.number,title:n(e),url:r(e.number,e.url),htmlUrl:r(e.number,e.url),status:li(e.status),createdAt:e.createdAt,updatedAt:e.updatedAt,isInMergeQueue:e.isDraft?void 0:e.isInMergeQueue}]:[]}function c6(t){const{prNumber:e,prUrl:r}=t;return e==null||!r?null:{id:`legacy-pr-${e}`,number:e,url:r,title:"",status:t.prStatus??rh.Open,createdAt:t.updatedAt,updatedAt:t.updatedAt}}function Bh(t){const e=t.lastSnapshot?.state?.toLowerCase();return e==="merged"?"merged":e==="closed"?"closed":t.lastSnapshot?.isDraft?"draft":t.state==="completed"?"closed":"open"}function Da(t,e,r){if(e.length===0)return t;const n=r?.split("/")[0],a=t.map(i=>({...i}));for(const i of e){const s=!i.resource&&!i.monitorAvailability&&(!r||i.repo===r),o=_n(i),c=o.toLowerCase(),h=a.find(d=>!!o&&d.url.toLowerCase()===c||(i.resource||i.monitorAvailability?d.monitorIdentity===Ia(i):!d.resource&&!d.monitorAvailability&&(s?!d.crossRepo&&d.number===i.prNumber:d.crossRepo===i.repo&&d.number===i.prNumber)));if(h){h.monitorAgentId=i.agentId,h.resource=i.resource,h.monitorAvailability=i.monitorAvailability,h.monitorIdentity=i.resource||i.monitorAvailability?Ia(i):void 0,h.monitorSnapshot=i.lastSnapshot??h.monitorSnapshot;continue}a.push({number:i.prNumber,title:i.title??`${i.repo}${P1(i,i.prNumber)}`,resource:i.resource,monitorAvailability:i.monitorAvailability,monitorIdentity:i.resource||i.monitorAvailability?Ia(i):void 0,url:o,htmlUrl:o,status:Bh(i),createdAt:i.createdAt,updatedAt:i.updatedAt,monitorAgentId:i.agentId,crossRepo:s?void 0:i.repo,crossRepoDisplay:s?void 0:Fi(i.repo,n),monitorSnapshot:i.lastSnapshot,monitorOnly:!0})}return a}function Fi(t,e){return e&&t.toLowerCase().startsWith(`${e.toLowerCase()}/`)?t.slice(e.length+1):t}function u6(t,e,r,n,a){const i=r?.toLowerCase(),s=new Set;for(const k of n)k.repoOwner&&k.repoName&&s.add(`${k.repoOwner}/${k.repoName}`.toLowerCase());let o=t;const c=[],h=[];if(t.some(k=>k.crossRepo)){o=[];for(const k of t)k.crossRepo?s.has(k.crossRepo.toLowerCase())?c.push(k):h.push(k):o.push(k)}const d=[],v=[],m=[];for(const k of e){const I=k.repo.toLowerCase();_n(k)&&o.some(R=>R.url===_n(k))||!k.resource&&!k.monitorAvailability&&(!i||I===i)?d.push(k):_n(k)&&c.some(R=>R.url===_n(k))||!k.resource&&!k.monitorAvailability&&s.has(I)?v.push(k):m.push(k)}const w=Da(o,d,r),A=r?.split("/")[0],C=new Set([...w,...c,...h].map(k=>`${(k.crossRepo??r??"").toLowerCase()}#${k.number}`)),M=[...c];for(const k of n){if(!k.repoOwner||!k.repoName)continue;const I=`${k.repoOwner}/${k.repoName}`;for(const R of k.pullRequests??[]){const Z=`${I.toLowerCase()}#${R.number}`;if(C.has(Z))continue;C.add(Z);const K=R.url||`https://github.com/${I}/pull/${R.number}`,ee=i!==void 0&&I.toLowerCase()===i;M.push({number:R.number,title:a(R),url:K,htmlUrl:K,status:li(R.status),createdAt:R.createdAt,updatedAt:R.updatedAt,crossRepo:ee?void 0:I,crossRepoDisplay:ee?void 0:Fi(I,A)})}}return{own:w,otherRoots:Da(M,v,r),otherTracked:Da(h,m,r)}}function eo(t){return t.status!=="open"?!1:t.monitorSnapshot?t.monitorSnapshot.isInMergeQueue===!0:t.isInMergeQueue===!0}function h6(t){const e=t.status==="merged"?ie.workspace_prSection_merged_label():t.status==="closed"?ie.workspace_prSection_closed_label():t.status==="draft"?ie.workspace_prSection_statusDraft_label():eo(t)?ie.workspace_prSection_statusQueued_label():ie.workspace_prSection_statusOpen_label(),r=[_1(t)??e],n=eo(t)?hh(t.monitorSnapshot?.mergeQueue):null;n&&r.push(n);const a=t.status==="merged"||t.status==="closed"?void 0:t.monitorSnapshot;return a&&(a.checks.total===null||a.checks.passed===null||a.checks.failed===null||a.checks.pending===null||a.availability&&a.availability.checks!=="available"?r.push(ie.chat_monitoredPrs_hover_checksUnknown_label()):a.checks.total>0&&r.push(ie.workspace_prSection_statusChecks_tooltip({passed:rt(a.checks.passed),failed:rt(a.checks.failed),pending:rt(a.checks.pending)})),r.push(a.approvals.have===null||a.availability&&a.availability.approvals!=="available"?ie.chat_monitoredPrs_hover_approvalsUnknown_label():a.approvals.needed!=null?ie.workspace_prSection_statusApprovalsOfNeeded_tooltip({count:rt(a.approvals.have),needed:rt(a.approvals.needed)}):ie.workspace_prSection_statusApprovals_tooltip({count:rt(a.approvals.have)})),a.approvals.changesRequested!==null&&a.approvals.changesRequested>0&&r.push(ie.workspace_prSection_statusChangesRequested_tooltip({count:rt(a.approvals.changesRequested)})),a.availability&&a.availability.discussions!=="available"?r.push(ie.workspace_prSection_statusUnresolvedThreadsUnknown_tooltip()):typeof a.threads.unresolved=="number"?a.threads.unresolved>0&&r.push(ie.workspace_prSection_statusUnresolvedThreads_tooltip({count:rt(a.threads.unresolved)})):a.threads.resolutionRequired&&r.push(ie.workspace_prSection_statusUnresolvedThreadsUnknown_tooltip()),a.mergeBlockedReason&&r.push(Ph(a.mergeBlockedReason))),r.join(`
2
2
  `)}function d6(t,e){return e.has(t??"manual")}function p6(t,e){return{path:t.relativePath,additions:t.stats.additions,deletions:t.stats.deletions,staged:e,status:t.status,attribution:t.attribution?.agent?{agentId:t.attribution.agent.agentId,agentName:t.attribution.agent.agentName,sessionId:t.attribution.agent.sessionId,turnNumber:t.attribution.agent.turnNumber,timestamp:t.attribution.timestamp}:void 0}}const oc=500;function m6(t,e=oc){const r=Math.max(0,Math.floor(e));return t.length<=r?{visible:t,shown:t.length,hiddenCount:0}:{visible:t.slice(0,r),shown:r,hiddenCount:t.length-r}}function f6(t,e,r=oc){let n=Math.max(0,Math.floor(r)),a=0,i=0;return{groups:t.map(o=>{if(e(o))return{group:o,visibleFiles:[]};const c=Math.min(n,o.files.length);return n-=c,a+=c,i+=o.files.length-c,{group:o,visibleFiles:c===o.files.length?o.files:o.files.slice(0,c)}}),shown:a,hiddenCount:i}}function g6(t){if(t.hiddenCount<=0)return"";const e=rt(t.shown),r=rt(t.shown+t.hiddenCount);return t.hiddenCount===1?ie.workspace_fileChanges_hiddenFiles_one({shown:e,total:r}):ie.workspace_fileChanges_hiddenFiles_many({shown:e,total:r,count:rt(t.hiddenCount)})}function qh(t){if(!t)return{};try{const e=JSON.parse(t);return e&&typeof e=="object"?e:{}}catch{return{}}}function ci(t){return t.startsWith("@")?t.slice(1):t}function Fh(t,e,r,n){const a=t.fullPath||t.path||t.filename;if(a)return ci(String(a));const i=[r,e,n.trim()].map(ci).filter(Boolean),s=i.find(o=>o.includes("/"))??i[0];return s?L1(s).path:void 0}function Hh(t){const e=t.line??t.startLine??t.range?.start;return typeof e=="number"&&Number.isFinite(e)?e:void 0}function Uh(t){if(!t||t.getAttribute("data-mention")===null)return null;const e=t.getAttribute("data-type")||"",r=t.getAttribute("data-id")||"",n=t.getAttribute("data-label")||"",a=t.getAttribute("data-uri")||"",i=qh(t.getAttribute("data-meta")),s={type:e,id:r,label:n,uri:a,meta:i},o=a.startsWith("intent://")?a:typeof i.fullUrl=="string"&&i.fullUrl.startsWith("intent://")?i.fullUrl:void 0;if(o&&(s.intentUrl=o),e==="file"||e==="file-range"){const c=Fh(i,n,r,t.textContent||"");c&&(s.filePath=c);const h=Hh(i);h!==void 0&&(s.line=h)}else if(e==="folder"||e==="source-folder"){const c=i.fullPath||i.path||r||n,h=c?ci(String(c)).replace(/\/+$/,""):"";h&&(s.folderPath=h)}else if(e==="note"||e==="note-range"){const c=i.noteId||r;c&&(s.note=i.isExternalLink&&i.workspaceId?{id:c,workspaceId:String(i.workspaceId)}:{id:c})}return s}function v6(t){return{sidebarTabId:"files",type:"file",filePath:`${t}/`}}function Hi(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var Fr=Hi();function lc(t){Fr=t}var Nr={exec:()=>null};function Cr(t){let e=[];return r=>{let n=Math.max(0,Math.min(3,r-1)),a=e[n];return a||(a=t(n),e[n]=a),a}}function oe(t,e=""){let r=typeof t=="string"?t:t.source,n={replace:(a,i)=>{let s=typeof i=="string"?i:i.source;return s=s.replace(Ue.caret,"$1"),r=r.replace(a,s),n},getRegex:()=>new RegExp(r,e)};return n}var cc=((t="")=>{try{return!!new RegExp("(?<=1)(?<!1)"+t)}catch{return!1}})(),Ue={codeRemoveIndent:/^(?: {0,3}\t| {1,4})/gm,listInterruptsParagraph:/^ {0,3}(?:[*+-]|1[.)])[ \t]+[^ \t\n]/,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,endingSpaceTabChar:/[ \t]$/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,leadingSpaceTab:/^[ \t]+/,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+)[ \t]*)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,blockquoteMarkerWhitespace:/^( {0,3}>)(\t[ \t]*)/gm,nestedBlockMarker:/^ {0,3}(?:(?:[*+-]|\d{1,9}[.)])(?: |$)|> ?)/,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\][ \t]+\S/,listReplaceTask:/^\[[ xX]\][ \t]+/,listTaskCheckbox:/\[[ xX]\]/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,numericCharacterReference:/&#(?:(\d{1,7})|[Xx]([A-Fa-f0-9]{1,6}));/,numericCharacterReferenceOrAmpersand:/&#(?:(\d{1,7})|[Xx]([A-Fa-f0-9]{1,6}));|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:t=>new RegExp(`^( {0,3}${t})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:Cr(t=>new RegExp(`^ {0,${t}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:Cr(t=>new RegExp(`^ {0,${t}}((?:-[ ]*){3,}|(?:_[ ]*){3,}|(?:\\*[ ]*){3,})(?:\\n+|$)`)),fencesBeginRegex:Cr(t=>new RegExp(`^ {0,${t}}(?:\`\`\`|~~~)`)),headingBeginRegex:Cr(t=>new RegExp(`^ {0,${t}}#{1,6}(?:\\s|$)`)),pedanticHeadingBeginRegex:Cr(t=>new RegExp(`^ {0,${t}}#`)),htmlBeginRegex:Cr(t=>new RegExp(`^ {0,${t}}(?:</?(?:${Wi})(?:[ \\t]+|$|/?>)|<(?:(?:script|pre|style|textarea)(?:[\\s>]|$)|!--)|<\\?|<![A-Za-z]|<!\\[CDATA\\[)`,"i")),blockquoteBeginRegex:Cr(t=>new RegExp(`^ {0,${t}}>`)),nestedContainerMarkers:/^(?: {0,3}(?:(?:[*+-]|\d{1,9}[.)])[ \t]+|>[ \t]?))+/},Wh=/^(?:[ \t]*(?:\n|$))+/,Gh=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,jh=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}(?:(?=`)\1`*|(?=~)\1~*) *(?=\n|$)|$)/,Kn=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,Vh=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,Ui=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,Wi="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",Xn=oe(" {0,3}(?:</?(?:tag)(?:[ \\t]+|\\n|/?>)|<(?:(?:script|pre|style|textarea)(?:[\\s>]|$)|!--)|<\\?|<![A-Za-z]|<!\\[CDATA\\[)").replace("tag",Wi).getRegex(),uc=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |fences|blockquote|heading|hr|html|table))+?)\n {0,3}(=+|-+)[ \t]*(?:\n+|$)/,hc=oe(uc).replace(/bull/g,Ui).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}(?:\s|$)/).replace(/hr/g,/ {0,3}(?:(?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/).replace(/\|table/g,"").replace(/html/g,Xn).getRegex(),Kh=oe(uc).replace(/bull/g,Ui).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}(?:\s|$)/).replace(/hr/g,/ {0,3}(?:(?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).replace(/html/g,Xn).getRegex(),Gi=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table|[ \t]+\n)[^\n]+)*)/,Xh=/^[^\n]+/,ji=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\\n]|\n(?![ \t]*\n))+/,Yh=oe(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<(?:\\.|[^\n<>\\])*>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",ji).replace("title",/(?:"(?:\\[\s\S]|[^"\\])*"|'(?:\\[\s\S]|[^'\\\n]|\n(?!\n))*'|\((?:\\[\s\S]|[^()\\])*\))/).getRegex(),Zh=oe(/^(bull)([ \t][^\n]*?)?(?:\n|$)/).replace(/bull/g,Ui).getRegex(),Vi=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,Qh=oe("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n*|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>[^\\n]*\\n*|$)|<![A-Z][\\s\\S]*?(?:>[^\\n]*\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>[^\\n]*\\n*|$)|</?(tag)(?:[ \\t]+|\\n|/?>|$)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!(?:script|pre|style|textarea)(?![a-z0-9-]))([a-z][a-z0-9-]*)(?:attribute)*?[ \\t]*/?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|</[a-z][a-z0-9-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))","i").replace("comment",Vi).replace("tag",Wi).replace("attribute",/[ \t]+[a-zA-Z:_][\w.:-]*(?:[ \t]*=[ \t]*"[^"\n]*"|[ \t]*=[ \t]*'[^'\n]*'|[ \t]*=[ \t]*[^\s"'=<>`]+)?/).getRegex(),dc=t=>oe(Gi).replace("hr",Kn).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list",t).replace("html",Xn).getRegex(),Jh=dc(/ {0,3}(?:[*+-]|1[.)])[ \t]+[^ \t\n]/),ed=dc(/ {0,3}(?:[*+-]|\d{1,9}[.)])(?:[ \t]|\n|$)/),td=oe(/^( {0,3}> ?(?:(?![ \t]*(?:\n|$))(paragraph)|[^\n]*)(?:\n|$))+/).replace("paragraph",ed).getRegex(),Ki={blockquote:td,code:Gh,def:Yh,fences:jh,heading:Vh,hr:Kn,html:Qh,lheading:hc,list:Zh,newline:Wh,paragraph:Jh,table:Nr,text:Xh},to=oe("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",Kn).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3} )[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html",Xn).getRegex(),rd={...Ki,lheading:Kh,table:to,paragraph:oe(Gi).replace("hr",Kn).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",to).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]+[^ \\t\\n]").replace("html",Xn).getRegex()},nd={...Ki,html:oe(`^ *(?:comment(?: *\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1>(?: *\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?>(?: *\\n{2,}|\\s*$))`).replace("comment",Vi).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:Nr,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:oe(Gi).replace("hr",Kn).replace("heading",` *#{1,6} *[^
3
3
  ]`).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").replace("lheading",hc).getRegex()},ad=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,id=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,pc=/^( {2,}|\\)\n(?!\s*$)[ \t]*/,sd=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,Pt=/[\p{P}\p{S}]/u,kn=/[\s\p{P}\p{S}]/u,Yn=/[^\s\p{P}\p{S}]/u,od=oe(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,kn).getRegex(),ld=/[\p{Pi}\p{Ps}"']/u,mc=/(?!~)[\p{P}\p{S}]/u,cd=/(?!~)[\s\p{P}\p{S}]/u,ud=/(?:[^\s\p{P}\p{S}]|~)/u,hd=oe(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",cc?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),fc=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,dd=oe(fc,"u").replace(/punct/g,Pt).getRegex(),pd=oe(fc,"u").replace(/punct/g,mc).getRegex(),md=/^(?:\*+(?:((?!\*)(?!openQuote)punct)|([^\s*]))?)|^_+(?:((?!_)(?!openQuote)punct)|([^\s_]))?/,fd=oe(md,"u").replace(/openQuote/g,ld).replace(/punct/g,Pt).getRegex(),gc="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",gd=oe(gc,"gu").replace(/notPunctSpace/g,Yn).replace(/punctSpace/g,kn).replace(/punct/g,Pt).getRegex(),vd=oe(gc,"gu").replace(/notPunctSpace/g,ud).replace(/punctSpace/g,cd).replace(/punct/g,mc).getRegex(),bd="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)[\\s](\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|(?:(?!\\*)punct|notPunctSpace)(\\*+)(?!\\*)(?=notPunctSpace)",yd=oe(bd,"gu").replace(/notPunctSpace/g,Yn).replace(/punctSpace/g,kn).replace(/punct/g,Pt).getRegex(),wd=oe("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,Yn).replace(/punctSpace/g,kn).replace(/punct/g,Pt).getRegex(),kd="^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)[\\s](_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)|(?:(?!_)punct|notPunctSpace)(_+)(?!_)(?=notPunctSpace)",xd=oe(kd,"gu").replace(/notPunctSpace/g,Yn).replace(/punctSpace/g,kn).replace(/punct/g,Pt).getRegex(),Sd=oe(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,Pt).getRegex(),Ad="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",Td=oe(Ad,"gu").replace(/notPunctSpace/g,Yn).replace(/punctSpace/g,kn).replace(/punct/g,Pt).getRegex(),Ed=oe(/\\(punct)/,"gu").replace(/punct/g,Pt).getRegex(),Cd=oe(/(`+)(?:[^`]|[^`][\s\S]*?[^`])\1(?!`)|`+|\\(punct)/,"gu").replace(/punct/g,Pt).getRegex(),Md=oe(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),Id=oe(Vi).replace("(?:-->|$)","-->").getRegex(),zd=oe("^comment|^</[a-zA-Z][a-zA-Z0-9-]*\\s*>|^<[a-zA-Z][a-zA-Z0-9-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>").replace("comment",Id).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),vc=/\[(?:\\[\s\S]|[^\[\]\\])*\]/,q0=oe(/(?:\[(?:brackets|\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/).replace("brackets",vc).getRegex(),Rd=oe(/^!?\[(label)\]\([ \t\n]*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?[ \t\n]*\)/).replace("label",q0).replace("href",/<(?:\\.|[^\n<>\\])*>|(?!<)[^ \t\n\x00-\x1f]+|(?=\))/).replace("title",/"(?:\\[\s\S]|[^"\\])*"|'(?:\\[\s\S]|[^'\\])*'|\((?:\\[\s\S]|[^)\\])*\)/).getRegex(),Dd=oe(/^!?\[(label)\]\[(ref)\]/).replace("label",q0).replace("ref",ji).getRegex(),Nd=oe(/^!?\[(ref)\](?:\[\])?/).replace("ref",ji).getRegex(),ro=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\]){1,999}/,Pd=oe(/(?:[^\[\]\\`]*(?:\[(?:brackets|\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\]))){0,999}?[^\[\]\\`]*?/).replace("brackets",vc).getRegex(),_d=oe("reflink|nolink(?!\\()","g").replace("reflink",oe(/^!?\[(label)\]\[(ref)\]/).replace("label",Pd).replace("ref",ro).getRegex()).replace("nolink",oe(/^!?\[(ref)\](?:\[\])?/).replace("ref",ro).getRegex()).getRegex(),no=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,Ld=/[A-Za-z0-9._+-]+@[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![\w-])/,Od=oe(/(?:mailto:email|xmpp:email(?:\/[A-Za-z0-9@.]+)?)/).replace(/email/g,Ld).getRegex(),Xi={_backpedal:Nr,anyPunctuation:Ed,anyPunctuationOutsideCode:Cd,autolink:Md,blockSkip:hd,br:pc,code:id,del:Nr,delLDelim:Nr,delRDelim:Nr,emStrongLDelim:dd,emStrongRDelimAst:gd,emStrongRDelimUnd:wd,escape:ad,link:Rd,nolink:Nd,punctuation:od,reflink:Dd,reflinkSearch:_d,tag:zd,text:sd,url:Nr},$d={...Xi,emStrongLDelim:fd,emStrongRDelimAst:yd,emStrongRDelimUnd:xd,link:oe(/^!?\[(label)\]\((.*?)\)/).replace("label",q0).getRegex(),reflink:oe(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",q0).getRegex()},ui={...Xi,emStrongRDelimAst:vd,emStrongLDelim:pd,delLDelim:Sd,delRDelim:Td,url:oe(/^emailProtocol|^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("emailProtocol",Od).replace("protocol",no).replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![\w-])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/,text:oe(/^(?:[^a-zA-Z0-9](?=emailProtocol)|(`+|~+|[^`~])(?:(?=[`~])|(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|wwwStart|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9](?=emailProtocol)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@))))/).replace("protocol",no).replace(/emailProtocol/g,/(?:mailto|xmpp):/).replace("wwwStart",cc?"(?<![^\\s*_~(])www\\.":"www\\.").getRegex()},Bd={...ui,br:oe(pc).replace("{2,}","*").getRegex(),text:oe(ui.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},S0={normal:Ki,gfm:rd,pedantic:nd},Mn={normal:Xi,gfm:ui,breaks:Bd,pedantic:$d},qd={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},ao=t=>qd[t];function mt(t,e){if(e){if(Ue.escapeTest.test(t))return t.replace(Ue.escapeReplace,ao)}else if(Ue.escapeTestNoEncode.test(t))return t.replace(Ue.escapeReplaceNoEncode,ao);return t}function Fd(t){return Ue.numericCharacterReference.test(t)?t.replace(Ue.numericCharacterReferenceOrAmpersand,(e,r,n)=>{if(r===void 0&&n===void 0)return"&amp;";let a=r===void 0?Number.parseInt(n,16):Number.parseInt(r,10);return a===0||a>1114111||a>=55296&&a<=57343?"�":a===38?"&amp;":String.fromCodePoint(a)}):t}function io(t){try{t=encodeURI(t).replace(Ue.percentDecode,"%")}catch{return null}return t}function so(t,e){let r=t.replace(Ue.findPipe,(i,s,o)=>{let c=!1,h=s;for(;--h>=0&&o[h]==="\\";)c=!c;return c?"|":" |"}),n=r.split(Ue.splitPipe),a=0;if(n[0].trim()||n.shift(),n.length>0&&!n.at(-1)?.trim()&&n.pop(),e)if(n.length>e)n.splice(e);else for(;n.length<e;)n.push("");for(;a<n.length;a++)n[a]=n[a].trim().replace(Ue.slashPipe,"|");return n}function qt(t,e,r){let n=t.length;if(n===0)return"";let a=0;for(;a<n&&t.charAt(n-a-1)===e;)a++;return t.slice(0,n-a)}function oo(t){let e=t.split(`
4
4
  `),r=e.length-1;for(;r>=0&&Ue.blankLine.test(e[r]);)r--;return e.length-r<=2?t:e.slice(0,r+1).join(`
@@ -1 +1 @@
1
- import{g as l,r as m,d as n}from"./CnDy2OA4.js";import{p}from"./DdpYiyRs.js";import{b as t,ay as o}from"./Bex9L_jH.js";import{M as u,a as f}from"./BBfR26V0.js";var c=f().RailroadEbnf.parser.LangiumParser,s=t(e=>{const r=e.alternatives.map(E);return r.length===1?r[0]:{type:"choice",alternatives:r}},"transformChoice"),E=t(e=>{const r=e.elements.map(y);return r.length===1?r[0]:{type:"sequence",elements:r}},"transformSequence"),i=t(e=>{switch(e.$type){case"EbnfTerminal":return{type:"terminal",value:e.value};case"EbnfNonTerminal":return{type:"nonterminal",name:e.name};case"EbnfSpecial":return{type:"special",text:e.text};case"EbnfGroup":return s(e.element);case"EbnfOptional":return{type:"optional",element:s(e.element)};case"EbnfRepetition":return{type:"repetition",element:s(e.element),min:0,max:1/0};default:throw new Error(`Unsupported EBNF primary node: ${e.$type}`)}},"transformPrimary"),b=t((e,r)=>{switch(r.$type){case"EbnfOptionalPostfix":return{type:"optional",element:e};case"EbnfZeroOrMorePostfix":return{type:"repetition",element:e,min:0,max:1/0};case"EbnfOneOrMorePostfix":return{type:"repetition",element:e,min:1,max:1/0};case"EbnfExceptionPostfix":return{type:"sequence",elements:[e,{type:"terminal",value:"-"},i(r.except)]};default:throw new Error(`Unsupported EBNF postfix node: ${r.$type}`)}},"transformPostfix"),y=t(e=>e.postfixes.reduce((r,a)=>b(r,a),i(e.base)),"transformTerm"),d=t(e=>({name:e.name,definition:s(e.definition)}),"transformRule"),v=t(e=>{p(e,n),e.title&&n.setTitle(e.title),e.rules.map(r=>n.addRule(d(r)))},"populateDb"),g={parse:t(e=>{n.clear(),o.debug("[EBNF Parser] Starting Langium parse");const r=c.parse(e);if(r.lexerErrors.length>0||r.parserErrors.length>0)throw new u(r);const a=r.value;o.debug("[EBNF Parser] Parsed rules:",a.rules.length),v(a),o.debug("[EBNF Parser] Parse complete")},"parse"),parser:{yy:n}},N={parser:g,db:n,renderer:m,styles:l};export{N as diagram};
1
+ import{g as l,r as m,d as n}from"./0biFhMxb.js";import{p}from"./DuiDeolO.js";import{b as t,ay as o}from"./DabFMHr_.js";import{M as u,a as f}from"./BBfR26V0.js";var c=f().RailroadEbnf.parser.LangiumParser,s=t(e=>{const r=e.alternatives.map(E);return r.length===1?r[0]:{type:"choice",alternatives:r}},"transformChoice"),E=t(e=>{const r=e.elements.map(y);return r.length===1?r[0]:{type:"sequence",elements:r}},"transformSequence"),i=t(e=>{switch(e.$type){case"EbnfTerminal":return{type:"terminal",value:e.value};case"EbnfNonTerminal":return{type:"nonterminal",name:e.name};case"EbnfSpecial":return{type:"special",text:e.text};case"EbnfGroup":return s(e.element);case"EbnfOptional":return{type:"optional",element:s(e.element)};case"EbnfRepetition":return{type:"repetition",element:s(e.element),min:0,max:1/0};default:throw new Error(`Unsupported EBNF primary node: ${e.$type}`)}},"transformPrimary"),b=t((e,r)=>{switch(r.$type){case"EbnfOptionalPostfix":return{type:"optional",element:e};case"EbnfZeroOrMorePostfix":return{type:"repetition",element:e,min:0,max:1/0};case"EbnfOneOrMorePostfix":return{type:"repetition",element:e,min:1,max:1/0};case"EbnfExceptionPostfix":return{type:"sequence",elements:[e,{type:"terminal",value:"-"},i(r.except)]};default:throw new Error(`Unsupported EBNF postfix node: ${r.$type}`)}},"transformPostfix"),y=t(e=>e.postfixes.reduce((r,a)=>b(r,a),i(e.base)),"transformTerm"),d=t(e=>({name:e.name,definition:s(e.definition)}),"transformRule"),v=t(e=>{p(e,n),e.title&&n.setTitle(e.title),e.rules.map(r=>n.addRule(d(r)))},"populateDb"),g={parse:t(e=>{n.clear(),o.debug("[EBNF Parser] Starting Langium parse");const r=c.parse(e);if(r.lexerErrors.length>0||r.parserErrors.length>0)throw new u(r);const a=r.value;o.debug("[EBNF Parser] Parsed rules:",a.rules.length),v(a),o.debug("[EBNF Parser] Parse complete")},"parse"),parser:{yy:n}},N={parser:g,db:n,renderer:m,styles:l};export{N as diagram};
@@ -1,2 +1,2 @@
1
- import{JH as l,s2 as u,Jk as b}from"./D0qhIm1r.js";import{au as v}from"./BeZe2Rt-.js";import{bJ as m}from"./cD292w1o.js";import{bd as S,b9 as P}from"./B3ZeLze4.js";import{L as M}from"./CDCAMh6o.js";import{bm as s}from"./Fcr7AvC-.js";import{l as E}from"./C7b3vXLD.js";const D=l.createSelector(t=>t.backgroundAgentSettings.defaultModel),O=l.createSelector(t=>t.backgroundAgentSettings.typeOverrides),H=l.createSelector(t=>t.backgroundAgentSettings.defaultReasoningEffort),j=l.createSelector(t=>t.backgroundAgentSettings.typeReasoningEffortOverrides),w=l.createSelector(t=>t.backgroundAgentSettings),A=l.createSelector(t=>{const a=new Map,o=(e,i)=>{const n=a.get(e)??new Set;n.add(i),a.set(e,n)},f=m.select(t),d=M.select(t),g=v.select(t)[d];g&&d&&o(d,s.settings_providers_inUseDefaultModel_label({model:g})),u(d)&&!g&&o(d,s.settings_providers_inUseDefaultProvider_label());const p=t.backgroundAgentSettings?.providerId;p&&u(p)&&o(p,s.settings_providers_inUseQuickActions_label());for(const e of S.select(t)){const i=P.select(t,e.id),n=e.source?{project:s.settings_providers_pinSourceProject_label(),user:s.settings_providers_pinSourceUser_label(),bundled:s.settings_providers_pinSourceBundled_label(),builtin:s.settings_providers_pinSourceBuiltin_label(),"electron-store":s.settings_providers_pinSourceLegacy_label()}[e.source]:void 0,c=r=>n&&i?s.settings_providers_inUseSourcePath_label({reason:r,source:n,path:i}):n?s.settings_providers_inUseSource_label({reason:r,source:n}):i?s.settings_providers_inUsePath_label({reason:r,path:i}):r;if(e.codingAgent&&o(e.codingAgent,c(s.settings_providers_inUseSpecialistAgent_label({name:e.name}))),e.modelOptions?.forEach((r,_)=>{r.provider&&u(r.provider)&&o(r.provider,c(s.settings_providers_inUseSpecialistModelOption_label({name:e.name,position:E(_+1)})))}),e.defaultModel)if(e.defaultModel.includes(":")){const r=b(e.defaultModel).providerId??f;o(r,c(s.settings_providers_inUseSpecialistModel_label({name:e.name,model:e.defaultModel})))}else e.codingAgent||o(f,c(s.settings_providers_inUseSpecialistModel_label({name:e.name,model:e.defaultModel})))}return Object.fromEntries([...a].map(([e,i])=>[e,[...i].join(`
1
+ import{JH as l,s2 as u,Jk as b}from"./D0qhIm1r.js";import{au as v}from"./BeZe2Rt-.js";import{bJ as m}from"./cD292w1o.js";import{bd as S,b9 as P}from"./OrDYwyck.js";import{L as M}from"./CDCAMh6o.js";import{bm as s}from"./Fcr7AvC-.js";import{l as E}from"./C7b3vXLD.js";const D=l.createSelector(t=>t.backgroundAgentSettings.defaultModel),O=l.createSelector(t=>t.backgroundAgentSettings.typeOverrides),H=l.createSelector(t=>t.backgroundAgentSettings.defaultReasoningEffort),j=l.createSelector(t=>t.backgroundAgentSettings.typeReasoningEffortOverrides),w=l.createSelector(t=>t.backgroundAgentSettings),A=l.createSelector(t=>{const a=new Map,o=(e,i)=>{const n=a.get(e)??new Set;n.add(i),a.set(e,n)},f=m.select(t),d=M.select(t),g=v.select(t)[d];g&&d&&o(d,s.settings_providers_inUseDefaultModel_label({model:g})),u(d)&&!g&&o(d,s.settings_providers_inUseDefaultProvider_label());const p=t.backgroundAgentSettings?.providerId;p&&u(p)&&o(p,s.settings_providers_inUseQuickActions_label());for(const e of S.select(t)){const i=P.select(t,e.id),n=e.source?{project:s.settings_providers_pinSourceProject_label(),user:s.settings_providers_pinSourceUser_label(),bundled:s.settings_providers_pinSourceBundled_label(),builtin:s.settings_providers_pinSourceBuiltin_label(),"electron-store":s.settings_providers_pinSourceLegacy_label()}[e.source]:void 0,c=r=>n&&i?s.settings_providers_inUseSourcePath_label({reason:r,source:n,path:i}):n?s.settings_providers_inUseSource_label({reason:r,source:n}):i?s.settings_providers_inUsePath_label({reason:r,path:i}):r;if(e.codingAgent&&o(e.codingAgent,c(s.settings_providers_inUseSpecialistAgent_label({name:e.name}))),e.modelOptions?.forEach((r,_)=>{r.provider&&u(r.provider)&&o(r.provider,c(s.settings_providers_inUseSpecialistModelOption_label({name:e.name,position:E(_+1)})))}),e.defaultModel)if(e.defaultModel.includes(":")){const r=b(e.defaultModel).providerId??f;o(r,c(s.settings_providers_inUseSpecialistModel_label({name:e.name,model:e.defaultModel})))}else e.codingAgent||o(f,c(s.settings_providers_inUseSpecialistModel_label({name:e.name,model:e.defaultModel})))}return Object.fromEntries([...a].map(([e,i])=>[e,[...i].join(`
2
2
  `)]))});l.createSelector((t,a)=>A.select(t)[a]??null);const h=[{id:"dracula",label:"Dracula"},{id:"nord",label:"Nord"},{id:"rose-pine",label:"Rosé Pine"},{id:"tokyo-night",label:"Tokyo Night"},{id:"solarized",label:"Solarized"},{id:"github",label:"GitHub"},{id:"high-contrast",label:"High Contrast"}],J=h.map(({id:t})=>t);export{J as T,h as a,H as b,w as c,O as d,j as e,A as f,D as s};