Commit Graph
467 Commits
Author SHA1 Message Date
yuanyuanxiangandClaude Code d6ea5fddea Fix(server): require left-button drag for desktop control of Android
桌面端(非触摸)控制 Android TV/盒子时,鼠标悬停会被客户端翻译成焦点移动,
鼠标划过画面就改变焦点。改为只在按住左键拖动时控制;触摸浏览器行为不变。

- MFC 主控:按 clientID 在主连接上解析并缓存客户端类型(新增线程安全的
  GetHostClientType,类型值在 m_cs 内读取);APK 主机的 WM_MOUSEMOVE 仅在
  MK_LBUTTON 按下时转发,不再每次移动都查主连接。
- Web 控制台:桌面 mousemove 对 Android 主机(优先使用服务端 isAndroidRemote,
  设备 os/clientType 只作兜底)只在左键按下时发 move;检查放在发送节流之后。
  touchstart/touchmove/touchend 未改动,触摸屏的单指移动、点按、拖拽、滚动
  和边缘手势保持原状。
- 安卓客户端未修改:TV 模式仍把带按键的 move 翻译成焦点导航,触摸浏览器
  发出的不带按键 move 继续可用。

验证:MFC Debug 服务端、Go 服务端构建通过;内联 JS 通过 node --check。

Model: deepseek-flash
Co-Authored-By: Claude Code <noreply@anthropic.com>
2026-11-19 21:57:38 +01:00
yuanyuanxiangandClaude Code 1320bb81a6 Docs: add client capability matrix
新增 docs/Client_Capability_Matrix.md,以 Windows 客户端为基线,按连接与传输、
远程桌面、文件管理、系统管理、监控审计、升级运维六类对比 Linux、macOS、
Android 的实现情况;另附平台前提与登录能力位对照。

- 主表所有行 Windows 均为 ✓,其他平台按客户端源码逐项核对(命令处理、能力位、
  管理器实现),不依赖 README 描述。
- 明确 WS/WSS 是出包能力(四端网络层都支持),运行时协议切换仅 Windows;Android
  剪贴板只写不读、进程管理需 root、缺关键帧请求与通用键盘注入;Linux 窗口列表
  实际回空、多显示器只能整 X root;macOS 无分享/转移/自升级。
- 补充连接管理、切换显示器、视图偏好、调优/硬编码、文件复制粘贴、C2C 文本、
  机器管理子项、RDP 维护、远程封禁等易漏能力,标注 Windows 独有或部分实现。

验证:独立审查代理对照 client/linux/macos/android 源码复核,修正 11 处错误或
遗漏;主表 74 行 Windows 列全为 ✓。

Model: deepseek-flash
Co-Authored-By: Claude Code <noreply@anthropic.com>
2026-11-19 20:43:30 +01:00
yuanyuanxiangandClaude Code d9fe93ff1e Fix(client): stop Windows share connections immediately on cancel
「取消分享」原来只清 share_list。Windows 的分享实例是同进程里的一个 ClientApp
线程,没有引用可停,连接会一直保持到客户端进程重启;Linux 的分享实例是独立
子进程,取消时直接 stop,两端行为不一致。

- 新增进程内分享实例登记表:起线程前登记 ClientApp 指针、种类与目标 ip:port,
  线程退出时(先摘除后 delete)注销;取消分享时在锁内逐个置 S_CLIENT_EXIT,
  心跳/重连循环约 1 秒内退出并关闭连接。登记项带 stopping 标记,正在退出的
  实例不再被视为可用连接。
- 区分 SHARED_KIND_SHARE / SHARED_KIND_TRANSFER:转移命令末尾贯穿到分享分支
  顺带起的连接标为 TRANSFER,取消分享不动它(取消分享撤销不了转移)。
- 同一目标只保留一条连接:重新分享(换 Shine/传输方式)先停旧实例并等待注销,
  再起新连接;启动时按 ip:port 去重历史 share_list,收到分享命令时也顺手归并
  旧记录;转移目标已有分享实例时不再多连一条(与 Linux SpawnManagedChild 一致)。
- 转移临时连接按 valid_to 自查到期(外层重连循环与内层心跳循环都查),主实例
  到期恢复分支也会停掉它,不再一直挂到进程重启。
- StartClientApp 只在状态不是 S_CLIENT_EXIT 时复位:取消请求可能在登记后、
  线程开跑前落地;SERVER_EXIT/UPDATE 仍照常复位,主控重启后分享实例照旧重连。
  分享实例退出不再置进程级 g_IsAppExit(否则会误伤 FRP 等模块),也不再做
  服务端退出专用的额外等待。
- 转移命令加 IsMainInstance 门禁;Linux 侧只更新注释。

验证:Debug 客户端构建通过;两个自动化 E2E(Debug 服务端 + 假 TCP 目标):
取消分享后连接 1 秒内关闭且主连接仍在线;同目标换 Shine 重新分享时旧连接关闭、
新连接建立,随后取消同样生效。

Model: deepseek-flash
Co-Authored-By: Claude Code <noreply@anthropic.com>
2026-11-19 19:05:04 +01:00
yuanyuanxiangandClaude Code b704258ba4 Feature: hide user-bound devices from MCP
设备绑定到 Web 用户后,MCP 端点(静态 token,等同管理员凭证)仍能按 ID
操作,与"私人设备只归 owner"的模型冲突。按产品决定采用最严格策略:MCP
只面向公共设备,绑定设备对 MCP 一律不可见、不可达,即使知道 ID 也一样。

- list_hosts / get_host_detail / get_server_status 先过滤绑定设备再计数与
  分页;离线列表用完整在线集合作差,避免在线私人设备以离线条目复现。
- 所有单主机工具在 callTool 统一拒绝(get_screenshot / list_files /
  read_file / terminal_exec / terminal_close 及将来新增工具),批量 ids 由
  逐台执行处拒绝;后续新工具不会再漏。
- 拒绝返回与离线主机相同的 -32002 "Host not found or offline",不泄露设备
  是否存在。
- get_audit_log 过滤 device_id / device / devices 中任意一个指向绑定设备的
  记录;owner 快照一次取用,不逐条加锁。
- cmd 把 Web 的 DeviceACL 注入 MCP;未启用 ACL 时行为完全不变。

验证:go build/test/vet 全绿;新增 MCP 侧列表隐藏、按 ID 拒绝、批量拒绝、
状态计数、审计过滤(三种字段写法)测试。

Model: deepseek-flash
Co-Authored-By: Claude Code <noreply@anthropic.com>
2026-11-19 11:17:56 +01:00
yuanyuanxiangandClaude Code 46434b46d0 Feature: add per-device owner bindings to the web console
Web 控制台此前所有 admin 角色用户共享全部设备。新增设备级归属:内置 admin
把设备绑定给一个用户名后,该设备对其他 admin/viewer 不可见不可控,只有
owner 与内置 admin 可见可控。

- 新增 device_acl.json(与 users.json 同目录,YAMA_DEVICE_ACL_FILE 可覆盖),
  原子写、启动加载;文件损坏拒绝启动,避免私人设备变成公共。
- 可见性:内置 admin 全部;未绑定设备仅 admin 角色;绑定设备仅 owner。
  覆盖 get_devices、/api/devices、屏幕墙,以及 connect/term_open/mouse/key/
  clipboard/keyframe/rdp_reset 全部控制通道;device_update 也只推给可见者。
- 只有内置 admin(用户名 admin + role admin)能 bind/unbind;admin 角色保留
  建用户、删设备、审计等既有功能。删设备清绑定。
- 审计日志也按归属过滤:非内置 admin 只能看到公共设备和自己绑定设备的记录
  (device_id / device / devices 三种写法都识别);auditquery 增 DeviceAllowed
  钩子,ACL 提供 Owner 快照,避免扫描时逐条加锁。
- 删用户会解绑其设备;但账号名下有绑定设备时只有内置 admin 能删,其他 admin
  删除会把设备释放到公共池,属于越权。解绑在删除前完成,解绑失败中止删除;
  删除失败时回滚绑定。
- 绑定/解绑后立即重新校验在线会话:失去权限的屏幕/终端会话被断开。
- 本地用户名禁止 '@'(保留给 SSO 邮箱);本地密码登录拒绝 '@' 用户名,
  SSO 拒绝名为 admin 的身份,避免绕过超级管理员判定。
- 前端:superadmin 卡片显示 owner、绑定按钮和弹窗(本地用户 datalist +
  SSO 邮箱自由输入);deviceAcl 能力位由服务端挑战下发,C++ 端无此位不显示;
  设备 ID 经 jsAttr 转义后再进 onclick,修掉存储型 XSS。

验证:go build/test/vet 全绿;新增 ACL 持久化、可见性矩阵、控制通道拒绝、
绑定/解绑会话重校验、device_update 不泄露、分组过滤、删用户解绑与越权拒绝、
审计按归属过滤等测试;本地起 Go 服务 + WebSocket 探针验证 challenge、绑定、
非 superadmin 拒绝、解绑。

Model: deepseek-flash
Co-Authored-By: Claude Code <noreply@anthropic.com>
2026-11-19 11:17:51 +01:00
yuanyuanxiangandClaude Code db148c4a69 Fix(android): humanize lock status and transfer messages
1) 锁屏时活动窗口与 Windows/macOS 对齐:由裸 "Locked" 改为
   "Locked: HH:MM:SS"(已锁时长)。起点取 ACTION_SCREEN_OFF,解锁由
   ACTION_USER_PRESENT 与 KeyguardManager 双重判定;历史活动仍上报裸
   "Locked" 当空闲处理,不记录。

2) 转移主机的提示/日志不再出现大整数:到期时刻格式化为
   "YYYY-MM-DD HH:MM:SS +ZZZZ",剩余有效期格式化为 "2h 05m"/"15m 03s"。
   原 "Host is already transferred until 1763..., ignored" 现在是
   "Host is already transferred until 2026-11-17 21:15:12 +0100
   (2h 00m left), ignored"。

验证:arm64/armeabi 编译通过;模拟器开无障碍后锁屏,服务端 list_hosts
收到 "Locked: 00:00:06",解锁后恢复 "Android";格式化函数单独跑过
2h/15m/42s/负数用例。

Model: deepseek-flash
Co-Authored-By: Claude Code <noreply@anthropic.com>
2026-11-16 21:41:02 +01:00
yuanyuanxiangandClaude Code b7f87c958a Feature: support process management on rooted Android hosts
Android 7 起 /proc 是 hidepid=2 + SELinux,普通 APK 连其它 PID 都看不到,
因此进程管理做成 root-only:登录时探测 su(常见路径 + which su,都不行再
su -c id 兜底),有 root 才声明 CLIENT_CAP_PROCESS。否定结果只缓存 5 分钟,
避免用户误点一次「拒绝」后整个进程生命周期都用不了。

- 客户端:RootProcess.kt 通过 su 枚举 /proc、批量 kill;子连接协议与 Linux
  一致(TOKEN_PSLIST / COMMAND_KILLPROCESS / 空 TOKEN_WSLIST)。
- 服务端:MCP list_processes/kill_process 与 GUI 进程管理对无能力位的 APK
  直接回「需要 root」,不再下发 COMMAND_SYSTEM 后干等超时。

验证:Android 编译通过;模拟器上的 su 仅 root:shell 可执行,验证了非 root
拒绝路径(MCP -32005 + GUI 提示)。真 root 设备的枚举/kill 待实机验证。

Model: deepseek-flash
Co-Authored-By: Claude Code <noreply@anthropic.com>
2026-11-16 21:26:19 +01:00
yuanyuanxiangandClaude Code 998c16edc5 Feature: support camera streaming on Android hosts
Android 摄像头(COMMAND_WEBCAM)此前未实现。客户端用 Camera2 ImageReader
直接输出 JPEG(1280x720、8fps、按传感器方向摆正),第一帧到达时从 JPEG
SOF 读出真实宽高再发 TOKEN_WEBCAM_BITMAPINFO(部分 HAL 会按方向物理旋转
导致宽高互换,以实际帧为准可避免服务端尺寸不符丢帧黑屏),之后每帧
[TOKEN_WEBCAM_DIB][isCompress=1][JPGD][JPEG]。

服务端视频对话框识别 JPGD FOURCC,用 libjpeg 直接解成 bottom-up BGR24;
DrawDib 与「保存 AVI」两条路径都不用改,目标机也不需要安装 VFW 编解码器。
BITMAPINFO 的 biSizeImage 按 DWORD 对齐的 stride 计算。

注意:服务端不要引用 turbojpeg 的 tj* 符号——会拉进与 Debug 构建不兼容的
运行时,启动即 0xC0000005;解码统一走项目已在用的 jpeg_* API。

验证:模拟器虚拟相机出图,窗口标题 127.0.0.1 - Video 1280x720;关闭对话框
后 camera stopped,服务端稳定。

Model: deepseek-flash
Co-Authored-By: Claude Code <noreply@anthropic.com>
2026-11-16 18:36:48 +01:00
yuanyuanxiangandClaude Code 28c0c9a2a6 Feature: add file management to the Android client
Android 客户端此前没有文件管理:声明了 CLIENT_CAP_V2 却没有实现,主控的
文件管理对话框和 MCP 的 list_files/download_file/upload_file 对 APK 只会
超时。本次复用 Linux/macOS 已在用的 common/FileManager.h,只补平台差异:

- 盘符模型:P=应用私有目录、I=内部存储、S/T/...=SD 卡与 U 盘;V2 上传
  通过 FileTransferV2::SetPathMapper 复用同一套映射。
- 文件通道线上是 GBK。NDK 的 iconv 要 API 28,客户端 minSdk 是 21,改走
  JNI -> Java Charset(NativeText.kt),严格模式失败原样透传。
- Android 11+ 引导开启「所有文件访问」;未授权时只挂 P: 并回一条提示。
  API <=29 用运行时存储权限 + requestLegacyExternalStorage。
- 顺带实现 COMMAND_SEARCH_FILE(深度 32、1 万条),并让 MCP 的
  list_files/download_file/upload_file/read_file 对 APK 开闸。

验证:arm64/armeabi 与模拟器 ABI 编译通过;模拟器上用 MCP 完成列盘、
列目录、下载、上传、中文文件名往返,GUI 文件管理器正常显示 P:/I:/S:。

Model: deepseek-flash
Co-Authored-By: Claude Code <noreply@anthropic.com>
2026-11-16 18:34:46 +01:00
yuanyuanxianganddeepseek-flash 7172ab376d Feature: add build_client MCP tool and improve build dialog linkage
Add a service-local MCP tool, build_client, that patches a client template
with this master's connect settings and writes the binary on the server.
It covers ghost/TestRun/ServerDll/TinyRun plus Linux, macOS and Android,
reusing the same byte path as CBuildDlg::OnBnClickedOk (CONNECT_ADDRESS
overwrite, build-date check, embedded TLS anchor before UPX/padding).
ShellCode AES and payload impersonation stay dialog-only.

The tool is gated by a new McpBuild switch (default 0) and McpReadonly=0.
It refuses to overwrite an existing file unless overwrite=true, protects
the server binaries/settings.ini/upx.exe, validates names strictly and
uses a unique UPX temp file so it cannot race the dialog. Results report
the path, size, target, TLS-anchor status and follow-up tips.

In the build dialog, Linux/macOS/Android targets now also grey out the
install-location combo/label and run mode, save and restore the Windows
compress choice, hide payload/download rows, grey the random-name and
run-as-admin menu items, and fix the TLS-anchor label for posix targets.
OnBnClickedOk is untouched; generated output is unchanged for every target.

New UI strings were added to the en_US, zh_TW and de_DE language packs.
McpBuild is off by default and changes require a server restart.
Verified on a Debug x64 instance: MCP generation for Linux is patched
correctly, Android and ghost anchor/error paths behave, and dialog-driven
Linux/TestRun/SC_AES generation still succeeds. mcp/tools.json regenerated
(55 tools); check_platform_table.py passes.

Co-Authored-By: deepseek-flash
2026-11-15 20:43:28 +01:00
yuanyuanxiangandDeepSeek-V4.1-Flash 1401ff0a4c Feat(android): support the assign-master command
The Android client now handles COMMAND_ASSIGN_MASTER (SHARE_TYPE_YAMA_FOREVER)
and reuses common/host_transfer.h for the parsing and for the on-disk record -
the same code the Linux and macOS clients already use.

Windows and Linux keep the main link where it is and spawn a second instance so
the new master sees the host right away, moving the main link only on the next
reconnect. Android cannot do that: the login state (ClientAuth verification,
the heartbeat ACK watchdog, the main client handle, g_bExit) is process-wide,
so a second login connection would reset the first one's verification and make
it drop every command it receives. Sharing has the same problem and stays
unimplemented. Android therefore switches immediately: change the target,
disconnect, reconnect. The new master sees the host at once and the old one
loses it at once.

Four cases, each exercised against two real masters:

  not transferred, target elsewhere        transfer
  not transferred, target is the original  ignored - it would only cost a
                                           reconnect and leave a record that
                                           "expires back to itself"
  transferred, target elsewhere            refused with a ClientMsg; this is
                                           what stops B from chaining the host
                                           to C, which would orphan the middle
                                           hop because expiry always restores
                                           to A
  transferred, target is the original      early return: the expiry time is set
                                           to now and the verified expiry path
                                           does the restore, so a master can
                                           hand the host back instead of
                                           waiting out the term

The record lives in filesDir/yama_transfer; the original master is captured
once at init and never written back, because restoring from a record that
points at the transfer target is a no-op loop. A target that stays unreachable
for 60 s (and at least 3 attempts) reverts to the original master so a typo
does not lose the host; the 60 s floor exists because a Wi-Fi hiccup would
otherwise cancel a perfectly good transfer.

