From 7f2bef4bd860f5398263b2f0052f6dc9462c917e Mon Sep 17 00:00:00 2001 From: xiaquwan1001 Date: Mon, 9 Nov 2026 22:50:21 +0800 Subject: [PATCH 1/2] Add headless CLI and stdio MCP entry points The 14 service classes were already Avalonia-free, so the orchestration is reused as-is instead of being copied: - Cli/: command registry, arg parser, exit codes (0/1/2/3/4/5), read-only commands info/doctor/getvar/extract/dump, and gated write commands flash-ota/flash-xml/vcom-unlock/oeminfo/downgrade-enable that print their plan and exit 4 without ever touching a device. - KirinTool.Cli/: thin console project referencing the main project so the command implementations exist only once. - --mcp / mcp subcommand: newline-delimited JSON-RPC 2.0 over stdio with tools/list and tools/call; write tools require confirm:true and still only return the plan. All diagnostics go to stderr so stdout stays protocol-clean. - Program.cs routes --mcp before Avalonia starts, so the MCP server never initializes a GUI. --- Cli/ArgParser.cs | 96 +++++ Cli/BinaryLocator.cs | 90 +++++ Cli/CliContext.cs | 39 +++ Cli/CliRunner.cs | 128 +++++++ Cli/CommandSupport.cs | 275 +++++++++++++++ Cli/Commands/ICliCommand.cs | 20 ++ Cli/Commands/ReadCommands.cs | 542 +++++++++++++++++++++++++++++ Cli/Commands/WriteCommands.cs | 400 +++++++++++++++++++++ Cli/ExitCodes.cs | 12 + Cli/Mcp/McpServer.cs | 312 +++++++++++++++++ Kirin-Tool.csproj | 6 + Kirin-Tool.sln | 28 +- KirinTool.Cli/KirinTool.Cli.csproj | 25 ++ KirinTool.Cli/Program.cs | 3 + Program.cs | 14 +- docs/cli-mcp.md | 48 +++ 16 files changed, 2035 insertions(+), 3 deletions(-) create mode 100644 Cli/ArgParser.cs create mode 100644 Cli/BinaryLocator.cs create mode 100644 Cli/CliContext.cs create mode 100644 Cli/CliRunner.cs create mode 100644 Cli/CommandSupport.cs create mode 100644 Cli/Commands/ICliCommand.cs create mode 100644 Cli/Commands/ReadCommands.cs create mode 100644 Cli/Commands/WriteCommands.cs create mode 100644 Cli/ExitCodes.cs create mode 100644 Cli/Mcp/McpServer.cs create mode 100644 KirinTool.Cli/KirinTool.Cli.csproj create mode 100644 KirinTool.Cli/Program.cs create mode 100644 docs/cli-mcp.md diff --git a/Cli/ArgParser.cs b/Cli/ArgParser.cs new file mode 100644 index 0000000..c7301cf --- /dev/null +++ b/Cli/ArgParser.cs @@ -0,0 +1,96 @@ +namespace Kirin_Tool.Cli; + +internal sealed class CliUsageException : Exception +{ + public CliUsageException(string message) : base(message) { } +} + +/// One documented command parameter (also feeds the MCP input schema). +internal sealed record CliParam( + string Name, + string Type, + string Description, + bool Required = false, + bool Positional = false, + IReadOnlyList? Enum = null, + string? Default = null); + +internal sealed class ParsedArgs +{ + private readonly Dictionary _values = new(StringComparer.OrdinalIgnoreCase); + private readonly HashSet _flags = new(StringComparer.OrdinalIgnoreCase); + + public List Positionals { get; } = new(); + + public IReadOnlyDictionary Values => _values; + public bool HasFlag(string name) => _flags.Contains(name); + public bool HasValue(string name) => _values.ContainsKey(name); + public string? Value(string name) => _values.TryGetValue(name, out string? value) ? value : null; + public void SetFlag(string name) => _flags.Add(name); + public void SetValue(string name, string value) => _values[name] = value; +} + +internal static class ArgParser +{ + /// + /// Minimal, predictable parser: --name value, --name=value, short aliases + /// (-o output, -y yes, -j json, -h help) and bare positionals. Unknown options are flags. + /// + public static ParsedArgs Parse(IReadOnlyList args, IEnumerable valueOptions) + { + var parsed = new ParsedArgs(); + var values = new HashSet(valueOptions, StringComparer.OrdinalIgnoreCase); + + for (int i = 0; i < args.Count; i++) + { + string token = args[i]; + if (token == "--") + { + for (int j = i + 1; j < args.Count; j++) parsed.Positionals.Add(args[j]); + break; + } + + if (token.Length > 1 && token[0] == '-') + { + string name = token.StartsWith("--", StringComparison.Ordinal) ? token[2..] : token[1..]; + string? inline = null; + int equals = name.IndexOf('='); + if (equals >= 0) + { + inline = name[(equals + 1)..]; + name = name[..equals]; + } + + name = name.ToLowerInvariant() switch + { + "o" => "output", + "y" => "yes", + "j" => "json", + "h" => "help", + _ => name, + }; + + if (inline != null) + { + parsed.SetValue(name, inline); + continue; + } + + if (!values.Contains(name)) + { + parsed.SetFlag(name); + continue; + } + + if (i + 1 >= args.Count) + throw new CliUsageException($"option --{name} requires a value"); + parsed.SetValue(name, args[++i]); + continue; + } + + parsed.Positionals.Add(token); + } + + return parsed; + } +} diff --git a/Cli/BinaryLocator.cs b/Cli/BinaryLocator.cs new file mode 100644 index 0000000..0ab1bd6 --- /dev/null +++ b/Cli/BinaryLocator.cs @@ -0,0 +1,90 @@ +namespace Kirin_Tool.Cli; + +/// +/// Resolves fastboot/adb without touching the GUI's helpers: explicit env override, +/// the app-local bundled layout, then PATH. Never downloads anything. +/// +internal static class BinaryLocator +{ + public const string FastbootOverrideVariable = "KIRIN_FASTBOOT"; + public const string AdbOverrideVariable = "KIRIN_ADB"; + + public static string? FindFastboot() => Find(FastbootOverrideVariable, "fastboot"); + + public static string? FindAdb() => Find(AdbOverrideVariable, "adb"); + + private static string? Find(string overrideVariable, string name) + { + var overrideValue = Environment.GetEnvironmentVariable(overrideVariable); + if (!string.IsNullOrWhiteSpace(overrideValue)) + { + string expanded = Environment.ExpandEnvironmentVariables(overrideValue.Trim()); + if (File.Exists(expanded)) return Path.GetFullPath(expanded); + string? located = FindOnPath(expanded); + if (located != null) return located; + } + + string executable = OperatingSystem.IsWindows() ? name + ".exe" : name; + foreach (string candidate in Candidates(name, executable)) + { + if (File.Exists(candidate) && IsExecutable(candidate)) return Path.GetFullPath(candidate); + } + + return FindOnPath(executable); + } + + private static IEnumerable Candidates(string name, string executable) + { + yield return Path.Combine(AppContext.BaseDirectory, executable); + yield return Path.Combine(AppContext.BaseDirectory, name, executable); + yield return Path.Combine(AppContext.BaseDirectory, "tools", executable); + // Side-by-side build output: /KirinTool.Cli/bin/... vs /bin/... + yield return Path.GetFullPath(Path.Combine(AppContext.BaseDirectory, "..", "..", "..", "..", "..", executable)); + yield return Path.GetFullPath(Path.Combine(AppContext.BaseDirectory, "..", "Kirin-Tool", executable)); + if (!OperatingSystem.IsWindows()) + { + yield return "/usr/bin/" + executable; + yield return "/usr/local/bin/" + executable; + } + } + + public static string? FindOnPath(string executable) + { + if (string.IsNullOrWhiteSpace(executable)) return null; + if (executable.Contains(Path.DirectorySeparatorChar) || executable.Contains('/')) + return File.Exists(executable) && IsExecutable(executable) ? Path.GetFullPath(executable) : null; + + string? path = Environment.GetEnvironmentVariable("PATH"); + if (string.IsNullOrEmpty(path)) return null; + + foreach (string directory in path.Split(Path.PathSeparator, StringSplitOptions.RemoveEmptyEntries)) + { + string candidate; + try + { + candidate = Path.Combine(directory, executable); + } + catch (ArgumentException) + { + continue; + } + if (File.Exists(candidate) && IsExecutable(candidate)) return Path.GetFullPath(candidate); + } + + return null; + } + + private static bool IsExecutable(string path) + { + if (OperatingSystem.IsWindows()) return true; + try + { + var mode = File.GetUnixFileMode(path); + return (mode & (UnixFileMode.UserExecute | UnixFileMode.GroupExecute | UnixFileMode.OtherExecute)) != 0; + } + catch (Exception) + { + return false; + } + } +} diff --git a/Cli/CliContext.cs b/Cli/CliContext.cs new file mode 100644 index 0000000..16301b3 --- /dev/null +++ b/Cli/CliContext.cs @@ -0,0 +1,39 @@ +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace Kirin_Tool.Cli; + +/// +/// Everything a command may touch. Console access is injected so the same +/// command implementation can serve the CLI (stdout) and the MCP server +/// (JSON-RPC response text) without ever polluting stdout in MCP mode. +/// +internal sealed class CliContext +{ + public static readonly JsonSerializerOptions JsonOptions = new() + { + WriteIndented = true, + DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, + Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping, + }; + + public CliContext(TextWriter output, TextWriter error, bool json, bool yes, string workingDirectory) + { + Output = output; + Error = error; + Json = json; + Yes = yes; + WorkingDirectory = workingDirectory; + } + + public TextWriter Output { get; } + public TextWriter Error { get; } + public bool Json { get; } + public bool Yes { get; } + public string WorkingDirectory { get; } + + public void WriteJson(object value) => Output.WriteLine(JsonSerializer.Serialize(value, JsonOptions)); + + /// Humans-only progress/diagnostics: always stderr. + public void Diag(string message) => Error.WriteLine(message); +} diff --git a/Cli/CliRunner.cs b/Cli/CliRunner.cs new file mode 100644 index 0000000..066dbb3 --- /dev/null +++ b/Cli/CliRunner.cs @@ -0,0 +1,128 @@ +using System.Text; +using Kirin_Tool.Cli.Commands; +using Kirin_Tool.Cli.Mcp; + +namespace Kirin_Tool.Cli; + +/// Headless entry point shared by the KirinTool.Cli executable and the main exe's --mcp switch. +public static class CliRunner +{ + internal static IReadOnlyList Commands { get; } = new ICliCommand[] + { + new InfoCommand(), + new DoctorCommand(), + new GetVarCommand(), + new ExtractCommand(), + new DumpCommand(), + new FlashOtaCommand(), + new FlashXmlCommand(), + new VcomUnlockCommand(), + new OemInfoCommand(), + new DowngradeEnableCommand(), + }; + + public static async Task RunAsync(string[] args, TextWriter? stdout = null, TextWriter? stderr = null) + { + TextWriter output = stdout ?? Console.Out; + TextWriter error = stderr ?? Console.Error; + + try + { + if (args.Length == 0) + { + WriteUsage(error); + return ExitCodes.Usage; + } + + string first = args[0]; + string normalized = first.TrimStart('-').ToLowerInvariant(); + + if (normalized is "help" or "h") + { + WriteUsage(output); + return ExitCodes.Ok; + } + + if (normalized == "version") + { + output.WriteLine($"{ToolInfo.Name} {ToolInfo.Version} ({ToolInfo.Framework})"); + return ExitCodes.Ok; + } + + if (normalized == "mcp") + return await McpEntry.RunAsync(); + + ICliCommand? command = Commands.FirstOrDefault(candidate => candidate.Name == normalized); + if (command == null) + { + error.WriteLine($"error: unknown command '{first}'"); + WriteUsage(error); + return ExitCodes.Usage; + } + + ParsedArgs parsed = ArgParser.Parse(args.Skip(1).ToArray(), ValueOptions(command)); + if (parsed.HasFlag("help")) + { + output.WriteLine(command.Usage); + return ExitCodes.Ok; + } + + var context = new CliContext( + output, + error, + parsed.HasFlag("json"), + parsed.HasFlag("yes"), + Directory.GetCurrentDirectory()); + + return await command.ExecuteAsync(parsed, context, CancellationToken.None); + } + catch (CliUsageException ex) + { + error.WriteLine($"error: {ex.Message}"); + return ExitCodes.Usage; + } + catch (OperationCanceledException) + { + error.WriteLine("error: cancelled"); + return ExitCodes.FileOrVerify; + } + catch (Exception ex) + { + error.WriteLine($"error: {ex.Message}"); + return ExitCodes.FileOrVerify; + } + } + + private static string[] ValueOptions(ICliCommand command) => + command.Params + .Where(parameter => !parameter.Positional && parameter.Type != "boolean") + .Select(parameter => parameter.Name) + .ToArray(); + + private static void WriteUsage(TextWriter writer) + { + var builder = new StringBuilder(); + builder.AppendLine($"{ToolInfo.Name} {ToolInfo.Version} - headless Kirin-Tool (read-only first, write commands are gated)"); + builder.AppendLine(); + builder.AppendLine("usage: kirintool [options]"); + builder.AppendLine(); + foreach (ICliCommand command in Commands) + { + builder.AppendLine($" {command.Name,-16} {command.Summary}"); + } + builder.AppendLine(); + builder.AppendLine(" mcp Run the MCP stdio JSON-RPC server (tools/list, tools/call)"); + builder.AppendLine(); + builder.AppendLine("global options: --json (structured output), --yes (acknowledge a write plan), -h/--help"); + builder.AppendLine("diagnostics always go to stderr."); + builder.AppendLine("exit codes: 0 ok, 1 usage, 2 no device, 3 device rejected, 4 gate refused, 5 file/verify failed"); + writer.Write(builder.ToString()); + } +} + +/// Public entry so the Avalonia exe can answer --mcp without starting the GUI. +public static class McpEntry +{ + public static Task RunAsync(CancellationToken cancellationToken = default) => + McpServer.RunAsync(Console.In, Console.Out, Console.Error, cancellationToken); +} diff --git a/Cli/CommandSupport.cs b/Cli/CommandSupport.cs new file mode 100644 index 0000000..c7bdc72 --- /dev/null +++ b/Cli/CommandSupport.cs @@ -0,0 +1,275 @@ +using System.Reflection; +using System.Text; +using Kirin_Tool.Models; +using Kirin_Tool.Services; +using Kirin_Tool.Utils; + +namespace Kirin_Tool.Cli; + +internal static class ToolInfo +{ + public const string Name = "KirinTool.Cli"; + + public static string Version => + typeof(FastbootClient).Assembly.GetCustomAttribute()?.InformationalVersion + ?? typeof(FastbootClient).Assembly.GetName().Version?.ToString() + ?? "unknown"; + + public static string Framework => System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription; +} + +internal sealed class FastbootSession +{ + private FastbootSession(string executablePath, FastbootClient client, bool connected) + { + ExecutablePath = executablePath; + Client = client; + Connected = connected; + } + + public string ExecutablePath { get; } + public FastbootClient Client { get; } + public bool Connected { get; } + + /// Null means no fastboot binary was found at all. + public static async Task TryOpenAsync() + { + string? path = BinaryLocator.FindFastboot(); + if (path == null) return null; + + var client = new FastbootClient(path); + bool connected; + try + { + connected = await client.IsDeviceConnected(); + } + catch (Exception) + { + connected = false; + } + return new FastbootSession(path, client, connected); + } +} + +internal static class DeviceVars +{ + /// Read-only getvar probe; never throws, returns null when unsupported. + public static async Task TryReadAsync(FastbootClient client, string variable) + { + try + { + ProcessResult result = await client.QueryVariableAsync(variable); + string output = result.Output ?? string.Empty; + if (!result.IsSuccess) return null; + if (output.Contains("FAILED", StringComparison.OrdinalIgnoreCase)) return null; + if (output.Contains("invalid command", StringComparison.OrdinalIgnoreCase)) return null; + if (output.Contains("not allowed", StringComparison.OrdinalIgnoreCase)) return null; + + try + { + return FastbootReadResponses.Variable(result, variable); + } + catch (InvalidOperationException) + { + // Some bootloaders print the value without the "name:" prefix. + string? line = output.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries) + .Select(l => l.Trim()) + .FirstOrDefault(l => l.Length > 0 && + !l.StartsWith("(bootloader)", StringComparison.OrdinalIgnoreCase) && + !l.StartsWith("OKAY", StringComparison.OrdinalIgnoreCase) && + !l.StartsWith("INFO", StringComparison.OrdinalIgnoreCase) && + !l.StartsWith("Finished", StringComparison.OrdinalIgnoreCase)); + return line; + } + } + catch (TimeoutException) + { + return null; + } + catch (Exception) + { + return null; + } + } + + public static async Task PsidReadableAsync(FastbootClient client) + { + try + { + await client.ReadPsidAsync(); + return true; + } + catch (Exception) + { + return false; + } + } + + public static async Task PartitionCountAsync(FastbootClient client) + { + try + { + ProcessResult result = await client.QueryVariableAsync("ptable"); + return FastbootReadResponses.Partitions(result).Count; + } + catch (Exception) + { + return null; + } + } +} + +internal static class DeviceOutcome +{ + private static readonly string[] RejectionMarkers = + { + "FAILED", "INVALID COMMAND", "NOT ALLOWED", "DENIED", "UNLOCK", "LOCKED", "UNKNOWN COMMAND", "NOT SUPPORTED", + }; + + public static bool LooksRejected(string? output) + { + if (string.IsNullOrEmpty(output)) return false; + string upper = output.ToUpperInvariant(); + return RejectionMarkers.Any(marker => upper.Contains(marker, StringComparison.Ordinal)); + } + + /// 3 = the device itself refused the command, 5 = local/file failure. + public static int FailureExit(string? output) => + LooksRejected(output) ? ExitCodes.DeviceRejected : ExitCodes.FileOrVerify; +} + +internal static class ToolProbe +{ + public static async Task VersionAsync(string executablePath) + { + try + { + ProcessResult result = await ProcessRunner.RunAsync(executablePath, new[] { "--version" }, timeoutSeconds: 5); + string text = (result.Output ?? string.Empty).Trim(); + if (text.Length == 0) return result.IsSuccess ? "unknown" : null; + return text.Split(new[] { '\r', '\n' })[0].Trim(); + } + catch (Exception) + { + return null; + } + } + + public static async Task> FastbootDevicesAsync(string executablePath) + { + try + { + ProcessResult result = await ProcessRunner.RunAsync(executablePath, new[] { "devices" }, timeoutSeconds: 10); + return result.Output + .Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries) + .Select(line => line.Trim()) + .Where(line => line.Length > 0) + .ToList(); + } + catch (Exception) + { + return Array.Empty(); + } + } + + public static async Task> AdbDevicesAsync(string executablePath) + { + try + { + ProcessResult result = await ProcessRunner.RunAsync(executablePath, new[] { "devices", "-l" }, timeoutSeconds: 10); + return result.Output + .Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries) + .Select(line => line.TrimEnd()) + .Where(line => line.Length > 0 && + !line.StartsWith("List of devices", StringComparison.OrdinalIgnoreCase) && + !line.StartsWith("* daemon", StringComparison.OrdinalIgnoreCase)) + .ToList(); + } + catch (Exception) + { + return Array.Empty(); + } + } +} + +/// Bundled VCOM loader inventory (read-only inspection of loaders/). +internal static class BundledLoaders +{ + public static string Directory => Path.Combine(AppContext.BaseDirectory, "loaders"); + + public static IReadOnlyList<(string Chip, int Files)> Inventory() + { + if (!System.IO.Directory.Exists(Directory)) return Array.Empty<(string, int)>(); + try + { + return System.IO.Directory.GetDirectories(Directory) + .OrderBy(path => path, StringComparer.Ordinal) + .Select(path => (Path.GetFileName(path), System.IO.Directory.GetFiles(path, "*.ktl").Length)) + .ToList(); + } + catch (Exception) + { + return Array.Empty<(string, int)>(); + } + } + + public static IReadOnlyList<(string Stage, string File, int Address, bool PwnFlag, bool Exists)> Plan(string chip, bool useFastFlashLoader = false) + { + if (!FirmwareUnlocker.CpuAddresses.TryGetValue(chip, out var stages)) return Array.Empty<(string, string, int, bool, bool)>(); + + string chipDirectory = Path.Combine(Directory, chip); + return stages.Select(stage => + { + string file = useFastFlashLoader && stage.Name == "FASTBOOT" + ? "fastbootf.ktl" + : stage.Name.ToLowerInvariant() + ".ktl"; + bool exists = File.Exists(Path.Combine(chipDirectory, file)); + return (stage.Name, file, stage.Address, stage.PwnFlag, exists); + }).ToList(); + } + + public static IReadOnlyList SupportedChips() => + FirmwareUnlocker.CpuAddresses.Keys.OrderBy(k => k, StringComparer.Ordinal).ToList(); +} + +internal static class TextFormat +{ + public static string Bytes(long bytes) + { + if (bytes <= 0) return "0 B"; + string[] units = { "B", "KB", "MB", "GB", "TB" }; + double size = bytes; + int unit = 0; + while (size >= 1024 && unit < units.Length - 1) + { + size /= 1024; + unit++; + } + return string.Create(System.Globalization.CultureInfo.InvariantCulture, $"{size:F1} {units[unit]}"); + } + + public static string Table(IReadOnlyList rows, params string[] headers) + { + var all = new List { headers }; + all.AddRange(rows); + int[] widths = new int[headers.Length]; + foreach (string[] row in all) + { + for (int i = 0; i < widths.Length && i < row.Length; i++) + widths[i] = Math.Max(widths[i], (row[i] ?? string.Empty).Length); + } + + var builder = new StringBuilder(); + foreach (string[] row in all) + { + for (int i = 0; i < widths.Length; i++) + { + string cell = i < row.Length ? row[i] ?? string.Empty : string.Empty; + builder.Append(cell.PadRight(widths[i])); + if (i < widths.Length - 1) builder.Append(" "); + } + builder.AppendLine(); + } + return builder.ToString().TrimEnd(); + } +} diff --git a/Cli/Commands/ICliCommand.cs b/Cli/Commands/ICliCommand.cs new file mode 100644 index 0000000..9a663f3 --- /dev/null +++ b/Cli/Commands/ICliCommand.cs @@ -0,0 +1,20 @@ +namespace Kirin_Tool.Cli.Commands; + +/// Local file/parse failure mapped to exit code 5. +internal sealed class CliFileException : Exception +{ + public CliFileException(string message) : base(message) { } +} + +internal interface ICliCommand +{ + string Name { get; } + string McpName { get; } + string Summary { get; } + string Usage { get; } + bool IsWrite { get; } + IReadOnlyList Params { get; } + Task ExecuteAsync(ParsedArgs args, CliContext context, CancellationToken cancellationToken); +} + +internal sealed record WritePlan(object Details, IReadOnlyList Lines); diff --git a/Cli/Commands/ReadCommands.cs b/Cli/Commands/ReadCommands.cs new file mode 100644 index 0000000..dce5ba5 --- /dev/null +++ b/Cli/Commands/ReadCommands.cs @@ -0,0 +1,542 @@ +using System.Diagnostics; +using Kirin_Tool.Models; +using Kirin_Tool.Services; + +namespace Kirin_Tool.Cli.Commands; + +internal sealed class InfoCommand : ICliCommand +{ + public string Name => "info"; + public string McpName => "info"; + public string Summary => "Show tool, fastboot and connected-device information (read-only)."; + public string Usage => "info [--json]"; + public bool IsWrite => false; + public IReadOnlyList Params => Array.Empty(); + + public async Task ExecuteAsync(ParsedArgs args, CliContext context, CancellationToken cancellationToken) + { + var session = await FastbootSession.TryOpenAsync(); + int exit = session == null ? ExitCodes.FileOrVerify + : session.Connected ? ExitCodes.Ok + : ExitCodes.NoDevice; + + var variables = new SortedDictionary(StringComparer.Ordinal); + bool psidReadable = false; + int? partitionCount = null; + + if (session is { Connected: true }) + { + foreach (string name in new[] { "product", "version", "serialno", "secure", "unlocked", "chipset", "base-version", "bootloader" }) + { + cancellationToken.ThrowIfCancellationRequested(); + variables[name] = await DeviceVars.TryReadAsync(session.Client, name); + } + psidReadable = await DeviceVars.PsidReadableAsync(session.Client); + partitionCount = await DeviceVars.PartitionCountAsync(session.Client); + } + + string chip = variables.TryGetValue("chipset", out string? chipValue) && !string.IsNullOrWhiteSpace(chipValue) + ? chipValue!.Trim().ToLowerInvariant() + : "unknown"; + + var rescue = RescuePartitionPlan.ForChip(chip) + .Select(entry => new { image = entry.Image, target = entry.Target }) + .ToList(); + + var payload = new + { + tool = new + { + name = ToolInfo.Name, + version = ToolInfo.Version, + framework = ToolInfo.Framework, + }, + fastboot = new + { + found = session != null, + path = session?.ExecutablePath, + }, + device = new + { + connected = session?.Connected ?? false, + chip, + psidReadable, + partitionCount, + variables = variables.Where(pair => pair.Value != null).ToDictionary(pair => pair.Key, pair => pair.Value!), + }, + capabilities = new + { + kirin9000 = string.Equals(chip, ChipCapabilities.Kirin9000, StringComparison.OrdinalIgnoreCase), + readOnly = ChipCapabilities.Allows(chip, "read-info"), + rescuePlan = rescue, + }, + }; + + if (context.Json) + { + context.WriteJson(payload); + } + else + { + context.Output.WriteLine($"{ToolInfo.Name} {ToolInfo.Version} ({ToolInfo.Framework})"); + context.Output.WriteLine(session == null + ? "fastboot: not found (set KIRIN_FASTBOOT or add fastboot to PATH)" + : $"fastboot: {session.ExecutablePath}"); + context.Output.WriteLine($"device: {(session?.Connected == true ? "connected" : "not connected")}"); + foreach (var pair in variables.Where(pair => pair.Value != null)) + context.Output.WriteLine($" {pair.Key}: {pair.Value}"); + if (session is { Connected: true }) + { + context.Output.WriteLine($" psid-readable: {psidReadable}"); + context.Output.WriteLine($" partition-count: {partitionCount?.ToString() ?? "unknown"}"); + } + context.Output.WriteLine($"capabilities (chip: {chip}): kirin9000={string.Equals(chip, ChipCapabilities.Kirin9000, StringComparison.OrdinalIgnoreCase)}"); + foreach (var entry in rescue) + context.Output.WriteLine($" rescue: {entry.image} -> {entry.target}"); + } + + if (session == null) + context.Diag("error: fastboot binary not found; set KIRIN_FASTBOOT or install platform-tools"); + else if (!session.Connected) + context.Diag("note: no fastboot device detected (exit 2)"); + + return exit; + } +} + +internal sealed class DoctorCommand : ICliCommand +{ + public string Name => "doctor"; + public string McpName => "doctor"; + public string Summary => "Diagnose toolchain: fastboot/adb paths, device enumeration and loader capability probes."; + public string Usage => "doctor [--json]"; + public bool IsWrite => false; + public IReadOnlyList Params => Array.Empty(); + + public async Task ExecuteAsync(ParsedArgs args, CliContext context, CancellationToken cancellationToken) + { + string? fastbootPath = BinaryLocator.FindFastboot(); + string? adbPath = BinaryLocator.FindAdb(); + + string? fastbootVersion = fastbootPath == null ? null : await ToolProbe.VersionAsync(fastbootPath); + string? adbVersion = adbPath == null ? null : await ToolProbe.VersionAsync(adbPath); + + var fastbootDevices = fastbootPath == null + ? Array.Empty() + : await ToolProbe.FastbootDevicesAsync(fastbootPath); + var adbDevices = adbPath == null + ? Array.Empty() + : await ToolProbe.AdbDevicesAsync(adbPath); + + var session = await FastbootSession.TryOpenAsync(); + bool connected = session?.Connected ?? false; + + var probes = new SortedDictionary(StringComparer.Ordinal); + bool psidReadable = false; + int? partitionCount = null; + if (connected && session != null) + { + foreach (string name in new[] { "product", "chipset", "secure", "unlocked", "version" }) + { + cancellationToken.ThrowIfCancellationRequested(); + probes[name] = await DeviceVars.TryReadAsync(session.Client, name); + } + psidReadable = await DeviceVars.PsidReadableAsync(session.Client); + partitionCount = await DeviceVars.PartitionCountAsync(session.Client); + } + + string chip = probes.TryGetValue("chipset", out string? chipValue) && !string.IsNullOrWhiteSpace(chipValue) + ? chipValue!.Trim().ToLowerInvariant() + : "unknown"; + + var loaders = BundledLoaders.Inventory(); + var checks = new List + { + new { name = "fastboot-found", ok = fastbootPath != null, detail = fastbootPath ?? "not found (KIRIN_FASTBOOT / PATH)" }, + new { name = "fastboot-runs", ok = fastbootVersion != null, detail = fastbootVersion ?? "fastboot --version failed" }, + new { name = "adb-found", ok = adbPath != null, detail = adbPath ?? "not found (optional, KIRIN_ADB / PATH)" }, + new { name = "loaders-bundled", ok = loaders.Count > 0, detail = $"{loaders.Count} chip directories under {BundledLoaders.Directory}" }, + new { name = "fastboot-device", ok = connected, detail = connected ? (probes.GetValueOrDefault("product") ?? "connected") : "no device in fastboot mode" }, + new { name = "psid-readable", ok = psidReadable, detail = psidReadable ? "oem get-psid answered" : "oem get-psid unavailable/rejected" }, + new { name = "ptable-readable", ok = partitionCount is > 0, detail = partitionCount is > 0 ? $"{partitionCount} partitions" : "getvar ptable unavailable" }, + }; + + var payload = new + { + tool = new { name = ToolInfo.Name, version = ToolInfo.Version, framework = ToolInfo.Framework, baseDirectory = AppContext.BaseDirectory }, + host = new + { + os = Environment.OSVersion.ToString(), + architecture = System.Runtime.InteropServices.RuntimeInformation.OSArchitecture.ToString(), + runtime = System.Runtime.InteropServices.RuntimeInformation.RuntimeIdentifier, + }, + fastboot = new { found = fastbootPath != null, path = fastbootPath, version = fastbootVersion, devices = fastbootDevices }, + adb = new { found = adbPath != null, path = adbPath, version = adbVersion, devices = adbDevices }, + loaders = new + { + directory = BundledLoaders.Directory, + exists = Directory.Exists(BundledLoaders.Directory), + chips = loaders.Select(entry => new { chip = entry.Chip, ktlFiles = entry.Files }).ToList(), + }, + device = new + { + connected, + chip, + probes = probes.Where(pair => pair.Value != null).ToDictionary(pair => pair.Key, pair => pair.Value!), + psidReadable, + partitionCount, + dumpCapable = connected && fastbootPath != null, + }, + checks, + ok = fastbootPath != null && fastbootVersion != null, + }; + + if (context.Json) + { + context.WriteJson(payload); + } + else + { + context.Output.WriteLine($"{ToolInfo.Name} {ToolInfo.Version} on {payload.host.os} ({payload.host.architecture})"); + context.Output.WriteLine($"fastboot: {fastbootPath ?? "NOT FOUND"} {(fastbootVersion != null ? "[" + fastbootVersion + "]" : string.Empty)}"); + context.Output.WriteLine($"adb: {adbPath ?? "not found (optional)"} {(adbVersion != null ? "[" + adbVersion + "]" : string.Empty)}"); + context.Output.WriteLine($"fastboot devices: {(fastbootDevices.Count == 0 ? "(none)" : string.Join(" | ", fastbootDevices))}"); + context.Output.WriteLine($"adb devices: {(adbDevices.Count == 0 ? "(none)" : string.Join(" | ", adbDevices))}"); + context.Output.WriteLine($"loaders: {loaders.Count} chips, {loaders.Sum(entry => entry.Files)} .ktl files in {BundledLoaders.Directory}"); + context.Output.WriteLine($"device: {(connected ? "connected" : "not connected")} chip={chip}"); + foreach (var pair in probes.Where(pair => pair.Value != null)) + context.Output.WriteLine($" {pair.Key}: {pair.Value}"); + if (connected) + { + context.Output.WriteLine($" psid-readable: {psidReadable}"); + context.Output.WriteLine($" partition-count: {partitionCount?.ToString() ?? "unknown"}"); + } + context.Output.WriteLine("checks:"); + foreach (var check in checks) + { + var type = check.GetType(); + bool ok = (bool)(type.GetProperty("ok")?.GetValue(check) ?? false); + string detail = (string?)(type.GetProperty("detail")?.GetValue(check) ?? string.Empty) ?? string.Empty; + string name = (string?)(type.GetProperty("name")?.GetValue(check) ?? string.Empty) ?? string.Empty; + context.Output.WriteLine($" [{(ok ? "ok" : "--")}] {name}: {detail}"); + } + } + + if (fastbootPath == null) + { + context.Diag("error: fastboot binary not found; set KIRIN_FASTBOOT or install platform-tools"); + return ExitCodes.FileOrVerify; + } + if (fastbootVersion == null) + { + context.Diag("error: fastboot is present but does not run; check the binary and its permissions"); + return ExitCodes.FileOrVerify; + } + return ExitCodes.Ok; + } +} + +internal sealed class GetVarCommand : ICliCommand +{ + public string Name => "getvar"; + public string McpName => "getvar"; + public string Summary => "Read a single fastboot variable (read-only)."; + public string Usage => "getvar [--json]"; + public bool IsWrite => false; + public IReadOnlyList Params => new[] + { + new CliParam("name", "string", "fastboot variable name, e.g. product, version, serialno, nve:...", Required: true, Positional: true), + }; + + public async Task ExecuteAsync(ParsedArgs args, CliContext context, CancellationToken cancellationToken) + { + if (args.Positionals.Count < 1) + throw new CliUsageException("getvar requires a variable name"); + string variable = args.Positionals[0]; + if (!IsSafeVariable(variable)) + throw new CliUsageException($"invalid variable name '{variable}'"); + + var session = await FastbootSession.TryOpenAsync(); + if (session == null) + { + context.Diag("error: fastboot binary not found; set KIRIN_FASTBOOT or install platform-tools"); + return ExitCodes.FileOrVerify; + } + if (!session.Connected) + { + context.Diag("error: no fastboot device detected"); + return ExitCodes.NoDevice; + } + + cancellationToken.ThrowIfCancellationRequested(); + ProcessResult result; + try + { + result = await session.Client.QueryVariableAsync(variable); + } + catch (TimeoutException) + { + context.Diag($"error: getvar {variable} timed out"); + return ExitCodes.DeviceRejected; + } + + string? value = null; + try + { + value = FastbootReadResponses.Variable(result, variable); + } + catch (InvalidOperationException) + { + value = null; + } + + if (value == null) + { + int exit = DeviceOutcome.FailureExit(result.Output); + if (exit == ExitCodes.DeviceRejected) + context.Diag($"error: device rejected getvar {variable}"); + else + context.Diag($"error: no unambiguous value for {variable}"); + if (context.Json) + { + context.WriteJson(new + { + variable, + value = (string?)null, + raw = result.Output, + exitCode = exit, + }); + } + return exit; + } + + if (context.Json) + { + context.WriteJson(new { variable, value, raw = result.Output }); + } + else + { + context.Output.WriteLine($"{variable}: {value}"); + } + return ExitCodes.Ok; + } + + private static bool IsSafeVariable(string variable) => + variable.Length is > 0 and <= 64 && + variable.All(c => char.IsAsciiLetterOrDigit(c) || c is '_' or '-' or ':' or '.'); +} + +internal sealed class ExtractCommand : ICliCommand +{ + public string Name => "extract"; + public string McpName => "extract"; + public string Summary => "List and extract partitions from an UPDATE.APP archive (read-only, no device)."; + public string Usage => "extract [outdir] [--json]"; + public bool IsWrite => false; + public IReadOnlyList Params => new[] + { + new CliParam("file", "string", "path to UPDATE.APP", Required: true, Positional: true), + new CliParam("outdir", "string", "output directory (default: ./-extracted)", Positional: true), + }; + + public async Task ExecuteAsync(ParsedArgs args, CliContext context, CancellationToken cancellationToken) + { + if (args.Positionals.Count < 1) throw new CliUsageException("extract requires an UPDATE.APP path"); + + string archivePath = Path.GetFullPath(args.Positionals[0], context.WorkingDirectory); + if (!File.Exists(archivePath)) + { + context.Diag($"error: file not found: {archivePath}"); + return ExitCodes.FileOrVerify; + } + + string outputDirectory = args.Positionals.Count > 1 + ? Path.GetFullPath(args.Positionals[1], context.WorkingDirectory) + : Path.Combine(context.WorkingDirectory, Path.GetFileNameWithoutExtension(archivePath) + "-extracted"); + + List entries; + try + { + entries = PartitionExtractor.Read(archivePath, cancellationToken); + } + catch (Exception ex) when (ex is InvalidDataException or InvalidOperationException or IOException or ArgumentException) + { + context.Diag($"error: cannot parse UPDATE.APP: {ex.Message}"); + return ExitCodes.FileOrVerify; + } + + foreach (ExtractionEntry entry in entries) entry.IsSelected = true; + + if (!context.Json) + { + context.Output.WriteLine($"archive: {archivePath}"); + context.Output.WriteLine($"output: {outputDirectory}"); + context.Output.WriteLine(TextFormat.Table( + entries.Select(entry => new[] { entry.Name, entry.Partition.FormattedSize, entry.FileName }).ToList(), + "PARTITION", "SIZE", "FILE")); + } + + var stopwatch = Stopwatch.StartNew(); + long lastReportedBytes = 0; + int lastIndex = -1; + int completed; + try + { + completed = await PartitionExtractor.ExtractAsync(archivePath, outputDirectory, entries, cancellationToken, progress => + { + if (progress.State is "Extracted" or "Failed" or "Cancelled") + { + context.Diag($"[{progress.Completed}/{progress.Total}] {progress.Name} {progress.State}"); + lastReportedBytes = progress.Bytes; + return; + } + + if (progress.Index != lastIndex) + { + lastIndex = progress.Index; + lastReportedBytes = progress.Bytes; + context.Diag($"[{progress.Completed}/{progress.Total}] {progress.Name} {progress.State} ({TextFormat.Bytes(progress.PartitionSize)})"); + return; + } + + if (progress.Bytes - lastReportedBytes >= 64L * 1024 * 1024) + { + lastReportedBytes = progress.Bytes; + context.Diag($"[{progress.Completed}/{progress.Total}] {progress.Name} {TextFormat.Bytes(progress.Bytes)}/{TextFormat.Bytes(progress.TotalBytes)}"); + } + }); + } + catch (OperationCanceledException) + { + context.Diag("error: extraction cancelled"); + return ExitCodes.FileOrVerify; + } + catch (Exception ex) when (ex is IOException or InvalidDataException or InvalidOperationException or UnauthorizedAccessException) + { + context.Diag($"error: extraction failed: {ex.Message}"); + return ExitCodes.FileOrVerify; + } + + stopwatch.Stop(); + long bytes = entries.Sum(entry => entry.Partition.Size); + var partitions = entries.Select(entry => new + { + name = entry.Name, + size = entry.Partition.Size, + formattedSize = entry.Partition.FormattedSize, + file = Path.Combine(outputDirectory, entry.FileName), + }).ToList(); + + if (context.Json) + { + context.WriteJson(new + { + archive = archivePath, + outputDirectory, + extracted = completed, + total = entries.Count, + bytes, + elapsedSeconds = Math.Round(stopwatch.Elapsed.TotalSeconds, 2), + partitions, + }); + } + else + { + context.Output.WriteLine($"extracted {completed}/{entries.Count} partitions, {TextFormat.Bytes(bytes)} in {stopwatch.Elapsed.TotalSeconds:F1}s"); + foreach (var partition in partitions) + context.Output.WriteLine($" {partition.name} -> {partition.file}"); + } + + return completed == entries.Count ? ExitCodes.Ok : ExitCodes.FileOrVerify; + } +} + +internal sealed class DumpCommand : ICliCommand +{ + public string Name => "dump"; + public string McpName => "dump"; + public string Summary => "Dump one device partition to a host file via oem dump-emmc (read-only on the device)."; + public string Usage => "dump -o [--json]"; + public bool IsWrite => false; + public IReadOnlyList Params => new[] + { + new CliParam("partition", "string", "partition name, e.g. oeminfo, ptable", Required: true, Positional: true), + new CliParam("output", "string", "output directory for .img", Default: "."), + }; + + public async Task ExecuteAsync(ParsedArgs args, CliContext context, CancellationToken cancellationToken) + { + if (args.Positionals.Count < 1) throw new CliUsageException("dump requires a partition name"); + string partition = args.Positionals[0]; + if (!IsSafePartition(partition)) + throw new CliUsageException($"invalid partition name '{partition}'"); + + string outputDirectory = Path.GetFullPath(args.Value("output") ?? ".", context.WorkingDirectory); + + var session = await FastbootSession.TryOpenAsync(); + if (session == null) + { + context.Diag("error: fastboot binary not found; set KIRIN_FASTBOOT or install platform-tools"); + return ExitCodes.FileOrVerify; + } + if (!session.Connected) + { + context.Diag("error: no fastboot device detected"); + return ExitCodes.NoDevice; + } + + try + { + Directory.CreateDirectory(outputDirectory); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + context.Diag($"error: cannot create output directory: {ex.Message}"); + return ExitCodes.FileOrVerify; + } + + string target = Path.Combine(outputDirectory, partition + ".img"); + var service = new FastbootFlasherService(session.Client); + (bool IsSuccess, string Message) result; + try + { + result = await service.DumpPartitionAsync(partition, target); + } + catch (OperationCanceledException) + { + context.Diag("error: dump cancelled"); + return ExitCodes.FileOrVerify; + } + + long size = 0; + if (File.Exists(target)) + { + try { size = new FileInfo(target).Length; } catch (Exception) { size = 0; } + } + + if (result.IsSuccess) + { + if (context.Json) + { + context.WriteJson(new { partition, output = target, bytes = size, message = result.Message }); + } + else + { + context.Output.WriteLine($"dumped {partition} -> {target} ({TextFormat.Bytes(size)})"); + } + return ExitCodes.Ok; + } + + int exit = DeviceOutcome.FailureExit(result.Message); + context.Diag($"error: dump failed: {result.Message}"); + if (context.Json) + { + context.WriteJson(new { partition, output = target, bytes = size, message = result.Message, exitCode = exit }); + } + return exit; + } + + private static bool IsSafePartition(string name) => + name.Length is > 0 and <= 64 && + name.All(c => char.IsAsciiLetterOrDigit(c) || c is '_' or '-' or '.'); +} diff --git a/Cli/Commands/WriteCommands.cs b/Cli/Commands/WriteCommands.cs new file mode 100644 index 0000000..43aa95e --- /dev/null +++ b/Cli/Commands/WriteCommands.cs @@ -0,0 +1,400 @@ +using System.Text; +using Kirin_Tool.Models; +using Kirin_Tool.Services; + +namespace Kirin_Tool.Cli.Commands; + +/// +/// Gate for the second batch: write commands compute and print exactly what would be +/// written, then refuse to touch the device. They require --yes (CLI) or +/// confirm: true (MCP) even to leave "plan" mode, and the actual write path is +/// intentionally not implemented in this build, so they still exit 4. +/// +internal abstract class GatedWriteCommand : ICliCommand +{ + public abstract string Name { get; } + public abstract string McpName { get; } + public abstract string Summary { get; } + public abstract string Usage { get; } + public bool IsWrite => true; + public abstract IReadOnlyList Params { get; } + + protected abstract Task BuildPlanAsync(ParsedArgs args, CliContext context, CancellationToken cancellationToken); + + public async Task ExecuteAsync(ParsedArgs args, CliContext context, CancellationToken cancellationToken) + { + WritePlan plan; + try + { + plan = await BuildPlanAsync(args, context, cancellationToken); + } + catch (CliUsageException) + { + throw; + } + catch (Exception ex) when (ex is IOException or InvalidDataException or InvalidOperationException or UnauthorizedAccessException or NotSupportedException or ArgumentException or CliFileException) + { + context.Diag($"error: {ex.Message}"); + return ExitCodes.FileOrVerify; + } + + bool confirmed = context.Yes || args.HasFlag("yes"); + string status = confirmed ? "confirmed-but-write-path-not-implemented" : "plan-only"; + + var payload = new + { + command = Name, + dryRun = true, + applied = false, + confirmed, + gate = new + { + required = "--yes (CLI) or confirm:true (MCP)", + status, + reason = "Write paths are gate-only in this build: the plan below was generated from the existing services, but nothing was flashed, erased or written.", + exitCode = ExitCodes.Gated, + }, + plan = plan.Details, + exitCode = ExitCodes.Gated, + }; + + if (context.Json) + { + context.WriteJson(payload); + } + else + { + foreach (string line in plan.Lines) context.Output.WriteLine(line); + context.Output.WriteLine(); + context.Output.WriteLine($"gate: {status} (exit {ExitCodes.Gated})"); + if (!confirmed) + context.Output.WriteLine("re-run with --yes (CLI) or confirm:true (MCP) to acknowledge the plan; this build still will not write."); + else + context.Output.WriteLine("write path not implemented in this build; no device state was changed."); + } + + if (!confirmed) context.Diag("gate: plan printed; re-run with --yes to acknowledge"); + else context.Diag("gate: acknowledged, but the write path is not implemented in this build"); + + return ExitCodes.Gated; + } +} + +internal sealed class FlashOtaCommand : GatedWriteCommand +{ + public override string Name => "flash-ota"; + public override string McpName => "flash_ota"; + public override string Summary => "Plan flashing every partition of an UPDATE.APP (gate-only: never writes in this build)."; + public override string Usage => "flash-ota [--yes] [--json]"; + public override IReadOnlyList Params => new[] + { + new CliParam("file", "string", "path to UPDATE.APP to inspect for the flash plan", Required: true, Positional: true), + }; + + protected override Task BuildPlanAsync(ParsedArgs args, CliContext context, CancellationToken cancellationToken) + { + if (args.Positionals.Count < 1) throw new CliUsageException("flash-ota requires an UPDATE.APP path"); + string archivePath = Path.GetFullPath(args.Positionals[0], context.WorkingDirectory); + if (!File.Exists(archivePath)) throw new CliFileException($"file not found: {archivePath}"); + + List entries = PartitionExtractor.Read(archivePath, cancellationToken); + long totalBytes = entries.Sum(entry => entry.Partition.Size); + + var partitions = entries.Select(entry => new + { + partition = entry.Name, + size = entry.Partition.Size, + formattedSize = entry.Partition.FormattedSize, + image = Path.Combine(Path.Combine(Path.GetTempPath(), "kirintool-flash", Path.GetFileNameWithoutExtension(archivePath)), entry.FileName), + }).ToList(); + + var details = new + { + archive = archivePath, + implementation = "Services/FastbootFlasherService.FlashPartitionAsync (not invoked in this build)", + partitionCount = partitions.Count, + totalBytes, + partitions, + }; + + var lines = new List + { + $"flash plan for {archivePath}", + $"would write {partitions.Count} partitions ({TextFormat.Bytes(totalBytes)}) via fastboot flash:", + TextFormat.Table(partitions.Select(p => new[] { p.partition, p.formattedSize }).ToList(), "PARTITION", "SIZE"), + }; + + return Task.FromResult(new WritePlan(details, lines)); + } +} + +internal sealed class FlashXmlCommand : GatedWriteCommand +{ + public override string Name => "flash-xml"; + public override string McpName => "flash_xml"; + public override string Summary => "Plan flashing from a Huawei flashing XML (gate-only: never writes in this build)."; + public override string Usage => "flash-xml [--yes] [--json]"; + public override IReadOnlyList Params => new[] + { + new CliParam("path", "string", "flashing XML file, or a directory containing one", Required: true, Positional: true), + }; + + protected override Task BuildPlanAsync(ParsedArgs args, CliContext context, CancellationToken cancellationToken) + { + if (args.Positionals.Count < 1) throw new CliUsageException("flash-xml requires a flashing XML path"); + string path = Path.GetFullPath(args.Positionals[0], context.WorkingDirectory); + + if (Directory.Exists(path)) + { + var candidates = Directory.GetFiles(path, "*.xml", SearchOption.TopDirectoryOnly) + .OrderBy(file => file, StringComparer.Ordinal) + .ToList(); + if (candidates.Count == 0) throw new CliFileException($"no *.xml flashing file found in {path}"); + if (candidates.Count > 1) + { + string? preferred = candidates.FirstOrDefault(file => + Path.GetFileName(file).Contains("flash", StringComparison.OrdinalIgnoreCase)); + path = preferred ?? candidates[0]; + } + else + { + path = candidates[0]; + } + } + + if (!File.Exists(path)) throw new CliFileException($"file not found: {path}"); + + string? fastbootPath = BinaryLocator.FindFastboot(); + var service = new FastbootFlasherService(new FastbootClient(fastbootPath ?? "fastboot")); + List partitions = service.ParseFlashingXml(path); + if (partitions.Count == 0) + throw new CliFileException($"no flashable entries parsed from {path}"); + + var images = partitions.Select(partition => new + { + partition = partition.Identifier, + name = partition.Name, + image = partition.DumpPath, + exists = partition.DumpPath != null && File.Exists(partition.DumpPath), + }).ToList(); + + var details = new + { + xml = path, + implementation = "Services/FastbootFlasherService.ParseFlashingXml + FlashPartitionAsync (not invoked in this build)", + imageCount = images.Count, + missingImages = images.Count(image => !image.exists), + images, + }; + + var lines = new List + { + $"flash plan for {path}", + $"would write {images.Count} images:", + TextFormat.Table(images.Select(i => new[] + { + i.partition, i.name, i.exists ? "present" : "MISSING", i.image ?? "(unresolved)", + }).ToList(), "PARTITION", "NAME", "STATE", "PATH"), + }; + if (images.Any(image => !image.exists)) + lines.Add("warning: some images are missing; a real flash would fail or be partial."); + + return Task.FromResult(new WritePlan(details, lines)); + } +} + +internal sealed class VcomUnlockCommand : GatedWriteCommand +{ + public override string Name => "vcom-unlock"; + public override string McpName => "vcom_unlock"; + public override string Summary => "Plan a VCOM/BootROM loader unlock for a chip (gate-only: never uploads in this build)."; + public override string Usage => "vcom-unlock --cpu [--yes] [--json]"; + public override IReadOnlyList Params => new[] + { + new CliParam("cpu", "string", "chipset loader family, e.g. hisi980, hisi990", Required: true, Enum: BundledLoaders.SupportedChips().ToList()), + }; + + protected override Task BuildPlanAsync(ParsedArgs args, CliContext context, CancellationToken cancellationToken) + { + string? cpu = args.Value("cpu"); + if (string.IsNullOrWhiteSpace(cpu)) + throw new CliUsageException("vcom-unlock requires --cpu (supported: " + string.Join(", ", BundledLoaders.SupportedChips()) + ")"); + + cpu = cpu.Trim().ToLowerInvariant(); + if (!FirmwareUnlocker.CpuAddresses.ContainsKey(cpu)) + throw new CliUsageException($"unsupported chip '{cpu}' (supported: {string.Join(", ", BundledLoaders.SupportedChips())})"); + + var stages = BundledLoaders.Plan(cpu); + string loaderDirectory = Path.Combine(BundledLoaders.Directory, cpu); + + var stageList = stages.Select(stage => new + { + stage = stage.Stage, + file = stage.File, + path = Path.Combine(loaderDirectory, stage.File), + address = "0x" + stage.Address.ToString("X8"), + pwn = stage.PwnFlag, + exists = stage.Exists, + }).ToList(); + + var details = new + { + cpu, + loaderDirectory, + implementation = "Services/FirmwareUnlocker.UnlockFastboot + Services/VcomFlasher (not invoked in this build)", + requiresVcomMode = "HUAWEI USB COM 1.0 (12d1:3609)", + stageCount = stageList.Count, + missingStages = stageList.Count(stage => !stage.exists), + stages = stageList, + }; + + var lines = new List + { + $"vcom unlock plan for {cpu}", + $"loader directory: {loaderDirectory}", + "would upload, in order (device must already be in VCOM mode):", + TextFormat.Table(stageList.Select(stage => new[] + { + stage.stage, stage.address, stage.file, stage.exists ? "present" : "MISSING", + }).ToList(), "STAGE", "ADDRESS", "LOADER", "FILE"), + }; + if (stageList.Any(stage => !stage.exists)) + lines.Add("warning: missing loader files would be skipped by the current service."); + + return Task.FromResult(new WritePlan(details, lines)); + } +} + +internal sealed class OemInfoCommand : GatedWriteCommand +{ + public override string Name => "oeminfo"; + public override string McpName => "oeminfo"; + public override string Summary => "Plan an OEMINFO model/region rewrite from a file or a device dump (gate-only: never flashes)."; + public override string Usage => "oeminfo --model --region (--input | --pull) [--yes] [--json]"; + public override IReadOnlyList Params => new[] + { + new CliParam("model", "string", "new model string written into the OEMINFO model entry", Required: true), + new CliParam("region", "string", "new vendor/country string written into the region entry", Required: true), + new CliParam("input", "string", "local oeminfo.img to convert"), + new CliParam("pull", "boolean", "dump oeminfo from the connected device instead of --input"), + }; + + protected override async Task BuildPlanAsync(ParsedArgs args, CliContext context, CancellationToken cancellationToken) + { + string? model = args.Value("model"); + string? region = args.Value("region"); + if (string.IsNullOrWhiteSpace(model)) throw new CliUsageException("oeminfo requires --model "); + if (string.IsNullOrWhiteSpace(region)) throw new CliUsageException("oeminfo requires --region "); + + bool pull = args.HasFlag("pull"); + string? input = args.Value("input"); + if (pull && input != null) throw new CliUsageException("oeminfo accepts either --pull or --input, not both"); + if (!pull && input == null) throw new CliUsageException("oeminfo requires --input or --pull"); + + string? inputPath = null; + int? detectedVersion = null; + object? conversion = null; + + if (!pull) + { + inputPath = Path.GetFullPath(input!, context.WorkingDirectory); + if (!File.Exists(inputPath)) throw new CliFileException($"file not found: {inputPath}"); + detectedVersion = TryDetectOemInfoVersion(inputPath); + + var service = new OemInfoService(new FastbootClient(BinaryLocator.FindFastboot() ?? "fastboot")); + cancellationToken.ThrowIfCancellationRequested(); + OemInfoConversionResult result = await service.ConvertOemInfo(false, inputPath, model!, region!); + service.CleanupTempFiles(); + conversion = new + { + success = result.IsSuccess, + error = result.ErrorMessage, + outputBytes = result.ConvertedData?.Length, + pulledFromDevice = result.PulledFromDevice, + }; + if (!result.IsSuccess) + throw new CliFileException($"OEMINFO conversion failed: {result.ErrorMessage}"); + } + + var details = new + { + mode = pull ? "device-pull" : "file", + input = inputPath, + model, + region, + target = "oeminfo", + oemInfoVersion = detectedVersion, + conversion, + implementation = "Services/OemInfoService.ConvertOemInfo + FastbootClient.FlashOemInfo (flash not invoked in this build)", + }; + + var lines = new List + { + $"oeminfo plan ({(pull ? "pull from device" : inputPath)})", + $"model: {model}", + $"region: {region}", + $"target partition: oeminfo", + }; + if (detectedVersion != null) lines.Add($"detected OEMINFO version: {detectedVersion}"); + if (!pull) lines.Add("conversion: succeeded locally (in-memory, temp files cleaned)"); + else lines.Add("conversion: would dump oeminfo from the device first"); + + return new WritePlan(details, lines); + } + + private static int? TryDetectOemInfoVersion(string path) + { + try + { + byte[] data = File.ReadAllBytes(path); + byte[] magic = Encoding.ASCII.GetBytes("OEM_INFO"); + for (int offset = 0; offset + 12 <= data.Length; offset += 0x400) + { + if (data.AsSpan(offset, magic.Length).SequenceEqual(magic)) + return BitConverter.ToInt32(data, offset + 8); + } + } + catch (Exception) + { + // best effort only + } + return null; + } +} + +internal sealed class DowngradeEnableCommand : GatedWriteCommand +{ + public override string Name => "downgrade-enable"; + public override string McpName => "downgrade_enable"; + public override string Summary => "Plan the OEMINFO version erase that enables downgrade (gate-only: never erases in this build)."; + public override string Usage => "downgrade-enable [--yes] [--json]"; + public override IReadOnlyList Params => Array.Empty(); + + protected override Task BuildPlanAsync(ParsedArgs args, CliContext context, CancellationToken cancellationToken) + { + string[] commands = + { + "oem oeminfoerase-amssver", + "oem oeminfoerase-basever", + "oem oeminfoerase-custver", + "oem oeminfoerase-preloadver", + }; + + var steps = commands.Select((command, index) => new { step = index + 1, command }).ToList(); + var details = new + { + implementation = "Services/FastbootClient.EnableDowngradeWithSteps (not invoked in this build)", + target = "oeminfo version fields", + steps, + }; + + var lines = new List + { + "downgrade-enable plan", + "would run these fastboot commands in order (irreversible version-field erase):", + TextFormat.Table(steps.Select(step => new[] { step.step.ToString(), step.command }).ToList(), "STEP", "COMMAND"), + }; + + return Task.FromResult(new WritePlan(details, lines)); + } +} diff --git a/Cli/ExitCodes.cs b/Cli/ExitCodes.cs new file mode 100644 index 0000000..ca32925 --- /dev/null +++ b/Cli/ExitCodes.cs @@ -0,0 +1,12 @@ +namespace Kirin_Tool.Cli; + +/// Stable CLI exit codes (documented in docs/cli-mcp.md). +internal static class ExitCodes +{ + public const int Ok = 0; + public const int Usage = 1; + public const int NoDevice = 2; + public const int DeviceRejected = 3; + public const int Gated = 4; + public const int FileOrVerify = 5; +} diff --git a/Cli/Mcp/McpServer.cs b/Cli/Mcp/McpServer.cs new file mode 100644 index 0000000..2c2e5fd --- /dev/null +++ b/Cli/Mcp/McpServer.cs @@ -0,0 +1,312 @@ +using System.Text.Json; +using System.Text.Json.Nodes; +using Kirin_Tool.Cli.Commands; + +namespace Kirin_Tool.Cli.Mcp; + +/// +/// Minimal MCP server over stdio. Transport is newline-delimited JSON-RPC 2.0 +/// (one request per line), which keeps stdout a clean protocol stream; all +/// logging goes to stderr. Implements initialize, ping, tools/list, tools/call. +/// +internal static class McpServer +{ + private const string ProtocolVersion = "2024-11-05"; + + private static readonly JsonSerializerOptions CompactJson = new() + { + Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping, + }; + + public static async Task RunAsync(TextReader input, TextWriter output, TextWriter log, CancellationToken cancellationToken = default) + { + log.WriteLine($"[mcp] {ToolInfo.Name} {ToolInfo.Version} stdio JSON-RPC (newline-delimited); protocol {ProtocolVersion}"); + log.WriteLine("[mcp] tools: " + string.Join(", ", CliRunner.Commands.Select(command => command.McpName))); + + string? line; + while ((line = await input.ReadLineAsync(cancellationToken).ConfigureAwait(false)) != null) + { + string trimmed = line.Trim(); + if (trimmed.Length == 0) continue; + + JsonObject? request; + try + { + request = JsonNode.Parse(trimmed) as JsonObject; + } + catch (JsonException ex) + { + await WriteAsync(output, ErrorResponse(null, -32700, "Parse error: " + ex.Message)); + continue; + } + + if (request == null) + { + await WriteAsync(output, ErrorResponse(null, -32600, "Invalid Request")); + continue; + } + + JsonNode? id = request["id"]; + string? method = request["method"]?.GetValue(); + if (string.IsNullOrEmpty(method)) + { + if (id != null) await WriteAsync(output, ErrorResponse(id, -32600, "Invalid Request")); + continue; + } + + bool isNotification = id == null; + JsonObject? parameters = request["params"] as JsonObject; + + try + { + switch (method) + { + case "initialize": + if (!isNotification) await WriteAsync(output, ResultResponse(id!, Initialize())); + break; + case "notifications/initialized": + case "initialized": + break; + case "ping": + if (!isNotification) await WriteAsync(output, ResultResponse(id!, new JsonObject())); + break; + case "tools/list": + if (!isNotification) await WriteAsync(output, ResultResponse(id!, new JsonObject { ["tools"] = BuildTools() })); + break; + case "tools/call": + if (isNotification) break; + if (parameters == null) + { + await WriteAsync(output, ErrorResponse(id, -32602, "Invalid params: missing tool name")); + break; + } + JsonObject callResult = await CallToolAsync(parameters, log, cancellationToken); + await WriteAsync(output, ResultResponse(id!, callResult)); + break; + default: + if (!isNotification) await WriteAsync(output, ErrorResponse(id, -32601, $"Method not found: {method}")); + break; + } + } + catch (OperationCanceledException) + { + break; + } + catch (Exception ex) + { + log.WriteLine("[mcp] internal error: " + ex); + if (!isNotification) await WriteAsync(output, ErrorResponse(id, -32603, "Internal error: " + ex.Message)); + } + } + + log.WriteLine("[mcp] stdin closed, exiting"); + return ExitCodes.Ok; + } + + private static JsonObject Initialize() => new() + { + ["protocolVersion"] = ProtocolVersion, + ["capabilities"] = new JsonObject + { + ["tools"] = new JsonObject { ["listChanged"] = false }, + }, + ["serverInfo"] = new JsonObject + { + ["name"] = "kirin-tool", + ["version"] = ToolInfo.Version, + }, + ["instructions"] = "Read-only tools run immediately. Write tools (flash_ota, flash_xml, vcom_unlock, oeminfo, downgrade_enable) require confirm:true, return a plan, and are gate-only in this build (exit 4, nothing is written).", + }; + + private static JsonArray BuildTools() + { + var tools = new JsonArray(); + foreach (ICliCommand command in CliRunner.Commands) tools.Add(BuildTool(command)); + return tools; + } + + private static JsonObject BuildTool(ICliCommand command) + { + var properties = new JsonObject(); + var required = new JsonArray(); + foreach (CliParam parameter in command.Params) + { + var schema = new JsonObject + { + ["type"] = parameter.Type, + ["description"] = parameter.Description, + }; + if (parameter.Enum is { Count: > 0 }) + { + schema["enum"] = new JsonArray(parameter.Enum.Select(value => (JsonNode)JsonValue.Create(value)!).ToArray()); + } + if (parameter.Default != null) schema["default"] = parameter.Default; + properties[parameter.Name] = schema; + if (parameter.Required) required.Add(parameter.Name); + } + + if (command.IsWrite) + { + properties["confirm"] = new JsonObject + { + ["type"] = "boolean", + ["description"] = "Acknowledge the printed plan. Required for write tools; true still does not write in this build (gate-only).", + ["default"] = false, + }; + required.Add("confirm"); + } + + var inputSchema = new JsonObject + { + ["type"] = "object", + ["properties"] = properties, + ["additionalProperties"] = false, + }; + if (required.Count > 0) inputSchema["required"] = required; + + var tool = new JsonObject + { + ["name"] = command.McpName, + ["description"] = command.Summary + " Usage: " + command.Usage, + ["inputSchema"] = inputSchema, + ["annotations"] = command.IsWrite + ? new JsonObject { ["readOnlyHint"] = false, ["destructiveHint"] = true, ["idempotentHint"] = false } + : new JsonObject { ["readOnlyHint"] = true, ["idempotentHint"] = true }, + }; + return tool; + } + + private static async Task CallToolAsync(JsonObject parameters, TextWriter log, CancellationToken cancellationToken) + { + string? name = parameters["name"]?.GetValue(); + var arguments = parameters["arguments"] as JsonObject; + + ICliCommand? command = CliRunner.Commands.FirstOrDefault(candidate => + string.Equals(candidate.McpName, name, StringComparison.OrdinalIgnoreCase) || + string.Equals(candidate.Name, name, StringComparison.OrdinalIgnoreCase)); + if (command == null) + return ToolResult($"Unknown tool: {name}", ExitCodes.Usage, stderr: null); + + ParsedArgs parsed = ToParsedArgs(command, arguments); + bool confirm = arguments?["confirm"]?.GetValue() == true; + if (confirm) parsed.SetFlag("yes"); + + var stdout = new StringWriter(); + var stderr = new StringWriter(); + var context = new CliContext(stdout, stderr, json: true, yes: confirm, workingDirectory: Directory.GetCurrentDirectory()); + + int exit; + try + { + exit = await command.ExecuteAsync(parsed, context, cancellationToken); + } + catch (CliUsageException ex) + { + exit = ExitCodes.Usage; + stderr.WriteLine("error: " + ex.Message); + } + catch (OperationCanceledException) + { + throw; + } + catch (Exception ex) + { + exit = ExitCodes.FileOrVerify; + stderr.WriteLine("error: " + ex.Message); + } + + string diagnostics = stderr.ToString().Trim(); + if (diagnostics.Length > 0) log.WriteLine($"[mcp] {command.McpName} stderr: {diagnostics}"); + log.WriteLine($"[mcp] {command.McpName} exit={exit}"); + + string text = stdout.ToString().Trim(); + if (text.Length == 0) + text = new JsonObject { ["exitCode"] = exit }.ToJsonString(); + + return ToolResult(text, exit, diagnostics); + } + + private static ParsedArgs ToParsedArgs(ICliCommand command, JsonObject? arguments) + { + var parsed = new ParsedArgs(); + if (arguments == null) return parsed; + + foreach (CliParam parameter in command.Params) + { + if (!arguments.TryGetPropertyValue(parameter.Name, out JsonNode? node) || node == null) continue; + + if (parameter.Type == "boolean") + { + if (node.GetValue()) parsed.SetFlag(parameter.Name); + continue; + } + + string value = node.GetValue(); + parsed.SetValue(parameter.Name, value); + } + + foreach (CliParam parameter in command.Params.Where(parameter => parameter.Positional)) + { + string? value = parsed.Value(parameter.Name); + if (value != null) parsed.Positionals.Add(value); + } + + return parsed; + } + + private static JsonObject ToolResult(string text, int exitCode, string? stderr) + { + JsonNode? structured = null; + try + { + structured = JsonNode.Parse(text); + } + catch (JsonException) + { + structured = null; + } + + // Exit 4 is the gate refusing a write: the plan is a valid result, not a protocol error. + bool isError = exitCode != ExitCodes.Ok && exitCode != ExitCodes.Gated; + var result = new JsonObject + { + ["content"] = new JsonArray(new JsonObject + { + ["type"] = "text", + ["text"] = text, + }), + ["isError"] = isError, + ["_meta"] = new JsonObject + { + ["exitCode"] = exitCode, + ["stderr"] = stderr, + }, + }; + if (structured != null) result["structuredContent"] = structured; + return result; + } + + private static JsonObject ResultResponse(JsonNode id, JsonObject result) => new() + { + ["jsonrpc"] = "2.0", + ["id"] = id.DeepClone(), + ["result"] = result, + }; + + private static JsonObject ErrorResponse(JsonNode? id, int code, string message) => new() + { + ["jsonrpc"] = "2.0", + ["id"] = id?.DeepClone(), + ["error"] = new JsonObject + { + ["code"] = code, + ["message"] = message, + }, + }; + + private static async Task WriteAsync(TextWriter output, JsonObject message) + { + await output.WriteLineAsync(message.ToJsonString(CompactJson)).ConfigureAwait(false); + await output.FlushAsync().ConfigureAwait(false); + } +} diff --git a/Kirin-Tool.csproj b/Kirin-Tool.csproj index 986bb1a..af69465 100644 --- a/Kirin-Tool.csproj +++ b/Kirin-Tool.csproj @@ -18,6 +18,12 @@ + + + + + diff --git a/Kirin-Tool.sln b/Kirin-Tool.sln index d233e1f..4000367 100644 --- a/Kirin-Tool.sln +++ b/Kirin-Tool.sln @@ -3,18 +3,44 @@ Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 17 VisualStudioVersion = 17.9.34616.47 MinimumVisualStudioVersion = 10.0.40219.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Kirin Tool for Linux", "Kirin-Tool.csproj", "{5354436F-1C05-4512-8AC2-D6282D956C72}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Kirin-Tool", "Kirin-Tool.csproj", "{5354436F-1C05-4512-8AC2-D6282D956C72}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "KirinTool.Cli", "KirinTool.Cli\KirinTool.Cli.csproj", "{3F42C64D-C0C6-42AD-A34C-866FFA8771D9}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 Release|Any CPU = Release|Any CPU + Release|x64 = Release|x64 + Release|x86 = Release|x86 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {5354436F-1C05-4512-8AC2-D6282D956C72}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {5354436F-1C05-4512-8AC2-D6282D956C72}.Debug|Any CPU.Build.0 = Debug|Any CPU + {5354436F-1C05-4512-8AC2-D6282D956C72}.Debug|x64.ActiveCfg = Debug|Any CPU + {5354436F-1C05-4512-8AC2-D6282D956C72}.Debug|x64.Build.0 = Debug|Any CPU + {5354436F-1C05-4512-8AC2-D6282D956C72}.Debug|x86.ActiveCfg = Debug|Any CPU + {5354436F-1C05-4512-8AC2-D6282D956C72}.Debug|x86.Build.0 = Debug|Any CPU {5354436F-1C05-4512-8AC2-D6282D956C72}.Release|Any CPU.ActiveCfg = Release|Any CPU {5354436F-1C05-4512-8AC2-D6282D956C72}.Release|Any CPU.Build.0 = Release|Any CPU + {5354436F-1C05-4512-8AC2-D6282D956C72}.Release|x64.ActiveCfg = Release|Any CPU + {5354436F-1C05-4512-8AC2-D6282D956C72}.Release|x64.Build.0 = Release|Any CPU + {5354436F-1C05-4512-8AC2-D6282D956C72}.Release|x86.ActiveCfg = Release|Any CPU + {5354436F-1C05-4512-8AC2-D6282D956C72}.Release|x86.Build.0 = Release|Any CPU + {3F42C64D-C0C6-42AD-A34C-866FFA8771D9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {3F42C64D-C0C6-42AD-A34C-866FFA8771D9}.Debug|Any CPU.Build.0 = Debug|Any CPU + {3F42C64D-C0C6-42AD-A34C-866FFA8771D9}.Debug|x64.ActiveCfg = Debug|Any CPU + {3F42C64D-C0C6-42AD-A34C-866FFA8771D9}.Debug|x64.Build.0 = Debug|Any CPU + {3F42C64D-C0C6-42AD-A34C-866FFA8771D9}.Debug|x86.ActiveCfg = Debug|Any CPU + {3F42C64D-C0C6-42AD-A34C-866FFA8771D9}.Debug|x86.Build.0 = Debug|Any CPU + {3F42C64D-C0C6-42AD-A34C-866FFA8771D9}.Release|Any CPU.ActiveCfg = Release|Any CPU + {3F42C64D-C0C6-42AD-A34C-866FFA8771D9}.Release|Any CPU.Build.0 = Release|Any CPU + {3F42C64D-C0C6-42AD-A34C-866FFA8771D9}.Release|x64.ActiveCfg = Release|Any CPU + {3F42C64D-C0C6-42AD-A34C-866FFA8771D9}.Release|x64.Build.0 = Release|Any CPU + {3F42C64D-C0C6-42AD-A34C-866FFA8771D9}.Release|x86.ActiveCfg = Release|Any CPU + {3F42C64D-C0C6-42AD-A34C-866FFA8771D9}.Release|x86.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/KirinTool.Cli/KirinTool.Cli.csproj b/KirinTool.Cli/KirinTool.Cli.csproj new file mode 100644 index 0000000..6d6cfb4 --- /dev/null +++ b/KirinTool.Cli/KirinTool.Cli.csproj @@ -0,0 +1,25 @@ + + + + Exe + net8.0 + enable + enable + KirinTool.Cli + Kirin_Tool.Cli + 2.4.8 + LatestMajor + Kirin Tool CLI + Headless CLI + MCP stdio entry for Kirin-Tool (local fork, read-only first). + + + + + + + + + + + + diff --git a/KirinTool.Cli/Program.cs b/KirinTool.Cli/Program.cs new file mode 100644 index 0000000..756cf53 --- /dev/null +++ b/KirinTool.Cli/Program.cs @@ -0,0 +1,3 @@ +using Kirin_Tool.Cli; + +return await CliRunner.RunAsync(args); diff --git a/Program.cs b/Program.cs index ae5bc9f..0371d66 100644 --- a/Program.cs +++ b/Program.cs @@ -1,13 +1,23 @@ using Avalonia; using Avalonia.Controls.ApplicationLifetimes; +using Kirin_Tool.Cli; namespace Kirin_Tool; class Program { [STAThread] - public static void Main(string[] args) => BuildAvaloniaApp() - .StartWithClassicDesktopLifetime(args); + public static int Main(string[] args) + { + // Headless MCP entry: must not initialize Avalonia nor write anything to + // stdout except JSON-RPC responses (the server logs to stderr only). + if (args.Length > 0 && args[0] is "--mcp" or "mcp") + { + return McpEntry.RunAsync().GetAwaiter().GetResult(); + } + + return BuildAvaloniaApp().StartWithClassicDesktopLifetime(args); + } public static AppBuilder BuildAvaloniaApp() => AppBuilder.Configure() .UsePlatformDetect() diff --git a/docs/cli-mcp.md b/docs/cli-mcp.md new file mode 100644 index 0000000..4f2d108 --- /dev/null +++ b/docs/cli-mcp.md @@ -0,0 +1,48 @@ +# CLI 与 MCP 入口(本地 fork 实验) + +> 上游自 2026-09-11 起为 Read-Only Reference License。本目录下的 CLI/MCP 仅作本地 fork 改造, +> 不发布、不分发;改用前请阅读 `FORK-NOTICE.md` 与 `LICENSE`。 + +## 生成物 + +- `KirinTool.Cli/`:薄 exe 工程,引用主工程,输出 `KirinTool.Cli.dll` +- `Cli/`:CLI 命令、闸门与 MCP server 实现,编译进主 exe,因此 `Kirin-Tool --mcp` 也可用 +- 两个入口共用 `CliRunner`,命令实现只有一份 + +## 命令 + +只读(第一批,已落地): + +| 命令 | 说明 | 复用 | +|---|---|---| +| `info` | 工具/fastboot/设备信息、能力与 rescue 计划 | `FastbootClient`、`FastbootReadResponses`、`ChipCapabilities`/`RescuePartitionPlan` | +| `doctor` | fastboot/adb 路径与版本、设备枚举、loader 清单、只读能力探测 | `BinaryLocator`、`ProcessRunner`、`FastbootClient`、`FastbootReadResponses`、`FirmwareUnlocker.CpuAddresses` | +| `getvar ` | 单个 fastboot 变量 | `FastbootClient.QueryVariableAsync` + `FastbootReadResponses.Variable` | +| `extract [outdir]` | 列出并导出全部分区 | `Services.PartitionExtractor.Read/ExtractAsync`(`Utils.UpdateApp`) | +| `dump -o ` | `oem dump-emmc` 导出分区 | `Services.FastbootFlasherService.DumpPartitionAsync` | + +写操作(第二批,仅骨架 + 闸门,永不真正写入):`flash-ota`、`flash-xml`、`vcom-unlock`、`oeminfo`、`downgrade-enable`。 +无 `--yes` 时打印计划清单;即使给了 `--yes` 也只打印 `confirmed-but-write-path-not-implemented`,一律 exit 4。 + +## 约定 + +- `--json` 输出结构化 JSON 到 stdout;进度/诊断一律 stderr,stdout 可安全管道 +- 退出码:0 成功 / 1 用法 / 2 无设备 / 3 设备拒绝 / 4 被闸门拒 / 5 文件或校验失败 +- fastboot 解析顺序:`KIRIN_FASTBOOT` 环境变量 → 程序目录及 `fastboot/` → PATH → `/usr/bin`、`/usr/local/bin`;adb 同理(`KIRIN_ADB`) +- 设备拒绝判定:输出包含 `FAILED`/`invalid command`/`not allowed`/`locked` 等 → exit 3 + +## MCP + +`KirinTool.Cli mcp` 或 `Kirin-Tool --mcp`:stdio、**换行分隔的 JSON-RPC 2.0**(每行一条报文), +日志只写 stderr。支持 `initialize`、`notifications/initialized`、`ping`、`tools/list`、`tools/call`。 + +工具名:`info`、`doctor`、`getvar`、`extract`、`dump`、`flash_ota`、`flash_xml`、`vcom_unlock`、`oeminfo`、`downgrade_enable`。 +写工具的 `inputSchema.required` 必含 `confirm: boolean`;缺省(false)时只返回计划清单,`isError=false`, +`_meta.exitCode` 为 4。 + +自测: + +```bash +printf '%s\n' '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}' \ + '{"jsonrpc":"2.0","id":2,"method":"tools/list"}' | ./KirinTool.Cli mcp +``` From 8c2d884ac7a220bdf3121e3559b06e51af96c1b5 Mon Sep 17 00:00:00 2001 From: xiaquwan1001 Date: Tue, 10 Nov 2026 12:11:22 +0800 Subject: [PATCH 2/2] ci: build CLI and MCP entry on PR branch Add a narrow GitHub Actions workflow that gates the headless CLI + stdio MCP entry points: restore/build Kirin-Tool.csproj and KirinTool.Cli.csproj on .NET 8, run hardware-free smoke tests (--help, version, doctor against a stub fastboot, and an MCP initialize/tools-list session), then upload the CLI build output. Firmware loaders and the bundled fastboot payload are excluded from the artifact; only runtimes/linux-x64 is kept. The upstream release pipeline in build.yml only runs on v* tags, so it cannot gate a branch push. --- .github/workflows/cli-mcp-ci.yml | 154 +++++++++++++++++++++++++++++++ 1 file changed, 154 insertions(+) create mode 100644 .github/workflows/cli-mcp-ci.yml diff --git a/.github/workflows/cli-mcp-ci.yml b/.github/workflows/cli-mcp-ci.yml new file mode 100644 index 0000000..ec8bfb9 --- /dev/null +++ b/.github/workflows/cli-mcp-ci.yml @@ -0,0 +1,154 @@ +name: cli-mcp-ci + +# Lightweight CI for the headless CLI + stdio MCP entry points. +# +# Why a separate workflow instead of extending build.yml: the upstream release +# pipeline (build.yml) only triggers on v* tags and builds the native fastboot +# payload, the AppImage (glibc 2.31 container) and the pacman package. None of +# that runs on a branch push, so it cannot gate the CLI/MCP change set. This +# workflow is deliberately narrow: restore, build the two C# projects, run +# hardware-free smoke tests, upload the CLI build output. Firmware/loaders and +# the bundled fastboot payload are excluded from the artifact on purpose +# (business-source-licensed assets, not build products). +# +# The main csproj runs "make -C native/usb-update" through its +# BuildUsbUpdateBridge target on Linux, so the CI needs cc + pkg-config + +# libusb-1.0 headers. That is the only native step required here; the whole +# native/fastboot-modern build stays in build.yml. + +on: + push: + branches: + - main + - feat/cli-and-mcp-entry + pull_request: + branches: + - main + - feat/cli-and-mcp-entry + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: cli-mcp-ci-${{ github.ref }} + cancel-in-progress: true + +jobs: + build-cli: + name: build CLI + MCP entry (net8.0) + runs-on: ubuntu-latest + timeout-minutes: 20 + env: + DOTNET_NOLOGO: 'true' + DOTNET_CLI_TELEMETRY_OPTOUT: 'true' + DOTNET_SKIP_FIRST_TIME_EXPERIENCE: 'true' + + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Set up .NET 8 SDK + uses: actions/setup-dotnet@v4 + with: + dotnet-version: '8.0.x' + + - name: Show SDK info + run: dotnet --info + + # Required by the BuildUsbUpdateBridge target in Kirin-Tool.csproj. + - name: Install native build dependencies (libusb headers only) + run: | + sudo apt-get update + sudo apt-get install -y --no-install-recommends build-essential pkg-config libusb-1.0-0-dev + + - name: Restore + run: | + dotnet restore Kirin-Tool.csproj + dotnet restore KirinTool.Cli/KirinTool.Cli.csproj + + - name: Build main app (Release) + run: dotnet build Kirin-Tool.csproj -c Release --no-restore -p:NuGetAudit=false + + - name: Build CLI project (Release) + run: dotnet build KirinTool.Cli/KirinTool.Cli.csproj -c Release --no-restore -p:NuGetAudit=false + + # The runner has no phone in fastboot mode. BinaryLocator also probes PATH + # and /usr/bin, so a tiny stub is enough to exercise "doctor" end to end + # without installing platform-tools or touching USB. + - name: Smoke test - help, version, doctor (stubbed fastboot) + run: | + set -euo pipefail + cli=KirinTool.Cli/bin/Release/net8.0/KirinTool.Cli + test -x "$cli" + + "$cli" --help | tee /tmp/help.txt + grep -q 'usage: kirintool' /tmp/help.txt + grep -q 'mcp' /tmp/help.txt + + "$cli" version + + stub="$RUNNER_TEMP/stub-bin" + mkdir -p "$stub" + # Written with echo (not a heredoc): a YAML block scalar cannot hold + # column-0 lines, and a shebang needs to start at column 0. + { + echo '#!/usr/bin/env bash' + echo 'if [ "${1:-}" = "--version" ]; then echo "fastboot version 35.0.2-ci-stub"; exit 0; fi' + echo 'if [ "${1:-}" = "devices" ]; then exit 0; fi' + echo 'echo "FAILED (remote: no device in CI stub)"; exit 1' + } > "$stub/fastboot" + chmod +x "$stub/fastboot" + + KIRIN_FASTBOOT="$stub/fastboot" "$cli" doctor --json | tee /tmp/doctor.json + grep -q '"fastboot-found"' /tmp/doctor.json + grep -q '"loaders-bundled"' /tmp/doctor.json + "$stub/fastboot" --version + + - name: Smoke test - stdio MCP session + run: | + set -euo pipefail + cli=KirinTool.Cli/bin/Release/net8.0/KirinTool.Cli + printf '%s\n' \ + '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}' \ + '{"jsonrpc":"2.0","id":2,"method":"tools/list"}' \ + | "$cli" mcp 2>/tmp/mcp.err | tee /tmp/mcp.out + grep -q '"result"' /tmp/mcp.out + grep -q '"tools"' /tmp/mcp.out + grep -q '"flash_ota"' /tmp/mcp.out + + # Build products only: skip the bundled loaders (**/*.ktl firmware) and the + # fastboot/payload blob, they are licensed assets copied from the repo, + # not something CI produced. The Skia/Avalonia native runtimes for + # win-*/osx/arm/musl are pull-through from Avalonia's package and account + # for ~120 MB; only runtimes/linux-x64 is kept so the artifact stays usable + # on x64 Linux without uploading other platforms' binaries. + - name: Stage artifact (CLI output, no firmware) + run: | + set -euo pipefail + src=KirinTool.Cli/bin/Release/net8.0 + dst=artifact/KirinTool.Cli + mkdir -p "$dst" + rsync -a \ + --exclude 'runtimes/' \ + --exclude 'loaders/' \ + --exclude 'fastboot/' \ + --exclude 'fastboot-modern/' \ + --exclude '*.pdb' \ + --exclude '*.dbg' \ + "$src/" "$dst/" + # Re-add only the x64 Linux native runtimes (SkiaSharp/HarfBuzzSharp). + mkdir -p "$dst/runtimes" + rsync -a "$src/runtimes/linux-x64" "$dst/runtimes/" + # Belt and braces: never ship a large blob by accident. + find artifact -type f -size +25M -print -delete + du -sh artifact/KirinTool.Cli + ls artifact/KirinTool.Cli | head -40 + + - name: Upload CLI artifact + uses: actions/upload-artifact@v4 + with: + name: kirin-tool-cli-${{ github.sha }} + path: artifact/KirinTool.Cli + if-no-files-found: error + retention-days: 14