Files
Reims-Go/pkg/pluginsdk/sdk.go
T
球球 7fd1947bef feat(plugin,host,macos,ui): 实现 Agent 受控接管、受保护阶段确认、离线预配置与自动装机基础 (#103, #105, #129) (#134)
* feat(plugin,host,ui): add agent session takeover, protected-phase confirmation, and autoinstall host foundation

* feat(macos,ui,cli): add offline REIMSPROV first-boot provisioning to skip Setup Assistant (#129)

Builds a per-VM read-only REIMSPROV disk image containing a pure-Go XAR Distribution flat package (provision.pkg) and an offline Recovery fallback script (provision-offline.sh). Passwords are hashed in memory to Apple SALTED-SHA512-PBKDF2 bplist00 ShadowHashData (never persisted in plaintext, no auto-login or NOPASSWD sudo). Uses native OpenDirectory.framework (JXA NSData) + dseditgroup under SIP-enabled live bootinstalld and dslocal plist + PlistBuddy under offline Recovery, skips Setup Assistant and Keyboard Setup Assistant, pre-stages Guest Tools, integrates with CreateWizard / VMPage / vm provision CLI / StartAutoInstall, and zero-wipes on finish_install, normal cold start, or DeleteVM.

* feat(autoinstall,host,ui): add input-locked session shield, recovery-only mode, and restart grace cap

Adds the real-machine end-to-end verified baseline for automatic macOS installation: (1) takeover_policy 'lock' with transparent Win32 VM client-area input shield, low-level key/mouse lock preserving host escape shortcuts (Alt+Tab/Alt+Esc/Win), HUD & UI Pause/Resume controls, and write guards while paused; (2) decoupled recovery_only vs full (REIMSPROV) modes in StartAutoInstall, CreateWizard, and VMAutoInstallPanel; (3) graceful_timeout_sec cap (default 10s) on automated built-in macOS host/vm.restart so Setup Assistant/Login Window restarts do not stall 90s on ACPI; (4) additional modifier aliases in console manager and agent-session/telemetry cleanup on VM deletion.

* feat(autoinstall,overlay,plugin): add built-in macOS auto-install plugin, dynamic island overlay, and review fixes

* fix(app,host,macos,ui): address PR #134 automated review findings

- Frontend & i18n:
  - Fix UTF-8/GBK mojibake in VMPage.tsx.
  - Emit reims:confirm-resolved on timeout/cancel/resolve so frontend modals auto-close and surface errors cleanly; stop submitCreate from continuing after PrepareVMProvision failure.
  - Gate AutoInstallPanel RapidOCR download button on preflight can_download_ocr when pinned default assets are unavailable.
- App / Sessions / Confirm / Lifecycle:
  - Add 30s denial cooldown for protected-phase confirmation prompts and revoke (pluginID, vmKey) grants on non-completed session exits.
  - Fix sessionOverlay / activeAgentSessions data race, remove duplicate permission-denied invocation, guard against clobbering other sessions or completed overlays, and unify VM key normalization.
  - Grant protected-phase confirmation and attach lock-mode session + watcher when resuming auto-install without an active session.
  - Unify FinishInstall and host/vm.finishInstall result handling and persist .reims-go-provision-ready across restarts.
  - Preserve non-timeout stop errors in restartMacOSVMLocked instead of force-killing.
- Host Takeover Hooks:
  - Require both keyboard and mouse WH_*_LL hooks (rolling back partial installs), initialize thread message queue before ready, reset started state on error/exit for retry, and report hook failures.
- macOS Provisioning & Autoinstall Engine:
  - Track REIMSPROV staged/wipe-pending/ready lifecycle markers, exclude "restore" recovery marker from re-attaching REIMSPROV, fail explicitly on offline admin plist creation failure, and report wipe failures.
  - Serialize per-VM Start/Stop/Resume with stop generation tokens, guard ROI fast-path against maxDim overflow, switch hostclient early-event buffer to FIFO eviction, fix untyped nil Engine return, tighten negation & high-risk fuzzy matching, preserve ackedQemuErrors across RebootWindow resets, and re-orient/expire stale inherited running checkpoints.
  - Document verified Windows SDK IDL vtable slots for WinOCR (live-tested on Windows) and add regression tests across app, host, macosdriver, startprep, installer, and autoinstall packages.

* fix(app,cli,host,macos,ui): address PR #134 second automated review findings

- CLI & Desktop Control Channel:
  - Add __reims_host__ / autoinstall desktop control channel with data_root verification so CLI status, resume, and stop talk directly to the live desktop runner instead of splitting checkpoint state or launching doomed short-lived CLI runners.
  - Merge live runners with on-disk checkpoints when listing status without a VM argument.
- App Sessions, Confirmations, Downloads & Telemetry:
  - Scope single-VM not_authorized errors to the target VM in handleSessionBegin and resolveComputerUseVM so active sessions on other VMs are not aborted.
  - Exclude stopped and suspended VMs from hasUnboundAgentSession fast-polling.
  - Revoke protected-phase grants when a VM disappears from poll results.
  - Require manifest Secret:true validation before storing auto-install passwords and remove the unsafe default account_password fallback.
  - Reject userinfo URLs in allow_custom_mirror, gate custom-mirror exemption strictly on plugin.ErrNetOriginNotDeclared, and keep redirect SSRF checks enabled on loopback custom mirrors.
  - Preserve VM telemetry milestones across suspend-resume and Win10 cold-reboot restarts while still resetting on fresh cold boots.
  - Log a warning when Guest Tools bridge is unavailable while preparing REIMSPROV.
  - Clarify CallHostAPI authorization/audit contract and add regression test proving built-in plugins enforce catalog permissions and audit logging.
- Host Takeover & Guest Tools:
  - Track locked mouse button presses via a 5-button bitmask so ButtonUp events from drags started outside the VM window are never swallowed.
  - Align active-window-reporter.js permissions to 0o100755 across ToolsDiskFiles, ToolsProvisionFiles, and postinstall.
- macOS Provisioning & Autoinstall Engine (OCR / Vision / Rules / Runner):
  - Never delete an unwiped REIMSPROV image on OpenFile/Write/Sync failure; persist wipe-pending marker and return error for retry.
  - Harden live postinstall preference writes with chmod 600, plutil -lint, chown, and cfprefsd flush.
  - Rewrite Windows RapidOCR C ABI structs and result extraction to match RapidAI/RapidOcrOnnx@675e73fe4c include/OcrLiteCApi.h:27-70 and src/OcrLiteCApi.cpp:12-160 (5-arg OcrInit verified).
  - Inspect PE32/PE32+ IMAGE_DIRECTORY_ENTRY_IMPORT directly to require onnxruntime.dll only for dynamically linked RapidOcrOnnx.dll builds.
  - Validate cfg.VM and use collision-free SHA-256-suffixed checkpoint paths with read fallback; redact PII/paths/UUIDs/MACs/IPs/tokens in diagnostic summaries; snapshot checkpoints before releasing r.mu for serialized disk I/O.
  - Add contrast/border/focus-ring ok return to DetectInputFieldNearLabel, enforce mask-dots verification in fillAccountForm and login screens, refuse blind password typing on clock-only lock screens, confirm shell readiness before typing install.sh, and prefer isolated button lines over modal prose in FindHit.
- Frontend:
  - Require explicit Apple SLA confirmation in both recovery_only and full modes across AutoInstallPanel and CreateWizard, with unit tests in frontend/scripts/test-autoinstall.mjs.

* fix(app,cli,host,macos,ui): address PR #134 third automated review findings

Addresses all confirmed findings from Review #6204465334 (commit d516350)
with targeted regression tests and hardens verified COM vtable bindings:

- App & Session Lifecycle:
  - Track hostPaused separately in agentSession so plugin host/session.update
    (paused_for_user=false) cannot clear physical user takeover or explicit
    PauseAgentSession holds; only host ResumeAgentSession or timed takeover
    expiry clears them.
  - Give each auto-install session watcher a monotonic watchGen + cancelable
    child context so restarting/resuming auto-install on the same VM cancels
    any superseded watcher and prevents stale timeout or secret cleanup.
  - Bound fast 500ms unbound-PID discovery for running VMs to
    sessionDiscoverGraceWindow via unboundSince (refreshed on restart/rebind).
  - Keep non-blocking buffered confirm resolution send inside confirmMu for
    clear mutual exclusion with cancelPendingConfirmations.
  - Clear cold-reboot telemetry preserveNextBoot via defer on all early-return
    and StartVM-failure paths in watchColdReboot.
  - Rebuild REIMSPROV with current StartAutoInstall credentials (preserving
    install_guest_tools) whenever VM is stopped instead of reusing stale images.
- CLI & macOS Provisioning / StartPrep:
  - Refuse `vm provision --clear` and overwriting existing REIMSPROV while the
    VM is running or paused.
  - Guard live "/" root in postinstall against macOS Recovery/Installer
    (/System/Installation/CDIS), forbid "/" in provision-offline.sh, and scope
    chmod 644 strictly to com.apple.keyboardtype.plist.
  - Reject unknown -* options in REIMSHELP/install.sh (including after --erase).
  - Defer clearing the one-shot REIMSPROV staged marker until after
    setExtraArgs (startprep) and StartWithCompat (macosdriver) succeed.
  - Preserve pending RestartFrom guards in AdvancePostInstallHandoff when
    checkpoint is already at StepDesktop.
- Host Input & Session Overlay:
  - Filter injected keyboard events (LLKHF_INJECTED / LLKHF_LOWER_IL_INJECTED)
    in locked-input mode consistently with the mouse hook.
  - Clean up exited overlay entries in entry.run() and recreate dead entries on
    Manager.Upsert when CreateWindowExW fails or exits early.
  - Cache the static island base surface (shell + icons + DirectWrite text) and
    measured text metrics across breathing frames, raising timerBreathMs to 100ms.
  - Replace magic Direct2D/DirectWrite vtable indices with named d2d1.h /
    dwrite.h constants, check EndDraw HRESULT, and add a live Windows DirectWrite
    rendering smoke test.
- Autoinstall OCR, Rules, Watchdog & Runner:
  - Persist and verify a per-file SHA-256 manifest.json in <dataDir>/ocr/
    before loading RapidOcrOnnx.dll / onnxruntime.dll; reject duplicate
    whitelisted basenames in offline zip imports.
  - Signal WinOCREngine.Close() before acquiring e.mu and add bounded wait +
    channel wakeup in Recognize so Close() immediately cancels in-flight OCR.
  - Fall back to installed RapidOCR when WinOCR initialization fails in Open(),
    and distinguish needs_rapidocr_import from needs_rapidocr_download in Probe.
  - Pause instead of pressing Return when post-TypeSecret login screenshot fails.
  - Re-baseline ColdRebootCount in Watchdog.ResetRebootWindow / ResetAfterResume.
  - Tighten recovery.main specificity (drop bare "Disk Utility"), guard 4-5 char
    pure-ASCII needles from sliding-window fuzzy collisions, use Unicode word
    boundaries for short names (<4 runes) in RedactDiagnosticText, and honor
    rule verify.wait_change_ms with early exit on visual frame diff.

* fix(autoinstall): handle CJK short-name redaction, sh-3.2 prompt bound, and OCR re-import pruning
2026-12-06 15:46:39 +08:00

879 lines
28 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"
"github.com/Nwflower/reims-go/pkg/pluginproto"
)
// PluginAPIVersion is the protocol version spoken by this SDK.
const PluginAPIVersion = "1.3.0"
// Error is a JSON-RPC error the host answered a Host API call with. Code is
// the JSON-RPC code, so a caller can tell a rejected request (-32602) from a
// method the host does not serve (-32601) or a failed call (-32000).
type Error struct {
Code int
Message string
}
func (e *Error) Error() string { return e.Message }
// InvalidParams is the code the host answers with when a request carries a
// field the contract does not define.
const InvalidParams = -32602
// MethodNotFound is the code the host answers with for a method it does not
// serve.
const MethodNotFound = -32601
// 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()
}
// HasFeature reports whether the host advertised feature in the handshake.
func (s *Server) HasFeature(feature string) bool {
s.mu.Lock()
defer s.mu.Unlock()
return s.initInfo.HasFeature(feature)
}
// callFeature invokes a Host API method the contract catalogs and the host
// advertised. A method outside the contract, or one this host does not
// advertise, is refused before it is sent, so a plugin never depends on a host
// that cannot serve it.
func (s *Server) callFeature(ctx context.Context, method string, params, out any) error {
if _, ok := pluginproto.Lookup(method); !ok {
return &Error{Code: MethodNotFound, Message: method + " is not part of the Host API contract"}
}
feature := pluginproto.Feature(method)
if !s.HasFeature(feature) {
return &Error{Code: MethodNotFound, Message: "the host does not advertise " + feature}
}
return s.CallHost(ctx, method, params, out)
}
// 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 &Error{Code: resp.Error.Code, Message: 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
}
// VMRef identifies a VM by its owning driver and name. Two drivers may own VMs
// with the same name, so a Sidecar with several drivers always sends the ref.
type VMRef = pluginproto.VMRef
// GuestOSInfo describes the guest operating system (family is one of
// "macos", "linux", "windows", "android").
type GuestOSInfo = pluginproto.GuestOSInfo
// VMEndpoint is one way to reach a guest. Kind is one of "ssh", "wsl", "rdp",
// "vmconnect" and "adb"; the host runs a fixed command per kind.
type VMEndpoint = pluginproto.VMEndpoint
// VMStateReport is the payload of `host/vm.reportState`.
type VMStateReport = pluginproto.ReportedVMState
// SpawnVMProcessWithRef spawns a VM process owned by ref. The host puts the
// process and every child it starts into one per-VM job, so monitoring,
// affinity and window lookup cover the whole tree.
func (s *Server) SpawnVMProcessWithRef(ctx context.Context, ref VMRef, 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{
"ref": ref,
"vm_name": ref.Name,
"exe_path": exePath,
"args": args,
"work_dir": workDir,
"env": env,
}, &resp)
return resp.PID, err
}
// StopVMProcessByRef terminates every process of ref's VM job.
func (s *Server) StopVMProcessByRef(ctx context.Context, ref VMRef) error {
return s.CallHost(ctx, "host/vm.stop", map[string]any{"ref": ref}, nil)
}
// IsVMProcessRunningByRef reports whether ref's VM job still has a process.
func (s *Server) IsVMProcessRunningByRef(ctx context.Context, ref VMRef) (bool, error) {
var resp struct {
Running bool `json:"running"`
}
err := s.CallHost(ctx, "host/vm.isRunning", map[string]any{"ref": ref}, &resp)
return resp.Running, err
}
// ReportVMState pushes the state of a VM the driver owns to the host.
func (s *Server) ReportVMState(ctx context.Context, report VMStateReport) error {
return s.CallHost(ctx, "host/vm.reportState", report, nil)
}
// MaterializeSecretRequest asks the host to fill Template with a secret
// setting and write the result to Dest inside the VM's folder. Format is
// "raw" (default), "xml" or "base64-utf16le"; Template must hold {{secret}}.
type MaterializeSecretRequest struct {
Setting string `json:"setting"`
Ref VMRef `json:"ref"`
Template string `json:"template"`
Dest string `json:"dest"`
Format string `json:"format,omitempty"`
}
// MaterializeSecret has the host write a file containing a secret setting and
// returns its path. The plugin never sees the secret itself.
func (s *Server) MaterializeSecret(ctx context.Context, req MaterializeSecretRequest) (string, error) {
var resp struct {
Path string `json:"path"`
}
err := s.CallHost(ctx, "host/secret.materialize", req, &resp)
return resp.Path, err
}
// DownloadRequest asks the host to download URL to Dest. The plugin must
// declare a `net:` permission for the URL's origin (HTTPS, or HTTP for
// loopback). Dest is relative to the plugin's data folder, or an absolute path
// inside it or inside a VM root the plugin's driver declared. The host verifies
// every file, so SHA256 or SHA256URL (with SHA256Name selecting a line) is
// required.
type DownloadRequest struct {
URL string `json:"url"`
SHA256 string `json:"sha256,omitempty"`
SHA256URL string `json:"sha256_url,omitempty"`
SHA256Name string `json:"sha256_name,omitempty"`
Dest string `json:"dest"`
Size int64 `json:"size,omitempty"`
Label string `json:"label,omitempty"`
ConnectTimeoutMS int `json:"connect_timeout_ms,omitempty"`
StallTimeoutMS int `json:"stall_timeout_ms,omitempty"`
AllowCustomMirror bool `json:"allow_custom_mirror,omitempty"`
}
// DownloadEvent is the payload of the host's `download/progress` notification.
// Status is "running", "done", "failed" or "canceled".
type DownloadEvent struct {
ID string `json:"id"`
Status string `json:"status"`
Done int64 `json:"done"`
Total int64 `json:"total"`
Percent float64 `json:"percent"`
Path string `json:"path,omitempty"`
Error string `json:"error,omitempty"`
}
// StartDownload has the host download a file in the background, with progress
// in the host's task list. It returns the download ID that
// `download/progress` notifications carry.
func (s *Server) StartDownload(ctx context.Context, req DownloadRequest) (string, error) {
var resp struct {
ID string `json:"id"`
}
err := s.CallHost(ctx, "host/download.start", req, &resp)
return resp.ID, err
}
// CancelDownload stops one of this plugin's downloads.
func (s *Server) CancelDownload(ctx context.Context, id string) error {
return s.CallHost(ctx, "host/download.cancel", map[string]any{"id": id}, nil)
}
// ElevationResult is returned by `host/elevate.request` after the user
// confirms both the host dialog and the Windows UAC prompt.
type ElevationResult struct {
OK bool `json:"ok"`
Action string `json:"action"`
ExitCode int `json:"exit_code,omitempty"`
RebootRequired bool `json:"reboot_required,omitempty"`
LogoffRequired bool `json:"logoff_required,omitempty"`
}
// RequestElevation asks the host to run one whitelisted Windows elevation
// action (`hyperv.enable`, `hyperv.addAdminGroup`, or `sandbox.enable`)
// after explicit user confirmation in the desktop window and Windows UAC.
func (s *Server) RequestElevation(ctx context.Context, action string) (ElevationResult, error) {
var resp ElevationResult
err := s.CallHost(ctx, "host/elevate.request", map[string]any{"action": action}, &resp)
return resp, err
}
// DiscardSecret deletes the files the host materialized for ref's VM, or only
// path when it is set. It returns how many files were removed.
func (s *Server) DiscardSecret(ctx context.Context, ref VMRef, path string) (int, error) {
var resp struct {
Removed int `json:"removed"`
}
err := s.CallHost(ctx, "host/secret.discard", map[string]any{"ref": ref, "path": path}, &resp)
return resp.Removed, 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)
}
// ConfirmRequest asks the host to show a native confirmation dialog.
type ConfirmRequest struct {
Title string `json:"title"`
Message string `json:"message"`
ConfirmLabel string `json:"confirm_label,omitempty"`
CancelLabel string `json:"cancel_label,omitempty"`
Danger bool `json:"danger,omitempty"`
VM string `json:"vm,omitempty"`
ProtectedPhase string `json:"protected_phase,omitempty"`
AllowDurationChoice bool `json:"allow_duration_choice,omitempty"`
DefaultDurationMin int `json:"default_duration_minutes,omitempty"`
PreferUntilPhaseExit bool `json:"prefer_until_phase_exit,omitempty"`
}
// ConfirmResult reports the user's answer to a host confirmation dialog.
type ConfirmResult struct {
Approved bool `json:"approved"`
DurationMinutes int `json:"duration_minutes,omitempty"`
UntilPhaseExit bool `json:"until_phase_exit,omitempty"`
Reason string `json:"reason,omitempty"`
}
// Confirm displays a native host confirmation dialog and waits for the user.
func (s *Server) Confirm(ctx context.Context, req ConfirmRequest) (ConfirmResult, error) {
var resp ConfirmResult
err := s.CallHost(ctx, "host/ui.confirm", req, &resp)
return resp, err
}
// SessionBeginRequest opens a visible remote-control session on a VM.
type SessionBeginRequest struct {
VM string `json:"vm"`
Label string `json:"label,omitempty"`
Stage string `json:"stage,omitempty"`
TakeoverPolicy string `json:"takeover_policy,omitempty"` // "" | "auto" | "manual" | "lock"
RequestProtectedPhaseAuth bool `json:"request_protected_phase_auth,omitempty"`
PreferUntilPhaseExit bool `json:"prefer_until_phase_exit,omitempty"`
}
// SessionUpdateRequest updates the visible stage/status shown in the host overlay and VM page.
type SessionUpdateRequest struct {
VM string `json:"vm"`
Stage string `json:"stage,omitempty"`
Status string `json:"status,omitempty"`
Message string `json:"message,omitempty"`
PausedForUser *bool `json:"paused_for_user,omitempty"`
}
// BeginSession starts a visible Agent/automation session on req.VM.
func (s *Server) BeginSession(ctx context.Context, req SessionBeginRequest) error {
return s.CallHost(ctx, "host/session.begin", req, nil)
}
// UpdateSession updates the visible progress state of an active session.
func (s *Server) UpdateSession(ctx context.Context, req SessionUpdateRequest) error {
return s.CallHost(ctx, "host/session.update", req, nil)
}
// EndSession ends the visible Agent/automation session on vm.
func (s *Server) EndSession(ctx context.Context, vm string) error {
return s.CallHost(ctx, "host/session.end", map[string]any{"vm": vm}, nil)
}
// ScreenshotRegion crops a framebuffer capture in source pixel coordinates.
type ScreenshotRegion struct {
X int `json:"x"`
Y int `json:"y"`
Width int `json:"width"`
Height int `json:"height"`
}
// ScreenshotRequest requests a full or cropped frame from a VM console.
type ScreenshotRequest struct {
VM string `json:"vm"`
Region *ScreenshotRegion `json:"region,omitempty"`
MaxEdge *int `json:"max_edge,omitempty"` // nil = default (1280 full, native cropped); 0 = native unscaled
Format string `json:"format,omitempty"` // "jpeg" | "png"
}
// ScreenshotResult is the payload returned by `host/console.screenshot`.
type ScreenshotResult struct {
MimeType string `json:"mime_type"`
Width int `json:"width"`
Height int `json:"height"`
SourceWidth int `json:"source_width"`
SourceHeight int `json:"source_height"`
Region *ScreenshotRegion `json:"region,omitempty"`
Blank bool `json:"blank"`
Data string `json:"data"`
}
// ConsoleScreenshot captures a full or cropped console screenshot.
func (s *Server) ConsoleScreenshot(ctx context.Context, req ScreenshotRequest) (ScreenshotResult, error) {
var resp ScreenshotResult
err := s.CallHost(ctx, "host/console.screenshot", req, &resp)
return resp, err
}
// ConsolePointerRequest sends one pointer event to a VM console.
type ConsolePointerRequest struct {
VM string `json:"vm"`
Action string `json:"action"` // move | click | button | scroll
X int `json:"x,omitempty"`
Y int `json:"y,omitempty"`
Width int `json:"width,omitempty"`
Height int `json:"height,omitempty"`
Button string `json:"button,omitempty"`
Down *bool `json:"down,omitempty"`
Delta int `json:"delta,omitempty"`
Horizontal bool `json:"horizontal,omitempty"`
}
// ConsolePointer sends a pointer action to a VM console.
func (s *Server) ConsolePointer(ctx context.Context, req ConsolePointerRequest) error {
return s.CallHost(ctx, "host/console.pointer", req, nil)
}
// ConsoleKey sends a key press with optional modifiers to a VM console.
func (s *Server) ConsoleKey(ctx context.Context, vm, key string, modifiers ...string) error {
return s.CallHost(ctx, "host/console.key", map[string]any{
"vm": vm,
"key": key,
"modifiers": modifiers,
}, nil)
}
// ConsoleType types UTF-8 text into a VM console.
func (s *Server) ConsoleType(ctx context.Context, vm, text string) (int, error) {
var resp struct {
Characters int `json:"characters"`
}
err := s.CallHost(ctx, "host/console.type", map[string]any{"vm": vm, "text": text}, &resp)
return resp.Characters, err
}
// ConsoleTypeSecret types a DPAPI-protected per-VM secret setting without trailing Enter.
func (s *Server) ConsoleTypeSecret(ctx context.Context, vm, setting string) (int, error) {
var resp struct {
Characters int `json:"characters"`
}
err := s.CallHost(ctx, "host/console.typeSecret", map[string]any{"vm": vm, "setting": setting}, &resp)
return resp.Characters, err
}
// FinishInstallVM invokes the VM driver's finish_install action (eject installer,
// remove REIMSHELP, enable network, upgrade AHCI->NVMe; never mounts REIMSTOOLS).
func (s *Server) FinishInstallVM(ctx context.Context, vm string) (map[string]any, error) {
var resp map[string]any
err := s.CallHost(ctx, "host/vm.finishInstall", map[string]any{"vm": vm}, &resp)
return resp, err
}
// RestartVM cleanly stops, waits for exit & memory reclaim, and restarts a VM.
func (s *Server) RestartVM(ctx context.Context, vm string) (map[string]any, error) {
var resp map[string]any
err := s.CallHost(ctx, "host/vm.restart", map[string]any{"vm": vm}, &resp)
return resp, err
}
// TelemetryMilestone is one parsed boot/runtime milestone from serial/QEMU logs.
type TelemetryMilestone struct {
Key string `json:"key"`
Count int `json:"count"`
At string `json:"at"`
}
// VMTelemetry is the redacted read-only snapshot returned by `host/vm.telemetry`.
type VMTelemetry struct {
VM string `json:"vm"`
State string `json:"state"`
Phase string `json:"phase"`
PID int `json:"pid"`
BootMilestones []TelemetryMilestone `json:"boot_milestones,omitempty"`
QemuErrors []string `json:"qemu_errors,omitempty"`
DiskBytes int64 `json:"disk_bytes"`
DiskDeltaBytes int64 `json:"disk_delta_bytes"`
CPUPercent float64 `json:"cpu_percent"`
ColdRebootCount int `json:"cold_reboot_count"`
UpdatedAt string `json:"updated_at,omitempty"`
}
// VMTelemetry queries structured, redacted runtime telemetry for vm.
func (s *Server) VMTelemetry(ctx context.Context, vm string) (VMTelemetry, error) {
var resp VMTelemetry
err := s.CallHost(ctx, "host/vm.telemetry", map[string]any{"vm": vm}, &resp)
return resp, err
}
// 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
}