Both the switch and the expiry are checked once a second rather than once per
heartbeat. With the 30 s cycle a 0.001 day (86 s) transfer took effect 14 s
late and restored 20 s late, measured; now both are under a second.

g_serverIp/g_serverPort moved behind a mutex and every connect site takes a
snapshot first: the transfer rewrites them at runtime while the screen, log,
chat, audio and terminal threads read them to connect, and assigning a
std::string frees the buffer another thread may still be holding.

ClientMsg titles are ASCII. The controller decodes title/text as ANSI/GBK, so a
Chinese literal from this UTF-8 source reaches the message pane as mojibake.

Verified on an API 35 x86_64 emulator: 443 -> 6543 -> back, refused chaining,
unreachable-target revert, natural expiry, and restart from a record.
host_transfer.h is covered by a standalone test (24 assertions: with and
without the transport field, share type rejected, port 0 / days 0 / empty IP /
bad transport, record round-trip, expiry). Sharing is answered with "Android
client does not support sharing a host" instead of being ignored.

Co-Authored-By: DeepSeek-V4.1-Flash
2026-11-15 17:51:44 +01:00
yuanyuanxiangandDeepSeek-V4.1-Flash 3ae54c808e Fix(audio): keep audio packets block-aligned end to end
waveOut only converts whole 65-byte GSM610 blocks; a trailing partial block is
dropped, never carried over. Windows hosts record into a 1000-byte buffer but
the driver fills only 975 (15 blocks) - the last 25 bytes are stale heap the
driver never wrote. Clients ship all 1000 bytes anyway, so PlayBuffer has to
truncate each packet to whole blocks and throw that tail away.

Accumulating the remainder across packets instead - the first attempt at this
fix - inserted 25 bytes of garbage every 1000 bytes and shifted the block
boundary, turning voice monitoring of existing Windows clients into pure noise
while Android stayed fine. Both symptoms are the same "per packet" versus
"across packets" opposition, and per packet is the one that matches the wire.

So the invariant is: one packet carries a whole number of 65-byte blocks, and
nothing is ever carried into the next packet. Windows hosts satisfy it for
free. Android now packs 15 blocks (975 bytes) and pads the rest with zeros to
keep the 1000-byte length that older controllers expect - see AudioHandler.h.

GetRecordBuffer keeps returning the full 1000 bytes on purpose: shortening the
packet would make a v1.4.2 controller memcpy m_ulBufferLength and read past the
end, which is real garbage rather than harmless stale bytes.

Measured against the real waveOut API with a 2 s 1 kHz tone (3250 bytes = 50
blocks = 16000 samples): one 3250-byte buffer played 16000 samples, four
1000-byte buffers played 15360 (25 bytes lost per packet), four 975-byte
buffers played 16000. The encoder was never at fault - the same libgsm WAV49
stream decodes through Windows ACM with a correlation of 0.9999 when handed
over whole.

Also check WHDR_INQUEUE before reusing a header and honour the waveOutWrite
return value, since the old code dropped data silently on WAVERR_BUSY; size the
playback buffers for the largest packet; and unprepare the waveOut headers in
the destructor, which was unpreparing the waveIn headers after they had already
been freed.

Android APKs built before this commit still send unaligned 1000-byte packets
and will sound noisy against this controller - rebuild the APK.

Co-Authored-By: DeepSeek-V4.1-Flash
2026-11-15 17:05:41 +01:00
yuanyuanxiangandDeepSeek-V4.1-Flash d987941e57 Fix(server): stop at startup when the process runs at Low integrity
An exe carrying a Low integrity label makes Windows downgrade the process
token, so HKCU reads/writes and %TEMP% logging all fail silently: the
settings dialog shows defaults, saving does nothing, and no log file is
ever written. Nothing in the UI hints at the real cause.

- Read TokenIntegrityLevel on startup and abort when below Medium
- Print the icacls fix command; Yes copies it to the clipboard
- Never fall through into the main window: running at Low IL is useless
- Keep the service-spawned agent silent, otherwise the 10-second relaunch
  loop turns the dialog into a flood
- Do not try runas: with UAC approval mode off it is a no-op and the child
  inherits Low, so icacls fails with "cannot assign the specified label"
- Add en_US / zh_TW / de_DE translations

The check has to run before both the UAC relaunch and the service self-heal.
Placed after HandleServiceCommandLine, a double-click installs/starts the
service, returns TRUE and exits, so the dialog could only come from the
service-spawned agent - which stays silent to avoid a flood, and the user
saw nothing at all. Placed after LaunchAsAdmin, a Low process without admin
rights loops forever, because runas spawns a child that is still Low.
Service commands (-service/-install/-uninstall) are exempted so the service
can still be installed and removed.

Co-Authored-By: DeepSeek-V4.1-Flash
2026-11-15 11:21:58 +01:00
yuanyuanxiang 7faca2c01b Fix(android): keep encoder operating rate at 30 to restore screen streaming
3ab5154 tied KEY_OPERATING_RATE to the tuned fps, so any profile below 30 (Good=20, Medium=15, Low=12, Minimal=8) pushed it under 30. Some hardware encoders, notably TV SoCs, then drop into a low-power mode that accepts configure/createInputSurface/start without error but never emits a single buffer. The controller receives BITMAPINFO and waits forever on the first decoded frame.

Confirmed on a Changhong Android TV: with operating rate 20 the log stopped right after SendBitmapInfo with no H.264 output at all; clamping to maxOf(fps, 30) produced a first IDR within the same second. KEY_OPERATING_RATE is a resource-planning hint, not a frame limiter - the actual rate is driven by KEY_FRAME_RATE and scene content.

Harden the capture lifecycle while here: fail loudly when createVirtualDisplay returns null instead of advertising a dead surface; downgrade the foreground type back to dataSync before stopping that projection, otherwise Android 14+ tears down a service still declaring mediaProjection and the controller loses the connection entirely; release the previous capture when MainActivity is reopened, including the projection-only state left behind when encoder creation throws before mediaCodec is assigned; ignore stale MediaProjection onStop callbacks that would otherwise tear down a fresh encoder; zero the native screen size on teardown; and make SendLoop's wait timeout so a silent zero-output encoder is reported instead of hanging.
2026-11-14 20:09:14 +01:00
yuanyuanxiang db4543ad54 Release v1.4.3 v1.4.3 2026-11-14 14:30:34 +01:00
yuanyuanxianganddeepseek-flash 06b93f7bdb Feat(client): complete the macOS feature set (phase 0 and 1)
Phase 0 makes implementations that already existed reachable. macOS now
declares TERMINAL, SCREEN_CLIPBOARD, PROCESS and C2C_RECV_ACK; PROCESS is a
new bit and Linux declares it too. SystemManager was dead code -- its
constructor took a second argument and it did not derive IOCPManager, so the
sub-connection skeleton could never instantiate it -- and now matches the
createHandler/OnReceive contract, so COMMAND_SYSTEM really spawns a
sub-connection (proc_listpids, SIGKILL). DataProcess always gets a NULL user,
so main.mm keeps a g_pMainClient handle and the V2 C2C receiver finally
answers TOKEN_C2C_RECV_RESULT. The server asks for SupportsTerminal() on MAC
for exec_command / terminal_* and for SupportsProcess() for kill_process, so
an old build gets "client is too old" instead of a command nobody answers;
kToolPlatforms and mcp/tools.json follow. http_probe stays win/lnx: the
terminal works on macOS, but the probe uses GNU-only base64 -w.

Phase 1 is POSIX parity. ScreenPreview captures through CGDisplayCreateImage,
scales and ships BGRX for the server to encode, and the capability is only
declared when preflight or a real capture says the display is readable.
ActivityHistory samples the frontmost layer-0 window once a second and prints
the same records as Windows and Linux. COMMAND_SCREEN_KEYFRAME_REQ is now
consumed by Linux (x264 IDR) and macOS (VideoToolbox force keyframe): the
receive thread raises a flag, the capture thread -- which owns the encoder --
consumes it and puts it back if the frame never went out. The macOS quality
level persists in NSUserDefaults because main.mm rewrites config.conf.

Linux client and Debug x64 server rebuild green; check_platform_table PASS.
Not built or run on a Mac.

Co-Authored-By: deepseek-flash
2026-11-14 13:30:50 +01:00
yuanyuanxianganddeepseek-flash c2b59f5d4a Feat(client): restart the macOS client once permissions are granted
macOS applies TCC grants per process, so ticking Screen Recording and
Accessibility in System Settings does nothing for a running client.
install.sh resets both with tccutil and re-signs the bundle ad-hoc, and a
rebuilt binary carries a new cdhash, so every update costs two rounds of
"grant one, kill the app, reopen it".

When a permission is missing at startup the client now starts a watcher
that polls CGPreflightScreenCaptureAccess and AXIsProcessTrusted -- only
for the permission that is actually missing, so a screen grant the startup
capture already proved is never re-judged by preflight, whose false
negatives after re-signing would otherwise block the restart forever.

