Files
Reims-Go/internal/plugin/sidecar.go
T
千川白浪 d55241cba2 feat(plugin): catalog the Host API, open secret typing and extend the SDK
Give the Sidecar Host API one authoritative catalog in pkg/pluginproto: every
host/* method's status, required permissions, handshake feature and request and
result shapes. The host, pkg/pluginsdk and plugins share those types, so a field
can no longer exist on one side only, and permissions come from the catalog
instead of from each handler. Tests gate that every served method is
catalogued, every stable catalogued method is served, and every catalogued
permission is one the host recognizes.

Open the interface up instead of adding consent gates. Typing a secret setting
is no longer reserved for reims.agent: any plugin that holds qmp:write and that
the user authorized for the VM can have the host type the plugin's own setting,
which the plugin never reads back. Restoring a snapshot works on any authorized
VM, a plugin names its own clones, a held key may carry modifiers, and a
screenshot width outside the supported range is brought into range rather than
refused. Deleting a VM stays limited to the temporary VMs a plugin created.

Record the keys and pointer buttons each plugin holds per VM and lift them when
the plugin's process exits, its scope is disposed, the VM stops or it stops
calling, so a guest never stays stuck with a modifier down. Requests from
plugins that declare pluginApi 1.3 or newer are decoded strictly and answer an
undefined field with JSON-RPC -32602, while older plugins keep tolerant
decoding.

Add typed VM and console methods to pkg/pluginsdk so a plugin no longer needs
its own JSON-RPC client. A method the contract does not catalog, or one the
host did not advertise in the handshake, is refused before it is sent, and the
host's JSON-RPC error code reaches the caller.
2026-12-05 01:43:28 -07:00

634 lines
17 KiB
Go

package plugin
import (
"bufio"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"maps"
"os"
"os/exec"
"slices"
"sync"
"sync/atomic"
"time"
"github.com/Nwflower/reims-go/pkg/pluginproto"
)
// SidecarOptions configures an L3 (or future L2) supervised child process (§8).
type SidecarOptions struct {
PluginID string
ExePath string
Args []string
DataDir string
Broker *Broker
Registry *Registry
IdleTimeout time.Duration // 0 = no idle shutdown
MemLimitBytes uintptr // optional Windows Job Object memory cap (L2)
MaxRestarts int // circuit breaker threshold (default 3)
ExtraHandlers map[string]RPCRequestHandler
LocaleProvider func() (string, []string, map[string]string) // returns (locale, fallbackChain, mergedBundle)
// OnExit runs whenever a Sidecar process goes away, whether it crashed or
// was stopped, so the embedder can undo state only that process could undo.
OnExit func()
}
type sidecarInstance struct {
cmd *exec.Cmd
job *sidecarJob
rpc *RPCConn
stdin io.WriteCloser
exited chan struct{}
inFlight atomic.Int32
}
// SidecarSupervisor manages the lifecycle of one per-plugin Sidecar process:
// lazy start, Windows Job Object containment, Content-Length JSON-RPC 2.0
// handshake, stderr log collection, exponential backoff restart + circuit
// breaker, graceful reload, and idle reclamation (§8).
type SidecarSupervisor struct {
opts SidecarOptions
startMu sync.Mutex
mu sync.Mutex
cur *sidecarInstance
stopped bool
crashCount int
lastCrash time.Time
lastActivity time.Time
idleCancel context.CancelFunc
capabilities map[string]any
}
func NewSidecarSupervisor(opts SidecarOptions) *SidecarSupervisor {
if opts.MaxRestarts <= 0 {
opts.MaxRestarts = 3
}
return &SidecarSupervisor{
opts: opts,
lastActivity: time.Now(),
}
}
// EnsureStarted lazily launches the Sidecar process and performs the
// `plugin/initialize` handshake (§8).
func (s *SidecarSupervisor) EnsureStarted(ctx context.Context) error {
s.startMu.Lock()
defer s.startMu.Unlock()
s.mu.Lock()
if s.stopped {
s.mu.Unlock()
return errors.New("sidecar supervisor stopped")
}
if s.cur != nil {
select {
case <-s.cur.exited:
s.cur = nil
default:
s.lastActivity = time.Now()
s.mu.Unlock()
return nil
}
}
if s.crashCount >= s.opts.MaxRestarts {
s.mu.Unlock()
return fmt.Errorf("sidecar %s circuit-broken after %d crashes", s.opts.PluginID, s.crashCount)
}
// Exponential backoff after prior crash.
backoff := time.Duration(0)
if s.crashCount > 0 {
backoff = time.Duration(200*(1<<(s.crashCount-1))) * time.Millisecond
if elapsed := time.Since(s.lastCrash); elapsed < backoff {
backoff -= elapsed
} else {
backoff = 0
}
}
s.mu.Unlock()
if backoff > 0 {
select {
case <-time.After(backoff):
case <-ctx.Done():
return ctx.Err()
}
}
inst, caps, err := s.spawnInstance(ctx)
if err != nil {
// Count start/handshake failures toward circuit breaker so broken sidecars
// don't spin infinitely on every hook call.
s.mu.Lock()
if !s.stopped {
s.crashCount++
s.lastCrash = time.Now()
crashes := s.crashCount
s.mu.Unlock()
if crashes >= s.opts.MaxRestarts && s.opts.Registry != nil {
s.opts.Registry.MarkFailed(s.opts.PluginID, fmt.Sprintf("sidecar failed to start %d times: %v", crashes, err))
}
} else {
s.mu.Unlock()
}
return err
}
s.mu.Lock()
if s.stopped {
s.mu.Unlock()
s.terminateInstance(inst)
return errors.New("sidecar stopped during startup")
}
s.cur = inst
s.capabilities = caps
s.lastActivity = time.Now()
if s.opts.IdleTimeout > 0 && s.idleCancel == nil {
idleCtx, cancel := context.WithCancel(context.Background())
s.idleCancel = cancel
go s.idleWatchLoop(idleCtx)
}
s.mu.Unlock()
return nil
}
func (s *SidecarSupervisor) spawnInstance(ctx context.Context) (*sidecarInstance, map[string]any, error) {
if s.opts.DataDir != "" {
if err := os.MkdirAll(s.opts.DataDir, 0o755); err != nil {
return nil, nil, err
}
}
cmd := exec.Command(s.opts.ExePath, s.opts.Args...)
cmd.Dir = s.opts.DataDir
configureSidecarCmd(cmd)
stdin, err := cmd.StdinPipe()
if err != nil {
return nil, nil, err
}
stdout, err := cmd.StdoutPipe()
if err != nil {
_ = stdin.Close()
return nil, nil, err
}
stderr, err := cmd.StderrPipe()
if err != nil {
_ = stdin.Close()
_ = stdout.Close()
return nil, nil, err
}
job, err := newSidecarJob(s.opts.MemLimitBytes)
if err != nil {
_ = stdin.Close()
_ = stdout.Close()
_ = stderr.Close()
return nil, nil, err
}
if err := cmd.Start(); err != nil {
_ = stdin.Close()
_ = stdout.Close()
_ = stderr.Close()
job.Close()
return nil, nil, fmt.Errorf("start sidecar %s: %w", s.opts.PluginID, err)
}
if err := job.Assign(cmd.Process.Pid); err != nil {
_ = cmd.Process.Kill()
_ = cmd.Wait()
job.Close()
return nil, nil, fmt.Errorf("assign sidecar %s to job: %w", s.opts.PluginID, err)
}
rpcConn := NewRPCConn(stdout, stdin)
s.registerReverseHostAPI(rpcConn)
inst := &sidecarInstance{
cmd: cmd,
job: job,
rpc: rpcConn,
stdin: stdin,
exited: make(chan struct{}),
}
// Collect stderr into rotated plugin audit log using bufio.Reader so lines
// >64 KiB are truncated and drained instead of wedging the pipe.
stderrDone := make(chan struct{})
go func() {
defer close(stderrDone)
const maxLineBytes = 8 * 1024
br := bufio.NewReaderSize(stderr, 16*1024)
var buf []byte
truncated := false
for {
chunk, isPrefix, err := br.ReadLine()
if len(chunk) > 0 {
if len(buf) < maxLineBytes {
remain := maxLineBytes - len(buf)
if len(chunk) > remain {
buf = append(buf, chunk[:remain]...)
truncated = true
} else {
buf = append(buf, chunk...)
}
} else {
truncated = true
}
}
if !isPrefix && (len(buf) > 0 || err != nil) {
if len(buf) > 0 && s.opts.Broker != nil {
line := string(buf)
if truncated {
line += "…(truncated)"
}
s.opts.Broker.Audit(s.opts.PluginID, "STDERR", line)
}
buf = buf[:0]
truncated = false
}
if err != nil {
return
}
}
}()
// StdoutPipe and StderrPipe must be drained before Wait closes their handles.
go func() {
<-rpcConn.doneCh
<-stderrDone
err := cmd.Wait()
rpcConn.Close()
job.Close()
close(inst.exited)
s.onInstanceExit(inst, err)
}()
// Handshake: plugin/initialize exchanging pluginApi version & capabilities.
initCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
var initResp struct {
PluginAPI string `json:"pluginApi"`
Capabilities map[string]any `json:"capabilities"`
}
initParams := map[string]any{
"pluginId": s.opts.PluginID,
"pluginApi": PluginAPIVersion,
"uiApi": UIAPIVersion,
"bridgeApi": BridgeAPIVersion,
"features": HostFeatures(),
"dataDir": s.opts.DataDir,
}
if s.opts.LocaleProvider != nil {
loc, chain, bundle := s.opts.LocaleProvider()
if loc != "" {
initParams["locale"] = loc
}
if len(chain) > 0 {
initParams["fallbackChain"] = chain
}
if len(bundle) > 0 {
initParams["l10nBundle"] = bundle
}
}
err = rpcConn.Call(initCtx, "plugin/initialize", initParams, &initResp)
if err != nil {
s.terminateInstance(inst)
return nil, nil, fmt.Errorf("sidecar %s handshake failed: %w", s.opts.PluginID, err)
}
return inst, initResp.Capabilities, nil
}
// ReverseHostAPIMethods lists the host/* methods the supervisor serves itself,
// as opposed to the ones the embedder adds through ExtraHandlers. It is derived
// from the registration table, so the list cannot drift from what is served.
func ReverseHostAPIMethods() []string {
return slices.Sorted(maps.Keys((&SidecarSupervisor{}).reverseHostAPIHandlers()))
}
// reverseHostAPIHandlers builds the methods this supervisor serves itself.
func (s *SidecarSupervisor) reverseHostAPIHandlers() map[string]func(context.Context, json.RawMessage) (any, error) {
pid := s.opts.PluginID
broker := s.opts.Broker
return map[string]func(context.Context, json.RawMessage) (any, error){
"host/notify": func(_ context.Context, raw json.RawMessage) (any, error) {
if broker == nil {
return nil, errors.New("broker unavailable")
}
req, err := pluginproto.DecodeParams[pluginproto.NotifyParams]("host/notify", raw, false)
if err != nil {
return nil, err
}
return pluginproto.OKResult{OK: true}, broker.Notify(pid, req.Title, req.Body)
},
"host/audit": func(_ context.Context, raw json.RawMessage) (any, error) {
req, err := pluginproto.DecodeParams[pluginproto.AuditParams]("host/audit", raw, false)
if err != nil {
return nil, err
}
if broker != nil {
if !broker.allowRate(pid) {
return nil, fmt.Errorf("plugin %q exceeded audit rate limit", pid)
}
broker.Audit(pid, "PLUGIN", req.Message)
}
return pluginproto.OKResult{OK: true}, nil
},
"host/vm.spawn": func(ctx context.Context, raw json.RawMessage) (any, error) {
if broker == nil {
return nil, errors.New("broker unavailable")
}
req, err := pluginproto.DecodeParams[pluginproto.SpawnParams]("host/vm.spawn", raw, false)
if err != nil {
return nil, err
}
ref := VMRef{Name: req.VMName}
if req.Ref != nil {
ref = *req.Ref
if ref.Name == "" {
ref.Name = req.VMName
}
}
vmPID, err := broker.SpawnManagedVMProcessWithRef(ctx, pid, ref, req.ExePath, req.Args, req.WorkDir, req.Env)
if err != nil {
return nil, err
}
return pluginproto.SpawnResult{PID: vmPID}, nil
},
"host/vm.stop": func(_ context.Context, raw json.RawMessage) (any, error) {
if broker == nil {
return nil, errors.New("broker unavailable")
}
req, err := pluginproto.DecodeParams[pluginproto.ProcessParams]("host/vm.stop", raw, false)
if err != nil {
return nil, err
}
if req.Ref != nil {
return pluginproto.OKResult{OK: true}, broker.StopManagedVMProcessByRef(pid, *req.Ref)
}
return pluginproto.OKResult{OK: true}, broker.StopManagedVMProcess(pid, req.PID)
},
"host/vm.isRunning": func(_ context.Context, raw json.RawMessage) (any, error) {
if broker == nil {
return pluginproto.IsRunningResult{Running: false}, nil
}
req, err := pluginproto.DecodeParams[pluginproto.ProcessParams]("host/vm.isRunning", raw, false)
if err != nil {
return nil, err
}
if req.Ref != nil {
return pluginproto.IsRunningResult{Running: broker.IsManagedVMRunningForPlugin(pid, *req.Ref)}, nil
}
return pluginproto.IsRunningResult{Running: broker.IsManagedProcessRunningForPlugin(pid, req.PID)}, nil
},
"host/vm.reportState": func(_ context.Context, raw json.RawMessage) (any, error) {
if broker == nil {
return nil, errors.New("broker unavailable")
}
rep, err := pluginproto.DecodeParams[pluginproto.ReportedVMState]("host/vm.reportState", raw, false)
if err != nil {
return nil, err
}
if err := broker.ReportVMState(pid, rep); err != nil {
return nil, err
}
return pluginproto.OKResult{OK: true}, nil
},
}
}
func (s *SidecarSupervisor) registerReverseHostAPI(conn *RPCConn) {
pid := s.opts.PluginID
broker := s.opts.Broker
// Every method authorizes from the contract catalog, so a permission can
// never drift from the method it guards. The broker repeats the check for
// the calls it owns.
handlers := s.reverseHostAPIHandlers()
for _, method := range ReverseHostAPIMethods() {
run := handlers[method]
conn.Handle(method, func(ctx context.Context, raw json.RawMessage) (any, error) {
spec, ok := pluginproto.Lookup(method)
if !ok {
return nil, &RPCError{Code: RPCMethodNotFound, Message: "method not found: " + method}
}
if broker != nil {
for _, perm := range spec.Permissions {
if perm == pluginproto.OriginPermission {
continue
}
if err := broker.Authorize(pid, perm); err != nil {
return nil, err
}
}
}
return run(ctx, raw)
})
}
for method, h := range s.opts.ExtraHandlers {
conn.Handle(method, h)
}
}
func (s *SidecarSupervisor) onInstanceExit(inst *sidecarInstance, exitErr error) {
s.mu.Lock()
isCurrent := s.cur == inst
stopped := s.stopped
if isCurrent {
s.cur = nil
}
s.mu.Unlock()
// The process that held input is gone only when the instance that exited
// was the live one. A zero-downtime reload retires the previous instance
// after the replacement is already serving, so releasing there would lift
// keys the replacement just pressed.
if (isCurrent || stopped) && s.opts.OnExit != nil {
s.opts.OnExit()
}
s.mu.Lock()
if !stopped && isCurrent {
s.crashCount++
s.lastCrash = time.Now()
crashes := s.crashCount
s.mu.Unlock()
if s.opts.Broker != nil {
s.opts.Broker.Audit(s.opts.PluginID, "CRASH", fmt.Sprintf("sidecar exited unexpectedly (count=%d): %v", crashes, exitErr))
}
if crashes >= s.opts.MaxRestarts && s.opts.Registry != nil {
s.opts.Registry.MarkFailed(s.opts.PluginID, fmt.Sprintf("sidecar crashed %d times: %v", crashes, exitErr))
}
return
}
s.mu.Unlock()
}
// Call lazily starts the Sidecar if needed and invokes a JSON-RPC 2.0 method.
func (s *SidecarSupervisor) Call(ctx context.Context, method string, params any, out any) error {
if err := s.EnsureStarted(ctx); err != nil {
return err
}
s.mu.Lock()
inst := s.cur
s.lastActivity = time.Now()
s.mu.Unlock()
if inst == nil {
return errors.New("sidecar not running")
}
inst.inFlight.Add(1)
defer inst.inFlight.Add(-1)
return inst.rpc.Call(ctx, method, params, out)
}
// Reload performs zero-downtime replacement: spawns new Sidecar, swaps pointer,
// drains in-flight requests on old Sidecar, then terminates old Job Object (§8).
func (s *SidecarSupervisor) Reload(ctx context.Context) error {
s.startMu.Lock()
defer s.startMu.Unlock()
s.mu.Lock()
if s.stopped {
s.mu.Unlock()
return errors.New("sidecar supervisor stopped")
}
s.mu.Unlock()
newInst, caps, err := s.spawnInstance(ctx)
if err != nil {
return err
}
s.mu.Lock()
if s.stopped {
s.mu.Unlock()
s.terminateInstance(newInst)
return errors.New("sidecar stopped during reload")
}
old := s.cur
s.cur = newInst
s.capabilities = caps
s.crashCount = 0
s.lastActivity = time.Now()
if s.opts.IdleTimeout > 0 && s.idleCancel == nil {
idleCtx, cancel := context.WithCancel(context.Background())
s.idleCancel = cancel
go s.idleWatchLoop(idleCtx)
}
s.mu.Unlock()
if old != nil {
go func() {
deadline := time.Now().Add(5 * time.Second)
for old.inFlight.Load() > 0 && time.Now().Before(deadline) {
time.Sleep(25 * time.Millisecond)
}
s.terminateInstance(old)
}()
}
return nil
}
// IsRunning reports whether a Sidecar child process is currently alive.
func (s *SidecarSupervisor) IsRunning() bool {
s.mu.Lock()
inst := s.cur
s.mu.Unlock()
if inst == nil {
return false
}
select {
case <-inst.exited:
return false
default:
return true
}
}
// PID returns the current Sidecar child process ID (0 if not running).
func (s *SidecarSupervisor) PID() int {
s.mu.Lock()
inst := s.cur
s.mu.Unlock()
if inst == nil || inst.cmd == nil || inst.cmd.Process == nil {
return 0
}
return inst.cmd.Process.Pid
}
func (s *SidecarSupervisor) idleWatchLoop(ctx context.Context) {
ticker := time.NewTicker(time.Second)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
s.mu.Lock()
inst := s.cur
idle := time.Since(s.lastActivity)
timeout := s.opts.IdleTimeout
if inst != nil && timeout > 0 && idle >= timeout && inst.inFlight.Load() == 0 {
s.cur = nil
s.mu.Unlock()
s.terminateInstance(inst)
} else {
s.mu.Unlock()
}
}
}
}
func (s *SidecarSupervisor) terminateInstance(inst *sidecarInstance) {
if inst == nil {
return
}
_ = inst.rpc.Notify(context.Background(), "plugin/shutdown", nil)
_ = inst.stdin.Close()
select {
case <-inst.exited:
case <-time.After(800 * time.Millisecond):
inst.job.Close()
select {
case <-inst.exited:
case <-time.After(1 * time.Second):
}
}
inst.job.Close()
inst.rpc.Close()
}
// NotifyIfRunning sends a fire-and-forget JSON-RPC notification only when the
// Sidecar process is currently alive (never waking an idle Sidecar).
func (s *SidecarSupervisor) NotifyIfRunning(method string, params any) {
s.mu.Lock()
inst := s.cur
s.mu.Unlock()
if inst == nil {
return
}
select {
case <-inst.exited:
return
default:
}
ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond)
defer cancel()
_ = inst.rpc.Notify(ctx, method, params)
}
// Stop terminates the Sidecar and its entire Job Object process tree cleanly.
func (s *SidecarSupervisor) Stop() {
s.mu.Lock()
s.stopped = true
inst := s.cur
s.cur = nil
cancel := s.idleCancel
s.idleCancel = nil
s.mu.Unlock()
if cancel != nil {
cancel()
}
s.terminateInstance(inst)
}