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

698 lines
23 KiB
Go

package cli
import (
"context"
"encoding/json"
"errors"
"flag"
"fmt"
"io"
"os"
"path/filepath"
"strings"
"github.com/Nwflower/reims-go/internal/config"
"github.com/Nwflower/reims-go/internal/dataroot"
"github.com/Nwflower/reims-go/internal/driver"
"github.com/Nwflower/reims-go/internal/host"
"github.com/Nwflower/reims-go/internal/i18n"
"github.com/Nwflower/reims-go/internal/lifecycle"
"github.com/Nwflower/reims-go/internal/plugin"
rt "github.com/Nwflower/reims-go/internal/runtime"
"github.com/Nwflower/reims-go/internal/version"
)
// Package cli is reims-go's command-line mode. The single reims-go.exe opens
// the desktop window when started without a command and runs this package
// when given one (see main.go); both share the internal/ packages.
// Main runs one command and returns the process exit code.
func Main(args []string) int {
i18n.SetDetailRedactor(host.RedactText)
loc, err := run(args)
if err != nil {
fmt.Fprintf(os.Stderr, "error: %s\n", i18n.FormatCLIError(loc, err))
return 1
}
return 0
}
// IsCommand reports whether args ask for command-line mode rather than the
// desktop window: anything except no arguments or the window's own flags.
func IsCommand(args []string) bool {
_, isWindow := ParseWindowArgs(args)
return !isWindow
}
func run(args []string) (i18n.Locale, error) {
fs := flag.NewFlagSet("reims-go", flag.ContinueOnError)
fs.SetOutput(io.Discard)
langFlag := fs.String("lang", "", "UI/CLI language: auto | zh-CN | en-US | <BCP-47> | en-XA")
dataRootFlag := fs.String("data-root", "", "Override reims-go data root directory")
helpFlag := fs.Bool("help", false, "Show CLI usage")
hFlag := fs.Bool("h", false, "Show CLI usage")
if err := fs.Parse(args); err != nil {
return i18n.Detect(), err
}
cfgPath := ""
if *dataRootFlag != "" {
cfgPath = filepath.Join(*dataRootFlag, "reims-go.json")
}
cfg, err := config.Load(cfgPath)
if err != nil {
return i18n.Detect(), err
}
if *dataRootFlag != "" {
cfg.DataRoot = *dataRootFlag
}
// Same check and upgrade the GUI runs on startup (internal/dataroot).
root := dataroot.Open(cfg.DataRoot, version.Version)
// Load enabled static language packs from <DataRoot>/plugins before resolving
// effective locale so "auto" and custom --lang tags (e.g. ja-JP, zh-TW) work in CLI.
plugin.LoadStaticLocalePacks(cfg.DataRoot)
if *langFlag != "" {
cfg.Locale = i18n.ParsePreference(*langFlag)
}
loc := i18n.EffectiveLocale(cfg.Locale)
cfg.Locale = loc
rest := fs.Args()
if len(rest) == 0 || *helpFlag || *hFlag {
printUsage(loc)
return loc, nil
}
// A folder open read-only (written by a newer release, damaged version
// record, failed upgrade) only serves commands that never write to it.
if root.ReadOnly && !readOnlySafeCommand(rest[0]) {
return loc, dataroot.Error(loc, root)
}
switch rest[0] {
case "doctor":
return loc, cmdDoctor(cfg, loc, root, rest[1:])
case "runtime":
return loc, cmdRuntime(cfg, loc, rest[1:])
case "vm":
return loc, cmdVM(cfg, loc, rest[1:], canHandoffDataRoot(cfg.DataRoot))
case "installer":
return loc, cmdInstaller(cfg, loc, rest[1:])
case "plugin":
return loc, cmdPlugin(cfg, loc, rest[1:])
case "host":
return loc, cmdHost(cfg, rest[1:])
case "version", "-v", "--version":
fmt.Printf("reims-go %s\n", version.Version)
return loc, nil
case "help", "-h", "--help":
printUsage(loc)
return loc, nil
default:
return loc, fmt.Errorf("unknown command %q", rest[0])
}
}
func printUsage(loc i18n.Locale) {
if isAppleCreateDriver(defaultCreateDriver()) {
printAppleUsage(loc)
return
}
fmt.Println(i18n.T(loc, "cli.usage.header"))
fmt.Println("\n" + i18n.T(loc, "cli.usage.section_usage"))
fmt.Println(i18n.T(loc, "cli.usage.line_gui"))
fmt.Println(i18n.T(loc, "cli.usage.line_cmd"))
fmt.Println("\n" + i18n.T(loc, "cli.usage.ps_hint"))
fmt.Println("\n" + i18n.T(loc, "cli.usage.section_commands"))
for _, k := range []string{
"cli.usage.cmd_doctor",
"cli.usage.cmd_rt_avail",
"cli.usage.cmd_rt_fetch",
"cli.usage.cmd_rt_install",
"cli.usage.cmd_rt_list",
"cli.usage.cmd_rt_use",
"cli.usage.cmd_rt_remove",
"cli.usage.cmd_vm_list",
"cli.usage.cmd_vm_create",
"cli.usage.cmd_vm_set",
"cli.usage.cmd_vm_resize",
"cli.usage.cmd_vm_compact",
"cli.usage.cmd_vm_start",
"cli.usage.cmd_vm_stop",
"cli.usage.cmd_vm_suspend",
"cli.usage.cmd_vm_resume",
"cli.usage.cmd_vm_discard_suspend",
"cli.usage.cmd_vm_type",
"cli.usage.cmd_inst_list",
"cli.usage.cmd_inst_dl",
"cli.usage.cmd_inst_cached",
"cli.usage.cmd_inst_del",
"cli.usage.cmd_plugin",
"cli.usage.cmd_version",
} {
fmt.Println(i18n.T(loc, k))
}
}
func cmdDoctor(cfg *config.Config, loc i18n.Locale, root dataroot.Status, args []string) error {
fs := flag.NewFlagSet("doctor", flag.ContinueOnError)
asJSON := fs.Bool("json", false, "Output JSON")
if err := fs.Parse(args); err != nil {
return err
}
rep := host.Inspect(cfg.DataRoot)
if native, err := nativeVirtualizationStatus(context.Background()); native {
rep.AppleVirtualization = &host.AppleVirtualizationStatus{Ready: err == nil}
if err != nil {
rep.AppleVirtualization.Detail = i18n.FormatCLIError(loc, err)
}
}
active, _ := rt.ResolveActive(cfg)
if *asJSON {
payload := map[string]any{
"host": rep,
"config": cfg,
"runtime": active,
"data_root": root,
}
return printJSON(payload)
}
fmt.Printf("=== %s ===\n", i18n.T(loc, "doctor.title"))
fmt.Printf("%-36s: %s/%s\n", i18n.T(loc, "doctor.os"), rep.OS, rep.Arch)
fmt.Printf("%-36s: %dC / %dT\n", i18n.T(loc, "doctor.cpu"), rep.PhysicalCores, rep.LogicalCPUs)
if rep.HasHybridCores {
fmt.Printf("%-36s: %s\n", i18n.T(loc, "doctor.pcores"), i18n.T(loc, "doctor.pcores.detail", rep.PCoreCount, rep.PCoreMaskHex, rep.PCoreLogicalCPUs))
fmt.Printf("%-36s: %s\n", i18n.T(loc, "doctor.ecores"), i18n.T(loc, "doctor.ecores.detail", rep.ECoreCount, rep.ECoreLogicalCPUs))
}
if rep.TotalRAMGB > 0 {
memory := i18n.M(loc, "doctor.ram.total_only", i18n.Vars{"total": rep.TotalRAMGB})
if rep.MemoryUsageKnown {
memory = i18n.T(loc, "doctor.ram.detail", rep.TotalRAMGB, rep.AvailRAMGB)
}
fmt.Printf("%-36s: %s\n", i18n.T(loc, "doctor.ram"), memory)
}
if rep.AppleVirtualization != nil {
printAppleVirtualizationStatus(loc, rep.AppleVirtualization)
}
if rep.FreeDiskGB > 0 {
fmt.Printf("%-36s: %.1f GB (%s)\n", i18n.T(loc, "doctor.disk"), rep.FreeDiskGB, rep.DataRoot)
}
if err := dataroot.Error(loc, root); err != nil {
fmt.Fprintln(os.Stderr, i18n.FormatCLIError(loc, err))
}
if rep.AppleVirtualization == nil {
whpxKey := "doctor.whpx.unsupported"
switch rep.WHPX {
case host.WHPXReady:
whpxKey = "doctor.whpx.ok"
case host.WHPXHypervisorOff:
whpxKey = "doctor.whpx.hypervisor_off"
case host.WHPXNoHypervisor:
whpxKey = "doctor.whpx.no_hv"
case host.WHPXMissing:
whpxKey = "doctor.whpx.missing"
}
fmt.Printf("%-36s: %s\n", i18n.T(loc, "doctor.whpx"), i18n.T(loc, whpxKey))
}
printDoctorVulkan(loc, rep)
if active == nil {
fmt.Printf("%-36s: %s\n", i18n.T(loc, "doctor.runtime"), i18n.T(loc, "doctor.runtime.none"))
} else {
fmt.Printf("%-36s: %s\n", i18n.T(loc, "doctor.runtime"), i18n.T(loc, "doctor.runtime.active", active.Commit, active.Dir))
}
if len(rep.DeepBackingChains) > 0 {
fmt.Printf("%s:\n", i18n.T(loc, "doctor.cow_chain"))
for _, c := range rep.DeepBackingChains {
if c.Broken {
fmt.Printf(" ! %s\n", i18n.T(loc, "doctor.cow_chain.broken", c.VMName, c.Depth, c.Path))
} else {
fmt.Printf(" ! %s\n", i18n.T(loc, "doctor.cow_chain.item", c.VMName, c.Depth, host.BackingChainWarnDepth))
}
}
}
return nil
}
func printDoctorVulkan(loc i18n.Locale, rep host.Report) {
if rep.AppleVirtualization != nil && rep.VulkanProbeError == "" && len(rep.GPUs) == 0 {
return // The native host does not use or probe Vulkan.
}
if rep.VulkanProbeError != "" {
fmt.Printf("%-36s: %s\n", i18n.T(loc, "doctor.gpu"), i18n.M(loc, "doctor.gpu.probe_failed", i18n.Vars{"detail": rep.VulkanProbeError}))
}
if len(rep.GPUs) == 0 && rep.VulkanProbeError == "" {
fmt.Printf("%-36s: %s\n", i18n.T(loc, "doctor.gpu"), i18n.T(loc, "doctor.gpu.none"))
} else if len(rep.GPUs) > 0 {
fmt.Printf("%s:\n", i18n.T(loc, "doctor.gpu"))
for _, g := range rep.GPUs {
tags := []string{}
if rep.RecommendedGPU != nil && sameGPU(rep.RecommendedGPU, &g) {
tags = append(tags, i18n.T(loc, "doctor.gpu.recommended"))
}
if g.Compat != "" {
tags = append(tags, i18n.T(loc, "doctor.gpu.compat."+string(g.Compat)))
}
tagStr := ""
if len(tags) > 0 {
tagStr = " [" + strings.Join(tags, " | ") + "]"
}
meta := []string{}
if g.VendorID != "" && g.DeviceID != "" {
meta = append(meta, g.VendorID+":"+g.DeviceID)
}
if g.VulkanVersion != "" {
meta = append(meta, "Vulkan "+g.VulkanVersion)
}
if g.DriverVersion != "" {
meta = append(meta, "drv "+g.DriverVersion)
}
metaStr := ""
if len(meta) > 0 {
metaStr = " (" + strings.Join(meta, ", ") + ")"
}
fmt.Printf(" - [%s] %s%s%s\n", g.Kind, g.Name, metaStr, tagStr)
if g.VulkanICD != "" {
fmt.Printf(" ICD: %s\n", g.VulkanICD)
}
if note := formatGPUCompatNote(loc, g); note != "" {
fmt.Printf(" ! %s\n", note)
}
}
}
}
func sameGPU(a, b *host.GPUInfo) bool {
if a == nil || b == nil {
return false
}
if a.VendorID != "" && a.DeviceID != "" && b.VendorID != "" && b.DeviceID != "" {
return a.VendorID == b.VendorID && a.DeviceID == b.DeviceID
}
return a.VulkanICD != "" && a.VulkanICD == b.VulkanICD && a.Name == b.Name
}
func formatGPUCompatNote(loc i18n.Locale, g host.GPUInfo) string {
switch g.CompatCode {
case "amd_legacy_win_driver":
return i18n.T(loc, "doctor.gpu.warn.amd_legacy", g.CompatDetail)
case "amd_rdna2_device_lost":
return i18n.T(loc, "doctor.gpu.warn.amd_rdna2", g.CompatDetail)
case "vulkan_too_old":
return i18n.T(loc, "doctor.gpu.err.vulkan_too_old", g.CompatDetail)
case "vulkan_missing_extensions":
return i18n.T(loc, "doctor.gpu.err.missing_ext", g.CompatDetail)
case "vulkan_cpu":
return i18n.T(loc, "doctor.gpu.err.vulkan_cpu")
default:
return ""
}
}
func activateRuntime(ctx context.Context, cfg *config.Config, loc i18n.Locale, commit string) error {
return rt.Activate(ctx, cfg, commit, func(warning error) {
fmt.Fprintln(os.Stderr, i18n.FormatCLIError(loc, warning))
})
}
func cmdRuntime(cfg *config.Config, loc i18n.Locale, args []string) error {
if len(args) == 0 {
return fmt.Errorf("usage: reims-go runtime <available|fetch|install|list|use|remove>")
}
switch args[0] {
case "install":
if len(args) < 2 {
return fmt.Errorf("usage: reims-go runtime install <archive.tar.zst|zip>")
}
inst, err := rt.InstallFromArchive(cfg, args[1])
if err != nil {
if errors.Is(err, rt.ErrRuntimeInUse) {
return i18n.NewCodedError(loc, "E_RUNTIME_IN_USE", "runtime.install_in_use", nil, err)
}
return err
}
if err := activateRuntime(context.Background(), cfg, loc, inst.Commit); err != nil {
return err
}
fmt.Println(i18n.T(loc, "runtime.installed", inst.Commit, inst.Dir))
return nil
case "list":
list, err := rt.List(cfg)
if err != nil {
return err
}
if len(list) == 0 {
fmt.Println(i18n.T(loc, "runtime.empty"))
return nil
}
for _, item := range list {
mark := " "
if item.Active {
mark = "*"
}
kind := item.Kind
if kind == "" {
kind = item.Manifest.EffectiveKind()
}
apiVer := item.Manifest.EffectiveRuntimeAPI()
caps := strings.Join(item.Manifest.EffectiveCapabilities(), ",")
if caps != "" {
caps = " [" + caps + "]"
}
fmt.Printf("%s %-11s %-12s api=%-6s %s%s (%s)\n", mark, kind, item.Commit, apiVer, item.Manifest.QemuVersion, caps, item.Dir)
}
return nil
case "use":
if len(args) < 2 {
return fmt.Errorf("usage: reims-go runtime use <commit>")
}
if err := activateRuntime(context.Background(), cfg, loc, args[1]); err != nil {
if errors.Is(err, rt.ErrNotFound) {
return errors.New(i18n.T(loc, "runtime.not_found", args[1]))
}
return err
}
fmt.Println(i18n.T(loc, "runtime.activated", args[1]))
return nil
case "remove", "rm", "delete":
if len(args) < 2 {
return fmt.Errorf("usage: reims-go runtime remove <commit>")
}
inst, err := rt.Remove(cfg, args[1])
if err != nil {
switch {
case errors.Is(err, rt.ErrNotFound):
return fmt.Errorf("%s", i18n.T(loc, "runtime.not_found", args[1]))
case errors.Is(err, rt.ErrRemoveActive):
return fmt.Errorf("%s", i18n.T(loc, "runtime.remove_active", args[1]))
case errors.Is(err, rt.ErrRuntimeInUse):
return fmt.Errorf("%s", i18n.T(loc, "runtime.remove_in_use", args[1]))
default:
return err
}
}
fmt.Println(i18n.T(loc, "runtime.removed", inst.Commit, inst.Dir))
return nil
case "available":
return cmdRuntimeAvailable(cfg, loc, args[1:])
case "fetch":
return cmdRuntimeFetch(cfg, loc, args[1:])
default:
return fmt.Errorf("unknown runtime subcommand %q", args[0])
}
}
func cmdVM(cfg *config.Config, loc i18n.Locale, args []string, viaWindow bool) error {
if len(args) == 0 {
return fmt.Errorf("usage: reims-go vm <list|create|set|start|stop|suspend|resume|discard-suspend|delete|eject|type|resize|compact|provision|autoinstall>")
}
ctx := context.Background()
switch args[0] {
case "provision":
return cmdVMMacOSProvision(ctx, cfg, loc, args[1:])
case "autoinstall":
return cmdVMAutoInstall(cfg, loc, args[1:])
case "list":
svc, closeService, err := openCLILifecycle(cfg)
if err != nil {
return err
}
defer closeService()
vms, err := svc.List(ctx)
if len(vms) == 0 {
if err != nil {
return err
}
fmt.Println(i18n.T(loc, "vm.empty"))
return nil
}
return errors.Join(printJSON(vms), err)
case "create":
return vmCreate(ctx, cfg, loc, args[1:], viaWindow)
case "set":
return vmSet(ctx, cfg, args[1:])
case "start":
driverID, name, err := parseVMTarget(args)
if err != nil {
return err
}
return startVM(ctx, cfg, driverID, name, viaWindow)
case "stop":
fs := flag.NewFlagSet("vm stop", flag.ContinueOnError)
driverID := fs.String("driver", "", "Owning driver ID when VM names are ambiguous")
force := fs.Bool("force", false, "Force power off if the guest cannot shut down normally")
if err := fs.Parse(args[1:]); err != nil {
return err
}
if fs.NArg() != 1 {
return fmt.Errorf("usage: reims-go vm stop [--driver <id>] [--force] <name>")
}
return stopVM(ctx, cfg, *driverID, fs.Arg(0), *force)
case "suspend":
driverID, name, err := parseVMTarget(args)
if err != nil {
return err
}
return suspendVM(ctx, cfg, driverID, name)
case "resume":
driverID, name, err := parseVMTarget(args)
if err != nil {
return err
}
return resumeVM(ctx, cfg, driverID, name, viaWindow)
case "discard-suspend":
driverID, name, err := parseVMTarget(args)
if err != nil {
return err
}
return discardSuspendVM(ctx, cfg, driverID, name)
case "delete":
fs := flag.NewFlagSet("vm delete", flag.ContinueOnError)
driverID := fs.String("driver", "", "Owning driver ID when VM names are ambiguous")
keepFiles := fs.Bool("keep-files", false, "Delete registration but keep VM files")
if err := fs.Parse(args[1:]); err != nil {
return err
}
if fs.NArg() < 1 {
return fmt.Errorf("usage: reims-go vm delete [--driver <id>] [--keep-files] <name>")
}
return deleteVM(ctx, cfg, *driverID, fs.Arg(0), *keepFiles)
case "eject":
driverID, name, err := parseVMTarget(args)
if err != nil {
return err
}
return actionVM(ctx, cfg, driverID, name, "eject", nil)
case "type":
return typeMacOSVM(ctx, cfg, loc, args)
case "resize":
fs := flag.NewFlagSet("vm resize", flag.ContinueOnError)
driverID := fs.String("driver", "", "Owning driver ID when VM names are ambiguous")
if err := fs.Parse(args[1:]); err != nil {
return err
}
if fs.NArg() < 2 {
return fmt.Errorf("usage: reims-go vm resize [--driver <id>] <name> <size> (e.g. 256G or +64G)")
}
res, err := resizeVM(ctx, cfg, *driverID, fs.Arg(0), fs.Arg(1))
if err != nil {
return err
}
fmt.Println(i18n.T(loc, "vm.resize.done", fs.Arg(0), float64(res.OldVirtualBytes)/float64(1<<30), float64(res.NewVirtualBytes)/float64(1<<30), res.GuestExpandCmd))
return nil
case "compact":
driverID, name, err := parseVMTarget(args)
if err != nil {
return err
}
res, err := compactVM(ctx, cfg, driverID, name)
if err != nil {
return err
}
fmt.Println(i18n.T(loc, "vm.compact.done", name, float64(res.BeforeBytes)/float64(1<<30), float64(res.AfterBytes)/float64(1<<30), float64(res.ReclaimedBytes)/float64(1<<30)))
return nil
default:
return fmt.Errorf("unknown vm subcommand %q", strings.Join(args, " "))
}
}
// parseVMTarget parses "<subcommand> [--driver <id>] <name>".
func parseVMTarget(args []string) (driverID, name string, err error) {
fs := flag.NewFlagSet("vm "+args[0], flag.ContinueOnError)
fs.StringVar(&driverID, "driver", "", "Owning driver ID when VM names are ambiguous")
if err := fs.Parse(args[1:]); err != nil {
return "", "", err
}
if fs.NArg() < 1 {
return "", "", fmt.Errorf("usage: reims-go vm %s [--driver <id>] <name>", args[0])
}
return driverID, fs.Arg(0), nil
}
func vmCreate(ctx context.Context, cfg *config.Config, loc i18n.Locale, args []string, viaWindow bool) error {
fs := flag.NewFlagSet("vm create", flag.ContinueOnError)
driverID := fs.String("driver", defaultCreateDriver(), "Guest VM driver ID")
ipsw := fs.String("ipsw", "", "Local Apple macOS restore image (Apple Virtualization only)")
dir := fs.String("dir", "", "Custom VM directory")
macos := fs.String("macos", "tahoe", "macOS version (e.g. tahoe)")
cpus := fs.Int("cpus", 8, "vCPU count")
mem := fs.String("memory", "16G", "RAM size (e.g. 8G, 16G)")
diskSize := fs.String("disk-size", "128G", "New disk size (e.g. 128G)")
disk := fs.String("disk", "", "Existing disk image or Windows raw partition path")
diskMode := fs.String("disk-mode", "", "Existing disk attach mode (copy, in-place)")
diskCache := fs.String("disk-cache", "", "Disk I/O cache mode (default, writeback, none, unsafe)")
gpu := fs.String("gpu", "auto", "GPU selector or Vulkan ICD JSON path")
capture := fs.Bool("capture", false, "Capture keyboard and mouse on window click")
logs := fs.Bool("logs", true, "Keep graphics and serial logs")
guestLang := fs.String("guest-lang", defaultMacOSGuestLang(loc), "macOS boot/recovery language prev-lang:kbd (e.g. zh-Hans:0, en-US:0)")
start := fs.Bool("start", false, "Start VM immediately after creation")
if err := fs.Parse(args); err != nil {
return err
}
if fs.NArg() < 1 {
return fmt.Errorf("usage: reims-go vm create [flags] <name>")
}
name := fs.Arg(0)
if *ipsw != "" && !isAppleCreateDriver(*driverID) {
return fmt.Errorf("--ipsw is only supported by the Apple Virtualization driver")
}
if isAppleCreateDriver(*driverID) {
return createAppleVM(ctx, cfg, *driverID, name, *dir, *ipsw, *cpus, *mem, *diskSize, *start, fs)
}
// Route non-reims guest drivers through the plugin Driver Router (§5.3, §10).
if strings.TrimSpace(*driverID) != "" && *driverID != driver.BuiltinReimsMacOSDriverID {
mgr, router, err := openCLIPluginManager(cfg, false)
if err != nil {
return err
}
defer mgr.Close()
drv, err := router.DriverByID(*driverID)
if err != nil {
return err
}
if strings.TrimSpace(*disk) != "" || strings.TrimSpace(*diskMode) != "" || strings.TrimSpace(*diskCache) != "" {
return fmt.Errorf("--disk, --disk-mode, and --disk-cache are only supported by the %s driver", driver.BuiltinReimsMacOSDriverID)
}
req := driver.CreateRequest{
DriverID: drv.ID(),
Name: name,
Dir: *dir,
Options: map[string]any{
"cpus": *cpus,
"memory": *mem,
"disk_size": *diskSize,
},
}
if issues := drv.ValidateCreate(ctx, req); len(issues) > 0 {
return fmt.Errorf("%s", issues[0].Message)
}
if err := drv.Create(ctx, req, os.Stdout, os.Stderr); err != nil {
return err
}
if *start {
svc := lifecycle.New(mgr.Registry(), router, nil)
_, err := svc.Start(ctx, driver.NewVMRef(drv.ID(), name), os.Stdout, os.Stderr)
return err
}
return nil
}
return createMacOSVM(ctx, cfg, loc, macOSCreateOptions{Name: name, Dir: *dir, MacOS: *macos, CPUs: *cpus, Memory: *mem, DiskSize: *diskSize, Disk: *disk, DiskMode: *diskMode, DiskCache: *diskCache, GPU: *gpu, Capture: *capture, Logs: *logs, GuestLang: *guestLang}, *start, viaWindow)
}
func vmSet(ctx context.Context, cfg *config.Config, args []string) error {
fs := flag.NewFlagSet("vm set", flag.ContinueOnError)
driverID := fs.String("driver", "", "Owning driver ID when VM names are ambiguous")
cpus := fs.Int("cpus", 0, "vCPU count")
mem := fs.String("memory", "", "RAM size")
diskCache := fs.String("disk-cache", "", "Disk I/O cache mode (default, writeback, none, unsafe)")
gpu := fs.String("gpu", "", "GPU selector or Vulkan ICD JSON")
res := fs.String("resolution", "", "Window resolution WIDTHxHEIGHT")
audioBackend := fs.String("audio-backend", "", "Audio backend (auto, dsound, none, wav)")
guestLang := fs.String("guest-lang", "", "macOS boot/recovery language prev-lang:kbd")
nestedVirt := fs.Bool("nested-virt", false, "Enable nested virtualization on the next cold start (macOS only)")
if err := fs.Parse(args); err != nil {
return err
}
if fs.NArg() < 1 {
return fmt.Errorf("usage: reims-go vm set [--driver <id>] [flags] <name>")
}
changes := map[string]any{}
if *cpus != 0 {
changes["cpus"] = *cpus
}
if *mem != "" {
changes["memory"] = *mem
}
if *diskCache != "" {
changes["disk_cache"] = *diskCache
}
if *gpu != "" {
changes["gpu"] = *gpu
}
if *res != "" {
changes["resolution"] = *res
}
if *audioBackend != "" {
changes["audio_backend"] = *audioBackend
}
if *guestLang != "" {
changes["guest_lang"] = *guestLang
}
fs.Visit(func(f *flag.Flag) {
if f.Name == "nested-virt" {
changes["nested_virt"] = *nestedVirt
}
})
return setVM(ctx, cfg, *driverID, fs.Arg(0), changes)
}
func printJSON(v any) error {
enc := json.NewEncoder(os.Stdout)
enc.SetIndent("", " ")
return enc.Encode(v)
}
// readOnlySafeCommand reports whether cmd runs without writing to the data
// folder, so it may run while the folder is open read-only.
func cmdHost(cfg *config.Config, args []string) error {
if len(args) == 0 || args[0] != "raw-disks" {
return fmt.Errorf("usage: reims-go host raw-disks [--json]")
}
fs := flag.NewFlagSet("host raw-disks", flag.ContinueOnError)
asJSON := fs.Bool("json", false, "Output JSON")
if err := fs.Parse(args[1:]); err != nil {
return err
}
list, err := host.ListRawPartitions(cfg.DataRoot)
if err != nil {
return err
}
if *asJSON {
return printJSON(list)
}
if len(list) == 0 {
fmt.Println("No eligible unmounted raw partitions or offline disks found.")
return nil
}
for _, c := range list {
apfs := ""
if c.IsAPFS {
apfs = " [APFS]"
}
fmt.Printf("%-46s %7.1f GiB disk=%d part=%d%s\n", c.DevicePath, float64(c.SizeBytes)/float64(1<<30), c.DiskNumber, c.PartitionNumber, apfs)
}
return nil
}
func readOnlySafeCommand(cmd string) bool {
switch cmd {
case "version", "-v", "--version", "help", "-h", "--help", "doctor", "host":
return true
}
return false
}