@wendongfly/myhi 1.3.157 → 1.3.158

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/index.min.js CHANGED
@@ -382,7 +382,7 @@ Content-Length: `+C+`\r
382
382
  `)}))})),this._proc.on("close",(h=>{if(!this._interrupted&&this._buffer.trim())try{const c=JSON.parse(this._buffer.trim());this._handleMessage(c)}catch{}this._keepAliveTimer&&(clearInterval(this._keepAliveTimer),this._keepAliveTimer=null),this._stopStallWatchdog(),this._proc=null,this._buffer="",console.log(`[agent] \u8FDB\u7A0B\u9000\u51FA (code ${h}), \u4F1A\u8BDD: ${this.claudeSessionId||"?"}`),this._busy&&(this._busy=!1,this._interrupted=!1,this.emit("agent:busy",!1),this._pendingReject&&(this._pendingReject(new Error(`Claude \u8FDB\u7A0B\u9000\u51FA (code ${h})`)),this._pendingResolve=null,this._pendingReject=null)),this._flushPendingSteer(),this.alive&&h!==0&&h!==null&&this.emit("agent:error",{message:`Claude \u8FDB\u7A0B\u5F02\u5E38\u9000\u51FA (code ${h})\uFF0C\u4E0B\u6B21\u67E5\u8BE2\u5C06\u81EA\u52A8\u91CD\u542F`})})),this._proc.on("error",(h=>{this._keepAliveTimer&&(clearInterval(this._keepAliveTimer),this._keepAliveTimer=null),this._stopStallWatchdog(),this._proc=null,this._busy=!1,this.emit("agent:busy",!1),this.emit("agent:error",{message:`\u542F\u52A8 Claude \u5931\u8D25: ${h.message}`}),this._pendingReject&&(this._pendingReject(h),this._pendingResolve=null,this._pendingReject=null)})),this._keepAliveTimer=setInterval((()=>{this._writeStdin({type:"keep_alive"})}),3e4)}async query(d,{internal:l=!1}={}){if(this._busy){this.emit("agent:error",{message:"\u6B63\u5728\u5904\u7406\u4E2D\uFF0C\u8BF7\u7B49\u5F85\u5B8C\u6210"});return}if(l||(this._followCount=0,this._followStopSignal=!1,this._cancelFollowUp()),d==="/clear"){this.reset(),this.emit("agent:message",{type:"system",subtype:"info",message:"\u5DF2\u6E05\u9664 Claude \u4E0A\u4E0B\u6587\uFF0C\u4E0B\u6B21\u63D0\u95EE\u5C06\u5F00\u542F\u5168\u65B0\u5BF9\u8BDD"});return}const n=d.match(/^\/resume\s+(\S+)/);if(n){if(this._proc){try{this._proc.kill("SIGTERM")}catch{}this._proc=null}this.claudeSessionId=n[1],this._history=[],this._buffer="",this._loadResumedHistory(),this.emit("agent:message",{type:"system",subtype:"info",message:`\u5DF2\u5207\u6362\u5230\u4F1A\u8BDD ${n[1].slice(0,8)}...\uFF0C\u4E0B\u6B21\u63D0\u95EE\u5C06\u6062\u590D\u8BE5\u5BF9\u8BDD`});return}const e=d.match(/^\/model\s+(\S+)/);if(e){if(this.modelId=e[1],this._proc){try{this._proc.kill("SIGTERM")}catch{}this._proc=null}this.emit("agent:message",{type:"system",subtype:"info",message:`\u6A21\u578B\u5DF2\u5207\u6362\u4E3A ${e[1]}`});return}if(d==="/plan"||d.startsWith("/plan ")){if(this.permissionMode==="plan"){if(this.permissionMode=normalizePermissionMode(this._prePlanMode),this._prePlanMode=null,this._proc){try{this._proc.kill("SIGTERM")}catch{}this._proc=null}this.emit("agent:message",{type:"system",subtype:"info",message:"\u5DF2\u9000\u51FA\u8BA1\u5212\u6A21\u5F0F"})}else{if(this._prePlanMode=this.permissionMode,this.permissionMode="plan",this._proc){try{this._proc.kill("SIGTERM")}catch{}this._proc=null}this.emit("agent:message",{type:"system",subtype:"info",message:"\u5DF2\u8FDB\u5165\u8BA1\u5212\u6A21\u5F0F\uFF08\u53EA\u89C4\u5212\u4E0D\u6267\u884C\uFF09"});const h=d.slice(5).trim();if(h){setTimeout((()=>this.query(h)),500);return}}return}if(d.startsWith("/rename")){this.emit("agent:message",{type:"system",subtype:"info",message:"\u4F1A\u8BDD\u5DF2\u547D\u540D"});return}this._busy=!0,this._interrupted=!1,this.emit("agent:busy",!0),this._loopSigCounts.clear(),this._loopPoisonHits=0,this._loopTurnToolCalls=0,this._loopTripped=!1,l||(this._loopAutoRecover=0),this._redactor=buildRedactor(),this._pseudoMap||(this._pseudoMap=loadMap(this.claudeSessionId||this.id)),this._pseudo=buildPseudonymizer(this.cwd,this._pseudoMap),this._lastActivityAt=Date.now(),this._awaitingTool=!1,this._startStallWatchdog();const o=redactDeep(d,this._redactor);return this._history.push({type:"user",content:o,timestamp:Date.now()}),!this.firstUserText&&typeof o=="string"&&!o.startsWith("/")&&(this.firstUserText=o.trim().slice(0,160)),this._proc||this._spawnProcess(),new Promise(((u,h)=>{this._pendingResolve=u,this._pendingReject=h,d.startsWith("/")&&(this._slashTimeout=setTimeout((()=>{this._busy&&(this._busy=!1,this._interrupted=!1,this.emit("agent:busy",!1),this.emit("agent:message",{type:"system",subtype:"info",message:`\u547D\u4EE4 ${d} \u5DF2\u53D1\u9001`}),this._pendingResolve&&(this._pendingResolve(0),this._pendingResolve=null,this._pendingReject=null))}),3e4));let c=d;if(this._pseudo?.enabled){const a=this._pseudo.pseudonymize(d);c=a.text;const t=this.claudeSessionId||this.id;saveMap(t,this._pseudoMap),a.count>0&&(appendAudit(t,{ts:Date.now(),level:this._pseudo.level,maskedCount:a.count,byType:a.byType,sentToModel:a.text}),this.emit("agent:message",{type:"system",subtype:"info",message:`\u{1F6E1} \u9690\u79C1\u62A4\u680F\uFF1A\u672C\u8F6E\u5DF2\u8131\u654F ${a.count} \u5904\u654F\u611F\u4FE1\u606F\uFF0C\u6A21\u578B\u53EA\u770B\u5230\u5360\u4F4D\u7B26\uFF08\u6620\u5C04\u8868\u7559\u672C\u673A\u3001\u53EF\u9006\u8FD8\u539F\uFF09\u3002`}))}this._writeStdin({type:"user",message:{role:"user",content:c}})||(this._busy=!1,this.emit("agent:busy",!1),this._pendingResolve=null,this._pendingReject=null,h(new Error("Claude \u8FDB\u7A0B\u4E0D\u53EF\u5199")))}))}_handleMessage(d){const l=!!this.claudeSessionId;if(this._lastActivityAt=Date.now(),d.type==="assistant"&&Array.isArray(d.message?.content)?d.message.content.some((c=>c.type==="tool_use"))&&(this._awaitingTool=!0):d.type==="user"&&(this._awaitingTool=!1),d.session_id&&!this.claudeSessionId&&(this.claudeSessionId=d.session_id),d.type==="system"&&d.subtype==="init"&&d.session_id&&(this.claudeSessionId=d.session_id),!l&&this.claudeSessionId&&this.emit("session-id",this.claudeSessionId),d.type==="system"&&d.subtype==="init"&&this.permissionMode==="bypassPermissions"&&d.permissionMode&&d.permissionMode!=="bypassPermissions"){const c=d.permissionMode;this.reset(),this.emit("agent:message",{type:"system",subtype:"warning",message:`\u26A0\uFE0F \u8FD9\u4E2A\u4F1A\u8BDD\u88AB --resume \u5E26\u56DE\u4E86\u300C${c}\u300D\u6A21\u5F0F\uFF08\u975E bypass\uFF0C\u4F1A\u62E6\u5199/\u5220\u4E14\u65E0\u6CD5\u8FD0\u884C\u65F6\u63D0\u6743\uFF0C\u70B9\u300C\u9000\u51FA\u8BA1\u5212\u300D\u4E5F\u9003\u4E0D\u6389\uFF09\u3002\u5DF2\u81EA\u52A8\u65AD\u5F00\u65E7\u4F1A\u8BDD\u94FE\u3001\u91CD\u5F00\u4E3A\u5E72\u51C0\u7684 bypass \u4F1A\u8BDD\u2014\u2014\u8BF7\u91CD\u53D1\u4F60\u521A\u624D\u7684\u6307\u4EE4\uFF0C\u8FD9\u6B21\u4F1A\u76F4\u63A5\u6267\u884C\u3002`});return}const n=this._pseudo?.enabled?redactDeep(d,this._pseudo.restore):d,e=redactDeep(n,this._redactor),o=stripHeavyPayload({...e,timestamp:Date.now()}),u=JSON.stringify(o);this._followEnabled&&u.includes("[\u8DDF\u8FDB\u5B8C\u6210]")&&(this._followStopSignal=!0),u.length>10240&&(o._truncated=!0),this._history.push(o);const h=500;if(this._history.length>h&&(this._history=this._history.slice(-h)),this.emit("agent:message",e),this._trackImagePressure(u),this._checkDeathLoop(d,u),d.type==="rate_limit_event"&&d.rate_limit_info&&(this._usage.rateLimitInfo=d.rate_limit_info),d.type==="result"&&(this._usage.queryCount++,d.total_cost_usd&&(this._usage.totalCostUSD+=d.total_cost_usd),d.usage&&(this._usage.totalInputTokens+=d.usage.input_tokens||0,this._usage.totalOutputTokens+=d.usage.output_tokens||0,this._usage.totalCacheReadTokens+=d.usage.cache_read_input_tokens||0,this._usage.totalCacheCreationTokens+=d.usage.cache_creation_input_tokens||0),d.modelUsage))for(const[c,i]of Object.entries(d.modelUsage))this._usage.modelUsage[c]||(this._usage.modelUsage[c]={inputTokens:0,outputTokens:0,costUSD:0}),this._usage.modelUsage[c].inputTokens+=i.inputTokens||0,this._usage.modelUsage[c].outputTokens+=i.outputTokens||0,this._usage.modelUsage[c].costUSD+=i.costUSD||0;{const c=d.type==="assistant"?d.message?.usage:d.type==="result"?d.usage:null;if(c){const i=(c.input_tokens||0)+(c.cache_read_input_tokens||0)+(c.cache_creation_input_tokens||0);i>this._contextTokens&&(this._contextTokens=i)}}if(d.type==="result"){this._slashTimeout&&(clearTimeout(this._slashTimeout),this._slashTimeout=null),this._stopStallWatchdog();const c=!this._interrupted&&!d.is_error;this._busy=!1,this._interrupted=!1,this.emit("agent:busy",!1),this._pendingResolve&&(this._pendingResolve(0),this._pendingResolve=null,this._pendingReject=null),this._flushPendingSteer(),c&&this._maybeRelayDraft(),this._maybeScheduleFollowUp()}}_trackImagePressure(d){const l=(d.match(/"type":"image"/g)||[]).length;l&&(this._imageBlockCount+=l,this._imageBlockCount>=this._imageNudgeAt&&(this._imageNudgeAt+=IMAGE_NUDGE_STEP,this.emit("agent:message",{type:"system",subtype:"warning",message:`\u2139\uFE0F \u672C\u4F1A\u8BDD\u5DF2\u7D2F\u79EF\u7EA6 ${this._imageBlockCount} \u5F20\u56FE\u7247\u3002\u56FE\u7247\u8D8A\u591A\u8D8A\u5BB9\u6613\u89E6\u53D1 API \u56FE\u7247\u5904\u7406\u9519\u8BEF\u5E76\u62D6\u6162/\u6D88\u8017\u989D\u5EA6\uFF0C\u5EFA\u8BAE\u7528 /clear \u91CD\u5F00\u4E00\u4E2A\u5E72\u51C0\u4F1A\u8BDD\uFF0C\u6216\u51CF\u5C11\u540E\u7EED\u622A\u56FE\u3002`})))}_checkDeathLoop(d,l){if(this._loopTripped)return;let n=!1;try{const e=l||JSON.stringify(d);if(LOOP_POISON_PHRASES.some((o=>e.includes(o)))){const o=d.type==="assistant",u=e.includes('"type":"image"'),h=e.length<=POISON_MAX_NOTICE_LEN;n=!o&&(u||h)}}catch{}if(n&&(this._loopPoisonHits++,this._loopPoisonHits>=LOOP_MAX_POISON_HITS)){this._tripLoopBreaker("\u8BE5\u56FE\u7247/\u5185\u5BB9 API \u53CD\u590D\u65E0\u6CD5\u5904\u7406\u5E76\u5DF2\u88AB\u79FB\u9664\uFF0C\u8BF7\u4E0D\u8981\u518D\u7528 Read \u91CD\u65B0\u8BFB\u53D6\u5B83\u2014\u2014\u5B83\u5DF2\u4E0D\u53EF\u7528\u3002\u8BF7\u57FA\u4E8E\u73B0\u6709\u6587\u5B57\u4FE1\u606F\u7EE7\u7EED\uFF1B\u82E5\u786E\u5B9E\u9700\u8981\u8BE5\u56FE\uFF0C\u8BF7\u63D0\u793A\u7528\u6237\u91CD\u65B0\u4E0A\u4F20\u4E00\u5F20\u66F4\u5C0F\u7684\u622A\u56FE\u3002");return}if(d.type==="assistant"&&Array.isArray(d.message?.content)){const e=!!d.parent_tool_use_id,o=d.parent_tool_use_id||"main";for(const u of d.message.content){if(u.type!=="tool_use")continue;if(!e&&(this._loopTurnToolCalls++,this._loopTurnToolCalls>LOOP_MAX_TURN_TOOLCALLS)){this._tripLoopBreaker(`\u672C\u8F6E\u5DE5\u5177\u8C03\u7528\u5DF2\u8FBE ${this._loopTurnToolCalls} \u6B21\u5E76\u63D2\u5165\u68C0\u67E5\u70B9\u3002\u82E5\u4ECD\u5728\u6B63\u5E38\u63A8\u8FDB\uFF0C\u8BF7\u6982\u8FF0\u5F53\u524D\u8FDB\u5C55\u540E\u7EE7\u7EED\uFF1B\u82E5\u5728\u91CD\u590D\u540C\u7C7B\u64CD\u4F5C\u800C\u6CA1\u6709\u8FDB\u5C55\uFF0C\u8BF7\u6362\u4E00\u79CD\u601D\u8DEF\uFF0C\u6216\u5148\u5411\u7528\u6237\u6C47\u62A5\u518D\u7B49\u5F85\u6307\u793A\u3002`);return}const h=`${o}:${u.name}:${this._hashInput(u.input)}`,c=(this._loopSigCounts.get(h)||0)+1;if(this._loopSigCounts.set(h,c),c>=LOOP_MAX_IDENTICAL_CALLS){this._tripLoopBreaker(`\u5DE5\u5177\u300C${u.name}\u300D\u5DF2\u7528\u5B8C\u5168\u76F8\u540C\u7684\u53C2\u6570\u8C03\u7528 ${c} \u6B21\uFF0C\u7591\u4F3C\u9677\u5165\u6B7B\u5FAA\u73AF\u3002\u8BF7\u505C\u6B62\u91CD\u590D\u8BE5\u8C03\u7528\uFF0C\u6539\u7528\u4E0D\u540C\u53C2\u6570/\u4E0D\u540C\u5DE5\u5177\uFF0C\u6216\u8DF3\u8FC7\u8FD9\u4E00\u6B65\u7EE7\u7EED\u3002`);return}}}}_hashInput(d){let l;try{l=JSON.stringify(stripHeavyPayload(d))}catch{l=String(d)}l.length>4096&&(l=l.slice(0,4096));let n=5381;for(let e=0;e<l.length;e++)n=(n<<5)+n+l.charCodeAt(e)|0;return n.toString(36)}_tripLoopBreaker(d){if(this._loopTripped=!0,console.warn("[agent] \u{1F50C} \u6B7B\u5FAA\u73AF\u7194\u65AD:",d),this._loopAutoRecover>=LOOP_MAX_AUTO_RECOVER){this._pendingSteer=null,this.emit("agent:message",{type:"system",subtype:"warning",message:"\u26A0\uFE0F \u591A\u6B21\u81EA\u52A8\u7EA0\u504F\u4ECD\u672A\u8DF3\u51FA\u5FAA\u73AF\uFF0C\u5DF2\u505C\u6B62\u4EE5\u4FDD\u62A4 session \u989D\u5EA6\u3002\u8BF7 /clear \u91CD\u5F00\u6216\u6362\u4E2A\u95EE\u6CD5\u3002"}),this.interrupt();return}this._loopAutoRecover++,this._pendingSteer=d,this.emit("agent:message",{type:"system",subtype:"warning",message:`\u26A0\uFE0F \u7194\u65AD\u4FDD\u62A4\uFF08\u7B2C ${this._loopAutoRecover} \u6B21\u81EA\u52A8\u7EA0\u504F\uFF09\uFF1A${d}`}),this.interrupt()}_flushPendingSteer(){if(!this._pendingSteer)return;const d=this._pendingSteer;this._pendingSteer=null,setTimeout((()=>{!this._busy&&this.alive&&this.query(d,{internal:!0}).catch((()=>{}))}),600)}setFollowUp({enabled:d,intervalMinutes:l}={}){if(typeof d=="boolean"&&(this._followEnabled=d),l!=null){const n=Math.max(1,Math.min(180,Number(l)||15));this._followIntervalMs=Math.round(n*60*1e3)}return this._followEnabled?this._busy||this._maybeScheduleFollowUp():(this._cancelFollowUp(),this._followCount=0),this.emit("agent:message",{type:"system",subtype:"info",message:this._followEnabled?`\u{1F504} \u81EA\u52A8\u8DDF\u8FDB\u5DF2\u5F00\u542F\uFF1A\u6BCF ${Math.round(this._followIntervalMs/6e4)} \u5206\u949F\u81EA\u52A8\u67E5\u4E00\u6B21\u8FDB\u5EA6\u5E76\u6C47\u62A5\uFF08\u6700\u591A ${this._followMax} \u6B21\uFF1BAI \u5224\u65AD\u5168\u90E8\u5B8C\u6210\u4F1A\u81EA\u52A8\u505C\uFF09\u3002`:"\u{1F504} \u81EA\u52A8\u8DDF\u8FDB\u5DF2\u5173\u95ED\u3002"}),this.followUpState()}followUpState(){return{enabled:this._followEnabled,intervalMinutes:Math.round(this._followIntervalMs/6e4),max:this._followMax,count:this._followCount}}_cancelFollowUp(){this._followTimer&&(clearTimeout(this._followTimer),this._followTimer=null)}_cancelRelay(){this._relayTimer&&(clearTimeout(this._relayTimer),this._relayTimer=null)}_maybeRelayDraft(){!this.alive||this._relayTimer||(this._relayTimer=setTimeout((()=>{if(this._relayTimer=null,this._busy||!this.alive)return;let d=null;try{d=nextAutoSendDraft(this.id)}catch{return}if(!d)return;try{removeDraft(d.id)}catch{}const l=buildDraftPrompt(d);l.trim()&&(this.emit("agent:message",{type:"system",subtype:"info",message:"\u{1F4E5} \u81EA\u52A8\u63A5\u529B\uFF1A\u4E0A\u4E00\u8F6E\u5DF2\u5B8C\u6210\uFF0C\u53D1\u51FA\u4E0B\u9762\u8FD9\u6761\u8349\u7A3F"}),this.emit("agent:message",{type:"user",content:draftDisplayText(d)||l,timestamp:Date.now()}),this.emit("draft-relayed",{id:d.id,sessionId:this.id}),this.lastInputTime=Date.now(),this.query(l).catch((()=>{})))}),RELAY_DELAY_MS),this._relayTimer.unref&&this._relayTimer.unref())}_maybeScheduleFollowUp(){if(this._cancelFollowUp(),!(!this._followEnabled||!this.alive)){if(this._followStopSignal){this._followStopSignal=!1,this._followCount=0,this.emit("agent:message",{type:"system",subtype:"info",message:"\u{1F504} AI \u5DF2\u786E\u8BA4\u4EFB\u52A1\u5168\u90E8\u5B8C\u6210\uFF0C\u81EA\u52A8\u8DDF\u8FDB\u505C\u6B62\u3002"});return}if(this._followCount>=this._followMax){this.emit("agent:message",{type:"system",subtype:"info",message:`\u{1F504} \u81EA\u52A8\u8DDF\u8FDB\u5DF2\u8FDE\u7EED ${this._followMax} \u6B21\uFF0C\u6682\u505C\uFF08\u9632\u7A7A\u8F6C\u70E7\u989D\u5EA6\uFF09\u3002\u9700\u8981\u7EE7\u7EED\u53EF\u624B\u52A8\u95EE\u4E00\u53E5\u6216\u91CD\u5F00\u3002`});return}this._followTimer=setTimeout((()=>{this._followTimer=null,!(this._busy||!this.alive||!this._followEnabled)&&(this._followCount++,this.emit("agent:message",{type:"system",subtype:"info",message:`\u{1F504} \u81EA\u52A8\u8DDF\u8FDB\uFF08\u7B2C ${this._followCount}/${this._followMax} \u6B21\uFF09\uFF1A\u8BA9 AI \u67E5\u770B\u8FDB\u5EA6\u2026`}),this.query(FOLLOW_UP_PROMPT,{internal:!0}).catch((()=>{})))}),this._followIntervalMs)}}_startStallWatchdog(){this._stopStallWatchdog(),this._watchdogTimer=setInterval((()=>{if(!this._busy){this._stopStallWatchdog();return}if(this._awaitingTool)return;const d=Date.now()-this._lastActivityAt;if(d>=STALL_WATCHDOG_MS){const l=Math.round(d/1e3);console.warn(`[agent] \u23F1 \u505C\u6446\u770B\u95E8\u72D7\u89E6\u53D1\uFF1A\u7B49\u5F85\u6A21\u578B\u54CD\u5E94\u5DF2 ${l}s \u65E0\u4EFB\u4F55\u6D88\u606F\uFF0C\u5F3A\u5236\u4E2D\u65AD`),this.emit("agent:message",{type:"system",subtype:"warning",message:`\u23F1 \u68C0\u6D4B\u5230\u4F1A\u8BDD\u505C\u6446\uFF08\u7B49\u5F85\u6A21\u578B\u54CD\u5E94 ${l}s \u65E0\u54CD\u5E94\uFF0C\u7591\u4F3C API \u4F20\u8F93\u5C42\u91CD\u8BD5\u5361\u4F4F\uFF09\uFF0C\u5DF2\u5F3A\u5236\u4E2D\u65AD\u672C\u56DE\u5408\u3002\u8BF7\u91CD\u8BD5\u6216\u7A0D\u540E\u518D\u8BD5\u3002`}),this._stopStallWatchdog(),this.interrupt()}}),STALL_CHECK_INTERVAL_MS),this._watchdogTimer.unref&&this._watchdogTimer.unref()}_stopStallWatchdog(){this._watchdogTimer&&(clearInterval(this._watchdogTimer),this._watchdogTimer=null)}respondPermission(d,l){return this._writeStdin({type:"control_response",request_id:d,allow:l})}_hardKillTree(d){if(d)try{if(process.platform==="win32")(0,external_child_process_namespaceObject.execSync)(`taskkill /PID ${d} /F /T`,{stdio:"pipe",timeout:5e3});else{try{process.kill(d,"SIGTERM")}catch{}setTimeout((()=>{try{process.kill(d,0)}catch{return}try{process.kill(d,"SIGKILL")}catch{}}),1e3)}}catch{}}interrupt(){if(!this._proc||!this._busy)return;this._interrupted=!0;const d=this._proc.pid,l=this._proc,e=this._writeStdin({type:"control_request",request_id:`interrupt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,request:{subtype:"interrupt"}})?1500:0;setTimeout((()=>{this._busy&&this._proc===l&&(console.log(`[agent] graceful interrupt \u8D85\u65F6\uFF0C\u5F3A\u5236\u7ED3\u675F\u8FDB\u7A0B\u6811 PID ${d}`),this._hardKillTree(d))}),e),this.emit("agent:message",{type:"system",subtype:"interrupted",message:"\u67E5\u8BE2\u5DF2\u4E2D\u65AD"})}kill(){if(this.alive=!1,this._cancelRelay(),this._cancelFollowUp(),this._keepAliveTimer&&(clearInterval(this._keepAliveTimer),this._keepAliveTimer=null),this._proc&&(this._hardKillTree(this._proc.pid),this._proc=null),this._pendingReject){try{this._pendingReject(new Error("\u4F1A\u8BDD\u5DF2\u7EC8\u6B62"))}catch{}this._pendingResolve=null,this._pendingReject=null}this._busy=!1}_loadResumedHistory(){try{const d=(0,external_path_.join)((0,external_os_.homedir)(),".claude","projects");if(!(0,external_fs_.existsSync)(d))return;for(const l of(0,external_fs_.readdirSync)(d,{withFileTypes:!0})){if(!l.isDirectory())continue;const n=(0,external_path_.join)(d,l.name,this.claudeSessionId+".jsonl");if(!(0,external_fs_.existsSync)(n))continue;const e=(0,external_fs_.readFileSync)(n,"utf8").split(`
383
383
  `).filter(Boolean),o=e.slice(-20);if(!this.firstUserText)for(const u of e.slice(0,40))try{const h=JSON.parse(u);if(h.type!=="user"&&h.type!=="human")continue;const c=h.message?.content,i=(typeof c=="string"?c:c?.find?.((a=>a.type==="text"))?.text||"").trim();if(!i||i.startsWith("/")||/^(Caveat:|<command-name>|<system-reminder>|<local-command)/.test(i))continue;this.firstUserText=i.slice(0,160);break}catch{}for(const u of o)try{const h=JSON.parse(u);if(h.type==="human"||h.type==="user"&&h.message?.content){const c=typeof h.message.content=="string"?h.message.content:h.message.content.find((i=>i.type==="text"))?.text||"";c&&this._history.push({type:"user",content:c,timestamp:h.timestamp})}else if(h.type==="assistant"&&h.message?.content){this._history.push({type:"assistant",message:h.message,timestamp:h.timestamp});const c=h.message.usage;if(c){const i=(c.input_tokens||0)+(c.cache_read_input_tokens||0)+(c.cache_creation_input_tokens||0);i>this._contextTokens&&(this._contextTokens=i)}}else h.type==="result"&&this._history.push({type:"result",total_cost_usd:h.costUSD||h.total_cost_usd,timestamp:h.timestamp})}catch{}try{const u=(0,external_fs_.statSync)(n).mtimeMs;u>0&&(this._lastActivityAt=Math.max(this._lastActivityAt,u))}catch{}return}}catch(d){console.warn("[agent] \u52A0\u8F7D\u6062\u590D\u4F1A\u8BDD\u5386\u53F2\u5931\u8D25:",d.message)}}get isBusy(){return this._busy}getRecentHistory(d=20){return this._history.slice(-d)}getUsage(){return{...this._usage}}addViewer(d,l){this._viewers.add(d),l&&this._viewerNames.set(d,l)}removeViewer(d){this._viewers.delete(d),this._viewerNames.delete(d)}get viewerCount(){return new Set(this._viewerNames.values()).size||this._viewers.size}takeControl(d,l){this.controlHolder=d,this.controlHolderName=l||null,this.lastInputTime=Date.now()}releaseControl(){this.controlHolder=null,this.controlHolderName=null,this.lastInputTime=null}isController(d){return this.controlHolder===d}setPermissionMode(d){this.permissionMode=normalizePermissionMode(d),this._proc&&(this.kill(),this.alive=!0)}reset(){this._proc&&(this._hardKillTree(this._proc.pid),this._proc=null),this.claudeSessionId=null,this._history=[],this._contextTokens=0,this._buffer="",this._imageBlockCount=0,this._imageNudgeAt=IMAGE_NUDGE_STEP,this._cancelFollowUp(),this._followCount=0,this._followStopSignal=!1,this._cancelRelay(),this.permissionMode="bypassPermissions"}toJSON(){return{id:this.id,title:this.title,firstUserText:this.firstUserText||"",cwd:this.cwd,tags:this.tags,createdAt:this.createdAt,lastActivityAt:this._lastActivityAt||null,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,contextTokens:this._contextTokens,followUp:this.followUpState()}}}function getSessionHealth(S){const d={found:!1,persistedMode:null,poisoned:!1,messageCount:0,transcriptKB:0,imageCount:0,updatedAt:null};if(!S)return d;try{const l=(0,external_path_.join)((0,external_os_.homedir)(),".claude","projects");if(!(0,external_fs_.existsSync)(l))return d;for(const n of(0,external_fs_.readdirSync)(l,{withFileTypes:!0})){if(!n.isDirectory())continue;const e=(0,external_path_.join)(l,n.name,S+".jsonl");if(!(0,external_fs_.existsSync)(e))continue;const o=(0,external_fs_.readFileSync)(e,"utf8"),u=o.split(`
384
384
  `).filter(Boolean);let h=null,c=null,i=0;for(const a of u){const t=a.match(/"type":"image"/g);if(t&&(i+=t.length),a.includes("permissionMode"))try{const r=JSON.parse(a);r.type==="user"&&r.permissionMode&&(h=r.permissionMode)}catch{}}try{const a=JSON.parse(u[u.length-1]);a.timestamp&&(c=a.timestamp)}catch{}return{found:!0,persistedMode:h,poisoned:!!(h&&h!=="bypassPermissions"),messageCount:u.length,transcriptKB:Math.round(o.length/1024),imageCount:i,updatedAt:c}}}catch{}return d}let _claudeSessionsCache=null,_claudeSessionsCacheTime=0;const CLAUDE_SESSIONS_CACHE_TTL=3e4;function listLocalClaudeSessions(S){const d=Date.now();if(_claudeSessionsCache&&d-_claudeSessionsCacheTime<CLAUDE_SESSIONS_CACHE_TTL){if(!S)return _claudeSessionsCache;const o=(0,external_path_.resolve)((0,external_path_.normalize)(S)).replace(/[\\/]+$/,"");return _claudeSessionsCache.filter((u=>(0,external_path_.resolve)((0,external_path_.normalize)(u.projectPath)).replace(/[\\/]+$/,"").startsWith(o)))}const l=[],n=S?(0,external_path_.resolve)((0,external_path_.normalize)(S)).replace(/[\\/]+$/,""):null;try{const o=(0,external_path_.join)((0,external_os_.homedir)(),".claude","projects");if(!(0,external_fs_.existsSync)(o))return l;for(const u of(0,external_fs_.readdirSync)(o,{withFileTypes:!0})){if(!u.isDirectory())continue;const h=(0,external_path_.join)(o,u.name);try{for(const c of(0,external_fs_.readdirSync)(h)){if(!c.endsWith(".jsonl"))continue;const i=c.replace(".jsonl",""),a=(0,external_path_.join)(h,c);try{const t=(0,external_fs_.readFileSync)(a,"utf8").split(`
385
- `).filter(Boolean);let r=null,p=null,f=0,s="";for(const m of t)try{const b=JSON.parse(m);if(r||(r=b),p=b,f++,!s&&b.type==="human"||b.type==="user"&&b.message?.content){const _=b.message.content;if(typeof _=="string")s=_.slice(0,120);else if(Array.isArray(_)){const g=_.find((w=>w.type==="text"));g&&(s=g.text?.slice(0,120)||"")}}}catch{}let v=u.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;l.push({sessionId:i,projectDir:u.name,projectPath:v,messageCount:f,summary:s,createdAt:r?.timestamp||null,updatedAt:p?.timestamp||null})}catch{}}}catch{}}}catch{}l.sort(((o,u)=>new Date(u.updatedAt||0).getTime()-new Date(o.updatedAt||0).getTime()));const e=l.slice(0,50);return _claudeSessionsCache=e,_claudeSessionsCacheTime=Date.now(),e.slice(0,20)}const DEFAULT_SHELL=process.platform==="win32"?process.env.SHELL||"powershell.exe":process.env.SHELL||"/bin/bash",sessions_CONFIG_DIR=(0,external_path_.join)((0,external_os_.homedir)(),".myhi"),SESSIONS_FILE=(0,external_path_.join)(sessions_CONFIG_DIR,"sessions.json"),savePath=null;function loadSavedConfigs(){let S;try{S=(0,external_fs_.readFileSync)(SESSIONS_FILE,"utf8")}catch{return[]}try{const d=JSON.parse(S);if(!Array.isArray(d))throw new Error("\u5185\u5BB9\u4E0D\u662F\u6570\u7EC4");return d}catch{const d=new Date().toISOString().replace(/[:.]/g,"-");try{(0,external_fs_.copyFileSync)(SESSIONS_FILE,SESSIONS_FILE+".corrupt-"+d)}catch{}console.error(`[sessions] \u26A0 sessions.json \u635F\u574F\uFF08\u65AD\u7535\u6495\u88C2\u5199/\u88AB\u6539\u574F\uFF09\uFF0C\u5DF2\u7559\u8BC1 sessions.json.corrupt-${d}`);try{const l=JSON.parse((0,external_fs_.readFileSync)(SESSIONS_FILE+".bak","utf8"));if(Array.isArray(l)&&l.length)return console.log(`[sessions] \u2714 \u5DF2\u4ECE .bak \u6062\u590D ${l.length} \u6761\u4F1A\u8BDD\u914D\u7F6E`),l}catch{}return console.error("[sessions] \u26A0 \u65E0 .bak \u53EF\u6062\u590D\uFF0C\u672C\u6B21\u542F\u52A8\u4F1A\u8BDD\u5217\u8868\u4E3A\u7A7A\uFF08\u78C1\u76D8\u8BC1\u636E\u5DF2\u7559\u6863\uFF09"),[]}}function writeSavedConfigs(S){try{(0,external_fs_.mkdirSync)(sessions_CONFIG_DIR,{recursive:!0});try{const l=(0,external_fs_.readFileSync)(SESSIONS_FILE,"utf8").trim();(!S||!S.length)&&l&&l!=="[]"&&console.error(`[sessions] \u26A0 \u5373\u5C06\u7528\u7A7A\u5217\u8868\u8986\u76D6 ${l.length} \u5B57\u8282\u7684\u5B58\u91CF\u4F1A\u8BDD\u6570\u636E\uFF08\u82E5\u975E\u672C\u4EBA\u6E05\u7A7A\u4F1A\u8BDD\uFF0C\u7ACB\u5373\u505C\u6B62 myhi \u5E76\u627E\u56DE .bak\uFF09`)}catch{}try{(0,external_fs_.copyFileSync)(SESSIONS_FILE,SESSIONS_FILE+".bak")}catch{}const d=SESSIONS_FILE+".tmp";(0,external_fs_.writeFileSync)(d,JSON.stringify(S,null,2),{mode:384});try{(0,external_fs_.renameSync)(d,SESSIONS_FILE)}catch{(0,external_fs_.copyFileSync)(d,SESSIONS_FILE);try{(0,external_fs_.rmSync)(d,{force:!0})}catch{}}}catch(d){console.error("[sessions] \u6301\u4E45\u5316\u5199\u5165\u5931\u8D25:",d.message)}}class Session extends external_events_.EventEmitter{constructor(d,l={}){super(),this.id=d,this.createdAt=l.createdAt||new Date().toISOString(),this.title=l.title||DEFAULT_SHELL,this.cwd=l.cwd||process.env.MYHI_CWD||process.cwd(),this.tags=Array.isArray(l.tags)?l.tags:[],this.initCmd=l.initCmd||null,this.owner=l.owner||null,this.cols=l.cols||120,this.rows=l.rows||30,this._lastActivityAt=l.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,l.userDir){const o=(0,external_path_.join)(l.userDir,".gitconfig");(0,external_fs_.existsSync)(o)&&(n.GIT_CONFIG_GLOBAL=o)}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 e=100*1024;if(this._pty.onData((o=>{this.emit("data",o),this._scrollback+=o,this._scrollback.length>e&&(this._scrollback=this._scrollback.slice(this._scrollback.length-e))})),this._pty.onExit((({exitCode:o})=>{this.exitCode=o,this.emit("exit",o)})),l.initCmd){const o=l.initCmd;let u=!1;const h=c=>{!u&&/[$>#\]]\s*$/.test(c.trimEnd())&&(u=!0,this._pty.off("data",h),setTimeout((()=>this._pty.write(o+"\r")),120))};this._pty.onData(h),setTimeout((()=>{u||(u=!0,this._pty.write(o+"\r"))}),3e3)}}write(d){d!=null&&(this._lastActivityAt=Date.now(),this._pty.write(d))}resize(d,l){this.cols=d,this.rows=l,this._pty.resize(d,l)}kill(){try{this._pty.kill()}catch{}}addViewer(d,l){this._viewers.add(d),l&&this._viewerNames.set(d,l)}removeViewer(d){this._viewers.delete(d),this._viewerNames.delete(d)}get viewerCount(){return new Set(this._viewerNames.values()).size||this._viewers.size}takeControl(d,l){this.controlHolder=d,this.controlHolderName=l||null,this.lastInputTime=Date.now()}releaseControl(){this.controlHolder=null,this.controlHolderName=null,this.lastInputTime=null}isController(d){return this.controlHolder===d}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;const d=loadSavedConfigs();let l=0;for(const n of d)try{if(n.mode==="agent")if(n.claudeSessionId){const e=(0,external_crypto_.randomUUID)(),o=new AgentSession(e,{...n,resumeSessionId:n.claudeSessionId});o.on("session-id",(()=>this._persist())),this._agentSessions.set(e,o),l++,console.log(`[\u4F1A\u8BDD] \u6062\u590D Agent "${n.title}" (claude: ${n.claudeSessionId.slice(0,8)}...)`)}else console.warn(`[\u4F1A\u8BDD] \u8DF3\u8FC7 "${n.title}"\uFF1Aagent \u4F1A\u8BDD\u65E0 claudeSessionId\uFF08\u4ECE\u672A\u53D1\u8D77\u8FC7\u67E5\u8BE2\uFF09\uFF0C\u65E0\u6CD5\u6062\u590D`);else this._spawn((0,external_crypto_.randomUUID)(),n,!1),l++}catch(e){console.warn(`[\u4F1A\u8BDD] \u6062\u590D "${n.title}" \u5931\u8D25:`,e.message)}d.length&&!l&&console.error(`[\u4F1A\u8BDD] \u26A0 \u78C1\u76D8\u4E0A\u6709 ${d.length} \u6761\u4F1A\u8BDD\u914D\u7F6E\u4F46\u4E00\u6761\u90FD\u6CA1\u6062\u590D\u6210\u529F \u2014\u2014 \u68C0\u67E5\u4E0A\u65B9\u65E5\u5FD7\uFF1Bsessions.json.bak \u91CC\u6709\u4E00\u4EFD\u597D\u6570\u636E`)}_spawn(d,l,n=!0){const e=new Session(d,l);return this._sessions.set(d,e),e.on("exit",(()=>{setTimeout((()=>this._sessions.delete(d)),300*1e3)})),n&&this._persist(),e}create(d={}){return this._spawn((0,external_crypto_.randomUUID)(),d,!0)}createAgent(d={}){const l=(0,external_crypto_.randomUUID)(),n=new AgentSession(l,d);return this._agentSessions.set(l,n),n.on("session-id",(()=>this._persist())),this._persist(),n}get(d){return this._sessions.get(d)||this._agentSessions.get(d)}list(d,l=!1){let n=[...this._sessions.values()].map((o=>({...o.toJSON(),mode:"pty"}))),e=[...this._agentSessions.values()].map((o=>o.toJSON()));return d&&!l&&(n=n.filter((o=>!o.owner||o.owner===d)),e=e.filter((o=>!o.owner||o.owner===d))),[...n,...e]}listSessions(){return[...this._sessions.values(),...this._agentSessions.values()]}kill(d){const l=this._sessions.get(d);if(l){l.kill(),this._sessions.delete(d),this._persist();return}const n=this._agentSessions.get(d);n&&(n.kill(),this._agentSessions.delete(d),this._persist())}persist(){this._persist()}_persist(){const d=[...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}))),l=[...this._agentSessions.values()].filter((n=>n.alive)).map((n=>({mode:"agent",title:n.title,firstUserText:n.firstUserText||void 0,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([...d,...l])}}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 d=rolesConfig.passwords[S];return d?{name:d.name||"\u7528\u6237",role:d.role||"viewer"}:null}function hasPermission(S,d){return(ROLE_LEVELS[S]||0)>=(ROLE_LEVELS[d]||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 d=usersConfig.users[S];return d?{name:d.name||"\u7528\u6237",dir:d.dir}:null}function listUsers(){return usersConfig?.users?Object.entries(usersConfig.users).map((([S,d])=>({password:S.slice(0,2)+"*".repeat(S.length-2),name:d.name,dir:d.dir}))):[]}function addUser(S,d,l){usersConfig||(usersConfig={users:{}}),usersConfig.users||(usersConfig.users={}),usersConfig.users[S]={name:d,dir:l},_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"),d=(0,external_path_.join)(server_configDir,"key.pem");if((0,external_fs_.existsSync)(S)&&(0,external_fs_.existsSync)(d))try{return{cert:(0,external_fs_.readFileSync)(S),key:(0,external_fs_.readFileSync)(d)}}catch{}try{const l=selfsigned.generate([{name:"commonName",value:"myhi"}],{days:3650,keySize:2048});return(0,external_fs_.writeFileSync)(S,l.cert,"utf8"),(0,external_fs_.writeFileSync)(d,l.private,"utf8"),console.log("[myhi] \u81EA\u7B7E\u540D HTTPS \u8BC1\u4E66\u5DF2\u751F\u6210"),{cert:l.cert,key:l.private}}catch{}try{return(0,external_child_process_namespaceObject.execSync)(`openssl req -x509 -newkey rsa:2048 -keyout "${d}" -out "${S}" -days 3650 -nodes -subj "/CN=myhi"`,{stdio:"pipe",timeout:1e4}),{cert:(0,external_fs_.readFileSync)(S),key:(0,external_fs_.readFileSync)(d)}}catch(l){return console.warn(`[myhi] \u751F\u6210 HTTPS \u8BC1\u4E66\u5931\u8D25: ${l.message?.split(`
385
+ `).filter(Boolean);let r=null,p=null,f=0,s="";for(const m of t)try{const b=JSON.parse(m);if(r||(r=b),p=b,f++,!s&&b.type==="human"||b.type==="user"&&b.message?.content){const _=b.message.content;if(typeof _=="string")s=_.slice(0,120);else if(Array.isArray(_)){const g=_.find((w=>w.type==="text"));g&&(s=g.text?.slice(0,120)||"")}}}catch{}let v=u.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;l.push({sessionId:i,projectDir:u.name,projectPath:v,messageCount:f,summary:s,createdAt:r?.timestamp||null,updatedAt:p?.timestamp||null})}catch{}}}catch{}}}catch{}l.sort(((o,u)=>new Date(u.updatedAt||0).getTime()-new Date(o.updatedAt||0).getTime()));const e=l.slice(0,50);return _claudeSessionsCache=e,_claudeSessionsCacheTime=Date.now(),e.slice(0,20)}const DEFAULT_SHELL=process.platform==="win32"?process.env.SHELL||"powershell.exe":process.env.SHELL||"/bin/bash",sessions_CONFIG_DIR=(0,external_path_.join)((0,external_os_.homedir)(),".myhi"),SESSIONS_FILE=(0,external_path_.join)(sessions_CONFIG_DIR,"sessions.json"),savePath=null;function loadSavedConfigs(){let S;try{S=(0,external_fs_.readFileSync)(SESSIONS_FILE,"utf8")}catch{return[]}try{const d=JSON.parse(S);if(!Array.isArray(d))throw new Error("\u5185\u5BB9\u4E0D\u662F\u6570\u7EC4");return d}catch{const d=new Date().toISOString().replace(/[:.]/g,"-");try{(0,external_fs_.copyFileSync)(SESSIONS_FILE,SESSIONS_FILE+".corrupt-"+d)}catch{}console.error(`[sessions] \u26A0 sessions.json \u635F\u574F\uFF08\u65AD\u7535\u6495\u88C2\u5199/\u88AB\u6539\u574F\uFF09\uFF0C\u5DF2\u7559\u8BC1 sessions.json.corrupt-${d}`);try{const l=JSON.parse((0,external_fs_.readFileSync)(SESSIONS_FILE+".bak","utf8"));if(Array.isArray(l)&&l.length)return console.log(`[sessions] \u2714 \u5DF2\u4ECE .bak \u6062\u590D ${l.length} \u6761\u4F1A\u8BDD\u914D\u7F6E`),l}catch{}return console.error("[sessions] \u26A0 \u65E0 .bak \u53EF\u6062\u590D\uFF0C\u672C\u6B21\u542F\u52A8\u4F1A\u8BDD\u5217\u8868\u4E3A\u7A7A\uFF08\u78C1\u76D8\u8BC1\u636E\u5DF2\u7559\u6863\uFF09"),[]}}function writeSavedConfigs(S){try{(0,external_fs_.mkdirSync)(sessions_CONFIG_DIR,{recursive:!0});try{const l=(0,external_fs_.readFileSync)(SESSIONS_FILE,"utf8").trim();(!S||!S.length)&&l&&l!=="[]"&&console.error(`[sessions] \u26A0 \u5373\u5C06\u7528\u7A7A\u5217\u8868\u8986\u76D6 ${l.length} \u5B57\u8282\u7684\u5B58\u91CF\u4F1A\u8BDD\u6570\u636E\uFF08\u82E5\u975E\u672C\u4EBA\u6E05\u7A7A\u4F1A\u8BDD\uFF0C\u7ACB\u5373\u505C\u6B62 myhi \u5E76\u627E\u56DE .bak\uFF09`)}catch{}try{(0,external_fs_.copyFileSync)(SESSIONS_FILE,SESSIONS_FILE+".bak")}catch{}const d=SESSIONS_FILE+".tmp";(0,external_fs_.writeFileSync)(d,JSON.stringify(S,null,2),{mode:384});try{(0,external_fs_.renameSync)(d,SESSIONS_FILE)}catch{(0,external_fs_.copyFileSync)(d,SESSIONS_FILE);try{(0,external_fs_.rmSync)(d,{force:!0})}catch{}}}catch(d){console.error("[sessions] \u6301\u4E45\u5316\u5199\u5165\u5931\u8D25:",d.message)}}class Session extends external_events_.EventEmitter{constructor(d,l={}){super(),this.id=d,this.createdAt=l.createdAt||new Date().toISOString(),this.title=l.title||DEFAULT_SHELL,this.cwd=l.cwd||process.env.MYHI_CWD||process.cwd(),this.tags=Array.isArray(l.tags)?l.tags:[],this.initCmd=l.initCmd||null,this.owner=l.owner||null,this.cols=l.cols||120,this.rows=l.rows||30,this._lastActivityAt=l.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,l.userDir){const o=(0,external_path_.join)(l.userDir,".gitconfig");(0,external_fs_.existsSync)(o)&&(n.GIT_CONFIG_GLOBAL=o)}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 e=100*1024;if(this._pty.onData((o=>{this.emit("data",o),this._scrollback+=o,this._scrollback.length>e&&(this._scrollback=this._scrollback.slice(this._scrollback.length-e))})),this._pty.onExit((({exitCode:o})=>{this.exitCode=o,this.emit("exit",o)})),l.initCmd){const o=l.initCmd;let u=!1;const h=c=>{!u&&/[$>#\]]\s*$/.test(c.trimEnd())&&(u=!0,this._pty.off("data",h),setTimeout((()=>this._pty.write(o+"\r")),120))};this._pty.onData(h),setTimeout((()=>{u||(u=!0,this._pty.write(o+"\r"))}),3e3)}}write(d){d!=null&&(this._lastActivityAt=Date.now(),this._pty.write(d))}resize(d,l){this.cols=d,this.rows=l,this._pty.resize(d,l)}kill(){try{this._pty.kill()}catch{}}addViewer(d,l){this._viewers.add(d),l&&this._viewerNames.set(d,l)}removeViewer(d){this._viewers.delete(d),this._viewerNames.delete(d)}get viewerCount(){return new Set(this._viewerNames.values()).size||this._viewers.size}takeControl(d,l){this.controlHolder=d,this.controlHolderName=l||null,this.lastInputTime=Date.now()}releaseControl(){this.controlHolder=null,this.controlHolderName=null,this.lastInputTime=null}isController(d){return this.controlHolder===d}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;const d=loadSavedConfigs();let l=0;for(const n of d)try{if(n.mode==="agent"){const e=(0,external_crypto_.randomUUID)(),o=new AgentSession(e,{...n,resumeSessionId:n.claudeSessionId});o.on("session-id",(()=>this._persist())),this._agentSessions.set(e,o),l++,console.log(n.claudeSessionId?`[\u4F1A\u8BDD] \u6062\u590D Agent "${n.title}" (claude: ${n.claudeSessionId.slice(0,8)}...)`:`[\u4F1A\u8BDD] \u6062\u590D Agent "${n.title}" (\u65B0\u4E0A\u4E0B\u6587\u2014\u2014\u6B64\u524D\u5DF2\u6E05\u9664/\u672A\u53D1\u8D77\u8FC7\u67E5\u8BE2)`)}else this._spawn((0,external_crypto_.randomUUID)(),n,!1),l++}catch(e){console.warn(`[\u4F1A\u8BDD] \u6062\u590D "${n.title}" \u5931\u8D25:`,e.message)}d.length&&!l&&console.error(`[\u4F1A\u8BDD] \u26A0 \u78C1\u76D8\u4E0A\u6709 ${d.length} \u6761\u4F1A\u8BDD\u914D\u7F6E\u4F46\u4E00\u6761\u90FD\u6CA1\u6062\u590D\u6210\u529F \u2014\u2014 \u68C0\u67E5\u4E0A\u65B9\u65E5\u5FD7\uFF1Bsessions.json.bak \u91CC\u6709\u4E00\u4EFD\u597D\u6570\u636E`)}_spawn(d,l,n=!0){const e=new Session(d,l);return this._sessions.set(d,e),e.on("exit",(()=>{setTimeout((()=>this._sessions.delete(d)),300*1e3)})),n&&this._persist(),e}create(d={}){return this._spawn((0,external_crypto_.randomUUID)(),d,!0)}createAgent(d={}){const l=(0,external_crypto_.randomUUID)(),n=new AgentSession(l,d);return this._agentSessions.set(l,n),n.on("session-id",(()=>this._persist())),this._persist(),n}get(d){return this._sessions.get(d)||this._agentSessions.get(d)}list(d,l=!1){let n=[...this._sessions.values()].map((o=>({...o.toJSON(),mode:"pty"}))),e=[...this._agentSessions.values()].map((o=>o.toJSON()));return d&&!l&&(n=n.filter((o=>!o.owner||o.owner===d)),e=e.filter((o=>!o.owner||o.owner===d))),[...n,...e]}listSessions(){return[...this._sessions.values(),...this._agentSessions.values()]}kill(d){const l=this._sessions.get(d);if(l){l.kill(),this._sessions.delete(d),this._persist();return}const n=this._agentSessions.get(d);n&&(n.kill(),this._agentSessions.delete(d),this._persist())}persist(){this._persist()}_persist(){const d=[...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}))),l=[...this._agentSessions.values()].filter((n=>n.alive)).map((n=>({mode:"agent",title:n.title,firstUserText:n.firstUserText||void 0,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([...d,...l])}}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 d=rolesConfig.passwords[S];return d?{name:d.name||"\u7528\u6237",role:d.role||"viewer"}:null}function hasPermission(S,d){return(ROLE_LEVELS[S]||0)>=(ROLE_LEVELS[d]||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 d=usersConfig.users[S];return d?{name:d.name||"\u7528\u6237",dir:d.dir}:null}function listUsers(){return usersConfig?.users?Object.entries(usersConfig.users).map((([S,d])=>({password:S.slice(0,2)+"*".repeat(S.length-2),name:d.name,dir:d.dir}))):[]}function addUser(S,d,l){usersConfig||(usersConfig={users:{}}),usersConfig.users||(usersConfig.users={}),usersConfig.users[S]={name:d,dir:l},_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"),d=(0,external_path_.join)(server_configDir,"key.pem");if((0,external_fs_.existsSync)(S)&&(0,external_fs_.existsSync)(d))try{return{cert:(0,external_fs_.readFileSync)(S),key:(0,external_fs_.readFileSync)(d)}}catch{}try{const l=selfsigned.generate([{name:"commonName",value:"myhi"}],{days:3650,keySize:2048});return(0,external_fs_.writeFileSync)(S,l.cert,"utf8"),(0,external_fs_.writeFileSync)(d,l.private,"utf8"),console.log("[myhi] \u81EA\u7B7E\u540D HTTPS \u8BC1\u4E66\u5DF2\u751F\u6210"),{cert:l.cert,key:l.private}}catch{}try{return(0,external_child_process_namespaceObject.execSync)(`openssl req -x509 -newkey rsa:2048 -keyout "${d}" -out "${S}" -days 3650 -nodes -subj "/CN=myhi"`,{stdio:"pipe",timeout:1e4}),{cert:(0,external_fs_.readFileSync)(S),key:(0,external_fs_.readFileSync)(d)}}catch(l){return console.warn(`[myhi] \u751F\u6210 HTTPS \u8BC1\u4E66\u5931\u8D25: ${l.message?.split(`
386
386
  `)[0]||l}`),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,d){let l=!1;try{process.kill(S,0),l=!0}catch{}if(!l)return!0;console.log(`[myhi] \u68C0\u6D4B\u5230\u5DF2\u8FD0\u884C\u7684${d} (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 o=Date.now()+200;for(;Date.now()<o;);}let e=!1;try{process.kill(S,0),e=!0}catch{}return!e}(function S(){try{const d=parseInt((0,external_fs_.readFileSync)(daemonPidFile,"utf8").trim(),10);if(d&&d!==process.pid&&d!==parseInt(process.env.MYHI_DAEMON_PID||"0",10)){let l=!1;try{process.kill(d,0),l=!0}catch{}if(l&&!IS_DAEMON_CHILD){console.log("[myhi] \u68C0\u6D4B\u5230\u540E\u53F0 daemon \u5728\u8FD0\u884C\uFF0C\u5148\u505C\u6B62..."),killOldProcess(d,"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 d=parseInt((0,external_fs_.readFileSync)(pidFile,"utf8").trim(),10);d&&d!==process.pid&&(killOldProcess(d,"\u5B9E\u4F8B")||(console.error(`[myhi] \u65E0\u6CD5\u505C\u6B62\u65E7\u8FDB\u7A0B (PID ${d})\uFF0C\u8BF7\u624B\u52A8\u6267\u884C\uFF1A`),console.error(" myhi stop"),console.error(` \u6216: ${process.platform==="win32"?`taskkill /PID ${d} /F`:`kill -9 ${d}`}`),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)}));const RECOVERABLE_ERRNO=new Set(["ECONNRESET","EPIPE","ECONNABORTED","ETIMEDOUT","ENOENT","EBUSY","EACCES","EPERM","EISDIR","ERR_STREAM_PREMATURE_CLOSE","ERR_STREAM_DESTROYED","ERR_HTTP_HEADERS_SENT"]);process.on("uncaughtException",(S=>{if(RECOVERABLE_ERRNO.has(S?.code)){console.error(`[myhi] \u5DF2\u5FFD\u7565\u53EF\u6062\u590D\u5F02\u5E38(${S.code}):`,S.message);return}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,d){try{if((0,external_fs_.existsSync)(S))return(0,external_fs_.readFileSync)(S,"utf8").trim()}catch{}const l=d();return(0,external_fs_.writeFileSync)(S,l,{mode:384}),l}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[d,l]of userSessions)l.permanent||(!l.lastUsed||S-l.lastUsed>SESSION_MAX_AGE)&&userSessions.delete(d)}),3600*1e3);function getTailscaleIP(){try{return(0,external_child_process_namespaceObject.execSync)("tailscale ip -4",{timeout:3e3,stdio:"pipe"}).toString().trim().split(`
387
387
  `)[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(),d=S.match(/interface:\s*(\S+)/i)||S.match(/0\.0\.0\.0\s+(\d+\.\d+\.\d+\.\d+)/);if(d){const l=(0,external_os_.networkInterfaces)()[d[1]];if(l){const n=l.find((e=>e.family==="IPv4"&&!e.internal));if(n)return n.address}if(/^\d+\.\d+\.\d+\.\d+$/.test(d[1]))return d[1]}}}catch{}for(const S of Object.values((0,external_os_.networkInterfaces)()))for(const d of S)if(d.family==="IPv4"&&!d.internal)return d.address;return"localhost"}function parseCookies(S=""){const d={};for(const l of S.split(";")){const n=l.indexOf("=");n>0&&(d[l.slice(0,n).trim()]=l.slice(n+1).trim())}return d}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,d,l){S.setHeader("Set-Cookie",`${SESSION_COOKIE}=${d||TOKEN}; ${cookieOpts(l)}`)}function getSessionToken(S){return parseCookies(S)[SESSION_COOKIE]||null}function hasValidSession(S){const d=getSessionToken(S);if(d&&userSessions.has(d)){const l=userSessions.get(d);return l&&(l.lastUsed=Date.now()),!0}return!1}function getUserInfo(S){const d=getSessionToken(S);return d?userSessions.get(d):null}const app=express();app.set("trust proxy",!0),app.use(((S,d,l)=>{d.setHeader("Referrer-Policy","no-referrer"),d.setHeader("X-Content-Type-Options","nosniff"),l()}));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,d)=>{const l=(S.headers.host||"").replace(/:\d+$/,"");d.writeHead(301,{Location:`https://${l}:${PORT}${S.url}`}),d.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,d)=>{if(!S||_corsAllowed.test(S))return d(null,!0);d(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,d){if(!AUTO_ATTACH||_autoSpawned.has(S)||!process.env.DISPLAY&&process.platform==="linux")return;_autoSpawned.add(S);const l=__nccwpck_require__.ab+"attach.js",n=process.execPath,e=d||"myhi";if(process.platform==="win32"){const o=`"${n}" "${l}" ${S}`,u=(0,external_child_process_namespaceObject.spawn)("wt.exe",["-w","0","new-tab","--title",e,"--","cmd","/k",o],{detached:!0,stdio:"ignore"});u.unref(),u.on("error",(h=>{console.warn("[attach] wt.exe \u5931\u8D25\uFF0C\u56DE\u9000\u5230 cmd:",h.message),(0,external_child_process_namespaceObject.spawn)("cmd.exe",["/c","start",`"${e}"`,"cmd","/k",o],{detached:!0,stdio:"ignore"}).unref()}))}else if(process.platform==="darwin"){const o=`tell application "Terminal" to do script "${n} ${l} ${S}"`;(0,external_child_process_namespaceObject.spawn)("osascript",["-e",o],{detached:!0,stdio:"ignore"}).unref()}else{const o=`${n} "${l}" ${S}`;for(const[u,h]of[["gnome-terminal",["--","bash","-c",`${o}; exec bash`]],["xterm",["-title",e,"-e",o]],["konsole",["--new-tab","-e",o]]]){const c=(0,external_child_process_namespaceObject.spawn)(u,h,{detached:!0,stdio:"ignore"});c.unref(),c.on("error",(()=>{}));break}}}const uploadDir=(0,external_path_.join)(server_configDir,"uploads");(0,external_fs_.mkdirSync)(uploadDir,{recursive:!0});function checkAuth(S,d,l){const n=S.query.token;if(n&&(n===TOKEN||userSessions.has(n))){const e=userSessions.get(n);if(e?.onetime){userSessions.delete(n);const h=(0,external_crypto_.randomBytes)(16).toString("hex");userSessions.set(h,{role:e.role,name:e.name,lastUsed:Date.now()}),setSessionCookie(d,h,S)}else setSessionCookie(d,n===TOKEN?TOKEN:n,S);const o=Object.keys(S.query).filter((h=>h!=="token")),u=S.path+(o.length?"?"+new URLSearchParams(Object.fromEntries(Object.entries(S.query).filter((([h])=>h!=="token")))):"");return d.redirect(u)}if(hasValidSession(S.headers.cookie)){if(isExclusiveMode()&&activeUser){const e=getSessionToken(S.headers.cookie);if(e!==TOKEN){const o=userSessions.get(e);if(!o||o.name!==activeUser.name)return d.setHeader("Set-Cookie",`${SESSION_COOKIE}=; HttpOnly; SameSite=Strict; Path=/; Max-Age=0`),d.redirect("/login")}}return l()}d.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,d)=>{d.endsWith(".js")&&S.setHeader("Content-Type","application/javascript; charset=utf-8")}})),app.get("/manifest.json",((S,d)=>d.sendFile((0,external_path_.join)(server_dirname,"manifest.json")))),app.get("/icon.png",((S,d)=>d.sendFile((0,external_path_.join)(server_dirname,"icon.png")))),app.get("/icon.svg",((S,d)=>d.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 d=Date.now(),l=_loginAttempts.get(S);return!l||d>l.resetAt?!0:l.count<LOGIN_MAX_ATTEMPTS}function recordLoginFailure(S){const d=Date.now(),l=_loginAttempts.get(S);!l||d>l.resetAt?_loginAttempts.set(S,{count:1,resetAt:d+LOGIN_LOCKOUT_MS}):l.count++}function clearLoginFailures(S){_loginAttempts.delete(S)}setInterval((()=>{const S=Date.now();for(const[d,l]of _loginAttempts)S>l.resetAt&&_loginAttempts.delete(d)}),600*1e3),app.get("/login",((S,d)=>{d.sendFile((0,external_path_.join)(server_dirname,"login.html"))})),app.post("/login",express.urlencoded({extended:!1}),((S,d)=>{const l=S.ip;if(!checkLoginRate(l))return d.redirect("/login?error=locked");loadRoles(),loadUsers();const n=S.body?.password,e=S.query.from,o=e&&e.startsWith("/")&&!e.startsWith("//")?e:"/";if(hasUsers()){const h=lookupUser(n);if(!h)return recordLoginFailure(l),d.redirect("/login?error=1");if(isExclusiveMode()&&activeUser&&activeUser.name!==h.name)return d.redirect("/login?error=occupied&user="+encodeURIComponent(activeUser.name));clearLoginFailures(l);const c=(0,external_crypto_.randomBytes)(16).toString("hex");return userSessions.set(c,{role:"operator",name:h.name,dir:h.dir,lastUsed:Date.now()}),isExclusiveMode()&&(activeUser?activeUser.tokens.add(c):activeUser={name:h.name,dir:h.dir,tokens:new Set([c]),loginAt:Date.now()}),setSessionCookie(d,c,S),console.log(`[\u767B\u5F55] ${h.name} \u767B\u5F55\uFF08${isExclusiveMode()?"\u72EC\u5360":"\u5171\u4EAB"}\u6A21\u5F0F\uFF09`),d.redirect(o)}const u=lookupPassword(n);if(u){clearLoginFailures(l);const h=(0,external_crypto_.randomBytes)(16).toString("hex");return userSessions.set(h,{role:u.role,name:u.name,lastUsed:Date.now()}),setSessionCookie(d,h,S),d.redirect(o)}if(n===PASSWORD){clearLoginFailures(l);const h=(0,external_crypto_.randomBytes)(16).toString("hex");return userSessions.set(h,{role:"admin",name:"\u7BA1\u7406\u5458",lastUsed:Date.now()}),setSessionCookie(d,h,S),d.redirect(o)}recordLoginFailure(l),d.redirect("/login?error=1")})),app.post("/logout",((S,d)=>{const l=getSessionToken(S.headers.cookie);l&&(activeUser&&activeUser.tokens.has(l)&&(activeUser.tokens.delete(l),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(l)),d.setHeader("Set-Cookie",`${SESSION_COOKIE}=; HttpOnly; SameSite=Strict; Path=/; Max-Age=0`),d.redirect("/login")})),app.get("/api/status",((S,d)=>{if(isExclusiveMode()&&activeUser)return d.json({occupied:!0,userName:activeUser.name,releasing:!!_exclusiveReleaseTimer});if(hasUsers()&&!isExclusiveMode()){const l=new Set;for(const[,n]of io.sockets.sockets){if(!n.data.userName||n.data.userName==="\u7BA1\u7406\u5458")continue;const e=n.handshake.headers.cookie;e&&!hasValidSession(e)||l.add(n.data.userName)}return d.json({occupied:!1,onlineUsers:[...l]})}d.json({occupied:!1})})),app.get("/admin",((S,d)=>d.sendFile((0,external_path_.join)(server_dirname,"admin.html")))),app.get("/",checkAuth,((S,d)=>d.sendFile((0,external_path_.join)(server_dirname,"index.html")))),app.get("/terminal/:id",checkAuth,((S,d)=>d.sendFile((0,external_path_.join)(server_dirname,"chat.html")))),app.get("/grid",checkAuth,((S,d)=>d.sendFile((0,external_path_.join)(server_dirname,"grid.html")))),app.get("/terminal-raw/:id",checkAuth,((S,d)=>d.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,d)=>{const l=getUserInfo(S.headers.cookie);d.json(manager.list(l?.name,l?.role==="admin"))})),app.get("/api/usage",((S,d)=>{try{const l=manager.listSessions().filter((e=>e.mode==="agent"&&e.alive)).map((e=>({id:e.id,title:e.title,owner:e.owner,usage:e._usage})));let n=null;for(const e of l)if(e.usage?.rateLimitInfo){n=e.usage.rateLimitInfo;break}d.json({rateLimit:n,activeSessions:l})}catch(l){d.status(500).json({error:l.message})}})),app.post("/api/sessions",checkAuth,express.json(),((S,d)=>{const l=getUserInfo(S.headers.cookie),n=manager.create({...S.body,owner:l?.name,userDir:l?.dir});d.status(201).json(n.toJSON())})),app.delete("/api/sessions/:id",checkAuth,((S,d)=>{manager.kill(S.params.id),d.status(204).end()})),app.get("/api/sessions/health",checkAuth,((S,d)=>{const l=getUserInfo(S.headers.cookie),n=manager.listSessions().filter((e=>e.mode==="agent")).filter((e=>!e.owner||!l?.name||e.owner===l.name)).map((e=>({...e.toJSON(),health:getSessionHealth(e.claudeSessionId)})));d.json({ok:!0,sessions:n})})),app.post("/api/sessions/:id/reset",checkAuth,((S,d)=>{const l=manager.get(S.params.id);if(!l||l.mode!=="agent"||typeof l.reset!="function")return d.status(404).json({ok:!1,error:"agent \u4F1A\u8BDD\u4E0D\u5B58\u5728"});l.reset(),l.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(),d.json({ok:!0})})),app.get("/api/claude-sessions",checkAuth,((S,d)=>{const l=getUserInfo(S.headers.cookie);d.json(listLocalClaudeSessions(l?.dir))})),app.get("/api/agent/history/:sessionId",checkAuth,((S,d)=>{const l=manager.get(S.params.sessionId);if(!l||l.mode!=="agent")return d.status(404).json({ok:!1,error:"\u4F1A\u8BDD\u4E0D\u5B58\u5728"});const n=l.claudeSessionId;if(!n)return d.json({ok:!0,messages:[],total:0,hasMore:!1});const e=(0,external_path_.join)((0,external_os_.homedir)(),".claude","projects");let o=null;try{if((0,external_fs_.existsSync)(e))for(const p of(0,external_fs_.readdirSync)(e,{withFileTypes:!0})){if(!p.isDirectory())continue;const f=(0,external_path_.join)(e,p.name,n+".jsonl");if((0,external_fs_.existsSync)(f)){o=f;break}}}catch{}if(!o)return d.json({ok:!0,messages:[],total:0,hasMore:!1});let u;try{u=(0,external_fs_.readFileSync)(o,"utf8").split(`
388
388
  `).filter(Boolean)}catch(p){return d.status(500).json({ok:!1,error:p.message})}const h=Math.max(0,parseInt(S.query.offset,10)||0),c=Math.min(200,Math.max(1,parseInt(S.query.limit,10)||50)),i=u.length,a=i-h,t=Math.max(0,a-c),r=[];for(let p=t;p<a;p++)try{const f=JSON.parse(u[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{}d.json({ok:!0,messages:r,total:i,hasMore:t>0})})),app.get("/api/dirs",checkAuth,((S,d)=>{const l=getUserInfo(S.headers.cookie);if(!l||l.role!=="admin")return d.status(403).json({error:"\u6CA1\u6709\u76EE\u5F55\u6D4F\u89C8\u6743\u9650"});const n=l.dir?(0,external_path_.resolve)((0,external_path_.normalize)(l.dir)):null,e=process.platform==="win32"?"\\":"/";let o=S.query.path||n||process.env.MYHI_CWD||(0,external_os_.homedir)(),u=(0,external_path_.resolve)((0,external_path_.normalize)(o)).replace(/[/\\]+$/,"");process.platform==="win32"&&/^[A-Za-z]:$/.test(u)&&(u+="\\"),n&&!u.startsWith(n)&&(u=n);try{const h=(0,external_fs_.readdirSync)(u,{withFileTypes:!0}).filter((a=>a.isDirectory()&&a.name!==".git")).map((a=>({name:a.name,path:u.replace(/[/\\]+$/,"")+e+a.name}))).sort(((a,t)=>a.name.localeCompare(t.name))),c=(0,external_path_.join)(u,".."),i=!n||(0,external_path_.resolve)((0,external_path_.normalize)(c)).startsWith(n);d.json({current:u,parent:i&&c!==u?c:null,dirs:h})}catch(h){d.status(400).json({error:h.message})}}));function safePath(S,d){const l=(0,external_path_.resolve)((0,external_path_.normalize)(S)),n=(0,external_path_.resolve)((0,external_path_.normalize)((0,external_path_.join)(S,d||"")));if(n!==l&&!n.startsWith(l+external_path_.sep))return null;try{const e=(0,external_fs_.realpathSync)(l),o=(0,external_fs_.existsSync)(n)?(0,external_fs_.realpathSync)(n):n;if(o!==e&&!o.startsWith(e+external_path_.sep))return null}catch{}return n}function walkFiles(S,d,l=[],n=0){if(n>20)return l;let e;try{e=(0,external_fs_.readdirSync)(S,{withFileTypes:!0})}catch{return l}for(const o of e){if(o.name===".git")continue;const u=(0,external_path_.join)(S,o.name),h=d?d+"/"+o.name:o.name;try{const c=(0,external_fs_.lstatSync)(u);if(c.isSymbolicLink())continue;c.isDirectory()?walkFiles(u,h,l,n+1):c.isFile()&&l.push({name:h,size:c.size,mtime:c.mtimeMs})}catch{}}return l}function fileHash(S){return new Promise(((d,l)=>{const n=(0,external_crypto_.createHash)("sha256"),e=(0,external_fs_.createReadStream)(S);e.on("data",(o=>n.update(o))),e.on("end",(()=>d(n.digest("hex")))),e.on("error",l)}))}app.get("/api/files/:sessionId",checkAuth,((S,d)=>{const l=manager.get(S.params.sessionId);if(!l)return d.status(404).json({error:"\u4F1A\u8BDD\u4E0D\u5B58\u5728"});const n=S.query.path||"",e=safePath(l.cwd,n);if(!e)return d.status(403).json({error:"\u8DEF\u5F84\u8D8A\u754C"});try{if(!(0,external_fs_.statSync)(e).isDirectory())return d.status(400).json({error:"\u4E0D\u662F\u76EE\u5F55"});const o=(0,external_fs_.readdirSync)(e,{withFileTypes:!0}).filter((c=>c.name!==".git")).map((c=>{const i=(0,external_path_.join)(e,c.name);try{const a=(0,external_fs_.lstatSync)(i);return a.isSymbolicLink()?null:{name:c.name,isDir:a.isDirectory(),size:a.isFile()?a.size:void 0,mtime:a.mtimeMs}}catch{return null}})).filter(Boolean).sort(((c,i)=>i.isDir-c.isDir||c.name.localeCompare(i.name))),u=n?n.replace(/\\/g,"/"):"",h=u.includes("/")?u.slice(0,u.lastIndexOf("/")):u?"":null;d.json({ok:!0,cwd:l.cwd,path:u,parent:h,entries:o})}catch(o){d.status(500).json({error:o.message})}})),app.get("/api/files/:sessionId/download",checkAuth,((S,d)=>{const l=manager.get(S.params.sessionId);if(!l)return d.status(404).json({error:"\u4F1A\u8BDD\u4E0D\u5B58\u5728"});const n=S.query.path;if(!n)return d.status(400).json({error:"\u7F3A\u5C11 path \u53C2\u6570"});const e=safePath(l.cwd,n);if(!e)return d.status(403).json({error:"\u8DEF\u5F84\u8D8A\u754C"});let o;try{o=(0,external_fs_.statSync)(e)}catch{return d.status(404).json({error:"\u6587\u4EF6\u4E0D\u5B58\u5728"})}if(!o.isFile())return d.status(400).json({error:"\u4E0D\u662F\u6587\u4EF6"});const u=n.split("/").pop();d.setHeader("Content-Disposition",`attachment; filename*=UTF-8''${encodeURIComponent(u)}`),d.sendFile(e,{dotfiles:"allow",acceptRanges:!0},(h=>{if(!h)return;const c=h.code||"";["ECONNABORTED","EPIPE","ECONNRESET"].includes(c)||d.writableEnded||(console.warn("[files] \u4E0B\u8F7D\u5931\u8D25:",n,c||h.message),d.headersSent?d.destroy():d.status(500).json({error:"\u8BFB\u53D6\u6587\u4EF6\u5931\u8D25: "+(c||h.message)}))}))})),app.post("/api/files/:sessionId/upload",checkAuth,((S,d)=>{const l=manager.get(S.params.sessionId);if(!l)return d.status(404).json({error:"\u4F1A\u8BDD\u4E0D\u5B58\u5728"});const n=(S.query.path||"").replace(/\\/g,"/"),e=safePath(l.cwd,n);if(!e)return d.status(403).json({error:"\u8DEF\u5F84\u8D8A\u754C"});(0,external_fs_.mkdirSync)(e,{recursive:!0}),multer({storage:multer.diskStorage({destination:(o,u,h)=>{u.originalname=Buffer.from(u.originalname,"latin1").toString("utf8");const c=u.originalname.includes("/")?u.originalname.slice(0,u.originalname.lastIndexOf("/")):"",i=c?(0,external_path_.join)(e,c):e,a=(0,external_path_.resolve)((0,external_path_.normalize)(i)),t=(0,external_path_.resolve)((0,external_path_.normalize)(l.cwd));if(a!==t&&!a.startsWith(t+external_path_.sep))return h(new Error("\u8DEF\u5F84\u8D8A\u754C"));(0,external_fs_.mkdirSync)(i,{recursive:!0}),h(null,i)},filename:(o,u,h)=>{const c=u.originalname.includes("/")?u.originalname.slice(u.originalname.lastIndexOf("/")+1):u.originalname;h(null,c)}}),limits:{fileSize:500*1024*1024}}).array("files",100)(S,d,(o=>{if(o)return d.status(400).json({error:o.message});if(!S.files?.length)return d.status(400).json({error:"\u6CA1\u6709\u6587\u4EF6"});const u=S.files.map((h=>({name:h.originalname,size:h.size,path:(0,external_path_.resolve)(h.path).replace(/\\/g,"/")})));io.emit("files:changed",{sessionId:l.id}),d.json({ok:!0,files:u})}))})),app.delete("/api/files/:sessionId",checkAuth,((S,d)=>{const l=manager.get(S.params.sessionId);if(!l)return d.status(404).json({error:"\u4F1A\u8BDD\u4E0D\u5B58\u5728"});const n=S.query.path;if(!n)return d.status(400).json({error:"\u7F3A\u5C11 path \u53C2\u6570"});const e=safePath(l.cwd,n);if(!e)return d.status(403).json({error:"\u8DEF\u5F84\u8D8A\u754C"});if((0,external_path_.resolve)((0,external_path_.normalize)(e))===(0,external_path_.resolve)((0,external_path_.normalize)(l.cwd)))return d.status(403).json({error:"\u4E0D\u80FD\u5220\u9664\u4F1A\u8BDD\u6839\u76EE\u5F55"});try{(0,external_fs_.statSync)(e).isDirectory()?(0,external_fs_.rmSync)(e,{recursive:!0}):(0,external_fs_.unlinkSync)(e),io.emit("files:changed",{sessionId:l.id}),d.json({ok:!0})}catch(o){d.status(500).json({error:o.message})}})),app.get("/api/files/:sessionId/manifest",checkAuth,(async(S,d)=>{const l=manager.get(S.params.sessionId);if(!l)return d.status(404).json({error:"\u4F1A\u8BDD\u4E0D\u5B58\u5728"});const n=S.query.path||"",e=safePath(l.cwd,n);if(!e)return d.status(403).json({error:"\u8DEF\u5F84\u8D8A\u754C"});try{const o=walkFiles(e,""),u=[];for(const h of o){if(h.size>=50*1024*1024){u.push(h);continue}try{const c=await fileHash((0,external_path_.join)(e,h.name));u.push({...h,hash:c})}catch{u.push(h)}}d.json({ok:!0,cwd:l.cwd,path:n,files:u})}catch(o){d.status(500).json({error:o.message})}}));const EDITABLE_EXTS=new Set(["md","markdown","txt","log","json","jsonc","json5","yml","yaml","toml","ini","cfg","conf","env","properties","editorconfig","csv","tsv","xml","svg","html","htm","css","scss","less","js","mjs","cjs","jsx","ts","mts","cts","tsx","vue","svelte","py","pyi","sh","bash","zsh","ps1","psm1","bat","cmd","sql","java","kt","kts","groovy","gradle","c","h","cpp","hpp","cc","cxx","cs","go","rs","rb","php","swift","lua","dart","proto","graphql","cmake","dockerfile","gitignore"]),EDIT_MAX_BYTES=2*1024*1024;function normRelPath(S){return String(S||"").replace(/\\/g,"/").replace(/^\/+/,"")}function editableTarget(S,d){const l=normRelPath(d);if(!l)return{error:"\u7F3A\u5C11 path",code:400};const n=safePath(S.cwd,l);if(!n)return{error:"\u8DEF\u5F84\u8D8A\u754C",code:403};const e=(l.split("/").pop().match(/\.([A-Za-z0-9]+)$/)||[])[1]?.toLowerCase()||"";return EDITABLE_EXTS.has(e)?{rel:l,target:n}:{error:"\u8BE5\u7C7B\u578B\u6587\u4EF6\u4E0D\u652F\u6301\u5728\u7EBF\u7F16\u8F91\uFF0C\u8BF7\u7528\u4E0B\u8F7D",code:415}}function looksBinary(S){const d=Math.min(S.length,8192);for(let l=0;l<d;l++)if(S[l]===0)return!0;return!1}app.get("/api/files/:sessionId/content",checkAuth,((S,d)=>{const l=manager.get(S.params.sessionId);if(!l)return d.status(404).json({error:"\u4F1A\u8BDD\u4E0D\u5B58\u5728"});const n=editableTarget(l,S.query.path);if(n.error)return d.status(n.code).json({error:n.error});let e;try{e=(0,external_fs_.statSync)(n.target)}catch{return d.status(404).json({error:"\u6587\u4EF6\u4E0D\u5B58\u5728"})}if(!e.isFile())return d.status(400).json({error:"\u4E0D\u662F\u6587\u4EF6"});if(e.size>EDIT_MAX_BYTES)return d.status(413).json({error:"\u6587\u4EF6\u8D85\u8FC7 2MB\uFF0C\u4EC5\u652F\u6301\u4E0B\u8F7D"});let o;try{o=(0,external_fs_.readFileSync)(n.target)}catch(u){return d.status(500).json({error:"\u8BFB\u53D6\u5931\u8D25: "+(u.code||u.message)})}if(looksBinary(o))return d.status(415).json({error:"\u4E8C\u8FDB\u5236\u6587\u4EF6\uFF0C\u4EC5\u652F\u6301\u4E0B\u8F7D"});d.json({ok:!0,path:n.rel,name:n.rel.split("/").pop(),content:o.toString("utf8"),mtime:e.mtimeMs,size:e.size,md:/\.(md|markdown)$/i.test(n.rel)})})),app.put("/api/files/:sessionId/content",checkAuth,express.json({limit:"4mb"}),((S,d)=>{const l=manager.get(S.params.sessionId);if(!l)return d.status(404).json({error:"\u4F1A\u8BDD\u4E0D\u5B58\u5728"});const{content:n,baseMtime:e,force:o}=S.body||{};if(typeof n!="string")return d.status(400).json({error:"\u7F3A\u5C11\u5185\u5BB9"});if(Buffer.byteLength(n,"utf8")>EDIT_MAX_BYTES)return d.status(413).json({error:"\u5185\u5BB9\u8D85\u8FC7 2MB"});const u=editableTarget(l,S.body.path);if(u.error)return d.status(u.code).json({error:u.error});let h;try{h=(0,external_fs_.statSync)(u.target)}catch{return d.status(404).json({error:"\u6587\u4EF6\u5DF2\u88AB\u5220\u9664\uFF0C\u65E0\u6CD5\u4FDD\u5B58"})}if(!h.isFile())return d.status(400).json({error:"\u4E0D\u662F\u6587\u4EF6"});if(!o&&typeof e=="number"&&Math.abs(h.mtimeMs-e)>300)return d.status(409).json({error:"conflict",mtime:h.mtimeMs});const c=u.target+".myhi-edit-"+Date.now();try{try{(0,external_fs_.writeFileSync)(c,n,"utf8"),(0,external_fs_.renameSync)(c,u.target)}catch{try{(0,external_fs_.rmSync)(c,{force:!0})}catch{}(0,external_fs_.writeFileSync)(u.target,n,"utf8")}}catch(a){const t=["EBUSY","EPERM","EACCES"].includes(a.code);return console.warn("[files] \u4FDD\u5B58\u5931\u8D25:",u.rel,a.code||a.message),d.status(500).json({error:t?"\u6587\u4EF6\u88AB\u5176\u5B83\u7A0B\u5E8F\u5360\u7528\uFF08AI \u53EF\u80FD\u6B63\u5728\u5199\u5165\uFF09\uFF0C\u7A0D\u540E\u518D\u8BD5":"\u4FDD\u5B58\u5931\u8D25: "+(a.code||a.message)})}let i=Date.now();try{i=(0,external_fs_.statSync)(u.target).mtimeMs}catch{}io.emit("files:changed",{sessionId:l.id}),d.json({ok:!0,mtime:i})})),app.get("/api/me",checkAuth,((S,d)=>{const l=getUserInfo(S.headers.cookie);d.json({name:l?.name||"\u7528\u6237",role:l?.role||"admin",exclusive:isExclusiveMode(),hasUsers:hasUsers(),dir:l?.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,d)=>{const l=loadGateway();d.json({baseUrl:l.baseUrl||"",apiKey:l.apiKey?l.apiKey.length>12?l.apiKey.slice(0,6)+"***"+l.apiKey.slice(-4):"***":"",hasKey:!!l.apiKey})})),app.post("/api/gateway",checkAdminAuth,express.json(),((S,d)=>{const{baseUrl:l,apiKey:n}=S.body||{},e=loadGateway(),o={baseUrl:typeof l=="string"?l.trim():e.baseUrl,apiKey:!n||n.includes("***")?e.apiKey:n.trim()};try{(0,external_fs_.mkdirSync)(server_configDir,{recursive:!0}),(0,external_fs_.writeFileSync)(gatewayFile,JSON.stringify(o,null,2),{mode:384}),d.json({ok:!0})}catch(u){d.status(500).json({error:u.message})}})),app.get("/api/secrets",checkAdminAuth,((S,d)=>{try{d.json(secretsOverview())}catch(l){d.status(500).json({error:l.message})}})),app.post("/api/secrets",checkAdminAuth,express.json(),((S,d)=>{const{name:l,value:n,type:e,scope:o,cwd:u}=S.body||{},h=upsertSecret({name:l,value:n,type:e,scope:o,cwd:u});if(h.error)return d.status(400).json(h);d.json(h)})),app.delete("/api/secrets",checkAdminAuth,express.json(),((S,d)=>{const{name:l,scope:n,cwd:e}=S.body||{};if(!l)return d.status(400).json({error:"\u7F3A\u5C11 name"});try{d.json(deleteSecret({name:l,scope:n,cwd:e}))}catch(o){d.status(500).json({error:o.message})}})),app.get("/api/session/:id/secrets",checkAuth,((S,d)=>{const l=manager.get(S.params.id);if(!l)return d.status(404).json({error:"\u4F1A\u8BDD\u4E0D\u5B58\u5728"});d.json({cwd:l.cwd,project:listSecrets("project",l.cwd),global:listSecrets("global")})})),app.post("/api/session/:id/secrets",checkAuth,express.json(),((S,d)=>{const l=manager.get(S.params.id);if(!l)return d.status(404).json({error:"\u4F1A\u8BDD\u4E0D\u5B58\u5728"});const{name:n,value:e,type:o}=S.body||{},u=upsertSecret({name:n,value:e,type:o,scope:"project",cwd:l.cwd});if(u.error)return d.status(400).json(u);d.json(u)})),app.delete("/api/session/:id/secrets",checkAuth,express.json(),((S,d)=>{const l=manager.get(S.params.id);if(!l)return d.status(404).json({error:"\u4F1A\u8BDD\u4E0D\u5B58\u5728"});const{name:n}=S.body||{};if(!n)return d.status(400).json({error:"\u7F3A\u5C11 name"});d.json(deleteSecret({name:n,scope:"project",cwd:l.cwd}))})),app.post("/api/session/:id/secrets/bulk",checkAuth,express.json(),((S,d)=>{const l=manager.get(S.params.id);if(!l)return d.status(404).json({error:"\u4F1A\u8BDD\u4E0D\u5B58\u5728"});const n=upsertManyProject(l.cwd,(S.body||{}).text||"");if(n.error)return d.status(400).json(n);d.json(n)})),app.get("/api/session/:id/guard",checkAuth,((S,d)=>{const l=manager.get(S.params.id);if(!l)return d.status(404).json({error:"\u4F1A\u8BDD\u4E0D\u5B58\u5728"});const n=getProjectGuard(l.cwd);d.json({cwd:l.cwd,enabled:n.enabled,level:n.level,entities:n.entities})})),app.put("/api/session/:id/guard",checkAuth,express.json(),((S,d)=>{const l=manager.get(S.params.id);if(!l)return d.status(404).json({error:"\u4F1A\u8BDD\u4E0D\u5B58\u5728"});const{enabled:n,level:e}=S.body||{},o=setProjectGuard(l.cwd,{enabled:n,level:e});if(o.error)return d.status(400).json(o);d.json(o)})),app.post("/api/session/:id/guard/entity",checkAuth,express.json(),((S,d)=>{const l=manager.get(S.params.id);if(!l)return d.status(404).json({error:"\u4F1A\u8BDD\u4E0D\u5B58\u5728"});const{name:n,type:e}=S.body||{},o=upsertEntity(l.cwd,{name:n,type:e});if(o.error)return d.status(400).json(o);d.json(o)})),app.delete("/api/session/:id/guard/entity",checkAuth,express.json(),((S,d)=>{const l=manager.get(S.params.id);if(!l)return d.status(404).json({error:"\u4F1A\u8BDD\u4E0D\u5B58\u5728"});const{name:n}=S.body||{};if(!n)return d.status(400).json({error:"\u7F3A\u5C11 name"});d.json(deleteEntity(l.cwd,n))})),app.post("/api/session/:id/guard/bulk",checkAuth,express.json(),((S,d)=>{const l=manager.get(S.params.id);if(!l)return d.status(404).json({error:"\u4F1A\u8BDD\u4E0D\u5B58\u5728"});const n=upsertManyEntities(l.cwd,(S.body||{}).text||"");if(n.error)return d.status(400).json(n);d.json(n)})),app.get("/api/session/:id/guard/audit",checkAuth,((S,d)=>{const l=manager.get(S.params.id);if(!l)return d.status(404).json({error:"\u4F1A\u8BDD\u4E0D\u5B58\u5728"});const n=l.claudeSessionId||S.params.id;d.json({entries:loadAudit(n)})})),app.get("/api/session/:id/followup",checkAuth,((S,d)=>{const l=manager.get(S.params.id);if(!l||typeof l.followUpState!="function")return d.status(404).json({error:"\u4F1A\u8BDD\u4E0D\u5B58\u5728\u6216\u975E AI \u4F1A\u8BDD"});d.json(l.followUpState())})),app.put("/api/session/:id/followup",checkAuth,express.json(),((S,d)=>{const l=manager.get(S.params.id);if(!l||typeof l.setFollowUp!="function")return d.status(404).json({error:"\u4F1A\u8BDD\u4E0D\u5B58\u5728\u6216\u975E AI \u4F1A\u8BDD"});const{enabled:n,intervalMinutes:e}=S.body||{};d.json(l.setFollowUp({enabled:n,intervalMinutes:e}))}));function maybeKickRelay(S){try{if(!S?.autoSend)return;const d=manager.get(S.sessionId);d&&typeof d._maybeRelayDraft=="function"&&d.alive&&!d.isBusy&&d._maybeRelayDraft()}catch{}}app.get("/api/inbox",checkAuth,((S,d)=>{const l=getUserInfo(S.headers.cookie),{sessionId:n}=S.query;try{try{rebindDrafts(manager.listSessions())}catch{}const e=listDrafts({sessionId:n||void 0,owner:l?.name,includeAll:l?.role==="admin"}),o=new Set(manager.listSessions().map((u=>u.id)));d.json({drafts:e.map((u=>({...u,sessionAlive:o.has(u.sessionId)}))),counts:countBySession()})}catch(e){d.status(500).json({error:e.message})}})),app.post("/api/inbox",checkAuth,express.json({limit:"1mb"}),((S,d)=>{const l=getUserInfo(S.headers.cookie),n=S.body||{},e=n.sessionId?manager.get(n.sessionId):null;try{const o=addDraft({...n,owner:n.owner||l?.name||null},e);maybeKickRelay(o),d.json({ok:!0,draft:o})}catch(o){d.status(400).json({error:o.message})}})),app.put("/api/inbox/:id",checkAuth,express.json({limit:"1mb"}),((S,d)=>{const l=S.body||{},n=l.sessionId?manager.get(l.sessionId):null,e=updateDraft(S.params.id,l,n);if(!e)return d.status(404).json({error:"\u8349\u7A3F\u4E0D\u5B58\u5728"});maybeKickRelay(e),d.json({ok:!0,draft:e})})),app.delete("/api/inbox/:id",checkAuth,((S,d)=>{if(!removeDraft(S.params.id))return d.status(404).json({error:"\u8349\u7A3F\u4E0D\u5B58\u5728"});d.json({ok:!0})}));function _spawnOpen(S,d){try{const l=(0,external_child_process_namespaceObject.spawn)(S,d,{detached:!0,stdio:"ignore",shell:process.platform==="win32"});return l.on("error",(()=>{})),l.unref(),!0}catch{return!1}}app.post("/api/session/:id/open-folder",checkAuth,((S,d)=>{const l=manager.get(S.params.id);if(!l?.cwd)return d.status(404).json({error:"\u4F1A\u8BDD\u6216\u76EE\u5F55\u4E0D\u5B58\u5728"});const n=l.cwd,e=process.platform==="win32"?_spawnOpen("explorer.exe",[n]):process.platform==="darwin"?_spawnOpen("open",[n]):_spawnOpen("xdg-open",[n]);d.json({ok:e,cwd:n})})),app.post("/api/session/:id/open-editor",checkAuth,((S,d)=>{const l=manager.get(S.params.id);if(!l?.cwd)return d.status(404).json({error:"\u4F1A\u8BDD\u6216\u76EE\u5F55\u4E0D\u5B58\u5728"});const n=_spawnOpen("code",[l.cwd]);d.json({ok:n})}));function getPkgVersion(){for(const S of["../package.json","./package.json","package.json"])try{const d=JSON.parse((0,external_fs_.readFileSync)((0,external_path_.join)(server_dirname,S),"utf8")).version;if(d&&d!=="0.0.0")return d}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 d=await fetch("https://registry.npmjs.org/@wendongfly/myhi/latest",{headers:{Accept:"application/json"},signal:AbortSignal.timeout(8e3)});d.ok&&(_latestVersion=(await d.json()).version,_lastVersionCheck=S)}catch{}return _latestVersion}app.get("/api/version",(async(S,d)=>{const l=getPkgVersion(),n=await checkLatestVersion();d.json({current:l,latest:n||l,updateAvailable:n&&n!==l})}));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,d)=>{const l=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""}})();d.json({asrUrl:l||""})})),app.post("/api/server-config",checkAuth,express.json(),((S,d)=>{const{asrUrl:l}=S.body||{},n=(0,external_path_.join)((0,external_os_.homedir)(),".myhi","asr.json");try{const e=(l||"").trim();(0,external_fs_.writeFileSync)(n,JSON.stringify({url:e},null,2),"utf8"),d.json({ok:!0})}catch(e){d.status(500).json({error:e.message})}})),app.post("/api/restart",checkAuth,((S,d)=>{d.json({ok:!0}),setTimeout((()=>restartService()),300)})),app.post("/api/update",checkAuth,(async(S,d)=>{try{await execAsync(getNpmUpgradeCmd(),{encoding:"utf8",timeout:12e4}),console.log("[myhi] \u5347\u7EA7\u5B8C\u6210"),d.json({ok:!0,message:"\u5347\u7EA7\u5B8C\u6210\uFF0C\u670D\u52A1\u5C06\u81EA\u52A8\u91CD\u542F..."}),setTimeout((()=>restartService()),500)}catch(l){const n=(l.stderr||l.stdout||l.message||"").split(`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wendongfly/myhi",
3
- "version": "1.3.157",
3
+ "version": "1.3.158",
4
4
  "description": "Web-based terminal sharing with chat UI — control your terminal from phone via LAN/Tailscale",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",