Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions electron/backend/memory/access.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,41 @@ class AgentAccess {
return { ok: true, command: cmd, steps, configPath: adapter.configPath, instructionPath: adapter.instruction ? adapter.instruction.path : "" };
}

/** 存量收敛:把旧版写入的「MCP 宿主=主程序 exe」改成独立命名的宿主。
* 只动我们自己的受控块,且仅当块里 command 仍是主程序 exe 时才重写——
* 用户手改成别的命令不碰。应用升级后主程序换了文件,宿主链接会被重建,
* 但配置里指的还是旧名字,不收敛的话下次升级仍会被 NSIS 的映像名判定挡住。 */
convergeHost(cfgAgents) {
const changed = [];
try {
for (const adapter of agents.list(cfgAgents)) {
if (adapter.format !== "yml-cordis-patch") continue;
const desired = verify.connectionCommand({
appPath: this.appPath,
resourcesPath: this.resourcesPath,
agentId: adapter.id,
}).command;
if (!desired) continue;
const current = inject.cordisManagedCommand(adapter);
if (current) {
if (current === desired) continue;
// 只收敛「宿主就是主程序」这一种旧形态,其余差异留给用户
if (!/AgentHub\.exe$/i.test(current)) continue;
const r = this.injectOne(adapter.id, cfgAgents);
changed.push({ id: adapter.id, ok: !!r.ok, from: current, to: desired, message: r.message || "" });
continue;
}
// 受控块之前的旧版插入块:同样指为主程序,只改它的 command 一行
const legacy = inject.legacyCordisCommand(adapter);
if (!legacy || legacy === desired) continue;
if (!/AgentHub\.exe$/i.test(legacy)) continue;
const r = inject.rewriteLegacyCordisCommand(adapter, desired);
changed.push({ id: adapter.id, ok: !!r.ok, from: legacy, to: desired, message: r.message || r.action || "" });
}
} catch { /* 收敛失败不影响启动 */ }
return changed;
}

uninjectOne(id, cfgAgents) {
const adapter = agents.list(cfgAgents).find((a) => a.id === id);
if (!adapter) return { ok: false, message: `未知 Agent:${id}` };
Expand Down
7 changes: 7 additions & 0 deletions electron/backend/memory/index.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -253,6 +253,13 @@ function init() {
appPath: electron && electron.app ? electron.app.getPath("exe") : process.execPath,
resourcesPath: electron && electron.app && process.resourcesPath ? process.resourcesPath : undefined,
});
// 启动即收敛一次:旧版把 MCP 宿主写成主程序 exe,常驻的 MCP 子进程会被 NSIS 按映像名
// 误判成「应用仍在运行」,导致「重启并更新」永远装不上(错误码 2)。只重写我们自己的受控块。
try {
const converged = access.convergeHost(settings().agents);
const failed = converged.filter((c) => !c.ok);
if (failed.length) console.warn("[memory] 宿主改名收敛失败:", failed.map((c) => `${c.id}: ${c.message}`).join("; "));
} catch { /* 收敛失败不阻塞启动 */ }
llm = new LlmClient({
service,
getConfig: () => service.flat(),
Expand Down
81 changes: 80 additions & 1 deletion electron/backend/memory/inject.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -455,10 +455,89 @@ function cordisHasEntry(adapter) {
return null;
}

/** 受控块里当前写入的 command(没注入过返回 null)。
* 供「宿主进程独立命名」的存量收敛判定:只读我们自己的块,不解析用户 patch 的其余部分。 */
function cordisManagedCommand(adapter) {
for (const file of cordisPatchFiles(adapter)) {
let text = "";
try {
text = fs.readFileSync(file, "utf8");
} catch {
continue;
}
const begin = text.indexOf(CORDIS_BEGIN);
if (begin < 0) continue;
const end = text.indexOf(CORDIS_END, begin);
const block = end < 0 ? text.slice(begin) : text.slice(begin, end);
const m = /^\s*command:\s*'((?:[^']|'')*)'\s*$/m.exec(block);
if (m) return m[1].replace(/''/g, "'");
}
return null;
}

// 旧版(受控注释之前)写入的 insert 块:没有 begin/end 标记,条目形如
// - insert:
// - id: agenthub-memory-mcp
// name: '@deepseek-ai/dsh-mcp-client'
// config:
// command: 'D:\AgentHub\AgentHub.exe'
// 这类块同样会因为「宿主=主程序」被 NSIS 误判,升级装不上。收敛时只改它的 command 一行,
// 不动块内其它字段、不动用户 patch 的其余内容。
const LEGACY_ID_RE = /^\s*-\s+id:\s*agenthub-memory-mcp\s*$/m;

/** 旧块里的 command 现值(没有旧块返回 null)。 */
function legacyCordisCommand(adapter) {
for (const file of cordisPatchFiles(adapter)) {
let text = "";
try {
text = fs.readFileSync(file, "utf8");
} catch {
continue;
}
if (text.includes(CORDIS_BEGIN)) continue; // 已经是受控块,交给 cordisManagedCommand
const m = LEGACY_ID_RE.exec(text);
if (!m) continue;
// 只在这条 id 之后的有限窗口里找 command,避免误改别的 insert 条目
const window = text.slice(m.index, m.index + 1200);
const c = /^(\s*)command:\s*'((?:[^']|'')*)'\s*$/m.exec(window);
if (c) return c[2].replace(/''/g, "'");
}
return null;
}

