diff --git a/tools/BootstrapBlazor.LLMsDocs.Cli/BootstrapBlazor.LLMsDocs.Cli.csproj b/tools/BootstrapBlazor.LLMsDocs.Cli/BootstrapBlazor.LLMsDocs.Cli.csproj index 173ce2a4..4d758163 100644 --- a/tools/BootstrapBlazor.LLMsDocs.Cli/BootstrapBlazor.LLMsDocs.Cli.csproj +++ b/tools/BootstrapBlazor.LLMsDocs.Cli/BootstrapBlazor.LLMsDocs.Cli.csproj @@ -1,7 +1,7 @@ - 11.0.0 + 11.0.1 Exe false diff --git a/tools/BootstrapBlazor.LLMsDocs.Cli/CommandFactory.cs b/tools/BootstrapBlazor.LLMsDocs.Cli/CommandFactory.cs index 891e95e2..689fa8c3 100644 --- a/tools/BootstrapBlazor.LLMsDocs.Cli/CommandFactory.cs +++ b/tools/BootstrapBlazor.LLMsDocs.Cli/CommandFactory.cs @@ -35,14 +35,14 @@ internal static class CommandFactory private static Command BuildIndexCommand() { - var (baseUrl, refresh, noCache) = SourceOptions(); - var cmd = new Command("index", "Print the raw llms.txt index.") { baseUrl, refresh, noCache }; + var (baseUrl, refresh, noCache, project, framework) = SourceOptions(); + var cmd = new Command("index", "Print the documentation index.") { baseUrl, refresh, noCache, project, framework }; cmd.SetAction(async (result, ct) => { try { - using var client = CreateClient(result, baseUrl, refresh, noCache); - Console.Out.Write(await client.GetIndexAsync(ct)); + using var client = CreateClient(result, baseUrl, refresh, noCache, project, framework); + Console.Out.Write(await client.IndexAsync(ct)); return 0; } catch (Exception ex) @@ -57,16 +57,16 @@ private static Command BuildListCommand() { var query = new Option("--query") { Description = "Optional name/description filter." }; var format = FormatOption(); - var (baseUrl, refresh, noCache) = SourceOptions(); + var (baseUrl, refresh, noCache, project, framework) = SourceOptions(); var cmd = new Command("list", "List components from the index (default JSON).") { - query, format, baseUrl, refresh, noCache + query, format, baseUrl, refresh, noCache, project, framework }; cmd.SetAction(async (result, ct) => { try { - using var client = CreateClient(result, baseUrl, refresh, noCache); + using var client = CreateClient(result, baseUrl, refresh, noCache, project, framework); var entries = await client.ListAsync(result.GetValue(query), ct); WriteEntries(entries, result.GetValue(format)); return 0; @@ -84,16 +84,16 @@ private static Command BuildSearchCommand() var query = new Argument("query") { Description = "Search term." }; var limit = new Option("--limit") { Description = "Maximum results (default 20)." }; var format = FormatOption(); - var (baseUrl, refresh, noCache) = SourceOptions(); + var (baseUrl, refresh, noCache, project, framework) = SourceOptions(); var cmd = new Command("search", "Search components by name or description (default JSON).") { - query, limit, format, baseUrl, refresh, noCache + query, limit, format, baseUrl, refresh, noCache, project, framework }; cmd.SetAction(async (result, ct) => { try { - using var client = CreateClient(result, baseUrl, refresh, noCache); + using var client = CreateClient(result, baseUrl, refresh, noCache, project, framework); var max = result.GetValue(limit); if (max <= 0) { @@ -115,18 +115,18 @@ private static Command BuildSearchCommand() private static Command BuildGetCommand() { var component = new Argument("component") { Description = "Component name, e.g. Button." }; - var (baseUrl, refresh, noCache) = SourceOptions(); + var (baseUrl, refresh, noCache, project, framework) = SourceOptions(); var cmd = new Command("get", "Fetch one component's API doc (the core command).") { - component, baseUrl, refresh, noCache + component, baseUrl, refresh, noCache, project, framework }; cmd.SetAction(async (result, ct) => { var name = result.GetValue(component)!; try { - using var client = CreateClient(result, baseUrl, refresh, noCache); - Console.Out.Write(await client.GetComponentAsync(name, ct)); + using var client = CreateClient(result, baseUrl, refresh, noCache, project, framework); + Console.Out.Write(await client.GetAsync(name, ct)); return 0; } catch (FileNotFoundException ex) @@ -153,11 +153,11 @@ private static Command BuildInstructionsCommand() private static Command BuildInstallCommand() { - var client = new Option("--client") { Description = "Target client: claude | cursor | trae | codex | all (default all)." }; + var client = new Option("--client") { Description = "Target client: copilot | claude | cursor | trae | codex | all (default all)." }; var scope = new Option("--scope") { Description = "Where to write: user (home, default) or project (cwd)." }; var target = new Option("--target") { Description = "Override base directory to write into." }; var force = new Option("--force") { Description = "Overwrite existing files." }; - var cmd = new Command("install", "Install agent discovery artifacts (Claude Code skill / Cursor rules / Trae skill / Codex AGENTS.md).") + var cmd = new Command("install", "Install agent discovery artifacts (Copilot / Claude Code / Cursor / Trae / Codex).") { client, scope, target, force }; @@ -181,7 +181,7 @@ private static Command BuildInstallCommand() // ---- helpers ---------------------------------------------------------- - private static (Option baseUrl, Option refresh, Option noCache) SourceOptions() + private static (Option baseUrl, Option refresh, Option noCache, Option project, Option framework) SourceOptions() { var baseUrl = new Option("--base-url") { @@ -189,15 +189,24 @@ private static (Option baseUrl, Option refresh, Option noCa }; var refresh = new Option("--refresh") { Description = "Ignore cache TTL and re-fetch from the source." }; var noCache = new Option("--no-cache") { Description = "Do not read or write the local cache." }; - return (baseUrl, refresh, noCache); + var project = new Option("--project") { Description = "Project file or directory to resolve package documentation." }; + var framework = new Option("--framework") { Description = "Target framework from project.assets.json." }; + return (baseUrl, refresh, noCache, project, framework); } private static Option FormatOption() => new("--format") { Description = "Output format: json (default) or text." }; - private static LlmsDocsClient CreateClient( - ParseResult result, Option baseUrl, Option refresh, Option noCache) => - new(result.GetValue(baseUrl), result.GetValue(refresh), result.GetValue(noCache)); + private static ProjectDocsClient CreateClient( + ParseResult result, Option baseUrl, Option refresh, Option noCache, + Option project, Option framework) + { + var source = result.GetValue(baseUrl); + var automatic = string.IsNullOrWhiteSpace(source) + && string.IsNullOrEmpty(Environment.GetEnvironmentVariable(LlmsDocsClient.BaseUrlEnvVar)); + var packages = automatic ? ProjectDocsResolver.Resolve(result.GetValue(project), result.GetValue(framework)) : []; + return new ProjectDocsClient(new LlmsDocsClient(source, result.GetValue(refresh), result.GetValue(noCache), automatic), packages, automatic); + } private static void WriteEntries(IReadOnlyList entries, string? format) { diff --git a/tools/BootstrapBlazor.LLMsDocs.Cli/Program.cs b/tools/BootstrapBlazor.LLMsDocs.Cli/Program.cs index 935f0e58..56401a3a 100644 --- a/tools/BootstrapBlazor.LLMsDocs.Cli/Program.cs +++ b/tools/BootstrapBlazor.LLMsDocs.Cli/Program.cs @@ -11,4 +11,4 @@ // Output is redirected and the encoding can't be set; ignore. } -return await CommandFactory.Build().Parse(args).InvokeAsync(); +return await CommandFactory.Build().Parse(args.Length == 0 ? ["--help"] : args).InvokeAsync(); diff --git a/tools/BootstrapBlazor.LLMsDocs.Cli/README.md b/tools/BootstrapBlazor.LLMsDocs.Cli/README.md index 6a085b93..d9f6e29b 100644 --- a/tools/BootstrapBlazor.LLMsDocs.Cli/README.md +++ b/tools/BootstrapBlazor.LLMsDocs.Cli/README.md @@ -1,11 +1,11 @@ # BootstrapBlazor LLMs Docs CLI(`bb-llms`) -一个轻量命令行工具,用于从 [www.blazor.zone/llms](https://www.blazor.zone/llms) -拉取 BootstrapBlazor 及 BootstrapBlazor.Extensions 组件的**官方 API 文档**(参数、事件回调、公开方法、源码链接), -供 AI agent(Claude Code / Cursor / Trae / Codex 等经 Bash 调用)和开发者查询。 +一个轻量命令行工具,用于查询项目已还原的 NuGet 包及 [www.blazor.zone/llms](https://www.blazor.zone/llms) +中的 BootstrapBlazor 和 BootstrapBlazor.Extensions API 文档(参数、事件回调、公开方法、源码链接), +供 AI agent(Copilot CLI / Claude Code / Cursor / Trae / Codex 等)和开发者查询。 组件文档由官网的 `BootstrapBlazor.LLMsDocsGenerator`(生产者,CI 侧用 Roslyn 生成并发布)产出, -本工具是**消费者**:只负责按需 HTTP 拉取已生成的 `.txt` 文档并本地缓存, +本工具是**消费者**:读取包内已生成的 `.txt` 文档,或按需 HTTP 拉取并缓存官网文档, **不克隆仓库、不做源码分析**。详见文末「设计说明」。 --- @@ -14,7 +14,7 @@ ### 前置条件 -- 已安装 **.NET 10 SDK**(提供 `dotnet tool` 能力)。 +- 已安装 **.NET 11 SDK**(当前源码目标为 `net11.0`)。 ### 全局安装 @@ -29,6 +29,8 @@ bb-llms --help bb-llms get Button # 能打印 Button 的 API 文档即安装成功 ``` +不带参数运行 `bb-llms` 会显示帮助信息。 + > 若提示找不到 `bb-llms`,请确认 `~/.dotnet/tools`(Windows 为 `%USERPROFILE%\.dotnet\tools`) > 已在 `PATH` 中,或重开一个终端。 @@ -39,8 +41,7 @@ dotnet tool update -g BootstrapBlazor.LLMsDocs.Cli dotnet tool uninstall -g BootstrapBlazor.LLMsDocs.Cli ``` -> 注意:**几乎不需要更新本工具**。新增组件、参数变化都来自远程文档的更新,工具自动拉取即可—— -> 只有当工具本身发布了新命令或修复时才需要 `update`。 +> 新增组件、参数变化来自包内文档或远程文档;工具本身发布新功能或修复时需要 `update`。 --- @@ -51,7 +52,7 @@ bb-llms search table # 按关键词搜索组件,定位准确名称 bb-llms get Table # 拉取 Table 组件的完整 API 文档(核心命令) bb-llms get SelectCity # 拉取 Region 扩展包中 SelectCity 的 API 文档 bb-llms list # 列出全部组件 -bb-llms index # 打印原始 llms.txt 索引 +bb-llms index # 打印文档索引 ``` --- @@ -62,14 +63,16 @@ bb-llms index # 打印原始 llms.txt 索引 | 命令 | 说明 | 输出 | |---|---|---| -| `bb-llms index` | 打印原始 `llms.txt` 索引 | 原始 Markdown | +| `bb-llms index` | 打印文档索引 | Markdown | | `bb-llms list [--query ]` | 列出组件,可按名称/描述过滤 | JSON(默认)/ text | | `bb-llms search [--limit ]` | 按名称或描述搜索,名称前缀匹配优先 | JSON(默认)/ text | -| `bb-llms get ` | 拉取单个组件的 API 文档(**核心命令**) | 原始 Markdown | +| `bb-llms get ` | 获取单个组件的 API 文档(**核心命令**) | 原始 Markdown | 要点: -- `get` / `index` 的输出保留远程 `.txt` 原文;`get` 会先解析 `llms.txt`,按名称找到文档路径,再直接读取核心或扩展文档,不通过请求失败来尝试其他目录。本地源也必须包含该索引。 +- `get` 输出文档原文;自动模式的 `index` 合并项目包和官网索引,显式指定源时输出其原始索引。本地源也必须包含 `llms.txt`。 +- 默认 `get` 优先使用当前项目实际还原的包内文档,本地缺少文档时查询官网。`index` / `list` / `search` 合并项目包和官网索引,以免遗漏未安装的组件;同名项优先使用项目包。官网不可用时仍可使用项目包结果。 +- 来源及官网版本可能不一致的提示写入 stderr,不影响 JSON 输出。 - `list` / `search` 包括组件和服务,默认输出 **JSON**;`isExtension` 表示文档位于 `extensions/`,不表示接口源码一定声明在扩展仓库。加 `--format text` 输出纯文本(`Name - 描述` 每行一条)。 - `search --limit` 默认 `20`,取值范围会被限制在 `1~100`。 - `search` 按文档路径去重后应用结果数量限制,避免多个包共用的服务占满结果;`list` 保留各包的索引项。 @@ -95,9 +98,14 @@ bb-llms get IRecognizerProvider # 共享服务接口,按包列出 Azure/B --base-url 文档源:HTTP(S) 网址或本地目录路径 --refresh 忽略缓存 TTL,强制回源拉取(仍写缓存) --no-cache 既不读也不写本地缓存 +--project 选择项目文件或只包含一个项目的目录 +--framework 选择 project.assets.json 中的目标框架 ``` -**文档源解析优先级**:`--base-url` > 环境变量 `BB_LLMS_BASE_URL` > 默认 `https://www.blazor.zone/llms` +**文档源解析优先级**:`--base-url` > 环境变量 `BB_LLMS_BASE_URL` > 当前项目还原的包内文档 > 官网。 +显式指定源时不进行项目发现,沿用该源原有行为。自动模式查找当前目录或父目录中的项目;若没有,再查找当前目录下的项目。项目或还原目标不唯一时必须分别用 `--project` 或 `--framework` 指定,不能任意选择版本;带运行时标识的目标使用完整名称,如 `net8.0/win-x64`。项目尚未还原时回退官网;当前只读取项目目录下 `obj/project.assets.json`。 + +包内核心文档支持 `skills/bb-api` 和旧版 `skills/bootstrapblazor`;扩展包读取 `docs/llms`。自动模式下的官网缓存与显式源缓存隔离。 ```bash # 用环境变量指向自建/镜像源 @@ -120,7 +128,7 @@ bb-llms get Button --base-url ./wwwroot/llms - 远程源的响应缓存在: - Windows:`%LOCALAPPDATA%\bb-llms` - Linux / macOS:`~/.local/share/bb-llms` -- 每个文档存「内容文件 + 同名 `.meta.json`(记录 ETag 与拉取时间)」。 +- 每个文档存「内容文件 + 同名 `.meta.json`(记录 ETag 与拉取时间)」;自动模式的官网缓存位于 `bb-llms/official`。 - **TTL 24 小时**:未过期直接用缓存;过期后带 `If-None-Match` 条件请求, 服务端返回 `304` 则沿用旧内容并刷新时间戳,`200` 则写入新内容。 - 想强制拿最新:`--refresh`;完全不碰缓存目录:`--no-cache`。 @@ -133,44 +141,49 @@ bb-llms get Button --base-url ./wwwroot/llms ## 给 AI agent 使用(发现层) -一个躺在 `PATH` 上的 CLI 对 agent 是「隐形」的——必须有指令文件告诉 agent -「需要 BootstrapBlazor 组件 API 时去跑 `bb-llms get `」。 -以下两个脚手架命令负责把这层「发现 / 触发」一键装好: +一个躺在 `PATH` 上的 CLI 对 agent 是「隐形」的。以下脚手架命令安装入口指令: +涉及 BootstrapBlazor 时,agent 优先发现当前项目实际还原的 NuGet 包内 skill 和参考文档; +本地找不到所需信息时,才使用 `bb-llms` 查询官网。 ```bash bb-llms instructions # 打印可粘贴进 CLAUDE.md / AGENTS.md 的通用片段 +bb-llms install --client copilot # 写 ~/.copilot/skills/bootstrapblazor/SKILL.md bb-llms install --client claude # 写 ~/.claude/skills/bootstrapblazor/SKILL.md bb-llms install --client cursor # 写 ~/.cursor/rules/bootstrapblazor.mdc bb-llms install --client trae # 写 ~/.trae/skills/bootstrapblazor/SKILL.md bb-llms install --client codex # 写 ~/.codex/AGENTS.md -bb-llms install --client all # 四者都写(默认) +bb-llms install --client all # 五者都写(默认) ``` `install` 选项: ``` ---client claude|cursor|trae|codex|all 目标客户端(默认 all) +--client copilot|claude|cursor|trae|codex|all 目标客户端(默认 all) --scope user|project user=用户主目录(默认),project=当前目录 --target 覆盖写入的根目录 --force 覆盖已存在的文件(默认存在则跳过) ``` -> 默认 scope 为 **user(用户主目录)**:四个客户端的发现文件都装到用户主目录 -> (`~/.claude/skills/`、`~/.cursor/rules/`、`~/.trae/skills/`、`~/.codex/AGENTS.md`), -> 配合全局安装的 `bb-llms`,在任意项目里都能被自动发现,装一次全局生效。 +> 默认 scope 为 **user(用户主目录)**:发现文件装到各客户端的用户目录, +> 包括 `~/.copilot/skills/`、`~/.claude/skills/`、`~/.cursor/rules/`、 +> `~/.trae/skills/` 和 `~/.codex/AGENTS.md`。 > 需要只对当前项目生效时,用 `--scope project` 显式覆盖 -> (如 `bb-llms install --client codex --scope project` 写仓库根目录的 `AGENTS.md`)。 +> (如 `--client copilot --scope project` 写 `.github/skills/`,`--client codex --scope project` 写仓库根目录的 `AGENTS.md`)。 + +自动加载取决于 agent 和权限设置,安装后可重启 agent 或重新加载其 skills。 +入口调用 `bb-llms`;工具通过 `obj/project.assets.json` 定位当前项目使用的包文档,无需安装 `dotnet-inspect`。本地缺少文档时查询官网,并说明官网版本可能与项目引用的版本不同。入口模板保留旧版内容,其中提及的官网是兜底源,实际优先级以本版工具为准;已有直接调用 `bb-llms` 的旧版入口的用户更新工具后无需重新安装入口。 + +接入方式: -五套生态接入方式: +- **Copilot CLI**:`bb-llms install --client copilot` 写入 + `~/.copilot/skills/bootstrapblazor/SKILL.md`;项目级安装写入 + `.github/skills/bootstrapblazor/SKILL.md`。 -- **Claude Code**:`bb-llms install --client claude` 在**用户主目录** `~/.claude/skills/` - 写入一个 skill,Claude Code 会根据其 `description` 在任务涉及 BootstrapBlazor 组件时 - **自动加载**并调用 `bb-llms`,等效于 MCP server 的自动发现。装一次即对所有项目生效。 +- **Claude Code**:`bb-llms install --client claude` 在用户目录 `~/.claude/skills/` + 写入一个 skill。 - **Cursor**:`bb-llms install --client cursor` 在**用户主目录** `~/.cursor/rules/` 写入规则(匹配 `*.razor` / `*.razor.cs`),全局生效。 -- **Trae**:`bb-llms install --client trae` 在**用户主目录** `~/.trae/skills/` 写入一个 skill。 - Trae 的 skill 与 Claude 同构(同样的 `SKILL.md` + name/description frontmatter,按描述**自动匹配**), - 因此复用同一套模板,同样装一次全局生效。 +- **Trae**:`bb-llms install --client trae` 在用户目录 `~/.trae/skills/` 写入与 Claude 共用的 skill。 - **Codex**:`bb-llms install --client codex` 写入 `~/.codex/AGENTS.md`(用户主目录,默认; `--scope project` 则写仓库根目录的 `AGENTS.md`)。Codex 没有独立的 skill/规则机制,统一读 `AGENTS.md`, 因此复用 `instructions` 的通用片段。 @@ -183,7 +196,7 @@ bb-llms install --client all # 四者都写(默认) ```bash dotnet tool install -g BootstrapBlazor.LLMsDocs.Cli # 1. 装工具 bb-llms install --client claude # 2. 装发现层(写入用户主目录,全局生效) -# 之后在 Claude Code 中让它写/改组件代码时,会自动用 bb-llms 查权威 API +# 之后 agent 可按项目版本查询包内 API;本地缺失时查询官网 ``` --- @@ -193,7 +206,7 @@ bb-llms install --client claude # 2. 装发现层(写入 在 Extentions 仓库根目录执行 CLI 回归检查: ```powershell -.\tools\BootstrapBlazor.LLMsDocs.Cli\tests\Verify-Client.ps1 +dotnet build .\tools\BootstrapBlazor.LLMsDocs.Cli\BootstrapBlazor.LLMsDocs.Cli.csproj -c Release ``` ```bash @@ -218,9 +231,9 @@ bb-llms get Table | 文件 | 对应命令 | |---|---| -| `Templates/instructions.md` | `bb-llms instructions`(粘进 CLAUDE.md / AGENTS.md 的片段)、`bb-llms install --client codex`(写 AGENTS.md) | -| `Templates/SKILL.md` | `bb-llms install --client claude` / `--client trae`(Claude / Trae skill) | -| `Templates/bootstrapblazor.mdc` | `bb-llms install --client cursor`(Cursor 规则) | +| `Templates/instructions.md` | `bb-llms instructions` 和 Codex 的通用片段 | +| `Templates/SKILL.md` | Copilot、Claude、Trae skill | +| `Templates/bootstrapblazor.mdc` | Cursor 规则 | 这些文件以**嵌入资源**编入程序集(见 `.csproj`),因此全局安装后工具仍能在运行时读取到,无需依赖项目源码目录。改完重新 `dotnet build` / `dotnet pack` 即生效。 @@ -230,17 +243,16 @@ bb-llms get Table 本工具刻意做成「瘦客户端」,与文档内容彻底解耦: -- **`bb-llms`(运行时)**:只做「解析源 → 拉取 → 缓存 → 输出」,几乎零迭代。 +- **`bb-llms`(运行时)**:解析项目包和配置源,按需查询、缓存并输出文档。 - **`llms/` 下的 `.txt`(数据)**:由生产者 `LLMsDocsGenerator` 随每次发版更新。 因此装一次工具,新组件 / 新参数会**自动随远程文档更新**,无需重装。 -唯一的隐式契约是 **`llms.txt` 索引行的格式**——只有 `list` / `search` 会解析它 -(`- [Name](components/Name.txt) - 描述` 行 + `### 分类` 标题)。核心命令 `get` / `index` -是纯透传,**与格式无关**,永远不受生产者格式调整影响。换言之: +**`llms.txt` 索引行的格式**是数据命令的契约:`list` / `search` 和 `get` 都会解析它 +(`- [Name](components/Name.txt) - 描述` 行 + `### 分类` 标题)。换言之: - 生产者改了文档**正文**:工具零感知,照常透传。 -- 生产者改了**索引行格式**:只需同步 `LlmsDocsClient` 里的两条正则,`get` 不受影响。 +- 生产者改了**索引行格式**:需同步 `LlmsDocsClient` 的解析规则,否则也可能影响 `get`。 --- diff --git a/tools/BootstrapBlazor.LLMsDocs.Cli/Scaffolder.cs b/tools/BootstrapBlazor.LLMsDocs.Cli/Scaffolder.cs index 8fc037cb..a505fa7e 100644 --- a/tools/BootstrapBlazor.LLMsDocs.Cli/Scaffolder.cs +++ b/tools/BootstrapBlazor.LLMsDocs.Cli/Scaffolder.cs @@ -20,9 +20,7 @@ internal static class Scaffolder public static string GenericSnippet => ReadTemplate("instructions.md"); /// - /// Skill manifest shared by Claude Code (.claude/skills/bootstrapblazor/SKILL.md) - /// and Trae (.trae/skills/bootstrapblazor/SKILL.md): both use the same SKILL.md - /// layout with name/description frontmatter, auto-matched by description. + /// Skill manifest shared by Copilot, Claude Code and Trae. /// public static string SkillMarkdown => ReadTemplate("SKILL.md"); @@ -47,12 +45,13 @@ public static int Install(string client, string? scope, string? target, bool for { var clients = client.ToLowerInvariant() switch { - "all" => new[] { "claude", "cursor", "trae", "codex" }, + "all" => new[] { "copilot", "claude", "cursor", "trae", "codex" }, + "copilot" => ["copilot"], "claude" => ["claude"], "cursor" => ["cursor"], "trae" => ["trae"], "codex" => ["codex"], - _ => throw new ArgumentException($"Unknown client: {client} (expected claude|cursor|trae|codex|all)") + _ => throw new ArgumentException($"Unknown client: {client} (expected copilot|claude|cursor|trae|codex|all)") }; // No explicit --scope defaults to the user home: the tool is installed globally, @@ -73,6 +72,9 @@ public static int Install(string client, string? scope, string? target, bool for { var (path, content) = c switch { + "copilot" => (scopeKey == "user" + ? Path.Combine(baseDir, ".copilot", "skills", "bootstrapblazor", "SKILL.md") + : Path.Combine(baseDir, ".github", "skills", "bootstrapblazor", "SKILL.md"), SkillMarkdown), "claude" => (Path.Combine(baseDir, ".claude", "skills", "bootstrapblazor", "SKILL.md"), SkillMarkdown), "cursor" => (Path.Combine(baseDir, ".cursor", "rules", "bootstrapblazor.mdc"), CursorRule), // Trae skills mirror Claude skills (.trae/skills//SKILL.md, same diff --git a/tools/BootstrapBlazor.LLMsDocs.Cli/Services/LlmsDocsClient.cs b/tools/BootstrapBlazor.LLMsDocs.Cli/Services/LlmsDocsClient.cs index 577668d1..6a6d0240 100644 --- a/tools/BootstrapBlazor.LLMsDocs.Cli/Services/LlmsDocsClient.cs +++ b/tools/BootstrapBlazor.LLMsDocs.Cli/Services/LlmsDocsClient.cs @@ -27,6 +27,11 @@ public sealed partial class LlmsDocsClient : IDisposable private readonly string _cacheRoot; public LlmsDocsClient(string? baseOverride, bool refresh = false, bool noCache = false) + : this(baseOverride, refresh, noCache, false) + { + } + + internal LlmsDocsClient(string? baseOverride, bool refresh, bool noCache, bool isolateOfficialCache) { var raw = !string.IsNullOrWhiteSpace(baseOverride) ? baseOverride! @@ -56,6 +61,10 @@ public LlmsDocsClient(string? baseOverride, bool refresh = false, bool noCache = _cacheRoot = Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "bb-llms"); + if (isolateOfficialCache) + { + _cacheRoot = Path.Combine(_cacheRoot, "official"); + } } /// Human-readable description of the resolved source, for diagnostics. diff --git a/tools/BootstrapBlazor.LLMsDocs.Cli/Services/ProjectDocsClient.cs b/tools/BootstrapBlazor.LLMsDocs.Cli/Services/ProjectDocsClient.cs new file mode 100644 index 00000000..bf74d04b --- /dev/null +++ b/tools/BootstrapBlazor.LLMsDocs.Cli/Services/ProjectDocsClient.cs @@ -0,0 +1,200 @@ +using System.Text; +using System.Text.RegularExpressions; + +namespace BootstrapBlazor.LLMsDocs.Cli.Services; + +internal sealed partial class ProjectDocsClient(LlmsDocsClient fallback, IReadOnlyList packages, bool automatic) : IDisposable +{ + private sealed record LocalEntry(ComponentEntry Entry, string File, PackageDocs Package); + + public async Task GetAsync(string name, CancellationToken ct) + { + var entry = ReadLocalEntries().OrderByDescending(e => e.Package.IsExtension) + .FirstOrDefault(e => e.Entry.Name.Equals(name, StringComparison.OrdinalIgnoreCase)); + if (entry is not null) + { + try + { + var content = await File.ReadAllTextAsync(entry.File, ct); + Console.Error.WriteLine($"Source: {entry.Package.Package} {entry.Package.Version} ({entry.File})"); + return content; + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + Console.Error.WriteLine($"Cannot read local documentation: {ex.Message}"); + } + } + + if (automatic) + { + Console.Error.WriteLine("Local documentation not found; online documentation may differ from the project version."); + } + return await fallback.GetComponentAsync(name, ct); + } + + public async Task IndexAsync(CancellationToken ct) + { + var local = ReadLocalEntries(); + if (local.Count == 0) + { + if (automatic) + { + Console.Error.WriteLine("Local documentation not found; online documentation may differ from the project version."); + } + return await fallback.GetIndexAsync(ct); + } + + var entries = await MergeAsync(local, ct); + var builder = new StringBuilder("# BootstrapBlazor\n"); + foreach (var group in entries.GroupBy(e => e.Category)) + { + builder.Append("\n### ").AppendLine(group.Key); + foreach (var entry in group) + { + builder.Append("- [").Append(entry.Name).Append("](").Append(entry.DocumentPath).Append(')'); + if (entry.Description is not null) + { + builder.Append(" - ").Append(entry.Description); + } + builder.AppendLine(); + } + } + return builder.ToString(); + } + + public async Task> ListAsync(string? query, CancellationToken ct) + { + var local = ReadLocalEntries(); + if (local.Count == 0) + { + if (automatic) + { + Console.Error.WriteLine("Local documentation not found; online documentation may differ from the project version."); + } + return await fallback.ListAsync(query, ct); + } + + var entries = await MergeAsync(local, ct); + return string.IsNullOrWhiteSpace(query) + ? entries + : entries.Where(e => e.Name.Contains(query, StringComparison.OrdinalIgnoreCase) + || (e.Description?.Contains(query, StringComparison.OrdinalIgnoreCase) ?? false)).ToList(); + } + + public async Task> SearchAsync(string query, int limit, CancellationToken ct) + { + if (string.IsNullOrWhiteSpace(query)) + { + return []; + } + + var entries = await ListAsync(query, ct); + return entries.DistinctBy(e => e.DocumentPath, StringComparer.Ordinal) + .OrderBy(e => e.Name.StartsWith(query, StringComparison.OrdinalIgnoreCase) ? 0 : 1) + .ThenBy(e => e.Name, StringComparer.OrdinalIgnoreCase) + .Take(Math.Clamp(limit, 1, 100)).ToList(); + } + + private async Task> MergeAsync(List local, CancellationToken ct) + { + var entries = local.Select(e => e.Entry).ToList(); + var names = entries.Select(e => e.Name).ToHashSet(StringComparer.OrdinalIgnoreCase); + Console.Error.WriteLine($"Source: project packages ({string.Join(", ", packages.Select(p => $"{p.Package} {p.Version}"))})."); + try + { + using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct); + timeout.CancelAfter(TimeSpan.FromSeconds(3)); + var online = await fallback.ListAsync(null, timeout.Token); + var added = false; + foreach (var entry in online) + { + if (!names.Contains(entry.Name)) + { + entries.Add(entry); + added = true; + } + } + if (added) + { + Console.Error.WriteLine("Additional online catalog entries may differ from the project version."); + } + } + catch (Exception ex) when (ex is HttpRequestException or IOException or TaskCanceledException && !ct.IsCancellationRequested) + { + Console.Error.WriteLine($"Online catalog unavailable: {ex.Message}"); + } + return entries; + } + + private List ReadLocalEntries() + { + var entries = new List(); + foreach (var package in packages) + { + try + { + entries.AddRange(ReadPackageEntries(package)); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + Console.Error.WriteLine($"Cannot read {package.Package} index: {ex.Message}"); + } + } + return entries; + } + + private static List ReadPackageEntries(PackageDocs package) + { + var entries = new List(); + var category = package.Package; + var basePath = Path.GetFullPath(package.Directory).TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar; + foreach (var line in File.ReadLines(Path.Combine(package.Directory, "llms.txt"))) + { + var heading = HeadingRegex().Match(line.TrimEnd('\r')); + if (heading.Success) + { + category = heading.Groups["category"].Value.Trim(); + continue; + } + + var match = LinkRegex().Match(line.TrimEnd('\r')); + if (!match.Success) + { + continue; + } + + var relative = match.Groups["path"].Value.Replace('/', Path.DirectorySeparatorChar); + string file; + try + { + file = Path.GetFullPath(relative, basePath); + } + catch (ArgumentException) + { + continue; + } + if (!file.StartsWith(basePath, OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal) || !File.Exists(file)) + { + continue; + } + + var name = match.Groups["name"].Value.Trim(); + var description = match.Groups["description"].Success ? match.Groups["description"].Value.Trim() : null; + var entry = new ComponentEntry(name, string.IsNullOrEmpty(description) ? null : description, category) + { + IsExtension = package.IsExtension, + DocumentPath = $"{(package.IsExtension ? "extensions" : "components")}/{name}.txt" + }; + entries.Add(new LocalEntry(entry, file, package)); + } + return entries; + } + + [GeneratedRegex(@"^###\s+(?.+?)\s*$")] + private static partial Regex HeadingRegex(); + + [GeneratedRegex(@"^- \[(?[^\]]+)\]\((?[^):]+\.txt)\)(?:\s*-\s*(?.*))?$")] + private static partial Regex LinkRegex(); + + public void Dispose() => fallback.Dispose(); +} diff --git a/tools/BootstrapBlazor.LLMsDocs.Cli/Services/ProjectDocsResolver.cs b/tools/BootstrapBlazor.LLMsDocs.Cli/Services/ProjectDocsResolver.cs new file mode 100644 index 00000000..7d25f728 --- /dev/null +++ b/tools/BootstrapBlazor.LLMsDocs.Cli/Services/ProjectDocsResolver.cs @@ -0,0 +1,211 @@ +using System.Text.Json; + +namespace BootstrapBlazor.LLMsDocs.Cli.Services; + +internal sealed record PackageDocs(string Package, string Version, string Directory, bool IsExtension); + +internal static class ProjectDocsResolver +{ + public static IReadOnlyList Resolve(string? project, string? framework) + { + string? projectPath; + try + { + projectPath = FindProject(project); + } + catch (Exception ex) when (string.IsNullOrWhiteSpace(project) && (ex is IOException or UnauthorizedAccessException)) + { + Console.Error.WriteLine($"Cannot discover projects: {ex.Message}; using the configured online source."); + return []; + } + if (projectPath is null) + { + if (!string.IsNullOrWhiteSpace(framework)) + { + throw new InvalidOperationException("No project found; specify --project when using --framework."); + } + return []; + } + + var assetsPath = Path.Combine(Path.GetDirectoryName(projectPath)!, "obj", "project.assets.json"); + if (!File.Exists(assetsPath)) + { + Console.Error.WriteLine($"Project is not restored: {projectPath}; using the configured online source."); + return []; + } + + try + { + return ReadPackages(assetsPath, framework); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or JsonException) + { + Console.Error.WriteLine($"Cannot read {assetsPath}: {ex.Message}; using the configured online source."); + return []; + } + } + + private static IReadOnlyList ReadPackages(string assetsPath, string? framework) + { + using var assets = JsonDocument.Parse(File.ReadAllText(assetsPath)); + var root = assets.RootElement; + if (root.ValueKind != JsonValueKind.Object || + !root.TryGetProperty("targets", out var targets) || targets.ValueKind != JsonValueKind.Object || + !root.TryGetProperty("libraries", out var libraries) || libraries.ValueKind != JsonValueKind.Object || + !root.TryGetProperty("packageFolders", out var packageFolders) || packageFolders.ValueKind != JsonValueKind.Object) + { + throw new JsonException("Missing targets, libraries or packageFolders."); + } + var target = SelectTarget(targets, framework); + if (target.Value.ValueKind != JsonValueKind.Object) + { + throw new JsonException("Invalid target."); + } + var folders = packageFolders.EnumerateObject().Select(p => p.Name).ToArray(); + var packages = new List(); + + foreach (var item in target.Value.EnumerateObject()) + { + var separator = item.Name.LastIndexOf('/'); + if (separator <= 0) + { + continue; + } + + var name = item.Name[..separator]; + var core = name.Equals("BootstrapBlazor", StringComparison.OrdinalIgnoreCase); + if (!core && !name.StartsWith("BootstrapBlazor.", StringComparison.OrdinalIgnoreCase)) + { + continue; + } + + if (!libraries.TryGetProperty(item.Name, out var library) || library.ValueKind != JsonValueKind.Object || + !library.TryGetProperty("type", out var type) || type.ValueKind != JsonValueKind.String || type.GetString() != "package" || + !library.TryGetProperty("path", out var path) || path.ValueKind != JsonValueKind.String) + { + continue; + } + + var packagePath = path.GetString(); + if (string.IsNullOrEmpty(packagePath)) + { + continue; + } + + foreach (var folder in folders) + { + var packageRoot = Path.Combine(folder, packagePath.Replace('/', Path.DirectorySeparatorChar)); + if (!Directory.Exists(packageRoot)) + { + continue; + } + var candidates = core + ? new[] { Path.Combine(packageRoot, "skills", "bb-api", "references"), Path.Combine(packageRoot, "skills", "bootstrapblazor", "references") } + : [Path.Combine(packageRoot, "docs", "llms")]; + var docs = candidates.FirstOrDefault(p => File.Exists(Path.Combine(p, "llms.txt")) + && (!core || File.Exists(Path.Combine(Path.GetDirectoryName(p)!, "SKILL.md")))); + if (docs is not null) + { + packages.Add(new PackageDocs(name, item.Name[(separator + 1)..], docs, !core)); + } + break; + } + } + + return packages; + } + + private static JsonProperty SelectTarget(JsonElement targets, string? framework) + { + var all = targets.EnumerateObject().ToArray(); + if (all.Length == 0) + { + throw new JsonException("No restore targets."); + } + if (!string.IsNullOrWhiteSpace(framework)) + { + var matches = all.Where(t => t.Name.Equals(framework, StringComparison.OrdinalIgnoreCase)).ToArray(); + if (matches.Length != 1) + { + throw new InvalidOperationException($"Target '{framework}' is not in project.assets.json. Available targets: {string.Join(", ", all.Select(t => t.Name))}"); + } + return matches[0]; + } + + if (all.Length != 1) + { + throw new InvalidOperationException($"Select a target with --framework. Available targets: {string.Join(", ", all.Select(t => t.Name))}"); + } + return all[0]; + } + + private static string? FindProject(string? project) + { + if (!string.IsNullOrWhiteSpace(project)) + { + var path = Path.GetFullPath(project); + if (Directory.Exists(path)) + { + var matches = Directory.GetFiles(path, "*.csproj"); + if (matches.Length != 1) + { + throw new InvalidOperationException($"Expected one project in {path}; specify a .csproj with --project."); + } + return matches[0]; + } + + if (!File.Exists(path) || !path.EndsWith(".csproj", StringComparison.OrdinalIgnoreCase)) + { + throw new FileNotFoundException($"Project not found: {path}"); + } + return path; + } + + var cwd = Directory.GetCurrentDirectory(); + for (var directory = new DirectoryInfo(cwd); directory is not null; directory = directory.Parent) + { + var projects = directory.GetFiles("*.csproj"); + if (projects.Length > 1) + { + throw new InvalidOperationException($"Multiple projects in {directory.FullName}; specify --project."); + } + if (projects.Length == 1) + { + return projects[0].FullName; + } + if (Directory.Exists(Path.Combine(directory.FullName, ".git")) || File.Exists(Path.Combine(directory.FullName, ".git"))) + { + break; + } + } + + var descendants = FindProjects(cwd).Take(2).ToArray(); + if (descendants.Length > 1) + { + throw new InvalidOperationException($"Multiple projects under {cwd}; specify --project."); + } + return descendants.FirstOrDefault(); + } + + private static IEnumerable FindProjects(string directory) + { + foreach (var project in Directory.EnumerateFiles(directory, "*.csproj")) + { + yield return project; + } + + foreach (var child in Directory.EnumerateDirectories(directory)) + { + var name = Path.GetFileName(child); + if (name.StartsWith('.') || name is "bin" or "obj" or "node_modules" || + (File.GetAttributes(child) & FileAttributes.ReparsePoint) != 0) + { + continue; + } + foreach (var project in FindProjects(child)) + { + yield return project; + } + } + } +}