Fix: Make the MCP command sentinel robust and fail stalled downloads fast
Re-verified every finding of the 2026-10-25 MCP test report against the source and then end-to-end on the Debug instance, and fixed the ones that live on the server. P1/P3/P4 share one root cause: the sentinel was appended to the command line, so any command that swallows the rest of its line (rem, cmd /c, if, for) swallowed the sentinel too and the call always timed out. On ConPTY clients the command and the sentinel are now sent as two lines, the sentinel prints %errorlevel% (whose echoed text is a literal template, not digits) so folding echo can no longer be mistaken for the sentinel, and FindSentinel returns the real exit code (9009, 1, 0, ...) instead of 0/1. Old non-PTY clients keep the single-line form, since their echo skipping depends on the write length. ConPTY also returns a rendered screen stream rather than a byte stream, so stripped VT sequences leave duplicate text behind; output cleaning now cuts through the echoed command line, strips the echoed sentinel line and erases any leftover sentinel text by its per-command nonce. StripAnsi no longer leaves the backslash of an OSC terminated by ST. A terminal session destroyed by a timeout used to report the same "not found" text as a typo in the session id; a 600s tombstone now says what happened instead. download_file gets a stall watchdog: no data for 60s fails with a clear message and releases the host, where a missing remote path used to hold the whole host for the full 600s default timeout. Also corrects the get_activity_history annotation (it does reach the remote host), completes the -32007/-32008/-32009 error table, documents the sentinel design in Mcp_Design.md 12.1, and corrects the report's claim that the tools blocked during a transfer are local DB reads -- they are remote machine-manager fetches, and purely server-local tools are unaffected. Co-Authored-By: deepseek-flash
This commit is contained in:
1 parent
1c5fab1645
commit
eaa10cc7d3
5 files changed
+486
-71
No files matched your search
+267
-65
@@ -1122,7 +1122,7 @@ Json::Value BuildExecCommandOutputSchema() {
|
||||
|
||||
Json::Value exitProp(Json::objectValue);
|
||||
exitProp["type"] = "integer";
|
||||
exitProp["description"] = u8"退出码:0=成功、1=非零退出、-1=未知(进程异常退出)";
|
||||
exitProp["description"] = u8"退出码:ConPTY 客户端为命令的真实退出码;老客户端(非 PTY)仅区分 0/非 0;-1=未知(进程异常退出)";
|
||||
props["exit_code"] = exitProp;
|
||||
|
||||
Json::Value schema(Json::objectValue);
|
||||
@@ -2624,24 +2624,139 @@ static std::string StripAnsi(const std::string& s) {
|
||||
++i; // 吞 ESC
|
||||
if (i < s.size() && s[i] == '[') { // CSI ... 结尾 @–~
|
||||
while (++i < s.size() && !(s[i] >= '@' && s[i] <= '~')) {}
|
||||
} else if (i < s.size() && s[i] == ']') { // OSC ... 结尾 BEL/ESC
|
||||
} else if (i < s.size() && s[i] == ']') { // OSC ... 结尾 BEL/ST(ESC \)
|
||||
while (++i < s.size() && s[i] != '\x07' && s[i] != '\x1b') {}
|
||||
// ST 是两字节 "ESC \":这里停在 ESC 上,须把 '\' 一起吞掉,否则会残留在输出里。
|
||||
if (i + 1 < s.size() && s[i] == '\x1b' && s[i + 1] == '\\') ++i;
|
||||
}
|
||||
// 其它单字节 ESC 序列吞掉当前字节即可(循环 ++i 会跳过它)
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// 去掉 ConPTY 把整行输入回显造成的噪声:echoedLine 是发送的哨兵命令行(含唯一 nonce),
|
||||
// 输出里若出现该行(连同其后换行)则整行剔除。非 PTY 老 ShellManager 已自行跳回显,
|
||||
// 找不到该行即无操作。echoedLine 含随机 nonce,命令真实输出不可能恰好相同。
|
||||
static std::string StripEchoedCommand(const std::string& s, const std::string& echoedLine) {
|
||||
if (echoedLine.empty() || s.empty()) return s;
|
||||
size_t p = s.find(echoedLine);
|
||||
if (p == std::string::npos) return s;
|
||||
size_t q = p + echoedLine.size();
|
||||
if (q < s.size() && s[q] == '\n') ++q; // CRLF 已归一为 \n
|
||||
return s.substr(0, p) + s.substr(q);
|
||||
// 去掉 ConPTY 把整行输入回显造成的噪声:line 是发送过的命令行(含唯一 nonce 或 "@echo off & "
|
||||
// 前缀),输出里若出现这段文本(连同其后的换行)则剔除。回显会被 80 列折行插入换行,
|
||||
// 所以比较时跳过 '\r'/'\n';随机 nonce/固定前缀保证命令真实输出不可能整行命中。
|
||||
// 只删第一处命中(输入回显只发生一次)。
|
||||
static void StripEchoedLine(std::string& s, const std::string& line) {
|
||||
if (line.empty() || s.empty()) return;
|
||||
const size_t n = s.size(), m = line.size();
|
||||
for (size_t i = 0; i < n; ++i) {
|
||||
size_t j = 0, k = i;
|
||||
while (j < m && k < n) {
|
||||
const char c = s[k];
|
||||
if (c == '\r' || c == '\n') { ++k; continue; }
|
||||
if (c != line[j]) break;
|
||||
++j; ++k;
|
||||
}
|
||||
if (j != m) continue;
|
||||
while (k < n && (s[k] == '\r' || s[k] == '\n')) ++k; // 连同回显行尾换行一起删
|
||||
s.erase(i, k - i);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// 把缓冲区开头一直删到回显行结束(含行尾换行)。ConPTY 起 shell 时会先回放启动画面与
|
||||
// 提示符(一长串空行 + "Microsoft Windows [Version ...]" + "C:\path>"),紧接着才是我们这行
|
||||
// 输入的回显;回显行即「真实输出的起点」,因此删到它结束可把启动噪声一并去掉。
|
||||
// 返回 false 表示没找到回显(例如客户端不回显),此时不动缓冲区。
|
||||
static bool CutThroughEchoedLine(std::string& s, const std::string& line) {
|
||||
if (line.empty() || s.empty()) return false;
|
||||
const size_t n = s.size(), m = line.size();
|
||||
for (size_t i = 0; i < n; ++i) {
|
||||
size_t j = 0, k = i;
|
||||
while (j < m && k < n) {
|
||||
const char c = s[k];
|
||||
if (c == '\r' || c == '\n') { ++k; continue; }
|
||||
if (c != line[j]) break;
|
||||
++j; ++k;
|
||||
}
|
||||
if (j != m) continue;
|
||||
while (k < n && (s[k] == '\r' || s[k] == '\n')) ++k;
|
||||
s.erase(0, k);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// 去掉开头的空行(启动画面残留 / 上一行命令尾部的空行)。
|
||||
static void TrimLeadingNewlines(std::string& s) {
|
||||
size_t i = 0;
|
||||
while (i < s.size() && (s[i] == '\r' || s[i] == '\n')) ++i;
|
||||
if (i) s.erase(0, i);
|
||||
}
|
||||
|
||||
// 擦掉输出里**残留**的哨兵文本。ConPTY 送回来的是「屏幕渲染流」而不是字节流:光标重绘
|
||||
// 会把同一行再输出一次,剥掉 VT 序列后同一段文字就重复出现。于是哨兵可能留有副本
|
||||
// (实测 `rem hello` 只剩哨兵、`cmd /c echo abc` 成了 "abc__MCP_DONE_x__0")。
|
||||
// nonce 每条命令随机生成,命令的真实输出不可能包含它,故按 nonce 文本擦除既彻底又安全。
|
||||
// 比较时跳过 '\r'/'\n'(折行回显);`%errorlevel%` 是回显模板本身,一并擦到行尾。
|
||||
static void StripSentinelText(std::string& s, const std::string& nonce) {
|
||||
if (nonce.empty() || s.empty()) return;
|
||||
const std::string marker = "__MCP_DONE_" + nonce + "__";
|
||||
size_t i = 0;
|
||||
while (i < s.size()) {
|
||||
size_t j = 0, k = i;
|
||||
while (j < marker.size() && k < s.size()) {
|
||||
const char c = s[k];
|
||||
if (c == '\r' || c == '\n') { ++k; continue; }
|
||||
if (c != marker[j]) break;
|
||||
++j; ++k;
|
||||
}
|
||||
if (j != marker.size()) { ++i; continue; }
|
||||
size_t end = k;
|
||||
if (end < s.size() && s[end] == '-') ++end;
|
||||
while (end < s.size() && s[end] >= '0' && s[end] <= '9') ++end;
|
||||
if (end < s.size() && s[end] == '%') // 回显模板 ...__%errorlevel%
|
||||
while (end < s.size() && s[end] != '\r' && s[end] != '\n') ++end;
|
||||
size_t begin = i; // 连带前面残留的 "echo "
|
||||
if (begin >= 5 && _strnicmp(s.c_str() + begin - 5, "echo ", 5) == 0) begin -= 5;
|
||||
s.erase(begin, end - begin);
|
||||
i = begin;
|
||||
}
|
||||
}
|
||||
|
||||
// 输入回显清洗(P4):PTY 下删「命令行」与「哨兵行」两处回显。非 PTY 只删哨兵行——
|
||||
// 老 ShellManager 在客户端按写入长度自行跳过回显,删命令行反而可能吃掉命令自身的输出
|
||||
// (如 `echo echo hello`)。
|
||||
static std::string StripEchoedInput(const std::string& s, bool isPty,
|
||||
const std::string& cmdLine, const std::string& sentLine,
|
||||
const std::string& nonce) {
|
||||
std::string out = s;
|
||||
bool cut = isPty && CutThroughEchoedLine(out, cmdLine);
|
||||
if (isPty && !cut) StripEchoedLine(out, cmdLine); // 没回显时退回按整行删
|
||||
StripEchoedLine(out, sentLine);
|
||||
StripSentinelText(out, nonce);
|
||||
TrimLeadingNewlines(out);
|
||||
return out;
|
||||
}
|
||||
|
||||
// 哨兵行有两种形态(见 docs/Mcp_Design.md §12.1):
|
||||
// - ConPTY(is_pty=true):命令与哨兵**分两行**下发。哨兵独立成行执行,于是 rem / cmd / c
|
||||
// exit / if / for 这类「吞行」命令不会连哨兵一起吞掉(P1);哨兵用 %errorlevel% 取真实
|
||||
// 退出码,回显文本里是字面 "%errorlevel%"、不是数字,FindSentinel 只认数字,折行回显再也
|
||||
// 不会被误判成哨兵(P3),也能返回真实退出码而非 0/1。
|
||||
// - 老 ShellManager(is_pty=false):客户端按写入字节数跳过回显,多写一行会吃掉上一行的
|
||||
// 输出,故仍用单行 && / || 形式(老客户端维持既有行为,已知不支持 rem / cmd /c)。
|
||||
static void BuildSentinelLines(bool isPty, const std::string& command, const std::string& nonce,
|
||||
std::string& cmdLine, std::string& sentLine) {
|
||||
if (!isPty) {
|
||||
cmdLine = command + " 2>&1 && echo __MCP_DONE_" + nonce + "__0 || echo __MCP_DONE_" + nonce + "__1";
|
||||
sentLine.clear();
|
||||
return;
|
||||
}
|
||||
cmdLine = "@echo off & " + command;
|
||||
sentLine = "echo __MCP_DONE_" + nonce + "__%errorlevel%";
|
||||
}
|
||||
|
||||
// 组包下发;cmdLine/sentLine 回传给调用方用于剔除输入回显。sentLine 为空表示单行形态。
|
||||
static void SendSentinelLines(context* subCtx, bool isPty, const std::string& command,
|
||||
const std::string& nonce, std::string& cmdLine, std::string& sentLine) {
|
||||
BuildSentinelLines(isPty, command, nonce, cmdLine, sentLine);
|
||||
UINT cp = isPty ? CP_UTF8 : 936;
|
||||
std::string wire = ToAnsi(cmdLine, cp) + "\r\n";
|
||||
if (!sentLine.empty()) wire += ToAnsi(sentLine, cp) + "\r\n";
|
||||
subCtx->Send2Client((BYTE*)wire.data(), (ULONG)wire.size());
|
||||
}
|
||||
|
||||
// 命令是否含控制字符(<0x20,含 \r\n)。\r\n 会把命令拆成多行:一次性 exec 里会绕过
|
||||
@@ -2712,15 +2827,10 @@ std::string BuildExecCommand(const Json::Value& id, const Json::Value& args, CMy
|
||||
|
||||
// 编码:ConPTY(UTF-8) / 老 cmd 管道(GBK)。哨兵为纯 ASCII,两种编码下字节一致。
|
||||
UINT cp = isPty ? CP_UTF8 : 936;
|
||||
// 哨兵命令行:@echo off 仅 ConPTY 需要(抑制回显噪声);老 ShellManager 已自行跳过回显,
|
||||
// 加 @echo off 反而破坏其回显跳过逻辑。&&/|| 取命令真实退出码(%errorlevel% 在复合句中
|
||||
// 是解析期展开、已过期,故用控制操作符)。哨兵为随机串,命令输出不可能恰好包含。
|
||||
std::string line;
|
||||
if (isPty) line += "@echo off & ";
|
||||
line += command;
|
||||
line += " 2>&1 && echo __MCP_DONE_" + nonce + "__0 || echo __MCP_DONE_" + nonce + "__1";
|
||||
std::string wireLine = ToAnsi(line, cp) + "\r\n";
|
||||
subCtx->Send2Client((BYTE*)wireLine.data(), (ULONG)wireLine.size());
|
||||
// 哨兵形态见 BuildSentinelLines:PTY 下命令与哨兵分两行下发(吞行命令不再超时),
|
||||
// 老 ShellManager 保持单行 && / || 形式(其客户端按写入长度跳回显)。
|
||||
std::string cmdLine, sentLine;
|
||||
SendSentinelLines(subCtx, isPty, command, nonce, cmdLine, sentLine);
|
||||
|
||||
std::vector<BYTE> raw;
|
||||
int exitCode = -1;
|
||||
@@ -2740,7 +2850,7 @@ std::string BuildExecCommand(const Json::Value& id, const Json::Value& args, CMy
|
||||
size_t p = 0;
|
||||
while ((p = stdoutStr.find("\r\n", p)) != std::string::npos)
|
||||
stdoutStr.erase(p, 1);
|
||||
stdoutStr = StripEchoedCommand(stdoutStr, line);
|
||||
stdoutStr = StripEchoedInput(stdoutStr, isPty, cmdLine, sentLine, nonce);
|
||||
stdoutStr = TrimRight(stdoutStr);
|
||||
}
|
||||
|
||||
@@ -2983,6 +3093,7 @@ std::string BuildGetServerStatus(const Json::Value& id, CMy2015RemoteDlg* parent
|
||||
// ===== P4:持久远程终端(terminal_open / terminal_exec / terminal_close)=====
|
||||
|
||||
static const int kTermIdleTimeoutSec = 300; // 持久终端 idle 回收超时(秒)
|
||||
static const int kTermTombstoneSec = 600; // 「终端被销毁」墓碑保留时长(秒),供后续报错文案用
|
||||
|
||||
// 共享前置:校验 McpTerminal && !readonly → 解析 id → FindMainContext → 拒绝 LNX/MAC。
|
||||
// 成功返回 true 并输出 devId/ctx;失败时 errJson 已写入对应 JSON 错误串。
|
||||
@@ -3016,24 +3127,19 @@ static bool ResolveTerminalSessionHost(const Json::Value& id, const Json::Value&
|
||||
return true;
|
||||
}
|
||||
|
||||
// 发送哨兵命令行(复用 exec_command 的编码/哨兵逻辑);返回所发送的完整命令行,
|
||||
// 发送哨兵命令行(复用 exec_command 的哨兵逻辑);回传所发送的两行,
|
||||
// 供调用方剔除 ConPTY 把输入整行回显造成的噪声。cp 由 isPty 决定。
|
||||
static std::string SendTerminalCommandLine(context* subCtx, bool isPty, const std::string& command,
|
||||
const std::string& nonce) {
|
||||
UINT cp = isPty ? CP_UTF8 : 936;
|
||||
std::string line;
|
||||
if (isPty) line += "@echo off & ";
|
||||
line += command;
|
||||
line += " 2>&1 && echo __MCP_DONE_" + nonce + "__0 || echo __MCP_DONE_" + nonce + "__1";
|
||||
std::string wireLine = ToAnsi(line, cp) + "\r\n";
|
||||
subCtx->Send2Client((BYTE*)wireLine.data(), (ULONG)wireLine.size());
|
||||
return line;
|
||||
static void SendTerminalCommandLine(context* subCtx, bool isPty, const std::string& command,
|
||||
const std::string& nonce,
|
||||
std::string& cmdLine, std::string& sentLine) {
|
||||
SendSentinelLines(subCtx, isPty, command, nonce, cmdLine, sentLine);
|
||||
}
|
||||
|
||||
// 输出清洗(复用 exec_command 尾部逻辑):raw → UTF-8 → 剥 ANSI → CRLF 归一 →
|
||||
// 去 ConPTY 回显命令行 → TrimRight。
|
||||
static std::string CleanTerminalOutput(const std::vector<BYTE>& raw, UINT cp,
|
||||
const std::string& echoedLine) {
|
||||
// 去输入回显 → TrimRight。
|
||||
static std::string CleanTerminalOutput(const std::vector<BYTE>& raw, UINT cp, bool isPty,
|
||||
const std::string& cmdLine, const std::string& sentLine,
|
||||
const std::string& nonce) {
|
||||
std::string stdoutStr;
|
||||
if (!raw.empty()) {
|
||||
std::string rawStr((const char*)raw.data(), raw.size());
|
||||
@@ -3041,7 +3147,7 @@ static std::string CleanTerminalOutput(const std::vector<BYTE>& raw, UINT cp,
|
||||
size_t p = 0;
|
||||
while ((p = stdoutStr.find("\r\n", p)) != std::string::npos)
|
||||
stdoutStr.erase(p, 1);
|
||||
stdoutStr = StripEchoedCommand(stdoutStr, echoedLine);
|
||||
stdoutStr = StripEchoedInput(stdoutStr, isPty, cmdLine, sentLine, nonce);
|
||||
stdoutStr = TrimRight(stdoutStr);
|
||||
}
|
||||
return stdoutStr;
|
||||
@@ -3124,7 +3230,7 @@ Json::Value BuildTerminalExecOutputSchema() {
|
||||
props["stdout"] = stdoutProp;
|
||||
Json::Value exitProp(Json::objectValue);
|
||||
exitProp["type"] = "integer";
|
||||
exitProp["description"] = u8"退出码:0=成功、1=非零退出、-1=未知(进程异常退出)";
|
||||
exitProp["description"] = u8"退出码:ConPTY 客户端为命令的真实退出码;老客户端(非 PTY)仅区分 0/非 0;-1=未知(进程异常退出)";
|
||||
props["exit_code"] = exitProp;
|
||||
Json::Value schema(Json::objectValue);
|
||||
schema["type"] = "object";
|
||||
@@ -3259,10 +3365,25 @@ std::string BuildTerminalExec(const Json::Value& id, const Json::Value& args, CM
|
||||
|
||||
context* subCtx = nullptr;
|
||||
bool isPty = false;
|
||||
if (!mcp.BeginTermCommand(devId, sessionId, command, nonce, subCtx, isPty))
|
||||
return BuildError(id, -32002, "Terminal session not found, not ready, or busy: " + sessionId);
|
||||
int begin = mcp.BeginTermCommand(devId, sessionId, command, nonce, subCtx, isPty);
|
||||
if (begin != 0) {
|
||||
// 区分「会话被超时/退出/关闭销毁」与「session_id 写错」「另一条命令在飞」(评审 P1)。
|
||||
std::string destroyed = mcp.DescribeTermDestroyed(devId, sessionId);
|
||||
if (!destroyed.empty())
|
||||
return BuildError(id, -32002, destroyed);
|
||||
if (begin == 4)
|
||||
return BuildError(id, -32003, "Device busy: another terminal_exec is already running for this session");
|
||||
if (begin == 2)
|
||||
return BuildError(id, -32002, "Terminal session_id mismatch: " + sessionId);
|
||||
if (begin == 3)
|
||||
return BuildError(id, -32002, "Terminal session is not ready yet: " + sessionId);
|
||||
if (begin == 5)
|
||||
return BuildError(id, -32002, "Terminal session is already closing: " + sessionId);
|
||||
return BuildError(id, -32002, "Terminal session not found: " + sessionId + " (call terminal_open first)");
|
||||
}
|
||||
|
||||
std::string sentLine = SendTerminalCommandLine(subCtx, isPty, command, nonce);
|
||||
std::string cmdLine, sentLine;
|
||||
SendTerminalCommandLine(subCtx, isPty, command, nonce, cmdLine, sentLine);
|
||||
|
||||
std::vector<BYTE> raw;
|
||||
int exitCode = -1;
|
||||
@@ -3276,7 +3397,8 @@ std::string BuildTerminalExec(const Json::Value& id, const Json::Value& args, CM
|
||||
subCtx->CancelIO();
|
||||
}
|
||||
|
||||
std::string stdoutStr = CleanTerminalOutput(raw, isPty ? CP_UTF8 : 936, sentLine);
|
||||
std::string stdoutStr = CleanTerminalOutput(raw, isPty ? CP_UTF8 : 936, isPty, cmdLine, sentLine,
|
||||
nonce);
|
||||
|
||||
// 审计:命令执行(不可关闭)。
|
||||
if (parent) {
|
||||
@@ -4508,6 +4630,9 @@ std::string BuildDownloadFile(const Json::Value& id, const Json::Value& args, CM
|
||||
}
|
||||
|
||||
const char* msg = (error == 1002) ? "Timeout waiting for file transfer"
|
||||
: (error == 1004) ? "File transfer stalled: no data received for 60s "
|
||||
"(the remote path is probably missing or inaccessible; "
|
||||
"verify it with list_files first)"
|
||||
: (error == 1001) ? "Path traversal detected in received path"
|
||||
: (error == 1003) ? "Connection lost: the transfer sub-connection closed"
|
||||
: (error == FEV2_HASH_MISMATCH) ? "File SHA-256 verification failed"
|
||||
@@ -6187,11 +6312,14 @@ std::string DispatchSingleHostTool(const Json::Value& id, const std::string& too
|
||||
|
||||
// ===== P3:exec_command 哨兵检测与终端会话 =====
|
||||
|
||||
// 在原始 shell 输出字节流中定位哨兵(纯 ASCII,编码无关)。真实哨兵由 echo 单独输出、独占
|
||||
// 一行(前面是 \n 或缓冲区开头);而 ConPTY 会把整条命令行回显进输出流,哨兵字样嵌在
|
||||
// "&& echo ... || echo ..." 里、前面是空格。据此从后往前找「行首命中」,排除回显行误判:
|
||||
// 否则回显包先于命令输出单独到达时,rfind 会命中回显里的 __1 提前结束、截断真实输出。
|
||||
// 老 ShellManager 已自行跳过回显,输出里只有真实哨兵(仍为行首)。命中 __0 → exit 0;__1 → exit 1。
|
||||
// 在原始 shell 输出字节流中定位哨兵(纯 ASCII,编码无关)。哨兵后紧跟退出码数字(可带负号)。
|
||||
//
|
||||
// ConPTY 会把输入整行回显进输出流,因此「哨兵必须独占行首」这条旧规则反而会把真实哨兵
|
||||
// 排除掉(命令最后一行没有换行时哨兵会接在其后),再往前命中回显里的 &&/|| 片段,得到
|
||||
// 错误的退出码(评审 P3,`ver` → exit_code=1)。现在两种哨兵形态都能安全地不依赖行首:
|
||||
// - 新形态(ConPTY):回显文本里是字面 "%errorlevel%",不是数字,天然不可能命中;
|
||||
// - 老形态(非 PTY):回显由客户端按写入长度跳过,且回显中的片段在真实哨兵之前。
|
||||
// 故从后往前找第一个「标记 + 数字」即可。
|
||||
static bool FindSentinel(const std::vector<BYTE>& buf, const std::string& nonce,
|
||||
size_t& pos, int& exitCode) {
|
||||
std::string marker = "__MCP_DONE_" + nonce + "__";
|
||||
@@ -6201,11 +6329,17 @@ static bool FindSentinel(const std::vector<BYTE>& buf, const std::string& nonce,
|
||||
while (true) {
|
||||
size_t p = s.rfind(marker, from);
|
||||
if (p == std::string::npos) return false;
|
||||
bool lineStart = (p == 0) || (s[p - 1] == '\n') || (s[p - 1] == '\r');
|
||||
size_t digitPos = p + marker.size();
|
||||
if (lineStart && digitPos < s.size() &&
|
||||
(s[digitPos] == '0' || s[digitPos] == '1')) {
|
||||
exitCode = (s[digitPos] == '0') ? 0 : 1;
|
||||
size_t q = p + marker.size();
|
||||
bool neg = false;
|
||||
if (q < s.size() && s[q] == '-') { neg = true; ++q; }
|
||||
size_t digits = q;
|
||||
long long v = 0;
|
||||
while (q < s.size() && s[q] >= '0' && s[q] <= '9' && q - digits < 9) {
|
||||
v = v * 10 + (s[q] - '0');
|
||||
++q;
|
||||
}
|
||||
if (q > digits) {
|
||||
exitCode = (int)(neg ? -v : v);
|
||||
pos = p;
|
||||
return true;
|
||||
}
|
||||
@@ -6356,17 +6490,47 @@ bool CMcpServer::BeginTermOpen(uint64_t device_id, const std::string& sessionId)
|
||||
return true;
|
||||
}
|
||||
|
||||
bool CMcpServer::BeginTermCommand(uint64_t device_id, const std::string& sessionId,
|
||||
const std::string& command, const std::string& nonce,
|
||||
context*& subCtx, bool& isPty) {
|
||||
// 墓碑:记下会话被销毁的原因,供后续 terminal_exec 给出可区分文案。
|
||||
// 调用方必须持有 m_TermMutex。会话不存在时记录是为了让「上一次超时后用户重试」能看懂。
|
||||
void CMcpServer::MarkTermDestroyedLocked(uint64_t device_id, const std::string& sessionId,
|
||||
const std::string& reason) {
|
||||
if (sessionId.empty()) return;
|
||||
TermDestroyedInfo info;
|
||||
info.sessionId = sessionId;
|
||||
info.reason = reason;
|
||||
info.expiry = std::chrono::steady_clock::now() + std::chrono::seconds(kTermTombstoneSec);
|
||||
m_TermDestroyed[device_id] = std::move(info);
|
||||
// 顺手清理过期项(条目极少,线性清一遍即可)
|
||||
auto now = std::chrono::steady_clock::now();
|
||||
for (auto it = m_TermDestroyed.begin(); it != m_TermDestroyed.end(); ) {
|
||||
if (it->second.expiry <= now) it = m_TermDestroyed.erase(it);
|
||||
else ++it;
|
||||
}
|
||||
}
|
||||
|
||||
std::string CMcpServer::DescribeTermDestroyed(uint64_t device_id, const std::string& sessionId) {
|
||||
std::lock_guard<std::mutex> lk(m_TermMutex);
|
||||
auto it = m_TermDestroyed.find(device_id);
|
||||
if (it == m_TermDestroyed.end()) return "";
|
||||
if (std::chrono::steady_clock::now() >= it->second.expiry) {
|
||||
m_TermDestroyed.erase(it);
|
||||
return "";
|
||||
}
|
||||
if (it->second.sessionId != sessionId) return ""; // 是「id 写错」,不是「已销毁」
|
||||
return it->second.reason;
|
||||
}
|
||||
|
||||
int CMcpServer::BeginTermCommand(uint64_t device_id, const std::string& sessionId,
|
||||
const std::string& command, const std::string& nonce,
|
||||
context*& subCtx, bool& isPty) {
|
||||
std::lock_guard<std::mutex> lk(m_TermMutex);
|
||||
auto it = m_TermSessions.find(device_id);
|
||||
if (it == m_TermSessions.end()) return false;
|
||||
if (it == m_TermSessions.end()) return 1; // 不存在(含已销毁)
|
||||
TermSession& s = it->second;
|
||||
if (!s.persistent || s.sessionId != sessionId) return false; // 非持久或 token 不匹配
|
||||
if (!s.started) return false; // 未就绪
|
||||
if (s.busy) return false; // 已有命令在飞
|
||||
if (s.closed) return false; // 已关闭
|
||||
if (!s.persistent || s.sessionId != sessionId) return 2; // 非持久或 token 不匹配
|
||||
if (!s.started) return 3; // 未就绪
|
||||
if (s.busy) return 4; // 已有命令在飞
|
||||
if (s.closed) return 5; // 已关闭
|
||||
s.busy = true;
|
||||
s.command = command;
|
||||
s.nonce = nonce;
|
||||
@@ -6378,7 +6542,7 @@ bool CMcpServer::BeginTermCommand(uint64_t device_id, const std::string& session
|
||||
s.lastActiveAt = time(nullptr);
|
||||
subCtx = s.subCtx;
|
||||
isPty = s.isPty;
|
||||
return true;
|
||||
return 0;
|
||||
}
|
||||
|
||||
bool CMcpServer::WaitTermCommand(uint64_t device_id, std::vector<BYTE>& out,
|
||||
@@ -6392,6 +6556,9 @@ bool CMcpServer::WaitTermCommand(uint64_t device_id, std::vector<BYTE>& out,
|
||||
|
||||
if (!signaled) { // 超时 → 清理会话+路由(调用方负责 CancelIO)
|
||||
context* subCtx = it->second.subCtx;
|
||||
MarkTermDestroyedLocked(device_id, it->second.sessionId,
|
||||
"Terminal session was destroyed after this command timed out (waited "
|
||||
+ std::to_string(timeoutMs) + " ms); call terminal_open again");
|
||||
m_TermContextToDevice.erase(subCtx);
|
||||
m_TermSessions.erase(it);
|
||||
return false;
|
||||
@@ -6402,6 +6569,8 @@ bool CMcpServer::WaitTermCommand(uint64_t device_id, std::vector<BYTE>& out,
|
||||
out = it->second.data;
|
||||
exitCode = -1;
|
||||
closed = true;
|
||||
MarkTermDestroyedLocked(device_id, it->second.sessionId,
|
||||
"Terminal session ended: the shell process exited; call terminal_open again");
|
||||
m_TermContextToDevice.erase(subCtx);
|
||||
m_TermSessions.erase(it);
|
||||
return true;
|
||||
@@ -6429,10 +6598,13 @@ int CMcpServer::CloseTermSession(uint64_t device_id, const std::string& sessionI
|
||||
if (s.busy) {
|
||||
// 有命令在飞:置 closed 唤醒等待线程,由其清理(避免双重擦除)。
|
||||
s.closed = true;
|
||||
MarkTermDestroyedLocked(device_id, sessionId,
|
||||
"Terminal session was closed by terminal_close while a command was running");
|
||||
m_TermCv.notify_all();
|
||||
return 0;
|
||||
}
|
||||
subCtx = s.subCtx;
|
||||
MarkTermDestroyedLocked(device_id, sessionId, "Terminal session was closed by terminal_close");
|
||||
m_TermContextToDevice.erase(s.subCtx);
|
||||
m_TermSessions.erase(it);
|
||||
}
|
||||
@@ -6449,6 +6621,9 @@ int CMcpServer::SweepIdleTerminals(time_t idleTimeoutSec) {
|
||||
TermSession& s = it->second;
|
||||
if (s.persistent && !s.busy && difftime(now, s.lastActiveAt) > (double)idleTimeoutSec) {
|
||||
if (s.subCtx) { m_TermContextToDevice.erase(s.subCtx); toCancel.push_back(s.subCtx); }
|
||||
MarkTermDestroyedLocked(it->first, s.sessionId,
|
||||
"Terminal session was reclaimed after " + std::to_string((int)idleTimeoutSec)
|
||||
+ "s of inactivity; call terminal_open again");
|
||||
it = m_TermSessions.erase(it);
|
||||
} else {
|
||||
++it;
|
||||
@@ -7366,6 +7541,10 @@ std::string GenerateRandomToken() {
|
||||
|
||||
// ===== P6:download_file 文件传输会话(状态机方法)=====
|
||||
|
||||
// 停滞看门狗:超过这么久没收到任何传输包即判失败(远程路径不存在时客户端不发包)。
|
||||
// 60s 足够覆盖极慢链路,又远小于 download_file 默认的 600s 总超时。
|
||||
static const int kFileXferStallMs = 60000;
|
||||
|
||||
bool CMcpServer::IsFileTransferPending(uint64_t device_id) {
|
||||
std::lock_guard<std::mutex> lk(m_FileXferMutex);
|
||||
return m_FileXferSessions.find(device_id) != m_FileXferSessions.end();
|
||||
@@ -7387,6 +7566,7 @@ bool CMcpServer::BeginFileTransferPending(uint64_t device_id, const std::string&
|
||||
s.remotePath = remotePath;
|
||||
s.overwrite = overwrite;
|
||||
s.startAt = time(nullptr);
|
||||
s.lastDataAt = std::chrono::steady_clock::now();
|
||||
m_FileXferSessions[device_id] = std::move(s);
|
||||
return true;
|
||||
}
|
||||
@@ -7402,6 +7582,7 @@ bool CMcpServer::BeginFileUpload(uint64_t device_id) {
|
||||
FileTransferSession s;
|
||||
s.tool = "upload_file";
|
||||
s.startAt = time(nullptr);
|
||||
s.lastDataAt = std::chrono::steady_clock::now();
|
||||
m_FileXferSessions[device_id] = std::move(s);
|
||||
return true;
|
||||
}
|
||||
@@ -7450,6 +7631,7 @@ void CMcpServer::OnFileChunkV2(uint64_t device_id, context* streamSubCtx, const
|
||||
FileTransferSession& s = it->second;
|
||||
if (s.tool != "download_file") return;
|
||||
if (s.done) return; // 已出错/完成,丢弃迟到包
|
||||
s.lastDataAt = std::chrono::steady_clock::now(); // 停滞看门狗:有包就续命
|
||||
|
||||
if (s.streamSubCtx == nullptr) {
|
||||
s.streamSubCtx = streamSubCtx;
|
||||
@@ -7528,6 +7710,7 @@ void CMcpServer::OnFileCompleteV2(uint64_t device_id, const BYTE* buf, ULONG len
|
||||
FileTransferSession& s = it->second;
|
||||
if (s.tool != "download_file") return;
|
||||
if (s.done) return;
|
||||
s.lastDataAt = std::chrono::steady_clock::now(); // 停滞看门狗:有包就续命
|
||||
|
||||
uint32_t fileIndex = pkt->fileIndex;
|
||||
|
||||
@@ -7560,18 +7743,37 @@ bool CMcpServer::WaitFileTransferDone(uint64_t device_id, int timeoutMs,
|
||||
auto it = m_FileXferSessions.find(device_id);
|
||||
if (it == m_FileXferSessions.end()) { error = 1002; return false; }
|
||||
|
||||
bool signaled = m_FileXferCv.wait_for(lk, std::chrono::milliseconds(timeoutMs),
|
||||
[&] { return it->second.done; });
|
||||
// 分段等待 + 停滞看门狗:远程路径不存在时客户端一个包都不发,只靠总超时(默认 600s)
|
||||
// 会把整台主机的单飞互斥占满 10 分钟(评审 P2)。改为「N 秒没有任何数据就判停滞」,
|
||||
// 大文件正常传输时每个 chunk 都会续命,不受影响。
|
||||
const auto deadline = std::chrono::steady_clock::now() + std::chrono::milliseconds(timeoutMs);
|
||||
bool signaled = false;
|
||||
while (true) {
|
||||
auto slice = std::chrono::milliseconds(500);
|
||||
auto now = std::chrono::steady_clock::now();
|
||||
if (now + slice > deadline) slice = std::chrono::duration_cast<std::chrono::milliseconds>(deadline - now);
|
||||
if (slice.count() <= 0) break; // 总超时
|
||||
if (m_FileXferCv.wait_for(lk, slice, [&] { return it->second.done; })) {
|
||||
signaled = true;
|
||||
break;
|
||||
}
|
||||
if (std::chrono::steady_clock::now() - it->second.lastDataAt >=
|
||||
std::chrono::milliseconds(kFileXferStallMs)) {
|
||||
it->second.error = 1004; // 停滞
|
||||
it->second.done = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
FileTransferSession& s = it->second;
|
||||
if (!signaled) s.error = 1002; // 超时
|
||||
if (!signaled && !s.done) s.error = 1002; // 总超时
|
||||
|
||||
error = s.error;
|
||||
// 复制已见文件(成功=完整文件;失败=供调用方删半成品)。跳过的既有文件不在此列。
|
||||
for (auto& kv : s.fileEntries) files.push_back(kv.second);
|
||||
skipped = (int)s.skipped.size();
|
||||
|
||||
return signaled && s.error == 0;
|
||||
return s.done && s.error == 0;
|
||||
}
|
||||
|
||||
void CMcpServer::ClearFileTransfer(uint64_t device_id) {
|
||||
|
||||
Reference in new issue
Block a user