Files
SimpleRemoter/server/go/mcp/term.go
T
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

196 lines
5.8 KiB
Go

package mcp
import (
"bytes"
"strconv"
"sync"
"time"
)
// termRingCap bounds one session's retained output. A shell that floods the
// session (a log tail, a build) must not grow server memory without bound;
// the oldest bytes are dropped and the loss is surfaced as truncated output
// (design §6.3).
const termRingCap = 256 << 10
// pendingCmd is one command whose output is still being collected. It lives
// on the session so a timed-out terminal_exec can hand the same command back
// to a later polling call: the shell keeps running and its output keeps
// accumulating whether or not an HTTP request is attached.
type pendingCmd struct {
sentinel string // "__MCP_DONE_<6 hex>__"
start uint64 // absolute offset where this command's output begins
scanPos uint64 // absolute offset scanned so far (sentinel may span chunks)
deadline time.Time // when the waiter gives up (the session survives)
done bool
exitCode int
outputEnd uint64 // absolute offset just past the sentinel's exit code
}
// termSession is the server-side view of one shell child. All mutable state
// is guarded by mu; cond wakes a waiter when data arrives, the command ends,
// or the session closes.
type termSession struct {
id string
deviceID string
createdAt time.Time
mu sync.Mutex
cond *sync.Cond
lastUsed time.Time
buf []byte // ring of termRingCap bytes
head int // index the next write goes to
size int // valid bytes in buf
total uint64 // bytes the shell produced, including dropped ones
delivered uint64 // absolute offset already handed to the client
droppedBytes uint64
isPTY bool
ready bool // OnTerminalReady seen
opening bool // hub.OpenTerminalSession still in flight
closed bool
closeReason string
pending *pendingCmd // nil = idle
}
func newTermSession(deviceID string) *termSession {
now := time.Now()
s := &termSession{
id: newSessionID(),
deviceID: deviceID,
createdAt: now,
lastUsed: now,
buf: make([]byte, termRingCap),
}
s.cond = sync.NewCond(&s.mu)
return s
}
// baseLocked is the absolute offset of the oldest retained byte.
func (s *termSession) baseLocked() uint64 { return s.total - uint64(s.size) }
// appendLocked writes p into the ring, dropping the oldest bytes on overflow.
// total counts every byte the shell produced, including dropped ones, so the
// absolute offsets stay monotonic and a client can tell that it lost data.
func (s *termSession) appendLocked(p []byte) {
s.lastUsed = time.Now()
if len(p) == 0 {
return
}
if len(p) > len(s.buf) {
drop := len(p) - len(s.buf)
s.droppedBytes += uint64(drop)
s.total += uint64(drop)
p = p[drop:]
}
if overflow := s.size + len(p) - len(s.buf); overflow > 0 {
// The oldest overflow bytes are simply forgotten: head still marks
// the next write, and size now describes a shorter prefix.
s.droppedBytes += uint64(overflow)
s.size -= overflow
}
if n := copy(s.buf[s.head:], p); n < len(p) {
copy(s.buf, p[n:])
}
s.head = (s.head + len(p)) % len(s.buf)
s.size += len(p)
s.total += uint64(len(p))
}
// readLocked returns up to max bytes starting at absolute offset. lost is
// true when the requested offset predates the ring's oldest byte; the data
// then starts at the oldest retained byte instead.
func (s *termSession) readLocked(offset uint64, max int) (data []byte, next uint64, lost bool) {
if max <= 0 {
return nil, offset, false
}
base := s.baseLocked()
if offset < base {
offset = base
lost = true
}
if offset >= s.total {
return nil, s.total, lost
}
n := int(min(s.total-offset, uint64(max)))
idx := (s.head - s.size + int(offset-base)) % len(s.buf)
if idx < 0 {
idx += len(s.buf)
}
data = make([]byte, n)
first := copy(data, s.buf[idx:min(idx+n, len(s.buf))])
copy(data[first:], s.buf[:n-first])
return data, offset + uint64(n), lost
}
// scanPendingLocked looks for the in-flight command's sentinel in the bytes
// appended since the last look. A tail overlap is retained so a sentinel split
// across two TCP reads is still found.
func (s *termSession) scanPendingLocked() {
p := s.pending
if p == nil || p.done {
return
}
from := max(p.scanPos, s.baseLocked())
if from >= s.total {
return
}
data, next, _ := s.readLocked(from, int(s.total-from))
if code, end, ok := scanSentinel(data, p.sentinel); ok {
p.done = true
p.exitCode = code
p.outputEnd = from + uint64(end)
s.cond.Broadcast()
return
}
// Keep the last few bytes: the next chunk may complete a sentinel whose
// prefix sits just before the boundary.
const overlap = 64
if next > overlap {
next -= overlap
}
if next > p.scanPos {
p.scanPos = next
}
}
// scanSentinel finds the first occurrence of sentinel followed by a decimal
// exit code. The Windows %errorlevel% is signed (0xC000013A prints as
// -1073741510), so a leading '-' is accepted. end is one past the last digit.
//
// Echoed command lines contain the sentinel too but not the exit code
// ("__MCP_DONE_x__$?" / "__MCP_DONE_x__%errorlevel%"), so occurrences without
// digits are skipped rather than reported.
func scanSentinel(data []byte, sentinel string) (code int, end int, ok bool) {
if sentinel == "" {
// Defensive: an empty needle matches everywhere and would spin the
// device read loop. Callers always mint a non-empty sentinel.
return 0, 0, false
}
needle := []byte(sentinel)
from := 0
for {
idx := bytes.Index(data[from:], needle)
if idx < 0 {
return 0, 0, false
}
idx += from
rest := data[idx+len(needle):]
i := 0
if i < len(rest) && rest[i] == '-' {
i++
}
digits := i
for i < len(rest) && rest[i] >= '0' && rest[i] <= '9' {
i++
}
if i > digits {
if n, err := strconv.Atoi(string(rest[:i])); err == nil {
return n, idx + len(needle) + i, true
}
}
from = idx + len(needle)
}
}