Files
Reims-Go/internal/plugin/builtin/builtin.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

486 lines
18 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// Package builtin registers compiled-in Reims-Go extensions onto the unified
// plugin Registry (see docs/plugin-architecture.md). Every builtin
// runs through the same reversible Scope, service dependency graph and HookBus
// as external plugins. The core (core.go) is always on; disabling any optional
// extension leaves zero residue.
package builtin
import (
"context"
"fmt"
"strings"
"github.com/Nwflower/reims-go/internal/appwindow"
"github.com/Nwflower/reims-go/internal/config"
"github.com/Nwflower/reims-go/internal/driver"
"github.com/Nwflower/reims-go/internal/guesttools"
"github.com/Nwflower/reims-go/internal/host"
"github.com/Nwflower/reims-go/internal/i18n"
"github.com/Nwflower/reims-go/internal/macos/reims"
"github.com/Nwflower/reims-go/internal/networkmsg"
"github.com/Nwflower/reims-go/internal/plugin"
"github.com/Nwflower/reims-go/internal/qmp"
"github.com/Nwflower/reims-go/internal/version"
)
// Builtin plugin IDs. IDCore lives in core.go.
const (
// IDThemeDefault is the default theme's contribution ID; the core plugin
// contributes it.
IDThemeDefault = "builtin.theme.default"
// IDDriverReimsMacOS is the guest driver ID of the reims macOS driver,
// recorded in VM ownership markers; internal/macos/guest registers it.
IDDriverReimsMacOS = driver.BuiltinReimsMacOSDriverID
IDGuestTools = "builtin.bridge.guest-tools"
IDClipboard = "builtin.bridge.clipboard"
IDInput = "builtin.input"
IDNpcapBridge = "builtin.network.npcap"
IDComputerUse = "builtin.computer-use"
)
// Service names provided by builtin extensions.
const (
ServiceGuestToolsTransport = "guest-tools.transport"
ServiceHostInput = "host.input"
ServiceNpcapBridge = "network.npcap"
ServiceComputerUse = "computer-use.console"
)
// HostCallbacks connects builtin extensions to host runtime services without
// creating an import cycle with internal/app.
type HostCallbacks struct {
GetConfig func() config.Config
Log func(source, line string)
EnsureGuestTools func() (*guesttools.Server, int, error)
StopGuestTools func()
LoadAndRegisterGuestTools func(*guesttools.Server, int, string, string) (guesttools.VMConfig, error)
OnIMEText func(target host.IMETarget, text string)
StartColdReboot func(vmName, qmpAddr string)
CancelColdReboot func(vmName string)
GuestToolsImg func(vmName string) string
BuildGuestToolsImage func(vmName, vmDir string) error
OpenAppWindow func(context.Context, *appwindow.Sessions, *guesttools.Server, ComputerUseService, string) error
PrepareVMNetwork func(context.Context, string, bool) (func(), error)
// 返回取消并等待本次恢复任务结束的清理函数,由插件 scope 先于通道释放执行。
RestorePacketBridges func(context.Context) func()
StopPacketBridges func()
OnInstallGuidesChanged func()
SyncInstallGuides func()
// GetSetting returns a saved plugin setting value (empty vmName = app scope).
GetSetting func(pluginID, vmName, key string) (any, bool)
// PluginDataDir returns the private writable data directory for pluginID.
PluginDataDir func(pluginID string) string
// PluginLogPath returns the audit log path for pluginID.
PluginLogPath func(pluginID string) string
// CallHostAPI invokes a host-owned reverse RPC handler through the plugin
// manager's permission and audit pipeline.
CallHostAPI func(ctx context.Context, pluginID, method string, params any, out any) error
}
func appVersion() string {
v := strings.TrimPrefix(strings.TrimSpace(version.Version), "v")
if v == "" || v == "dev" {
return "0.2.13"
}
return v
}
// RegisterAll registers the core and the optional builtin extensions into reg.
// desiredFn optionally overrides defaultEnabled (e.g. from state.json).
func RegisterAll(reg *plugin.Registry, cb HostCallbacks, desiredFn func(id string, defaultEnabled bool) bool) error {
if desiredFn == nil {
desiredFn = func(_ string, def bool) bool { return def }
}
ver := appVersion()
defs := []plugin.PluginDef{
defCore(ver),
defGuestTools(ver, cb, desiredFn),
defClipboard(ver, desiredFn),
defInput(ver, cb, desiredFn),
defNpcapBridge(ver, cb, desiredFn),
defComputerUse(ver, desiredFn),
defAppWindow(ver, cb, desiredFn),
defDownloaderParallel(ver, cb, desiredFn),
}
for _, d := range defs {
if err := reg.Register(d); err != nil {
return err
}
}
return nil
}
func defGuestTools(ver string, cb HostCallbacks, desiredFn func(string, bool) bool) plugin.PluginDef {
return plugin.PluginDef{
Manifest: plugin.Manifest{
Schema: 1,
ID: IDGuestTools,
Version: ver,
Name: plugin.LocalizedText{ZhCN: "Guest Tools 传输服务", EnUS: "Guest Tools Transport"},
Description: plugin.LocalizedText{
ZhCN: "宿主与虚拟机之间的通信通道,支撑共享文件夹和防休眠",
EnUS: "Host–guest channel behind shared folders and keep-awake",
},
Publisher: "Reims-Go",
License: "Apache-2.0",
Icon: iconGuestTools,
Provides: []plugin.ServiceProvision{{Service: ServiceGuestToolsTransport, Version: "1.0.0"}},
Permissions: []string{"vm:intent", "fs:shared", "ui:slot"},
DefaultEnabled: true,
},
Source: plugin.SourceBuiltin,
Trust: plugin.TrustOfficial,
Desired: desiredFn(IDGuestTools, true),
Activate: func(_ context.Context, sc *plugin.Scope) error {
var srv *guesttools.Server
if cb.EnsureGuestTools != nil {
s, _, err := cb.EnsureGuestTools()
if err != nil {
return err
}
srv = s
} else {
srv = guesttools.NewTransportServer(nil)
}
sc.Provide(ServiceGuestToolsTransport, "1.0.0", srv)
sc.OnDispose(func() {
if cb.StopGuestTools != nil {
cb.StopGuestTools()
}
})
sc.Registry().RegisterVMCard(sc, plugin.VMCardContribution{
ID: "guest-tools-transport",
Title: plugin.LocalizedText{ZhCN: "宿客协作通道", EnUS: "Guest Tools Bridge"},
Value: plugin.LocalizedText{ZhCN: "已就绪", EnUS: "Ready"},
Badge: "ok",
When: "capability:guest_tools",
})
sc.Registry().Hooks().Subscribe(sc, plugin.HookRegistration{
Event: plugin.EventVMBeforeStart,
Builtin: true,
Handler: func(_ context.Context, raw any) (any, error) {
p, ok := raw.(plugin.BeforeStartPayload)
if !ok || p.VMDir == "" || p.DriverID != IDDriverReimsMacOS {
return nil, nil
}
if cb.EnsureGuestTools == nil || cb.LoadAndRegisterGuestTools == nil {
return nil, nil
}
s, port, err := cb.EnsureGuestTools()
if err != nil || port <= 0 {
return nil, nil
}
intent := plugin.StartIntent{
PluginID: IDGuestTools,
Env: map[string]string{},
}
gtCfg, err := cb.LoadAndRegisterGuestTools(s, port, p.VMDir, p.VMName)
if err == nil && gtCfg.Token != "" {
rec, _ := reims.ReadNetworkRecord(p.VMDir)
netEnabled, _ := reims.ReadVMNetworkEnabled(p.VMDir)
mode := reims.EffectiveNetworkMode(netEnabled, p.ExtraArgs, rec)
if mode == "bridge" && sc.Registry().IsActive(IDNpcapBridge) {
loc := i18n.Auto
if cb.GetConfig != nil {
loc = cb.GetConfig().Locale
}
tokens, argsErr := reims.GuestToolsNetworkUnixArgs(p.VMDir, gtCfg.ManagementOutSock, gtCfg.ManagementInSock)
if argsErr != nil {
return nil, networkmsg.Localize(argsErr, loc)
}
intent.Args = append(intent.Args, plugin.ArgFragment{PluginID: IDGuestTools, Key: "guest-tools-network", Tokens: tokens, Builtin: true, Priority: 79})
} else {
s.StopManagementNetwork(p.VMName)
intent.ClearKeys = append(intent.ClearKeys, "guest-tools-network")
}
if plugin.HasCap(p.RuntimeCaps, "window-file-drop") {
if token := s.HostDropToken(gtCfg.DriverID, p.VMName); token != "" {
intent.Env["REIMS_GO_DROP_URL"] = fmt.Sprintf("http://127.0.0.1:%d/v1/host-drop", port)
intent.Env["REIMS_GO_DROP_TOKEN"] = token
}
}
if sc.Registry().IsActive(IDInput) && plugin.HasCap(p.RuntimeCaps, "win32-unicode-input") {
intent.Env["REIMS_GO_INPUT_URL"] = fmt.Sprintf("http://127.0.0.1:%d/v1/host-text", port)
intent.Env["REIMS_GO_INPUT_TOKEN"] = gtCfg.Token
}
}
if reims.HasGuestToolsArgs(p.ExtraArgs) && cb.GuestToolsImg != nil && err == nil {
imgPath := cb.GuestToolsImg(p.VMName)
tokens := qmp.SplitArgs(reims.MergeGuestToolsArgs("", imgPath))
intent.Args = append(intent.Args, plugin.ArgFragment{
PluginID: IDGuestTools,
Key: "reimstools",
Tokens: tokens,
Builtin: true,
Priority: 80,
})
} else if !reims.HasGuestToolsArgs(p.ExtraArgs) {
intent.ClearKeys = append(intent.ClearKeys, "reimstools")
}
return intent, nil
},
})
return nil
},
}
}
func defClipboard(ver string, desiredFn func(string, bool) bool) plugin.PluginDef {
minMB := 1.0
maxMB := 16.0
minFileMB := float64(guesttools.MinClipboardMaxFileMB)
maxFileMB := float64(guesttools.MaxClipboardMaxFileMB)
return plugin.PluginDef{
Manifest: plugin.Manifest{
Schema: 1,
ID: IDClipboard,
Version: ver,
Name: plugin.LocalizedText{ZhCN: "剪贴板互通", EnUS: "Clipboard Sync"},
Description: plugin.LocalizedText{
ZhCN: "在 Windows 和 macOS 之间同步复制的文本、截图与文件",
EnUS: "Sync copied text, screenshots, and files between Windows and macOS",
},
Publisher: "Reims-Go",
License: "Apache-2.0",
Icon: iconClipboard,
Requires: []plugin.ServiceRequirement{{Service: ServiceGuestToolsTransport, Version: "^1.0.0"}},
Permissions: []string{"host:clipboard", "ui:slot"},
DefaultEnabled: true,
Settings: &plugin.SettingsSchema{
Title: plugin.LocalizedText{ZhCN: "剪贴板互通", EnUS: "Clipboard Sync"},
Scope: "app",
Order: []string{"enabled", "direction", "sync_images", "max_image_mb", "sync_files", "max_file_mb"},
Properties: map[string]plugin.SettingProperty{
"enabled": {
Type: "boolean",
Title: plugin.LocalizedText{ZhCN: "启用剪贴板互通", EnUS: "Enable clipboard sync"},
Default: true,
Effect: "immediate",
Scope: "app",
},
"direction": {
Type: "string",
Title: plugin.LocalizedText{ZhCN: "同步方向", EnUS: "Sync direction"},
Enum: []string{"bidirectional", "host-to-guest", "guest-to-host"},
EnumLabels: []plugin.LocalizedText{
{ZhCN: "双向同步", EnUS: "Bidirectional"},
{ZhCN: "仅宿主到虚拟机", EnUS: "Host to guest only"},
{ZhCN: "仅虚拟机到宿主", EnUS: "Guest to host only"},
},
Default: "bidirectional",
Effect: "immediate",
Scope: "app",
},
"sync_images": {
Type: "boolean",
Title: plugin.LocalizedText{ZhCN: "同步剪贴板图片", EnUS: "Sync clipboard images"},
Default: true,
Effect: "immediate",
Scope: "app",
},
"max_image_mb": {
Type: "integer",
Title: plugin.LocalizedText{ZhCN: "图片大小上限 (MB)", EnUS: "Max image size (MB)"},
Default: 16,
Minimum: &minMB,
Maximum: &maxMB,
Effect: "immediate",
Scope: "app",
},
"sync_files": {
Type: "boolean",
Title: plugin.LocalizedText{ZhCN: "同步剪贴板文件", EnUS: "Sync clipboard files"},
Default: true,
Effect: "immediate",
Scope: "app",
},
"max_file_mb": {
Type: "integer",
Title: plugin.LocalizedText{ZhCN: "文件传输上限 (MB)", EnUS: "File transfer limit (MB)"},
Description: plugin.LocalizedText{
ZhCN: "限制从 macOS 粘贴到 Windows 或共享挂载不可用时的单次传输总大小。",
EnUS: "Limits the total size per paste from macOS to Windows or when the shared mount is unavailable.",
},
Default: guesttools.DefaultClipboardPolicy().MaxFileBytes >> 20,
Minimum: &minFileMB,
Maximum: &maxFileMB,
Effect: "immediate",
Scope: "app",
},
},
},
},
Source: plugin.SourceBuiltin,
Trust: plugin.TrustOfficial,
Desired: desiredFn(IDClipboard, true),
Activate: func(_ context.Context, sc *plugin.Scope) error {
rawSvc, ok := sc.Lookup(ServiceGuestToolsTransport)
if !ok {
return fmt.Errorf("required service %q not available", ServiceGuestToolsTransport)
}
srv, ok := rawSvc.(*guesttools.Server)
if !ok || srv == nil {
return fmt.Errorf("invalid %q service instance", ServiceGuestToolsTransport)
}
srv.SetClipboardActive(true)
sc.OnDispose(func() {
srv.SetClipboardActive(false)
})
sc.Registry().RegisterVMCard(sc, plugin.VMCardContribution{
ID: "clipboard-sync",
Title: plugin.LocalizedText{ZhCN: "剪贴板互通", EnUS: "Clipboard Sync"},
Value: plugin.LocalizedText{ZhCN: "已启用", EnUS: "Active"},
Badge: "ok",
When: "capability:guest_tools",
})
sc.Registry().RegisterDiagnostics(sc, plugin.DiagnosticsContribution{
ID: "clipboard-stats",
Title: plugin.LocalizedText{ZhCN: "剪贴板同步统计", EnUS: "Clipboard Sync Counters"},
}, func(_ context.Context, _ string) (plugin.DiagnosticsEntry, error) {
stats := srv.ClipboardDiagnostics()
// Privacy rule: record counters and errors only, never clipboard content.
return plugin.DiagnosticsEntry{
PluginID: IDClipboard,
Title: "Clipboard Sync Counters",
Data: map[string]any{
"active": stats.Active,
"watcher_running": stats.WatcherRunning,
"host_to_guest_count": stats.HostToGuestCount,
"host_to_guest_files_applied_count": stats.HostToGuestFilesAppliedCount,
"guest_to_host_count": stats.GuestToHostCount,
"error_count": stats.ErrorCount,
},
}, nil
})
return nil
},
}
}
func defInput(ver string, cb HostCallbacks, desiredFn func(string, bool) bool) plugin.PluginDef {
return plugin.PluginDef{
Manifest: plugin.Manifest{
Schema: 1,
ID: IDInput,
Version: ver,
Name: plugin.LocalizedText{ZhCN: "宿主输入服务与 IME 桥接", EnUS: "Host Input Service & IME Bridge"},
Description: plugin.LocalizedText{
ZhCN: "用 Windows 输入法直接向虚拟机输入文字",
EnUS: "Type into the VM directly with the Windows IME",
},
Publisher: "Reims-Go",
License: "Apache-2.0",
Icon: iconInput,
Provides: []plugin.ServiceProvision{{Service: ServiceHostInput, Version: "1.0.0"}},
Permissions: []string{"input:filter"},
DefaultEnabled: true,
},
Source: plugin.SourceBuiltin,
Trust: plugin.TrustOfficial,
Desired: desiredFn(IDInput, true),
Activate: func(_ context.Context, sc *plugin.Scope) error {
svc := host.NewInputService(cb.OnIMEText)
if cb.OnIMEText != nil {
if err := svc.EnableIME(true); err != nil && cb.Log != nil {
cb.Log("app", "Remote IME hook unavailable: "+err.Error())
}
}
sc.Provide(ServiceHostInput, "1.0.0", svc)
sc.OnDispose(func() {
svc.Close()
})
return nil
},
}
}
func defNpcapBridge(ver string, cb HostCallbacks, desiredFn func(string, bool) bool) plugin.PluginDef {
return plugin.PluginDef{
Manifest: plugin.Manifest{
Schema: 1,
ID: IDNpcapBridge,
Version: ver,
Name: plugin.LocalizedText{ZhCN: "Npcap 网络桥接", EnUS: "Npcap Network Bridge"},
Description: plugin.LocalizedText{
ZhCN: "通过 Npcap 为虚拟机提供独立物理出口桥接与运行中切换出口",
EnUS: "Per-VM physical uplink bridging and live uplink switching via Npcap",
},
Publisher: "Reims-Go",
License: "Apache-2.0",
Icon: iconNpcap,
Provides: []plugin.ServiceProvision{{Service: ServiceNpcapBridge, Version: "1.0.0"}},
Permissions: []string{"vm:intent"},
DefaultEnabled: true,
},
Source: plugin.SourceBuiltin,
Trust: plugin.TrustOfficial,
Desired: desiredFn(IDNpcapBridge, true),
Activate: func(ctx context.Context, sc *plugin.Scope) error {
sc.Provide(ServiceNpcapBridge, "1.0.0", struct{}{})
sc.OnDispose(func() {
if cb.StopPacketBridges != nil {
cb.StopPacketBridges()
}
})
if cb.RestorePacketBridges != nil {
// 激活请求结束不取消常驻任务;任务生命周期由本插件 scope 管理。
sc.OnDispose(cb.RestorePacketBridges(context.WithoutCancel(ctx)))
}
sc.Registry().Hooks().Subscribe(sc, plugin.HookRegistration{
Event: plugin.EventVMBeforeStart,
Builtin: true,
Handler: func(_ context.Context, raw any) (any, error) {
p, ok := raw.(plugin.BeforeStartPayload)
if !ok || p.VMDir == "" || p.DriverID != IDDriverReimsMacOS {
return nil, nil
}
intent := plugin.StartIntent{PluginID: IDNpcapBridge}
rec, err := reims.ReadNetworkRecord(p.VMDir)
if err != nil || rec.Corrupt || rec.Pending {
return intent, nil
}
netEnabled, _ := reims.ReadVMNetworkEnabled(p.VMDir)
mode := reims.EffectiveNetworkMode(netEnabled, p.ExtraArgs, rec)
if mode != "bridge" || rec.UplinkGUID == "" {
intent.ClearKeys = append(intent.ClearKeys, "bridge-network", "npcap-bridge")
return intent, nil
}
mac, err := reims.ReadVMNetworkMAC(p.VMDir)
if err != nil {
return nil, err
}
tmpDir := ""
if cb.GetConfig != nil {
cfg := cb.GetConfig()
tmpDir = cfg.TempDir()
}
sockPath := rec.SocketPath
if sockPath == "" {
sockPath = reims.VMUnixSocketPath(p.VMDir, tmpDir, p.VMName, "bridge.sock")
}
tokens, err := reims.PacketBridgeUnixTokens(mac, sockPath)
if err != nil {
return nil, err
}
// 键名按字典序排在 guest-tools-network 之前,确保带固定 addr=0x3 的主网卡先于管理网卡声明,避免被抢占 PCI 3 号槽位。
intent.ClearKeys = append(intent.ClearKeys, "npcap-bridge")
intent.Args = append(intent.Args, plugin.ArgFragment{
PluginID: IDNpcapBridge,
Key: "bridge-network",
Tokens: tokens,
Builtin: true,
Priority: 78,
})
return intent, nil
},
})
return nil
},
}
}