9remote 3.0.51 → 3.0.52

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 (192) hide show
  1. package/dist/cli.cjs +2 -2
  2. package/dist/server.cjs +6 -6
  3. package/dist/ui/assets/index-BgdHbxnD.js +8 -0
  4. package/dist/ui/index.html +1 -1
  5. package/dist/web/404.html +1 -1
  6. package/dist/web/__next.__PAGE__.txt +1 -1
  7. package/dist/web/__next._full.txt +1 -1
  8. package/dist/web/__next._head.txt +1 -1
  9. package/dist/web/__next._index.txt +1 -1
  10. package/dist/web/__next._tree.txt +1 -1
  11. package/dist/web/_not-found/__next._full.txt +1 -1
  12. package/dist/web/_not-found/__next._head.txt +1 -1
  13. package/dist/web/_not-found/__next._index.txt +1 -1
  14. package/dist/web/_not-found/__next._not-found.__PAGE__.txt +1 -1
  15. package/dist/web/_not-found/__next._not-found.txt +1 -1
  16. package/dist/web/_not-found/__next._tree.txt +1 -1
  17. package/dist/web/_not-found.html +1 -1
  18. package/dist/web/_not-found.txt +1 -1
  19. package/dist/web/admin/__next._full.txt +1 -1
  20. package/dist/web/admin/__next._head.txt +1 -1
  21. package/dist/web/admin/__next._index.txt +1 -1
  22. package/dist/web/admin/__next._tree.txt +1 -1
  23. package/dist/web/admin/__next.admin.__PAGE__.txt +1 -1
  24. package/dist/web/admin/__next.admin.txt +1 -1
  25. package/dist/web/admin/access/__next._full.txt +1 -1
  26. package/dist/web/admin/access/__next._head.txt +1 -1
  27. package/dist/web/admin/access/__next._index.txt +1 -1
  28. package/dist/web/admin/access/__next._tree.txt +1 -1
  29. package/dist/web/admin/access/__next.admin.access.__PAGE__.txt +1 -1
  30. package/dist/web/admin/access/__next.admin.access.txt +1 -1
  31. package/dist/web/admin/access/__next.admin.txt +1 -1
  32. package/dist/web/admin/access.html +1 -1
  33. package/dist/web/admin/access.txt +1 -1
  34. package/dist/web/admin/login/__next._full.txt +1 -1
  35. package/dist/web/admin/login/__next._head.txt +1 -1
  36. package/dist/web/admin/login/__next._index.txt +1 -1
  37. package/dist/web/admin/login/__next._tree.txt +1 -1
  38. package/dist/web/admin/login/__next.admin.login.__PAGE__.txt +1 -1
  39. package/dist/web/admin/login/__next.admin.login.txt +1 -1
  40. package/dist/web/admin/login/__next.admin.txt +1 -1
  41. package/dist/web/admin/login.html +1 -1
  42. package/dist/web/admin/login.txt +1 -1
  43. package/dist/web/admin/ota/__next._full.txt +1 -1
  44. package/dist/web/admin/ota/__next._head.txt +1 -1
  45. package/dist/web/admin/ota/__next._index.txt +1 -1
  46. package/dist/web/admin/ota/__next._tree.txt +1 -1
  47. package/dist/web/admin/ota/__next.admin.ota.__PAGE__.txt +1 -1
  48. package/dist/web/admin/ota/__next.admin.ota.txt +1 -1
  49. package/dist/web/admin/ota/__next.admin.txt +1 -1
  50. package/dist/web/admin/ota.html +1 -1
  51. package/dist/web/admin/ota.txt +1 -1
  52. package/dist/web/admin/turn/__next._full.txt +1 -1
  53. package/dist/web/admin/turn/__next._head.txt +1 -1
  54. package/dist/web/admin/turn/__next._index.txt +1 -1
  55. package/dist/web/admin/turn/__next._tree.txt +1 -1
  56. package/dist/web/admin/turn/__next.admin.turn.__PAGE__.txt +1 -1
  57. package/dist/web/admin/turn/__next.admin.turn.txt +1 -1
  58. package/dist/web/admin/turn/__next.admin.txt +1 -1
  59. package/dist/web/admin/turn.html +1 -1
  60. package/dist/web/admin/turn.txt +1 -1
  61. package/dist/web/admin.html +1 -1
  62. package/dist/web/admin.txt +1 -1
  63. package/dist/web/download/__next._full.txt +1 -1
  64. package/dist/web/download/__next._head.txt +1 -1
  65. package/dist/web/download/__next._index.txt +1 -1
  66. package/dist/web/download/__next._tree.txt +1 -1
  67. package/dist/web/download/__next.download.__PAGE__.txt +1 -1
  68. package/dist/web/download/__next.download.txt +1 -1
  69. package/dist/web/download.html +1 -1
  70. package/dist/web/download.txt +1 -1
  71. package/dist/web/index.html +1 -1
  72. package/dist/web/index.txt +1 -1
  73. package/dist/web/login/__next._full.txt +1 -1
  74. package/dist/web/login/__next._head.txt +1 -1
  75. package/dist/web/login/__next._index.txt +1 -1
  76. package/dist/web/login/__next._tree.txt +1 -1
  77. package/dist/web/login/__next.login.__PAGE__.txt +1 -1
  78. package/dist/web/login/__next.login.txt +1 -1
  79. package/dist/web/login.html +1 -1
  80. package/dist/web/login.txt +1 -1
  81. package/dist/web/workspace/__next._full.txt +1 -1
  82. package/dist/web/workspace/__next._head.txt +1 -1
  83. package/dist/web/workspace/__next._index.txt +1 -1
  84. package/dist/web/workspace/__next._tree.txt +1 -1
  85. package/dist/web/workspace/__next.workspace.__PAGE__.txt +1 -1
  86. package/dist/web/workspace/__next.workspace.txt +1 -1
  87. package/dist/web/workspace/browse/__next._full.txt +1 -1
  88. package/dist/web/workspace/browse/__next._head.txt +1 -1
  89. package/dist/web/workspace/browse/__next._index.txt +1 -1
  90. package/dist/web/workspace/browse/__next._tree.txt +1 -1
  91. package/dist/web/workspace/browse/__next.workspace.browse.__PAGE__.txt +1 -1
  92. package/dist/web/workspace/browse/__next.workspace.browse.txt +1 -1
  93. package/dist/web/workspace/browse/__next.workspace.txt +1 -1
  94. package/dist/web/workspace/browse.html +1 -1
  95. package/dist/web/workspace/browse.txt +1 -1
  96. package/dist/web/workspace/editor/__next._full.txt +1 -1
  97. package/dist/web/workspace/editor/__next._head.txt +1 -1
  98. package/dist/web/workspace/editor/__next._index.txt +1 -1
  99. package/dist/web/workspace/editor/__next._tree.txt +1 -1
  100. package/dist/web/workspace/editor/__next.workspace.editor.__PAGE__.txt +1 -1
  101. package/dist/web/workspace/editor/__next.workspace.editor.txt +1 -1
  102. package/dist/web/workspace/editor/__next.workspace.txt +1 -1
  103. package/dist/web/workspace/editor.html +1 -1
  104. package/dist/web/workspace/editor.txt +1 -1
  105. package/dist/web/workspace/files/__next._full.txt +1 -1
  106. package/dist/web/workspace/files/__next._head.txt +1 -1
  107. package/dist/web/workspace/files/__next._index.txt +1 -1
  108. package/dist/web/workspace/files/__next._tree.txt +1 -1
  109. package/dist/web/workspace/files/__next.workspace.files.__PAGE__.txt +1 -1
  110. package/dist/web/workspace/files/__next.workspace.files.txt +1 -1
  111. package/dist/web/workspace/files/__next.workspace.txt +1 -1
  112. package/dist/web/workspace/files.html +1 -1
  113. package/dist/web/workspace/files.txt +1 -1
  114. package/dist/web/workspace/git/__next._full.txt +1 -1
  115. package/dist/web/workspace/git/__next._head.txt +1 -1
  116. package/dist/web/workspace/git/__next._index.txt +1 -1
  117. package/dist/web/workspace/git/__next._tree.txt +1 -1
  118. package/dist/web/workspace/git/__next.workspace.git.__PAGE__.txt +1 -1
  119. package/dist/web/workspace/git/__next.workspace.git.txt +1 -1
  120. package/dist/web/workspace/git/__next.workspace.txt +1 -1
  121. package/dist/web/workspace/git.html +1 -1
  122. package/dist/web/workspace/git.txt +1 -1
  123. package/dist/web/workspace/mobile/__next._full.txt +1 -1
  124. package/dist/web/workspace/mobile/__next._head.txt +1 -1
  125. package/dist/web/workspace/mobile/__next._index.txt +1 -1
  126. package/dist/web/workspace/mobile/__next._tree.txt +1 -1
  127. package/dist/web/workspace/mobile/__next.workspace.mobile.__PAGE__.txt +1 -1
  128. package/dist/web/workspace/mobile/__next.workspace.mobile.txt +1 -1
  129. package/dist/web/workspace/mobile/__next.workspace.txt +1 -1
  130. package/dist/web/workspace/mobile.html +1 -1
  131. package/dist/web/workspace/mobile.txt +1 -1
  132. package/dist/web/workspace/pair/__next._full.txt +1 -1
  133. package/dist/web/workspace/pair/__next._head.txt +1 -1
  134. package/dist/web/workspace/pair/__next._index.txt +1 -1
  135. package/dist/web/workspace/pair/__next._tree.txt +1 -1
  136. package/dist/web/workspace/pair/__next.workspace.pair.__PAGE__.txt +1 -1
  137. package/dist/web/workspace/pair/__next.workspace.pair.txt +1 -1
  138. package/dist/web/workspace/pair/__next.workspace.txt +1 -1
  139. package/dist/web/workspace/pair.html +1 -1
  140. package/dist/web/workspace/pair.txt +1 -1
  141. package/dist/web/workspace/remote/__next._full.txt +1 -1
  142. package/dist/web/workspace/remote/__next._head.txt +1 -1
  143. package/dist/web/workspace/remote/__next._index.txt +1 -1
  144. package/dist/web/workspace/remote/__next._tree.txt +1 -1
  145. package/dist/web/workspace/remote/__next.workspace.remote.__PAGE__.txt +1 -1
  146. package/dist/web/workspace/remote/__next.workspace.remote.txt +1 -1
  147. package/dist/web/workspace/remote/__next.workspace.txt +1 -1
  148. package/dist/web/workspace/remote.html +1 -1
  149. package/dist/web/workspace/remote.txt +1 -1
  150. package/dist/web/workspace/settings/__next._full.txt +1 -1
  151. package/dist/web/workspace/settings/__next._head.txt +1 -1
  152. package/dist/web/workspace/settings/__next._index.txt +1 -1
  153. package/dist/web/workspace/settings/__next._tree.txt +1 -1
  154. package/dist/web/workspace/settings/__next.workspace.settings.__PAGE__.txt +1 -1
  155. package/dist/web/workspace/settings/__next.workspace.settings.txt +1 -1
  156. package/dist/web/workspace/settings/__next.workspace.txt +1 -1
  157. package/dist/web/workspace/settings.html +1 -1
  158. package/dist/web/workspace/settings.txt +1 -1
  159. package/dist/web/workspace/terminal/default/__next._full.txt +1 -1
  160. package/dist/web/workspace/terminal/default/__next._head.txt +1 -1
  161. package/dist/web/workspace/terminal/default/__next._index.txt +1 -1
  162. package/dist/web/workspace/terminal/default/__next._tree.txt +1 -1
  163. package/dist/web/workspace/terminal/default/__next.workspace.terminal.$d$sessionId.__PAGE__.txt +1 -1
  164. package/dist/web/workspace/terminal/default/__next.workspace.terminal.$d$sessionId.txt +1 -1
  165. package/dist/web/workspace/terminal/default/__next.workspace.terminal.txt +1 -1
  166. package/dist/web/workspace/terminal/default/__next.workspace.txt +1 -1
  167. package/dist/web/workspace/terminal/default.html +1 -1
  168. package/dist/web/workspace/terminal/default.txt +1 -1
  169. package/dist/web/workspace/welcome/__next._full.txt +1 -1
  170. package/dist/web/workspace/welcome/__next._head.txt +1 -1
  171. package/dist/web/workspace/welcome/__next._index.txt +1 -1
  172. package/dist/web/workspace/welcome/__next._tree.txt +1 -1
  173. package/dist/web/workspace/welcome/__next.workspace.txt +1 -1
  174. package/dist/web/workspace/welcome/__next.workspace.welcome.__PAGE__.txt +1 -1
  175. package/dist/web/workspace/welcome/__next.workspace.welcome.txt +1 -1
  176. package/dist/web/workspace/welcome.html +1 -1
  177. package/dist/web/workspace/welcome.txt +1 -1
  178. package/dist/web/workspace/workspaces/__next._full.txt +1 -1
  179. package/dist/web/workspace/workspaces/__next._head.txt +1 -1
  180. package/dist/web/workspace/workspaces/__next._index.txt +1 -1
  181. package/dist/web/workspace/workspaces/__next._tree.txt +1 -1
  182. package/dist/web/workspace/workspaces/__next.workspace.txt +1 -1
  183. package/dist/web/workspace/workspaces/__next.workspace.workspaces.__PAGE__.txt +1 -1
  184. package/dist/web/workspace/workspaces/__next.workspace.workspaces.txt +1 -1
  185. package/dist/web/workspace/workspaces.html +1 -1
  186. package/dist/web/workspace/workspaces.txt +1 -1
  187. package/dist/web/workspace.html +1 -1
  188. package/dist/web/workspace.txt +1 -1
  189. package/package.json +1 -1
  190. package/dist/ui/assets/index-DBIJ-xKe.js +0 -8
  191. /package/dist/web/_next/static/{LIdIrEk-ouqVQIPGxkDup → Sbm6VmM9scgfPUKCTCQc1}/_buildManifest.js +0 -0
  192. /package/dist/web/_next/static/{LIdIrEk-ouqVQIPGxkDup → Sbm6VmM9scgfPUKCTCQc1}/_ssgManifest.js +0 -0
package/dist/server.cjs CHANGED
@@ -220,10 +220,10 @@ Cost: $${Number(t.cost).toFixed(2)}`:"")+n}var V0,Zoe=ne(()=>{uq();V0=class exte
220
220
  `)){let r;try{r=JSON.parse(n)}catch{continue}if(!(r?.type!=="response"||r.id!=="m1"||r.success===!1))for(let i of Array.isArray(r.data?.models)?r.data.models:[]){if(!i?.id||!i.provider)continue;let s=i.provider==="9router"?i.id:i.name||i.id;e.push({id:`${i.provider}/${i.id}`,provider:i.provider,label:s,short:s,desc:"",efforts:[],defaultEffort:"",contextWindow:i.contextWindow||0})}}return e.sort((n,r)=>n.provider.localeCompare(r.provider)||n.label.localeCompare(r.label))}function cae(){let t="";try{let e=(0,Dh.spawnSync)("pi",["--mode","rpc","--no-session"],{input:JSON.stringify({id:"m1",type:"get_available_models"})+`
221
221
  `,encoding:"utf8",timeout:Y0});!e.error&&e.status===0&&(t=e.stdout||"")}catch{return[]}return j4e(t)}function W4e(){let t="";try{let n=(0,Dh.spawnSync)("omp",["models","--json"],{encoding:"utf8",timeout:Y0});!n.error&&n.status===0&&(t=n.stdout||"")}catch{return[]}let e=[];try{e=JSON.parse(t).models||[]}catch{return[]}return e.filter(n=>n?.id&&n.provider).map(n=>{let r=n.selector||`${n.provider}/${n.id}`,i=n.provider==="9router"?n.id:n.name||n.id;return{id:r,provider:n.provider,label:i,short:i,desc:"",efforts:Array.isArray(n.thinking)?n.thinking:[],defaultEffort:"",contextWindow:n.contextWindow||0}}).sort((n,r)=>n.provider.localeCompare(r.provider)||n.label.localeCompare(r.label))}function z4e(){let t="";try{let r=(0,Dh.spawnSync)("devin",["models","list","--format","json"],{encoding:"utf8",env:xr(),timeout:Y0});!r.error&&r.status===0&&(t=r.stdout||"")}catch{return[]}let e=[];try{e=JSON.parse(t).families||[]}catch{return[]}let n=[];for(let r of e)for(let i of r.variants||[])i.model_uid&&n.push({id:i.model_uid,provider:r.family_label||r.slug||"Devin",label:i.label||i.model_uid,short:i.label||i.model_uid,desc:i.cost_summary||"",efforts:[],defaultEffort:"",contextWindow:0});return n.sort((r,i)=>r.provider.localeCompare(i.provider)||r.label.localeCompare(i.label))}async function lae(){let t=new Map,e=[];try{let i=eo.default.join(rl.default.homedir(),".local","state","opencode","model.json"),s=JSON.parse(Ji.default.readFileSync(i,"utf8"));for(let o of s?.recent||[])o?.providerID&&o?.modelID&&e.push(`${o.providerID}/${o.modelID}`)}catch{}for(let i of X0()){let s=i.id.startsWith("opencode-go/")?"opencode-go":"opencode";t.set(i.id,{...i,provider:s,label:i.label||i.id,short:i.short||i.id,desc:i.desc||"",contextWindow:i.contextWindow||0})}let n=await G4e();for(let i of n){let s=t.get(i.id),o=i.id.startsWith("opencode-go/")?"opencode-go":"opencode";t.set(i.id,{...s,...i,provider:o,label:i.label||s?.label||i.id,short:i.short||s?.short||i.id})}return Array.from(t.values()).map(i=>{let s=e.indexOf(i.id);return{...i,recent:s>=0,recentRank:s>=0?s:999}})}function fae(t,e){let n=new RegExp(`^${e}:\\s*$`,"m").exec(t);if(!n)return"";let r=t.slice(n.index+n[0].length),i=/^[A-Za-z_]/m.exec(r);return i?r.slice(0,i.index):r}function hae(t){let e=dae(),n=Ji.default.readFileSync(e,"utf8"),r=/^agent:[ \t]*$/m.exec(n);if(!r)throw new Error("No agent: block in ~/.hermes/config.yaml");let i=r.index+r[0].length,s=n.slice(i),o=/^[A-Za-z_]/m.exec(s),a=o?i+o.index:n.length,c=n.slice(i,a);if(!/^[ \t]*reasoning_effort:/m.test(c))throw new Error("No agent.reasoning_effort key in ~/.hermes/config.yaml");let l=c.replace(/^([ \t]*reasoning_effort:\s*).*$/m,`$1${t}`);Ji.default.writeFileSync(e,n.slice(0,i)+l+n.slice(a))}function mae(t){pq=Array.isArray(t)&&t.length?t:null}function V4e(){if(pq)return pq;let t=fae(pae(),"model"),e=/^\s*default:\s*["']?([^"'\n]+)/m.exec(t)?.[1]?.trim()||"";if(!e)return[];let n=/^\s*provider:\s*["']?([^"'\n]+)/m.exec(t)?.[1]?.trim()||"",r=n&&!e.startsWith(`${n}:`)?`${n}:${e}`:e;return[{id:r,label:r,short:r,desc:"",efforts:[],defaultEffort:"",contextWindow:0}]}var Ji,rl,eo,Dh,nae,M4e,rae,O4e,N4e,Y0,L4e,iae,B4e,rR,q4e,$4e,uae,dae,pae,pq,sR=ne(()=>{Ji=Q(require("fs"),1),rl=Q(require("os"),1),eo=Q(require("path"),1),Dh=require("node:child_process"),nae=require("node:module");qt();qo();nc();Jo();M4e=(0,nae.createRequire)(__importMetaUrl),rae=[["ANTHROPIC_CUSTOM_MODEL_OPTION","Custom"],["ANTHROPIC_DEFAULT_FABLE_MODEL","Fable"],["ANTHROPIC_DEFAULT_OPUS_MODEL","Opus"],["ANTHROPIC_DEFAULT_SONNET_MODEL","Sonnet"],["ANTHROPIC_DEFAULT_HAIKU_MODEL","Haiku"]],O4e=[{id:"haiku",label:"Haiku"},{id:"sonnet",label:"Sonnet"},{id:"opus",label:"Opus"}],N4e=5e3,Y0=1e4;L4e=[{id:"gpt-5.6-sol",label:"GPT-5.6-Sol",short:"5.6 Sol",provider:"openai",desc:"Flagship reasoning model for complex engineering"},{id:"gpt-5.6-terra",label:"GPT-5.6-Terra",short:"5.6 Terra",provider:"openai",desc:"High-throughput balanced model"},{id:"gpt-5.6-luna",label:"GPT-5.6-Luna",short:"5.6 Luna",provider:"openai",desc:"Fast, lightweight reasoning model"},{id:"gpt-5.5",label:"GPT-5.5",short:"5.5",provider:"openai",desc:"Advanced reasoning and coding model"},{id:"gpt-5.3-codex",label:"GPT-5.3-Codex",short:"5.3 Codex",provider:"openai",desc:"Specialized code generation & editing model"},{id:"gpt-5.1-codex-max",label:"GPT-5.1-Codex-Max",short:"5.1 Max",provider:"openai",desc:"Large-context deep reasoning model"},{id:"gpt-5.1-codex-mini",label:"GPT-5.1-Codex-Mini",short:"5.1 Mini",provider:"openai",desc:"Fast, cost-effective coding model"},{id:"gpt-6-astra",label:"GPT-6-Astra",short:"6 Astra",provider:"openai",desc:"Our most capable model for complex, demanding work"}];iae=eo.default.join(Pe.STATE,"aiPreferences.json");B4e={claude:D4e,codex:U4e,opencode:X0,antigravity:H4e,omp:W4e,pi:cae,devin:z4e,hermes:V4e};rR={at:0,id:""},q4e={claude(){let t=fq(),e=typeof t.model=="string"?t.model:"";if(!e)return"";let n=rae.find(([r,i])=>i.toLowerCase()===e.toLowerCase());return n&&t.env?.[n[0]]||e},codex(){try{let t=eo.default.join(rl.default.homedir(),".codex","config.toml"),n=Ji.default.readFileSync(t,"utf8").split(/^\s*\[/m)[0]||"";return/^\s*model\s*=\s*"([^"]+)"/m.exec(n)?.[1]||""}catch{return""}},opencode(){try{let t=eo.default.join(rl.default.homedir(),".local","state","opencode","model.json"),e=JSON.parse(Ji.default.readFileSync(t,"utf8")).recent||[],{providerID:n,modelID:r}=e[0]||{};if(!n||!r)return"";let i=`${n}/${r}`,s=X0();return s.length===0||s.some(o=>o.id===i)?i:""}catch{return""}},omp(){try{let t=eo.default.join(rl.default.homedir(),".omp","agent","config.yml"),e=Ji.default.readFileSync(t,"utf8"),n=/^\s*default:\s*([^\s\n]+)/m.exec(e);if(n?.[1])return n[1].trim()}catch{return""}},pi(){let t=Date.now();if(rR.id&&t-rR.at<MC)return rR.id;let e=cae()[0]?.id||"";return e&&(rR={at:t,id:e}),e},devin(){try{let{DatabaseSync:t}=M4e("node:sqlite"),e=eo.default.join(rl.default.homedir(),".local","share","devin","cli","sessions.db");if(!Ji.default.existsSync(e))return"";let n=new t(e,{readOnly:!0});try{return n.prepare("SELECT model FROM sessions WHERE model IS NOT NULL AND model != '' ORDER BY last_activity_at DESC LIMIT 1").get()?.model||""}finally{n.close()}}catch{return""}}};$4e={claude(){let t=fq().effortLevel;return typeof t=="string"?t.trim():""},codex(){try{let e=Ji.default.readFileSync(eo.default.join(rl.default.homedir(),".codex","config.toml"),"utf8").split(/^\s*\[/m)[0]||"";return/^\s*model_reasoning_effort\s*=\s*"([^"]+)"/m.exec(e)?.[1]||""}catch{return""}},hermes(){return/^\s*reasoning_effort:\s*["']?([\w-]+)/m.exec(fae(pae(),"agent"))?.[1]||""}};uae=new Set(["none","minimal","low","medium","high","xhigh","max","ultra"]),dae=()=>eo.default.join(rl.default.homedir(),".hermes","config.yaml"),pae=()=>{try{return Ji.default.readFileSync(dae(),"utf8")}catch{return""}};pq=null});function _ae(t,e){let n=(Array.isArray(t)?t:[]).find(r=>r?.type==="diff"&&r.path);return n?{file:n.path,name:e,patch:L0(e,{old_string:n.oldText,new_string:n.newText}),content:""}:null}var ikt,Vy,gae,K4e,yae,Y4e,vae,J0,wae=ne(()=>{Iu();O0();Cu();U0();nc();sR();mp();$e();ikt=Ee("ai"),Vy=6e4,gae=6e5,K4e=5e3,yae=t=>(Array.isArray(t)?t:[]).map(e=>e?.content?.text??e?.text??"").filter(Boolean).join(`
222
222
  `),Y4e=[[/^terminal: /,"terminal"],[/^read: /,"read_file"],[/^write: /,"write_file"],[/^patch \(/,"patch"],[/^search: /,"search_files"],[/^web search: /,"web_search"],[/^extract: /,"web_extract"],[/^delegate: /,"delegate_task"],[/^execute code/,"execute_code"],[/^analyze image: /,"vision_analyze"]],vae=t=>{for(let[e,n]of Y4e)if(e.test(t||""))return n;return String(t||"tool")};J0=class t{constructor({cwd:e,onEvent:n,proc:r=null,sessionId:i=null,model:s="",hostSessionId:o=null}={}){this.cwd=e||process.cwd(),this.onEvent=n,this.hostSessionId=o,this.proc=r||new rc({procId:""}),this.activeSessionId=i||null,this._resumeId=i||null,this.isTurnRunning=!1,this.currentModel=s||"",this.pendingRequests=new Map,this.toolCalls=new Map,this._toolSeq=0,this._planSeq=0,this.stats={inputTokens:0,outputTokens:0,cachedTokens:0,reasoningTokens:0,totalTurns:0,contextTokens:0,contextWindow:0},this.metadata={model:this.currentModel,sessionId:this.activeSessionId||"",permissionMode:"default",effort:"",threadName:"",commands:[]},this.desiredMode=null,this._spawnedYolo=null,this.currentEffort="",this._pendingEffortApply=null,this._titledSession=null,this._titleTimer=null,this._catalogEmitted=!1,this._stopping=null}_warn(e){this.onEvent?.("cli_event",{type:"warning",record:{message:e}})}static _modelOptions(e){return(Array.isArray(e?.availableModels)?e.availableModels:[]).map(r=>{let i=String(r?.modelId||"").trim();if(!i)return null;let s=i.includes(":")?i.slice(0,i.indexOf(":")):"";return{id:i,label:String(r?.name||i),short:String(r?.name||i),...s?{provider:s}:{}}}).filter(Boolean)}_spawnArgs(){return[...this.desiredMode==="dont_ask"?["--yolo"]:[],"acp","--accept-hooks"]}async _ensureStarted(){if(this.rpc)return;this._stopping&&(await this._stopping,this._stopping=null),this._spawnedYolo=this.desiredMode==="dont_ask";let e=await this.proc.start({bin:"hermes",args:this._spawnArgs(),cwd:this.cwd,env:xr({hostSessionId:this.hostSessionId}),keepStdin:!0});this.rpc=new Qo(this.proc,{onMessage:i=>this.handleFrame(i)}),this.rpc.on("session/request_permission",(i,s)=>this._onPermission(i,s)),this.rpc.onExit(i=>this._handleExit(i)),e.commit?.(i=>this.rpc.feed(i)),await this.rpc.request("initialize",{protocolVersion:1,clientCapabilities:{fs:{readTextFile:!1,writeTextFile:!1}}},{timeoutMs:Vy});let n={cwd:this.cwd,mcpServers:[]},r=null;if(this._resumeId)try{r=await this.rpc.request("session/load",{...n,sessionId:this._resumeId},{timeoutMs:Vy})}catch{this._resumeId=null,this._warn("Hermes could not reopen that conversation (older versions cannot load past sessions into the pane \u2014 `hermes update` helps). Starting a new one.")}r||=await this.rpc.request("session/new",n,{timeoutMs:Vy}),this._absorbSession(r),this.desiredMode&&this.desiredMode!==this.metadata.permissionMode&&this.rpc.request("session/set_mode",{sessionId:this.activeSessionId,modeId:this.desiredMode},{timeoutMs:Vy}).then(()=>{this.metadata.permissionMode=this.desiredMode,this._emitInit()}).catch(()=>{}),this._scheduleTitleRefresh(),this._emitInit()}_absorbSession(e){this.activeSessionId=this._resumeId=e.sessionId||this._resumeId,this.metadata.sessionId=this.activeSessionId||"";let n=t._modelOptions(e.models);n.length&&(this.metadata.modelOptions=n,mae(n)),!this.currentModel&&e.models?.currentModelId&&(this.currentModel=this.metadata.model=e.models.currentModelId),e.modes?.currentModeId&&(this.metadata.permissionMode=e.modes.currentModeId)}_handleExit({code:e,signal:n,error:r}={}){let i=this.isTurnRunning;this.rpc=null,this.isTurnRunning=!1,this.pendingRequests.clear(),r?this.onEvent?.("error",{message:r}):i&&this.onEvent?.("turn_complete",{stats:this.stats,result:e!=null&&e!==0?`Hermes exited (code ${e}).`:n?`Hermes was killed (${n})`:"",isError:e!=null&&e!==0||!!n,subtype:"exit"})}setOptions({model:e,mode:n,effort:r,resume:i}={}){if(e&&e!==this.currentModel&&(this.currentModel=this.metadata.model=e,this.rpc&&this.rpc.request("session/set_model",{sessionId:this.activeSessionId,modelId:e},{timeoutMs:Vy}).catch(()=>{if(this.isTurnRunning){this._warn("Hermes applies a new model when the turn ends \u2014 pick it again then.");return}this._slash(`/model ${e}`)})),n&&n!==this.metadata.permissionMode&&(this.desiredMode=n,this.rpc?this._spawnedYolo!==null&&n==="dont_ask"!==this._spawnedYolo?(this.metadata.permissionMode=n,this._recycle(),this._warn("Hermes permission level changed \u2014 its process restarts to apply.")):this.rpc.request("session/set_mode",{sessionId:this.activeSessionId,modeId:n},{timeoutMs:Vy}).then(()=>{this.metadata.permissionMode=n,this._emitInit()}).catch(()=>this._warn("This Hermes version holds its mode in config \u2014 the pane shows it but cannot switch.")):this.metadata.permissionMode=n),typeof r=="string"&&uae.has(r)&&(r!==this.currentEffort&&(this.currentEffort=r,this.metadata.effort=r),r!==iR("hermes"))){let s=()=>{try{hae(r),this._recycle(),this._warn(`Hermes thinking level set to ${r} \u2014 its process restarts to apply.`)}catch(o){this._warn(`Could not set the Hermes thinking level: ${o.message}`)}};this.isTurnRunning?this._pendingEffortApply=s:s()}i&&i!==this._resumeId&&(this._resumeId=i,this.activeSessionId=i,this.metadata.sessionId=i,this.rpc&&this._recycle(),this._warn("Hermes conversation switched \u2014 its process restarts to apply.")),this._emitInit()}_recycle(){this.rpc?.close(),this.rpc=null,this._stopping=this.proc.stop().catch(()=>{})}_emitInit(){let e={...this.metadata};this._catalogEmitted?delete e.modelOptions:e.modelOptions?.length&&(this._catalogEmitted=!0),this.onEvent?.("init",e)}static doctorSpec(){return{command:"hermes",args:["doctor"]}}async adopt(e=0,n=null){let r=typeof e=="object"&&e!==null?e.from??0:Number(e)||0,i=typeof e=="object"&&e!==null?e.epoch??null:n??null,s=await this.proc.attach(r,i);return s.alive&&(this._spawnedYolo=this.desiredMode==="dont_ask",this.rpc=new Qo(this.proc,{onMessage:o=>this.handleFrame(o)}),this.rpc.on("session/request_permission",(o,a)=>this._onPermission(o,a)),this.rpc.onExit(o=>this._handleExit(o)),this.isTurnRunning=this._midTurn(s.lines)),s}_midTurn(e=[]){for(let n=e.length-1;n>=0;n--){let r;try{r=JSON.parse(Ru(e[n]))}catch{continue}if(r?.result?.stopReason!=null)return!1;if(r?.method==="session/update")return!0}return!1}sendPrompt(e,n=null){if(this.isTurnRunning)throw new Error("Hermes turn is already running.");let r=n?.length?n.map(bs):null,i=[{type:"text",text:gp(e,r)}];this.isTurnRunning=!0,Promise.resolve().then(()=>this._ensureStarted()).then(()=>this.rpc.request("session/prompt",{sessionId:this.activeSessionId,prompt:i},{timeoutMs:gae})).then(s=>this._finishTurn(s)).catch(s=>{this.isTurnRunning=!1,this.onEvent?.("error",{message:s.message})})}_slash(e){Promise.resolve().then(()=>this._ensureStarted()).then(()=>this.rpc.request("session/prompt",{sessionId:this.activeSessionId,prompt:[{type:"text",text:e}]},{timeoutMs:gae})).then(n=>this._finishTurn(n)).catch(n=>this._warn(`Hermes /command failed: ${n.message}`))}feed(e){let n=null;try{n=JSON.parse(String(e))}catch{return}if(n?.result?.stopReason!=null)return this._finishTurn(n.result);if(n?.method==="session/request_permission"&&n.id!=null)return this._onPermission(n.params||{},n.id);this.handleFrame(n)}interrupt(){return this.rpc?(this.isTurnRunning=!1,this.rpc.notify("session/cancel",{sessionId:this.activeSessionId}),!0):!1}signal(e="SIGINT"){if(this.rpc)return this.interrupt();if(typeof this.proc?.signal!="function")return!1;try{return this.proc.signal(e),!0}catch{return!1}}stop(){this.isTurnRunning=!1,this._titleTimer&&(clearTimeout(this._titleTimer),this._titleTimer=null),this.rpc?.close(),this.rpc=null;let e=this._stopping||this.proc.stop().catch(()=>{});return this._stopping=e,e}_onPermission(e,n){let r=e?.toolCall||{},i=r.rawInput||{},s=i.arguments||(i.command?{command:i.command}:{}),o=i.tool||(i.command?"terminal":vae(r.title));this.isTurnRunning=!0,this.pendingRequests.set(n,{options:Array.isArray(e?.options)?e.options:[]}),this.onEvent?.("permission_request",{requestId:n,tool:o,input:s,type:"permission"})}resolvePermission(e,n){let r=this.pendingRequests.get(e);if(this.pendingRequests.delete(e),!r)return!1;let i=o=>r.options.some(a=>a?.optionId===o),s;return n==="allow"?s="allow_once":n==="allowAlways"?s=i("allow_always")?"allow_always":"allow_session":s=i("deny")?"deny":"deny_always",this.rpc?.respond(e,{outcome:{outcome:"selected",optionId:s}}),!0}resolveQuestion(){return!1}handleFrame(e){if(!(!e||typeof e!="object")){if(e.method==="session/update")return this._onUpdate(e.params?.update||{});if(e.result?.stopReason!=null)return this._finishTurn(e.result)}}_onUpdate(e){switch(e.sessionUpdate){case"agent_message_chunk":{let n=e.content?.text||"";if(!n)return;this.isTurnRunning=!0,this.onEvent?.("delta",{text:n});return}case"agent_thought_chunk":{let n=e.content?.text||"";if(!n)return;this.isTurnRunning=!0,this.onEvent?.("thinking",{text:n});return}case"user_message_chunk":return;case"tool_call":{let n=e.toolCallId||`hermes-${this._toolSeq++}`,r=e.rawInput||{},i=r.tool||vae(e.title);if(this.toolCalls.set(n,{name:i,kind:e.kind||"",input:r.arguments||r}),this.isTurnRunning=!0,this.onEvent?.("tool_start",{id:n,name:i,input:r.arguments||r,status:"running",title:e.title}),e.kind==="edit"){let s=_ae(e.content,i);s&&this.onEvent?.("diff",s)}return}case"tool_call_update":return this._onToolUpdate(e);case"plan":return this._onPlan(e);case"usage_update":{e.used&&(this.stats.contextTokens=e.used),e.size&&(this.stats.contextWindow=e.size),this.onEvent?.("stats",{stats:this.stats});return}case"available_commands_update":{let n=(Array.isArray(e.availableCommands)?e.availableCommands:[]).map(r=>({name:String(r.name||""),description:String(r.description||r.input?.hint||"")})).filter(r=>r.name);n.length&&(this.metadata.commands=n,this._emitInit());return}case"current_mode_update":e.currentModeId&&e.currentModeId!==this.metadata.permissionMode&&(this.metadata.permissionMode=e.currentModeId,this._emitInit());return;default:this.onEvent?.("cli_event",{type:e.sessionUpdate||"",subtype:"",record:e})}}_onToolUpdate(e){let n=this.toolCalls.get(e.toolCallId);if(n){if(e.status==="failed"){this.toolCalls.delete(e.toolCallId);let r=yae(e.content)||"Tool failed.";this.onEvent?.("tool_result",{id:e.toolCallId,name:n.name,error:r,status:"error"});return}if(e.status==="completed"&&(this.toolCalls.delete(e.toolCallId),this.onEvent?.("tool_result",{id:e.toolCallId,name:n.name,output:yae(e.content)||String(e.rawOutput||""),status:"done"}),n.kind==="edit")){let r=_ae(e.content,n.name);r&&this.onEvent?.("diff",r)}}}_onPlan(e){let n=(Array.isArray(e.entries)?e.entries:[]).map(i=>({content:String(i?.content||"").trim(),status:i?.status||"pending"})).filter(i=>i.content);if(!n.length)return;let r=`hermes-plan-${this._planSeq++}`;this.onEvent?.("tool_start",{id:r,name:"todo_list",input:{todos:n},status:"running"}),this.onEvent?.("tool_result",{id:r,name:"todo_list",output:"",status:"done"})}_finishTurn(e){this.isTurnRunning=!1,this.pendingRequests.clear();let n=e?.usage||{};this.stats.inputTokens=n.inputTokens??n.input_tokens??n.prompt_tokens??0,this.stats.outputTokens=n.outputTokens??n.output_tokens??n.completion_tokens??0,this.stats.cachedTokens=n.cachedReadTokens??n.cached_read_tokens??0,this.stats.reasoningTokens=n.thoughtTokens??n.thought_tokens??n.reasoning_tokens??0,this.stats.totalTurns+=1;let r=this._pendingEffortApply;this._pendingEffortApply=null,r&&r(),this._scheduleTitleRefresh();let i=String(e?.stopReason||"end_turn"),s=i!=="end_turn"&&i!=="cancelled";this.onEvent?.("turn_complete",{stats:this.stats,result:s?`The turn stopped early (${i}).`:"",isError:s,subtype:i})}_scheduleTitleRefresh(){this._titleTimer||this._titledSession===this.activeSessionId||(this._titleTimer=setTimeout(()=>{this._titleTimer=null,this._refreshTitle()},K4e))}_refreshTitle(){if(!this.activeSessionId||this._titledSession===this.activeSessionId)return;let e=wse(this.activeSessionId);this._titledSession=this.activeSessionId,!(!e||e===this.metadata.threadName)&&(this.metadata.threadName=e.slice(0,80),this._emitInit())}renameThread(e){let n=xse(this.activeSessionId,e);return n&&(this._titledSession=this.activeSessionId,this.metadata.threadName=e.slice(0,80),this._emitInit()),n}}});var Lh,oR,X4e,mq,gq,xae,Eae=ne(()=>{U0();qoe();Joe();$B();uq();Zoe();tae();wae();Lh=(t,e)=>(n,r)=>{!n[t]&&r[e]&&(n[t]=r[e])},oR=Object.freeze({claude:{Adapter:N0,managed:!0,build:t=>{let e=new N0(t);return t.model&&(e.metadata.model=t.model),t.effort&&(e.effort=t.effort),t.sessionId&&(e.metadata.sessionId=t.sessionId),e.currentMode=t.mode,e},bindResume:(t,e)=>{!t.metadata.sessionId&&e.cliSessionId&&(t.metadata.sessionId=e.cliSessionId)}},codex:{Adapter:G0,managed:!0,build:t=>new G0(t),seed:(t,e)=>{(e.permissionMode||e.options.model||e.options.effort||e.effort||e.options.sandbox||e.options.flags)&&t.setOptions({...e.options,effort:e.effort||e.options.effort,mode:e.permissionMode||e.options.mode})},bindResume:Lh("activeThreadId","threadId")},opencode:{Adapter:W0,managed:!0,build:t=>new W0(t),seed:(t,e)=>{(e.permissionMode||e.options.model||e.options.variant||e.options.flags)&&t.setOptions({...e.options,mode:e.permissionMode||e.options.mode})},bindResume:Lh("activeSessionId","cliSessionId")},antigravity:{Adapter:$0,managed:!0,build:t=>new $0(t),seed:(t,e)=>{(e.permissionMode||e.options.model||e.options.flags||e.effort)&&t.setOptions({...e.options,effort:e.effort||e.options.effort,mode:e.permissionMode||e.options.mode})},bindResume:Lh("activeConversationId","cliSessionId")},omp:{Adapter:Nh,managed:!0,build:t=>new Nh(t),seed:(t,e)=>{(e.permissionMode||e.options.model||e.effort)&&t.setOptions({...e.options,effort:e.effort||e.options.effort,mode:e.permissionMode||e.options.mode})},bindResume:Lh("_resumeId","cliSessionId")},pi:{Adapter:V0,managed:!0,build:t=>new V0(t),seed:(t,e)=>{(e.permissionMode||e.options.model||e.effort)&&t.setOptions({...e.options,effort:e.effort||e.options.effort,mode:e.permissionMode||e.options.mode})},bindResume:Lh("_resumeId","cliSessionId")},devin:{Adapter:K0,managed:!0,build:t=>new K0(t),seed:(t,e)=>{(e.model||e.options.model)&&t.setOptions({model:e.model||e.options.model})},bindResume:Lh("_resumeId","cliSessionId")},hermes:{Adapter:J0,managed:!0,build:t=>new J0(t),seed:(t,e)=>{(e.permissionMode||e.model||e.effort)&&t.setOptions({mode:e.permissionMode||e.options.mode,model:e.model||e.options.model,effort:e.effort||e.options.effort})},bindResume:Lh("_resumeId","cliSessionId")}}),X4e=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),mq=t=>t!=null&&X4e(oR,t)?oR[t]:null,gq=t=>!!oR[t]?.managed,xae=t=>oR[t]?.Adapter?.doctorSpec?.()||null});function Q0(t){return JSON.stringify(t)?.length??0}function yq(t){let e=0;for(let n of t)e+=Q0(n)+1;return e+2}function vq(t,e,n){let r=e;for(;r>0&&Q0(t[r-1])>n;)r--;let i=0;for(;r>0;){let s=Q0(t[r-1]);if(i+s>n)break;i+=s,r--}return r}function Sae(t,e,n,r){let i=Z4e(t,e);if(i!==e&&yq(t.slice(i,n))<=r)return i;let s=e;for(;s<n&&t[s].event!=="user_message";)s++;return s<n?s:e}function Tae(t,e,n,r){if(e===0)return e;let i=new Map;for(let o=0;o<n;o++){let a=t[o];a.event==="tool_start"&&a.data?.id&&i.set(a.data.id,o)}let s=e;for(let o=e;o<n;o++){let a=t[o];if(a.event!=="tool_result"||!a.data?.id)continue;let c=i.get(a.data.id);c!=null&&c<s&&(s=c)}return s===e?e:yq(t.slice(s,n))<=Math.max(r,Pse)?s:e}function bae(t,e,n){let r=new Set;for(let s=e;s<n;s++){let o=t[s];o.event==="tool_start"&&o.data?.id&&r.add(o.data.id)}let i=s=>_q(s)?r.has(s.data?.parentToolUseId):s.event==="tool_result"&&s.data?.id?r.has(s.data.id):Aae(s);for(let s=e;s<n;s++)if(i(t[s]))return e;for(let s=e-1;s>=0;s--)if(t[s].event==="user_message")return s;return e}function J4e(t,e){let n=vq(t,t.length,e);if(n===0)return bae(t,0,t.length);let r=Sae(t,n,t.length,e),i=Tae(t,r,t.length,e);return bae(t,i,t.length)}function Cae(t){let e=new Set;for(let n of t)n.event==="tool_start"&&n.data?.id&&e.add(n.data.id);return t.filter(n=>_q(n)?e.has(n.data?.parentToolUseId):n.event==="tool_result"&&n.data?.id?e.has(n.data.id):!0)}function Rae(t,e,n,r){let i=n;for(;i>e&&Q0(t[i-1])>r;)i--;return t.slice(e,i)}function aR(t,e){let n=J4e(t,e),r=t.slice(n),i=Cae(Iae(r,e)),s=i.some(Aae)?i:Q4e(r,e),o=n>0||s.length<t.length;return{events:s,hasMore:o,fromSeq:s[0]?.seq??0}}function Q4e(t,e){let n=t.filter(o=>!_q(o)),r=Cae(Iae(n,e)),i=t.find(o=>o.event==="user_message");if(!i||r.includes(i))return r;let s=[i,...r];return yq(s)<=e?s:r}function Iae(t,e){return Rae(t,vq(t,t.length,e),t.length,e)}function kae(t,e,n){if(!e)return{events:[],hasMore:!1};let r=t.findIndex(c=>c.seq>=e),i=r===-1?t.length:r,s=vq(t,i,n),o=Sae(t,s,i,n),a=Tae(t,o,i,n);return{events:Rae(t,a,i,n),hasMore:a>0}}function Pae(t,e,n){let r=t.findIndex(o=>(o.seq??0)>e);if(r===-1)return{events:[],hasMore:!1};let i=r,s=0;for(;i<t.length;){let o=Q0(t[i])+1;if(s+o>n)break;s+=o,i++}return{events:t.slice(r,i),hasMore:i<t.length}}function Z4e(t,e){let n=e;for(;n>0&&t[n].event!=="user_message";)n--;return t[n]?.event==="user_message"?n:e}var _q,Aae,cR=ne(()=>{Jo();_q=t=>t.event==="tool_child"||t.event==="tool_result_child",Aae=t=>t.event==="user_message"||t.event==="delta"||t.event==="thinking"||t.event==="tool_start"||t.event==="tool_result"||t.event==="diff"});var Z0,eWe,Mae,Fh,wq=ne(()=>{Z0=Object.freeze({user_message:"working",tool_start:"working",permission_resolved:"working",permission_request:"blocked",blocked:"blocked",turn_complete:"done",sleep:"sleep",stopped:"idle",stall:"idle",error:"idle",exit:"idle"}),eWe=new Set(["user_message","tool_start"]),Mae=(t,e,n)=>e==="blocked"&&!!n&&eWe.has(t),Fh=new Set(Object.keys(Z0).filter(t=>Z0[t]==="done"||Z0[t]==="idle"))});async function Aq(t,e,n=!1){if(n)return{ok:!0,output:"Mock doctor: environment OK.",version:"mock"};let r=xae(t);return r?.command?new Promise(i=>{let s=(0,Fae.default)(r.command,r.args||[],{cwd:e,env:xr()}),o="",a="",c=setTimeout(()=>{try{s.kill("SIGKILL")}catch{}i({ok:!1,error:`${r.command} doctor timed out.`})},Lse);s.stdout?.on("data",l=>{o+=l.toString()}),s.stderr?.on("data",l=>{a+=l.toString()}),s.on("error",l=>{clearTimeout(c),i({ok:!1,error:l.message})}),s.on("close",l=>{clearTimeout(c);let u=rWe(o||a);if(l!==0&&!u)return i({ok:!1,error:`${r.command} doctor exited with code ${l}`});i({ok:!0,output:u,version:""})})}):{ok:!1,error:`No doctor command for engine: ${t}`}}function Bh(t,e){let n=String(t).replace(/[^a-zA-Z0-9_-]/g,"_");return Lae.default.join(Sq,`${e}-${n}.json`)}function iWe(t,e){try{let n=Uh.default.readFileSync(Bh(t,e),"utf8"),r=JSON.parse(n);return!r||r.engine!==e?null:r}catch{return null}}function Tq(t){if(typeof t=="string")return t.length>Uy?`${t.slice(0,Uy)}
223
- \u2026 [truncated]`:t;if(Array.isArray(t)){let e=!1,n=t.map(r=>{let i=Tq(r);return i!==r&&(e=!0),i});return e?n:t}if(t&&typeof t=="object"){let e=!1,n={};for(let r of Object.keys(t)){let i=Tq(t[r]);i!==t[r]&&(e=!0),n[r]=i}return e?n:t}return t}function lWe(t){if(!t?.attachment||t.rendered===void 0&&t.attachment.snippet===void 0)return t;let{rendered:e,attachment:n,...r}=t;if(n.snippet===void 0)return{...r,attachment:n};let{snippet:i,...s}=n;return{...r,attachment:s}}function Uae(t,e){if(!e||t==="init"||t==="options_changed"||t==="stats")return e;if(t==="cli_event"&&e.type==="attachment"){let n=lWe(e.record);return n===e.record?e:{...e,record:n}}return Tq(e)}function xq(t){return(t||[]).map((e,n)=>{if(e.seq===n+1)return e;let r={...e,seq:n+1};return r._fromSeq!=null&&(r._fromSeq=0),r})}function Nae(t){return(t||[]).map(e=>{let n=Uae(e.event,e.data);return n===e.data?e:{...e,data:n}})}function bq(t,e){return t.length?hWe(e,t):e}function pWe(t,e){let n=new Set;for(let i=e.length-1;i>=0;i--){let s=e[i];if(Fh.has(s.event))break;s.event==="user_message"&&n.add(s.data?.text)}let r=[];for(let i=t.length-1;i>=0;i--){let s=t[i];if(Fh.has(s.event))break;s.event==="user_message"&&!n.has(s.data?.text)&&r.unshift(s)}return r}function fWe(t){if(!Array.isArray(t)||t.length<=1)return t;let e=[];for(let n of t){let r=e[e.length-1];r&&r.event===n.event&&(n.event==="delta"||n.event==="thinking")?(r.data={text:qae(r.data?.text,n.data?.text)},n.seq&&(r.seq!=null&&r._fromSeq==null&&(r._fromSeq=r.seq),r.seq=n.seq)):e.push({...n})}return e}function hWe(t,e){let n=[],r=0,i=o=>{let a=0;for(let c=0;c<o;c++)s.has(c)||a++;return a},s=new Set(e.map(({i:o})=>o));for(let{e:o,i:a}of e){let c=Math.min(i(a),t.length);for(;r<c;)n.push(t[r++]);n.push(o)}for(;r<t.length;)n.push(t[r++]);return n}var Uh,Lae,Fae,tWe,ex,nWe,rWe,Sq,sWe,oWe,aWe,Oae,cWe,uWe,dWe,uR,Bae,Eq,qae,Dae,mWe,lR,Cq=ne(()=>{Uh=Q(require("node:fs"),1),Lae=Q(require("node:path"),1),Fae=Q(DC(),1);Jo();nc();jC();$C();koe();Eae();Iu();cR();Jo();ri();j0();Cu();xs();wq();sR();qt();$e();tWe=Ee("ai"),ex=t=>t===null||typeof t!="object"?JSON.stringify(t)??"null":Array.isArray(t)?`[${t.map(ex).join(",")}]`:`{${Object.keys(t).sort().map(e=>`${JSON.stringify(e)}:${ex(t[e])}`).join(",")}}`,nWe=/\[[0-9;]*m/g,rWe=t=>String(t||"").replace(nWe,"");Sq=Pe.AI_SESSIONS;try{Uh.default.existsSync(Sq)||Uh.default.mkdirSync(Sq,{recursive:!0})}catch{}sWe={tool_start:"tool_child",tool_result:"tool_result_child"},oWe=new Set(["thinking_tokens","tool_progress","hook_started","hook_progress","hook_response","status","control_response","api_retry"]),aWe=new Set(["prompt_suggestion","rate_limit_event","hook/started","hook/completed","rawResponseItem/completed","rawResponse/completed","mcpServer/startupStatus/updated","mcpServer/event/stream/notification","mcpServer/oauthLogin/completed","account/rateLimits/updated","remoteControl/status/changed","thread/status/changed","model/safetyBuffering/updated","turn/moderationMetadata","fs/changed","process/outputDelta","process/exited"]),Oae=/^[A-Za-z0-9_][A-Za-z0-9_-]{0,127}$/,cWe=new Set(["codex default","opencode default"]);uWe="deny",dWe="User skipped this request";uR=new Set(["task_started","task_updated","task_notification","background_tasks_changed"]),Bae=t=>t.event==="cli_event"&&uR.has(t.data?.subtype),Eq=t=>(t||[]).map((e,n)=>({e,i:n})).filter(({e})=>Bae(e));qae=(t,e)=>{let n=t||"";if(n.length>=Uy)return n;let r=n+(e||"");return r.length>Uy?`${r.slice(0,Uy)}
223
+ \u2026 [truncated]`:t;if(Array.isArray(t)){let e=!1,n=t.map(r=>{let i=Tq(r);return i!==r&&(e=!0),i});return e?n:t}if(t&&typeof t=="object"){let e=!1,n={};for(let r of Object.keys(t)){let i=Tq(t[r]);i!==t[r]&&(e=!0),n[r]=i}return e?n:t}return t}function lWe(t){if(!t?.attachment)return t;let e=t.attachment;if(e.type==="hook_success"&&e.hookEvent!=="SessionStart"){let{command:a,stdout:c,stderr:l,content:u,...d}=e;t={...t,attachment:d}}if(t.rendered===void 0&&t.attachment.snippet===void 0)return t;let{rendered:n,attachment:r,...i}=t;if(r.snippet===void 0)return{...i,attachment:r};let{snippet:s,...o}=r;return{...i,attachment:o}}function Uae(t,e){if(!e||t==="init"||t==="options_changed"||t==="stats")return e;if(t==="cli_event"&&e.type==="attachment"){let n=lWe(e.record);return n===e.record?e:{...e,record:n}}return Tq(e)}function xq(t){return(t||[]).map((e,n)=>{if(e.seq===n+1)return e;let r={...e,seq:n+1};return r._fromSeq!=null&&(r._fromSeq=0),r})}function Nae(t){return(t||[]).map(e=>{let n=Uae(e.event,e.data);return n===e.data?e:{...e,data:n}})}function bq(t,e){return t.length?hWe(e,t):e}function pWe(t,e){let n=new Set;for(let i=e.length-1;i>=0;i--){let s=e[i];if(Fh.has(s.event))break;s.event==="user_message"&&n.add(s.data?.text)}let r=[];for(let i=t.length-1;i>=0;i--){let s=t[i];if(Fh.has(s.event))break;s.event==="user_message"&&!n.has(s.data?.text)&&r.unshift(s)}return r}function fWe(t){if(!Array.isArray(t)||t.length<=1)return t;let e=[];for(let n of t){let r=e[e.length-1];r&&r.event===n.event&&(n.event==="delta"||n.event==="thinking")?(r.data={text:qae(r.data?.text,n.data?.text)},n.seq&&(r.seq!=null&&r._fromSeq==null&&(r._fromSeq=r.seq),r.seq=n.seq)):e.push({...n})}return e}function hWe(t,e){let n=[],r=0,i=o=>{let a=0;for(let c=0;c<o;c++)s.has(c)||a++;return a},s=new Set(e.map(({i:o})=>o));for(let{e:o,i:a}of e){let c=Math.min(i(a),t.length);for(;r<c;)n.push(t[r++]);n.push(o)}for(;r<t.length;)n.push(t[r++]);return n}var Uh,Lae,Fae,tWe,ex,nWe,rWe,Sq,sWe,oWe,aWe,Oae,cWe,uWe,dWe,uR,Bae,Eq,qae,Dae,mWe,lR,Cq=ne(()=>{Uh=Q(require("node:fs"),1),Lae=Q(require("node:path"),1),Fae=Q(DC(),1);Jo();nc();jC();$C();koe();Eae();Iu();cR();Jo();ri();j0();Cu();xs();wq();sR();qt();$e();tWe=Ee("ai"),ex=t=>t===null||typeof t!="object"?JSON.stringify(t)??"null":Array.isArray(t)?`[${t.map(ex).join(",")}]`:`{${Object.keys(t).sort().map(e=>`${JSON.stringify(e)}:${ex(t[e])}`).join(",")}}`,nWe=/\[[0-9;]*m/g,rWe=t=>String(t||"").replace(nWe,"");Sq=Pe.AI_SESSIONS;try{Uh.default.existsSync(Sq)||Uh.default.mkdirSync(Sq,{recursive:!0})}catch{}sWe={tool_start:"tool_child",tool_result:"tool_result_child"},oWe=new Set(["thinking_tokens","tool_progress","hook_started","hook_progress","hook_response","status","control_response","api_retry"]),aWe=new Set(["prompt_suggestion","rate_limit_event","hook/started","hook/completed","rawResponseItem/completed","rawResponse/completed","mcpServer/startupStatus/updated","mcpServer/event/stream/notification","mcpServer/oauthLogin/completed","account/rateLimits/updated","remoteControl/status/changed","thread/status/changed","model/safetyBuffering/updated","turn/moderationMetadata","fs/changed","process/outputDelta","process/exited"]),Oae=/^[A-Za-z0-9_][A-Za-z0-9_-]{0,127}$/,cWe=new Set(["codex default","opencode default"]);uWe="deny",dWe="User skipped this request";uR=new Set(["task_started","task_updated","task_notification","background_tasks_changed"]),Bae=t=>t.event==="cli_event"&&uR.has(t.data?.subtype),Eq=t=>(t||[]).map((e,n)=>({e,i:n})).filter(({e})=>Bae(e));qae=(t,e)=>{let n=t||"";if(n.length>=Uy)return n;let r=n+(e||"");return r.length>Uy?`${r.slice(0,Uy)}
224
224
  \u2026 [truncated]`:r};Dae=t=>`ai:${t}`,mWe=0,lR=class{constructor({id:e,engine:n,cwd:r,options:i={},onEvent:s}){this.id=e,this.engine=n,this.cwd=r||process.cwd(),this.options=i,this.onEvent=s,this.createdAt=Date.now(),this.isTurnRunning=!1,this.promptQueue=[],this._drainTimer=null,this._ensureAlive=null,this.asyncTimers=new Map,this.turnStartedAt=0,this.lastTurnMs=0,this.lastPrompt="",this.adapter=null,this.goalReading=null,this.goalKey=null;let o=iWe(e,n);this.options={...o?.options||{},...i},this.attachmentOffset=o?.attachmentOffset??null,this.proc=gq(n)?new rc({procId:e}):null,this.consumedLines=o?.consumedLines||0,this.consumedEpoch=o?.consumedEpoch??null,this.ready=null;let a=typeof i.cliSessionId=="string"&&Oae.test(i.cliSessionId)?i.cliSessionId:null,c=o?.threadId||o?.cliSessionId||a||i.threadId||i.sessionId||null;this.threadId=n===kt.CODEX?c:null,this.cliSessionId=n===kt.CODEX?null:c,this.history=[];let l=null;if(c){let u=this._rebuildFromStore(c);l=u.state,u.events&&(this.history=bq(Eq(this.history),u.events))}if(this._settleRestoredAsync(),this.seqCounter=this.history.at(-1)?.seq||0,this.logEpoch=Math.floor(Date.now()/1e3),this.persisting=!1,this.persistAgain=!1,this.persistTimer=null,this.model=o?.model||i.model||i.defaultModel||"",this.effort=o?.effort||i.effort||i.defaultEffort||(this.engine===kt.CODEX?"xhigh":""),this.permissionMode=o?.permissionMode||i.mode||i.defaultMode||null,this.asleep=!!o?.asleep,this.lastActivityAt=Date.now(),this.engine===kt.CLAUDE&&l){let u=l;u.permissionMode&&(this.permissionMode=u.permissionMode),u.lastPrompt&&(this.lastPrompt=u.lastPrompt),u.cwd&&(this.harnessCwd=u.cwd),u.isWorktree&&(this.isWorktree=!0),u.title&&(this.harnessTitle=u.title)}this.skills=[],i.mock||(this.engine===kt.OPENCODE&&rq(),this._kvPromise=this._restoreFromDaemonKv().catch(()=>{}),this.ready=this.initAdapter().then(async u=>(await this._applyKvToAdapter(),u)))}_saveKvState(e=this.isTurnRunning){gn()&&vu(Dae(this.id),{engine:this.engine,stats:this.adapter?.stats||null,turn:{running:e,startedAt:this.turnStartedAt||null,lastTurnMs:this.lastTurnMs||0},lastPrompt:this.lastPrompt||"",threadTitle:this.threadTitle||"",carried:Eq(this.history),permissionMode:this.permissionMode||null,model:this.model||"",effort:this.effort||"",cwd:this.cwd,cliSessionId:this.cliSessionId||null,threadId:this.threadId||null,asleep:this.asleep||!1,options:this.options||{},consumedLines:this.consumedLines||0,consumedEpoch:this.consumedEpoch??null,pendingPermission:this.pendingPermission?.()||null}).catch(()=>{})}async _restoreFromDaemonKv(){if(gn())try{let e=await _u(Dae(this.id));if(!e)return;if(e.lastPrompt&&!this.lastPrompt&&(this.lastPrompt=e.lastPrompt),e.threadTitle&&!this.threadTitle&&(this.threadTitle=e.threadTitle),e.permissionMode&&this.permissionMode===(this.options.defaultMode||"default")&&(this.permissionMode=e.permissionMode,this._kvModeFilled=!0),e.model&&!this.model&&(this.model=e.model),e.effort&&!this.effort&&(this.effort=e.effort),e.cwd&&!this.cwd&&(this.cwd=e.cwd),e.cliSessionId&&!this.cliSessionId&&(this.cliSessionId=e.cliSessionId),e.threadId&&!this.threadId&&(this.threadId=e.threadId),e.asleep&&(this.asleep=!0),e.options&&(this.options={...e.options,...this.options}),Array.isArray(e.carried)&&e.carried.length){let n=new Set(this.history.map(i=>i.data?.record?.task_id||i.data?.id).filter(Boolean)),r=e.carried.map((i,s)=>i?.e?i:{e:i,i:s}).filter(({e:i})=>{let s=i?.data?.record?.task_id||i?.data?.id;return!s||!n.has(s)});r.length&&(this.history=xq(bq(r,this.history)),this.seqCounter=this.history.length,this.logEpoch++)}this._kvSaved=e}catch{}}async _applyKvToAdapter(){let e=this._kvSaved;if(!(!e||this.destroyed||!this.adapter))try{if(e.stats&&this.adapter.stats)for(let[n,r]of Object.entries(e.stats))typeof r=="number"&&!this.adapter.stats[n]&&(this.adapter.stats[n]=r);if(this._kvModeFilled)if(this.adapter.currentMode==="default"&&(this.adapter.currentMode=e.permissionMode),this.adapter.permissionMode==="default")this.adapter.permissionMode=e.permissionMode;else{let n=this.adapter.setOptions?.({mode:e.permissionMode});n?.then&&n.then(r=>this._replay(r))}if(e.model&&this.adapter.metadata&&!this.adapter.metadata.model&&(this.adapter.metadata.model=e.model),e.effort&&!this.adapter.effort&&(this.adapter.effort=e.effort),e.turn?.running){let n=!1;if(this.engine===kt.OPENCODE)try{n=(await this.adapter?.server?.activeSessions?.())?.[this.cliSessionId]?.type!=="idle"}catch{}else{let r=await RA();n=((Array.isArray(r)?r:r?.procs)||[]).some(s=>(s.procId===this.id||s.id===this.id)&&s.alive!==!1)}if(n){this.isTurnRunning=!0,this.asleep=!1,this.turnStartedAt=e.turn.startedAt||Date.now();let r=e.pendingPermission;r?.requestId!=null&&this.adapter?.pendingRequests&&!this.adapter.pendingRequests.size&&this.adapter.pendingRequests.set(r.requestId,{toolName:r.tool||"",input:r.input||{}})}}}catch{}}initAdapter(){let e=null,n=(o,a)=>{this.adapter===e&&this.emitNormalized(o,a)},r=this.permissionMode||this.options.mode||"default",i=mq(this.engine);if(!i)throw new Error(`Unsupported engine: ${this.engine}`);let s={cwd:this.cwd,onEvent:n,proc:this.managed?this.proc:null,hostSessionId:this.id,sessionId:this.cliSessionId,threadId:this.threadId,conversationId:this.cliSessionId,model:this.model||this.options.model,effort:this.effort,mode:r,options:this.options,transport:this.options.transport||null};return e=i.build(s),this.adapter=e,i.seed?.(e,this),this._startManaged(e,r)}get managed(){return gq(this.engine)&&gn()}async _startManaged(e,n){if(await this._kvPromise?.catch(()=>{}),mq(this.engine)?.bindResume?.(e,this),this.engine===kt.CLAUDE&&this.permissionMode&&this.permissionMode!==n&&(n=e.currentMode=this.permissionMode),this.managed){let i=await e.adopt(this.consumedLines,this.consumedEpoch);if(i.alive||i.lines?.length)return this.adopted=!0,e.isTurnRunning&&(this.isTurnRunning=!0),this._replay(i),i}if(this.adopted=!1,this.consumedLines=0,this.consumedEpoch=null,!e.persistent&&this.engine!==kt.CLAUDE||this.asleep)return null;let r=await e.start(n,this.cliSessionId||this.threadId);return this._replay(r),r}_replay(e){e&&(this.lastMissed=e.missed||0,e.missed>0&&this._fillGap(e.missed),e.commit?.(n=>this.adapter.feed(n)),this.consumedLines=this.proc?.lineNo||0,this.consumedEpoch=this.proc?.epoch??null)}_rebuildFromStore(e,n=null){let r=Coe(this.engine,this.cwd,e,n);return r?{events:r.events?.length?xq(Nae(r.events)):null,state:r.state||null}:{events:null,state:null}}refreshFromStore(){if(!this.cliSessionId)return!1;let{events:e}=this._rebuildFromStore(this.cliSessionId);if(!e||e.length<=this.history.length)return!1;let n=a=>ex(a?.data);if(!this.history.length){for(let a of e)this.history.push({...a,seq:++this.seqCounter,timestamp:a.timestamp||Date.now()});return this.flushSaveSnapshot(),!0}let r=this.history[this.history.length-1],i=n(r),s=-1;for(let a=e.length-1;a>=0;a--)if(e[a].event===r.event&&(e[a].data===r.data||n(e[a])===i)){s=a;break}if(s<0)return!1;let o=e.slice(s+1);for(let a of o)this.history.push({...a,seq:++this.seqCounter,timestamp:a.timestamp||Date.now()});return o.length&&this.flushSaveSnapshot(),o.length>0}reloadFromStore(e=null){if(!this.cliSessionId)return!1;let{events:n}=this._rebuildFromStore(this.cliSessionId,e);return n?(this._adoptLog(n),!0):!1}_adoptLog(e,{carryUnreleased:n=!1}={}){let r=bq(Eq(this.history),e);if(n){let c=pWe(this.history,r);c.length&&(r=[...r,...c])}let i=xq(Nae(r));if(this.history.length===i.length&&i.every((c,l)=>{let u=this.history[l];return!!u&&u.event===c.event&&(u.data===c.data||ex(u.data)===ex(c.data))}))return this.history;this.seqCounter=i.length,this.logEpoch++,this.history=i;let{events:s,hasMore:o,fromSeq:a}=aR(i,Fy);this.onEvent?.(this.id,"conversation_reset",{hasMore:o,fromSeq:a,epoch:this.logEpoch,lastTurnMs:this.lastTurnMs,taskRecords:this.taskRecords(),queue:this.getQueue(),...this.turnState()});for(let c of s)this.onEvent?.(this.id,c.event,{...c.data,replay:!0},c.seq);return this.flushSaveSnapshot(),i}_fillGap(e){this.cliSessionId&&this.refreshFromStore()||this.emitNormalized("ansi",{chunk:`\r
225
225
  [9remote] ${e} d\xF2ng output \u0111\xE3 m\u1EA5t trong l\xFAc agent kh\u1EDFi \u0111\u1ED9ng l\u1EA1i.\r
226
- `})}_runningAsync(){if(this.asyncTimers.size)return!0;let e=new Set;for(let{event:n,data:r}of this.history)n!=="tool_result"||!r?.async||!r.id||(r.status==="running"?e.add(r.id):e.delete(r.id));return e.size>0}get idleKillEligible(){if(!(!this.destroyed&&!this.asleep&&Fse.has(this.engine)&&!!this.adapter&&!this.proc?.dead&&!this.promptQueue?.length&&!this._runningAsync()))return!1;let n=Date.now()-this.lastActivityAt;return n>=$se?!0:!this.isTurnRunning&&!this.pendingPermission()&&n>=Use}async idleKill(){return this.idleKillEligible?(this.asleep=!0,this.emitNormalized("sleep",{}),await this.adapter?.stop(),this._saveKvState(!1),this.flushSaveSnapshot(),!0):!1}turnState(){return{isTurnRunning:this.isTurnRunning,elapsedMs:this.isTurnRunning&&this.turnStartedAt?Date.now()-this.turnStartedAt:0}}taskRecords(){let e=[],n=0,r=Date.now();for(let i=this.history.length-1;i>=0;i--){let s=this.history[i];if(!Bae(s))continue;let o={...s.data,ageMs:r-(s.timestamp||r)},a=JSON.stringify(o).length;if(n+a>kse)break;n+=a,e.push(o)}return e.reverse()}emitNormalized(e,n,r=!0){if(e==="cli_reset"){this._resetConversation({conversationId:n?.conversationId||null});return}if(r&&e==="cli_event"&&oWe.has(n?.subtype)&&(r=!1),r&&e==="cli_event"&&aWe.has(n?.type)&&(r=!1),r&&e==="cli_event"&&n?.type==="attachment"){let c=n.record?.attachment||n.record;c?.type==="hook_success"&&c.hookEvent!=="SessionStart"&&(r=!1)}e==="init"&&(n?.threadId&&(this.threadId=n.threadId),n?.sessionId&&n.sessionId!==this.cliSessionId&&(this.attachmentOffset=null,this.threadTitle=""),n?.sessionId&&(this.cliSessionId=n.sessionId),n?.model&&!cWe.has(n.model)&&(this.model=n.model),n?.effort&&(this.effort=n.effort),this.engine===kt.CODEX&&n?.threadId&&this.refreshGoal(n.threadId),n?.threadName&&(this.threadTitle=String(n.threadName).trim(),this._saveKvState())),n=Uae(e,n),e==="cli_event"&&uR.has(n?.subtype)&&(n={...n,ageMs:0},this._saveKvState());let i=Date.now();this.lastActivityAt=i,e==="user_message"?(this.turnStartedAt=i,this.lastTurnMs=0,this.asleep=!1):Fh.has(e)&&(this.turnStartedAt&&(this.lastTurnMs=i-this.turnStartedAt),n={...n,turnMs:this.lastTurnMs});let s=sWe[e],o=n?.parentToolUseId&&s?{event:s,data:n}:{event:e,data:n};Fh.has(e)&&this._pullAttachments(),Fh.has(e)&&this.engine===kt.CODEX&&this.threadId&&this.refreshGoal(this.threadId);let a=r?++this.seqCounter:void 0;if(r){let c=this.history[this.history.length-1];c&&c.event===o.event&&(o.event==="delta"||o.event==="thinking")&&typeof n?.text=="string"&&typeof c.data?.text=="string"?(c.seq!=null&&c._fromSeq==null&&(c._fromSeq=c.seq),c.data={text:qae(c.data.text,n.text)},c.seq=a,c.timestamp=Date.now()):(this.history.push({seq:a,event:o.event,data:n,timestamp:Date.now()}),this.history.length>Ose&&this.history.shift())}if(vC(this.id),this.onEvent?.(this.id,o.event,n,a,this.logEpoch),r&&this.scheduleSaveSnapshot(),e==="cli_event"&&n?.subtype==="task_notification"){let c=n.record?.tool_use_id;c&&(this.clearAsyncWatchdog(c),this.emitNormalized("tool_result",{id:c,status:"done",async:!0}))}e==="tool_result"&&(n?.async&&n?.handle?this.armAsyncWatchdog(n.id,n.parentToolUseId):n?.id&&this.clearAsyncWatchdog(n.id)),Fh.has(e)&&(this.isTurnRunning=!1,this._settleForegroundTasks(),this.history=fWe(this.history),this.flushSaveSnapshot(),this.applyPendingOptions(),this._saveKvState(!1),this._drainQueue())}_drainQueue(){this.isTurnRunning||!this.promptQueue?.length||this.destroyed||(this._drainTimer&&clearTimeout(this._drainTimer),this._drainTimer=setTimeout(()=>{if(this._drainTimer=null,this.isTurnRunning||!this.promptQueue?.length||this.destroyed)return;let e=this.promptQueue.shift();this.emitQueueUpdate(),this.sendPrompt(e.text,e.attachments)},50))}getQueue(){return Array.isArray(this.promptQueue)?this.promptQueue.map(e=>({id:e.id,text:e.text,attachments:(e.attachments||[]).map(n=>({name:n.name||n.filename,type:n.type}))})):[]}emitQueueUpdate(){this.onEvent?.(this.id,"queue_update",{queue:this.getQueue()})}removeQueueItem(e){if(!Array.isArray(this.promptQueue))return!1;let n=this.promptQueue.length;return this.promptQueue=this.promptQueue.filter(r=>r.id!==e),this.promptQueue.length!==n?(this.emitQueueUpdate(),!0):!1}clearQueue(){this._drainTimer&&(clearTimeout(this._drainTimer),this._drainTimer=null),this.promptQueue?.length&&(this.promptQueue=[],this.emitQueueUpdate())}_pullAttachments(){if(this.engine!==kt.CLAUDE||!this.cliSessionId||this.destroyed)return;if(this.attachmentOffset==null){let n=this._seedAttachmentOffset?this._seedAttachmentOffset():DB(this.cwd,this.cliSessionId,1/0);this.attachmentOffset=n?.offset||0;return}let e=this._readAttachments?this._readAttachments():DB(this.cwd,this.cliSessionId,this.attachmentOffset);if(!e?.records?.length){e?.offset!=null&&(this.attachmentOffset=e.offset);return}this.attachmentOffset=e.offset;for(let n of e.records)this.emitNormalized("cli_event",{type:"attachment",subtype:n.attachment?.type||"",record:n})}hasRecordedInit(){return this.history.some(e=>e.event==="init")}async refreshGoal(e){if(this.engine!==kt.CODEX||this.goalReading===e)return;this.goalReading=e;let n=await Ioe(e,this.cwd).catch(()=>null);if(this.goalReading=null,this.threadId!==e)return;let r=n?`${n.objective}|${n.status}`:"";r===this.goalKey||r===this.lastRecordedGoalKey()||(this.goalKey=r,this.emitNormalized("goal",{goal:n}))}lastRecordedGoalKey(){for(let e=this.history.length-1;e>=0;e--){if(this.history[e].event!=="goal")continue;let n=this.history[e].data?.goal;return n?`${n.objective}|${n.status}`:""}return null}armAsyncWatchdog(e,n){e&&(this.clearAsyncWatchdog(e),this.asyncTimers.set(e,setTimeout(()=>{this.asyncTimers.delete(e),this.emitNormalized("tool_result",{id:e,status:"done",async:!0,...n?{parentToolUseId:n}:{}})},Cse)))}clearAsyncWatchdog(e){let n=this.asyncTimers.get(e);n&&(clearTimeout(n),this.asyncTimers.delete(e))}clearAllAsyncWatchdogs(){for(let e of this.asyncTimers.values())clearTimeout(e);this.asyncTimers.clear()}_settleForegroundTasks(e=!1){let n=new Set;for(let r of this.history||[]){if(r.event!=="cli_event")continue;let i=r.data?.subtype,s=r.data?.record?.task_id||r.data?.task_id;i==="task_notification"&&s&&n.add(s)}for(let r of this.history||[]){if(r.event!=="cli_event"||r.data?.subtype!=="task_started")continue;let i=r.data?.record||{},s=i.task_id||r.data?.task_id;!s||n.has(s)||(e||!i.is_backgrounded)&&(n.add(s),this.emitNormalized("cli_event",{type:"system",subtype:"task_notification",record:{type:"system",subtype:"task_notification",task_id:s,status:"completed"}}))}}_settleRestoredAsync(){for(let e of this.history||[])e.event!=="tool_result"||!e.data?.async||e.data.status!=="running"||(e.data={...e.data,status:"done"});this._settleForegroundTasks(!1)}scheduleSaveSnapshot(){if(this.destroyed||this.persistTimer)return;let e=this.isTurnRunning?Ise:Rse;this.persistTimer=setTimeout(()=>{this.persistTimer=null,this.saveSnapshot()},e),this.persistTimer.unref?.()}flushSaveSnapshot(){this.persistTimer&&(clearTimeout(this.persistTimer),this.persistTimer=null),this.saveSnapshot(!0)}saveSnapshot(e=!1){if(this.persisting){this.persistAgain=!0;return}this.persisting=!0;try{let n=JSON.stringify({engine:this.engine,cwd:this.cwd,threadId:this.threadId,cliSessionId:this.cliSessionId,model:this.model,effort:this.effort,permissionMode:this.permissionMode,createdAt:this.createdAt,options:this.options,asleep:this.asleep,consumedLines:this.consumedLines,consumedEpoch:this.consumedEpoch,attachmentOffset:this.attachmentOffset});if(e){Uh.default.writeFileSync(Bh(this.id,this.engine),n),this.persisting=!1,this.persistAgain&&(this.persistAgain=!1,this.saveSnapshot(!0));return}Uh.default.writeFile(Bh(this.id,this.engine),n,()=>{this.persisting=!1,this.persistAgain&&(this.persistAgain=!1,this.saveSnapshot())})}catch{this.persisting=!1}}_resetConversation({conversationId:e=null,rebuildProcess:n=!1}={}){if(this.threadId=null,this.threadTitle="",this.cliSessionId=e,this.history=[],this.seqCounter=0,this.logEpoch++,this.consumedLines=0,this.consumedEpoch=null,this.attachmentOffset=null,this.isTurnRunning=!1,this.turnStartedAt=0,this.lastTurnMs=0,this.flushSaveSnapshot(),n&&!this.options.mock&&!this.managed){try{this.adapter?.stop()}catch{}this.ready=this.initAdapter()}let r=this.metadata();this.history.push({seq:++this.seqCounter,event:"init",data:r,timestamp:Date.now()}),this.onEvent?.(this.id,"conversation_reset",{hasMore:!1,fromSeq:0,epoch:this.logEpoch,taskRecords:[],lastTurnMs:0,isTurnRunning:!1,elapsedMs:0}),this.onEvent?.(this.id,"init",r),this.clearQueue(),this.flushSaveSnapshot()}sendPrompt(e,n=null,r=null){if(String(e).trim()==="/clear"){if(this.isTurnRunning){this.emitNormalized("error",{message:"Turn is still running \u2014 stop it before /clear."});return}this._resetConversation({rebuildProcess:!0});return}if(this.isTurnRunning){this.skipOpenGates(),Array.isArray(this.promptQueue)||(this.promptQueue=[]);let i={id:`q-${Date.now()}-${++mWe}`,text:e,attachments:n,promptId:r};return this.promptQueue.push(i),this.emitQueueUpdate(),{queued:!0,item:i}}if(this.lastPrompt=e,this.options.mock){this.isTurnRunning=!0,this.skipOpenGates(),this.emitNormalized("user_message",{text:e,attachments:kB(n)}),this.emitNormalized("delta",{text:`[Mock reply to: ${e}]`}),this.emitNormalized("turn_complete",{stats:{}});return}try{this.adapter?.sendPrompt(e,n,r)}catch(i){let s=String(i?.message||i);return this.emitNormalized("prompt_refused",{text:e,promptId:r,reason:s}),this.promptQueue?.length&&this._drainQueue(),{refused:!0,error:s}}this.isTurnRunning=!0,this.turnStartedAt=Date.now(),this._saveKvState(!0),this.skipOpenGates(),this.emitNormalized("user_message",{text:e,attachments:kB(n)})}async renameConversation(e){try{await this.adapter?.renameThread?.(e)}catch{}this.threadTitle!==e&&(this.threadTitle=e,this._saveKvState())}metadata(){return{model:this.model||"",threadId:this.threadId||"",sessionId:this.cliSessionId||"",skills:this.skills||[]}}pendingPermission(){let e=this.adapter?.pendingRequests;if(!e?.size)return null;let n=[...e.keys()].at(-1),r=e.get(n);return{requestId:n,tool:r.toolName||"",input:r.input||{}}}resolvePermission(e,n,r){return this.adapter?.resolvePermission?.(e,n,r)===!1?!1:(this.emitNormalized("permission_resolved",{requestId:e,behavior:n}),!0)}resolveQuestion(e,n){return this.adapter?.resolveQuestion?.(e,n)===!1?!1:(this.emitNormalized("permission_resolved",{requestId:e,behavior:"allow"}),!0)}skipOpenGates(){let e=this.adapter?.pendingRequests;if(!e?.size)return 0;let n=0;for(let r of[...e.keys()])this.resolvePermission(r,uWe,dWe)&&n++;return n}setOptions(e){let{resume:n,...r}=e||{},i=typeof n=="string"&&Oae.test(n)?n:null;if(this.options={...this.options,...r},r?.mode&&(this.permissionMode=r.mode),r?.effort&&(this.effort=r.effort),r?.model&&(this.model=r.model),(r?.model||r?.effort)&&sae(this.engine,{model:this.model,effort:this.effort}),i&&(this.pendingResume=i,this.engine===kt.CLAUDE?this.cliSessionId=i:this.engine===kt.CODEX?this.threadId=i:this.engine===kt.OPENCODE?this.cliSessionId=i:this.engine===kt.ANTIGRAVITY?this.cliSessionId=i:this.engine===kt.DEVIN?this.cliSessionId=i:this.engine===kt.HERMES?this.cliSessionId=i:this.engine===kt.PI&&(this.cliSessionId=i),this.attachmentOffset=null,this._adoptLog(this._rebuildFromStore(i).events||[]),this.turnStartedAt=0,this.lastTurnMs=0,this.history.length||tWe.info(`[ai] rewind left an empty log: engine=${this.engine} resume=${i} cwd=${this.cwd}`)),this.isTurnRunning){this.restartPending=!0,(r?.mode||r?.effort||r?.model||i)&&(this._saveKvState(),this.flushSaveSnapshot());return}let s=this.adapter?.setOptions?.({...e,resume:i});s?.then&&s.then(o=>this._replay(o)),(r?.mode||r?.effort||r?.model||i)&&(this._saveKvState(),this.flushSaveSnapshot())}applyPendingOptions(){if(!this.restartPending)return;this.restartPending=!1;let e=this.pendingResume||null;this.pendingResume=null;let n=this.adapter?.setOptions?.({mode:this.permissionMode,model:this.model,effort:this.effort,...e?{resume:e}:{}});n?.then&&n.then(r=>this._replay(r))}async runDoctor(){return Aq(this.engine,this.cwd,this.options.mock)}stop(){let e=this.adapter?.interrupt?.(),n=e?!1:this.adapter?.signal?.("SIGINT");return!e&&!n?(this.emitNormalized("error",{message:`${this.engine} could not stop this turn \u2014 the CLI is still running.`}),!1):(this.emitNormalized("stopped",{}),!0)}stopTask(e){return!this.adapter?.stopTask?.(e)&&e&&this.emitNormalized("cli_event",{type:"system",subtype:"task_notification",record:{type:"system",subtype:"task_notification",task_id:String(e),status:"stopped"}}),!0}async ensureProcAlive(){if(!(!this.managed||!this.proc||this.adapter?.proc!==this.proc)&&!(this.destroyed||this.options.mock)){if(this._ensureAlive)return this._ensureAlive;this._ensureAlive=(async()=>{let e=!0;try{e=(await RA()).some(n=>n.procId===this.id&&n.alive!==!1)}catch{return}e||await this.restart()})();try{await this._ensureAlive}finally{this._ensureAlive=null}}}async restart(){this.clearAllAsyncWatchdogs(),this.isTurnRunning=!1,this.turnStartedAt=0,this.lastTurnMs=0,this.skipOpenGates();let e=this.adapter;if(this.adapter=null,e)try{await Promise.resolve(e.stop?.())}catch{}return this.managed&&(this.proc=new rc({procId:this.id})),this.ready=this.initAdapter().then(async n=>(await this._applyKvToAdapter(),n)),await this.ready,this.refreshFromStore(),this.emitNormalized("stopped",{}),this._saveKvState(!1),this.flushSaveSnapshot(),!0}destroy(){this.clearAllAsyncWatchdogs(),this._drainTimer&&(clearTimeout(this._drainTimer),this._drainTimer=null),this.promptQueue=[],this.persistTimer&&(clearTimeout(this.persistTimer),this.persistTimer=null);let e=this.options.mock||typeof this.adapter?.stop!="function"?Promise.resolve():this.adapter.stop();if(this.destroyed=!0,this.emitNormalized("stopped",{}),this.engine===kt.OPENCODE&&!this.options.mock){let i=()=>iq();e?.then?e.then(i,i):i()}let n=Bh(this.id,this.engine),r=()=>{try{Uh.default.unlinkSync(n)}catch{}};e?.then?e.then(r,r):r()}}});function yWe(t,e){try{let r=dR.default.readFileSync(t,"utf8").match(/^---\s*([\s\S]*?)\s*---/),i=e,s=`Skill: ${e}`;if(r){let o=r[1],a=o.match(/^name:\s*(.+)$/m),c=o.match(/^description:\s*([\s\S]*?)(?=\n[a-z_]+:|$)/m);a&&(i=a[1].trim()),c&&(s=c[1].trim().replace(/\n+/g," "))}return{name:i,description:s}}catch{return{name:e,description:`Skill: ${e}`}}}function vWe(t){if(!dR.default.existsSync(t))return[];let e=[];try{let n=dR.default.readdirSync(t,{withFileTypes:!0});for(let r of n){if(!r.isDirectory()||r.name.startsWith("."))continue;let i=to.default.join(t,r.name),s=to.default.join(i,"SKILL.md"),{name:o,description:a}=yWe(s,r.name);e.push({id:r.name,name:o,description:a,path:i})}}catch{}return e}function Gae(t="claude",e=null){let n=Date.now();if(tx[t]&&n-tx.at<gWe)return tx[t];let r=$ae.default.homedir(),i=nx(t,r,e),s=new Map;for(let a of i)for(let c of vWe(a))s.has(c.id)||s.set(c.id,c);let o=Array.from(s.values());return tx[t]=o,tx.at=n,o}function nx(t,e,n){return _We[t]?.(e,n)??[]}var dR,to,$ae,tx,gWe,_We,Rq=ne(()=>{dR=Q(require("node:fs"),1),to=Q(require("node:path"),1),$ae=Q(require("node:os"),1),tx={claude:null,codex:null,at:0},gWe=1e4;_We={codex:t=>[to.default.join(t,".codex","skills")],opencode:t=>[to.default.join(t,".config","opencode","skills")],antigravity:t=>[to.default.join(t,".gemini","skills"),to.default.join(t,".gemini","antigravity-cli","builtin","skills")],claude:(t,e)=>[to.default.join(t,".claude","skills"),to.default.join(t,".claude","skills copy"),...e?[to.default.join(e,".claude","skills")]:[]],hermes:t=>[to.default.join(t,".hermes","skills")],pi:(t,e)=>[to.default.join(t,".pi","agent","skills"),...e?[to.default.join(e,".pi","agent","skills")]:[]]}});var Iq,rx,pR,kq,fR,Hae,jae,Pq,Mq,Oq,hR,Wae,mR,zae,Vae,Kae,Nq,gR,Ep,Dq,ix,Yae,yR,Lq,Xae,Fq,Mu=ne(()=>{Iq="jpeg",rx={width:1120,height:780},pR=15e3,kq=5e3,fR=3e4,Hae=100,jae=200,Pq=5,Mq=2e5,Oq=800,hR=2e3,Wae=2e3,mR=1200,zae=25e3,Vae=500,Kae="opencode/1.18.31",Nq={free:{label:"Free",endpoint:"https://opencode.ai/zen/v1/systemone",model:"jev-1.13-free",models:["jev-1.13-free"],note:"OpenCode free lane \xB7 no key \xB7 direct call"},openrouter:{label:"OpenRouter",endpoint:"https://openrouter.ai/api/v1/systemone",model:"typesafe/jev-1.13",models:["typesafe/jev-1.13","inception/mercury-decide:free"],note:"Needs OpenRouter key"},custom:{label:"Custom",endpoint:"",model:"",note:"Any systemone-compatible endpoint"}},gR={enabled:!1,preset:"free",endpoint:"",model:"",apiKey:"",minConfidence:.55,headless:!0,mode:"own"},Ep=["own","attach","extension"],Dq="browserUse.config",ix="chrome://inspect/#remote-debugging",Yae=["Open chrome://inspect/#remote-debugging in Chrome (or use the Open button)",'Enable "Allow remote debugging"',"Come back and Check again"],yR="__extension__",Lq="/browser-relay",Xae=15e3,Fq="chrome://extensions/"});function Jae(t){let e="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",n=Array.from(Uq.default.randomBytes(14),r=>e[r%62]).join("");return`${t}_${Uq.default.randomBytes(6).toString("hex")}${n}`}function wWe(t={}){let e=Nq[t.preset]||Nq.free,n=(t.endpoint||e.endpoint||"").trim(),r=(t.model||e.model||"").trim();if(!n)return{error:"No systemone endpoint configured"};if(!r)return{error:"No model configured"};let i=n.endsWith("/systemone")?n:`${n.replace(/\/$/,"")}/systemone`,s={"Content-Type":"application/json"};if(t.preset==="free"||n.includes("opencode.ai"))Object.assign(s,{Authorization:"Bearer public","User-Agent":Kae,"x-opencode-client":"desktop","x-opencode-session":Jae("ses"),"x-opencode-request":Jae("msg"),"x-opencode-project":"global"});else if(t.apiKey)s.Authorization=`Bearer ${t.apiKey}`;else if(hs().voiceConfig?.openrouterKey)s.Authorization=`Bearer ${hs().voiceConfig.openrouterKey}`;else if(n.includes("openrouter.ai"))return{error:"OpenRouter preset needs an API key \u2014 set it in settings"};return{url:i,model:r,headers:s}}function sx(t,e){try{let n=t.probabilities,r=[...Object.values(n),t.confidence],i=Object.keys(n).length===e.length&&e.every(o=>o in n);return e.includes(t.choice)&&i&&r.every(o=>typeof o=="number"&&Number.isFinite(o)&&o>=0&&o<=1)&&Math.abs(Object.values(n).reduce((o,a)=>o+a,0)-1)<.02&&n[t.choice]>=Math.max(...Object.values(n))-1e-6?t:null}catch{return null}}async function xWe(t,e,n){for(let r=0;r<3;r++){let i;try{i=await fetch(t,{method:"POST",headers:e,body:JSON.stringify(n),signal:AbortSignal.timeout(zae)})}catch(s){throw new Error(`Jev connection failed: ${s.message}`)}if([429,503,529].includes(i.status)&&r<2){await new Promise(s=>setTimeout(s,Vae*2**r));continue}if(!i.ok){let s=`HTTP ${i.status}`;try{let o=await i.json();s=o?.error?.message||o?.message||s}catch{}throw new Error(`Jev provider error: ${s}`)}return await i.json()}throw new Error("Jev provider unavailable")}async function Bq({state:t,questions:e},n){let r=wWe(n);if(r.error)throw new Error(r.error);let i=await xWe(r.url,r.headers,{model:r.model,state:t,questions:e}),s=i?.answers;if(!s||typeof s!="object")throw new Error("Jev returned no answers");return{answers:s,model:i.model||r.model,usage:i.usage||{}}}async function qq(t){let e=Date.now(),n=await Bq({state:{page:{url:"https://example.com",title:"Test",text:"test"},elements:[],recent_actions:[]},questions:{operation:{type:"choice",criteria:{DONE:"Nothing to do",BLOCKED:"Cannot progress"},instructions:{goal:"connectivity test",rules:"pick one"}}}},t),r=sx(n.answers.operation,["DONE","BLOCKED"]);if(!r)throw new Error("Jev response failed validation");return{ok:!0,model:n.model,choice:r.choice,latencyMs:Date.now()-e}}var Uq,$q=ne(()=>{Uq=Q(require("node:crypto"),1);oh();Mu()});function EWe(t){let e=new Set;return t.map(n=>{if(!e.has(n))return e.add(n),n;let r=2;for(;e.has(`${n} (${r})`);)r++;let i=`${n} (${r})`;return e.add(i),i})}function bWe(t,e){let n=new Map;for(let r of t){let i=e(r)||"Page";n.has(i)||n.set(i,[]),n.get(i).push(r)}return[...n].map(([r,i])=>({path:r,items:i}))}function SWe(t,e,n){let{period:r,cycles:i,constant:s}=e;if(r===1&&s[0])return[`${t[0].role} "${ox(t[0].label)}" \xD7${i}: `+t.map(c=>c.id).join(" ")];let o=Array.from({length:r},(c,l)=>s[l]?`${t[l].role} "${ox(t[l].label)}"`:t[l].role),a=[];for(let c=0;c<i;c++)a.push(Array.from({length:r},(l,u)=>{let d=t[c*r+u];return s[u]?d.id:`${d.id} ${ox(n.get(d.id))}`}).join(" \xB7 "));return[`row \xD7${i} [${o.join(", ")}]`,...a]}function TWe(t,e,n){let r=0;for(;e+(r+1)*n<=t.length&&t.slice(e+r*n,e+(r+1)*n).every((i,s)=>Gq(i)===Gq(t[e+s]));)r++;return r}function tce(t,e,n=!1){let r=null,i=(c,l,u)=>!r||c>r.density+1e-9||Math.abs(c-r.density)<1e-9&&(l>r.len||l===r.len&&u<r.cycle.period);for(let c=0;c+6<=t.length;c++){let l=Math.min(50,Math.floor((t.length-c)/3));for(let u=1;u<=l;u++){let d=TWe(t,c,u);if(d<3||u===1&&new Set(t.slice(c,c+d).map(y=>y.label)).size>1)continue;let p=Array.from({length:u},(y,v)=>{let E=t[c+v].label;for(let A=1;A<d;A++)if(t[c+A*u+v].label!==E)return!1;return!0}),m=p.filter(Boolean).length;if(m===0&&new Set(t.slice(c,c+u).map(Gq)).size<2)continue;let h=d*u;i(m/u,h,u)&&(r={start:c,len:h,cycle:{period:u,cycles:d,constant:p},density:m/u})}}if(!r)return t.map(c=>Qae(c,e.get(c.id),n));let s=t.slice(0,r.start).map(c=>Qae(c,e.get(c.id),n)),o=SWe(t.slice(r.start,r.start+r.len),r.cycle,e),a=tce(t.slice(r.start+r.len),e,n);return[...s,...o,...a]}function ax(t,{coords:e=!1}={}){let n=EWe(t.map(o=>o.label)),r=new Map(t.map((o,a)=>[o.id,n[a]])),i=[],s=(o,a)=>{for(let{path:c,items:l}of bWe(o,u=>u.path?.[0])){i.push(`${Zae(a)}${c}:`);let u=l.filter(p=>(p.path?.length??1)>1).map(p=>({...p,path:p.path.slice(1)})),d=l.filter(p=>(p.path?.length??1)<=1);for(let p of tce(d,r,e))i.push(`${Zae(a+1)}${p}`);u.length&&s(u,a+1)}};return s(t,0),i.join(`
226
+ `})}_runningAsync(){if(this.asyncTimers.size)return!0;let e=new Set;for(let{event:n,data:r}of this.history)n!=="tool_result"||!r?.async||!r.id||(r.status==="running"?e.add(r.id):e.delete(r.id));return e.size>0}get idleKillEligible(){if(!(!this.destroyed&&!this.asleep&&Fse.has(this.engine)&&!!this.adapter&&!this.proc?.dead&&!this.promptQueue?.length&&!this._runningAsync()))return!1;let n=Date.now()-this.lastActivityAt;return n>=$se?!0:!this.isTurnRunning&&!this.pendingPermission()&&n>=Use}async idleKill(){return this.idleKillEligible?(this.asleep=!0,this.emitNormalized("sleep",{}),await this.adapter?.stop(),this._saveKvState(!1),this.flushSaveSnapshot(),!0):!1}turnState(){return{isTurnRunning:this.isTurnRunning,elapsedMs:this.isTurnRunning&&this.turnStartedAt?Date.now()-this.turnStartedAt:0}}taskRecords(){let e=[],n=0,r=Date.now();for(let i=this.history.length-1;i>=0;i--){let s=this.history[i];if(!Bae(s))continue;let o={...s.data,ageMs:r-(s.timestamp||r)},a=JSON.stringify(o).length;if(n+a>kse)break;n+=a,e.push(o)}return e.reverse()}emitNormalized(e,n,r=!0){if(e==="cli_reset"){this._resetConversation({conversationId:n?.conversationId||null});return}r&&e==="cli_event"&&oWe.has(n?.subtype)&&(r=!1),r&&e==="cli_event"&&aWe.has(n?.type)&&(r=!1),e==="init"&&(n?.threadId&&(this.threadId=n.threadId),n?.sessionId&&n.sessionId!==this.cliSessionId&&(this.attachmentOffset=null,this.threadTitle=""),n?.sessionId&&(this.cliSessionId=n.sessionId),n?.model&&!cWe.has(n.model)&&(this.model=n.model),n?.effort&&(this.effort=n.effort),this.engine===kt.CODEX&&n?.threadId&&this.refreshGoal(n.threadId),n?.threadName&&(this.threadTitle=String(n.threadName).trim(),this._saveKvState())),n=Uae(e,n),e==="cli_event"&&uR.has(n?.subtype)&&(n={...n,ageMs:0},this._saveKvState());let i=Date.now();this.lastActivityAt=i,e==="user_message"?(this.turnStartedAt=i,this.lastTurnMs=0,this.asleep=!1):Fh.has(e)&&(this.turnStartedAt&&(this.lastTurnMs=i-this.turnStartedAt),n={...n,turnMs:this.lastTurnMs});let s=sWe[e],o=n?.parentToolUseId&&s?{event:s,data:n}:{event:e,data:n};Fh.has(e)&&this._pullAttachments(),Fh.has(e)&&this.engine===kt.CODEX&&this.threadId&&this.refreshGoal(this.threadId);let a=r?++this.seqCounter:void 0;if(r){let c=this.history[this.history.length-1];c&&c.event===o.event&&(o.event==="delta"||o.event==="thinking")&&typeof n?.text=="string"&&typeof c.data?.text=="string"?(c.seq!=null&&c._fromSeq==null&&(c._fromSeq=c.seq),c.data={text:qae(c.data.text,n.text)},c.seq=a,c.timestamp=Date.now()):(this.history.push({seq:a,event:o.event,data:n,timestamp:Date.now()}),this.history.length>Ose&&this.history.shift())}if(vC(this.id),this.onEvent?.(this.id,o.event,n,a,this.logEpoch),r&&this.scheduleSaveSnapshot(),e==="cli_event"&&n?.subtype==="task_notification"){let c=n.record?.tool_use_id;c&&(this.clearAsyncWatchdog(c),this.emitNormalized("tool_result",{id:c,status:"done",async:!0}))}e==="tool_result"&&(n?.async&&n?.handle?this.armAsyncWatchdog(n.id,n.parentToolUseId):n?.id&&this.clearAsyncWatchdog(n.id)),Fh.has(e)&&(this.isTurnRunning=!1,this._settleForegroundTasks(),this.history=fWe(this.history),this.flushSaveSnapshot(),this.applyPendingOptions(),this._saveKvState(!1),this._drainQueue())}_drainQueue(){this.isTurnRunning||!this.promptQueue?.length||this.destroyed||(this._drainTimer&&clearTimeout(this._drainTimer),this._drainTimer=setTimeout(()=>{if(this._drainTimer=null,this.isTurnRunning||!this.promptQueue?.length||this.destroyed)return;let e=this.promptQueue.shift();this.emitQueueUpdate(),this.sendPrompt(e.text,e.attachments)},50))}getQueue(){return Array.isArray(this.promptQueue)?this.promptQueue.map(e=>({id:e.id,text:e.text,attachments:(e.attachments||[]).map(n=>({name:n.name||n.filename,type:n.type}))})):[]}emitQueueUpdate(){this.onEvent?.(this.id,"queue_update",{queue:this.getQueue()})}removeQueueItem(e){if(!Array.isArray(this.promptQueue))return!1;let n=this.promptQueue.length;return this.promptQueue=this.promptQueue.filter(r=>r.id!==e),this.promptQueue.length!==n?(this.emitQueueUpdate(),!0):!1}clearQueue(){this._drainTimer&&(clearTimeout(this._drainTimer),this._drainTimer=null),this.promptQueue?.length&&(this.promptQueue=[],this.emitQueueUpdate())}_pullAttachments(){if(this.engine!==kt.CLAUDE||!this.cliSessionId||this.destroyed)return;if(this.attachmentOffset==null){let n=this._seedAttachmentOffset?this._seedAttachmentOffset():DB(this.cwd,this.cliSessionId,1/0);this.attachmentOffset=n?.offset||0;return}let e=this._readAttachments?this._readAttachments():DB(this.cwd,this.cliSessionId,this.attachmentOffset);if(!e?.records?.length){e?.offset!=null&&(this.attachmentOffset=e.offset);return}this.attachmentOffset=e.offset;for(let n of e.records)this.emitNormalized("cli_event",{type:"attachment",subtype:n.attachment?.type||"",record:n})}hasRecordedInit(){return this.history.some(e=>e.event==="init")}async refreshGoal(e){if(this.engine!==kt.CODEX||this.goalReading===e)return;this.goalReading=e;let n=await Ioe(e,this.cwd).catch(()=>null);if(this.goalReading=null,this.threadId!==e)return;let r=n?`${n.objective}|${n.status}`:"";r===this.goalKey||r===this.lastRecordedGoalKey()||(this.goalKey=r,this.emitNormalized("goal",{goal:n}))}lastRecordedGoalKey(){for(let e=this.history.length-1;e>=0;e--){if(this.history[e].event!=="goal")continue;let n=this.history[e].data?.goal;return n?`${n.objective}|${n.status}`:""}return null}armAsyncWatchdog(e,n){e&&(this.clearAsyncWatchdog(e),this.asyncTimers.set(e,setTimeout(()=>{this.asyncTimers.delete(e),this.emitNormalized("tool_result",{id:e,status:"done",async:!0,...n?{parentToolUseId:n}:{}})},Cse)))}clearAsyncWatchdog(e){let n=this.asyncTimers.get(e);n&&(clearTimeout(n),this.asyncTimers.delete(e))}clearAllAsyncWatchdogs(){for(let e of this.asyncTimers.values())clearTimeout(e);this.asyncTimers.clear()}_settleForegroundTasks(e=!1){let n=new Set;for(let r of this.history||[]){if(r.event!=="cli_event")continue;let i=r.data?.subtype,s=r.data?.record?.task_id||r.data?.task_id;i==="task_notification"&&s&&n.add(s)}for(let r of this.history||[]){if(r.event!=="cli_event"||r.data?.subtype!=="task_started")continue;let i=r.data?.record||{},s=i.task_id||r.data?.task_id;!s||n.has(s)||(e||!i.is_backgrounded)&&(n.add(s),this.emitNormalized("cli_event",{type:"system",subtype:"task_notification",record:{type:"system",subtype:"task_notification",task_id:s,status:"completed"}}))}}_settleRestoredAsync(){for(let e of this.history||[])e.event!=="tool_result"||!e.data?.async||e.data.status!=="running"||(e.data={...e.data,status:"done"});this._settleForegroundTasks(!1)}scheduleSaveSnapshot(){if(this.destroyed||this.persistTimer)return;let e=this.isTurnRunning?Ise:Rse;this.persistTimer=setTimeout(()=>{this.persistTimer=null,this.saveSnapshot()},e),this.persistTimer.unref?.()}flushSaveSnapshot(){this.persistTimer&&(clearTimeout(this.persistTimer),this.persistTimer=null),this.saveSnapshot(!0)}saveSnapshot(e=!1){if(this.persisting){this.persistAgain=!0;return}this.persisting=!0;try{let n=JSON.stringify({engine:this.engine,cwd:this.cwd,threadId:this.threadId,cliSessionId:this.cliSessionId,model:this.model,effort:this.effort,permissionMode:this.permissionMode,createdAt:this.createdAt,options:this.options,asleep:this.asleep,consumedLines:this.consumedLines,consumedEpoch:this.consumedEpoch,attachmentOffset:this.attachmentOffset});if(e){Uh.default.writeFileSync(Bh(this.id,this.engine),n),this.persisting=!1,this.persistAgain&&(this.persistAgain=!1,this.saveSnapshot(!0));return}Uh.default.writeFile(Bh(this.id,this.engine),n,()=>{this.persisting=!1,this.persistAgain&&(this.persistAgain=!1,this.saveSnapshot())})}catch{this.persisting=!1}}_resetConversation({conversationId:e=null,rebuildProcess:n=!1}={}){if(this.threadId=null,this.threadTitle="",this.cliSessionId=e,this.history=[],this.seqCounter=0,this.logEpoch++,this.consumedLines=0,this.consumedEpoch=null,this.attachmentOffset=null,this.isTurnRunning=!1,this.turnStartedAt=0,this.lastTurnMs=0,this.flushSaveSnapshot(),n&&!this.options.mock&&!this.managed){try{this.adapter?.stop()}catch{}this.ready=this.initAdapter()}let r=this.metadata();this.history.push({seq:++this.seqCounter,event:"init",data:r,timestamp:Date.now()}),this.onEvent?.(this.id,"conversation_reset",{hasMore:!1,fromSeq:0,epoch:this.logEpoch,taskRecords:[],lastTurnMs:0,isTurnRunning:!1,elapsedMs:0}),this.onEvent?.(this.id,"init",r),this.clearQueue(),this.flushSaveSnapshot()}sendPrompt(e,n=null,r=null){if(String(e).trim()==="/clear"){if(this.isTurnRunning){this.emitNormalized("error",{message:"Turn is still running \u2014 stop it before /clear."});return}this._resetConversation({rebuildProcess:!0});return}if(this.isTurnRunning){this.skipOpenGates(),Array.isArray(this.promptQueue)||(this.promptQueue=[]);let i={id:`q-${Date.now()}-${++mWe}`,text:e,attachments:n,promptId:r};return this.promptQueue.push(i),this.emitQueueUpdate(),{queued:!0,item:i}}if(this.lastPrompt=e,this.options.mock){this.isTurnRunning=!0,this.skipOpenGates(),this.emitNormalized("user_message",{text:e,attachments:kB(n)}),this.emitNormalized("delta",{text:`[Mock reply to: ${e}]`}),this.emitNormalized("turn_complete",{stats:{}});return}try{this.adapter?.sendPrompt(e,n,r)}catch(i){let s=String(i?.message||i);return this.emitNormalized("prompt_refused",{text:e,promptId:r,reason:s}),this.promptQueue?.length&&this._drainQueue(),{refused:!0,error:s}}this.isTurnRunning=!0,this.turnStartedAt=Date.now(),this._saveKvState(!0),this.skipOpenGates(),this.emitNormalized("user_message",{text:e,attachments:kB(n)})}async renameConversation(e){try{await this.adapter?.renameThread?.(e)}catch{}this.threadTitle!==e&&(this.threadTitle=e,this._saveKvState())}metadata(){return{model:this.model||"",threadId:this.threadId||"",sessionId:this.cliSessionId||"",skills:this.skills||[]}}pendingPermission(){let e=this.adapter?.pendingRequests;if(!e?.size)return null;let n=[...e.keys()].at(-1),r=e.get(n);return{requestId:n,tool:r.toolName||"",input:r.input||{}}}resolvePermission(e,n,r){return this.adapter?.resolvePermission?.(e,n,r)===!1?!1:(this.emitNormalized("permission_resolved",{requestId:e,behavior:n}),!0)}resolveQuestion(e,n){return this.adapter?.resolveQuestion?.(e,n)===!1?!1:(this.emitNormalized("permission_resolved",{requestId:e,behavior:"allow"}),!0)}skipOpenGates(){let e=this.adapter?.pendingRequests;if(!e?.size)return 0;let n=0;for(let r of[...e.keys()])this.resolvePermission(r,uWe,dWe)&&n++;return n}setOptions(e){let{resume:n,...r}=e||{},i=typeof n=="string"&&Oae.test(n)?n:null;if(this.options={...this.options,...r},r?.mode&&(this.permissionMode=r.mode),r?.effort&&(this.effort=r.effort),r?.model&&(this.model=r.model),(r?.model||r?.effort)&&sae(this.engine,{model:this.model,effort:this.effort}),i&&(this.pendingResume=i,this.engine===kt.CLAUDE?this.cliSessionId=i:this.engine===kt.CODEX?this.threadId=i:this.engine===kt.OPENCODE?this.cliSessionId=i:this.engine===kt.ANTIGRAVITY?this.cliSessionId=i:this.engine===kt.DEVIN?this.cliSessionId=i:this.engine===kt.HERMES?this.cliSessionId=i:this.engine===kt.PI&&(this.cliSessionId=i),this.attachmentOffset=null,this._adoptLog(this._rebuildFromStore(i).events||[]),this.turnStartedAt=0,this.lastTurnMs=0,this.history.length||tWe.info(`[ai] rewind left an empty log: engine=${this.engine} resume=${i} cwd=${this.cwd}`)),this.isTurnRunning){this.restartPending=!0,(r?.mode||r?.effort||r?.model||i)&&(this._saveKvState(),this.flushSaveSnapshot());return}let s=this.adapter?.setOptions?.({...e,resume:i});s?.then&&s.then(o=>this._replay(o)),(r?.mode||r?.effort||r?.model||i)&&(this._saveKvState(),this.flushSaveSnapshot())}applyPendingOptions(){if(!this.restartPending)return;this.restartPending=!1;let e=this.pendingResume||null;this.pendingResume=null;let n=this.adapter?.setOptions?.({mode:this.permissionMode,model:this.model,effort:this.effort,...e?{resume:e}:{}});n?.then&&n.then(r=>this._replay(r))}async runDoctor(){return Aq(this.engine,this.cwd,this.options.mock)}stop(){let e=this.adapter?.interrupt?.(),n=e?!1:this.adapter?.signal?.("SIGINT");return!e&&!n?(this.emitNormalized("error",{message:`${this.engine} could not stop this turn \u2014 the CLI is still running.`}),!1):(this.emitNormalized("stopped",{}),!0)}stopTask(e){return!this.adapter?.stopTask?.(e)&&e&&this.emitNormalized("cli_event",{type:"system",subtype:"task_notification",record:{type:"system",subtype:"task_notification",task_id:String(e),status:"stopped"}}),!0}async ensureProcAlive(){if(!(!this.managed||!this.proc||this.adapter?.proc!==this.proc)&&!(this.destroyed||this.options.mock)){if(this._ensureAlive)return this._ensureAlive;this._ensureAlive=(async()=>{let e=!0;try{e=(await RA()).some(n=>n.procId===this.id&&n.alive!==!1)}catch{return}e||await this.restart()})();try{await this._ensureAlive}finally{this._ensureAlive=null}}}async restart(){this.clearAllAsyncWatchdogs(),this.isTurnRunning=!1,this.turnStartedAt=0,this.lastTurnMs=0,this.skipOpenGates();let e=this.adapter;if(this.adapter=null,e)try{await Promise.resolve(e.stop?.())}catch{}return this.managed&&(this.proc=new rc({procId:this.id})),this.ready=this.initAdapter().then(async n=>(await this._applyKvToAdapter(),n)),await this.ready,this.refreshFromStore(),this.emitNormalized("stopped",{}),this._saveKvState(!1),this.flushSaveSnapshot(),!0}destroy(){this.clearAllAsyncWatchdogs(),this._drainTimer&&(clearTimeout(this._drainTimer),this._drainTimer=null),this.promptQueue=[],this.persistTimer&&(clearTimeout(this.persistTimer),this.persistTimer=null);let e=this.options.mock||typeof this.adapter?.stop!="function"?Promise.resolve():this.adapter.stop();if(this.destroyed=!0,this.emitNormalized("stopped",{}),this.engine===kt.OPENCODE&&!this.options.mock){let i=()=>iq();e?.then?e.then(i,i):i()}let n=Bh(this.id,this.engine),r=()=>{try{Uh.default.unlinkSync(n)}catch{}};e?.then?e.then(r,r):r()}}});function yWe(t,e){try{let r=dR.default.readFileSync(t,"utf8").match(/^---\s*([\s\S]*?)\s*---/),i=e,s=`Skill: ${e}`;if(r){let o=r[1],a=o.match(/^name:\s*(.+)$/m),c=o.match(/^description:\s*([\s\S]*?)(?=\n[a-z_]+:|$)/m);a&&(i=a[1].trim()),c&&(s=c[1].trim().replace(/\n+/g," "))}return{name:i,description:s}}catch{return{name:e,description:`Skill: ${e}`}}}function vWe(t){if(!dR.default.existsSync(t))return[];let e=[];try{let n=dR.default.readdirSync(t,{withFileTypes:!0});for(let r of n){if(!r.isDirectory()||r.name.startsWith("."))continue;let i=to.default.join(t,r.name),s=to.default.join(i,"SKILL.md"),{name:o,description:a}=yWe(s,r.name);e.push({id:r.name,name:o,description:a,path:i})}}catch{}return e}function Gae(t="claude",e=null){let n=Date.now();if(tx[t]&&n-tx.at<gWe)return tx[t];let r=$ae.default.homedir(),i=nx(t,r,e),s=new Map;for(let a of i)for(let c of vWe(a))s.has(c.id)||s.set(c.id,c);let o=Array.from(s.values());return tx[t]=o,tx.at=n,o}function nx(t,e,n){return _We[t]?.(e,n)??[]}var dR,to,$ae,tx,gWe,_We,Rq=ne(()=>{dR=Q(require("node:fs"),1),to=Q(require("node:path"),1),$ae=Q(require("node:os"),1),tx={claude:null,codex:null,at:0},gWe=1e4;_We={codex:t=>[to.default.join(t,".codex","skills")],opencode:t=>[to.default.join(t,".config","opencode","skills")],antigravity:t=>[to.default.join(t,".gemini","skills"),to.default.join(t,".gemini","antigravity-cli","builtin","skills")],claude:(t,e)=>[to.default.join(t,".claude","skills"),to.default.join(t,".claude","skills copy"),...e?[to.default.join(e,".claude","skills")]:[]],hermes:t=>[to.default.join(t,".hermes","skills")],pi:(t,e)=>[to.default.join(t,".pi","agent","skills"),...e?[to.default.join(e,".pi","agent","skills")]:[]]}});var Iq,rx,pR,kq,fR,Hae,jae,Pq,Mq,Oq,hR,Wae,mR,zae,Vae,Kae,Nq,gR,Ep,Dq,ix,Yae,yR,Lq,Xae,Fq,Mu=ne(()=>{Iq="jpeg",rx={width:1120,height:780},pR=15e3,kq=5e3,fR=3e4,Hae=100,jae=200,Pq=5,Mq=2e5,Oq=800,hR=2e3,Wae=2e3,mR=1200,zae=25e3,Vae=500,Kae="opencode/1.18.31",Nq={free:{label:"Free",endpoint:"https://opencode.ai/zen/v1/systemone",model:"jev-1.13-free",models:["jev-1.13-free"],note:"OpenCode free lane \xB7 no key \xB7 direct call"},openrouter:{label:"OpenRouter",endpoint:"https://openrouter.ai/api/v1/systemone",model:"typesafe/jev-1.13",models:["typesafe/jev-1.13","inception/mercury-decide:free"],note:"Needs OpenRouter key"},custom:{label:"Custom",endpoint:"",model:"",note:"Any systemone-compatible endpoint"}},gR={enabled:!1,preset:"free",endpoint:"",model:"",apiKey:"",minConfidence:.55,headless:!0,mode:"own"},Ep=["own","attach","extension"],Dq="browserUse.config",ix="chrome://inspect/#remote-debugging",Yae=["Open chrome://inspect/#remote-debugging in Chrome (or use the Open button)",'Enable "Allow remote debugging"',"Come back and Check again"],yR="__extension__",Lq="/browser-relay",Xae=15e3,Fq="chrome://extensions/"});function Jae(t){let e="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",n=Array.from(Uq.default.randomBytes(14),r=>e[r%62]).join("");return`${t}_${Uq.default.randomBytes(6).toString("hex")}${n}`}function wWe(t={}){let e=Nq[t.preset]||Nq.free,n=(t.endpoint||e.endpoint||"").trim(),r=(t.model||e.model||"").trim();if(!n)return{error:"No systemone endpoint configured"};if(!r)return{error:"No model configured"};let i=n.endsWith("/systemone")?n:`${n.replace(/\/$/,"")}/systemone`,s={"Content-Type":"application/json"};if(t.preset==="free"||n.includes("opencode.ai"))Object.assign(s,{Authorization:"Bearer public","User-Agent":Kae,"x-opencode-client":"desktop","x-opencode-session":Jae("ses"),"x-opencode-request":Jae("msg"),"x-opencode-project":"global"});else if(t.apiKey)s.Authorization=`Bearer ${t.apiKey}`;else if(hs().voiceConfig?.openrouterKey)s.Authorization=`Bearer ${hs().voiceConfig.openrouterKey}`;else if(n.includes("openrouter.ai"))return{error:"OpenRouter preset needs an API key \u2014 set it in settings"};return{url:i,model:r,headers:s}}function sx(t,e){try{let n=t.probabilities,r=[...Object.values(n),t.confidence],i=Object.keys(n).length===e.length&&e.every(o=>o in n);return e.includes(t.choice)&&i&&r.every(o=>typeof o=="number"&&Number.isFinite(o)&&o>=0&&o<=1)&&Math.abs(Object.values(n).reduce((o,a)=>o+a,0)-1)<.02&&n[t.choice]>=Math.max(...Object.values(n))-1e-6?t:null}catch{return null}}async function xWe(t,e,n){for(let r=0;r<3;r++){let i;try{i=await fetch(t,{method:"POST",headers:e,body:JSON.stringify(n),signal:AbortSignal.timeout(zae)})}catch(s){throw new Error(`Jev connection failed: ${s.message}`)}if([429,503,529].includes(i.status)&&r<2){await new Promise(s=>setTimeout(s,Vae*2**r));continue}if(!i.ok){let s=`HTTP ${i.status}`;try{let o=await i.json();s=o?.error?.message||o?.message||s}catch{}throw new Error(`Jev provider error: ${s}`)}return await i.json()}throw new Error("Jev provider unavailable")}async function Bq({state:t,questions:e},n){let r=wWe(n);if(r.error)throw new Error(r.error);let i=await xWe(r.url,r.headers,{model:r.model,state:t,questions:e}),s=i?.answers;if(!s||typeof s!="object")throw new Error("Jev returned no answers");return{answers:s,model:i.model||r.model,usage:i.usage||{}}}async function qq(t){let e=Date.now(),n=await Bq({state:{page:{url:"https://example.com",title:"Test",text:"test"},elements:[],recent_actions:[]},questions:{operation:{type:"choice",criteria:{DONE:"Nothing to do",BLOCKED:"Cannot progress"},instructions:{goal:"connectivity test",rules:"pick one"}}}},t),r=sx(n.answers.operation,["DONE","BLOCKED"]);if(!r)throw new Error("Jev response failed validation");return{ok:!0,model:n.model,choice:r.choice,latencyMs:Date.now()-e}}var Uq,$q=ne(()=>{Uq=Q(require("node:crypto"),1);oh();Mu()});function EWe(t){let e=new Set;return t.map(n=>{if(!e.has(n))return e.add(n),n;let r=2;for(;e.has(`${n} (${r})`);)r++;let i=`${n} (${r})`;return e.add(i),i})}function bWe(t,e){let n=new Map;for(let r of t){let i=e(r)||"Page";n.has(i)||n.set(i,[]),n.get(i).push(r)}return[...n].map(([r,i])=>({path:r,items:i}))}function SWe(t,e,n){let{period:r,cycles:i,constant:s}=e;if(r===1&&s[0])return[`${t[0].role} "${ox(t[0].label)}" \xD7${i}: `+t.map(c=>c.id).join(" ")];let o=Array.from({length:r},(c,l)=>s[l]?`${t[l].role} "${ox(t[l].label)}"`:t[l].role),a=[];for(let c=0;c<i;c++)a.push(Array.from({length:r},(l,u)=>{let d=t[c*r+u];return s[u]?d.id:`${d.id} ${ox(n.get(d.id))}`}).join(" \xB7 "));return[`row \xD7${i} [${o.join(", ")}]`,...a]}function TWe(t,e,n){let r=0;for(;e+(r+1)*n<=t.length&&t.slice(e+r*n,e+(r+1)*n).every((i,s)=>Gq(i)===Gq(t[e+s]));)r++;return r}function tce(t,e,n=!1){let r=null,i=(c,l,u)=>!r||c>r.density+1e-9||Math.abs(c-r.density)<1e-9&&(l>r.len||l===r.len&&u<r.cycle.period);for(let c=0;c+6<=t.length;c++){let l=Math.min(50,Math.floor((t.length-c)/3));for(let u=1;u<=l;u++){let d=TWe(t,c,u);if(d<3||u===1&&new Set(t.slice(c,c+d).map(y=>y.label)).size>1)continue;let p=Array.from({length:u},(y,v)=>{let E=t[c+v].label;for(let A=1;A<d;A++)if(t[c+A*u+v].label!==E)return!1;return!0}),m=p.filter(Boolean).length;if(m===0&&new Set(t.slice(c,c+u).map(Gq)).size<2)continue;let h=d*u;i(m/u,h,u)&&(r={start:c,len:h,cycle:{period:u,cycles:d,constant:p},density:m/u})}}if(!r)return t.map(c=>Qae(c,e.get(c.id),n));let s=t.slice(0,r.start).map(c=>Qae(c,e.get(c.id),n)),o=SWe(t.slice(r.start,r.start+r.len),r.cycle,e),a=tce(t.slice(r.start+r.len),e,n);return[...s,...o,...a]}function ax(t,{coords:e=!1}={}){let n=EWe(t.map(o=>o.label)),r=new Map(t.map((o,a)=>[o.id,n[a]])),i=[],s=(o,a)=>{for(let{path:c,items:l}of bWe(o,u=>u.path?.[0])){i.push(`${Zae(a)}${c}:`);let u=l.filter(p=>(p.path?.length??1)>1).map(p=>({...p,path:p.path.slice(1)})),d=l.filter(p=>(p.path?.length??1)<=1);for(let p of tce(d,r,e))i.push(`${Zae(a+1)}${p}`);u.length&&s(u,a+1)}};return s(t,0),i.join(`
227
227
  `)}var Gq,ece,ox,Qae,Zae,Hq=ne(()=>{Gq=t=>`${t.role}|${t.kind}`,ece=t=>String(t??"").replace(/\s+/g," ").trim(),ox=(t,e=80)=>{let n=ece(t);return n.length>e?n.slice(0,e-1)+"\u2026":n},Qae=(t,e,n=!1)=>{let r=t.value?` =${ece(t.value).slice(0,30)}`:"",i=t.checked?` [${t.checked}]`:"",s=t.href?` -> ${ox(t.href,70)}`:"",o=n&&t.rect?` [${Math.round(t.rect.x+(t.rect.w?t.rect.w/2:0))},${Math.round(t.rect.y+(t.rect.h?t.rect.h/2:0))}]`:"";return`${t.id} ${t.role||t.kind} "${ox(e)}"${i}${r}${s}${o}`};Zae=t=>" ".repeat(t)});function bp(t,e){if(!e)return t;let n=String(e).toLowerCase(),r=i=>(i.path||[]).some(s=>String(s).toLowerCase().includes(n))||String(i.ctx||"").toLowerCase().includes(n);return t.filter(i=>i.kind==="scroll"||i.kind==="wait"||r(i))}function kWe(t,e=null){let n=252;if(t.length>n){let l=new Set(t.slice(0,n).map(u=>u.id));t=t.filter(u=>u.kind==="scroll"||u.kind==="wait"||l.has(u.id))}let r={CLICK:{},SELECT:{}},i={},s=[],o=new Map,a={};for(let l of t){if(l.kind==="wait"){i.WAIT=l;continue}if(l.kind!=="upload"){if(l.kind==="scroll"){i[l.id.toUpperCase()]=l;continue}if(l.kind==="fill"){nce(s,o,l);let u=PWe(e,l.label);u!==null&&(a[l.id]={...l,text:u});continue}nce(s,o,l),r[l.kind==="select"?"SELECT":"CLICK"][l.id]=l}}Object.keys(a).length&&(r.TYPE_TEXT=a);for(let l of Object.keys(r))Object.keys(r[l]).length||delete r[l];let c=80;for(let l of Object.keys(r)){let u=r[l],d=new Map;for(let p of Object.keys(u)){let m=u[p],h=String(m.label||""),y=h.length>c?`${h.slice(0,c-3)}\u2026`:h,v=(d.get(y)||0)+1;d.set(y,v),u[p]={...m,label:v>1?`${y} (${v})`:y}}}return{elements:s,targets:r,controls:i}}function nce(t,e,n){if(e.has(n.node)){e.get(n.node).labels.push(n.label);return}let r={index:String(t.length+1),label:String(n.label||"").split(" \u2192 ")[0].slice(0,80),role:n.role||null,value:n.value??"",labels:[n.label]};e.set(n.node,r),t.push(r)}function PWe(t,e){if(!t)return null;let n=Object.keys(t),r=String(e||"").toLowerCase(),i=n.find(o=>o.toLowerCase()===r)||n.find(o=>r.includes(o.toLowerCase()));if(i===void 0)return null;let s=t[i];return typeof s=="string"&&s.trim()?s:null}function MWe(t,e,n,r){let i={};for(let a of Object.keys(r.targets))i[a]=rce[a];for(let a of Object.keys(r.controls))i[a]=rce[a]||r.controls[a].label;i.DONE="Every requirement is visibly satisfied.",i.BLOCKED="No supported operation can make progress.";let s={operation:{type:"choice",criteria:i,instructions:{goal:e,rules:ice}}};for(let[a,c]of Object.entries(r.targets))s[`${a.toLowerCase()}_target`]={type:"choice",criteria:Object.fromEntries(Object.entries(c).map(([l,u])=>{let p={element:Ou(u.ctx?`[${l}] ${u.label} \xB7 in ${u.ctx}`:`[${l}] ${u.label}`),current_value:Ou(u.current_value??u.value??""),role:u.role||null},m=[];return u.checked&&m.push(u.checked==="true"?"checked":"unchecked"),u.expanded&&m.push(u.expanded==="true"?"expanded":"collapsed"),m.length&&(p.state=m.join(",")),[l,p]})),instructions:{goal:e,operation:a,rules:[ice,OWe]}};let o=oce(r);for(let a=2;a<=3&&Object.keys(o).length;a++)s[`step_${a}`]={type:"choice",criteria:Object.fromEntries([["SKIP",NWe],...Object.entries(o).map(([c,l])=>[c,Ou(l.planLabel||l.label)])]),instructions:{goal:e,rules:[DWe]}};return{state:{page:{url:Ou(t.url),title:Ou(t.title),text:Ou(t.text),headings:(t.headings||[]).map(Ou),scroll:t.scroll||null,omitted:t.omitted_actions||0,tree:Ou(ax(t.actions||[]))},recent_actions:n.slice(-10).map(a=>({action:Ou(a.action),kind:a.kind,text:a.text,page_changed:a.page_changed}))},questions:s}}function il(t,{url:e=null,title:n=null,text:r=[]}={}){let i=(Array.isArray(r)?r:[r]).map(l=>String(l)),s=(t.actions||[]).filter(l=>l.kind==="fill"&&l.value).map(l=>`${l.label}: ${l.value}`).join(`
228
228
  `),o=(t.actions||[]).filter(l=>l.kind==="select").map(l=>l.label||"").join(`
229
229
  `),a=`${t.text||""}
@@ -1058,7 +1058,7 @@ export default function (pi) {
1058
1058
  pi.on("agent_start", async (_e, ctx) => { if (ctx?.hasUI) post("working", csidOf(ctx)); });
1059
1059
  pi.on("agent_end", async (_e, ctx) => { if (ctx?.hasUI) post("done", csidOf(ctx)); });
1060
1060
  }
1061
- `}function I5e(t){let e=C5e[t];if(!e)return{success:!1,error:"Unknown tool"};try{return t==="codex"||t==="opencode"||t==="amp"||t==="pi"||t==="omp"?e.enable():e.enable(yn[t]())}catch(n){return{success:!1,error:n.message}}}function k5e(t){let e=(process.env.PATH||"").split(Sr.default.delimiter).filter(Boolean),n=process.platform==="win32"?(process.env.PATHEXT||".EXE;.CMD;.BAT").split(";"):[""];return e.some(r=>n.some(i=>{try{return ze.default.existsSync(Sr.default.join(r,t+i))}catch{return!1}}))}function xhe(t){let e=ghe[t];if(e&&k5e(e))return!0;let n=r5e[t]?.();return n?(Array.isArray(n)?n:[n]).some(r=>ze.default.existsSync(r)):!1}function Ehe(){let t={};for(let e of R5e)if(xhe(e))try{let n=I5e(e);t[e]=n.success&&!n.untrusted?.length}catch{t[e]=!1}return t}async function bhe(){if(!xhe("codex"))return null;try{let{missing:t}=await h5e();return t.length&&console.warn(`\u26A0\uFE0F codex hooks written but not trusted: ${t.length} \u2014 run codex and trust them`),t.length?{untrusted:t.length}:{untrusted:0}}catch(t){return console.warn(`\u26A0\uFE0F codex hook trust failed: ${t.message}`),{error:t.message}}}function She(){let t=yn.claude(),e=zr(t);if(!e.hooks?.Stop&&!e.hooks?.Notification)return;let n=e.env||{};Object.keys(iw).some(i=>n[i]!==iw[i])&&(yhe(e),Cs(t,e))}var fhe,ze,Sr,hhe,VI,mhe,n5e,Ni,kp,yn,ghe,Jh,r5e,EG,KI,zI,i5e,WI,vhe,d1t,_he,u5e,p5e,uhe,xG,g5e,dhe,v5e,x5e,b5e,S5e,T5e,A5e,C5e,R5e,The=ne(()=>{fhe=Q(require("os"),1),ze=Q(require("fs"),1),Sr=Q(require("path"),1),hhe=require("child_process");qt();qo();Jc();VI=`http://localhost:${Ua}/api/notify`,mhe="nineRemoteNotify",n5e=Sr.default.join(Pe.STATE,"claudeEnvBackup.json"),Ni=(...t)=>Sr.default.join(fhe.default.homedir(),...t),kp=(t,...e)=>{let n=process.env[t];return n&&n.trim()?n.trim():Ni(...e)},yn={claude:()=>Ni(".claude","settings.json"),codex:()=>Ni(".codex","config.toml"),codexHooks:()=>Ni(".codex","hooks.json"),codexScript:()=>Ni(".codex","9remote-notify.sh"),opencode:()=>Ni(".config","opencode","plugin",`${mhe}.js`),grok:()=>Sr.default.join(kp("GROK_HOME",".grok"),"hooks","9remote.json"),cursor:()=>Ni(".cursor","hooks.json"),antigravity:()=>Ni(".gemini","config","hooks.json"),kiro:()=>Sr.default.join(kp("KIRO_HOME",".kiro"),"agents","9remote.json"),copilot:()=>Sr.default.join(kp("COPILOT_HOME",".copilot"),"config.json"),codebuddy:()=>Sr.default.join(kp("CODEBUDDY_CONFIG_DIR",".codebuddy"),"settings.json"),factory:()=>Ni(".factory","settings.json"),qoder:()=>Sr.default.join(kp("QODER_CONFIG_DIR",".qoder"),"settings.json"),rovodev:()=>Ni(".rovodev","config.yml"),hermes:()=>Sr.default.join(kp("HERMES_HOME",".hermes"),"config.yaml"),amp:()=>Ni(".config","amp","plugins","9remote.ts"),devin:()=>Ni(".config","devin","config.json"),pi:()=>Sr.default.join(kp("PI_CODING_AGENT_DIR",".pi","agent"),"extensions","9remote.ts"),omp:()=>Sr.default.join(kp("PI_CODING_AGENT_DIR",".omp","agent"),"extensions","9remote.ts")},ghe={claude:"claude",codex:"codex",opencode:"opencode",grok:"grok",cursor:"cursor-agent",antigravity:"agy",kiro:"kiro-cli",copilot:"copilot",codebuddy:"codebuddy",factory:"droid",qoder:"qodercli",rovodev:"acli",hermes:"hermes",amp:"amp",pi:"pi",omp:"omp",devin:"devin"},Jh=(t,e,{sessionId:n=!1}={})=>{let r=n?QU(e)[0]:null;return`${r?`csid=$(cat 2>/dev/null | sed -n 's/.*"${r}" *: *"\\([^"]*\\)".*/\\1/p'); `:""}command -v curl >/dev/null 2>&1 && curl -s --connect-timeout 1 --max-time 2 "${VI}?type=${t}&sessionId=$NINE_REMOTE_SESSION_ID${r?"&csid=$csid":""}&tool=${e}" > /dev/null 2>&1 & true`},r5e={claude:()=>Ni(".claude"),codex:()=>Ni(".codex"),opencode:()=>[Ni(".config","opencode"),Ni(".opencode")]},EG=t=>Math.ceil(t/1e3),KI=5e3,zI=t=>t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),i5e=t=>`"${t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`;WI={UserPromptSubmit:"working",PreToolUse:"working",PostToolUse:"working",Stop:"done",PermissionRequest:"blocked"},vhe=t=>t.replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase(),d1t=Object.fromEntries(Object.keys(WI).map(t=>[vhe(t),t])),_he=/^\[hooks\.state\."(?<key>[^"]+)"\]$/m,u5e=15e3;p5e=t=>/^sha256:/.test(t)?t:`sha256:${t}`,uhe=t=>t.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),xG=(t,e)=>t.replace(/\\+/g,"\\")===e.replace(/\\+/g,"\\");g5e=/# 9Remote notification\nnotify\s*=.*\n?/g,dhe=/^# 9Remote-saved: (notify\s*=.*)$/m;v5e={enable(){let t=yn.codexHooks(),e=zr(t),n={...e.hooks||{}};for(let[r,i]of Object.entries(WI))n[r]=[...(n[r]||[]).filter(s=>!wG(s)),_5e(i)];return e.hooks=n,Cs(t,e),y5e(),{success:!0}},disable(){let t=yn.codexHooks(),e=new Set(whe(t).filter(n=>n.command.includes("&tool=codex")).map(n=>n.key));if(ze.default.existsSync(t)){let n=zr(t);if(n.hooks){for(let r of Object.keys(WI))n.hooks[r]=(n.hooks[r]||[]).filter(i=>!wG(i)),n.hooks[r].length===0&&delete n.hooks[r];Object.keys(n.hooks).length===0&&delete n.hooks}Cs(t,n)}return m5e(yn.codex(),e),{success:!0}},isEnabled(){let t=zr(yn.codexHooks()).hooks||{};return Object.keys(WI).every(e=>(t[e]||[]).some(wG))}};x5e={enable(){let t=yn.opencode(),e=Sr.default.dirname(t);return ze.default.existsSync(e)||ze.default.mkdirSync(e,{recursive:!0}),ze.default.writeFileSync(t,w5e(),"utf8"),{success:!0}},disable(){let t=yn.opencode();return ze.default.existsSync(t)&&ze.default.unlinkSync(t),{success:!0}},isEnabled(){let t=yn.opencode();return ze.default.existsSync(t)&&ze.default.readFileSync(t,"utf8").includes("&sessionID=")}};b5e="# 9remote hooks begin",S5e="# 9remote hooks end",T5e=" # 9remote hooks begin",A5e=" # 9remote hooks end",C5e={claude:Xh("claude",{UserPromptSubmit:"working",PreToolUse:"working",PostToolUse:"working",Stop:"done",PermissionRequest:"blocked",Notification:"blocked"},t=>t,{matchers:{Notification:"permission_prompt"},extra:yhe,sessionId:!0}),devin:Xh("devin",{UserPromptSubmit:"working",PreToolUse:"working",PostToolUse:"working",Stop:"done",PermissionRequest:"blocked"},t=>t,{sessionId:!0}),codex:v5e,opencode:x5e,grok:Xh("grok",{UserPromptSubmit:"working",PreToolUse:"working",PostToolUse:"working",Stop:"done",Notification:"blocked"},EG),cursor:a5e("cursor",{stop:"done",beforeShellExecution:"blocked",beforeToolCall:"working"},{extra:t=>{t.version=t.version||1}}),antigravity:c5e("antigravity","9remote",{UserPromptSubmit:"working",PreToolUse:"working",Stop:"done",Notification:"blocked"}),kiro:l5e("kiro",{UserPromptSubmit:"working",PostToolUse:"working",preToolUse:"blocked",stop:"done"}),copilot:Xh("copilot",{UserPromptSubmit:"working",PostToolUse:"working",PreToolUse:"blocked",Stop:"done"},t=>t),codebuddy:Xh("codebuddy",{UserPromptSubmit:"working",PostToolUse:"working",PreToolUse:"blocked",Stop:"done"},t=>t),factory:Xh("factory",{UserPromptSubmit:"working",PostToolUse:"working",PreToolUse:"blocked",Stop:"done"},t=>t),qoder:Xh("qoder",{UserPromptSubmit:"working",PostToolUse:"working",PreToolUse:"blocked",Stop:"done"},t=>t),rovodev:lhe("rovodev",{begin:T5e,end:A5e,items:[{event:"on_complete",type:"done"},{event:"on_error",type:"done"},{event:"on_tool_permission",type:"blocked"},{event:"on_message",type:"working"},{event:"on_tool_start",type:"working"}]}),hermes:(()=>{let t=lhe("hermes",{begin:b5e,end:S5e,items:[{event:"pre_llm_call",type:"working"},{event:"pre_tool_call",type:"working"},{event:"post_tool_call",type:"working"},{event:"pre_approval_request",type:"blocked"},{event:"post_llm_call",type:"done"}]}),e=()=>Sr.default.join(Sr.default.dirname(yn.hermes()),"shell-hooks-allowlist.json");return{enable:()=>{let n=t.enable(yn.hermes()),r=zr(e()),i=(r.approvals||[]).filter(s=>!(typeof s.command=="string"&&s.command.includes("&tool=hermes")));return r.approvals=[...i,...[{event:"pre_llm_call",type:"working"},{event:"pre_tool_call",type:"working"},{event:"post_tool_call",type:"working"},{event:"pre_approval_request",type:"blocked"},{event:"post_llm_call",type:"done"}].map(({event:s,type:o})=>({event:s,command:Jh(o,"hermes"),approved_at:"2020-01-01T00:00:00Z"}))],Cs(e(),r),n},disable:()=>{let n=t.disable(yn.hermes()),r=e();if(ze.default.existsSync(r)){let i=zr(r);i.approvals=(i.approvals||[]).filter(s=>!(typeof s.command=="string"&&s.command.includes("&tool=hermes"))),i.approvals.length?Cs(r,i):ze.default.unlinkSync(r)}return n},isEnabled:()=>t.isEnabled(yn.hermes())}})(),amp:{enable(){let t=yn.amp(),e=Sr.default.dirname(t);return ze.default.existsSync(e)||ze.default.mkdirSync(e,{recursive:!0}),ze.default.writeFileSync(t,phe("amp","amp","agent.start","agent.end"),"utf8"),{success:!0}},disable(){return ze.default.existsSync(yn.amp())&&ze.default.unlinkSync(yn.amp()),{success:!0}},isEnabled(){return ze.default.existsSync(yn.amp())}},pi:{enable(){let t=yn.pi(),e=Sr.default.dirname(t);return ze.default.existsSync(e)||ze.default.mkdirSync(e,{recursive:!0}),ze.default.writeFileSync(t,phe("pi","pi","agent_start","agent_end"),"utf8"),{success:!0}},disable(){return ze.default.existsSync(yn.pi())&&ze.default.unlinkSync(yn.pi()),{success:!0}},isEnabled(){return ze.default.existsSync(yn.pi())}},omp:{enable(){let t=yn.omp(),e=Sr.default.dirname(t);return ze.default.existsSync(e)||ze.default.mkdirSync(e,{recursive:!0}),ze.default.writeFileSync(t,E5e(),"utf8"),{success:!0}},disable(){return ze.default.existsSync(yn.omp())&&ze.default.unlinkSync(yn.omp()),{success:!0}},isEnabled(){return ze.default.existsSync(yn.omp())}}},R5e=iY});var bG=ne(()=>{xs()});var jI={};fr(jI,{broadcastAiStatus:()=>Hx,broadcastServerInfo:()=>QI,initializeTerminal:()=>RG,listSessionRoots:()=>Wu,matchWorkspacePath:()=>Mhe,registerManagedSession:()=>CG,setConnectCheckHandler:()=>IG,setupTerminalHandlers:()=>kG,setupTerminalSocket:()=>Np,workspaceOfSession:()=>U5e});async function N5e(t,e){if(!qie(e))return;let r=(await zc().catch(()=>null))?.find(s=>s.id===e);Bie(e,r?.foregroundProcess)?.state==="idle"&&(Ge(t,"statusChange",{sessionId:e,state:"idle",tool:null,conversationId:null}),Ge(t,"statusState",Zc()))}function D5e(t,e){let n=(XI.get(t)||"")+e,r=null;Ahe.lastIndex=0;for(let o;o=Ahe.exec(n);)r=o[1];if(r){let o=Tie(r);o&&_s(t,o)}let i=n.lastIndexOf("\x1B]"),s=i===-1?"":n.slice(i);s&&s.length<=M5e&&!s.slice(3).includes("\x07")&&!s.includes("\x1B\\")?XI.set(t,s):XI.delete(t)}function Rhe(){let t=(Che||Promise.resolve()).catch(()=>{}).then(()=>L5e());return Che=t.catch(()=>{}),t}async function L5e(){let t=await zc(),e=new Map(t.map(r=>[r.id,r])),n=TC();for(let r of t)if(!n[r.id])try{await Qd(r.id)}catch{}Tr.clear();for(let[r,i]of Object.entries(n)){let s=e.get(r);Tr.set(r,{daemon:!0,name:i.name,autoNamed:i.autoNamed!==!1,createdAt:i.createdAt,shellId:i.shellId,cwd:s?.cwd||i.cwd,workspacePath:i.workspacePath??$x[r]??null,lastCols:i.cols??null,lastRows:i.rows??null,needsRespawn:!s,agent:i.agent||null}),i.agent&&_s(r,i.agent),oB(r,i)}ii(Tr)}function F5e(t){!Pp||!t||Gx.has(t)||Gx.set(t,setTimeout(()=>{Gx.delete(t),rI(Pp,Tr,t).catch(()=>{})},lte))}async function Ihe(){let t=[...Tr.entries()].filter(([,n])=>n.daemon&&n.needsRespawn),e=0;for(let[n,r]of t)try{let{cols:i,rows:s}=tI(r),o=await wu(r.name,i,s,r.shellId,n,r.cwd);if(!o.success)continue;delete r.needsRespawn,r.cwd=o.cwd,r.shellLabel=o.shellLabel,r.lastCols=i,r.lastRows=s,e++;let a=Mi(n),c=a&&ur(a.agent),l=c&&a.id&&Au(c,a.id);l&&setTimeout(()=>$h(n,r,`${Ax}${l}\r`),ute)}catch(i){Phe.warn(`[respawn] session ${n} failed: ${i.message}`)}e&&(ii(Tr),Ge(null,"sessionsChanged"),console.log(AG(`\u{1F504} Respawned ${e} session(s) after daemon restart`)))}function SG(){let{assignments:t,created:e}=lse({sessions:Tr,workspaces:[...Mp.values()],sessionWorkspaces:Op});if(Object.keys(t).length){for(let n of e)Mp.set(n.id,n);for(let[n,r]of Object.entries(t)){Op[n]=r;let i=Tr.get(n);i&&!i.workspacePath&&(i.workspacePath=Mp.get(r)?.path||null)}Oy(Mp,Op,JI),ii(Tr),console.log(AG(`\u{1F4C1} Grouped ${Object.keys(t).length} loose terminal(s)`+(e.length?` into ${e.length} new workspace(s)`:"")))}}function U5e(t){if(Tr.has(t))return Op[t]??null}function Wu(){return[...Tr.entries()].map(([t,e])=>({id:t,name:e.name,workspacePath:e.workspacePath||null,cwd:e.cwd||null}))}function Mhe(t,e){let n=e?(0,Qh.resolve)(e):"";if(!n)return null;let r=null,i=null,s=null;for(let o of t||[]){if(!o?.path)continue;let a=(0,Qh.resolve)(o.path);n===a?r=o:n.startsWith(a+"/")&&(!i||a.length>(0,Qh.resolve)(i.path).length)?i=o:a.startsWith(n+"/")&&(!s||a.length<(0,Qh.resolve)(s.path).length)&&(s=o)}return r||i||s||null}function CG({sessionId:t,name:e,autoNamed:n=!0,cwd:r=null,workspacePath:i=null,shellId:s=null,shellLabel:o=null,agent:a=null}){let c=Mhe([...Mp.values()],i||r)||null;return Tr.set(t,{daemon:!0,name:e,autoNamed:n,createdAt:Date.now(),cwd:r||c?.path||null,workspacePath:c?.path||null,shellId:s,shellLabel:o,agent:a}),c&&(Op[t]=c.id,Oy(Mp,Op,JI)),ii(Tr),Ge(null,"sessionsChanged"),{success:!0,sessionId:t,workspacePath:c?.path||null}}async function RG(){let t=ese();if(!t){let r=TC(),i=Zie();t=cse(i,r);let s=new Map(t.workspaces.map(c=>[c.id,c]));if(Oy(s,t.sessionWorkspaces,t.sessionOrder),$x=t.sessionPaths||{},Object.keys($x).length){for(let[c,l]of Object.entries($x))r[c]&&(r[c].workspacePath=l);Qie(r)}let o=(i.groups||[]).filter(c=>t.workspaces.some(l=>l.id===c.id)).length,a=(i.groups||[]).length-o;(t.workspaces.length||a)&&console.log(AG(`\u{1F4C1} Migrated ${t.workspaces.length} workspace(s) from terminal groups`+(a?`, dropped ${a} empty group(s)`:"")))}for(let r of t.workspaces)Mp.set(r.id,r);Object.assign(Op,t.sessionWorkspaces),JI.push(...t.sessionOrder),Die(()=>ii(Tr)),Gie(F5e);try{She()}catch{}try{Ehe()}catch{}bhe().catch(()=>{});try{nhe()}catch{}if(TG==="daemon")if(!await VF())console.error("\u274C Failed to connect to PTY daemon, falling back to buffer mode");else{await Rhe(),SG(),Ihe().catch(()=>{}),yu("connected",()=>{Rhe().then(SG).then(Ihe).catch(()=>{})});return}console.log("\u{1F4E6} Buffer persistence mode - scrollback enabled");let e=Jie(),n=TC();for(let r of e){let i=n[r]||{};Tr.set(r,{pty:null,name:i.name||`Terminal ${Tr.size+1}`,autoNamed:i.autoNamed!==!1,createdAt:i.createdAt||Date.now(),cwd:i.cwd,workspacePath:i.workspacePath??$x[r]??null,shellId:i.shellId,buffer:[],needsRestore:!0}),oB(r,i),console.log(`\u{1F504} Found saved session: ${r}`)}e.length>0&&console.log(`\u2705 Found ${e.length} saved session(s)`),SG()}function Np(t,e){Pp=t,TG==="daemon"&&(yu("output",({sessionId:i,enc:s,data:o,replay:a})=>{a!==!0&&(wC(i),vC(i));let c=s==="b64"?Buffer.from(o,"base64"):Buffer.from(o||"");c.length>Ja&&(YI++,(YI===1||YI%500===0)&&Phe.info(`[slice] chunk ${c.length>>10}KB \u2192 ${Math.ceil(c.length/Ja)} events (total sliced: ${YI})`)),s==="b64"&&D5e(i,c.toString("utf8"));for(let l=0;l<c.length||l===0;l+=Ja){let u=c.subarray(l,l+Ja),d=a===!0?Cx(i):rde(i);a!==!0&&ide(i,d,u),Ge(t,"output",{sessionId:i,enc:"bin",data:u,replay:a===!0,seq:d})}}),Vie(i=>Ge(t,"statusState",Zc())),Wie(()=>Ge(t,"statusState",Zc())),yu("cwdChange",({sessionId:i,cwd:s})=>{let o=Tr.get(i);o&&s&&o.cwd!==s&&(o.cwd=s,ii(Tr)),Ge(t,"cwdChange",{sessionId:i,cwd:s})}),yu("processChange",({sessionId:i,process:s})=>{let o=Uie(i,s);if(o?.state==="pendingShell"){setTimeout(()=>N5e(t,i),O5e);return}o?.state==="idle"&&(Ge(t,"statusChange",{sessionId:i,state:"idle",tool:null,conversationId:null}),Ge(t,"statusState",Zc()))}),yu("sessionClosed",i=>{Tr.delete(i),sv(i),ky(i),XI.delete(i);let s=Gx.get(i);s&&(clearTimeout(s),Gx.delete(i)),lB(i),Ge(t,"sessionClosed",i),Ge(t,"notificationCleared",i)}));let n=()=>({version:P5e,remoteAvailable:ch(),remoteStatus:oF(),mobileAvailable:oie(),daemonMode:TG==="daemon"&&gn(),platform:process.platform,updateAvailable:Ww(),canSelfUpdate:!0,caps:{joinSessionSize:!0,artifact:!0},artifactEnabled:qx(),voiceConfig:hs().voiceConfig||null,mcpClients:bv,...lie()}),r=()=>{let i=n();for(let s of t.sockets.sockets.values())s.data?.approved&&s.emit("serverInfo",i);for(let s of iy()){let o=s._host;if(!(!o?.defersWsAdapter||!o.data?.approved))try{s.emit("serverInfo",i)}catch{}}};cF(r),Np._buildServerInfo=n,Np._emitServerInfo=r}function QI(){Np._emitServerInfo?.()}function Hx(t,e,n,r=null){if(!Pp)return null;if(e==="done")return _C(t,()=>{let a=r?.sessionId||r?.threadId||Mi(t)?.id||null,c=fp(t),l=Th({type:e,sessionId:t,tool:n});!l||l===c||(Ge(Pp,"statusChange",{sessionId:t,state:e,tool:n,conversationId:a}),Ge(Pp,"statusState",Zc()))}),fp(t);let i=r?.sessionId||r?.threadId||Mi(t)?.id||null,s=fp(t),o=Th({type:e,sessionId:t,tool:n});return!o||o===s||(Ge(Pp,"statusChange",{sessionId:t,state:e,tool:n,conversationId:i}),Ge(Pp,"statusState",Zc())),o}function IG(t){Ohe=t}async function kG(t,e,n){uie(),Ohe?.(),t.emit("srvCaps",{env2:1,seqCtl:1,inputAck:1,promptDedupe:1}),t.emit("serverInfo",Np._buildServerInfo?.()),lde(t,e,Tr,Mp,Op,JI),gde(t,Tr),ahe(t,e),HA()&&await Ine(t,n).catch(r=>{console.error("\u274C Failed to setup remote handlers:",r.message)}),aie(t),t.on("disconnect",()=>{Dfe(t.id),die()})}var Qh,khe,Phe,z1t,AG,TG,P5e,Ahe,M5e,O5e,XI,Tr,Mp,Op,JI,$x,Che,Gx,Pp,YI,Ohe,aa=ne(()=>{J1();Qh=require("path"),khe=require("url");ri();jA();cie();ys();rC();AC();CC();sI();yde();che();The();HI();oh();LI();bG();xs();Jc();mp();Tu();m$();yi();v$();mu();$e();Phe=Ee("terminal"),z1t=(0,Qh.dirname)((0,khe.fileURLToPath)(__importMetaUrl)),AG=tw.rgb(230,138,110),TG="daemon",P5e="3.0.51",Ahe=/\x1b\](?:0|2);([^\x07\x1b]*)(?:\x07|\x1b\\)/g,M5e=256,O5e=1500,XI=new Map;Tr=new Map,Mp=new Map,Op={},JI=[],$x={},Che=null;Gx=new Map,Pp=null;YI=0;Ohe=null});var jx=H((V1t,Uhe)=>{"use strict";var B5e=require("path"),hl="\\\\/",Nhe=`[^${hl}]`,q5e=0,zu="\\.",$5e="\\+",G5e="\\?",ZI="\\/",H5e="(?=.)",Dhe="[^/]",PG=`(?:${ZI}|$)`,Lhe=`(?:^|${ZI})`,MG=`${zu}{1,2}${PG}`,j5e=`(?!${zu})`,W5e=`(?!${Lhe}${MG})`,z5e=`(?!${zu}{0,1}${PG})`,V5e=`(?!${MG})`,K5e=`[^.${ZI}]`,Y5e=`${Dhe}*?`,Fhe={DOT_LITERAL:zu,PLUS_LITERAL:$5e,QMARK_LITERAL:G5e,SLASH_LITERAL:ZI,ONE_CHAR:H5e,QMARK:Dhe,END_ANCHOR:PG,DOTS_SLASH:MG,NO_DOT:j5e,NO_DOTS:W5e,NO_DOT_SLASH:z5e,NO_DOTS_SLASH:V5e,QMARK_NO_DOT:K5e,STAR:Y5e,START_ANCHOR:Lhe},X5e={...Fhe,SLASH_LITERAL:`[${hl}]`,QMARK:Nhe,STAR:`${Nhe}*?`,DOTS_SLASH:`${zu}{1,2}(?:[${hl}]|$)`,NO_DOT:`(?!${zu})`,NO_DOTS:`(?!(?:^|[${hl}])${zu}{1,2}(?:[${hl}]|$))`,NO_DOT_SLASH:`(?!${zu}{0,1}(?:[${hl}]|$))`,NO_DOTS_SLASH:`(?!${zu}{1,2}(?:[${hl}]|$))`,QMARK_NO_DOT:`[^.${hl}]`,START_ANCHOR:`(?:^|[${hl}])`,END_ANCHOR:`(?:[${hl}]|$)`},J5e={__proto__:null,alnum:"a-zA-Z0-9",alpha:"a-zA-Z",ascii:"\\x00-\\x7F",blank:" \\t",cntrl:"\\x00-\\x1F\\x7F",digit:"0-9",graph:"\\x21-\\x7E",lower:"a-z",print:"\\x20-\\x7E ",punct:"\\-!\"#$%&'()\\*+,./:;<=>?@[\\]^_`{|}~",space:" \\t\\r\\n\\v\\f",upper:"A-Z",word:"A-Za-z0-9_",xdigit:"A-Fa-f0-9"};Uhe.exports={DEFAULT_MAX_EXTGLOB_RECURSION:q5e,MAX_LENGTH:1024*64,POSIX_REGEX_SOURCE:J5e,REGEX_BACKSLASH:/\\(?![*+?^${}(|)[\]])/g,REGEX_NON_SPECIAL_CHARS:/^[^@![\].,$*+?^{}()|\\/]+/,REGEX_SPECIAL_CHARS:/[-*+?.^${}(|)[\]]/,REGEX_SPECIAL_CHARS_BACKREF:/(\\?)((\W)(\3*))/g,REGEX_SPECIAL_CHARS_GLOBAL:/([-*+?.^${}(|)[\]])/g,REGEX_REMOVE_BACKSLASH:/(?:\[.*?[^\\]\]|\\(?=.))/g,REPLACEMENTS:{__proto__:null,"***":"*","**/**":"**","**/**/**":"**"},CHAR_0:48,CHAR_9:57,CHAR_UPPERCASE_A:65,CHAR_LOWERCASE_A:97,CHAR_UPPERCASE_Z:90,CHAR_LOWERCASE_Z:122,CHAR_LEFT_PARENTHESES:40,CHAR_RIGHT_PARENTHESES:41,CHAR_ASTERISK:42,CHAR_AMPERSAND:38,CHAR_AT:64,CHAR_BACKWARD_SLASH:92,CHAR_CARRIAGE_RETURN:13,CHAR_CIRCUMFLEX_ACCENT:94,CHAR_COLON:58,CHAR_COMMA:44,CHAR_DOT:46,CHAR_DOUBLE_QUOTE:34,CHAR_EQUAL:61,CHAR_EXCLAMATION_MARK:33,CHAR_FORM_FEED:12,CHAR_FORWARD_SLASH:47,CHAR_GRAVE_ACCENT:96,CHAR_HASH:35,CHAR_HYPHEN_MINUS:45,CHAR_LEFT_ANGLE_BRACKET:60,CHAR_LEFT_CURLY_BRACE:123,CHAR_LEFT_SQUARE_BRACKET:91,CHAR_LINE_FEED:10,CHAR_NO_BREAK_SPACE:160,CHAR_PERCENT:37,CHAR_PLUS:43,CHAR_QUESTION_MARK:63,CHAR_RIGHT_ANGLE_BRACKET:62,CHAR_RIGHT_CURLY_BRACE:125,CHAR_RIGHT_SQUARE_BRACKET:93,CHAR_SEMICOLON:59,CHAR_SINGLE_QUOTE:39,CHAR_SPACE:32,CHAR_TAB:9,CHAR_UNDERSCORE:95,CHAR_VERTICAL_LINE:124,CHAR_ZERO_WIDTH_NOBREAK_SPACE:65279,SEP:B5e.sep,extglobChars(t){return{"!":{type:"negate",open:"(?:(?!(?:",close:`))${t.STAR})`},"?":{type:"qmark",open:"(?:",close:")?"},"+":{type:"plus",open:"(?:",close:")+"},"*":{type:"star",open:"(?:",close:")*"},"@":{type:"at",open:"(?:",close:")"}}},globChars(t){return t===!0?X5e:Fhe}}});var ek=H(Rs=>{"use strict";var Q5e=require("path"),Z5e=process.platform==="win32",{REGEX_BACKSLASH:eYe,REGEX_REMOVE_BACKSLASH:tYe,REGEX_SPECIAL_CHARS:nYe,REGEX_SPECIAL_CHARS_GLOBAL:rYe}=jx();Rs.isObject=t=>t!==null&&typeof t=="object"&&!Array.isArray(t);Rs.hasRegexChars=t=>nYe.test(t);Rs.isRegexChar=t=>t.length===1&&Rs.hasRegexChars(t);Rs.escapeRegex=t=>t.replace(rYe,"\\$1");Rs.toPosixSlashes=t=>t.replace(eYe,"/");Rs.removeBackslashes=t=>t.replace(tYe,e=>e==="\\"?"":e);Rs.supportsLookbehinds=()=>{let t=process.version.slice(1).split(".").map(Number);return t.length===3&&t[0]>=9||t[0]===8&&t[1]>=10};Rs.isWindows=t=>t&&typeof t.windows=="boolean"?t.windows:Z5e===!0||Q5e.sep==="\\";Rs.escapeLast=(t,e,n)=>{let r=t.lastIndexOf(e,n);return r===-1?t:t[r-1]==="\\"?Rs.escapeLast(t,e,r-1):`${t.slice(0,r)}\\${t.slice(r)}`};Rs.removePrefix=(t,e={})=>{let n=t;return n.startsWith("./")&&(n=n.slice(2),e.prefix="./"),n};Rs.wrapOutput=(t,e={},n={})=>{let r=n.contains?"":"^",i=n.contains?"":"$",s=`${r}(?:${t})${i}`;return e.negated===!0&&(s=`(?:^(?!${s}).*$)`),s}});var zhe=H((Y1t,Whe)=>{"use strict";var Bhe=ek(),{CHAR_ASTERISK:OG,CHAR_AT:iYe,CHAR_BACKWARD_SLASH:Wx,CHAR_COMMA:sYe,CHAR_DOT:NG,CHAR_EXCLAMATION_MARK:DG,CHAR_FORWARD_SLASH:jhe,CHAR_LEFT_CURLY_BRACE:LG,CHAR_LEFT_PARENTHESES:FG,CHAR_LEFT_SQUARE_BRACKET:oYe,CHAR_PLUS:aYe,CHAR_QUESTION_MARK:qhe,CHAR_RIGHT_CURLY_BRACE:cYe,CHAR_RIGHT_PARENTHESES:$he,CHAR_RIGHT_SQUARE_BRACKET:lYe}=jx(),Ghe=t=>t===jhe||t===Wx,Hhe=t=>{t.isPrefix!==!0&&(t.depth=t.isGlobstar?1/0:1)},uYe=(t,e)=>{let n=e||{},r=t.length-1,i=n.parts===!0||n.scanToEnd===!0,s=[],o=[],a=[],c=t,l=-1,u=0,d=0,p=!1,m=!1,h=!1,y=!1,v=!1,E=!1,A=!1,b=!1,S=!1,I=!1,F=0,D,B,M={value:"",depth:0,isGlob:!1},P=()=>l>=r,x=()=>c.charCodeAt(l+1),R=()=>(D=B,c.charCodeAt(++l));for(;l<r;){B=R();let Y;if(B===Wx){A=M.backslashes=!0,B=R(),B===LG&&(E=!0);continue}if(E===!0||B===LG){for(F++;P()!==!0&&(B=R());){if(B===Wx){A=M.backslashes=!0,R();continue}if(B===LG){F++;continue}if(E!==!0&&B===NG&&(B=R())===NG){if(p=M.isBrace=!0,h=M.isGlob=!0,I=!0,i===!0)continue;break}if(E!==!0&&B===sYe){if(p=M.isBrace=!0,h=M.isGlob=!0,I=!0,i===!0)continue;break}if(B===cYe&&(F--,F===0)){E=!1,p=M.isBrace=!0,I=!0;break}}if(i===!0)continue;break}if(B===jhe){if(s.push(l),o.push(M),M={value:"",depth:0,isGlob:!1},I===!0)continue;if(D===NG&&l===u+1){u+=2;continue}d=l+1;continue}if(n.noext!==!0&&(B===aYe||B===iYe||B===OG||B===qhe||B===DG)===!0&&x()===FG){if(h=M.isGlob=!0,y=M.isExtglob=!0,I=!0,B===DG&&l===u&&(S=!0),i===!0){for(;P()!==!0&&(B=R());){if(B===Wx){A=M.backslashes=!0,B=R();continue}if(B===$he){h=M.isGlob=!0,I=!0;break}}continue}break}if(B===OG){if(D===OG&&(v=M.isGlobstar=!0),h=M.isGlob=!0,I=!0,i===!0)continue;break}if(B===qhe){if(h=M.isGlob=!0,I=!0,i===!0)continue;break}if(B===oYe){for(;P()!==!0&&(Y=R());){if(Y===Wx){A=M.backslashes=!0,R();continue}if(Y===lYe){m=M.isBracket=!0,h=M.isGlob=!0,I=!0;break}}if(i===!0)continue;break}if(n.nonegate!==!0&&B===DG&&l===u){b=M.negated=!0,u++;continue}if(n.noparen!==!0&&B===FG){if(h=M.isGlob=!0,i===!0){for(;P()!==!0&&(B=R());){if(B===FG){A=M.backslashes=!0,B=R();continue}if(B===$he){I=!0;break}}continue}break}if(h===!0){if(I=!0,i===!0)continue;break}}n.noext===!0&&(y=!1,h=!1);let N=c,k="",O="";u>0&&(k=c.slice(0,u),c=c.slice(u),d-=u),N&&h===!0&&d>0?(N=c.slice(0,d),O=c.slice(d)):h===!0?(N="",O=c):N=c,N&&N!==""&&N!=="/"&&N!==c&&Ghe(N.charCodeAt(N.length-1))&&(N=N.slice(0,-1)),n.unescape===!0&&(O&&(O=Bhe.removeBackslashes(O)),N&&A===!0&&(N=Bhe.removeBackslashes(N)));let $={prefix:k,input:t,start:u,base:N,glob:O,isBrace:p,isBracket:m,isGlob:h,isExtglob:y,isGlobstar:v,negated:b,negatedExtglob:S};if(n.tokens===!0&&($.maxDepth=0,Ghe(B)||o.push(M),$.tokens=o),n.parts===!0||n.tokens===!0){let Y;for(let L=0;L<s.length;L++){let C=Y?Y+1:u,G=s[L],le=t.slice(C,G);n.tokens&&(L===0&&u!==0?(o[L].isPrefix=!0,o[L].value=k):o[L].value=le,Hhe(o[L]),$.maxDepth+=o[L].depth),(L!==0||le!=="")&&a.push(le),Y=G}if(Y&&Y+1<t.length){let L=t.slice(Y+1);a.push(L),n.tokens&&(o[o.length-1].value=L,Hhe(o[o.length-1]),$.maxDepth+=o[o.length-1].depth)}$.slashes=s,$.parts=a}return $};Whe.exports=uYe});var Jhe=H((X1t,Xhe)=>{"use strict";var zx=jx(),Di=ek(),{MAX_LENGTH:tk,POSIX_REGEX_SOURCE:dYe,REGEX_NON_SPECIAL_CHARS:pYe,REGEX_SPECIAL_CHARS_BACKREF:fYe,REPLACEMENTS:Vhe}=zx,hYe=(t,e)=>{if(typeof e.expandRange=="function")return e.expandRange(...t,e);t.sort();let n=`[${t.join("-")}]`;try{new RegExp(n)}catch{return t.map(i=>Di.escapeRegex(i)).join("..")}return n},Sv=(t,e)=>`Missing ${t}: "${e}" - use "\\\\${e}" to match literal characters`,Khe=t=>{let e=[],n=0,r=0,i=0,s="",o=!1;for(let a of t){if(o===!0){s+=a,o=!1;continue}if(a==="\\"){s+=a,o=!0;continue}if(a==='"'){i=i===1?0:1,s+=a;continue}if(i===0){if(a==="[")n++;else if(a==="]"&&n>0)n--;else if(n===0){if(a==="(")r++;else if(a===")"&&r>0)r--;else if(a==="|"&&r===0){e.push(s),s="";continue}}}s+=a}return e.push(s),e},mYe=t=>{let e=!1;for(let n of t){if(e===!0){e=!1;continue}if(n==="\\"){e=!0;continue}if(/[?*+@!()[\]{}]/.test(n))return!1}return!0},Yhe=t=>{let e=t.trim(),n=!0;for(;n===!0;)n=!1,/^@\([^\\()[\]{}|]+\)$/.test(e)&&(e=e.slice(2,-1),n=!0);if(mYe(e))return e.replace(/\\(.)/g,"$1")},gYe=t=>{let e=t.map(Yhe).filter(Boolean);for(let n=0;n<e.length;n++)for(let r=n+1;r<e.length;r++){let i=e[n],s=e[r],o=i[0];if(!(!o||i!==o.repeat(i.length)||s!==o.repeat(s.length))&&(i===s||i.startsWith(s)||s.startsWith(i)))return!0}return!1},UG=(t,e=!0)=>{if(t[0]!=="+"&&t[0]!=="*"||t[1]!=="(")return;let n=0,r=0,i=0,s=!1;for(let o=1;o<t.length;o++){let a=t[o];if(s===!0){s=!1;continue}if(a==="\\"){s=!0;continue}if(a==='"'){i=i===1?0:1;continue}if(i!==1){if(a==="["){n++;continue}if(a==="]"&&n>0){n--;continue}if(!(n>0)){if(a==="("){r++;continue}if(a===")"&&(r--,r===0))return e===!0&&o!==t.length-1?void 0:{type:t[0],body:t.slice(2,o),end:o}}}}},yYe=t=>{let e=0,n=[];for(;e<t.length;){let i=UG(t.slice(e),!1);if(!i||i.type!=="*")return;let s=Khe(i.body).map(a=>a.trim());if(s.length!==1)return;let o=Yhe(s[0]);if(!o||o.length!==1)return;n.push(o),e+=i.end+1}return n.length<1?void 0:`${n.length===1?Di.escapeRegex(n[0]):`[${n.map(i=>Di.escapeRegex(i)).join("")}]`}*`},vYe=t=>{let e=0,n=t.trim(),r=UG(n);for(;r;)e++,n=r.body.trim(),r=UG(n);return e},_Ye=(t,e)=>{if(e.maxExtglobRecursion===!1)return{risky:!1};let n=typeof e.maxExtglobRecursion=="number"?e.maxExtglobRecursion:zx.DEFAULT_MAX_EXTGLOB_RECURSION,r=Khe(t).map(i=>i.trim());if(r.length>1&&(r.some(i=>i==="")||r.some(i=>/^[*?]+$/.test(i))||gYe(r)))return{risky:!0};for(let i of r){let s=yYe(i);if(s)return{risky:!0,safeOutput:s};if(vYe(i)>n)return{risky:!0}}return{risky:!1}},BG=(t,e)=>{if(typeof t!="string")throw new TypeError("Expected a string");t=Vhe[t]||t;let n={...e},r=typeof n.maxLength=="number"?Math.min(tk,n.maxLength):tk,i=t.length;if(i>r)throw new SyntaxError(`Input length: ${i}, exceeds maximum allowed length: ${r}`);let s={type:"bos",value:"",output:n.prepend||""},o=[s],a=n.capture?"":"?:",c=Di.isWindows(e),l=zx.globChars(c),u=zx.extglobChars(l),{DOT_LITERAL:d,PLUS_LITERAL:p,SLASH_LITERAL:m,ONE_CHAR:h,DOTS_SLASH:y,NO_DOT:v,NO_DOT_SLASH:E,NO_DOTS_SLASH:A,QMARK:b,QMARK_NO_DOT:S,STAR:I,START_ANCHOR:F}=l,D=q=>`(${a}(?:(?!${F}${q.dot?y:d}).)*?)`,B=n.dot?"":v,M=n.dot?b:S,P=n.bash===!0?D(n):I;n.capture&&(P=`(${P})`),typeof n.noext=="boolean"&&(n.noextglob=n.noext);let x={input:t,index:-1,start:0,dot:n.dot===!0,consumed:"",output:"",prefix:"",backtrack:!1,negated:!1,brackets:0,braces:0,parens:0,quotes:0,globstar:!1,tokens:o};t=Di.removePrefix(t,x),i=t.length;let R=[],N=[],k=[],O=s,$,Y=()=>x.index===i-1,L=x.peek=(q=1)=>t[x.index+q],C=x.advance=()=>t[++x.index]||"",G=()=>t.slice(x.index+1),le=(q="",V=0)=>{x.consumed+=q,x.index+=V},ce=q=>{x.output+=q.output!=null?q.output:q.value,le(q.value)},J=()=>{let q=1;for(;L()==="!"&&(L(2)!=="("||L(3)==="?");)C(),x.start++,q++;return q%2===0?!1:(x.negated=!0,x.start++,!0)},fe=q=>{x[q]++,k.push(q)},we=q=>{x[q]--,k.pop()},xe=q=>{if(O.type==="globstar"){let V=x.braces>0&&(q.type==="comma"||q.type==="brace"),W=q.extglob===!0||R.length&&(q.type==="pipe"||q.type==="paren");q.type!=="slash"&&q.type!=="paren"&&!V&&!W&&(x.output=x.output.slice(0,-O.output.length),O.type="star",O.value="*",O.output=P,x.output+=O.output)}if(R.length&&q.type!=="paren"&&(R[R.length-1].inner+=q.value),(q.value||q.output)&&ce(q),O&&O.type==="text"&&q.type==="text"){O.value+=q.value,O.output=(O.output||"")+q.value;return}q.prev=O,o.push(q),O=q},Ue=(q,V)=>{let W={...u[V],conditions:1,inner:""};W.prev=O,W.parens=x.parens,W.output=x.output,W.startIndex=x.index,W.tokensIndex=o.length;let Z=(n.capture?"(":"")+W.open;fe("parens"),xe({type:q,value:V,output:x.output?"":h}),xe({type:"paren",extglob:!0,value:C(),output:Z}),R.push(W)},ke=q=>{let V=t.slice(q.startIndex,x.index+1),W=t.slice(q.startIndex+2,x.index),Z=_Ye(W,n);if((q.type==="plus"||q.type==="star")&&Z.risky){let oe=Z.safeOutput?(q.output?"":h)+(n.capture?`(${Z.safeOutput})`:Z.safeOutput):void 0,ie=o[q.tokensIndex];ie.type="text",ie.value=V,ie.output=oe||Di.escapeRegex(V);for(let se=q.tokensIndex+1;se<o.length;se++)o[se].value="",o[se].output="",delete o[se].suffix;x.output=q.output+ie.output,x.backtrack=!0,xe({type:"paren",extglob:!0,value:$,output:""}),we("parens");return}let ee=q.close+(n.capture?")":""),te;if(q.type==="negate"){let oe=P;if(q.inner&&q.inner.length>1&&q.inner.includes("/")&&(oe=D(n)),(oe!==P||Y()||/^\)+$/.test(G()))&&(ee=q.close=`)$))${oe}`),q.inner.includes("*")&&(te=G())&&/^\.[^\\/.]+$/.test(te)){let ie=BG(te,{...e,fastpaths:!1}).output;ee=q.close=`)${ie})${oe})`}q.prev.type==="bos"&&(x.negatedExtglob=!0)}xe({type:"paren",extglob:!0,value:$,output:ee}),we("parens")};if(n.fastpaths!==!1&&!/(^[*!]|[/()[\]{}"])/.test(t)){let q=!1,V=t.replace(fYe,(W,Z,ee,te,oe,ie)=>te==="\\"?(q=!0,W):te==="?"?Z?Z+te+(oe?b.repeat(oe.length):""):ie===0?M+(oe?b.repeat(oe.length):""):b.repeat(ee.length):te==="."?d.repeat(ee.length):te==="*"?Z?Z+te+(oe?P:""):P:Z?W:`\\${W}`);return q===!0&&(n.unescape===!0?V=V.replace(/\\/g,""):V=V.replace(/\\+/g,W=>W.length%2===0?"\\\\":W?"\\":"")),V===t&&n.contains===!0?(x.output=t,x):(x.output=Di.wrapOutput(V,x,e),x)}for(;!Y();){if($=C(),$==="\0")continue;if($==="\\"){let W=L();if(W==="/"&&n.bash!==!0||W==="."||W===";")continue;if(!W){$+="\\",xe({type:"text",value:$});continue}let Z=/^\\+/.exec(G()),ee=0;if(Z&&Z[0].length>2&&(ee=Z[0].length,x.index+=ee,ee%2!==0&&($+="\\")),n.unescape===!0?$=C():$+=C(),x.brackets===0){xe({type:"text",value:$});continue}}if(x.brackets>0&&($!=="]"||O.value==="["||O.value==="[^")){if(n.posix!==!1&&$===":"){let W=O.value.slice(1);if(W.includes("[")&&(O.posix=!0,W.includes(":"))){let Z=O.value.lastIndexOf("["),ee=O.value.slice(0,Z),te=O.value.slice(Z+2),oe=dYe[te];if(oe){O.value=ee+oe,x.backtrack=!0,C(),!s.output&&o.indexOf(O)===1&&(s.output=h);continue}}}($==="["&&L()!==":"||$==="-"&&L()==="]")&&($=`\\${$}`),$==="]"&&(O.value==="["||O.value==="[^")&&($=`\\${$}`),n.posix===!0&&$==="!"&&O.value==="["&&($="^"),O.value+=$,ce({value:$});continue}if(x.quotes===1&&$!=='"'){$=Di.escapeRegex($),O.value+=$,ce({value:$});continue}if($==='"'){x.quotes=x.quotes===1?0:1,n.keepQuotes===!0&&xe({type:"text",value:$});continue}if($==="("){fe("parens"),xe({type:"paren",value:$});continue}if($===")"){if(x.parens===0&&n.strictBrackets===!0)throw new SyntaxError(Sv("opening","("));let W=R[R.length-1];if(W&&x.parens===W.parens+1){ke(R.pop());continue}xe({type:"paren",value:$,output:x.parens?")":"\\)"}),we("parens");continue}if($==="["){if(n.nobracket===!0||!G().includes("]")){if(n.nobracket!==!0&&n.strictBrackets===!0)throw new SyntaxError(Sv("closing","]"));$=`\\${$}`}else fe("brackets");xe({type:"bracket",value:$});continue}if($==="]"){if(n.nobracket===!0||O&&O.type==="bracket"&&O.value.length===1){xe({type:"text",value:$,output:`\\${$}`});continue}if(x.brackets===0){if(n.strictBrackets===!0)throw new SyntaxError(Sv("opening","["));xe({type:"text",value:$,output:`\\${$}`});continue}we("brackets");let W=O.value.slice(1);if(O.posix!==!0&&W[0]==="^"&&!W.includes("/")&&($=`/${$}`),O.value+=$,ce({value:$}),n.literalBrackets===!1||Di.hasRegexChars(W))continue;let Z=Di.escapeRegex(O.value);if(x.output=x.output.slice(0,-O.value.length),n.literalBrackets===!0){x.output+=Z,O.value=Z;continue}O.value=`(${a}${Z}|${O.value})`,x.output+=O.value;continue}if($==="{"&&n.nobrace!==!0){fe("braces");let W={type:"brace",value:$,output:"(",outputIndex:x.output.length,tokensIndex:x.tokens.length};N.push(W),xe(W);continue}if($==="}"){let W=N[N.length-1];if(n.nobrace===!0||!W){xe({type:"text",value:$,output:$});continue}let Z=")";if(W.dots===!0){let ee=o.slice(),te=[];for(let oe=ee.length-1;oe>=0&&(o.pop(),ee[oe].type!=="brace");oe--)ee[oe].type!=="dots"&&te.unshift(ee[oe].value);Z=hYe(te,n),x.backtrack=!0}if(W.comma!==!0&&W.dots!==!0){let ee=x.output.slice(0,W.outputIndex),te=x.tokens.slice(W.tokensIndex);W.value=W.output="\\{",$=Z="\\}",x.output=ee;for(let oe of te)x.output+=oe.output||oe.value}xe({type:"brace",value:$,output:Z}),we("braces"),N.pop();continue}if($==="|"){R.length>0&&R[R.length-1].conditions++,xe({type:"text",value:$});continue}if($===","){let W=$,Z=N[N.length-1];Z&&k[k.length-1]==="braces"&&(Z.comma=!0,W="|"),xe({type:"comma",value:$,output:W});continue}if($==="/"){if(O.type==="dot"&&x.index===x.start+1){x.start=x.index+1,x.consumed="",x.output="",o.pop(),O=s;continue}xe({type:"slash",value:$,output:m});continue}if($==="."){if(x.braces>0&&O.type==="dot"){O.value==="."&&(O.output=d);let W=N[N.length-1];O.type="dots",O.output+=$,O.value+=$,W.dots=!0;continue}if(x.braces+x.parens===0&&O.type!=="bos"&&O.type!=="slash"){xe({type:"text",value:$,output:d});continue}xe({type:"dot",value:$,output:d});continue}if($==="?"){if(!(O&&O.value==="(")&&n.noextglob!==!0&&L()==="("&&L(2)!=="?"){Ue("qmark",$);continue}if(O&&O.type==="paren"){let Z=L(),ee=$;if(Z==="<"&&!Di.supportsLookbehinds())throw new Error("Node.js v10 or higher is required for regex lookbehinds");(O.value==="("&&!/[!=<:]/.test(Z)||Z==="<"&&!/<([!=]|\w+>)/.test(G()))&&(ee=`\\${$}`),xe({type:"text",value:$,output:ee});continue}if(n.dot!==!0&&(O.type==="slash"||O.type==="bos")){xe({type:"qmark",value:$,output:S});continue}xe({type:"qmark",value:$,output:b});continue}if($==="!"){if(n.noextglob!==!0&&L()==="("&&(L(2)!=="?"||!/[!=<:]/.test(L(3)))){Ue("negate",$);continue}if(n.nonegate!==!0&&x.index===0){J();continue}}if($==="+"){if(n.noextglob!==!0&&L()==="("&&L(2)!=="?"){Ue("plus",$);continue}if(O&&O.value==="("||n.regex===!1){xe({type:"plus",value:$,output:p});continue}if(O&&(O.type==="bracket"||O.type==="paren"||O.type==="brace")||x.parens>0){xe({type:"plus",value:$});continue}xe({type:"plus",value:p});continue}if($==="@"){if(n.noextglob!==!0&&L()==="("&&L(2)!=="?"){xe({type:"at",extglob:!0,value:$,output:""});continue}xe({type:"text",value:$});continue}if($!=="*"){($==="$"||$==="^")&&($=`\\${$}`);let W=pYe.exec(G());W&&($+=W[0],x.index+=W[0].length),xe({type:"text",value:$});continue}if(O&&(O.type==="globstar"||O.star===!0)){O.type="star",O.star=!0,O.value+=$,O.output=P,x.backtrack=!0,x.globstar=!0,le($);continue}let q=G();if(n.noextglob!==!0&&/^\([^?]/.test(q)){Ue("star",$);continue}if(O.type==="star"){if(n.noglobstar===!0){le($);continue}let W=O.prev,Z=W.prev,ee=W.type==="slash"||W.type==="bos",te=Z&&(Z.type==="star"||Z.type==="globstar");if(n.bash===!0&&(!ee||q[0]&&q[0]!=="/")){xe({type:"star",value:$,output:""});continue}let oe=x.braces>0&&(W.type==="comma"||W.type==="brace"),ie=R.length&&(W.type==="pipe"||W.type==="paren");if(!ee&&W.type!=="paren"&&!oe&&!ie){xe({type:"star",value:$,output:""});continue}for(;q.slice(0,3)==="/**";){let se=t[x.index+4];if(se&&se!=="/")break;q=q.slice(3),le("/**",3)}if(W.type==="bos"&&Y()){O.type="globstar",O.value+=$,O.output=D(n),x.output=O.output,x.globstar=!0,le($);continue}if(W.type==="slash"&&W.prev.type!=="bos"&&!te&&Y()){x.output=x.output.slice(0,-(W.output+O.output).length),W.output=`(?:${W.output}`,O.type="globstar",O.output=D(n)+(n.strictSlashes?")":"|$)"),O.value+=$,x.globstar=!0,x.output+=W.output+O.output,le($);continue}if(W.type==="slash"&&W.prev.type!=="bos"&&q[0]==="/"){let se=q[1]!==void 0?"|$":"";x.output=x.output.slice(0,-(W.output+O.output).length),W.output=`(?:${W.output}`,O.type="globstar",O.output=`${D(n)}${m}|${m}${se})`,O.value+=$,x.output+=W.output+O.output,x.globstar=!0,le($+C()),xe({type:"slash",value:"/",output:""});continue}if(W.type==="bos"&&q[0]==="/"){O.type="globstar",O.value+=$,O.output=`(?:^|${m}|${D(n)}${m})`,x.output=O.output,x.globstar=!0,le($+C()),xe({type:"slash",value:"/",output:""});continue}x.output=x.output.slice(0,-O.output.length),O.type="globstar",O.output=D(n),O.value+=$,x.output+=O.output,x.globstar=!0,le($);continue}let V={type:"star",value:$,output:P};if(n.bash===!0){V.output=".*?",(O.type==="bos"||O.type==="slash")&&(V.output=B+V.output),xe(V);continue}if(O&&(O.type==="bracket"||O.type==="paren")&&n.regex===!0){V.output=$,xe(V);continue}(x.index===x.start||O.type==="slash"||O.type==="dot")&&(O.type==="dot"?(x.output+=E,O.output+=E):n.dot===!0?(x.output+=A,O.output+=A):(x.output+=B,O.output+=B),L()!=="*"&&(x.output+=h,O.output+=h)),xe(V)}for(;x.brackets>0;){if(n.strictBrackets===!0)throw new SyntaxError(Sv("closing","]"));x.output=Di.escapeLast(x.output,"["),we("brackets")}for(;x.parens>0;){if(n.strictBrackets===!0)throw new SyntaxError(Sv("closing",")"));x.output=Di.escapeLast(x.output,"("),we("parens")}for(;x.braces>0;){if(n.strictBrackets===!0)throw new SyntaxError(Sv("closing","}"));x.output=Di.escapeLast(x.output,"{"),we("braces")}if(n.strictSlashes!==!0&&(O.type==="star"||O.type==="bracket")&&xe({type:"maybe_slash",value:"",output:`${m}?`}),x.backtrack===!0){x.output="";for(let q of x.tokens)x.output+=q.output!=null?q.output:q.value,q.suffix&&(x.output+=q.suffix)}return x};BG.fastpaths=(t,e)=>{let n={...e},r=typeof n.maxLength=="number"?Math.min(tk,n.maxLength):tk,i=t.length;if(i>r)throw new SyntaxError(`Input length: ${i}, exceeds maximum allowed length: ${r}`);t=Vhe[t]||t;let s=Di.isWindows(e),{DOT_LITERAL:o,SLASH_LITERAL:a,ONE_CHAR:c,DOTS_SLASH:l,NO_DOT:u,NO_DOTS:d,NO_DOTS_SLASH:p,STAR:m,START_ANCHOR:h}=zx.globChars(s),y=n.dot?d:u,v=n.dot?p:u,E=n.capture?"":"?:",A={negated:!1,prefix:""},b=n.bash===!0?".*?":m;n.capture&&(b=`(${b})`);let S=B=>B.noglobstar===!0?b:`(${E}(?:(?!${h}${B.dot?l:o}).)*?)`,I=B=>{switch(B){case"*":return`${y}${c}${b}`;case".*":return`${o}${c}${b}`;case"*.*":return`${y}${b}${o}${c}${b}`;case"*/*":return`${y}${b}${a}${c}${v}${b}`;case"**":return y+S(n);case"**/*":return`(?:${y}${S(n)}${a})?${v}${c}${b}`;case"**/*.*":return`(?:${y}${S(n)}${a})?${v}${b}${o}${c}${b}`;case"**/.*":return`(?:${y}${S(n)}${a})?${o}${c}${b}`;default:{let M=/^(.*?)\.(\w+)$/.exec(B);if(!M)return;let P=I(M[1]);return P?P+o+M[2]:void 0}}},F=Di.removePrefix(t,A),D=I(F);return D&&n.strictSlashes!==!0&&(D+=`${a}?`),D};Xhe.exports=BG});var Zhe=H((J1t,Qhe)=>{"use strict";var wYe=require("path"),xYe=zhe(),qG=Jhe(),$G=ek(),EYe=jx(),bYe=t=>t&&typeof t=="object"&&!Array.isArray(t),Ar=(t,e,n=!1)=>{if(Array.isArray(t)){let u=t.map(p=>Ar(p,e,n));return p=>{for(let m of u){let h=m(p);if(h)return h}return!1}}let r=bYe(t)&&t.tokens&&t.input;if(t===""||typeof t!="string"&&!r)throw new TypeError("Expected pattern to be a non-empty string");let i=e||{},s=$G.isWindows(e),o=r?Ar.compileRe(t,e):Ar.makeRe(t,e,!1,!0),a=o.state;delete o.state;let c=()=>!1;if(i.ignore){let u={...e,ignore:null,onMatch:null,onResult:null};c=Ar(i.ignore,u,n)}let l=(u,d=!1)=>{let{isMatch:p,match:m,output:h}=Ar.test(u,o,e,{glob:t,posix:s}),y={glob:t,state:a,regex:o,posix:s,input:u,output:h,match:m,isMatch:p};return typeof i.onResult=="function"&&i.onResult(y),p===!1?(y.isMatch=!1,d?y:!1):c(u)?(typeof i.onIgnore=="function"&&i.onIgnore(y),y.isMatch=!1,d?y:!1):(typeof i.onMatch=="function"&&i.onMatch(y),d?y:!0)};return n&&(l.state=a),l};Ar.test=(t,e,n,{glob:r,posix:i}={})=>{if(typeof t!="string")throw new TypeError("Expected input to be a string");if(t==="")return{isMatch:!1,output:""};let s=n||{},o=s.format||(i?$G.toPosixSlashes:null),a=t===r,c=a&&o?o(t):t;return a===!1&&(c=o?o(t):t,a=c===r),(a===!1||s.capture===!0)&&(s.matchBase===!0||s.basename===!0?a=Ar.matchBase(t,e,n,i):a=e.exec(c)),{isMatch:!!a,match:a,output:c}};Ar.matchBase=(t,e,n,r=$G.isWindows(n))=>(e instanceof RegExp?e:Ar.makeRe(e,n)).test(wYe.basename(t));Ar.isMatch=(t,e,n)=>Ar(e,n)(t);Ar.parse=(t,e)=>Array.isArray(t)?t.map(n=>Ar.parse(n,e)):qG(t,{...e,fastpaths:!1});Ar.scan=(t,e)=>xYe(t,e);Ar.compileRe=(t,e,n=!1,r=!1)=>{if(n===!0)return t.output;let i=e||{},s=i.contains?"":"^",o=i.contains?"":"$",a=`${s}(?:${t.output})${o}`;t&&t.negated===!0&&(a=`^(?!${a}).*$`);let c=Ar.toRegex(a,e);return r===!0&&(c.state=t),c};Ar.makeRe=(t,e={},n=!1,r=!1)=>{if(!t||typeof t!="string")throw new TypeError("Expected a non-empty string");let i={negated:!1,fastpaths:!0};return e.fastpaths!==!1&&(t[0]==="."||t[0]==="*")&&(i.output=qG.fastpaths(t,e)),i.output||(i=qG(t,e)),Ar.compileRe(i,e,n,r)};Ar.toRegex=(t,e)=>{try{let n=e||{};return new RegExp(t,n.flags||(n.nocase?"i":""))}catch(n){if(e&&e.debug===!0)throw n;return/$^/}};Ar.constants=EYe;Qhe.exports=Ar});var GG=H((Q1t,eme)=>{"use strict";eme.exports=Zhe()});var cme=H((Z1t,ame)=>{"use strict";var Kx=require("fs"),{Readable:SYe}=require("stream"),Vx=require("path"),{promisify:sk}=require("util"),HG=GG(),TYe=sk(Kx.readdir),AYe=sk(Kx.stat),tme=sk(Kx.lstat),CYe=sk(Kx.realpath),RYe="!",sme="READDIRP_RECURSIVE_ERROR",IYe=new Set(["ENOENT","EPERM","EACCES","ELOOP",sme]),jG="files",ome="directories",rk="files_directories",nk="all",nme=[jG,ome,rk,nk],kYe=t=>IYe.has(t.code),[rme,PYe]=process.versions.node.split(".").slice(0,2).map(t=>Number.parseInt(t,10)),MYe=process.platform==="win32"&&(rme>10||rme===10&&PYe>=5),ime=t=>{if(t!==void 0){if(typeof t=="function")return t;if(typeof t=="string"){let e=HG(t.trim());return n=>e(n.basename)}if(Array.isArray(t)){let e=[],n=[];for(let r of t){let i=r.trim();i.charAt(0)===RYe?n.push(HG(i.slice(1))):e.push(HG(i))}return n.length>0?e.length>0?r=>e.some(i=>i(r.basename))&&!n.some(i=>i(r.basename)):r=>!n.some(i=>i(r.basename)):r=>e.some(i=>i(r.basename))}}},ik=class t extends SYe{static get defaultOptions(){return{root:".",fileFilter:e=>!0,directoryFilter:e=>!0,type:jG,lstat:!1,depth:2147483648,alwaysStat:!1}}constructor(e={}){super({objectMode:!0,autoDestroy:!0,highWaterMark:e.highWaterMark||4096});let n={...t.defaultOptions,...e},{root:r,type:i}=n;this._fileFilter=ime(n.fileFilter),this._directoryFilter=ime(n.directoryFilter);let s=n.lstat?tme:AYe;MYe?this._stat=o=>s(o,{bigint:!0}):this._stat=s,this._maxDepth=n.depth,this._wantsDir=[ome,rk,nk].includes(i),this._wantsFile=[jG,rk,nk].includes(i),this._wantsEverything=i===nk,this._root=Vx.resolve(r),this._isDirent="Dirent"in Kx&&!n.alwaysStat,this._statsProp=this._isDirent?"dirent":"stats",this._rdOptions={encoding:"utf8",withFileTypes:this._isDirent},this.parents=[this._exploreDir(r,1)],this.reading=!1,this.parent=void 0}async _read(e){if(!this.reading){this.reading=!0;try{for(;!this.destroyed&&e>0;){let{path:n,depth:r,files:i=[]}=this.parent||{};if(i.length>0){let s=i.splice(0,e).map(o=>this._formatEntry(o,n));for(let o of await Promise.all(s)){if(this.destroyed)return;let a=await this._getEntryType(o);a==="directory"&&this._directoryFilter(o)?(r<=this._maxDepth&&this.parents.push(this._exploreDir(o.fullPath,r+1)),this._wantsDir&&(this.push(o),e--)):(a==="file"||this._includeAsFile(o))&&this._fileFilter(o)&&this._wantsFile&&(this.push(o),e--)}}else{let s=this.parents.pop();if(!s){this.push(null);break}if(this.parent=await s,this.destroyed)return}}}catch(n){this.destroy(n)}finally{this.reading=!1}}}async _exploreDir(e,n){let r;try{r=await TYe(e,this._rdOptions)}catch(i){this._onError(i)}return{files:r,depth:n,path:e}}async _formatEntry(e,n){let r;try{let i=this._isDirent?e.name:e,s=Vx.resolve(Vx.join(n,i));r={path:Vx.relative(this._root,s),fullPath:s,basename:i},r[this._statsProp]=this._isDirent?e:await this._stat(s)}catch(i){this._onError(i)}return r}_onError(e){kYe(e)&&!this.destroyed?this.emit("warn",e):this.destroy(e)}async _getEntryType(e){let n=e&&e[this._statsProp];if(n){if(n.isFile())return"file";if(n.isDirectory())return"directory";if(n&&n.isSymbolicLink()){let r=e.fullPath;try{let i=await CYe(r),s=await tme(i);if(s.isFile())return"file";if(s.isDirectory()){let o=i.length;if(r.startsWith(i)&&r.substr(o,1)===Vx.sep){let a=new Error(`Circular symlink detected: "${r}" points to "${i}"`);return a.code=sme,this._onError(a)}return"directory"}}catch(i){this._onError(i)}}}}_includeAsFile(e){let n=e&&e[this._statsProp];return n&&this._wantsEverything&&!n.isDirectory()}},Tv=(t,e={})=>{let n=e.entryType||e.type;if(n==="both"&&(n=rk),n&&(e.type=n),t){if(typeof t!="string")throw new TypeError("readdirp: root argument must be a string. Usage: readdirp(root, options)");if(n&&!nme.includes(n))throw new Error(`readdirp: Invalid type passed. Use one of ${nme.join(", ")}`)}else throw new Error("readdirp: root argument is required. Usage: readdirp(root, options)");return e.root=t,new ik(e)},OYe=(t,e={})=>new Promise((n,r)=>{let i=[];Tv(t,e).on("data",s=>i.push(s)).on("end",()=>n(i)).on("error",s=>r(s))});Tv.promise=OYe;Tv.ReaddirpStream=ik;Tv.default=Tv;ame.exports=Tv});var Av=H((eNt,lme)=>{lme.exports=function(t,e){if(typeof t!="string")throw new TypeError("expected path to be a string");if(t==="\\"||t==="/")return"/";var n=t.length;if(n<=1)return t;var r="";if(n>4&&t[3]==="\\"){var i=t[2];(i==="?"||i===".")&&t.slice(0,2)==="\\\\"&&(t=t.slice(2),r="//")}var s=t.split(/[/\\]+/);return e!==!1&&s[s.length-1]===""&&s.pop(),r+s.join("/")}});var mme=H((fme,hme)=>{"use strict";Object.defineProperty(fme,"__esModule",{value:!0});var pme=GG(),NYe=Av(),ume="!",DYe={returnIndex:!1},LYe=t=>Array.isArray(t)?t:[t],FYe=(t,e)=>{if(typeof t=="function")return t;if(typeof t=="string"){let n=pme(t,e);return r=>t===r||n(r)}return t instanceof RegExp?n=>t.test(n):n=>!1},dme=(t,e,n,r)=>{let i=Array.isArray(n),s=i?n[0]:n;if(!i&&typeof s!="string")throw new TypeError("anymatch: second argument must be a string: got "+Object.prototype.toString.call(s));let o=NYe(s,!1);for(let c=0;c<e.length;c++){let l=e[c];if(l(o))return r?-1:!1}let a=i&&[o].concat(n.slice(1));for(let c=0;c<t.length;c++){let l=t[c];if(i?l(...a):l(o))return r?c:!0}return r?-1:!1},WG=(t,e,n=DYe)=>{if(t==null)throw new TypeError("anymatch: specify first argument");let r=typeof n=="boolean"?{returnIndex:n}:n,i=r.returnIndex||!1,s=LYe(t),o=s.filter(c=>typeof c=="string"&&c.charAt(0)===ume).map(c=>c.slice(1)).map(c=>pme(c,r)),a=s.filter(c=>typeof c!="string"||typeof c=="string"&&c.charAt(0)!==ume).map(c=>FYe(c,r));return e==null?(c,l=!1)=>dme(a,o,c,typeof l=="boolean"?l:!1):dme(a,o,e,i)};WG.default=WG;hme.exports=WG});var yme=H((tNt,gme)=>{gme.exports=function(e){if(typeof e!="string"||e==="")return!1;for(var n;n=/(\\).|([@?!+*]\(.*\))/g.exec(e);){if(n[2])return!0;e=e.slice(n.index+n[0].length)}return!1}});var zG=H((nNt,_me)=>{var UYe=yme(),vme={"{":"}","(":")","[":"]"},BYe=function(t){if(t[0]==="!")return!0;for(var e=0,n=-2,r=-2,i=-2,s=-2,o=-2;e<t.length;){if(t[e]==="*"||t[e+1]==="?"&&/[\].+)]/.test(t[e])||r!==-1&&t[e]==="["&&t[e+1]!=="]"&&(r<e&&(r=t.indexOf("]",e)),r>e&&(o===-1||o>r||(o=t.indexOf("\\",e),o===-1||o>r)))||i!==-1&&t[e]==="{"&&t[e+1]!=="}"&&(i=t.indexOf("}",e),i>e&&(o=t.indexOf("\\",e),o===-1||o>i))||s!==-1&&t[e]==="("&&t[e+1]==="?"&&/[:!=]/.test(t[e+2])&&t[e+3]!==")"&&(s=t.indexOf(")",e),s>e&&(o=t.indexOf("\\",e),o===-1||o>s))||n!==-1&&t[e]==="("&&t[e+1]!=="|"&&(n<e&&(n=t.indexOf("|",e)),n!==-1&&t[n+1]!==")"&&(s=t.indexOf(")",n),s>n&&(o=t.indexOf("\\",n),o===-1||o>s))))return!0;if(t[e]==="\\"){var a=t[e+1];e+=2;var c=vme[a];if(c){var l=t.indexOf(c,e);l!==-1&&(e=l+1)}if(t[e]==="!")return!0}else e++}return!1},qYe=function(t){if(t[0]==="!")return!0;for(var e=0;e<t.length;){if(/[*?{}()[\]]/.test(t[e]))return!0;if(t[e]==="\\"){var n=t[e+1];e+=2;var r=vme[n];if(r){var i=t.indexOf(r,e);i!==-1&&(e=i+1)}if(t[e]==="!")return!0}else e++}return!1};_me.exports=function(e,n){if(typeof e!="string"||e==="")return!1;if(UYe(e))return!0;var r=BYe;return n&&n.strict===!1&&(r=qYe),r(e)}});var xme=H((rNt,wme)=>{"use strict";var $Ye=zG(),GYe=require("path").posix.dirname,HYe=require("os").platform()==="win32",VG="/",jYe=/\\/g,WYe=/[\{\[].*[\}\]]$/,zYe=/(^|[^\\])([\{\[]|\([^\)]+$)/,VYe=/\\([\!\*\?\|\[\]\(\)\{\}])/g;wme.exports=function(e,n){var r=Object.assign({flipBackslashes:!0},n);r.flipBackslashes&&HYe&&e.indexOf(VG)<0&&(e=e.replace(jYe,VG)),WYe.test(e)&&(e+=VG),e+="a";do e=GYe(e);while($Ye(e)||zYe.test(e));return e.replace(VYe,"$1")}});var ok=H(ca=>{"use strict";ca.isInteger=t=>typeof t=="number"?Number.isInteger(t):typeof t=="string"&&t.trim()!==""?Number.isInteger(Number(t)):!1;ca.find=(t,e)=>t.nodes.find(n=>n.type===e);ca.exceedsLimit=(t,e,n=1,r)=>r===!1||!ca.isInteger(t)||!ca.isInteger(e)?!1:(Number(e)-Number(t))/Number(n)>=r;ca.escapeNode=(t,e=0,n)=>{let r=t.nodes[e];r&&(n&&r.type===n||r.type==="open"||r.type==="close")&&r.escaped!==!0&&(r.value="\\"+r.value,r.escaped=!0)};ca.encloseBrace=t=>t.type!=="brace"?!1:t.commas>>0+t.ranges>>0===0?(t.invalid=!0,!0):!1;ca.isInvalidBrace=t=>t.type!=="brace"?!1:t.invalid===!0||t.dollar?!0:t.commas>>0+t.ranges>>0===0||t.open!==!0||t.close!==!0?(t.invalid=!0,!0):!1;ca.isOpenOrClose=t=>t.type==="open"||t.type==="close"?!0:t.open===!0||t.close===!0;ca.reduce=t=>t.reduce((e,n)=>(n.type==="text"&&e.push(n.value),n.type==="range"&&(n.type="text"),e),[]);ca.flatten=(...t)=>{let e=[],n=r=>{for(let i=0;i<r.length;i++){let s=r[i];if(Array.isArray(s)){n(s);continue}s!==void 0&&e.push(s)}return e};return n(t),e}});var ak=H((sNt,bme)=>{"use strict";var Eme=ok();bme.exports=(t,e={})=>{let n=(r,i={})=>{let s=e.escapeInvalid&&Eme.isInvalidBrace(i),o=r.invalid===!0&&e.escapeInvalid===!0,a="";if(r.value)return(s||o)&&Eme.isOpenOrClose(r)?"\\"+r.value:r.value;if(r.value)return r.value;if(r.nodes)for(let c of r.nodes)a+=n(c);return a};return n(t)}});var Tme=H((oNt,Sme)=>{"use strict";Sme.exports=function(t){return typeof t=="number"?t-t===0:typeof t=="string"&&t.trim()!==""?Number.isFinite?Number.isFinite(+t):isFinite(+t):!1}});var Nme=H((aNt,Ome)=>{"use strict";var Ame=Tme(),Zh=(t,e,n)=>{if(Ame(t)===!1)throw new TypeError("toRegexRange: expected the first argument to be a number");if(e===void 0||t===e)return String(t);if(Ame(e)===!1)throw new TypeError("toRegexRange: expected the second argument to be a number.");let r={relaxZeros:!0,...n};typeof r.strictZeros=="boolean"&&(r.relaxZeros=r.strictZeros===!1);let i=String(r.relaxZeros),s=String(r.shorthand),o=String(r.capture),a=String(r.wrap),c=t+":"+e+"="+i+s+o+a;if(Zh.cache.hasOwnProperty(c))return Zh.cache[c].result;let l=Math.min(t,e),u=Math.max(t,e);if(Math.abs(l-u)===1){let y=t+"|"+e;return r.capture?`(${y})`:r.wrap===!1?y:`(?:${y})`}let d=Mme(t)||Mme(e),p={min:t,max:e,a:l,b:u},m=[],h=[];if(d&&(p.isPadded=d,p.maxLen=String(p.max).length),l<0){let y=u<0?Math.abs(u):1;h=Cme(y,Math.abs(l),p,r),l=p.a=0}return u>=0&&(m=Cme(l,u,p,r)),p.negatives=h,p.positives=m,p.result=KYe(h,m,r),r.capture===!0?p.result=`(${p.result})`:r.wrap!==!1&&m.length+h.length>1&&(p.result=`(?:${p.result})`),Zh.cache[c]=p,p.result};function KYe(t,e,n){let r=KG(t,e,"-",!1,n)||[],i=KG(e,t,"",!1,n)||[],s=KG(t,e,"-?",!0,n)||[];return r.concat(s).concat(i).join("|")}function YYe(t,e){let n=1,r=1,i=Ime(t,n),s=new Set([e]);for(;t<=i&&i<=e;)s.add(i),n+=1,i=Ime(t,n);for(i=kme(e+1,r)-1;t<i&&i<=e;)s.add(i),r+=1,i=kme(e+1,r)-1;return s=[...s],s.sort(QYe),s}function XYe(t,e,n){if(t===e)return{pattern:t,count:[],digits:0};let r=JYe(t,e),i=r.length,s="",o=0;for(let a=0;a<i;a++){let[c,l]=r[a];c===l?s+=c:c!=="0"||l!=="9"?s+=ZYe(c,l,n):o++}return o&&(s+=n.shorthand===!0?"\\d":"[0-9]"),{pattern:s,count:[o],digits:i}}function Cme(t,e,n,r){let i=YYe(t,e),s=[],o=t,a;for(let c=0;c<i.length;c++){let l=i[c],u=XYe(String(o),String(l),r),d="";if(!n.isPadded&&a&&a.pattern===u.pattern){a.count.length>1&&a.count.pop(),a.count.push(u.count[0]),a.string=a.pattern+Pme(a.count),o=l+1;continue}n.isPadded&&(d=eXe(l,n,r)),u.string=d+u.pattern+Pme(u.count),s.push(u),o=l+1,a=u}return s}function KG(t,e,n,r,i){let s=[];for(let o of t){let{string:a}=o;!r&&!Rme(e,"string",a)&&s.push(n+a),r&&Rme(e,"string",a)&&s.push(n+a)}return s}function JYe(t,e){let n=[];for(let r=0;r<t.length;r++)n.push([t[r],e[r]]);return n}function QYe(t,e){return t>e?1:e>t?-1:0}function Rme(t,e,n){return t.some(r=>r[e]===n)}function Ime(t,e){return Number(String(t).slice(0,-e)+"9".repeat(e))}function kme(t,e){return t-t%Math.pow(10,e)}function Pme(t){let[e=0,n=""]=t;return n||e>1?`{${e+(n?","+n:"")}}`:""}function ZYe(t,e,n){return`[${t}${e-t===1?"":"-"}${e}]`}function Mme(t){return/^-?(0+)\d/.test(t)}function eXe(t,e,n){if(!e.isPadded)return t;let r=Math.abs(e.maxLen-String(t).length),i=n.relaxZeros!==!1;switch(r){case 0:return"";case 1:return i?"0?":"0";case 2:return i?"0{0,2}":"00";default:return i?`0{0,${r}}`:`0{${r}}`}}Zh.cache={};Zh.clearCache=()=>Zh.cache={};Ome.exports=Zh});var JG=H((cNt,$me)=>{"use strict";var tXe=require("util"),Lme=Nme(),Dme=t=>t!==null&&typeof t=="object"&&!Array.isArray(t),nXe=t=>e=>t===!0?Number(e):String(e),YG=t=>typeof t=="number"||typeof t=="string"&&t!=="",Yx=t=>Number.isInteger(+t),XG=t=>{let e=`${t}`,n=-1;if(e[0]==="-"&&(e=e.slice(1)),e==="0")return!1;for(;e[++n]==="0";);return n>0},rXe=(t,e,n)=>typeof t=="string"||typeof e=="string"?!0:n.stringify===!0,iXe=(t,e,n)=>{if(e>0){let r=t[0]==="-"?"-":"";r&&(t=t.slice(1)),t=r+t.padStart(r?e-1:e,"0")}return n===!1?String(t):t},lk=(t,e)=>{let n=t[0]==="-"?"-":"";for(n&&(t=t.slice(1),e--);t.length<e;)t="0"+t;return n?"-"+t:t},sXe=(t,e,n)=>{t.negatives.sort((a,c)=>a<c?-1:a>c?1:0),t.positives.sort((a,c)=>a<c?-1:a>c?1:0);let r=e.capture?"":"?:",i="",s="",o;return t.positives.length&&(i=t.positives.map(a=>lk(String(a),n)).join("|")),t.negatives.length&&(s=`-(${r}${t.negatives.map(a=>lk(String(a),n)).join("|")})`),i&&s?o=`${i}|${s}`:o=i||s,e.wrap?`(${r}${o})`:o},Fme=(t,e,n,r)=>{if(n)return Lme(t,e,{wrap:!1,...r});let i=String.fromCharCode(t);if(t===e)return i;let s=String.fromCharCode(e);return`[${i}-${s}]`},Ume=(t,e,n)=>{if(Array.isArray(t)){let r=n.wrap===!0,i=n.capture?"":"?:";return r?`(${i}${t.join("|")})`:t.join("|")}return Lme(t,e,n)},Bme=(...t)=>new RangeError("Invalid range arguments: "+tXe.inspect(...t)),qme=(t,e,n)=>{if(n.strictRanges===!0)throw Bme([t,e]);return[]},oXe=(t,e)=>{if(e.strictRanges===!0)throw new TypeError(`Expected step "${t}" to be a number`);return[]},aXe=(t,e,n=1,r={})=>{let i=Number(t),s=Number(e);if(!Number.isInteger(i)||!Number.isInteger(s)){if(r.strictRanges===!0)throw Bme([t,e]);return[]}i===0&&(i=0),s===0&&(s=0);let o=i>s,a=String(t),c=String(e),l=String(n);n=Math.max(Math.abs(n),1);let u=XG(a)||XG(c)||XG(l),d=u?Math.max(a.length,c.length,l.length):0,p=u===!1&&rXe(t,e,r)===!1,m=r.transform||nXe(p);if(r.toRegex&&n===1)return Fme(lk(t,d),lk(e,d),!0,r);let h={negatives:[],positives:[]},y=A=>h[A<0?"negatives":"positives"].push(Math.abs(A)),v=[],E=0;for(;o?i>=s:i<=s;)r.toRegex===!0&&n>1?y(i):v.push(iXe(m(i,E),d,p)),i=o?i-n:i+n,E++;return r.toRegex===!0?n>1?sXe(h,r,d):Ume(v,null,{wrap:!1,...r}):v},cXe=(t,e,n=1,r={})=>{if(!Yx(t)&&t.length>1||!Yx(e)&&e.length>1)return qme(t,e,r);let i=r.transform||(p=>String.fromCharCode(p)),s=`${t}`.charCodeAt(0),o=`${e}`.charCodeAt(0),a=s>o,c=Math.min(s,o),l=Math.max(s,o);if(r.toRegex&&n===1)return Fme(c,l,!1,r);let u=[],d=0;for(;a?s>=o:s<=o;)u.push(i(s,d)),s=a?s-n:s+n,d++;return r.toRegex===!0?Ume(u,null,{wrap:!1,options:r}):u},ck=(t,e,n,r={})=>{if(e==null&&YG(t))return[t];if(!YG(t)||!YG(e))return qme(t,e,r);if(typeof n=="function")return ck(t,e,1,{transform:n});if(Dme(n))return ck(t,e,0,n);let i={...r};return i.capture===!0&&(i.wrap=!0),n=n||i.step||1,Yx(n)?Yx(t)&&Yx(e)?aXe(t,e,n,i):cXe(t,e,Math.max(Math.abs(n),1),i):n!=null&&!Dme(n)?oXe(n,i):ck(t,e,1,n)};$me.exports=ck});var jme=H((lNt,Hme)=>{"use strict";var lXe=JG(),Gme=ok(),uXe=(t,e={})=>{let n=(r,i={})=>{let s=Gme.isInvalidBrace(i),o=r.invalid===!0&&e.escapeInvalid===!0,a=s===!0||o===!0,c=e.escapeInvalid===!0?"\\":"",l="";if(r.isOpen===!0)return c+r.value;if(r.isClose===!0)return console.log("node.isClose",c,r.value),c+r.value;if(r.type==="open")return a?c+r.value:"(";if(r.type==="close")return a?c+r.value:")";if(r.type==="comma")return r.prev.type==="comma"?"":a?r.value:"|";if(r.value)return r.value;if(r.nodes&&r.ranges>0){let u=Gme.reduce(r.nodes),d=lXe(...u,{...e,wrap:!1,toRegex:!0,strictZeros:!0});if(d.length!==0)return u.length>1&&d.length>1?`(${d})`:d}if(r.nodes)for(let u of r.nodes)l+=n(u,r);return l};return n(t)};Hme.exports=uXe});var Vme=H((uNt,zme)=>{"use strict";var dXe=JG(),Wme=ak(),Cv=ok(),em=(t="",e="",n=!1)=>{let r=[];if(t=[].concat(t),e=[].concat(e),!e.length)return t;if(!t.length)return n?Cv.flatten(e).map(i=>`{${i}}`):e;for(let i of t)if(Array.isArray(i))for(let s of i)r.push(em(s,e,n));else for(let s of e)n===!0&&typeof s=="string"&&(s=`{${s}}`),r.push(Array.isArray(s)?em(i,s,n):i+s);return Cv.flatten(r)},pXe=(t,e={})=>{let n=e.rangeLimit===void 0?1e3:e.rangeLimit,r=(i,s={})=>{i.queue=[];let o=s,a=s.queue;for(;o.type!=="brace"&&o.type!=="root"&&o.parent;)o=o.parent,a=o.queue;if(i.invalid||i.dollar){a.push(em(a.pop(),Wme(i,e)));return}if(i.type==="brace"&&i.invalid!==!0&&i.nodes.length===2){a.push(em(a.pop(),["{}"]));return}if(i.nodes&&i.ranges>0){let d=Cv.reduce(i.nodes);if(Cv.exceedsLimit(...d,e.step,n))throw new RangeError("expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.");let p=dXe(...d,e);p.length===0&&(p=Wme(i,e)),a.push(em(a.pop(),p)),i.nodes=[];return}let c=Cv.encloseBrace(i),l=i.queue,u=i;for(;u.type!=="brace"&&u.type!=="root"&&u.parent;)u=u.parent,l=u.queue;for(let d=0;d<i.nodes.length;d++){let p=i.nodes[d];if(p.type==="comma"&&i.type==="brace"){d===1&&l.push(""),l.push("");continue}if(p.type==="close"){a.push(em(a.pop(),l,c));continue}if(p.value&&p.type!=="open"){l.push(em(l.pop(),p.value));continue}p.nodes&&r(p,i)}return l};return Cv.flatten(r(t))};zme.exports=pXe});var Yme=H((dNt,Kme)=>{"use strict";Kme.exports={MAX_LENGTH:1e4,CHAR_0:"0",CHAR_9:"9",CHAR_UPPERCASE_A:"A",CHAR_LOWERCASE_A:"a",CHAR_UPPERCASE_Z:"Z",CHAR_LOWERCASE_Z:"z",CHAR_LEFT_PARENTHESES:"(",CHAR_RIGHT_PARENTHESES:")",CHAR_ASTERISK:"*",CHAR_AMPERSAND:"&",CHAR_AT:"@",CHAR_BACKSLASH:"\\",CHAR_BACKTICK:"`",CHAR_CARRIAGE_RETURN:"\r",CHAR_CIRCUMFLEX_ACCENT:"^",CHAR_COLON:":",CHAR_COMMA:",",CHAR_DOLLAR:"$",CHAR_DOT:".",CHAR_DOUBLE_QUOTE:'"',CHAR_EQUAL:"=",CHAR_EXCLAMATION_MARK:"!",CHAR_FORM_FEED:"\f",CHAR_FORWARD_SLASH:"/",CHAR_HASH:"#",CHAR_HYPHEN_MINUS:"-",CHAR_LEFT_ANGLE_BRACKET:"<",CHAR_LEFT_CURLY_BRACE:"{",CHAR_LEFT_SQUARE_BRACKET:"[",CHAR_LINE_FEED:`
1061
+ `}function I5e(t){let e=C5e[t];if(!e)return{success:!1,error:"Unknown tool"};try{return t==="codex"||t==="opencode"||t==="amp"||t==="pi"||t==="omp"?e.enable():e.enable(yn[t]())}catch(n){return{success:!1,error:n.message}}}function k5e(t){let e=(process.env.PATH||"").split(Sr.default.delimiter).filter(Boolean),n=process.platform==="win32"?(process.env.PATHEXT||".EXE;.CMD;.BAT").split(";"):[""];return e.some(r=>n.some(i=>{try{return ze.default.existsSync(Sr.default.join(r,t+i))}catch{return!1}}))}function xhe(t){let e=ghe[t];if(e&&k5e(e))return!0;let n=r5e[t]?.();return n?(Array.isArray(n)?n:[n]).some(r=>ze.default.existsSync(r)):!1}function Ehe(){let t={};for(let e of R5e)if(xhe(e))try{let n=I5e(e);t[e]=n.success&&!n.untrusted?.length}catch{t[e]=!1}return t}async function bhe(){if(!xhe("codex"))return null;try{let{missing:t}=await h5e();return t.length&&console.warn(`\u26A0\uFE0F codex hooks written but not trusted: ${t.length} \u2014 run codex and trust them`),t.length?{untrusted:t.length}:{untrusted:0}}catch(t){return console.warn(`\u26A0\uFE0F codex hook trust failed: ${t.message}`),{error:t.message}}}function She(){let t=yn.claude(),e=zr(t);if(!e.hooks?.Stop&&!e.hooks?.Notification)return;let n=e.env||{};Object.keys(iw).some(i=>n[i]!==iw[i])&&(yhe(e),Cs(t,e))}var fhe,ze,Sr,hhe,VI,mhe,n5e,Ni,kp,yn,ghe,Jh,r5e,EG,KI,zI,i5e,WI,vhe,d1t,_he,u5e,p5e,uhe,xG,g5e,dhe,v5e,x5e,b5e,S5e,T5e,A5e,C5e,R5e,The=ne(()=>{fhe=Q(require("os"),1),ze=Q(require("fs"),1),Sr=Q(require("path"),1),hhe=require("child_process");qt();qo();Jc();VI=`http://localhost:${Ua}/api/notify`,mhe="nineRemoteNotify",n5e=Sr.default.join(Pe.STATE,"claudeEnvBackup.json"),Ni=(...t)=>Sr.default.join(fhe.default.homedir(),...t),kp=(t,...e)=>{let n=process.env[t];return n&&n.trim()?n.trim():Ni(...e)},yn={claude:()=>Ni(".claude","settings.json"),codex:()=>Ni(".codex","config.toml"),codexHooks:()=>Ni(".codex","hooks.json"),codexScript:()=>Ni(".codex","9remote-notify.sh"),opencode:()=>Ni(".config","opencode","plugin",`${mhe}.js`),grok:()=>Sr.default.join(kp("GROK_HOME",".grok"),"hooks","9remote.json"),cursor:()=>Ni(".cursor","hooks.json"),antigravity:()=>Ni(".gemini","config","hooks.json"),kiro:()=>Sr.default.join(kp("KIRO_HOME",".kiro"),"agents","9remote.json"),copilot:()=>Sr.default.join(kp("COPILOT_HOME",".copilot"),"config.json"),codebuddy:()=>Sr.default.join(kp("CODEBUDDY_CONFIG_DIR",".codebuddy"),"settings.json"),factory:()=>Ni(".factory","settings.json"),qoder:()=>Sr.default.join(kp("QODER_CONFIG_DIR",".qoder"),"settings.json"),rovodev:()=>Ni(".rovodev","config.yml"),hermes:()=>Sr.default.join(kp("HERMES_HOME",".hermes"),"config.yaml"),amp:()=>Ni(".config","amp","plugins","9remote.ts"),devin:()=>Ni(".config","devin","config.json"),pi:()=>Sr.default.join(kp("PI_CODING_AGENT_DIR",".pi","agent"),"extensions","9remote.ts"),omp:()=>Sr.default.join(kp("PI_CODING_AGENT_DIR",".omp","agent"),"extensions","9remote.ts")},ghe={claude:"claude",codex:"codex",opencode:"opencode",grok:"grok",cursor:"cursor-agent",antigravity:"agy",kiro:"kiro-cli",copilot:"copilot",codebuddy:"codebuddy",factory:"droid",qoder:"qodercli",rovodev:"acli",hermes:"hermes",amp:"amp",pi:"pi",omp:"omp",devin:"devin"},Jh=(t,e,{sessionId:n=!1}={})=>{let r=n?QU(e)[0]:null;return`${r?`csid=$(cat 2>/dev/null | sed -n 's/.*"${r}" *: *"\\([^"]*\\)".*/\\1/p'); `:""}command -v curl >/dev/null 2>&1 && curl -s --connect-timeout 1 --max-time 2 "${VI}?type=${t}&sessionId=$NINE_REMOTE_SESSION_ID${r?"&csid=$csid":""}&tool=${e}" > /dev/null 2>&1 & true`},r5e={claude:()=>Ni(".claude"),codex:()=>Ni(".codex"),opencode:()=>[Ni(".config","opencode"),Ni(".opencode")]},EG=t=>Math.ceil(t/1e3),KI=5e3,zI=t=>t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),i5e=t=>`"${t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`;WI={UserPromptSubmit:"working",PreToolUse:"working",PostToolUse:"working",Stop:"done",PermissionRequest:"blocked"},vhe=t=>t.replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase(),d1t=Object.fromEntries(Object.keys(WI).map(t=>[vhe(t),t])),_he=/^\[hooks\.state\."(?<key>[^"]+)"\]$/m,u5e=15e3;p5e=t=>/^sha256:/.test(t)?t:`sha256:${t}`,uhe=t=>t.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),xG=(t,e)=>t.replace(/\\+/g,"\\")===e.replace(/\\+/g,"\\");g5e=/# 9Remote notification\nnotify\s*=.*\n?/g,dhe=/^# 9Remote-saved: (notify\s*=.*)$/m;v5e={enable(){let t=yn.codexHooks(),e=zr(t),n={...e.hooks||{}};for(let[r,i]of Object.entries(WI))n[r]=[...(n[r]||[]).filter(s=>!wG(s)),_5e(i)];return e.hooks=n,Cs(t,e),y5e(),{success:!0}},disable(){let t=yn.codexHooks(),e=new Set(whe(t).filter(n=>n.command.includes("&tool=codex")).map(n=>n.key));if(ze.default.existsSync(t)){let n=zr(t);if(n.hooks){for(let r of Object.keys(WI))n.hooks[r]=(n.hooks[r]||[]).filter(i=>!wG(i)),n.hooks[r].length===0&&delete n.hooks[r];Object.keys(n.hooks).length===0&&delete n.hooks}Cs(t,n)}return m5e(yn.codex(),e),{success:!0}},isEnabled(){let t=zr(yn.codexHooks()).hooks||{};return Object.keys(WI).every(e=>(t[e]||[]).some(wG))}};x5e={enable(){let t=yn.opencode(),e=Sr.default.dirname(t);return ze.default.existsSync(e)||ze.default.mkdirSync(e,{recursive:!0}),ze.default.writeFileSync(t,w5e(),"utf8"),{success:!0}},disable(){let t=yn.opencode();return ze.default.existsSync(t)&&ze.default.unlinkSync(t),{success:!0}},isEnabled(){let t=yn.opencode();return ze.default.existsSync(t)&&ze.default.readFileSync(t,"utf8").includes("&sessionID=")}};b5e="# 9remote hooks begin",S5e="# 9remote hooks end",T5e=" # 9remote hooks begin",A5e=" # 9remote hooks end",C5e={claude:Xh("claude",{UserPromptSubmit:"working",PreToolUse:"working",PostToolUse:"working",Stop:"done",PermissionRequest:"blocked",Notification:"blocked"},t=>t,{matchers:{Notification:"permission_prompt"},extra:yhe,sessionId:!0}),devin:Xh("devin",{UserPromptSubmit:"working",PreToolUse:"working",PostToolUse:"working",Stop:"done",PermissionRequest:"blocked"},t=>t,{sessionId:!0}),codex:v5e,opencode:x5e,grok:Xh("grok",{UserPromptSubmit:"working",PreToolUse:"working",PostToolUse:"working",Stop:"done",Notification:"blocked"},EG),cursor:a5e("cursor",{stop:"done",beforeShellExecution:"blocked",beforeToolCall:"working"},{extra:t=>{t.version=t.version||1}}),antigravity:c5e("antigravity","9remote",{UserPromptSubmit:"working",PreToolUse:"working",Stop:"done",Notification:"blocked"}),kiro:l5e("kiro",{UserPromptSubmit:"working",PostToolUse:"working",preToolUse:"blocked",stop:"done"}),copilot:Xh("copilot",{UserPromptSubmit:"working",PostToolUse:"working",PreToolUse:"blocked",Stop:"done"},t=>t),codebuddy:Xh("codebuddy",{UserPromptSubmit:"working",PostToolUse:"working",PreToolUse:"blocked",Stop:"done"},t=>t),factory:Xh("factory",{UserPromptSubmit:"working",PostToolUse:"working",PreToolUse:"blocked",Stop:"done"},t=>t),qoder:Xh("qoder",{UserPromptSubmit:"working",PostToolUse:"working",PreToolUse:"blocked",Stop:"done"},t=>t),rovodev:lhe("rovodev",{begin:T5e,end:A5e,items:[{event:"on_complete",type:"done"},{event:"on_error",type:"done"},{event:"on_tool_permission",type:"blocked"},{event:"on_message",type:"working"},{event:"on_tool_start",type:"working"}]}),hermes:(()=>{let t=lhe("hermes",{begin:b5e,end:S5e,items:[{event:"pre_llm_call",type:"working"},{event:"pre_tool_call",type:"working"},{event:"post_tool_call",type:"working"},{event:"pre_approval_request",type:"blocked"},{event:"post_llm_call",type:"done"}]}),e=()=>Sr.default.join(Sr.default.dirname(yn.hermes()),"shell-hooks-allowlist.json");return{enable:()=>{let n=t.enable(yn.hermes()),r=zr(e()),i=(r.approvals||[]).filter(s=>!(typeof s.command=="string"&&s.command.includes("&tool=hermes")));return r.approvals=[...i,...[{event:"pre_llm_call",type:"working"},{event:"pre_tool_call",type:"working"},{event:"post_tool_call",type:"working"},{event:"pre_approval_request",type:"blocked"},{event:"post_llm_call",type:"done"}].map(({event:s,type:o})=>({event:s,command:Jh(o,"hermes"),approved_at:"2020-01-01T00:00:00Z"}))],Cs(e(),r),n},disable:()=>{let n=t.disable(yn.hermes()),r=e();if(ze.default.existsSync(r)){let i=zr(r);i.approvals=(i.approvals||[]).filter(s=>!(typeof s.command=="string"&&s.command.includes("&tool=hermes"))),i.approvals.length?Cs(r,i):ze.default.unlinkSync(r)}return n},isEnabled:()=>t.isEnabled(yn.hermes())}})(),amp:{enable(){let t=yn.amp(),e=Sr.default.dirname(t);return ze.default.existsSync(e)||ze.default.mkdirSync(e,{recursive:!0}),ze.default.writeFileSync(t,phe("amp","amp","agent.start","agent.end"),"utf8"),{success:!0}},disable(){return ze.default.existsSync(yn.amp())&&ze.default.unlinkSync(yn.amp()),{success:!0}},isEnabled(){return ze.default.existsSync(yn.amp())}},pi:{enable(){let t=yn.pi(),e=Sr.default.dirname(t);return ze.default.existsSync(e)||ze.default.mkdirSync(e,{recursive:!0}),ze.default.writeFileSync(t,phe("pi","pi","agent_start","agent_end"),"utf8"),{success:!0}},disable(){return ze.default.existsSync(yn.pi())&&ze.default.unlinkSync(yn.pi()),{success:!0}},isEnabled(){return ze.default.existsSync(yn.pi())}},omp:{enable(){let t=yn.omp(),e=Sr.default.dirname(t);return ze.default.existsSync(e)||ze.default.mkdirSync(e,{recursive:!0}),ze.default.writeFileSync(t,E5e(),"utf8"),{success:!0}},disable(){return ze.default.existsSync(yn.omp())&&ze.default.unlinkSync(yn.omp()),{success:!0}},isEnabled(){return ze.default.existsSync(yn.omp())}}},R5e=iY});var bG=ne(()=>{xs()});var jI={};fr(jI,{broadcastAiStatus:()=>Hx,broadcastServerInfo:()=>QI,initializeTerminal:()=>RG,listSessionRoots:()=>Wu,matchWorkspacePath:()=>Mhe,registerManagedSession:()=>CG,setConnectCheckHandler:()=>IG,setupTerminalHandlers:()=>kG,setupTerminalSocket:()=>Np,workspaceOfSession:()=>U5e});async function N5e(t,e){if(!qie(e))return;let r=(await zc().catch(()=>null))?.find(s=>s.id===e);Bie(e,r?.foregroundProcess)?.state==="idle"&&(Ge(t,"statusChange",{sessionId:e,state:"idle",tool:null,conversationId:null}),Ge(t,"statusState",Zc()))}function D5e(t,e){let n=(XI.get(t)||"")+e,r=null;Ahe.lastIndex=0;for(let o;o=Ahe.exec(n);)r=o[1];if(r){let o=Tie(r);o&&_s(t,o)}let i=n.lastIndexOf("\x1B]"),s=i===-1?"":n.slice(i);s&&s.length<=M5e&&!s.slice(3).includes("\x07")&&!s.includes("\x1B\\")?XI.set(t,s):XI.delete(t)}function Rhe(){let t=(Che||Promise.resolve()).catch(()=>{}).then(()=>L5e());return Che=t.catch(()=>{}),t}async function L5e(){let t=await zc(),e=new Map(t.map(r=>[r.id,r])),n=TC();for(let r of t)if(!n[r.id])try{await Qd(r.id)}catch{}Tr.clear();for(let[r,i]of Object.entries(n)){let s=e.get(r);Tr.set(r,{daemon:!0,name:i.name,autoNamed:i.autoNamed!==!1,createdAt:i.createdAt,shellId:i.shellId,cwd:s?.cwd||i.cwd,workspacePath:i.workspacePath??$x[r]??null,lastCols:i.cols??null,lastRows:i.rows??null,needsRespawn:!s,agent:i.agent||null}),i.agent&&_s(r,i.agent),oB(r,i)}ii(Tr)}function F5e(t){!Pp||!t||Gx.has(t)||Gx.set(t,setTimeout(()=>{Gx.delete(t),rI(Pp,Tr,t).catch(()=>{})},lte))}async function Ihe(){let t=[...Tr.entries()].filter(([,n])=>n.daemon&&n.needsRespawn),e=0;for(let[n,r]of t)try{let{cols:i,rows:s}=tI(r),o=await wu(r.name,i,s,r.shellId,n,r.cwd);if(!o.success)continue;delete r.needsRespawn,r.cwd=o.cwd,r.shellLabel=o.shellLabel,r.lastCols=i,r.lastRows=s,e++;let a=Mi(n),c=a&&ur(a.agent),l=c&&a.id&&Au(c,a.id);l&&setTimeout(()=>$h(n,r,`${Ax}${l}\r`),ute)}catch(i){Phe.warn(`[respawn] session ${n} failed: ${i.message}`)}e&&(ii(Tr),Ge(null,"sessionsChanged"),console.log(AG(`\u{1F504} Respawned ${e} session(s) after daemon restart`)))}function SG(){let{assignments:t,created:e}=lse({sessions:Tr,workspaces:[...Mp.values()],sessionWorkspaces:Op});if(Object.keys(t).length){for(let n of e)Mp.set(n.id,n);for(let[n,r]of Object.entries(t)){Op[n]=r;let i=Tr.get(n);i&&!i.workspacePath&&(i.workspacePath=Mp.get(r)?.path||null)}Oy(Mp,Op,JI),ii(Tr),console.log(AG(`\u{1F4C1} Grouped ${Object.keys(t).length} loose terminal(s)`+(e.length?` into ${e.length} new workspace(s)`:"")))}}function U5e(t){if(Tr.has(t))return Op[t]??null}function Wu(){return[...Tr.entries()].map(([t,e])=>({id:t,name:e.name,workspacePath:e.workspacePath||null,cwd:e.cwd||null}))}function Mhe(t,e){let n=e?(0,Qh.resolve)(e):"";if(!n)return null;let r=null,i=null,s=null;for(let o of t||[]){if(!o?.path)continue;let a=(0,Qh.resolve)(o.path);n===a?r=o:n.startsWith(a+"/")&&(!i||a.length>(0,Qh.resolve)(i.path).length)?i=o:a.startsWith(n+"/")&&(!s||a.length<(0,Qh.resolve)(s.path).length)&&(s=o)}return r||i||s||null}function CG({sessionId:t,name:e,autoNamed:n=!0,cwd:r=null,workspacePath:i=null,shellId:s=null,shellLabel:o=null,agent:a=null}){let c=Mhe([...Mp.values()],i||r)||null;return Tr.set(t,{daemon:!0,name:e,autoNamed:n,createdAt:Date.now(),cwd:r||c?.path||null,workspacePath:c?.path||null,shellId:s,shellLabel:o,agent:a}),c&&(Op[t]=c.id,Oy(Mp,Op,JI)),ii(Tr),Ge(null,"sessionsChanged"),{success:!0,sessionId:t,workspacePath:c?.path||null}}async function RG(){let t=ese();if(!t){let r=TC(),i=Zie();t=cse(i,r);let s=new Map(t.workspaces.map(c=>[c.id,c]));if(Oy(s,t.sessionWorkspaces,t.sessionOrder),$x=t.sessionPaths||{},Object.keys($x).length){for(let[c,l]of Object.entries($x))r[c]&&(r[c].workspacePath=l);Qie(r)}let o=(i.groups||[]).filter(c=>t.workspaces.some(l=>l.id===c.id)).length,a=(i.groups||[]).length-o;(t.workspaces.length||a)&&console.log(AG(`\u{1F4C1} Migrated ${t.workspaces.length} workspace(s) from terminal groups`+(a?`, dropped ${a} empty group(s)`:"")))}for(let r of t.workspaces)Mp.set(r.id,r);Object.assign(Op,t.sessionWorkspaces),JI.push(...t.sessionOrder),Die(()=>ii(Tr)),Gie(F5e);try{She()}catch{}try{Ehe()}catch{}bhe().catch(()=>{});try{nhe()}catch{}if(TG==="daemon")if(!await VF())console.error("\u274C Failed to connect to PTY daemon, falling back to buffer mode");else{await Rhe(),SG(),Ihe().catch(()=>{}),yu("connected",()=>{Rhe().then(SG).then(Ihe).catch(()=>{})});return}console.log("\u{1F4E6} Buffer persistence mode - scrollback enabled");let e=Jie(),n=TC();for(let r of e){let i=n[r]||{};Tr.set(r,{pty:null,name:i.name||`Terminal ${Tr.size+1}`,autoNamed:i.autoNamed!==!1,createdAt:i.createdAt||Date.now(),cwd:i.cwd,workspacePath:i.workspacePath??$x[r]??null,shellId:i.shellId,buffer:[],needsRestore:!0}),oB(r,i),console.log(`\u{1F504} Found saved session: ${r}`)}e.length>0&&console.log(`\u2705 Found ${e.length} saved session(s)`),SG()}function Np(t,e){Pp=t,TG==="daemon"&&(yu("output",({sessionId:i,enc:s,data:o,replay:a})=>{a!==!0&&(wC(i),vC(i));let c=s==="b64"?Buffer.from(o,"base64"):Buffer.from(o||"");c.length>Ja&&(YI++,(YI===1||YI%500===0)&&Phe.info(`[slice] chunk ${c.length>>10}KB \u2192 ${Math.ceil(c.length/Ja)} events (total sliced: ${YI})`)),s==="b64"&&D5e(i,c.toString("utf8"));for(let l=0;l<c.length||l===0;l+=Ja){let u=c.subarray(l,l+Ja),d=a===!0?Cx(i):rde(i);a!==!0&&ide(i,d,u),Ge(t,"output",{sessionId:i,enc:"bin",data:u,replay:a===!0,seq:d})}}),Vie(i=>Ge(t,"statusState",Zc())),Wie(()=>Ge(t,"statusState",Zc())),yu("cwdChange",({sessionId:i,cwd:s})=>{let o=Tr.get(i);o&&s&&o.cwd!==s&&(o.cwd=s,ii(Tr)),Ge(t,"cwdChange",{sessionId:i,cwd:s})}),yu("processChange",({sessionId:i,process:s})=>{let o=Uie(i,s);if(o?.state==="pendingShell"){setTimeout(()=>N5e(t,i),O5e);return}o?.state==="idle"&&(Ge(t,"statusChange",{sessionId:i,state:"idle",tool:null,conversationId:null}),Ge(t,"statusState",Zc()))}),yu("sessionClosed",i=>{Tr.delete(i),sv(i),ky(i),XI.delete(i);let s=Gx.get(i);s&&(clearTimeout(s),Gx.delete(i)),lB(i),Ge(t,"sessionClosed",i),Ge(t,"notificationCleared",i)}));let n=()=>({version:P5e,remoteAvailable:ch(),remoteStatus:oF(),mobileAvailable:oie(),daemonMode:TG==="daemon"&&gn(),platform:process.platform,updateAvailable:Ww(),canSelfUpdate:!0,caps:{joinSessionSize:!0,artifact:!0},artifactEnabled:qx(),voiceConfig:hs().voiceConfig||null,mcpClients:bv,...lie()}),r=()=>{let i=n();for(let s of t.sockets.sockets.values())s.data?.approved&&s.emit("serverInfo",i);for(let s of iy()){let o=s._host;if(!(!o?.defersWsAdapter||!o.data?.approved))try{s.emit("serverInfo",i)}catch{}}};cF(r),Np._buildServerInfo=n,Np._emitServerInfo=r}function QI(){Np._emitServerInfo?.()}function Hx(t,e,n,r=null){if(!Pp)return null;if(e==="done")return _C(t,()=>{let a=r?.sessionId||r?.threadId||Mi(t)?.id||null,c=fp(t),l=Th({type:e,sessionId:t,tool:n});!l||l===c||(Ge(Pp,"statusChange",{sessionId:t,state:e,tool:n,conversationId:a}),Ge(Pp,"statusState",Zc()))}),fp(t);let i=r?.sessionId||r?.threadId||Mi(t)?.id||null,s=fp(t),o=Th({type:e,sessionId:t,tool:n});return!o||o===s||(Ge(Pp,"statusChange",{sessionId:t,state:e,tool:n,conversationId:i}),Ge(Pp,"statusState",Zc())),o}function IG(t){Ohe=t}async function kG(t,e,n){uie(),Ohe?.(),t.emit("srvCaps",{env2:1,seqCtl:1,inputAck:1,promptDedupe:1}),t.emit("serverInfo",Np._buildServerInfo?.()),lde(t,e,Tr,Mp,Op,JI),gde(t,Tr),ahe(t,e),HA()&&await Ine(t,n).catch(r=>{console.error("\u274C Failed to setup remote handlers:",r.message)}),aie(t),t.on("disconnect",()=>{Dfe(t.id),die()})}var Qh,khe,Phe,z1t,AG,TG,P5e,Ahe,M5e,O5e,XI,Tr,Mp,Op,JI,$x,Che,Gx,Pp,YI,Ohe,aa=ne(()=>{J1();Qh=require("path"),khe=require("url");ri();jA();cie();ys();rC();AC();CC();sI();yde();che();The();HI();oh();LI();bG();xs();Jc();mp();Tu();m$();yi();v$();mu();$e();Phe=Ee("terminal"),z1t=(0,Qh.dirname)((0,khe.fileURLToPath)(__importMetaUrl)),AG=tw.rgb(230,138,110),TG="daemon",P5e="3.0.52",Ahe=/\x1b\](?:0|2);([^\x07\x1b]*)(?:\x07|\x1b\\)/g,M5e=256,O5e=1500,XI=new Map;Tr=new Map,Mp=new Map,Op={},JI=[],$x={},Che=null;Gx=new Map,Pp=null;YI=0;Ohe=null});var jx=H((V1t,Uhe)=>{"use strict";var B5e=require("path"),hl="\\\\/",Nhe=`[^${hl}]`,q5e=0,zu="\\.",$5e="\\+",G5e="\\?",ZI="\\/",H5e="(?=.)",Dhe="[^/]",PG=`(?:${ZI}|$)`,Lhe=`(?:^|${ZI})`,MG=`${zu}{1,2}${PG}`,j5e=`(?!${zu})`,W5e=`(?!${Lhe}${MG})`,z5e=`(?!${zu}{0,1}${PG})`,V5e=`(?!${MG})`,K5e=`[^.${ZI}]`,Y5e=`${Dhe}*?`,Fhe={DOT_LITERAL:zu,PLUS_LITERAL:$5e,QMARK_LITERAL:G5e,SLASH_LITERAL:ZI,ONE_CHAR:H5e,QMARK:Dhe,END_ANCHOR:PG,DOTS_SLASH:MG,NO_DOT:j5e,NO_DOTS:W5e,NO_DOT_SLASH:z5e,NO_DOTS_SLASH:V5e,QMARK_NO_DOT:K5e,STAR:Y5e,START_ANCHOR:Lhe},X5e={...Fhe,SLASH_LITERAL:`[${hl}]`,QMARK:Nhe,STAR:`${Nhe}*?`,DOTS_SLASH:`${zu}{1,2}(?:[${hl}]|$)`,NO_DOT:`(?!${zu})`,NO_DOTS:`(?!(?:^|[${hl}])${zu}{1,2}(?:[${hl}]|$))`,NO_DOT_SLASH:`(?!${zu}{0,1}(?:[${hl}]|$))`,NO_DOTS_SLASH:`(?!${zu}{1,2}(?:[${hl}]|$))`,QMARK_NO_DOT:`[^.${hl}]`,START_ANCHOR:`(?:^|[${hl}])`,END_ANCHOR:`(?:[${hl}]|$)`},J5e={__proto__:null,alnum:"a-zA-Z0-9",alpha:"a-zA-Z",ascii:"\\x00-\\x7F",blank:" \\t",cntrl:"\\x00-\\x1F\\x7F",digit:"0-9",graph:"\\x21-\\x7E",lower:"a-z",print:"\\x20-\\x7E ",punct:"\\-!\"#$%&'()\\*+,./:;<=>?@[\\]^_`{|}~",space:" \\t\\r\\n\\v\\f",upper:"A-Z",word:"A-Za-z0-9_",xdigit:"A-Fa-f0-9"};Uhe.exports={DEFAULT_MAX_EXTGLOB_RECURSION:q5e,MAX_LENGTH:1024*64,POSIX_REGEX_SOURCE:J5e,REGEX_BACKSLASH:/\\(?![*+?^${}(|)[\]])/g,REGEX_NON_SPECIAL_CHARS:/^[^@![\].,$*+?^{}()|\\/]+/,REGEX_SPECIAL_CHARS:/[-*+?.^${}(|)[\]]/,REGEX_SPECIAL_CHARS_BACKREF:/(\\?)((\W)(\3*))/g,REGEX_SPECIAL_CHARS_GLOBAL:/([-*+?.^${}(|)[\]])/g,REGEX_REMOVE_BACKSLASH:/(?:\[.*?[^\\]\]|\\(?=.))/g,REPLACEMENTS:{__proto__:null,"***":"*","**/**":"**","**/**/**":"**"},CHAR_0:48,CHAR_9:57,CHAR_UPPERCASE_A:65,CHAR_LOWERCASE_A:97,CHAR_UPPERCASE_Z:90,CHAR_LOWERCASE_Z:122,CHAR_LEFT_PARENTHESES:40,CHAR_RIGHT_PARENTHESES:41,CHAR_ASTERISK:42,CHAR_AMPERSAND:38,CHAR_AT:64,CHAR_BACKWARD_SLASH:92,CHAR_CARRIAGE_RETURN:13,CHAR_CIRCUMFLEX_ACCENT:94,CHAR_COLON:58,CHAR_COMMA:44,CHAR_DOT:46,CHAR_DOUBLE_QUOTE:34,CHAR_EQUAL:61,CHAR_EXCLAMATION_MARK:33,CHAR_FORM_FEED:12,CHAR_FORWARD_SLASH:47,CHAR_GRAVE_ACCENT:96,CHAR_HASH:35,CHAR_HYPHEN_MINUS:45,CHAR_LEFT_ANGLE_BRACKET:60,CHAR_LEFT_CURLY_BRACE:123,CHAR_LEFT_SQUARE_BRACKET:91,CHAR_LINE_FEED:10,CHAR_NO_BREAK_SPACE:160,CHAR_PERCENT:37,CHAR_PLUS:43,CHAR_QUESTION_MARK:63,CHAR_RIGHT_ANGLE_BRACKET:62,CHAR_RIGHT_CURLY_BRACE:125,CHAR_RIGHT_SQUARE_BRACKET:93,CHAR_SEMICOLON:59,CHAR_SINGLE_QUOTE:39,CHAR_SPACE:32,CHAR_TAB:9,CHAR_UNDERSCORE:95,CHAR_VERTICAL_LINE:124,CHAR_ZERO_WIDTH_NOBREAK_SPACE:65279,SEP:B5e.sep,extglobChars(t){return{"!":{type:"negate",open:"(?:(?!(?:",close:`))${t.STAR})`},"?":{type:"qmark",open:"(?:",close:")?"},"+":{type:"plus",open:"(?:",close:")+"},"*":{type:"star",open:"(?:",close:")*"},"@":{type:"at",open:"(?:",close:")"}}},globChars(t){return t===!0?X5e:Fhe}}});var ek=H(Rs=>{"use strict";var Q5e=require("path"),Z5e=process.platform==="win32",{REGEX_BACKSLASH:eYe,REGEX_REMOVE_BACKSLASH:tYe,REGEX_SPECIAL_CHARS:nYe,REGEX_SPECIAL_CHARS_GLOBAL:rYe}=jx();Rs.isObject=t=>t!==null&&typeof t=="object"&&!Array.isArray(t);Rs.hasRegexChars=t=>nYe.test(t);Rs.isRegexChar=t=>t.length===1&&Rs.hasRegexChars(t);Rs.escapeRegex=t=>t.replace(rYe,"\\$1");Rs.toPosixSlashes=t=>t.replace(eYe,"/");Rs.removeBackslashes=t=>t.replace(tYe,e=>e==="\\"?"":e);Rs.supportsLookbehinds=()=>{let t=process.version.slice(1).split(".").map(Number);return t.length===3&&t[0]>=9||t[0]===8&&t[1]>=10};Rs.isWindows=t=>t&&typeof t.windows=="boolean"?t.windows:Z5e===!0||Q5e.sep==="\\";Rs.escapeLast=(t,e,n)=>{let r=t.lastIndexOf(e,n);return r===-1?t:t[r-1]==="\\"?Rs.escapeLast(t,e,r-1):`${t.slice(0,r)}\\${t.slice(r)}`};Rs.removePrefix=(t,e={})=>{let n=t;return n.startsWith("./")&&(n=n.slice(2),e.prefix="./"),n};Rs.wrapOutput=(t,e={},n={})=>{let r=n.contains?"":"^",i=n.contains?"":"$",s=`${r}(?:${t})${i}`;return e.negated===!0&&(s=`(?:^(?!${s}).*$)`),s}});var zhe=H((Y1t,Whe)=>{"use strict";var Bhe=ek(),{CHAR_ASTERISK:OG,CHAR_AT:iYe,CHAR_BACKWARD_SLASH:Wx,CHAR_COMMA:sYe,CHAR_DOT:NG,CHAR_EXCLAMATION_MARK:DG,CHAR_FORWARD_SLASH:jhe,CHAR_LEFT_CURLY_BRACE:LG,CHAR_LEFT_PARENTHESES:FG,CHAR_LEFT_SQUARE_BRACKET:oYe,CHAR_PLUS:aYe,CHAR_QUESTION_MARK:qhe,CHAR_RIGHT_CURLY_BRACE:cYe,CHAR_RIGHT_PARENTHESES:$he,CHAR_RIGHT_SQUARE_BRACKET:lYe}=jx(),Ghe=t=>t===jhe||t===Wx,Hhe=t=>{t.isPrefix!==!0&&(t.depth=t.isGlobstar?1/0:1)},uYe=(t,e)=>{let n=e||{},r=t.length-1,i=n.parts===!0||n.scanToEnd===!0,s=[],o=[],a=[],c=t,l=-1,u=0,d=0,p=!1,m=!1,h=!1,y=!1,v=!1,E=!1,A=!1,b=!1,S=!1,I=!1,F=0,D,B,M={value:"",depth:0,isGlob:!1},P=()=>l>=r,x=()=>c.charCodeAt(l+1),R=()=>(D=B,c.charCodeAt(++l));for(;l<r;){B=R();let Y;if(B===Wx){A=M.backslashes=!0,B=R(),B===LG&&(E=!0);continue}if(E===!0||B===LG){for(F++;P()!==!0&&(B=R());){if(B===Wx){A=M.backslashes=!0,R();continue}if(B===LG){F++;continue}if(E!==!0&&B===NG&&(B=R())===NG){if(p=M.isBrace=!0,h=M.isGlob=!0,I=!0,i===!0)continue;break}if(E!==!0&&B===sYe){if(p=M.isBrace=!0,h=M.isGlob=!0,I=!0,i===!0)continue;break}if(B===cYe&&(F--,F===0)){E=!1,p=M.isBrace=!0,I=!0;break}}if(i===!0)continue;break}if(B===jhe){if(s.push(l),o.push(M),M={value:"",depth:0,isGlob:!1},I===!0)continue;if(D===NG&&l===u+1){u+=2;continue}d=l+1;continue}if(n.noext!==!0&&(B===aYe||B===iYe||B===OG||B===qhe||B===DG)===!0&&x()===FG){if(h=M.isGlob=!0,y=M.isExtglob=!0,I=!0,B===DG&&l===u&&(S=!0),i===!0){for(;P()!==!0&&(B=R());){if(B===Wx){A=M.backslashes=!0,B=R();continue}if(B===$he){h=M.isGlob=!0,I=!0;break}}continue}break}if(B===OG){if(D===OG&&(v=M.isGlobstar=!0),h=M.isGlob=!0,I=!0,i===!0)continue;break}if(B===qhe){if(h=M.isGlob=!0,I=!0,i===!0)continue;break}if(B===oYe){for(;P()!==!0&&(Y=R());){if(Y===Wx){A=M.backslashes=!0,R();continue}if(Y===lYe){m=M.isBracket=!0,h=M.isGlob=!0,I=!0;break}}if(i===!0)continue;break}if(n.nonegate!==!0&&B===DG&&l===u){b=M.negated=!0,u++;continue}if(n.noparen!==!0&&B===FG){if(h=M.isGlob=!0,i===!0){for(;P()!==!0&&(B=R());){if(B===FG){A=M.backslashes=!0,B=R();continue}if(B===$he){I=!0;break}}continue}break}if(h===!0){if(I=!0,i===!0)continue;break}}n.noext===!0&&(y=!1,h=!1);let N=c,k="",O="";u>0&&(k=c.slice(0,u),c=c.slice(u),d-=u),N&&h===!0&&d>0?(N=c.slice(0,d),O=c.slice(d)):h===!0?(N="",O=c):N=c,N&&N!==""&&N!=="/"&&N!==c&&Ghe(N.charCodeAt(N.length-1))&&(N=N.slice(0,-1)),n.unescape===!0&&(O&&(O=Bhe.removeBackslashes(O)),N&&A===!0&&(N=Bhe.removeBackslashes(N)));let $={prefix:k,input:t,start:u,base:N,glob:O,isBrace:p,isBracket:m,isGlob:h,isExtglob:y,isGlobstar:v,negated:b,negatedExtglob:S};if(n.tokens===!0&&($.maxDepth=0,Ghe(B)||o.push(M),$.tokens=o),n.parts===!0||n.tokens===!0){let Y;for(let L=0;L<s.length;L++){let C=Y?Y+1:u,G=s[L],le=t.slice(C,G);n.tokens&&(L===0&&u!==0?(o[L].isPrefix=!0,o[L].value=k):o[L].value=le,Hhe(o[L]),$.maxDepth+=o[L].depth),(L!==0||le!=="")&&a.push(le),Y=G}if(Y&&Y+1<t.length){let L=t.slice(Y+1);a.push(L),n.tokens&&(o[o.length-1].value=L,Hhe(o[o.length-1]),$.maxDepth+=o[o.length-1].depth)}$.slashes=s,$.parts=a}return $};Whe.exports=uYe});var Jhe=H((X1t,Xhe)=>{"use strict";var zx=jx(),Di=ek(),{MAX_LENGTH:tk,POSIX_REGEX_SOURCE:dYe,REGEX_NON_SPECIAL_CHARS:pYe,REGEX_SPECIAL_CHARS_BACKREF:fYe,REPLACEMENTS:Vhe}=zx,hYe=(t,e)=>{if(typeof e.expandRange=="function")return e.expandRange(...t,e);t.sort();let n=`[${t.join("-")}]`;try{new RegExp(n)}catch{return t.map(i=>Di.escapeRegex(i)).join("..")}return n},Sv=(t,e)=>`Missing ${t}: "${e}" - use "\\\\${e}" to match literal characters`,Khe=t=>{let e=[],n=0,r=0,i=0,s="",o=!1;for(let a of t){if(o===!0){s+=a,o=!1;continue}if(a==="\\"){s+=a,o=!0;continue}if(a==='"'){i=i===1?0:1,s+=a;continue}if(i===0){if(a==="[")n++;else if(a==="]"&&n>0)n--;else if(n===0){if(a==="(")r++;else if(a===")"&&r>0)r--;else if(a==="|"&&r===0){e.push(s),s="";continue}}}s+=a}return e.push(s),e},mYe=t=>{let e=!1;for(let n of t){if(e===!0){e=!1;continue}if(n==="\\"){e=!0;continue}if(/[?*+@!()[\]{}]/.test(n))return!1}return!0},Yhe=t=>{let e=t.trim(),n=!0;for(;n===!0;)n=!1,/^@\([^\\()[\]{}|]+\)$/.test(e)&&(e=e.slice(2,-1),n=!0);if(mYe(e))return e.replace(/\\(.)/g,"$1")},gYe=t=>{let e=t.map(Yhe).filter(Boolean);for(let n=0;n<e.length;n++)for(let r=n+1;r<e.length;r++){let i=e[n],s=e[r],o=i[0];if(!(!o||i!==o.repeat(i.length)||s!==o.repeat(s.length))&&(i===s||i.startsWith(s)||s.startsWith(i)))return!0}return!1},UG=(t,e=!0)=>{if(t[0]!=="+"&&t[0]!=="*"||t[1]!=="(")return;let n=0,r=0,i=0,s=!1;for(let o=1;o<t.length;o++){let a=t[o];if(s===!0){s=!1;continue}if(a==="\\"){s=!0;continue}if(a==='"'){i=i===1?0:1;continue}if(i!==1){if(a==="["){n++;continue}if(a==="]"&&n>0){n--;continue}if(!(n>0)){if(a==="("){r++;continue}if(a===")"&&(r--,r===0))return e===!0&&o!==t.length-1?void 0:{type:t[0],body:t.slice(2,o),end:o}}}}},yYe=t=>{let e=0,n=[];for(;e<t.length;){let i=UG(t.slice(e),!1);if(!i||i.type!=="*")return;let s=Khe(i.body).map(a=>a.trim());if(s.length!==1)return;let o=Yhe(s[0]);if(!o||o.length!==1)return;n.push(o),e+=i.end+1}return n.length<1?void 0:`${n.length===1?Di.escapeRegex(n[0]):`[${n.map(i=>Di.escapeRegex(i)).join("")}]`}*`},vYe=t=>{let e=0,n=t.trim(),r=UG(n);for(;r;)e++,n=r.body.trim(),r=UG(n);return e},_Ye=(t,e)=>{if(e.maxExtglobRecursion===!1)return{risky:!1};let n=typeof e.maxExtglobRecursion=="number"?e.maxExtglobRecursion:zx.DEFAULT_MAX_EXTGLOB_RECURSION,r=Khe(t).map(i=>i.trim());if(r.length>1&&(r.some(i=>i==="")||r.some(i=>/^[*?]+$/.test(i))||gYe(r)))return{risky:!0};for(let i of r){let s=yYe(i);if(s)return{risky:!0,safeOutput:s};if(vYe(i)>n)return{risky:!0}}return{risky:!1}},BG=(t,e)=>{if(typeof t!="string")throw new TypeError("Expected a string");t=Vhe[t]||t;let n={...e},r=typeof n.maxLength=="number"?Math.min(tk,n.maxLength):tk,i=t.length;if(i>r)throw new SyntaxError(`Input length: ${i}, exceeds maximum allowed length: ${r}`);let s={type:"bos",value:"",output:n.prepend||""},o=[s],a=n.capture?"":"?:",c=Di.isWindows(e),l=zx.globChars(c),u=zx.extglobChars(l),{DOT_LITERAL:d,PLUS_LITERAL:p,SLASH_LITERAL:m,ONE_CHAR:h,DOTS_SLASH:y,NO_DOT:v,NO_DOT_SLASH:E,NO_DOTS_SLASH:A,QMARK:b,QMARK_NO_DOT:S,STAR:I,START_ANCHOR:F}=l,D=q=>`(${a}(?:(?!${F}${q.dot?y:d}).)*?)`,B=n.dot?"":v,M=n.dot?b:S,P=n.bash===!0?D(n):I;n.capture&&(P=`(${P})`),typeof n.noext=="boolean"&&(n.noextglob=n.noext);let x={input:t,index:-1,start:0,dot:n.dot===!0,consumed:"",output:"",prefix:"",backtrack:!1,negated:!1,brackets:0,braces:0,parens:0,quotes:0,globstar:!1,tokens:o};t=Di.removePrefix(t,x),i=t.length;let R=[],N=[],k=[],O=s,$,Y=()=>x.index===i-1,L=x.peek=(q=1)=>t[x.index+q],C=x.advance=()=>t[++x.index]||"",G=()=>t.slice(x.index+1),le=(q="",V=0)=>{x.consumed+=q,x.index+=V},ce=q=>{x.output+=q.output!=null?q.output:q.value,le(q.value)},J=()=>{let q=1;for(;L()==="!"&&(L(2)!=="("||L(3)==="?");)C(),x.start++,q++;return q%2===0?!1:(x.negated=!0,x.start++,!0)},fe=q=>{x[q]++,k.push(q)},we=q=>{x[q]--,k.pop()},xe=q=>{if(O.type==="globstar"){let V=x.braces>0&&(q.type==="comma"||q.type==="brace"),W=q.extglob===!0||R.length&&(q.type==="pipe"||q.type==="paren");q.type!=="slash"&&q.type!=="paren"&&!V&&!W&&(x.output=x.output.slice(0,-O.output.length),O.type="star",O.value="*",O.output=P,x.output+=O.output)}if(R.length&&q.type!=="paren"&&(R[R.length-1].inner+=q.value),(q.value||q.output)&&ce(q),O&&O.type==="text"&&q.type==="text"){O.value+=q.value,O.output=(O.output||"")+q.value;return}q.prev=O,o.push(q),O=q},Ue=(q,V)=>{let W={...u[V],conditions:1,inner:""};W.prev=O,W.parens=x.parens,W.output=x.output,W.startIndex=x.index,W.tokensIndex=o.length;let Z=(n.capture?"(":"")+W.open;fe("parens"),xe({type:q,value:V,output:x.output?"":h}),xe({type:"paren",extglob:!0,value:C(),output:Z}),R.push(W)},ke=q=>{let V=t.slice(q.startIndex,x.index+1),W=t.slice(q.startIndex+2,x.index),Z=_Ye(W,n);if((q.type==="plus"||q.type==="star")&&Z.risky){let oe=Z.safeOutput?(q.output?"":h)+(n.capture?`(${Z.safeOutput})`:Z.safeOutput):void 0,ie=o[q.tokensIndex];ie.type="text",ie.value=V,ie.output=oe||Di.escapeRegex(V);for(let se=q.tokensIndex+1;se<o.length;se++)o[se].value="",o[se].output="",delete o[se].suffix;x.output=q.output+ie.output,x.backtrack=!0,xe({type:"paren",extglob:!0,value:$,output:""}),we("parens");return}let ee=q.close+(n.capture?")":""),te;if(q.type==="negate"){let oe=P;if(q.inner&&q.inner.length>1&&q.inner.includes("/")&&(oe=D(n)),(oe!==P||Y()||/^\)+$/.test(G()))&&(ee=q.close=`)$))${oe}`),q.inner.includes("*")&&(te=G())&&/^\.[^\\/.]+$/.test(te)){let ie=BG(te,{...e,fastpaths:!1}).output;ee=q.close=`)${ie})${oe})`}q.prev.type==="bos"&&(x.negatedExtglob=!0)}xe({type:"paren",extglob:!0,value:$,output:ee}),we("parens")};if(n.fastpaths!==!1&&!/(^[*!]|[/()[\]{}"])/.test(t)){let q=!1,V=t.replace(fYe,(W,Z,ee,te,oe,ie)=>te==="\\"?(q=!0,W):te==="?"?Z?Z+te+(oe?b.repeat(oe.length):""):ie===0?M+(oe?b.repeat(oe.length):""):b.repeat(ee.length):te==="."?d.repeat(ee.length):te==="*"?Z?Z+te+(oe?P:""):P:Z?W:`\\${W}`);return q===!0&&(n.unescape===!0?V=V.replace(/\\/g,""):V=V.replace(/\\+/g,W=>W.length%2===0?"\\\\":W?"\\":"")),V===t&&n.contains===!0?(x.output=t,x):(x.output=Di.wrapOutput(V,x,e),x)}for(;!Y();){if($=C(),$==="\0")continue;if($==="\\"){let W=L();if(W==="/"&&n.bash!==!0||W==="."||W===";")continue;if(!W){$+="\\",xe({type:"text",value:$});continue}let Z=/^\\+/.exec(G()),ee=0;if(Z&&Z[0].length>2&&(ee=Z[0].length,x.index+=ee,ee%2!==0&&($+="\\")),n.unescape===!0?$=C():$+=C(),x.brackets===0){xe({type:"text",value:$});continue}}if(x.brackets>0&&($!=="]"||O.value==="["||O.value==="[^")){if(n.posix!==!1&&$===":"){let W=O.value.slice(1);if(W.includes("[")&&(O.posix=!0,W.includes(":"))){let Z=O.value.lastIndexOf("["),ee=O.value.slice(0,Z),te=O.value.slice(Z+2),oe=dYe[te];if(oe){O.value=ee+oe,x.backtrack=!0,C(),!s.output&&o.indexOf(O)===1&&(s.output=h);continue}}}($==="["&&L()!==":"||$==="-"&&L()==="]")&&($=`\\${$}`),$==="]"&&(O.value==="["||O.value==="[^")&&($=`\\${$}`),n.posix===!0&&$==="!"&&O.value==="["&&($="^"),O.value+=$,ce({value:$});continue}if(x.quotes===1&&$!=='"'){$=Di.escapeRegex($),O.value+=$,ce({value:$});continue}if($==='"'){x.quotes=x.quotes===1?0:1,n.keepQuotes===!0&&xe({type:"text",value:$});continue}if($==="("){fe("parens"),xe({type:"paren",value:$});continue}if($===")"){if(x.parens===0&&n.strictBrackets===!0)throw new SyntaxError(Sv("opening","("));let W=R[R.length-1];if(W&&x.parens===W.parens+1){ke(R.pop());continue}xe({type:"paren",value:$,output:x.parens?")":"\\)"}),we("parens");continue}if($==="["){if(n.nobracket===!0||!G().includes("]")){if(n.nobracket!==!0&&n.strictBrackets===!0)throw new SyntaxError(Sv("closing","]"));$=`\\${$}`}else fe("brackets");xe({type:"bracket",value:$});continue}if($==="]"){if(n.nobracket===!0||O&&O.type==="bracket"&&O.value.length===1){xe({type:"text",value:$,output:`\\${$}`});continue}if(x.brackets===0){if(n.strictBrackets===!0)throw new SyntaxError(Sv("opening","["));xe({type:"text",value:$,output:`\\${$}`});continue}we("brackets");let W=O.value.slice(1);if(O.posix!==!0&&W[0]==="^"&&!W.includes("/")&&($=`/${$}`),O.value+=$,ce({value:$}),n.literalBrackets===!1||Di.hasRegexChars(W))continue;let Z=Di.escapeRegex(O.value);if(x.output=x.output.slice(0,-O.value.length),n.literalBrackets===!0){x.output+=Z,O.value=Z;continue}O.value=`(${a}${Z}|${O.value})`,x.output+=O.value;continue}if($==="{"&&n.nobrace!==!0){fe("braces");let W={type:"brace",value:$,output:"(",outputIndex:x.output.length,tokensIndex:x.tokens.length};N.push(W),xe(W);continue}if($==="}"){let W=N[N.length-1];if(n.nobrace===!0||!W){xe({type:"text",value:$,output:$});continue}let Z=")";if(W.dots===!0){let ee=o.slice(),te=[];for(let oe=ee.length-1;oe>=0&&(o.pop(),ee[oe].type!=="brace");oe--)ee[oe].type!=="dots"&&te.unshift(ee[oe].value);Z=hYe(te,n),x.backtrack=!0}if(W.comma!==!0&&W.dots!==!0){let ee=x.output.slice(0,W.outputIndex),te=x.tokens.slice(W.tokensIndex);W.value=W.output="\\{",$=Z="\\}",x.output=ee;for(let oe of te)x.output+=oe.output||oe.value}xe({type:"brace",value:$,output:Z}),we("braces"),N.pop();continue}if($==="|"){R.length>0&&R[R.length-1].conditions++,xe({type:"text",value:$});continue}if($===","){let W=$,Z=N[N.length-1];Z&&k[k.length-1]==="braces"&&(Z.comma=!0,W="|"),xe({type:"comma",value:$,output:W});continue}if($==="/"){if(O.type==="dot"&&x.index===x.start+1){x.start=x.index+1,x.consumed="",x.output="",o.pop(),O=s;continue}xe({type:"slash",value:$,output:m});continue}if($==="."){if(x.braces>0&&O.type==="dot"){O.value==="."&&(O.output=d);let W=N[N.length-1];O.type="dots",O.output+=$,O.value+=$,W.dots=!0;continue}if(x.braces+x.parens===0&&O.type!=="bos"&&O.type!=="slash"){xe({type:"text",value:$,output:d});continue}xe({type:"dot",value:$,output:d});continue}if($==="?"){if(!(O&&O.value==="(")&&n.noextglob!==!0&&L()==="("&&L(2)!=="?"){Ue("qmark",$);continue}if(O&&O.type==="paren"){let Z=L(),ee=$;if(Z==="<"&&!Di.supportsLookbehinds())throw new Error("Node.js v10 or higher is required for regex lookbehinds");(O.value==="("&&!/[!=<:]/.test(Z)||Z==="<"&&!/<([!=]|\w+>)/.test(G()))&&(ee=`\\${$}`),xe({type:"text",value:$,output:ee});continue}if(n.dot!==!0&&(O.type==="slash"||O.type==="bos")){xe({type:"qmark",value:$,output:S});continue}xe({type:"qmark",value:$,output:b});continue}if($==="!"){if(n.noextglob!==!0&&L()==="("&&(L(2)!=="?"||!/[!=<:]/.test(L(3)))){Ue("negate",$);continue}if(n.nonegate!==!0&&x.index===0){J();continue}}if($==="+"){if(n.noextglob!==!0&&L()==="("&&L(2)!=="?"){Ue("plus",$);continue}if(O&&O.value==="("||n.regex===!1){xe({type:"plus",value:$,output:p});continue}if(O&&(O.type==="bracket"||O.type==="paren"||O.type==="brace")||x.parens>0){xe({type:"plus",value:$});continue}xe({type:"plus",value:p});continue}if($==="@"){if(n.noextglob!==!0&&L()==="("&&L(2)!=="?"){xe({type:"at",extglob:!0,value:$,output:""});continue}xe({type:"text",value:$});continue}if($!=="*"){($==="$"||$==="^")&&($=`\\${$}`);let W=pYe.exec(G());W&&($+=W[0],x.index+=W[0].length),xe({type:"text",value:$});continue}if(O&&(O.type==="globstar"||O.star===!0)){O.type="star",O.star=!0,O.value+=$,O.output=P,x.backtrack=!0,x.globstar=!0,le($);continue}let q=G();if(n.noextglob!==!0&&/^\([^?]/.test(q)){Ue("star",$);continue}if(O.type==="star"){if(n.noglobstar===!0){le($);continue}let W=O.prev,Z=W.prev,ee=W.type==="slash"||W.type==="bos",te=Z&&(Z.type==="star"||Z.type==="globstar");if(n.bash===!0&&(!ee||q[0]&&q[0]!=="/")){xe({type:"star",value:$,output:""});continue}let oe=x.braces>0&&(W.type==="comma"||W.type==="brace"),ie=R.length&&(W.type==="pipe"||W.type==="paren");if(!ee&&W.type!=="paren"&&!oe&&!ie){xe({type:"star",value:$,output:""});continue}for(;q.slice(0,3)==="/**";){let se=t[x.index+4];if(se&&se!=="/")break;q=q.slice(3),le("/**",3)}if(W.type==="bos"&&Y()){O.type="globstar",O.value+=$,O.output=D(n),x.output=O.output,x.globstar=!0,le($);continue}if(W.type==="slash"&&W.prev.type!=="bos"&&!te&&Y()){x.output=x.output.slice(0,-(W.output+O.output).length),W.output=`(?:${W.output}`,O.type="globstar",O.output=D(n)+(n.strictSlashes?")":"|$)"),O.value+=$,x.globstar=!0,x.output+=W.output+O.output,le($);continue}if(W.type==="slash"&&W.prev.type!=="bos"&&q[0]==="/"){let se=q[1]!==void 0?"|$":"";x.output=x.output.slice(0,-(W.output+O.output).length),W.output=`(?:${W.output}`,O.type="globstar",O.output=`${D(n)}${m}|${m}${se})`,O.value+=$,x.output+=W.output+O.output,x.globstar=!0,le($+C()),xe({type:"slash",value:"/",output:""});continue}if(W.type==="bos"&&q[0]==="/"){O.type="globstar",O.value+=$,O.output=`(?:^|${m}|${D(n)}${m})`,x.output=O.output,x.globstar=!0,le($+C()),xe({type:"slash",value:"/",output:""});continue}x.output=x.output.slice(0,-O.output.length),O.type="globstar",O.output=D(n),O.value+=$,x.output+=O.output,x.globstar=!0,le($);continue}let V={type:"star",value:$,output:P};if(n.bash===!0){V.output=".*?",(O.type==="bos"||O.type==="slash")&&(V.output=B+V.output),xe(V);continue}if(O&&(O.type==="bracket"||O.type==="paren")&&n.regex===!0){V.output=$,xe(V);continue}(x.index===x.start||O.type==="slash"||O.type==="dot")&&(O.type==="dot"?(x.output+=E,O.output+=E):n.dot===!0?(x.output+=A,O.output+=A):(x.output+=B,O.output+=B),L()!=="*"&&(x.output+=h,O.output+=h)),xe(V)}for(;x.brackets>0;){if(n.strictBrackets===!0)throw new SyntaxError(Sv("closing","]"));x.output=Di.escapeLast(x.output,"["),we("brackets")}for(;x.parens>0;){if(n.strictBrackets===!0)throw new SyntaxError(Sv("closing",")"));x.output=Di.escapeLast(x.output,"("),we("parens")}for(;x.braces>0;){if(n.strictBrackets===!0)throw new SyntaxError(Sv("closing","}"));x.output=Di.escapeLast(x.output,"{"),we("braces")}if(n.strictSlashes!==!0&&(O.type==="star"||O.type==="bracket")&&xe({type:"maybe_slash",value:"",output:`${m}?`}),x.backtrack===!0){x.output="";for(let q of x.tokens)x.output+=q.output!=null?q.output:q.value,q.suffix&&(x.output+=q.suffix)}return x};BG.fastpaths=(t,e)=>{let n={...e},r=typeof n.maxLength=="number"?Math.min(tk,n.maxLength):tk,i=t.length;if(i>r)throw new SyntaxError(`Input length: ${i}, exceeds maximum allowed length: ${r}`);t=Vhe[t]||t;let s=Di.isWindows(e),{DOT_LITERAL:o,SLASH_LITERAL:a,ONE_CHAR:c,DOTS_SLASH:l,NO_DOT:u,NO_DOTS:d,NO_DOTS_SLASH:p,STAR:m,START_ANCHOR:h}=zx.globChars(s),y=n.dot?d:u,v=n.dot?p:u,E=n.capture?"":"?:",A={negated:!1,prefix:""},b=n.bash===!0?".*?":m;n.capture&&(b=`(${b})`);let S=B=>B.noglobstar===!0?b:`(${E}(?:(?!${h}${B.dot?l:o}).)*?)`,I=B=>{switch(B){case"*":return`${y}${c}${b}`;case".*":return`${o}${c}${b}`;case"*.*":return`${y}${b}${o}${c}${b}`;case"*/*":return`${y}${b}${a}${c}${v}${b}`;case"**":return y+S(n);case"**/*":return`(?:${y}${S(n)}${a})?${v}${c}${b}`;case"**/*.*":return`(?:${y}${S(n)}${a})?${v}${b}${o}${c}${b}`;case"**/.*":return`(?:${y}${S(n)}${a})?${o}${c}${b}`;default:{let M=/^(.*?)\.(\w+)$/.exec(B);if(!M)return;let P=I(M[1]);return P?P+o+M[2]:void 0}}},F=Di.removePrefix(t,A),D=I(F);return D&&n.strictSlashes!==!0&&(D+=`${a}?`),D};Xhe.exports=BG});var Zhe=H((J1t,Qhe)=>{"use strict";var wYe=require("path"),xYe=zhe(),qG=Jhe(),$G=ek(),EYe=jx(),bYe=t=>t&&typeof t=="object"&&!Array.isArray(t),Ar=(t,e,n=!1)=>{if(Array.isArray(t)){let u=t.map(p=>Ar(p,e,n));return p=>{for(let m of u){let h=m(p);if(h)return h}return!1}}let r=bYe(t)&&t.tokens&&t.input;if(t===""||typeof t!="string"&&!r)throw new TypeError("Expected pattern to be a non-empty string");let i=e||{},s=$G.isWindows(e),o=r?Ar.compileRe(t,e):Ar.makeRe(t,e,!1,!0),a=o.state;delete o.state;let c=()=>!1;if(i.ignore){let u={...e,ignore:null,onMatch:null,onResult:null};c=Ar(i.ignore,u,n)}let l=(u,d=!1)=>{let{isMatch:p,match:m,output:h}=Ar.test(u,o,e,{glob:t,posix:s}),y={glob:t,state:a,regex:o,posix:s,input:u,output:h,match:m,isMatch:p};return typeof i.onResult=="function"&&i.onResult(y),p===!1?(y.isMatch=!1,d?y:!1):c(u)?(typeof i.onIgnore=="function"&&i.onIgnore(y),y.isMatch=!1,d?y:!1):(typeof i.onMatch=="function"&&i.onMatch(y),d?y:!0)};return n&&(l.state=a),l};Ar.test=(t,e,n,{glob:r,posix:i}={})=>{if(typeof t!="string")throw new TypeError("Expected input to be a string");if(t==="")return{isMatch:!1,output:""};let s=n||{},o=s.format||(i?$G.toPosixSlashes:null),a=t===r,c=a&&o?o(t):t;return a===!1&&(c=o?o(t):t,a=c===r),(a===!1||s.capture===!0)&&(s.matchBase===!0||s.basename===!0?a=Ar.matchBase(t,e,n,i):a=e.exec(c)),{isMatch:!!a,match:a,output:c}};Ar.matchBase=(t,e,n,r=$G.isWindows(n))=>(e instanceof RegExp?e:Ar.makeRe(e,n)).test(wYe.basename(t));Ar.isMatch=(t,e,n)=>Ar(e,n)(t);Ar.parse=(t,e)=>Array.isArray(t)?t.map(n=>Ar.parse(n,e)):qG(t,{...e,fastpaths:!1});Ar.scan=(t,e)=>xYe(t,e);Ar.compileRe=(t,e,n=!1,r=!1)=>{if(n===!0)return t.output;let i=e||{},s=i.contains?"":"^",o=i.contains?"":"$",a=`${s}(?:${t.output})${o}`;t&&t.negated===!0&&(a=`^(?!${a}).*$`);let c=Ar.toRegex(a,e);return r===!0&&(c.state=t),c};Ar.makeRe=(t,e={},n=!1,r=!1)=>{if(!t||typeof t!="string")throw new TypeError("Expected a non-empty string");let i={negated:!1,fastpaths:!0};return e.fastpaths!==!1&&(t[0]==="."||t[0]==="*")&&(i.output=qG.fastpaths(t,e)),i.output||(i=qG(t,e)),Ar.compileRe(i,e,n,r)};Ar.toRegex=(t,e)=>{try{let n=e||{};return new RegExp(t,n.flags||(n.nocase?"i":""))}catch(n){if(e&&e.debug===!0)throw n;return/$^/}};Ar.constants=EYe;Qhe.exports=Ar});var GG=H((Q1t,eme)=>{"use strict";eme.exports=Zhe()});var cme=H((Z1t,ame)=>{"use strict";var Kx=require("fs"),{Readable:SYe}=require("stream"),Vx=require("path"),{promisify:sk}=require("util"),HG=GG(),TYe=sk(Kx.readdir),AYe=sk(Kx.stat),tme=sk(Kx.lstat),CYe=sk(Kx.realpath),RYe="!",sme="READDIRP_RECURSIVE_ERROR",IYe=new Set(["ENOENT","EPERM","EACCES","ELOOP",sme]),jG="files",ome="directories",rk="files_directories",nk="all",nme=[jG,ome,rk,nk],kYe=t=>IYe.has(t.code),[rme,PYe]=process.versions.node.split(".").slice(0,2).map(t=>Number.parseInt(t,10)),MYe=process.platform==="win32"&&(rme>10||rme===10&&PYe>=5),ime=t=>{if(t!==void 0){if(typeof t=="function")return t;if(typeof t=="string"){let e=HG(t.trim());return n=>e(n.basename)}if(Array.isArray(t)){let e=[],n=[];for(let r of t){let i=r.trim();i.charAt(0)===RYe?n.push(HG(i.slice(1))):e.push(HG(i))}return n.length>0?e.length>0?r=>e.some(i=>i(r.basename))&&!n.some(i=>i(r.basename)):r=>!n.some(i=>i(r.basename)):r=>e.some(i=>i(r.basename))}}},ik=class t extends SYe{static get defaultOptions(){return{root:".",fileFilter:e=>!0,directoryFilter:e=>!0,type:jG,lstat:!1,depth:2147483648,alwaysStat:!1}}constructor(e={}){super({objectMode:!0,autoDestroy:!0,highWaterMark:e.highWaterMark||4096});let n={...t.defaultOptions,...e},{root:r,type:i}=n;this._fileFilter=ime(n.fileFilter),this._directoryFilter=ime(n.directoryFilter);let s=n.lstat?tme:AYe;MYe?this._stat=o=>s(o,{bigint:!0}):this._stat=s,this._maxDepth=n.depth,this._wantsDir=[ome,rk,nk].includes(i),this._wantsFile=[jG,rk,nk].includes(i),this._wantsEverything=i===nk,this._root=Vx.resolve(r),this._isDirent="Dirent"in Kx&&!n.alwaysStat,this._statsProp=this._isDirent?"dirent":"stats",this._rdOptions={encoding:"utf8",withFileTypes:this._isDirent},this.parents=[this._exploreDir(r,1)],this.reading=!1,this.parent=void 0}async _read(e){if(!this.reading){this.reading=!0;try{for(;!this.destroyed&&e>0;){let{path:n,depth:r,files:i=[]}=this.parent||{};if(i.length>0){let s=i.splice(0,e).map(o=>this._formatEntry(o,n));for(let o of await Promise.all(s)){if(this.destroyed)return;let a=await this._getEntryType(o);a==="directory"&&this._directoryFilter(o)?(r<=this._maxDepth&&this.parents.push(this._exploreDir(o.fullPath,r+1)),this._wantsDir&&(this.push(o),e--)):(a==="file"||this._includeAsFile(o))&&this._fileFilter(o)&&this._wantsFile&&(this.push(o),e--)}}else{let s=this.parents.pop();if(!s){this.push(null);break}if(this.parent=await s,this.destroyed)return}}}catch(n){this.destroy(n)}finally{this.reading=!1}}}async _exploreDir(e,n){let r;try{r=await TYe(e,this._rdOptions)}catch(i){this._onError(i)}return{files:r,depth:n,path:e}}async _formatEntry(e,n){let r;try{let i=this._isDirent?e.name:e,s=Vx.resolve(Vx.join(n,i));r={path:Vx.relative(this._root,s),fullPath:s,basename:i},r[this._statsProp]=this._isDirent?e:await this._stat(s)}catch(i){this._onError(i)}return r}_onError(e){kYe(e)&&!this.destroyed?this.emit("warn",e):this.destroy(e)}async _getEntryType(e){let n=e&&e[this._statsProp];if(n){if(n.isFile())return"file";if(n.isDirectory())return"directory";if(n&&n.isSymbolicLink()){let r=e.fullPath;try{let i=await CYe(r),s=await tme(i);if(s.isFile())return"file";if(s.isDirectory()){let o=i.length;if(r.startsWith(i)&&r.substr(o,1)===Vx.sep){let a=new Error(`Circular symlink detected: "${r}" points to "${i}"`);return a.code=sme,this._onError(a)}return"directory"}}catch(i){this._onError(i)}}}}_includeAsFile(e){let n=e&&e[this._statsProp];return n&&this._wantsEverything&&!n.isDirectory()}},Tv=(t,e={})=>{let n=e.entryType||e.type;if(n==="both"&&(n=rk),n&&(e.type=n),t){if(typeof t!="string")throw new TypeError("readdirp: root argument must be a string. Usage: readdirp(root, options)");if(n&&!nme.includes(n))throw new Error(`readdirp: Invalid type passed. Use one of ${nme.join(", ")}`)}else throw new Error("readdirp: root argument is required. Usage: readdirp(root, options)");return e.root=t,new ik(e)},OYe=(t,e={})=>new Promise((n,r)=>{let i=[];Tv(t,e).on("data",s=>i.push(s)).on("end",()=>n(i)).on("error",s=>r(s))});Tv.promise=OYe;Tv.ReaddirpStream=ik;Tv.default=Tv;ame.exports=Tv});var Av=H((eNt,lme)=>{lme.exports=function(t,e){if(typeof t!="string")throw new TypeError("expected path to be a string");if(t==="\\"||t==="/")return"/";var n=t.length;if(n<=1)return t;var r="";if(n>4&&t[3]==="\\"){var i=t[2];(i==="?"||i===".")&&t.slice(0,2)==="\\\\"&&(t=t.slice(2),r="//")}var s=t.split(/[/\\]+/);return e!==!1&&s[s.length-1]===""&&s.pop(),r+s.join("/")}});var mme=H((fme,hme)=>{"use strict";Object.defineProperty(fme,"__esModule",{value:!0});var pme=GG(),NYe=Av(),ume="!",DYe={returnIndex:!1},LYe=t=>Array.isArray(t)?t:[t],FYe=(t,e)=>{if(typeof t=="function")return t;if(typeof t=="string"){let n=pme(t,e);return r=>t===r||n(r)}return t instanceof RegExp?n=>t.test(n):n=>!1},dme=(t,e,n,r)=>{let i=Array.isArray(n),s=i?n[0]:n;if(!i&&typeof s!="string")throw new TypeError("anymatch: second argument must be a string: got "+Object.prototype.toString.call(s));let o=NYe(s,!1);for(let c=0;c<e.length;c++){let l=e[c];if(l(o))return r?-1:!1}let a=i&&[o].concat(n.slice(1));for(let c=0;c<t.length;c++){let l=t[c];if(i?l(...a):l(o))return r?c:!0}return r?-1:!1},WG=(t,e,n=DYe)=>{if(t==null)throw new TypeError("anymatch: specify first argument");let r=typeof n=="boolean"?{returnIndex:n}:n,i=r.returnIndex||!1,s=LYe(t),o=s.filter(c=>typeof c=="string"&&c.charAt(0)===ume).map(c=>c.slice(1)).map(c=>pme(c,r)),a=s.filter(c=>typeof c!="string"||typeof c=="string"&&c.charAt(0)!==ume).map(c=>FYe(c,r));return e==null?(c,l=!1)=>dme(a,o,c,typeof l=="boolean"?l:!1):dme(a,o,e,i)};WG.default=WG;hme.exports=WG});var yme=H((tNt,gme)=>{gme.exports=function(e){if(typeof e!="string"||e==="")return!1;for(var n;n=/(\\).|([@?!+*]\(.*\))/g.exec(e);){if(n[2])return!0;e=e.slice(n.index+n[0].length)}return!1}});var zG=H((nNt,_me)=>{var UYe=yme(),vme={"{":"}","(":")","[":"]"},BYe=function(t){if(t[0]==="!")return!0;for(var e=0,n=-2,r=-2,i=-2,s=-2,o=-2;e<t.length;){if(t[e]==="*"||t[e+1]==="?"&&/[\].+)]/.test(t[e])||r!==-1&&t[e]==="["&&t[e+1]!=="]"&&(r<e&&(r=t.indexOf("]",e)),r>e&&(o===-1||o>r||(o=t.indexOf("\\",e),o===-1||o>r)))||i!==-1&&t[e]==="{"&&t[e+1]!=="}"&&(i=t.indexOf("}",e),i>e&&(o=t.indexOf("\\",e),o===-1||o>i))||s!==-1&&t[e]==="("&&t[e+1]==="?"&&/[:!=]/.test(t[e+2])&&t[e+3]!==")"&&(s=t.indexOf(")",e),s>e&&(o=t.indexOf("\\",e),o===-1||o>s))||n!==-1&&t[e]==="("&&t[e+1]!=="|"&&(n<e&&(n=t.indexOf("|",e)),n!==-1&&t[n+1]!==")"&&(s=t.indexOf(")",n),s>n&&(o=t.indexOf("\\",n),o===-1||o>s))))return!0;if(t[e]==="\\"){var a=t[e+1];e+=2;var c=vme[a];if(c){var l=t.indexOf(c,e);l!==-1&&(e=l+1)}if(t[e]==="!")return!0}else e++}return!1},qYe=function(t){if(t[0]==="!")return!0;for(var e=0;e<t.length;){if(/[*?{}()[\]]/.test(t[e]))return!0;if(t[e]==="\\"){var n=t[e+1];e+=2;var r=vme[n];if(r){var i=t.indexOf(r,e);i!==-1&&(e=i+1)}if(t[e]==="!")return!0}else e++}return!1};_me.exports=function(e,n){if(typeof e!="string"||e==="")return!1;if(UYe(e))return!0;var r=BYe;return n&&n.strict===!1&&(r=qYe),r(e)}});var xme=H((rNt,wme)=>{"use strict";var $Ye=zG(),GYe=require("path").posix.dirname,HYe=require("os").platform()==="win32",VG="/",jYe=/\\/g,WYe=/[\{\[].*[\}\]]$/,zYe=/(^|[^\\])([\{\[]|\([^\)]+$)/,VYe=/\\([\!\*\?\|\[\]\(\)\{\}])/g;wme.exports=function(e,n){var r=Object.assign({flipBackslashes:!0},n);r.flipBackslashes&&HYe&&e.indexOf(VG)<0&&(e=e.replace(jYe,VG)),WYe.test(e)&&(e+=VG),e+="a";do e=GYe(e);while($Ye(e)||zYe.test(e));return e.replace(VYe,"$1")}});var ok=H(ca=>{"use strict";ca.isInteger=t=>typeof t=="number"?Number.isInteger(t):typeof t=="string"&&t.trim()!==""?Number.isInteger(Number(t)):!1;ca.find=(t,e)=>t.nodes.find(n=>n.type===e);ca.exceedsLimit=(t,e,n=1,r)=>r===!1||!ca.isInteger(t)||!ca.isInteger(e)?!1:(Number(e)-Number(t))/Number(n)>=r;ca.escapeNode=(t,e=0,n)=>{let r=t.nodes[e];r&&(n&&r.type===n||r.type==="open"||r.type==="close")&&r.escaped!==!0&&(r.value="\\"+r.value,r.escaped=!0)};ca.encloseBrace=t=>t.type!=="brace"?!1:t.commas>>0+t.ranges>>0===0?(t.invalid=!0,!0):!1;ca.isInvalidBrace=t=>t.type!=="brace"?!1:t.invalid===!0||t.dollar?!0:t.commas>>0+t.ranges>>0===0||t.open!==!0||t.close!==!0?(t.invalid=!0,!0):!1;ca.isOpenOrClose=t=>t.type==="open"||t.type==="close"?!0:t.open===!0||t.close===!0;ca.reduce=t=>t.reduce((e,n)=>(n.type==="text"&&e.push(n.value),n.type==="range"&&(n.type="text"),e),[]);ca.flatten=(...t)=>{let e=[],n=r=>{for(let i=0;i<r.length;i++){let s=r[i];if(Array.isArray(s)){n(s);continue}s!==void 0&&e.push(s)}return e};return n(t),e}});var ak=H((sNt,bme)=>{"use strict";var Eme=ok();bme.exports=(t,e={})=>{let n=(r,i={})=>{let s=e.escapeInvalid&&Eme.isInvalidBrace(i),o=r.invalid===!0&&e.escapeInvalid===!0,a="";if(r.value)return(s||o)&&Eme.isOpenOrClose(r)?"\\"+r.value:r.value;if(r.value)return r.value;if(r.nodes)for(let c of r.nodes)a+=n(c);return a};return n(t)}});var Tme=H((oNt,Sme)=>{"use strict";Sme.exports=function(t){return typeof t=="number"?t-t===0:typeof t=="string"&&t.trim()!==""?Number.isFinite?Number.isFinite(+t):isFinite(+t):!1}});var Nme=H((aNt,Ome)=>{"use strict";var Ame=Tme(),Zh=(t,e,n)=>{if(Ame(t)===!1)throw new TypeError("toRegexRange: expected the first argument to be a number");if(e===void 0||t===e)return String(t);if(Ame(e)===!1)throw new TypeError("toRegexRange: expected the second argument to be a number.");let r={relaxZeros:!0,...n};typeof r.strictZeros=="boolean"&&(r.relaxZeros=r.strictZeros===!1);let i=String(r.relaxZeros),s=String(r.shorthand),o=String(r.capture),a=String(r.wrap),c=t+":"+e+"="+i+s+o+a;if(Zh.cache.hasOwnProperty(c))return Zh.cache[c].result;let l=Math.min(t,e),u=Math.max(t,e);if(Math.abs(l-u)===1){let y=t+"|"+e;return r.capture?`(${y})`:r.wrap===!1?y:`(?:${y})`}let d=Mme(t)||Mme(e),p={min:t,max:e,a:l,b:u},m=[],h=[];if(d&&(p.isPadded=d,p.maxLen=String(p.max).length),l<0){let y=u<0?Math.abs(u):1;h=Cme(y,Math.abs(l),p,r),l=p.a=0}return u>=0&&(m=Cme(l,u,p,r)),p.negatives=h,p.positives=m,p.result=KYe(h,m,r),r.capture===!0?p.result=`(${p.result})`:r.wrap!==!1&&m.length+h.length>1&&(p.result=`(?:${p.result})`),Zh.cache[c]=p,p.result};function KYe(t,e,n){let r=KG(t,e,"-",!1,n)||[],i=KG(e,t,"",!1,n)||[],s=KG(t,e,"-?",!0,n)||[];return r.concat(s).concat(i).join("|")}function YYe(t,e){let n=1,r=1,i=Ime(t,n),s=new Set([e]);for(;t<=i&&i<=e;)s.add(i),n+=1,i=Ime(t,n);for(i=kme(e+1,r)-1;t<i&&i<=e;)s.add(i),r+=1,i=kme(e+1,r)-1;return s=[...s],s.sort(QYe),s}function XYe(t,e,n){if(t===e)return{pattern:t,count:[],digits:0};let r=JYe(t,e),i=r.length,s="",o=0;for(let a=0;a<i;a++){let[c,l]=r[a];c===l?s+=c:c!=="0"||l!=="9"?s+=ZYe(c,l,n):o++}return o&&(s+=n.shorthand===!0?"\\d":"[0-9]"),{pattern:s,count:[o],digits:i}}function Cme(t,e,n,r){let i=YYe(t,e),s=[],o=t,a;for(let c=0;c<i.length;c++){let l=i[c],u=XYe(String(o),String(l),r),d="";if(!n.isPadded&&a&&a.pattern===u.pattern){a.count.length>1&&a.count.pop(),a.count.push(u.count[0]),a.string=a.pattern+Pme(a.count),o=l+1;continue}n.isPadded&&(d=eXe(l,n,r)),u.string=d+u.pattern+Pme(u.count),s.push(u),o=l+1,a=u}return s}function KG(t,e,n,r,i){let s=[];for(let o of t){let{string:a}=o;!r&&!Rme(e,"string",a)&&s.push(n+a),r&&Rme(e,"string",a)&&s.push(n+a)}return s}function JYe(t,e){let n=[];for(let r=0;r<t.length;r++)n.push([t[r],e[r]]);return n}function QYe(t,e){return t>e?1:e>t?-1:0}function Rme(t,e,n){return t.some(r=>r[e]===n)}function Ime(t,e){return Number(String(t).slice(0,-e)+"9".repeat(e))}function kme(t,e){return t-t%Math.pow(10,e)}function Pme(t){let[e=0,n=""]=t;return n||e>1?`{${e+(n?","+n:"")}}`:""}function ZYe(t,e,n){return`[${t}${e-t===1?"":"-"}${e}]`}function Mme(t){return/^-?(0+)\d/.test(t)}function eXe(t,e,n){if(!e.isPadded)return t;let r=Math.abs(e.maxLen-String(t).length),i=n.relaxZeros!==!1;switch(r){case 0:return"";case 1:return i?"0?":"0";case 2:return i?"0{0,2}":"00";default:return i?`0{0,${r}}`:`0{${r}}`}}Zh.cache={};Zh.clearCache=()=>Zh.cache={};Ome.exports=Zh});var JG=H((cNt,$me)=>{"use strict";var tXe=require("util"),Lme=Nme(),Dme=t=>t!==null&&typeof t=="object"&&!Array.isArray(t),nXe=t=>e=>t===!0?Number(e):String(e),YG=t=>typeof t=="number"||typeof t=="string"&&t!=="",Yx=t=>Number.isInteger(+t),XG=t=>{let e=`${t}`,n=-1;if(e[0]==="-"&&(e=e.slice(1)),e==="0")return!1;for(;e[++n]==="0";);return n>0},rXe=(t,e,n)=>typeof t=="string"||typeof e=="string"?!0:n.stringify===!0,iXe=(t,e,n)=>{if(e>0){let r=t[0]==="-"?"-":"";r&&(t=t.slice(1)),t=r+t.padStart(r?e-1:e,"0")}return n===!1?String(t):t},lk=(t,e)=>{let n=t[0]==="-"?"-":"";for(n&&(t=t.slice(1),e--);t.length<e;)t="0"+t;return n?"-"+t:t},sXe=(t,e,n)=>{t.negatives.sort((a,c)=>a<c?-1:a>c?1:0),t.positives.sort((a,c)=>a<c?-1:a>c?1:0);let r=e.capture?"":"?:",i="",s="",o;return t.positives.length&&(i=t.positives.map(a=>lk(String(a),n)).join("|")),t.negatives.length&&(s=`-(${r}${t.negatives.map(a=>lk(String(a),n)).join("|")})`),i&&s?o=`${i}|${s}`:o=i||s,e.wrap?`(${r}${o})`:o},Fme=(t,e,n,r)=>{if(n)return Lme(t,e,{wrap:!1,...r});let i=String.fromCharCode(t);if(t===e)return i;let s=String.fromCharCode(e);return`[${i}-${s}]`},Ume=(t,e,n)=>{if(Array.isArray(t)){let r=n.wrap===!0,i=n.capture?"":"?:";return r?`(${i}${t.join("|")})`:t.join("|")}return Lme(t,e,n)},Bme=(...t)=>new RangeError("Invalid range arguments: "+tXe.inspect(...t)),qme=(t,e,n)=>{if(n.strictRanges===!0)throw Bme([t,e]);return[]},oXe=(t,e)=>{if(e.strictRanges===!0)throw new TypeError(`Expected step "${t}" to be a number`);return[]},aXe=(t,e,n=1,r={})=>{let i=Number(t),s=Number(e);if(!Number.isInteger(i)||!Number.isInteger(s)){if(r.strictRanges===!0)throw Bme([t,e]);return[]}i===0&&(i=0),s===0&&(s=0);let o=i>s,a=String(t),c=String(e),l=String(n);n=Math.max(Math.abs(n),1);let u=XG(a)||XG(c)||XG(l),d=u?Math.max(a.length,c.length,l.length):0,p=u===!1&&rXe(t,e,r)===!1,m=r.transform||nXe(p);if(r.toRegex&&n===1)return Fme(lk(t,d),lk(e,d),!0,r);let h={negatives:[],positives:[]},y=A=>h[A<0?"negatives":"positives"].push(Math.abs(A)),v=[],E=0;for(;o?i>=s:i<=s;)r.toRegex===!0&&n>1?y(i):v.push(iXe(m(i,E),d,p)),i=o?i-n:i+n,E++;return r.toRegex===!0?n>1?sXe(h,r,d):Ume(v,null,{wrap:!1,...r}):v},cXe=(t,e,n=1,r={})=>{if(!Yx(t)&&t.length>1||!Yx(e)&&e.length>1)return qme(t,e,r);let i=r.transform||(p=>String.fromCharCode(p)),s=`${t}`.charCodeAt(0),o=`${e}`.charCodeAt(0),a=s>o,c=Math.min(s,o),l=Math.max(s,o);if(r.toRegex&&n===1)return Fme(c,l,!1,r);let u=[],d=0;for(;a?s>=o:s<=o;)u.push(i(s,d)),s=a?s-n:s+n,d++;return r.toRegex===!0?Ume(u,null,{wrap:!1,options:r}):u},ck=(t,e,n,r={})=>{if(e==null&&YG(t))return[t];if(!YG(t)||!YG(e))return qme(t,e,r);if(typeof n=="function")return ck(t,e,1,{transform:n});if(Dme(n))return ck(t,e,0,n);let i={...r};return i.capture===!0&&(i.wrap=!0),n=n||i.step||1,Yx(n)?Yx(t)&&Yx(e)?aXe(t,e,n,i):cXe(t,e,Math.max(Math.abs(n),1),i):n!=null&&!Dme(n)?oXe(n,i):ck(t,e,1,n)};$me.exports=ck});var jme=H((lNt,Hme)=>{"use strict";var lXe=JG(),Gme=ok(),uXe=(t,e={})=>{let n=(r,i={})=>{let s=Gme.isInvalidBrace(i),o=r.invalid===!0&&e.escapeInvalid===!0,a=s===!0||o===!0,c=e.escapeInvalid===!0?"\\":"",l="";if(r.isOpen===!0)return c+r.value;if(r.isClose===!0)return console.log("node.isClose",c,r.value),c+r.value;if(r.type==="open")return a?c+r.value:"(";if(r.type==="close")return a?c+r.value:")";if(r.type==="comma")return r.prev.type==="comma"?"":a?r.value:"|";if(r.value)return r.value;if(r.nodes&&r.ranges>0){let u=Gme.reduce(r.nodes),d=lXe(...u,{...e,wrap:!1,toRegex:!0,strictZeros:!0});if(d.length!==0)return u.length>1&&d.length>1?`(${d})`:d}if(r.nodes)for(let u of r.nodes)l+=n(u,r);return l};return n(t)};Hme.exports=uXe});var Vme=H((uNt,zme)=>{"use strict";var dXe=JG(),Wme=ak(),Cv=ok(),em=(t="",e="",n=!1)=>{let r=[];if(t=[].concat(t),e=[].concat(e),!e.length)return t;if(!t.length)return n?Cv.flatten(e).map(i=>`{${i}}`):e;for(let i of t)if(Array.isArray(i))for(let s of i)r.push(em(s,e,n));else for(let s of e)n===!0&&typeof s=="string"&&(s=`{${s}}`),r.push(Array.isArray(s)?em(i,s,n):i+s);return Cv.flatten(r)},pXe=(t,e={})=>{let n=e.rangeLimit===void 0?1e3:e.rangeLimit,r=(i,s={})=>{i.queue=[];let o=s,a=s.queue;for(;o.type!=="brace"&&o.type!=="root"&&o.parent;)o=o.parent,a=o.queue;if(i.invalid||i.dollar){a.push(em(a.pop(),Wme(i,e)));return}if(i.type==="brace"&&i.invalid!==!0&&i.nodes.length===2){a.push(em(a.pop(),["{}"]));return}if(i.nodes&&i.ranges>0){let d=Cv.reduce(i.nodes);if(Cv.exceedsLimit(...d,e.step,n))throw new RangeError("expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.");let p=dXe(...d,e);p.length===0&&(p=Wme(i,e)),a.push(em(a.pop(),p)),i.nodes=[];return}let c=Cv.encloseBrace(i),l=i.queue,u=i;for(;u.type!=="brace"&&u.type!=="root"&&u.parent;)u=u.parent,l=u.queue;for(let d=0;d<i.nodes.length;d++){let p=i.nodes[d];if(p.type==="comma"&&i.type==="brace"){d===1&&l.push(""),l.push("");continue}if(p.type==="close"){a.push(em(a.pop(),l,c));continue}if(p.value&&p.type!=="open"){l.push(em(l.pop(),p.value));continue}p.nodes&&r(p,i)}return l};return Cv.flatten(r(t))};zme.exports=pXe});var Yme=H((dNt,Kme)=>{"use strict";Kme.exports={MAX_LENGTH:1e4,CHAR_0:"0",CHAR_9:"9",CHAR_UPPERCASE_A:"A",CHAR_LOWERCASE_A:"a",CHAR_UPPERCASE_Z:"Z",CHAR_LOWERCASE_Z:"z",CHAR_LEFT_PARENTHESES:"(",CHAR_RIGHT_PARENTHESES:")",CHAR_ASTERISK:"*",CHAR_AMPERSAND:"&",CHAR_AT:"@",CHAR_BACKSLASH:"\\",CHAR_BACKTICK:"`",CHAR_CARRIAGE_RETURN:"\r",CHAR_CIRCUMFLEX_ACCENT:"^",CHAR_COLON:":",CHAR_COMMA:",",CHAR_DOLLAR:"$",CHAR_DOT:".",CHAR_DOUBLE_QUOTE:'"',CHAR_EQUAL:"=",CHAR_EXCLAMATION_MARK:"!",CHAR_FORM_FEED:"\f",CHAR_FORWARD_SLASH:"/",CHAR_HASH:"#",CHAR_HYPHEN_MINUS:"-",CHAR_LEFT_ANGLE_BRACKET:"<",CHAR_LEFT_CURLY_BRACE:"{",CHAR_LEFT_SQUARE_BRACKET:"[",CHAR_LINE_FEED:`
1062
1062
  `,CHAR_NO_BREAK_SPACE:"\xA0",CHAR_PERCENT:"%",CHAR_PLUS:"+",CHAR_QUESTION_MARK:"?",CHAR_RIGHT_ANGLE_BRACKET:">",CHAR_RIGHT_CURLY_BRACE:"}",CHAR_RIGHT_SQUARE_BRACKET:"]",CHAR_SEMICOLON:";",CHAR_SINGLE_QUOTE:"'",CHAR_SPACE:" ",CHAR_TAB:" ",CHAR_UNDERSCORE:"_",CHAR_VERTICAL_LINE:"|",CHAR_ZERO_WIDTH_NOBREAK_SPACE:"\uFEFF"}});var ege=H((pNt,Zme)=>{"use strict";var fXe=ak(),{MAX_LENGTH:Xme,CHAR_BACKSLASH:QG,CHAR_BACKTICK:hXe,CHAR_COMMA:mXe,CHAR_DOT:gXe,CHAR_LEFT_PARENTHESES:yXe,CHAR_RIGHT_PARENTHESES:vXe,CHAR_LEFT_CURLY_BRACE:_Xe,CHAR_RIGHT_CURLY_BRACE:wXe,CHAR_LEFT_SQUARE_BRACKET:Jme,CHAR_RIGHT_SQUARE_BRACKET:Qme,CHAR_DOUBLE_QUOTE:xXe,CHAR_SINGLE_QUOTE:EXe,CHAR_NO_BREAK_SPACE:bXe,CHAR_ZERO_WIDTH_NOBREAK_SPACE:SXe}=Yme(),TXe=(t,e={})=>{if(typeof t!="string")throw new TypeError("Expected a string");let n=e||{},r=typeof n.maxLength=="number"?Math.min(Xme,n.maxLength):Xme;if(t.length>r)throw new SyntaxError(`Input length (${t.length}), exceeds max characters (${r})`);let i={type:"root",input:t,nodes:[]},s=[i],o=i,a=i,c=0,l=t.length,u=0,d=0,p,m=()=>t[u++],h=y=>{if(y.type==="text"&&a.type==="dot"&&(a.type="text"),a&&a.type==="text"&&y.type==="text"){a.value+=y.value;return}return o.nodes.push(y),y.parent=o,y.prev=a,a=y,y};for(h({type:"bos"});u<l;)if(o=s[s.length-1],p=m(),!(p===SXe||p===bXe)){if(p===QG){h({type:"text",value:(e.keepEscaping?p:"")+m()});continue}if(p===Qme){h({type:"text",value:"\\"+p});continue}if(p===Jme){c++;let y;for(;u<l&&(y=m());){if(p+=y,y===Jme){c++;continue}if(y===QG){p+=m();continue}if(y===Qme&&(c--,c===0))break}h({type:"text",value:p});continue}if(p===yXe){o=h({type:"paren",nodes:[]}),s.push(o),h({type:"text",value:p});continue}if(p===vXe){if(o.type!=="paren"){h({type:"text",value:p});continue}o=s.pop(),h({type:"text",value:p}),o=s[s.length-1];continue}if(p===xXe||p===EXe||p===hXe){let y=p,v;for(e.keepQuotes!==!0&&(p="");u<l&&(v=m());){if(v===QG){p+=v+m();continue}if(v===y){e.keepQuotes===!0&&(p+=v);break}p+=v}h({type:"text",value:p});continue}if(p===_Xe){d++;let v={type:"brace",open:!0,close:!1,dollar:a.value&&a.value.slice(-1)==="$"||o.dollar===!0,depth:d,commas:0,ranges:0,nodes:[]};o=h(v),s.push(o),h({type:"open",value:p});continue}if(p===wXe){if(o.type!=="brace"){h({type:"text",value:p});continue}let y="close";o=s.pop(),o.close=!0,h({type:y,value:p}),d--,o=s[s.length-1];continue}if(p===mXe&&d>0){if(o.ranges>0){o.ranges=0;let y=o.nodes.shift();o.nodes=[y,{type:"text",value:fXe(o)}]}h({type:"comma",value:p}),o.commas++;continue}if(p===gXe&&d>0&&o.commas===0){let y=o.nodes;if(d===0||y.length===0){h({type:"text",value:p});continue}if(a.type==="dot"){if(o.range=[],a.value+=p,a.type="range",o.nodes.length!==3&&o.nodes.length!==5){o.invalid=!0,o.ranges=0,a.type="text";continue}o.ranges++,o.args=[];continue}if(a.type==="range"){y.pop();let v=y[y.length-1];v.value+=a.value+p,a=v,o.ranges--;continue}h({type:"dot",value:p});continue}h({type:"text",value:p})}do if(o=s.pop(),o.type!=="root"){o.nodes.forEach(E=>{E.nodes||(E.type==="open"&&(E.isOpen=!0),E.type==="close"&&(E.isClose=!0),E.nodes||(E.type="text"),E.invalid=!0)});let y=s[s.length-1],v=y.nodes.indexOf(o);y.nodes.splice(v,1,...o.nodes)}while(s.length>0);return h({type:"eos"}),i};Zme.exports=TXe});var rge=H((fNt,nge)=>{"use strict";var tge=ak(),AXe=jme(),CXe=Vme(),RXe=ege(),lo=(t,e={})=>{let n=[];if(Array.isArray(t))for(let r of t){let i=lo.create(r,e);Array.isArray(i)?n.push(...i):n.push(i)}else n=[].concat(lo.create(t,e));return e&&e.expand===!0&&e.nodupes===!0&&(n=[...new Set(n)]),n};lo.parse=(t,e={})=>RXe(t,e);lo.stringify=(t,e={})=>tge(typeof t=="string"?lo.parse(t,e):t,e);lo.compile=(t,e={})=>(typeof t=="string"&&(t=lo.parse(t,e)),AXe(t,e));lo.expand=(t,e={})=>{typeof t=="string"&&(t=lo.parse(t,e));let n=CXe(t,e);return e.noempty===!0&&(n=n.filter(Boolean)),e.nodupes===!0&&(n=[...new Set(n)]),n};lo.create=(t,e={})=>t===""||t.length<3?[t]:e.expand!==!0?lo.compile(t,e):lo.expand(t,e);nge.exports=lo});var ige=H((hNt,IXe)=>{IXe.exports=["3dm","3ds","3g2","3gp","7z","a","aac","adp","afdesign","afphoto","afpub","ai","aif","aiff","alz","ape","apk","appimage","ar","arj","asf","au","avi","bak","baml","bh","bin","bk","bmp","btif","bz2","bzip2","cab","caf","cgm","class","cmx","cpio","cr2","cur","dat","dcm","deb","dex","djvu","dll","dmg","dng","doc","docm","docx","dot","dotm","dra","DS_Store","dsk","dts","dtshd","dvb","dwg","dxf","ecelp4800","ecelp7470","ecelp9600","egg","eol","eot","epub","exe","f4v","fbs","fh","fla","flac","flatpak","fli","flv","fpx","fst","fvt","g3","gh","gif","graffle","gz","gzip","h261","h263","h264","icns","ico","ief","img","ipa","iso","jar","jpeg","jpg","jpgv","jpm","jxr","key","ktx","lha","lib","lvp","lz","lzh","lzma","lzo","m3u","m4a","m4v","mar","mdi","mht","mid","midi","mj2","mka","mkv","mmr","mng","mobi","mov","movie","mp3","mp4","mp4a","mpeg","mpg","mpga","mxu","nef","npx","numbers","nupkg","o","odp","ods","odt","oga","ogg","ogv","otf","ott","pages","pbm","pcx","pdb","pdf","pea","pgm","pic","png","pnm","pot","potm","potx","ppa","ppam","ppm","pps","ppsm","ppsx","ppt","pptm","pptx","psd","pya","pyc","pyo","pyv","qt","rar","ras","raw","resources","rgb","rip","rlc","rmf","rmvb","rpm","rtf","rz","s3m","s7z","scpt","sgi","shar","snap","sil","sketch","slk","smv","snk","so","stl","suo","sub","swf","tar","tbz","tbz2","tga","tgz","thmx","tif","tiff","tlz","ttc","ttf","txz","udf","uvh","uvi","uvm","uvp","uvs","uvu","viv","vob","war","wav","wax","wbmp","wdp","weba","webm","webp","whl","wim","wm","wma","wmv","wmx","woff","woff2","wrm","wvx","xbm","xif","xla","xlam","xls","xlsb","xlsm","xlsx","xlt","xltm","xltx","xm","xmind","xpi","xpm","xwd","xz","z","zip","zipx"]});var oge=H((mNt,sge)=>{sge.exports=ige()});var cge=H((gNt,age)=>{"use strict";var kXe=require("path"),PXe=oge(),MXe=new Set(PXe);age.exports=t=>MXe.has(kXe.extname(t).slice(1).toLowerCase())});var uk=H(He=>{"use strict";var{sep:OXe}=require("path"),{platform:ZG}=process,NXe=require("os");He.EV_ALL="all";He.EV_READY="ready";He.EV_ADD="add";He.EV_CHANGE="change";He.EV_ADD_DIR="addDir";He.EV_UNLINK="unlink";He.EV_UNLINK_DIR="unlinkDir";He.EV_RAW="raw";He.EV_ERROR="error";He.STR_DATA="data";He.STR_END="end";He.STR_CLOSE="close";He.FSEVENT_CREATED="created";He.FSEVENT_MODIFIED="modified";He.FSEVENT_DELETED="deleted";He.FSEVENT_MOVED="moved";He.FSEVENT_CLONED="cloned";He.FSEVENT_UNKNOWN="unknown";He.FSEVENT_FLAG_MUST_SCAN_SUBDIRS=1;He.FSEVENT_TYPE_FILE="file";He.FSEVENT_TYPE_DIRECTORY="directory";He.FSEVENT_TYPE_SYMLINK="symlink";He.KEY_LISTENERS="listeners";He.KEY_ERR="errHandlers";He.KEY_RAW="rawEmitters";He.HANDLER_KEYS=[He.KEY_LISTENERS,He.KEY_ERR,He.KEY_RAW];He.DOT_SLASH=`.${OXe}`;He.BACK_SLASH_RE=/\\/g;He.DOUBLE_SLASH_RE=/\/\//;He.SLASH_OR_BACK_SLASH_RE=/[/\\]/;He.DOT_RE=/\..*\.(sw[px])$|~$|\.subl.*\.tmp/;He.REPLACER_RE=/^\.[/\\]/;He.SLASH="/";He.SLASH_SLASH="//";He.BRACE_START="{";He.BANG="!";He.ONE_DOT=".";He.TWO_DOTS="..";He.STAR="*";He.GLOBSTAR="**";He.ROOT_GLOBSTAR="/**/*";He.SLASH_GLOBSTAR="/**";He.DIR_SUFFIX="Dir";He.ANYMATCH_OPTS={dot:!0};He.STRING_TYPE="string";He.FUNCTION_TYPE="function";He.EMPTY_STR="";He.EMPTY_FN=()=>{};He.IDENTITY_FN=t=>t;He.isWindows=ZG==="win32";He.isMacos=ZG==="darwin";He.isLinux=ZG==="linux";He.isIBMi=NXe.type()==="OS400"});var hge=H((vNt,fge)=>{"use strict";var Vu=require("fs"),ci=require("path"),{promisify:Zx}=require("util"),DXe=cge(),{isWindows:LXe,isLinux:FXe,EMPTY_FN:UXe,EMPTY_STR:BXe,KEY_LISTENERS:Rv,KEY_ERR:eH,KEY_RAW:Xx,HANDLER_KEYS:qXe,EV_CHANGE:pk,EV_ADD:dk,EV_ADD_DIR:$Xe,EV_ERROR:uge,STR_DATA:GXe,STR_END:HXe,BRACE_START:jXe,STAR:WXe}=uk(),zXe="watch",VXe=Zx(Vu.open),dge=Zx(Vu.stat),KXe=Zx(Vu.lstat),YXe=Zx(Vu.close),tH=Zx(Vu.realpath),XXe={lstat:KXe,stat:dge},rH=(t,e)=>{t instanceof Set?t.forEach(e):e(t)},Jx=(t,e,n)=>{let r=t[e];r instanceof Set||(t[e]=r=new Set([r])),r.add(n)},JXe=t=>e=>{let n=t[e];n instanceof Set?n.clear():delete t[e]},Qx=(t,e,n)=>{let r=t[e];r instanceof Set?r.delete(n):r===n&&delete t[e]},pge=t=>t instanceof Set?t.size===0:!t,fk=new Map;function lge(t,e,n,r,i){let s=(o,a)=>{n(t),i(o,a,{watchedPath:t}),a&&t!==a&&hk(ci.resolve(t,a),Rv,ci.join(t,a))};try{return Vu.watch(t,e,s)}catch(o){r(o)}}var hk=(t,e,n,r,i)=>{let s=fk.get(t);s&&rH(s[e],o=>{o(n,r,i)})},QXe=(t,e,n,r)=>{let{listener:i,errHandler:s,rawEmitter:o}=r,a=fk.get(e),c;if(!n.persistent)return c=lge(t,n,i,s,o),c.close.bind(c);if(a)Jx(a,Rv,i),Jx(a,eH,s),Jx(a,Xx,o);else{if(c=lge(t,n,hk.bind(null,e,Rv),s,hk.bind(null,e,Xx)),!c)return;c.on(uge,async l=>{let u=hk.bind(null,e,eH);if(a.watcherUnusable=!0,LXe&&l.code==="EPERM")try{let d=await VXe(t,"r");await YXe(d),u(l)}catch{}else u(l)}),a={listeners:i,errHandlers:s,rawEmitters:o,watcher:c},fk.set(e,a)}return()=>{Qx(a,Rv,i),Qx(a,eH,s),Qx(a,Xx,o),pge(a.listeners)&&(a.watcher.close(),fk.delete(e),qXe.forEach(JXe(a)),a.watcher=void 0,Object.freeze(a))}},nH=new Map,ZXe=(t,e,n,r)=>{let{listener:i,rawEmitter:s}=r,o=nH.get(e),a=new Set,c=new Set,l=o&&o.options;return l&&(l.persistent<n.persistent||l.interval>n.interval)&&(a=o.listeners,c=o.rawEmitters,Vu.unwatchFile(e),o=void 0),o?(Jx(o,Rv,i),Jx(o,Xx,s)):(o={listeners:i,rawEmitters:s,options:n,watcher:Vu.watchFile(e,n,(u,d)=>{rH(o.rawEmitters,m=>{m(pk,e,{curr:u,prev:d})});let p=u.mtimeMs;(u.size!==d.size||p>d.mtimeMs||p===0)&&rH(o.listeners,m=>m(t,u))})},nH.set(e,o)),()=>{Qx(o,Rv,i),Qx(o,Xx,s),pge(o.listeners)&&(nH.delete(e),Vu.unwatchFile(e),o.options=o.watcher=void 0,Object.freeze(o))}},iH=class{constructor(e){this.fsw=e,this._boundHandleError=n=>e._handleError(n)}_watchWithNodeFs(e,n){let r=this.fsw.options,i=ci.dirname(e),s=ci.basename(e);this.fsw._getWatchedDir(i).add(s);let a=ci.resolve(e),c={persistent:r.persistent};n||(n=UXe);let l;return r.usePolling?(c.interval=r.enableBinaryInterval&&DXe(s)?r.binaryInterval:r.interval,l=ZXe(e,a,c,{listener:n,rawEmitter:this.fsw._emitRaw})):l=QXe(e,a,c,{listener:n,errHandler:this._boundHandleError,rawEmitter:this.fsw._emitRaw}),l}_handleFile(e,n,r){if(this.fsw.closed)return;let i=ci.dirname(e),s=ci.basename(e),o=this.fsw._getWatchedDir(i),a=n;if(o.has(s))return;let c=async(u,d)=>{if(this.fsw._throttle(zXe,e,5)){if(!d||d.mtimeMs===0)try{let p=await dge(e);if(this.fsw.closed)return;let m=p.atimeMs,h=p.mtimeMs;(!m||m<=h||h!==a.mtimeMs)&&this.fsw._emit(pk,e,p),FXe&&a.ino!==p.ino?(this.fsw._closeFile(u),a=p,this.fsw._addPathCloser(u,this._watchWithNodeFs(e,c))):a=p}catch{this.fsw._remove(i,s)}else if(o.has(s)){let p=d.atimeMs,m=d.mtimeMs;(!p||p<=m||m!==a.mtimeMs)&&this.fsw._emit(pk,e,d),a=d}}},l=this._watchWithNodeFs(e,c);if(!(r&&this.fsw.options.ignoreInitial)&&this.fsw._isntIgnored(e)){if(!this.fsw._throttle(dk,e,0))return;this.fsw._emit(dk,e,n)}return l}async _handleSymlink(e,n,r,i){if(this.fsw.closed)return;let s=e.fullPath,o=this.fsw._getWatchedDir(n);if(!this.fsw.options.followSymlinks){this.fsw._incrReadyCount();let a;try{a=await tH(r)}catch{return this.fsw._emitReady(),!0}return this.fsw.closed?void 0:(o.has(i)?this.fsw._symlinkPaths.get(s)!==a&&(this.fsw._symlinkPaths.set(s,a),this.fsw._emit(pk,r,e.stats)):(o.add(i),this.fsw._symlinkPaths.set(s,a),this.fsw._emit(dk,r,e.stats)),this.fsw._emitReady(),!0)}if(this.fsw._symlinkPaths.has(s))return!0;this.fsw._symlinkPaths.set(s,!0)}_handleRead(e,n,r,i,s,o,a){if(e=ci.join(e,BXe),!r.hasGlob&&(a=this.fsw._throttle("readdir",e,1e3),!a))return;let c=this.fsw._getWatchedDir(r.path),l=new Set,u=this.fsw._readdirp(e,{fileFilter:d=>r.filterPath(d),directoryFilter:d=>r.filterDir(d),depth:0}).on(GXe,async d=>{if(this.fsw.closed){u=void 0;return}let p=d.path,m=ci.join(e,p);if(l.add(p),!(d.stats.isSymbolicLink()&&await this._handleSymlink(d,e,m,p))){if(this.fsw.closed){u=void 0;return}(p===i||!i&&!c.has(p))&&(this.fsw._incrReadyCount(),m=ci.join(s,ci.relative(s,m)),this._addToNodeFs(m,n,r,o+1))}}).on(uge,this._boundHandleError);return new Promise(d=>u.once(HXe,()=>{if(this.fsw.closed){u=void 0;return}let p=a?a.clear():!1;d(),c.getChildren().filter(m=>m!==e&&!l.has(m)&&(!r.hasGlob||r.filterPath({fullPath:ci.resolve(e,m)}))).forEach(m=>{this.fsw._remove(e,m)}),u=void 0,p&&this._handleRead(e,!1,r,i,s,o,a)}))}async _handleDir(e,n,r,i,s,o,a){let c=this.fsw._getWatchedDir(ci.dirname(e)),l=c.has(ci.basename(e));!(r&&this.fsw.options.ignoreInitial)&&!s&&!l&&(!o.hasGlob||o.globFilter(e))&&this.fsw._emit($Xe,e,n),c.add(ci.basename(e)),this.fsw._getWatchedDir(e);let u,d,p=this.fsw.options.depth;if((p==null||i<=p)&&!this.fsw._symlinkPaths.has(a)){if(!s&&(await this._handleRead(e,r,o,s,e,i,u),this.fsw.closed))return;d=this._watchWithNodeFs(e,(m,h)=>{h&&h.mtimeMs===0||this._handleRead(m,!1,o,s,e,i,u)})}return d}async _addToNodeFs(e,n,r,i,s){let o=this.fsw._emitReady;if(this.fsw._isIgnored(e)||this.fsw.closed)return o(),!1;let a=this.fsw._getWatchHelpers(e,i);!a.hasGlob&&r&&(a.hasGlob=r.hasGlob,a.globFilter=r.globFilter,a.filterPath=c=>r.filterPath(c),a.filterDir=c=>r.filterDir(c));try{let c=await XXe[a.statMethod](a.watchPath);if(this.fsw.closed)return;if(this.fsw._isIgnored(a.watchPath,c))return o(),!1;let l=this.fsw.options.followSymlinks&&!e.includes(WXe)&&!e.includes(jXe),u;if(c.isDirectory()){let d=ci.resolve(e),p=l?await tH(e):e;if(this.fsw.closed||(u=await this._handleDir(a.watchPath,c,n,i,s,a,p),this.fsw.closed))return;d!==p&&p!==void 0&&this.fsw._symlinkPaths.set(d,p)}else if(c.isSymbolicLink()){let d=l?await tH(e):e;if(this.fsw.closed)return;let p=ci.dirname(a.watchPath);if(this.fsw._getWatchedDir(p).add(a.watchPath),this.fsw._emit(dk,a.watchPath,c),u=await this._handleDir(p,c,n,i,e,a,d),this.fsw.closed)return;d!==void 0&&this.fsw._symlinkPaths.set(ci.resolve(e),d)}else u=this._handleFile(a.watchPath,c,n);return o(),this.fsw._addPathCloser(e,u),!1}catch(c){if(this.fsw._handleError(c))return o(),e}}};fge.exports=iH});var xge=H((_Nt,pH)=>{"use strict";var uH=require("fs"),li=require("path"),{promisify:dH}=require("util"),Iv;try{Iv=require("fsevents")}catch(t){process.env.CHOKIDAR_PRINT_FSEVENTS_REQUIRE_ERROR&&console.error(t)}if(Iv){let t=process.version.match(/v(\d+)\.(\d+)/);if(t&&t[1]&&t[2]){let e=Number.parseInt(t[1],10),n=Number.parseInt(t[2],10);e===8&&n<16&&(Iv=void 0)}}var{EV_ADD:sH,EV_CHANGE:eJe,EV_ADD_DIR:mge,EV_UNLINK:mk,EV_ERROR:tJe,STR_DATA:nJe,STR_END:rJe,FSEVENT_CREATED:iJe,FSEVENT_MODIFIED:sJe,FSEVENT_DELETED:oJe,FSEVENT_MOVED:aJe,FSEVENT_UNKNOWN:cJe,FSEVENT_FLAG_MUST_SCAN_SUBDIRS:lJe,FSEVENT_TYPE_FILE:uJe,FSEVENT_TYPE_DIRECTORY:eE,FSEVENT_TYPE_SYMLINK:wge,ROOT_GLOBSTAR:gge,DIR_SUFFIX:dJe,DOT_SLASH:yge,FUNCTION_TYPE:oH,EMPTY_FN:pJe,IDENTITY_FN:fJe}=uk(),hJe=t=>isNaN(t)?{}:{depth:t},cH=dH(uH.stat),mJe=dH(uH.lstat),vge=dH(uH.realpath),gJe={stat:cH,lstat:mJe},tm=new Map,yJe=10,vJe=new Set([69888,70400,71424,72704,73472,131328,131840,262912]),_Je=(t,e)=>({stop:Iv.watch(t,e)});function wJe(t,e,n,r){let i=li.extname(e)?li.dirname(e):e,s=li.dirname(i),o=tm.get(i);xJe(s)&&(i=s);let a=li.resolve(t),c=a!==e,l=(d,p,m)=>{c&&(d=d.replace(e,a)),(d===a||!d.indexOf(a+li.sep))&&n(d,p,m)},u=!1;for(let d of tm.keys())if(e.indexOf(li.resolve(d)+li.sep)===0){i=d,o=tm.get(i),u=!0;break}return o||u?o.listeners.add(l):(o={listeners:new Set([l]),rawEmitter:r,watcher:_Je(i,(d,p)=>{if(!o.listeners.size||p&lJe)return;let m=Iv.getInfo(d,p);o.listeners.forEach(h=>{h(d,p,m)}),o.rawEmitter(m.event,d,m)})},tm.set(i,o)),()=>{let d=o.listeners;if(d.delete(l),!d.size&&(tm.delete(i),o.watcher))return o.watcher.stop().then(()=>{o.rawEmitter=o.watcher=void 0,Object.freeze(o)})}}var xJe=t=>{let e=0;for(let n of tm.keys())if(n.indexOf(t)===0&&(e++,e>=yJe))return!0;return!1},EJe=()=>Iv&&tm.size<128,aH=(t,e)=>{let n=0;for(;!t.indexOf(e)&&(t=li.dirname(t))!==e;)n++;return n},_ge=(t,e)=>t.type===eE&&e.isDirectory()||t.type===wge&&e.isSymbolicLink()||t.type===uJe&&e.isFile(),lH=class{constructor(e){this.fsw=e}checkIgnored(e,n){let r=this.fsw._ignoredPaths;if(this.fsw._isIgnored(e,n))return r.add(e),n&&n.isDirectory()&&r.add(e+gge),!0;r.delete(e),r.delete(e+gge)}addOrChange(e,n,r,i,s,o,a,c){let l=s.has(o)?eJe:sH;this.handleEvent(l,e,n,r,i,s,o,a,c)}async checkExists(e,n,r,i,s,o,a,c){try{let l=await cH(e);if(this.fsw.closed)return;_ge(a,l)?this.addOrChange(e,n,r,i,s,o,a,c):this.handleEvent(mk,e,n,r,i,s,o,a,c)}catch(l){l.code==="EACCES"?this.addOrChange(e,n,r,i,s,o,a,c):this.handleEvent(mk,e,n,r,i,s,o,a,c)}}handleEvent(e,n,r,i,s,o,a,c,l){if(!(this.fsw.closed||this.checkIgnored(n)))if(e===mk){let u=c.type===eE;(u||o.has(a))&&this.fsw._remove(s,a,u)}else{if(e===sH){if(c.type===eE&&this.fsw._getWatchedDir(n),c.type===wge&&l.followSymlinks){let d=l.depth===void 0?void 0:aH(r,i)+1;return this._addToFsEvents(n,!1,!0,d)}this.fsw._getWatchedDir(s).add(a)}let u=c.type===eE?e+dJe:e;this.fsw._emit(u,n),u===mge&&this._addToFsEvents(n,!1,!0)}}_watchWithFsEvents(e,n,r,i){if(this.fsw.closed||this.fsw._isIgnored(e))return;let s=this.fsw.options,a=wJe(e,n,async(c,l,u)=>{if(this.fsw.closed||s.depth!==void 0&&aH(c,n)>s.depth)return;let d=r(li.join(e,li.relative(e,c)));if(i&&!i(d))return;let p=li.dirname(d),m=li.basename(d),h=this.fsw._getWatchedDir(u.type===eE?d:p);if(vJe.has(l)||u.event===cJe)if(typeof s.ignored===oH){let y;try{y=await cH(d)}catch{}if(this.fsw.closed||this.checkIgnored(d,y))return;_ge(u,y)?this.addOrChange(d,c,n,p,h,m,u,s):this.handleEvent(mk,d,c,n,p,h,m,u,s)}else this.checkExists(d,c,n,p,h,m,u,s);else switch(u.event){case iJe:case sJe:return this.addOrChange(d,c,n,p,h,m,u,s);case oJe:case aJe:return this.checkExists(d,c,n,p,h,m,u,s)}},this.fsw._emitRaw);return this.fsw._emitReady(),a}async _handleFsEventsSymlink(e,n,r,i){if(!(this.fsw.closed||this.fsw._symlinkPaths.has(n))){this.fsw._symlinkPaths.set(n,!0),this.fsw._incrReadyCount();try{let s=await vge(e);if(this.fsw.closed)return;if(this.fsw._isIgnored(s))return this.fsw._emitReady();this.fsw._incrReadyCount(),this._addToFsEvents(s||e,o=>{let a=e;return s&&s!==yge?a=o.replace(s,e):o!==yge&&(a=li.join(e,o)),r(a)},!1,i)}catch(s){if(this.fsw._handleError(s))return this.fsw._emitReady()}}}emitAdd(e,n,r,i,s){let o=r(e),a=n.isDirectory(),c=this.fsw._getWatchedDir(li.dirname(o)),l=li.basename(o);a&&this.fsw._getWatchedDir(o),!c.has(l)&&(c.add(l),(!i.ignoreInitial||s===!0)&&this.fsw._emit(a?mge:sH,o,n))}initWatch(e,n,r,i){if(this.fsw.closed)return;let s=this._watchWithFsEvents(r.watchPath,li.resolve(e||r.watchPath),i,r.globFilter);this.fsw._addPathCloser(n,s)}async _addToFsEvents(e,n,r,i){if(this.fsw.closed)return;let s=this.fsw.options,o=typeof n===oH?n:fJe,a=this.fsw._getWatchHelpers(e);try{let c=await gJe[a.statMethod](a.watchPath);if(this.fsw.closed)return;if(this.fsw._isIgnored(a.watchPath,c))throw null;if(c.isDirectory()){if(a.globFilter||this.emitAdd(o(e),c,o,s,r),i&&i>s.depth)return;this.fsw._readdirp(a.watchPath,{fileFilter:l=>a.filterPath(l),directoryFilter:l=>a.filterDir(l),...hJe(s.depth-(i||0))}).on(nJe,l=>{if(this.fsw.closed||l.stats.isDirectory()&&!a.filterPath(l))return;let u=li.join(a.watchPath,l.path),{fullPath:d}=l;if(a.followSymlinks&&l.stats.isSymbolicLink()){let p=s.depth===void 0?void 0:aH(u,li.resolve(a.watchPath))+1;this._handleFsEventsSymlink(u,d,o,p)}else this.emitAdd(u,l.stats,o,s,r)}).on(tJe,pJe).on(rJe,()=>{this.fsw._emitReady()})}else this.emitAdd(a.watchPath,c,o,s,r),this.fsw._emitReady()}catch(c){(!c||this.fsw._handleError(c))&&(this.fsw._emitReady(),this.fsw._emitReady())}if(s.persistent&&r!==!0)if(typeof n===oH)this.initWatch(void 0,e,a,o);else{let c;try{c=await vge(a.watchPath)}catch{}this.initWatch(c,e,a,o)}}};pH.exports=lH;pH.exports.canUse=EJe});var Mge=H(CH=>{"use strict";var{EventEmitter:bJe}=require("events"),TH=require("fs"),vn=require("path"),{promisify:Rge}=require("util"),SJe=cme(),vH=mme().default,TJe=xme(),fH=zG(),AJe=rge(),CJe=Av(),RJe=hge(),Ege=xge(),{EV_ALL:hH,EV_READY:IJe,EV_ADD:gk,EV_CHANGE:tE,EV_UNLINK:bge,EV_ADD_DIR:kJe,EV_UNLINK_DIR:PJe,EV_RAW:MJe,EV_ERROR:mH,STR_CLOSE:OJe,STR_END:NJe,BACK_SLASH_RE:DJe,DOUBLE_SLASH_RE:Sge,SLASH_OR_BACK_SLASH_RE:LJe,DOT_RE:FJe,REPLACER_RE:UJe,SLASH:gH,SLASH_SLASH:BJe,BRACE_START:qJe,BANG:_H,ONE_DOT:Ige,TWO_DOTS:$Je,GLOBSTAR:GJe,SLASH_GLOBSTAR:yH,ANYMATCH_OPTS:wH,STRING_TYPE:AH,FUNCTION_TYPE:HJe,EMPTY_STR:xH,EMPTY_FN:jJe,isWindows:WJe,isMacos:zJe,isIBMi:VJe}=uk(),KJe=Rge(TH.stat),YJe=Rge(TH.readdir),EH=(t=[])=>Array.isArray(t)?t:[t],kge=(t,e=[])=>(t.forEach(n=>{Array.isArray(n)?kge(n,e):e.push(n)}),e),Tge=t=>{let e=kge(EH(t));if(!e.every(n=>typeof n===AH))throw new TypeError(`Non-string provided as watch path: ${e}`);return e.map(Pge)},Age=t=>{let e=t.replace(DJe,gH),n=!1;for(e.startsWith(BJe)&&(n=!0);e.match(Sge);)e=e.replace(Sge,gH);return n&&(e=gH+e),e},Pge=t=>Age(vn.normalize(Age(t))),Cge=(t=xH)=>e=>typeof e!==AH?e:Pge(vn.isAbsolute(e)?e:vn.join(t,e)),XJe=(t,e)=>vn.isAbsolute(t)?t:t.startsWith(_H)?_H+vn.join(e,t.slice(1)):vn.join(e,t),ac=(t,e)=>t[e]===void 0,bH=class{constructor(e,n){this.path=e,this._removeWatcher=n,this.items=new Set}add(e){let{items:n}=this;n&&e!==Ige&&e!==$Je&&n.add(e)}async remove(e){let{items:n}=this;if(!n||(n.delete(e),n.size>0))return;let r=this.path;try{await YJe(r)}catch{this._removeWatcher&&this._removeWatcher(vn.dirname(r),vn.basename(r))}}has(e){let{items:n}=this;if(n)return n.has(e)}getChildren(){let{items:e}=this;if(e)return[...e.values()]}dispose(){this.items.clear(),delete this.path,delete this._removeWatcher,delete this.items,Object.freeze(this)}},JJe="stat",QJe="lstat",SH=class{constructor(e,n,r,i){this.fsw=i,this.path=e=e.replace(UJe,xH),this.watchPath=n,this.fullWatchPath=vn.resolve(n),this.hasGlob=n!==e,e===xH&&(this.hasGlob=!1),this.globSymlink=this.hasGlob&&r?void 0:!1,this.globFilter=this.hasGlob?vH(e,void 0,wH):!1,this.dirParts=this.getDirParts(e),this.dirParts.forEach(s=>{s.length>1&&s.pop()}),this.followSymlinks=r,this.statMethod=r?JJe:QJe}checkGlobSymlink(e){return this.globSymlink===void 0&&(this.globSymlink=e.fullParentDir===this.fullWatchPath?!1:{realPath:e.fullParentDir,linkPath:this.fullWatchPath}),this.globSymlink?e.fullPath.replace(this.globSymlink.realPath,this.globSymlink.linkPath):e.fullPath}entryPath(e){return vn.join(this.watchPath,vn.relative(this.watchPath,this.checkGlobSymlink(e)))}filterPath(e){let{stats:n}=e;if(n&&n.isSymbolicLink())return this.filterDir(e);let r=this.entryPath(e);return(this.hasGlob&&typeof this.globFilter===HJe?this.globFilter(r):!0)&&this.fsw._isntIgnored(r,n)&&this.fsw._hasReadPermissions(n)}getDirParts(e){if(!this.hasGlob)return[];let n=[];return(e.includes(qJe)?AJe.expand(e):[e]).forEach(i=>{n.push(vn.relative(this.watchPath,i).split(LJe))}),n}filterDir(e){if(this.hasGlob){let n=this.getDirParts(this.checkGlobSymlink(e)),r=!1;this.unmatchedGlob=!this.dirParts.some(i=>i.every((s,o)=>(s===GJe&&(r=!0),r||!n[0][o]||vH(s,n[0][o],wH))))}return!this.unmatchedGlob&&this.fsw._isntIgnored(this.entryPath(e),e.stats)}},yk=class extends bJe{constructor(e){super();let n={};e&&Object.assign(n,e),this._watched=new Map,this._closers=new Map,this._ignoredPaths=new Set,this._throttled=new Map,this._symlinkPaths=new Map,this._streams=new Set,this.closed=!1,ac(n,"persistent")&&(n.persistent=!0),ac(n,"ignoreInitial")&&(n.ignoreInitial=!1),ac(n,"ignorePermissionErrors")&&(n.ignorePermissionErrors=!1),ac(n,"interval")&&(n.interval=100),ac(n,"binaryInterval")&&(n.binaryInterval=300),ac(n,"disableGlobbing")&&(n.disableGlobbing=!1),n.enableBinaryInterval=n.binaryInterval!==n.interval,ac(n,"useFsEvents")&&(n.useFsEvents=!n.usePolling),Ege.canUse()||(n.useFsEvents=!1),ac(n,"usePolling")&&!n.useFsEvents&&(n.usePolling=zJe),VJe&&(n.usePolling=!0);let i=process.env.CHOKIDAR_USEPOLLING;if(i!==void 0){let c=i.toLowerCase();c==="false"||c==="0"?n.usePolling=!1:c==="true"||c==="1"?n.usePolling=!0:n.usePolling=!!c}let s=process.env.CHOKIDAR_INTERVAL;s&&(n.interval=Number.parseInt(s,10)),ac(n,"atomic")&&(n.atomic=!n.usePolling&&!n.useFsEvents),n.atomic&&(this._pendingUnlinks=new Map),ac(n,"followSymlinks")&&(n.followSymlinks=!0),ac(n,"awaitWriteFinish")&&(n.awaitWriteFinish=!1),n.awaitWriteFinish===!0&&(n.awaitWriteFinish={});let o=n.awaitWriteFinish;o&&(o.stabilityThreshold||(o.stabilityThreshold=2e3),o.pollInterval||(o.pollInterval=100),this._pendingWrites=new Map),n.ignored&&(n.ignored=EH(n.ignored));let a=0;this._emitReady=()=>{a++,a>=this._readyCount&&(this._emitReady=jJe,this._readyEmitted=!0,process.nextTick(()=>this.emit(IJe)))},this._emitRaw=(...c)=>this.emit(MJe,...c),this._readyEmitted=!1,this.options=n,n.useFsEvents?this._fsEventsHandler=new Ege(this):this._nodeFsHandler=new RJe(this),Object.freeze(n)}add(e,n,r){let{cwd:i,disableGlobbing:s}=this.options;this.closed=!1;let o=Tge(e);return i&&(o=o.map(a=>{let c=XJe(a,i);return s||!fH(a)?c:CJe(c)})),o=o.filter(a=>a.startsWith(_H)?(this._ignoredPaths.add(a.slice(1)),!1):(this._ignoredPaths.delete(a),this._ignoredPaths.delete(a+yH),this._userIgnored=void 0,!0)),this.options.useFsEvents&&this._fsEventsHandler?(this._readyCount||(this._readyCount=o.length),this.options.persistent&&(this._readyCount+=o.length),o.forEach(a=>this._fsEventsHandler._addToFsEvents(a))):(this._readyCount||(this._readyCount=0),this._readyCount+=o.length,Promise.all(o.map(async a=>{let c=await this._nodeFsHandler._addToNodeFs(a,!r,0,0,n);return c&&this._emitReady(),c})).then(a=>{this.closed||a.filter(c=>c).forEach(c=>{this.add(vn.dirname(c),vn.basename(n||c))})})),this}unwatch(e){if(this.closed)return this;let n=Tge(e),{cwd:r}=this.options;return n.forEach(i=>{!vn.isAbsolute(i)&&!this._closers.has(i)&&(r&&(i=vn.join(r,i)),i=vn.resolve(i)),this._closePath(i),this._ignoredPaths.add(i),this._watched.has(i)&&this._ignoredPaths.add(i+yH),this._userIgnored=void 0}),this}close(){if(this.closed)return this._closePromise;this.closed=!0,this.removeAllListeners();let e=[];return this._closers.forEach(n=>n.forEach(r=>{let i=r();i instanceof Promise&&e.push(i)})),this._streams.forEach(n=>n.destroy()),this._userIgnored=void 0,this._readyCount=0,this._readyEmitted=!1,this._watched.forEach(n=>n.dispose()),["closers","watched","streams","symlinkPaths","throttled"].forEach(n=>{this[`_${n}`].clear()}),this._closePromise=e.length?Promise.all(e).then(()=>{}):Promise.resolve(),this._closePromise}getWatched(){let e={};return this._watched.forEach((n,r)=>{let i=this.options.cwd?vn.relative(this.options.cwd,r):r;e[i||Ige]=n.getChildren().sort()}),e}emitWithAll(e,n){this.emit(...n),e!==mH&&this.emit(hH,...n)}async _emit(e,n,r,i,s){if(this.closed)return;let o=this.options;WJe&&(n=vn.normalize(n)),o.cwd&&(n=vn.relative(o.cwd,n));let a=[e,n];s!==void 0?a.push(r,i,s):i!==void 0?a.push(r,i):r!==void 0&&a.push(r);let c=o.awaitWriteFinish,l;if(c&&(l=this._pendingWrites.get(n)))return l.lastChange=new Date,this;if(o.atomic){if(e===bge)return this._pendingUnlinks.set(n,a),setTimeout(()=>{this._pendingUnlinks.forEach((u,d)=>{this.emit(...u),this.emit(hH,...u),this._pendingUnlinks.delete(d)})},typeof o.atomic=="number"?o.atomic:100),this;e===gk&&this._pendingUnlinks.has(n)&&(e=a[0]=tE,this._pendingUnlinks.delete(n))}if(c&&(e===gk||e===tE)&&this._readyEmitted){let u=(d,p)=>{d?(e=a[0]=mH,a[1]=d,this.emitWithAll(e,a)):p&&(a.length>2?a[2]=p:a.push(p),this.emitWithAll(e,a))};return this._awaitWriteFinish(n,c.stabilityThreshold,e,u),this}if(e===tE&&!this._throttle(tE,n,50))return this;if(o.alwaysStat&&r===void 0&&(e===gk||e===kJe||e===tE)){let u=o.cwd?vn.join(o.cwd,n):n,d;try{d=await KJe(u)}catch{}if(!d||this.closed)return;a.push(d)}return this.emitWithAll(e,a),this}_handleError(e){let n=e&&e.code;return e&&n!=="ENOENT"&&n!=="ENOTDIR"&&(!this.options.ignorePermissionErrors||n!=="EPERM"&&n!=="EACCES")&&this.emit(mH,e),e||this.closed}_throttle(e,n,r){this._throttled.has(e)||this._throttled.set(e,new Map);let i=this._throttled.get(e),s=i.get(n);if(s)return s.count++,!1;let o,a=()=>{let l=i.get(n),u=l?l.count:0;return i.delete(n),clearTimeout(o),l&&clearTimeout(l.timeoutObject),u};o=setTimeout(a,r);let c={timeoutObject:o,clear:a,count:0};return i.set(n,c),c}_incrReadyCount(){return this._readyCount++}_awaitWriteFinish(e,n,r,i){let s,o=e;this.options.cwd&&!vn.isAbsolute(e)&&(o=vn.join(this.options.cwd,e));let a=new Date,c=l=>{TH.stat(o,(u,d)=>{if(u||!this._pendingWrites.has(e)){u&&u.code!=="ENOENT"&&i(u);return}let p=Number(new Date);l&&d.size!==l.size&&(this._pendingWrites.get(e).lastChange=p);let m=this._pendingWrites.get(e);p-m.lastChange>=n?(this._pendingWrites.delete(e),i(void 0,d)):s=setTimeout(c,this.options.awaitWriteFinish.pollInterval,d)})};this._pendingWrites.has(e)||(this._pendingWrites.set(e,{lastChange:a,cancelWait:()=>(this._pendingWrites.delete(e),clearTimeout(s),r)}),s=setTimeout(c,this.options.awaitWriteFinish.pollInterval))}_getGlobIgnored(){return[...this._ignoredPaths.values()]}_isIgnored(e,n){if(this.options.atomic&&FJe.test(e))return!0;if(!this._userIgnored){let{cwd:r}=this.options,i=this.options.ignored,s=i&&i.map(Cge(r)),o=EH(s).filter(c=>typeof c===AH&&!fH(c)).map(c=>c+yH),a=this._getGlobIgnored().map(Cge(r)).concat(s,o);this._userIgnored=vH(a,void 0,wH)}return this._userIgnored([e,n])}_isntIgnored(e,n){return!this._isIgnored(e,n)}_getWatchHelpers(e,n){let r=n||this.options.disableGlobbing||!fH(e)?e:TJe(e),i=this.options.followSymlinks;return new SH(e,r,i,this)}_getWatchedDir(e){this._boundRemove||(this._boundRemove=this._remove.bind(this));let n=vn.resolve(e);return this._watched.has(n)||this._watched.set(n,new bH(n,this._boundRemove)),this._watched.get(n)}_hasReadPermissions(e){if(this.options.ignorePermissionErrors)return!0;let r=(e&&Number.parseInt(e.mode,10))&511;return!!(4&Number.parseInt(r.toString(8)[0],10))}_remove(e,n,r){let i=vn.join(e,n),s=vn.resolve(i);if(r=r??(this._watched.has(i)||this._watched.has(s)),!this._throttle("remove",i,100))return;!r&&!this.options.useFsEvents&&this._watched.size===1&&this.add(e,n,!0),this._getWatchedDir(i).getChildren().forEach(p=>this._remove(i,p));let c=this._getWatchedDir(e),l=c.has(n);c.remove(n),this._symlinkPaths.has(s)&&this._symlinkPaths.delete(s);let u=i;if(this.options.cwd&&(u=vn.relative(this.options.cwd,i)),this.options.awaitWriteFinish&&this._pendingWrites.has(u)&&this._pendingWrites.get(u).cancelWait()===gk)return;this._watched.delete(i),this._watched.delete(s);let d=r?PJe:bge;l&&!this._isIgnored(i)&&this._emit(d,i),this.options.useFsEvents||this._closePath(i)}_closePath(e){this._closeFile(e);let n=vn.dirname(e);this._getWatchedDir(n).remove(vn.basename(e))}_closeFile(e){let n=this._closers.get(e);n&&(n.forEach(r=>r()),this._closers.delete(e))}_addPathCloser(e,n){if(!n)return;let r=this._closers.get(e);r||(r=[],this._closers.set(e,r)),r.push(n)}_readdirp(e,n){if(this.closed)return;let r={type:hH,alwaysStat:!0,lstat:!0,...n},i=SJe(e,r);return this._streams.add(i),i.once(OJe,()=>{i=void 0}),i.once(NJe,()=>{i&&(this._streams.delete(i),i=void 0)}),i}};CH.FSWatcher=yk;var ZJe=(t,e)=>{let n=new yk(e);return n.add(t),n};CH.watch=ZJe});function Uge(t){return zR.includes(t)}function Pv(t){return VR.includes(uo.default.extname(t).toLowerCase())}function c9e(t,e){return t.isDirectory()?"folder":Pv(e)?"binary":"file"}function Dp(t){return t<1024?`${t}B`:t<1024*1024?`${(t/1024).toFixed(1)}KB`:`${(t/(1024*1024)).toFixed(1)}MB`}function l9e(t){if(!RH.has(t)){let e=process.platform==="win32"?"where":"which";RH.set(t,(0,la.spawnSync)(e,[t],{stdio:"ignore"}).status===0)}return RH.get(t)}function u9e(t){let e=Yue.find(r=>l9e(r.cmd));if(!e)throw new Error("HEIC needs a system converter (macOS has sips; on Linux install libheif-examples or imagemagick)");let n=uo.default.join(cc.default.tmpdir(),`9r-heic-${process.pid}-${Date.now()}.jpg`);try{let r=(0,la.spawnSync)(e.cmd,e.args(t,n),{timeout:Xue});if(r.status!==0||!st.default.existsSync(n))throw new Error(`HEIC decode failed (${e.cmd}): ${r.stderr?.toString().trim()||"unknown error"}`);return st.default.readFileSync(n)}finally{try{st.default.unlinkSync(n)}catch{}}}async function Mv(t,e,n=1600){let r=KR(e)?u9e(e):t,i=await(0,_k.default)(r).metadata(),s=i.orientation>=5,o=(s?i.height:i.width)||0,a=(s?i.width:i.height)||0,c=[80,60,40],l=n>=1600?[1600,1200,800]:[n],u=r,d=o,p=a;for(let m of l)for(let h of c){u=await(0,_k.default)(r).rotate().resize({width:m,height:m,fit:"inside",withoutEnlargement:!0}).jpeg({quality:h,mozjpeg:!0}).toBuffer();let y=await(0,_k.default)(u).metadata();if(d=y.width||m,p=y.height||m,u.length<=3145728)return{buffer:u,width:d,height:p,originalWidth:o,originalHeight:a}}return{buffer:u,width:d,height:p,originalWidth:o,originalHeight:a}}function Bge(t,e,n,r=50){if(!(n.length>=r))try{for(let i of st.default.readdirSync(t)){if(n.length>=r)return;if(i.startsWith(".")||Uge(i))continue;let s=uo.default.join(t,i);try{let o=st.default.statSync(s);o.isDirectory()?Bge(s,e,n,r):i.toLowerCase().includes(e.toLowerCase())&&n.push({name:i,path:s,type:Pv(i)?"binary":"file",size:o.size,sizeFormatted:Dp(o.size)})}catch{}}}catch{}}function Nge(t){if(!t)return null;let e=t.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*/g,"::ANY::").replace(/\*/g,"[^/]*").replace(/::ANY::/g,".*").replace(/\?/g,".");return new RegExp(`^${e}$`)}function d9e(){return vk!==null?Promise.resolve(vk):new Promise(t=>{(0,la.execFile)("rg",["--version"],{timeout:2e3},e=>{vk=!e,t(vk)})})}function p9e(t,{query:e,caseSensitive:n,wholeWord:r,regex:i,includeGlob:s,excludeGlob:o}){return new Promise(a=>{let c=["--json","--hidden","--max-filesize","1M","-m",String(10)];n||c.push("-i"),r&&c.push("-w"),c.push("-g",`!{${zR.join(",")}}`),s&&c.push("-g",s),o&&c.push("-g",`!${o}`),c.push("--",i?e:e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),t);let l=(0,la.spawn)("rg",c,{stdio:["ignore","pipe","ignore"],windowsHide:!0}),u=[],d=null,p=setTimeout(()=>l.kill(),1e4),m=()=>{clearTimeout(p),a(u)};Lge.default.createInterface({input:l.stdout}).on("line",y=>{let v;try{v=JSON.parse(y)}catch{return}if(v.type!=="match"||!v.data)return;let E=v.data,A=E.path?.text,b=E.submatches?.[0];if(!A||b===void 0||gt(A))return;if(!d||d.path!==A){if(u.length>=200){l.kill(),m();return}d={path:A,matches:[]},u.push(d)}let S=(E.lines?.text||"").replace(/\r?\n$/,""),I=Math.max(0,b.start-120),F=Math.min(S.length,b.end+120);d.matches.push({line:E.line_number,column:b.start+1,contextStart:I,lineText:S.slice(I,F),matchLength:b.end-b.start})}),l.on("error",()=>{clearTimeout(p),a(null)}),l.on("close",y=>{clearTimeout(p),a(y===2&&u.length===0?null:u)})})}async function qge(t,e,n,r,i,s,o){if(s.length>=200)return;let a;try{a=st.default.readdirSync(t,{withFileTypes:!0})}catch{return}for(let c of a){if(s.length>=200||Date.now()>o.deadline)return;if(++o.count%64===0&&await new Promise(d=>setImmediate(d)),Uge(c.name))continue;let l=uo.default.join(t,c.name),u=uo.default.relative(e,l);if(c.isDirectory()){await qge(l,e,n,r,i,s,o);continue}if(c.isFile()&&!Pv(c.name)&&!gt(l)&&!(i&&i.test(u))&&!(r&&!r.test(u)))try{if(st.default.statSync(l).size>1048576)continue;let m=st.default.readFileSync(l,"utf-8").split(`
1063
1063
  `),h=[];for(let y=0;y<m.length&&h.length<10;y++){let v=m[y],E=n(v);for(let A of E){if(h.length>=10)break;let b=Math.max(0,A.column-120),S=Math.min(v.length,A.column+A.length+120);h.push({line:y+1,column:A.column+1,contextStart:b,lineText:v.slice(b,S),matchLength:A.length})}}h.length&&s.push({path:l,matches:h})}catch{}}}function $ge(t,e,n){let r;try{r=st.default.readdirSync(t,{withFileTypes:!0})}catch{return[]}let i=[];for(let s of r){if(!n&&s.name.startsWith(".")&&s.name!==".env"&&s.name!==".env.example")continue;let o=uo.default.join(t,s.name);if(s.isDirectory()){let a={name:s.name,path:o,type:"folder"};e>0&&(a.children=$ge(o,e-1,n)),i.push(a)}else s.isFile()&&i.push({name:s.name,path:o,type:Pv(s.name)?"binary":"file"})}return i.sort((s,o)=>s.type==="folder"&&o.type!=="folder"?-1:s.type!=="folder"&&o.type==="folder"?1:s.name.localeCompare(o.name)),i}function f9e(){if(process.platform!=="win32")return[];try{return(0,la.execSync)("wmic logicaldisk get name",{encoding:"utf-8",stdio:["pipe","pipe","pipe"],windowsHide:!0}).split(/\r?\n/).map(e=>e.trim()).filter(e=>/^[A-Z]:$/.test(e)).map(e=>({letter:e[0],path:e+"\\"}))}catch{return"CDEFGHIJ".split("").map(t=>`${t}:\\`).filter(t=>st.default.existsSync(t)).map(t=>({letter:t[0],path:t}))}}function Gge(t){t.on("getSystemInfo",n=>{let r=process.platform;n({success:!0,platform:r,isWindows:r==="win32",drives:r==="win32"?f9e():[],homedir:cc.default.homedir()})}),t.on("getFiles",({dirPath:n,showHidden:r},i)=>{try{let s=n||cc.default.homedir(),o=s.startsWith("~")?s.replace("~",cc.default.homedir()):s;if(gt(o))return i({success:!1,error:"Access denied"});if(!st.default.existsSync(o))return i({success:!1,error:"Directory not found"});let a;try{a=st.default.readdirSync(o,{withFileTypes:!0})}catch(d){return i({success:!1,error:d.message})}r||(a=a.filter(d=>!(d.name.startsWith(".")&&d.name!==".env"&&d.name!==".env.example"))),a.sort((d,p)=>{let m=d.isDirectory(),h=p.isDirectory();return m&&!h?-1:!m&&h?1:d.name.localeCompare(p.name)});let c=a.length>300,l=c?a.slice(0,300):a,u=[];for(let d of l)try{let p=uo.default.join(o,d.name),m=st.default.statSync(p);u.push({name:d.name,path:p,type:c9e(m,d.name),size:m.isFile()?m.size:null,sizeFormatted:m.isFile()?Dp(m.size):null,modified:m.mtime.getTime()})}catch{}i({success:!0,files:u,currentPath:o,parentPath:uo.default.dirname(o),truncated:c})}catch(s){i({success:!1,error:s.message})}}),t.on("searchFiles",({workspace:n,query:r},i)=>{try{if(!r||r.length<2)return i({success:!0,files:[]});let s=(n||cc.default.homedir()).replace(/^~/,cc.default.homedir());if(!st.default.existsSync(s))return i({success:!1,error:"Workspace not found"});let o=[];Bge(s,r,o,50),o.sort((a,c)=>{let l=a.name.toLowerCase()===r.toLowerCase(),u=c.name.toLowerCase()===r.toLowerCase();return l&&!u?-1:!l&&u?1:a.path.length-c.path.length}),i({success:!0,files:o})}catch(s){i({success:!1,error:s.message})}}),t.on("readFile",({filePath:n},r)=>{try{if(gt(n))return r({success:!1,error:"Access denied"});if(!st.default.existsSync(n))return r({success:!1,error:"File not found"});let i=st.default.statSync(n);if(i.size>1048576)return r({success:!1,error:`File too large (${Dp(i.size)}). Max ${Dp(1048576)}`});if(Pv(n))return r({success:!1,error:"Cannot open binary file"});if(i.size>Cw)return r({success:!0,content:"",streamInstead:!0,size:i.size});r({success:!0,content:st.default.readFileSync(n,"utf-8")})}catch(i){r({success:!1,error:i.message})}}),t.on("readMedia",async({filePath:n,maxDim:r},i)=>{try{if(gt(n))return i({success:!1,error:"Access denied"});if(!st.default.existsSync(n))return i({success:!1,error:"File not found"});let s=st.default.statSync(n),o=uo.default.extname(n).toLowerCase().slice(1),a=Gh[o]||"application/octet-stream",c=a.startsWith("image/"),l=c?20971520:5242880;if(s.size>l)return i({success:!1,error:`File too large (${Dp(s.size)}). Max ${Dp(l)}`});let u=st.default.readFileSync(n);if(c){let d=Number(r),p=Number.isFinite(d)&&d>0?Math.min(d,1600):1600,m=await Mv(u,n,p),h=`data:image/jpeg;base64,${m.buffer.toString("base64")}`;i({success:!0,dataUrl:h,size:s.size,mime:a,originalSize:s.size,originalWidth:m.originalWidth,originalHeight:m.originalHeight,width:m.width,height:m.height,scaled:m.buffer.length<s.size})}else{let d=`data:${a};base64,${u.toString("base64")}`;i({success:!0,dataUrl:d,size:s.size,mime:a})}}catch(s){i({success:!1,error:s.message})}}),t.on("readImage",async({filePath:n},r)=>{try{if(gt(n))return r({success:!1,error:"Access denied"});if(!st.default.existsSync(n))return r({success:!1,error:"File not found"});let i=st.default.statSync(n);if(i.size>20971520)return r({success:!1,error:`Image too large (${Dp(i.size)}). Max ${Dp(20971520)}`});let s=st.default.readFileSync(n),o=await Mv(s,n),a=`data:image/jpeg;base64,${o.buffer.toString("base64")}`;r({success:!0,dataUrl:a,size:i.size,mime:"image/jpeg",originalSize:i.size,originalWidth:o.originalWidth,originalHeight:o.originalHeight,width:o.width,height:o.height,scaled:o.buffer.length<i.size})}catch(i){r({success:!1,error:i.message})}}),t.on("writeFile",({filePath:n,content:r},i)=>{try{if(gt(n))return i({success:!1,error:"Access denied"});st.default.writeFileSync(n,r,"utf-8"),i({success:!0})}catch(s){i({success:!1,error:s.message})}}),t.on("createItem",({itemPath:n,type:r},i)=>{try{if(gt(n))return i({success:!1,error:"Access denied"});if(st.default.existsSync(n))return i({success:!1,error:"Item already exists"});r==="folder"?st.default.mkdirSync(n,{recursive:!0}):st.default.writeFileSync(n,"","utf-8"),i({success:!0})}catch(s){i({success:!1,error:s.message})}}),t.on("deleteItem",({itemPath:n},r)=>{try{if(gt(n))return r({success:!1,error:"Access denied"});if(!st.default.existsSync(n))return r({success:!1,error:"Item not found"});st.default.statSync(n).isDirectory()?st.default.rmSync(n,{recursive:!0}):st.default.unlinkSync(n),r({success:!0})}catch(i){r({success:!1,error:i.message})}}),t.on("copyItem",({srcPath:n,destPath:r},i)=>{try{if(gt(n)||gt(r))return i({success:!1,error:"Access denied"});if(!st.default.existsSync(n))return i({success:!1,error:"Item not found"});if(st.default.existsSync(r))return i({success:!1,error:"Target already exists"});if(r.startsWith(n+"/"))return i({success:!1,error:"Cannot copy into itself"});st.default.cpSync(n,r,{recursive:!0}),i({success:!0})}catch(s){i({success:!1,error:s.message})}}),t.on("renameItem",({oldPath:n,newPath:r},i)=>{try{if(gt(n)||gt(r))return i({success:!1,error:"Access denied"});if(!st.default.existsSync(n))return i({success:!1,error:"Item not found"});if(st.default.existsSync(r))return i({success:!1,error:"Target already exists"});st.default.renameSync(n,r),i({success:!0})}catch(s){i({success:!1,error:s.message})}}),t.on("searchInFiles",async({workspace:n,query:r,caseSensitive:i,wholeWord:s,regex:o,includeGlob:a,excludeGlob:c},l)=>{try{if(!r)return l({success:!0,results:[]});let u=(n||cc.default.homedir()).replace(/^~/,cc.default.homedir());if(!st.default.existsSync(u))return l({success:!1,error:"Workspace not found"});if(await d9e()){let E=await p9e(u,{query:r,caseSensitive:i,wholeWord:s,regex:o,includeGlob:a,excludeGlob:c});if(E)return l({success:!0,results:E})}let d=E=>A=>{let b=[],S;for(E.lastIndex=0;(S=E.exec(A))!==null;)b.push({column:S.index,length:S[0].length}),S.index===E.lastIndex&&E.lastIndex++;return b},p;if(o){let E;try{E=new RegExp(r,i?"g":"gi")}catch(A){return l({success:!1,error:`Invalid regex: ${A.message}`})}p=d(E)}else if(s){let E=r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");p=d(new RegExp(`\\b${E}\\b`,i?"g":"gi"))}else{let E=i?r:r.toLowerCase();p=A=>{let b=i?A:A.toLowerCase(),S=[],I=0;for(;(I=b.indexOf(E,I))!==-1;)S.push({column:I,length:E.length}),I+=E.length||1;return S}}let m=Nge(a),h=Nge(c),y=[],v={count:0,deadline:Date.now()+1e4};await qge(u,u,p,m,h,y,v),l({success:!0,results:y})}catch(u){l({success:!1,error:u.message})}}),t.on("replaceInFiles",({workspace:n,query:r,replacement:i,caseSensitive:s,regex:o,files:a},c)=>{try{if(!r||!Array.isArray(a)||!a.length)return c({success:!0,replacedCount:0,fileCount:0});let l;if(o){let p;try{p=new RegExp(r,s?"g":"gi")}catch(m){return c({success:!1,error:`Invalid regex: ${m.message}`})}l=m=>{let h=0;return{next:m.replace(p,v=>(h++,i)),count:h}}}else l=p=>{let m=0,h=s?"g":"gi",y=r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),v=new RegExp(y,h);return{next:p.replace(v,()=>(m++,i)),count:m}};let u=0,d=0;for(let p of a)try{if(!st.default.existsSync(p)||Pv(p)||gt(p))continue;let m=st.default.statSync(p);if(!m.isFile()||m.size>1048576)continue;let h=st.default.readFileSync(p,"utf-8"),{next:y,count:v}=l(h);v>0&&(st.default.writeFileSync(p,y,"utf-8"),u+=v,d++)}catch{}c({success:!0,replacedCount:u,fileCount:d})}catch(l){c({success:!1,error:l.message})}});let e=new Map;t.on("watchDir",({dirPath:n},r)=>{try{if(!n||!st.default.existsSync(n))return r({success:!1,error:"Directory not found"});let i=e.get(n);if(i)return i.count++,r({success:!0});if(e.size>=60)return r({success:!0,watching:!1});let s=Fge.default.watch(n,{depth:0,ignoreInitial:!0,persistent:!0,ignored:c=>zR.includes(uo.default.basename(c))}),o={w:s,count:1,burstStart:0,burstCount:0,mutedUntil:0},a=c=>l=>{let u=Date.now();if(!(u<o.mutedUntil)){if(u-o.burstStart>1e3&&(o.burstStart=u,o.burstCount=0),++o.burstCount>30)return o.mutedUntil=u+3e3,t.emit("fileChange",{type:"flooded",path:n});t.emit("fileChange",{type:c,path:l})}};s.on("add",a("add")).on("change",a("change")).on("unlink",a("unlink")).on("addDir",a("addDir")).on("unlinkDir",a("unlinkDir")),e.set(n,o),r({success:!0,watching:!0})}catch(i){r({success:!1,error:i.message})}}),t.on("unwatchDir",({dirPath:n},r)=>{try{let i=e.get(n);i&&--i.count<=0&&(i.w.close(),e.delete(n)),r({success:!0})}catch(i){r({success:!1,error:i.message})}}),t.once("disconnect",()=>{for(let{w:n}of e.values())try{n.close()}catch{}e.clear()}),t.on("revealInOS",({filePath:n},r)=>{try{if(!n)return r({success:!1,error:"No path"});let i=process.platform,s,o;i==="darwin"?(s="open",o=["-R",n]):i==="win32"?(s="explorer",o=[`/select,${n}`]):(s="xdg-open",o=[uo.default.dirname(n)]);let a=(0,la.spawn)(s,o,{detached:!0,stdio:"ignore",windowsHide:!0});a.on("error",c=>r({success:!1,error:c.message})),a.unref(),r({success:!0})}catch(i){r({success:!1,error:i.message})}}),t.on("openInTerminal",({dirPath:n},r)=>{try{if(!n||!st.default.existsSync(n))return r({success:!1,error:"Directory not found"});let i=process.platform,s,o,a={detached:!0,stdio:"ignore",windowsHide:!0};i==="darwin"?(s="open",o=["-a","Terminal",n]):i==="win32"?(s="cmd",o=["/C","start",'"9Remote"',"cmd","/K"],a.shell=!1,a.cwd=n):(s="gnome-terminal",o=["--working-directory",n]);let c=(0,la.spawn)(s,o,a);c.on("error",()=>{if(i==="linux"){let l=(0,la.spawn)("xterm",["-e","bash"],{...a,cwd:n});l.on("error",u=>r({success:!1,error:u.message})),l.unref()}else r({success:!1,error:"Failed to open terminal"})}),c.unref(),r({success:!0})}catch(i){r({success:!1,error:i.message})}}),t.on("getFileTree",({dirPath:n,depth:r,showHidden:i},s)=>{try{let o=(n||cc.default.homedir()).replace(/^~/,cc.default.homedir());if(!st.default.existsSync(o))return s({success:!1,error:"Directory not found"});let c=$ge(o,typeof r=="number"?r:3,!!i);s({success:!0,tree:{name:uo.default.basename(o)||o,path:o,type:"folder",children:c}})}catch(o){s({success:!1,error:o.message})}})}var st,uo,cc,Lge,la,Fge,_k,RH,vk,xk=ne(()=>{st=Q(require("fs"),1),uo=Q(require("path"),1),cc=Q(require("os"),1),Lge=Q(require("readline"),1),la=require("child_process"),Fge=Q(Mge(),1),_k=Q(require("sharp"),1);iv();zi();jh();RH=new Map;vk=null});async function OH(t,e){if(!t||!Xo(t))return{success:!1,error:"Not a git repository or git not available"};let n=MH.get(t),r=Date.now();if(!e&&n&&r-n.ts<g9e)return n.value;if(n?.pending)try{return await n.pending}catch{return{success:!1}}let i=Vr(["status","--porcelain","--no-renames","-uall"],t).then(s=>{let o=s.code===0?{success:!0,count:s.stdout.trim()?s.stdout.trim().split(`
1064
1064
  `).length:0}:{success:!1,error:"Not a git repository or git not available"};return MH.set(t,{ts:Date.now(),value:o,pending:null}),o}).catch(()=>({success:!1}));MH.set(t,{ts:r,value:{success:!1},pending:i});try{return await i}catch{return{success:!1}}}function y9e(){return Hge("git")?"git":(process.platform==="win32"?["C:\\Program Files\\Git\\cmd\\git.exe","C:\\Program Files (x86)\\Git\\cmd\\git.exe"]:["/usr/bin/git","/usr/local/bin/git","/opt/homebrew/bin/git"]).find(Hge)||null}function Vr(t,e){return new Promise(n=>{if(!rE)return n({code:-1,stdout:"",stderr:zge});let r=(0,Ku.spawn)(rE,t,{cwd:e,windowsHide:!0}),i="",s="";r.stdout.on("data",o=>{i+=o.toString()}),r.stderr.on("data",o=>{s+=o.toString()}),r.on("error",o=>n({code:-1,stdout:i,stderr:o.message})),r.on("close",o=>n({code:o,stdout:i,stderr:s}))})}function Ov(t,e){if(!rE)throw new Error(zge);let n=(0,Ku.spawnSync)(rE,t,{cwd:e,encoding:"utf-8",windowsHide:!0,maxBuffer:67108864});if(n.error)throw n.error;return n.stdout??""}function jge(t){return VR.includes(Nr.default.extname(t).toLowerCase())}function Wge(t,e){if(!e||!t||!Nr.default.isAbsolute(e))return e;let n=Nr.default.relative(t,e);return!n||n.startsWith("..")||Nr.default.isAbsolute(n)?e:n.split(Nr.default.sep).join("/")}function v9e(t){return t.length<=4194304?t:`${t.slice(0,4194304)}
@@ -1177,9 +1177,9 @@ https://cloud.google.com/compute/docs/metadata/predefined-metadata-keys`};var Z6
1177
1177
  return "default";
1178
1178
  })()`,Jke=new Map,Qke=new Map,Zke=new Map,ePe=!1;zb=new Map});function cPe(){let t="";for(let e=0;e<ext;e++)t+=sPe[PK.default.randomInt(sPe.length)];return t}function MK(){let t=mZ(aPe,null);return!t||Date.now()>t.expiresAt?null:t}function lPe(t){try{kn(aPe,t)}catch(e){l1.error(`persist pairing state: ${e.message}`)}}function uPe(t,e,n,r=null){lPe({tempKey:t,tail:e,expiresAt:n,workerUrl:r})}function txt(){lPe({tempKey:null,tail:null,expiresAt:0,workerUrl:null})}async function nxt(t,e){if(!(!t||!e))try{await Rc(`${e}/api/temp-key/remove`,{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({tempKey:t})}),l1.info(`one-time code revoked at the Worker: ${t}`)}catch(n){l1.warn(`could not revoke the code at the Worker: ${n.message}`)}}function Vb(){let t=MK();return t?{tempKey:t.tempKey,tail:t.tail,expiresAt:t.expiresAt}:null}function u1(t){let e=MK();if(!e?.tail||!t)return!1;let n=Buffer.from(String(t).toUpperCase(),"utf8"),r=Buffer.from(String(e.tail).toUpperCase(),"utf8");return n.length===r.length&&PK.default.timingSafeEqual(n,r)}function OK(t,e=null){let n=MK();return!n||!t?{match:!1,burned:!1}:u1(t)?{match:!0,burned:!1}:!e||String(e).trim().toUpperCase()===String(n.tempKey).trim().toUpperCase()?(txt(),l1.warn("pairing tail mismatch \u2014 code killed here and at the Worker"),nxt(n.tempKey,n.workerUrl),{match:!1,burned:!0}):{match:!1,burned:!1}}var PK,oPe,l1,aPe,sPe,ext,NK=ne(()=>{PK=Q(require("crypto"),1),oPe=require("path");qt();$e();qo();qt();l1=Ee("pairing"),aPe=(0,oPe.join)(Pe.STATE,"pairing.json"),sPe="ABCDEFGHIJKLMNPQRSTUVWXYZ123456789",ext=2});function pPe(){let t="";for(let e=0;e<rxt;e++)t+=dPe[fPe.default.randomInt(dPe.length)];return t}function hPe(t){return`sk-${(t||"").slice(0,8).toLowerCase()}-${pPe()}-${pPe()}`}function mPe(t){return/^sk-[a-z0-9]{8}-[a-np-z1-9]{8}-[a-np-z1-9]{8}$/.test(t||"")}function sr(t){if(!mPe(t))return t||null;let e=t.split("-");return`${e[0]}-${e[1]}-${e[2]}`}function d1(t){return mPe(t)?t.split("-")[3]:null}var fPe,dPe,rxt,Um=ne(()=>{fPe=Q(require("crypto"),1),dPe="abcdefghijklmnpqrstuvwxyz123456789",rxt=8});var wPe={};fr(wPe,{PROOF_DEADLINE:()=>$K,admissionGate:()=>GK,clearProofWaiters:()=>qK,finishTailRejection:()=>h1,handleTailProof:()=>HK,isProvingExpired:()=>lxt,isTailProofEnabled:()=>q_,noteTailFailure:()=>Yb,onTailProven:()=>f1,presentedTailOf:()=>Xb,submitTailProof:()=>p1,verdictStateOf:()=>Kb,verifyKeyTail:()=>$_,verifyPresentedTail:()=>dxt});function _Pe(){return d1(Go()?.key||"")}function q_(){return!!_Pe()}function BK(t,e){let n=t?FK.get(t):null;return!n||n.keyHead!==e?null:n}function yPe(t,e,n,r=null){if(!t)return;let i=FK.get(t);FK.set(t,{keyHead:e,state:n,reason:r,since:Date.now()}),n!==i?.state&&(n===Uo.proven&&uxt(t),n===Uo.rejected&&gd.delete(t))}function p1(t,e,{pairing:n=!1,tempKey:r=null}={}){let i=sr(Go()?.key||"");if(!t||!q_()&&!n)return!1;if((n?OK(e,r):{match:$_(e)}).match)return yPe(t,i,Uo.proven),dee(t,i),LK.info(`[seal] proof accepted: device=${t.slice(0,8)}`),!0;let o=e===null?mi.sealUnreadable:mi.mismatch;return yPe(t,i,Uo.rejected,o),LK.warn(`[seal] proof rejected (${o}): device=${t.slice(0,8)}`),!1}function lxt(t){let e=BK(t,sr(Go()?.key||""));return!!e&&e.state===Uo.proving&&Date.now()-e.since>UK}function Kb(t){return BK(t,sr(Go()?.key||""))?.state||null}function f1(t,e,n){if(!t||!q_()||Kb(t)===Uo.proven)return e();gd.has(t)||gd.set(t,new Set),gd.get(t).add(e),n&&setTimeout(()=>{let r=gd.get(t);r?.delete(e)&&(r.size||gd.delete(t),n())},UK)}function uxt(t){let e=gd.get(t);if(e){gd.delete(t);for(let n of e)try{n()}catch{}}}function qK(t){gd.delete(t)}function Yb(t){let e=Date.now(),n=(gPe.get(t)||[]).filter(i=>e-i<axt);n.push(e),gPe.set(t,n);let r=n.length-ixt;return r<=0?0:Math.min(sxt*2**(r-1),oxt)}function dxt({tail:t,tempKey:e}={}){let n=!!e;if(!n&&!q_())return{ok:!0};if(!t)return{ok:!1,reason:mi.mismatch,penaltyMs:0};let r=n?OK(t,e):{match:$_(t)};return r.match?{ok:!0}:{ok:!1,reason:mi.mismatch,burned:!!r.burned,penaltyMs:Yb(sr(Go()?.key||""))}}function GK(t,e,{provenSocket:n=!1,tempKey:r=null}={}){let i=sr(Go()?.key||""),s=Kw(t);if(s===ds.rejected)return{step:"authz",decision:$r.reject,reason:"device-rejected"};let o=!!r&&!vA(t);if(o){let a=Vb();LK.info(`[pair] device=${t?.slice(0,8)} presented=${e===void 0?"none":String(e).length+"ch"} liveCode=${a?"yes":"no"} liveTail=${a?.tail?String(a.tail).length+"ch":"none"} match=${e===void 0?"n/a":u1(String(e))}`)}if(q_()||o){let a=BK(t,i);if(a?.state===Uo.rejected&&e===void 0)return{step:"auth",decision:$r.reject,reason:a.reason};let c=u=>o?u1(u):$_(u);if(!(n||a?.state===Uo.proven||e!==void 0&&c(e)))return e!==void 0?{step:"auth",decision:$r.reject,reason:e===null?mi.sealUnreadable:mi.mismatch}:{step:"auth",decision:$r.hold,reason:"awaiting-proof"}}return s===ds.approved||s===ds.auto?{step:"authz",decision:$r.admit}:{step:"authz",decision:$r.hold,reason:"host-decides"}}function $_(t){let e=_Pe();if(!e||!t)return!1;let n=Buffer.from(String(t),"utf8"),r=Buffer.from(e,"utf8");return n.length===r.length&&vPe.default.timingSafeEqual(n,r)}function Xb(t,e){let n=t?.keyTailSealed;return n!==void 0?!n||typeof n!="object"||Array.isArray(n)?null:e(n)??null:t?.keyTail}function HK(t,e){let n=t?.data?.auth?.deviceId||t.handshake?.auth?.deviceId||t.deviceId||null,r=e&&"tempKey"in e?e.tempKey||null:t.handshake?.auth?.tempKey||null,i=!!r&&!!Vb();if(!n||!q_()&&!i)return!0;let s=Xb(e,Ow);return s===void 0||p1(n,s,{pairing:i,tempKey:r})?!0:(t.data.tailReject={reason:s===null?mi.sealUnreadable:mi.mismatch,penaltyMs:Yb(sr(Go()?.key||""))},!1)}function h1(t,e){if(t.data?.tailRejectFinished)return;t.data.tailRejectFinished=!0;let{reason:n,penaltyMs:r=0}=t.data?.tailReject||{},i=DK>=cxt,s=i?0:r;i||DK++,setTimeout(()=>{i||DK--;try{t.emit("device:tailRejected",{reason:n}),t.disconnect()}catch{}e?.()},s)}var vPe,LK,ixt,sxt,oxt,axt,cxt,gPe,DK,FK,UK,gd,$K,jK=ne(()=>{vPe=Q(require("crypto"),1);$e();Xw();NK();zi();Um();hu();Nw();LK=Ee("deviceAuth");ixt=5,sxt=1e3,oxt=60*1e3,axt=3600*1e3,cxt=20,gPe=new Map,DK=0,FK=new Map,UK=2e4;gd=new Map;$K=UK});var xPe,m1,EPe=ne(()=>{xPe=require("events");Qg();m1=class extends xPe.EventEmitter{constructor({deviceId:e,peerId:n=null,apiKey:r=null}){super(),this.setMaxListeners(0),this.deviceId=e,this.peerId=n||e,this.apiKey=r,this.createdAt=Date.now(),this.data={},this._state=ti.authenticating,this._carriers=new Map}get state(){return this._state}get active(){return this._state===ti.active}get closed(){return this._state===ti.closed}get carrierIds(){return[...this._carriers.keys()]}get connected(){for(let e of this._carriers.values())if(e?.ready)return!0;return!1}attach(e,n){if(this.closed)return!1;let r=this._carriers.get(e);return r&&r!==n&&this._detachOne(e,r),this._carriers.set(e,n),this.emit("carrierAttached",e,n),!0}detach(e){let n=this._carriers.get(e);return n?(this._detachOne(e,n),!0):!1}_detachOne(e,n){this._carriers.delete(e),this.emit("carrierDetached",e,n)}hasCarrier(e){return this._carriers.has(e)}carrier(e){return this._carriers.get(e)||null}allows(e){return this.active?!0:this.closed?!1:Jg.has(e)}keyProven(){return this._state!==ti.authenticating?!1:this._transition(ti.awaitingHost,"key-proven")}hostAllowed(){return this._state!==ti.awaitingHost?!1:this._transition(ti.active,"host-allowed")}close(e="closed"){if(this.closed)return!1;for(let[n,r]of[...this._carriers])this._detachOne(n,r);return this._transition(ti.closed,e)}_transition(e,n){let r=this._state;return this._state=e,this.emit("state",{from:r,to:e,reason:n,deviceId:this.deviceId}),!0}toJSON(){return{deviceId:this.deviceId,peerId:this.peerId,state:this._state,carriers:this.carrierIds,createdAt:this.createdAt}}}});var g1,bPe=ne(()=>{EPe();Qg();g1=class{constructor(){this._byPeer=new Map,this._byDevice=new Map}open({deviceId:e,peerId:n,apiKey:r}){let i=n||e,s=this._byPeer.get(i);if(s&&!s.closed)return s;let o=new m1({deviceId:e,peerId:i,apiKey:r});return this._byPeer.set(i,o),this._byDevice.has(e)||this._byDevice.set(e,new Set),this._byDevice.get(e).add(i),o.on("state",a=>{a.to===ti.closed&&this.delete(i)}),o}get(e){let n=this._byPeer.get(e);return n&&!n.closed?n:null}forDevice(e){let n=this._byDevice.get(e);if(!n)return[];let r=[];for(let i of n){let s=this._byPeer.get(i);s&&!s.closed&&r.push(s)}return r}closeDevice(e,n){let r=this.forDevice(e);for(let i of r)i.close(n);return r.length}delete(e){let n=this._byPeer.get(e);if(!n)return!1;this._byPeer.delete(e);let r=this._byDevice.get(n.deviceId);return r&&(r.delete(e),r.size||this._byDevice.delete(n.deviceId)),!0}get size(){return this._byPeer.size}all(){return[...this._byPeer.values()]}}});function SPe(t,e){return!t||t.closed?{effects:[]}:e.decision===$r.reject?{effects:["refuse"],reason:e.reason||mi.mismatch}:e.decision===$r.hold&&e.step==="auth"?t.state===ti.authenticating?{effects:["open-auth-channel"],reason:e.reason}:{effects:[],reason:e.reason}:(t.state===ti.authenticating&&t.keyProven(),e.decision===$r.hold?{effects:["ask-host"],reason:e.reason}:(t.state===ti.awaitingHost&&t.hostAllowed(),{effects:t.active?["start-session"]:[]}))}var TPe=ne(()=>{Qg();zi()});function Sa(){try{let t=(0,RPe.join)(Pe.ROOT,"keys.json");return JSON.parse((0,CPe.readFileSync)(t,"utf8")).key||null}catch{return null}}function jr(){return Ns}function Qb(t){return t.carrier||{id:"ws",ip:t.handshake?.headers?.["x-forwarded-for"]||t.handshake?.address||"unknown",pendingId:t.id}}function or(t){return t?.data?.auth||t?.handshake?.auth||null}function VK(t,e){let n=t?Xb(or(t),Ow):void 0,r=GK(e,n,{provenSocket:t?.data?.provenDevice===!0,tempKey:or(t)?.tempKey||null});Rr.info(`gate: device=${e?.slice(0,8)??"none"} step=${r.step} decision=${r.decision}${r.reason?` reason=${r.reason}`:""} carrier=${t?Qb(t).id:"signaling"}`);let i=!!or(t)?.tempKey,s=r.step==="authz"&&!i;return t&&n!==void 0&&(s||r.step==="auth")&&p1(e,n,{pairing:i,tempKey:or(t)?.tempKey||null}),t&&r.decision===$r.reject&&r.step==="auth"&&(t.data.tailReject=t.data.tailReject||{reason:r.reason,penaltyMs:Yb(sr(Sa()||""))}),r}function fxt(t){t.data.authHandlersReady||(t.data.authHandlersReady=!0,t.on("device:tailProof",e=>{let n=or(t)?.deviceId;e?.tempKey&&t.data&&(t.data.auth||(t.data.auth={}),t.data.auth.tempKey=e.tempKey);try{let r=HK(t,e);Rr.info(`tailProof: device=${n?.slice(0,8)} carrier=${Qb(t).id} accepted=${r}`),r||H_(t,n)}catch(r){Rr.warn(`tailProof handler failed: ${r.message}`)}}))}async function Zb(t){if(or(t)?.tempKey&&(Rr.info("one-time key used \u2014 clearing from UI"),dA()),await gxt(t),fxt(t),!t.data.localUi){let e=or(t)?.deviceId||null,n=yxt(t);if(!n)return;let{id:r}=Qb(t);n.attach(r,t.data.protocol?._adapters?.get(r)||null);let i=VK(t,e),{effects:s,reason:o}=SPe(n,i);if(Rr.info(`flow: device=${e?.slice(0,8)} state=${n.state} effects=[${s.join(",")}]${o?` reason=${o}`:""}`),tn(`[auth] ${e?.slice(0,8)}: ${n.state} \u2192 ${s.join(",")||"wait"}`),s.includes("refuse")){H_(t,e,o);return}if(s.includes("open-auth-channel")){t.data.awaitingProof||(t.data.awaitingProof=!0,f1(e,()=>{t.data.awaitingProof=!1,t.connected&&Zb(t).catch(()=>{})},()=>H_(t,e,mi.timeout)));return}if(s.includes("ask-host")){let a=Qb(t);QK(e,{socketId:a.pendingId,ip:a.ip,peerId:t.peerId,notify:()=>Bm(t,"device:pendingApproval")});return}if(!s.includes("start-session"))return;Kw(e)===ds.auto&&(_A(e),dy(e),qn("deviceApproval",{action:"refresh"}))}await mxt(t)}function hxt(t){if(!or(t)?.tempKey)return;let e=d1(Sa()||"");e&&JK(t,()=>{Bm(t,"device:keyIssued",{tail:e}),Rr.info(`key issued to paired device=${or(t)?.deviceId?.slice(0,8)}`)})}function IPe(t){if(!t.connected||!t.data?.conn?.active&&!t.data?.localUi||!t.data?.clientReady)return;y1(t),hxt(t);let e=Np._buildServerInfo?.();e&&t.emit("serverInfo",e),t.emit("srvCaps",{env2:1,fragCtl:1,seqCtl:1,inputAck:1,promptDedupe:1}),t.emit("tunnel:updated",uA())}async function mxt(t){t.data.sessionReady||(t.data.sessionReady=!0,t.data.approved=!0,UEe(t),qEe(t),Sbe(t),kbe(t),gSe(t,Ns),Gke(t),a$(t),rPe(t),await kG(t,Ns,Sa()),IPe(t),t.emit("terminal:ready"))}async function gxt(t){if(t.data.protocol)return;let{webrtc:e,streaming:n}=Te,r=new xA(t,{enableWebRTC:e.enableWebRTC,enableTurn:e.enableTurn??!1,apiKey:sr(Sa()),turnApiUrl:e.turnApiUrl||null,turnRefreshInterval:e.turnRefreshInterval,dcMaxMessageSize:e.dcMaxMessageSize,dcChunkSize:e.dcChunkSize,dcMaxTilesPerFrame:e.dcMaxTilesPerFrame,answerTimeout:e.answerTimeout,maxControlBuffer:e.maxControlBuffer,wsChunkSize:n.chunkSize,signaling:{deviceId:t.peerId||or(t)?.peerId||or(t)?.deviceId||null,doUrl:e.signalingDoUrl,apiKey:Sa()}});t.data.protocol=r,t.defersWsAdapter&&(r._onDead=()=>{Rr.debug(`[diag] _onDead fired peer=${(t.peerId||"").slice(0,12)} \u2014 rtc never returned in grace`),vi(`RTC session closed: ${or(t)?.deviceId?.slice(0,8)}...`);try{r.close()}catch{}Kd(r),t.disconnect()}),HZ(r),r.attachAsBus(t);try{await r.init()}catch(i){console.error("[transport] pm init failed:",i.message)}}function yxt(t){let e=or(t)?.deviceId||null;if(!e)return null;let n=t.peerId||or(t)?.peerId||e,r=t.data.conn;if(r&&!r.closed)return r;let i=KK.open({deviceId:e,peerId:n,apiKey:Sa()});return t.data.conn=i,i}function IF(){return YK}function tee(t){if(YK=t,!t){VL();return}WZ();for(let e of[...Os.keys()])qm(e),vi(`RTC test-disabled: killed session ${e?.slice(0,8)}`)}function JK(t,e){t.data.clientReady?e():t.once("device:clientReady",e)}function kPe(t){t.data.clientReady=!1,t.on("device:clientReady",()=>{t.data.clientReady=!0,IPe(t)})}function vxt(t){if(!t)return;if(!G_()){Jb(t,{type:"error",message:"remote-disabled"});return}if(YK){Jb(t,{type:"error",message:"rtc-disabled"});return}let e=t.split(":")[0],n=Os.get(t);if(n){if(!n.data.protocol?._closed&&!n.data.conn?.closed)return;vi(`Stale RTC session ${e.slice(0,8)} \u2014 rebuilding`),qm(t)}let r=_xt(t),i=VK(null,e);if(i.decision===$r.hold&&i.step==="auth")return r?void 0:(Rr.info(`rtc-offer: building session so the TAIL proof has a road device=${e.slice(0,8)}`),void WK(t,e));switch(i.decision){case $r.admit:return r?void 0:void WK(t,e);case $r.reject:DF(e,APe(t),"rtc"),Jb(t,{type:"error",message:$g.rejected}),Sw(t),tn(`Rejected device via RTC: ${e.slice(0,8)} \u2014 waiting in Clients list`),qn("deviceApproval",{action:"refresh"});return;default:QK(e,{socketId:APe(t),ip:"rtc",peerId:t,notify:()=>Jb(t,{type:"error",message:$g.pending})})}}function QK(t,{socketId:e,ip:n,peerId:r,notify:i}){if(i(),fee(t)){tn(`[auth] already pending, not asking twice: ${t?.slice(0,8)}`);return}MF(e,{deviceId:t,ip:n,...r?{peerId:r}:{}}),Rr.info(`asking host: device=${t?.slice(0,8)} via=${r?"rtc":"ws"}`),tn(`[auth] ASKING HOST: ${t?.slice(0,8)} via=${r?"rtc":"ws"} socketId=${e}`),tn(`Device needs approval: ${t?.slice(0,8)||"no-id"}`),qn("deviceApproval",{socketId:e,deviceId:t,ip:n,action:"pending"})}function _xt(t){for(let e of Ns?.sockets.sockets.values()||[])if(e.connected&&or(e)?.peerId===t)return!0;return!1}function Bm(t,e,...n){let r=t.data?.protocol;r&&!r._closed&&r.emitEverywhere(e,...n)||t.emit(e,...n)}function y1(t){let e=()=>{t.connected&&JK(t,()=>Bm(t,"device:approved"))};if(t.data.localUi)return e();let n=t.data.conn;if(n?.active)return e();if(n)return void n.on("state",function r(i){i.to===ti.closed&&n.off("state",r),i.to===ti.active&&(n.off("state",r),e())})}function PPe(t){return t.data.approved||t.data.unlocking?Promise.resolve():(t.data.unlocking=!0,y1(t),Zb(t).catch(n=>tn(`Feature setup failed: ${n.message}`)).finally(()=>{t.data.unlocking=!1}))}async function MPe(t){if(!t)return;let e=Yw(t);e&&uh(e);let n=[];for(let r of Ns?.sockets.sockets.values()||[])or(r)?.deviceId!==t||r.data.approved||n.push(PPe(r));for(let r of Os.values())or(r)?.deviceId!==t||r.data.approved||n.push(Zb(r).catch(i=>tn(`Connection resume failed: ${i.message}`)));await Promise.allSettled(n);for(let r of Q7(t))WK(r,t)}function H_(t,e,n){Rr.debug(`[diag] rejectDeviceTail device=${e?.slice(0,8)} reason=${n}`),t.data.tailReject=t.data.tailReject||{reason:n,penaltyMs:0};let r=t.data.tailReject.reason;Rr.warn(`tail rejected (${r}): device=${e?.slice(0,8)??"none"} carrier=${Qb(t).id}`),tn(`Device refused (${r}): ${e?.slice(0,8)}`),or(t)?.tempKey&&r===mi.mismatch&&(Rr.warn("one-time key burned (wrong TAIL) \u2014 clearing from UI"),dA()),h1(t,()=>{t.defersWsAdapter&&qm(t.peerId),OPe(e,r)})}function OPe(t,e){if(Rr.debug(`[diag] revokeDevice device=${t?.slice(0,8)} reason=${e}`),!!t){qK(t),uh(Yw(t)||""),KK.closeDevice(t,e);for(let n of Ns?.sockets.sockets.values()||[])or(n)?.deviceId===t&&(n.data.tailReject=n.data.tailReject||{reason:e,penaltyMs:0},h1(n));for(let[n,r]of Os)or(r)?.deviceId===t&&(r.data?.tailReject||qm(n))}}function NPe(t){let e=OF(t);if(e)return{key:t,...e};let n=XK(t)?.split(":")[0]||or(Ns?.sockets.sockets.get(t)||null)?.deviceId||null,r=n?Yw(n):null,i=r?OF(r):null;return i?{key:r,...i}:null}function qm(t){let e=t?Os.get(t):null;if(!e)return;let n=e.data?.protocol;Os.delete(t);try{e.disconnect()}catch{}if(n){try{n.close()}catch{}Kd(n)}}function WK(t,e){wxt(t,e).catch(n=>{qm(t),tn(`RTC session failed: ${n.message}`)})}async function wxt(t,e){if(Os.has(t))return;let n=new UT({deviceId:e,peerId:t,apiKey:Sa()});n.data.approved=!1,n.data.rtcSession=!0,n.data.conn=KK.open({deviceId:e,peerId:t,apiKey:Sa()}),kPe(n);let r;n.data.ready=new Promise(i=>{r=i}),Os.set(t,n),mA(n.id,"rtc",e,"rtc"),n.on("disconnect",()=>{Rr.debug(`[diag] HostBus disconnect peer=${(t||"").slice(0,12)} \u2192 untrack + conn.close`),Os.get(t)===n&&Os.delete(t),gA(n.id),n.data.conn?.close("carrier-gone"),r()}),vi(`RTC session: ${e.slice(0,8)}...`);try{await Zb(n)}finally{r()}setTimeout(()=>{Os.get(t)===n&&Kb(e)!==Uo.proven&&(tn(`Device never proved its TAIL: ${e.slice(0,8)} \u2014 dropping session`),H_(n,e,mi.timeout))},$K+1e3),y1(n)}function DPe(t){if(!Ns)return!1;let e=NPe(t);return e?Kb(e.deviceId)===Uo.rejected?(Rr.warn(`approve refused \u2014 TAIL was rejected: device=${e.deviceId.slice(0,8)}`),tn(`Cannot approve ${e.deviceId.slice(0,8)} \u2014 wrong access key`),uh(e.key),OPe(e.deviceId,mi.mismatch),qn("deviceApproval",{action:"refresh"}),!1):(_A(e.deviceId),dy(e.deviceId),tn(`Device approved: ${e.deviceId.slice(0,8)}...`),MPe(e.deviceId),qn("deviceApproval",{action:"refresh"}),!0):!1}function LPe(t){return!Ns||!t?!1:(_A(t),dy(t),tn(`Device approved from pending: ${t.slice(0,8)}...`),MPe(t),qn("deviceApproval",{action:"refresh"}),!0)}function v1(t){Rr.debug(`[diag] disconnectDeviceSockets device=${t?.slice(0,8)} \u2014 stack hint: ${new Error().stack.split(`
1179
1179
  `)[2]?.trim()?.slice(0,90)}`);let e=Ns;if(!e||!t)return 0;let n=0;for(let r of e.sockets.sockets.values())or(r)?.deviceId===t&&(r.disconnect(!0),n++);for(let r of iy())r._closed||r._deviceId?.split(":")[0]===t&&(sy(r),n++);for(let[r,i]of Os)if(r.split(":")[0]===t){try{i.data.protocol?.close()}catch{}Kd(i.data.protocol),Sw(r),i.disconnect(),n++}return n&&vi(`Disconnected ${n} socket(s) for device ${t.slice(0,8)}...`),n}function FPe(t){if(!Ns)return!1;let e=NPe(t),n=Ns.sockets.sockets.get(t);uh(e?.key||t),e?.deviceId&&mee(e.deviceId,{ip:e.ip,socketId:t}),n&&(Bm(n,"device:rejected"),n.disconnect(!0));let r=e?.peerId||XK(t);return r&&(Jb(r,{type:"error",message:$g.rejected}),Sw(r)),qn("deviceApproval",{action:"refresh"}),tn(`Device rejected: ${e?.deviceId?.slice(0,8)||"unknown"}...`),!0}function G_(){return sh().remoteEnabled!==!1}function UPe(t){let e=t.handshake?.address||"";return e==="127.0.0.1"||e==="::1"||e==="::ffff:127.0.0.1"}function zK(t){return t.handshake?.headers?.["cf-connecting-ip"]?!1:UPe(t)}function BPe(t){if(t){qg(sr(Sa())),VL();return}rL();for(let r of iy())if(!r._closed){try{r._offGlobalSig?.()}catch{}r._offGlobalSig=null}let e=Ns,n=new Set;if(e)for(let r of e.sockets.sockets.values()){if(r.data.localUi||zK(r)){r.data.protocol&&n.add(r.data.protocol);continue}r.disconnect(!0)}for(let r of iy())r._closed||n.has(r)||sy(r);for(let[r,i]of Os){try{i.data.protocol?.close()}catch{}Kd(i.data.protocol),Sw(r),i.disconnect()}}async function qPe(t){oee(),yee(),G_()&&qg(sr(Sa())),setInterval(()=>{if(!G_())return;let r=sr(Sa());r&&qg(r)},pxt),X7(vxt),NT(()=>ay());let e=new W7(t,{cors:{origin:"*",methods:["GET","POST"],credentials:!0,allowedHeaders:["*"]},allowRequest:(r,i)=>i(null,!0),transports:["websocket","polling"],allowEIO3:!0,allowUpgrades:!0,pingTimeout:3e4,pingInterval:12e3,maxHttpBufferSize:1e8,perMessageDeflate:{threshold:1024}}),n=await bne();return sF(n),e.on("connection",r=>{LT("client-connected");let i=r.handshake.headers["x-forwarded-for"]||r.handshake.address||"unknown",s=or(r)?.deviceId||null;kPe(r),r.data.approved=!1,r.use((d,p)=>{if(r.data.localUi)return p();let m=r.data.conn;return m?m.allows(d[0])?p():p(new Error("Device not approved")):Jg.has(d[0])?p():p(new Error("Device not approved"))});let o=UPe(r),a=!!r.handshake.headers["cf-connecting-ip"],c=r.handshake.headers.origin,l=!c||$f.includes(c);if(!a&&o&&l&&iQ(r.handshake.auth?.localToken)){r.data.approved=!0,r.data.localUi=!0,vi("Local UI connected \u2014 trusted (token)"),Zb(r).catch(d=>tn(`Feature setup failed: ${d.message}`));return}if(s===qf){tn(`Rejected untrusted local-ui socket from ${i}`),r.disconnect(!0);return}if(!G_()&&!zK(r)){vi(`Rejected ${s?.slice(0,8)||"unknown"} from ${i} \u2014 remote access is off`),r.disconnect(!0);return}if(!a&&o&&l&&s&&!vA(s)){let d=Xb(or(r),Ow);d&&$_(d)&&Kw(s)===ds.unknown&&(cee(s),Rr.info(`loopback workspace device admitted for this session (key TAIL verified): ${s.slice(0,8)}`),vi(`Loopback workspace admitted (session): ${s.slice(0,8)} (key TAIL verified)`))}zK(r)?vi(`Local connection not tracked: ${i} (device: ${s?.slice(0,8)||"none"})`):(mA(r.id,i,s),vi(`Client connected: ${i} (device: ${s?.slice(0,8)||"none"})`)),r.on("disconnect",d=>{gA(r.id),uh(r.id);let p=r.data?.conn;p&&(p.detach("ws"),!p.connected&&!r.data?.rtcHost&&p.close("carrier-gone"));let m=r.data?.protocol;vi(`Client disconnected: ${i} (${d}) pm=${m?._deviceId?.slice(0,12)||"none"} remoteAttached=${!!r.data?.remoteAttached}`),m&&!r.data?.remoteAttached&&sy(m)});let u=()=>{if(!r.connected)return;let d=r.handshake.auth?.peerId||null,p=()=>{if(r.data.approved)return;let v=Yw(s);if(v&&!XK(v)){vi(`Device ${s?.slice(0,8)} already pending, ignoring duplicate`),r.disconnect(!0);return}let E=!!v;v&&uh(v),JK(r,()=>{if(!(r.data.approved||!r.connected)){if(E){MF(r.id,{deviceId:s,ip:i}),Bm(r,"device:pendingApproval");return}QK(s,{socketId:r.id,ip:i,notify:()=>Bm(r,"device:pendingApproval")})}})},m=v=>{let E=v.data.conn;r.data.conn=E,r.data.approved=!!E?.active,r.data.rtcHost=v,Promise.resolve(v.data.ready).then(()=>v.data.protocol?.attachSocket(r)).then(()=>E?.attach("ws",v.data.protocol?._adapters?.get("ws")||null)).then(()=>{E?.active&&r.emit("terminal:ready")}).catch(A=>tn(`RTC session attachSocket failed: ${A.message}`)),vi(`Tunnel attached to RTC session: ${s.slice(0,8)}...`),y1(r)},h=d?Os.get(d):null;if(h?.data.conn?.closed&&(Rr.warn(`route: stale RTC session (conn closed) peer=${d.slice(0,12)} \u2192 rebuild`),qm(d),h=null),!h&&d&&!r.data._rtcWaited&&eQ(d)){r.data._rtcWaited=!0,vi(`WS first, RTC offer pending \u2192 grace 500ms (device ${s.slice(0,8)})`),setTimeout(u,500);return}let y=VK(r,s);if(y.decision===$r.hold&&y.step==="auth"){if(!s){Rr.warn(`route: socket with no device id (${i}) \u2014 disconnecting`),r.disconnect(!0);return}Rr.info(`route: awaiting TAIL proof device=${s?.slice(0,8)||"no-id"}`),f1(s,()=>u(),()=>{H_(r,s,mi.timeout)});return}switch(y.decision){case $r.admit:if(h)return void m(h);vi(`Device admitted: ${s?.slice(0,8)}...`),PPe(r);return;case $r.reject:{if(r.data?.tailReject)return void H_(r,s);DF(s,r.id,i),tn(`Rejected device reconnected: ${s.slice(0,8)} \u2014 waiting in Clients list`),Bm(r,"device:rejected"),qn("deviceApproval",{action:"refresh"});return}default:Rr.info(`route: hold for approval device=${s?.slice(0,8)||"no-id"}`),tn(`Device needs approval: ${s?.slice(0,8)||"no-id"}`),p()}};u()}),Np(e,Sa()),Ns=e,e}var CPe,RPe,Rr,pxt,Ns,Os,KK,YK,APe,XK,Jb,jo=ne(()=>{z7();CPe=require("fs"),RPe=require("path");Tw();tQ();qt();BT();_ee();zi();yi();Gr();hu();aa();jA();BEe();$Ee();Tbe();Pbe();ySe();Hke();HR();iPe();ys();Xw();jK();Nw();zi();Um();$e();bPe();TPe();Qg();Rr=Ee("transport");pxt=5e3,Ns=null;Os=new Map,KK=new g1;YK=!1;APe=t=>`rtc-${t}`,XK=t=>t.startsWith("rtc-")?t.slice(4):null,Jb=(t,e)=>DT({...e,to:t});zZ(qm)});var zPe=H((tS,ZK)=>{(function(t,e){typeof tS=="object"&&typeof ZK=="object"?ZK.exports=e(require("child_process"),require("crypto")):typeof define=="function"&&define.amd?define(["child_process","crypto"],e):typeof tS=="object"?tS["electron-machine-id"]=e(require("child_process"),require("crypto")):t["electron-machine-id"]=e(t.child_process,t.crypto)})(tS,function(t,e){return(function(n){function r(s){if(i[s])return i[s].exports;var o=i[s]={exports:{},id:s,loaded:!1};return n[s].call(o.exports,o,o.exports,r),o.loaded=!0,o.exports}var i={};return r.m=n,r.c=i,r.p="",r(0)})([function(n,r,i){n.exports=i(34)},function(n,r,i){var s=i(29)("wks"),o=i(33),a=i(2).Symbol,c=typeof a=="function",l=n.exports=function(u){return s[u]||(s[u]=c&&a[u]||(c?a:o)("Symbol."+u))};l.store=s},function(n,r){var i=n.exports=typeof window<"u"&&window.Math==Math?window:typeof self<"u"&&self.Math==Math?self:Function("return this")();typeof __g=="number"&&(__g=i)},function(n,r,i){var s=i(9);n.exports=function(o){if(!s(o))throw TypeError(o+" is not an object!");return o}},function(n,r,i){n.exports=!i(24)(function(){return Object.defineProperty({},"a",{get:function(){return 7}}).a!=7})},function(n,r,i){var s=i(12),o=i(17);n.exports=i(4)?function(a,c,l){return s.f(a,c,o(1,l))}:function(a,c,l){return a[c]=l,a}},function(n,r){var i=n.exports={version:"2.4.0"};typeof __e=="number"&&(__e=i)},function(n,r,i){var s=i(14);n.exports=function(o,a,c){if(s(o),a===void 0)return o;switch(c){case 1:return function(l){return o.call(a,l)};case 2:return function(l,u){return o.call(a,l,u)};case 3:return function(l,u,d){return o.call(a,l,u,d)}}return function(){return o.apply(a,arguments)}}},function(n,r){var i={}.hasOwnProperty;n.exports=function(s,o){return i.call(s,o)}},function(n,r){n.exports=function(i){return typeof i=="object"?i!==null:typeof i=="function"}},function(n,r){n.exports={}},function(n,r){var i={}.toString;n.exports=function(s){return i.call(s).slice(8,-1)}},function(n,r,i){var s=i(3),o=i(26),a=i(32),c=Object.defineProperty;r.f=i(4)?Object.defineProperty:function(l,u,d){if(s(l),u=a(u,!0),s(d),o)try{return c(l,u,d)}catch{}if("get"in d||"set"in d)throw TypeError("Accessors not supported!");return"value"in d&&(l[u]=d.value),l}},function(n,r,i){var s=i(42),o=i(15);n.exports=function(a){return s(o(a))}},function(n,r){n.exports=function(i){if(typeof i!="function")throw TypeError(i+" is not a function!");return i}},function(n,r){n.exports=function(i){if(i==null)throw TypeError("Can't call method on "+i);return i}},function(n,r,i){var s=i(9),o=i(2).document,a=s(o)&&s(o.createElement);n.exports=function(c){return a?o.createElement(c):{}}},function(n,r){n.exports=function(i,s){return{enumerable:!(1&i),configurable:!(2&i),writable:!(4&i),value:s}}},function(n,r,i){var s=i(12).f,o=i(8),a=i(1)("toStringTag");n.exports=function(c,l,u){c&&!o(c=u?c:c.prototype,a)&&s(c,a,{configurable:!0,value:l})}},function(n,r,i){var s=i(29)("keys"),o=i(33);n.exports=function(a){return s[a]||(s[a]=o(a))}},function(n,r){var i=Math.ceil,s=Math.floor;n.exports=function(o){return isNaN(o=+o)?0:(o>0?s:i)(o)}},function(n,r,i){var s=i(11),o=i(1)("toStringTag"),a=s((function(){return arguments})())=="Arguments",c=function(l,u){try{return l[u]}catch{}};n.exports=function(l){var u,d,p;return l===void 0?"Undefined":l===null?"Null":typeof(d=c(u=Object(l),o))=="string"?d:a?s(u):(p=s(u))=="Object"&&typeof u.callee=="function"?"Arguments":p}},function(n,r){n.exports="constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf".split(",")},function(n,r,i){var s=i(2),o=i(6),a=i(7),c=i(5),l="prototype",u=function(d,p,m){var h,y,v,E=d&u.F,A=d&u.G,b=d&u.S,S=d&u.P,I=d&u.B,F=d&u.W,D=A?o:o[p]||(o[p]={}),B=D[l],M=A?s:b?s[p]:(s[p]||{})[l];A&&(m=p);for(h in m)y=!E&&M&&M[h]!==void 0,y&&h in D||(v=y?M[h]:m[h],D[h]=A&&typeof M[h]!="function"?m[h]:I&&y?a(v,s):F&&M[h]==v?(function(P){var x=function(R,N,k){if(this instanceof P){switch(arguments.length){case 0:return new P;case 1:return new P(R);case 2:return new P(R,N)}return new P(R,N,k)}return P.apply(this,arguments)};return x[l]=P[l],x})(v):S&&typeof v=="function"?a(Function.call,v):v,S&&((D.virtual||(D.virtual={}))[h]=v,d&u.R&&B&&!B[h]&&c(B,h,v)))};u.F=1,u.G=2,u.S=4,u.P=8,u.B=16,u.W=32,u.U=64,u.R=128,n.exports=u},function(n,r){n.exports=function(i){try{return!!i()}catch{return!0}}},function(n,r,i){n.exports=i(2).document&&document.documentElement},function(n,r,i){n.exports=!i(4)&&!i(24)(function(){return Object.defineProperty(i(16)("div"),"a",{get:function(){return 7}}).a!=7})},function(n,r,i){"use strict";var s=i(28),o=i(23),a=i(57),c=i(5),l=i(8),u=i(10),d=i(45),p=i(18),m=i(52),h=i(1)("iterator"),y=!([].keys&&"next"in[].keys()),v="@@iterator",E="keys",A="values",b=function(){return this};n.exports=function(S,I,F,D,B,M,P){d(F,I,D);var x,R,N,k=function(J){if(!y&&J in L)return L[J];switch(J){case E:return function(){return new F(this,J)};case A:return function(){return new F(this,J)}}return function(){return new F(this,J)}},O=I+" Iterator",$=B==A,Y=!1,L=S.prototype,C=L[h]||L[v]||B&&L[B],G=C||k(B),le=B?$?k("entries"):G:void 0,ce=I=="Array"&&L.entries||C;if(ce&&(N=m(ce.call(new S)),N!==Object.prototype&&(p(N,O,!0),s||l(N,h)||c(N,h,b))),$&&C&&C.name!==A&&(Y=!0,G=function(){return C.call(this)}),s&&!P||!y&&!Y&&L[h]||c(L,h,G),u[I]=G,u[O]=b,B)if(x={values:$?G:k(A),keys:M?G:k(E),entries:le},P)for(R in x)R in L||a(L,R,x[R]);else o(o.P+o.F*(y||Y),I,x);return x}},function(n,r){n.exports=!0},function(n,r,i){var s=i(2),o="__core-js_shared__",a=s[o]||(s[o]={});n.exports=function(c){return a[c]||(a[c]={})}},function(n,r,i){var s,o,a,c=i(7),l=i(41),u=i(25),d=i(16),p=i(2),m=p.process,h=p.setImmediate,y=p.clearImmediate,v=p.MessageChannel,E=0,A={},b="onreadystatechange",S=function(){var F=+this;if(A.hasOwnProperty(F)){var D=A[F];delete A[F],D()}},I=function(F){S.call(F.data)};h&&y||(h=function(F){for(var D=[],B=1;arguments.length>B;)D.push(arguments[B++]);return A[++E]=function(){l(typeof F=="function"?F:Function(F),D)},s(E),E},y=function(F){delete A[F]},i(11)(m)=="process"?s=function(F){m.nextTick(c(S,F,1))}:v?(o=new v,a=o.port2,o.port1.onmessage=I,s=c(a.postMessage,a,1)):p.addEventListener&&typeof postMessage=="function"&&!p.importScripts?(s=function(F){p.postMessage(F+"","*")},p.addEventListener("message",I,!1)):s=b in d("script")?function(F){u.appendChild(d("script"))[b]=function(){u.removeChild(this),S.call(F)}}:function(F){setTimeout(c(S,F,1),0)}),n.exports={set:h,clear:y}},function(n,r,i){var s=i(20),o=Math.min;n.exports=function(a){return a>0?o(s(a),9007199254740991):0}},function(n,r,i){var s=i(9);n.exports=function(o,a){if(!s(o))return o;var c,l;if(a&&typeof(c=o.toString)=="function"&&!s(l=c.call(o))||typeof(c=o.valueOf)=="function"&&!s(l=c.call(o))||!a&&typeof(c=o.toString)=="function"&&!s(l=c.call(o)))return l;throw TypeError("Can't convert object to primitive value")}},function(n,r){var i=0,s=Math.random();n.exports=function(o){return"Symbol(".concat(o===void 0?"":o,")_",(++i+s).toString(36))}},function(n,r,i){"use strict";function s(b){return b&&b.__esModule?b:{default:b}}function o(){return process.platform!=="win32"?"":process.arch==="ia32"&&process.env.hasOwnProperty("PROCESSOR_ARCHITEW6432")?"mixed":"native"}function a(b){return(0,h.createHash)("sha256").update(b).digest("hex")}function c(b){switch(v){case"darwin":return b.split("IOPlatformUUID")[1].split(`
1180
- `)[0].replace(/\=|\s+|\"/gi,"").toLowerCase();case"win32":return b.toString().split("REG_SZ")[1].replace(/\r+|\n+|\s+/gi,"").toLowerCase();case"linux":return b.toString().replace(/\r+|\n+|\s+/gi,"").toLowerCase();case"freebsd":return b.toString().replace(/\r+|\n+|\s+/gi,"").toLowerCase();default:throw new Error("Unsupported platform: "+process.platform)}}function l(b){var S=c((0,m.execSync)(A[v]).toString());return b?S:a(S)}function u(b){return new p.default(function(S,I){return(0,m.exec)(A[v],{},function(F,D,B){if(F)return I(new Error("Error while obtaining machine id: "+F.stack));var M=c(D.toString());return S(b?M:a(M))})})}Object.defineProperty(r,"__esModule",{value:!0});var d=i(35),p=s(d);r.machineIdSync=l,r.machineId=u;var m=i(70),h=i(71),y=process,v=y.platform,E={native:"%windir%\\System32",mixed:"%windir%\\sysnative\\cmd.exe /c %windir%\\System32"},A={darwin:"ioreg -rd1 -c IOPlatformExpertDevice",win32:E[o()]+"\\REG.exe QUERY HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Cryptography /v MachineGuid",linux:"( cat /var/lib/dbus/machine-id /etc/machine-id 2> /dev/null || hostname ) | head -n 1 || :",freebsd:"kenv -q smbios.system.uuid || sysctl -n kern.hostuuid"}},function(n,r,i){n.exports={default:i(36),__esModule:!0}},function(n,r,i){i(66),i(68),i(69),i(67),n.exports=i(6).Promise},function(n,r){n.exports=function(){}},function(n,r){n.exports=function(i,s,o,a){if(!(i instanceof s)||a!==void 0&&a in i)throw TypeError(o+": incorrect invocation!");return i}},function(n,r,i){var s=i(13),o=i(31),a=i(62);n.exports=function(c){return function(l,u,d){var p,m=s(l),h=o(m.length),y=a(d,h);if(c&&u!=u){for(;h>y;)if(p=m[y++],p!=p)return!0}else for(;h>y;y++)if((c||y in m)&&m[y]===u)return c||y||0;return!c&&-1}}},function(n,m,i){var s=i(7),o=i(44),a=i(43),c=i(3),l=i(31),u=i(64),d={},p={},m=n.exports=function(h,y,v,E,A){var b,S,I,F,D=A?function(){return h}:u(h),B=s(v,E,y?2:1),M=0;if(typeof D!="function")throw TypeError(h+" is not iterable!");if(a(D)){for(b=l(h.length);b>M;M++)if(F=y?B(c(S=h[M])[0],S[1]):B(h[M]),F===d||F===p)return F}else for(I=D.call(h);!(S=I.next()).done;)if(F=o(I,B,S.value,y),F===d||F===p)return F};m.BREAK=d,m.RETURN=p},function(n,r){n.exports=function(i,s,o){var a=o===void 0;switch(s.length){case 0:return a?i():i.call(o);case 1:return a?i(s[0]):i.call(o,s[0]);case 2:return a?i(s[0],s[1]):i.call(o,s[0],s[1]);case 3:return a?i(s[0],s[1],s[2]):i.call(o,s[0],s[1],s[2]);case 4:return a?i(s[0],s[1],s[2],s[3]):i.call(o,s[0],s[1],s[2],s[3])}return i.apply(o,s)}},function(n,r,i){var s=i(11);n.exports=Object("z").propertyIsEnumerable(0)?Object:function(o){return s(o)=="String"?o.split(""):Object(o)}},function(n,r,i){var s=i(10),o=i(1)("iterator"),a=Array.prototype;n.exports=function(c){return c!==void 0&&(s.Array===c||a[o]===c)}},function(n,r,i){var s=i(3);n.exports=function(o,a,c,l){try{return l?a(s(c)[0],c[1]):a(c)}catch(d){var u=o.return;throw u!==void 0&&s(u.call(o)),d}}},function(n,r,i){"use strict";var s=i(49),o=i(17),a=i(18),c={};i(5)(c,i(1)("iterator"),function(){return this}),n.exports=function(l,u,d){l.prototype=s(c,{next:o(1,d)}),a(l,u+" Iterator")}},function(n,r,i){var s=i(1)("iterator"),o=!1;try{var a=[7][s]();a.return=function(){o=!0},Array.from(a,function(){throw 2})}catch{}n.exports=function(c,l){if(!l&&!o)return!1;var u=!1;try{var d=[7],p=d[s]();p.next=function(){return{done:u=!0}},d[s]=function(){return p},c(d)}catch{}return u}},function(n,r){n.exports=function(i,s){return{value:s,done:!!i}}},function(n,r,i){var s=i(2),o=i(30).set,a=s.MutationObserver||s.WebKitMutationObserver,c=s.process,l=s.Promise,u=i(11)(c)=="process";n.exports=function(){var d,p,m,h=function(){var A,b;for(u&&(A=c.domain)&&A.exit();d;){b=d.fn,d=d.next;try{b()}catch(S){throw d?m():p=void 0,S}}p=void 0,A&&A.enter()};if(u)m=function(){c.nextTick(h)};else if(a){var y=!0,v=document.createTextNode("");new a(h).observe(v,{characterData:!0}),m=function(){v.data=y=!y}}else if(l&&l.resolve){var E=l.resolve();m=function(){E.then(h)}}else m=function(){o.call(s,h)};return function(A){var b={fn:A,next:void 0};p&&(p.next=b),d||(d=b,m()),p=b}}},function(n,r,i){var s=i(3),o=i(50),a=i(22),c=i(19)("IE_PROTO"),l=function(){},u="prototype",d=function(){var p,m=i(16)("iframe"),h=a.length,y=">";for(m.style.display="none",i(25).appendChild(m),m.src="javascript:",p=m.contentWindow.document,p.open(),p.write("<script>document.F=Object</script"+y),p.close(),d=p.F;h--;)delete d[u][a[h]];return d()};n.exports=Object.create||function(p,m){var h;return p!==null?(l[u]=s(p),h=new l,l[u]=null,h[c]=p):h=d(),m===void 0?h:o(h,m)}},function(n,r,i){var s=i(12),o=i(3),a=i(54);n.exports=i(4)?Object.defineProperties:function(c,l){o(c);for(var u,d=a(l),p=d.length,m=0;p>m;)s.f(c,u=d[m++],l[u]);return c}},function(n,r,i){var s=i(55),o=i(17),a=i(13),c=i(32),l=i(8),u=i(26),d=Object.getOwnPropertyDescriptor;r.f=i(4)?d:function(p,m){if(p=a(p),m=c(m,!0),u)try{return d(p,m)}catch{}if(l(p,m))return o(!s.f.call(p,m),p[m])}},function(n,r,i){var s=i(8),o=i(63),a=i(19)("IE_PROTO"),c=Object.prototype;n.exports=Object.getPrototypeOf||function(l){return l=o(l),s(l,a)?l[a]:typeof l.constructor=="function"&&l instanceof l.constructor?l.constructor.prototype:l instanceof Object?c:null}},function(n,r,i){var s=i(8),o=i(13),a=i(39)(!1),c=i(19)("IE_PROTO");n.exports=function(l,u){var d,p=o(l),m=0,h=[];for(d in p)d!=c&&s(p,d)&&h.push(d);for(;u.length>m;)s(p,d=u[m++])&&(~a(h,d)||h.push(d));return h}},function(n,r,i){var s=i(53),o=i(22);n.exports=Object.keys||function(a){return s(a,o)}},function(n,r){r.f={}.propertyIsEnumerable},function(n,r,i){var s=i(5);n.exports=function(o,a,c){for(var l in a)c&&o[l]?o[l]=a[l]:s(o,l,a[l]);return o}},function(n,r,i){n.exports=i(5)},function(n,r,i){var s=i(9),o=i(3),a=function(c,l){if(o(c),!s(l)&&l!==null)throw TypeError(l+": can't set as prototype!")};n.exports={set:Object.setPrototypeOf||("__proto__"in{}?(function(c,l,u){try{u=i(7)(Function.call,i(51).f(Object.prototype,"__proto__").set,2),u(c,[]),l=!(c instanceof Array)}catch{l=!0}return function(d,p){return a(d,p),l?d.__proto__=p:u(d,p),d}})({},!1):void 0),check:a}},function(n,r,i){"use strict";var s=i(2),o=i(6),a=i(12),c=i(4),l=i(1)("species");n.exports=function(u){var d=typeof o[u]=="function"?o[u]:s[u];c&&d&&!d[l]&&a.f(d,l,{configurable:!0,get:function(){return this}})}},function(n,r,i){var s=i(3),o=i(14),a=i(1)("species");n.exports=function(c,l){var u,d=s(c).constructor;return d===void 0||(u=s(d)[a])==null?l:o(u)}},function(n,r,i){var s=i(20),o=i(15);n.exports=function(a){return function(c,l){var u,d,p=String(o(c)),m=s(l),h=p.length;return m<0||m>=h?a?"":void 0:(u=p.charCodeAt(m),u<55296||u>56319||m+1===h||(d=p.charCodeAt(m+1))<56320||d>57343?a?p.charAt(m):u:a?p.slice(m,m+2):(u-55296<<10)+(d-56320)+65536)}}},function(n,r,i){var s=i(20),o=Math.max,a=Math.min;n.exports=function(c,l){return c=s(c),c<0?o(c+l,0):a(c,l)}},function(n,r,i){var s=i(15);n.exports=function(o){return Object(s(o))}},function(n,r,i){var s=i(21),o=i(1)("iterator"),a=i(10);n.exports=i(6).getIteratorMethod=function(c){if(c!=null)return c[o]||c["@@iterator"]||a[s(c)]}},function(n,r,i){"use strict";var s=i(37),o=i(47),a=i(10),c=i(13);n.exports=i(27)(Array,"Array",function(l,u){this._t=c(l),this._i=0,this._k=u},function(){var l=this._t,u=this._k,d=this._i++;return!l||d>=l.length?(this._t=void 0,o(1)):u=="keys"?o(0,d):u=="values"?o(0,l[d]):o(0,[d,l[d]])},"values"),a.Arguments=a.Array,s("keys"),s("values"),s("entries")},function(n,r){},function(n,r,i){"use strict";var s,o,a,c=i(28),l=i(2),u=i(7),d=i(21),p=i(23),m=i(9),h=(i(3),i(14)),y=i(38),v=i(40),E=(i(58).set,i(60)),A=i(30).set,b=i(48)(),S="Promise",I=l.TypeError,D=l.process,F=l[S],D=l.process,B=d(D)=="process",M=function(){},P=!!(function(){try{var ce=F.resolve(1),J=(ce.constructor={})[i(1)("species")]=function(fe){fe(M,M)};return(B||typeof PromiseRejectionEvent=="function")&&ce.then(M)instanceof J}catch{}})(),x=function(ce,J){return ce===J||ce===F&&J===a},R=function(ce){var J;return!(!m(ce)||typeof(J=ce.then)!="function")&&J},N=function(ce){return x(F,ce)?new k(ce):new o(ce)},k=o=function(ce){var J,fe;this.promise=new ce(function(we,xe){if(J!==void 0||fe!==void 0)throw I("Bad Promise constructor");J=we,fe=xe}),this.resolve=h(J),this.reject=h(fe)},O=function(ce){try{ce()}catch(J){return{error:J}}},$=function(ce,J){if(!ce._n){ce._n=!0;var fe=ce._c;b(function(){for(var we=ce._v,xe=ce._s==1,Ue=0,ke=function(q){var V,W,Z=xe?q.ok:q.fail,ee=q.resolve,te=q.reject,oe=q.domain;try{Z?(xe||(ce._h==2&&C(ce),ce._h=1),Z===!0?V=we:(oe&&oe.enter(),V=Z(we),oe&&oe.exit()),V===q.promise?te(I("Promise-chain cycle")):(W=R(V))?W.call(V,ee,te):ee(V)):te(we)}catch(ie){te(ie)}};fe.length>Ue;)ke(fe[Ue++]);ce._c=[],ce._n=!1,J&&!ce._h&&Y(ce)})}},Y=function(ce){A.call(l,function(){var J,fe,we,xe=ce._v;if(L(ce)&&(J=O(function(){B?D.emit("unhandledRejection",xe,ce):(fe=l.onunhandledrejection)?fe({promise:ce,reason:xe}):(we=l.console)&&we.error&&we.error("Unhandled promise rejection",xe)}),ce._h=B||L(ce)?2:1),ce._a=void 0,J)throw J.error})},L=function(ce){if(ce._h==1)return!1;for(var J,fe=ce._a||ce._c,we=0;fe.length>we;)if(J=fe[we++],J.fail||!L(J.promise))return!1;return!0},C=function(ce){A.call(l,function(){var J;B?D.emit("rejectionHandled",ce):(J=l.onrejectionhandled)&&J({promise:ce,reason:ce._v})})},G=function(ce){var J=this;J._d||(J._d=!0,J=J._w||J,J._v=ce,J._s=2,J._a||(J._a=J._c.slice()),$(J,!0))},le=function(ce){var J,fe=this;if(!fe._d){fe._d=!0,fe=fe._w||fe;try{if(fe===ce)throw I("Promise can't be resolved itself");(J=R(ce))?b(function(){var we={_w:fe,_d:!1};try{J.call(ce,u(le,we,1),u(G,we,1))}catch(xe){G.call(we,xe)}}):(fe._v=ce,fe._s=1,$(fe,!1))}catch(we){G.call({_w:fe,_d:!1},we)}}};P||(F=function(ce){y(this,F,S,"_h"),h(ce),s.call(this);try{ce(u(le,this,1),u(G,this,1))}catch(J){G.call(this,J)}},s=function(ce){this._c=[],this._a=void 0,this._s=0,this._d=!1,this._v=void 0,this._h=0,this._n=!1},s.prototype=i(56)(F.prototype,{then:function(ce,J){var fe=N(E(this,F));return fe.ok=typeof ce!="function"||ce,fe.fail=typeof J=="function"&&J,fe.domain=B?D.domain:void 0,this._c.push(fe),this._a&&this._a.push(fe),this._s&&$(this,!1),fe.promise},catch:function(ce){return this.then(void 0,ce)}}),k=function(){var ce=new s;this.promise=ce,this.resolve=u(le,ce,1),this.reject=u(G,ce,1)}),p(p.G+p.W+p.F*!P,{Promise:F}),i(18)(F,S),i(59)(S),a=i(6)[S],p(p.S+p.F*!P,S,{reject:function(ce){var J=N(this),fe=J.reject;return fe(ce),J.promise}}),p(p.S+p.F*(c||!P),S,{resolve:function(ce){if(ce instanceof F&&x(ce.constructor,this))return ce;var J=N(this),fe=J.resolve;return fe(ce),J.promise}}),p(p.S+p.F*!(P&&i(46)(function(ce){F.all(ce).catch(M)})),S,{all:function(ce){var J=this,fe=N(J),we=fe.resolve,xe=fe.reject,Ue=O(function(){var ke=[],q=0,V=1;v(ce,!1,function(W){var Z=q++,ee=!1;ke.push(void 0),V++,J.resolve(W).then(function(te){ee||(ee=!0,ke[Z]=te,--V||we(ke))},xe)}),--V||we(ke)});return Ue&&xe(Ue.error),fe.promise},race:function(ce){var J=this,fe=N(J),we=fe.reject,xe=O(function(){v(ce,!1,function(Ue){J.resolve(Ue).then(fe.resolve,we)})});return xe&&we(xe.error),fe.promise}})},function(n,r,i){"use strict";var s=i(61)(!0);i(27)(String,"String",function(o){this._t=String(o),this._i=0},function(){var o,a=this._t,c=this._i;return c>=a.length?{value:void 0,done:!0}:(o=s(a,c),this._i+=o.length,{value:o,done:!1})})},function(n,r,i){i(65);for(var s=i(2),o=i(5),a=i(10),c=i(1)("toStringTag"),l=["NodeList","DOMTokenList","MediaList","StyleSheetList","CSSRuleList"],u=0;u<5;u++){var d=l[u],p=s[d],m=p&&p.prototype;m&&!m[c]&&o(m,c,d),a[d]=a.Array}},function(n,r){n.exports=require("child_process")},function(n,r){n.exports=require("crypto")}])})});var Vxt={};fr(Vxt,{startServer:()=>XMe});module.exports=WOe(Vxt);for(let t of[process.stdout,process.stderr])t?.on?.("error",e=>{if(e?.code!=="EPIPE")throw e});var E1=require("http"),$m=require("child_process"),is=require("fs"),pn=require("path"),KMe=require("url");qr();qt();$e();jo();aa();Um();BT();var eS=require("fs"),HPe=require("url");var _1=Q(require("path"),1),jPe=Q(require("os"),1);qt();var $Pe=Q(require("path"),1),GPe=Q(require("os"),1);var W$t=$Pe.default.join(GPe.default.homedir(),".9remote","pids");WL();eh();$e();var tGt=Ee("update"),nGt=_1.default.dirname((0,HPe.fileURLToPath)(__importMetaUrl)),rGt=(0,eS.existsSync)("/.dockerenv");var iGt=_1.default.join(jPe.default.homedir(),".9remote","cloudflared.pid");function WPe(t,e){let n=t.split(".").map(Number),r=e.split(".").map(Number);for(let i=0;i<3;i++){if(r[i]>n[i])return!0;if(r[i]<n[i])return!1}return!1}var sGt=_1.default.join(Pe.STATE,Ew.lockFile);HR();wR();gx();ys();aa();eh();qr();hu();Um();var VPe=Q(zPe(),1),e5=Q(require("crypto"),1),{machineIdSync:xxt}=VPe.default;async function KPe(t=null){let e=t||process.env.MACHINE_ID_SALT||"9remote-salt";try{let n=xxt();return e5.default.createHash("sha256").update(n+e).digest("hex").substring(0,16)}catch(n){return console.error("Error getting machine ID:",n),e5.default.randomUUID().replace(/-/g,"").substring(0,16)}}ys();qt();$e();Nw();Um();NK();var t5=Ee("session"),Ext=10;async function YPe(t,e){let n=async()=>{let r=await Rc(`${e}/api/temp-key/create`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify((()=>{let i={apiKey:sr(t),expiryMinutes:Ext};return{...i,...YT(i)}})())});if(!r.ok){let i=await r.json().catch(()=>null);throw new Error(i?.error||`HTTP ${r.status}`)}return r.json()};try{let r;try{r=await n()}catch(s){if(t5.warn(`Temp key creation failed (${s.message}) \u2014 re-registering session`),!await n5(t,e))throw s;r=await n()}let i=cPe();return uPe(r.tempKey,i,r.expiresAt,e),{...r,oneTimeKey:`${r.tempKey}${i}`}}catch(r){return t5.error(`Temp key creation failed: ${r?.message||r}`),null}}function XPe(t,e){return e?.tempKey?`${t}/login?k=${e.tempKey}#${e.oneTimeKey}`:`${t}/login`}async function n5(t,e,n,r){try{let i=await Rc(`${e}/api/session/create`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:sr(t),hostPublicKey:VT(),hostX25519Key:KT(),tempKey:Vb()?.tempKey||void 0})});if(!i.ok)throw new Error(`HTTP ${i.status}`);return n&&await Rc(`${e}/api/session/update`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:sr(t),tunnelUrl:n,...YT({apiKey:sr(t),tunnelUrl:n})})}).catch(()=>{}),r&&sr(r)!==sr(t)&&await Rc(`${e}/api/session/delete`,{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:sr(r),...YT({apiKey:sr(r)})})}).catch(()=>{}),!0}catch(i){return t5.error(`Session registration failed: ${i?.message||i}`),!1}}Tw();Um();eh();function r5(t){return sh().remoteEnabled!==!1?!1:(ut(t,409,"Remote access is off"),!0)}async function JPe(t,e){if(r5(e))return;let n=lA(),r=n.workerUrl||Nc;if(!n.permanentKey){ut(e,400,"No permanent key set");return}let i=await YPe(n.permanentKey,r);if(!i){ut(e,500,"Temp key creation failed");return}let s=XPe(r,i);Ho({oneTimeKey:i.oneTimeKey,oneTimeKeyExpiresAt:i.expiresAt,qrUrl:s}),De(e,{oneTimeKey:i.oneTimeKey,expiresAt:i.expiresAt,qrUrl:s})}async function QPe(t,e){r5(e)||(LT("session-registered"),De(e,FT()))}async function ZPe(t,e){if(!r5(e))try{let n=lA(),r=n.workerUrl||Nc,i=await KPe(),s=hPe(i),o=Go();if(!await n5(s,r,n.tunnelUrl,o?.key)){ut(e,502,"Could not register the new key with the server");return}IZ(i,s,o?.name||"Default"),qg(sr(s)),Ho({permanentKey:s,oneTimeKey:"",oneTimeKeyExpiresAt:null,qrUrl:"",pairingUsed:!0}),De(e,{ok:!0,permanentKey:s})}catch(n){ut(e,500,n.message)}}qr();jo();Xw();async function eMe(t,e){let n=await kr(t,e);if(!n)return;let r=DPe(n.socketId);De(e,{ok:r})}async function tMe(t,e){let n=await kr(t,e);if(!n)return;let r=FPe(n.socketId);De(e,{ok:r})}function nMe(t,e){De(e,{pending:hee()})}function rMe(t,e){De(e,{devices:pee()})}function iMe(t,e){De(e,{rejected:gee()})}async function sMe(t,e){let n=await kr(t,e);if(!n)return;let r=LPe(n.deviceId);De(e,{ok:r})}async function oMe(t,e){let n=await kr(t,e);n&&(v1(n.deviceId),dy(n.deviceId),De(e))}async function aMe(t,e){let n=await kr(t,e);n&&(v1(n.deviceId),lee(n.deviceId),De(e))}async function cMe(t,e){let n=await kr(t,e);if(!n)return;aee(n.deviceId);let r=v1(n.deviceId);De(e,{disconnected:r})}function lMe(t,e){De(e,{enabled:LF()})}async function uMe(t,e){let n=await kr(t,e);if(!n)return;let r=uee(n.deviceId,n.label);De(e,{ok:r})}async function dMe(t,e){let n=await kr(t,e);if(!n)return;let r=vee(!!n.enabled);De(e,{enabled:r})}qr();jo();yi();LI();xs();Jc();bG();xK();var pMe={},bxt=1e4;function Sxt(t,e){if(e?.csid&&up.test(e.csid))return e.csid;let{sessionId:n,...r}=e||{};return _ie(t,r)}function hMe(t,e){if(e)return{type:e.type||"stop",sessionId:e.sessionId||"",tool:e.tool||"",csid:e.csid||"",...e};let n=JSON.parse(t||"{}");return{type:n.type||"stop",sessionId:n.sessionId||"",tool:n.tool||"",csid:n.csid||"",...n}}async function mMe(t,e){let n="";await new Promise(r=>{t.on("data",i=>n+=i),t.on("end",r)});try{yMe(hMe(n,null)),De(e,{success:!0})}catch{ut(e,400,"Invalid JSON")}}function gMe(t,e,{query:n}){yMe(hMe(null,n)),De(e,{success:!0})}function fMe(t,e,n){let{type:r,sessionId:i,tool:s}=t,o={type:r,sessionId:i,tool:s,timestamp:n},c=Th({type:r,sessionId:i,tool:s})?.state||Qt.IDLE,l=Mi(i);if(Ge(e,"statusChange",{sessionId:i,state:c,tool:s,since:n,...l?{conversationId:l.id}:{}}),aB(i,o),Ge(e,"chatNotification",o),(c===Qt.DONE||c===Qt.BLOCKED)&&yC(i),(c===Qt.DONE||c===Qt.BLOCKED)&&wK(i),c!==Qt.DONE&&c!==Qt.BLOCKED)return;let u=`${i}:${c}`;n-(pMe[u]||0)<bxt||(pMe[u]=n,Ffe({...o,state:c}))}function yMe(t){let{type:e,sessionId:n,tool:r}=t,i=Date.now(),s=jr();if(!s||!n)return;let o=Sxt(r,t);if(o&&tc(n,r,o,"hook"),hC[e]===Qt.DONE){_C(n,()=>fMe(t,s,Date.now()));return}fMe(t,s,i)}qr();gG();HI();qt();var i5=Q(require("fs"),1),w1=Q(require("path"),1);jo();yi();jh();aa();var Txt=process.platform==="darwin"||process.platform==="win32",vMe=t=>Txt?t.toLowerCase():t,_Me=(t,e)=>{let n=vMe(t),r=vMe(e);return n===r||n.startsWith(r+w1.default.sep)},wMe=t=>[t.cwd,t.workspacePath].filter(Boolean);function Axt(t,e,n){if(e&&n.some(s=>s.id===e))return e;let r=null,i=-1;for(let s of n)for(let o of wMe(s))_Me(t,o)&&o.length>i&&(r=s.id,i=o.length);return r}function xMe({path:t,title:e},n=null){if(!t||typeof t!="string")return{error:"path is required"};let r=w1.default.resolve(t);try{r=i5.default.realpathSync(r)}catch{return{error:"File not found"}}if(gt(r))return{error:"Access denied"};if(!i5.default.statSync(r).isFile())return{error:"Not a file"};let i=Wu(),s=i.filter(c=>wMe(c).some(l=>_Me(r,l)));if(n&&i.some(c=>c.id===n)&&!s.some(c=>c.id===n))return{error:"File is outside this terminal's workspace"};if(!s.length)return{error:"File is outside every open terminal's workspace"};let o=jr();if(!o)return{error:"Server not ready"};let a=Axt(r,n,s);return Ge(o,"artifactOpen",{path:r,title:e||w1.default.basename(r),sessionId:a}),{path:r}}var Cxt={name:"openArtifact",description:"Show a file you just created or edited in the 9Remote app, sliding it in beside the terminal. Use it for files worth looking at \u2014 html, markdown, svg, images, pdf, csv, diagrams, code. Skip files with nothing to see. The user closes it themselves.",inputSchema:{type:"object",properties:{path:{type:"string",description:"Absolute path to the file."},title:{type:"string",description:"Optional label for the panel header."}},required:["path"]},run({path:t,title:e},n){let r=xMe({path:t,title:e},n?.sessionId);return r.error?r:`Opened ${r.path}`}},EMe=Cxt;ZE();V4();var Rxt=500;function Ixt(t={applyAction:p_}){return{name:"report_task",description:"Report what you just finished, in one or two sentences. It lands on this session's card on the kanban board the user watches, so progress is visible without reading your terminal. Call it when a chunk of work completes, and again with status when your own state changes (todo | in_progress | needs_input | done). While a turn of yours is actually running, the live state wins \u2014 the self-report takes effect when you go idle.",inputSchema:{type:"object",properties:{summary:{type:"string",description:"1-2 sentences of what was done or what changed"},status:{type:"string",enum:z4,description:"Optional self-reported status; live turn state still wins while running"}},required:["summary"]},async run({summary:e,status:n}={},r={}){let i=String(e||"").trim().slice(0,Rxt);if(!i)return{error:"summary is required"};let s=r?.sessionId;if(!s)return{error:"no session identity; cannot tell which card is yours"};let{error:o}=await t.applyAction({type:"report",sessionId:s,summary:i,...n?{status:n}:{}});return o?{error:o}:"reported"}}}var bMe=Ixt();nM();var SMe=[EMe],TMe=new Map([...SMe,...sf,bMe].map(t=>[t.name,t])),AMe=()=>SMe.map(({name:t,description:e,inputSchema:n})=>({name:t,description:e,inputSchema:n}));var x1=(t,e=!1)=>({content:[{type:"text",text:t}],isError:e});async function kxt(t,e,n){let r=TMe.get(t);if(!r)return x1(`Unknown tool: ${t}`,!0);try{let i=await r.run(e||{},n||{});return i?.error?x1(i.error,!0):x1(typeof i=="string"?i:JSON.stringify(i))}catch(i){return x1(i.message,!0)}}async function CMe(t,e){let{id:n,method:r,params:i}=t||{},s=o=>({jsonrpc:"2.0",id:n,result:o});return r==="initialize"?s({protocolVersion:i?.protocolVersion||Kl.PROTOCOL_VERSION,capabilities:{tools:{}},serverInfo:{name:Kl.SERVER_NAME,version:"3.0.51"}}):r==="tools/list"?s({tools:AMe()}):r==="tools/call"?s(await kxt(i?.name,i?.arguments,e)):r==="ping"?s({}):n==null?null:{jsonrpc:"2.0",id:n,error:{code:-32601,message:`Method not found: ${r}`}}}var o5=Q(require("fs"),1),IMe=require("child_process");$e();hG();var Pxt=Ee("artifact"),RMe=/(?:^|[\s\0])NINE_REMOTE_SESSION_ID=([^\s\0]+)/,s5=new WeakMap,a5=(t,e)=>(0,IMe.execFileSync)(t,e,{encoding:"utf8",timeout:_v.PROBE_TIMEOUT_MS,stdio:["ignore","pipe","ignore"]});function Mxt(t,e){let n=a5("lsof",["-nP",`-iTCP:${t}`,"-Fpn"]),r=null;for(let i of n.split(`
1181
- `))if(i[0]==="p")r=parseInt(i.slice(1),10);else if(i[0]==="n"&&r&&r!==e){let s=i.match(/^n(?:\[[^\]]+\]|[^:]+):(\d+)->/);if(s&&Number(s[1])===t)return r}return null}function Oxt(t){try{return process.platform==="linux"?o5.default.readFileSync(`/proc/${t}/environ`,"utf8").match(RMe)?.[1]||null:a5("ps",["-Eww","-o","command=","-p",String(t)]).match(RMe)?.[1]||null}catch{return null}}function Nxt(t){try{if(process.platform==="linux"){let e=o5.default.readFileSync(`/proc/${t}/stat`,"utf8");return parseInt(e.slice(e.lastIndexOf(")")+2).split(" ")[1],10)||null}return parseInt(a5("ps",["-o","ppid=","-p",String(t)]).trim(),10)||null}catch{return null}}function Dxt(t){for(let e=0;t>1&&t!==process.pid&&e<_v.MAX_PARENT_HOPS;e++){let n=Oxt(t);if(n)return n;if(t=Nxt(t),!t)return null}return null}function kMe(t){let e=t?.headers?.[_v.HEADER];if(e&&!/[${}]/.test(e))return e;let n=t?.socket;if(!n)return null;if(s5.has(n))return s5.get(n);let r=null;try{let i=Mxt(n.remotePort,process.pid);i&&(r=Dxt(i))}catch(i){Pxt.warn(`caller probe failed: ${i.message}`)}return s5.set(n,r),r}async function PMe(t,e){if(!Yfe(t.headers.authorization))return ut(e,401,"Unauthorized");if(!qx())return ut(e,403,"MCP is turned off in 9Remote settings");let n=await kr(t,e);if(n===null&&!e.writableEnded)return ut(e,400,"Invalid request");if(e.writableEnded)return;let r;try{r=await CMe(n,{sessionId:kMe(t)})}catch(i){r={jsonrpc:"2.0",id:n?.id??null,error:{code:-32603,message:i.message}}}if(!r)return e.writeHead(202),e.end();e.setHeader("Content-Type","application/json"),e.writeHead(200),e.end(JSON.stringify(r))}qr();oA();hu();Gr();ys();function MMe(){return{mode:ZL(),active:QL(),presets:Object.keys(Te.sleepInhibit?.presets||{})}}function OMe(t,e){De(e,MMe())}async function NMe(t,e){let n=await kr(t,e);if(!n)return;let r=Hw(n.mode);QT({sleepInhibitMode:r});let i=MMe();qn("sleepInhibit",i),De(e,i)}qr();hu();jo();ys();function DMe(t){return{enabled:t}}function LMe(t,e){De(e,DMe(G_()))}async function FMe(t,e){let n=await kr(t,e);if(!n)return;if(typeof n.enabled!="boolean")return ut(e,400,"enabled must be a boolean");QT({remoteEnabled:n.enabled}),BPe(n.enabled),Va(n.enabled?"start-tunnel":"stop-tunnel");let r=DMe(n.enabled);qn("remote",r),De(e,r)}qr();rU();async function UMe(t,e){let n=await MA();De(e,n)}async function BMe(t,e){let n=await Nte(),r=await MA();De(e,{...n,...r})}async function qMe(t,e){let n=await kr(t,e);if(!n)return;if(typeof n.text!="string"||!n.text){ut(e,400,"Missing text");return}let r=await r0(n.text);De(e,{ok:r.ok,reason:r.reason||null})}async function $Me(t,e){let n=await Ote(),r=await MA();De(e,{...n,...r})}ri();qr();async function GMe(t,e){try{let n=await zc();De(e,{sessions:n})}catch(n){ut(e,500,n.message)}}async function HMe(t,e){let n=await kr(t,e);if(n){if(!n.sessionId)return ut(e,400,"sessionId required");try{await Qd(n.sessionId),De(e)}catch(r){ut(e,500,r.message)}}}var yd=Q(require("os"),1);Gr();jA();qr();function Lxt(){let t=Sne();if(!t?.activeClients)return{total:0,streaming:0};let e=0;for(let n of t.activeClients.values())n.isStreaming&&e++;return{total:t.activeClients.size,streaming:e}}function Fxt(){let t=process.memoryUsage(),e=yd.default.cpus();return{agent:{pid:process.pid,version:"3.0.51",nodeVersion:process.version,platform:`${process.platform}/${process.arch}`,uptimeSec:Math.round(process.uptime()),memory:{heapUsedMB:Math.round(t.heapUsed/1048576*10)/10,heapTotalMB:Math.round(t.heapTotal/1048576*10)/10,rssMB:Math.round(t.rss/1048576*10)/10,externalMB:Math.round(t.external/1048576*10)/10}},os:{hostname:yd.default.hostname(),platform:yd.default.platform(),arch:yd.default.arch(),uptimeSec:Math.round(yd.default.uptime()),loadAvg:yd.default.loadavg(),cpuModel:e?.[0]?.model||"unknown",cpuCount:e.length,totalMemMB:Math.round(yd.default.totalmem()/1048576),freeMemMB:Math.round(yd.default.freemem()/1048576)},remote:{available:HA(),...Lxt(),memoryWarningThresholdMB:Te.resourceManagement.memoryWarningThreshold},timestamp:Date.now()}}function jMe(t,e){try{De(e,Fxt())}catch(n){ut(e,500,"stats error",n.message)}}oA();hu();Gr();eY();fY();var Ds=Ee("server"),Ta=(0,KMe.fileURLToPath)(new URL(".",__importMetaUrl)),YMe=process.env.NREMOTE_ENV==="development",Uxt=5173,c5=[(0,pn.join)(Ta,"dist","ui"),(0,pn.join)(Ta,"ui","dist"),(0,pn.join)(Ta,"ui")].find(t=>(0,is.existsSync)(t))||(0,pn.join)(Ta,"dist","ui"),Ml=[(0,pn.join)(Ta,"dist","web"),(0,pn.join)(Ta,"web"),(0,pn.join)(Ta,"..","web","out")].find(t=>(0,is.existsSync)(t))||c5,Bxt={".html":"text/html; charset=utf-8",".js":"application/javascript; charset=utf-8",".mjs":"application/javascript; charset=utf-8",".css":"text/css; charset=utf-8",".svg":"image/svg+xml",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp",".gif":"image/gif",".ico":"image/x-icon",".woff2":"font/woff2",".woff":"font/woff",".ttf":"font/ttf",".json":"application/json; charset=utf-8",".txt":"text/x-component; charset=utf-8",".webmanifest":"application/manifest+json"};function qxt(t,e,n){let r=(0,E1.request)({hostname:"localhost",port:Uxt,path:t.url,method:t.method,headers:t.headers},i=>{e.writeHead(i.statusCode,i.headers),i.pipe(e)});r.on("error",()=>n?n():void(e.writeHead(502),e.end("Vite dev server not ready"))),t.pipe(r)}function So(t,e,{frameable:n=!1}={}){if(!(0,is.existsSync)(e))return!1;try{if((0,is.statSync)(e).isDirectory()){let a=(0,pn.join)(e,"index.html");return(0,is.existsSync)(a)?So(t,a,{frameable:n}):!1}let i=(0,pn.extname)(e),s=Bxt[i]||"application/octet-stream";t.setHeader("Content-Type",s),i===".html"&&!n&&t.setHeader("X-Frame-Options","SAMEORIGIN");let o=e.includes(`${pn.sep}_next${pn.sep}static${pn.sep}`);return t.hasHeader("Cache-Control")||t.setHeader("Cache-Control",o?"public, max-age=31536000, immutable":"no-cache"),t.writeHead(200),t.end((0,is.readFileSync)(e)),!0}catch{return!1}}async function l5(t){try{let e=await Rc(Z1);if(!e.ok)return;let{version:n}=await e.json();if(n&&WPe(t,n)){pA({version:n}),qn("updateAvailable",{version:n}),QI();return}Ww()&&(pA(null),QI())}catch{}}var WMe=0;function $xt(t){let e=Date.now();e-WMe<Ew.connectCheckDebounceMs||(WMe=e,l5(t))}function Gxt(t,e){if(process.env.CODESPACES!=="true"){ut(e,400,"Not running on Codespaces");return}let n=process.env.CODESPACE_NAME;if(!n){ut(e,400,"Codespace name not found");return}let r=jr();r&&r.emit("codespace:stopping"),De(e,{success:!0,message:"Stopping codespace..."}),setTimeout(()=>(0,$m.execFile)("gh",["codespace","stop","-c",n],{windowsHide:!0}),500)}async function Hxt(t,e){let{parseJsonBody:n}=await Promise.resolve().then(()=>(qr(),Md)),r=await n(t,e);if(!r)return;let{verifyPresentedTail:i}=await Promise.resolve().then(()=>(jK(),wPe)),s=i({tail:r.tail,tempKey:r.tempKey});if(s.ok){De(e,{ok:!0});return}let o=t.headers["x-forwarded-for"]||t.socket?.remoteAddress||"unknown";if(r.tempKey&&r.tail)if(s.burned){Ds.warn(`wrong one-time code TAIL (${o}) \u2014 code burned, clearing from UI`);let{clearOneTimeKey:a}=await Promise.resolve().then(()=>(ys(),RF));a()}else Ds.warn(`stale one-time code TAIL (${o}) \u2014 code still live`);else r.tempKey?Ds.warn(`wrong one-time code TAIL (${o}) \u2014 no TAIL presented, code still live`):Ds.warn(`wrong API-key TAIL (${o}) \u2014 rejected`);setTimeout(()=>De(e,{ok:!1,reason:s.reason}),s.penaltyMs||0)}var jxt=[{path:"/api/health",method:"GET",public:!0,handler:(t,e)=>De(e,{status:"ok",timestamp:Date.now()})},{path:"/api/version",method:"GET",public:!0,handler:(t,e)=>{let n="3.0.51";e.setHeader("Cache-Control","no-store"),De(e,{version:n})}},{path:"/api/notify",method:"POST",public:!0,handler:mMe},{path:"/api/notify",method:"GET",public:!0,handler:gMe},{path:"/api/ui/events",method:"GET",handler:pF},{path:"/api/local-token",method:"GET",handler:lF},{path:Kl.PATH,method:"POST",handler:PMe},{path:"/api/browser-use",method:"POST",handler:c$},{path:"/api/ui/state",method:"GET",handler:fF},{path:"/api/ui/state",method:"POST",handler:hF},{path:"/api/ui/stop",method:"POST",handler:mF},{path:"/api/ui/start",method:"POST",handler:gF},{path:"/api/ui/stop-tunnel",method:"POST",handler:yF},{path:"/api/ui/shutdown",method:"POST",handler:vF},{path:"/api/update",method:"POST",handler:_F},{path:"/api/system/stats",method:"GET",handler:jMe},{path:"/api/key/one-time",method:"POST",handler:JPe},{path:"/api/key/regenerate",method:"POST",handler:ZPe},{path:"/api/signaling/retry",method:"POST",handler:QPe},{path:"/api/device/approve",method:"POST",handler:eMe},{path:"/api/device/reject",method:"POST",handler:tMe},{path:"/api/device/pending",method:"GET",handler:nMe},{path:"/api/device/approved",method:"GET",handler:rMe},{path:"/api/device/rejected",method:"GET",handler:iMe},{path:"/api/device/approve-rejected",method:"POST",handler:sMe},{path:"/api/device/clear-rejected",method:"POST",handler:oMe},{path:"/api/device/remove",method:"POST",handler:aMe},{path:"/api/device/label",method:"POST",handler:uMe},{path:"/api/device/disconnect",method:"POST",handler:cMe},{path:"/api/device/auto-approve",method:"GET",handler:lMe},{path:"/api/device/auto-approve",method:"POST",handler:dMe},{path:"/api/connections",method:"GET",handler:wF},{path:"/api/logs",method:"GET",handler:xF},{path:"/api/logs/clear",method:"POST",handler:EF},{path:"/api/permissions",method:"GET",handler:SF},{path:"/api/permissions/request",method:"POST",handler:CF},{path:"/api/desktop/toggle",method:"POST",handler:bF},{path:"/api/ui/rtc-toggle",method:"POST",handler:uF},{path:"/api/autostart",method:"GET",handler:TF},{path:"/api/autostart",method:"POST",handler:AF},{path:"/api/sleep-inhibit",method:"GET",handler:OMe},{path:"/api/sleep-inhibit",method:"POST",handler:NMe},{path:"/api/remote/enabled",method:"GET",handler:LMe},{path:"/api/remote/enabled",method:"POST",handler:FMe},{path:"/api/desktop-unlock",method:"GET",handler:UMe},{path:"/api/desktop-unlock/install",method:"POST",handler:BMe},{path:"/api/desktop-unlock/uninstall",method:"POST",handler:$Me},{path:"/api/desktop-unlock/type",method:"POST",handler:qMe},{path:"/api/sessions",method:"GET",handler:GMe},{path:"/api/sessions/delete",method:"POST",handler:HMe},{path:"/api/codespace/stop",method:"POST",handler:Gxt},{path:"/api/verify-key",method:"POST",public:!0,handler:Hxt}];var zMe=parseInt(process.env.PORT||"2208",10),nS=null;function Wxt(t){if(process.platform!=="win32")try{let e=(0,$m.execSync)(`pgrep -f "vite --config ${t}"`,{encoding:"utf8"}).trim();for(let n of e.split(`
1182
- `).filter(Boolean))if((0,$m.execSync)(`ps -o ppid= -p ${n}`,{encoding:"utf8"}).trim()==="1")try{process.kill(Number(n))}catch{}}catch{}}function zxt(){if(!YMe)return;let t=(0,pn.join)(Ta,"vite.config.js");if(!(0,is.existsSync)(t))return;Wxt(t);let e=(0,is.existsSync)((0,pn.join)(Ta,"node_modules",".bin","vite"))?(0,pn.join)(Ta,"node_modules",".bin","vite"):(0,pn.join)(Ta,"..","node_modules",".bin","vite");nS=(0,$m.spawn)("node",[e,"--config",t],{cwd:Ta,stdio:"ignore",detached:!1}),nS.on("error",()=>{}),nS.unref()}async function XMe(){let t=sh(),e=t.sleepInhibitMode;e||(t.sleepInhibit===!1?e="none":e=Te.sleepInhibit?.defaultMode||"never"),Hw(e),await RG(),zxt();let r=tN(jxt,{fallback:(l,u,{pathname:d})=>{if(d.startsWith("/api/")||d.startsWith("/socket.io")){ut(u,404,"Not found");return}if(d==="/"||d==="/ui"){u.writeHead(302,{Location:"/workspace"}),u.end();return}let p=d.replace(/^\//,"");if(p.split(/[\\/]/).includes("..")){ut(u,400,"Bad request");return}if((0,is.existsSync)(Ml)&&p)try{let y=(0,pn.join)(Ml,p);if((0,is.existsSync)(y)&&!(0,is.statSync)(y).isDirectory()&&So(u,y))return}catch{}if((d==="/workspace"||d.startsWith("/workspace/")||d.startsWith("/_next/")||d==="/login"||d.startsWith("/login/"))&&(0,is.existsSync)(Ml)){let y=(0,pn.join)(Ml,p);if(So(u,y)||So(u,`${y}.html`)||So(u,(0,pn.join)(y,"index.html"))||(l.headers.rsc==="1"||p.endsWith(".txt"))&&(p.startsWith("workspace/terminal/")&&So(u,(0,pn.join)(Ml,"workspace","terminal","default.txt"))||So(u,(0,pn.join)(Ml,"workspace.txt")))||d.startsWith("/workspace")&&(So(u,(0,pn.join)(Ml,"workspace.html"))||So(u,(0,pn.join)(Ml,"workspace","index.html")))||d.startsWith("/login")&&(So(u,(0,pn.join)(Ml,"login.html"))||So(u,(0,pn.join)(Ml,"login","index.html"))))return;ut(u,404,"Not found");return}let h=()=>{let y=p==="ui"||p===""?"index.html":p.replace(/^ui\/?/,""),v=(0,pn.join)(c5,y);So(u,v)||So(u,(0,pn.join)(c5,"index.html"))||ut(u,404,"Not found")};if(YMe){qxt(l,u,h);return}h()}}),i=(0,E1.createServer)(async(l,u)=>{await r(l,u)});sL(),nF(),rF();let s=Go()?.key;s&&Ho({permanentKey:s});let o=()=>fA().catch(l=>Ds.error(`permission refresh failed: ${l?.message||l}`));o(),process.platform==="darwin"&&setInterval(o,tY),mce(i,zMe),await qPe(i),i.on("error",l=>{Ds.error(`HTTP server error: ${l?.message||l}`),l?.code==="EADDRINUSE"&&process.exit(1)}),i.listen(zMe,l=>{if(l)throw l;let u="3.0.51";l5(u),setInterval(()=>l5(u),Ew.checkIntervalMs),IG(()=>$xt(u))});let a=!1,c=async l=>{if(a)return;a=!0,JL(),Ds.info(`\u{1F6D1} Received ${l}, shutting down gracefully...`);let u=setTimeout(()=>{Ds.error("\u26A0\uFE0F Forced exit"),process.exit(1)},5e3);try{if(i.close(()=>Ds.info("\u2713 HTTP server closed")),nS)try{nS.kill()}catch{}let d=jr();if(d&&(d.emit("server:shutdown"),d.close(()=>Ds.info("\u2713 Socket.IO closed"))),process.env.NREMOTE_ENV!=="development")try{await Ole()}catch{}await new Promise(p=>setTimeout(p,500)),clearTimeout(u),Ds.info("\u2705 Server stopped cleanly"),process.exit(0)}catch(d){Ds.error(`\u274C Error during shutdown: ${d?.message||d}`),clearTimeout(u),process.exit(1)}};return process.on("SIGINT",()=>c("SIGINT")),process.on("SIGTERM",()=>c("SIGTERM")),process.platform==="win32"&&process.on("SIGBREAK",()=>c("SIGBREAK")),i}var VMe=process.argv.slice(2).filter(t=>!t.startsWith("--"));VMe.length&&(Ds.error(`host/index.js takes no commands (got: ${VMe.join(" ")}) \u2014 use \`9remote <command>\``),process.exit(1));XMe().catch(t=>{Ds.error(`Server failed to start: ${t?.stack||t?.message||t}`),process.exit(1)});0&&(module.exports={startServer});
1180
+ `)[0].replace(/\=|\s+|\"/gi,"").toLowerCase();case"win32":return b.toString().split("REG_SZ")[1].replace(/\r+|\n+|\s+/gi,"").toLowerCase();case"linux":return b.toString().replace(/\r+|\n+|\s+/gi,"").toLowerCase();case"freebsd":return b.toString().replace(/\r+|\n+|\s+/gi,"").toLowerCase();default:throw new Error("Unsupported platform: "+process.platform)}}function l(b){var S=c((0,m.execSync)(A[v]).toString());return b?S:a(S)}function u(b){return new p.default(function(S,I){return(0,m.exec)(A[v],{},function(F,D,B){if(F)return I(new Error("Error while obtaining machine id: "+F.stack));var M=c(D.toString());return S(b?M:a(M))})})}Object.defineProperty(r,"__esModule",{value:!0});var d=i(35),p=s(d);r.machineIdSync=l,r.machineId=u;var m=i(70),h=i(71),y=process,v=y.platform,E={native:"%windir%\\System32",mixed:"%windir%\\sysnative\\cmd.exe /c %windir%\\System32"},A={darwin:"ioreg -rd1 -c IOPlatformExpertDevice",win32:E[o()]+"\\REG.exe QUERY HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Cryptography /v MachineGuid",linux:"( cat /var/lib/dbus/machine-id /etc/machine-id 2> /dev/null || hostname ) | head -n 1 || :",freebsd:"kenv -q smbios.system.uuid || sysctl -n kern.hostuuid"}},function(n,r,i){n.exports={default:i(36),__esModule:!0}},function(n,r,i){i(66),i(68),i(69),i(67),n.exports=i(6).Promise},function(n,r){n.exports=function(){}},function(n,r){n.exports=function(i,s,o,a){if(!(i instanceof s)||a!==void 0&&a in i)throw TypeError(o+": incorrect invocation!");return i}},function(n,r,i){var s=i(13),o=i(31),a=i(62);n.exports=function(c){return function(l,u,d){var p,m=s(l),h=o(m.length),y=a(d,h);if(c&&u!=u){for(;h>y;)if(p=m[y++],p!=p)return!0}else for(;h>y;y++)if((c||y in m)&&m[y]===u)return c||y||0;return!c&&-1}}},function(n,m,i){var s=i(7),o=i(44),a=i(43),c=i(3),l=i(31),u=i(64),d={},p={},m=n.exports=function(h,y,v,E,A){var b,S,I,F,D=A?function(){return h}:u(h),B=s(v,E,y?2:1),M=0;if(typeof D!="function")throw TypeError(h+" is not iterable!");if(a(D)){for(b=l(h.length);b>M;M++)if(F=y?B(c(S=h[M])[0],S[1]):B(h[M]),F===d||F===p)return F}else for(I=D.call(h);!(S=I.next()).done;)if(F=o(I,B,S.value,y),F===d||F===p)return F};m.BREAK=d,m.RETURN=p},function(n,r){n.exports=function(i,s,o){var a=o===void 0;switch(s.length){case 0:return a?i():i.call(o);case 1:return a?i(s[0]):i.call(o,s[0]);case 2:return a?i(s[0],s[1]):i.call(o,s[0],s[1]);case 3:return a?i(s[0],s[1],s[2]):i.call(o,s[0],s[1],s[2]);case 4:return a?i(s[0],s[1],s[2],s[3]):i.call(o,s[0],s[1],s[2],s[3])}return i.apply(o,s)}},function(n,r,i){var s=i(11);n.exports=Object("z").propertyIsEnumerable(0)?Object:function(o){return s(o)=="String"?o.split(""):Object(o)}},function(n,r,i){var s=i(10),o=i(1)("iterator"),a=Array.prototype;n.exports=function(c){return c!==void 0&&(s.Array===c||a[o]===c)}},function(n,r,i){var s=i(3);n.exports=function(o,a,c,l){try{return l?a(s(c)[0],c[1]):a(c)}catch(d){var u=o.return;throw u!==void 0&&s(u.call(o)),d}}},function(n,r,i){"use strict";var s=i(49),o=i(17),a=i(18),c={};i(5)(c,i(1)("iterator"),function(){return this}),n.exports=function(l,u,d){l.prototype=s(c,{next:o(1,d)}),a(l,u+" Iterator")}},function(n,r,i){var s=i(1)("iterator"),o=!1;try{var a=[7][s]();a.return=function(){o=!0},Array.from(a,function(){throw 2})}catch{}n.exports=function(c,l){if(!l&&!o)return!1;var u=!1;try{var d=[7],p=d[s]();p.next=function(){return{done:u=!0}},d[s]=function(){return p},c(d)}catch{}return u}},function(n,r){n.exports=function(i,s){return{value:s,done:!!i}}},function(n,r,i){var s=i(2),o=i(30).set,a=s.MutationObserver||s.WebKitMutationObserver,c=s.process,l=s.Promise,u=i(11)(c)=="process";n.exports=function(){var d,p,m,h=function(){var A,b;for(u&&(A=c.domain)&&A.exit();d;){b=d.fn,d=d.next;try{b()}catch(S){throw d?m():p=void 0,S}}p=void 0,A&&A.enter()};if(u)m=function(){c.nextTick(h)};else if(a){var y=!0,v=document.createTextNode("");new a(h).observe(v,{characterData:!0}),m=function(){v.data=y=!y}}else if(l&&l.resolve){var E=l.resolve();m=function(){E.then(h)}}else m=function(){o.call(s,h)};return function(A){var b={fn:A,next:void 0};p&&(p.next=b),d||(d=b,m()),p=b}}},function(n,r,i){var s=i(3),o=i(50),a=i(22),c=i(19)("IE_PROTO"),l=function(){},u="prototype",d=function(){var p,m=i(16)("iframe"),h=a.length,y=">";for(m.style.display="none",i(25).appendChild(m),m.src="javascript:",p=m.contentWindow.document,p.open(),p.write("<script>document.F=Object</script"+y),p.close(),d=p.F;h--;)delete d[u][a[h]];return d()};n.exports=Object.create||function(p,m){var h;return p!==null?(l[u]=s(p),h=new l,l[u]=null,h[c]=p):h=d(),m===void 0?h:o(h,m)}},function(n,r,i){var s=i(12),o=i(3),a=i(54);n.exports=i(4)?Object.defineProperties:function(c,l){o(c);for(var u,d=a(l),p=d.length,m=0;p>m;)s.f(c,u=d[m++],l[u]);return c}},function(n,r,i){var s=i(55),o=i(17),a=i(13),c=i(32),l=i(8),u=i(26),d=Object.getOwnPropertyDescriptor;r.f=i(4)?d:function(p,m){if(p=a(p),m=c(m,!0),u)try{return d(p,m)}catch{}if(l(p,m))return o(!s.f.call(p,m),p[m])}},function(n,r,i){var s=i(8),o=i(63),a=i(19)("IE_PROTO"),c=Object.prototype;n.exports=Object.getPrototypeOf||function(l){return l=o(l),s(l,a)?l[a]:typeof l.constructor=="function"&&l instanceof l.constructor?l.constructor.prototype:l instanceof Object?c:null}},function(n,r,i){var s=i(8),o=i(13),a=i(39)(!1),c=i(19)("IE_PROTO");n.exports=function(l,u){var d,p=o(l),m=0,h=[];for(d in p)d!=c&&s(p,d)&&h.push(d);for(;u.length>m;)s(p,d=u[m++])&&(~a(h,d)||h.push(d));return h}},function(n,r,i){var s=i(53),o=i(22);n.exports=Object.keys||function(a){return s(a,o)}},function(n,r){r.f={}.propertyIsEnumerable},function(n,r,i){var s=i(5);n.exports=function(o,a,c){for(var l in a)c&&o[l]?o[l]=a[l]:s(o,l,a[l]);return o}},function(n,r,i){n.exports=i(5)},function(n,r,i){var s=i(9),o=i(3),a=function(c,l){if(o(c),!s(l)&&l!==null)throw TypeError(l+": can't set as prototype!")};n.exports={set:Object.setPrototypeOf||("__proto__"in{}?(function(c,l,u){try{u=i(7)(Function.call,i(51).f(Object.prototype,"__proto__").set,2),u(c,[]),l=!(c instanceof Array)}catch{l=!0}return function(d,p){return a(d,p),l?d.__proto__=p:u(d,p),d}})({},!1):void 0),check:a}},function(n,r,i){"use strict";var s=i(2),o=i(6),a=i(12),c=i(4),l=i(1)("species");n.exports=function(u){var d=typeof o[u]=="function"?o[u]:s[u];c&&d&&!d[l]&&a.f(d,l,{configurable:!0,get:function(){return this}})}},function(n,r,i){var s=i(3),o=i(14),a=i(1)("species");n.exports=function(c,l){var u,d=s(c).constructor;return d===void 0||(u=s(d)[a])==null?l:o(u)}},function(n,r,i){var s=i(20),o=i(15);n.exports=function(a){return function(c,l){var u,d,p=String(o(c)),m=s(l),h=p.length;return m<0||m>=h?a?"":void 0:(u=p.charCodeAt(m),u<55296||u>56319||m+1===h||(d=p.charCodeAt(m+1))<56320||d>57343?a?p.charAt(m):u:a?p.slice(m,m+2):(u-55296<<10)+(d-56320)+65536)}}},function(n,r,i){var s=i(20),o=Math.max,a=Math.min;n.exports=function(c,l){return c=s(c),c<0?o(c+l,0):a(c,l)}},function(n,r,i){var s=i(15);n.exports=function(o){return Object(s(o))}},function(n,r,i){var s=i(21),o=i(1)("iterator"),a=i(10);n.exports=i(6).getIteratorMethod=function(c){if(c!=null)return c[o]||c["@@iterator"]||a[s(c)]}},function(n,r,i){"use strict";var s=i(37),o=i(47),a=i(10),c=i(13);n.exports=i(27)(Array,"Array",function(l,u){this._t=c(l),this._i=0,this._k=u},function(){var l=this._t,u=this._k,d=this._i++;return!l||d>=l.length?(this._t=void 0,o(1)):u=="keys"?o(0,d):u=="values"?o(0,l[d]):o(0,[d,l[d]])},"values"),a.Arguments=a.Array,s("keys"),s("values"),s("entries")},function(n,r){},function(n,r,i){"use strict";var s,o,a,c=i(28),l=i(2),u=i(7),d=i(21),p=i(23),m=i(9),h=(i(3),i(14)),y=i(38),v=i(40),E=(i(58).set,i(60)),A=i(30).set,b=i(48)(),S="Promise",I=l.TypeError,D=l.process,F=l[S],D=l.process,B=d(D)=="process",M=function(){},P=!!(function(){try{var ce=F.resolve(1),J=(ce.constructor={})[i(1)("species")]=function(fe){fe(M,M)};return(B||typeof PromiseRejectionEvent=="function")&&ce.then(M)instanceof J}catch{}})(),x=function(ce,J){return ce===J||ce===F&&J===a},R=function(ce){var J;return!(!m(ce)||typeof(J=ce.then)!="function")&&J},N=function(ce){return x(F,ce)?new k(ce):new o(ce)},k=o=function(ce){var J,fe;this.promise=new ce(function(we,xe){if(J!==void 0||fe!==void 0)throw I("Bad Promise constructor");J=we,fe=xe}),this.resolve=h(J),this.reject=h(fe)},O=function(ce){try{ce()}catch(J){return{error:J}}},$=function(ce,J){if(!ce._n){ce._n=!0;var fe=ce._c;b(function(){for(var we=ce._v,xe=ce._s==1,Ue=0,ke=function(q){var V,W,Z=xe?q.ok:q.fail,ee=q.resolve,te=q.reject,oe=q.domain;try{Z?(xe||(ce._h==2&&C(ce),ce._h=1),Z===!0?V=we:(oe&&oe.enter(),V=Z(we),oe&&oe.exit()),V===q.promise?te(I("Promise-chain cycle")):(W=R(V))?W.call(V,ee,te):ee(V)):te(we)}catch(ie){te(ie)}};fe.length>Ue;)ke(fe[Ue++]);ce._c=[],ce._n=!1,J&&!ce._h&&Y(ce)})}},Y=function(ce){A.call(l,function(){var J,fe,we,xe=ce._v;if(L(ce)&&(J=O(function(){B?D.emit("unhandledRejection",xe,ce):(fe=l.onunhandledrejection)?fe({promise:ce,reason:xe}):(we=l.console)&&we.error&&we.error("Unhandled promise rejection",xe)}),ce._h=B||L(ce)?2:1),ce._a=void 0,J)throw J.error})},L=function(ce){if(ce._h==1)return!1;for(var J,fe=ce._a||ce._c,we=0;fe.length>we;)if(J=fe[we++],J.fail||!L(J.promise))return!1;return!0},C=function(ce){A.call(l,function(){var J;B?D.emit("rejectionHandled",ce):(J=l.onrejectionhandled)&&J({promise:ce,reason:ce._v})})},G=function(ce){var J=this;J._d||(J._d=!0,J=J._w||J,J._v=ce,J._s=2,J._a||(J._a=J._c.slice()),$(J,!0))},le=function(ce){var J,fe=this;if(!fe._d){fe._d=!0,fe=fe._w||fe;try{if(fe===ce)throw I("Promise can't be resolved itself");(J=R(ce))?b(function(){var we={_w:fe,_d:!1};try{J.call(ce,u(le,we,1),u(G,we,1))}catch(xe){G.call(we,xe)}}):(fe._v=ce,fe._s=1,$(fe,!1))}catch(we){G.call({_w:fe,_d:!1},we)}}};P||(F=function(ce){y(this,F,S,"_h"),h(ce),s.call(this);try{ce(u(le,this,1),u(G,this,1))}catch(J){G.call(this,J)}},s=function(ce){this._c=[],this._a=void 0,this._s=0,this._d=!1,this._v=void 0,this._h=0,this._n=!1},s.prototype=i(56)(F.prototype,{then:function(ce,J){var fe=N(E(this,F));return fe.ok=typeof ce!="function"||ce,fe.fail=typeof J=="function"&&J,fe.domain=B?D.domain:void 0,this._c.push(fe),this._a&&this._a.push(fe),this._s&&$(this,!1),fe.promise},catch:function(ce){return this.then(void 0,ce)}}),k=function(){var ce=new s;this.promise=ce,this.resolve=u(le,ce,1),this.reject=u(G,ce,1)}),p(p.G+p.W+p.F*!P,{Promise:F}),i(18)(F,S),i(59)(S),a=i(6)[S],p(p.S+p.F*!P,S,{reject:function(ce){var J=N(this),fe=J.reject;return fe(ce),J.promise}}),p(p.S+p.F*(c||!P),S,{resolve:function(ce){if(ce instanceof F&&x(ce.constructor,this))return ce;var J=N(this),fe=J.resolve;return fe(ce),J.promise}}),p(p.S+p.F*!(P&&i(46)(function(ce){F.all(ce).catch(M)})),S,{all:function(ce){var J=this,fe=N(J),we=fe.resolve,xe=fe.reject,Ue=O(function(){var ke=[],q=0,V=1;v(ce,!1,function(W){var Z=q++,ee=!1;ke.push(void 0),V++,J.resolve(W).then(function(te){ee||(ee=!0,ke[Z]=te,--V||we(ke))},xe)}),--V||we(ke)});return Ue&&xe(Ue.error),fe.promise},race:function(ce){var J=this,fe=N(J),we=fe.reject,xe=O(function(){v(ce,!1,function(Ue){J.resolve(Ue).then(fe.resolve,we)})});return xe&&we(xe.error),fe.promise}})},function(n,r,i){"use strict";var s=i(61)(!0);i(27)(String,"String",function(o){this._t=String(o),this._i=0},function(){var o,a=this._t,c=this._i;return c>=a.length?{value:void 0,done:!0}:(o=s(a,c),this._i+=o.length,{value:o,done:!1})})},function(n,r,i){i(65);for(var s=i(2),o=i(5),a=i(10),c=i(1)("toStringTag"),l=["NodeList","DOMTokenList","MediaList","StyleSheetList","CSSRuleList"],u=0;u<5;u++){var d=l[u],p=s[d],m=p&&p.prototype;m&&!m[c]&&o(m,c,d),a[d]=a.Array}},function(n,r){n.exports=require("child_process")},function(n,r){n.exports=require("crypto")}])})});var Vxt={};fr(Vxt,{startServer:()=>XMe});module.exports=WOe(Vxt);for(let t of[process.stdout,process.stderr])t?.on?.("error",e=>{if(e?.code!=="EPIPE")throw e});var E1=require("http"),$m=require("child_process"),is=require("fs"),pn=require("path"),KMe=require("url");qr();qt();$e();jo();aa();Um();BT();var eS=require("fs"),HPe=require("url");var _1=Q(require("path"),1),jPe=Q(require("os"),1);qt();var $Pe=Q(require("path"),1),GPe=Q(require("os"),1);var W$t=$Pe.default.join(GPe.default.homedir(),".9remote","pids");WL();eh();$e();var tGt=Ee("update"),nGt=_1.default.dirname((0,HPe.fileURLToPath)(__importMetaUrl)),rGt=(0,eS.existsSync)("/.dockerenv");var iGt=_1.default.join(jPe.default.homedir(),".9remote","cloudflared.pid");function WPe(t,e){let n=t.split(".").map(Number),r=e.split(".").map(Number);for(let i=0;i<3;i++){if(r[i]>n[i])return!0;if(r[i]<n[i])return!1}return!1}var sGt=_1.default.join(Pe.STATE,Ew.lockFile);HR();wR();gx();ys();aa();eh();qr();hu();Um();var VPe=Q(zPe(),1),e5=Q(require("crypto"),1),{machineIdSync:xxt}=VPe.default;async function KPe(t=null){let e=t||process.env.MACHINE_ID_SALT||"9remote-salt";try{let n=xxt();return e5.default.createHash("sha256").update(n+e).digest("hex").substring(0,16)}catch(n){return console.error("Error getting machine ID:",n),e5.default.randomUUID().replace(/-/g,"").substring(0,16)}}ys();qt();$e();Nw();Um();NK();var t5=Ee("session"),Ext=10;async function YPe(t,e){let n=async()=>{let r=await Rc(`${e}/api/temp-key/create`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify((()=>{let i={apiKey:sr(t),expiryMinutes:Ext};return{...i,...YT(i)}})())});if(!r.ok){let i=await r.json().catch(()=>null);throw new Error(i?.error||`HTTP ${r.status}`)}return r.json()};try{let r;try{r=await n()}catch(s){if(t5.warn(`Temp key creation failed (${s.message}) \u2014 re-registering session`),!await n5(t,e))throw s;r=await n()}let i=cPe();return uPe(r.tempKey,i,r.expiresAt,e),{...r,oneTimeKey:`${r.tempKey}${i}`}}catch(r){return t5.error(`Temp key creation failed: ${r?.message||r}`),null}}function XPe(t,e){return e?.tempKey?`${t}/login?k=${e.tempKey}#${e.oneTimeKey}`:`${t}/login`}async function n5(t,e,n,r){try{let i=await Rc(`${e}/api/session/create`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:sr(t),hostPublicKey:VT(),hostX25519Key:KT(),tempKey:Vb()?.tempKey||void 0})});if(!i.ok)throw new Error(`HTTP ${i.status}`);return n&&await Rc(`${e}/api/session/update`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:sr(t),tunnelUrl:n,...YT({apiKey:sr(t),tunnelUrl:n})})}).catch(()=>{}),r&&sr(r)!==sr(t)&&await Rc(`${e}/api/session/delete`,{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:sr(r),...YT({apiKey:sr(r)})})}).catch(()=>{}),!0}catch(i){return t5.error(`Session registration failed: ${i?.message||i}`),!1}}Tw();Um();eh();function r5(t){return sh().remoteEnabled!==!1?!1:(ut(t,409,"Remote access is off"),!0)}async function JPe(t,e){if(r5(e))return;let n=lA(),r=n.workerUrl||Nc;if(!n.permanentKey){ut(e,400,"No permanent key set");return}let i=await YPe(n.permanentKey,r);if(!i){ut(e,500,"Temp key creation failed");return}let s=XPe(r,i);Ho({oneTimeKey:i.oneTimeKey,oneTimeKeyExpiresAt:i.expiresAt,qrUrl:s}),De(e,{oneTimeKey:i.oneTimeKey,expiresAt:i.expiresAt,qrUrl:s})}async function QPe(t,e){r5(e)||(LT("session-registered"),De(e,FT()))}async function ZPe(t,e){if(!r5(e))try{let n=lA(),r=n.workerUrl||Nc,i=await KPe(),s=hPe(i),o=Go();if(!await n5(s,r,n.tunnelUrl,o?.key)){ut(e,502,"Could not register the new key with the server");return}IZ(i,s,o?.name||"Default"),qg(sr(s)),Ho({permanentKey:s,oneTimeKey:"",oneTimeKeyExpiresAt:null,qrUrl:"",pairingUsed:!0}),De(e,{ok:!0,permanentKey:s})}catch(n){ut(e,500,n.message)}}qr();jo();Xw();async function eMe(t,e){let n=await kr(t,e);if(!n)return;let r=DPe(n.socketId);De(e,{ok:r})}async function tMe(t,e){let n=await kr(t,e);if(!n)return;let r=FPe(n.socketId);De(e,{ok:r})}function nMe(t,e){De(e,{pending:hee()})}function rMe(t,e){De(e,{devices:pee()})}function iMe(t,e){De(e,{rejected:gee()})}async function sMe(t,e){let n=await kr(t,e);if(!n)return;let r=LPe(n.deviceId);De(e,{ok:r})}async function oMe(t,e){let n=await kr(t,e);n&&(v1(n.deviceId),dy(n.deviceId),De(e))}async function aMe(t,e){let n=await kr(t,e);n&&(v1(n.deviceId),lee(n.deviceId),De(e))}async function cMe(t,e){let n=await kr(t,e);if(!n)return;aee(n.deviceId);let r=v1(n.deviceId);De(e,{disconnected:r})}function lMe(t,e){De(e,{enabled:LF()})}async function uMe(t,e){let n=await kr(t,e);if(!n)return;let r=uee(n.deviceId,n.label);De(e,{ok:r})}async function dMe(t,e){let n=await kr(t,e);if(!n)return;let r=vee(!!n.enabled);De(e,{enabled:r})}qr();jo();yi();LI();xs();Jc();bG();xK();var pMe={},bxt=1e4;function Sxt(t,e){if(e?.csid&&up.test(e.csid))return e.csid;let{sessionId:n,...r}=e||{};return _ie(t,r)}function hMe(t,e){if(e)return{type:e.type||"stop",sessionId:e.sessionId||"",tool:e.tool||"",csid:e.csid||"",...e};let n=JSON.parse(t||"{}");return{type:n.type||"stop",sessionId:n.sessionId||"",tool:n.tool||"",csid:n.csid||"",...n}}async function mMe(t,e){let n="";await new Promise(r=>{t.on("data",i=>n+=i),t.on("end",r)});try{yMe(hMe(n,null)),De(e,{success:!0})}catch{ut(e,400,"Invalid JSON")}}function gMe(t,e,{query:n}){yMe(hMe(null,n)),De(e,{success:!0})}function fMe(t,e,n){let{type:r,sessionId:i,tool:s}=t,o={type:r,sessionId:i,tool:s,timestamp:n},c=Th({type:r,sessionId:i,tool:s})?.state||Qt.IDLE,l=Mi(i);if(Ge(e,"statusChange",{sessionId:i,state:c,tool:s,since:n,...l?{conversationId:l.id}:{}}),aB(i,o),Ge(e,"chatNotification",o),(c===Qt.DONE||c===Qt.BLOCKED)&&yC(i),(c===Qt.DONE||c===Qt.BLOCKED)&&wK(i),c!==Qt.DONE&&c!==Qt.BLOCKED)return;let u=`${i}:${c}`;n-(pMe[u]||0)<bxt||(pMe[u]=n,Ffe({...o,state:c}))}function yMe(t){let{type:e,sessionId:n,tool:r}=t,i=Date.now(),s=jr();if(!s||!n)return;let o=Sxt(r,t);if(o&&tc(n,r,o,"hook"),hC[e]===Qt.DONE){_C(n,()=>fMe(t,s,Date.now()));return}fMe(t,s,i)}qr();gG();HI();qt();var i5=Q(require("fs"),1),w1=Q(require("path"),1);jo();yi();jh();aa();var Txt=process.platform==="darwin"||process.platform==="win32",vMe=t=>Txt?t.toLowerCase():t,_Me=(t,e)=>{let n=vMe(t),r=vMe(e);return n===r||n.startsWith(r+w1.default.sep)},wMe=t=>[t.cwd,t.workspacePath].filter(Boolean);function Axt(t,e,n){if(e&&n.some(s=>s.id===e))return e;let r=null,i=-1;for(let s of n)for(let o of wMe(s))_Me(t,o)&&o.length>i&&(r=s.id,i=o.length);return r}function xMe({path:t,title:e},n=null){if(!t||typeof t!="string")return{error:"path is required"};let r=w1.default.resolve(t);try{r=i5.default.realpathSync(r)}catch{return{error:"File not found"}}if(gt(r))return{error:"Access denied"};if(!i5.default.statSync(r).isFile())return{error:"Not a file"};let i=Wu(),s=i.filter(c=>wMe(c).some(l=>_Me(r,l)));if(n&&i.some(c=>c.id===n)&&!s.some(c=>c.id===n))return{error:"File is outside this terminal's workspace"};if(!s.length)return{error:"File is outside every open terminal's workspace"};let o=jr();if(!o)return{error:"Server not ready"};let a=Axt(r,n,s);return Ge(o,"artifactOpen",{path:r,title:e||w1.default.basename(r),sessionId:a}),{path:r}}var Cxt={name:"openArtifact",description:"Show a file you just created or edited in the 9Remote app, sliding it in beside the terminal. Use it for files worth looking at \u2014 html, markdown, svg, images, pdf, csv, diagrams, code. Skip files with nothing to see. The user closes it themselves.",inputSchema:{type:"object",properties:{path:{type:"string",description:"Absolute path to the file."},title:{type:"string",description:"Optional label for the panel header."}},required:["path"]},run({path:t,title:e},n){let r=xMe({path:t,title:e},n?.sessionId);return r.error?r:`Opened ${r.path}`}},EMe=Cxt;ZE();V4();var Rxt=500;function Ixt(t={applyAction:p_}){return{name:"report_task",description:"Report what you just finished, in one or two sentences. It lands on this session's card on the kanban board the user watches, so progress is visible without reading your terminal. Call it when a chunk of work completes, and again with status when your own state changes (todo | in_progress | needs_input | done). While a turn of yours is actually running, the live state wins \u2014 the self-report takes effect when you go idle.",inputSchema:{type:"object",properties:{summary:{type:"string",description:"1-2 sentences of what was done or what changed"},status:{type:"string",enum:z4,description:"Optional self-reported status; live turn state still wins while running"}},required:["summary"]},async run({summary:e,status:n}={},r={}){let i=String(e||"").trim().slice(0,Rxt);if(!i)return{error:"summary is required"};let s=r?.sessionId;if(!s)return{error:"no session identity; cannot tell which card is yours"};let{error:o}=await t.applyAction({type:"report",sessionId:s,summary:i,...n?{status:n}:{}});return o?{error:o}:"reported"}}}var bMe=Ixt();nM();var SMe=[EMe],TMe=new Map([...SMe,...sf,bMe].map(t=>[t.name,t])),AMe=()=>SMe.map(({name:t,description:e,inputSchema:n})=>({name:t,description:e,inputSchema:n}));var x1=(t,e=!1)=>({content:[{type:"text",text:t}],isError:e});async function kxt(t,e,n){let r=TMe.get(t);if(!r)return x1(`Unknown tool: ${t}`,!0);try{let i=await r.run(e||{},n||{});return i?.error?x1(i.error,!0):x1(typeof i=="string"?i:JSON.stringify(i))}catch(i){return x1(i.message,!0)}}async function CMe(t,e){let{id:n,method:r,params:i}=t||{},s=o=>({jsonrpc:"2.0",id:n,result:o});return r==="initialize"?s({protocolVersion:i?.protocolVersion||Kl.PROTOCOL_VERSION,capabilities:{tools:{}},serverInfo:{name:Kl.SERVER_NAME,version:"3.0.52"}}):r==="tools/list"?s({tools:AMe()}):r==="tools/call"?s(await kxt(i?.name,i?.arguments,e)):r==="ping"?s({}):n==null?null:{jsonrpc:"2.0",id:n,error:{code:-32601,message:`Method not found: ${r}`}}}var o5=Q(require("fs"),1),IMe=require("child_process");$e();hG();var Pxt=Ee("artifact"),RMe=/(?:^|[\s\0])NINE_REMOTE_SESSION_ID=([^\s\0]+)/,s5=new WeakMap,a5=(t,e)=>(0,IMe.execFileSync)(t,e,{encoding:"utf8",timeout:_v.PROBE_TIMEOUT_MS,stdio:["ignore","pipe","ignore"]});function Mxt(t,e){let n=a5("lsof",["-nP",`-iTCP:${t}`,"-Fpn"]),r=null;for(let i of n.split(`
1181
+ `))if(i[0]==="p")r=parseInt(i.slice(1),10);else if(i[0]==="n"&&r&&r!==e){let s=i.match(/^n(?:\[[^\]]+\]|[^:]+):(\d+)->/);if(s&&Number(s[1])===t)return r}return null}function Oxt(t){try{return process.platform==="linux"?o5.default.readFileSync(`/proc/${t}/environ`,"utf8").match(RMe)?.[1]||null:a5("ps",["-Eww","-o","command=","-p",String(t)]).match(RMe)?.[1]||null}catch{return null}}function Nxt(t){try{if(process.platform==="linux"){let e=o5.default.readFileSync(`/proc/${t}/stat`,"utf8");return parseInt(e.slice(e.lastIndexOf(")")+2).split(" ")[1],10)||null}return parseInt(a5("ps",["-o","ppid=","-p",String(t)]).trim(),10)||null}catch{return null}}function Dxt(t){for(let e=0;t>1&&t!==process.pid&&e<_v.MAX_PARENT_HOPS;e++){let n=Oxt(t);if(n)return n;if(t=Nxt(t),!t)return null}return null}function kMe(t){let e=t?.headers?.[_v.HEADER];if(e&&!/[${}]/.test(e))return e;let n=t?.socket;if(!n)return null;if(s5.has(n))return s5.get(n);let r=null;try{let i=Mxt(n.remotePort,process.pid);i&&(r=Dxt(i))}catch(i){Pxt.warn(`caller probe failed: ${i.message}`)}return s5.set(n,r),r}async function PMe(t,e){if(!Yfe(t.headers.authorization))return ut(e,401,"Unauthorized");if(!qx())return ut(e,403,"MCP is turned off in 9Remote settings");let n=await kr(t,e);if(n===null&&!e.writableEnded)return ut(e,400,"Invalid request");if(e.writableEnded)return;let r;try{r=await CMe(n,{sessionId:kMe(t)})}catch(i){r={jsonrpc:"2.0",id:n?.id??null,error:{code:-32603,message:i.message}}}if(!r)return e.writeHead(202),e.end();e.setHeader("Content-Type","application/json"),e.writeHead(200),e.end(JSON.stringify(r))}qr();oA();hu();Gr();ys();function MMe(){return{mode:ZL(),active:QL(),presets:Object.keys(Te.sleepInhibit?.presets||{})}}function OMe(t,e){De(e,MMe())}async function NMe(t,e){let n=await kr(t,e);if(!n)return;let r=Hw(n.mode);QT({sleepInhibitMode:r});let i=MMe();qn("sleepInhibit",i),De(e,i)}qr();hu();jo();ys();function DMe(t){return{enabled:t}}function LMe(t,e){De(e,DMe(G_()))}async function FMe(t,e){let n=await kr(t,e);if(!n)return;if(typeof n.enabled!="boolean")return ut(e,400,"enabled must be a boolean");QT({remoteEnabled:n.enabled}),BPe(n.enabled),Va(n.enabled?"start-tunnel":"stop-tunnel");let r=DMe(n.enabled);qn("remote",r),De(e,r)}qr();rU();async function UMe(t,e){let n=await MA();De(e,n)}async function BMe(t,e){let n=await Nte(),r=await MA();De(e,{...n,...r})}async function qMe(t,e){let n=await kr(t,e);if(!n)return;if(typeof n.text!="string"||!n.text){ut(e,400,"Missing text");return}let r=await r0(n.text);De(e,{ok:r.ok,reason:r.reason||null})}async function $Me(t,e){let n=await Ote(),r=await MA();De(e,{...n,...r})}ri();qr();async function GMe(t,e){try{let n=await zc();De(e,{sessions:n})}catch(n){ut(e,500,n.message)}}async function HMe(t,e){let n=await kr(t,e);if(n){if(!n.sessionId)return ut(e,400,"sessionId required");try{await Qd(n.sessionId),De(e)}catch(r){ut(e,500,r.message)}}}var yd=Q(require("os"),1);Gr();jA();qr();function Lxt(){let t=Sne();if(!t?.activeClients)return{total:0,streaming:0};let e=0;for(let n of t.activeClients.values())n.isStreaming&&e++;return{total:t.activeClients.size,streaming:e}}function Fxt(){let t=process.memoryUsage(),e=yd.default.cpus();return{agent:{pid:process.pid,version:"3.0.52",nodeVersion:process.version,platform:`${process.platform}/${process.arch}`,uptimeSec:Math.round(process.uptime()),memory:{heapUsedMB:Math.round(t.heapUsed/1048576*10)/10,heapTotalMB:Math.round(t.heapTotal/1048576*10)/10,rssMB:Math.round(t.rss/1048576*10)/10,externalMB:Math.round(t.external/1048576*10)/10}},os:{hostname:yd.default.hostname(),platform:yd.default.platform(),arch:yd.default.arch(),uptimeSec:Math.round(yd.default.uptime()),loadAvg:yd.default.loadavg(),cpuModel:e?.[0]?.model||"unknown",cpuCount:e.length,totalMemMB:Math.round(yd.default.totalmem()/1048576),freeMemMB:Math.round(yd.default.freemem()/1048576)},remote:{available:HA(),...Lxt(),memoryWarningThresholdMB:Te.resourceManagement.memoryWarningThreshold},timestamp:Date.now()}}function jMe(t,e){try{De(e,Fxt())}catch(n){ut(e,500,"stats error",n.message)}}oA();hu();Gr();eY();fY();var Ds=Ee("server"),Ta=(0,KMe.fileURLToPath)(new URL(".",__importMetaUrl)),YMe=process.env.NREMOTE_ENV==="development",Uxt=5173,c5=[(0,pn.join)(Ta,"dist","ui"),(0,pn.join)(Ta,"ui","dist"),(0,pn.join)(Ta,"ui")].find(t=>(0,is.existsSync)(t))||(0,pn.join)(Ta,"dist","ui"),Ml=[(0,pn.join)(Ta,"dist","web"),(0,pn.join)(Ta,"web"),(0,pn.join)(Ta,"..","web","out")].find(t=>(0,is.existsSync)(t))||c5,Bxt={".html":"text/html; charset=utf-8",".js":"application/javascript; charset=utf-8",".mjs":"application/javascript; charset=utf-8",".css":"text/css; charset=utf-8",".svg":"image/svg+xml",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp",".gif":"image/gif",".ico":"image/x-icon",".woff2":"font/woff2",".woff":"font/woff",".ttf":"font/ttf",".json":"application/json; charset=utf-8",".txt":"text/x-component; charset=utf-8",".webmanifest":"application/manifest+json"};function qxt(t,e,n){let r=(0,E1.request)({hostname:"localhost",port:Uxt,path:t.url,method:t.method,headers:t.headers},i=>{e.writeHead(i.statusCode,i.headers),i.pipe(e)});r.on("error",()=>n?n():void(e.writeHead(502),e.end("Vite dev server not ready"))),t.pipe(r)}function So(t,e,{frameable:n=!1}={}){if(!(0,is.existsSync)(e))return!1;try{if((0,is.statSync)(e).isDirectory()){let a=(0,pn.join)(e,"index.html");return(0,is.existsSync)(a)?So(t,a,{frameable:n}):!1}let i=(0,pn.extname)(e),s=Bxt[i]||"application/octet-stream";t.setHeader("Content-Type",s),i===".html"&&!n&&t.setHeader("X-Frame-Options","SAMEORIGIN");let o=e.includes(`${pn.sep}_next${pn.sep}static${pn.sep}`);return t.hasHeader("Cache-Control")||t.setHeader("Cache-Control",o?"public, max-age=31536000, immutable":"no-cache"),t.writeHead(200),t.end((0,is.readFileSync)(e)),!0}catch{return!1}}async function l5(t){try{let e=await Rc(Z1);if(!e.ok)return;let{version:n}=await e.json();if(n&&WPe(t,n)){pA({version:n}),qn("updateAvailable",{version:n}),QI();return}Ww()&&(pA(null),QI())}catch{}}var WMe=0;function $xt(t){let e=Date.now();e-WMe<Ew.connectCheckDebounceMs||(WMe=e,l5(t))}function Gxt(t,e){if(process.env.CODESPACES!=="true"){ut(e,400,"Not running on Codespaces");return}let n=process.env.CODESPACE_NAME;if(!n){ut(e,400,"Codespace name not found");return}let r=jr();r&&r.emit("codespace:stopping"),De(e,{success:!0,message:"Stopping codespace..."}),setTimeout(()=>(0,$m.execFile)("gh",["codespace","stop","-c",n],{windowsHide:!0}),500)}async function Hxt(t,e){let{parseJsonBody:n}=await Promise.resolve().then(()=>(qr(),Md)),r=await n(t,e);if(!r)return;let{verifyPresentedTail:i}=await Promise.resolve().then(()=>(jK(),wPe)),s=i({tail:r.tail,tempKey:r.tempKey});if(s.ok){De(e,{ok:!0});return}let o=t.headers["x-forwarded-for"]||t.socket?.remoteAddress||"unknown";if(r.tempKey&&r.tail)if(s.burned){Ds.warn(`wrong one-time code TAIL (${o}) \u2014 code burned, clearing from UI`);let{clearOneTimeKey:a}=await Promise.resolve().then(()=>(ys(),RF));a()}else Ds.warn(`stale one-time code TAIL (${o}) \u2014 code still live`);else r.tempKey?Ds.warn(`wrong one-time code TAIL (${o}) \u2014 no TAIL presented, code still live`):Ds.warn(`wrong API-key TAIL (${o}) \u2014 rejected`);setTimeout(()=>De(e,{ok:!1,reason:s.reason}),s.penaltyMs||0)}var jxt=[{path:"/api/health",method:"GET",public:!0,handler:(t,e)=>De(e,{status:"ok",timestamp:Date.now()})},{path:"/api/version",method:"GET",public:!0,handler:(t,e)=>{let n="3.0.52";e.setHeader("Cache-Control","no-store"),De(e,{version:n})}},{path:"/api/notify",method:"POST",public:!0,handler:mMe},{path:"/api/notify",method:"GET",public:!0,handler:gMe},{path:"/api/ui/events",method:"GET",handler:pF},{path:"/api/local-token",method:"GET",handler:lF},{path:Kl.PATH,method:"POST",handler:PMe},{path:"/api/browser-use",method:"POST",handler:c$},{path:"/api/ui/state",method:"GET",handler:fF},{path:"/api/ui/state",method:"POST",handler:hF},{path:"/api/ui/stop",method:"POST",handler:mF},{path:"/api/ui/start",method:"POST",handler:gF},{path:"/api/ui/stop-tunnel",method:"POST",handler:yF},{path:"/api/ui/shutdown",method:"POST",handler:vF},{path:"/api/update",method:"POST",handler:_F},{path:"/api/system/stats",method:"GET",handler:jMe},{path:"/api/key/one-time",method:"POST",handler:JPe},{path:"/api/key/regenerate",method:"POST",handler:ZPe},{path:"/api/signaling/retry",method:"POST",handler:QPe},{path:"/api/device/approve",method:"POST",handler:eMe},{path:"/api/device/reject",method:"POST",handler:tMe},{path:"/api/device/pending",method:"GET",handler:nMe},{path:"/api/device/approved",method:"GET",handler:rMe},{path:"/api/device/rejected",method:"GET",handler:iMe},{path:"/api/device/approve-rejected",method:"POST",handler:sMe},{path:"/api/device/clear-rejected",method:"POST",handler:oMe},{path:"/api/device/remove",method:"POST",handler:aMe},{path:"/api/device/label",method:"POST",handler:uMe},{path:"/api/device/disconnect",method:"POST",handler:cMe},{path:"/api/device/auto-approve",method:"GET",handler:lMe},{path:"/api/device/auto-approve",method:"POST",handler:dMe},{path:"/api/connections",method:"GET",handler:wF},{path:"/api/logs",method:"GET",handler:xF},{path:"/api/logs/clear",method:"POST",handler:EF},{path:"/api/permissions",method:"GET",handler:SF},{path:"/api/permissions/request",method:"POST",handler:CF},{path:"/api/desktop/toggle",method:"POST",handler:bF},{path:"/api/ui/rtc-toggle",method:"POST",handler:uF},{path:"/api/autostart",method:"GET",handler:TF},{path:"/api/autostart",method:"POST",handler:AF},{path:"/api/sleep-inhibit",method:"GET",handler:OMe},{path:"/api/sleep-inhibit",method:"POST",handler:NMe},{path:"/api/remote/enabled",method:"GET",handler:LMe},{path:"/api/remote/enabled",method:"POST",handler:FMe},{path:"/api/desktop-unlock",method:"GET",handler:UMe},{path:"/api/desktop-unlock/install",method:"POST",handler:BMe},{path:"/api/desktop-unlock/uninstall",method:"POST",handler:$Me},{path:"/api/desktop-unlock/type",method:"POST",handler:qMe},{path:"/api/sessions",method:"GET",handler:GMe},{path:"/api/sessions/delete",method:"POST",handler:HMe},{path:"/api/codespace/stop",method:"POST",handler:Gxt},{path:"/api/verify-key",method:"POST",public:!0,handler:Hxt}];var zMe=parseInt(process.env.PORT||"2208",10),nS=null;function Wxt(t){if(process.platform!=="win32")try{let e=(0,$m.execSync)(`pgrep -f "vite --config ${t}"`,{encoding:"utf8"}).trim();for(let n of e.split(`
1182
+ `).filter(Boolean))if((0,$m.execSync)(`ps -o ppid= -p ${n}`,{encoding:"utf8"}).trim()==="1")try{process.kill(Number(n))}catch{}}catch{}}function zxt(){if(!YMe)return;let t=(0,pn.join)(Ta,"vite.config.js");if(!(0,is.existsSync)(t))return;Wxt(t);let e=(0,is.existsSync)((0,pn.join)(Ta,"node_modules",".bin","vite"))?(0,pn.join)(Ta,"node_modules",".bin","vite"):(0,pn.join)(Ta,"..","node_modules",".bin","vite");nS=(0,$m.spawn)("node",[e,"--config",t],{cwd:Ta,stdio:"ignore",detached:!1}),nS.on("error",()=>{}),nS.unref()}async function XMe(){let t=sh(),e=t.sleepInhibitMode;e||(t.sleepInhibit===!1?e="none":e=Te.sleepInhibit?.defaultMode||"never"),Hw(e),await RG(),zxt();let r=tN(jxt,{fallback:(l,u,{pathname:d})=>{if(d.startsWith("/api/")||d.startsWith("/socket.io")){ut(u,404,"Not found");return}if(d==="/"||d==="/ui"){u.writeHead(302,{Location:"/workspace"}),u.end();return}let p=d.replace(/^\//,"");if(p.split(/[\\/]/).includes("..")){ut(u,400,"Bad request");return}if((0,is.existsSync)(Ml)&&p)try{let y=(0,pn.join)(Ml,p);if((0,is.existsSync)(y)&&!(0,is.statSync)(y).isDirectory()&&So(u,y))return}catch{}if((d==="/workspace"||d.startsWith("/workspace/")||d.startsWith("/_next/")||d==="/login"||d.startsWith("/login/"))&&(0,is.existsSync)(Ml)){let y=(0,pn.join)(Ml,p);if(So(u,y)||So(u,`${y}.html`)||So(u,(0,pn.join)(y,"index.html"))||(l.headers.rsc==="1"||p.endsWith(".txt"))&&(p.startsWith("workspace/terminal/")&&So(u,(0,pn.join)(Ml,"workspace","terminal","default.txt"))||So(u,(0,pn.join)(Ml,"workspace.txt")))||d.startsWith("/workspace")&&(So(u,(0,pn.join)(Ml,"workspace.html"))||So(u,(0,pn.join)(Ml,"workspace","index.html")))||d.startsWith("/login")&&(So(u,(0,pn.join)(Ml,"login.html"))||So(u,(0,pn.join)(Ml,"login","index.html"))))return;ut(u,404,"Not found");return}let h=()=>{let y=p==="ui"||p===""?"index.html":p.replace(/^ui\/?/,""),v=(0,pn.join)(c5,y);So(u,v)||So(u,(0,pn.join)(c5,"index.html"))||ut(u,404,"Not found")};if(YMe){qxt(l,u,h);return}h()}}),i=(0,E1.createServer)(async(l,u)=>{await r(l,u)});sL(),nF(),rF();let s=Go()?.key;s&&Ho({permanentKey:s});let o=()=>fA().catch(l=>Ds.error(`permission refresh failed: ${l?.message||l}`));o(),process.platform==="darwin"&&setInterval(o,tY),mce(i,zMe),await qPe(i),i.on("error",l=>{Ds.error(`HTTP server error: ${l?.message||l}`),l?.code==="EADDRINUSE"&&process.exit(1)}),i.listen(zMe,l=>{if(l)throw l;let u="3.0.52";l5(u),setInterval(()=>l5(u),Ew.checkIntervalMs),IG(()=>$xt(u))});let a=!1,c=async l=>{if(a)return;a=!0,JL(),Ds.info(`\u{1F6D1} Received ${l}, shutting down gracefully...`);let u=setTimeout(()=>{Ds.error("\u26A0\uFE0F Forced exit"),process.exit(1)},5e3);try{if(i.close(()=>Ds.info("\u2713 HTTP server closed")),nS)try{nS.kill()}catch{}let d=jr();if(d&&(d.emit("server:shutdown"),d.close(()=>Ds.info("\u2713 Socket.IO closed"))),process.env.NREMOTE_ENV!=="development")try{await Ole()}catch{}await new Promise(p=>setTimeout(p,500)),clearTimeout(u),Ds.info("\u2705 Server stopped cleanly"),process.exit(0)}catch(d){Ds.error(`\u274C Error during shutdown: ${d?.message||d}`),clearTimeout(u),process.exit(1)}};return process.on("SIGINT",()=>c("SIGINT")),process.on("SIGTERM",()=>c("SIGTERM")),process.platform==="win32"&&process.on("SIGBREAK",()=>c("SIGBREAK")),i}var VMe=process.argv.slice(2).filter(t=>!t.startsWith("--"));VMe.length&&(Ds.error(`host/index.js takes no commands (got: ${VMe.join(" ")}) \u2014 use \`9remote <command>\``),process.exit(1));XMe().catch(t=>{Ds.error(`Server failed to start: ${t?.stack||t?.message||t}`),process.exit(1)});0&&(module.exports={startServer});
1183
1183
  /*! Bundled license information:
1184
1184
 
1185
1185
  negotiator/index.js: