Feature: Support the remote terminal on Android hosts

The terminal tools were Windows/Linux only because the Android client had
no COMMAND_SHELL handler: the server opened a shell sub-connection and
the command was silently dropped, leaving exec_command to time out. This
adds the PTY path on the client and the matching server gating.

Client: COMMAND_SHELL on the main connection spawns a terminal thread
that opens an authenticated sub-connection, sends TOKEN_TERMINAL_START
and keeps the PTY alive until the server closes it. common/PTYHandler.h
is reused, with a minSdk-21 openpty built from posix_openpt/grantpt and
/system/bin/sh (mksh) as the shell. A new CLIENT_CAP_TERMINAL bit lets
the server reject old APKs up front with -32005.

Server: the tool masks, instructions and docs matrix accept APK. While
verifying, exec_command left a second echoed copy of the command line in
stdout: mksh forks with ECHO still on, so input written before its line
editor takes over is echoed by the line discipline in addition to the
shell's own redraw. The server now waits for the shell's first output
(the prompt) before sending the command and sentinel, which restores the
single-echo assumption the cleaning step relies on. terminal_exec on a
ready session is unaffected.

Verified on the Android 15 emulator: exec_command returns clean stdout
and real exit codes for id/uname/df/ls (including a failing command),
and terminal_open keeps cwd across commands, pipes work and close is
clean. The committed ghost.apk is stale and must be rebuilt before
release; a rebuilt APK was used for this testing.

Co-Authored-By: deepseek-flash
This commit is contained in:
yuanyuanxianganddeepseek-flash committed 2026-11-11 21:58:54 +01:00
1 parent 915c587964
commit 445bd8bbb9
9 files changed
+205 -32

No files matched your search

