Files
Reims-Go/pkg/pluginsdk/sdk.go
T
Dnyo666 ceeec602be feat(i18n,plugin): implement end-to-end i18n & L10n v2 architecture and language pack protocol
- Build single-source-of-truth 7-domain locale catalog (`locales/{zh-CN,en-US}/*.json`, 1,100+ keys) and `cmd/i18ngen` generator emitting Go catalogs and eager/lazy-split TypeScript domain modules (`core`/`vm` eager; `wizard`/`settings`/`plugins` lazy)
- Add zero-dependency ICU MessageFormat subset (`{var}`, `{n, number}`, CLDR `plural`, `select`), 8-hop cycle-free regional fallback (`zh-HK/zh-MO -> zh-Hant -> zh-TW -> zh-CN`), `auto` OS display-language preference, and `en-XA` pseudo-localization across Go and TypeScript
- Introduce `CodedError` supportability with `[E_CODE]` badges, collapsible `[detail]` diagnostics, and automatic SMC OSK / SMBIOS serial / MAC / token redaction
- Add Host × Guest macOS dual-terminology annotation (`FormatGuestTerm`) across 6 official Apple guest UI locales and localize Win32 system tray, file pickers, and DPI-adaptive `installguide` overlays with CJK font fallback probing
- Upgrade L1–L4 plugin localization to dual-track v2: Track A full language packs (`files`, WOFF2 `fonts`, cross-plugin `pluginOverrides`), Track B plugin-scoped `l10n` bundles (`HasUIMessages` isolation), live `plugin/localeChanged` notifications, `< 2ms` static CLI pack loading, and `reims-go plugin locale init|check` translator toolchain with `zh-TW` and `ja-JP` reference packs
- Harden security, WCAG 2.1 AA token contrast, `< 768px` responsive drawer & form layouts, and RTL logical properties; add backend security/locale regression tests and frontend `node --test` static/runtime guard suite in CI

# Conflicts:
#	frontend/src/i18n.ts
#	internal/cli/cli.go
#	internal/i18n/i18n.go
2026-11-30 14:56:19 +08:00

428 lines
11 KiB
Go

// Package pluginsdk provides a lightweight, zero-dependency Go SDK for writing
// external L3 Sidecar plugins (and guest VM drivers such as Linux) for Reims-Go.
// Communication uses Content-Length framed JSON-RPC 2.0 over stdin/stdout while
// diagnostics/logs write to stderr (docs/plugin-architecture.md §8, §12 Phase 3).
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"`
DataDir string `json:"dataDir"`
Locale string `json:"locale,omitempty"`
FallbackChain []string `json:"fallbackChain,omitempty"`
L10nBundle map[string]string `json:"l10nBundle,omitempty"`
}
// 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
}
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 = ev.L10nBundle
cb := s.onLocaleChanged
s.mu.Unlock()
if cb != nil {
cb(ev)
}
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 len(vars) == 0 || !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
}
end := strings.IndexByte(tpl[i+1:], '\'')
if end >= 0 {
b.WriteString(tpl[i+1 : i+1+end])
i += 1 + end + 1
continue
}
}
if tpl[i] == '{' {
end := strings.IndexByte(tpl[i+1:], '}')
if end > 0 {
token := strings.TrimSpace(tpl[i+1 : i+1+end])
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 += 1 + end + 1
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 the handshake metadata sent by the host.
func (s *Server) InitInfo() InitInfo {
s.mu.Lock()
defer s.mu.Unlock()
return s.initInfo
}
// 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 != "" {
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
}