Once everything reads granted the main loop disconnects and hands over to
a fresh process instead of exec'ing in place: TCC re-evaluates by pid, and
the child closes every fd above 2 before exec, so the old main and
sub-connection sockets cannot keep the server holding a dead host. The
parent exits only after the child starts; a child that dies on the spot
(exec failure, AMFI rejecting an un-re-signed binary, dyld abort) keeps
the current process alive instead, and a stop request during the hand-off
terminates it again. GHOST_AUTO_RELAUNCHED bounds this to one auto-restart
per launch, and the new process logs that it was started this way, which
is what the 运行日志 dialog shows.

Not built or run on a Mac yet.

Co-Authored-By: deepseek-flash
2026-11-14 12:52:48 +01:00
yuanyuanxianganddeepseek-flash 4456467c50 Fix(client): build on macOS after the pthread_t cast
The macOS client failed to compile at client/IOCPClient.cpp:788:
static_cast from 'pthread_t' (aka '_opaque_pthread_t *') to 'uintptr_t'
is not allowed. Darwin defines pthread_t as a pointer, while Linux and
Android define it as an integer, so routing it through uintptr_t refused
to build there.

On POSIX the stored value is only a non-null "a worker thread exists"
marker: CloseHandle and SAFE_CLOSE_HANDLE are no-ops, and nothing ever
dereferences it. reinterpret_cast<HANDLE> accepts both shapes — integer
to pointer on Linux/Android, pointer to pointer on macOS — so the same
line now compiles everywhere. IOCPUDPClient.cpp had the identical cast
and got the same one-line change; it is not in any current build list,
but it would hit the same error if it were.

Verified with a green Linux client rebuild (integral pthread_t). Not yet
built on a real Mac.

Co-Authored-By: deepseek-flash
2026-11-14 12:19:44 +01:00
yuanyuanxianganddeepseek-flash a25e89b220 Feat(client): report macOS runtime logs to the controller
macOS already handled COMMAND_QUERY_LOG and opened the sub-connection that
sends TOKEN_REPORT_LOG, but the snapshot was always empty: macOS Mprintf went
to NSLog/fprintf(stderr) and never through Logger, so the ring it dumps stayed
empty and both the 运行日志 dialog and MCP get_client_log got nothing.

macOS now writes Logger like Linux does, with enable=false so no second log
file appears under ~/.config/ghost, and Logger mirrors each line to stderr,
which main.mm already redirects to /tmp/ghost.log in daemon and App bundle
mode. Prefix and timestamp match on both sides, so dialog and file can be
compared line for line.

main.mm logged its own lifecycle through NSLog, which never reaches the ring,
so the lines people open the dialog for were missing; those calls now use
Mprintf. The ObjC helpers (ScreenHandler/H264Encoder/InputHandler/Permissions)
keep NSLog and stay file-only. POSIX reports one snapshot per connection, so
reopening 运行日志 takes a fresh one; Windows keeps pushing every 3s.

Verified with a WSL probe built with -D__APPLE__ (ring, incremental dump,
stderr mirror), a MinGW probe for the _WIN32 branch, and a green Linux client
rebuild. Not built or run on a real Mac.

Co-Authored-By: deepseek-flash
2026-11-14 12:08:52 +01:00
yuanyuanxianganddeepseek-flash b743de6747 Feat(client): add TLS transport to the macOS client
macOS shares the Linux transport: TlsChannel.h now dispatches __APPLE__ to
the OpenSSL implementation, so handshake, pinned trust anchor, reload and
removal all come from client/TlsChannelLinux.cpp. Only the platform glue
is new: ConfigDir() follows initConfigPaths (HOME, then getpwuid(), then
/tmp; no XDG) so the anchor sits next to config.conf, and ExeDir() uses
_NSGetExecutablePath.

First connect stays plaintext. The operator turns TLS on from the online
list: COMMAND_TLS_ENABLE carries the anchor PEM, COMMAND_TLS_DISABLE
removes it. macos/main.mm saves the anchor, calls TlsReload() and only
reconnects when the transport actually changed, so re-saving the same
anchor does not drop a live session. RES_TLS is filled from TlsEnabled()
and refreshed on every reconnect; fillLoginInfo clears szReserved first
now, because AddReserved appends and it runs twice on a group change.

CMake builds arm64 only (deployment target 11.0) and links Homebrew
openssl@3 statically when libcrypto.a is present, so the binary carries
no Homebrew path dependency. Not built or run on a Mac yet: the Apple
branch was syntax-checked under WSL and the login refresh probe-tested;
macos/README.txt has the build and verify steps.

Co-Authored-By: deepseek-flash
2026-11-14 11:43:30 +01:00
yuanyuanxianganddeepseek-flash 3d87ec6720 Fix(client): detach the receive thread instead of leaking one per connection
CloseHandle and SAFE_CLOSE_HANDLE are empty off Windows, so the POSIX
receive thread is never released: nothing detaches it and nothing joins
it. Every IOCPClient keeps one thread for good, and each screen, file,
shell or log sub-connection constructs a fresh IOCPClient. Once the leak
reaches RLIMIT_NPROC, pthread_create returns EAGAIN, std::thread throws,
and OnServerReceiving's catch(...) swallows it: every command that spawns
a worker goes quiet while COMMAND_SYSTEM keeps working. Observed on a Mac
after six weeks: 2048 threads against a 1333 limit.

Detach the thread right after creation so it is reclaimed when it
returns; the destructor still waits on m_bWorkThread, so nothing else
changes. Also log the pthread_create failure that used to be silent, and
publish S_STOP as the very last write in WorkThreadProc: the destructor
reads it as "thread is gone" and frees this, so the m_bIsRunning that
used to follow it could land in freed memory.

Two smaller fixes on the same sub-connection path:

- common/sub_conn_thread.h never called SetDefaultProto, so sub-connects
  fell back to plaintext TCP whatever g_SETTINGS.protoType said: behind a
  reverse proxy the packet dies before the master (no [ConnAuth] on the
  server, only "waiting for ack timed out" on the client). Android did.
- macos/main.mm and linux/main.cpp log the spawn before starting the
  worker and catch std::system_error, reporting e.code().value() rather
  than errno, which libc++/libstdc++ never set here. The macOS skeleton
  also reports ConnectServer failures and a null createHandler.

Co-Authored-By: deepseek-flash
2026-11-14 11:43:04 +01:00
yuanyuanxianganddeepseek-flash 80c7d1ed53 Fix(go): decode Windows host names with the system code page
The web console showed Chinese computer names as a run of U+FFFD.
ParseLoginInfo sent every string field through the UTF-8 decoder once a
client advertised CLIENT_CAP_UTF8, but szPCName and the OS string are not
covered by that bit: Windows fills them from gethostname(), a narrow API,
so they carry CP936/GBK even on modern clients. The MFC server decodes
these two fields with CP_ACP (HostJson.cpp::AnsiToUtf8), which is why the
Windows server and its web view were never affected.

A new DecodeLoginAnsiField picks by client type instead of capability:
LNX/MAC/macOS/APK are UTF-8 (they build the field from a UTF-8 host name
or, for Android, the device model), everything else is GBK. "macOS" is
what pre-1.0 macOS builds report; GetClientType sends "MAC" today and the
MFC WebService still accepts both. ASCII host names come out
byte-identical either way, and legacy clients keep the name they had.

Reserved keeps its capability-based decoding, so UTF-8 file paths and
locations are untouched; OS strings are ASCII in practice. The one case
that gets worse is a Windows machine running the "Beta: Use Unicode UTF-8"
locale, which will now mojibake there. Sniffing UTF-8 to cover it would
misfire on real GBK names -- 930 of 6763 GBK hanzi pass as a UTF-8
two-byte sequence, roughly 2% of two-character names -- so the
deterministic rule wins and the trade is written next to the function.

Tests cover GBK names from capable and legacy clients, UTF-8 names from
Linux, Android and legacy macOS, and Reserved still honoring the bit.

Co-Authored-By: deepseek-flash
2026-11-14 11:42:32 +01:00
yuanyuanxianganddeepseek-flash 9fadb58c76 Fix(client): rotate HELL header encoding across reconnects
A Release client drew one of the twelve HELL header encodings in the
constructor and kept it for life. The Go fallback server latches a type
from the first packet and only decodes None..V6, so every client that
drew V7..V10 could never log in to it — a third of them, at random, for
good.

The main connection now advances to the next type when it reconnects
after a connection that was never login-acked (CMD_MASTERSETTING), and
republishes the accepted type into CONNECT_ADDRESS::szFuture. A type that
did log in is kept, so a healthy client no longer churns through values
the fallback would reject. Sub-connections, including one-shot ones
(file/process/screen), inherit the published value at construction and
on every reconnect instead of rolling their own dice. Debug keeps its
None..V6-only range; the initial Release type now comes from
random_device rather than time() % N, which handed a whole batch started
in the same second the same value.