+59 -17
View File
@@ -353,9 +353,11 @@ const char* kServerInstructions =
u8"无障碍服务、抓屏依赖已授权录屏,两者都没有能力位可查,命令下发成功不代表生效),"
u8"卸载主机(uninstall_host,会拉起系统的卸载确认框,需要有人在设备上点确认)、"
u8"远程交谈(chat_open / chat_send / chat_wait / chat_close,聊天界面在 App 内,"
u8"需要声明 CLIENT_CAP_REMOTE_CHAT 的新版 APK,老 APK 返回 -32005),以及 "
u8"需要声明 CLIENT_CAP_REMOTE_CHAT 的新版 APK)、远程终端(exec_command / terminal_open / "
u8"terminal_exec / terminal_close,PTY 里跑 /system/bin/sh(mksh),命令由 toybox 提供,"
u8"需要声明 CLIENT_CAP_TERMINAL 的新版 APK,老 APK 返回 -32005),以及 "
u8"host_set_remark / host_set_watch_level 这两个只改服务端本地数据的工具。其余一律不支持"
u8"(客户端未实现 SYSTEM 与 SHELL)。\n"
u8"(客户端未实现 SYSTEM 等命令)。\n"
u8"copy_files_c2c 是唯一有方向性的工具:源端 src_id 必须是 win,目标端 dst_id 可以是 "
u8"win / lnx / mac。Linux 和 macOS 只能当接收方,不能当发送方(反向不支持)。\n"
u8"这些不支持的组合会立刻返回 -32005,不会白等超时;反之,遇到超时不要当成平台不支持。\n"
@@ -2485,7 +2487,7 @@ std::string BuildToolsListResult(const Json::Value& id) {
if (!CMcpServer::Instance().IsReadonly()) {
Json::Value tool(Json::objectValue);
tool["name"] = "exec_command";
tool["description"] = u8"在指定在线 Windows 或 Linux 主机上执行一条命令并返回 stdout 与退出码(受只读模式与命令白名单约束,默认仅允许只读命令前缀,见 McpReadonly / McpCmdWhitelist;Linux 有独立的 POSIX 默认白名单,禁用 ; 反引号 $( ${ ! 等串联/子命令字符)。";
tool["description"] = u8"在指定在线 Windows、Linux 或 Android 主机上执行一条命令并返回 stdout 与退出码(受只读模式与命令白名单约束,默认仅允许只读命令前缀,见 McpReadonly / McpCmdWhitelist;Linux/Android 有独立的 POSIX 默认白名单,禁用 ; 反引号 $( ${ ! 等串联/子命令字符)。Android 上 shell 是 /system/bin/sh(mksh),可用命令由 toybox 提供。";
tool["inputSchema"] = BuildExecCommandInputSchema();
tool["outputSchema"] = BuildExecCommandOutputSchema();
@@ -2499,7 +2501,7 @@ std::string BuildToolsListResult(const Json::Value& id) {
{
Json::Value tool(Json::objectValue);
tool["name"] = "terminal_open";
tool["description"] = u8"在指定在线 Windows 或 Linux 主机上打开一个持久 shell 会话并返回 session_id 与终端模式。后续 terminal_exec 复用该会话(cwd/环境变量跨命令保持),用毕须 terminal_close。Linux 使用 POSIX PTY(UTF-8,is_pty=true)。";
tool["description"] = u8"在指定在线 Windows、Linux 或 Android 主机上打开一个持久 shell 会话并返回 session_id 与终端模式。后续 terminal_exec 复用该会话(cwd/环境变量跨命令保持),用毕须 terminal_close。Linux/Android 使用 POSIX PTY(UTF-8,is_pty=true),Android 的 shell 是 /system/bin/sh(mksh)。";
tool["inputSchema"] = BuildTerminalOpenInputSchema();
tool["outputSchema"] = BuildTerminalOpenOutputSchema();
tools.append(tool);
@@ -2507,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 PTY)下可用管道 | 与 && / || 串联,退出码取整条管道/串联,适合「ls -1 | wc -l」这类先过滤再回传的用法;不要用后台执行符 &(POSIX)或换行。老非 PTY Windows 客户端仍不支持 & 与 |,请拆成多条调用。";
tool["description"] = u8"在已打开的持久会话中执行一条命令并返回 stdout 与退出码。命令不受白名单约束。PTY 会话(新 Windows 客户端 ConPTY / Linux 与新版 Android 的 POSIX PTY)下可用管道 | 与 && / || 串联,退出码取整条管道/串联,适合「ls -1 | wc -l」这类先过滤再回传的用法;不要用后台执行符 &(POSIX)或换行。老非 PTY Windows 客户端仍不支持 & 与 |,请拆成多条调用。";
tool["inputSchema"] = BuildTerminalExecInputSchema();
tool["outputSchema"] = BuildTerminalExecOutputSchema();
tools.append(tool);
@@ -4074,11 +4076,16 @@ std::string BuildExecCommand(const Json::Value& id, const Json::Value& args, CMy
if (!ctx)
return BuildError(id, -32002, "Host not found or offline: " + std::to_string(devId));
// Linux 客户端同样走 PTY + POSIX 哨兵;macOS 本轮不开放。
// Linux/Android 客户端同样走 PTY + POSIX 哨兵;macOS 本轮不开放。
CString clientType = ctx->GetAdditionalData(RES_CLIENT_TYPE);
const bool posix = (clientType == "LNX");
const bool posix = (clientType == "LNX" || clientType == "APK");
if (clientType == "MAC")
return BuildError(id, -32005, "exec_command is only supported on Windows and Linux hosts");
return BuildError(id, -32005, "exec_command is only supported on Windows, Linux and Android hosts");
// 老 APK 的 COMMAND_SHELL 是空实现,发下去只会拖到超时;按能力位提前拒绝。
if (clientType == "APK" && !ctx->SupportsTerminal())
return BuildError(id, -32005,
"Android client is too old for exec_command: "
"the APK has no COMMAND_SHELL handler, upgrade the client first");
std::string command = Trim(GetStringArg(args, "command"));
if (command.empty())
@@ -4127,6 +4134,9 @@ std::string BuildExecCommand(const Json::Value& id, const Json::Value& args, CMy
// 编码:PTY(UTF-8) / 老 cmd 管道(GBK)。哨兵为纯 ASCII,两种编码下字节一致。
UINT cp = (posix || isPty) ? CP_UTF8 : 936;
// POSIX 上等 shell 打印提示符再写命令,避免驱动多回显一份输入(见 WaitTerminalBootstrap)。
if (posix && isPty)
mcp.WaitTerminalBootstrap(devId, timeoutMs < 2000 ? timeoutMs : 2000);
// 哨兵形态见 BuildSentinelLines:POSIX PTY / ConPTY 下命令与哨兵分两行下发(吞行命令
// 不再超时),老 ShellManager 保持单行 && / || 形式(其客户端按写入长度跳回显)。
std::string cmdLine, sentLine;
@@ -4686,7 +4696,13 @@ static bool ResolveTerminalSessionHost(const Json::Value& id, const Json::Value&
CString clientType = ctx->GetAdditionalData(RES_CLIENT_TYPE);
if (clientType == "MAC") {
errJson = BuildError(id, -32005, "Persistent terminal is only supported on Windows and Linux hosts");
errJson = BuildError(id, -32005, "Persistent terminal is only supported on Windows, Linux and Android hosts");
return false;
}
if (clientType == "APK" && !ctx->SupportsTerminal()) {
errJson = BuildError(id, -32005,
"Android client is too old for the persistent terminal: "
"the APK has no COMMAND_SHELL handler, upgrade the client first");
return false;
}
return true;
@@ -4907,7 +4923,8 @@ std::string BuildTerminalExec(const Json::Value& id, const Json::Value& args, CM
std::string errJson;
if (!ResolveTerminalSessionHost(id, args, parent, devId, ctx, errJson))
return errJson;
const bool posix = (ctx->GetAdditionalData(RES_CLIENT_TYPE) == "LNX");
const bool posix = (ctx->GetAdditionalData(RES_CLIENT_TYPE) == "LNX" ||
ctx->GetAdditionalData(RES_CLIENT_TYPE) == "APK");
std::string sessionId = GetStringArg(args, "session_id");
if (sessionId.empty())
@@ -4965,6 +4982,10 @@ std::string BuildTerminalExec(const Json::Value& id, const Json::Value& args, CM
if (begin != 0)
return sessionError(begin);
// 新会话的第一条命令可能与 shell 启动竞争,等提示符到达再写(见 WaitTerminalBootstrap)。
if (posix && isPty)
mcp.WaitTerminalBootstrap(devId, timeoutMs < 2000 ? timeoutMs : 2000);
std::string cmdLine, sentLine;
SendTerminalCommandLine(subCtx, isPty, posix, command, nonce, cmdLine, sentLine);
@@ -10196,7 +10217,8 @@ static const long long kBatchDeadlineMs = 50000;
// ===== 平台门禁:调用前拦掉「该客户端根本没实现」的组合 =====
//
// 判据来自各平台客户端对相应 COMMAND_ 的处理实现,不能看「是否引用了常量」:
// - android/.../main.cpp:534-540 的 COMMAND_SYSTEM / COMMAND_SHELL 都是空实现
// - android/.../main.cpp 的 COMMAND_SYSTEM 是空实现;COMMAND_SHELL 从 CLIENT_CAP_TERMINAL
// 开始才有 PTY 子连接(工具内部还会按能力位二次拦截老 APK)
// - macOS 能处理 SEND_FILE_V2,但 DefaultCaps() 不给 SCREEN_PREVIEW,截屏仍不可用
// 表内容与 mcp/tools.json 的 platforms 字段一一对应,
// tools/mcp_tools/check_platform_table.py 会校验两边一致。
@@ -10251,11 +10273,12 @@ const ToolPlatform kToolPlatforms[] = {
// COMMAND_SCREEN_CTRL_ALT_DEL:只有 Android 客户端实现(映射为系统锁屏)
{ "remote_lock_screen", kPlatApk },
// macOS 客户端有 PTY 实现(macos/main.mm:753),但服务端刻意不开放
// (McpServer.cpp:3652「macOS 本轮不开放」),故实际不可用
{ "exec_command", kPlatWin|kPlatLnx },
{ "terminal_open", kPlatWin|kPlatLnx },
{ "terminal_exec", kPlatWin|kPlatLnx },
{ "terminal_close", kPlatWin|kPlatLnx },
// (McpServer.cpp:3652「macOS 本轮不开放」),故实际不可用;
// Android 新版复用 common/PTYHandler.h(/system/bin/sh),声明 CLIENT_CAP_TERMINAL
{ "exec_command", kPlatWin|kPlatLnx|kPlatApk },
{ "terminal_open", kPlatWin|kPlatLnx|kPlatApk },
{ "terminal_exec", kPlatWin|kPlatLnx|kPlatApk },
{ "terminal_close", kPlatWin|kPlatLnx|kPlatApk },
// macOS 客户端有 COMMAND_KILLPROCESS 分支,服务端同样拦着(McpServer.cpp:6870)
{ "kill_process", kPlatWin|kPlatLnx },
// ---- win ---- 服务 / 注册表 / 键日志 / 文件写 / host_* / chat_* / power_action
@@ -10730,10 +10753,13 @@ 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);
// 第一屏输出到达 = shell 已接管终端(见 WaitTerminalBootstrap)。BeginTermCommand 会清
// data,故就绪态需要单独记一个旗标,跨命令保持。
s.sawOutput = true;
if (FindSentinel(s.data, s.nonce, s.sentPos, s.exitCode)) {
s.done = true;
m_TermCv.notify_all();
}
m_TermCv.notify_all(); // 唤醒 WaitTerminalBootstrap / WaitTerminalDone
}
void CMcpServer::OnTerminalClosed(context* subCtx) {
@@ -10780,6 +10806,22 @@ bool CMcpServer::WaitTerminalReady(uint64_t device_id, context*& subCtx, bool& i
return true;
}
// 写命令前等 shell 启动完成。背景:PTY 的行规程负责回显输入,交互式 shell 进入行编辑
// 模式后会关掉 ECHO 自己回显一份;但 shell 刚 fork 出来、还没走到读循环时 ECHO 仍开着,
// 这时写进去的输入会被驱动先回显一遍,shell 再回显一遍——服务端清洗(CutThroughEchoedLine)
// 只剔一份,多出来的「提示符 + 命令行」就留在 stdout 里。Android 的 mksh 启动比 bash 慢,
// 实测 exec_command 稳定触发(terminal_exec 因会话已就绪不触发)。shell 打印第一屏
// (提示符)即表示行编辑已接管终端,此时写入只会回显一份。超时则照常写入,不阻塞功能。
void CMcpServer::WaitTerminalBootstrap(uint64_t device_id, int timeoutMs) {
std::unique_lock<std::mutex> lk(m_TermMutex);
auto it = m_TermSessions.find(device_id);
if (it == m_TermSessions.end()) return;
WaitWithCancel(lk, m_TermCv, DeadlineAfter(timeoutMs), [&] {
auto jt = m_TermSessions.find(device_id);
return jt == m_TermSessions.end() || jt->second.sawOutput || jt->second.closed;
});
}
bool CMcpServer::WaitTerminalDone(uint64_t device_id, std::vector<BYTE>& out,
int& exitCode, bool& closed, int timeoutMs) {
std::unique_lock<std::mutex> lk(m_TermMutex);