Files
Reims-Go/pkg/pluginsdk/sdk.go
T

500 lines
13 KiB
Go

// Package pluginsdk provides a zero-dependency Go SDK for external L3 Sidecar
// plugins communicating via Content-Length framed JSON-RPC 2.0 over stdin/stdout
// while writing diagnostics and logs to stderr.
package pluginsdk
import (
"bufio"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"strconv"
"strings"
"sync"
"sync/atomic"
)
// PluginAPIVersion is the protocol version spoken by this SDK.
const PluginAPIVersion = "1.0.0"
// Handler handles one inbound JSON-RPC method from the Reims-Go host.
type Handler func(ctx context.Context, params json.RawMessage) (any, error)
// InitInfo contains initialization data received from the host during handshake.
type InitInfo struct {
PluginID string `json:"pluginId"`
PluginAPI string `json:"pluginApi"`
UIAPI string `json:"uiApi,omitempty"`
BridgeAPI string `json:"bridgeApi,omitempty"`
// Features lists stable host features (e.g. "bridge.vm.list",
// "slot.settings.plugin.panel"); check HasFeature instead of comparing versions.
Features []string `json:"features,omitempty"`
DataDir string `json:"dataDir"`
Locale string `json:"locale,omitempty"`
FallbackChain []string `json:"fallbackChain,omitempty"`
L10nBundle map[string]string `json:"l10nBundle,omitempty"`
}
// HasFeature reports whether the host advertised feature in the handshake.
func (i InitInfo) HasFeature(feature string) bool {
for _, f := range i.Features {
if f == feature {
return true
}
}
return false
}
// LocaleChangedEvent is delivered via the `plugin/localeChanged` notification
// whenever the user changes the Reims-Go interface language at runtime.
type LocaleChangedEvent struct {
Locale string `json:"locale"`
FallbackChain []string `json:"fallbackChain,omitempty"`
L10nBundle map[string]string `json:"l10nBundle,omitempty"`
}
type rpcError struct {
Code int `json:"code"`
Message string `json:"message"`
}
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"`
}
// Server runs inside a Sidecar executable, serving host requests over stdin/stdout
// and issuing reverse Host API calls back to Reims-Go.
type Server struct {
in *bufio.Reader
out io.Writer
mu sync.Mutex
handlers map[string]Handler
pending map[string]chan envelope
writeMu sync.Mutex
nextID atomic.Uint64
initInfo InitInfo
caps map[string]any
onLocaleChanged func(LocaleChangedEvent)
}
// New creates a Sidecar SDK server bound to os.Stdin / os.Stdout.
func New() *Server {
return NewWithIO(os.Stdin, os.Stdout)
}
// NewWithIO creates a Sidecar SDK server over custom streams (useful for tests).
func NewWithIO(r io.Reader, w io.Writer) *Server {
s := &Server{
in: bufio.NewReaderSize(r, 64*1024),
out: w,
handlers: make(map[string]Handler),
pending: make(map[string]chan envelope),
caps: map[string]any{},
}
s.Handle("plugin/initialize", func(_ context.Context, raw json.RawMessage) (any, error) {
var info InitInfo
if err := json.Unmarshal(raw, &info); err != nil {
return nil, err
}
s.mu.Lock()
if info.Locale == "" {
info.Locale = "en-US"
}
s.initInfo = info
caps := s.caps
s.mu.Unlock()
return map[string]any{
"pluginApi": PluginAPIVersion,
"capabilities": caps,
}, nil
})
s.Handle("plugin/localeChanged", func(_ context.Context, raw json.RawMessage) (any, error) {
var ev LocaleChangedEvent
if err := json.Unmarshal(raw, &ev); err != nil {
return nil, nil
}
var bundleCopy map[string]string
if ev.L10nBundle != nil {
bundleCopy = make(map[string]string, len(ev.L10nBundle))
for k, v := range ev.L10nBundle {
bundleCopy[k] = v
}
}
s.mu.Lock()
if ev.Locale != "" {
s.initInfo.Locale = ev.Locale
}
if len(ev.FallbackChain) > 0 {
s.initInfo.FallbackChain = append([]string(nil), ev.FallbackChain...)
}
s.initInfo.L10nBundle = bundleCopy
cb := s.onLocaleChanged
s.mu.Unlock()
if cb != nil {
evCopy := ev
evCopy.FallbackChain = append([]string(nil), ev.FallbackChain...)
if bundleCopy != nil {
evCopy.L10nBundle = make(map[string]string, len(bundleCopy))
for k, v := range bundleCopy {
evCopy.L10nBundle[k] = v
}
}
cb(evCopy)
}
return nil, nil
})
return s
}
// OnLocaleChanged registers an optional callback invoked when the host broadcasts
// `plugin/localeChanged` at runtime.
func (s *Server) OnLocaleChanged(fn func(LocaleChangedEvent)) {
s.mu.Lock()
s.onLocaleChanged = fn
s.mu.Unlock()
}
// Locale returns the active effective BCP-47 locale negotiated with the host.
func (s *Server) Locale() string {
s.mu.Lock()
loc := s.initInfo.Locale
s.mu.Unlock()
if loc == "" {
return "en-US"
}
return loc
}
// FallbackChain returns the active locale fallback chain negotiated with the host.
func (s *Server) FallbackChain() []string {
s.mu.Lock()
defer s.mu.Unlock()
return append([]string(nil), s.initInfo.FallbackChain...)
}
// T formats a plugin-private localization key using the merged L10nBundle pushed
// by Reims-Go (combining the plugin's own `<l10n>/<tag>.json` with any active
// Language Pack `pluginOverrides`), substituting `{var}` placeholders from vars.
func (s *Server) T(key string, vars map[string]any) string {
s.mu.Lock()
tpl := ""
if s.initInfo.L10nBundle != nil {
tpl = s.initInfo.L10nBundle[key]
}
s.mu.Unlock()
if tpl == "" {
tpl = key
}
if !strings.ContainsRune(tpl, '{') && !strings.ContainsRune(tpl, '\'') {
return tpl
}
var b strings.Builder
b.Grow(len(tpl) + 16)
for i := 0; i < len(tpl); {
if tpl[i] == '\'' {
if i+1 < len(tpl) && tpl[i+1] == '\'' {
b.WriteByte('\'')
i += 2
continue
}
// ICU DOUBLE_OPTIONAL: only enter quoted span when ' precedes '{', '}', or '#'.
if i+1 < len(tpl) && (tpl[i+1] == '{' || tpl[i+1] == '}' || tpl[i+1] == '#') {
i++
for i < len(tpl) {
if tpl[i] == '\'' {
if i+1 < len(tpl) && tpl[i+1] == '\'' {
b.WriteByte('\'')
i += 2
continue
}
i++
break
}
b.WriteByte(tpl[i])
i++
}
continue
}
b.WriteByte('\'')
i++
continue
}
if tpl[i] == '{' && len(vars) > 0 {
// Scan matching brace depth so nested ICU plural/select blocks aren't truncated.
depth := 1
j := i + 1
for j < len(tpl) && depth > 0 {
if tpl[j] == '{' {
depth++
} else if tpl[j] == '}' {
depth--
}
j++
}
if depth == 0 {
inner := strings.TrimSpace(tpl[i+1 : j-1])
if inner != "" && !strings.ContainsAny(inner, "{}") {
token := inner
if comma := strings.IndexByte(token, ','); comma > 0 {
token = strings.TrimSpace(token[:comma])
}
if val, ok := vars[token]; ok && val != nil {
b.WriteString(fmt.Sprint(val))
i = j
continue
}
}
}
}
b.WriteByte(tpl[i])
i++
}
return b.String()
}
// SetCapability advertises a capability in the handshake response.
func (s *Server) SetCapability(k string, v any) {
s.mu.Lock()
s.caps[k] = v
s.mu.Unlock()
}
// InitInfo returns a defensive copy of the handshake metadata sent by the host.
func (s *Server) InitInfo() InitInfo {
s.mu.Lock()
defer s.mu.Unlock()
cp := s.initInfo
if len(s.initInfo.FallbackChain) > 0 {
cp.FallbackChain = append([]string(nil), s.initInfo.FallbackChain...)
}
if s.initInfo.L10nBundle != nil {
cp.L10nBundle = make(map[string]string, len(s.initInfo.L10nBundle))
for k, v := range s.initInfo.L10nBundle {
cp.L10nBundle[k] = v
}
}
return cp
}
// Handle registers a JSON-RPC method handler (e.g. "hook/vm.beforeStart",
// "command/invoke", "diagnostics/collect", "driver/list", ...).
func (s *Server) Handle(method string, h Handler) {
s.mu.Lock()
s.handlers[method] = h
s.mu.Unlock()
}
// CallHost invokes a reverse Host API method on Reims-Go (e.g. "host/notify",
// "host/vm.spawn", "host/vm.stop", "host/audit").
func (s *Server) CallHost(ctx context.Context, method string, params any, out any) error {
idStr := strconv.FormatUint(s.nextID.Add(1), 10)
var rawParams json.RawMessage
if params != nil {
b, err := json.Marshal(params)
if err != nil {
return err
}
rawParams = b
}
ch := make(chan envelope, 1)
s.mu.Lock()
s.pending[idStr] = ch
s.mu.Unlock()
defer func() {
s.mu.Lock()
delete(s.pending, idStr)
s.mu.Unlock()
}()
if err := s.writeFrame(envelope{
JSONRPC: "2.0",
ID: json.RawMessage(idStr),
Method: method,
Params: rawParams,
}); err != nil {
return err
}
select {
case resp := <-ch:
if resp.Error != nil {
return errors.New(resp.Error.Message)
}
if out != nil && len(resp.Result) > 0 && string(resp.Result) != "null" {
return json.Unmarshal(resp.Result, out)
}
return nil
case <-ctx.Done():
return ctx.Err()
}
}
// SpawnVMProcess requests Reims-Go to spawn a VM process outside the Sidecar's Job Object.
func (s *Server) SpawnVMProcess(ctx context.Context, vmName, exePath string, args []string, workDir string, env []string) (int, error) {
var resp struct {
PID int `json:"pid"`
}
err := s.CallHost(ctx, "host/vm.spawn", map[string]any{
"vm_name": vmName,
"exe_path": exePath,
"args": args,
"work_dir": workDir,
"env": env,
}, &resp)
return resp.PID, err
}
// StopVMProcess requests Reims-Go to terminate a host-managed VM process.
func (s *Server) StopVMProcess(ctx context.Context, pid int) error {
return s.CallHost(ctx, "host/vm.stop", map[string]any{"pid": pid}, nil)
}
// IsVMProcessRunning queries whether a host-managed VM process is still alive.
func (s *Server) IsVMProcessRunning(ctx context.Context, pid int) (bool, error) {
var resp struct {
Running bool `json:"running"`
}
err := s.CallHost(ctx, "host/vm.isRunning", map[string]any{"pid": pid}, &resp)
return resp.Running, err
}
// Notify requests a host UI notification (requires ui:notify permission).
func (s *Server) Notify(ctx context.Context, title, body string) error {
return s.CallHost(ctx, "host/notify", map[string]any{"title": title, "body": body}, nil)
}
// Serve runs the JSON-RPC frame loop until EOF or `plugin/shutdown`.
func (s *Server) Serve(ctx context.Context) error {
for {
if ctx.Err() != nil {
return ctx.Err()
}
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 {
continue
}
if env.Method == "plugin/shutdown" {
return nil
}
if env.Method == "plugin/localeChanged" {
// Apply locale changes in arrival order to avoid stale overwrites.
s.dispatch(ctx, env)
continue
}
if env.Method != "" {
go s.dispatch(ctx, env)
continue
}
if len(env.ID) > 0 {
key := strings.TrimSpace(string(env.ID))
s.mu.Lock()
ch := s.pending[key]
s.mu.Unlock()
if ch != nil {
select {
case ch <- env:
default:
}
}
}
}
}
func (s *Server) dispatch(ctx context.Context, env envelope) {
s.mu.Lock()
h := s.handlers[env.Method]
s.mu.Unlock()
if h == nil {
if len(env.ID) > 0 {
_ = s.writeFrame(envelope{
JSONRPC: "2.0",
ID: env.ID,
Error: &rpcError{Code: -32601, Message: "method not found: " + env.Method},
})
}
return
}
res, err := h(ctx, env.Params)
if len(env.ID) == 0 {
return
}
if err != nil {
_ = s.writeFrame(envelope{
JSONRPC: "2.0",
ID: env.ID,
Error: &rpcError{Code: -32000, Message: err.Error()},
})
return
}
var rawRes json.RawMessage
if res == nil {
rawRes = json.RawMessage("null")
} else {
rawRes, _ = json.Marshal(res)
}
_ = s.writeFrame(envelope{
JSONRPC: "2.0",
ID: env.ID,
Result: rawRes,
})
}
func (s *Server) writeFrame(env envelope) error {
b, err := json.Marshal(env)
if err != nil {
return err
}
s.writeMu.Lock()
defer s.writeMu.Unlock()
if _, err := fmt.Fprintf(s.out, "Content-Length: %d\r\n\r\n", len(b)); err != nil {
return err
}
_, err = s.out.Write(b)
return err
}
func readFrame(r *bufio.Reader) ([]byte, error) {
contentLen := -1
for {
line, err := r.ReadString('\n')
if err != nil {
return nil, err
}
line = strings.TrimRight(line, "\r\n")
if line == "" {
break
}
k, v, ok := strings.Cut(line, ":")
if ok && strings.EqualFold(strings.TrimSpace(k), "Content-Length") {
n, err := strconv.Atoi(strings.TrimSpace(v))
if err != nil || n < 0 {
return nil, fmt.Errorf("invalid Content-Length %q", v)
}
contentLen = n
}
}
if contentLen < 0 {
return nil, errors.New("missing Content-Length")
}
buf := make([]byte, contentLen)
if _, err := io.ReadFull(r, buf); err != nil {
return nil, err
}
return buf, nil
}