@wendongfly/zihi 1.0.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/admin.html CHANGED
@@ -3,7 +3,7 @@
3
3
  <head>
4
4
  <meta charset="UTF-8">
5
5
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
- <title>weHi 管理</title>
6
+ <title>ZiHi 管理</title>
7
7
  <style>
8
8
  * { margin: 0; padding: 0; box-sizing: border-box; }
9
9
  body { font-family: -apple-system, system-ui, sans-serif; background: #0d1117; color: #e6edf3; min-height: 100vh; }
@@ -51,7 +51,7 @@
51
51
 
52
52
  <div class="login-wrap" id="pg-login">
53
53
  <div class="login-box">
54
- <h2>weHi 管理</h2>
54
+ <h2>ZiHi 管理</h2>
55
55
  <div class="err" id="login-err"></div>
56
56
  <input type="password" id="admin-pwd" placeholder="输入管理密码" autofocus>
57
57
  <button onclick="doLogin()">登录</button>
@@ -60,7 +60,7 @@
60
60
 
61
61
  <div class="wrap" id="pg-admin" style="display:none">
62
62
  <div class="header">
63
- <h1>weHi 管理</h1>
63
+ <h1>ZiHi 管理</h1>
64
64
  <button class="logout" onclick="doLogout()">退出</button>
65
65
  </div>
66
66
 
package/dist/chat.html CHANGED
@@ -8,7 +8,7 @@
8
8
  <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
9
9
  <link rel="manifest" href="/manifest.json">
10
10
  <link rel="apple-touch-icon" href="/icon.png">
11
- <title>weHi 会话</title>
11
+ <title>ZiHi 会话</title>
12
12
  <script src="/socket.io/socket.io.js"></script>
13
13
  <style>
14
14
  * { box-sizing: border-box; margin: 0; padding: 0; }
@@ -244,7 +244,6 @@
244
244
  <div id="session-cwd"></div>
245
245
  </div>
246
246
  <button class="top-btn" onclick="openFiles()" title="文件" style="font-size:0.7rem;color:var(--muted)">文件</button>
247
- <button class="top-btn" id="sync-btn" onclick="openSync()" title="同步" style="display:none;font-size:0.7rem;color:var(--muted)">同步</button>
248
247
  <button class="top-btn" onclick="showUsage()" title="用量" style="font-size:0.7rem;color:var(--muted)">用量</button>
249
248
  <button class="top-btn" onclick="openSettings()" title="设置">
250
249
  <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 00.33 1.82l.06.06a2 2 0 01-2.83 2.83l-.06-.06a1.65 1.65 0 00-1.82-.33 1.65 1.65 0 00-1 1.51V21a2 2 0 01-4 0v-.09A1.65 1.65 0 009 19.4a1.65 1.65 0 00-1.82.33l-.06.06a2 2 0 01-2.83-2.83l.06-.06A1.65 1.65 0 004.68 15a1.65 1.65 0 00-1.51-1H3a2 2 0 010-4h.09A1.65 1.65 0 004.6 9a1.65 1.65 0 00-.33-1.82l-.06-.06a2 2 0 012.83-2.83l.06.06A1.65 1.65 0 009 4.68a1.65 1.65 0 001-1.51V3a2 2 0 014 0v.09a1.65 1.65 0 001 1.51 1.65 1.65 0 001.82-.33l.06-.06a2 2 0 012.83 2.83l-.06.06A1.65 1.65 0 0019.4 9a1.65 1.65 0 001.51 1H21a2 2 0 010 4h-.09a1.65 1.65 0 00-1.51 1z"/></svg>
@@ -293,7 +292,6 @@
293
292
 
294
293
  <div id="shortcut-bar" style="display:none">
295
294
  <div id="sk-claude-agent">
296
- <button class="sk sk-claude" onclick="openModelSheet()">模型</button>
297
295
  <button class="sk sk-claude" onclick="doSlashCmd('/plan')">计划</button>
298
296
  <button class="sk sk-claude" onclick="doSlashCmd('/compact')">压缩</button>
299
297
  <button class="sk sk-claude" onclick="openResumeSheet()">恢复</button>
@@ -439,7 +437,7 @@
439
437
  } catch (e) {
440
438
  // AnsiUp 加载失败时用简单的 fallback
441
439
  console.error('[zihi] AnsiUp 加载失败:', e);
442
- ansi = { ansi_to_html: (t) => t.replace(/</g, '&lt;'), use_classes: false };
440
+ ansi = { ansi_to_html: (t) => t.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&#39;'), use_classes: false };
443
441
  }
444
442
 
445
443
  // ── Service Worker 注册 ──
@@ -1364,7 +1362,7 @@
1364
1362
  overlay.classList.add('hidden');
1365
1363
  // 请求通知权限(不阻塞)
1366
1364
  try { requestNotifyPermission(); } catch {}
1367
- document.title = session.title + ' — weHi';
1365
+ document.title = session.title + ' — ZiHi';
1368
1366
  document.getElementById('session-title').textContent = session.title;
1369
1367
  if (session.cwd) document.getElementById('session-cwd').textContent = session.cwd;
1370
1368
  updateViewers(session.viewers);
@@ -1724,11 +1722,6 @@
1724
1722
  function updateViewers(count) { document.getElementById('viewer-count').textContent = count > 1 ? `${count} 人在线` : ''; }
1725
1723
  window.goBack = function() { window.location.href = '/'; };
1726
1724
  window.openFiles = function() { window.open('/files?session=' + SESSION_ID, '_blank'); };
1727
- window.openSync = function() { window.open('/sync?session=' + SESSION_ID, '_blank'); };
1728
- // 仅桌面浏览器显示同步按钮
1729
- if ('showDirectoryPicker' in window) {
1730
- document.getElementById('sync-btn').style.display = '';
1731
- }
1732
1725
  function scrollToBottom() { requestAnimationFrame(() => { chatArea.scrollTop = chatArea.scrollHeight; }); }
1733
1726
  function trimMessages() {
1734
1727
  const msgs = chatArea.querySelectorAll('.msg');
@@ -1909,7 +1902,7 @@
1909
1902
  socket.on('session-renamed', ({ sessionId, title }) => {
1910
1903
  if (sessionId !== SESSION_ID) return;
1911
1904
  document.getElementById('session-title').textContent = title;
1912
- document.title = title + ' — weHi';
1905
+ document.title = title + ' — ZiHi';
1913
1906
  addStatusMessage('会话已命名为: ' + title);
1914
1907
  });
1915
1908
 
package/dist/files.html CHANGED
@@ -6,8 +6,8 @@
6
6
  <meta name="theme-color" content="#0d1117">
7
7
  <meta name="apple-mobile-web-app-capable" content="yes">
8
8
  <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
9
- <meta name="apple-mobile-web-app-title" content="weHi Files">
10
- <title>weHi - Files</title>
9
+ <meta name="apple-mobile-web-app-title" content="ZiHi Files">
10
+ <title>ZiHi - Files</title>
11
11
  <style>
12
12
  :root {
13
13
  --bg: #0d1117;
@@ -257,7 +257,6 @@
257
257
  </div>
258
258
  <div class="header-right">
259
259
  <span id="user-name" style="font-size:0.8rem;color:var(--muted)"></span>
260
- <a id="sync-btn" class="hdr-btn" style="display:none;text-decoration:none">同步</a>
261
260
  <button class="hdr-btn" id="hidden-toggle" onclick="toggleHidden()">.*</button>
262
261
  <button class="hdr-btn" onclick="doLogout()">退出</button>
263
262
  </div>
@@ -341,13 +340,6 @@ const SESSION_ID = new URLSearchParams(location.search).get('session') || '';
341
340
 
342
341
  // ── Init ──
343
342
  (async function init() {
344
- if ('showDirectoryPicker' in window) {
345
- const syncBtn = document.getElementById('sync-btn');
346
- if (syncBtn) {
347
- syncBtn.style.display = '';
348
- syncBtn.href = '/sync' + (SESSION_ID ? '?session=' + SESSION_ID : '');
349
- }
350
- }
351
343
  try {
352
344
  const me = await fetch('/api/me').then(r => r.json());
353
345
  document.getElementById('user-name').textContent = me.name || '';
@@ -393,7 +385,7 @@ async function loadDir(path) {
393
385
  const res = await api('/api/files/list?' + params);
394
386
  if (!res) return;
395
387
  const data = await res.json();
396
- if (data.error) { list.innerHTML = `<div class="empty-state"><p>${data.error}</p></div>`; return; }
388
+ if (data.error) { list.innerHTML = `<div class="empty-state"><p>${esc(data.error)}</p></div>`; return; }
397
389
 
398
390
  currentPath = data.current;
399
391
  rootPath = data.root;
@@ -402,7 +394,7 @@ async function loadDir(path) {
402
394
  renderFiles(data.entries);
403
395
  document.getElementById('file-count').textContent = `${data.entries.length} 项`;
404
396
  } catch (e) {
405
- list.innerHTML = `<div class="empty-state"><p>加载失败: ${e.message}</p></div>`;
397
+ list.innerHTML = `<div class="empty-state"><p>加载失败: ${esc(e.message)}</p></div>`;
406
398
  } finally {
407
399
  loading.classList.remove('show');
408
400
  }
package/dist/index.html CHANGED
@@ -6,10 +6,10 @@
6
6
  <meta name="theme-color" content="#0d1117">
7
7
  <meta name="apple-mobile-web-app-capable" content="yes">
8
8
  <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
9
- <meta name="apple-mobile-web-app-title" content="weHi">
9
+ <meta name="apple-mobile-web-app-title" content="ZiHi">
10
10
  <link rel="manifest" href="/manifest.json">
11
11
  <link rel="apple-touch-icon" href="/icon.png">
12
- <title>weHi</title>
12
+ <title>ZiHi</title>
13
13
  <script src="/socket.io/socket.io.js"></script>
14
14
  <style>
15
15
  :root {
@@ -451,12 +451,9 @@
451
451
 
452
452
  <div class="field">
453
453
  <label>名称</label>
454
- <input id="inp-title" type="text" placeholder="自定义名称…" autocomplete="off" spellcheck="false">
455
- </div>
456
- <div class="field">
457
- <label>启动命令 <span style="font-weight:400;text-transform:none">(可选)</span></label>
458
- <input id="inp-cmd" type="text" placeholder="留空仅打开 shell" autocomplete="off" spellcheck="false" style="font-family:'SF Mono',Consolas,monospace;font-size:0.85rem">
454
+ <input id="inp-title" type="text" placeholder="请输入任务名称,方便后续查看" autocomplete="off" spellcheck="false">
459
455
  </div>
456
+ <input id="inp-cmd" type="hidden">
460
457
  <div class="field">
461
458
  <label>工作目录 <span style="font-weight:400;text-transform:none">(可选)</span></label>
462
459
  <div style="display:flex;gap:0.5rem">
@@ -466,7 +463,7 @@
466
463
  <div id="recent-dirs" style="display:flex;flex-wrap:wrap;gap:0.35rem;margin-top:0.4rem"></div>
467
464
  </div>
468
465
  <button id="btn-create" onclick="createSession()">创建</button>
469
- <button id="btn-import" onclick="openImportSheet()" style="width:100%;background:var(--bg);color:var(--accent);border:1.5px solid var(--accent);border-radius:10px;padding:0.7rem;font-size:0.85rem;font-weight:600;cursor:pointer;margin-top:0.5rem">导入已有 Claude 会话</button>
466
+ <button id="btn-import" onclick="openImportSheet()" style="width:100%;background:var(--bg);color:var(--accent);border:1.5px solid var(--accent);border-radius:10px;padding:0.7rem;font-size:0.85rem;font-weight:600;cursor:pointer;margin-top:0.5rem">导入历史任务</button>
470
467
  </div>
471
468
 
472
469
  <!-- Dir picker -->
@@ -500,7 +497,7 @@
500
497
  <div id="import-backdrop" onclick="closeImportSheet()" style="position:absolute;inset:0;background:rgba(0,0,0,0.55)"></div>
501
498
  <div id="import-box" style="position:relative;background:var(--surface);border-radius:20px 20px 0 0;width:100%;max-width:640px;padding:0 1.25rem;padding-bottom:max(1.5rem,env(safe-area-inset-bottom));max-height:70vh;display:flex;flex-direction:column;z-index:1">
502
499
  <div class="sheet-handle"></div>
503
- <div class="sheet-title">导入已有 Claude 会话</div>
500
+ <div class="sheet-title">导入历史任务</div>
504
501
  <div id="import-list" style="flex:1;overflow-y:auto;padding:0.4rem 0;-webkit-overflow-scrolling:touch"></div>
505
502
  <div style="padding:0.75rem 0;border-top:1px solid var(--border)">
506
503
  <button class="dir-btn cancel" onclick="closeImportSheet()" style="width:100%">取消</button>
@@ -720,7 +717,7 @@
720
717
  document.querySelectorAll('.chip').forEach((c, j) =>
721
718
  c.classList.toggle('selected', j === i));
722
719
  const p = PRESETS[i];
723
- document.getElementById('inp-title').value = p.title;
720
+ document.getElementById('inp-title').value = '';
724
721
  document.getElementById('inp-cmd').value = p.cmd || '';
725
722
  }
726
723
 
@@ -744,7 +741,7 @@
744
741
  });
745
742
 
746
743
  function createSession() {
747
- const title = document.getElementById('inp-title').value.trim() || 'shell';
744
+ const title = document.getElementById('inp-title').value.trim() || '新任务';
748
745
  const initCmd = document.getElementById('inp-cmd').value.trim() || undefined;
749
746
  const cwd = document.getElementById('inp-cwd').value.trim() || undefined;
750
747
  if (cwd) recordDir(cwd);
@@ -910,7 +907,7 @@
910
907
  .then(sessions => {
911
908
  const el = document.getElementById('import-list');
912
909
  if (!sessions.length) {
913
- el.innerHTML = '<div style="padding:1rem;color:var(--muted);font-size:0.85rem">未找到本地 Claude 会话<br><span style="font-size:0.72rem">会话数据存储在 ~/.claude/projects/ 目录</span></div>';
910
+ el.innerHTML = '<div style="padding:1rem;color:var(--muted);font-size:0.85rem">未找到历史任务<br><span style="font-size:0.72rem">会话数据存储在 ~/.claude/projects/ 目录</span></div>';
914
911
  return;
915
912
  }
916
913
  el.innerHTML = '';
@@ -941,11 +938,9 @@
941
938
 
942
939
  function importSession(session) {
943
940
  closeImportSheet();
944
- const cwd = session.projectPath || document.getElementById('inp-cwd').value.trim() || undefined;
945
- const title = session.summary ? session.summary.slice(0, 30) : 'claude (导入)';
941
+ const title = session.summary ? session.summary.slice(0, 30) : '导入任务';
946
942
  socket.emit('create-agent', {
947
943
  title,
948
- cwd,
949
944
  resumeSessionId: session.sessionId,
950
945
  }, (res) => {
951
946
  if (res?.ok) openSession(res.session.id);
package/dist/index.js CHANGED
@@ -222,10 +222,10 @@ return fn.apply(this, arguments)
222
222
  object-assign
223
223
  (c) Sindre Sorhus
224
224
  @license MIT
225
- */var t=Object.getOwnPropertySymbols,u=Object.prototype.hasOwnProperty,d=Object.prototype.propertyIsEnumerable;function p(x){if(x==null)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(x)}function h(){try{if(!Object.assign)return!1;var x=new String("abc");if(x[5]="de",Object.getOwnPropertyNames(x)[0]==="5")return!1;for(var j={},b=0;b<10;b++)j["_"+String.fromCharCode(b)]=b;var w=Object.getOwnPropertyNames(j).map((function(O){return j[O]}));if(w.join("")!=="0123456789")return!1;var $={};return"abcdefghijklmnopqrst".split("").forEach((function(O){$[O]=O})),Object.keys(Object.assign({},$)).join("")==="abcdefghijklmnopqrst"}catch{return!1}}r.exports=h()?Object.assign:function(x,j){for(var b,w=p(x),$,O=1;O<arguments.length;O++){b=Object(arguments[O]);for(var I in b)u.call(b,I)&&(w[I]=b[I]);if(t){$=t(b);for(var U=0;U<$.length;U++)d.call(b,$[U])&&(w[$[U]]=b[$[U]])}}return w}},506:(r,t,u)=>{var d=typeof Map=="function"&&Map.prototype,p=Object.getOwnPropertyDescriptor&&d?Object.getOwnPropertyDescriptor(Map.prototype,"size"):null,h=d&&p&&typeof p.get=="function"?p.get:null,x=d&&Map.prototype.forEach,j=typeof Set=="function"&&Set.prototype,b=Object.getOwnPropertyDescriptor&&j?Object.getOwnPropertyDescriptor(Set.prototype,"size"):null,w=j&&b&&typeof b.get=="function"?b.get:null,$=j&&Set.prototype.forEach,O=typeof WeakMap=="function"&&WeakMap.prototype,I=O?WeakMap.prototype.has:null,U=typeof WeakSet=="function"&&WeakSet.prototype,z=U?WeakSet.prototype.has:null,N=typeof WeakRef=="function"&&WeakRef.prototype,B=N?WeakRef.prototype.deref:null,L=Boolean.prototype.valueOf,W=Object.prototype.toString,H=Function.prototype.toString,V=String.prototype.match,J=String.prototype.slice,G=String.prototype.replace,X=String.prototype.toUpperCase,K=String.prototype.toLowerCase,Y=RegExp.prototype.test,ee=Array.prototype.concat,Q=Array.prototype.join,ie=Array.prototype.slice,ae=Math.floor,ne=typeof BigInt=="function"?BigInt.prototype.valueOf:null,te=Object.getOwnPropertySymbols,oe=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?Symbol.prototype.toString:null,de=typeof Symbol=="function"&&typeof Symbol.iterator=="object",ke=typeof Symbol=="function"&&Symbol.toStringTag&&(typeof Symbol.toStringTag===de||!0)?Symbol.toStringTag:null,xe=Object.prototype.propertyIsEnumerable,_e=(typeof Reflect=="function"?Reflect.getPrototypeOf:Object.getPrototypeOf)||([].__proto__===Array.prototype?function(Te){return Te.__proto__}:null);function se(Te,Pe){if(Te===1/0||Te===-1/0||Te!==Te||Te&&Te>-1e3&&Te<1e3||Y.call(/e/,Pe))return Pe;var Le=/[0-9](?=(?:[0-9]{3})+(?![0-9]))/g;if(typeof Te=="number"){var He=Te<0?-ae(-Te):ae(Te);if(He!==Te){var Ze=String(He),Ue=J.call(Pe,Ze.length+1);return G.call(Ze,Le,"$&_")+"."+G.call(G.call(Ue,/([0-9]{3})/g,"$&_"),/_$/,"")}}return G.call(Pe,Le,"$&_")}var ye=u(8502),fe=ye.custom,re=$e(fe)?fe:null,ce={__proto__:null,double:'"',single:"'"},he={__proto__:null,double:/(["\\])/g,single:/(['\\])/g};r.exports=function Te(Pe,Le,He,Ze){var Ue=Le||{};if(we(Ue,"quoteStyle")&&!we(ce,Ue.quoteStyle))throw new TypeError('option "quoteStyle" must be "single" or "double"');if(we(Ue,"maxStringLength")&&(typeof Ue.maxStringLength=="number"?Ue.maxStringLength<0&&Ue.maxStringLength!==1/0:Ue.maxStringLength!==null))throw new TypeError('option "maxStringLength", if provided, must be a positive integer, Infinity, or `null`');var Ye=we(Ue,"customInspect")?Ue.customInspect:!0;if(typeof Ye!="boolean"&&Ye!=="symbol")throw new TypeError("option \"customInspect\", if provided, must be `true`, `false`, or `'symbol'`");if(we(Ue,"indent")&&Ue.indent!==null&&Ue.indent!==" "&&!(parseInt(Ue.indent,10)===Ue.indent&&Ue.indent>0))throw new TypeError('option "indent" must be "\\t", an integer > 0, or `null`');if(we(Ue,"numericSeparator")&&typeof Ue.numericSeparator!="boolean")throw new TypeError('option "numericSeparator", if provided, must be `true` or `false`');var ti=Ue.numericSeparator;if(typeof Pe>"u")return"undefined";if(Pe===null)return"null";if(typeof Pe=="boolean")return Pe?"true":"false";if(typeof Pe=="string")return Me(Pe,Ue);if(typeof Pe=="number"){if(Pe===0)return 1/0/Pe>0?"0":"-0";var Xe=String(Pe);return ti?se(Pe,Xe):Xe}if(typeof Pe=="bigint"){var ni=String(Pe)+"n";return ti?se(Pe,ni):ni}var ui=typeof Ue.depth>"u"?5:Ue.depth;if(typeof He>"u"&&(He=0),He>=ui&&ui>0&&typeof Pe=="object")return ge(Pe)?"[Array]":"[Object]";var ri=Ke(Ue,He);if(typeof Ze>"u")Ze=[];else if(Ne(Ze,Pe)>=0)return"[Circular]";function Qe(si,li,Ei){if(li&&(Ze=ie.call(Ze),Ze.push(li)),Ei){var Si={depth:Ue.depth};return we(Ue,"quoteStyle")&&(Si.quoteStyle=Ue.quoteStyle),Te(si,Si,He+1,Ze)}return Te(si,Ue,He+1,Ze)}if(typeof Pe=="function"&&!pe(Pe)){var gi=Oe(Pe),xi=ii(Pe,Qe);return"[Function"+(gi?": "+gi:" (anonymous)")+"]"+(xi.length>0?" { "+Q.call(xi,", ")+" }":"")}if($e(Pe)){var bi=de?G.call(String(Pe),/^(Symbol\(.*\))_[^)]*$/,"$1"):oe.call(Pe);return typeof Pe=="object"&&!de?Je(bi):bi}if(Ge(Pe)){for(var oi="<"+K.call(String(Pe.nodeName)),pi=Pe.attributes||[],ci=0;ci<pi.length;ci++)oi+=" "+pi[ci].name+"="+ve(je(pi[ci].value),"double",Ue);return oi+=">",Pe.childNodes&&Pe.childNodes.length&&(oi+="..."),oi+="</"+K.call(String(Pe.nodeName))+">",oi}if(ge(Pe)){if(Pe.length===0)return"[]";var di=ii(Pe,Qe);return ri&&!Be(di)?"["+ei(di,ri)+"]":"[ "+Q.call(di,", ")+" ]"}if(me(Pe)){var fi=ii(Pe,Qe);return!("cause"in Error.prototype)&&"cause"in Pe&&!xe.call(Pe,"cause")?"{ ["+String(Pe)+"] "+Q.call(ee.call("[cause]: "+Qe(Pe.cause),fi),", ")+" }":fi.length===0?"["+String(Pe)+"]":"{ ["+String(Pe)+"] "+Q.call(fi,", ")+" }"}if(typeof Pe=="object"&&Ye){if(re&&typeof Pe[re]=="function"&&ye)return ye(Pe,{depth:ui-He});if(Ye!=="symbol"&&typeof Pe.inspect=="function")return Pe.inspect()}if(Ae(Pe)){var yi=[];return x&&x.call(Pe,(function(si,li){yi.push(Qe(li,Pe,!0)+" => "+Qe(si,Pe))})),We("Map",h.call(Pe),yi,ri)}if(ze(Pe)){var _i=[];return $&&$.call(Pe,(function(si){_i.push(Qe(si,Pe))})),We("Set",w.call(Pe),_i,ri)}if(qe(Pe))return ai("WeakMap");if(Fe(Pe))return ai("WeakSet");if(De(Pe))return ai("WeakRef");if(le(Pe))return Je(Qe(Number(Pe)));if(Ie(Pe))return Je(Qe(ne.call(Pe)));if(ue(Pe))return Je(L.call(Pe));if(Se(Pe))return Je(Qe(String(Pe)));if(typeof window<"u"&&Pe===window)return"{ [object Window] }";if(typeof globalThis<"u"&&Pe===globalThis||typeof global<"u"&&Pe===global)return"{ [object globalThis] }";if(!be(Pe)&&!pe(Pe)){var mi=ii(Pe,Qe),wi=_e?_e(Pe)===Object.prototype:Pe instanceof Object||Pe.constructor===Object,hi=Pe instanceof Object?"":"null prototype",ki=!wi&&ke&&Object(Pe)===Pe&&ke in Pe?J.call(Ee(Pe),8,-1):hi?"Object":"",$i=wi||typeof Pe.constructor!="function"?"":Pe.constructor.name?Pe.constructor.name+" ":"",vi=$i+(ki||hi?"["+Q.call(ee.call([],ki||[],hi||[]),": ")+"] ":"");return mi.length===0?vi+"{}":ri?vi+"{"+ei(mi,ri)+"}":vi+"{ "+Q.call(mi,", ")+" }"}return String(Pe)};function ve(Te,Pe,Le){var He=Le.quoteStyle||Pe,Ze=ce[He];return Ze+Te+Ze}function je(Te){return G.call(String(Te),/"/g,"&quot;")}function Ce(Te){return!ke||!(typeof Te=="object"&&(ke in Te||typeof Te[ke]<"u"))}function ge(Te){return Ee(Te)==="[object Array]"&&Ce(Te)}function be(Te){return Ee(Te)==="[object Date]"&&Ce(Te)}function pe(Te){return Ee(Te)==="[object RegExp]"&&Ce(Te)}function me(Te){return Ee(Te)==="[object Error]"&&Ce(Te)}function Se(Te){return Ee(Te)==="[object String]"&&Ce(Te)}function le(Te){return Ee(Te)==="[object Number]"&&Ce(Te)}function ue(Te){return Ee(Te)==="[object Boolean]"&&Ce(Te)}function $e(Te){if(de)return Te&&typeof Te=="object"&&Te instanceof Symbol;if(typeof Te=="symbol")return!0;if(!Te||typeof Te!="object"||!oe)return!1;try{return oe.call(Te),!0}catch{}return!1}function Ie(Te){if(!Te||typeof Te!="object"||!ne)return!1;try{return ne.call(Te),!0}catch{}return!1}var Re=Object.prototype.hasOwnProperty||function(Te){return Te in this};function we(Te,Pe){return Re.call(Te,Pe)}function Ee(Te){return W.call(Te)}function Oe(Te){if(Te.name)return Te.name;var Pe=V.call(H.call(Te),/^function\s*([\w$]+)/);return Pe?Pe[1]:null}function Ne(Te,Pe){if(Te.indexOf)return Te.indexOf(Pe);for(var Le=0,He=Te.length;Le<He;Le++)if(Te[Le]===Pe)return Le;return-1}function Ae(Te){if(!h||!Te||typeof Te!="object")return!1;try{h.call(Te);try{w.call(Te)}catch{return!0}return Te instanceof Map}catch{}return!1}function qe(Te){if(!I||!Te||typeof Te!="object")return!1;try{I.call(Te,I);try{z.call(Te,z)}catch{return!0}return Te instanceof WeakMap}catch{}return!1}function De(Te){if(!B||!Te||typeof Te!="object")return!1;try{return B.call(Te),!0}catch{}return!1}function ze(Te){if(!w||!Te||typeof Te!="object")return!1;try{w.call(Te);try{h.call(Te)}catch{return!0}return Te instanceof Set}catch{}return!1}function Fe(Te){if(!z||!Te||typeof Te!="object")return!1;try{z.call(Te,z);try{I.call(Te,I)}catch{return!0}return Te instanceof WeakSet}catch{}return!1}function Ge(Te){return!Te||typeof Te!="object"?!1:typeof HTMLElement<"u"&&Te instanceof HTMLElement?!0:typeof Te.nodeName=="string"&&typeof Te.getAttribute=="function"}function Me(Te,Pe){if(Te.length>Pe.maxStringLength){var Le=Te.length-Pe.maxStringLength,He="... "+Le+" more character"+(Le>1?"s":"");return Me(J.call(Te,0,Pe.maxStringLength),Pe)+He}var Ze=he[Pe.quoteStyle||"single"];Ze.lastIndex=0;var Ue=G.call(G.call(Te,Ze,"\\$1"),/[\x00-\x1f]/g,Ve);return ve(Ue,"single",Pe)}function Ve(Te){var Pe=Te.charCodeAt(0),Le={8:"b",9:"t",10:"n",12:"f",13:"r"}[Pe];return Le?"\\"+Le:"\\x"+(Pe<16?"0":"")+X.call(Pe.toString(16))}function Je(Te){return"Object("+Te+")"}function ai(Te){return Te+" { ? }"}function We(Te,Pe,Le,He){var Ze=He?ei(Le,He):Q.call(Le,", ");return Te+" ("+Pe+") {"+Ze+"}"}function Be(Te){for(var Pe=0;Pe<Te.length;Pe++)if(Ne(Te[Pe],`
225
+ */var t=Object.getOwnPropertySymbols,u=Object.prototype.hasOwnProperty,d=Object.prototype.propertyIsEnumerable;function p(x){if(x==null)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(x)}function h(){try{if(!Object.assign)return!1;var x=new String("abc");if(x[5]="de",Object.getOwnPropertyNames(x)[0]==="5")return!1;for(var j={},b=0;b<10;b++)j["_"+String.fromCharCode(b)]=b;var w=Object.getOwnPropertyNames(j).map((function(O){return j[O]}));if(w.join("")!=="0123456789")return!1;var $={};return"abcdefghijklmnopqrst".split("").forEach((function(O){$[O]=O})),Object.keys(Object.assign({},$)).join("")==="abcdefghijklmnopqrst"}catch{return!1}}r.exports=h()?Object.assign:function(x,j){for(var b,w=p(x),$,O=1;O<arguments.length;O++){b=Object(arguments[O]);for(var I in b)u.call(b,I)&&(w[I]=b[I]);if(t){$=t(b);for(var U=0;U<$.length;U++)d.call(b,$[U])&&(w[$[U]]=b[$[U]])}}return w}},506:(r,t,u)=>{var d=typeof Map=="function"&&Map.prototype,p=Object.getOwnPropertyDescriptor&&d?Object.getOwnPropertyDescriptor(Map.prototype,"size"):null,h=d&&p&&typeof p.get=="function"?p.get:null,x=d&&Map.prototype.forEach,j=typeof Set=="function"&&Set.prototype,b=Object.getOwnPropertyDescriptor&&j?Object.getOwnPropertyDescriptor(Set.prototype,"size"):null,w=j&&b&&typeof b.get=="function"?b.get:null,$=j&&Set.prototype.forEach,O=typeof WeakMap=="function"&&WeakMap.prototype,I=O?WeakMap.prototype.has:null,U=typeof WeakSet=="function"&&WeakSet.prototype,z=U?WeakSet.prototype.has:null,N=typeof WeakRef=="function"&&WeakRef.prototype,B=N?WeakRef.prototype.deref:null,L=Boolean.prototype.valueOf,W=Object.prototype.toString,H=Function.prototype.toString,V=String.prototype.match,J=String.prototype.slice,G=String.prototype.replace,X=String.prototype.toUpperCase,K=String.prototype.toLowerCase,Y=RegExp.prototype.test,ee=Array.prototype.concat,Q=Array.prototype.join,ie=Array.prototype.slice,ae=Math.floor,ne=typeof BigInt=="function"?BigInt.prototype.valueOf:null,te=Object.getOwnPropertySymbols,oe=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?Symbol.prototype.toString:null,de=typeof Symbol=="function"&&typeof Symbol.iterator=="object",ke=typeof Symbol=="function"&&Symbol.toStringTag&&(typeof Symbol.toStringTag===de||!0)?Symbol.toStringTag:null,xe=Object.prototype.propertyIsEnumerable,_e=(typeof Reflect=="function"?Reflect.getPrototypeOf:Object.getPrototypeOf)||([].__proto__===Array.prototype?function(Te){return Te.__proto__}:null);function se(Te,Pe){if(Te===1/0||Te===-1/0||Te!==Te||Te&&Te>-1e3&&Te<1e3||Y.call(/e/,Pe))return Pe;var Le=/[0-9](?=(?:[0-9]{3})+(?![0-9]))/g;if(typeof Te=="number"){var Ze=Te<0?-ae(-Te):ae(Te);if(Ze!==Te){var He=String(Ze),Ue=J.call(Pe,He.length+1);return G.call(He,Le,"$&_")+"."+G.call(G.call(Ue,/([0-9]{3})/g,"$&_"),/_$/,"")}}return G.call(Pe,Le,"$&_")}var ye=u(8502),fe=ye.custom,re=$e(fe)?fe:null,ce={__proto__:null,double:'"',single:"'"},he={__proto__:null,double:/(["\\])/g,single:/(['\\])/g};r.exports=function Te(Pe,Le,Ze,He){var Ue=Le||{};if(we(Ue,"quoteStyle")&&!we(ce,Ue.quoteStyle))throw new TypeError('option "quoteStyle" must be "single" or "double"');if(we(Ue,"maxStringLength")&&(typeof Ue.maxStringLength=="number"?Ue.maxStringLength<0&&Ue.maxStringLength!==1/0:Ue.maxStringLength!==null))throw new TypeError('option "maxStringLength", if provided, must be a positive integer, Infinity, or `null`');var Ye=we(Ue,"customInspect")?Ue.customInspect:!0;if(typeof Ye!="boolean"&&Ye!=="symbol")throw new TypeError("option \"customInspect\", if provided, must be `true`, `false`, or `'symbol'`");if(we(Ue,"indent")&&Ue.indent!==null&&Ue.indent!==" "&&!(parseInt(Ue.indent,10)===Ue.indent&&Ue.indent>0))throw new TypeError('option "indent" must be "\\t", an integer > 0, or `null`');if(we(Ue,"numericSeparator")&&typeof Ue.numericSeparator!="boolean")throw new TypeError('option "numericSeparator", if provided, must be `true` or `false`');var ti=Ue.numericSeparator;if(typeof Pe>"u")return"undefined";if(Pe===null)return"null";if(typeof Pe=="boolean")return Pe?"true":"false";if(typeof Pe=="string")return Me(Pe,Ue);if(typeof Pe=="number"){if(Pe===0)return 1/0/Pe>0?"0":"-0";var Xe=String(Pe);return ti?se(Pe,Xe):Xe}if(typeof Pe=="bigint"){var ni=String(Pe)+"n";return ti?se(Pe,ni):ni}var ui=typeof Ue.depth>"u"?5:Ue.depth;if(typeof Ze>"u"&&(Ze=0),Ze>=ui&&ui>0&&typeof Pe=="object")return ge(Pe)?"[Array]":"[Object]";var ri=Ke(Ue,Ze);if(typeof He>"u")He=[];else if(Ne(He,Pe)>=0)return"[Circular]";function Qe(si,li,Ei){if(li&&(He=ie.call(He),He.push(li)),Ei){var Si={depth:Ue.depth};return we(Ue,"quoteStyle")&&(Si.quoteStyle=Ue.quoteStyle),Te(si,Si,Ze+1,He)}return Te(si,Ue,Ze+1,He)}if(typeof Pe=="function"&&!pe(Pe)){var gi=Oe(Pe),xi=ii(Pe,Qe);return"[Function"+(gi?": "+gi:" (anonymous)")+"]"+(xi.length>0?" { "+Q.call(xi,", ")+" }":"")}if($e(Pe)){var bi=de?G.call(String(Pe),/^(Symbol\(.*\))_[^)]*$/,"$1"):oe.call(Pe);return typeof Pe=="object"&&!de?Je(bi):bi}if(Ge(Pe)){for(var oi="<"+K.call(String(Pe.nodeName)),pi=Pe.attributes||[],ci=0;ci<pi.length;ci++)oi+=" "+pi[ci].name+"="+ve(je(pi[ci].value),"double",Ue);return oi+=">",Pe.childNodes&&Pe.childNodes.length&&(oi+="..."),oi+="</"+K.call(String(Pe.nodeName))+">",oi}if(ge(Pe)){if(Pe.length===0)return"[]";var di=ii(Pe,Qe);return ri&&!Be(di)?"["+ei(di,ri)+"]":"[ "+Q.call(di,", ")+" ]"}if(me(Pe)){var fi=ii(Pe,Qe);return!("cause"in Error.prototype)&&"cause"in Pe&&!xe.call(Pe,"cause")?"{ ["+String(Pe)+"] "+Q.call(ee.call("[cause]: "+Qe(Pe.cause),fi),", ")+" }":fi.length===0?"["+String(Pe)+"]":"{ ["+String(Pe)+"] "+Q.call(fi,", ")+" }"}if(typeof Pe=="object"&&Ye){if(re&&typeof Pe[re]=="function"&&ye)return ye(Pe,{depth:ui-Ze});if(Ye!=="symbol"&&typeof Pe.inspect=="function")return Pe.inspect()}if(Ae(Pe)){var yi=[];return x&&x.call(Pe,(function(si,li){yi.push(Qe(li,Pe,!0)+" => "+Qe(si,Pe))})),We("Map",h.call(Pe),yi,ri)}if(ze(Pe)){var _i=[];return $&&$.call(Pe,(function(si){_i.push(Qe(si,Pe))})),We("Set",w.call(Pe),_i,ri)}if(qe(Pe))return ai("WeakMap");if(Fe(Pe))return ai("WeakSet");if(De(Pe))return ai("WeakRef");if(le(Pe))return Je(Qe(Number(Pe)));if(Ie(Pe))return Je(Qe(ne.call(Pe)));if(ue(Pe))return Je(L.call(Pe));if(Se(Pe))return Je(Qe(String(Pe)));if(typeof window<"u"&&Pe===window)return"{ [object Window] }";if(typeof globalThis<"u"&&Pe===globalThis||typeof global<"u"&&Pe===global)return"{ [object globalThis] }";if(!be(Pe)&&!pe(Pe)){var mi=ii(Pe,Qe),wi=_e?_e(Pe)===Object.prototype:Pe instanceof Object||Pe.constructor===Object,hi=Pe instanceof Object?"":"null prototype",ki=!wi&&ke&&Object(Pe)===Pe&&ke in Pe?J.call(Ee(Pe),8,-1):hi?"Object":"",$i=wi||typeof Pe.constructor!="function"?"":Pe.constructor.name?Pe.constructor.name+" ":"",vi=$i+(ki||hi?"["+Q.call(ee.call([],ki||[],hi||[]),": ")+"] ":"");return mi.length===0?vi+"{}":ri?vi+"{"+ei(mi,ri)+"}":vi+"{ "+Q.call(mi,", ")+" }"}return String(Pe)};function ve(Te,Pe,Le){var Ze=Le.quoteStyle||Pe,He=ce[Ze];return He+Te+He}function je(Te){return G.call(String(Te),/"/g,"&quot;")}function Ce(Te){return!ke||!(typeof Te=="object"&&(ke in Te||typeof Te[ke]<"u"))}function ge(Te){return Ee(Te)==="[object Array]"&&Ce(Te)}function be(Te){return Ee(Te)==="[object Date]"&&Ce(Te)}function pe(Te){return Ee(Te)==="[object RegExp]"&&Ce(Te)}function me(Te){return Ee(Te)==="[object Error]"&&Ce(Te)}function Se(Te){return Ee(Te)==="[object String]"&&Ce(Te)}function le(Te){return Ee(Te)==="[object Number]"&&Ce(Te)}function ue(Te){return Ee(Te)==="[object Boolean]"&&Ce(Te)}function $e(Te){if(de)return Te&&typeof Te=="object"&&Te instanceof Symbol;if(typeof Te=="symbol")return!0;if(!Te||typeof Te!="object"||!oe)return!1;try{return oe.call(Te),!0}catch{}return!1}function Ie(Te){if(!Te||typeof Te!="object"||!ne)return!1;try{return ne.call(Te),!0}catch{}return!1}var Re=Object.prototype.hasOwnProperty||function(Te){return Te in this};function we(Te,Pe){return Re.call(Te,Pe)}function Ee(Te){return W.call(Te)}function Oe(Te){if(Te.name)return Te.name;var Pe=V.call(H.call(Te),/^function\s*([\w$]+)/);return Pe?Pe[1]:null}function Ne(Te,Pe){if(Te.indexOf)return Te.indexOf(Pe);for(var Le=0,Ze=Te.length;Le<Ze;Le++)if(Te[Le]===Pe)return Le;return-1}function Ae(Te){if(!h||!Te||typeof Te!="object")return!1;try{h.call(Te);try{w.call(Te)}catch{return!0}return Te instanceof Map}catch{}return!1}function qe(Te){if(!I||!Te||typeof Te!="object")return!1;try{I.call(Te,I);try{z.call(Te,z)}catch{return!0}return Te instanceof WeakMap}catch{}return!1}function De(Te){if(!B||!Te||typeof Te!="object")return!1;try{return B.call(Te),!0}catch{}return!1}function ze(Te){if(!w||!Te||typeof Te!="object")return!1;try{w.call(Te);try{h.call(Te)}catch{return!0}return Te instanceof Set}catch{}return!1}function Fe(Te){if(!z||!Te||typeof Te!="object")return!1;try{z.call(Te,z);try{I.call(Te,I)}catch{return!0}return Te instanceof WeakSet}catch{}return!1}function Ge(Te){return!Te||typeof Te!="object"?!1:typeof HTMLElement<"u"&&Te instanceof HTMLElement?!0:typeof Te.nodeName=="string"&&typeof Te.getAttribute=="function"}function Me(Te,Pe){if(Te.length>Pe.maxStringLength){var Le=Te.length-Pe.maxStringLength,Ze="... "+Le+" more character"+(Le>1?"s":"");return Me(J.call(Te,0,Pe.maxStringLength),Pe)+Ze}var He=he[Pe.quoteStyle||"single"];He.lastIndex=0;var Ue=G.call(G.call(Te,He,"\\$1"),/[\x00-\x1f]/g,Ve);return ve(Ue,"single",Pe)}function Ve(Te){var Pe=Te.charCodeAt(0),Le={8:"b",9:"t",10:"n",12:"f",13:"r"}[Pe];return Le?"\\"+Le:"\\x"+(Pe<16?"0":"")+X.call(Pe.toString(16))}function Je(Te){return"Object("+Te+")"}function ai(Te){return Te+" { ? }"}function We(Te,Pe,Le,Ze){var He=Ze?ei(Le,Ze):Q.call(Le,", ");return Te+" ("+Pe+") {"+He+"}"}function Be(Te){for(var Pe=0;Pe<Te.length;Pe++)if(Ne(Te[Pe],`
226
226
  `)>=0)return!1;return!0}function Ke(Te,Pe){var Le;if(Te.indent===" ")Le=" ";else if(typeof Te.indent=="number"&&Te.indent>0)Le=Q.call(Array(Te.indent+1)," ");else return null;return{base:Le,prev:Q.call(Array(Pe+1),Le)}}function ei(Te,Pe){if(Te.length===0)return"";var Le=`
227
227
  `+Pe.prev+Pe.base;return Le+Q.call(Te,","+Le)+`
228
- `+Pe.prev}function ii(Te,Pe){var Le=ge(Te),He=[];if(Le){He.length=Te.length;for(var Ze=0;Ze<Te.length;Ze++)He[Ze]=we(Te,Ze)?Pe(Te[Ze],Te):""}var Ue=typeof te=="function"?te(Te):[],Ye;if(de){Ye={};for(var ti=0;ti<Ue.length;ti++)Ye["$"+Ue[ti]]=Ue[ti]}for(var Xe in Te)we(Te,Xe)&&(Le&&String(Number(Xe))===Xe&&Xe<Te.length||de&&Ye["$"+Xe]instanceof Symbol||(Y.call(/[^\w$]/,Xe)?He.push(Pe(Xe,Te)+": "+Pe(Te[Xe],Te)):He.push(Xe+": "+Pe(Te[Xe],Te))));if(typeof te=="function")for(var ni=0;ni<Ue.length;ni++)xe.call(Te,Ue[ni])&&He.push("["+Pe(Ue[ni])+"]: "+Pe(Te[Ue[ni]],Te));return He}},8502:(r,t,u)=>{r.exports=u(9023).inspect},5698:(r,t,u)=>{/*!
228
+ `+Pe.prev}function ii(Te,Pe){var Le=ge(Te),Ze=[];if(Le){Ze.length=Te.length;for(var He=0;He<Te.length;He++)Ze[He]=we(Te,He)?Pe(Te[He],Te):""}var Ue=typeof te=="function"?te(Te):[],Ye;if(de){Ye={};for(var ti=0;ti<Ue.length;ti++)Ye["$"+Ue[ti]]=Ue[ti]}for(var Xe in Te)we(Te,Xe)&&(Le&&String(Number(Xe))===Xe&&Xe<Te.length||de&&Ye["$"+Xe]instanceof Symbol||(Y.call(/[^\w$]/,Xe)?Ze.push(Pe(Xe,Te)+": "+Pe(Te[Xe],Te)):Ze.push(Xe+": "+Pe(Te[Xe],Te))));if(typeof te=="function")for(var ni=0;ni<Ue.length;ni++)xe.call(Te,Ue[ni])&&Ze.push("["+Pe(Ue[ni])+"]: "+Pe(Te[Ue[ni]],Te));return Ze}},8502:(r,t,u)=>{r.exports=u(9023).inspect},5698:(r,t,u)=>{/*!
229
229
  * on-finished
230
230
  * Copyright(c) 2013 Jonathan Ong
231
231
  * Copyright(c) 2014 Douglas Christopher Wilson
@@ -357,7 +357,7 @@ Minimum version required to store current data is: `+ne+`.
357
357
  `+Object.keys(ee).map((Q=>`${Q}: ${ee[Q]}`)).join(`\r
358
358
  `)+`\r
359
359
  \r
360
- `+Y)}function G(X,K,Y,ee,Q,ie){if(X.listenerCount("wsClientError")){const ae=new Error(Q);Error.captureStackTrace(ae,G),X.emit("wsClientError",ae,Y,K)}else J(Y,ee,Q,ie)}},6681:(r,t,u)=>{const d=u(4434),p=u(5692),h=u(8611),x=u(9278),j=u(4756),{randomBytes:b,createHash:w}=u(6982),{Duplex:$,Readable:O}=u(2203),{URL:I}=u(7016),U=u(4376),z=u(893),N=u(7389),{isBlob:B}=u(6615),{BINARY_TYPES:L,EMPTY_BUFFER:W,GUID:H,kForOnEventAttribute:V,kListener:J,kStatusCode:G,kWebSocket:X,NOOP:K}=u(1791),{EventTarget:{addEventListener:Y,removeEventListener:ee}}=u(4634),{format:Q,parse:ie}=u(1335),{toBuffer:ae}=u(5803),ne=30*1e3,te=Symbol("kAborted"),oe=[8,13],de=["CONNECTING","OPEN","CLOSING","CLOSED"],ke=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;class xe extends d{constructor(Ee,Oe,Ne){super(),this._binaryType=L[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=W,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=xe.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,Ee!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,Oe===void 0?Oe=[]:Array.isArray(Oe)||(typeof Oe=="object"&&Oe!==null?(Ne=Oe,Oe=[]):Oe=[Oe]),_e(this,Ee,Oe,Ne)):(this._autoPong=Ne.autoPong,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(Ee){L.includes(Ee)&&(this._binaryType=Ee,this._receiver&&(this._receiver._binaryType=Ee))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(Ee,Oe,Ne){const Ae=new z({allowSynchronousEvents:Ne.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:Ne.maxPayload,skipUTF8Validation:Ne.skipUTF8Validation}),qe=new N(Ee,this._extensions,Ne.generateMask);this._receiver=Ae,this._sender=qe,this._socket=Ee,Ae[X]=this,qe[X]=this,Ee[X]=this,Ae.on("conclude",he),Ae.on("drain",ve),Ae.on("error",je),Ae.on("message",ge),Ae.on("ping",be),Ae.on("pong",pe),qe.onerror=Se,Ee.setTimeout&&Ee.setTimeout(0),Ee.setNoDelay&&Ee.setNoDelay(),Oe.length>0&&Ee.unshift(Oe),Ee.on("close",ue),Ee.on("data",$e),Ee.on("end",Ie),Ee.on("error",Re),this._readyState=xe.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=xe.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[U.extensionName]&&this._extensions[U.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=xe.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(Ee,Oe){if(this.readyState!==xe.CLOSED){if(this.readyState===xe.CONNECTING){re(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===xe.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=xe.CLOSING,this._sender.close(Ee,Oe,!this._isServer,(Ne=>{Ne||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())})),le(this)}}pause(){this.readyState===xe.CONNECTING||this.readyState===xe.CLOSED||(this._paused=!0,this._socket.pause())}ping(Ee,Oe,Ne){if(this.readyState===xe.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof Ee=="function"?(Ne=Ee,Ee=Oe=void 0):typeof Oe=="function"&&(Ne=Oe,Oe=void 0),typeof Ee=="number"&&(Ee=Ee.toString()),this.readyState!==xe.OPEN){ce(this,Ee,Ne);return}Oe===void 0&&(Oe=!this._isServer),this._sender.ping(Ee||W,Oe,Ne)}pong(Ee,Oe,Ne){if(this.readyState===xe.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof Ee=="function"?(Ne=Ee,Ee=Oe=void 0):typeof Oe=="function"&&(Ne=Oe,Oe=void 0),typeof Ee=="number"&&(Ee=Ee.toString()),this.readyState!==xe.OPEN){ce(this,Ee,Ne);return}Oe===void 0&&(Oe=!this._isServer),this._sender.pong(Ee||W,Oe,Ne)}resume(){this.readyState===xe.CONNECTING||this.readyState===xe.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(Ee,Oe,Ne){if(this.readyState===xe.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof Oe=="function"&&(Ne=Oe,Oe={}),typeof Ee=="number"&&(Ee=Ee.toString()),this.readyState!==xe.OPEN){ce(this,Ee,Ne);return}const Ae={binary:typeof Ee!="string",mask:!this._isServer,compress:!0,fin:!0,...Oe};this._extensions[U.extensionName]||(Ae.compress=!1),this._sender.send(Ee||W,Ae,Ne)}terminate(){if(this.readyState!==xe.CLOSED){if(this.readyState===xe.CONNECTING){re(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=xe.CLOSING,this._socket.destroy())}}}Object.defineProperty(xe,"CONNECTING",{enumerable:!0,value:de.indexOf("CONNECTING")}),Object.defineProperty(xe.prototype,"CONNECTING",{enumerable:!0,value:de.indexOf("CONNECTING")}),Object.defineProperty(xe,"OPEN",{enumerable:!0,value:de.indexOf("OPEN")}),Object.defineProperty(xe.prototype,"OPEN",{enumerable:!0,value:de.indexOf("OPEN")}),Object.defineProperty(xe,"CLOSING",{enumerable:!0,value:de.indexOf("CLOSING")}),Object.defineProperty(xe.prototype,"CLOSING",{enumerable:!0,value:de.indexOf("CLOSING")}),Object.defineProperty(xe,"CLOSED",{enumerable:!0,value:de.indexOf("CLOSED")}),Object.defineProperty(xe.prototype,"CLOSED",{enumerable:!0,value:de.indexOf("CLOSED")}),["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach((we=>{Object.defineProperty(xe.prototype,we,{enumerable:!0})})),["open","error","close","message"].forEach((we=>{Object.defineProperty(xe.prototype,`on${we}`,{enumerable:!0,get(){for(const Ee of this.listeners(we))if(Ee[V])return Ee[J];return null},set(Ee){for(const Oe of this.listeners(we))if(Oe[V]){this.removeListener(we,Oe);break}typeof Ee=="function"&&this.addEventListener(we,Ee,{[V]:!0})}})})),xe.prototype.addEventListener=Y,xe.prototype.removeEventListener=ee,r.exports=xe;function _e(we,Ee,Oe,Ne){const Ae={allowSynchronousEvents:!0,autoPong:!0,protocolVersion:oe[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...Ne,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(we._autoPong=Ae.autoPong,!oe.includes(Ae.protocolVersion))throw new RangeError(`Unsupported protocol version: ${Ae.protocolVersion} (supported versions: ${oe.join(", ")})`);let qe;if(Ee instanceof I)qe=Ee;else try{qe=new I(Ee)}catch{throw new SyntaxError(`Invalid URL: ${Ee}`)}qe.protocol==="http:"?qe.protocol="ws:":qe.protocol==="https:"&&(qe.protocol="wss:"),we._url=qe.href;const De=qe.protocol==="wss:",ze=qe.protocol==="ws+unix:";let Fe;if(qe.protocol!=="ws:"&&!De&&!ze?Fe=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:ze&&!qe.pathname?Fe="The URL's pathname is empty":qe.hash&&(Fe="The URL contains a fragment identifier"),Fe){const Be=new SyntaxError(Fe);if(we._redirects===0)throw Be;se(we,Be);return}const Ge=De?443:80,Me=b(16).toString("base64"),Ve=De?p.request:h.request,Je=new Set;let ai;if(Ae.createConnection=Ae.createConnection||(De?fe:ye),Ae.defaultPort=Ae.defaultPort||Ge,Ae.port=qe.port||Ge,Ae.host=qe.hostname.startsWith("[")?qe.hostname.slice(1,-1):qe.hostname,Ae.headers={...Ae.headers,"Sec-WebSocket-Version":Ae.protocolVersion,"Sec-WebSocket-Key":Me,Connection:"Upgrade",Upgrade:"websocket"},Ae.path=qe.pathname+qe.search,Ae.timeout=Ae.handshakeTimeout,Ae.perMessageDeflate&&(ai=new U(Ae.perMessageDeflate!==!0?Ae.perMessageDeflate:{},!1,Ae.maxPayload),Ae.headers["Sec-WebSocket-Extensions"]=Q({[U.extensionName]:ai.offer()})),Oe.length){for(const Be of Oe){if(typeof Be!="string"||!ke.test(Be)||Je.has(Be))throw new SyntaxError("An invalid or duplicated subprotocol was specified");Je.add(Be)}Ae.headers["Sec-WebSocket-Protocol"]=Oe.join(",")}if(Ae.origin&&(Ae.protocolVersion<13?Ae.headers["Sec-WebSocket-Origin"]=Ae.origin:Ae.headers.Origin=Ae.origin),(qe.username||qe.password)&&(Ae.auth=`${qe.username}:${qe.password}`),ze){const Be=Ae.path.split(":");Ae.socketPath=Be[0],Ae.path=Be[1]}let We;if(Ae.followRedirects){if(we._redirects===0){we._originalIpc=ze,we._originalSecure=De,we._originalHostOrSocketPath=ze?Ae.socketPath:qe.host;const Be=Ne&&Ne.headers;if(Ne={...Ne,headers:{}},Be)for(const[Ke,ei]of Object.entries(Be))Ne.headers[Ke.toLowerCase()]=ei}else if(we.listenerCount("redirect")===0){const Be=ze?we._originalIpc?Ae.socketPath===we._originalHostOrSocketPath:!1:we._originalIpc?!1:qe.host===we._originalHostOrSocketPath;(!Be||we._originalSecure&&!De)&&(delete Ae.headers.authorization,delete Ae.headers.cookie,Be||delete Ae.headers.host,Ae.auth=void 0)}Ae.auth&&!Ne.headers.authorization&&(Ne.headers.authorization="Basic "+Buffer.from(Ae.auth).toString("base64")),We=we._req=Ve(Ae),we._redirects&&we.emit("redirect",we.url,We)}else We=we._req=Ve(Ae);Ae.timeout&&We.on("timeout",(()=>{re(we,We,"Opening handshake has timed out")})),We.on("error",(Be=>{We===null||We[te]||(We=we._req=null,se(we,Be))})),We.on("response",(Be=>{const Ke=Be.headers.location,ei=Be.statusCode;if(Ke&&Ae.followRedirects&&ei>=300&&ei<400){if(++we._redirects>Ae.maxRedirects){re(we,We,"Maximum redirects exceeded");return}We.abort();let ii;try{ii=new I(Ke,Ee)}catch{const Pe=new SyntaxError(`Invalid URL: ${Ke}`);se(we,Pe);return}_e(we,ii,Oe,Ne)}else we.emit("unexpected-response",We,Be)||re(we,We,`Unexpected server response: ${Be.statusCode}`)})),We.on("upgrade",((Be,Ke,ei)=>{if(we.emit("upgrade",Be),we.readyState!==xe.CONNECTING)return;We=we._req=null;const ii=Be.headers.upgrade;if(ii===void 0||ii.toLowerCase()!=="websocket"){re(we,Ke,"Invalid Upgrade header");return}const Te=w("sha1").update(Me+H).digest("base64");if(Be.headers["sec-websocket-accept"]!==Te){re(we,Ke,"Invalid Sec-WebSocket-Accept header");return}const Pe=Be.headers["sec-websocket-protocol"];let Le;if(Pe!==void 0?Je.size?Je.has(Pe)||(Le="Server sent an invalid subprotocol"):Le="Server sent a subprotocol but none was requested":Je.size&&(Le="Server sent no subprotocol"),Le){re(we,Ke,Le);return}Pe&&(we._protocol=Pe);const He=Be.headers["sec-websocket-extensions"];if(He!==void 0){if(!ai){re(we,Ke,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let Ze;try{Ze=ie(He)}catch{re(we,Ke,"Invalid Sec-WebSocket-Extensions header");return}const Ue=Object.keys(Ze);if(Ue.length!==1||Ue[0]!==U.extensionName){re(we,Ke,"Server indicated an extension that was not requested");return}try{ai.accept(Ze[U.extensionName])}catch{re(we,Ke,"Invalid Sec-WebSocket-Extensions header");return}we._extensions[U.extensionName]=ai}we.setSocket(Ke,ei,{allowSynchronousEvents:Ae.allowSynchronousEvents,generateMask:Ae.generateMask,maxPayload:Ae.maxPayload,skipUTF8Validation:Ae.skipUTF8Validation})})),Ae.finishRequest?Ae.finishRequest(We,we):We.end()}function se(we,Ee){we._readyState=xe.CLOSING,we._errorEmitted=!0,we.emit("error",Ee),we.emitClose()}function ye(we){return we.path=we.socketPath,x.connect(we)}function fe(we){return we.path=void 0,!we.servername&&we.servername!==""&&(we.servername=x.isIP(we.host)?"":we.host),j.connect(we)}function re(we,Ee,Oe){we._readyState=xe.CLOSING;const Ne=new Error(Oe);Error.captureStackTrace(Ne,re),Ee.setHeader?(Ee[te]=!0,Ee.abort(),Ee.socket&&!Ee.socket.destroyed&&Ee.socket.destroy(),process.nextTick(se,we,Ne)):(Ee.destroy(Ne),Ee.once("error",we.emit.bind(we,"error")),Ee.once("close",we.emitClose.bind(we)))}function ce(we,Ee,Oe){if(Ee){const Ne=B(Ee)?Ee.size:ae(Ee).length;we._socket?we._sender._bufferedBytes+=Ne:we._bufferedAmount+=Ne}if(Oe){const Ne=new Error(`WebSocket is not open: readyState ${we.readyState} (${de[we.readyState]})`);process.nextTick(Oe,Ne)}}function he(we,Ee){const Oe=this[X];Oe._closeFrameReceived=!0,Oe._closeMessage=Ee,Oe._closeCode=we,Oe._socket[X]!==void 0&&(Oe._socket.removeListener("data",$e),process.nextTick(me,Oe._socket),we===1005?Oe.close():Oe.close(we,Ee))}function ve(){const we=this[X];we.isPaused||we._socket.resume()}function je(we){const Ee=this[X];Ee._socket[X]!==void 0&&(Ee._socket.removeListener("data",$e),process.nextTick(me,Ee._socket),Ee.close(we[G])),Ee._errorEmitted||(Ee._errorEmitted=!0,Ee.emit("error",we))}function Ce(){this[X].emitClose()}function ge(we,Ee){this[X].emit("message",we,Ee)}function be(we){const Ee=this[X];Ee._autoPong&&Ee.pong(we,!this._isServer,K),Ee.emit("ping",we)}function pe(we){this[X].emit("pong",we)}function me(we){we.resume()}function Se(we){const Ee=this[X];Ee.readyState!==xe.CLOSED&&(Ee.readyState===xe.OPEN&&(Ee._readyState=xe.CLOSING,le(Ee)),this._socket.end(),Ee._errorEmitted||(Ee._errorEmitted=!0,Ee.emit("error",we)))}function le(we){we._closeTimer=setTimeout(we._socket.destroy.bind(we._socket),ne)}function ue(){const we=this[X];this.removeListener("close",ue),this.removeListener("data",$e),this.removeListener("end",Ie),we._readyState=xe.CLOSING;let Ee;!this._readableState.endEmitted&&!we._closeFrameReceived&&!we._receiver._writableState.errorEmitted&&(Ee=we._socket.read())!==null&&we._receiver.write(Ee),we._receiver.end(),this[X]=void 0,clearTimeout(we._closeTimer),we._receiver._writableState.finished||we._receiver._writableState.errorEmitted?we.emitClose():(we._receiver.on("error",Ce),we._receiver.on("finish",Ce))}function $e(we){this[X]._receiver.write(we)||this.pause()}function Ie(){const we=this[X];we._readyState=xe.CLOSING,we._receiver.end(),this.end()}function Re(){const we=this[X];this.removeListener("error",Re),this.on("error",K),we&&(we._readyState=xe.CLOSING,this.destroy())}},8327:module=>{module.exports=eval("require")("bufferutil")},75:module=>{module.exports=eval("require")("supports-color")},2414:module=>{module.exports=eval("require")("utf-8-validate")},2613:r=>{r.exports=__WEBPACK_EXTERNAL_createRequire(import.meta.url)("assert")},290:r=>{r.exports=__WEBPACK_EXTERNAL_createRequire(import.meta.url)("async_hooks")},181:r=>{r.exports=__WEBPACK_EXTERNAL_createRequire(import.meta.url)("buffer")},6982:r=>{r.exports=__WEBPACK_EXTERNAL_createRequire(import.meta.url)("crypto")},4434:r=>{r.exports=__WEBPACK_EXTERNAL_createRequire(import.meta.url)("events")},9896:r=>{r.exports=__WEBPACK_EXTERNAL_createRequire(import.meta.url)("fs")},8611:r=>{r.exports=__WEBPACK_EXTERNAL_createRequire(import.meta.url)("http")},5692:r=>{r.exports=__WEBPACK_EXTERNAL_createRequire(import.meta.url)("https")},9278:r=>{r.exports=__WEBPACK_EXTERNAL_createRequire(import.meta.url)("net")},4573:r=>{r.exports=__WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:buffer")},8474:r=>{r.exports=__WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:events")},3024:r=>{r.exports=__WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:fs")},7067:r=>{r.exports=__WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:http")},7030:r=>{r.exports=__WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:net")},6760:r=>{r.exports=__WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:path")},1792:r=>{r.exports=__WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:querystring")},8522:r=>{r.exports=__WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:zlib")},857:r=>{r.exports=__WEBPACK_EXTERNAL_createRequire(import.meta.url)("os")},6928:r=>{r.exports=__WEBPACK_EXTERNAL_createRequire(import.meta.url)("path")},3480:r=>{r.exports=__WEBPACK_EXTERNAL_createRequire(import.meta.url)("querystring")},2203:r=>{r.exports=__WEBPACK_EXTERNAL_createRequire(import.meta.url)("stream")},3193:r=>{r.exports=__WEBPACK_EXTERNAL_createRequire(import.meta.url)("string_decoder")},3557:r=>{r.exports=__WEBPACK_EXTERNAL_createRequire(import.meta.url)("timers")},4756:r=>{r.exports=__WEBPACK_EXTERNAL_createRequire(import.meta.url)("tls")},2018:r=>{r.exports=__WEBPACK_EXTERNAL_createRequire(import.meta.url)("tty")},7016:r=>{r.exports=__WEBPACK_EXTERNAL_createRequire(import.meta.url)("url")},9023:r=>{r.exports=__WEBPACK_EXTERNAL_createRequire(import.meta.url)("util")},3106:r=>{r.exports=__WEBPACK_EXTERNAL_createRequire(import.meta.url)("zlib")},2998:(r,t)=>{t.Emitter=u;function u(p){if(p)return d(p)}function d(p){for(var h in u.prototype)p[h]=u.prototype[h];return p}u.prototype.on=u.prototype.addEventListener=function(p,h){return this._callbacks=this._callbacks||{},(this._callbacks["$"+p]=this._callbacks["$"+p]||[]).push(h),this},u.prototype.once=function(p,h){function x(){this.off(p,x),h.apply(this,arguments)}return x.fn=h,this.on(p,x),this},u.prototype.off=u.prototype.removeListener=u.prototype.removeAllListeners=u.prototype.removeEventListener=function(p,h){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var x=this._callbacks["$"+p];if(!x)return this;if(arguments.length==1)return delete this._callbacks["$"+p],this;for(var j,b=0;b<x.length;b++)if(j=x[b],j===h||j.fn===h){x.splice(b,1);break}return x.length===0&&delete this._callbacks["$"+p],this},u.prototype.emit=function(p){this._callbacks=this._callbacks||{};for(var h=new Array(arguments.length-1),x=this._callbacks["$"+p],j=1;j<arguments.length;j++)h[j-1]=arguments[j];if(x){x=x.slice(0);for(var j=0,b=x.length;j<b;++j)x[j].apply(this,h)}return this},u.prototype.emitReserved=u.prototype.emit,u.prototype.listeners=function(p){return this._callbacks=this._callbacks||{},this._callbacks["$"+p]||[]},u.prototype.hasListeners=function(p){return!!this.listeners(p).length}},2717:(r,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ERROR_PACKET=t.PACKET_TYPES_REVERSE=t.PACKET_TYPES=void 0;const u=Object.create(null);t.PACKET_TYPES=u,u.open="0",u.close="1",u.ping="2",u.pong="3",u.message="4",u.upgrade="5",u.noop="6";const d=Object.create(null);t.PACKET_TYPES_REVERSE=d,Object.keys(u).forEach((h=>{d[u[h]]=h}));const p={type:"error",data:"parser error"};t.ERROR_PACKET=p},3377:(r,t,u)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.decodePacket=void 0;const d=u(2717),p=(x,j)=>{if(typeof x!="string")return{type:"message",data:h(x,j)};const b=x.charAt(0);if(b==="b"){const w=Buffer.from(x.substring(1),"base64");return{type:"message",data:h(w,j)}}return d.PACKET_TYPES_REVERSE[b]?x.length>1?{type:d.PACKET_TYPES_REVERSE[b],data:x.substring(1)}:{type:d.PACKET_TYPES_REVERSE[b]}:d.ERROR_PACKET};t.decodePacket=p;const h=(x,j)=>j==="arraybuffer"?x instanceof ArrayBuffer?x:Buffer.isBuffer(x)?x.buffer.slice(x.byteOffset,x.byteOffset+x.byteLength):x.buffer:Buffer.isBuffer(x)?x:Buffer.from(x)},5897:(r,t,u)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.encodePacket=void 0,t.encodePacketToBinary=j;const d=u(2717),p=({type:b,data:w},$,O)=>w instanceof ArrayBuffer||ArrayBuffer.isView(w)?O($?w:"b"+h(w,!0).toString("base64")):O(d.PACKET_TYPES[b]+(w||""));t.encodePacket=p;const h=(b,w)=>Buffer.isBuffer(b)||b instanceof Uint8Array&&!w?b:b instanceof ArrayBuffer?Buffer.from(b):Buffer.from(b.buffer,b.byteOffset,b.byteLength);let x;function j(b,w){if(b.data instanceof ArrayBuffer||ArrayBuffer.isView(b.data))return w(h(b.data,!1));(0,t.encodePacket)(b,!0,($=>{x||(x=new TextEncoder),w(x.encode($))}))}},8007:(r,t,u)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.decodePayload=t.decodePacket=t.encodePayload=t.encodePacket=t.protocol=void 0,t.createPacketEncoderStream=w,t.createPacketDecoderStream=U;const d=u(5897);Object.defineProperty(t,"encodePacket",{enumerable:!0,get:function(){return d.encodePacket}});const p=u(3377);Object.defineProperty(t,"decodePacket",{enumerable:!0,get:function(){return p.decodePacket}});const h=u(2717),x="",j=(z,N)=>{const B=z.length,L=new Array(B);let W=0;z.forEach(((H,V)=>{(0,d.encodePacket)(H,!1,(J=>{L[V]=J,++W===B&&N(L.join(x))}))}))};t.encodePayload=j;const b=(z,N)=>{const B=z.split(x),L=[];for(let W=0;W<B.length;W++){const H=(0,p.decodePacket)(B[W],N);if(L.push(H),H.type==="error")break}return L};t.decodePayload=b;function w(){return new TransformStream({transform(z,N){(0,d.encodePacketToBinary)(z,(B=>{const L=B.length;let W;if(L<126)W=new Uint8Array(1),new DataView(W.buffer).setUint8(0,L);else if(L<65536){W=new Uint8Array(3);const H=new DataView(W.buffer);H.setUint8(0,126),H.setUint16(1,L)}else{W=new Uint8Array(9);const H=new DataView(W.buffer);H.setUint8(0,127),H.setBigUint64(1,BigInt(L))}z.data&&typeof z.data!="string"&&(W[0]|=128),N.enqueue(W),N.enqueue(B)}))}})}let $;function O(z){return z.reduce(((N,B)=>N+B.length),0)}function I(z,N){if(z[0].length===N)return z.shift();const B=new Uint8Array(N);let L=0;for(let W=0;W<N;W++)B[W]=z[0][L++],L===z[0].length&&(z.shift(),L=0);return z.length&&L<z[0].length&&(z[0]=z[0].slice(L)),B}function U(z,N){$||($=new TextDecoder);const B=[];let L=0,W=-1,H=!1;return new TransformStream({transform(V,J){for(B.push(V);;){if(L===0){if(O(B)<1)break;const G=I(B,1);H=(G[0]&128)===128,W=G[0]&127,W<126?L=3:W===126?L=1:L=2}else if(L===1){if(O(B)<2)break;const G=I(B,2);W=new DataView(G.buffer,G.byteOffset,G.length).getUint16(0),L=3}else if(L===2){if(O(B)<8)break;const G=I(B,8),X=new DataView(G.buffer,G.byteOffset,G.length),K=X.getUint32(0);if(K>Math.pow(2,21)-1){J.enqueue(h.ERROR_PACKET);break}W=K*Math.pow(2,32)+X.getUint32(4),L=3}else{if(O(B)<W)break;const G=I(B,W);J.enqueue((0,p.decodePacket)(H?G:$.decode(G),N)),L=0}if(W===0||W>z){J.enqueue(h.ERROR_PACKET);break}}}})}t.protocol=4},68:(r,t,u)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.protocol=t.Transport=t.Socket=t.uServer=t.parser=t.transports=t.Server=void 0,t.listen=$,t.attach=O;const d=u(8611),p=u(2317);Object.defineProperty(t,"Server",{enumerable:!0,get:function(){return p.Server}});const h=u(2975);t.transports=h.default;const x=u(8007);t.parser=x;var j=u(2056);Object.defineProperty(t,"uServer",{enumerable:!0,get:function(){return j.uServer}});var b=u(3739);Object.defineProperty(t,"Socket",{enumerable:!0,get:function(){return b.Socket}});var w=u(4621);Object.defineProperty(t,"Transport",{enumerable:!0,get:function(){return w.Transport}}),t.protocol=x.protocol;function $(I,U,z){typeof U=="function"&&(z=U,U={});const N=(0,d.createServer)((function(L,W){W.writeHead(501),W.end("Not Implemented")})),B=O(N,U);return B.httpServer=N,N.listen(I,z),B}function O(I,U){const z=new p.Server(U);return z.attach(I,U),z}},2674:(r,t,u)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.packets=t.protocol=void 0,t.encodePacket=b,t.encodeBase64Packet=$,t.decodePacket=O,t.decodeBase64Packet=U,t.encodePayload=z,t.decodePayload=L,t.encodePayloadAsBinary=J,t.decodePayloadAsBinary=X;var d=u(4875);t.protocol=3;const p=K=>{for(const Y of K)if(Y.data instanceof ArrayBuffer||ArrayBuffer.isView(Y.data))return!0;return!1};t.packets={open:0,close:1,ping:2,pong:3,message:4,upgrade:5,noop:6};var h=Object.keys(t.packets),x={type:"error",data:"parser error"};const j=Buffer.concat([]);function b(K,Y,ee,Q){if(typeof Y=="function"&&(Q=Y,Y=null),typeof ee=="function"&&(Q=ee,ee=null),Buffer.isBuffer(K.data))return w(K,Y,Q);if(K.data&&(K.data.buffer||K.data)instanceof ArrayBuffer)return w({type:K.type,data:V(K.data)},Y,Q);var ie=t.packets[K.type];return K.data!==void 0&&(ie+=ee?d.encode(String(K.data),{strict:!1}):String(K.data)),Q(""+ie)}function w(K,Y,ee){if(!Y)return $(K,ee);var Q=K.data,ie=Buffer.allocUnsafe(1);return ie[0]=t.packets[K.type],ee(Buffer.concat([ie,Q]))}function $(K,Y){var ee=Buffer.isBuffer(K.data)?K.data:V(K.data),Q="b"+t.packets[K.type];return Q+=ee.toString("base64"),Y(Q)}function O(K,Y,ee){if(K===void 0)return x;let Q;if(typeof K=="string")return Q=K.charAt(0),Q==="b"?U(K.slice(1),Y):ee&&(K=I(K),K===!1)||Number(Q)!=Q||!h[Q]?x:K.length>1?{type:h[Q],data:K.slice(1)}:{type:h[Q]};if(Y==="arraybuffer"){var ie=new Uint8Array(K);return Q=ie[0],{type:h[Q],data:ie.buffer.slice(1)}}return K instanceof ArrayBuffer&&(K=V(K)),Q=K[0],{type:h[Q],data:K.slice(1)}}function I(K){try{K=d.decode(K,{strict:!1})}catch{return!1}return K}function U(K,Y){var ee=h[K.charAt(0)],Q=Buffer.from(K.slice(1),"base64");if(Y==="arraybuffer"){for(var ie=new Uint8Array(Q.length),ae=0;ae<ie.length;ae++)ie[ae]=Q[ae];Q=ie.buffer}return{type:ee,data:Q}}function z(K,Y,ee){if(typeof Y=="function"&&(ee=Y,Y=null),Y&&p(K))return J(K,ee);if(!K.length)return ee("0:");function Q(ie,ae){b(ie,Y,!1,(function(ne){ae(null,N(ne))}))}B(K,Q,(function(ie,ae){return ee(ae.join(""))}))}function N(K){return K.length+":"+K}function B(K,Y,ee){const Q=new Array(K.length);let ie=0;for(let ae=0;ae<K.length;ae++)Y(K[ae],((ne,te)=>{Q[ae]=te,++ie===K.length&&ee(null,Q)}))}function L(K,Y,ee){if(typeof K!="string")return X(K,Y,ee);if(typeof Y=="function"&&(ee=Y,Y=null),K==="")return ee(x,0,1);for(var Q="",ie,ae,ne,te=0,oe=K.length;te<oe;te++){var de=K.charAt(te);if(de!==":"){Q+=de;continue}if(Q===""||Q!=(ie=Number(Q))||(ae=K.slice(te+1,te+1+ie),Q!=ae.length))return ee(x,0,1);if(ae.length){if(ne=O(ae,Y,!1),x.type===ne.type&&x.data===ne.data)return ee(x,0,1);var ke=ee(ne,te+ie,oe);if(ke===!1)return}te+=ie,Q=""}if(Q!=="")return ee(x,0,1)}function W(K){for(var Y="",ee=0,Q=K.length;ee<Q;ee++)Y+=String.fromCharCode(K[ee]);return Y}function H(K){for(var Y=Buffer.allocUnsafe(K.length),ee=0,Q=K.length;ee<Q;ee++)Y.writeUInt8(K.charCodeAt(ee),ee);return Y}function V(K){var Y=K.byteLength||K.length,ee=K.byteOffset||0;return Buffer.from(K.buffer||K,ee,Y)}function J(K,Y){if(!K.length)return Y(j);B(K,G,(function(ee,Q){return Y(Buffer.concat(Q))}))}function G(K,Y){function ee(Q){var ie=""+Q.length,ae;if(typeof Q=="string"){ae=Buffer.allocUnsafe(ie.length+2),ae[0]=0;for(var ne=0;ne<ie.length;ne++)ae[ne+1]=parseInt(ie[ne],10);return ae[ae.length-1]=255,Y(null,Buffer.concat([ae,H(Q)]))}ae=Buffer.allocUnsafe(ie.length+2),ae[0]=1;for(var ne=0;ne<ie.length;ne++)ae[ne+1]=parseInt(ie[ne],10);ae[ae.length-1]=255,Y(null,Buffer.concat([ae,Q]))}b(K,!0,!0,ee)}function X(K,Y,ee){typeof Y=="function"&&(ee=Y,Y=null);for(var Q=K,ie=[],ae;Q.length>0;){var ne="",te=Q[0]===0;for(ae=1;Q[ae]!==255;ae++){if(ne.length>310)return ee(x,0,1);ne+=""+Q[ae]}Q=Q.slice(ne.length+1);var oe=parseInt(ne,10),de=Q.slice(1,oe+1);te&&(de=W(de)),ie.push(de),Q=Q.slice(oe+1)}var ke=ie.length;for(ae=0;ae<ke;ae++){var xe=ie[ae];ee(O(xe,Y,!0),ae,ke)}}},4875:r=>{/*! https://mths.be/utf8js v2.1.2 by @mathias */var t=String.fromCharCode;function u(z){for(var N=[],B=0,L=z.length,W,H;B<L;)W=z.charCodeAt(B++),W>=55296&&W<=56319&&B<L?(H=z.charCodeAt(B++),(H&64512)==56320?N.push(((W&1023)<<10)+(H&1023)+65536):(N.push(W),B--)):N.push(W);return N}function d(z){for(var N=z.length,B=-1,L,W="";++B<N;)L=z[B],L>65535&&(L-=65536,W+=t(L>>>10&1023|55296),L=56320|L&1023),W+=t(L);return W}function p(z,N){if(z>=55296&&z<=57343){if(N)throw Error("Lone surrogate U+"+z.toString(16).toUpperCase()+" is not a scalar value");return!1}return!0}function h(z,N){return t(z>>N&63|128)}function x(z,N){if((z&4294967168)==0)return t(z);var B="";return(z&4294965248)==0?B=t(z>>6&31|192):(z&4294901760)==0?(p(z,N)||(z=65533),B=t(z>>12&15|224),B+=h(z,6)):(z&4292870144)==0&&(B=t(z>>18&7|240),B+=h(z,12),B+=h(z,6)),B+=t(z&63|128),B}function j(z,N){N=N||{};for(var B=N.strict!==!1,L=u(z),W=L.length,H=-1,V,J="";++H<W;)V=L[H],J+=x(V,B);return J}function b(){if(I>=O)throw Error("Invalid byte index");var z=$[I]&255;if(I++,(z&192)==128)return z&63;throw Error("Invalid continuation byte")}function w(z){var N,B,L,W,H;if(I>O)throw Error("Invalid byte index");if(I==O)return!1;if(N=$[I]&255,I++,(N&128)==0)return N;if((N&224)==192){if(B=b(),H=(N&31)<<6|B,H>=128)return H;throw Error("Invalid continuation byte")}if((N&240)==224){if(B=b(),L=b(),H=(N&15)<<12|B<<6|L,H>=2048)return p(H,z)?H:65533;throw Error("Invalid continuation byte")}if((N&248)==240&&(B=b(),L=b(),W=b(),H=(N&7)<<18|B<<12|L<<6|W,H>=65536&&H<=1114111))return H;throw Error("Invalid UTF-8 detected")}var $,O,I;function U(z,N){N=N||{};var B=N.strict!==!1;$=u(z),O=$.length,I=0;for(var L=[],W;(W=w(B))!==!1;)L.push(W);return d(L)}r.exports={version:"2.1.2",encode:j,decode:U}},2317:(r,t,u)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Server=t.BaseServer=void 0;const d=u(1942),p=u(2975),h=u(4434),x=u(3739),j=u(2830),b=u(3814),w=u(1354),$=u(8868),O=u(8007),I=(0,j.default)("engine"),U=Symbol("responseHeaders");function z(G){try{const X=JSON.parse(G);if(typeof X.sid=="string")return X.sid}catch{}}class N extends h.EventEmitter{constructor(X={}){super(),this.middlewares=[],this.clients={},this.clientsCount=0,this.opts=Object.assign({wsEngine:w.Server,pingTimeout:2e4,pingInterval:25e3,upgradeTimeout:1e4,maxHttpBufferSize:1e6,transports:["polling","websocket"],allowUpgrades:!0,httpCompression:{threshold:1024},cors:!1,allowEIO3:!1},X),X.cookie&&(this.opts.cookie=Object.assign({name:"io",path:"/",httpOnly:X.cookie.path!==!1,sameSite:"lax"},X.cookie)),this.opts.cors&&this.use(u(4085)(this.opts.cors)),X.perMessageDeflate&&(this.opts.perMessageDeflate=Object.assign({threshold:1024},X.perMessageDeflate)),this.init()}_computePath(X){let K=(X.path||"/engine.io").replace(/\/$/,"");return X.addTrailingSlash!==!1&&(K+="/"),K}upgrades(X){return this.opts.allowUpgrades?p.default[X].upgradesTo||[]:[]}verify(X,K,Y){const ee=X._query.transport;if(!~this.opts.transports.indexOf(ee)||ee==="webtransport")return I('unknown transport "%s"',ee),Y(L.errors.UNKNOWN_TRANSPORT,{transport:ee});if(J(X.headers.origin)){const ae=X.headers.origin;return X.headers.origin=null,I("origin header invalid"),Y(L.errors.BAD_REQUEST,{name:"INVALID_ORIGIN",origin:ae})}const ie=X._query.sid;if(ie){if(!this.clients.hasOwnProperty(ie))return I('unknown sid "%s"',ie),Y(L.errors.UNKNOWN_SID,{sid:ie});const ae=this.clients[ie].transport.name;if(!K&&ae!==ee)return I("bad request: unexpected transport without upgrade"),Y(L.errors.BAD_REQUEST,{name:"TRANSPORT_MISMATCH",transport:ee,previousTransport:ae})}else return X.method!=="GET"?Y(L.errors.BAD_HANDSHAKE_METHOD,{method:X.method}):ee==="websocket"&&!K?(I("invalid transport upgrade"),Y(L.errors.BAD_REQUEST,{name:"TRANSPORT_HANDSHAKE_ERROR"})):this.opts.allowRequest?this.opts.allowRequest(X,((ae,ne)=>{if(!ne)return Y(L.errors.FORBIDDEN,{message:ae});Y()})):Y();Y()}use(X){this.middlewares.push(X)}_applyMiddlewares(X,K,Y){if(this.middlewares.length===0)return I("no middleware to apply, skipping"),Y();const ee=Q=>{I("applying middleware n\xB0%d",Q+1),this.middlewares[Q](X,K,(ie=>{if(ie)return Y(ie);Q+1<this.middlewares.length?ee(Q+1):Y()}))};ee(0)}close(){I("closing all open clients");for(let X in this.clients)this.clients.hasOwnProperty(X)&&this.clients[X].close(!0);return this.cleanup(),this}generateId(X){return d.generateId()}async handshake(X,K,Y){const ee=K._query.EIO==="4"?4:3;if(ee===3&&!this.opts.allowEIO3){I("unsupported protocol version"),this.emit("connection_error",{req:K,code:L.errors.UNSUPPORTED_PROTOCOL_VERSION,message:L.errorMessages[L.errors.UNSUPPORTED_PROTOCOL_VERSION],context:{protocol:ee}}),Y(L.errors.UNSUPPORTED_PROTOCOL_VERSION);return}let Q;try{Q=await this.generateId(K)}catch(ne){I("error while generating an id"),this.emit("connection_error",{req:K,code:L.errors.BAD_REQUEST,message:L.errorMessages[L.errors.BAD_REQUEST],context:{name:"ID_GENERATION_ERROR",error:ne}}),Y(L.errors.BAD_REQUEST);return}I('handshaking client "%s"',Q);try{var ie=this.createTransport(X,K);X==="polling"?(ie.maxHttpBufferSize=this.opts.maxHttpBufferSize,ie.httpCompression=this.opts.httpCompression):X==="websocket"&&(ie.perMessageDeflate=this.opts.perMessageDeflate)}catch(ne){I('error handshaking to transport "%s"',X),this.emit("connection_error",{req:K,code:L.errors.BAD_REQUEST,message:L.errorMessages[L.errors.BAD_REQUEST],context:{name:"TRANSPORT_HANDSHAKE_ERROR",error:ne}}),Y(L.errors.BAD_REQUEST);return}const ae=new x.Socket(Q,this,ie,K,ee);return ie.on("headers",((ne,te)=>{!te._query.sid&&(this.opts.cookie&&(ne["Set-Cookie"]=[(0,b.serialize)(this.opts.cookie.name,Q,this.opts.cookie)]),this.emit("initial_headers",ne,te)),this.emit("headers",ne,te)})),ie.onRequest(K),this.clients[Q]=ae,this.clientsCount++,ae.once("close",(()=>{delete this.clients[Q],this.clientsCount--})),this.emit("connection",ae),ie}async onWebTransportSession(X){const K=setTimeout((()=>{I("the client failed to establish a bidirectional stream in the given period"),X.close()}),this.opts.upgradeTimeout),ee=await X.incomingBidirectionalStreams.getReader().read();if(ee.done){I("session is closed");return}const Q=ee.value,ie=(0,O.createPacketDecoderStream)(this.opts.maxHttpBufferSize,"nodebuffer"),ae=Q.readable.pipeThrough(ie).getReader(),{value:ne,done:te}=await ae.read();if(te){I("stream is closed");return}if(clearTimeout(K),ne.type!=="open")return I("invalid WebTransport handshake"),X.close();if(ne.data===void 0){const ke=new $.WebTransport(X,Q,ae),xe=d.generateId();I('handshaking client "%s" (WebTransport)',xe);const _e=new x.Socket(xe,this,ke,null,4);this.clients[xe]=_e,this.clientsCount++,_e.once("close",(()=>{delete this.clients[xe],this.clientsCount--})),this.emit("connection",_e);return}const oe=z(ne.data);if(!oe)return I("invalid WebTransport handshake"),X.close();const de=this.clients[oe];if(!de)I("upgrade attempt for closed client"),X.close();else if(de.upgrading)I("transport has already been trying to upgrade"),X.close();else if(de.upgraded)I("transport had already been upgraded"),X.close();else{I("upgrading existing transport");const ke=new $.WebTransport(X,Q,ae);de._maybeUpgrade(ke)}}}t.BaseServer=N,N.errors={UNKNOWN_TRANSPORT:0,UNKNOWN_SID:1,BAD_HANDSHAKE_METHOD:2,BAD_REQUEST:3,FORBIDDEN:4,UNSUPPORTED_PROTOCOL_VERSION:5},N.errorMessages={0:"Transport unknown",1:"Session ID unknown",2:"Bad handshake method",3:"Bad request",4:"Forbidden",5:"Unsupported protocol version"};class B{constructor(X,K){this.req=X,this.socket=K,X[U]={}}setHeader(X,K){this.req[U][X]=K}getHeader(X){return this.req[U][X]}removeHeader(X){delete this.req[U][X]}write(){}writeHead(){}end(){this.socket.destroy()}}class L extends N{init(){~this.opts.transports.indexOf("websocket")&&(this.ws&&this.ws.close(),this.ws=new this.opts.wsEngine({noServer:!0,clientTracking:!1,perMessageDeflate:this.opts.perMessageDeflate,maxPayload:this.opts.maxHttpBufferSize}),typeof this.ws.on=="function"&&this.ws.on("headers",((X,K)=>{const Y=K[U]||{};delete K[U],!K._query.sid&&this.emit("initial_headers",Y,K),this.emit("headers",Y,K),I("writing headers: %j",Y),Object.keys(Y).forEach((Q=>{X.push(`${Q}: ${Y[Q]}`)}))})))}cleanup(){this.ws&&(I("closing webSocketServer"),this.ws.close())}prepare(X){if(!X._query){const K=new URL(X.url,"https://socket.io");X._query=Object.fromEntries(K.searchParams.entries())}}createTransport(X,K){return new p.default[X](K)}handleRequest(X,K){I('handling "%s" http request "%s"',X.method,X.url),this.prepare(X),X.res=K;const Y=(ee,Q)=>{if(ee!==void 0){this.emit("connection_error",{req:X,code:ee,message:L.errorMessages[ee],context:Q}),W(K,ee,Q);return}if(X._query.sid)I("setting new request for existing client"),this.clients[X._query.sid].transport.onRequest(X);else{const ie=(ae,ne)=>W(K,ae,ne);this.handshake(X._query.transport,X,ie)}};this._applyMiddlewares(X,K,(ee=>{ee?Y(L.errors.BAD_REQUEST,{name:"MIDDLEWARE_FAILURE"}):this.verify(X,!1,Y)}))}handleUpgrade(X,K,Y){this.prepare(X);const ee=new B(X,K),Q=(ie,ae)=>{if(ie!==void 0){this.emit("connection_error",{req:X,code:ie,message:L.errorMessages[ie],context:ae}),H(K,ie,ae);return}const ne=Buffer.from(Y);Y=null,ee.writeHead(),this.ws.handleUpgrade(X,K,ne,(te=>{this.onWebSocket(X,K,te)}))};this._applyMiddlewares(X,ee,(ie=>{ie?Q(L.errors.BAD_REQUEST,{name:"MIDDLEWARE_FAILURE"}):this.verify(X,!0,Q)}))}onWebSocket(X,K,Y){if(Y.on("error",Q),p.default[X._query.transport]!==void 0&&!p.default[X._query.transport].prototype.handlesUpgrades){I("transport doesnt handle upgraded requests"),Y.close();return}const ee=X._query.sid;if(X.websocket=Y,ee){const ie=this.clients[ee];if(!ie)I("upgrade attempt for closed client"),Y.close();else if(ie.upgrading)I("transport has already been trying to upgrade"),Y.close();else if(ie.upgraded)I("transport had already been upgraded"),Y.close();else{I("upgrading existing transport"),Y.removeListener("error",Q);const ae=this.createTransport(X._query.transport,X);ae.perMessageDeflate=this.opts.perMessageDeflate,ie._maybeUpgrade(ae)}}else{const ie=(ae,ne)=>H(K,ae,ne);this.handshake(X._query.transport,X,ie)}function Q(){I("websocket error before upgrade")}}attach(X,K={}){const Y=this._computePath(K),ee=K.destroyUpgradeTimeout||1e3;function Q(ae){return Y===ae.url.slice(0,Y.length)}const ie=X.listeners("request").slice(0);X.removeAllListeners("request"),X.on("close",this.close.bind(this)),X.on("listening",this.init.bind(this)),X.on("request",((ae,ne)=>{if(Q(ae))I('intercepting request for path "%s"',Y),this.handleRequest(ae,ne);else{let te=0;const oe=ie.length;for(;te<oe;te++)ie[te].call(X,ae,ne)}})),~this.opts.transports.indexOf("websocket")&&X.on("upgrade",((ae,ne,te)=>{Q(ae)?this.handleUpgrade(ae,ne,te):K.destroyUpgrade!==!1&&setTimeout((function(){if(ne.writable&&ne.bytesWritten<=0)return ne.on("error",(oe=>{I("error while destroying upgrade: %s",oe.message)})),ne.end()}),ee)}))}}t.Server=L;function W(G,X,K){const Y=X===L.errors.FORBIDDEN?403:400,ee=K&&K.message?K.message:L.errorMessages[X];G.writeHead(Y,{"Content-Type":"application/json"}),G.end(JSON.stringify({code:X,message:ee}))}function H(G,X,K={}){if(G.on("error",(()=>{I("ignoring error from closed connection")})),G.writable){const Y=K.message||L.errorMessages[X],ee=Buffer.byteLength(Y);G.write(`HTTP/1.1 400 Bad Request\r
360
+ `+Y)}function G(X,K,Y,ee,Q,ie){if(X.listenerCount("wsClientError")){const ae=new Error(Q);Error.captureStackTrace(ae,G),X.emit("wsClientError",ae,Y,K)}else J(Y,ee,Q,ie)}},6681:(r,t,u)=>{const d=u(4434),p=u(5692),h=u(8611),x=u(9278),j=u(4756),{randomBytes:b,createHash:w}=u(6982),{Duplex:$,Readable:O}=u(2203),{URL:I}=u(7016),U=u(4376),z=u(893),N=u(7389),{isBlob:B}=u(6615),{BINARY_TYPES:L,EMPTY_BUFFER:W,GUID:H,kForOnEventAttribute:V,kListener:J,kStatusCode:G,kWebSocket:X,NOOP:K}=u(1791),{EventTarget:{addEventListener:Y,removeEventListener:ee}}=u(4634),{format:Q,parse:ie}=u(1335),{toBuffer:ae}=u(5803),ne=30*1e3,te=Symbol("kAborted"),oe=[8,13],de=["CONNECTING","OPEN","CLOSING","CLOSED"],ke=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;class xe extends d{constructor(Ee,Oe,Ne){super(),this._binaryType=L[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=W,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=xe.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,Ee!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,Oe===void 0?Oe=[]:Array.isArray(Oe)||(typeof Oe=="object"&&Oe!==null?(Ne=Oe,Oe=[]):Oe=[Oe]),_e(this,Ee,Oe,Ne)):(this._autoPong=Ne.autoPong,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(Ee){L.includes(Ee)&&(this._binaryType=Ee,this._receiver&&(this._receiver._binaryType=Ee))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(Ee,Oe,Ne){const Ae=new z({allowSynchronousEvents:Ne.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:Ne.maxPayload,skipUTF8Validation:Ne.skipUTF8Validation}),qe=new N(Ee,this._extensions,Ne.generateMask);this._receiver=Ae,this._sender=qe,this._socket=Ee,Ae[X]=this,qe[X]=this,Ee[X]=this,Ae.on("conclude",he),Ae.on("drain",ve),Ae.on("error",je),Ae.on("message",ge),Ae.on("ping",be),Ae.on("pong",pe),qe.onerror=Se,Ee.setTimeout&&Ee.setTimeout(0),Ee.setNoDelay&&Ee.setNoDelay(),Oe.length>0&&Ee.unshift(Oe),Ee.on("close",ue),Ee.on("data",$e),Ee.on("end",Ie),Ee.on("error",Re),this._readyState=xe.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=xe.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[U.extensionName]&&this._extensions[U.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=xe.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(Ee,Oe){if(this.readyState!==xe.CLOSED){if(this.readyState===xe.CONNECTING){re(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===xe.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=xe.CLOSING,this._sender.close(Ee,Oe,!this._isServer,(Ne=>{Ne||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())})),le(this)}}pause(){this.readyState===xe.CONNECTING||this.readyState===xe.CLOSED||(this._paused=!0,this._socket.pause())}ping(Ee,Oe,Ne){if(this.readyState===xe.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof Ee=="function"?(Ne=Ee,Ee=Oe=void 0):typeof Oe=="function"&&(Ne=Oe,Oe=void 0),typeof Ee=="number"&&(Ee=Ee.toString()),this.readyState!==xe.OPEN){ce(this,Ee,Ne);return}Oe===void 0&&(Oe=!this._isServer),this._sender.ping(Ee||W,Oe,Ne)}pong(Ee,Oe,Ne){if(this.readyState===xe.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof Ee=="function"?(Ne=Ee,Ee=Oe=void 0):typeof Oe=="function"&&(Ne=Oe,Oe=void 0),typeof Ee=="number"&&(Ee=Ee.toString()),this.readyState!==xe.OPEN){ce(this,Ee,Ne);return}Oe===void 0&&(Oe=!this._isServer),this._sender.pong(Ee||W,Oe,Ne)}resume(){this.readyState===xe.CONNECTING||this.readyState===xe.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(Ee,Oe,Ne){if(this.readyState===xe.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof Oe=="function"&&(Ne=Oe,Oe={}),typeof Ee=="number"&&(Ee=Ee.toString()),this.readyState!==xe.OPEN){ce(this,Ee,Ne);return}const Ae={binary:typeof Ee!="string",mask:!this._isServer,compress:!0,fin:!0,...Oe};this._extensions[U.extensionName]||(Ae.compress=!1),this._sender.send(Ee||W,Ae,Ne)}terminate(){if(this.readyState!==xe.CLOSED){if(this.readyState===xe.CONNECTING){re(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=xe.CLOSING,this._socket.destroy())}}}Object.defineProperty(xe,"CONNECTING",{enumerable:!0,value:de.indexOf("CONNECTING")}),Object.defineProperty(xe.prototype,"CONNECTING",{enumerable:!0,value:de.indexOf("CONNECTING")}),Object.defineProperty(xe,"OPEN",{enumerable:!0,value:de.indexOf("OPEN")}),Object.defineProperty(xe.prototype,"OPEN",{enumerable:!0,value:de.indexOf("OPEN")}),Object.defineProperty(xe,"CLOSING",{enumerable:!0,value:de.indexOf("CLOSING")}),Object.defineProperty(xe.prototype,"CLOSING",{enumerable:!0,value:de.indexOf("CLOSING")}),Object.defineProperty(xe,"CLOSED",{enumerable:!0,value:de.indexOf("CLOSED")}),Object.defineProperty(xe.prototype,"CLOSED",{enumerable:!0,value:de.indexOf("CLOSED")}),["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach((we=>{Object.defineProperty(xe.prototype,we,{enumerable:!0})})),["open","error","close","message"].forEach((we=>{Object.defineProperty(xe.prototype,`on${we}`,{enumerable:!0,get(){for(const Ee of this.listeners(we))if(Ee[V])return Ee[J];return null},set(Ee){for(const Oe of this.listeners(we))if(Oe[V]){this.removeListener(we,Oe);break}typeof Ee=="function"&&this.addEventListener(we,Ee,{[V]:!0})}})})),xe.prototype.addEventListener=Y,xe.prototype.removeEventListener=ee,r.exports=xe;function _e(we,Ee,Oe,Ne){const Ae={allowSynchronousEvents:!0,autoPong:!0,protocolVersion:oe[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...Ne,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(we._autoPong=Ae.autoPong,!oe.includes(Ae.protocolVersion))throw new RangeError(`Unsupported protocol version: ${Ae.protocolVersion} (supported versions: ${oe.join(", ")})`);let qe;if(Ee instanceof I)qe=Ee;else try{qe=new I(Ee)}catch{throw new SyntaxError(`Invalid URL: ${Ee}`)}qe.protocol==="http:"?qe.protocol="ws:":qe.protocol==="https:"&&(qe.protocol="wss:"),we._url=qe.href;const De=qe.protocol==="wss:",ze=qe.protocol==="ws+unix:";let Fe;if(qe.protocol!=="ws:"&&!De&&!ze?Fe=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:ze&&!qe.pathname?Fe="The URL's pathname is empty":qe.hash&&(Fe="The URL contains a fragment identifier"),Fe){const Be=new SyntaxError(Fe);if(we._redirects===0)throw Be;se(we,Be);return}const Ge=De?443:80,Me=b(16).toString("base64"),Ve=De?p.request:h.request,Je=new Set;let ai;if(Ae.createConnection=Ae.createConnection||(De?fe:ye),Ae.defaultPort=Ae.defaultPort||Ge,Ae.port=qe.port||Ge,Ae.host=qe.hostname.startsWith("[")?qe.hostname.slice(1,-1):qe.hostname,Ae.headers={...Ae.headers,"Sec-WebSocket-Version":Ae.protocolVersion,"Sec-WebSocket-Key":Me,Connection:"Upgrade",Upgrade:"websocket"},Ae.path=qe.pathname+qe.search,Ae.timeout=Ae.handshakeTimeout,Ae.perMessageDeflate&&(ai=new U(Ae.perMessageDeflate!==!0?Ae.perMessageDeflate:{},!1,Ae.maxPayload),Ae.headers["Sec-WebSocket-Extensions"]=Q({[U.extensionName]:ai.offer()})),Oe.length){for(const Be of Oe){if(typeof Be!="string"||!ke.test(Be)||Je.has(Be))throw new SyntaxError("An invalid or duplicated subprotocol was specified");Je.add(Be)}Ae.headers["Sec-WebSocket-Protocol"]=Oe.join(",")}if(Ae.origin&&(Ae.protocolVersion<13?Ae.headers["Sec-WebSocket-Origin"]=Ae.origin:Ae.headers.Origin=Ae.origin),(qe.username||qe.password)&&(Ae.auth=`${qe.username}:${qe.password}`),ze){const Be=Ae.path.split(":");Ae.socketPath=Be[0],Ae.path=Be[1]}let We;if(Ae.followRedirects){if(we._redirects===0){we._originalIpc=ze,we._originalSecure=De,we._originalHostOrSocketPath=ze?Ae.socketPath:qe.host;const Be=Ne&&Ne.headers;if(Ne={...Ne,headers:{}},Be)for(const[Ke,ei]of Object.entries(Be))Ne.headers[Ke.toLowerCase()]=ei}else if(we.listenerCount("redirect")===0){const Be=ze?we._originalIpc?Ae.socketPath===we._originalHostOrSocketPath:!1:we._originalIpc?!1:qe.host===we._originalHostOrSocketPath;(!Be||we._originalSecure&&!De)&&(delete Ae.headers.authorization,delete Ae.headers.cookie,Be||delete Ae.headers.host,Ae.auth=void 0)}Ae.auth&&!Ne.headers.authorization&&(Ne.headers.authorization="Basic "+Buffer.from(Ae.auth).toString("base64")),We=we._req=Ve(Ae),we._redirects&&we.emit("redirect",we.url,We)}else We=we._req=Ve(Ae);Ae.timeout&&We.on("timeout",(()=>{re(we,We,"Opening handshake has timed out")})),We.on("error",(Be=>{We===null||We[te]||(We=we._req=null,se(we,Be))})),We.on("response",(Be=>{const Ke=Be.headers.location,ei=Be.statusCode;if(Ke&&Ae.followRedirects&&ei>=300&&ei<400){if(++we._redirects>Ae.maxRedirects){re(we,We,"Maximum redirects exceeded");return}We.abort();let ii;try{ii=new I(Ke,Ee)}catch{const Pe=new SyntaxError(`Invalid URL: ${Ke}`);se(we,Pe);return}_e(we,ii,Oe,Ne)}else we.emit("unexpected-response",We,Be)||re(we,We,`Unexpected server response: ${Be.statusCode}`)})),We.on("upgrade",((Be,Ke,ei)=>{if(we.emit("upgrade",Be),we.readyState!==xe.CONNECTING)return;We=we._req=null;const ii=Be.headers.upgrade;if(ii===void 0||ii.toLowerCase()!=="websocket"){re(we,Ke,"Invalid Upgrade header");return}const Te=w("sha1").update(Me+H).digest("base64");if(Be.headers["sec-websocket-accept"]!==Te){re(we,Ke,"Invalid Sec-WebSocket-Accept header");return}const Pe=Be.headers["sec-websocket-protocol"];let Le;if(Pe!==void 0?Je.size?Je.has(Pe)||(Le="Server sent an invalid subprotocol"):Le="Server sent a subprotocol but none was requested":Je.size&&(Le="Server sent no subprotocol"),Le){re(we,Ke,Le);return}Pe&&(we._protocol=Pe);const Ze=Be.headers["sec-websocket-extensions"];if(Ze!==void 0){if(!ai){re(we,Ke,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let He;try{He=ie(Ze)}catch{re(we,Ke,"Invalid Sec-WebSocket-Extensions header");return}const Ue=Object.keys(He);if(Ue.length!==1||Ue[0]!==U.extensionName){re(we,Ke,"Server indicated an extension that was not requested");return}try{ai.accept(He[U.extensionName])}catch{re(we,Ke,"Invalid Sec-WebSocket-Extensions header");return}we._extensions[U.extensionName]=ai}we.setSocket(Ke,ei,{allowSynchronousEvents:Ae.allowSynchronousEvents,generateMask:Ae.generateMask,maxPayload:Ae.maxPayload,skipUTF8Validation:Ae.skipUTF8Validation})})),Ae.finishRequest?Ae.finishRequest(We,we):We.end()}function se(we,Ee){we._readyState=xe.CLOSING,we._errorEmitted=!0,we.emit("error",Ee),we.emitClose()}function ye(we){return we.path=we.socketPath,x.connect(we)}function fe(we){return we.path=void 0,!we.servername&&we.servername!==""&&(we.servername=x.isIP(we.host)?"":we.host),j.connect(we)}function re(we,Ee,Oe){we._readyState=xe.CLOSING;const Ne=new Error(Oe);Error.captureStackTrace(Ne,re),Ee.setHeader?(Ee[te]=!0,Ee.abort(),Ee.socket&&!Ee.socket.destroyed&&Ee.socket.destroy(),process.nextTick(se,we,Ne)):(Ee.destroy(Ne),Ee.once("error",we.emit.bind(we,"error")),Ee.once("close",we.emitClose.bind(we)))}function ce(we,Ee,Oe){if(Ee){const Ne=B(Ee)?Ee.size:ae(Ee).length;we._socket?we._sender._bufferedBytes+=Ne:we._bufferedAmount+=Ne}if(Oe){const Ne=new Error(`WebSocket is not open: readyState ${we.readyState} (${de[we.readyState]})`);process.nextTick(Oe,Ne)}}function he(we,Ee){const Oe=this[X];Oe._closeFrameReceived=!0,Oe._closeMessage=Ee,Oe._closeCode=we,Oe._socket[X]!==void 0&&(Oe._socket.removeListener("data",$e),process.nextTick(me,Oe._socket),we===1005?Oe.close():Oe.close(we,Ee))}function ve(){const we=this[X];we.isPaused||we._socket.resume()}function je(we){const Ee=this[X];Ee._socket[X]!==void 0&&(Ee._socket.removeListener("data",$e),process.nextTick(me,Ee._socket),Ee.close(we[G])),Ee._errorEmitted||(Ee._errorEmitted=!0,Ee.emit("error",we))}function Ce(){this[X].emitClose()}function ge(we,Ee){this[X].emit("message",we,Ee)}function be(we){const Ee=this[X];Ee._autoPong&&Ee.pong(we,!this._isServer,K),Ee.emit("ping",we)}function pe(we){this[X].emit("pong",we)}function me(we){we.resume()}function Se(we){const Ee=this[X];Ee.readyState!==xe.CLOSED&&(Ee.readyState===xe.OPEN&&(Ee._readyState=xe.CLOSING,le(Ee)),this._socket.end(),Ee._errorEmitted||(Ee._errorEmitted=!0,Ee.emit("error",we)))}function le(we){we._closeTimer=setTimeout(we._socket.destroy.bind(we._socket),ne)}function ue(){const we=this[X];this.removeListener("close",ue),this.removeListener("data",$e),this.removeListener("end",Ie),we._readyState=xe.CLOSING;let Ee;!this._readableState.endEmitted&&!we._closeFrameReceived&&!we._receiver._writableState.errorEmitted&&(Ee=we._socket.read())!==null&&we._receiver.write(Ee),we._receiver.end(),this[X]=void 0,clearTimeout(we._closeTimer),we._receiver._writableState.finished||we._receiver._writableState.errorEmitted?we.emitClose():(we._receiver.on("error",Ce),we._receiver.on("finish",Ce))}function $e(we){this[X]._receiver.write(we)||this.pause()}function Ie(){const we=this[X];we._readyState=xe.CLOSING,we._receiver.end(),this.end()}function Re(){const we=this[X];this.removeListener("error",Re),this.on("error",K),we&&(we._readyState=xe.CLOSING,this.destroy())}},8327:module=>{module.exports=eval("require")("bufferutil")},75:module=>{module.exports=eval("require")("supports-color")},2414:module=>{module.exports=eval("require")("utf-8-validate")},2613:r=>{r.exports=__WEBPACK_EXTERNAL_createRequire(import.meta.url)("assert")},290:r=>{r.exports=__WEBPACK_EXTERNAL_createRequire(import.meta.url)("async_hooks")},181:r=>{r.exports=__WEBPACK_EXTERNAL_createRequire(import.meta.url)("buffer")},6982:r=>{r.exports=__WEBPACK_EXTERNAL_createRequire(import.meta.url)("crypto")},4434:r=>{r.exports=__WEBPACK_EXTERNAL_createRequire(import.meta.url)("events")},9896:r=>{r.exports=__WEBPACK_EXTERNAL_createRequire(import.meta.url)("fs")},8611:r=>{r.exports=__WEBPACK_EXTERNAL_createRequire(import.meta.url)("http")},5692:r=>{r.exports=__WEBPACK_EXTERNAL_createRequire(import.meta.url)("https")},9278:r=>{r.exports=__WEBPACK_EXTERNAL_createRequire(import.meta.url)("net")},4573:r=>{r.exports=__WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:buffer")},8474:r=>{r.exports=__WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:events")},3024:r=>{r.exports=__WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:fs")},7067:r=>{r.exports=__WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:http")},7030:r=>{r.exports=__WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:net")},6760:r=>{r.exports=__WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:path")},1792:r=>{r.exports=__WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:querystring")},8522:r=>{r.exports=__WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:zlib")},857:r=>{r.exports=__WEBPACK_EXTERNAL_createRequire(import.meta.url)("os")},6928:r=>{r.exports=__WEBPACK_EXTERNAL_createRequire(import.meta.url)("path")},3480:r=>{r.exports=__WEBPACK_EXTERNAL_createRequire(import.meta.url)("querystring")},2203:r=>{r.exports=__WEBPACK_EXTERNAL_createRequire(import.meta.url)("stream")},3193:r=>{r.exports=__WEBPACK_EXTERNAL_createRequire(import.meta.url)("string_decoder")},3557:r=>{r.exports=__WEBPACK_EXTERNAL_createRequire(import.meta.url)("timers")},4756:r=>{r.exports=__WEBPACK_EXTERNAL_createRequire(import.meta.url)("tls")},2018:r=>{r.exports=__WEBPACK_EXTERNAL_createRequire(import.meta.url)("tty")},7016:r=>{r.exports=__WEBPACK_EXTERNAL_createRequire(import.meta.url)("url")},9023:r=>{r.exports=__WEBPACK_EXTERNAL_createRequire(import.meta.url)("util")},3106:r=>{r.exports=__WEBPACK_EXTERNAL_createRequire(import.meta.url)("zlib")},2998:(r,t)=>{t.Emitter=u;function u(p){if(p)return d(p)}function d(p){for(var h in u.prototype)p[h]=u.prototype[h];return p}u.prototype.on=u.prototype.addEventListener=function(p,h){return this._callbacks=this._callbacks||{},(this._callbacks["$"+p]=this._callbacks["$"+p]||[]).push(h),this},u.prototype.once=function(p,h){function x(){this.off(p,x),h.apply(this,arguments)}return x.fn=h,this.on(p,x),this},u.prototype.off=u.prototype.removeListener=u.prototype.removeAllListeners=u.prototype.removeEventListener=function(p,h){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var x=this._callbacks["$"+p];if(!x)return this;if(arguments.length==1)return delete this._callbacks["$"+p],this;for(var j,b=0;b<x.length;b++)if(j=x[b],j===h||j.fn===h){x.splice(b,1);break}return x.length===0&&delete this._callbacks["$"+p],this},u.prototype.emit=function(p){this._callbacks=this._callbacks||{};for(var h=new Array(arguments.length-1),x=this._callbacks["$"+p],j=1;j<arguments.length;j++)h[j-1]=arguments[j];if(x){x=x.slice(0);for(var j=0,b=x.length;j<b;++j)x[j].apply(this,h)}return this},u.prototype.emitReserved=u.prototype.emit,u.prototype.listeners=function(p){return this._callbacks=this._callbacks||{},this._callbacks["$"+p]||[]},u.prototype.hasListeners=function(p){return!!this.listeners(p).length}},2717:(r,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ERROR_PACKET=t.PACKET_TYPES_REVERSE=t.PACKET_TYPES=void 0;const u=Object.create(null);t.PACKET_TYPES=u,u.open="0",u.close="1",u.ping="2",u.pong="3",u.message="4",u.upgrade="5",u.noop="6";const d=Object.create(null);t.PACKET_TYPES_REVERSE=d,Object.keys(u).forEach((h=>{d[u[h]]=h}));const p={type:"error",data:"parser error"};t.ERROR_PACKET=p},3377:(r,t,u)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.decodePacket=void 0;const d=u(2717),p=(x,j)=>{if(typeof x!="string")return{type:"message",data:h(x,j)};const b=x.charAt(0);if(b==="b"){const w=Buffer.from(x.substring(1),"base64");return{type:"message",data:h(w,j)}}return d.PACKET_TYPES_REVERSE[b]?x.length>1?{type:d.PACKET_TYPES_REVERSE[b],data:x.substring(1)}:{type:d.PACKET_TYPES_REVERSE[b]}:d.ERROR_PACKET};t.decodePacket=p;const h=(x,j)=>j==="arraybuffer"?x instanceof ArrayBuffer?x:Buffer.isBuffer(x)?x.buffer.slice(x.byteOffset,x.byteOffset+x.byteLength):x.buffer:Buffer.isBuffer(x)?x:Buffer.from(x)},5897:(r,t,u)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.encodePacket=void 0,t.encodePacketToBinary=j;const d=u(2717),p=({type:b,data:w},$,O)=>w instanceof ArrayBuffer||ArrayBuffer.isView(w)?O($?w:"b"+h(w,!0).toString("base64")):O(d.PACKET_TYPES[b]+(w||""));t.encodePacket=p;const h=(b,w)=>Buffer.isBuffer(b)||b instanceof Uint8Array&&!w?b:b instanceof ArrayBuffer?Buffer.from(b):Buffer.from(b.buffer,b.byteOffset,b.byteLength);let x;function j(b,w){if(b.data instanceof ArrayBuffer||ArrayBuffer.isView(b.data))return w(h(b.data,!1));(0,t.encodePacket)(b,!0,($=>{x||(x=new TextEncoder),w(x.encode($))}))}},8007:(r,t,u)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.decodePayload=t.decodePacket=t.encodePayload=t.encodePacket=t.protocol=void 0,t.createPacketEncoderStream=w,t.createPacketDecoderStream=U;const d=u(5897);Object.defineProperty(t,"encodePacket",{enumerable:!0,get:function(){return d.encodePacket}});const p=u(3377);Object.defineProperty(t,"decodePacket",{enumerable:!0,get:function(){return p.decodePacket}});const h=u(2717),x="",j=(z,N)=>{const B=z.length,L=new Array(B);let W=0;z.forEach(((H,V)=>{(0,d.encodePacket)(H,!1,(J=>{L[V]=J,++W===B&&N(L.join(x))}))}))};t.encodePayload=j;const b=(z,N)=>{const B=z.split(x),L=[];for(let W=0;W<B.length;W++){const H=(0,p.decodePacket)(B[W],N);if(L.push(H),H.type==="error")break}return L};t.decodePayload=b;function w(){return new TransformStream({transform(z,N){(0,d.encodePacketToBinary)(z,(B=>{const L=B.length;let W;if(L<126)W=new Uint8Array(1),new DataView(W.buffer).setUint8(0,L);else if(L<65536){W=new Uint8Array(3);const H=new DataView(W.buffer);H.setUint8(0,126),H.setUint16(1,L)}else{W=new Uint8Array(9);const H=new DataView(W.buffer);H.setUint8(0,127),H.setBigUint64(1,BigInt(L))}z.data&&typeof z.data!="string"&&(W[0]|=128),N.enqueue(W),N.enqueue(B)}))}})}let $;function O(z){return z.reduce(((N,B)=>N+B.length),0)}function I(z,N){if(z[0].length===N)return z.shift();const B=new Uint8Array(N);let L=0;for(let W=0;W<N;W++)B[W]=z[0][L++],L===z[0].length&&(z.shift(),L=0);return z.length&&L<z[0].length&&(z[0]=z[0].slice(L)),B}function U(z,N){$||($=new TextDecoder);const B=[];let L=0,W=-1,H=!1;return new TransformStream({transform(V,J){for(B.push(V);;){if(L===0){if(O(B)<1)break;const G=I(B,1);H=(G[0]&128)===128,W=G[0]&127,W<126?L=3:W===126?L=1:L=2}else if(L===1){if(O(B)<2)break;const G=I(B,2);W=new DataView(G.buffer,G.byteOffset,G.length).getUint16(0),L=3}else if(L===2){if(O(B)<8)break;const G=I(B,8),X=new DataView(G.buffer,G.byteOffset,G.length),K=X.getUint32(0);if(K>Math.pow(2,21)-1){J.enqueue(h.ERROR_PACKET);break}W=K*Math.pow(2,32)+X.getUint32(4),L=3}else{if(O(B)<W)break;const G=I(B,W);J.enqueue((0,p.decodePacket)(H?G:$.decode(G),N)),L=0}if(W===0||W>z){J.enqueue(h.ERROR_PACKET);break}}}})}t.protocol=4},68:(r,t,u)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.protocol=t.Transport=t.Socket=t.uServer=t.parser=t.transports=t.Server=void 0,t.listen=$,t.attach=O;const d=u(8611),p=u(2317);Object.defineProperty(t,"Server",{enumerable:!0,get:function(){return p.Server}});const h=u(2975);t.transports=h.default;const x=u(8007);t.parser=x;var j=u(2056);Object.defineProperty(t,"uServer",{enumerable:!0,get:function(){return j.uServer}});var b=u(3739);Object.defineProperty(t,"Socket",{enumerable:!0,get:function(){return b.Socket}});var w=u(4621);Object.defineProperty(t,"Transport",{enumerable:!0,get:function(){return w.Transport}}),t.protocol=x.protocol;function $(I,U,z){typeof U=="function"&&(z=U,U={});const N=(0,d.createServer)((function(L,W){W.writeHead(501),W.end("Not Implemented")})),B=O(N,U);return B.httpServer=N,N.listen(I,z),B}function O(I,U){const z=new p.Server(U);return z.attach(I,U),z}},2674:(r,t,u)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.packets=t.protocol=void 0,t.encodePacket=b,t.encodeBase64Packet=$,t.decodePacket=O,t.decodeBase64Packet=U,t.encodePayload=z,t.decodePayload=L,t.encodePayloadAsBinary=J,t.decodePayloadAsBinary=X;var d=u(4875);t.protocol=3;const p=K=>{for(const Y of K)if(Y.data instanceof ArrayBuffer||ArrayBuffer.isView(Y.data))return!0;return!1};t.packets={open:0,close:1,ping:2,pong:3,message:4,upgrade:5,noop:6};var h=Object.keys(t.packets),x={type:"error",data:"parser error"};const j=Buffer.concat([]);function b(K,Y,ee,Q){if(typeof Y=="function"&&(Q=Y,Y=null),typeof ee=="function"&&(Q=ee,ee=null),Buffer.isBuffer(K.data))return w(K,Y,Q);if(K.data&&(K.data.buffer||K.data)instanceof ArrayBuffer)return w({type:K.type,data:V(K.data)},Y,Q);var ie=t.packets[K.type];return K.data!==void 0&&(ie+=ee?d.encode(String(K.data),{strict:!1}):String(K.data)),Q(""+ie)}function w(K,Y,ee){if(!Y)return $(K,ee);var Q=K.data,ie=Buffer.allocUnsafe(1);return ie[0]=t.packets[K.type],ee(Buffer.concat([ie,Q]))}function $(K,Y){var ee=Buffer.isBuffer(K.data)?K.data:V(K.data),Q="b"+t.packets[K.type];return Q+=ee.toString("base64"),Y(Q)}function O(K,Y,ee){if(K===void 0)return x;let Q;if(typeof K=="string")return Q=K.charAt(0),Q==="b"?U(K.slice(1),Y):ee&&(K=I(K),K===!1)||Number(Q)!=Q||!h[Q]?x:K.length>1?{type:h[Q],data:K.slice(1)}:{type:h[Q]};if(Y==="arraybuffer"){var ie=new Uint8Array(K);return Q=ie[0],{type:h[Q],data:ie.buffer.slice(1)}}return K instanceof ArrayBuffer&&(K=V(K)),Q=K[0],{type:h[Q],data:K.slice(1)}}function I(K){try{K=d.decode(K,{strict:!1})}catch{return!1}return K}function U(K,Y){var ee=h[K.charAt(0)],Q=Buffer.from(K.slice(1),"base64");if(Y==="arraybuffer"){for(var ie=new Uint8Array(Q.length),ae=0;ae<ie.length;ae++)ie[ae]=Q[ae];Q=ie.buffer}return{type:ee,data:Q}}function z(K,Y,ee){if(typeof Y=="function"&&(ee=Y,Y=null),Y&&p(K))return J(K,ee);if(!K.length)return ee("0:");function Q(ie,ae){b(ie,Y,!1,(function(ne){ae(null,N(ne))}))}B(K,Q,(function(ie,ae){return ee(ae.join(""))}))}function N(K){return K.length+":"+K}function B(K,Y,ee){const Q=new Array(K.length);let ie=0;for(let ae=0;ae<K.length;ae++)Y(K[ae],((ne,te)=>{Q[ae]=te,++ie===K.length&&ee(null,Q)}))}function L(K,Y,ee){if(typeof K!="string")return X(K,Y,ee);if(typeof Y=="function"&&(ee=Y,Y=null),K==="")return ee(x,0,1);for(var Q="",ie,ae,ne,te=0,oe=K.length;te<oe;te++){var de=K.charAt(te);if(de!==":"){Q+=de;continue}if(Q===""||Q!=(ie=Number(Q))||(ae=K.slice(te+1,te+1+ie),Q!=ae.length))return ee(x,0,1);if(ae.length){if(ne=O(ae,Y,!1),x.type===ne.type&&x.data===ne.data)return ee(x,0,1);var ke=ee(ne,te+ie,oe);if(ke===!1)return}te+=ie,Q=""}if(Q!=="")return ee(x,0,1)}function W(K){for(var Y="",ee=0,Q=K.length;ee<Q;ee++)Y+=String.fromCharCode(K[ee]);return Y}function H(K){for(var Y=Buffer.allocUnsafe(K.length),ee=0,Q=K.length;ee<Q;ee++)Y.writeUInt8(K.charCodeAt(ee),ee);return Y}function V(K){var Y=K.byteLength||K.length,ee=K.byteOffset||0;return Buffer.from(K.buffer||K,ee,Y)}function J(K,Y){if(!K.length)return Y(j);B(K,G,(function(ee,Q){return Y(Buffer.concat(Q))}))}function G(K,Y){function ee(Q){var ie=""+Q.length,ae;if(typeof Q=="string"){ae=Buffer.allocUnsafe(ie.length+2),ae[0]=0;for(var ne=0;ne<ie.length;ne++)ae[ne+1]=parseInt(ie[ne],10);return ae[ae.length-1]=255,Y(null,Buffer.concat([ae,H(Q)]))}ae=Buffer.allocUnsafe(ie.length+2),ae[0]=1;for(var ne=0;ne<ie.length;ne++)ae[ne+1]=parseInt(ie[ne],10);ae[ae.length-1]=255,Y(null,Buffer.concat([ae,Q]))}b(K,!0,!0,ee)}function X(K,Y,ee){typeof Y=="function"&&(ee=Y,Y=null);for(var Q=K,ie=[],ae;Q.length>0;){var ne="",te=Q[0]===0;for(ae=1;Q[ae]!==255;ae++){if(ne.length>310)return ee(x,0,1);ne+=""+Q[ae]}Q=Q.slice(ne.length+1);var oe=parseInt(ne,10),de=Q.slice(1,oe+1);te&&(de=W(de)),ie.push(de),Q=Q.slice(oe+1)}var ke=ie.length;for(ae=0;ae<ke;ae++){var xe=ie[ae];ee(O(xe,Y,!0),ae,ke)}}},4875:r=>{/*! https://mths.be/utf8js v2.1.2 by @mathias */var t=String.fromCharCode;function u(z){for(var N=[],B=0,L=z.length,W,H;B<L;)W=z.charCodeAt(B++),W>=55296&&W<=56319&&B<L?(H=z.charCodeAt(B++),(H&64512)==56320?N.push(((W&1023)<<10)+(H&1023)+65536):(N.push(W),B--)):N.push(W);return N}function d(z){for(var N=z.length,B=-1,L,W="";++B<N;)L=z[B],L>65535&&(L-=65536,W+=t(L>>>10&1023|55296),L=56320|L&1023),W+=t(L);return W}function p(z,N){if(z>=55296&&z<=57343){if(N)throw Error("Lone surrogate U+"+z.toString(16).toUpperCase()+" is not a scalar value");return!1}return!0}function h(z,N){return t(z>>N&63|128)}function x(z,N){if((z&4294967168)==0)return t(z);var B="";return(z&4294965248)==0?B=t(z>>6&31|192):(z&4294901760)==0?(p(z,N)||(z=65533),B=t(z>>12&15|224),B+=h(z,6)):(z&4292870144)==0&&(B=t(z>>18&7|240),B+=h(z,12),B+=h(z,6)),B+=t(z&63|128),B}function j(z,N){N=N||{};for(var B=N.strict!==!1,L=u(z),W=L.length,H=-1,V,J="";++H<W;)V=L[H],J+=x(V,B);return J}function b(){if(I>=O)throw Error("Invalid byte index");var z=$[I]&255;if(I++,(z&192)==128)return z&63;throw Error("Invalid continuation byte")}function w(z){var N,B,L,W,H;if(I>O)throw Error("Invalid byte index");if(I==O)return!1;if(N=$[I]&255,I++,(N&128)==0)return N;if((N&224)==192){if(B=b(),H=(N&31)<<6|B,H>=128)return H;throw Error("Invalid continuation byte")}if((N&240)==224){if(B=b(),L=b(),H=(N&15)<<12|B<<6|L,H>=2048)return p(H,z)?H:65533;throw Error("Invalid continuation byte")}if((N&248)==240&&(B=b(),L=b(),W=b(),H=(N&7)<<18|B<<12|L<<6|W,H>=65536&&H<=1114111))return H;throw Error("Invalid UTF-8 detected")}var $,O,I;function U(z,N){N=N||{};var B=N.strict!==!1;$=u(z),O=$.length,I=0;for(var L=[],W;(W=w(B))!==!1;)L.push(W);return d(L)}r.exports={version:"2.1.2",encode:j,decode:U}},2317:(r,t,u)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Server=t.BaseServer=void 0;const d=u(1942),p=u(2975),h=u(4434),x=u(3739),j=u(2830),b=u(3814),w=u(1354),$=u(8868),O=u(8007),I=(0,j.default)("engine"),U=Symbol("responseHeaders");function z(G){try{const X=JSON.parse(G);if(typeof X.sid=="string")return X.sid}catch{}}class N extends h.EventEmitter{constructor(X={}){super(),this.middlewares=[],this.clients={},this.clientsCount=0,this.opts=Object.assign({wsEngine:w.Server,pingTimeout:2e4,pingInterval:25e3,upgradeTimeout:1e4,maxHttpBufferSize:1e6,transports:["polling","websocket"],allowUpgrades:!0,httpCompression:{threshold:1024},cors:!1,allowEIO3:!1},X),X.cookie&&(this.opts.cookie=Object.assign({name:"io",path:"/",httpOnly:X.cookie.path!==!1,sameSite:"lax"},X.cookie)),this.opts.cors&&this.use(u(4085)(this.opts.cors)),X.perMessageDeflate&&(this.opts.perMessageDeflate=Object.assign({threshold:1024},X.perMessageDeflate)),this.init()}_computePath(X){let K=(X.path||"/engine.io").replace(/\/$/,"");return X.addTrailingSlash!==!1&&(K+="/"),K}upgrades(X){return this.opts.allowUpgrades?p.default[X].upgradesTo||[]:[]}verify(X,K,Y){const ee=X._query.transport;if(!~this.opts.transports.indexOf(ee)||ee==="webtransport")return I('unknown transport "%s"',ee),Y(L.errors.UNKNOWN_TRANSPORT,{transport:ee});if(J(X.headers.origin)){const ae=X.headers.origin;return X.headers.origin=null,I("origin header invalid"),Y(L.errors.BAD_REQUEST,{name:"INVALID_ORIGIN",origin:ae})}const ie=X._query.sid;if(ie){if(!this.clients.hasOwnProperty(ie))return I('unknown sid "%s"',ie),Y(L.errors.UNKNOWN_SID,{sid:ie});const ae=this.clients[ie].transport.name;if(!K&&ae!==ee)return I("bad request: unexpected transport without upgrade"),Y(L.errors.BAD_REQUEST,{name:"TRANSPORT_MISMATCH",transport:ee,previousTransport:ae})}else return X.method!=="GET"?Y(L.errors.BAD_HANDSHAKE_METHOD,{method:X.method}):ee==="websocket"&&!K?(I("invalid transport upgrade"),Y(L.errors.BAD_REQUEST,{name:"TRANSPORT_HANDSHAKE_ERROR"})):this.opts.allowRequest?this.opts.allowRequest(X,((ae,ne)=>{if(!ne)return Y(L.errors.FORBIDDEN,{message:ae});Y()})):Y();Y()}use(X){this.middlewares.push(X)}_applyMiddlewares(X,K,Y){if(this.middlewares.length===0)return I("no middleware to apply, skipping"),Y();const ee=Q=>{I("applying middleware n\xB0%d",Q+1),this.middlewares[Q](X,K,(ie=>{if(ie)return Y(ie);Q+1<this.middlewares.length?ee(Q+1):Y()}))};ee(0)}close(){I("closing all open clients");for(let X in this.clients)this.clients.hasOwnProperty(X)&&this.clients[X].close(!0);return this.cleanup(),this}generateId(X){return d.generateId()}async handshake(X,K,Y){const ee=K._query.EIO==="4"?4:3;if(ee===3&&!this.opts.allowEIO3){I("unsupported protocol version"),this.emit("connection_error",{req:K,code:L.errors.UNSUPPORTED_PROTOCOL_VERSION,message:L.errorMessages[L.errors.UNSUPPORTED_PROTOCOL_VERSION],context:{protocol:ee}}),Y(L.errors.UNSUPPORTED_PROTOCOL_VERSION);return}let Q;try{Q=await this.generateId(K)}catch(ne){I("error while generating an id"),this.emit("connection_error",{req:K,code:L.errors.BAD_REQUEST,message:L.errorMessages[L.errors.BAD_REQUEST],context:{name:"ID_GENERATION_ERROR",error:ne}}),Y(L.errors.BAD_REQUEST);return}I('handshaking client "%s"',Q);try{var ie=this.createTransport(X,K);X==="polling"?(ie.maxHttpBufferSize=this.opts.maxHttpBufferSize,ie.httpCompression=this.opts.httpCompression):X==="websocket"&&(ie.perMessageDeflate=this.opts.perMessageDeflate)}catch(ne){I('error handshaking to transport "%s"',X),this.emit("connection_error",{req:K,code:L.errors.BAD_REQUEST,message:L.errorMessages[L.errors.BAD_REQUEST],context:{name:"TRANSPORT_HANDSHAKE_ERROR",error:ne}}),Y(L.errors.BAD_REQUEST);return}const ae=new x.Socket(Q,this,ie,K,ee);return ie.on("headers",((ne,te)=>{!te._query.sid&&(this.opts.cookie&&(ne["Set-Cookie"]=[(0,b.serialize)(this.opts.cookie.name,Q,this.opts.cookie)]),this.emit("initial_headers",ne,te)),this.emit("headers",ne,te)})),ie.onRequest(K),this.clients[Q]=ae,this.clientsCount++,ae.once("close",(()=>{delete this.clients[Q],this.clientsCount--})),this.emit("connection",ae),ie}async onWebTransportSession(X){const K=setTimeout((()=>{I("the client failed to establish a bidirectional stream in the given period"),X.close()}),this.opts.upgradeTimeout),ee=await X.incomingBidirectionalStreams.getReader().read();if(ee.done){I("session is closed");return}const Q=ee.value,ie=(0,O.createPacketDecoderStream)(this.opts.maxHttpBufferSize,"nodebuffer"),ae=Q.readable.pipeThrough(ie).getReader(),{value:ne,done:te}=await ae.read();if(te){I("stream is closed");return}if(clearTimeout(K),ne.type!=="open")return I("invalid WebTransport handshake"),X.close();if(ne.data===void 0){const ke=new $.WebTransport(X,Q,ae),xe=d.generateId();I('handshaking client "%s" (WebTransport)',xe);const _e=new x.Socket(xe,this,ke,null,4);this.clients[xe]=_e,this.clientsCount++,_e.once("close",(()=>{delete this.clients[xe],this.clientsCount--})),this.emit("connection",_e);return}const oe=z(ne.data);if(!oe)return I("invalid WebTransport handshake"),X.close();const de=this.clients[oe];if(!de)I("upgrade attempt for closed client"),X.close();else if(de.upgrading)I("transport has already been trying to upgrade"),X.close();else if(de.upgraded)I("transport had already been upgraded"),X.close();else{I("upgrading existing transport");const ke=new $.WebTransport(X,Q,ae);de._maybeUpgrade(ke)}}}t.BaseServer=N,N.errors={UNKNOWN_TRANSPORT:0,UNKNOWN_SID:1,BAD_HANDSHAKE_METHOD:2,BAD_REQUEST:3,FORBIDDEN:4,UNSUPPORTED_PROTOCOL_VERSION:5},N.errorMessages={0:"Transport unknown",1:"Session ID unknown",2:"Bad handshake method",3:"Bad request",4:"Forbidden",5:"Unsupported protocol version"};class B{constructor(X,K){this.req=X,this.socket=K,X[U]={}}setHeader(X,K){this.req[U][X]=K}getHeader(X){return this.req[U][X]}removeHeader(X){delete this.req[U][X]}write(){}writeHead(){}end(){this.socket.destroy()}}class L extends N{init(){~this.opts.transports.indexOf("websocket")&&(this.ws&&this.ws.close(),this.ws=new this.opts.wsEngine({noServer:!0,clientTracking:!1,perMessageDeflate:this.opts.perMessageDeflate,maxPayload:this.opts.maxHttpBufferSize}),typeof this.ws.on=="function"&&this.ws.on("headers",((X,K)=>{const Y=K[U]||{};delete K[U],!K._query.sid&&this.emit("initial_headers",Y,K),this.emit("headers",Y,K),I("writing headers: %j",Y),Object.keys(Y).forEach((Q=>{X.push(`${Q}: ${Y[Q]}`)}))})))}cleanup(){this.ws&&(I("closing webSocketServer"),this.ws.close())}prepare(X){if(!X._query){const K=new URL(X.url,"https://socket.io");X._query=Object.fromEntries(K.searchParams.entries())}}createTransport(X,K){return new p.default[X](K)}handleRequest(X,K){I('handling "%s" http request "%s"',X.method,X.url),this.prepare(X),X.res=K;const Y=(ee,Q)=>{if(ee!==void 0){this.emit("connection_error",{req:X,code:ee,message:L.errorMessages[ee],context:Q}),W(K,ee,Q);return}if(X._query.sid)I("setting new request for existing client"),this.clients[X._query.sid].transport.onRequest(X);else{const ie=(ae,ne)=>W(K,ae,ne);this.handshake(X._query.transport,X,ie)}};this._applyMiddlewares(X,K,(ee=>{ee?Y(L.errors.BAD_REQUEST,{name:"MIDDLEWARE_FAILURE"}):this.verify(X,!1,Y)}))}handleUpgrade(X,K,Y){this.prepare(X);const ee=new B(X,K),Q=(ie,ae)=>{if(ie!==void 0){this.emit("connection_error",{req:X,code:ie,message:L.errorMessages[ie],context:ae}),H(K,ie,ae);return}const ne=Buffer.from(Y);Y=null,ee.writeHead(),this.ws.handleUpgrade(X,K,ne,(te=>{this.onWebSocket(X,K,te)}))};this._applyMiddlewares(X,ee,(ie=>{ie?Q(L.errors.BAD_REQUEST,{name:"MIDDLEWARE_FAILURE"}):this.verify(X,!0,Q)}))}onWebSocket(X,K,Y){if(Y.on("error",Q),p.default[X._query.transport]!==void 0&&!p.default[X._query.transport].prototype.handlesUpgrades){I("transport doesnt handle upgraded requests"),Y.close();return}const ee=X._query.sid;if(X.websocket=Y,ee){const ie=this.clients[ee];if(!ie)I("upgrade attempt for closed client"),Y.close();else if(ie.upgrading)I("transport has already been trying to upgrade"),Y.close();else if(ie.upgraded)I("transport had already been upgraded"),Y.close();else{I("upgrading existing transport"),Y.removeListener("error",Q);const ae=this.createTransport(X._query.transport,X);ae.perMessageDeflate=this.opts.perMessageDeflate,ie._maybeUpgrade(ae)}}else{const ie=(ae,ne)=>H(K,ae,ne);this.handshake(X._query.transport,X,ie)}function Q(){I("websocket error before upgrade")}}attach(X,K={}){const Y=this._computePath(K),ee=K.destroyUpgradeTimeout||1e3;function Q(ae){return Y===ae.url.slice(0,Y.length)}const ie=X.listeners("request").slice(0);X.removeAllListeners("request"),X.on("close",this.close.bind(this)),X.on("listening",this.init.bind(this)),X.on("request",((ae,ne)=>{if(Q(ae))I('intercepting request for path "%s"',Y),this.handleRequest(ae,ne);else{let te=0;const oe=ie.length;for(;te<oe;te++)ie[te].call(X,ae,ne)}})),~this.opts.transports.indexOf("websocket")&&X.on("upgrade",((ae,ne,te)=>{Q(ae)?this.handleUpgrade(ae,ne,te):K.destroyUpgrade!==!1&&setTimeout((function(){if(ne.writable&&ne.bytesWritten<=0)return ne.on("error",(oe=>{I("error while destroying upgrade: %s",oe.message)})),ne.end()}),ee)}))}}t.Server=L;function W(G,X,K){const Y=X===L.errors.FORBIDDEN?403:400,ee=K&&K.message?K.message:L.errorMessages[X];G.writeHead(Y,{"Content-Type":"application/json"}),G.end(JSON.stringify({code:X,message:ee}))}function H(G,X,K={}){if(G.on("error",(()=>{I("ignoring error from closed connection")})),G.writable){const Y=K.message||L.errorMessages[X],ee=Buffer.byteLength(Y);G.write(`HTTP/1.1 400 Bad Request\r
361
361
  Connection: close\r
362
362
  Content-type: text/html\r
363
363
  Content-Length: `+ee+`\r
@@ -465,7 +465,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
465
465
  `).filter(Boolean).slice(-20);for(const x of h)try{const j=JSON.parse(x);if(j.type==="human"&&j.message?.content){const b=typeof j.message.content=="string"?j.message.content:j.message.content.find((w=>w.type==="text"))?.text||"";b&&this._history.push({type:"user",content:b,timestamp:j.timestamp})}else j.type==="assistant"&&j.message?.content?this._history.push({type:"assistant",message:j.message,timestamp:j.timestamp}):j.type==="result"&&this._history.push({type:"result",total_cost_usd:j.costUSD||j.total_cost_usd,timestamp:j.timestamp})}catch{}return}}catch(t){console.warn("[agent] \u52A0\u8F7D\u6062\u590D\u4F1A\u8BDD\u5386\u53F2\u5931\u8D25:",t.message)}}get isBusy(){return this._busy}addViewer(t,u){this._viewers.add(t),u&&this._viewerNames.set(t,u)}removeViewer(t){this._viewers.delete(t),this._viewerNames.delete(t)}get viewerCount(){return new Set(this._viewerNames.values()).size||this._viewers.size}takeControl(t,u){this.controlHolder=t,this.controlHolderName=u||null,this.lastInputTime=Date.now()}releaseControl(){this.controlHolder=null,this.controlHolderName=null,this.lastInputTime=null}isController(t){return this.controlHolder===t}toJSON(){return{id:this.id,title:this.title,cwd:this.cwd,createdAt:this.createdAt,mode:"agent",alive:this.alive,viewers:this.viewerCount,controlHolder:this.controlHolder,controlHolderName:this.controlHolderName,permissionMode:this.permissionMode,owner:this.owner,claudeSessionId:this.claudeSessionId,busy:this._busy,usage:this._usage}}}let _claudeSessionsCache=null,_claudeSessionsCacheTime=0;const CLAUDE_SESSIONS_CACHE_TTL=3e4;function listLocalClaudeSessions(r){const t=Date.now();if(_claudeSessionsCache&&t-_claudeSessionsCacheTime<CLAUDE_SESSIONS_CACHE_TTL){if(!r)return _claudeSessionsCache;const h=(0,external_path_.resolve)((0,external_path_.normalize)(r)).replace(/[\\/]+$/,"");return _claudeSessionsCache.filter((x=>(0,external_path_.resolve)((0,external_path_.normalize)(x.projectPath)).replace(/[\\/]+$/,"").startsWith(h)))}const u=[],d=r?(0,external_path_.resolve)((0,external_path_.normalize)(r)).replace(/[\\/]+$/,""):null;try{const h=(0,external_path_.join)((0,external_os_.homedir)(),".claude","projects");if(!(0,external_fs_.existsSync)(h))return u;for(const x of(0,external_fs_.readdirSync)(h,{withFileTypes:!0})){if(!x.isDirectory())continue;const j=(0,external_path_.join)(h,x.name);try{for(const b of(0,external_fs_.readdirSync)(j)){if(!b.endsWith(".jsonl"))continue;const w=b.replace(".jsonl",""),$=(0,external_path_.join)(j,b);try{const O=(0,external_fs_.readFileSync)($,"utf8").split(`
466
466
  `).filter(Boolean);let I=null,U=null,z=0,N="";for(const L of O)try{const W=JSON.parse(L);if(I||(I=W),U=W,z++,!N&&W.type==="human"&&W.message?.content){const H=W.message.content;if(typeof H=="string")N=H.slice(0,120);else if(Array.isArray(H)){const V=H.find((J=>J.type==="text"));V&&(N=V.text?.slice(0,120)||"")}}}catch{}let B=x.name;if(process.platform==="win32"&&/^[A-Za-z]--/.test(B)?B=B[0]+":\\"+B.slice(3).replace(/-/g,"\\"):B.startsWith("-")&&(B=B.replace(/-/g,"/")),d&&!(0,external_path_.resolve)((0,external_path_.normalize)(B)).replace(/[\\/]+$/,"").startsWith(d))continue;u.push({sessionId:w,projectDir:x.name,projectPath:B,messageCount:z,summary:N,createdAt:I?.timestamp||null,updatedAt:U?.timestamp||null})}catch{}}}catch{}}}catch{}u.sort(((h,x)=>new Date(x.updatedAt||0).getTime()-new Date(h.updatedAt||0).getTime()));const p=u.slice(0,50);return _claudeSessionsCache=p,_claudeSessionsCacheTime=Date.now(),p.slice(0,20)}const CONFIG_DIR=(0,external_path_.join)((0,external_os_.homedir)(),".zihi"),SESSIONS_FILE=(0,external_path_.join)(CONFIG_DIR,"sessions.json");function loadSavedConfigs(){try{return JSON.parse((0,external_fs_.readFileSync)(SESSIONS_FILE,"utf8"))}catch{return[]}}function writeSavedConfigs(r){try{(0,external_fs_.mkdirSync)(CONFIG_DIR,{recursive:!0});const t=SESSIONS_FILE+".tmp";(0,external_fs_.writeFileSync)(t,JSON.stringify(r,null,2),{mode:384}),(0,external_fs_.renameSync)(t,SESSIONS_FILE)}catch(t){console.error("[sessions] \u6301\u4E45\u5316\u5199\u5165\u5931\u8D25:",t.message)}}class SessionManager{constructor(){this._agentSessions=new Map;for(const t of loadSavedConfigs())try{if(t.claudeSessionId){const u=(0,external_crypto_.randomUUID)(),d=new AgentSession(u,{...t,resumeSessionId:t.claudeSessionId});d.on("session-id",(()=>this._persist())),this._agentSessions.set(u,d),console.log(`[\u4F1A\u8BDD] \u6062\u590D Agent "${t.title}" (claude: ${t.claudeSessionId.slice(0,8)}...)`)}}catch(u){console.warn(`[\u4F1A\u8BDD] \u6062\u590D "${t.title}" \u5931\u8D25:`,u.message)}}createAgent(t={}){const u=(0,external_crypto_.randomUUID)(),d=new AgentSession(u,t);return this._agentSessions.set(u,d),d.on("session-id",(()=>this._persist())),this._persist(),d}get(t){return this._agentSessions.get(t)}list(t,u=!1){let d=[...this._agentSessions.values()].map((p=>p.toJSON()));return t&&!u&&(d=d.filter((p=>!p.owner||p.owner===t))),d}listSessions(){return[...this._agentSessions.values()]}kill(t){const u=this._agentSessions.get(t);u&&(u.kill(),this._agentSessions.delete(t),this._persist())}persist(){this._persist()}_persist(){const t=[...this._agentSessions.values()].filter((u=>u.alive)).map((u=>({mode:"agent",title:u.title,cwd:u.cwd,permissionMode:u.permissionMode||void 0,owner:u.owner||void 0,userDir:u.userDir||void 0,claudeSessionId:u.claudeSessionId||void 0})));writeSavedConfigs(t)}}const roles_CONFIG_DIR=(0,external_path_.join)((0,external_os_.homedir)(),".zihi"),ROLES_FILE=(0,external_path_.join)(roles_CONFIG_DIR,"roles.json"),USERS_FILE=(0,external_path_.join)(roles_CONFIG_DIR,"users.json"),ROLE_LEVELS={admin:3,operator:2,viewer:1};let rolesConfig=null;function loadRoles(){try{if((0,external_fs_.existsSync)(ROLES_FILE))return rolesConfig=JSON.parse((0,external_fs_.readFileSync)(ROLES_FILE,"utf8")),rolesConfig}catch(r){console.warn("[\u89D2\u8272] \u52A0\u8F7D roles.json \u5931\u8D25:",r.message)}return rolesConfig=null,null}function lookupPassword(r){if(!rolesConfig?.passwords)return null;const t=rolesConfig.passwords[r];return t?{name:t.name||"\u7528\u6237",role:t.role||"viewer"}:null}function hasPermission(r,t){return(ROLE_LEVELS[r]||0)>=(ROLE_LEVELS[t]||0)}function isMultiUserMode(){return rolesConfig!==null&&rolesConfig.passwords&&Object.keys(rolesConfig.passwords).length>0}function getDefaultRole(){return rolesConfig?.defaultRole||"admin"}let usersConfig=null;function loadUsers(){try{if((0,external_fs_.existsSync)(USERS_FILE))return usersConfig=JSON.parse((0,external_fs_.readFileSync)(USERS_FILE,"utf8")),usersConfig}catch(r){console.warn("[\u7528\u6237] \u52A0\u8F7D users.json \u5931\u8D25:",r.message)}return usersConfig=null,null}function hasUsers(){return usersConfig!==null&&usersConfig.users&&Object.keys(usersConfig.users).length>0}function isExclusiveMode(){return hasUsers()&&usersConfig.exclusive===!0}function setExclusiveMode(r){usersConfig||(usersConfig={users:{}}),usersConfig.exclusive=!!r,_writeUsers()}function lookupUser(r){if(!usersConfig?.users)return null;const t=usersConfig.users[r];return t?{name:t.name||"\u7528\u6237",dir:t.dir}:null}function listUsers(){return usersConfig?.users?Object.entries(usersConfig.users).map((([r,t])=>({password:r.slice(0,2)+"*".repeat(r.length-2),name:t.name,dir:t.dir}))):[]}function addUser(r,t,u){usersConfig||(usersConfig={users:{}}),usersConfig.users||(usersConfig.users={}),usersConfig.users[r]={name:t,dir:u},_writeUsers()}function removeUser(r){return!usersConfig?.users||!usersConfig.users[r]?!1:(delete usersConfig.users[r],_writeUsers(),!0)}function _writeUsers(){(0,external_fs_.mkdirSync)(roles_CONFIG_DIR,{recursive:!0}),(0,external_fs_.writeFileSync)(USERS_FILE,JSON.stringify(usersConfig,null,2),{mode:384})}const server_dirname=(0,external_path_.dirname)((0,external_url_.fileURLToPath)(import.meta.url));let PORT=parseInt(process.env.PORT,10)||12345;const HOST=process.env.HOST||"0.0.0.0",PORT_EXPLICIT=!!process.env.PORT,configDir=(0,external_path_.join)((0,external_os_.homedir)(),".zihi");(0,external_fs_.mkdirSync)(configDir,{recursive:!0});const pidFile=(0,external_path_.join)(configDir,"daemon.pid"),IS_DAEMON_CHILD=!!process.env.ZIHI_DAEMON;(function r(){if(!IS_DAEMON_CHILD){try{const t=parseInt((0,external_fs_.readFileSync)(pidFile,"utf8").trim(),10);if(t&&t!==process.pid){let u=!1;try{process.kill(t,0),u=!0}catch{}if(u){console.log(`[zihi] \u68C0\u6D4B\u5230\u5DF2\u8FD0\u884C\u7684\u5B9E\u4F8B (PID ${t})\uFF0C\u6B63\u5728\u505C\u6B62...`);try{process.platform==="win32"?(0,external_child_process_namespaceObject.execSync)(`taskkill /PID ${t} /F /T`,{stdio:"pipe",timeout:5e3}):process.kill(t,"SIGTERM")}catch(h){console.warn(`[zihi] \u505C\u6B62\u65E7\u8FDB\u7A0B\u5931\u8D25: ${h.message?.split(`
467
467
  `)[0]||h}`)}const d=Date.now()+5e3;for(;Date.now()<d;){try{process.kill(t,0)}catch{break}const h=Date.now()+200;for(;Date.now()<h;);}let p=!1;try{process.kill(t,0),p=!0}catch{}p&&(console.error(`[zihi] \u65E0\u6CD5\u505C\u6B62\u65E7\u8FDB\u7A0B (PID ${t})\uFF0C\u8BF7\u624B\u52A8\u6267\u884C\uFF1A`),console.error(" zihi stop"),console.error(` \u6216: ${process.platform==="win32"?`taskkill /PID ${t} /F`:`kill -9 ${t}`}`),process.exit(1))}}}catch{}IS_DAEMON_CHILD||(0,external_fs_.writeFileSync)(pidFile,String(process.pid))}})();function cleanupPid(){try{parseInt((0,external_fs_.readFileSync)(pidFile,"utf8").trim(),10)===process.pid&&(0,external_fs_.unlinkSync)(pidFile)}catch{}}function gracefulShutdown(){try{if(typeof manager<"u"){try{manager.persist()}catch{}for(const r of manager.listSessions())try{r.kill()}catch{}}}catch{}cleanupPid()}process.on("exit",cleanupPid),process.on("SIGTERM",(()=>{gracefulShutdown(),process.exit(0)})),process.on("SIGINT",(()=>{gracefulShutdown(),process.exit(0)})),process.on("uncaughtException",(r=>{console.error("[zihi] \u672A\u6355\u83B7\u5F02\u5E38:",r.message),gracefulShutdown(),process.exit(1)})),process.on("unhandledRejection",(r=>{console.error("[zihi] \u672A\u5904\u7406\u7684 Promise \u62D2\u7EDD:",r)}));function readOrCreate(r,t){try{if((0,external_fs_.existsSync)(r))return(0,external_fs_.readFileSync)(r,"utf8").trim()}catch{}const u=t();return(0,external_fs_.writeFileSync)(r,u,{mode:384}),u}const TOKEN=readOrCreate((0,external_path_.join)(configDir,"token"),(()=>(0,external_crypto_.randomBytes)(16).toString("hex")));let PASSWORD=readOrCreate((0,external_path_.join)(configDir,"password"),(()=>String(Math.floor(1e3+Math.random()*9e3))));loadRoles(),loadUsers();let activeUser=null;const userSessions=new Map;userSessions.set(TOKEN,{role:"admin",name:"\u7BA1\u7406\u5458",permanent:!0});const SESSION_MAX_AGE=10080*60*1e3;setInterval((()=>{const r=Date.now();for(const[t,u]of userSessions)u.permanent||(!u.lastUsed||r-u.lastUsed>SESSION_MAX_AGE)&&userSessions.delete(t)}),3600*1e3);function getTailscaleIP(){try{return(0,external_child_process_namespaceObject.execSync)("tailscale ip -4",{timeout:3e3,stdio:"pipe"}).toString().trim().split(`
468
- `)[0]}catch{}try{if(process.platform==="win32"){const t=(0,external_child_process_namespaceObject.execSync)("route print 0.0.0.0",{timeout:3e3,stdio:"pipe"}).toString().match(/0\.0\.0\.0\s+0\.0\.0\.0\s+\S+\s+(\d+\.\d+\.\d+\.\d+)/);if(t)return t[1]}else try{const t=(0,external_child_process_namespaceObject.execSync)("ip route get 1.1.1.1",{timeout:3e3,stdio:"pipe"}).toString().match(/src\s+(\d+\.\d+\.\d+\.\d+)/);if(t)return t[1]}catch{const r=(0,external_child_process_namespaceObject.execSync)("route -n get default 2>/dev/null || route -n 2>/dev/null",{timeout:3e3,stdio:"pipe"}).toString(),t=r.match(/interface:\s*(\S+)/i)||r.match(/0\.0\.0\.0\s+(\d+\.\d+\.\d+\.\d+)/);if(t){const u=(0,external_os_.networkInterfaces)()[t[1]];if(u){const d=u.find((p=>p.family==="IPv4"&&!p.internal));if(d)return d.address}if(/^\d+\.\d+\.\d+\.\d+$/.test(t[1]))return t[1]}}}catch{}for(const r of Object.values((0,external_os_.networkInterfaces)()))for(const t of r)if(t.family==="IPv4"&&!t.internal)return t.address;return"localhost"}function parseCookies(r=""){const t={};for(const u of r.split(";")){const d=u.indexOf("=");d>0&&(t[u.slice(0,d).trim()]=u.slice(d+1).trim())}return t}const SESSION_COOKIE="zihi_sid",COOKIE_OPTS="HttpOnly; SameSite=Lax; Path=/; Max-Age=31536000";function setSessionCookie(r,t){r.setHeader("Set-Cookie",`${SESSION_COOKIE}=${t||TOKEN}; ${COOKIE_OPTS}`)}function getSessionToken(r){return parseCookies(r)[SESSION_COOKIE]||null}function hasValidSession(r){const t=getSessionToken(r);if(t&&userSessions.has(t)){const u=userSessions.get(t);return u&&(u.lastUsed=Date.now()),!0}return!1}function getUserInfo(r){const t=getSessionToken(r);return t?userSessions.get(t):null}const MIME_MAP={".html":"text/html",".css":"text/css",".js":"text/javascript",".mjs":"text/javascript",".json":"application/json",".xml":"application/xml",".txt":"text/plain",".md":"text/plain",".csv":"text/csv",".log":"text/plain",".sh":"text/plain",".py":"text/plain",".ts":"text/plain",".jsx":"text/plain",".tsx":"text/plain",".yml":"text/plain",".yaml":"text/plain",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml",".webp":"image/webp",".ico":"image/x-icon",".bmp":"image/bmp",".mp3":"audio/mpeg",".wav":"audio/wav",".ogg":"audio/ogg",".flac":"audio/flac",".m4a":"audio/mp4",".aac":"audio/aac",".wma":"audio/x-ms-wma",".mp4":"video/mp4",".webm":"video/webm",".mkv":"video/x-matroska",".avi":"video/x-msvideo",".mov":"video/quicktime",".flv":"video/x-flv",".pdf":"application/pdf",".zip":"application/zip",".gz":"application/gzip",".tar":"application/x-tar",".7z":"application/x-7z-compressed",".rar":"application/x-rar-compressed",".doc":"application/msword",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".xls":"application/vnd.ms-excel",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",".ppt":"application/vnd.ms-powerpoint",".pptx":"application/vnd.openxmlformats-officedocument.presentationml.presentation",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".eot":"application/vnd.ms-fontobject"};function getMime(r){return MIME_MAP[(0,external_path_.extname)(r).toLowerCase()]||"application/octet-stream"}function resolveUserFilePath(r,t){const u=getUserInfo(r.headers.cookie),d=r.query.sessionId||r.body?.sessionId,p=d?manager.get(d):null,x=(p?.cwd?(0,external_path_.resolve)((0,external_path_.normalize)(p.cwd)):null)||(u?.dir?(0,external_path_.resolve)((0,external_path_.normalize)(u.dir)):process.env.ZIHI_CWD||(0,external_os_.homedir)());let j=t?(0,external_path_.resolve)((0,external_path_.normalize)(x),(0,external_path_.normalize)(t)):x;if(process.platform==="win32"&&/^[A-Za-z]:$/.test(j)&&(j+="\\"),!j.startsWith(x))return{error:"\u8BBF\u95EE\u88AB\u62D2\u7EDD\uFF1A\u8DEF\u5F84\u8D85\u51FA\u5141\u8BB8\u8303\u56F4",status:403};try{if(!(0,external_fs_.realpathSync)(j).startsWith(x))return{error:"\u8BBF\u95EE\u88AB\u62D2\u7EDD\uFF1A\u7B26\u53F7\u94FE\u63A5\u6307\u5411\u5141\u8BB8\u8303\u56F4\u5916",status:403}}catch{}return{resolved:j,userRoot:x,info:u}}const syncConfigFile=(0,external_path_.join)(configDir,"sync.json");function loadSyncConfig(){try{return JSON.parse((0,external_fs_.readFileSync)(syncConfigFile,"utf8"))}catch{return{}}}function saveSyncConfig(r){(0,external_fs_.writeFileSync)(syncConfigFile,JSON.stringify(r,null,2))}const DEFAULT_IGNORE=["node_modules",".git",".DS_Store","Thumbs.db","__pycache__",".env",".env.local","*.pyc",".cache","dist","build"];function shouldIgnore(r,t){for(const u of t)if(u.startsWith("*.")){if(r.endsWith(u.slice(1)))return!0}else if(r===u)return!0;return!1}function scanDirTree(r,t,u={}){const d={},p=u.maxDepth||20,h=u.withHash||!1;function x(j,b,w){if(w>p)return;let $;try{$=(0,external_fs_.readdirSync)(j,{withFileTypes:!0})}catch{return}for(const O of $){if(O.name.startsWith(".")&&!u.showHidden||shouldIgnore(O.name,t))continue;const I=(0,external_path_.join)(j,O.name),U=b?b+"/"+O.name:O.name;if(O.isDirectory())x(I,U,w+1);else if(O.isFile())try{const z=(0,external_fs_.statSync)(I),N={size:z.size,mtime:z.mtimeMs};if(h&&z.size<50*1024*1024){const B=(0,external_crypto_.createHash)("sha256"),L=(0,external_fs_.readFileSync)(I);B.update(L),N.hash=B.digest("hex")}d[U]=N}catch{}}}return x(r,"",0),d}function fileHash(r){const t=(0,external_crypto_.createHash)("sha256");return t.update((0,external_fs_.readFileSync)(r)),t.digest("hex")}function walkFiles(r,t,u=[]){try{for(const d of(0,external_fs_.readdirSync)(r,{withFileTypes:!0})){if(d.name.startsWith("."))continue;const p=(0,external_path_.join)(r,d.name),h=t?t+"/"+d.name:d.name;if(d.isDirectory())walkFiles(p,h,u);else if(d.isFile())try{const x=(0,external_fs_.statSync)(p),j={name:h,size:x.size,mtime:x.mtimeMs};x.size<50*1024*1024&&(j.hash=fileHash(p)),u.push(j)}catch{}}}catch{}return u}const app=express();app.set("trust proxy",!0),app.use(((r,t,u)=>{t.setHeader("Referrer-Policy","no-referrer"),t.setHeader("X-Content-Type-Options","nosniff"),u()}));const httpServer=(0,external_http_.createServer)(app),_corsAllowed=/^https?:\/\/(localhost|127\.0\.0\.1|\[::1\]|10\.\d+\.\d+\.\d+|172\.(1[6-9]|2\d|3[01])\.\d+\.\d+|192\.168\.\d+\.\d+|100\.(6[4-9]|[7-9]\d|1[01]\d|12[0-7])\.\d+\.\d+)(:\d+)?$/,io=new Server({cors:{origin:(r,t)=>{if(!r||_corsAllowed.test(r))return t(null,!0);t(new Error("CORS \u4E0D\u5141\u8BB8\u6B64\u6765\u6E90"),!1)},credentials:!0},transports:["polling","websocket"],pingTimeout:6e4,pingInterval:25e3,upgradeTimeout:3e4,allowUpgrades:!0,maxHttpBufferSize:5e6});io.attach(httpServer);const manager=new SessionManager,uploadDir=(0,external_path_.join)(configDir,"uploads");(0,external_fs_.mkdirSync)(uploadDir,{recursive:!0});function checkAuth(r,t,u){const d=r.query.token;if(d&&(d===TOKEN||userSessions.has(d))){const p=userSessions.get(d);if(p?.onetime){userSessions.delete(d);const x=(0,external_crypto_.randomBytes)(16).toString("hex");userSessions.set(x,{role:p.role,name:p.name,lastUsed:Date.now()}),setSessionCookie(t,x)}else setSessionCookie(t,d===TOKEN?TOKEN:d);const h=r.path+(Object.keys(r.query).filter((x=>x!=="token")).length?"?"+new URLSearchParams(Object.fromEntries(Object.entries(r.query).filter((([x])=>x!=="token")))):"");return t.redirect(h)}if(hasValidSession(r.headers.cookie)){if(isExclusiveMode()&&activeUser){const p=getSessionToken(r.headers.cookie);if(p!==TOKEN){const h=userSessions.get(p);if(!h||h.name!==activeUser.name)return t.setHeader("Set-Cookie",`${SESSION_COOKIE}=; HttpOnly; SameSite=Strict; Path=/; Max-Age=0`),t.redirect("/login")}}return u()}t.redirect("/login")}const server_require=(0,external_module_namespaceObject.createRequire)(import.meta.url);function pkgDirSafe(r){try{return(0,external_path_.dirname)(server_require.resolve(`${r}/package.json`))}catch{return null}}const libDir=(0,external_path_.join)(server_dirname,"lib"),staticOpts={maxAge:864e5};app.use("/lib/xterm",express.static(pkgDirSafe("xterm")||(0,external_path_.join)(libDir,"xterm"),staticOpts)),app.use("/lib/xterm-fit",express.static(pkgDirSafe("xterm-addon-fit")||(0,external_path_.join)(libDir,"xterm-fit"),staticOpts)),app.use("/lib/xterm-links",express.static(pkgDirSafe("xterm-addon-web-links")||(0,external_path_.join)(libDir,"xterm-links"),staticOpts));const _loginAttempts=new Map,LOGIN_MAX_ATTEMPTS=5,LOGIN_LOCKOUT_MS=300*1e3;function checkLoginRate(r){const t=Date.now(),u=_loginAttempts.get(r);return!u||t>u.resetAt?!0:u.count<LOGIN_MAX_ATTEMPTS}function recordLoginFailure(r){const t=Date.now(),u=_loginAttempts.get(r);!u||t>u.resetAt?_loginAttempts.set(r,{count:1,resetAt:t+LOGIN_LOCKOUT_MS}):u.count++}function clearLoginFailures(r){_loginAttempts.delete(r)}setInterval((()=>{const r=Date.now();for(const[t,u]of _loginAttempts)r>u.resetAt&&_loginAttempts.delete(t)}),600*1e3),app.get("/login",((r,t)=>{t.sendFile(__nccwpck_require__.ab+"login.html")})),app.post("/login",express.urlencoded({extended:!1}),((r,t)=>{const u=r.ip;if(!checkLoginRate(u))return t.redirect("/login?error=locked");loadRoles(),loadUsers();const d=r.body?.password,p=r.query.from,h=p&&p.startsWith("/")&&!p.startsWith("//")?p:"/";if(hasUsers()){const j=lookupUser(d);if(!j)return recordLoginFailure(u),t.redirect("/login?error=1");if(isExclusiveMode()&&activeUser&&activeUser.name!==j.name)return t.redirect("/login?error=occupied&user="+encodeURIComponent(activeUser.name));clearLoginFailures(u);const b=(0,external_crypto_.randomBytes)(16).toString("hex");return userSessions.set(b,{role:"operator",name:j.name,dir:j.dir,lastUsed:Date.now()}),isExclusiveMode()&&(activeUser?activeUser.tokens.add(b):activeUser={name:j.name,dir:j.dir,tokens:new Set([b]),loginAt:Date.now()}),setSessionCookie(t,b),console.log(`[\u767B\u5F55] ${j.name} \u767B\u5F55\uFF08${isExclusiveMode()?"\u72EC\u5360":"\u5171\u4EAB"}\u6A21\u5F0F\uFF09`),t.redirect(h)}const x=lookupPassword(d);if(x){clearLoginFailures(u);const j=(0,external_crypto_.randomBytes)(16).toString("hex");return userSessions.set(j,{role:x.role,name:x.name,lastUsed:Date.now()}),setSessionCookie(t,j),t.redirect(h)}if(d===PASSWORD){clearLoginFailures(u);const j=(0,external_crypto_.randomBytes)(16).toString("hex");return userSessions.set(j,{role:"admin",name:"\u7BA1\u7406\u5458",lastUsed:Date.now()}),setSessionCookie(t,j),t.redirect(h)}recordLoginFailure(u),t.redirect("/login?error=1")})),app.post("/logout",((r,t)=>{const u=getSessionToken(r.headers.cookie);u&&(activeUser&&activeUser.tokens.has(u)&&(activeUser.tokens.delete(u),activeUser.tokens.size===0?(console.log(`[\u9000\u51FA] ${activeUser.name} \u5168\u90E8\u8BBE\u5907\u9000\u51FA\uFF0C\u91CA\u653E\u767B\u5F55\u72B6\u6001\uFF08\u4F1A\u8BDD\u4FDD\u7559\uFF09`),activeUser=null):console.log(`[\u9000\u51FA] ${activeUser.name} \u4E00\u4E2A\u8BBE\u5907\u9000\u51FA\uFF08\u5269\u4F59 ${activeUser.tokens.size} \u4E2A\uFF09`)),userSessions.delete(u)),t.setHeader("Set-Cookie",`${SESSION_COOKIE}=; HttpOnly; SameSite=Strict; Path=/; Max-Age=0`),t.redirect("/login")})),app.get("/api/status",((r,t)=>{if(isExclusiveMode()&&activeUser)return t.json({occupied:!0,userName:activeUser.name,releasing:!!_exclusiveReleaseTimer});if(hasUsers()&&!isExclusiveMode()){const u=new Set;for(const[,d]of io.sockets.sockets){if(!d.data.userName||d.data.userName==="\u7BA1\u7406\u5458")continue;const p=d.handshake.headers.cookie;p&&!hasValidSession(p)||u.add(d.data.userName)}return t.json({occupied:!1,onlineUsers:[...u]})}t.json({occupied:!1})})),app.get("/admin",((r,t)=>t.sendFile(__nccwpck_require__.ab+"admin.html"))),app.get("/sw.js",((r,t)=>{t.setHeader("Service-Worker-Allowed","/"),t.sendFile(__nccwpck_require__.ab+"sw.js")})),app.get("/",checkAuth,((r,t)=>t.sendFile(__nccwpck_require__.ab+"index.html"))),app.get("/terminal/:id",checkAuth,((r,t)=>t.sendFile(__nccwpck_require__.ab+"chat.html"))),app.get("/files",checkAuth,((r,t)=>t.sendFile(__nccwpck_require__.ab+"files.html"))),app.get("/sync",checkAuth,((r,t)=>t.sendFile(__nccwpck_require__.ab+"sync.html"))),app.use("/lib",express.static(__nccwpck_require__.ab+"lib",staticOpts)),app.get("/api/sessions",checkAuth,((r,t)=>{const u=getUserInfo(r.headers.cookie);t.json(manager.list(u?.name,u?.role==="admin"))})),app.get("/api/usage",((r,t)=>{try{const u=manager.listSessions().filter((p=>p.mode==="agent"&&p.alive)).map((p=>({id:p.id,title:p.title,owner:p.owner,usage:p._usage})));let d=null;for(const p of u)if(p.usage?.rateLimitInfo){d=p.usage.rateLimitInfo;break}t.json({rateLimit:d,activeSessions:u})}catch(u){t.status(500).json({error:u.message})}})),app.post("/api/sessions",checkAuth,express.json(),((r,t)=>{const u=getUserInfo(r.headers.cookie),d=manager.createAgent({...r.body,owner:u?.name,userDir:u?.dir});t.status(201).json(d.toJSON())})),app.delete("/api/sessions/:id",checkAuth,((r,t)=>{manager.kill(r.params.id),t.status(204).end()})),app.get("/api/claude-sessions",checkAuth,((r,t)=>{const u=getUserInfo(r.headers.cookie);t.json(listLocalClaudeSessions(u?.dir))})),app.get("/api/dirs",checkAuth,((r,t)=>{const u=getUserInfo(r.headers.cookie);if(!u||u.role!=="admin")return t.status(403).json({error:"\u6CA1\u6709\u76EE\u5F55\u6D4F\u89C8\u6743\u9650"});const d=u.dir?(0,external_path_.resolve)((0,external_path_.normalize)(u.dir)):null,p=process.platform==="win32"?"\\":"/";let h=r.query.path||d||process.env.ZIHI_CWD||(0,external_os_.homedir)(),x=(0,external_path_.resolve)((0,external_path_.normalize)(h)).replace(/[/\\]+$/,"");process.platform==="win32"&&/^[A-Za-z]:$/.test(x)&&(x+="\\"),d&&!x.startsWith(d)&&(x=d);try{const j=(0,external_fs_.readdirSync)(x,{withFileTypes:!0}).filter(($=>$.isDirectory()&&!$.name.startsWith("."))).map(($=>({name:$.name,path:x.replace(/[/\\]+$/,"")+p+$.name}))).sort((($,O)=>$.name.localeCompare(O.name))),b=(0,external_path_.join)(x,".."),w=!d||(0,external_path_.resolve)((0,external_path_.normalize)(b)).startsWith(d);t.json({current:x,parent:w&&b!==x?b:null,dirs:j})}catch(j){t.status(400).json({error:j.message})}})),app.get("/api/me",checkAuth,((r,t)=>{const u=getUserInfo(r.headers.cookie);t.json({name:u?.name||"\u7528\u6237",exclusive:isExclusiveMode(),hasUsers:hasUsers(),dir:u?.dir||null})}));function getPkgVersion(){for(const r of["../package.json","./package.json","package.json"])try{const t=JSON.parse((0,external_fs_.readFileSync)((0,external_path_.join)(server_dirname,r),"utf8")).version;if(t&&t!=="0.0.0")return t}catch{}return"0.0.0"}const PKG_VERSION=getPkgVersion();let _latestVersion=null,_lastVersionCheck=0;const VERSION_CHECK_INTERVAL=600*1e3;async function checkLatestVersion(){const r=Date.now();if(_latestVersion&&r-_lastVersionCheck<VERSION_CHECK_INTERVAL)return _latestVersion;try{const t=await fetch("https://registry.npmjs.org/@wendongfly/zihi/latest",{headers:{Accept:"application/json"},signal:AbortSignal.timeout(8e3)});t.ok&&(_latestVersion=(await t.json()).version,_lastVersionCheck=r)}catch{}return _latestVersion}app.get("/api/version",(async(r,t)=>{const u=getPkgVersion(),d=await checkLatestVersion();t.json({current:u,latest:d||u,updateAvailable:d&&d!==u})})),app.post("/api/git/push",checkAuth,express.json(),(async(r,t)=>{const{sessionId:u,url:d,username:p,password:h,message:x,branch:j}=r.body||{};if(!u||!x)return t.status(400).json({ok:!1,error:"\u7F3A\u5C11\u53C2\u6570"});const b=manager.get(u);if(!b)return t.status(404).json({ok:!1,error:"\u4F1A\u8BDD\u4E0D\u5B58\u5728"});const w=b.cwd||process.cwd(),$=process.platform==="win32",O="git";function I(U,z={}){return new Promise(((N,B)=>{const L={...process.env,GIT_TERMINAL_PROMPT:"0"},W=(0,external_path_.join)(w,".gitconfig");(0,external_fs_.existsSync)(W)&&(L.GIT_CONFIG_GLOBAL=W);const H=(0,external_child_process_namespaceObject.spawn)(O,U,{cwd:w,env:L,timeout:6e4});let V="",J="";H.stdout.on("data",(G=>V+=G)),H.stderr.on("data",(G=>J+=G)),H.on("close",(G=>G===0?N(V.trim()):B(new Error(J.trim()||`exit ${G}`)))),H.on("error",B)}))}try{try{await I(["rev-parse","--git-dir"])}catch{await I(["init"])}if(d&&p&&h){const B=new URL(d);B.username=encodeURIComponent(p),B.password=encodeURIComponent(h);const L=B.toString(),W=(0,external_path_.join)(w,".git-credentials");(0,external_fs_.writeFileSync)(W,L+`
468
+ `)[0]}catch{}try{if(process.platform==="win32"){const t=(0,external_child_process_namespaceObject.execSync)("route print 0.0.0.0",{timeout:3e3,stdio:"pipe"}).toString().match(/0\.0\.0\.0\s+0\.0\.0\.0\s+\S+\s+(\d+\.\d+\.\d+\.\d+)/);if(t)return t[1]}else try{const t=(0,external_child_process_namespaceObject.execSync)("ip route get 1.1.1.1",{timeout:3e3,stdio:"pipe"}).toString().match(/src\s+(\d+\.\d+\.\d+\.\d+)/);if(t)return t[1]}catch{const r=(0,external_child_process_namespaceObject.execSync)("route -n get default 2>/dev/null || route -n 2>/dev/null",{timeout:3e3,stdio:"pipe"}).toString(),t=r.match(/interface:\s*(\S+)/i)||r.match(/0\.0\.0\.0\s+(\d+\.\d+\.\d+\.\d+)/);if(t){const u=(0,external_os_.networkInterfaces)()[t[1]];if(u){const d=u.find((p=>p.family==="IPv4"&&!p.internal));if(d)return d.address}if(/^\d+\.\d+\.\d+\.\d+$/.test(t[1]))return t[1]}}}catch{}for(const r of Object.values((0,external_os_.networkInterfaces)()))for(const t of r)if(t.family==="IPv4"&&!t.internal)return t.address;return"localhost"}function parseCookies(r=""){const t={};for(const u of r.split(";")){const d=u.indexOf("=");d>0&&(t[u.slice(0,d).trim()]=u.slice(d+1).trim())}return t}const SESSION_COOKIE="zihi_sid",COOKIE_OPTS="HttpOnly; SameSite=Lax; Path=/; Max-Age=31536000";function setSessionCookie(r,t){r.setHeader("Set-Cookie",`${SESSION_COOKIE}=${t||TOKEN}; ${COOKIE_OPTS}`)}function getSessionToken(r){return parseCookies(r)[SESSION_COOKIE]||null}function hasValidSession(r){const t=getSessionToken(r);if(t&&userSessions.has(t)){const u=userSessions.get(t);return u&&(u.lastUsed=Date.now()),!0}return!1}function getUserInfo(r){const t=getSessionToken(r);return t?userSessions.get(t):null}const MIME_MAP={".html":"text/html",".css":"text/css",".js":"text/javascript",".mjs":"text/javascript",".json":"application/json",".xml":"application/xml",".txt":"text/plain",".md":"text/plain",".csv":"text/csv",".log":"text/plain",".sh":"text/plain",".py":"text/plain",".ts":"text/plain",".jsx":"text/plain",".tsx":"text/plain",".yml":"text/plain",".yaml":"text/plain",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml",".webp":"image/webp",".ico":"image/x-icon",".bmp":"image/bmp",".mp3":"audio/mpeg",".wav":"audio/wav",".ogg":"audio/ogg",".flac":"audio/flac",".m4a":"audio/mp4",".aac":"audio/aac",".wma":"audio/x-ms-wma",".mp4":"video/mp4",".webm":"video/webm",".mkv":"video/x-matroska",".avi":"video/x-msvideo",".mov":"video/quicktime",".flv":"video/x-flv",".pdf":"application/pdf",".zip":"application/zip",".gz":"application/gzip",".tar":"application/x-tar",".7z":"application/x-7z-compressed",".rar":"application/x-rar-compressed",".doc":"application/msword",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".xls":"application/vnd.ms-excel",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",".ppt":"application/vnd.ms-powerpoint",".pptx":"application/vnd.openxmlformats-officedocument.presentationml.presentation",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".eot":"application/vnd.ms-fontobject"};function getMime(r){return MIME_MAP[(0,external_path_.extname)(r).toLowerCase()]||"application/octet-stream"}function sanitizeError(r){return(r||"\u64CD\u4F5C\u5931\u8D25").replace(/[<>"'&]/g,(t=>({"<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;","&":"&amp;"})[t]))}function resolveUserFilePath(r,t){const u=getUserInfo(r.headers.cookie),d=r.query.sessionId||r.body?.sessionId,p=d?manager.get(d):null,x=(p?.cwd?(0,external_path_.resolve)((0,external_path_.normalize)(p.cwd)):null)||(u?.dir?(0,external_path_.resolve)((0,external_path_.normalize)(u.dir)):process.env.ZIHI_CWD||(0,external_os_.homedir)());let j=t?(0,external_path_.resolve)((0,external_path_.normalize)(x),(0,external_path_.normalize)(t)):x;if(process.platform==="win32"&&/^[A-Za-z]:$/.test(j)&&(j+="\\"),!j.startsWith(x))return{error:"\u8BBF\u95EE\u88AB\u62D2\u7EDD\uFF1A\u8DEF\u5F84\u8D85\u51FA\u5141\u8BB8\u8303\u56F4",status:403};try{if(!(0,external_fs_.realpathSync)(j).startsWith(x))return{error:"\u8BBF\u95EE\u88AB\u62D2\u7EDD\uFF1A\u7B26\u53F7\u94FE\u63A5\u6307\u5411\u5141\u8BB8\u8303\u56F4\u5916",status:403}}catch{}return{resolved:j,userRoot:x,info:u}}const app=express();app.set("trust proxy","loopback"),app.use(((r,t,u)=>{t.setHeader("Referrer-Policy","no-referrer"),t.setHeader("X-Content-Type-Options","nosniff"),u()}));const httpServer=(0,external_http_.createServer)(app),_corsAllowed=/^https?:\/\/(localhost|127\.0\.0\.1|\[::1\]|10\.\d+\.\d+\.\d+|172\.(1[6-9]|2\d|3[01])\.\d+\.\d+|192\.168\.\d+\.\d+|100\.(6[4-9]|[7-9]\d|1[01]\d|12[0-7])\.\d+\.\d+)(:\d+)?$/,io=new Server({cors:{origin:(r,t)=>{if(!r||_corsAllowed.test(r))return t(null,!0);t(new Error("CORS \u4E0D\u5141\u8BB8\u6B64\u6765\u6E90"),!1)},credentials:!0},transports:["polling","websocket"],pingTimeout:6e4,pingInterval:25e3,upgradeTimeout:3e4,allowUpgrades:!0,maxHttpBufferSize:5e6});io.attach(httpServer);const manager=new SessionManager,uploadDir=(0,external_path_.join)(configDir,"uploads");(0,external_fs_.mkdirSync)(uploadDir,{recursive:!0});function checkAuth(r,t,u){const d=r.query.token;if(d&&userSessions.has(d)){const p=userSessions.get(d);if(p?.onetime){userSessions.delete(d);const x=(0,external_crypto_.randomBytes)(16).toString("hex");userSessions.set(x,{role:p.role,name:p.name,lastUsed:Date.now()}),setSessionCookie(t,x)}else setSessionCookie(t,d);const h=r.path+(Object.keys(r.query).filter((x=>x!=="token")).length?"?"+new URLSearchParams(Object.fromEntries(Object.entries(r.query).filter((([x])=>x!=="token")))):"");return t.redirect(h)}if(hasValidSession(r.headers.cookie)){if(isExclusiveMode()&&activeUser){const p=getSessionToken(r.headers.cookie);if(p!==TOKEN){const h=userSessions.get(p);if(!h||h.name!==activeUser.name)return t.setHeader("Set-Cookie",`${SESSION_COOKIE}=; HttpOnly; SameSite=Strict; Path=/; Max-Age=0`),t.redirect("/login")}}return u()}t.redirect("/login")}const server_require=(0,external_module_namespaceObject.createRequire)(import.meta.url);function pkgDirSafe(r){try{return(0,external_path_.dirname)(server_require.resolve(`${r}/package.json`))}catch{return null}}const libDir=(0,external_path_.join)(server_dirname,"lib"),staticOpts={maxAge:864e5};app.use("/lib/xterm",express.static(pkgDirSafe("xterm")||(0,external_path_.join)(libDir,"xterm"),staticOpts)),app.use("/lib/xterm-fit",express.static(pkgDirSafe("xterm-addon-fit")||(0,external_path_.join)(libDir,"xterm-fit"),staticOpts)),app.use("/lib/xterm-links",express.static(pkgDirSafe("xterm-addon-web-links")||(0,external_path_.join)(libDir,"xterm-links"),staticOpts));const _loginAttempts=new Map,LOGIN_MAX_ATTEMPTS=5,LOGIN_LOCKOUT_MS=300*1e3;function checkLoginRate(r){const t=Date.now(),u=_loginAttempts.get(r);return!u||t>u.resetAt?!0:u.count<LOGIN_MAX_ATTEMPTS}function recordLoginFailure(r){const t=Date.now(),u=_loginAttempts.get(r);!u||t>u.resetAt?_loginAttempts.set(r,{count:1,resetAt:t+LOGIN_LOCKOUT_MS}):u.count++}function clearLoginFailures(r){_loginAttempts.delete(r)}setInterval((()=>{const r=Date.now();for(const[t,u]of _loginAttempts)r>u.resetAt&&_loginAttempts.delete(t)}),600*1e3),app.get("/login",((r,t)=>{t.sendFile(__nccwpck_require__.ab+"login.html")})),app.post("/login",express.urlencoded({extended:!1}),((r,t)=>{const u=r.ip;if(!checkLoginRate(u))return t.redirect("/login?error=locked");loadRoles(),loadUsers();const d=r.body?.password,p=r.query.from,h=p&&p.startsWith("/")&&!p.startsWith("//")?p:"/";if(hasUsers()){const j=lookupUser(d);if(!j)return recordLoginFailure(u),t.redirect("/login?error=1");if(isExclusiveMode()&&activeUser&&activeUser.name!==j.name)return t.redirect("/login?error=occupied&user="+encodeURIComponent(activeUser.name));clearLoginFailures(u);const b=(0,external_crypto_.randomBytes)(16).toString("hex");return userSessions.set(b,{role:"operator",name:j.name,dir:j.dir,lastUsed:Date.now()}),isExclusiveMode()&&(activeUser?activeUser.tokens.add(b):activeUser={name:j.name,dir:j.dir,tokens:new Set([b]),loginAt:Date.now()}),setSessionCookie(t,b),console.log(`[\u767B\u5F55] ${j.name} \u767B\u5F55\uFF08${isExclusiveMode()?"\u72EC\u5360":"\u5171\u4EAB"}\u6A21\u5F0F\uFF09`),t.redirect(h)}const x=lookupPassword(d);if(x){clearLoginFailures(u);const j=(0,external_crypto_.randomBytes)(16).toString("hex");return userSessions.set(j,{role:x.role,name:x.name,lastUsed:Date.now()}),setSessionCookie(t,j),t.redirect(h)}if(d===PASSWORD){clearLoginFailures(u);const j=(0,external_crypto_.randomBytes)(16).toString("hex");return userSessions.set(j,{role:"admin",name:"\u7BA1\u7406\u5458",lastUsed:Date.now()}),setSessionCookie(t,j),t.redirect(h)}recordLoginFailure(u),t.redirect("/login?error=1")})),app.post("/logout",((r,t)=>{const u=getSessionToken(r.headers.cookie);u&&(activeUser&&activeUser.tokens.has(u)&&(activeUser.tokens.delete(u),activeUser.tokens.size===0?(console.log(`[\u9000\u51FA] ${activeUser.name} \u5168\u90E8\u8BBE\u5907\u9000\u51FA\uFF0C\u91CA\u653E\u767B\u5F55\u72B6\u6001\uFF08\u4F1A\u8BDD\u4FDD\u7559\uFF09`),activeUser=null):console.log(`[\u9000\u51FA] ${activeUser.name} \u4E00\u4E2A\u8BBE\u5907\u9000\u51FA\uFF08\u5269\u4F59 ${activeUser.tokens.size} \u4E2A\uFF09`)),userSessions.delete(u)),t.setHeader("Set-Cookie",`${SESSION_COOKIE}=; HttpOnly; SameSite=Strict; Path=/; Max-Age=0`),t.redirect("/login")})),app.get("/api/status",((r,t)=>{if(isExclusiveMode()&&activeUser)return t.json({occupied:!0,userName:activeUser.name,releasing:!!_exclusiveReleaseTimer});if(hasUsers()&&!isExclusiveMode()){const u=new Set;for(const[,d]of io.sockets.sockets){if(!d.data.userName||d.data.userName==="\u7BA1\u7406\u5458")continue;const p=d.handshake.headers.cookie;p&&!hasValidSession(p)||u.add(d.data.userName)}return t.json({occupied:!1,onlineUsers:[...u]})}t.json({occupied:!1})})),app.get("/admin",((r,t)=>t.sendFile(__nccwpck_require__.ab+"admin.html"))),app.get("/sw.js",((r,t)=>{t.setHeader("Service-Worker-Allowed","/"),t.sendFile(__nccwpck_require__.ab+"sw.js")})),app.get("/",checkAuth,((r,t)=>t.sendFile(__nccwpck_require__.ab+"index.html"))),app.get("/terminal/:id",checkAuth,((r,t)=>t.sendFile(__nccwpck_require__.ab+"chat.html"))),app.get("/files",checkAuth,((r,t)=>t.sendFile(__nccwpck_require__.ab+"files.html"))),app.use("/lib",express.static(__nccwpck_require__.ab+"lib",staticOpts)),app.get("/api/sessions",checkAuth,((r,t)=>{const u=getUserInfo(r.headers.cookie);t.json(manager.list(u?.name,u?.role==="admin"))})),app.get("/api/usage",checkAuth,((r,t)=>{try{const u=manager.listSessions().filter((p=>p.mode==="agent"&&p.alive)).map((p=>({id:p.id,title:p.title,owner:p.owner,usage:p._usage})));let d=null;for(const p of u)if(p.usage?.rateLimitInfo){d=p.usage.rateLimitInfo;break}t.json({rateLimit:d,activeSessions:u})}catch(u){t.status(500).json({error:u.message})}})),app.post("/api/sessions",checkAuth,express.json(),((r,t)=>{const u=getUserInfo(r.headers.cookie),d=manager.createAgent({...r.body,owner:u?.name,userDir:u?.dir});t.status(201).json(d.toJSON())})),app.delete("/api/sessions/:id",checkAuth,((r,t)=>{manager.kill(r.params.id),t.status(204).end()})),app.get("/api/claude-sessions",checkAuth,((r,t)=>{const u=getUserInfo(r.headers.cookie);t.json(listLocalClaudeSessions(u?.dir))})),app.get("/api/dirs",checkAuth,((r,t)=>{const u=getUserInfo(r.headers.cookie);if(!u||u.role!=="admin")return t.status(403).json({error:"\u6CA1\u6709\u76EE\u5F55\u6D4F\u89C8\u6743\u9650"});const d=u.dir?(0,external_path_.resolve)((0,external_path_.normalize)(u.dir)):null,p=process.platform==="win32"?"\\":"/";let h=r.query.path||d||process.env.ZIHI_CWD||(0,external_os_.homedir)(),x=(0,external_path_.resolve)((0,external_path_.normalize)(h)).replace(/[/\\]+$/,"");process.platform==="win32"&&/^[A-Za-z]:$/.test(x)&&(x+="\\"),d&&!x.startsWith(d)&&(x=d);try{const j=(0,external_fs_.readdirSync)(x,{withFileTypes:!0}).filter(($=>$.isDirectory()&&!$.name.startsWith("."))).map(($=>({name:$.name,path:x.replace(/[/\\]+$/,"")+p+$.name}))).sort((($,O)=>$.name.localeCompare(O.name))),b=(0,external_path_.join)(x,".."),w=!d||(0,external_path_.resolve)((0,external_path_.normalize)(b)).startsWith(d);t.json({current:x,parent:w&&b!==x?b:null,dirs:j})}catch(j){t.status(400).json({error:sanitizeError(j.message)})}})),app.get("/api/me",checkAuth,((r,t)=>{const u=getUserInfo(r.headers.cookie);t.json({name:u?.name||"\u7528\u6237",exclusive:isExclusiveMode(),hasUsers:hasUsers(),dir:u?.dir||null})}));function getPkgVersion(){for(const r of["../package.json","./package.json","package.json"])try{const t=JSON.parse((0,external_fs_.readFileSync)((0,external_path_.join)(server_dirname,r),"utf8")).version;if(t&&t!=="0.0.0")return t}catch{}return"0.0.0"}const PKG_VERSION=getPkgVersion();let _latestVersion=null,_lastVersionCheck=0;const VERSION_CHECK_INTERVAL=600*1e3;async function checkLatestVersion(){const r=Date.now();if(_latestVersion&&r-_lastVersionCheck<VERSION_CHECK_INTERVAL)return _latestVersion;try{const t=await fetch("https://registry.npmjs.org/@wendongfly/zihi/latest",{headers:{Accept:"application/json"},signal:AbortSignal.timeout(8e3)});t.ok&&(_latestVersion=(await t.json()).version,_lastVersionCheck=r)}catch{}return _latestVersion}app.get("/api/version",(async(r,t)=>{const u=getPkgVersion(),d=await checkLatestVersion();t.json({current:u,latest:d||u,updateAvailable:d&&d!==u})})),app.post("/api/git/push",checkAuth,express.json(),(async(r,t)=>{const{sessionId:u,url:d,username:p,password:h,message:x,branch:j}=r.body||{};if(!u||!x)return t.status(400).json({ok:!1,error:"\u7F3A\u5C11\u53C2\u6570"});const b=manager.get(u);if(!b)return t.status(404).json({ok:!1,error:"\u4F1A\u8BDD\u4E0D\u5B58\u5728"});const w=b.cwd||process.cwd(),$=process.platform==="win32",O="git";function I(U,z={}){return new Promise(((N,B)=>{const L={...process.env,GIT_TERMINAL_PROMPT:"0"},W=(0,external_path_.join)(w,".gitconfig");(0,external_fs_.existsSync)(W)&&(L.GIT_CONFIG_GLOBAL=W);const H=(0,external_child_process_namespaceObject.spawn)(O,U,{cwd:w,env:L,timeout:6e4});let V="",J="";H.stdout.on("data",(G=>V+=G)),H.stderr.on("data",(G=>J+=G)),H.on("close",(G=>G===0?N(V.trim()):B(new Error(J.trim()||`exit ${G}`)))),H.on("error",B)}))}try{try{await I(["rev-parse","--git-dir"])}catch{await I(["init"])}if(d&&p&&h){const B=new URL(d);B.username=encodeURIComponent(p),B.password=encodeURIComponent(h);const L=B.toString(),W=(0,external_path_.join)(w,".git-credentials");(0,external_fs_.writeFileSync)(W,L+`
469
469
  `,{mode:384});const H=(0,external_path_.join)(w,".gitconfig"),J=`[credential]
470
470
  helper = store --file ${W.replace(/\\/g,"/")}
471
471
  [user]
@@ -475,7 +475,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
475
475
  helper = store --file ${x.replace(/\\/g,"/")}
476
476
  [user]
477
477
  name = ${d}
478
- `,{mode:384})}catch{}console.log(`[\u7BA1\u7406] \u6DFB\u52A0\u7528\u6237 ${d} (\u76EE\u5F55: ${p})`),t.json({ok:!0})})),app.delete("/api/admin/user",checkAdminAuth,express.json(),((r,t)=>{const{name:u}=r.body||{};if(!u)return t.json({ok:!1,error:"\u8BF7\u6307\u5B9A\u7528\u6237\u540D\u79F0"});if(loadUsers(),!listUsers().find((h=>h.name===u)))return t.json({ok:!1,error:"\u7528\u6237\u4E0D\u5B58\u5728"});try{const h=(0,external_path_.join)(configDir,"users.json"),x=JSON.parse((0,external_fs_.readFileSync)(h,"utf8"));for(const[j,b]of Object.entries(x.users||{}))if(b.name===u){delete x.users[j];break}(0,external_fs_.writeFileSync)(h,JSON.stringify(x,null,2),{mode:384}),loadUsers(),console.log(`[\u7BA1\u7406] \u5220\u9664\u7528\u6237 ${u}`),t.json({ok:!0})}catch(h){t.json({ok:!1,error:h.message})}})),app.post("/api/admin/user/password",checkAdminAuth,express.json(),((r,t)=>{const{name:u,password:d}=r.body||{};if(!u||!d)return t.json({ok:!1,error:"\u540D\u79F0\u548C\u65B0\u5BC6\u7801\u5FC5\u586B"});try{const p=(0,external_path_.join)(configDir,"users.json"),h=JSON.parse((0,external_fs_.readFileSync)(p,"utf8"));let x=null;for(const[j,b]of Object.entries(h.users||{}))if(b.name===u){x=b,delete h.users[j];break}if(!x)return t.json({ok:!1,error:"\u7528\u6237\u4E0D\u5B58\u5728"});h.users[d]=x,(0,external_fs_.writeFileSync)(p,JSON.stringify(h,null,2),{mode:384}),loadUsers(),console.log(`[\u7BA1\u7406] \u4FEE\u6539\u7528\u6237 ${u} \u7684\u5BC6\u7801`),t.json({ok:!0})}catch(p){t.json({ok:!1,error:p.message})}})),app.post("/api/admin/password",checkAdminAuth,express.json(),((r,t)=>{const{password:u}=r.body||{};if(!u||u.length<4)return t.json({ok:!1,error:"\u5BC6\u7801\u81F3\u5C114\u4F4D"});try{(0,external_fs_.writeFileSync)((0,external_path_.join)(configDir,"password"),u,{mode:384}),PASSWORD=u,t.json({ok:!0}),console.log("[\u7BA1\u7406] \u7BA1\u7406\u5BC6\u7801\u5DF2\u4FEE\u6539")}catch(d){t.json({ok:!1,error:d.message})}})),app.post("/upload",checkAuth,((r,t)=>{const u=r.query.sessionId,d=u?manager.get(u):null,p=d?.cwd?(0,external_path_.join)(d.cwd,"upload"):uploadDir;(0,external_fs_.mkdirSync)(p,{recursive:!0}),multer({storage:multer.diskStorage({destination:p,filename:(x,j,b)=>{const w=j.originalname.match(/\.[^.]+$/)?.[0]||".jpg";b(null,`${Date.now()}-${(0,external_crypto_.randomBytes)(3).toString("hex")}${w}`)}}),limits:{fileSize:20*1024*1024},fileFilter:(x,j,b)=>b(null,j.mimetype.startsWith("image/")),defParamCharset:"utf-8"}).single("image")(r,t,(x=>{if(x)return t.status(400).json({error:x.message});if(!r.file)return t.status(400).json({error:"\u6CA1\u6709\u56FE\u7247"});t.json({path:(0,external_path_.resolve)(r.file.path).replace(/\\/g,"/")})}))})),app.get("/api/files/list",checkAuth,((r,t)=>{const u=resolveUserFilePath(r,r.query.path);if(u.error)return t.status(u.status).json({error:u.error});try{if(!(0,external_fs_.statSync)(u.resolved).isDirectory())return t.status(400).json({error:"\u4E0D\u662F\u76EE\u5F55"});const p=r.query.showHidden==="1",h=(0,external_fs_.readdirSync)(u.resolved,{withFileTypes:!0}).filter(($=>p||!$.name.startsWith("."))).map(($=>{try{const O=(0,external_path_.join)(u.resolved,$.name),I=(0,external_fs_.statSync)(O);return{name:$.name,type:$.isDirectory()?"dir":"file",size:I.size,mtime:I.mtime}}catch{return{name:$.name,type:$.isDirectory()?"dir":"file",size:0,mtime:null}}})).sort((($,O)=>$.type===O.type?$.name.localeCompare(O.name):$.type==="dir"?-1:1)),x=(0,external_path_.join)(u.resolved,".."),j=(0,external_path_.resolve)((0,external_path_.normalize)(x)),b=j.startsWith(u.userRoot)&&j!==u.resolved,w=u.resolved.startsWith(u.userRoot)?u.resolved.slice(u.userRoot.length).replace(/^[/\\]+/,""):"";t.json({current:u.resolved.replace(/\\/g,"/"),currentRel:w.replace(/\\/g,"/"),parent:b?j.replace(/\\/g,"/"):null,root:u.userRoot.replace(/\\/g,"/"),entries:h})}catch(d){t.status(400).json({error:d.message})}})),app.post("/api/files/upload",checkAuth,((r,t)=>{const u=resolveUserFilePath(r,r.query.path);if(u.error)return t.status(u.status).json({error:u.error});(0,external_fs_.mkdirSync)(u.resolved,{recursive:!0}),multer({storage:multer.diskStorage({destination:(p,h,x)=>{const j=h.originalname||"",b=j.lastIndexOf("/"),w=b>0?j.slice(0,b):"",$=w?(0,external_path_.join)(u.resolved,w):u.resolved;(0,external_fs_.mkdirSync)($,{recursive:!0}),x(null,$)},filename:(p,h,x)=>{const j=h.originalname||"",b=j.lastIndexOf("/"),w=b>0?j.slice(b+1):(0,external_path_.basename)(j);x(null,w||`${Date.now()}.bin`)}}),limits:{fileSize:500*1024*1024},defParamCharset:"utf-8"}).array("files",100)(r,t,(p=>{if(p)return t.status(400).json({error:p.message});if(!r.files?.length)return t.status(400).json({error:"\u6CA1\u6709\u6587\u4EF6"});const h={ok:!0,files:r.files.map((j=>({name:j.filename,path:(0,external_path_.resolve)(j.path).replace(/\\/g,"/"),size:j.size})))};t.json(h);const x=r.query.sessionId;x&&io.to(x).emit("files:changed",{sessionId:x})}))})),app.get("/api/files/download",checkAuth,((r,t)=>{if(!r.query.path)return t.status(400).json({error:"\u7F3A\u5C11 path \u53C2\u6570"});const u=resolveUserFilePath(r,r.query.path);if(u.error)return t.status(u.status).json({error:u.error});try{const d=(0,external_fs_.statSync)(u.resolved);if(!d.isFile())return t.status(400).json({error:"\u4E0D\u662F\u6587\u4EF6"});const p=(0,external_path_.basename)(u.resolved);t.setHeader("Content-Type",getMime(p)),t.setHeader("Content-Length",d.size),t.setHeader("Content-Disposition",`attachment; filename*=UTF-8''${encodeURIComponent(p)}`),(0,external_fs_.createReadStream)(u.resolved).pipe(t)}catch(d){t.status(404).json({error:d.message})}})),app.get("/api/files/preview",checkAuth,((r,t)=>{if(!r.query.path)return t.status(400).json({error:"\u7F3A\u5C11 path \u53C2\u6570"});const u=resolveUserFilePath(r,r.query.path);if(u.error)return t.status(u.status).json({error:u.error});try{const d=(0,external_fs_.statSync)(u.resolved);if(!d.isFile())return t.status(400).json({error:"\u4E0D\u662F\u6587\u4EF6"});const p=(0,external_path_.basename)(u.resolved),h=getMime(p);t.setHeader("Content-Type",h),t.setHeader("Content-Length",d.size),t.setHeader("Content-Disposition",`inline; filename*=UTF-8''${encodeURIComponent(p)}`),(0,external_fs_.createReadStream)(u.resolved).pipe(t)}catch(d){t.status(404).json({error:d.message})}})),app.post("/api/files/mkdir",checkAuth,express.json(),((r,t)=>{const{path:u}=r.body||{};if(!u)return t.status(400).json({error:"\u7F3A\u5C11 path"});const d=resolveUserFilePath(r,u);if(d.error)return t.status(d.status).json({error:d.error});try{(0,external_fs_.mkdirSync)(d.resolved,{recursive:!0}),t.json({ok:!0,path:d.resolved.replace(/\\/g,"/")})}catch(p){t.status(400).json({error:p.message})}})),app.delete("/api/files/delete",checkAuth,express.json(),((r,t)=>{const u=getUserInfo(r.headers.cookie);if(!u||u.role!=="admin")return t.status(403).json({error:"\u4EC5\u7BA1\u7406\u5458\u53EF\u5220\u9664"});const{path:d}=r.body||{};if(!d)return t.status(400).json({error:"\u7F3A\u5C11 path"});const p=resolveUserFilePath(r,d);if(p.error)return t.status(p.status).json({error:p.error});if(p.resolved===p.userRoot)return t.status(403).json({error:"\u4E0D\u5141\u8BB8\u5220\u9664\u6839\u76EE\u5F55"});try{(0,external_fs_.statSync)(p.resolved).isDirectory()?(0,external_fs_.rmSync)(p.resolved,{recursive:!1}):(0,external_fs_.unlinkSync)(p.resolved),t.json({ok:!0});const x=r.body?.sessionId||r.query.sessionId;x&&io.to(x).emit("files:changed",{sessionId:x})}catch(h){t.status(400).json({error:h.message})}})),app.get("/api/files/manifest",checkAuth,((r,t)=>{const u=resolveUserFilePath(r,r.query.path);if(u.error)return t.status(u.status).json({error:u.error});try{if(!(0,external_fs_.statSync)(u.resolved).isDirectory())return t.status(400).json({error:"\u4E0D\u662F\u76EE\u5F55"});const p=walkFiles(u.resolved,"");t.json({ok:!0,cwd:u.resolved.replace(/\\/g,"/"),path:(r.query.path||"").replace(/\\/g,"/"),files:p})}catch(d){t.status(400).json({error:d.message})}})),app.get("/api/sync/config",checkAuth,((r,t)=>{const u=getUserInfo(r.headers.cookie),d=loadSyncConfig(),p=u?.name||"_default";t.json(d[p]||{projects:[]})})),app.post("/api/sync/config",checkAuth,express.json(),((r,t)=>{const d=getUserInfo(r.headers.cookie)?.name||"_default",p=loadSyncConfig();p[d]=r.body,saveSyncConfig(p),t.json({ok:!0})})),app.get("/api/sync/tree",checkAuth,((r,t)=>{const u=resolveUserFilePath(r,r.query.path);if(u.error)return t.status(u.status).json({error:u.error});try{if(!(0,external_fs_.statSync)(u.resolved).isDirectory())return t.status(400).json({error:"\u4E0D\u662F\u76EE\u5F55"});const p=r.query.ignore?JSON.parse(r.query.ignore):DEFAULT_IGNORE,h=scanDirTree(u.resolved,p,{withHash:r.query.hash==="1",showHidden:r.query.showHidden==="1"});t.json({root:u.resolved.replace(/\\/g,"/"),tree:h})}catch(d){t.status(400).json({error:d.message})}})),app.post("/api/sync/pull-file",checkAuth,express.json(),((r,t)=>{const{path:u}=r.body||{};if(!u)return t.status(400).json({error:"\u7F3A\u5C11 path"});const d=resolveUserFilePath(r,u);if(d.error)return t.status(d.status).json({error:d.error});try{const p=(0,external_fs_.statSync)(d.resolved);if(!p.isFile())return t.status(400).json({error:"\u4E0D\u662F\u6587\u4EF6"});t.setHeader("Content-Type","application/octet-stream"),t.setHeader("Content-Length",p.size),(0,external_fs_.createReadStream)(d.resolved).pipe(t)}catch(p){t.status(404).json({error:p.message})}})),app.post("/api/sync/push-file",checkAuth,((r,t)=>{const u=r.query.path;if(!u)return t.status(400).json({error:"\u7F3A\u5C11 path"});const d=resolveUserFilePath(r,u);if(d.error)return t.status(d.status).json({error:d.error});const p=(0,external_path_.join)(d.resolved,"..");(0,external_fs_.mkdirSync)(p,{recursive:!0}),multer({storage:multer.diskStorage({destination:p,filename:(x,j,b)=>b(null,(0,external_path_.basename)(d.resolved))}),limits:{fileSize:500*1024*1024}}).single("file")(r,t,(x=>{if(x)return t.status(400).json({error:x.message});if(!r.file)return t.status(400).json({error:"\u6CA1\u6709\u6587\u4EF6"});t.json({ok:!0,path:d.resolved.replace(/\\/g,"/"),size:r.file.size})}))})),app.post("/api/sync/delete-file",checkAuth,express.json(),((r,t)=>{const{path:u}=r.body||{};if(!u)return t.status(400).json({error:"\u7F3A\u5C11 path"});const d=resolveUserFilePath(r,u);if(d.error)return t.status(d.status).json({error:d.error});if(d.resolved===d.userRoot)return t.status(403).json({error:"\u4E0D\u5141\u8BB8\u5220\u9664\u6839\u76EE\u5F55"});try{if((0,external_fs_.statSync)(d.resolved).isDirectory())return t.status(400).json({error:"\u4E0D\u80FD\u901A\u8FC7\u540C\u6B65\u5220\u9664\u76EE\u5F55"});(0,external_fs_.unlinkSync)(d.resolved),t.json({ok:!0})}catch(p){t.status(400).json({error:p.message})}})),app.get("/qr/:sessionId",checkAuth,(async(r,t)=>{const u=getTailscaleIP(),d=(0,external_crypto_.randomBytes)(16).toString("hex");userSessions.set(d,{role:"admin",name:"\u626B\u7801\u7528\u6237",onetime:!0,lastUsed:Date.now()});const p=`http://${u}:${PORT}/terminal/${r.params.sessionId}?token=${d}`;try{const h=await lib.toString(p,{type:"svg"});t.setHeader("Content-Type","image/svg+xml"),t.send(h)}catch(h){t.status(500).send(h.message)}})),io.use(((r,t)=>{const u=r.handshake.headers.cookie;if(hasValidSession(u)){const h=getUserInfo(u);return r.data.role=h?.role||"admin",r.data.userName=h?.name||"\u7528\u6237",r.data.dir=h?.dir||null,t()}const d=r.handshake.auth?.password;if(d){loadUsers();const h=lookupUser(d);if(h)return r.data.role="operator",r.data.userName=h.name,r.data.dir=h.dir,t()}if((r.handshake.auth?.token||r.handshake.query?.token)===TOKEN)return r.data.role="admin",r.data.userName="\u7BA1\u7406\u5458",t();t(new Error("\u672A\u6388\u6743"))}));const EXCLUSIVE_RELEASE_DELAY=120*1e3;let _exclusiveReleaseTimer=null;function checkExclusiveRelease(){if(!isExclusiveMode()||!activeUser)return;let r=!1;for(const[,t]of io.sockets.sockets)if(t.data.userName===activeUser.name){r=!0;break}if(r){_exclusiveReleaseTimer&&(clearTimeout(_exclusiveReleaseTimer),_exclusiveReleaseTimer=null);return}_exclusiveReleaseTimer||(_exclusiveReleaseTimer=setTimeout((()=>{if(_exclusiveReleaseTimer=null,!!activeUser){for(const[,t]of io.sockets.sockets)if(t.data.userName===activeUser.name)return;console.log(`[\u72EC\u5360] ${activeUser.name} \u5DF2\u79BB\u7EBF\u8D85\u65F6\uFF0C\u91CA\u653E\u767B\u5F55\u72B6\u6001\uFF08\u4F1A\u8BDD\u4FDD\u7559\uFF09`);for(const t of activeUser.tokens)userSessions.delete(t);activeUser=null}}),EXCLUSIVE_RELEASE_DELAY))}let _broadcastTimer=null;function broadcastSessions(){_broadcastTimer||(_broadcastTimer=setTimeout((()=>{_broadcastTimer=null;for(const[,r]of io.sockets.sockets)r.emit("sessions",manager.list(r.data.userName,r.data.role==="admin"))}),100))}io.on("connection",(r=>{const t=r.handshake.address?.replace("::ffff:","")||"?",u=r.handshake.headers?.referer||"?";console.log(`[\u8FDE\u63A5] ${r.data.userName}(${r.data.role}) \u4ECE ${t} \u63A5\u5165 id=${r.id} \u9875\u9762=${u}`),_exclusiveReleaseTimer&&activeUser&&r.data.userName===activeUser.name&&(clearTimeout(_exclusiveReleaseTimer),_exclusiveReleaseTimer=null);let d=null,p=null,h=null,x=null,j=null;function b(){d&&(d.isController(r.id)&&(d.releaseControl(),io.emit("control-changed",{sessionId:d.id,holder:null,holderName:null})),d.removeViewer(r.id),p&&d.off("data",p),h&&d.off("agent:message",h),x&&d.off("agent:busy",x),j&&d.off("agent:error",j),p=null,h=null,x=null,j=null)}r.on("join",(w=>{const $=manager.get(w);if(!$){r.emit("error",{message:`\u4F1A\u8BDD ${w} \u672A\u627E\u5230`});return}b(),d=$,d.addViewer(r.id,r.data.userName),r.join(w),h=O=>r.emit("agent:message",O),d.on("agent:message",h),x=O=>r.emit("agent:busy",O),d.on("agent:busy",x),j=O=>r.emit("agent:error",O),d.on("agent:error",j),console.log(`[\u52A0\u5165] ${r.data.userName} \u52A0\u5165\u4F1A\u8BDD "${$.title}" (${w})`),r.emit("joined",{...$.toJSON(),role:r.data.role}),$._history?.length&&r.emit("agent:history",$._history),broadcastSessions()})),r.on("disconnect",(w=>{console.log(`[\u65AD\u5F00] ${r.data.userName} \u79BB\u5F00\u4F1A\u8BDD "${d?.title||"?"}" id=${r.id} \u539F\u56E0=${w}`),b(),broadcastSessions(),checkExclusiveRelease(),manager.persist()})),r.on("agent:query",(async({prompt:w}={})=>{if(!d||d.mode!=="agent"){r.emit("agent:error",{message:"\u5F53\u524D\u4E0D\u662F Agent \u6A21\u5F0F\u4F1A\u8BDD"});return}if(!d.isController(r.id)){r.emit("control-denied",{reason:"\u4F60\u6CA1\u6709\u5F53\u524D\u4F1A\u8BDD\u7684\u63A7\u5236\u6743"});return}if(d.isBusy){r.emit("agent:error",{message:"\u6B63\u5728\u5904\u7406\u4E2D\uFF0C\u8BF7\u7B49\u5F85\u5B8C\u6210"});return}try{await d.query(w)}catch($){console.error("[agent:query] \u9519\u8BEF:",$.message);try{r.connected&&r.emit("agent:error",{message:$.message})}catch{}}})),r.on("agent:interrupt",(()=>{!d||d.mode!=="agent"||d.interrupt()})),r.on("agent:permission",(({requestId:w,allow:$,toolName:O,approveAll:I}={})=>{if(!(!d||d.mode!=="agent")){if(!d.isController(r.id)){r.emit("control-denied",{reason:"\u4F60\u6CA1\u6709\u5F53\u524D\u4F1A\u8BDD\u7684\u63A7\u5236\u6743"});return}d.respondPermission(w,$,O,I)}})),r.on("set-mode",(({sessionId:w,mode:$}={})=>{const O=w?manager.get(w):d;O&&(O.setPermissionMode&&(O.setPermissionMode($),console.log(`[\u6A21\u5F0F] ${r.data.userName} \u5207\u6362\u4F1A\u8BDD "${O.title}" \u4E3A ${$}`)),io.emit("mode-changed",{sessionId:O.id,mode:$}),manager.persist())})),r.on("create-agent",((w,$)=>{if(!hasPermission(r.data.role,"operator")){typeof $=="function"&&$({ok:!1,error:"\u6CA1\u6709\u521B\u5EFA\u4F1A\u8BDD\u7684\u6743\u9650"});return}if(r.data.dir){const I=(0,external_path_.resolve)((0,external_path_.normalize)(r.data.dir)),U=w?.cwd?(0,external_path_.resolve)((0,external_path_.normalize)(w.cwd)):null;if(U&&U!==I&&!U.startsWith(I+external_path_.sep)){typeof $=="function"&&$({ok:!1,error:"\u4E0D\u80FD\u5728\u7ED1\u5B9A\u76EE\u5F55\u4E4B\u5916\u521B\u5EFA\u4F1A\u8BDD"});return}U||(w={...w,cwd:I})}const O=w?.cwd||process.env.ZIHI_CWD||process.cwd();if(!(0,external_fs_.existsSync)(O))try{(0,external_fs_.mkdirSync)(O,{recursive:!0}),console.log(`[\u521B\u5EFA] \u81EA\u52A8\u521B\u5EFA\u76EE\u5F55: ${O}`)}catch(I){typeof $=="function"&&$({ok:!1,error:`\u521B\u5EFA\u76EE\u5F55\u5931\u8D25: ${I.message}`});return}try{const I=manager.createAgent({...w,owner:r.data.userName,userDir:r.data.dir});console.log(`[\u4F1A\u8BDD] ${r.data.userName} \u521B\u5EFA Agent \u4F1A\u8BDD "${I.title}" (${I.id})`),broadcastSessions(),typeof $=="function"&&$({ok:!0,session:I.toJSON()})}catch(I){typeof $=="function"&&$({ok:!1,error:I.message})}})),r.on("take-control",(({sessionId:w}={})=>{const $=w?manager.get(w):d;if($){if(!hasPermission(r.data.role,"operator")){r.emit("control-denied",{reason:"\u4F60\u7684\u89D2\u8272\u6CA1\u6709\u63A7\u5236\u6743\u9650"});return}if($.controlHolder&&$.controlHolder!==r.id){const O=$.controlHolderName===r.data.userName;if(r.data.role!=="admin"&&!O){r.emit("control-denied",{reason:"\u5176\u4ED6\u7528\u6237\u6B63\u5728\u63A7\u5236\u4E2D\uFF0C\u8BF7\u7B49\u5F85\u91CA\u653E"});return}}$.takeControl(r.id,r.data.userName),console.log(`[\u63A7\u5236] ${r.data.userName} \u83B7\u53D6\u4F1A\u8BDD "${$.title}" \u7684\u63A7\u5236\u6743`),io.emit("control-changed",{sessionId:$.id,holder:r.id,holderName:r.data.userName})}})),r.on("release-control",(({sessionId:w}={})=>{const $=w?manager.get(w):d;$&&$.isController(r.id)&&(console.log(`[\u63A7\u5236] ${r.data.userName} \u91CA\u653E\u4F1A\u8BDD "${$.title}" \u7684\u63A7\u5236\u6743`),$.releaseControl(),io.emit("control-changed",{sessionId:$.id,holder:null,holderName:null}))})),r.on("rename",(({sessionId:w,title:$}={})=>{const O=w?manager.get(w):d;!O||!$||(O.title=$,io.emit("session-renamed",{sessionId:O.id,title:$}),broadcastSessions(),manager.persist())})),r.on("resize",(({cols:w,rows:$})=>d?.resize(w,$))),r.on("list",(()=>r.emit("sessions",manager.list(r.data.userName,r.data.role==="admin")))),r.on("dirs",((w,$)=>{if(typeof $!="function")return;const O=r.data.dir?(0,external_path_.resolve)((0,external_path_.normalize)(r.data.dir)):null,I=process.platform==="win32"?"\\":"/";let U=(w||O||process.env.ZIHI_CWD||(0,external_os_.homedir)()).replace(/[/\\]+$/,"")||(0,external_os_.homedir)();process.platform==="win32"&&/^[A-Za-z]:$/.test(U)&&(U+="\\");const z=(0,external_path_.resolve)((0,external_path_.normalize)(U));O&&z!==O&&!z.startsWith(O+I)&&(U=O);try{const N=(0,external_fs_.readdirSync)(U,{withFileTypes:!0}).filter((H=>H.isDirectory()&&!H.name.startsWith("."))).map((H=>({name:H.name,path:U.replace(/[/\\]+$/,"")+I+H.name}))).sort(((H,V)=>H.name.localeCompare(V.name))),B=(0,external_path_.join)(U,".."),L=(0,external_path_.resolve)((0,external_path_.normalize)(B)),W=!O||L===O||L.startsWith(O+I);$({ok:!0,current:U,parent:W&&B!==U?B:null,dirs:N})}catch(N){$({ok:!1,error:N.message})}})),r.on("kill",(w=>{if(!hasPermission(r.data.role,"operator")){r.emit("error",{message:"\u6CA1\u6709\u5220\u9664\u4F1A\u8BDD\u7684\u6743\u9650"});return}console.log(`[\u4F1A\u8BDD] ${r.data.userName} \u5220\u9664\u4F1A\u8BDD ${w}`),manager.kill(w),broadcastSessions()})),r.on("kick-user",(({socketId:w,sessionId:$}={},O)=>{if(!hasPermission(r.data.role,"admin")){typeof O=="function"&&O({ok:!1,error:"\u6CA1\u6709\u8E22\u51FA\u7528\u6237\u7684\u6743\u9650"});return}const I=io.sockets.sockets.get(w);if(!I){typeof O=="function"&&O({ok:!1,error:"\u76EE\u6807\u7528\u6237\u4E0D\u5728\u7EBF"});return}const U=I.data.userName||"\u672A\u77E5";console.log(`[\u8E22\u51FA] ${r.data.userName} \u8E22\u51FA\u4E86\u7528\u6237 ${U} (${w})`),I.emit("kicked",{reason:`\u4F60\u5DF2\u88AB\u7BA1\u7406\u5458 ${r.data.userName} \u8E22\u51FA`}),I.disconnect(!0),typeof O=="function"&&O({ok:!0,name:U})})),r.on("list-viewers",(({sessionId:w}={},$)=>{if(typeof $!="function")return;const O=w?manager.get(w):d;if(!O){$({ok:!1,error:"\u4F1A\u8BDD\u4E0D\u5B58\u5728"});return}const I=[];for(const U of O._viewers){const z=io.sockets.sockets.get(U);z&&I.push({socketId:U,userName:z.data.userName||"\u672A\u77E5",role:z.data.role||"viewer",isController:O.controlHolder===U})}$({ok:!0,viewers:I})}))}));const CONTROL_TIMEOUT=300*1e3;setInterval((()=>{for(const r of manager.listSessions()){r.controlHolder&&(!io.sockets.sockets.get(r.controlHolder)||r.lastInputTime&&Date.now()-r.lastInputTime>CONTROL_TIMEOUT)&&(r.releaseControl(),io.emit("control-changed",{sessionId:r.id,holder:null,holderName:null}));for(const t of r._viewers)io.sockets.sockets.has(t)||r.removeViewer(t)}}),60*1e3);function showStartupInfo(){const r=httpServer.address().port;PORT=r;const t=getTailscaleIP(),u=`http://${t}:${r}/admin`;console.log(`
478
+ `,{mode:384})}catch{}console.log(`[\u7BA1\u7406] \u6DFB\u52A0\u7528\u6237 ${d} (\u76EE\u5F55: ${p})`),t.json({ok:!0})})),app.delete("/api/admin/user",checkAdminAuth,express.json(),((r,t)=>{const{name:u}=r.body||{};if(!u)return t.json({ok:!1,error:"\u8BF7\u6307\u5B9A\u7528\u6237\u540D\u79F0"});if(loadUsers(),!listUsers().find((h=>h.name===u)))return t.json({ok:!1,error:"\u7528\u6237\u4E0D\u5B58\u5728"});try{const h=(0,external_path_.join)(configDir,"users.json"),x=JSON.parse((0,external_fs_.readFileSync)(h,"utf8"));for(const[j,b]of Object.entries(x.users||{}))if(b.name===u){delete x.users[j];break}(0,external_fs_.writeFileSync)(h,JSON.stringify(x,null,2),{mode:384}),loadUsers(),console.log(`[\u7BA1\u7406] \u5220\u9664\u7528\u6237 ${u}`),t.json({ok:!0})}catch(h){t.json({ok:!1,error:h.message})}})),app.post("/api/admin/user/password",checkAdminAuth,express.json(),((r,t)=>{const{name:u,password:d}=r.body||{};if(!u||!d)return t.json({ok:!1,error:"\u540D\u79F0\u548C\u65B0\u5BC6\u7801\u5FC5\u586B"});try{const p=(0,external_path_.join)(configDir,"users.json"),h=JSON.parse((0,external_fs_.readFileSync)(p,"utf8"));let x=null;for(const[j,b]of Object.entries(h.users||{}))if(b.name===u){x=b,delete h.users[j];break}if(!x)return t.json({ok:!1,error:"\u7528\u6237\u4E0D\u5B58\u5728"});h.users[d]=x,(0,external_fs_.writeFileSync)(p,JSON.stringify(h,null,2),{mode:384}),loadUsers(),console.log(`[\u7BA1\u7406] \u4FEE\u6539\u7528\u6237 ${u} \u7684\u5BC6\u7801`),t.json({ok:!0})}catch(p){t.json({ok:!1,error:p.message})}})),app.post("/api/admin/password",checkAdminAuth,express.json(),((r,t)=>{const{password:u}=r.body||{};if(!u||u.length<4)return t.json({ok:!1,error:"\u5BC6\u7801\u81F3\u5C114\u4F4D"});try{(0,external_fs_.writeFileSync)((0,external_path_.join)(configDir,"password"),u,{mode:384}),PASSWORD=u,t.json({ok:!0}),console.log("[\u7BA1\u7406] \u7BA1\u7406\u5BC6\u7801\u5DF2\u4FEE\u6539")}catch(d){t.json({ok:!1,error:d.message})}})),app.post("/upload",checkAuth,((r,t)=>{const u=r.query.sessionId,d=u?manager.get(u):null,p=d?.cwd?(0,external_path_.join)(d.cwd,"upload"):uploadDir;(0,external_fs_.mkdirSync)(p,{recursive:!0}),multer({storage:multer.diskStorage({destination:p,filename:(x,j,b)=>{const w=j.originalname.match(/\.[^.]+$/)?.[0]||".jpg";b(null,`${Date.now()}-${(0,external_crypto_.randomBytes)(3).toString("hex")}${w}`)}}),limits:{fileSize:20*1024*1024},fileFilter:(x,j,b)=>b(null,j.mimetype.startsWith("image/")),defParamCharset:"utf-8"}).single("image")(r,t,(x=>{if(x)return t.status(400).json({error:x.message});if(!r.file)return t.status(400).json({error:"\u6CA1\u6709\u56FE\u7247"});t.json({path:(0,external_path_.resolve)(r.file.path).replace(/\\/g,"/")})}))})),app.get("/api/files/list",checkAuth,((r,t)=>{const u=resolveUserFilePath(r,r.query.path);if(u.error)return t.status(u.status).json({error:u.error});try{if(!(0,external_fs_.statSync)(u.resolved).isDirectory())return t.status(400).json({error:"\u4E0D\u662F\u76EE\u5F55"});const p=r.query.showHidden==="1",h=(0,external_fs_.readdirSync)(u.resolved,{withFileTypes:!0}).filter(($=>p||!$.name.startsWith("."))).map(($=>{try{const O=(0,external_path_.join)(u.resolved,$.name),I=(0,external_fs_.statSync)(O);return{name:$.name,type:$.isDirectory()?"dir":"file",size:I.size,mtime:I.mtime}}catch{return{name:$.name,type:$.isDirectory()?"dir":"file",size:0,mtime:null}}})).sort((($,O)=>$.type===O.type?$.name.localeCompare(O.name):$.type==="dir"?-1:1)),x=(0,external_path_.join)(u.resolved,".."),j=(0,external_path_.resolve)((0,external_path_.normalize)(x)),b=j.startsWith(u.userRoot)&&j!==u.resolved,w=u.resolved.startsWith(u.userRoot)?u.resolved.slice(u.userRoot.length).replace(/^[/\\]+/,""):"";t.json({current:u.resolved.replace(/\\/g,"/"),currentRel:w.replace(/\\/g,"/"),parent:b?j.replace(/\\/g,"/"):null,root:u.userRoot.replace(/\\/g,"/"),entries:h})}catch(d){t.status(400).json({error:sanitizeError(d.message)})}})),app.post("/api/files/upload",checkAuth,((r,t)=>{const u=resolveUserFilePath(r,r.query.path);if(u.error)return t.status(u.status).json({error:u.error});(0,external_fs_.mkdirSync)(u.resolved,{recursive:!0}),multer({storage:multer.diskStorage({destination:(p,h,x)=>{const j=h.originalname||"",b=j.lastIndexOf("/"),w=b>0?j.slice(0,b):"",$=w?(0,external_path_.join)(u.resolved,w):u.resolved;if(!(0,external_path_.resolve)($).startsWith(u.resolved))return x(new Error("\u8DEF\u5F84\u4E0D\u5408\u6CD5"));(0,external_fs_.mkdirSync)($,{recursive:!0}),x(null,$)},filename:(p,h,x)=>{const j=h.originalname||"",b=j.lastIndexOf("/"),w=b>0?j.slice(b+1):(0,external_path_.basename)(j);x(null,w||`${Date.now()}.bin`)}}),limits:{fileSize:500*1024*1024},defParamCharset:"utf-8"}).array("files",100)(r,t,(p=>{if(p)return t.status(400).json({error:p.message});if(!r.files?.length)return t.status(400).json({error:"\u6CA1\u6709\u6587\u4EF6"});const h={ok:!0,files:r.files.map((j=>({name:j.filename,path:(0,external_path_.resolve)(j.path).replace(/\\/g,"/"),size:j.size})))};t.json(h);const x=r.query.sessionId;x&&io.to(x).emit("files:changed",{sessionId:x})}))})),app.get("/api/files/download",checkAuth,((r,t)=>{if(!r.query.path)return t.status(400).json({error:"\u7F3A\u5C11 path \u53C2\u6570"});const u=resolveUserFilePath(r,r.query.path);if(u.error)return t.status(u.status).json({error:u.error});try{const d=(0,external_fs_.statSync)(u.resolved);if(!d.isFile())return t.status(400).json({error:"\u4E0D\u662F\u6587\u4EF6"});const p=(0,external_path_.basename)(u.resolved);t.setHeader("Content-Type",getMime(p)),t.setHeader("Content-Length",d.size),t.setHeader("Content-Disposition",`attachment; filename*=UTF-8''${encodeURIComponent(p)}`),(0,external_fs_.createReadStream)(u.resolved).pipe(t)}catch(d){t.status(404).json({error:sanitizeError(d.message)})}})),app.get("/api/files/preview",checkAuth,((r,t)=>{if(!r.query.path)return t.status(400).json({error:"\u7F3A\u5C11 path \u53C2\u6570"});const u=resolveUserFilePath(r,r.query.path);if(u.error)return t.status(u.status).json({error:u.error});try{const d=(0,external_fs_.statSync)(u.resolved);if(!d.isFile())return t.status(400).json({error:"\u4E0D\u662F\u6587\u4EF6"});const p=(0,external_path_.basename)(u.resolved),h=getMime(p);t.setHeader("Content-Type",h),t.setHeader("Content-Length",d.size),t.setHeader("Content-Disposition",`inline; filename*=UTF-8''${encodeURIComponent(p)}`),(0,external_fs_.createReadStream)(u.resolved).pipe(t)}catch(d){t.status(404).json({error:sanitizeError(d.message)})}})),app.post("/api/files/mkdir",checkAuth,express.json(),((r,t)=>{const{path:u}=r.body||{};if(!u)return t.status(400).json({error:"\u7F3A\u5C11 path"});const d=resolveUserFilePath(r,u);if(d.error)return t.status(d.status).json({error:d.error});try{(0,external_fs_.mkdirSync)(d.resolved,{recursive:!0}),t.json({ok:!0,path:d.resolved.replace(/\\/g,"/")})}catch(p){t.status(400).json({error:sanitizeError(p.message)})}})),app.delete("/api/files/delete",checkAuth,express.json(),((r,t)=>{const u=getUserInfo(r.headers.cookie);if(!u||u.role!=="admin")return t.status(403).json({error:"\u4EC5\u7BA1\u7406\u5458\u53EF\u5220\u9664"});const{path:d}=r.body||{};if(!d)return t.status(400).json({error:"\u7F3A\u5C11 path"});const p=resolveUserFilePath(r,d);if(p.error)return t.status(p.status).json({error:p.error});if(p.resolved===p.userRoot)return t.status(403).json({error:"\u4E0D\u5141\u8BB8\u5220\u9664\u6839\u76EE\u5F55"});try{(0,external_fs_.statSync)(p.resolved).isDirectory()?(0,external_fs_.rmSync)(p.resolved,{recursive:!1}):(0,external_fs_.unlinkSync)(p.resolved),t.json({ok:!0});const x=r.body?.sessionId||r.query.sessionId;x&&io.to(x).emit("files:changed",{sessionId:x})}catch(h){t.status(400).json({error:sanitizeError(h.message)})}})),app.get("/qr/:sessionId",checkAuth,(async(r,t)=>{const u=getTailscaleIP(),d=(0,external_crypto_.randomBytes)(16).toString("hex");userSessions.set(d,{role:"operator",name:"\u626B\u7801\u7528\u6237",onetime:!0,lastUsed:Date.now()});const p=`http://${u}:${PORT}/terminal/${r.params.sessionId}?token=${d}`;try{const h=await lib.toString(p,{type:"svg"});t.setHeader("Content-Type","image/svg+xml"),t.send(h)}catch(h){t.status(500).send(h.message)}})),io.use(((r,t)=>{const u=r.handshake.headers.cookie;if(hasValidSession(u)){const h=getUserInfo(u);return r.data.role=h?.role||"admin",r.data.userName=h?.name||"\u7528\u6237",r.data.dir=h?.dir||null,t()}const d=r.handshake.auth?.password;if(d){loadUsers();const h=lookupUser(d);if(h)return r.data.role="operator",r.data.userName=h.name,r.data.dir=h.dir,t()}if((r.handshake.auth?.token||r.handshake.query?.token)===TOKEN)return r.data.role="admin",r.data.userName="\u7BA1\u7406\u5458",t();t(new Error("\u672A\u6388\u6743"))}));const EXCLUSIVE_RELEASE_DELAY=120*1e3;let _exclusiveReleaseTimer=null;function checkExclusiveRelease(){if(!isExclusiveMode()||!activeUser)return;let r=!1;for(const[,t]of io.sockets.sockets)if(t.data.userName===activeUser.name){r=!0;break}if(r){_exclusiveReleaseTimer&&(clearTimeout(_exclusiveReleaseTimer),_exclusiveReleaseTimer=null);return}_exclusiveReleaseTimer||(_exclusiveReleaseTimer=setTimeout((()=>{if(_exclusiveReleaseTimer=null,!!activeUser){for(const[,t]of io.sockets.sockets)if(t.data.userName===activeUser.name)return;console.log(`[\u72EC\u5360] ${activeUser.name} \u5DF2\u79BB\u7EBF\u8D85\u65F6\uFF0C\u91CA\u653E\u767B\u5F55\u72B6\u6001\uFF08\u4F1A\u8BDD\u4FDD\u7559\uFF09`);for(const t of activeUser.tokens)userSessions.delete(t);activeUser=null}}),EXCLUSIVE_RELEASE_DELAY))}let _broadcastTimer=null;function broadcastSessions(){_broadcastTimer||(_broadcastTimer=setTimeout((()=>{_broadcastTimer=null;for(const[,r]of io.sockets.sockets)r.emit("sessions",manager.list(r.data.userName,r.data.role==="admin"))}),100))}io.on("connection",(r=>{const t=r.handshake.address?.replace("::ffff:","")||"?",u=r.handshake.headers?.referer||"?";console.log(`[\u8FDE\u63A5] ${r.data.userName}(${r.data.role}) \u4ECE ${t} \u63A5\u5165 id=${r.id} \u9875\u9762=${u}`),_exclusiveReleaseTimer&&activeUser&&r.data.userName===activeUser.name&&(clearTimeout(_exclusiveReleaseTimer),_exclusiveReleaseTimer=null);let d=null,p=null,h=null,x=null,j=null;function b(){d&&(d.isController(r.id)&&(d.releaseControl(),io.emit("control-changed",{sessionId:d.id,holder:null,holderName:null})),d.removeViewer(r.id),p&&d.off("data",p),h&&d.off("agent:message",h),x&&d.off("agent:busy",x),j&&d.off("agent:error",j),p=null,h=null,x=null,j=null)}r.on("join",(w=>{const $=manager.get(w);if(!$){r.emit("error",{message:`\u4F1A\u8BDD ${w} \u672A\u627E\u5230`});return}if(r.data.role!=="admin"&&$.owner&&$.owner!==r.data.userName){r.emit("error",{message:"\u6CA1\u6709\u52A0\u5165\u8BE5\u4F1A\u8BDD\u7684\u6743\u9650"});return}b(),d=$,d.addViewer(r.id,r.data.userName),r.join(w),h=O=>r.emit("agent:message",O),d.on("agent:message",h),x=O=>r.emit("agent:busy",O),d.on("agent:busy",x),j=O=>r.emit("agent:error",O),d.on("agent:error",j),console.log(`[\u52A0\u5165] ${r.data.userName} \u52A0\u5165\u4F1A\u8BDD "${$.title}" (${w})`),r.emit("joined",{...$.toJSON(),role:r.data.role}),$._history?.length&&r.emit("agent:history",$._history),broadcastSessions()})),r.on("disconnect",(w=>{console.log(`[\u65AD\u5F00] ${r.data.userName} \u79BB\u5F00\u4F1A\u8BDD "${d?.title||"?"}" id=${r.id} \u539F\u56E0=${w}`),b(),broadcastSessions(),checkExclusiveRelease(),manager.persist()})),r.on("agent:query",(async({prompt:w}={})=>{if(!d||d.mode!=="agent"){r.emit("agent:error",{message:"\u5F53\u524D\u4E0D\u662F Agent \u6A21\u5F0F\u4F1A\u8BDD"});return}if(!d.isController(r.id)){r.emit("control-denied",{reason:"\u4F60\u6CA1\u6709\u5F53\u524D\u4F1A\u8BDD\u7684\u63A7\u5236\u6743"});return}if(d.isBusy){r.emit("agent:error",{message:"\u6B63\u5728\u5904\u7406\u4E2D\uFF0C\u8BF7\u7B49\u5F85\u5B8C\u6210"});return}try{await d.query(w)}catch($){console.error("[agent:query] \u9519\u8BEF:",$.message);try{r.connected&&r.emit("agent:error",{message:$.message})}catch{}}})),r.on("agent:interrupt",(()=>{if(!(!d||d.mode!=="agent")){if(!d.isController(r.id)){r.emit("control-denied",{reason:"\u4F60\u6CA1\u6709\u5F53\u524D\u4F1A\u8BDD\u7684\u63A7\u5236\u6743"});return}d.interrupt()}})),r.on("agent:permission",(({requestId:w,allow:$,toolName:O,approveAll:I}={})=>{if(!(!d||d.mode!=="agent")){if(!d.isController(r.id)){r.emit("control-denied",{reason:"\u4F60\u6CA1\u6709\u5F53\u524D\u4F1A\u8BDD\u7684\u63A7\u5236\u6743"});return}d.respondPermission(w,$,O,I)}})),r.on("set-mode",(({sessionId:w,mode:$}={})=>{const O=w?manager.get(w):d;if(O){if(r.data.role!=="admin"&&O.owner&&O.owner!==r.data.userName){r.emit("error",{message:"\u6CA1\u6709\u66F4\u6539\u6A21\u5F0F\u7684\u6743\u9650"});return}O.setPermissionMode&&(O.setPermissionMode($),console.log(`[\u6A21\u5F0F] ${r.data.userName} \u5207\u6362\u4F1A\u8BDD "${O.title}" \u4E3A ${$}`)),io.emit("mode-changed",{sessionId:O.id,mode:$}),manager.persist()}})),r.on("create-agent",((w,$)=>{if(!hasPermission(r.data.role,"operator")){typeof $=="function"&&$({ok:!1,error:"\u6CA1\u6709\u521B\u5EFA\u4F1A\u8BDD\u7684\u6743\u9650"});return}if(r.data.dir){const U=(0,external_path_.resolve)((0,external_path_.normalize)(r.data.dir)),z=w?.cwd?(0,external_path_.resolve)((0,external_path_.normalize)(w.cwd)):null;if(z&&z!==U&&!z.startsWith(U+external_path_.sep)){typeof $=="function"&&$({ok:!1,error:"\u4E0D\u80FD\u5728\u7ED1\u5B9A\u76EE\u5F55\u4E4B\u5916\u521B\u5EFA\u4F1A\u8BDD"});return}z||(w={...w,cwd:U})}const O=w?.cwd||r.data.dir||process.env.ZIHI_CWD||process.cwd(),I=(0,external_path_.join)(O,".zihi-sessions",`${Date.now()}-${randomUUID().slice(0,8)}`);try{(0,external_fs_.mkdirSync)(I,{recursive:!0})}catch(U){typeof $=="function"&&$({ok:!1,error:`\u521B\u5EFA\u9694\u79BB\u76EE\u5F55\u5931\u8D25: ${U.message}`});return}w={...w,cwd:I};try{const U=manager.createAgent({...w,owner:r.data.userName,userDir:r.data.dir});console.log(`[\u4F1A\u8BDD] ${r.data.userName} \u521B\u5EFA Agent \u4F1A\u8BDD "${U.title}" (${U.id})`),broadcastSessions(),typeof $=="function"&&$({ok:!0,session:U.toJSON()})}catch(U){typeof $=="function"&&$({ok:!1,error:U.message})}})),r.on("take-control",(({sessionId:w}={})=>{const $=w?manager.get(w):d;if($){if(!hasPermission(r.data.role,"operator")){r.emit("control-denied",{reason:"\u4F60\u7684\u89D2\u8272\u6CA1\u6709\u63A7\u5236\u6743\u9650"});return}if($.controlHolder&&$.controlHolder!==r.id){const O=$.controlHolderName===r.data.userName;if(r.data.role!=="admin"&&!O){r.emit("control-denied",{reason:"\u5176\u4ED6\u7528\u6237\u6B63\u5728\u63A7\u5236\u4E2D\uFF0C\u8BF7\u7B49\u5F85\u91CA\u653E"});return}}$.takeControl(r.id,r.data.userName),console.log(`[\u63A7\u5236] ${r.data.userName} \u83B7\u53D6\u4F1A\u8BDD "${$.title}" \u7684\u63A7\u5236\u6743`),io.emit("control-changed",{sessionId:$.id,holder:r.id,holderName:r.data.userName})}})),r.on("release-control",(({sessionId:w}={})=>{const $=w?manager.get(w):d;$&&$.isController(r.id)&&(console.log(`[\u63A7\u5236] ${r.data.userName} \u91CA\u653E\u4F1A\u8BDD "${$.title}" \u7684\u63A7\u5236\u6743`),$.releaseControl(),io.emit("control-changed",{sessionId:$.id,holder:null,holderName:null}))})),r.on("rename",(({sessionId:w,title:$}={})=>{const O=w?manager.get(w):d;if(!(!O||!$)){if(r.data.role!=="admin"&&O.owner&&O.owner!==r.data.userName){r.emit("error",{message:"\u6CA1\u6709\u91CD\u547D\u540D\u4F1A\u8BDD\u7684\u6743\u9650"});return}O.title=$,io.emit("session-renamed",{sessionId:O.id,title:$}),broadcastSessions(),manager.persist()}})),r.on("resize",(({cols:w,rows:$})=>d?.resize(w,$))),r.on("list",(()=>r.emit("sessions",manager.list(r.data.userName,r.data.role==="admin")))),r.on("dirs",((w,$)=>{if(typeof $!="function")return;const O=r.data.dir?(0,external_path_.resolve)((0,external_path_.normalize)(r.data.dir)):null,I=process.platform==="win32"?"\\":"/";let U=(w||O||process.env.ZIHI_CWD||(0,external_os_.homedir)()).replace(/[/\\]+$/,"")||(0,external_os_.homedir)();process.platform==="win32"&&/^[A-Za-z]:$/.test(U)&&(U+="\\");const z=(0,external_path_.resolve)((0,external_path_.normalize)(U));O&&z!==O&&!z.startsWith(O+I)&&(U=O);try{const N=(0,external_fs_.readdirSync)(U,{withFileTypes:!0}).filter((H=>H.isDirectory()&&!H.name.startsWith("."))).map((H=>({name:H.name,path:U.replace(/[/\\]+$/,"")+I+H.name}))).sort(((H,V)=>H.name.localeCompare(V.name))),B=(0,external_path_.join)(U,".."),L=(0,external_path_.resolve)((0,external_path_.normalize)(B)),W=!O||L===O||L.startsWith(O+I);$({ok:!0,current:U,parent:W&&B!==U?B:null,dirs:N})}catch(N){$({ok:!1,error:N.message})}})),r.on("kill",(w=>{if(!hasPermission(r.data.role,"operator")){r.emit("error",{message:"\u6CA1\u6709\u5220\u9664\u4F1A\u8BDD\u7684\u6743\u9650"});return}const $=manager.get(w);if($&&r.data.role!=="admin"&&$.owner&&$.owner!==r.data.userName){r.emit("error",{message:"\u6CA1\u6709\u5220\u9664\u8BE5\u4F1A\u8BDD\u7684\u6743\u9650"});return}console.log(`[\u4F1A\u8BDD] ${r.data.userName} \u5220\u9664\u4F1A\u8BDD ${w}`),manager.kill(w),broadcastSessions()})),r.on("kick-user",(({socketId:w,sessionId:$}={},O)=>{if(!hasPermission(r.data.role,"admin")){typeof O=="function"&&O({ok:!1,error:"\u6CA1\u6709\u8E22\u51FA\u7528\u6237\u7684\u6743\u9650"});return}const I=io.sockets.sockets.get(w);if(!I){typeof O=="function"&&O({ok:!1,error:"\u76EE\u6807\u7528\u6237\u4E0D\u5728\u7EBF"});return}const U=I.data.userName||"\u672A\u77E5";console.log(`[\u8E22\u51FA] ${r.data.userName} \u8E22\u51FA\u4E86\u7528\u6237 ${U} (${w})`),I.emit("kicked",{reason:`\u4F60\u5DF2\u88AB\u7BA1\u7406\u5458 ${r.data.userName} \u8E22\u51FA`}),I.disconnect(!0),typeof O=="function"&&O({ok:!0,name:U})})),r.on("list-viewers",(({sessionId:w}={},$)=>{if(typeof $!="function")return;const O=w?manager.get(w):d;if(!O){$({ok:!1,error:"\u4F1A\u8BDD\u4E0D\u5B58\u5728"});return}const I=[];for(const U of O._viewers){const z=io.sockets.sockets.get(U);z&&I.push({socketId:U,userName:z.data.userName||"\u672A\u77E5",role:z.data.role||"viewer",isController:O.controlHolder===U})}$({ok:!0,viewers:I})}))}));const CONTROL_TIMEOUT=300*1e3;setInterval((()=>{for(const r of manager.listSessions()){r.controlHolder&&(!io.sockets.sockets.get(r.controlHolder)||r.lastInputTime&&Date.now()-r.lastInputTime>CONTROL_TIMEOUT)&&(r.releaseControl(),io.emit("control-changed",{sessionId:r.id,holder:null,holderName:null}));for(const t of r._viewers)io.sockets.sockets.has(t)||r.removeViewer(t)}}),60*1e3);function showStartupInfo(){const r=httpServer.address().port;PORT=r;const t=getTailscaleIP(),u=`http://${t}:${r}/admin`;console.log(`
479
479
  \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501`),console.log(" zihi \u2014 \u57FA\u4E8E Tailscale \u7684 Web \u7EC8\u7AEF"),console.log("\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501"),console.log(`
480
480
  \u5730\u5740: http://${t}:${r}`),console.log(` \u5BC6\u7801: ${PASSWORD} (\u7F16\u8F91 ~/.zihi/password \u53EF\u4FEE\u6539)`),console.log(`
481
481
  \u626B\u63CF\u4E8C\u7EF4\u7801\u5728\u624B\u673A\u4E0A\u6253\u5F00:
package/dist/login.html CHANGED
@@ -8,7 +8,7 @@
8
8
  <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
9
9
  <link rel="apple-touch-icon" href="/icon.png">
10
10
  <link rel="manifest" href="/manifest.json">
11
- <title>weHi</title>
11
+ <title>ZiHi</title>
12
12
  <style>
13
13
  * { box-sizing: border-box; margin: 0; padding: 0; }
14
14
  html, body {
package/dist/package.json CHANGED
@@ -1 +1 @@
1
- {"type":"module","version":"1.0.0"}
1
+ {"type":"module","version":"1.1.0"}
package/dist/sw.js CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * weHi Service Worker
2
+ * ZiHi Service Worker
3
3
  * 离线缓存 + 推送通知
4
4
  */
5
5
 
@@ -72,7 +72,7 @@ self.addEventListener('fetch', (event) => {
72
72
  // ── Push 通知(从服务器推送时触发)──
73
73
  self.addEventListener('push', (event) => {
74
74
  const data = event.data ? event.data.json() : {};
75
- const title = data.title || 'weHi 权限请求';
75
+ const title = data.title || 'ZiHi 权限请求';
76
76
  const options = {
77
77
  body: data.body || '有操作需要你的审批',
78
78
  icon: data.icon || '/icon-192.png',
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wendongfly/zihi",
3
- "version": "1.0.0",
3
+ "version": "1.1.0",
4
4
  "description": "AI Agent terminal sharing with interactive permission approval via Claude Agent SDK",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",