The slot sits at szFuture+16, after LOCAL_TEST_CLIENT_MAGIC, guarded by
static_asserts; it is memory-only and never persisted or sent. Swapping
the encoder is a single atomic function-pointer store, so the send and
receive threads see either the old or the new encoder and never a
dropped object.

Co-Authored-By: deepseek-flash
2026-11-13 16:47:53 +01:00
yuanyuanxianganddeepseek-flash a818ace83c Fix(mcp): declare conditional tool arguments and surface probe headers
Several tools enforced argument requirements that existed only in prose,
so a model had to send a bad call to learn them. A new
AppendConditionalRequired helper emits allOf/if/then entries, and the
schemas now say:

- get_screenshot: mode=region needs width and height; mode=window needs
  hwnd. monitor keeps its default of 0.
- remote_keyboard: action=type needs text; key_down/key_up/key_press
  need key.
- remote_mouse: action=drag needs x2 and y2.
- terminal_exec: command or session_id, at least one (anyOf), matching the
  handler's -32602 when both are missing.

http_probe put the response headers only in structuredContent, which a
client that reads the text block never sees; Location, Set-Cookie and
Content-Type are exactly what a redirect or auth decision needs. The
text block now starts with a headers section, bounded to 4096 bytes and
1200 bytes per line, backing off to a UTF-8 boundary when a line has to
be cut. The full set stays in structuredContent.headers.

mcp/tools.json mirrors the schemas and tools_minimal.json is regenerated.
Verified against a fresh Debug build: verify_tools --live reports 49
tools identical.

Co-Authored-By: deepseek-flash
2026-11-13 13:12:10 +01:00
yuanyuanxianganddeepseek-flash 31883edc09 Fix(mcp): align Go tool text and list_files batch with Win32
The Go minimal server sent models after tools it does not have: read_file
pointed at download_file and search_file, both absent from its nine-tool
set, and the 2 MiB message named a download path that does not exist. It
now names list_files, terminal_exec and the Windows controller server.

Terminal errors lost the one piece of state the model needs to recover.
A busy terminal now says the holder is the web console (no MCP session to
close), and a cancelled exec carries the session_id to poll or release.

list_files ids[] was advertised in the shared schema but answered -32005.
It now implements the Win32 batch contract: 50 ids, ids past the 50 s
deadline marked skipped rather than failed, results in input order. The
deadline only gates starting a host; one already running finishes on its
own timeout, so its result is never mislabelled as a client abort. Each
entry takes the per-device lock the single-host path gets, so a host busy
with another tool fails that entry with -32003 instead of running beside
it. An empty ids array is a valid empty batch, as on Win32.

The initialize instructions now describe only what this build implements.

Co-Authored-By: deepseek-flash
2026-11-13 12:57:12 +01:00
yuanyuanxianganddeepseek-flash 61b9031269 Fix(mcp): bound host_inspect, precheck remote_open, name the busy holder
Three smaller contract fixes that remove ways for an agent call to hang
or fail without an explanation:

- host_inspect with several aspects opens one sub-connection per aspect
  (5s ready + 12s list each), so all ten could run ~170s and outlive the
  caller's HTTP timeout. After 60s no new aspect is started; the running
  one finishes on its own timeout and the skipped ones land in
  errors.<aspect> with code -32001 and a "skipped:" message, so the model
  can retry with fewer aspects.
- remote_open checked nothing before opening the hidden screen session.
  A Linux host that declares capability bits but not
  CLIENT_CAP_SCREEN_PREVIEW has no X11 display, so capture and injection
  cannot work: return -32005 immediately instead of waiting out
  timeout_ms and then reporting a sub-connection timeout. Android is
  deliberately excluded -- its SCREEN_PREVIEW bit tracks accessibility
  (API 30+ takeScreenshot for get_screenshot), while remote control uses
  MediaProjection capture and dispatchGesture, which can work without it.
  Old hosts with empty caps are still let through.
- The -32003 busy errors in remote_open now append the DescribeBusy
  suffix (tool, elapsed), matching the other busy paths.

tools.json descriptions are kept byte-identical to the C++ literals.
Debug build green; check_platform_table, gen_go_tools --check and
go test ./... pass.

Co-Authored-By: deepseek-flash
2026-11-13 12:43:37 +01:00
yuanyuanxianganddeepseek-flash d49ebe521d Docs(mcp): correct claims in the server instructions agents rely on
The initialize.instructions text is the only guide a model gets (it cannot
read docs/), and several statements disagreed with the code:

- get_keylog was described as always visible; it is gated by McpKeylog and
  hidden when the switch is off.
- Dangerous machine actions were not mentioned: freeze/thaw and
  stop/restart stay in tools/list but need McpMachineDangerous and return
  -32006 at call time.
- -32006 was described as policy/admin-only; MFC also returns it when an
  old client lacks CLIENT_CAP_V2. The Go server returns -32005 for that
  case, so its own instructions now say so.
- -32001 advice assumed every failure is a timeout; it also covers
  cancellations, http_probe parse failures and unconfirmed writes.
- "Unsupported combos always return -32005 immediately" ignored paths that
  surface as -32001 once a sub-connection is involved.
- Linux matrix listed all host_* as unsupported, but host_set_remark and
  host_set_watch_level only touch server-local data.
- local_dir / local_path are paths on the controller, not the user's box.

Also align the error table and platform distribution in the docs, and note
that hidden fallback aliases remain callable. Debug build green; go test,
check_platform_table and gen_go_tools --check pass.

Co-Authored-By: deepseek-flash
2026-11-13 12:32:33 +01:00
yuanyuanxianganddeepseek-flash 292c3191dc Fix(mcp): make declared schemas match what the handlers return
Several tool contracts disagreed with the runtime shape, which forces an
agent to guess instead of following outputSchema:

- get_server_status returned {"status": {...}} while outputSchema has the
  fields at top level; return the status object directly.
- get_screenshot description claimed structuredContent.image carries the
  base64 data; it only carries mimeType/width/height/bytes, the bytes are
  in the content image block.
- host_control_service accepted service_name silently, but not in schema;
  document the alias and add anyOf [{required:[name]},{required:[service_name]}]
  so a call missing both fails at validation, not at execution.
- kill_network_connection dry_run invented dryRun/connection fields absent
  from ActionOutputSchema; use the shared BuildDryRunResult shape.
- search_file outputSchema left files.items untyped; declare
  path/name/modified/dir/size and the paging fields it already emits.
- chat_* id hints still named the removed list_online_hosts/search_hosts.

tools.json hunks keep the live-dump key order (alphabetical inside schemas),
tools_minimal.json is regenerated, and mcp_smoke.ps1 now reads the flat
structuredContent. Debug build green; check_platform_table, gen_go_tools
--check and go test ./... pass.

Co-Authored-By: deepseek-flash
2026-11-13 12:23:39 +01:00
yuanyuanxianganddeepseek-flash 5e012019ba Fix(mcp): list the whole directory before paging list_files
list_files stopped parsing at 500 entries, so a larger directory reported
total=500 with hasMore=false and offsets past 500 returned nothing: the model
was told a false limit and could not reach the tail. Parse the full
TOKEN_FILE_LIST payload (100000 cap only to bound a pathological directory),
page over it, and report truncated=true plus a summary note when the cap hits.

Only an empty path now means list drives. Windows "." "/" "\" are normalized
to empty in BuildListFiles, while Linux/macOS "/" is a real root directory and
is listed; OnDriveList no longer keeps its own copy of the magic-path rule.

The file-manager channel carries GBK both ways (Windows FindFirstFileA;
common/FileManager.h runs gbkToUtf8 on incoming paths, utf8ToGbk on outgoing
names). The old CP_UTF8 choice for LNX/MAC decoded GBK names wrongly and sent
UTF-8 paths to a client that treats them as GBK. Paths now go out as GBK, or
as raw UTF-8 when GBK cannot represent them (the client's iconv then passes
the bytes through). Names decode GBK-first, UTF-8 on failure: UTF-8-first
misreads ~18% of common hanzi whose GBK bytes are also valid UTF-8.

Go's server gets the same contract: 100000 cap, truncated in
structuredContent, and the cap check after a real record so an exact-cap
listing with trailing padding is not called truncated. tools_minimal.json is
regenerated; the Go truncation test and the design doc are updated.

Debug server builds; check_platform_table, gen_go_tools --check and
go test ./... pass. The Release instance was not rebuilt or restarted.

Co-Authored-By: deepseek-flash
2026-11-13 12:13:20 +01:00
yuanyuanxianganddeepseek-flash 42dd70fe20 Fix(mcp): make terminal busy and cancel semantics usable by an agent
exec_command answered -32003 "device busy" with no way forward: the message
named neither the occupying session nor how to free it, and mcp_cancel_session
could only target in-flight calls, so a persistent terminal left behind by an
earlier session blocked the host until its idle timer expired. An agent had no
route back to a working state.

