Files
reims-agent/internal/sidecar/rpc.go
T
千川白浪andClaude Opus 5.5 d682620fe5 feat(mcp)!: 工具设计范式更新到 0.2.0 (#6)
Serve six computer-use tools on the mcp channel and add the guest,
restore point, clone and test tools on a new mcp-dev channel.

- vm_power replaces vm_start, vm_shutdown, vm_suspend and vm_resume and adds
  force_stop.
- screen replaces the screenshot and zoom actions and wait_for_screen: it can
  wait for a change or a stable frame (up to 180 s while booting) and return
  one region at up to source resolution.
- computer_input replaces computer and computer_batch: it checks every step
  before sending input, holds modifiers around pointer actions, stops on a
  wait_screen timeout, and releases held keys and buttons on success, error
  or cancellation.
- Coordinates follow the last full image returned, so scaled screenshots no
  longer misplace clicks; results report the image size and a short sha256
  as compact JSON and structuredContent.
- Calls on one VM run in order instead of all tools sharing one lock;
  request ids and cancellation are scoped per client connection, and a
  closed connection cancels its calls.
- guest_wait_ready returns the plugin public key; logs_read pages guest and
  test logs; test_wait returns the result once finished; sessions and test
  runs always use a clone. Removed the screen resource.
- Tools carry annotations and one-sentence descriptions, and arguments the
  schema does not name are refused.

Requires a Reims-Go host with region screenshots, held-key input,
host/console.release and forced shutdown.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-04 23:52:45 -07:00

314 lines
7.5 KiB
Go

package sidecar
import (
"bufio"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"strconv"
"strings"
"sync"
"sync/atomic"
)
const maxFrameBytes = 8 << 20
const maxHeaderBytes = 16 << 10
// Channels lists the channels this sidecar serves. "mcp" carries the core
// computer-use tools and "mcp-dev" adds guest, snapshot and test tools.
var Channels = []string{"mcp", "mcp-dev"}
// MCPHandler answers MCP messages. session identifies one client connection;
// SessionClosed is called once that connection has ended.
type MCPHandler interface {
Handle(ctx context.Context, channel, session string, message json.RawMessage) (json.RawMessage, error)
SessionClosed(channel, session string)
}
type HostClient struct{ Server *Server }
func (c HostClient) Call(ctx context.Context, method string, params any, out any) error {
if c.Server == nil {
return errors.New("Reims-Go Host API is unavailable")
}
return c.Server.CallHost(ctx, method, params, out)
}
type envelope struct {
JSONRPC string `json:"jsonrpc"`
ID json.RawMessage `json:"id,omitempty"`
Method string `json:"method,omitempty"`
Params json.RawMessage `json:"params,omitempty"`
Result json.RawMessage `json:"result,omitempty"`
Error *rpcError `json:"error,omitempty"`
}
type rpcError struct {
Code int `json:"code"`
Message string `json:"message"`
}
type hostReply struct {
Message string `json:"message"`
}
type Server struct {
in *bufio.Reader
out io.Writer
mcp MCPHandler
mu sync.Mutex
pending map[string]chan envelope
writeMu sync.Mutex
nextID atomic.Uint64
}
func New(handler MCPHandler) *Server {
return &Server{
in: bufio.NewReaderSize(os.Stdin, 64*1024),
out: os.Stdout,
mcp: handler,
pending: make(map[string]chan envelope),
}
}
func NewWithIO(r io.Reader, w io.Writer, handler MCPHandler) *Server {
return &Server{
in: bufio.NewReaderSize(r, 64*1024),
out: w,
mcp: handler,
pending: make(map[string]chan envelope),
}
}
func (s *Server) Serve(parent context.Context) error {
ctx, cancel := context.WithCancel(parent)
defer cancel()
for {
frame, err := readFrame(s.in)
if err != nil {
if errors.Is(err, io.EOF) {
return nil
}
return err
}
var env envelope
if err := json.Unmarshal(frame, &env); err != nil {
_ = s.writeFrame(envelope{JSONRPC: "2.0", ID: json.RawMessage("null"), Error: &rpcError{Code: -32700, Message: "parse error"}})
continue
}
if env.Method == "plugin/shutdown" {
return nil
}
if env.Method != "" {
go s.dispatch(ctx, env)
continue
}
if len(env.ID) > 0 {
key := strings.TrimSpace(string(env.ID))
s.mu.Lock()
waiter := s.pending[key]
s.mu.Unlock()
if waiter != nil {
select {
case waiter <- env:
default:
}
}
}
}
}
func (s *Server) dispatch(ctx context.Context, env envelope) {
var result any
var err error
channel, event := channelMethod(env.Method)
switch {
case env.Method == "plugin/initialize":
result = map[string]any{
"pluginApi": "1.1.0",
"capabilities": map[string]any{"channels": Channels},
}
case env.Method == "plugin/localeChanged":
return
case event == "message":
var params struct {
Message json.RawMessage `json:"message"`
Session string `json:"session"`
}
if err = json.Unmarshal(env.Params, &params); err == nil && len(params.Message) == 0 {
err = errors.New("channel message is missing")
}
if err == nil {
var message json.RawMessage
message, err = s.mcp.Handle(ctx, channel, params.Session, params.Message)
if err == nil {
if len(message) == 0 {
message = json.RawMessage("null")
}
result = map[string]json.RawMessage{"message": message}
}
}
case event == "closed":
var params struct {
Session string `json:"session"`
}
if err = json.Unmarshal(env.Params, &params); err == nil && params.Session != "" {
s.mcp.SessionClosed(channel, params.Session)
}
default:
err = fmt.Errorf("method not found: %s", env.Method)
}
if len(env.ID) == 0 {
return
}
response := envelope{JSONRPC: "2.0", ID: env.ID}
if err != nil {
response.Error = &rpcError{Code: -32000, Message: err.Error()}
} else if result == nil {
response.Result = json.RawMessage("null")
} else {
response.Result, err = json.Marshal(result)
if err != nil {
response.Result = nil
response.Error = &rpcError{Code: -32603, Message: "internal error"}
}
}
_ = s.writeFrame(response)
}
// channelMethod splits "channel/<id>/<event>" for a channel this sidecar
// serves. It returns empty strings for any other method.
func channelMethod(method string) (string, string) {
rest, ok := strings.CutPrefix(method, "channel/")
if !ok {
return "", ""
}
channel, event, ok := strings.Cut(rest, "/")
if !ok {
return "", ""
}
for _, served := range Channels {
if channel == served {
return channel, event
}
}
return "", ""
}
func (s *Server) CallHost(ctx context.Context, method string, params any, out any) error {
if ctx == nil {
ctx = context.Background()
}
id := strconv.FormatUint(s.nextID.Add(1), 10)
var rawParams json.RawMessage
if params != nil {
encoded, err := json.Marshal(params)
if err != nil {
return err
}
rawParams = encoded
}
waiter := make(chan envelope, 1)
s.mu.Lock()
s.pending[id] = waiter
s.mu.Unlock()
defer func() {
s.mu.Lock()
delete(s.pending, id)
s.mu.Unlock()
}()
if err := s.writeFrame(envelope{
JSONRPC: "2.0",
ID: json.RawMessage(id),
Method: method,
Params: rawParams,
}); err != nil {
return err
}
select {
case response := <-waiter:
if response.Error != nil {
return errors.New(response.Error.Message)
}
if out != nil && len(response.Result) > 0 && string(response.Result) != "null" {
return json.Unmarshal(response.Result, out)
}
return nil
case <-ctx.Done():
return ctx.Err()
}
}
func (s *Server) writeFrame(env envelope) error {
frame, err := json.Marshal(env)
if err != nil {
return err
}
if len(frame) > maxFrameBytes {
return errors.New("Sidecar RPC frame exceeds limit")
}
s.writeMu.Lock()
defer s.writeMu.Unlock()
header := []byte(fmt.Sprintf("Content-Length: %d\r\n\r\n", len(frame)))
if err := writeFull(s.out, header); err != nil {
return err
}
return writeFull(s.out, frame)
}
func readFrame(reader *bufio.Reader) ([]byte, error) {
contentLength := -1
headerBytes := 0
for range 64 {
rawLine, err := reader.ReadSlice('\n')
if errors.Is(err, bufio.ErrBufferFull) || len(rawLine)+headerBytes > maxHeaderBytes {
return nil, errors.New("Sidecar RPC header exceeds limit")
}
if err != nil {
return nil, err
}
headerBytes += len(rawLine)
line := strings.TrimRight(string(rawLine), "\r\n")
if line == "" {
break
}
key, value, ok := strings.Cut(line, ":")
if ok && strings.EqualFold(strings.TrimSpace(key), "Content-Length") {
if contentLength >= 0 {
return nil, errors.New("duplicate Sidecar RPC Content-Length")
}
length, err := strconv.Atoi(strings.TrimSpace(value))
if err != nil || length < 0 || length > maxFrameBytes {
return nil, errors.New("invalid Sidecar RPC Content-Length")
}
contentLength = length
}
}
if contentLength < 0 {
return nil, errors.New("Sidecar RPC frame is missing Content-Length")
}
frame := make([]byte, contentLength)
if _, err := io.ReadFull(reader, frame); err != nil {
return nil, err
}
return frame, nil
}
func writeFull(writer io.Writer, data []byte) error {
for len(data) > 0 {
written, err := writer.Write(data)
if err != nil {
return err
}
if written == 0 {
return io.ErrShortWrite
}
data = data[written:]
}
return nil
}