aws-runtime-bridge 1.9.119 → 1.9.122
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/README.md +2 -0
- package/dist/adapter/AcodeSdkAdapter.d.ts +18 -0
- package/dist/adapter/AcodeSdkAdapter.js +5 -5
- package/dist/adapter/types.d.ts +4 -0
- package/dist/adapter/types.js +1 -1
- package/dist/browser/built-in-browser-tools.js +1 -1
- package/dist/desktop/built-in-desktop-tools.d.ts +49 -0
- package/dist/desktop/built-in-desktop-tools.js +2 -0
- package/dist/desktop/desktop-mcp-client.d.ts +47 -0
- package/dist/desktop/desktop-mcp-client.js +3 -0
- package/dist/index.js +1 -1
- package/dist/routes/dashboard.js +4 -4
- package/dist/routes/file-browser.js +1 -1
- package/dist/routes/git.d.ts +39 -0
- package/dist/routes/git.js +33 -25
- package/dist/routes/instance.js +1 -1
- package/dist/routes/jdks.d.ts +2 -0
- package/dist/routes/jdks.js +2 -0
- package/dist/routes/launch.d.ts +6 -0
- package/dist/routes/launch.js +30 -0
- package/dist/routes/terminal.js +30 -30
- package/dist/services/change-cache-retention.d.ts +5 -0
- package/dist/services/change-cache-retention.js +2 -0
- package/dist/services/desktop-mcp-manager.d.ts +47 -0
- package/dist/services/desktop-mcp-manager.js +2 -0
- package/dist/services/instance-features.d.ts +6 -0
- package/dist/services/instance-features.js +1 -1
- package/dist/services/jdk-scanner.d.ts +20 -0
- package/dist/services/jdk-scanner.js +2 -0
- package/dist/services/launch-manager.d.ts +181 -0
- package/dist/services/launch-manager.js +12 -0
- package/dist/services/launch-metrics.d.ts +89 -0
- package/dist/services/launch-metrics.js +4 -0
- package/dist/services/launch-streams.d.ts +24 -0
- package/dist/services/launch-streams.js +11 -0
- package/dist/services/mcp-launch-binding-queue.js +1 -1
- package/dist/services/panel-auth.d.ts +10 -0
- package/dist/services/panel-auth.js +1 -1
- package/dist/services/panel-env.d.ts +5 -0
- package/dist/services/panel-env.js +2 -0
- package/dist/services/port-detector.d.ts +3 -0
- package/dist/services/port-detector.js +6 -0
- package/dist/services/runtime-lifecycle-policy.d.ts +1 -0
- package/dist/services/runtime-lifecycle-policy.js +1 -1
- package/dist/services/tunnel-client.js +1 -1
- package/dist/services/workspace-files.d.ts +31 -0
- package/dist/services/workspace-files.js +1 -1
- package/dist/services/workspaceTaskChangeWatcher.d.ts +2 -0
- package/dist/services/workspaceTaskChangeWatcher.js +3 -3
- package/package/acode/dist/built-in-file-tools.d.ts +2 -0
- package/package/acode/dist/runtime.d.ts +20 -0
- package/package/acode/dist/runtime.js +27 -27
- package/package/acode/dist/sub-agent-manager.d.ts +4 -0
- package/package/acode/dist/sub-agent-manager.js +1 -1
- package/package/acode/dist/sub-agent-tools.d.ts +6 -0
- package/package/acode/dist/sub-agent-tools.js +39 -10
- package/package/acode/dist/sub-agent-types.d.ts +2 -0
- package/package/acode/dist/tool-allocation.d.ts +55 -0
- package/package/acode/dist/tool-allocation.js +2 -0
- package/package/acode/dist/types.d.ts +6 -0
- package/package/aws-client-agent-mcp/dist/agent-client.d.ts +24 -0
- package/package/aws-client-agent-mcp/dist/agent-client.js +1 -1
- package/package/aws-client-agent-mcp/dist/agent-client.test.js +19 -5
- package/package/aws-client-agent-mcp/dist/context-manager.test.js +6 -6
- package/package/aws-client-agent-mcp/dist/http-client.d.ts +2 -0
- package/package/aws-client-agent-mcp/dist/http-client.js +1 -1
- package/package/aws-client-agent-mcp/dist/index.js +1 -1
- package/package/aws-client-agent-mcp/dist/launch-config-tools.test.d.ts +1 -0
- package/package/aws-client-agent-mcp/dist/launch-config-tools.test.js +106 -0
- package/package/aws-client-agent-mcp/dist/logger.d.ts +4 -0
- package/package/aws-client-agent-mcp/dist/logger.js +2 -2
- package/package/aws-client-agent-mcp/dist/mcp-server.d.ts +21 -0
- package/package/aws-client-agent-mcp/dist/mcp-server.js +25 -25
- package/package/aws-client-agent-mcp/dist/mcp-server.test.js +24 -16
- package/package/aws-client-agent-mcp/dist/mcp-tools.d.ts +20 -0
- package/package/aws-client-agent-mcp/dist/mcp-tools.js +8 -8
- package/package/aws-client-agent-mcp/dist/mcp-tools.test.js +55 -1
- package/package/aws-client-agent-mcp/dist/memory-store.test.js +5 -1
- package/package/aws-client-agent-mcp/dist/parent-lifecycle.d.ts +10 -0
- package/package/aws-client-agent-mcp/dist/parent-lifecycle.js +2 -0
- package/package/aws-client-agent-mcp/dist/parent-lifecycle.test.d.ts +1 -0
- package/package/aws-client-agent-mcp/dist/parent-lifecycle.test.js +81 -0
- package/package/aws-client-agent-mcp/dist/status-reporter.js +1 -1
- package/package/aws-client-agent-mcp/dist/types.d.ts +4 -0
- package/package/aws-client-agent-mcp/dist/watchdog-worker.d.ts +1 -0
- package/package/aws-client-agent-mcp/dist/watchdog-worker.js +3 -0
- package/package/aws-client-agent-mcp/dist/watchdog.d.ts +17 -0
- package/package/aws-client-agent-mcp/dist/watchdog.js +2 -0
- package/package/aws-client-agent-mcp/dist/watchdog.test.d.ts +1 -0
- package/package/aws-client-agent-mcp/dist/watchdog.test.js +124 -0
- package/package/aws-client-agent-mcp/dist/websocket-client.d.ts +4 -0
- package/package/aws-client-agent-mcp/dist/websocket-client.js +1 -1
- package/package/aws-client-agent-mcp/dist/websocket-client.test.js +83 -6
- package/package/aws-client-agent-mcp/package.json +1 -1
- package/package.json +4 -1
- package/scripts/ensure-build-tools.mjs +141 -0
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{McpServer as
|
|
2
|
+
import{McpServer as e}from"./mcp-server.js";import{initializeStartupLogFile as i,logger as r}from"./logger.js";import{watchParentLifecycle as n}from"./parent-lifecycle.js";import{startEventLoopWatchdog as a}from"./watchdog.js";async function f(){const t=i();t&&r.info(`[Logger] MCP \u542F\u52A8\u65E5\u5FD7: ${t}`),a(),n(),r.info("=".repeat(60)),r.info("AgentsWorkStudio - Agent MCP Client"),r.info("\u7F16\u7A0B Agent \u4E0E\u8C03\u5EA6\u4E2D\u5FC3\u7684\u901A\u4FE1\u6865\u6881"),r.info("=".repeat(60)),r.info("");try{await new e().start()}catch(o){r.error("[Main] \u542F\u52A8\u5931\u8D25:",o),process.exit(1)}}f();
|
|
3
3
|
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import { mkdtemp, rm } from "node:fs/promises";
|
|
3
|
+
import os from "node:os";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import { afterEach, describe, it } from "node:test";
|
|
6
|
+
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
|
7
|
+
import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";
|
|
8
|
+
import { McpServer } from "./mcp-server.js";
|
|
9
|
+
import { MCP_TOOLS, LAUNCH_CONFIG_TOOL_NAMES } from "./mcp-tools.js";
|
|
10
|
+
import { MessageBuffer } from "./message-buffer.js";
|
|
11
|
+
import { MemoryStore } from "./memory-store.js";
|
|
12
|
+
const LAUNCH_ITEM_FEATURE_KEY = "agentSys.launchItem";
|
|
13
|
+
const LAUNCH_TOOLS_ENV_KEY = "AWS_LAUNCH_CONFIG_TOOLS";
|
|
14
|
+
const LAUNCH_TOOL_NAMES = [...LAUNCH_CONFIG_TOOL_NAMES];
|
|
15
|
+
/**
|
|
16
|
+
* 构造带能力开关 stub 的 McpServer(内存存储 + 假 agentClient),
|
|
17
|
+
* 通过 InMemoryTransport 暴露 SDK server,供真实 MCP Client 连接调用。
|
|
18
|
+
*/
|
|
19
|
+
async function buildServer(getRuntimeFeatures) {
|
|
20
|
+
const dir = await mkdtemp(path.join(os.tmpdir(), "aws-mcp-launch-"));
|
|
21
|
+
const server = new McpServer();
|
|
22
|
+
Reflect.set(server, "messageBuffer", new MessageBuffer());
|
|
23
|
+
Reflect.set(server, "memoryStore", new MemoryStore(path.join(dir, "instance-memory")));
|
|
24
|
+
Reflect.set(server, "roleMemoryStore", new MemoryStore(path.join(dir, "role-memory")));
|
|
25
|
+
Reflect.set(server, "sessionContextMemoryStore", new MemoryStore(path.join(dir, "session-context")));
|
|
26
|
+
Reflect.set(server, "agentClient", {
|
|
27
|
+
getStatusReporter: () => null,
|
|
28
|
+
getRuntimeFeatures,
|
|
29
|
+
});
|
|
30
|
+
const sdkServer = Reflect.get(server, "server");
|
|
31
|
+
const [serverTransport, clientTransport] = InMemoryTransport.createLinkedPair();
|
|
32
|
+
await sdkServer.connect(serverTransport);
|
|
33
|
+
const client = new Client({ name: "test", version: "1.0.0" });
|
|
34
|
+
await client.connect(clientTransport);
|
|
35
|
+
return { server, client, dir };
|
|
36
|
+
}
|
|
37
|
+
async function listToolNames(client) {
|
|
38
|
+
const result = await client.listTools();
|
|
39
|
+
return result.tools.map((tool) => tool.name);
|
|
40
|
+
}
|
|
41
|
+
describe("launch_config_* 能力开关门控(aws-mcp 侧)", () => {
|
|
42
|
+
const dirs = [];
|
|
43
|
+
const originalEnv = process.env[LAUNCH_TOOLS_ENV_KEY];
|
|
44
|
+
afterEach(async () => {
|
|
45
|
+
if (originalEnv === undefined) {
|
|
46
|
+
delete process.env[LAUNCH_TOOLS_ENV_KEY];
|
|
47
|
+
}
|
|
48
|
+
else {
|
|
49
|
+
process.env[LAUNCH_TOOLS_ENV_KEY] = originalEnv;
|
|
50
|
+
}
|
|
51
|
+
await Promise.all(dirs.splice(0).map((dir) => rm(dir, { recursive: true, force: true })));
|
|
52
|
+
});
|
|
53
|
+
it("未开启「启动项管理」时完全不暴露 launch_config_* 工具", async () => {
|
|
54
|
+
const { client, dir } = await buildServer(async () => ({}));
|
|
55
|
+
dirs.push(dir);
|
|
56
|
+
const names = await listToolNames(client);
|
|
57
|
+
for (const launchTool of LAUNCH_TOOL_NAMES) {
|
|
58
|
+
assert.equal(names.includes(launchTool), false, `${launchTool} 不应暴露`);
|
|
59
|
+
}
|
|
60
|
+
assert.equal(names.length, MCP_TOOLS.length - LAUNCH_TOOL_NAMES.length);
|
|
61
|
+
});
|
|
62
|
+
it("开启「启动项管理」后暴露全部 9 个启动项工具", async () => {
|
|
63
|
+
const { client, dir } = await buildServer(async () => ({
|
|
64
|
+
[LAUNCH_ITEM_FEATURE_KEY]: true,
|
|
65
|
+
}));
|
|
66
|
+
dirs.push(dir);
|
|
67
|
+
const names = await listToolNames(client);
|
|
68
|
+
for (const launchTool of LAUNCH_TOOL_NAMES) {
|
|
69
|
+
assert.equal(names.includes(launchTool), true, `${launchTool} 应暴露`);
|
|
70
|
+
}
|
|
71
|
+
});
|
|
72
|
+
it("能力拉取失败时回退启动期 env:env=1 暴露,无 env 不暴露", async () => {
|
|
73
|
+
process.env[LAUNCH_TOOLS_ENV_KEY] = "1";
|
|
74
|
+
const { client, dir } = await buildServer(async () => {
|
|
75
|
+
throw new Error("network down");
|
|
76
|
+
});
|
|
77
|
+
dirs.push(dir);
|
|
78
|
+
const namesWithEnv = await listToolNames(client);
|
|
79
|
+
for (const launchTool of LAUNCH_TOOL_NAMES) {
|
|
80
|
+
assert.equal(namesWithEnv.includes(launchTool), true, `${launchTool} 应回退暴露(env=1)`);
|
|
81
|
+
}
|
|
82
|
+
// 独立实例(新缓存):无 env → 不暴露
|
|
83
|
+
delete process.env[LAUNCH_TOOLS_ENV_KEY];
|
|
84
|
+
const second = await buildServer(async () => {
|
|
85
|
+
throw new Error("network down");
|
|
86
|
+
});
|
|
87
|
+
dirs.push(second.dir);
|
|
88
|
+
const namesWithoutEnv = await listToolNames(second.client);
|
|
89
|
+
for (const launchTool of LAUNCH_TOOL_NAMES) {
|
|
90
|
+
assert.equal(namesWithoutEnv.includes(launchTool), false, `${launchTool} 不应暴露(无 env)`);
|
|
91
|
+
}
|
|
92
|
+
});
|
|
93
|
+
it("未开启时直接调用 launch_config_* 被执行期守卫拒绝", async () => {
|
|
94
|
+
const { client, dir } = await buildServer(async () => ({}));
|
|
95
|
+
dirs.push(dir);
|
|
96
|
+
const result = await client.callTool({
|
|
97
|
+
name: "launch_config_list",
|
|
98
|
+
arguments: {},
|
|
99
|
+
});
|
|
100
|
+
assert.equal(result.isError, true, "未开启时应返回 isError");
|
|
101
|
+
const text = result.content
|
|
102
|
+
.map((block) => block.text ?? "")
|
|
103
|
+
.join("");
|
|
104
|
+
assert.match(text, /启动项管理能力未开启/);
|
|
105
|
+
});
|
|
106
|
+
});
|
|
@@ -22,6 +22,10 @@ export declare function initializeStartupLogFile(): string | null;
|
|
|
22
22
|
|
|
23
23
|
export declare function updateStartupLogIdentity(roleName: string, instanceName: string): void;
|
|
24
24
|
|
|
25
|
+
export declare function appendStartupLogLine(level: LogLevel, message: string): void;
|
|
26
|
+
|
|
27
|
+
export declare function getStartupLogFilePath(): string | null;
|
|
28
|
+
|
|
25
29
|
export declare function setMcpNodeLogSink(sink: McpNodeLogSink | null): void;
|
|
26
30
|
export declare const logger: {
|
|
27
31
|
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import*as
|
|
2
|
-
|
|
1
|
+
import*as u from"node:fs";import*as f from"node:os";import*as o from"node:path";import{format as m}from"node:util";const d=new Date,E=new Set(["0","false","off","no"]),S=200,L="aws-mcp-node";let t,c=null,g=null;const l=[];function s(e,r=2){return String(e).padStart(r,"0")}function N(e){return`${e.getFullYear()}-${s(e.getMonth()+1)}`}function M(e){return[s(e.getDate()),"-",s(e.getHours()),s(e.getMinutes()),s(e.getSeconds()),s(e.getMilliseconds(),3)].join("")}function _(e){const r=new RegExp("[\0-]","g");return e.replace(/[<>:"/\\|?*]/g,"_").replace(r,"_").replace(/\s+/g," ").trim().replace(/[. ]+$/g,"")||"workspace"}function h(e={}){const r=e.logDir||o.join(e.homeDir||f.homedir(),".aws-bridge","log"),n=_(e.roleName||process.env.AWS_ROLE_NAME||"unknown-role"),i=_(e.instanceName||process.env.AWS_AGENT_ID||"unknown-instance"),a=e.startupTime||d,w=N(a),D=`${M(a)}.log`;return o.join(r,"agent",L,`${n}-${i}`,w,D)}function $(){if(t!==void 0)return t;const e=String(process.env.AWS_MCP_FILE_LOG||"").trim().toLowerCase();if(E.has(e))return t=null,null;try{return c=process.env.AWS_MCP_LOG_DIR||void 0||o.join(f.homedir(),".aws-bridge","log"),t=h({logDir:c,roleName:process.env.AWS_ROLE_NAME||void 0,instanceName:process.env.AWS_AGENT_ID||void 0}),u.mkdirSync(o.dirname(t),{recursive:!0}),t}catch(r){return t=null,c=null,console.warn("[Logger] \u65E0\u6CD5\u521B\u5EFA MCP \u542F\u52A8\u65E5\u5FD7\u6587\u4EF6:",r),null}}function x(e,r){if(t==null||!c)return;const n=t,i=h({logDir:c,roleName:e,instanceName:r,startupTime:d});if(n!==i)try{u.mkdirSync(o.dirname(i),{recursive:!0}),u.renameSync(n,i),t=i,console.log(`[Logger] MCP \u542F\u52A8\u65E5\u5FD7\u8DEF\u5F84\u5DF2\u66F4\u65B0: ${n} -> ${i}`);const a=o.join(c,"agent",L);A(o.dirname(n),a)}catch(a){console.warn("[Logger] \u65E0\u6CD5\u66F4\u65B0 MCP \u542F\u52A8\u65E5\u5FD7\u8EAB\u4EFD\u6807\u8BC6:",a)}}function A(e,r){let n=o.normalize(e);const i=o.normalize(r),a=o.parse(n).root;for(;n!==i&&n!==a;){try{u.rmdirSync(n)}catch{break}n=o.dirname(n)}}function P(e,r){if(t===void 0)return;const n=t;if(n)try{u.appendFileSync(n,`${new Date().toISOString()} [${e.toUpperCase()}] ${r}
|
|
2
|
+
`,"utf8")}catch{t=null}}function I(){return t??null}function y(e,r){P(e,m(...r))}function p(e,r){const n={level:e,message:m(...r),timestamp:new Date().toISOString()};if(y(e,r),F(n),!!process.stderr.isTTY)try{switch(e){case"info":console.error(...r);break;case"warn":console.warn(...r);break;case"error":console.error(...r);break}}catch{}}function O(e){if(g=e,!!e)for(const r of l)e(r)}function F(e){l.push(e),l.length>S&&l.splice(0,l.length-S),g&&g(e)}const b={debug:(...e)=>{},info:(...e)=>p("info",e),warn:(...e)=>p("warn",e),error:(...e)=>p("error",e)};export{P as appendStartupLogLine,h as buildStartupLogFilePath,M as formatLogFileTimestamp,N as formatLogYearMonth,I as getStartupLogFilePath,$ as initializeStartupLogFile,b as logger,_ as sanitizeLogFileNameSegment,O as setMcpNodeLogSink,x as updateStartupLogIdentity};
|
|
3
3
|
|
|
@@ -23,6 +23,15 @@ export declare class McpServer {
|
|
|
23
23
|
|
|
24
24
|
private isSubAgent;
|
|
25
25
|
|
|
26
|
+
private fileChangeNotifyHistory;
|
|
27
|
+
|
|
28
|
+
private featuresCache;
|
|
29
|
+
private static readonly FEATURES_CACHE_TTL_MS;
|
|
30
|
+
|
|
31
|
+
private static readonly LAUNCH_ITEM_FEATURE_KEY;
|
|
32
|
+
|
|
33
|
+
private static readonly LAUNCH_TOOLS_ENV_KEY;
|
|
34
|
+
|
|
26
35
|
private leaseRenewalTimer;
|
|
27
36
|
private activeLeaseUris;
|
|
28
37
|
private static readonly LEASE_DURATION_MINUTES;
|
|
@@ -53,7 +62,13 @@ export declare class McpServer {
|
|
|
53
62
|
|
|
54
63
|
private handleToolCall;
|
|
55
64
|
|
|
65
|
+
private safeReportStatus;
|
|
66
|
+
|
|
56
67
|
private executeToolCall;
|
|
68
|
+
|
|
69
|
+
private isLaunchConfigToolsEnabled;
|
|
70
|
+
|
|
71
|
+
private fetchRuntimeFeaturesWithStatus;
|
|
57
72
|
private static readonly MEMORY_TYPES;
|
|
58
73
|
private static readonly MEMORY_TOOL_NAMES;
|
|
59
74
|
|
|
@@ -154,12 +169,18 @@ export declare class McpServer {
|
|
|
154
169
|
|
|
155
170
|
private computeBoundFileStatuses;
|
|
156
171
|
|
|
172
|
+
private fileChangeFingerprint;
|
|
173
|
+
|
|
174
|
+
private filterFileChangesByRenotifyCooldown;
|
|
175
|
+
|
|
157
176
|
private checkMemoriesFileChanges;
|
|
158
177
|
|
|
159
178
|
private calculateFileMd5;
|
|
160
179
|
private verifyFileNotExist;
|
|
161
180
|
private handleGetMessage;
|
|
162
181
|
|
|
182
|
+
private confirmServerMessages;
|
|
183
|
+
|
|
163
184
|
private hydrateUnreadMessagesFromServer;
|
|
164
185
|
|
|
165
186
|
private hydrateBrowserListenerEvents;
|
|
@@ -1,49 +1,49 @@
|
|
|
1
|
-
import $ from"node:fs";import
|
|
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 H,this.messageBuffer=new V,this.initialRoleName=v.resolveRoleMemoryDirectoryName(),this.hasRoleName=!!process.env.AWS_ROLE_NAME;const e=v.resolveMemoryStorePaths();this.memoryStore=new Q(this.agentClient),this.roleMemoryStore=new N(e.rolePath),this.sessionContextMemoryStore=new N(f.join(f.dirname(e.rolePath),"..","session_context")),this.isSubAgent=process.env.AWS_SUB_AGENT==="true",this.contextManager=new X(this.sessionContextMemoryStore),this.server=new U({name:z,version:G},{capabilities:{tools:{}}}),this.setupHandlers()}setupHandlers(){this.server.setRequestHandler(W,async()=>({tools:this.isSubAgent?D.filter(t=>F.has(t.name)):D})),this.server.setRequestHandler(q,async e=>{const{name:t,arguments:r}=e.params;try{const s=await this.handleToolCall(t,r);return{content:this.buildToolResultContent(s)}}catch(s){const i=s instanceof Error?s.message:String(s),n=s instanceof Z?{error:i,...s.details}:{error:i};return a.error("[McpServer] \u5DE5\u5177\u8C03\u7528\u5F02\u5E38: tool=%s, error=%s, stack=%s",t,i,s instanceof Error?s.stack:"(no stack)"),{content:[{type:"text",text:JSON.stringify(n,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){const r=t?._aws_sub_agent===!0,s=t?._aws_silent_poll===!0,i=t?._aws_force_inject===!0,n={...t};delete n._aws_sub_agent,delete n._aws_silent_poll,delete n._aws_force_inject;const o=r?null:this.agentClient.getStatusReporter();o&&!s&&o.reportToolUse(e,this.sanitizeToolUseArgs(e,n));try{const l=await this.executeToolCall(e,n,{forceInject:i});if(o&&!s){const h=this.stripAutoDelegateForReporting(l);h!==null&&(o.reportToolResult(h),o.reportThinking())}return l}catch(l){throw o&&!s&&o.reportToolError(l),l}}async executeToolCall(e,t,r={}){if(this.isSubAgent&&!F.has(e))throw new Error(`Sub-agent is not allowed to call tool: ${e}`);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();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"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);default:throw new Error(`Unknown tool: ${e}`)}}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=f.resolve(e);for(;;){if($.existsSync(f.join(t,".agentswork")))return f.join(t,".agentswork");const r=f.dirname(t);if(r===t)break;t=r}return f.join(f.resolve(e),".agentswork")}static sanitizeRoleDirectoryName(e){return String(e||"").trim().split("").map(r=>re.has(r)||r.charCodeAt(0)<32?"_":r).join("").replace(/^\.+|\.+$/g,"").trim()||"default-role"}static resolveRoleMemoryDirectoryName(){return v.sanitizeRoleDirectoryName(process.env.AWS_ROLE_NAME||"")}static buildRoleMemoryStorePath(e){const t=process.env.AWS_WORKSPACE_PATH||process.cwd(),r=v.findAgentsworkDirSync(t);return f.join(r,"memory","memory",v.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=v.findAgentsworkDirSync(t),s=String(process.env.AWS_INSTANCE_MEMORY_STORE_PATH||"").trim()||f.join(r,"memory","server-managed"),i=String(process.env.AWS_ROLE_MEMORY_STORE_PATH||"").trim()||f.join(r,"memory","memory",v.resolveRoleMemoryDirectoryName());return{instancePath:s,rolePath:i}}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(s=>String(s)):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 v.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(!v.MEMORY_TOOL_NAMES.has(e))return t;const r={},s=this.getOptionalString(t,"uri"),i=this.getOptionalString(t,"memory_type"),n=this.getOptionalNumber(t,"limit");return s&&(r.uri=s),i&&(r.memory_type=i),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:[],s=Array.isArray(t.groupMessages)?t.groupMessages:[],i=l=>!!l&&typeof l=="object"&&"_acodeAutoDelegate"in l;if(!r.some(i))return e;const o=r.filter(l=>!i(l));return o.length===0&&s.length===0?null:{...t,directMessages:o}}async handleCreateMemory(e){const t=this.normalizeBoundFiles(this.getOptionalStringArray(e,"bound_files"));await this.validateBoundFilesExist(t);let r,s;if(t&&t.length>0){r={};for(const o of t){const l=await this.calculateFileMd5(o);l&&(r[o]=l)}s=new Date().toISOString()}const i={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:s},n=await this.memoryStore.createMemory(i);return i.memory_type==="project_memory"&&this.backupProjectMemoryToLocal(i).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",s=this.getOptionalString(e,"append");if(t&&!r)throw new Error("old_string and new_string must be provided together");const i={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:s,keywords:this.getOptionalStringArray(e,"keywords"),bound_files:this.normalizeBoundFiles(this.getOptionalStringArray(e,"bound_files"))},n=await this.findMemoryStoreForMutation(i),o=await n.store.readMemory({uri:i.uri,memory_type:n.memory_type??i.memory_type});i.bound_files!==void 0?await this.validateBoundFilesExist(i.bound_files):o?.bound_files&&o.bound_files.length>0&&await this.validateBoundFilesExist(o.bound_files);const l=i.bound_files??o?.bound_files;let h,m;if(l&&l.length>0){h={};for(const u of l){const p=await this.calculateFileMd5(u);p&&(h[u]=p)}m=new Date().toISOString()}const d=await n.store.updateMemory({...i,memory_type:n.memory_type??i.memory_type,file_md5_map:h,last_check_time:m});if(n.memory_type==="project_memory"&&this.backupProjectMemoryToLocal({...i,memory_type:"project_memory",file_md5_map:h,last_check_time:m}).catch(u=>{a.warn("[McpServer] \u5907\u4EFD project_memory \u66F4\u65B0\u5230\u672C\u5730\u5931\u8D25:",u)}),await this.reportMemoryStatsToServer(),n.memory_type==="project_memory"&&o?.memory_status==="updating")try{await this.memoryStore.releaseMemoryClaim(i.uri),this.activeLeaseUris.delete(i.uri),this.activeLeaseUris.size===0&&this.stopLeaseRenewal()}catch(u){a.warn("[McpServer] \u91CA\u653E memory claim \u5931\u8D25: uri=%s, error=%s",i.uri,u instanceof Error?u.message:String(u))}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 s=0;const i=[],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 h=l,m=typeof h.uri=="string"?h.uri:"";if(!m){n.push({uri:"",reason:`memories[${o}].uri \u7F3A\u5931`});continue}const d=typeof h.memory_type=="string"?this.parseMemoryType(h.memory_type):void 0;try{await this.deleteMemorySingle(m,d,!0)?s++:i.push(m)}catch(u){n.push({uri:m,reason:u instanceof Error?u.message:String(u)})}}return s>0&&await this.reportMemoryStatsToServer(),{deleted:s,not_found:i,failed:n}}async deleteMemorySingle(e,t,r=!1){const s={uri:e,memory_type:t},i=await this.findMemoryStoreForMutation(s),n=i.memory_type??s.memory_type,o=await i.store.deleteMemory({...s,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",s=this.getOptionalString(e,"keyword_mode"),i=s==="all"?"all":s==="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:i,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 s=new Set,i=typeof r=="number"&&r>0?r:10,n=[...e.results,...t.results].filter(o=>{const l=o.uri;return s.has(l)?!1:(s.add(l),!0)}).sort((o,l)=>l.updatedAt.localeCompare(o.updatedAt)).slice(0,i);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),s=this.getOptionalMemoryType(e),i=this.getOptionalString(e,"scope"),n=i==="own"||i==="children"?i:"all",o=async()=>await this.memoryStore.listByFile(r,{memory_type:s,scope:"children"}).catch(()=>[]);if(n==="children"){const u=await o();return{file_path:r,count:u.length,memories:u.map(p=>this.toMemoryRecordWithMetadata(p))}}const l=await this.collectOwnMemoriesByFile(r,s);if(n==="own")return{file_path:r,count:l.length,memories:l.map(u=>this.toMemoryRecordWithMetadata(u))};const h=await o(),m=new Set(l.map(u=>u.id)),d=[...l];for(const u of h)m.has(u.id)||(d.push(u),m.add(u.id));return d.sort((u,p)=>p.updatedAt.localeCompare(u.updatedAt)),{file_path:r,count:d.length,memories:d.map(u=>this.toMemoryRecordWithMetadata(u))}}mergeIdDedupe(e,t){const r=new Set;for(const i of e)i.id&&r.add(i.id);const s=[...e];for(const i of t)i.id&&!r.has(i.id)&&(s.push(i),r.add(i.id));return s.sort((i,n)=>n.updatedAt.localeCompare(i.updatedAt)),s}async searchChildMemoriesByFileLocal(e,t){const r=process.env.AWS_WORKSPACE_PATH||process.cwd(),s=this.normalizeBoundFilePath(e),n=(s.startsWith("./")?s.substring(2):s).split("/"),o=[],l=new Set,{access:h,readdir:m,readFile:d}=await import("node:fs/promises");for(let u=n.length-1;u>=1;u--){const p=n.slice(0,u),b="./"+n.slice(u).join("/"),A=f.join(r,...p);if(A===r)continue;const c=f.join(A,".agentswork");try{await h(c)}catch{continue}const g=f.join(c,"memory","memory");let R;try{R=(await m(g,{withFileTypes:!0})).filter(_=>_.isDirectory()).map(_=>_.name)}catch{continue}for(const M of R){const _=f.join(g,M);let C;try{C=await m(_)}catch{continue}for(const y of C){if(!y.endsWith(".json"))continue;const w=f.join(_,y);let S;try{S=await d(w,"utf-8")}catch{continue}let k;try{k=JSON.parse(S)}catch{continue}if(k.by_uri)for(const[E,I]of Object.entries(k.by_uri)){if(!I)continue;const O=I.id||E;l.has(O)||t&&I.memory_type!==t||I.bound_files&&I.bound_files.length>0&&I.bound_files.some(B=>this.normalizeBoundFilePath(B)===b)&&(l.add(O),o.push({...I,uri:I.uri||E}))}}}}return o.sort((u,p)=>p.updatedAt.localeCompare(u.updatedAt)),o}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),s=await this.memoryStore.readMemory({uri:t,memory_type:r});return s?.bound_files&&s.bound_files.length>0&&await this.validateBoundFilesExist(s.bound_files),await this.memoryStore.releaseMemoryClaim(t),s?.memory_type==="project_memory"&&this.backupProjectMemoryToLocal({uri:t,memory_type:"project_memory"}).catch(i=>{a.info(`[McpServer] abandon_memory_update: \u540C\u6B65\u672C\u5730\u5907\u4EFD\u5931\u8D25: ${t}`,i)}),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 i=[...r].sort((l,h)=>{const m=new Date(l.expiresAt||l.createdAt||0).getTime(),d=new Date(h.expiresAt||h.createdAt||0).getTime();return m-d}).slice(0,t),n=Math.max(0,r.length-i.length);return{memories:i.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:i.length,limit:t,remaining:n,totalExpired:r.length,message:n>0?`\u672C\u6B21\u5904\u7406 ${i.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
|
|
1
|
+
import $ from"node:fs";import F from"node:os";import f from"node:path";import{Server as W}from"@modelcontextprotocol/sdk/server/index.js";import{StdioServerTransport as G}from"@modelcontextprotocol/sdk/server/stdio.js";import{CallToolRequestSchema as z,ListToolsRequestSchema as Y}from"@modelcontextprotocol/sdk/types.js";import{AgentClient as K}from"./agent-client.js";import{MCP_SERVER_NAME as J,MCP_SERVER_VERSION as V,REGISTER_MAX_RETRIES as N,REGISTER_RETRY_INTERVAL_MS as X,DEGRADED_MODE_ENABLED as j,DEGRADED_MODE_RETRY_INTERVAL_MS as Z,DEGRADED_MODE_MAX_RETRIES as Q}from"./constants.js";import{logger as a}from"./logger.js";import{MCP_TOOLS as O,MEMORY_TOOL_NAMES as B,LAUNCH_CONFIG_TOOL_NAMES as U}from"./mcp-tools.js";import{MessageBuffer as ee}from"./message-buffer.js";import{ContextManager as te}from"./context-manager.js";import{MemoryCapacityError as re,MemoryStore as P}from"./memory-store.js";import{ServerMemoryStore as se}from"./server-memory-store.js";const ie=3e3,ne=10,x=(()=>{const L=Number.parseInt(process.env.AWS_MCP_FILE_CHANGE_RENOTIFY_COOLDOWN_MS||"",10);return Number.isFinite(L)&&L>0?L:30*6e4})(),H=500,oe=new Set(["<",">",":",'"',"/","\\","|","?","*"]);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";leaseRenewalTimer=null;activeLeaseUris=new Set;static LEASE_DURATION_MINUTES=10;static LEASE_RENEW_INTERVAL_MS=6e4;profileSynced=!1;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 P(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=f.dirname(w.buildRoleMemoryStorePath(this.initialRoleName));a.info(`[McpServer] \u5C1D\u8BD5\u4ECE\u9057\u7559\u76EE\u5F55\u8BFB\u53D6: ${n}`);try{const l=await new P(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=f.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}}constructor(){this.agentClient=new K,this.messageBuffer=new ee,this.initialRoleName=w.resolveRoleMemoryDirectoryName(),this.hasRoleName=!!process.env.AWS_ROLE_NAME;const e=w.resolveMemoryStorePaths();this.memoryStore=new se(this.agentClient),this.roleMemoryStore=new P(e.rolePath),this.sessionContextMemoryStore=new P(f.join(f.dirname(e.rolePath),"..","session_context")),this.isSubAgent=process.env.AWS_SUB_AGENT==="true",this.contextManager=new te(this.sessionContextMemoryStore),this.server=new W({name:J,version:V},{capabilities:{tools:{}}}),this.setupHandlers()}setupHandlers(){this.server.setRequestHandler(Y,async()=>{let e=this.isSubAgent?O.filter(t=>B.has(t.name)):O;return!this.isSubAgent&&!await this.isLaunchConfigToolsEnabled()&&(e=e.filter(t=>!U.has(t.name))),{tools:e}}),this.server.setRequestHandler(z,async e=>{const{name:t,arguments:r}=e.params;try{const i=await this.handleToolCall(t,r);return{content:this.buildToolResultContent(i)}}catch(i){const s=i instanceof Error?i.message:String(i),n=i instanceof re?{error:s,...i.details}:{error:s};return a.error("[McpServer] \u5DE5\u5177\u8C03\u7528\u5F02\u5E38: tool=%s, error=%s, stack=%s",t,s,i instanceof Error?i.stack:"(no stack)"),{content:[{type:"text",text:JSON.stringify(n,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){const r=t?._aws_sub_agent===!0,i=t?._aws_silent_poll===!0,s=t?._aws_force_inject===!0,n={...t};delete n._aws_sub_agent,delete n._aws_silent_poll,delete n._aws_force_inject;const o=r?null:this.agentClient.getStatusReporter();o&&!i&&this.safeReportStatus(()=>o.reportToolUse(e,this.sanitizeToolUseArgs(e,n)));try{const l=await this.executeToolCall(e,n,{forceInject:s});if(o&&!i){const h=this.stripAutoDelegateForReporting(l);h!==null&&(this.safeReportStatus(()=>o.reportToolResult(h)),this.safeReportStatus(()=>o.reportThinking()))}return l}catch(l){throw o&&!i&&this.safeReportStatus(()=>o.reportToolError(l)),l}}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&&!B.has(e))throw new Error(`Sub-agent is not allowed to call tool: ${e}`);if(U.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");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();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"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 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=f.resolve(e);for(;;){if($.existsSync(f.join(t,".agentswork")))return f.join(t,".agentswork");const r=f.dirname(t);if(r===t)break;t=r}return f.join(f.resolve(e),".agentswork")}static sanitizeRoleDirectoryName(e){return String(e||"").trim().split("").map(r=>oe.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 f.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()||f.join(r,"memory","server-managed"),s=String(process.env.AWS_ROLE_MEMORY_STORE_PATH||"").trim()||f.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 h,c;if(l&&l.length>0){h={};for(const u of l){const g=await this.calculateFileMd5(u);g&&(h[u]=g)}c=new Date().toISOString()}const d=await n.store.updateMemory({...s,memory_type:n.memory_type??s.memory_type,file_md5_map:h,last_check_time:c});if(n.memory_type==="project_memory"&&this.backupProjectMemoryToLocal({...s,memory_type:"project_memory",file_md5_map:h,last_check_time:c}).catch(u=>{a.warn("[McpServer] \u5907\u4EFD project_memory \u66F4\u65B0\u5230\u672C\u5730\u5931\u8D25:",u)}),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(u){a.warn("[McpServer] \u91CA\u653E memory claim \u5931\u8D25: uri=%s, error=%s",s.uri,u instanceof Error?u.message:String(u))}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 h=l,c=typeof h.uri=="string"?h.uri:"";if(!c){n.push({uri:"",reason:`memories[${o}].uri \u7F3A\u5931`});continue}const d=typeof h.memory_type=="string"?this.parseMemoryType(h.memory_type):void 0;try{await this.deleteMemorySingle(c,d,!0)?i++:s.push(c)}catch(u){n.push({uri:c,reason:u instanceof Error?u.message:String(u)})}}return i>0&&await this.reportMemoryStatsToServer(),{deleted:i,not_found:s,failed:n}}async deleteMemorySingle(e,t,r=!1){const i={uri:e,memory_type:t},s=await this.findMemoryStoreForMutation(i),n=s.memory_type??i.memory_type,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 u=await o();return{file_path:r,count:u.length,memories:u.map(g=>this.toMemoryRecordWithMetadata(g))}}const l=await this.collectOwnMemoriesByFile(r,i);if(n==="own")return{file_path:r,count:l.length,memories:l.map(u=>this.toMemoryRecordWithMetadata(u))};const h=await o(),c=new Set(l.map(u=>u.id)),d=[...l];for(const u of h)c.has(u.id)||(d.push(u),c.add(u.id));return d.sort((u,g)=>g.updatedAt.localeCompare(u.updatedAt)),{file_path:r,count:d.length,memories:d.map(u=>this.toMemoryRecordWithMetadata(u))}}mergeIdDedupe(e,t){const r=new Set;for(const s of e)s.id&&r.add(s.id);const i=[...e];for(const s of t)s.id&&!r.has(s.id)&&(i.push(s),r.add(s.id));return i.sort((s,n)=>n.updatedAt.localeCompare(s.updatedAt)),i}async searchChildMemoriesByFileLocal(e,t){const r=process.env.AWS_WORKSPACE_PATH||process.cwd(),i=this.normalizeBoundFilePath(e),n=(i.startsWith("./")?i.substring(2):i).split("/"),o=[],l=new Set,{access:h,readdir:c,readFile:d}=await import("node:fs/promises");for(let u=n.length-1;u>=1;u--){const g=n.slice(0,u),C="./"+n.slice(u).join("/"),k=f.join(r,...g);if(k===r)continue;const m=f.join(k,".agentswork");try{await h(m)}catch{continue}const p=f.join(m,"memory","memory");let R;try{R=(await c(p,{withFileTypes:!0})).filter(_=>_.isDirectory()).map(_=>_.name)}catch{continue}for(const M of R){const _=f.join(p,M);let E;try{E=await c(_)}catch{continue}for(const y of E){if(!y.endsWith(".json"))continue;const v=f.join(_,y);let S;try{S=await d(v,"utf-8")}catch{continue}let b;try{b=JSON.parse(S)}catch{continue}if(b.by_uri)for(const[A,I]of Object.entries(b.by_uri)){if(!I)continue;const D=I.id||A;l.has(D)||t&&I.memory_type!==t||I.bound_files&&I.bound_files.length>0&&I.bound_files.some(q=>this.normalizeBoundFilePath(q)===C)&&(l.add(D),o.push({...I,uri:I.uri||A}))}}}}return o.sort((u,g)=>g.updatedAt.localeCompare(u.updatedAt)),o}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,h)=>{const c=new Date(l.expiresAt||l.createdAt||0).getTime(),d=new Date(h.expiresAt||h.createdAt||0).getTime();return c-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
|
-
\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 ${
|
|
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(
|
|
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){if(!e.content||typeof e.content!="string")throw new Error("content is required");return this.recordMessageTokenUsage(e.content).catch(t=>a.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=>a.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(){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"),await this.pendingPollMessage;this.pendingPollMessage=(async()=>await this.doPollMessage())();try{return await this.pendingPollMessage}finally{this.pendingPollMessage=null}}async doPollMessage(){a.info("[McpServer] doPollMessage \u88AB\u8C03\u7528");const e=await this.buildTodoBlockNotification();if(e)return this.buildPollResult({directMessages:[e],groupMessages:[]});await this.hydrateUnreadMessagesFromServer({blockIfEmpty:!1,includePipelineTasks:!0}),await this.hydrateBrowserListenerEvents();const t=await this.buildBackgroundTaskNotification(),r=await this.confirmServerMessages(this.messageBuffer.get());if(r.directMessages.length>0||r.groupMessages.length>0)return t&&r.directMessages.unshift(t),this.buildPollResult(r);if(t)return this.buildPollResult({directMessages:[t],groupMessages:[]});const i=await this.checkAllLocalNonUrgentNotifications();if(i.length>0)return this.buildPollResult({directMessages:i,groupMessages:[]});let s=!1,n=0;for(;;){if(!s){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",{}),s=!0}}const o=await this.confirmServerMessages(await this.messageBuffer.poll(ie));if(o.directMessages.length>0||o.groupMessages.length>0)return this.buildPollResult(o);if(a.debug("[McpServer] poll \u8D85\u65F6\uFF0C\u68C0\u67E5\u6D4F\u89C8\u5668\u76D1\u542C\u5668\u4E8B\u4EF6"),await this.hydrateBrowserListenerEvents()){const g=await this.confirmServerMessages(this.messageBuffer.get());if(g.directMessages.length>0||g.groupMessages.length>0)return a.info("[McpServer] \u76D1\u542C\u5668\u4E8B\u4EF6\u5DF2\u6CE8\u5165\uFF0Cpoll_message \u8FD4\u56DE %d \u6761\u79C1\u4FE1",g.directMessages.length),this.buildPollResult(g)}if(n++,n<ne)continue;n=0;const h=await this.buildTodoBlockNotification();if(h)return this.buildPollResult({directMessages:[h],groupMessages:[]});await this.hydrateUnreadMessagesFromServer({blockIfEmpty:!1,includePipelineTasks:!0});const c=await this.buildBackgroundTaskNotification(),d=this.messageBuffer.get();if(d.directMessages.length>0||d.groupMessages.length>0)return c&&d.directMessages.unshift(c),this.buildPollResult(d);if(c)return this.buildPollResult({directMessages:[c],groupMessages:[]});const u=await this.checkAllLocalNonUrgentNotifications(!1);if(u.length>0)return this.buildPollResult({directMessages:u,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{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(([,h])=>h.exceeded).map(([h,c])=>({memoryType:o,domain:h,domainStats:c})):[]);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:h})=>`${o}/${l} \u7C7B\u578B\u4E0B\u5F53\u524D ${h.count} \u6761 memory\uFF0C\u5EFA\u8BAE\u4E0A\u9650 ${h.limit} \u6761\uFF0C\u786C\u4E0A\u9650 ${h.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
8
|
`);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
9
|
|
|
10
10
|
\u5F85\u758F\u7406\u8BB0\u5FC6\uFF1A
|
|
11
|
-
${
|
|
12
|
-
...\u53CA\u5176\u4ED6 ${r.length-5} \u6761`:""}`,requireReply:!1,timestamp:new Date().toISOString(),_acodeAutoDelegate:{type:"memory_expiration",uris:r.map(n=>n.uri)}}}if(
|
|
13
|
-
`);return{msgId:`memory-recurrence-${Date.now()}`,senderId:"MCP-System",senderName:"\u7CFB\u7EDF",receiverId:t,content:`\u6709 ${
|
|
11
|
+
${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(n=>n.uri)}}}if(i.length>0){const s=i.slice(0,5).map(n=>n.uri).join(`
|
|
13
|
+
`);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
14
|
|
|
15
15
|
\u5373\u5C06\u9057\u5FD8\u7684\u8BB0\u5FC6\uFF1A
|
|
16
|
-
${
|
|
17
|
-
...\u53CA\u5176\u4ED6 ${
|
|
16
|
+
${s}${i.length>5?`
|
|
17
|
+
...\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(m=>m.memory_status==="updating"&&m.updating_agent_id===e);if(r.length>0){this.startLeaseRenewal();const m=this.filterFileChangesByRenotifyCooldown(await this.checkMemoriesFileChanges(r));if(m.length>0){for(const S of m){const b=r.find(A=>A.id===S.memoryId);b&&await this.memoryStore.updateMemory({uri:b.uri,memory_type:"project_memory",memory_status:"updating",updating_agent_id:e,file_md5_map:b.file_md5_map,last_check_time:b.last_check_time,bound_files:b.bound_files})}const y=Math.min(m.length,5),v=m.slice(0,5).map(S=>`- ${S.memoryUri} (\u6587\u4EF6: ${S.changedFiles.join(", ")})`).join(`
|
|
18
18
|
`);return{msgId:`memory-file-change-${Date.now()}`,senderId:"MCP-System",senderName:"\u7CFB\u7EDF",receiverId:e,content:`\u68C0\u6D4B\u5230\u4EE5\u4E0B ${y} \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
19
|
|
|
20
|
-
${
|
|
20
|
+
${v}
|
|
21
21
|
|
|
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:
|
|
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:m.slice(0,5).map(S=>S.memoryUri),fileChanges:m.slice(0,5).map(S=>{const b=r.find(A=>A.id===S.memoryId);return{uri:S.memoryUri,boundFiles:b?.bound_files??[],fileStatuses:S.fileStatuses,changedFiles:S.changedFiles}})}}}const p=r,R=new Map;for(const y of p.slice(0,5))R.set(y.uri,await this.computeBoundFileStatuses(y));const M=p.filter(y=>{const v=R.get(y.uri);return!v||v.length===0?!1:v.some(S=>S.status==="content_changed"||S.status==="not_found")}),_=p.filter(y=>!M.includes(y));if(_.length>0){a.info(`[McpServer] \u6587\u4EF6\u53D8\u66F4\u68C0\u6D4B Step1: ${_.length} \u4E2A updating memory \u7ED1\u5B9A\u6587\u4EF6\u65E0\u771F\u5B9E\u53D8\u66F4\uFF0C\u81EA\u52A8\u91CA\u653E: ${_.map(y=>y.uri).join(", ")}`);for(const y of _)try{await this.memoryStore.releaseMemoryClaim(y.uri),this.activeLeaseUris.delete(y.uri),await this.memoryStore.updateMemory({uri:y.uri,memory_type:"project_memory"})}catch(v){a.info(`[McpServer] \u81EA\u52A8\u91CA\u653E stale updating memory \u5931\u8D25: ${y.uri}`,v)}this.activeLeaseUris.size===0&&this.stopLeaseRenewal()}if(M.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 E=M.slice(0,5).map(y=>`- ${y.uri} (\u6587\u4EF6: ${y.bound_files?.join(", ")||"\u672A\u77E5"})`).join(`
|
|
23
23
|
`);return a.info(`[McpServer] \u6587\u4EF6\u53D8\u66F4\u68C0\u6D4B Step1: ${M.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
24
|
|
|
25
|
-
${
|
|
25
|
+
${E}
|
|
26
26
|
|
|
27
|
-
\u8BF7\u7EE7\u7EED\u5B8C\u6210\u66F4\u65B0\u5DE5\u4F5C\u3002`,requireReply:!1,timestamp:new Date().toISOString(),_acodeAutoDelegate:{type:"memory_file_change",uris:M.slice(0,5).map(y=>y.uri),fileChanges:M.slice(0,5).map(y=>({uri:y.uri,boundFiles:y.bound_files??[],fileStatuses:R.get(y.uri)??[]}))}}}const
|
|
27
|
+
\u8BF7\u7EE7\u7EED\u5B8C\u6210\u66F4\u65B0\u5DE5\u4F5C\u3002`,requireReply:!1,timestamp:new Date().toISOString(),_acodeAutoDelegate:{type:"memory_file_change",uris:M.slice(0,5).map(y=>y.uri),fileChanges:M.slice(0,5).map(y=>({uri:y.uri,boundFiles:y.bound_files??[],fileStatuses:R.get(y.uri)??[]}))}}}const i=await this.memoryStore.listByType("recently_memory"),s=await this.memoryStore.listByType("agent_memory"),n=[...i,...s],o=n.filter(m=>m.bound_files&&m.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(m=>`${m.uri}(bound=${m.bound_files?.length??0},md5=${Object.keys(m.file_md5_map??{}).length})`).join("; ")||"\u65E0 memory"}`);const l=new Map;for(const m of n)m.bound_files&&m.bound_files.length>0&&l.set(m.id,JSON.stringify(m.file_md5_map??{}));const h=this.filterFileChangesByRenotifyCooldown(await this.checkMemoriesFileChanges(n)),c=h;a.info(`[McpServer] \u6587\u4EF6\u53D8\u66F4\u68C0\u6D4B Step2: \u68C0\u6D4B\u5230\u53D8\u66F4=${h.length}`+(h.length>0?` \u53D8\u66F4\u9879: ${h.map(m=>`${m.memoryUri}(${m.changedFiles.join(",")})`).join("; ")}`:""));const d=n.filter(m=>{if(!m.bound_files||m.bound_files.length===0||h.some(M=>M.memoryId===m.id))return!1;const p=l.get(m.id),R=JSON.stringify(m.file_md5_map??{});return p!==R});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 m of d)try{await this.memoryStore.updateMemory({uri:m.uri,memory_type:m.memory_type,file_md5_map:m.file_md5_map,last_check_time:m.last_check_time})}catch(p){a.info(`[McpServer] \u56DE\u5199 listable MD5 map \u5931\u8D25: ${m.uri}`,p)}}if(c.length>0){const m=c.map(p=>`- ${p.memoryUri} (\u6587\u4EF6: ${p.changedFiles.join(", ")})`).join(`
|
|
28
28
|
`);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
29
|
|
|
30
|
-
${
|
|
30
|
+
${m}
|
|
31
31
|
|
|
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:
|
|
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:c.map(p=>p.memoryUri),fileChanges:c.map(p=>{const R=n.find(M=>M.id===p.memoryId);return{uri:p.memoryUri,boundFiles:R?.bound_files??[],fileStatuses:p.fileStatuses,changedFiles:p.changedFiles}})}}}const u=t.filter(m=>m.bound_files&&m.bound_files.length>0&&(m.memory_status==="normal"||!m.memory_status)&&!this.isClaimCached(m.uri)),g=t.filter(m=>m.bound_files&&m.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=${g.length}, \u5F85\u68C0\u6D4B(\u8FC7\u6EE4updating/claimed\u540E)=${u.length}\u3002\u88AB\u8FC7\u6EE4\u539F\u56E0: ${g.length-u.length} \u9879(memory_status=updating \u6216 isClaimCached)`);const T=new Map;for(const m of u)T.set(m.id,JSON.stringify(m.file_md5_map??{}));const C=this.filterFileChangesByRenotifyCooldown(await this.checkMemoriesFileChanges(u)),k=u.filter(m=>{if(C.some(M=>M.memoryId===m.id))return!1;const p=T.get(m.id),R=JSON.stringify(m.file_md5_map??{});return p!==R&&m.file_md5_map&&Object.keys(m.file_md5_map).length>0});if(k.length>0){a.info(`[McpServer] \u6587\u4EF6\u53D8\u66F4\u68C0\u6D4B Step3: \u56DE\u5199 ${k.length} \u4E2A memory \u7684\u4FEE\u6B63 MD5 map \u5230\u670D\u52A1\u7AEF\uFF08\u65E0\u57FA\u7EBF/\u952E\u7F3A\u5931\u4FEE\u590D\uFF09`);for(const m of k)try{await this.memoryStore.updateMemory({uri:m.uri,memory_type:"project_memory",file_md5_map:m.file_md5_map,last_check_time:m.last_check_time})}catch(p){a.info(`[McpServer] \u56DE\u5199\u57FA\u7EBF MD5 \u5931\u8D25: ${m.uri}`,p)}}if(a.info(`[McpServer] \u6587\u4EF6\u53D8\u66F4\u68C0\u6D4B Step3: \u68C0\u6D4B\u5230\u53D8\u66F4=${C.length}`+(C.length>0?` \u53D8\u66F4\u9879: ${C.map(m=>`${m.memoryUri}(${m.changedFiles.join(",")})`).join("; ")}`:"")),C.length>0){const m=C.slice(0,5),p=m.map(_=>_.memoryUri);let R=!1,M=new Set;try{const _=await this.memoryStore.claimMemoryUpdate(p,w.LEASE_DURATION_MINUTES,"project_memory");M=new Set(_.claimed_uris??[]),R=!0}catch(_){a.info("[McpServer] Server claim API \u4E0D\u53EF\u7528\uFF0C\u964D\u7EA7\u5230\u672C\u5730\u76F4\u63A5\u6807\u8BB0:",_),M=new Set(p)}if(M.size>0){const _=m.filter(y=>M.has(y.memoryUri));for(const y of _){const v=t.find(S=>S.id===y.memoryId);v&&(await this.memoryStore.updateMemory({uri:v.uri,memory_type:"project_memory",memory_status:"updating",updating_agent_id:e,file_md5_map:v.file_md5_map,last_check_time:v.last_check_time,bound_files:v.bound_files}),this.activeLeaseUris.add(v.uri))}R&&M.size>0&&this.startLeaseRenewal();const E=_.map(y=>`- ${y.memoryUri} (\u6587\u4EF6: ${y.changedFiles.join(", ")})`).join(`
|
|
33
33
|
`);return{msgId:`memory-file-change-${Date.now()}`,senderId:"MCP-System",senderName:"\u7CFB\u7EDF",receiverId:e,content:`\u68C0\u6D4B\u5230\u4EE5\u4E0B ${_.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
34
|
|
|
35
|
-
${
|
|
35
|
+
${E}
|
|
36
36
|
|
|
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:_.map(y=>y.memoryUri),fileChanges:_.map(y=>{const
|
|
38
|
-
`:"",
|
|
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:_.map(y=>y.memoryUri),fileChanges:_.map(y=>{const v=t.find(S=>S.id===y.memoryId);return{uri:y.memoryUri,boundFiles:v?.bound_files??[],fileStatuses:y.fileStatuses,changedFiles:y.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=f.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<x){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,x),this.fileChangeNotifyHistory.size>H){const s=this.fileChangeNotifyHistory.size-H;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(),h=Object.keys(o).length===0;let c=!1;for(const d of r.bound_files)try{const u=await this.calculateFileMd5(d);if(u===null){const T=f.resolve(l,d);a.info(`[McpServer] MD5 \u8BA1\u7B97\u8FD4\u56DE null: ${d} -> ${T} (workspace=${l})`);const C=o[d];C?await this.verifyFileNotExist(T)?(s.push({path:d,status:"not_found",serverMd5:C}),i.push(`${d}\uFF08\u6587\u4EF6\u627E\u4E0D\u5230 Server: ${C}\uFF09`),r.bound_files&&(r.bound_files=r.bound_files.filter(m=>m!==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]=u;const g=o[d];g?g!==u?(a.info(`[McpServer] \u6587\u4EF6\u53D8\u66F4: ${d} old=${g} new=${u} (workspace=${l})`),s.push({path:d,status:"content_changed",localMd5:u,serverMd5:g}),i.push(`${d}\uFF08\u5185\u5BB9\u53D8\u66F4 \u672C\u5730: ${u} Server: ${g}\uFF09`)):s.push({path:d,status:"no_change"}):(s.push({path:d,status:"no_change"}),c=!0,a.info(`[McpServer] \u5EFA\u7ACB\u5355\u6587\u4EF6\u57FA\u7EBF: ${d} new=${u} (workspace=${l}, memory=${r.uri})`))}catch(u){a.info(`[McpServer] \u8BA1\u7B97\u6587\u4EF6 MD5 \u5931\u8D25: ${d}`,u),s.push({path:d,status:"no_change"})}if(h&&Object.keys(n).length>0){r.file_md5_map=n,r.last_check_time=new Date().toISOString();continue}c&&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=f.resolve(i,e),n=f.resolve(i),o=f.resolve(s);return!o.startsWith(n+f.sep)&&o!==n?(a.warn(`[McpServer] calculateFileMd5: \u8DEF\u5F84\u9003\u9038\u88AB\u62D2\u7EDD: ${e}`),null):new Promise(l=>{const h=r("md5"),c=t(s);c.on("data",d=>h.update(d)),c.on("end",()=>l(h.digest("hex"))),c.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 $.promises.access(e,$.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=e.directMessages.filter(i=>i._awsServerMessage&&i.msgId),r=e.groupMessages.filter(i=>i._awsServerMessage&&i.msgId!==void 0);if(t.length===0&&r.length===0)return e;try{let i=null;t.length>0&&(i=await this.agentClient.markDmRead(t.map(c=>c.msgId)));const s=new Set,n=new Map;for(const c of r){if(!c.roomId){s.add(c.msgId);continue}const d=n.get(c.roomId)||[];d.push(c.msgId),n.set(c.roomId,d)}for(const[c,d]of n){const u=await this.agentClient.markGroupRead(c,d);for(const g of u)s.add(g)}const o=e.directMessages.filter(c=>!c._awsServerMessage||!c.msgId?!0:i?i.has(c.msgId):!0),l=e.groupMessages.filter(c=>!c._awsServerMessage||c.msgId===void 0?!0:s.has(c.msgId)),h=e.directMessages.length-o.length+e.groupMessages.length-l.length;h>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",h,e.directMessages.length-o.length,e.groupMessages.length-l.length);for(const c of o)delete c._awsServerMessage;for(const c of l)delete c._awsServerMessage;return{directMessages:o,groupMessages:l}}catch(i){a.warn("[McpServer] \u6D88\u606F\u4EA4\u4ED8\u786E\u8BA4\u5931\u8D25\uFF0C\u964D\u7EA7\u4E3A\u76F4\u63A5\u4EA4\u4ED8: %s",i instanceof Error?i.message:String(i));for(const s of e.directMessages)delete s._awsServerMessage;for(const s of e.groupMessages)delete s._awsServerMessage;return e}}async hydrateUnreadMessagesFromServer(e={}){try{const t=await this.agentClient.fetchUnreadMessages({blockIfEmpty:e.blockIfEmpty??!1,blockTimeoutMs:e.blockTimeoutMs,includePipelineTasks:e.includePipelineTasks});if(t.directMessages.length===0&&t.groupMessages.length===0)return!0;const r=t.directMessages.filter(s=>this.shouldBufferIncomingMessage(s)),i=t.groupMessages.filter(s=>this.shouldBufferIncomingMessage(s));return r.forEach(s=>{s._awsServerMessage=!0,this.messageBuffer.push(s)}),i.forEach(s=>{s._awsServerMessage=!0,this.messageBuffer.push(s)}),a.info(`[McpServer] \u5DF2\u8865\u62C9\u672A\u8BFB\u6D88\u606F\uFF0C\u79C1\u804A: ${r.length}\uFF0C\u7FA4\u804A: ${i.length}`),!0}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)"),!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}
|
|
38
|
+
`:"",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
|
|
39
|
+
${i}\u53D8\u5316\u7C7B\u578B: ${s}
|
|
40
40
|
\u89E6\u53D1\u65F6\u95F4: ${n}
|
|
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: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)"}`),this.messageBuffer.push(e),!this.isGroupMessage(e)&&e.force===!0&&this.agentClient.notifyBridgeForceMessage().catch(()=>{})}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=f.join(
|
|
42
|
-
lines=${
|
|
43
|
-
Use read_background_output(task_id="${
|
|
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: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)"}`),e._awsServerMessage=!0,this.messageBuffer.push(e),!this.isGroupMessage(e)&&e.force===!0&&this.agentClient.notifyBridgeForceMessage().catch(()=>{})}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=f.join(F.homedir(),".acode","todos",`${this.sanitizeAgentIdForTodoFile(e)}.json`);let r;try{r=await $.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=f.join(F.homedir(),".acode","bg-tasks",this.sanitizeAgentIdForTodoFile(e),"state.json");let r;try{r=await $.promises.readFile(t,"utf-8")}catch(c){if(c?.code==="ENOENT")return null;throw c}const i=JSON.parse(r),s=Array.isArray(i.tasks)?i.tasks:[],n=s.filter(c=>c&&typeof c=="object"&&typeof c.taskId=="string"&&c.status!=="running"&&!c.notified);if(n.length===0)return null;const o=n.slice(0,5),l=o.map(c=>`[bg:${c.taskId}] ${c.status} (exitCode=${c.exitCode??"?"}) ${c.commandPreview??""}
|
|
42
|
+
lines=${c.outputLineCount??0} bytes=${c.outputBytes??0}
|
|
43
|
+
Use read_background_output(task_id="${c.taskId}", mode="tail", lines=50) for full output.`).join(`
|
|
44
44
|
|
|
45
45
|
`),h=n.length>o.length?`
|
|
46
46
|
|
|
47
|
-
\uFF08\u53E6\u6709 ${n.length-o.length} \u6761\u5DF2\u5B8C\u6210\uFF0C\u8BF7\u7528 ListBackgroundCommands \u67E5\u770B\uFF09`:"";return await $.promises.writeFile(t,JSON.stringify({...
|
|
48
|
-
${l}${h}`,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
|
|
47
|
+
\uFF08\u53E6\u6709 ${n.length-o.length} \u6761\u5DF2\u5B8C\u6210\uFF0C\u8BF7\u7528 ListBackgroundCommands \u67E5\u770B\uFF09`:"";return await $.promises.writeFile(t,JSON.stringify({...i,updatedAt:Date.now(),tasks:s.map(c=>n.some(d=>d.taskId===c.taskId)?{...c,notified:!0}:c)},null,2),"utf-8").catch(c=>{a.warn("[McpServer] \u6807\u8BB0\u540E\u53F0\u4EFB\u52A1\u5DF2\u901A\u77E5\u5931\u8D25: %s",c?.message??c)}),{msgId:`bg-notif-${Date.now()}`,senderId:"MCP-System",senderName:"ACode Background",receiverId:e,content:`[Background commands completed]
|
|
48
|
+
${l}${h}`,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 G;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: ${O.map(t=>t.name).join(", ")}`),a.info(`[McpServer] \u5DE5\u4F5C\u76EE\u5F55: ${process.env.AWS_WORKSPACE_PATH||process.cwd()}`),j&&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++,N>0&&t>=N){if(j){a.warn(`[McpServer] \u6CE8\u518C\u8D85\u8FC7\u6700\u5927\u91CD\u8BD5\u6B21\u6570 (${N}\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(Z,Q);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 (${N}\u6B21)\uFF0C\u653E\u5F03\u542F\u52A8: ${i}`)}a.warn(`[McpServer] \u6CE8\u518C\u5931\u8D25\uFF0C\u7B49\u5F85\u91CD\u8BD5... (${t}/${N}): ${i}`),await this.delay(X)}}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}),this.activelySyncProfile();return}this.agentClient.start(this.handleIncomingMessage.bind(this),{pollMode:!1,profileHandler:e}),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
49
|
|