Build the busy text from the live session table: terminal sessions now report
parent session_id, idle and elapsed seconds, and point at terminal_exec (or
terminal_close with id and session_id) when a persistent session holds the
host, or at mcp_cancel_session(request_id) when the occupier is a running
exec_command. exec_command sweeps idle terminals before it begins a pending
wait, so a session abandoned after 300s does not require a terminal_* call
first; SweepIdleTerminals now requires started so it cannot reclaim a session
that is still in BeginTermPending and hand the device to a second caller.

Cancel becomes addressable and honest. id=0 is rejected with -32602 instead of
being treated as "all hosts", the calling request is excluded from matched and
released (previously the poll saw itself and released was never true), rows
carry cancellable, and when nothing was cancelled the reply lists what matched
and which close tool takes it. Instructions, tool description, inputSchema
(anyOf request_id/id/session_id) and the released description now agree:
kind=call only, persistent sessions close by id+session_id, pending and
file_transfer entries are released by cancelling the call that owns them.

tools.json is regenerated for the schema and description changes. Debug server
builds, check_platform_table.py and gen_go_tools.py --check pass; the Release
instance was not rebuilt or restarted.

Co-Authored-By: deepseek-flash
2026-11-13 11:56:25 +01:00
yuanyuanxianganddeepseek-flash 3d18b2119a Fix(mcp): put listing rows and host ids into text blocks
MCP clients that surface only content[].text saw just count summaries from
list_hosts and get_audit_log; the 64-bit host id lived only in
structuredContent. Without the id, read_file, get_host_detail and
terminal_exec cannot be addressed, so the tools were unusable from those
clients.

Append a tab-separated table after the summary for every list-shaped local
tool: list_hosts (id first, then name/ip/group/os/online/clientType/
last_seen), get_audit_log (time/type/msg), list_files (drives and directory
entries) and get_host_detail (compact host JSON; id/ok/detail rows for a
batch call). Only the returned page is rendered, cells are flattened to one
line, and the truncation note stays on its own line before the table.

structuredContent is unchanged and remains the authoritative copy. Tests
cover row contents, paging, escaping and truncation ordering; a live run
against a Debug client confirmed the id is now visible in text. The MFC
server needs no equivalent change: BuildResult already appends the full
structuredContent as a second text item, so text-only clients there already
receive host ids. Go's envelope emits a single text item, which is why the
rows go into it.

Co-Authored-By: deepseek-flash
2026-11-13 11:25:57 +01:00
yuanyuanxianganddeepseek-flash 70556391dd Docs(mcp): record the Go MCP overall acceptance
Run the section 5 checklist end to end against the debug Go server and a
Windows debug ghost: nine tools called, tools/list at 22578 B, twenty
consecutive terminal_exec calls with zero failures, read_file SHA-256
matched, 30 audit entries with device/tool/code/ms, and --subset passing
in both 9-tool and readonly 7-tool modes. Race tests stay clean.

Two checklist items get corrected rather than ticked: hub did change
(SendToConn in M6 and the terminal lease generation in M4a, both needed
and unit tested), and the MFC regression has no target because the whole
milestone range touches no C++ file. Note the running Release binary is
an older build reporting the old tool names; it was left alone.

Co-Authored-By: deepseek-flash
2026-11-12 23:12:29 +01:00
yuanyuanxianganddeepseek-flash d4f10db1f2 Feature(Go): verify_tools --subset and MCP deployment docs
Add a third mode to verify_tools.py that validates the Go server end to
end: it fetches /mcp tools/list and requires the name set to equal the
nine implemented tools exactly (seven in readonly mode), compares
description / inputSchema / outputSchema field by field against
mcp/tools.json, and also checks the published order. Unlike --live,
extra or missing tools are failures, not notes.

The field-comparison loop is factored into report_field_diffs so
--offline / --live and --subset share one comparison, diff printer and
FIELDS tuple.

Document and deploy the endpoint: the systemd env example gains
YAMA_MCP_TOKEN / READONLY / TERM_IDLE / MAX_CONCURRENCY / READ_MAX,
the design doc moves to implemented and its section 10 now matches the
code (embedded tools_minimal.json, the three packet dispatch groups).
The tools README explains gen_go_tools.py --check and --subset.

Verified against a freshly built debug Go server on 16543/18090:
read-write mode passes with 9 tools, YAMA_MCP_READONLY=1 passes with 7,
and both mismatch directions (extra tools, missing tools) fail with
exit 1. gen_go_tools.py --check stays clean; no Go code changed.

Co-Authored-By: deepseek-flash
2026-11-12 23:09:33 +01:00
yuanyuanxianganddeepseek-flash 9ce1a58bc3 Feature(Go): read_file over the V2 stream receiver
read_file reuses the list_files handshake: COMMAND_LIST_DRIVE opens the
file-manager sub-conn, which then gets
[CMD_DOWN_FILES_V2][targetDir\0][path\0][\0] and streams
COMMAND_SEND_FILE_V2 chunks plus a COMMAND_FILE_COMPLETE_V2 carrying the
whole-file SHA-256. Windows clients open a fresh authenticated sub-conn
for the chunks; POSIX clients stream on the file-manager conn itself, so
that conn is retired when the call ends rather than right after the
request. TOKEN_DOWNLOAD_ERROR on the file-manager conn maps to -32009 /
-32010 / -32000 like the Win32 server.

Bytes land only in a per-call os.MkdirTemp dir; the client name is
checked against the target dir (separator-normalised, path.Clean, so
..\.., absolute, UNC and mixed separators are refused) as
defence-in-depth, never used as a path. First chunk enforces the size
gate (ReadMax) and rejects multi-file batches, so an expanded directory
fails with -32602 instead of returning its first file. Chunks from a
sub-conn opened for an earlier call are dropped by connection ID, data
sub-conns are closed when the call ends, and a closed sub-conn fails the
call fast instead of waiting for the stall watchdog.

Text windowing, encoding detection (BOM / UTF-8 / GBK / explicit /
latin1) and EOL handling mirror McpServer.cpp. Verified with the Debug
ghost on Windows 11 and the WSL Ubuntu ghost: .env text plus newline is
byte-identical, sha256 equals SHA-256 over the file, windows/GBK/empty/
max_bytes/directory/size-gate/missing-path/POSIX-path cases all pass.

Co-Authored-By: deepseek-flash
2026-11-12 23:04:35 +01:00
yuanyuanxianganddeepseek-flash d7accf1d30 Feature(Go): list_files over the file-manager sub-connection
The MCP server could not browse a device's file system. It now sends
COMMAND_LIST_DRIVE on the main connection, waits for the client to open
its file-manager sub-connection and report drives, then reuses that same
sub-connection for COMMAND_LIST_FILES with the directory path. Replies
are TOKEN_DRIVE_LIST, TOKEN_FILE_LIST or TOKEN_FILE_LIST_ERROR, decoded
from the same GBK the C++ client writes on every platform.

An empty or missing path returns the drive list, matching the published
tool description. Any other path, including /, lists one level of that
directory; the Win32 server folds / into the drive list, but doing so
would make a POSIX root listing unreachable. Entries carry name, isDir,
size and an mtime converted from FILETIME, and the 500-entry cap matches
the served contract and the Win32 parser; a truncated listing says so in
the summary. The reply is paged with the usual limit/offset window.

Errors are translated like the Win32 server: win32 5 is a permission
error, 2 and 3 are not-found, anything else is internal. Legacy clients
stay silent instead of reporting an error, which surfaces as a timeout
with an explanation.

The sub-connection is a resource the client allocates per call, so one
deferred cancel is the single retirement point: it reports the sub-conn
it saw and that connection is closed on every exit path, including a
call that gives up while the drive list is already queued. Packets that
arrive after the call returned are treated as orphans and retired, and
only the connection that answered the drive-list phase may answer the
directory request.

Also add a uniqueness test over the command and token byte constants,
and SendToConn so sub-connections are written through the hub's framing
path instead of a raw conn write.

Co-Authored-By: deepseek-flash
2026-11-12 22:34:17 +01:00
yuanyuanxianganddeepseek-flash 5227d4d78e Feature(Go): get_screenshot over the main-connection preview RPC
COMMAND_SCREEN_PREVIEW_REQ (247) / TOKEN_SCREEN_PREVIEW_RSP (248) is a
request/reply pair on the device's main connection: the client captures,
scales and encodes the frame itself, so no sub-connection is opened and no
screen-session slot is taken. get_screenshot can therefore run while a
human is watching the same machine.

The server keeps one pending request per device in a small table, matches
replies by reqId and drops foreign or late ones, and bounds a round trip
with an 8s timer. A missing CLIENT_CAP_SCREEN_PREVIEW bit is refused with
-32005 before anything is sent; region/window/monitor parameters are
refused with the same code because the v2 CLIENT_CAP_SCREEN_REGION
extension is not implemented in this build. Status 4 maps to -32602
because the caller can fix the target, while capture/encode failures stay
-32000.

