diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..59e1c7f --- /dev/null +++ b/.gitattributes @@ -0,0 +1,3 @@ +# Generated agent-plugin MCP server bundle. Rebuilt by `npm run build`; CI +# fails if the committed copy is stale. Keep bytes exact on every platform. +plugin/server/llmwiki-mcp.cjs -text linguist-generated=true diff --git a/.github/plugin/marketplace.json b/.github/plugin/marketplace.json new file mode 100644 index 0000000..baa2387 --- /dev/null +++ b/.github/plugin/marketplace.json @@ -0,0 +1,22 @@ +{ + "name": "llmwiki", + "owner": { + "name": "Microsoft" + }, + "metadata": { + "description": "Agent plugin for LLM Wiki, a personal knowledge base that your agent maintains.", + "version": "1.0.1" + }, + "plugins": [ + { + "name": "llmwiki", + "description": "Skills to ask, research, ingest, save and fix an LLM Wiki, a Wiki Librarian agent, and the LLM Wiki MCP server.", + "version": "1.0.1", + "source": "./plugin", + "homepage": "https://github.com/microsoft/llmwiki#readme", + "repository": "https://github.com/microsoft/llmwiki", + "license": "MIT", + "keywords": ["wiki", "knowledge-base", "mcp", "markdown", "skills"] + } + ] +} diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index a31aa0d..401967e 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -31,6 +31,13 @@ jobs: - name: Build VS Code extension run: npm run build --workspace=packages/vscode + - name: Check the committed plugin server bundle is up to date + run: | + if ! git diff --exit-code --stat -- plugin/server/; then + echo "::error::plugin/server/llmwiki-mcp.cjs is stale. Run 'npm run build' and commit the result." + exit 1 + fi + - name: Lint core run: npm run lint --workspace=packages/core diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index c818ddf..b5b6351 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -87,6 +87,7 @@ llmwiki/ │ │ │ ├── index.ts # Barrel export │ │ │ ├── constants.ts # API_VERSION │ │ │ ├── errors.ts # isNotFoundError, isPermissionError +│ │ │ ├── lock.ts # withWikiLock (cross-process wiki write lock) │ │ │ ├── wiki.ts # readPage, writePage, listPages, getPageLinks, │ │ │ │ # directoryExists, createEntityPage, │ │ │ │ # createConceptPage, addCrosslinks @@ -102,13 +103,21 @@ llmwiki/ │ │ │ ├── ingest.ts # ingestSource (single-file ingest) │ │ │ ├── ingest-context.ts # ingestWithContext (enriched response) │ │ │ ├── bulk-ingest.ts # bulkIngest (batch ingest helper) +│ │ │ ├── fix.ts # fixWiki (orphaned derived pages + lintFix in one pass) │ │ │ ├── query.ts # queryWiki, slugifyQuery (weighted search) │ │ │ ├── status.ts # getWikiStatus (aggregate statistics) │ │ │ └── mcp/ │ │ │ ├── index.ts # Barrel export │ │ │ ├── server.ts # createMcpServer — registers tools, dispatches -│ │ │ ├── read-tools.ts # 7 read-only tools -│ │ │ ├── write-tools.ts # 7 write tools +│ │ │ ├── read-tools.ts # 7 read-only tools (+ ToolDefinition/annotations types) +│ │ │ ├── write-tools.ts # 9 write tools (incl. wiki_fix, wiki_delete_page) +│ │ │ ├── workspace-tools.ts # wiki_open, wiki_init (discovery mode only) +│ │ │ ├── wiki-root.ts # WikiRootState — fixed root or discovery (roots, cwd, open) +│ │ │ ├── instructions.ts # Server instructions (+ the wiki's AGENTS.md) +│ │ │ ├── schemas.ts # Output schemas for structured tool results +│ │ │ ├── completions.ts # Argument completions for templates and prompts +│ │ │ ├── resources.ts # resource://wiki/* resources and templates +│ │ │ ├── prompts.ts # Prompt templates (ingest, lint, research) │ │ │ └── bin.ts # llmwiki-mcp stdio launcher (shebang + StdioServerTransport) │ │ ├── package.json # @llmwiki/core (bin: llmwiki-mcp) │ │ └── tsconfig.json @@ -116,23 +125,34 @@ llmwiki/ │ └── vscode/ # llmwiki — VS Code extension │ ├── src/ │ │ ├── extension.ts # activate/deactivate — wires providers & watchers -│ │ ├── commands.ts # Command handlers (init, ingest, query, status, …) +│ │ ├── commands.ts # Command handlers (init, ingest, query, status, lint, fix, …) │ │ ├── llmIngest.ts # LM API enrichment pipeline for single-file ingest │ │ ├── statusBar.ts # StatusBarManager — debounced live page count │ │ ├── wikiPagesTree.ts # WikiPagesTreeDataProvider (Entities/Concepts/Sources) │ │ ├── rawSourcesTree.ts # RawSourcesTreeDataProvider (raw/ browser) │ │ ├── backlinksTree.ts # BacklinksTreeDataProvider (reverse links) │ │ ├── lintFindingsTree.ts # LintFindingsTreeDataProvider (severity-grouped) -│ │ ├── mcpProvider.ts # vscode.lm.registerMcpServerDefinitionProvider → llmwiki-mcp -│ │ └── chatParticipant.ts # @wiki chat participant (/status, /save, /lint, /fix) -│ ├── package.json # VS Code extension manifest -│ └── esbuild.config.mjs # CJS bundle, external: ['vscode'] +│ │ └── mcpProvider.ts # vscode.lm.registerMcpServerDefinitionProvider → llmwiki-mcp +│ ├── package.json # VS Code extension manifest (incl. chatSkills/chatAgents/chatInstructions) +│ └── esbuild.config.mjs # CJS bundles + plugin server bundle + copies chat customizations +│ +├── plugin/ # Agent plugin (Agent Plugins 1.0) +│ ├── plugin.json # Manifest +│ ├── mcp.json # Starts server/llmwiki-mcp.cjs with node +│ ├── server/llmwiki-mcp.cjs # Generated, committed MCP server bundle +│ ├── skills/ # wiki-ask, wiki-research, wiki-ingest, wiki-save, wiki-fix +│ └── com.github.copilot/ +│ ├── agents/ # wiki-librarian.agent.md +│ └── rules/ # llmwiki.instructions.md (applyTo .wiki/**) │ ├── tests/ │ ├── shared/ # Shared library tests (incl. mcp/) │ ├── vscode/ # Extension tests (mocked vscode module) +│ │ └── integration/ # Real VS Code tests (npm run test:integration) +│ ├── plugin/ # Plugin validation + stdio e2e of the bundle │ └── fixtures/ # Test fixture data ├── .github/ +│ ├── plugin/marketplace.json # Marketplace index for the agent plugin │ └── workflows/ │ └── ci.yml # CI — lint, build, test on push/PR to main ├── package.json # Workspace root — workspaces: @@ -236,7 +256,7 @@ Activity Bar: "LLM Wiki" ($(book) icon) │ └── Lint Findings (lintFindingsTree.ts) └── LintFindingsTreeDataProvider - ├── Populated by llmwiki.lint via setFindings() + ├── Populated by llmwiki.lint, llmwiki.fix and llmwiki.refresh via setFindings() ├── Groups by severity (Errors → Warnings → Info) └── Click to open the affected file ``` @@ -252,9 +272,11 @@ Activity Bar: "LLM Wiki" ($(book) icon) | `llmwiki.openPage` | Command palette | Quick pick from index entries → opens selected page | | `llmwiki.search` | Command palette | Filter entities/concepts by title, summary, or tag | | `llmwiki.searchRaw` | Command palette | Find a raw source file by name | -| `llmwiki.refresh` | Command palette | Runs lint-fix, prunes orphans, refreshes trees | -| `llmwiki.fix` | Lint Findings view | Opens `@wiki /fix` chat to interactively resolve findings | -| `llmwiki.removeSource` | Raw Sources context menu | Deletes a raw source plus pages derived from it | +| `llmwiki.refresh` | Command palette | Runs `fixWiki` (prunes orphaned pages, lint-fix), refreshes trees | +| `llmwiki.lint` | Palette / Lint Findings view | Runs `lintWiki` and shows the findings in the Lint Findings view | +| `llmwiki.fix` | Raw Sources / Lint Findings views | Runs `fixWiki` with progress; remaining findings go to the Lint Findings view with a **Fix with Copilot** action | +| `llmwiki.fixWithCopilot` | Lint Findings view / notifications | Opens Copilot Chat with the `/wiki-fix` skill | +| `llmwiki.removeSource` | Raw Sources context menu | Deletes a raw source, its summary page, and pages derived only from it (`removeSourcePages`) | ### Bulk Ingest @@ -299,14 +321,15 @@ withProgress (Notification) → for each file: - **Auto-refresh:** file system watchers on `wiki/**/*.md` and `raw/**` with 300ms debounce - **Uninitialized state:** shows "Wiki: Not initialized" -### Chat Participant (`@wiki`) +### Copilot Chat Integration + +The extension has no chat participant (VS Code deprecated the Chat Participant API and the Copilot harness doesn't run participants). It integrates with Copilot Chat through: -The extension contributes a chat participant for GitHub Copilot Chat: +- **The MCP server** — registered by `mcpProvider.ts`; answers questions and edits the wiki through annotated tools, with server instructions that include the wiki's `AGENTS.md`. +- **Skills, a custom agent and instructions** — contributed through `chatSkills`, `chatAgents` and `chatInstructions` (gated on `llmwiki.isWikiWorkspace`). They are authored once in `plugin/` and copied to `out/chat/` by `esbuild.config.mjs`, so the extension and the agent plugin always ship the same content. +- **Commands** — `llmwiki.fixWithCopilot` opens chat with `/wiki-fix` after **Fix Issues** has applied the deterministic fixes. -- `@wiki /status` — show wiki statistics. -- `@wiki /save` — save the previous answer as a wiki page. -- `@wiki /lint` — run health checks and get fix suggestions. -- `@wiki /fix` — auto-fix lint issues using the LLM. +The Language Model API is still used directly for ingestion enrichment (`llmIngest.ts`), which runs outside chat. ### Bundling @@ -318,7 +341,7 @@ The MCP server lives in `@llmwiki/core` and exposes wiki operations via the [Mod ### Launcher (`llmwiki-mcp`) -`packages/core/src/mcp/bin.ts` is the executable entry point declared in the package `bin` field. It accepts a single argument — the path to a wiki root (defaulting to `./.wiki`) — validates the directory exists, builds a server via `createMcpServer({ wikiRoot })`, and connects it to a `StdioServerTransport`. The CJS bundle output is `dist/mcp/bin.js` with a Node shebang preserved by tsc. +`packages/core/src/mcp/bin.ts` is the executable entry point declared in the package `bin` field. It takes the wiki root from its single argument or the `LLMWIKI_ROOT` environment variable, validates the directory exists, builds a server via `createMcpServer({ wikiRoot })`, and connects it to a `StdioServerTransport`. With neither, it starts in discovery mode (`createMcpServer({ cwd })`). The output is `dist/mcp/bin.js` with a Node shebang preserved by tsc. Once `@llmwiki/core` is installed, the launcher is invoked as: @@ -326,11 +349,30 @@ Once `@llmwiki/core` is installed, the launcher is invoked as: npx llmwiki-mcp ./.wiki ``` -This is what `mcp.json` entries (Claude Desktop, Cursor, `.vscode/mcp.json`) point at. +This is what `mcp.json` entries (Claude Desktop, Cursor, `.vscode/mcp.json`, `.mcp.json`) point at. The same launcher is bundled into `out/mcp-server.cjs` (VSIX) and `plugin/server/llmwiki-mcp.cjs` (agent plugin). + +### Locating the Wiki + +`WikiRootState` (`mcp/wiki-root.ts`) decides which wiki the server works on: + +- **Bound** — a root from the argument or `LLMWIKI_ROOT`. Only that wiki is used; `wiki_open`/`wiki_init` are not offered. +- **Discovery** — no root given. If `/.wiki` exists when the server starts, it is used (and its `AGENTS.md` goes into the instructions). Otherwise, on the first tool call the server checks the client's workspace roots (MCP `roots/list`; a wiki found this way is re-discovered after `roots/list_changed`). Agents can also select a wiki with `wiki_open` or create one with `wiki_init`. Agent plugin clients start servers in the plugin folder and may report no roots, so the plugin's skills call `wiki_open` with the workspace folder when needed. + +A folder counts as a wiki when `.wiki/wiki/` exists. `initWiki` and the extension use the same test, so a wiki whose `index.md` is missing still opens, and `wiki_fix` can rebuild the index. + +Tool calls made before a wiki is found return an error that tells the agent how to open one. + +### Server Metadata + +- **Tool annotations and titles** — read tools set `readOnlyHint` (VS Code skips the confirmation prompt); tools that overwrite or delete content set `destructiveHint`; all tools set `openWorldHint: false`. +- **Structured output** — `wiki_status`, `wiki_query`, `wiki_lint` and `wiki_fix` declare an `outputSchema` (`mcp/schemas.ts`) and return matching `structuredContent` alongside the JSON text. +- **Instructions** — `mcp/instructions.ts` explains the wiki layout and workflows; when the root is known at startup, the wiki's `AGENTS.md` is appended (capped at 12,000 characters). +- **Completions** — page paths for `resource://wiki/pages/{path}`, source paths for `resource://wiki/sources/{path}`, `raw/` paths for the `ingest-and-integrate` prompt, and index titles for `research-topic`. +- **Server info** — name, title, version (`CORE_VERSION`, kept in sync with `package.json` by a test), website and icon. ### VS Code Auto-Registration -`packages/vscode/src/mcpProvider.ts` calls `vscode.lm.registerMcpServerDefinitionProvider` (stable API, requires VS Code ≥ 1.101) to advertise the launcher to Copilot automatically when a `.wiki` workspace is detected. The provider resolves `@llmwiki/core/mcp-bin` via `require.resolve`, builds a `vscode.McpStdioServerDefinition` pointing at `process.execPath `, and exposes it under the id `llmwiki`. No `mcp.json` is required for the VS Code path. +`packages/vscode/src/mcpProvider.ts` calls `vscode.lm.registerMcpServerDefinitionProvider` (stable API since VS Code 1.101) to advertise the launcher to Copilot automatically when a `.wiki` workspace is detected. The provider uses the bundled `out/mcp-server.cjs` (falling back to `@llmwiki/core/mcp-bin` in a dev checkout), builds a `vscode.McpStdioServerDefinition` pointing at `process.execPath ` with `ELECTRON_RUN_AS_NODE=1` (so the editor binary runs as Node even when the spawning process, such as the Agent Host, doesn't set it), and exposes it under the id `llmwiki`. No `mcp.json` is required for the VS Code path. ### Tool Inventory @@ -344,12 +386,16 @@ This is what `mcp.json` entries (Claude Desktop, Cursor, `.vscode/mcp.json`) poi | `wiki_read_page` | Read | Single page content by path | | `wiki_read_index` | Read | All index entries | | `wiki_write_page` | Write | Create/overwrite page with auto-index | -| `wiki_create_entity` | Write | Create entity page at `entities/{slug}.md` | -| `wiki_create_concept` | Write | Create concept page at `concepts/{slug}.md` | +| `wiki_create_entity` | Write | Create entity page at `entities/{slug}.md` (optional `sources` provenance) | +| `wiki_create_concept` | Write | Create concept page at `concepts/{slug}.md` (optional `sources` provenance) | | `wiki_update_page` | Write | Merge partial updates into existing page | | `wiki_add_crosslinks` | Write | Add "See also" section with validated links | | `wiki_update_index` | Write | Update index entry metadata | -| `wiki_ingest_with_context` | Write | Ingest source with context-rich response | +| `wiki_ingest_with_context` | Write | Ingest source (path relative to the wiki root) with context-rich response | +| `wiki_fix` | Write | Deterministic fixes via `fixWiki`, with `dryRun` preview | +| `wiki_delete_page` | Write | Delete a page and its index entry; reports remaining backlinks | +| `wiki_open` | Workspace | Select the wiki by path (discovery mode only) | +| `wiki_init` | Workspace | Create a wiki in a project folder (discovery mode only) | ### MCP Data Flow @@ -365,7 +411,7 @@ External LLM Agent ├─────────┬───────────┤ │ Read │ Write │ │ Tools │ Tools │ -│ (7) │ (7) │ +│ (7) │ (9) │ └────┬────┴────┬──────┘ │ │ ▼ ▼ @@ -388,6 +434,9 @@ External LLM Agent - **Input validation:** All required fields are checked for non-empty strings; arrays are validated for correct element types. - **Empty slug/title rejection:** Tools reject empty or whitespace-only slug and title arguments. - **Index injection prevention:** Index updates use an upsert (find-or-replace) pattern to prevent duplicate entries. +- **Protected files:** `wiki_delete_page` refuses `index.md`, `log.md` (in any letter case) and non-markdown files. `deletePage` checks the path again after resolving symlinked folders, so a link such as `wiki/linked -> ../raw` can't be used to delete files outside the wiki. +- **Concurrent writes:** every read-modify-write of a page or `index.md` (ingest, `upsertDerivedPage`, crosslinks, `wiki_update_page`, index updates, fixes and source cleanup) runs under the wiki write lock (`withWikiLock` in `lock.ts`). The lock is a `wiki/.llmwiki.lock` file, so the extension and every MCP server process share it. It is re-entrant within one call chain, and a lock left by a crashed process is broken after 10 seconds. +- **Provenance:** `sources` / `addSources` must name existing summary pages under `sources/`. Only such entries take part in cleanup: a page is deleted as orphaned when every one of them is definitely missing (`ENOENT`), and other entries (raw paths, URLs) count as present. Pages without `sources` are never deleted automatically, and the extension's LLM ingest extends existing pages instead of overwriting them. - **Error isolation:** Each tool call is wrapped in try/catch, returning `isError: true` on failure without crashing the server. ## Data Flow @@ -455,7 +504,7 @@ Human runs llmwiki.query and supplies search terms ### Lint Flow ``` -llmwiki.lint or @wiki /lint +llmwiki.lint, llmwiki.fix, or the wiki_lint / wiki_fix MCP tools │ ▼ ┌─────────────────┐ @@ -481,7 +530,7 @@ llmwiki.lint or @wiki /lint ### CI (`ci.yml`) -Runs on every push and pull request to `main`. Executes lint (`tsc --noEmit`), build, and test (`vitest run` with coverage) for `@llmwiki/core` and the VS Code extension on Node.js 20. +Runs on every push and pull request to `main`. Executes lint (`tsc --noEmit`), build, and test (`vitest run` with coverage) for `@llmwiki/core` and the VS Code extension on Node.js 20, and fails if the committed `plugin/server/llmwiki-mcp.cjs` differs from a fresh build. ## Module Dependencies @@ -506,7 +555,7 @@ Runs on every push and pull request to `main`. Executes lint (`tsc --noEmit`), b ``` extension.ts - └─► commands.ts ──► @llmwiki/core (readIndex, directoryExists, lintWiki, + └─► commands.ts ──► @llmwiki/core (readIndex, directoryExists, lintWiki, fixWiki, │ appendEntry, ingestSource, queryWiki, getWikiStatus) │ └─► llmIngest.ts (LM API enrichment) └─► wikiPagesTree.ts ──► @llmwiki/core (readIndex) @@ -514,26 +563,27 @@ extension.ts └─► backlinksTree.ts ──► @llmwiki/core (getBacklinks) └─► lintFindingsTree.ts ──► @llmwiki/core (LintFinding type) └─► statusBar.ts ──► @llmwiki/core (directoryExists, getWikiStatus) - └─► chatParticipant.ts ──► @llmwiki/core (queryWiki, lintWiki, writePage, …) └─► mcpProvider.ts ──► vscode.lm.registerMcpServerDefinitionProvider - (spawns `@llmwiki/core/mcp-bin` over stdio) + (spawns out/mcp-server.cjs over stdio) ``` ### Shared Library Modules | Module | Exports | Purpose | |--------|---------|---------| -| `constants.ts` | `API_VERSION` | API version string (`'1'`) included in MCP JSON output. | +| `constants.ts` | `API_VERSION`, `WIKI_DIR_NAME`, `CORE_VERSION` | API version string (`'1'`) included in MCP JSON output, the `.wiki` directory name, and the package version reported by the MCP server. | | `errors.ts` | `isNotFoundError`, `isPermissionError` | Error classification guards for ENOENT and EACCES. | +| `lock.ts` | `withWikiLock` | Runs a read-modify-write of pages or `index.md` under the wiki write lock: a `wiki/.llmwiki.lock` file shared by the extension and MCP server processes, re-entrant within one call chain, and broken when stale. | | `wiki.ts` | `readPage`, `writePage`, `listPages`, `getPageLinks`, `directoryExists`, `createEntityPage`, `createConceptPage`, `addCrosslinks` | Read/write wiki pages with gray-matter frontmatter. List `.md` files recursively. Extract internal markdown links. Create typed pages with auto-index registration. Append cross-reference links. | | `index-ops.ts` | `readIndex`, `writeIndex`, `addEntry`, `removeEntry`, `findEntries`, `updateIndexEntry` | Parse and serialize the categorized `index.md` format. CRUD operations on index entries including partial metadata updates. | | `log.ts` | `appendEntry`, `readLog`, `getRecentEntries` | Append timestamped entries to `log.md`. Parse log entries. Retrieve recent entries. | | `sources.ts` | `listSources` | List all files in `raw/` with metadata (name, path, size, modified, extension). | | `backlinks.ts` | `getBacklinks` | Find all pages containing links to a target page via link resolution. | -| `lint.ts` | `lintWiki` | Run 6 health-check categories (including frontmatter-validation) and return structured `LintResult`. | +| `lint.ts` | `lintWiki`, `lintFix` | Run 6 health-check categories (including frontmatter-validation) and return structured `LintResult`; `lintFix` applies the deterministic fixes (with an optional `dryRun`). | +| `fix.ts` | `fixWiki`, `findOrphanedDerivedPages`, `removeSourcePages` | One pass of every deterministic fix: delete entity/concept pages whose sources were all removed, then `lintFix` with orphan indexing. Used by the extension's Fix Issues/Refresh commands and the `wiki_fix` tool. `removeSourcePages` deletes a removed source's summary and the pages left with no existing source (Remove Source and the `raw/` deletion watcher). | | `utils.ts` | `slugify`, `excerpt` | Slugify filenames for wiki paths. Extract text excerpts with configurable max length. | | `search.ts` | `countOccurrences` | Case-insensitive substring occurrence counting for query scoring. | -| `init.ts` | `initWiki` | Initialize a wiki: create directory structure, index, log, and AGENTS.md template. | +| `init.ts` | `initWiki`, `isWikiInitialized` | Initialize a wiki: create directory structure, index, log, and AGENTS.md template. `isWikiInitialized` (a `wiki/` folder exists) is also what MCP discovery checks. | | `ingest.ts` | `ingestSource` | Ingest a single source file with duplicate detection. | | `ingest-context.ts` | `ingestWithContext` | Ingest a source with enriched context: word count, content type detection, related pages, follow-up actions. Used by `wiki_ingest_with_context`. | | `bulk-ingest.ts` | `bulkIngest` | Batch ingest all files from `raw/`, with progress callbacks and per-file status tracking. | @@ -554,7 +604,7 @@ extension.ts ### Why a VS Code extension as the only UI? - **Primary editor.** Most wiki users already work in VS Code. A native extension removes context-switching between terminal and editor. -- **Rich interaction.** Tree views, quick picks, the status bar, and the `@wiki` chat participant provide discovery and navigation that a CLI cannot match. +- **Rich interaction.** Tree views, quick picks, the status bar, and Copilot Chat skills backed by the wiki's MCP server provide discovery and navigation that a CLI cannot match. - **LM API built in.** The extension uses VS Code's Language Model API for ingestion enrichment, with no extra credentials or HTTP wiring. - **Single surface.** Concentrating on one client keeps the shared library focused and the test surface small. diff --git a/README.md b/README.md index c93d2a5..a7e3174 100644 --- a/README.md +++ b/README.md @@ -13,9 +13,9 @@ You never write the wiki yourself. You curate sources, ask questions, and think. ## Example interface -![LLM Wiki running in VS Code — tree views for entities, concepts, raw sources, and backlinks on the left, a wiki page in the editor, and the @wiki chat participant answering a cross-document question on the right.](docs/images/interface.png) +![LLM Wiki running in VS Code — the LLM Wiki sidebar with Entities, Concepts, Raw Sources, Backlinks, and Lint Findings views on the left, a wiki page in the editor, and Copilot Chat on the right answering "/wiki-ask Is JWST a replacement for Hubble?" by calling the LLM Wiki MCP tools and citing the wiki pages it used.](docs/images/interface.png) -The LLM Wiki sidebar surfaces **Entities**, **Concepts**, **Raw Sources**, and **Backlinks** tree views. The generated wiki pages open in the editor, and the `@wiki` chat participant answers questions that synthesize across multiple sources. +The LLM Wiki sidebar surfaces **Entities**, **Concepts**, **Raw Sources**, **Backlinks**, and **Lint Findings** tree views, and the generated wiki pages open in the editor. In Copilot Chat, the `/wiki-ask` skill answers questions that synthesize across sources: it searches and reads the wiki through the LLM Wiki MCP tools (`wiki_query`, `wiki_read_page`) and links its answer to the pages it used. ## Architecture @@ -35,8 +35,10 @@ The project is an npm workspaces monorepo with two packages: | Package | npm name | Description | |---------|----------|-------------| -| [packages/core](packages/core) | `@llmwiki/core` | Core wiki operations + MCP server — page I/O, index parsing, log management, lint checks, MCP tool server, ingest pipeline, bulk ingest, search, status. | -| [packages/vscode](packages/vscode) | `llmwiki` | VS Code extension — tree views, command palette, status bar, `@wiki` chat participant, bulk ingest of files and folders. | +| [packages/core](packages/core) | `@llmwiki/core` | Core wiki operations + MCP server — page I/O, index parsing, log management, lint checks and fixes, MCP tool server, ingest pipeline, bulk ingest, search, status. | +| [packages/vscode](packages/vscode) | `llmwiki` | VS Code extension — tree views, command palette, status bar, Copilot skills and the Wiki Librarian agent, bulk ingest of files and folders. | + +The repository also contains an [agent plugin](plugin) (`plugin/`) that packages the same skills and agent with a self-contained MCP server for GitHub Copilot CLI, the GitHub Copilot app, and other Agent Plugins clients. ``` llmwiki (VS Code extension) ──depends-on──▶ @llmwiki/core @@ -45,7 +47,7 @@ llmwiki (VS Code extension) ──depends-on──▶ @llmwiki/core ## Prerequisites - [Node.js](https://nodejs.org/) v20 or later -- [VS Code](https://code.visualstudio.com/) 1.101 or later +- [VS Code](https://code.visualstudio.com/) 1.109 or later - A GitHub Copilot subscription (the extension uses VS Code's Language Model API for ingestion enrichment) ## Installation @@ -75,6 +77,7 @@ Open the **LLM Wiki** icon in the Activity Bar to access: - **Concepts** — Browse concept pages (ideas, techniques, patterns). - **Raw Sources** — See every file in `raw/` with size & date; right-click to remove. - **Backlinks** — See pages that link to the page you currently have open. +- **Lint Findings** — Health-check results grouped by severity; click one to open the page. ### Commands @@ -88,10 +91,12 @@ Open the **LLM Wiki** icon in the Activity Bar to access: | `llmwiki.search` | LLM Wiki: Search Wiki | Filter entities/concepts by title, summary, or tag. | | `llmwiki.searchRaw` | LLM Wiki: Search Sources | Find a raw source file by name. | | `llmwiki.refresh` | LLM Wiki: Refresh | Run lint-fix, prune orphaned pages, and refresh all views. | -| `llmwiki.fix` | LLM Wiki: Fix Issues | Open the `@wiki /fix` chat to interactively resolve lint findings. | -| `llmwiki.removeSource` | LLM Wiki: Remove Source | Delete a raw source plus the wiki pages derived from it. | +| `llmwiki.lint` | LLM Wiki: Run Lint | Run health checks and show the results in the Lint Findings view. | +| `llmwiki.fix` | LLM Wiki: Fix Issues | Apply the deterministic fixes (stale index entries, unindexed pages, missing frontmatter, pages whose sources were removed) and list what still needs judgment in Lint Findings. | +| `llmwiki.fixWithCopilot` | LLM Wiki: Fix Remaining Issues with Copilot | Open Copilot Chat with the `/wiki-fix` skill to resolve the remaining findings. | +| `llmwiki.removeSource` | LLM Wiki: Remove Source | Delete a raw source, its summary page, and the wiki pages derived only from it (pages that also draw on another source are kept). | | `llmwiki.scanRaw` | LLM Wiki: Scan Sources for New Files | Scan `raw/` for files that have no wiki page yet and offer to ingest them. | -| `llmwiki.selectModel` | LLM Wiki: Select Model | Choose which installed GitHub Copilot model family powers ingestion enrichment and `@wiki`. | +| `llmwiki.selectModel` | LLM Wiki: Select Model | Choose which installed GitHub Copilot model family powers LLM-powered ingestion. | ### Bulk Ingest @@ -104,29 +109,69 @@ The **LLM Wiki: Ingest Files or Folder** command supports four invocation modes: When a folder is selected the extension walks it recursively, skipping `.`-prefixed entries and common build directories (`node_modules`, `dist`, `out`, `build`, `.wiki`). External files are copied into `/.wiki/raw/` first, then sent through the per-file ingestion pipeline. Selecting more than 20 files triggers a confirmation prompt so you don't kick off a huge batch by accident. -### `@wiki` Chat Participant +### Copilot Chat: skills and the Wiki Librarian agent + +The extension contributes Copilot customizations that work in the Copilot harness (which VS Code 1.142 began rolling out as the default for new chat sessions) as well as the Local harness. They are available in workspaces that contain a wiki. + +- **Just ask.** In Agent mode, questions about your wiki are answered through the LLM Wiki MCP tools, which the extension registers automatically. Read-only tools are annotated as such, so they run without confirmation prompts. +- **Skills** (type `/` in chat): + + | Skill | Use it to | + |-------|-----------| + | `/wiki-ask` | Answer a question from the wiki and cite the pages used. Copilot also loads it automatically for wiki questions. | + | `/wiki-research` | Synthesize everything the wiki knows about a topic and list knowledge gaps. Also loaded automatically. | + | `/wiki-ingest` | Ingest a source and integrate it: summary, entities, concepts, crosslinks, health check. Also loaded automatically. | + | `/wiki-save` | Save the previous answer as a page under `wiki/queries/`. Runs only when you invoke it. | + | `/wiki-fix` | Apply the deterministic fixes, then resolve broken links and other findings that need judgment, asking before deleting anything. Runs only when you invoke it. | -Open the Chat view and type `@wiki` to converse with the wiki via GitHub Copilot: +- **Wiki Librarian** — a custom agent in the agent picker for longer sessions with the wiki. +- **Instructions** — guidance applied whenever chat works with files under `.wiki/`. -- `@wiki /status` — show wiki statistics. -- `@wiki /save` — save the previous answer as a wiki page. -- `@wiki /lint` — run health checks and get fix suggestions. -- `@wiki /fix` — auto-fix lint issues using the LLM. +#### Migrating from `@wiki` + +VS Code [deprecated chat participants](https://code.visualstudio.com/api/extension-guides/ai/chat), and they don't run in the Copilot harness, so the `@wiki` participant has been removed. + +| Before | Now | +|--------|-----| +| `@wiki ` | Ask in Agent mode, or use `/wiki-ask ` | +| `@wiki /status` | The status bar item, **LLM Wiki: Show Status**, or the `wiki_status` tool | +| `@wiki /lint` | **LLM Wiki: Run Lint** (results in the Lint Findings view) or the `wiki_lint` tool | +| `@wiki /fix` | **LLM Wiki: Fix Issues** for the deterministic fixes, then `/wiki-fix` (or **Fix with Copilot**) for the rest | +| `@wiki /save` | `/wiki-save [title]` (previously only suggested a path) | ### Settings | Setting | Default | Description | |---------|---------|-------------| -| `llmwiki.modelFamily` | `claude-opus-4.6` | Preferred GitHub Copilot model family for ingestion enrichment and the `@wiki` chat participant. Falls back to any available Copilot model when the requested family isn't installed; leave blank to always use the first available model. Run **LLM Wiki: Select Model** to pick one interactively. | +| `llmwiki.modelFamily` | `claude-opus-4.6` | Preferred GitHub Copilot model family for LLM-powered ingestion. Falls back to any available Copilot model when the requested family isn't installed; leave blank to always use the first available model. Run **LLM Wiki: Select Model** to pick one interactively. | ## MCP Server -The `@llmwiki/core` package also exposes a Model Context Protocol server so external agents (Claude Desktop, Cursor, VS Code Copilot via MCP, etc.) can read, write, and maintain wiki content programmatically. +The `@llmwiki/core` package also exposes a Model Context Protocol server so external agents (Claude Desktop, Cursor, VS Code Copilot via MCP, Copilot CLI, etc.) can read, write, and maintain wiki content programmatically. + +Every tool declares a title and [annotations](https://modelcontextprotocol.io/specification/2025-11-25/server/tools#tool-annotations): read-only tools are marked `readOnlyHint`, so VS Code runs them without a confirmation prompt, and tools that overwrite or delete content are marked `destructiveHint`. The server also sends **instructions** that explain how to use the wiki, followed by the wiki's own `AGENTS.md` schema. ### Connecting from VS Code (automatic) If you have the LLM Wiki VS Code extension installed, the MCP server registers itself automatically through VS Code's `mcpServerDefinitionProviders` contribution. No JSON to edit — just initialize a wiki (`LLM Wiki: Initialize Wiki`) and the `LLM Wiki` server will appear in the Copilot MCP server list. The launcher is started on demand using the editor's bundled Node. +### Copilot CLI, the GitHub Copilot app, and other agent plugin clients + +The [agent plugin](plugin) bundles the skills, the Wiki Librarian agent, and a self-contained MCP server (it needs Node.js 20+ on `PATH`): + +```bash +copilot plugin install microsoft/llmwiki:plugin +# or, through the marketplace index in this repository: +copilot plugin marketplace add microsoft/llmwiki +copilot plugin install llmwiki@llmwiki +``` + +Plugin skills are prefixed with the plugin name, for example `/llmwiki:wiki-ask`. In VS Code, install the extension rather than the plugin; it contributes the same skills and agent. + +### How the server finds the wiki + +`llmwiki-mcp [wiki-root]` uses the wiki root (the `.wiki` directory) given as its argument or in the `LLMWIKI_ROOT` environment variable, and works only on that wiki. Without either, it uses `/.wiki` if that exists when it starts; otherwise it looks in the client's workspace roots on the first tool call. In that mode it also offers two more tools: `wiki_open` selects a wiki by path, and `wiki_init` creates one. This is how the plugin works, because plugin servers start in the plugin folder. + ### Connecting from Claude Desktop / Cursor / other MCP clients The shared package ships an `llmwiki-mcp` stdio launcher. Add it to your client's MCP configuration: @@ -144,11 +189,24 @@ The shared package ships an `llmwiki-mcp` stdio launcher. Add it to your client' } ``` -If you've installed `@llmwiki/core` globally (`npm i -g @llmwiki/core`), you can use `llmwiki-mcp` directly as the command instead of going through `npx`. The wiki-root argument is optional; when omitted the launcher defaults to `/.wiki`. +If you've installed `@llmwiki/core` globally (`npm i -g @llmwiki/core`), you can use `llmwiki-mcp` directly as the command instead of going through `npx`. Without npm, point the client at the self-contained bundle in a clone of this repository: `"command": "node", "args": ["/path/to/llmwiki/plugin/server/llmwiki-mcp.cjs", "/absolute/path/to/your-project/.wiki"]`. -### Manual JSON config in VS Code +### Manual JSON config -If you'd rather pin the server in a workspace, add a `.vscode/mcp.json`: +To pin the server in a workspace for the Copilot harness and Copilot CLI, add a `.mcp.json` at the workspace root: + +```jsonc +{ + "mcpServers": { + "llmwiki": { + "command": "npx", + "args": ["-y", "-p", "@llmwiki/core", "llmwiki-mcp", ".wiki"] + } + } +} +``` + +For the Local harness in VS Code, use `.vscode/mcp.json`: ```jsonc { @@ -163,7 +221,7 @@ If you'd rather pin the server in a workspace, add a `.vscode/mcp.json`: ### Available Tools -**Read tools:** +**Read tools** (read-only): | Tool | Description | |------|-------------| @@ -180,32 +238,41 @@ If you'd rather pin the server in a workspace, add a `.vscode/mcp.json`: | Tool | Description | |------|-------------| | `wiki_write_page` | Create or overwrite a page (auto-updates index) | -| `wiki_create_entity` | Create entity page at `entities/{slug}.md` | -| `wiki_create_concept` | Create concept page at `concepts/{slug}.md` | -| `wiki_update_page` | Merge partial updates into an existing page | +| `wiki_create_entity` | Create entity page at `entities/{slug}.md`, optionally recording its `sources` | +| `wiki_create_concept` | Create concept page at `concepts/{slug}.md`, optionally recording its `sources` | +| `wiki_update_page` | Merge partial updates into an existing page; `addSources` extends a derived page's sources | | `wiki_add_crosslinks` | Add "See also" links (validates targets exist) | | `wiki_update_index` | Update index entry metadata | -| `wiki_ingest_with_context` | Ingest source with context-rich response | +| `wiki_ingest_with_context` | Ingest a source (path relative to the wiki root, e.g. `raw/article.md`) with a context-rich response | +| `wiki_fix` | Apply the deterministic fixes; `dryRun` previews them | +| `wiki_delete_page` | Delete a page and its index entry; reports pages that still link to it | -**Prompts & resources:** Beyond tools, the server also registers MCP **prompts** (`ingest-and-integrate`, `lint-and-fix`, `research-topic`) and **resources** — `resource://wiki/index`, `resource://wiki/pages`, `resource://wiki/sources`, plus the `resource://wiki/pages/{path}` and `resource://wiki/sources/{path}` templates — so agents can browse wiki content without invoking tools. +**Workspace tools** (only when the server isn't bound to a wiki root): `wiki_open` and `wiki_init`. + +`wiki_status`, `wiki_query`, `wiki_lint` and `wiki_fix` also return structured results that match their declared output schemas. + +**Prompts & resources:** Beyond tools, the server also registers MCP **prompts** (`ingest-and-integrate`, `lint-and-fix`, `research-topic`) and **resources** — `resource://wiki/index`, `resource://wiki/pages`, `resource://wiki/sources`, plus the `resource://wiki/pages/{path}` and `resource://wiki/sources/{path}` templates — so agents can browse wiki content without invoking tools. Argument completions suggest page paths, source paths and topics. See [docs/mcp-tools.md](docs/mcp-tools.md) for the full tool reference with schemas and workflows. ## GitHub Actions -[.github/workflows/ci.yml](.github/workflows/ci.yml) runs on push and PR to `main`. It installs dependencies, builds `@llmwiki/core` and the VS Code extension, type-checks both packages, runs the full test suite with coverage, and writes a coverage summary to the run. +[.github/workflows/ci.yml](.github/workflows/ci.yml) runs on push and PR to `main`. It installs dependencies, builds `@llmwiki/core` and the VS Code extension, checks that the committed plugin server bundle is up to date, type-checks both packages, runs the full test suite with coverage, and writes a coverage summary to the run. ## Development ```bash npm ci # Install all workspace dependencies -npm run build # Build all packages (core → vscode) +npm run build # Build all packages (core → vscode) and plugin/server/llmwiki-mcp.cjs npm test # Run tests (vitest) npm run lint # Type-check all packages (tsc --noEmit) npm run dev # Watch mode (vitest watch) npm run coverage # Run tests with coverage reporting (@vitest/coverage-v8) +npm run test:integration # Run the extension in a real VS Code instance (after npm run build) ``` +`npm run build` regenerates `plugin/server/llmwiki-mcp.cjs`; commit it together with any change to `@llmwiki/core`. The skills, agent and instructions are authored once in `plugin/` and copied into the extension at build time. + **Per-package commands:** ```bash diff --git a/docs/images/interface.png b/docs/images/interface.png index adfc7b3..c4b90ee 100644 Binary files a/docs/images/interface.png and b/docs/images/interface.png differ diff --git a/docs/mcp-tools.md b/docs/mcp-tools.md index 07e213b..b2d9ceb 100644 --- a/docs/mcp-tools.md +++ b/docs/mcp-tools.md @@ -21,6 +21,11 @@ - [wiki_add_crosslinks](#wiki_add_crosslinks) - [wiki_update_index](#wiki_update_index) - [wiki_ingest_with_context](#wiki_ingest_with_context) + - [wiki_fix](#wiki_fix) + - [wiki_delete_page](#wiki_delete_page) +- [Workspace Tools](#workspace-tools) + - [wiki_open](#wiki_open) + - [wiki_init](#wiki_init) - [Security Model](#security-model) - [Example Workflows](#example-workflows) - [See Also](#see-also) @@ -33,13 +38,15 @@ The `llmwiki` MCP server exposes wiki operations over the [Model Context Protoco | Property | Value | |----------|-------| -| **Server name** | `llmwiki` | -| **Version** | `0.1.0` | +| **Server name** | `llmwiki` (title: LLM Wiki) | +| **Version** | The `@llmwiki/core` package version | | **Protocol** | MCP over stdio | | **Launcher** | `llmwiki-mcp [wiki-root]` (bin from `@llmwiki/core`) | | **VS Code** | Auto-registered by the LLM Wiki extension via `mcpServerDefinitionProviders` | -| **Response format** | JSON text content | +| **Agent plugin** | `plugin/` — `copilot plugin install microsoft/llmwiki:plugin` | +| **Response format** | JSON text content; `wiki_status`, `wiki_query`, `wiki_lint` and `wiki_fix` also return `structuredContent` matching their `outputSchema` | | **Error shape** | `{ isError: true }` with an error message string | +| **Instructions** | Usage guidance plus the wiki's `AGENTS.md` (when the wiki is known at startup) | ### Connecting @@ -58,9 +65,11 @@ The `llmwiki` MCP server exposes wiki operations over the [Model Context Protoco } ``` -The wiki-root argument is optional; when omitted the launcher defaults to `/.wiki`. Install `@llmwiki/core` globally (`npm i -g @llmwiki/core`) to skip the `npx` indirection. +The wiki root comes from the argument or the `LLMWIKI_ROOT` environment variable. Without either, the server uses `/.wiki` when it exists at startup, otherwise looks in the client's workspace roots, and adds the [workspace tools](#workspace-tools) so an agent can open or create one. Install `@llmwiki/core` globally (`npm i -g @llmwiki/core`) to skip the `npx` indirection. -The server provides **7 read tools** for querying and inspecting the wiki, and **7 write tools** for creating, updating, and maintaining content. All tools accept a single JSON object as input and return a single JSON object as output. +The server provides **7 read tools** for querying and inspecting the wiki, and **9 write tools** for creating, updating, and maintaining content. All tools accept a single JSON object as input and return a single JSON object as output. + +Every tool has a `title` and [annotations](https://modelcontextprotocol.io/specification/2025-11-25/server/tools#tool-annotations). Read tools set `readOnlyHint: true`, so VS Code runs them without asking for confirmation. Write tools set `readOnlyHint: false`; those that can overwrite or delete content also set `destructiveHint: true`. All tools set `openWorldHint: false`. --- @@ -423,6 +432,9 @@ Create a new wiki entity page at `wiki/entities/{slug}.md` with proper frontmatt | `name` | string | **Yes** | Entity name (used for title and slug generation) | | `content` | string | **Yes** | Markdown body content | | `tags` | string[] | No | Tags for frontmatter and index | +| `sources` | string[] | No | Existing source summary pages under `sources/` that the page is derived from (e.g. `["sources/report-summary.md"]`). Anything else is rejected. If all of them are later removed, `wiki_fix` deletes the page. | + +An existing page with the same slug is overwritten, so check for one first. **Output** @@ -433,6 +445,7 @@ Create a new wiki entity page at `wiki/entities/{slug}.md` with proper frontmatt | `title` | string | Entity name used as title | | `type` | string | Always `"entity"` | | `tags` | string[] | Applied tags | +| `sources` | string[] | Recorded sources, when given | **Example** @@ -470,6 +483,9 @@ Create a new wiki concept page at `wiki/concepts/{slug}.md` with proper frontmat | `name` | string | **Yes** | Concept name (used for title and slug generation) | | `content` | string | **Yes** | Markdown body content | | `tags` | string[] | No | Tags for frontmatter and index | +| `sources` | string[] | No | Existing source summary pages under `sources/` that the page is derived from. Anything else is rejected. If all of them are later removed, `wiki_fix` deletes the page. | + +An existing page with the same slug is overwritten, so check for one first. **Output** @@ -480,6 +496,7 @@ Create a new wiki concept page at `wiki/concepts/{slug}.md` with proper frontmat | `title` | string | Concept name used as title | | `type` | string | Always `"concept"` | | `tags` | string[] | Applied tags | +| `sources` | string[] | Recorded sources, when given | **Example** @@ -520,6 +537,7 @@ Update an existing wiki page by merging partial frontmatter changes and/or appen | `tags` | string[] | No | New tags (replaces existing tags) | | `bodyAppend` | string | No | Markdown to append to existing body | | `bodyReplace` | string | No | Markdown to replace entire body | +| `addSources` | string[] | No | Summary pages of other sources whose content you are adding (e.g. `["sources/second-report-summary.md"]`). Appended to the page's existing `sources`, so the page is only deleted once all of its sources are removed. Must be existing summary pages under `sources/`. Ignored for pages that list no sources, so hand-written pages never become eligible for cleanup. | **Output** @@ -530,6 +548,7 @@ Update an existing wiki page by merging partial frontmatter changes and/or appen | `frontmatter` | object | Updated frontmatter | | `bodyUpdated` | boolean | Whether the body was changed | | `indexUpdated` | boolean | Whether the index was refreshed | +| `sourcesUpdated` | boolean | Whether `addSources` added any source | > **Note:** Fails gracefully if the target page does not exist. @@ -661,7 +680,7 @@ Ingest a source file into the wiki and return enhanced context including related | Parameter | Type | Required | Description | |-----------|------|----------|-------------| -| `sourcePath` | string | **Yes** | Path to source file, relative to project root | +| `sourcePath` | string | **Yes** | Path to the source file inside the wiki root — relative to the wiki root (e.g. `raw/article.md`) or absolute | | `dryRun` | boolean | No | If `true`, preview the ingest without writing files | | `force` | boolean | No | If `true`, re-ingest even if the source was previously processed | @@ -671,7 +690,7 @@ Ingest result plus enriched context: | Field | Type | Description | |-------|------|-------------| -| `ingest` | object | Standard ingest output (`status`, `pages_created`, `pages_updated`, `dry_run`, etc.) | +| `ingest` | object | Standard ingest output (`status`, `pages_created`, `pages_updated`, `dry_run`, etc.). When `status` is `"skipped"` because the source was already ingested, `summary_page` names the existing summary page. | | `source_word_count` | number | Word count of the source file | | `source_content_type` | string | Detected content type from file extension (e.g. `"markdown"`, `"pdf"`, `"text"`, `"html"`) | | `related_pages` | array | Existing wiki pages related to the ingested content (each with `path`, `title`, `score`, `excerpt`) | @@ -714,6 +733,100 @@ Ingest result plus enriched context: --- +### `wiki_fix` + +Apply every deterministic fix in one pass: delete entity/concept pages whose `sources` were all removed, drop stale index entries, add unlisted pages to the index, and add missing frontmatter defaults. Findings that need judgment (broken links, invalid page types, missing pages) are returned in `remaining`. Successful fixes are logged in `log.md` as `lint-fix`. + +Preview with `dryRun` first. The preview lints the wiki as it would be after the deletions, so `remaining` already includes the links those deletions would break. When `removed_pages` is not empty, agents should apply the fixes only after the user approves deleting those pages. + +**Input Schema** + +| Parameter | Type | Required | Description | +|-----------|------|----------|-------------| +| `dryRun` | boolean | No | If `true`, report what would change without writing anything | + +**Output** (also returned as `structuredContent`) + +| Field | Type | Description | +|-------|------|-------------| +| `dry_run` | boolean | Whether this was a preview | +| `removed_pages` | string[] | Derived pages deleted (or that would be deleted) because their sources are gone | +| `fixed` | LintFinding[] | Findings that were fixed | +| `remaining` | LintFinding[] | Findings that still need attention | +| `fixedCount` | number | `fixed.length` | +| `remainingCount` | number | `remaining.length` | + +**Example** + +```json +// Request +{ "tool": "wiki_fix", "input": { "dryRun": true } } + +// Response +{ + "command": "fix", + "api_version": "1", + "dry_run": true, + "removed_pages": ["entities/old-vendor.md"], + "fixed": [ + { "severity": "error", "category": "stale-entries", "message": "Stale index entry \"Deleted\" points to missing file \"concepts/deleted.md\"", "file": "concepts/deleted.md" } + ], + "remaining": [ + { "severity": "error", "category": "broken-links", "message": "Broken link to \"concepts/missing.md\" in page \"concepts/linked.md\"", "file": "concepts/linked.md" } + ], + "fixedCount": 1, + "remainingCount": 1 +} +``` + +--- + +### `wiki_delete_page` + +Delete a wiki page and remove it from the index. Refuses `index.md` and `log.md` (in any letter case), non-markdown files, and paths that leave the wiki directory, including through a symlinked folder. The deletion is logged in `log.md`. Agents should only call it after the user confirms. + +**Input Schema** + +| Parameter | Type | Required | Description | +|-----------|------|----------|-------------| +| `pagePath` | string | **Yes** | Relative path within `wiki/` (e.g. `"concepts/ai.md"`) | + +**Output** + +| Field | Type | Description | +|-------|------|-------------| +| `status` | string | Always `"deleted"` | +| `path` | string | Normalized path of the deleted page | +| `linkedFrom` | array | Pages that still link to it (`page`, `title`, `linkText`), so their links can be fixed | + +--- + +## Workspace Tools + +These tools are listed only when the server was started without a wiki root (no argument and no `LLMWIKI_ROOT`), for example from the agent plugin. + +### `wiki_open` + +Select the wiki to work with. Read-only. + +| Parameter | Type | Required | Description | +|-----------|------|----------|-------------| +| `path` | string | **Yes** | Absolute path of the project folder that contains `.wiki`, or of the `.wiki` folder itself | + +Returns `{ "status": "opened", "wiki_root", "wiki_page_count", "source_count" }`. A folder counts as a wiki when it has `.wiki/wiki/` (the same test `wiki_init` uses). If its `index.md` is missing, `wiki_fix` rebuilds it. + +### `wiki_init` + +Create a new wiki (`.wiki/` with `raw/`, `wiki/`, `index.md`, `log.md` and `AGENTS.md`) and open it. Does nothing if the folder already has one. + +| Parameter | Type | Required | Description | +|-----------|------|----------|-------------| +| `path` | string | No | Absolute path of the project folder. Defaults to the first workspace root reported by the client. | + +Returns the init result plus `wiki_root`. + +--- + ## Security Model All MCP tools enforce a layered security model to prevent unauthorized file system access and data corruption. @@ -732,6 +845,12 @@ Every tool that reads or writes wiki files validates paths with `assertWithinDir | **Empty slug rejection** | `wiki_create_entity`, `wiki_create_concept` | Names that produce empty slugs are rejected | | **Target existence check** | `wiki_add_crosslinks` | All target pages must exist before links are written | | **Index injection prevention** | `wiki_update_index`, `wiki_write_page` | Upsert pattern prevents duplicate or malformed index entries | +| **Protected files** | `wiki_delete_page` | `index.md`, `log.md` (in any letter case) and non-markdown files cannot be deleted, and the path is checked again after resolving symlinked folders | +| **Source containment** | `wiki_ingest_with_context`, `wiki_create_entity`, `wiki_create_concept`, `wiki_update_page` | Source paths must resolve inside the wiki root; recorded `sources`/`addSources` must be existing pages | + +### Concurrent Writes + +Tools that read, merge and write a page or `index.md` (for example `wiki_update_page`, `wiki_add_crosslinks`, `wiki_fix` and the create tools with `sources`) hold the wiki write lock, a `wiki/.llmwiki.lock` file. The VS Code extension's ingest and cleanup use the same lock, so two writers in different processes can't overwrite each other's changes. A lock left behind by a process that crashed is removed after 10 seconds. --- @@ -788,13 +907,18 @@ Ingest a source file, create a new entity from the findings, and link it to exis ### 3. Maintain Wiki Health -Run a lint pass, fix issues found, and update the index to keep metadata accurate. +Run a lint pass, apply the deterministic fixes, fix what remains, and update the index to keep metadata accurate. ```jsonc // Step 1 — Run lint to discover problems { "tool": "wiki_lint", "input": {} } -// Step 2 — Fix a page with outdated content +// Step 2 — Preview, then apply the deterministic fixes +// (if the preview lists removed_pages, apply only after the user approves) +{ "tool": "wiki_fix", "input": { "dryRun": true } } +{ "tool": "wiki_fix", "input": {} } + +// Step 3 — Fix a page with outdated content { "tool": "wiki_update_page", "input": { @@ -804,7 +928,7 @@ Run a lint pass, fix issues found, and update the index to keep metadata accurat } } -// Step 3 — Update the index entry to match +// Step 4 — Update the index entry to match { "tool": "wiki_update_index", "input": { diff --git a/docs/workflows/smart-ingest.md b/docs/workflows/smart-ingest.md index 9c5d1de..3426ee9 100644 --- a/docs/workflows/smart-ingest.md +++ b/docs/workflows/smart-ingest.md @@ -16,7 +16,7 @@ The agent doesn't just dump raw content into pages — it performs a structured 6. **Enrich** existing pages with knowledge from the new source. 7. **Verify** wiki health to catch broken links, missing metadata, or orphan pages. -This workflow uses the `llmwiki` MCP server — 14 tools over stdio transport. Launch it via the `llmwiki-mcp` bin shipped by `@llmwiki/core`: +This workflow uses the `llmwiki` MCP server over stdio transport. Launch it via the `llmwiki-mcp` bin shipped by `@llmwiki/core` (in VS Code the extension registers it for you, and the `/wiki-ingest` skill runs this workflow): ```bash npx -p @llmwiki/core llmwiki-mcp /abs/path/to/your-project/.wiki @@ -623,6 +623,6 @@ If `wiki_lint` returns errors after the workflow, inspect each finding: ## See Also -- [MCP Tools Reference](../mcp-tools.md) — Full schema documentation for all 14 tools +- [MCP Tools Reference](../mcp-tools.md) — Full schema documentation for all tools - [Model Context Protocol Specification](https://modelcontextprotocol.io/) — The MCP protocol standard - [ARCHITECTURE.md](../../ARCHITECTURE.md) — System architecture and the three-layer model diff --git a/package-lock.json b/package-lock.json index db1569c..3b0f7fe 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1844,13 +1844,6 @@ "dev": true, "license": "MIT" }, - "node_modules/@types/vscode": { - "version": "1.120.0", - "resolved": "https://registry.npmjs.org/@types/vscode/-/vscode-1.120.0.tgz", - "integrity": "sha512-feaT4Rst+FkTch5zz/ZbNCxoIvo55YU80Be2kiL7OJcod4+CUYf2lUBPdIJzozNnSEMq1VRTGrWEcCGFB3fBmA==", - "dev": true, - "license": "MIT" - }, "node_modules/@typespec/ts-http-runtime": { "version": "0.3.6", "resolved": "https://registry.npmjs.org/@typespec/ts-http-runtime/-/ts-http-runtime-0.3.6.tgz", @@ -8232,7 +8225,7 @@ "@types/glob": "^9.0.0", "@types/mocha": "^10.0.10", "@types/node": "^20.0.0", - "@types/vscode": "^1.93.0", + "@types/vscode": "~1.109.0", "@vscode/test-electron": "^2.5.2", "@vscode/vsce": "^3.7.1", "esbuild": "^0.28.1", @@ -8241,8 +8234,15 @@ "typescript": "^5.4.0" }, "engines": { - "vscode": "^1.101.0" + "vscode": "^1.109.0" } + }, + "packages/vscode/node_modules/@types/vscode": { + "version": "1.109.0", + "resolved": "https://registry.npmjs.org/@types/vscode/-/vscode-1.109.0.tgz", + "integrity": "sha512-0Pf95rnwEIwDbmXGC08r0B4TQhAbsHQ5UyTIgVgoieDe4cOnf92usuR5dEczb6bTKEp7ziZH4TV1TRGPPCExtw==", + "dev": true, + "license": "MIT" } } } diff --git a/package.json b/package.json index 63fb203..2a7c27f 100644 --- a/package.json +++ b/package.json @@ -20,6 +20,7 @@ "scripts": { "build": "npm run build --workspace=packages/core && npm run build --workspace=packages/vscode", "test": "vitest run", + "test:integration": "node tests/vscode/integration/build.mjs && node tests/vscode/integration/out/runTest.js", "coverage": "vitest run --coverage", "lint": "npm run lint --workspace=packages/core && npm run lint --workspace=packages/vscode", "dev": "vitest watch" diff --git a/packages/core/README.md b/packages/core/README.md index 01da1ed..257cab9 100644 --- a/packages/core/README.md +++ b/packages/core/README.md @@ -26,7 +26,7 @@ See the [main README](https://github.com/microsoft/llmwiki#readme) for the full ## Use as an MCP server -The package ships an `llmwiki-mcp` binary that exposes 14 wiki tools over stdio. +The package ships an `llmwiki-mcp` binary that exposes the wiki tools, resources and prompts over stdio. ```bash # Direct invocation @@ -39,7 +39,7 @@ npx llmwiki-mcp ./.wiki } ``` -The single positional argument is the path to a `.wiki/` directory; it defaults to `./.wiki` when omitted. +The single positional argument (or the `LLMWIKI_ROOT` environment variable) is the path to a `.wiki/` directory. Without it, the server uses `./.wiki` if present, otherwise looks for the wiki in the client's workspace roots, and adds `wiki_open` and `wiki_init` tools so an agent can select or create one. ## License diff --git a/packages/core/src/constants.ts b/packages/core/src/constants.ts index 0ee24b2..c1885fe 100644 --- a/packages/core/src/constants.ts +++ b/packages/core/src/constants.ts @@ -9,3 +9,9 @@ export const API_VERSION = '1'; * All wiki data (raw/, wiki/, AGENTS.md) lives under this directory. */ export const WIKI_DIR_NAME = '.wiki'; + +/** + * Version of the `@llmwiki/core` package, reported by the MCP server. + * A unit test keeps it in sync with `packages/core/package.json`. + */ +export const CORE_VERSION = '0.1.2'; diff --git a/packages/core/src/fix.ts b/packages/core/src/fix.ts new file mode 100644 index 0000000..22110f8 --- /dev/null +++ b/packages/core/src/fix.ts @@ -0,0 +1,201 @@ +import { readdir, stat } from 'node:fs/promises'; +import { extname, join, resolve } from 'node:path'; +import { readPage, deletePage } from './wiki.js'; +import { lintFix, type LintFinding } from './lint.js'; +import { appendEntry } from './log.js'; +import { withWikiLock } from './lock.js'; +import { API_VERSION } from './constants.js'; +import { isNotFoundError } from './errors.js'; + +export interface FixWikiOptions { + /** Report what would change without writing anything. Default: false. */ + dryRun?: boolean; +} + +export interface FixWikiResult { + command: 'fix'; + api_version: string; + dry_run: boolean; + /** Entity/concept pages removed because every source they were derived from is gone. */ + removed_pages: string[]; + fixed: LintFinding[]; + remaining: LintFinding[]; + fixedCount: number; + remainingCount: number; +} + +/** Wiki-relative paths (forward slashes) of every page except index.md and log.md. */ +async function listContentPages(wikiDir: string): Promise { + let files: string[]; + try { + files = (await readdir(wikiDir, { recursive: true })) as string[]; + } catch (err) { + if (isNotFoundError(err)) return []; + throw err; + } + return files + .map((f) => String(f).replace(/\\/g, '/')) + .filter((f) => extname(f) === '.md' && f !== 'index.md' && f !== 'log.md') + .sort(); +} + +async function readSources(wikiDir: string, relPath: string): Promise { + try { + return (await readPage(join(wikiDir, relPath))).frontmatter.sources; + } catch { + return undefined; + } +} + +/** + * Normalize one entry of a page's `sources` frontmatter. Only wiki-relative + * summary pages under `sources/` (e.g. "sources/article-summary.md") take part + * in provenance cleanup; anything else (raw/ paths, URLs, free text) returns + * undefined and is treated as a source that still exists. + */ +export function normalizeSourceRef(source: unknown): string | undefined { + if (typeof source !== 'string') return undefined; + const ref = source.trim().replace(/\\/g, '/').replace(/^(\.\/)+/, ''); + if (!/^sources\/.+\.md$/i.test(ref)) return undefined; + if (ref.split('/').some((segment) => segment === '' || segment === '.' || segment === '..')) { + return undefined; + } + return ref; +} + +/** + * True when `sources` lists at least one path and every one of them is a + * summary page that is definitely gone. Other entries and errors other than + * "not found" count as present, so a page is never deleted on bad data. + */ +async function allSourcesMissing(wikiDir: string, sources: unknown): Promise { + if (!Array.isArray(sources) || sources.length === 0) return false; + const missing = await Promise.all( + sources.map(async (source) => { + const ref = normalizeSourceRef(source); + if (!ref) return false; + try { + await stat(join(wikiDir, ref)); + return false; + } catch (err) { + return isNotFoundError(err); + } + }), + ); + return missing.every(Boolean); +} + +/** + * Find entity/concept pages whose frontmatter `sources` all point to files + * that no longer exist (the raw source was removed after ingest). + * Returns wiki-relative paths with forward slashes, sorted. + */ +export async function findOrphanedDerivedPages(wikiDir: string): Promise { + const orphaned: string[] = []; + for (const relPath of await listContentPages(wikiDir)) { + if (!relPath.startsWith('entities/') && !relPath.startsWith('concepts/')) continue; + if (await allSourcesMissing(wikiDir, await readSources(wikiDir, relPath))) { + orphaned.push(relPath); + } + } + return orphaned; +} + +/** + * Remove the wiki pages of a raw source that was deleted: its summary page + * (`summaryRelPath`, e.g. "sources/article-summary.md") and every page that + * lists it in `sources` and has no other source left. Pages that still have + * another existing source are kept. Returns the wiki-relative paths deleted. + * Runs under the wiki lock, so an ingest can't add a source to a page between + * the check and the deletion. + */ +export async function removeSourcePages(wikiDir: string, summaryRelPath: string): Promise { + return withWikiLock(wikiDir, async () => { + const removed: string[] = []; + try { + await deletePage(wikiDir, summaryRelPath); + removed.push(summaryRelPath); + } catch { + // The source was never ingested, or its summary is already gone. + } + + for (const relPath of await listContentPages(wikiDir)) { + const sources = await readSources(wikiDir, relPath); + if (!Array.isArray(sources) || !sources.some((s) => normalizeSourceRef(s) === summaryRelPath)) continue; + if (!(await allSourcesMissing(wikiDir, sources))) continue; + try { + await deletePage(wikiDir, relPath); + removed.push(relPath); + } catch { + // Already gone. + } + } + return removed; + }); +} + +/** + * Apply every deterministic wiki fix in one pass: + * 1. Delete entity/concept pages whose sources were all removed. + * 2. Run {@link lintFix} with orphan indexing enabled (stale index entries, + * missing index entries, missing frontmatter defaults, orphan pages). + * + * Findings that need judgment (broken links, invalid types, missing pages) + * are returned in `remaining`. With `dryRun`, nothing is written and the + * result describes what would change: the lint runs against the wiki as it + * would be after the deletions. Otherwise the whole pass runs under the wiki + * lock. + */ +export async function fixWiki( + wikiRoot: string, + options: FixWikiOptions = {}, +): Promise { + const root = resolve(wikiRoot); + const wikiDir = join(root, 'wiki'); + const dryRun = options.dryRun === true; + + const run = async (): Promise => { + const removed: string[] = []; + for (const relPath of await findOrphanedDerivedPages(wikiDir)) { + if (dryRun) { + removed.push(relPath); + continue; + } + try { + await deletePage(wikiDir, relPath); + removed.push(relPath); + } catch { + // Already gone — nothing to report. + } + } + + // In a dry run the pages are still there, so lint as if they were deleted: + // links to them break, and their own links and findings disappear. + const { fixed, remaining } = await lintFix(root, { + fixOrphans: true, + dryRun, + assumeDeleted: removed, + }); + + if (!dryRun && (removed.length > 0 || fixed.length > 0)) { + await appendEntry(join(wikiDir, 'log.md'), { + verb: 'lint-fix', + subject: 'wiki', + details: `Removed ${removed.length} orphaned page(s), fixed ${fixed.length} issue(s), ${remaining.length} remaining.`, + }); + } + + return { + command: 'fix', + api_version: API_VERSION, + dry_run: dryRun, + removed_pages: removed, + fixed, + remaining, + fixedCount: fixed.length, + remainingCount: remaining.length, + }; + }; + + return dryRun ? run() : withWikiLock(wikiDir, run); +} diff --git a/packages/core/src/index-ops.ts b/packages/core/src/index-ops.ts index 58a066b..bd07365 100644 --- a/packages/core/src/index-ops.ts +++ b/packages/core/src/index-ops.ts @@ -1,6 +1,7 @@ import { readFile, writeFile, mkdir } from 'node:fs/promises'; import { dirname } from 'node:path'; import { isNotFoundError } from './errors.js'; +import { withWikiLock } from './lock.js'; export interface IndexEntry { path: string; @@ -158,9 +159,31 @@ export async function addEntry( filePath: string, entry: IndexEntry, ): Promise { - const entries = await readIndex(filePath); - entries.push(entry); - await writeIndex(filePath, entries); + await withWikiLock(dirname(filePath), async () => { + const entries = await readIndex(filePath); + entries.push(entry); + await writeIndex(filePath, entries); + }); +} + +/** + * Add an entry, or replace the existing entry with the same path. An empty + * `summary` keeps the existing entry's summary. + */ +export async function upsertEntry( + filePath: string, + entry: IndexEntry, +): Promise { + await withWikiLock(dirname(filePath), async () => { + const entries = await readIndex(filePath); + const idx = entries.findIndex((e) => e.path === entry.path); + if (idx >= 0) { + entries[idx] = { ...entry, summary: entry.summary || entries[idx].summary }; + } else { + entries.push(entry); + } + await writeIndex(filePath, entries); + }); } /** @@ -171,9 +194,11 @@ export async function removeEntry( filePath: string, path: string, ): Promise { - const entries = await readIndex(filePath); - const filtered = entries.filter((e) => e.path !== path); - await writeIndex(filePath, filtered); + await withWikiLock(dirname(filePath), async () => { + const entries = await readIndex(filePath); + const filtered = entries.filter((e) => e.path !== path); + await writeIndex(filePath, filtered); + }); } /** @@ -185,18 +210,20 @@ export async function updateIndexEntry( pagePath: string, updates: Partial>, ): Promise { - const entries = await readIndex(filePath); - const idx = entries.findIndex((e) => e.path === pagePath); - if (idx < 0) return false; - - const entry = entries[idx]; - if (updates.title !== undefined) entry.title = updates.title; - if (updates.summary !== undefined) entry.summary = updates.summary; - if (updates.tags !== undefined) entry.tags = updates.tags; - if (updates.category !== undefined) entry.category = updates.category; - - await writeIndex(filePath, entries); - return true; + return withWikiLock(dirname(filePath), async () => { + const entries = await readIndex(filePath); + const idx = entries.findIndex((e) => e.path === pagePath); + if (idx < 0) return false; + + const entry = entries[idx]; + if (updates.title !== undefined) entry.title = updates.title; + if (updates.summary !== undefined) entry.summary = updates.summary; + if (updates.tags !== undefined) entry.tags = updates.tags; + if (updates.category !== undefined) entry.category = updates.category; + + await writeIndex(filePath, entries); + return true; + }); } /** diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 9492418..af65ecf 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -1,11 +1,13 @@ export * from './constants.js'; export * from './errors.js'; +export * from './lock.js'; export * from './wiki.js'; export * from './index-ops.js'; export * from './log.js'; export * from './sources.js'; export * from './backlinks.js'; export * from './lint.js'; +export * from './fix.js'; export * from './utils.js'; export * from './search.js'; export * from './ingest.js'; diff --git a/packages/core/src/ingest-context.ts b/packages/core/src/ingest-context.ts index 2d9d8b2..ea33fdb 100644 --- a/packages/core/src/ingest-context.ts +++ b/packages/core/src/ingest-context.ts @@ -104,7 +104,9 @@ function generateSuggestedActions( } if (ingestResult.status === 'skipped') { - actions.push('Use force=true to re-ingest this source'); + actions.push( + 'Source already ingested: read the existing summary page (summary_page) and build on it; re-ingest with force only if the user asks', + ); return actions; } diff --git a/packages/core/src/ingest.ts b/packages/core/src/ingest.ts index 4405a29..6b36e59 100644 --- a/packages/core/src/ingest.ts +++ b/packages/core/src/ingest.ts @@ -3,6 +3,7 @@ import { join, resolve, basename, dirname, extname, relative } from 'node:path'; import { writePage, directoryExists } from './wiki.js'; import { addEntry, removeEntry } from './index-ops.js'; import { appendEntry } from './log.js'; +import { withWikiLock } from './lock.js'; import { slugify } from './utils.js'; import { API_VERSION } from './constants.js'; import { isNotFoundError, isPermissionError } from './errors.js'; @@ -19,19 +20,34 @@ export interface IngestResult { dry_run: boolean; error?: string; message?: string; + /** Existing summary page (wiki-relative) when the source was already ingested. */ + summary_page?: string; } /** * Ingest a source file into the wiki knowledge base. * * Reads the source, creates a summary page in wiki/sources/, - * updates wiki/index.md, and appends to wiki/log.md. + * updates wiki/index.md, and appends to wiki/log.md. Unless `dryRun` is set, + * this runs under the wiki lock so the duplicate check and the writes don't + * interleave with other writers. */ export async function ingestSource( sourcePath: string, targetPath: string, dryRun: boolean, force: boolean = false, +): Promise { + if (dryRun) return ingestSourceFile(sourcePath, targetPath, dryRun, force); + const wikiDir = join(resolve(targetPath), 'wiki'); + return withWikiLock(wikiDir, () => ingestSourceFile(sourcePath, targetPath, dryRun, force)); +} + +async function ingestSourceFile( + sourcePath: string, + targetPath: string, + dryRun: boolean, + force: boolean, ): Promise { const root = resolve(targetPath); const wikiDir = join(root, 'wiki'); @@ -112,7 +128,8 @@ export async function ingestSource( pages_created: [], pages_updated: [], dry_run: dryRun, - message: 'Source already ingested. Use --force to re-ingest.', + message: 'Source already ingested. Read summary_page and build on it; re-ingest with force only if the user asks.', + summary_page: summaryRelPath, }; } diff --git a/packages/core/src/init.ts b/packages/core/src/init.ts index 1f42661..4f17192 100644 --- a/packages/core/src/init.ts +++ b/packages/core/src/init.ts @@ -1,8 +1,8 @@ -import { mkdir, stat, writeFile } from 'node:fs/promises'; +import { statSync } from 'node:fs'; +import { mkdir, writeFile } from 'node:fs/promises'; import { join, resolve } from 'node:path'; import { appendEntry } from './log.js'; import { API_VERSION, WIKI_DIR_NAME } from './constants.js'; -import { isNotFoundError } from './errors.js'; /** * Result of running the init command. @@ -66,7 +66,7 @@ const AGENTS_CONTENT = `# AGENTS.md **Optional fields:** - \`tags\` — Array of tag strings -- \`sources\` — Array of source references +- \`sources\` — Source summary pages this page was derived from, as wiki-relative paths (e.g. \`sources/article-summary.md\`). When all of them are removed, the page is cleaned up. Pages without \`sources\` are never removed automatically. - \`created\` — Creation date (YYYY-MM-DD) - \`updated\` — Last updated date (YYYY-MM-DD) - \`source_path\` — Relative path to the original source file @@ -112,7 +112,7 @@ results_count: ### Ingest Workflow -1. Place a raw file in the \`raw/\` directory (or run **LLM Wiki: Add Source** from the Command Palette). +1. Place a raw file in the \`raw/\` directory (or run **LLM Wiki: Ingest Files or Folder** from the Command Palette). 2. The extension automatically ingests new sources and writes a summary page in \`wiki/sources/\`. 3. \`wiki/index.md\` is updated with the new entry. 4. \`wiki/log.md\` records the ingestion event. @@ -125,7 +125,7 @@ results_count: - **stale-entries** (error) — Index entries pointing to deleted files - **missing-pages** (info) — Referenced pages that do not exist yet -Run lint via the **LLM Wiki** chat participant: \`@wiki /lint\`. +Run lint with **LLM Wiki: Run Lint** and apply the deterministic fixes with **LLM Wiki: Fix Issues**. In Copilot Chat, the \`/wiki-fix\` skill resolves the remaining findings. ### Cross-Referencing Guidelines @@ -136,6 +136,20 @@ Run lint via the **LLM Wiki** chat participant: \`@wiki /lint\`. - The lint command detects broken links and orphan pages `; +/** + * True when `root` (a `.wiki` folder) holds an initialized wiki, meaning it + * has a `wiki/` directory. initWiki, MCP wiki discovery and the VS Code + * extension use the same test, so a wiki whose index.md went missing still + * opens and wiki_fix can rebuild the index. + */ +export function isWikiInitialized(root: string): boolean { + try { + return statSync(join(root, 'wiki')).isDirectory(); + } catch { + return false; + } +} + /** * Initialize a wiki knowledge base at the given path. * Creates the `.wiki` directory containing the wiki structure. @@ -146,24 +160,17 @@ Run lint via the **LLM Wiki** chat participant: \`@wiki /lint\`. */ export async function initWiki(targetPath: string): Promise { const root = resolve(targetPath, WIKI_DIR_NAME); - const wikiDir = join(root, 'wiki'); // Detect if already initialized - try { - const wikiStat = await stat(wikiDir); - if (wikiStat.isDirectory()) { - return { - command: 'init', - api_version: API_VERSION, - status: 'already_initialized', - created_dirs: [], - created_files: [], - warning: 'Wiki is already initialized (wiki/ directory exists)', - }; - } - } catch (err) { - if (!isNotFoundError(err)) throw err; - // Directory does not exist — proceed with init + if (isWikiInitialized(root)) { + return { + command: 'init', + api_version: API_VERSION, + status: 'already_initialized', + created_dirs: [], + created_files: [], + warning: 'Wiki is already initialized (wiki/ directory exists)', + }; } // Create directory structure diff --git a/packages/core/src/lint.ts b/packages/core/src/lint.ts index d23244b..87ff867 100644 --- a/packages/core/src/lint.ts +++ b/packages/core/src/lint.ts @@ -2,6 +2,7 @@ import { access, constants } from 'node:fs/promises'; import { join, resolve, relative, dirname, basename } from 'node:path'; import { listPages, readPage, writePage, getPageLinks, type WikiPageFrontmatter } from './wiki.js'; import { readIndex, removeEntry, addEntry, type IndexEntry } from './index-ops.js'; +import { withWikiLock } from './lock.js'; import { API_VERSION } from './constants.js'; import { isNotFoundError } from './errors.js'; @@ -39,6 +40,15 @@ function normalizePath(p: string): string { return p.replace(/\\/g, '/'); } +export interface LintOptions { + /** + * Wiki-relative pages to treat as already deleted, together with their + * index entries (as `deletePage` leaves them). Lets a dry run lint the + * state that a planned deletion would leave. + */ + assumeDeleted?: Iterable; +} + /** * Run lint checks on a wiki knowledge base. * If categories is provided and non-empty, only run those check categories. @@ -46,21 +56,23 @@ function normalizePath(p: string): string { export async function lintWiki( targetPath: string, categories?: string[], + options: LintOptions = {}, ): Promise { const root = resolve(targetPath); const wikiDir = join(root, 'wiki'); const indexPath = join(wikiDir, 'index.md'); + const deleted = new Set([...(options.assumeDeleted ?? [])].map(normalizePath)); const findings: LintFinding[] = []; const shouldRun = (cat: string): boolean => !categories || categories.length === 0 || categories.includes(cat); - // Gather wiki pages (excluding index.md and log.md) + // Gather wiki pages (excluding index.md, log.md and pages assumed deleted) const allPages = await listPages(wikiDir); const wikiPages = allPages.filter((p) => { const rel = normalizePath(relative(wikiDir, p)); - return rel !== 'index.md' && rel !== 'log.md'; + return rel !== 'index.md' && rel !== 'log.md' && !deleted.has(rel); }); // Build a set of existing wiki page relative paths @@ -94,8 +106,8 @@ export async function lintWiki( } } - // Read index - const indexEntries = await readIndex(indexPath); + // Read index (deletePage removes the entry of a deleted page) + const indexEntries = (await readIndex(indexPath)).filter((e) => !deleted.has(e.path)); const indexedPaths = new Set(indexEntries.map((e) => normalizePath(e.path))); // ── broken-links: Links pointing to non-existent files ── @@ -148,7 +160,7 @@ export async function lintWiki( for (const entry of indexEntries) { const entryPath = normalizePath(entry.path); const fullPath = join(wikiDir, entryPath); - if (!(await fileExists(fullPath))) { + if (deleted.has(entryPath) || !(await fileExists(fullPath))) { findings.push({ severity: 'error', category: 'stale-entries', @@ -250,9 +262,11 @@ export async function lintWiki( }; } -export interface LintFixOptions { - /** When true, remove orphan pages (destructive). Default: false. */ +export interface LintFixOptions extends LintOptions { + /** When true, add orphan pages to the index. Default: false. */ fixOrphans?: boolean; + /** When true, report what would be fixed without writing any files. */ + dryRun?: boolean; } export interface LintFixResult { @@ -302,17 +316,28 @@ function categoryFromPath(relPath: string): string { * - orphan-pages → destructive, requires fixOrphans: true * - broken-links → requires human judgment * - missing-pages → informational (broken-links covers the error) + * + * Unless `dryRun` is set, the lint and the fixes run under the wiki lock. */ export async function lintFix( targetPath: string, options: LintFixOptions = {}, +): Promise { + if (options.dryRun) return applyLintFixes(targetPath, options); + return withWikiLock(join(resolve(targetPath), 'wiki'), () => applyLintFixes(targetPath, options)); +} + +async function applyLintFixes( + targetPath: string, + options: LintFixOptions, ): Promise { const root = resolve(targetPath); const wikiDir = join(root, 'wiki'); const indexPath = join(wikiDir, 'index.md'); + const dryRun = options.dryRun === true; // 1. Run full lint to get all findings - const lintResult = await lintWiki(targetPath); + const lintResult = await lintWiki(targetPath, undefined, { assumeDeleted: options.assumeDeleted }); const fixed: LintFinding[] = []; const remaining: LintFinding[] = []; @@ -337,7 +362,7 @@ export async function lintFix( continue; } try { - await removeEntry(indexPath, finding.file); + if (!dryRun) await removeEntry(indexPath, finding.file); fixed.push(finding); } catch { remaining.push(finding); @@ -348,6 +373,9 @@ export async function lintFix( const missingIndexFindings = fixableFindings.filter( (f) => f.category === 'index-completeness', ); + // An orphan page also fails index-completeness; track additions so the + // orphan pass below does not add the same page to the index twice. + const addedToIndex = new Set(); for (const finding of missingIndexFindings) { if (!finding.file) { remaining.push(finding); @@ -364,7 +392,8 @@ export async function lintFix( category: categoryFromPath(relPath), tags: page.frontmatter.tags || [], }; - await addEntry(indexPath, entry); + if (!dryRun) await addEntry(indexPath, entry); + addedToIndex.add(relPath); fixed.push(finding); } catch { remaining.push(finding); @@ -423,7 +452,7 @@ export async function lintFix( } } - if (modified) { + if (modified && !dryRun) { await writePage(fullPath, page); } fixed.push(...fixedInPage); @@ -444,6 +473,10 @@ export async function lintFix( continue; } const relPath = finding.file; + if (addedToIndex.has(relPath)) { + fixed.push(finding); + continue; + } const fullPath = join(wikiDir, relPath); try { const page = await readPage(fullPath); @@ -454,7 +487,8 @@ export async function lintFix( category: categoryFromPath(relPath), tags: page.frontmatter.tags || [], }; - await addEntry(indexPath, entry); + if (!dryRun) await addEntry(indexPath, entry); + addedToIndex.add(relPath); fixed.push(finding); } catch { remaining.push(finding); diff --git a/packages/core/src/lock.ts b/packages/core/src/lock.ts new file mode 100644 index 0000000..aefecba --- /dev/null +++ b/packages/core/src/lock.ts @@ -0,0 +1,116 @@ +import { AsyncLocalStorage } from 'node:async_hooks'; +import { open, stat, unlink, utimes } from 'node:fs/promises'; +import { join, resolve } from 'node:path'; +import { isNotFoundError } from './errors.js'; + +/** Lock file that exists in the wiki directory while a write is in progress. */ +export const WIKI_LOCK_FILE = '.llmwiki.lock'; + +/** A lock that hasn't been refreshed for this long was left behind by a process that died. */ +const STALE_MS = 10_000; +/** How long to wait for another writer before giving up. */ +const TIMEOUT_MS = 30_000; + +/** Wiki directories whose lock the current async call chain already holds. */ +const held = new AsyncLocalStorage>(); + +function errorCode(err: unknown): string | undefined { + return (err as NodeJS.ErrnoException | undefined)?.code; +} + +/** Errors Windows reports while another process is still releasing the lock file. */ +function isTransient(err: unknown): boolean { + return process.platform === 'win32' && ['EPERM', 'EACCES', 'EBUSY'].includes(errorCode(err) ?? ''); +} + +function sleep(ms: number): Promise { + return new Promise((done) => setTimeout(done, ms)); +} + +/** + * Run `fn` while holding the write lock of the wiki in `wikiDir`, so that + * read-modify-write updates of pages and index.md never interleave. The lock + * is a file in `wikiDir`, which makes it shared by every process that uses + * @llmwiki/core: the VS Code extension and any MCP servers. It is re-entrant + * within one async call chain. If `wikiDir` doesn't exist, `fn` runs without + * a lock. + */ +export async function withWikiLock(wikiDir: string, fn: () => Promise): Promise { + const key = process.platform === 'win32' ? resolve(wikiDir).toLowerCase() : resolve(wikiDir); + const outer = held.getStore(); + if (outer?.has(key)) return fn(); + + const lockPath = join(wikiDir, WIKI_LOCK_FILE); + if (!(await acquire(lockPath))) return fn(); + + // Keep the lock fresh so a long operation isn't mistaken for a dead one. + const heartbeat = setInterval(() => { + const now = new Date(); + utimes(lockPath, now, now).catch(() => {}); + }, STALE_MS / 4); + heartbeat.unref(); + try { + return await held.run(new Set([...(outer ?? []), key]), fn); + } finally { + clearInterval(heartbeat); + await release(lockPath); + } +} + +/** Create the lock file, waiting while another writer holds it. False if its directory is missing. */ +async function acquire(lockPath: string): Promise { + const deadline = Date.now() + TIMEOUT_MS; + for (let delay = 5; ; delay = Math.min(delay * 2, 100)) { + try { + await (await open(lockPath, 'wx')).close(); + return true; + } catch (err) { + if (isNotFoundError(err)) return false; + // A transient error with no lock file present is a real permission problem. + const busy = errorCode(err) === 'EEXIST' || (isTransient(err) && (await mayExist(lockPath))); + if (!busy) throw err; + if (Date.now() >= deadline) { + if (errorCode(err) !== 'EEXIST') throw err; + throw new Error( + `Timed out waiting for another LLM Wiki write to finish. If none is running, delete ${lockPath}.`, + ); + } + } + if (await isStale(lockPath)) { + await unlink(lockPath).catch(() => {}); + continue; + } + await sleep(delay); + } +} + +/** False only when the file is definitely absent. */ +async function mayExist(path: string): Promise { + try { + await stat(path); + return true; + } catch (err) { + return !isNotFoundError(err); + } +} + +async function isStale(lockPath: string): Promise { + try { + return Date.now() - (await stat(lockPath)).mtimeMs > STALE_MS; + } catch { + return false; + } +} + +async function release(lockPath: string): Promise { + for (let attempt = 1; ; attempt++) { + try { + await unlink(lockPath); + return; + } catch (err) { + // If it can't be removed, other writers take over once it is stale. + if (!isTransient(err) || attempt >= 5) return; + await sleep(20); + } + } +} diff --git a/packages/core/src/mcp/bin.ts b/packages/core/src/mcp/bin.ts index 673714c..83e7386 100644 --- a/packages/core/src/mcp/bin.ts +++ b/packages/core/src/mcp/bin.ts @@ -6,41 +6,49 @@ * llmwiki-mcp [wiki-root] * npx -p @llmwiki/core llmwiki-mcp [wiki-root] * - * If `wiki-root` is omitted it defaults to `/.wiki`, matching the - * directory created by `LLM Wiki: Initialize` in the VS Code extension. + * The wiki root is the `.wiki` directory created by `LLM Wiki: Initialize + * Wiki` in VS Code. It comes from the first argument, or else the + * `LLMWIKI_ROOT` environment variable; the server then works on that wiki + * only. Without either, the server uses `/.wiki` if it exists at + * startup, otherwise the client's workspace roots, and finally the + * `wiki_open` and `wiki_init` tools (agent plugins start the server in the + * plugin folder). * * Intended to be invoked by MCP-compatible hosts (Claude Desktop, Cursor, - * VS Code Copilot MCP, etc.) over stdio. + * VS Code Copilot MCP, Copilot CLI plugins, etc.) over stdio. */ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'; import { resolve } from 'node:path'; import { stat } from 'node:fs/promises'; -import { WIKI_DIR_NAME } from '../constants.js'; import { createMcpServer } from './server.js'; async function main(): Promise { const arg = process.argv[2]; - const wikiRoot = resolve(arg && arg.length > 0 ? arg : `./${WIKI_DIR_NAME}`); + const configured = arg && arg.length > 0 ? arg : process.env.LLMWIKI_ROOT; - try { - const info = await stat(wikiRoot); - if (!info.isDirectory()) { + let wikiRoot: string | undefined; + if (configured && configured.length > 0) { + wikiRoot = resolve(configured); + try { + const info = await stat(wikiRoot); + if (!info.isDirectory()) { + process.stderr.write( + `llmwiki-mcp: ${wikiRoot} exists but is not a directory.\n`, + ); + process.exit(1); + } + } catch { process.stderr.write( - `llmwiki-mcp: ${wikiRoot} exists but is not a directory.\n`, + `llmwiki-mcp: wiki root not found at ${wikiRoot}.\n` + + `Initialize one first (e.g. via "LLM Wiki: Initialize Wiki" in VS Code) ` + + `or pass the path explicitly:\n` + + ` llmwiki-mcp \n`, ); process.exit(1); } - } catch { - process.stderr.write( - `llmwiki-mcp: wiki root not found at ${wikiRoot}.\n` + - `Initialize one first (e.g. via "LLM Wiki: Initialize" in VS Code) ` + - `or pass the path explicitly:\n` + - ` llmwiki-mcp \n`, - ); - process.exit(1); } - const server = createMcpServer(wikiRoot); + const server = createMcpServer(wikiRoot ? { wikiRoot } : { cwd: process.cwd() }); const transport = new StdioServerTransport(); await server.connect(transport); diff --git a/packages/core/src/mcp/completions.ts b/packages/core/src/mcp/completions.ts new file mode 100644 index 0000000..3d0d0f8 --- /dev/null +++ b/packages/core/src/mcp/completions.ts @@ -0,0 +1,68 @@ +import { join, relative } from 'node:path'; +import type { Server } from '@modelcontextprotocol/sdk/server/index.js'; +import { CompleteRequestSchema } from '@modelcontextprotocol/sdk/types.js'; +import { listPages } from '../wiki.js'; +import { listSources } from '../sources.js'; +import { readIndex } from '../index-ops.js'; + +/** Maximum number of values returned in one completion response (MCP limit). */ +const MAX_COMPLETIONS = 100; + +async function pagePaths(wikiRoot: string): Promise { + const wikiDir = join(wikiRoot, 'wiki'); + return (await listPages(wikiDir)) + .map((p) => relative(wikiDir, p).replace(/\\/g, '/')) + .filter((p) => p !== 'index.md' && p !== 'log.md') + .sort(); +} + +async function sourcePaths(wikiRoot: string): Promise { + return (await listSources(join(wikiRoot, 'raw'))).map((s) => s.path).sort(); +} + +/** + * Suggest values for resource-template and prompt arguments: + * - `resource://wiki/pages/{path}` → wiki page paths + * - `resource://wiki/sources/{path}` → raw source paths + * - prompt `ingest-and-integrate` `source_path` → `raw/` paths + * - prompt `research-topic` `topic` → page titles from the index + */ +export function registerCompletions( + server: Server, + getWikiRoot: () => Promise, +): void { + server.setRequestHandler(CompleteRequestSchema, async (request) => { + const { ref, argument } = request.params; + + let candidates: string[] = []; + try { + if (ref.type === 'ref/resource' && argument.name === 'path') { + if (ref.uri === 'resource://wiki/pages/{path}') { + candidates = await pagePaths(await getWikiRoot()); + } else if (ref.uri === 'resource://wiki/sources/{path}') { + candidates = await sourcePaths(await getWikiRoot()); + } + } else if (ref.type === 'ref/prompt') { + if (ref.name === 'ingest-and-integrate' && argument.name === 'source_path') { + candidates = (await sourcePaths(await getWikiRoot())).map((p) => `raw/${p}`); + } else if (ref.name === 'research-topic' && argument.name === 'topic') { + const entries = await readIndex(join(await getWikiRoot(), 'wiki', 'index.md')); + candidates = [...new Set(entries.map((e) => e.title))].sort(); + } + } + } catch { + // No wiki located yet: offer no suggestions rather than failing. + candidates = []; + } + + const needle = (argument.value ?? '').toLowerCase(); + const matches = candidates.filter((c) => c.toLowerCase().includes(needle)); + return { + completion: { + values: matches.slice(0, MAX_COMPLETIONS), + total: matches.length, + hasMore: matches.length > MAX_COMPLETIONS, + }, + }; + }); +} diff --git a/packages/core/src/mcp/index.ts b/packages/core/src/mcp/index.ts index 358fe7f..b5b27fb 100644 --- a/packages/core/src/mcp/index.ts +++ b/packages/core/src/mcp/index.ts @@ -1,6 +1,12 @@ export { createMcpServer } from './server.js'; +export type { CreateMcpServerOptions } from './server.js'; export { READ_TOOLS, handleReadToolCall, assertWithinDir } from './read-tools.js'; -export type { ToolArgs, ToolDefinition } from './read-tools.js'; +export type { ToolAnnotations, ToolArgs, ToolDefinition } from './read-tools.js'; export { WRITE_TOOLS, handleWriteToolCall } from './write-tools.js'; +export { WORKSPACE_TOOLS, handleWorkspaceToolCall } from './workspace-tools.js'; +export { WikiRootState, NoWikiError, findWikiRoot } from './wiki-root.js'; +export type { WikiRootSource, WikiRootStateOptions } from './wiki-root.js'; +export { BASE_INSTRUCTIONS, buildInstructions } from './instructions.js'; export { registerResources } from './resources.js'; export { registerPrompts, PROMPTS } from './prompts.js'; +export { registerCompletions } from './completions.js'; diff --git a/packages/core/src/mcp/instructions.ts b/packages/core/src/mcp/instructions.ts new file mode 100644 index 0000000..3fe208d --- /dev/null +++ b/packages/core/src/mcp/instructions.ts @@ -0,0 +1,52 @@ +import { readFileSync } from 'node:fs'; +import { join } from 'node:path'; + +/** Upper bound for the AGENTS.md excerpt embedded in the instructions. */ +export const MAX_SCHEMA_CHARS = 12_000; + +/** How agents should use the LLM Wiki tools (sent as MCP server instructions). */ +export const BASE_INSTRUCTIONS = `LLM Wiki is a personal knowledge base that an LLM maintains as interlinked markdown. A wiki root (usually /.wiki) contains: +- raw/: immutable sources the user curates. Read them; never modify them. +- wiki/: pages you maintain. entities/ (people, organizations, things), concepts/ (ideas, techniques), sources/ (one summary per raw source), plus wiki/index.md (the catalog) and wiki/log.md (append-only history). +- AGENTS.md: the wiki's schema and conventions. Follow it. + +Answering questions: +1. Find candidate pages with wiki_query (or scan wiki_read_index), then read the most relevant ones with wiki_read_page. +2. Answer from the wiki content and cite the pages you used by title and path. Point out connections between pages. +3. If the wiki does not cover the question, say so and suggest sources the user could add. +4. When an answer is a valuable synthesis, offer to save it as a page with wiki_write_page (type "query", path "queries/.md"). + +Maintaining the wiki: +- Prefer wiki_create_entity, wiki_create_concept, wiki_update_page and wiki_add_crosslinks over editing files directly; they keep index.md consistent. +- To ingest a source, make sure the file is under raw/, then call wiki_ingest_with_context with sourcePath "raw/". +- For health checks call wiki_lint. wiki_fix applies the deterministic fixes: preview with dryRun first, and if the preview lists removed_pages, apply only after the user approves deleting them. Resolve the remaining findings by editing pages. +- Delete pages with wiki_delete_page only after the user confirms.`; + +const DISCOVERY_INSTRUCTIONS = `Locating the wiki: if a tool reports that no wiki is open, call wiki_open with the absolute path of the user's project folder (usually the current working directory). Use wiki_init only when the user wants a new wiki.`; + +/** + * Build the MCP server instructions. When the wiki root is known, its + * AGENTS.md schema is appended (truncated to {@link MAX_SCHEMA_CHARS}). + */ +export function buildInstructions( + wikiRoot: string | undefined, + options: { discovery?: boolean } = {}, +): string { + const parts = [BASE_INSTRUCTIONS]; + if (options.discovery) parts.push(DISCOVERY_INSTRUCTIONS); + + if (wikiRoot) { + let schema = ''; + try { + schema = readFileSync(join(wikiRoot, 'AGENTS.md'), 'utf-8').trim(); + } catch { + // No schema file — the base instructions still apply. + } + if (schema.length > MAX_SCHEMA_CHARS) { + schema = `${schema.slice(0, MAX_SCHEMA_CHARS)}\n\n[Truncated. Read .wiki/AGENTS.md for the full schema.]`; + } + if (schema) parts.push(`This wiki's schema (.wiki/AGENTS.md):\n\n${schema}`); + } + + return parts.join('\n\n'); +} diff --git a/packages/core/src/mcp/prompts.ts b/packages/core/src/mcp/prompts.ts index 512e71d..eccb7dd 100644 --- a/packages/core/src/mcp/prompts.ts +++ b/packages/core/src/mcp/prompts.ts @@ -55,7 +55,7 @@ function ingestAndIntegrateMessages(sourcePath: string) { text: [ `Ingest the source file "${sourcePath}" and fully integrate its knowledge into the wiki. Follow these steps:`, '', - '1. **Ingest with context**: Call wiki_ingest_with_context with source_path set to', + '1. **Ingest with context**: Call wiki_ingest_with_context with sourcePath set to', ` "${sourcePath}". Review the returned related_pages and suggested_actions.`, '', '2. **Create entity pages**: For each person, organization, or named thing mentioned', @@ -94,18 +94,20 @@ function lintAndFixMessages() { '1. **Run lint**: Call wiki_lint to get all findings. Note the total count and', ' severity breakdown (error, warning, info).', '', - '2. **Review errors first**: For each error-severity finding, determine if it can', - ' be fixed deterministically:', - ' - Stale index entries (page referenced in index but file missing) → remove entry', - ' - Missing index entries (page exists but not in index) → add entry', - ' - Missing frontmatter fields (no title, no tags) → add sensible defaults', + '2. **Preview deterministic fixes**: Call wiki_fix with dryRun set to true. It lists', + ' stale index entries to drop, unlisted pages to index, missing frontmatter', + ' defaults to add, and entity/concept pages whose raw sources were removed.', '', - '3. **Fix deterministic issues**: Use wiki_update_index to fix index problems.', - ' Use wiki_read_page and appropriate write tools to fix frontmatter issues.', + '3. **Confirm deletions**: If removed_pages is not empty, list those pages and ask', + ' the user whether to delete them. Wait for an explicit yes. If the user declines', + ' or does not answer, skip step 4: do not call wiki_fix without dryRun, because', + ' it would delete those pages.', '', - '4. **Report remaining**: List any findings that require human judgment:', - ' - Orphan pages (exist but nothing links to them)', + '4. **Apply them**: Call wiki_fix (without dryRun) and note what it fixed.', + '', + '5. **Report remaining**: List the findings that still require human judgment:', ' - Broken crosslinks (link target does not exist)', + ' - Invalid page types', ' - Contradictory information across pages', '', 'Summarize: how many issues found, how many fixed, how many remain.', @@ -161,7 +163,7 @@ function researchTopicMessages(topic: string) { * Prompts provide structured multi-step instructions that guide an LLM agent * through common wiki operations using the available MCP tools. */ -export function registerPrompts(server: Server, _wikiRoot: string): void { +export function registerPrompts(server: Server, _wikiRoot?: string): void { server.setRequestHandler(ListPromptsRequestSchema, async () => ({ prompts: PROMPTS.map((p) => ({ name: p.name, diff --git a/packages/core/src/mcp/read-tools.ts b/packages/core/src/mcp/read-tools.ts index 3ce8039..e295fc2 100644 --- a/packages/core/src/mcp/read-tools.ts +++ b/packages/core/src/mcp/read-tools.ts @@ -6,18 +6,36 @@ import { listPages, readPage } from '../wiki.js'; import { listSources } from '../sources.js'; import { readIndex } from '../index-ops.js'; import { isNotFoundError } from '../errors.js'; +import { LINT_OUTPUT_SCHEMA, QUERY_OUTPUT_SCHEMA, STATUS_OUTPUT_SCHEMA } from './schemas.js'; + +/** MCP tool behaviour hints (the MCP specification's `ToolAnnotations`). */ +export interface ToolAnnotations { + readOnlyHint?: boolean; + destructiveHint?: boolean; + idempotentHint?: boolean; + openWorldHint?: boolean; +} /** JSON-Schema definition for a single MCP tool. */ export interface ToolDefinition { name: string; + /** Human-readable name shown by MCP clients. */ + title: string; description: string; inputSchema: Record; + /** When set, the tool also returns `structuredContent` matching this schema. */ + outputSchema?: Record; + annotations: ToolAnnotations; } +/** Read-only tools have no side effects and only touch the local wiki. */ +const READ_ONLY: ToolAnnotations = { readOnlyHint: true, openWorldHint: false }; + /** All read-only tool definitions exposed by the MCP server. */ export const READ_TOOLS: ToolDefinition[] = [ { name: 'wiki_status', + title: 'Wiki status', description: 'Return wiki status including source count, page count, lint dates, orphan pages and index coverage.', inputSchema: { @@ -26,11 +44,14 @@ export const READ_TOOLS: ToolDefinition[] = [ required: [], additionalProperties: false, }, + outputSchema: STATUS_OUTPUT_SCHEMA, + annotations: READ_ONLY, }, { name: 'wiki_query', + title: 'Search wiki', description: - 'Search the wiki for pages matching a free-text query. Returns matched pages with relevance scores.', + 'Search the wiki for pages matching a free-text query. Returns matched pages with relevance scores and excerpts. Start here when answering a question, then read the best matches with wiki_read_page.', inputSchema: { type: 'object', properties: { @@ -39,9 +60,12 @@ export const READ_TOOLS: ToolDefinition[] = [ required: ['query'], additionalProperties: false, }, + outputSchema: QUERY_OUTPUT_SCHEMA, + annotations: READ_ONLY, }, { name: 'wiki_lint', + title: 'Lint wiki', description: 'Lint the wiki and return findings grouped by severity (error, warning, info) with optional category filter.', inputSchema: { @@ -55,9 +79,12 @@ export const READ_TOOLS: ToolDefinition[] = [ required: [], additionalProperties: false, }, + outputSchema: LINT_OUTPUT_SCHEMA, + annotations: READ_ONLY, }, { name: 'wiki_list_pages', + title: 'List wiki pages', description: 'List all wiki pages with their file paths and frontmatter metadata.', inputSchema: { @@ -66,9 +93,11 @@ export const READ_TOOLS: ToolDefinition[] = [ required: [], additionalProperties: false, }, + annotations: READ_ONLY, }, { name: 'wiki_list_sources', + title: 'List raw sources', description: 'List all raw source files with name, path, size, modified date and extension.', inputSchema: { @@ -77,9 +106,11 @@ export const READ_TOOLS: ToolDefinition[] = [ required: [], additionalProperties: false, }, + annotations: READ_ONLY, }, { name: 'wiki_read_page', + title: 'Read wiki page', description: 'Read a single wiki page by relative path. Returns frontmatter and body content.', inputSchema: { @@ -93,9 +124,11 @@ export const READ_TOOLS: ToolDefinition[] = [ required: ['path'], additionalProperties: false, }, + annotations: READ_ONLY, }, { name: 'wiki_read_index', + title: 'Read wiki index', description: 'Read the wiki index file and return parsed entries with path, title, summary, category and tags.', inputSchema: { @@ -104,6 +137,7 @@ export const READ_TOOLS: ToolDefinition[] = [ required: [], additionalProperties: false, }, + annotations: READ_ONLY, }, ]; diff --git a/packages/core/src/mcp/resources.ts b/packages/core/src/mcp/resources.ts index be05f58..b03ff73 100644 --- a/packages/core/src/mcp/resources.ts +++ b/packages/core/src/mcp/resources.ts @@ -27,11 +27,14 @@ import { assertWithinDir } from './read-tools.js'; * Template resources: * - `resource://wiki/pages/{path}` — single page content + frontmatter * - `resource://wiki/sources/{path}` — raw source file content + * + * @param wikiRoot The wiki root, or a function that resolves it on demand. */ -export function registerResources(server: Server, wikiRoot: string): void { - const wikiDir = join(wikiRoot, 'wiki'); - const rawDir = join(wikiRoot, 'raw'); - const indexPath = join(wikiDir, 'index.md'); +export function registerResources( + server: Server, + wikiRoot: string | (() => Promise), +): void { + const getWikiRoot = typeof wikiRoot === 'string' ? async () => wikiRoot : wikiRoot; // ----------------------------------------------------------------- // List static resources @@ -89,6 +92,10 @@ export function registerResources(server: Server, wikiRoot: string): void { // ----------------------------------------------------------------- server.setRequestHandler(ReadResourceRequestSchema, async (request) => { const { uri } = request.params; + const root = await getWikiRoot(); + const wikiDir = join(root, 'wiki'); + const rawDir = join(root, 'raw'); + const indexPath = join(wikiDir, 'index.md'); // --- Static: wiki index ------------------------------------------- if (uri === 'resource://wiki/index') { diff --git a/packages/core/src/mcp/schemas.ts b/packages/core/src/mcp/schemas.ts new file mode 100644 index 0000000..d526f35 --- /dev/null +++ b/packages/core/src/mcp/schemas.ts @@ -0,0 +1,95 @@ +/** + * JSON Schemas for the structured results of tools that declare an + * `outputSchema`. Each mirrors the corresponding TypeScript result type. + */ + +const LINT_FINDING_SCHEMA = { + type: 'object', + properties: { + severity: { type: 'string', enum: ['error', 'warning', 'info'] }, + category: { type: 'string' }, + message: { type: 'string' }, + file: { type: 'string' }, + }, + required: ['severity', 'category', 'message'], +}; + +/** Mirrors `StatusResult`. */ +export const STATUS_OUTPUT_SCHEMA = { + type: 'object', + properties: { + command: { type: 'string' }, + api_version: { type: 'string' }, + source_count: { type: 'integer' }, + wiki_page_count: { type: 'integer' }, + last_ingest_date: { type: ['string', 'null'] }, + last_lint_date: { type: ['string', 'null'] }, + orphan_page_count: { type: 'integer' }, + index_coverage_pct: { type: 'number' }, + }, + required: [ + 'source_count', + 'wiki_page_count', + 'last_ingest_date', + 'last_lint_date', + 'orphan_page_count', + 'index_coverage_pct', + ], +}; + +/** Mirrors `LintResult`. */ +export const LINT_OUTPUT_SCHEMA = { + type: 'object', + properties: { + command: { type: 'string' }, + api_version: { type: 'string' }, + findings: { type: 'array', items: LINT_FINDING_SCHEMA }, + errorCount: { type: 'integer' }, + warningCount: { type: 'integer' }, + infoCount: { type: 'integer' }, + categorySummary: { type: 'object', additionalProperties: { type: 'integer' } }, + }, + required: ['findings', 'errorCount', 'warningCount', 'infoCount', 'categorySummary'], +}; + +/** Mirrors `QueryOutput`. */ +export const QUERY_OUTPUT_SCHEMA = { + type: 'object', + properties: { + command: { type: 'string' }, + api_version: { type: 'string' }, + query: { type: 'string' }, + matches: { type: 'integer' }, + results: { + type: 'array', + items: { + type: 'object', + properties: { + title: { type: 'string' }, + path: { type: 'string' }, + score: { type: 'number' }, + excerpt: { type: 'string' }, + }, + required: ['title', 'path', 'score', 'excerpt'], + }, + }, + saved: { type: 'string' }, + }, + required: ['query', 'matches', 'results'], +}; + +/** Mirrors `FixWikiResult`. */ +export const FIX_OUTPUT_SCHEMA = { + type: 'object', + properties: { + command: { type: 'string' }, + api_version: { type: 'string' }, + dry_run: { type: 'boolean' }, + removed_pages: { type: 'array', items: { type: 'string' } }, + fixed: { type: 'array', items: LINT_FINDING_SCHEMA }, + remaining: { type: 'array', items: LINT_FINDING_SCHEMA }, + fixedCount: { type: 'integer' }, + remainingCount: { type: 'integer' }, + }, + required: ['dry_run', 'removed_pages', 'fixed', 'remaining', 'fixedCount', 'remainingCount'], +}; diff --git a/packages/core/src/mcp/server.ts b/packages/core/src/mcp/server.ts index 7e62bd0..d8dab1a 100644 --- a/packages/core/src/mcp/server.ts +++ b/packages/core/src/mcp/server.ts @@ -3,14 +3,37 @@ import { CallToolRequestSchema, ListToolsRequestSchema, } from '@modelcontextprotocol/sdk/types.js'; +import { CORE_VERSION } from '../constants.js'; import { READ_TOOLS, handleReadToolCall } from './read-tools.js'; -import type { ToolArgs } from './read-tools.js'; +import type { ToolArgs, ToolDefinition } from './read-tools.js'; import { WRITE_TOOLS, handleWriteToolCall } from './write-tools.js'; +import { WORKSPACE_TOOLS, handleWorkspaceToolCall } from './workspace-tools.js'; +import { WikiRootState } from './wiki-root.js'; +import { buildInstructions } from './instructions.js'; import { registerResources } from './resources.js'; import { registerPrompts } from './prompts.js'; +import { registerCompletions } from './completions.js'; const READ_TOOL_NAMES = new Set(READ_TOOLS.map((t) => t.name)); const WRITE_TOOL_NAMES = new Set(WRITE_TOOLS.map((t) => t.name)); +const WORKSPACE_TOOL_NAMES = new Set(WORKSPACE_TOOLS.map((t) => t.name)); + +/** An open book, drawn for the server's icon. */ +const ICON_SVG = + '' + + '' + + ''; +const ICON_DATA_URI = `data:image/svg+xml;base64,${Buffer.from(ICON_SVG).toString('base64')}`; + +export interface CreateMcpServerOptions { + /** + * Wiki root (the `.wiki` directory) the server is bound to. When omitted, + * the server locates the wiki itself and exposes `wiki_open`/`wiki_init`. + */ + wikiRoot?: string; + /** Directory checked for a `.wiki` folder when no root is given. Default: `process.cwd()`. */ + cwd?: string; +} /** * Create a fully-configured MCP server for LLM Wiki. @@ -18,33 +41,69 @@ const WRITE_TOOL_NAMES = new Set(WRITE_TOOLS.map((t) => t.name)); * The returned {@link Server} has all tool handlers registered and is ready to * be connected to a transport (e.g. `StdioServerTransport`). * - * @param wikiRoot Path to the wiki root directory. Every tool handler - * receives this as implicit context so callers don't have to - * supply it per-request. + * @param options The wiki root to bind to, or {@link CreateMcpServerOptions}. + * With no root, the wiki is discovered from the client's + * workspace roots or the working directory, or opened with + * the `wiki_open` tool. */ -export function createMcpServer(wikiRoot: string): Server { +export function createMcpServer(options: string | CreateMcpServerOptions = {}): Server { + const opts: CreateMcpServerOptions = typeof options === 'string' ? { wikiRoot: options } : options; + const discovery = opts.wikiRoot === undefined; + const state = new WikiRootState( + discovery ? { cwd: opts.cwd ?? process.cwd() } : { fixed: opts.wikiRoot }, + ); + + const tools: ToolDefinition[] = [ + ...READ_TOOLS, + ...WRITE_TOOLS, + ...(discovery ? WORKSPACE_TOOLS : []), + ]; + const toolsByName = new Map(tools.map((t) => [t.name, t])); + const server = new Server( - { name: 'llmwiki', version: '0.1.0' }, - { capabilities: { tools: {}, resources: {}, prompts: {} } }, + { + name: 'llmwiki', + title: 'LLM Wiki', + version: CORE_VERSION, + websiteUrl: 'https://github.com/microsoft/llmwiki', + icons: [{ src: ICON_DATA_URI, mimeType: 'image/svg+xml', sizes: ['any'] }], + }, + { + capabilities: { tools: {}, resources: {}, prompts: {}, completions: {} }, + instructions: buildInstructions(state.current, { discovery }), + }, ); + state.attach(server); + const getWikiRoot = () => state.require(server); - // Unified tool listing: read + write tools - server.setRequestHandler(ListToolsRequestSchema, async () => ({ - tools: [...READ_TOOLS, ...WRITE_TOOLS], - })); + server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools })); - // Unified call dispatch: route to the correct handler server.setRequestHandler(CallToolRequestSchema, async (request) => { - const { name, arguments: args } = request.params; + const { name, arguments: rawArgs } = request.params; + const args = (rawArgs ?? {}) as ToolArgs; try { + const tool = toolsByName.get(name); + if (!tool) { + throw new Error(`Unknown tool: ${name}`); + } + let text: string; - if (READ_TOOL_NAMES.has(name)) { - text = await handleReadToolCall(name, (args ?? {}) as ToolArgs, wikiRoot); + if (WORKSPACE_TOOL_NAMES.has(name)) { + text = await handleWorkspaceToolCall(name, args, state, server); + } else if (READ_TOOL_NAMES.has(name)) { + text = await handleReadToolCall(name, args, await getWikiRoot()); } else if (WRITE_TOOL_NAMES.has(name)) { - text = await handleWriteToolCall(name, (args ?? {}) as ToolArgs, wikiRoot); + text = await handleWriteToolCall(name, args, await getWikiRoot()); } else { throw new Error(`Unknown tool: ${name}`); } + + if (tool.outputSchema) { + return { + content: [{ type: 'text' as const, text }], + structuredContent: JSON.parse(text) as Record, + }; + } return { content: [{ type: 'text' as const, text }] }; } catch (err: unknown) { const message = err instanceof Error ? err.message : String(err); @@ -56,10 +115,13 @@ export function createMcpServer(wikiRoot: string): Server { }); // Resource handlers (browsable wiki content) - registerResources(server, wikiRoot); + registerResources(server, getWikiRoot); // Prompt templates (reusable agent workflows) - registerPrompts(server, wikiRoot); + registerPrompts(server); + + // Argument completions for resource templates and prompts + registerCompletions(server, getWikiRoot); return server; } diff --git a/packages/core/src/mcp/wiki-root.ts b/packages/core/src/mcp/wiki-root.ts new file mode 100644 index 0000000..c622d23 --- /dev/null +++ b/packages/core/src/mcp/wiki-root.ts @@ -0,0 +1,134 @@ +import { basename, join, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import type { Server } from '@modelcontextprotocol/sdk/server/index.js'; +import { RootsListChangedNotificationSchema } from '@modelcontextprotocol/sdk/types.js'; +import { WIKI_DIR_NAME } from '../constants.js'; +import { isWikiInitialized } from '../init.js'; + +/** Raised when a tool needs a wiki but the server has not located one yet. */ +export class NoWikiError extends Error { + constructor() { + super( + 'No LLM Wiki is open. Call wiki_open with the absolute path of the project folder ' + + `that contains the ${WIKI_DIR_NAME} directory (usually the current working directory), ` + + 'or wiki_init to create a new wiki there.', + ); + this.name = 'NoWikiError'; + } +} + +/** + * Resolve the wiki root for `dir`, which may be a project folder containing + * `.wiki/` or the `.wiki` folder itself. Returns `undefined` if neither holds + * an initialized wiki: a `wiki/` directory, the same test wiki_init uses. A + * wiki whose index.md is missing still opens, so wiki_fix can rebuild it. + */ +export function findWikiRoot(dir: string): string | undefined { + const abs = resolve(dir); + const nested = join(abs, WIKI_DIR_NAME); + if (isWikiInitialized(nested)) return nested; + if (basename(abs) === WIKI_DIR_NAME && isWikiInitialized(abs)) return abs; + return undefined; +} + +export type WikiRootSource = 'config' | 'cwd' | 'roots' | 'open'; + +export interface WikiRootStateOptions { + /** Wiki root fixed by configuration (CLI argument or LLMWIKI_ROOT). */ + fixed?: string; + /** Directory to check for `.wiki/` when no root is fixed. */ + cwd?: string; +} + +/** + * Tracks which wiki the MCP server operates on. + * + * With a fixed root (the VS Code extension passes one) nothing else applies. + * Otherwise `/.wiki` is used when it exists at startup; if not, the root + * is discovered on the first tool call from the client's workspace roots (and + * the working directory again, in case a wiki was created since). Agents can + * also choose one explicitly with `wiki_open` / `wiki_init`: agent plugins + * start servers in the plugin folder, and some clients report no roots. + */ +export class WikiRootState { + readonly isFixed: boolean; + private root: string | undefined; + private source: WikiRootSource | undefined; + private readonly cwd: string | undefined; + + constructor(options: WikiRootStateOptions) { + this.isFixed = options.fixed !== undefined; + this.cwd = options.cwd; + if (options.fixed !== undefined) { + this.set(resolve(options.fixed), 'config'); + } else if (options.cwd) { + const found = findWikiRoot(options.cwd); + if (found) this.set(found, 'cwd'); + } + } + + /** The wiki root located so far, if any. */ + get current(): string | undefined { + return this.root; + } + + /** Forget a root discovered from client roots when the client's roots change. */ + attach(server: Server): void { + server.setNotificationHandler(RootsListChangedNotificationSchema, async () => { + if (this.source === 'roots') { + this.root = undefined; + this.source = undefined; + } + }); + } + + /** Return the active wiki root, discovering it if needed. */ + async require(server: Server): Promise { + if (this.root) return this.root; + + for (const folder of await this.workspaceFolders(server)) { + const found = findWikiRoot(folder); + if (found) return this.set(found, 'roots'); + } + + if (this.cwd) { + const found = findWikiRoot(this.cwd); + if (found) return this.set(found, 'cwd'); + } + + throw new NoWikiError(); + } + + /** Absolute paths of the client's `file://` workspace roots (empty if unsupported). */ + async workspaceFolders(server: Server): Promise { + if (!server.getClientCapabilities()?.roots) return []; + try { + const { roots } = await server.listRoots(); + return roots + .filter((r) => r.uri.startsWith('file:')) + .map((r) => fileURLToPath(r.uri)); + } catch { + return []; + } + } + + /** Select a wiki explicitly. Throws if `dir` holds no initialized wiki. */ + open(dir: string): string { + const found = findWikiRoot(dir); + if (!found) { + throw new Error( + `No LLM Wiki found at ${resolve(dir)} (expected a ${WIKI_DIR_NAME}/wiki/ folder). Use wiki_init to create one.`, + ); + } + if (this.isFixed && found !== this.root) { + throw new Error(`This LLM Wiki server is bound to ${this.root} by its configuration.`); + } + return this.set(found, 'open'); + } + + private set(root: string, source: WikiRootSource): string { + this.root = root; + this.source = source; + return root; + } +} diff --git a/packages/core/src/mcp/workspace-tools.ts b/packages/core/src/mcp/workspace-tools.ts new file mode 100644 index 0000000..f846c5f --- /dev/null +++ b/packages/core/src/mcp/workspace-tools.ts @@ -0,0 +1,103 @@ +import { isAbsolute, join } from 'node:path'; +import type { Server } from '@modelcontextprotocol/sdk/server/index.js'; +import { getWikiStatus } from '../status.js'; +import { initWiki } from '../init.js'; +import { WIKI_DIR_NAME } from '../constants.js'; +import { requireString, optionalString } from './read-tools.js'; +import type { ToolArgs, ToolDefinition } from './read-tools.js'; +import type { WikiRootState } from './wiki-root.js'; + +/** + * Tools for choosing or creating the wiki. Only exposed when the server is not + * bound to a fixed wiki root (for example when it runs from an agent plugin). + */ +export const WORKSPACE_TOOLS: ToolDefinition[] = [ + { + name: 'wiki_open', + title: 'Open wiki', + description: + `Select the LLM Wiki to work with. Pass the absolute path of the project folder that contains the ${WIKI_DIR_NAME} directory (usually the current working directory). Call this when another wiki tool reports that no wiki is open.`, + inputSchema: { + type: 'object', + properties: { + path: { + type: 'string', + description: `Absolute path of the project folder (or of its ${WIKI_DIR_NAME} directory)`, + }, + }, + required: ['path'], + additionalProperties: false, + }, + annotations: { readOnlyHint: true, openWorldHint: false }, + }, + { + name: 'wiki_init', + title: 'Initialize wiki', + description: + `Create a new LLM Wiki (${WIKI_DIR_NAME}/ with raw/, wiki/, index.md, log.md and AGENTS.md) in a project folder and open it. Does nothing if the folder already has a wiki.`, + inputSchema: { + type: 'object', + properties: { + path: { + type: 'string', + description: + 'Absolute path of the project folder. Defaults to the first workspace folder reported by the client.', + }, + }, + required: [], + additionalProperties: false, + }, + annotations: { + readOnlyHint: false, + destructiveHint: false, + idempotentHint: true, + openWorldHint: false, + }, + }, +]; + +function requireAbsolute(path: string): string { + if (!isAbsolute(path)) { + throw new Error(`'path' must be an absolute path (got "${path}")`); + } + return path; +} + +/** Resolve a workspace tool call to its result text. */ +export async function handleWorkspaceToolCall( + name: string, + args: ToolArgs, + state: WikiRootState, + server: Server, +): Promise { + switch (name) { + case 'wiki_open': { + const wikiRoot = state.open(requireAbsolute(requireString(args, 'path'))); + const status = await getWikiStatus(wikiRoot); + return JSON.stringify({ + status: 'opened', + wiki_root: wikiRoot, + wiki_page_count: status.wiki_page_count, + source_count: status.source_count, + }); + } + + case 'wiki_init': { + const requested = optionalString(args, 'path'); + const target = requested + ? requireAbsolute(requested) + : (await state.workspaceFolders(server))[0]; + if (!target) { + throw new Error( + "Pass 'path': the absolute path of the project folder to create the wiki in (usually the current working directory).", + ); + } + const result = await initWiki(target); + const wikiRoot = state.open(join(target, WIKI_DIR_NAME)); + return JSON.stringify({ ...result, wiki_root: wikiRoot }); + } + + default: + throw new Error(`Unknown tool: ${name}`); + } +} diff --git a/packages/core/src/mcp/write-tools.ts b/packages/core/src/mcp/write-tools.ts index ce544b2..cfb3453 100644 --- a/packages/core/src/mcp/write-tools.ts +++ b/packages/core/src/mcp/write-tools.ts @@ -1,21 +1,54 @@ -import { join } from 'node:path'; -import { readPage, writePage, createEntityPage, createConceptPage, addCrosslinks } from '../wiki.js'; +import { dirname, join, relative, extname } from 'node:path'; +import { stat } from 'node:fs/promises'; +import { + readPage, + writePage, + createEntityPage, + createConceptPage, + addCrosslinks, + deletePage, + isSpecialWikiFile, +} from '../wiki.js'; +import { withWikiLock } from '../lock.js'; import { slugify } from '../utils.js'; import { readIndex, writeIndex, updateIndexEntry } from '../index-ops.js'; import type { IndexEntry } from '../index-ops.js'; import { isNotFoundError } from '../errors.js'; import { ingestWithContext } from '../ingest-context.js'; +import { fixWiki, normalizeSourceRef } from '../fix.js'; +import { appendEntry } from '../log.js'; import { assertWithinDir, requireString, optionalString, } from './read-tools.js'; -import type { ToolArgs, ToolDefinition } from './read-tools.js'; +import type { ToolAnnotations, ToolArgs, ToolDefinition } from './read-tools.js'; +import { FIX_OUTPUT_SCHEMA } from './schemas.js'; + +/** Overwrites or removes existing content; repeating the call may change more. */ +const DESTRUCTIVE: ToolAnnotations = { + readOnlyHint: false, + destructiveHint: true, + idempotentHint: false, + openWorldHint: false, +}; + +/** Overwrites existing content, but repeating the same call has no further effect. */ +const DESTRUCTIVE_IDEMPOTENT: ToolAnnotations = { ...DESTRUCTIVE, idempotentHint: true }; + +/** Provenance of a derived page; lets wiki_fix remove it when its sources are gone. */ +const SOURCES_PROPERTY = { + type: 'array', + items: { type: 'string' }, + description: + 'Optional wiki-relative paths of the source summary pages this page is derived from (e.g. ["sources/article-summary.md"]). If all of them are later removed, wiki_fix deletes this page.', +}; /** All write tool definitions exposed by the MCP server. */ export const WRITE_TOOLS: ToolDefinition[] = [ { name: 'wiki_write_page', + title: 'Write wiki page', description: 'Create or overwrite a wiki page with frontmatter and body content. Automatically updates the index.', inputSchema: { @@ -46,11 +79,13 @@ export const WRITE_TOOLS: ToolDefinition[] = [ required: ['pagePath', 'title', 'type', 'body'], additionalProperties: false, }, + annotations: DESTRUCTIVE_IDEMPOTENT, }, { name: 'wiki_create_entity', + title: 'Create entity page', description: - 'Create a new wiki entity page at wiki/entities/{slug}.md with proper frontmatter and auto-register it in the index.', + 'Create a new wiki entity page at wiki/entities/{slug}.md with proper frontmatter and auto-register it in the index. Overwrites an existing page with the same slug, so check for one first.', inputSchema: { type: 'object', properties: { @@ -67,15 +102,18 @@ export const WRITE_TOOLS: ToolDefinition[] = [ items: { type: 'string' }, description: 'Optional list of tags', }, + sources: SOURCES_PROPERTY, }, required: ['name', 'content'], additionalProperties: false, }, + annotations: DESTRUCTIVE, }, { name: 'wiki_create_concept', + title: 'Create concept page', description: - 'Create a new wiki concept page at wiki/concepts/{slug}.md with proper frontmatter and auto-register it in the index.', + 'Create a new wiki concept page at wiki/concepts/{slug}.md with proper frontmatter and auto-register it in the index. Overwrites an existing page with the same slug, so check for one first.', inputSchema: { type: 'object', properties: { @@ -92,13 +130,16 @@ export const WRITE_TOOLS: ToolDefinition[] = [ items: { type: 'string' }, description: 'Optional list of tags', }, + sources: SOURCES_PROPERTY, }, required: ['name', 'content'], additionalProperties: false, }, + annotations: DESTRUCTIVE, }, { name: 'wiki_update_page', + title: 'Update wiki page', description: 'Update an existing wiki page by merging partial frontmatter changes and/or appending or replacing body content. Updates the index if metadata changed.', inputSchema: { @@ -129,13 +170,21 @@ export const WRITE_TOOLS: ToolDefinition[] = [ type: 'string', description: 'Content to replace the entire body with', }, + addSources: { + type: 'array', + items: { type: 'string' }, + description: + 'Summary pages of other sources whose content you are adding (e.g. ["sources/second-article-summary.md"]). Appended to the page\'s existing "sources" so it is only deleted once all of its sources are removed. Ignored for pages that list no sources.', + }, }, required: ['pagePath'], additionalProperties: false, }, + annotations: DESTRUCTIVE, }, { name: 'wiki_add_crosslinks', + title: 'Add crosslinks', description: 'Add cross-reference links ("See also" section) from one wiki page to one or more target pages. Validates all target pages exist.', inputSchema: { @@ -154,9 +203,17 @@ export const WRITE_TOOLS: ToolDefinition[] = [ required: ['pagePath', 'targetPages'], additionalProperties: false, }, + // Only appends links and skips duplicates. + annotations: { + readOnlyHint: false, + destructiveHint: false, + idempotentHint: true, + openWorldHint: false, + }, }, { name: 'wiki_update_index', + title: 'Update index entry', description: 'Update metadata (summary, tags, category) for an existing entry in the wiki index. Returns success/failure.', inputSchema: { @@ -183,9 +240,11 @@ export const WRITE_TOOLS: ToolDefinition[] = [ required: ['pagePath'], additionalProperties: false, }, + annotations: DESTRUCTIVE_IDEMPOTENT, }, { name: 'wiki_ingest_with_context', + title: 'Ingest source with context', description: 'Ingest a source file into the wiki and return enhanced context including related pages, word count, content type, and suggested next actions. Use this instead of plain ingest when you want to understand how the source relates to existing wiki content.', inputSchema: { @@ -194,7 +253,7 @@ export const WRITE_TOOLS: ToolDefinition[] = [ sourcePath: { type: 'string', description: - 'Path to the source file to ingest (relative to project root)', + 'Path to the source file inside the wiki root, relative to the wiki root (e.g. "raw/article.md") or absolute', }, dryRun: { type: 'boolean', @@ -209,6 +268,45 @@ export const WRITE_TOOLS: ToolDefinition[] = [ required: ['sourcePath'], additionalProperties: false, }, + // `force` overwrites an existing summary page. + annotations: DESTRUCTIVE, + }, + { + name: 'wiki_fix', + title: 'Fix wiki issues', + description: + 'Apply every deterministic wiki fix: delete entity/concept pages whose raw sources were removed, drop stale index entries, index unlisted pages, and add missing frontmatter defaults. Returns the fixes and the findings that still need judgment (for example broken links). Call with dryRun first to preview; if the preview lists removed_pages, apply only after the user approves deleting them.', + inputSchema: { + type: 'object', + properties: { + dryRun: { + type: 'boolean', + description: 'If true, report what would change without writing anything', + }, + }, + required: [], + additionalProperties: false, + }, + outputSchema: FIX_OUTPUT_SCHEMA, + annotations: DESTRUCTIVE_IDEMPOTENT, + }, + { + name: 'wiki_delete_page', + title: 'Delete wiki page', + description: + 'Delete a wiki page and remove it from the index. Returns the pages that still link to it so you can fix those links. Only use after the user confirms the deletion.', + inputSchema: { + type: 'object', + properties: { + pagePath: { + type: 'string', + description: 'Relative path within the wiki/ directory (e.g. "concepts/ai.md")', + }, + }, + required: ['pagePath'], + additionalProperties: false, + }, + annotations: DESTRUCTIVE_IDEMPOTENT, }, ]; @@ -257,6 +355,57 @@ function optionalStringArray(args: ToolArgs, key: string): string[] | undefined return val as string[]; } +/** + * Validate optional source-page paths (`key` = "sources" or "addSources"): + * each must be an existing summary page under wiki/sources/, such as the one + * returned by wiki_ingest_with_context. Returns de-duplicated wiki-relative + * paths. Rejecting anything else matters because a page whose sources are all + * missing is deleted by wiki_fix. + */ +async function optionalSources( + args: ToolArgs, + wikiDir: string, + key = 'sources', +): Promise { + const sources = optionalStringArray(args, key); + if (!sources || sources.length === 0) return undefined; + if (sources.length > MAX_TAGS_COUNT) { + throw new Error(`Too many ${key} (max ${MAX_TAGS_COUNT})`); + } + const normalized: string[] = []; + for (const source of sources) { + validateLength(source, key, MAX_PATH_LENGTH); + const relPath = normalizeSourceRef( + relative(wikiDir, assertWithinDir(wikiDir, source)).replace(/\\/g, '/'), + ); + let isFile = false; + if (relPath) { + try { + isFile = (await stat(join(wikiDir, relPath))).isFile(); + } catch { + isFile = false; + } + } + if (!relPath || !isFile) { + throw new Error( + `Source page not found: "${source}". Sources must be existing summary pages under sources/, such as the summary_page or pages_created path returned by wiki_ingest_with_context (e.g. "sources/article-summary.md").`, + ); + } + if (!normalized.includes(relPath)) normalized.push(relPath); + } + return normalized; +} + +/** Record the pages a derived page came from in its frontmatter. */ +async function setSources(wikiDir: string, relPath: string, sources: string[]): Promise { + const fullPath = join(wikiDir, relPath); + await withWikiLock(wikiDir, async () => { + const page = await readPage(fullPath); + page.frontmatter.sources = sources; + await writePage(fullPath, page); + }); +} + /** * Derive a category from the page path. * For paths like "concepts/ai.md" → "Concepts". @@ -279,14 +428,16 @@ async function upsertIndexEntry( indexPath: string, entry: IndexEntry, ): Promise { - const entries = await readIndex(indexPath); - const idx = entries.findIndex((e) => e.path === entry.path); - if (idx >= 0) { - entries[idx] = entry; - } else { - entries.push(entry); - } - await writeIndex(indexPath, entries); + await withWikiLock(dirname(indexPath), async () => { + const entries = await readIndex(indexPath); + const idx = entries.findIndex((e) => e.path === entry.path); + if (idx >= 0) { + entries[idx] = entry; + } else { + entries.push(entry); + } + await writeIndex(indexPath, entries); + }); } // --------------------------------------------------------------------------- @@ -318,17 +469,19 @@ export async function handleWriteToolCall( const fullPath = assertWithinDir(wikiDir, pagePath); - await writePage(fullPath, { - frontmatter: { type, title, tags }, - body, - }); + await withWikiLock(wikiDir, async () => { + await writePage(fullPath, { + frontmatter: { type, title, tags }, + body, + }); - await upsertIndexEntry(indexPath, { - path: pagePath, - title, - summary: '', - category: categoryFromPath(pagePath), - tags, + await upsertIndexEntry(indexPath, { + path: pagePath, + title, + summary: '', + category: categoryFromPath(pagePath), + tags, + }); }); return JSON.stringify({ @@ -349,6 +502,7 @@ export async function handleWriteToolCall( validateLength(entityName, 'name', MAX_TITLE_LENGTH); validateLength(content, 'content', MAX_BODY_LENGTH); validateTags(tags); + const sources = await optionalSources(args, wikiDir); // S-3: Reject empty slugs (e.g. all-punctuation or non-Latin names) const slug = slugify(entityName); @@ -359,7 +513,11 @@ export async function handleWriteToolCall( // Validate the derived path stays within wiki dir assertWithinDir(wikiDir, `entities/${slug}.md`); - const result = await createEntityPage(wikiDir, entityName, content, tags); + const result = await withWikiLock(wikiDir, async () => { + const created = await createEntityPage(wikiDir, entityName, content, tags); + if (sources) await setSources(wikiDir, created.path, sources); + return created; + }); return JSON.stringify({ status: 'created', @@ -367,6 +525,7 @@ export async function handleWriteToolCall( title: entityName, type: 'entity', tags, + sources, }); } @@ -379,6 +538,7 @@ export async function handleWriteToolCall( validateLength(conceptName, 'name', MAX_TITLE_LENGTH); validateLength(content, 'content', MAX_BODY_LENGTH); validateTags(tags); + const sources = await optionalSources(args, wikiDir); // S-3: Reject empty slugs (e.g. all-punctuation or non-Latin names) const slug = slugify(conceptName); @@ -389,7 +549,11 @@ export async function handleWriteToolCall( // Validate the derived path stays within wiki dir assertWithinDir(wikiDir, `concepts/${slug}.md`); - const result = await createConceptPage(wikiDir, conceptName, content, tags); + const result = await withWikiLock(wikiDir, async () => { + const created = await createConceptPage(wikiDir, conceptName, content, tags); + if (sources) await setSources(wikiDir, created.path, sources); + return created; + }); return JSON.stringify({ status: 'created', @@ -397,6 +561,7 @@ export async function handleWriteToolCall( title: conceptName, type: 'concept', tags, + sources, }); } @@ -405,70 +570,90 @@ export async function handleWriteToolCall( validateLength(pagePath, 'pagePath', MAX_PATH_LENGTH); const fullPath = assertWithinDir(wikiDir, pagePath); - // Read existing page — fail gracefully if not found - let existing; - try { - existing = await readPage(fullPath); - } catch (err) { - if (isNotFoundError(err)) { - throw new Error(`Page not found: ${pagePath}`); + // Read, merge and write under the wiki lock so concurrent updates (from + // this server, another one, or the VS Code extension) don't overwrite + // each other's content or sources. + return withWikiLock(wikiDir, async () => { + // Read existing page — fail gracefully if not found + let existing; + try { + existing = await readPage(fullPath); + } catch (err) { + if (isNotFoundError(err)) { + throw new Error(`Page not found: ${pagePath}`); + } + throw err; } - throw err; - } - // Merge frontmatter updates - const newTitle = optionalString(args, 'title'); - // S-7: Reject empty titles - if (newTitle !== undefined && newTitle.length === 0) { - throw new Error("'title' must be non-empty when provided"); - } - if (newTitle !== undefined) validateLength(newTitle, 'title', MAX_TITLE_LENGTH); - const newType = optionalString(args, 'type'); - const newTags = optionalStringArray(args, 'tags'); - validateTags(newTags); - - const mergedFrontmatter = { ...existing.frontmatter }; - if (newTitle !== undefined) mergedFrontmatter.title = newTitle; - if (newType !== undefined) mergedFrontmatter.type = newType; - if (newTags !== undefined) mergedFrontmatter.tags = newTags; - - // Handle body updates - const bodyAppend = optionalString(args, 'bodyAppend'); - if (bodyAppend !== undefined) validateLength(bodyAppend, 'bodyAppend', MAX_BODY_LENGTH); - const bodyReplace = optionalString(args, 'bodyReplace'); - if (bodyReplace !== undefined) validateLength(bodyReplace, 'bodyReplace', MAX_BODY_LENGTH); - - let mergedBody = existing.body; - if (bodyReplace !== undefined) { - mergedBody = bodyReplace; - } else if (bodyAppend !== undefined) { - mergedBody = existing.body + '\n\n' + bodyAppend; - } + // Merge frontmatter updates + const newTitle = optionalString(args, 'title'); + // S-7: Reject empty titles + if (newTitle !== undefined && newTitle.length === 0) { + throw new Error("'title' must be non-empty when provided"); + } + if (newTitle !== undefined) validateLength(newTitle, 'title', MAX_TITLE_LENGTH); + const newType = optionalString(args, 'type'); + const newTags = optionalStringArray(args, 'tags'); + validateTags(newTags); + + const mergedFrontmatter = { ...existing.frontmatter }; + if (newTitle !== undefined) mergedFrontmatter.title = newTitle; + if (newType !== undefined) mergedFrontmatter.type = newType; + if (newTags !== undefined) mergedFrontmatter.tags = newTags; + + // Extend the provenance of a derived page. Pages without sources are not + // derived from a raw source and must never become eligible for cleanup. + const addSources = await optionalSources(args, wikiDir, 'addSources'); + let sourcesUpdated = false; + const currentSources = existing.frontmatter.sources; + if (addSources && Array.isArray(currentSources) && currentSources.length > 0) { + const mergedSources = [...currentSources]; + for (const source of addSources) { + if (!mergedSources.includes(source)) mergedSources.push(source); + } + sourcesUpdated = mergedSources.length !== currentSources.length; + mergedFrontmatter.sources = mergedSources; + } - await writePage(fullPath, { - frontmatter: mergedFrontmatter, - body: mergedBody, - }); + // Handle body updates + const bodyAppend = optionalString(args, 'bodyAppend'); + if (bodyAppend !== undefined) validateLength(bodyAppend, 'bodyAppend', MAX_BODY_LENGTH); + const bodyReplace = optionalString(args, 'bodyReplace'); + if (bodyReplace !== undefined) validateLength(bodyReplace, 'bodyReplace', MAX_BODY_LENGTH); + + let mergedBody = existing.body; + if (bodyReplace !== undefined) { + mergedBody = bodyReplace; + } else if (bodyAppend !== undefined) { + mergedBody = existing.body + '\n\n' + bodyAppend; + } - // Update index if metadata changed - const metadataChanged = - newTitle !== undefined || newType !== undefined || newTags !== undefined; - if (metadataChanged) { - await upsertIndexEntry(indexPath, { - path: pagePath, - title: (mergedFrontmatter.title as string) ?? '', - summary: '', - category: categoryFromPath(pagePath), - tags: (mergedFrontmatter.tags as string[]) ?? [], + await writePage(fullPath, { + frontmatter: mergedFrontmatter, + body: mergedBody, }); - } - return JSON.stringify({ - status: 'updated', - path: pagePath, - frontmatter: mergedFrontmatter, - bodyUpdated: bodyAppend !== undefined || bodyReplace !== undefined, - indexUpdated: metadataChanged, + // Update index if metadata changed + const metadataChanged = + newTitle !== undefined || newType !== undefined || newTags !== undefined; + if (metadataChanged) { + await upsertIndexEntry(indexPath, { + path: pagePath, + title: (mergedFrontmatter.title as string) ?? '', + summary: '', + category: categoryFromPath(pagePath), + tags: (mergedFrontmatter.tags as string[]) ?? [], + }); + } + + return JSON.stringify({ + status: 'updated', + path: pagePath, + frontmatter: mergedFrontmatter, + bodyUpdated: bodyAppend !== undefined || bodyReplace !== undefined, + indexUpdated: metadataChanged, + sourcesUpdated, + }); }); } @@ -525,14 +710,54 @@ export async function handleWriteToolCall( case 'wiki_ingest_with_context': { const sourcePath = requireString(args, 'sourcePath'); validateLength(sourcePath, 'sourcePath', MAX_PATH_LENGTH); - // Validate source path stays within project root - assertWithinDir(wikiRoot, sourcePath); + // Resolve relative paths against the wiki root (not the server's cwd) + // and keep the source inside it. + const fullSourcePath = assertWithinDir(wikiRoot, sourcePath); const dryRun = args.dryRun === true; const force = args.force === true; - const result = await ingestWithContext(sourcePath, wikiRoot, dryRun, force); + const result = await ingestWithContext(fullSourcePath, wikiRoot, dryRun, force); return JSON.stringify(result); } + case 'wiki_fix': { + const dryRun = args.dryRun === true; + return JSON.stringify(await fixWiki(wikiRoot, { dryRun })); + } + + case 'wiki_delete_page': { + const pagePath = requireString(args, 'pagePath'); + validateLength(pagePath, 'pagePath', MAX_PATH_LENGTH); + const relPath = relative(wikiDir, assertWithinDir(wikiDir, pagePath)).replace(/\\/g, '/'); + if (isSpecialWikiFile(relPath)) { + throw new Error(`'${relPath}' is a special wiki file and cannot be deleted`); + } + if (extname(relPath) !== '.md') { + throw new Error("'pagePath' must point to a markdown page (.md)"); + } + + // deletePage repeats these checks after resolving symlinked folders. + const result = await deletePage(wikiDir, relPath); + // deletePage already removed the index entry, so only report real pages. + const linkedFrom = result.backlinkWarnings + .map((b) => ({ + page: relative(wikiDir, b.sourcePage).replace(/\\/g, '/'), + title: b.sourceTitle, + linkText: b.linkText, + })) + .filter((l) => !isSpecialWikiFile(l.page)); + + await appendEntry(join(wikiDir, 'log.md'), { + verb: 'deleted', + subject: relPath, + details: + linkedFrom.length > 0 + ? `Page deleted. Still linked from: ${linkedFrom.map((l) => l.page).join(', ')}.` + : 'Page deleted.', + }); + + return JSON.stringify({ status: 'deleted', path: relPath, linkedFrom }); + } + default: throw new Error(`Unknown tool: ${name}`); } diff --git a/packages/core/src/query.ts b/packages/core/src/query.ts index 5e67962..b83c301 100644 --- a/packages/core/src/query.ts +++ b/packages/core/src/query.ts @@ -3,6 +3,7 @@ import { mkdir } from 'node:fs/promises'; import { readPage, writePage, directoryExists } from './wiki.js'; import { readIndex, type IndexEntry } from './index-ops.js'; import { appendEntry } from './log.js'; +import { withWikiLock } from './lock.js'; import { countOccurrences } from './search.js'; import { excerpt } from './utils.js'; import { API_VERSION } from './constants.js'; @@ -137,21 +138,23 @@ export async function queryWiki( body += `- **Excerpt:** ${r.excerpt}\n\n`; } - await writePage(queryFullPath, { - frontmatter: { - type: 'query', - title: `Query: ${queryStr}`, - created: today, - query: queryStr, - }, - body: body.trim(), - }); - - const logPath = join(wikiDir, 'log.md'); - await appendEntry(logPath, { - verb: 'queried', - subject: queryStr, - details: `Saved query "${queryStr}" → ${queryRelPath} (${results.length} results)`, + await withWikiLock(wikiDir, async () => { + await writePage(queryFullPath, { + frontmatter: { + type: 'query', + title: `Query: ${queryStr}`, + created: today, + query: queryStr, + }, + body: body.trim(), + }); + + const logPath = join(wikiDir, 'log.md'); + await appendEntry(logPath, { + verb: 'queried', + subject: queryStr, + details: `Saved query "${queryStr}" → ${queryRelPath} (${results.length} results)`, + }); }); output.saved = queryRelPath; diff --git a/packages/core/src/wiki.ts b/packages/core/src/wiki.ts index f513d75..d0050fa 100644 --- a/packages/core/src/wiki.ts +++ b/packages/core/src/wiki.ts @@ -1,9 +1,10 @@ import matter from 'gray-matter'; -import { readFile, writeFile, readdir, stat, mkdir, unlink } from 'node:fs/promises'; -import { join, dirname, extname, relative, resolve } from 'node:path'; +import { readFile, writeFile, readdir, stat, mkdir, unlink, realpath } from 'node:fs/promises'; +import { join, dirname, extname, relative, resolve, basename, isAbsolute, sep } from 'node:path'; import { isNotFoundError } from './errors.js'; +import { withWikiLock } from './lock.js'; import { slugify } from './utils.js'; -import { addEntry, escapeMarkdownLinkText, readIndex, removeEntry, writeIndex } from './index-ops.js'; +import { escapeMarkdownLinkText, readIndex, removeEntry, upsertEntry, writeIndex } from './index-ops.js'; import type { IndexEntry } from './index-ops.js'; import { getBacklinks } from './backlinks.js'; import type { BacklinkResult } from './backlinks.js'; @@ -25,7 +26,10 @@ export interface WikiPage { export async function readPage(filePath: string): Promise { const raw = await readFile(filePath, 'utf-8'); - const { data, content } = matter(raw); + // Passing options bypasses gray-matter's content-keyed cache, which hands + // out shared `data` objects: a caller mutating one page's frontmatter would + // otherwise change what later reads of identical content return. + const { data, content } = matter(raw, {}); return { frontmatter: data as WikiPageFrontmatter, body: content.trim(), @@ -112,28 +116,30 @@ export async function createEntityPage( const fullPath = join(wikiDir, relPath); const now = new Date().toISOString(); - await writePage(fullPath, { - frontmatter: { - type: 'entity', + return withWikiLock(wikiDir, async () => { + await writePage(fullPath, { + frontmatter: { + type: 'entity', + title: name, + tags, + created: now, + }, + body: content, + }); + + const indexEntry: IndexEntry = { + path: relPath, title: name, + summary: '', + category: 'Entities', tags, - created: now, - }, - body: content, - }); + }; - const indexEntry: IndexEntry = { - path: relPath, - title: name, - summary: '', - category: 'Entities', - tags, - }; + const indexPath = join(wikiDir, 'index.md'); + await upsertEntry(indexPath, indexEntry); - const indexPath = join(wikiDir, 'index.md'); - await addEntry(indexPath, indexEntry); - - return { path: relPath, indexEntry }; + return { path: relPath, indexEntry }; + }); } /** @@ -151,28 +157,110 @@ export async function createConceptPage( const fullPath = join(wikiDir, relPath); const now = new Date().toISOString(); - await writePage(fullPath, { - frontmatter: { - type: 'concept', + return withWikiLock(wikiDir, async () => { + await writePage(fullPath, { + frontmatter: { + type: 'concept', + title: name, + tags, + created: now, + }, + body: content, + }); + + const indexEntry: IndexEntry = { + path: relPath, title: name, + summary: '', + category: 'Concepts', tags, - created: now, - }, - body: content, + }; + + const indexPath = join(wikiDir, 'index.md'); + await upsertEntry(indexPath, indexEntry); + + return { path: relPath, indexEntry }; }); +} - const indexEntry: IndexEntry = { - path: relPath, - title: name, - summary: '', - category: 'Concepts', - tags, - }; +export interface UpsertDerivedPageResult extends CreatePageResult { + /** False when an existing page was extended instead. */ + created: boolean; +} - const indexPath = join(wikiDir, 'index.md'); - await addEntry(indexPath, indexEntry); +/** + * Create an entity or concept page derived from a source summary page, or — + * if a page with the same slug exists — extend it instead of overwriting it: + * the content is added before any "## See also" section (unless already + * present), tags are combined, and `sourcePage` is added to `sources` when the + * page already lists sources. New pages record `sources: [sourcePage]`. + * + * The read, merge and write happen under the wiki lock, so concurrent ingests + * (in this process or another one) extend the page one after the other + * instead of overwriting each other's content and sources. + */ +export async function upsertDerivedPage( + wikiDir: string, + kind: 'entity' | 'concept', + name: string, + content: string, + tags: string[] = [], + sourcePage?: string, +): Promise { + const relPath = `${kind === 'entity' ? 'entities' : 'concepts'}/${slugify(name)}.md`; + const fullPath = join(wikiDir, relPath); + + return withWikiLock(wikiDir, async () => { + let existing: WikiPage | undefined; + try { + existing = await readPage(fullPath); + } catch (err) { + if (!isNotFoundError(err)) throw err; + } + + if (!existing) { + const result = + kind === 'entity' + ? await createEntityPage(wikiDir, name, content, tags) + : await createConceptPage(wikiDir, name, content, tags); + if (sourcePage) { + const page = await readPage(fullPath); + page.frontmatter.sources = [sourcePage]; + await writePage(fullPath, page); + } + return { ...result, created: true }; + } + + const frontmatter: WikiPageFrontmatter = { ...existing.frontmatter }; + const existingTags = Array.isArray(frontmatter.tags) ? frontmatter.tags : []; + frontmatter.tags = [...new Set([...existingTags, ...tags])]; + const sources = frontmatter.sources; + if (sourcePage && Array.isArray(sources) && sources.length > 0 && !sources.includes(sourcePage)) { + frontmatter.sources = [...sources, sourcePage]; + } - return { path: relPath, indexEntry }; + let body = existing.body; + const addition = content.trim(); + if (addition && !body.includes(addition)) { + const seeAlso = body.search(/^## See also\b/m); + body = + seeAlso >= 0 + ? `${body.slice(0, seeAlso).trimEnd()}\n\n${addition}\n\n${body.slice(seeAlso)}` + : `${body.trimEnd()}\n\n${addition}`; + } + await writePage(fullPath, { frontmatter, body }); + + const indexEntry: IndexEntry = { + path: relPath, + title: (frontmatter.title as string | undefined) || name, + summary: '', + category: kind === 'entity' ? 'Entities' : 'Concepts', + tags: frontmatter.tags, + }; + await upsertEntry(join(wikiDir, 'index.md'), indexEntry); + + return { path: relPath, indexEntry, created: false }; + }); } /** @@ -180,6 +268,7 @@ export async function createConceptPage( * Validates all source and target pages exist, reads target titles from * frontmatter, and appends (or extends) a "## See also" section with * relative markdown links. Duplicate links are silently skipped. + * Runs under the wiki lock, like other page updates. */ export async function addCrosslinks( wikiDir: string, @@ -187,7 +276,14 @@ export async function addCrosslinks( toPages: string[], ): Promise { if (toPages.length === 0) return; + await withWikiLock(wikiDir, () => appendCrosslinks(wikiDir, fromPage, toPages)); +} +async function appendCrosslinks( + wikiDir: string, + fromPage: string, + toPages: string[], +): Promise { const fromFull = join(wikiDir, fromPage); // Validate fromPage exists @@ -285,12 +381,63 @@ export interface DeleteResult { backlinkWarnings: BacklinkResult[]; } +/** + * True for the wiki's own index.md and log.md (wiki-relative path), in any + * letter case: on case-insensitive file systems `Index.md` is the index. + */ +export function isSpecialWikiFile(relPath: string): boolean { + const normalized = relPath.replace(/\\/g, '/').toLowerCase(); + return normalized === 'index.md' || normalized === 'log.md'; +} + +/** True when `target` is strictly inside `base` (both absolute). */ +function isInside(base: string, target: string): boolean { + const rel = relative(base, target); + return rel !== '' && rel !== '..' && !rel.startsWith(`..${sep}`) && !isAbsolute(rel); +} + +/** + * Resolve the file that `deletePage` may remove. The path must stay inside + * the wiki both as written and after resolving symlinked folders (so a link + * such as wiki/linked -> ../raw can't delete a raw source), and must not be + * index.md or log.md at either location. Returns the resolved path. + */ +async function resolveDeletablePage(wikiDir: string, pagePath: string): Promise { + const base = resolve(wikiDir); + const full = resolve(base, pagePath); + if (!isInside(base, full)) { + throw new Error('Path traversal detected — pagePath must stay within wikiDir'); + } + + let realBase: string; + let realParent: string; + try { + realBase = await realpath(base); + realParent = await realpath(dirname(full)); + } catch (err) { + if (isNotFoundError(err)) throw new Error(`Page not found: ${pagePath}`); + throw err; + } + const realFull = join(realParent, basename(full)); + if (!isInside(realBase, realFull)) { + throw new Error('Path traversal detected — pagePath must stay within wikiDir'); + } + + for (const rel of [relative(base, full), relative(realBase, realFull)]) { + if (isSpecialWikiFile(rel)) { + throw new Error(`'${rel.replace(/\\/g, '/')}' is a special wiki file and cannot be deleted`); + } + } + return realFull; +} + /** * Delete a wiki page by relative path. * Validates the page exists, computes backlink warnings, removes the index * entry, then deletes the file from disk. * - * Security: validates pagePath stays within wikiDir (no path traversal). + * Security: pagePath must stay within wikiDir, also after resolving symlinked + * folders, and can't be index.md or log.md (in any letter case). * Order: index entry removed FIRST, then file deleted (safer to have orphan * file than orphan index entry). */ @@ -298,39 +445,36 @@ export async function deletePage( wikiDir: string, pagePath: string, ): Promise { - // 1. Path traversal validation - const resolvedBase = resolve(wikiDir).replace(/\\/g, '/'); - const resolvedFull = resolve(wikiDir, pagePath).replace(/\\/g, '/'); - if (!resolvedFull.startsWith(resolvedBase + '/') && resolvedFull !== resolvedBase) { - throw new Error('Path traversal detected — pagePath must stay within wikiDir'); - } + // 1. Path traversal and special-file validation + const fullPath = await resolveDeletablePage(wikiDir, pagePath); - // 2. Validate page exists - const fullPath = join(wikiDir, pagePath); - try { - await stat(fullPath); - } catch (err) { - if (isNotFoundError(err)) { - throw new Error(`Page not found: ${pagePath}`); + return withWikiLock(wikiDir, async () => { + // 2. Validate page exists + try { + await stat(fullPath); + } catch (err) { + if (isNotFoundError(err)) { + throw new Error(`Page not found: ${pagePath}`); + } + throw err; } - throw err; - } - // 3. Compute backlinks before deletion - const backlinkWarnings = await getBacklinks(wikiDir, pagePath); + // 3. Compute backlinks before deletion + const backlinkWarnings = await getBacklinks(wikiDir, pagePath); - // 4. Remove index entry FIRST (safer order) - const indexPath = join(wikiDir, 'index.md'); - await removeEntry(indexPath, pagePath); + // 4. Remove index entry FIRST (safer order) + const indexPath = join(wikiDir, 'index.md'); + await removeEntry(indexPath, pagePath); - // 5. Delete the file from disk - await unlink(fullPath); + // 5. Delete the file from disk + await unlink(fullPath); - return { - deletedPath: pagePath, - deleted: true, - backlinkWarnings, - }; + return { + deletedPath: pagePath, + deleted: true, + backlinkWarnings, + }; + }); } export interface RenameResult { @@ -349,7 +493,8 @@ export interface RenameResult { /** * Rename (move) a wiki page from oldPath to newPath. * Rewrites backlinks across the wiki, updates the index entry, and - * optionally updates a path-derived frontmatter title. + * optionally updates a path-derived frontmatter title. Runs under the wiki + * lock, like other page updates. * * Security: validates both paths stay within wikiDir (no path traversal). */ @@ -357,6 +502,14 @@ export async function renamePage( wikiDir: string, oldPath: string, newPath: string, +): Promise { + return withWikiLock(wikiDir, () => movePage(wikiDir, oldPath, newPath)); +} + +async function movePage( + wikiDir: string, + oldPath: string, + newPath: string, ): Promise { // 1. Path traversal guard on BOTH paths const resolvedBase = resolve(wikiDir).replace(/\\/g, '/'); diff --git a/packages/vscode/CHANGELOG.md b/packages/vscode/CHANGELOG.md index 1947b18..f0aab53 100644 --- a/packages/vscode/CHANGELOG.md +++ b/packages/vscode/CHANGELOG.md @@ -5,6 +5,50 @@ All notable changes to the LLM Wiki VS Code extension will be documented in this The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [Unreleased] + +VS Code deprecated chat participants, and the Copilot harness (which VS Code 1.142 began rolling out as the default for new chat sessions) doesn't run them. This release replaces `@wiki` with skills, a custom agent and a richer MCP server. It is a breaking change. + +### Removed + +- The `@wiki` chat participant. Migration: + + | Before | Now | + |--------|-----| + | `@wiki ` | Ask in Agent mode, or `/wiki-ask ` | + | `@wiki /status` | Status bar, **LLM Wiki: Show Status**, or the `wiki_status` tool | + | `@wiki /lint` | **LLM Wiki: Run Lint**, or the `wiki_lint` tool | + | `@wiki /fix` | **LLM Wiki: Fix Issues**, then `/wiki-fix` for the rest | + | `@wiki /save` | `/wiki-save [title]` | + +### Added + +- Copilot skills contributed by the extension: `/wiki-ask`, `/wiki-research`, `/wiki-ingest`, `/wiki-save` and `/wiki-fix`. +- **Wiki Librarian** custom agent and instructions for files under `.wiki/`. +- Agent plugin (`plugin/`) with the same skills and agent plus a self-contained MCP server, for Copilot CLI, the GitHub Copilot app and other Agent Plugins clients (`copilot plugin install microsoft/llmwiki:plugin`). +- **LLM Wiki: Run Lint** and **LLM Wiki: Fix Remaining Issues with Copilot** commands, and the **Lint Findings** view. +- MCP server: `wiki_fix` and `wiki_delete_page` tools; `wiki_open` and `wiki_init` when the server isn't bound to a wiki root; tool titles and annotations (read-only tools no longer prompt for confirmation in VS Code); server instructions that include the wiki's `AGENTS.md`; structured output for `wiki_status`, `wiki_query`, `wiki_lint` and `wiki_fix`; argument completions; a server icon and version. +- `wiki_create_entity` and `wiki_create_concept` accept `sources`, and `wiki_update_page` accepts `addSources`, so pages created or extended by agents are cleaned up when all of their sources are removed. +- The `llmwiki-mcp` launcher reads `LLMWIKI_ROOT` and, without a wiki root, finds the wiki from the client's workspace roots. +- `wiki_ingest_with_context` reports the existing `summary_page` when a source was already ingested. + +### Changed + +- **LLM Wiki: Fix Issues** applies the deterministic fixes directly and lists what still needs judgment, instead of opening `@wiki /fix`. It no longer lets the model delete pages without confirmation. +- Removing a source (**Remove Source**, or deleting a file from `raw/`) deletes only the pages that have no other remaining source; pages that also draw on another source are kept. +- The extension's LLM ingest extends an entity or concept page that already exists (adding the new content, tags and source) instead of overwriting it, and keeps a summary page that was edited while the model was running. +- Requires VS Code 1.109 or later. + +### Fixed + +- `wiki_ingest_with_context` resolves relative `sourcePath` values (such as `raw/article.md`) against the wiki root instead of the server's working directory. +- **Refresh** and **Fix Issues** no longer delete pages whose `sources` list something other than summary pages (such as `raw/` paths or URLs); only `sources/.md` entries are tracked. +- Lint auto-fix no longer adds an unindexed orphan page to the index twice, and creating an entity or concept page that already exists updates its index entry instead of adding a duplicate. +- Reading a page no longer returns frontmatter mutated by an earlier caller when the file's content repeats (gray-matter cache), which could make lint miss findings in long-running processes such as the MCP server. +- The MCP server definition sets `ELECTRON_RUN_AS_NODE` explicitly, so it also starts when spawned by a process that doesn't inherit it. +- Concurrent writers no longer overwrite each other's changes. For example, two ingests that extend the same entity page now both keep their content and `sources`. Page and index updates hold a write lock (`wiki/.llmwiki.lock`) that the extension and every MCP server process share. +- Deleting pages (**Remove Source**, cleanup after a source is removed, `wiki_delete_page`) never deletes `index.md` or `log.md` under another letter case. It also refuses paths that leave the wiki through a symlinked folder. + ## [1.0.1] — 2026-10-12 ### Security diff --git a/packages/vscode/README.md b/packages/vscode/README.md index e654d9d..79fddec 100644 --- a/packages/vscode/README.md +++ b/packages/vscode/README.md @@ -10,7 +10,7 @@ Interactive wiki browsing powered by LLM maintenance. Browse, query, and grow yo - **Lint Findings panel** — Review wiki quality issues grouped by severity; click to jump to the affected file. - **Status bar integration** — Live page count, tooltip with coverage %, click for a full status notification. - **Bulk ingest** — Pick multiple files, pick a folder, or right-click a selection in the Explorer. -- **`@wiki` chat participant** — Talk to the wiki through Copilot Chat with slash commands. +- **Copilot skills and the Wiki Librarian agent** — Ask, research, ingest, save and fix from Copilot Chat with `/wiki-ask`, `/wiki-research`, `/wiki-ingest`, `/wiki-save` and `/wiki-fix`, backed by the bundled LLM Wiki MCP server. ## Installation @@ -44,8 +44,10 @@ npm run package --workspace=packages/vscode | `llmwiki.search` | LLM Wiki: Search Wiki | Filter entities/concepts by title, summary, or tag | | `llmwiki.searchRaw` | LLM Wiki: Search Sources | Find a raw source file by name | | `llmwiki.refresh` | LLM Wiki: Refresh | Run lint-fix, prune orphaned pages, and refresh views | -| `llmwiki.fix` | LLM Wiki: Fix Issues | Open the `@wiki /fix` chat to interactively resolve findings | -| `llmwiki.removeSource` | LLM Wiki: Remove Source | Delete a raw source plus the wiki pages derived from it | +| `llmwiki.lint` | LLM Wiki: Run Lint | Run health checks and show the results in the Lint Findings view | +| `llmwiki.fix` | LLM Wiki: Fix Issues | Apply the deterministic fixes and list what still needs judgment in Lint Findings | +| `llmwiki.fixWithCopilot` | LLM Wiki: Fix Remaining Issues with Copilot | Open Copilot Chat with the `/wiki-fix` skill | +| `llmwiki.removeSource` | LLM Wiki: Remove Source | Delete a raw source, its summary page, and the wiki pages derived only from it | ## Bulk Ingest @@ -72,16 +74,17 @@ The extension contributes an **LLM Wiki** activity-bar container with four tree - **Wiki Pages** — Entities, Concepts, and Sources read from `wiki/index.md`. - **Raw Sources** — Files in `raw/`, grouped by subdirectory if any exist. - **Backlinks** — Pages that link to the currently open wiki page. -- **Lint Findings** — Errors, warnings, and info populated by the last lint run. +- **Lint Findings** — Errors, warnings, and info from the last **Run Lint**, **Fix Issues** or **Refresh**. -## `@wiki` Chat Participant +## Copilot Chat -Open the Chat view and type `@wiki` to converse with the wiki via GitHub Copilot: +In workspaces with a wiki, the extension contributes: -- `@wiki /status` — show wiki statistics. -- `@wiki /save` — save the previous answer as a wiki page. -- `@wiki /lint` — run health checks and get fix suggestions. -- `@wiki /fix` — auto-fix lint issues using the LLM. +- **Skills** — `/wiki-ask`, `/wiki-research` and `/wiki-ingest` (Copilot also loads these automatically when relevant), plus `/wiki-save` and `/wiki-fix`, which run only when you invoke them. +- **Wiki Librarian** — a custom agent in the agent picker. +- **Instructions** for files under `.wiki/`. + +They work in both the Copilot harness and the Local harness. The `@wiki` chat participant was removed because VS Code deprecated chat participants; see the [migration table](https://github.com/microsoft/llmwiki#migrating-from-wiki). ## Configuration @@ -89,17 +92,17 @@ The extension activates automatically when a workspace contains a wiki at `.wiki ## Requirements -- **VS Code** 1.93 or later +- **VS Code** 1.109 or later - **Node.js** 20.x or later (for building from source) - **GitHub Copilot** subscription (the extension uses the VS Code Language Model API for ingestion enrichment) ## Architecture -The extension uses `@llmwiki/core` exclusively for wiki logic — no operations are duplicated in extension code. Commands delegate to shared functions like `ingestSource`, `queryWiki`, `getWikiStatus`, `lintWiki`, and `getBacklinks`, keeping the extension a thin UI layer. +The extension uses `@llmwiki/core` exclusively for wiki logic — no operations are duplicated in extension code. Commands delegate to shared functions like `ingestSource`, `queryWiki`, `getWikiStatus`, `lintWiki`, `fixWiki`, and `getBacklinks`, keeping the extension a thin UI layer. ## MCP Server -The extension automatically registers an MCP (Model Context Protocol) server named **LLM Wiki** with Copilot Chat (via the `mcpServerDefinitionProviders` contribution) — no configuration required. Open the Chat view's MCP server picker and you'll see it listed; tools are available to any chat session that opts in. +The extension automatically registers an MCP (Model Context Protocol) server named **LLM Wiki** with Copilot Chat (via the `mcpServerDefinitionProviders` contribution) — no configuration required. Open the Chat view's MCP server picker and you'll see it listed; tools are available to any chat session that opts in. Read-only tools are annotated so they run without confirmation prompts. The same server can be used from Claude Desktop, Cursor, or any other MCP-compatible client via the `llmwiki-mcp` stdio launcher shipped by `@llmwiki/core`: diff --git a/packages/vscode/esbuild.config.mjs b/packages/vscode/esbuild.config.mjs index 31b176b..b9f639b 100644 --- a/packages/vscode/esbuild.config.mjs +++ b/packages/vscode/esbuild.config.mjs @@ -1,4 +1,5 @@ import * as esbuild from 'esbuild'; +import { cp, rm } from 'node:fs/promises'; const watch = process.argv.includes('--watch'); const production = process.argv.includes('--production'); @@ -33,6 +34,30 @@ const mcpBuildOptions = { treeShaking: true, }; +// The agent plugin (../../plugin) ships the same server as a committed, +// self-contained bundle so `copilot plugin install microsoft/llmwiki:plugin` +// works without npm. Always minified and without a source map so the output +// is identical on every machine; CI fails if the committed copy is stale. +const pluginServerBuildOptions = { + ...mcpBuildOptions, + outfile: '../../plugin/server/llmwiki-mcp.cjs', + sourcemap: false, + minify: true, + legalComments: 'eof', +}; + +// Skills, the custom agent and the instructions file are authored once in the +// agent plugin and contributed by the extension (package.json `chatSkills`, +// `chatAgents`, `chatInstructions`) from these copies. +async function copyChatCustomizations() { + await rm('out/chat', { recursive: true, force: true }); + await cp('../../plugin/skills', 'out/chat/skills', { recursive: true }); + await cp('../../plugin/com.github.copilot/agents', 'out/chat/agents', { recursive: true }); + await cp('../../plugin/com.github.copilot/rules', 'out/chat/instructions', { recursive: true }); +} + +await copyChatCustomizations(); + if (watch) { const ctx = await esbuild.context(buildOptions); const mcpCtx = await esbuild.context(mcpBuildOptions); @@ -42,5 +67,6 @@ if (watch) { } else { await esbuild.build(buildOptions); await esbuild.build(mcpBuildOptions); - console.log(`Build complete: out/extension.js${production ? ' (minified)' : ''}`); + await esbuild.build(pluginServerBuildOptions); + console.log(`Build complete: out/extension.js${production ? ' (minified)' : ''}, plugin/server/llmwiki-mcp.cjs`); } diff --git a/packages/vscode/package.json b/packages/vscode/package.json index e4425cb..00b8304 100644 --- a/packages/vscode/package.json +++ b/packages/vscode/package.json @@ -5,7 +5,7 @@ "version": "1.0.1", "publisher": "eag-rss", "engines": { - "vscode": "^1.101.0" + "vscode": "^1.109.0" }, "categories": [ "Other" @@ -23,7 +23,8 @@ "onView:entities", "onView:concepts", "onView:rawSources", - "onView:backlinks" + "onView:backlinks", + "onView:lintFindings" ], "contributes": { "mcpServerDefinitionProviders": [ @@ -32,31 +33,38 @@ "label": "LLM Wiki" } ], - "chatParticipants": [ - { - "id": "llmwiki.wiki", - "fullName": "LLM Wiki", - "name": "wiki", - "description": "Ask questions about your wiki knowledge base", - "isSticky": true, - "commands": [ - { - "name": "status", - "description": "Show wiki status and statistics" - }, - { - "name": "save", - "description": "Save the previous answer as a wiki page" - }, - { - "name": "lint", - "description": "Run wiki health checks and get fix suggestions" - }, - { - "name": "fix", - "description": "Auto-fix wiki issues using LLM" - } - ] + "chatSkills": [ + { + "path": "./out/chat/skills/wiki-ask/SKILL.md", + "when": "llmwiki.isWikiWorkspace" + }, + { + "path": "./out/chat/skills/wiki-research/SKILL.md", + "when": "llmwiki.isWikiWorkspace" + }, + { + "path": "./out/chat/skills/wiki-ingest/SKILL.md", + "when": "llmwiki.isWikiWorkspace" + }, + { + "path": "./out/chat/skills/wiki-save/SKILL.md", + "when": "llmwiki.isWikiWorkspace" + }, + { + "path": "./out/chat/skills/wiki-fix/SKILL.md", + "when": "llmwiki.isWikiWorkspace" + } + ], + "chatAgents": [ + { + "path": "./out/chat/agents/wiki-librarian.agent.md", + "when": "llmwiki.isWikiWorkspace" + } + ], + "chatInstructions": [ + { + "path": "./out/chat/instructions/llmwiki.instructions.md", + "when": "llmwiki.isWikiWorkspace" } ], "commands": [ @@ -91,6 +99,16 @@ "title": "LLM Wiki: Fix Issues", "icon": "$(wand)" }, + { + "command": "llmwiki.lint", + "title": "LLM Wiki: Run Lint", + "icon": "$(checklist)" + }, + { + "command": "llmwiki.fixWithCopilot", + "title": "LLM Wiki: Fix Remaining Issues with Copilot", + "icon": "$(sparkle)" + }, { "command": "llmwiki.search", "title": "LLM Wiki: Search Wiki", @@ -144,6 +162,10 @@ { "id": "backlinks", "name": "Backlinks" + }, + { + "id": "lintFindings", + "name": "Lint Findings" } ] }, @@ -173,6 +195,21 @@ "command": "llmwiki.refresh", "when": "view =~ /^(entities|concepts|rawSources)$/ && llmwiki.isWikiWorkspace", "group": "navigation@4" + }, + { + "command": "llmwiki.lint", + "when": "view == lintFindings && llmwiki.isWikiWorkspace", + "group": "navigation@1" + }, + { + "command": "llmwiki.fix", + "when": "view == lintFindings && llmwiki.isWikiWorkspace", + "group": "navigation@2" + }, + { + "command": "llmwiki.fixWithCopilot", + "when": "view == lintFindings && llmwiki.hasLintFindings", + "group": "navigation@3" } ], "view/item/context": [ @@ -208,7 +245,7 @@ "llmwiki.modelFamily": { "type": "string", "default": "claude-opus-4.6", - "description": "Preferred GitHub Copilot model family for ingestion enrichment and the @wiki chat participant. Run \"LLM Wiki: Select Model\" from the Command Palette to pick from installed Copilot models. Falls back to any available Copilot model when the requested family is unavailable. Leave blank to always use the first available Copilot model." + "description": "Preferred GitHub Copilot model family for LLM-powered ingestion. Run \"LLM Wiki: Select Model\" from the Command Palette to pick from installed Copilot models. Falls back to any available Copilot model when the requested family is unavailable. Leave blank to always use the first available Copilot model." } } } @@ -230,7 +267,7 @@ "@types/glob": "^9.0.0", "@types/mocha": "^10.0.10", "@types/node": "^20.0.0", - "@types/vscode": "^1.93.0", + "@types/vscode": "~1.109.0", "@vscode/test-electron": "^2.5.2", "@vscode/vsce": "^3.7.1", "esbuild": "^0.28.1", diff --git a/packages/vscode/src/chatHistory.ts b/packages/vscode/src/chatHistory.ts deleted file mode 100644 index dde2391..0000000 --- a/packages/vscode/src/chatHistory.ts +++ /dev/null @@ -1,22 +0,0 @@ -export interface HistoryTurn { - role: 'user' | 'assistant'; - text: string; -} - -/** - * Map ordered chat turns into model messages. - * - * Walks the turns in the order they happened. Assistant turns whose text is - * an empty string are dropped; whitespace-only text is kept. User turns are - * always kept. - */ -export function historyToMessages(turns: readonly HistoryTurn[]): HistoryTurn[] { - const messages: HistoryTurn[] = []; - for (const turn of turns) { - if (turn.role === 'assistant' && turn.text.length === 0) { - continue; - } - messages.push({ role: turn.role, text: turn.text }); - } - return messages; -} diff --git a/packages/vscode/src/chatParticipant.ts b/packages/vscode/src/chatParticipant.ts deleted file mode 100644 index 05a8b41..0000000 --- a/packages/vscode/src/chatParticipant.ts +++ /dev/null @@ -1,547 +0,0 @@ -import * as vscode from 'vscode'; -import { join } from 'node:path'; -import { readFile } from 'node:fs/promises'; -import { historyToMessages, type HistoryTurn } from './chatHistory'; -import { selectPreferredModel } from './modelSelection'; -import { - queryWiki, - readIndex, - readPage, - writePage, - directoryExists, - lintWiki, - lintFix, - deletePage, - type IndexEntry, -} from '@llmwiki/core'; - -import { WIKI_DIR_NAME } from '@llmwiki/core'; - -/** - * Get the preferred LLM model — honours the `llmwiki.modelFamily` setting, - * falls back to any available Copilot model, and finally to the request's - * own model if Copilot exposes nothing else. - */ -async function getModel( - requestModel: vscode.LanguageModelChat, - outputChannel: vscode.OutputChannel, -): Promise { - const preferred = await selectPreferredModel(outputChannel); - if (preferred) { - return preferred; - } - outputChannel.appendLine(`[wiki chat] Using request model: ${requestModel.family}`); - return requestModel; -} - -/** - * Register the @wiki chat participant. - * - * The participant answers questions from the compiled wiki. - * Strategy-aligned: "the LLM reads the index first to find relevant pages, - * then drills into them" — exactly what this does. - */ -export function registerChatParticipant( - context: vscode.ExtensionContext, - workspaceFolder: string, - outputChannel: vscode.OutputChannel, -): void { - const wikiRoot = join(workspaceFolder, WIKI_DIR_NAME); - const wikiDir = join(wikiRoot, 'wiki'); - const indexPath = join(wikiDir, 'index.md'); - - const handler: vscode.ChatRequestHandler = async ( - request: vscode.ChatRequest, - chatContext: vscode.ChatContext, - stream: vscode.ChatResponseStream, - token: vscode.CancellationToken, - ) => { - // Check wiki exists - if (!(await directoryExists(wikiDir))) { - stream.markdown( - 'The wiki is not initialized yet. Run **LLM Wiki: Initialize Wiki** from the command palette first.', - ); - return; - } - - if (request.command === 'status') { - return handleStatus(wikiRoot, stream); - } - - if (request.command === 'lint') { - return handleLint(request, wikiRoot, wikiDir, stream, token, outputChannel); - } - - if (request.command === 'fix') { - return handleFix(request, wikiRoot, wikiDir, stream, token, outputChannel); - } - - if (request.command === 'save') { - return handleSave(request, wikiRoot, stream, outputChannel); - } - - // Default: answer a question from the wiki - return handleQuery( - request, - chatContext, - stream, - token, - wikiRoot, - wikiDir, - indexPath, - outputChannel, - ); - }; - - const participant = vscode.chat.createChatParticipant('llmwiki.wiki', handler); - participant.iconPath = new vscode.ThemeIcon('book'); - context.subscriptions.push(participant); -} - -// ── /query (default) ───────────────────────────────────────────── - -async function handleQuery( - request: vscode.ChatRequest, - chatContext: vscode.ChatContext, - stream: vscode.ChatResponseStream, - token: vscode.CancellationToken, - wikiRoot: string, - wikiDir: string, - indexPath: string, - outputChannel: vscode.OutputChannel, -): Promise { - const question = request.prompt.trim(); - if (!question) { - stream.markdown('Ask me anything about your wiki knowledge base.'); - return; - } - - stream.progress('Searching wiki…'); - - // Step 1: Read the index for full context - let entries: IndexEntry[] = []; - try { - entries = await readIndex(indexPath); - } catch { - // empty index - } - - // Step 2: Keyword search for relevant pages - const searchResult = await queryWiki(question, wikiRoot, false); - const topResults = searchResult.results.slice(0, 8); - - // Step 3: Read the content of top-matching pages - stream.progress('Reading relevant pages…'); - const pageContents: Array<{ title: string; path: string; content: string }> = []; - for (const result of topResults) { - try { - const page = await readPage(join(wikiDir, result.path)); - pageContents.push({ - title: result.title, - path: result.path, - content: page.body.slice(0, 3000), - }); - } catch { - // skip unreadable pages - } - } - - // Step 4: Build the wiki context for the LLM - const wikiIndex = entries - .map((e) => `- [${e.title}](${e.path}) (${e.category}): ${e.summary}`) - .join('\n'); - - const relevantPages = pageContents.length > 0 - ? pageContents - .map((p) => `### ${p.title} (${p.path})\n${p.content}`) - .join('\n\n---\n\n') - : 'No pages matched the query.'; - - // Step 5: Build conversation history in the order the turns happened. - const historyTurns: HistoryTurn[] = []; - for (const turn of chatContext.history) { - if (turn instanceof vscode.ChatRequestTurn) { - historyTurns.push({ role: 'user', text: turn.prompt }); - continue; - } - if (turn instanceof vscode.ChatResponseTurn) { - let text = ''; - for (const part of turn.response) { - if (part instanceof vscode.ChatResponseMarkdownPart) { - text += part.value.value; - } - } - historyTurns.push({ role: 'assistant', text }); - } - } - - const messages: vscode.LanguageModelChatMessage[] = []; - - messages.push( - vscode.LanguageModelChatMessage.User( - `You are a knowledgeable assistant that answers questions using a personal wiki knowledge base. You have access to the wiki's index and relevant page content below. - -Rules: -- Answer based on the wiki content. Cite specific pages by name when referencing information. -- If the wiki doesn't contain enough information to answer, say so honestly and suggest what sources could be added. -- Be concise but thorough. Use markdown formatting. -- If the answer reveals connections between pages, mention them — cross-referencing is a core value of this wiki. -- Good answers can become wiki pages themselves. If the user's question produces a valuable synthesis, suggest they save it with /save. - -## Wiki Index -${wikiIndex || 'No pages in the index yet.'} - -## Relevant Pages -${relevantPages}`, - ), - ); - - for (const message of historyToMessages(historyTurns)) { - messages.push( - message.role === 'assistant' - ? vscode.LanguageModelChatMessage.Assistant(message.text) - : vscode.LanguageModelChatMessage.User(message.text), - ); - } - - messages.push(vscode.LanguageModelChatMessage.User(question)); - - // Step 6: Stream the LLM response - stream.progress('Thinking…'); - - try { - const model = await getModel(request.model, outputChannel); - const chatResponse = await model.sendRequest(messages, {}, token); - for await (const fragment of chatResponse.text) { - stream.markdown(fragment); - } - } catch (err) { - if (err instanceof vscode.LanguageModelError) { - outputChannel.appendLine(`[wiki chat] LLM error: ${err.message} (${err.code})`); - stream.markdown(`Failed to get a response: ${err.message}`); - } else { - throw err; - } - } - - // Add references to cited pages - if (pageContents.length > 0) { - stream.markdown('\n\n---\n**Sources:**\n'); - for (const page of pageContents) { - const uri = vscode.Uri.file(join(wikiDir, page.path)); - stream.anchor(uri, page.title); - stream.markdown(' '); - } - } -} - -// ── /status ────────────────────────────────────────────────────── - -async function handleStatus( - wikiRoot: string, - stream: vscode.ChatResponseStream, -): Promise { - const { getWikiStatus } = await import('@llmwiki/core'); - const status = await getWikiStatus(wikiRoot); - - stream.markdown(`## Wiki Status\n\n`); - stream.markdown(`| Metric | Value |\n|--------|-------|\n`); - stream.markdown(`| Pages | ${status.wiki_page_count} |\n`); - stream.markdown(`| Sources | ${status.source_count} |\n`); - stream.markdown(`| Coverage | ${status.index_coverage_pct}% |\n`); - stream.markdown(`| Last ingest | ${status.last_ingest_date ?? '—'} |\n`); - stream.markdown(`| Orphans | ${status.orphan_page_count} |\n`); -} - -// ── /save ──────────────────────────────────────────────────────── - -async function handleSave( - request: vscode.ChatRequest, - wikiRoot: string, - stream: vscode.ChatResponseStream, - outputChannel: vscode.OutputChannel, -): Promise { - // Save the last assistant response as a wiki page - // (requires user to provide a name) - const name = request.prompt.trim(); - if (!name) { - stream.markdown('Usage: `@wiki /save `\n\nProvide a name and the previous answer will be saved as a wiki concept page.'); - return; - } - - stream.markdown(`To save this as a wiki page, use the **LLM Wiki: Ingest Source** command or create the page manually in the wiki.`); - stream.markdown(`\n\nSuggested path: \`concepts/${name.toLowerCase().replace(/[^a-z0-9]+/g, '-')}.md\``); -} - -// ── /lint ──────────────────────────────────────────────────────── - -async function handleLint( - request: vscode.ChatRequest, - wikiRoot: string, - wikiDir: string, - stream: vscode.ChatResponseStream, - token: vscode.CancellationToken, - outputChannel: vscode.OutputChannel, -): Promise { - stream.progress('Running wiki health checks…'); - - const result = await lintWiki(wikiRoot); - - if (result.findings.length === 0) { - stream.markdown('**Wiki health check passed** — no issues found.\n'); - return; - } - - // Group findings for the LLM to interpret - const findingsSummary = result.findings - .map((f) => `- **${f.severity}** (${f.category}): ${f.message}${f.file ? ` — \`${f.file}\`` : ''}`) - .join('\n'); - - const messages: vscode.LanguageModelChatMessage[] = [ - vscode.LanguageModelChatMessage.User( - `You are a wiki health advisor. Analyze the following lint findings from a personal knowledge base and provide: -1. A brief summary of the wiki's health -2. For each issue category, explain what it means and suggest specific fixes -3. Prioritize: which issues should be fixed first? -4. If any issues could be automatically fixed by re-ingesting sources, mention that - -Be concise and actionable. Use markdown formatting. - -## Lint Results -- Errors: ${result.errorCount} -- Warnings: ${result.warningCount} -- Info: ${result.findings.length - result.errorCount - result.warningCount} - -## Findings -${findingsSummary}`, - ), - ]; - - try { - const model = await getModel(request.model, outputChannel); - const chatResponse = await model.sendRequest(messages, {}, token); - for await (const fragment of chatResponse.text) { - stream.markdown(fragment); - } - } catch (err) { - if (err instanceof vscode.LanguageModelError) { - outputChannel.appendLine(`[wiki chat] LLM error: ${err.message} (${err.code})`); - } - // Fall back to raw findings if LLM fails - stream.markdown(`## Wiki Lint Results\n\n`); - stream.markdown(`**${result.errorCount}** errors, **${result.warningCount}** warnings\n\n`); - stream.markdown(findingsSummary); - } - - // Add file references for findings with associated files - const filesReferenced = new Set(); - for (const finding of result.findings) { - if (finding.file && !filesReferenced.has(finding.file)) { - filesReferenced.add(finding.file); - const uri = vscode.Uri.file(join(wikiDir, finding.file)); - stream.reference(uri); - } - } -} - -// ── /fix ───────────────────────────────────────────────────────── - -async function handleFix( - request: vscode.ChatRequest, - wikiRoot: string, - wikiDir: string, - stream: vscode.ChatResponseStream, - token: vscode.CancellationToken, - outputChannel: vscode.OutputChannel, -): Promise { - // Step 1: Clean orphaned entity/concept pages whose source is gone - stream.progress('Cleaning orphaned pages…'); - let cleanedPages = 0; - try { - const { readdir, stat: fsStat } = await import('node:fs/promises'); - const { extname } = await import('node:path'); - const allFiles = await readdir(wikiDir, { recursive: true }) as string[]; - const mdPages = allFiles - .filter((f) => typeof f === 'string' && extname(f) === '.md') - .map((f) => f.replace(/\\/g, '/')) - .filter((f) => f.startsWith('entities/') || f.startsWith('concepts/')); - - for (const relPath of mdPages) { - try { - const page = await readPage(join(wikiDir, relPath)); - const sources = page.frontmatter.sources as string[] | undefined; - if (sources && sources.length > 0) { - const allMissing = (await Promise.all( - sources.map(async (s) => { - try { await fsStat(join(wikiDir, s)); return false; } - catch { return true; } - }), - )).every(Boolean); - - if (allMissing) { - await deletePage(wikiDir, relPath); - cleanedPages++; - outputChannel.appendLine(`[fix] Cleaned orphaned page: ${relPath}`); - } - } - } catch { - // Skip - } - } - } catch { - // readdir may fail - } - - if (cleanedPages > 0) { - stream.markdown(`**Cleaned ${cleanedPages} orphaned page(s)** whose source files were removed.\n\n`); - } - - // Step 2: Run mechanical lint-fix - stream.progress('Running auto-fix…'); - const fixResult = await lintFix(wikiRoot, { fixOrphans: true }); - - if (fixResult.fixedCount > 0) { - stream.markdown(`**Auto-fixed ${fixResult.fixedCount} issue(s):**\n`); - for (const f of fixResult.fixed) { - stream.markdown(`- ✓ (${f.category}) ${f.message}\n`); - } - stream.markdown('\n'); - } - - // Step 3: If remaining issues, use LLM to analyze and fix - const remaining = fixResult.remaining; - if (remaining.length === 0 && cleanedPages === 0 && fixResult.fixedCount === 0) { - stream.markdown('**Wiki is healthy** — no issues found.\n'); - return; - } - - if (remaining.length === 0) { - stream.markdown('**All issues resolved.** ✓\n'); - return; - } - - // Step 4: Ask LLM to fix remaining issues - stream.progress('Analyzing remaining issues with LLM…'); - - const findingsSummary = remaining - .map((f) => `- **${f.severity}** (${f.category}): ${f.message}${f.file ? ` — \`${f.file}\`` : ''}`) - .join('\n'); - - // Read affected pages for context - const affectedFiles = new Set(); - for (const f of remaining) { - if (f.file) affectedFiles.add(f.file); - } - - let pagesContext = ''; - for (const relPath of affectedFiles) { - try { - const page = await readPage(join(wikiDir, relPath)); - pagesContext += `### ${relPath}\n\`\`\`yaml\n${JSON.stringify(page.frontmatter, null, 2)}\n\`\`\`\n${page.body.slice(0, 1000)}\n\n`; - } catch { - // skip - } - } - - const messages: vscode.LanguageModelChatMessage[] = [ - vscode.LanguageModelChatMessage.User( - `You are a wiki maintenance bot. The automated lint-fix has already handled what it could. The following issues remain and need your help. - -For each issue, provide a specific fix action. You can: -1. For **broken-links**: suggest removing the broken link or what the correct link target should be -2. For **orphan-pages**: suggest whether to delete the page or what pages should link to it -3. For other issues: explain the fix needed - -Respond in this JSON format: -{ - "fixes": [ - { - "file": "relative/path.md", - "action": "remove-link" | "update-link" | "delete-page" | "skip", - "details": "explanation", - "old_text": "text to find (for link fixes)", - "new_text": "replacement text (for link fixes)" - } - ], - "summary": "brief summary of fixes applied" -} - -Only output valid JSON. No markdown fences, no explanation outside the JSON. - -## Remaining Issues -${findingsSummary} - -## Affected Pages -${pagesContext}`, - ), - ]; - - try { - const model = await getModel(request.model, outputChannel); - const chatResponse = await model.sendRequest(messages, {}, token); - - let fullResponse = ''; - for await (const chunk of chatResponse.text) { - fullResponse += chunk; - } - - // Parse and apply fixes - let cleaned = fullResponse.trim(); - if (cleaned.startsWith('```')) { - cleaned = cleaned.replace(/^```(?:json)?\s*\n?/, '').replace(/\n?```\s*$/, ''); - } - - const parsed = JSON.parse(cleaned); - let appliedFixes = 0; - - if (Array.isArray(parsed.fixes)) { - for (const fix of parsed.fixes) { - if (!fix.file || fix.action === 'skip') continue; - - try { - if (fix.action === 'delete-page') { - await deletePage(wikiDir, fix.file); - appliedFixes++; - stream.markdown(`- ✓ Deleted \`${fix.file}\`: ${fix.details}\n`); - } else if ((fix.action === 'remove-link' || fix.action === 'update-link') && fix.old_text) { - const page = await readPage(join(wikiDir, fix.file)); - const newBody = page.body.replace(fix.old_text, fix.new_text ?? ''); - if (newBody !== page.body) { - page.body = newBody; - await writePage(join(wikiDir, fix.file), page); - appliedFixes++; - stream.markdown(`- ✓ Fixed link in \`${fix.file}\`: ${fix.details}\n`); - } - } - } catch (err) { - stream.markdown(`- ✗ Failed to fix \`${fix.file}\`: ${err}\n`); - outputChannel.appendLine(`[fix] Failed: ${fix.file} — ${err}`); - } - } - } - - stream.markdown(`\n**${appliedFixes} LLM fix(es) applied.**`); - if (parsed.summary) { - stream.markdown(` ${parsed.summary}`); - } - stream.markdown('\n'); - } catch (err) { - if (err instanceof vscode.LanguageModelError) { - outputChannel.appendLine(`[fix] LLM error: ${err.message} (${err.code})`); - } else { - outputChannel.appendLine(`[fix] Error: ${err}`); - } - // Fall back to showing remaining issues - stream.markdown(`\n**${remaining.length} issue(s) could not be auto-fixed:**\n${findingsSummary}\n`); - } - - // Add references to affected files - for (const relPath of affectedFiles) { - try { - const uri = vscode.Uri.file(join(wikiDir, relPath)); - stream.reference(uri); - } catch { - // skip - } - } -} diff --git a/packages/vscode/src/commands.ts b/packages/vscode/src/commands.ts index 31910f8..ebe54d5 100644 --- a/packages/vscode/src/commands.ts +++ b/packages/vscode/src/commands.ts @@ -1,24 +1,33 @@ import * as vscode from 'vscode'; -import { join, resolve, basename, extname } from 'node:path'; -import { writeFile, mkdir, copyFile, unlink, readdir } from 'node:fs/promises'; +import { join, resolve, basename } from 'node:path'; +import { writeFile, mkdir, copyFile, unlink } from 'node:fs/promises'; import { readIndex, directoryExists, appendEntry, initWiki, lintWiki, + fixWiki, queryWiki, getWikiStatus, isNotFoundError, - deletePage, - readPage, + removeSourcePages, slugify, type IndexEntry, + type LintFinding, } from '@llmwiki/core'; import { llmIngest } from './llmIngest'; import { selectModelInteractively } from './modelSelection'; import type { WikiPagesTreeDataProvider } from './wikiPagesTree'; import type { RawSourcesTreeDataProvider } from './rawSourcesTree'; +import type { LintFindingsTreeDataProvider } from './lintFindingsTree'; + +/** Slash command of the `wiki-fix` skill contributed by this extension. */ +export const WIKI_FIX_CHAT_QUERY = '/wiki-fix'; + +const FIX_WITH_COPILOT = 'Fix with Copilot'; +const FIX_ISSUES = 'Fix Issues'; +const SHOW_FINDINGS = 'Show Findings'; /** * If the selected file is outside the workspace, copy it into raw/ first. @@ -116,6 +125,7 @@ interface TreeProviders { entities: WikiPagesTreeDataProvider; concepts: WikiPagesTreeDataProvider; rawSources: RawSourcesTreeDataProvider; + lintFindings: Pick; } export function registerCommands( @@ -144,6 +154,32 @@ export function registerCommands( const logPath = join(wikiDir, 'log.md'); const rawDir = join(workspaceFolder, 'raw'); + const refreshTrees = () => { + providers.entities.refresh(); + providers.concepts.refresh(); + providers.rawSources.refresh(); + }; + + /** Show findings in the Lint Findings view and update its context key. */ + const showFindings = (findings: LintFinding[]) => { + providers.lintFindings.setFindings(findings); + void vscode.commands.executeCommand('setContext', 'llmwiki.hasLintFindings', findings.length > 0); + }; + + // Notification buttons are handled without awaiting so commands finish + // as soon as their work is done. + const offer = (message: string, actions: string[]) => { + void vscode.window.showWarningMessage(message, ...actions).then((choice) => { + if (choice === FIX_WITH_COPILOT) { + void vscode.commands.executeCommand('llmwiki.fixWithCopilot'); + } else if (choice === FIX_ISSUES) { + void vscode.commands.executeCommand('llmwiki.fix'); + } else if (choice === SHOW_FINDINGS) { + void vscode.commands.executeCommand('lintFindings.focus'); + } + }); + }; + // ── llmwiki.init ───────────────────────────────────────────── reg('llmwiki.init', async () => { // Check if already initialized @@ -298,53 +334,23 @@ export function registerCommands( await unlink(filePath); outputChannel.appendLine(`[removeSource] Deleted raw file: ${filePath}`); - // Delete the corresponding summary page + index entry - const slug = slugify(fileName); - const summaryRelPath = `sources/${slug}-summary.md`; - try { - await deletePage(wikiDir, summaryRelPath); - outputChannel.appendLine(`[removeSource] Deleted wiki page: ${summaryRelPath}`); - } catch { - // Summary page may not exist (never ingested) - } - - // Delete entity/concept pages that were created from this source - let removedPages = 0; - try { - const allFiles = await readdir(wikiDir, { recursive: true }) as unknown as string[]; - const mdPages = allFiles - .filter((f) => typeof f === 'string' && extname(f) === '.md') - .map((f) => f.replace(/\\/g, '/')) - .filter((f) => f !== 'index.md' && f !== 'log.md'); - - for (const relPath of mdPages) { - try { - const page = await readPage(join(wikiDir, relPath)); - const sources = page.frontmatter.sources as string[] | undefined; - if (sources && sources.includes(summaryRelPath)) { - await deletePage(wikiDir, relPath); - removedPages++; - outputChannel.appendLine(`[removeSource] Deleted tagged page: ${relPath}`); - } - } catch { - // Skip unreadable pages - } - } - } catch { - // readdir may fail if wiki dir is empty + // Delete its summary page and the pages derived only from it. + const summaryRelPath = `sources/${slugify(fileName)}-summary.md`; + const removed = await removeSourcePages(wikiDir, summaryRelPath); + for (const relPath of removed) { + outputChannel.appendLine(`[removeSource] Deleted wiki page: ${relPath}`); } // Log the removal await appendEntry(logPath, { verb: 'removed', subject: fileName, - details: `Source file and ${removedPages + 1} wiki pages removed.`, + details: `Source file and ${removed.length} wiki page(s) removed.`, }); providers.entities.refresh(); providers.concepts.refresh(); providers.rawSources.refresh(); - const pageCount = removedPages + 1; // summary + tagged pages - vscode.window.showInformationMessage(`Removed "${fileName}" and ${pageCount} wiki page(s).`); + vscode.window.showInformationMessage(`Removed "${fileName}" and ${removed.length} wiki page(s).`); } catch (err: unknown) { const msg = err instanceof Error ? err.message : String(err); outputChannel.appendLine(`[removeSource] Error: ${msg}`); @@ -530,61 +536,19 @@ export function registerCommands( // ── llmwiki.refresh ───────────────────────────────────────── reg('llmwiki.refresh', async () => { if (!(await directoryExists(wikiDir))) { - providers.entities.refresh(); providers.concepts.refresh(); - providers.rawSources.refresh(); + refreshTrees(); return; } - // Step 1: Delete entity/concept pages whose source no longer exists - let cleanedPages = 0; - try { - const allFiles = await readdir(wikiDir, { recursive: true }) as unknown as string[]; - const mdPages = allFiles - .filter((f) => typeof f === 'string' && extname(f) === '.md') - .map((f) => f.replace(/\\/g, '/')) - .filter((f) => f.startsWith('entities/') || f.startsWith('concepts/')); - - for (const relPath of mdPages) { - try { - const page = await readPage(join(wikiDir, relPath)); - const sources = page.frontmatter.sources as string[] | undefined; - if (sources && sources.length > 0) { - // Check if all referenced source pages still exist - const { stat: fsStat } = await import('node:fs/promises'); - const allMissing = (await Promise.all( - sources.map(async (s) => { - try { await fsStat(join(wikiDir, s)); return false; } - catch { return true; } - }), - )).every(Boolean); - - if (allMissing) { - await deletePage(wikiDir, relPath); - cleanedPages++; - outputChannel.appendLine(`[refresh] Cleaned orphaned page: ${relPath}`); - } - } - } catch { - // Skip - } - } - } catch { - // readdir may fail - } - - // Step 2: Run lint-fix to resolve stale entries, missing index, frontmatter - const { lintFix } = await import('@llmwiki/core'); - const fixResult = await lintFix(workspaceFolder, { fixOrphans: true }); - - // Step 3: Check remaining issues - const remaining = fixResult.remaining.filter((f) => f.severity === 'error' || f.severity === 'warning'); - - providers.entities.refresh(); providers.concepts.refresh(); - providers.rawSources.refresh(); + // Prune pages whose sources are gone, then apply the deterministic lint fixes. + const result = await fixWiki(workspaceFolder); + refreshTrees(); + showFindings(result.remaining); + const remaining = result.remaining.filter((f) => f.severity === 'error' || f.severity === 'warning'); const parts: string[] = []; - if (cleanedPages > 0) parts.push(`${cleanedPages} orphaned page(s) removed`); - if (fixResult.fixedCount > 0) parts.push(`${fixResult.fixedCount} issue(s) fixed`); + if (result.removed_pages.length > 0) parts.push(`${result.removed_pages.length} orphaned page(s) removed`); + if (result.fixedCount > 0) parts.push(`${result.fixedCount} issue(s) fixed`); if (remaining.length > 0) parts.push(`${remaining.length} issue(s) remaining`); if (parts.length === 0) { @@ -592,10 +556,70 @@ export function registerCommands( } else if (remaining.length === 0) { vscode.window.showInformationMessage(`Wiki refreshed — ${parts.join(', ')} ✓`); } else { - vscode.window.showWarningMessage(`Wiki refreshed — ${parts.join(', ')}. Use @wiki /lint for details.`); + offer(`Wiki refreshed — ${parts.join(', ')}.`, [SHOW_FINDINGS, FIX_WITH_COPILOT]); } }); + // ── llmwiki.lint ──────────────────────────────────────────── + reg('llmwiki.lint', async () => { + if (!(await directoryExists(wikiDir))) { + vscode.window.showWarningMessage('Wiki not initialized. Run "LLM Wiki: Initialize Wiki" first.'); + return; + } + + const result = await lintWiki(workspaceFolder); + showFindings(result.findings); + + if (result.findings.length === 0) { + vscode.window.showInformationMessage('LLM Wiki: health check passed — no issues found ✓'); + return; + } + void vscode.commands.executeCommand('lintFindings.focus'); + offer( + `LLM Wiki: ${result.errorCount} error(s), ${result.warningCount} warning(s), ${result.infoCount} info.`, + [FIX_ISSUES, FIX_WITH_COPILOT], + ); + }); + + // ── llmwiki.fix ───────────────────────────────────────────── + // Applies the deterministic fixes locally; findings that need judgment are + // listed in the Lint Findings view and can be handed to Copilot. + reg('llmwiki.fix', async () => { + if (!(await directoryExists(wikiDir))) { + vscode.window.showWarningMessage('Wiki not initialized. Run "LLM Wiki: Initialize Wiki" first.'); + return; + } + + const result = await vscode.window.withProgress( + { location: vscode.ProgressLocation.Notification, title: 'LLM Wiki: Fixing wiki issues…' }, + () => fixWiki(workspaceFolder), + ); + refreshTrees(); + showFindings(result.remaining); + outputChannel.appendLine( + `[fix] removed ${result.removed_pages.length} page(s), fixed ${result.fixedCount}, ${result.remainingCount} remaining`, + ); + + const parts: string[] = []; + if (result.removed_pages.length > 0) parts.push(`${result.removed_pages.length} orphaned page(s) removed`); + if (result.fixedCount > 0) parts.push(`${result.fixedCount} issue(s) fixed`); + + if (result.remainingCount === 0) { + vscode.window.showInformationMessage( + parts.length > 0 ? `LLM Wiki: ${parts.join(', ')} ✓` : 'LLM Wiki: wiki is healthy — no issues found ✓', + ); + return; + } + + void vscode.commands.executeCommand('lintFindings.focus'); + parts.push(`${result.remainingCount} issue(s) need your judgment`); + offer(`LLM Wiki: ${parts.join(', ')}.`, [FIX_WITH_COPILOT]); + }); + + // ── llmwiki.fixWithCopilot ────────────────────────────────── + reg('llmwiki.fixWithCopilot', async () => { + await vscode.commands.executeCommand('workbench.action.chat.open', { query: WIKI_FIX_CHAT_QUERY }); + }); // ── llmwiki.selectModel ───────────────────────────────────── reg('llmwiki.selectModel', async () => { await selectModelInteractively(outputChannel); diff --git a/packages/vscode/src/extension.ts b/packages/vscode/src/extension.ts index 8a328af..42e56ba 100644 --- a/packages/vscode/src/extension.ts +++ b/packages/vscode/src/extension.ts @@ -3,9 +3,9 @@ import { join, basename } from 'node:path'; import { WikiPagesTreeDataProvider } from './wikiPagesTree'; import { RawSourcesTreeDataProvider } from './rawSourcesTree'; import { BacklinksTreeDataProvider } from './backlinksTree'; +import { LintFindingsTreeDataProvider } from './lintFindingsTree'; import { registerCommands } from './commands'; import { createStatusBar } from './statusBar'; -import { registerChatParticipant } from './chatParticipant'; import { llmIngest } from './llmIngest'; import { registerMcpServerProvider } from './mcpProvider'; @@ -87,6 +87,10 @@ function registerFullViews( const backlinksProvider = new BacklinksTreeDataProvider(wikiProjectRoot); const backlinksRegistration = vscode.window.registerTreeDataProvider('backlinks', backlinksProvider); + const lintFindingsProvider = new LintFindingsTreeDataProvider(wikiProjectRoot); + const lintFindingsRegistration = vscode.window.registerTreeDataProvider('lintFindings', lintFindingsProvider); + vscode.commands.executeCommand('setContext', 'llmwiki.hasLintFindings', false); + const watcher = vscode.workspace.createFileSystemWatcher( new vscode.RelativePattern(workspaceFolder, `${WIKI_DIR_NAME}/wiki/**/*.md`), ); @@ -127,21 +131,18 @@ function registerFullViews( autoCleanup(uri, wikiProjectRoot, outputChannel, wikiProviders); }); - const wikiProviders = { entities: entitiesProvider, concepts: conceptsProvider, rawSources: rawSourcesProvider }; + const wikiProviders = { + entities: entitiesProvider, + concepts: conceptsProvider, + rawSources: rawSourcesProvider, + lintFindings: lintFindingsProvider, + }; registerCommands(context, workspaceFolder, wikiProjectRoot, wikiProviders, outputChannel); - registerChatParticipant(context, workspaceFolder, outputChannel); registerMcpServerProvider(context, workspaceFolder, outputChannel); - // Fix button opens @wiki /fix in chat - context.subscriptions.push( - vscode.commands.registerCommand('llmwiki.fix', () => { - vscode.commands.executeCommand('workbench.action.chat.open', { query: '@wiki /fix' }); - }), - ); - const statusBar = createStatusBar(context, wikiProjectRoot); - context.subscriptions.push(entitiesRegistration, conceptsRegistration, watcher, entitiesProvider, conceptsProvider, rawSourcesRegistration, rawWatcher, rawSourcesProvider, backlinksRegistration, backlinksProvider, statusBar); + context.subscriptions.push(entitiesRegistration, conceptsRegistration, watcher, entitiesProvider, conceptsProvider, rawSourcesRegistration, rawWatcher, rawSourcesProvider, backlinksRegistration, backlinksProvider, lintFindingsRegistration, lintFindingsProvider, statusBar); // Manual scan command — also resilient backup if the watcher misses an event. context.subscriptions.push( @@ -329,9 +330,7 @@ async function autoCleanup( outputChannel: vscode.OutputChannel, providers: { entities: WikiPagesTreeDataProvider; concepts: WikiPagesTreeDataProvider; rawSources: RawSourcesTreeDataProvider }, ): Promise { - const { slugify, deletePage, readPage, appendEntry } = await import('@llmwiki/core'); - const { readdir } = await import('node:fs/promises'); - const { extname } = await import('node:path'); + const { slugify, removeSourcePages, appendEntry } = await import('@llmwiki/core'); const wikiDir = join(wikiProjectRoot, 'wiki'); const logPath = join(wikiDir, 'log.md'); const fileName = basename(uri.fsPath); @@ -340,41 +339,18 @@ async function autoCleanup( outputChannel.appendLine(`[autoCleanup] Source removed: ${fileName}, looking for ${summaryRelPath}`); - let removedCount = 0; - - // Delete summary page + // Delete the summary and the pages derived only from this source; pages + // that still have another existing source are kept. + let removed: string[] = []; try { - await deletePage(wikiDir, summaryRelPath); - removedCount++; - outputChannel.appendLine(`[autoCleanup] Deleted summary: ${summaryRelPath}`); - } catch { - // May not exist - } - - // Delete entity/concept pages tagged with this source - try { - const allFiles = await readdir(wikiDir, { recursive: true }) as string[]; - const mdPages = allFiles - .filter((f) => typeof f === 'string' && extname(f) === '.md') - .map((f) => f.replace(/\\/g, '/')) - .filter((f) => f !== 'index.md' && f !== 'log.md'); - - for (const relPath of mdPages) { - try { - const page = await readPage(join(wikiDir, relPath)); - const sources = page.frontmatter.sources as string[] | undefined; - if (sources && sources.includes(summaryRelPath)) { - await deletePage(wikiDir, relPath); - removedCount++; - outputChannel.appendLine(`[autoCleanup] Deleted tagged page: ${relPath}`); - } - } catch { - // Skip unreadable pages - } + removed = await removeSourcePages(wikiDir, summaryRelPath); + for (const relPath of removed) { + outputChannel.appendLine(`[autoCleanup] Deleted: ${relPath}`); } } catch (err) { - outputChannel.appendLine(`[autoCleanup] Error scanning pages: ${err}`); + outputChannel.appendLine(`[autoCleanup] Error removing pages: ${err}`); } + const removedCount = removed.length; if (removedCount > 0) { try { diff --git a/packages/vscode/src/llmIngest.ts b/packages/vscode/src/llmIngest.ts index f3e2ad6..84b0f4a 100644 --- a/packages/vscode/src/llmIngest.ts +++ b/packages/vscode/src/llmIngest.ts @@ -7,10 +7,10 @@ import { readIndex, readPage, writePage, - createEntityPage, - createConceptPage, + upsertDerivedPage, addCrosslinks, appendEntry, + withWikiLock, type IndexEntry, } from '@llmwiki/core'; @@ -57,6 +57,18 @@ export async function llmIngest( pagesCreated.push(...ingestResult.pages_created); pagesUpdated.push(...ingestResult.pages_updated); + // Remember the stub summary so a summary edited while the model runs (for + // example by a Copilot agent using the wiki tools) is not overwritten. + const summaryRelPath = ingestResult.pages_created[0]; + let stubSummary: string | undefined; + if (summaryRelPath) { + try { + stubSummary = (await readPage(join(wikiDir, summaryRelPath))).body; + } catch { + // Summary missing; step 4 skips it. + } + } + // ── Step 2: Read source content + existing wiki context ────── progress.report({ message: 'Extracting text from source…' }); const sourceContent = await extractText(sourcePath); @@ -82,53 +94,43 @@ export async function llmIngest( } // ── Step 4: Rewrite the summary page with LLM summary ─────── - if (analysis.summary && ingestResult.pages_created.length > 0) { + if (analysis.summary && summaryRelPath) { progress.report({ message: 'Writing LLM summary…' }); - const summaryPath = join(wikiDir, ingestResult.pages_created[0]); - const { readPage, writePage } = await import('@llmwiki/core'); + const summaryPath = join(wikiDir, summaryRelPath); try { - const page = await readPage(summaryPath); - page.body = analysis.summary; - await writePage(summaryPath, page); - pagesUpdated.push(ingestResult.pages_created[0]); - outputChannel.appendLine(`[llmIngest] Rewrote summary: ${ingestResult.pages_created[0]}`); + await withWikiLock(wikiDir, async () => { + const page = await readPage(summaryPath); + if (stubSummary !== undefined && page.body !== stubSummary) { + outputChannel.appendLine(`[llmIngest] Kept summary edited during ingest: ${summaryRelPath}`); + } else { + page.body = analysis.summary; + await writePage(summaryPath, page); + pagesUpdated.push(summaryRelPath); + outputChannel.appendLine(`[llmIngest] Rewrote summary: ${summaryRelPath}`); + } + }); } catch (err) { outputChannel.appendLine(`[llmIngest] Failed to rewrite summary: ${err}`); } } - // ── Step 5: Create entity pages ────────────────────────────── - const sourceRelPath = ingestResult.pages_created[0] ?? ''; - for (const entity of analysis.entities) { - progress.report({ message: `Creating entity: ${entity.name}…` }); - try { - const result = await createEntityPage(wikiDir, entity.name, entity.content, entity.tags); - // Tag with source for cleanup on removal - const pagePath = join(wikiDir, result.path); - const page = await readPage(pagePath); - page.frontmatter.sources = [sourceRelPath]; - await writePage(pagePath, page); - pagesCreated.push(result.path); - outputChannel.appendLine(`[llmIngest] Created entity: ${result.path}`); - } catch (err) { - outputChannel.appendLine(`[llmIngest] Failed to create entity "${entity.name}": ${err}`); - } - } - - // ── Step 6: Create concept pages ───────────────────────────── - for (const concept of analysis.concepts) { - progress.report({ message: `Creating concept: ${concept.name}…` }); + // ── Steps 5–6: Create or extend entity and concept pages ───── + // Pages that already exist (from another source, or written while the + // model ran) are extended rather than overwritten, keeping their sources. + // upsertDerivedPage holds the wiki lock while it merges, so concurrent + // ingests and MCP tools can't overwrite each other's changes. + const derived = [ + ...analysis.entities.map((item) => ({ kind: 'entity' as const, item })), + ...analysis.concepts.map((item) => ({ kind: 'concept' as const, item })), + ]; + for (const { kind, item } of derived) { + progress.report({ message: `Adding ${kind}: ${item.name}…` }); try { - const result = await createConceptPage(wikiDir, concept.name, concept.content, concept.tags); - // Tag with source for cleanup on removal - const pagePath = join(wikiDir, result.path); - const page = await readPage(pagePath); - page.frontmatter.sources = [sourceRelPath]; - await writePage(pagePath, page); - pagesCreated.push(result.path); - outputChannel.appendLine(`[llmIngest] Created concept: ${result.path}`); + const result = await upsertDerivedPage(wikiDir, kind, item.name, item.content, item.tags, summaryRelPath); + (result.created ? pagesCreated : pagesUpdated).push(result.path); + outputChannel.appendLine(`[llmIngest] ${result.created ? 'Created' : 'Extended'} ${kind}: ${result.path}`); } catch (err) { - outputChannel.appendLine(`[llmIngest] Failed to create concept "${concept.name}": ${err}`); + outputChannel.appendLine(`[llmIngest] Failed to add ${kind} "${item.name}": ${err}`); } } @@ -147,8 +149,8 @@ export async function llmIngest( // ── Step 8: Log the enrichment ─────────────────────────────── await appendEntry(logPath, { verb: 'enriched', - subject: ingestResult.pages_created[0] ?? sourcePath, - details: `LLM created ${analysis.entities.length} entities, ${analysis.concepts.length} concepts, ${analysis.crosslinks.length} crosslinks.`, + subject: summaryRelPath ?? sourcePath, + details: `LLM added ${analysis.entities.length} entities, ${analysis.concepts.length} concepts, ${analysis.crosslinks.length} crosslinks.`, }); return { pagesCreated, pagesUpdated }; diff --git a/packages/vscode/src/mcpProvider.ts b/packages/vscode/src/mcpProvider.ts index 85d3e19..843be0e 100644 --- a/packages/vscode/src/mcpProvider.ts +++ b/packages/vscode/src/mcpProvider.ts @@ -3,6 +3,32 @@ import { join } from 'node:path'; import { existsSync } from 'node:fs'; import { WIKI_DIR_NAME } from '@llmwiki/core'; +/** + * Build the stdio definition VS Code uses to start the `llmwiki` MCP server. + * + * The command is the editor's own executable (`process.execPath`), so the + * server doesn't depend on a system Node install. That binary only behaves + * like Node when `ELECTRON_RUN_AS_NODE` is set, and the process that spawns + * MCP servers (for example the Agent Host behind the Copilot harness) may not + * inherit it from the extension host, so it is set explicitly. + */ +export function createLlmWikiServerDefinition( + launcherPath: string, + wikiRoot: string, + workspaceFolder: string, + version: string, +): vscode.McpStdioServerDefinition { + const definition = new vscode.McpStdioServerDefinition( + 'LLM Wiki', + process.execPath, + [launcherPath, wikiRoot], + { ELECTRON_RUN_AS_NODE: '1' }, + version, + ); + definition.cwd = vscode.Uri.file(workspaceFolder); + return definition; +} + /** * Registers an `McpServerDefinitionProvider` that exposes the `llmwiki` MCP * server to Copilot Chat (and any other MCP-aware consumer in VS Code). @@ -58,18 +84,14 @@ export function registerMcpServerProvider( const provider: vscode.McpServerDefinitionProvider = { onDidChangeMcpServerDefinitions: emitter.event, - provideMcpServerDefinitions: () => { - const definition = new vscode.McpStdioServerDefinition( - 'LLM Wiki', - // Use the editor's bundled Node so we don't depend on a system install. - process.execPath, - [launcherPath, wikiRoot], - {}, + provideMcpServerDefinitions: () => [ + createLlmWikiServerDefinition( + launcherPath, + wikiRoot, + workspaceFolder, context.extension.packageJSON.version as string, - ); - definition.cwd = vscode.Uri.file(workspaceFolder); - return [definition]; - }, + ), + ], }; outputChannel.appendLine( diff --git a/plugin/README.md b/plugin/README.md new file mode 100644 index 0000000..0e8695f --- /dev/null +++ b/plugin/README.md @@ -0,0 +1,37 @@ +# LLM Wiki agent plugin + +An [Agent Plugins](https://agent-plugins.org) package for [LLM Wiki](https://github.com/microsoft/llmwiki), a personal knowledge base that your agent maintains as interlinked markdown in `.wiki/`. + +It works in GitHub Copilot CLI, the GitHub Copilot app, VS Code, and other Agent Plugins clients. In VS Code, prefer the [LLM Wiki extension](../packages/vscode), which contributes the same skills and agent and adds tree views and commands. + +## Contents + +| Component | Path | Purpose | +|-----------|------|---------| +| Skills | `skills/` | `wiki-ask`, `wiki-research`, `wiki-ingest` (also loaded automatically), and `wiki-save`, `wiki-fix` (run on request) | +| MCP server | `mcp.json`, `server/llmwiki-mcp.cjs` | The LLM Wiki tools, resources and prompts. Needs Node.js 20+ on `PATH`. | +| Agent | `com.github.copilot/agents/wiki-librarian.agent.md` | The Wiki Librarian custom agent | +| Rule | `com.github.copilot/rules/llmwiki.instructions.md` | Conventions for files under `.wiki/` | + +## Install + +```bash +copilot plugin install microsoft/llmwiki:plugin +``` + +Or add this repository as a marketplace and install from it: + +```bash +copilot plugin marketplace add microsoft/llmwiki +copilot plugin install llmwiki@llmwiki +``` + +Skills from a plugin are prefixed with its name, for example `/llmwiki:wiki-ask What do my notes say about attention?`. + +## Using it + +The MCP server starts in the plugin folder, so it has to find your wiki first. It checks the client's workspace roots; when the client doesn't report any, the skills tell the agent to call `wiki_open` with your project folder. To create a wiki, ask the agent to run `wiki_init` for the project folder, or use **LLM Wiki: Initialize Wiki** in VS Code. + +## Development + +The skills, agent and rule are the single source for both this plugin and the VS Code extension, which copies them at build time. `server/llmwiki-mcp.cjs` is generated: run `npm run build` at the repository root and commit the result. CI fails when it is out of date. diff --git a/plugin/com.github.copilot/agents/wiki-librarian.agent.md b/plugin/com.github.copilot/agents/wiki-librarian.agent.md new file mode 100644 index 0000000..2a31018 --- /dev/null +++ b/plugin/com.github.copilot/agents/wiki-librarian.agent.md @@ -0,0 +1,14 @@ +--- +name: Wiki Librarian +description: Answers questions from your LLM Wiki and keeps it healthy — searches and cites wiki pages, ingests new sources, saves syntheses and fixes issues. +--- + +You are the librarian of the user's LLM Wiki: a personal knowledge base in `.wiki/` that you maintain with the LLM Wiki MCP tools (`wiki_*`). + +- Answer from the wiki, not from general knowledge. Search with `wiki_query`, read pages with `wiki_read_page`, and cite each page you use as a link to its file (`.wiki/wiki/`). Say clearly when the wiki doesn't cover something, and suggest sources to add. +- Follow the wiki's schema and conventions in `.wiki/AGENTS.md`. +- Treat `.wiki/raw/` as read-only: those are the user's sources. +- Change pages through the wiki tools rather than editing files directly, so the index and log stay consistent. +- Ask before deleting pages or re-ingesting a source with `force`. +- Use the wiki skills when they fit: `wiki-ask`, `wiki-research`, `wiki-ingest`, `wiki-save` and `wiki-fix`. +- If a tool reports that no wiki is open, call `wiki_open` with the absolute path of the current workspace folder. diff --git a/plugin/com.github.copilot/rules/llmwiki.instructions.md b/plugin/com.github.copilot/rules/llmwiki.instructions.md new file mode 100644 index 0000000..0e1be91 --- /dev/null +++ b/plugin/com.github.copilot/rules/llmwiki.instructions.md @@ -0,0 +1,11 @@ +--- +name: LLM Wiki conventions +description: Conventions for reading and editing an LLM Wiki in .wiki/ +applyTo: ".wiki/**" +--- + +- `.wiki/` is an LLM Wiki. Its schema and conventions are in `.wiki/AGENTS.md`; follow them. +- Never modify files in `.wiki/raw/`. They are the user's sources. +- Prefer the LLM Wiki MCP tools (`wiki_write_page`, `wiki_update_page`, `wiki_create_entity`, `wiki_create_concept`, `wiki_add_crosslinks`, `wiki_delete_page`) over editing files in `.wiki/wiki/` directly, so `wiki/index.md` and `wiki/log.md` stay consistent. +- If you do edit a page directly, keep its frontmatter (`type`, `title`, `tags`) valid and run `wiki_lint` afterwards. +- Link pages with relative markdown links that end in `.md`. diff --git a/plugin/mcp.json b/plugin/mcp.json new file mode 100644 index 0000000..517e5d4 --- /dev/null +++ b/plugin/mcp.json @@ -0,0 +1,10 @@ +{ + "$schema": "https://agent-plugins.org/schemas/1.0.0/mcp.schema.json", + "mcpServers": { + "llmwiki": { + "type": "stdio", + "command": "node", + "args": ["${PLUGIN_ROOT}/server/llmwiki-mcp.cjs"] + } + } +} diff --git a/plugin/plugin.json b/plugin/plugin.json new file mode 100644 index 0000000..71d93c8 --- /dev/null +++ b/plugin/plugin.json @@ -0,0 +1,14 @@ +{ + "$schema": "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json", + "name": "llmwiki", + "version": "1.0.1", + "description": "LLM Wiki: a personal knowledge base that your agent maintains. Skills to ask, research, ingest, save and fix, a Wiki Librarian agent, and the LLM Wiki MCP server.", + "author": { + "name": "Microsoft", + "url": "https://github.com/microsoft/llmwiki" + }, + "homepage": "https://github.com/microsoft/llmwiki#readme", + "repository": "https://github.com/microsoft/llmwiki", + "license": "MIT", + "keywords": ["wiki", "knowledge-base", "mcp", "markdown", "skills"] +} diff --git a/plugin/server/llmwiki-mcp.cjs b/plugin/server/llmwiki-mcp.cjs new file mode 100644 index 0000000..08605fe --- /dev/null +++ b/plugin/server/llmwiki-mcp.cjs @@ -0,0 +1,302 @@ +#!/usr/bin/env node +"use strict";var nb=Object.create;var Oa=Object.defineProperty;var ob=Object.getOwnPropertyDescriptor;var ib=Object.getOwnPropertyNames;var sb=Object.getPrototypeOf,ab=Object.prototype.hasOwnProperty;var x=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}},jf=(e,t)=>{for(var r in t)Oa(e,r,{get:t[r],enumerable:!0})},cb=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of ib(t))!ab.call(e,o)&&o!==r&&Oa(e,o,{get:()=>t[o],enumerable:!(n=ob(t,o))||n.enumerable});return e};var ui=(e,t,r)=>(r=e!=null?nb(sb(e)):{},cb(t||!e||!e.__esModule?Oa(r,"default",{value:e,enumerable:!0}):r,e));var vo=x(K=>{"use strict";Object.defineProperty(K,"__esModule",{value:!0});K.regexpCode=K.getEsmExportName=K.getProperty=K.safeStringify=K.stringify=K.strConcat=K.addCodeArg=K.str=K._=K.nil=K._Code=K.Name=K.IDENTIFIER=K._CodeOrName=void 0;var wo=class{};K._CodeOrName=wo;K.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var wr=class extends wo{constructor(t){if(super(),!K.IDENTIFIER.test(t))throw new Error("CodeGen: name must be a valid identifier");this.str=t}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};K.Name=wr;var it=class extends wo{constructor(t){super(),this._items=typeof t=="string"?[t]:t}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let t=this._items[0];return t===""||t==='""'}get str(){var t;return(t=this._str)!==null&&t!==void 0?t:this._str=this._items.reduce((r,n)=>`${r}${n}`,"")}get names(){var t;return(t=this._names)!==null&&t!==void 0?t:this._names=this._items.reduce((r,n)=>(n instanceof wr&&(r[n.str]=(r[n.str]||0)+1),r),{})}};K._Code=it;K.nil=new it("");function zg(e,...t){let r=[e[0]],n=0;for(;n{"use strict";Object.defineProperty(Ve,"__esModule",{value:!0});Ve.ValueScope=Ve.ValueScopeName=Ve.Scope=Ve.varKinds=Ve.UsedValueState=void 0;var Ue=vo(),uu=class extends Error{constructor(t){super(`CodeGen: "code" for ${t} not defined`),this.value=t.value}},hs;(function(e){e[e.Started=0]="Started",e[e.Completed=1]="Completed"})(hs||(Ve.UsedValueState=hs={}));Ve.varKinds={const:new Ue.Name("const"),let:new Ue.Name("let"),var:new Ue.Name("var")};var gs=class{constructor({prefixes:t,parent:r}={}){this._names={},this._prefixes=t,this._parent=r}toName(t){return t instanceof Ue.Name?t:this.name(t)}name(t){return new Ue.Name(this._newName(t))}_newName(t){let r=this._names[t]||this._nameGroup(t);return`${t}${r.index++}`}_nameGroup(t){var r,n;if(!((n=(r=this._parent)===null||r===void 0?void 0:r._prefixes)===null||n===void 0)&&n.has(t)||this._prefixes&&!this._prefixes.has(t))throw new Error(`CodeGen: prefix "${t}" is not allowed in this scope`);return this._names[t]={prefix:t,index:0}}};Ve.Scope=gs;var ys=class extends Ue.Name{constructor(t,r){super(r),this.prefix=t}setValue(t,{property:r,itemIndex:n}){this.value=t,this.scopePath=(0,Ue._)`.${new Ue.Name(r)}[${n}]`}};Ve.ValueScopeName=ys;var wz=(0,Ue._)`\n`,lu=class extends gs{constructor(t){super(t),this._values={},this._scope=t.scope,this.opts={...t,_n:t.lines?wz:Ue.nil}}get(){return this._scope}name(t){return new ys(t,this._newName(t))}value(t,r){var n;if(r.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let o=this.toName(t),{prefix:i}=o,s=(n=r.key)!==null&&n!==void 0?n:r.ref,a=this._values[i];if(a){let l=a.get(s);if(l)return l}else a=this._values[i]=new Map;a.set(s,o);let c=this._scope[i]||(this._scope[i]=[]),u=c.length;return c[u]=r.ref,o.setValue(r,{property:i,itemIndex:u}),o}getValue(t,r){let n=this._values[t];if(n)return n.get(r)}scopeRefs(t,r=this._values){return this._reduceValues(r,n=>{if(n.scopePath===void 0)throw new Error(`CodeGen: name "${n}" has no value`);return(0,Ue._)`${t}${n.scopePath}`})}scopeCode(t=this._values,r,n){return this._reduceValues(t,o=>{if(o.value===void 0)throw new Error(`CodeGen: name "${o}" has no value`);return o.value.code},r,n)}_reduceValues(t,r,n={},o){let i=Ue.nil;for(let s in t){let a=t[s];if(!a)continue;let c=n[s]=n[s]||new Map;a.forEach(u=>{if(c.has(u))return;c.set(u,hs.Started);let l=r(u);if(l){let f=this.opts.es5?Ve.varKinds.var:Ve.varKinds.const;i=(0,Ue._)`${i}${f} ${u} = ${l};${this.opts._n}`}else if(l=o?.(u))i=(0,Ue._)`${i}${l}${this.opts._n}`;else throw new uu(u);c.set(u,hs.Completed)})}return i}};Ve.ValueScope=lu});var j=x(M=>{"use strict";Object.defineProperty(M,"__esModule",{value:!0});M.or=M.and=M.not=M.CodeGen=M.operators=M.varKinds=M.ValueScopeName=M.ValueScope=M.Scope=M.Name=M.regexpCode=M.stringify=M.getProperty=M.nil=M.strConcat=M.str=M._=void 0;var U=vo(),gt=fu(),er=vo();Object.defineProperty(M,"_",{enumerable:!0,get:function(){return er._}});Object.defineProperty(M,"str",{enumerable:!0,get:function(){return er.str}});Object.defineProperty(M,"strConcat",{enumerable:!0,get:function(){return er.strConcat}});Object.defineProperty(M,"nil",{enumerable:!0,get:function(){return er.nil}});Object.defineProperty(M,"getProperty",{enumerable:!0,get:function(){return er.getProperty}});Object.defineProperty(M,"stringify",{enumerable:!0,get:function(){return er.stringify}});Object.defineProperty(M,"regexpCode",{enumerable:!0,get:function(){return er.regexpCode}});Object.defineProperty(M,"Name",{enumerable:!0,get:function(){return er.Name}});var vs=fu();Object.defineProperty(M,"Scope",{enumerable:!0,get:function(){return vs.Scope}});Object.defineProperty(M,"ValueScope",{enumerable:!0,get:function(){return vs.ValueScope}});Object.defineProperty(M,"ValueScopeName",{enumerable:!0,get:function(){return vs.ValueScopeName}});Object.defineProperty(M,"varKinds",{enumerable:!0,get:function(){return vs.varKinds}});M.operators={GT:new U._Code(">"),GTE:new U._Code(">="),LT:new U._Code("<"),LTE:new U._Code("<="),EQ:new U._Code("==="),NEQ:new U._Code("!=="),NOT:new U._Code("!"),OR:new U._Code("||"),AND:new U._Code("&&"),ADD:new U._Code("+")};var Mt=class{optimizeNodes(){return this}optimizeNames(t,r){return this}},du=class extends Mt{constructor(t,r,n){super(),this.varKind=t,this.name=r,this.rhs=n}render({es5:t,_n:r}){let n=t?gt.varKinds.var:this.varKind,o=this.rhs===void 0?"":` = ${this.rhs}`;return`${n} ${this.name}${o};`+r}optimizeNames(t,r){if(t[this.name.str])return this.rhs&&(this.rhs=sn(this.rhs,t,r)),this}get names(){return this.rhs instanceof U._CodeOrName?this.rhs.names:{}}},_s=class extends Mt{constructor(t,r,n){super(),this.lhs=t,this.rhs=r,this.sideEffects=n}render({_n:t}){return`${this.lhs} = ${this.rhs};`+t}optimizeNames(t,r){if(!(this.lhs instanceof U.Name&&!t[this.lhs.str]&&!this.sideEffects))return this.rhs=sn(this.rhs,t,r),this}get names(){let t=this.lhs instanceof U.Name?{}:{...this.lhs.names};return xs(t,this.rhs)}},pu=class extends _s{constructor(t,r,n,o){super(t,n,o),this.op=r}render({_n:t}){return`${this.lhs} ${this.op}= ${this.rhs};`+t}},mu=class extends Mt{constructor(t){super(),this.label=t,this.names={}}render({_n:t}){return`${this.label}:`+t}},hu=class extends Mt{constructor(t){super(),this.label=t,this.names={}}render({_n:t}){return`break${this.label?` ${this.label}`:""};`+t}},gu=class extends Mt{constructor(t){super(),this.error=t}render({_n:t}){return`throw ${this.error};`+t}get names(){return this.error.names}},yu=class extends Mt{constructor(t){super(),this.code=t}render({_n:t}){return`${this.code};`+t}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(t,r){return this.code=sn(this.code,t,r),this}get names(){return this.code instanceof U._CodeOrName?this.code.names:{}}},bo=class extends Mt{constructor(t=[]){super(),this.nodes=t}render(t){return this.nodes.reduce((r,n)=>r+n.render(t),"")}optimizeNodes(){let{nodes:t}=this,r=t.length;for(;r--;){let n=t[r].optimizeNodes();Array.isArray(n)?t.splice(r,1,...n):n?t[r]=n:t.splice(r,1)}return t.length>0?this:void 0}optimizeNames(t,r){let{nodes:n}=this,o=n.length;for(;o--;){let i=n[o];i.optimizeNames(t,r)||(xz(t,i.names),n.splice(o,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((t,r)=>br(t,r.names),{})}},qt=class extends bo{render(t){return"{"+t._n+super.render(t)+"}"+t._n}},_u=class extends bo{},on=class extends qt{};on.kind="else";var xr=class e extends qt{constructor(t,r){super(r),this.condition=t}render(t){let r=`if(${this.condition})`+super.render(t);return this.else&&(r+="else "+this.else.render(t)),r}optimizeNodes(){super.optimizeNodes();let t=this.condition;if(t===!0)return this.nodes;let r=this.else;if(r){let n=r.optimizeNodes();r=this.else=Array.isArray(n)?new on(n):n}if(r)return t===!1?r instanceof e?r:r.nodes:this.nodes.length?this:new e(Eg(t),r instanceof e?[r]:r.nodes);if(!(t===!1||!this.nodes.length))return this}optimizeNames(t,r){var n;if(this.else=(n=this.else)===null||n===void 0?void 0:n.optimizeNames(t,r),!!(super.optimizeNames(t,r)||this.else))return this.condition=sn(this.condition,t,r),this}get names(){let t=super.names;return xs(t,this.condition),this.else&&br(t,this.else.names),t}};xr.kind="if";var vr=class extends qt{};vr.kind="for";var wu=class extends vr{constructor(t){super(),this.iteration=t}render(t){return`for(${this.iteration})`+super.render(t)}optimizeNames(t,r){if(super.optimizeNames(t,r))return this.iteration=sn(this.iteration,t,r),this}get names(){return br(super.names,this.iteration.names)}},xu=class extends vr{constructor(t,r,n,o){super(),this.varKind=t,this.name=r,this.from=n,this.to=o}render(t){let r=t.es5?gt.varKinds.var:this.varKind,{name:n,from:o,to:i}=this;return`for(${r} ${n}=${o}; ${n}<${i}; ${n}++)`+super.render(t)}get names(){let t=xs(super.names,this.from);return xs(t,this.to)}},ws=class extends vr{constructor(t,r,n,o){super(),this.loop=t,this.varKind=r,this.name=n,this.iterable=o}render(t){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(t)}optimizeNames(t,r){if(super.optimizeNames(t,r))return this.iterable=sn(this.iterable,t,r),this}get names(){return br(super.names,this.iterable.names)}},So=class extends qt{constructor(t,r,n){super(),this.name=t,this.args=r,this.async=n}render(t){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(t)}};So.kind="func";var $o=class extends bo{render(t){return"return "+super.render(t)}};$o.kind="return";var vu=class extends qt{render(t){let r="try"+super.render(t);return this.catch&&(r+=this.catch.render(t)),this.finally&&(r+=this.finally.render(t)),r}optimizeNodes(){var t,r;return super.optimizeNodes(),(t=this.catch)===null||t===void 0||t.optimizeNodes(),(r=this.finally)===null||r===void 0||r.optimizeNodes(),this}optimizeNames(t,r){var n,o;return super.optimizeNames(t,r),(n=this.catch)===null||n===void 0||n.optimizeNames(t,r),(o=this.finally)===null||o===void 0||o.optimizeNames(t,r),this}get names(){let t=super.names;return this.catch&&br(t,this.catch.names),this.finally&&br(t,this.finally.names),t}},ko=class extends qt{constructor(t){super(),this.error=t}render(t){return`catch(${this.error})`+super.render(t)}};ko.kind="catch";var zo=class extends qt{render(t){return"finally"+super.render(t)}};zo.kind="finally";var bu=class{constructor(t,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?` +`:""},this._extScope=t,this._scope=new gt.Scope({parent:t}),this._nodes=[new _u]}toString(){return this._root.render(this.opts)}name(t){return this._scope.name(t)}scopeName(t){return this._extScope.name(t)}scopeValue(t,r){let n=this._extScope.value(t,r);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(t,r){return this._extScope.getValue(t,r)}scopeRefs(t){return this._extScope.scopeRefs(t,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(t,r,n,o){let i=this._scope.toName(r);return n!==void 0&&o&&(this._constants[i.str]=n),this._leafNode(new du(t,i,n)),i}const(t,r,n){return this._def(gt.varKinds.const,t,r,n)}let(t,r,n){return this._def(gt.varKinds.let,t,r,n)}var(t,r,n){return this._def(gt.varKinds.var,t,r,n)}assign(t,r,n){return this._leafNode(new _s(t,r,n))}add(t,r){return this._leafNode(new pu(t,M.operators.ADD,r))}code(t){return typeof t=="function"?t():t!==U.nil&&this._leafNode(new yu(t)),this}object(...t){let r=["{"];for(let[n,o]of t)r.length>1&&r.push(","),r.push(n),(n!==o||this.opts.es5)&&(r.push(":"),(0,U.addCodeArg)(r,o));return r.push("}"),new U._Code(r)}if(t,r,n){if(this._blockNode(new xr(t)),r&&n)this.code(r).else().code(n).endIf();else if(r)this.code(r).endIf();else if(n)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(t){return this._elseNode(new xr(t))}else(){return this._elseNode(new on)}endIf(){return this._endBlockNode(xr,on)}_for(t,r){return this._blockNode(t),r&&this.code(r).endFor(),this}for(t,r){return this._for(new wu(t),r)}forRange(t,r,n,o,i=this.opts.es5?gt.varKinds.var:gt.varKinds.let){let s=this._scope.toName(t);return this._for(new xu(i,s,r,n),()=>o(s))}forOf(t,r,n,o=gt.varKinds.const){let i=this._scope.toName(t);if(this.opts.es5){let s=r instanceof U.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,U._)`${s}.length`,a=>{this.var(i,(0,U._)`${s}[${a}]`),n(i)})}return this._for(new ws("of",o,i,r),()=>n(i))}forIn(t,r,n,o=this.opts.es5?gt.varKinds.var:gt.varKinds.const){if(this.opts.ownProperties)return this.forOf(t,(0,U._)`Object.keys(${r})`,n);let i=this._scope.toName(t);return this._for(new ws("in",o,i,r),()=>n(i))}endFor(){return this._endBlockNode(vr)}label(t){return this._leafNode(new mu(t))}break(t){return this._leafNode(new hu(t))}return(t){let r=new $o;if(this._blockNode(r),this.code(t),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode($o)}try(t,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new vu;if(this._blockNode(o),this.code(t),r){let i=this.name("e");this._currNode=o.catch=new ko(i),r(i)}return n&&(this._currNode=o.finally=new zo,this.code(n)),this._endBlockNode(ko,zo)}throw(t){return this._leafNode(new gu(t))}block(t,r){return this._blockStarts.push(this._nodes.length),t&&this.code(t).endBlock(r),this}endBlock(t){let r=this._blockStarts.pop();if(r===void 0)throw new Error("CodeGen: not in self-balancing block");let n=this._nodes.length-r;if(n<0||t!==void 0&&n!==t)throw new Error(`CodeGen: wrong number of nodes: ${n} vs ${t} expected`);return this._nodes.length=r,this}func(t,r=U.nil,n,o){return this._blockNode(new So(t,r,n)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(So)}optimize(t=1){for(;t-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(t){return this._currNode.nodes.push(t),this}_blockNode(t){this._currNode.nodes.push(t),this._nodes.push(t)}_endBlockNode(t,r){let n=this._currNode;if(n instanceof t||r&&n instanceof r)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${r?`${t.kind}/${r.kind}`:t.kind}"`)}_elseNode(t){let r=this._currNode;if(!(r instanceof xr))throw new Error('CodeGen: "else" without "if"');return this._currNode=r.else=t,this}get _root(){return this._nodes[0]}get _currNode(){let t=this._nodes;return t[t.length-1]}set _currNode(t){let r=this._nodes;r[r.length-1]=t}};M.CodeGen=bu;function br(e,t){for(let r in t)e[r]=(e[r]||0)+(t[r]||0);return e}function xs(e,t){return t instanceof U._CodeOrName?br(e,t.names):e}function sn(e,t,r){if(e instanceof U.Name)return n(e);if(!o(e))return e;return new U._Code(e._items.reduce((i,s)=>(s instanceof U.Name&&(s=n(s)),s instanceof U._Code?i.push(...s._items):i.push(s),i),[]));function n(i){let s=r[i.str];return s===void 0||t[i.str]!==1?i:(delete t[i.str],s)}function o(i){return i instanceof U._Code&&i._items.some(s=>s instanceof U.Name&&t[s.str]===1&&r[s.str]!==void 0)}}function xz(e,t){for(let r in t)e[r]=(e[r]||0)-(t[r]||0)}function Eg(e){return typeof e=="boolean"||typeof e=="number"||e===null?!e:(0,U._)`!${Su(e)}`}M.not=Eg;var vz=Tg(M.operators.AND);function bz(...e){return e.reduce(vz)}M.and=bz;var Sz=Tg(M.operators.OR);function $z(...e){return e.reduce(Sz)}M.or=$z;function Tg(e){return(t,r)=>t===U.nil?r:r===U.nil?t:(0,U._)`${Su(t)} ${e} ${Su(r)}`}function Su(e){return e instanceof U.Name?e:(0,U._)`(${e})`}});var V=x(Z=>{"use strict";Object.defineProperty(Z,"__esModule",{value:!0});Z.checkStrictMode=Z.getErrorPath=Z.Type=Z.useFunc=Z.setEvaluated=Z.evaluatedPropsToName=Z.mergeEvaluated=Z.eachItem=Z.unescapeJsonPointer=Z.escapeJsonPointer=Z.escapeFragment=Z.unescapeFragment=Z.schemaRefOrVal=Z.schemaHasRulesButRef=Z.schemaHasRules=Z.checkUnknownRules=Z.alwaysValidSchema=Z.toHash=void 0;var Y=j(),kz=vo();function zz(e){let t={};for(let r of e)t[r]=!0;return t}Z.toHash=zz;function Pz(e,t){return typeof t=="boolean"?t:Object.keys(t).length===0?!0:(Ig(e,t),!Rg(t,e.self.RULES.all))}Z.alwaysValidSchema=Pz;function Ig(e,t=e.schema){let{opts:r,self:n}=e;if(!r.strictSchema||typeof t=="boolean")return;let o=n.RULES.keywords;for(let i in t)o[i]||jg(e,`unknown keyword: "${i}"`)}Z.checkUnknownRules=Ig;function Rg(e,t){if(typeof e=="boolean")return!e;for(let r in e)if(t[r])return!0;return!1}Z.schemaHasRules=Rg;function Ez(e,t){if(typeof e=="boolean")return!e;for(let r in e)if(r!=="$ref"&&t.all[r])return!0;return!1}Z.schemaHasRulesButRef=Ez;function Tz({topSchemaRef:e,schemaPath:t},r,n,o){if(!o){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,Y._)`${r}`}return(0,Y._)`${e}${t}${(0,Y.getProperty)(n)}`}Z.schemaRefOrVal=Tz;function Oz(e){return Cg(decodeURIComponent(e))}Z.unescapeFragment=Oz;function Az(e){return encodeURIComponent(ku(e))}Z.escapeFragment=Az;function ku(e){return typeof e=="number"?`${e}`:e.replace(/~/g,"~0").replace(/\//g,"~1")}Z.escapeJsonPointer=ku;function Cg(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}Z.unescapeJsonPointer=Cg;function Iz(e,t){if(Array.isArray(e))for(let r of e)t(r);else t(e)}Z.eachItem=Iz;function Og({mergeNames:e,mergeToName:t,mergeValues:r,resultToName:n}){return(o,i,s,a)=>{let c=s===void 0?i:s instanceof Y.Name?(i instanceof Y.Name?e(o,i,s):t(o,i,s),s):i instanceof Y.Name?(t(o,s,i),i):r(i,s);return a===Y.Name&&!(c instanceof Y.Name)?n(o,c):c}}Z.mergeEvaluated={props:Og({mergeNames:(e,t,r)=>e.if((0,Y._)`${r} !== true && ${t} !== undefined`,()=>{e.if((0,Y._)`${t} === true`,()=>e.assign(r,!0),()=>e.assign(r,(0,Y._)`${r} || {}`).code((0,Y._)`Object.assign(${r}, ${t})`))}),mergeToName:(e,t,r)=>e.if((0,Y._)`${r} !== true`,()=>{t===!0?e.assign(r,!0):(e.assign(r,(0,Y._)`${r} || {}`),zu(e,r,t))}),mergeValues:(e,t)=>e===!0?!0:{...e,...t},resultToName:Ng}),items:Og({mergeNames:(e,t,r)=>e.if((0,Y._)`${r} !== true && ${t} !== undefined`,()=>e.assign(r,(0,Y._)`${t} === true ? true : ${r} > ${t} ? ${r} : ${t}`)),mergeToName:(e,t,r)=>e.if((0,Y._)`${r} !== true`,()=>e.assign(r,t===!0?!0:(0,Y._)`${r} > ${t} ? ${r} : ${t}`)),mergeValues:(e,t)=>e===!0?!0:Math.max(e,t),resultToName:(e,t)=>e.var("items",t)})};function Ng(e,t){if(t===!0)return e.var("props",!0);let r=e.var("props",(0,Y._)`{}`);return t!==void 0&&zu(e,r,t),r}Z.evaluatedPropsToName=Ng;function zu(e,t,r){Object.keys(r).forEach(n=>e.assign((0,Y._)`${t}${(0,Y.getProperty)(n)}`,!0))}Z.setEvaluated=zu;var Ag={};function Rz(e,t){return e.scopeValue("func",{ref:t,code:Ag[t.code]||(Ag[t.code]=new kz._Code(t.code))})}Z.useFunc=Rz;var $u;(function(e){e[e.Num=0]="Num",e[e.Str=1]="Str"})($u||(Z.Type=$u={}));function Cz(e,t,r){if(e instanceof Y.Name){let n=t===$u.Num;return r?n?(0,Y._)`"[" + ${e} + "]"`:(0,Y._)`"['" + ${e} + "']"`:n?(0,Y._)`"/" + ${e}`:(0,Y._)`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,Y.getProperty)(e).toString():"/"+ku(e)}Z.getErrorPath=Cz;function jg(e,t,r=e.opts.strictSchema){if(r){if(t=`strict mode: ${t}`,r===!0)throw new Error(t);e.self.logger.warn(t)}}Z.checkStrictMode=jg});var Ft=x(Pu=>{"use strict";Object.defineProperty(Pu,"__esModule",{value:!0});var Ae=j(),Nz={data:new Ae.Name("data"),valCxt:new Ae.Name("valCxt"),instancePath:new Ae.Name("instancePath"),parentData:new Ae.Name("parentData"),parentDataProperty:new Ae.Name("parentDataProperty"),rootData:new Ae.Name("rootData"),dynamicAnchors:new Ae.Name("dynamicAnchors"),vErrors:new Ae.Name("vErrors"),errors:new Ae.Name("errors"),this:new Ae.Name("this"),self:new Ae.Name("self"),scope:new Ae.Name("scope"),json:new Ae.Name("json"),jsonPos:new Ae.Name("jsonPos"),jsonLen:new Ae.Name("jsonLen"),jsonPart:new Ae.Name("jsonPart")};Pu.default=Nz});var Po=x(Ie=>{"use strict";Object.defineProperty(Ie,"__esModule",{value:!0});Ie.extendErrors=Ie.resetErrorsCount=Ie.reportExtraError=Ie.reportError=Ie.keyword$DataError=Ie.keywordError=void 0;var H=j(),bs=V(),Me=Ft();Ie.keywordError={message:({keyword:e})=>(0,H.str)`must pass "${e}" keyword validation`};Ie.keyword$DataError={message:({keyword:e,schemaType:t})=>t?(0,H.str)`"${e}" keyword must be ${t} ($data)`:(0,H.str)`"${e}" keyword is invalid ($data)`};function jz(e,t=Ie.keywordError,r,n){let{it:o}=e,{gen:i,compositeRule:s,allErrors:a}=o,c=qg(e,t,r);n??(s||a)?Dg(i,c):Mg(o,(0,H._)`[${c}]`)}Ie.reportError=jz;function Dz(e,t=Ie.keywordError,r){let{it:n}=e,{gen:o,compositeRule:i,allErrors:s}=n,a=qg(e,t,r);Dg(o,a),i||s||Mg(n,Me.default.vErrors)}Ie.reportExtraError=Dz;function Mz(e,t){e.assign(Me.default.errors,t),e.if((0,H._)`${Me.default.vErrors} !== null`,()=>e.if(t,()=>e.assign((0,H._)`${Me.default.vErrors}.length`,t),()=>e.assign(Me.default.vErrors,null)))}Ie.resetErrorsCount=Mz;function qz({gen:e,keyword:t,schemaValue:r,data:n,errsCount:o,it:i}){if(o===void 0)throw new Error("ajv implementation error");let s=e.name("err");e.forRange("i",o,Me.default.errors,a=>{e.const(s,(0,H._)`${Me.default.vErrors}[${a}]`),e.if((0,H._)`${s}.instancePath === undefined`,()=>e.assign((0,H._)`${s}.instancePath`,(0,H.strConcat)(Me.default.instancePath,i.errorPath))),e.assign((0,H._)`${s}.schemaPath`,(0,H.str)`${i.errSchemaPath}/${t}`),i.opts.verbose&&(e.assign((0,H._)`${s}.schema`,r),e.assign((0,H._)`${s}.data`,n))})}Ie.extendErrors=qz;function Dg(e,t){let r=e.const("err",t);e.if((0,H._)`${Me.default.vErrors} === null`,()=>e.assign(Me.default.vErrors,(0,H._)`[${r}]`),(0,H._)`${Me.default.vErrors}.push(${r})`),e.code((0,H._)`${Me.default.errors}++`)}function Mg(e,t){let{gen:r,validateName:n,schemaEnv:o}=e;o.$async?r.throw((0,H._)`new ${e.ValidationError}(${t})`):(r.assign((0,H._)`${n}.errors`,t),r.return(!1))}var Sr={keyword:new H.Name("keyword"),schemaPath:new H.Name("schemaPath"),params:new H.Name("params"),propertyName:new H.Name("propertyName"),message:new H.Name("message"),schema:new H.Name("schema"),parentSchema:new H.Name("parentSchema")};function qg(e,t,r){let{createErrors:n}=e.it;return n===!1?(0,H._)`{}`:Fz(e,t,r)}function Fz(e,t,r={}){let{gen:n,it:o}=e,i=[Zz(o,r),Lz(e,r)];return Uz(e,t,i),n.object(...i)}function Zz({errorPath:e},{instancePath:t}){let r=t?(0,H.str)`${e}${(0,bs.getErrorPath)(t,bs.Type.Str)}`:e;return[Me.default.instancePath,(0,H.strConcat)(Me.default.instancePath,r)]}function Lz({keyword:e,it:{errSchemaPath:t}},{schemaPath:r,parentSchema:n}){let o=n?t:(0,H.str)`${t}/${e}`;return r&&(o=(0,H.str)`${o}${(0,bs.getErrorPath)(r,bs.Type.Str)}`),[Sr.schemaPath,o]}function Uz(e,{params:t,message:r},n){let{keyword:o,data:i,schemaValue:s,it:a}=e,{opts:c,propertyName:u,topSchemaRef:l,schemaPath:f}=a;n.push([Sr.keyword,o],[Sr.params,typeof t=="function"?t(e):t||(0,H._)`{}`]),c.messages&&n.push([Sr.message,typeof r=="function"?r(e):r]),c.verbose&&n.push([Sr.schema,s],[Sr.parentSchema,(0,H._)`${l}${f}`],[Me.default.data,i]),u&&n.push([Sr.propertyName,u])}});var Zg=x(an=>{"use strict";Object.defineProperty(an,"__esModule",{value:!0});an.boolOrEmptySchema=an.topBoolOrEmptySchema=void 0;var Vz=Po(),Hz=j(),Bz=Ft(),Kz={message:"boolean schema is false"};function Jz(e){let{gen:t,schema:r,validateName:n}=e;r===!1?Fg(e,!1):typeof r=="object"&&r.$async===!0?t.return(Bz.default.data):(t.assign((0,Hz._)`${n}.errors`,null),t.return(!0))}an.topBoolOrEmptySchema=Jz;function Wz(e,t){let{gen:r,schema:n}=e;n===!1?(r.var(t,!1),Fg(e)):r.var(t,!0)}an.boolOrEmptySchema=Wz;function Fg(e,t){let{gen:r,data:n}=e,o={gen:r,keyword:"false schema",data:n,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:e};(0,Vz.reportError)(o,Kz,void 0,t)}});var Eu=x(cn=>{"use strict";Object.defineProperty(cn,"__esModule",{value:!0});cn.getRules=cn.isJSONType=void 0;var Gz=["string","number","integer","boolean","null","object","array"],Yz=new Set(Gz);function Xz(e){return typeof e=="string"&&Yz.has(e)}cn.isJSONType=Xz;function Qz(){let e={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...e,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},e.number,e.string,e.array,e.object],post:{rules:[]},all:{},keywords:{}}}cn.getRules=Qz});var Tu=x(tr=>{"use strict";Object.defineProperty(tr,"__esModule",{value:!0});tr.shouldUseRule=tr.shouldUseGroup=tr.schemaHasRulesForType=void 0;function eP({schema:e,self:t},r){let n=t.RULES.types[r];return n&&n!==!0&&Lg(e,n)}tr.schemaHasRulesForType=eP;function Lg(e,t){return t.rules.some(r=>Ug(e,r))}tr.shouldUseGroup=Lg;function Ug(e,t){var r;return e[t.keyword]!==void 0||((r=t.definition.implements)===null||r===void 0?void 0:r.some(n=>e[n]!==void 0))}tr.shouldUseRule=Ug});var Eo=x(Re=>{"use strict";Object.defineProperty(Re,"__esModule",{value:!0});Re.reportTypeError=Re.checkDataTypes=Re.checkDataType=Re.coerceAndCheckDataType=Re.getJSONTypes=Re.getSchemaTypes=Re.DataType=void 0;var tP=Eu(),rP=Tu(),nP=Po(),N=j(),Vg=V(),un;(function(e){e[e.Correct=0]="Correct",e[e.Wrong=1]="Wrong"})(un||(Re.DataType=un={}));function oP(e){let t=Hg(e.type);if(t.includes("null")){if(e.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!t.length&&e.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');e.nullable===!0&&t.push("null")}return t}Re.getSchemaTypes=oP;function Hg(e){let t=Array.isArray(e)?e:e?[e]:[];if(t.every(tP.isJSONType))return t;throw new Error("type must be JSONType or JSONType[]: "+t.join(","))}Re.getJSONTypes=Hg;function iP(e,t){let{gen:r,data:n,opts:o}=e,i=sP(t,o.coerceTypes),s=t.length>0&&!(i.length===0&&t.length===1&&(0,rP.schemaHasRulesForType)(e,t[0]));if(s){let a=Au(t,n,o.strictNumbers,un.Wrong);r.if(a,()=>{i.length?aP(e,t,i):Iu(e)})}return s}Re.coerceAndCheckDataType=iP;var Bg=new Set(["string","number","integer","boolean","null"]);function sP(e,t){return t?e.filter(r=>Bg.has(r)||t==="array"&&r==="array"):[]}function aP(e,t,r){let{gen:n,data:o,opts:i}=e,s=n.let("dataType",(0,N._)`typeof ${o}`),a=n.let("coerced",(0,N._)`undefined`);i.coerceTypes==="array"&&n.if((0,N._)`${s} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>n.assign(o,(0,N._)`${o}[0]`).assign(s,(0,N._)`typeof ${o}`).if(Au(t,o,i.strictNumbers),()=>n.assign(a,o))),n.if((0,N._)`${a} !== undefined`);for(let u of r)(Bg.has(u)||u==="array"&&i.coerceTypes==="array")&&c(u);n.else(),Iu(e),n.endIf(),n.if((0,N._)`${a} !== undefined`,()=>{n.assign(o,a),cP(e,a)});function c(u){switch(u){case"string":n.elseIf((0,N._)`${s} == "number" || ${s} == "boolean"`).assign(a,(0,N._)`"" + ${o}`).elseIf((0,N._)`${o} === null`).assign(a,(0,N._)`""`);return;case"number":n.elseIf((0,N._)`${s} == "boolean" || ${o} === null + || (${s} == "string" && ${o} && ${o} == +${o})`).assign(a,(0,N._)`+${o}`);return;case"integer":n.elseIf((0,N._)`${s} === "boolean" || ${o} === null + || (${s} === "string" && ${o} && ${o} == +${o} && !(${o} % 1))`).assign(a,(0,N._)`+${o}`);return;case"boolean":n.elseIf((0,N._)`${o} === "false" || ${o} === 0 || ${o} === null`).assign(a,!1).elseIf((0,N._)`${o} === "true" || ${o} === 1`).assign(a,!0);return;case"null":n.elseIf((0,N._)`${o} === "" || ${o} === 0 || ${o} === false`),n.assign(a,null);return;case"array":n.elseIf((0,N._)`${s} === "string" || ${s} === "number" + || ${s} === "boolean" || ${o} === null`).assign(a,(0,N._)`[${o}]`)}}}function cP({gen:e,parentData:t,parentDataProperty:r},n){e.if((0,N._)`${t} !== undefined`,()=>e.assign((0,N._)`${t}[${r}]`,n))}function Ou(e,t,r,n=un.Correct){let o=n===un.Correct?N.operators.EQ:N.operators.NEQ,i;switch(e){case"null":return(0,N._)`${t} ${o} null`;case"array":i=(0,N._)`Array.isArray(${t})`;break;case"object":i=(0,N._)`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case"integer":i=s((0,N._)`!(${t} % 1) && !isNaN(${t})`);break;case"number":i=s();break;default:return(0,N._)`typeof ${t} ${o} ${e}`}return n===un.Correct?i:(0,N.not)(i);function s(a=N.nil){return(0,N.and)((0,N._)`typeof ${t} == "number"`,a,r?(0,N._)`isFinite(${t})`:N.nil)}}Re.checkDataType=Ou;function Au(e,t,r,n){if(e.length===1)return Ou(e[0],t,r,n);let o,i=(0,Vg.toHash)(e);if(i.array&&i.object){let s=(0,N._)`typeof ${t} != "object"`;o=i.null?s:(0,N._)`!${t} || ${s}`,delete i.null,delete i.array,delete i.object}else o=N.nil;i.number&&delete i.integer;for(let s in i)o=(0,N.and)(o,Ou(s,t,r,n));return o}Re.checkDataTypes=Au;var uP={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>typeof e=="string"?(0,N._)`{type: ${e}}`:(0,N._)`{type: ${t}}`};function Iu(e){let t=lP(e);(0,nP.reportError)(t,uP)}Re.reportTypeError=Iu;function lP(e){let{gen:t,data:r,schema:n}=e,o=(0,Vg.schemaRefOrVal)(e,n,"type");return{gen:t,keyword:"type",data:r,schema:n.type,schemaCode:o,schemaValue:o,parentSchema:n,params:{},it:e}}});var Jg=x(Ss=>{"use strict";Object.defineProperty(Ss,"__esModule",{value:!0});Ss.assignDefaults=void 0;var ln=j(),fP=V();function dP(e,t){let{properties:r,items:n}=e.schema;if(t==="object"&&r)for(let o in r)Kg(e,o,r[o].default);else t==="array"&&Array.isArray(n)&&n.forEach((o,i)=>Kg(e,i,o.default))}Ss.assignDefaults=dP;function Kg(e,t,r){let{gen:n,compositeRule:o,data:i,opts:s}=e;if(r===void 0)return;let a=(0,ln._)`${i}${(0,ln.getProperty)(t)}`;if(o){(0,fP.checkStrictMode)(e,`default is ignored for: ${a}`);return}let c=(0,ln._)`${a} === undefined`;s.useDefaults==="empty"&&(c=(0,ln._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,ln._)`${a} = ${(0,ln.stringify)(r)}`)}});var st=x(G=>{"use strict";Object.defineProperty(G,"__esModule",{value:!0});G.validateUnion=G.validateArray=G.usePattern=G.callValidateCode=G.schemaProperties=G.allSchemaProperties=G.noPropertyInData=G.propertyInData=G.isOwnProperty=G.hasPropFunc=G.reportMissingProp=G.checkMissingProp=G.checkReportMissingProp=void 0;var ne=j(),Ru=V(),rr=Ft(),pP=V();function mP(e,t){let{gen:r,data:n,it:o}=e;r.if(Nu(r,n,t,o.opts.ownProperties),()=>{e.setParams({missingProperty:(0,ne._)`${t}`},!0),e.error()})}G.checkReportMissingProp=mP;function hP({gen:e,data:t,it:{opts:r}},n,o){return(0,ne.or)(...n.map(i=>(0,ne.and)(Nu(e,t,i,r.ownProperties),(0,ne._)`${o} = ${i}`)))}G.checkMissingProp=hP;function gP(e,t){e.setParams({missingProperty:t},!0),e.error()}G.reportMissingProp=gP;function Wg(e){return e.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,ne._)`Object.prototype.hasOwnProperty`})}G.hasPropFunc=Wg;function Cu(e,t,r){return(0,ne._)`${Wg(e)}.call(${t}, ${r})`}G.isOwnProperty=Cu;function yP(e,t,r,n){let o=(0,ne._)`${t}${(0,ne.getProperty)(r)} !== undefined`;return n?(0,ne._)`${o} && ${Cu(e,t,r)}`:o}G.propertyInData=yP;function Nu(e,t,r,n){let o=(0,ne._)`${t}${(0,ne.getProperty)(r)} === undefined`;return n?(0,ne.or)(o,(0,ne.not)(Cu(e,t,r))):o}G.noPropertyInData=Nu;function Gg(e){return e?Object.keys(e).filter(t=>t!=="__proto__"):[]}G.allSchemaProperties=Gg;function _P(e,t){return Gg(t).filter(r=>!(0,Ru.alwaysValidSchema)(e,t[r]))}G.schemaProperties=_P;function wP({schemaCode:e,data:t,it:{gen:r,topSchemaRef:n,schemaPath:o,errorPath:i},it:s},a,c,u){let l=u?(0,ne._)`${e}, ${t}, ${n}${o}`:t,f=[[rr.default.instancePath,(0,ne.strConcat)(rr.default.instancePath,i)],[rr.default.parentData,s.parentData],[rr.default.parentDataProperty,s.parentDataProperty],[rr.default.rootData,rr.default.rootData]];s.opts.dynamicRef&&f.push([rr.default.dynamicAnchors,rr.default.dynamicAnchors]);let d=(0,ne._)`${l}, ${r.object(...f)}`;return c!==ne.nil?(0,ne._)`${a}.call(${c}, ${d})`:(0,ne._)`${a}(${d})`}G.callValidateCode=wP;var xP=(0,ne._)`new RegExp`;function vP({gen:e,it:{opts:t}},r){let n=t.unicodeRegExp?"u":"",{regExp:o}=t.code,i=o(r,n);return e.scopeValue("pattern",{key:i.toString(),ref:i,code:(0,ne._)`${o.code==="new RegExp"?xP:(0,pP.useFunc)(e,o)}(${r}, ${n})`})}G.usePattern=vP;function bP(e){let{gen:t,data:r,keyword:n,it:o}=e,i=t.name("valid");if(o.allErrors){let a=t.let("valid",!0);return s(()=>t.assign(a,!1)),a}return t.var(i,!0),s(()=>t.break()),i;function s(a){let c=t.const("len",(0,ne._)`${r}.length`);t.forRange("i",0,c,u=>{e.subschema({keyword:n,dataProp:u,dataPropType:Ru.Type.Num},i),t.if((0,ne.not)(i),a)})}}G.validateArray=bP;function SP(e){let{gen:t,schema:r,keyword:n,it:o}=e;if(!Array.isArray(r))throw new Error("ajv implementation error");if(r.some(c=>(0,Ru.alwaysValidSchema)(o,c))&&!o.opts.unevaluated)return;let s=t.let("valid",!1),a=t.name("_valid");t.block(()=>r.forEach((c,u)=>{let l=e.subschema({keyword:n,schemaProp:u,compositeRule:!0},a);t.assign(s,(0,ne._)`${s} || ${a}`),e.mergeValidEvaluated(l,a)||t.if((0,ne.not)(s))})),e.result(s,()=>e.reset(),()=>e.error(!0))}G.validateUnion=SP});var Qg=x(vt=>{"use strict";Object.defineProperty(vt,"__esModule",{value:!0});vt.validateKeywordUsage=vt.validSchemaType=vt.funcKeywordCode=vt.macroKeywordCode=void 0;var qe=j(),$r=Ft(),$P=st(),kP=Po();function zP(e,t){let{gen:r,keyword:n,schema:o,parentSchema:i,it:s}=e,a=t.macro.call(s.self,o,i,s),c=Xg(r,n,a);s.opts.validateSchema!==!1&&s.self.validateSchema(a,!0);let u=r.name("valid");e.subschema({schema:a,schemaPath:qe.nil,errSchemaPath:`${s.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},u),e.pass(u,()=>e.error(!0))}vt.macroKeywordCode=zP;function PP(e,t){var r;let{gen:n,keyword:o,schema:i,parentSchema:s,$data:a,it:c}=e;TP(c,t);let u=!a&&t.compile?t.compile.call(c.self,i,s,c):t.validate,l=Xg(n,o,u),f=n.let("valid");e.block$data(f,d),e.ok((r=t.valid)!==null&&r!==void 0?r:f);function d(){if(t.errors===!1)h(),t.modifying&&Yg(e),g(()=>e.error());else{let y=t.async?p():m();t.modifying&&Yg(e),g(()=>EP(e,y))}}function p(){let y=n.let("ruleErrs",null);return n.try(()=>h((0,qe._)`await `),v=>n.assign(f,!1).if((0,qe._)`${v} instanceof ${c.ValidationError}`,()=>n.assign(y,(0,qe._)`${v}.errors`),()=>n.throw(v))),y}function m(){let y=(0,qe._)`${l}.errors`;return n.assign(y,null),h(qe.nil),y}function h(y=t.async?(0,qe._)`await `:qe.nil){let v=c.opts.passContext?$r.default.this:$r.default.self,S=!("compile"in t&&!a||t.schema===!1);n.assign(f,(0,qe._)`${y}${(0,$P.callValidateCode)(e,l,v,S)}`,t.modifying)}function g(y){var v;n.if((0,qe.not)((v=t.valid)!==null&&v!==void 0?v:f),y)}}vt.funcKeywordCode=PP;function Yg(e){let{gen:t,data:r,it:n}=e;t.if(n.parentData,()=>t.assign(r,(0,qe._)`${n.parentData}[${n.parentDataProperty}]`))}function EP(e,t){let{gen:r}=e;r.if((0,qe._)`Array.isArray(${t})`,()=>{r.assign($r.default.vErrors,(0,qe._)`${$r.default.vErrors} === null ? ${t} : ${$r.default.vErrors}.concat(${t})`).assign($r.default.errors,(0,qe._)`${$r.default.vErrors}.length`),(0,kP.extendErrors)(e)},()=>e.error())}function TP({schemaEnv:e},t){if(t.async&&!e.$async)throw new Error("async keyword in sync schema")}function Xg(e,t,r){if(r===void 0)throw new Error(`keyword "${t}" failed to compile`);return e.scopeValue("keyword",typeof r=="function"?{ref:r}:{ref:r,code:(0,qe.stringify)(r)})}function OP(e,t,r=!1){return!t.length||t.some(n=>n==="array"?Array.isArray(e):n==="object"?e&&typeof e=="object"&&!Array.isArray(e):typeof e==n||r&&typeof e>"u")}vt.validSchemaType=OP;function AP({schema:e,opts:t,self:r,errSchemaPath:n},o,i){if(Array.isArray(o.keyword)?!o.keyword.includes(i):o.keyword!==i)throw new Error("ajv implementation error");let s=o.dependencies;if(s?.some(a=>!Object.prototype.hasOwnProperty.call(e,a)))throw new Error(`parent schema must have dependencies of ${i}: ${s.join(",")}`);if(o.validateSchema&&!o.validateSchema(e[i])){let c=`keyword "${i}" value is invalid at path "${n}": `+r.errorsText(o.validateSchema.errors);if(t.validateSchema==="log")r.logger.error(c);else throw new Error(c)}}vt.validateKeywordUsage=AP});var ty=x(nr=>{"use strict";Object.defineProperty(nr,"__esModule",{value:!0});nr.extendSubschemaMode=nr.extendSubschemaData=nr.getSubschema=void 0;var bt=j(),ey=V();function IP(e,{keyword:t,schemaProp:r,schema:n,schemaPath:o,errSchemaPath:i,topSchemaRef:s}){if(t!==void 0&&n!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(t!==void 0){let a=e.schema[t];return r===void 0?{schema:a,schemaPath:(0,bt._)`${e.schemaPath}${(0,bt.getProperty)(t)}`,errSchemaPath:`${e.errSchemaPath}/${t}`}:{schema:a[r],schemaPath:(0,bt._)`${e.schemaPath}${(0,bt.getProperty)(t)}${(0,bt.getProperty)(r)}`,errSchemaPath:`${e.errSchemaPath}/${t}/${(0,ey.escapeFragment)(r)}`}}if(n!==void 0){if(o===void 0||i===void 0||s===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:o,topSchemaRef:s,errSchemaPath:i}}throw new Error('either "keyword" or "schema" must be passed')}nr.getSubschema=IP;function RP(e,t,{dataProp:r,dataPropType:n,data:o,dataTypes:i,propertyName:s}){if(o!==void 0&&r!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:a}=t;if(r!==void 0){let{errorPath:u,dataPathArr:l,opts:f}=t,d=a.let("data",(0,bt._)`${t.data}${(0,bt.getProperty)(r)}`,!0);c(d),e.errorPath=(0,bt.str)`${u}${(0,ey.getErrorPath)(r,n,f.jsPropertySyntax)}`,e.parentDataProperty=(0,bt._)`${r}`,e.dataPathArr=[...l,e.parentDataProperty]}if(o!==void 0){let u=o instanceof bt.Name?o:a.let("data",o,!0);c(u),s!==void 0&&(e.propertyName=s)}i&&(e.dataTypes=i);function c(u){e.data=u,e.dataLevel=t.dataLevel+1,e.dataTypes=[],t.definedProperties=new Set,e.parentData=t.data,e.dataNames=[...t.dataNames,u]}}nr.extendSubschemaData=RP;function CP(e,{jtdDiscriminator:t,jtdMetadata:r,compositeRule:n,createErrors:o,allErrors:i}){n!==void 0&&(e.compositeRule=n),o!==void 0&&(e.createErrors=o),i!==void 0&&(e.allErrors=i),e.jtdDiscriminator=t,e.jtdMetadata=r}nr.extendSubschemaMode=CP});var ju=x((c2,ry)=>{"use strict";ry.exports=function e(t,r){if(t===r)return!0;if(t&&r&&typeof t=="object"&&typeof r=="object"){if(t.constructor!==r.constructor)return!1;var n,o,i;if(Array.isArray(t)){if(n=t.length,n!=r.length)return!1;for(o=n;o--!==0;)if(!e(t[o],r[o]))return!1;return!0}if(t.constructor===RegExp)return t.source===r.source&&t.flags===r.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===r.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===r.toString();if(i=Object.keys(t),n=i.length,n!==Object.keys(r).length)return!1;for(o=n;o--!==0;)if(!Object.prototype.hasOwnProperty.call(r,i[o]))return!1;for(o=n;o--!==0;){var s=i[o];if(!e(t[s],r[s]))return!1}return!0}return t!==t&&r!==r}});var oy=x((u2,ny)=>{"use strict";var or=ny.exports=function(e,t,r){typeof t=="function"&&(r=t,t={}),r=t.cb||r;var n=typeof r=="function"?r:r.pre||function(){},o=r.post||function(){};$s(t,n,o,e,"",e)};or.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};or.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};or.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};or.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function $s(e,t,r,n,o,i,s,a,c,u){if(n&&typeof n=="object"&&!Array.isArray(n)){t(n,o,i,s,a,c,u);for(var l in n){var f=n[l];if(Array.isArray(f)){if(l in or.arrayKeywords)for(var d=0;d{"use strict";Object.defineProperty(He,"__esModule",{value:!0});He.getSchemaRefs=He.resolveUrl=He.normalizeId=He._getFullPath=He.getFullPath=He.inlineRef=void 0;var jP=V(),DP=ju(),MP=oy(),qP=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function FP(e,t=!0){return typeof e=="boolean"?!0:t===!0?!Du(e):t?iy(e)<=t:!1}He.inlineRef=FP;var ZP=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Du(e){for(let t in e){if(ZP.has(t))return!0;let r=e[t];if(Array.isArray(r)&&r.some(Du)||typeof r=="object"&&Du(r))return!0}return!1}function iy(e){let t=0;for(let r in e){if(r==="$ref")return 1/0;if(t++,!qP.has(r)&&(typeof e[r]=="object"&&(0,jP.eachItem)(e[r],n=>t+=iy(n)),t===1/0))return 1/0}return t}function sy(e,t="",r){r!==!1&&(t=fn(t));let n=e.parse(t);return ay(e,n)}He.getFullPath=sy;function ay(e,t){return e.serialize(t).split("#")[0]+"#"}He._getFullPath=ay;var LP=/#\/?$/;function fn(e){return e?e.replace(LP,""):""}He.normalizeId=fn;function UP(e,t,r){return r=fn(r),e.resolve(t,r)}He.resolveUrl=UP;var VP=/^[a-z_][-a-z0-9._]*$/i;function HP(e,t){if(typeof e=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,o=fn(e[r]||t),i={"":o},s=sy(n,o,!1),a={},c=new Set;return MP(e,{allKeys:!0},(f,d,p,m)=>{if(m===void 0)return;let h=s+d,g=i[m];typeof f[r]=="string"&&(g=y.call(this,f[r])),v.call(this,f.$anchor),v.call(this,f.$dynamicAnchor),i[d]=g;function y(S){let k=this.opts.uriResolver.resolve;if(S=fn(g?k(g,S):S),c.has(S))throw l(S);c.add(S);let $=this.refs[S];return typeof $=="string"&&($=this.refs[$]),typeof $=="object"?u(f,$.schema,S):S!==fn(h)&&(S[0]==="#"?(u(f,a[S],S),a[S]=f):this.refs[S]=h),S}function v(S){if(typeof S=="string"){if(!VP.test(S))throw new Error(`invalid anchor "${S}"`);y.call(this,`#${S}`)}}}),a;function u(f,d,p){if(d!==void 0&&!DP(f,d))throw l(p)}function l(f){return new Error(`reference "${f}" resolves to more than one schema`)}}He.getSchemaRefs=HP});var Io=x(ir=>{"use strict";Object.defineProperty(ir,"__esModule",{value:!0});ir.getData=ir.KeywordCxt=ir.validateFunctionCode=void 0;var dy=Zg(),cy=Eo(),qu=Tu(),ks=Eo(),BP=Jg(),Ao=Qg(),Mu=ty(),E=j(),R=Ft(),KP=To(),Zt=V(),Oo=Po();function JP(e){if(hy(e)&&(gy(e),my(e))){YP(e);return}py(e,()=>(0,dy.topBoolOrEmptySchema)(e))}ir.validateFunctionCode=JP;function py({gen:e,validateName:t,schema:r,schemaEnv:n,opts:o},i){o.code.es5?e.func(t,(0,E._)`${R.default.data}, ${R.default.valCxt}`,n.$async,()=>{e.code((0,E._)`"use strict"; ${uy(r,o)}`),GP(e,o),e.code(i)}):e.func(t,(0,E._)`${R.default.data}, ${WP(o)}`,n.$async,()=>e.code(uy(r,o)).code(i))}function WP(e){return(0,E._)`{${R.default.instancePath}="", ${R.default.parentData}, ${R.default.parentDataProperty}, ${R.default.rootData}=${R.default.data}${e.dynamicRef?(0,E._)`, ${R.default.dynamicAnchors}={}`:E.nil}}={}`}function GP(e,t){e.if(R.default.valCxt,()=>{e.var(R.default.instancePath,(0,E._)`${R.default.valCxt}.${R.default.instancePath}`),e.var(R.default.parentData,(0,E._)`${R.default.valCxt}.${R.default.parentData}`),e.var(R.default.parentDataProperty,(0,E._)`${R.default.valCxt}.${R.default.parentDataProperty}`),e.var(R.default.rootData,(0,E._)`${R.default.valCxt}.${R.default.rootData}`),t.dynamicRef&&e.var(R.default.dynamicAnchors,(0,E._)`${R.default.valCxt}.${R.default.dynamicAnchors}`)},()=>{e.var(R.default.instancePath,(0,E._)`""`),e.var(R.default.parentData,(0,E._)`undefined`),e.var(R.default.parentDataProperty,(0,E._)`undefined`),e.var(R.default.rootData,R.default.data),t.dynamicRef&&e.var(R.default.dynamicAnchors,(0,E._)`{}`)})}function YP(e){let{schema:t,opts:r,gen:n}=e;py(e,()=>{r.$comment&&t.$comment&&_y(e),rE(e),n.let(R.default.vErrors,null),n.let(R.default.errors,0),r.unevaluated&&XP(e),yy(e),iE(e)})}function XP(e){let{gen:t,validateName:r}=e;e.evaluated=t.const("evaluated",(0,E._)`${r}.evaluated`),t.if((0,E._)`${e.evaluated}.dynamicProps`,()=>t.assign((0,E._)`${e.evaluated}.props`,(0,E._)`undefined`)),t.if((0,E._)`${e.evaluated}.dynamicItems`,()=>t.assign((0,E._)`${e.evaluated}.items`,(0,E._)`undefined`))}function uy(e,t){let r=typeof e=="object"&&e[t.schemaId];return r&&(t.code.source||t.code.process)?(0,E._)`/*# sourceURL=${r} */`:E.nil}function QP(e,t){if(hy(e)&&(gy(e),my(e))){eE(e,t);return}(0,dy.boolOrEmptySchema)(e,t)}function my({schema:e,self:t}){if(typeof e=="boolean")return!e;for(let r in e)if(t.RULES.all[r])return!0;return!1}function hy(e){return typeof e.schema!="boolean"}function eE(e,t){let{schema:r,gen:n,opts:o}=e;o.$comment&&r.$comment&&_y(e),nE(e),oE(e);let i=n.const("_errs",R.default.errors);yy(e,i),n.var(t,(0,E._)`${i} === ${R.default.errors}`)}function gy(e){(0,Zt.checkUnknownRules)(e),tE(e)}function yy(e,t){if(e.opts.jtd)return ly(e,[],!1,t);let r=(0,cy.getSchemaTypes)(e.schema),n=(0,cy.coerceAndCheckDataType)(e,r);ly(e,r,!n,t)}function tE(e){let{schema:t,errSchemaPath:r,opts:n,self:o}=e;t.$ref&&n.ignoreKeywordsWithRef&&(0,Zt.schemaHasRulesButRef)(t,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function rE(e){let{schema:t,opts:r}=e;t.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,Zt.checkStrictMode)(e,"default is ignored in the schema root")}function nE(e){let t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,KP.resolveUrl)(e.opts.uriResolver,e.baseId,t))}function oE(e){if(e.schema.$async&&!e.schemaEnv.$async)throw new Error("async schema in sync schema")}function _y({gen:e,schemaEnv:t,schema:r,errSchemaPath:n,opts:o}){let i=r.$comment;if(o.$comment===!0)e.code((0,E._)`${R.default.self}.logger.log(${i})`);else if(typeof o.$comment=="function"){let s=(0,E.str)`${n}/$comment`,a=e.scopeValue("root",{ref:t.root});e.code((0,E._)`${R.default.self}.opts.$comment(${i}, ${s}, ${a}.schema)`)}}function iE(e){let{gen:t,schemaEnv:r,validateName:n,ValidationError:o,opts:i}=e;r.$async?t.if((0,E._)`${R.default.errors} === 0`,()=>t.return(R.default.data),()=>t.throw((0,E._)`new ${o}(${R.default.vErrors})`)):(t.assign((0,E._)`${n}.errors`,R.default.vErrors),i.unevaluated&&sE(e),t.return((0,E._)`${R.default.errors} === 0`))}function sE({gen:e,evaluated:t,props:r,items:n}){r instanceof E.Name&&e.assign((0,E._)`${t}.props`,r),n instanceof E.Name&&e.assign((0,E._)`${t}.items`,n)}function ly(e,t,r,n){let{gen:o,schema:i,data:s,allErrors:a,opts:c,self:u}=e,{RULES:l}=u;if(i.$ref&&(c.ignoreKeywordsWithRef||!(0,Zt.schemaHasRulesButRef)(i,l))){o.block(()=>xy(e,"$ref",l.all.$ref.definition));return}c.jtd||aE(e,t),o.block(()=>{for(let d of l.rules)f(d);f(l.post)});function f(d){(0,qu.shouldUseGroup)(i,d)&&(d.type?(o.if((0,ks.checkDataType)(d.type,s,c.strictNumbers)),fy(e,d),t.length===1&&t[0]===d.type&&r&&(o.else(),(0,ks.reportTypeError)(e)),o.endIf()):fy(e,d),a||o.if((0,E._)`${R.default.errors} === ${n||0}`))}}function fy(e,t){let{gen:r,schema:n,opts:{useDefaults:o}}=e;o&&(0,BP.assignDefaults)(e,t.type),r.block(()=>{for(let i of t.rules)(0,qu.shouldUseRule)(n,i)&&xy(e,i.keyword,i.definition,t.type)})}function aE(e,t){e.schemaEnv.meta||!e.opts.strictTypes||(cE(e,t),e.opts.allowUnionTypes||uE(e,t),lE(e,e.dataTypes))}function cE(e,t){if(t.length){if(!e.dataTypes.length){e.dataTypes=t;return}t.forEach(r=>{wy(e.dataTypes,r)||Fu(e,`type "${r}" not allowed by context "${e.dataTypes.join(",")}"`)}),dE(e,t)}}function uE(e,t){t.length>1&&!(t.length===2&&t.includes("null"))&&Fu(e,"use allowUnionTypes to allow union type keyword")}function lE(e,t){let r=e.self.RULES.all;for(let n in r){let o=r[n];if(typeof o=="object"&&(0,qu.shouldUseRule)(e.schema,o)){let{type:i}=o.definition;i.length&&!i.some(s=>fE(t,s))&&Fu(e,`missing type "${i.join(",")}" for keyword "${n}"`)}}}function fE(e,t){return e.includes(t)||t==="number"&&e.includes("integer")}function wy(e,t){return e.includes(t)||t==="integer"&&e.includes("number")}function dE(e,t){let r=[];for(let n of e.dataTypes)wy(t,n)?r.push(n):t.includes("integer")&&n==="number"&&r.push("integer");e.dataTypes=r}function Fu(e,t){let r=e.schemaEnv.baseId+e.errSchemaPath;t+=` at "${r}" (strictTypes)`,(0,Zt.checkStrictMode)(e,t,e.opts.strictTypes)}var zs=class{constructor(t,r,n){if((0,Ao.validateKeywordUsage)(t,r,n),this.gen=t.gen,this.allErrors=t.allErrors,this.keyword=n,this.data=t.data,this.schema=t.schema[n],this.$data=r.$data&&t.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,Zt.schemaRefOrVal)(t,this.schema,n,this.$data),this.schemaType=r.schemaType,this.parentSchema=t.schema,this.params={},this.it=t,this.def=r,this.$data)this.schemaCode=t.gen.const("vSchema",vy(this.$data,t));else if(this.schemaCode=this.schemaValue,!(0,Ao.validSchemaType)(this.schema,r.schemaType,r.allowUndefined))throw new Error(`${n} value must be ${JSON.stringify(r.schemaType)}`);("code"in r?r.trackErrors:r.errors!==!1)&&(this.errsCount=t.gen.const("_errs",R.default.errors))}result(t,r,n){this.failResult((0,E.not)(t),r,n)}failResult(t,r,n){this.gen.if(t),n?n():this.error(),r?(this.gen.else(),r(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(t,r){this.failResult((0,E.not)(t),void 0,r)}fail(t){if(t===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(t),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(t){if(!this.$data)return this.fail(t);let{schemaCode:r}=this;this.fail((0,E._)`${r} !== undefined && (${(0,E.or)(this.invalid$data(),t)})`)}error(t,r,n){if(r){this.setParams(r),this._error(t,n),this.setParams({});return}this._error(t,n)}_error(t,r){(t?Oo.reportExtraError:Oo.reportError)(this,this.def.error,r)}$dataError(){(0,Oo.reportError)(this,this.def.$dataError||Oo.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,Oo.resetErrorsCount)(this.gen,this.errsCount)}ok(t){this.allErrors||this.gen.if(t)}setParams(t,r){r?Object.assign(this.params,t):this.params=t}block$data(t,r,n=E.nil){this.gen.block(()=>{this.check$data(t,n),r()})}check$data(t=E.nil,r=E.nil){if(!this.$data)return;let{gen:n,schemaCode:o,schemaType:i,def:s}=this;n.if((0,E.or)((0,E._)`${o} === undefined`,r)),t!==E.nil&&n.assign(t,!0),(i.length||s.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),t!==E.nil&&n.assign(t,!1)),n.else()}invalid$data(){let{gen:t,schemaCode:r,schemaType:n,def:o,it:i}=this;return(0,E.or)(s(),a());function s(){if(n.length){if(!(r instanceof E.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,E._)`${(0,ks.checkDataTypes)(c,r,i.opts.strictNumbers,ks.DataType.Wrong)}`}return E.nil}function a(){if(o.validateSchema){let c=t.scopeValue("validate$data",{ref:o.validateSchema});return(0,E._)`!${c}(${r})`}return E.nil}}subschema(t,r){let n=(0,Mu.getSubschema)(this.it,t);(0,Mu.extendSubschemaData)(n,this.it,t),(0,Mu.extendSubschemaMode)(n,t);let o={...this.it,...n,items:void 0,props:void 0};return QP(o,r),o}mergeEvaluated(t,r){let{it:n,gen:o}=this;n.opts.unevaluated&&(n.props!==!0&&t.props!==void 0&&(n.props=Zt.mergeEvaluated.props(o,t.props,n.props,r)),n.items!==!0&&t.items!==void 0&&(n.items=Zt.mergeEvaluated.items(o,t.items,n.items,r)))}mergeValidEvaluated(t,r){let{it:n,gen:o}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return o.if(r,()=>this.mergeEvaluated(t,E.Name)),!0}};ir.KeywordCxt=zs;function xy(e,t,r,n){let o=new zs(e,r,t);"code"in r?r.code(o,n):o.$data&&r.validate?(0,Ao.funcKeywordCode)(o,r):"macro"in r?(0,Ao.macroKeywordCode)(o,r):(r.compile||r.validate)&&(0,Ao.funcKeywordCode)(o,r)}var pE=/^\/(?:[^~]|~0|~1)*$/,mE=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function vy(e,{dataLevel:t,dataNames:r,dataPathArr:n}){let o,i;if(e==="")return R.default.rootData;if(e[0]==="/"){if(!pE.test(e))throw new Error(`Invalid JSON-pointer: ${e}`);o=e,i=R.default.rootData}else{let u=mE.exec(e);if(!u)throw new Error(`Invalid JSON-pointer: ${e}`);let l=+u[1];if(o=u[2],o==="#"){if(l>=t)throw new Error(c("property/index",l));return n[t-l]}if(l>t)throw new Error(c("data",l));if(i=r[t-l],!o)return i}let s=i,a=o.split("/");for(let u of a)u&&(i=(0,E._)`${i}${(0,E.getProperty)((0,Zt.unescapeJsonPointer)(u))}`,s=(0,E._)`${s} && ${i}`);return s;function c(u,l){return`Cannot access ${u} ${l} levels up, current level is ${t}`}}ir.getData=vy});var Ps=x(Lu=>{"use strict";Object.defineProperty(Lu,"__esModule",{value:!0});var Zu=class extends Error{constructor(t){super("validation failed"),this.errors=t,this.ajv=this.validation=!0}};Lu.default=Zu});var Ro=x(Hu=>{"use strict";Object.defineProperty(Hu,"__esModule",{value:!0});var Uu=To(),Vu=class extends Error{constructor(t,r,n,o){super(o||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,Uu.resolveUrl)(t,r,n),this.missingSchema=(0,Uu.normalizeId)((0,Uu.getFullPath)(t,this.missingRef))}};Hu.default=Vu});var Ts=x(at=>{"use strict";Object.defineProperty(at,"__esModule",{value:!0});at.resolveSchema=at.getCompilingSchema=at.resolveRef=at.compileSchema=at.SchemaEnv=void 0;var yt=j(),hE=Ps(),kr=Ft(),_t=To(),by=V(),gE=Io(),dn=class{constructor(t){var r;this.refs={},this.dynamicAnchors={};let n;typeof t.schema=="object"&&(n=t.schema),this.schema=t.schema,this.schemaId=t.schemaId,this.root=t.root||this,this.baseId=(r=t.baseId)!==null&&r!==void 0?r:(0,_t.normalizeId)(n?.[t.schemaId||"$id"]),this.schemaPath=t.schemaPath,this.localRefs=t.localRefs,this.meta=t.meta,this.$async=n?.$async,this.refs={}}};at.SchemaEnv=dn;function Ku(e){let t=Sy.call(this,e);if(t)return t;let r=(0,_t.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:n,lines:o}=this.opts.code,{ownProperties:i}=this.opts,s=new yt.CodeGen(this.scope,{es5:n,lines:o,ownProperties:i}),a;e.$async&&(a=s.scopeValue("Error",{ref:hE.default,code:(0,yt._)`require("ajv/dist/runtime/validation_error").default`}));let c=s.scopeName("validate");e.validateName=c;let u={gen:s,allErrors:this.opts.allErrors,data:kr.default.data,parentData:kr.default.parentData,parentDataProperty:kr.default.parentDataProperty,dataNames:[kr.default.data],dataPathArr:[yt.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:s.scopeValue("schema",this.opts.code.source===!0?{ref:e.schema,code:(0,yt.stringify)(e.schema)}:{ref:e.schema}),validateName:c,ValidationError:a,schema:e.schema,schemaEnv:e,rootId:r,baseId:e.baseId||r,schemaPath:yt.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,yt._)`""`,opts:this.opts,self:this},l;try{this._compilations.add(e),(0,gE.validateFunctionCode)(u),s.optimize(this.opts.code.optimize);let f=s.toString();l=`${s.scopeRefs(kr.default.scope)}return ${f}`,this.opts.code.process&&(l=this.opts.code.process(l,e));let p=new Function(`${kr.default.self}`,`${kr.default.scope}`,l)(this,this.scope.get());if(this.scope.value(c,{ref:p}),p.errors=null,p.schema=e.schema,p.schemaEnv=e,e.$async&&(p.$async=!0),this.opts.code.source===!0&&(p.source={validateName:c,validateCode:f,scopeValues:s._values}),this.opts.unevaluated){let{props:m,items:h}=u;p.evaluated={props:m instanceof yt.Name?void 0:m,items:h instanceof yt.Name?void 0:h,dynamicProps:m instanceof yt.Name,dynamicItems:h instanceof yt.Name},p.source&&(p.source.evaluated=(0,yt.stringify)(p.evaluated))}return e.validate=p,e}catch(f){throw delete e.validate,delete e.validateName,l&&this.logger.error("Error compiling schema, function code:",l),f}finally{this._compilations.delete(e)}}at.compileSchema=Ku;function yE(e,t,r){var n;r=(0,_t.resolveUrl)(this.opts.uriResolver,t,r);let o=e.refs[r];if(o)return o;let i=xE.call(this,e,r);if(i===void 0){let s=(n=e.localRefs)===null||n===void 0?void 0:n[r],{schemaId:a}=this.opts;s&&(i=new dn({schema:s,schemaId:a,root:e,baseId:t}))}if(i!==void 0)return e.refs[r]=_E.call(this,i)}at.resolveRef=yE;function _E(e){return(0,_t.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:Ku.call(this,e)}function Sy(e){for(let t of this._compilations)if(wE(t,e))return t}at.getCompilingSchema=Sy;function wE(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}function xE(e,t){let r;for(;typeof(r=this.refs[t])=="string";)t=r;return r||this.schemas[t]||Es.call(this,e,t)}function Es(e,t){let r=this.opts.uriResolver.parse(t),n=(0,_t._getFullPath)(this.opts.uriResolver,r),o=(0,_t.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&n===o)return Bu.call(this,r,e);let i=(0,_t.normalizeId)(n),s=this.refs[i]||this.schemas[i];if(typeof s=="string"){let a=Es.call(this,e,s);return typeof a?.schema!="object"?void 0:Bu.call(this,r,a)}if(typeof s?.schema=="object"){if(s.validate||Ku.call(this,s),i===(0,_t.normalizeId)(t)){let{schema:a}=s,{schemaId:c}=this.opts,u=a[c];return u&&(o=(0,_t.resolveUrl)(this.opts.uriResolver,o,u)),new dn({schema:a,schemaId:c,root:e,baseId:o})}return Bu.call(this,r,s)}}at.resolveSchema=Es;var vE=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Bu(e,{baseId:t,schema:r,root:n}){var o;if(((o=e.fragment)===null||o===void 0?void 0:o[0])!=="/")return;for(let a of e.fragment.slice(1).split("/")){if(typeof r=="boolean")return;let c=r[(0,by.unescapeFragment)(a)];if(c===void 0)return;r=c;let u=typeof r=="object"&&r[this.opts.schemaId];!vE.has(a)&&u&&(t=(0,_t.resolveUrl)(this.opts.uriResolver,t,u))}let i;if(typeof r!="boolean"&&r.$ref&&!(0,by.schemaHasRulesButRef)(r,this.RULES)){let a=(0,_t.resolveUrl)(this.opts.uriResolver,t,r.$ref);i=Es.call(this,n,a)}let{schemaId:s}=this.opts;if(i=i||new dn({schema:r,schemaId:s,root:n,baseId:t}),i.schema!==i.root.schema)return i}});var $y=x((h2,bE)=>{bE.exports={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1}});var Qu=x((g2,Iy)=>{"use strict";var SE=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),Wu=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u),$E=RegExp.prototype.test.bind(/^\d*$/u),zr=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),Gu=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),zy=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/]$/u),Yu=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/?]$/u),kE=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:]$/u),Be=new Array(256);{let e="0123456789ABCDEF";for(let t=0;t<256;t++)Be[t]="%"+e[t>>4]+e[t&15]}function Ce(e){return e<2048?Be[192|e>>6]+Be[128|e&63]:e<65536?Be[224|e>>12]+Be[128|e>>6&63]+Be[128|e&63]:Be[240|e>>18]+Be[128|e>>12&63]+Be[128|e>>6&63]+Be[128|e&63]}function zE(e){let t="",r=0,n=0;for(n=0;n=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";t+=e[n];break}for(n+=1;n=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";t+=e[n]}return t}var PE=RegExp.prototype.test.bind(/^[\dA-Fa-f]{1,4}$/),EE=RegExp.prototype.test.bind(/^[vV][\dA-Fa-f]+\.[A-Za-z\d\-._~!$&'()*+,;=:]+$/),TE=RegExp.prototype.test.bind(/^[A-Za-z\d\-._~]$/),OE=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function AE(e){if(e.length===0)return!1;for(let t=0;tr&&(r=o,t=n)):(n=-1,o=0);if(r<2)return e.join(":");let i=e.slice(0,t).join(":"),s=e.slice(t+r).join(":");return i+"::"+s}function IE(e){let t=e.indexOf("::");if(t!==-1&&e.indexOf("::",t+1)!==-1)return;let r=t===-1?e.split(":"):e.slice(0,t).split(":"),n=t===-1?[]:e.slice(t+2).split(":");t!==-1&&(r.length===1&&r[0]===""&&(r.length=0),n.length===1&&n[0]===""&&(n.length=0));let o=r.concat(n),i=0;for(let a=0;a=8)return;let s=o.slice(0,r.length);for(let a=i;a<8;a++)s.push("0");for(let a=r.length;aNE[n])}function Ty(e,t=!1){if(e.indexOf("%")===-1)return e;let r="";for(let n=0;n57343)t+=Ce(o);else if(o<=56319&&r+1=56320&&i<=57343?(t+=Ce(65536+(o-55296<<10)+(i-56320)),r++):t+=Ce(65533)}else t+=Ce(65533)}}return t}function qE(e,t=!1){let r="",n=t&&e[0]!=="/";for(let o=0;o57343)r+=Ce(s);else if(s<=56319&&o+1=56320&&a<=57343?(r+=Ce(65536+(s-55296<<10)+(a-56320)),o++):r+=Ce(65533)}else r+=Ce(65533)}}return r}function Xu(e,t){let r="";for(let n=0;n57343)r+=Ce(i);else if(i<=56319&&n+1=56320&&s<=57343?(r+=Ce(65536+(i-55296<<10)+(s-56320)),n++):r+=Ce(65533)}else r+=Ce(65533)}}return r}function Oy(e){return Xu(e,kE)}function FE(e){return Xu(e,Yu)}function ZE(e){return Xu(e,Yu)}function Ay(e){return e>=48&&e<=57||e>=65&&e<=90||e>=97&&e<=122||e===42||e===43||e===45||e===46||e===47||e===64||e===95}function LE(e){let t="";for(let r=0;r57343)t+=Ce(o);else if(o<=56319&&r+1=56320&&i<=57343?(t+=Ce(65536+(o-55296<<10)+(i-56320)),r++):t+=Ce(65533)}else t+=Ce(65533)}}return t}function UE(e){let t="";for(let r=0;r{"use strict";var{isUUID:HE}=Qu(),BE=/^([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-./:;=@]|%[\da-f]{2})+)$/iu,KE=["http","https","ws","wss","urn","urn:uuid"];function JE(e){return KE.indexOf(e)!==-1}function el(e){return e.secure===!0?!0:e.secure===!1?!1:e.scheme?e.scheme.length===3&&(e.scheme[0]==="w"||e.scheme[0]==="W")&&(e.scheme[1]==="s"||e.scheme[1]==="S")&&(e.scheme[2]==="s"||e.scheme[2]==="S"):!1}function Ry(e){return e.host||(e.error=e.error||"HTTP URIs must have a host."),e}function Cy(e){let t=String(e.scheme).toLowerCase()==="https";return(e.port===(t?443:80)||e.port==="")&&(e.port=void 0),e.path||(e.path="/"),e}function WE(e){return e.secure=el(e),e.resourceName=(e.path||"/")+(e.query?"?"+e.query:""),e.path=void 0,e.query=void 0,e}function GE(e){if((e.port===(el(e)?443:80)||e.port==="")&&(e.port=void 0),typeof e.secure=="boolean"&&(e.scheme=e.secure?"wss":"ws",e.secure=void 0),e.resourceName){let t=e.resourceName.indexOf("?"),r=t===-1?e.resourceName:e.resourceName.slice(0,t);e.path=r&&r!=="/"?r:void 0,e.query=t===-1?void 0:e.resourceName.slice(t+1),e.resourceName=void 0}return e.fragment=void 0,e}function YE(e,t){if(!e.path)return e.error="URN can not be parsed",e;let r=e.path.match(BE);if(r&&r[0]===e.path){let n=t.scheme||e.scheme||"urn";e.nid=r[1].toLowerCase(),e.nss=r[2];let o=`${n}:${t.nid||e.nid}`,i=tl(o);e.path=void 0,i&&(e=i.parse(e,t))}else e.error=e.error||"URN can not be parsed.";return e}function XE(e,t){if(e.nid===void 0)throw new Error("URN without nid cannot be serialized");let r=t.scheme||e.scheme||"urn",n=e.nid.toLowerCase(),o=`${r}:${t.nid||n}`,i=tl(o);i&&(e=i.serialize(e,t));let s=e,a=e.nss;return s.path=`${n||t.nid}:${a}`,t.skipEscape=!0,s}function QE(e,t){let r=e;return r.uuid=r.nss,r.nss=void 0,!t.tolerant&&(!r.uuid||!HE(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function eT(e){let t=e;return t.nss=(e.uuid||"").toLowerCase(),t}var Ny={scheme:"http",domainHost:!0,parse:Ry,serialize:Cy},tT={scheme:"https",domainHost:Ny.domainHost,parse:Ry,serialize:Cy},Os={scheme:"ws",domainHost:!0,parse:WE,serialize:GE},rT={scheme:"wss",domainHost:Os.domainHost,parse:Os.parse,serialize:Os.serialize},nT={scheme:"urn",parse:YE,serialize:XE,skipNormalize:!0},oT={scheme:"urn:uuid",parse:QE,serialize:eT,skipNormalize:!0},As={http:Ny,https:tT,ws:Os,wss:rT,urn:nT,"urn:uuid":oT};Object.setPrototypeOf(As,null);function tl(e){return e&&(As[e]||As[e.toLowerCase()])||void 0}jy.exports={wsIsSecure:el,SCHEMES:As,isValidSchemeName:JE,getSchemeHandler:tl}});var Xy=x((_2,js)=>{"use strict";var{normalizeIPv6:Ly,removeDotSegments:No,removeDotSegmentsRelative:Uy,recomposeAuthority:iT,normalizePercentEncoding:rl,normalizePathEncoding:sT,serializePathEncoding:My,normalizeQueryFragmentEncoding:qy,encodeQuery:aT,encodeFragment:cT,reescapeHostDelimiters:uT,isIPv4:Vy,nonSimpleDomain:lT}=Qu(),{SCHEMES:Hy,getSchemeHandler:nl}=Dy(),By=/^[A-Za-z][A-Za-z0-9+.-]*$/u,Ky="URI scheme is malformed.",Is="URI host is malformed.",fT=/[\0-\x20"#/:<>?@[\\\]^`{|}\x7F]/u;function Fy(e){let t=String(e);if(!By.test(t))throw new TypeError(Ky);return t}function dT(e,t){return typeof e=="string"?e=vT(e,t):typeof e=="object"&&(e=Cs(Pr(e,t),t)),e}function pT(e,t,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},{parsed:o,malformedAuthorityOrPort:i,malformedPercentEncoding:s,malformedSchemeSpecific:a,malformedHost:c,malformedScheme:u}=Rs(e,n),{parsed:l,malformedAuthorityOrPort:f,malformedPercentEncoding:d,malformedSchemeSpecific:p,malformedHost:m,malformedScheme:h}=Rs(t,n);if(i||f||s||d||a||p||c||m||u||h)throw new Error(o.error||l.error||"URI is malformed.");let g=Jy(o,l,n,!0),y=nl(r&&r.scheme||g.scheme),v=g.host,S=v!==void 0&&v!==""&&(Vy(v)||Ly(v).isIPV6);if(Gy(g,r||{},y,S))throw new Error(Is);Wy(g,r||{},y,S);let k=v&&v.indexOf("%")!==-1&&!new RegExp("\\P{ASCII}","u").test(v);if(g.error&&!k)throw new Error(g.error);return n.skipEscape=!0,Pr(g,n)}function Jy(e,t,r,n){let o={};if(n||(e=Cs(Pr(e,r),r),t=Cs(Pr(t,r),r)),r=r||{},!r.tolerant&&t.scheme)o.scheme=t.scheme,o.userinfo=t.userinfo,o.host=t.host,o.port=t.port,o.path=No(t.path||""),o.query=t.query;else{if(t.userinfo!==void 0||t.host!==void 0||t.port!==void 0)o.userinfo=t.userinfo,o.host=t.host,o.port=t.port,o.path=No(t.path||""),o.query=t.query;else{if(!t.path)o.path=e.path,t.query!==void 0?o.query=t.query:o.query=e.query;else{if(t.path[0]==="/")o.path=No(t.path);else{let i=e.userinfo!==void 0||e.host!==void 0||e.port!==void 0;i&&!e.path?o.path="/"+t.path:e.path?o.path=e.path.slice(0,e.path.lastIndexOf("/")+1)+t.path:o.path=t.path,o.path=e.scheme===void 0&&!i&&o.path[0]!=="/"?Uy(o.path):No(o.path)}o.query=t.query}o.userinfo=e.userinfo,o.host=e.host,o.port=e.port}o.scheme=e.scheme}return o.fragment=t.fragment,o}function mT(e,t,r){let n=Zy(e,r),o=Zy(t,r);return n!==void 0&&o!==void 0&&n===o}function Pr(e,t){let r={host:e.host,scheme:e.scheme,userinfo:e.userinfo,port:e.port,path:e.path,query:e.query,nid:e.nid,nss:e.nss,uuid:e.uuid,fragment:e.fragment,reference:e.reference,resourceName:e.resourceName,secure:e.secure,error:""},n=Object.assign({},t),o=[];r.scheme&&(r.scheme=Fy(r.scheme));let i=nl(n.scheme||r.scheme);i&&i.serialize&&i.serialize(r,n);let s=r.userinfo!==void 0||r.host!==void 0||r.port!==void 0,a=(r.scheme===void 0||n.reference==="suffix")&&!s,c=!n.skipEscape&&a;r.path!==void 0&&(n.skipEscape?r.path=rl(r.path):r.path=My(r.path,c)),n.reference!=="suffix"&&r.scheme&&(r.scheme=Fy(r.scheme),o.push(r.scheme,":"));let u=iT(r);if(u!==void 0&&(n.reference!=="suffix"&&o.push("//"),o.push(u),r.path&&r.path[0]!=="/"&&o.push("/")),r.path!==void 0){let l=r.path;!n.absolutePath&&(!i||!i.absolutePath)&&(l=a&&l[0]!=="/"?Uy(l):No(l)),a&&(l=My(l,!0)),u===void 0&&l[0]==="/"&&l[1]==="/"&&(l="/%2F"+l.slice(2)),o.push(l)}return r.query!==void 0&&o.push("?",aT(r.query)),r.fragment!==void 0&&o.push("#",cT(r.fragment)),o.join("")}var hT=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,gT=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,yT=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function _T(e,t){if(t[2]!==void 0&&e.path&&e.path[0]!=="/")return'URI path must start with "/" when authority is present.';if(typeof e.port=="number"&&(e.port<0||e.port>65535))return"URI port is malformed."}function Co(e){if(e===void 0)return!1;let t=e.indexOf("%");for(;t!==-1;){if(t+2>=e.length||!/^[\da-f]{2}$/iu.test(e.slice(t+1,t+3)))return!0;t=e.indexOf("%",t+3)}return!1}function Ns(e){return e[0]==="["&&e[e.length-1]==="]"}function wT(e){let t=e[4];return Co(e[3])||t!==void 0&&!Ns(t)&&Co(t)||Co(e[6])||Co(e[7])||Co(e[8])}function Wy(e,t,r,n){if(Gy(e,t,r,n))return e.error=e.error||Is,!0;if(!t.unicodeSupport&&(!r||!r.unicodeSupport)&&e.host&&!Ns(e.host)&&(t.domainHost||r&&r.domainHost)&&n===!1&&lT(e.host)){let o;try{o=new URL("http://"+e.host)}catch(i){return e.error=e.error||"Host's domain name can not be converted to ASCII: "+i,!0}if(!xT(o))return e.error=e.error||Is,!0;e.host=o.hostname}return!1}function Gy(e,t,r,n){return!!(e.host&&n===!1&&!Ns(e.host)&&(t.domainHost||r&&r.domainHost)&&fT.test(e.host))}function xT(e){return e.username===""&&e.password===""&&e.port===""&&e.pathname==="/"&&e.search===""&&e.hash===""&&e.hostname!==""}function Rs(e,t){let r=Object.assign({},t),n={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},o=!1,i=!1,s=!1,a=!1,c=!1,u=!1,l=!1;r.reference==="suffix"&&(r.scheme?e=r.scheme+":"+e:e="//"+e);let f=e.match(gT);f!==null&&f[1].indexOf("\\")!==-1&&(n.error="URI authority must not contain a literal backslash.",o=!0);let d=e.match(yT);if(d!==null){let m=d[1],h=m.replace(/[\t\n\r]/g,"");h.length>=2&&(h.slice(0,2)!=="//"?(n.error=n.error||"URI authority must not contain a literal backslash.",o=!0):m.length!==h.length&&(n.error=n.error||"URI authority introducer must not contain whitespace.",o=!0))}let p=e.match(hT);if(p){n.scheme=p[1],n.userinfo=p[3],n.host=p[4],n.port=parseInt(p[5],10),n.path=p[6]||"",n.query=p[7],n.fragment=p[8],n.scheme!==void 0&&(By.test(n.scheme)?n.scheme=n.scheme.toLowerCase():(n.error=n.error||Ky,u=!0)),i=wT(p),i&&(n.error=n.error||"URI contains malformed percent-encoding."),isNaN(n.port)&&(n.port=p[5]);let m=_T(n,p);if(m!==void 0&&(n.error=n.error||m,o=!0),n.host)if(Vy(n.host)===!1){let y=Ns(n.host),v=n.host.indexOf("[")!==-1||n.host.indexOf("]")!==-1,S=Ly(n.host);l=S.isIPV6||S.isIPVFuture===!0,c=v&&(!y||S.error===!0),n.host=l?S.host:S.host.toLowerCase(),c&&(n.error=n.error||Is,o=!0)}else l=!0;n.scheme===void 0&&n.userinfo===void 0&&n.host===void 0&&n.port===void 0&&n.query===void 0&&!n.path?n.reference="same-document":n.scheme===void 0?n.reference="relative":n.fragment===void 0?n.reference="absolute":n.reference="uri",r.reference&&r.reference!=="suffix"&&r.reference!==n.reference&&(n.error=n.error||"URI is not a "+r.reference+" reference.");let h=nl(r.scheme||n.scheme);if(c||(a=Wy(n,r,h,l)),e.indexOf("%")!==-1&&n.host!==void 0&&!c){let g=l?n.host:rl(n.host,!0);l||(g=rl(g.toLowerCase())),n.host=l||r.scheme!=="null"?uT(g,l):g}(!h||h&&!h.skipNormalize)&&(n.path&&(n.path=sT(n.path)),n.query&&(n.query=qy(n.query)),n.fragment&&(n.fragment=qy(n.fragment))),h&&h.parse&&(h.parse(n,r),h===Hy.urn&&n.nid===void 0&&(s=!0))}else n.error=n.error||"URI can not be parsed.";return{parsed:n,malformedAuthorityOrPort:o,malformedPercentEncoding:i,malformedSchemeSpecific:s,malformedHost:a,malformedScheme:u}}function Cs(e,t){return Rs(e,t).parsed}function vT(e,t){return Yy(e,t).normalized}function Yy(e,t){let{parsed:r,malformedAuthorityOrPort:n,malformedPercentEncoding:o,malformedSchemeSpecific:i,malformedHost:s,malformedScheme:a}=Rs(e,t);return{normalized:n||o||i||s||a?e:Pr(r,t),malformedAuthorityOrPort:n,malformedPercentEncoding:o,malformedSchemeSpecific:i,malformedHost:s,malformedScheme:a}}function Zy(e,t){if(typeof e!="string"&&typeof e!="object")return;let r;try{r=typeof e=="string"?e:Pr(e,t)}catch{return}let{normalized:n,malformedAuthorityOrPort:o,malformedPercentEncoding:i,malformedSchemeSpecific:s,malformedHost:a,malformedScheme:c}=Yy(r,t);return o||i||s||a||c?void 0:n}var ol={SCHEMES:Hy,normalize:dT,resolve:pT,resolveComponent:Jy,equal:mT,serialize:Pr,parse:Cs};js.exports=ol;js.exports.default=ol;js.exports.fastUri=ol});var e_=x(il=>{"use strict";Object.defineProperty(il,"__esModule",{value:!0});var Qy=Xy();Qy.code='require("ajv/dist/runtime/uri").default';il.default=Qy});var c_=x(Ee=>{"use strict";Object.defineProperty(Ee,"__esModule",{value:!0});Ee.CodeGen=Ee.Name=Ee.nil=Ee.stringify=Ee.str=Ee._=Ee.KeywordCxt=void 0;var bT=Io();Object.defineProperty(Ee,"KeywordCxt",{enumerable:!0,get:function(){return bT.KeywordCxt}});var pn=j();Object.defineProperty(Ee,"_",{enumerable:!0,get:function(){return pn._}});Object.defineProperty(Ee,"str",{enumerable:!0,get:function(){return pn.str}});Object.defineProperty(Ee,"stringify",{enumerable:!0,get:function(){return pn.stringify}});Object.defineProperty(Ee,"nil",{enumerable:!0,get:function(){return pn.nil}});Object.defineProperty(Ee,"Name",{enumerable:!0,get:function(){return pn.Name}});Object.defineProperty(Ee,"CodeGen",{enumerable:!0,get:function(){return pn.CodeGen}});var ST=Ps(),i_=Ro(),$T=Eu(),jo=Ts(),kT=j(),Do=To(),Ds=Eo(),al=V(),t_=$y(),zT=e_(),s_=(e,t)=>new RegExp(e,t);s_.code="new RegExp";var PT=["removeAdditional","useDefaults","coerceTypes"],ET=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),TT={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},OT={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},r_=200;function AT(e){var t,r,n,o,i,s,a,c,u,l,f,d,p,m,h,g,y,v,S,k,$,b,T,F,me;let ft=e.strict,Bt=(t=e.code)===null||t===void 0?void 0:t.optimize,hr=Bt===!0||Bt===void 0?1:Bt||0,ci=(n=(r=e.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:s_,rb=(o=e.uriResolver)!==null&&o!==void 0?o:zT.default;return{strictSchema:(s=(i=e.strictSchema)!==null&&i!==void 0?i:ft)!==null&&s!==void 0?s:!0,strictNumbers:(c=(a=e.strictNumbers)!==null&&a!==void 0?a:ft)!==null&&c!==void 0?c:!0,strictTypes:(l=(u=e.strictTypes)!==null&&u!==void 0?u:ft)!==null&&l!==void 0?l:"log",strictTuples:(d=(f=e.strictTuples)!==null&&f!==void 0?f:ft)!==null&&d!==void 0?d:"log",strictRequired:(m=(p=e.strictRequired)!==null&&p!==void 0?p:ft)!==null&&m!==void 0?m:!1,code:e.code?{...e.code,optimize:hr,regExp:ci}:{optimize:hr,regExp:ci},loopRequired:(h=e.loopRequired)!==null&&h!==void 0?h:r_,loopEnum:(g=e.loopEnum)!==null&&g!==void 0?g:r_,meta:(y=e.meta)!==null&&y!==void 0?y:!0,messages:(v=e.messages)!==null&&v!==void 0?v:!0,inlineRefs:(S=e.inlineRefs)!==null&&S!==void 0?S:!0,schemaId:(k=e.schemaId)!==null&&k!==void 0?k:"$id",addUsedSchema:($=e.addUsedSchema)!==null&&$!==void 0?$:!0,validateSchema:(b=e.validateSchema)!==null&&b!==void 0?b:!0,validateFormats:(T=e.validateFormats)!==null&&T!==void 0?T:!0,unicodeRegExp:(F=e.unicodeRegExp)!==null&&F!==void 0?F:!0,int32range:(me=e.int32range)!==null&&me!==void 0?me:!0,uriResolver:rb}}var Mo=class{constructor(t={}){this.schemas={},this.refs={},this.formats=Object.create(null),this._compilations=new Set,this._loading={},this._cache=new Map,t=this.opts={...t,...AT(t)};let{es5:r,lines:n}=this.opts.code;this.scope=new kT.ValueScope({scope:{},prefixes:ET,es5:r,lines:n}),this.logger=DT(t.logger);let o=t.validateFormats;t.validateFormats=!1,this.RULES=(0,$T.getRules)(),n_.call(this,TT,t,"NOT SUPPORTED"),n_.call(this,OT,t,"DEPRECATED","warn"),this._metaOpts=NT.call(this),t.formats&&RT.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),t.keywords&&CT.call(this,t.keywords),typeof t.meta=="object"&&this.addMetaSchema(t.meta),IT.call(this),t.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:t,meta:r,schemaId:n}=this.opts,o=t_;n==="id"&&(o={...t_},o.id=o.$id,delete o.$id),r&&t&&this.addMetaSchema(o,o[n],!1)}defaultMeta(){let{meta:t,schemaId:r}=this.opts;return this.opts.defaultMeta=typeof t=="object"?t[r]||t:void 0}validate(t,r){let n;if(typeof t=="string"){if(n=this.getSchema(t),!n)throw new Error(`no schema with key or ref "${t}"`)}else n=this.compile(t);let o=n(r);return"$async"in n||(this.errors=n.errors),o}compile(t,r){let n=this._addSchema(t,r);return n.validate||this._compileSchemaEnv(n)}compileAsync(t,r){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:n}=this.opts;return o.call(this,t,r);async function o(l,f){await i.call(this,l.$schema);let d=this._addSchema(l,f);return d.validate||s.call(this,d)}async function i(l){l&&!this.getSchema(l)&&await o.call(this,{$ref:l},!0)}async function s(l){try{return this._compileSchemaEnv(l)}catch(f){if(!(f instanceof i_.default))throw f;return a.call(this,f),await c.call(this,f.missingSchema),s.call(this,l)}}function a({missingSchema:l,missingRef:f}){if(this.refs[l])throw new Error(`AnySchema ${l} is loaded but ${f} cannot be resolved`)}async function c(l){let f=await u.call(this,l);this.refs[l]||await i.call(this,f.$schema),this.refs[l]||this.addSchema(f,l,r)}async function u(l){let f=this._loading[l];if(f)return f;try{return await(this._loading[l]=n(l))}finally{delete this._loading[l]}}}addSchema(t,r,n,o=this.opts.validateSchema){if(Array.isArray(t)){for(let s of t)this.addSchema(s,void 0,n,o);return this}let i;if(typeof t=="object"){let{schemaId:s}=this.opts;if(i=t[s],i!==void 0&&typeof i!="string")throw new Error(`schema ${s} must be string`)}return r=(0,Do.normalizeId)(r||i),this._checkUnique(r),this.schemas[r]=this._addSchema(t,n,r,o,!0),this}addMetaSchema(t,r,n=this.opts.validateSchema){return this.addSchema(t,r,!0,n),this}validateSchema(t,r){if(typeof t=="boolean")return!0;let n;if(n=t.$schema,n!==void 0&&typeof n!="string")throw new Error("$schema must be a string");if(n=n||this.opts.defaultMeta||this.defaultMeta(),!n)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let o=this.validate(n,t);if(!o&&r){let i="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(i);else throw new Error(i)}return o}getSchema(t){let r;for(;typeof(r=o_.call(this,t))=="string";)t=r;if(r===void 0){let{schemaId:n}=this.opts,o=new jo.SchemaEnv({schema:{},schemaId:n});if(r=jo.resolveSchema.call(this,o,t),!r)return;this.refs[t]=r}return r.validate||this._compileSchemaEnv(r)}removeSchema(t){if(t instanceof RegExp)return this._removeAllSchemas(this.schemas,t),this._removeAllSchemas(this.refs,t),this;switch(typeof t){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let r=o_.call(this,t);return typeof r=="object"&&this._cache.delete(r.schema),delete this.schemas[t],delete this.refs[t],this}case"object":{let r=t;this._cache.delete(r);let n=t[this.opts.schemaId];return n&&(n=(0,Do.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(t){for(let r of t)this.addKeyword(r);return this}addKeyword(t,r){let n;if(typeof t=="string")n=t,typeof r=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),r.keyword=n);else if(typeof t=="object"&&r===void 0){if(r=t,n=r.keyword,Array.isArray(n)&&!n.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(qT.call(this,n,r),!r)return(0,al.eachItem)(n,i=>sl.call(this,i)),this;ZT.call(this,r);let o={...r,type:(0,Ds.getJSONTypes)(r.type),schemaType:(0,Ds.getJSONTypes)(r.schemaType)};return(0,al.eachItem)(n,o.type.length===0?i=>sl.call(this,i,o):i=>o.type.forEach(s=>sl.call(this,i,o,s))),this}getKeyword(t){let r=this.RULES.all[t];return typeof r=="object"?r.definition:!!r}removeKeyword(t){let{RULES:r}=this;delete r.keywords[t],delete r.all[t];for(let n of r.rules){let o=n.rules.findIndex(i=>i.keyword===t);o>=0&&n.rules.splice(o,1)}return this}addFormat(t,r){return typeof r=="string"&&(r=new RegExp(r)),this.formats[t]=r,this}errorsText(t=this.errors,{separator:r=", ",dataVar:n="data"}={}){return!t||t.length===0?"No errors":t.map(o=>`${n}${o.instancePath} ${o.message}`).reduce((o,i)=>o+r+i)}$dataMetaSchema(t,r){let n=this.RULES.all;t=JSON.parse(JSON.stringify(t));for(let o of r){let i=o.split("/").slice(1),s=t;for(let a of i)s=s[a];for(let a in n){let c=n[a];if(typeof c!="object")continue;let{$data:u}=c.definition,l=s[a];u&&l&&(s[a]=a_(l))}}return t}_removeAllSchemas(t,r){for(let n in t){let o=t[n];(!r||r.test(n))&&(typeof o=="string"?delete t[n]:o&&!o.meta&&(this._cache.delete(o.schema),delete t[n]))}}_addSchema(t,r,n,o=this.opts.validateSchema,i=this.opts.addUsedSchema){let s,{schemaId:a}=this.opts;if(typeof t=="object")s=t[a];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof t!="boolean")throw new Error("schema must be object or boolean")}let c=this._cache.get(t);if(c!==void 0)return c;n=(0,Do.normalizeId)(s||n);let u=Do.getSchemaRefs.call(this,t,n);return c=new jo.SchemaEnv({schema:t,schemaId:a,meta:r,baseId:n,localRefs:u}),this._cache.set(c.schema,c),i&&!n.startsWith("#")&&(n&&this._checkUnique(n),this.refs[n]=c),o&&this.validateSchema(t,!0),c}_checkUnique(t){if(this.schemas[t]||this.refs[t])throw new Error(`schema with key or id "${t}" already exists`)}_compileSchemaEnv(t){if(t.meta?this._compileMetaSchema(t):jo.compileSchema.call(this,t),!t.validate)throw new Error("ajv implementation error");return t.validate}_compileMetaSchema(t){let r=this.opts;this.opts=this._metaOpts;try{jo.compileSchema.call(this,t)}finally{this.opts=r}}};Mo.ValidationError=ST.default;Mo.MissingRefError=i_.default;Ee.default=Mo;function n_(e,t,r,n="error"){for(let o in e){let i=o;i in t&&this.logger[n](`${r}: option ${o}. ${e[i]}`)}}function o_(e){return e=(0,Do.normalizeId)(e),this.schemas[e]||this.refs[e]}function IT(){let e=this.opts.schemas;if(e)if(Array.isArray(e))this.addSchema(e);else for(let t in e)this.addSchema(e[t],t)}function RT(){for(let e in this.opts.formats){let t=this.opts.formats[e];t&&this.addFormat(e,t)}}function CT(e){if(Array.isArray(e)){this.addVocabulary(e);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let t in e){let r=e[t];r.keyword||(r.keyword=t),this.addKeyword(r)}}function NT(){let e={...this.opts};for(let t of PT)delete e[t];return e}var jT={log(){},warn(){},error(){}};function DT(e){if(e===!1)return jT;if(e===void 0)return console;if(e.log&&e.warn&&e.error)return e;throw new Error("logger must implement log, warn and error methods")}var MT=/^[a-z_$][a-z0-9_$:-]*$/i;function qT(e,t){let{RULES:r}=this;if((0,al.eachItem)(e,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!MT.test(n))throw new Error(`Keyword ${n} has invalid name`)}),!!t&&t.$data&&!("code"in t||"validate"in t))throw new Error('$data keyword must have "code" or "validate" function')}function sl(e,t,r){var n;let o=t?.post;if(r&&o)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:i}=this,s=o?i.post:i.rules.find(({type:c})=>c===r);if(s||(s={type:r,rules:[]},i.rules.push(s)),i.keywords[e]=!0,!t)return;let a={keyword:e,definition:{...t,type:(0,Ds.getJSONTypes)(t.type),schemaType:(0,Ds.getJSONTypes)(t.schemaType)}};t.before?FT.call(this,s,a,t.before):s.rules.push(a),i.all[e]=a,(n=t.implements)===null||n===void 0||n.forEach(c=>this.addKeyword(c))}function FT(e,t,r){let n=e.rules.findIndex(o=>o.keyword===r);n>=0?e.rules.splice(n,0,t):(e.rules.push(t),this.logger.warn(`rule ${r} is not defined`))}function ZT(e){let{metaSchema:t}=e;t!==void 0&&(e.$data&&this.opts.$data&&(t=a_(t)),e.validateSchema=this.compile(t,!0))}var LT={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function a_(e){return{anyOf:[e,LT]}}});var u_=x(cl=>{"use strict";Object.defineProperty(cl,"__esModule",{value:!0});var UT={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};cl.default=UT});var p_=x(Er=>{"use strict";Object.defineProperty(Er,"__esModule",{value:!0});Er.callRef=Er.getValidate=void 0;var VT=Ro(),l_=st(),Ke=j(),mn=Ft(),f_=Ts(),Ms=V(),HT={keyword:"$ref",schemaType:"string",code(e){let{gen:t,schema:r,it:n}=e,{baseId:o,schemaEnv:i,validateName:s,opts:a,self:c}=n,{root:u}=i;if((r==="#"||r==="#/")&&o===u.baseId)return f();let l=f_.resolveRef.call(c,u,o,r);if(l===void 0)throw new VT.default(n.opts.uriResolver,o,r);if(l instanceof f_.SchemaEnv)return d(l);return p(l);function f(){if(i===u)return qs(e,s,i,i.$async);let m=t.scopeValue("root",{ref:u});return qs(e,(0,Ke._)`${m}.validate`,u,u.$async)}function d(m){let h=d_(e,m);qs(e,h,m,m.$async)}function p(m){let h=t.scopeValue("schema",a.code.source===!0?{ref:m,code:(0,Ke.stringify)(m)}:{ref:m}),g=t.name("valid"),y=e.subschema({schema:m,dataTypes:[],schemaPath:Ke.nil,topSchemaRef:h,errSchemaPath:r},g);e.mergeEvaluated(y),e.ok(g)}}};function d_(e,t){let{gen:r}=e;return t.validate?r.scopeValue("validate",{ref:t.validate}):(0,Ke._)`${r.scopeValue("wrapper",{ref:t})}.validate`}Er.getValidate=d_;function qs(e,t,r,n){let{gen:o,it:i}=e,{allErrors:s,schemaEnv:a,opts:c}=i,u=c.passContext?mn.default.this:Ke.nil;n?l():f();function l(){if(!a.$async)throw new Error("async schema referenced by sync schema");let m=o.let("valid");o.try(()=>{o.code((0,Ke._)`await ${(0,l_.callValidateCode)(e,t,u)}`),p(t),s||o.assign(m,!0)},h=>{o.if((0,Ke._)`!(${h} instanceof ${i.ValidationError})`,()=>o.throw(h)),d(h),s||o.assign(m,!1)}),e.ok(m)}function f(){e.result((0,l_.callValidateCode)(e,t,u),()=>p(t),()=>d(t))}function d(m){let h=(0,Ke._)`${m}.errors`;o.assign(mn.default.vErrors,(0,Ke._)`${mn.default.vErrors} === null ? ${h} : ${mn.default.vErrors}.concat(${h})`),o.assign(mn.default.errors,(0,Ke._)`${mn.default.vErrors}.length`)}function p(m){var h;if(!i.opts.unevaluated)return;let g=(h=r?.validate)===null||h===void 0?void 0:h.evaluated;if(i.props!==!0)if(g&&!g.dynamicProps)g.props!==void 0&&(i.props=Ms.mergeEvaluated.props(o,g.props,i.props));else{let y=o.var("props",(0,Ke._)`${m}.evaluated.props`);i.props=Ms.mergeEvaluated.props(o,y,i.props,Ke.Name)}if(i.items!==!0)if(g&&!g.dynamicItems)g.items!==void 0&&(i.items=Ms.mergeEvaluated.items(o,g.items,i.items));else{let y=o.var("items",(0,Ke._)`${m}.evaluated.items`);i.items=Ms.mergeEvaluated.items(o,y,i.items,Ke.Name)}}}Er.callRef=qs;Er.default=HT});var m_=x(ul=>{"use strict";Object.defineProperty(ul,"__esModule",{value:!0});var BT=u_(),KT=p_(),JT=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",BT.default,KT.default];ul.default=JT});var h_=x(ll=>{"use strict";Object.defineProperty(ll,"__esModule",{value:!0});var Fs=j(),sr=Fs.operators,Zs={maximum:{okStr:"<=",ok:sr.LTE,fail:sr.GT},minimum:{okStr:">=",ok:sr.GTE,fail:sr.LT},exclusiveMaximum:{okStr:"<",ok:sr.LT,fail:sr.GTE},exclusiveMinimum:{okStr:">",ok:sr.GT,fail:sr.LTE}},WT={message:({keyword:e,schemaCode:t})=>(0,Fs.str)`must be ${Zs[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>(0,Fs._)`{comparison: ${Zs[e].okStr}, limit: ${t}}`},GT={keyword:Object.keys(Zs),type:"number",schemaType:"number",$data:!0,error:WT,code(e){let{keyword:t,data:r,schemaCode:n}=e;e.fail$data((0,Fs._)`${r} ${Zs[t].fail} ${n} || isNaN(${r})`)}};ll.default=GT});var g_=x(fl=>{"use strict";Object.defineProperty(fl,"__esModule",{value:!0});var qo=j(),YT={message:({schemaCode:e})=>(0,qo.str)`must be multiple of ${e}`,params:({schemaCode:e})=>(0,qo._)`{multipleOf: ${e}}`},XT={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:YT,code(e){let{gen:t,data:r,schemaCode:n,it:o}=e,i=o.opts.multipleOfPrecision,s=t.let("res"),a=i?(0,qo._)`Math.abs(Math.round(${s}) - ${s}) > 1e-${i}`:(0,qo._)`${s} !== parseInt(${s})`;e.fail$data((0,qo._)`(${n} === 0 || (${s} = ${r}/${n}, ${a}))`)}};fl.default=XT});var __=x(dl=>{"use strict";Object.defineProperty(dl,"__esModule",{value:!0});function y_(e){let t=e.length,r=0,n=0,o;for(;n=55296&&o<=56319&&n{"use strict";Object.defineProperty(pl,"__esModule",{value:!0});var Tr=j(),QT=V(),eO=__(),tO={message({keyword:e,schemaCode:t}){let r=e==="maxLength"?"more":"fewer";return(0,Tr.str)`must NOT have ${r} than ${t} characters`},params:({schemaCode:e})=>(0,Tr._)`{limit: ${e}}`},rO={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:tO,code(e){let{keyword:t,data:r,schemaCode:n,it:o}=e,i=t==="maxLength"?Tr.operators.GT:Tr.operators.LT,s=o.opts.unicode===!1?(0,Tr._)`${r}.length`:(0,Tr._)`${(0,QT.useFunc)(e.gen,eO.default)}(${r})`;e.fail$data((0,Tr._)`${s} ${i} ${n}`)}};pl.default=rO});var x_=x(ml=>{"use strict";Object.defineProperty(ml,"__esModule",{value:!0});var nO=st(),oO=V(),hn=j(),iO={message:({schemaCode:e})=>(0,hn.str)`must match pattern "${e}"`,params:({schemaCode:e})=>(0,hn._)`{pattern: ${e}}`},sO={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:iO,code(e){let{gen:t,data:r,$data:n,schema:o,schemaCode:i,it:s}=e,a=s.opts.unicodeRegExp?"u":"";if(n){let{regExp:c}=s.opts.code,u=c.code==="new RegExp"?(0,hn._)`new RegExp`:(0,oO.useFunc)(t,c),l=t.let("valid");t.try(()=>t.assign(l,(0,hn._)`${u}(${i}, ${a}).test(${r})`),()=>t.assign(l,!1)),e.fail$data((0,hn._)`!${l}`)}else{let c=(0,nO.usePattern)(e,o);e.fail$data((0,hn._)`!${c}.test(${r})`)}}};ml.default=sO});var v_=x(hl=>{"use strict";Object.defineProperty(hl,"__esModule",{value:!0});var Fo=j(),aO={message({keyword:e,schemaCode:t}){let r=e==="maxProperties"?"more":"fewer";return(0,Fo.str)`must NOT have ${r} than ${t} properties`},params:({schemaCode:e})=>(0,Fo._)`{limit: ${e}}`},cO={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:aO,code(e){let{keyword:t,data:r,schemaCode:n}=e,o=t==="maxProperties"?Fo.operators.GT:Fo.operators.LT;e.fail$data((0,Fo._)`Object.keys(${r}).length ${o} ${n}`)}};hl.default=cO});var b_=x(gl=>{"use strict";Object.defineProperty(gl,"__esModule",{value:!0});var Zo=st(),Lo=j(),uO=V(),lO={message:({params:{missingProperty:e}})=>(0,Lo.str)`must have required property '${e}'`,params:({params:{missingProperty:e}})=>(0,Lo._)`{missingProperty: ${e}}`},fO={keyword:"required",type:"object",schemaType:"array",$data:!0,error:lO,code(e){let{gen:t,schema:r,schemaCode:n,data:o,$data:i,it:s}=e,{opts:a}=s;if(!i&&r.length===0)return;let c=r.length>=a.loopRequired;if(s.allErrors?u():l(),a.strictRequired){let p=e.parentSchema.properties,{definedProperties:m}=e.it;for(let h of r)if(p?.[h]===void 0&&!m.has(h)){let g=s.schemaEnv.baseId+s.errSchemaPath,y=`required property "${h}" is not defined at "${g}" (strictRequired)`;(0,uO.checkStrictMode)(s,y,s.opts.strictRequired)}}function u(){if(c||i)e.block$data(Lo.nil,f);else for(let p of r)(0,Zo.checkReportMissingProp)(e,p)}function l(){let p=t.let("missing");if(c||i){let m=t.let("valid",!0);e.block$data(m,()=>d(p,m)),e.ok(m)}else t.if((0,Zo.checkMissingProp)(e,r,p)),(0,Zo.reportMissingProp)(e,p),t.else()}function f(){t.forOf("prop",n,p=>{e.setParams({missingProperty:p}),t.if((0,Zo.noPropertyInData)(t,o,p,a.ownProperties),()=>e.error())})}function d(p,m){e.setParams({missingProperty:p}),t.forOf(p,n,()=>{t.assign(m,(0,Zo.propertyInData)(t,o,p,a.ownProperties)),t.if((0,Lo.not)(m),()=>{e.error(),t.break()})},Lo.nil)}}};gl.default=fO});var S_=x(yl=>{"use strict";Object.defineProperty(yl,"__esModule",{value:!0});var Uo=j(),dO={message({keyword:e,schemaCode:t}){let r=e==="maxItems"?"more":"fewer";return(0,Uo.str)`must NOT have ${r} than ${t} items`},params:({schemaCode:e})=>(0,Uo._)`{limit: ${e}}`},pO={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:dO,code(e){let{keyword:t,data:r,schemaCode:n}=e,o=t==="maxItems"?Uo.operators.GT:Uo.operators.LT;e.fail$data((0,Uo._)`${r}.length ${o} ${n}`)}};yl.default=pO});var Ls=x(_l=>{"use strict";Object.defineProperty(_l,"__esModule",{value:!0});var $_=ju();$_.code='require("ajv/dist/runtime/equal").default';_l.default=$_});var k_=x(xl=>{"use strict";Object.defineProperty(xl,"__esModule",{value:!0});var wl=Eo(),Te=j(),mO=V(),hO=Ls(),gO={message:({params:{i:e,j:t}})=>(0,Te.str)`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,params:({params:{i:e,j:t}})=>(0,Te._)`{i: ${e}, j: ${t}}`},yO={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:gO,code(e){let{gen:t,data:r,$data:n,schema:o,parentSchema:i,schemaCode:s,it:a}=e;if(!n&&!o)return;let c=t.let("valid"),u=i.items?(0,wl.getSchemaTypes)(i.items):[];e.block$data(c,l,(0,Te._)`${s} === false`),e.ok(c);function l(){let m=t.let("i",(0,Te._)`${r}.length`),h=t.let("j");e.setParams({i:m,j:h}),t.assign(c,!0),t.if((0,Te._)`${m} > 1`,()=>(f()?d:p)(m,h))}function f(){return u.length>0&&!u.some(m=>m==="object"||m==="array")}function d(m,h){let g=t.name("item"),y=(0,wl.checkDataTypes)(u,g,a.opts.strictNumbers,wl.DataType.Wrong),v=t.const("indices",(0,Te._)`{}`);t.for((0,Te._)`;${m}--;`,()=>{t.let(g,(0,Te._)`${r}[${m}]`),t.if(y,(0,Te._)`continue`),u.length>1&&t.if((0,Te._)`typeof ${g} == "string"`,(0,Te._)`${g} += "_"`),t.if((0,Te._)`typeof ${v}[${g}] == "number"`,()=>{t.assign(h,(0,Te._)`${v}[${g}]`),e.error(),t.assign(c,!1).break()}).code((0,Te._)`${v}[${g}] = ${m}`)})}function p(m,h){let g=(0,mO.useFunc)(t,hO.default),y=t.name("outer");t.label(y).for((0,Te._)`;${m}--;`,()=>t.for((0,Te._)`${h} = ${m}; ${h}--;`,()=>t.if((0,Te._)`${g}(${r}[${m}], ${r}[${h}])`,()=>{e.error(),t.assign(c,!1).break(y)})))}}};xl.default=yO});var z_=x(bl=>{"use strict";Object.defineProperty(bl,"__esModule",{value:!0});var vl=j(),_O=V(),wO=Ls(),xO={message:"must be equal to constant",params:({schemaCode:e})=>(0,vl._)`{allowedValue: ${e}}`},vO={keyword:"const",$data:!0,error:xO,code(e){let{gen:t,data:r,$data:n,schemaCode:o,schema:i}=e;n||i&&typeof i=="object"?e.fail$data((0,vl._)`!${(0,_O.useFunc)(t,wO.default)}(${r}, ${o})`):e.fail((0,vl._)`${i} !== ${r}`)}};bl.default=vO});var P_=x(Sl=>{"use strict";Object.defineProperty(Sl,"__esModule",{value:!0});var Vo=j(),bO=V(),SO=Ls(),$O={message:"must be equal to one of the allowed values",params:({schemaCode:e})=>(0,Vo._)`{allowedValues: ${e}}`},kO={keyword:"enum",schemaType:"array",$data:!0,error:$O,code(e){let{gen:t,data:r,$data:n,schema:o,schemaCode:i,it:s}=e;if(!n&&o.length===0)throw new Error("enum must have non-empty array");let a=o.length>=s.opts.loopEnum,c,u=()=>c??(c=(0,bO.useFunc)(t,SO.default)),l;if(a||n)l=t.let("valid"),e.block$data(l,f);else{if(!Array.isArray(o))throw new Error("ajv implementation error");let p=t.const("vSchema",i);l=(0,Vo.or)(...o.map((m,h)=>d(p,h)))}e.pass(l);function f(){t.assign(l,!1),t.forOf("v",i,p=>t.if((0,Vo._)`${u()}(${r}, ${p})`,()=>t.assign(l,!0).break()))}function d(p,m){let h=o[m];return typeof h=="object"&&h!==null?(0,Vo._)`${u()}(${r}, ${p}[${m}])`:(0,Vo._)`${r} === ${h}`}}};Sl.default=kO});var E_=x($l=>{"use strict";Object.defineProperty($l,"__esModule",{value:!0});var zO=h_(),PO=g_(),EO=w_(),TO=x_(),OO=v_(),AO=b_(),IO=S_(),RO=k_(),CO=z_(),NO=P_(),jO=[zO.default,PO.default,EO.default,TO.default,OO.default,AO.default,IO.default,RO.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},CO.default,NO.default];$l.default=jO});var zl=x(Ho=>{"use strict";Object.defineProperty(Ho,"__esModule",{value:!0});Ho.validateAdditionalItems=void 0;var Or=j(),kl=V(),DO={message:({params:{len:e}})=>(0,Or.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,Or._)`{limit: ${e}}`},MO={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:DO,code(e){let{parentSchema:t,it:r}=e,{items:n}=t;if(!Array.isArray(n)){(0,kl.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}T_(e,n)}};function T_(e,t){let{gen:r,schema:n,data:o,keyword:i,it:s}=e;s.items=!0;let a=r.const("len",(0,Or._)`${o}.length`);if(n===!1)e.setParams({len:t.length}),e.pass((0,Or._)`${a} <= ${t.length}`);else if(typeof n=="object"&&!(0,kl.alwaysValidSchema)(s,n)){let u=r.var("valid",(0,Or._)`${a} <= ${t.length}`);r.if((0,Or.not)(u),()=>c(u)),e.ok(u)}function c(u){r.forRange("i",t.length,a,l=>{e.subschema({keyword:i,dataProp:l,dataPropType:kl.Type.Num},u),s.allErrors||r.if((0,Or.not)(u),()=>r.break())})}}Ho.validateAdditionalItems=T_;Ho.default=MO});var Pl=x(Bo=>{"use strict";Object.defineProperty(Bo,"__esModule",{value:!0});Bo.validateTuple=void 0;var O_=j(),Us=V(),qO=st(),FO={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(e){let{schema:t,it:r}=e;if(Array.isArray(t))return A_(e,"additionalItems",t);r.items=!0,!(0,Us.alwaysValidSchema)(r,t)&&e.ok((0,qO.validateArray)(e))}};function A_(e,t,r=e.schema){let{gen:n,parentSchema:o,data:i,keyword:s,it:a}=e;l(o),a.opts.unevaluated&&r.length&&a.items!==!0&&(a.items=Us.mergeEvaluated.items(n,r.length,a.items));let c=n.name("valid"),u=n.const("len",(0,O_._)`${i}.length`);r.forEach((f,d)=>{(0,Us.alwaysValidSchema)(a,f)||(n.if((0,O_._)`${u} > ${d}`,()=>e.subschema({keyword:s,schemaProp:d,dataProp:d},c)),e.ok(c))});function l(f){let{opts:d,errSchemaPath:p}=a,m=r.length,h=m===f.minItems&&(m===f.maxItems||f[t]===!1);if(d.strictTuples&&!h){let g=`"${s}" is ${m}-tuple, but minItems or maxItems/${t} are not specified or different at path "${p}"`;(0,Us.checkStrictMode)(a,g,d.strictTuples)}}}Bo.validateTuple=A_;Bo.default=FO});var I_=x(El=>{"use strict";Object.defineProperty(El,"__esModule",{value:!0});var ZO=Pl(),LO={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:e=>(0,ZO.validateTuple)(e,"items")};El.default=LO});var C_=x(Tl=>{"use strict";Object.defineProperty(Tl,"__esModule",{value:!0});var R_=j(),UO=V(),VO=st(),HO=zl(),BO={message:({params:{len:e}})=>(0,R_.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,R_._)`{limit: ${e}}`},KO={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:BO,code(e){let{schema:t,parentSchema:r,it:n}=e,{prefixItems:o}=r;n.items=!0,!(0,UO.alwaysValidSchema)(n,t)&&(o?(0,HO.validateAdditionalItems)(e,o):e.ok((0,VO.validateArray)(e)))}};Tl.default=KO});var N_=x(Ol=>{"use strict";Object.defineProperty(Ol,"__esModule",{value:!0});var ct=j(),Vs=V(),JO={message:({params:{min:e,max:t}})=>t===void 0?(0,ct.str)`must contain at least ${e} valid item(s)`:(0,ct.str)`must contain at least ${e} and no more than ${t} valid item(s)`,params:({params:{min:e,max:t}})=>t===void 0?(0,ct._)`{minContains: ${e}}`:(0,ct._)`{minContains: ${e}, maxContains: ${t}}`},WO={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:JO,code(e){let{gen:t,schema:r,parentSchema:n,data:o,it:i}=e,s,a,{minContains:c,maxContains:u}=n;i.opts.next?(s=c===void 0?1:c,a=u):s=1;let l=t.const("len",(0,ct._)`${o}.length`);if(e.setParams({min:s,max:a}),a===void 0&&s===0){(0,Vs.checkStrictMode)(i,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&s>a){(0,Vs.checkStrictMode)(i,'"minContains" > "maxContains" is always invalid'),e.fail();return}if((0,Vs.alwaysValidSchema)(i,r)){let h=(0,ct._)`${l} >= ${s}`;a!==void 0&&(h=(0,ct._)`${h} && ${l} <= ${a}`),e.pass(h);return}i.items=!0;let f=t.name("valid");a===void 0&&s===1?p(f,()=>t.if(f,()=>t.break())):s===0?(t.let(f,!0),a!==void 0&&t.if((0,ct._)`${o}.length > 0`,d)):(t.let(f,!1),d()),e.result(f,()=>e.reset());function d(){let h=t.name("_valid"),g=t.let("count",0);p(h,()=>t.if(h,()=>m(g)))}function p(h,g){t.forRange("i",0,l,y=>{e.subschema({keyword:"contains",dataProp:y,dataPropType:Vs.Type.Num,compositeRule:!0},h),g()})}function m(h){t.code((0,ct._)`${h}++`),a===void 0?t.if((0,ct._)`${h} >= ${s}`,()=>t.assign(f,!0).break()):(t.if((0,ct._)`${h} > ${a}`,()=>t.assign(f,!1).break()),s===1?t.assign(f,!0):t.if((0,ct._)`${h} >= ${s}`,()=>t.assign(f,!0)))}}};Ol.default=WO});var M_=x(St=>{"use strict";Object.defineProperty(St,"__esModule",{value:!0});St.validateSchemaDeps=St.validatePropertyDeps=St.error=void 0;var Al=j(),GO=V(),Ko=st();St.error={message:({params:{property:e,depsCount:t,deps:r}})=>{let n=t===1?"property":"properties";return(0,Al.str)`must have ${n} ${r} when property ${e} is present`},params:({params:{property:e,depsCount:t,deps:r,missingProperty:n}})=>(0,Al._)`{property: ${e}, + missingProperty: ${n}, + depsCount: ${t}, + deps: ${r}}`};var YO={keyword:"dependencies",type:"object",schemaType:"object",error:St.error,code(e){let[t,r]=XO(e);j_(e,t),D_(e,r)}};function XO({schema:e}){let t={},r={};for(let n in e){if(n==="__proto__")continue;let o=Array.isArray(e[n])?t:r;o[n]=e[n]}return[t,r]}function j_(e,t=e.schema){let{gen:r,data:n,it:o}=e;if(Object.keys(t).length===0)return;let i=r.let("missing");for(let s in t){let a=t[s];if(a.length===0)continue;let c=(0,Ko.propertyInData)(r,n,s,o.opts.ownProperties);e.setParams({property:s,depsCount:a.length,deps:a.join(", ")}),o.allErrors?r.if(c,()=>{for(let u of a)(0,Ko.checkReportMissingProp)(e,u)}):(r.if((0,Al._)`${c} && (${(0,Ko.checkMissingProp)(e,a,i)})`),(0,Ko.reportMissingProp)(e,i),r.else())}}St.validatePropertyDeps=j_;function D_(e,t=e.schema){let{gen:r,data:n,keyword:o,it:i}=e,s=r.name("valid");for(let a in t)(0,GO.alwaysValidSchema)(i,t[a])||(r.if((0,Ko.propertyInData)(r,n,a,i.opts.ownProperties),()=>{let c=e.subschema({keyword:o,schemaProp:a},s);e.mergeValidEvaluated(c,s)},()=>r.var(s,!0)),e.ok(s))}St.validateSchemaDeps=D_;St.default=YO});var F_=x(Il=>{"use strict";Object.defineProperty(Il,"__esModule",{value:!0});var q_=j(),QO=V(),eA={message:"property name must be valid",params:({params:e})=>(0,q_._)`{propertyName: ${e.propertyName}}`},tA={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:eA,code(e){let{gen:t,schema:r,data:n,it:o}=e;if((0,QO.alwaysValidSchema)(o,r))return;let i=t.name("valid");t.forIn("key",n,s=>{e.setParams({propertyName:s}),e.subschema({keyword:"propertyNames",data:s,dataTypes:["string"],propertyName:s,compositeRule:!0},i),t.if((0,q_.not)(i),()=>{e.error(!0),o.allErrors||t.break()})}),e.ok(i)}};Il.default=tA});var Cl=x(Rl=>{"use strict";Object.defineProperty(Rl,"__esModule",{value:!0});var Hs=st(),wt=j(),rA=Ft(),Bs=V(),nA={message:"must NOT have additional properties",params:({params:e})=>(0,wt._)`{additionalProperty: ${e.additionalProperty}}`},oA={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:nA,code(e){let{gen:t,schema:r,parentSchema:n,data:o,errsCount:i,it:s}=e;if(!i)throw new Error("ajv implementation error");let{allErrors:a,opts:c}=s;if(s.props=!0,c.removeAdditional!=="all"&&(0,Bs.alwaysValidSchema)(s,r))return;let u=(0,Hs.allSchemaProperties)(n.properties),l=(0,Hs.allSchemaProperties)(n.patternProperties);f(),e.ok((0,wt._)`${i} === ${rA.default.errors}`);function f(){t.forIn("key",o,g=>{!u.length&&!l.length?m(g):t.if(d(g),()=>m(g))})}function d(g){let y;if(u.length>8){let v=(0,Bs.schemaRefOrVal)(s,n.properties,"properties");y=(0,Hs.isOwnProperty)(t,v,g)}else u.length?y=(0,wt.or)(...u.map(v=>(0,wt._)`${g} === ${v}`)):y=wt.nil;return l.length&&(y=(0,wt.or)(y,...l.map(v=>(0,wt._)`${(0,Hs.usePattern)(e,v)}.test(${g})`))),(0,wt.not)(y)}function p(g){t.code((0,wt._)`delete ${o}[${g}]`)}function m(g){if(c.removeAdditional==="all"||c.removeAdditional&&r===!1){p(g);return}if(r===!1){e.setParams({additionalProperty:g}),e.error(),a||t.break();return}if(typeof r=="object"&&!(0,Bs.alwaysValidSchema)(s,r)){let y=t.name("valid");c.removeAdditional==="failing"?(h(g,y,!1),t.if((0,wt.not)(y),()=>{e.reset(),p(g)})):(h(g,y),a||t.if((0,wt.not)(y),()=>t.break()))}}function h(g,y,v){let S={keyword:"additionalProperties",dataProp:g,dataPropType:Bs.Type.Str};v===!1&&Object.assign(S,{compositeRule:!0,createErrors:!1,allErrors:!1}),e.subschema(S,y)}}};Rl.default=oA});var U_=x(jl=>{"use strict";Object.defineProperty(jl,"__esModule",{value:!0});var iA=Io(),Z_=st(),Nl=V(),L_=Cl(),sA={keyword:"properties",type:"object",schemaType:"object",code(e){let{gen:t,schema:r,parentSchema:n,data:o,it:i}=e;i.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&L_.default.code(new iA.KeywordCxt(i,L_.default,"additionalProperties"));let s=(0,Z_.allSchemaProperties)(r);for(let f of s)i.definedProperties.add(f);i.opts.unevaluated&&s.length&&i.props!==!0&&(i.props=Nl.mergeEvaluated.props(t,(0,Nl.toHash)(s),i.props));let a=s.filter(f=>!(0,Nl.alwaysValidSchema)(i,r[f]));if(a.length===0)return;let c=t.name("valid");for(let f of a)u(f)?l(f):(t.if((0,Z_.propertyInData)(t,o,f,i.opts.ownProperties)),l(f),i.allErrors||t.else().var(c,!0),t.endIf()),e.it.definedProperties.add(f),e.ok(c);function u(f){return i.opts.useDefaults&&!i.compositeRule&&r[f].default!==void 0}function l(f){e.subschema({keyword:"properties",schemaProp:f,dataProp:f},c)}}};jl.default=sA});var K_=x(Dl=>{"use strict";Object.defineProperty(Dl,"__esModule",{value:!0});var V_=st(),Ks=j(),H_=V(),B_=V(),aA={keyword:"patternProperties",type:"object",schemaType:"object",code(e){let{gen:t,schema:r,data:n,parentSchema:o,it:i}=e,{opts:s}=i,a=(0,V_.allSchemaProperties)(r),c=a.filter(h=>(0,H_.alwaysValidSchema)(i,r[h]));if(a.length===0||c.length===a.length&&(!i.opts.unevaluated||i.props===!0))return;let u=s.strictSchema&&!s.allowMatchingProperties&&o.properties,l=t.name("valid");i.props!==!0&&!(i.props instanceof Ks.Name)&&(i.props=(0,B_.evaluatedPropsToName)(t,i.props));let{props:f}=i;d();function d(){for(let h of a)u&&p(h),i.allErrors?m(h):(t.var(l,!0),m(h),t.if(l))}function p(h){for(let g in u)new RegExp(h).test(g)&&(0,H_.checkStrictMode)(i,`property ${g} matches pattern ${h} (use allowMatchingProperties)`)}function m(h){t.forIn("key",n,g=>{t.if((0,Ks._)`${(0,V_.usePattern)(e,h)}.test(${g})`,()=>{let y=c.includes(h);y||e.subschema({keyword:"patternProperties",schemaProp:h,dataProp:g,dataPropType:B_.Type.Str},l),i.opts.unevaluated&&f!==!0?t.assign((0,Ks._)`${f}[${g}]`,!0):!y&&!i.allErrors&&t.if((0,Ks.not)(l),()=>t.break())})})}}};Dl.default=aA});var J_=x(Ml=>{"use strict";Object.defineProperty(Ml,"__esModule",{value:!0});var cA=V(),uA={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(e){let{gen:t,schema:r,it:n}=e;if((0,cA.alwaysValidSchema)(n,r)){e.fail();return}let o=t.name("valid");e.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},o),e.failResult(o,()=>e.reset(),()=>e.error())},error:{message:"must NOT be valid"}};Ml.default=uA});var W_=x(ql=>{"use strict";Object.defineProperty(ql,"__esModule",{value:!0});var lA=st(),fA={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:lA.validateUnion,error:{message:"must match a schema in anyOf"}};ql.default=fA});var G_=x(Fl=>{"use strict";Object.defineProperty(Fl,"__esModule",{value:!0});var Js=j(),dA=V(),pA={message:"must match exactly one schema in oneOf",params:({params:e})=>(0,Js._)`{passingSchemas: ${e.passing}}`},mA={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:pA,code(e){let{gen:t,schema:r,parentSchema:n,it:o}=e;if(!Array.isArray(r))throw new Error("ajv implementation error");if(o.opts.discriminator&&n.discriminator)return;let i=r,s=t.let("valid",!1),a=t.let("passing",null),c=t.name("_valid");e.setParams({passing:a}),t.block(u),e.result(s,()=>e.reset(),()=>e.error(!0));function u(){i.forEach((l,f)=>{let d;(0,dA.alwaysValidSchema)(o,l)?t.var(c,!0):d=e.subschema({keyword:"oneOf",schemaProp:f,compositeRule:!0},c),f>0&&t.if((0,Js._)`${c} && ${s}`).assign(s,!1).assign(a,(0,Js._)`[${a}, ${f}]`).else(),t.if(c,()=>{t.assign(s,!0),t.assign(a,f),d&&e.mergeEvaluated(d,Js.Name)})})}}};Fl.default=mA});var Y_=x(Zl=>{"use strict";Object.defineProperty(Zl,"__esModule",{value:!0});var hA=V(),gA={keyword:"allOf",schemaType:"array",code(e){let{gen:t,schema:r,it:n}=e;if(!Array.isArray(r))throw new Error("ajv implementation error");let o=t.name("valid");r.forEach((i,s)=>{if((0,hA.alwaysValidSchema)(n,i))return;let a=e.subschema({keyword:"allOf",schemaProp:s},o);e.ok(o),e.mergeEvaluated(a)})}};Zl.default=gA});var e0=x(Ll=>{"use strict";Object.defineProperty(Ll,"__esModule",{value:!0});var Ws=j(),Q_=V(),yA={message:({params:e})=>(0,Ws.str)`must match "${e.ifClause}" schema`,params:({params:e})=>(0,Ws._)`{failingKeyword: ${e.ifClause}}`},_A={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:yA,code(e){let{gen:t,parentSchema:r,it:n}=e;r.then===void 0&&r.else===void 0&&(0,Q_.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let o=X_(n,"then"),i=X_(n,"else");if(!o&&!i)return;let s=t.let("valid",!0),a=t.name("_valid");if(c(),e.reset(),o&&i){let l=t.let("ifClause");e.setParams({ifClause:l}),t.if(a,u("then",l),u("else",l))}else o?t.if(a,u("then")):t.if((0,Ws.not)(a),u("else"));e.pass(s,()=>e.error(!0));function c(){let l=e.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);e.mergeEvaluated(l)}function u(l,f){return()=>{let d=e.subschema({keyword:l},a);t.assign(s,a),e.mergeValidEvaluated(d,s),f?t.assign(f,(0,Ws._)`${l}`):e.setParams({ifClause:l})}}}};function X_(e,t){let r=e.schema[t];return r!==void 0&&!(0,Q_.alwaysValidSchema)(e,r)}Ll.default=_A});var t0=x(Ul=>{"use strict";Object.defineProperty(Ul,"__esModule",{value:!0});var wA=V(),xA={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:e,parentSchema:t,it:r}){t.if===void 0&&(0,wA.checkStrictMode)(r,`"${e}" without "if" is ignored`)}};Ul.default=xA});var r0=x(Vl=>{"use strict";Object.defineProperty(Vl,"__esModule",{value:!0});var vA=zl(),bA=I_(),SA=Pl(),$A=C_(),kA=N_(),zA=M_(),PA=F_(),EA=Cl(),TA=U_(),OA=K_(),AA=J_(),IA=W_(),RA=G_(),CA=Y_(),NA=e0(),jA=t0();function DA(e=!1){let t=[AA.default,IA.default,RA.default,CA.default,NA.default,jA.default,PA.default,EA.default,zA.default,TA.default,OA.default];return e?t.push(bA.default,$A.default):t.push(vA.default,SA.default),t.push(kA.default),t}Vl.default=DA});var n0=x(Hl=>{"use strict";Object.defineProperty(Hl,"__esModule",{value:!0});var pe=j(),MA={message:({schemaCode:e})=>(0,pe.str)`must match format "${e}"`,params:({schemaCode:e})=>(0,pe._)`{format: ${e}}`},qA={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:MA,code(e,t){let{gen:r,data:n,$data:o,schema:i,schemaCode:s,it:a}=e,{opts:c,errSchemaPath:u,schemaEnv:l,self:f}=a;if(!c.validateFormats)return;o?d():p();function d(){let m=r.scopeValue("formats",{ref:f.formats,code:c.code.formats}),h=r.const("fDef",(0,pe._)`${m}[${s}]`),g=r.let("fType"),y=r.let("format");r.if((0,pe._)`typeof ${h} == "object" && !(${h} instanceof RegExp)`,()=>r.assign(g,(0,pe._)`${h}.type || "string"`).assign(y,(0,pe._)`${h}.validate`),()=>r.assign(g,(0,pe._)`"string"`).assign(y,h)),e.fail$data((0,pe.or)(v(),S()));function v(){return c.strictSchema===!1?pe.nil:(0,pe._)`${s} && !${y}`}function S(){let k=l.$async?(0,pe._)`(${h}.async ? await ${y}(${n}) : ${y}(${n}))`:(0,pe._)`${y}(${n})`,$=(0,pe._)`(typeof ${y} == "function" ? ${k} : ${y}.test(${n}))`;return(0,pe._)`${y} && ${y} !== true && ${g} === ${t} && !${$}`}}function p(){let m=f.formats[i];if(!m){v();return}if(m===!0)return;let[h,g,y]=S(m);h===t&&e.pass(k());function v(){if(c.strictSchema===!1){f.logger.warn($());return}throw new Error($());function $(){return`unknown format "${i}" ignored in schema at path "${u}"`}}function S($){let b=$ instanceof RegExp?(0,pe.regexpCode)($):c.code.formats?(0,pe._)`${c.code.formats}${(0,pe.getProperty)(i)}`:void 0,T=r.scopeValue("formats",{key:i,ref:$,code:b});return typeof $=="object"&&!($ instanceof RegExp)?[$.type||"string",$.validate,(0,pe._)`${T}.validate`]:["string",$,T]}function k(){if(typeof m=="object"&&!(m instanceof RegExp)&&m.async){if(!l.$async)throw new Error("async format in sync schema");return(0,pe._)`await ${y}(${n})`}return typeof g=="function"?(0,pe._)`${y}(${n})`:(0,pe._)`${y}.test(${n})`}}}};Hl.default=qA});var o0=x(Bl=>{"use strict";Object.defineProperty(Bl,"__esModule",{value:!0});var FA=n0(),ZA=[FA.default];Bl.default=ZA});var i0=x(gn=>{"use strict";Object.defineProperty(gn,"__esModule",{value:!0});gn.contentVocabulary=gn.metadataVocabulary=void 0;gn.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];gn.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var a0=x(Kl=>{"use strict";Object.defineProperty(Kl,"__esModule",{value:!0});var LA=m_(),UA=E_(),VA=r0(),HA=o0(),s0=i0(),BA=[LA.default,UA.default,(0,VA.default)(),HA.default,s0.metadataVocabulary,s0.contentVocabulary];Kl.default=BA});var u0=x(Gs=>{"use strict";Object.defineProperty(Gs,"__esModule",{value:!0});Gs.DiscrError=void 0;var c0;(function(e){e.Tag="tag",e.Mapping="mapping"})(c0||(Gs.DiscrError=c0={}))});var f0=x(Wl=>{"use strict";Object.defineProperty(Wl,"__esModule",{value:!0});var yn=j(),Jl=u0(),l0=Ts(),KA=Ro(),JA=V(),WA={message:({params:{discrError:e,tagName:t}})=>e===Jl.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:t,tagName:r}})=>(0,yn._)`{error: ${e}, tag: ${r}, tagValue: ${t}}`},GA={keyword:"discriminator",type:"object",schemaType:"object",error:WA,code(e){let{gen:t,data:r,schema:n,parentSchema:o,it:i}=e,{oneOf:s}=o;if(!i.opts.discriminator)throw new Error("discriminator: requires discriminator option");let a=n.propertyName;if(typeof a!="string")throw new Error("discriminator: requires propertyName");if(n.mapping)throw new Error("discriminator: mapping is not supported");if(!s)throw new Error("discriminator: requires oneOf keyword");let c=t.let("valid",!1),u=t.const("tag",(0,yn._)`${r}${(0,yn.getProperty)(a)}`);t.if((0,yn._)`typeof ${u} == "string"`,()=>l(),()=>e.error(!1,{discrError:Jl.DiscrError.Tag,tag:u,tagName:a})),e.ok(c);function l(){let p=d();t.if(!1);for(let m in p)t.elseIf((0,yn._)`${u} === ${m}`),t.assign(c,f(p[m]));t.else(),e.error(!1,{discrError:Jl.DiscrError.Mapping,tag:u,tagName:a}),t.endIf()}function f(p){let m=t.name("valid"),h=e.subschema({keyword:"oneOf",schemaProp:p},m);return e.mergeEvaluated(h,yn.Name),m}function d(){var p;let m={},h=y(o),g=!0;for(let k=0;k{YA.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0}});var Yl=x((oe,Gl)=>{"use strict";Object.defineProperty(oe,"__esModule",{value:!0});oe.MissingRefError=oe.ValidationError=oe.CodeGen=oe.Name=oe.nil=oe.stringify=oe.str=oe._=oe.KeywordCxt=oe.Ajv=void 0;var XA=c_(),QA=a0(),e1=f0(),p0=d0(),t1=["/properties"],Ys="http://json-schema.org/draft-07/schema",_n=class extends XA.default{_addVocabularies(){super._addVocabularies(),QA.default.forEach(t=>this.addVocabulary(t)),this.opts.discriminator&&this.addKeyword(e1.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let t=this.opts.$data?this.$dataMetaSchema(p0,t1):p0;this.addMetaSchema(t,Ys,!1),this.refs["http://json-schema.org/schema"]=Ys}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Ys)?Ys:void 0)}};oe.Ajv=_n;Gl.exports=oe=_n;Gl.exports.Ajv=_n;Object.defineProperty(oe,"__esModule",{value:!0});oe.default=_n;var r1=Io();Object.defineProperty(oe,"KeywordCxt",{enumerable:!0,get:function(){return r1.KeywordCxt}});var wn=j();Object.defineProperty(oe,"_",{enumerable:!0,get:function(){return wn._}});Object.defineProperty(oe,"str",{enumerable:!0,get:function(){return wn.str}});Object.defineProperty(oe,"stringify",{enumerable:!0,get:function(){return wn.stringify}});Object.defineProperty(oe,"nil",{enumerable:!0,get:function(){return wn.nil}});Object.defineProperty(oe,"Name",{enumerable:!0,get:function(){return wn.Name}});Object.defineProperty(oe,"CodeGen",{enumerable:!0,get:function(){return wn.CodeGen}});var n1=Ps();Object.defineProperty(oe,"ValidationError",{enumerable:!0,get:function(){return n1.default}});var o1=Ro();Object.defineProperty(oe,"MissingRefError",{enumerable:!0,get:function(){return o1.default}})});var v0=x(kt=>{"use strict";Object.defineProperty(kt,"__esModule",{value:!0});kt.formatNames=kt.fastFormats=kt.fullFormats=void 0;function $t(e,t){return{validate:e,compare:t}}kt.fullFormats={date:$t(y0,tf),time:$t(Ql(!0),rf),"date-time":$t(m0(!0),w0),"iso-time":$t(Ql(),_0),"iso-date-time":$t(m0(),x0),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:l1,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:y1,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:f1,int32:{type:"number",validate:m1},int64:{type:"number",validate:h1},float:{type:"number",validate:g0},double:{type:"number",validate:g0},password:!0,binary:!0};kt.fastFormats={...kt.fullFormats,date:$t(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,tf),time:$t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,rf),"date-time":$t(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,w0),"iso-time":$t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,_0),"iso-date-time":$t(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,x0),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i};kt.formatNames=Object.keys(kt.fullFormats);function i1(e){return e%4===0&&(e%100!==0||e%400===0)}var s1=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,a1=[0,31,28,31,30,31,30,31,31,30,31,30,31];function y0(e){let t=s1.exec(e);if(!t)return!1;let r=+t[1],n=+t[2],o=+t[3];return n>=1&&n<=12&&o>=1&&o<=(n===2&&i1(r)?29:a1[n])}function tf(e,t){if(e&&t)return e>t?1:e23||l>59||e&&!a)return!1;if(o<=23&&i<=59&&s<60)return!0;let f=i-l*c,d=o-u*c-(f<0?1:0);return(d===23||d===-1)&&(f===59||f===-1)&&s<61}}function rf(e,t){if(!(e&&t))return;let r=new Date("2020-01-01T"+e).valueOf(),n=new Date("2020-01-01T"+t).valueOf();if(r&&n)return r-n}function _0(e,t){if(!(e&&t))return;let r=Xl.exec(e),n=Xl.exec(t);if(r&&n)return e=r[1]+r[2]+r[3],t=n[1]+n[2]+n[3],e>t?1:e=d1}function h1(e){return Number.isInteger(e)}function g0(){return!0}var g1=/[^\\]\\Z/;function y1(e){if(g1.test(e))return!1;try{return new RegExp(e),!0}catch{return!1}}});var b0=x(xn=>{"use strict";Object.defineProperty(xn,"__esModule",{value:!0});xn.formatLimitDefinition=void 0;var _1=Yl(),xt=j(),ar=xt.operators,Xs={formatMaximum:{okStr:"<=",ok:ar.LTE,fail:ar.GT},formatMinimum:{okStr:">=",ok:ar.GTE,fail:ar.LT},formatExclusiveMaximum:{okStr:"<",ok:ar.LT,fail:ar.GTE},formatExclusiveMinimum:{okStr:">",ok:ar.GT,fail:ar.LTE}},w1={message:({keyword:e,schemaCode:t})=>(0,xt.str)`should be ${Xs[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>(0,xt._)`{comparison: ${Xs[e].okStr}, limit: ${t}}`};xn.formatLimitDefinition={keyword:Object.keys(Xs),type:"string",schemaType:"string",$data:!0,error:w1,code(e){let{gen:t,data:r,schemaCode:n,keyword:o,it:i}=e,{opts:s,self:a}=i;if(!s.validateFormats)return;let c=new _1.KeywordCxt(i,a.RULES.all.format.definition,"format");c.$data?u():l();function u(){let d=t.scopeValue("formats",{ref:a.formats,code:s.code.formats}),p=t.const("fmt",(0,xt._)`${d}[${c.schemaCode}]`);e.fail$data((0,xt.or)((0,xt._)`typeof ${p} != "object"`,(0,xt._)`${p} instanceof RegExp`,(0,xt._)`typeof ${p}.compare != "function"`,f(p)))}function l(){let d=c.schema,p=a.formats[d];if(!p||p===!0)return;if(typeof p!="object"||p instanceof RegExp||typeof p.compare!="function")throw new Error(`"${o}": format "${d}" does not define "compare" function`);let m=t.scopeValue("formats",{key:d,ref:p,code:s.code.formats?(0,xt._)`${s.code.formats}${(0,xt.getProperty)(d)}`:void 0});e.fail$data(f(m))}function f(d){return(0,xt._)`${d}.compare(${r}, ${n}) ${Xs[o].fail} 0`}},dependencies:["format"]};var x1=e=>(e.addKeyword(xn.formatLimitDefinition),e);xn.default=x1});var z0=x((Jo,k0)=>{"use strict";Object.defineProperty(Jo,"__esModule",{value:!0});var vn=v0(),v1=b0(),nf=j(),S0=new nf.Name("fullFormats"),b1=new nf.Name("fastFormats"),of=(e,t={keywords:!0})=>{if(Array.isArray(t))return $0(e,t,vn.fullFormats,S0),e;let[r,n]=t.mode==="fast"?[vn.fastFormats,b1]:[vn.fullFormats,S0],o=t.formats||vn.formatNames;return $0(e,o,r,n),t.keywords&&(0,v1.default)(e),e};of.get=(e,t="full")=>{let n=(t==="fast"?vn.fastFormats:vn.fullFormats)[e];if(!n)throw new Error(`Unknown format "${e}"`);return n};function $0(e,t,r,n){var o,i;(o=(i=e.opts.code).formats)!==null&&o!==void 0||(i.formats=(0,nf._)`require("ajv-formats/dist/formats").${n}`);for(let s of t)e.addFormat(s,r[s])}k0.exports=Jo=of;Object.defineProperty(Jo,"__esModule",{value:!0});Jo.default=of});var Wo=x((vL,R0)=>{var $1=Object.prototype.toString;R0.exports=function(t){if(t===void 0)return"undefined";if(t===null)return"null";var r=typeof t;if(r==="boolean")return"boolean";if(r==="string")return"string";if(r==="number")return"number";if(r==="symbol")return"symbol";if(r==="function")return T1(t)?"generatorfunction":"function";if(k1(t))return"array";if(I1(t))return"buffer";if(A1(t))return"arguments";if(P1(t))return"date";if(z1(t))return"error";if(E1(t))return"regexp";switch(I0(t)){case"Symbol":return"symbol";case"Promise":return"promise";case"WeakMap":return"weakmap";case"WeakSet":return"weakset";case"Map":return"map";case"Set":return"set";case"Int8Array":return"int8array";case"Uint8Array":return"uint8array";case"Uint8ClampedArray":return"uint8clampedarray";case"Int16Array":return"int16array";case"Uint16Array":return"uint16array";case"Int32Array":return"int32array";case"Uint32Array":return"uint32array";case"Float32Array":return"float32array";case"Float64Array":return"float64array"}if(O1(t))return"generator";switch(r=$1.call(t),r){case"[object Object]":return"object";case"[object Map Iterator]":return"mapiterator";case"[object Set Iterator]":return"setiterator";case"[object String Iterator]":return"stringiterator";case"[object Array Iterator]":return"arrayiterator"}return r.slice(8,-1).toLowerCase().replace(/\s/g,"")};function I0(e){return typeof e.constructor=="function"?e.constructor.name:null}function k1(e){return Array.isArray?Array.isArray(e):e instanceof Array}function z1(e){return e instanceof Error||typeof e.message=="string"&&e.constructor&&typeof e.constructor.stackTraceLimit=="number"}function P1(e){return e instanceof Date?!0:typeof e.toDateString=="function"&&typeof e.getDate=="function"&&typeof e.setDate=="function"}function E1(e){return e instanceof RegExp?!0:typeof e.flags=="string"&&typeof e.ignoreCase=="boolean"&&typeof e.multiline=="boolean"&&typeof e.global=="boolean"}function T1(e,t){return I0(e)==="GeneratorFunction"}function O1(e){return typeof e.throw=="function"&&typeof e.return=="function"&&typeof e.next=="function"}function A1(e){try{if(typeof e.length=="number"&&typeof e.callee=="function")return!0}catch(t){if(t.message.indexOf("callee")!==-1)return!0}return!1}function I1(e){return e.constructor&&typeof e.constructor.isBuffer=="function"?e.constructor.isBuffer(e):!1}});var N0=x((bL,C0)=>{"use strict";C0.exports=function(t){return typeof t<"u"&&t!==null&&(typeof t=="object"||typeof t=="function")}});var M0=x((SL,D0)=>{"use strict";var j0=N0();D0.exports=function(t){j0(t)||(t={});for(var r=arguments.length,n=1;n{"use strict";var N1=Wo(),j1=M0();F0.exports=function(e,t){typeof t=="function"&&(t={parse:t});var r=M1(e),n={section_delimiter:"---",parse:F1},o=j1({},n,t),i=o.section_delimiter,s=r.content.split(/\r?\n/),a=null,c=q0(),u=[],l=[];function f(y){r.content=y,a=[],u=[]}function d(y){l.length&&(c.key=q1(l[0],i),c.content=y,o.parse(c,a),a.push(c),c=q0(),u=[],l=[])}for(var p=0;p{"use strict";function L0(e){return typeof e>"u"||e===null}function L1(e){return typeof e=="object"&&e!==null}function U1(e){return Array.isArray(e)?e:L0(e)?[]:[e]}function V1(e,t){var r,n,o,i;if(t)for(i=Object.keys(t),r=0,n=i.length;r{"use strict";function Go(e,t){Error.call(this),this.name="YAMLException",this.reason=e,this.mark=t,this.message=(this.reason||"(unknown reason)")+(this.mark?" "+this.mark.toString():""),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack||""}Go.prototype=Object.create(Error.prototype);Go.prototype.constructor=Go;Go.prototype.toString=function(t){var r=this.name+": ";return r+=this.reason||"(unknown reason)",!t&&this.mark&&(r+=" "+this.mark.toString()),r};U0.exports=Go});var B0=x((PL,H0)=>{"use strict";var V0=Ir();function sf(e,t,r,n,o){this.name=e,this.buffer=t,this.position=r,this.line=n,this.column=o}sf.prototype.getSnippet=function(t,r){var n,o,i,s,a;if(!this.buffer)return null;for(t=t||4,r=r||75,n="",o=this.position;o>0&&`\0\r +\x85\u2028\u2029`.indexOf(this.buffer.charAt(o-1))===-1;)if(o-=1,this.position-o>r/2-1){n=" ... ",o+=5;break}for(i="",s=this.position;sr/2-1){i=" ... ",s-=5;break}return a=this.buffer.slice(o,s),V0.repeat(" ",t)+n+a+i+` +`+V0.repeat(" ",t+this.position-o+n.length)+"^"};sf.prototype.toString=function(t){var r,n="";return this.name&&(n+='in "'+this.name+'" '),n+="at line "+(this.line+1)+", column "+(this.column+1),t||(r=this.getSnippet(),r&&(n+=`: +`+r)),n};H0.exports=sf});var ye=x((EL,J0)=>{"use strict";var K0=bn(),K1=["kind","resolve","construct","instanceOf","predicate","represent","defaultStyle","styleAliases"],J1=["scalar","sequence","mapping"];function W1(e){var t={};return e!==null&&Object.keys(e).forEach(function(r){e[r].forEach(function(n){t[String(n)]=r})}),t}function G1(e,t){if(t=t||{},Object.keys(t).forEach(function(r){if(K1.indexOf(r)===-1)throw new K0('Unknown option "'+r+'" is met in definition of "'+e+'" YAML type.')}),this.tag=e,this.kind=t.kind||null,this.resolve=t.resolve||function(){return!0},this.construct=t.construct||function(r){return r},this.instanceOf=t.instanceOf||null,this.predicate=t.predicate||null,this.represent=t.represent||null,this.defaultStyle=t.defaultStyle||null,this.styleAliases=W1(t.styleAliases||null),J1.indexOf(this.kind)===-1)throw new K0('Unknown kind "'+this.kind+'" is specified for "'+e+'" YAML type.')}J0.exports=G1});var Rr=x((TL,G0)=>{"use strict";var W0=Ir(),ra=bn(),Y1=ye();function af(e,t,r){var n=[];return e.include.forEach(function(o){r=af(o,t,r)}),e[t].forEach(function(o){r.forEach(function(i,s){i.tag===o.tag&&i.kind===o.kind&&n.push(s)}),r.push(o)}),r.filter(function(o,i){return n.indexOf(i)===-1})}function X1(){var e={scalar:{},sequence:{},mapping:{},fallback:{}},t,r;function n(o){e[o.kind][o.tag]=e.fallback[o.tag]=o}for(t=0,r=arguments.length;t{"use strict";var Q1=ye();Y0.exports=new Q1("tag:yaml.org,2002:str",{kind:"scalar",construct:function(e){return e!==null?e:""}})});var ew=x((AL,Q0)=>{"use strict";var eI=ye();Q0.exports=new eI("tag:yaml.org,2002:seq",{kind:"sequence",construct:function(e){return e!==null?e:[]}})});var rw=x((IL,tw)=>{"use strict";var tI=ye();tw.exports=new tI("tag:yaml.org,2002:map",{kind:"mapping",construct:function(e){return e!==null?e:{}}})});var na=x((RL,nw)=>{"use strict";var rI=Rr();nw.exports=new rI({explicit:[X0(),ew(),rw()]})});var iw=x((CL,ow)=>{"use strict";var nI=ye();function oI(e){if(e===null)return!0;var t=e.length;return t===1&&e==="~"||t===4&&(e==="null"||e==="Null"||e==="NULL")}function iI(){return null}function sI(e){return e===null}ow.exports=new nI("tag:yaml.org,2002:null",{kind:"scalar",resolve:oI,construct:iI,predicate:sI,represent:{canonical:function(){return"~"},lowercase:function(){return"null"},uppercase:function(){return"NULL"},camelcase:function(){return"Null"}},defaultStyle:"lowercase"})});var aw=x((NL,sw)=>{"use strict";var aI=ye();function cI(e){if(e===null)return!1;var t=e.length;return t===4&&(e==="true"||e==="True"||e==="TRUE")||t===5&&(e==="false"||e==="False"||e==="FALSE")}function uI(e){return e==="true"||e==="True"||e==="TRUE"}function lI(e){return Object.prototype.toString.call(e)==="[object Boolean]"}sw.exports=new aI("tag:yaml.org,2002:bool",{kind:"scalar",resolve:cI,construct:uI,predicate:lI,represent:{lowercase:function(e){return e?"true":"false"},uppercase:function(e){return e?"TRUE":"FALSE"},camelcase:function(e){return e?"True":"False"}},defaultStyle:"lowercase"})});var uw=x((jL,cw)=>{"use strict";var fI=Ir(),dI=ye();function pI(e){return 48<=e&&e<=57||65<=e&&e<=70||97<=e&&e<=102}function mI(e){return 48<=e&&e<=55}function hI(e){return 48<=e&&e<=57}function gI(e){if(e===null)return!1;var t=e.length,r=0,n=!1,o;if(!t)return!1;if(o=e[r],(o==="-"||o==="+")&&(o=e[++r]),o==="0"){if(r+1===t)return!0;if(o=e[++r],o==="b"){for(r++;r=0?"0b"+e.toString(2):"-0b"+e.toString(2).slice(1)},octal:function(e){return e>=0?"0"+e.toString(8):"-0"+e.toString(8).slice(1)},decimal:function(e){return e.toString(10)},hexadecimal:function(e){return e>=0?"0x"+e.toString(16).toUpperCase():"-0x"+e.toString(16).toUpperCase().slice(1)}},defaultStyle:"decimal",styleAliases:{binary:[2,"bin"],octal:[8,"oct"],decimal:[10,"dec"],hexadecimal:[16,"hex"]}})});var dw=x((DL,fw)=>{"use strict";var lw=Ir(),wI=ye(),xI=new RegExp("^(?:[-+]?(?:0|[1-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?|[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\.[0-9_]*|[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$");function vI(e){return!(e===null||!xI.test(e)||e[e.length-1]==="_")}function bI(e){var t,r,n,o;return t=e.replace(/_/g,"").toLowerCase(),r=t[0]==="-"?-1:1,o=[],"+-".indexOf(t[0])>=0&&(t=t.slice(1)),t===".inf"?r===1?Number.POSITIVE_INFINITY:Number.NEGATIVE_INFINITY:t===".nan"?NaN:t.indexOf(":")>=0?(t.split(":").forEach(function(i){o.unshift(parseFloat(i,10))}),t=0,n=1,o.forEach(function(i){t+=i*n,n*=60}),r*t):r*parseFloat(t,10)}var SI=/^[-+]?[0-9]+e/;function $I(e,t){var r;if(isNaN(e))switch(t){case"lowercase":return".nan";case"uppercase":return".NAN";case"camelcase":return".NaN"}else if(Number.POSITIVE_INFINITY===e)switch(t){case"lowercase":return".inf";case"uppercase":return".INF";case"camelcase":return".Inf"}else if(Number.NEGATIVE_INFINITY===e)switch(t){case"lowercase":return"-.inf";case"uppercase":return"-.INF";case"camelcase":return"-.Inf"}else if(lw.isNegativeZero(e))return"-0.0";return r=e.toString(10),SI.test(r)?r.replace("e",".e"):r}function kI(e){return Object.prototype.toString.call(e)==="[object Number]"&&(e%1!==0||lw.isNegativeZero(e))}fw.exports=new wI("tag:yaml.org,2002:float",{kind:"scalar",resolve:vI,construct:bI,predicate:kI,represent:$I,defaultStyle:"lowercase"})});var cf=x((ML,pw)=>{"use strict";var zI=Rr();pw.exports=new zI({include:[na()],implicit:[iw(),aw(),uw(),dw()]})});var uf=x((qL,mw)=>{"use strict";var PI=Rr();mw.exports=new PI({include:[cf()]})});var _w=x((FL,yw)=>{"use strict";var EI=ye(),hw=new RegExp("^([0-9][0-9][0-9][0-9])-([0-9][0-9])-([0-9][0-9])$"),gw=new RegExp("^([0-9][0-9][0-9][0-9])-([0-9][0-9]?)-([0-9][0-9]?)(?:[Tt]|[ \\t]+)([0-9][0-9]?):([0-9][0-9]):([0-9][0-9])(?:\\.([0-9]*))?(?:[ \\t]*(Z|([-+])([0-9][0-9]?)(?::([0-9][0-9]))?))?$");function TI(e){return e===null?!1:hw.exec(e)!==null||gw.exec(e)!==null}function OI(e){var t,r,n,o,i,s,a,c=0,u=null,l,f,d;if(t=hw.exec(e),t===null&&(t=gw.exec(e)),t===null)throw new Error("Date resolve error");if(r=+t[1],n=+t[2]-1,o=+t[3],!t[4])return new Date(Date.UTC(r,n,o));if(i=+t[4],s=+t[5],a=+t[6],t[7]){for(c=t[7].slice(0,3);c.length<3;)c+="0";c=+c}return t[9]&&(l=+t[10],f=+(t[11]||0),u=(l*60+f)*6e4,t[9]==="-"&&(u=-u)),d=new Date(Date.UTC(r,n,o,i,s,a,c)),u&&d.setTime(d.getTime()-u),d}function AI(e){return e.toISOString()}yw.exports=new EI("tag:yaml.org,2002:timestamp",{kind:"scalar",resolve:TI,construct:OI,instanceOf:Date,represent:AI})});var xw=x((ZL,ww)=>{"use strict";var II=ye();function RI(e){return e==="<<"||e===null}ww.exports=new II("tag:yaml.org,2002:merge",{kind:"scalar",resolve:RI})});var Sw=x((LL,bw)=>{"use strict";var Cr;try{vw=require,Cr=vw("buffer").Buffer}catch{}var vw,CI=ye(),lf=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/= +\r`;function NI(e){if(e===null)return!1;var t,r,n=0,o=e.length,i=lf;for(r=0;r64)){if(t<0)return!1;n+=6}return n%8===0}function jI(e){var t,r,n=e.replace(/[\r\n=]/g,""),o=n.length,i=lf,s=0,a=[];for(t=0;t>16&255),a.push(s>>8&255),a.push(s&255)),s=s<<6|i.indexOf(n.charAt(t));return r=o%4*6,r===0?(a.push(s>>16&255),a.push(s>>8&255),a.push(s&255)):r===18?(a.push(s>>10&255),a.push(s>>2&255)):r===12&&a.push(s>>4&255),Cr?Cr.from?Cr.from(a):new Cr(a):a}function DI(e){var t="",r=0,n,o,i=e.length,s=lf;for(n=0;n>18&63],t+=s[r>>12&63],t+=s[r>>6&63],t+=s[r&63]),r=(r<<8)+e[n];return o=i%3,o===0?(t+=s[r>>18&63],t+=s[r>>12&63],t+=s[r>>6&63],t+=s[r&63]):o===2?(t+=s[r>>10&63],t+=s[r>>4&63],t+=s[r<<2&63],t+=s[64]):o===1&&(t+=s[r>>2&63],t+=s[r<<4&63],t+=s[64],t+=s[64]),t}function MI(e){return Cr&&Cr.isBuffer(e)}bw.exports=new CI("tag:yaml.org,2002:binary",{kind:"scalar",resolve:NI,construct:jI,predicate:MI,represent:DI})});var zw=x((UL,kw)=>{"use strict";var qI=ye(),$w=Object.prototype.hasOwnProperty,FI=Object.prototype.toString;function ZI(e){if(e===null)return!0;var t={},r,n,o,i,s,a=e;for(r=0,n=a.length;r{"use strict";var UI=ye(),VI=Object.prototype.toString;function HI(e){if(e===null)return!0;var t,r,n,o,i,s=e;for(i=new Array(s.length),t=0,r=s.length;t{"use strict";var KI=ye(),JI=Object.prototype.hasOwnProperty;function WI(e){if(e===null)return!0;var t,r=e;for(t in r)if(JI.call(r,t)&&r[t]!==null)return!1;return!0}function GI(e){return e!==null?e:{}}Tw.exports=new KI("tag:yaml.org,2002:set",{kind:"mapping",resolve:WI,construct:GI})});var $n=x((BL,Aw)=>{"use strict";var YI=Rr();Aw.exports=new YI({include:[uf()],implicit:[_w(),xw()],explicit:[Sw(),zw(),Ew(),Ow()]})});var Rw=x((KL,Iw)=>{"use strict";var XI=ye();function QI(){return!0}function eR(){}function tR(){return""}function rR(e){return typeof e>"u"}Iw.exports=new XI("tag:yaml.org,2002:js/undefined",{kind:"scalar",resolve:QI,construct:eR,predicate:rR,represent:tR})});var Nw=x((JL,Cw)=>{"use strict";var nR=ye();function oR(e){if(e===null||e.length===0)return!1;var t=e,r=/\/([gim]*)$/.exec(e),n="";return!(t[0]==="/"&&(r&&(n=r[1]),n.length>3||t[t.length-n.length-1]!=="/"))}function iR(e){var t=e,r=/\/([gim]*)$/.exec(e),n="";return t[0]==="/"&&(r&&(n=r[1]),t=t.slice(1,t.length-n.length-1)),new RegExp(t,n)}function sR(e){var t="/"+e.source+"/";return e.global&&(t+="g"),e.multiline&&(t+="m"),e.ignoreCase&&(t+="i"),t}function aR(e){return Object.prototype.toString.call(e)==="[object RegExp]"}Cw.exports=new nR("tag:yaml.org,2002:js/regexp",{kind:"scalar",resolve:oR,construct:iR,predicate:aR,represent:sR})});var Mw=x((WL,Dw)=>{"use strict";var oa;try{jw=require,oa=jw("esprima")}catch{typeof window<"u"&&(oa=window.esprima)}var jw,cR=ye();function uR(e){if(e===null)return!1;try{var t="("+e+")",r=oa.parse(t,{range:!0});return!(r.type!=="Program"||r.body.length!==1||r.body[0].type!=="ExpressionStatement"||r.body[0].expression.type!=="ArrowFunctionExpression"&&r.body[0].expression.type!=="FunctionExpression")}catch{return!1}}function lR(e){var t="("+e+")",r=oa.parse(t,{range:!0}),n=[],o;if(r.type!=="Program"||r.body.length!==1||r.body[0].type!=="ExpressionStatement"||r.body[0].expression.type!=="ArrowFunctionExpression"&&r.body[0].expression.type!=="FunctionExpression")throw new Error("Failed to resolve function");return r.body[0].expression.params.forEach(function(i){n.push(i.name)}),o=r.body[0].expression.body.range,r.body[0].expression.body.type==="BlockStatement"?new Function(n,t.slice(o[0]+1,o[1]-1)):new Function(n,"return "+t.slice(o[0],o[1]))}function fR(e){return e.toString()}function dR(e){return Object.prototype.toString.call(e)==="[object Function]"}Dw.exports=new cR("tag:yaml.org,2002:js/function",{kind:"scalar",resolve:uR,construct:lR,predicate:dR,represent:fR})});var Yo=x((GL,Fw)=>{"use strict";var qw=Rr();Fw.exports=qw.DEFAULT=new qw({include:[$n()],explicit:[Rw(),Nw(),Mw()]})});var ax=x((YL,Xo)=>{"use strict";var Lt=Ir(),Jw=bn(),pR=B0(),Ww=$n(),mR=Yo(),ur=Object.prototype.hasOwnProperty,ia=1,Gw=2,Yw=3,sa=4,ff=1,hR=2,Zw=3,gR=/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/,yR=/[\x85\u2028\u2029]/,_R=/[,\[\]\{\}]/,Xw=/^(?:!|!!|![a-z\-]+!)$/i,Qw=/^(?:!|[^,\[\]\{\}])(?:%[0-9a-f]{2}|[0-9a-z\-#;\/\?:@&=\+\$,_\.!~\*'\(\)\[\]])*$/i;function Lw(e){return Object.prototype.toString.call(e)}function zt(e){return e===10||e===13}function jr(e){return e===9||e===32}function Je(e){return e===9||e===32||e===10||e===13}function kn(e){return e===44||e===91||e===93||e===123||e===125}function wR(e){var t;return 48<=e&&e<=57?e-48:(t=e|32,97<=t&&t<=102?t-97+10:-1)}function xR(e){return e===120?2:e===117?4:e===85?8:0}function vR(e){return 48<=e&&e<=57?e-48:-1}function Uw(e){return e===48?"\0":e===97?"\x07":e===98?"\b":e===116||e===9?" ":e===110?` +`:e===118?"\v":e===102?"\f":e===114?"\r":e===101?"\x1B":e===32?" ":e===34?'"':e===47?"/":e===92?"\\":e===78?"\x85":e===95?"\xA0":e===76?"\u2028":e===80?"\u2029":""}function bR(e){return e<=65535?String.fromCharCode(e):String.fromCharCode((e-65536>>10)+55296,(e-65536&1023)+56320)}function ex(e,t,r){t==="__proto__"?Object.defineProperty(e,t,{configurable:!0,enumerable:!0,writable:!0,value:r}):e[t]=r}var tx=new Array(256),rx=new Array(256);for(Nr=0;Nr<256;Nr++)tx[Nr]=Uw(Nr)?1:0,rx[Nr]=Uw(Nr);var Nr;function SR(e,t){this.input=e,this.filename=t.filename||null,this.schema=t.schema||mR,this.onWarning=t.onWarning||null,this.legacy=t.legacy||!1,this.json=t.json||!1,this.listener=t.listener||null,this.maxTotalMergeKeys=typeof t.maxTotalMergeKeys=="number"?t.maxTotalMergeKeys:1e4,this.implicitTypes=this.schema.compiledImplicit,this.typeMap=this.schema.compiledTypeMap,this.length=e.length,this.position=0,this.line=0,this.lineStart=0,this.lineIndent=0,this.totalMergeKeys=0,this.documents=[]}function nx(e,t){return new Jw(t,new pR(e.filename,e.input,e.position,e.line,e.position-e.lineStart))}function O(e,t){throw nx(e,t)}function aa(e,t){e.onWarning&&e.onWarning.call(null,nx(e,t))}var Vw={YAML:function(t,r,n){var o,i,s;t.version!==null&&O(t,"duplication of %YAML directive"),n.length!==1&&O(t,"YAML directive accepts exactly one argument"),o=/^([0-9]+)\.([0-9]+)$/.exec(n[0]),o===null&&O(t,"ill-formed argument of the YAML directive"),i=parseInt(o[1],10),s=parseInt(o[2],10),i!==1&&O(t,"unacceptable YAML version of the document"),t.version=n[0],t.checkLineBreaks=s<2,s!==1&&s!==2&&aa(t,"unsupported YAML version of the document")},TAG:function(t,r,n){var o,i;n.length!==2&&O(t,"TAG directive accepts exactly two arguments"),o=n[0],i=n[1],Xw.test(o)||O(t,"ill-formed tag handle (first argument) of the TAG directive"),ur.call(t.tagMap,o)&&O(t,'there is a previously declared suffix for "'+o+'" tag handle'),Qw.test(i)||O(t,"ill-formed tag prefix (second argument) of the TAG directive"),t.tagMap[o]=i}};function cr(e,t,r,n){var o,i,s,a;if(te.maxTotalMergeKeys&&O(e,"merge keys exceeded maxTotalMergeKeys ("+e.maxTotalMergeKeys+")")}function Bw(e,t,r,n){var o,i,s,a;for(Lt.isObject(r)||O(e,"cannot merge mappings; the provided source object is unacceptable"),Hw(e),o=Object.keys(r),s=0,a=o.length;s100&&O(e,"abnormal merge sequence size"),c=0,u=i.length;c1&&(e.result+=Lt.repeat(` +`,t-1))}function $R(e,t,r){var n,o,i,s,a,c,u,l,f=e.kind,d=e.result,p;if(p=e.input.charCodeAt(e.position),Je(p)||kn(p)||p===35||p===38||p===42||p===33||p===124||p===62||p===39||p===34||p===37||p===64||p===96||(p===63||p===45)&&(o=e.input.charCodeAt(e.position+1),Je(o)||r&&kn(o)))return!1;for(e.kind="scalar",e.result="",i=s=e.position,a=!1;p!==0;){if(p===58){if(o=e.input.charCodeAt(e.position+1),Je(o)||r&&kn(o))break}else if(p===35){if(n=e.input.charCodeAt(e.position-1),Je(n))break}else{if(e.position===e.lineStart&&ca(e)||r&&kn(p))break;if(zt(p))if(c=e.line,u=e.lineStart,l=e.lineIndent,he(e,!1,-1),e.lineIndent>=t){a=!0,p=e.input.charCodeAt(e.position);continue}else{e.position=s,e.line=c,e.lineStart=u,e.lineIndent=l;break}}a&&(cr(e,i,s,!1),pf(e,e.line-c),i=s=e.position,a=!1),jr(p)||(s=e.position+1),p=e.input.charCodeAt(++e.position)}return cr(e,i,s,!1),e.result?!0:(e.kind=f,e.result=d,!1)}function kR(e,t){var r,n,o;if(r=e.input.charCodeAt(e.position),r!==39)return!1;for(e.kind="scalar",e.result="",e.position++,n=o=e.position;(r=e.input.charCodeAt(e.position))!==0;)if(r===39)if(cr(e,n,e.position,!0),r=e.input.charCodeAt(++e.position),r===39)n=e.position,e.position++,o=e.position;else return!0;else zt(r)?(cr(e,n,o,!0),pf(e,he(e,!1,t)),n=o=e.position):e.position===e.lineStart&&ca(e)?O(e,"unexpected end of the document within a single quoted scalar"):(e.position++,o=e.position);O(e,"unexpected end of the stream within a single quoted scalar")}function zR(e,t){var r,n,o,i,s,a;if(a=e.input.charCodeAt(e.position),a!==34)return!1;for(e.kind="scalar",e.result="",e.position++,r=n=e.position;(a=e.input.charCodeAt(e.position))!==0;){if(a===34)return cr(e,r,e.position,!0),e.position++,!0;if(a===92){if(cr(e,r,e.position,!0),a=e.input.charCodeAt(++e.position),zt(a))he(e,!1,t);else if(a<256&&tx[a])e.result+=rx[a],e.position++;else if((s=xR(a))>0){for(o=s,i=0;o>0;o--)a=e.input.charCodeAt(++e.position),(s=wR(a))>=0?i=(i<<4)+s:O(e,"expected hexadecimal character");e.result+=bR(i),e.position++}else O(e,"unknown escape sequence");r=n=e.position}else zt(a)?(cr(e,r,n,!0),pf(e,he(e,!1,t)),r=n=e.position):e.position===e.lineStart&&ca(e)?O(e,"unexpected end of the document within a double quoted scalar"):(e.position++,n=e.position)}O(e,"unexpected end of the stream within a double quoted scalar")}function PR(e,t){var r=!0,n,o=e.tag,i,s=e.anchor,a,c,u,l,f,d={},p,m,h,g;if(g=e.input.charCodeAt(e.position),g===91)c=93,f=!1,i=[];else if(g===123)c=125,f=!0,i={};else return!1;for(e.anchor!==null&&(e.anchorMap[e.anchor]=i),g=e.input.charCodeAt(++e.position);g!==0;){if(he(e,!0,t),g=e.input.charCodeAt(e.position),g===c)return e.position++,e.tag=o,e.anchor=s,e.kind=f?"mapping":"sequence",e.result=i,!0;r||O(e,"missed comma between flow collection entries"),m=p=h=null,u=l=!1,g===63&&(a=e.input.charCodeAt(e.position+1),Je(a)&&(u=l=!0,e.position++,he(e,!0,t))),n=e.line,Pn(e,t,ia,!1,!0),m=e.tag,p=e.result,he(e,!0,t),g=e.input.charCodeAt(e.position),(l||e.line===n)&&g===58&&(u=!0,g=e.input.charCodeAt(++e.position),he(e,!0,t),Pn(e,t,ia,!1,!0),h=e.result),f?zn(e,i,d,m,p,h):u?i.push(zn(e,null,d,m,p,h)):i.push(p),he(e,!0,t),g=e.input.charCodeAt(e.position),g===44?(r=!0,g=e.input.charCodeAt(++e.position)):r=!1}O(e,"unexpected end of the stream within a flow collection")}function ER(e,t){var r,n,o=ff,i=!1,s=!1,a=t,c=0,u=!1,l,f;if(f=e.input.charCodeAt(e.position),f===124)n=!1;else if(f===62)n=!0;else return!1;for(e.kind="scalar",e.result="";f!==0;)if(f=e.input.charCodeAt(++e.position),f===43||f===45)ff===o?o=f===43?Zw:hR:O(e,"repeat of a chomping mode identifier");else if((l=vR(f))>=0)l===0?O(e,"bad explicit indentation width of a block scalar; it cannot be less than one"):s?O(e,"repeat of an indentation width identifier"):(a=t+l-1,s=!0);else break;if(jr(f)){do f=e.input.charCodeAt(++e.position);while(jr(f));if(f===35)do f=e.input.charCodeAt(++e.position);while(!zt(f)&&f!==0)}for(;f!==0;){for(df(e),e.lineIndent=0,f=e.input.charCodeAt(e.position);(!s||e.lineIndenta&&(a=e.lineIndent),zt(f)){c++;continue}if(e.lineIndentt)&&c!==0)O(e,"bad indentation of a sequence entry");else if(e.lineIndentt)&&(Pn(e,t,sa,!0,o)&&(m?d=e.result:p=e.result),m||(zn(e,u,l,f,d,p,i,s),f=d=p=null),he(e,!0,-1),g=e.input.charCodeAt(e.position)),e.lineIndent>t&&g!==0)O(e,"bad indentation of a mapping entry");else if(e.lineIndentt?c=1:e.lineIndent===t?c=0:e.lineIndentt?c=1:e.lineIndent===t?c=0:e.lineIndent tag; it should be "scalar", not "'+e.kind+'"'),f=0,d=e.implicitTypes.length;f tag; it should be "'+p.kind+'", not "'+e.kind+'"'),p.resolve(e.result)?(e.result=p.construct(e.result),e.anchor!==null&&(e.anchorMap[e.anchor]=e.result)):O(e,"cannot resolve a node with !<"+e.tag+"> explicit tag")):O(e,"unknown tag !<"+e.tag+">");return e.listener!==null&&e.listener("close",e),e.tag!==null||e.anchor!==null||l}function RR(e){var t=e.position,r,n,o,i=!1,s;for(e.version=null,e.checkLineBreaks=e.legacy,e.tagMap={},e.anchorMap={};(s=e.input.charCodeAt(e.position))!==0&&(he(e,!0,-1),s=e.input.charCodeAt(e.position),!(e.lineIndent>0||s!==37));){for(i=!0,s=e.input.charCodeAt(++e.position),r=e.position;s!==0&&!Je(s);)s=e.input.charCodeAt(++e.position);for(n=e.input.slice(r,e.position),o=[],n.length<1&&O(e,"directive name must not be less than one character in length");s!==0;){for(;jr(s);)s=e.input.charCodeAt(++e.position);if(s===35){do s=e.input.charCodeAt(++e.position);while(s!==0&&!zt(s));break}if(zt(s))break;for(r=e.position;s!==0&&!Je(s);)s=e.input.charCodeAt(++e.position);o.push(e.input.slice(r,e.position))}s!==0&&df(e),ur.call(Vw,n)?Vw[n](e,n,o):aa(e,'unknown document directive "'+n+'"')}if(he(e,!0,-1),e.lineIndent===0&&e.input.charCodeAt(e.position)===45&&e.input.charCodeAt(e.position+1)===45&&e.input.charCodeAt(e.position+2)===45?(e.position+=3,he(e,!0,-1)):i&&O(e,"directives end mark is expected"),Pn(e,e.lineIndent-1,sa,!1,!0),he(e,!0,-1),e.checkLineBreaks&&yR.test(e.input.slice(t,e.position))&&aa(e,"non-ASCII line breaks are interpreted as content"),e.documents.push(e.result),e.position===e.lineStart&&ca(e)){e.input.charCodeAt(e.position)===46&&(e.position+=3,he(e,!0,-1));return}if(e.position"u"&&(r=t,t=null);var n=ox(e,r);if(typeof t!="function")return n;for(var o=0,i=n.length;o"u"&&(r=t,t=null),ix(e,t,Lt.extend({schema:Ww},r))}function NR(e,t){return sx(e,Lt.extend({schema:Ww},t))}Xo.exports.loadAll=ix;Xo.exports.load=sx;Xo.exports.safeLoadAll=CR;Xo.exports.safeLoad=NR});var Ox=x((XL,yf)=>{"use strict";var ei=Ir(),ti=bn(),jR=Yo(),DR=$n(),hx=Object.prototype.toString,gx=Object.prototype.hasOwnProperty,MR=9,Qo=10,qR=13,FR=32,ZR=33,LR=34,yx=35,UR=37,VR=38,HR=39,BR=42,_x=44,KR=45,wx=58,JR=61,WR=62,GR=63,YR=64,xx=91,vx=93,XR=96,bx=123,QR=124,Sx=125,Ne={};Ne[0]="\\0";Ne[7]="\\a";Ne[8]="\\b";Ne[9]="\\t";Ne[10]="\\n";Ne[11]="\\v";Ne[12]="\\f";Ne[13]="\\r";Ne[27]="\\e";Ne[34]='\\"';Ne[92]="\\\\";Ne[133]="\\N";Ne[160]="\\_";Ne[8232]="\\L";Ne[8233]="\\P";var eC=["y","Y","yes","Yes","YES","on","On","ON","n","N","no","No","NO","off","Off","OFF"];function tC(e,t){var r,n,o,i,s,a,c;if(t===null)return{};for(r={},n=Object.keys(t),o=0,i=n.length;o0?e.charCodeAt(i-1):null,d=d&&lx(s,a)}else{for(i=0;in&&e[f+1]!==" ",f=i);else if(!En(s))return ua;a=i>0?e.charCodeAt(i-1):null,d=d&&lx(s,a)}u=u||l&&i-f-1>n&&e[f+1]!==" "}return!c&&!u?d&&!o(e)?kx:zx:r>9&&$x(e)?ua:u?Ex:Px}function aC(e,t,r,n){e.dump=(function(){if(t.length===0)return"''";if(!e.noCompatMode&&eC.indexOf(t)!==-1)return"'"+t+"'";var o=e.indent*Math.max(1,r),i=e.lineWidth===-1?-1:Math.max(Math.min(e.lineWidth,40),e.lineWidth-o),s=n||e.flowLevel>-1&&r>=e.flowLevel;function a(c){return nC(e,c)}switch(sC(t,s,e.indent,i,a)){case kx:return t;case zx:return"'"+t.replace(/'/g,"''")+"'";case Px:return"|"+fx(t,e.indent)+dx(ux(t,o));case Ex:return">"+fx(t,e.indent)+dx(ux(cC(t,i),o));case ua:return'"'+uC(t,i)+'"';default:throw new ti("impossible error: invalid scalar style")}})()}function fx(e,t){var r=$x(e)?String(t):"",n=e[e.length-1]===` +`,o=n&&(e[e.length-2]===` +`||e===` +`),i=o?"+":n?"":"-";return r+i+` +`}function dx(e){return e[e.length-1]===` +`?e.slice(0,-1):e}function cC(e,t){for(var r=/(\n+)([^\n]*)/g,n=(function(){var u=e.indexOf(` +`);return u=u!==-1?u:e.length,r.lastIndex=u,px(e.slice(0,u),t)})(),o=e[0]===` +`||e[0]===" ",i,s;s=r.exec(e);){var a=s[1],c=s[2];i=c[0]===" ",n+=a+(!o&&!i&&c!==""?` +`:"")+px(c,t),o=i}return n}function px(e,t){if(e===""||e[0]===" ")return e;for(var r=/ [^ ]/g,n,o=0,i,s=0,a=0,c="";n=r.exec(e);)a=n.index,a-o>t&&(i=s>o?s:a,c+=` +`+e.slice(o,i),o=i+1),s=a;return c+=` +`,e.length-o>t&&s>o?c+=e.slice(o,s)+` +`+e.slice(s+1):c+=e.slice(o),c.slice(1)}function uC(e){for(var t="",r,n,o,i=0;i=55296&&r<=56319&&(n=e.charCodeAt(i+1),n>=56320&&n<=57343)){t+=cx((r-55296)*1024+n-56320+65536),i++;continue}o=Ne[r],t+=!o&&En(r)?e[i]:o||cx(r)}return t}function lC(e,t,r){var n="",o=e.tag,i,s;for(i=0,s=r.length;i1024&&(l+="? "),l+=e.dump+(e.condenseFlow?'"':"")+":"+(e.condenseFlow?"":" "),Dr(e,t,u,!1,!1)&&(l+=e.dump,n+=l));e.tag=o,e.dump="{"+n+"}"}function pC(e,t,r,n){var o="",i=e.tag,s=Object.keys(r),a,c,u,l,f,d;if(e.sortKeys===!0)s.sort();else if(typeof e.sortKeys=="function")s.sort(e.sortKeys);else if(e.sortKeys)throw new ti("sortKeys must be a boolean or a function");for(a=0,c=s.length;a1024,f&&(e.dump&&Qo===e.dump.charCodeAt(0)?d+="?":d+="? "),d+=e.dump,f&&(d+=mf(e,t)),Dr(e,t+1,l,!0,f)&&(e.dump&&Qo===e.dump.charCodeAt(0)?d+=":":d+=": ",d+=e.dump,o+=d));e.tag=i,e.dump=o||"{}"}function mx(e,t,r){var n,o,i,s,a,c;for(o=r?e.explicitTypes:e.implicitTypes,i=0,s=o.length;i tag resolver accepts not "'+c+'" style');e.dump=n}return!0}return!1}function Dr(e,t,r,n,o,i){e.tag=null,e.dump=r,mx(e,r,!1)||mx(e,r,!0);var s=hx.call(e.dump);n&&(n=e.flowLevel<0||e.flowLevel>t);var a=s==="[object Object]"||s==="[object Array]",c,u;if(a&&(c=e.duplicates.indexOf(r),u=c!==-1),(e.tag!==null&&e.tag!=="?"||u||e.indent!==2&&t>0)&&(o=!1),u&&e.usedDuplicates[c])e.dump="*ref_"+c;else{if(a&&u&&!e.usedDuplicates[c]&&(e.usedDuplicates[c]=!0),s==="[object Object]")n&&Object.keys(e.dump).length!==0?(pC(e,t,e.dump,o),u&&(e.dump="&ref_"+c+e.dump)):(dC(e,t,e.dump),u&&(e.dump="&ref_"+c+" "+e.dump));else if(s==="[object Array]"){var l=e.noArrayIndent&&t>0?t-1:t;n&&e.dump.length!==0?(fC(e,l,e.dump,o),u&&(e.dump="&ref_"+c+e.dump)):(lC(e,l,e.dump),u&&(e.dump="&ref_"+c+" "+e.dump))}else if(s==="[object String]")e.tag!=="?"&&aC(e,e.dump,t,i);else{if(e.skipInvalid)return!1;throw new ti("unacceptable kind of an object to dump "+s)}e.tag!==null&&e.tag!=="?"&&(e.dump="!<"+e.tag+"> "+e.dump)}return!0}function mC(e,t){var r=[],n=[],o,i;for(hf(e,r,n),o=0,i=n.length;o{"use strict";var la=ax(),Ax=Ox();function fa(e){return function(){throw new Error("Function "+e+" is deprecated and cannot be used.")}}le.exports.Type=ye();le.exports.Schema=Rr();le.exports.FAILSAFE_SCHEMA=na();le.exports.JSON_SCHEMA=cf();le.exports.CORE_SCHEMA=uf();le.exports.DEFAULT_SAFE_SCHEMA=$n();le.exports.DEFAULT_FULL_SCHEMA=Yo();le.exports.load=la.load;le.exports.loadAll=la.loadAll;le.exports.safeLoad=la.safeLoad;le.exports.safeLoadAll=la.safeLoadAll;le.exports.dump=Ax.dump;le.exports.safeDump=Ax.safeDump;le.exports.YAMLException=bn();le.exports.MINIMAL_SCHEMA=na();le.exports.SAFE_SCHEMA=$n();le.exports.DEFAULT_SCHEMA=Yo();le.exports.scan=fa("scan");le.exports.parse=fa("parse");le.exports.compose=fa("compose");le.exports.addConstructor=fa("addConstructor")});var Cx=x((e9,Rx)=>{"use strict";var gC=Ix();Rx.exports=gC});var _f=x((exports,module)=>{"use strict";var yaml=Cx(),engines=exports=module.exports;engines.yaml={parse:yaml.safeLoad.bind(yaml),stringify:yaml.safeDump.bind(yaml)};engines.json={parse:JSON.parse.bind(JSON),stringify:function(e,t){let r=Object.assign({replacer:null,space:2},t);return JSON.stringify(e,r.replacer,r.space)}};engines.javascript={parse:function parse(str,options,wrap){try{return wrap!==!1&&(str=`(function() { +return `+str.trim()+`; +}());`),eval(str)||{}}catch(e){if(wrap!==!1&&/(unexpected|identifier)/i.test(e.message))return parse(str,options,!1);throw new SyntaxError(e)}},stringify:function(){throw new Error("stringifying JavaScript is not supported")}}});var jx=x((t9,Nx)=>{"use strict";Nx.exports=function(e){return typeof e=="string"&&e.charAt(0)==="\uFEFF"?e.slice(1):e}});var da=x(Ut=>{"use strict";var Dx=jx(),Mx=Wo();Ut.define=function(e,t,r){Reflect.defineProperty(e,t,{enumerable:!1,configurable:!0,writable:!0,value:r})};Ut.isBuffer=function(e){return Mx(e)==="buffer"};Ut.isObject=function(e){return Mx(e)==="object"};Ut.toBuffer=function(e){return typeof e=="string"?Buffer.from(e):e};Ut.toString=function(e){if(Ut.isBuffer(e))return Dx(String(e));if(typeof e!="string")throw new TypeError("expected input to be a string or buffer");return Dx(e)};Ut.arrayify=function(e){return e?Array.isArray(e)?e:[e]:[]};Ut.startsWith=function(e,t,r){return typeof r!="number"&&(r=t.length),e.slice(0,r)===t}});var ri=x((n9,qx)=>{"use strict";var yC=_f(),_C=da();qx.exports=function(e){let t=Object.assign({},e);return t.delimiters=_C.arrayify(t.delims||t.delimiters||"---"),t.delimiters.length===1&&t.delimiters.push(t.delimiters[0]),t.language=(t.language||t.lang||"yaml").toLowerCase(),t.engines=Object.assign({},yC,t.parsers,t.engines),t}});var wf=x((o9,Fx)=>{"use strict";Fx.exports=function(e,t){let r=t.engines[e]||t.engines[wC(e)];if(typeof r>"u")throw new Error('gray-matter engine "'+e+'" is not registered');return typeof r=="function"&&(r={parse:r}),r};function wC(e){switch(e.toLowerCase()){case"js":case"javascript":return"javascript";case"coffee":case"coffeescript":case"cson":return"coffee";case"yaml":case"yml":return"yaml";default:return e}}});var xf=x((i9,Zx)=>{"use strict";var xC=Wo(),vC=wf(),bC=ri();Zx.exports=function(e,t,r){if(t==null&&r==null)switch(xC(e)){case"object":t=e.data,r={};break;case"string":return e;default:throw new TypeError("expected file to be a string or object")}let n=e.content,o=bC(r);if(t==null){if(!o.data)return e;t=o.data}let i=e.language||o.language,s=vC(i,o);if(typeof s.stringify!="function")throw new TypeError('expected "'+i+'.stringify" to be a function');t=Object.assign({},e.data,t);let a=o.delimiters[0],c=o.delimiters[1],u=s.stringify(t,r).trim(),l="";return u!=="{}"&&(l=Tn(a)+Tn(u)+Tn(c)),typeof e.excerpt=="string"&&e.excerpt!==""&&n.indexOf(e.excerpt.trim())===-1&&(l+=Tn(e.excerpt)+Tn(c)),l+Tn(n)};function Tn(e){return e.slice(-1)!==` +`?e+` +`:e}});var Ux=x((s9,Lx)=>{"use strict";var SC=ri();Lx.exports=function(e,t){let r=SC(t);if(e.data==null&&(e.data={}),typeof r.excerpt=="function")return r.excerpt(e,r);let n=e.data.excerpt_separator||r.excerpt_separator;if(n==null&&(r.excerpt===!1||r.excerpt==null))return e;let o=typeof r.excerpt=="string"?r.excerpt:n||r.delimiters[0],i=e.content.indexOf(o);return i!==-1&&(e.excerpt=e.content.slice(0,i)),e}});var Bx=x((a9,Hx)=>{"use strict";var Vx=Wo(),$C=xf(),On=da();Hx.exports=function(e){return Vx(e)!=="object"&&(e={content:e}),Vx(e.data)!=="object"&&(e.data={}),e.contents&&e.content==null&&(e.content=e.contents),On.define(e,"orig",On.toBuffer(e.content)),On.define(e,"language",e.language||""),On.define(e,"matter",e.matter||""),On.define(e,"stringify",function(t,r){return r&&r.language&&(e.language=r.language),$C(e,t,r)}),e.content=On.toString(e.content),e.isEmpty=!1,e.excerpt="",e}});var Jx=x((c9,Kx)=>{"use strict";var kC=wf(),zC=ri();Kx.exports=function(e,t,r){let n=zC(r),o=kC(e,n);if(typeof o.parse!="function")throw new TypeError('expected "'+e+'.parse" to be a function');return o.parse(t,n)}});var Xx=x((u9,Yx)=>{"use strict";var PC=require("fs"),EC=Z0(),vf=ri(),TC=xf(),Wx=Ux(),OC=_f(),AC=Bx(),IC=Jx(),Gx=da();function Fe(e,t){if(e==="")return{data:{},content:e,excerpt:"",orig:e};let r=AC(e),n=Fe.cache[r.content];if(!t){if(n)return r=Object.assign({},n),r.orig=n.orig,r;Fe.cache[r.content]=r}return RC(r,t)}function RC(e,t){let r=vf(t),n=r.delimiters[0],o=` +`+r.delimiters[1],i=e.content;r.language&&(e.language=r.language);let s=n.length;if(!Gx.startsWith(i,n,s))return Wx(e,r),e;if(i.charAt(s)===n.slice(-1))return e;i=i.slice(s);let a=i.length,c=Fe.language(i,r);c.name&&(e.language=c.name,i=i.slice(c.raw.length));let u=i.indexOf(o);return u===-1&&(u=a),e.matter=i.slice(0,u),e.matter.replace(/^\s*#[^\n]+/gm,"").trim()===""?(e.isEmpty=!0,e.empty=e.content,e.data={}):e.data=IC(e.language,e.matter,r),u===a?e.content="":(e.content=i.slice(u+o.length),e.content[0]==="\r"&&(e.content=e.content.slice(1)),e.content[0]===` +`&&(e.content=e.content.slice(1))),Wx(e,r),(r.sections===!0||typeof r.section=="function")&&EC(e,r.section),e}Fe.engines=OC;Fe.stringify=function(e,t,r){return typeof e=="string"&&(e=Fe(e,r)),TC(e,t,r)};Fe.read=function(e,t){let r=PC.readFileSync(e,"utf8"),n=Fe(r,t);return n.path=e,n};Fe.test=function(e,t){return Gx.startsWith(e,vf(t).delimiters[0])};Fe.language=function(e,t){let n=vf(t).delimiters[0];Fe.test(e)&&(e=e.slice(n.length));let o=e.slice(0,e.search(/\r?\n/));return{raw:o,name:o?o.trim():""}};Fe.cache={};Fe.clearCache=function(){Fe.cache={}};Yx.exports=Fe});var ou=ui(require("node:process"),1);var I={};jf(I,{BIGINT_FORMAT_RANGES:()=>pi,CONSTANT_CATCH:()=>Kf,Class:()=>Ra,NUMBER_FORMAT_RANGES:()=>Zn,aborted:()=>pt,allowsEval:()=>Ma,assert:()=>mb,assertEqual:()=>ub,assertIs:()=>db,assertNever:()=>pb,assertNotEqual:()=>lb,assignProp:()=>Ye,attachSchema:()=>Ln,base64ToUint8Array:()=>Hf,base64urlToUint8Array:()=>Rb,cached:()=>Kr,captureStackTrace:()=>fi,cleanEnum:()=>Ib,cleanRegex:()=>Fn,clone:()=>dt,cloneDef:()=>yb,codePointLength:()=>Un,constantCatch:()=>Jf,createTransparentProxy:()=>Sb,defineLazy:()=>Mf,defineLazyInternal:()=>B,derived:()=>Db,esc:()=>ja,escapeRegex:()=>Ct,explicitlyAborted:()=>Za,extend:()=>zb,finalizeIssue:()=>mt,floatSafeRemainder:()=>Na,getElementAtPath:()=>_b,getEnumValues:()=>Hr,getLengthableOrigin:()=>Vn,getParsedType:()=>bb,getSizableOrigin:()=>Vf,hexToUint8Array:()=>Nb,hide:()=>gi,installLazyProp:()=>Zb,isObject:()=>yr,isPlainObject:()=>Wt,issue:()=>Wr,joinValues:()=>li,jsonStringifyReplacer:()=>Br,members:()=>Ua,merge:()=>Eb,mergeDefs:()=>Rt,normalizeParams:()=>A,nullish:()=>Ca,numKeys:()=>vb,objectClone:()=>hb,omit:()=>kb,optionalKeys:()=>Fa,own:()=>Jt,parsedType:()=>La,partial:()=>Tb,pick:()=>$b,prefixIssues:()=>Nt,primitiveTypes:()=>Lf,promiseAllObject:()=>wb,propertyKeyTypes:()=>qa,randomString:()=>xb,rawShape:()=>Jr,required:()=>Ob,safeExtend:()=>Pb,shallowClone:()=>Zf,sizeCaps:()=>hi,slugify:()=>Da,stringifyPrimitive:()=>di,toZod:()=>fb,uint8ArrayToBase64:()=>Bf,uint8ArrayToBase64url:()=>Cb,uint8ArrayToHex:()=>jb,unwrapMessage:()=>Vr});function ub(e){return e}function lb(e){return e}function fb(){return e=>e}function db(e){}function pb(e){throw new Error("Unexpected value in exhaustive check")}function mb(e){}function Hr(e){let t=Object.values(e).filter(n=>typeof n=="number");return Object.entries(e).filter(([n,o])=>t.indexOf(+n)===-1).map(([n,o])=>o)}function li(e,t="|"){return e.map(r=>di(r)).join(t)}function Br(e,t){return typeof t=="bigint"?t.toString():t}var Ia=class{constructor(t){this._getter=t,this._value=void 0}get value(){let t=this._getter;return t!==void 0&&(this._value=t(),this._getter=void 0),this._value}};function Kr(e){return new Ia(e)}function Ca(e){return e==null}function Fn(e){let t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function Na(e,t){let r=e/t,n=Math.round(r),o=4*Number.EPSILON*Math.max(Math.abs(r),1);return Math.abs(r-n){let a=t._zod.def.shape[i];return n?n(a,i):a}):Ff(e,i,n?n(s.value,i):s.value))}}function gb(e,t){for(let r of Reflect.ownKeys(t)){let n=Object.getOwnPropertyDescriptor(t,r);n.enumerable&&(n.get?qf(e,r,()=>t[r]):Ff(e,r,n.value))}}function Rt(...e){let t={};for(let r of e){let n=Object.getOwnPropertyDescriptors(r);Object.assign(t,n)}return Object.defineProperties({},t)}function yb(e){return Rt(e._zod.def)}function _b(e,t){return t?t.reduce((r,n)=>r?.[n],e):e}function wb(e){let t=Object.keys(e),r=t.map(n=>e[n]);return Promise.all(r).then(n=>{let o={};for(let i=0;i{};function yr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var Ma=Kr(()=>{if(Ze.jitless||typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let e=Function;return new e(""),!0}catch{return!1}});function Wt(e){if(yr(e)===!1)return!1;let t=e.constructor;if(t===void 0||typeof t!="function")return!0;let r=t.prototype;return!(yr(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function Zf(e){return Wt(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}function vb(e){let t=0;for(let r in e)Object.prototype.hasOwnProperty.call(e,r)&&t++;return t}var bb=e=>{let t=typeof e;switch(t){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(e)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(e)?"array":e===null?"null":e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?"promise":typeof Map<"u"&&e instanceof Map?"map":typeof Set<"u"&&e instanceof Set?"set":typeof Date<"u"&&e instanceof Date?"date":typeof File<"u"&&e instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${t}`)}},qa=new Set(["string","number","symbol"]),Lf=new Set(["string","number","bigint","boolean","symbol","undefined"]);function Ct(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function dt(e,t,r){let n=new e._zod.constr(t??e._zod.def);return(!t||r?.parent)&&(n._zod.parent=e),n}function A(e){let t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function Sb(e){let t;return new Proxy({},{get(r,n,o){return t??(t=e()),Reflect.get(t,n,o)},set(r,n,o,i){return t??(t=e()),Reflect.set(t,n,o,i)},has(r,n){return t??(t=e()),Reflect.has(t,n)},deleteProperty(r,n){return t??(t=e()),Reflect.deleteProperty(t,n)},ownKeys(r){return t??(t=e()),Reflect.ownKeys(t)},getOwnPropertyDescriptor(r,n){return t??(t=e()),Reflect.getOwnPropertyDescriptor(t,n)},defineProperty(r,n,o){return t??(t=e()),Reflect.defineProperty(t,n,o)}})}function di(e){return typeof e=="bigint"?e.toString()+"n":typeof e=="string"?`"${e}"`:`${e}`}function Fa(e){return Object.keys(e).filter(t=>e[t]._zod.optin!==void 0&&e[t]._zod.optout==="optional")}var Zn={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},pi={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function $b(e,t){let r=e._zod.def,n=r.checks;if(n&&n.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");let i={};return gr(i,e,mi(e,t)),dt(e,Rt(r,{shape:i,checks:[]}))}function mi(e,t){let r=It(e),n=[];for(let o of Reflect.ownKeys(t)){if(!Object.getOwnPropertyDescriptor(r,o)?.enumerable)throw new Error(`Unrecognized key: "${String(o)}"`);t[o]&&n.push(o)}return n}function kb(e,t){let r=e._zod.def,n=r.checks;if(n&&n.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");let i=new Set(mi(e,t)),s={};return gr(s,e,Reflect.ownKeys(It(e)).filter(a=>!i.has(a))),dt(e,Rt(r,{shape:s,checks:[]}))}function zb(e,t){if(!Wt(t))throw new Error("Invalid input to extend: expected a plain object");let r=e._zod.def.checks;if(r&&r.length>0){let o=It(e);for(let i of Reflect.ownKeys(t))if(Object.getOwnPropertyDescriptor(o,i)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}return dt(e,Rt(e._zod.def,{shape:Uf(e,t)}))}function Uf(e,t){let r={};return gr(r,e,Reflect.ownKeys(It(e))),gb(r,t),r}function Pb(e,t){if(!Wt(t))throw new Error("Invalid input to safeExtend: expected a plain object");return dt(e,Rt(e._zod.def,{shape:Uf(e,t)}))}function Eb(e,t){if(!t?._zod?.def)throw new Error("Invalid input to merge: expected an object schema. To merge a plain shape, use `.extend()`.");if(e._zod.def.checks?.length)throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let r={};gr(r,e,Reflect.ownKeys(It(e))),gr(r,t,Reflect.ownKeys(It(t)));let n=Rt(e._zod.def,{shape:r,get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return dt(e,n)}function Tb(e,t,r,n="partial"){let i=t._zod.def.checks;if(i&&i.length>0)throw new Error(`.${n}() cannot be used on object schemas containing refinements`);let a=r?new Set(mi(t,r)):void 0,c={};return gr(c,t,Reflect.ownKeys(It(t)),e&&((u,l)=>a&&!a.has(l)?u:new e({type:"optional",innerType:u}))),dt(t,Rt(t._zod.def,{shape:c,checks:[]}))}function Ob(e,t,r){let n=r?new Set(mi(t,r)):void 0,o={};return gr(o,t,Reflect.ownKeys(It(t)),(i,s)=>n&&!n.has(s)?i:new e({type:"nonoptional",innerType:i})),dt(t,Rt(t._zod.def,{shape:o}))}function pt(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r{var n;return(n=r).path??(n.path=[]),r.path.unshift(e),r})}function Vr(e){return typeof e=="string"?e:e?.message}function hi(e){let t=[];for(let r of e??[]){let n=r._zod.def;if(!/_(length|size)$|_equals$/.test(n.check))break;let o=n.maximum??n.length??n.size;o>=0&&t.push([o,r])}return t}function Ln(e,t,r){var n;for(let o=t;oNumber.isNaN(Number.parseInt(t,10))).map(t=>t[1])}function Hf(e){let t=atob(e),r=new Uint8Array(t.length);for(let n=0;nt.toString(16).padStart(2,"0")).join("")}var Ra=class{constructor(...t){}};function Ua(e,t){for(let r in t){let n=Object.getOwnPropertyDescriptor(t,r);n.get?Object.defineProperty(e,r,{...n,enumerable:!1}):Mb(e,r,n.value)}}function Jt(e,t,r,n=!0){return Object.defineProperty(e,t,{configurable:!0,writable:!0,enumerable:n,value:r}),r}function gi(e,t,r){return Jt(e,t,r,!1)}function Db(e,t){for(let r in e){let n=e[r];Object.defineProperty(t,r,{configurable:!0,enumerable:!0,get(){return Jt(this,r,n(this))},set(o){Jt(this,r,o)}})}return t}function Mb(e,t,r){Object.defineProperty(e,t,{configurable:!0,get(){return this==null?r:Jt(this,t,r.bind(this))},set(n){Jt(this,t,n)}})}function qb(e,t){let r=Object.getPrototypeOf(e);return t in r?void 0:r}var Aa,Kt=!1,Fb={configurable:!0,get(){Kt=!0}};function B(e,t,r){let n=Object.getPrototypeOf(e._zod);if(t in n&&Aa!==e._zod){Aa=void 0;return}Aa=e._zod,Object.defineProperty(n,t,{configurable:!0,get(){Object.defineProperty(this,t,Fb);let o=Kt;Kt=!1;try{let i=r(this);return Kt?delete this[t]:Object.defineProperty(this,t,{configurable:!0,writable:!0,value:i}),Kt=Kt||o,i}catch(i){throw delete this[t],Kt=Kt||o,i}},set(o){Object.defineProperty(this,t,{configurable:!0,writable:!0,value:o})}})}function Zb(e,t,r,n){let o=qb(e,t);o&&Object.defineProperty(o,t,{configurable:!0,get(){let i={configurable:!0,writable:!0,enumerable:n,value:void 0};return Object.defineProperty(this,t,i),i.value=r(this),Object.defineProperty(this,t,i),i.value},set(i){Object.defineProperty(this,t,{configurable:!0,writable:!0,enumerable:n,value:i})}})}var Kf="~constantCatch";function Jf(e){let t=()=>e;return t[Kf]=!0,t}var Wf;var Va={value:void 0,enumerable:!1},Gf="captureStackTrace"in Error?Error:null;function Lb(e){let t=Gf;if(t){let r=t.stackTraceLimit;if(typeof r=="number"){try{t.stackTraceLimit=0}catch{return Gf=null,new e}try{return new e}finally{t.stackTraceLimit=r}}}return new e}function w(e,t,r,n){let o={};function i(d){this.def=d,this.constr=f,this.traits=new Set}i.prototype=o;let s=r,a=s&&new WeakSet;function c(d,p){if(d._zod){if(d._zod.traits.has(e))return}else{Va.value=new i(p);try{Object.defineProperty(d,"_zod",Va)}finally{Va.value=void 0}}if(d._zod.traits.add(e),t(d,p),a){let h=Object.getPrototypeOf(d),g=d._zod.constr.prototype,y=h;for(;y&&y!==g;)y=Object.getPrototypeOf(y);let v=y??h;a.has(v)||(a.add(v),Ua(v,s))}let m=f.prototype;for(let h in m)Object.prototype.hasOwnProperty.call(m,h)&&(h in d||(d[h]=m[h].bind(d)))}let u=n?.Parent??Object;class l extends u{}Object.defineProperty(l,"name",{value:e});function f(d){let p=n?.Parent?Lb(l):this;c(p,d);let m=p._zod.deferred;if(m){for(let g of m)g();p._zod.deferred=void 0}let h=globalThis.__zod_globalConfig?.postProcessor;return h&&h(p),p}return Object.defineProperty(f,"init",{value:c}),Object.defineProperty(f,Symbol.hasInstance,{value:d=>n?.Parent&&d instanceof n.Parent?!0:d?._zod?.traits?.has(e)}),Object.defineProperty(f,"name",{value:e}),f}var ht=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},Gr=class extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}};(Wf=globalThis).__zod_globalConfig??(Wf.__zod_globalConfig={});var Ze=globalThis.__zod_globalConfig;function Xe(e){return e&&Object.assign(Ze,e),Ze}function Ub(){let e=this._zod;return e.message??(e.message=JSON.stringify(e.def,Br,2)),e.message}function Vb(e){this._zod.message=e}var Hb={get:Ub,set:Vb,enumerable:!0,configurable:!0},Ba={value:void 0,enumerable:!1},Yf=new WeakSet([Object.prototype,Error.prototype]),Xf=(e,t)=>{e.name="$ZodError",Ba.value=t,Object.defineProperty(e,"issues",Ba),Ba.value=void 0,Object.defineProperty(e,"message",Hb);let r=Object.getPrototypeOf(e);Yf.has(r)||(Yf.add(r),Object.defineProperty(r,"toString",{configurable:!0,enumerable:!1,get(){let n=()=>this.message;return Object.defineProperty(this,"toString",{value:n,configurable:!0,writable:!0}),n},set(n){Object.defineProperty(this,"toString",{value:n,configurable:!0,writable:!0})}}))},Qf=w("$ZodError",Xf),ed=w("$ZodError",Xf,void 0,{Parent:Error});function Bb(e,t,r){return Object.prototype.hasOwnProperty.call(e,t)||(t==="__proto__"?Object.defineProperty(e,t,{value:r(),writable:!0,enumerable:!0,configurable:!0}):e[t]=r()),e[t]}function td(e,t=r=>r.message){let r={},n=[];for(let o of e.issues)o.path.length>0?Bb(r,o.path[0],()=>[]).push(t(o)):n.push(t(o));return{formErrors:n,fieldErrors:r}}function rd(e,t=r=>r.message){let r={_errors:[]},n=(o,i=[])=>{for(let s of o.issues)if(s.code==="invalid_union"&&s.errors.length)s.errors.map(a=>n({issues:a},[...i,...s.path]));else if(s.code==="invalid_key")n({issues:s.issues},[...i,...s.path]);else if(s.code==="invalid_element")n({issues:s.issues},[...i,...s.path]);else{let a=[...i,...s.path];if(a.length===0)r._errors.push(t(s));else{let c=r,u=0;for(;u{let t=(r,n,o,i)=>{let s=o?{...o,async:!1}:{async:!1},a=r._zod.run({value:n,issues:[]},s);if(a instanceof Promise)throw new ht;if(a.issues.length){let c=new(i?.Err??e)(a.issues.map(u=>mt(u,s,Xe())));throw fi(c,i?.callee??t),c}return a.value};return t};var wi=e=>{let t=async(r,n,o,i)=>{let s=o?{...o,async:!0}:{async:!0},a=r._zod.run({value:n,issues:[]},s);if(a instanceof Promise&&(a=await a),a.issues.length){let c=new(i?.Err??e)(a.issues.map(u=>mt(u,s,Xe())));throw fi(c,i?.callee??t),c}return a.value};return t};var Hn=e=>(t,r,n)=>{let o=n?{...n,async:!1}:{async:!1},i=t._zod.run({value:r,issues:[]},o);if(i instanceof Promise)throw new ht;return i.issues.length?nd(e,i.issues,o):{success:!0,data:i.value}},Ka=Hn(ed);function nd(e,t,r){let n;return{success:!1,get error(){return n||(n=new e(t.map(o=>mt(o,r,Xe()))),t=void 0,r=void 0),n},set error(o){n=o,t=void 0,r=void 0}}}var xi=e=>async(t,r,n)=>{let o=n?{...n,async:!0}:{async:!0},i=t._zod.run({value:r,issues:[]},o);return i instanceof Promise&&(i=await i),i.issues.length?nd(e,i.issues,o):{success:!0,data:i.value}};var Jb=Symbol.for("zod.compile.invalid"),Wb=Symbol.for("zod.compile.fallback"),vi=((e,t,r)=>{let n=e._zod.bag.validator;if(n!==void 0){if(n(t)!==Jb)return!0;if(n.definite===!0&&r===void 0)return!1}return Gb(e,t,r)});function Gb(e,t,r){let n=r?{...r,async:!1,abortEarly:!0}:{async:!1,abortEarly:!0},o=e._zod.bag.fallbackRun,i;if(o?(n[Wb]=!0,i=o({value:t,issues:[]},n)):i=e._zod.run({value:t,issues:[]},n),i instanceof Promise)throw new ht;return i.issues.length===0}var bi=async(e,t,r)=>{let n=r?{...r,async:!0,abortEarly:!0}:{async:!0,abortEarly:!0},o=e._zod.run({value:t,issues:[]},n);return o instanceof Promise&&(o=await o),o.issues.length===0},od=e=>{let t=_i(e),r=(n,o,i,s)=>{let a=i?{...i,direction:"backward"}:{direction:"backward"};return t(n,o,a,yi(r,s))};return r};var id=e=>{let t=_i(e),r=(n,o,i,s)=>t(n,o,i,yi(r,s));return r};var sd=e=>{let t=wi(e),r=async(n,o,i,s)=>{let a=i?{...i,direction:"backward"}:{direction:"backward"};return await t(n,o,a,yi(r,s))};return r};var ad=e=>{let t=wi(e),r=async(n,o,i,s)=>await t(n,o,i,yi(r,s));return r};var cd=e=>(t,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return Hn(e)(t,r,o)};var ud=e=>(t,r,n)=>Hn(e)(t,r,n);var ld=e=>async(t,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return xi(e)(t,r,o)};var fd=e=>async(t,r,n)=>xi(e)(t,r,n);var dd=/^[cC][0-9a-z]{6,}$/,pd=/^[0-9a-z]+$/,md=/^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/,hd=/^[0-9a-vA-V]{20}$/,gd=/^[A-Za-z0-9]{27}$/,yd=/^[a-zA-Z0-9_-]{21}$/;function _d(e){return new RegExp(`^[a-zA-Z0-9_-]{${e}}$`)}var wd=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var xd=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,Wa=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;var vd=/^(?:[A-Za-z0-9_'+\-]+\.)*[A-Za-z0-9_'+\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var Yb="^(?=[\\s\\S]*[\\p{Extended_Pictographic}\\p{Regional_Indicator}\\u20E3])[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$";function bd(){return new RegExp(Yb,"u")}var Sd=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,$d=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/;var kd=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,zd=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Pd=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Ed=/^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-]{2,3})?$/;var Td=/^https?$/,Od=/^\+[1-9]\d{6,14}$/;var Ad="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))";function Xb(e){return new RegExp(`^${e}$`)}var Id=Xb(Ad);function Ja(e){let t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof e.precision=="number"?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:e.seconds?`${t}:[0-5]\\d(?:\\.\\d+)?`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function Rd(e){return new RegExp(`^${Ja(e)}$`)}function Cd(e){let t=["Z"];e.offset&&t.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let r=`${Ja({precision:e.precision,seconds:!0})}(?:${t.join("|")})`,n=e.local?`${r}|${Ja({precision:e.precision})}`:r;return new RegExp(`^${Ad}T(?:${n})$`)}var Nd=/^[\s\S]{0,}$/;var Ga=/^-?\d+$/,Bn=/^-?\d+(?:\.\d+)?$/,jd=/^(?:true|false)$/i,Dd=/^null$/i;var Md=/^[^A-Z]*$/,qd=/^[^a-z]*$/;var $e=w("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])});var Ya=e=>{let t=e.value;return!Ca(t)&&t.length!==void 0},Si={number:"number",bigint:"bigint",object:"date"},Xa=w("$ZodCheckLessThan",(e,t)=>{$e.init(e,t);let r=Si[typeof t.value];e._zod.check=n=>{(t.inclusive?n.value<=t.value:n.value{$e.init(e,t);let r=Si[typeof t.value];e._zod.check=n=>{(t.inclusive?n.value>=t.value:n.value>t.value)||n.issues.push({origin:Si[typeof n.value]??r,code:"too_small",minimum:typeof t.value=="object"?t.value.getTime():t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Fd=w("$ZodCheckMultipleOf",(e,t)=>{$e.init(e,t),e._zod.check=r=>{if(typeof r.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?t.value!==BigInt(0)&&r.value%t.value===BigInt(0):Na(r.value,t.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:t.value,input:r.value,inst:e,continue:!t.abort})}}),Zd=w("$ZodCheckNumberFormat",(e,t)=>{$e.init(e,t),t.format=t.format||"float64";let r=t.format?.includes("int"),n=r?"int":"number",[o,i]=Zn[t.format];e._zod.check=s=>{let a=s.value;if(r){if(!Number.isInteger(a)){s.issues.push({expected:n,format:t.format,code:"invalid_type",continue:!1,input:a,inst:e});return}if(!Number.isSafeInteger(a)){a>0?s.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,inclusive:!0,continue:!t.abort}):s.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,inclusive:!0,continue:!t.abort});return}}ai&&s.issues.push({origin:"number",input:a,code:"too_big",maximum:i,inclusive:!0,inst:e,continue:!t.abort})}});var Ld=w("$ZodCheckMaxLength",(e,t)=>{var r;$e.init(e,t),(r=e._zod.def).when??(r.when=Ya),e._zod.check=n=>{let o=n.value,i=o.length;if((typeof o=="string"&&i>t.maximum?Un(o):i)<=t.maximum)return;let a=Vn(o);n.issues.push({origin:a,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),Ud=w("$ZodCheckMinLength",(e,t)=>{var r;$e.init(e,t),(r=e._zod.def).when??(r.when=Ya),e._zod.check=n=>{let o=n.value,i=o.length;if((typeof o=="string"&&i>=t.minimum&&i=t.minimum)return;let a=Vn(o);n.issues.push({origin:a,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),Vd=w("$ZodCheckLengthEquals",(e,t)=>{var r;$e.init(e,t),(r=e._zod.def).when??(r.when=Ya),e._zod.check=n=>{let o=n.value,i=o.length,s=typeof o=="string"&&i>=t.length&&i<=t.length*2?Un(o):i;if(s===t.length)return;let a=Vn(o),c=s>t.length;n.issues.push({origin:a,...c?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),Jn=w("$ZodCheckStringFormat",(e,t)=>{var r,n;$e.init(e,t),t.pattern?(r=e._zod).check??(r.check=o=>{t.pattern.lastIndex=0,!t.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:t.format,input:o.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(n=e._zod).check??(n.check=()=>{})}),Hd=w("$ZodCheckRegex",(e,t)=>{Jn.init(e,t),e._zod.check=r=>{t.pattern.lastIndex=0,!t.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),Bd=w("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=Md),Jn.init(e,t)}),Kd=w("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=qd),Jn.init(e,t)}),Jd=w("$ZodCheckIncludes",(e,t)=>{$e.init(e,t);let r=Ct(t.includes),n=new RegExp(typeof t.position=="number"?`^.{${t.position},}${r}`:r);t.pattern=n,e._zod.check=o=>{o.value.includes(t.includes,t.position)||o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:o.value,inst:e,continue:!t.abort})}}),Wd=w("$ZodCheckStartsWith",(e,t)=>{$e.init(e,t);let r=new RegExp(`^${Ct(t.prefix)}.*`);t.pattern??(t.pattern=r),e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),Gd=w("$ZodCheckEndsWith",(e,t)=>{$e.init(e,t);let r=new RegExp(`.*${Ct(t.suffix)}$`);t.pattern??(t.pattern=r),e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}});var Yd=w("$ZodCheckOverwrite",(e,t)=>{$e.init(e,t),e._zod.check=r=>{r.value=t.tx(r.value)}});var $i=class{constructor(t=[],r={}){this.content=[],this.indent=0,this.args=t,this.closed=r}indented(t){this.indent+=1;try{t(this)}finally{this.indent-=1}}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}let n=t.split(` +`).filter(s=>s),o=Math.min(...n.map(s=>s.length-s.trimStart().length)),i=n.map(s=>s.slice(o)).map(s=>" ".repeat(this.indent*2)+s);for(let s of i)this.content.push(s)}compile(){let t=Function,r=this?.content??[""];return new t(...Object.keys(this.closed),`return function (${this.args.join(", ")}) { +${r.join(` +`)} +};`)(...Object.values(this.closed))}};var Qd={major:4,minor:6,patch:7};var ee=w("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Qd;let n=e._zod.def.checks,o=e._zod.traits.has("$ZodCheck")?[e,...n??[]]:n?.length?[...n]:[];for(let i of o)for(let s of i._zod.onattach)s(e);if(o.length===0)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let i=(a,c,u)=>{if(a.memo)return a;let l=pt(a),f;for(let d of c){if(d._zod.def.when){if(Za(a)||!d._zod.def.when(a))continue}else if(l)continue;let p=a.issues.length,m=d._zod.check(a);if(m instanceof Promise&&u?.async===!1)throw new ht;if(f||m instanceof Promise)f=(f??Promise.resolve()).then(async()=>{await m,a.issues.length!==p&&(Ln(a.issues,p,e),l||(l=pt(a,p)))});else{if(a.issues.length===p)continue;Ln(a.issues,p,e),l||(l=pt(a,p))}}return f?f.then(()=>a):a},s=(a,c,u)=>{if(pt(a))return a.aborted=!0,a;let l=i(c,o,u);if(l instanceof Promise){if(u.async===!1)throw new ht;return l.then(f=>e._zod.parse(f,u))}return e._zod.parse(l,u)};e._zod.run=(a,c)=>{if(c.skipChecks)return e._zod.parse(a,c);if(c.direction==="backward"){let l=e._zod.parse({value:a.value,issues:[]},{...c,skipChecks:!0});return l instanceof Promise?l.then(f=>s(f,a,c)):s(l,a,c)}let u=e._zod.parse(a,c);if(u instanceof Promise){if(c.async===!1)throw new ht;return u.then(l=>i(l,o,c))}return i(u,o,c)}}},{get"~standard"(){return gi(this,"~standard",tc(this))},set"~standard"(e){Jt(this,"~standard",e)}}),lp=(e,t)=>e.issues.length?{issues:e.issues.map(r=>mt(r,t,Xe()))}:{value:e.value};async function Qb(e,t){let r={async:!0};return lp(await e._zod.run({value:t,issues:[]},r),r)}function tc(e){return{validate:t=>{let r={async:!1};try{let n=e._zod.run({value:t,issues:[]},r);if(!(n instanceof Promise))return lp(n,r)}catch{}return Qb(e,t)},vendor:"zod",version:1}}var Ei=w("$ZodString",(e,t)=>{ee.init(e,t),e._zod.pattern=t.pattern??Nd,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:e}),r}}),te=w("$ZodStringFormat",(e,t)=>{Jn.init(e,t),Ei.init(e,t)}),fp=w("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=xd),te.init(e,t)}),dp=w("$ZodUUID",(e,t)=>{if(t.version){let n={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(n===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=Wa(n))}else t.pattern??(t.pattern=Wa());te.init(e,t)}),pp=w("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=vd),te.init(e,t)}),mp=1,zi=2;function hp(e){try{return typeof URL<"u"&&typeof URL.canParse=="function"?URL.canParse(e):(new URL(e),!0)}catch{return!1}}function eS(e,t){return!("normalize"in t)&&!("hostname"in t)&&!("protocol"in t)?hp(e)||zi:tS(e,t)}function tS(e,t){if(!t.normalize&&t.protocol?.source===Td.source&&!/^https?:\/\//i.test(e))return mp;try{if(typeof URL<"u"){let r=URL;if(typeof r.parse=="function")return r.parse(e)??zi}return new URL(e)}catch{return zi}}var rS=/[\t\n\r]/g;function ep(e){return e.replace(rS,"")}function nS(e,t){return t.lastIndex=0,t.test(e.hostname)}function oS(e,t){return t.lastIndex=0,t.test(e.protocol.endsWith(":")?e.protocol.slice(0,-1):e.protocol)}var gp=w("$ZodURL",(e,t)=>{te.init(e,t),e._zod.check=r=>{try{let n=r.value.trim(),o=eS(n,t);if(o===mp){r.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:r.value,inst:e,continue:!t.abort});return}if(o===zi){r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:e,continue:!t.abort});return}if(o===!0){r.value=ep(n);return}t.hostname&&!nS(o,t.hostname)&&r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:r.value,inst:e,continue:!t.abort}),t.protocol&&!oS(o,t.protocol)&&r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:r.value,inst:e,continue:!t.abort}),r.value=t.normalize?o.href:ep(n);return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:e,continue:!t.abort})}}}),yp=w("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=bd()),te.init(e,t)}),_p=w("$ZodNanoID",(e,t)=>{if(t.length!==void 0&&(!Number.isInteger(t.length)||t.length<1))throw new Error(`Invalid nanoid length: ${t.length}`);t.pattern??(t.pattern=t.length===void 0?yd:_d(t.length)),te.init(e,t)}),wp=w("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=dd),te.init(e,t)}),xp=w("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=pd),te.init(e,t)}),vp=w("$ZodULID",(e,t)=>{t.pattern??(t.pattern=md),te.init(e,t)}),bp=w("$ZodXID",(e,t)=>{t.pattern??(t.pattern=hd),te.init(e,t)}),Sp=w("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=gd),te.init(e,t)}),$p=w("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=Cd(t)),te.init(e,t)}),kp=w("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=Id),te.init(e,t)}),zp=w("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=Rd(t)),te.init(e,t)}),Pp=w("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=wd),te.init(e,t)}),Ep=w("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=Sd),te.init(e,t)}),iS=/^[0-9a-fA-F:.]+$/;function Tp(e){return iS.test(e)?hp(`http://[${e}]`):!1}var Op=w("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=$d),te.init(e,t),e._zod.check=r=>{Tp(r.value)||r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:e,continue:!t.abort})}});var Ap=w("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=kd),te.init(e,t)});function sS(e){let t=e.split("/");if(t.length!==2)return!1;let[r,n]=t;if(!n)return!1;let o=Number(n);return`${o}`!==n||o<0||o>128?!1:Tp(r)}var Ip=w("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=zd),te.init(e,t),e._zod.check=r=>{sS(r.value)||r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:e,continue:!t.abort})}});function Rp(e){if(e==="")return!0;if(/\s/.test(e)||e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}var rc=/^[0-9a-zA-Z+/]*={0,2}$/,Cp=w("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=rc),te.init(e,t),e._zod.check=r=>{Rp(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}}),Ti=/^[A-Za-z0-9_-]*$/;function aS(e){if(!Ti.test(e))return!1;let t=e.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=t.padEnd(Math.ceil(t.length/4)*4,"=");return Rp(r)}var Np=w("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=Ti),te.init(e,t),e._zod.check=r=>{aS(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),jp=w("$ZodE164",(e,t)=>{t.pattern??(t.pattern=Od),te.init(e,t)});function cS(e,t=null){try{let r=e.split(".");if(r.length!==3)return!1;let[n]=r;if(!n)return!1;let o=JSON.parse(atob(n));return!("typ"in o&&o?.typ!=="JWT"||!o.alg||t&&(!("alg"in o)||o.alg!==t))}catch{return!1}}var Dp=w("$ZodJWT",(e,t)=>{te.init(e,t),e._zod.check=r=>{cS(r.value,t.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}});var nc=w("$ZodNumber",(e,t)=>{ee.init(e,t),e._zod.pattern=Bn,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=Number(r.value)}catch{}let o=r.value;if(typeof o=="number"&&!Number.isNaN(o)&&Number.isFinite(o))return r;let i=typeof o=="number"?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:String(o):void 0;return r.issues.push({expected:"number",code:"invalid_type",input:o,inst:e,...i?{received:i}:{}}),r}}),Mp=w("$ZodNumberFormat",(e,t)=>{Zd.init(e,t),nc.init(e,t)}),qp=w("$ZodBoolean",(e,t)=>{ee.init(e,t),e._zod.pattern=jd,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=!!r.value}catch{}let o=r.value;return typeof o=="boolean"||r.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:e}),r}});var Fp=w("$ZodNull",(e,t)=>{ee.init(e,t),e._zod.pattern=Dd,e._zod.values=new Set([null]),e._zod.parse=(r,n)=>{let o=r.value;return o===null||r.issues.push({expected:"null",code:"invalid_type",input:o,inst:e}),r}});var Zp=w("$ZodUnknown",(e,t)=>{ee.init(e,t),e._zod.parse=r=>r}),Lp=w("$ZodNever",(e,t)=>{ee.init(e,t),e._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:e}),r)});function uS(e,t){let r=hi(e._zod.def.checks);if(!r.length)return;let n=Math.min(...r.map(i=>i[0])),o=e._zod.parse;e._zod.parse=(i,s)=>{let a=t(i.value);if(a>n&&!s?.skipChecks&&s?.direction!=="backward"){for(let[c,u]of hi(e._zod.def.checks))if(a>c&&u._zod.def.when(i)){let l=i.issues.length;return u._zod.check(i),i.issues[l].continue=!1,Ln(i.issues,l,e),i}}return o(i,s)}}var lS=e=>Array.isArray(e)?e.length:-1;function tp(e,t,r){e.issues.length&&t.issues.push(...Nt(r,e.issues)),t.value[r]=e.value}var Up=w("$ZodArray",(e,t)=>{ee.init(e,t);let r=Ze.memoizer;r?.attach(e),e._zod.parse=(n,o)=>{let i=n.value;if(!Array.isArray(i))return n.issues.push({expected:"array",code:"invalid_type",input:i,inst:e}),n;n.value=r?r.alloc(e,n,Array(i.length),o):Array(i.length);let s=[],a=o?.abortEarly;for(let c=0;ctp(f,n,c)));else if(tp(l,n,c),a&&l.issues.length!==0&&pt(l))break}return s.length?Promise.all(s).then(()=>n):n},uS(e,lS)});function Pi(e,t,r,n,o,i){let s=r in n,a=i==="optional";if(!(!s&&a&&o==="optional")){if(e.issues.length){if(o!==void 0&&a&&!s)return;t.issues.push(...Nt(r,e.issues))}if(!s&&o===void 0){e.issues.length||t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[r]});return}e.value===void 0?(s||o==="defaulted"&&!a)&&(t.value[r]=void 0):t.value[r]=e.value}}var fS=[];function Vp(e){let t=Object.keys(e.shape),r=Object.getOwnPropertySymbols(e.shape),n=r.length?r:fS,o=n.length?[...t,...n]:t;for(let s of o)if(!e.shape?.[s]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${String(s)}": expected a Zod schema`);let i=Fa(e.shape);return{...e,allKeys:o,symbolKeys:n,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(i)}}function Hp(e,t,r,n,o,i,s){let a=[],c=o.keySet,u=o.catchall._zod,l=u.def.type,f=u.optin,d=u.optout,p=0;for(let m in t){if(s&&r.issues.length!==p){if(pt(r,p))break;p=r.issues.length}if(c.has(m))continue;if(m==="__proto__"){l==="never"&&a.push(m);continue}if(l==="never"){a.push(m);continue}let h=u.run({value:t[m],issues:[]},n);h instanceof Promise?e.push(h.then(g=>Pi(g,r,m,t,f,d))):Pi(h,r,m,t,f,d)}return a.length&&r.issues.push({code:"unrecognized_keys",keys:a,input:t,inst:i,continue:!0}),e.length?Promise.all(e).then(()=>r):r}var dS=w("$ZodObject",(e,t)=>{ee.init(e,t);let r=Object.getOwnPropertyDescriptor(t,"shape"),n=r?.get?r.get.raw:t.shape??{};if(n){let u=()=>{let l={...n};return Object.defineProperty(t,"shape",{value:l}),u.raw=l,l};u.raw=n,Object.defineProperty(t,"shape",{get:u})}let o=Kr(()=>Vp(t));B(e,"propValues",u=>{let l=u.def.shape,f={};for(let d in l){let p=l[d]._zod;if(p.values){Object.prototype.hasOwnProperty.call(f,d)||Ye(f,d,new Set);for(let m of p.values)f[d].add(m);p.optin!==void 0&&f[d].add(void 0)}}return f});let i=yr,s=t.catchall,a,c=Ze.memoizer;c?.attach(e),e._zod.parse=(u,l)=>{a??(a=o.value);let f=u.value;if(!i(f))return u.issues.push({expected:"object",code:"invalid_type",input:f,inst:e}),u;u.value=c?c.alloc(e,u,{},l):{};let d=[],p=a.shape,m=l?.abortEarly,h=u.issues.length;for(let g of a.allKeys){if(m&&u.issues.length!==h){if(pt(u,h))break;h=u.issues.length}if(g==="__proto__")continue;let y=p[g],v=y._zod.optin,S=y._zod.optout,k=y._zod.run({value:f[g],issues:[]},l);k instanceof Promise?d.push(k.then($=>Pi($,u,g,f,v,S))):Pi(k,u,g,f,v,S)}return s?Hp(d,f,u,l,o.value,e,m===!0):d.length?Promise.all(d).then(()=>u):u}}),Bp=w("$ZodObjectJIT",(e,t)=>{dS.init(e,t);let r=e._zod.parse,n=Kr(()=>Vp(t)),o=Ze.memoizer,i=p=>{let m=n.value,h=m.symbolKeys,g=new $i(["payload","ctx"],{shape:p,inst:e,memo:o,syms:h}),y=$=>`shape[${$}]._zod.run({ value: input[${$}], issues: [] }, ctx)`,v=($,b)=>` + let ${$}_ab = false; + for (let i = 0; i < ${$}.issues.length; i++) { + const iss = ${$}.issues[i]; + iss.path = iss.path ? [${b}, ...iss.path] : [${b}]; + payload.issues.push(iss); + if (iss.continue !== true) ${$}_ab = true; + } + if (${$}_ab && ctx && ctx.abortEarly) { + payload.value = newResult; + return payload; + }`;g.write("const input = payload.value;");let S=Object.create(null),k=0;for(let $ of m.allKeys)S[$]=`key_${k++}`;g.write(o?"const newResult = memo.alloc(inst, payload, {}, ctx);":"const newResult = {};");for(let $ of m.allKeys){if($==="__proto__")continue;let b=S[$],T=typeof $=="symbol"?`syms[${h.indexOf($)}]`:ja($),F=`${T} in input`,me=p[$],ft=me?._zod?.optin,Bt=ft!==void 0,hr=me?._zod?.optout==="optional";if(g.write(`const ${b} = ${y(T)};`),Bt&&hr){let ci=ft==="optional"?`${b}_present`:`${b}.value !== undefined || ${b}_present`;g.write(` + const ${b}_present = ${F}; + if (!${b}.issues.length || ${b}_present) { + if (${b}.issues.length) {${v(b,T)} + } + + if (${ci}) { + newResult[${T}] = ${b}.value; + } + } + + `)}else Bt?(g.write(` + if (${b}.issues.length) {${v(b,T)} + } + `),ft==="defaulted"?g.write(`newResult[${T}] = ${b}.value;`):g.write(` + if (${b}.value !== undefined || ${F}) { + newResult[${T}] = ${b}.value; + } + `)):g.write(` + const ${b}_present = ${F}; + if (${b}.issues.length) {${v(b,T)} + } + if (!${b}_present && !${b}.issues.length) { + payload.issues.push({ + code: "invalid_type", + expected: "nonoptional", + input: undefined, + path: [${T}] + }); + if (ctx && ctx.abortEarly) { + payload.value = newResult; + return payload; + } + } + + if (${b}_present) { + newResult[${T}] = ${b}.value; + } + + `)}return g.write("payload.value = newResult;"),g.write("return payload;"),g.compile()},s,a=yr,c=!Ze.jitless,l=c&&Ma.value,f=t.catchall,d;e._zod.parse=(p,m)=>{d??(d=n.value);let h=p.value;return a(h)?c&&l&&m?.async===!1&&m.jitless!==!0?(s||(s=i(t.shape)),p=s(p,m),f?Hp([],h,p,m,d,e,m?.abortEarly===!0):p):r(p,m):(p.issues.push({expected:"object",code:"invalid_type",input:h,inst:e}),p)}});function rp(e,t,r,n){for(let i of e)if(i.issues.length===0)return t.value=i.value,t;let o=e.filter(i=>!pt(i));return o.length===1?(t.value=o[0].value,o[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map(i=>i.issues.map(s=>mt(s,n,Xe())))}),t)}var oc=w("$ZodUnion",(e,t)=>{ee.init(e,t),B(e,"optin",n=>n.def.options.some(o=>o._zod.optin==="defaulted")?"defaulted":n.def.options.some(o=>o._zod.optin!==void 0)?"optional":void 0),B(e,"optout",n=>n.def.options.some(o=>o._zod.optout==="optional")?"optional":void 0),B(e,"values",n=>{if(n.def.options.every(o=>o._zod.values))return new Set(n.def.options.flatMap(o=>Array.from(o._zod.values)))}),B(e,"pattern",n=>{if(n.def.options.every(o=>o._zod.pattern)){let o=n.def.options.map(i=>i._zod.pattern);return new RegExp(`^(${o.map(i=>Fn(i.source)).join("|")})$`)}});let r=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(n,o)=>{if(r)return r(n,o);let i=!1,s=[];for(let a of t.options){let c=a._zod.run({value:n.value,issues:[]},o);if(c instanceof Promise)s.push(c),i=!0;else{if(c.issues.length===0)return c;s.push(c)}}return i?Promise.all(s).then(a=>rp(a,n,e,o)):rp(s,n,e,o)}});function pS(e){let t=new Map;for(let r of e.options){let n=r._zod.propValues?.[e.discriminator];if(!n||n.size===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(r)}"`);for(let o of n)if(t.has(o)){if(o!==void 0)throw new Error(`Duplicate discriminator value "${String(o)}"`);t.set(o,null)}else t.set(o,r)}return t}var Kp=w("$ZodDiscriminatedUnion",(e,t)=>{t.inclusive=!1,oc.init(e,t);let r=e._zod.parse;B(e,"propValues",o=>{let i={},s=0;for(let a of o.def.options){let c=a._zod.propValues;if(!c||Object.keys(c).length===0)throw new Error(`Invalid discriminated union option at index "${o.def.options.indexOf(a)}"`);c[o.def.discriminator]?.has(void 0)&&s++;for(let[u,l]of Object.entries(c)){Object.prototype.hasOwnProperty.call(i,u)||Ye(i,u,new Set);for(let f of l)i[u].add(f)}}return!o.def.unionFallback&&s>1&&i[o.def.discriminator]?.delete(void 0),i}),t.options.forEach((o,i)=>{let s=Jr(o._zod.def);if(s&&!Object.prototype.hasOwnProperty.call(s,t.discriminator))throw new Error(`Invalid discriminated union option at index "${i}"`)});let n=Kr(()=>pS(t));e._zod.parse=(o,i)=>{let s=o.value;if(!yr(s))return o.issues.push({code:"invalid_type",expected:"object",input:s,inst:e}),o;let a=s?.[t.discriminator],c=n.value.get(a);return c&&(a!==void 0||i.direction!=="backward")?c._zod.run(o,i):t.unionFallback||i.direction==="backward"?r(o,i):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:t.discriminator,options:Array.from(n.value.keys()).filter(u=>n.value.get(u)!==null),input:s,path:[t.discriminator],inst:e}),o)}}),Jp=w("$ZodIntersection",(e,t)=>{ee.init(e,t),e._zod.parse=(r,n)=>{let o=r.value,i=t.left._zod.run({value:o,issues:[]},n),s=t.right._zod.run({value:o,issues:[]},n);return i instanceof Promise||s instanceof Promise?Promise.all([i,s]).then(([c,u])=>np(r,c,u)):np(r,i,s)}});function ec(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(Wt(e)&&Wt(t)){let r=Object.keys(t),n=Object.keys(e).filter(i=>r.indexOf(i)!==-1),o={...e,...t};Object.prototype.hasOwnProperty.call(o,"__proto__")&&delete o.__proto__;for(let i of n){if(i==="__proto__")continue;let s=ec(e[i],t[i]);if(!s.valid)return{valid:!1,mergeErrorPath:[i,...s.mergeErrorPath]};o[i]=s.data}return{valid:!0,data:o}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let r=[];for(let n=0;n{let f;if(u.code==="unrecognized_keys"&&!u.path?.length)o??(o=u),f=u.keys;else if(u.code==="invalid_key"&&u.origin==="record"&&u.path?.length===1){let d=String(u.path[0]);i.has(d)||i.set(d,u),f=[d]}else return!1;for(let d of f)n.has(d)||n.set(d,{}),n.get(d)[l]=!0;return!0};for(let u of t.issues)s(u,"l")||e.issues.push(u);for(let u of r.issues)s(u,"r")||e.issues.push(u);let a=[...n].filter(([,u])=>u.l&&u.r).map(([u])=>u);if(a.length){let u=o?a.filter(l=>o.keys.includes(l)):[];u.length&&e.issues.push({...o,keys:u});for(let l of a)!u.includes(l)&&i.has(l)&&e.issues.push(i.get(l))}let c=ec(t.value,r.value);if(!c.valid){if(pt(e))return e;throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(c.mergeErrorPath)}`)}return e.value=c.data,e}var Wp=w("$ZodRecord",(e,t)=>{ee.init(e,t);let r=Ze.memoizer;r?.attach(e),e._zod.parse=(n,o)=>{let i=n.value;if(!Wt(i))return n.issues.push({expected:"record",code:"invalid_type",input:i,inst:e}),n;let s=[],a=t.keyType._zod.values;if(a&&!t.partial){n.value=r?r.alloc(e,n,{},o):{};let c=new Set;for(let l of a)if(typeof l=="string"||typeof l=="number"||typeof l=="symbol"){if(c.add(typeof l=="number"?l.toString():l),l==="__proto__")continue;let f=t.keyType._zod.run({value:l,issues:[]},o);if(f instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(f.issues.length){n.issues.push({code:"invalid_key",origin:"record",issues:f.issues.map(m=>mt(m,o,Xe())),input:l,path:[l],inst:e});continue}let d=f.value;if(d==="__proto__")continue;let p=t.valueType._zod.run({value:i[l],issues:[]},o);p instanceof Promise?s.push(p.then(m=>{m.issues.length&&n.issues.push(...Nt(l,m.issues)),n.value[d]=m.value})):(p.issues.length&&n.issues.push(...Nt(l,p.issues)),n.value[d]=p.value)}let u;for(let l in i)if(!c.has(l))if(t.mode==="loose"){if(l==="__proto__")continue;n.value[l]=i[l]}else u=u??[],u.push(l);u&&u.length>0&&n.issues.push({code:"unrecognized_keys",input:i,inst:e,keys:u,continue:!0})}else{n.value=r?r.alloc(e,n,{},o):{};let c;for(let u of Reflect.ownKeys(i)){if(u==="__proto__"||!Object.prototype.propertyIsEnumerable.call(i,u))continue;let l=t.keyType._zod.run({value:u,issues:[]},o);if(l instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(typeof u=="string"&&Bn.test(u)&&l.issues.length){let m=t.keyType._zod.run({value:Number(u),issues:[]},o);if(m instanceof Promise)throw new Error("Async schemas not supported in object keys currently");m.issues.length===0&&(l=m)}if(l.issues.length){t.mode==="loose"?n.value[u]=i[u]:a?(c=c??[],c.push(u)):n.issues.push({code:"invalid_key",origin:"record",issues:l.issues.map(m=>mt(m,o,Xe())),input:u,path:[u],inst:e});continue}let d=l.value;if(d==="__proto__")continue;let p=t.valueType._zod.run({value:i[u],issues:[]},o);p instanceof Promise?s.push(p.then(m=>{m.issues.length&&n.issues.push(...Nt(u,m.issues)),n.value[d]=m.value})):(p.issues.length&&n.issues.push(...Nt(u,p.issues)),n.value[d]=p.value)}c&&c.length>0&&n.issues.push({code:"unrecognized_keys",input:i,inst:e,keys:c,continue:!0})}return s.length?Promise.all(s).then(()=>n):n}});var Gp=w("$ZodEnum",(e,t)=>{ee.init(e,t);let r=Hr(t.entries),n=new Set(r);e._zod.values=n,B(e,"pattern",o=>{let i=Hr(o.def.entries).filter(s=>qa.has(typeof s));return new RegExp(i.length?`^(${i.map(s=>Ct(s.toString())).join("|")})$`:"^[^\\s\\S]$")}),e._zod.parse=(o,i)=>{let s=o.value;return n.has(s)||o.issues.push({code:"invalid_value",values:r,input:s,inst:e}),o}}),Yp=w("$ZodLiteral",(e,t)=>{ee.init(e,t);let r=new Set(t.values);e._zod.values=r,B(e,"pattern",n=>{let o=n.def.values;return new RegExp(o.length?`^(${o.map(i=>typeof i=="string"?Ct(i):i?Ct(i.toString()):String(i)).join("|")})$`:"^[^\\s\\S]$")}),e._zod.parse=(n,o)=>{let i=n.value;return r.has(i)||n.issues.push({code:"invalid_value",values:t.values,input:i,inst:e}),n}});var Xp=w("$ZodTransform",(e,t)=>{ee.init(e,t),e._zod.optin="optional",Ze.memoizer?.guard(e),e._zod.parse=(r,n)=>{if(n.direction==="backward")throw new Gr(e.constructor.name);let o=t.transform(r.value,r);if(n.async)return(o instanceof Promise?o:Promise.resolve(o)).then(s=>(r.value=s,r));if(o instanceof Promise)throw new ht;return r.value=o,r}});function op(e,t){return e.value=t.issues.length?void 0:t.value,e}var ic=w("$ZodOptional",(e,t)=>{ee.init(e,t),B(e,"optin",r=>r.def.innerType._zod.optin==="defaulted"?"defaulted":"optional"),e._zod.optout="optional",B(e,"values",r=>{let n=r.def.innerType._zod.values;return n?new Set([...n,void 0]):void 0}),B(e,"pattern",r=>{let n=r.def.innerType._zod.pattern;return n?new RegExp(`^(${Fn(n.source)})?$`):void 0}),e._zod.parse=(r,n)=>{if(r.value===void 0){if(t.innerType._zod.optin!=="defaulted")return r;let o=t.innerType._zod.run({value:r.value,issues:[]},n);return o instanceof Promise?o.then(i=>op(r,i)):op(r,o)}return t.innerType._zod.run(r,n)}}),Qp=w("$ZodExactOptional",(e,t)=>{ic.init(e,t),B(e,"values",r=>r.def.innerType._zod.values),B(e,"pattern",r=>r.def.innerType._zod.pattern),e._zod.parse=(r,n)=>t.innerType._zod.run(r,n)}),em=w("$ZodNullable",(e,t)=>{ee.init(e,t),B(e,"optin",r=>r.def.innerType._zod.optin),B(e,"optout",r=>r.def.innerType._zod.optout),B(e,"pattern",r=>{let n=r.def.innerType._zod.pattern;return n?new RegExp(`^(${Fn(n.source)}|null)$`):void 0}),B(e,"values",r=>r.def.innerType._zod.values?new Set([...r.def.innerType._zod.values,null]):void 0),e._zod.parse=(r,n)=>r.value===null?r:t.innerType._zod.run(r,n)}),tm=w("$ZodDefault",(e,t)=>{ee.init(e,t),e._zod.optin="defaulted",B(e,"values",r=>r.def.innerType._zod.values),e._zod.parse=(r,n)=>{if(n.direction==="backward")return t.innerType._zod.run(r,n);if(r.value===void 0)return r.value=t.defaultValue,r;let o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(i=>ip(i,t)):ip(o,t)}});function ip(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}var rm=w("$ZodPrefault",(e,t)=>{ee.init(e,t),e._zod.optin="defaulted",B(e,"values",r=>r.def.innerType._zod.values),e._zod.parse=(r,n)=>(n.direction==="backward"||r.value===void 0&&(r.value=t.defaultValue),t.innerType._zod.run(r,n))}),nm=w("$ZodNonOptional",(e,t)=>{ee.init(e,t),B(e,"values",r=>{let n=r.def.innerType._zod.values;return n?new Set([...n].filter(o=>o!==void 0)):void 0}),e._zod.parse=(r,n)=>{let o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(i=>sp(i,e)):sp(o,e)}});function sp(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}function ap(e,t,r,n){return t.issues.length?(e.value=r.catchValue({...t,value:e.value,error:{issues:t.issues.map(o=>mt(o,n,Xe()))},input:e.value}),e):(e.value=t.value,t.memo&&(e.memo=!0),e)}var om=w("$ZodCatch",(e,t)=>{ee.init(e,t),B(e,"optin",r=>r.def.innerType._zod.optin==="defaulted"?"defaulted":"optional"),B(e,"optout",r=>r.def.innerType._zod.optout),B(e,"values",r=>r.def.innerType._zod.values),e._zod.parse=(r,n)=>{if(n.direction==="backward")return t.innerType._zod.run(r,n);let o=t.innerType._zod.run({value:r.value,issues:[]},n);return o instanceof Promise?o.then(i=>ap(r,i,t,n)):ap(r,o,t,n)}});var sc=w("$ZodPipe",(e,t)=>{ee.init(e,t),B(e,"values",r=>r.def.in._zod.values),B(e,"optin",r=>r.def.in._zod.optin),B(e,"optout",r=>r.def.out._zod.optout),B(e,"propValues",r=>r.def.in._zod.propValues),e._zod.parse=(r,n)=>{if(n.direction==="backward"){let i=t.out._zod.run(r,n);return i instanceof Promise?i.then(s=>ki(s,t.in,n)):ki(i,t.in,n)}let o=t.in._zod.run(r,n);return o instanceof Promise?o.then(i=>ki(i,t.out,n)):ki(o,t.out,n)}});function ki(e,t,r){return e.issues.some(n=>n.code!=="unrecognized_keys")?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues},r)}var im=w("$ZodPreprocess",(e,t)=>{sc.init(e,t)}),sm=w("$ZodReadonly",(e,t)=>{ee.init(e,t),B(e,"propValues",r=>r.def.innerType._zod.propValues),B(e,"values",r=>r.def.innerType._zod.values),B(e,"optin",r=>r.def.innerType?._zod?.optin),B(e,"optout",r=>r.def.innerType?._zod?.optout),e._zod.parse=(r,n)=>{if(n.direction==="backward")return t.innerType._zod.run(r,n);let o=t.innerType._zod.run(r,n);return o instanceof Promise?o.then(cp):cp(o)}});function cp(e){return e.memo||(e.value=Object.freeze(e.value)),e}var am=w("$ZodCustom",(e,t)=>{$e.init(e,t),ee.init(e,t),e._zod.parse=(r,n)=>r,e._zod.check=r=>{let n=r.value,o=t.fn(n);if(o instanceof Promise)return o.then(i=>up(i,r,n,e));up(o,r,n,e)}});function up(e,t,r,n){if(!e){let o={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(o.params=n._zod.def.params),t.issues.push(Wr(o))}}var cc=class extends Error{constructor(){super("Cannot parse a reference cycle that closes through a transform"),this.name="ZodCyclicError"}},uc="~memo",cm=[];function um(e){return e!==null&&typeof e=="object"}function ac(e){return e.map(t=>t.path?{...t,path:t.path.slice()}:{...t})}var lm=new WeakMap,Wn=0,Ii=1,Gn=2;function Ri(e,t,r){let n=lm.get(e);if(n!==void 0)return n?Gn:Wn;if(t.has(e))return Gn;t.add(e);let o=Wn,i=l=>{if(o!==Gn&&l?._zod){let f=Ri(l,t,r);f>o&&(o=f)}},s=(l,f)=>{let d=Wn;for(let p of Reflect.ownKeys(l)){let m=Object.getOwnPropertyDescriptor(l,p);if(f&&!m.enumerable)continue;let h=m.get?Ii:m.value?._zod?Ri(m.value,t,r):Wn;h>d&&(d=h)}return d},a=l=>{l>o&&(o=l)},c=e._zod.def,u=c.type;switch(u){case"object":{let l=Jr(c);a(l?s(l,!0):Ii),i(c.catchall);break}case"array":i(c.element);break;case"tuple":for(let l of c.items)i(l);i(c.rest);break;case"record":case"map":i(c.keyType),i(c.valueType);break;case"set":i(c.valueType);break;case"union":for(let l of c.options)i(l);break;case"intersection":i(c.left),i(c.right);break;case"optional":case"nullable":case"default":case"prefault":case"catch":case"readonly":case"nonoptional":case"promise":case"success":i(c.innerType);break;case"pipe":i(c.in),i(c.out);break;case"function":i(c.input),i(c.output);break;case"lazy":{let l=c._cachedInner??(r?e._zod.innerType:void 0);a(l?Ri(l,t,!1):Ii);break}case"template_literal":case"string":case"number":case"int":case"boolean":case"bigint":case"symbol":case"undefined":case"null":case"void":case"never":case"any":case"unknown":case"date":case"nan":case"enum":case"literal":case"file":case"transform":case"custom":break;default:for(let l in c){let f=Object.getOwnPropertyDescriptor(c,l);if(!f||f.get)continue;let d=f.value;if(!(!d||typeof d!="object")){if(d._zod)i(d);else if(Array.isArray(d))for(let p of d)i(p)}}}return t.delete(e),mS(e,o)}function mS(e,t){return t!==Ii&&lm.set(e,t===Gn),t}function hS(e,t){let r=e.buckets.get(t);return r||(r=new WeakMap,e.buckets.set(t,r)),r}var Oi,Ai=[],gS={alloc(e,t,r){let n=Oi;if(!n)return r;Oi=void 0;let o={value:r,issues:null};return n.set(t.value,o),Ai.push(o),r},guard(e){var t;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{let r=e._zod.parse,n=(o,i)=>{if(i.direction!=="backward"&&yS(i,o.value))throw new cc;return r(o,i)};e._zod.parse=n,e._zod.run===r&&(e._zod.run=n)})},attach(e){var t;let r,n=!1,o,i;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{let s=e._zod.parse,a=(c,u)=>{if(r===void 0){let y=Ri(e,new Set,!1);if(y===Wn)return e._zod.parse=s,e._zod.run===a&&(e._zod.run=s),s(c,u);y===Gn||n?r=!0:n=!0}let l=c.value;if(!um(l))return s(c,u);let f=u[uc];f||(f={buckets:new WeakMap,backEdges:void 0},u[uc]=f);let d;o===u?d=i:(d=hS(f,e),o=u,i=d);let p=d.get(l);if(p)return c.value=p.value,p.issues?p.issues.length&&c.issues.push(...ac(p.issues)):(c.memo=!0,f.backEdges??(f.backEdges=new WeakSet),f.backEdges.add(p.value)),c;Oi=d;let m=Ai.length,h=s(c,u);Oi=void 0;let g=Ai.length>m?Ai.pop():void 0;return h instanceof Promise?h.then(y=>(g&&(g.issues=y.issues.length?ac(y.issues):cm),y)):(g&&(g.issues=h.issues.length?ac(h.issues):cm),h)};e._zod.parse=a,e._zod.run===s&&(e._zod.run=a)})}};function fm(){return gS}function yS(e,t){let r=e[uc]?.backEdges;return r!==void 0&&um(t)&&r.has(t)}var _S=()=>{let e={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"},map:{unit:"entries",verb:"to have"}};function t(i){return e[i]??null}let r={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",mac:"MAC address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",currency_code:"currency code",credit_card:"credit card number",iban:"IBAN",jwt:"JWT",template_literal:"input"},n={nan:"NaN"};function o(i,s){return i==="number"&&typeof s=="number"&&!Number.isFinite(s)?String(s):n[i]??i}return i=>{switch(i.code){case"invalid_type":{let s=o(i.expected),a=La(i.input),c=o(a,i.input);return`Invalid input: expected ${s}, received ${c}`}case"invalid_value":return i.values.length===1?`Invalid input: expected ${di(i.values[0])}`:`Invalid option: expected one of ${li(i.values,"|")}`;case"too_big":{let s=i.exact?"exactly ":i.inclusive?"<=":"<",a=t(i.origin);return a?`Too big: expected ${i.origin??"value"} to have ${s}${i.maximum.toString()} ${a.unit??"elements"}`:`Too big: expected ${i.origin??"value"} to be ${s}${i.maximum.toString()}`}case"too_small":{let s=i.exact?"exactly ":i.inclusive?">=":">",a=t(i.origin);return a?`Too small: expected ${i.origin} to have ${s}${i.minimum.toString()} ${a.unit}`:`Too small: expected ${i.origin} to be ${s}${i.minimum.toString()}`}case"invalid_format":{let s=i;return s.format==="starts_with"?`Invalid string: must start with "${s.prefix}"`:s.format==="ends_with"?`Invalid string: must end with "${s.suffix}"`:s.format==="includes"?`Invalid string: must include "${s.includes}"`:s.format==="regex"?`Invalid string: must match pattern ${s.pattern}`:`Invalid ${r[s.format]??i.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${i.divisor}`;case"unrecognized_keys":return`Unrecognized key${i.keys.length>1?"s":""}: ${li(i.keys,", ")}`;case"invalid_key":return`Invalid key in ${i.origin}`;case"invalid_union":return i.options&&Array.isArray(i.options)&&i.options.length>0?`Invalid discriminator value. Expected ${i.options.map(a=>`'${a}'`).join(" | ")}`:i.inclusive===!1?"Invalid input: more than one option matched":"Invalid input";case"invalid_element":return`Invalid value in ${i.origin}`;default:return"Invalid input"}}};function dm(){return{localeError:_S()}}var pm;var lc=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(t,...r){let n=r[0];return this._map.set(t,n),n&&typeof n=="object"&&"id"in n&&this._idmap.set(n.id,t),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(t){let r=this._map.get(t);return r&&typeof r=="object"&&"id"in r&&this._idmap.delete(r.id),this._map.delete(t),this}get(t){let r=t._zod.parent;if(r){let n={...this.get(r)??{}};delete n.id;let o={...n,...this._map.get(t)};return Object.keys(o).length?o:void 0}return this._map.get(t)}has(t){return this._map.has(t)}};function wS(){return new lc}(pm=globalThis).__zod_globalRegistry??(pm.__zod_globalRegistry=wS());var _r=globalThis.__zod_globalRegistry;function mm(e){return e.checks&&(e.checks=[...e.checks]),e}function hm(e,t){return new e(mm({type:"string",...A(t)}))}function gm(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...A(t)})}function ym(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...A(t)})}function _m(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...A(t)})}function wm(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...A(t)})}function xm(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...A(t)})}function vm(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...A(t)})}function bm(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...A(t)})}function Sm(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...A(t)})}function $m(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...A(t)})}function km(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...A(t)})}function zm(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...A(t)})}function Pm(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...A(t)})}function Em(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...A(t)})}function Tm(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...A(t)})}function Om(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...A(t)})}function Am(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...A(t)})}function Im(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...A(t)})}function Rm(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...A(t)})}function Cm(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...A(t)})}function Nm(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...A(t)})}function jm(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...A(t)})}function Dm(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...A(t)})}function Ci(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...A(t)})}function Ni(e,t){return new e({type:"string",format:"date",check:"string_format",...A(t)})}function ji(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...A(t)})}function Di(e,t){return new e({type:"string",format:"duration",check:"string_format",...A(t)})}function Mm(e,t){return new e(mm({type:"number",checks:[],...A(t)}))}function qm(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...A(t)})}function Fm(e,t){return new e({type:"boolean",...A(t)})}function Zm(e,t){return new e({type:"null",...A(t)})}function Lm(e){return new e({type:"unknown"})}function Um(e,t){return new e({type:"never",...A(t)})}function Mi(e,t){return new Xa({check:"less_than",...A(t),value:e,inclusive:!1})}function Yn(e,t){return new Xa({check:"less_than",...A(t),value:e,inclusive:!0})}function qi(e,t){return new Qa({check:"greater_than",...A(t),value:e,inclusive:!1})}function Xn(e,t){return new Qa({check:"greater_than",...A(t),value:e,inclusive:!0})}function Fi(e,t){return new Fd({check:"multiple_of",...A(t),value:e})}function Zi(e,t){return new Ld({check:"max_length",...A(t),maximum:e})}function Yr(e,t){return new Ud({check:"min_length",...A(t),minimum:e})}function Li(e,t){return new Vd({check:"length_equals",...A(t),length:e})}function fc(e,t){return new Hd({check:"string_format",format:"regex",...A(t),pattern:e})}function dc(e){return new Bd({check:"string_format",format:"lowercase",...A(e)})}function pc(e){return new Kd({check:"string_format",format:"uppercase",...A(e)})}function mc(e,t){return new Jd({check:"string_format",format:"includes",...A(t),includes:e})}function hc(e,t){return new Wd({check:"string_format",format:"starts_with",...A(t),prefix:e})}function gc(e,t){return new Gd({check:"string_format",format:"ends_with",...A(t),suffix:e})}function Gt(e){return new Yd({check:"overwrite",tx:e})}function yc(e){return Gt(t=>t.normalize(e))}function _c(){return Gt(e=>e.trim())}function wc(){return Gt(e=>e.toLowerCase())}function xc(){return Gt(e=>e.toUpperCase())}function vc(){return Gt(e=>Da(e))}function Vm(e,t,r){return new e({type:"array",element:t,...A(r)})}function Hm(e,t,r){let n=A(r);return n.abort??(n.abort=!0),new e({type:"custom",check:"custom",fn:t,...n})}function Bm(e,t,r){return new e({type:"custom",check:"custom",fn:t,...A(r)})}function Km(e,t){let r=xS(n=>(n.addIssue=o=>{if(typeof o=="string")n.issues.push(Wr(o,n.value,r._zod.def));else{let i=o;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),"input"in i||(i.input=n.value),i.inst??(i.inst=r),i.continue??(i.continue=!r._zod.def.abort),n.issues.push(Wr(i))}},e(n.value,n)),t);return r}function xS(e,t){let r=new $e({check:"custom",...A(t)});return r._zod.check=e,r}function Qn(e,...t){for(let r of t)for(let n of Reflect.ownKeys(r))Object.prototype.propertyIsEnumerable.call(r,n)&&Ye(e,n,r[n]);return e}function Sc(e){let t=e?.target??"draft-2020-12";return t==="draft-4"&&(t="draft-04"),t==="draft-7"&&(t="draft-07"),{processors:e.processors??{},metadataRegistry:e?.metadata??_r,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,sharedDefsExtractedFor:void 0,sharedEmitDoneFor:void 0,cycles:e?.cycles??"ref",reused:e?.reused??"inline",intersections:[],deferred:[],external:e?.external??void 0}}function jt(e,t,r,n,o){let i=typeof t.unrepresentable=="function"?t.unrepresentable({zodSchema:e,path:n.path,message:o}):t.unrepresentable;if(i==="any")return!1;if(i===void 0||i==="throw")throw new Error(o);return Object.assign(r,i),!0}function de(e,t,r={path:[],schemaPath:[]}){var n;let o=e._zod.def,i=t.seen.get(e);if(i)return i.count++,r.schemaPath.includes(e)&&(i.cycle=r.path),i.schema;let s={schema:{},count:1,cycle:void 0,path:r.path};t.seen.set(e,s),t.sharedDefsExtractedFor=void 0,t.sharedEmitDoneFor=void 0;let a=e._zod.toJSONSchema?.();if(a)s.schema=a;else{let l={...r,schemaPath:[...r.schemaPath,e],path:r.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,s.schema,l);else{let d=s.schema,p=t.processors[o.type];if(!p)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${o.type}`);p(e,t,d,l)}let f=e._zod.parent;f&&(s.ref||(s.ref=f),de(f,t,l),t.seen.get(f).isParent=!0)}let c=t.metadataRegistry.get(e);return c&&Qn(s.schema,c),t.io==="input"&&je(e)&&(delete s.schema.examples,delete s.schema.default),t.io==="input"&&"_prefault"in s.schema&&((n=s.schema).default??(n.default=s.schema._prefault)),delete s.schema._prefault,t.seen.get(e).schema}function Jm(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}function $c(e,t){let r=e.seen.get(t);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");if(e.external&&e.sharedDefsExtractedFor===e.external)return;let n=new Map;for(let s of e.seen.entries()){let a=e.metadataRegistry.get(s[0])?.id;if(a){let c=n.get(a);if(c&&c!==s[0])throw new Error(`Duplicate schema id "${a}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);n.set(a,s[0])}}let o=s=>{let a=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){let f=e.external.registry.get(s[0])?.id,d=e.external.uri??(m=>m);if(f)return{ref:d(f)};let p=s[1].defId??s[1].schema.id??`schema${e.counter++}`;return s[1].defId=p,{defId:p,ref:`${d("__shared")}#/${a}/${Jm(p)}`}}let c="#",u=`${c}/${a}/`;if(s[1]===r&&!s[1].schema.id)return{ref:c};let l=s[1].schema.id??`__schema${e.counter++}`;return{defId:l,ref:u+Jm(l)}},i=s=>{if(s[1].schema.$ref)return;let a=s[1],{ref:c,defId:u}=o(s);a.def={...a.schema},u&&(a.defId=u);let l=a.schema;for(let f in l)delete l[f];l.$ref=c};if(e.cycles==="throw")for(let s of e.seen.entries()){let a=s[1];if(a.cycle)throw new Error(`Cycle detected: #/${a.cycle?.join("/")}/ + +Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let s of e.seen.entries()){let a=s[1];if(t===s[0]){i(s);continue}if(e.external){let u=e.external.registry.get(s[0])?.id;if(t!==s[0]&&u){i(s);continue}}if(e.metadataRegistry.get(s[0])?.id){i(s);continue}if(a.cycle){i(s);continue}a.count>1&&e.reused==="ref"&&i(s)}e.external&&(e.sharedDefsExtractedFor=e.external)}function Ym(e){let t=e.anyOf;if(!Array.isArray(t)||t.length===0||e.type!==void 0)return;let r=[];for(let n of t){if(!n||typeof n!="object")return;Ym(n);let o=Object.keys(n);if(o.length!==1||o[0]!=="type")return;let i=n.type;for(let s of Array.isArray(i)?i:[i]){if(typeof s!="string")return;r.includes(s)||r.push(s)}}delete e.anyOf,e.type=r.length===1?r[0]:r}var Xm=new Set(["type","properties","required","additionalProperties"]),Wm=["oneOf","anyOf"];function Gm(e){let t=e.additionalProperties;return t===void 0||t===!1||typeof t!="object"||t===null?null:Object.keys(t).length?t:null}function bc(e){let t=[];for(let i of e){if(typeof i!="object"||i.type!=="object")return null;for(let s in i)if(!Xm.has(s))return null;t.push(i)}let r={},n=new Set;for(let i of t){for(let s in i.properties){if(Object.prototype.hasOwnProperty.call(r,s))continue;let a=[];for(let u of t){let l=u.properties?.[s]??Gm(u);l!=null&&(a.some(f=>JSON.stringify(f)===JSON.stringify(l))||a.push(l))}let c=a.length===1?a[0]:bc(a)??{allOf:a};Ye(r,s,c)}for(let s of i.required??[])n.add(s)}let o={type:"object",properties:r};if(n.size&&(o.required=[...n]),t.every(i=>i.additionalProperties===!1))o.additionalProperties=!1;else{let i=[];for(let s of t){let a=Gm(s);a&&!i.some(c=>JSON.stringify(c)===JSON.stringify(a))&&i.push(a)}i.length===1?o.additionalProperties=i[0]:i.length>1&&(o.additionalProperties={allOf:i})}return o}function vS(e){let t=e.allOf;if(!Array.isArray(t)||t.length<2)return;for(let o of Xm)if(o in e)return;let r=t.filter(o=>Wm.some(i=>Array.isArray(o[i]))),n=null;if(!r.length)n=bc(t);else{let o=r[0],i=Wm.find(c=>Array.isArray(o[c]));if(Object.keys(o).length!==1)return;let s=t.filter(c=>c!==o),a=o[i].map(c=>bc([...s,c]));if(a.some(c=>!c))return;n={[i]:a}}n&&(delete e.allOf,Qn(e,n))}function kc(e,t){let r=e.seen.get(t);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");let n=a=>{let c=e.seen.get(a);if(c.ref===null)return;let u=c.def??c.schema,l={...u},f=c.ref;if(c.ref=null,f){n(f);let p=e.seen.get(f),m=p.schema;if(m.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(u.allOf=u.allOf??[],u.allOf.push(m)):Qn(u,m),Qn(u,l),a._zod.parent===f)for(let g in u)g==="$ref"||g==="allOf"||g in l||delete u[g];if(m.$ref&&p.def)for(let g in u)g==="$ref"||g==="allOf"||g in p.def&&JSON.stringify(u[g])===JSON.stringify(p.def[g])&&delete u[g]}let d=a._zod.parent;if(d&&d!==f){n(d);let p=e.seen.get(d);if(p?.schema.$ref&&(u.$ref=p.schema.$ref,p.def))for(let m in u)m==="$ref"||m==="allOf"||m in p.def&&JSON.stringify(u[m])===JSON.stringify(p.def[m])&&delete u[m]}e.override({zodSchema:a,jsonSchema:u,path:c.path??[]})};if(!e.external||e.sharedEmitDoneFor!==e.external){for(let a of[...e.seen.entries()].reverse())n(a[0]);if(e.target!=="openapi-3.0")for(let a of e.seen.entries())Ym(a[1].def??a[1].schema);for(let a of e.deferred)a();if(e.intersections.length){let a=new Map;for(let c of e.seen.values())for(let u of[c.schema,c.def]){let l=u?.allOf;if(!Array.isArray(l))continue;let f=a.get(l);f?f.push(u):a.set(l,[u])}for(let c of e.intersections)for(let u of a.get(c)??[])vS(u)}}let o={};if(e.target==="draft-2020-12"?o.$schema="https://json-schema.org/draft/2020-12/schema":e.target==="draft-07"?o.$schema="http://json-schema.org/draft-07/schema#":e.target==="draft-04"?o.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){let a=e.external.registry.get(t)?.id;if(!a)throw new Error("Schema is missing an `id` property");o.$id=e.external.uri(a)}Qn(o,r.defId?r.schema:r.def??r.schema);let i=e.metadataRegistry.get(t)?.id;i!==void 0&&o.id===i&&delete o.id;let s=e.external?.defs??{};if(!e.external||e.sharedEmitDoneFor!==e.external)for(let a of e.seen.entries()){let c=a[1];c.def&&c.defId&&(c.def.id===c.defId&&delete c.def.id,Ye(s,c.defId,c.def))}e.external&&(e.sharedEmitDoneFor=e.external),e.external||Object.keys(s).length>0&&(e.target==="draft-2020-12"?o.$defs=s:o.definitions=s);try{let a=JSON.parse(JSON.stringify(o));return Object.defineProperty(a,"~standard",{value:{...t["~standard"],jsonSchema:{input:eo(t,"input",e.processors),output:eo(t,"output",e.processors)}},enumerable:!1,writable:!1}),a}catch{throw new Error("Error converting schema to JSON.")}}function je(e,t){let r=t??{seen:new Set};if(r.seen.has(e))return!1;r.seen.add(e);let n=e._zod.def;if(n.type==="transform")return!0;if(n.type==="array")return je(n.element,r);if(n.type==="set")return je(n.valueType,r);if(n.type==="lazy")return je(n.getter(),r);if(n.type==="promise"||n.type==="optional"||n.type==="nonoptional"||n.type==="nullable"||n.type==="readonly"||n.type==="default"||n.type==="prefault"||n.type==="catch")return je(n.innerType,r);if(n.type==="intersection")return je(n.left,r)||je(n.right,r);if(n.type==="record"||n.type==="map")return je(n.keyType,r)||je(n.valueType,r);if(n.type==="pipe")return e._zod.traits.has("$ZodCodec")?!0:je(n.in,r)||je(n.out,r);if(n.type==="object"){for(let o in n.shape)if(je(n.shape[o],r))return!0;return!1}if(n.type==="union"){for(let o of n.options)if(je(o,r))return!0;return!1}if(n.type==="tuple"){for(let o of n.items)if(je(o,r))return!0;return!!(n.rest&&je(n.rest,r))}return!1}var Qm=(e,t={})=>r=>{let n=Sc({...r,processors:t});return de(e,n),$c(n,e),kc(n,e)},eo=(e,t,r={})=>n=>{let{libraryOptions:o,target:i}=n??{},s=Sc({...o??{},target:i,io:t,processors:r});return de(e,s),$c(s,e),kc(s,e)};var Xr=(e,t,r)=>{(e[t]===void 0||r>e[t])&&(e[t]=r)},Qr=(e,t,r)=>{(e[t]===void 0||r{Xr(e,"minimum",t),Qr(e,"maximum",t)},oh=(e,t)=>{e.multipleOf??(e.multipleOf=[]),e.multipleOf.includes(t)||e.multipleOf.push(t)},ih=(e,t)=>{e.patterns??(e.patterns=new Set),e.patterns.add(t)},sh=(e,t)=>{e.mime=e.mime?e.mime.filter(r=>t.includes(r)):[...t]},ah=(e,t)=>{e.format=t,t.includes("int")&&(e.isInt=!0)},th=(e,t)=>Xr(e,"minimum",t.minimum),rh=(e,t)=>Qr(e,"maximum",t.maximum),nh=e=>(t,r)=>{ah(t,r.format);let[n,o]=e[r.format];Xr(t,"minimum",n),Qr(t,"maximum",o)},bS={greater_than:(e,t)=>Xr(e,t.inclusive?"minimum":"exclusiveMinimum",t.value),less_than:(e,t)=>Qr(e,t.inclusive?"maximum":"exclusiveMaximum",t.value),multiple_of:(e,t)=>oh(e,t.value),number_format:nh(Zn),bigint_format:nh(pi),min_length:th,max_length:rh,length_equals:(e,t)=>eh(e,t.length),min_size:th,max_size:rh,size_equals:(e,t)=>eh(e,t.size),string_format:(e,t)=>{ah(e,t.format),t.pattern&&ih(e,t.pattern),(t.format==="base64"||t.format==="base64url")&&(e.contentEncoding=t.format),(t.local||t.precision===-1)&&(e.laxFormat=!0)},mime_type:(e,t)=>sh(e,t.mime)};function rt(e){let t={},r=e._zod.def,n=e._zod.traits.has("$ZodCheck")?[e,...r.checks??[]]:r.checks??[];for(let i of n)bS[i._zod.def.check]?.(t,i._zod.def);let o=e._zod.bag;o.minimum!==void 0&&Xr(t,"minimum",o.minimum),o.exclusiveMinimum!==void 0&&Xr(t,"exclusiveMinimum",o.exclusiveMinimum),o.maximum!==void 0&&Qr(t,"maximum",o.maximum),o.exclusiveMaximum!==void 0&&Qr(t,"exclusiveMaximum",o.exclusiveMaximum),o.multipleOf!==void 0&&oh(t,o.multipleOf),o.format!==void 0&&(t.format??(t.format=o.format),o.format.includes("int")&&(t.isInt=!0)),o.mime&&sh(t,o.mime);for(let i of o.patterns??[])ih(t,i);return t}var SS={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},$S=new Map([[rc,Pd],[Ti,Ed]]),ch=e=>$S.get(e)??e,uh=(e,t,r,n)=>{let o=r;o.type="string";let{minimum:i,maximum:s,format:a,patterns:c,contentEncoding:u,laxFormat:l}=rt(e);if(typeof i=="number"&&(o.minLength=i),typeof s=="number"&&(o.maxLength=s),a&&(o.format=SS[a]??a,o.format===""&&delete o.format,(a==="time"||l)&&delete o.format),u&&(o.contentEncoding=u),c&&c.size>0){let f=[...c].map(ch);f.length===1?o.pattern=f[0].source:f.length>1&&(o.allOf=[...f.map(d=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:d.source}))])}},lh=(e,t,r,n)=>{let o=r,{minimum:i,maximum:s,multipleOf:a,exclusiveMaximum:c,exclusiveMinimum:u,isInt:l}=rt(e);o.type=l?"integer":"number";let f=typeof u=="number"&&u>=(i??Number.NEGATIVE_INFINITY),d=typeof c=="number"&&c<=(s??Number.POSITIVE_INFINITY),p=t.target==="draft-04"||t.target==="openapi-3.0";if(f?p?(o.minimum=u,o.exclusiveMinimum=!0):o.exclusiveMinimum=u:typeof i=="number"&&(o.minimum=i),d?p?(o.maximum=c,o.exclusiveMaximum=!0):o.exclusiveMaximum=c:typeof s=="number"&&(o.maximum=s),a){let m=new Set;for(let y of a)Number.isFinite(y)&&y!==0?m.add(Math.abs(y)):jt(e,t,o,n,`A multipleOf divisor of ${y} cannot be represented in JSON Schema`);let[h,...g]=m;h!==void 0&&(o.multipleOf=h),g.length&&(o.allOf=[...o.allOf??[],...g.map(y=>({multipleOf:y}))])}},fh=(e,t,r,n)=>{r.type="boolean"};var dh=(e,t,r,n)=>{t.target==="openapi-3.0"?(r.type="string",r.nullable=!0,r.enum=[null]):r.type="null"};var ph=(e,t,r,n)=>{r.not={}};var mh=(e,t,r,n)=>{};var hh=(e,t,r,n)=>{let o=e._zod.def,i=Hr(o.entries);if(i.length===0){r.not={};return}i.every(s=>typeof s=="number")&&(r.type="number"),i.every(s=>typeof s=="string")&&(r.type="string"),r.enum=i},gh=(e,t,r,n)=>{let o=e._zod.def;if(o.values.length===0){r.not={};return}let i=[];for(let s of o.values)if(s===void 0){if(jt(e,t,r,n,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof s=="bigint"){if(jt(e,t,r,n,"BigInt literals cannot be represented in JSON Schema"))return;i.push(Number(s))}else i.push(s);if(i.length!==0)if(i.length===1){let s=i[0];r.type=s===null?"null":typeof s,t.target==="draft-04"||t.target==="openapi-3.0"?r.enum=[s]:r.const=s}else i.every(s=>typeof s=="number")&&(r.type="number"),i.every(s=>typeof s=="string")&&(r.type="string"),i.every(s=>typeof s=="boolean")&&(r.type="boolean"),i.every(s=>s===null)&&(r.type="null"),r.enum=i};var yh=(e,t,r,n)=>{jt(e,t,r,n,"Custom types cannot be represented in JSON Schema")};var _h=(e,t,r,n)=>{jt(e,t,r,n,"Transforms cannot be represented in JSON Schema")};var wh=(e,t,r,n)=>{let o=r,i=e._zod.def,{minimum:s,maximum:a}=rt(e);typeof s=="number"&&(o.minItems=s),typeof a=="number"&&(o.maxItems=a),o.type="array",o.items=de(i.element,t,{...n,path:[...n.path,"items"]})};function Ui(e){let t=e._zod.def;return t.type==="pipe"&&t.in._zod.traits.has("$ZodTransform")?Ui(t.out):t.type==="catch"?Ui(t.innerType):e._zod.optin}var xh=(e,t,r,n)=>{let o=r,i=e._zod.def,s=i.shape;if(Object.getOwnPropertySymbols(s).length&&jt(e,t,o,n,"Symbol keys cannot be represented in JSON Schema"))return;o.type="object",o.properties={};for(let u in s)Ye(o.properties,u,de(s[u],t,{...n,path:[...n.path,"properties",u]}));let c=[];for(let u of Object.keys(s)){let l=i.shape[u];(t.io==="input"?Ui(l)===void 0:l._zod.optout===void 0)&&c.push(u)}c.length>0&&(o.required=c),i.catchall?._zod.def.type==="never"?o.additionalProperties=!1:i.catchall?i.catchall&&(o.additionalProperties=de(i.catchall,t,{...n,path:[...n.path,"additionalProperties"]})):t.io==="output"&&(o.additionalProperties=!1)},vh=(e,t,r,n)=>{let o=e._zod.def,i=o.inclusive===!1,s=o.options.map((a,c)=>de(a,t,{...n,path:[...n.path,i?"oneOf":"anyOf",c]}));i?r.oneOf=s:r.anyOf=s},bh=(e,t,r,n)=>{let o=e._zod.def,i=de(o.left,t,{...n,path:[...n.path,"allOf",0]}),s=de(o.right,t,{...n,path:[...n.path,"allOf",1]}),a=u=>"allOf"in u&&Object.keys(u).length===1,c=[...a(i)?i.allOf:[i],...a(s)?s.allOf:[s]];r.allOf=c,t.intersections.push(c)};function zc(e,t,r){if(t.$ref){if(r.has(t))return t;r.add(t);let m=e.get(t)?.def;if(!m)return t;let h=zc(e,m,r);return h===m?t:h}for(let m of["anyOf","oneOf"]){let h=t[m];if(!Array.isArray(h))continue;let g=h.map(y=>zc(e,y,r));g.some((y,v)=>y!==h[v])&&(t={...t,[m]:g})}let n=Array.isArray(t.type)?t.type:[t.type],o=!n.includes("string")&&n.some(m=>m==="number"||m==="integer"),i=t.enum??(t.const!==void 0?[t.const]:void 0);if(!o&&!i?.some(m=>typeof m=="number"))return t;let{minimum:s,maximum:a,exclusiveMinimum:c,exclusiveMaximum:u,multipleOf:l,format:f,id:d,...p}=t;return p.enum?p.enum=p.enum.map(m=>typeof m=="number"?String(m):m):typeof p.const=="number"&&(p.const=String(p.const)),o&&(p.type="string",i||(p.pattern=(n.includes("number")?Bn:Ga).source)),p}var Pc=new WeakMap;function kS(e){let t=new Map;for(let n of e.seen.values())n.def&&!t.has(n.schema)&&t.set(n.schema,n);let r=new Map;for(let n of Pc.get(e)??[]){let o=e.seen.get(n),i=(o?.def??o?.schema)?.propertyNames;if(!i||i===!0||r.has(i))continue;let s=zc(t,i,new Set);s!==i&&r.set(i,s)}if(r.size)for(let n of e.seen.values())for(let o of[n.schema,n.def]){let i=o&&r.get(o.propertyNames);i&&(o.propertyNames=i)}}var Sh=(e,t,r,n)=>{let o=r,i=e._zod.def;o.type="object";let s=i.keyType,a=rt(s).patterns;if(i.mode==="loose"&&a&&a.size>0){let l=de(i.valueType,t,{...n,path:[...n.path,"patternProperties","*"]});o.patternProperties={};for(let f of a)Ye(o.patternProperties,ch(f).source,l)}else{if(t.target==="draft-07"||t.target==="draft-2020-12"){o.propertyNames=de(i.keyType,t,{...n,path:[...n.path,"propertyNames"]});let l=Pc.get(t);l||(l=[],Pc.set(t,l),t.deferred.push(()=>kS(t))),l.push(e)}o.additionalProperties=de(i.valueType,t,{...n,path:[...n.path,"additionalProperties"]})}let c=s._zod.values,u=t.io==="input"&&Ui(i.valueType)!==void 0;if(c&&!i.partial&&!u){let l=[...c].filter(f=>typeof f=="string"||typeof f=="number");l.length>0&&(o.required=l.map(String))}},$h=(e,t,r,n)=>{let o=e._zod.def,i=de(o.innerType,t,n),s=t.seen.get(e);t.target==="openapi-3.0"?(s.ref=o.innerType,r.nullable=!0):r.anyOf=[i,{type:"null"}]},kh=(e,t,r,n)=>{let o=e._zod.def;de(o.innerType,t,n);let i=t.seen.get(e);i.ref=o.innerType},Ec=Symbol();function zh(e,t,r,n,o){let i=!1,s=JSON.stringify(e,(a,c)=>typeof c!="bigint"?c:(i=!0,null));return i?(jt(t,r,n,o,"BigInt defaults cannot be represented in JSON Schema"),Ec):JSON.parse(s)}var Ph=(e,t,r,n)=>{let o=e._zod.def;de(o.innerType,t,n);let i=t.seen.get(e);i.ref=o.innerType;let s=zh(o.defaultValue,e,t,r,n);s!==Ec&&(r.default=s)},Eh=(e,t,r,n)=>{let o=e._zod.def;de(o.innerType,t,n);let i=t.seen.get(e);if(i.ref=o.innerType,t.io!=="input")return;let s=zh(o.defaultValue,e,t,r,n);s!==Ec&&(r._prefault=s)},Th=(e,t,r,n)=>{let o=e._zod.def;de(o.innerType,t,n);let i=t.seen.get(e);i.ref=o.innerType;let s;try{s=o.catchValue(void 0)}catch{jt(e,t,r,n,"Dynamic catch values are not supported in JSON Schema");return}r.default=s},Oh=(e,t,r,n)=>{let o=e._zod.def,i=o.in._zod.traits.has("$ZodTransform"),s=t.io==="input"?i?o.out:o.in:o.out;de(s,t,n);let a=t.seen.get(e);a.ref=s},Ah=(e,t,r,n)=>{let o=e._zod.def;de(o.innerType,t,n);let i=t.seen.get(e);i.ref=o.innerType,r.readOnly=!0};var Tc=(e,t,r,n)=>{let o=e._zod.def;de(o.innerType,t,n);let i=t.seen.get(e);i.ref=o.innerType};var Ih=new WeakSet([Object.prototype,Error.prototype]);function Vi(e,t,r){Object.defineProperty(e,t,{configurable:!0,enumerable:!1,get(){let n=r(this);return Object.defineProperty(this,t,{value:n,configurable:!0,writable:!0}),n},set(n){Object.defineProperty(this,t,{value:n,configurable:!0,writable:!0})}})}var CS=(e,t)=>{Qf.init(e,t),e.name="ZodError";let r=Object.getPrototypeOf(e);Ih.has(r)||(Ih.add(r),Vi(r,"format",n=>o=>rd(n,o)),Vi(r,"flatten",n=>o=>td(n,o)),Vi(r,"addIssue",n=>o=>{n.issues.push(o),n.message=JSON.stringify(n.issues,Br,2)}),Vi(r,"addIssues",n=>o=>{n.issues.push(...o),n.message=JSON.stringify(n.issues,Br,2)}),Object.defineProperty(r,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}}))};var Qe=w("ZodError",CS,void 0,{Parent:Error});var Rh=_i(Qe),Ch=wi(Qe),Nh=Hn(Qe),jh=xi(Qe),Dh=od(Qe),Mh=id(Qe),qh=sd(Qe),Fh=ad(Qe),Zh=cd(Qe),Lh=ud(Qe),Uh=ld(Qe),Vh=fd(Qe);function jS(){Ze.localeError||Xe(dm())}function Bi(){Ze.memoizer||Xe({memoizer:fm()})}var ce=w("ZodType",(e,t)=>(jS(),ee.init(e,t),e.def=t,e.type=t.type,e),{check(...e){let t=this.def;return this.clone(I.mergeDefs(t,{checks:[...t.checks??[],...e.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return dt(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(k$(e,t))},superRefine(e,t){return this.check(z$(e,t))},overwrite(e){return this.check(Gt(e))},optional(){return ae(this)},exactOptional(){return p$(this)},nullable(){return Kh(this)},nullish(){return ae(Kh(this))},nonoptional(e){return w$(this,e)},array(){return L(this)},or(e){return re([this,e])},and(e){return Ki(this,e)},transform(e){return Jh(this,eg(e))},default(e){return g$(this,e)},prefault(e){return _$(this,e)},catch(e){return v$(this,e)},pipe(e){return Jh(this,e)},readonly(){return $$(this)},describe(e){let t=this.clone();return _r.add(t,{description:e}),t},meta(...e){if(e.length===0)return _r.get(this);let t=this.clone();return _r.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e,...t){return t.length===0?e(this):e(this,...t)},get"~standard"(){return I.hide(this,"~standard",{...tc(this),jsonSchema:{input:eo(this,"input"),output:eo(this,"output")}})},set"~standard"(e){I.own(this,"~standard",e)},parse:function e(t,r){return Rh(this,t,r,{callee:e})},parseAsync:async function e(t,r){return await Ch(this,t,r,{callee:e})},safeParse(e,t){return Nh(this,e,t)},async safeParseAsync(e,t){return jh(this,e,t)},get spa(){return this?.safeParseAsync},set spa(e){I.own(this,"spa",e)},validate(e,t){return vi(this,e,t)},validateAsync(e,t){return bi(this,e,t)},encode:function e(t,r){return Dh(this,t,r,{callee:e})},decode:function e(t,r){return Mh(this,t,r,{callee:e})},encodeAsync:async function e(t,r){return await qh(this,t,r,{callee:e})},decodeAsync:async function e(t,r){return await Fh(this,t,r,{callee:e})},safeEncode(e,t){return Zh(this,e,t)},safeDecode(e,t){return Lh(this,e,t)},async safeEncodeAsync(e,t){return Uh(this,e,t)},async safeDecodeAsync(e,t){return Vh(this,e,t)},toJSONSchema(e){return Qm(this,{})(e)},get description(){return _r.get(this)?.description},get _def(){return this._zod.def}}),Wh=w("_ZodString",(e,t)=>{Ei.init(e,t),ce.init(e,t),e._zod.processJSONSchema=(r,n,o)=>uh(e,r,n,o)},I.derived({format:e=>rt(e).format??null,minLength:e=>rt(e).minimum??null,maxLength:e=>rt(e).maximum??null},{regex(...e){return this.check(fc(...e))},includes(...e){return this.check(mc(...e))},startsWith(...e){return this.check(hc(...e))},endsWith(...e){return this.check(gc(...e))},min(...e){return this.check(Yr(...e))},max(...e){return this.check(Zi(...e))},length(...e){return this.check(Li(...e))},nonempty(...e){return this.check(Yr(1,...e))},lowercase(e){return this.check(dc(e))},uppercase(e){return this.check(pc(e))},trim(){return this.check(_c())},normalize(...e){return this.check(yc(...e))},toLowerCase(){return this.check(wc())},toUpperCase(){return this.check(xc())},slugify(){return this.check(vc())}})),DS=w("ZodString",(e,t)=>{Ei.init(e,t),Wh.init(e,t)},{email(e){return this.check(gm(MS,e))},url(e){return this.check(bm(FS,e))},jwt(e){return this.check(Dm(t$,e))},emoji(e){return this.check(Sm(ZS,e))},guid(e){return this.check(ym(qS,e))},uuid(e){return this.check(_m(Hi,e))},uuidv4(e){return this.check(wm(Hi,e))},uuidv6(e){return this.check(xm(Hi,e))},uuidv7(e){return this.check(vm(Hi,e))},nanoid(e){return this.check($m(LS,e))},cuid(e){return this.check(km(US,e))},cuid2(e){return this.check(zm(VS,e))},ulid(e){return this.check(Pm(HS,e))},base64(e){return this.check(Cm(XS,e))},base64url(e){return this.check(Nm(QS,e))},xid(e){return this.check(Em(BS,e))},ksuid(e){return this.check(Tm(KS,e))},ipv4(e){return this.check(Om(JS,e))},ipv6(e){return this.check(Am(WS,e))},cidrv4(e){return this.check(Im(GS,e))},cidrv6(e){return this.check(Rm(YS,e))},e164(e){return this.check(jm(e$,e))},datetime(e){return this.check(Ci(ro,e))},date(e){return this.check(Ni(no,e))},time(e){return this.check(ji(oo,e))},duration(e){return this.check(Di(io,e))}});function _(e){return hm(DS,e)}var ue=w("ZodStringFormat",(e,t)=>{te.init(e,t),Wh.init(e,t)}),ro=w("ZodISODateTime",(e,t)=>{$p.init(e,t),ue.init(e,t)}),no=w("ZodISODate",(e,t)=>{kp.init(e,t),ue.init(e,t)}),oo=w("ZodISOTime",(e,t)=>{zp.init(e,t),ue.init(e,t)}),io=w("ZodISODuration",(e,t)=>{Pp.init(e,t),ue.init(e,t)}),MS=w("ZodEmail",(e,t)=>{pp.init(e,t),ue.init(e,t)});var qS=w("ZodGUID",(e,t)=>{fp.init(e,t),ue.init(e,t)});var Hi=w("ZodUUID",(e,t)=>{dp.init(e,t),ue.init(e,t)});var FS=w("ZodURL",(e,t)=>{gp.init(e,t),ue.init(e,t)});var ZS=w("ZodEmoji",(e,t)=>{yp.init(e,t),ue.init(e,t)});var LS=w("ZodNanoID",(e,t)=>{_p.init(e,t),ue.init(e,t)});var US=w("ZodCUID",(e,t)=>{wp.init(e,t),ue.init(e,t)});var VS=w("ZodCUID2",(e,t)=>{xp.init(e,t),ue.init(e,t)});var HS=w("ZodULID",(e,t)=>{vp.init(e,t),ue.init(e,t)});var BS=w("ZodXID",(e,t)=>{bp.init(e,t),ue.init(e,t)});var KS=w("ZodKSUID",(e,t)=>{Sp.init(e,t),ue.init(e,t)});var JS=w("ZodIPv4",(e,t)=>{Ep.init(e,t),ue.init(e,t)});var WS=w("ZodIPv6",(e,t)=>{Op.init(e,t),ue.init(e,t)});var GS=w("ZodCIDRv4",(e,t)=>{Ap.init(e,t),ue.init(e,t)});var YS=w("ZodCIDRv6",(e,t)=>{Ip.init(e,t),ue.init(e,t)});var XS=w("ZodBase64",(e,t)=>{Cp.init(e,t),ue.init(e,t)});var QS=w("ZodBase64URL",(e,t)=>{Np.init(e,t),ue.init(e,t)});var e$=w("ZodE164",(e,t)=>{jp.init(e,t),ue.init(e,t)});var t$=w("ZodJWT",(e,t)=>{Dp.init(e,t),ue.init(e,t)});var Gh=w("ZodNumber",(e,t)=>{nc.init(e,t),ce.init(e,t),e._zod.processJSONSchema=(r,n,o)=>lh(e,r,n,o),e.isFinite=!0},I.derived({minValue:e=>{let{minimum:t,exclusiveMinimum:r}=rt(e);return Math.max(t??Number.NEGATIVE_INFINITY,r??Number.NEGATIVE_INFINITY)},maxValue:e=>{let{maximum:t,exclusiveMaximum:r}=rt(e);return Math.min(t??Number.POSITIVE_INFINITY,r??Number.POSITIVE_INFINITY)},isInt:e=>{let{isInt:t,multipleOf:r}=rt(e);return!!t||!!r?.some(Number.isSafeInteger)},format:e=>rt(e).format??null},{gt(e,t){return this.check(qi(e,t))},gte(e,t){return this.check(Xn(e,t))},min(e,t){return this.check(Xn(e,t))},lt(e,t){return this.check(Mi(e,t))},lte(e,t){return this.check(Yn(e,t))},max(e,t){return this.check(Yn(e,t))},int(e){return this.check(Hh(e))},safe(e){return this.check(Hh(e))},positive(e){return this.check(qi(0,e))},nonnegative(e){return this.check(Xn(0,e))},negative(e){return this.check(Mi(0,e))},nonpositive(e){return this.check(Yn(0,e))},multipleOf(e,t){return this.check(Fi(e,t))},step(e,t){return this.check(Fi(e,t))},finite(){return this}}));function W(e){return Mm(Gh,e)}var r$=w("ZodNumberFormat",(e,t)=>{Mp.init(e,t),Gh.init(e,t)});function Hh(e){return qm(r$,e)}var n$=w("ZodBoolean",(e,t)=>{qp.init(e,t),ce.init(e,t),e._zod.processJSONSchema=(r,n,o)=>fh(e,r,n,o)});function xe(e){return Fm(n$,e)}var o$=w("ZodNull",(e,t)=>{Fp.init(e,t),ce.init(e,t),e._zod.processJSONSchema=(r,n,o)=>dh(e,r,n,o)});function Yh(e){return Zm(o$,e)}var i$=w("ZodUnknown",(e,t)=>{Zp.init(e,t),ce.init(e,t),e._zod.processJSONSchema=(r,n,o)=>mh(e,r,n,o)});function se(){return Lm(i$)}var s$=w("ZodNever",(e,t)=>{Lp.init(e,t),ce.init(e,t),e._zod.processJSONSchema=(r,n,o)=>ph(e,r,n,o)});function a$(e){return Um(s$,e)}var c$=w("ZodArray",(e,t)=>{Bi(),Up.init(e,t),ce.init(e,t),e._zod.processJSONSchema=(r,n,o)=>wh(e,r,n,o),e.element=t.element},{min(e,t){return this.check(Yr(e,t))},nonempty(e){return this.check(Yr(1,e))},max(e,t){return this.check(Zi(e,t))},length(e,t){return this.check(Li(e,t))},unwrap(){return this.element}});function L(e,t){return Vm(c$,e,t)}var Xh=w("ZodObject",(e,t)=>{Bi(),Bp.init(e,t),ce.init(e,t),e._zod.processJSONSchema=(r,n,o)=>xh(e,r,n,o),I.installLazyProp(e,"shape",r=>r._zod.def.shape,!1)},{keyof(){return Le(Object.keys(this._zod.def.shape))},catchall(e){return this.clone(I.mergeDefs(this._zod.def,{catchall:e}))},passthrough(){return this.clone(I.mergeDefs(this._zod.def,{catchall:se()}))},loose(){return this.clone(I.mergeDefs(this._zod.def,{catchall:se()}))},strict(){return this.clone(I.mergeDefs(this._zod.def,{catchall:a$()}))},strip(){return this.clone(I.mergeDefs(this._zod.def,{catchall:void 0}))},extend(e){return I.extend(this,e)},safeExtend(e){return I.safeExtend(this,e)},merge(e){return I.merge(this,e)},pick(e){return I.pick(this,e)},omit(e){return I.omit(this,e)},partial(...e){return I.partial(tg,this,e[0])},exactPartial(...e){return I.partial(rg,this,e[0],"exactPartial")},required(...e){return I.required(ng,this,e[0])}});function z(e,t){let r={type:"object",shape:e??{},...I.normalizeParams(t)};return new Xh(r)}function De(e,t){return new Xh({type:"object",shape:e,catchall:se(),...I.normalizeParams(t)})}var Qh=w("ZodUnion",(e,t)=>{oc.init(e,t),ce.init(e,t),e._zod.processJSONSchema=(r,n,o)=>vh(e,r,n,o),e.options=t.options});function re(e,t){return new Qh({type:"union",options:e,...I.normalizeParams(t)})}var u$=w("ZodDiscriminatedUnion",(e,t)=>{Qh.init(e,t),Kp.init(e,t)});function Ac(e,t,r){return new u$({type:"union",options:t,discriminator:e,...I.normalizeParams(r)})}var l$=w("ZodIntersection",(e,t)=>{Jp.init(e,t),ce.init(e,t),e._zod.processJSONSchema=(r,n,o)=>bh(e,r,n,o)});function Ki(e,t){return new l$({type:"intersection",left:e,right:t})}var Bh=w("ZodRecord",(e,t)=>{Bi(),Wp.init(e,t),ce.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Sh(e,r,n,o),e.keyType=t.keyType,e.valueType=t.valueType});function X(e,t,r){return!t||!t._zod?new Bh({type:"record",keyType:_(),valueType:e,...I.normalizeParams(t)}):new Bh({type:"record",keyType:e,valueType:t,...I.normalizeParams(r)})}var Oc=w("ZodEnum",(e,t)=>{Gp.init(e,t),ce.init(e,t),e._zod.processJSONSchema=(n,o,i)=>hh(e,n,o,i),e.enum=t.entries,e.options=[...e._zod.values];let r=new Set(Object.keys(t.entries));e.extract=(n,o)=>{let i={};for(let s of n)if(r.has(s))i[s]=t.entries[s];else throw new Error(`Key ${s} not found in enum`);return new Oc({...t,checks:[],...I.normalizeParams(o),entries:i})},e.exclude=(n,o)=>{let i={...t.entries};for(let s of n)if(r.has(s))delete i[s];else throw new Error(`Key ${s} not found in enum`);return new Oc({...t,checks:[],...I.normalizeParams(o),entries:i})}});function Le(e,t){let r=Array.isArray(e)?Object.fromEntries(e.map(n=>[n,n])):e;return new Oc({type:"enum",entries:r,...I.normalizeParams(t)})}var f$=w("ZodLiteral",(e,t)=>{Yp.init(e,t),ce.init(e,t),e._zod.processJSONSchema=(r,n,o)=>gh(e,r,n,o),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function P(e,t){return new f$({type:"literal",values:Array.isArray(e)?e:[e],...I.normalizeParams(t)})}var d$=w("ZodTransform",(e,t)=>{Bi(),Xp.init(e,t),ce.init(e,t),e._zod.processJSONSchema=(r,n,o)=>_h(e,r,n,o),e._zod.parse=(r,n)=>{if(n.direction==="backward")throw new Gr(e.constructor.name);r.addIssue=i=>{if(typeof i=="string")r.issues.push(I.issue(i,r.value,t));else{let s=i;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),"input"in s||(s.input=r.value),s.inst??(s.inst=e),r.issues.push(I.issue(s))}};let o=t.transform(r.value,r);return o instanceof Promise?o.then(i=>(r.value=i,r)):(r.value=o,r)}});function eg(e){return new d$({type:"transform",transform:e})}var tg=w("ZodOptional",(e,t)=>{ic.init(e,t),ce.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Tc(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});function ae(e){return new tg({type:"optional",innerType:e})}var rg=w("ZodExactOptional",(e,t)=>{Qp.init(e,t),ce.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Tc(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});function p$(e){return new rg({type:"optional",innerType:e})}var m$=w("ZodNullable",(e,t)=>{em.init(e,t),ce.init(e,t),e._zod.processJSONSchema=(r,n,o)=>$h(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});function Kh(e){return new m$({type:"nullable",innerType:e})}var h$=w("ZodDefault",(e,t)=>{tm.init(e,t),ce.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Ph(e,r,n,o),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function g$(e,t){return new h$({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():I.shallowClone(t)}})}var y$=w("ZodPrefault",(e,t)=>{rm.init(e,t),ce.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Eh(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});function _$(e,t){return new y$({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():I.shallowClone(t)}})}var ng=w("ZodNonOptional",(e,t)=>{nm.init(e,t),ce.init(e,t),e._zod.processJSONSchema=(r,n,o)=>kh(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});function w$(e,t){return new ng({type:"nonoptional",innerType:e,...I.normalizeParams(t)})}var x$=w("ZodCatch",(e,t)=>{om.init(e,t),ce.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Th(e,r,n,o),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function v$(e,t){return new x$({type:"catch",innerType:e,catchValue:typeof t=="function"?t:I.constantCatch(t)})}var og=w("ZodPipe",(e,t)=>{sc.init(e,t),ce.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Oh(e,r,n,o),e.in=t.in,e.out=t.out});function Jh(e,t){return new og({type:"pipe",in:e,out:t})}var b$=w("ZodPreprocess",(e,t)=>{og.init(e,t),im.init(e,t)}),S$=w("ZodReadonly",(e,t)=>{sm.init(e,t),ce.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Ah(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});function $$(e){return new S$({type:"readonly",innerType:e})}var ig=w("ZodCustom",(e,t)=>{am.init(e,t),ce.init(e,t),e._zod.processJSONSchema=(r,n,o)=>yh(e,r,n,o)});function sg(e,t){return Hm(ig,e??(()=>!0),t)}function k$(e,t={}){return Bm(ig,e,t)}function z$(e,t){return Km(e,t)}function Ic(e,t){return new b$({type:"pipe",in:eg(e),out:t})}var Ji={};jf(Ji,{ZodISODate:()=>no,ZodISODateTime:()=>ro,ZodISODuration:()=>io,ZodISOTime:()=>oo,date:()=>E$,datetime:()=>P$,duration:()=>O$,time:()=>T$});function P$(e){return Ci(ro,e)}function E$(e){return Ni(no,e)}function T$(e){return ji(oo,e)}function O$(e){return Di(io,e)}var Cc="2025-11-25";var ag=[Cc,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Yt="io.modelcontextprotocol/related-task",Gi="2.0",ge=sg(e=>e!==null&&(typeof e=="object"||typeof e=="function")),cg=re([_(),W().int()]),ug=_(),ZD=De({ttl:W().optional(),pollInterval:W().optional()}),A$=z({ttl:W().optional()}),I$=z({taskId:_()}),Nc=De({progressToken:cg.optional(),[Yt]:I$.optional()}),et=z({_meta:Nc.optional()}),so=et.extend({task:A$.optional()}),lg=e=>so.safeParse(e).success,ke=z({method:_(),params:et.loose().optional()}),nt=z({_meta:Nc.optional()}),ot=z({method:_(),params:nt.loose().optional()}),ze=De({_meta:Nc.optional()}),Yi=re([_(),W().int()]),fg=z({jsonrpc:P(Gi),id:Yi,...ke.shape}).strict(),jc=e=>fg.safeParse(e).success,dg=z({jsonrpc:P(Gi),...ot.shape}).strict(),pg=e=>dg.safeParse(e).success,Dc=z({jsonrpc:P(Gi),id:Yi,result:ze}).strict(),ao=e=>Dc.safeParse(e).success;var D;(function(e){e[e.ConnectionClosed=-32e3]="ConnectionClosed",e[e.RequestTimeout=-32001]="RequestTimeout",e[e.ParseError=-32700]="ParseError",e[e.InvalidRequest=-32600]="InvalidRequest",e[e.MethodNotFound=-32601]="MethodNotFound",e[e.InvalidParams=-32602]="InvalidParams",e[e.InternalError=-32603]="InternalError",e[e.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(D||(D={}));var Mc=z({jsonrpc:P(Gi),id:Yi.optional(),error:z({code:W().int(),message:_(),data:se().optional()})}).strict();var mg=e=>Mc.safeParse(e).success;var hg=re([fg,dg,Dc,Mc]),LD=re([Dc,Mc]),Xi=ze.strict(),R$=nt.extend({requestId:Yi.optional(),reason:_().optional()}),Qi=ot.extend({method:P("notifications/cancelled"),params:R$}),C$=z({src:_(),mimeType:_().optional(),sizes:L(_()).optional(),theme:Le(["light","dark"]).optional()}),co=z({icons:L(C$).optional()}),en=z({name:_(),title:_().optional()}),gg=en.extend({...en.shape,...co.shape,version:_(),websiteUrl:_().optional(),description:_().optional()}),N$=Ki(z({applyDefaults:xe().optional()}),X(_(),se())),j$=Ic(e=>e&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,Ki(z({form:N$.optional(),url:ge.optional()}),X(_(),se()).optional())),D$=De({list:ge.optional(),cancel:ge.optional(),requests:De({sampling:De({createMessage:ge.optional()}).optional(),elicitation:De({create:ge.optional()}).optional()}).optional()}),M$=De({list:ge.optional(),cancel:ge.optional(),requests:De({tools:De({call:ge.optional()}).optional()}).optional()}),q$=z({experimental:X(_(),ge).optional(),sampling:z({context:ge.optional(),tools:ge.optional()}).optional(),elicitation:j$.optional(),roots:z({listChanged:xe().optional()}).optional(),tasks:D$.optional(),extensions:X(_(),ge).optional()}),F$=et.extend({protocolVersion:_(),capabilities:q$,clientInfo:gg}),qc=ke.extend({method:P("initialize"),params:F$});var Z$=z({experimental:X(_(),ge).optional(),logging:ge.optional(),completions:ge.optional(),prompts:z({listChanged:xe().optional()}).optional(),resources:z({subscribe:xe().optional(),listChanged:xe().optional()}).optional(),tools:z({listChanged:xe().optional()}).optional(),tasks:M$.optional(),extensions:X(_(),ge).optional()}),L$=ze.extend({protocolVersion:_(),capabilities:Z$,serverInfo:gg,instructions:_().optional()}),Fc=ot.extend({method:P("notifications/initialized"),params:nt.optional()});var es=ke.extend({method:P("ping"),params:et.optional()}),U$=z({progress:W(),total:ae(W()),message:ae(_())}),V$=z({...nt.shape,...U$.shape,progressToken:cg}),ts=ot.extend({method:P("notifications/progress"),params:V$}),H$=et.extend({cursor:ug.optional()}),uo=ke.extend({params:H$.optional()}),lo=ze.extend({nextCursor:ug.optional()}),B$=Le(["working","input_required","completed","failed","cancelled"]),fo=z({taskId:_(),status:B$,ttl:re([W(),Yh()]),createdAt:_(),lastUpdatedAt:_(),pollInterval:ae(W()),statusMessage:ae(_())}),tn=ze.extend({task:fo}),K$=nt.merge(fo),po=ot.extend({method:P("notifications/tasks/status"),params:K$}),rs=ke.extend({method:P("tasks/get"),params:et.extend({taskId:_()})}),ns=ze.merge(fo),os=ke.extend({method:P("tasks/result"),params:et.extend({taskId:_()})}),UD=ze.loose(),is=uo.extend({method:P("tasks/list")}),ss=lo.extend({tasks:L(fo)}),as=ke.extend({method:P("tasks/cancel"),params:et.extend({taskId:_()})}),yg=ze.merge(fo),_g=z({uri:_(),mimeType:ae(_()),_meta:X(_(),se()).optional()}),wg=_g.extend({text:_()}),Zc=_().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),xg=_g.extend({blob:Zc}),mo=Le(["user","assistant"]),rn=z({audience:L(mo).optional(),priority:W().min(0).max(1).optional(),lastModified:Ji.datetime({offset:!0}).optional()}),vg=z({...en.shape,...co.shape,uri:_(),description:ae(_()),mimeType:ae(_()),size:ae(W()),annotations:rn.optional(),_meta:ae(De({}))}),J$=z({...en.shape,...co.shape,uriTemplate:_(),description:ae(_()),mimeType:ae(_()),annotations:rn.optional(),_meta:ae(De({}))}),Lc=uo.extend({method:P("resources/list")}),W$=lo.extend({resources:L(vg)}),Uc=uo.extend({method:P("resources/templates/list")}),G$=lo.extend({resourceTemplates:L(J$)}),Vc=et.extend({uri:_()}),Y$=Vc,Hc=ke.extend({method:P("resources/read"),params:Y$}),X$=ze.extend({contents:L(re([wg,xg]))}),Q$=ot.extend({method:P("notifications/resources/list_changed"),params:nt.optional()}),ek=Vc,tk=ke.extend({method:P("resources/subscribe"),params:ek}),rk=Vc,nk=ke.extend({method:P("resources/unsubscribe"),params:rk}),ok=nt.extend({uri:_()}),ik=ot.extend({method:P("notifications/resources/updated"),params:ok}),sk=z({name:_(),description:ae(_()),required:ae(xe())}),ak=z({...en.shape,...co.shape,description:ae(_()),arguments:ae(L(sk)),_meta:ae(De({}))}),Bc=uo.extend({method:P("prompts/list")}),ck=lo.extend({prompts:L(ak)}),uk=et.extend({name:_(),arguments:X(_(),_()).optional()}),Kc=ke.extend({method:P("prompts/get"),params:uk}),Jc=z({type:P("text"),text:_(),annotations:rn.optional(),_meta:X(_(),se()).optional()}),Wc=z({type:P("image"),data:Zc,mimeType:_(),annotations:rn.optional(),_meta:X(_(),se()).optional()}),Gc=z({type:P("audio"),data:Zc,mimeType:_(),annotations:rn.optional(),_meta:X(_(),se()).optional()}),lk=z({type:P("tool_use"),name:_(),id:_(),input:X(_(),se()),_meta:X(_(),se()).optional()}),fk=z({type:P("resource"),resource:re([wg,xg]),annotations:rn.optional(),_meta:X(_(),se()).optional()}),dk=vg.extend({type:P("resource_link")}),Yc=re([Jc,Wc,Gc,dk,fk]),pk=z({role:mo,content:Yc}),mk=ze.extend({description:_().optional(),messages:L(pk)}),hk=ot.extend({method:P("notifications/prompts/list_changed"),params:nt.optional()}),gk=z({title:_().optional(),readOnlyHint:xe().optional(),destructiveHint:xe().optional(),idempotentHint:xe().optional(),openWorldHint:xe().optional()}),yk=z({taskSupport:Le(["required","optional","forbidden"]).optional()}),bg=z({...en.shape,...co.shape,description:_().optional(),inputSchema:z({type:P("object"),properties:X(_(),ge).optional(),required:L(_()).optional()}).catchall(se()),outputSchema:z({type:P("object"),properties:X(_(),ge).optional(),required:L(_()).optional()}).catchall(se()).optional(),annotations:gk.optional(),execution:yk.optional(),_meta:X(_(),se()).optional()}),Xc=uo.extend({method:P("tools/list")}),_k=lo.extend({tools:L(bg)}),cs=ze.extend({content:L(Yc).default([]),structuredContent:X(_(),se()).optional(),isError:xe().optional()}),VD=cs.or(ze.extend({toolResult:se()})),wk=so.extend({name:_(),arguments:X(_(),se()).optional()}),ho=ke.extend({method:P("tools/call"),params:wk}),xk=ot.extend({method:P("notifications/tools/list_changed"),params:nt.optional()}),HD=z({autoRefresh:xe().default(!0),debounceMs:W().int().nonnegative().default(300)}),go=Le(["debug","info","notice","warning","error","critical","alert","emergency"]),vk=et.extend({level:go}),Qc=ke.extend({method:P("logging/setLevel"),params:vk}),bk=nt.extend({level:go,logger:_().optional(),data:se()}),Sk=ot.extend({method:P("notifications/message"),params:bk}),$k=z({name:_().optional()}),kk=z({hints:L($k).optional(),costPriority:W().min(0).max(1).optional(),speedPriority:W().min(0).max(1).optional(),intelligencePriority:W().min(0).max(1).optional()}),zk=z({mode:Le(["auto","required","none"]).optional()}),Pk=z({type:P("tool_result"),toolUseId:_().describe("The unique identifier for the corresponding tool call."),content:L(Yc).default([]),structuredContent:z({}).loose().optional(),isError:xe().optional(),_meta:X(_(),se()).optional()}),Ek=Ac("type",[Jc,Wc,Gc]),Wi=Ac("type",[Jc,Wc,Gc,lk,Pk]),Tk=z({role:mo,content:re([Wi,L(Wi)]),_meta:X(_(),se()).optional()}),Ok=so.extend({messages:L(Tk),modelPreferences:kk.optional(),systemPrompt:_().optional(),includeContext:Le(["none","thisServer","allServers"]).optional(),temperature:W().optional(),maxTokens:W().int(),stopSequences:L(_()).optional(),metadata:ge.optional(),tools:L(bg).optional(),toolChoice:zk.optional()}),Ak=ke.extend({method:P("sampling/createMessage"),params:Ok}),yo=ze.extend({model:_(),stopReason:ae(Le(["endTurn","stopSequence","maxTokens"]).or(_())),role:mo,content:Ek}),eu=ze.extend({model:_(),stopReason:ae(Le(["endTurn","stopSequence","maxTokens","toolUse"]).or(_())),role:mo,content:re([Wi,L(Wi)])}),Ik=z({type:P("boolean"),title:_().optional(),description:_().optional(),default:xe().optional()}),Rk=z({type:P("string"),title:_().optional(),description:_().optional(),minLength:W().optional(),maxLength:W().optional(),format:Le(["email","uri","date","date-time"]).optional(),default:_().optional()}),Ck=z({type:Le(["number","integer"]),title:_().optional(),description:_().optional(),minimum:W().optional(),maximum:W().optional(),default:W().optional()}),Nk=z({type:P("string"),title:_().optional(),description:_().optional(),enum:L(_()),default:_().optional()}),jk=z({type:P("string"),title:_().optional(),description:_().optional(),oneOf:L(z({const:_(),title:_()})),default:_().optional()}),Dk=z({type:P("string"),title:_().optional(),description:_().optional(),enum:L(_()),enumNames:L(_()).optional(),default:_().optional()}),Mk=re([Nk,jk]),qk=z({type:P("array"),title:_().optional(),description:_().optional(),minItems:W().optional(),maxItems:W().optional(),items:z({type:P("string"),enum:L(_())}),default:L(_()).optional()}),Fk=z({type:P("array"),title:_().optional(),description:_().optional(),minItems:W().optional(),maxItems:W().optional(),items:z({anyOf:L(z({const:_(),title:_()}))}),default:L(_()).optional()}),Zk=re([qk,Fk]),Lk=re([Dk,Mk,Zk]),Uk=re([Lk,Ik,Rk,Ck]),Vk=so.extend({mode:P("form").optional(),message:_(),requestedSchema:z({type:P("object"),properties:X(_(),Uk),required:L(_()).optional()})}),Hk=so.extend({mode:P("url"),message:_(),elicitationId:_(),url:_().url()}),Bk=re([Vk,Hk]),Kk=ke.extend({method:P("elicitation/create"),params:Bk}),Jk=nt.extend({elicitationId:_()}),Wk=ot.extend({method:P("notifications/elicitation/complete"),params:Jk}),nn=ze.extend({action:Le(["accept","decline","cancel"]),content:Ic(e=>e===null?void 0:e,X(_(),re([_(),W(),xe(),L(_())])).optional())}),Gk=z({type:P("ref/resource"),uri:_()});var Yk=z({type:P("ref/prompt"),name:_()}),Xk=et.extend({ref:re([Yk,Gk]),argument:z({name:_(),value:_()}),context:z({arguments:X(_(),_()).optional()}).optional()}),tu=ke.extend({method:P("completion/complete"),params:Xk});var Qk=ze.extend({completion:De({values:L(_()).max(100),total:ae(W().int()),hasMore:ae(xe())})}),ez=z({uri:_().startsWith("file://"),name:_().optional(),_meta:X(_(),se()).optional()}),tz=ke.extend({method:P("roots/list"),params:et.optional()}),ru=ze.extend({roots:L(ez)}),nu=ot.extend({method:P("notifications/roots/list_changed"),params:nt.optional()}),BD=re([es,qc,tu,Qc,Kc,Bc,Lc,Uc,Hc,tk,nk,ho,Xc,rs,os,is,as]),KD=re([Qi,ts,Fc,nu,po]),JD=re([Xi,yo,eu,nn,ru,ns,ss,tn]),WD=re([es,Ak,Kk,tz,rs,os,is,as]),GD=re([Qi,ts,Sk,ik,Q$,xk,hk,po,Wk]),YD=re([Xi,L$,Qk,mk,ck,W$,G$,X$,cs,_k,ns,ss,tn]),C=class e extends Error{constructor(t,r,n){super(`MCP error ${t}: ${r}`),this.code=t,this.data=n,this.name="McpError"}static fromError(t,r,n){if(t===D.UrlElicitationRequired&&n){let o=n;if(o.elicitations)return new Rc(o.elicitations,r)}return new e(t,r,n)}},Rc=class extends C{constructor(t,r=`URL elicitation${t.length>1?"s":""} required`){super(D.UrlElicitationRequired,r,{elicitations:t})}get elicitations(){return this.data?.elicitations??[]}};var rz=10*1024*1024,us=class{constructor(t){this._maxBufferSize=t?.maxBufferSize??rz}append(t){if((this._buffer?.length??0)+t.length>this._maxBufferSize)throw this.clear(),new Error(`ReadBuffer exceeded maximum size of ${this._maxBufferSize} bytes`);this._buffer=this._buffer?Buffer.concat([this._buffer,t]):t}readMessage(){if(!this._buffer)return null;let t=this._buffer.indexOf(` +`);if(t===-1)return null;let r=this._buffer.toString("utf8",0,t).replace(/\r$/,"");return this._buffer=this._buffer.subarray(t+1),nz(r)}clear(){this._buffer=void 0}};function nz(e){return hg.parse(JSON.parse(e))}function Sg(e){return JSON.stringify(e)+` +`}var ls=class{constructor(t=ou.default.stdin,r=ou.default.stdout,n){this._stdin=t,this._stdout=r,this._started=!1,this._ondata=o=>{try{this._readBuffer.append(o),this.processReadBuffer()}catch(i){this.onerror?.(i),this.close().catch(()=>{})}},this._onerror=o=>{this.onerror?.(o)},this._readBuffer=new us({maxBufferSize:n?.maxBufferSize})}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(;;)try{let t=this._readBuffer.readMessage();if(t===null)break;this.onmessage?.(t)}catch(t){this.onerror?.(t)}}async close(){this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(t){return new Promise(r=>{let n=Sg(t);this._stdout.write(n)?r():this._stdout.once("drain",r)})}};var eb=require("node:path"),tb=require("node:fs/promises");function fs(e){return!!e._zod}function Xt(e,t){return fs(e)?Ka(e,t):e.safeParse(t)}function ds(e){if(!e)return;let t;if(fs(e)?t=e._zod?.def?.shape:t=e.shape,!!t){if(typeof t=="function")try{return t()}catch{return}return t}}function ps(e){if(fs(e)){let i=e._zod?.def;if(i){if(i.value!==void 0)return i.value;if(Array.isArray(i.values)&&i.values.length>0)return i.values[0]}}let r=e._def;if(r){if(r.value!==void 0)return r.value;if(Array.isArray(r.values)&&r.values.length>0)return r.values[0]}let n=e.value;if(n!==void 0)return n}function Qt(e){return e==="completed"||e==="failed"||e==="cancelled"}var WM=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function iu(e){let r=ds(e)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=ps(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function su(e,t){let r=Xt(e,t);if(!r.success)throw r.error;return r.data}var lz=6e4,ms=class{constructor(t){this._options=t,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(Qi,r=>{this._oncancel(r)}),this.setNotificationHandler(ts,r=>{this._onprogress(r)}),this.setRequestHandler(es,r=>({})),this._taskStore=t?.taskStore,this._taskMessageQueue=t?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(rs,async(r,n)=>{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new C(D.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(os,async(r,n)=>{let o=async()=>{let i=r.params.taskId;if(!await this._taskStore.getTask(i,n.sessionId))throw new C(D.InvalidParams,`Task not found: ${i}`);if(this._taskMessageQueue){let a;for(;a=await this._taskMessageQueue.dequeue(i,n.sessionId);){if(a.type==="response"||a.type==="error"){let c=a.message,u=c.id,l=this._requestResolvers.get(u);if(l)if(this._requestResolvers.delete(u),a.type==="response")l(c);else{let f=c,d=new C(f.error.code,f.error.message,f.error.data);l(d)}else{let f=a.type==="response"?"Response":"Error";this._onerror(new Error(`${f} handler missing for request ${u}`))}continue}await this._transport?.send(a.message,{relatedRequestId:n.requestId})}}let s=await this._taskStore.getTask(i,n.sessionId);if(!s)throw new C(D.InvalidParams,`Task not found: ${i}`);if(!Qt(s.status))return await this._waitForTaskUpdate(i,n.signal,n.sessionId),await o();if(Qt(s.status)){let a=await this._taskStore.getTaskResult(i,n.sessionId);return this._clearTaskQueue(i,n.sessionId),{...a,_meta:{...a._meta,[Yt]:{taskId:i}}}}return await o()};return await o()}),this.setRequestHandler(is,async(r,n)=>{try{let{tasks:o,nextCursor:i}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:o,nextCursor:i,_meta:{}}}catch(o){throw new C(D.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(as,async(r,n)=>{try{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new C(D.InvalidParams,`Task not found: ${r.params.taskId}`);if(Qt(o.status))throw new C(D.InvalidParams,`Cannot cancel task in terminal status: ${o.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId,n.sessionId);let i=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!i)throw new C(D.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...i}}catch(o){throw o instanceof C?o:new C(D.InvalidRequest,`Failed to cancel task: ${o instanceof Error?o.message:String(o)}`)}}))}async _oncancel(t){if(!t.params.requestId)return;this._requestHandlerAbortControllers.get(t.params.requestId)?.abort(t.params.reason)}_setupTimeout(t,r,n,o,i=!1){this._timeoutInfo.set(t,{timeoutId:setTimeout(o,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:i,onTimeout:o})}_resetTimeout(t){let r=this._timeoutInfo.get(t);if(!r)return!1;let n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(t),C.fromError(D.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(t){let r=this._timeoutInfo.get(t);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(t))}async connect(t){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=t;let r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=i=>{n?.(i),this._onerror(i)};let o=this._transport?.onmessage;this._transport.onmessage=(i,s)=>{o?.(i,s),ao(i)||mg(i)?this._onresponse(i):jc(i)?this._onrequest(i,s):pg(i)?this._onnotification(i):this._onerror(new Error(`Unknown message type: ${JSON.stringify(i)}`))},await this._transport.start()}_onclose(){let t=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let n of this._timeoutInfo.values())clearTimeout(n.timeoutId);this._timeoutInfo.clear();for(let n of this._requestHandlerAbortControllers.values())n.abort();this._requestHandlerAbortControllers.clear();let r=C.fromError(D.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let n of t.values())n(r)}_onerror(t){this.onerror?.(t)}_onnotification(t){let r=this._notificationHandlers.get(t.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(t)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(t,r){let n=this._requestHandlers.get(t.method)??this.fallbackRequestHandler,o=this._transport,i=t.params?._meta?.[Yt]?.taskId,s=o?.sessionId,a=this._taskStore,c=!0,u;if(i&&a&&this._taskMessageQueue&&s!==void 0&&(c=!1,u=(async()=>{if(!await a.getTask(i,s))throw new C(D.InvalidParams,`Task not found: ${i}`);c=!0})()),n===void 0){let m={jsonrpc:"2.0",id:t.id,error:{code:D.MethodNotFound,message:"Method not found"}};if(i&&u){let h={type:"error",message:m,timestamp:Date.now()};u.then(()=>this._enqueueTaskMessage(i,h,s),()=>o?.send(m)).catch(g=>this._onerror(new Error(`Failed to send an error response: ${g}`)))}else i&&this._taskMessageQueue?this._enqueueTaskMessage(i,{type:"error",message:m,timestamp:Date.now()},o?.sessionId).catch(h=>this._onerror(new Error(`Failed to enqueue error response: ${h}`))):o?.send(m).catch(h=>this._onerror(new Error(`Failed to send an error response: ${h}`)));return}let l=new AbortController;this._requestHandlerAbortControllers.set(t.id,l);let f=lg(t.params)?t.params.task:void 0,d=this._taskStore?this.requestTaskStore(t,o?.sessionId):void 0,p={signal:l.signal,sessionId:o?.sessionId,_meta:t.params?._meta,sendNotification:async m=>{if(l.signal.aborted)return;let h={relatedRequestId:t.id};i&&(h.relatedTask={taskId:i}),await this.notification(m,h)},sendRequest:async(m,h,g)=>{if(l.signal.aborted)throw new C(D.ConnectionClosed,"Request was cancelled");let y={...g,relatedRequestId:t.id};i&&!y.relatedTask&&(y.relatedTask={taskId:i});let v=y.relatedTask?.taskId??i;return v&&d&&await d.updateTaskStatus(v,"input_required"),await this.request(m,h,y)},authInfo:r?.authInfo,requestId:t.id,requestInfo:r?.requestInfo,taskId:i,taskStore:d,taskRequestedTtl:f?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};(u??Promise.resolve()).then(()=>{if(u&&l.signal.aborted)throw new C(D.ConnectionClosed,"Request was cancelled");f&&this.assertTaskHandlerCapability(t.method)}).then(()=>n(t,p)).then(async m=>{if(l.signal.aborted)return;let h={result:m,jsonrpc:"2.0",id:t.id};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:"response",message:h,timestamp:Date.now()},o?.sessionId):await o?.send(h)},async m=>{if(l.signal.aborted)return;let h={jsonrpc:"2.0",id:t.id,error:{code:Number.isSafeInteger(m.code)?m.code:D.InternalError,message:m.message??"Internal error",...m.data!==void 0&&{data:m.data}}};i&&this._taskMessageQueue&&c?await this._enqueueTaskMessage(i,{type:"error",message:h,timestamp:Date.now()},o?.sessionId):await o?.send(h)}).catch(m=>this._onerror(new Error(`Failed to send response: ${m}`))).finally(()=>{this._requestHandlerAbortControllers.get(t.id)===l&&this._requestHandlerAbortControllers.delete(t.id)})}_onprogress(t){let{progressToken:r,...n}=t.params,o=Number(r),i=this._progressHandlers.get(o);if(!i){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(t)}`));return}let s=this._responseHandlers.get(o),a=this._timeoutInfo.get(o);if(a&&s&&a.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(c){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),s(c);return}i(n)}_onresponse(t){let r=Number(t.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),ao(t))n(t);else{let s=new C(t.error.code,t.error.message,t.error.data);n(s)}return}let o=this._responseHandlers.get(r);if(o===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(t)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let i=!1;if(ao(t)&&t.result&&typeof t.result=="object"){let s=t.result;if(s.task&&typeof s.task=="object"){let a=s.task;typeof a.taskId=="string"&&(i=!0,this._taskProgressTokens.set(a.taskId,r))}}if(i||this._progressHandlers.delete(r),ao(t))o(t);else{let s=C.fromError(t.error.code,t.error.message,t.error.data);o(s)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(t,r,n){let{task:o}=n??{};if(!o){try{yield{type:"result",result:await this.request(t,r,n)}}catch(s){yield{type:"error",error:s instanceof C?s:new C(D.InternalError,String(s))}}return}let i;try{let s=await this.request(t,tn,n);if(s.task)i=s.task.taskId,yield{type:"taskCreated",task:s.task};else throw new C(D.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:i},n);if(yield{type:"taskStatus",task:a},Qt(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:i},r,n)}:a.status==="failed"?yield{type:"error",error:new C(D.InternalError,`Task ${i} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new C(D.InternalError,`Task ${i} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:i},r,n)};return}let c=a.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(u=>setTimeout(u,c)),n?.signal?.throwIfAborted()}}catch(s){yield{type:"error",error:s instanceof C?s:new C(D.InternalError,String(s))}}}request(t,r,n){let{relatedRequestId:o,resumptionToken:i,onresumptiontoken:s,task:a,relatedTask:c}=n??{};return new Promise((u,l)=>{let f=v=>{l(v)};if(!this._transport){f(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(t.method),a&&this.assertTaskCapability(t.method)}catch(v){f(v);return}n?.signal?.throwIfAborted();let d=this._requestMessageId++,p={...t,jsonrpc:"2.0",id:d};n?.onprogress&&(this._progressHandlers.set(d,n.onprogress),p.params={...t.params,_meta:{...t.params?._meta||{},progressToken:d}}),a&&(p.params={...p.params,task:a}),c&&(p.params={...p.params,_meta:{...p.params?._meta||{},[Yt]:c}});let m=v=>{this._responseHandlers.delete(d),this._progressHandlers.delete(d),this._cleanupTimeout(d),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:d,reason:String(v)}},{relatedRequestId:o,resumptionToken:i,onresumptiontoken:s}).catch(k=>this._onerror(new Error(`Failed to send cancellation: ${k}`)));let S=v instanceof C?v:new C(D.RequestTimeout,String(v));l(S)};this._responseHandlers.set(d,v=>{if(!n?.signal?.aborted){if(v instanceof Error)return l(v);try{let S=Xt(r,v.result);S.success?u(S.data):l(S.error)}catch(S){l(S)}}}),n?.signal?.addEventListener("abort",()=>{m(n?.signal?.reason)});let h=n?.timeout??lz,g=()=>m(C.fromError(D.RequestTimeout,"Request timed out",{timeout:h}));this._setupTimeout(d,h,n?.maxTotalTimeout,g,n?.resetTimeoutOnProgress??!1);let y=c?.taskId;if(y){let v=S=>{let k=this._responseHandlers.get(d);k?k(S):this._onerror(new Error(`Response handler missing for side-channeled request ${d}`))};this._requestResolvers.set(d,v),this._enqueueTaskMessage(y,{type:"request",message:p,timestamp:Date.now()}).catch(S=>{this._cleanupTimeout(d),l(S)})}else this._transport.send(p,{relatedRequestId:o,resumptionToken:i,onresumptiontoken:s}).catch(v=>{this._cleanupTimeout(d),l(v)})})}async getTask(t,r){return this.request({method:"tasks/get",params:t},ns,r)}async getTaskResult(t,r,n){return this.request({method:"tasks/result",params:t},r,n)}async listTasks(t,r){return this.request({method:"tasks/list",params:t},ss,r)}async cancelTask(t,r){return this.request({method:"tasks/cancel",params:t},yg,r)}async notification(t,r){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(t.method);let n=r?.relatedTask?.taskId;if(n){let a={...t,jsonrpc:"2.0",params:{...t.params,_meta:{...t.params?._meta||{},[Yt]:r.relatedTask}}};await this._enqueueTaskMessage(n,{type:"notification",message:a,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(t.method)&&!t.params&&!r?.relatedRequestId&&!r?.relatedTask){if(this._pendingDebouncedNotifications.has(t.method))return;this._pendingDebouncedNotifications.add(t.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(t.method),!this._transport)return;let a={...t,jsonrpc:"2.0"};r?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[Yt]:r.relatedTask}}}),this._transport?.send(a,r).catch(c=>this._onerror(c))});return}let s={...t,jsonrpc:"2.0"};r?.relatedTask&&(s={...s,params:{...s.params,_meta:{...s.params?._meta||{},[Yt]:r.relatedTask}}}),await this._transport.send(s,r)}setRequestHandler(t,r){let n=iu(t);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,i)=>{let s=su(t,o);return Promise.resolve(r(s,i))})}removeRequestHandler(t){this._requestHandlers.delete(t)}assertCanSetRequestHandler(t){if(this._requestHandlers.has(t))throw new Error(`A request handler for ${t} already exists, which would be overridden`)}setNotificationHandler(t,r){let n=iu(t);this._notificationHandlers.set(n,o=>{let i=su(t,o);return Promise.resolve(r(i))})}removeNotificationHandler(t){this._notificationHandlers.delete(t)}_cleanupTaskProgressHandler(t){let r=this._taskProgressTokens.get(t);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(t))}async _enqueueTaskMessage(t,r,n){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let o=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(t,r,n??this._transport?.sessionId,o)}async _clearTaskQueue(t,r){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(t,r);for(let o of n)if(o.type==="request"&&jc(o.message)){let i=o.message.id,s=this._requestResolvers.get(i);s?(s(new C(D.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(i)):this._onerror(new Error(`Resolver missing for request ${i} during task ${t} cleanup`))}}}async _waitForTaskUpdate(t,r,n){let o=this._options?.defaultTaskPollInterval??1e3;try{let i=await this._taskStore?.getTask(t,n);i?.pollInterval&&(o=i.pollInterval)}catch{}return new Promise((i,s)=>{if(r.aborted){s(new C(D.InvalidRequest,"Request cancelled"));return}let a=setTimeout(i,o);r.addEventListener("abort",()=>{clearTimeout(a),s(new C(D.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(t,r){let n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async o=>{if(!t)throw new Error("No request provided");return await n.createTask(o,t.id,{method:t.method,params:t.params},r)},getTask:async o=>{let i=await n.getTask(o,r);if(!i)throw new C(D.InvalidParams,"Failed to retrieve task: Task not found");return i},storeTaskResult:async(o,i,s)=>{await n.storeTaskResult(o,i,s,r);let a=await n.getTask(o,r);if(a){let c=po.parse({method:"notifications/tasks/status",params:a});await this.notification(c),Qt(a.status)&&this._cleanupTaskProgressHandler(o)}},getTaskResult:o=>n.getTaskResult(o,r),updateTaskStatus:async(o,i,s)=>{let a=await n.getTask(o,r);if(!a)throw new C(D.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(Qt(a.status))throw new C(D.InvalidParams,`Cannot update task "${o}" from terminal status "${a.status}" to "${i}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(o,i,s,r);let c=await n.getTask(o,r);if(c){let u=po.parse({method:"notifications/tasks/status",params:c});await this.notification(u),Qt(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}};function $g(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function kg(e,t){let r={...e};for(let n in t){let o=n,i=t[o];if(i===void 0)continue;let s=r[o];$g(s)&&$g(i)?r[o]={...s,...i}:r[o]=i}return r}var P0=ui(Yl(),1),E0=ui(z0(),1);function S1(){let e=new P0.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,E0.default)(e),e}var Qs=class{constructor(t){this._ajv=t??S1()}getValidator(t){let r="$id"in t&&typeof t.$id=="string"?this._ajv.getSchema(t.$id)??this._ajv.compile(t):this._ajv.compile(t);return n=>r(n)?{valid:!0,data:n,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(r.errors)}}};var ea=class{constructor(t){this._server=t}requestStream(t,r,n){return this._server.requestStream(t,r,n)}createMessageStream(t,r){let n=this._server.getClientCapabilities();if((t.tools||t.toolChoice)&&!n?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(t.messages.length>0){let o=t.messages[t.messages.length-1],i=Array.isArray(o.content)?o.content:[o.content],s=i.some(l=>l.type==="tool_result"),a=t.messages.length>1?t.messages[t.messages.length-2]:void 0,c=a?Array.isArray(a.content)?a.content:[a.content]:[],u=c.some(l=>l.type==="tool_use");if(s){if(i.some(l=>l.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!u)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(u){let l=new Set(c.filter(d=>d.type==="tool_use").map(d=>d.id)),f=new Set(i.filter(d=>d.type==="tool_result").map(d=>d.toolUseId));if(l.size!==f.size||![...l].every(d=>f.has(d)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.requestStream({method:"sampling/createMessage",params:t},yo,r)}elicitInputStream(t,r){let n=this._server.getClientCapabilities(),o=t.mode??"form";switch(o){case"url":{if(!n?.elicitation?.url)throw new Error("Client does not support url elicitation.");break}case"form":{if(!n?.elicitation?.form)throw new Error("Client does not support form elicitation.");break}}let i=o==="form"&&t.mode===void 0?{...t,mode:"form"}:t;return this.requestStream({method:"elicitation/create",params:i},nn,r)}async getTask(t,r){return this._server.getTask({taskId:t},r)}async getTaskResult(t,r,n){return this._server.getTaskResult({taskId:t},r,n)}async listTasks(t,r){return this._server.listTasks(t?{cursor:t}:void 0,r)}async cancelTask(t,r){return this._server.cancelTask({taskId:t},r)}};function T0(e,t,r){if(!e)throw new Error(`${r} does not support task creation (required for ${t})`);switch(t){case"tools/call":if(!e.tools?.call)throw new Error(`${r} does not support task creation for tools/call (required for ${t})`);break;default:break}}function O0(e,t,r){if(!e)throw new Error(`${r} does not support task creation (required for ${t})`);switch(t){case"sampling/createMessage":if(!e.sampling?.createMessage)throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${t})`);break;case"elicitation/create":if(!e.elicitation?.create)throw new Error(`${r} does not support task creation for elicitation/create (required for ${t})`);break;default:break}}var ta=class extends ms{constructor(t,r){super(r),this._serverInfo=t,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(go.options.map((n,o)=>[n,o])),this.isMessageIgnored=(n,o)=>{let i=this._loggingLevels.get(o);return i?this.LOG_LEVEL_SEVERITY.get(n)this._oninitialize(n)),this.setNotificationHandler(Fc,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(Qc,async(n,o)=>{let i=o.sessionId||o.requestInfo?.headers["mcp-session-id"]||void 0,{level:s}=n.params,a=go.safeParse(s);return a.success&&this._loggingLevels.set(i,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new ea(this)}),this._experimental}registerCapabilities(t){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=kg(this._capabilities,t)}setRequestHandler(t,r){let o=ds(t)?.method;if(!o)throw new Error("Schema is missing a method literal");let i=ps(o);if(typeof i!="string")throw new Error("Schema method literal must be a string");if(i==="tools/call"){let a=async(c,u)=>{let l=Xt(ho,c);if(!l.success){let m=l.error instanceof Error?l.error.message:String(l.error);throw new C(D.InvalidParams,`Invalid tools/call request: ${m}`)}let{params:f}=l.data,d=await Promise.resolve(r(c,u));if(f.task){let m=Xt(tn,d);if(!m.success){let h=m.error instanceof Error?m.error.message:String(m.error);throw new C(D.InvalidParams,`Invalid task creation result: ${h}`)}return m.data}let p=Xt(cs,d);if(!p.success){let m=p.error instanceof Error?p.error.message:String(p.error);throw new C(D.InvalidParams,`Invalid tools/call result: ${m}`)}return p.data};return super.setRequestHandler(t,a)}return super.setRequestHandler(t,r)}assertCapabilityForMethod(t){switch(t){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${t})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${t})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${t})`);break;case"ping":break}}assertNotificationCapability(t){switch(t){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${t})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${t})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${t})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${t})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${t})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(t){if(this._capabilities)switch(t){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${t})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${t})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${t})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${t})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${t})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${t})`);break;case"ping":case"initialize":break}}assertTaskCapability(t){O0(this._clientCapabilities?.tasks?.requests,t,"Client")}assertTaskHandlerCapability(t){this._capabilities&&T0(this._capabilities.tasks?.requests,t,"Server")}async _oninitialize(t){let r=t.params.protocolVersion;return this._clientCapabilities=t.params.capabilities,this._clientVersion=t.params.clientInfo,{protocolVersion:ag.includes(r)?r:Cc,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},Xi)}async createMessage(t,r){if((t.tools||t.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(t.messages.length>0){let n=t.messages[t.messages.length-1],o=Array.isArray(n.content)?n.content:[n.content],i=o.some(u=>u.type==="tool_result"),s=t.messages.length>1?t.messages[t.messages.length-2]:void 0,a=s?Array.isArray(s.content)?s.content:[s.content]:[],c=a.some(u=>u.type==="tool_use");if(i){if(o.some(u=>u.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!c)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(c){let u=new Set(a.filter(f=>f.type==="tool_use").map(f=>f.id)),l=new Set(o.filter(f=>f.type==="tool_result").map(f=>f.toolUseId));if(u.size!==l.size||![...u].every(f=>l.has(f)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return t.tools?this.request({method:"sampling/createMessage",params:t},eu,r):this.request({method:"sampling/createMessage",params:t},yo,r)}async elicitInput(t,r){switch(t.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");let o=t;return this.request({method:"elicitation/create",params:o},nn,r)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let o=t.mode==="form"?t:{...t,mode:"form"},i=await this.request({method:"elicitation/create",params:o},nn,r);if(i.action==="accept"&&i.content&&o.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(o.requestedSchema)(i.content);if(!a.valid)throw new C(D.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(s){throw s instanceof C?s:new C(D.InternalError,`Error validating elicitation response: ${s instanceof Error?s.message:String(s)}`)}return i}}}createElicitationCompletionNotifier(t,r){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:t}},r)}async listRoots(t,r){return this.request({method:"roots/list",params:t},ru,r)}async sendLoggingMessage(t,r){if(this._capabilities.logging&&!this.isMessageIgnored(t.level,r))return this.notification({method:"notifications/message",params:t})}async sendResourceUpdated(t){return this.notification({method:"notifications/resources/updated",params:t})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}};var ut=".wiki",A0="0.1.2";var Fr=require("node:path");var mv=require("node:fs/promises"),Tt=require("node:path");var zf=ui(Xx(),1),ve=require("node:fs/promises"),J=require("node:path");function q(e){return e instanceof Error&&e.code==="ENOENT"}function pa(e){return e instanceof Error&&e.code==="EACCES"}var ev=require("node:async_hooks"),Pt=require("node:fs/promises"),ni=require("node:path");var CC=".llmwiki.lock",tv=1e4,NC=3e4,Qx=new ev.AsyncLocalStorage;function bf(e){return e?.code}function rv(e){return process.platform==="win32"&&["EPERM","EACCES","EBUSY"].includes(bf(e)??"")}function nv(e){return new Promise(t=>setTimeout(t,e))}async function ie(e,t){let r=process.platform==="win32"?(0,ni.resolve)(e).toLowerCase():(0,ni.resolve)(e),n=Qx.getStore();if(n?.has(r))return t();let o=(0,ni.join)(e,CC);if(!await jC(o))return t();let i=setInterval(()=>{let s=new Date;(0,Pt.utimes)(o,s,s).catch(()=>{})},tv/4);i.unref();try{return await Qx.run(new Set([...n??[],r]),t)}finally{clearInterval(i),await qC(o)}}async function jC(e){let t=Date.now()+NC;for(let r=5;;r=Math.min(r*2,100)){try{return await(await(0,Pt.open)(e,"wx")).close(),!0}catch(n){if(q(n))return!1;if(!(bf(n)==="EEXIST"||rv(n)&&await DC(e)))throw n;if(Date.now()>=t)throw bf(n)!=="EEXIST"?n:new Error(`Timed out waiting for another LLM Wiki write to finish. If none is running, delete ${e}.`)}if(await MC(e)){await(0,Pt.unlink)(e).catch(()=>{});continue}await nv(r)}}async function DC(e){try{return await(0,Pt.stat)(e),!0}catch(t){return!q(t)}}async function MC(e){try{return Date.now()-(await(0,Pt.stat)(e)).mtimeMs>tv}catch{return!1}}async function qC(e){for(let t=1;;t++)try{await(0,Pt.unlink)(e);return}catch(r){if(!rv(r)||t>=5)return;await nv(20)}}function lr(e){return e.replace(/\.[^.]+$/,"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function ov(e,t=200){let r=e.replace(/\s+/g," ").trim();return r.length<=t?r:r.slice(0,t)+"\u2026"}var An=require("node:fs/promises"),In=require("node:path");function Sf(e){return e.replace(/([[\]()])/g,"\\$1")}function FC(e){return e.replace(/\\([[\]()])/g,"$1")}function ZC(e,t){let n=e.trim().match(/^-\s+\[((?:[^\]\\]|\\.)+)\]\(((?:[^)\\]|\\.)+)\)(.*)$/);if(!n)return null;let o=FC(n[1]),i=n[2],s=n[3].trim(),a="",c=[];if(s){let u=s.match(/^[—–-]\s*(.*)$/),l=u?u[1]:s,f=/#([\w-]+)/g,d;for(;(d=f.exec(l))!==null;)c.push(d[1]);a=l.replace(/#[\w-]+/g,"").trim()}return{path:i,title:o,summary:a,category:t,tags:c}}function LC(e){let t=`- [${Sf(e.title)}](${e.path})`,r=[];return e.summary&&r.push(e.summary),e.tags.length>0&&r.push(e.tags.map(n=>`#${n}`).join(" ")),r.length>0&&(t+=` \u2014 ${r.join(" ")}`),t}async function _e(e){let t;try{t=await(0,An.readFile)(e,"utf-8")}catch(o){if(q(o))return[];throw o}let r=[],n="";for(let o of t.split(` +`)){let i=o.trim(),s=i.match(/^##\s+(.+)$/);if(s){n=s[1].trim();continue}if(n){let a=ZC(i,n);a&&r.push(a)}}return r}async function Mr(e,t){let r=new Map;for(let o of t)r.has(o.category)||r.set(o.category,[]),r.get(o.category).push(o);let n=`# Wiki Index +`;for(let[o,i]of r){n+=` +## ${o} + +`;for(let s of i)n+=LC(s)+` +`}await(0,An.mkdir)((0,In.dirname)(e),{recursive:!0}),await(0,An.writeFile)(e,n,"utf-8")}async function oi(e,t){await ie((0,In.dirname)(e),async()=>{let r=await _e(e);r.push(t),await Mr(e,r)})}async function $f(e,t){await ie((0,In.dirname)(e),async()=>{let r=await _e(e),n=r.findIndex(o=>o.path===t.path);n>=0?r[n]={...t,summary:t.summary||r[n].summary}:r.push(t),await Mr(e,r)})}async function Rn(e,t){await ie((0,In.dirname)(e),async()=>{let n=(await _e(e)).filter(o=>o.path!==t);await Mr(e,n)})}async function iv(e,t,r){return ie((0,In.dirname)(e),async()=>{let n=await _e(e),o=n.findIndex(s=>s.path===t);if(o<0)return!1;let i=n[o];return r.title!==void 0&&(i.title=r.title),r.summary!==void 0&&(i.summary=r.summary),r.tags!==void 0&&(i.tags=r.tags),r.category!==void 0&&(i.category=r.category),await Mr(e,n),!0})}var fr=require("node:path");async function sv(e,t){let r=await lt(e),n=[],o=t.replace(/\\/g,"/");for(let i of r){let s=await fe(i),a=kf(s.body);for(let{text:c,target:u}of a){let l=(0,fr.dirname)(i),f=(0,fr.join)(l,u);(0,fr.relative)(e,f).replace(/\\/g,"/")===o&&n.push({sourcePage:i,sourceTitle:s.frontmatter.title??(0,fr.basename)(i,".md"),linkText:c})}}return n}async function fe(e){let t=await(0,ve.readFile)(e,"utf-8"),{data:r,content:n}=(0,zf.default)(t,{});return{frontmatter:r,body:n.trim()}}async function tt(e,t){await(0,ve.mkdir)((0,J.dirname)(e),{recursive:!0});let r=zf.default.stringify(t.body,t.frontmatter);await(0,ve.writeFile)(e,r,"utf-8")}async function lt(e){try{return(await(0,ve.readdir)(e,{recursive:!0})).filter(r=>typeof r=="string"&&(0,J.extname)(r)===".md").map(r=>(0,J.join)(e,r))}catch(t){if(q(t))return[];throw t}}async function ma(e){try{return(await(0,ve.stat)(e)).isDirectory()}catch(t){if(q(t))return!1;throw t}}function kf(e){let t=/\[([^\]]+)\]\(([^)]+)\)/g,r=[],n;for(;(n=t.exec(e))!==null;){let o=n[1],i=n[2];i.endsWith(".md")&&!i.startsWith("http://")&&!i.startsWith("https://")&&r.push({text:o,target:i})}return r}function cv(e){return kf(e).map(t=>t.target)}async function uv(e,t,r,n=[]){let i=`entities/${lr(t)}.md`,s=(0,J.join)(e,i),a=new Date().toISOString();return ie(e,async()=>{await tt(s,{frontmatter:{type:"entity",title:t,tags:n,created:a},body:r});let c={path:i,title:t,summary:"",category:"Entities",tags:n},u=(0,J.join)(e,"index.md");return await $f(u,c),{path:i,indexEntry:c}})}async function lv(e,t,r,n=[]){let i=`concepts/${lr(t)}.md`,s=(0,J.join)(e,i),a=new Date().toISOString();return ie(e,async()=>{await tt(s,{frontmatter:{type:"concept",title:t,tags:n,created:a},body:r});let c={path:i,title:t,summary:"",category:"Concepts",tags:n},u=(0,J.join)(e,"index.md");return await $f(u,c),{path:i,indexEntry:c}})}async function fv(e,t,r){r.length!==0&&await ie(e,()=>UC(e,t,r))}async function UC(e,t,r){let n=(0,J.join)(e,t);try{await(0,ve.stat)(n)}catch(l){throw q(l)?new Error(`Source page not found: ${t}`):l}let o=[];for(let l of r)try{await(0,ve.stat)((0,J.join)(e,l))}catch(f){if(q(f))o.push(l);else throw f}if(o.length>0)throw new Error(`Target pages not found: ${o.join(", ")}`);let i=await fe(n),s=[];for(let l of r){let f=(0,J.join)(e,l),d;try{d=(await fe(f)).frontmatter.title||l.replace(/\.md$/,"").split("/").pop()}catch{d=l.replace(/\.md$/,"").split("/").pop()}let p=(0,J.relative)((0,J.dirname)(n),f).replace(/\\/g,"/");s.push(`- [${Sf(d)}](${p})`)}let a="## See also",c=i.body.indexOf(a),u;if(c!==-1){let l=c+a.length,f=i.body.slice(l).search(/\n## /),d=f!==-1?l+f:i.body.length,p=i.body.slice(l,d),m=new Set(p.split(` +`).map(v=>v.trim()).filter(v=>v.startsWith("- ["))),h=s.filter(v=>!m.has(v));if(h.length===0)return;let g=i.body.slice(0,d).trimEnd(),y=i.body.slice(d);u=g+` +`+h.join(` +`)+y}else u=i.body.trimEnd()+` + +`+a+` + +`+s.join(` +`);await tt(n,{frontmatter:i.frontmatter,body:u})}function ha(e){let t=e.replace(/\\/g,"/").toLowerCase();return t==="index.md"||t==="log.md"}function av(e,t){let r=(0,J.relative)(e,t);return r!==""&&r!==".."&&!r.startsWith(`..${J.sep}`)&&!(0,J.isAbsolute)(r)}async function VC(e,t){let r=(0,J.resolve)(e),n=(0,J.resolve)(r,t);if(!av(r,n))throw new Error("Path traversal detected \u2014 pagePath must stay within wikiDir");let o,i;try{o=await(0,ve.realpath)(r),i=await(0,ve.realpath)((0,J.dirname)(n))}catch(a){throw q(a)?new Error(`Page not found: ${t}`):a}let s=(0,J.join)(i,(0,J.basename)(n));if(!av(o,s))throw new Error("Path traversal detected \u2014 pagePath must stay within wikiDir");for(let a of[(0,J.relative)(r,n),(0,J.relative)(o,s)])if(ha(a))throw new Error(`'${a.replace(/\\/g,"/")}' is a special wiki file and cannot be deleted`);return s}async function ga(e,t){let r=await VC(e,t);return ie(e,async()=>{try{await(0,ve.stat)(r)}catch(i){throw q(i)?new Error(`Page not found: ${t}`):i}let n=await sv(e,t),o=(0,J.join)(e,"index.md");return await Rn(o,t),await(0,ve.unlink)(r),{deletedPath:t,deleted:!0,backlinkWarnings:n}})}var Cn=require("node:fs/promises"),dv=require("node:path");async function Et(e,t){let n=`## [${t.date??new Date().toISOString().slice(0,10)}] ${t.verb} | ${t.subject} + +${t.details} + +`;await(0,Cn.mkdir)((0,dv.dirname)(e),{recursive:!0}),await(0,Cn.appendFile)(e,n,"utf-8")}async function pv(e){let t;try{t=await(0,Cn.readFile)(e,"utf-8")}catch(a){if(q(a))return[];throw a}if(!t.trim())return[];let r=[],n=/^## \[(\d{4}-\d{2}-\d{2})\] (\S+) \| (.+)$/,o=t.replace(/\r\n/g,` +`).split(` +`),i=null,s=[];for(let a of o){let c=a.match(n);c?(i&&r.push({...i,details:s.join(` +`).trim()}),i={date:c[1],verb:c[2],subject:c[3].trim()},s=[]):i&&s.push(a)}return i&&r.push({...i,details:s.join(` +`).trim()}),r}async function ya(e){let t=(0,Tt.resolve)(e),r=(0,Tt.join)(t,"raw"),n=(0,Tt.join)(t,"wiki"),o=(0,Tt.join)(n,"index.md"),i=(0,Tt.join)(n,"log.md"),s=0;try{s=(await(0,mv.readdir)(r,{withFileTypes:!0,recursive:!0})).filter($=>$.isFile()).length}catch(k){if(!q(k))throw k}let c=(await lt(n)).filter(k=>{let $=(0,Tt.relative)(n,k).replace(/\\/g,"/");return $!=="index.md"&&$!=="log.md"}),u=c.length,l=await pv(i),f=l.filter(k=>k.verb.toLowerCase().includes("ingest")),d=l.filter(k=>k.verb.toLowerCase().includes("lint")),p=f.length>0?f[f.length-1].date:null,m=d.length>0?d[d.length-1].date:null,h=await _e(o),g=new Set(h.map(k=>k.path)),y=c.filter(k=>{let $=(0,Tt.relative)(n,k).replace(/\\/g,"/");return!g.has($)}).length,v=u-y,S=u>0?Math.round(v/u*100):100;return{command:"status",api_version:"1",source_count:s,wiki_page_count:u,last_ingest_date:p,last_lint_date:m,orphan_page_count:y,index_coverage_pct:S}}var Vt=require("node:path"),hv=require("node:fs/promises");function _a(e,t){let r=e.toLowerCase(),n=t.toLowerCase();if(!n)return 0;let o=0,i=0;for(;(i=r.indexOf(n,i))!==-1;)o++,i+=n.length;return o}function HC(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,50)}async function wa(e,t,r=!1){let n=(0,Vt.resolve)(t),o=(0,Vt.join)(n,"wiki"),i=(0,Vt.join)(o,"index.md");if(!await ma(o))return{command:"query",api_version:"1",query:e,matches:0,results:[]};let s=await _e(i),a=e.toLowerCase().split(/\s+/).filter(Boolean);if(a.length===0)return{command:"query",api_version:"1",query:e,matches:0,results:[]};let c=[];for(let f of s){let d=0;for(let p of a)d+=_a(f.title,p)*3,d+=_a(f.summary,p)*2;d>0&&c.push({entry:f,indexScore:d})}let u=[];for(let{entry:f,indexScore:d}of c){let p=0,m="";try{let h=(0,Vt.join)(o,f.path);m=(await fe(h)).body;for(let y of a)p+=_a(m,y)}catch(h){if(!q(h))throw h}u.push({title:f.title,path:f.path,score:d+p,excerpt:ov(m)})}u.sort((f,d)=>d.score-f.score);let l={command:"query",api_version:"1",query:e,matches:u.length,results:u};if(r&&u.length>0){let d=`queries/${HC(e)}.md`,p=(0,Vt.join)(o,d),m=new Date().toISOString().slice(0,10);await(0,hv.mkdir)((0,Vt.join)(o,"queries"),{recursive:!0});let h=`# Query: ${e} + +`;h+=`Found ${u.length} result(s). + +`;for(let g of u)h+=`## ${g.title} + +`,h+=`- **Path:** ${g.path} +`,h+=`- **Score:** ${g.score} +`,h+=`- **Excerpt:** ${g.excerpt} + +`;await ie(o,async()=>{await tt(p,{frontmatter:{type:"query",title:`Query: ${e}`,created:m,query:e},body:h.trim()});let g=(0,Vt.join)(o,"log.md");await Et(g,{verb:"queried",subject:e,details:`Saved query "${e}" \u2192 ${d} (${u.length} results)`})}),l.saved=d}return l}var xa=require("node:fs/promises"),Q=require("node:path");async function BC(e){try{return await(0,xa.access)(e,xa.constants.F_OK),!0}catch(t){if(q(t))return!1;throw t}}function dr(e){return e.replace(/\\/g,"/")}async function Ef(e,t,r={}){let n=(0,Q.resolve)(e),o=(0,Q.join)(n,"wiki"),i=(0,Q.join)(o,"index.md"),s=new Set([...r.assumeDeleted??[]].map(dr)),a=[],c=b=>!t||t.length===0||t.includes(b),l=(await lt(o)).filter(b=>{let T=dr((0,Q.relative)(o,b));return T!=="index.md"&&T!=="log.md"&&!s.has(T)}),f=new Set(l.map(b=>dr((0,Q.relative)(o,b)))),d=new Map,p=new Map,m=new Map,h=new Set;for(let b of l)try{let T=await fe(b);d.set(b,T.body),p.set(b,T.frontmatter);let F=cv(T.body),me=[];for(let ft of F){let Bt=(0,Q.resolve)((0,Q.dirname)(b),ft),hr=dr((0,Q.relative)(o,Bt));me.push(hr),h.add(hr)}m.set(b,me)}catch(T){if(!q(T))throw T}let g=(await _e(i)).filter(b=>!s.has(b.path)),y=new Set(g.map(b=>dr(b.path)));if(c("broken-links"))for(let[b,T]of m){let F=dr((0,Q.relative)(o,b));for(let me of T)f.has(me)||a.push({severity:"error",category:"broken-links",message:`Broken link to "${me}" in page "${F}"`,file:F})}if(c("orphan-pages"))for(let b of f)!h.has(b)&&!y.has(b)&&a.push({severity:"warning",category:"orphan-pages",message:`Orphan page "${b}" \u2014 not linked and not indexed`,file:b});if(c("index-completeness"))for(let b of f)y.has(b)||a.push({severity:"warning",category:"index-completeness",message:`Page "${b}" is not listed in index.md`,file:b});if(c("stale-entries"))for(let b of g){let T=dr(b.path),F=(0,Q.join)(o,T);(s.has(T)||!await BC(F))&&a.push({severity:"error",category:"stale-entries",message:`Stale index entry "${b.title}" points to missing file "${T}"`,file:T})}if(c("missing-pages")){let b=new Set;for(let[,T]of m)for(let F of T)!f.has(F)&&!b.has(F)&&(b.add(F),a.push({severity:"info",category:"missing-pages",message:`Referenced page "${F}" does not exist`,file:F}))}if(c("frontmatter-validation")){let b=["entity","concept","source","summary","query"];for(let T of l){let F=dr((0,Q.relative)(o,T)),me=p.get(T);me&&(me.type?b.includes(me.type)||a.push({severity:"warning",category:"frontmatter-validation",message:`Invalid type "${me.type}" in "${F}" \u2014 expected one of: ${b.join(", ")}`,file:F}):a.push({severity:"error",category:"frontmatter-validation",message:`Missing required "type" field in frontmatter of "${F}"`,file:F}),me.title||a.push({severity:"error",category:"frontmatter-validation",message:`Missing required "title" field in frontmatter of "${F}"`,file:F}),me.tags||a.push({severity:"info",category:"frontmatter-validation",message:`Missing recommended "tags" field in "${F}"`,file:F}),me.created||a.push({severity:"info",category:"frontmatter-validation",message:`Missing recommended "created" field in "${F}"`,file:F}))}}let v=a.filter(b=>b.severity==="error").length,S=a.filter(b=>b.severity==="warning").length,k=a.filter(b=>b.severity==="info").length,$={};for(let b of a)$[b.category]=($[b.category]??0)+1;return{command:"lint",api_version:"1",findings:a,errorCount:v,warningCount:S,infoCount:k,categorySummary:$}}var KC=new Set(["stale-entries","index-completeness","frontmatter-validation"]);function Pf(e){return(0,Q.basename)(e,".md").replace(/[-_]/g," ").replace(/\b\w/g,r=>r.toUpperCase())}function gv(e){let t=(0,Q.dirname)(e);if(t===".")return"Uncategorized";let r=t.split("/")[0];return r.charAt(0).toUpperCase()+r.slice(1)}async function _v(e,t={}){return t.dryRun?yv(e,t):ie((0,Q.join)((0,Q.resolve)(e),"wiki"),()=>yv(e,t))}async function yv(e,t){let r=(0,Q.resolve)(e),n=(0,Q.join)(r,"wiki"),o=(0,Q.join)(n,"index.md"),i=t.dryRun===!0,s=await Ef(e,void 0,{assumeDeleted:t.assumeDeleted}),a=[],c=[],u=[];for(let h of s.findings)KC.has(h.category)||h.category==="orphan-pages"&&t.fixOrphans?u.push(h):c.push(h);let l=u.filter(h=>h.category==="stale-entries");for(let h of l){if(!h.file){c.push(h);continue}try{i||await Rn(o,h.file),a.push(h)}catch{c.push(h)}}let f=u.filter(h=>h.category==="index-completeness"),d=new Set;for(let h of f){if(!h.file){c.push(h);continue}let g=h.file,y=(0,Q.join)(n,g);try{let v=await fe(y),S={path:g,title:v.frontmatter.title||Pf(g),summary:"",category:gv(g),tags:v.frontmatter.tags||[]};i||await oi(o,S),d.add(g),a.push(h)}catch{c.push(h)}}let p=u.filter(h=>h.category==="frontmatter-validation"),m=new Map;for(let h of p){if(!h.file){c.push(h);continue}m.has(h.file)||m.set(h.file,[]),m.get(h.file).push(h)}for(let[h,g]of m){let y=(0,Q.join)(n,h);try{let v=await fe(y),S=!1,k=[],$=[];for(let b of g){let T=b.message;T.includes('Missing required "type"')?(v.frontmatter.type="entity",S=!0,k.push(b)):T.includes('Missing required "title"')?(v.frontmatter.title=Pf(h),S=!0,k.push(b)):T.includes('Missing recommended "tags"')?(v.frontmatter.tags=[],S=!0,k.push(b)):T.includes('Missing recommended "created"')?(v.frontmatter.created=new Date().toISOString().split("T")[0],S=!0,k.push(b)):(T.includes("Invalid type"),$.push(b))}S&&!i&&await tt(y,v),a.push(...k),c.push(...$)}catch{c.push(...g)}}if(t.fixOrphans){let h=u.filter(g=>g.category==="orphan-pages");for(let g of h){if(!g.file){c.push(g);continue}let y=g.file;if(d.has(y)){a.push(g);continue}let v=(0,Q.join)(n,y);try{let S=await fe(v),k={path:y,title:S.frontmatter.title||Pf(y),summary:"",category:gv(y),tags:S.frontmatter.tags||[]};i||await oi(o,k),d.add(y),a.push(g)}catch{c.push(g)}}}return{command:"lint-fix",api_version:"1",fixed:a,remaining:c,fixedCount:a.length}}var va=require("node:fs/promises"),Nn=require("node:path");async function jn(e){let t;try{t=await(0,va.readdir)(e,{recursive:!0})}catch(n){if(q(n))return[];throw n}let r=[];for(let n of t){let o=(0,Nn.join)(e,n);try{let i=await(0,va.stat)(o);i.isFile()&&r.push({name:(0,Nn.basename)(n),path:n.replace(/\\/g,"/"),size:i.size,modified:i.mtime.toISOString(),extension:(0,Nn.extname)(n)})}catch(i){if(!q(i))throw i}}return r}var Tf={type:"object",properties:{severity:{type:"string",enum:["error","warning","info"]},category:{type:"string"},message:{type:"string"},file:{type:"string"}},required:["severity","category","message"]},wv={type:"object",properties:{command:{type:"string"},api_version:{type:"string"},source_count:{type:"integer"},wiki_page_count:{type:"integer"},last_ingest_date:{type:["string","null"]},last_lint_date:{type:["string","null"]},orphan_page_count:{type:"integer"},index_coverage_pct:{type:"number"}},required:["source_count","wiki_page_count","last_ingest_date","last_lint_date","orphan_page_count","index_coverage_pct"]},xv={type:"object",properties:{command:{type:"string"},api_version:{type:"string"},findings:{type:"array",items:Tf},errorCount:{type:"integer"},warningCount:{type:"integer"},infoCount:{type:"integer"},categorySummary:{type:"object",additionalProperties:{type:"integer"}}},required:["findings","errorCount","warningCount","infoCount","categorySummary"]},vv={type:"object",properties:{command:{type:"string"},api_version:{type:"string"},query:{type:"string"},matches:{type:"integer"},results:{type:"array",items:{type:"object",properties:{title:{type:"string"},path:{type:"string"},score:{type:"number"},excerpt:{type:"string"}},required:["title","path","score","excerpt"]}},saved:{type:"string"}},required:["query","matches","results"]},bv={type:"object",properties:{command:{type:"string"},api_version:{type:"string"},dry_run:{type:"boolean"},removed_pages:{type:"array",items:{type:"string"}},fixed:{type:"array",items:Tf},remaining:{type:"array",items:Tf},fixedCount:{type:"integer"},remainingCount:{type:"integer"}},required:["dry_run","removed_pages","fixed","remaining","fixedCount","remainingCount"]};var qr={readOnlyHint:!0,openWorldHint:!1},Of=[{name:"wiki_status",title:"Wiki status",description:"Return wiki status including source count, page count, lint dates, orphan pages and index coverage.",inputSchema:{type:"object",properties:{},required:[],additionalProperties:!1},outputSchema:wv,annotations:qr},{name:"wiki_query",title:"Search wiki",description:"Search the wiki for pages matching a free-text query. Returns matched pages with relevance scores and excerpts. Start here when answering a question, then read the best matches with wiki_read_page.",inputSchema:{type:"object",properties:{query:{type:"string",description:"Free-text search query"}},required:["query"],additionalProperties:!1},outputSchema:vv,annotations:qr},{name:"wiki_lint",title:"Lint wiki",description:"Lint the wiki and return findings grouped by severity (error, warning, info) with optional category filter.",inputSchema:{type:"object",properties:{category:{type:"string",description:"Optional category to restrict linting to"}},required:[],additionalProperties:!1},outputSchema:xv,annotations:qr},{name:"wiki_list_pages",title:"List wiki pages",description:"List all wiki pages with their file paths and frontmatter metadata.",inputSchema:{type:"object",properties:{},required:[],additionalProperties:!1},annotations:qr},{name:"wiki_list_sources",title:"List raw sources",description:"List all raw source files with name, path, size, modified date and extension.",inputSchema:{type:"object",properties:{},required:[],additionalProperties:!1},annotations:qr},{name:"wiki_read_page",title:"Read wiki page",description:"Read a single wiki page by relative path. Returns frontmatter and body content.",inputSchema:{type:"object",properties:{path:{type:"string",description:'Relative path within the wiki/ directory (e.g. "topic.md")'}},required:["path"],additionalProperties:!1},annotations:qr},{name:"wiki_read_index",title:"Read wiki index",description:"Read the wiki index file and return parsed entries with path, title, summary, category and tags.",inputSchema:{type:"object",properties:{},required:[],additionalProperties:!1},annotations:qr}];function be(e,t){let r=e[t];if(typeof r!="string"||r.length===0)throw new Error(`'${t}' must be a non-empty string`);return r}function Ot(e,t){let r=e[t];if(r!=null){if(typeof r!="string")throw new Error(`'${t}' must be a string`);return r}}function We(e,t){let r=(0,Fr.resolve)(e).replace(/\\/g,"/"),n=(0,Fr.resolve)(e,t).replace(/\\/g,"/");if(!n.startsWith(r+"/")&&n!==r)throw new Error("Path traversal detected \u2014 path must stay within wiki directory");return n}async function Sv(e,t,r){let n=(0,Fr.join)(r,"wiki"),o=(0,Fr.join)(r,"raw"),i=(0,Fr.join)(r,"wiki","index.md");switch(e){case"wiki_status":return JSON.stringify(await ya(r));case"wiki_query":return JSON.stringify(await wa(be(t,"query"),r));case"wiki_lint":{let s=Ot(t,"category");return JSON.stringify(await Ef(r,s?[s]:void 0))}case"wiki_list_pages":{let s=await lt(n),a=await Promise.all(s.map(async c=>{try{let u=await fe(c);return{path:c,frontmatter:u.frontmatter}}catch(u){if(!q(u))throw u;return{path:c,frontmatter:{}}}}));return JSON.stringify(a)}case"wiki_list_sources":return JSON.stringify(await jn(o));case"wiki_read_page":{let s=be(t,"path"),a=We(n,s);return JSON.stringify(await fe(a))}case"wiki_read_index":return JSON.stringify(await _e(i));default:throw new Error(`Unknown tool: ${e}`)}}var Ge=require("node:path"),Nv=require("node:fs/promises");var zv=require("node:fs/promises"),Zr=require("node:path");var At=require("node:fs/promises"),Se=require("node:path");async function kv(e,t,r,n=!1){if(r)return $v(e,t,r,n);let o=(0,Se.join)((0,Se.resolve)(t),"wiki");return ie(o,()=>$v(e,t,r,n))}async function $v(e,t,r,n){let o=(0,Se.resolve)(t),i=(0,Se.join)(o,"wiki"),s=(0,Se.join)(i,"index.md"),a=(0,Se.join)(i,"log.md");if(!await ma(i))return{command:"ingest",api_version:"1",status:"error",pages_created:[],pages_updated:[],dry_run:r,error:'Wiki is not initialized. Run the "LLM Wiki: Initialize Wiki" command first.'};let c=(0,Se.resolve)(e),u=c.replace(/\\/g,"/"),l=(0,Se.dirname)(o).replace(/\\/g,"/");if(!u.startsWith(l+"/")&&u!==l)return{command:"ingest",api_version:"1",status:"error",pages_created:[],pages_updated:[],dry_run:r,error:`Source path escapes project root: ${e}`};try{await(0,At.access)(c,At.constants.R_OK)}catch(F){if(q(F)||pa(F))return{command:"ingest",api_version:"1",status:"error",pages_created:[],pages_updated:[],dry_run:r,error:`Source file not found: ${e}`};throw F}let f=await(0,At.readFile)(c,"utf-8"),d=await(0,At.stat)(c),p=(0,Se.basename)(c),m=(0,Se.extname)(c),g=`sources/${lr(p)}-summary.md`,y=(0,Se.join)(i,g),v=!1;try{await(0,At.access)(y,At.constants.F_OK),v=!0}catch(F){if(!q(F))throw F}if(v&&!n)return{command:"ingest",api_version:"1",status:"skipped",pages_created:[],pages_updated:[],dry_run:r,message:"Source already ingested. Read summary_page and build on it; re-ingest with force only if the user asks.",summary_page:g};let S=f.length>500?f.slice(0,500)+"\u2026":f,k=(0,Se.relative)(o,c).replace(/\\/g,"/"),$=new Date().toISOString().slice(0,10),b=[],T=[];return r?(b.push(g),T.push("index.md","log.md")):(await tt(y,{frontmatter:{type:"source",title:p,source_path:k,ingested:$,created:$,tags:[]},body:`# ${p} + +**Source:** ${k} +**Type:** ${m||"unknown"} +**Size:** ${d.size} bytes +**Ingested:** ${$} + +## Content Preview + +${S}`}),b.push(g),n&&v&&await Rn(s,g),await oi(s,{path:g,title:p,summary:`Source file (${m||"unknown"})`,category:"Sources",tags:[]}),T.push("index.md"),await Et(a,{verb:"ingested",subject:p,details:`Ingested source "${p}" \u2192 ${g}`}),T.push("log.md")),{command:"ingest",api_version:"1",status:"success",pages_created:b,pages_updated:T,dry_run:r}}var JC=new Set(["the","a","an","and","or","but","in","on","at","to","for","of","with","by","from","is","are","was","were","be","been","being","have","has","had","do","does","did","will","would","could","should","may","might","shall","can","this","that","these","those","it","its","not","no","as","if","then","than","so","such","when","where","how","what","which","who","whom","we","he","she","they","you","i","me","my","your","his","her","our","their","us","them","about","up","out","just","also","very","all","any","each","every","both","few","more","most","other","some","only","own","same"]);function WC(e){let t=(0,Zr.extname)(e).toLowerCase();return{".md":"markdown",".txt":"text",".pdf":"pdf",".html":"html",".htm":"html",".json":"json",".csv":"csv",".xml":"xml",".yaml":"yaml",".yml":"yaml",".rst":"restructuredtext",".tex":"latex",".doc":"word",".docx":"word",".rtf":"richtext"}[t]??"unknown"}function GC(e){let t=e.trim();return t.length===0?0:t.split(/\s+/).length}function YC(e,t=200){let r=e.slice(0,t*10).toLowerCase().replace(/[^a-z0-9\s]/g," ").split(/\s+/).filter(i=>i.length>2&&!JC.has(i)),n=new Set,o=[];for(let i of r)!n.has(i)&&o.length0?(r.push("Add crosslinks between the new page and related existing pages"),r.push("Update existing related pages with new information from this source")):r.push("Consider creating foundational concept pages to build wiki structure"),r.push("Update the wiki index if additional metadata is needed"),r)}async function Pv(e,t,r=!1,n=!1){let o="",i=0,s=WC(e),a=(0,Zr.resolve)(e),c=a.replace(/\\/g,"/"),u=(0,Zr.dirname)((0,Zr.resolve)(t)).replace(/\\/g,"/");if(!c.startsWith(u+"/")&&c!==u)throw new Error(`Source path escapes project root: ${e}`);if(!new Set(["pdf","word","richtext"]).has(s))try{o=await(0,zv.readFile)(a,"utf-8"),i=GC(o)}catch(m){if(!q(m)&&!pa(m))throw m}let f=await kv(e,t,r,n),d=[];if(f.status!=="error"&&o.length>0)try{let m=YC(o);if(m.length>0){let h=m.slice(0,20).join(" ");d=(await wa(h,t,!1)).results.map(v=>({path:v.path,title:v.title,score:v.score,excerpt:v.excerpt}));let y=new Set([...f.pages_created,...f.pages_updated]);d=d.filter(v=>!y.has(v.path))}}catch(m){if(!q(m))throw m}let p=XC(f,d);return{ingest:f,source_word_count:i,source_content_type:s,related_pages:d,suggested_actions:p}}var ba=require("node:fs/promises"),Ht=require("node:path");async function QC(e){let t;try{t=await(0,ba.readdir)(e,{recursive:!0})}catch(r){if(q(r))return[];throw r}return t.map(r=>String(r).replace(/\\/g,"/")).filter(r=>(0,Ht.extname)(r)===".md"&&r!=="index.md"&&r!=="log.md").sort()}async function eN(e,t){try{return(await fe((0,Ht.join)(e,t))).frontmatter.sources}catch{return}}function Af(e){if(typeof e!="string")return;let t=e.trim().replace(/\\/g,"/").replace(/^(\.\/)+/,"");if(/^sources\/.+\.md$/i.test(t)&&!t.split("/").some(r=>r===""||r==="."||r===".."))return t}async function tN(e,t){return!Array.isArray(t)||t.length===0?!1:(await Promise.all(t.map(async n=>{let o=Af(n);if(!o)return!1;try{return await(0,ba.stat)((0,Ht.join)(e,o)),!1}catch(i){return q(i)}}))).every(Boolean)}async function rN(e){let t=[];for(let r of await QC(e))!r.startsWith("entities/")&&!r.startsWith("concepts/")||await tN(e,await eN(e,r))&&t.push(r);return t}async function Ev(e,t={}){let r=(0,Ht.resolve)(e),n=(0,Ht.join)(r,"wiki"),o=t.dryRun===!0,i=async()=>{let s=[];for(let u of await rN(n)){if(o){s.push(u);continue}try{await ga(n,u),s.push(u)}catch{}}let{fixed:a,remaining:c}=await _v(r,{fixOrphans:!0,dryRun:o,assumeDeleted:s});return!o&&(s.length>0||a.length>0)&&await Et((0,Ht.join)(n,"log.md"),{verb:"lint-fix",subject:"wiki",details:`Removed ${s.length} orphaned page(s), fixed ${a.length} issue(s), ${c.length} remaining.`}),{command:"fix",api_version:"1",dry_run:o,removed_pages:s,fixed:a,remaining:c,fixedCount:a.length,remainingCount:c.length}};return o?i():ie(n,i)}var si={readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!1},Sa={...si,idempotentHint:!0},Tv={type:"array",items:{type:"string"},description:'Optional wiki-relative paths of the source summary pages this page is derived from (e.g. ["sources/article-summary.md"]). If all of them are later removed, wiki_fix deletes this page.'},Rf=[{name:"wiki_write_page",title:"Write wiki page",description:"Create or overwrite a wiki page with frontmatter and body content. Automatically updates the index.",inputSchema:{type:"object",properties:{pagePath:{type:"string",description:'Relative path within the wiki/ directory (e.g. "concepts/ai.md")'},title:{type:"string",description:"Page title (required)"},type:{type:"string",description:'Page type, e.g. "entity", "concept", "source" (required)'},tags:{type:"array",items:{type:"string"},description:"Optional list of tags"},body:{type:"string",description:"Markdown body content"}},required:["pagePath","title","type","body"],additionalProperties:!1},annotations:Sa},{name:"wiki_create_entity",title:"Create entity page",description:"Create a new wiki entity page at wiki/entities/{slug}.md with proper frontmatter and auto-register it in the index. Overwrites an existing page with the same slug, so check for one first.",inputSchema:{type:"object",properties:{name:{type:"string",description:"Entity name (used as title and slugified for filename)"},content:{type:"string",description:"Markdown body content for the entity page"},tags:{type:"array",items:{type:"string"},description:"Optional list of tags"},sources:Tv},required:["name","content"],additionalProperties:!1},annotations:si},{name:"wiki_create_concept",title:"Create concept page",description:"Create a new wiki concept page at wiki/concepts/{slug}.md with proper frontmatter and auto-register it in the index. Overwrites an existing page with the same slug, so check for one first.",inputSchema:{type:"object",properties:{name:{type:"string",description:"Concept name (used as title and slugified for filename)"},content:{type:"string",description:"Markdown body content for the concept page"},tags:{type:"array",items:{type:"string"},description:"Optional list of tags"},sources:Tv},required:["name","content"],additionalProperties:!1},annotations:si},{name:"wiki_update_page",title:"Update wiki page",description:"Update an existing wiki page by merging partial frontmatter changes and/or appending or replacing body content. Updates the index if metadata changed.",inputSchema:{type:"object",properties:{pagePath:{type:"string",description:'Relative path within the wiki/ directory (e.g. "concepts/ai.md")'},title:{type:"string",description:"New title (optional, keeps existing if omitted)"},type:{type:"string",description:"New type (optional, keeps existing if omitted)"},tags:{type:"array",items:{type:"string"},description:"New tags list (optional, keeps existing if omitted)"},bodyAppend:{type:"string",description:"Content to append to the existing body"},bodyReplace:{type:"string",description:"Content to replace the entire body with"},addSources:{type:"array",items:{type:"string"},description:`Summary pages of other sources whose content you are adding (e.g. ["sources/second-article-summary.md"]). Appended to the page's existing "sources" so it is only deleted once all of its sources are removed. Ignored for pages that list no sources.`}},required:["pagePath"],additionalProperties:!1},annotations:si},{name:"wiki_add_crosslinks",title:"Add crosslinks",description:'Add cross-reference links ("See also" section) from one wiki page to one or more target pages. Validates all target pages exist.',inputSchema:{type:"object",properties:{pagePath:{type:"string",description:'Relative path of the source page within wiki/ (e.g. "concepts/ai.md")'},targetPages:{type:"array",items:{type:"string"},description:'Array of relative paths to link to (e.g. ["entities/openai.md"])'}},required:["pagePath","targetPages"],additionalProperties:!1},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},{name:"wiki_update_index",title:"Update index entry",description:"Update metadata (summary, tags, category) for an existing entry in the wiki index. Returns success/failure.",inputSchema:{type:"object",properties:{pagePath:{type:"string",description:'Path of the index entry to update (e.g. "concepts/ai.md")'},summary:{type:"string",description:"New summary text (optional)"},tags:{type:"array",items:{type:"string"},description:"New tags list (optional)"},category:{type:"string",description:"New category (optional)"}},required:["pagePath"],additionalProperties:!1},annotations:Sa},{name:"wiki_ingest_with_context",title:"Ingest source with context",description:"Ingest a source file into the wiki and return enhanced context including related pages, word count, content type, and suggested next actions. Use this instead of plain ingest when you want to understand how the source relates to existing wiki content.",inputSchema:{type:"object",properties:{sourcePath:{type:"string",description:'Path to the source file inside the wiki root, relative to the wiki root (e.g. "raw/article.md") or absolute'},dryRun:{type:"boolean",description:"If true, simulate ingest without writing files"},force:{type:"boolean",description:"If true, re-ingest even if source was already ingested"}},required:["sourcePath"],additionalProperties:!1},annotations:si},{name:"wiki_fix",title:"Fix wiki issues",description:"Apply every deterministic wiki fix: delete entity/concept pages whose raw sources were removed, drop stale index entries, index unlisted pages, and add missing frontmatter defaults. Returns the fixes and the findings that still need judgment (for example broken links). Call with dryRun first to preview; if the preview lists removed_pages, apply only after the user approves deleting them.",inputSchema:{type:"object",properties:{dryRun:{type:"boolean",description:"If true, report what would change without writing anything"}},required:[],additionalProperties:!1},outputSchema:bv,annotations:Sa},{name:"wiki_delete_page",title:"Delete wiki page",description:"Delete a wiki page and remove it from the index. Returns the pages that still link to it so you can fix those links. Only use after the user confirms the deletion.",inputSchema:{type:"object",properties:{pagePath:{type:"string",description:'Relative path within the wiki/ directory (e.g. "concepts/ai.md")'}},required:["pagePath"],additionalProperties:!1},annotations:Sa}],Dn=1e6,$a=500,ka=50,Ov=100,Av=100,Lr=500;function Oe(e,t,r){if(e.length>r)throw new Error(`'${t}' exceeds maximum length of ${r} characters`)}function ii(e){if(e){if(e.length>ka)throw new Error(`Too many tags (max ${ka})`);for(let t of e)if(t.length>Ov)throw new Error(`Tag exceeds maximum length of ${Ov} characters`)}}function Ur(e,t){let r=e[t];if(r!=null){if(!Array.isArray(r)||!r.every(n=>typeof n=="string"))throw new Error(`'${t}' must be an array of strings`);return r}}async function If(e,t,r="sources"){let n=Ur(e,r);if(!n||n.length===0)return;if(n.length>ka)throw new Error(`Too many ${r} (max ${ka})`);let o=[];for(let i of n){Oe(i,r,Lr);let s=Af((0,Ge.relative)(t,We(t,i)).replace(/\\/g,"/")),a=!1;if(s)try{a=(await(0,Nv.stat)((0,Ge.join)(t,s))).isFile()}catch{a=!1}if(!s||!a)throw new Error(`Source page not found: "${i}". Sources must be existing summary pages under sources/, such as the summary_page or pages_created path returned by wiki_ingest_with_context (e.g. "sources/article-summary.md").`);o.includes(s)||o.push(s)}return o}async function Iv(e,t,r){let n=(0,Ge.join)(e,t);await ie(e,async()=>{let o=await fe(n);o.frontmatter.sources=r,await tt(n,o)})}function Rv(e){let t=e.replace(/\\/g,"/").split("/");if(t.length>1){let r=t[0];return r.charAt(0).toUpperCase()+r.slice(1)}return"General"}async function Cv(e,t){await ie((0,Ge.dirname)(e),async()=>{let r=await _e(e),n=r.findIndex(o=>o.path===t.path);n>=0?r[n]=t:r.push(t),await Mr(e,r)})}async function jv(e,t,r){let n=(0,Ge.join)(r,"wiki"),o=(0,Ge.join)(r,"wiki","index.md");switch(e){case"wiki_write_page":{let i=be(t,"pagePath"),s=be(t,"title"),a=be(t,"type"),c=Ur(t,"tags")??[],u=be(t,"body");Oe(i,"pagePath",Lr),Oe(s,"title",$a),Oe(u,"body",Dn),ii(c);let l=We(n,i);return await ie(n,async()=>{await tt(l,{frontmatter:{type:a,title:s,tags:c},body:u}),await Cv(o,{path:i,title:s,summary:"",category:Rv(i),tags:c})}),JSON.stringify({status:"created",path:i,title:s,type:a,tags:c})}case"wiki_create_entity":{let i=be(t,"name"),s=be(t,"content"),a=Ur(t,"tags")??[];Oe(i,"name",$a),Oe(s,"content",Dn),ii(a);let c=await If(t,n),u=lr(i);if(u.length===0)throw new Error("'name' must contain at least one alphanumeric character");We(n,`entities/${u}.md`);let l=await ie(n,async()=>{let f=await uv(n,i,s,a);return c&&await Iv(n,f.path,c),f});return JSON.stringify({status:"created",path:l.path,title:i,type:"entity",tags:a,sources:c})}case"wiki_create_concept":{let i=be(t,"name"),s=be(t,"content"),a=Ur(t,"tags")??[];Oe(i,"name",$a),Oe(s,"content",Dn),ii(a);let c=await If(t,n),u=lr(i);if(u.length===0)throw new Error("'name' must contain at least one alphanumeric character");We(n,`concepts/${u}.md`);let l=await ie(n,async()=>{let f=await lv(n,i,s,a);return c&&await Iv(n,f.path,c),f});return JSON.stringify({status:"created",path:l.path,title:i,type:"concept",tags:a,sources:c})}case"wiki_update_page":{let i=be(t,"pagePath");Oe(i,"pagePath",Lr);let s=We(n,i);return ie(n,async()=>{let a;try{a=await fe(s)}catch(S){throw q(S)?new Error(`Page not found: ${i}`):S}let c=Ot(t,"title");if(c!==void 0&&c.length===0)throw new Error("'title' must be non-empty when provided");c!==void 0&&Oe(c,"title",$a);let u=Ot(t,"type"),l=Ur(t,"tags");ii(l);let f={...a.frontmatter};c!==void 0&&(f.title=c),u!==void 0&&(f.type=u),l!==void 0&&(f.tags=l);let d=await If(t,n,"addSources"),p=!1,m=a.frontmatter.sources;if(d&&Array.isArray(m)&&m.length>0){let S=[...m];for(let k of d)S.includes(k)||S.push(k);p=S.length!==m.length,f.sources=S}let h=Ot(t,"bodyAppend");h!==void 0&&Oe(h,"bodyAppend",Dn);let g=Ot(t,"bodyReplace");g!==void 0&&Oe(g,"bodyReplace",Dn);let y=a.body;g!==void 0?y=g:h!==void 0&&(y=a.body+` + +`+h),await tt(s,{frontmatter:f,body:y});let v=c!==void 0||u!==void 0||l!==void 0;return v&&await Cv(o,{path:i,title:f.title??"",summary:"",category:Rv(i),tags:f.tags??[]}),JSON.stringify({status:"updated",path:i,frontmatter:f,bodyUpdated:h!==void 0||g!==void 0,indexUpdated:v,sourcesUpdated:p})})}case"wiki_add_crosslinks":{let i=be(t,"pagePath");Oe(i,"pagePath",Lr);let s=Ur(t,"targetPages");if(!s||s.length===0)throw new Error("'targetPages' must be a non-empty array of strings");if(s.length>Av)throw new Error(`Too many target pages (max ${Av})`);We(n,i);for(let a of s)We(n,a);return await fv(n,i,s),JSON.stringify({status:"updated",path:i,crosslinks:s})}case"wiki_update_index":{let i=be(t,"pagePath");Oe(i,"pagePath",Lr);let s=Ot(t,"summary");s!==void 0&&Oe(s,"summary",Dn);let a=Ur(t,"tags");ii(a);let c=Ot(t,"category"),u={};s!==void 0&&(u.summary=s),a!==void 0&&(u.tags=a),c!==void 0&&(u.category=c);let l=await iv(o,i,u);return JSON.stringify({status:l?"updated":"not_found",path:i,fieldsUpdated:Object.keys(u)})}case"wiki_ingest_with_context":{let i=be(t,"sourcePath");Oe(i,"sourcePath",Lr);let s=We(r,i),a=t.dryRun===!0,c=t.force===!0,u=await Pv(s,r,a,c);return JSON.stringify(u)}case"wiki_fix":{let i=t.dryRun===!0;return JSON.stringify(await Ev(r,{dryRun:i}))}case"wiki_delete_page":{let i=be(t,"pagePath");Oe(i,"pagePath",Lr);let s=(0,Ge.relative)(n,We(n,i)).replace(/\\/g,"/");if(ha(s))throw new Error(`'${s}' is a special wiki file and cannot be deleted`);if((0,Ge.extname)(s)!==".md")throw new Error("'pagePath' must point to a markdown page (.md)");let c=(await ga(n,s)).backlinkWarnings.map(u=>({page:(0,Ge.relative)(n,u.sourcePage).replace(/\\/g,"/"),title:u.sourceTitle,linkText:u.linkText})).filter(u=>!ha(u.page));return await Et((0,Ge.join)(n,"log.md"),{verb:"deleted",subject:s,details:c.length>0?`Page deleted. Still linked from: ${c.map(u=>u.page).join(", ")}.`:"Page deleted."}),JSON.stringify({status:"deleted",path:s,linkedFrom:c})}default:throw new Error(`Unknown tool: ${e}`)}}var Pa=require("node:path");var Mv=require("node:fs"),ai=require("node:fs/promises"),pr=require("node:path");var Dv=["raw","wiki","wiki/entities","wiki/concepts","wiki/sources"],nN=`# Wiki Index + +## Entities + +## Concepts + +## Sources +`,oN=`# AGENTS.md + +## Wiki Schema + +### Page Types + +- **entity** \u2014 A person, place, organization, or thing +- **concept** \u2014 An idea, theory, or abstract topic +- **source** \u2014 A reference to raw material +- **summary** \u2014 An auto-generated summary of an ingested source +- **query** \u2014 A saved query result page + +### Directory Structure + +- \`raw/\` \u2014 Raw ingested documents +- \`wiki/\` \u2014 Processed wiki pages + - \`wiki/entities/\` \u2014 Entity pages + - \`wiki/concepts/\` \u2014 Concept pages + - \`wiki/sources/\` \u2014 Source reference pages + - \`wiki/index.md\` \u2014 Master index + - \`wiki/log.md\` \u2014 Change log + +### Frontmatter Schema + +**Required fields:** +- \`type\` \u2014 Page type (entity, concept, source, summary, query) +- \`title\` \u2014 Page title + +**Optional fields:** +- \`tags\` \u2014 Array of tag strings +- \`sources\` \u2014 Source summary pages this page was derived from, as wiki-relative paths (e.g. \`sources/article-summary.md\`). When all of them are removed, the page is cleaned up. Pages without \`sources\` are never removed automatically. +- \`created\` \u2014 Creation date (YYYY-MM-DD) +- \`updated\` \u2014 Last updated date (YYYY-MM-DD) +- \`source_path\` \u2014 Relative path to the original source file +- \`ingested\` \u2014 Date the source was ingested + +\`\`\`yaml +type: entity | concept | source | summary | query +title: string +tags: string[] +sources: string[] +created: YYYY-MM-DD +updated: YYYY-MM-DD +source_path: string # source/summary pages only +ingested: YYYY-MM-DD # source/summary pages only +query: string # query pages only \u2014 the original query string +results_count: number # query pages only \u2014 number of results +\`\`\` + +### Query Page Frontmatter + +Query pages use the following frontmatter: + +\`\`\`yaml +type: query +title: "" +tags: + - +created: YYYY-MM-DD +query: "" +results_count: +\`\`\` + +### Naming Conventions + +- Filenames are lowercased +- Extensions are stripped +- Non-alphanumeric characters become hyphens +- Leading/trailing hyphens are removed +- Example: \`My Report (2024).pdf\` \u2192 \`my-report-2024\` +- Summary pages: \`sources/{slug}-summary.md\` +- Entity pages: \`entities/{slug}.md\` +- Concept pages: \`concepts/{slug}.md\` + +### Ingest Workflow + +1. Place a raw file in the \`raw/\` directory (or run **LLM Wiki: Ingest Files or Folder** from the Command Palette). +2. The extension automatically ingests new sources and writes a summary page in \`wiki/sources/\`. +3. \`wiki/index.md\` is updated with the new entry. +4. \`wiki/log.md\` records the ingestion event. + +### Lint Rules + +- **broken-links** (error) \u2014 Links pointing to non-existent files +- **orphan-pages** (warning) \u2014 Pages with no inbound links and not in index +- **index-completeness** (warning) \u2014 Pages not listed in wiki/index.md +- **stale-entries** (error) \u2014 Index entries pointing to deleted files +- **missing-pages** (info) \u2014 Referenced pages that do not exist yet + +Run lint with **LLM Wiki: Run Lint** and apply the deterministic fixes with **LLM Wiki: Fix Issues**. In Copilot Chat, the \`/wiki-fix\` skill resolves the remaining findings. + +### Cross-Referencing Guidelines + +- Use standard Markdown links: \`[Title](relative/path.md)\` +- Links must be relative paths ending in \`.md\` +- External URLs (http/https) are ignored by lint +- Use relative paths from the current file location +- The lint command detects broken links and orphan pages +`;function za(e){try{return(0,Mv.statSync)((0,pr.join)(e,"wiki")).isDirectory()}catch{return!1}}async function qv(e){let t=(0,pr.resolve)(e,ut);if(za(t))return{command:"init",api_version:"1",status:"already_initialized",created_dirs:[],created_files:[],warning:"Wiki is already initialized (wiki/ directory exists)"};for(let s of Dv)await(0,ai.mkdir)((0,pr.join)(t,s),{recursive:!0});let r=(0,pr.join)(t,"wiki","index.md");await(0,ai.writeFile)(r,nN,"utf-8");let n=(0,pr.join)(t,"wiki","log.md");await Et(n,{verb:"initialized",subject:"wiki",details:"Wiki knowledge base initialized."});let o=(0,pr.join)(t,"AGENTS.md");await(0,ai.writeFile)(o,oN,"utf-8");let i=["wiki/index.md","wiki/log.md","AGENTS.md"];return{command:"init",api_version:"1",status:"created",created_dirs:[...Dv],created_files:i}}var Cf=[{name:"wiki_open",title:"Open wiki",description:`Select the LLM Wiki to work with. Pass the absolute path of the project folder that contains the ${ut} directory (usually the current working directory). Call this when another wiki tool reports that no wiki is open.`,inputSchema:{type:"object",properties:{path:{type:"string",description:`Absolute path of the project folder (or of its ${ut} directory)`}},required:["path"],additionalProperties:!1},annotations:{readOnlyHint:!0,openWorldHint:!1}},{name:"wiki_init",title:"Initialize wiki",description:`Create a new LLM Wiki (${ut}/ with raw/, wiki/, index.md, log.md and AGENTS.md) in a project folder and open it. Does nothing if the folder already has a wiki.`,inputSchema:{type:"object",properties:{path:{type:"string",description:"Absolute path of the project folder. Defaults to the first workspace folder reported by the client."}},required:[],additionalProperties:!1},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}}];function Fv(e){if(!(0,Pa.isAbsolute)(e))throw new Error(`'path' must be an absolute path (got "${e}")`);return e}async function Zv(e,t,r,n){switch(e){case"wiki_open":{let o=r.open(Fv(be(t,"path"))),i=await ya(o);return JSON.stringify({status:"opened",wiki_root:o,wiki_page_count:i.wiki_page_count,source_count:i.source_count})}case"wiki_init":{let o=Ot(t,"path"),i=o?Fv(o):(await r.workspaceFolders(n))[0];if(!i)throw new Error("Pass 'path': the absolute path of the project folder to create the wiki in (usually the current working directory).");let s=await qv(i),a=r.open((0,Pa.join)(i,ut));return JSON.stringify({...s,wiki_root:a})}default:throw new Error(`Unknown tool: ${e}`)}}var mr=require("node:path"),Lv=require("node:url");var Nf=class extends Error{constructor(){super(`No LLM Wiki is open. Call wiki_open with the absolute path of the project folder that contains the ${ut} directory (usually the current working directory), or wiki_init to create a new wiki there.`),this.name="NoWikiError"}};function Ea(e){let t=(0,mr.resolve)(e),r=(0,mr.join)(t,ut);if(za(r))return r;if((0,mr.basename)(t)===ut&&za(t))return t}var Ta=class{isFixed;root;source;cwd;constructor(t){if(this.isFixed=t.fixed!==void 0,this.cwd=t.cwd,t.fixed!==void 0)this.set((0,mr.resolve)(t.fixed),"config");else if(t.cwd){let r=Ea(t.cwd);r&&this.set(r,"cwd")}}get current(){return this.root}attach(t){t.setNotificationHandler(nu,async()=>{this.source==="roots"&&(this.root=void 0,this.source=void 0)})}async require(t){if(this.root)return this.root;for(let r of await this.workspaceFolders(t)){let n=Ea(r);if(n)return this.set(n,"roots")}if(this.cwd){let r=Ea(this.cwd);if(r)return this.set(r,"cwd")}throw new Nf}async workspaceFolders(t){if(!t.getClientCapabilities()?.roots)return[];try{let{roots:r}=await t.listRoots();return r.filter(n=>n.uri.startsWith("file:")).map(n=>(0,Lv.fileURLToPath)(n.uri))}catch{return[]}}open(t){let r=Ea(t);if(!r)throw new Error(`No LLM Wiki found at ${(0,mr.resolve)(t)} (expected a ${ut}/wiki/ folder). Use wiki_init to create one.`);if(this.isFixed&&r!==this.root)throw new Error(`This LLM Wiki server is bound to ${this.root} by its configuration.`);return this.set(r,"open")}set(t,r){return this.root=t,this.source=r,t}};var Vv=require("node:fs"),Hv=require("node:path"),Uv=12e3,iN=`LLM Wiki is a personal knowledge base that an LLM maintains as interlinked markdown. A wiki root (usually /.wiki) contains: +- raw/: immutable sources the user curates. Read them; never modify them. +- wiki/: pages you maintain. entities/ (people, organizations, things), concepts/ (ideas, techniques), sources/ (one summary per raw source), plus wiki/index.md (the catalog) and wiki/log.md (append-only history). +- AGENTS.md: the wiki's schema and conventions. Follow it. + +Answering questions: +1. Find candidate pages with wiki_query (or scan wiki_read_index), then read the most relevant ones with wiki_read_page. +2. Answer from the wiki content and cite the pages you used by title and path. Point out connections between pages. +3. If the wiki does not cover the question, say so and suggest sources the user could add. +4. When an answer is a valuable synthesis, offer to save it as a page with wiki_write_page (type "query", path "queries/.md"). + +Maintaining the wiki: +- Prefer wiki_create_entity, wiki_create_concept, wiki_update_page and wiki_add_crosslinks over editing files directly; they keep index.md consistent. +- To ingest a source, make sure the file is under raw/, then call wiki_ingest_with_context with sourcePath "raw/". +- For health checks call wiki_lint. wiki_fix applies the deterministic fixes: preview with dryRun first, and if the preview lists removed_pages, apply only after the user approves deleting them. Resolve the remaining findings by editing pages. +- Delete pages with wiki_delete_page only after the user confirms.`,sN="Locating the wiki: if a tool reports that no wiki is open, call wiki_open with the absolute path of the user's project folder (usually the current working directory). Use wiki_init only when the user wants a new wiki.";function Bv(e,t={}){let r=[iN];if(t.discovery&&r.push(sN),e){let n="";try{n=(0,Vv.readFileSync)((0,Hv.join)(e,"AGENTS.md"),"utf-8").trim()}catch{}n.length>Uv&&(n=`${n.slice(0,Uv)} + +[Truncated. Read .wiki/AGENTS.md for the full schema.]`),n&&r.push(`This wiki's schema (.wiki/AGENTS.md): + +${n}`)}return r.join(` + +`)}var Mn=require("node:path"),Kv=require("node:fs/promises");function Jv(e,t){let r=typeof t=="string"?async()=>t:t;e.setRequestHandler(Lc,async()=>({resources:[{uri:"resource://wiki/index",name:"Wiki Index",description:"Complete wiki index as JSON with all entries, titles, summaries, categories, and tags",mimeType:"application/json"},{uri:"resource://wiki/pages",name:"Wiki Pages",description:"List of all wiki pages with their relative paths and frontmatter metadata",mimeType:"application/json"},{uri:"resource://wiki/sources",name:"Wiki Sources",description:"List of all raw source files with name, path, size, modified date, and extension",mimeType:"application/json"}]})),e.setRequestHandler(Uc,async()=>({resourceTemplates:[{uriTemplate:"resource://wiki/pages/{path}",name:"Wiki Page",description:"Read a single wiki page by relative path. Returns frontmatter and body content as JSON.",mimeType:"application/json"},{uriTemplate:"resource://wiki/sources/{path}",name:"Source File",description:"Read a raw source file by relative path. Returns the file content as plain text.",mimeType:"text/plain"}]})),e.setRequestHandler(Hc,async n=>{let{uri:o}=n.params,i=await r(),s=(0,Mn.join)(i,"wiki"),a=(0,Mn.join)(i,"raw"),c=(0,Mn.join)(s,"index.md");if(o==="resource://wiki/index"){let f=await _e(c);return{contents:[{uri:o,mimeType:"application/json",text:JSON.stringify(f,null,2)}]}}if(o==="resource://wiki/pages"){let f=await lt(s),d=await Promise.all(f.map(async p=>{let m=(0,Mn.relative)(s,p).replace(/\\/g,"/");try{let h=await fe(p);return{path:m,frontmatter:h.frontmatter}}catch(h){if(!q(h))throw h;return{path:m,frontmatter:{}}}}));return{contents:[{uri:o,mimeType:"application/json",text:JSON.stringify(d,null,2)}]}}if(o==="resource://wiki/sources"){let f=await jn(a);return{contents:[{uri:o,mimeType:"application/json",text:JSON.stringify(f,null,2)}]}}let u=o.match(/^resource:\/\/wiki\/pages\/(.+)$/);if(u){let f=decodeURIComponent(u[1]),d=We(s,f),p=await fe(d);return{contents:[{uri:o,mimeType:"application/json",text:JSON.stringify(p,null,2)}]}}let l=o.match(/^resource:\/\/wiki\/sources\/(.+)$/);if(l){let f=decodeURIComponent(l[1]),d=We(a,f),p=await(0,Kv.readFile)(d,"utf-8");return{contents:[{uri:o,mimeType:"text/plain",text:p}]}}throw new Error(`Unknown resource: ${o}`)})}var aN=[{name:"ingest-and-integrate",description:"Ingest a source file and integrate its knowledge into the wiki \u2014 create entities, concepts, crosslinks, and verify health.",arguments:[{name:"source_path",description:"Path to source file in the raw/ directory",required:!0}]},{name:"lint-and-fix",description:"Run wiki lint, review findings by severity, fix deterministic issues, and report remaining problems that need human judgment."},{name:"research-topic",description:"Research a topic across the wiki \u2014 query, read related pages, synthesize findings, and identify knowledge gaps.",arguments:[{name:"topic",description:"The topic to research across the wiki",required:!0}]}];function cN(e){return{description:`Ingest ${e} and integrate its knowledge into the wiki.`,messages:[{role:"user",content:{type:"text",text:[`Ingest the source file "${e}" and fully integrate its knowledge into the wiki. Follow these steps:`,"","1. **Ingest with context**: Call wiki_ingest_with_context with sourcePath set to",` "${e}". Review the returned related_pages and suggested_actions.`,"","2. **Create entity pages**: For each person, organization, or named thing mentioned"," in the source, call wiki_create_entity with a descriptive title, summary, and"," relevant tags. Skip entities that already exist in related_pages.","","3. **Create concept pages**: For each idea, technique, or mechanism described in"," the source, call wiki_create_concept with a clear title, summary, and tags."," Skip concepts that already exist.","","4. **Add crosslinks**: Call wiki_add_crosslinks for each new page to connect it"," to related existing pages. Also update existing pages to link back to new ones.","","5. **Verify wiki health**: Call wiki_lint and review the findings. Fix any errors"," introduced during this workflow (missing index entries, broken links).","","Report a summary of what was created, linked, and any remaining lint findings."].join(` +`)}}]}}function uN(){return{description:"Run wiki lint, fix deterministic issues, and report remaining findings.",messages:[{role:"user",content:{type:"text",text:["Audit the wiki for quality issues and fix what you can. Follow these steps:","","1. **Run lint**: Call wiki_lint to get all findings. Note the total count and"," severity breakdown (error, warning, info).","","2. **Preview deterministic fixes**: Call wiki_fix with dryRun set to true. It lists"," stale index entries to drop, unlisted pages to index, missing frontmatter"," defaults to add, and entity/concept pages whose raw sources were removed.","","3. **Confirm deletions**: If removed_pages is not empty, list those pages and ask"," the user whether to delete them. Wait for an explicit yes. If the user declines"," or does not answer, skip step 4: do not call wiki_fix without dryRun, because"," it would delete those pages.","","4. **Apply them**: Call wiki_fix (without dryRun) and note what it fixed.","","5. **Report remaining**: List the findings that still require human judgment:"," - Broken crosslinks (link target does not exist)"," - Invalid page types"," - Contradictory information across pages","","Summarize: how many issues found, how many fixed, how many remain."].join(` +`)}}]}}function lN(e){return{description:`Research "${e}" across the wiki and synthesize findings.`,messages:[{role:"user",content:{type:"text",text:[`Research the topic "${e}" across the wiki. Follow these steps:`,"","1. **Query the wiki**: Call wiki_query with the topic to find relevant pages."," Note the number of results and their relevance.","","2. **Read key pages**: For each highly relevant result, call wiki_read_page to"," read the full content. Focus on the top 5-10 most relevant pages.","","3. **Synthesize findings**: Combine information across pages into a coherent"," summary. Note where pages agree, where they add complementary detail, and"," where they might contradict each other.","","4. **Identify knowledge gaps**: Based on your synthesis, identify:"," - Sub-topics that are mentioned but have no dedicated page"," - Related topics that the wiki doesn't cover yet"," - Pages that could be enriched with more detail","",`Report your synthesis of "${e}" and a prioritized list of suggested`,"wiki improvements (new pages to create, existing pages to enrich)."].join(` +`)}}]}}function Wv(e,t){e.setRequestHandler(Bc,async()=>({prompts:aN.map(r=>({name:r.name,description:r.description,arguments:"arguments"in r?[...r.arguments]:void 0}))})),e.setRequestHandler(Kc,async r=>{let{name:n,arguments:o}=r.params;switch(n){case"ingest-and-integrate":{let i=o?.source_path;if(!i)throw new Error("Missing required argument: source_path");return cN(i)}case"lint-and-fix":return uN();case"research-topic":{let i=o?.topic;if(!i)throw new Error("Missing required argument: topic");return lN(i)}default:throw new Error(`Unknown prompt: ${n}`)}})}var qn=require("node:path");var Gv=100;async function fN(e){let t=(0,qn.join)(e,"wiki");return(await lt(t)).map(r=>(0,qn.relative)(t,r).replace(/\\/g,"/")).filter(r=>r!=="index.md"&&r!=="log.md").sort()}async function Yv(e){return(await jn((0,qn.join)(e,"raw"))).map(t=>t.path).sort()}function Xv(e,t){e.setRequestHandler(tu,async r=>{let{ref:n,argument:o}=r.params,i=[];try{if(n.type==="ref/resource"&&o.name==="path")n.uri==="resource://wiki/pages/{path}"?i=await fN(await t()):n.uri==="resource://wiki/sources/{path}"&&(i=await Yv(await t()));else if(n.type==="ref/prompt"){if(n.name==="ingest-and-integrate"&&o.name==="source_path")i=(await Yv(await t())).map(c=>`raw/${c}`);else if(n.name==="research-topic"&&o.name==="topic"){let c=await _e((0,qn.join)(await t(),"wiki","index.md"));i=[...new Set(c.map(u=>u.title))].sort()}}}catch{i=[]}let s=(o.value??"").toLowerCase(),a=i.filter(c=>c.toLowerCase().includes(s));return{completion:{values:a.slice(0,Gv),total:a.length,hasMore:a.length>Gv}}})}var dN=new Set(Of.map(e=>e.name)),pN=new Set(Rf.map(e=>e.name)),mN=new Set(Cf.map(e=>e.name)),hN='',gN=`data:image/svg+xml;base64,${Buffer.from(hN).toString("base64")}`;function Qv(e={}){let t=typeof e=="string"?{wikiRoot:e}:e,r=t.wikiRoot===void 0,n=new Ta(r?{cwd:t.cwd??process.cwd()}:{fixed:t.wikiRoot}),o=[...Of,...Rf,...r?Cf:[]],i=new Map(o.map(c=>[c.name,c])),s=new ta({name:"llmwiki",title:"LLM Wiki",version:A0,websiteUrl:"https://github.com/microsoft/llmwiki",icons:[{src:gN,mimeType:"image/svg+xml",sizes:["any"]}]},{capabilities:{tools:{},resources:{},prompts:{},completions:{}},instructions:Bv(n.current,{discovery:r})});n.attach(s);let a=()=>n.require(s);return s.setRequestHandler(Xc,async()=>({tools:o})),s.setRequestHandler(ho,async c=>{let{name:u,arguments:l}=c.params,f=l??{};try{let d=i.get(u);if(!d)throw new Error(`Unknown tool: ${u}`);let p;if(mN.has(u))p=await Zv(u,f,n,s);else if(dN.has(u))p=await Sv(u,f,await a());else if(pN.has(u))p=await jv(u,f,await a());else throw new Error(`Unknown tool: ${u}`);return d.outputSchema?{content:[{type:"text",text:p}],structuredContent:JSON.parse(p)}:{content:[{type:"text",text:p}]}}catch(d){return{content:[{type:"text",text:`Error: ${d instanceof Error?d.message:String(d)}`}],isError:!0}}}),Jv(s,a),Wv(s),Xv(s,a),s}async function yN(){let e=process.argv[2],t=e&&e.length>0?e:process.env.LLMWIKI_ROOT,r;if(t&&t.length>0){r=(0,eb.resolve)(t);try{(await(0,tb.stat)(r)).isDirectory()||(process.stderr.write(`llmwiki-mcp: ${r} exists but is not a directory. +`),process.exit(1))}catch{process.stderr.write(`llmwiki-mcp: wiki root not found at ${r}. +Initialize one first (e.g. via "LLM Wiki: Initialize Wiki" in VS Code) or pass the path explicitly: + llmwiki-mcp +`),process.exit(1)}}let n=Qv(r?{wikiRoot:r}:{cwd:process.cwd()}),o=new ls;await n.connect(o)}yN().catch(e=>{let t=e instanceof Error?e.message:String(e);process.stderr.write(`llmwiki-mcp: fatal error \u2014 ${t} +`),process.exit(1)}); +/*! Bundled license information: + +is-extendable/index.js: + (*! + * is-extendable + * + * Copyright (c) 2015, Jon Schlinkert. + * Licensed under the MIT License. + *) + +strip-bom-string/index.js: + (*! + * strip-bom-string + * + * Copyright (c) 2015, 2017, Jon Schlinkert. + * Released under the MIT License. + *) +*/ diff --git a/plugin/skills/wiki-ask/SKILL.md b/plugin/skills/wiki-ask/SKILL.md new file mode 100644 index 0000000..e87f7e2 --- /dev/null +++ b/plugin/skills/wiki-ask/SKILL.md @@ -0,0 +1,17 @@ +--- +name: wiki-ask +description: Answer a question from the user's LLM Wiki knowledge base (.wiki/) by searching and reading wiki pages with the LLM Wiki MCP tools, and cite the pages used. Use when the user asks about people, ideas, sources or topics collected in their wiki, or asks to "ask the wiki". +argument-hint: "[question]" +--- + +# Ask the wiki + +Answer the user's question from their LLM Wiki, not from general knowledge. + +1. Search with `wiki_query` using the key terms of the question. If nothing relevant comes back, try synonyms, or scan the catalog with `wiki_read_index`. +2. Read the most relevant pages (usually 3–8) with `wiki_read_page`. Follow links to closely related pages when they add needed context. +3. Answer from what the pages say. Cite every page you rely on as a link to its file, for example `[Attention](.wiki/wiki/concepts/attention.md)`. Point out connections and contradictions between pages. +4. If the wiki doesn't answer the question, say so plainly and suggest sources the user could add to `.wiki/raw/`. +5. If the answer is a useful synthesis, offer to save it to the wiki with the `wiki-save` skill. + +If a tool reports that no wiki is open, call `wiki_open` with the absolute path of the current workspace folder, then retry. diff --git a/plugin/skills/wiki-fix/SKILL.md b/plugin/skills/wiki-fix/SKILL.md new file mode 100644 index 0000000..860118a --- /dev/null +++ b/plugin/skills/wiki-fix/SKILL.md @@ -0,0 +1,19 @@ +--- +name: wiki-fix +description: Find and fix problems in the user's LLM Wiki — stale index entries, unindexed pages, missing frontmatter, broken links, orphaned pages — with the LLM Wiki MCP tools, asking before anything is deleted. +disable-model-invocation: true +--- + +# Fix wiki issues + +1. **Preview.** Call `wiki_fix` with `dryRun: true` and summarize what it would change. +2. **Confirm deletions.** If `removed_pages` is not empty, list those pages (entity/concept pages whose raw sources were all removed) and ask the user whether to delete them. Wait for an explicit yes. If the user declines or doesn't answer, don't call `wiki_fix` without `dryRun`, because it would delete them. Run `wiki_lint` instead, and continue with step 4 using its findings. +3. **Apply.** Call `wiki_fix` without `dryRun`, only if the preview listed no pages to delete or the user approved deleting them. +4. **Resolve what remains.** Work through the findings that still need judgment: + - `broken-links` / `missing-pages`: read the page with `wiki_read_page`, find the intended target with `wiki_query`, then fix the link with `wiki_update_page` (`bodyReplace` with the corrected body), or remove the link. Create a missing page only if the user wants it. + - `frontmatter-validation` (invalid type): set a valid type (entity, concept, source, summary or query) with `wiki_update_page`. + - `orphan-pages`: link the page from related pages with `wiki_add_crosslinks`. +5. **Never delete without confirmation.** Use `wiki_delete_page` only after the user explicitly agrees, then fix the links it reports in `linkedFrom`. +6. **Verify.** Run `wiki_lint` and report what was fixed and what still needs the user's decision. + +If a tool reports that no wiki is open, call `wiki_open` with the absolute path of the current workspace folder, then retry. diff --git a/plugin/skills/wiki-ingest/SKILL.md b/plugin/skills/wiki-ingest/SKILL.md new file mode 100644 index 0000000..f5a9ee8 --- /dev/null +++ b/plugin/skills/wiki-ingest/SKILL.md @@ -0,0 +1,20 @@ +--- +name: wiki-ingest +description: Ingest a source document (article, paper, notes, transcript) into the user's LLM Wiki and integrate it — summary page, entity and concept pages, crosslinks and a health check — with the LLM Wiki MCP tools. Use when the user wants to add, file, import or ingest a source into their wiki. +argument-hint: "[file path]" +--- + +# Ingest a source into the wiki + +1. **Place the source.** Sources live in `.wiki/raw/` and are never modified there. If the user points at a file elsewhere, copy it into `.wiki/raw/` (keep the original where it is). In VS Code with the LLM Wiki extension, a file that appears in `.wiki/raw/` is also ingested by the extension automatically. +2. **Ingest.** Call `wiki_ingest_with_context` with `sourcePath` set to `raw/`. It writes a summary page under `sources/` and returns `related_pages` and `suggested_actions`. + - If it reports `skipped` because the source was already ingested (for example by the VS Code extension), don't force it. Read the existing summary page it returns as `summary_page`, check which entity and concept pages already exist, and only add what is missing in the steps below. + - Re-ingesting with `force: true` overwrites the summary page; do it only if the user asks. +3. **Improve the summary.** Read the source and the summary page. If the summary is a thin stub, rewrite it with `wiki_update_page` (`bodyReplace`): key points, notable claims and numbers, open questions. +4. **Extract entities and concepts.** For each important person, organization or named thing, use `wiki_create_entity`; for each idea, technique or mechanism, use `wiki_create_concept`. Pass `sources` with the summary page path (for example `["sources/article-summary.md"]`) so the page is cleaned up if the source is removed later. + - First check `related_pages` and `wiki_query`: if a page already exists, extend it with `wiki_update_page` (`bodyAppend`) and pass `addSources` with the summary page path instead. The create tools overwrite a page with the same name. +5. **Connect.** Use `wiki_add_crosslinks` to link the new pages to related existing pages, and the existing pages back to the new ones. +6. **Check health.** Run `wiki_lint` and fix anything this ingest introduced (for example broken links). +7. **Report** what was created, updated and linked. + +If a tool reports that no wiki is open, call `wiki_open` with the absolute path of the current workspace folder, then retry. diff --git a/plugin/skills/wiki-research/SKILL.md b/plugin/skills/wiki-research/SKILL.md new file mode 100644 index 0000000..726cf43 --- /dev/null +++ b/plugin/skills/wiki-research/SKILL.md @@ -0,0 +1,22 @@ +--- +name: wiki-research +description: Research a topic across the user's LLM Wiki — gather every relevant page, synthesize what the wiki knows, flag contradictions, and list knowledge gaps with suggested new pages. Use when the user wants an overview, literature-style synthesis or gap analysis of a topic in their wiki. +argument-hint: "[topic]" +--- + +# Research a topic in the wiki + +1. Search with `wiki_query` for the topic and for its main sub-topics and synonyms. Use `wiki_read_index` to spot pages whose titles or summaries match. +2. Read the 5–10 most relevant pages with `wiki_read_page`, plus pages they link to that are clearly on topic. +3. Write a synthesis: + - what the wiki says about the topic, organized by theme rather than by page; + - where pages agree, add complementary detail, or contradict each other; + - a link to each page you used, for example `[Transformers](.wiki/wiki/concepts/transformers.md)`. +4. List knowledge gaps, most important first: + - sub-topics that are mentioned but have no page; + - related topics the wiki doesn't cover yet; + - pages that are thin and should be enriched; + - sources the user could add to `.wiki/raw/` to close the gaps. +5. Offer to save the synthesis with the `wiki-save` skill, or to create the missing pages. + +If a tool reports that no wiki is open, call `wiki_open` with the absolute path of the current workspace folder, then retry. diff --git a/plugin/skills/wiki-save/SKILL.md b/plugin/skills/wiki-save/SKILL.md new file mode 100644 index 0000000..1077550 --- /dev/null +++ b/plugin/skills/wiki-save/SKILL.md @@ -0,0 +1,17 @@ +--- +name: wiki-save +description: Save an answer or synthesis from this conversation as a page in the user's LLM Wiki, linked to the wiki pages it draws on. +argument-hint: "[page title]" +disable-model-invocation: true +--- + +# Save to the wiki + +1. **Pick the content.** Use the previous answer in this conversation, unless the user supplied the text to save. Don't add new claims. +2. **Pick the title.** Use the argument if one was given; otherwise a short descriptive title. The slug is the title in lowercase words joined by hyphens. +3. **Avoid duplicates.** Search with `wiki_query`. If a page on the same topic exists, ask whether to extend it with `wiki_update_page` (`bodyAppend`) instead of creating a new page. +4. **Save.** Call `wiki_write_page` with `pagePath` `queries/.md`, `type` `query`, the title, a few tags, and the content as `body`. Write links to wiki pages relative to the new page, for example `[Attention](../concepts/attention.md)`. +5. **Link.** Use `wiki_add_crosslinks` from the new page to the pages it cites. +6. **Confirm** the saved path to the user. + +If a tool reports that no wiki is open, call `wiki_open` with the absolute path of the current workspace folder, then retry. diff --git a/tests/plugin/plugin.test.ts b/tests/plugin/plugin.test.ts new file mode 100644 index 0000000..2b71847 --- /dev/null +++ b/tests/plugin/plugin.test.ts @@ -0,0 +1,186 @@ +/** + * Validates the agent plugin (plugin/), its marketplace entry, and that the + * VS Code extension contributes the same skills, agent and instructions. + */ +import { describe, it, expect } from 'vitest'; +import { readFileSync, readdirSync, existsSync } from 'node:fs'; +import { join } from 'node:path'; +import matter from 'gray-matter'; +import { READ_TOOLS } from '../../packages/core/src/mcp/read-tools.js'; +import { WRITE_TOOLS } from '../../packages/core/src/mcp/write-tools.js'; +import { WORKSPACE_TOOLS } from '../../packages/core/src/mcp/workspace-tools.js'; +import { PROMPTS } from '../../packages/core/src/mcp/prompts.js'; +import { BASE_INSTRUCTIONS, buildInstructions } from '../../packages/core/src/mcp/instructions.js'; +import { Client } from '@modelcontextprotocol/sdk/client/index.js'; +import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js'; +import { createMcpServer } from '../../packages/core/src/mcp/server.js'; + +const REPO = join(__dirname, '../..'); +const PLUGIN = join(REPO, 'plugin'); +const readJson = (path: string) => JSON.parse(readFileSync(path, 'utf-8')); + +const pluginJson = readJson(join(PLUGIN, 'plugin.json')); +const mcpJson = readJson(join(PLUGIN, 'mcp.json')); +const marketplace = readJson(join(REPO, '.github', 'plugin', 'marketplace.json')); +const extensionPkg = readJson(join(REPO, 'packages', 'vscode', 'package.json')); + +const skillNames = readdirSync(join(PLUGIN, 'skills'), { withFileTypes: true }) + .filter((d) => d.isDirectory()) + .map((d) => d.name) + .sort(); +const skills = skillNames.map((name) => ({ + name, + ...matter(readFileSync(join(PLUGIN, 'skills', name, 'SKILL.md'), 'utf-8')), +})); +const agentFiles = readdirSync(join(PLUGIN, 'com.github.copilot', 'agents')); +const ruleFiles = readdirSync(join(PLUGIN, 'com.github.copilot', 'rules')); + +const TOOL_NAMES = new Set([...READ_TOOLS, ...WRITE_TOOLS, ...WORKSPACE_TOOLS].map((t) => t.name)); + +describe('plugin manifest', () => { + it('declares the Agent Plugins 1.0 schema and a valid name', () => { + expect(pluginJson.$schema).toBe('https://agent-plugins.org/schemas/1.0.0/plugin.schema.json'); + expect(pluginJson.name).toMatch(/^[a-z0-9](?:[a-z0-9.-]{0,62}[a-z0-9])?$/); + expect(pluginJson.name).not.toMatch(/--|\.\./); + }); + + it('keeps the plugin, marketplace and extension versions in sync', () => { + expect(pluginJson.version).toBe(extensionPkg.version); + const entry = marketplace.plugins.find((p: { name: string }) => p.name === pluginJson.name); + expect(entry?.version).toBe(pluginJson.version); + expect(marketplace.metadata.version).toBe(pluginJson.version); + }); + + it('has a marketplace entry that points at the plugin folder', () => { + const entry = marketplace.plugins.find((p: { name: string }) => p.name === pluginJson.name); + expect(entry).toBeDefined(); + expect(existsSync(join(REPO, entry.source, 'plugin.json'))).toBe(true); + expect(marketplace.owner.name).toBeTruthy(); + }); + + it('starts the bundled MCP server from the plugin root', () => { + expect(mcpJson.$schema).toBe('https://agent-plugins.org/schemas/1.0.0/mcp.schema.json'); + expect(Object.keys(mcpJson)).toEqual(['$schema', 'mcpServers']); + const server = mcpJson.mcpServers.llmwiki; + expect(server).toEqual({ + type: 'stdio', + command: 'node', + args: ['${PLUGIN_ROOT}/server/llmwiki-mcp.cjs'], + }); + expect(existsSync(join(PLUGIN, 'server', 'llmwiki-mcp.cjs'))).toBe(true); + }); +}); + +describe('skills', () => { + it('ships the expected skills', () => { + expect(skillNames).toEqual(['wiki-ask', 'wiki-fix', 'wiki-ingest', 'wiki-research', 'wiki-save']); + }); + + it.each(skillNames)('%s has valid SKILL.md frontmatter', (name) => { + const skill = skills.find((s) => s.name === name)!; + expect(skill.data.name).toBe(name); + expect(skill.data.name).toMatch(/^[a-z0-9-]{1,64}$/); + expect(typeof skill.data.description).toBe('string'); + expect(skill.data.description.length).toBeGreaterThan(20); + expect(skill.data.description.length).toBeLessThanOrEqual(1024); + expect(skill.content.trim().length).toBeGreaterThan(0); + }); + + it('only runs wiki-fix and wiki-save when the user asks', () => { + for (const skill of skills) { + const manual = skill.name === 'wiki-fix' || skill.name === 'wiki-save'; + expect(skill.data['disable-model-invocation'] === true, skill.name).toBe(manual); + } + }); + + it('applies wiki_fix only after the user approves the pages it would delete', () => { + const fix = skills.find((s) => s.name === 'wiki-fix')!; + expect(fix.content).toContain('removed_pages'); + expect(fix.content).toMatch(/Wait for an explicit yes/); + expect(fix.content).toMatch(/don't call `wiki_fix` without `dryRun`/); + expect(BASE_INSTRUCTIONS).toMatch(/removed_pages, apply only after the user approves/); + }); +}); + +describe('agent and rules', () => { + it('ships the Wiki Librarian agent', () => { + expect(agentFiles).toEqual(['wiki-librarian.agent.md']); + const agent = matter(readFileSync(join(PLUGIN, 'com.github.copilot', 'agents', agentFiles[0]), 'utf-8')); + expect(agent.data.name).toBe('Wiki Librarian'); + expect(agent.data.description).toBeTruthy(); + // Harness-specific fields would make the agent fail in other harnesses. + expect(Object.keys(agent.data).sort()).toEqual(['description', 'name']); + }); + + it('ships the wiki instructions scoped to .wiki/**', () => { + expect(ruleFiles).toEqual(['llmwiki.instructions.md']); + const rule = matter(readFileSync(join(PLUGIN, 'com.github.copilot', 'rules', ruleFiles[0]), 'utf-8')); + expect(rule.data.applyTo).toBe('.wiki/**'); + }); +}); + +describe('VS Code extension contributions', () => { + const contributes = extensionPkg.contributes; + + it('no longer contributes a chat participant', () => { + expect(contributes.chatParticipants).toBeUndefined(); + }); + + it('contributes every plugin skill, the agent and the instructions from out/chat', () => { + const skillPaths = contributes.chatSkills.map((s: { path: string }) => s.path).sort(); + expect(skillPaths).toEqual(skillNames.map((n) => `./out/chat/skills/${n}/SKILL.md`)); + expect(contributes.chatAgents.map((a: { path: string }) => a.path)).toEqual( + agentFiles.map((f) => `./out/chat/agents/${f}`), + ); + expect(contributes.chatInstructions.map((i: { path: string }) => i.path)).toEqual( + ruleFiles.map((f) => `./out/chat/instructions/${f}`), + ); + }); + + it('only offers them in wiki workspaces', () => { + for (const entry of [...contributes.chatSkills, ...contributes.chatAgents, ...contributes.chatInstructions]) { + expect(entry.when, entry.path).toBe('llmwiki.isWikiWorkspace'); + } + }); + + it('requires a VS Code version that supports extension-contributed skills', () => { + expect(extensionPkg.engines.vscode).toBe('^1.109.0'); + expect(extensionPkg.devDependencies['@types/vscode']).toBe('~1.109.0'); + }); +}); + +describe('tool references', () => { + const referenced = (text: string) => new Set(text.match(/\bwiki_[a-z_]+\b/g) ?? []); + + async function promptTexts(): Promise { + const server = createMcpServer({ cwd: REPO }); + const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); + const client = new Client({ name: 'test', version: '1.0.0' }); + await server.connect(serverTransport); + await client.connect(clientTransport); + const texts: string[] = []; + for (const prompt of PROMPTS) { + const args = 'arguments' in prompt ? Object.fromEntries(prompt.arguments.map((a) => [a.name, 'x'])) : undefined; + const result = await client.getPrompt({ name: prompt.name, arguments: args }); + for (const m of result.messages) if ('text' in m.content) texts.push(m.content.text); + } + return texts.join('\n'); + } + + it('only mention tools the MCP server provides', async () => { + const sources: Record = { + 'server instructions': buildInstructions(undefined, { discovery: true }), + 'MCP prompts': await promptTexts(), + 'agent': readFileSync(join(PLUGIN, 'com.github.copilot', 'agents', agentFiles[0]), 'utf-8'), + 'rules': readFileSync(join(PLUGIN, 'com.github.copilot', 'rules', ruleFiles[0]), 'utf-8'), + }; + for (const skill of skills) sources[`skill ${skill.name}`] = skill.content; + + for (const [where, text] of Object.entries(sources)) { + for (const name of referenced(text)) { + expect(TOOL_NAMES.has(name), `${where} mentions unknown tool ${name}`).toBe(true); + } + } + expect(referenced(BASE_INSTRUCTIONS).size).toBeGreaterThan(5); + }); +}); diff --git a/tests/plugin/server-stdio.test.ts b/tests/plugin/server-stdio.test.ts new file mode 100644 index 0000000..c062a8a --- /dev/null +++ b/tests/plugin/server-stdio.test.ts @@ -0,0 +1,109 @@ +/** + * End-to-end check of the committed plugin server bundle over real stdio, + * the way an agent plugin client starts it (`node server/llmwiki-mcp.cjs` + * from the plugin folder, no wiki-root argument). + */ +import { describe, it, expect, beforeAll, afterAll } from 'vitest'; +import { mkdtemp, rm, writeFile } from 'node:fs/promises'; +import { existsSync } from 'node:fs'; +import { join } from 'node:path'; +import { tmpdir } from 'node:os'; +import { Client } from '@modelcontextprotocol/sdk/client/index.js'; +import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js'; +import { initWiki } from '../../packages/core/src/init.js'; +import { CORE_VERSION } from '../../packages/core/src/constants.js'; + +const PLUGIN = join(__dirname, '../../plugin'); +const BUNDLE = join(PLUGIN, 'server', 'llmwiki-mcp.cjs'); + +let base: string; +let project: string; + +async function startServer(options: { cwd: string; args?: string[]; env?: Record }) { + const transport = new StdioClientTransport({ + command: process.execPath, + args: [BUNDLE, ...(options.args ?? [])], + cwd: options.cwd, + env: { ...(process.env as Record), ...options.env }, + stderr: 'pipe', + }); + const client = new Client({ name: 'stdio-e2e', version: '1.0.0' }); + await client.connect(transport); + return client; +} + +async function call(client: Client, name: string, args: Record = {}) { + const result = await client.callTool({ name, arguments: args }); + const text = (result.content as Array<{ text: string }>)[0].text; + return { text, isError: result.isError === true, structured: result.structuredContent as any }; +} + +beforeAll(async () => { + base = await mkdtemp(join(tmpdir(), 'plugin-stdio-')); + project = join(base, 'project'); + await initWiki(project); + await writeFile(join(project, '.wiki', 'raw', 'turing.md'), '# Alan Turing\n\nAlan Turing proposed the Turing machine.'); +}); + +afterAll(async () => { + await rm(base, { recursive: true, force: true }); +}); + +describe('plugin server bundle (stdio)', () => { + it('exists', () => { + expect(existsSync(BUNDLE)).toBe(true); + }); + + it('starts in the plugin folder, opens a wiki and works end to end', async () => { + const client = await startServer({ cwd: PLUGIN }); + try { + expect(client.getServerVersion()?.version).toBe(CORE_VERSION); + expect(client.getInstructions()).toContain('wiki_open'); + + const { tools } = await client.listTools(); + expect(tools.map((t) => t.name)).toEqual(expect.arrayContaining(['wiki_open', 'wiki_init', 'wiki_fix'])); + expect(tools.find((t) => t.name === 'wiki_read_page')?.annotations?.readOnlyHint).toBe(true); + + const before = await call(client, 'wiki_status'); + expect(before.isError).toBe(true); + expect(before.text).toContain('No LLM Wiki is open'); + + const opened = await call(client, 'wiki_open', { path: project }); + expect(opened.isError).toBe(false); + + const ingested = await call(client, 'wiki_ingest_with_context', { sourcePath: 'raw/turing.md' }); + expect(ingested.isError).toBe(false); + expect(existsSync(join(project, '.wiki', 'wiki', 'sources', 'turing-summary.md'))).toBe(true); + + const status = await call(client, 'wiki_status'); + expect(status.isError).toBe(false); + expect(status.structured.source_count).toBe(1); + + const fix = await call(client, 'wiki_fix', { dryRun: true }); + expect(fix.structured.dry_run).toBe(true); + } finally { + await client.close(); + } + }); + + it('binds to an explicit wiki root and includes its AGENTS.md', async () => { + const client = await startServer({ cwd: base, args: [join(project, '.wiki')] }); + try { + const names = (await client.listTools()).tools.map((t) => t.name); + expect(names).not.toContain('wiki_open'); + expect(client.getInstructions()).toContain("This wiki's schema (.wiki/AGENTS.md)"); + expect((await call(client, 'wiki_status')).isError).toBe(false); + } finally { + await client.close(); + } + }); + + it('honors LLMWIKI_ROOT', async () => { + const client = await startServer({ cwd: PLUGIN, env: { LLMWIKI_ROOT: join(project, '.wiki') } }); + try { + expect((await call(client, 'wiki_status')).isError).toBe(false); + } finally { + await client.close(); + } + }); +}); diff --git a/tests/shared/delete.test.ts b/tests/shared/delete.test.ts index 296b3a3..eb3e052 100644 --- a/tests/shared/delete.test.ts +++ b/tests/shared/delete.test.ts @@ -1,7 +1,8 @@ import { describe, it, expect, beforeEach, afterEach } from 'vitest'; import { deletePage, writePage } from '../../packages/core/src/wiki.js'; import { addEntry, readIndex } from '../../packages/core/src/index-ops.js'; -import { mkdtemp, rm, writeFile, mkdir, stat } from 'node:fs/promises'; +import { mkdtemp, rm, writeFile, mkdir, stat, symlink } from 'node:fs/promises'; +import { existsSync } from 'node:fs'; import { join } from 'node:path'; import { tmpdir } from 'node:os'; @@ -110,4 +111,55 @@ describe('deletePage', () => { deletePage(wikiDir, '../../etc/passwd'), ).rejects.toThrow('Path traversal detected'); }); + + it.each(['index.md', 'Index.md', 'LOG.md', 'concepts/../Log.md'])( + 'refuses to delete %s (case-insensitive file systems)', + async (pagePath) => { + await expect(deletePage(wikiDir, pagePath)).rejects.toThrow('special wiki file'); + expect(existsSync(join(wikiDir, 'index.md'))).toBe(true); + }, + ); + + describe('through symlinked folders', () => { + let outside: string; + + // Junctions need no special rights on Windows; elsewhere these are symlinks. + const link = (target: string, name: string) => symlink(target, join(wikiDir, name), 'junction'); + + beforeEach(async () => { + outside = await mkdtemp(join(tmpdir(), 'wiki-delete-outside-')); + await writeFile(join(outside, 'source.md'), '# Raw source', 'utf-8'); + await link(outside, 'linked'); + }); + + afterEach(async () => { + await rm(outside, { recursive: true, force: true }); + }); + + it('refuses a page whose folder links outside the wiki', async () => { + await expect(deletePage(wikiDir, 'linked/source.md')).rejects.toThrow('Path traversal detected'); + expect(existsSync(join(outside, 'source.md'))).toBe(true); + }); + + it.each(['self/index.md', 'self/Index.md', 'self/log.md'])( + 'refuses %s, which resolves to a special wiki file', + async (pagePath) => { + await link(wikiDir, 'self'); + await expect(deletePage(wikiDir, pagePath)).rejects.toThrow('special wiki file'); + expect(existsSync(join(wikiDir, 'index.md'))).toBe(true); + }, + ); + + it('still deletes a page reached through a folder link inside the wiki', async () => { + await writePage(join(wikiDir, 'concepts', 'target.md'), { + frontmatter: { title: 'Target' }, + body: 'Body.', + }); + await link(join(wikiDir, 'concepts'), 'alias'); + + await deletePage(wikiDir, 'alias/target.md'); + + expect(existsSync(join(wikiDir, 'concepts', 'target.md'))).toBe(false); + }); + }); }); diff --git a/tests/shared/fix.test.ts b/tests/shared/fix.test.ts new file mode 100644 index 0000000..81a4362 --- /dev/null +++ b/tests/shared/fix.test.ts @@ -0,0 +1,288 @@ +import { describe, it, expect, beforeEach, afterEach } from 'vitest'; +import { mkdtemp, rm, mkdir, readFile, writeFile } from 'node:fs/promises'; +import { existsSync } from 'node:fs'; +import { join } from 'node:path'; +import { tmpdir } from 'node:os'; +import { fixWiki, findOrphanedDerivedPages, normalizeSourceRef, removeSourcePages } from '../../packages/core/src/fix.js'; +import { lintFix, type LintFinding } from '../../packages/core/src/lint.js'; +import { writePage } from '../../packages/core/src/wiki.js'; +import { writeIndex, readIndex } from '../../packages/core/src/index-ops.js'; +import { readLog } from '../../packages/core/src/log.js'; + +let root: string; +let wikiDir: string; + +async function page(relPath: string, frontmatter: Record, body = 'Body.') { + await writePage(join(wikiDir, relPath), { frontmatter, body }); +} + +beforeEach(async () => { + root = await mkdtemp(join(tmpdir(), 'fixwiki-')); + wikiDir = join(root, 'wiki'); + await mkdir(join(wikiDir, 'entities'), { recursive: true }); + await mkdir(join(wikiDir, 'concepts'), { recursive: true }); + await mkdir(join(wikiDir, 'sources'), { recursive: true }); +}); + +afterEach(async () => { + await rm(root, { recursive: true, force: true }); +}); + +describe('findOrphanedDerivedPages', () => { + it('returns entity/concept pages whose sources are all missing', async () => { + await page('sources/kept-summary.md', { type: 'summary', title: 'Kept' }); + await page('entities/gone.md', { type: 'entity', title: 'Gone', sources: ['sources/removed-summary.md'] }); + await page('concepts/kept.md', { type: 'concept', title: 'Kept', sources: ['sources/kept-summary.md'] }); + await page('concepts/mixed.md', { + type: 'concept', + title: 'Mixed', + sources: ['sources/removed-summary.md', 'sources/kept-summary.md'], + }); + await page('concepts/no-sources.md', { type: 'concept', title: 'No sources' }); + + expect(await findOrphanedDerivedPages(wikiDir)).toEqual(['entities/gone.md']); + }); + + it('never treats malformed sources as missing', async () => { + await page('entities/odd.md', { type: 'entity', title: 'Odd', sources: [42, ''] }); + expect(await findOrphanedDerivedPages(wikiDir)).toEqual([]); + }); + + it('ignores sources that are not summary pages (raw paths, URLs)', async () => { + await page('entities/raw-ref.md', { type: 'entity', title: 'Raw ref', sources: ['raw/paper.pdf'] }); + await page('entities/url-ref.md', { type: 'entity', title: 'URL ref', sources: ['https://arxiv.org/abs/1706.03762'] }); + await page('concepts/mixed-ref.md', { + type: 'concept', + title: 'Mixed ref', + sources: ['sources/gone-summary.md', 'raw/notes.md'], + }); + expect(await findOrphanedDerivedPages(wikiDir)).toEqual([]); + }); + + it('returns an empty list when the wiki directory does not exist', async () => { + expect(await findOrphanedDerivedPages(join(root, 'missing'))).toEqual([]); + }); +}); + +describe('normalizeSourceRef', () => { + it.each([ + ['sources/a-summary.md', 'sources/a-summary.md'], + ['./sources/a-summary.md', 'sources/a-summary.md'], + ['sources\\a-summary.md', 'sources/a-summary.md'], + [' sources/nested/b-summary.md ', 'sources/nested/b-summary.md'], + ])('accepts %j', (input, expected) => { + expect(normalizeSourceRef(input)).toBe(expected); + }); + + it.each([ + 'raw/paper.pdf', + 'https://example.com/sources/a.md', + 'concepts/ai.md', + 'sources/../concepts/ai.md', + 'sources//a.md', + 'sources/a-summary.txt', + '', + 42, + undefined, + ])('rejects %j', (input) => { + expect(normalizeSourceRef(input)).toBeUndefined(); + }); +}); + +describe('removeSourcePages', () => { + beforeEach(async () => { + await page('sources/a-summary.md', { type: 'summary', title: 'A' }); + await page('sources/b-summary.md', { type: 'summary', title: 'B' }); + await page('entities/only-a.md', { type: 'entity', title: 'Only A', sources: ['sources/a-summary.md'] }); + await page('concepts/a-and-b.md', { + type: 'concept', + title: 'A and B', + sources: ['sources/a-summary.md', 'sources/b-summary.md'], + }); + await page('concepts/only-b.md', { type: 'concept', title: 'Only B', sources: ['sources/b-summary.md'] }); + await page('concepts/hand-written.md', { type: 'concept', title: 'Hand-written' }); + await writeIndex(join(wikiDir, 'index.md'), [ + { path: 'entities/only-a.md', title: 'Only A', summary: '', category: 'Entities', tags: [] }, + { path: 'concepts/a-and-b.md', title: 'A and B', summary: '', category: 'Concepts', tags: [] }, + ]); + }); + + it('deletes the summary and the pages with no other remaining source', async () => { + const removed = await removeSourcePages(wikiDir, 'sources/a-summary.md'); + + expect(removed.sort()).toEqual(['entities/only-a.md', 'sources/a-summary.md']); + expect(existsSync(join(wikiDir, 'entities', 'only-a.md'))).toBe(false); + expect(existsSync(join(wikiDir, 'concepts', 'a-and-b.md'))).toBe(true); + expect(existsSync(join(wikiDir, 'concepts', 'only-b.md'))).toBe(true); + expect(existsSync(join(wikiDir, 'concepts', 'hand-written.md'))).toBe(true); + const paths = (await readIndex(join(wikiDir, 'index.md'))).map((e) => e.path); + expect(paths).toEqual(['concepts/a-and-b.md']); + }); + + it('deletes a multi-source page once its last source is removed', async () => { + await removeSourcePages(wikiDir, 'sources/a-summary.md'); + const removed = await removeSourcePages(wikiDir, 'sources/b-summary.md'); + + expect(removed.sort()).toEqual(['concepts/a-and-b.md', 'concepts/only-b.md', 'sources/b-summary.md']); + expect(existsSync(join(wikiDir, 'concepts', 'hand-written.md'))).toBe(true); + }); + + it('still cleans up derived pages when the summary was never written', async () => { + await rm(join(wikiDir, 'sources', 'a-summary.md')); + expect(await removeSourcePages(wikiDir, 'sources/a-summary.md')).toEqual(['entities/only-a.md']); + }); + + it('returns nothing for an unknown source', async () => { + expect(await removeSourcePages(wikiDir, 'sources/unknown-summary.md')).toEqual([]); + }); + + it('matches sources written with a leading ./', async () => { + await page('concepts/dotted.md', { type: 'concept', title: 'Dotted', sources: ['./sources/a-summary.md'] }); + expect(await removeSourcePages(wikiDir, 'sources/a-summary.md')).toContain('concepts/dotted.md'); + }); +}); + +describe('fixWiki', () => { + async function seedBrokenWiki() { + await page('entities/gone.md', { type: 'entity', title: 'Gone', sources: ['sources/removed-summary.md'] }); + await page('concepts/unindexed.md', { type: 'concept', title: 'Unindexed', tags: [], created: '2026-01-01' }); + await page('concepts/linked.md', { type: 'concept', title: 'Linked', tags: [], created: '2026-01-01' }, 'See [missing](missing.md).'); + await writeIndex(join(wikiDir, 'index.md'), [ + { path: 'entities/gone.md', title: 'Gone', summary: '', category: 'Entities', tags: [] }, + { path: 'concepts/linked.md', title: 'Linked', summary: '', category: 'Concepts', tags: [] }, + { path: 'concepts/deleted.md', title: 'Deleted', summary: '', category: 'Concepts', tags: [] }, + ]); + } + + it('removes orphaned derived pages, applies lint fixes and reports the rest', async () => { + await seedBrokenWiki(); + + const result = await fixWiki(root); + + expect(result.command).toBe('fix'); + expect(result.dry_run).toBe(false); + expect(result.removed_pages).toEqual(['entities/gone.md']); + expect(existsSync(join(wikiDir, 'entities', 'gone.md'))).toBe(false); + + const categories = result.fixed.map((f) => f.category); + expect(categories).toContain('stale-entries'); + expect(categories).toContain('index-completeness'); + expect(result.fixedCount).toBe(result.fixed.length); + + expect(result.remaining.some((f) => f.category === 'broken-links')).toBe(true); + expect(result.remainingCount).toBe(result.remaining.length); + + const paths = (await readIndex(join(wikiDir, 'index.md'))).map((e) => e.path).sort(); + expect(paths).toEqual(['concepts/linked.md', 'concepts/unindexed.md']); + }); + + it('logs a lint-fix entry when it changes something', async () => { + await seedBrokenWiki(); + await fixWiki(root); + + const log = await readLog(join(wikiDir, 'log.md')); + expect(log.at(-1)?.verb).toBe('lint-fix'); + expect(log.at(-1)?.details).toContain('Removed 1 orphaned page(s)'); + }); + + it('does not log when there is nothing to fix', async () => { + await page('concepts/a.md', { type: 'concept', title: 'A', tags: [], created: '2026-01-01' }); + await writeIndex(join(wikiDir, 'index.md'), [ + { path: 'concepts/a.md', title: 'A', summary: '', category: 'Concepts', tags: [] }, + ]); + + const result = await fixWiki(root); + + expect(result.fixedCount).toBe(0); + expect(result.removed_pages).toEqual([]); + expect(existsSync(join(wikiDir, 'log.md'))).toBe(false); + }); + + it('changes nothing in dry-run mode but reports the same plan', async () => { + await seedBrokenWiki(); + const indexBefore = await readFile(join(wikiDir, 'index.md'), 'utf-8'); + + const result = await fixWiki(root, { dryRun: true }); + + expect(result.dry_run).toBe(true); + expect(result.removed_pages).toEqual(['entities/gone.md']); + expect(existsSync(join(wikiDir, 'entities', 'gone.md'))).toBe(true); + expect(await readFile(join(wikiDir, 'index.md'), 'utf-8')).toBe(indexBefore); + expect(existsSync(join(wikiDir, 'log.md'))).toBe(false); + + // Findings about the page that would be removed are left out. + const files = [...result.fixed, ...result.remaining].map((f) => f.file); + expect(files).not.toContain('entities/gone.md'); + expect(result.fixed.map((f) => f.category)).toContain('stale-entries'); + }); + + it('previews exactly what applying reports, linting the wiki as it will be after the deletions', async () => { + await page( + 'entities/gone.md', + { type: 'entity', title: 'Gone', tags: [], created: '2026-01-01', sources: ['sources/removed-summary.md'] }, + 'See [nowhere](../concepts/nowhere.md) and [only from gone](../concepts/only-from-gone.md).', + ); + await page('concepts/keeper.md', { type: 'concept', title: 'Keeper', tags: [], created: '2026-01-01' }, 'Built on [Gone](../entities/gone.md).'); + await page('concepts/only-from-gone.md', { type: 'concept', title: 'Only from gone', tags: [], created: '2026-01-01' }); + await writeIndex(join(wikiDir, 'index.md'), [ + { path: 'entities/gone.md', title: 'Gone', summary: '', category: 'Entities', tags: [] }, + { path: 'concepts/keeper.md', title: 'Keeper', summary: '', category: 'Concepts', tags: [] }, + ]); + const sorted = (findings: LintFinding[]) => + findings.map((f) => `${f.category} | ${f.file} | ${f.message}`).sort(); + + const preview = await fixWiki(root, { dryRun: true }); + const applied = await fixWiki(root); + + expect(preview.removed_pages).toEqual(['entities/gone.md']); + expect(applied.removed_pages).toEqual(['entities/gone.md']); + expect(sorted(preview.fixed)).toEqual(sorted(applied.fixed)); + expect(sorted(preview.remaining)).toEqual(sorted(applied.remaining)); + + // The link to the removed page breaks… + expect(preview.remaining).toContainEqual( + expect.objectContaining({ category: 'broken-links', file: 'concepts/keeper.md' }), + ); + // …the removed page's own links no longer count… + expect(JSON.stringify(preview)).not.toContain('concepts/nowhere.md'); + // …and the page only it linked to becomes an orphan that gets indexed. + expect(preview.fixed).toContainEqual( + expect.objectContaining({ category: 'orphan-pages', file: 'concepts/only-from-gone.md' }), + ); + }); +}); + +describe('lintFix', () => { + it('dryRun reports fixes without writing', async () => { + await page('concepts/unindexed.md', { type: 'concept', title: 'Unindexed' }); + await writeIndex(join(wikiDir, 'index.md'), [ + { path: 'concepts/stale.md', title: 'Stale', summary: '', category: 'Concepts', tags: [] }, + ]); + const indexBefore = await readFile(join(wikiDir, 'index.md'), 'utf-8'); + const pageBefore = await readFile(join(wikiDir, 'concepts', 'unindexed.md'), 'utf-8'); + + const result = await lintFix(root, { fixOrphans: true, dryRun: true }); + + expect(result.fixedCount).toBeGreaterThan(0); + expect(await readFile(join(wikiDir, 'index.md'), 'utf-8')).toBe(indexBefore); + expect(await readFile(join(wikiDir, 'concepts', 'unindexed.md'), 'utf-8')).toBe(pageBefore); + }); + + it('adds an unindexed orphan page to the index only once', async () => { + await page('entities/orphan.md', { type: 'entity', title: 'Orphan', tags: [], created: '2026-01-01' }); + await writeIndex(join(wikiDir, 'index.md'), []); + + const result = await lintFix(root, { fixOrphans: true }); + + const fixedCategories = result.fixed.map((f) => f.category).sort(); + expect(fixedCategories).toEqual(['index-completeness', 'orphan-pages']); + const entries = await readIndex(join(wikiDir, 'index.md')); + expect(entries.filter((e) => e.path === 'entities/orphan.md')).toHaveLength(1); + }); + + it('still reports remaining findings when the index file is missing', async () => { + await writeFile(join(wikiDir, 'concepts', 'x.md'), '# no frontmatter\n\n[gone](gone.md)\n'); + const result = await lintFix(root); + expect(result.remaining.some((f) => f.category === 'broken-links')).toBe(true); + }); +}); diff --git a/tests/shared/ingest-context.test.ts b/tests/shared/ingest-context.test.ts index 6082218..b493d0c 100644 --- a/tests/shared/ingest-context.test.ts +++ b/tests/shared/ingest-context.test.ts @@ -329,9 +329,10 @@ describe('ingestWithContext', () => { const result = await ingestWithContext(sourceFile, tempDir); expect(result.ingest.status).toBe('skipped'); - expect(result.suggested_actions).toContain( - 'Use force=true to re-ingest this source', - ); + expect(result.ingest.summary_page).toBe('sources/dup-summary.md'); + expect(result.suggested_actions).toEqual([ + 'Source already ingested: read the existing summary page (summary_page) and build on it; re-ingest with force only if the user asks', + ]); }); it('finds related pages when wiki has matching content', async () => { diff --git a/tests/shared/lock.test.ts b/tests/shared/lock.test.ts new file mode 100644 index 0000000..c56363c --- /dev/null +++ b/tests/shared/lock.test.ts @@ -0,0 +1,97 @@ +/** + * withWikiLock: the wiki write lock shared by the VS Code extension and MCP + * server processes (a lock file in the wiki directory). + */ +import { describe, it, expect, beforeEach, afterEach } from 'vitest'; +import { mkdtemp, rm, writeFile, utimes } from 'node:fs/promises'; +import { existsSync } from 'node:fs'; +import { join } from 'node:path'; +import { tmpdir } from 'node:os'; +import { withWikiLock, WIKI_LOCK_FILE } from '../../packages/core/src/lock.js'; + +let wikiDir: string; +let lockPath: string; + +const sleep = (ms: number) => new Promise((done) => setTimeout(done, ms)); + +beforeEach(async () => { + wikiDir = await mkdtemp(join(tmpdir(), 'wiki-lock-')); + lockPath = join(wikiDir, WIKI_LOCK_FILE); +}); + +afterEach(async () => { + await rm(wikiDir, { recursive: true, force: true }); +}); + +describe('withWikiLock', () => { + it('holds a lock file in the wiki directory while the operation runs', async () => { + expect(await withWikiLock(wikiDir, async () => existsSync(lockPath))).toBe(true); + expect(existsSync(lockPath)).toBe(false); + }); + + it('runs one operation at a time', async () => { + const events: string[] = []; + const operation = (name: string) => + withWikiLock(wikiDir, async () => { + events.push(`start ${name}`); + await sleep(20); + events.push(`end ${name}`); + }); + + await Promise.all([operation('a'), operation('b'), operation('c')]); + + expect(events).toHaveLength(6); + for (let i = 0; i < events.length; i += 2) { + expect(events[i + 1]).toBe(events[i].replace('start', 'end')); + } + }); + + it('waits while another process holds the lock', async () => { + await writeFile(lockPath, ''); // as another process would + let ran = false; + const pending = withWikiLock(wikiDir, async () => { + ran = true; + }); + + await sleep(150); + expect(ran).toBe(false); + + await rm(lockPath); + await pending; + expect(ran).toBe(true); + }); + + it('takes over a lock left behind by a process that died', async () => { + await writeFile(lockPath, ''); + const old = new Date(Date.now() - 60_000); + await utimes(lockPath, old, old); + + const started = Date.now(); + await withWikiLock(wikiDir, async () => {}); + + expect(Date.now() - started).toBeLessThan(2_000); + expect(existsSync(lockPath)).toBe(false); + }); + + it('is re-entrant within one call chain', async () => { + const result = await withWikiLock(wikiDir, () => withWikiLock(wikiDir, async () => 'nested')); + expect(result).toBe('nested'); + }); + + it('releases the lock when the operation fails', async () => { + await expect( + withWikiLock(wikiDir, async () => { + throw new Error('boom'); + }), + ).rejects.toThrow('boom'); + + expect(existsSync(lockPath)).toBe(false); + expect(await withWikiLock(wikiDir, async () => 'again')).toBe('again'); + }); + + it('runs without a lock when the wiki directory does not exist', async () => { + const missing = join(wikiDir, 'missing'); + expect(await withWikiLock(missing, async () => 'ran')).toBe('ran'); + expect(existsSync(missing)).toBe(false); + }); +}); diff --git a/tests/shared/mcp/completions.test.ts b/tests/shared/mcp/completions.test.ts new file mode 100644 index 0000000..7feb691 --- /dev/null +++ b/tests/shared/mcp/completions.test.ts @@ -0,0 +1,117 @@ +import { describe, it, expect, beforeEach, afterEach } from 'vitest'; +import { mkdtemp, rm, writeFile, mkdir } from 'node:fs/promises'; +import { join } from 'node:path'; +import { tmpdir } from 'node:os'; +import { Client } from '@modelcontextprotocol/sdk/client/index.js'; +import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js'; +import { createMcpServer } from '../../../packages/core/src/mcp/server.js'; +import { initWiki } from '../../../packages/core/src/init.js'; +import { writePage } from '../../../packages/core/src/wiki.js'; +import { writeIndex } from '../../../packages/core/src/index-ops.js'; + +let projectDir: string; +let client: Client; + +async function connect(options: Parameters[0]) { + const server = createMcpServer(options); + const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); + const c = new Client({ name: 'test-client', version: '1.0.0' }); + await server.connect(serverTransport); + await c.connect(clientTransport); + return c; +} + +beforeEach(async () => { + projectDir = await mkdtemp(join(tmpdir(), 'mcp-complete-')); + await initWiki(projectDir); + const wikiRoot = join(projectDir, '.wiki'); + const wikiDir = join(wikiRoot, 'wiki'); + for (const [path, title] of [ + ['concepts/attention.md', 'Attention'], + ['concepts/transformers.md', 'Transformers'], + ['entities/turing.md', 'Alan Turing'], + ]) { + await writePage(join(wikiDir, path), { frontmatter: { type: 'concept', title }, body: title }); + } + await writeIndex(join(wikiDir, 'index.md'), [ + { path: 'concepts/attention.md', title: 'Attention', summary: '', category: 'Concepts', tags: [] }, + { path: 'concepts/transformers.md', title: 'Transformers', summary: '', category: 'Concepts', tags: [] }, + { path: 'entities/turing.md', title: 'Alan Turing', summary: '', category: 'Entities', tags: [] }, + ]); + await mkdir(join(wikiRoot, 'raw', 'papers'), { recursive: true }); + await writeFile(join(wikiRoot, 'raw', 'papers', 'attention.pdf'), 'pdf'); + await writeFile(join(wikiRoot, 'raw', 'notes.md'), 'notes'); + + client = await connect(wikiRoot); +}); + +afterEach(async () => { + await rm(projectDir, { recursive: true, force: true }); +}); + +describe('Completions', () => { + it('suggests page paths for resource://wiki/pages/{path}', async () => { + const result = await client.complete({ + ref: { type: 'ref/resource', uri: 'resource://wiki/pages/{path}' }, + argument: { name: 'path', value: 'con' }, + }); + expect(result.completion.values).toEqual(['concepts/attention.md', 'concepts/transformers.md']); + expect(result.completion.hasMore).toBe(false); + }); + + it('never suggests index.md or log.md', async () => { + const result = await client.complete({ + ref: { type: 'ref/resource', uri: 'resource://wiki/pages/{path}' }, + argument: { name: 'path', value: '' }, + }); + expect(result.completion.values).not.toContain('index.md'); + expect(result.completion.values).not.toContain('log.md'); + expect(result.completion.total).toBe(3); + }); + + it('suggests raw paths for resource://wiki/sources/{path}', async () => { + const result = await client.complete({ + ref: { type: 'ref/resource', uri: 'resource://wiki/sources/{path}' }, + argument: { name: 'path', value: 'ATT' }, + }); + expect(result.completion.values).toEqual(['papers/attention.pdf']); + }); + + it('suggests raw/ paths for the ingest-and-integrate prompt', async () => { + const result = await client.complete({ + ref: { type: 'ref/prompt', name: 'ingest-and-integrate' }, + argument: { name: 'source_path', value: '' }, + }); + expect(result.completion.values).toEqual(['raw/notes.md', 'raw/papers/attention.pdf']); + }); + + it('suggests index titles for the research-topic prompt', async () => { + const result = await client.complete({ + ref: { type: 'ref/prompt', name: 'research-topic' }, + argument: { name: 'topic', value: 'tur' }, + }); + expect(result.completion.values).toEqual(['Alan Turing']); + }); + + it('returns nothing for unknown references', async () => { + const result = await client.complete({ + ref: { type: 'ref/prompt', name: 'lint-and-fix' }, + argument: { name: 'anything', value: '' }, + }); + expect(result.completion.values).toEqual([]); + }); + + it('returns nothing before a wiki is located', async () => { + const empty = await mkdtemp(join(tmpdir(), 'mcp-complete-empty-')); + try { + const discoveryClient = await connect({ cwd: empty }); + const result = await discoveryClient.complete({ + ref: { type: 'ref/resource', uri: 'resource://wiki/pages/{path}' }, + argument: { name: 'path', value: '' }, + }); + expect(result.completion.values).toEqual([]); + } finally { + await rm(empty, { recursive: true, force: true }); + } + }); +}); diff --git a/tests/shared/mcp/discovery.test.ts b/tests/shared/mcp/discovery.test.ts new file mode 100644 index 0000000..ca3a069 --- /dev/null +++ b/tests/shared/mcp/discovery.test.ts @@ -0,0 +1,245 @@ +/** + * Wiki discovery for servers started without a wiki root (agent plugins, + * `llmwiki-mcp` with no argument): cwd, client roots, wiki_open, wiki_init. + */ +import { describe, it, expect, beforeEach, afterEach } from 'vitest'; +import { mkdtemp, rm } from 'node:fs/promises'; +import { existsSync } from 'node:fs'; +import { join } from 'node:path'; +import { tmpdir } from 'node:os'; +import { pathToFileURL } from 'node:url'; +import { Client } from '@modelcontextprotocol/sdk/client/index.js'; +import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js'; +import { ListRootsRequestSchema } from '@modelcontextprotocol/sdk/types.js'; +import { createMcpServer } from '../../../packages/core/src/mcp/server.js'; +import { findWikiRoot } from '../../../packages/core/src/mcp/wiki-root.js'; +import { initWiki } from '../../../packages/core/src/init.js'; +import { writePage } from '../../../packages/core/src/wiki.js'; +import { addEntry, readIndex } from '../../../packages/core/src/index-ops.js'; + +let base: string; +let projectA: string; +let projectB: string; +let emptyDir: string; + +async function makeWiki(project: string, title: string) { + await initWiki(project); + const wikiDir = join(project, '.wiki', 'wiki'); + await writePage(join(wikiDir, 'concepts', 'topic.md'), { + frontmatter: { type: 'concept', title, tags: [], created: '2026-01-01' }, + body: `${title} body.`, + }); + await addEntry(join(wikiDir, 'index.md'), { + path: 'concepts/topic.md', + title, + summary: '', + category: 'Concepts', + tags: [], + }); +} + +async function connect( + cwd: string, + roots?: { current: string[] }, +): Promise { + const server = createMcpServer({ cwd }); + const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); + const client = new Client( + { name: 'test-client', version: '1.0.0' }, + roots ? { capabilities: { roots: { listChanged: true } } } : undefined, + ); + if (roots) { + client.setRequestHandler(ListRootsRequestSchema, async () => ({ + roots: roots.current.map((dir) => ({ uri: pathToFileURL(dir).href })), + })); + } + await server.connect(serverTransport); + await client.connect(clientTransport); + return client; +} + +async function call(client: Client, name: string, args: Record = {}) { + const result = await client.callTool({ name, arguments: args }); + const text = (result.content as Array<{ text: string }>)[0].text; + let parsed: any; + try { + parsed = JSON.parse(text); + } catch { + parsed = undefined; + } + return { text, parsed, isError: result.isError === true }; +} + +beforeEach(async () => { + base = await mkdtemp(join(tmpdir(), 'mcp-discovery-')); + projectA = join(base, 'project-a'); + projectB = join(base, 'project-b'); + emptyDir = join(base, 'plugin-root'); + await makeWiki(projectA, 'Alpha'); + await makeWiki(projectB, 'Beta'); + await initWiki(emptyDir); // creates the folder… + await rm(join(emptyDir, '.wiki'), { recursive: true, force: true }); // …without a wiki +}); + +afterEach(async () => { + await rm(base, { recursive: true, force: true }); +}); + +describe('findWikiRoot', () => { + it('accepts a project folder or its .wiki folder', () => { + expect(findWikiRoot(projectA)).toBe(join(projectA, '.wiki')); + expect(findWikiRoot(join(projectA, '.wiki'))).toBe(join(projectA, '.wiki')); + }); + + it('rejects folders without an initialized wiki', () => { + expect(findWikiRoot(emptyDir)).toBeUndefined(); + expect(findWikiRoot(join(base, 'does-not-exist'))).toBeUndefined(); + }); + + it('accepts a wiki whose index.md is missing, like wiki_init does', async () => { + await rm(join(projectA, '.wiki', 'wiki', 'index.md')); + expect(findWikiRoot(projectA)).toBe(join(projectA, '.wiki')); + }); +}); + +describe('Discovery mode', () => { + it('lists wiki_open and wiki_init in addition to the wiki tools', async () => { + const client = await connect(emptyDir); + const names = (await client.listTools()).tools.map((t) => t.name); + expect(names).toContain('wiki_open'); + expect(names).toContain('wiki_init'); + expect(names).toHaveLength(18); + }); + + it('uses /.wiki when present', async () => { + const client = await connect(projectA); + const { parsed, isError } = await call(client, 'wiki_query', { query: 'alpha' }); + expect(isError).toBe(false); + expect(parsed.results[0].title).toBe('Alpha'); + }); + + it('explains how to open a wiki when none is found', async () => { + const client = await connect(emptyDir); + const { text, isError } = await call(client, 'wiki_status'); + expect(isError).toBe(true); + expect(text).toContain('No LLM Wiki is open'); + expect(text).toContain('wiki_open'); + }); + + it('fails resource reads with the same guidance', async () => { + const client = await connect(emptyDir); + await expect(client.readResource({ uri: 'resource://wiki/index' })).rejects.toThrow(/No LLM Wiki is open/); + }); + + it('wiki_open selects a wiki for the session', async () => { + const client = await connect(emptyDir); + const opened = await call(client, 'wiki_open', { path: projectB }); + expect(opened.isError).toBe(false); + expect(opened.parsed).toMatchObject({ status: 'opened', wiki_root: join(projectB, '.wiki'), wiki_page_count: 1 }); + + const { parsed } = await call(client, 'wiki_query', { query: 'beta' }); + expect(parsed.results[0].title).toBe('Beta'); + }); + + it('wiki_open rejects relative paths and folders without a wiki', async () => { + const client = await connect(emptyDir); + const relative = await call(client, 'wiki_open', { path: 'project-a' }); + expect(relative.isError).toBe(true); + expect(relative.text).toContain('absolute path'); + + const missing = await call(client, 'wiki_open', { path: emptyDir }); + expect(missing.isError).toBe(true); + expect(missing.text).toContain('Use wiki_init'); + }); + + it('wiki_init creates and opens a wiki at an explicit path', async () => { + const client = await connect(emptyDir); + const target = join(base, 'new-project'); + + const { parsed, isError } = await call(client, 'wiki_init', { path: target }); + + expect(isError).toBe(false); + expect(parsed.status).toBe('created'); + expect(parsed.wiki_root).toBe(join(target, '.wiki')); + expect(existsSync(join(target, '.wiki', 'wiki', 'index.md'))).toBe(true); + expect(existsSync(join(target, '.wiki', 'AGENTS.md'))).toBe(true); + + const status = await call(client, 'wiki_status'); + expect(status.isError).toBe(false); + + const again = await call(client, 'wiki_init', { path: target }); + expect(again.parsed.status).toBe('already_initialized'); + }); + + it('wiki_init needs a path when the client reports no workspace folders', async () => { + const client = await connect(emptyDir); + const { text, isError } = await call(client, 'wiki_init'); + expect(isError).toBe(true); + expect(text).toContain("Pass 'path'"); + expect(existsSync(join(emptyDir, '.wiki'))).toBe(false); + }); + + it('opens a wiki whose index.md is missing so wiki_fix can rebuild the index', async () => { + const indexPath = join(projectB, '.wiki', 'wiki', 'index.md'); + await rm(indexPath); + const client = await connect(emptyDir); + + const opened = await call(client, 'wiki_open', { path: projectB }); + expect(opened.isError).toBe(false); + const init = await call(client, 'wiki_init', { path: projectB }); + expect(init.isError).toBe(false); + expect(init.parsed.status).toBe('already_initialized'); + + const fix = await call(client, 'wiki_fix'); + expect(fix.isError).toBe(false); + expect((await readIndex(indexPath)).map((e) => e.path)).toEqual(['concepts/topic.md']); + }); +}); + +describe('Discovery from client roots', () => { + it('finds the wiki in a workspace root', async () => { + const client = await connect(emptyDir, { current: [emptyDir, projectA] }); + const { parsed, isError } = await call(client, 'wiki_query', { query: 'alpha' }); + expect(isError).toBe(false); + expect(parsed.results[0].title).toBe('Alpha'); + }); + + it('re-discovers after the client reports changed roots', async () => { + const roots = { current: [projectA] }; + const client = await connect(emptyDir, roots); + expect((await call(client, 'wiki_query', { query: 'alpha' })).parsed.matches).toBe(1); + + roots.current = [projectB]; + await client.sendRootsListChanged(); + await new Promise((resolve) => setTimeout(resolve, 10)); + + const { parsed } = await call(client, 'wiki_query', { query: 'beta' }); + expect(parsed.results[0].title).toBe('Beta'); + }); + + it('wiki_init defaults to the first workspace root', async () => { + const workspace = join(base, 'workspace'); + const client = await connect(emptyDir, { current: [workspace] }); + await initWiki(workspace); + await rm(join(workspace, '.wiki'), { recursive: true, force: true }); + + const { parsed, isError } = await call(client, 'wiki_init'); + + expect(isError).toBe(false); + expect(parsed.wiki_root).toBe(join(workspace, '.wiki')); + }); +}); + +describe('Bound mode', () => { + it('rejects wiki_open and wiki_init as unknown tools', async () => { + const server = createMcpServer(join(projectA, '.wiki')); + const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); + const client = new Client({ name: 'test-client', version: '1.0.0' }); + await server.connect(serverTransport); + await client.connect(clientTransport); + + const { text, isError } = await call(client, 'wiki_open', { path: projectB }); + expect(isError).toBe(true); + expect(text).toContain('Unknown tool: wiki_open'); + }); +}); diff --git a/tests/shared/mcp/maintenance-tools.test.ts b/tests/shared/mcp/maintenance-tools.test.ts new file mode 100644 index 0000000..2f61e00 --- /dev/null +++ b/tests/shared/mcp/maintenance-tools.test.ts @@ -0,0 +1,321 @@ +/** + * MCP maintenance tools: wiki_fix, wiki_delete_page, and relative source + * paths for wiki_ingest_with_context. + */ +import { describe, it, expect, beforeEach, afterEach } from 'vitest'; +import { mkdtemp, rm, writeFile, readFile, symlink } from 'node:fs/promises'; +import { existsSync } from 'node:fs'; +import { join } from 'node:path'; +import { tmpdir } from 'node:os'; +import { Client } from '@modelcontextprotocol/sdk/client/index.js'; +import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js'; +import { createMcpServer } from '../../../packages/core/src/mcp/server.js'; +import { initWiki } from '../../../packages/core/src/init.js'; +import { readPage, upsertDerivedPage, writePage } from '../../../packages/core/src/wiki.js'; +import { readIndex, writeIndex } from '../../../packages/core/src/index-ops.js'; + +let projectDir: string; +let wikiRoot: string; +let wikiDir: string; +let client: Client; + +async function call(name: string, args: Record = {}) { + const result = await client.callTool({ name, arguments: args }); + const text = (result.content as Array<{ text: string }>)[0].text; + let parsed: any; + try { + parsed = JSON.parse(text); + } catch { + parsed = undefined; + } + return { text, parsed, isError: result.isError === true }; +} + +beforeEach(async () => { + projectDir = await mkdtemp(join(tmpdir(), 'mcp-maint-')); + await initWiki(projectDir); + wikiRoot = join(projectDir, '.wiki'); + wikiDir = join(wikiRoot, 'wiki'); + + await writePage(join(wikiDir, 'concepts', 'ai.md'), { + frontmatter: { type: 'concept', title: 'AI', tags: [], created: '2026-01-01' }, + body: 'See [Turing](../entities/turing.md).', + }); + await writePage(join(wikiDir, 'entities', 'turing.md'), { + frontmatter: { type: 'entity', title: 'Alan Turing', tags: [], created: '2026-01-01' }, + body: 'Mathematician.', + }); + await writePage(join(wikiDir, 'entities', 'gone.md'), { + frontmatter: { type: 'entity', title: 'Gone', tags: [], created: '2026-01-01', sources: ['sources/removed-summary.md'] }, + body: 'Derived from a removed source.', + }); + await writeIndex(join(wikiDir, 'index.md'), [ + { path: 'concepts/ai.md', title: 'AI', summary: '', category: 'Concepts', tags: [] }, + { path: 'entities/turing.md', title: 'Alan Turing', summary: '', category: 'Entities', tags: [] }, + { path: 'entities/gone.md', title: 'Gone', summary: '', category: 'Entities', tags: [] }, + { path: 'entities/stale.md', title: 'Stale', summary: '', category: 'Entities', tags: [] }, + ]); + + const server = createMcpServer(wikiRoot); + const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); + client = new Client({ name: 'test-client', version: '1.0.0' }); + await server.connect(serverTransport); + await client.connect(clientTransport); +}); + +afterEach(async () => { + await rm(projectDir, { recursive: true, force: true }); +}); + +describe('wiki_fix', () => { + it('lint stays accurate after a fixed page is rewritten to its earlier content', async () => { + // Regression: the long-lived server reused cached, mutated frontmatter. + const page = { pagePath: 'queries/saved.md', title: 'Saved', type: 'query', body: 'Saved answer.' }; + await call('wiki_write_page', page); + await call('wiki_fix'); // adds the missing "created" field + await call('wiki_write_page', page); // the original content again, without "created" + + const { parsed } = await call('wiki_lint'); + const messages = parsed.findings.map((f: { message: string }) => f.message); + expect(messages).toContain('Missing recommended "created" field in "queries/saved.md"'); + }); + + it('previews fixes with dryRun without touching files', async () => { + const indexBefore = await readFile(join(wikiDir, 'index.md'), 'utf-8'); + + const { parsed, isError } = await call('wiki_fix', { dryRun: true }); + + expect(isError).toBe(false); + expect(parsed.dry_run).toBe(true); + expect(parsed.removed_pages).toEqual(['entities/gone.md']); + expect(parsed.fixed.map((f: { category: string }) => f.category)).toContain('stale-entries'); + expect(existsSync(join(wikiDir, 'entities', 'gone.md'))).toBe(true); + expect(await readFile(join(wikiDir, 'index.md'), 'utf-8')).toBe(indexBefore); + }); + + it('applies the fixes', async () => { + const { parsed } = await call('wiki_fix'); + + expect(parsed.dry_run).toBe(false); + expect(parsed.removed_pages).toEqual(['entities/gone.md']); + expect(existsSync(join(wikiDir, 'entities', 'gone.md'))).toBe(false); + const paths = (await readIndex(join(wikiDir, 'index.md'))).map((e) => e.path).sort(); + expect(paths).toEqual(['concepts/ai.md', 'entities/turing.md']); + }); +}); + +describe('wiki_delete_page', () => { + it('deletes the page, removes it from the index, logs it and lists backlinks', async () => { + const { parsed, isError } = await call('wiki_delete_page', { pagePath: 'entities/turing.md' }); + + expect(isError).toBe(false); + expect(parsed.status).toBe('deleted'); + expect(parsed.path).toBe('entities/turing.md'); + expect(parsed.linkedFrom).toEqual([ + { page: 'concepts/ai.md', title: 'AI', linkText: 'Turing' }, + ]); + expect(existsSync(join(wikiDir, 'entities', 'turing.md'))).toBe(false); + const paths = (await readIndex(join(wikiDir, 'index.md'))).map((e) => e.path); + expect(paths).not.toContain('entities/turing.md'); + const log = await readFile(join(wikiDir, 'log.md'), 'utf-8'); + expect(log).toContain('deleted | entities/turing.md'); + expect(log).toContain('Still linked from: concepts/ai.md'); + }); + + it('normalizes equivalent paths', async () => { + const { parsed } = await call('wiki_delete_page', { pagePath: './entities/../entities/turing.md' }); + expect(parsed.path).toBe('entities/turing.md'); + }); + + it.each(['index.md', 'log.md', 'concepts/../index.md', 'Index.md', 'LOG.md'])('refuses to delete %s', async (pagePath) => { + const { text, isError } = await call('wiki_delete_page', { pagePath }); + expect(isError).toBe(true); + expect(text).toContain('special wiki file'); + expect(existsSync(join(wikiDir, 'index.md'))).toBe(true); + }); + + it('refuses a page reached through a folder that links outside the wiki', async () => { + await writeFile(join(wikiRoot, 'raw', 'source.md'), '# Source'); + await symlink(join(wikiRoot, 'raw'), join(wikiDir, 'linked'), 'junction'); + + const { text, isError } = await call('wiki_delete_page', { pagePath: 'linked/source.md' }); + + expect(isError).toBe(true); + expect(text).toContain('Path traversal'); + expect(existsSync(join(wikiRoot, 'raw', 'source.md'))).toBe(true); + }); + + it('refuses paths outside the wiki directory', async () => { + const { text, isError } = await call('wiki_delete_page', { pagePath: '../AGENTS.md' }); + expect(isError).toBe(true); + expect(text).toContain('Path traversal'); + expect(existsSync(join(wikiRoot, 'AGENTS.md'))).toBe(true); + }); + + it('refuses non-markdown files', async () => { + await writeFile(join(wikiDir, 'notes.txt'), 'x'); + const { text, isError } = await call('wiki_delete_page', { pagePath: 'notes.txt' }); + expect(isError).toBe(true); + expect(text).toContain('markdown page'); + }); + + it('reports a missing page', async () => { + const { text, isError } = await call('wiki_delete_page', { pagePath: 'concepts/nope.md' }); + expect(isError).toBe(true); + expect(text).toContain('Page not found'); + }); +}); + +describe('wiki_create_entity / wiki_create_concept sources', () => { + it('records sources so wiki_fix can clean the page up later', async () => { + await writePage(join(wikiDir, 'sources', 'paper-summary.md'), { + frontmatter: { type: 'summary', title: 'Paper' }, + body: 'Summary.', + }); + + const { parsed, isError } = await call('wiki_create_concept', { + name: 'Self-Attention', + content: 'Attention over a sequence.', + sources: ['./sources/paper-summary.md'], + }); + + expect(isError).toBe(false); + expect(parsed.sources).toEqual(['sources/paper-summary.md']); + const page = await readFile(join(wikiDir, 'concepts', 'self-attention.md'), 'utf-8'); + expect(page).toContain('sources:'); + expect(page).toContain('sources/paper-summary.md'); + + await rm(join(wikiDir, 'sources', 'paper-summary.md')); + const fix = await call('wiki_fix'); + expect(fix.parsed.removed_pages).toContain('concepts/self-attention.md'); + }); + + it('rejects sources outside the wiki directory', async () => { + const { text, isError } = await call('wiki_create_entity', { + name: 'Mallory', + content: 'x', + sources: ['../../etc/passwd'], + }); + expect(isError).toBe(true); + expect(text).toContain('Path traversal'); + expect(existsSync(join(wikiDir, 'entities', 'mallory.md'))).toBe(false); + }); + + it.each([['sources/missing-summary.md'], ['raw/article.md'], ['concepts/ai.md']])( + 'rejects source %s that is not an existing summary page', + async (source) => { + const { text, isError } = await call('wiki_create_concept', { + name: 'Premature', + content: 'x', + sources: [source], + }); + expect(isError).toBe(true); + expect(text).toContain('Source page not found'); + expect(existsSync(join(wikiDir, 'concepts', 'premature.md'))).toBe(false); + }, + ); + + describe('wiki_update_page addSources', () => { + beforeEach(async () => { + for (const name of ['a', 'b']) { + await writePage(join(wikiDir, 'sources', `${name}-summary.md`), { + frontmatter: { type: 'summary', title: name.toUpperCase() }, + body: 'Summary.', + }); + } + await call('wiki_create_concept', { name: 'Shared', content: 'From A.', sources: ['sources/a-summary.md'] }); + }); + + it('appends sources so the page survives removing one of them', async () => { + const { parsed, isError } = await call('wiki_update_page', { + pagePath: 'concepts/shared.md', + bodyAppend: 'From B.', + addSources: ['sources/b-summary.md', 'sources/a-summary.md'], + }); + + expect(isError).toBe(false); + expect(parsed.sourcesUpdated).toBe(true); + expect(parsed.frontmatter.sources).toEqual(['sources/a-summary.md', 'sources/b-summary.md']); + + await rm(join(wikiDir, 'sources', 'a-summary.md')); + expect((await call('wiki_fix', { dryRun: true })).parsed.removed_pages).not.toContain('concepts/shared.md'); + + await rm(join(wikiDir, 'sources', 'b-summary.md')); + expect((await call('wiki_fix', { dryRun: true })).parsed.removed_pages).toContain('concepts/shared.md'); + }); + + it('never adds sources to a page that lists none', async () => { + const { parsed } = await call('wiki_update_page', { + pagePath: 'entities/turing.md', + bodyAppend: 'Extra.', + addSources: ['sources/b-summary.md'], + }); + + expect(parsed.sourcesUpdated).toBe(false); + expect(parsed.frontmatter.sources).toBeUndefined(); + }); + + it('rejects sources that do not exist', async () => { + const { text, isError } = await call('wiki_update_page', { + pagePath: 'concepts/shared.md', + addSources: ['sources/nope-summary.md'], + }); + expect(isError).toBe(true); + expect(text).toContain('Source page not found'); + }); + + it('keeps every change when updates and an ingest overlap', async () => { + const names = ['b', 'c', 'd', 'e']; + for (const name of ['c', 'd', 'e', 'f']) { + await writePage(join(wikiDir, 'sources', `${name}-summary.md`), { + frontmatter: { type: 'summary', title: name.toUpperCase() }, + body: 'Summary.', + }); + } + + const [updates] = await Promise.all([ + Promise.all( + names.map((name) => + call('wiki_update_page', { + pagePath: 'concepts/shared.md', + bodyAppend: `From ${name.toUpperCase()}.`, + addSources: [`sources/${name}-summary.md`], + }), + ), + ), + // The VS Code extension's ingest extends pages through the same lock. + upsertDerivedPage(wikiDir, 'concept', 'Shared', 'From F.', [], 'sources/f-summary.md'), + ]); + + expect(updates.map((u) => u.isError)).toEqual(names.map(() => false)); + const page = await readPage(join(wikiDir, 'concepts', 'shared.md')); + expect([...(page.frontmatter.sources ?? [])].sort()).toEqual( + ['a', 'b', 'c', 'd', 'e', 'f'].map((name) => `sources/${name}-summary.md`), + ); + for (const name of [...names, 'f']) expect(page.body).toContain(`From ${name.toUpperCase()}.`); + }); + }); +}); + +describe('wiki_ingest_with_context', () => { + it('resolves a relative sourcePath against the wiki root', async () => { + await writeFile(join(wikiRoot, 'raw', 'note.md'), '# Note\n\nTuring machines and artificial intelligence.'); + + const { parsed, isError } = await call('wiki_ingest_with_context', { sourcePath: 'raw/note.md' }); + + expect(isError).toBe(false); + expect(parsed.ingest.status).not.toBe('error'); + expect(existsSync(join(wikiDir, 'sources', 'note-summary.md'))).toBe(true); + + const again = await call('wiki_ingest_with_context', { sourcePath: 'raw/note.md' }); + expect(again.parsed.ingest.status).toBe('skipped'); + expect(again.parsed.ingest.summary_page).toBe('sources/note-summary.md'); + }); + + it('still rejects sources outside the wiki root', async () => { + await writeFile(join(projectDir, 'outside.md'), 'secret'); + const { text, isError } = await call('wiki_ingest_with_context', { sourcePath: '../outside.md' }); + expect(isError).toBe(true); + expect(text).toContain('Path traversal'); + }); +}); diff --git a/tests/shared/mcp/prompts.test.ts b/tests/shared/mcp/prompts.test.ts index 801a4b0..8700980 100644 --- a/tests/shared/mcp/prompts.test.ts +++ b/tests/shared/mcp/prompts.test.ts @@ -185,6 +185,17 @@ describe('MCP Prompts — GetPrompt lint-and-fix', () => { expect(allText).toContain('wiki_lint'); expect(allText).toMatch(/severity|error.*warning|warning.*error/i); }); + + it('asks the user before applying fixes that delete pages', async () => { + const result = await client.getPrompt({ name: 'lint-and-fix' }); + const allText = result.messages + .map((m) => ('text' in m.content ? m.content.text : '')) + .join('\n'); + + expect(allText).toContain('removed_pages'); + expect(allText).toMatch(/Wait for an explicit yes/); + expect(allText).toMatch(/do not call wiki_fix without dryRun/); + }); }); // --------------------------------------------------------------------------- diff --git a/tests/shared/mcp/server-integration.test.ts b/tests/shared/mcp/server-integration.test.ts index f5295ec..f02318e 100644 --- a/tests/shared/mcp/server-integration.test.ts +++ b/tests/shared/mcp/server-integration.test.ts @@ -161,7 +161,15 @@ describe('MCP Server — Read Tools (InMemoryTransport)', () => { expect(names).toContain('wiki_update_index'); expect(names).toContain('wiki_ingest_with_context'); - expect(result.tools.length).toBe(14); + // Maintenance tools + expect(names).toContain('wiki_fix'); + expect(names).toContain('wiki_delete_page'); + + // A server bound to a wiki root does not offer wiki_open/wiki_init. + expect(names).not.toContain('wiki_open'); + expect(names).not.toContain('wiki_init'); + + expect(result.tools.length).toBe(16); }); // ----------------------------------------------------------------------- diff --git a/tests/shared/mcp/server-metadata.test.ts b/tests/shared/mcp/server-metadata.test.ts new file mode 100644 index 0000000..cd4090d --- /dev/null +++ b/tests/shared/mcp/server-metadata.test.ts @@ -0,0 +1,172 @@ +/** + * MCP server metadata: tool titles/annotations, structured output, server + * info, capabilities and instructions. + */ +import { describe, it, expect, beforeEach, afterEach } from 'vitest'; +import { mkdtemp, rm, writeFile, readFile } from 'node:fs/promises'; +import { join } from 'node:path'; +import { tmpdir } from 'node:os'; +import { Client } from '@modelcontextprotocol/sdk/client/index.js'; +import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js'; +import { createMcpServer, type CreateMcpServerOptions } from '../../../packages/core/src/mcp/server.js'; +import { READ_TOOLS } from '../../../packages/core/src/mcp/read-tools.js'; +import { WRITE_TOOLS } from '../../../packages/core/src/mcp/write-tools.js'; +import { WORKSPACE_TOOLS } from '../../../packages/core/src/mcp/workspace-tools.js'; +import { BASE_INSTRUCTIONS, MAX_SCHEMA_CHARS } from '../../../packages/core/src/mcp/instructions.js'; +import { initWiki } from '../../../packages/core/src/init.js'; +import { writePage } from '../../../packages/core/src/wiki.js'; +import { CORE_VERSION } from '../../../packages/core/src/constants.js'; + +let projectDir: string; +let wikiRoot: string; + +async function connect(options: string | CreateMcpServerOptions): Promise { + const server = createMcpServer(options); + const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); + const client = new Client({ name: 'test-client', version: '1.0.0' }); + await server.connect(serverTransport); + await client.connect(clientTransport); + return client; +} + +beforeEach(async () => { + projectDir = await mkdtemp(join(tmpdir(), 'mcp-meta-')); + await initWiki(projectDir); + wikiRoot = join(projectDir, '.wiki'); + await writePage(join(wikiRoot, 'wiki', 'concepts', 'ai.md'), { + frontmatter: { type: 'concept', title: 'Artificial Intelligence', tags: ['ai'], created: '2026-01-01' }, + body: 'Artificial intelligence and [a missing page](missing.md).', + }); +}); + +afterEach(async () => { + await rm(projectDir, { recursive: true, force: true }); +}); + +describe('Tool metadata', () => { + it('gives every tool a title and annotations', () => { + for (const tool of [...READ_TOOLS, ...WRITE_TOOLS, ...WORKSPACE_TOOLS]) { + expect(tool.title, tool.name).toMatch(/\S/); + expect(tool.annotations, tool.name).toBeDefined(); + expect(tool.annotations.openWorldHint, tool.name).toBe(false); + } + }); + + it('marks read tools read-only and write tools not', () => { + for (const tool of READ_TOOLS) { + expect(tool.annotations.readOnlyHint, tool.name).toBe(true); + } + for (const tool of WRITE_TOOLS) { + expect(tool.annotations.readOnlyHint, tool.name).toBe(false); + } + }); + + it('flags tools that overwrite or delete content as destructive', () => { + const byName = new Map(WRITE_TOOLS.map((t) => [t.name, t.annotations])); + for (const name of ['wiki_write_page', 'wiki_update_page', 'wiki_delete_page', 'wiki_fix', 'wiki_create_entity']) { + expect(byName.get(name)?.destructiveHint, name).toBe(true); + } + expect(byName.get('wiki_add_crosslinks')?.destructiveHint).toBe(false); + expect(byName.get('wiki_add_crosslinks')?.idempotentHint).toBe(true); + }); + + it('serves titles and annotations through tools/list', async () => { + const client = await connect(wikiRoot); + const { tools } = await client.listTools(); + const query = tools.find((t) => t.name === 'wiki_query'); + expect(query?.title).toBe('Search wiki'); + expect(query?.annotations?.readOnlyHint).toBe(true); + const del = tools.find((t) => t.name === 'wiki_delete_page'); + expect(del?.annotations?.destructiveHint).toBe(true); + }); +}); + +describe('Structured tool output', () => { + it.each([ + ['wiki_status', {}], + ['wiki_query', { query: 'intelligence' }], + ['wiki_lint', {}], + ['wiki_fix', { dryRun: true }], + ])('%s returns structuredContent that matches its text and outputSchema', async (name, args) => { + const client = await connect(wikiRoot); + const { tools } = await client.listTools(); + expect(tools.find((t) => t.name === name)?.outputSchema).toBeDefined(); + + // The SDK client validates structuredContent against the cached outputSchema. + const result = await client.callTool({ name, arguments: args }); + expect(result.isError).toBeFalsy(); + const text = (result.content as Array<{ text: string }>)[0].text; + expect(result.structuredContent).toEqual(JSON.parse(text)); + }); + + it('omits structuredContent for tools without an outputSchema', async () => { + const client = await connect(wikiRoot); + const result = await client.callTool({ name: 'wiki_read_index', arguments: {} }); + expect(result.structuredContent).toBeUndefined(); + }); +}); + +describe('Server info and capabilities', () => { + it('reports name, title, version, website and icon', async () => { + const client = await connect(wikiRoot); + const info = client.getServerVersion(); + expect(info?.name).toBe('llmwiki'); + expect(info?.title).toBe('LLM Wiki'); + expect(info?.version).toBe(CORE_VERSION); + expect(info?.websiteUrl).toBe('https://github.com/microsoft/llmwiki'); + expect(info?.icons?.[0]?.src).toMatch(/^data:image\/svg\+xml;base64,/); + }); + + it('keeps CORE_VERSION in sync with packages/core/package.json', async () => { + const pkg = JSON.parse(await readFile(join(__dirname, '../../../packages/core/package.json'), 'utf-8')); + expect(CORE_VERSION).toBe(pkg.version); + }); + + it('advertises completions alongside tools, resources and prompts', async () => { + const client = await connect(wikiRoot); + const caps = client.getServerCapabilities(); + expect(caps?.tools).toBeDefined(); + expect(caps?.resources).toBeDefined(); + expect(caps?.prompts).toBeDefined(); + expect(caps?.completions).toBeDefined(); + }); +}); + +describe('Server instructions', () => { + it('include the usage guidance and the wiki AGENTS.md schema', async () => { + const client = await connect(wikiRoot); + const instructions = client.getInstructions() ?? ''; + expect(instructions.startsWith(BASE_INSTRUCTIONS)).toBe(true); + expect(instructions).toContain('wiki_query'); + expect(instructions).toContain("This wiki's schema (.wiki/AGENTS.md)"); + expect(instructions).toContain('### Page Types'); + // Bound servers have no wiki_open, so they do not mention it. + expect(instructions).not.toContain('wiki_open'); + }); + + it('truncate a very large AGENTS.md', async () => { + await writeFile(join(wikiRoot, 'AGENTS.md'), `# Schema\n\n${'x'.repeat(MAX_SCHEMA_CHARS * 2)}`); + const client = await connect(wikiRoot); + const instructions = client.getInstructions() ?? ''; + expect(instructions).toContain('[Truncated. Read .wiki/AGENTS.md for the full schema.]'); + expect(instructions.length).toBeLessThan(BASE_INSTRUCTIONS.length + MAX_SCHEMA_CHARS + 500); + }); + + it('work without an AGENTS.md', async () => { + await rm(join(wikiRoot, 'AGENTS.md')); + const client = await connect(wikiRoot); + expect(client.getInstructions()).toBe(BASE_INSTRUCTIONS); + }); + + it('explain how to open a wiki when the server discovers it', async () => { + const empty = await mkdtemp(join(tmpdir(), 'mcp-meta-empty-')); + try { + const client = await connect({ cwd: empty }); + const instructions = client.getInstructions() ?? ''; + expect(instructions).toContain('wiki_open'); + expect(instructions).not.toContain("This wiki's schema"); + } finally { + await rm(empty, { recursive: true, force: true }); + } + }); +}); diff --git a/tests/shared/wiki-create-pages.test.ts b/tests/shared/wiki-create-pages.test.ts index d9dde22..053b1bb 100644 --- a/tests/shared/wiki-create-pages.test.ts +++ b/tests/shared/wiki-create-pages.test.ts @@ -1,6 +1,6 @@ import { describe, it, expect, beforeEach, afterEach } from 'vitest'; -import { createEntityPage, createConceptPage, readPage } from '../../packages/core/src/wiki.js'; -import { readIndex } from '../../packages/core/src/index-ops.js'; +import { createEntityPage, createConceptPage, readPage, upsertDerivedPage, writePage } from '../../packages/core/src/wiki.js'; +import { readIndex, updateIndexEntry } from '../../packages/core/src/index-ops.js'; import { mkdtemp, rm, writeFile, mkdir } from 'node:fs/promises'; import { join } from 'node:path'; import { tmpdir } from 'node:os'; @@ -62,6 +62,18 @@ describe('createEntityPage', () => { const result = await createEntityPage(wikiDir, 'Some Complex Name!', 'Content.'); expect(result.path).toBe('entities/some-complex-name.md'); }); + + it('should update the existing index entry when the page is created again', async () => { + await createEntityPage(wikiDir, 'Ada Lovelace', 'First version.', ['history']); + await updateIndexEntry(join(wikiDir, 'index.md'), 'entities/ada-lovelace.md', { summary: 'First programmer' }); + + await createEntityPage(wikiDir, 'Ada Lovelace', 'Second version.', ['history', 'math']); + + const entries = await readIndex(join(wikiDir, 'index.md')); + expect(entries).toHaveLength(1); + expect(entries[0].tags).toEqual(['history', 'math']); + expect(entries[0].summary).toBe('First programmer'); + }); }); describe('createConceptPage', () => { @@ -115,3 +127,85 @@ describe('createConceptPage', () => { expect(page.frontmatter.tags).toEqual([]); }); }); + +describe('upsertDerivedPage', () => { + let wikiDir: string; + + beforeEach(async () => { + wikiDir = await mkdtemp(join(tmpdir(), 'wiki-upsert-test-')); + await writeFile(join(wikiDir, 'index.md'), '', 'utf-8'); + }); + + afterEach(async () => { + await rm(wikiDir, { recursive: true, force: true }); + }); + + it('creates a new page that records its source', async () => { + const result = await upsertDerivedPage(wikiDir, 'entity', 'Grace Hopper', 'Wrote A-0.', ['people'], 'sources/a-summary.md'); + + expect(result).toMatchObject({ path: 'entities/grace-hopper.md', created: true }); + const page = await readPage(join(wikiDir, result.path)); + expect(page.frontmatter.sources).toEqual(['sources/a-summary.md']); + expect(page.body).toBe('Wrote A-0.'); + }); + + it('extends an existing derived page instead of overwriting it', async () => { + await upsertDerivedPage(wikiDir, 'concept', 'COBOL', 'Business language (1959).', ['language'], 'sources/a-summary.md'); + await writePage(join(wikiDir, 'concepts', 'cobol.md'), { + frontmatter: { ...(await readPage(join(wikiDir, 'concepts', 'cobol.md'))).frontmatter }, + body: 'Business language (1959).\n\n## See also\n\n- [Hopper](../entities/grace-hopper.md)', + }); + + const result = await upsertDerivedPage(wikiDir, 'concept', 'COBOL', 'Designed by CODASYL.', ['history'], 'sources/b-summary.md'); + + expect(result.created).toBe(false); + const page = await readPage(join(wikiDir, 'concepts', 'cobol.md')); + expect(page.body).toBe( + 'Business language (1959).\n\nDesigned by CODASYL.\n\n## See also\n\n- [Hopper](../entities/grace-hopper.md)', + ); + expect(page.frontmatter.tags).toEqual(['language', 'history']); + expect(page.frontmatter.sources).toEqual(['sources/a-summary.md', 'sources/b-summary.md']); + const entries = await readIndex(join(wikiDir, 'index.md')); + expect(entries).toHaveLength(1); + expect(entries[0].tags).toEqual(['language', 'history']); + }); + + it('does not repeat content that is already on the page', async () => { + await upsertDerivedPage(wikiDir, 'entity', 'Ada', 'Wrote the first program.', [], 'sources/a-summary.md'); + await upsertDerivedPage(wikiDir, 'entity', 'Ada', 'Wrote the first program.', [], 'sources/a-summary.md'); + + const page = await readPage(join(wikiDir, 'entities', 'ada.md')); + expect(page.body).toBe('Wrote the first program.'); + expect(page.frontmatter.sources).toEqual(['sources/a-summary.md']); + }); + + it('never adds sources to a hand-written page', async () => { + await writePage(join(wikiDir, 'entities', 'mine.md'), { + frontmatter: { type: 'entity', title: 'Mine', tags: ['personal'] }, + body: 'My own notes.', + }); + + await upsertDerivedPage(wikiDir, 'entity', 'Mine', 'From a source.', [], 'sources/a-summary.md'); + + const page = await readPage(join(wikiDir, 'entities', 'mine.md')); + expect(page.frontmatter.sources).toBeUndefined(); + expect(page.frontmatter.title).toBe('Mine'); + expect(page.body).toBe('My own notes.\n\nFrom a source.'); + }); + + it('keeps every source when ingests extend the same page at the same time', async () => { + const sources = ['a', 'b', 'c', 'd', 'e'].map((name) => `sources/${name}-summary.md`); + + await Promise.all( + sources.map((source, i) => + upsertDerivedPage(wikiDir, 'entity', 'Grace Hopper', `Fact ${i}.`, [`tag-${i}`], source), + ), + ); + + const page = await readPage(join(wikiDir, 'entities', 'grace-hopper.md')); + expect([...(page.frontmatter.sources ?? [])].sort()).toEqual(sources); + expect([...(page.frontmatter.tags ?? [])].sort()).toEqual(['tag-0', 'tag-1', 'tag-2', 'tag-3', 'tag-4']); + for (let i = 0; i < sources.length; i++) expect(page.body).toContain(`Fact ${i}.`); + expect(await readIndex(join(wikiDir, 'index.md'))).toHaveLength(1); + }); +}); diff --git a/tests/shared/wiki.test.ts b/tests/shared/wiki.test.ts index 4268c42..99da0fc 100644 --- a/tests/shared/wiki.test.ts +++ b/tests/shared/wiki.test.ts @@ -43,6 +43,36 @@ describe('readPage', () => { }); }); +describe('readPage frontmatter isolation', () => { + let dir: string; + + beforeEach(async () => { + dir = await mkdtemp(join(tmpdir(), 'readpage-')); + }); + + afterEach(async () => { + await rm(dir, { recursive: true, force: true }); + }); + + it('does not leak mutations into later reads of identical content', async () => { + const file = join(dir, 'page.md'); + const original = { frontmatter: { type: 'query', title: 'Saved' }, body: 'Body.' }; + await writePage(file, original); + + // A caller (e.g. lintFix) mutates the frontmatter it read and writes it back. + const first = await readPage(file); + first.frontmatter.created = '2026-01-01'; + await writePage(file, first); + + // The page later returns to its original content. + await writePage(file, original); + + const again = await readPage(file); + expect(again.frontmatter.created).toBeUndefined(); + expect(again.frontmatter).toEqual({ type: 'query', title: 'Saved' }); + }); +}); + describe('writePage', () => { let tmpDir: string; diff --git a/tests/vscode/chatHistory.test.ts b/tests/vscode/chatHistory.test.ts deleted file mode 100644 index 7812bf4..0000000 --- a/tests/vscode/chatHistory.test.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { describe, it, expect } from 'vitest'; -import { historyToMessages } from '../../packages/vscode/src/chatHistory'; - -describe('historyToMessages', () => { - it('keeps interleaved user and assistant turns in their original order', () => { - const messages = historyToMessages([ - { role: 'user', text: 'A' }, - { role: 'assistant', text: 'B' }, - { role: 'user', text: 'C' }, - ]); - - expect(messages.map((message) => message.role)).toEqual(['user', 'assistant', 'user']); - expect(messages.map((message) => message.text)).toEqual(['A', 'B', 'C']); - }); - - it('drops assistant turns whose text is empty', () => { - const messages = historyToMessages([ - { role: 'user', text: 'A' }, - { role: 'assistant', text: '' }, - { role: 'user', text: 'C' }, - ]); - - expect(messages).toEqual([ - { role: 'user', text: 'A' }, - { role: 'user', text: 'C' }, - ]); - }); - - it('returns an empty array when history is empty', () => { - expect(historyToMessages([])).toEqual([]); - }); -}); diff --git a/tests/vscode/commands.test.ts b/tests/vscode/commands.test.ts index 9b029fd..89b9c57 100644 --- a/tests/vscode/commands.test.ts +++ b/tests/vscode/commands.test.ts @@ -52,9 +52,12 @@ vi.mock('@llmwiki/core', () => ({ initWiki: vi.fn(), lintWiki: vi.fn(), lintFix: vi.fn(), + fixWiki: vi.fn(), ingestSource: vi.fn(), queryWiki: vi.fn(), getWikiStatus: vi.fn(), + removeSourcePages: vi.fn(), + slugify: (name: string) => name.toLowerCase().replace(/\.[^.]+$/, '').replace(/[^a-z0-9]+/g, '-'), isNotFoundError: (err: unknown) => err instanceof Error && (err as NodeJS.ErrnoException).code === 'ENOENT', })); @@ -80,18 +83,24 @@ import { readIndex, directoryExists, lintWiki, + fixWiki, + removeSourcePages, + appendEntry, listPages, readLog, ingestSource, queryWiki, getWikiStatus, } from '@llmwiki/core'; -import { readdir } from 'node:fs/promises'; +import { readdir, unlink } from 'node:fs/promises'; +import { join } from 'node:path'; import * as vscode from 'vscode'; const mockDirectoryExists = directoryExists as Mock; const mockReadIndex = readIndex as Mock; const mockLintWiki = lintWiki as Mock; +const mockFixWiki = fixWiki as Mock; +const mockRemoveSourcePages = removeSourcePages as Mock; const mockListPages = listPages as Mock; const mockReadLog = readLog as Mock; const mockReaddir = readdir as Mock; @@ -110,6 +119,7 @@ const mockProviders = { entities: { refresh: vi.fn() }, concepts: { refresh: vi.fn() }, rawSources: { refresh: vi.fn() }, + lintFindings: { setFindings: vi.fn() }, }; const mockOutputChannel = { @@ -132,6 +142,8 @@ describe('Command handlers', () => { vi.clearAllMocks(); Object.keys(commandHandlers).forEach((k) => delete commandHandlers[k]); mockContext.subscriptions = []; + // VS Code resolves notification promises with the chosen button (or undefined). + mockShowWarningMessage.mockResolvedValue(undefined); registerCommands( mockContext, @@ -370,24 +382,161 @@ describe('Command handlers', () => { }); describe('llmwiki.refresh', () => { - it('should refresh all providers and run lint-fix', async () => { + const noIssues = { removed_pages: [], fixed: [], remaining: [], fixedCount: 0, remainingCount: 0 }; + + it('should refresh all providers and run the wiki fixes', async () => { mockDirectoryExists.mockResolvedValue(true); - const { lintFix } = await import('@llmwiki/core'); - (lintFix as Mock).mockResolvedValue({ - fixed: [], - remaining: [], - fixedCount: 0, - }); + mockFixWiki.mockResolvedValue(noIssues); await commandHandlers['llmwiki.refresh'](); + expect(mockFixWiki).toHaveBeenCalledWith(WORKSPACE); expect(mockProviders.entities.refresh).toHaveBeenCalled(); expect(mockProviders.concepts.refresh).toHaveBeenCalled(); expect(mockProviders.rawSources.refresh).toHaveBeenCalled(); + expect(mockProviders.lintFindings.setFindings).toHaveBeenCalledWith([]); expect(mockShowInformationMessage).toHaveBeenCalledWith( expect.stringContaining('no issues found'), ); }); + + it('should list remaining issues and offer to show them or fix them with Copilot', async () => { + mockDirectoryExists.mockResolvedValue(true); + const broken = { severity: 'error', category: 'broken-links', message: 'Broken link', file: 'a.md' }; + mockFixWiki.mockResolvedValue({ + removed_pages: ['entities/gone.md'], + fixed: [], + remaining: [broken], + fixedCount: 0, + remainingCount: 1, + }); + + await commandHandlers['llmwiki.refresh'](); + + expect(mockProviders.lintFindings.setFindings).toHaveBeenCalledWith([broken]); + expect(mockShowWarningMessage).toHaveBeenCalledWith( + 'Wiki refreshed — 1 orphaned page(s) removed, 1 issue(s) remaining.', + 'Show Findings', + 'Fix with Copilot', + ); + const messages = mockShowWarningMessage.mock.calls.map((c) => String(c[0])); + expect(messages.some((m) => m.includes('@wiki'))).toBe(false); + }); + }); + + describe('llmwiki.fix', () => { + const broken = { severity: 'error', category: 'broken-links', message: 'Broken link', file: 'a.md' }; + + it('should warn when the wiki is not initialized', async () => { + mockDirectoryExists.mockResolvedValue(false); + + await commandHandlers['llmwiki.fix'](); + + expect(mockFixWiki).not.toHaveBeenCalled(); + expect(mockShowWarningMessage).toHaveBeenCalledWith(expect.stringContaining('not initialized')); + }); + + it('should report a healthy wiki', async () => { + mockDirectoryExists.mockResolvedValue(true); + mockFixWiki.mockResolvedValue({ removed_pages: [], fixed: [], remaining: [], fixedCount: 0, remainingCount: 0 }); + + await commandHandlers['llmwiki.fix'](); + + expect(vscode.window.withProgress).toHaveBeenCalled(); + expect(mockShowInformationMessage).toHaveBeenCalledWith(expect.stringContaining('wiki is healthy')); + expect(vscode.commands.executeCommand).toHaveBeenCalledWith('setContext', 'llmwiki.hasLintFindings', false); + }); + + it('should apply fixes, show remaining findings and offer Copilot', async () => { + mockDirectoryExists.mockResolvedValue(true); + mockFixWiki.mockResolvedValue({ + removed_pages: [], + fixed: [{ severity: 'error', category: 'stale-entries', message: 'Stale' }], + remaining: [broken], + fixedCount: 1, + remainingCount: 1, + }); + mockShowWarningMessage.mockResolvedValue('Fix with Copilot'); + + await commandHandlers['llmwiki.fix'](); + await new Promise((resolve) => setImmediate(resolve)); + + expect(mockProviders.lintFindings.setFindings).toHaveBeenCalledWith([broken]); + expect(vscode.commands.executeCommand).toHaveBeenCalledWith('setContext', 'llmwiki.hasLintFindings', true); + expect(vscode.commands.executeCommand).toHaveBeenCalledWith('lintFindings.focus'); + expect(mockShowWarningMessage).toHaveBeenCalledWith( + 'LLM Wiki: 1 issue(s) fixed, 1 issue(s) need your judgment.', + 'Fix with Copilot', + ); + expect(vscode.commands.executeCommand).toHaveBeenCalledWith('llmwiki.fixWithCopilot'); + }); + }); + + describe('llmwiki.lint', () => { + it('should populate the Lint Findings view', async () => { + mockDirectoryExists.mockResolvedValue(true); + const finding = { severity: 'warning', category: 'orphan-pages', message: 'Orphan', file: 'b.md' }; + mockLintWiki.mockResolvedValue({ findings: [finding], errorCount: 0, warningCount: 1, infoCount: 0 }); + mockShowWarningMessage.mockResolvedValue('Fix Issues'); + + await commandHandlers['llmwiki.lint'](); + await new Promise((resolve) => setImmediate(resolve)); + + expect(mockProviders.lintFindings.setFindings).toHaveBeenCalledWith([finding]); + expect(mockShowWarningMessage).toHaveBeenCalledWith( + 'LLM Wiki: 0 error(s), 1 warning(s), 0 info.', + 'Fix Issues', + 'Fix with Copilot', + ); + expect(vscode.commands.executeCommand).toHaveBeenCalledWith('llmwiki.fix'); + }); + + it('should report a clean wiki', async () => { + mockDirectoryExists.mockResolvedValue(true); + mockLintWiki.mockResolvedValue({ findings: [], errorCount: 0, warningCount: 0, infoCount: 0 }); + + await commandHandlers['llmwiki.lint'](); + + expect(mockShowInformationMessage).toHaveBeenCalledWith(expect.stringContaining('no issues found')); + }); + }); + + describe('llmwiki.fixWithCopilot', () => { + it('should open chat with the wiki-fix skill', async () => { + await commandHandlers['llmwiki.fixWithCopilot'](); + + expect(vscode.commands.executeCommand).toHaveBeenCalledWith('workbench.action.chat.open', { + query: '/wiki-fix', + }); + }); + }); + + describe('llmwiki.removeSource', () => { + const filePath = join(WORKSPACE, 'raw', 'Paper.md'); + + it('should delete the raw file and the pages derived only from it', async () => { + mockShowWarningMessage.mockResolvedValue('Remove'); + mockRemoveSourcePages.mockResolvedValue(['sources/paper-summary.md', 'entities/author.md']); + + await commandHandlers['llmwiki.removeSource']({ filePath }); + + expect(unlink).toHaveBeenCalledWith(filePath); + expect(mockRemoveSourcePages).toHaveBeenCalledWith(join(WORKSPACE, 'wiki'), 'sources/paper-summary.md'); + expect(appendEntry).toHaveBeenCalledWith( + join(WORKSPACE, 'wiki', 'log.md'), + expect.objectContaining({ verb: 'removed', subject: 'Paper.md', details: 'Source file and 2 wiki page(s) removed.' }), + ); + expect(mockShowInformationMessage).toHaveBeenCalledWith('Removed "Paper.md" and 2 wiki page(s).'); + }); + + it('should do nothing when the user cancels', async () => { + mockShowWarningMessage.mockResolvedValue(undefined); + + await commandHandlers['llmwiki.removeSource']({ filePath }); + + expect(unlink).not.toHaveBeenCalled(); + expect(mockRemoveSourcePages).not.toHaveBeenCalled(); + }); }); describe('error wrapping', () => { diff --git a/tests/vscode/integration/build.mjs b/tests/vscode/integration/build.mjs new file mode 100644 index 0000000..9a79d9e --- /dev/null +++ b/tests/vscode/integration/build.mjs @@ -0,0 +1,30 @@ +/** + * Bundles the integration test runner and suite into ./out (CommonJS) so + * they can run without ts-node. Used by `npm run test:integration`. + */ +import * as esbuild from 'esbuild'; +import { readdirSync, mkdirSync, writeFileSync } from 'node:fs'; +import { fileURLToPath } from 'node:url'; +import { join } from 'node:path'; + +const here = fileURLToPath(new URL('.', import.meta.url)); +const suiteFiles = readdirSync(join(here, 'suite')) + .filter((f) => f.endsWith('.ts')) + .map((f) => join(here, 'suite', f)); + +await esbuild.build({ + entryPoints: [join(here, 'runTest.ts'), ...suiteFiles], + outdir: join(here, 'out'), + outbase: here, + bundle: true, + platform: 'node', + target: 'node20', + format: 'cjs', + external: ['vscode', 'mocha', '@vscode/test-electron'], + sourcemap: true, + logLevel: 'warning', +}); + +// The repo root is "type": "module"; the bundles are CommonJS. +mkdirSync(join(here, 'out'), { recursive: true }); +writeFileSync(join(here, 'out', 'package.json'), '{ "type": "commonjs" }\n'); diff --git a/tests/vscode/integration/runTest.ts b/tests/vscode/integration/runTest.ts index be01e99..ff34eff 100644 --- a/tests/vscode/integration/runTest.ts +++ b/tests/vscode/integration/runTest.ts @@ -1,21 +1,63 @@ /** * Integration test runner for the LLM Wiki VS Code extension. - * Uses @vscode/test-electron to launch a real VS Code instance. + * Uses @vscode/test-electron to launch a real VS Code instance on a fixture + * workspace that contains a wiki with known problems. * - * Run locally: npx ts-node tests/vscode/integration/runTest.ts + * Run locally: npm run build && npm run test:integration * Not run in CI (needs a display server). */ import { runTests } from '@vscode/test-electron'; import * as path from 'node:path'; +import { mkdtemp, mkdir, writeFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { initWiki, writePage, writeIndex } from '../../../packages/core/dist/index.js'; + +/** + * Create a workspace whose wiki needs fixing: + * - entities/gone.md was derived from a source summary that no longer exists + * - the index lists a page that was deleted (stale entry) + * - concepts/unindexed.md is missing from the index + * - concepts/linked.md links to a page that does not exist + */ +async function createFixtureWorkspace(): Promise { + const workspace = await mkdtemp(path.join(tmpdir(), 'llmwiki-integration-')); + await initWiki(workspace); + const wikiDir = path.join(workspace, '.wiki', 'wiki'); + + await writePage(path.join(wikiDir, 'entities', 'gone.md'), { + frontmatter: { type: 'entity', title: 'Gone', tags: [], created: '2026-01-01', sources: ['sources/removed-summary.md'] }, + body: 'Derived from a source that was removed.', + }); + await writePage(path.join(wikiDir, 'concepts', 'linked.md'), { + frontmatter: { type: 'concept', title: 'Linked', tags: [], created: '2026-01-01' }, + body: 'See [a missing page](missing.md).', + }); + await writePage(path.join(wikiDir, 'concepts', 'unindexed.md'), { + frontmatter: { type: 'concept', title: 'Unindexed', tags: [], created: '2026-01-01' }, + body: 'Not in the index yet.', + }); + await writeIndex(path.join(wikiDir, 'index.md'), [ + { path: 'entities/gone.md', title: 'Gone', summary: '', category: 'Entities', tags: [] }, + { path: 'concepts/linked.md', title: 'Linked', summary: '', category: 'Concepts', tags: [] }, + { path: 'concepts/deleted.md', title: 'Deleted', summary: '', category: 'Concepts', tags: [] }, + ]); + + await mkdir(path.join(workspace, '.wiki', 'raw'), { recursive: true }); + await writeFile(path.join(workspace, '.wiki', 'raw', 'note.md'), '# Note\n\nA raw source.'); + return workspace; +} async function main(): Promise { try { - const extensionDevelopmentPath = path.resolve(__dirname, '../../../packages/vscode'); + const extensionDevelopmentPath = path.resolve(__dirname, '../../../../packages/vscode'); const extensionTestsPath = path.resolve(__dirname, './suite/index'); + const workspace = await createFixtureWorkspace(); await runTests({ extensionDevelopmentPath, extensionTestsPath, + launchArgs: [workspace, '--disable-extensions', '--skip-welcome', '--skip-release-notes'], + extensionTestsEnv: { LLMWIKI_TEST_WORKSPACE: workspace }, }); } catch (err) { console.error('Failed to run tests:', err); diff --git a/tests/vscode/integration/suite/extension.test.ts b/tests/vscode/integration/suite/extension.test.ts index 5de3c33..6260d00 100644 --- a/tests/vscode/integration/suite/extension.test.ts +++ b/tests/vscode/integration/suite/extension.test.ts @@ -1,21 +1,136 @@ /** - * Smoke test: verifies the LLM Wiki extension activates in a real VS Code instance. - * Run via: npx ts-node tests/vscode/integration/runTest.ts + * Integration tests that run inside a real VS Code instance on the fixture + * workspace created by runTest.ts. */ import * as assert from 'node:assert'; +import { existsSync, readFileSync } from 'node:fs'; +import { join } from 'node:path'; import * as vscode from 'vscode'; +import { Client } from '@modelcontextprotocol/sdk/client/index.js'; +import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js'; -suite('Extension Activation', () => { - test('Extension should be present', () => { - const ext = vscode.extensions.getExtension('llmwiki.llmwiki-vscode'); - assert.ok(ext, 'Extension not found — check publisher.name in package.json'); +const EXTENSION_ID = 'eag-rss.llmwiki'; + +function workspaceRoot(): string { + const folder = vscode.workspace.workspaceFolders?.[0]?.uri.fsPath; + assert.ok(folder, 'Expected the fixture workspace to be open'); + return folder; +} + +async function waitFor(check: () => Promise, timeoutMs = 20_000): Promise { + const start = Date.now(); + while (!(await check())) { + if (Date.now() - start > timeoutMs) throw new Error('Timed out waiting for condition'); + await new Promise((resolve) => setTimeout(resolve, 200)); + } +} + +function frontmatterName(file: string): string | undefined { + const match = readFileSync(file, 'utf-8').match(/^---\r?\n([\s\S]*?)\r?\n---/); + return match?.[1].match(/^name:\s*(.+)$/m)?.[1].trim(); +} + +suite('LLM Wiki extension', () => { + let extension: vscode.Extension; + + suiteSetup(async () => { + const found = vscode.extensions.getExtension(EXTENSION_ID); + assert.ok(found, `Extension ${EXTENSION_ID} not found`); + extension = found; + await extension.activate(); + // Views and commands are registered once the wiki is detected. + await waitFor(async () => (await vscode.commands.getCommands(true)).includes('llmwiki.lint')); + }); + + test('activates in a workspace with a wiki', () => { + assert.ok(extension.isActive); + }); + + test('no longer contributes a chat participant', () => { + assert.strictEqual(extension.packageJSON.contributes.chatParticipants, undefined); + }); + + test('ships every contributed skill, agent and instructions file', () => { + const contributes = extension.packageJSON.contributes; + const entries: Array<{ path: string }> = [ + ...contributes.chatSkills, + ...contributes.chatAgents, + ...contributes.chatInstructions, + ]; + assert.strictEqual(contributes.chatSkills.length, 5); + for (const entry of entries) { + const file = join(extension.extensionPath, entry.path); + assert.ok(existsSync(file), `Missing ${entry.path}`); + } + for (const skill of contributes.chatSkills as Array<{ path: string }>) { + const file = join(extension.extensionPath, skill.path); + const folder = skill.path.split('/').slice(-2, -1)[0]; + assert.strictEqual(frontmatterName(file), folder, `${skill.path} name must match its folder`); + } }); - test('Extension should activate', async () => { - const ext = vscode.extensions.getExtension('llmwiki.llmwiki-vscode'); - if (ext && !ext.isActive) { - await ext.activate(); + test('registers the wiki maintenance commands', async () => { + const commands = await vscode.commands.getCommands(true); + for (const id of ['llmwiki.fix', 'llmwiki.lint', 'llmwiki.fixWithCopilot', 'llmwiki.refresh']) { + assert.ok(commands.includes(id), `Command ${id} is not registered`); + } + }); + + test('Run Lint completes without changing the wiki', async () => { + const indexPath = join(workspaceRoot(), '.wiki', 'wiki', 'index.md'); + const before = readFileSync(indexPath, 'utf-8'); + await vscode.commands.executeCommand('llmwiki.lint'); + assert.strictEqual(readFileSync(indexPath, 'utf-8'), before); + }); + + test('Fix Issues applies the deterministic fixes on disk', async () => { + const wikiDir = join(workspaceRoot(), '.wiki', 'wiki'); + + await vscode.commands.executeCommand('llmwiki.fix'); + + assert.ok(!existsSync(join(wikiDir, 'entities', 'gone.md')), 'orphaned derived page should be removed'); + const index = readFileSync(join(wikiDir, 'index.md'), 'utf-8'); + assert.ok(!index.includes('concepts/deleted.md'), 'stale index entry should be removed'); + assert.ok(index.includes('concepts/unindexed.md'), 'unindexed page should be added'); + assert.ok(index.includes('concepts/linked.md')); + const log = readFileSync(join(wikiDir, 'log.md'), 'utf-8'); + assert.ok(log.includes('lint-fix | wiki'), 'fix should be logged'); + // The broken link needs judgment and is left for /wiki-fix. + assert.ok(readFileSync(join(wikiDir, 'concepts', 'linked.md'), 'utf-8').includes('missing.md')); + }); + + test('the MCP server starts with the editor runtime the provider uses', async function () { + this.timeout(60_000); + const launcher = join(extension.extensionPath, 'out', 'mcp-server.cjs'); + const wikiRoot = join(workspaceRoot(), '.wiki'); + assert.ok(existsSync(launcher), 'out/mcp-server.cjs is missing — run npm run build'); + + // Mirror createLlmWikiServerDefinition: process.execPath + launcher + wiki + // root, with ELECTRON_RUN_AS_NODE supplied by the definition rather than + // inherited from the extension host. + const env: Record = {}; + for (const [key, value] of Object.entries(process.env)) { + if (value !== undefined && key !== 'ELECTRON_RUN_AS_NODE') env[key] = value; + } + env.ELECTRON_RUN_AS_NODE = '1'; + + const client = new Client({ name: 'integration-test', version: '1.0.0' }); + await client.connect( + new StdioClientTransport({ command: process.execPath, args: [launcher, wikiRoot], env, cwd: workspaceRoot() }), + ); + try { + const { tools } = await client.listTools(); + const names = tools.map((t) => t.name); + assert.ok(names.includes('wiki_fix') && names.includes('wiki_delete_page')); + assert.ok(!names.includes('wiki_open'), 'a bound server should not offer wiki_open'); + assert.strictEqual(tools.find((t) => t.name === 'wiki_query')?.annotations?.readOnlyHint, true); + assert.ok(client.getInstructions()?.includes("This wiki's schema (.wiki/AGENTS.md)")); + + const status = await client.callTool({ name: 'wiki_status', arguments: {} }); + assert.ok(!status.isError); + assert.strictEqual((status.structuredContent as { source_count: number }).source_count, 1); + } finally { + await client.close(); } - assert.ok(ext?.isActive, 'Extension did not activate'); }); }); diff --git a/tests/vscode/integration/suite/index.ts b/tests/vscode/integration/suite/index.ts index c8226f1..d3d09ca 100644 --- a/tests/vscode/integration/suite/index.ts +++ b/tests/vscode/integration/suite/index.ts @@ -10,7 +10,7 @@ export async function run(): Promise { const mocha = new Mocha({ ui: 'tdd', color: true, - timeout: 10_000, + timeout: 30_000, }); const testsRoot = path.resolve(__dirname, '.'); diff --git a/tests/vscode/mcpProvider.test.ts b/tests/vscode/mcpProvider.test.ts new file mode 100644 index 0000000..c528c71 --- /dev/null +++ b/tests/vscode/mcpProvider.test.ts @@ -0,0 +1,95 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest'; +import type { Mock } from 'vitest'; + +vi.mock('vscode', () => { + class McpStdioServerDefinition { + cwd?: { fsPath: string }; + constructor( + public label: string, + public command: string, + public args: string[], + public env: Record, + public version?: string, + ) {} + } + class EventEmitter { + event = vi.fn(); + fire = vi.fn(); + dispose = vi.fn(); + } + return { + McpStdioServerDefinition, + EventEmitter, + Uri: { file: (fsPath: string) => ({ fsPath, scheme: 'file' }) }, + lm: { registerMcpServerDefinitionProvider: vi.fn(() => ({ dispose: vi.fn() })) }, + }; +}); + +vi.mock('node:fs', () => ({ existsSync: vi.fn(() => true) })); +vi.mock('@llmwiki/core', () => ({ WIKI_DIR_NAME: '.wiki' })); + +import * as vscode from 'vscode'; +import { + createLlmWikiServerDefinition, + registerMcpServerProvider, +} from '../../packages/vscode/src/mcpProvider'; + +const outputChannel = { appendLine: vi.fn() } as unknown as vscode.OutputChannel; + +function makeContext() { + return { + subscriptions: [] as Array<{ dispose: () => void }>, + asAbsolutePath: (p: string) => `/ext/${p.replace(/\\/g, '/')}`, + extension: { packageJSON: { version: '9.9.9' } }, + } as unknown as vscode.ExtensionContext; +} + +describe('createLlmWikiServerDefinition', () => { + it('runs the bundled launcher with the editor binary in Node mode', () => { + const def = createLlmWikiServerDefinition('/ext/out/mcp-server.cjs', '/ws/.wiki', '/ws', '1.2.3'); + + expect(def.label).toBe('LLM Wiki'); + expect(def.command).toBe(process.execPath); + expect(def.args).toEqual(['/ext/out/mcp-server.cjs', '/ws/.wiki']); + expect(def.env).toEqual({ ELECTRON_RUN_AS_NODE: '1' }); + expect(def.version).toBe('1.2.3'); + expect(def.cwd?.fsPath).toBe('/ws'); + }); +}); + +describe('registerMcpServerProvider', () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + it('registers a provider that serves the llmwiki definition', async () => { + const context = makeContext(); + + const disposable = registerMcpServerProvider(context, '/ws', outputChannel); + + expect(disposable).toBeDefined(); + const register = vscode.lm.registerMcpServerDefinitionProvider as unknown as Mock; + expect(register).toHaveBeenCalledWith('llmwiki', expect.any(Object)); + const provider = register.mock.calls[0][1] as vscode.McpServerDefinitionProvider; + const defs = (await provider.provideMcpServerDefinitions( + {} as vscode.CancellationToken, + )) as vscode.McpStdioServerDefinition[]; + expect(defs).toHaveLength(1); + expect(defs[0].args[0]).toBe('/ext/out/mcp-server.cjs'); + expect(defs[0].args[1].replace(/\\/g, '/')).toBe('/ws/.wiki'); + expect(defs[0].env).toEqual({ ELECTRON_RUN_AS_NODE: '1' }); + expect(defs[0].version).toBe('9.9.9'); + }); + + it('skips registration when the MCP API is unavailable', () => { + const lm = vscode.lm as unknown as Record; + const original = lm.registerMcpServerDefinitionProvider; + lm.registerMcpServerDefinitionProvider = undefined; + try { + expect(registerMcpServerProvider(makeContext(), '/ws', outputChannel)).toBeUndefined(); + expect(outputChannel.appendLine).toHaveBeenCalledWith(expect.stringContaining('unavailable')); + } finally { + lm.registerMcpServerDefinitionProvider = original; + } + }); +}); diff --git a/vitest.config.ts b/vitest.config.ts index de47300..3a58fab 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -23,10 +23,8 @@ export default defineConfig({ // tests/vscode/integration/* which run in a real VS Code host, not by // the unit suite that uses a mocked `vscode` module). "packages/vscode/src/extension.ts", - "packages/vscode/src/chatParticipant.ts", "packages/vscode/src/extractText.ts", "packages/vscode/src/llmIngest.ts", - "packages/vscode/src/mcpProvider.ts", "packages/vscode/src/modelSelection.ts", ], thresholds: {