@wendongfly/myhi 1.3.103 → 1.3.104
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/bin/myhi.js +25 -0
- package/dist/index.js +1 -1
- package/dist/index.min.js +1 -1
- package/package.json +1 -1
package/dist/index.min.js
CHANGED
|
@@ -378,7 +378,7 @@ Content-Length: `+C+`\r
|
|
|
378
378
|
`).filter(Boolean);let m=null,o=null,i=0;for(const a of l){const e=a.match(/"type":"image"/g);if(e&&(i+=e.length),a.includes("permissionMode"))try{const r=JSON.parse(a);r.type==="user"&&r.permissionMode&&(m=r.permissionMode)}catch{}}try{const a=JSON.parse(l[l.length-1]);a.timestamp&&(o=a.timestamp)}catch{}return{found:!0,persistedMode:m,poisoned:!!(m&&m!=="bypassPermissions"),messageCount:l.length,transcriptKB:Math.round(c.length/1024),imageCount:i,updatedAt:o}}}catch{}return _}let _claudeSessionsCache=null,_claudeSessionsCacheTime=0;const CLAUDE_SESSIONS_CACHE_TTL=3e4;function listLocalClaudeSessions(S){const _=Date.now();if(_claudeSessionsCache&&_-_claudeSessionsCacheTime<CLAUDE_SESSIONS_CACHE_TTL){if(!S)return _claudeSessionsCache;const c=(0,external_path_.resolve)((0,external_path_.normalize)(S)).replace(/[\\/]+$/,"");return _claudeSessionsCache.filter((l=>(0,external_path_.resolve)((0,external_path_.normalize)(l.projectPath)).replace(/[\\/]+$/,"").startsWith(c)))}const u=[],n=S?(0,external_path_.resolve)((0,external_path_.normalize)(S)).replace(/[\\/]+$/,""):null;try{const c=(0,external_path_.join)((0,external_os_.homedir)(),".claude","projects");if(!(0,external_fs_.existsSync)(c))return u;for(const l of(0,external_fs_.readdirSync)(c,{withFileTypes:!0})){if(!l.isDirectory())continue;const m=(0,external_path_.join)(c,l.name);try{for(const o of(0,external_fs_.readdirSync)(m)){if(!o.endsWith(".jsonl"))continue;const i=o.replace(".jsonl",""),a=(0,external_path_.join)(m,o);try{const e=(0,external_fs_.readFileSync)(a,"utf8").split(`
|
|
379
379
|
`).filter(Boolean);let r=null,p=null,f=0,s="";for(const h of e)try{const g=JSON.parse(h);if(r||(r=g),p=g,f++,!s&&g.type==="human"||g.type==="user"&&g.message?.content){const b=g.message.content;if(typeof b=="string")s=b.slice(0,120);else if(Array.isArray(b)){const d=b.find((w=>w.type==="text"));d&&(s=d.text?.slice(0,120)||"")}}}catch{}let v=l.name;if(process.platform==="win32"&&/^[A-Za-z]--/.test(v)?v=v[0]+":\\"+v.slice(3).replace(/-/g,"\\"):v.startsWith("-")&&(v=v.replace(/-/g,"/")),n&&!(0,external_path_.resolve)((0,external_path_.normalize)(v)).replace(/[\\/]+$/,"").startsWith(n))continue;u.push({sessionId:i,projectDir:l.name,projectPath:v,messageCount:f,summary:s,createdAt:r?.timestamp||null,updatedAt:p?.timestamp||null})}catch{}}}catch{}}}catch{}u.sort(((c,l)=>new Date(l.updatedAt||0).getTime()-new Date(c.updatedAt||0).getTime()));const t=u.slice(0,50);return _claudeSessionsCache=t,_claudeSessionsCacheTime=Date.now(),t.slice(0,20)}const DEFAULT_SHELL=process.platform==="win32"?process.env.SHELL||"powershell.exe":process.env.SHELL||"/bin/bash",CONFIG_DIR=(0,external_path_.join)((0,external_os_.homedir)(),".myhi"),SESSIONS_FILE=(0,external_path_.join)(CONFIG_DIR,"sessions.json"),savePath=null;function loadSavedConfigs(){try{return JSON.parse((0,external_fs_.readFileSync)(SESSIONS_FILE,"utf8"))}catch{return[]}}function writeSavedConfigs(S){try{(0,external_fs_.mkdirSync)(CONFIG_DIR,{recursive:!0});const _=SESSIONS_FILE+".tmp";(0,external_fs_.writeFileSync)(_,JSON.stringify(S,null,2),{mode:384}),(0,external_fs_.renameSync)(_,SESSIONS_FILE)}catch(_){console.error("[sessions] \u6301\u4E45\u5316\u5199\u5165\u5931\u8D25:",_.message)}}class Session extends external_events_.EventEmitter{constructor(_,u={}){super(),this.id=_,this.createdAt=u.createdAt||new Date().toISOString(),this.title=u.title||DEFAULT_SHELL,this.cwd=u.cwd||process.env.MYHI_CWD||process.cwd(),this.tags=Array.isArray(u.tags)?u.tags:[],this.initCmd=u.initCmd||null,this.owner=u.owner||null,this.cols=u.cols||120,this.rows=u.rows||30,this._lastActivityAt=u.lastActivityAt||0,this._viewers=new Set,this._viewerNames=new Map,this.controlHolder=null,this.controlHolderName=null,this.lastInputTime=null;const n={...process.env};if(delete n.CLAUDECODE,delete n.CLAUDE_CODE_ENTRYPOINT,delete n.CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC,u.userDir){const c=(0,external_path_.join)(u.userDir,".gitconfig");(0,external_fs_.existsSync)(c)&&(n.GIT_CONFIG_GLOBAL=c)}this._pty=external_node_pty_namespaceObject.spawn(DEFAULT_SHELL,[],{name:"xterm-256color",cols:this.cols,rows:this.rows,cwd:this.cwd,env:n,useConpty:!1}),this._scrollback="";const t=100*1024;if(this._pty.onData((c=>{this.emit("data",c),this._scrollback+=c,this._scrollback.length>t&&(this._scrollback=this._scrollback.slice(this._scrollback.length-t))})),this._pty.onExit((({exitCode:c})=>{this.exitCode=c,this.emit("exit",c)})),u.initCmd){const c=u.initCmd;let l=!1;const m=o=>{!l&&/[$>#\]]\s*$/.test(o.trimEnd())&&(l=!0,this._pty.off("data",m),setTimeout((()=>this._pty.write(c+"\r")),120))};this._pty.onData(m),setTimeout((()=>{l||(l=!0,this._pty.write(c+"\r"))}),3e3)}}write(_){_!=null&&(this._lastActivityAt=Date.now(),this._pty.write(_))}resize(_,u){this.cols=_,this.rows=u,this._pty.resize(_,u)}kill(){try{this._pty.kill()}catch{}}addViewer(_,u){this._viewers.add(_),u&&this._viewerNames.set(_,u)}removeViewer(_){this._viewers.delete(_),this._viewerNames.delete(_)}get viewerCount(){return new Set(this._viewerNames.values()).size||this._viewers.size}takeControl(_,u){this.controlHolder=_,this.controlHolderName=u||null,this.lastInputTime=Date.now()}releaseControl(){this.controlHolder=null,this.controlHolderName=null,this.lastInputTime=null}isController(_){return this.controlHolder===_}toJSON(){return{id:this.id,title:this.title,cwd:this.cwd,tags:this.tags,createdAt:this.createdAt,lastActivityAt:this._lastActivityAt||null,cols:this.cols,rows:this.rows,viewers:this.viewerCount,alive:this.exitCode===void 0,controlHolder:this.controlHolder,controlHolderName:this.controlHolderName,owner:this.owner}}}class SessionManager{constructor(){this._sessions=new Map,this._agentSessions=new Map;for(const _ of loadSavedConfigs())try{if(_.mode==="agent"){if(_.claudeSessionId){const u=(0,external_crypto_.randomUUID)(),n=new AgentSession(u,{..._,resumeSessionId:_.claudeSessionId});n.on("session-id",(()=>this._persist())),this._agentSessions.set(u,n),console.log(`[\u4F1A\u8BDD] \u6062\u590D Agent "${_.title}" (claude: ${_.claudeSessionId.slice(0,8)}...)`)}}else this._spawn((0,external_crypto_.randomUUID)(),_,!1)}catch(u){console.warn(`[\u4F1A\u8BDD] \u6062\u590D "${_.title}" \u5931\u8D25:`,u.message)}}_spawn(_,u,n=!0){const t=new Session(_,u);return this._sessions.set(_,t),t.on("exit",(()=>{setTimeout((()=>this._sessions.delete(_)),300*1e3)})),n&&this._persist(),t}create(_={}){return this._spawn((0,external_crypto_.randomUUID)(),_,!0)}createAgent(_={}){const u=(0,external_crypto_.randomUUID)(),n=new AgentSession(u,_);return this._agentSessions.set(u,n),n.on("session-id",(()=>this._persist())),this._persist(),n}get(_){return this._sessions.get(_)||this._agentSessions.get(_)}list(_,u=!1){let n=[...this._sessions.values()].map((c=>({...c.toJSON(),mode:"pty"}))),t=[...this._agentSessions.values()].map((c=>c.toJSON()));return _&&!u&&(n=n.filter((c=>!c.owner||c.owner===_)),t=t.filter((c=>!c.owner||c.owner===_))),[...n,...t]}listSessions(){return[...this._sessions.values(),...this._agentSessions.values()]}kill(_){const u=this._sessions.get(_);if(u){u.kill(),this._sessions.delete(_),this._persist();return}const n=this._agentSessions.get(_);n&&(n.kill(),this._agentSessions.delete(_),this._persist())}persist(){this._persist()}_persist(){const _=[...this._sessions.values()].filter((n=>n.exitCode===void 0)).map((n=>({mode:"pty",title:n.title,cwd:n.cwd,tags:n.tags?.length?n.tags:void 0,createdAt:n.createdAt||void 0,lastActivityAt:n._lastActivityAt||void 0,initCmd:n.initCmd||void 0,owner:n.owner||void 0}))),u=[...this._agentSessions.values()].filter((n=>n.alive)).map((n=>({mode:"agent",title:n.title,cwd:n.cwd,tags:n.tags?.length?n.tags:void 0,createdAt:n.createdAt||void 0,lastActivityAt:n._lastActivityAt||void 0,owner:n.owner||void 0,userDir:n.userDir||void 0,claudeSessionId:n.claudeSessionId||void 0})));writeSavedConfigs([..._,...u])}}const roles_CONFIG_DIR=(0,external_path_.join)((0,external_os_.homedir)(),".myhi"),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,usersConfig=null;function loadRoles(){try{if((0,external_fs_.existsSync)(ROLES_FILE))return rolesConfig=JSON.parse((0,external_fs_.readFileSync)(ROLES_FILE,"utf8")),rolesConfig}catch(S){console.warn("[\u89D2\u8272] \u52A0\u8F7D roles.json \u5931\u8D25:",S.message)}return rolesConfig=null,null}function lookupPassword(S){if(!rolesConfig?.passwords)return null;const _=rolesConfig.passwords[S];return _?{name:_.name||"\u7528\u6237",role:_.role||"viewer"}:null}function hasPermission(S,_){return(ROLE_LEVELS[S]||0)>=(ROLE_LEVELS[_]||0)}function isMultiUserMode(){return rolesConfig!==null&&rolesConfig.passwords&&Object.keys(rolesConfig.passwords).length>0}function getDefaultRole(){return rolesConfig?.defaultRole||"admin"}function loadUsers(){try{if((0,external_fs_.existsSync)(USERS_FILE))return usersConfig=JSON.parse((0,external_fs_.readFileSync)(USERS_FILE,"utf8")),usersConfig}catch(S){console.warn("[\u7528\u6237] \u52A0\u8F7D users.json \u5931\u8D25:",S.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(S){usersConfig||(usersConfig={users:{}}),usersConfig.exclusive=!!S,_writeUsers()}function lookupUser(S){if(!usersConfig?.users)return null;const _=usersConfig.users[S];return _?{name:_.name||"\u7528\u6237",dir:_.dir}:null}function listUsers(){return usersConfig?.users?Object.entries(usersConfig.users).map((([S,_])=>({password:S.slice(0,2)+"*".repeat(S.length-2),name:_.name,dir:_.dir}))):[]}function addUser(S,_,u){usersConfig||(usersConfig={users:{}}),usersConfig.users||(usersConfig.users={}),usersConfig.users[S]={name:_,dir:u},_writeUsers()}function removeUser(S){return!usersConfig?.users||!usersConfig.users[S]?!1:(delete usersConfig.users[S],_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 execAsync=(0,external_util_.promisify)(external_child_process_namespaceObject.exec),server_dirname=(0,external_path_.dirname)((0,external_url_.fileURLToPath)(import.meta.url));let PORT=parseInt(process.env.PORT,10)||12300;const HOST=process.env.HOST||"0.0.0.0",PORT_EXPLICIT=!!process.env.PORT,server_configDir=(0,external_path_.join)((0,external_os_.homedir)(),".myhi");(0,external_fs_.mkdirSync)(server_configDir,{recursive:!0});let httpsServer=null,httpServer=null;function getOrCreateCert(){const S=(0,external_path_.join)(server_configDir,"cert.pem"),_=(0,external_path_.join)(server_configDir,"key.pem");if((0,external_fs_.existsSync)(S)&&(0,external_fs_.existsSync)(_))try{return{cert:(0,external_fs_.readFileSync)(S),key:(0,external_fs_.readFileSync)(_)}}catch{}try{const u=selfsigned.generate([{name:"commonName",value:"myhi"}],{days:3650,keySize:2048});return(0,external_fs_.writeFileSync)(S,u.cert,"utf8"),(0,external_fs_.writeFileSync)(_,u.private,"utf8"),console.log("[myhi] \u81EA\u7B7E\u540D HTTPS \u8BC1\u4E66\u5DF2\u751F\u6210"),{cert:u.cert,key:u.private}}catch{}try{return(0,external_child_process_namespaceObject.execSync)(`openssl req -x509 -newkey rsa:2048 -keyout "${_}" -out "${S}" -days 3650 -nodes -subj "/CN=myhi"`,{stdio:"pipe",timeout:1e4}),{cert:(0,external_fs_.readFileSync)(S),key:(0,external_fs_.readFileSync)(_)}}catch(u){return console.warn(`[myhi] \u751F\u6210 HTTPS \u8BC1\u4E66\u5931\u8D25: ${u.message?.split(`
|
|
380
380
|
`)[0]||u}`),null}}const pidFile=(0,external_path_.join)(server_configDir,"server.pid"),daemonPidFile=(0,external_path_.join)(server_configDir,"daemon.pid"),IS_DAEMON_CHILD=!!process.env.MYHI_DAEMON;function killOldProcess(S,_){let u=!1;try{process.kill(S,0),u=!0}catch{}if(!u)return!0;console.log(`[myhi] \u68C0\u6D4B\u5230\u5DF2\u8FD0\u884C\u7684${_} (PID ${S})\uFF0C\u6B63\u5728\u505C\u6B62...`);try{process.platform==="win32"?(0,external_child_process_namespaceObject.execSync)(`taskkill /PID ${S} /F /T`,{stdio:"pipe",timeout:5e3}):process.kill(S,"SIGTERM")}catch{}const n=Date.now()+5e3;for(;Date.now()<n;){try{process.kill(S,0)}catch{return!0}const c=Date.now()+200;for(;Date.now()<c;);}let t=!1;try{process.kill(S,0),t=!0}catch{}return!t}(function S(){try{const _=parseInt((0,external_fs_.readFileSync)(daemonPidFile,"utf8").trim(),10);if(_&&_!==process.pid&&_!==parseInt(process.env.MYHI_DAEMON_PID||"0",10)){let u=!1;try{process.kill(_,0),u=!0}catch{}if(u&&!IS_DAEMON_CHILD){console.log("[myhi] \u68C0\u6D4B\u5230\u540E\u53F0 daemon \u5728\u8FD0\u884C\uFF0C\u5148\u505C\u6B62..."),killOldProcess(_,"daemon")||(console.error("[myhi] \u65E0\u6CD5\u505C\u6B62 daemon\uFF0C\u8BF7\u5148\u8FD0\u884C: myhi stop"),process.exit(1));try{(0,external_fs_.unlinkSync)(daemonPidFile)}catch{}}}}catch{}if(!IS_DAEMON_CHILD)try{const _=parseInt((0,external_fs_.readFileSync)(pidFile,"utf8").trim(),10);_&&_!==process.pid&&(killOldProcess(_,"\u5B9E\u4F8B")||(console.error(`[myhi] \u65E0\u6CD5\u505C\u6B62\u65E7\u8FDB\u7A0B (PID ${_})\uFF0C\u8BF7\u624B\u52A8\u6267\u884C\uFF1A`),console.error(" myhi stop"),console.error(` \u6216: ${process.platform==="win32"?`taskkill /PID ${_} /F`:`kill -9 ${_}`}`),process.exit(1)))}catch{}(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 S of manager.listSessions())try{S.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",(S=>{console.error("[myhi] \u672A\u6355\u83B7\u5F02\u5E38:",S.message),gracefulShutdown(),process.exit(1)})),process.on("unhandledRejection",(S=>{console.error("[myhi] \u672A\u5904\u7406\u7684 Promise \u62D2\u7EDD:",S)}));function readOrCreate(S,_){try{if((0,external_fs_.existsSync)(S))return(0,external_fs_.readFileSync)(S,"utf8").trim()}catch{}const u=_();return(0,external_fs_.writeFileSync)(S,u,{mode:384}),u}const TOKEN=readOrCreate((0,external_path_.join)(server_configDir,"token"),(()=>(0,external_crypto_.randomBytes)(16).toString("hex")));let PASSWORD=readOrCreate((0,external_path_.join)(server_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 S=Date.now();for(const[_,u]of userSessions)u.permanent||(!u.lastUsed||S-u.lastUsed>SESSION_MAX_AGE)&&userSessions.delete(_)}),3600*1e3);function getTailscaleIP(){try{return(0,external_child_process_namespaceObject.execSync)("tailscale ip -4",{timeout:3e3,stdio:"pipe"}).toString().trim().split(`
|
|
381
|
-
`)[0]}catch{}try{if(process.platform==="win32"){const S=(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(S)return S[1]}else try{const S=(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(S)return S[1]}catch{const S=(0,external_child_process_namespaceObject.execSync)("route -n get default 2>/dev/null || route -n 2>/dev/null",{timeout:3e3,stdio:"pipe"}).toString(),_=S.match(/interface:\s*(\S+)/i)||S.match(/0\.0\.0\.0\s+(\d+\.\d+\.\d+\.\d+)/);if(_){const u=(0,external_os_.networkInterfaces)()[_[1]];if(u){const n=u.find((t=>t.family==="IPv4"&&!t.internal));if(n)return n.address}if(/^\d+\.\d+\.\d+\.\d+$/.test(_[1]))return _[1]}}}catch{}for(const S of Object.values((0,external_os_.networkInterfaces)()))for(const _ of S)if(_.family==="IPv4"&&!_.internal)return _.address;return"localhost"}function parseCookies(S=""){const _={};for(const u of S.split(";")){const n=u.indexOf("=");n>0&&(_[u.slice(0,n).trim()]=u.slice(n+1).trim())}return _}const SESSION_COOKIE="myhi_sid",COOKIE_OPTS_BASE="HttpOnly; SameSite=Strict; Path=/; Max-Age=31536000";function cookieOpts(S){return S?.secure||S?.headers?.["x-forwarded-proto"]==="https"?COOKIE_OPTS_BASE+"; Secure":COOKIE_OPTS_BASE}function setSessionCookie(S,_,u){S.setHeader("Set-Cookie",`${SESSION_COOKIE}=${_||TOKEN}; ${cookieOpts(u)}`)}function getSessionToken(S){return parseCookies(S)[SESSION_COOKIE]||null}function hasValidSession(S){const _=getSessionToken(S);if(_&&userSessions.has(_)){const u=userSessions.get(_);return u&&(u.lastUsed=Date.now()),!0}return!1}function getUserInfo(S){const _=getSessionToken(S);return _?userSessions.get(_):null}const app=express();app.set("trust proxy",!0),app.use(((S,_,u)=>{_.setHeader("Referrer-Policy","no-referrer"),_.setHeader("X-Content-Type-Options","nosniff"),u()}));const _tlsOpts=process.env.MYHI_NO_HTTPS?null:getOrCreateCert();_tlsOpts?(httpsServer=(0,external_https_.createServer)(_tlsOpts,app),httpServer=(0,external_http_.createServer)(((S,_)=>{const u=(S.headers.host||"").replace(/:\d+$/,"");_.writeHead(301,{Location:`https://${u}:${PORT}${S.url}`}),_.end()}))):(console.warn("[myhi] TLS \u4E0D\u53EF\u7528\uFF0C\u4EE5 HTTP \u6A21\u5F0F\u8FD0\u884C\uFF08\u9EA6\u514B\u98CE/\u6444\u50CF\u5934\u7B49\u6D4F\u89C8\u5668\u5B89\u5168\u529F\u80FD\u53D7\u9650\uFF09"),httpServer=(0,external_http_.createServer)(app));const _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({serveClient:!1,cors:{origin:(S,_)=>{if(!S||_corsAllowed.test(S))return _(null,!0);_(new Error("CORS \u4E0D\u5141\u8BB8\u6B64\u6765\u6E90"),!1)},credentials:!0},transports:["websocket","polling"],pingTimeout:6e4,pingInterval:25e3,upgradeTimeout:3e4,maxHttpBufferSize:5e6});httpsServer?io.attach(httpsServer):io.attach(httpServer);const manager=new SessionManager,AUTO_ATTACH=process.env.MYHI_AUTO_ATTACH!=="0",_autoSpawned=new Set;function spawnLocalTerminal(S,_){if(!AUTO_ATTACH||_autoSpawned.has(S)||!process.env.DISPLAY&&process.platform==="linux")return;_autoSpawned.add(S);const u=__nccwpck_require__.ab+"attach.js",n=process.execPath,t=_||"myhi";if(process.platform==="win32"){const c=`"${n}" "${u}" ${S}`,l=(0,external_child_process_namespaceObject.spawn)("wt.exe",["-w","0","new-tab","--title",t,"--","cmd","/k",c],{detached:!0,stdio:"ignore"});l.unref(),l.on("error",(m=>{console.warn("[attach] wt.exe \u5931\u8D25\uFF0C\u56DE\u9000\u5230 cmd:",m.message),(0,external_child_process_namespaceObject.spawn)("cmd.exe",["/c","start",`"${t}"`,"cmd","/k",c],{detached:!0,stdio:"ignore"}).unref()}))}else if(process.platform==="darwin"){const c=`tell application "Terminal" to do script "${n} ${u} ${S}"`;(0,external_child_process_namespaceObject.spawn)("osascript",["-e",c],{detached:!0,stdio:"ignore"}).unref()}else{const c=`${n} "${u}" ${S}`;for(const[l,m]of[["gnome-terminal",["--","bash","-c",`${c}; exec bash`]],["xterm",["-title",t,"-e",c]],["konsole",["--new-tab","-e",c]]]){const o=(0,external_child_process_namespaceObject.spawn)(l,m,{detached:!0,stdio:"ignore"});o.unref(),o.on("error",(()=>{}));break}}}const uploadDir=(0,external_path_.join)(server_configDir,"uploads");(0,external_fs_.mkdirSync)(uploadDir,{recursive:!0});function checkAuth(S,_,u){const n=S.query.token;if(n&&(n===TOKEN||userSessions.has(n))){const t=userSessions.get(n);if(t?.onetime){userSessions.delete(n);const m=(0,external_crypto_.randomBytes)(16).toString("hex");userSessions.set(m,{role:t.role,name:t.name,lastUsed:Date.now()}),setSessionCookie(_,m,S)}else setSessionCookie(_,n===TOKEN?TOKEN:n,S);const c=Object.keys(S.query).filter((m=>m!=="token")),l=S.path+(c.length?"?"+new URLSearchParams(Object.fromEntries(Object.entries(S.query).filter((([m])=>m!=="token")))):"");return _.redirect(l)}if(hasValidSession(S.headers.cookie)){if(isExclusiveMode()&&activeUser){const t=getSessionToken(S.headers.cookie);if(t!==TOKEN){const c=userSessions.get(t);if(!c||c.name!==activeUser.name)return _.setHeader("Set-Cookie",`${SESSION_COOKIE}=; HttpOnly; SameSite=Strict; Path=/; Max-Age=0`),_.redirect("/login")}}return u()}_.redirect("/login")}const _require=(0,external_module_namespaceObject.createRequire)(import.meta.url);function pkgDirSafe(S){try{return(0,external_path_.dirname)(_require.resolve(`${S}/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)),app.use("/sio-client",express.static((0,external_path_.join)(server_dirname,"client-dist"),{maxAge:"1h",index:!1,setHeaders:(S,_)=>{_.endsWith(".js")&&S.setHeader("Content-Type","application/javascript; charset=utf-8")}})),app.get("/manifest.json",((S,_)=>_.sendFile((0,external_path_.join)(server_dirname,"manifest.json")))),app.get("/icon.png",((S,_)=>_.sendFile((0,external_path_.join)(server_dirname,"icon.png")))),app.get("/icon.svg",((S,_)=>_.sendFile((0,external_path_.join)(server_dirname,"icon.svg"))));const _loginAttempts=new Map,LOGIN_MAX_ATTEMPTS=5,LOGIN_LOCKOUT_MS=300*1e3;function checkLoginRate(S){const _=Date.now(),u=_loginAttempts.get(S);return!u||_>u.resetAt?!0:u.count<LOGIN_MAX_ATTEMPTS}function recordLoginFailure(S){const _=Date.now(),u=_loginAttempts.get(S);!u||_>u.resetAt?_loginAttempts.set(S,{count:1,resetAt:_+LOGIN_LOCKOUT_MS}):u.count++}function clearLoginFailures(S){_loginAttempts.delete(S)}setInterval((()=>{const S=Date.now();for(const[_,u]of _loginAttempts)S>u.resetAt&&_loginAttempts.delete(_)}),600*1e3),app.get("/login",((S,_)=>{_.sendFile((0,external_path_.join)(server_dirname,"login.html"))})),app.post("/login",express.urlencoded({extended:!1}),((S,_)=>{const u=S.ip;if(!checkLoginRate(u))return _.redirect("/login?error=locked");loadRoles(),loadUsers();const n=S.body?.password,t=S.query.from,c=t&&t.startsWith("/")&&!t.startsWith("//")?t:"/";if(hasUsers()){const m=lookupUser(n);if(!m)return recordLoginFailure(u),_.redirect("/login?error=1");if(isExclusiveMode()&&activeUser&&activeUser.name!==m.name)return _.redirect("/login?error=occupied&user="+encodeURIComponent(activeUser.name));clearLoginFailures(u);const o=(0,external_crypto_.randomBytes)(16).toString("hex");return userSessions.set(o,{role:"operator",name:m.name,dir:m.dir,lastUsed:Date.now()}),isExclusiveMode()&&(activeUser?activeUser.tokens.add(o):activeUser={name:m.name,dir:m.dir,tokens:new Set([o]),loginAt:Date.now()}),setSessionCookie(_,o,S),console.log(`[\u767B\u5F55] ${m.name} \u767B\u5F55\uFF08${isExclusiveMode()?"\u72EC\u5360":"\u5171\u4EAB"}\u6A21\u5F0F\uFF09`),_.redirect(c)}const l=lookupPassword(n);if(l){clearLoginFailures(u);const m=(0,external_crypto_.randomBytes)(16).toString("hex");return userSessions.set(m,{role:l.role,name:l.name,lastUsed:Date.now()}),setSessionCookie(_,m,S),_.redirect(c)}if(n===PASSWORD){clearLoginFailures(u);const m=(0,external_crypto_.randomBytes)(16).toString("hex");return userSessions.set(m,{role:"admin",name:"\u7BA1\u7406\u5458",lastUsed:Date.now()}),setSessionCookie(_,m,S),_.redirect(c)}recordLoginFailure(u),_.redirect("/login?error=1")})),app.post("/logout",((S,_)=>{const u=getSessionToken(S.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)),_.setHeader("Set-Cookie",`${SESSION_COOKIE}=; HttpOnly; SameSite=Strict; Path=/; Max-Age=0`),_.redirect("/login")})),app.get("/api/status",((S,_)=>{if(isExclusiveMode()&&activeUser)return _.json({occupied:!0,userName:activeUser.name,releasing:!!_exclusiveReleaseTimer});if(hasUsers()&&!isExclusiveMode()){const u=new Set;for(const[,n]of io.sockets.sockets){if(!n.data.userName||n.data.userName==="\u7BA1\u7406\u5458")continue;const t=n.handshake.headers.cookie;t&&!hasValidSession(t)||u.add(n.data.userName)}return _.json({occupied:!1,onlineUsers:[...u]})}_.json({occupied:!1})})),app.get("/admin",((S,_)=>_.sendFile((0,external_path_.join)(server_dirname,"admin.html")))),app.get("/",checkAuth,((S,_)=>_.sendFile((0,external_path_.join)(server_dirname,"index.html")))),app.get("/terminal/:id",checkAuth,((S,_)=>_.sendFile((0,external_path_.join)(server_dirname,"chat.html")))),app.get("/terminal-raw/:id",checkAuth,((S,_)=>_.sendFile((0,external_path_.join)(server_dirname,"terminal.html")))),app.use("/lib",express.static((0,external_path_.join)(server_dirname,"lib"),staticOpts)),app.get("/api/sessions",checkAuth,((S,_)=>{const u=getUserInfo(S.headers.cookie);_.json(manager.list(u?.name,u?.role==="admin"))})),app.get("/api/usage",((S,_)=>{try{const u=manager.listSessions().filter((t=>t.mode==="agent"&&t.alive)).map((t=>({id:t.id,title:t.title,owner:t.owner,usage:t._usage})));let n=null;for(const t of u)if(t.usage?.rateLimitInfo){n=t.usage.rateLimitInfo;break}_.json({rateLimit:n,activeSessions:u})}catch(u){_.status(500).json({error:u.message})}})),app.post("/api/sessions",checkAuth,express.json(),((S,_)=>{const u=getUserInfo(S.headers.cookie),n=manager.create({...S.body,owner:u?.name,userDir:u?.dir});_.status(201).json(n.toJSON())})),app.delete("/api/sessions/:id",checkAuth,((S,_)=>{manager.kill(S.params.id),_.status(204).end()})),app.get("/api/sessions/health",checkAuth,((S,_)=>{const u=getUserInfo(S.headers.cookie),n=manager.listSessions().filter((t=>t.mode==="agent")).filter((t=>!t.owner||!u?.name||t.owner===u.name)).map((t=>({...t.toJSON(),health:getSessionHealth(t.claudeSessionId)})));_.json({ok:!0,sessions:n})})),app.post("/api/sessions/:id/reset",checkAuth,((S,_)=>{const u=manager.get(S.params.id);if(!u||u.mode!=="agent"||typeof u.reset!="function")return _.status(404).json({ok:!1,error:"agent \u4F1A\u8BDD\u4E0D\u5B58\u5728"});u.reset(),u.emit("agent:message",{type:"system",subtype:"info",message:"\u5DF2\u91CD\u5F00\u4E3A\u5E72\u51C0\u4F1A\u8BDD\uFF0C\u4E0B\u6B21\u63D0\u95EE\u5F00\u542F\u5168\u65B0\u5BF9\u8BDD\uFF08\u65E7\u4E0A\u4E0B\u6587\u5DF2\u65AD\u5F00\uFF09"}),broadcastSessions(),_.json({ok:!0})})),app.get("/api/claude-sessions",checkAuth,((S,_)=>{const u=getUserInfo(S.headers.cookie);_.json(listLocalClaudeSessions(u?.dir))})),app.get("/api/agent/history/:sessionId",checkAuth,((S,_)=>{const u=manager.get(S.params.sessionId);if(!u||u.mode!=="agent")return _.status(404).json({ok:!1,error:"\u4F1A\u8BDD\u4E0D\u5B58\u5728"});const n=u.claudeSessionId;if(!n)return _.json({ok:!0,messages:[],total:0,hasMore:!1});const t=(0,external_path_.join)((0,external_os_.homedir)(),".claude","projects");let c=null;try{if((0,external_fs_.existsSync)(t))for(const p of(0,external_fs_.readdirSync)(t,{withFileTypes:!0})){if(!p.isDirectory())continue;const f=(0,external_path_.join)(t,p.name,n+".jsonl");if((0,external_fs_.existsSync)(f)){c=f;break}}}catch{}if(!c)return _.json({ok:!0,messages:[],total:0,hasMore:!1});let l;try{l=(0,external_fs_.readFileSync)(c,"utf8").split(`
|
|
381
|
+
`)[0]}catch{}try{if(process.platform==="win32"){const S=(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(S)return S[1]}else try{const S=(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(S)return S[1]}catch{const S=(0,external_child_process_namespaceObject.execSync)("route -n get default 2>/dev/null || route -n 2>/dev/null",{timeout:3e3,stdio:"pipe"}).toString(),_=S.match(/interface:\s*(\S+)/i)||S.match(/0\.0\.0\.0\s+(\d+\.\d+\.\d+\.\d+)/);if(_){const u=(0,external_os_.networkInterfaces)()[_[1]];if(u){const n=u.find((t=>t.family==="IPv4"&&!t.internal));if(n)return n.address}if(/^\d+\.\d+\.\d+\.\d+$/.test(_[1]))return _[1]}}}catch{}for(const S of Object.values((0,external_os_.networkInterfaces)()))for(const _ of S)if(_.family==="IPv4"&&!_.internal)return _.address;return"localhost"}function parseCookies(S=""){const _={};for(const u of S.split(";")){const n=u.indexOf("=");n>0&&(_[u.slice(0,n).trim()]=u.slice(n+1).trim())}return _}const SESSION_COOKIE="myhi_sid",COOKIE_OPTS_BASE="HttpOnly; SameSite=Strict; Path=/; Max-Age=31536000";function cookieOpts(S){return S?.secure||S?.headers?.["x-forwarded-proto"]==="https"?COOKIE_OPTS_BASE+"; Secure":COOKIE_OPTS_BASE}function setSessionCookie(S,_,u){S.setHeader("Set-Cookie",`${SESSION_COOKIE}=${_||TOKEN}; ${cookieOpts(u)}`)}function getSessionToken(S){return parseCookies(S)[SESSION_COOKIE]||null}function hasValidSession(S){const _=getSessionToken(S);if(_&&userSessions.has(_)){const u=userSessions.get(_);return u&&(u.lastUsed=Date.now()),!0}return!1}function getUserInfo(S){const _=getSessionToken(S);return _?userSessions.get(_):null}const app=express();app.set("trust proxy",!0),app.use(((S,_,u)=>{_.setHeader("Referrer-Policy","no-referrer"),_.setHeader("X-Content-Type-Options","nosniff"),u()}));function _httpOnlyFromConfig(){try{return!!JSON.parse((0,external_fs_.readFileSync)((0,external_path_.join)(server_configDir,"config.json"),"utf8")).httpOnly}catch{return!1}}const _tlsOpts=process.env.MYHI_NO_HTTPS||_httpOnlyFromConfig()?null:getOrCreateCert();_tlsOpts?(httpsServer=(0,external_https_.createServer)(_tlsOpts,app),httpServer=(0,external_http_.createServer)(((S,_)=>{const u=(S.headers.host||"").replace(/:\d+$/,"");_.writeHead(301,{Location:`https://${u}:${PORT}${S.url}`}),_.end()}))):(console.warn("[myhi] TLS \u4E0D\u53EF\u7528\uFF0C\u4EE5 HTTP \u6A21\u5F0F\u8FD0\u884C\uFF08\u9EA6\u514B\u98CE/\u6444\u50CF\u5934\u7B49\u6D4F\u89C8\u5668\u5B89\u5168\u529F\u80FD\u53D7\u9650\uFF09"),httpServer=(0,external_http_.createServer)(app));const _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({serveClient:!1,cors:{origin:(S,_)=>{if(!S||_corsAllowed.test(S))return _(null,!0);_(new Error("CORS \u4E0D\u5141\u8BB8\u6B64\u6765\u6E90"),!1)},credentials:!0},transports:["websocket","polling"],pingTimeout:6e4,pingInterval:25e3,upgradeTimeout:3e4,maxHttpBufferSize:5e6});httpsServer?io.attach(httpsServer):io.attach(httpServer);const manager=new SessionManager,AUTO_ATTACH=process.env.MYHI_AUTO_ATTACH!=="0",_autoSpawned=new Set;function spawnLocalTerminal(S,_){if(!AUTO_ATTACH||_autoSpawned.has(S)||!process.env.DISPLAY&&process.platform==="linux")return;_autoSpawned.add(S);const u=__nccwpck_require__.ab+"attach.js",n=process.execPath,t=_||"myhi";if(process.platform==="win32"){const c=`"${n}" "${u}" ${S}`,l=(0,external_child_process_namespaceObject.spawn)("wt.exe",["-w","0","new-tab","--title",t,"--","cmd","/k",c],{detached:!0,stdio:"ignore"});l.unref(),l.on("error",(m=>{console.warn("[attach] wt.exe \u5931\u8D25\uFF0C\u56DE\u9000\u5230 cmd:",m.message),(0,external_child_process_namespaceObject.spawn)("cmd.exe",["/c","start",`"${t}"`,"cmd","/k",c],{detached:!0,stdio:"ignore"}).unref()}))}else if(process.platform==="darwin"){const c=`tell application "Terminal" to do script "${n} ${u} ${S}"`;(0,external_child_process_namespaceObject.spawn)("osascript",["-e",c],{detached:!0,stdio:"ignore"}).unref()}else{const c=`${n} "${u}" ${S}`;for(const[l,m]of[["gnome-terminal",["--","bash","-c",`${c}; exec bash`]],["xterm",["-title",t,"-e",c]],["konsole",["--new-tab","-e",c]]]){const o=(0,external_child_process_namespaceObject.spawn)(l,m,{detached:!0,stdio:"ignore"});o.unref(),o.on("error",(()=>{}));break}}}const uploadDir=(0,external_path_.join)(server_configDir,"uploads");(0,external_fs_.mkdirSync)(uploadDir,{recursive:!0});function checkAuth(S,_,u){const n=S.query.token;if(n&&(n===TOKEN||userSessions.has(n))){const t=userSessions.get(n);if(t?.onetime){userSessions.delete(n);const m=(0,external_crypto_.randomBytes)(16).toString("hex");userSessions.set(m,{role:t.role,name:t.name,lastUsed:Date.now()}),setSessionCookie(_,m,S)}else setSessionCookie(_,n===TOKEN?TOKEN:n,S);const c=Object.keys(S.query).filter((m=>m!=="token")),l=S.path+(c.length?"?"+new URLSearchParams(Object.fromEntries(Object.entries(S.query).filter((([m])=>m!=="token")))):"");return _.redirect(l)}if(hasValidSession(S.headers.cookie)){if(isExclusiveMode()&&activeUser){const t=getSessionToken(S.headers.cookie);if(t!==TOKEN){const c=userSessions.get(t);if(!c||c.name!==activeUser.name)return _.setHeader("Set-Cookie",`${SESSION_COOKIE}=; HttpOnly; SameSite=Strict; Path=/; Max-Age=0`),_.redirect("/login")}}return u()}_.redirect("/login")}const _require=(0,external_module_namespaceObject.createRequire)(import.meta.url);function pkgDirSafe(S){try{return(0,external_path_.dirname)(_require.resolve(`${S}/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)),app.use("/sio-client",express.static((0,external_path_.join)(server_dirname,"client-dist"),{maxAge:"1h",index:!1,setHeaders:(S,_)=>{_.endsWith(".js")&&S.setHeader("Content-Type","application/javascript; charset=utf-8")}})),app.get("/manifest.json",((S,_)=>_.sendFile((0,external_path_.join)(server_dirname,"manifest.json")))),app.get("/icon.png",((S,_)=>_.sendFile((0,external_path_.join)(server_dirname,"icon.png")))),app.get("/icon.svg",((S,_)=>_.sendFile((0,external_path_.join)(server_dirname,"icon.svg"))));const _loginAttempts=new Map,LOGIN_MAX_ATTEMPTS=5,LOGIN_LOCKOUT_MS=300*1e3;function checkLoginRate(S){const _=Date.now(),u=_loginAttempts.get(S);return!u||_>u.resetAt?!0:u.count<LOGIN_MAX_ATTEMPTS}function recordLoginFailure(S){const _=Date.now(),u=_loginAttempts.get(S);!u||_>u.resetAt?_loginAttempts.set(S,{count:1,resetAt:_+LOGIN_LOCKOUT_MS}):u.count++}function clearLoginFailures(S){_loginAttempts.delete(S)}setInterval((()=>{const S=Date.now();for(const[_,u]of _loginAttempts)S>u.resetAt&&_loginAttempts.delete(_)}),600*1e3),app.get("/login",((S,_)=>{_.sendFile((0,external_path_.join)(server_dirname,"login.html"))})),app.post("/login",express.urlencoded({extended:!1}),((S,_)=>{const u=S.ip;if(!checkLoginRate(u))return _.redirect("/login?error=locked");loadRoles(),loadUsers();const n=S.body?.password,t=S.query.from,c=t&&t.startsWith("/")&&!t.startsWith("//")?t:"/";if(hasUsers()){const m=lookupUser(n);if(!m)return recordLoginFailure(u),_.redirect("/login?error=1");if(isExclusiveMode()&&activeUser&&activeUser.name!==m.name)return _.redirect("/login?error=occupied&user="+encodeURIComponent(activeUser.name));clearLoginFailures(u);const o=(0,external_crypto_.randomBytes)(16).toString("hex");return userSessions.set(o,{role:"operator",name:m.name,dir:m.dir,lastUsed:Date.now()}),isExclusiveMode()&&(activeUser?activeUser.tokens.add(o):activeUser={name:m.name,dir:m.dir,tokens:new Set([o]),loginAt:Date.now()}),setSessionCookie(_,o,S),console.log(`[\u767B\u5F55] ${m.name} \u767B\u5F55\uFF08${isExclusiveMode()?"\u72EC\u5360":"\u5171\u4EAB"}\u6A21\u5F0F\uFF09`),_.redirect(c)}const l=lookupPassword(n);if(l){clearLoginFailures(u);const m=(0,external_crypto_.randomBytes)(16).toString("hex");return userSessions.set(m,{role:l.role,name:l.name,lastUsed:Date.now()}),setSessionCookie(_,m,S),_.redirect(c)}if(n===PASSWORD){clearLoginFailures(u);const m=(0,external_crypto_.randomBytes)(16).toString("hex");return userSessions.set(m,{role:"admin",name:"\u7BA1\u7406\u5458",lastUsed:Date.now()}),setSessionCookie(_,m,S),_.redirect(c)}recordLoginFailure(u),_.redirect("/login?error=1")})),app.post("/logout",((S,_)=>{const u=getSessionToken(S.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)),_.setHeader("Set-Cookie",`${SESSION_COOKIE}=; HttpOnly; SameSite=Strict; Path=/; Max-Age=0`),_.redirect("/login")})),app.get("/api/status",((S,_)=>{if(isExclusiveMode()&&activeUser)return _.json({occupied:!0,userName:activeUser.name,releasing:!!_exclusiveReleaseTimer});if(hasUsers()&&!isExclusiveMode()){const u=new Set;for(const[,n]of io.sockets.sockets){if(!n.data.userName||n.data.userName==="\u7BA1\u7406\u5458")continue;const t=n.handshake.headers.cookie;t&&!hasValidSession(t)||u.add(n.data.userName)}return _.json({occupied:!1,onlineUsers:[...u]})}_.json({occupied:!1})})),app.get("/admin",((S,_)=>_.sendFile((0,external_path_.join)(server_dirname,"admin.html")))),app.get("/",checkAuth,((S,_)=>_.sendFile((0,external_path_.join)(server_dirname,"index.html")))),app.get("/terminal/:id",checkAuth,((S,_)=>_.sendFile((0,external_path_.join)(server_dirname,"chat.html")))),app.get("/terminal-raw/:id",checkAuth,((S,_)=>_.sendFile((0,external_path_.join)(server_dirname,"terminal.html")))),app.use("/lib",express.static((0,external_path_.join)(server_dirname,"lib"),staticOpts)),app.get("/api/sessions",checkAuth,((S,_)=>{const u=getUserInfo(S.headers.cookie);_.json(manager.list(u?.name,u?.role==="admin"))})),app.get("/api/usage",((S,_)=>{try{const u=manager.listSessions().filter((t=>t.mode==="agent"&&t.alive)).map((t=>({id:t.id,title:t.title,owner:t.owner,usage:t._usage})));let n=null;for(const t of u)if(t.usage?.rateLimitInfo){n=t.usage.rateLimitInfo;break}_.json({rateLimit:n,activeSessions:u})}catch(u){_.status(500).json({error:u.message})}})),app.post("/api/sessions",checkAuth,express.json(),((S,_)=>{const u=getUserInfo(S.headers.cookie),n=manager.create({...S.body,owner:u?.name,userDir:u?.dir});_.status(201).json(n.toJSON())})),app.delete("/api/sessions/:id",checkAuth,((S,_)=>{manager.kill(S.params.id),_.status(204).end()})),app.get("/api/sessions/health",checkAuth,((S,_)=>{const u=getUserInfo(S.headers.cookie),n=manager.listSessions().filter((t=>t.mode==="agent")).filter((t=>!t.owner||!u?.name||t.owner===u.name)).map((t=>({...t.toJSON(),health:getSessionHealth(t.claudeSessionId)})));_.json({ok:!0,sessions:n})})),app.post("/api/sessions/:id/reset",checkAuth,((S,_)=>{const u=manager.get(S.params.id);if(!u||u.mode!=="agent"||typeof u.reset!="function")return _.status(404).json({ok:!1,error:"agent \u4F1A\u8BDD\u4E0D\u5B58\u5728"});u.reset(),u.emit("agent:message",{type:"system",subtype:"info",message:"\u5DF2\u91CD\u5F00\u4E3A\u5E72\u51C0\u4F1A\u8BDD\uFF0C\u4E0B\u6B21\u63D0\u95EE\u5F00\u542F\u5168\u65B0\u5BF9\u8BDD\uFF08\u65E7\u4E0A\u4E0B\u6587\u5DF2\u65AD\u5F00\uFF09"}),broadcastSessions(),_.json({ok:!0})})),app.get("/api/claude-sessions",checkAuth,((S,_)=>{const u=getUserInfo(S.headers.cookie);_.json(listLocalClaudeSessions(u?.dir))})),app.get("/api/agent/history/:sessionId",checkAuth,((S,_)=>{const u=manager.get(S.params.sessionId);if(!u||u.mode!=="agent")return _.status(404).json({ok:!1,error:"\u4F1A\u8BDD\u4E0D\u5B58\u5728"});const n=u.claudeSessionId;if(!n)return _.json({ok:!0,messages:[],total:0,hasMore:!1});const t=(0,external_path_.join)((0,external_os_.homedir)(),".claude","projects");let c=null;try{if((0,external_fs_.existsSync)(t))for(const p of(0,external_fs_.readdirSync)(t,{withFileTypes:!0})){if(!p.isDirectory())continue;const f=(0,external_path_.join)(t,p.name,n+".jsonl");if((0,external_fs_.existsSync)(f)){c=f;break}}}catch{}if(!c)return _.json({ok:!0,messages:[],total:0,hasMore:!1});let l;try{l=(0,external_fs_.readFileSync)(c,"utf8").split(`
|
|
382
382
|
`).filter(Boolean)}catch(p){return _.status(500).json({ok:!1,error:p.message})}const m=Math.max(0,parseInt(S.query.offset,10)||0),o=Math.min(200,Math.max(1,parseInt(S.query.limit,10)||50)),i=l.length,a=i-m,e=Math.max(0,a-o),r=[];for(let p=e;p<a;p++)try{const f=JSON.parse(l[p]);if((f.type==="human"||f.type==="user")&&f.message?.content){const s=typeof f.message.content=="string"?f.message.content:f.message.content.find((v=>v.type==="text"))?.text||"";s&&r.push({type:"user",content:s,timestamp:f.timestamp})}else f.type==="assistant"&&f.message?.content?r.push({type:"assistant",message:f.message,timestamp:f.timestamp}):f.type==="result"&&r.push({type:"result",total_cost_usd:f.costUSD||f.total_cost_usd,timestamp:f.timestamp})}catch{}_.json({ok:!0,messages:r,total:i,hasMore:e>0})})),app.get("/api/dirs",checkAuth,((S,_)=>{const u=getUserInfo(S.headers.cookie);if(!u||u.role!=="admin")return _.status(403).json({error:"\u6CA1\u6709\u76EE\u5F55\u6D4F\u89C8\u6743\u9650"});const n=u.dir?(0,external_path_.resolve)((0,external_path_.normalize)(u.dir)):null,t=process.platform==="win32"?"\\":"/";let c=S.query.path||n||process.env.MYHI_CWD||(0,external_os_.homedir)(),l=(0,external_path_.resolve)((0,external_path_.normalize)(c)).replace(/[/\\]+$/,"");process.platform==="win32"&&/^[A-Za-z]:$/.test(l)&&(l+="\\"),n&&!l.startsWith(n)&&(l=n);try{const m=(0,external_fs_.readdirSync)(l,{withFileTypes:!0}).filter((a=>a.isDirectory()&&a.name!==".git")).map((a=>({name:a.name,path:l.replace(/[/\\]+$/,"")+t+a.name}))).sort(((a,e)=>a.name.localeCompare(e.name))),o=(0,external_path_.join)(l,".."),i=!n||(0,external_path_.resolve)((0,external_path_.normalize)(o)).startsWith(n);_.json({current:l,parent:i&&o!==l?o:null,dirs:m})}catch(m){_.status(400).json({error:m.message})}}));function safePath(S,_){const u=(0,external_path_.resolve)((0,external_path_.normalize)(S)),n=(0,external_path_.resolve)((0,external_path_.normalize)((0,external_path_.join)(S,_||"")));if(n!==u&&!n.startsWith(u+external_path_.sep))return null;try{const t=(0,external_fs_.realpathSync)(u),c=(0,external_fs_.existsSync)(n)?(0,external_fs_.realpathSync)(n):n;if(c!==t&&!c.startsWith(t+external_path_.sep))return null}catch{}return n}function walkFiles(S,_,u=[],n=0){if(n>20)return u;let t;try{t=(0,external_fs_.readdirSync)(S,{withFileTypes:!0})}catch{return u}for(const c of t){if(c.name===".git")continue;const l=(0,external_path_.join)(S,c.name),m=_?_+"/"+c.name:c.name;try{const o=(0,external_fs_.lstatSync)(l);if(o.isSymbolicLink())continue;o.isDirectory()?walkFiles(l,m,u,n+1):o.isFile()&&u.push({name:m,size:o.size,mtime:o.mtimeMs})}catch{}}return u}function fileHash(S){return new Promise(((_,u)=>{const n=(0,external_crypto_.createHash)("sha256"),t=(0,external_fs_.createReadStream)(S);t.on("data",(c=>n.update(c))),t.on("end",(()=>_(n.digest("hex")))),t.on("error",u)}))}app.get("/api/files/:sessionId",checkAuth,((S,_)=>{const u=manager.get(S.params.sessionId);if(!u)return _.status(404).json({error:"\u4F1A\u8BDD\u4E0D\u5B58\u5728"});const n=S.query.path||"",t=safePath(u.cwd,n);if(!t)return _.status(403).json({error:"\u8DEF\u5F84\u8D8A\u754C"});try{if(!(0,external_fs_.statSync)(t).isDirectory())return _.status(400).json({error:"\u4E0D\u662F\u76EE\u5F55"});const c=(0,external_fs_.readdirSync)(t,{withFileTypes:!0}).filter((o=>o.name!==".git")).map((o=>{const i=(0,external_path_.join)(t,o.name);try{const a=(0,external_fs_.lstatSync)(i);return a.isSymbolicLink()?null:{name:o.name,isDir:a.isDirectory(),size:a.isFile()?a.size:void 0,mtime:a.mtimeMs}}catch{return null}})).filter(Boolean).sort(((o,i)=>i.isDir-o.isDir||o.name.localeCompare(i.name))),l=n?n.replace(/\\/g,"/"):"",m=l.includes("/")?l.slice(0,l.lastIndexOf("/")):l?"":null;_.json({ok:!0,cwd:u.cwd,path:l,parent:m,entries:c})}catch(c){_.status(500).json({error:c.message})}})),app.get("/api/files/:sessionId/download",checkAuth,((S,_)=>{const u=manager.get(S.params.sessionId);if(!u)return _.status(404).json({error:"\u4F1A\u8BDD\u4E0D\u5B58\u5728"});const n=S.query.path;if(!n)return _.status(400).json({error:"\u7F3A\u5C11 path \u53C2\u6570"});const t=safePath(u.cwd,n);if(!t)return _.status(403).json({error:"\u8DEF\u5F84\u8D8A\u754C"});try{const c=(0,external_fs_.statSync)(t);if(!c.isFile())return _.status(400).json({error:"\u4E0D\u662F\u6587\u4EF6"});const l=n.split("/").pop();_.setHeader("Content-Disposition",`attachment; filename*=UTF-8''${encodeURIComponent(l)}`),_.setHeader("Content-Length",c.size),(0,external_fs_.createReadStream)(t).pipe(_)}catch{_.status(404).json({error:"\u6587\u4EF6\u4E0D\u5B58\u5728"})}})),app.post("/api/files/:sessionId/upload",checkAuth,((S,_)=>{const u=manager.get(S.params.sessionId);if(!u)return _.status(404).json({error:"\u4F1A\u8BDD\u4E0D\u5B58\u5728"});const n=(S.query.path||"").replace(/\\/g,"/"),t=safePath(u.cwd,n);if(!t)return _.status(403).json({error:"\u8DEF\u5F84\u8D8A\u754C"});(0,external_fs_.mkdirSync)(t,{recursive:!0}),multer({storage:multer.diskStorage({destination:(c,l,m)=>{l.originalname=Buffer.from(l.originalname,"latin1").toString("utf8");const o=l.originalname.includes("/")?l.originalname.slice(0,l.originalname.lastIndexOf("/")):"",i=o?(0,external_path_.join)(t,o):t,a=(0,external_path_.resolve)((0,external_path_.normalize)(i)),e=(0,external_path_.resolve)((0,external_path_.normalize)(u.cwd));if(a!==e&&!a.startsWith(e+external_path_.sep))return m(new Error("\u8DEF\u5F84\u8D8A\u754C"));(0,external_fs_.mkdirSync)(i,{recursive:!0}),m(null,i)},filename:(c,l,m)=>{const o=l.originalname.includes("/")?l.originalname.slice(l.originalname.lastIndexOf("/")+1):l.originalname;m(null,o)}}),limits:{fileSize:500*1024*1024}}).array("files",100)(S,_,(c=>{if(c)return _.status(400).json({error:c.message});if(!S.files?.length)return _.status(400).json({error:"\u6CA1\u6709\u6587\u4EF6"});const l=S.files.map((m=>({name:m.originalname,size:m.size,path:(0,external_path_.resolve)(m.path).replace(/\\/g,"/")})));io.emit("files:changed",{sessionId:u.id}),_.json({ok:!0,files:l})}))})),app.delete("/api/files/:sessionId",checkAuth,((S,_)=>{const u=manager.get(S.params.sessionId);if(!u)return _.status(404).json({error:"\u4F1A\u8BDD\u4E0D\u5B58\u5728"});const n=S.query.path;if(!n)return _.status(400).json({error:"\u7F3A\u5C11 path \u53C2\u6570"});const t=safePath(u.cwd,n);if(!t)return _.status(403).json({error:"\u8DEF\u5F84\u8D8A\u754C"});if((0,external_path_.resolve)((0,external_path_.normalize)(t))===(0,external_path_.resolve)((0,external_path_.normalize)(u.cwd)))return _.status(403).json({error:"\u4E0D\u80FD\u5220\u9664\u4F1A\u8BDD\u6839\u76EE\u5F55"});try{(0,external_fs_.statSync)(t).isDirectory()?(0,external_fs_.rmSync)(t,{recursive:!0}):(0,external_fs_.unlinkSync)(t),io.emit("files:changed",{sessionId:u.id}),_.json({ok:!0})}catch(c){_.status(500).json({error:c.message})}})),app.get("/api/files/:sessionId/manifest",checkAuth,(async(S,_)=>{const u=manager.get(S.params.sessionId);if(!u)return _.status(404).json({error:"\u4F1A\u8BDD\u4E0D\u5B58\u5728"});const n=S.query.path||"",t=safePath(u.cwd,n);if(!t)return _.status(403).json({error:"\u8DEF\u5F84\u8D8A\u754C"});try{const c=walkFiles(t,""),l=[];for(const m of c){if(m.size>=50*1024*1024){l.push(m);continue}try{const o=await fileHash((0,external_path_.join)(t,m.name));l.push({...m,hash:o})}catch{l.push(m)}}_.json({ok:!0,cwd:u.cwd,path:n,files:l})}catch(c){_.status(500).json({error:c.message})}})),app.get("/api/me",checkAuth,((S,_)=>{const u=getUserInfo(S.headers.cookie);_.json({name:u?.name||"\u7528\u6237",role:u?.role||"admin",exclusive:isExclusiveMode(),hasUsers:hasUsers(),dir:u?.dir||null})}));const gatewayFile=(0,external_path_.join)(server_configDir,"gateway.json");function loadGateway(){try{return JSON.parse((0,external_fs_.readFileSync)(gatewayFile,"utf8"))}catch{return{baseUrl:"",apiKey:""}}}app.get("/api/gateway",checkAdminAuth,((S,_)=>{const u=loadGateway();_.json({baseUrl:u.baseUrl||"",apiKey:u.apiKey?u.apiKey.length>12?u.apiKey.slice(0,6)+"***"+u.apiKey.slice(-4):"***":"",hasKey:!!u.apiKey})})),app.post("/api/gateway",checkAdminAuth,express.json(),((S,_)=>{const{baseUrl:u,apiKey:n}=S.body||{},t=loadGateway(),c={baseUrl:typeof u=="string"?u.trim():t.baseUrl,apiKey:!n||n.includes("***")?t.apiKey:n.trim()};try{(0,external_fs_.mkdirSync)(server_configDir,{recursive:!0}),(0,external_fs_.writeFileSync)(gatewayFile,JSON.stringify(c,null,2),{mode:384}),_.json({ok:!0})}catch(l){_.status(500).json({error:l.message})}})),app.get("/api/secrets",checkAdminAuth,((S,_)=>{try{_.json(secretsOverview())}catch(u){_.status(500).json({error:u.message})}})),app.post("/api/secrets",checkAdminAuth,express.json(),((S,_)=>{const{name:u,value:n,type:t,scope:c,cwd:l}=S.body||{},m=upsertSecret({name:u,value:n,type:t,scope:c,cwd:l});if(m.error)return _.status(400).json(m);_.json(m)})),app.delete("/api/secrets",checkAdminAuth,express.json(),((S,_)=>{const{name:u,scope:n,cwd:t}=S.body||{};if(!u)return _.status(400).json({error:"\u7F3A\u5C11 name"});try{_.json(deleteSecret({name:u,scope:n,cwd:t}))}catch(c){_.status(500).json({error:c.message})}})),app.get("/api/session/:id/secrets",checkAuth,((S,_)=>{const u=manager.get(S.params.id);if(!u)return _.status(404).json({error:"\u4F1A\u8BDD\u4E0D\u5B58\u5728"});_.json({cwd:u.cwd,project:listSecrets("project",u.cwd),global:listSecrets("global")})})),app.post("/api/session/:id/secrets",checkAuth,express.json(),((S,_)=>{const u=manager.get(S.params.id);if(!u)return _.status(404).json({error:"\u4F1A\u8BDD\u4E0D\u5B58\u5728"});const{name:n,value:t,type:c}=S.body||{},l=upsertSecret({name:n,value:t,type:c,scope:"project",cwd:u.cwd});if(l.error)return _.status(400).json(l);_.json(l)})),app.delete("/api/session/:id/secrets",checkAuth,express.json(),((S,_)=>{const u=manager.get(S.params.id);if(!u)return _.status(404).json({error:"\u4F1A\u8BDD\u4E0D\u5B58\u5728"});const{name:n}=S.body||{};if(!n)return _.status(400).json({error:"\u7F3A\u5C11 name"});_.json(deleteSecret({name:n,scope:"project",cwd:u.cwd}))})),app.post("/api/session/:id/secrets/bulk",checkAuth,express.json(),((S,_)=>{const u=manager.get(S.params.id);if(!u)return _.status(404).json({error:"\u4F1A\u8BDD\u4E0D\u5B58\u5728"});const n=upsertManyProject(u.cwd,(S.body||{}).text||"");if(n.error)return _.status(400).json(n);_.json(n)}));function getPkgVersion(){for(const S of["../package.json","./package.json","package.json"])try{const _=JSON.parse((0,external_fs_.readFileSync)((0,external_path_.join)(server_dirname,S),"utf8")).version;if(_&&_!=="0.0.0")return _}catch{}return"0.0.0"}const PKG_VERSION=getPkgVersion();let _latestVersion=null,_lastVersionCheck=0;const VERSION_CHECK_INTERVAL=600*1e3;async function checkLatestVersion(){const S=Date.now();if(_latestVersion&&S-_lastVersionCheck<VERSION_CHECK_INTERVAL)return _latestVersion;try{const _=await fetch("https://registry.npmjs.org/@wendongfly/myhi/latest",{headers:{Accept:"application/json"},signal:AbortSignal.timeout(8e3)});_.ok&&(_latestVersion=(await _.json()).version,_lastVersionCheck=S)}catch{}return _latestVersion}app.get("/api/version",(async(S,_)=>{const u=getPkgVersion(),n=await checkLatestVersion();_.json({current:u,latest:n||u,updateAvailable:n&&n!==u})}));function isSystemd(){return process.platform==="linux"&&(process.env.INVOCATION_ID||process.env.JOURNAL_STREAM)}function getNpmUpgradeCmd(){const S="--registry https://registry.npmjs.org";return process.platform==="win32"?`npm.cmd install -g @wendongfly/myhi@latest ${S}`:`npm install -g @wendongfly/myhi@latest ${S}`}function restartService(){if(process.send)process.send({type:"restart"});else if(isSystemd())try{(0,external_child_process_namespaceObject.spawn)("sudo",["systemctl","restart","myhi.service"],{detached:!0,stdio:"ignore"}).unref()}catch{}else process.exit(0)}app.get("/api/server-config",checkAuth,((S,_)=>{const u=process.env.ASR_URL||(()=>{try{return JSON.parse((0,external_fs_.readFileSync)((0,external_path_.join)((0,external_os_.homedir)(),".myhi","asr.json"),"utf8")).url}catch{return""}})();_.json({asrUrl:u||""})})),app.post("/api/server-config",checkAuth,express.json(),((S,_)=>{const{asrUrl:u}=S.body||{},n=(0,external_path_.join)((0,external_os_.homedir)(),".myhi","asr.json");try{const t=(u||"").trim();(0,external_fs_.writeFileSync)(n,JSON.stringify({url:t},null,2),"utf8"),_.json({ok:!0})}catch(t){_.status(500).json({error:t.message})}})),app.post("/api/restart",checkAuth,((S,_)=>{_.json({ok:!0}),setTimeout((()=>restartService()),300)})),app.post("/api/update",checkAuth,(async(S,_)=>{try{await execAsync(getNpmUpgradeCmd(),{encoding:"utf8",timeout:12e4}),console.log("[myhi] \u5347\u7EA7\u5B8C\u6210"),_.json({ok:!0,message:"\u5347\u7EA7\u5B8C\u6210\uFF0C\u670D\u52A1\u5C06\u81EA\u52A8\u91CD\u542F..."}),setTimeout((()=>restartService()),500)}catch(u){const n=(u.stderr||u.stdout||u.message||"").split(`
|
|
383
383
|
`).filter((t=>t.trim())).slice(-5).join(`
|
|
384
384
|
`);console.error("[myhi] \u5347\u7EA7\u5931\u8D25:",n),_.status(500).json({ok:!1,error:`npm install \u5931\u8D25\uFF1A
|
package/package.json
CHANGED