Windows clients return JPEG directly. Linux clients have no JPEG encoder
and return top-down BGRX, which the server converts (R/B swap, opaque
alpha) before wrapping the frame as an MCP image item. The image item is
new to the content envelope; text tools keep text-only items.

Verified live against x64\Debug\ghost.exe (JPEG FF D8 FF, decoded size
matches metadata, max_width clamped to 64) and against linux/ghost under
WSL (BGRX path, valid JPEG, black frame from the known Xwayland capture
limitation). gofmt/vet clean, unit and -race tests green.

Co-Authored-By: deepseek-flash
2026-11-12 22:07:07 +01:00
yuanyuanxianganddeepseek-flash 808747f9d2 Feature(Go): terminal_close, idle sweep and legacy-client guard
Add the terminal_close tool so a caller can release a shell session
explicitly instead of waiting for it to age out. The tool is idempotent
for the session it names, rejects a session_id that does not match the
live session with -32002, and runs without the per-device lock so it can
interrupt a terminal_exec call that is still polling on the same device.

Give hub leases a generation counter: the generation is bumped when a
pending lease is created and carried across a device re-login. MCP-side
closes pass the generation, so a stale session can no longer tear down a
shell a human operator opened after the device reconnected. The reaper
runs on a 30 s ticker (shortened when TermIdle is smaller), skips
sessions that are still opening, and reclaims idle sessions as well as
commands overdue past the one-hour busy cap.

The pre-bind terminal-close path in cmd no longer closes
unconditionally; it touches only a pending lease, because an unbound
sub-connection carries no lease identity and may be a stale orphan.

Covered by unit tests for close semantics, lock exemption, reaper
lifecycle and lease-generation ownership, plus a live run against a
Debug ghost: close before and during a command, reopen, idle reap and
mismatched-id rejection all behave as specified.

Co-Authored-By: deepseek-flash
2026-11-12 21:53:54 +01:00
yuanyuanxianganddeepseek-flash 599c891c00 Feature(Go): terminal_exec with sentinel cleaning and polling
Implement M4b of the Go MCP minimal plan: terminal_exec runs one command in a
device's persistent shell and polls the rest of a timed-out command.

Wire format follows the Win32 server: ConPTY sends "@echo off & <cmd>" plus a
sentinel line carrying %errorlevel%; POSIX PTY clears PS1 and uses $?. Output
cleaning is a byte-faithful port of the MFC stages (ANSI, CRLF, echoed input,
sentinel remnants) and is shared by commands and polls.

A timed-out call leaves the session and the command running; the next call with
only session_id delivers from the cursor it left. Per-window output is bounded
by max_output_bytes, truncated on a line boundary, and ring evictions are
reported as dropped_bytes. When the shell dies mid-command the session stays
reachable until its buffered tail has been polled, then is released without
touching the hub, which may already belong to a new viewer.

Adds ClientCapTerminal (0x8000) for the Android gate; older APKs, macOS and
legacy non-PTY shells are refused with -32005.

Co-Authored-By: deepseek-flash
2026-11-12 21:38:00 +01:00
yuanyuanxianganddeepseek-flash 12b1bd4786 Feature(Go): MCP terminal sessions with a 256 KiB ring buffer
Add the server-side half of the terminal tools: a per-device session
table that claims the hub's single-viewer shell lease for MCP, and an
output ring that survives a timed-out request so a later poll can still
collect the command's result (terminal_exec itself arrives in M4b).

The ring keeps the newest 256 KiB of shell output, tracks absolute
offsets, and counts dropped bytes so callers can report truncation. A
sentinel scanner looks for the per-command done marker, skipping the
echoed command line and accepting Windows' negative error codes; its
scan position is incremental with a small overlap so a marker split
across TCP reads is still found.

Server implements hub.EventHandler and cmd subscribes it when the
endpoint is enabled; only the three terminal callbacks do work, and
OnTerminalData stays cheap on the TCP read loop (lookup, append, scan,
broadcast). Opening inserts the session before calling the hub so an
early OnTerminalReady cannot be lost, stale close events that race a
fresh open are ignored while the hub still holds the lease, and idle
sweeps verify session identity. The reaper and terminal_close land in
M4c.

Co-Authored-By: deepseek-flash
2026-11-12 21:14:53 +01:00
yuanyuanxianganddeepseek-flash 1076e7614a Feature(Go): per-device locks, a global call gate and tool-call audit
Add the three cross-cutting guards the Go MCP endpoint needs before any
tool talks to a client. Each tools/call now takes one of MaxConcurrency
global slots and, for single-host tools, that host's device lock; both are
non-blocking, so contention returns -32003 instead of queueing. Panicking
handlers are converted to -32000 rather than dropping the connection.

Write one mcp.tool.call audit record per named call, including rejected
ones: actor/role/source, tool, device, ok/code, duration, a size-only
result summary and a truncated argument digest. Commands keep only their
first word plus length, and free-form or credential fields (text, message,
body, headers, password, token) are replaced by their size, so secrets do
not reach the audit file.

Co-Authored-By: deepseek-flash
2026-11-12 21:05:37 +01:00
yuanyuanxianganddeepseek-flash 774c0d2545 Feature(Go): four local MCP read tools and a shared audit query package
Implement milestone M2 of the minimal MCP plan: the tools that answer from
the server's own state instead of opening a device channel.

- Extract the audit-log scanner from web into package auditquery so the
  admin page and get_audit_log share one implementation. The web handler
  keeps its 500-row cap, the MCP tool uses the protocol's 1000-row cap.
  Query gains json tags for the web snake_case wire format (device_id,
  warn_only) and reports TotalAll before filters.
- Add package buildinfo and inject Version/Commit with -X from build.ps1
  and the Makefile; go-winres refreshes Windows resources from the git tag
  when available. An unversioned build reports "", and only initialize
  substitutes "dev".
- list_hosts: online/offline pools, include_offline merge, every
  documented filter, limit/offset paging with total/totalAll/hasMore, and
  schema-named host fields (authStatus/tls/remark are never fabricated).
- get_host_detail: single id or a batch of up to 50, online lookup then
  the last history record, capabilities from protocol.SupportsCap plus the
  Windows/registry/virtual-desktop rules; v2 is not listed.
- get_server_status: version, uptime, online/offline counts, port and
  bind. sessions stays absent until the MCP session table lands in M3.
- get_audit_log: case-insensitive event substring, keyword, paging;
  hasMore turns false at the MaxOffset clamp so paging cannot loop.

Wire hub, history, audit path and listen address through mcp.Config from
cmd/main.go. Tests cover pools/filters/paging, capability bits, batch
failures, audit paging and the unversioned build.

Co-Authored-By: deepseek-flash
2026-11-12 20:55:18 +01:00
yuanyuanxianganddeepseek-flash 3f1957a9c9 Feature(Go): MCP endpoint with bearer auth and tools/list
Add a stateless POST /mcp endpoint to the Go server, mounted by the web
server and built from an environment-driven Config in cmd.

The endpoint gates on YAMA_MCP_TOKEN: without it the route is not
registered and /mcp 404s. Requests use a constant-time bearer compare,
and transport failures stay transport failures (401 with a
WWW-Authenticate challenge, 405 for anything but POST, 413 above 8 MiB,
204 for notifications). Everything after a parsed JSON-RPC request is
HTTP 200, including -32600 for batch arrays and -32601 for unknown
methods or tools.

tools/list returns the nine minimal tools verbatim from an embedded
copy of the canonical schemas. tools/mcp_tools/gen_go_tools.py extracts
them from mcp/tools.json, preserving order and only the four published
fields, and its --check mode detects drift. Readonly mode hides and
refuses terminal_exec/terminal_close (-32006); tools that are listed but
not implemented yet answer -32000 until their milestone lands.

Also sync design §3.2 and the M2/M7/M8 plan text to tools.json, which
is the sole schema contract: files not entries, line-based read_file,
no since, camelCase capabilities, max_width [64,1920] defaulting to
1024, and outputSchema included in the M8 subset comparison.

Co-Authored-By: deepseek-flash
2026-11-12 20:35:03 +01:00
yuanyuanxianganddeepseek-flash 5f124fcb3a Docs(mcp): add Go minimal MCP design and implementation plan
Add the v1.0 design for the Go-side minimal MCP server (nine read-only
tools over hub, audit log, terminal and file channels) and the staged
plan that turns it into eight commits.

Record the five decisions settled before construction: extract the audit
query scanner into server/go/auditquery, inject version and commit via a
buildinfo package plus go-winres, treat mcp/tools.json as the only tool
schema contract, verify against a real client, and expose seven tools in
readonly mode.

Add the M0 findings: TestRun.exe cannot log in, because it needs
ServerDll.dll loaded through MemoryDllRunner and the release build deletes
itself when started outside its install path. A Debug ghost.exe came
online against a local Go server in trial signer mode within ten seconds.