/** 把旧块的 command 改成 nextCommand;只替换那一行,返回 {ok, file, backup, from}。 */
function rewriteLegacyCordisCommand(adapter, nextCommand) {
for (const file of cordisPatchFiles(adapter)) {
let text = "";
try {
text = fs.readFileSync(file, "utf8");
} catch {
continue;
}
if (text.includes(CORDIS_BEGIN)) continue;
const m = LEGACY_ID_RE.exec(text);
if (!m) continue;
const windowStart = m.index;
const window = text.slice(windowStart, windowStart + 1200);
const c = /^(\s*)command:\s*'((?:[^']|'')*)'\s*$/m.exec(window);
if (!c) continue;
const from = c[2].replace(/''/g, "'");
if (from === nextCommand) return { ok: true, action: "noop", file, from };
const lineStart = windowStart + c.index;
const lineEnd = lineStart + c[0].length;
const nextLine = `${c[1]}command: ${ymlString(nextCommand)}`;
const bak = backupFile(file);
writeAtomic(file, text.slice(0, lineStart) + nextLine + text.slice(lineEnd));
return { ok: true, action: "rewrote-legacy", file, backup: bak, from };
}
return { ok: false, action: "not-found", message: "未找到旧版记忆中枢插入块" };
}

module.exports = {
BLOCK_BEGIN, BLOCK_END, SERVER_KEY, INSTRUCTION_BLOCK,
injectBlock, removeBlock, hasBlock,
injectJsonConfig, uninjectJsonConfig, injectTomlConfig, uninjectTomlConfig,
injectCordisPatch, uninjectCordisPatch, cordisHasEntry,
injectCordisPatch, uninjectCordisPatch, cordisHasEntry, cordisManagedCommand,
legacyCordisCommand, rewriteLegacyCordisCommand,
tomlHasEntry, jsonHasEntry, backupFile, writeAtomic, tomlBlockRange, tomlString,
};
51 changes: 49 additions & 2 deletions electron/backend/memory/verify.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -55,10 +55,57 @@ function resolveHostExe(appPath) {
return appPath || null;
}

// MCP 宿主进程名必须与主程序**不同名**。
//
// 为什么:electron-builder 的 NSIS 安装/卸载阶段按「映像名」(AgentHub.exe)判定应用是否仍在运行,
// 不看路径也不看命令行。而记忆中枢的 MCP 桥是常驻进程——DSH / Cursor / Claude 等客户端长期持有它。
// 若它用主程序 exe 启动,就会出现:应用自己「重启并更新」时主进程已干净退出(crash.log 有
// `quit exitCode=0`),安装器却因为还挂着一个同名但不同用途的 MCP 子进程而拒绝卸载旧文件,
// 弹出「Failed to uninstall old application files. Please try running the installer again.: 2」,
// 升级永远装不上。给它一个独立名字,动作照旧,判定不再撞车。
const MCP_HOST_BASENAME = "agenthub-mcp";

/** 与主程序同内容、不同名字的 MCP 宿主可执行路径(仅 Windows 需要,其余平台原样返回)。 */
function resolveMcpHostExe(appPath) {
if (!appPath || process.platform !== "win32") return appPath;
if (!/\.exe$/i.test(appPath) || !fs.existsSync(appPath)) return appPath;
const dst = path.join(path.dirname(appPath), `${MCP_HOST_BASENAME}.exe`);
try {
const src = fs.statSync(appPath);
if (fs.existsSync(dst)) {
const cur = fs.statSync(dst);
// 同 inode 即同一份文件(硬链接),无需重建;应用升级换过主程序后 inode 变化
if (cur.ino === src.ino && cur.size === src.size) return dst;
try {
fs.unlinkSync(dst);
} catch {
// 旧宿主正被 MCP 客户端占用(指向运行中映像的链接删不掉,EPERM):
// 它仍是能跑 Node 的同一套 Electron,继续用旧链接比另造新名字更干净,
// 等旧进程退出后下一次启动会自行换成新主程序。
return dst;
}
}
try {
fs.linkSync(appPath, dst); // 同卷硬链接:毫秒级、零字节拷贝
return dst;
} catch {
// 跨卷 / 非 NTFS / 目录不可写:退回复制(慢但只发生一次)
try {
fs.copyFileSync(appPath, dst);
return dst;
} catch {
return appPath; // 都失败则保持旧行为,不阻断接入
}
}
} catch {
return appPath;
}
}

// 注入预览/实际写入用的命令行(含路径可达性预检结果)。
// opts.agentId:写入具体 Agent 配置时必须带上,桥用它上报心跳归属(三级校验按 adapter.id 匹配)。
function connectionCommand(opts) {
const host = resolveHostExe(opts.appPath);
const host = resolveMcpHostExe(resolveHostExe(opts.appPath));
const bridge = resolveBridge(opts.appPath, opts.resourcesPath);
const env = { ELECTRON_RUN_AS_NODE: "1" };
if (opts.agentId) env.AGENTHUB_AGENT = opts.agentId;
Expand Down Expand Up @@ -257,4 +304,4 @@ async function verifyAll(opts) {
return out;
}

module.exports = { verifyAgent, verifyAll, verifyConfig, handshake, connectionCommand, renderSnippet, resolveBridge, resolveHostExe, bridgeCandidates };
module.exports = { verifyAgent, verifyAll, verifyConfig, handshake, connectionCommand, renderSnippet, resolveBridge, resolveHostExe, resolveMcpHostExe, bridgeCandidates };
Loading