aws-runtime-bridge 1.9.131 → 1.9.134
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/adapter/AcodeSdkAdapter.d.ts +15 -0
- package/dist/adapter/AcodeSdkAdapter.js +5 -5
- package/dist/adapter/types.d.ts +9 -0
- package/dist/browser/built-in-browser-tools.js +1 -1
- package/dist/routes/system-metrics.js +1 -1
- package/dist/routes/terminal.js +19 -19
- package/dist/services/instance-features.d.ts +5 -0
- package/dist/services/instance-features.js +1 -1
- package/dist/services/process-detail.d.ts +77 -0
- package/dist/services/process-detail.js +32 -0
- package/dist/services/process-top.d.ts +53 -0
- package/dist/services/process-top.js +50 -0
- package/dist/services/session-output.d.ts +10 -0
- package/dist/services/session-output.js +3 -3
- package/package/acode/dist/built-in-file-tools.d.ts +25 -1
- package/package/acode/dist/built-in-file-tools.js +2 -2
- package/package/acode/dist/image-utils.d.ts +52 -0
- package/package/acode/dist/image-utils.js +2 -0
- package/package/acode/dist/index.d.ts +1 -0
- package/package/acode/dist/index.js +1 -1
- package/package/acode/dist/runtime.d.ts +15 -1
- package/package/acode/dist/runtime.js +26 -26
- package/package/acode/dist/types.d.ts +3 -1
- package/package/aws-client-agent-mcp/dist/http-client.d.ts +4 -0
- package/package/aws-client-agent-mcp/dist/http-client.js +1 -1
- package/package/aws-client-agent-mcp/dist/mcp-server.d.ts +8 -0
- package/package/aws-client-agent-mcp/dist/mcp-server.js +28 -25
- package/package/aws-client-agent-mcp/dist/mcp-tools.js +6 -6
- package/package/aws-client-agent-mcp/dist/memory-store.d.ts +6 -0
- package/package/aws-client-agent-mcp/dist/memory-tools.js +2 -2
- package/package/aws-client-agent-mcp/dist/types.d.ts +4 -0
- package/package/aws-client-agent-mcp/package.json +1 -1
- package/package.json +1 -1
- package/package/aws-client-agent-mcp/dist/agent-client.test.d.ts +0 -1
- package/package/aws-client-agent-mcp/dist/agent-client.test.js +0 -1066
- package/package/aws-client-agent-mcp/dist/config.test.d.ts +0 -1
- package/package/aws-client-agent-mcp/dist/config.test.js +0 -259
- package/package/aws-client-agent-mcp/dist/context-manager.test.d.ts +0 -2
- package/package/aws-client-agent-mcp/dist/context-manager.test.js +0 -312
- package/package/aws-client-agent-mcp/dist/http-client.test.d.ts +0 -1
- package/package/aws-client-agent-mcp/dist/http-client.test.js +0 -808
- package/package/aws-client-agent-mcp/dist/launch-config-tools.test.d.ts +0 -1
- package/package/aws-client-agent-mcp/dist/launch-config-tools.test.js +0 -110
- package/package/aws-client-agent-mcp/dist/logger.test.d.ts +0 -1
- package/package/aws-client-agent-mcp/dist/logger.test.js +0 -27
- package/package/aws-client-agent-mcp/dist/mcp-server.test.d.ts +0 -1
- package/package/aws-client-agent-mcp/dist/mcp-server.test.js +0 -2798
- package/package/aws-client-agent-mcp/dist/mcp-tools.test.d.ts +0 -1
- package/package/aws-client-agent-mcp/dist/mcp-tools.test.js +0 -152
- package/package/aws-client-agent-mcp/dist/memory-store.test.d.ts +0 -1
- package/package/aws-client-agent-mcp/dist/memory-store.test.js +0 -664
- package/package/aws-client-agent-mcp/dist/message-buffer.test.d.ts +0 -1
- package/package/aws-client-agent-mcp/dist/message-buffer.test.js +0 -142
- package/package/aws-client-agent-mcp/dist/parent-lifecycle.test.d.ts +0 -1
- package/package/aws-client-agent-mcp/dist/parent-lifecycle.test.js +0 -81
- package/package/aws-client-agent-mcp/dist/runtime-launch-binding.test.d.ts +0 -1
- package/package/aws-client-agent-mcp/dist/runtime-launch-binding.test.js +0 -201
- package/package/aws-client-agent-mcp/dist/status-reporter.test.d.ts +0 -1
- package/package/aws-client-agent-mcp/dist/status-reporter.test.js +0 -157
- package/package/aws-client-agent-mcp/dist/watchdog.test.d.ts +0 -1
- package/package/aws-client-agent-mcp/dist/watchdog.test.js +0 -124
- package/package/aws-client-agent-mcp/dist/websocket-client.test.d.ts +0 -1
- package/package/aws-client-agent-mcp/dist/websocket-client.test.js +0 -725
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{logger as o}from"./logger.js";import{meetingDebugLog as h}from"./meeting-debug-log.js";const w=12e4,g=5e3,T=3e4,d=1e3;function p(l){const e=l.trim();return e?e.length<=d?e:`${e.slice(0,d)}...(truncated)`:""}function y(l){return l.replace(/^((?:https?|wss?):\/\/(?:\[[^\]]+\]|[^/:?#]+):\d+):\d+(?=\/|$)/i,"$1")}function C(l){const e=l.toLowerCase();return e==="localhost"||e==="::1"||e==="[::1]"?"127.0.0.1":e}function m(l,e={}){const r=String(l||"").trim();if(!r)return;const s=y(r);try{const t=new URL(s);t.protocol==="ws:"?t.protocol="http:":t.protocol==="wss:"?t.protocol="https:":t.protocol=t.protocol.toLowerCase(),t.hostname=C(t.hostname);const n=e.fromAgentWebSocketUrl?t.pathname.replace(/\/ws\/agent\/?$/,""):t.pathname;return t.pathname=n.includes("/mcp/call")?n:`${n.replace(/\/$/,"")}/mcp/call`,t.search="",t.hash="",t.toString()}catch{const t=(e.fromAgentWebSocketUrl?s.replace(/\/ws\/agent\/?$/i,""):s).replace(/\/+$/,"");return t.endsWith("/mcp/call")?t:`${t}/mcp/call`}}const R=6e5;class E{serverConfig;mcpHttpUrl;tokenRefreshPromise=null;constructor(e){this.serverConfig=e,this.mcpHttpUrl=this.resolveMcpHttpUrl()}async callTool(e,r){await this.ensureRuntimeAccessToken();const s=Date.now()+this.resolveRetryMaxAccumulatedMs();let t=0;for(;;){t++;let n;try{n=await this.executeToolRequest(e,r)}catch(a){if(Date.now()<s&&this.isTransientError(a)){await this.delayForRetry(s,e,t);continue}throw o.warn("[HttpClient] MCP tool %s \u8BF7\u6C42\u4E0D\u53EF\u6062\u590D\u5F02\u5E38 (attempt=%s): %s",e,t,a instanceof Error?a.message:String(a)),a}if(n.status===401){if(o.warn(`[HttpClient] MCP Tool ${e} \u8FD4\u56DE 401\uFF0C\u5C1D\u8BD5\u5411 bridge \u5237\u65B0 token`),await this.tryRefreshToken(r)){let c;try{c=await this.executeToolRequest(e,r)}catch(f){if(Date.now()<s&&this.isTransientError(f)){await this.delayForRetry(s,e,t);continue}throw o.warn("[HttpClient] MCP tool %s 401\u91CD\u8BD5\u5F02\u5E38 (attempt=%s): %s",e,t,f instanceof Error?f.message:String(f)),f}if(!c.ok){if(Date.now()<s&&this.isRetryableHttpStatus(c.status)){await this.delayForRetry(s,e,t);continue}const f=typeof c.text=="function"?p(await c.text().catch(()=>"")):"";throw new Error(`MCP tool ${e} call failed: ${c.status} ${c.statusText}${f?` - ${f}`:""}`)}const u=await c.json();if(typeof u.error=="string"&&u.error.trim().length>0)throw new Error(`MCP tool ${e} failed: ${u.error}`);return u}o.warn("[HttpClient] token \u5237\u65B0\u5931\u8D25\u6216\u65E0\u65B0 token\uFF0C\u8FD4\u56DE\u539F\u59CB 401 \u9519\u8BEF")}if(!n.ok){if(Date.now()<s&&this.isRetryableHttpStatus(n.status)){await this.delayForRetry(s,e,t);continue}const a=typeof n.text=="function"?p(await n.text().catch(()=>"")):"";throw new Error(`MCP tool ${e} call failed: ${n.status} ${n.statusText}${a?` - ${a}`:""}`)}const i=await n.json();if(typeof i.error=="string"&&i.error.trim().length>0)throw new Error(`MCP tool ${e} failed: ${i.error}`);return i}}async fetchRuntimeFeatures(){await this.ensureRuntimeAccessToken();const e=this.mcpHttpUrl.replace(/\/mcp\/call(\/)?$/,"/mcp/features$1");let r;try{r=await fetch(e,{method:"POST",headers:this.buildRequestHeaders(),body:JSON.stringify({})})}catch(t){throw o.warn("[HttpClient] \u67E5\u8BE2\u80FD\u529B\u5F00\u5173\u8BF7\u6C42\u5931\u8D25: %s",t instanceof Error?t.message:String(t)),new Error(`fetch runtime features failed: ${t instanceof Error?t.message:String(t)}`)}if(!r.ok)throw o.warn("[HttpClient] \u67E5\u8BE2\u80FD\u529B\u5F00\u5173\u5931\u8D25: status=%s, statusText=%s",r.status,r.statusText),new Error(`fetch runtime features failed: ${r.status} ${r.statusText}`);const s=await r.json();return!s||typeof s.features!="object"||s.features===null?{}:s.features}async callToolOnce(e,r,s=R){await this.ensureRuntimeAccessToken(),o.info("[HttpClient] callToolOnce \u5F00\u59CB: tool=%s, timeoutMs=%d, url=%s, agentId=%s",e,s,this.mcpHttpUrl,String(r?.agentId??"")),e==="poll_message"&&h("http.callToolOnce.start",`tool=${e} timeoutMs=${s} preemptiveJoinWaitMs=${String(r?.preemptiveJoinWaitMs??"-")}`);const t=c=>fetch(this.mcpHttpUrl,{method:"POST",headers:this.buildRequestHeaders(),body:JSON.stringify({tool:e,arguments:r}),signal:c}),n=Date.now();let i=await this.singleFetchWithTimeout(t,s,e);if(o.info("[HttpClient] callToolOnce \u6536\u5230\u54CD\u5E94: tool=%s, status=%d, \u8017\u65F6=%dms",e,i.status,Date.now()-n),e==="poll_message"&&h("http.callToolOnce.response",`status=${i.status} elapsedMs=${Date.now()-n}`),i.status===401&&(o.warn(`[HttpClient] MCP Tool ${e} \u8FD4\u56DE 401\uFF0C\u5C1D\u8BD5\u5411 bridge \u5237\u65B0 token`),await this.tryRefreshToken(r)&&(i=await this.singleFetchWithTimeout(t,s,e),o.info("[HttpClient] callToolOnce token \u5237\u65B0\u540E\u91CD\u8BD5\u6536\u5230\u54CD\u5E94: tool=%s, status=%d, \u7D2F\u8BA1\u8017\u65F6=%dms",e,i.status,Date.now()-n))),!i.ok){const c=typeof i.text=="function"?p(await this.readTextWithTimeout(i,s,e).catch(()=>"")):"";throw o.info("[HttpClient] callToolOnce \u975E 2xx \u54CD\u5E94: tool=%s, status=%d, body=%s",e,i.status,c||"(\u7A7A)"),new Error(`MCP tool ${e} call failed: ${i.status} ${i.statusText}${c?` - ${c}`:""}`)}const a=await this.parseJsonWithTimeout(i,s,e);if(o.info("[HttpClient] callToolOnce \u5B8C\u6210: tool=%s, \u603B\u8017\u65F6=%dms, error=%s",e,Date.now()-n,typeof a.error=="string"?a.error:"(\u65E0)"),e==="poll_message"){const c=Array.isArray(a.messages)?a.messages:[];h("http.callToolOnce.parsed",`totalElapsedMs=${Date.now()-n} serverMessages=${c.length} `+JSON.stringify(c.map(u=>({msgId:u.msgId,channel:u.channel,sender:u.senderId}))))}if(typeof a.error=="string"&&a.error.trim().length>0)throw new Error(`MCP tool ${e} failed: ${a.error}`);return a}async readTextWithTimeout(e,r,s){if(r<=0)return await e.text();let t;try{return await Promise.race([e.text(),new Promise((n,i)=>{t=setTimeout(()=>i(new Error(`MCP tool ${s} timed out after ${r}ms`)),r)})])}finally{t!==void 0&&clearTimeout(t)}}async parseJsonWithTimeout(e,r,s){if(r<=0)return await e.json();let t;try{return await Promise.race([e.json(),new Promise((n,i)=>{t=setTimeout(()=>i(new Error(`MCP tool ${s} timed out after ${r}ms`)),r)})])}finally{t!==void 0&&clearTimeout(t)}}async singleFetchWithTimeout(e,r,s){const t=new AbortController;let n;r>0&&(n=setTimeout(()=>t.abort(),r));try{return await e(t.signal)}catch(i){throw t.signal.aborted?(s==="poll_message"&&h("http.callToolOnce.timeout",`timeoutMs=${r} \u670D\u52A1\u7AEF\u53EF\u80FD\u4ECD\u5728\u6267\u884C\u540C\u4E00\u8BF7\u6C42\uFF08Callable \u5360\u7EBF\u81F3\u9884\u7B97\u7ED3\u675F\uFF09`),new Error(`MCP tool ${s} timed out after ${r}ms`)):i}finally{n!==void 0&&clearTimeout(n)}}async executeToolRequest(e,r){return await this.fetchWithTimeout(this.mcpHttpUrl,{method:"POST",headers:this.buildRequestHeaders(),body:JSON.stringify({tool:e,arguments:r})},`MCP tool ${e}`)}async fetchWithTimeout(e,r,s){const t=this.resolveRequestTimeoutMs(),n=new AbortController,i=setTimeout(()=>n.abort(),t);try{return await fetch(e,{...r,signal:n.signal})}catch(a){throw n.signal.aborted?new Error(`${s} timed out after ${t}ms`):a}finally{clearTimeout(i)}}resolveRequestTimeoutMs(){const e=this.serverConfig.mcpHttpRequestTimeoutMs;return typeof e=="number"&&Number.isFinite(e)&&e>0?e:w}resolveRetryIntervalMs(){const e=this.serverConfig.mcpRetryIntervalMs;return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:g}resolveRetryMaxAccumulatedMs(){const e=this.serverConfig.mcpRetryMaxAccumulatedMs;return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:T}isTransientError(e){if(!(e instanceof Error))return!1;const r=e.message;return!!(/timed out after \d+ms/.test(r)||/fetch failed/i.test(r)||/network/i.test(r)||/ECONNREFUSED/i.test(r)||/ECONNRESET/i.test(r))}isRetryableHttpStatus(e){return e>=500||e===429}async delayForRetry(e,r,s){const t=e-Date.now(),n=Math.min(this.resolveRetryIntervalMs(),Math.max(0,t));o.warn(`[HttpClient] MCP tool ${r} \u8BF7\u6C42\u5931\u8D25\uFF0C${n}ms \u540E\u91CD\u8BD5 (\u7B2C${s}\u6B21)`),n>0&&await new Promise(i=>setTimeout(i,n))}buildRequestHeaders(){const e={"Content-Type":"application/json"};return this.serverConfig.runtimeAccessToken&&(e["X-Runtime-Token"]=this.serverConfig.runtimeAccessToken,e.Authorization=`Bearer ${this.serverConfig.runtimeAccessToken}`),e}async ensureRuntimeAccessToken(){if(this.serverConfig.runtimeAccessToken||!this.serverConfig.runtimeBridgeBaseUrl){o.info("[HttpClient] ensureRuntimeAccessToken: tokenLen=%d, bridgeBaseUrl=%s",(this.serverConfig.runtimeAccessToken||"").length,this.serverConfig.runtimeBridgeBaseUrl||"(\u7A7A)");return}throw new Error("runtimeAccessToken is required; MCP nodes must claim a session token from launch binding")}async tryRefreshToken(e){if(this.tokenRefreshPromise)return this.tokenRefreshPromise;this.tokenRefreshPromise=this.doRefreshToken(e);try{return await this.tokenRefreshPromise}finally{this.tokenRefreshPromise=null}}async doRefreshToken(e){const r=this.serverConfig.runtimeBridgeBaseUrl;if(!r)return o.warn("[HttpClient] \u65E0 runtimeBridgeBaseUrl\uFF0C\u65E0\u6CD5\u5237\u65B0 token"),!1;const s=String(e?.agentId||"").trim();if(!s)return o.warn("[HttpClient] \u65E0 agentId\uFF0C\u65E0\u6CD5\u5237\u65B0 token"),!1;try{const t=await fetch(`${r}/runtime/binding/refresh-token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({agentId:s,currentToken:this.serverConfig.runtimeAccessToken||""})});if(!t.ok)return o.warn(`[HttpClient] bridge refresh-token \u8FD4\u56DE ${t.status}\uFF0C\u65E0\u6CD5\u5237\u65B0`),!1;const i=(await t.json()).runtimeAccessToken;return i?i===this.serverConfig.runtimeAccessToken?!1:(this.serverConfig.runtimeAccessToken=i,o.info("[HttpClient] runtimeAccessToken \u5DF2\u901A\u8FC7 bridge refresh \u66F4\u65B0"),!0):(o.warn("[HttpClient] bridge \u672A\u8FD4\u56DE\u65B0 token"),!1)}catch(t){return o.warn("[HttpClient] \u5237\u65B0 token \u5931\u8D25: %s",t instanceof Error?t.message:String(t)),t instanceof Error&&t.stack&&o.warn("[HttpClient] \u5237\u65B0 token \u5F02\u5E38\u5806\u6808:",t.stack),!1}}async refreshRuntimeAccessToken(e){return this.tryRefreshToken({agentId:e})}resolveMcpHttpUrl(){const e=this.serverConfig.mcpHttpUrl;if(e&&e.trim().length>0){const s=m(e);if(s)return s}const r=m(this.serverConfig.serverUrl,{fromAgentWebSocketUrl:!0});return r||this.serverConfig.serverUrl}getMcpHttpUrl(){return this.mcpHttpUrl}}export{E as HttpClient};
|
|
1
|
+
import{logger as o}from"./logger.js";import{meetingDebugLog as h}from"./meeting-debug-log.js";const w=12e4,g=5e3,T=3e4,d=1e3;function p(l){const e=l.trim();return e?e.length<=d?e:`${e.slice(0,d)}...(truncated)`:""}function y(l){return l.replace(/^((?:https?|wss?):\/\/(?:\[[^\]]+\]|[^/:?#]+):\d+):\d+(?=\/|$)/i,"$1")}function C(l){const e=l.toLowerCase();return e==="localhost"||e==="::1"||e==="[::1]"?"127.0.0.1":e}function m(l,e={}){const r=R(l,e);if(r)try{const s=new URL(r);return s.pathname=s.pathname.includes("/mcp/call")?s.pathname:`${s.pathname.replace(/\/$/,"")}/mcp/call`,s.search="",s.hash="",s.toString()}catch{return r.endsWith("/mcp/call")?r:`${r}/mcp/call`}}function R(l,e={}){const r=String(l||"").trim();if(!r)return;const s=y(r);try{const t=new URL(s);t.protocol==="ws:"?t.protocol="http:":t.protocol==="wss:"?t.protocol="https:":t.protocol=t.protocol.toLowerCase(),t.hostname=C(t.hostname);const n=e.fromAgentWebSocketUrl?t.pathname.replace(/\/ws\/agent\/?$/,""):t.pathname;return t.pathname=n,t.search="",t.hash="",t.toString().replace(/\/+$/,"")}catch{return(e.fromAgentWebSocketUrl?s.replace(/\/ws\/agent\/?$/i,""):s).replace(/\/+$/,"")||void 0}}const $=6e5;class H{serverConfig;mcpHttpUrl;tokenRefreshPromise=null;constructor(e){this.serverConfig=e,this.mcpHttpUrl=this.resolveMcpHttpUrl()}async callTool(e,r){await this.ensureRuntimeAccessToken();const s=Date.now()+this.resolveRetryMaxAccumulatedMs();let t=0;for(;;){t++;let n;try{n=await this.executeToolRequest(e,r)}catch(a){if(Date.now()<s&&this.isTransientError(a)){await this.delayForRetry(s,e,t);continue}throw o.warn("[HttpClient] MCP tool %s \u8BF7\u6C42\u4E0D\u53EF\u6062\u590D\u5F02\u5E38 (attempt=%s): %s",e,t,a instanceof Error?a.message:String(a)),a}if(n.status===401){if(o.warn(`[HttpClient] MCP Tool ${e} \u8FD4\u56DE 401\uFF0C\u5C1D\u8BD5\u5411 bridge \u5237\u65B0 token`),await this.tryRefreshToken(r)){let c;try{c=await this.executeToolRequest(e,r)}catch(f){if(Date.now()<s&&this.isTransientError(f)){await this.delayForRetry(s,e,t);continue}throw o.warn("[HttpClient] MCP tool %s 401\u91CD\u8BD5\u5F02\u5E38 (attempt=%s): %s",e,t,f instanceof Error?f.message:String(f)),f}if(!c.ok){if(Date.now()<s&&this.isRetryableHttpStatus(c.status)){await this.delayForRetry(s,e,t);continue}const f=typeof c.text=="function"?p(await c.text().catch(()=>"")):"";throw new Error(`MCP tool ${e} call failed: ${c.status} ${c.statusText}${f?` - ${f}`:""}`)}const u=await c.json();if(typeof u.error=="string"&&u.error.trim().length>0)throw new Error(`MCP tool ${e} failed: ${u.error}`);return u}o.warn("[HttpClient] token \u5237\u65B0\u5931\u8D25\u6216\u65E0\u65B0 token\uFF0C\u8FD4\u56DE\u539F\u59CB 401 \u9519\u8BEF")}if(!n.ok){if(Date.now()<s&&this.isRetryableHttpStatus(n.status)){await this.delayForRetry(s,e,t);continue}const a=typeof n.text=="function"?p(await n.text().catch(()=>"")):"";throw new Error(`MCP tool ${e} call failed: ${n.status} ${n.statusText}${a?` - ${a}`:""}`)}const i=await n.json();if(typeof i.error=="string"&&i.error.trim().length>0)throw new Error(`MCP tool ${e} failed: ${i.error}`);return i}}async fetchRuntimeFeatures(){await this.ensureRuntimeAccessToken();const e=this.mcpHttpUrl.replace(/\/mcp\/call(\/)?$/,"/mcp/features$1");let r;try{r=await fetch(e,{method:"POST",headers:this.buildRequestHeaders(),body:JSON.stringify({})})}catch(t){throw o.warn("[HttpClient] \u67E5\u8BE2\u80FD\u529B\u5F00\u5173\u8BF7\u6C42\u5931\u8D25: %s",t instanceof Error?t.message:String(t)),new Error(`fetch runtime features failed: ${t instanceof Error?t.message:String(t)}`)}if(!r.ok)throw o.warn("[HttpClient] \u67E5\u8BE2\u80FD\u529B\u5F00\u5173\u5931\u8D25: status=%s, statusText=%s",r.status,r.statusText),new Error(`fetch runtime features failed: ${r.status} ${r.statusText}`);const s=await r.json();return!s||typeof s.features!="object"||s.features===null?{}:s.features}async callToolOnce(e,r,s=$){await this.ensureRuntimeAccessToken(),o.info("[HttpClient] callToolOnce \u5F00\u59CB: tool=%s, timeoutMs=%d, url=%s, agentId=%s",e,s,this.mcpHttpUrl,String(r?.agentId??"")),e==="poll_message"&&h("http.callToolOnce.start",`tool=${e} timeoutMs=${s} preemptiveJoinWaitMs=${String(r?.preemptiveJoinWaitMs??"-")}`);const t=c=>fetch(this.mcpHttpUrl,{method:"POST",headers:this.buildRequestHeaders(),body:JSON.stringify({tool:e,arguments:r}),signal:c}),n=Date.now();let i=await this.singleFetchWithTimeout(t,s,e);if(o.info("[HttpClient] callToolOnce \u6536\u5230\u54CD\u5E94: tool=%s, status=%d, \u8017\u65F6=%dms",e,i.status,Date.now()-n),e==="poll_message"&&h("http.callToolOnce.response",`status=${i.status} elapsedMs=${Date.now()-n}`),i.status===401&&(o.warn(`[HttpClient] MCP Tool ${e} \u8FD4\u56DE 401\uFF0C\u5C1D\u8BD5\u5411 bridge \u5237\u65B0 token`),await this.tryRefreshToken(r)&&(i=await this.singleFetchWithTimeout(t,s,e),o.info("[HttpClient] callToolOnce token \u5237\u65B0\u540E\u91CD\u8BD5\u6536\u5230\u54CD\u5E94: tool=%s, status=%d, \u7D2F\u8BA1\u8017\u65F6=%dms",e,i.status,Date.now()-n))),!i.ok){const c=typeof i.text=="function"?p(await this.readTextWithTimeout(i,s,e).catch(()=>"")):"";throw o.info("[HttpClient] callToolOnce \u975E 2xx \u54CD\u5E94: tool=%s, status=%d, body=%s",e,i.status,c||"(\u7A7A)"),new Error(`MCP tool ${e} call failed: ${i.status} ${i.statusText}${c?` - ${c}`:""}`)}const a=await this.parseJsonWithTimeout(i,s,e);if(o.info("[HttpClient] callToolOnce \u5B8C\u6210: tool=%s, \u603B\u8017\u65F6=%dms, error=%s",e,Date.now()-n,typeof a.error=="string"?a.error:"(\u65E0)"),e==="poll_message"){const c=Array.isArray(a.messages)?a.messages:[];h("http.callToolOnce.parsed",`totalElapsedMs=${Date.now()-n} serverMessages=${c.length} `+JSON.stringify(c.map(u=>({msgId:u.msgId,channel:u.channel,sender:u.senderId}))))}if(typeof a.error=="string"&&a.error.trim().length>0)throw new Error(`MCP tool ${e} failed: ${a.error}`);return a}async readTextWithTimeout(e,r,s){if(r<=0)return await e.text();let t;try{return await Promise.race([e.text(),new Promise((n,i)=>{t=setTimeout(()=>i(new Error(`MCP tool ${s} timed out after ${r}ms`)),r)})])}finally{t!==void 0&&clearTimeout(t)}}async parseJsonWithTimeout(e,r,s){if(r<=0)return await e.json();let t;try{return await Promise.race([e.json(),new Promise((n,i)=>{t=setTimeout(()=>i(new Error(`MCP tool ${s} timed out after ${r}ms`)),r)})])}finally{t!==void 0&&clearTimeout(t)}}async singleFetchWithTimeout(e,r,s){const t=new AbortController;let n;r>0&&(n=setTimeout(()=>t.abort(),r));try{return await e(t.signal)}catch(i){throw t.signal.aborted?(s==="poll_message"&&h("http.callToolOnce.timeout",`timeoutMs=${r} \u670D\u52A1\u7AEF\u53EF\u80FD\u4ECD\u5728\u6267\u884C\u540C\u4E00\u8BF7\u6C42\uFF08Callable \u5360\u7EBF\u81F3\u9884\u7B97\u7ED3\u675F\uFF09`),new Error(`MCP tool ${s} timed out after ${r}ms`)):i}finally{n!==void 0&&clearTimeout(n)}}async executeToolRequest(e,r){return await this.fetchWithTimeout(this.mcpHttpUrl,{method:"POST",headers:this.buildRequestHeaders(),body:JSON.stringify({tool:e,arguments:r})},`MCP tool ${e}`)}async fetchWithTimeout(e,r,s){const t=this.resolveRequestTimeoutMs(),n=new AbortController,i=setTimeout(()=>n.abort(),t);try{return await fetch(e,{...r,signal:n.signal})}catch(a){throw n.signal.aborted?new Error(`${s} timed out after ${t}ms`):a}finally{clearTimeout(i)}}resolveRequestTimeoutMs(){const e=this.serverConfig.mcpHttpRequestTimeoutMs;return typeof e=="number"&&Number.isFinite(e)&&e>0?e:w}resolveRetryIntervalMs(){const e=this.serverConfig.mcpRetryIntervalMs;return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:g}resolveRetryMaxAccumulatedMs(){const e=this.serverConfig.mcpRetryMaxAccumulatedMs;return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:T}isTransientError(e){if(!(e instanceof Error))return!1;const r=e.message;return!!(/timed out after \d+ms/.test(r)||/fetch failed/i.test(r)||/network/i.test(r)||/ECONNREFUSED/i.test(r)||/ECONNRESET/i.test(r))}isRetryableHttpStatus(e){return e>=500||e===429}async delayForRetry(e,r,s){const t=e-Date.now(),n=Math.min(this.resolveRetryIntervalMs(),Math.max(0,t));o.warn(`[HttpClient] MCP tool ${r} \u8BF7\u6C42\u5931\u8D25\uFF0C${n}ms \u540E\u91CD\u8BD5 (\u7B2C${s}\u6B21)`),n>0&&await new Promise(i=>setTimeout(i,n))}buildRequestHeaders(){const e={"Content-Type":"application/json"};return this.serverConfig.runtimeAccessToken&&(e["X-Runtime-Token"]=this.serverConfig.runtimeAccessToken,e.Authorization=`Bearer ${this.serverConfig.runtimeAccessToken}`),e}async ensureRuntimeAccessToken(){if(this.serverConfig.runtimeAccessToken||!this.serverConfig.runtimeBridgeBaseUrl){o.info("[HttpClient] ensureRuntimeAccessToken: tokenLen=%d, bridgeBaseUrl=%s",(this.serverConfig.runtimeAccessToken||"").length,this.serverConfig.runtimeBridgeBaseUrl||"(\u7A7A)");return}throw new Error("runtimeAccessToken is required; MCP nodes must claim a session token from launch binding")}async tryRefreshToken(e){if(this.tokenRefreshPromise)return this.tokenRefreshPromise;this.tokenRefreshPromise=this.doRefreshToken(e);try{return await this.tokenRefreshPromise}finally{this.tokenRefreshPromise=null}}async doRefreshToken(e){const r=this.serverConfig.runtimeBridgeBaseUrl;if(!r)return o.warn("[HttpClient] \u65E0 runtimeBridgeBaseUrl\uFF0C\u65E0\u6CD5\u5237\u65B0 token"),!1;const s=String(e?.agentId||"").trim();if(!s)return o.warn("[HttpClient] \u65E0 agentId\uFF0C\u65E0\u6CD5\u5237\u65B0 token"),!1;try{const t=await fetch(`${r}/runtime/binding/refresh-token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({agentId:s,currentToken:this.serverConfig.runtimeAccessToken||""})});if(!t.ok)return o.warn(`[HttpClient] bridge refresh-token \u8FD4\u56DE ${t.status}\uFF0C\u65E0\u6CD5\u5237\u65B0`),!1;const i=(await t.json()).runtimeAccessToken;return i?i===this.serverConfig.runtimeAccessToken?!1:(this.serverConfig.runtimeAccessToken=i,o.info("[HttpClient] runtimeAccessToken \u5DF2\u901A\u8FC7 bridge refresh \u66F4\u65B0"),!0):(o.warn("[HttpClient] bridge \u672A\u8FD4\u56DE\u65B0 token"),!1)}catch(t){return o.warn("[HttpClient] \u5237\u65B0 token \u5931\u8D25: %s",t instanceof Error?t.message:String(t)),t instanceof Error&&t.stack&&o.warn("[HttpClient] \u5237\u65B0 token \u5F02\u5E38\u5806\u6808:",t.stack),!1}}async refreshRuntimeAccessToken(e){return this.tryRefreshToken({agentId:e})}resolveMcpHttpUrl(){const e=this.serverConfig.mcpHttpUrl;if(e&&e.trim().length>0){const s=m(e);if(s)return s}const r=m(this.serverConfig.serverUrl,{fromAgentWebSocketUrl:!0});return r||this.serverConfig.serverUrl}getMcpHttpUrl(){return this.mcpHttpUrl}}export{H as HttpClient,R as normalizeServerHttpBase};
|
|
2
2
|
|
|
@@ -150,6 +150,8 @@ export declare class McpServer {
|
|
|
150
150
|
|
|
151
151
|
private searchChildMemoriesByFileLocal;
|
|
152
152
|
|
|
153
|
+
private searchPeerMemoriesByFileLocal;
|
|
154
|
+
|
|
153
155
|
private collectOwnMemoriesByFile;
|
|
154
156
|
|
|
155
157
|
private handleAbandonMemoryUpdate;
|
|
@@ -161,6 +163,12 @@ export declare class McpServer {
|
|
|
161
163
|
private fetchRecentMessages;
|
|
162
164
|
private handleSendGroup;
|
|
163
165
|
|
|
166
|
+
private uploadAttachmentFiles;
|
|
167
|
+
|
|
168
|
+
private uploadFileRequest;
|
|
169
|
+
|
|
170
|
+
private mergeContentWithAttachmentMarkers;
|
|
171
|
+
|
|
164
172
|
private recordMessageTokenUsage;
|
|
165
173
|
private handleHireColleague;
|
|
166
174
|
private handleHireColleaguesBatch;
|
|
@@ -1,49 +1,52 @@
|
|
|
1
|
-
import N from"node:fs";import M from"node:path";import{Server as
|
|
2
|
-
${
|
|
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}}constructor(){this.agentClient=new Z,this.messageBuffer=new ne,this.initialRoleName=S.resolveRoleMemoryDirectoryName(),this.hasRoleName=!!process.env.AWS_ROLE_NAME;const e=S.resolveMemoryStorePaths();this.memoryStore=new le(this.agentClient),this.roleMemoryStore=new D(e.rolePath),this.sessionContextMemoryStore=new D(M.join(M.dirname(e.rolePath),"..","session_context")),this.isSubAgent=process.env.AWS_SUB_AGENT==="true",this.contextManager=new oe(this.sessionContextMemoryStore),this.server=new J({name:ee,version:te},{capabilities:{tools:{}}}),this.setupHandlers()}setupHandlers(){this.server.setRequestHandler(X,async()=>{let e=this.isSubAgent?F.filter(t=>W.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=>!x.has(t.name))),{tools:e}}),this.server.setRequestHandler(V,async(e,t)=>{const{name:r,arguments:n}=e.params;try{const s=await this.handleToolCall(r,n,t?.signal);return{content:this.buildToolResultContent(s)}}catch(s){const i=s instanceof Error?s.message:String(s),a=s instanceof ae?{error:i,...s.details}:{error:i};return o.error("[McpServer] \u5DE5\u5177\u8C03\u7528\u5F02\u5E38: tool=%s, error=%s, stack=%s",r,i,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 n=t?._aws_sub_agent===!0,s=t?._aws_silent_poll===!0,i=t?._aws_force_inject===!0,a={...t};delete a._aws_sub_agent,delete a._aws_silent_poll,delete a._aws_force_inject;const l=n?null:this.agentClient.getStatusReporter();l&&!s&&this.safeReportStatus(()=>l.reportToolUse(e,this.sanitizeToolUseArgs(e,a)));try{const m=await this.executeToolCall(e,a,{forceInject:i,signal:r});if(l&&!s){const u=this.stripAutoDelegateForReporting(m);u!==null&&(this.safeReportStatus(()=>l.reportToolResult(u)),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&&!W.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(x.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[S.LAUNCH_ITEM_FEATURE_KEY]===!0:process.env[S.LAUNCH_TOOLS_ENV_KEY]==="1"}async isHireToolsEnabled(){const{features:e,ok:t}=await this.fetchRuntimeFeaturesWithStatus();return t?e[S.HIRE_FEATURE_KEY]===!0:process.env[S.HIRE_TOOLS_ENV_KEY]==="1"}async fetchRuntimeFeaturesWithStatus(){const e=Date.now();if(this.featuresCache&&e-this.featuresCache.fetchedAt<S.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(n){o.warn("[McpServer] \u83B7\u53D6\u80FD\u529B\u5F00\u5173\u5931\u8D25\uFF0C\u6309\u542F\u52A8\u671F env \u515C\u5E95: %s",n instanceof Error?n.message:String(n))}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=M.resolve(e);for(;;){if(N.existsSync(M.join(t,".agentswork")))return M.join(t,".agentswork");const r=M.dirname(t);if(r===t)break;t=r}return M.join(M.resolve(e),".agentswork")}static sanitizeRoleDirectoryName(e){return String(e||"").trim().split("").map(r=>me.has(r)||r.charCodeAt(0)<32?"_":r).join("").replace(/^\.+|\.+$/g,"").trim()||"default-role"}static resolveRoleMemoryDirectoryName(){return S.sanitizeRoleDirectoryName(process.env.AWS_ROLE_NAME||"")}static buildRoleMemoryStorePath(e){const t=process.env.AWS_WORKSPACE_PATH||process.cwd(),r=S.findAgentsworkDirSync(t);return M.join(r,"memory","memory",S.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=S.findAgentsworkDirSync(t),n=String(process.env.AWS_INSTANCE_MEMORY_STORE_PATH||"").trim()||M.join(r,"memory","server-managed"),s=String(process.env.AWS_ROLE_MEMORY_STORE_PATH||"").trim()||M.join(r,"memory","memory",S.resolveRoleMemoryDirectoryName());return{instancePath:n,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(n=>String(n)):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 S.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(!S.MEMORY_TOOL_NAMES.has(e))return t;const r={},n=this.getOptionalString(t,"uri"),s=this.getOptionalString(t,"memory_type"),i=this.getOptionalNumber(t,"limit");return n&&(r.uri=n),s&&(r.memory_type=s),typeof i=="number"&&(r.limit=i),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:[],n=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&&n.length===0?null:{...t,directMessages:a}}async handleCreateMemory(e){const t=this.normalizeBoundFiles(this.getOptionalStringArray(e,"bound_files"));await this.validateBoundFilesExist(t);let r,n;if(t&&t.length>0){r={};for(const a of t){const l=await this.calculateFileMd5(a);l&&(r[a]=l)}n=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:n},i=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(i)}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",n=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:n,keywords:this.getOptionalStringArray(e,"keywords"),bound_files:this.normalizeBoundFiles(this.getOptionalStringArray(e,"bound_files"))},i=await this.findMemoryStoreForMutation(s),a=await i.store.readMemory({uri:s.uri,memory_type:i.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,u;if(l&&l.length>0){m={};for(const d of l){const _=await this.calculateFileMd5(d);_&&(m[d]=_)}u=new Date().toISOString()}const h=await i.store.updateMemory({...s,memory_type:i.memory_type??s.memory_type,file_md5_map:m,last_check_time:u});if(i.memory_type==="project_memory"&&this.backupProjectMemoryToLocal({...s,memory_type:"project_memory",file_md5_map:m,last_check_time:u}).catch(d=>{o.warn("[McpServer] \u5907\u4EFD project_memory \u66F4\u65B0\u5230\u672C\u5730\u5931\u8D25:",d)}),await this.reportMemoryStatsToServer(),i.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(d){o.warn("[McpServer] \u91CA\u653E memory claim \u5931\u8D25: uri=%s, error=%s",s.uri,d instanceof Error?d.message:String(d))}return this.toMemoryWriteResult(h)}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 n=0;const s=[],i=[];for(let a=0;a<r.length;a++){const l=r[a];if(typeof l!="object"||l===null){i.push({uri:String(l),reason:`memories[${a}] \u4E0D\u662F\u5BF9\u8C61`});continue}const m=l,u=typeof m.uri=="string"?m.uri:"";if(!u){i.push({uri:"",reason:`memories[${a}].uri \u7F3A\u5931`});continue}const h=typeof m.memory_type=="string"?this.parseMemoryType(m.memory_type):void 0;try{await this.deleteMemorySingle(u,h,!0)?n++:s.push(u)}catch(d){i.push({uri:u,reason:d instanceof Error?d.message:String(d)})}}return n>0&&await this.reportMemoryStatsToServer(),{deleted:n,not_found:s,failed:i}}async deleteMemorySingle(e,t,r=!1){const n={uri:e,memory_type:t},s=await this.findMemoryStoreForMutation(n),i=s.memory_type??n.memory_type,a=await s.store.deleteMemory({...n,memory_type:i});return a&&(i==="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",n=this.getOptionalString(e,"keyword_mode"),s=n==="all"?"all":n==="any"?"any":void 0,i={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(i);const a=await this.searchOwnMemories(i);if(r==="own")return a;const l=await this.memoryStore.searchMemory({...i,scope:"children"});return this.mergeSearchResults(a,l,i.limit)}async searchOwnMemories(e){return await this.memoryStore.searchMemory(e)}mergeSearchResults(e,t,r){const n=new Set,s=typeof r=="number"&&r>0?r:10,i=[...e.results,...t.results].filter(a=>{const l=a.uri;return n.has(l)?!1:(n.add(l),!0)}).sort((a,l)=>l.updatedAt.localeCompare(a.updatedAt)).slice(0,s);return{query:e.query||t.query,results:i}}async handleListMemories(e){const t=this.getRequiredString(e,"memory_type");if(t==="project_memory"||t==="session_context")throw new Error(`Invalid memory_type: ${t}`);return await this.memoryStore.listByType(t)}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),n=this.getOptionalMemoryType(e),s=this.getOptionalString(e,"scope"),i=s==="own"||s==="children"?s:"all",a=async()=>await this.memoryStore.listByFile(r,{memory_type:n,scope:"children"}).catch(()=>[]);if(i==="children"){const d=await a();return{file_path:r,count:d.length,memories:d.map(_=>this.toMemoryRecordWithMetadata(_))}}const l=await this.collectOwnMemoriesByFile(r,n);if(i==="own")return{file_path:r,count:l.length,memories:l.map(d=>this.toMemoryRecordWithMetadata(d))};const m=await a(),u=new Set(l.map(d=>d.id)),h=[...l];for(const d of m)u.has(d.id)||(h.push(d),u.add(d.id));return h.sort((d,_)=>_.updatedAt.localeCompare(d.updatedAt)),{file_path:r,count:h.length,memories:h.map(d=>this.toMemoryRecordWithMetadata(d))}}mergeIdDedupe(e,t){const r=new Set;for(const s of e)s.id&&r.add(s.id);const n=[...e];for(const s of t)s.id&&!r.has(s.id)&&(n.push(s),r.add(s.id));return n.sort((s,i)=>i.updatedAt.localeCompare(s.updatedAt)),n}async searchChildMemoriesByFileLocal(e,t){const r=process.env.AWS_WORKSPACE_PATH||process.cwd(),n=this.normalizeBoundFilePath(e),i=(n.startsWith("./")?n.substring(2):n).split("/"),a=[],l=new Set,{access:m,readdir:u,readFile:h}=await import("node:fs/promises");for(let d=i.length-1;d>=1;d--){const _=i.slice(0,d),f="./"+i.slice(d).join("/"),y=M.join(r,..._);if(y===r)continue;const c=M.join(y,".agentswork");try{await m(c)}catch{continue}const g=M.join(c,"memory","memory");let T;try{T=(await u(g,{withFileTypes:!0})).filter(w=>w.isDirectory()).map(w=>w.name)}catch{continue}for(const R of T){const w=M.join(g,R);let k;try{k=await u(w)}catch{continue}for(const p of k){if(!p.endsWith(".json"))continue;const b=M.join(w,p);let E;try{E=await h(b,"utf-8")}catch{continue}let C;try{C=JSON.parse(E)}catch{continue}if(C.by_uri)for(const[$,A]of Object.entries(C.by_uri)){if(!A)continue;const B=A.id||$;l.has(B)||t&&A.memory_type!==t||A.bound_files&&A.bound_files.length>0&&A.bound_files.some(z=>this.normalizeBoundFilePath(z)===f)&&(l.add(B),a.push({...A,uri:A.uri||$}))}}}}return a.sort((d,_)=>_.updatedAt.localeCompare(d.updatedAt)),a}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),n=await this.memoryStore.readMemory({uri:t,memory_type:r});return n?.bound_files&&n.bound_files.length>0&&await this.validateBoundFilesExist(n.bound_files),await this.memoryStore.releaseMemoryClaim(t),n?.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 u=new Date(l.expiresAt||l.createdAt||0).getTime(),h=new Date(m.expiresAt||m.createdAt||0).getTime();return u-h}).slice(0,t),i=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:i,totalExpired:r.length,message:i>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 ${i} \u6761\u5F85\u5904\u7406\u3002
|
|
1
|
+
import N from"node:fs";import M 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 a}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 A=Number.parseInt(process.env.AWS_MCP_FILE_CHANGE_RENOTIFY_COOLDOWN_MS||"",10);return Number.isFinite(A)&&A>0?A:30*6e4})(),G=500,de=new Set(["<",">",":",'"',"/","\\","|","?","*"]),Y=20*1024*1024,he={".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(A){return he[M.extname(A).toLowerCase()]||"application/octet-stream"}function ge(A){return(A||"").replace(/[|[\]\r\n]/g,"_").trim()||"\u6587\u4EF6"}function fe(A){if(!Number.isFinite(A)||A<=0)return"0 B";const e=["B","KB","MB","GB"],t=Math.min(e.length-1,Math.floor(Math.log(A)/Math.log(1024)));return`${Number.parseFloat((A/1024**t).toFixed(2))} ${e[t]}`}function ye(A){return`[\u6587\u4EF6: ${ge(A.name)} | ${A.url} | ${A.mediaType||"application/octet-stream"} | ${fe(A.size)}]`}class w{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;static MEETING_HYDRATE_RETRY_COUNT=3;static MEETING_HYDRATE_RETRY_DELAY_MS=150;static MEETING_HYDRATE_TIMEOUT_REARM_DELAY_MS=1e4;meetingHydrateTimeoutRearmDelayMs=w.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(a.info(`[McpServer] syncRoleMemoryStore \u88AB\u8C03\u7528: displayName=${e.displayName}, roleName="${e.roleName??"(\u7A7A)"}", id=${e.id}`),!e.roleName){a.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=w.sanitizeRoleDirectoryName(e.roleName);this.hasRoleName=!0,t!==this.initialRoleName&&(a.info(`[McpServer] \u89D2\u8272\u76EE\u5F55\u4E0E\u521D\u59CB\u503C\u4E0D\u4E00\u81F4\uFF0C\u91CD\u5EFA roleMemoryStore: "${this.initialRoleName}" -> "${t}"`),this.roleMemoryStore=new L(w.buildRoleMemoryStorePath(t)),this.initialRoleName=t)}maybeSyncPermanentMemoryToServer(){this.doMaybeSyncPermanentMemoryToServer().catch(e=>{a.warn("[McpServer] maybeSyncPermanentMemoryToServer \u5F02\u5E38: %s, stack=%s",e instanceof Error?e.message:String(e),e instanceof Error?e.stack:"(no stack)")})}async doMaybeSyncPermanentMemoryToServer(){a.info("[McpServer] maybeSyncPermanentMemoryToServer \u5F00\u59CB\uFF0CinitialRoleName="+this.initialRoleName);let e;try{e=await this.memoryStore.getStats()}catch(n){a.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;a.info(`[McpServer] server memory \u8BA1\u6570=${t}`);let r=[];try{r=await this.roleMemoryStore.listByType("project_memory"),a.info(`[McpServer] \u89D2\u8272\u5B50\u76EE\u5F55\u8BFB\u53D6\u5230 ${r.length} \u6761\u6C38\u4E45\u8BB0\u5FC6`)}catch(n){a.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=M.dirname(w.buildRoleMemoryStorePath(this.initialRoleName));a.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&&(a.info(`[McpServer] \u4ECE\u9057\u7559\u76EE\u5F55\u8BFB\u53D6\u5230 ${l.length} \u6761\u6C38\u4E45\u8BB0\u5FC6`),r=l)}catch(o){a.warn("[McpServer] \u8BFB\u53D6\u9057\u7559\u76EE\u5F55\u6C38\u4E45\u8BB0\u5FC6\u5931\u8D25:",o instanceof Error?o.message:o)}}if(r.length===0){a.info("[McpServer] \u672C\u5730\u4E5F\u65E0\u6C38\u4E45\u8BB0\u5FC6\uFF0C\u8DF3\u8FC7\u540C\u6B65");return}if(t>=r.length){a.info(`[McpServer] \u670D\u52A1\u7AEF\u5DF2\u6709 ${t} \u6761 >= \u672C\u5730 ${r.length} \u6761\uFF0C\u65E0\u9700\u56DE\u586B`);return}a.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++,a.info(`[McpServer] \u540C\u6B65\u6C38\u4E45\u8BB0\u5FC6\u6210\u529F: ${n.uri}`)}catch(o){const l=o instanceof Error?o.message:String(o);l.includes("already exists")||l.includes("Memory already exists")||a.warn(`[McpServer] \u540C\u6B65\u6C38\u4E45\u8BB0\u5FC6\u5931\u8D25 (${n.uri}): ${l}`),s++}a.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=M.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
|
+
${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=w.resolveRoleMemoryDirectoryName(),this.hasRoleName=!!process.env.AWS_ROLE_NAME;const e=w.resolveMemoryStorePaths();this.memoryStore=new me(this.agentClient),this.roleMemoryStore=new L(e.rolePath),this.sessionContextMemoryStore=new L(M.join(M.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),o=s instanceof ce?{error:n,...s.details}:{error:n};return a.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(o,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,o={...t};delete o._aws_sub_agent,delete o._aws_silent_poll,delete o._aws_force_inject;const l=i?null:this.agentClient.getStatusReporter();l&&!s&&this.safeReportStatus(()=>l.reportToolUse(e,this.sanitizeToolUseArgs(e,o)));try{const m=await this.executeToolCall(e,o,{forceInject:n,signal:r});if(l&&!s){const u=this.stripAutoDelegateForReporting(m);u!==null&&(this.safeReportStatus(()=>l.reportToolResult(u)),this.safeReportStatus(()=>l.reportThinking()))}return m}catch(m){throw l&&!s&&this.safeReportStatus(()=>l.reportToolError(m)),m}}safeReportStatus(e){try{e()}catch(t){a.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 / 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[w.LAUNCH_ITEM_FEATURE_KEY]===!0:process.env[w.LAUNCH_TOOLS_ENV_KEY]==="1"}async isHireToolsEnabled(){const{features:e,ok:t}=await this.fetchRuntimeFeaturesWithStatus();return t?e[w.HIRE_FEATURE_KEY]===!0:process.env[w.HIRE_TOOLS_ENV_KEY]==="1"}async fetchRuntimeFeaturesWithStatus(){const e=Date.now();if(this.featuresCache&&e-this.featuresCache.fetchedAt<w.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){a.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=M.resolve(e);for(;;){if(N.existsSync(M.join(t,".agentswork")))return M.join(t,".agentswork");const r=M.dirname(t);if(r===t)break;t=r}return M.join(M.resolve(e),".agentswork")}static sanitizeRoleDirectoryName(e){return String(e||"").trim().split("").map(r=>de.has(r)||r.charCodeAt(0)<32?"_":r).join("").replace(/^\.+|\.+$/g,"").trim()||"default-role"}static resolveRoleMemoryDirectoryName(){return w.sanitizeRoleDirectoryName(process.env.AWS_ROLE_NAME||"")}static buildRoleMemoryStorePath(e){const t=process.env.AWS_WORKSPACE_PATH||process.cwd(),r=w.findAgentsworkDirSync(t);return M.join(r,"memory","memory",w.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=w.findAgentsworkDirSync(t),i=String(process.env.AWS_INSTANCE_MEMORY_STORE_PATH||"").trim()||M.join(r,"memory","server-managed"),s=String(process.env.AWS_ROLE_MEMORY_STORE_PATH||"").trim()||M.join(r,"memory","memory",w.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 w.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){a.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){a.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){a.warn("[McpServer] \u4E0A\u62A5 memory \u7EDF\u8BA1\u5931\u8D25:",t)}}sanitizeToolUseArgs(e,t){if(!w.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 o=r.filter(l=>!s(l));return o.length===0&&i.length===0?null:{...t,directMessages:o}}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 o of t){const l=await this.calculateFileMd5(o);l&&(r[o]=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(o=>{a.warn("[McpServer] \u5907\u4EFD project_memory \u5230\u672C\u5730\u5931\u8D25:",o)}),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),o=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):o?.bound_files&&o.bound_files.length>0&&await this.validateBoundFilesExist(o.bound_files);const l=s.bound_files??o?.bound_files;let m,u;if(l&&l.length>0){m={};for(const h of l){const y=await this.calculateFileMd5(h);y&&(m[h]=y)}u=new Date().toISOString()}const d=await n.store.updateMemory({...s,memory_type:n.memory_type??s.memory_type,file_md5_map:m,last_check_time:u});if(n.memory_type==="project_memory"&&this.backupProjectMemoryToLocal({...s,memory_type:"project_memory",file_md5_map:m,last_check_time:u}).catch(h=>{a.warn("[McpServer] \u5907\u4EFD project_memory \u66F4\u65B0\u5230\u672C\u5730\u5931\u8D25:",h)}),await this.reportMemoryStatsToServer(),n.memory_type==="project_memory"&&o?.memory_status==="updating")try{await this.memoryStore.releaseMemoryClaim(s.uri),this.activeLeaseUris.delete(s.uri),this.activeLeaseUris.size===0&&this.stopLeaseRenewal()}catch(h){a.warn("[McpServer] \u91CA\u653E memory claim \u5931\u8D25: uri=%s, error=%s",s.uri,h instanceof Error?h.message:String(h))}return this.toMemoryWriteResult(d)}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 o=this.getOptionalMemoryType(e);return{deleted:await this.deleteMemorySingle(t,o)}}let i=0;const s=[],n=[];for(let o=0;o<r.length;o++){const l=r[o];if(typeof l!="object"||l===null){n.push({uri:String(l),reason:`memories[${o}] \u4E0D\u662F\u5BF9\u8C61`});continue}const m=l,u=typeof m.uri=="string"?m.uri:"";if(!u){n.push({uri:"",reason:`memories[${o}].uri \u7F3A\u5931`});continue}const d=typeof m.memory_type=="string"?this.parseMemoryType(m.memory_type):void 0;try{await this.deleteMemorySingle(u,d,!0)?i++:s.push(u)}catch(h){n.push({uri:u,reason:h instanceof Error?h.message:String(h)})}}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,o=await s.store.deleteMemory({...i,memory_type:n});return o&&(n==="project_memory"&&this.removeProjectMemoryLocalBackup(e).catch(l=>{a.warn("[McpServer] \u5220\u9664 project_memory \u672C\u5730\u5907\u4EFD\u5931\u8D25:",l)}),r||await this.reportMemoryStatsToServer()),o}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 o=await this.searchOwnMemories(n);if(r==="own")return o;const l=await this.memoryStore.searchMemory({...n,scope:"children"});return this.mergeSearchResults(o,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(o=>{const l=o.uri;return i.has(l)?!1:(i.add(l),!0)}).sort((o,l)=>l.updatedAt.localeCompare(o.updatedAt)).slice(0,s);return{query:e.query||t.query,results:n}}async handleListMemories(e){const t=this.getRequiredString(e,"memory_type");if(t==="project_memory"||t==="session_context")throw new Error(`Invalid memory_type: ${t}`);return await this.memoryStore.listByType(t)}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",o=async()=>await this.memoryStore.listByFile(r,{memory_type:i,scope:"children"}).catch(()=>[]);if(n==="children"){const h=await o();return{file_path:r,count:h.length,memories:h.map(y=>this.toMemoryRecordWithMetadata(y))}}if(n==="own"){const h=await this.collectOwnMemoriesByFile(r,i);return{file_path:r,count:h.length,memories:h.map(y=>this.toMemoryRecordWithMetadata(y))}}const[l,m,u]=await Promise.all([this.memoryStore.listByFile(r,{memory_type:i,scope:"all"}).catch(()=>[]),this.searchChildMemoriesByFileLocal(r,i).catch(()=>[]),this.searchPeerMemoriesByFileLocal(r,i).catch(()=>[])]),d=this.mergeIdDedupe(this.mergeIdDedupe(l,m),u);return{file_path:r,count:d.length,memories:d.map(h=>this.toMemoryRecordWithMetadata(h))}}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("/"),o=[],l=new Set,{access:m,readdir:u,readFile:d}=await import("node:fs/promises");for(let h=n.length-1;h>=1;h--){const y=n.slice(0,h),g="./"+n.slice(h).join("/"),_=M.join(r,...y);if(_===r)continue;const c=M.join(_,".agentswork");try{await m(c)}catch{continue}const p=M.join(c,"memory","memory");let T;try{T=(await u(p,{withFileTypes:!0})).filter(S=>S.isDirectory()).map(S=>S.name)}catch{continue}for(const v of T){const S=M.join(p,v);let C;try{C=await u(S)}catch{continue}for(const f of C){if(!f.endsWith(".json"))continue;const I=M.join(S,f);let b;try{b=await d(I,"utf-8")}catch{continue}let k;try{k=JSON.parse(b)}catch{continue}if(k.by_uri)for(const[P,$]of Object.entries(k.by_uri)){if(!$)continue;const B=$.id||P;l.has(B)||t&&$.memory_type!==t||$.bound_files&&$.bound_files.length>0&&$.bound_files.some(J=>this.normalizeBoundFilePath(J)===g)&&(l.add(B),o.push({...$,uri:$.uri||P}))}}}}return o.sort((h,y)=>String(y.updatedAt??"").localeCompare(String(h.updatedAt??""))),o}async searchPeerMemoriesByFileLocal(e,t){if(!this.hasRoleName||!this.initialRoleName)return[];const r=process.env.AWS_WORKSPACE_PATH||process.cwd(),i=this.normalizeBoundFilePath(e),s=M.join(r,".agentswork","memory","memory"),{access:n,readdir:o,readFile:l}=await import("node:fs/promises");try{await n(s)}catch{return[]}let m;try{m=(await o(s,{withFileTypes:!0})).filter(y=>y.isDirectory()).map(y=>y.name)}catch{return[]}const u=[],d=new Set;for(const h of m){if(h===this.initialRoleName)continue;const y=M.join(s,h);let R;try{R=await o(y)}catch{continue}for(const g of R){if(!g.endsWith(".json"))continue;let _;try{_=JSON.parse(await l(M.join(y,g),"utf-8"))}catch{continue}if(_.by_uri)for(const[c,p]of Object.entries(_.by_uri)){if(!p)continue;const T=p.id||c;d.has(T)||p.memory_type==="project_memory"&&(t&&p.memory_type!==t||p.bound_files&&p.bound_files.length>0&&p.bound_files.some(S=>this.normalizeBoundFilePath(S)===i)&&(d.add(T),u.push({...p,uri:p.uri||c,readonly:!0,source_role_name:h})))}}}return u.sort((h,y)=>String(y.updatedAt??"").localeCompare(String(h.updatedAt??""))),u}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=>{a.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){a.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 u=new Date(l.expiresAt||l.createdAt||0).getTime(),d=new Date(m.expiresAt||m.createdAt||0).getTime();return u-d}).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
|
-
\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(n){o.warn("[McpServer] \u6E05\u7406\u56DE\u5FC6\u4E2D\u8BB0\u5FC6\u5931\u8D25: %s",n instanceof Error?n.message:String(n))}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((n,s)=>new Date(n.timestamp).getTime()-new Date(s.timestamp).getTime()),r}async handleSendGroup(e){if(!e.content||typeof e.content!="string")throw new Error("content is required");return this.recordMessageTokenUsage(e.content).catch(t=>o.warn("[McpServer] Failed to record token usage",t)),await this.agentClient.sendGroupMessage(e.content,e.projectId,e.roomId)}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");if(!e.content||typeof e.content!="string")throw new Error("content is required");return this.recordMessageTokenUsage(e.content).catch(t=>o.warn("[McpServer] Failed to record token usage",t)),await this.agentClient.sendDirectMessage(e.targetId,e.content,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"),v("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),v("poll.resolved",`elapsedMs=${Date.now()-t} dm=${P(r?.directMessages)} gm=${P(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)),v("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"),v("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();const r=await this.buildBackgroundTaskNotification(),n=await this.confirmServerMessages(this.messageBuffer.get());if(n.directMessages.length>0||n.groupMessages.length>0)return e?.aborted?(this.messageBuffer.requeue(n),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&&n.directMessages.unshift(r),this.buildPollResult(n));if(r)return this.buildPollResult({directMessages:[r],groupMessages:[]});const s=await this.checkAllLocalNonUrgentNotifications();if(s.length>0)return this.buildPollResult({directMessages:s,groupMessages:[]});let i=!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"),v("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(!i){const g=this.agentClient.getStatusReporter();if(g){const T=g.getCurrentStatus();T.status==="tool_using"&&T.actionDetail!=null&&T.actionDetail.includes("poll_message")||g.reportToolUse("poll_message",{}),i=!0}}const m=await this.confirmServerMessages(await this.messageBuffer.poll(ce));if(l++,v("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 g=await this.confirmServerMessages(this.messageBuffer.get());if(g.directMessages.length>0||g.groupMessages.length>0)return e?.aborted?(this.messageBuffer.requeue(g),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",g.directMessages.length+g.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",g.directMessages.length),this.buildPollResult(g))}a++;let h=!1;if(this.urgentMeetingHydrateRequested&&(this.urgentMeetingHydrateRequested=!1,a=j,h=!0),a<j)continue;a=0;const d=await this.buildTodoBlockNotification();if(d)return this.buildPollResult({directMessages:[d],groupMessages:[]});let _=!1;const I=h?S.MEETING_HYDRATE_RETRY_COUNT:1;for(let g=1;g<=I;g++){o.info("[McpServer] %s hydrate poll_message\uFF0C\u7B2C %d/%d \u6B21",h?"\u4F1A\u8BAE\u9080\u8BF7\u5F3A\u5236":"\u666E\u901A",g,I);const T=this.messageBuffer.size();if(h&&T>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",T);break}const R={blockIfEmpty:!1,includePipelineTasks:!0,pollMessageTimeoutMs:h?S.MEETING_HYDRATE_POLL_TIMEOUT_MS:void 0,skipGroupMessages:h,preemptiveJoinWaitMs:h?S.MEETING_PREEMPTIVE_JOIN_WAIT_MS:0,propagatePollTimeout:h},w=Date.now(),k=await this.hydrateUnreadMessagesFromServer(R);if(h&&v("poll.forced-hydrate-outcome",`\u7B2C ${g}/${I} \u6B21\u5F3A\u5236 hydrate \u5B8C\u6210\uFF08\u8017\u65F6 ${Date.now()-w}ms\uFF09: timedOut=${k.timedOut} failed=${k.failed} \u7F13\u51B2\u533A=${this.messageBuffer.size()} \u6761`),k.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",g,I),_=!0;break}const p=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",g,I,p),p>0||!h)break;g<I&&await new Promise(b=>setTimeout(b,S.MEETING_HYDRATE_RETRY_DELAY_MS))}_&&(v("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 f=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 y=await this.confirmServerMessages(this.messageBuffer.get());if(y.directMessages.length>0||y.groupMessages.length>0)return e?.aborted?(this.messageBuffer.requeue(y),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",y.directMessages.length+y.groupMessages.length),this.buildPollResult({directMessages:[],groupMessages:[]})):(f&&y.directMessages.unshift(f),this.buildPollResult(y));if(h&&!f&&!_&&(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"),v("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),f)return this.buildPollResult({directMessages:[f],groupMessages:[]});const c=await this.checkAllLocalNonUrgentNotifications(!1);if(c.length>0)return this.buildPollResult({directMessages:c,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 n=await this.buildMemoryCleanupNotification();return n&&t.push(n),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:[]}}parsePositiveIntegerEnv(e,t){const r=process.env[e];if(!r||!r.trim())return t;const n=Number.parseInt(r,10);return!Number.isFinite(n)||n<=0?(o.warn(`[McpServer] ${e} \u65E0\u6548\uFF0C\u4F7F\u7528\u9ED8\u8BA4\u503C ${t}ms`),t):n}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,u])=>({memoryType:a,domain:m,domainStats:u})):[]);if(t.length===0&&r.length===0)return null;const n=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`),i=["\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${[...n,...s].join("\uFF1B")}\u3002${i}\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"),n=e.filter(s=>!r.includes(s));if(r.length>0){const s=r.slice(0,5).map(i=>i.uri).join(`
|
|
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){a.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=>a.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=M.resolve(t),i=this.agentClient.getServerConfig(),s=te(i.serverUrl,{fromAgentWebSocketUrl:!0})||"",n=i.runtimeAccessToken||"",o=[];for(const l of e){if(typeof l!="string"||!l.trim())throw new Error("attachments \u4E2D\u5B58\u5728\u7A7A\u8DEF\u5F84");const m=M.resolve(r,l);let u;try{u=await N.promises.stat(m)}catch{throw new Error(`\u9644\u4EF6\u6587\u4EF6\u4E0D\u5B58\u5728: ${l}\uFF08\u89E3\u6790\u4E3A ${m}\uFF09`)}if(!u.isFile())throw new Error(`\u9644\u4EF6\u4E0D\u662F\u666E\u901A\u6587\u4EF6: ${l}`);if(u.size>Y)throw new Error(`\u9644\u4EF6\u6587\u4EF6\u8FC7\u5927\uFF08\u4E0A\u9650 ${Math.floor(Y/1024/1024)}MB\uFF09: ${l}`);const d=M.basename(m),h=pe(m),y=new FormData;y.append("file",new Blob([await N.promises.readFile(m)],{type:h}),d);const R=await this.uploadFileRequest(`${s}/api/files/upload`,y,n,d);if(!R.ok){const _=await R.text().catch(()=>"");throw new Error(`\u9644\u4EF6\u4E0A\u4F20\u5931\u8D25 (HTTP ${R.status}): ${d}${_?` - ${_.slice(0,200)}`:""}`)}const g=await R.json();if(!g?.url)throw new Error(`\u9644\u4EF6\u4E0A\u4F20\u54CD\u5E94\u7F3A\u5C11 url: ${d}`);o.push({name:g.name||d,url:g.url.startsWith("http")?g.url:`${s}${g.url}`,mediaType:g.mediaType||h,size:typeof g.size=="number"?g.size:u.size})}return o}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,o=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} - ${o}`)}}mergeContentWithAttachmentMarkers(e,t){if(t.length===0)return e;const r=t.map(ye).join(`
|
|
8
|
+
`);return e.trim()?`${e}
|
|
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=>a.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(a.info("[McpServer] handlePollMessage \u88AB\u8C03\u7528"),this.pendingPollMessage)return a.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 a.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 a.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(a.info("[McpServer] doPollMessage \u88AB\u8C03\u7528"),E("poll.enter","doPollMessage \u5165\u53E3"),e?.aborted)return a.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();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),a.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,o=0,l=0;for(;;){if(e?.aborted)return a.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 T=p.getCurrentStatus();T.status==="tool_using"&&T.actionDetail!=null&&T.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),a.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(a.debug("[McpServer] poll \u8D85\u65F6\uFF0C\u68C0\u67E5\u6D4F\u89C8\u5668\u76D1\u542C\u5668\u4E8B\u4EF6"),await this.hydrateBrowserListenerEvents()){if(e?.aborted)return a.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),a.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:[]})):(a.info("[McpServer] \u76D1\u542C\u5668\u4E8B\u4EF6\u5DF2\u6CE8\u5165\uFF0Cpoll_message \u8FD4\u56DE %d \u6761\u79C1\u4FE1",p.directMessages.length),this.buildPollResult(p))}o++;let d=!1;if(this.urgentMeetingHydrateRequested&&(this.urgentMeetingHydrateRequested=!1,o=j,d=!0),o<j)continue;o=0;const h=await this.buildTodoBlockNotification();if(h)return this.buildPollResult({directMessages:[h],groupMessages:[]});let y=!1;const R=d?w.MEETING_HYDRATE_RETRY_COUNT:1;for(let p=1;p<=R;p++){a.info("[McpServer] %s hydrate poll_message\uFF0C\u7B2C %d/%d \u6B21",d?"\u4F1A\u8BAE\u9080\u8BF7\u5F3A\u5236":"\u666E\u901A",p,R);const T=this.messageBuffer.size();if(d&&T>0){a.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",T);break}const v={blockIfEmpty:!1,includePipelineTasks:!0,pollMessageTimeoutMs:d?w.MEETING_HYDRATE_POLL_TIMEOUT_MS:void 0,skipGroupMessages:d,preemptiveJoinWaitMs:d?w.MEETING_PREEMPTIVE_JOIN_WAIT_MS:0,propagatePollTimeout:d},S=Date.now(),C=await this.hydrateUnreadMessagesFromServer(v);if(d&&E("poll.forced-hydrate-outcome",`\u7B2C ${p}/${R} \u6B21\u5F3A\u5236 hydrate \u5B8C\u6210\uFF08\u8017\u65F6 ${Date.now()-S}ms\uFF09: timedOut=${C.timedOut} failed=${C.failed} \u7F13\u51B2\u533A=${this.messageBuffer.size()} \u6761`),C.timedOut){a.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,R),y=!0;break}const f=this.messageBuffer.size();if(a.info("[McpServer] hydrate poll_message \u5B8C\u6210\uFF0C\u7B2C %d/%d \u6B21\uFF0C\u7F13\u51B2\u533A\u6D88\u606F\u6570=%d",p,R,f),f>0||!d)break;p<R&&await new Promise(I=>setTimeout(I,w.MEETING_HYDRATE_RETRY_DELAY_MS))}y&&(E("poll.forced-hydrate-rearm",`\u5F3A\u5236 hydrate \u8D85\u65F6\uFF0C${this.meetingHydrateTimeoutRearmDelayMs}ms \u540E\u91CD\u65B0\u7F6E\u4F4D\u5524\u9192\u6807\u8BB0`),setTimeout(()=>{a.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 g=await this.buildBackgroundTaskNotification();if(e?.aborted)return a.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 _=await this.confirmServerMessages(this.messageBuffer.get());if(_.directMessages.length>0||_.groupMessages.length>0)return e?.aborted?(this.messageBuffer.requeue(_),a.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",_.directMessages.length+_.groupMessages.length),this.buildPollResult({directMessages:[],groupMessages:[]})):(g&&_.directMessages.unshift(g),this.buildPollResult(_));if(d&&!g&&!y&&(a.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"),o=j-1),g)return this.buildPollResult({directMessages:[g],groupMessages:[]});const c=await this.checkAllLocalNonUrgentNotifications(!1);if(c.length>0)return this.buildPollResult({directMessages:c,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 a.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:[]}}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?(a.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(([,o])=>o.listable&&o.exceeded),r=Object.entries(e.by_type).flatMap(([o,l])=>l.listable?Object.entries(l.by_domain).filter(([,m])=>m.exceeded).map(([m,u])=>({memoryType:o,domain:m,domainStats:u})):[]);if(t.length===0&&r.length===0)return null;const i=t.map(([o,l])=>`${o} \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:o,domain:l,domainStats:m})=>`${o}/${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(o=>`${o.memoryType}/${o.domain}`)}}}catch(e){return a.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(`
|
|
8
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
|
|
9
12
|
|
|
10
13
|
\u5F85\u758F\u7406\u8BB0\u5FC6\uFF1A
|
|
11
14
|
${s}${r.length>5?`
|
|
12
|
-
...\u53CA\u5176\u4ED6 ${r.length-5} \u6761`:""}`,requireReply:!1,timestamp:new Date().toISOString(),_acodeAutoDelegate:{type:"memory_expiration",uris:r.map(
|
|
13
|
-
`);return{msgId:`memory-recurrence-${Date.now()}`,senderId:"MCP-System",senderName:"\u7CFB\u7EDF",receiverId:t,content:`\u6709 ${
|
|
15
|
+
...\u53CA\u5176\u4ED6 ${r.length-5} \u6761`:""}`,requireReply:!1,timestamp:new Date().toISOString(),_acodeAutoDelegate:{type:"memory_expiration",uris:r.map(n=>n.uri)}}}if(i.length>0){const s=i.slice(0,5).map(n=>n.uri).join(`
|
|
16
|
+
`);return{msgId:`memory-recurrence-${Date.now()}`,senderId:"MCP-System",senderName:"\u7CFB\u7EDF",receiverId:t,content:`\u6709 ${i.length} \u6761\u5373\u5C06\u9057\u5FD8\u7684\u8BB0\u5FC6\u5F97\u6574\u7406\uFF0C\u8BF7\u4F7F\u7528 memory_recurrence(limit=10) \u5206\u6279\u5904\u7406\uFF08\u6700\u65E9\u8FC7\u671F\u4F18\u5148\uFF0C\u6BCF\u6B21 10 \u6761\uFF09\u3002
|
|
14
17
|
|
|
15
18
|
\u5373\u5C06\u9057\u5FD8\u7684\u8BB0\u5FC6\uFF1A
|
|
16
|
-
${s}${
|
|
17
|
-
...\u53CA\u5176\u4ED6 ${
|
|
18
|
-
`);return{msgId:`memory-file-change-${Date.now()}`,senderId:"MCP-System",senderName:"\u7CFB\u7EDF",receiverId:e,content:`\u68C0\u6D4B\u5230\u4EE5\u4E0B ${
|
|
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 a.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(a.info(`[McpServer] buildMemoryFileChangeNotification \u88AB\u8C03\u7528: hasRoleName=${this.hasRoleName}, agentId=${this.getCurrentAgentId()??"(\u7A7A)"}`),!this.hasRoleName)return a.info("[McpServer] \u6587\u4EF6\u53D8\u66F4\u68C0\u6D4B\u8DF3\u8FC7: hasRoleName=false"),null;try{const e=this.getCurrentAgentId();if(!e)return a.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 b of c){const k=r.find(P=>P.id===b.memoryId);k&&await this.memoryStore.updateMemory({uri:k.uri,memory_type:"project_memory",memory_status:"updating",updating_agent_id:e,file_md5_map:k.file_md5_map,last_check_time:k.last_check_time,bound_files:k.bound_files})}const f=Math.min(c.length,5),I=c.slice(0,5).map(b=>`- ${b.memoryUri} (\u6587\u4EF6: ${b.changedFiles.join(", ")})`).join(`
|
|
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
|
|
19
22
|
|
|
20
|
-
${
|
|
23
|
+
${I}
|
|
21
24
|
|
|
22
|
-
\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(
|
|
23
|
-
`);return
|
|
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(b=>b.memoryUri),fileChanges:c.slice(0,5).map(b=>{const k=r.find(P=>P.id===b.memoryId);return{uri:b.memoryUri,boundFiles:k?.bound_files??[],fileStatuses:b.fileStatuses,changedFiles:b.changedFiles}})}}}const p=r,T=new Map;for(const f of p.slice(0,5))T.set(f.uri,await this.computeBoundFileStatuses(f));const v=p.filter(f=>{const I=T.get(f.uri);return!I||I.length===0?!1:I.some(b=>b.status==="content_changed"||b.status==="not_found")}),S=p.filter(f=>!v.includes(f));if(S.length>0){a.info(`[McpServer] \u6587\u4EF6\u53D8\u66F4\u68C0\u6D4B Step1: ${S.length} \u4E2A updating memory \u7ED1\u5B9A\u6587\u4EF6\u65E0\u771F\u5B9E\u53D8\u66F4\uFF0C\u81EA\u52A8\u91CA\u653E: ${S.map(f=>f.uri).join(", ")}`);for(const f of S)try{await this.memoryStore.releaseMemoryClaim(f.uri),this.activeLeaseUris.delete(f.uri),await this.memoryStore.updateMemory({uri:f.uri,memory_type:"project_memory"})}catch(I){a.info(`[McpServer] \u81EA\u52A8\u91CA\u653E stale updating memory \u5931\u8D25: ${f.uri}`,I)}this.activeLeaseUris.size===0&&this.stopLeaseRenewal()}if(v.length===0)return a.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 C=v.slice(0,5).map(f=>`- ${f.uri} (\u6587\u4EF6: ${f.bound_files?.join(", ")||"\u672A\u77E5"})`).join(`
|
|
26
|
+
`);return a.info(`[McpServer] \u6587\u4EF6\u53D8\u66F4\u68C0\u6D4B Step1: ${v.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
|
|
24
27
|
|
|
25
|
-
${
|
|
28
|
+
${C}
|
|
26
29
|
|
|
27
|
-
\u8BF7\u7EE7\u7EED\u5B8C\u6210\u66F4\u65B0\u5DE5\u4F5C\u3002`,requireReply:!1,timestamp:new Date().toISOString(),_acodeAutoDelegate:{type:"memory_file_change",uris:
|
|
30
|
+
\u8BF7\u7EE7\u7EED\u5B8C\u6210\u66F4\u65B0\u5DE5\u4F5C\u3002`,requireReply:!1,timestamp:new Date().toISOString(),_acodeAutoDelegate:{type:"memory_file_change",uris:v.slice(0,5).map(f=>f.uri),fileChanges:v.slice(0,5).map(f=>({uri:f.uri,boundFiles:f.bound_files??[],fileStatuses:T.get(f.uri)??[]}))}}}const i=await this.memoryStore.listByType("recently_memory"),s=await this.memoryStore.listByType("agent_memory"),n=[...i,...s],o=n.filter(c=>c.bound_files&&c.bound_files.length>0);a.info(`[McpServer] \u6587\u4EF6\u53D8\u66F4\u68C0\u6D4B Step2: recently=${i.length}, agent=${s.length}, \u6709\u7ED1\u5B9A\u6587\u4EF6=${o.length}/${n.length}\u3002\u8BE6\u60C5: ${n.map(c=>`${c.uri}(bound=${c.bound_files?.length??0},md5=${Object.keys(c.file_md5_map??{}).length})`).join("; ")||"\u65E0 memory"}`);const l=new Map;for(const c of n)c.bound_files&&c.bound_files.length>0&&l.set(c.id,JSON.stringify(c.file_md5_map??{}));const m=this.filterFileChangesByRenotifyCooldown(await this.checkMemoriesFileChanges(n)),u=m;a.info(`[McpServer] \u6587\u4EF6\u53D8\u66F4\u68C0\u6D4B Step2: \u68C0\u6D4B\u5230\u53D8\u66F4=${m.length}`+(m.length>0?` \u53D8\u66F4\u9879: ${m.map(c=>`${c.memoryUri}(${c.changedFiles.join(",")})`).join("; ")}`:""));const d=n.filter(c=>{if(!c.bound_files||c.bound_files.length===0||m.some(v=>v.memoryId===c.id))return!1;const p=l.get(c.id),T=JSON.stringify(c.file_md5_map??{});return p!==T});if(d.length>0){a.info(`[McpServer] \u6587\u4EF6\u53D8\u66F4\u68C0\u6D4B Step2: \u56DE\u5199 ${d.length} \u4E2A listable memory \u7684\u4FEE\u6B63 MD5 map`);for(const c of d)try{await this.memoryStore.updateMemory({uri:c.uri,memory_type:c.memory_type,file_md5_map:c.file_md5_map,last_check_time:c.last_check_time})}catch(p){a.info(`[McpServer] \u56DE\u5199 listable MD5 map \u5931\u8D25: ${c.uri}`,p)}}if(u.length>0){const c=u.map(p=>`- ${p.memoryUri} (\u6587\u4EF6: ${p.changedFiles.join(", ")})`).join(`
|
|
28
31
|
`);return{msgId:`memory-file-change-${Date.now()}`,senderId:"MCP-System",senderName:"\u7CFB\u7EDF",receiverId:e,content:`\u68C0\u6D4B\u5230\u4EE5\u4E0B Memory \u7ED1\u5B9A\u7684\u6587\u4EF6\u5DF2\u53D8\u66F4\uFF0C\u8BF7\u53CA\u65F6\u66F4\u65B0\uFF1A
|
|
29
32
|
|
|
30
33
|
${c}
|
|
31
34
|
|
|
32
|
-
\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:u.map(
|
|
33
|
-
`);return{msgId:`memory-file-change-${Date.now()}`,senderId:"MCP-System",senderName:"\u7CFB\u7EDF",receiverId:e,content:`\u68C0\u6D4B\u5230\u4EE5\u4E0B ${
|
|
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:u.map(p=>p.memoryUri),fileChanges:u.map(p=>{const T=n.find(v=>v.id===p.memoryId);return{uri:p.memoryUri,boundFiles:T?.bound_files??[],fileStatuses:p.fileStatuses,changedFiles:p.changedFiles}})}}}const h=t.filter(c=>c.bound_files&&c.bound_files.length>0&&(c.memory_status==="normal"||!c.memory_status)&&!this.isClaimCached(c.uri)),y=t.filter(c=>c.bound_files&&c.bound_files.length>0);a.info(`[McpServer] \u6587\u4EF6\u53D8\u66F4\u68C0\u6D4B Step3: project_memory \u603B\u6570=${t.length}, \u6709\u7ED1\u5B9A\u6587\u4EF6=${y.length}, \u5F85\u68C0\u6D4B(\u8FC7\u6EE4updating/claimed\u540E)=${h.length}\u3002\u88AB\u8FC7\u6EE4\u539F\u56E0: ${y.length-h.length} \u9879(memory_status=updating \u6216 isClaimCached)`);const R=new Map;for(const c of h)R.set(c.id,JSON.stringify(c.file_md5_map??{}));const g=this.filterFileChangesByRenotifyCooldown(await this.checkMemoriesFileChanges(h)),_=h.filter(c=>{if(g.some(v=>v.memoryId===c.id))return!1;const p=R.get(c.id),T=JSON.stringify(c.file_md5_map??{});return p!==T&&c.file_md5_map&&Object.keys(c.file_md5_map).length>0});if(_.length>0){a.info(`[McpServer] \u6587\u4EF6\u53D8\u66F4\u68C0\u6D4B Step3: \u56DE\u5199 ${_.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 _)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(p){a.info(`[McpServer] \u56DE\u5199\u57FA\u7EBF MD5 \u5931\u8D25: ${c.uri}`,p)}}if(a.info(`[McpServer] \u6587\u4EF6\u53D8\u66F4\u68C0\u6D4B Step3: \u68C0\u6D4B\u5230\u53D8\u66F4=${g.length}`+(g.length>0?` \u53D8\u66F4\u9879: ${g.map(c=>`${c.memoryUri}(${c.changedFiles.join(",")})`).join("; ")}`:"")),g.length>0){const c=g.slice(0,5),p=c.map(S=>S.memoryUri);let T=!1,v=new Set;try{const S=await this.memoryStore.claimMemoryUpdate(p,w.LEASE_DURATION_MINUTES,"project_memory");v=new Set(S.claimed_uris??[]),T=!0}catch(S){a.info("[McpServer] Server claim API \u4E0D\u53EF\u7528\uFF0C\u964D\u7EA7\u5230\u672C\u5730\u76F4\u63A5\u6807\u8BB0:",S),v=new Set(p)}if(v.size>0){const S=c.filter(f=>v.has(f.memoryUri));for(const f of S){const I=t.find(b=>b.id===f.memoryId);I&&(await this.memoryStore.updateMemory({uri:I.uri,memory_type:"project_memory",memory_status:"updating",updating_agent_id:e,file_md5_map:I.file_md5_map,last_check_time:I.last_check_time,bound_files:I.bound_files}),this.activeLeaseUris.add(I.uri))}T&&v.size>0&&this.startLeaseRenewal();const C=S.map(f=>`- ${f.memoryUri} (\u6587\u4EF6: ${f.changedFiles.join(", ")})`).join(`
|
|
36
|
+
`);return{msgId:`memory-file-change-${Date.now()}`,senderId:"MCP-System",senderName:"\u7CFB\u7EDF",receiverId:e,content:`\u68C0\u6D4B\u5230\u4EE5\u4E0B ${S.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
|
|
34
37
|
|
|
35
|
-
${
|
|
38
|
+
${C}
|
|
36
39
|
|
|
37
|
-
\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:w.map(p=>p.memoryUri),fileChanges:w.map(p=>{const b=t.find(E=>E.id===p.memoryId);return{uri:p.memoryUri,boundFiles:b?.bound_files??[],fileStatuses:p.fileStatuses,changedFiles:p.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||{},n=process.env.AWS_WORKSPACE_PATH||process.cwd();for(const s of e.bound_files)try{const i=await this.calculateFileMd5(s);if(i===null){const l=M.resolve(n,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!==i?t.push({path:s,status:"content_changed",localMd5:i,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 n=0;for(const s of e){const i=this.fileChangeFingerprint(s),a=this.fileChangeNotifyHistory.get(i);if(a!==void 0&&t-a<G){n++;continue}this.fileChangeNotifyHistory.set(i,t),r.push(s)}if(n>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",n,G),this.fileChangeNotifyHistory.size>Y){const s=this.fileChangeNotifyHistory.size-Y;let i=0;for(const a of this.fileChangeNotifyHistory.keys()){if(i>=s)break;this.fileChangeNotifyHistory.delete(a),i++}}return r}async checkMemoriesFileChanges(e){const t=[];for(const r of e)if(!(!r.bound_files||r.bound_files.length===0))try{const n=[],s=[],i={},a=r.file_md5_map||{},l=process.env.AWS_WORKSPACE_PATH||process.cwd(),m=Object.keys(a).length===0;let u=!1;for(const h of r.bound_files)try{const d=await this.calculateFileMd5(h);if(d===null){const I=M.resolve(l,h);o.info(`[McpServer] MD5 \u8BA1\u7B97\u8FD4\u56DE null: ${h} -> ${I} (workspace=${l})`);const f=a[h];f?await this.verifyFileNotExist(I)?(s.push({path:h,status:"not_found",serverMd5:f}),n.push(`${h}\uFF08\u6587\u4EF6\u627E\u4E0D\u5230 Server: ${f}\uFF09`),r.bound_files&&(r.bound_files=r.bound_files.filter(c=>c!==h))):(o.info(`[McpServer] \u6587\u4EF6\u5B58\u5728\u4F46 MD5 \u8BA1\u7B97\u5931\u8D25\uFF08\u77AC\u6001\u9519\u8BEF\uFF09\uFF0C\u8DF3\u8FC7: ${h}`),s.push({path:h,status:"no_change"})):s.push({path:h,status:"no_change"});continue}i[h]=d;const _=a[h];_?_!==d?(o.info(`[McpServer] \u6587\u4EF6\u53D8\u66F4: ${h} old=${_} new=${d} (workspace=${l})`),s.push({path:h,status:"content_changed",localMd5:d,serverMd5:_}),n.push(`${h}\uFF08\u5185\u5BB9\u53D8\u66F4 \u672C\u5730: ${d} Server: ${_}\uFF09`)):s.push({path:h,status:"no_change"}):(s.push({path:h,status:"no_change"}),u=!0,o.info(`[McpServer] \u5EFA\u7ACB\u5355\u6587\u4EF6\u57FA\u7EBF: ${h} new=${d} (workspace=${l}, memory=${r.uri})`))}catch(d){o.info(`[McpServer] \u8BA1\u7B97\u6587\u4EF6 MD5 \u5931\u8D25: ${h}`,d),s.push({path:h,status:"no_change"})}if(m&&Object.keys(i).length>0){r.file_md5_map=i,r.last_check_time=new Date().toISOString();continue}u&&Object.keys(i).length>0&&(r.file_md5_map=i,r.last_check_time=new Date().toISOString()),n.length>0&&(t.push({memoryId:r.id,memoryUri:r.uri,fileStatuses:s,changedFiles:n}),r.last_check_time=new Date().toISOString())}catch(n){o.warn(`[McpServer] \u68C0\u67E5 Memory ${r.id} \u6587\u4EF6\u53D8\u66F4\u5931\u8D25:`,n)}return t}async calculateFileMd5(e){try{const{createReadStream:t}=await import("node:fs"),{createHash:r}=await import("node:crypto"),n=process.env.AWS_WORKSPACE_PATH||process.cwd(),s=M.resolve(n,e),i=M.resolve(n),a=M.resolve(s);return!a.startsWith(i+M.sep)&&a!==i?(o.warn(`[McpServer] calculateFileMd5: \u8DEF\u5F84\u9003\u9038\u88AB\u62D2\u7EDD: ${e}`),null):new Promise(l=>{const m=r("md5"),u=t(s);u.on("data",h=>m.update(h)),u.on("end",()=>l(m.digest("hex"))),u.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 N.promises.access(e,N.constants.F_OK),!1}catch{return!0}}async handleGetMessage(e=!1){if(e){const i=await this.confirmServerMessages(this.messageBuffer.takeForceDirectMessages());return this.buildPollResult(i)}const t=this.messageBuffer.size()>0;await this.hydrateUnreadMessagesFromServer();const r=await this.confirmServerMessages(this.messageBuffer.get()),n=r.directMessages.length>0||r.groupMessages.length>0,s=t||!n;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",n=e.directMessages.filter(l=>l._awsServerMessage&&l.msgId&&!r(l)),s=e.directMessages.filter(r),i=e.groupMessages.filter(l=>l._awsServerMessage&&l.msgId!==void 0),a=e.directMessages.filter(t);if(n.length===0&&s.length===0&&i.length===0&&a.length===0)return e;try{const l=Date.now();let m=null;if(n.length>0&&(v("confirm.dm-read.start",`mark_dm_read ${n.length} \u6761\uFF08\u6807\u51C6 callTool\uFF0C\u5E26\u91CD\u8BD5\u6700\u957F\u53EF\u8FBE 30s\uFF09`),m=await this.agentClient.markDmRead(n.map(f=>f.msgId)),v("confirm.dm-read.done",`\u8017\u65F6 ${Date.now()-l}ms\uFF0C\u53EF\u4EA4\u4ED8=${m.size}/${n.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(y=>({id:y.msgId,channel:y.channel})))),v("confirm.meeting-messages",`count=${s.length} msgs=${P(s)}\uFF08\u5F00\u59CB mark_meeting_read\uFF09`);const f=Date.now();await this.agentClient.markMeetingRead(s.map(y=>y.msgId)),v("confirm.meeting-messages.done",`mark_meeting_read \u5B8C\u6210\uFF0C\u8017\u65F6 ${Date.now()-f}ms`)}const u=new Set,h=new Map;for(const f of i){if(!f.roomId){u.add(f.msgId);continue}const y=h.get(f.roomId)||[];y.push(f.msgId),h.set(f.roomId,y)}for(const[f,y]of h){const c=await this.agentClient.markGroupRead(f,y);for(const g of c)u.add(g)}if(a.length>0){o.info("[McpServer][DEBUG-poll] \u786E\u8BA4\u4EA4\u4ED8\u901A\u77E5 %d \u6761: %s",a.length,JSON.stringify(a.map(y=>({id:y.msgId,channel:y.channel})))),v("confirm.notifications",`count=${a.length} msgs=${P(a)}\uFF08\u5F00\u59CB mark_notification_read\uFF09`);const f=Date.now();await this.agentClient.markNotificationRead(a.map(y=>y.msgId)),v("confirm.notifications.done",`mark_notification_read \u5B8C\u6210\uFF0C\u7D2F\u8BA1\u8017\u65F6 ${Date.now()-l}ms`)}const d=e.directMessages.filter(f=>t(f)||r(f)||!f._awsServerMessage||!f.msgId?!0:m?m.has(f.msgId):!0),_=e.groupMessages.filter(f=>!f._awsServerMessage||f.msgId===void 0?!0:u.has(f.msgId)),I=e.directMessages.length-d.length+e.groupMessages.length-_.length;I>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",I,e.directMessages.length-d.length,e.groupMessages.length-_.length);for(const f of d)delete f._awsServerMessage;for(const f of _)delete f._awsServerMessage;return{directMessages:d,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)),v("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(i){if(i instanceof Q)return v("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 i}if(t.directMessages.length===0&&t.groupMessages.length===0)return v("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(i=>!this.shouldBufferIncomingMessage(i)),n=t.directMessages.filter(i=>this.shouldBufferIncomingMessage(i));r.length>0&&v("hydrate.dropped-by-filter",`dropped=${P(r)}`);const s=t.groupMessages.filter(i=>this.shouldBufferIncomingMessage(i));return n.forEach(i=>{const a=i.channel;a!=="meeting_invite"&&a!=="notification"&&(i._awsServerMessage=!0),this.messageBuffer.push(i)}),s.forEach(i=>{i._awsServerMessage=!0,this.messageBuffer.push(i)}),o.info(`[McpServer] \u5DF2\u8865\u62C9\u672A\u8BFB\u6D88\u606F\uFF0C\u79C1\u804A: ${n.length}\uFF0C\u7FA4\u804A: ${s.length}`),v("hydrate.buffered",`dm=${P(n)} 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)"),v("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}}buildListenerEventNotification(e){try{const t=this.getCurrentAgentId(),r=e.browserId&&e.browserId!=="default"?`\u6D4F\u89C8\u5668[${e.browserId}]`:"\u6D4F\u89C8\u5668",n=e.selector?`\u5143\u7D20\u9009\u62E9\u5668: ${e.selector}
|
|
38
|
-
`:"",s=this.formatChangeType(e.changeType),
|
|
39
|
-
${
|
|
40
|
-
\u89E6\u53D1\u65F6\u95F4: ${
|
|
41
|
-
\u63D0\u793A\u8BCD: ${e.prompt}`;return{msgId:`browser-listener-${e.listenerId}-${e.triggeredAt}`,senderId:"MCP-BrowserListener",senderName:"\u6D4F\u89C8\u5668\u76D1\u542C\u5668",receiverId:t||void 0,content:
|
|
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:S.map(f=>f.memoryUri),fileChanges:S.map(f=>{const I=t.find(b=>b.id===f.memoryId);return{uri:f.memoryUri,boundFiles:I?.bound_files??[],fileStatuses:f.fileStatuses,changedFiles:f.changedFiles}})}}}}return a.info("[McpServer] \u6587\u4EF6\u53D8\u66F4\u68C0\u6D4B\u5B8C\u6210: \u65E0\u53D8\u66F4\u901A\u77E5\u4EA7\u751F"),null}catch(e){return a.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=M.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 o=r[s];o?o!==n?t.push({path:s,status:"content_changed",localMd5:n,serverMd5:o}):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),o=this.fileChangeNotifyHistory.get(n);if(o!==void 0&&t-o<z){i++;continue}this.fileChangeNotifyHistory.set(n,t),r.push(s)}if(i>0&&a.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 o of this.fileChangeNotifyHistory.keys()){if(n>=s)break;this.fileChangeNotifyHistory.delete(o),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={},o=r.file_md5_map||{},l=process.env.AWS_WORKSPACE_PATH||process.cwd(),m=Object.keys(o).length===0;let u=!1;for(const d of r.bound_files)try{const h=await this.calculateFileMd5(d);if(h===null){const R=M.resolve(l,d);a.info(`[McpServer] MD5 \u8BA1\u7B97\u8FD4\u56DE null: ${d} -> ${R} (workspace=${l})`);const g=o[d];g?await this.verifyFileNotExist(R)?(s.push({path:d,status:"not_found",serverMd5:g}),i.push(`${d}\uFF08\u6587\u4EF6\u627E\u4E0D\u5230 Server: ${g}\uFF09`),r.bound_files&&(r.bound_files=r.bound_files.filter(c=>c!==d))):(a.info(`[McpServer] \u6587\u4EF6\u5B58\u5728\u4F46 MD5 \u8BA1\u7B97\u5931\u8D25\uFF08\u77AC\u6001\u9519\u8BEF\uFF09\uFF0C\u8DF3\u8FC7: ${d}`),s.push({path:d,status:"no_change"})):s.push({path:d,status:"no_change"});continue}n[d]=h;const y=o[d];y?y!==h?(a.info(`[McpServer] \u6587\u4EF6\u53D8\u66F4: ${d} old=${y} new=${h} (workspace=${l})`),s.push({path:d,status:"content_changed",localMd5:h,serverMd5:y}),i.push(`${d}\uFF08\u5185\u5BB9\u53D8\u66F4 \u672C\u5730: ${h} Server: ${y}\uFF09`)):s.push({path:d,status:"no_change"}):(s.push({path:d,status:"no_change"}),u=!0,a.info(`[McpServer] \u5EFA\u7ACB\u5355\u6587\u4EF6\u57FA\u7EBF: ${d} new=${h} (workspace=${l}, memory=${r.uri})`))}catch(h){a.info(`[McpServer] \u8BA1\u7B97\u6587\u4EF6 MD5 \u5931\u8D25: ${d}`,h),s.push({path:d,status:"no_change"})}if(m&&Object.keys(n).length>0){r.file_md5_map=n,r.last_check_time=new Date().toISOString();continue}u&&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){a.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=M.resolve(i,e),n=M.resolve(i),o=M.resolve(s);return!o.startsWith(n+M.sep)&&o!==n?(a.warn(`[McpServer] calculateFileMd5: \u8DEF\u5F84\u9003\u9038\u88AB\u62D2\u7EDD: ${e}`),null):new Promise(l=>{const m=r("md5"),u=t(s);u.on("data",d=>m.update(d)),u.on("end",()=>l(m.digest("hex"))),u.on("error",()=>l(null))})}catch(t){return a.info(`[McpServer] \u8BA1\u7B97\u6587\u4EF6 MD5 \u5931\u8D25: ${e}`,t),null}}async verifyFileNotExist(e){try{return await N.promises.access(e,N.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),o=e.directMessages.filter(t);if(i.length===0&&s.length===0&&n.length===0&&o.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(g=>g.msgId)),E("confirm.dm-read.done",`\u8017\u65F6 ${Date.now()-l}ms\uFF0C\u53EF\u4EA4\u4ED8=${m.size}/${i.length}`)),s.length>0){a.info("[McpServer][DEBUG-poll] \u786E\u8BA4\u4EA4\u4ED8\u4F1A\u8BAE\u6D88\u606F %d \u6761: %s",s.length,JSON.stringify(s.map(_=>({id:_.msgId,channel:_.channel})))),E("confirm.meeting-messages",`count=${s.length} msgs=${O(s)}\uFF08\u5F00\u59CB mark_meeting_read\uFF09`);const g=Date.now();await this.agentClient.markMeetingRead(s.map(_=>_.msgId)),E("confirm.meeting-messages.done",`mark_meeting_read \u5B8C\u6210\uFF0C\u8017\u65F6 ${Date.now()-g}ms`)}const u=new Set,d=new Map;for(const g of n){if(!g.roomId){u.add(g.msgId);continue}const _=d.get(g.roomId)||[];_.push(g.msgId),d.set(g.roomId,_)}for(const[g,_]of d){const c=await this.agentClient.markGroupRead(g,_);for(const p of c)u.add(p)}if(o.length>0){a.info("[McpServer][DEBUG-poll] \u786E\u8BA4\u4EA4\u4ED8\u901A\u77E5 %d \u6761: %s",o.length,JSON.stringify(o.map(_=>({id:_.msgId,channel:_.channel})))),E("confirm.notifications",`count=${o.length} msgs=${O(o)}\uFF08\u5F00\u59CB mark_notification_read\uFF09`);const g=Date.now();await this.agentClient.markNotificationRead(o.map(_=>_.msgId)),E("confirm.notifications.done",`mark_notification_read \u5B8C\u6210\uFF0C\u7D2F\u8BA1\u8017\u65F6 ${Date.now()-l}ms`)}const h=e.directMessages.filter(g=>t(g)||r(g)||!g._awsServerMessage||!g.msgId?!0:m?m.has(g.msgId):!0),y=e.groupMessages.filter(g=>!g._awsServerMessage||g.msgId===void 0?!0:u.has(g.msgId)),R=e.directMessages.length-h.length+e.groupMessages.length-y.length;R>0&&a.info("[McpServer] \u4EA4\u4ED8\u786E\u8BA4\uFF1A\u4E22\u5F03\u5DF2\u64A4\u56DE\u6D88\u606F %d \u6761\uFF08\u79C1\u4FE1 %d / \u7FA4\u804A %d\uFF09",R,e.directMessages.length-h.length,e.groupMessages.length-y.length);for(const g of h)delete g._awsServerMessage;for(const g of y)delete g._awsServerMessage;return{directMessages:h,groupMessages:y}}catch(l){a.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 o=n.channel;o!=="meeting_invite"&&o!=="notification"&&(n._awsServerMessage=!0),this.messageBuffer.push(n)}),s.forEach(n=>{n._awsServerMessage=!0,this.messageBuffer.push(n)}),a.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 a.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;a.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 a.warn("[McpServer] \u62C9\u53D6\u6D4F\u89C8\u5668\u76D1\u542C\u5668\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
|
+
`:"",s=this.formatChangeType(e.changeType),n=new Date(e.triggeredAt).toISOString(),o=`\u3010\u6D4F\u89C8\u5668\u76D1\u542C\u5668\u89E6\u53D1 | ${r} | URL: ${e.url}\u3011
|
|
42
|
+
${i}\u53D8\u5316\u7C7B\u578B: ${s}
|
|
43
|
+
\u89E6\u53D1\u65F6\u95F4: ${n}
|
|
44
|
+
\u63D0\u793A\u8BCD: ${e.prompt}`;return{msgId:`browser-listener-${e.listenerId}-${e.triggeredAt}`,senderId:"MCP-BrowserListener",senderName:"\u6D4F\u89C8\u5668\u76D1\u542C\u5668",receiverId:t||void 0,content:o,requireReply:!1,role:"system",timestamp:n}}catch{return null}}formatChangeType(e){switch(e){case"added":return"\u65B0\u589E";case"removed":return"\u5220\u9664";case"changed":return"\u6539\u53D8";case"exists":return"\u5B58\u5728";default:return"\u6539\u53D8"}}async handleGetDmHistory(e){return await this.agentClient.getDmHistory(e.targetUserId,e.limit,e.since)}async handleGetGroupHistory(e){return await this.agentClient.getGroupHistory(e.limit,e.roomId,e.since)}async handleSubmitTaskResult(e){if(!e.nodeId||typeof e.nodeId!="string")throw new Error("nodeId is required");if(!e.outputPayload||typeof e.outputPayload!="string")throw new Error("outputPayload is required");const t=Array.isArray(e.changeLog)?e.changeLog:void 0;return await this.agentClient.submitTaskResult(e.nodeId,e.outputPayload,t)}async handleStartTaskRollback(e){const t={rollbackTaskId:this.getRequiredString(e,"rollbackTaskId")};return await this.agentClient.startTaskRollback(t)}async handleFinishTaskRollback(e){const t={rollbackTaskId:this.getRequiredString(e,"rollbackTaskId"),resultMessage:this.getOptionalString(e,"resultMessage")};return await this.agentClient.finishTaskRollback(t)}async handleRejectTask(e){if(!e.nodeId||typeof e.nodeId!="string")throw new Error("nodeId is required");if(!e.reason||typeof e.reason!="string")throw new Error("reason is required");return await this.agentClient.rejectTask(e.nodeId,e.reason)}async handleTerminateTask(e){if(!e.taskInstanceId||typeof e.taskInstanceId!="string")throw new Error("taskInstanceId is required");if(!e.reason||typeof e.reason!="string")throw new Error("reason is required");return await this.agentClient.terminateTask(e.taskInstanceId,e.reason)}async handleIncomingMessage(e){if(!this.shouldBufferIncomingMessage(e)){!this.isGroupMessage(e)&&this.isPipelineTaskAssignedNotification(e)&&(a.info("[McpServer] \u6536\u5230 pipeline_task_assigned \u5524\u9192\u4FE1\u53F7\uFF0C\u7ACB\u5373\u5524\u9192 poll \u8D70 hydrate \u91CD\u67E5"),this.messageBuffer.wakeUpWaiters());return}a.info(`[McpServer] \u6536\u5230\u6D88\u606F: ${e.content?.substring(0,50)||"(\u65E0\u5185\u5BB9)"}`);const t=e.channel;t!=="meeting_invite"&&t!=="notification"&&(e._awsServerMessage=!0),this.messageBuffer.push(e),!this.isGroupMessage(e)&&e.force===!0&&this.agentClient.notifyBridgeForceMessage().catch(()=>{})}handleSystemNotify(e){const t=e?.type;if(typeof t!="string"||t!=="meeting_invite"&&t!=="meeting_creator_prompt")return;const r=this.parseNotificationPayload(e.payload);a.info("[McpServer] \u6536\u5230\u4F1A\u8BAE\u57DF\u7CFB\u7EDF\u901A\u77E5(type=%s, competitive=%s, meetingId=%s)\uFF0C\u5524\u9192 poll \u89E6\u53D1\u5F3A\u5236 hydrate",t,r?.competitive===!0?"true(\u89D2\u8272\u5E2D\u4F4D)":"false(\u76F4\u63A5\u6307\u540D)",typeof r?.meetingId=="string"?r.meetingId:typeof e.meetingId=="string"?e.meetingId:"unknown"),this.urgentMeetingHydrateRequested=!0,this.messageBuffer.wakeUpWaiters(),E("systemNotify.meeting-domain",`type=${t} \u5DF2\u7F6E\u4F4D\u5F3A\u5236 hydrate \u5E76\u5524\u9192 poll`)}parseNotificationPayload(e){if(e&&typeof e=="object")return e;if(!(typeof e!="string"||e.length===0))try{const t=JSON.parse(e);return t&&typeof t=="object"?t:void 0}catch{return}}shouldBufferIncomingMessage(e){return!e||typeof e!="object"?(a.warn("[McpServer] \u5FFD\u7565\u7ED3\u6784\u5F02\u5E38\u7684\u6D88\u606F\uFF0C\u907F\u514D\u7F13\u51B2\u533A\u6C61\u67D3"),!1):this.isSelfSentMessage(e)?(a.info("[McpServer] \u5FFD\u7565\u5F53\u524D Agent \u81EA\u5DF1\u53D1\u9001\u7684\u6D88\u606F\uFF0C\u907F\u514D poll_message/get_message \u56DE\u73AF"),!1):this.isGroupMessage(e)?!0:this.isPipelineTaskAssignedNotification(e)?(a.info("[McpServer] \u5FFD\u7565\u6301\u4E45\u5316 pipeline_task_assigned \u79C1\u4FE1\uFF0C\u4EC5\u4F5C\u4E3A poll_message \u5524\u9192\u4FE1\u53F7\u5904\u7406"),!1):!0}isGroupMessage(e){return!!e&&typeof e=="object"&&typeof e.msgId=="number"}isPipelineTaskAssignedNotification(e){const t=typeof e.content=="string"?e.content:"",r=typeof e.prompt=="string"?e.prompt:"";return t.includes("pipeline_task_assigned")||r.includes("pipeline_task_assigned")}isSelfSentMessage(e){if(!e||typeof e!="object")return!1;const t=this.getCurrentAgentId();return!!t&&typeof e.senderId=="string"&&e.senderId===t}getCurrentAgentId(){const e=this.agentClient;return typeof e.getState!="function"?null:e.getState().agentId??null}sanitizeAgentIdForTodoFile(e){return String(e).replace(/[^a-zA-Z0-9_-]/g,"_")}async buildTodoBlockNotification(){const e=this.getCurrentAgentId();if(!e)return null;const t=M.join(U(),"todos",`${this.sanitizeAgentIdForTodoFile(e)}.json`);let r;try{r=await N.promises.readFile(t,"utf-8")}catch(o){return o?.code==="ENOENT"||a.warn("[McpServer] \u8BFB\u53D6 Todo \u6587\u4EF6\u5931\u8D25\uFF0C\u653E\u884C poll_message: %s",o instanceof Error?o.message:String(o)),null}let i;try{i=JSON.parse(r)}catch(o){return a.warn("[McpServer] \u89E3\u6790 Todo \u6587\u4EF6\u5931\u8D25\uFF0C\u653E\u884C poll_message: %s",o instanceof Error?o.message:String(o)),null}return(Array.isArray(i.todos)?i.todos:[]).filter(o=>o&&typeof o=="object"&&typeof o.content=="string"&&(o.status==="pending"||o.status==="in_progress"||o.status==="cancelled")).length===0?null:{msgId:`todo-block-${Date.now()}`,senderId:"MCP-System",senderName:"\u7CFB\u7EDF",receiverId:e,content:"\u5F53\u524D\u6709\u672A\u5904\u7406\u7684todo list\u4E0D\u80FD\u4F7F\u7528poll_message\u963B\u585E\u83B7\u53D6\u6D88\u606F",requireReply:!1,timestamp:new Date().toISOString()}}async buildBackgroundTaskNotification(){try{const e=this.getCurrentAgentId();if(!e)return null;const t=M.join(U(),"bg-tasks",this.sanitizeAgentIdForTodoFile(e),"state.json");let r;try{r=await N.promises.readFile(t,"utf-8")}catch(u){if(u?.code==="ENOENT")return null;throw u}const i=JSON.parse(r),s=Array.isArray(i.tasks)?i.tasks:[],n=s.filter(u=>u&&typeof u=="object"&&typeof u.taskId=="string"&&u.status!=="running"&&!u.notified);if(n.length===0)return null;const o=n.slice(0,5),l=o.map(u=>`[bg:${u.taskId}] ${u.status} (exitCode=${u.exitCode??"?"}) ${u.commandPreview??""}
|
|
42
45
|
lines=${u.outputLineCount??0} bytes=${u.outputBytes??0}
|
|
43
46
|
Use read_background_output(task_id="${u.taskId}", mode="tail", lines=50) for full output.`).join(`
|
|
44
47
|
|
|
45
|
-
`),m=
|
|
48
|
+
`),m=n.length>o.length?`
|
|
46
49
|
|
|
47
|
-
\uFF08\u53E6\u6709 ${
|
|
48
|
-
${l}${m}`,requireReply:!1,timestamp:new Date().toISOString()}}catch(e){return
|
|
50
|
+
\uFF08\u53E6\u6709 ${n.length-o.length} \u6761\u5DF2\u5B8C\u6210\uFF0C\u8BF7\u7528 list_background_commands \u67E5\u770B\uFF09`:"";return await N.promises.writeFile(t,JSON.stringify({...i,updatedAt:Date.now(),tasks:s.map(u=>n.some(d=>d.taskId===u.taskId)?{...u,notified:!0}:u)},null,2),"utf-8").catch(u=>{a.warn("[McpServer] \u6807\u8BB0\u540E\u53F0\u4EFB\u52A1\u5DF2\u901A\u77E5\u5931\u8D25: %s",u?.message??u)}),{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 a.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(),a.info("[McpServer] MCP Server \u5DF2\u542F\u52A8\uFF0C\u7B49\u5F85\u8FDE\u63A5..."),a.info(`[McpServer] \u53EF\u7528\u5DE5\u5177: ${F.map(t=>t.name).join(", ")}`),a.info(`[McpServer] \u5DE5\u4F5C\u76EE\u5F55: ${process.env.AWS_WORKSPACE_PATH||process.cwd()}`),H&&a.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(),a.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(w.LEASE_DURATION_MINUTES)).renewed===0&&(a.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")?(a.info("[McpServer] \u5F53\u524D\u5B58\u50A8\u4E0D\u652F\u6301\u79DF\u7EA6\u7EED\u671F\uFF0C\u505C\u6B62\u7EED\u671F\u5B9A\u65F6\u5668"),this.stopLeaseRenewal()):a.warn("[McpServer] \u7EED\u671F\u79DF\u7EA6\u5931\u8D25: %s",t)}},w.LEASE_RENEW_INTERVAL_MS),a.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,a.info("[McpServer] \u79DF\u7EA6\u7EED\u671F\u5B9A\u65F6\u5668\u5DF2\u505C\u6B62"))}stop(){this.stopLeaseRenewal(),this.getCurrentAgentId()&&this.memoryStore.releaseAllMemoryClaims().catch(t=>a.warn("[McpServer] \u91CA\u653E claim \u5931\u8D25: %s",t instanceof Error?t.message:String(t))),this.agentClient.stop(),a.info("[McpServer] MCP Server \u5DF2\u505C\u6B62")}async autoRegister(){const e=this.agentClient.getAgentConfig();a.info(`[McpServer] \u89D2\u8272: "${e.roleName}"`),a.info(`[McpServer] AgentID: "${e.agentId||"(\u81EA\u52A8\u5206\u914D)"}"`),a.info("[McpServer] \u6B63\u5728\u8BF7\u6C42\u8C03\u5EA6\u4E2D\u5FC3\u6CE8\u518C...");let t=0;for(;;)try{const r=await this.agentClient.register();a.info(`[McpServer] \u6CE8\u518C\u6210\u529F: ${r.displayName} (${r.agentId})`),a.info(`[McpServer] \u72B6\u6001: ${r.status}`),this.startListeningInternal(),a.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){a.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(),a.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}`)}a.warn(`[McpServer] \u6CE8\u518C\u5931\u8D25\uFF0C\u7B49\u5F85\u91CD\u8BD5... (${t}/${D}): ${i}`),await this.delay(ie)}}autoRegisterInBackground(){this.autoRegister().catch(e=>{a.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(){a.info("[McpServer] startListeningInternal \u88AB\u8C03\u7528");const e=t=>{a.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()){a.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,a.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=>{a.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{w as McpServer};
|
|
49
52
|
|