aws-runtime-bridge 1.9.140 → 1.9.142

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.
@@ -1,2 +1,2 @@
1
- import{configManager as g}from"./config.js";import{MESSAGE_POLL_INTERVAL_MS as I}from"./constants.js";import{HttpClient as f}from"./http-client.js";import{logger as s,setMcpNodeLogSink as w,updateStartupLogIdentity as u}from"./logger.js";import{claimRuntimeLaunchBindingDetailed as m}from"./runtime-launch-binding.js";import{StatusReporter as A}from"./status-reporter.js";import{WebSocketClient as p}from"./websocket-client.js";class T extends Error{constructor(e){super(e),this.name="PollLongPollTimeoutError"}}const C=27e4;class N{wsClient;httpClient;agentConfig;serverConfig;agentId=null;displayName=null;projectId=null;isRunning=!1;isDegradedMode=!1;messageHandler=null;profileHandler=null;configHandler=null;systemNotifyHandler=null;pollTimer=null;statusReporter=null;newCharacterHandler=null;runtimeTokenRefreshTimer=null;pendingLaunchBindingClaim=!1;cachedProfile=null;constructor(){g.loadConfig(),this.agentConfig=g.getAgentConfig(),this.serverConfig=g.getServerConfig(),this.wsClient=new p(this.serverConfig),this.httpClient=new f(this.serverConfig),this.setupWebSocketListeners()}async initialize(){const e=await m(this.agentConfig,this.serverConfig);if(e.status==="claimed"){this.applyLaunchBinding(e.binding);return}if(e.status==="unreachable"){this.pendingLaunchBindingClaim=!0,s.warn("[AgentClient] runtime-bridge \u672A\u5C31\u7EEA\uFF0C\u542F\u52A8\u7ED1\u5B9A\u8BA4\u9886\u5DF2\u6302\u8D77\uFF0C\u5C06\u5728\u6CE8\u518C\u91CD\u8BD5\u4E2D\u91CD\u65B0\u8BA4\u9886: %s",e.message);return}this.serverConfig.runtimeBridgeBaseUrl=void 0}applyLaunchBinding(e){g.applyRuntimeLaunchBinding(e),this.agentConfig=g.getAgentConfig(),this.serverConfig=g.getServerConfig(),this.wsClient=new p(this.serverConfig),this.httpClient=new f(this.serverConfig),this.setupWebSocketListeners()}async retryPendingLaunchBindingClaim(){if(!this.pendingLaunchBindingClaim)return!0;const e=await m(this.agentConfig,this.serverConfig);if(e.status==="claimed")return this.pendingLaunchBindingClaim=!1,s.info("[AgentClient] \u542F\u52A8\u7ED1\u5B9A\u8865\u8BA4\u9886\u6210\u529F\uFF0C\u7EE7\u7EED\u6CE8\u518C\u6D41\u7A0B"),this.applyLaunchBinding(e.binding),!0;if(e.status==="missing")return this.pendingLaunchBindingClaim=!1,this.serverConfig.runtimeBridgeBaseUrl=void 0,s.warn("[AgentClient] \u542F\u52A8\u7ED1\u5B9A\u8865\u8BA4\u9886\u672A\u627E\u5230\u5F85\u8BA4\u9886\u8BB0\u5F55\uFF0C\u6309\u65E0\u7ED1\u5B9A\u6A21\u5F0F\u7EE7\u7EED\u6CE8\u518C"),!1;const t=e.status==="unreachable"?e.message:e.reason;return s.warn("[AgentClient] \u542F\u52A8\u7ED1\u5B9A\u8865\u8BA4\u9886\u5931\u8D25\uFF0C\u4FDD\u7559\u6302\u8D77\u72B6\u6001\u7B49\u5F85\u4E0B\u6B21\u6CE8\u518C\u91CD\u8BD5: %s",t),!1}setupWebSocketListeners(){this.wsClient.on("directMessage",e=>{this.handleIncomingDm(e)}),this.wsClient.on("groupMessage",e=>{this.handleIncomingGroup(e)}),this.wsClient.on("meetingMessage",e=>{this.handleIncomingMeeting(e)}),this.wsClient.on("systemNotify",e=>{this.systemNotifyHandler?.(e)}),this.wsClient.on("profileInfo",e=>{s.info(`[AgentClient] WebSocket profileInfo \u4E8B\u4EF6\u89E6\u53D1\uFF0CdisplayName: ${e.displayName}`),this.handleProfileInfo(e)}),this.wsClient.on("agentConfig",e=>{s.info("[AgentClient] WebSocket agentConfig \u4E8B\u4EF6\u89E6\u53D1"),this.configHandler&&this.configHandler(e??{})}),this.wsClient.on("agentStatus",e=>{s.info(`[AgentClient] WebSocket agentStatus \u4E8B\u4EF6\u89E6\u53D1: ${e.status}`)}),this.wsClient.on("disconnected",(e,t)=>{const n=t?.toString()||"";s.warn("[AgentClient] WebSocket \u65AD\u5F00\u8FDE\u63A5: code=%s, reason=%s, agentId=%s, \u6B63\u5728\u81EA\u52A8\u91CD\u8FDE",e,n,this.agentId)}),this.wsClient.on("error",e=>{s.error("[AgentClient] WebSocket \u9519\u8BEF: %s, stack=%s",e.message,e.stack)}),this.wsClient.on("reconnectFailed",()=>{s.error("[AgentClient] \u91CD\u8FDE\u5931\u8D25\uFF08\u5DF2\u8FBE\u91CD\u8BD5\u4E0A\u9650\uFF09\uFF0C\u505C\u6B62\u6D88\u606F\u5FAA\u73AF, agentId=%s",this.agentId),this.stop()}),this.wsClient.on("tokenRejected",()=>{s.error("[AgentClient] runtime token \u88AB 1008 \u62D2\u7EDD\u4E14\u5237\u65B0\u65E0\u53D8\u5316\uFF0C\u8FDB\u5165\u6162\u901F\u91CD\u8BD5\u7B49\u5F85\u65B0 token \u7B7E\u53D1: agentId=%s",this.agentId)}),this.wsClient.on("tokenRefreshFailed",e=>{s.error("[AgentClient] runtime token \u5237\u65B0\u8FDE\u7EED\u5931\u8D25 %s \u6B21\uFF0C\u8FDB\u5165\u6162\u901F\u91CD\u8BD5\u7B49\u5F85 bridge \u6062\u590D: agentId=%s",e,this.agentId)})}async register(){return s.info("[AgentClient] \u6B63\u5728\u6CE8\u518C Agent..."),await this.retryPendingLaunchBindingClaim(),this.hasPresetAgentId()?await this.registerWithExistingAgentId():await this.registerAsNewAgent()}hasPresetAgentId(){return!!(this.agentConfig.agentId&&this.agentConfig.agentId.trim().length>0)}async registerWithExistingAgentId(){const e=this.agentConfig.agentId;if(!e)throw new Error("Preset agentId is missing");this.agentId=e.trim();let t;try{t=await this.getProfileByAgentId(this.agentId)}catch(r){throw s.error("[AgentClient] getProfileByAgentId \u5931\u8D25 (presetAgentId=%s): %s",this.agentId,r instanceof Error?r.message:String(r)),r}this.displayName=t.displayName,this.projectId=t.projectId||null,s.info(`[AgentClient] \u4F7F\u7528\u9884\u8BBE AgentID \u7ED1\u5B9A\u5B9E\u4F8B: ${this.displayName} (${this.agentId})`),s.info(`[AgentClient] \u6240\u5C5E\u9879\u76EE: ${this.projectId||"(\u672A\u8BBE\u7F6E)"}`);try{await this.wsClient.connect(this.agentId)}catch(r){throw s.error("[AgentClient] WebSocket \u8FDE\u63A5\u5931\u8D25 (agentId=%s): %s",this.agentId,r instanceof Error?r.message:String(r)),r}s.info("[AgentClient] WebSocket \u8FDE\u63A5\u5DF2\u5EFA\u7ACB\uFF0CAgent \u73B0\u5728\u5DF2\u4E0A\u7EBF"),this.initializeStatusReporter();const n=await this.getProfileByAgentId(this.agentId);return this.displayName=n.displayName,this.projectId=n.projectId||null,u(n.roleName||"unknown-role",n.instanceName||this.agentId),{agentId:this.agentId,displayName:this.displayName,status:n.isOnline?"online":"offline",projectId:n.projectId,workspacePath:n.workspacePath,runtimeStatus:n.runtimeStatus,runtimeSessionId:n.runtimeSessionId}}async registerAsNewAgent(){const e=await this.httpClient.callTool("register",{roleName:this.agentConfig.roleName,projectId:this.agentConfig.projectId,workspacePath:this.agentConfig.workspacePath,prompt:this.agentConfig.prompt,runtimeBridgeBaseUrl:this.serverConfig.runtimeBridgeBaseUrl}),t=e.agentId;if(!t)throw new Error("Registration failed: agentId was not returned");return this.agentId=t,this.displayName=e.displayName,this.projectId=e.projectId||null,u(this.agentConfig.roleName||"unknown-role",e.instanceName||t),s.info(`[AgentClient] \u6CE8\u518C\u6210\u529F: ${this.displayName} (${this.agentId})`),s.info(`[AgentClient] \u72B6\u6001: ${e.status}`),s.info(`[AgentClient] \u6240\u5C5E\u9879\u76EE: ${this.projectId||"(\u672A\u8BBE\u7F6E)"}`),await this.wsClient.connect(this.agentId),s.info("[AgentClient] WebSocket \u8FDE\u63A5\u5DF2\u5EFA\u7ACB\uFF0CAgent \u73B0\u5728\u5DF2\u4E0A\u7EBF"),this.initializeStatusReporter(),e.isExisting===!1&&this.newCharacterHandler&&this.newCharacterHandler(),e}async unregister(){s.info("[AgentClient] \u6B63\u5728\u6CE8\u9500 Agent..."),this.agentId&&await this.httpClient.callTool("unregister",{agentId:this.agentId}),this.stopRuntimeTokenRefresh(),this.wsClient.disconnect(),this.agentId=null,this.displayName=null,this.projectId=null,this.isRunning=!1,s.info("[AgentClient] \u5DF2\u6CE8\u9500")}async discoverColleagues(){return await this.httpClient.callTool("discover_colleague",{agentId:this.agentId})}async discoverGroupRooms(){return this.ensureRegistered(),await this.httpClient.callTool("discover_group_rooms",{agentId:this.agentId})}async hireColleague(e){return this.ensureRegistered(),await this.httpClient.callTool("hire_colleague",{...e,agentId:this.agentId})}async hireColleaguesBatch(e){return this.ensureRegistered(),await this.httpClient.callTool("hire_colleagues_batch",{...e,agentId:this.agentId})}async callAgentScopedTool(e,t){this.ensureRegistered();const n={...t,agentId:this.agentId};if(e==="create_meeting"){const r=typeof t.waitTimeoutMs=="number"?t.waitTimeoutMs:Number.NaN,i=Number.isFinite(r)&&r>0?Math.min(r,C):C;return await this.httpClient.callToolOnce(e,{...n,waitTimeoutMs:i},0)}return await this.httpClient.callTool(e,n)}async reportMemoryStats(e){await this.callAgentScopedTool("report_memory_stats",{memoryStats:e})}async sendGroupMessage(e,t,n){this.ensureRegistered();const r=t||this.projectId||this.agentConfig.projectId;return await this.httpClient.callTool("send_group_message",{agentId:this.agentId,projectId:r,roomId:n,content:e})}async sendDirectMessage(e,t,n=!1,r,i){this.ensureRegistered();const a={agentId:this.agentId,targetId:e,content:t,requireReply:n,waitReply:n,replyToCallId:r};if(typeof i=="number"&&i>0&&(a.timeoutMs=i),n){const c=typeof i=="number"&&i>0?i+3e4:0;return await this.httpClient.callToolOnce("send_dm",a,c)}return await this.httpClient.callTool("send_dm",a)}async sendCallAndWaitReply(e,t,n=6e4){const r=await this.sendDirectMessage(e,t,!0,void 0,n);if(r.reply)return r.reply;throw new Error("No reply received for call-style direct message before timeout")}async replyToCall(e,t,n){return await this.sendDirectMessage(t,n,!1,e)}async getDmHistory(e,t=50,n){this.ensureRegistered();const r={agentId:this.agentId,targetUserId:e,limit:t};return n&&(r.since=n),await this.httpClient.callTool("get_dm_history",r)}async getGroupHistory(e=50,t,n){if(this.ensureRegistered(),t){const o={projectId:this.projectId||this.agentConfig.projectId,roomId:t,limit:e};return n&&(o.since=n),await this.httpClient.callTool("get_group_history",o)}const r=await this.discoverGroupRooms(),i=this.projectId||this.agentConfig.projectId,a=this.collectRoomIds(r,i);if(a.length===0)return{messages:[],count:0};const h=(await Promise.all(a.map(async o=>{const l={projectId:i,roomId:o,limit:e};return n&&(l.since=n),await this.httpClient.callTool("get_group_history",l)}))).flatMap(o=>o.messages).sort((o,l)=>new Date(o.timestamp).getTime()-new Date(l.timestamp).getTime());return{messages:h,count:h.length}}async fetchUnreadMessages(e={}){this.ensureRegistered();const t=this.projectId||this.agentConfig.projectId,n={agentId:this.agentId,blockIfEmpty:e.blockIfEmpty??!1};e.since&&(n.since=e.since),e.blockTimeoutMs&&e.blockTimeoutMs>0&&(n.blockTimeoutMs=e.blockTimeoutMs),e.preemptiveJoinWaitMs!==void 0&&e.preemptiveJoinWaitMs!==null&&e.preemptiveJoinWaitMs>=0&&(n.preemptiveJoinWaitMs=e.preemptiveJoinWaitMs);const r=e.includePipelineTasks?"poll_message":"get_dm_messages";s.info("[AgentClient] fetchUnreadMessages \u5165\u53E3: tool=%s, blockIfEmpty=%s, blockTimeoutMs=%s, pollMessageTimeoutMs=%s, skipGroupMessages=%s, preemptiveJoinWaitMs=%s, agentId=%s",r,String(e.blockIfEmpty??!1),String(e.blockTimeoutMs??"-"),String(e.pollMessageTimeoutMs??"-"),String(e.skipGroupMessages??!1),String(e.preemptiveJoinWaitMs??"-"),this.agentId);const i=await this.fetchDirectMessagesWithRecovery(r,n,e.pollMessageTimeoutMs,e.propagatePollTimeout===!0);if(s.info("[AgentClient] fetchUnreadMessages \u79C1\u4FE1\u9636\u6BB5\u8FD4\u56DE: %s \u6761",Array.isArray(i.messages)?i.messages.length:0),e.skipGroupMessages)return s.info("[AgentClient] \u4F1A\u8BAE\u5FEB\u901F hydrate \u5DF2\u53D6\u5F97\u79C1\u4FE1\u54CD\u5E94\uFF0C\u8DF3\u8FC7\u7FA4\u804A\u53D1\u73B0\u5E76\u7ACB\u5373\u8FD4\u56DE: directMessages=%s",Array.isArray(i.messages)?i.messages.length:0),{directMessages:Array.isArray(i.messages)?i.messages:[],groupMessages:[]};let a;try{a=await this.discoverGroupRooms()}catch(o){s.warn("[AgentClient] \u53D1\u73B0\u7FA4\u623F\u95F4\u5931\u8D25\uFF0C\u672C\u6B21\u6309\u65E0\u7FA4\u6D88\u606F\u5904\u7406\uFF08\u5DF2\u53D6\u5230\u7684\u79C1\u4FE1\u4E0D\u53D7\u5F71\u54CD\uFF09: %s",o instanceof Error?o.message:String(o)),a={groups:[]}}const c=this.collectRoomIds(a,t),h=await Promise.all(c.map(async o=>{const l={agentId:this.agentId,projectId:t,roomId:o};e.since&&(l.since=e.since);try{return await this.httpClient.callTool("get_group_messages",l)}catch(d){return s.warn("[AgentClient] \u8DF3\u8FC7\u7FA4\u623F\u95F4\u672A\u8BFB\u8865\u62C9\u5931\u8D25: roomId=%s, error=%s",o,d instanceof Error?d.message:String(d)),{messages:[],currentReadPos:0,hasMore:!1}}}));return{directMessages:Array.isArray(i.messages)?i.messages:[],groupMessages:h.flatMap(o=>this.normalizeGroupMessages(o)).sort((o,l)=>new Date(o.timestamp).getTime()-new Date(l.timestamp).getTime())}}async markDmRead(e){if(e.length===0)return new Set;this.ensureRegistered();try{const t=await this.httpClient.callTool("mark_dm_read",{agentId:this.agentId,msgIds:e}),n=new Set(Array.isArray(t?.deliverableMsgIds)?t.deliverableMsgIds:[]),r=e.filter(i=>!n.has(i));return r.length>0?s.warn("[AgentClient] mark_dm_read \u786E\u8BA4\u540E\u5C06\u6709 %d \u6761\u6D88\u606F\u88AB\u4E22\u5F03\u4E0D\u4EA4\u4ED8: \u8BF7\u6C42=%s, \u53EF\u4EA4\u4ED8=%s, \u88AB\u4E22\u5F03=%s",r.length,JSON.stringify(e),JSON.stringify([...n]),JSON.stringify(r)):s.info("[AgentClient] mark_dm_read \u786E\u8BA4\u5B8C\u6210: %d \u6761\u5168\u90E8\u53EF\u4EA4\u4ED8",e.length),n}catch(t){throw s.warn("[AgentClient] mark_dm_read \u8BF7\u6C42\u5931\u8D25\uFF08\u5C06\u964D\u7EA7\u4E3A\u76F4\u63A5\u4EA4\u4ED8\uFF09: %s",t instanceof Error?t.message:String(t)),t}}async markGroupRead(e,t){if(t.length===0)return new Set;this.ensureRegistered();const n=await this.httpClient.callTool("mark_group_read",{agentId:this.agentId,roomId:e,msgIds:t});return new Set(Array.isArray(n?.deliverableMsgIds)?n.deliverableMsgIds:[])}async markNotificationRead(e){if(e.length!==0){this.ensureRegistered();try{await this.httpClient.callTool("mark_notification_read",{agentId:this.agentId,msgIds:e})}catch{}}}async markMeetingRead(e){if(e.length!==0){this.ensureRegistered();try{await this.httpClient.callTool("mark_meeting_read",{agentId:this.agentId,msgIds:e})}catch{}}}async fetchBrowserListenerEvents(){const e=this.serverConfig.runtimeBridgeBaseUrl,t=this.agentId;if(!e||!t)return s.info("[AgentClient] fetchBrowserListenerEvents \u8DF3\u8FC7: bridgeBaseUrl=%s, agentId=%s",e||"(\u7A7A)",t||"(\u7A7A)"),[];try{const n=`${e}/runtime/browser-listeners/${encodeURIComponent(t)}/events`,r=this.serverConfig.runtimeAccessToken||"";s.debug("[AgentClient] \u62C9\u53D6\u76D1\u542C\u5668\u4E8B\u4EF6: url=%s, tokenLen=%d",n,r.length);const i=await fetch(n,{method:"GET",headers:{"X-Runtime-Token":r},signal:AbortSignal.timeout(3e3)});if(!i.ok)return s.warn("[AgentClient] \u62C9\u53D6\u76D1\u542C\u5668\u4E8B\u4EF6\u5931\u8D25: HTTP %s, url=%s",i.status,n),[];const a=await i.json();return!a.ok||!Array.isArray(a.events)?(s.warn("[AgentClient] \u62C9\u53D6\u76D1\u542C\u5668\u4E8B\u4EF6\u54CD\u5E94\u5F02\u5E38: ok=%s, eventsType=%s",a.ok,Array.isArray(a.events)?"array":typeof a.events),[]):(s.debug("[AgentClient] \u62C9\u53D6\u76D1\u542C\u5668\u4E8B\u4EF6\u6210\u529F: %d \u6761\u4E8B\u4EF6",a.events.length),a.events)}catch(n){return s.warn("[AgentClient] \u62C9\u53D6\u76D1\u542C\u5668\u4E8B\u4EF6\u5F02\u5E38: %s",n instanceof Error?n.message:String(n)),[]}}async fetchPluginEvents(){const e=this.serverConfig.runtimeBridgeBaseUrl,t=this.agentId;if(!e||!t)return{revision:0,events:[],catalog:null,compactionSeq:0};try{const n=`${e}/runtime/plugin-events/${encodeURIComponent(t)}/events`,r=this.serverConfig.runtimeAccessToken||"",i=await fetch(n,{method:"GET",headers:{"X-Runtime-Token":r},signal:AbortSignal.timeout(3e3)});if(!i.ok)return s.warn("[AgentClient] \u62C9\u53D6\u63D2\u4EF6\u4E8B\u4EF6\u5931\u8D25: HTTP %s, url=%s",i.status,n),{revision:0,events:[],catalog:null,compactionSeq:0};const a=await i.json();return!a.ok||!Array.isArray(a.events)?(s.warn("[AgentClient] \u62C9\u53D6\u63D2\u4EF6\u4E8B\u4EF6\u54CD\u5E94\u5F02\u5E38: ok=%s",String(a.ok)),{revision:0,events:[],catalog:null,compactionSeq:0}):(s.debug("[AgentClient] \u62C9\u53D6\u63D2\u4EF6\u4E8B\u4EF6\u6210\u529F: %d \u6761\u4E8B\u4EF6, revision=%s, catalog=%s, compactionSeq=%s",a.events.length,String(a.revision??0),a.catalog?`${a.catalog.plugins.length} \u4E2A\u63D2\u4EF6`:"null",String(a.compactionSeq??0)),{revision:a.revision??0,events:a.events,catalog:a.catalog??null,compactionSeq:typeof a.compactionSeq=="number"&&Number.isFinite(a.compactionSeq)?a.compactionSeq:0})}catch(n){return s.warn("[AgentClient] \u62C9\u53D6\u63D2\u4EF6\u4E8B\u4EF6\u5F02\u5E38: %s",n instanceof Error?n.message:String(n)),{revision:0,events:[],catalog:null,compactionSeq:0}}}async notifyBridgeForceMessage(){const e=this.serverConfig.runtimeBridgeBaseUrl,t=this.agentId;if(!(!e||!t))try{const n=`${e}/runtime/sessions/${encodeURIComponent(t)}/notify-force-message`,r=this.serverConfig.runtimeAccessToken||"",i=await fetch(n,{method:"POST",headers:{"X-Runtime-Token":r},signal:AbortSignal.timeout(3e3)});i.ok||s.warn("[AgentClient] \u901A\u77E5 bridge \u5F3A\u5236\u6D88\u606F\u5931\u8D25: HTTP %s, url=%s",i.status,n)}catch(n){s.warn("[AgentClient] \u901A\u77E5 bridge \u5F3A\u5236\u6D88\u606F\u5F02\u5E38: %s",n instanceof Error?n.message:String(n))}}async fetchDirectMessagesWithRecovery(e,t,n,r=!1){if(e==="poll_message"){s.info("[AgentClient] fetchDirectMessagesWithRecovery \u5165\u53E3: tool=poll_message, pollMessageTimeoutMs=%s, agentId=%s",String(n??"(\u9ED8\u8BA4)"),String(t?.agentId??""));try{const i=await this.httpClient.callToolOnce(e,t,n);return s.info("[AgentClient] fetchDirectMessagesWithRecovery poll_message \u6210\u529F\u8FD4\u56DE: %s \u6761",Array.isArray(i?.messages)?i.messages.length:0),i}catch(i){if(this.isRecoverableLongPollError(i)){if(r)throw new T(i instanceof Error?i.message:String(i));return s.warn("[AgentClient] poll_message \u5355\u6B21\u957F\u8F6E\u8BE2\u8D85\u65F6\uFF0C\u6309\u7A7A\u7ED3\u679C\u9000\u907F\u540E\u7EE7\u7EED\u7B49\u5F85:",i),{messages:[]}}throw i}}return await this.httpClient.callTool(e,t)}isRecoverableLongPollError(e){return e instanceof Error?/MCP tool poll_message call failed: 503(?:\s|$)/.test(e.message)||/MCP tool poll_message timed out after \d+ms/.test(e.message):!1}normalizeGroupMessages(e){return Array.isArray(e.messages)?e.messages.filter(t=>!!(t&&typeof t=="object"&&typeof t.msgId=="number"&&typeof t.senderId=="string"&&typeof t.content=="string"&&typeof t.timestamp=="string")):[]}collectRoomIds(e,t){const n=e.groups.filter(r=>r.projectId===t).map(r=>r.id);return Array.from(new Set(n))}async getProfile(){this.ensureRegistered();const e=this.agentId;if(!e)throw new Error("Agent is not registered");return{...await this.getProfileByAgentId(e),describe:this.agentConfig.describe}}async getProfileByAgentId(e){return await this.httpClient.callTool("get_profile",{agentId:e})}async getMyTasks(){return this.ensureRegistered(),await this.httpClient.callTool("my_task",{agentId:this.agentId})}async createTaskInstanceComment(e){this.ensureRegistered();const t={agentId:this.agentId,...e};return await this.httpClient.callTool("create_task_instance_comment",t)}async submitTaskResult(e,t,n){this.ensureRegistered();const r={agentId:this.agentId,nodeId:e,outputPayload:t};return n&&Array.isArray(n)&&n.length>0&&(r.changeLog=n),await this.httpClient.callTool("submit_task_result",r)}async startTaskRollback(e){return this.ensureRegistered(),await this.httpClient.callTool("start_task_rollback",{agentId:this.agentId,...e})}async finishTaskRollback(e){return this.ensureRegistered(),await this.httpClient.callTool("finish_task_rollback",{agentId:this.agentId,...e})}async rejectTask(e,t){return this.ensureRegistered(),await this.httpClient.callTool("reject_task",{agentId:this.agentId,nodeId:e,reason:t})}async terminateTask(e,t){return this.ensureRegistered(),await this.httpClient.callTool("terminate_task",{agentId:this.agentId,taskInstanceId:e,reason:t})}async getDebugLogConfig(){return await this.httpClient.callTool("get_debug_log_config",{agentId:this.agentId})}async queryDebugLogs(e){return this.ensureRegistered(),await this.httpClient.callTool("query_debug_logs",{...e})}async queryFileChangesHistory(e){return this.ensureRegistered(),await this.httpClient.callTool("query_file_changes_history",{...e})}async getRuntimeFeatures(){return await this.httpClient.fetchRuntimeFeatures()}async listLaunchConfigs(){return this.ensureRegistered(),await this.httpClient.callTool("launch_config_list",{})}async createLaunchConfig(e){return this.ensureRegistered(),await this.httpClient.callTool("launch_config_create",{...e})}async updateLaunchConfig(e){return this.ensureRegistered(),await this.httpClient.callTool("launch_config_update",{...e})}async deleteLaunchConfig(e){return this.ensureRegistered(),await this.httpClient.callTool("launch_config_delete",{configId:e})}async startLaunchConfig(e){this.ensureRegistered();const t=Math.max(0,Math.min(3e5,Number(e.wait_timeout_ms)||0));return t>0?await this.httpClient.callToolOnce("launch_config_start",e,t+6e4):await this.httpClient.callTool("launch_config_start",{...e})}async restartLaunchConfig(e){this.ensureRegistered();const t=Math.max(0,Math.min(3e5,Number(e.wait_timeout_ms)||0));return t>0?await this.httpClient.callToolOnce("launch_config_restart",e,t+6e4):await this.httpClient.callTool("launch_config_restart",{...e})}async stopLaunchConfig(e){return this.ensureRegistered(),await this.httpClient.callTool("launch_config_stop",{configId:e})}async getLaunchLogs(e){return this.ensureRegistered(),await this.httpClient.callTool("launch_config_logs",{...e})}async listLaunchRuns(){return this.ensureRegistered(),await this.httpClient.callTool("launch_config_status",{})}start(e,t){if(this.isRunning){s.warn("[AgentClient] \u6D88\u606F\u5FAA\u73AF\u5DF2\u5728\u8FD0\u884C\u4E2D");return}this.isDegradedMode||this.ensureRegistered(),this.messageHandler=e,this.profileHandler=t?.profileHandler||null,this.configHandler=t?.configHandler||null,this.systemNotifyHandler=t?.systemNotifyHandler||null,this.isRunning=!0,s.info(`[AgentClient] start() \u88AB\u8C03\u7528\uFF0CcachedProfile: ${this.cachedProfile?"\u5B58\u5728":"\u4E0D\u5B58\u5728"}, profileHandler: ${this.profileHandler?"\u5DF2\u8BBE\u7F6E":"\u672A\u8BBE\u7F6E"}, \u964D\u7EA7\u6A21\u5F0F: ${this.isDegradedMode?"\u662F":"\u5426"}`),this.cachedProfile&&this.profileHandler&&(s.info(`[AgentClient] \u5904\u7406\u7F13\u5B58\u7684 Profile \u4FE1\u606F: ${this.cachedProfile.displayName}`),this.profileHandler(this.cachedProfile),this.cachedProfile=null),t?.pollMode??!1?(s.warn("[AgentClient] \u542F\u52A8\u6D88\u606F\u4E3B\u5FAA\u73AF\uFF08HTTP\u8F6E\u8BE2\u6A21\u5F0F - \u4E0D\u63A8\u8350\uFF09"),this.messageLoop()):s.info("[AgentClient] \u542F\u52A8\u6D88\u606F\u4E3B\u5FAA\u73AF\uFF08WebSocket\u63A8\u9001\u6A21\u5F0F - \u63A8\u8350\uFF09")}stop(){this.isRunning=!1,this.pollTimer&&(clearTimeout(this.pollTimer),this.pollTimer=null),this.stopRuntimeTokenRefresh(),s.info("[AgentClient] \u6D88\u606F\u4E3B\u5FAA\u73AF\u5DF2\u505C\u6B62")}async messageLoop(){for(;this.isRunning;)try{await this.delay(I)}catch(e){s.error("[AgentClient] \u6D88\u606F\u5FAA\u73AF\u9519\u8BEF:",e),await this.delay(5e3)}}handleIncomingDm(e){e.senderId!==this.agentId&&this.processMessage(e)}handleIncomingGroup(e){e.senderId!==this.agentId&&this.processMessage(e)}handleIncomingMeeting(e){!e||e.senderId===this.agentId||this.processMessage(e)}handleProfileInfo(e){s.info(`[AgentClient] \u6536\u5230 Profile \u4FE1\u606F: ${e.displayName} (${e.roleName})`),e.projectId&&(this.projectId=e.projectId,s.info(`[AgentClient] \u66F4\u65B0\u6240\u5C5E\u9879\u76EE: ${this.projectId}`)),e.roleName&&e.roleName!==this.agentConfig.roleName&&(s.info(`[AgentClient] \u540C\u6B65\u89D2\u8272\u540D: "${this.agentConfig.roleName||"(\u7A7A)"}" -> "${e.roleName}"`),this.agentConfig.roleName=e.roleName),e.roleName&&u(e.roleName,e.instanceName||this.agentId||""),this.profileHandler?this.profileHandler(e):(s.info("[AgentClient] profileHandler \u672A\u8BBE\u7F6E\uFF0C\u7F13\u5B58 Profile \u4FE1\u606F"),this.cachedProfile=e)}async processMessage(e){if(!this.messageHandler)return;const t=typeof e.msgId=="string";s.info(`[AgentClient] \u6536\u5230${t?"\u79C1\u4FE1":"\u7FA4\u6D88\u606F"}\u6765\u81EA ${e.senderName}: ${e.content.substring(0,50)}...`);try{const n=await this.messageHandler(e);if(t){const r=e;r.requireReply&&r.callId&&await this.replyToCall(r.callId,r.senderId,n||"\u5DF2\u6536\u5230\u6D88\u606F\uFF0C\u6B63\u5728\u5904\u7406\u4E2D...")}}catch(n){const r=typeof e.msgId=="string";if(s.error("[AgentClient] \u5904\u7406\u6D88\u606F\u5931\u8D25: type=%s, senderId=%s, senderName=%s, msgId=%s, error=%s",r?"\u79C1\u4FE1":"\u7FA4\u6D88\u606F",e.senderId,e.senderName,e.msgId,n instanceof Error?n.message:String(n)),r){const i=e;i.requireReply&&i.callId&&await this.replyToCall(i.callId,i.senderId,`\u5904\u7406\u5931\u8D25: ${n}`)}}}ensureRegistered(){if(!this.agentId)throw new Error("Agent is not registered")}delay(e){return new Promise(t=>{this.pollTimer=setTimeout(t,e)})}onNewCharacter(e){this.newCharacterHandler=e}getState(){return{agentId:this.agentId,displayName:this.displayName,projectId:this.projectId,isConnected:this.wsClient.isConnected(),isRunning:this.isRunning}}getAgentConfig(){return this.agentConfig}getServerConfig(){return this.serverConfig}reloadConfig(){g.loadConfig(),this.agentConfig=g.getAgentConfig(),s.info(`[AgentClient] \u914D\u7F6E\u5DF2\u91CD\u65B0\u52A0\u8F7D\uFF0C\u89D2\u8272: ${this.agentConfig.roleName}`)}enterDegradedMode(){this.isDegradedMode=!0,s.warn("[AgentClient] \u8FDB\u5165\u964D\u7EA7\u6A21\u5F0F\uFF0C\u5C06\u5728\u540E\u53F0\u6301\u7EED\u5C1D\u8BD5\u91CD\u8FDE")}exitDegradedMode(){this.isDegradedMode=!1,s.info("[AgentClient] \u9000\u51FA\u964D\u7EA7\u6A21\u5F0F")}isInDegradedMode(){return this.isDegradedMode}async retryRegistrationInBackground(e,t){let n=0;(async()=>{for(;this.isDegradedMode;)try{s.info(`[AgentClient] \u964D\u7EA7\u6A21\u5F0F\uFF1A\u5C1D\u8BD5\u91CD\u65B0\u6CE8\u518C (${n+1}/${t===-1?"\u65E0\u9650":t})`);const i=await this.register();s.info(`[AgentClient] \u964D\u7EA7\u6A21\u5F0F\uFF1A\u6CE8\u518C\u6210\u529F - ${i.displayName} (${i.agentId})`),this.exitDegradedMode(),this.messageHandler&&this.start(this.messageHandler);return}catch(i){n++;const a=i instanceof Error?i.message:String(i);if(s.warn(`[AgentClient] \u964D\u7EA7\u6A21\u5F0F\uFF1A\u6CE8\u518C\u5931\u8D25 (${n}/${t===-1?"\u65E0\u9650":t}): ${a}`),t>0&&n>=t){s.error("[AgentClient] \u964D\u7EA7\u6A21\u5F0F\uFF1A\u8FBE\u5230\u6700\u5927\u91CD\u8BD5\u6B21\u6570\uFF0C\u505C\u6B62\u91CD\u8FDE"),this.isDegradedMode=!1;return}await new Promise(c=>setTimeout(c,e))}})().catch(i=>{s.error("[AgentClient] \u964D\u7EA7\u6A21\u5F0F\u540E\u53F0\u91CD\u8BD5\u5FAA\u73AF\u5F02\u5E38\u9000\u51FA: error=%s, stack=%s",i instanceof Error?i.message:String(i),i instanceof Error?i.stack:"(no stack)")})}initializeStatusReporter(){if(!this.agentId){s.warn("[AgentClient] \u65E0\u6CD5\u521D\u59CB\u5316\u72B6\u6001\u62A5\u544A\u5668\uFF1AagentId \u4E3A\u7A7A");return}this.statusReporter=new A({agentId:this.agentId,sendStatusUpdate:e=>{this.wsClient.send({type:"AGENT_STATUS",data:e,timestamp:new Date().toISOString()})}}),w(e=>this.reportMcpNodeLog(e)),this.startRuntimeTokenRefresh(),s.info("[AgentClient] \u72B6\u6001\u62A5\u544A\u5668\u5DF2\u521D\u59CB\u5316")}startRuntimeTokenRefresh(){this.stopRuntimeTokenRefresh();const e=this.serverConfig.runtimeTokenRefreshIntervalMs;if(!e||e<=0){s.warn("[AgentClient] runtimeTokenRefreshIntervalMs \u672A\u914D\u7F6E\u6216\u65E0\u6548\uFF0C\u8DF3\u8FC7\u4E3B\u52A8\u7EED\u671F");return}const t=this.agentId;if(!t){s.warn("[AgentClient] agentId \u4E3A\u7A7A\uFF0C\u8DF3\u8FC7\u4E3B\u52A8\u7EED\u671F");return}this.runtimeTokenRefreshTimer=setInterval(async()=>{try{await this.httpClient.refreshRuntimeAccessToken(t)&&s.info("[AgentClient] runtimeAccessToken \u5DF2\u4E3B\u52A8\u7EED\u671F")}catch(n){s.warn("[AgentClient] \u4E3B\u52A8\u7EED\u671F runtimeAccessToken \u5931\u8D25: %s",n instanceof Error?n.message:String(n)),n instanceof Error&&n.stack&&s.warn("[AgentClient] \u4E3B\u52A8\u7EED\u671F\u5F02\u5E38\u5806\u6808:",n.stack)}},e),this.runtimeTokenRefreshTimer.unref?.(),s.info(`[AgentClient] runtime token \u4E3B\u52A8\u7EED\u671F\u5DF2\u542F\u52A8\uFF0C\u95F4\u9694 ${e}ms`)}stopRuntimeTokenRefresh(){this.runtimeTokenRefreshTimer&&(clearInterval(this.runtimeTokenRefreshTimer),this.runtimeTokenRefreshTimer=null)}reportMcpNodeLog(e){const t=this.wsClient;!this.agentId||!this.wsClient.isConnected()||typeof t.sendMcpNodeLog!="function"||t.sendMcpNodeLog(e)}getStatusReporter(){return this.statusReporter}}export{N as AgentClient,T as PollLongPollTimeoutError};
1
+ import{configManager as g}from"./config.js";import{MESSAGE_POLL_INTERVAL_MS as I}from"./constants.js";import{HttpClient as f}from"./http-client.js";import{logger as s,setMcpNodeLogSink as w,updateStartupLogIdentity as u}from"./logger.js";import{claimRuntimeLaunchBindingDetailed as m}from"./runtime-launch-binding.js";import{StatusReporter as A}from"./status-reporter.js";import{WebSocketClient as p}from"./websocket-client.js";class T extends Error{constructor(e){super(e),this.name="PollLongPollTimeoutError"}}const C=27e4;class N{wsClient;httpClient;agentConfig;serverConfig;agentId=null;displayName=null;projectId=null;isRunning=!1;isDegradedMode=!1;messageHandler=null;profileHandler=null;configHandler=null;systemNotifyHandler=null;pollTimer=null;statusReporter=null;newCharacterHandler=null;runtimeTokenRefreshTimer=null;pendingLaunchBindingClaim=!1;cachedProfile=null;constructor(){g.loadConfig(),this.agentConfig=g.getAgentConfig(),this.serverConfig=g.getServerConfig(),this.wsClient=new p(this.serverConfig),this.httpClient=new f(this.serverConfig),this.setupWebSocketListeners()}async initialize(){const e=await m(this.agentConfig,this.serverConfig);if(e.status==="claimed"){this.applyLaunchBinding(e.binding);return}if(e.status==="unreachable"){this.pendingLaunchBindingClaim=!0,s.warn("[AgentClient] runtime-bridge \u672A\u5C31\u7EEA\uFF0C\u542F\u52A8\u7ED1\u5B9A\u8BA4\u9886\u5DF2\u6302\u8D77\uFF0C\u5C06\u5728\u6CE8\u518C\u91CD\u8BD5\u4E2D\u91CD\u65B0\u8BA4\u9886: %s",e.message);return}this.serverConfig.runtimeBridgeBaseUrl=void 0}applyLaunchBinding(e){g.applyRuntimeLaunchBinding(e),this.agentConfig=g.getAgentConfig(),this.serverConfig=g.getServerConfig(),this.wsClient=new p(this.serverConfig),this.httpClient=new f(this.serverConfig),this.setupWebSocketListeners()}async retryPendingLaunchBindingClaim(){if(!this.pendingLaunchBindingClaim)return!0;const e=await m(this.agentConfig,this.serverConfig);if(e.status==="claimed")return this.pendingLaunchBindingClaim=!1,s.info("[AgentClient] \u542F\u52A8\u7ED1\u5B9A\u8865\u8BA4\u9886\u6210\u529F\uFF0C\u7EE7\u7EED\u6CE8\u518C\u6D41\u7A0B"),this.applyLaunchBinding(e.binding),!0;if(e.status==="missing")return this.pendingLaunchBindingClaim=!1,this.serverConfig.runtimeBridgeBaseUrl=void 0,s.warn("[AgentClient] \u542F\u52A8\u7ED1\u5B9A\u8865\u8BA4\u9886\u672A\u627E\u5230\u5F85\u8BA4\u9886\u8BB0\u5F55\uFF0C\u6309\u65E0\u7ED1\u5B9A\u6A21\u5F0F\u7EE7\u7EED\u6CE8\u518C"),!1;const t=e.status==="unreachable"?e.message:e.reason;return s.warn("[AgentClient] \u542F\u52A8\u7ED1\u5B9A\u8865\u8BA4\u9886\u5931\u8D25\uFF0C\u4FDD\u7559\u6302\u8D77\u72B6\u6001\u7B49\u5F85\u4E0B\u6B21\u6CE8\u518C\u91CD\u8BD5: %s",t),!1}setupWebSocketListeners(){this.wsClient.on("directMessage",e=>{this.handleIncomingDm(e)}),this.wsClient.on("groupMessage",e=>{this.handleIncomingGroup(e)}),this.wsClient.on("meetingMessage",e=>{this.handleIncomingMeeting(e)}),this.wsClient.on("systemNotify",e=>{this.systemNotifyHandler?.(e)}),this.wsClient.on("profileInfo",e=>{s.info(`[AgentClient] WebSocket profileInfo \u4E8B\u4EF6\u89E6\u53D1\uFF0CdisplayName: ${e.displayName}`),this.handleProfileInfo(e)}),this.wsClient.on("agentConfig",e=>{s.info("[AgentClient] WebSocket agentConfig \u4E8B\u4EF6\u89E6\u53D1"),this.configHandler&&this.configHandler(e??{})}),this.wsClient.on("agentStatus",e=>{s.info(`[AgentClient] WebSocket agentStatus \u4E8B\u4EF6\u89E6\u53D1: ${e.status}`)}),this.wsClient.on("disconnected",(e,t)=>{const n=t?.toString()||"";s.warn("[AgentClient] WebSocket \u65AD\u5F00\u8FDE\u63A5: code=%s, reason=%s, agentId=%s, \u6B63\u5728\u81EA\u52A8\u91CD\u8FDE",e,n,this.agentId)}),this.wsClient.on("error",e=>{s.error("[AgentClient] WebSocket \u9519\u8BEF: %s, stack=%s",e.message,e.stack)}),this.wsClient.on("reconnectFailed",()=>{s.error("[AgentClient] \u91CD\u8FDE\u5931\u8D25\uFF08\u5DF2\u8FBE\u91CD\u8BD5\u4E0A\u9650\uFF09\uFF0C\u505C\u6B62\u6D88\u606F\u5FAA\u73AF, agentId=%s",this.agentId),this.stop()}),this.wsClient.on("tokenRejected",()=>{s.error("[AgentClient] runtime token \u88AB 1008 \u62D2\u7EDD\u4E14\u5237\u65B0\u65E0\u53D8\u5316\uFF0C\u8FDB\u5165\u6162\u901F\u91CD\u8BD5\u7B49\u5F85\u65B0 token \u7B7E\u53D1: agentId=%s",this.agentId)}),this.wsClient.on("tokenRefreshFailed",e=>{s.error("[AgentClient] runtime token \u5237\u65B0\u8FDE\u7EED\u5931\u8D25 %s \u6B21\uFF0C\u8FDB\u5165\u6162\u901F\u91CD\u8BD5\u7B49\u5F85 bridge \u6062\u590D: agentId=%s",e,this.agentId)})}async register(){return s.info("[AgentClient] \u6B63\u5728\u6CE8\u518C Agent..."),await this.retryPendingLaunchBindingClaim(),this.hasPresetAgentId()?await this.registerWithExistingAgentId():await this.registerAsNewAgent()}hasPresetAgentId(){return!!(this.agentConfig.agentId&&this.agentConfig.agentId.trim().length>0)}async registerWithExistingAgentId(){const e=this.agentConfig.agentId;if(!e)throw new Error("Preset agentId is missing");this.agentId=e.trim();let t;try{t=await this.getProfileByAgentId(this.agentId)}catch(r){throw s.error("[AgentClient] getProfileByAgentId \u5931\u8D25 (presetAgentId=%s): %s",this.agentId,r instanceof Error?r.message:String(r)),r}this.displayName=t.displayName,this.projectId=t.projectId||null,s.info(`[AgentClient] \u4F7F\u7528\u9884\u8BBE AgentID \u7ED1\u5B9A\u5B9E\u4F8B: ${this.displayName} (${this.agentId})`),s.info(`[AgentClient] \u6240\u5C5E\u9879\u76EE: ${this.projectId||"(\u672A\u8BBE\u7F6E)"}`);try{await this.wsClient.connect(this.agentId)}catch(r){throw s.error("[AgentClient] WebSocket \u8FDE\u63A5\u5931\u8D25 (agentId=%s): %s",this.agentId,r instanceof Error?r.message:String(r)),r}s.info("[AgentClient] WebSocket \u8FDE\u63A5\u5DF2\u5EFA\u7ACB\uFF0CAgent \u73B0\u5728\u5DF2\u4E0A\u7EBF"),this.initializeStatusReporter();const n=await this.getProfileByAgentId(this.agentId);return this.displayName=n.displayName,this.projectId=n.projectId||null,u(n.roleName||"unknown-role",n.instanceName||this.agentId),{agentId:this.agentId,displayName:this.displayName,status:n.isOnline?"online":"offline",projectId:n.projectId,workspacePath:n.workspacePath,runtimeStatus:n.runtimeStatus,runtimeSessionId:n.runtimeSessionId}}async registerAsNewAgent(){const e=await this.httpClient.callTool("register",{roleName:this.agentConfig.roleName,projectId:this.agentConfig.projectId,workspacePath:this.agentConfig.workspacePath,prompt:this.agentConfig.prompt,runtimeBridgeBaseUrl:this.serverConfig.runtimeBridgeBaseUrl}),t=e.agentId;if(!t)throw new Error("Registration failed: agentId was not returned");return this.agentId=t,this.displayName=e.displayName,this.projectId=e.projectId||null,u(this.agentConfig.roleName||"unknown-role",e.instanceName||t),s.info(`[AgentClient] \u6CE8\u518C\u6210\u529F: ${this.displayName} (${this.agentId})`),s.info(`[AgentClient] \u72B6\u6001: ${e.status}`),s.info(`[AgentClient] \u6240\u5C5E\u9879\u76EE: ${this.projectId||"(\u672A\u8BBE\u7F6E)"}`),await this.wsClient.connect(this.agentId),s.info("[AgentClient] WebSocket \u8FDE\u63A5\u5DF2\u5EFA\u7ACB\uFF0CAgent \u73B0\u5728\u5DF2\u4E0A\u7EBF"),this.initializeStatusReporter(),e.isExisting===!1&&this.newCharacterHandler&&this.newCharacterHandler(),e}async unregister(){s.info("[AgentClient] \u6B63\u5728\u6CE8\u9500 Agent..."),this.agentId&&await this.httpClient.callTool("unregister",{agentId:this.agentId}),this.stopRuntimeTokenRefresh(),this.wsClient.disconnect(),this.agentId=null,this.displayName=null,this.projectId=null,this.isRunning=!1,s.info("[AgentClient] \u5DF2\u6CE8\u9500")}async discoverColleagues(){return await this.httpClient.callTool("discover_colleague",{agentId:this.agentId})}async discoverGroupRooms(){return this.ensureRegistered(),await this.httpClient.callTool("discover_group_rooms",{agentId:this.agentId})}async hireColleague(e){return this.ensureRegistered(),await this.httpClient.callTool("hire_colleague",{...e,agentId:this.agentId})}async callAgentScopedTool(e,t){this.ensureRegistered();const n={...t,agentId:this.agentId};if(e==="create_meeting"){const r=typeof t.waitTimeoutMs=="number"?t.waitTimeoutMs:Number.NaN,i=Number.isFinite(r)&&r>0?Math.min(r,C):C;return await this.httpClient.callToolOnce(e,{...n,waitTimeoutMs:i},0)}return await this.httpClient.callTool(e,n)}async reportMemoryStats(e){await this.callAgentScopedTool("report_memory_stats",{memoryStats:e})}async sendGroupMessage(e,t,n){this.ensureRegistered();const r=t||this.projectId||this.agentConfig.projectId;return await this.httpClient.callTool("send_group_message",{agentId:this.agentId,projectId:r,roomId:n,content:e})}async sendDirectMessage(e,t,n=!1,r,i){this.ensureRegistered();const a={agentId:this.agentId,targetId:e,content:t,requireReply:n,waitReply:n,replyToCallId:r};if(typeof i=="number"&&i>0&&(a.timeoutMs=i),n){const c=typeof i=="number"&&i>0?i+3e4:0;return await this.httpClient.callToolOnce("send_dm",a,c)}return await this.httpClient.callTool("send_dm",a)}async sendCallAndWaitReply(e,t,n=6e4){const r=await this.sendDirectMessage(e,t,!0,void 0,n);if(r.reply)return r.reply;throw new Error("No reply received for call-style direct message before timeout")}async replyToCall(e,t,n){return await this.sendDirectMessage(t,n,!1,e)}async getDmHistory(e,t=50,n){this.ensureRegistered();const r={agentId:this.agentId,targetUserId:e,limit:t};return n&&(r.since=n),await this.httpClient.callTool("get_dm_history",r)}async getGroupHistory(e=50,t,n){if(this.ensureRegistered(),t){const o={projectId:this.projectId||this.agentConfig.projectId,roomId:t,limit:e};return n&&(o.since=n),await this.httpClient.callTool("get_group_history",o)}const r=await this.discoverGroupRooms(),i=this.projectId||this.agentConfig.projectId,a=this.collectRoomIds(r,i);if(a.length===0)return{messages:[],count:0};const h=(await Promise.all(a.map(async o=>{const l={projectId:i,roomId:o,limit:e};return n&&(l.since=n),await this.httpClient.callTool("get_group_history",l)}))).flatMap(o=>o.messages).sort((o,l)=>new Date(o.timestamp).getTime()-new Date(l.timestamp).getTime());return{messages:h,count:h.length}}async fetchUnreadMessages(e={}){this.ensureRegistered();const t=this.projectId||this.agentConfig.projectId,n={agentId:this.agentId,blockIfEmpty:e.blockIfEmpty??!1};e.since&&(n.since=e.since),e.blockTimeoutMs&&e.blockTimeoutMs>0&&(n.blockTimeoutMs=e.blockTimeoutMs),e.preemptiveJoinWaitMs!==void 0&&e.preemptiveJoinWaitMs!==null&&e.preemptiveJoinWaitMs>=0&&(n.preemptiveJoinWaitMs=e.preemptiveJoinWaitMs);const r=e.includePipelineTasks?"poll_message":"get_dm_messages";s.info("[AgentClient] fetchUnreadMessages \u5165\u53E3: tool=%s, blockIfEmpty=%s, blockTimeoutMs=%s, pollMessageTimeoutMs=%s, skipGroupMessages=%s, preemptiveJoinWaitMs=%s, agentId=%s",r,String(e.blockIfEmpty??!1),String(e.blockTimeoutMs??"-"),String(e.pollMessageTimeoutMs??"-"),String(e.skipGroupMessages??!1),String(e.preemptiveJoinWaitMs??"-"),this.agentId);const i=await this.fetchDirectMessagesWithRecovery(r,n,e.pollMessageTimeoutMs,e.propagatePollTimeout===!0);if(s.info("[AgentClient] fetchUnreadMessages \u79C1\u4FE1\u9636\u6BB5\u8FD4\u56DE: %s \u6761",Array.isArray(i.messages)?i.messages.length:0),e.skipGroupMessages)return s.info("[AgentClient] \u4F1A\u8BAE\u5FEB\u901F hydrate \u5DF2\u53D6\u5F97\u79C1\u4FE1\u54CD\u5E94\uFF0C\u8DF3\u8FC7\u7FA4\u804A\u53D1\u73B0\u5E76\u7ACB\u5373\u8FD4\u56DE: directMessages=%s",Array.isArray(i.messages)?i.messages.length:0),{directMessages:Array.isArray(i.messages)?i.messages:[],groupMessages:[]};let a;try{a=await this.discoverGroupRooms()}catch(o){s.warn("[AgentClient] \u53D1\u73B0\u7FA4\u623F\u95F4\u5931\u8D25\uFF0C\u672C\u6B21\u6309\u65E0\u7FA4\u6D88\u606F\u5904\u7406\uFF08\u5DF2\u53D6\u5230\u7684\u79C1\u4FE1\u4E0D\u53D7\u5F71\u54CD\uFF09: %s",o instanceof Error?o.message:String(o)),a={groups:[]}}const c=this.collectRoomIds(a,t),h=await Promise.all(c.map(async o=>{const l={agentId:this.agentId,projectId:t,roomId:o};e.since&&(l.since=e.since);try{return await this.httpClient.callTool("get_group_messages",l)}catch(d){return s.warn("[AgentClient] \u8DF3\u8FC7\u7FA4\u623F\u95F4\u672A\u8BFB\u8865\u62C9\u5931\u8D25: roomId=%s, error=%s",o,d instanceof Error?d.message:String(d)),{messages:[],currentReadPos:0,hasMore:!1}}}));return{directMessages:Array.isArray(i.messages)?i.messages:[],groupMessages:h.flatMap(o=>this.normalizeGroupMessages(o)).sort((o,l)=>new Date(o.timestamp).getTime()-new Date(l.timestamp).getTime())}}async markDmRead(e){if(e.length===0)return new Set;this.ensureRegistered();try{const t=await this.httpClient.callTool("mark_dm_read",{agentId:this.agentId,msgIds:e}),n=new Set(Array.isArray(t?.deliverableMsgIds)?t.deliverableMsgIds:[]),r=e.filter(i=>!n.has(i));return r.length>0?s.warn("[AgentClient] mark_dm_read \u786E\u8BA4\u540E\u5C06\u6709 %d \u6761\u6D88\u606F\u88AB\u4E22\u5F03\u4E0D\u4EA4\u4ED8: \u8BF7\u6C42=%s, \u53EF\u4EA4\u4ED8=%s, \u88AB\u4E22\u5F03=%s",r.length,JSON.stringify(e),JSON.stringify([...n]),JSON.stringify(r)):s.info("[AgentClient] mark_dm_read \u786E\u8BA4\u5B8C\u6210: %d \u6761\u5168\u90E8\u53EF\u4EA4\u4ED8",e.length),n}catch(t){throw s.warn("[AgentClient] mark_dm_read \u8BF7\u6C42\u5931\u8D25\uFF08\u5C06\u964D\u7EA7\u4E3A\u76F4\u63A5\u4EA4\u4ED8\uFF09: %s",t instanceof Error?t.message:String(t)),t}}async markGroupRead(e,t){if(t.length===0)return new Set;this.ensureRegistered();const n=await this.httpClient.callTool("mark_group_read",{agentId:this.agentId,roomId:e,msgIds:t});return new Set(Array.isArray(n?.deliverableMsgIds)?n.deliverableMsgIds:[])}async markNotificationRead(e){if(e.length!==0){this.ensureRegistered();try{await this.httpClient.callTool("mark_notification_read",{agentId:this.agentId,msgIds:e})}catch{}}}async markMeetingRead(e){if(e.length!==0){this.ensureRegistered();try{await this.httpClient.callTool("mark_meeting_read",{agentId:this.agentId,msgIds:e})}catch{}}}async fetchBrowserListenerEvents(){const e=this.serverConfig.runtimeBridgeBaseUrl,t=this.agentId;if(!e||!t)return s.info("[AgentClient] fetchBrowserListenerEvents \u8DF3\u8FC7: bridgeBaseUrl=%s, agentId=%s",e||"(\u7A7A)",t||"(\u7A7A)"),[];try{const n=`${e}/runtime/browser-listeners/${encodeURIComponent(t)}/events`,r=this.serverConfig.runtimeAccessToken||"";s.debug("[AgentClient] \u62C9\u53D6\u76D1\u542C\u5668\u4E8B\u4EF6: url=%s, tokenLen=%d",n,r.length);const i=await fetch(n,{method:"GET",headers:{"X-Runtime-Token":r},signal:AbortSignal.timeout(3e3)});if(!i.ok)return s.warn("[AgentClient] \u62C9\u53D6\u76D1\u542C\u5668\u4E8B\u4EF6\u5931\u8D25: HTTP %s, url=%s",i.status,n),[];const a=await i.json();return!a.ok||!Array.isArray(a.events)?(s.warn("[AgentClient] \u62C9\u53D6\u76D1\u542C\u5668\u4E8B\u4EF6\u54CD\u5E94\u5F02\u5E38: ok=%s, eventsType=%s",a.ok,Array.isArray(a.events)?"array":typeof a.events),[]):(s.debug("[AgentClient] \u62C9\u53D6\u76D1\u542C\u5668\u4E8B\u4EF6\u6210\u529F: %d \u6761\u4E8B\u4EF6",a.events.length),a.events)}catch(n){return s.warn("[AgentClient] \u62C9\u53D6\u76D1\u542C\u5668\u4E8B\u4EF6\u5F02\u5E38: %s",n instanceof Error?n.message:String(n)),[]}}async fetchPluginEvents(){const e=this.serverConfig.runtimeBridgeBaseUrl,t=this.agentId;if(!e||!t)return{revision:0,events:[],catalog:null,compactionSeq:0};try{const n=`${e}/runtime/plugin-events/${encodeURIComponent(t)}/events`,r=this.serverConfig.runtimeAccessToken||"",i=await fetch(n,{method:"GET",headers:{"X-Runtime-Token":r},signal:AbortSignal.timeout(3e3)});if(!i.ok)return s.warn("[AgentClient] \u62C9\u53D6\u63D2\u4EF6\u4E8B\u4EF6\u5931\u8D25: HTTP %s, url=%s",i.status,n),{revision:0,events:[],catalog:null,compactionSeq:0};const a=await i.json();return!a.ok||!Array.isArray(a.events)?(s.warn("[AgentClient] \u62C9\u53D6\u63D2\u4EF6\u4E8B\u4EF6\u54CD\u5E94\u5F02\u5E38: ok=%s",String(a.ok)),{revision:0,events:[],catalog:null,compactionSeq:0}):(s.debug("[AgentClient] \u62C9\u53D6\u63D2\u4EF6\u4E8B\u4EF6\u6210\u529F: %d \u6761\u4E8B\u4EF6, revision=%s, catalog=%s, compactionSeq=%s",a.events.length,String(a.revision??0),a.catalog?`${a.catalog.plugins.length} \u4E2A\u63D2\u4EF6`:"null",String(a.compactionSeq??0)),{revision:a.revision??0,events:a.events,catalog:a.catalog??null,compactionSeq:typeof a.compactionSeq=="number"&&Number.isFinite(a.compactionSeq)?a.compactionSeq:0})}catch(n){return s.warn("[AgentClient] \u62C9\u53D6\u63D2\u4EF6\u4E8B\u4EF6\u5F02\u5E38: %s",n instanceof Error?n.message:String(n)),{revision:0,events:[],catalog:null,compactionSeq:0}}}async notifyBridgeForceMessage(){const e=this.serverConfig.runtimeBridgeBaseUrl,t=this.agentId;if(!(!e||!t))try{const n=`${e}/runtime/sessions/${encodeURIComponent(t)}/notify-force-message`,r=this.serverConfig.runtimeAccessToken||"",i=await fetch(n,{method:"POST",headers:{"X-Runtime-Token":r},signal:AbortSignal.timeout(3e3)});i.ok||s.warn("[AgentClient] \u901A\u77E5 bridge \u5F3A\u5236\u6D88\u606F\u5931\u8D25: HTTP %s, url=%s",i.status,n)}catch(n){s.warn("[AgentClient] \u901A\u77E5 bridge \u5F3A\u5236\u6D88\u606F\u5F02\u5E38: %s",n instanceof Error?n.message:String(n))}}async fetchDirectMessagesWithRecovery(e,t,n,r=!1){if(e==="poll_message"){s.info("[AgentClient] fetchDirectMessagesWithRecovery \u5165\u53E3: tool=poll_message, pollMessageTimeoutMs=%s, agentId=%s",String(n??"(\u9ED8\u8BA4)"),String(t?.agentId??""));try{const i=await this.httpClient.callToolOnce(e,t,n);return s.info("[AgentClient] fetchDirectMessagesWithRecovery poll_message \u6210\u529F\u8FD4\u56DE: %s \u6761",Array.isArray(i?.messages)?i.messages.length:0),i}catch(i){if(this.isRecoverableLongPollError(i)){if(r)throw new T(i instanceof Error?i.message:String(i));return s.warn("[AgentClient] poll_message \u5355\u6B21\u957F\u8F6E\u8BE2\u8D85\u65F6\uFF0C\u6309\u7A7A\u7ED3\u679C\u9000\u907F\u540E\u7EE7\u7EED\u7B49\u5F85:",i),{messages:[]}}throw i}}return await this.httpClient.callTool(e,t)}isRecoverableLongPollError(e){return e instanceof Error?/MCP tool poll_message call failed: 503(?:\s|$)/.test(e.message)||/MCP tool poll_message timed out after \d+ms/.test(e.message):!1}normalizeGroupMessages(e){return Array.isArray(e.messages)?e.messages.filter(t=>!!(t&&typeof t=="object"&&typeof t.msgId=="number"&&typeof t.senderId=="string"&&typeof t.content=="string"&&typeof t.timestamp=="string")):[]}collectRoomIds(e,t){const n=e.groups.filter(r=>r.projectId===t).map(r=>r.id);return Array.from(new Set(n))}async getProfile(){this.ensureRegistered();const e=this.agentId;if(!e)throw new Error("Agent is not registered");return{...await this.getProfileByAgentId(e),describe:this.agentConfig.describe}}async getProfileByAgentId(e){return await this.httpClient.callTool("get_profile",{agentId:e})}async getMyTasks(){return this.ensureRegistered(),await this.httpClient.callTool("my_task",{agentId:this.agentId})}async createTaskInstanceComment(e){this.ensureRegistered();const t={agentId:this.agentId,...e};return await this.httpClient.callTool("create_task_instance_comment",t)}async submitTaskResult(e,t,n){this.ensureRegistered();const r={agentId:this.agentId,nodeId:e,outputPayload:t};return n&&Array.isArray(n)&&n.length>0&&(r.changeLog=n),await this.httpClient.callTool("submit_task_result",r)}async startTaskRollback(e){return this.ensureRegistered(),await this.httpClient.callTool("start_task_rollback",{agentId:this.agentId,...e})}async finishTaskRollback(e){return this.ensureRegistered(),await this.httpClient.callTool("finish_task_rollback",{agentId:this.agentId,...e})}async rejectTask(e,t){return this.ensureRegistered(),await this.httpClient.callTool("reject_task",{agentId:this.agentId,nodeId:e,reason:t})}async terminateTask(e,t){return this.ensureRegistered(),await this.httpClient.callTool("terminate_task",{agentId:this.agentId,taskInstanceId:e,reason:t})}async getDebugLogConfig(){return await this.httpClient.callTool("get_debug_log_config",{agentId:this.agentId})}async queryDebugLogs(e){return this.ensureRegistered(),await this.httpClient.callTool("query_debug_logs",{...e})}async queryFileChangesHistory(e){return this.ensureRegistered(),await this.httpClient.callTool("query_file_changes_history",{...e})}async getRuntimeFeatures(){return await this.httpClient.fetchRuntimeFeatures()}async listLaunchConfigs(){return this.ensureRegistered(),await this.httpClient.callTool("launch_config_list",{})}async createLaunchConfig(e){return this.ensureRegistered(),await this.httpClient.callTool("launch_config_create",{...e})}async updateLaunchConfig(e){return this.ensureRegistered(),await this.httpClient.callTool("launch_config_update",{...e})}async deleteLaunchConfig(e){return this.ensureRegistered(),await this.httpClient.callTool("launch_config_delete",{configId:e})}async startLaunchConfig(e){this.ensureRegistered();const t=Math.max(0,Math.min(3e5,Number(e.wait_timeout_ms)||0));return t>0?await this.httpClient.callToolOnce("launch_config_start",e,t+6e4):await this.httpClient.callTool("launch_config_start",{...e})}async restartLaunchConfig(e){this.ensureRegistered();const t=Math.max(0,Math.min(3e5,Number(e.wait_timeout_ms)||0));return t>0?await this.httpClient.callToolOnce("launch_config_restart",e,t+6e4):await this.httpClient.callTool("launch_config_restart",{...e})}async stopLaunchConfig(e){return this.ensureRegistered(),await this.httpClient.callTool("launch_config_stop",{configId:e})}async getLaunchLogs(e){return this.ensureRegistered(),await this.httpClient.callTool("launch_config_logs",{...e})}async listLaunchRuns(){return this.ensureRegistered(),await this.httpClient.callTool("launch_config_status",{})}start(e,t){if(this.isRunning){s.warn("[AgentClient] \u6D88\u606F\u5FAA\u73AF\u5DF2\u5728\u8FD0\u884C\u4E2D");return}this.isDegradedMode||this.ensureRegistered(),this.messageHandler=e,this.profileHandler=t?.profileHandler||null,this.configHandler=t?.configHandler||null,this.systemNotifyHandler=t?.systemNotifyHandler||null,this.isRunning=!0,s.info(`[AgentClient] start() \u88AB\u8C03\u7528\uFF0CcachedProfile: ${this.cachedProfile?"\u5B58\u5728":"\u4E0D\u5B58\u5728"}, profileHandler: ${this.profileHandler?"\u5DF2\u8BBE\u7F6E":"\u672A\u8BBE\u7F6E"}, \u964D\u7EA7\u6A21\u5F0F: ${this.isDegradedMode?"\u662F":"\u5426"}`),this.cachedProfile&&this.profileHandler&&(s.info(`[AgentClient] \u5904\u7406\u7F13\u5B58\u7684 Profile \u4FE1\u606F: ${this.cachedProfile.displayName}`),this.profileHandler(this.cachedProfile),this.cachedProfile=null),t?.pollMode??!1?(s.warn("[AgentClient] \u542F\u52A8\u6D88\u606F\u4E3B\u5FAA\u73AF\uFF08HTTP\u8F6E\u8BE2\u6A21\u5F0F - \u4E0D\u63A8\u8350\uFF09"),this.messageLoop()):s.info("[AgentClient] \u542F\u52A8\u6D88\u606F\u4E3B\u5FAA\u73AF\uFF08WebSocket\u63A8\u9001\u6A21\u5F0F - \u63A8\u8350\uFF09")}stop(){this.isRunning=!1,this.pollTimer&&(clearTimeout(this.pollTimer),this.pollTimer=null),this.stopRuntimeTokenRefresh(),s.info("[AgentClient] \u6D88\u606F\u4E3B\u5FAA\u73AF\u5DF2\u505C\u6B62")}async messageLoop(){for(;this.isRunning;)try{await this.delay(I)}catch(e){s.error("[AgentClient] \u6D88\u606F\u5FAA\u73AF\u9519\u8BEF:",e),await this.delay(5e3)}}handleIncomingDm(e){e.senderId!==this.agentId&&this.processMessage(e)}handleIncomingGroup(e){e.senderId!==this.agentId&&this.processMessage(e)}handleIncomingMeeting(e){!e||e.senderId===this.agentId||this.processMessage(e)}handleProfileInfo(e){s.info(`[AgentClient] \u6536\u5230 Profile \u4FE1\u606F: ${e.displayName} (${e.roleName})`),e.projectId&&(this.projectId=e.projectId,s.info(`[AgentClient] \u66F4\u65B0\u6240\u5C5E\u9879\u76EE: ${this.projectId}`)),e.roleName&&e.roleName!==this.agentConfig.roleName&&(s.info(`[AgentClient] \u540C\u6B65\u89D2\u8272\u540D: "${this.agentConfig.roleName||"(\u7A7A)"}" -> "${e.roleName}"`),this.agentConfig.roleName=e.roleName),e.roleName&&u(e.roleName,e.instanceName||this.agentId||""),this.profileHandler?this.profileHandler(e):(s.info("[AgentClient] profileHandler \u672A\u8BBE\u7F6E\uFF0C\u7F13\u5B58 Profile \u4FE1\u606F"),this.cachedProfile=e)}async processMessage(e){if(!this.messageHandler)return;const t=typeof e.msgId=="string";s.info(`[AgentClient] \u6536\u5230${t?"\u79C1\u4FE1":"\u7FA4\u6D88\u606F"}\u6765\u81EA ${e.senderName}: ${e.content.substring(0,50)}...`);try{const n=await this.messageHandler(e);if(t){const r=e;r.requireReply&&r.callId&&await this.replyToCall(r.callId,r.senderId,n||"\u5DF2\u6536\u5230\u6D88\u606F\uFF0C\u6B63\u5728\u5904\u7406\u4E2D...")}}catch(n){const r=typeof e.msgId=="string";if(s.error("[AgentClient] \u5904\u7406\u6D88\u606F\u5931\u8D25: type=%s, senderId=%s, senderName=%s, msgId=%s, error=%s",r?"\u79C1\u4FE1":"\u7FA4\u6D88\u606F",e.senderId,e.senderName,e.msgId,n instanceof Error?n.message:String(n)),r){const i=e;i.requireReply&&i.callId&&await this.replyToCall(i.callId,i.senderId,`\u5904\u7406\u5931\u8D25: ${n}`)}}}ensureRegistered(){if(!this.agentId)throw new Error("Agent is not registered")}delay(e){return new Promise(t=>{this.pollTimer=setTimeout(t,e)})}onNewCharacter(e){this.newCharacterHandler=e}getState(){return{agentId:this.agentId,displayName:this.displayName,projectId:this.projectId,isConnected:this.wsClient.isConnected(),isRunning:this.isRunning}}getAgentConfig(){return this.agentConfig}getServerConfig(){return this.serverConfig}reloadConfig(){g.loadConfig(),this.agentConfig=g.getAgentConfig(),s.info(`[AgentClient] \u914D\u7F6E\u5DF2\u91CD\u65B0\u52A0\u8F7D\uFF0C\u89D2\u8272: ${this.agentConfig.roleName}`)}enterDegradedMode(){this.isDegradedMode=!0,s.warn("[AgentClient] \u8FDB\u5165\u964D\u7EA7\u6A21\u5F0F\uFF0C\u5C06\u5728\u540E\u53F0\u6301\u7EED\u5C1D\u8BD5\u91CD\u8FDE")}exitDegradedMode(){this.isDegradedMode=!1,s.info("[AgentClient] \u9000\u51FA\u964D\u7EA7\u6A21\u5F0F")}isInDegradedMode(){return this.isDegradedMode}async retryRegistrationInBackground(e,t){let n=0;(async()=>{for(;this.isDegradedMode;)try{s.info(`[AgentClient] \u964D\u7EA7\u6A21\u5F0F\uFF1A\u5C1D\u8BD5\u91CD\u65B0\u6CE8\u518C (${n+1}/${t===-1?"\u65E0\u9650":t})`);const i=await this.register();s.info(`[AgentClient] \u964D\u7EA7\u6A21\u5F0F\uFF1A\u6CE8\u518C\u6210\u529F - ${i.displayName} (${i.agentId})`),this.exitDegradedMode(),this.messageHandler&&this.start(this.messageHandler);return}catch(i){n++;const a=i instanceof Error?i.message:String(i);if(s.warn(`[AgentClient] \u964D\u7EA7\u6A21\u5F0F\uFF1A\u6CE8\u518C\u5931\u8D25 (${n}/${t===-1?"\u65E0\u9650":t}): ${a}`),t>0&&n>=t){s.error("[AgentClient] \u964D\u7EA7\u6A21\u5F0F\uFF1A\u8FBE\u5230\u6700\u5927\u91CD\u8BD5\u6B21\u6570\uFF0C\u505C\u6B62\u91CD\u8FDE"),this.isDegradedMode=!1;return}await new Promise(c=>setTimeout(c,e))}})().catch(i=>{s.error("[AgentClient] \u964D\u7EA7\u6A21\u5F0F\u540E\u53F0\u91CD\u8BD5\u5FAA\u73AF\u5F02\u5E38\u9000\u51FA: error=%s, stack=%s",i instanceof Error?i.message:String(i),i instanceof Error?i.stack:"(no stack)")})}initializeStatusReporter(){if(!this.agentId){s.warn("[AgentClient] \u65E0\u6CD5\u521D\u59CB\u5316\u72B6\u6001\u62A5\u544A\u5668\uFF1AagentId \u4E3A\u7A7A");return}this.statusReporter=new A({agentId:this.agentId,sendStatusUpdate:e=>{this.wsClient.send({type:"AGENT_STATUS",data:e,timestamp:new Date().toISOString()})}}),w(e=>this.reportMcpNodeLog(e)),this.startRuntimeTokenRefresh(),s.info("[AgentClient] \u72B6\u6001\u62A5\u544A\u5668\u5DF2\u521D\u59CB\u5316")}startRuntimeTokenRefresh(){this.stopRuntimeTokenRefresh();const e=this.serverConfig.runtimeTokenRefreshIntervalMs;if(!e||e<=0){s.warn("[AgentClient] runtimeTokenRefreshIntervalMs \u672A\u914D\u7F6E\u6216\u65E0\u6548\uFF0C\u8DF3\u8FC7\u4E3B\u52A8\u7EED\u671F");return}const t=this.agentId;if(!t){s.warn("[AgentClient] agentId \u4E3A\u7A7A\uFF0C\u8DF3\u8FC7\u4E3B\u52A8\u7EED\u671F");return}this.runtimeTokenRefreshTimer=setInterval(async()=>{try{await this.httpClient.refreshRuntimeAccessToken(t)&&s.info("[AgentClient] runtimeAccessToken \u5DF2\u4E3B\u52A8\u7EED\u671F")}catch(n){s.warn("[AgentClient] \u4E3B\u52A8\u7EED\u671F runtimeAccessToken \u5931\u8D25: %s",n instanceof Error?n.message:String(n)),n instanceof Error&&n.stack&&s.warn("[AgentClient] \u4E3B\u52A8\u7EED\u671F\u5F02\u5E38\u5806\u6808:",n.stack)}},e),this.runtimeTokenRefreshTimer.unref?.(),s.info(`[AgentClient] runtime token \u4E3B\u52A8\u7EED\u671F\u5DF2\u542F\u52A8\uFF0C\u95F4\u9694 ${e}ms`)}stopRuntimeTokenRefresh(){this.runtimeTokenRefreshTimer&&(clearInterval(this.runtimeTokenRefreshTimer),this.runtimeTokenRefreshTimer=null)}reportMcpNodeLog(e){const t=this.wsClient;!this.agentId||!this.wsClient.isConnected()||typeof t.sendMcpNodeLog!="function"||t.sendMcpNodeLog(e)}getStatusReporter(){return this.statusReporter}}export{N as AgentClient,T as PollLongPollTimeoutError};
2
2
 