Co-Authored-By: deepseek-flash
2026-11-12 20:17:54 +01:00
yuanyuanxianganddeepseek-flash 425d737ca0 Fix(mcp): harden terminal teardown and fill annotation gaps
OnTerminalClosed now erases the shell route and nulls the session pointer
before OfflineProc returns that context to the pool, and WaitTerminalReady
re-looks-up the session on every wake, failing with cleanup when it is gone,
closed, or has no sub-connection. Before, a waiter could CancelIO a recycled
context, or a late cleanup could unroute a connection that reused it.

terminal_close only set closed and expected a waiter to clean up, so after a
caller timeout the remote shell kept running and the slot stayed busy for an
hour. A waiters counter now separates the cases: with a waiter the close
hands off, without one it erases the session and cancels IO at once.
WaitTermCommand's closed branch keeps a truncated tail pollable instead of
dropping it, cancelling IO immediately, and the drained poll cleans up.

The write side had the same hazard. exec_command, terminal_exec and
http_probe wrote the command line after the prompt wait without rechecking
the sub-connection; IsTermSubCtxLive now skips the write when the shell has
died, and WaitTerminalDone reports closed on every failure path so callers
never CancelIO a pointer that may be back in the pool.

list_hosts, read_file and http_probe were missing from kToolHints and got
destructive defaults; the first two are now read-only/idempotent, http_probe
stays writable because its method can mutate the probed service.

Verified on the isolated Debug instance: the truncated tail drains without
gaps (12514 lines), a waiterless close frees the slot in 0.1s, and the
terminal, exec_command, http_probe, 8a/8b/8c and verify_tools checks pass.

Co-Authored-By: deepseek-flash
2026-11-12 18:27:07 +01:00
yuanyuanxianganddeepseek-flash 5841f27df9 Feature(mcp): unify window and service controls behind one name per state
operate_window / host_control_window and control_service / host_control_service were two
implementations of the same intent. tools/list now exposes exactly one of each pair,
chosen by McpMachine: the host_control_* names when host management is enabled, the
main-connection names when it is not.

The advertised tool accepts the union of actions. host_control_window routes close/show
to the main-connection implementation, which stays the only path with close/show
semantics and requires McpManage; the machine path keeps its post-action verification
for restore/hide/maximize/minimize/activate. host_control_service routes
set_auto/set_manual the same way and rejects dry_run for them instead of pretending to
run one. Both old names remain callable aliases, and service_name is accepted as an
alias for the machine tool's name parameter.

The manifest generator treats the two main-connection tools as !machine entries, so the
two-capture union still covers both states. tools/list is 49 entries when everything is
on (was 51) and 47 when host management is off; the response shrinks from 193,008 B to
168,634 B (-12.6%), short of the 15% estimate because state-conditional tools must stay
in the manifest. The plan document records that measurement and the reason.

Verified with a dedicated two-state test: visibility matrix, close/show and
set_auto/set_manual routing through dry_run and validation paths, alias dispatch, and
-32006 for host_* names when host management is off. Step 8a/8b regressions and
verify_tools --live still pass.

Co-Authored-By: deepseek-flash
2026-11-12 17:40:51 +01:00
yuanyuanxianganddeepseek-flash c73db530f4 Feature(mcp): hide the degraded list_* tools when host management is on
host_inspect now covers processes, windows and services, so with
McpMachine=1 the older list_processes / list_windows / list_services
entries only competed with it: same intent, two names, two long
descriptions to read before choosing. They no longer appear in
tools/list while host management is enabled, but their names still
dispatch, so callers that cached them keep working.

They must stay visible when McpMachine=0: that is the default state and
the only way such a server can list processes, windows or services, so
the entries sit behind !IsMachineEnabled() rather than being removed.
list_network_connections is deliberately not folded in: it reads the
connection-manager view (IPv6 rows, killable flag, numeric state) which
host_inspect's IPv4-only network aspect does not provide.

tools.json is now generated from two captures, all-switches-on plus
McpMachine=0, because neither state contains the whole surface; the
off-state entries are marked gate "!machine" and verify_tools.py skips
them when comparing against an all-on server. tools/list went from 54
to 51 entries and from 183,336 B to 171,929 B (-6.2%).

Co-Authored-By: deepseek-flash
2026-11-12 17:28:28 +01:00
yuanyuanxianganddeepseek-flash 59f0f16f74 Feature(mcp): merge the ten host_list_* tools into host_inspect
The ten read-only host-management tools (host_list_processes, windows,
network_state, software, browser_history, favorites, win32_services,
driver_services, scheduled_tasks, host_get_hosts_file) each carried a
name, description and schema for what is one connection to the host,
one tab id per aspect and one paged list shape. Ten entries made
tools/list hard to scan and took a large share of the description
budget.

They are now one tool, host_inspect(aspects[], ...), where aspects is a
required, deduplicated array of the ten former names. A single aspect
returns exactly what the old tool returned (same builder, same code
path), so output is byte-identical; several aspects are fetched over
separate managed sessions and merged into results.<aspect>, with
failures isolated in errors.<aspect> and isError only when every aspect
failed. Filters (pid/name/arch/title/url/publisher/folder/status/
start_type/process/protocol/ports/state/max_bytes) are still applied
server-side before paging and are ignored by aspects they don't apply
to.

The old names stay as dispatch aliases so existing callers keep working
but no longer appear in tools/list; the platform table, batch read-only
list, tool hints, instructions, generator tables and the captured
mcp/tools.json move to the new name (63 tools -> 54).

The description also notes that win32_services / driver_services need
an elevated client: a non-elevated one cannot open SCM and never
answers, so the call times out after ~12 s.

Co-Authored-By: deepseek-flash
2026-11-12 17:21:36 +01:00
yuanyuanxianganddeepseek-flash cac5adaafc Docs(mcp): distinguish client runtime log from business app logs
get_client_log reads the YAMA client's own in-memory ring buffer, but its
description could easily be read as "the logs of whatever program runs on
the host". That misreading sends callers looking for business logs into
the wrong tool and back out empty-handed.

The description now opens by saying this is not the business program's
log, points at read_file with offset=-N for reading files on the host,
and states that this tool is for client/connection troubleshooting.
read_file's description gains the same explicit offset=-N hint at the
tail where log-reading is recommended.

Descriptions only - no behavior change. mcp/tools.json regenerated from
the live capture.

Co-Authored-By: deepseek-flash
2026-11-12 17:02:54 +01:00
yuanyuanxianganddeepseek-flash 88269df548 Feature(mcp): merge the three host-list tools into list_hosts
list_online_hosts, search_hosts and list_all_hosts differed only in
whether offline hosts were included and in which filter fields they
accepted, which made the host-list surface confusing and duplicated
three handlers over the same CollectAllHosts snapshot.

They now share one tool, list_hosts(query?, online?=true,
include_offline?=false, group?, os?, client_type?, limit?, offset?).
The old names stay as aliases routed to the same handler, so existing
callers keep working, but tools/list exposes only list_hosts. The
legacy "offline" boolean of list_all_hosts is still honored, and
list_all_hosts keeps its online+offline default.

With offline history included the list is now ordered online-first:
the host library holds thousands of records, so the default page of
100 would otherwise be all stale entries and the online hosts a caller
can actually operate on would be buried behind paging.

instructions, every id-description string, the platform table, the
tools.json generator and the captured mcp/tools.json are updated to
the new name (65 tools -> 63).

Co-Authored-By: deepseek-flash
2026-11-12 17:01:16 +01:00
yuanyuanxianganddeepseek-flash 613aa7291a Feature(mcp): add http_probe for private-network HTTP checks
Run an HTTP/HTTPS request inside a shell on a managed host and return a
structured result: status code, headers, body (UTF-8 or base64), size and
elapsed time, so interface health on the host or its subnet can be checked
without a full remote-control session.

The safety boundary is hard-coded on the server, not in the shell script:
only http/https and IP literals (or localhost); only loopback and private
ranges (127/8, ::1, 10/8, 172.16/12, 192.168/16) are accepted; redirects
are not followed; the body is capped at 64KB; TLS certificates are
verified. Domain names are refused on purpose - resolving them on the
server would probe the wrong network.

Windows runs a single-line PowerShell 2.0-compatible script based on
HttpWebRequest. Accept/User-Agent/Referer are mapped to their dedicated
properties because .NET rejects them through Headers.Add. Linux uses curl
with temp files.

Payloads cross the terminal channel as 56-character base64 chunks with a
declared byte length. ConPTY re-emits the boundary character of lines
wider than 80 columns, so single-line base64 arrives corrupted; the length
check converts any remaining loss into an explicit error rather than
silent garbage.

The tool reuses an existing persistent terminal session. Sessions it
creates itself are closed after the command and kept only when the probe
timed out while still running. Platform gating: Windows and Linux only.

Co-Authored-By: deepseek-flash
2026-11-12 16:52:17 +01:00