Feature(mcp): keep terminal sessions on timeout and allow output polling

terminal_exec used to destroy the persistent session on timeout, so long
commands (robocopy, upgrade scripts) could never be observed: the collected
output was thrown away and the shell was killed. Waiting is now decoupled from
the command:

- WaitTermCommand delivers [delivered, ...) and no longer erases on timeout.
  It returns done:false plus the output produced so far; the session stays
  busy and polling continues until done:true with exit_code.
- Calling terminal_exec with only session_id polls (no command); command is
  optional and the result gains session_id / done / truncated / dropped_bytes
  / elapsed_ms.
- Request cancellation still destroys the session (-32800 path); shell exit
  and terminal_close deliver the remaining output and then clean up.
- Chunks are capped at max_output_bytes (default 64KB, newline-aligned); the
  per-command buffer is capped at 8MB and reports dropped_bytes; busy sessions
  are force-reclaimed after an hour so a host cannot stay busy forever.
- A finished command with undrained output returns -32003 with a drain hint
  instead of silently losing it when the next command clears the buffer.

Verified on an isolated Debug instance against a Windows host: a 3s timeout on
an 8s ping returns done:false + partial output and two polls finish it; a
277KB dir listing needs 5 polls and then accepts a new command; 200 echo lines
delivered in 12 chunks arrive exactly once in order; cancel returns -32800 and
destroys the session. tools.json regenerated (63 tools, PASS).

Co-Authored-By: deepseek-flash
This commit is contained in:
yuanyuanxianganddeepseek-flash committed 2026-11-12 15:53:33 +01:00
1 parent b63c97c5eb
commit 3fe3a11494
3 files changed
+339 -134

No files matched your search