@@ -47,9 +47,9 @@ export declare class McpServer {
47
47
 
48
48
  private cachedPluginCatalog;
49
49
 
50
- private pluginCatalogDeliveredRevision;
51
- private pluginCatalogDeliveredCompactionSeq;
50
+ private deliveredPluginNames;
52
51
  private pluginCatalogDrainCompactionSeq;
52
+ private pluginCatalogLastSeenCompactionSeq;
53
53
  private static readonly MEETING_HYDRATE_RETRY_COUNT;
54
54
  private static readonly MEETING_HYDRATE_RETRY_DELAY_MS;
55
55
 
@@ -177,7 +177,6 @@ export declare class McpServer {
177
177
 
178
178
  private recordMessageTokenUsage;
179
179
  private handleHireColleague;
180
- private handleHireColleaguesBatch;
181
180
  private handleSendPrivate;
182
181
  private handleCreateTaskInstanceComment;
183
182
 
@@ -1,13 +1,13 @@
1
- import P from"node:fs";import S from"node:path";import{Server as K}from"@modelcontextprotocol/sdk/server/index.js";import{StdioServerTransport as V}from"@modelcontextprotocol/sdk/server/stdio.js";import{CallToolRequestSchema as X,ListToolsRequestSchema as Z}from"@modelcontextprotocol/sdk/types.js";import{AgentClient as Q,PollLongPollTimeoutError as ee}from"./agent-client.js";import{normalizeServerHttpBase as te}from"./http-client.js";import{MCP_SERVER_NAME as re,MCP_SERVER_VERSION as se,REGISTER_MAX_RETRIES as O,REGISTER_RETRY_INTERVAL_MS as ie,DEGRADED_MODE_ENABLED as H,DEGRADED_MODE_RETRY_INTERVAL_MS as ne,DEGRADED_MODE_MAX_RETRIES as oe}from"./constants.js";import{resolveAcodeDataHome as U}from"./config.js";import{logger as o}from"./logger.js";import{meetingDebugFingerprints as D,meetingDebugLog as E}from"./meeting-debug-log.js";import{MCP_TOOLS as F,MEMORY_TOOL_NAMES as x,LAUNCH_CONFIG_TOOL_NAMES as q,HIRE_TOOL_NAMES as W}from"./mcp-tools.js";import{MessageBuffer as ae}from"./message-buffer.js";import{ContextManager as le}from"./context-manager.js";import{MemoryCapacityError as ce,MemoryStore as L}from"./memory-store.js";import{ServerMemoryStore as me}from"./server-memory-store.js";const ue=3e3,B=10,z=(()=>{const I=Number.parseInt(process.env.AWS_MCP_FILE_CHANGE_RENOTIFY_COOLDOWN_MS||"",10);return Number.isFinite(I)&&I>0?I:30*6e4})(),G=500,de=30,he=new Set(["<",">",":",'"',"/","\\","|","?","*"]),Y=20*1024*1024,ge={".pdf":"application/pdf",".txt":"text/plain",".md":"text/markdown",".csv":"text/csv",".json":"application/json",".html":"text/html",".xml":"application/xml",".doc":"application/msword",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".xls":"application/vnd.ms-excel",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",".ppt":"application/vnd.ms-powerpoint",".pptx":"application/vnd.openxmlformats-officedocument.presentationml.presentation",".zip":"application/zip",".gz":"application/gzip",".tar":"application/x-tar",".7z":"application/x-7z-compressed",".rar":"application/vnd.rar",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".svg":"image/svg+xml",".mp3":"audio/mpeg",".mp4":"video/mp4"};function pe(I){return ge[S.extname(I).toLowerCase()]||"application/octet-stream"}function fe(I){return(I||"").replace(/[|[\]\r\n]/g,"_").trim()||"\u6587\u4EF6"}function ye(I){if(!Number.isFinite(I)||I<=0)return"0 B";const e=["B","KB","MB","GB"],t=Math.min(e.length-1,Math.floor(Math.log(I)/Math.log(1024)));return`${Number.parseFloat((I/1024**t).toFixed(2))} ${e[t]}`}function _e(I){return`[\u6587\u4EF6: ${fe(I.name)} | ${I.url} | ${I.mediaType||"application/octet-stream"} | ${ye(I.size)}]`}class R{server;agentClient;messageBuffer;memoryStore;roleMemoryStore;sessionContextMemoryStore;initialRoleName="";hasRoleName=!1;contextManager;isSubAgent;fileChangeNotifyHistory=new Map;featuresCache=null;static FEATURES_CACHE_TTL_MS=5e3;static LAUNCH_ITEM_FEATURE_KEY="agentSys.launchItem";static LAUNCH_TOOLS_ENV_KEY="AWS_LAUNCH_CONFIG_TOOLS";static HIRE_FEATURE_KEY="agentSys.hire";static HIRE_TOOLS_ENV_KEY="AWS_HIRE_TOOLS";leaseRenewalTimer=null;activeLeaseUris=new Set;static LEASE_DURATION_MINUTES=10;static LEASE_RENEW_INTERVAL_MS=6e4;profileSynced=!1;urgentMeetingHydrateRequested=!1;cachedPluginCatalog=null;pluginCatalogDeliveredRevision=-1;pluginCatalogDeliveredCompactionSeq=-1;pluginCatalogDrainCompactionSeq=0;static MEETING_HYDRATE_RETRY_COUNT=3;static MEETING_HYDRATE_RETRY_DELAY_MS=150;static MEETING_HYDRATE_TIMEOUT_REARM_DELAY_MS=1e4;meetingHydrateTimeoutRearmDelayMs=R.MEETING_HYDRATE_TIMEOUT_REARM_DELAY_MS;static MEETING_HYDRATE_POLL_TIMEOUT_MS=65e3;static MEETING_PREEMPTIVE_JOIN_WAIT_MS=45e3;pendingPollMessage=null;syncRoleMemoryStore(e){if(o.info(`[McpServer] syncRoleMemoryStore \u88AB\u8C03\u7528: displayName=${e.displayName}, roleName="${e.roleName??"(\u7A7A)"}", id=${e.id}`),!e.roleName){o.warn(`[McpServer] syncRoleMemoryStore: profile.roleName \u4E3A\u7A7A\uFF0ChasRoleName \u4FDD\u6301 false\u3002profile=${JSON.stringify({id:e.id,displayName:e.displayName,roleName:e.roleName,instanceName:e.instanceName})}`);return}const t=R.sanitizeRoleDirectoryName(e.roleName);this.hasRoleName=!0,t!==this.initialRoleName&&(o.info(`[McpServer] \u89D2\u8272\u76EE\u5F55\u4E0E\u521D\u59CB\u503C\u4E0D\u4E00\u81F4\uFF0C\u91CD\u5EFA roleMemoryStore: "${this.initialRoleName}" -> "${t}"`),this.roleMemoryStore=new L(R.buildRoleMemoryStorePath(t)),this.initialRoleName=t)}maybeSyncPermanentMemoryToServer(){this.doMaybeSyncPermanentMemoryToServer().catch(e=>{o.warn("[McpServer] maybeSyncPermanentMemoryToServer \u5F02\u5E38: %s, stack=%s",e instanceof Error?e.message:String(e),e instanceof Error?e.stack:"(no stack)")})}async doMaybeSyncPermanentMemoryToServer(){o.info("[McpServer] maybeSyncPermanentMemoryToServer \u5F00\u59CB\uFF0CinitialRoleName="+this.initialRoleName);let e;try{e=await this.memoryStore.getStats()}catch(n){o.warn("[McpServer] \u83B7\u53D6 server \u8BB0\u5FC6\u7EDF\u8BA1\u5931\u8D25\uFF0C\u8DF3\u8FC7\u540C\u6B65:",n instanceof Error?n.message:n);return}const t=e.by_type.project_memory?.count??0;o.info(`[McpServer] server memory \u8BA1\u6570=${t}`);let r=[];try{r=await this.roleMemoryStore.listByType("project_memory"),o.info(`[McpServer] \u89D2\u8272\u5B50\u76EE\u5F55\u8BFB\u53D6\u5230 ${r.length} \u6761\u6C38\u4E45\u8BB0\u5FC6`)}catch(n){o.warn("[McpServer] \u8BFB\u53D6\u89D2\u8272\u5B50\u76EE\u5F55\u6C38\u4E45\u8BB0\u5FC6\u5931\u8D25:",n instanceof Error?n.message:n)}if(r.length===0){const n=S.dirname(R.buildRoleMemoryStorePath(this.initialRoleName));o.info(`[McpServer] \u5C1D\u8BD5\u4ECE\u9057\u7559\u76EE\u5F55\u8BFB\u53D6: ${n}`);try{const l=await new L(n).listByType("project_memory");l.length>0&&(o.info(`[McpServer] \u4ECE\u9057\u7559\u76EE\u5F55\u8BFB\u53D6\u5230 ${l.length} \u6761\u6C38\u4E45\u8BB0\u5FC6`),r=l)}catch(a){o.warn("[McpServer] \u8BFB\u53D6\u9057\u7559\u76EE\u5F55\u6C38\u4E45\u8BB0\u5FC6\u5931\u8D25:",a instanceof Error?a.message:a)}}if(r.length===0){o.info("[McpServer] \u672C\u5730\u4E5F\u65E0\u6C38\u4E45\u8BB0\u5FC6\uFF0C\u8DF3\u8FC7\u540C\u6B65");return}if(t>=r.length){o.info(`[McpServer] \u670D\u52A1\u7AEF\u5DF2\u6709 ${t} \u6761 >= \u672C\u5730 ${r.length} \u6761\uFF0C\u65E0\u9700\u56DE\u586B`);return}o.info(`[McpServer] \u68C0\u6D4B\u5230\u7F3A\u91CF\uFF1A\u672C\u5730 ${r.length} \u6761 > \u670D\u52A1\u7AEF ${t} \u6761\uFF0C\u5F00\u59CB\u589E\u91CF\u56DE\u586B`);let i=0,s=0;for(const n of r)try{await this.memoryStore.createMemory({memory_type:"project_memory",uri:n.uri,title:n.title,content:n.content,keywords:n.keywords,bound_files:n.bound_files,file_md5_map:n.file_md5_map,last_check_time:n.last_check_time}),i++,o.info(`[McpServer] \u540C\u6B65\u6C38\u4E45\u8BB0\u5FC6\u6210\u529F: ${n.uri}`)}catch(a){const l=a instanceof Error?a.message:String(a);l.includes("already exists")||l.includes("Memory already exists")||o.warn(`[McpServer] \u540C\u6B65\u6C38\u4E45\u8BB0\u5FC6\u5931\u8D25 (${n.uri}): ${l}`),s++}o.info(`[McpServer] \u6C38\u4E45\u8BB0\u5FC6\u540C\u6B65\u5B8C\u6210: \u6210\u529F ${i}, \u8DF3\u8FC7 ${s}, \u5171 ${r.length}`),await this.reportMemoryStatsToServer()}normalizeBoundFilePath(e){const t=String(e||"").trim().replace(/\\/g,"/");if(!t)return t;const r=t.startsWith("@/")?t.substring(1):t;return r.startsWith("./")?r:`./${r.replace(/^\/+/,"")}`}normalizeBoundFiles(e){return!e||!Array.isArray(e)?e:e.map(t=>this.normalizeBoundFilePath(String(t)))}async validateBoundFilesExist(e){if(!e||e.length===0)return;const t=process.env.AWS_WORKSPACE_PATH||process.cwd(),{access:r}=await import("node:fs/promises"),i=[];for(const s of e)try{const n=S.resolve(t,s);await r(n)}catch{i.push(s)}if(i.length>0)throw new Error(`\u7ED1\u5B9A\u7684\u6587\u4EF6\u4E0D\u5B58\u5728\uFF0C\u8BF7\u786E\u8BA4\u6587\u4EF6\u8DEF\u5F84\u6B63\u786E\u540E\u518D\u91CD\u65B0\u63D0\u4EA4:
1
+ import P from"node:fs";import S from"node:path";import{Server as K}from"@modelcontextprotocol/sdk/server/index.js";import{StdioServerTransport as V}from"@modelcontextprotocol/sdk/server/stdio.js";import{CallToolRequestSchema as X,ListToolsRequestSchema as Z}from"@modelcontextprotocol/sdk/types.js";import{AgentClient as Q,PollLongPollTimeoutError as ee}from"./agent-client.js";import{normalizeServerHttpBase as te}from"./http-client.js";import{MCP_SERVER_NAME as re,MCP_SERVER_VERSION as se,REGISTER_MAX_RETRIES as D,REGISTER_RETRY_INTERVAL_MS as ie,DEGRADED_MODE_ENABLED as H,DEGRADED_MODE_RETRY_INTERVAL_MS as ne,DEGRADED_MODE_MAX_RETRIES as oe}from"./constants.js";import{resolveAcodeDataHome as U}from"./config.js";import{logger as o}from"./logger.js";import{meetingDebugFingerprints as O,meetingDebugLog as E}from"./meeting-debug-log.js";import{MCP_TOOLS as F,MEMORY_TOOL_NAMES as x,LAUNCH_CONFIG_TOOL_NAMES as W,HIRE_TOOL_NAMES as q}from"./mcp-tools.js";import{MessageBuffer as ae}from"./message-buffer.js";import{ContextManager as le}from"./context-manager.js";import{MemoryCapacityError as ce,MemoryStore as L}from"./memory-store.js";import{ServerMemoryStore as me}from"./server-memory-store.js";const ue=3e3,j=10,z=(()=>{const I=Number.parseInt(process.env.AWS_MCP_FILE_CHANGE_RENOTIFY_COOLDOWN_MS||"",10);return Number.isFinite(I)&&I>0?I:30*6e4})(),G=500,de=30,he=new Set(["<",">",":",'"',"/","\\","|","?","*"]),Y=20*1024*1024,ge={".pdf":"application/pdf",".txt":"text/plain",".md":"text/markdown",".csv":"text/csv",".json":"application/json",".html":"text/html",".xml":"application/xml",".doc":"application/msword",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".xls":"application/vnd.ms-excel",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",".ppt":"application/vnd.ms-powerpoint",".pptx":"application/vnd.openxmlformats-officedocument.presentationml.presentation",".zip":"application/zip",".gz":"application/gzip",".tar":"application/x-tar",".7z":"application/x-7z-compressed",".rar":"application/vnd.rar",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".svg":"image/svg+xml",".mp3":"audio/mpeg",".mp4":"video/mp4"};function pe(I){return ge[S.extname(I).toLowerCase()]||"application/octet-stream"}function fe(I){return(I||"").replace(/[|[\]\r\n]/g,"_").trim()||"\u6587\u4EF6"}function ye(I){if(!Number.isFinite(I)||I<=0)return"0 B";const e=["B","KB","MB","GB"],t=Math.min(e.length-1,Math.floor(Math.log(I)/Math.log(1024)));return`${Number.parseFloat((I/1024**t).toFixed(2))} ${e[t]}`}function _e(I){return`[\u6587\u4EF6: ${fe(I.name)} | ${I.url} | ${I.mediaType||"application/octet-stream"} | ${ye(I.size)}]`}class T{server;agentClient;messageBuffer;memoryStore;roleMemoryStore;sessionContextMemoryStore;initialRoleName="";hasRoleName=!1;contextManager;isSubAgent;fileChangeNotifyHistory=new Map;featuresCache=null;static FEATURES_CACHE_TTL_MS=5e3;static LAUNCH_ITEM_FEATURE_KEY="agentSys.launchItem";static LAUNCH_TOOLS_ENV_KEY="AWS_LAUNCH_CONFIG_TOOLS";static HIRE_FEATURE_KEY="agentSys.hire";static HIRE_TOOLS_ENV_KEY="AWS_HIRE_TOOLS";leaseRenewalTimer=null;activeLeaseUris=new Set;static LEASE_DURATION_MINUTES=10;static LEASE_RENEW_INTERVAL_MS=6e4;profileSynced=!1;urgentMeetingHydrateRequested=!1;cachedPluginCatalog=null;deliveredPluginNames=new Set;pluginCatalogDrainCompactionSeq=0;pluginCatalogLastSeenCompactionSeq=0;static MEETING_HYDRATE_RETRY_COUNT=3;static MEETING_HYDRATE_RETRY_DELAY_MS=150;static MEETING_HYDRATE_TIMEOUT_REARM_DELAY_MS=1e4;meetingHydrateTimeoutRearmDelayMs=T.MEETING_HYDRATE_TIMEOUT_REARM_DELAY_MS;static MEETING_HYDRATE_POLL_TIMEOUT_MS=65e3;static MEETING_PREEMPTIVE_JOIN_WAIT_MS=45e3;pendingPollMessage=null;syncRoleMemoryStore(e){if(o.info(`[McpServer] syncRoleMemoryStore \u88AB\u8C03\u7528: displayName=${e.displayName}, roleName="${e.roleName??"(\u7A7A)"}", id=${e.id}`),!e.roleName){o.warn(`[McpServer] syncRoleMemoryStore: profile.roleName \u4E3A\u7A7A\uFF0ChasRoleName \u4FDD\u6301 false\u3002profile=${JSON.stringify({id:e.id,displayName:e.displayName,roleName:e.roleName,instanceName:e.instanceName})}`);return}const t=T.sanitizeRoleDirectoryName(e.roleName);this.hasRoleName=!0,t!==this.initialRoleName&&(o.info(`[McpServer] \u89D2\u8272\u76EE\u5F55\u4E0E\u521D\u59CB\u503C\u4E0D\u4E00\u81F4\uFF0C\u91CD\u5EFA roleMemoryStore: "${this.initialRoleName}" -> "${t}"`),this.roleMemoryStore=new L(T.buildRoleMemoryStorePath(t)),this.initialRoleName=t)}maybeSyncPermanentMemoryToServer(){this.doMaybeSyncPermanentMemoryToServer().catch(e=>{o.warn("[McpServer] maybeSyncPermanentMemoryToServer \u5F02\u5E38: %s, stack=%s",e instanceof Error?e.message:String(e),e instanceof Error?e.stack:"(no stack)")})}async doMaybeSyncPermanentMemoryToServer(){o.info("[McpServer] maybeSyncPermanentMemoryToServer \u5F00\u59CB\uFF0CinitialRoleName="+this.initialRoleName);let e;try{e=await this.memoryStore.getStats()}catch(n){o.warn("[McpServer] \u83B7\u53D6 server \u8BB0\u5FC6\u7EDF\u8BA1\u5931\u8D25\uFF0C\u8DF3\u8FC7\u540C\u6B65:",n instanceof Error?n.message:n);return}const t=e.by_type.project_memory?.count??0;o.info(`[McpServer] server memory \u8BA1\u6570=${t}`);let r=[];try{r=await this.roleMemoryStore.listByType("project_memory"),o.info(`[McpServer] \u89D2\u8272\u5B50\u76EE\u5F55\u8BFB\u53D6\u5230 ${r.length} \u6761\u6C38\u4E45\u8BB0\u5FC6`)}catch(n){o.warn("[McpServer] \u8BFB\u53D6\u89D2\u8272\u5B50\u76EE\u5F55\u6C38\u4E45\u8BB0\u5FC6\u5931\u8D25:",n instanceof Error?n.message:n)}if(r.length===0){const n=S.dirname(T.buildRoleMemoryStorePath(this.initialRoleName));o.info(`[McpServer] \u5C1D\u8BD5\u4ECE\u9057\u7559\u76EE\u5F55\u8BFB\u53D6: ${n}`);try{const l=await new L(n).listByType("project_memory");l.length>0&&(o.info(`[McpServer] \u4ECE\u9057\u7559\u76EE\u5F55\u8BFB\u53D6\u5230 ${l.length} \u6761\u6C38\u4E45\u8BB0\u5FC6`),r=l)}catch(a){o.warn("[McpServer] \u8BFB\u53D6\u9057\u7559\u76EE\u5F55\u6C38\u4E45\u8BB0\u5FC6\u5931\u8D25:",a instanceof Error?a.message:a)}}if(r.length===0){o.info("[McpServer] \u672C\u5730\u4E5F\u65E0\u6C38\u4E45\u8BB0\u5FC6\uFF0C\u8DF3\u8FC7\u540C\u6B65");return}if(t>=r.length){o.info(`[McpServer] \u670D\u52A1\u7AEF\u5DF2\u6709 ${t} \u6761 >= \u672C\u5730 ${r.length} \u6761\uFF0C\u65E0\u9700\u56DE\u586B`);return}o.info(`[McpServer] \u68C0\u6D4B\u5230\u7F3A\u91CF\uFF1A\u672C\u5730 ${r.length} \u6761 > \u670D\u52A1\u7AEF ${t} \u6761\uFF0C\u5F00\u59CB\u589E\u91CF\u56DE\u586B`);let i=0,s=0;for(const n of r)try{await this.memoryStore.createMemory({memory_type:"project_memory",uri:n.uri,title:n.title,content:n.content,keywords:n.keywords,bound_files:n.bound_files,file_md5_map:n.file_md5_map,last_check_time:n.last_check_time}),i++,o.info(`[McpServer] \u540C\u6B65\u6C38\u4E45\u8BB0\u5FC6\u6210\u529F: ${n.uri}`)}catch(a){const l=a instanceof Error?a.message:String(a);l.includes("already exists")||l.includes("Memory already exists")||o.warn(`[McpServer] \u540C\u6B65\u6C38\u4E45\u8BB0\u5FC6\u5931\u8D25 (${n.uri}): ${l}`),s++}o.info(`[McpServer] \u6C38\u4E45\u8BB0\u5FC6\u540C\u6B65\u5B8C\u6210: \u6210\u529F ${i}, \u8DF3\u8FC7 ${s}, \u5171 ${r.length}`),await this.reportMemoryStatsToServer()}normalizeBoundFilePath(e){const t=String(e||"").trim().replace(/\\/g,"/");if(!t)return t;const r=t.startsWith("@/")?t.substring(1):t;return r.startsWith("./")?r:`./${r.replace(/^\/+/,"")}`}normalizeBoundFiles(e){return!e||!Array.isArray(e)?e:e.map(t=>this.normalizeBoundFilePath(String(t)))}async validateBoundFilesExist(e){if(!e||e.length===0)return;const t=process.env.AWS_WORKSPACE_PATH||process.cwd(),{access:r}=await import("node:fs/promises"),i=[];for(const s of e)try{const n=S.resolve(t,s);await r(n)}catch{i.push(s)}if(i.length>0)throw new Error(`\u7ED1\u5B9A\u7684\u6587\u4EF6\u4E0D\u5B58\u5728\uFF0C\u8BF7\u786E\u8BA4\u6587\u4EF6\u8DEF\u5F84\u6B63\u786E\u540E\u518D\u91CD\u65B0\u63D0\u4EA4:
2
2
  ${i.map(s=>` - ${s}`).join(`
3
- `)}`)}toMemoryWriteResult(e){return{id:e.id,uri:e.uri,domain:e.domain,path:e.path,title:e.title,memory_type:e.memory_type,createdAt:e.createdAt,updatedAt:e.updatedAt,version:e.version,keywords:e.keywords,bound_files:e.bound_files}}toMemoryRecordWithMetadata(e){return{id:e.id,uri:e.uri,domain:e.domain,path:e.path,title:e.title,content:e.content,memory_type:e.memory_type,createdAt:e.createdAt,updatedAt:e.updatedAt,version:e.version,keywords:e.keywords,bound_files:e.bound_files,file_md5_map:e.file_md5_map,memory_status:e.memory_status,updating_agent_id:e.updating_agent_id,last_check_time:e.last_check_time,path_prefix:e.path_prefix,readonly:e.readonly,source_agent_id:e.source_agent_id,source_display_name:e.source_display_name,source_role_name:e.source_role_name,source_workspace_path:e.source_workspace_path}}constructor(){this.agentClient=new Q,this.messageBuffer=new ae,this.initialRoleName=R.resolveRoleMemoryDirectoryName(),this.hasRoleName=!!process.env.AWS_ROLE_NAME;const e=R.resolveMemoryStorePaths();this.memoryStore=new me(this.agentClient),this.roleMemoryStore=new L(e.rolePath),this.sessionContextMemoryStore=new L(S.join(S.dirname(e.rolePath),"..","session_context")),this.isSubAgent=process.env.AWS_SUB_AGENT==="true",this.contextManager=new le(this.sessionContextMemoryStore),this.server=new K({name:re,version:se},{capabilities:{tools:{}}}),this.setupHandlers()}setupHandlers(){this.server.setRequestHandler(Z,async()=>{let e=this.isSubAgent?F.filter(t=>x.has(t.name)):F;return!this.isSubAgent&&!await this.isLaunchConfigToolsEnabled()&&(e=e.filter(t=>!q.has(t.name))),!this.isSubAgent&&!await this.isHireToolsEnabled()&&(e=e.filter(t=>!W.has(t.name))),{tools:e}}),this.server.setRequestHandler(X,async(e,t)=>{const{name:r,arguments:i}=e.params;try{const s=await this.handleToolCall(r,i,t?.signal);return{content:this.buildToolResultContent(s)}}catch(s){const n=s instanceof Error?s.message:String(s),a=s instanceof ce?{error:n,...s.details}:{error:n};return o.error("[McpServer] \u5DE5\u5177\u8C03\u7528\u5F02\u5E38: tool=%s, error=%s, stack=%s",r,n,s instanceof Error?s.stack:"(no stack)"),{content:[{type:"text",text:JSON.stringify(a,null,2)}],isError:!0}}})}buildToolResultContent(e){if(e&&typeof e=="object"&&!Array.isArray(e)){const t=e;if(typeof t.image=="string"&&typeof t.mimeType=="string")return[{type:"image",data:t.image,mimeType:t.mimeType}]}return[{type:"text",text:JSON.stringify(e,null,2)}]}async handleToolCall(e,t,r){const i=t?._aws_sub_agent===!0,s=t?._aws_silent_poll===!0,n=t?._aws_force_inject===!0,a={...t};delete a._aws_sub_agent,delete a._aws_silent_poll,delete a._aws_force_inject;const l=i?null:this.agentClient.getStatusReporter();l&&!s&&this.safeReportStatus(()=>l.reportToolUse(e,this.sanitizeToolUseArgs(e,a)));try{const m=await this.executeToolCall(e,a,{forceInject:n,signal:r});if(l&&!s){const d=this.stripAutoDelegateForReporting(m);d!==null&&(this.safeReportStatus(()=>l.reportToolResult(d)),this.safeReportStatus(()=>l.reportThinking()))}return m}catch(m){throw l&&!s&&this.safeReportStatus(()=>l.reportToolError(m)),m}}safeReportStatus(e){try{e()}catch(t){o.warn("[McpServer] \u72B6\u6001\u4E0A\u62A5\u5931\u8D25\uFF08\u5DF2\u5FFD\u7565\uFF0C\u4E0D\u5F71\u54CD\u5DE5\u5177\u8C03\u7528\uFF09: %s",t instanceof Error?t.message:String(t))}}async executeToolCall(e,t,r={}){if(this.isSubAgent&&!x.has(e))throw new Error(`Sub-agent is not allowed to call tool: ${e}`);if(q.has(e)&&!await this.isLaunchConfigToolsEnabled())throw new Error("\u542F\u52A8\u9879\u7BA1\u7406\u80FD\u529B\u672A\u5F00\u542F\uFF08\u8BF7\u5148\u5728\u80FD\u529B\u914D\u7F6E\u4E2D\u5F00\u542F\u300CAgent \u7CFB\u7EDF\u7BA1\u7406 \u2192 \u542F\u52A8\u9879\u7BA1\u7406\u300D\u540E\u518D\u8C03\u7528 launch_config_* \u5DE5\u5177\uFF09");if(W.has(e)&&!await this.isHireToolsEnabled())throw new Error("\u62DB\u8058\u5DE5\u5177\u80FD\u529B\u672A\u5F00\u542F\uFF08\u8BF7\u5148\u5728\u80FD\u529B\u914D\u7F6E\u4E2D\u5F00\u542F\u300CAgent \u7CFB\u7EDF\u7BA1\u7406 \u2192 \u62DB\u8058\u5DE5\u5177\u300D\u540E\u518D\u8C03\u7528 hire_colleague / hire_colleagues_batch\uFF09");switch(e){case"get_colleague":return await this.agentClient.discoverColleagues();case"get_group_rooms":return await this.agentClient.discoverGroupRooms();case"get_profile":return await this.agentClient.getProfile();case"hire_colleague":return await this.handleHireColleague(t);case"hire_colleagues_batch":return await this.handleHireColleaguesBatch(t);case"send_group":return await this.handleSendGroup(t);case"send_private":return await this.handleSendPrivate(t);case"poll_message":return await this.handlePollMessage(r.signal);case"get_message":return this.handleGetMessage(r.forceInject===!0);case"get_dm_history":return await this.handleGetDmHistory(t);case"get_group_history":return await this.handleGetGroupHistory(t);case"create_meeting":case"leave_meeting":case"end_meeting":case"meeting_speak":case"get_meeting_info":case"my_meetings":return await this.agentClient.callAgentScopedTool(e,t);case"my_task":return await this.agentClient.getMyTasks();case"create_task_instance_comment":return await this.handleCreateTaskInstanceComment(t);case"submit_task_result":return await this.handleSubmitTaskResult(t);case"start_task_rollback":return await this.handleStartTaskRollback(t);case"finish_task_rollback":return await this.handleFinishTaskRollback(t);case"reject_task":return await this.handleRejectTask(t);case"terminate_task":return await this.handleTerminateTask(t);case"create_memory":return await this.handleCreateMemory(t);case"read_memory":return await this.handleReadMemory(t);case"update_memory":return await this.handleUpdateMemory(t);case"delete_memory":return await this.handleDeleteMemory(t);case"search_memory":return await this.handleSearchMemory(t);case"list_memories":return await this.handleListMemories(t);case"get_memory_stats":return await this.handleGetMemoryStats(t);case"list_memories_by_file":return await this.handleListMemoriesByFile(t);case"abandon_memory_update":return await this.handleAbandonMemoryUpdate(t);case"memory_recurrence":return await this.handleMemoryRecurrence(t);case"memory_recurrence_complete":return await this.handleMemoryRecurrenceComplete(t);case"get_debug_log_config":return await this.agentClient.getDebugLogConfig();case"query_debug_logs":return await this.agentClient.queryDebugLogs(t);case"query_file_changes_history":return await this.agentClient.queryFileChangesHistory(t);case"launch_config_list":return await this.agentClient.listLaunchConfigs();case"launch_config_create":return await this.agentClient.createLaunchConfig(t);case"launch_config_update":return await this.agentClient.updateLaunchConfig(t);case"launch_config_delete":return await this.agentClient.deleteLaunchConfig(String(t?.configId??""));case"launch_config_start":return await this.agentClient.startLaunchConfig(t);case"launch_config_restart":return await this.agentClient.restartLaunchConfig(t);case"launch_config_stop":return await this.agentClient.stopLaunchConfig(String(t?.configId??""));case"launch_config_logs":return await this.agentClient.getLaunchLogs(t);case"launch_config_status":return await this.agentClient.listLaunchRuns();default:throw new Error(`Unknown tool: ${e}`)}}async isLaunchConfigToolsEnabled(){const{features:e,ok:t}=await this.fetchRuntimeFeaturesWithStatus();return t?e[R.LAUNCH_ITEM_FEATURE_KEY]===!0:process.env[R.LAUNCH_TOOLS_ENV_KEY]==="1"}async isHireToolsEnabled(){const{features:e,ok:t}=await this.fetchRuntimeFeaturesWithStatus();return t?e[R.HIRE_FEATURE_KEY]===!0:process.env[R.HIRE_TOOLS_ENV_KEY]==="1"}async fetchRuntimeFeaturesWithStatus(){const e=Date.now();if(this.featuresCache&&e-this.featuresCache.fetchedAt<R.FEATURES_CACHE_TTL_MS)return{features:this.featuresCache.features,ok:this.featuresCache.ok};let t={},r=!1;try{t=await this.agentClient.getRuntimeFeatures(),r=!0}catch(i){o.warn("[McpServer] \u83B7\u53D6\u80FD\u529B\u5F00\u5173\u5931\u8D25\uFF0C\u6309\u542F\u52A8\u671F env \u515C\u5E95: %s",i instanceof Error?i.message:String(i))}return this.featuresCache={features:t,ok:r,fetchedAt:e},{features:t,ok:r}}static MEMORY_TYPES=["recently_memory","agent_memory","project_memory","session_context"];static MEMORY_TOOL_NAMES=new Set(["create_memory","read_memory","update_memory","delete_memory","search_memory","list_memories","get_memory_stats","list_memories_by_file","abandon_memory_update","memory_recurrence","memory_recurrence_complete"]);static findAgentsworkDirSync(e){let t=S.resolve(e);for(;;){if(P.existsSync(S.join(t,".agentswork")))return S.join(t,".agentswork");const r=S.dirname(t);if(r===t)break;t=r}return S.join(S.resolve(e),".agentswork")}static sanitizeRoleDirectoryName(e){return String(e||"").trim().split("").map(r=>he.has(r)||r.charCodeAt(0)<32?"_":r).join("").replace(/^\.+|\.+$/g,"").trim()||"default-role"}static resolveRoleMemoryDirectoryName(){return R.sanitizeRoleDirectoryName(process.env.AWS_ROLE_NAME||"")}static buildRoleMemoryStorePath(e){const t=process.env.AWS_WORKSPACE_PATH||process.cwd(),r=R.findAgentsworkDirSync(t);return S.join(r,"memory","memory",R.sanitizeRoleDirectoryName(e))}static resolveMemoryStorePaths(){const e=String(process.env.AWS_MEMORY_STORE_PATH||"").trim();if(e)return{instancePath:e,rolePath:e};const t=process.env.AWS_WORKSPACE_PATH||process.cwd(),r=R.findAgentsworkDirSync(t),i=String(process.env.AWS_INSTANCE_MEMORY_STORE_PATH||"").trim()||S.join(r,"memory","server-managed"),s=String(process.env.AWS_ROLE_MEMORY_STORE_PATH||"").trim()||S.join(r,"memory","memory",R.resolveRoleMemoryDirectoryName());return{instancePath:i,rolePath:s}}getRequiredString(e,t){const r=e[t];if(typeof r!="string"||r.trim().length===0)throw new Error(`${t} is required`);return r}getOptionalString(e,t){const r=e[t];return typeof r=="string"?r:void 0}getOptionalNumber(e,t){const r=e[t];return typeof r=="number"?r:void 0}getOptionalStringArray(e,t){const r=e[t];return Array.isArray(r)?r.map(i=>String(i)):void 0}getOptionalMemoryType(e){const t=e.memory_type;if(t!==void 0)return this.parseMemoryType(t)}parseMemoryType(e){if(typeof e!="string")throw new Error(`Invalid memory_type: ${String(e)}`);const t=e.trim();if(!this.isMemoryType(t))throw new Error(`Invalid memory_type: ${e}`);return t}isMemoryType(e){return R.MEMORY_TYPES.some(t=>t===e)}getMemoryStoreForType(e){return this.memoryStore}async readMemoryFromScopedStores(e){if(e.memory_type)return await this.memoryStore.readMemory(e);const t=await this.memoryStore.readMemory({...e,memory_type:"project_memory"}).catch(()=>null);return t||await this.memoryStore.readMemory(e)}async backupProjectMemoryToLocal(e){try{const t=await this.memoryStore.readMemory({uri:e.uri,memory_type:"project_memory"});t&&(await this.roleMemoryStore.deleteMemory({uri:e.uri,memory_type:"project_memory"}).catch(()=>{}),await this.roleMemoryStore.createMemory(t))}catch(t){o.warn("[McpServer] backupProjectMemoryToLocal \u5931\u8D25: uri=%s",e.uri,t)}}async removeProjectMemoryLocalBackup(e){try{await this.roleMemoryStore.deleteMemory({uri:e,memory_type:"project_memory"})}catch(t){o.warn("[McpServer] removeProjectMemoryLocalBackup \u5931\u8D25: uri=%s",e,t)}}async findMemoryStoreForMutation(e){return e.memory_type?{store:this.memoryStore,memory_type:e.memory_type}:await this.memoryStore.readMemory({uri:e.uri,memory_type:"project_memory"}).catch(()=>null)?{store:this.memoryStore,memory_type:"project_memory"}:{store:this.memoryStore}}async reportMemoryStatsToServer(){const e=await this.memoryStore.getStats();try{await this.agentClient.reportMemoryStats(e)}catch(t){o.warn("[McpServer] \u4E0A\u62A5 memory \u7EDF\u8BA1\u5931\u8D25:",t)}}sanitizeToolUseArgs(e,t){if(!R.MEMORY_TOOL_NAMES.has(e))return t;const r={},i=this.getOptionalString(t,"uri"),s=this.getOptionalString(t,"memory_type"),n=this.getOptionalNumber(t,"limit");return i&&(r.uri=i),s&&(r.memory_type=s),typeof n=="number"&&(r.limit=n),e==="search_memory"&&(r.queryProvided=typeof t.query=="string"&&t.query.length>0,t.keyword_mode!==void 0&&(r.keyword_mode=t.keyword_mode)),r}stripAutoDelegateForReporting(e){if(!e||typeof e!="object")return e;const t=e,r=Array.isArray(t.directMessages)?t.directMessages:[],i=Array.isArray(t.groupMessages)?t.groupMessages:[],s=l=>!!l&&typeof l=="object"&&"_acodeAutoDelegate"in l;if(!r.some(s))return e;const a=r.filter(l=>!s(l));return a.length===0&&i.length===0?null:{...t,directMessages:a}}async handleCreateMemory(e){const t=this.normalizeBoundFiles(this.getOptionalStringArray(e,"bound_files"));await this.validateBoundFilesExist(t);let r,i;if(t&&t.length>0){r={};for(const a of t){const l=await this.calculateFileMd5(a);l&&(r[a]=l)}i=new Date().toISOString()}const s={memory_type:this.parseMemoryType(this.getRequiredString(e,"memory_type")),uri:this.getRequiredString(e,"uri"),title:this.getOptionalString(e,"title"),content:this.getRequiredString(e,"content"),keywords:this.getOptionalStringArray(e,"keywords"),bound_files:t,file_md5_map:r,last_check_time:i},n=await this.memoryStore.createMemory(s);return s.memory_type==="project_memory"&&this.backupProjectMemoryToLocal(s).catch(a=>{o.warn("[McpServer] \u5907\u4EFD project_memory \u5230\u672C\u5730\u5931\u8D25:",a)}),await this.reportMemoryStatsToServer(),this.toMemoryWriteResult(n)}async handleReadMemory(e){const t={uri:this.getRequiredString(e,"uri"),memory_type:this.getOptionalMemoryType(e)};return await this.readMemoryFromScopedStores(t)}async handleUpdateMemory(e){const t=typeof e.old_string=="string"||typeof e.new_string=="string",r=typeof e.old_string=="string"&&typeof e.new_string=="string",i=this.getOptionalString(e,"append");if(t&&!r)throw new Error("old_string and new_string must be provided together");const s={uri:this.getRequiredString(e,"uri"),memory_type:this.getOptionalMemoryType(e),title:this.getOptionalString(e,"title"),old_string:this.getOptionalString(e,"old_string"),new_string:this.getOptionalString(e,"new_string"),append:i,keywords:this.getOptionalStringArray(e,"keywords"),bound_files:this.normalizeBoundFiles(this.getOptionalStringArray(e,"bound_files"))},n=await this.findMemoryStoreForMutation(s),a=await n.store.readMemory({uri:s.uri,memory_type:n.memory_type??s.memory_type});s.bound_files!==void 0?await this.validateBoundFilesExist(s.bound_files):a?.bound_files&&a.bound_files.length>0&&await this.validateBoundFilesExist(a.bound_files);const l=s.bound_files??a?.bound_files;let m,d;if(l&&l.length>0){m={};for(const u of l){const _=await this.calculateFileMd5(u);_&&(m[u]=_)}d=new Date().toISOString()}const g=await n.store.updateMemory({...s,memory_type:n.memory_type??s.memory_type,file_md5_map:m,last_check_time:d});if(n.memory_type==="project_memory"&&this.backupProjectMemoryToLocal({...s,memory_type:"project_memory",file_md5_map:m,last_check_time:d}).catch(u=>{o.warn("[McpServer] \u5907\u4EFD project_memory \u66F4\u65B0\u5230\u672C\u5730\u5931\u8D25:",u)}),await this.reportMemoryStatsToServer(),n.memory_type==="project_memory"&&a?.memory_status==="updating")try{await this.memoryStore.releaseMemoryClaim(s.uri),this.activeLeaseUris.delete(s.uri),this.activeLeaseUris.size===0&&this.stopLeaseRenewal()}catch(u){o.warn("[McpServer] \u91CA\u653E memory claim \u5931\u8D25: uri=%s, error=%s",s.uri,u instanceof Error?u.message:String(u))}return this.toMemoryWriteResult(g)}async handleDeleteMemory(e){const t=typeof e.uri=="string"?e.uri:void 0,r=Array.isArray(e.memories)?e.memories:void 0;if(t&&r&&r.length>0)throw new Error("delete_memory \u4E0D\u652F\u6301\u540C\u65F6\u4F20\u5165 uri \u548C memories\uFF0C\u8BF7\u4E8C\u9009\u4E00");if(!t&&(!r||r.length===0))throw new Error("delete_memory \u9700\u8981 uri \u6216 memories \u53C2\u6570");if(t){const a=this.getOptionalMemoryType(e);return{deleted:await this.deleteMemorySingle(t,a)}}let i=0;const s=[],n=[];for(let a=0;a<r.length;a++){const l=r[a];if(typeof l!="object"||l===null){n.push({uri:String(l),reason:`memories[${a}] \u4E0D\u662F\u5BF9\u8C61`});continue}const m=l,d=typeof m.uri=="string"?m.uri:"";if(!d){n.push({uri:"",reason:`memories[${a}].uri \u7F3A\u5931`});continue}const g=typeof m.memory_type=="string"?this.parseMemoryType(m.memory_type):void 0;try{await this.deleteMemorySingle(d,g,!0)?i++:s.push(d)}catch(u){n.push({uri:d,reason:u instanceof Error?u.message:String(u)})}}return i>0&&await this.reportMemoryStatsToServer(),{deleted:i,not_found:s,failed:n}}async deleteMemorySingle(e,t,r=!1){const i={uri:e,memory_type:t},s=await this.findMemoryStoreForMutation(i),n=s.memory_type??i.memory_type,a=await s.store.deleteMemory({...i,memory_type:n});return a&&(n==="project_memory"&&this.removeProjectMemoryLocalBackup(e).catch(l=>{o.warn("[McpServer] \u5220\u9664 project_memory \u672C\u5730\u5907\u4EFD\u5931\u8D25:",l)}),r||await this.reportMemoryStatsToServer()),a}async handleSearchMemory(e){const t=this.getOptionalString(e,"scope"),r=t==="children"||t==="all"?t:"own",i=this.getOptionalString(e,"keyword_mode"),s=i==="all"?"all":i==="any"?"any":void 0,n={query:this.getRequiredString(e,"query"),limit:this.getOptionalNumber(e,"limit"),memory_type:this.getOptionalMemoryType(e),keywords:this.getOptionalStringArray(e,"keywords"),keyword_mode:s,scope:r};if(r==="children")return await this.memoryStore.searchMemory(n);const a=await this.searchOwnMemories(n);if(r==="own")return a;const l=await this.memoryStore.searchMemory({...n,scope:"children"});return this.mergeSearchResults(a,l,n.limit)}async searchOwnMemories(e){return await this.memoryStore.searchMemory(e)}mergeSearchResults(e,t,r){const i=new Set,s=typeof r=="number"&&r>0?r:10,n=[...e.results,...t.results].filter(a=>{const l=a.uri;return i.has(l)?!1:(i.add(l),!0)}).sort((a,l)=>l.updatedAt.localeCompare(a.updatedAt)).slice(0,s);return{query:e.query||t.query,results:n}}async handleListMemories(e){const t=this.getRequiredString(e,"memory_type"),r=this.getOptionalNumber(e,"offset"),i=this.getOptionalNumber(e,"limit"),s=Math.max(0,Math.floor(r??0)),n=i!==void 0&&i>=1?Math.floor(i):de,a=await this.memoryStore.listByType(t),l=a.length,m=a.slice(s,s+n);return{memory_type:t,total:l,offset:s,limit:n,has_more:s+n<l,memories:m}}async handleGetMemoryStats(e){const t=await this.memoryStore.getStats(),r=this.getOptionalMemoryType(e);return r?{memory_type:r,total:t.by_type[r].count,by_type:{[r]:t.by_type[r]}}:t}async handleListMemoriesByFile(e){const t=this.getRequiredString(e,"file_path"),r=this.normalizeBoundFilePath(t),i=this.getOptionalMemoryType(e),s=this.getOptionalString(e,"scope"),n=s==="own"||s==="children"?s:"all",a=async()=>await this.memoryStore.listByFile(r,{memory_type:i,scope:"children"}).catch(()=>[]);if(n==="children"){const u=await a();return{file_path:r,count:u.length,memories:u.map(_=>this.toMemoryRecordWithMetadata(_))}}if(n==="own"){const u=await this.collectOwnMemoriesByFile(r,i);return{file_path:r,count:u.length,memories:u.map(_=>this.toMemoryRecordWithMetadata(_))}}const[l,m,d]=await Promise.all([this.memoryStore.listByFile(r,{memory_type:i,scope:"all"}).catch(()=>[]),this.searchChildMemoriesByFileLocal(r,i).catch(()=>[]),this.searchPeerMemoriesByFileLocal(r,i).catch(()=>[])]),g=this.mergeIdDedupe(this.mergeIdDedupe(l,m),d);return{file_path:r,count:g.length,memories:g.map(u=>this.toMemoryRecordWithMetadata(u))}}mergeIdDedupe(e,t){const r=new Set;for(const s of e)s.id&&r.add(s.id);const i=[...e];for(const s of t)s.id&&!r.has(s.id)&&(i.push(s),r.add(s.id));return i.sort((s,n)=>n.updatedAt.localeCompare(s.updatedAt)),i}async searchChildMemoriesByFileLocal(e,t){const r=process.env.AWS_WORKSPACE_PATH||process.cwd(),i=this.normalizeBoundFilePath(e),n=(i.startsWith("./")?i.substring(2):i).split("/"),a=[],l=new Set,{access:m,readdir:d,readFile:g}=await import("node:fs/promises");for(let u=n.length-1;u>=1;u--){const _=n.slice(0,u),h="./"+n.slice(u).join("/"),M=S.join(r,..._);if(M===r)continue;const c=S.join(M,".agentswork");try{await m(c)}catch{continue}const y=S.join(c,"memory","memory");let p;try{p=(await d(y,{withFileTypes:!0})).filter(v=>v.isDirectory()).map(v=>v.name)}catch{continue}for(const w of p){const v=S.join(y,w);let k;try{k=await d(v)}catch{continue}for(const f of k){if(!f.endsWith(".json"))continue;const C=S.join(v,f);let T;try{T=await g(C,"utf-8")}catch{continue}let A;try{A=JSON.parse(T)}catch{continue}if(A.by_uri)for(const[N,$]of Object.entries(A.by_uri)){if(!$)continue;const j=$.id||N;l.has(j)||t&&$.memory_type!==t||$.bound_files&&$.bound_files.length>0&&$.bound_files.some(J=>this.normalizeBoundFilePath(J)===h)&&(l.add(j),a.push({...$,uri:$.uri||N}))}}}}return a.sort((u,_)=>String(_.updatedAt??"").localeCompare(String(u.updatedAt??""))),a}async searchPeerMemoriesByFileLocal(e,t){if(!this.hasRoleName||!this.initialRoleName)return[];const r=process.env.AWS_WORKSPACE_PATH||process.cwd(),i=this.normalizeBoundFilePath(e),s=S.join(r,".agentswork","memory","memory"),{access:n,readdir:a,readFile:l}=await import("node:fs/promises");try{await n(s)}catch{return[]}let m;try{m=(await a(s,{withFileTypes:!0})).filter(_=>_.isDirectory()).map(_=>_.name)}catch{return[]}const d=[],g=new Set;for(const u of m){if(u===this.initialRoleName)continue;const _=S.join(s,u);let b;try{b=await a(_)}catch{continue}for(const h of b){if(!h.endsWith(".json"))continue;let M;try{M=JSON.parse(await l(S.join(_,h),"utf-8"))}catch{continue}if(M.by_uri)for(const[c,y]of Object.entries(M.by_uri)){if(!y)continue;const p=y.id||c;g.has(p)||y.memory_type==="project_memory"&&(t&&y.memory_type!==t||y.bound_files&&y.bound_files.length>0&&y.bound_files.some(v=>this.normalizeBoundFilePath(v)===i)&&(g.add(p),d.push({...y,uri:y.uri||c,readonly:!0,source_role_name:u})))}}}return d.sort((u,_)=>String(_.updatedAt??"").localeCompare(String(u.updatedAt??""))),d}async collectOwnMemoriesByFile(e,t){return await this.memoryStore.listByFile(e,{memory_type:t})}async handleAbandonMemoryUpdate(e){const t=this.getRequiredString(e,"uri"),r=this.getOptionalMemoryType(e),i=await this.memoryStore.readMemory({uri:t,memory_type:r});return i?.bound_files&&i.bound_files.length>0&&await this.validateBoundFilesExist(i.bound_files),await this.memoryStore.releaseMemoryClaim(t),i?.memory_type==="project_memory"&&this.backupProjectMemoryToLocal({uri:t,memory_type:"project_memory"}).catch(s=>{o.info(`[McpServer] abandon_memory_update: \u540C\u6B65\u672C\u5730\u5907\u4EFD\u5931\u8D25: ${t}`,s)}),this.activeLeaseUris.delete(t),this.activeLeaseUris.size===0&&this.stopLeaseRenewal(),{success:!0,uri:t,message:"Memory \u66F4\u65B0\u72B6\u6001\u5DF2\u6E05\u9664"}}async handleMemoryRecurrence(e){const t=Math.max(1,e?.limit??10);try{((await this.memoryStore.markExpiredMemoriesRecalling()).uris?.length??0)>0&&this.startLeaseRenewal()}catch(l){o.warn("[McpServer] \u539F\u5B50\u8BA4\u9886\u8FC7\u671F\u8BB0\u5FC6\u5931\u8D25: %s",l instanceof Error?l.message:String(l))}const r=await this.memoryStore.listExpiredRecentlyMemories();if(r.length===0)return{memories:[],count:0,limit:t,remaining:0,totalExpired:0,message:"\u6CA1\u6709\u5F85\u56DE\u5FC6\u7684\u5373\u5C06\u9057\u5FD8\u8BB0\u5FC6\u3002"};const s=[...r].sort((l,m)=>{const d=new Date(l.expiresAt||l.createdAt||0).getTime(),g=new Date(m.expiresAt||m.createdAt||0).getTime();return d-g}).slice(0,t),n=Math.max(0,r.length-s.length);return{memories:s.map(l=>({uri:l.uri,title:l.title,domain:l.domain,path:l.path,memory_status:"recalling",contentPreview:typeof l.content=="string"&&l.content.length>200?l.content.substring(0,200)+"...":l.content,createdAt:l.createdAt,updatedAt:l.updatedAt})),count:s.length,limit:t,remaining:n,totalExpired:r.length,message:n>0?`\u672C\u6B21\u5904\u7406 ${s.length} \u6761\u5373\u5C06\u9057\u5FD8\u7684\u8BB0\u5FC6\uFF08\u6700\u65E9\u8FC7\u671F\u4F18\u5148\uFF09\uFF0C\u5269\u4F59 ${n} \u6761\u5F85\u5904\u7406\u3002
3
+ `)}`)}toMemoryWriteResult(e){return{id:e.id,uri:e.uri,domain:e.domain,path:e.path,title:e.title,memory_type:e.memory_type,createdAt:e.createdAt,updatedAt:e.updatedAt,version:e.version,keywords:e.keywords,bound_files:e.bound_files}}toMemoryRecordWithMetadata(e){return{id:e.id,uri:e.uri,domain:e.domain,path:e.path,title:e.title,content:e.content,memory_type:e.memory_type,createdAt:e.createdAt,updatedAt:e.updatedAt,version:e.version,keywords:e.keywords,bound_files:e.bound_files,file_md5_map:e.file_md5_map,memory_status:e.memory_status,updating_agent_id:e.updating_agent_id,last_check_time:e.last_check_time,path_prefix:e.path_prefix,readonly:e.readonly,source_agent_id:e.source_agent_id,source_display_name:e.source_display_name,source_role_name:e.source_role_name,source_workspace_path:e.source_workspace_path}}constructor(){this.agentClient=new Q,this.messageBuffer=new ae,this.initialRoleName=T.resolveRoleMemoryDirectoryName(),this.hasRoleName=!!process.env.AWS_ROLE_NAME;const e=T.resolveMemoryStorePaths();this.memoryStore=new me(this.agentClient),this.roleMemoryStore=new L(e.rolePath),this.sessionContextMemoryStore=new L(S.join(S.dirname(e.rolePath),"..","session_context")),this.isSubAgent=process.env.AWS_SUB_AGENT==="true",this.contextManager=new le(this.sessionContextMemoryStore),this.server=new K({name:re,version:se},{capabilities:{tools:{}}}),this.setupHandlers()}setupHandlers(){this.server.setRequestHandler(Z,async()=>{let e=this.isSubAgent?F.filter(t=>x.has(t.name)):F;return!this.isSubAgent&&!await this.isLaunchConfigToolsEnabled()&&(e=e.filter(t=>!W.has(t.name))),!this.isSubAgent&&!await this.isHireToolsEnabled()&&(e=e.filter(t=>!q.has(t.name))),{tools:e}}),this.server.setRequestHandler(X,async(e,t)=>{const{name:r,arguments:i}=e.params;try{const s=await this.handleToolCall(r,i,t?.signal);return{content:this.buildToolResultContent(s)}}catch(s){const n=s instanceof Error?s.message:String(s),a=s instanceof ce?{error:n,...s.details}:{error:n};return o.error("[McpServer] \u5DE5\u5177\u8C03\u7528\u5F02\u5E38: tool=%s, error=%s, stack=%s",r,n,s instanceof Error?s.stack:"(no stack)"),{content:[{type:"text",text:JSON.stringify(a,null,2)}],isError:!0}}})}buildToolResultContent(e){if(e&&typeof e=="object"&&!Array.isArray(e)){const t=e;if(typeof t.image=="string"&&typeof t.mimeType=="string")return[{type:"image",data:t.image,mimeType:t.mimeType}]}return[{type:"text",text:JSON.stringify(e,null,2)}]}async handleToolCall(e,t,r){const i=t?._aws_sub_agent===!0,s=t?._aws_silent_poll===!0,n=t?._aws_force_inject===!0,a={...t};delete a._aws_sub_agent,delete a._aws_silent_poll,delete a._aws_force_inject;const l=i?null:this.agentClient.getStatusReporter();l&&!s&&this.safeReportStatus(()=>l.reportToolUse(e,this.sanitizeToolUseArgs(e,a)));try{const m=await this.executeToolCall(e,a,{forceInject:n,signal:r});if(l&&!s){const d=this.stripAutoDelegateForReporting(m);d!==null&&(this.safeReportStatus(()=>l.reportToolResult(d)),this.safeReportStatus(()=>l.reportThinking()))}return m}catch(m){throw l&&!s&&this.safeReportStatus(()=>l.reportToolError(m)),m}}safeReportStatus(e){try{e()}catch(t){o.warn("[McpServer] \u72B6\u6001\u4E0A\u62A5\u5931\u8D25\uFF08\u5DF2\u5FFD\u7565\uFF0C\u4E0D\u5F71\u54CD\u5DE5\u5177\u8C03\u7528\uFF09: %s",t instanceof Error?t.message:String(t))}}async executeToolCall(e,t,r={}){if(this.isSubAgent&&!x.has(e))throw new Error(`Sub-agent is not allowed to call tool: ${e}`);if(W.has(e)&&!await this.isLaunchConfigToolsEnabled())throw new Error("\u542F\u52A8\u9879\u7BA1\u7406\u80FD\u529B\u672A\u5F00\u542F\uFF08\u8BF7\u5148\u5728\u80FD\u529B\u914D\u7F6E\u4E2D\u5F00\u542F\u300CAgent \u7CFB\u7EDF\u7BA1\u7406 \u2192 \u542F\u52A8\u9879\u7BA1\u7406\u300D\u540E\u518D\u8C03\u7528 launch_config_* \u5DE5\u5177\uFF09");if(q.has(e)&&!await this.isHireToolsEnabled())throw new Error("\u62DB\u8058\u5DE5\u5177\u80FD\u529B\u672A\u5F00\u542F\uFF08\u8BF7\u5148\u5728\u80FD\u529B\u914D\u7F6E\u4E2D\u5F00\u542F\u300CAgent \u7CFB\u7EDF\u7BA1\u7406 \u2192 \u62DB\u8058\u5DE5\u5177\u300D\u540E\u518D\u8C03\u7528 hire_colleague\uFF09");switch(e){case"get_colleague":return await this.agentClient.discoverColleagues();case"get_group_rooms":return await this.agentClient.discoverGroupRooms();case"get_profile":return await this.agentClient.getProfile();case"hire_colleague":return await this.handleHireColleague(t);case"send_group":return await this.handleSendGroup(t);case"send_private":return await this.handleSendPrivate(t);case"poll_message":return await this.handlePollMessage(r.signal);case"get_message":return this.handleGetMessage(r.forceInject===!0);case"get_dm_history":return await this.handleGetDmHistory(t);case"get_group_history":return await this.handleGetGroupHistory(t);case"create_meeting":case"leave_meeting":case"end_meeting":case"meeting_speak":case"get_meeting_info":case"my_meetings":return await this.agentClient.callAgentScopedTool(e,t);case"my_task":return await this.agentClient.getMyTasks();case"create_task_instance_comment":return await this.handleCreateTaskInstanceComment(t);case"submit_task_result":return await this.handleSubmitTaskResult(t);case"start_task_rollback":return await this.handleStartTaskRollback(t);case"finish_task_rollback":return await this.handleFinishTaskRollback(t);case"reject_task":return await this.handleRejectTask(t);case"terminate_task":return await this.handleTerminateTask(t);case"create_memory":return await this.handleCreateMemory(t);case"read_memory":return await this.handleReadMemory(t);case"update_memory":return await this.handleUpdateMemory(t);case"delete_memory":return await this.handleDeleteMemory(t);case"search_memory":return await this.handleSearchMemory(t);case"list_memories":return await this.handleListMemories(t);case"get_memory_stats":return await this.handleGetMemoryStats(t);case"list_memories_by_file":return await this.handleListMemoriesByFile(t);case"abandon_memory_update":return await this.handleAbandonMemoryUpdate(t);case"memory_recurrence":return await this.handleMemoryRecurrence(t);case"memory_recurrence_complete":return await this.handleMemoryRecurrenceComplete(t);case"get_debug_log_config":return await this.agentClient.getDebugLogConfig();case"query_debug_logs":return await this.agentClient.queryDebugLogs(t);case"query_file_changes_history":return await this.agentClient.queryFileChangesHistory(t);case"launch_config_list":return await this.agentClient.listLaunchConfigs();case"launch_config_create":return await this.agentClient.createLaunchConfig(t);case"launch_config_update":return await this.agentClient.updateLaunchConfig(t);case"launch_config_delete":return await this.agentClient.deleteLaunchConfig(String(t?.configId??""));case"launch_config_start":return await this.agentClient.startLaunchConfig(t);case"launch_config_restart":return await this.agentClient.restartLaunchConfig(t);case"launch_config_stop":return await this.agentClient.stopLaunchConfig(String(t?.configId??""));case"launch_config_logs":return await this.agentClient.getLaunchLogs(t);case"launch_config_status":return await this.agentClient.listLaunchRuns();default:throw new Error(`Unknown tool: ${e}`)}}async isLaunchConfigToolsEnabled(){const{features:e,ok:t}=await this.fetchRuntimeFeaturesWithStatus();return t&&Object.keys(e).length>0?e[T.LAUNCH_ITEM_FEATURE_KEY]===!0:process.env[T.LAUNCH_TOOLS_ENV_KEY]==="1"}async isHireToolsEnabled(){const{features:e,ok:t}=await this.fetchRuntimeFeaturesWithStatus();return t&&Object.keys(e).length>0?e[T.HIRE_FEATURE_KEY]===!0:process.env[T.HIRE_TOOLS_ENV_KEY]==="1"}async fetchRuntimeFeaturesWithStatus(){const e=Date.now();if(this.featuresCache&&e-this.featuresCache.fetchedAt<T.FEATURES_CACHE_TTL_MS)return{features:this.featuresCache.features,ok:this.featuresCache.ok};let t={},r=!1;try{t=await this.agentClient.getRuntimeFeatures(),r=!0}catch(i){o.warn("[McpServer] \u83B7\u53D6\u80FD\u529B\u5F00\u5173\u5931\u8D25\uFF0C\u6309\u542F\u52A8\u671F env \u515C\u5E95: %s",i instanceof Error?i.message:String(i))}return this.featuresCache={features:t,ok:r,fetchedAt:e},{features:t,ok:r}}static MEMORY_TYPES=["recently_memory","agent_memory","project_memory","session_context"];static MEMORY_TOOL_NAMES=new Set(["create_memory","read_memory","update_memory","delete_memory","search_memory","list_memories","get_memory_stats","list_memories_by_file","abandon_memory_update","memory_recurrence","memory_recurrence_complete"]);static findAgentsworkDirSync(e){let t=S.resolve(e);for(;;){if(P.existsSync(S.join(t,".agentswork")))return S.join(t,".agentswork");const r=S.dirname(t);if(r===t)break;t=r}return S.join(S.resolve(e),".agentswork")}static sanitizeRoleDirectoryName(e){return String(e||"").trim().split("").map(r=>he.has(r)||r.charCodeAt(0)<32?"_":r).join("").replace(/^\.+|\.+$/g,"").trim()||"default-role"}static resolveRoleMemoryDirectoryName(){return T.sanitizeRoleDirectoryName(process.env.AWS_ROLE_NAME||"")}static buildRoleMemoryStorePath(e){const t=process.env.AWS_WORKSPACE_PATH||process.cwd(),r=T.findAgentsworkDirSync(t);return S.join(r,"memory","memory",T.sanitizeRoleDirectoryName(e))}static resolveMemoryStorePaths(){const e=String(process.env.AWS_MEMORY_STORE_PATH||"").trim();if(e)return{instancePath:e,rolePath:e};const t=process.env.AWS_WORKSPACE_PATH||process.cwd(),r=T.findAgentsworkDirSync(t),i=String(process.env.AWS_INSTANCE_MEMORY_STORE_PATH||"").trim()||S.join(r,"memory","server-managed"),s=String(process.env.AWS_ROLE_MEMORY_STORE_PATH||"").trim()||S.join(r,"memory","memory",T.resolveRoleMemoryDirectoryName());return{instancePath:i,rolePath:s}}getRequiredString(e,t){const r=e[t];if(typeof r!="string"||r.trim().length===0)throw new Error(`${t} is required`);return r}getOptionalString(e,t){const r=e[t];return typeof r=="string"?r:void 0}getOptionalNumber(e,t){const r=e[t];return typeof r=="number"?r:void 0}getOptionalStringArray(e,t){const r=e[t];return Array.isArray(r)?r.map(i=>String(i)):void 0}getOptionalMemoryType(e){const t=e.memory_type;if(t!==void 0)return this.parseMemoryType(t)}parseMemoryType(e){if(typeof e!="string")throw new Error(`Invalid memory_type: ${String(e)}`);const t=e.trim();if(!this.isMemoryType(t))throw new Error(`Invalid memory_type: ${e}`);return t}isMemoryType(e){return T.MEMORY_TYPES.some(t=>t===e)}getMemoryStoreForType(e){return this.memoryStore}async readMemoryFromScopedStores(e){if(e.memory_type)return await this.memoryStore.readMemory(e);const t=await this.memoryStore.readMemory({...e,memory_type:"project_memory"}).catch(()=>null);return t||await this.memoryStore.readMemory(e)}async backupProjectMemoryToLocal(e){try{const t=await this.memoryStore.readMemory({uri:e.uri,memory_type:"project_memory"});t&&(await this.roleMemoryStore.deleteMemory({uri:e.uri,memory_type:"project_memory"}).catch(()=>{}),await this.roleMemoryStore.createMemory(t))}catch(t){o.warn("[McpServer] backupProjectMemoryToLocal \u5931\u8D25: uri=%s",e.uri,t)}}async removeProjectMemoryLocalBackup(e){try{await this.roleMemoryStore.deleteMemory({uri:e,memory_type:"project_memory"})}catch(t){o.warn("[McpServer] removeProjectMemoryLocalBackup \u5931\u8D25: uri=%s",e,t)}}async findMemoryStoreForMutation(e){return e.memory_type?{store:this.memoryStore,memory_type:e.memory_type}:await this.memoryStore.readMemory({uri:e.uri,memory_type:"project_memory"}).catch(()=>null)?{store:this.memoryStore,memory_type:"project_memory"}:{store:this.memoryStore}}async reportMemoryStatsToServer(){const e=await this.memoryStore.getStats();try{await this.agentClient.reportMemoryStats(e)}catch(t){o.warn("[McpServer] \u4E0A\u62A5 memory \u7EDF\u8BA1\u5931\u8D25:",t)}}sanitizeToolUseArgs(e,t){if(!T.MEMORY_TOOL_NAMES.has(e))return t;const r={},i=this.getOptionalString(t,"uri"),s=this.getOptionalString(t,"memory_type"),n=this.getOptionalNumber(t,"limit");return i&&(r.uri=i),s&&(r.memory_type=s),typeof n=="number"&&(r.limit=n),e==="search_memory"&&(r.queryProvided=typeof t.query=="string"&&t.query.length>0,t.keyword_mode!==void 0&&(r.keyword_mode=t.keyword_mode)),r}stripAutoDelegateForReporting(e){if(!e||typeof e!="object")return e;const t=e,r=Array.isArray(t.directMessages)?t.directMessages:[],i=Array.isArray(t.groupMessages)?t.groupMessages:[],s=l=>!!l&&typeof l=="object"&&"_acodeAutoDelegate"in l;if(!r.some(s))return e;const a=r.filter(l=>!s(l));return a.length===0&&i.length===0?null:{...t,directMessages:a}}async handleCreateMemory(e){const t=this.normalizeBoundFiles(this.getOptionalStringArray(e,"bound_files"));await this.validateBoundFilesExist(t);let r,i;if(t&&t.length>0){r={};for(const a of t){const l=await this.calculateFileMd5(a);l&&(r[a]=l)}i=new Date().toISOString()}const s={memory_type:this.parseMemoryType(this.getRequiredString(e,"memory_type")),uri:this.getRequiredString(e,"uri"),title:this.getOptionalString(e,"title"),content:this.getRequiredString(e,"content"),keywords:this.getOptionalStringArray(e,"keywords"),bound_files:t,file_md5_map:r,last_check_time:i},n=await this.memoryStore.createMemory(s);return s.memory_type==="project_memory"&&this.backupProjectMemoryToLocal(s).catch(a=>{o.warn("[McpServer] \u5907\u4EFD project_memory \u5230\u672C\u5730\u5931\u8D25:",a)}),await this.reportMemoryStatsToServer(),this.toMemoryWriteResult(n)}async handleReadMemory(e){const t={uri:this.getRequiredString(e,"uri"),memory_type:this.getOptionalMemoryType(e)};return await this.readMemoryFromScopedStores(t)}async handleUpdateMemory(e){const t=typeof e.old_string=="string"||typeof e.new_string=="string",r=typeof e.old_string=="string"&&typeof e.new_string=="string",i=this.getOptionalString(e,"append");if(t&&!r)throw new Error("old_string and new_string must be provided together");const s={uri:this.getRequiredString(e,"uri"),memory_type:this.getOptionalMemoryType(e),title:this.getOptionalString(e,"title"),old_string:this.getOptionalString(e,"old_string"),new_string:this.getOptionalString(e,"new_string"),append:i,keywords:this.getOptionalStringArray(e,"keywords"),bound_files:this.normalizeBoundFiles(this.getOptionalStringArray(e,"bound_files"))},n=await this.findMemoryStoreForMutation(s),a=await n.store.readMemory({uri:s.uri,memory_type:n.memory_type??s.memory_type});s.bound_files!==void 0?await this.validateBoundFilesExist(s.bound_files):a?.bound_files&&a.bound_files.length>0&&await this.validateBoundFilesExist(a.bound_files);const l=s.bound_files??a?.bound_files;let m,d;if(l&&l.length>0){m={};for(const u of l){const _=await this.calculateFileMd5(u);_&&(m[u]=_)}d=new Date().toISOString()}const g=await n.store.updateMemory({...s,memory_type:n.memory_type??s.memory_type,file_md5_map:m,last_check_time:d});if(n.memory_type==="project_memory"&&this.backupProjectMemoryToLocal({...s,memory_type:"project_memory",file_md5_map:m,last_check_time:d}).catch(u=>{o.warn("[McpServer] \u5907\u4EFD project_memory \u66F4\u65B0\u5230\u672C\u5730\u5931\u8D25:",u)}),await this.reportMemoryStatsToServer(),n.memory_type==="project_memory"&&a?.memory_status==="updating")try{await this.memoryStore.releaseMemoryClaim(s.uri),this.activeLeaseUris.delete(s.uri),this.activeLeaseUris.size===0&&this.stopLeaseRenewal()}catch(u){o.warn("[McpServer] \u91CA\u653E memory claim \u5931\u8D25: uri=%s, error=%s",s.uri,u instanceof Error?u.message:String(u))}return this.toMemoryWriteResult(g)}async handleDeleteMemory(e){const t=typeof e.uri=="string"?e.uri:void 0,r=Array.isArray(e.memories)?e.memories:void 0;if(t&&r&&r.length>0)throw new Error("delete_memory \u4E0D\u652F\u6301\u540C\u65F6\u4F20\u5165 uri \u548C memories\uFF0C\u8BF7\u4E8C\u9009\u4E00");if(!t&&(!r||r.length===0))throw new Error("delete_memory \u9700\u8981 uri \u6216 memories \u53C2\u6570");if(t){const a=this.getOptionalMemoryType(e);return{deleted:await this.deleteMemorySingle(t,a)}}let i=0;const s=[],n=[];for(let a=0;a<r.length;a++){const l=r[a];if(typeof l!="object"||l===null){n.push({uri:String(l),reason:`memories[${a}] \u4E0D\u662F\u5BF9\u8C61`});continue}const m=l,d=typeof m.uri=="string"?m.uri:"";if(!d){n.push({uri:"",reason:`memories[${a}].uri \u7F3A\u5931`});continue}const g=typeof m.memory_type=="string"?this.parseMemoryType(m.memory_type):void 0;try{await this.deleteMemorySingle(d,g,!0)?i++:s.push(d)}catch(u){n.push({uri:d,reason:u instanceof Error?u.message:String(u)})}}return i>0&&await this.reportMemoryStatsToServer(),{deleted:i,not_found:s,failed:n}}async deleteMemorySingle(e,t,r=!1){const i={uri:e,memory_type:t},s=await this.findMemoryStoreForMutation(i),n=s.memory_type??i.memory_type,a=await s.store.deleteMemory({...i,memory_type:n});return a&&(n==="project_memory"&&this.removeProjectMemoryLocalBackup(e).catch(l=>{o.warn("[McpServer] \u5220\u9664 project_memory \u672C\u5730\u5907\u4EFD\u5931\u8D25:",l)}),r||await this.reportMemoryStatsToServer()),a}async handleSearchMemory(e){const t=this.getOptionalString(e,"scope"),r=t==="children"||t==="all"?t:"own",i=this.getOptionalString(e,"keyword_mode"),s=i==="all"?"all":i==="any"?"any":void 0,n={query:this.getRequiredString(e,"query"),limit:this.getOptionalNumber(e,"limit"),memory_type:this.getOptionalMemoryType(e),keywords:this.getOptionalStringArray(e,"keywords"),keyword_mode:s,scope:r};if(r==="children")return await this.memoryStore.searchMemory(n);const a=await this.searchOwnMemories(n);if(r==="own")return a;const l=await this.memoryStore.searchMemory({...n,scope:"children"});return this.mergeSearchResults(a,l,n.limit)}async searchOwnMemories(e){return await this.memoryStore.searchMemory(e)}mergeSearchResults(e,t,r){const i=new Set,s=typeof r=="number"&&r>0?r:10,n=[...e.results,...t.results].filter(a=>{const l=a.uri;return i.has(l)?!1:(i.add(l),!0)}).sort((a,l)=>l.updatedAt.localeCompare(a.updatedAt)).slice(0,s);return{query:e.query||t.query,results:n}}async handleListMemories(e){const t=this.getRequiredString(e,"memory_type"),r=this.getOptionalNumber(e,"offset"),i=this.getOptionalNumber(e,"limit"),s=Math.max(0,Math.floor(r??0)),n=i!==void 0&&i>=1?Math.floor(i):de,a=await this.memoryStore.listByType(t),l=a.length,m=a.slice(s,s+n);return{memory_type:t,total:l,offset:s,limit:n,has_more:s+n<l,memories:m}}async handleGetMemoryStats(e){const t=await this.memoryStore.getStats(),r=this.getOptionalMemoryType(e);return r?{memory_type:r,total:t.by_type[r].count,by_type:{[r]:t.by_type[r]}}:t}async handleListMemoriesByFile(e){const t=this.getRequiredString(e,"file_path"),r=this.normalizeBoundFilePath(t),i=this.getOptionalMemoryType(e),s=this.getOptionalString(e,"scope"),n=s==="own"||s==="children"?s:"all",a=async()=>await this.memoryStore.listByFile(r,{memory_type:i,scope:"children"}).catch(()=>[]);if(n==="children"){const u=await a();return{file_path:r,count:u.length,memories:u.map(_=>this.toMemoryRecordWithMetadata(_))}}if(n==="own"){const u=await this.collectOwnMemoriesByFile(r,i);return{file_path:r,count:u.length,memories:u.map(_=>this.toMemoryRecordWithMetadata(_))}}const[l,m,d]=await Promise.all([this.memoryStore.listByFile(r,{memory_type:i,scope:"all"}).catch(()=>[]),this.searchChildMemoriesByFileLocal(r,i).catch(()=>[]),this.searchPeerMemoriesByFileLocal(r,i).catch(()=>[])]),g=this.mergeIdDedupe(this.mergeIdDedupe(l,m),d);return{file_path:r,count:g.length,memories:g.map(u=>this.toMemoryRecordWithMetadata(u))}}mergeIdDedupe(e,t){const r=new Set;for(const s of e)s.id&&r.add(s.id);const i=[...e];for(const s of t)s.id&&!r.has(s.id)&&(i.push(s),r.add(s.id));return i.sort((s,n)=>n.updatedAt.localeCompare(s.updatedAt)),i}async searchChildMemoriesByFileLocal(e,t){const r=process.env.AWS_WORKSPACE_PATH||process.cwd(),i=this.normalizeBoundFilePath(e),n=(i.startsWith("./")?i.substring(2):i).split("/"),a=[],l=new Set,{access:m,readdir:d,readFile:g}=await import("node:fs/promises");for(let u=n.length-1;u>=1;u--){const _=n.slice(0,u),h="./"+n.slice(u).join("/"),M=S.join(r,..._);if(M===r)continue;const c=S.join(M,".agentswork");try{await m(c)}catch{continue}const y=S.join(c,"memory","memory");let p;try{p=(await d(y,{withFileTypes:!0})).filter(v=>v.isDirectory()).map(v=>v.name)}catch{continue}for(const w of p){const v=S.join(y,w);let k;try{k=await d(v)}catch{continue}for(const f of k){if(!f.endsWith(".json"))continue;const C=S.join(v,f);let R;try{R=await g(C,"utf-8")}catch{continue}let A;try{A=JSON.parse(R)}catch{continue}if(A.by_uri)for(const[N,$]of Object.entries(A.by_uri)){if(!$)continue;const B=$.id||N;l.has(B)||t&&$.memory_type!==t||$.bound_files&&$.bound_files.length>0&&$.bound_files.some(J=>this.normalizeBoundFilePath(J)===h)&&(l.add(B),a.push({...$,uri:$.uri||N}))}}}}return a.sort((u,_)=>String(_.updatedAt??"").localeCompare(String(u.updatedAt??""))),a}async searchPeerMemoriesByFileLocal(e,t){if(!this.hasRoleName||!this.initialRoleName)return[];const r=process.env.AWS_WORKSPACE_PATH||process.cwd(),i=this.normalizeBoundFilePath(e),s=S.join(r,".agentswork","memory","memory"),{access:n,readdir:a,readFile:l}=await import("node:fs/promises");try{await n(s)}catch{return[]}let m;try{m=(await a(s,{withFileTypes:!0})).filter(_=>_.isDirectory()).map(_=>_.name)}catch{return[]}const d=[],g=new Set;for(const u of m){if(u===this.initialRoleName)continue;const _=S.join(s,u);let b;try{b=await a(_)}catch{continue}for(const h of b){if(!h.endsWith(".json"))continue;let M;try{M=JSON.parse(await l(S.join(_,h),"utf-8"))}catch{continue}if(M.by_uri)for(const[c,y]of Object.entries(M.by_uri)){if(!y)continue;const p=y.id||c;g.has(p)||y.memory_type==="project_memory"&&(t&&y.memory_type!==t||y.bound_files&&y.bound_files.length>0&&y.bound_files.some(v=>this.normalizeBoundFilePath(v)===i)&&(g.add(p),d.push({...y,uri:y.uri||c,readonly:!0,source_role_name:u})))}}}return d.sort((u,_)=>String(_.updatedAt??"").localeCompare(String(u.updatedAt??""))),d}async collectOwnMemoriesByFile(e,t){return await this.memoryStore.listByFile(e,{memory_type:t})}async handleAbandonMemoryUpdate(e){const t=this.getRequiredString(e,"uri"),r=this.getOptionalMemoryType(e),i=await this.memoryStore.readMemory({uri:t,memory_type:r});return i?.bound_files&&i.bound_files.length>0&&await this.validateBoundFilesExist(i.bound_files),await this.memoryStore.releaseMemoryClaim(t),i?.memory_type==="project_memory"&&this.backupProjectMemoryToLocal({uri:t,memory_type:"project_memory"}).catch(s=>{o.info(`[McpServer] abandon_memory_update: \u540C\u6B65\u672C\u5730\u5907\u4EFD\u5931\u8D25: ${t}`,s)}),this.activeLeaseUris.delete(t),this.activeLeaseUris.size===0&&this.stopLeaseRenewal(),{success:!0,uri:t,message:"Memory \u66F4\u65B0\u72B6\u6001\u5DF2\u6E05\u9664"}}async handleMemoryRecurrence(e){const t=Math.max(1,e?.limit??10);try{((await this.memoryStore.markExpiredMemoriesRecalling()).uris?.length??0)>0&&this.startLeaseRenewal()}catch(l){o.warn("[McpServer] \u539F\u5B50\u8BA4\u9886\u8FC7\u671F\u8BB0\u5FC6\u5931\u8D25: %s",l instanceof Error?l.message:String(l))}const r=await this.memoryStore.listExpiredRecentlyMemories();if(r.length===0)return{memories:[],count:0,limit:t,remaining:0,totalExpired:0,message:"\u6CA1\u6709\u5F85\u56DE\u5FC6\u7684\u5373\u5C06\u9057\u5FD8\u8BB0\u5FC6\u3002"};const s=[...r].sort((l,m)=>{const d=new Date(l.expiresAt||l.createdAt||0).getTime(),g=new Date(m.expiresAt||m.createdAt||0).getTime();return d-g}).slice(0,t),n=Math.max(0,r.length-s.length);return{memories:s.map(l=>({uri:l.uri,title:l.title,domain:l.domain,path:l.path,memory_status:"recalling",contentPreview:typeof l.content=="string"&&l.content.length>200?l.content.substring(0,200)+"...":l.content,createdAt:l.createdAt,updatedAt:l.updatedAt})),count:s.length,limit:t,remaining:n,totalExpired:r.length,message:n>0?`\u672C\u6B21\u5904\u7406 ${s.length} \u6761\u5373\u5C06\u9057\u5FD8\u7684\u8BB0\u5FC6\uFF08\u6700\u65E9\u8FC7\u671F\u4F18\u5148\uFF09\uFF0C\u5269\u4F59 ${n} \u6761\u5F85\u5904\u7406\u3002
4
4
  \u8BF7\u5BA1\u67E5\u540E\u51B3\u5B9A\uFF08update_memory \u7EED\u671F\uFF0CTTL \xD72 / \u4E0D\u5904\u7406\uFF09\uFF0C
5
5
  \u672C\u6279\u5BA1\u67E5\u5B8C\u6BD5\u540E\u8C03\u7528 memory_recurrence_complete(uris=[\u672C\u6279\u786E\u5B9A\u5220\u9664\u7684URI]) \u6E05\u7406\uFF0C\u518D\u8C03 memory_recurrence \u5904\u7406\u4E0B\u4E00\u6279\u3002`:`\u5DF2\u5904\u7406\u5168\u90E8 ${s.length} \u6761\u5373\u5C06\u9057\u5FD8\u7684\u8BB0\u5FC6\u3002
6
6
  \u8BF7\u5BA1\u67E5\u540E\u51B3\u5B9A\uFF08update_memory \u7EED\u671F\uFF0CTTL \xD72 / \u4E0D\u5904\u7406\uFF09\uFF0C
7
7
  \u672C\u6279\u5BA1\u67E5\u5B8C\u6BD5\u540E\u8C03\u7528 memory_recurrence_complete(uris=[\u672C\u6279\u786E\u5B9A\u5220\u9664\u7684URI]) \u6E05\u7406\u3002`}}async handleMemoryRecurrenceComplete(e){let t={deleted:0,uris:[]};try{t=await this.memoryStore.clearRecallingExpiredMemories(e?.uris)}catch(i){o.warn("[McpServer] \u6E05\u7406\u56DE\u5FC6\u4E2D\u8BB0\u5FC6\u5931\u8D25: %s",i instanceof Error?i.message:String(i))}await this.reportMemoryStatsToServer();const r=t.deleted??0;return{deleted:r,uris:t.uris??[],message:r===0?"\u6CA1\u6709\u5F85\u758F\u7406\u7684\u56DE\u5FC6\u4E2D\u8BB0\u5FC6\u3002":`\u5DF2\u6E05\u7406 ${r} \u6761\u5DF2\u8FC7\u671F\u8FD1\u671F\u8BB0\u5FC6\u3002`}}async fetchRecentMessages(){const[e,t]=await Promise.all([this.agentClient.getDmHistory(void 0,200).catch(()=>({messages:[],count:0})),this.agentClient.getGroupHistory(200).catch(()=>({messages:[],count:0}))]),r=[...e.messages,...t.messages];return r.sort((i,s)=>new Date(i.timestamp).getTime()-new Date(s.timestamp).getTime()),r}async handleSendGroup(e){const t=typeof e.content=="string"?e.content:"",r=Array.isArray(e.attachments)?e.attachments:[];if(!t.trim()&&r.length===0)throw new Error("content \u4E0E attachments \u81F3\u5C11\u63D0\u4F9B\u4E00\u4E2A\u975E\u7A7A\u503C");const i=r.length>0?this.mergeContentWithAttachmentMarkers(t,await this.uploadAttachmentFiles(r)):t;return this.recordMessageTokenUsage(i).catch(s=>o.warn("[McpServer] Failed to record token usage",s)),await this.agentClient.sendGroupMessage(i,e.projectId,e.roomId)}async uploadAttachmentFiles(e){if(e.length===0)return[];const t=process.env.AWS_WORKSPACE_PATH||process.cwd(),r=S.resolve(t),i=this.agentClient.getServerConfig(),s=te(i.serverUrl,{fromAgentWebSocketUrl:!0})||"",n=i.runtimeAccessToken||"",a=[];for(const l of e){if(typeof l!="string"||!l.trim())throw new Error("attachments \u4E2D\u5B58\u5728\u7A7A\u8DEF\u5F84");const m=S.resolve(r,l);let d;try{d=await P.promises.stat(m)}catch{throw new Error(`\u9644\u4EF6\u6587\u4EF6\u4E0D\u5B58\u5728: ${l}\uFF08\u89E3\u6790\u4E3A ${m}\uFF09`)}if(!d.isFile())throw new Error(`\u9644\u4EF6\u4E0D\u662F\u666E\u901A\u6587\u4EF6: ${l}`);if(d.size>Y)throw new Error(`\u9644\u4EF6\u6587\u4EF6\u8FC7\u5927\uFF08\u4E0A\u9650 ${Math.floor(Y/1024/1024)}MB\uFF09: ${l}`);const g=S.basename(m),u=pe(m),_=new FormData;_.append("file",new Blob([await P.promises.readFile(m)],{type:u}),g);const b=await this.uploadFileRequest(`${s}/api/files/upload`,_,n,g);if(!b.ok){const M=await b.text().catch(()=>"");throw new Error(`\u9644\u4EF6\u4E0A\u4F20\u5931\u8D25 (HTTP ${b.status}): ${g}${M?` - ${M.slice(0,200)}`:""}`)}const h=await b.json();if(!h?.url)throw new Error(`\u9644\u4EF6\u4E0A\u4F20\u54CD\u5E94\u7F3A\u5C11 url: ${g}`);a.push({name:h.name||g,url:h.url.startsWith("http")?h.url:`${s}${h.url}`,mediaType:h.mediaType||u,size:typeof h.size=="number"?h.size:d.size})}return a}async uploadFileRequest(e,t,r,i){try{return await fetch(e,{method:"POST",headers:r?{"X-Runtime-Token":r}:void 0,body:t})}catch(s){const n=s?.cause,a=n?.code||n?.message||(s instanceof Error?s.message:String(s));throw new Error(`\u9644\u4EF6\u4E0A\u4F20\u8BF7\u6C42\u5931\u8D25\uFF08\u670D\u52A1\u7AEF\u4E0D\u53EF\u8FBE ${e}\uFF09: ${i} - ${a}`)}}mergeContentWithAttachmentMarkers(e,t){if(t.length===0)return e;const r=t.map(_e).join(`
8
8
  `);return e.trim()?`${e}
9
9
 
10
- ${r}`:r}async recordMessageTokenUsage(e){try{const t=await this.agentClient.getProfile().catch(()=>null);if(!t?.runtimeSessionId)return;const r=this.contextManager.estimateTokens(e);await this.contextManager.recordUsage(t.runtimeSessionId,{input:0,output:r})}catch{}}async handleHireColleague(e){if(!e.workspacePath||typeof e.workspacePath!="string")throw new Error("workspacePath is required");return await this.agentClient.hireColleague(e)}async handleHireColleaguesBatch(e){if(!Array.isArray(e.items)||e.items.length===0)throw new Error("items is required and must contain at least one hire item");return e.items.forEach((t,r)=>{if(!t.workspacePath||typeof t.workspacePath!="string")throw new Error(`items[${r}].workspacePath is required`)}),await this.agentClient.hireColleaguesBatch(e)}async handleSendPrivate(e){if(!e.targetId||typeof e.targetId!="string")throw new Error("targetId is required");const t=typeof e.content=="string"?e.content:"",r=Array.isArray(e.attachments)?e.attachments:[];if(!t.trim()&&r.length===0)throw new Error("content \u4E0E attachments \u81F3\u5C11\u63D0\u4F9B\u4E00\u4E2A\u975E\u7A7A\u503C");const i=r.length>0?this.mergeContentWithAttachmentMarkers(t,await this.uploadAttachmentFiles(r)):t;return this.recordMessageTokenUsage(i).catch(s=>o.warn("[McpServer] Failed to record token usage",s)),await this.agentClient.sendDirectMessage(e.targetId,i,e.waitReply,e.replyToCallId,e.timeoutMs)}async handleCreateTaskInstanceComment(e){const t=this.getRequiredString(e,"taskInstanceId"),r=this.getRequiredString(e,"content");return await this.agentClient.createTaskInstanceComment({taskInstanceId:t,content:r})}async prependMemoryNotification(e,t){const r=await t();return r?(e.directMessages.unshift(r),!0):!1}async handlePollMessage(e){if(o.info("[McpServer] handlePollMessage \u88AB\u8C03\u7528"),this.pendingPollMessage)return o.info("[McpServer] poll_message \u5DF2\u6709\u8FDB\u884C\u4E2D\u7684\u8C03\u7528\uFF0C\u7B49\u5F85\u5176\u5B8C\u6210"),E("poll.singleton-join","\u7B2C\u4E8C\u4E2A poll_message \u8C03\u7528\u5230\u8FBE\uFF0C\u5408\u5E76\u5230\u8FDB\u884C\u4E2D\u7684 poll Promise\uFF08\u82E5\u9996\u4E2A\u5FAA\u73AF\u5361\u6B7B\u5219\u4E24\u8005\u4E00\u8D77\u6302\u8D77\uFF09"),await this.pendingPollMessage;const t=Date.now();this.pendingPollMessage=(async()=>await this.doPollMessage(e))();try{const r=await this.pendingPollMessage;return o.info("[McpServer] poll_message Promise resolved\uFF0C\u8017\u65F6 %dms, directMessages=%d, groupMessages=%d",Date.now()-t,Array.isArray(r?.directMessages)?r.directMessages.length:-1,Array.isArray(r?.groupMessages)?r.groupMessages.length:-1),E("poll.resolved",`elapsedMs=${Date.now()-t} dm=${D(r?.directMessages)} gm=${D(r?.groupMessages)}`),r}catch(r){throw o.warn("[McpServer] poll_message Promise rejected\uFF0C\u8017\u65F6 %dms: %s",Date.now()-t,r instanceof Error?r.message:String(r)),E("poll.rejected",`elapsedMs=${Date.now()-t} error=${r instanceof Error?r.message:String(r)}`),r}finally{this.pendingPollMessage=null}}async doPollMessage(e){if(o.info("[McpServer] doPollMessage \u88AB\u8C03\u7528"),E("poll.enter","doPollMessage \u5165\u53E3"),e?.aborted)return o.info("[McpServer] poll_message \u8C03\u7528\u5DF2\u88AB\u5BA2\u6237\u7AEF\u53D6\u6D88\uFF0C\u8DF3\u8FC7\u963B\u585E\u7B49\u5F85"),this.buildPollResult({directMessages:[],groupMessages:[]});const t=await this.buildTodoBlockNotification();if(t)return this.buildPollResult({directMessages:[t],groupMessages:[]});await this.hydrateUnreadMessagesFromServer({blockIfEmpty:!1,includePipelineTasks:!0,pollMessageTimeoutMs:5e3,preemptiveJoinWaitMs:0}),await this.hydrateBrowserListenerEvents(),await this.hydratePluginEvents();const r=await this.buildBackgroundTaskNotification(),i=await this.confirmServerMessages(this.messageBuffer.get());if(i.directMessages.length>0||i.groupMessages.length>0)return e?.aborted?(this.messageBuffer.requeue(i),o.info("[McpServer] poll_message \u5165\u53E3\u68C0\u67E5\u671F\u95F4\u88AB\u5BA2\u6237\u7AEF\u53D6\u6D88\uFF0C\u56DE\u6EDA\u672A\u4EA4\u4ED8\u6D88\u606F"),this.buildPollResult({directMessages:[],groupMessages:[]})):(r&&i.directMessages.unshift(r),this.buildPollResult(i));if(r)return this.buildPollResult({directMessages:[r],groupMessages:[]});const s=await this.checkAllLocalNonUrgentNotifications();if(s.length>0)return this.buildPollResult({directMessages:s,groupMessages:[]});let n=!1,a=0,l=0;for(;;){if(e?.aborted)return o.info("[McpServer] poll_message \u7B49\u5F85\u671F\u95F4\u88AB\u5BA2\u6237\u7AEF\u53D6\u6D88\uFF0C\u9000\u51FA\u963B\u585E\u5FAA\u73AF"),E("poll.loop-abort","\u7B49\u5F85\u671F\u95F4\u88AB\u5BA2\u6237\u7AEF\u53D6\u6D88\uFF0C\u9000\u51FA\u963B\u585E\u5FAA\u73AF"),this.buildPollResult({directMessages:[],groupMessages:[]});if(!n){const p=this.agentClient.getStatusReporter();if(p){const w=p.getCurrentStatus();w.status==="tool_using"&&w.actionDetail!=null&&w.actionDetail.includes("poll_message")||p.reportToolUse("poll_message",{}),n=!0}}const m=await this.confirmServerMessages(await this.messageBuffer.poll(ue));if(l++,E("poll.loop-tick",`\u7B2C ${l} \u62CD: polled dm=${m.directMessages.length} gm=${m.groupMessages.length}`),e?.aborted)return this.messageBuffer.requeue(m),o.info("[McpServer] poll_message \u7B49\u5F85\u671F\u95F4\u88AB\u5BA2\u6237\u7AEF\u53D6\u6D88\uFF0C\u56DE\u6EDA %d \u6761\u672A\u4EA4\u4ED8\u6D88\u606F\u540E\u9000\u51FA\u963B\u585E\u5FAA\u73AF",m.directMessages.length+m.groupMessages.length),this.buildPollResult({directMessages:[],groupMessages:[]});if(m.directMessages.length>0||m.groupMessages.length>0)return this.buildPollResult(m);if(o.debug("[McpServer] poll \u8D85\u65F6\uFF0C\u68C0\u67E5\u6D4F\u89C8\u5668\u76D1\u542C\u5668\u4E8B\u4EF6"),await this.hydrateBrowserListenerEvents()){if(e?.aborted)return o.info("[McpServer] poll_message \u76D1\u542C\u5668\u4E8B\u4EF6\u68C0\u67E5\u671F\u95F4\u88AB\u5BA2\u6237\u7AEF\u53D6\u6D88\uFF0C\u9000\u51FA\u963B\u585E\u5FAA\u73AF"),this.buildPollResult({directMessages:[],groupMessages:[]});const p=await this.confirmServerMessages(this.messageBuffer.get());if(p.directMessages.length>0||p.groupMessages.length>0)return e?.aborted?(this.messageBuffer.requeue(p),o.info("[McpServer] poll_message \u76D1\u542C\u5668\u4E8B\u4EF6\u786E\u8BA4\u671F\u95F4\u88AB\u5BA2\u6237\u7AEF\u53D6\u6D88\uFF0C\u56DE\u6EDA %d \u6761\u672A\u4EA4\u4ED8\u6D88\u606F",p.directMessages.length+p.groupMessages.length),this.buildPollResult({directMessages:[],groupMessages:[]})):(o.info("[McpServer] \u76D1\u542C\u5668\u4E8B\u4EF6\u5DF2\u6CE8\u5165\uFF0Cpoll_message \u8FD4\u56DE %d \u6761\u79C1\u4FE1",p.directMessages.length),this.buildPollResult(p))}if(o.debug("[McpServer] poll \u8D85\u65F6\uFF0C\u68C0\u67E5\u63D2\u4EF6\u4E8B\u4EF6"),await this.hydratePluginEvents()){if(e?.aborted)return o.info("[McpServer] poll_message \u63D2\u4EF6\u4E8B\u4EF6\u68C0\u67E5\u671F\u95F4\u88AB\u5BA2\u6237\u7AEF\u53D6\u6D88\uFF0C\u9000\u51FA\u963B\u585E\u5FAA\u73AF"),this.buildPollResult({directMessages:[],groupMessages:[]});const p=await this.confirmServerMessages(this.messageBuffer.get());if(p.directMessages.length>0||p.groupMessages.length>0)return e?.aborted?(this.messageBuffer.requeue(p),o.info("[McpServer] poll_message \u63D2\u4EF6\u4E8B\u4EF6\u786E\u8BA4\u671F\u95F4\u88AB\u5BA2\u6237\u7AEF\u53D6\u6D88\uFF0C\u56DE\u6EDA %d \u6761\u672A\u4EA4\u4ED8\u6D88\u606F",p.directMessages.length+p.groupMessages.length),this.buildPollResult({directMessages:[],groupMessages:[]})):(o.info("[McpServer] \u63D2\u4EF6\u4E8B\u4EF6\u5DF2\u6CE8\u5165\uFF0Cpoll_message \u8FD4\u56DE %d \u6761\u79C1\u4FE1",p.directMessages.length),this.buildPollResult(p))}a++;let u=!1;if(this.urgentMeetingHydrateRequested&&(this.urgentMeetingHydrateRequested=!1,a=B,u=!0),a<B)continue;a=0;const _=await this.buildTodoBlockNotification();if(_)return this.buildPollResult({directMessages:[_],groupMessages:[]});let b=!1;const h=u?R.MEETING_HYDRATE_RETRY_COUNT:1;for(let p=1;p<=h;p++){o.info("[McpServer] %s hydrate poll_message\uFF0C\u7B2C %d/%d \u6B21",u?"\u4F1A\u8BAE\u9080\u8BF7\u5F3A\u5236":"\u666E\u901A",p,h);const w=this.messageBuffer.size();if(u&&w>0){o.info("[McpServer] \u4F1A\u8BAE\u9080\u8BF7\u5F3A\u5236 hydrate \u524D\u53D1\u73B0\u672C\u5730\u7F13\u51B2\u5DF2\u6709 %d \u6761\u6D88\u606F\uFF0C\u8DF3\u8FC7 hydrate \u76F4\u63A5\u4EA4\u4ED8",w);break}const v={blockIfEmpty:!1,includePipelineTasks:!0,pollMessageTimeoutMs:u?R.MEETING_HYDRATE_POLL_TIMEOUT_MS:void 0,skipGroupMessages:u,preemptiveJoinWaitMs:u?R.MEETING_PREEMPTIVE_JOIN_WAIT_MS:0,propagatePollTimeout:u},k=Date.now(),f=await this.hydrateUnreadMessagesFromServer(v);if(u&&E("poll.forced-hydrate-outcome",`\u7B2C ${p}/${h} \u6B21\u5F3A\u5236 hydrate \u5B8C\u6210\uFF08\u8017\u65F6 ${Date.now()-k}ms\uFF09: timedOut=${f.timedOut} failed=${f.failed} \u7F13\u51B2\u533A=${this.messageBuffer.size()} \u6761`),f.timedOut){o.warn("[McpServer] \u4F1A\u8BAE\u9080\u8BF7\u5F3A\u5236 hydrate \u7B2C %d/%d \u6B21\u5BA2\u6237\u7AEF\u8D85\u65F6\uFF08\u670D\u52A1\u7AEF\u53EF\u80FD\u4ECD\u5728\u6267\u884C\u4E0A\u4E00\u8BF7\u6C42\uFF09\uFF0C\u505C\u6B62\u7ACB\u5373\u91CD\u8BD5",p,h),b=!0;break}const C=this.messageBuffer.size();if(o.info("[McpServer] hydrate poll_message \u5B8C\u6210\uFF0C\u7B2C %d/%d \u6B21\uFF0C\u7F13\u51B2\u533A\u6D88\u606F\u6570=%d",p,h,C),C>0||!u)break;p<h&&await new Promise(T=>setTimeout(T,R.MEETING_HYDRATE_RETRY_DELAY_MS))}b&&(E("poll.forced-hydrate-rearm",`\u5F3A\u5236 hydrate \u8D85\u65F6\uFF0C${this.meetingHydrateTimeoutRearmDelayMs}ms \u540E\u91CD\u65B0\u7F6E\u4F4D\u5524\u9192\u6807\u8BB0`),setTimeout(()=>{o.info("[McpServer] \u4F1A\u8BAE\u5F3A\u5236 hydrate \u8D85\u65F6\u81EA\u6108\uFF1A\u91CD\u65B0\u7F6E\u4F4D\u5524\u9192\u6807\u8BB0\u89E6\u53D1\u4E0B\u4E00\u8F6E\u5F3A\u5236 hydrate"),this.urgentMeetingHydrateRequested=!0,this.messageBuffer.wakeUpWaiters()},this.meetingHydrateTimeoutRearmDelayMs).unref());const M=await this.buildBackgroundTaskNotification();if(e?.aborted)return o.info("[McpServer] poll_message hydrate \u540E\u68C0\u67E5\u671F\u95F4\u88AB\u5BA2\u6237\u7AEF\u53D6\u6D88\uFF0C\u9000\u51FA\u963B\u585E\u5FAA\u73AF"),this.buildPollResult({directMessages:[],groupMessages:[]});const c=await this.confirmServerMessages(this.messageBuffer.get());if(c.directMessages.length>0||c.groupMessages.length>0)return e?.aborted?(this.messageBuffer.requeue(c),o.info("[McpServer] poll_message hydrate \u786E\u8BA4\u671F\u95F4\u88AB\u5BA2\u6237\u7AEF\u53D6\u6D88\uFF0C\u56DE\u6EDA %d \u6761\u672A\u4EA4\u4ED8\u6D88\u606F",c.directMessages.length+c.groupMessages.length),this.buildPollResult({directMessages:[],groupMessages:[]})):(M&&c.directMessages.unshift(M),this.buildPollResult(c));if(u&&!M&&!b&&(o.info("[McpServer] \u4F1A\u8BAE\u9080\u8BF7\u5524\u9192\u540E\u7684\u5F3A\u5236 hydrate \u672A\u53D6\u5230\u53EF\u6295\u9012\u6D88\u606F\uFF08\u670D\u52A1\u7AEF\u672A\u62A2\u5360\u6216\u65E0\u65B0\u4F1A\u8BAE\u5185\u5BB9\uFF09\uFF0C\u7EE7\u7EED\u7B49\u5F85"),E("poll.forced-hydrate-empty","\u4F1A\u8BAE\u9080\u8BF7\u5524\u9192\u540E\u7684\u5F3A\u5236 hydrate \u672A\u53D6\u5230\u4EFB\u4F55\u53EF\u6295\u9012\u6D88\u606F\uFF08\u670D\u52A1\u7AEF\u672A\u62A2\u5360/\u65E0\u65B0\u5185\u5BB9/\u6D88\u606F\u88AB\u53BB\u91CD\u62E6\u622A\uFF09\uFF0C\u7EE7\u7EED\u7B49\u5F85"),a=B-1),M)return this.buildPollResult({directMessages:[M],groupMessages:[]});const y=await this.checkAllLocalNonUrgentNotifications(!1);if(y.length>0)return this.buildPollResult({directMessages:y,groupMessages:[]})}}async checkAllLocalNonUrgentNotifications(e=!0){const t=[],r=await this.buildMemoryRecurrenceNotification();if(r&&t.push(r),e){const s=await this.buildMemoryFileChangeNotification();s&&t.push(s)}const i=await this.buildMemoryCleanupNotification();return i&&t.push(i),t}buildPollResult(e,t=!0){return o.info("[McpServer][DEBUG-poll] \u8FD4\u56DE poll \u7ED3\u679C: directMessages=%d, groupMessages=%d, \u660E\u7EC6=%s",e.directMessages.length,e.groupMessages.length,JSON.stringify(e.directMessages.map(r=>({id:r.msgId,channel:r.channel,sender:r.senderId})))),{directMessages:e.directMessages,groupMessages:e.groupMessages,fromBuffer:t,systemMessages:[],...this.shouldDeliverPluginCatalog()?{pluginCatalog:this.cachedPluginCatalog}:{}}}shouldDeliverPluginCatalog(){if(!this.cachedPluginCatalog)return!1;const e=this.cachedPluginCatalog.revision;return e===this.pluginCatalogDeliveredRevision&&this.pluginCatalogDrainCompactionSeq===this.pluginCatalogDeliveredCompactionSeq?!1:(this.pluginCatalogDeliveredRevision=e,this.pluginCatalogDeliveredCompactionSeq=this.pluginCatalogDrainCompactionSeq,o.debug("[McpServer] \u4EA4\u4ED8 pluginCatalog: revision=%d, compactionSeq=%d",e,this.pluginCatalogDrainCompactionSeq),!0)}parsePositiveIntegerEnv(e,t){const r=process.env[e];if(!r||!r.trim())return t;const i=Number.parseInt(r,10);return!Number.isFinite(i)||i<=0?(o.warn(`[McpServer] ${e} \u65E0\u6548\uFF0C\u4F7F\u7528\u9ED8\u8BA4\u503C ${t}ms`),t):i}sleep(e){return e<=0?Promise.resolve():new Promise(t=>setTimeout(t,e))}async buildMemoryCleanupNotification(){try{const e=await this.memoryStore.getStats(),t=Object.entries(e.by_type).filter(([,a])=>a.listable&&a.exceeded),r=Object.entries(e.by_type).flatMap(([a,l])=>l.listable?Object.entries(l.by_domain).filter(([,m])=>m.exceeded).map(([m,d])=>({memoryType:a,domain:m,domainStats:d})):[]);if(t.length===0&&r.length===0)return null;const i=t.map(([a,l])=>`${a} \u5F53\u524D ${l.domainCount} \u4E2A URI domain \u7C7B\u578B\uFF0C\u5EFA\u8BAE\u4E0A\u9650 ${l.limit} \u4E2A\uFF0C\u786C\u4E0A\u9650 ${l.hardLimit} \u4E2A`),s=r.map(({memoryType:a,domain:l,domainStats:m})=>`${a}/${l} \u7C7B\u578B\u4E0B\u5F53\u524D ${m.count} \u6761 memory\uFF0C\u5EFA\u8BAE\u4E0A\u9650 ${m.limit} \u6761\uFF0C\u786C\u4E0A\u9650 ${m.hardLimit} \u6761`),n=["\u8BF7\u8C03\u7528 get_memory_stats \u67E5\u770B\u5BB9\u91CF\u8BE6\u60C5","\u8C03\u7528 list_memories \u6309\u7C7B\u578B\u67E5\u770B\u8D85\u9650\u8BB0\u5FC6","\u5220\u9664\u4E0D\u518D\u9700\u8981\u7684 recently_memory","\u66F4\u65B0 agent_memory \u7EED\u671F\uFF08TTL \xD72\uFF09\u6216\u5220\u9664\u8FC7\u671F\u9879"].join("\uFF1B");return{msgId:`memory-cleanup-${Date.now()}`,senderId:"MCP-System",senderName:"\u7CFB\u7EDF",receiverId:this.getCurrentAgentId()||void 0,content:`\u672C\u5730 memory \u5DF2\u8D85\u8FC7\u5EFA\u8BAE\u5BB9\u91CF\uFF0C\u9700\u8981\u6574\u7406\u3002${[...i,...s].join("\uFF1B")}\u3002${n}\u3002`,requireReply:!1,timestamp:new Date().toISOString(),_acodeAutoDelegate:{type:"memory_cleanup",uris:r.map(a=>`${a.memoryType}/${a.domain}`)}}}catch(e){return o.warn("[McpServer] \u6784\u5EFA\u672C\u5730 memory \u6574\u7406\u63D0\u9192\u5931\u8D25: %s",e instanceof Error?e.message:String(e)),null}}async buildMemoryRecurrenceNotification(){try{const e=await this.memoryStore.listExpiredRecentlyMemories();if(e.length===0)return null;const t=this.getCurrentAgentId();if(!t)return null;const r=e.filter(s=>s.memory_status==="recalling"),i=e.filter(s=>!r.includes(s));if(r.length>0){const s=r.slice(0,5).map(n=>n.uri).join(`
10
+ ${r}`:r}async recordMessageTokenUsage(e){try{const t=await this.agentClient.getProfile().catch(()=>null);if(!t?.runtimeSessionId)return;const r=this.contextManager.estimateTokens(e);await this.contextManager.recordUsage(t.runtimeSessionId,{input:0,output:r})}catch{}}async handleHireColleague(e){if(Array.isArray(e.items)){if(e.items.length===0)throw new Error("items must contain at least one hire item");return e.items.forEach((t,r)=>{if(!t.workspacePath||typeof t.workspacePath!="string")throw new Error(`items[${r}].workspacePath is required`)}),await this.agentClient.hireColleague(e)}if(!e.workspacePath||typeof e.workspacePath!="string")throw new Error("workspacePath is required");return await this.agentClient.hireColleague(e)}async handleSendPrivate(e){if(!e.targetId||typeof e.targetId!="string")throw new Error("targetId is required");const t=typeof e.content=="string"?e.content:"",r=Array.isArray(e.attachments)?e.attachments:[];if(!t.trim()&&r.length===0)throw new Error("content \u4E0E attachments \u81F3\u5C11\u63D0\u4F9B\u4E00\u4E2A\u975E\u7A7A\u503C");const i=r.length>0?this.mergeContentWithAttachmentMarkers(t,await this.uploadAttachmentFiles(r)):t;return this.recordMessageTokenUsage(i).catch(s=>o.warn("[McpServer] Failed to record token usage",s)),await this.agentClient.sendDirectMessage(e.targetId,i,e.waitReply,e.replyToCallId,e.timeoutMs)}async handleCreateTaskInstanceComment(e){const t=this.getRequiredString(e,"taskInstanceId"),r=this.getRequiredString(e,"content");return await this.agentClient.createTaskInstanceComment({taskInstanceId:t,content:r})}async prependMemoryNotification(e,t){const r=await t();return r?(e.directMessages.unshift(r),!0):!1}async handlePollMessage(e){if(o.info("[McpServer] handlePollMessage \u88AB\u8C03\u7528"),this.pendingPollMessage)return o.info("[McpServer] poll_message \u5DF2\u6709\u8FDB\u884C\u4E2D\u7684\u8C03\u7528\uFF0C\u7B49\u5F85\u5176\u5B8C\u6210"),E("poll.singleton-join","\u7B2C\u4E8C\u4E2A poll_message \u8C03\u7528\u5230\u8FBE\uFF0C\u5408\u5E76\u5230\u8FDB\u884C\u4E2D\u7684 poll Promise\uFF08\u82E5\u9996\u4E2A\u5FAA\u73AF\u5361\u6B7B\u5219\u4E24\u8005\u4E00\u8D77\u6302\u8D77\uFF09"),await this.pendingPollMessage;const t=Date.now();this.pendingPollMessage=(async()=>await this.doPollMessage(e))();try{const r=await this.pendingPollMessage;return o.info("[McpServer] poll_message Promise resolved\uFF0C\u8017\u65F6 %dms, directMessages=%d, groupMessages=%d",Date.now()-t,Array.isArray(r?.directMessages)?r.directMessages.length:-1,Array.isArray(r?.groupMessages)?r.groupMessages.length:-1),E("poll.resolved",`elapsedMs=${Date.now()-t} dm=${O(r?.directMessages)} gm=${O(r?.groupMessages)}`),r}catch(r){throw o.warn("[McpServer] poll_message Promise rejected\uFF0C\u8017\u65F6 %dms: %s",Date.now()-t,r instanceof Error?r.message:String(r)),E("poll.rejected",`elapsedMs=${Date.now()-t} error=${r instanceof Error?r.message:String(r)}`),r}finally{this.pendingPollMessage=null}}async doPollMessage(e){if(o.info("[McpServer] doPollMessage \u88AB\u8C03\u7528"),E("poll.enter","doPollMessage \u5165\u53E3"),e?.aborted)return o.info("[McpServer] poll_message \u8C03\u7528\u5DF2\u88AB\u5BA2\u6237\u7AEF\u53D6\u6D88\uFF0C\u8DF3\u8FC7\u963B\u585E\u7B49\u5F85"),this.buildPollResult({directMessages:[],groupMessages:[]});const t=await this.buildTodoBlockNotification();if(t)return this.buildPollResult({directMessages:[t],groupMessages:[]});await this.hydrateUnreadMessagesFromServer({blockIfEmpty:!1,includePipelineTasks:!0,pollMessageTimeoutMs:5e3,preemptiveJoinWaitMs:0}),await this.hydrateBrowserListenerEvents(),await this.hydratePluginEvents();const r=await this.buildBackgroundTaskNotification(),i=await this.confirmServerMessages(this.messageBuffer.get());if(i.directMessages.length>0||i.groupMessages.length>0)return e?.aborted?(this.messageBuffer.requeue(i),o.info("[McpServer] poll_message \u5165\u53E3\u68C0\u67E5\u671F\u95F4\u88AB\u5BA2\u6237\u7AEF\u53D6\u6D88\uFF0C\u56DE\u6EDA\u672A\u4EA4\u4ED8\u6D88\u606F"),this.buildPollResult({directMessages:[],groupMessages:[]})):(r&&i.directMessages.unshift(r),this.buildPollResult(i));if(r)return this.buildPollResult({directMessages:[r],groupMessages:[]});const s=await this.checkAllLocalNonUrgentNotifications();if(s.length>0)return this.buildPollResult({directMessages:s,groupMessages:[]});let n=!1,a=0,l=0;for(;;){if(e?.aborted)return o.info("[McpServer] poll_message \u7B49\u5F85\u671F\u95F4\u88AB\u5BA2\u6237\u7AEF\u53D6\u6D88\uFF0C\u9000\u51FA\u963B\u585E\u5FAA\u73AF"),E("poll.loop-abort","\u7B49\u5F85\u671F\u95F4\u88AB\u5BA2\u6237\u7AEF\u53D6\u6D88\uFF0C\u9000\u51FA\u963B\u585E\u5FAA\u73AF"),this.buildPollResult({directMessages:[],groupMessages:[]});if(!n){const p=this.agentClient.getStatusReporter();if(p){const w=p.getCurrentStatus();w.status==="tool_using"&&w.actionDetail!=null&&w.actionDetail.includes("poll_message")||p.reportToolUse("poll_message",{}),n=!0}}const m=await this.confirmServerMessages(await this.messageBuffer.poll(ue));if(l++,E("poll.loop-tick",`\u7B2C ${l} \u62CD: polled dm=${m.directMessages.length} gm=${m.groupMessages.length}`),e?.aborted)return this.messageBuffer.requeue(m),o.info("[McpServer] poll_message \u7B49\u5F85\u671F\u95F4\u88AB\u5BA2\u6237\u7AEF\u53D6\u6D88\uFF0C\u56DE\u6EDA %d \u6761\u672A\u4EA4\u4ED8\u6D88\u606F\u540E\u9000\u51FA\u963B\u585E\u5FAA\u73AF",m.directMessages.length+m.groupMessages.length),this.buildPollResult({directMessages:[],groupMessages:[]});if(m.directMessages.length>0||m.groupMessages.length>0)return this.buildPollResult(m);if(o.debug("[McpServer] poll \u8D85\u65F6\uFF0C\u68C0\u67E5\u6D4F\u89C8\u5668\u76D1\u542C\u5668\u4E8B\u4EF6"),await this.hydrateBrowserListenerEvents()){if(e?.aborted)return o.info("[McpServer] poll_message \u76D1\u542C\u5668\u4E8B\u4EF6\u68C0\u67E5\u671F\u95F4\u88AB\u5BA2\u6237\u7AEF\u53D6\u6D88\uFF0C\u9000\u51FA\u963B\u585E\u5FAA\u73AF"),this.buildPollResult({directMessages:[],groupMessages:[]});const p=await this.confirmServerMessages(this.messageBuffer.get());if(p.directMessages.length>0||p.groupMessages.length>0)return e?.aborted?(this.messageBuffer.requeue(p),o.info("[McpServer] poll_message \u76D1\u542C\u5668\u4E8B\u4EF6\u786E\u8BA4\u671F\u95F4\u88AB\u5BA2\u6237\u7AEF\u53D6\u6D88\uFF0C\u56DE\u6EDA %d \u6761\u672A\u4EA4\u4ED8\u6D88\u606F",p.directMessages.length+p.groupMessages.length),this.buildPollResult({directMessages:[],groupMessages:[]})):(o.info("[McpServer] \u76D1\u542C\u5668\u4E8B\u4EF6\u5DF2\u6CE8\u5165\uFF0Cpoll_message \u8FD4\u56DE %d \u6761\u79C1\u4FE1",p.directMessages.length),this.buildPollResult(p))}if(o.debug("[McpServer] poll \u8D85\u65F6\uFF0C\u68C0\u67E5\u63D2\u4EF6\u4E8B\u4EF6"),await this.hydratePluginEvents()){if(e?.aborted)return o.info("[McpServer] poll_message \u63D2\u4EF6\u4E8B\u4EF6\u68C0\u67E5\u671F\u95F4\u88AB\u5BA2\u6237\u7AEF\u53D6\u6D88\uFF0C\u9000\u51FA\u963B\u585E\u5FAA\u73AF"),this.buildPollResult({directMessages:[],groupMessages:[]});const p=await this.confirmServerMessages(this.messageBuffer.get());if(p.directMessages.length>0||p.groupMessages.length>0)return e?.aborted?(this.messageBuffer.requeue(p),o.info("[McpServer] poll_message \u63D2\u4EF6\u4E8B\u4EF6\u786E\u8BA4\u671F\u95F4\u88AB\u5BA2\u6237\u7AEF\u53D6\u6D88\uFF0C\u56DE\u6EDA %d \u6761\u672A\u4EA4\u4ED8\u6D88\u606F",p.directMessages.length+p.groupMessages.length),this.buildPollResult({directMessages:[],groupMessages:[]})):(o.info("[McpServer] \u63D2\u4EF6\u4E8B\u4EF6\u5DF2\u6CE8\u5165\uFF0Cpoll_message \u8FD4\u56DE %d \u6761\u79C1\u4FE1",p.directMessages.length),this.buildPollResult(p))}a++;let u=!1;if(this.urgentMeetingHydrateRequested&&(this.urgentMeetingHydrateRequested=!1,a=j,u=!0),a<j)continue;a=0;const _=await this.buildTodoBlockNotification();if(_)return this.buildPollResult({directMessages:[_],groupMessages:[]});let b=!1;const h=u?T.MEETING_HYDRATE_RETRY_COUNT:1;for(let p=1;p<=h;p++){o.info("[McpServer] %s hydrate poll_message\uFF0C\u7B2C %d/%d \u6B21",u?"\u4F1A\u8BAE\u9080\u8BF7\u5F3A\u5236":"\u666E\u901A",p,h);const w=this.messageBuffer.size();if(u&&w>0){o.info("[McpServer] \u4F1A\u8BAE\u9080\u8BF7\u5F3A\u5236 hydrate \u524D\u53D1\u73B0\u672C\u5730\u7F13\u51B2\u5DF2\u6709 %d \u6761\u6D88\u606F\uFF0C\u8DF3\u8FC7 hydrate \u76F4\u63A5\u4EA4\u4ED8",w);break}const v={blockIfEmpty:!1,includePipelineTasks:!0,pollMessageTimeoutMs:u?T.MEETING_HYDRATE_POLL_TIMEOUT_MS:void 0,skipGroupMessages:u,preemptiveJoinWaitMs:u?T.MEETING_PREEMPTIVE_JOIN_WAIT_MS:0,propagatePollTimeout:u},k=Date.now(),f=await this.hydrateUnreadMessagesFromServer(v);if(u&&E("poll.forced-hydrate-outcome",`\u7B2C ${p}/${h} \u6B21\u5F3A\u5236 hydrate \u5B8C\u6210\uFF08\u8017\u65F6 ${Date.now()-k}ms\uFF09: timedOut=${f.timedOut} failed=${f.failed} \u7F13\u51B2\u533A=${this.messageBuffer.size()} \u6761`),f.timedOut){o.warn("[McpServer] \u4F1A\u8BAE\u9080\u8BF7\u5F3A\u5236 hydrate \u7B2C %d/%d \u6B21\u5BA2\u6237\u7AEF\u8D85\u65F6\uFF08\u670D\u52A1\u7AEF\u53EF\u80FD\u4ECD\u5728\u6267\u884C\u4E0A\u4E00\u8BF7\u6C42\uFF09\uFF0C\u505C\u6B62\u7ACB\u5373\u91CD\u8BD5",p,h),b=!0;break}const C=this.messageBuffer.size();if(o.info("[McpServer] hydrate poll_message \u5B8C\u6210\uFF0C\u7B2C %d/%d \u6B21\uFF0C\u7F13\u51B2\u533A\u6D88\u606F\u6570=%d",p,h,C),C>0||!u)break;p<h&&await new Promise(R=>setTimeout(R,T.MEETING_HYDRATE_RETRY_DELAY_MS))}b&&(E("poll.forced-hydrate-rearm",`\u5F3A\u5236 hydrate \u8D85\u65F6\uFF0C${this.meetingHydrateTimeoutRearmDelayMs}ms \u540E\u91CD\u65B0\u7F6E\u4F4D\u5524\u9192\u6807\u8BB0`),setTimeout(()=>{o.info("[McpServer] \u4F1A\u8BAE\u5F3A\u5236 hydrate \u8D85\u65F6\u81EA\u6108\uFF1A\u91CD\u65B0\u7F6E\u4F4D\u5524\u9192\u6807\u8BB0\u89E6\u53D1\u4E0B\u4E00\u8F6E\u5F3A\u5236 hydrate"),this.urgentMeetingHydrateRequested=!0,this.messageBuffer.wakeUpWaiters()},this.meetingHydrateTimeoutRearmDelayMs).unref());const M=await this.buildBackgroundTaskNotification();if(e?.aborted)return o.info("[McpServer] poll_message hydrate \u540E\u68C0\u67E5\u671F\u95F4\u88AB\u5BA2\u6237\u7AEF\u53D6\u6D88\uFF0C\u9000\u51FA\u963B\u585E\u5FAA\u73AF"),this.buildPollResult({directMessages:[],groupMessages:[]});const c=await this.confirmServerMessages(this.messageBuffer.get());if(c.directMessages.length>0||c.groupMessages.length>0)return e?.aborted?(this.messageBuffer.requeue(c),o.info("[McpServer] poll_message hydrate \u786E\u8BA4\u671F\u95F4\u88AB\u5BA2\u6237\u7AEF\u53D6\u6D88\uFF0C\u56DE\u6EDA %d \u6761\u672A\u4EA4\u4ED8\u6D88\u606F",c.directMessages.length+c.groupMessages.length),this.buildPollResult({directMessages:[],groupMessages:[]})):(M&&c.directMessages.unshift(M),this.buildPollResult(c));if(u&&!M&&!b&&(o.info("[McpServer] \u4F1A\u8BAE\u9080\u8BF7\u5524\u9192\u540E\u7684\u5F3A\u5236 hydrate \u672A\u53D6\u5230\u53EF\u6295\u9012\u6D88\u606F\uFF08\u670D\u52A1\u7AEF\u672A\u62A2\u5360\u6216\u65E0\u65B0\u4F1A\u8BAE\u5185\u5BB9\uFF09\uFF0C\u7EE7\u7EED\u7B49\u5F85"),E("poll.forced-hydrate-empty","\u4F1A\u8BAE\u9080\u8BF7\u5524\u9192\u540E\u7684\u5F3A\u5236 hydrate \u672A\u53D6\u5230\u4EFB\u4F55\u53EF\u6295\u9012\u6D88\u606F\uFF08\u670D\u52A1\u7AEF\u672A\u62A2\u5360/\u65E0\u65B0\u5185\u5BB9/\u6D88\u606F\u88AB\u53BB\u91CD\u62E6\u622A\uFF09\uFF0C\u7EE7\u7EED\u7B49\u5F85"),a=j-1),M)return this.buildPollResult({directMessages:[M],groupMessages:[]});const y=await this.checkAllLocalNonUrgentNotifications(!1);if(y.length>0)return this.buildPollResult({directMessages:y,groupMessages:[]})}}async checkAllLocalNonUrgentNotifications(e=!0){const t=[],r=await this.buildMemoryRecurrenceNotification();if(r&&t.push(r),e){const s=await this.buildMemoryFileChangeNotification();s&&t.push(s)}const i=await this.buildMemoryCleanupNotification();return i&&t.push(i),t}buildPollResult(e,t=!0){o.info("[McpServer][DEBUG-poll] \u8FD4\u56DE poll \u7ED3\u679C: directMessages=%d, groupMessages=%d, \u660E\u7EC6=%s",e.directMessages.length,e.groupMessages.length,JSON.stringify(e.directMessages.map(i=>({id:i.msgId,channel:i.channel,sender:i.senderId}))));const r=this.shouldDeliverPluginCatalog();return{directMessages:e.directMessages,groupMessages:e.groupMessages,fromBuffer:t,systemMessages:[],...r?{pluginCatalog:r}:{}}}shouldDeliverPluginCatalog(){if(!this.cachedPluginCatalog||this.cachedPluginCatalog.plugins.length===0)return null;const e=this.pluginCatalogDrainCompactionSeq;e!==this.pluginCatalogLastSeenCompactionSeq&&(this.deliveredPluginNames.clear(),this.pluginCatalogLastSeenCompactionSeq=e);const t=[];for(const r of this.cachedPluginCatalog.plugins)this.deliveredPluginNames.has(r.plugin)||(this.deliveredPluginNames.add(r.plugin),t.push(r));return t.length===0?null:(o.debug("[McpServer] \u4EA4\u4ED8 pluginCatalog: plugins=[%s], compactionSeq=%d",t.map(r=>r.plugin).join(", "),e),{revision:this.cachedPluginCatalog.revision,plugins:t})}parsePositiveIntegerEnv(e,t){const r=process.env[e];if(!r||!r.trim())return t;const i=Number.parseInt(r,10);return!Number.isFinite(i)||i<=0?(o.warn(`[McpServer] ${e} \u65E0\u6548\uFF0C\u4F7F\u7528\u9ED8\u8BA4\u503C ${t}ms`),t):i}sleep(e){return e<=0?Promise.resolve():new Promise(t=>setTimeout(t,e))}async buildMemoryCleanupNotification(){try{const e=await this.memoryStore.getStats(),t=Object.entries(e.by_type).filter(([,a])=>a.listable&&a.exceeded),r=Object.entries(e.by_type).flatMap(([a,l])=>l.listable?Object.entries(l.by_domain).filter(([,m])=>m.exceeded).map(([m,d])=>({memoryType:a,domain:m,domainStats:d})):[]);if(t.length===0&&r.length===0)return null;const i=t.map(([a,l])=>`${a} \u5F53\u524D ${l.domainCount} \u4E2A URI domain \u7C7B\u578B\uFF0C\u5EFA\u8BAE\u4E0A\u9650 ${l.limit} \u4E2A\uFF0C\u786C\u4E0A\u9650 ${l.hardLimit} \u4E2A`),s=r.map(({memoryType:a,domain:l,domainStats:m})=>`${a}/${l} \u7C7B\u578B\u4E0B\u5F53\u524D ${m.count} \u6761 memory\uFF0C\u5EFA\u8BAE\u4E0A\u9650 ${m.limit} \u6761\uFF0C\u786C\u4E0A\u9650 ${m.hardLimit} \u6761`),n=["\u8BF7\u8C03\u7528 get_memory_stats \u67E5\u770B\u5BB9\u91CF\u8BE6\u60C5","\u8C03\u7528 list_memories \u6309\u7C7B\u578B\u67E5\u770B\u8D85\u9650\u8BB0\u5FC6","\u5220\u9664\u4E0D\u518D\u9700\u8981\u7684 recently_memory","\u66F4\u65B0 agent_memory \u7EED\u671F\uFF08TTL \xD72\uFF09\u6216\u5220\u9664\u8FC7\u671F\u9879"].join("\uFF1B");return{msgId:`memory-cleanup-${Date.now()}`,senderId:"MCP-System",senderName:"\u7CFB\u7EDF",receiverId:this.getCurrentAgentId()||void 0,content:`\u672C\u5730 memory \u5DF2\u8D85\u8FC7\u5EFA\u8BAE\u5BB9\u91CF\uFF0C\u9700\u8981\u6574\u7406\u3002${[...i,...s].join("\uFF1B")}\u3002${n}\u3002`,requireReply:!1,timestamp:new Date().toISOString(),_acodeAutoDelegate:{type:"memory_cleanup",uris:r.map(a=>`${a.memoryType}/${a.domain}`)}}}catch(e){return o.warn("[McpServer] \u6784\u5EFA\u672C\u5730 memory \u6574\u7406\u63D0\u9192\u5931\u8D25: %s",e instanceof Error?e.message:String(e)),null}}async buildMemoryRecurrenceNotification(){try{const e=await this.memoryStore.listExpiredRecentlyMemories();if(e.length===0)return null;const t=this.getCurrentAgentId();if(!t)return null;const r=e.filter(s=>s.memory_status==="recalling"),i=e.filter(s=>!r.includes(s));if(r.length>0){const s=r.slice(0,5).map(n=>n.uri).join(`
11
11
  `);return{msgId:`memory-recurrence-pending-${Date.now()}`,senderId:"MCP-System",senderName:"\u7CFB\u7EDF",receiverId:t,content:`\u5B58\u5728\u5F85\u758F\u7406\u7684\u5373\u5C06\u9057\u5FD8\u8BB0\u5FC6\uFF08\u5171 ${r.length} \u6761\uFF09\uFF0C\u8BF7\u901A\u8FC7 memory_recurrence \u83B7\u53D6\u8FDB\u884C\u6574\u7406\u3002
12
12
 
13
13
  \u5F85\u758F\u7406\u8BB0\u5FC6\uFF1A
@@ -17,12 +17,12 @@ ${s}${r.length>5?`
17
17
 
18
18
  \u5373\u5C06\u9057\u5FD8\u7684\u8BB0\u5FC6\uFF1A
19
19
  ${s}${i.length>5?`
20
- ...\u53CA\u5176\u4ED6 ${i.length-5} \u6761`:""}`,requireReply:!1,timestamp:new Date().toISOString(),_acodeAutoDelegate:{type:"memory_expiration",uris:i.map(n=>n.uri)}}}return null}catch(e){return o.warn("[McpServer] \u6784\u5EFA\u8FD1\u671F\u8BB0\u5FC6\u8FC7\u671F\u56DE\u5FC6\u901A\u77E5\u5931\u8D25: %s",e instanceof Error?e.message:String(e)),null}}async buildMemoryFileChangeNotification(){if(o.info(`[McpServer] buildMemoryFileChangeNotification \u88AB\u8C03\u7528: hasRoleName=${this.hasRoleName}, agentId=${this.getCurrentAgentId()??"(\u7A7A)"}`),!this.hasRoleName)return o.info("[McpServer] \u6587\u4EF6\u53D8\u66F4\u68C0\u6D4B\u8DF3\u8FC7: hasRoleName=false"),null;try{const e=this.getCurrentAgentId();if(!e)return o.info("[McpServer] \u6587\u4EF6\u53D8\u66F4\u68C0\u6D4B\u8DF3\u8FC7: agentId \u4E3A\u7A7A"),null;const t=await this.memoryStore.listByType("project_memory"),r=t.filter(c=>c.memory_status==="updating"&&c.updating_agent_id===e);if(r.length>0){this.startLeaseRenewal();const c=this.filterFileChangesByRenotifyCooldown(await this.checkMemoriesFileChanges(r));if(c.length>0){for(const T of c){const A=r.find(N=>N.id===T.memoryId);A&&await this.memoryStore.updateMemory({uri:A.uri,memory_type:"project_memory",memory_status:"updating",updating_agent_id:e,file_md5_map:A.file_md5_map,last_check_time:A.last_check_time,bound_files:A.bound_files})}const f=Math.min(c.length,5),C=c.slice(0,5).map(T=>`- ${T.memoryUri} (\u6587\u4EF6: ${T.changedFiles.join(", ")})`).join(`
20
+ ...\u53CA\u5176\u4ED6 ${i.length-5} \u6761`:""}`,requireReply:!1,timestamp:new Date().toISOString(),_acodeAutoDelegate:{type:"memory_expiration",uris:i.map(n=>n.uri)}}}return null}catch(e){return o.warn("[McpServer] \u6784\u5EFA\u8FD1\u671F\u8BB0\u5FC6\u8FC7\u671F\u56DE\u5FC6\u901A\u77E5\u5931\u8D25: %s",e instanceof Error?e.message:String(e)),null}}async buildMemoryFileChangeNotification(){if(o.info(`[McpServer] buildMemoryFileChangeNotification \u88AB\u8C03\u7528: hasRoleName=${this.hasRoleName}, agentId=${this.getCurrentAgentId()??"(\u7A7A)"}`),!this.hasRoleName)return o.info("[McpServer] \u6587\u4EF6\u53D8\u66F4\u68C0\u6D4B\u8DF3\u8FC7: hasRoleName=false"),null;try{const e=this.getCurrentAgentId();if(!e)return o.info("[McpServer] \u6587\u4EF6\u53D8\u66F4\u68C0\u6D4B\u8DF3\u8FC7: agentId \u4E3A\u7A7A"),null;const t=await this.memoryStore.listByType("project_memory"),r=t.filter(c=>c.memory_status==="updating"&&c.updating_agent_id===e);if(r.length>0){this.startLeaseRenewal();const c=this.filterFileChangesByRenotifyCooldown(await this.checkMemoriesFileChanges(r));if(c.length>0){for(const R of c){const A=r.find(N=>N.id===R.memoryId);A&&await this.memoryStore.updateMemory({uri:A.uri,memory_type:"project_memory",memory_status:"updating",updating_agent_id:e,file_md5_map:A.file_md5_map,last_check_time:A.last_check_time,bound_files:A.bound_files})}const f=Math.min(c.length,5),C=c.slice(0,5).map(R=>`- ${R.memoryUri} (\u6587\u4EF6: ${R.changedFiles.join(", ")})`).join(`
21
21
  `);return{msgId:`memory-file-change-${Date.now()}`,senderId:"MCP-System",senderName:"\u7CFB\u7EDF",receiverId:e,content:`\u68C0\u6D4B\u5230\u4EE5\u4E0B ${f} \u4E2A\u5904\u4E8E\u66F4\u65B0\u4E2D\u7684 Memory \u7ED1\u5B9A\u7684\u6587\u4EF6\u518D\u6B21\u53D8\u66F4\uFF0C\u5DF2\u66F4\u65B0 MD5 \u8BB0\u5F55\uFF1A
22
22
 
23
23
  ${C}
24
24
 
25
- \u8BF7\u8C03\u7528 read_memory \u67E5\u770B\u6700\u65B0\u5185\u5BB9\u5E76\u8C03\u7528 update_memory \u66F4\u65B0\u3002`,requireReply:!1,timestamp:new Date().toISOString(),_acodeAutoDelegate:{type:"memory_file_change",uris:c.slice(0,5).map(T=>T.memoryUri),fileChanges:c.slice(0,5).map(T=>{const A=r.find(N=>N.id===T.memoryId);return{uri:T.memoryUri,boundFiles:A?.bound_files??[],fileStatuses:T.fileStatuses,changedFiles:T.changedFiles}})}}}const y=r,p=new Map;for(const f of y.slice(0,5))p.set(f.uri,await this.computeBoundFileStatuses(f));const w=y.filter(f=>{const C=p.get(f.uri);return!C||C.length===0?!1:C.some(T=>T.status==="content_changed"||T.status==="not_found")}),v=y.filter(f=>!w.includes(f));if(v.length>0){o.info(`[McpServer] \u6587\u4EF6\u53D8\u66F4\u68C0\u6D4B Step1: ${v.length} \u4E2A updating memory \u7ED1\u5B9A\u6587\u4EF6\u65E0\u771F\u5B9E\u53D8\u66F4\uFF0C\u81EA\u52A8\u91CA\u653E: ${v.map(f=>f.uri).join(", ")}`);for(const f of v)try{await this.memoryStore.releaseMemoryClaim(f.uri),this.activeLeaseUris.delete(f.uri),await this.memoryStore.updateMemory({uri:f.uri,memory_type:"project_memory"})}catch(C){o.info(`[McpServer] \u81EA\u52A8\u91CA\u653E stale updating memory \u5931\u8D25: ${f.uri}`,C)}this.activeLeaseUris.size===0&&this.stopLeaseRenewal()}if(w.length===0)return o.info("[McpServer] \u6587\u4EF6\u53D8\u66F4\u68C0\u6D4B Step1: \u6240\u6709 updating memory \u7ED1\u5B9A\u6587\u4EF6\u5747\u65E0\u771F\u5B9E\u53D8\u66F4\uFF0C\u5DF2\u81EA\u52A8\u91CA\u653E\uFF0C\u8DF3\u8FC7\u59D4\u6258"),null;const k=w.slice(0,5).map(f=>`- ${f.uri} (\u6587\u4EF6: ${f.bound_files?.join(", ")||"\u672A\u77E5"})`).join(`
25
+ \u8BF7\u8C03\u7528 read_memory \u67E5\u770B\u6700\u65B0\u5185\u5BB9\u5E76\u8C03\u7528 update_memory \u66F4\u65B0\u3002`,requireReply:!1,timestamp:new Date().toISOString(),_acodeAutoDelegate:{type:"memory_file_change",uris:c.slice(0,5).map(R=>R.memoryUri),fileChanges:c.slice(0,5).map(R=>{const A=r.find(N=>N.id===R.memoryId);return{uri:R.memoryUri,boundFiles:A?.bound_files??[],fileStatuses:R.fileStatuses,changedFiles:R.changedFiles}})}}}const y=r,p=new Map;for(const f of y.slice(0,5))p.set(f.uri,await this.computeBoundFileStatuses(f));const w=y.filter(f=>{const C=p.get(f.uri);return!C||C.length===0?!1:C.some(R=>R.status==="content_changed"||R.status==="not_found")}),v=y.filter(f=>!w.includes(f));if(v.length>0){o.info(`[McpServer] \u6587\u4EF6\u53D8\u66F4\u68C0\u6D4B Step1: ${v.length} \u4E2A updating memory \u7ED1\u5B9A\u6587\u4EF6\u65E0\u771F\u5B9E\u53D8\u66F4\uFF0C\u81EA\u52A8\u91CA\u653E: ${v.map(f=>f.uri).join(", ")}`);for(const f of v)try{await this.memoryStore.releaseMemoryClaim(f.uri),this.activeLeaseUris.delete(f.uri),await this.memoryStore.updateMemory({uri:f.uri,memory_type:"project_memory"})}catch(C){o.info(`[McpServer] \u81EA\u52A8\u91CA\u653E stale updating memory \u5931\u8D25: ${f.uri}`,C)}this.activeLeaseUris.size===0&&this.stopLeaseRenewal()}if(w.length===0)return o.info("[McpServer] \u6587\u4EF6\u53D8\u66F4\u68C0\u6D4B Step1: \u6240\u6709 updating memory \u7ED1\u5B9A\u6587\u4EF6\u5747\u65E0\u771F\u5B9E\u53D8\u66F4\uFF0C\u5DF2\u81EA\u52A8\u91CA\u653E\uFF0C\u8DF3\u8FC7\u59D4\u6258"),null;const k=w.slice(0,5).map(f=>`- ${f.uri} (\u6587\u4EF6: ${f.bound_files?.join(", ")||"\u672A\u77E5"})`).join(`
26
26
  `);return o.info(`[McpServer] \u6587\u4EF6\u53D8\u66F4\u68C0\u6D4B Step1: ${w.length}/${r.length} \u4E2A updating memory \u6709\u771F\u5B9E\u6587\u4EF6\u53D8\u66F4\uFF0C\u89E6\u53D1\u59D4\u6258`),{msgId:`memory-update-pending-${Date.now()}`,senderId:"MCP-System",senderName:"\u7CFB\u7EDF",receiverId:e,content:`\u60A8\u6709\u4EE5\u4E0B Memory \u6B63\u5904\u4E8E\u66F4\u65B0\u4E2D\u72B6\u6001\u4F46\u5C1A\u672A\u5B8C\u6210\u66F4\u65B0\uFF1A
27
27
 
28
28
  ${k}
@@ -32,12 +32,12 @@ ${k}
32
32
 
33
33
  ${c}
34
34
 
35
- \u8BF7\u8C03\u7528 read_memory \u67E5\u770B\u5185\u5BB9\u5E76\u8C03\u7528 update_memory \u66F4\u65B0\u3002`,requireReply:!1,timestamp:new Date().toISOString(),_acodeAutoDelegate:{type:"memory_file_change",uris:d.map(y=>y.memoryUri),fileChanges:d.map(y=>{const p=n.find(w=>w.id===y.memoryId);return{uri:y.memoryUri,boundFiles:p?.bound_files??[],fileStatuses:y.fileStatuses,changedFiles:y.changedFiles}})}}}const u=t.filter(c=>c.bound_files&&c.bound_files.length>0&&(c.memory_status==="normal"||!c.memory_status)&&!this.isClaimCached(c.uri)),_=t.filter(c=>c.bound_files&&c.bound_files.length>0);o.info(`[McpServer] \u6587\u4EF6\u53D8\u66F4\u68C0\u6D4B Step3: project_memory \u603B\u6570=${t.length}, \u6709\u7ED1\u5B9A\u6587\u4EF6=${_.length}, \u5F85\u68C0\u6D4B(\u8FC7\u6EE4updating/claimed\u540E)=${u.length}\u3002\u88AB\u8FC7\u6EE4\u539F\u56E0: ${_.length-u.length} \u9879(memory_status=updating \u6216 isClaimCached)`);const b=new Map;for(const c of u)b.set(c.id,JSON.stringify(c.file_md5_map??{}));const h=this.filterFileChangesByRenotifyCooldown(await this.checkMemoriesFileChanges(u)),M=u.filter(c=>{if(h.some(w=>w.memoryId===c.id))return!1;const y=b.get(c.id),p=JSON.stringify(c.file_md5_map??{});return y!==p&&c.file_md5_map&&Object.keys(c.file_md5_map).length>0});if(M.length>0){o.info(`[McpServer] \u6587\u4EF6\u53D8\u66F4\u68C0\u6D4B Step3: \u56DE\u5199 ${M.length} \u4E2A memory \u7684\u4FEE\u6B63 MD5 map \u5230\u670D\u52A1\u7AEF\uFF08\u65E0\u57FA\u7EBF/\u952E\u7F3A\u5931\u4FEE\u590D\uFF09`);for(const c of M)try{await this.memoryStore.updateMemory({uri:c.uri,memory_type:"project_memory",file_md5_map:c.file_md5_map,last_check_time:c.last_check_time})}catch(y){o.info(`[McpServer] \u56DE\u5199\u57FA\u7EBF MD5 \u5931\u8D25: ${c.uri}`,y)}}if(o.info(`[McpServer] \u6587\u4EF6\u53D8\u66F4\u68C0\u6D4B Step3: \u68C0\u6D4B\u5230\u53D8\u66F4=${h.length}`+(h.length>0?` \u53D8\u66F4\u9879: ${h.map(c=>`${c.memoryUri}(${c.changedFiles.join(",")})`).join("; ")}`:"")),h.length>0){const c=h.slice(0,5),y=c.map(v=>v.memoryUri);let p=!1,w=new Set;try{const v=await this.memoryStore.claimMemoryUpdate(y,R.LEASE_DURATION_MINUTES,"project_memory");w=new Set(v.claimed_uris??[]),p=!0}catch(v){o.info("[McpServer] Server claim API \u4E0D\u53EF\u7528\uFF0C\u964D\u7EA7\u5230\u672C\u5730\u76F4\u63A5\u6807\u8BB0:",v),w=new Set(y)}if(w.size>0){const v=c.filter(f=>w.has(f.memoryUri));for(const f of v){const C=t.find(T=>T.id===f.memoryId);C&&(await this.memoryStore.updateMemory({uri:C.uri,memory_type:"project_memory",memory_status:"updating",updating_agent_id:e,file_md5_map:C.file_md5_map,last_check_time:C.last_check_time,bound_files:C.bound_files}),this.activeLeaseUris.add(C.uri))}p&&w.size>0&&this.startLeaseRenewal();const k=v.map(f=>`- ${f.memoryUri} (\u6587\u4EF6: ${f.changedFiles.join(", ")})`).join(`
35
+ \u8BF7\u8C03\u7528 read_memory \u67E5\u770B\u5185\u5BB9\u5E76\u8C03\u7528 update_memory \u66F4\u65B0\u3002`,requireReply:!1,timestamp:new Date().toISOString(),_acodeAutoDelegate:{type:"memory_file_change",uris:d.map(y=>y.memoryUri),fileChanges:d.map(y=>{const p=n.find(w=>w.id===y.memoryId);return{uri:y.memoryUri,boundFiles:p?.bound_files??[],fileStatuses:y.fileStatuses,changedFiles:y.changedFiles}})}}}const u=t.filter(c=>c.bound_files&&c.bound_files.length>0&&(c.memory_status==="normal"||!c.memory_status)&&!this.isClaimCached(c.uri)),_=t.filter(c=>c.bound_files&&c.bound_files.length>0);o.info(`[McpServer] \u6587\u4EF6\u53D8\u66F4\u68C0\u6D4B Step3: project_memory \u603B\u6570=${t.length}, \u6709\u7ED1\u5B9A\u6587\u4EF6=${_.length}, \u5F85\u68C0\u6D4B(\u8FC7\u6EE4updating/claimed\u540E)=${u.length}\u3002\u88AB\u8FC7\u6EE4\u539F\u56E0: ${_.length-u.length} \u9879(memory_status=updating \u6216 isClaimCached)`);const b=new Map;for(const c of u)b.set(c.id,JSON.stringify(c.file_md5_map??{}));const h=this.filterFileChangesByRenotifyCooldown(await this.checkMemoriesFileChanges(u)),M=u.filter(c=>{if(h.some(w=>w.memoryId===c.id))return!1;const y=b.get(c.id),p=JSON.stringify(c.file_md5_map??{});return y!==p&&c.file_md5_map&&Object.keys(c.file_md5_map).length>0});if(M.length>0){o.info(`[McpServer] \u6587\u4EF6\u53D8\u66F4\u68C0\u6D4B Step3: \u56DE\u5199 ${M.length} \u4E2A memory \u7684\u4FEE\u6B63 MD5 map \u5230\u670D\u52A1\u7AEF\uFF08\u65E0\u57FA\u7EBF/\u952E\u7F3A\u5931\u4FEE\u590D\uFF09`);for(const c of M)try{await this.memoryStore.updateMemory({uri:c.uri,memory_type:"project_memory",file_md5_map:c.file_md5_map,last_check_time:c.last_check_time})}catch(y){o.info(`[McpServer] \u56DE\u5199\u57FA\u7EBF MD5 \u5931\u8D25: ${c.uri}`,y)}}if(o.info(`[McpServer] \u6587\u4EF6\u53D8\u66F4\u68C0\u6D4B Step3: \u68C0\u6D4B\u5230\u53D8\u66F4=${h.length}`+(h.length>0?` \u53D8\u66F4\u9879: ${h.map(c=>`${c.memoryUri}(${c.changedFiles.join(",")})`).join("; ")}`:"")),h.length>0){const c=h.slice(0,5),y=c.map(v=>v.memoryUri);let p=!1,w=new Set;try{const v=await this.memoryStore.claimMemoryUpdate(y,T.LEASE_DURATION_MINUTES,"project_memory");w=new Set(v.claimed_uris??[]),p=!0}catch(v){o.info("[McpServer] Server claim API \u4E0D\u53EF\u7528\uFF0C\u964D\u7EA7\u5230\u672C\u5730\u76F4\u63A5\u6807\u8BB0:",v),w=new Set(y)}if(w.size>0){const v=c.filter(f=>w.has(f.memoryUri));for(const f of v){const C=t.find(R=>R.id===f.memoryId);C&&(await this.memoryStore.updateMemory({uri:C.uri,memory_type:"project_memory",memory_status:"updating",updating_agent_id:e,file_md5_map:C.file_md5_map,last_check_time:C.last_check_time,bound_files:C.bound_files}),this.activeLeaseUris.add(C.uri))}p&&w.size>0&&this.startLeaseRenewal();const k=v.map(f=>`- ${f.memoryUri} (\u6587\u4EF6: ${f.changedFiles.join(", ")})`).join(`
36
36
  `);return{msgId:`memory-file-change-${Date.now()}`,senderId:"MCP-System",senderName:"\u7CFB\u7EDF",receiverId:e,content:`\u68C0\u6D4B\u5230\u4EE5\u4E0B ${v.length} \u4E2A\u6C38\u4E45\u8BB0\u5FC6\u7ED1\u5B9A\u7684\u6587\u4EF6\u5DF2\u53D8\u66F4\uFF0C\u5DF2\u4E3A\u60A8\u6807\u8BB0\u4E3A\u66F4\u65B0\u4E2D\uFF1A
37
37
 
38
38
  ${k}
39
39
 
40
- \u8BF7\u8C03\u7528 read_memory \u67E5\u770B\u5185\u5BB9\u5E76\u8C03\u7528 update_memory \u66F4\u65B0\u3002\u66F4\u65B0\u5B8C\u6210\u540E\u72B6\u6001\u5C06\u81EA\u52A8\u6062\u590D\u4E3A\u6B63\u5E38\u3002`,requireReply:!1,timestamp:new Date().toISOString(),_acodeAutoDelegate:{type:"memory_file_change",uris:v.map(f=>f.memoryUri),fileChanges:v.map(f=>{const C=t.find(T=>T.id===f.memoryId);return{uri:f.memoryUri,boundFiles:C?.bound_files??[],fileStatuses:f.fileStatuses,changedFiles:f.changedFiles}})}}}}return o.info("[McpServer] \u6587\u4EF6\u53D8\u66F4\u68C0\u6D4B\u5B8C\u6210: \u65E0\u53D8\u66F4\u901A\u77E5\u4EA7\u751F"),null}catch(e){return o.warn("[McpServer] \u6784\u5EFA Memory \u6587\u4EF6\u53D8\u66F4\u68C0\u6D4B\u901A\u77E5\u5931\u8D25: %s",e instanceof Error?e.message:String(e)),null}}isClaimCached(e){return this.activeLeaseUris.has(e)}async computeBoundFileStatuses(e){const t=[];if(!e.bound_files||e.bound_files.length===0)return t;const r=e.file_md5_map||{},i=process.env.AWS_WORKSPACE_PATH||process.cwd();for(const s of e.bound_files)try{const n=await this.calculateFileMd5(s);if(n===null){const l=S.resolve(i,s);await this.verifyFileNotExist(l)&&r[s]?t.push({path:s,status:"not_found",serverMd5:r[s]}):t.push({path:s,status:"no_change"});continue}const a=r[s];a?a!==n?t.push({path:s,status:"content_changed",localMd5:n,serverMd5:a}):t.push({path:s,status:"no_change"}):t.push({path:s,status:"no_change"})}catch{t.push({path:s,status:"no_change"})}return t}fileChangeFingerprint(e){const t=e.fileStatuses.filter(r=>r.status!=="no_change").map(r=>`${r.path}:${r.status}:${r.localMd5??""}`).sort();return`${e.memoryId}|${t.join("|")}`}filterFileChangesByRenotifyCooldown(e){if(e.length===0)return e;const t=Date.now(),r=[];let i=0;for(const s of e){const n=this.fileChangeFingerprint(s),a=this.fileChangeNotifyHistory.get(n);if(a!==void 0&&t-a<z){i++;continue}this.fileChangeNotifyHistory.set(n,t),r.push(s)}if(i>0&&o.info("[McpServer] \u6587\u4EF6\u53D8\u66F4\u63D0\u9192\u51B7\u5374\u4E2D\uFF0C\u672C\u8F6E\u6291\u5236 %d \u6761\u91CD\u590D\u901A\u77E5\uFF08cooldown=%dms\uFF09",i,z),this.fileChangeNotifyHistory.size>G){const s=this.fileChangeNotifyHistory.size-G;let n=0;for(const a of this.fileChangeNotifyHistory.keys()){if(n>=s)break;this.fileChangeNotifyHistory.delete(a),n++}}return r}async checkMemoriesFileChanges(e){const t=[];for(const r of e)if(!(!r.bound_files||r.bound_files.length===0))try{const i=[],s=[],n={},a=r.file_md5_map||{},l=process.env.AWS_WORKSPACE_PATH||process.cwd(),m=Object.keys(a).length===0;let d=!1;for(const g of r.bound_files)try{const u=await this.calculateFileMd5(g);if(u===null){const b=S.resolve(l,g);o.info(`[McpServer] MD5 \u8BA1\u7B97\u8FD4\u56DE null: ${g} -> ${b} (workspace=${l})`);const h=a[g];h?await this.verifyFileNotExist(b)?(s.push({path:g,status:"not_found",serverMd5:h}),i.push(`${g}\uFF08\u6587\u4EF6\u627E\u4E0D\u5230 Server: ${h}\uFF09`),r.bound_files&&(r.bound_files=r.bound_files.filter(c=>c!==g))):(o.info(`[McpServer] \u6587\u4EF6\u5B58\u5728\u4F46 MD5 \u8BA1\u7B97\u5931\u8D25\uFF08\u77AC\u6001\u9519\u8BEF\uFF09\uFF0C\u8DF3\u8FC7: ${g}`),s.push({path:g,status:"no_change"})):s.push({path:g,status:"no_change"});continue}n[g]=u;const _=a[g];_?_!==u?(o.info(`[McpServer] \u6587\u4EF6\u53D8\u66F4: ${g} old=${_} new=${u} (workspace=${l})`),s.push({path:g,status:"content_changed",localMd5:u,serverMd5:_}),i.push(`${g}\uFF08\u5185\u5BB9\u53D8\u66F4 \u672C\u5730: ${u} Server: ${_}\uFF09`)):s.push({path:g,status:"no_change"}):(s.push({path:g,status:"no_change"}),d=!0,o.info(`[McpServer] \u5EFA\u7ACB\u5355\u6587\u4EF6\u57FA\u7EBF: ${g} new=${u} (workspace=${l}, memory=${r.uri})`))}catch(u){o.info(`[McpServer] \u8BA1\u7B97\u6587\u4EF6 MD5 \u5931\u8D25: ${g}`,u),s.push({path:g,status:"no_change"})}if(m&&Object.keys(n).length>0){r.file_md5_map=n,r.last_check_time=new Date().toISOString();continue}d&&Object.keys(n).length>0&&(r.file_md5_map=n,r.last_check_time=new Date().toISOString()),i.length>0&&(t.push({memoryId:r.id,memoryUri:r.uri,fileStatuses:s,changedFiles:i}),r.last_check_time=new Date().toISOString())}catch(i){o.warn(`[McpServer] \u68C0\u67E5 Memory ${r.id} \u6587\u4EF6\u53D8\u66F4\u5931\u8D25:`,i)}return t}async calculateFileMd5(e){try{const{createReadStream:t}=await import("node:fs"),{createHash:r}=await import("node:crypto"),i=process.env.AWS_WORKSPACE_PATH||process.cwd(),s=S.resolve(i,e),n=S.resolve(i),a=S.resolve(s);return!a.startsWith(n+S.sep)&&a!==n?(o.warn(`[McpServer] calculateFileMd5: \u8DEF\u5F84\u9003\u9038\u88AB\u62D2\u7EDD: ${e}`),null):new Promise(l=>{const m=r("md5"),d=t(s);d.on("data",g=>m.update(g)),d.on("end",()=>l(m.digest("hex"))),d.on("error",()=>l(null))})}catch(t){return o.info(`[McpServer] \u8BA1\u7B97\u6587\u4EF6 MD5 \u5931\u8D25: ${e}`,t),null}}async verifyFileNotExist(e){try{return await P.promises.access(e,P.constants.F_OK),!1}catch{return!0}}async handleGetMessage(e=!1){if(e){const n=await this.confirmServerMessages(this.messageBuffer.takeForceDirectMessages());return this.buildPollResult(n)}const t=this.messageBuffer.size()>0;await this.hydrateUnreadMessagesFromServer();const r=await this.confirmServerMessages(this.messageBuffer.get()),i=r.directMessages.length>0||r.groupMessages.length>0,s=t||!i;return await this.prependMemoryNotification(r,()=>this.buildMemoryRecurrenceNotification())?this.buildPollResult(r,s):await this.prependMemoryNotification(r,()=>this.buildMemoryCleanupNotification())?this.buildPollResult(r,s):this.buildPollResult(r,s)}async confirmServerMessages(e){const t=l=>!!l.msgId&&(l.channel==="meeting_invite"||l.channel==="notification")&&!l._awsServerMessage,r=l=>!!l._awsServerMessage&&!!l.msgId&&l.channel==="meeting",i=e.directMessages.filter(l=>l._awsServerMessage&&l.msgId&&!r(l)),s=e.directMessages.filter(r),n=e.groupMessages.filter(l=>l._awsServerMessage&&l.msgId!==void 0),a=e.directMessages.filter(t);if(i.length===0&&s.length===0&&n.length===0&&a.length===0)return e;try{const l=Date.now();let m=null;if(i.length>0&&(E("confirm.dm-read.start",`mark_dm_read ${i.length} \u6761\uFF08\u6807\u51C6 callTool\uFF0C\u5E26\u91CD\u8BD5\u6700\u957F\u53EF\u8FBE 30s\uFF09`),m=await this.agentClient.markDmRead(i.map(h=>h.msgId)),E("confirm.dm-read.done",`\u8017\u65F6 ${Date.now()-l}ms\uFF0C\u53EF\u4EA4\u4ED8=${m.size}/${i.length}`)),s.length>0){o.info("[McpServer][DEBUG-poll] \u786E\u8BA4\u4EA4\u4ED8\u4F1A\u8BAE\u6D88\u606F %d \u6761: %s",s.length,JSON.stringify(s.map(M=>({id:M.msgId,channel:M.channel})))),E("confirm.meeting-messages",`count=${s.length} msgs=${D(s)}\uFF08\u5F00\u59CB mark_meeting_read\uFF09`);const h=Date.now();await this.agentClient.markMeetingRead(s.map(M=>M.msgId)),E("confirm.meeting-messages.done",`mark_meeting_read \u5B8C\u6210\uFF0C\u8017\u65F6 ${Date.now()-h}ms`)}const d=new Set,g=new Map;for(const h of n){if(!h.roomId){d.add(h.msgId);continue}const M=g.get(h.roomId)||[];M.push(h.msgId),g.set(h.roomId,M)}for(const[h,M]of g){const c=await this.agentClient.markGroupRead(h,M);for(const y of c)d.add(y)}if(a.length>0){o.info("[McpServer][DEBUG-poll] \u786E\u8BA4\u4EA4\u4ED8\u901A\u77E5 %d \u6761: %s",a.length,JSON.stringify(a.map(M=>({id:M.msgId,channel:M.channel})))),E("confirm.notifications",`count=${a.length} msgs=${D(a)}\uFF08\u5F00\u59CB mark_notification_read\uFF09`);const h=Date.now();await this.agentClient.markNotificationRead(a.map(M=>M.msgId)),E("confirm.notifications.done",`mark_notification_read \u5B8C\u6210\uFF0C\u7D2F\u8BA1\u8017\u65F6 ${Date.now()-l}ms`)}const u=e.directMessages.filter(h=>t(h)||r(h)||!h._awsServerMessage||!h.msgId?!0:m?m.has(h.msgId):!0),_=e.groupMessages.filter(h=>!h._awsServerMessage||h.msgId===void 0?!0:d.has(h.msgId)),b=e.directMessages.length-u.length+e.groupMessages.length-_.length;b>0&&o.info("[McpServer] \u4EA4\u4ED8\u786E\u8BA4\uFF1A\u4E22\u5F03\u5DF2\u64A4\u56DE\u6D88\u606F %d \u6761\uFF08\u79C1\u4FE1 %d / \u7FA4\u804A %d\uFF09",b,e.directMessages.length-u.length,e.groupMessages.length-_.length);for(const h of u)delete h._awsServerMessage;for(const h of _)delete h._awsServerMessage;return{directMessages:u,groupMessages:_}}catch(l){o.warn("[McpServer] \u6D88\u606F\u4EA4\u4ED8\u786E\u8BA4\u5931\u8D25\uFF0C\u964D\u7EA7\u4E3A\u76F4\u63A5\u4EA4\u4ED8: %s",l instanceof Error?l.message:String(l)),E("confirm.failed-degrade",`\u786E\u8BA4\u5931\u8D25\u964D\u7EA7\u4E3A\u76F4\u63A5\u4EA4\u4ED8: ${l instanceof Error?l.message:String(l)}\uFF08\u82E5\u6B64\u5904\u957F\u65F6\u95F4\u65E0\u4E0B\u6587\uFF0C\u8BF4\u660E\u5361\u5728\u6807\u51C6 callTool \u7684\u91CD\u8BD5\u5FAA\u73AF\u5185\uFF09`);for(const m of e.directMessages)delete m._awsServerMessage;for(const m of e.groupMessages)delete m._awsServerMessage;return e}}async hydrateUnreadMessagesFromServer(e={}){try{let t;try{t=await this.agentClient.fetchUnreadMessages({blockIfEmpty:e.blockIfEmpty??!1,blockTimeoutMs:e.blockTimeoutMs,includePipelineTasks:e.includePipelineTasks,pollMessageTimeoutMs:e.pollMessageTimeoutMs,skipGroupMessages:e.skipGroupMessages,preemptiveJoinWaitMs:e.preemptiveJoinWaitMs,propagatePollTimeout:e.propagatePollTimeout===!0})}catch(n){if(n instanceof ee)return E("hydrate.poll-timeout",`pollMessageTimeoutMs=${String(e.pollMessageTimeoutMs??"-")} \u5BA2\u6237\u7AEF\u8D85\u65F6\uFF0C\u670D\u52A1\u7AEF\u5927\u6982\u7387\u4ECD\u5728\u6267\u884C\u540C\u4E00\u8BF7\u6C42`),{failed:!0,timedOut:!0};throw n}if(t.directMessages.length===0&&t.groupMessages.length===0)return E("hydrate.empty",`blockIfEmpty=${String(e.blockIfEmpty??!1)} preemptiveJoinWaitMs=${String(e.preemptiveJoinWaitMs??"-")} \u670D\u52A1\u7AEF\u672C\u6B21\u8FD4\u56DE 0 \u6761`),{failed:!1,timedOut:!1};const r=t.directMessages.filter(n=>!this.shouldBufferIncomingMessage(n)),i=t.directMessages.filter(n=>this.shouldBufferIncomingMessage(n));r.length>0&&E("hydrate.dropped-by-filter",`dropped=${D(r)}`);const s=t.groupMessages.filter(n=>this.shouldBufferIncomingMessage(n));return i.forEach(n=>{const a=n.channel;a!=="meeting_invite"&&a!=="notification"&&(n._awsServerMessage=!0),this.messageBuffer.push(n)}),s.forEach(n=>{n._awsServerMessage=!0,this.messageBuffer.push(n)}),o.info(`[McpServer] \u5DF2\u8865\u62C9\u672A\u8BFB\u6D88\u606F\uFF0C\u79C1\u804A: ${i.length}\uFF0C\u7FA4\u804A: ${s.length}`),E("hydrate.buffered",`dm=${D(i)} gm=${s.length}`),{failed:!1,timedOut:!1}}catch(t){return o.error("[McpServer] \u8865\u62C9\u672A\u8BFB\u6D88\u606F\u5931\u8D25: %s, stack=%s",t instanceof Error?t.message:String(t),t instanceof Error?t.stack:"(no stack)"),E("hydrate.failed",`${t instanceof Error?t.message:String(t)}`),{failed:!0,timedOut:!1}}}async hydrateBrowserListenerEvents(){try{const e=await this.agentClient.fetchBrowserListenerEvents();if(e.length===0)return!1;o.info(`[McpServer] \u62C9\u53D6\u5230 ${e.length} \u6761\u6D4F\u89C8\u5668\u76D1\u542C\u5668\u4E8B\u4EF6\uFF0C\u6CE8\u5165\u6D88\u606F\u7F13\u51B2`);for(const t of e){const r=this.buildListenerEventNotification(t);r&&this.messageBuffer.push(r)}return!0}catch(e){return o.warn("[McpServer] \u62C9\u53D6\u6D4F\u89C8\u5668\u76D1\u542C\u5668\u4E8B\u4EF6\u5931\u8D25: %s",e instanceof Error?e.message:String(e)),!1}}async hydratePluginEvents(){try{const e=await this.agentClient.fetchPluginEvents();if(e.catalog&&(this.cachedPluginCatalog=e.catalog,this.pluginCatalogDrainCompactionSeq=e.compactionSeq),e.events.length===0)return!1;o.info(`[McpServer] \u62C9\u53D6\u5230 ${e.events.length} \u6761\u63D2\u4EF6\u4E8B\u4EF6\uFF0C\u6CE8\u5165\u6D88\u606F\u7F13\u51B2`);for(const t of e.events)this.messageBuffer.push(t);return!0}catch(e){return o.warn("[McpServer] \u62C9\u53D6\u63D2\u4EF6\u4E8B\u4EF6\u5931\u8D25: %s",e instanceof Error?e.message:String(e)),!1}}buildListenerEventNotification(e){try{const t=this.getCurrentAgentId(),r=e.browserId&&e.browserId!=="default"?`\u6D4F\u89C8\u5668[${e.browserId}]`:"\u6D4F\u89C8\u5668",i=e.selector?`\u5143\u7D20\u9009\u62E9\u5668: ${e.selector}
40
+ \u8BF7\u8C03\u7528 read_memory \u67E5\u770B\u5185\u5BB9\u5E76\u8C03\u7528 update_memory \u66F4\u65B0\u3002\u66F4\u65B0\u5B8C\u6210\u540E\u72B6\u6001\u5C06\u81EA\u52A8\u6062\u590D\u4E3A\u6B63\u5E38\u3002`,requireReply:!1,timestamp:new Date().toISOString(),_acodeAutoDelegate:{type:"memory_file_change",uris:v.map(f=>f.memoryUri),fileChanges:v.map(f=>{const C=t.find(R=>R.id===f.memoryId);return{uri:f.memoryUri,boundFiles:C?.bound_files??[],fileStatuses:f.fileStatuses,changedFiles:f.changedFiles}})}}}}return o.info("[McpServer] \u6587\u4EF6\u53D8\u66F4\u68C0\u6D4B\u5B8C\u6210: \u65E0\u53D8\u66F4\u901A\u77E5\u4EA7\u751F"),null}catch(e){return o.warn("[McpServer] \u6784\u5EFA Memory \u6587\u4EF6\u53D8\u66F4\u68C0\u6D4B\u901A\u77E5\u5931\u8D25: %s",e instanceof Error?e.message:String(e)),null}}isClaimCached(e){return this.activeLeaseUris.has(e)}async computeBoundFileStatuses(e){const t=[];if(!e.bound_files||e.bound_files.length===0)return t;const r=e.file_md5_map||{},i=process.env.AWS_WORKSPACE_PATH||process.cwd();for(const s of e.bound_files)try{const n=await this.calculateFileMd5(s);if(n===null){const l=S.resolve(i,s);await this.verifyFileNotExist(l)&&r[s]?t.push({path:s,status:"not_found",serverMd5:r[s]}):t.push({path:s,status:"no_change"});continue}const a=r[s];a?a!==n?t.push({path:s,status:"content_changed",localMd5:n,serverMd5:a}):t.push({path:s,status:"no_change"}):t.push({path:s,status:"no_change"})}catch{t.push({path:s,status:"no_change"})}return t}fileChangeFingerprint(e){const t=e.fileStatuses.filter(r=>r.status!=="no_change").map(r=>`${r.path}:${r.status}:${r.localMd5??""}`).sort();return`${e.memoryId}|${t.join("|")}`}filterFileChangesByRenotifyCooldown(e){if(e.length===0)return e;const t=Date.now(),r=[];let i=0;for(const s of e){const n=this.fileChangeFingerprint(s),a=this.fileChangeNotifyHistory.get(n);if(a!==void 0&&t-a<z){i++;continue}this.fileChangeNotifyHistory.set(n,t),r.push(s)}if(i>0&&o.info("[McpServer] \u6587\u4EF6\u53D8\u66F4\u63D0\u9192\u51B7\u5374\u4E2D\uFF0C\u672C\u8F6E\u6291\u5236 %d \u6761\u91CD\u590D\u901A\u77E5\uFF08cooldown=%dms\uFF09",i,z),this.fileChangeNotifyHistory.size>G){const s=this.fileChangeNotifyHistory.size-G;let n=0;for(const a of this.fileChangeNotifyHistory.keys()){if(n>=s)break;this.fileChangeNotifyHistory.delete(a),n++}}return r}async checkMemoriesFileChanges(e){const t=[];for(const r of e)if(!(!r.bound_files||r.bound_files.length===0))try{const i=[],s=[],n={},a=r.file_md5_map||{},l=process.env.AWS_WORKSPACE_PATH||process.cwd(),m=Object.keys(a).length===0;let d=!1;for(const g of r.bound_files)try{const u=await this.calculateFileMd5(g);if(u===null){const b=S.resolve(l,g);o.info(`[McpServer] MD5 \u8BA1\u7B97\u8FD4\u56DE null: ${g} -> ${b} (workspace=${l})`);const h=a[g];h?await this.verifyFileNotExist(b)?(s.push({path:g,status:"not_found",serverMd5:h}),i.push(`${g}\uFF08\u6587\u4EF6\u627E\u4E0D\u5230 Server: ${h}\uFF09`),r.bound_files&&(r.bound_files=r.bound_files.filter(c=>c!==g))):(o.info(`[McpServer] \u6587\u4EF6\u5B58\u5728\u4F46 MD5 \u8BA1\u7B97\u5931\u8D25\uFF08\u77AC\u6001\u9519\u8BEF\uFF09\uFF0C\u8DF3\u8FC7: ${g}`),s.push({path:g,status:"no_change"})):s.push({path:g,status:"no_change"});continue}n[g]=u;const _=a[g];_?_!==u?(o.info(`[McpServer] \u6587\u4EF6\u53D8\u66F4: ${g} old=${_} new=${u} (workspace=${l})`),s.push({path:g,status:"content_changed",localMd5:u,serverMd5:_}),i.push(`${g}\uFF08\u5185\u5BB9\u53D8\u66F4 \u672C\u5730: ${u} Server: ${_}\uFF09`)):s.push({path:g,status:"no_change"}):(s.push({path:g,status:"no_change"}),d=!0,o.info(`[McpServer] \u5EFA\u7ACB\u5355\u6587\u4EF6\u57FA\u7EBF: ${g} new=${u} (workspace=${l}, memory=${r.uri})`))}catch(u){o.info(`[McpServer] \u8BA1\u7B97\u6587\u4EF6 MD5 \u5931\u8D25: ${g}`,u),s.push({path:g,status:"no_change"})}if(m&&Object.keys(n).length>0){r.file_md5_map=n,r.last_check_time=new Date().toISOString();continue}d&&Object.keys(n).length>0&&(r.file_md5_map=n,r.last_check_time=new Date().toISOString()),i.length>0&&(t.push({memoryId:r.id,memoryUri:r.uri,fileStatuses:s,changedFiles:i}),r.last_check_time=new Date().toISOString())}catch(i){o.warn(`[McpServer] \u68C0\u67E5 Memory ${r.id} \u6587\u4EF6\u53D8\u66F4\u5931\u8D25:`,i)}return t}async calculateFileMd5(e){try{const{createReadStream:t}=await import("node:fs"),{createHash:r}=await import("node:crypto"),i=process.env.AWS_WORKSPACE_PATH||process.cwd(),s=S.resolve(i,e),n=S.resolve(i),a=S.resolve(s);return!a.startsWith(n+S.sep)&&a!==n?(o.warn(`[McpServer] calculateFileMd5: \u8DEF\u5F84\u9003\u9038\u88AB\u62D2\u7EDD: ${e}`),null):new Promise(l=>{const m=r("md5"),d=t(s);d.on("data",g=>m.update(g)),d.on("end",()=>l(m.digest("hex"))),d.on("error",()=>l(null))})}catch(t){return o.info(`[McpServer] \u8BA1\u7B97\u6587\u4EF6 MD5 \u5931\u8D25: ${e}`,t),null}}async verifyFileNotExist(e){try{return await P.promises.access(e,P.constants.F_OK),!1}catch{return!0}}async handleGetMessage(e=!1){if(e){const n=await this.confirmServerMessages(this.messageBuffer.takeForceDirectMessages());return this.buildPollResult(n)}const t=this.messageBuffer.size()>0;await this.hydrateUnreadMessagesFromServer();const r=await this.confirmServerMessages(this.messageBuffer.get()),i=r.directMessages.length>0||r.groupMessages.length>0,s=t||!i;return await this.prependMemoryNotification(r,()=>this.buildMemoryRecurrenceNotification())?this.buildPollResult(r,s):await this.prependMemoryNotification(r,()=>this.buildMemoryCleanupNotification())?this.buildPollResult(r,s):this.buildPollResult(r,s)}async confirmServerMessages(e){const t=l=>!!l.msgId&&(l.channel==="meeting_invite"||l.channel==="notification")&&!l._awsServerMessage,r=l=>!!l._awsServerMessage&&!!l.msgId&&l.channel==="meeting",i=e.directMessages.filter(l=>l._awsServerMessage&&l.msgId&&!r(l)),s=e.directMessages.filter(r),n=e.groupMessages.filter(l=>l._awsServerMessage&&l.msgId!==void 0),a=e.directMessages.filter(t);if(i.length===0&&s.length===0&&n.length===0&&a.length===0)return e;try{const l=Date.now();let m=null;if(i.length>0&&(E("confirm.dm-read.start",`mark_dm_read ${i.length} \u6761\uFF08\u6807\u51C6 callTool\uFF0C\u5E26\u91CD\u8BD5\u6700\u957F\u53EF\u8FBE 30s\uFF09`),m=await this.agentClient.markDmRead(i.map(h=>h.msgId)),E("confirm.dm-read.done",`\u8017\u65F6 ${Date.now()-l}ms\uFF0C\u53EF\u4EA4\u4ED8=${m.size}/${i.length}`)),s.length>0){o.info("[McpServer][DEBUG-poll] \u786E\u8BA4\u4EA4\u4ED8\u4F1A\u8BAE\u6D88\u606F %d \u6761: %s",s.length,JSON.stringify(s.map(M=>({id:M.msgId,channel:M.channel})))),E("confirm.meeting-messages",`count=${s.length} msgs=${O(s)}\uFF08\u5F00\u59CB mark_meeting_read\uFF09`);const h=Date.now();await this.agentClient.markMeetingRead(s.map(M=>M.msgId)),E("confirm.meeting-messages.done",`mark_meeting_read \u5B8C\u6210\uFF0C\u8017\u65F6 ${Date.now()-h}ms`)}const d=new Set,g=new Map;for(const h of n){if(!h.roomId){d.add(h.msgId);continue}const M=g.get(h.roomId)||[];M.push(h.msgId),g.set(h.roomId,M)}for(const[h,M]of g){const c=await this.agentClient.markGroupRead(h,M);for(const y of c)d.add(y)}if(a.length>0){o.info("[McpServer][DEBUG-poll] \u786E\u8BA4\u4EA4\u4ED8\u901A\u77E5 %d \u6761: %s",a.length,JSON.stringify(a.map(M=>({id:M.msgId,channel:M.channel})))),E("confirm.notifications",`count=${a.length} msgs=${O(a)}\uFF08\u5F00\u59CB mark_notification_read\uFF09`);const h=Date.now();await this.agentClient.markNotificationRead(a.map(M=>M.msgId)),E("confirm.notifications.done",`mark_notification_read \u5B8C\u6210\uFF0C\u7D2F\u8BA1\u8017\u65F6 ${Date.now()-l}ms`)}const u=e.directMessages.filter(h=>t(h)||r(h)||!h._awsServerMessage||!h.msgId?!0:m?m.has(h.msgId):!0),_=e.groupMessages.filter(h=>!h._awsServerMessage||h.msgId===void 0?!0:d.has(h.msgId)),b=e.directMessages.length-u.length+e.groupMessages.length-_.length;b>0&&o.info("[McpServer] \u4EA4\u4ED8\u786E\u8BA4\uFF1A\u4E22\u5F03\u5DF2\u64A4\u56DE\u6D88\u606F %d \u6761\uFF08\u79C1\u4FE1 %d / \u7FA4\u804A %d\uFF09",b,e.directMessages.length-u.length,e.groupMessages.length-_.length);for(const h of u)delete h._awsServerMessage;for(const h of _)delete h._awsServerMessage;return{directMessages:u,groupMessages:_}}catch(l){o.warn("[McpServer] \u6D88\u606F\u4EA4\u4ED8\u786E\u8BA4\u5931\u8D25\uFF0C\u964D\u7EA7\u4E3A\u76F4\u63A5\u4EA4\u4ED8: %s",l instanceof Error?l.message:String(l)),E("confirm.failed-degrade",`\u786E\u8BA4\u5931\u8D25\u964D\u7EA7\u4E3A\u76F4\u63A5\u4EA4\u4ED8: ${l instanceof Error?l.message:String(l)}\uFF08\u82E5\u6B64\u5904\u957F\u65F6\u95F4\u65E0\u4E0B\u6587\uFF0C\u8BF4\u660E\u5361\u5728\u6807\u51C6 callTool \u7684\u91CD\u8BD5\u5FAA\u73AF\u5185\uFF09`);for(const m of e.directMessages)delete m._awsServerMessage;for(const m of e.groupMessages)delete m._awsServerMessage;return e}}async hydrateUnreadMessagesFromServer(e={}){try{let t;try{t=await this.agentClient.fetchUnreadMessages({blockIfEmpty:e.blockIfEmpty??!1,blockTimeoutMs:e.blockTimeoutMs,includePipelineTasks:e.includePipelineTasks,pollMessageTimeoutMs:e.pollMessageTimeoutMs,skipGroupMessages:e.skipGroupMessages,preemptiveJoinWaitMs:e.preemptiveJoinWaitMs,propagatePollTimeout:e.propagatePollTimeout===!0})}catch(n){if(n instanceof ee)return E("hydrate.poll-timeout",`pollMessageTimeoutMs=${String(e.pollMessageTimeoutMs??"-")} \u5BA2\u6237\u7AEF\u8D85\u65F6\uFF0C\u670D\u52A1\u7AEF\u5927\u6982\u7387\u4ECD\u5728\u6267\u884C\u540C\u4E00\u8BF7\u6C42`),{failed:!0,timedOut:!0};throw n}if(t.directMessages.length===0&&t.groupMessages.length===0)return E("hydrate.empty",`blockIfEmpty=${String(e.blockIfEmpty??!1)} preemptiveJoinWaitMs=${String(e.preemptiveJoinWaitMs??"-")} \u670D\u52A1\u7AEF\u672C\u6B21\u8FD4\u56DE 0 \u6761`),{failed:!1,timedOut:!1};const r=t.directMessages.filter(n=>!this.shouldBufferIncomingMessage(n)),i=t.directMessages.filter(n=>this.shouldBufferIncomingMessage(n));r.length>0&&E("hydrate.dropped-by-filter",`dropped=${O(r)}`);const s=t.groupMessages.filter(n=>this.shouldBufferIncomingMessage(n));return i.forEach(n=>{const a=n.channel;a!=="meeting_invite"&&a!=="notification"&&(n._awsServerMessage=!0),this.messageBuffer.push(n)}),s.forEach(n=>{n._awsServerMessage=!0,this.messageBuffer.push(n)}),o.info(`[McpServer] \u5DF2\u8865\u62C9\u672A\u8BFB\u6D88\u606F\uFF0C\u79C1\u804A: ${i.length}\uFF0C\u7FA4\u804A: ${s.length}`),E("hydrate.buffered",`dm=${O(i)} gm=${s.length}`),{failed:!1,timedOut:!1}}catch(t){return o.error("[McpServer] \u8865\u62C9\u672A\u8BFB\u6D88\u606F\u5931\u8D25: %s, stack=%s",t instanceof Error?t.message:String(t),t instanceof Error?t.stack:"(no stack)"),E("hydrate.failed",`${t instanceof Error?t.message:String(t)}`),{failed:!0,timedOut:!1}}}async hydrateBrowserListenerEvents(){try{const e=await this.agentClient.fetchBrowserListenerEvents();if(e.length===0)return!1;o.info(`[McpServer] \u62C9\u53D6\u5230 ${e.length} \u6761\u6D4F\u89C8\u5668\u76D1\u542C\u5668\u4E8B\u4EF6\uFF0C\u6CE8\u5165\u6D88\u606F\u7F13\u51B2`);for(const t of e){const r=this.buildListenerEventNotification(t);r&&this.messageBuffer.push(r)}return!0}catch(e){return o.warn("[McpServer] \u62C9\u53D6\u6D4F\u89C8\u5668\u76D1\u542C\u5668\u4E8B\u4EF6\u5931\u8D25: %s",e instanceof Error?e.message:String(e)),!1}}async hydratePluginEvents(){try{const e=await this.agentClient.fetchPluginEvents();if(e.catalog&&(this.cachedPluginCatalog=e.catalog,this.pluginCatalogDrainCompactionSeq=e.compactionSeq),e.events.length===0)return!1;o.info(`[McpServer] \u62C9\u53D6\u5230 ${e.events.length} \u6761\u63D2\u4EF6\u4E8B\u4EF6\uFF0C\u6CE8\u5165\u6D88\u606F\u7F13\u51B2`);for(const t of e.events)this.messageBuffer.push(t);return!0}catch(e){return o.warn("[McpServer] \u62C9\u53D6\u63D2\u4EF6\u4E8B\u4EF6\u5931\u8D25: %s",e instanceof Error?e.message:String(e)),!1}}buildListenerEventNotification(e){try{const t=this.getCurrentAgentId(),r=e.browserId&&e.browserId!=="default"?`\u6D4F\u89C8\u5668[${e.browserId}]`:"\u6D4F\u89C8\u5668",i=e.selector?`\u5143\u7D20\u9009\u62E9\u5668: ${e.selector}
41
41
  `:"",s=this.formatChangeType(e.changeType),n=new Date(e.triggeredAt).toISOString(),a=`\u3010\u6D4F\u89C8\u5668\u76D1\u542C\u5668\u89E6\u53D1 | ${r} | URL: ${e.url}\u3011
42
42
  ${i}\u53D8\u5316\u7C7B\u578B: ${s}
43
43
  \u89E6\u53D1\u65F6\u95F4: ${n}
@@ -48,5 +48,5 @@ ${i}\u53D8\u5316\u7C7B\u578B: ${s}
48
48
  `),m=n.length>a.length?`
49
49
 
50
50
  \uFF08\u53E6\u6709 ${n.length-a.length} \u6761\u5DF2\u5B8C\u6210\uFF0C\u8BF7\u7528 list_background_commands \u67E5\u770B\uFF09`:"";return await P.promises.writeFile(t,JSON.stringify({...i,updatedAt:Date.now(),tasks:s.map(d=>n.some(g=>g.taskId===d.taskId)?{...d,notified:!0}:d)},null,2),"utf-8").catch(d=>{o.warn("[McpServer] \u6807\u8BB0\u540E\u53F0\u4EFB\u52A1\u5DF2\u901A\u77E5\u5931\u8D25: %s",d?.message??d)}),{msgId:`bg-notif-${Date.now()}`,senderId:"MCP-System",senderName:"ACode Background",receiverId:e,content:`[Background commands completed]
51
- ${l}${m}`,requireReply:!1,timestamp:new Date().toISOString()}}catch(e){return o.warn("[McpServer] \u6784\u5EFA\u540E\u53F0\u547D\u4EE4\u5B8C\u6210\u901A\u77E5\u5931\u8D25: %s",e instanceof Error?e.message:String(e)),null}}async start(){const e=new V;await this.server.connect(e),await this.agentClient.initialize(),o.info("[McpServer] MCP Server \u5DF2\u542F\u52A8\uFF0C\u7B49\u5F85\u8FDE\u63A5..."),o.info(`[McpServer] \u53EF\u7528\u5DE5\u5177: ${F.map(t=>t.name).join(", ")}`),o.info(`[McpServer] \u5DE5\u4F5C\u76EE\u5F55: ${process.env.AWS_WORKSPACE_PATH||process.cwd()}`),H&&o.info("[McpServer] \u964D\u7EA7\u6A21\u5F0F\u5DF2\u542F\u7528\uFF0C\u6CE8\u518C\u5931\u8D25\u65F6\u5C06\u4EE5\u79BB\u7EBF\u6A21\u5F0F\u7EE7\u7EED\u8FD0\u884C"),this.autoRegisterInBackground(),o.info("[McpServer] MCP Server \u5DF2\u5C31\u7EEA\uFF0C\u5DE5\u5177\u5DF2\u53EF\u7528")}startLeaseRenewal(){this.leaseRenewalTimer||(this.leaseRenewalTimer=setInterval(async()=>{try{if(!this.getCurrentAgentId())return;(await this.memoryStore.renewMemoryLease(R.LEASE_DURATION_MINUTES)).renewed===0&&(o.warn("[McpServer] \u79DF\u7EA6\u5DF2\u4E22\u5931\uFF08renewed=0\uFF09\uFF0C\u505C\u6B62\u7EED\u671F\u5B9A\u65F6\u5668"),this.stopLeaseRenewal())}catch(e){const t=e instanceof Error?e.message:String(e);t.includes("not supported")?(o.info("[McpServer] \u5F53\u524D\u5B58\u50A8\u4E0D\u652F\u6301\u79DF\u7EA6\u7EED\u671F\uFF0C\u505C\u6B62\u7EED\u671F\u5B9A\u65F6\u5668"),this.stopLeaseRenewal()):o.warn("[McpServer] \u7EED\u671F\u79DF\u7EA6\u5931\u8D25: %s",t)}},R.LEASE_RENEW_INTERVAL_MS),o.info("[McpServer] \u79DF\u7EA6\u7EED\u671F\u5B9A\u65F6\u5668\u5DF2\u542F\u52A8\uFF0C\u95F4\u9694: 60s"))}stopLeaseRenewal(){this.leaseRenewalTimer&&(clearInterval(this.leaseRenewalTimer),this.leaseRenewalTimer=null,o.info("[McpServer] \u79DF\u7EA6\u7EED\u671F\u5B9A\u65F6\u5668\u5DF2\u505C\u6B62"))}stop(){this.stopLeaseRenewal(),this.getCurrentAgentId()&&this.memoryStore.releaseAllMemoryClaims().catch(t=>o.warn("[McpServer] \u91CA\u653E claim \u5931\u8D25: %s",t instanceof Error?t.message:String(t))),this.agentClient.stop(),o.info("[McpServer] MCP Server \u5DF2\u505C\u6B62")}async autoRegister(){const e=this.agentClient.getAgentConfig();o.info(`[McpServer] \u89D2\u8272: "${e.roleName}"`),o.info(`[McpServer] AgentID: "${e.agentId||"(\u81EA\u52A8\u5206\u914D)"}"`),o.info("[McpServer] \u6B63\u5728\u8BF7\u6C42\u8C03\u5EA6\u4E2D\u5FC3\u6CE8\u518C...");let t=0;for(;;)try{const r=await this.agentClient.register();o.info(`[McpServer] \u6CE8\u518C\u6210\u529F: ${r.displayName} (${r.agentId})`),o.info(`[McpServer] \u72B6\u6001: ${r.status}`),this.startListeningInternal(),o.info("[McpServer] \u6D88\u606F\u76D1\u542C\u5DF2\u81EA\u52A8\u542F\u52A8");const i=this.agentClient.getStatusReporter();i&&i.reportWaitingInput(),await this.reportMemoryStatsToServer(),this.maybeSyncPermanentMemoryToServer();return}catch(r){const i=r instanceof Error?r.message:String(r);if(t++,O>0&&t>=O){if(H){o.warn(`[McpServer] \u6CE8\u518C\u8D85\u8FC7\u6700\u5927\u91CD\u8BD5\u6B21\u6570 (${O}\u6B21)\uFF0C\u8FDB\u5165\u964D\u7EA7\u6A21\u5F0F`),this.agentClient.enterDegradedMode(),this.startListeningInternal(),o.info("[McpServer] \u964D\u7EA7\u6A21\u5F0F\uFF1A\u6D88\u606F\u76D1\u542C\u5DF2\u542F\u52A8"),this.agentClient.retryRegistrationInBackground(ne,oe);const s=this.agentClient.getStatusReporter();s&&s.reportWaitingInput(),await this.reportMemoryStatsToServer();return}throw new Error(`\u6CE8\u518C\u8D85\u8FC7\u6700\u5927\u91CD\u8BD5\u6B21\u6570 (${O}\u6B21)\uFF0C\u653E\u5F03\u542F\u52A8: ${i}`)}o.warn(`[McpServer] \u6CE8\u518C\u5931\u8D25\uFF0C\u7B49\u5F85\u91CD\u8BD5... (${t}/${O}): ${i}`),await this.delay(ie)}}autoRegisterInBackground(){this.autoRegister().catch(e=>{o.error("[McpServer] \u540E\u53F0\u6CE8\u518C\u5F02\u5E38: %s, stack=%s",e instanceof Error?e.message:String(e),e instanceof Error?e.stack:"(no stack)")})}startListeningInternal(){o.info("[McpServer] startListeningInternal \u88AB\u8C03\u7528");const e=t=>{o.info(`[McpServer] profileHandler \u88AB\u8C03\u7528\uFF0CdisplayName: ${t.displayName}`),this.messageBuffer.setProfileMessage(t),this.profileSynced=!0,this.syncRoleMemoryStore(t),this.maybeSyncPermanentMemoryToServer()};if(this.agentClient.isInDegradedMode()){o.info("[McpServer] \u964D\u7EA7\u6A21\u5F0F\uFF1A\u8DF3\u8FC7 WebSocket \u8FDE\u63A5\uFF0C\u4EC5\u542F\u52A8\u672C\u5730\u6D88\u606F\u76D1\u542C"),this.agentClient.start(this.handleIncomingMessage.bind(this),{pollMode:!1,profileHandler:e,systemNotifyHandler:this.handleSystemNotify.bind(this)}),this.activelySyncProfile();return}this.agentClient.start(this.handleIncomingMessage.bind(this),{pollMode:!1,profileHandler:e,systemNotifyHandler:this.handleSystemNotify.bind(this)}),this.activelySyncProfile()}activelySyncProfile(){this.profileSynced||this.agentClient.getProfile().then(e=>{this.profileSynced||(this.profileSynced=!0,o.info(`[McpServer] \u4E3B\u52A8\u83B7\u53D6 profile \u6210\u529F: displayName=${e.displayName}, roleName="${e.roleName??"(\u7A7A)"}"`),this.messageBuffer.setProfileMessage(e),this.syncRoleMemoryStore(e),this.maybeSyncPermanentMemoryToServer())}).catch(e=>{o.warn("[McpServer] \u4E3B\u52A8\u83B7\u53D6 profile \u5931\u8D25: %s",e instanceof Error?e.message:String(e))})}delay(e){return new Promise(t=>setTimeout(t,e))}}export{R as McpServer};
51
+ ${l}${m}`,requireReply:!1,timestamp:new Date().toISOString()}}catch(e){return o.warn("[McpServer] \u6784\u5EFA\u540E\u53F0\u547D\u4EE4\u5B8C\u6210\u901A\u77E5\u5931\u8D25: %s",e instanceof Error?e.message:String(e)),null}}async start(){const e=new V;await this.server.connect(e),await this.agentClient.initialize(),o.info("[McpServer] MCP Server \u5DF2\u542F\u52A8\uFF0C\u7B49\u5F85\u8FDE\u63A5..."),o.info(`[McpServer] \u53EF\u7528\u5DE5\u5177: ${F.map(t=>t.name).join(", ")}`),o.info(`[McpServer] \u5DE5\u4F5C\u76EE\u5F55: ${process.env.AWS_WORKSPACE_PATH||process.cwd()}`),H&&o.info("[McpServer] \u964D\u7EA7\u6A21\u5F0F\u5DF2\u542F\u7528\uFF0C\u6CE8\u518C\u5931\u8D25\u65F6\u5C06\u4EE5\u79BB\u7EBF\u6A21\u5F0F\u7EE7\u7EED\u8FD0\u884C"),this.autoRegisterInBackground(),o.info("[McpServer] MCP Server \u5DF2\u5C31\u7EEA\uFF0C\u5DE5\u5177\u5DF2\u53EF\u7528")}startLeaseRenewal(){this.leaseRenewalTimer||(this.leaseRenewalTimer=setInterval(async()=>{try{if(!this.getCurrentAgentId())return;(await this.memoryStore.renewMemoryLease(T.LEASE_DURATION_MINUTES)).renewed===0&&(o.warn("[McpServer] \u79DF\u7EA6\u5DF2\u4E22\u5931\uFF08renewed=0\uFF09\uFF0C\u505C\u6B62\u7EED\u671F\u5B9A\u65F6\u5668"),this.stopLeaseRenewal())}catch(e){const t=e instanceof Error?e.message:String(e);t.includes("not supported")?(o.info("[McpServer] \u5F53\u524D\u5B58\u50A8\u4E0D\u652F\u6301\u79DF\u7EA6\u7EED\u671F\uFF0C\u505C\u6B62\u7EED\u671F\u5B9A\u65F6\u5668"),this.stopLeaseRenewal()):o.warn("[McpServer] \u7EED\u671F\u79DF\u7EA6\u5931\u8D25: %s",t)}},T.LEASE_RENEW_INTERVAL_MS),o.info("[McpServer] \u79DF\u7EA6\u7EED\u671F\u5B9A\u65F6\u5668\u5DF2\u542F\u52A8\uFF0C\u95F4\u9694: 60s"))}stopLeaseRenewal(){this.leaseRenewalTimer&&(clearInterval(this.leaseRenewalTimer),this.leaseRenewalTimer=null,o.info("[McpServer] \u79DF\u7EA6\u7EED\u671F\u5B9A\u65F6\u5668\u5DF2\u505C\u6B62"))}stop(){this.stopLeaseRenewal(),this.getCurrentAgentId()&&this.memoryStore.releaseAllMemoryClaims().catch(t=>o.warn("[McpServer] \u91CA\u653E claim \u5931\u8D25: %s",t instanceof Error?t.message:String(t))),this.agentClient.stop(),o.info("[McpServer] MCP Server \u5DF2\u505C\u6B62")}async autoRegister(){const e=this.agentClient.getAgentConfig();o.info(`[McpServer] \u89D2\u8272: "${e.roleName}"`),o.info(`[McpServer] AgentID: "${e.agentId||"(\u81EA\u52A8\u5206\u914D)"}"`),o.info("[McpServer] \u6B63\u5728\u8BF7\u6C42\u8C03\u5EA6\u4E2D\u5FC3\u6CE8\u518C...");let t=0;for(;;)try{const r=await this.agentClient.register();o.info(`[McpServer] \u6CE8\u518C\u6210\u529F: ${r.displayName} (${r.agentId})`),o.info(`[McpServer] \u72B6\u6001: ${r.status}`),this.startListeningInternal(),o.info("[McpServer] \u6D88\u606F\u76D1\u542C\u5DF2\u81EA\u52A8\u542F\u52A8");const i=this.agentClient.getStatusReporter();i&&i.reportWaitingInput(),await this.reportMemoryStatsToServer(),this.maybeSyncPermanentMemoryToServer();return}catch(r){const i=r instanceof Error?r.message:String(r);if(t++,D>0&&t>=D){if(H){o.warn(`[McpServer] \u6CE8\u518C\u8D85\u8FC7\u6700\u5927\u91CD\u8BD5\u6B21\u6570 (${D}\u6B21)\uFF0C\u8FDB\u5165\u964D\u7EA7\u6A21\u5F0F`),this.agentClient.enterDegradedMode(),this.startListeningInternal(),o.info("[McpServer] \u964D\u7EA7\u6A21\u5F0F\uFF1A\u6D88\u606F\u76D1\u542C\u5DF2\u542F\u52A8"),this.agentClient.retryRegistrationInBackground(ne,oe);const s=this.agentClient.getStatusReporter();s&&s.reportWaitingInput(),await this.reportMemoryStatsToServer();return}throw new Error(`\u6CE8\u518C\u8D85\u8FC7\u6700\u5927\u91CD\u8BD5\u6B21\u6570 (${D}\u6B21)\uFF0C\u653E\u5F03\u542F\u52A8: ${i}`)}o.warn(`[McpServer] \u6CE8\u518C\u5931\u8D25\uFF0C\u7B49\u5F85\u91CD\u8BD5... (${t}/${D}): ${i}`),await this.delay(ie)}}autoRegisterInBackground(){this.autoRegister().catch(e=>{o.error("[McpServer] \u540E\u53F0\u6CE8\u518C\u5F02\u5E38: %s, stack=%s",e instanceof Error?e.message:String(e),e instanceof Error?e.stack:"(no stack)")})}startListeningInternal(){o.info("[McpServer] startListeningInternal \u88AB\u8C03\u7528");const e=t=>{o.info(`[McpServer] profileHandler \u88AB\u8C03\u7528\uFF0CdisplayName: ${t.displayName}`),this.messageBuffer.setProfileMessage(t),this.profileSynced=!0,this.syncRoleMemoryStore(t),this.maybeSyncPermanentMemoryToServer()};if(this.agentClient.isInDegradedMode()){o.info("[McpServer] \u964D\u7EA7\u6A21\u5F0F\uFF1A\u8DF3\u8FC7 WebSocket \u8FDE\u63A5\uFF0C\u4EC5\u542F\u52A8\u672C\u5730\u6D88\u606F\u76D1\u542C"),this.agentClient.start(this.handleIncomingMessage.bind(this),{pollMode:!1,profileHandler:e,systemNotifyHandler:this.handleSystemNotify.bind(this)}),this.activelySyncProfile();return}this.agentClient.start(this.handleIncomingMessage.bind(this),{pollMode:!1,profileHandler:e,systemNotifyHandler:this.handleSystemNotify.bind(this)}),this.activelySyncProfile()}activelySyncProfile(){this.profileSynced||this.agentClient.getProfile().then(e=>{this.profileSynced||(this.profileSynced=!0,o.info(`[McpServer] \u4E3B\u52A8\u83B7\u53D6 profile \u6210\u529F: displayName=${e.displayName}, roleName="${e.roleName??"(\u7A7A)"}"`),this.messageBuffer.setProfileMessage(e),this.syncRoleMemoryStore(e),this.maybeSyncPermanentMemoryToServer())}).catch(e=>{o.warn("[McpServer] \u4E3B\u52A8\u83B7\u53D6 profile \u5931\u8D25: %s",e instanceof Error?e.message:String(e))})}delay(e){return new Promise(t=>setTimeout(t,e))}}export{T as McpServer};
52
52
 
@@ -10,8 +10,6 @@ export declare const GET_PROFILE_TOOL: Tool;
10
10
 
11
11
  export declare const HIRE_COLLEAGUE_TOOL: Tool;
12
12
 
13
- export declare const HIRE_COLLEAGUES_BATCH_TOOL: Tool;
14
-
15
13
  export declare const SEND_GROUP_TOOL: Tool;
16
14
 
17
15
  export declare const SEND_PRIVATE_TOOL: Tool;