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
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