+34 -10
View File
@@ -2235,7 +2235,7 @@
},
{
"name": "terminal_exec",
"description": "在已打开的持久会话中执行一条命令并返回 stdout 与退出码。命令不受白名单约束。PTY 会话(新 Windows 客户端 ConPTY / Linux 与新版 Android 的 POSIX PTY)下可用管道 | 与 && / || 串联,退出码取整条管道/串联,适合「ls -1 | wc -l」这类先过滤再回传的用法;不要用后台执行符 &(POSIX)或换行。老非 PTY Windows 客户端仍不支持 & 与 |,请拆成多条调用。",
"description": "在已打开的持久会话中执行一条命令,或轮询取回正在运行的命令输出。带 command 时执行并在 timeout_ms 内等待;等待超时返回 done:false 与已产生的部分输出,会话不销毁(命令仍在远端运行)。不带 command、只传 session_id 时进入轮询模式:继续等待并取回增量输出,直到 done:true(此时有 exit_code)。命令不受白名单约束。PTY 会话(新 Windows 客户端 ConPTY / Linux 与新版 Android 的 POSIX PTY)下可用管道 | 与 && / || 串联,退出码取整条管道/串联,适合「ls -1 | wc -l」这类先过滤再回传的用法;不要用后台执行符 &(POSIX)或换行。老非 PTY Windows 客户端仍不支持 & 与 |,请拆成多条调用。",
"gate": "terminal",
"write": true,
"platforms": [
@@ -2247,43 +2247,67 @@
"inputSchema": {
"properties": {
"command": {
"description": "要执行的命令(完整 shell,不受白名单约束)。PTY 会话(Windows ConPTY / Linux PTY)下可用管道 | 与 && / || 串联,退出码取整条管道/串联;不要用后台执行符 &(POSIX)或换行。老非 PTY 客户端仍不支持 & 与 |,请拆成多条调用。Linux 下通过 POSIX shell 执行,可用 ; 串联且退出码取最后一条命令",
"description": "要执行的命令(完整 shell,不受白名单约束)。省略时进入轮询模式:不执行新命令,只等待并取回当前会话的增量输出(上一条命令超时后用这个方式继续取)。PTY 会话(Windows ConPTY / Linux PTY)下可用管道 | 与 && / || 串联,退出码取整条管道/串联;不要用后台执行符 &(POSIX)或换行。老非 PTY 客户端仍不支持 & 与 |,请拆成多条调用。Linux 下通过 POSIX shell 执行,可用 ; 串联且退出码取最后一条命令",
"type": "string"
},
"id": {
"description": "主机 id,取 list_online_hosts / search_hosts 返回的 id 字段",
"type": "string"
},
"max_output_bytes": {
"description": "单次返回的原始输出上限(可选,默认 65536,最小 1024,最大 1048576);超出按换行边界截断并置 truncated:true,再轮询一次可取回剩余",
"type": "integer"
},
"session_id": {
"description": "terminal_open 返回的 session_id",
"type": "string"
},
"timeout_ms": {
"description": "等待输出完成的超时毫秒数(可选,默认 20000,上限 600000)",
"description": "本次调用最多等待的毫秒数(可选,默认 20000,上限 600000)。等待超时不算失败:返回 done:false 与已产生的输出,命令仍在远端运行,继续轮询即可",
"type": "integer"
}
},
"required": [
"id",
"session_id",
"command"
"session_id"
],
"type": "object"
},
"outputSchema": {
"properties": {
"exit_code": {
"description": "退出码:PTY 客户端(Windows ConPTY / Linux PTY)为命令的真实退出码;老客户端(非 PTY)仅区分 0/非 0;-1=未知(进程异常退出)",
"done": {
"description": "false=命令仍在运行,用同一工具只传 session_id 继续取增量;true=命令已结束,exit_code 有效",
"type": "boolean"
},
"dropped_bytes": {
"description": "因单条命令输出超过 8MB 上限被丢弃的最旧字节数(该命令累计,0 或省略=无丢失)",
"type": "integer"
},
"stdout": {
"description": "命令输出(已剥哨兵与 ANSI 转义)",
"elapsed_ms": {
"description": "本次调用实际等待的毫秒数",
"type": "integer"
},
"exit_code": {
"description": "退出码(done=true 时提供):PTY 客户端(Windows ConPTY / Linux PTY)为命令的真实退出码;老客户端(非 PTY)仅区分 0/非 0;-1=未知(shell 进程退出)",
"type": "integer"
},
"session_id": {
"description": "会话 token,原样回传,便于续接轮询",
"type": "string"
},
"stdout": {
"description": "本次新增的输出(已剥哨兵与 ANSI 转义)",
"type": "string"
},
"truncated": {
"description": "true=本次受 max_output_bytes 限制仍有剩余输出,立即再轮询即可取回",
"type": "boolean"
}
},
"required": [
"stdout",
"exit_code"
"done",
"session_id"
],
"type": "object"
}
+286 -121
View File
@@ -2509,7 +2509,7 @@ std::string BuildToolsListResult(const Json::Value& id) {
{
Json::Value tool(Json::objectValue);
tool["name"] = "terminal_exec";
tool["description"] = u8"在已打开的持久会话中执行一条命令并返回 stdout 与退出码。命令不受白名单约束。PTY 会话(新 Windows 客户端 ConPTY / Linux 与新版 Android 的 POSIX PTY)下可用管道 | 与 && / || 串联,退出码取整条管道/串联,适合「ls -1 | wc -l」这类先过滤再回传的用法;不要用后台执行符 &(POSIX)或换行。老非 PTY Windows 客户端仍不支持 & 与 |,请拆成多条调用。";
tool["description"] = u8"在已打开的持久会话中执行一条命令,或轮询取回正在运行的命令输出。带 command 时执行并在 timeout_ms 内等待;等待超时返回 done:false 与已产生的部分输出,会话不销毁(命令仍在远端运行)。不带 command、只传 session_id 时进入轮询模式:继续等待并取回增量输出,直到 done:true(此时有 exit_code)。命令不受白名单约束。PTY 会话(新 Windows 客户端 ConPTY / Linux 与新版 Android 的 POSIX PTY)下可用管道 | 与 && / || 串联,退出码取整条管道/串联,适合「ls -1 | wc -l」这类先过滤再回传的用法;不要用后台执行符 &(POSIX)或换行。老非 PTY Windows 客户端仍不支持 & 与 |,请拆成多条调用。";
tool["inputSchema"] = BuildTerminalExecInputSchema();
tool["outputSchema"] = BuildTerminalExecOutputSchema();
tools.append(tool);
@@ -4673,6 +4673,10 @@ static std::string BuildMcpCancelSession(const Json::Value& id, const Json::Valu
static const int kTermIdleTimeoutSec = 300; // 持久终端 idle 回收超时(秒)
static const int kTermTombstoneSec = 600; // 「终端被销毁」墓碑保留时长(秒),供后续报错文案用
// 超时轮询(P0-2):超时不再销毁会话,改为返回部分输出 + 可继续轮询,因此需要三个上限。
static const int kTermMaxDataBytes = 8 * 1024 * 1024; // 单条命令原始输出硬上限(超出丢最旧字节)
static const int kTermMaxOutputBytes = 64 * 1024; // 单次 terminal_exec 返回的原始输出上限
static const int kTermBusyMaxSec = 3600; // busy 兜底:命令跑满 1 小时强制回收
// 共享前置:校验 McpTerminal && !readonly → 解析 id → FindMainContext → 拒绝 macOS。
// 成功返回 true 并输出 devId/ctx;失败时 errJson 已写入对应 JSON 错误串。
@@ -4722,9 +4726,11 @@ static void SendTerminalCommandLine(context* subCtx, bool isPty, bool posix,
// 输出清洗(复用 exec_command 尾部逻辑):raw → UTF-8 → 剥 ANSI → CRLF 归一 →
// 去输入回显 → TrimRight。
// trimTrailing=false 用于「本次只交付片段」:块尾的换行/空格属于这一块,必须原样保留,
// 否则下一块的输出会和这一块的最后一行粘在一起(P0-2 逐块交付踩过:LINE-17LINE-18)。
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) {
const std::string& nonce, bool trimTrailing = true) {
std::string stdoutStr;
if (!raw.empty()) {
std::string rawStr((const char*)raw.data(), raw.size());
@@ -4733,7 +4739,7 @@ static std::string CleanTerminalOutput(const std::vector<BYTE>& raw, UINT cp, bo
while ((p = stdoutStr.find("\r\n", p)) != std::string::npos)
stdoutStr.erase(p, 1);
stdoutStr = StripEchoedInput(stdoutStr, isPty, cmdLine, sentLine, nonce);
stdoutStr = TrimRight(stdoutStr);
if (trimTrailing) stdoutStr = TrimRight(stdoutStr);
}
return stdoutStr;
}
@@ -4790,19 +4796,22 @@ Json::Value BuildTerminalExecInputSchema() {
props["session_id"] = sid;
Json::Value cmdProp(Json::objectValue);
cmdProp["type"] = "string";
cmdProp["description"] = u8"要执行的命令(完整 shell,不受白名单约束)。PTY 会话(Windows ConPTY / Linux PTY)下可用管道 | 与 && / || 串联,退出码取整条管道/串联;不要用后台执行符 &(POSIX)或换行。老非 PTY 客户端仍不支持 & 与 |,请拆成多条调用。Linux 下通过 POSIX shell 执行,可用 ; 串联且退出码取最后一条命令";
cmdProp["description"] = u8"要执行的命令(完整 shell,不受白名单约束)。省略时进入轮询模式:不执行新命令,只等待并取回当前会话的增量输出(上一条命令超时后用这个方式继续取)。PTY 会话(Windows ConPTY / Linux PTY)下可用管道 | 与 && / || 串联,退出码取整条管道/串联;不要用后台执行符 &(POSIX)或换行。老非 PTY 客户端仍不支持 & 与 |,请拆成多条调用。Linux 下通过 POSIX shell 执行,可用 ; 串联且退出码取最后一条命令";
props["command"] = cmdProp;
Json::Value timeoutProp(Json::objectValue);
timeoutProp["type"] = "integer";
timeoutProp["description"] = u8"等待输出完成的超时毫秒数(可选,默认 20000,上限 600000)";
timeoutProp["description"] = u8"本次调用最多等待的毫秒数(可选,默认 20000,上限 600000)。等待超时不算失败:返回 done:false 与已产生的输出,命令仍在远端运行,继续轮询即可";
props["timeout_ms"] = timeoutProp;
Json::Value maxOutProp(Json::objectValue);
maxOutProp["type"] = "integer";
maxOutProp["description"] = u8"单次返回的原始输出上限(可选,默认 65536,最小 1024,最大 1048576);超出按换行边界截断并置 truncated:true,再轮询一次可取回剩余";
props["max_output_bytes"] = maxOutProp;
Json::Value schema(Json::objectValue);
schema["type"] = "object";
schema["properties"] = props;
Json::Value required(Json::arrayValue);
required.append("id");
required.append("session_id");
required.append("command");
schema["required"] = required;
return schema;
}
@@ -4811,18 +4820,39 @@ Json::Value BuildTerminalExecOutputSchema() {
Json::Value props(Json::objectValue);
Json::Value stdoutProp(Json::objectValue);
stdoutProp["type"] = "string";
stdoutProp["description"] = u8"命令输出(已剥哨兵与 ANSI 转义)";
stdoutProp["description"] = u8"本次新增的输出(已剥哨兵与 ANSI 转义)";
props["stdout"] = stdoutProp;
Json::Value doneProp(Json::objectValue);
doneProp["type"] = "boolean";
doneProp["description"] = u8"false=命令仍在运行,用同一工具只传 session_id 继续取增量;true=命令已结束,exit_code 有效";
props["done"] = doneProp;
Json::Value sid(Json::objectValue);
sid["type"] = "string";
sid["description"] = u8"会话 token,原样回传,便于续接轮询";
props["session_id"] = sid;
Json::Value exitProp(Json::objectValue);
exitProp["type"] = "integer";
exitProp["description"] = u8"退出码:PTY 客户端(Windows ConPTY / Linux PTY)为命令的真实退出码;老客户端(非 PTY)仅区分 0/非 0;-1=未知(进程异常退出)";
exitProp["description"] = u8"退出码(done=true 时提供):PTY 客户端(Windows ConPTY / Linux PTY)为命令的真实退出码;老客户端(非 PTY)仅区分 0/非 0;-1=未知(shell 进程退出)";
props["exit_code"] = exitProp;
Json::Value truncProp(Json::objectValue);
truncProp["type"] = "boolean";
truncProp["description"] = u8"true=本次受 max_output_bytes 限制仍有剩余输出,立即再轮询即可取回";
props["truncated"] = truncProp;
Json::Value dropProp(Json::objectValue);
dropProp["type"] = "integer";
dropProp["description"] = u8"因单条命令输出超过 8MB 上限被丢弃的最旧字节数(该命令累计,0 或省略=无丢失)";
props["dropped_bytes"] = dropProp;
Json::Value elapsedProp(Json::objectValue);
elapsedProp["type"] = "integer";
elapsedProp["description"] = u8"本次调用实际等待的毫秒数";
props["elapsed_ms"] = elapsedProp;
Json::Value schema(Json::objectValue);
schema["type"] = "object";
schema["properties"] = props;
Json::Value required(Json::arrayValue);
required.append("stdout");
required.append("exit_code");
required.append("done");
required.append("session_id");
schema["required"] = required;
return schema;
}
@@ -4917,7 +4947,52 @@ std::string BuildTerminalOpen(const Json::Value& id, const Json::Value& args, CM
return BuildResult(id, result);
}
// tools/call:terminal_exec(在已打开的持久会话中执行一条命令;无白名单;PTY 下允许管道/串联)
// terminal_exec 的结果 JSON:一次调用可能只拿到片段(超时/轮询/截断),done 与 truncated
// 各自表达「命令是否结束」与「本块之后是否还有输出」,模型据此决定是否继续轮询。
static std::string BuildTerminalExecResult(const Json::Value& id, const std::string& sessionId,
const std::string& output, bool done, bool closed,
int exitCode, bool truncated, size_t droppedBytes,
int elapsedMs) {
const int finalExit = done ? (closed ? -1 : exitCode) : -1;
Json::Value structuredContent(Json::objectValue);
structuredContent["stdout"] = output;
structuredContent["done"] = done;
structuredContent["session_id"] = sessionId;
if (done) structuredContent["exit_code"] = finalExit;
structuredContent["truncated"] = truncated;
if (droppedBytes > 0) structuredContent["dropped_bytes"] = (Json::UInt64)droppedBytes;
structuredContent["elapsed_ms"] = elapsedMs;
Json::Value result(Json::objectValue);
result["structuredContent"] = structuredContent;
// 同 exec_command:stdout 在正文里,正文外只补状态字段。
Json::Value textPayload(Json::objectValue);
textPayload["done"] = done;
textPayload["session_id"] = sessionId;
if (done) textPayload["exit_code"] = finalExit;
textPayload["truncated"] = truncated;
if (droppedBytes > 0) textPayload["dropped_bytes"] = (Json::UInt64)droppedBytes;
SetStructuredTextPayload(result, textPayload);
Json::Value content(Json::arrayValue);
Json::Value item(Json::objectValue);
item["type"] = "text";
if (!output.empty()) item["text"] = output;
else item["text"] = done ? std::string(u8"(无输出)")
: std::string(u8"(暂无新输出,命令仍在运行,继续轮询)");
content.append(item);
result["content"] = content;
result["isError"] = false;
return BuildResult(id, result);
}
// tools/call:terminal_exec
// 带 command → 在已打开的持久会话中执行一条命令(无白名单;PTY 下允许管道/串联)
// 不带 command、只传 session_id → 轮询模式:等待/取回当前命令的增量输出
// 超时不再销毁会话:返回 done:false + 已产生的输出,会话保持 busy,后续轮询直到 done:true。
std::string BuildTerminalExec(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent) {
CMcpServer& mcp = CMcpServer::Instance();
mcp.SweepIdleTerminals(kTermIdleTimeoutSec);
@@ -4934,9 +5009,9 @@ std::string BuildTerminalExec(const Json::Value& id, const Json::Value& args, CM
if (sessionId.empty())
return BuildError(id, -32602, "Missing required parameter: session_id");
// command 省略 = 轮询模式(P0-2);command 与 session_id 之外都不再是必填。
std::string command = Trim(GetStringArg(args, "command"));
if (command.empty())
return BuildError(id, -32602, "Missing required parameter: command");
const bool isPoll = command.empty();
auto sessionError = [&](int code) -> std::string {
// 区分「会话被超时/退出/关闭销毁」与「session_id 写错」「另一条命令在飞」(评审 P1)。
@@ -4945,97 +5020,103 @@ std::string BuildTerminalExec(const Json::Value& id, const Json::Value& args, CM
return BuildError(id, -32002, destroyed);
if (code == 4)
return BuildError(id, -32003, "Device busy: another terminal_exec is already running for this session");
if (code == 6)
return BuildError(id, -32003,
"Device busy: the previous command finished but its output is not fully drained; "
"call terminal_exec with only session_id to collect the rest first");
if (code == 2)
return BuildError(id, -32002, "Terminal session_id mismatch: " + sessionId);
if (code == 3)
return BuildError(id, -32002, "Terminal session is not ready yet: " + sessionId);
if (code == 5)
return BuildError(id, -32002, "Terminal session is already closing: " + sessionId);
if (code == 7)
return BuildError(id, -32002,
"Terminal session is idle: no command is running; pass command to execute one");
return BuildError(id, -32002, "Terminal session not found: " + sessionId + " (call terminal_open first)");
};
// 先只读查会话形态:PTY 会话才允许管道/串联;失败时状态不变。
bool isPty = false;
int peek = mcp.PeekTermSession(devId, sessionId, isPty);
if (peek != 0)
return sessionError(peek);
// 正确性门(非安全门):换行会拆成多行、只有末行被哨兵包装,一律拒绝。
// 管道 | 与 && 串联在 PTY 会话(ConPTY / POSIX PTY)下是安全的:哨兵独立成行执行,
// 拿到的是整条管道/串联的退出码。老非 PTY 客户端仍是单行哨兵,继续拒绝 & 与 |。
if (ContainsControlChar(command))
return BuildError(id, kErrValidation,
"Command contains a control character (newline/tab); send one line per call");
if (!isPty && command.find_first_of("&|") != std::string::npos)
return BuildError(id, kErrValidation,
"Pipes and & require a PTY session (newer client); this session uses the legacy "
"non-PTY shell. Run the commands as separate terminal_exec calls");
if (posix && HasPosixBackgroundAmpersand(command))
return BuildError(id, kErrValidation,
"Background execution (&) breaks output capture; use && to chain commands "
"or run it in a separate session");
int timeoutMs = CMcpServer::Instance().ToolTimeoutMs();
int v = 0;
if (GetIntArg(args, "timeout_ms", v) && v > 0 && v <= 600000) timeoutMs = v;
std::string nonce = GenerateRandomToken().substr(0, 8);
int maxOutputBytes = kTermMaxOutputBytes;
if (GetIntArg(args, "max_output_bytes", v) && v >= 1024 && v <= 1024 * 1024) maxOutputBytes = v;
context* subCtx = nullptr;
int begin = mcp.BeginTermCommand(devId, sessionId, command, nonce, subCtx, isPty);
if (begin != 0)
return sessionError(begin);
const auto started = std::chrono::steady_clock::now();
std::string nonce, cmdLine, sentLine;
bool isPty = false;
// 新会话的第一条命令可能与 shell 启动竞争,等提示符到达再写(见 WaitTerminalBootstrap)。
if (posix && isPty)
mcp.WaitTerminalBootstrap(devId, timeoutMs < 2000 ? timeoutMs : 2000);
if (!isPoll) {
// 先只读查会话形态:PTY 会话才允许管道/串联;失败时状态不变。
int peek = mcp.PeekTermSession(devId, sessionId, isPty);
if (peek != 0)
return sessionError(peek);
std::string cmdLine, sentLine;
SendTerminalCommandLine(subCtx, isPty, posix, command, nonce, cmdLine, sentLine);
// 正确性门(非安全门):换行会拆成多行、只有末行被哨兵包装,一律拒绝。
// 管道 | 与 && 串联在 PTY 会话(ConPTY / POSIX PTY)下是安全的:哨兵独立成行执行,
// 拿到的是整条管道/串联的退出码。老非 PTY 客户端仍是单行哨兵,继续拒绝 & 与 |。
if (ContainsControlChar(command))
return BuildError(id, kErrValidation,
"Command contains a control character (newline/tab); send one line per call");
if (!isPty && command.find_first_of("&|") != std::string::npos)
return BuildError(id, kErrValidation,
"Pipes and & require a PTY session (newer client); this session uses the legacy "
"non-PTY shell. Run the commands as separate terminal_exec calls");
if (posix && HasPosixBackgroundAmpersand(command))
return BuildError(id, kErrValidation,
"Background execution (&) breaks output capture; use && to chain commands "
"or run it in a separate session");
nonce = GenerateRandomToken().substr(0, 8);
context* subCtx = nullptr;
int begin = mcp.BeginTermCommand(devId, sessionId, command, nonce, subCtx, isPty);
if (begin != 0)
return sessionError(begin);
// 新会话的第一条命令可能与 shell 启动竞争,等提示符到达再写(见 WaitTerminalBootstrap)。
if (posix && isPty)
mcp.WaitTerminalBootstrap(devId, timeoutMs < 2000 ? timeoutMs : 2000);
SendTerminalCommandLine(subCtx, isPty, posix, command, nonce, cmdLine, sentLine);
// 审计:命令执行(不可关闭)。
if (parent) {
std::string text = "host " + std::to_string(devId) + " term-exec [" + sessionId + "]: " + command;
parent->PostMessageA(WM_SHOWERRORMSG,
(WPARAM)new CString(ToAnsi(text, 936).c_str()),
(LPARAM)new CString(_TR("MCP持久终端")));
}
}
std::vector<BYTE> raw;
int exitCode = -1;
bool closed = false;
if (!mcp.WaitTermCommand(devId, raw, exitCode, closed, timeoutMs)) {
subCtx->CancelIO();
return BuildError(id, -32001, "Timeout waiting for command output");
}
if (closed) {
// shell 进程退出:会话已被 WaitTermCommand 清理,子链接已死,CancelIO 仅对称(无害)。
subCtx->CancelIO();
}
bool done = false, closed = false, truncated = false;
size_t droppedBytes = 0;
int waitResult = mcp.WaitTermCommand(devId, sessionId, raw, done, exitCode, closed,
truncated, droppedBytes, isPty, nonce,
maxOutputBytes, timeoutMs, isPoll);
if (waitResult == 2) // 取消:会话已销毁(分发层会把错误改写成 -32800)
return BuildError(id, -32001, "Request cancelled; the terminal session was destroyed");
if (waitResult != 0 && waitResult != 1)
return sessionError(waitResult);
int elapsedMs = (int)std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::steady_clock::now() - started).count();
// shell 退出时 WaitTermCommand 已清理会话与路由;子连接本身已由客户端关闭,无需 CancelIO。
// 轮询块没有命令回显可剥(回显只在首块);命令路径带 cmdLine/sentLine 走完整清洗。
// 片段交付(命令未结束或本次被 max_output_bytes 截断)保留块尾空白,拼接才不粘连。
const bool finalChunk = done && !truncated;
std::string stdoutStr = CleanTerminalOutput(raw, (posix || isPty) ? CP_UTF8 : 936, isPty,
cmdLine, sentLine, nonce);
isPoll ? std::string() : cmdLine,
isPoll ? std::string() : sentLine, nonce,
finalChunk);
// 审计:命令执行(不可关闭)。
if (parent) {
std::string text = "host " + std::to_string(devId) + " term-exec [" + sessionId + "]: " + command;
parent->PostMessageA(WM_SHOWERRORMSG,
(WPARAM)new CString(ToAnsi(text, 936).c_str()),
(LPARAM)new CString(_TR("MCP持久终端")));
}
Json::Value result(Json::objectValue);
Json::Value structuredContent(Json::objectValue);
structuredContent["stdout"] = stdoutStr;
structuredContent["exit_code"] = exitCode;
result["structuredContent"] = structuredContent;
// 同 exec_command:stdout 在正文里,正文外只补退出码。
Json::Value textPayload(Json::objectValue);
textPayload["exit_code"] = exitCode;
SetStructuredTextPayload(result, textPayload);
Json::Value content(Json::arrayValue);
Json::Value item(Json::objectValue);
item["type"] = "text";
item["text"] = stdoutStr.empty() ? std::string(u8"(无输出)") : stdoutStr;
content.append(item);
result["content"] = content;
result["isError"] = false;
return BuildResult(id, result);
return BuildTerminalExecResult(id, sessionId, stdoutStr, done, closed, exitCode,
truncated, droppedBytes, elapsedMs);
}
// tools/call:terminal_close(关闭持久会话;幂等,session_id 不匹配报错)
@@ -10763,6 +10844,15 @@ void CMcpServer::OnTerminalData(context* subCtx, const BYTE* data, ULONG len) {
TermSession& s = sit->second;
if (s.done || s.closed) return; // 已结束,忽略迟到数据
s.data.insert(s.data.end(), data, data + len);
// 硬上限(P0-2):轮询设计下命令输出可能堆到 MB 级。超限时丢弃最旧字节(含未交付的),
// delivered/sentPos 同步前移,丢弃量如实记进 droppedBytes。哨兵在尾部,不受丢弃影响。
if ((int)s.data.size() > kTermMaxDataBytes) {
size_t excess = s.data.size() - (size_t)kTermMaxDataBytes;
s.data.erase(s.data.begin(), s.data.begin() + excess);
s.droppedBytes += excess;
s.delivered = s.delivered > excess ? s.delivered - excess : 0;
s.sentPos = s.sentPos > excess ? s.sentPos - excess : 0;
}
// 第一屏输出到达 = shell 已接管终端(见 WaitTerminalBootstrap)。BeginTermCommand 会清
// data,故就绪态需要单独记一个旗标,跨命令保持。
s.sawOutput = true;
@@ -10918,13 +11008,19 @@ int CMcpServer::BeginTermCommand(uint64_t device_id, const std::string& sessionI
TermSession& s = it->second;
if (!s.persistent || s.sessionId != sessionId) return 2; // 非持久或 token 不匹配
if (!s.started) return 3; // 未就绪
if (s.busy) return 4; // 已有命令在飞
if (s.closed) return 5; // 已关闭
// 上一条命令已结束但输出还没取完:data 即将被清空,必须先轮询取走,否则静默丢输出。
// 这个状态同时满足 busy(取完才复位),所以必须排在 busy 之前,否则会误报「另一条命令在跑」。
if (s.done && s.delivered < s.sentPos) return 6;
if (s.busy) return 4; // 已有命令在飞
s.busy = true;
s.busySince = std::chrono::steady_clock::now();
s.command = command;
s.nonce = nonce;
s.data.clear();
s.sentPos = 0;
s.delivered = 0;
s.droppedBytes = 0;
s.exitCode = -1;
s.done = false;
s.closed = false;
@@ -10941,55 +11037,114 @@ int CMcpServer::PeekTermSession(uint64_t device_id, const std::string& sessionId
TermSession& s = it->second;
if (!s.persistent || s.sessionId != sessionId) return 2;
if (!s.started) return 3;
if (s.busy) return 4;
if (s.closed) return 5;
if (s.done && s.delivered < s.sentPos) return 6; // 与 BeginTermCommand 的顺序保持一致
if (s.busy) return 4;
isPty = s.isPty;
return 0;
}
bool CMcpServer::WaitTermCommand(uint64_t device_id, std::vector<BYTE>& out,
int& exitCode, bool& closed, int timeoutMs) {
// 交付窗口的截断点:优先回退到窗口内最后一个换行——UTF-8 与 GBK 的换行字节都不会出现在
// 多字节字符内部,按行截断既不会切坏编码,模型读起来也完整。4KB 内找不到换行就直接硬切。
static size_t ChooseDeliverEnd(const std::vector<BYTE>& data, size_t start, size_t end) {
if (end <= start) return end;
size_t floorPos = end > start + 4096 ? end - 4096 : start;
for (size_t i = end; i > floorPos; --i)
if (data[i - 1] == '\n') return i;
return end;
}
int CMcpServer::WaitTermCommand(uint64_t device_id, const std::string& sessionId,
std::vector<BYTE>& out, bool& done, int& exitCode, bool& closed,
bool& truncated, size_t& droppedBytes,
bool& isPty, std::string& nonce,
int maxOutputBytes, int timeoutMs, bool pollMode) {
std::unique_lock<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 3;
if (!it->second.persistent) return 3;
if (it->second.sessionId != sessionId) return 4;
if (!it->second.started) return 3;
if (pollMode && !it->second.busy && !it->second.done && !it->second.closed)
return 7; // 没有在跑的命令:轮询只会空等到超时,直接告诉调用方用错
isPty = it->second.isPty;
nonce = it->second.nonce;
bool signaled = WaitWithCancel(lk, m_TermCv, DeadlineAfter(timeoutMs),
[&] { return it->second.done || it->second.closed; });
// 谓词每次都重新查表:等待期间会话可能被 terminal_close / busy 兜底回收擦掉。
const std::string sid = sessionId;
auto ended = [&] {
auto jt = m_TermSessions.find(device_id);
if (jt == m_TermSessions.end() || jt->second.sessionId != sid) return true;
return jt->second.done || jt->second.closed;
};
bool signaled = WaitWithCancel(lk, m_TermCv, DeadlineAfter(timeoutMs), ended);
if (!signaled) { // 超时/取消 → 清理会话+路由(调用方负责 CancelIO)
context* subCtx = it->second.subCtx;
MarkTermDestroyedLocked(device_id, it->second.sessionId,
McpCallCancelled()
? std::string("Terminal session was destroyed because the request was cancelled; "
"call terminal_open again")
: "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;
}
if (it->second.closed) { // 进程退出 → 清理,返回已收集输出(无哨兵)
context* subCtx = it->second.subCtx;
out = it->second.data;
exitCode = -1;
it = m_TermSessions.find(device_id);
if (it == m_TermSessions.end() || it->second.sessionId != sid) {
// 等待期间会话被销毁(关闭 / 长时间在飞的兜底回收);墓碑里有原因。
done = true;
closed = true;
MarkTermDestroyedLocked(device_id, it->second.sessionId,
"Terminal session ended: the shell process exited; call terminal_open again");
m_TermContextToDevice.erase(subCtx);
exitCode = -1;
return 3;
}
TermSession& s = it->second;
if (!signaled && McpCallCancelled()) {
// 取消:处理线程已经走了,不会再有人来轮询,照旧销毁(shell 一并结束)。
context* subCtx = s.subCtx;
MarkTermDestroyedLocked(device_id, s.sessionId,
"Terminal session was destroyed because the request was cancelled; call terminal_open again");
if (subCtx) m_TermContextToDevice.erase(subCtx);
m_TermSessions.erase(it);
return true;
lk.unlock();
if (subCtx) subCtx->CancelIO();
return 2;
}
// 哨兵命中 → 保持会话,复位 busy;刷新 lastActiveAt,避免「长命令刚完成即被 idle 回收」
// (idle 语义应为「距上次活动」,而非「距上次命令开始」)。
it->second.busy = false;
it->second.lastActiveAt = time(nullptr);
exitCode = it->second.exitCode;
closed = false;
if (it->second.sentPos <= it->second.data.size())
out.assign(it->second.data.begin(), it->second.data.begin() + it->second.sentPos);
return true;
closed = s.closed;
done = s.done || s.closed;
droppedBytes = s.droppedBytes;
// 交付窗口:done 时截止到哨兵(不含哨兵),否则到当前缓冲末尾。
size_t end = s.data.size();
if (s.done && s.sentPos <= s.data.size()) end = s.sentPos;
if (s.delivered > end) s.delivered = end; // 防御:游标只前进不后退
size_t deliverEnd = end;
if (end - s.delivered > (size_t)maxOutputBytes) {
deliverEnd = s.delivered + (size_t)maxOutputBytes;
deliverEnd = ChooseDeliverEnd(s.data, s.delivered, deliverEnd);
truncated = true;
}
out.assign(s.data.begin() + s.delivered, s.data.begin() + deliverEnd);
s.delivered = deliverEnd;
if (s.closed) { // shell 进程退出(或运行中被 terminal_close)→ 交付剩余输出后清理会话+路由
context* subCtx = s.subCtx;
exitCode = -1;
MarkTermDestroyedLocked(device_id, s.sessionId,
"Terminal session ended: the shell process exited; call terminal_open again");
if (subCtx) m_TermContextToDevice.erase(subCtx);
m_TermSessions.erase(it);
if (subCtx) {
lk.unlock();
subCtx->CancelIO(); // 对称注销:已退出的子连接无害,运行中被 close 的由这里结束 shell
}
return 0;
}
if (s.done) { // 哨兵命中:输出取完才复位 busy,否则下一条命令会清掉未交付的输出
exitCode = s.exitCode;
if (s.delivered >= end) {
s.busy = false;
s.lastActiveAt = time(nullptr); // idle 语义是「距上次活动」,避免刚完成就被回收
}
return 0;
}
// 超时:命令仍在远端运行。会话保持 busy、不销毁,调用方继续轮询(P0-2)。
s.lastActiveAt = time(nullptr);
return 1;
}
int CMcpServer::CloseTermSession(uint64_t device_id, const std::string& sessionId) {
@@ -11022,13 +11177,23 @@ int CMcpServer::SweepIdleTerminals(time_t idleTimeoutSec) {
std::vector<context*> toCancel;
{
std::lock_guard<std::mutex> lk(m_TermMutex);
const auto steadyNow = std::chrono::steady_clock::now();
for (auto it = m_TermSessions.begin(); it != m_TermSessions.end(); ) {
TermSession& s = it->second;
if (s.persistent && !s.busy && difftime(now, s.lastActiveAt) > (double)idleTimeoutSec) {
const bool idle = s.persistent && !s.busy &&
difftime(now, s.lastActiveAt) > (double)idleTimeoutSec;
// busy 兜底(P0-2):超时轮询下会话一直 busy,调用方若再也不回来,该主机的终端槽
// 会永远返回 -32003。跑满 1 小时强制回收(等待函数会重新查表,不会悬空)。
const bool overdue = s.persistent && s.busy &&
steadyNow - s.busySince > std::chrono::seconds(kTermBusyMaxSec);
if (idle || overdue) {
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");
overdue
? "Terminal session was reclaimed after the command ran longer than "
+ std::to_string(kTermBusyMaxSec) + "s; call terminal_open again"
: "Terminal session was reclaimed after " + std::to_string((int)idleTimeoutSec)
+ "s of inactivity; call terminal_open again");
it = m_TermSessions.erase(it);
} else {
++it;
+19 -3
View File
@@ -273,9 +273,21 @@ public:
// 否则返回空串。sessionId 不匹配时也返回空串(那是「id 写错」而不是「已销毁」)。
std::string DescribeTermDestroyed(uint64_t device_id, const std::string& sessionId);
// 等待本条命令完成(done || closed || 超时)。done=保持会话;closed/超时=清理会话+路由。
bool WaitTermCommand(uint64_t device_id, std::vector<BYTE>& out, int& exitCode,
bool& closed, int timeoutMs);
// 等待本条命令结束或超时,并交付 [delivered, ...) 的增量输出。
// pollMode=true 表示本次调用没有携带新命令(只轮询),此时会话空闲 = 调用方用错,返回 7。
// 返回:0=命令结束(done=true;closed=true 表示 shell 退出,会话已清理)
// 1=等待超时,命令仍在运行(done=false;会话保持 busy,可再次轮询)
// 2=请求被取消,会话已销毁(与旧语义一致:取消方不会再轮询)
// 3=会话不存在/未就绪/等待期间被销毁(细节看 DescribeTermDestroyed)
// 4=sessionId 不匹配
// 7=轮询时没有在跑的命令(会话空闲)
// 每次最多交付 maxOutputBytes 原始字节(按换行边界回退);truncated=本次是否仍有剩余。
// droppedBytes=该命令因 data 硬上限被丢弃的字节数(累计,如实上报)。
int WaitTermCommand(uint64_t device_id, const std::string& sessionId,
std::vector<BYTE>& out, bool& done, int& exitCode, bool& closed,
bool& truncated, size_t& droppedBytes,
bool& isPty, std::string& nonce,
int maxOutputBytes, int timeoutMs, bool pollMode);
// 关闭持久终端(校验 sessionId;CancelIO + 清理路由/会话)。
// 返回:0=已关闭;1=会话不存在(幂等);2=sessionId 不匹配(调用方报错)。
@@ -828,6 +840,10 @@ private:
bool busy = false; // 一条命令在飞(terminal_exec 复位→WaitTermCommand 返回)
time_t lastActiveAt = 0; // idle 回收用(秒)
std::chrono::steady_clock::time_point startedAt = std::chrono::steady_clock::now(); // P11
// ===== 超时轮询(P0-2)=====
size_t delivered = 0; // 已交付给调用方的 data 前缀长度(超时/轮询增量回传)
size_t droppedBytes = 0; // 因 data 硬上限被丢弃的最旧字节数(如实上报)
std::chrono::steady_clock::time_point busySince{}; // busy 起点(长时间在飞的强制回收兜底)
};
std::mutex m_TermMutex;
std::condition_variable m_TermCv;