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
This commit is contained in:
yuanyuanxianganddeepseek-flash committed 2026-11-12 21:53:54 +01:00
1 parent 599c891c00
commit 808747f9d2
10 files changed
+633 -52

No files matched your search

+48 -4
View File
@@ -10,6 +10,7 @@ import (
"net/http"
"runtime/debug"
"strings"
"sync"
"time"
"github.com/yuanyuanxiang/SimpleRemoter/server/go/devicehistory"
@@ -29,6 +30,10 @@ const (
defaultTermIdle = 180 * time.Second
defaultMaxConcurrency = 16
defaultReadMax = 2 << 20
// termSweepInterval is how often the reaper looks for sessions a model
// forgot to close. The sweep itself is cheap: one mutex per session.
termSweepInterval = 30 * time.Second
)
// Config is filled by cmd/main.go from the YAMA_MCP_* environment variables;
@@ -71,6 +76,13 @@ type Server struct {
locks *deviceLocks
sem chan struct{}
sessions *sessionTable
// stop ends the idle reaper and reaperDone reports that it returned;
// closeOnce makes Close idempotent (tests call it both explicitly and from
// Cleanup). reaperDone is nil when no reaper was started (hub-less server).
stop chan struct{}
reaperDone chan struct{}
closeOnce sync.Once
}
// New builds the endpoint. Zero-valued knobs fall back to the documented
@@ -102,6 +114,7 @@ func New(cfg Config) *Server {
handlers: make(map[string]toolFunc),
locks: newDeviceLocks(),
sem: make(chan struct{}, cfg.MaxConcurrency),
stop: make(chan struct{}),
}
if cfg.Hub != nil {
s.sessions = newSessionTable(cfg.Hub)
@@ -110,6 +123,12 @@ func New(cfg Config) *Server {
}
s.registerLocalTools()
s.registerTerminalTools()
if cfg.Hub != nil {
// No hub means no shell can ever be opened, so there is nothing to
// reap; skipping the goroutine keeps hub-less servers inert.
s.reaperDone = make(chan struct{})
go s.sweepLoop()
}
return s
}
@@ -118,9 +137,34 @@ func New(cfg Config) *Server {
// unknown path.
func (s *Server) Enabled() bool { return s != nil && s.cfg.Token != "" }
// Close releases resources held by long-lived tool state: every terminal
// session MCP owns is torn down and the shell told to exit.
func (s *Server) Close() { s.sessions.closeAll() }
// Close releases resources held by long-lived tool state: the reaper stops and
// every terminal session MCP owns is torn down and the shell told to exit.
func (s *Server) Close() {
s.closeOnce.Do(func() {
close(s.stop)
if s.reaperDone != nil {
<-s.reaperDone
}
s.sessions.closeAll()
})
}
// sweepLoop reclaims terminal sessions nobody closed. The interval shrinks to
// TermIdle when that is shorter, so a test (or a deliberately tiny idle knob)
// sees the sweep fire on schedule instead of up to 30 s late.
func (s *Server) sweepLoop() {
defer close(s.reaperDone)
ticker := time.NewTicker(min(termSweepInterval, s.cfg.TermIdle))
defer ticker.Stop()
for {
select {
case <-s.stop:
return
case now := <-ticker.C:
s.sessions.sweepIdle(now, s.cfg.TermIdle)
}
}
}
// Handle serves POST /mcp. Transport-level failures (405/401/413) are answered
// here; everything after a successfully parsed JSON-RPC request returns HTTP
@@ -303,7 +347,7 @@ func (s *Server) callTool(ctx context.Context, raw json.RawMessage) (result any,
s.cfg.MaxConcurrency)
}
if deviceID != "" {
if deviceID != "" && !unlockedTools[params.Name] {
held, acquired := s.locks.tryAcquire(deviceID, params.Name)
if !acquired {
return nil, errf(CodeBusy, "%s", busyMessage(held))